Skip to content

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

:lock: Harden encrypted notebook isolation across import, asset, block, reference and AV paths https://github.com/siyuan-note/siyuan/issues/18034

Daniele06cc11ac2df
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 470c27b773..500b893548 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -305,6 +305,8 @@ func setFileAnnotation(c *gin.Context) {
// 加密笔记本的 .sya 写盘前必须加密;加密笔记本未解锁时拒绝写入(fail-closed,避免明文落盘)
writeData := []byte(data)
if boxID := model.ExtractBoxIDFromAssetsPath(writePath); boxID != "" && model.IsEncryptedBox(boxID) {
+ model.HoldBoxReadLock(boxID)
+ defer model.ReleaseBoxReadLock(boxID)
dek, dekErr := model.GetDEKIfUnlocked(boxID)
if dekErr != nil {
ret.Code = -1
@@ -360,6 +362,8 @@ func getFileAnnotation(c *gin.Context) {
}
// 加密笔记本的 .sya 读盘后必须解密;未解锁时拒绝返回(fail-closed,避免返回密文或误判)
if boxID := model.ExtractBoxIDFromAssetsPath(readPath); boxID != "" && model.IsEncryptedBox(boxID) {
+ model.HoldBoxReadLock(boxID)
+ defer model.ReleaseBoxReadLock(boxID)
dek, dekErr := model.GetDEKIfUnlocked(boxID)
if dekErr != nil {
ret.Code = -1
diff --git a/kernel/api/block.go b/kernel/api/block.go
index c06ccbf8c2..69746f5527 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -68,7 +68,7 @@ func getBlockTreeInfos(c *gin.Context) {
ids = append(ids, id.(string))
}
- ret.Data = model.GetBlockTreeInfos(ids)
+ ret.Data = model.GetBlockTreeInfosInBox(ids, encryptedNotebookFromArg(arg))
}
func getBlockSiblingID(c *gin.Context) {
@@ -81,7 +81,7 @@ func getBlockSiblingID(c *gin.Context) {
}
id := arg["id"].(string)
- parent, previous, next := model.GetBlockSiblingID(id)
+ parent, previous, next := model.GetBlockSiblingIDInBox(id, encryptedNotebookFromArg(arg))
ret.Data = map[string]string{
"parent": parent,
"next": next,
@@ -99,7 +99,7 @@ func getBlockRelevantIDs(c *gin.Context) {
}
id := arg["id"].(string)
- parentID, previousID, nextID, err := model.GetBlockRelevantIDs(id)
+ parentID, previousID, nextID, err := model.GetBlockRelevantIDsInBox(id, encryptedNotebookFromArg(arg))
if nil != err {
ret.Code = -1
ret.Msg = err.Error()
@@ -589,7 +589,7 @@ func getRefIDs(c *gin.Context) {
}
id := arg["id"].(string)
- refDefs, originalRefBlockIDs := model.GetBlockRefs(id)
+ refDefs, originalRefBlockIDs := model.GetBlockRefsInBox(id, encryptedNotebookFromArg(arg))
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
publishIgnore := model.GetInvisiblePublishAccess(publishAccess)
@@ -817,18 +817,18 @@ func getBlockDOM(c *gin.Context) {
}
id := arg["id"].(string)
- dom := model.GetBlockDOM(id)
+ boxID := encryptedNotebookFromArg(arg)
+ dom := model.GetBlockDOMInBox(id, boxID)
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
publishIgnore := model.GetDisablePublishAccess(publishAccess)
- bt := treenode.GetBlockTree(id)
- if bt != nil {
+ bt := treenode.GetBlockTreeInBox(id, boxID)
+ if nil == bt {
+ dom = ""
+ } else {
passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
- if password != "" && !model.CheckPublishAuthCookie(c, passwordID, password) {
- dom = ""
- }
- if !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
+ if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
dom = ""
}
}
@@ -855,21 +855,13 @@ func getBlockDOMs(c *gin.Context) {
ids = append(ids, id.(string))
}
- doms := model.GetBlockDOMs(ids)
+ boxID := encryptedNotebookFromArg(arg)
+ doms := model.GetBlockDOMsInBox(ids, boxID)
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
publishIgnore := model.GetDisablePublishAccess(publishAccess)
- bts := treenode.GetBlockTrees(ids)
- for id, bt := range bts {
- _, ok := doms[id]
- if ok {
- passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
- if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
- doms[id] = ""
- }
- }
- }
+ filterBlockDOMsByPublishAccess(c, doms, ids, boxID, publishAccess, publishIgnore)
}
ret.Data = doms
@@ -885,18 +877,18 @@ func getBlockDOMWithEmbed(c *gin.Context) {
}
id := arg["id"].(string)
- dom := model.GetBlockDOMWithEmbed(id)
+ boxID := encryptedNotebookFromArg(arg)
+ dom := model.GetBlockDOMWithEmbedInBox(id, boxID)
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
publishIgnore := model.GetDisablePublishAccess(publishAccess)
- bt := treenode.GetBlockTree(id)
- if bt != nil {
+ bt := treenode.GetBlockTreeInBox(id, boxID)
+ if nil == bt {
+ dom = ""
+ } else {
passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
- if password != "" && !model.CheckPublishAuthCookie(c, passwordID, password) {
- dom = ""
- }
- if !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
+ if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
dom = ""
}
}
@@ -923,26 +915,43 @@ func getBlockDOMsWithEmbed(c *gin.Context) {
ids = append(ids, id.(string))
}
- doms := model.GetBlockDOMsWithEmbed(ids)
+ boxID := encryptedNotebookFromArg(arg)
+ doms := model.GetBlockDOMsWithEmbedInBox(ids, boxID)
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
publishIgnore := model.GetDisablePublishAccess(publishAccess)
- bts := treenode.GetBlockTrees(ids)
- for id, bt := range bts {
- _, ok := doms[id]
- if ok {
- passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
- if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
- doms[id] = ""
- }
- }
- }
+ filterBlockDOMsByPublishAccess(c, doms, ids, boxID, publishAccess, publishIgnore)
}
ret.Data = doms
}
+func encryptedNotebookFromArg(arg map[string]any) string {
+ notebook, _ := arg["notebook"].(string)
+ if notebook != "" && model.IsEncryptedBox(notebook) {
+ return notebook
+ }
+ return ""
+}
+
+func filterBlockDOMsByPublishAccess(c *gin.Context, doms map[string]string, ids []string, boxID string, publishAccess model.PublishAccess, publishIgnore model.PublishAccess) {
+ for _, id := range ids {
+ if _, ok := doms[id]; !ok {
+ continue
+ }
+ bt := treenode.GetBlockTreeInBox(id, boxID)
+ if nil == bt {
+ doms[id] = ""
+ continue
+ }
+ passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
+ if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
+ doms[id] = ""
+ }
+ }
+}
+
func getBlockKramdown(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
@@ -970,9 +979,10 @@ func getBlockKramdown(c *gin.Context) {
}
}
+ boxID := encryptedNotebookFromArg(arg)
var kramdown string
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
- kramdown = model.GetBlockKramdownInBox(id, mode, notebook)
+ if boxID != "" {
+ kramdown = model.GetBlockKramdownInBox(id, mode, boxID)
} else {
kramdown = model.GetBlockKramdown(id, mode)
}
@@ -980,13 +990,12 @@ func getBlockKramdown(c *gin.Context) {
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
publishIgnore := model.GetDisablePublishAccess(publishAccess)
- bt := treenode.GetBlockTree(id)
- if bt != nil {
+ bt := treenode.GetBlockTreeInBox(id, boxID)
+ if nil == bt {
+ kramdown = ""
+ } else {
passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
- if password != "" && !model.CheckPublishAuthCookie(c, passwordID, password) {
- kramdown = ""
- }
- if !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
+ if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
kramdown = ""
}
}
@@ -1030,9 +1039,10 @@ func getBlockKramdowns(c *gin.Context) {
}
}
+ boxID := encryptedNotebookFromArg(arg)
var kramdowns map[string]string
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
- kramdowns = model.GetBlockKramdownsInBox(ids, mode, notebook)
+ if boxID != "" {
+ kramdowns = model.GetBlockKramdownsInBox(ids, mode, boxID)
} else {
kramdowns = model.GetBlockKramdowns(ids, mode)
}
@@ -1040,21 +1050,29 @@ func getBlockKramdowns(c *gin.Context) {
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
publishIgnore := model.GetDisablePublishAccess(publishAccess)
- bts := treenode.GetBlockTrees(ids)
- for id, bt := range bts {
- _, ok := kramdowns[id]
- if ok {
- passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
- if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
- kramdowns[id] = ""
- }
- }
- }
+ filterBlockKramdownsByPublishAccess(c, kramdowns, ids, boxID, publishAccess, publishIgnore)
}
ret.Data = kramdowns
}
+func filterBlockKramdownsByPublishAccess(c *gin.Context, kramdowns map[string]string, ids []string, boxID string, publishAccess model.PublishAccess, publishIgnore model.PublishAccess) {
+ for _, id := range ids {
+ if _, ok := kramdowns[id]; !ok {
+ continue
+ }
+ bt := treenode.GetBlockTreeInBox(id, boxID)
+ if nil == bt {
+ kramdowns[id] = ""
+ continue
+ }
+ passwordID, password := model.GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
+ if (password != "" && !model.CheckPublishAuthCookie(c, passwordID, password)) || !model.CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {
+ kramdowns[id] = ""
+ }
+ }
+}
+
func getChildBlocks(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/api/file.go b/kernel/api/file.go
index 574fbaca45..88e28289c1 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -69,6 +69,8 @@ func copyDecryptedAsset(src, dest string) error {
if boxID == "" || !model.IsEncryptedBox(boxID) {
return fmt.Errorf("source is not an encrypted asset")
}
+ model.HoldBoxReadLock(boxID)
+ defer model.ReleaseBoxReadLock(boxID)
dek, dekErr := model.GetDEKIfUnlocked(boxID)
if dekErr != nil {
return dekErr
diff --git a/kernel/api/ref.go b/kernel/api/ref.go
index 757d6e0cf8..4589352a33 100644
--- a/kernel/api/ref.go
+++ b/kernel/api/ref.go
@@ -52,6 +52,10 @@ func getBackmentionDoc(c *gin.Context) {
defID := arg["defID"].(string)
refTreeID := arg["refTreeID"].(string)
keyword := arg["keyword"].(string)
+ var notebook string
+ if val, ok := arg["notebook"]; ok {
+ notebook = val.(string)
+ }
containChildren := model.Conf.Editor.BacklinkContainChildren
if val, ok := arg["containChildren"]; ok {
containChildren = val.(bool)
@@ -60,7 +64,13 @@ func getBackmentionDoc(c *gin.Context) {
if val, ok := arg["highlight"]; ok {
highlight = val.(bool)
}
- backlinks, keywords := model.GetBackmentionDoc(defID, refTreeID, keyword, containChildren, highlight)
+ var backlinks []*model.Backlink
+ var keywords []string
+ if notebook != "" && model.IsEncryptedBox(notebook) {
+ backlinks, keywords = model.GetBackmentionDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)
+ } else {
+ backlinks, keywords = model.GetBackmentionDoc(defID, refTreeID, keyword, containChildren, highlight)
+ }
ret.Data = map[string]any{
"backmentions": backlinks,
"keywords": keywords,
@@ -79,6 +89,10 @@ func getBacklinkDoc(c *gin.Context) {
defID := arg["defID"].(string)
refTreeID := arg["refTreeID"].(string)
keyword := arg["keyword"].(string)
+ var notebook string
+ if val, ok := arg["notebook"]; ok {
+ notebook = val.(string)
+ }
containChildren := model.Conf.Editor.BacklinkContainChildren
if val, ok := arg["containChildren"]; ok {
containChildren = val.(bool)
@@ -87,7 +101,13 @@ func getBacklinkDoc(c *gin.Context) {
if val, ok := arg["highlight"]; ok {
highlight = val.(bool)
}
- backlinks, keywords := model.GetBacklinkDoc(defID, refTreeID, keyword, containChildren, highlight)
+ var backlinks []*model.Backlink
+ var keywords []string
+ if notebook != "" && model.IsEncryptedBox(notebook) {
+ backlinks, keywords = model.GetBacklinkDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)
+ } else {
+ backlinks, keywords = model.GetBacklinkDoc(defID, refTreeID, keyword, containChildren, highlight)
+ }
ret.Data = map[string]any{
"backlinks": backlinks,
"keywords": keywords,
diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.go
index 7433d7645c..3384cdb483 100644
--- a/kernel/av/encrypted_hook.go
+++ b/kernel/av/encrypted_hook.go
@@ -87,15 +87,6 @@ func FindAttributeViewPath(avID string) (path string, boxID string) {
if filelock.IsExist(globalPath) {
return globalPath, ""
}
- // 遍历已打开的加密 box
- if AVEncryptedBoxIDs != nil {
- for _, encBoxID := range AVEncryptedBoxIDs() {
- encPath := attributeViewDataPathByBox(avID, encBoxID)
- if filelock.IsExist(encPath) {
- return encPath, encBoxID
- }
- }
- }
return "", ""
}
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index 83854b0767..33ebe925a9 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -202,6 +202,115 @@ func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlight
return
}
+func GetBacklinkDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string) (ret []*Backlink, keywords []string) {
+ keyword = strings.TrimSpace(keyword)
+ if "" != keyword {
+ keywords = strings.Split(keyword, " ")
+ }
+ keywords = gulu.Str.RemoveDuplicatedElem(keywords)
+ if 1 > len(keywords) {
+ keywords = []string{}
+ }
+
+ ret = []*Backlink{}
+ sqlBlock := sql.GetBlockInBox(defID, boxID)
+ if nil == sqlBlock {
+ return
+ }
+ rootID := sqlBlock.RootID
+
+ tmpRefs := sql.QueryRefsByDefIDInBox(defID, containChildren, boxID)
+ var refs []*sql.Ref
+ for _, ref := range tmpRefs {
+ if ref.RootID == refTreeID {
+ refs = append(refs, ref)
+ }
+ }
+ refs = removeDuplicatedRefs(refs)
+
+ linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, boxID)
+ refTree, err := loadTreeByBlockIDInBox(refTreeID, boxID)
+ if err != nil {
+ logging.LogWarnf("load ref tree [%s] failed: %s", refTreeID, err)
+ return
+ }
+
+ luteEngine := util.NewLute()
+ for _, linkRef := range linkRefs {
+ backlink := buildBacklink(linkRef.ID, refTree, originalRefBlockIDs, keywords, highlight, luteEngine)
+ if nil != backlink {
+ ret = append(ret, backlink)
+ }
+ }
+
+ sortBacklinks(ret, refTree)
+ filterBlockPaths(ret)
+ return
+}
+
+func GetBackmentionDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string) (ret []*Backlink, keywords []string) {
+ keyword = strings.TrimSpace(keyword)
+ if "" != keyword {
+ keywords = strings.Split(keyword, " ")
+ }
+ ret = []*Backlink{}
+ beforeLen := 12
+ sqlBlock := sql.GetBlockInBox(defID, boxID)
+ if nil == sqlBlock {
+ return
+ }
+ rootID := sqlBlock.RootID
+
+ refs := sql.QueryRefsByDefIDInBox(defID, containChildren, boxID)
+ refs = removeDuplicatedRefs(refs)
+
+ linkRefs, _, excludeBacklinkIDs, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, boxID)
+ tmpMentions, mentionKeywords := buildTreeBackmentionInBox(sqlBlock, linkRefs, keyword, excludeBacklinkIDs, beforeLen, boxID)
+ luteEngine := util.NewLute()
+ var mentions []*Block
+ for _, mention := range tmpMentions {
+ if mention.RootID == refTreeID {
+ mentions = append(mentions, mention)
+ }
+ }
+ var mentionBlockIDs []string
+ for _, mention := range mentions {
+ mentionBlockIDs = append(mentionBlockIDs, mention.ID)
+ }
+ mentionBlockIDs = gulu.Str.RemoveDuplicatedElem(mentionBlockIDs)
+
+ if "" != keyword {
+ mentionKeywords = append(mentionKeywords, strings.Split(keyword, " ")...)
+ }
+ mentionKeywords = gulu.Str.RemoveDuplicatedElem(mentionKeywords)
+ keywords = append(keywords, mentionKeywords...)
+ keywords = gulu.Str.RemoveDuplicatedElem(keywords)
+ if 1 > len(keywords) {
+ keywords = []string{}
+ }
+
+ var refTree *parse.Tree
+ for _, id := range mentionBlockIDs {
+ tree, loadErr := loadTreeByBlockIDInBox(id, boxID)
+ if loadErr != nil || tree == nil {
+ continue
+ }
+ backlink := buildBacklink(id, tree, originalRefBlockIDs, mentionKeywords, highlight, luteEngine)
+ if nil != backlink {
+ ret = append(ret, backlink)
+ }
+ if nil != tree && nil == refTree {
+ refTree = tree
+ }
+ }
+
+ if 0 < len(ret) {
+ sortBacklinks(ret, refTree)
+ filterBlockPaths(ret)
+ }
+ return
+}
+
func filterBlockPaths(blockLinks []*Backlink) {
for _, b := range blockLinks {
if 2 == len(b.BlockPaths) {
@@ -820,6 +929,9 @@ func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keywo
}
}
root := treenode.GetBlockTreeInBox(defSQLBlock.RootID, boxID)
+ if nil == root {
+ return
+ }
rootID = root.ID
}
diff --git a/kernel/model/block.go b/kernel/model/block.go
index 591eef5964..315f307f06 100644
--- a/kernel/model/block.go
+++ b/kernel/model/block.go
@@ -164,9 +164,17 @@ type BlockTreeInfo struct {
}
func GetBlockTreeInfos(ids []string) (ret map[string]*BlockTreeInfo) {
+ return GetBlockTreeInfosInBox(ids, "")
+}
+
+// GetBlockTreeInfosInBox 获取指定笔记本内的块树信息。空 box 仅查询普通全局库。
+func GetBlockTreeInfosInBox(ids []string, boxID string) (ret map[string]*BlockTreeInfo) {
ret = map[string]*BlockTreeInfo{}
- trees := filesys.LoadTrees(ids)
- for id, tree := range trees {
+ for _, id := range ids {
+ tree := loadTreeForBlockDOM(id, boxID)
+ if nil == tree {
+ continue
+ }
node := treenode.GetNodeInTree(tree, id)
if nil == node {
ret[id] = &BlockTreeInfo{ID: id}
@@ -195,8 +203,13 @@ func GetBlockTreeInfos(ids []string) (ret map[string]*BlockTreeInfo) {
}
func GetBlockSiblingID(id string) (parent, previous, next string) {
- tree, err := LoadTreeByBlockID(id)
- if err != nil {
+ return GetBlockSiblingIDInBox(id, "")
+}
+
+// GetBlockSiblingIDInBox 获取指定笔记本内块的相邻关系。空 box 不回退搜索加密笔记本。
+func GetBlockSiblingIDInBox(id, boxID string) (parent, previous, next string) {
+ tree := loadTreeForBlockDOM(id, boxID)
+ if nil == tree {
return
}
@@ -305,8 +318,14 @@ func getPreNext(parent *ast.Node) (previous, next string) {
}
func GetBlockRelevantIDs(id string) (parentID, previousID, nextID string, err error) {
- tree, err := LoadTreeByBlockID(id)
- if err != nil {
+ return GetBlockRelevantIDsInBox(id, "")
+}
+
+// GetBlockRelevantIDsInBox 获取指定笔记本内块的父级及相邻块 ID。空 box 不回退搜索加密笔记本。
+func GetBlockRelevantIDsInBox(id, boxID string) (parentID, previousID, nextID string, err error) {
+ tree := loadTreeForBlockDOM(id, boxID)
+ if nil == tree {
+ err = ErrTreeNotFound
return
}
@@ -825,24 +844,37 @@ func GetHeadingLevelTransaction(id string, level int) (transaction *Transaction,
}
func GetBlockDOM(id string) (ret string) {
+ return GetBlockDOMInBox(id, "")
+}
+
+// GetBlockDOMInBox 渲染指定笔记本内的块 DOM。boxID 为空时仅查询普通全局库。
+func GetBlockDOMInBox(id, boxID string) (ret string) {
if "" == id {
return
}
- doms := GetBlockDOMs([]string{id})
+ doms := GetBlockDOMsInBox([]string{id}, boxID)
ret = doms[id]
return
}
func GetBlockDOMs(ids []string) (ret map[string]string) {
+ return GetBlockDOMsInBox(ids, "")
+}
+
+// GetBlockDOMsInBox 渲染指定笔记本内的块 DOM。禁止在 boxID 未指定时遍历加密笔记本。
+func GetBlockDOMsInBox(ids []string, boxID string) (ret map[string]string) {
ret = map[string]string{}
if 0 == len(ids) {
return
}
luteEngine := NewLute()
- trees := filesys.LoadTrees(ids)
- for id, tree := range trees {
+ for _, id := range ids {
+ tree := loadTreeForBlockDOM(id, boxID)
+ if nil == tree {
+ continue
+ }
node := treenode.GetNodeInTree(tree, id)
if nil == node {
continue
@@ -865,30 +897,43 @@ func GetBlockDOMs(ids []string) (ret map[string]string) {
}
func GetBlockDOMWithEmbed(id string) (ret string) {
+ return GetBlockDOMWithEmbedInBox(id, "")
+}
+
+// GetBlockDOMWithEmbedInBox 渲染指定笔记本内包含嵌入块的 DOM。
+func GetBlockDOMWithEmbedInBox(id, boxID string) (ret string) {
if "" == id {
return
}
- doms := GetBlockDOMsWithEmbed([]string{id})
+ doms := GetBlockDOMsWithEmbedInBox([]string{id}, boxID)
ret = doms[id]
return
}
func GetBlockDOMsWithEmbed(ids []string) (ret map[string]string) {
+ return GetBlockDOMsWithEmbedInBox(ids, "")
+}
+
+// GetBlockDOMsWithEmbedInBox 渲染指定笔记本内包含嵌入块的 DOM。boxID 为空时仅查询普通全局库。
+func GetBlockDOMsWithEmbedInBox(ids []string, boxID string) (ret map[string]string) {
ret = map[string]string{}
if 0 == len(ids) {
return
}
luteEngine := NewLute()
- trees := filesys.LoadTrees(ids)
- for id, tree := range trees {
+ for _, id := range ids {
+ tree := loadTreeForBlockDOM(id, boxID)
+ if nil == tree {
+ continue
+ }
node := treenode.GetNodeInTree(tree, id)
if nil == node {
continue
}
- resolveEmbedContent(node, luteEngine)
+ resolveEmbedContentInBox(node, luteEngine, boxID)
// 处理折叠标题
ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
@@ -912,6 +957,23 @@ func GetBlockDOMsWithEmbed(ids []string) (ret map[string]string) {
}
func resolveEmbedContent(n *ast.Node, luteEngine *lute.Lute) {
+ resolveEmbedContentInBox(n, luteEngine, "")
+}
+
+// loadTreeForBlockDOM 按指定 box 加载树,空 box 不回退搜索已打开的加密笔记本。
+func loadTreeForBlockDOM(id, boxID string) *parse.Tree {
+ bt := treenode.GetBlockTreeInBox(id, boxID)
+ if nil == bt {
+ return nil
+ }
+ tree, err := loadTreeByBlockTree(bt)
+ if nil != err {
+ return nil
+ }
+ return tree
+}
+
+func resolveEmbedContentInBox(n *ast.Node, luteEngine *lute.Lute, boxID string) {
ast.Walk(n, func(node *ast.Node, entering bool) ast.WalkStatus {
if !entering || ast.NodeBlockQueryEmbed != node.Type {
return ast.WalkContinue
@@ -927,7 +989,7 @@ func resolveEmbedContent(n *ast.Node, luteEngine *lute.Lute) {
stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
// 执行查询获取嵌入的块
- sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
+ sqlBlocks := sql.SelectBlocksRawStmtInBox(stmt, 1, Conf.Search.Limit, boxID)
// 收集所有嵌入块的内容 HTML
var embedContents []string
@@ -936,7 +998,7 @@ func resolveEmbedContent(n *ast.Node, luteEngine *lute.Lute) {
continue
}
- subTree, _ := LoadTreeByBlockID(sqlBlock.ID)
+ subTree := loadTreeForBlockDOM(sqlBlock.ID, boxID)
if nil == subTree {
continue
}
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index ea2687b8b1..32b472d293 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -383,17 +383,14 @@ type RefDefs struct {
}
func GetBlockRefs(defID string) (refDefs []*RefDefs, originalRefBlockIDs map[string]string) {
+ return GetBlockRefsInBox(defID, "")
+}
+
+// GetBlockRefsInBox 获取指定笔记本内的块引用关系。空 box 不回退搜索加密笔记本。
+func GetBlockRefsInBox(defID, boxID string) (refDefs []*RefDefs, originalRefBlockIDs map[string]string) {
refDefs = []*RefDefs{}
originalRefBlockIDs = map[string]string{}
- bt := treenode.GetBlockTree(defID)
- if nil == bt {
- for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
- if encBT := treenode.GetBlockTreeInBox(defID, encBoxID); nil != encBT {
- bt = encBT
- break
- }
- }
- }
+ bt := treenode.GetBlockTreeInBox(defID, boxID)
if nil == bt {
return
}
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 3207dff4c7..9ac5baba3b 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -3612,6 +3612,8 @@ func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode i
}
// 加密 box 的 .sya 是密文,需先解密
if IsEncryptedBox(boxID) {
+ HoldBoxReadLock(boxID)
+ defer ReleaseBoxReadLock(boxID)
dek, dekErr := GetDEKIfUnlocked(boxID)
if dekErr != nil {
logging.LogWarnf("get DEK for file annotation [%s] failed: %s", sya, dekErr)
diff --git a/kernel/model/history.go b/kernel/model/history.go
index f6357c4a83..7b94ad8097 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -186,6 +186,8 @@ func GetDocHistoryContent(historyPath, keyword string, highlight bool) (id, root
if len(pathParts) >= 2 {
histBoxID := pathParts[1]
if IsEncryptedBox(histBoxID) {
+ HoldBoxReadLock(histBoxID)
+ defer ReleaseBoxReadLock(histBoxID)
dek, dekErr := GetDEKIfUnlocked(histBoxID)
if dekErr != nil {
err = errors.New(Conf.Language(314))
@@ -313,6 +315,8 @@ func RollbackDocHistory(historyPath string) (err error) {
return
}
if IsEncryptedBox(origBoxID) {
+ HoldBoxReadLock(origBoxID)
+ defer ReleaseBoxReadLock(origBoxID)
dek, dekErr := GetDEKIfUnlocked(origBoxID)
if dekErr != nil {
err = errors.New(Conf.Language(314))
diff --git a/kernel/model/import.go b/kernel/model/import.go
index b94e5ee6ae..264cdcccd4 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -444,27 +444,9 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
data = buf.Bytes()
}
- // 加密笔记本的数据需先加密再落盘,导入的 .sy 原文是明文 JSON
- if IsEncryptedBox(boxID) {
- dek, dekErr := GetDEKIfUnlocked(boxID)
- if dekErr != nil {
- err = errors.New(Conf.Language(314))
- return
- }
- var encErr error
- data, encErr = EncryptFile(boxID, finalRelPath, dek, data)
- if encErr != nil {
- logging.LogErrorf("encrypt import .sy failed: %s", encErr)
- return
- }
- }
- if err = os.WriteFile(syPath, data, 0644); err != nil {
- logging.LogErrorf("write .sy [%s] failed: %s", syPath, err)
- return
- }
newSyPath := filepath.Join(filepath.Dir(syPath), finalSyName)
- if err = filelock.Rename(syPath, newSyPath); err != nil {
- logging.LogErrorf("rename .sy from [%s] to [%s] failed: %s", syPath, newSyPath, err)
+ if err = writeImportedTree(boxID, syPath, newSyPath, finalRelPath, data); err != nil {
+ logging.LogErrorf("write imported .sy [%s] failed: %s", syPath, err)
return
}
tree.Path = finalRelPath
@@ -782,6 +764,26 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
return
}
+func writeImportedTree(boxID, syPath, newSyPath, relPath string, data []byte) error {
+ if IsEncryptedBox(boxID) {
+ HoldBoxReadLock(boxID)
+ defer ReleaseBoxReadLock(boxID)
+
+ dek, err := GetDEKIfUnlocked(boxID)
+ if err != nil {
+ return errors.New(Conf.Language(314))
+ }
+ data, err = EncryptFile(boxID, relPath, dek, data)
+ if err != nil {
+ return err
+ }
+ }
+ if err := os.WriteFile(syPath, data, 0644); err != nil {
+ return err
+ }
+ return filelock.Rename(syPath, newSyPath)
+}
+
// updateImportedAssetRefs 遍历树的 assets 引用路径,将原始文件名替换为脱敏文件名。
// 覆盖:链接 href、图片 src、data-src、音视频 src、文件标注等。
func updateImportedAssetRefs(tree *parse.Tree, assetNameMap map[string]string) {
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 621f772214..1e8b4f9bca 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -436,6 +436,8 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
repoBoxID = parts[0]
}
if repoBoxID != "" && IsEncryptedBox(repoBoxID) {
+ HoldBoxReadLock(repoBoxID)
+ defer ReleaseBoxReadLock(repoBoxID)
if dek, dekErr := GetDEKIfUnlocked(repoBoxID); dekErr == nil && dek != nil {
avID := strings.TrimSuffix(filepath.Base(file.Path), ".json")
if plainData, decErr := av.DecryptAVData(repoBoxID, avID, data); decErr == nil {
@@ -465,6 +467,8 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
repoBoxID = parts[0]
}
if repoBoxID != "" && IsEncryptedBox(repoBoxID) {
+ HoldBoxReadLock(repoBoxID)
+ defer ReleaseBoxReadLock(repoBoxID)
// 加密 asset:尝试解密后预览,无法解密则 fail-closed
if dek, dekErr := GetDEKIfUnlocked(repoBoxID); dekErr == nil && dek != nil {
diskName := filepath.Base(file.Path)
@@ -794,6 +798,8 @@ func ExportRepoFile(id string) (exportPath string, err error) {
repoRel := strings.TrimPrefix(file.Path, "/")
repoParts := strings.SplitN(repoRel, "/", 2)
if len(repoParts) >= 1 && ast.IsNodeIDPattern(repoParts[0]) && IsEncryptedBox(repoParts[0]) {
+ HoldBoxReadLock(repoParts[0])
+ defer ReleaseBoxReadLock(repoParts[0])
if _, dekErr := GetDEKIfUnlocked(repoParts[0]); dekErr != nil {
err = errors.New(Conf.Language(314))
return
diff --git a/kernel/model/tree.go b/kernel/model/tree.go
index 5c17a67382..b91d7e9e7d 100644
--- a/kernel/model/tree.go
+++ b/kernel/model/tree.go
@@ -171,6 +171,8 @@ func loadTree(localPath string, luteEngine *lute.Lute) (ret *parse.Tree, err err
// 加密笔记本的 .sy 是密文,需先解密。从路径反推 boxID,已解锁的加密笔记本用 fileKey 解密;
// 加密笔记本未解锁时返回错误(fail-closed);非加密笔记本原样 data。
if boxID := extractBoxIDFromPath(localPath); boxID != "" && IsEncryptedBox(boxID) {
+ HoldBoxReadLock(boxID)
+ defer ReleaseBoxReadLock(boxID)
dek, dekErr := GetDEKIfUnlocked(boxID)
if dekErr != nil {
err = dekErr
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index bbf3247afe..da0bfcd032 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -436,6 +436,8 @@ func writeAssetFile(writePath string, src io.Reader, boxID string) (err error) {
actualBoxID = boxID // 路径不在 box 下(如全局 assets),回退传入值
}
if actualBoxID != "" && IsEncryptedBox(actualBoxID) {
+ HoldBoxReadLock(actualBoxID)
+ defer ReleaseBoxReadLock(actualBoxID)
dek, dekErr := GetDEKIfUnlocked(actualBoxID)
if dekErr != nil {
// 加密笔记本未解锁:拒绝写入,避免明文落盘(深度防御,见 issue #18034)
@@ -469,10 +471,13 @@ func StoreAssetForBox(boxID, assetDirPath, originalName string, data []byte) (di
// boxID 为空时按普通 box 处理(写入全局 assets)。
func storeAssetForBox(boxID, assetDirPath, originalName string, data []byte) (diskName string, err error) {
if IsEncryptedBox(boxID) {
+ HoldBoxReadLock(boxID)
+ defer ReleaseBoxReadLock(boxID)
+
ext := filepath.Ext(originalName)
blockID := ast.NewNodeID()
diskName = encryptedAssetName(ext, blockID)
- writeAssetNameMapping(boxID, diskName, originalName)
+ writeAssetNameMappingLocked(boxID, diskName, originalName)
dek, dekErr := GetDEKIfUnlocked(boxID)
if dekErr != nil {
@@ -517,12 +522,18 @@ func writeAssetNameMapping(boxID, diskName, originalName string) {
if boxID == "" || !IsEncryptedBox(boxID) {
return
}
+ HoldBoxReadLock(boxID)
+ defer ReleaseBoxReadLock(boxID)
+ writeAssetNameMappingLocked(boxID, diskName, originalName)
+}
+
+func writeAssetNameMappingLocked(boxID, diskName, originalName string) {
muI, _ := assetNameMappingLocks.LoadOrStore(boxID, &sync.Mutex{})
mu := muI.(*sync.Mutex)
mu.Lock()
defer mu.Unlock()
- mapping := readAssetNameMapping(boxID)
+ mapping := readAssetNameMappingLocked(boxID)
mapping[diskName] = originalName
data, err := json.Marshal(mapping)
if err != nil {
@@ -550,6 +561,13 @@ func readAssetNameMapping(boxID string) map[string]string {
if boxID == "" || !IsEncryptedBox(boxID) {
return ret
}
+ HoldBoxReadLock(boxID)
+ defer ReleaseBoxReadLock(boxID)
+ return readAssetNameMappingLocked(boxID)
+}
+
+func readAssetNameMappingLocked(boxID string) map[string]string {
+ ret := map[string]string{}
p := assetNameMappingPath(boxID)
enc, err := filelock.ReadFile(p)
if err != nil {
@@ -576,3 +594,8 @@ func readAssetNameMapping(boxID string) map[string]string {
func LookupAssetOriginalName(boxID, diskName string) string {
return readAssetNameMapping(boxID)[diskName]
}
+
+// LookupAssetOriginalNameLocked 在调用方已持有 box 读锁时查询原始资源名。
+func LookupAssetOriginalNameLocked(boxID, diskName string) string {
+ return readAssetNameMappingLocked(boxID)[diskName]
+}
diff --git a/kernel/model/virutalref.go b/kernel/model/virutalref.go
index 9fd16d485b..49c0cc19cc 100644
--- a/kernel/model/virutalref.go
+++ b/kernel/model/virutalref.go
@@ -113,6 +113,9 @@ func CacheVirtualBlockRefJob() {
func ResetVirtualBlockRefCache() {
virtualBlockRefCache.Clear()
+ if nil == Conf {
+ return
+ }
if !Conf.Editor.VirtualBlockRef {
return
}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 3cfe3880c8..0ce14ed524 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -833,7 +833,7 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
return true
}
// 下载时用原始文件名(查加密映射),查不到则退回磁盘名
- if originalName := model.LookupAssetOriginalName(boxID, diskName); originalName != "" {
+ if originalName := model.LookupAssetOriginalNameLocked(boxID, diskName); originalName != "" {
setAssetsAttachmentDisposition(context, originalName)
} else {
setAssetsAttachmentDisposition(context, absPath)
@@ -953,6 +953,8 @@ func serveRepoDiff(ginServer *gin.Engine) {
// 从路径提取 boxID,加密笔记本已锁定时拒绝访问(锁定后 repo 预览解密文件仍存在磁盘上)
parts := strings.SplitN(strings.TrimPrefix(requestPath, "/"), "/", 2)
if len(parts) >= 1 && model.IsEncryptedBox(parts[0]) {
+ model.HoldBoxReadLock(parts[0])
+ defer model.ReleaseBoxReadLock(parts[0])
if _, dekErr := model.GetDEKIfUnlocked(parts[0]); dekErr != nil {
context.Status(http.StatusForbidden)
return