Skip to content

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

:lock: Fix encrypted asset plaintext leaks in extension copy/html2BlockDOM/import rollback, append ?box= to network/imported asset refs, fix .sy decryption timing in rollback and history AAD path extraction, fail-closed for encrypted repo snapshot assets https://github.com/siyuan-note/siyuan/issues/18034

Daniel710c7fe9bba0
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 2687a8aeff..766cb9d1f0 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -359,14 +359,14 @@ func getFileAnnotation(c *gin.Context) {
}
func resolveFileAnnotationAbsPath(assetRelPath string) (ret string, err error) {
+ // .sya 在 URL 末尾,例如 assets/a.pdf?box=<id>.sya
+ // TrimSuffix 去掉 .sya 得到 assets/a.pdf?box=<id>,保留 query 供 box-aware 解析
filePath := strings.TrimSuffix(assetRelPath, ".sya")
absPath, err := model.GetAssetAbsPathInBox(filePath, "")
if err != nil {
return
}
- dir := filepath.Dir(absPath)
- base := filepath.Base(assetRelPath)
- ret = filepath.Join(dir, base)
+ ret = absPath + ".sya"
return
}
diff --git a/kernel/api/extension.go b/kernel/api/extension.go
index ac8ca42d31..e74a0181a5 100644
--- a/kernel/api/extension.go
+++ b/kernel/api/extension.go
@@ -33,7 +33,6 @@ import (
"github.com/88250/lute/parse"
"github.com/gabriel-vasile/mimetype"
"github.com/gin-gonic/gin"
- "github.com/siyuan-note/filelock"
"github.com/siyuan-note/httpclient"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/model"
@@ -47,10 +46,17 @@ func extensionCopy(c *gin.Context) {
form, _ := c.MultipartForm()
dom := form.Value["dom"][0]
assets := filepath.Join(util.DataDir, "assets")
+ boxID := ""
if notebookVal := form.Value["notebook"]; 0 < len(notebookVal) {
- assets = filepath.Join(util.DataDir, notebookVal[0], "assets")
- if !gulu.File.IsDir(assets) {
- assets = filepath.Join(util.DataDir, "assets")
+ nb := notebookVal[0]
+ if model.IsEncryptedBox(nb) {
+ boxID = nb
+ assets = filepath.Join(util.DataDir, nb, "assets")
+ } else {
+ assets = filepath.Join(util.DataDir, nb, "assets")
+ if !gulu.File.IsDir(assets) {
+ assets = filepath.Join(util.DataDir, "assets")
+ }
}
}
@@ -159,15 +165,19 @@ func extensionCopy(c *gin.Context) {
fName += ext
}
- fName = util.AssetName(fName, ast.NewNodeID())
- writePath := filepath.Join(assets, fName)
- if err = filelock.WriteFile(writePath, data); err != nil {
+ // 统一通过 storeAssetForBox 写入,加密 box 自动脱敏 + 加密落盘 + 追加 ?box=
+ storedName, storeErr := model.StoreAssetForBox(boxID, assets, fName, data)
+ if storeErr != nil {
ret.Code = -1
- ret.Msg = err.Error()
+ ret.Msg = storeErr.Error()
break
}
- uploaded[unescaped] = "assets/" + fName
+ assetURL := "assets/" + storedName
+ if boxID != "" {
+ assetURL += "?box=" + boxID
+ }
+ uploaded[unescaped] = assetURL
}
luteEngine := util.NewLute()
@@ -234,7 +244,7 @@ func extensionCopy(c *gin.Context) {
return s
})
- tree, withMath = model.HTML2Tree(dom, luteEngine, "")
+ tree, withMath = model.HTML2Tree(dom, luteEngine, boxID)
} else {
tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)
}
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 28fedf8cdf..2bd7922166 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -18,6 +18,7 @@ package api
import (
"net/http"
+ "os"
"path/filepath"
"strings"
@@ -27,7 +28,6 @@ import (
"github.com/88250/lute/parse"
"github.com/88250/lute/render"
"github.com/gin-gonic/gin"
- "github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -176,12 +176,19 @@ func html2BlockDOM(c *gin.Context) {
ext := filepath.Ext(name)
name = name[0 : len(name)-len(ext)]
name = name + "-" + ast.NewNodeID() + ext
- targetPath := filepath.Join(util.DataDir, "assets", name)
- if err := filelock.Copy(localPath, targetPath); err != nil {
- logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", localPath, targetPath, err)
+
+ data, readErr := os.ReadFile(localPath)
+ if readErr != nil {
+ logging.LogErrorf("read asset [%s] failed: %s", localPath, readErr)
+ return ast.WalkStop
+ }
+ assetsDir := filepath.Join(util.DataDir, "assets")
+ storedName, storeErr := model.StoreAssetForBox("", assetsDir, name, data)
+ if storeErr != nil {
+ logging.LogErrorf("store asset [%s] failed: %s", localPath, storeErr)
return ast.WalkStop
}
- n.Tokens = gulu.Str.ToBytes("assets/" + name)
+ n.Tokens = gulu.Str.ToBytes("assets/" + storedName)
return ast.WalkContinue
})
}
diff --git a/kernel/av/av.go b/kernel/av/av.go
index 485d40f5de..1c2ab85b8f 100644
--- a/kernel/av/av.go
+++ b/kernel/av/av.go
@@ -514,13 +514,15 @@ func ParseAttributeView(avID string) (ret *AttributeView, err error) {
}
func ParseAttributeViewInBox(avID, boxID string) (ret *AttributeView, err error) {
- if boxID != "" {
- SetAVBoxID(avID, boxID)
- }
avJSONPath, avBoxID := FindAttributeViewPathInBox(avID, boxID)
if avJSONPath == "" {
avJSONPath = attributeViewDataPathByBox(avID, boxID)
avBoxID = boxID
+ } else {
+ // 只在文件确实存在于该 box 内时才设置映射,避免错误 boxID 污染后续路由
+ if boxID != "" {
+ SetAVBoxID(avID, boxID)
+ }
}
return parseAttributeViewByPathInBox(avJSONPath, avBoxID)
}
diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.go
index 6a23efb06d..7502e0abe6 100644
--- a/kernel/av/encrypted_hook.go
+++ b/kernel/av/encrypted_hook.go
@@ -36,13 +36,15 @@ var AVIsEncryptedBox func(boxID string) bool
var pendingAVBox = map[string]string{}
var pendingAVBoxLock = sync.RWMutex{}
-// SetAVBoxID 预设 AV 定义的归属 box。加密笔记本创建 AV 时调用。
+// SetAVBoxID 预设 AV 定义的归属 box。加密笔记本创建 AV 时调用,boxID 为空时清理映射。
// 普通笔记本不需要调(AV 默认走全局路径)。
func SetAVBoxID(avID, boxID string) {
+ pendingAVBoxLock.Lock()
+ defer pendingAVBoxLock.Unlock()
if boxID != "" {
- pendingAVBoxLock.Lock()
- defer pendingAVBoxLock.Unlock()
pendingAVBox[avID] = boxID
+ } else {
+ delete(pendingAVBox, avID)
}
}
@@ -64,14 +66,15 @@ func attributeViewDataPathByBox(avID, boxID string) string {
}
// FindAttributeViewPath 按 fallback 逻辑查找 AV 定义文件的实际路径。
-// 1. 先查 pendingAVBox(首次创建预设的 boxID)
+// 1. 先查 pendingAVBox(首次创建预设的 boxID),不检查文件是否存在(首次创建场景)
// 2. 查全局 storage/av/(普通 box)
// 3. 遍历已打开的加密笔记本查找
// 返回找到的路径和对应的 boxID(普通 box 返回空 boxID)。找不到返回空串。
func FindAttributeViewPath(avID string) (path string, boxID string) {
- // 先查 pendingAVBox(首次创建场景)
+ // 先查 pendingAVBox(首次创建场景),不要求文件存在
if pendingBoxID := GetAVBoxID(avID); pendingBoxID != "" {
encPath := attributeViewDataPathByBox(avID, pendingBoxID)
+ // pending 存在就直接返回该 box 路径(首次创建时文件尚不存在)
return encPath, pendingBoxID
}
// 查全局
@@ -95,9 +98,10 @@ func FindAttributeViewPath(avID string) (path string, boxID string) {
func FindAttributeViewPathInBox(avID, boxID string) (path string, retBoxID string) {
if pendingBoxID := GetAVBoxID(avID); pendingBoxID != "" {
if pendingBoxID == boxID {
+ // pending 匹配目标 box,直接返回(首次创建时文件尚不存在)
return attributeViewDataPathByBox(avID, pendingBoxID), pendingBoxID
}
- return "", boxID
+ // pending 映射属于其他 box,不遮蔽本 box 的文件查找,继续检查磁盘
}
avPath := attributeViewDataPathByBox(avID, boxID)
if filelock.IsExist(avPath) {
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index dba1cfb413..c34eb606f8 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -74,7 +74,7 @@ func GetAssetImgSizeInBox(assetPath, boxID string) (width, height int) {
}
// ReadAssetBytesInBox 读取指定 box 内的资源文件字节。若 box 为加密笔记本则自动解密返回明文。
-// relativePath 形如 "assets/xxx.png"。
+// relativePath 形如 "assets/xxx.png",可带 ?box= 查询参数。
func ReadAssetBytesInBox(boxID, relativePath string) ([]byte, error) {
absPath, err := GetAssetAbsPathInBox(relativePath, boxID)
if err != nil {
@@ -84,13 +84,15 @@ func ReadAssetBytesInBox(boxID, relativePath string) ([]byte, error) {
if readErr != nil {
return nil, readErr
}
- if IsEncryptedBox(boxID) {
- dek, dekErr := GetDEKIfUnlocked(boxID)
+ // 从解析到的绝对路径反推有效 boxID,不轻信传入参数(路径可能通过 ?box= 指定了不同 box)
+ effectiveBoxID := ExtractBoxIDFromAssetsPath(absPath)
+ if effectiveBoxID != "" && IsEncryptedBox(effectiveBoxID) {
+ dek, dekErr := GetDEKIfUnlocked(effectiveBoxID)
if dekErr != nil {
return nil, dekErr
}
- diskName := filepath.Base(relativePath)
- plain, decErr := DecryptAsset(boxID, diskName, dek, data)
+ diskName := filepath.Base(AssetPathWithoutQuery(relativePath))
+ plain, decErr := DecryptAsset(effectiveBoxID, diskName, dek, data)
if decErr != nil {
return nil, decErr
}
@@ -380,7 +382,11 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,
}
}
- setAssetsLinkDest(destNode, dest, "assets/"+name)
+ assetURL := "assets/" + name
+ if IsEncryptedBox(tree.Box) {
+ assetURL += "?box=" + tree.Box
+ }
+ setAssetsLinkDest(destNode, dest, assetURL)
assetsMap[u] = name
files++
size += gulu.File.GetFileSize(writePath)
@@ -504,7 +510,11 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,
}
}
- setAssetsLinkDest(destNode, dest, "assets/"+name)
+ assetURL := "assets/" + name
+ if IsEncryptedBox(tree.Box) {
+ assetURL += "?box=" + tree.Box
+ }
+ setAssetsLinkDest(destNode, dest, assetURL)
assetsMap[u] = name
files++
size += int64(len(data))
@@ -645,14 +655,19 @@ func AssetPathWithoutQuery(relativePath string) string {
return filepath.ToSlash(relativePath)
}
-func assetPathAndBox(relativePath, defaultBoxID string) (cleanPath, boxID string) {
+func assetPathAndBox(relativePath, defaultBoxID string) (cleanPath, boxID string, err error) {
relativePath = strings.TrimSpace(relativePath)
boxID = defaultBoxID
if idx := strings.Index(relativePath, "?"); idx >= 0 {
query := relativePath[idx+1:]
relativePath = relativePath[:idx]
- if values, err := url.ParseQuery(query); err == nil {
+ if values, parseErr := url.ParseQuery(query); parseErr == nil {
if queryBoxID := strings.TrimSpace(values.Get("box")); queryBoxID != "" {
+ if defaultBoxID != "" && defaultBoxID != queryBoxID {
+ // 调用方指定了 boxID 但 URL 里是另一个 box:拒绝,防止解析到错误 box
+ err = fmt.Errorf("box mismatch: caller specified [%s] but URL has [%s]", defaultBoxID, queryBoxID)
+ return
+ }
boxID = queryBoxID
}
}
@@ -662,14 +677,21 @@ func assetPathAndBox(relativePath, defaultBoxID string) (cleanPath, boxID string
}
// GetAssetAbsPathInBox 在指定 box 内解析资源绝对路径,不进行全局遍历。
-// boxID 为空且路径没有 box 查询参数时只解析普通/全局资源,不遍历加密 box。
+// relativePath 必须以 assets/ 前缀开头,boxID 为空且路径没有 box 查询参数时只解析普通/全局资源,不遍历加密 box。
// 加密 box 直接从 <boxID>/assets/ 查找,不依赖后缀匹配。
func GetAssetAbsPathInBox(relativePath, boxID string) (string, error) {
- relativePath, boxID = assetPathAndBox(relativePath, boxID)
+ var err error
+ relativePath, boxID, err = assetPathAndBox(relativePath, boxID)
+ if err != nil {
+ return "", err
+ }
relativePath = path.Clean(relativePath)
if relativePath == "." || strings.HasPrefix(relativePath, "../") || relativePath == ".." || path.IsAbs(relativePath) {
return "", fmt.Errorf("[%s] is not an asset path", relativePath)
}
+ if !strings.HasPrefix(relativePath, "assets/") {
+ return "", fmt.Errorf("[%s] is not an asset path (must start with assets/)", relativePath)
+ }
if boxID != "" && !ast.IsNodeIDPattern(boxID) {
return "", fmt.Errorf("[%s] is not a box id", boxID)
}
@@ -1828,8 +1850,11 @@ func allAssetAbsPaths() (assetsAbsPathMap map[string]string, err error) {
}
assetsAbsPathMap = map[string]string{}
- // 笔记本 assets
+ // 笔记本 assets(跳过加密 box,加密资产不参与全局去重/清理)
for _, notebook := range notebooks {
+ if IsEncryptedBox(notebook.ID) {
+ continue
+ }
notebookAbsPath := filepath.Join(util.DataDir, notebook.ID)
filelock.Walk(notebookAbsPath, func(path string, d fs.DirEntry, err error) error {
if notebookAbsPath == path {
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 774e72da0c..932a04a6fe 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, avID, 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, newAvID, 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 2c573ee826..7eff6f5c29 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, avID, 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
diff --git a/kernel/model/export.go b/kernel/model/export.go
index f5379d0f2a..3207dff4c7 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -1581,6 +1581,12 @@ func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, boxID
if !removeAssets {
// 不移除资源文件夹的话将超链接指向资源文件夹
+ // 加密资源的 link.URI 需要保留 ?box= 上下文,否则导出的 PDF 链接无法解析
+ if idx := strings.Index(sourceURI, "?"); 0 < idx {
+ if strings.Contains(sourceURI[idx:], "box=") {
+ link.URI = sourceURI
+ }
+ }
if 1 > len(linkMap[link.Page]) {
linkMap[link.Page] = []model.AnnotationRenderer{link}
} else {
@@ -2441,16 +2447,22 @@ func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap
}
// 级联导出关联列关联的数据库
- exportRelationAvs(avID, exportStorageAvDir)
+ exportRelationAvs(avID, boxID, exportStorageAvDir)
}
-func exportRelationAvs(avID, exportStorageAvDir string) {
+func exportRelationAvs(avID, boxID, exportStorageAvDir string) {
avIDs := hashset.New()
- walkRelationAvs(avID, avIDs)
+ walkRelationAvs(avID, boxID, avIDs)
for _, v := range avIDs.Values() {
relAvID := v.(string)
- relAvData, readErr := av.ReadAttributeViewData(relAvID)
+ var relAvData []byte
+ var readErr error
+ if boxID != "" {
+ relAvData, readErr = av.ReadAttributeViewDataInBox(relAvID, boxID)
+ } else {
+ relAvData, readErr = av.ReadAttributeViewData(relAvID)
+ }
if readErr != nil {
logging.LogErrorf("read relation attribute view [%s] failed: %s", relAvID, readErr)
continue
@@ -2464,12 +2476,17 @@ func exportRelationAvs(avID, exportStorageAvDir string) {
}
}
-func walkRelationAvs(avID string, exportAvIDs *hashset.Set) {
+func walkRelationAvs(avID, boxID string, exportAvIDs *hashset.Set) {
if exportAvIDs.Contains(avID) {
return
}
- attrView, _ := av.ParseAttributeView(avID)
+ var attrView *av.AttributeView
+ if boxID != "" {
+ attrView, _ = av.ParseAttributeViewInBox(avID, boxID)
+ } else {
+ attrView, _ = av.ParseAttributeView(avID)
+ }
if nil == attrView {
return
}
@@ -2482,7 +2499,7 @@ func walkRelationAvs(avID string, exportAvIDs *hashset.Set) {
break
}
- walkRelationAvs(keyValues.Key.Relation.AvID, exportAvIDs)
+ walkRelationAvs(keyValues.Key.Relation.AvID, boxID, exportAvIDs)
}
}
}
@@ -2756,7 +2773,7 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,
return ast.WalkSkipChildren
}
- status := processFileAnnotationRef(refID, n, fileAnnotationRefMode)
+ status := processFileAnnotationRef(refID, n, fileAnnotationRefMode, tree.Box)
unlinks = append(unlinks, n)
return status
} else if n.IsTextMarkType("tag") {
@@ -3580,19 +3597,33 @@ type refAsFootnotes struct {
refAnchorText string
}
-func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode int) ast.WalkStatus {
+func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode int, boxID string) ast.WalkStatus {
p := refID[:strings.LastIndex(refID, "/")]
- absPath, err := GetAssetAbsPathInBox(p, "")
+ absPath, err := GetAssetAbsPathInBox(p, boxID)
if err != nil {
logging.LogWarnf("get assets abs path by rel path [%s] failed: %s", p, err)
return ast.WalkSkipChildren
}
sya := absPath + ".sya"
- syaData, err := os.ReadFile(sya)
- if err != nil {
- logging.LogErrorf("read file [%s] failed: %s", sya, err)
+ syaData, readErr := os.ReadFile(sya)
+ if readErr != nil {
+ logging.LogErrorf("read file [%s] failed: %s", sya, readErr)
return ast.WalkSkipChildren
}
+ // 加密 box 的 .sya 是密文,需先解密
+ if IsEncryptedBox(boxID) {
+ dek, dekErr := GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ logging.LogWarnf("get DEK for file annotation [%s] failed: %s", sya, dekErr)
+ return ast.WalkSkipChildren
+ }
+ plain, decErr := DecryptAsset(boxID, filepath.Base(sya), dek, syaData)
+ if decErr != nil {
+ logging.LogWarnf("decrypt file annotation [%s] failed: %s", sya, decErr)
+ return ast.WalkSkipChildren
+ }
+ syaData = plain
+ }
syaJSON := map[string]any{}
if err = gulu.JSON.UnmarshalJSON(syaData, &syaJSON); err != nil {
logging.LogErrorf("unmarshal file [%s] failed: %s", sya, err)
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 7fce1ba6c8..952610b00c 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -809,6 +809,10 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
// updateImportedAssetRefs 遍历树的 assets 引用路径,将原始文件名替换为脱敏文件名。
// 覆盖:链接 href、图片 src、data-src、音视频 src、文件标注等。
func updateImportedAssetRefs(tree *parse.Tree, assetNameMap map[string]string) {
+ boxSuffix := ""
+ if IsEncryptedBox(tree.Box) {
+ boxSuffix = "?box=" + tree.Box
+ }
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
@@ -817,26 +821,26 @@ func updateImportedAssetRefs(tree *parse.Tree, assetNameMap map[string]string) {
case ast.NodeLink:
// 链接 dest
dest := string(n.Tokens)
- if updated := replaceAssetName(dest, assetNameMap); updated != dest {
+ if updated := replaceAssetName(dest, assetNameMap, boxSuffix); updated != dest {
n.Tokens = []byte(updated)
}
case ast.NodeImage:
// 图片 src 在 LinkDest 子节点
if dest := n.ChildByType(ast.NodeLinkDest); nil != dest {
src := string(dest.Tokens)
- if updated := replaceAssetName(src, assetNameMap); updated != src {
+ if updated := replaceAssetName(src, assetNameMap, boxSuffix); updated != src {
dest.Tokens = []byte(updated)
}
}
case ast.NodeAudio, ast.NodeVideo:
src := n.TokensStr()
- if updated := replaceAssetName(src, assetNameMap); updated != src {
+ if updated := replaceAssetName(src, assetNameMap, boxSuffix); updated != src {
n.Tokens = []byte(updated)
}
case ast.NodeTextMark:
// 行级文本标记里的 data-href(附件链接)
if "" != n.TextMarkAHref {
- if updated := replaceAssetName(n.TextMarkAHref, assetNameMap); updated != n.TextMarkAHref {
+ if updated := replaceAssetName(n.TextMarkAHref, assetNameMap, boxSuffix); updated != n.TextMarkAHref {
n.TextMarkAHref = updated
}
}
@@ -845,8 +849,8 @@ func updateImportedAssetRefs(tree *parse.Tree, assetNameMap map[string]string) {
})
}
-// replaceAssetName 在 assets 路径中替换原始文件名为脱敏文件名。
-func replaceAssetName(path string, assetNameMap map[string]string) string {
+// replaceAssetName 在 assets 路径中替换原始文件名为脱敏文件名,并按需追加 box query。
+func replaceAssetName(path string, assetNameMap map[string]string, boxSuffix string) string {
if !strings.Contains(path, "assets/") {
return path
}
@@ -855,6 +859,10 @@ func replaceAssetName(path string, assetNameMap map[string]string) string {
idx := strings.LastIndex(path, original)
if idx > 0 && strings.Contains(path[idx:], original) {
path = path[:idx] + diskName + path[idx+len(original):]
+ // 替换后如果没有 box query,补上
+ if boxSuffix != "" && !strings.Contains(path, "?box=") {
+ path += boxSuffix
+ }
}
}
return path
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index b69aa285d8..03a7ed6f25 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -258,6 +258,14 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {
util.PushClearProgress()
from := filepath.Join(tempRepoDiffDir, f)
+ // 加密笔记本的快照数据是密文,写入临时文件前先解密
+ if strings.HasSuffix(file.Path, ".sy") {
+ boxID := strings.TrimPrefix(file.Path, "/")
+ boxID = strings.Split(boxID, "/")[0]
+ if IsEncryptedBox(boxID) {
+ data = decryptRepoDataIfNeeded(data, file.Path)
+ }
+ }
if err = os.WriteFile(from, data, 0644); nil != err {
logging.LogErrorf("write file [%s] failed: %v", filepath.Join(tempRepoDiffDir, file.Path), err)
return
@@ -423,6 +431,29 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
content = gulu.Str.FromBytes(data)
} else {
if strings.Contains(file.Path, "assets/") { // 剔除笔记本级或者文档级资源文件路径前缀
+ // 加密 notebook 的 asset 在仓库里是密文,不解密直接写临时目录会泄漏密文
+ // 先用原始 path 检测是否加密 box,再裁剪 file.Path 到 assets/ 前缀
+ 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) {
+ // 加密 asset:尝试解密后预览,无法解密则 fail-closed
+ if dek, dekErr := GetDEKIfUnlocked(repoBoxID); dekErr == nil && dek != nil {
+ diskName := filepath.Base(file.Path)
+ if plainData, decErr := DecryptAsset(repoBoxID, diskName, dek, data); decErr == nil {
+ data = plainData
+ } else {
+ logging.LogWarnf("decrypt repo snapshot asset [%s] failed: %s", file.Path, decErr)
+ content = file.Path
+ return
+ }
+ } else {
+ content = file.Path
+ return
+ }
+ }
file.Path = file.Path[strings.Index(file.Path, "assets/"):]
if util.IsDisplayableAsset(file.Path) {
dir, f := filepath.Split(file.Path)
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index 521ac6a650..bbf3247afe 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -455,6 +455,14 @@ 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) {
+ return storeAssetForBox(boxID, assetDirPath, originalName, data)
+}
+
// storeAssetForBox 统一资产写入入口:根据 boxID 决定加密/明文写入,返回磁盘文件名(不含路径前缀)。
// 加密 box:生成脱敏名 → writeAssetNameMapping 记录映射 → EncryptAsset 加密 → filelock.WriteFile
// 普通 box:util.AssetName 生成名 → filelock.WriteFile 明文写入
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 0c20eb6484..30c0e4556d 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -862,9 +862,9 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
var plain []byte
var decErr error
if strings.HasSuffix(absPath, ".sy") {
- // 从绝对路径推导 box 内相对路径作为 AAD
- relPath := strings.TrimPrefix(absPath, filepath.Join(util.DataDir, boxID)+string(os.PathSeparator))
- relPath = filepath.ToSlash(relPath)
+ // history 路径格式:<historyDir>/<datePrefix>/<boxID>/<relativePath>
+ // 需提取 box 内相对路径作为 AAD,不能用 DataDir 前缀 trim
+ relPath := extractHistoryRelPath(absPath, boxID)
plain, decErr = model.DecryptFile(boxID, relPath, dek, ciphertext)
} else if strings.Contains(absPath, "assets"+string(os.PathSeparator)) {
diskName := filepath.Base(absPath)
@@ -891,6 +891,18 @@ func serveEncryptedHistory(context *gin.Context, absPath string) bool {
return true
}
+// extractHistoryRelPath 从 history 绝对路径中提取 box 内相对路径作为 AAD。
+// history 路径格式:<historyDir>/<datePrefix>/<boxID>/<relativePath>。
+func extractHistoryRelPath(absPath, boxID string) string {
+ absPath = filepath.ToSlash(absPath)
+ idx := strings.Index(absPath, "/"+boxID+"/")
+ if idx < 0 {
+ return ""
+ }
+ rel := absPath[idx+len("/"+boxID+"/"):]
+ return rel
+}
+
func serveThumbnail(context *gin.Context, assetAbsPath, requestPath string) bool {
// 加密笔记本的资源是密文,imaging.Open 无法解析,跳过缩略图生成(由 serveEncryptedAsset 解密输出原图)
if model.IsEncryptedAssetPath(assetAbsPath) {