Skip to content

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

:lock: Fix ImportSY .sy AAD path before rename, non-encrypted box asset fallback to global, html2BlockDOM box context, clippingSym tree.Box, GetAttributeViewName/IsAttributeViewExist box-aware routing, cloud sync AV cache invalidation for encrypted box paths, OCR fail-closed for encrypted assets, repo snapshot AV decryption, extractHistoryRelPath structural parsing https://github.com/siyuan-note/siyuan/issues/18034

Daniele1ca0491f114
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 766cb9d1f0..470c27b773 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -122,6 +122,14 @@ func getImageOCRText(c *gin.Context) {
path = arg["path"].(string)
+ // 加密笔记本的资源不参与全局 OCR(OCR 文本存在全局 data/assets/ocr-texts.json)
+ if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {
+ ret.Data = map[string]any{
+ "text": "",
+ }
+ return
+ }
+
ret.Data = map[string]any{
"text": util.GetAssetText(path),
}
@@ -138,6 +146,11 @@ func setImageOCRText(c *gin.Context) {
path := arg["path"].(string)
text := arg["text"].(string)
+
+ // 加密笔记本的资源不参与全局 OCR
+ if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {
+ return
+ }
util.SetAssetText(path, text)
// 刷新 OCR 结果到数据库
@@ -160,6 +173,14 @@ func ocr(c *gin.Context) {
path := arg["path"].(string)
+ // 加密笔记本的资源不参与全局 OCR
+ if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {
+ ret.Code = -1
+ ret.Msg = "OCR is not supported for assets in encrypted notebooks"
+ ret.Data = map[string]any{"closeTimeout": 3000}
+ return
+ }
+
ocrJSON, err := util.OcrAsset(path)
if nil != err {
ret.Code = -1
diff --git a/kernel/api/extension.go b/kernel/api/extension.go
index e74a0181a5..d6048f13a4 100644
--- a/kernel/api/extension.go
+++ b/kernel/api/extension.go
@@ -200,6 +200,7 @@ func extensionCopy(c *gin.Context) {
md = string(bodyData)
luteEngine.SetIndentCodeBlock(true) // 链滴支持缩进代码块,因此需要开启
tree := parse.Parse("", []byte(md), luteEngine.ParseOptions)
+ tree.Box = boxID
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if ast.NodeInlineMath == n.Type {
withMath = true
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 2bd7922166..add3ee8547 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -88,10 +88,17 @@ func html2BlockDOM(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("dom", &dom, true, false)) {
return
}
+ // 可选 notebook 参数:指定目标加密笔记本时资源写入 box 内并加密
+ boxID := ""
+ if notebook, ok := arg["notebook"].(string); ok && notebook != "" {
+ if model.IsEncryptedBox(notebook) {
+ boxID = notebook
+ }
+ }
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})
- tree, _ := model.HTML2Tree(dom, luteEngine, "")
+ tree, _ := model.HTML2Tree(dom, luteEngine, boxID)
if nil == tree {
ret.Data = "Failed to convert"
return
@@ -183,12 +190,19 @@ func html2BlockDOM(c *gin.Context) {
return ast.WalkStop
}
assetsDir := filepath.Join(util.DataDir, "assets")
- storedName, storeErr := model.StoreAssetForBox("", assetsDir, name, data)
+ if boxID != "" {
+ assetsDir = filepath.Join(util.DataDir, boxID, "assets")
+ }
+ storedName, storeErr := model.StoreAssetForBox(boxID, assetsDir, name, data)
if storeErr != nil {
logging.LogErrorf("store asset [%s] failed: %s", localPath, storeErr)
return ast.WalkStop
}
- n.Tokens = gulu.Str.ToBytes("assets/" + storedName)
+ assetURL := "assets/" + storedName
+ if boxID != "" {
+ assetURL += "?box=" + boxID
+ }
+ n.Tokens = gulu.Str.ToBytes(assetURL)
return ast.WalkContinue
})
}
diff --git a/kernel/av/av.go b/kernel/av/av.go
index 1c2ab85b8f..d3a0ab15d1 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -425,20 +425,34 @@ func NewAttributeView(id string) (ret *AttributeView) {
}
func GetAttributeViewName(avID string) (ret string, err error) {
- avJSONPath := GetAttributeViewDataPath(avID)
+ // 通过 fallback 查找 AV 定义的真实路径(普通 box 全局,加密笔记本笔记本级)
+ avJSONPath, boxID := FindAttributeViewPath(avID)
+ if avJSONPath == "" {
+ avJSONPath = GetAttributeViewDataPath(avID)
+ boxID = ""
+ }
if !filelock.IsExist(avJSONPath) {
return
}
- return GetAttributeViewNameByPath(avJSONPath)
+ return getAttributeViewNameByPathInBox(avJSONPath, boxID)
}
-func GetAttributeViewNameByPath(avJSONPath string) (ret string, err error) {
+func getAttributeViewNameByPathInBox(avJSONPath, boxID string) (ret string, err error) {
data, err := filelock.ReadFile(avJSONPath)
if err != nil {
logging.LogErrorf("read attribute view [%s] failed: %s", avJSONPath, err)
return
}
+ if boxID != "" {
+ avID := strings.TrimSuffix(filepath.Base(avJSONPath), filepath.Ext(avJSONPath))
+ plain, decErr := decryptAVData(boxID, avID, data)
+ if decErr != nil {
+ logging.LogErrorf("decrypt attribute view [%s] failed: %s", avJSONPath, decErr)
+ return "", decErr
+ }
+ data = plain
+ }
val := jsoniter.Get(data, "name")
if nil == val || val.ValueType() == jsoniter.InvalidValue {
@@ -448,6 +462,11 @@ func GetAttributeViewNameByPath(avJSONPath string) (ret string, err error) {
return
}
+// GetAttributeViewNameByPath 从指定路径读取 AV 名称(不加密,普通 box 兼容入口)。
+func GetAttributeViewNameByPath(avJSONPath string) (ret string, err error) {
+ return getAttributeViewNameByPathInBox(avJSONPath, "")
+}
+
func GetAttributeViewContent(avID string) (content string) {
if "" == avID {
return
@@ -495,7 +514,11 @@ func getAttributeViewContent0(attrView *AttributeView) (content string) {
}
func IsAttributeViewExist(avID string) bool {
- avJSONPath := GetAttributeViewDataPath(avID)
+ // 通过 fallback 查找(普通 box 全局,加密笔记本笔记本级)
+ avJSONPath, _ := FindAttributeViewPath(avID)
+ if avJSONPath == "" {
+ avJSONPath = GetAttributeViewDataPath(avID)
+ }
return filelock.IsExist(avJSONPath)
}
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index c34eb606f8..b3adbae9c0 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -707,6 +707,10 @@ func GetAssetAbsPathInBox(relativePath, boxID string) (string, error) {
}
return p, nil
}
+ // 非加密 box 的资源可能回退到全局 data/assets(兼容旧笔记本结构)
+ if !IsEncryptedBox(boxID) {
+ return GetAssetAbsPathWithOpt(relativePath, false)
+ }
return "", fmt.Errorf(Conf.Language(12), relativePath)
}
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 952610b00c..795261c366 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -456,6 +456,9 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
for _, tree := range trees {
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))
syPath := filepath.Join(unzipRootPath, tree.Path)
+ // 加密前确定最终文件名:tree.ID + ".sy",确保加密 AAD 用的是最终 box-relative path
+ finalSyName := tree.ID + ".sy"
+ finalRelPath := filepath.ToSlash(filepath.Join(filepath.Dir(tree.Path), finalSyName))
treenode.UpgradeSpec(tree)
renderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)
data := renderer.Render()
@@ -477,7 +480,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
return
}
var encErr error
- data, encErr = EncryptFile(boxID, tree.Path, dek, data)
+ data, encErr = EncryptFile(boxID, finalRelPath, dek, data)
if encErr != nil {
logging.LogErrorf("encrypt import .sy failed: %s", encErr)
return
@@ -487,11 +490,12 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
logging.LogErrorf("write .sy [%s] failed: %s", syPath, err)
return
}
- newSyPath := filepath.Join(filepath.Dir(syPath), tree.ID+".sy")
+ 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)
return
}
+ tree.Path = finalRelPath
}
// 合并 sort.json
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 03a7ed6f25..840e686ecb 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -56,6 +56,7 @@ import (
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/httpclient"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/sql"
@@ -337,7 +338,7 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {
return
}
- if strings.HasPrefix(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
+ if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
avID := strings.TrimSuffix(filepath.Base(file.Path), ".json")
cache.RemoveAVData(avID)
ReloadAttrView(avID)
@@ -425,6 +426,29 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
} else {
displayInText = true
title = file.Path
+ // 加密 notebook 的 AV 定义在仓库里是密文,需先解密再展示
+ if strings.Contains(file.Path, "storage/av/") && strings.HasSuffix(file.Path, ".json") {
+ repoBoxID := ""
+ origPath := strings.TrimPrefix(file.Path, "/")
+ if parts := strings.SplitN(origPath, "/", 2); len(parts) >= 1 && ast.IsNodeIDPattern(parts[0]) {
+ repoBoxID = parts[0]
+ }
+ if repoBoxID != "" && IsEncryptedBox(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 {
+ data = plainData
+ } else {
+ logging.LogWarnf("decrypt repo snapshot AV [%s] failed: %s", file.Path, decErr)
+ content = file.Path
+ return
+ }
+ } else {
+ content = file.Path
+ return
+ }
+ }
+ }
if mimeType := mime.TypeByExtension(filepath.Ext(file.Path)); strings.HasPrefix(mimeType, "text/") || strings.Contains(mimeType, "json") {
// 如果是文本文件,直接返回文本内容
// All plain text formats are supported when comparing data snapshots https://github.com/siyuan-note/siyuan/issues/12975
@@ -2062,7 +2086,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
needReloadSnippet = true
}
- if strings.HasPrefix(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
+ if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
cache.RemoveAVData(strings.TrimSuffix(filepath.Base(file.Path), ".json"))
}
}
@@ -2122,7 +2146,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
needReloadSnippet = true
}
- if strings.HasPrefix(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
+ if strings.Contains(file.Path, "/storage/av/") && strings.HasSuffix(file.Path, ".json") {
cache.RemoveAVData(strings.TrimSuffix(filepath.Base(file.Path), ".json"))
}
}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 30c0e4556d..12eec0a9a5 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -895,12 +895,18 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
// history 路径格式:<historyDir>/<datePrefix>/<boxID>/<relativePath>。
func extractHistoryRelPath(absPath, boxID string) string {
absPath = filepath.ToSlash(absPath)
- idx := strings.Index(absPath, "/"+boxID+"/")
- if idx < 0 {
+ historyDir := filepath.ToSlash(util.HistoryDir)
+ rel, err := filepath.Rel(historyDir, absPath)
+ if err != nil {
+ return ""
+ }
+ rel = filepath.ToSlash(rel)
+ // rel 格式:<datePrefix>/<boxID>/<relativePath>
+ parts := strings.SplitN(rel, "/", 3)
+ if len(parts) < 3 || parts[1] != boxID {
return ""
}
- rel := absPath[idx+len("/"+boxID+"/"):]
- return rel
+ return parts[2]
}
func serveThumbnail(context *gin.Context, assetAbsPath, requestPath string) bool {