Skip to content

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

:bug: fix encrypted-notebook P0/P1/P2 issues from full audit #18034

Daniel48920481b54d
diff --git a/kernel/api/file.go b/kernel/api/file.go
index b9c57d0f76..80f03b2af2 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -394,6 +394,16 @@ func getFile(c *gin.Context) {
}
}
+ // 加密笔记本的 .sy 是密文,直接返回密文无意义且可能被插件误解析
+ if strings.HasSuffix(filePath, ".sy") {
+ boxID := model.ExtractBoxIDFromAssetsPath(fileAbsPath)
+ if "" != boxID && model.IsEncryptedBox(boxID) {
+ ret.Code = -1
+ ret.Msg = "access to encrypted notebook .sy files is not supported via this API"
+ return
+ }
+ }
+
data, err := filelock.ReadFile(fileAbsPath)
if err != nil {
logging.LogErrorf("read file [%s] failed: %s", fileAbsPath, err)
@@ -767,6 +777,16 @@ func putFile(c *gin.Context) {
break
}
+ // 加密笔记本的 .sy 写入会破坏密文格式
+ if strings.HasSuffix(fileAbsPath, ".sy") {
+ boxID := model.ExtractBoxIDFromAssetsPath(fileAbsPath)
+ if "" != boxID && model.IsEncryptedBox(boxID) {
+ ret.Code = -1
+ ret.Msg = "writing to encrypted notebook .sy files is not supported via this API"
+ return
+ }
+ }
+
err = filelock.WriteFile(fileAbsPath, data)
if err != nil {
logging.LogErrorf("write file [%s] failed: %s", fileAbsPath, err)
diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.go
index b1102fe1dd..0a2a6aa5d3 100644
--- a/kernel/av/encrypted_hook.go
+++ b/kernel/av/encrypted_hook.go
@@ -63,7 +63,7 @@ func attributeViewDataPathByBox(avID, boxID string) string {
return filepath.Join(util.DataDir, "storage", "av", avID+".json")
}
-// findAttributeViewPath 按 fallback 逻辑查找 AV 定义文件的实际路径。
+// FindAttributeViewPath 按 fallback 逻辑查找 AV 定义文件的实际路径。
// 1. 先查 pendingAVBox(首次创建预设的 boxID)
// 2. 查全局 storage/av/(普通 box)
// 3. 遍历已打开的加密 box 查找
diff --git a/kernel/mcp/tools/file.go b/kernel/mcp/tools/file.go
index e52aeab95b..45e951b617 100644
--- a/kernel/mcp/tools/file.go
+++ b/kernel/mcp/tools/file.go
@@ -24,6 +24,7 @@ import (
"strings"
"github.com/88250/gulu"
+ "github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -156,6 +157,10 @@ func fileRead(args map[string]interface{}) (CallToolResult, error) {
if err != nil {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil
}
+ // 加密笔记本的文件不可通过 AI/MCP 读取
+ if model.IsEncryptedAssetPath(abs) {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "access denied: encrypted notebook files are not accessible to AI"}}, IsError: true}, nil
+ }
data, err := os.ReadFile(abs)
if err != nil {
return CallToolResult{Content: []ContentItem{{Type: "text", Text: "read file failed: " + err.Error()}}, IsError: true}, nil
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 65ba7f49e6..0e3c119fa6 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -909,6 +909,14 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
oldPath = oldPath[:idx]
}
+ // 加密笔记本的资源文件名已脱敏,重命名会破坏映射关系,禁止
+ if absPath, absErr := GetAssetAbsPath(oldPath); absErr == nil {
+ if IsEncryptedAssetPath(absPath) {
+ err = errors.New("renaming assets in encrypted notebooks is not supported")
+ return
+ }
+ }
+
newName = strings.TrimSpace(newName)
newName = util.FilterUploadFileName(newName)
if path.Base(oldPath) == newName {
@@ -971,6 +979,10 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
luteEngine := util.NewLute()
for _, notebook := range notebooks {
+ // 加密笔记本的资源重命名已在入口处拦截,这里跳过加密 box
+ if IsEncryptedBox(notebook.ID) {
+ continue
+ }
pages := pagedPaths(filepath.Join(util.DataDir, notebook.ID), 32)
for _, paths := range pages {
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 418f3711b1..8a9fdd6566 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -1638,8 +1638,11 @@ func insertItemAfter(items []string, item, previousItemID string) []string {
}
func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error) {
- storageAvDir := filepath.Join(util.DataDir, "storage", "av")
- oldAvPath := filepath.Join(storageAvDir, avID+".json")
+ // 加密 box 的 AV 定义在笔记本级目录,通过 fallback 查找实际路径
+ oldAvPath, avBoxID := av.FindAttributeViewPath(avID)
+ if oldAvPath == "" {
+ oldAvPath = av.GetAttributeViewDataPath(avID)
+ }
newAvID, newBlockID = ast.NewNodeID(), ast.NewNodeID()
oldAv, err := av.ParseAttributeView(avID)
@@ -1653,6 +1656,17 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error)
return
}
+ // 加密 box 的 AV 是密文,需先解密再处理
+ if avBoxID != "" {
+ if dek, decErr := GetDEK(avBoxID); decErr == nil && dek != nil {
+ if data, decErr = util.Decrypt(dek, data); decErr != nil {
+ logging.LogErrorf("decrypt attribute view [%s] failed: %s", avID, decErr)
+ err = decErr
+ return
+ }
+ }
+ }
+
data = bytes.ReplaceAll(data, []byte(avID), []byte(newAvID))
av.UpsertBlockRel(newAvID, newBlockID)
@@ -1680,7 +1694,19 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error)
return
}
- newAvPath := filepath.Join(storageAvDir, newAvID+".json")
+ // 加密 box 的新 AV 定义也存笔记本级目录,且需 DEK 加密
+ newAvPath := filepath.Join(util.DataDir, "storage", "av", newAvID+".json")
+ if avBoxID != "" {
+ newAvPath = filepath.Join(util.DataDir, avBoxID, "storage", "av", newAvID+".json")
+ if dek, decErr := GetDEK(avBoxID); decErr == nil && dek != nil {
+ if data, decErr = util.Encrypt(dek, data); decErr != nil {
+ logging.LogErrorf("encrypt attribute view [%s] failed: %s", newAvID, decErr)
+ err = decErr
+ return
+ }
+ }
+ av.SetAVBoxID(newAvID, avBoxID)
+ }
if err = filelock.WriteFile(newAvPath, data); err != nil {
logging.LogErrorf("write attribute view [%s] failed: %s", newAvID, err)
return
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index fd7c5cfad0..a5fe4b4d2e 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -44,7 +44,16 @@ func RefreshBacklink(id string) {
}
func refreshRefsByDefID(defID string) {
+ // 全局查 + 加密 box fallback
refs := sql.QueryRefsByDefID(defID, true)
+ if len(refs) == 0 {
+ for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if encRefs := sql.QueryRefsByDefIDInBox(defID, true, encBoxID); len(encRefs) > 0 {
+ refs = encRefs
+ break
+ }
+ }
+ }
var rootIDs []string
for _, ref := range refs {
rootIDs = append(rootIDs, ref.RootID)
diff --git a/kernel/model/heading.go b/kernel/model/heading.go
index 76fe617157..9b6c1047ef 100644
--- a/kernel/model/heading.go
+++ b/kernel/model/heading.go
@@ -177,6 +177,12 @@ func Doc2Heading(srcID, targetID string, after bool) (srcTreeBox, srcTreePath st
return
}
+ // 禁止跨加密边界:Doc2Heading 会合并 srcTree 和 targetTree 的内容
+ if IsEncryptedBox(srcTree.Box) != IsEncryptedBox(targetTree.Box) {
+ err = errors.New(Conf.Language(313))
+ return
+ }
+
pivot := treenode.GetNodeInTree(targetTree, targetID)
if nil == pivot {
err = ErrBlockNotFound
diff --git a/kernel/model/history.go b/kernel/model/history.go
index 5a5bc7c973..91a7e60db4 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -311,7 +311,16 @@ func RollbackDocHistory(historyPath string) (err error) {
avNodes := tree.Root.ChildrenByType(ast.NodeAttributeView)
for _, avNode := range avNodes {
srcAvPath := filepath.Join(historyDir, "storage", "av", avNode.AttributeViewID+".json")
+ // 加密 box 的 AV 定义在笔记本级目录
destAvPath := filepath.Join(util.DataDir, "storage", "av", avNode.AttributeViewID+".json")
+ if IsEncryptedBox(boxID) {
+ // 历史目录里 AV 也可能在 boxID 子目录下
+ boxSrcAvPath := filepath.Join(historyDir, boxID, "storage", "av", avNode.AttributeViewID+".json")
+ if gulu.File.IsExist(boxSrcAvPath) {
+ srcAvPath = boxSrcAvPath
+ }
+ destAvPath = filepath.Join(util.DataDir, boxID, "storage", "av", avNode.AttributeViewID+".json")
+ }
if gulu.File.IsExist(destAvPath) {
if copyErr := filelock.CopyNewtimes(srcAvPath, destAvPath); nil != copyErr {
logging.LogErrorf("copy av [%s] failed: %s", srcAvPath, copyErr)
@@ -465,7 +474,18 @@ func RollbackAssetsHistory(historyPath string) (err error) {
}
from := historyPath
+ // 从路径提取 boxID 判断是否加密 box 的资源
+ relPath := strings.TrimPrefix(filepath.ToSlash(historyPath), filepath.ToSlash(util.HistoryDir))
+ relPath = strings.TrimPrefix(relPath, "/")
+ pathParts := strings.SplitN(relPath, "/", 3)
to := filepath.Join(util.DataDir, "assets", filepath.Base(historyPath))
+ if len(pathParts) >= 2 && IsEncryptedBox(pathParts[1]) {
+ // 加密 box 的资源回滚到笔记本级 assets 目录
+ to = filepath.Join(util.DataDir, pathParts[1], "assets", filepath.Base(historyPath))
+ if err = os.MkdirAll(filepath.Dir(to), 0755); err != nil {
+ return
+ }
+ }
if err = filelock.CopyNewtimes(from, to); err != nil {
logging.LogErrorf("copy file [%s] to [%s] failed: %s", from, to, err)
@@ -504,7 +524,18 @@ func RollbackAttributeViewHistory(historyPath string) (err error) {
}
from := historyPath
+ // 从路径提取 boxID 判断是否加密 box 的 AV
+ relPath := strings.TrimPrefix(filepath.ToSlash(historyPath), filepath.ToSlash(util.HistoryDir))
+ relPath = strings.TrimPrefix(relPath, "/")
+ pathParts := strings.SplitN(relPath, "/", 3)
to := filepath.Join(util.DataDir, "storage", "av", filepath.Base(historyPath))
+ if len(pathParts) >= 2 && IsEncryptedBox(pathParts[1]) {
+ // 加密 box 的 AV 定义回滚到笔记本级目录
+ to = filepath.Join(util.DataDir, pathParts[1], "storage", "av", filepath.Base(historyPath))
+ if err = os.MkdirAll(filepath.Dir(to), 0755); err != nil {
+ return
+ }
+ }
if err = filelock.CopyNewtimes(from, to); err != nil {
logging.LogErrorf("copy file [%s] to [%s] failed: %s", from, to, err)
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 28cb04314d..eb734bcf2d 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -471,12 +471,14 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
// 加密笔记本的数据需先加密再落盘,导入的 .sy 原文是明文 JSON
if IsEncryptedBox(boxID) {
dek, decErr := GetDEK(boxID)
- if decErr == nil && dek != nil {
- data, decErr = util.Encrypt(dek, data)
- if decErr != nil {
- logging.LogErrorf("encrypt import .sy failed: %s", decErr)
- return
- }
+ if decErr != nil || dek == nil {
+ err = errors.New(Conf.Language(314))
+ return
+ }
+ data, decErr = util.Encrypt(dek, data)
+ if decErr != nil {
+ logging.LogErrorf("encrypt import .sy failed: %s", decErr)
+ return
}
}
if err = os.WriteFile(syPath, data, 0644); err != nil {
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 8d6c463447..6788d0b7da 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -367,6 +367,8 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
updated = file.Updated
if strings.HasSuffix(file.Path, ".sy") {
+ // 加密笔记本的 .sy 在仓库里是密文,按路径提取 boxID 解密
+ data = decryptRepoDataIfNeeded(data, file.Path)
luteEngine := NewLute()
var snapshotTree *parse.Tree
displayInText, snapshotTree, err = parseTreeInSnapshot(data, luteEngine)
diff --git a/kernel/model/sync.go b/kernel/model/sync.go
index 2ee97438f6..eb40bc9fc6 100644
--- a/kernel/model/sync.go
+++ b/kernel/model/sync.go
@@ -322,7 +322,7 @@ func removeIndexes(removeFilePaths []string) (removeRootIDs []string) {
cache.RemoveDocIAL(block.Path)
}
sql.RemoveTreeQueue(boxID, rootID)
- bts := treenode.GetBlockTreesByRootID(rootID)
+ bts := treenode.GetBlockTreesByRootIDInBox(rootID, boxID)
for _, b := range bts {
cache.RemoveBlockIAL(b.ID)
}
@@ -366,7 +366,7 @@ func upsertIndexes(upsertFilePaths []string) (upsertRootIDs []string) {
treenode.UpsertBlockTree(tree)
sql.UpsertTreeQueue(tree)
- bts := treenode.GetBlockTreesByRootID(rootID)
+ bts := treenode.GetBlockTreesByRootIDInBox(rootID, tree.Box)
for _, b := range bts {
cache.RemoveBlockIAL(b.ID)
}