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: Enforce publish access for path resolution endpoints https://github.com/siyuan-note/siyuan/security/advisories/GHSA-5w7r-f4cg-rqq7
Daniel5bae0926b896
diff --git a/app/src/boot/globalEvent/command/panel.ts b/app/src/boot/globalEvent/command/panel.tsindex 081e69057c..799be5586e 100644--- a/app/src/boot/globalEvent/command/panel.ts+++ b/app/src/boot/globalEvent/command/panel.ts@@ -337,6 +337,9 @@ export const execByCommand = async (options: {notebook: protyle.notebookId,path: protyle.path.endsWith(".sy") ? protyle.path : protyle.path + ".sy"});+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }popSearch(options.app, {page: 1,hasReplace: true,@@ -385,6 +388,9 @@ export const execByCommand = async (options: {notebook: protyle.notebookId,path: protyle.path.endsWith(".sy") ? protyle.path : protyle.path + ".sy"});+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }popSearch(options.app, {page: 1,hasReplace: false,diff --git a/app/src/business/openRecentDocs.ts b/app/src/business/openRecentDocs.tsindex c0b85658fd..108ce16109 100644--- a/app/src/business/openRecentDocs.ts+++ b/app/src/business/openRecentDocs.ts@@ -34,7 +34,9 @@ const renderRecentDocsContent = async (data: {const pathResponse = await fetchSyncPost("/api/filetree/getFullHPathByID", {id: data[0].rootID // 过滤后的第一个文档 ID});- switchPath = escapeHtml(pathResponse.data);+ if (pathResponse.code === 0 && typeof pathResponse.data === "string") {+ switchPath = escapeHtml(pathResponse.data);+ }}let dockHtml = "";if (!isWindow()) {diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.tsindex e3d4f47b64..1d79b1bf22 100644--- a/app/src/menus/navigation.ts+++ b/app/src/menus/navigation.ts@@ -687,6 +687,9 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, lnotebook: notebookId,path: searchPath + ".sy"});+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }popSearch(app, {hasReplace: false,hPath: pathPosix().join(getNotebookName(notebookId), response.data),@@ -715,6 +718,9 @@ export const initFileMenu = (app: App, notebookId: string, pathString: string, lnotebook: notebookId,path: searchPath + ".sy"});+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }popSearch(app, {hasReplace: true,hPath: pathPosix().join(getNotebookName(notebookId), response.data),diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.tsindex d340328268..72f277befd 100644--- a/app/src/mobile/menu/search.ts+++ b/app/src/mobile/menu/search.ts@@ -479,6 +479,9 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab} else if (type === "currentPath" && !target.hasAttribute("disabled")) {const editProtyle = getCurrentEditor().protyle;fetchPost("/api/filetree/getHPathsByPaths", {paths: [editProtyle.path]}, (response) => {+ if (!Array.isArray(response.data) || typeof response.data[0] !== "string") {+ return;+ }config.idPath = [pathPosix().join(editProtyle.notebookId, editProtyle.path)];config.hPath = response.data[0];const searchPathElement = element.querySelector("#searchPath");diff --git a/app/src/protyle/header/openTitleMenu.ts b/app/src/protyle/header/openTitleMenu.tsindex 3205754996..c5b5f8bafa 100644--- a/app/src/protyle/header/openTitleMenu.ts+++ b/app/src/protyle/header/openTitleMenu.ts@@ -248,6 +248,9 @@ export const openTitleMenu = (protyle: IProtyle, position: IPosition, from: strinotebook: protyle.notebookId,path: searchPath + ".sy"});+ if (!isBoxDoc && (pathResponse?.code !== 0 || typeof pathResponse?.data !== "string")) {+ return;+ }popSearch(protyle.app, {hasReplace: false,hPath: isBoxDoc ? getNotebookName(protyle.notebookId) : pathPosix().join(getNotebookName(protyle.notebookId), pathResponse.data),diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.tsindex 3086cccffc..f940c85803 100644--- a/app/src/protyle/render/av/action.ts+++ b/app/src/protyle/render/av/action.ts@@ -619,6 +619,9 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positicontent = cellElement.querySelector(".av__celltext").textContent;} else {const response = await fetchSyncPost("/api/filetree/getHPathByID", {id});+ if (response.code !== 0 || typeof response.data !== "string") {+ continue;+ }content = response.data;}diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.tsindex 555fb2bc44..77153bae2f 100644--- a/app/src/protyle/toolbar/util.ts+++ b/app/src/protyle/toolbar/util.ts@@ -262,6 +262,9 @@ export const copyTextByType = async (ids: string[],text += `[${response.data.replace("[", "\\[").replace("]", "\\]")}](siyuan://blocks/${id})`;} else if (type === "hPath") {const response = await fetchSyncPost("/api/filetree/getHPathByID", {id});+ if (response.code !== 0 || typeof response.data !== "string") {+ continue;+ }text += response.data;} else if (type === "webURL") {text += `${window.location.origin}?id=${id}`;diff --git a/app/src/search/spread.ts b/app/src/search/spread.tsindex c3b88fc1e0..d24287c691 100644--- a/app/src/search/spread.ts+++ b/app/src/search/spread.ts@@ -24,6 +24,9 @@ export const openSearch = async (options: {notebook: options.notebookId,path: options.searchPath.endsWith(".sy") ? options.searchPath : options.searchPath + ".sy"});+ if (response.code !== 0 || typeof response.data !== "string") {+ return;+ }hPath = pathPosix().join(hPath, response.data);idPath[0] = pathPosix().join(idPath[0], options.searchPath);}@@ -74,6 +77,9 @@ export const openSearch = async (options: {cloneData.hasReplace = false;const toPath = item.editors.edit.protyle.path;fetchPost("/api/filetree/getHPathsByPaths", {paths: [toPath]}, (response) => {+ if (!Array.isArray(response.data) || typeof response.data[0] !== "string") {+ return;+ }cloneData.idPath = [pathPosix().join(item.editors.edit.protyle.notebookId, toPath)];cloneData.hPath = response.data[0];item.data.idPath = cloneData.idPath;diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 8ba213788d..ef8111b6da 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -376,6 +376,15 @@ func getHPathByPath(c *gin.Context) {ret.Msg = err.Error()return}+ if p != "/" && model.IsReadOnlyRoleContext(c) {+ publishAccess := model.GetPublishAccess()+ id := util.GetTreeID(p)+ if !model.CheckBlockIdMetadataAccessableByPublishAccessInBox(c, publishAccess, id, notebook) {+ ret.Code = -1+ ret.Msg = model.ErrBlockNotFound.Error()+ return+ }+ }ret.Data = hPath}@@ -393,6 +402,7 @@ func getHPathsByPaths(c *gin.Context) {for _, p := range pathsArg {paths = append(paths, p.(string))}+ paths = filterFileTreePathsByPublishMetadataAccess(c, paths)hPath, err := model.GetHPathsByPaths(paths)if err != nil {ret.Code = -1@@ -422,6 +432,14 @@ func getHPathByID(c *gin.Context) {ret.Msg = err.Error()return}+ if model.IsReadOnlyRoleContext(c) {+ publishAccess := model.GetPublishAccess()+ if !model.CheckBlockIdMetadataAccessableByPublishAccess(c, publishAccess, id) {+ ret.Code = -1+ ret.Msg = model.ErrTreeNotFound.Error()+ return+ }+ }ret.Data = hPath}@@ -448,6 +466,14 @@ func getPathByID(c *gin.Context) {ret.Msg = err.Error()return}+ if model.IsReadOnlyRoleContext(c) {+ publishAccess := model.GetPublishAccess()+ if !model.CheckBlockIdMetadataAccessableByPublishAccessInBox(c, publishAccess, id, notebook) {+ ret.Code = -1+ ret.Msg = model.ErrTreeNotFound.Error()+ return+ }+ }ret.Data = map[string]any{"path": p,"notebook": notebook,@@ -467,12 +493,23 @@ func getFullHPathByID(c *gin.Context) {}id := arg["id"].(string)+ if util.InvalidIDPattern(id, ret) {+ return+ }hPath, err := model.GetFullHPathByID(id)if err != nil {ret.Code = -1ret.Msg = err.Error()return}+ if model.IsReadOnlyRoleContext(c) {+ publishAccess := model.GetPublishAccess()+ if !model.CheckBlockIdMetadataAccessableByPublishAccess(c, publishAccess, id) {+ ret.Code = -1+ ret.Msg = model.ErrTreeNotFound.Error()+ return+ }+ }ret.Data = hPath}@@ -503,9 +540,46 @@ func getIDsByHPath(c *gin.Context) {ret.Msg = err.Error()return}+ ids = filterFileTreeBlockIDsByPublishDiscoverability(c, ids, notebook)ret.Data = ids}+func filterFileTreePathsByPublishMetadataAccess(c *gin.Context, paths []string) (ret []string) {+ if !model.IsReadOnlyRoleContext(c) {+ return paths+ }++ ids := make([]string, 0, len(paths))+ for _, p := range paths {+ ids = append(ids, util.GetTreeID(p))+ }+ blockTrees := treenode.GetBlockTrees(ids)+ publishAccess := model.GetPublishAccess()+ ret = make([]string, 0, len(paths))+ for i, p := range paths {+ if model.CheckBlockTreeMetadataAccessableByPublishAccess(c, publishAccess, blockTrees[ids[i]]) {+ ret = append(ret, p)+ }+ }+ return+}++func filterFileTreeBlockIDsByPublishDiscoverability(c *gin.Context, ids []string, boxID string) (ret []string) {+ if !model.IsReadOnlyRoleContext(c) {+ return ids+ }++ blockTrees := treenode.GetBlockTreesInBox(ids, boxID)+ publishAccess := model.GetPublishAccess()+ ret = make([]string, 0, len(ids))+ for _, id := range ids {+ if model.CheckBlockTreeDiscoverableByPublishAccess(publishAccess, blockTrees[id]) {+ ret = append(ret, id)+ }+ }+ return+}+func moveDocs(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.goindex eac83647a0..2e05361fef 100644--- a/kernel/api/filetree_test.go+++ b/kernel/api/filetree_test.go@@ -20,10 +20,17 @@ import ("encoding/json""net/http""net/http/httptest"+ "path/filepath"+ "slices""strings""testing"+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util")func TestSetSortRejectsInvalidRequest(t *testing.T) {@@ -61,3 +68,91 @@ func TestSetSortRejectsInvalidRequest(t *testing.T) {})}}++func TestFilterFileTreePublishAccess(t *testing.T) {+ const (+ boxID = "20260725000000-boxid01"+ publicID = "20260725000001-public1"+ protectedID = "20260725000002-protect"+ hiddenID = "20260725000003-hidden1"+ privateID = "20260725000004-private"+ forbiddenID = "20260725000005-forbid1"+ missingID = "20260725000006-missing"+ privatePassword = "private-password"+ protectedPassword = "protected-password"+ )++ previousBlockTreeDBPath := util.BlockTreeDBPath+ previousDataDir := util.DataDir+ util.DataDir = t.TempDir()+ util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")+ treenode.InitBlockTree(true)+ previousPublishAccess := model.GetPublishAccess()+ if err := model.SetPublishAccess(model.PublishAccess{+ {ID: protectedID, Visible: true, Password: protectedPassword},+ {ID: hiddenID, Visible: false},+ {ID: privateID, Visible: false, Password: privatePassword},+ {ID: forbiddenID, Visible: false, Disable: true},+ }); err != nil {+ t.Fatalf("set publish access failed: %v", err)+ }+ t.Cleanup(func() {+ _ = model.SetPublishAccess(previousPublishAccess)+ treenode.CloseDatabase()+ util.BlockTreeDBPath = previousBlockTreeDBPath+ util.DataDir = previousDataDir+ })++ ids := []string{publicID, protectedID, hiddenID, privateID, forbiddenID}+ allIDs := append(slices.Clone(ids), missingID)+ for _, id := range ids {+ treenode.IndexBlockTree(&parse.Tree{+ ID: id,+ Box: boxID,+ Path: "/" + id + ".sy",+ HPath: "/" + id,+ Root: &ast.Node{ID: id, Type: ast.NodeDocument},+ })+ }++ paths := []string{+ "/" + publicID + ".sy",+ "/" + protectedID + ".sy",+ "/" + hiddenID + ".sy",+ "/" + privateID + ".sy",+ "/" + forbiddenID + ".sy",+ "/" + missingID + ".sy",+ }+ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest(http.MethodPost, "/", nil)+ c.Set(model.RoleContextKey, model.RoleReader)++ expectedPaths := paths[:3]+ if filtered := filterFileTreePathsByPublishMetadataAccess(c, paths); !slices.Equal(filtered, expectedPaths) {+ t.Fatalf("unexpected unauthenticated reader paths: %v", filtered)+ }+ expectedIDs := []string{publicID, protectedID}+ if filtered := filterFileTreeBlockIDsByPublishDiscoverability(c, allIDs, boxID); !slices.Equal(filtered, expectedIDs) {+ t.Fatalf("unexpected reader discoverable IDs: %v", filtered)+ }++ c.Request.AddCookie(&http.Cookie{+ Name: "publish-auth-" + privateID,+ Value: util.SHA256Hash([]byte(privateID + privatePassword)),+ })+ expectedPaths = paths[:4]+ if filtered := filterFileTreePathsByPublishMetadataAccess(c, paths); !slices.Equal(filtered, expectedPaths) {+ t.Fatalf("unexpected authenticated reader paths: %v", filtered)+ }+ if filtered := filterFileTreeBlockIDsByPublishDiscoverability(c, allIDs, boxID); !slices.Equal(filtered, expectedIDs) {+ t.Fatalf("private documents should remain undiscoverable: %v", filtered)+ }++ c.Set(model.RoleContextKey, model.RoleAdministrator)+ if filtered := filterFileTreePathsByPublishMetadataAccess(c, paths); !slices.Equal(filtered, paths) {+ t.Fatalf("administrator paths should remain unchanged: %v", filtered)+ }+ if filtered := filterFileTreeBlockIDsByPublishDiscoverability(c, allIDs, boxID); !slices.Equal(filtered, allIDs) {+ t.Fatalf("administrator IDs should remain unchanged: %v", filtered)+ }+}diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.goindex 5d06d57d30..a78c5c7dc8 100644--- a/kernel/model/publish_access.go+++ b/kernel/model/publish_access.go@@ -226,6 +226,50 @@ func CheckBlockIdAccessableByPublishAccessInBox(c *gin.Context, publishAccess Pureturn checkBlockTreeAccessableByPublishAccess(c, publishAccess, bt)}+func CheckBlockIdMetadataAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, blockID string) bool {+ return CheckBlockIdMetadataAccessableByPublishAccessInBox(c, publishAccess, blockID, "")+}++func CheckBlockIdMetadataAccessableByPublishAccessInBox(c *gin.Context, publishAccess PublishAccess, blockID, boxID string) bool {+ bt := treenode.GetBlockTreeInBox(blockID, boxID)+ return CheckBlockTreeMetadataAccessableByPublishAccess(c, publishAccess, bt)+}++func CheckBlockTreeMetadataAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, bt *treenode.BlockTree) bool {+ if bt == nil {+ return false+ }++ publishDisable := GetDisablePublishAccess(publishAccess)+ if !CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishDisable) {+ return false+ }++ publishInvisible := GetInvisiblePublishAccess(publishAccess)+ if CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishInvisible) {+ return true+ }++ passwordID, password := GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)+ return password == "" || CheckPublishAuthCookie(c, passwordID, password)+}++func CheckBlockIdDiscoverableByPublishAccessInBox(publishAccess PublishAccess, blockID, boxID string) bool {+ bt := treenode.GetBlockTreeInBox(blockID, boxID)+ return CheckBlockTreeDiscoverableByPublishAccess(publishAccess, bt)+}++func CheckBlockTreeDiscoverableByPublishAccess(publishAccess PublishAccess, bt *treenode.BlockTree) bool {+ if bt == nil {+ return false+ }++ publishInvisible := GetInvisiblePublishAccess(publishAccess)+ publishDisable := GetDisablePublishAccess(publishAccess)+ return CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishInvisible) &&+ CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishDisable)+}+func checkBlockTreeAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, bt *treenode.BlockTree) bool {if bt == nil {return falsediff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.goindex f6e554280f..4d177a1204 100644--- a/kernel/model/publish_access_test.go+++ b/kernel/model/publish_access_test.go@@ -63,6 +63,148 @@ func TestCheckBlockTreeAccessableByPublishAccess(t *testing.T) {}}+func TestCheckBlockTreeMetadataAccessableByPublishAccess(t *testing.T) {+ const (+ boxID = "20260725000000-boxid01"+ docID = "20260725000001-docid01"+ parentID = "20260725000002-parent1"+ privateID = "20260725000003-private"+ privatePass = "password"+ protectedID = "20260725000004-protect"+ protectedPass = "protected-password"+ inconsistentID = "20260725000005-invalid"+ childID = "20260725000006-child01"+ )+ newBlockTree := func(id, blockPath string) *treenode.BlockTree {+ return &treenode.BlockTree{+ ID: id,+ BoxID: boxID,+ Path: blockPath,+ }+ }+ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest(http.MethodGet, "/", nil)++ tests := []struct {+ name string+ publishAccess PublishAccess+ blockTree *treenode.BlockTree+ metadata bool+ discoverable bool+ }{+ {+ name: "missing",+ blockTree: nil,+ metadata: false,+ discoverable: false,+ },+ {+ name: "public",+ blockTree: newBlockTree(docID, "/"+docID+".sy"),+ metadata: true,+ discoverable: true,+ },+ {+ name: "protected",+ publishAccess: PublishAccess{{ID: protectedID, Visible: true, Password: protectedPass}},+ blockTree: newBlockTree(protectedID, "/"+protectedID+".sy"),+ metadata: true,+ discoverable: true,+ },+ {+ name: "hidden",+ publishAccess: PublishAccess{{ID: docID, Visible: false}},+ blockTree: newBlockTree(docID, "/"+docID+".sy"),+ metadata: true,+ discoverable: false,+ },+ {+ name: "private",+ publishAccess: PublishAccess{{ID: privateID, Visible: false, Password: privatePass}},+ blockTree: newBlockTree(privateID, "/"+privateID+".sy"),+ metadata: false,+ discoverable: false,+ },+ {+ name: "forbidden",+ publishAccess: PublishAccess{{ID: docID, Visible: false, Disable: true}},+ blockTree: newBlockTree(docID, "/"+docID+".sy"),+ metadata: false,+ discoverable: false,+ },+ {+ name: "hidden parent",+ publishAccess: PublishAccess{{ID: parentID, Visible: false}},+ blockTree: newBlockTree(docID, "/"+parentID+"/"+docID+".sy"),+ metadata: true,+ discoverable: false,+ },+ {+ name: "private parent",+ publishAccess: PublishAccess{{ID: privateID, Visible: false, Password: privatePass}},+ blockTree: newBlockTree(docID, "/"+privateID+"/"+docID+".sy"),+ metadata: false,+ discoverable: false,+ },+ {+ name: "hidden notebook",+ publishAccess: PublishAccess{{ID: boxID, Visible: false}},+ blockTree: newBlockTree(docID, "/"+docID+".sy"),+ metadata: true,+ discoverable: false,+ },+ {+ name: "inconsistent visible forbidden",+ publishAccess: PublishAccess{{ID: inconsistentID, Visible: true, Disable: true}},+ blockTree: newBlockTree(inconsistentID, "/"+inconsistentID+".sy"),+ metadata: false,+ discoverable: false,+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if actual := CheckBlockTreeMetadataAccessableByPublishAccess(c, test.publishAccess, test.blockTree); actual != test.metadata {+ t.Fatalf("metadata access = %v, want %v", actual, test.metadata)+ }+ if actual := CheckBlockTreeDiscoverableByPublishAccess(test.publishAccess, test.blockTree); actual != test.discoverable {+ t.Fatalf("discoverable = %v, want %v", actual, test.discoverable)+ }+ })+ }++ privateTree := newBlockTree(privateID, "/"+privateID+".sy")+ privateAccess := PublishAccess{{ID: privateID, Visible: false, Password: privatePass}}+ c.Request.AddCookie(&http.Cookie{+ Name: "publish-auth-" + privateID,+ Value: util.SHA256Hash([]byte(privateID + privatePass)),+ })+ if !CheckBlockTreeMetadataAccessableByPublishAccess(c, privateAccess, privateTree) {+ t.Fatal("private document metadata should be accessible after authorization")+ }+ if CheckBlockTreeDiscoverableByPublishAccess(privateAccess, privateTree) {+ t.Fatal("private document should remain undiscoverable after authorization")+ }++ protectedChildTree := newBlockTree(childID, "/"+parentID+"/"+protectedID+"/"+childID+".sy")+ inheritedAccess := PublishAccess{+ {ID: parentID, Visible: false},+ {ID: protectedID, Visible: true, Password: protectedPass},+ }+ if CheckBlockTreeMetadataAccessableByPublishAccess(c, inheritedAccess, protectedChildTree) {+ t.Fatal("protected child metadata under a hidden parent should require authorization")+ }+ c.Request.AddCookie(&http.Cookie{+ Name: "publish-auth-" + protectedID,+ Value: util.SHA256Hash([]byte(protectedID + protectedPass)),+ })+ if !CheckBlockTreeMetadataAccessableByPublishAccess(c, inheritedAccess, protectedChildTree) {+ t.Fatal("protected child metadata under a hidden parent should be accessible after authorization")+ }+ if CheckBlockTreeDiscoverableByPublishAccess(inheritedAccess, protectedChildTree) {+ t.Fatal("protected child under a hidden parent should remain undiscoverable")+ }+}+func TestCheckAttributeViewItemIDAccessableByPublishAccess(t *testing.T) {attrView := &av.AttributeView{KeyValues: []*av.KeyValues{