Skip to content

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

:lock: Add unified asset write entry storeAssetForBox to prevent plaintext leaks in import/HTML conversion, add box-aware asset resolution with GetAssetAbsPathInBox and ?box= URL parameter, bind AAD to object identity (file path/asset disk name/AV id) instead of only boxID, skip encrypted assets in file watcher to prevent ciphertext indexing, add per-box mutex for .names.json concurrent writes, harden /assets route with path traversal rejection https://github.com/siyuan-note/siyuan/issues/18034

Daniel00da47a80a57
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index d8f4be10d0..efdb5680dc 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -290,7 +290,7 @@ func setFileAnnotation(c *gin.Context) {
ret.Msg = dekErr.Error()
return
}
- enc, encErr := model.EncryptAsset(boxID, dek, writeData)
+ enc, encErr := model.EncryptAsset(boxID, filepath.Base(writePath), dek, writeData)
if encErr != nil {
ret.Code = -1
ret.Msg = encErr.Error()
@@ -345,7 +345,7 @@ func getFileAnnotation(c *gin.Context) {
ret.Msg = dekErr.Error()
return
}
- plain, decErr := model.DecryptAsset(boxID, dek, data)
+ plain, decErr := model.DecryptAsset(boxID, filepath.Base(readPath), dek, data)
if decErr != nil {
ret.Code = -1
ret.Msg = decErr.Error()
diff --git a/kernel/api/extension.go b/kernel/api/extension.go
index ed6ce540c2..ac8ca42d31 100644
--- a/kernel/api/extension.go
+++ b/kernel/api/extension.go
@@ -234,7 +234,7 @@ func extensionCopy(c *gin.Context) {
return s
})
- tree, withMath = model.HTML2Tree(dom, luteEngine)
+ tree, withMath = model.HTML2Tree(dom, luteEngine, "")
} else {
tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)
}
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index d4ae9c7de5..28fedf8cdf 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -91,7 +91,7 @@ func html2BlockDOM(c *gin.Context) {
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})
- tree, _ := model.HTML2Tree(dom, luteEngine)
+ tree, _ := model.HTML2Tree(dom, luteEngine, "")
if nil == tree {
ret.Data = "Failed to convert"
return
diff --git a/kernel/av/av.go b/kernel/av/av.go
index 9bc1088400..5e9b1ff076 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -530,8 +530,8 @@ func ParseAttributeViewByPath(avJSONPath string) (ret *AttributeView, err error)
return
}
// 加密笔记本的 AV 定义是密文,按路径反查 boxID 后解密
- if boxID := avBoxIDFromPath(avJSONPath); boxID != "" {
- data, readErr = decryptAVData(boxID, data)
+ if boxID := avBoxIDFromPath(avJSONPath); boxID != "" {
+ data, readErr = decryptAVData(boxID, avID, data)
if readErr != nil {
logging.LogErrorf("decrypt attribute view [%s] failed: %s", avID, readErr)
return
@@ -681,7 +681,7 @@ func SaveAttributeView(av *AttributeView) (err error) {
if diskData, readErr := filelock.ReadFile(avJSONPath); nil == readErr {
// 加密笔记本的磁盘数据是密文,需先解密再比对
if avBoxID != "" {
- diskData, _ = decryptAVData(avBoxID, diskData)
+ diskData, _ = decryptAVData(avBoxID, av.ID, diskData)
}
if len(diskData) == len(data) && bytes.Equal(diskData, data) {
cache.SetAVData(av.ID, data)
@@ -692,8 +692,8 @@ func SaveAttributeView(av *AttributeView) (err error) {
// 加密笔记本的数据需加密后再写盘
writeData := data
- if avBoxID != "" {
- writeData, err = encryptAVData(avBoxID, data)
+ if avBoxID != "" {
+ writeData, err = encryptAVData(avBoxID, av.ID, data)
if err != nil {
logging.LogErrorf("encrypt attribute view [%s] failed: %s", av.ID, err)
return
diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.go
index e2483d0bef..e3631deba6 100644
--- a/kernel/av/encrypted_hook.go
+++ b/kernel/av/encrypted_hook.go
@@ -103,7 +103,7 @@ func readAttributeViewData(avID string) ([]byte, error) {
}
// 加密笔记本的数据需解密
if boxID != "" {
- data, err = decryptAVData(boxID, data)
+ data, err = decryptAVData(boxID, avID, data)
if err != nil {
return nil, err
}
@@ -129,7 +129,7 @@ func writeAttributeViewData(avID, boxID string, data []byte) error {
// 加密笔记本的数据需加密
if boxID != "" {
var err error
- data, err = encryptAVData(boxID, data)
+ data, err = encryptAVData(boxID, avID, data)
if err != nil {
return err
}
@@ -168,9 +168,9 @@ func readMirrorBlocks(boxID string) (ret map[string][]string) {
logging.LogErrorf("read attribute view blocks failed: %s", err)
return
}
- if boxID != "" {
- // 加密笔记本的镜像索引是密文,解密后再反序列化
- dec, decErr := decryptAVData(boxID, data)
+ if boxID != "" {
+ // 加密笔记本的镜像索引是密文,解密后再反序列化
+ dec, decErr := decryptAVData(boxID, "mirror", data)
if decErr != nil {
logging.LogErrorf("decrypt attribute view blocks failed: %s", decErr)
return
@@ -195,9 +195,9 @@ func writeMirrorBlocks(boxID string, data map[string][]string) error {
if err != nil {
return err
}
- if boxID != "" {
- // 加密笔记本的镜像索引写入前加密
- enc, encErr := encryptAVData(boxID, raw)
+ if boxID != "" {
+ // 加密笔记本的镜像索引写入前加密
+ enc, encErr := encryptAVData(boxID, "mirror", raw)
if encErr != nil {
return encErr
}
@@ -226,7 +226,7 @@ func avBoxIDFromPath(absPath string) string {
return boxID
}
-func encryptAVData(boxID string, data []byte) ([]byte, error) {
+func encryptAVData(boxID, avID string, data []byte) ([]byte, error) {
if AVDEKProvider == nil {
return data, nil
}
@@ -238,10 +238,11 @@ func encryptAVData(boxID string, data []byte) ([]byte, error) {
return data, nil // 非加密 box
}
avKey := util.DeriveSubKey(dek, "siyuan/av")
- return util.EncryptWithAAD(avKey, data, []byte(boxID))
+ aad := "siyuan:v1:av:" + boxID + ":" + avID
+ return util.EncryptWithAAD(avKey, data, []byte(aad))
}
-func decryptAVData(boxID string, data []byte) ([]byte, error) {
+func decryptAVData(boxID, avID string, data []byte) ([]byte, error) {
if AVDEKProvider == nil {
return data, nil
}
@@ -253,15 +254,16 @@ func decryptAVData(boxID string, data []byte) ([]byte, error) {
return data, nil // 非加密 box
}
avKey := util.DeriveSubKey(dek, "siyuan/av")
- return util.DecryptWithAAD(avKey, data, []byte(boxID))
+ aad := "siyuan:v1:av:" + boxID + ":" + avID
+ return util.DecryptWithAAD(avKey, data, []byte(aad))
}
// EncryptAVData 是 encryptAVData 的导出版本,供 model 层(导入/复制数据库等)统一加密 AV 定义。
-func EncryptAVData(boxID string, data []byte) ([]byte, error) {
- return encryptAVData(boxID, data)
+func EncryptAVData(boxID, avID string, data []byte) ([]byte, error) {
+ return encryptAVData(boxID, avID, data)
}
// DecryptAVData 是 decryptAVData 的导出版本。
-func DecryptAVData(boxID string, data []byte) ([]byte, error) {
- return decryptAVData(boxID, data)
+func DecryptAVData(boxID, avID string, data []byte) ([]byte, error) {
+ return decryptAVData(boxID, avID, data)
}
diff --git a/kernel/av/relation.go b/kernel/av/relation.go
index 3d8719ab36..2ac37ab448 100644
--- a/kernel/av/relation.go
+++ b/kernel/av/relation.go
@@ -39,7 +39,7 @@ func readRelations(boxID string) (avRels map[string][]string) {
return
}
if boxID != "" {
- dec, decErr := decryptAVData(boxID, data)
+ dec, decErr := decryptAVData(boxID, "relation", data)
if decErr != nil {
logging.LogErrorf("decrypt attribute view relations failed: %s", decErr)
return
@@ -66,7 +66,7 @@ func writeRelations(boxID string, avRels map[string][]string) {
return
}
if boxID != "" {
- enc, encErr := encryptAVData(boxID, data)
+ enc, encErr := encryptAVData(boxID, "relation", data)
if encErr != nil {
logging.LogErrorf("encrypt attribute view relations failed: %s", encErr)
return
diff --git a/kernel/filesys/crypto_hook.go b/kernel/filesys/crypto_hook.go
index bd26f5c457..a3fcf78521 100644
--- a/kernel/filesys/crypto_hook.go
+++ b/kernel/filesys/crypto_hook.go
@@ -30,9 +30,9 @@ import (
// filesys 不能直接 import model(会形成 model → filesys → model 循环依赖),故采用回调注入。
var DEKProvider func(boxID string) ([]byte, error)
-// encryptData 若 boxID 是已解锁的加密 box,用 fileKey(DEK 派生子密钥)加密 data 并绑定 boxID 为 AAD;
-// 非加密笔记本原样返回;加密但未解锁时返回 error,拒绝写盘(防止明文泄漏)。
-func encryptData(boxID string, data []byte) ([]byte, error) {
+// encryptData 若 boxID 是已解锁的加密 box,用 fileKey(DEK 派生子密钥)加密 data,
+// AAD 绑定 boxID + 相对路径;非加密笔记本原样返回;加密但未解锁时返回 error,拒绝写盘(防止明文泄漏)。
+func encryptData(boxID, relativePath string, data []byte) ([]byte, error) {
if DEKProvider == nil {
return data, nil
}
@@ -44,11 +44,12 @@ func encryptData(boxID string, data []byte) ([]byte, error) {
return data, nil // 非加密 box
}
fileKey := util.DeriveSubKey(dek, "siyuan/file")
- return util.EncryptWithAAD(fileKey, data, []byte(boxID))
+ aad := "siyuan:v1:file:" + boxID + ":" + relativePath
+ return util.EncryptWithAAD(fileKey, data, []byte(aad))
}
// decryptData 对应解密。非加密笔记本原样返回;加密但未解锁时返回 error,拒绝读盘。
-func decryptData(boxID string, data []byte) ([]byte, error) {
+func decryptData(boxID, relativePath string, data []byte) ([]byte, error) {
if DEKProvider == nil {
return data, nil
}
@@ -60,7 +61,8 @@ func decryptData(boxID string, data []byte) ([]byte, error) {
return data, nil // 非加密 box
}
fileKey := util.DeriveSubKey(dek, "siyuan/file")
- return util.DecryptWithAAD(fileKey, data, []byte(boxID))
+ aad := "siyuan:v1:file:" + boxID + ":" + relativePath
+ return util.DecryptWithAAD(fileKey, data, []byte(aad))
}
// docIALBoxID 从 .sy 绝对路径反推 boxID,供 DocIAL 判断是否需整体解密。
diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.go
index 62aaee29ca..f3a7a55f0a 100644
--- a/kernel/filesys/tree.go
+++ b/kernel/filesys/tree.go
@@ -158,7 +158,7 @@ func LoadTreeWithFix(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, n
}
// 加密笔记本的 .sy 是密文,读盘后解密成明文供后续解析;非加密笔记本原样返回
- if data, err = decryptData(boxID, data); nil != err {
+ if data, err = decryptData(boxID, p, data); nil != err {
logging.LogErrorf("decrypt tree [%s] failed: %s", p, err)
return
}
@@ -257,7 +257,8 @@ func DocIAL(absPath string) (ret map[string]string) {
logging.LogErrorf("read file [%s] failed: %s", absPath, readErr)
return nil
}
- plain, decErr := decryptData(boxID, raw)
+ relPath := filepath.ToSlash(strings.TrimPrefix(absPath, filepath.Join(util.DataDir, boxID)+string(os.PathSeparator)))
+ plain, decErr := decryptData(boxID, relPath, raw)
if decErr != nil {
// 解密失败(可能文件损坏或密钥不匹配):返回空 map 而非 nil,
// 避免 LoadTreeByData 的父文档补全逻辑把 nil 误判为"文档缺失"而凭空创建文档
@@ -319,7 +320,7 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {
}
// 加密笔记本的落盘内容用密文 encData,缓存与比对仍用明文 data(缓存存明文)
- encData, encErr := encryptData(tree.Box, data)
+ encData, encErr := encryptData(tree.Box, tree.Path, data)
if encErr != nil {
err = encErr
return
@@ -333,7 +334,7 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {
} else {
// 读盘比对:加密笔记本的磁盘数据是密文,需先解密成明文再与 data 比对
if diskData, readErr := filelock.ReadFile(filePath); nil == readErr {
- decDisk, decErr := decryptData(tree.Box, diskData)
+ decDisk, decErr := decryptData(tree.Box, tree.Path, diskData)
if decErr == nil && len(decDisk) == len(data) && bytes.Equal(decDisk, data) {
cache.SetTreeData(tree.ID, data)
return
@@ -515,7 +516,7 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (d
return
}
// 订正后的 data 是明文,加密笔记本落盘前需加密
- encData, encErr := encryptData(ret.Box, data)
+ encData, encErr := encryptData(ret.Box, ret.Path, data)
if encErr != nil {
err = encErr
return
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 0aea71ea79..7d3817d6d4 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -69,6 +69,32 @@ func GetAssetImgSize(assetPath string) (width, height int) {
return
}
+// ReadAssetBytesInBox 读取指定 box 内的资源文件字节。若 box 为加密笔记本则自动解密返回明文。
+// relativePath 形如 "assets/xxx.png"。
+func ReadAssetBytesInBox(boxID, relativePath string) ([]byte, error) {
+ absPath, err := GetAssetAbsPathInBox(relativePath, boxID)
+ if err != nil {
+ return nil, err
+ }
+ data, readErr := os.ReadFile(absPath)
+ if readErr != nil {
+ return nil, readErr
+ }
+ if IsEncryptedBox(boxID) {
+ dek, dekErr := GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ return nil, dekErr
+ }
+ diskName := filepath.Base(relativePath)
+ plain, decErr := DecryptAsset(boxID, diskName, dek, data)
+ if decErr != nil {
+ return nil, decErr
+ }
+ return plain, nil
+ }
+ return data, nil
+}
+
// GetAssetPathByHash 按 hash 查已存在的 asset 路径用于去重。boxID 非空且为加密笔记本时返回空——
// 加密笔记本不参与全局去重(避免复用普通明文 asset);普通 box 走全局 cache/SQL(加密笔记本数据不在全局表)。
func GetAssetPathByHash(hash, boxID string) string {
@@ -105,6 +131,12 @@ func HandleAssetsRemoveEvent(assetAbsPath string) {
return
}
+ // 加密笔记本的 asset 是密文,跳过全局索引和 hash 缓存操作
+ if IsEncryptedAssetPath(assetAbsPath) {
+ removeAssetThumbnail(assetAbsPath)
+ return
+ }
+
removeIndexAssetContent(assetAbsPath)
removeAssetThumbnail(assetAbsPath)
@@ -133,6 +165,12 @@ func HandleAssetsChangeEvent(assetAbsPath string) {
return
}
+ // 加密笔记本的 asset 是密文,跳过全局内容索引和 hash 缓存(避免密文污染搜索索引)
+ if IsEncryptedAssetPath(assetAbsPath) {
+ removeAssetThumbnail(assetAbsPath)
+ return
+ }
+
indexAssetContent(assetAbsPath)
removeAssetThumbnail(assetAbsPath)
@@ -594,6 +632,30 @@ func GetAssetAbsPath(relativePath string) (string, error) {
return GetAssetAbsPathWithOpt(relativePath, false)
}
+// GetAssetAbsPathInBox 在指定 box 内解析资源绝对路径,不进行全局遍历。
+// boxID 为空时退化为全局搜索 GetAssetAbsPathWithOpt(..., true)。
+// 加密 box 直接从 <boxID>/assets/ 查找,不依赖后缀匹配。
+func GetAssetAbsPathInBox(relativePath, boxID string) (string, error) {
+ relativePath = strings.TrimSpace(relativePath)
+ if idx := strings.Index(relativePath, "?"); idx >= 0 {
+ relativePath = relativePath[:idx]
+ }
+ relativePath = filepath.ToSlash(relativePath)
+
+ if boxID == "" {
+ return GetAssetAbsPathWithOpt(relativePath, true)
+ }
+
+ p := filepath.Join(util.DataDir, boxID, relativePath)
+ if gulu.File.IsExist(p) {
+ if !gulu.File.IsSubPath(util.WorkspaceDir, p) {
+ return "", fmt.Errorf("[%s] is not sub path of workspace", p)
+ }
+ return p, nil
+ }
+ return "", fmt.Errorf(Conf.Language(12), relativePath)
+}
+
// GetAssetAbsPathWithOpt 与 GetAssetAbsPath 一致,但可通过 includeEncrypted 控制是否遍历加密 box。
// serveAssets 传 true(下游 serveEncryptedAsset 会按锁定状态 fail-closed),其他调用方传 false(安全跳过)。
func GetAssetAbsPathWithOpt(relativePath string, includeEncrypted bool) (string, error) {
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index c7488335da..774e72da0c 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -1656,9 +1656,9 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error)
}
// 加密笔记本的 AV 是密文,需先解密再处理(av.DecryptAVData 内部按 box 加密/已解锁路由)
- if avBoxID != "" && IsEncryptedBox(avBoxID) {
- var decErr error
- data, decErr = av.DecryptAVData(avBoxID, data)
+ if avBoxID != "" && IsEncryptedBox(avBoxID) {
+ var decErr error
+ data, decErr = av.DecryptAVData(avBoxID, avID, data)
if decErr != nil {
logging.LogErrorf("decrypt attribute view [%s] failed: %s", avID, decErr)
err = decErr
@@ -1695,10 +1695,10 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error)
// 加密笔记本的新 AV 定义也存笔记本级目录,且需 avKey 加密
newAvPath := filepath.Join(util.DataDir, "storage", "av", newAvID+".json")
- if avBoxID != "" {
- newAvPath = filepath.Join(util.DataDir, avBoxID, "storage", "av", newAvID+".json")
- var encErr error
- data, encErr = av.EncryptAVData(avBoxID, data)
+ if avBoxID != "" {
+ newAvPath = filepath.Join(util.DataDir, avBoxID, "storage", "av", newAvID+".json")
+ var encErr error
+ data, encErr = av.EncryptAVData(avBoxID, newAvID, data)
if encErr != nil {
logging.LogErrorf("encrypt attribute view [%s] failed: %s", newAvID, encErr)
err = encErr
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index de890cb885..2c573ee826 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -594,8 +594,8 @@ func RenderRepoSnapshotAttributeView(indexID, avID string) (viewable av.Viewable
}
// 加密笔记本的 AV 在快照中是密文,按路径反查 boxID 后解密
- if histBoxID := avBoxIDFromRepoPath(avFile.Path); histBoxID != "" && IsEncryptedBox(histBoxID) {
- dec, decErr := av.DecryptAVData(histBoxID, data)
+ if histBoxID := avBoxIDFromRepoPath(avFile.Path); histBoxID != "" && IsEncryptedBox(histBoxID) {
+ dec, decErr := av.DecryptAVData(histBoxID, avID, data)
if decErr != nil {
logging.LogErrorf("decrypt snapshot attribute view [%s] failed: %s", avID, decErr)
err = decErr
@@ -698,7 +698,7 @@ func RenderHistoryAttributeView(blockID, avID, viewID, query string, page, pageS
}
}
if histBoxID != "" && IsEncryptedBox(histBoxID) {
- data, err = av.DecryptAVData(histBoxID, data)
+ data, err = av.DecryptAVData(histBoxID, avID, data)
if err != nil {
logging.LogErrorf("decrypt history AV [%s] failed: %s", avID, err)
return
@@ -706,7 +706,7 @@ func RenderHistoryAttributeView(blockID, avID, viewID, query string, page, pageS
} else {
// 路径没提取到 boxID(如历史目录无 boxID 前缀的旧路径),尝试遍历已打开的加密笔记本解密
for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
- if dec, decErr := av.DecryptAVData(encBoxID, data); decErr == nil {
+ if dec, decErr := av.DecryptAVData(encBoxID, avID, data); decErr == nil {
data = dec
break
}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index ffbc0c6580..06d818108e 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -1165,30 +1165,34 @@ func ExtractBoxIDFromHistoryPath(absPath string) string {
// copyAssetDecryptIfEncrypted 把 srcPath 的 asset 复制到 destPath。
// 若 srcPath 在已解锁的加密笔记本下,读密文→解密→写明文到 destPath(导出目录);
// 否则走 filelock.Copy 原路径(字节级复制,密文/明文均可)。
-// EncryptFile 用 fileKey(DEK 派生子密钥)加密 .sy 文档字节,AAD 绑定 boxID。
-// 与 filesys.encryptData/decryptData 使用相同的 AAD(boxID 级),保证读写一致。
-func EncryptFile(boxID string, dek, plaintext []byte) ([]byte, error) {
+// EncryptFile 用 fileKey(DEK 派生子密钥)加密 .sy 文档字节,AAD 绑定 boxID + 相对路径。
+// relativePath 形如 "/20240101000000-abc123.sy",与 filesys.encryptData/decryptData 保持一致。
+func EncryptFile(boxID, relativePath string, dek, plaintext []byte) ([]byte, error) {
fileKey := util.DeriveSubKey(dek, "siyuan/file")
- return util.EncryptWithAAD(fileKey, plaintext, []byte(boxID))
+ aad := "siyuan:v1:file:" + boxID + ":" + relativePath
+ return util.EncryptWithAAD(fileKey, plaintext, []byte(aad))
}
// DecryptFile 对应解密。
-func DecryptFile(boxID string, dek, ciphertext []byte) ([]byte, error) {
+func DecryptFile(boxID, relativePath string, dek, ciphertext []byte) ([]byte, error) {
fileKey := util.DeriveSubKey(dek, "siyuan/file")
- return util.DecryptWithAAD(fileKey, ciphertext, []byte(boxID))
+ aad := "siyuan:v1:file:" + boxID + ":" + relativePath
+ return util.DecryptWithAAD(fileKey, ciphertext, []byte(aad))
}
-// EncryptAsset 用 assetKey(DEK 派生子密钥)加密 asset 字节,AAD 绑定 boxID。
-// 供 assets/.names.json/.sya 等资源类数据统一加密,与 .sy(fileKey)和 AV(avKey)用途分离。
-func EncryptAsset(boxID string, dek, plaintext []byte) ([]byte, error) {
+// EncryptAsset 用 assetKey(DEK 派生子密钥)加密 asset 字节,AAD 绑定 boxID + 磁盘文件名。
+// diskName 为磁盘上的脱敏文件名(加密 box)或原始文件名(普通 box)。
+func EncryptAsset(boxID, diskName string, dek, plaintext []byte) ([]byte, error) {
assetKey := util.DeriveSubKey(dek, "siyuan/asset")
- return util.EncryptWithAAD(assetKey, plaintext, []byte(boxID))
+ aad := "siyuan:v1:asset:" + boxID + ":assets/" + diskName
+ return util.EncryptWithAAD(assetKey, plaintext, []byte(aad))
}
// DecryptAsset 对应解密。
-func DecryptAsset(boxID string, dek, ciphertext []byte) ([]byte, error) {
+func DecryptAsset(boxID, diskName string, dek, ciphertext []byte) ([]byte, error) {
assetKey := util.DeriveSubKey(dek, "siyuan/asset")
- return util.DecryptWithAAD(assetKey, ciphertext, []byte(boxID))
+ aad := "siyuan:v1:asset:" + boxID + ":assets/" + diskName
+ return util.DecryptWithAAD(assetKey, ciphertext, []byte(aad))
}
// notebookCryptBackupPath 返回加密笔记本的独立 BoxCrypt 备份路径。
@@ -1255,7 +1259,8 @@ func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {
if readErr != nil {
return readErr
}
- plain, decErr := DecryptAsset(boxID, dek, raw)
+ diskName := filepath.Base(srcPath)
+ plain, decErr := DecryptAsset(boxID, diskName, dek, raw)
if decErr != nil {
return errors.New(Conf.Language(316))
}
diff --git a/kernel/model/history.go b/kernel/model/history.go
index 1f6a920d56..64f676550b 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -192,7 +192,12 @@ func GetDocHistoryContent(historyPath, keyword string, highlight bool) (id, root
return
}
var decErr error
- data, decErr = DecryptFile(histBoxID, dek, data)
+ // 历史路径格式:<historyDir>/<datePrefix>/<boxID>/<relativePath>
+ filePath := ""
+ if len(pathParts) >= 3 {
+ filePath = pathParts[2]
+ }
+ data, decErr = DecryptFile(histBoxID, filePath, dek, data)
if decErr != nil {
logging.LogErrorf("decrypt history [%s] failed: %s", historyPath, decErr)
err = decErr
@@ -314,7 +319,9 @@ func RollbackDocHistory(historyPath string) (err error) {
return
}
var decErr error
- srcData, decErr = DecryptFile(boxID, dek, srcData)
+ // 历史路径格式:<historyDir>/<datePrefix>/<boxID>/<relativePath>
+ filePath := parts[2]
+ srcData, decErr = DecryptFile(boxID, filePath, dek, srcData)
if decErr != nil {
logging.LogErrorf("decrypt history [%s] failed: %s", srcPath, decErr)
err = decErr
diff --git a/kernel/model/import.go b/kernel/model/import.go
index e2b6662408..7fce1ba6c8 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -56,9 +56,13 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-func HTML2Tree(htmlStr string, luteEngine *lute.Lute) (tree *parse.Tree, withMath bool) {
+func HTML2Tree(htmlStr string, luteEngine *lute.Lute, boxID string) (tree *parse.Tree, withMath bool) {
htmlStr = gulu.Str.RemovePUA(htmlStr)
assetDirPath := filepath.Join(util.DataDir, "assets")
+ if boxID != "" {
+ assetDirPath = filepath.Join(util.DataDir, boxID, "assets")
+ _ = os.MkdirAll(assetDirPath, 0755)
+ }
tree = luteEngine.HTML2Tree(htmlStr)
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
@@ -85,7 +89,7 @@ func HTML2Tree(htmlStr string, luteEngine *lute.Lute) (tree *parse.Tree, withMat
}
}
} else if bytes.Contains(n.Tokens, []byte("<svg")) {
- processHTMLBlockSvgImg(n, assetDirPath)
+ processHTMLBlockSvgImg(n, assetDirPath, boxID)
}
}
case ast.NodeText:
@@ -99,7 +103,7 @@ func HTML2Tree(htmlStr string, luteEngine *lute.Lute) (tree *parse.Tree, withMat
case ast.NodeLinkDest:
dest := n.TokensStr()
if strings.HasPrefix(dest, "data:image") && strings.Contains(dest, ";base64,") {
- processBase64Img(n, dest, assetDirPath)
+ processBase64Img(n, dest, assetDirPath, boxID)
}
}
return ast.WalkContinue
@@ -413,8 +417,9 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
if readErr != nil {
return readErr
}
+ avID := strings.TrimSuffix(d.Name(), ".json")
// av.EncryptAVData 内部按 box 是否加密/已解锁路由,加密笔记本用 avKey+AAD
- enc, encErr := av.EncryptAVData(boxID, src)
+ enc, encErr := av.EncryptAVData(boxID, avID, src)
if encErr != nil {
return encErr
}
@@ -472,7 +477,7 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
return
}
var encErr error
- data, encErr = EncryptFile(boxID, dek, data)
+ data, encErr = EncryptFile(boxID, tree.Path, dek, data)
if encErr != nil {
logging.LogErrorf("encrypt import .sy failed: %s", encErr)
return
@@ -987,12 +992,21 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {
existName := assetsDone[currentPath]
var name string
if "" == existName {
- name = filepath.Base(currentPath)
- name = util.FilterUploadFileName(name)
- name = util.AssetName(name, ast.NewNodeID())
- assetTargetPath := filepath.Join(util.DataDir, "assets", name)
- if err = filelock.Copy(currentPath, assetTargetPath); err != nil {
- logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", currentPath, assetTargetPath, err)
+ baseName := filepath.Base(currentPath)
+ baseName = util.FilterUploadFileName(baseName)
+ data, readErr := os.ReadFile(currentPath)
+ if readErr != nil {
+ logging.LogErrorf("read asset [%s] failed: %s", currentPath, readErr)
+ return nil
+ }
+ assetDirForBox := filepath.Join(util.DataDir, "assets")
+ if boxID != "" {
+ assetDirForBox = filepath.Join(util.DataDir, boxID, "assets")
+ _ = os.MkdirAll(assetDirForBox, 0755)
+ }
+ name, err = storeAssetForBox(boxID, assetDirForBox, baseName, data)
+ if err != nil {
+ logging.LogErrorf("store asset [%s] for box [%s] failed: %s", currentPath, boxID, err)
return nil
}
assetsDone[currentPath] = name
@@ -1112,7 +1126,7 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {
}
if strings.HasPrefix(dest, "data:image") && strings.Contains(dest, ";base64,") {
- processBase64Img(n, dest, assetDirPath)
+ processBase64Img(n, dest, assetDirPath, boxID)
return ast.WalkContinue
}
@@ -1184,9 +1198,17 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {
name = existName
}
if ast.NodeLinkDest == n.Type {
- n.Tokens = []byte("assets/" + name)
+ assetURL := "assets/" + name
+ if IsEncryptedBox(boxID) {
+ assetURL += "?box=" + boxID
+ }
+ n.Tokens = []byte(assetURL)
} else {
- n.TextMarkAHref = "assets/" + name
+ assetURL := "assets/" + name
+ if IsEncryptedBox(boxID) {
+ assetURL += "?box=" + boxID
+ }
+ n.TextMarkAHref = assetURL
}
return ast.WalkContinue
})
@@ -1265,7 +1287,7 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {
}
if strings.HasPrefix(dest, "data:image") && strings.Contains(dest, ";base64,") {
- processBase64Img(n, dest, assetDirPath)
+ processBase64Img(n, dest, assetDirPath, boxID)
return ast.WalkContinue
}
@@ -1298,22 +1320,48 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {
existName := assetsDone[absolutePath]
var name string
if "" == existName {
- name = filepath.Base(absolutePath)
- name = util.FilterUploadFileName(name)
- name = util.AssetName(name, ast.NewNodeID())
- assetTargetPath := filepath.Join(assetDirPath, name)
- if err = filelock.Copy(absolutePath, assetTargetPath); err != nil {
- logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", absolutePath, assetTargetPath, err)
- return ast.WalkContinue
+ baseName := filepath.Base(absolutePath)
+ if IsEncryptedBox(boxID) {
+ // 加密笔记本:文件名脱敏 + 内容加密
+ ext := filepath.Ext(baseName)
+ blockID := ast.NewNodeID()
+ name = encryptedAssetName(ext, blockID)
+ writeAssetNameMapping(boxID, name, baseName)
+ assetTargetPath := filepath.Join(assetDirPath, name)
+ src, readErr := filelock.ReadFile(absolutePath)
+ if readErr != nil {
+ logging.LogErrorf("read asset [%s] failed: %s", absolutePath, readErr)
+ return ast.WalkContinue
+ }
+ if err = writeAssetFile(assetTargetPath, bytes.NewReader(src), boxID); err != nil {
+ logging.LogErrorf("write encrypted asset [%s] failed: %s", assetTargetPath, err)
+ return ast.WalkContinue
+ }
+ } else {
+ name = util.FilterUploadFileName(baseName)
+ name = util.AssetName(name, ast.NewNodeID())
+ assetTargetPath := filepath.Join(assetDirPath, name)
+ if err = filelock.Copy(absolutePath, assetTargetPath); err != nil {
+ logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", absolutePath, assetTargetPath, err)
+ return ast.WalkContinue
+ }
}
assetsDone[absolutePath] = name
} else {
name = existName
}
if ast.NodeLinkDest == n.Type {
- n.Tokens = []byte("assets/" + name)
+ assetURL := "assets/" + name
+ if IsEncryptedBox(boxID) {
+ assetURL += "?box=" + boxID
+ }
+ n.Tokens = []byte(assetURL)
} else {
- n.TextMarkAHref = "assets/" + name
+ assetURL := "assets/" + name
+ if IsEncryptedBox(boxID) {
+ assetURL += "?box=" + boxID
+ }
+ n.TextMarkAHref = assetURL
}
return ast.WalkContinue
})
@@ -1432,7 +1480,7 @@ func htmlBlock2Media(tree *parse.Tree) {
})
}
-func processHTMLBlockSvgImg(n *ast.Node, assetDirPath string) {
+func processHTMLBlockSvgImg(n *ast.Node, assetDirPath, boxID string) {
re := regexp.MustCompile(`(?i)<svg[^>]*>(.*?)</svg>`)
matches := re.FindStringSubmatch(string(n.Tokens))
if 1 >= len(matches) {
@@ -1440,13 +1488,16 @@ func processHTMLBlockSvgImg(n *ast.Node, assetDirPath string) {
}
svgContent := matches[0]
- name := util.AssetName("image.svg", ast.NewNodeID())
- writePath := filepath.Join(assetDirPath, name)
- if err := filelock.WriteFile(writePath, []byte(svgContent)); err != nil {
- logging.LogErrorf("write svg asset file [%s] failed: %s", writePath, err)
+ name, err := storeAssetForBox(boxID, assetDirPath, "image.svg", []byte(svgContent))
+ if err != nil {
+ logging.LogErrorf("store svg asset for box [%s] failed: %s", boxID, err)
return
}
+ assetURL := "assets/" + name
+ if boxID != "" && IsEncryptedBox(boxID) {
+ assetURL += "?box=" + boxID
+ }
n.Type = ast.NodeParagraph
img := &ast.Node{Type: ast.NodeImage}
img.AppendChild(&ast.Node{Type: ast.NodeBang})
@@ -1454,14 +1505,11 @@ func processHTMLBlockSvgImg(n *ast.Node, assetDirPath string) {
img.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte("image")})
img.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
img.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
- img.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("assets/" + name)})
+ img.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(assetURL)})
img.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
n.AppendChild(img)
}
-func processBase64Img(n *ast.Node, dest string, assetDirPath string) {
- base64TmpDir := filepath.Join(util.TempDir, "base64")
- os.MkdirAll(base64TmpDir, 0755)
-
+func processBase64Img(n *ast.Node, dest string, assetDirPath, boxID string) {
sep := strings.Index(dest, ";base64,")
str := strings.TrimSpace(dest[sep+8:])
re := regexp.MustCompile(`(?i)%0A`)
@@ -1505,37 +1553,40 @@ func processBase64Img(n *ast.Node, dest string, assetDirPath string) {
name = alt.TokensStr() + ext
}
name = util.FilterUploadFileName(name)
- name = util.AssetName(name, ast.NewNodeID())
- tmp := filepath.Join(base64TmpDir, name)
- tmpFile, openErr := os.OpenFile(tmp, os.O_RDWR|os.O_CREATE, 0644)
- if nil != openErr {
- logging.LogErrorf("open temp file [%s] failed: %s", tmp, openErr)
- return
- }
-
- var encodeErr error
+ var data []byte
switch typ {
- case "image/png":
- encodeErr = png.Encode(tmpFile, img)
- case "image/jpeg":
- encodeErr = jpeg.Encode(tmpFile, img, &jpeg.Options{Quality: 100})
case "image/svg+xml":
- _, encodeErr = tmpFile.Write(unbased)
- }
- if nil != encodeErr {
- logging.LogErrorf("encode base64 image failed: %s", encodeErr)
- tmpFile.Close()
- return
+ data = unbased
+ default:
+ var buf bytes.Buffer
+ switch typ {
+ case "image/png":
+ encodeErr := png.Encode(&buf, img)
+ if nil != encodeErr {
+ logging.LogErrorf("encode png image failed: %s", encodeErr)
+ return
+ }
+ case "image/jpeg":
+ encodeErr := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 100})
+ if nil != encodeErr {
+ logging.LogErrorf("encode jpeg image failed: %s", encodeErr)
+ return
+ }
+ }
+ data = buf.Bytes()
}
- tmpFile.Close()
- assetTargetPath := filepath.Join(assetDirPath, name)
- if err := filelock.Copy(tmp, assetTargetPath); err != nil {
- logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", tmp, assetTargetPath, err)
+ diskName, err := storeAssetForBox(boxID, assetDirPath, name, data)
+ if err != nil {
+ logging.LogErrorf("store base64 image for box [%s] failed: %s", boxID, err)
return
}
- n.Tokens = []byte("assets/" + name)
+ assetURL := "assets/" + diskName
+ if boxID != "" && IsEncryptedBox(boxID) {
+ assetURL += "?box=" + boxID
+ }
+ n.Tokens = []byte(assetURL)
}
func htmlBlock2Inline(tree *parse.Tree) {
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 09e32800f8..b69aa285d8 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -618,7 +618,12 @@ func decryptRepoDataIfNeeded(data []byte, filePath string) []byte {
if err != nil {
return data // 加密笔记本未解锁:同步快照解析返回原数据(调用方解析失败时按文件名回退)
}
- plain, err := DecryptFile(boxID, dek, data)
+ // repo 路径格式:/<boxID>/<relativePath>,parts[1] 为 box 内相对路径作为 AAD
+ boxRelPath := ""
+ if len(parts) >= 2 {
+ boxRelPath = parts[1]
+ }
+ plain, err := DecryptFile(boxID, boxRelPath, dek, data)
if err != nil {
return data
}
diff --git a/kernel/model/tree.go b/kernel/model/tree.go
index 2732aaf69b..5c17a67382 100644
--- a/kernel/model/tree.go
+++ b/kernel/model/tree.go
@@ -176,7 +176,9 @@ func loadTree(localPath string, luteEngine *lute.Lute) (ret *parse.Tree, err err
err = dekErr
return
}
- if data, err = DecryptFile(boxID, dek, data); err != nil {
+ // 从绝对路径推导 box 内相对路径作为 AAD
+ relPath := filepath.ToSlash(strings.TrimPrefix(localPath, filepath.Join(util.DataDir, boxID)+string(os.PathSeparator)))
+ if data, err = DecryptFile(boxID, relPath, dek, data); err != nil {
logging.LogErrorf("decrypt tree [path=%s] failed: %s", localPath, err)
return
}
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index a6d4f94546..8c78a7d277 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -25,6 +25,7 @@ import (
"path"
"path/filepath"
"strings"
+ "sync"
"github.com/88250/gulu"
"github.com/88250/lute/ast"
@@ -129,6 +130,9 @@ func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMa
f.Close()
p := "assets/" + fName
+ if IsEncryptedBox(bt.BoxID) {
+ p += "?box=" + bt.BoxID
+ }
succMap[baseName] = p
if !IsEncryptedBox(bt.BoxID) {
cache.SetAssetHash(hash, p) // 加密笔记本不写全局 cache,避免跨边界去重污染
@@ -371,6 +375,9 @@ func Upload(c *gin.Context) {
}
p := strings.TrimPrefix(path.Join(relAssetsDirPath, fName), "/")
+ if uploadBoxID != "" && IsEncryptedBox(uploadBoxID) {
+ p += "?box=" + uploadBoxID
+ }
succMap[baseName] = p
if uploadBoxID == "" || !IsEncryptedBox(uploadBoxID) {
cache.SetAssetHash(hash, p) // 加密笔记本不写全局 cache
@@ -433,7 +440,7 @@ func writeAssetFile(writePath string, src io.Reader, boxID string) (err error) {
if readErr != nil {
return readErr
}
- enc, encErr := EncryptAsset(actualBoxID, dek, raw)
+ enc, encErr := EncryptAsset(actualBoxID, filepath.Base(writePath), dek, raw)
if encErr != nil {
return encErr
}
@@ -442,6 +449,41 @@ func writeAssetFile(writePath string, src io.Reader, boxID string) (err error) {
return filelock.WriteFileByReader(writePath, src)
}
+// storeAssetForBox 统一资产写入入口:根据 boxID 决定加密/明文写入,返回磁盘文件名(不含路径前缀)。
+// 加密 box:生成脱敏名 → writeAssetNameMapping 记录映射 → EncryptAsset 加密 → filelock.WriteFile
+// 普通 box:util.AssetName 生成名 → filelock.WriteFile 明文写入
+// boxID 为空时按普通 box 处理(写入全局 assets)。
+func storeAssetForBox(boxID, assetDirPath, originalName string, data []byte) (diskName string, err error) {
+ if IsEncryptedBox(boxID) {
+ ext := filepath.Ext(originalName)
+ blockID := ast.NewNodeID()
+ diskName = encryptedAssetName(ext, blockID)
+ writeAssetNameMapping(boxID, diskName, originalName)
+
+ dek, dekErr := GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ return "", dekErr
+ }
+ enc, encErr := EncryptAsset(boxID, diskName, dek, data)
+ if encErr != nil {
+ return "", encErr
+ }
+ writePath := filepath.Join(assetDirPath, diskName)
+ if err = filelock.WriteFile(writePath, enc); err != nil {
+ return "", err
+ }
+ return diskName, nil
+ }
+
+ // 普通 box:生成带 ID 的文件名,明文写入
+ diskName = util.AssetName(originalName, ast.NewNodeID())
+ writePath := filepath.Join(assetDirPath, diskName)
+ if err = filelock.WriteFile(writePath, data); err != nil {
+ return "", err
+ }
+ return diskName, nil
+}
+
// encryptedAssetName 生成加密笔记本专用的无语义资源文件名:uuid-blockID.ext。
// 原始语义文件名(如"合同.pdf")通过 writeAssetNameMapping 存入加密映射,磁盘上只保留随机名。
func encryptedAssetName(ext, blockID string) string {
@@ -453,11 +495,19 @@ func assetNameMappingPath(boxID string) string {
return filepath.Join(util.DataDir, boxID, "assets", ".names.json")
}
+// assetNameMappingLocks 按 boxID 分组的互斥锁,保护 .names.json read-modify-write 的并发安全
+var assetNameMappingLocks sync.Map // map[string]*sync.Mutex
+
// writeAssetNameMapping 把"磁盘文件名 -> 原始文件名"映射写入加密笔记本的 .names.json(DEK 加密落盘)。
func writeAssetNameMapping(boxID, diskName, originalName string) {
if boxID == "" || !IsEncryptedBox(boxID) {
return
}
+ muI, _ := assetNameMappingLocks.LoadOrStore(boxID, &sync.Mutex{})
+ mu := muI.(*sync.Mutex)
+ mu.Lock()
+ defer mu.Unlock()
+
mapping := readAssetNameMapping(boxID)
mapping[diskName] = originalName
data, err := json.Marshal(mapping)
@@ -470,7 +520,7 @@ func writeAssetNameMapping(boxID, diskName, originalName string) {
logging.LogErrorf("get DEK for asset name mapping failed: %s", err)
return
}
- enc, err := EncryptAsset(boxID, dek, data)
+ enc, err := EncryptAsset(boxID, ".names.json", dek, data)
if err != nil {
logging.LogErrorf("encrypt asset name mapping failed: %s", err)
return
@@ -495,7 +545,7 @@ func readAssetNameMapping(boxID string) map[string]string {
if err != nil || dek == nil {
return ret
}
- data, err := DecryptAsset(boxID, dek, enc)
+ data, err := DecryptAsset(boxID, ".names.json", dek, enc)
if err != nil {
logging.LogErrorf("decrypt asset name mapping failed: %s", err)
return ret
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 547db448ab..c8936b5543 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -668,13 +668,39 @@ func serveAssets(ginServer *gin.Engine) {
return
}
+ // 硬边界:拒绝路径遍历
+ if strings.Contains(requestPath, "..") || filepath.IsAbs(requestPath) {
+ context.Status(http.StatusForbidden)
+ return
+ }
+
relativePath := path.Join("assets", requestPath)
- p, err := model.GetAssetAbsPathWithOpt(relativePath, true)
- if err != nil {
+ cleanPath := path.Clean(relativePath)
+ if !strings.HasPrefix(cleanPath, "assets/") {
+ context.Status(http.StatusForbidden)
+ return
+ }
+
+ // 解析 box 查询参数,加密 box 资源按 box 内精确查找(不全局搜索)
+ boxID := context.Query("box")
+ var p string
+ var err error
+ if boxID != "" {
+ p, err = model.GetAssetAbsPathInBox(cleanPath, boxID)
+ } else {
+ p, err = model.GetAssetAbsPathWithOpt(cleanPath, true)
+ }
+ if err != nil || p == "" {
context.Status(http.StatusNotFound)
return
}
+ // 验证最终绝对路径必须在 data/assets 或 <boxID>/assets 下
+ if !strings.HasSuffix(filepath.ToSlash(p), "/"+strings.TrimPrefix(cleanPath, "/")) {
+ context.Status(http.StatusForbidden)
+ return
+ }
+
if !model.IsAdminRoleContext(context) {
publishAccess := model.GetPublishAccess()
if !model.CheckAbsPathAccessableByPublishAccess(context, p, publishAccess) {
@@ -738,12 +764,13 @@ func readAssetBytes(absPath string) ([]byte, error) {
if err != nil {
return nil, err
}
- if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" && model.IsEncryptedBox(boxID) {
- dek, dekErr := model.GetDEKIfUnlocked(boxID)
- if dekErr != nil {
- return nil, dekErr // 加密笔记本未解锁:fail-closed,不返回密文
- }
- plain, decErr := model.DecryptAsset(boxID, dek, data)
+ if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" && model.IsEncryptedBox(boxID) {
+ dek, dekErr := model.GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ return nil, dekErr // 加密笔记本未解锁:fail-closed,不返回密文
+ }
+ diskName := filepath.Base(absPath)
+ plain, decErr := model.DecryptAsset(boxID, diskName, dek, data)
if decErr != nil {
return nil, decErr
}
@@ -771,15 +798,15 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
context.Status(http.StatusNotFound)
return true
}
- plain, decErr := model.DecryptAsset(boxID, dek, ciphertext)
- if decErr != nil {
- logging.LogErrorf("decrypt asset [%s] failed: %s", absPath, decErr)
- context.Status(http.StatusInternalServerError)
- return true
- }
- // 下载时用原始文件名(查加密映射),查不到则退回磁盘名
- diskName := filepath.Base(absPath)
- if originalName := model.LookupAssetOriginalName(boxID, diskName); originalName != "" {
+ diskName := filepath.Base(absPath)
+ plain, decErr := model.DecryptAsset(boxID, diskName, dek, ciphertext)
+ if decErr != nil {
+ logging.LogErrorf("decrypt asset [%s] failed: %s", absPath, decErr)
+ context.Status(http.StatusInternalServerError)
+ return true
+ }
+ // 下载时用原始文件名(查加密映射),查不到则退回磁盘名
+ if originalName := model.LookupAssetOriginalName(boxID, diskName); originalName != "" {
setAssetsAttachmentDisposition(context, originalName)
} else {
setAssetsAttachmentDisposition(context, absPath)
@@ -815,15 +842,21 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
var plain []byte
var decErr error
if strings.HasSuffix(absPath, ".sy") {
- plain, decErr = model.DecryptFile(boxID, dek, ciphertext)
+ // 从绝对路径推导 box 内相对路径作为 AAD
+ relPath := strings.TrimPrefix(absPath, filepath.Join(util.DataDir, boxID)+string(os.PathSeparator))
+ relPath = filepath.ToSlash(relPath)
+ plain, decErr = model.DecryptFile(boxID, relPath, dek, ciphertext)
} else if strings.Contains(absPath, "assets"+string(os.PathSeparator)) {
- plain, decErr = model.DecryptAsset(boxID, dek, ciphertext)
+ diskName := filepath.Base(absPath)
+ plain, decErr = model.DecryptAsset(boxID, diskName, dek, ciphertext)
} else if strings.Contains(absPath, "storage"+string(os.PathSeparator)+"av"+string(os.PathSeparator)) {
// AV 定义用 siyuan/av 子密钥加密,与 assets 的 siyuan/asset 子密钥不同
- plain, decErr = av.DecryptAVData(boxID, ciphertext)
+ avID := strings.TrimSuffix(filepath.Base(absPath), filepath.Ext(absPath))
+ plain, decErr = av.DecryptAVData(boxID, avID, ciphertext)
} else {
// 其他历史文件(如 JSON 元数据等)尝试用 asset 解密方式
- plain, decErr = model.DecryptAsset(boxID, dek, ciphertext)
+ diskName := filepath.Base(absPath)
+ plain, decErr = model.DecryptAsset(boxID, diskName, dek, ciphertext)
}
if decErr != nil {
logging.LogErrorf("decrypt history [%s] failed: %s", absPath, decErr)