Skip to content

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

:sparkles: encrypt assets for encrypted notebooks (stage 4) #18034

Danielfdae43d0a76f
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 78248296fb..46a8a16906 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -280,10 +280,21 @@ func setFileAnnotation(c *gin.Context) {
ret.Msg = err.Error()
return
}
- } else if err = filelock.WriteFile(writePath, []byte(data)); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ } else {
+ // 加密笔记本的 .sya 写盘前加密
+ writeData := []byte(data)
+ if boxID := model.ExtractBoxIDFromAssetsPath(writePath); boxID != "" {
+ if dek, decErr := model.GetDEK(boxID); decErr == nil && dek != nil {
+ if enc, encErr := util.Encrypt(dek, writeData); encErr == nil {
+ writeData = enc
+ }
+ }
+ }
+ if err = filelock.WriteFile(writePath, writeData); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
}
model.IncSync()
@@ -318,6 +329,14 @@ func getFileAnnotation(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ // 加密笔记本的 .sya 读盘后解密
+ if boxID := model.ExtractBoxIDFromAssetsPath(readPath); boxID != "" {
+ if dek, decErr := model.GetDEK(boxID); decErr == nil && dek != nil {
+ if plain, decErr := util.Decrypt(dek, data); decErr == nil {
+ data = plain
+ }
+ }
+ }
ret.Data = map[string]any{
"data": string(data),
}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 16e1dd1ca4..62025ff510 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -24,6 +24,7 @@ import (
"time"
"github.com/88250/lute/ast"
+ "github.com/siyuan-note/filelock"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -293,6 +294,13 @@ func GetDEKIfUnlocked(boxID string) ([]byte, error) {
// 路径形如 <DataDir>/<boxID>/...,切出紧跟在 DataDir 后的一段。
// 若路径不在 DataDir 下或格式不符,返回空字符串。
func extractBoxIDFromPath(absPath string) string {
+ return ExtractBoxIDFromAssetsPath(absPath)
+}
+
+// ExtractBoxIDFromAssetsPath 从 data 目录下的绝对路径(.sy 或 assets)反推 boxID。
+// 供 server/api 层判断 asset 是否属于加密笔记本。路径形如 <DataDir>/<boxID>/...;
+// 若不在 DataDir 下或 boxID 非合法 ID 模式,返回空串。
+func ExtractBoxIDFromAssetsPath(absPath string) string {
absPath = filepath.ToSlash(absPath)
dataDir := filepath.ToSlash(util.DataDir)
rel, err := filepath.Rel(dataDir, absPath)
@@ -311,6 +319,30 @@ func extractBoxIDFromPath(absPath string) string {
return boxID
}
+// copyAssetDecryptIfEncrypted 把 srcPath 的 asset 复制到 destPath。
+// 若 srcPath 在已解锁的加密 box 下,读密文→解密→写明文到 destPath(导出目录);
+// 否则走 filelock.Copy 原路径(字节级复制,密文/明文均可)。
+func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {
+ boxID := ExtractBoxIDFromAssetsPath(srcPath)
+ if boxID != "" {
+ if dek, err := GetDEK(boxID); err == nil && dek != nil {
+ raw, readErr := filelock.ReadFile(srcPath)
+ if readErr != nil {
+ return readErr
+ }
+ plain, decErr := util.Decrypt(dek, raw)
+ if decErr != nil {
+ return decErr
+ }
+ if err := filelock.WriteFile(destPath, plain); err != nil {
+ return err
+ }
+ return nil
+ }
+ }
+ return filelock.Copy(srcPath, destPath)
+}
+
// CreateEncryptedBox 创建一个新的加密笔记本。可多次调用创建多个。
// 前置:加密功能已启用。创建时需要主密码(临时派生 KEK 用于 wrap DEK,用完即弃)。
// 创建后笔记本处于"已锁定"状态(DEK 未缓存),需调用方再调 UnlockBox + Mount 才能打开。
diff --git a/kernel/model/export.go b/kernel/model/export.go
index c8e3c75064..f13bfc7379 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -2132,7 +2132,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (
}
destPath := filepath.Join(exportDir, asset)
- assetErr := filelock.Copy(srcPath, destPath)
+ assetErr := copyAssetDecryptIfEncrypted(srcPath, destPath)
if nil != assetErr {
logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, assetErr)
continue
@@ -2142,7 +2142,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (
sya := srcPath + ".sya"
if filelock.IsExist(sya) {
// Related PDF annotation information is not exported when exporting .sy.zip https://github.com/siyuan-note/siyuan/issues/7836
- if syaErr := filelock.Copy(sya, destPath+".sya"); nil != syaErr {
+ if syaErr := copyAssetDecryptIfEncrypted(sya, destPath+".sya"); nil != syaErr {
logging.LogErrorf("copy sya from [%s] to [%s] failed: %s", sya, destPath+".sya", syaErr)
}
}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 574870b4e3..083d2266f8 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1627,7 +1627,10 @@ func removeDoc(box *Box, p string, luteEngine *lute.Lute) (ret *parse.Tree) {
}
generateAvHistoryInTree(ret, historyDir)
- copyDocAssetsToDataAssets(box.ID, p)
+ // 加密笔记本的 assets 不提升到全局
+ if !IsEncryptedBox(box.ID) {
+ copyDocAssetsToDataAssets(box.ID, p)
+ }
removeIDs := treenode.RootChildIDs(ret.ID)
dir := path.Dir(p)
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index c594f874cc..c2af8b6a82 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -151,7 +151,10 @@ func RemoveBox(boxID string) (err error) {
return
}
- copyBoxAssetsToDataAssets(boxID)
+ // 加密笔记本的 assets 不提升到全局 data/assets,避免密文污染全局或被全局索引
+ if !IsEncryptedBox(boxID) {
+ copyBoxAssetsToDataAssets(boxID)
+ }
}
unmount0(boxID)
diff --git a/kernel/model/upload.go b/kernel/model/upload.go
index 726fd8dc45..e64186d044 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -113,7 +113,7 @@ func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMa
f.Close()
return
}
- if err = filelock.WriteFileByReader(writePath, f); err != nil {
+ if err = writeAssetFile(writePath, f, bt.BoxID); err != nil {
f.Close()
return
}
@@ -140,6 +140,7 @@ func Upload(c *gin.Context) {
return
}
assetsDirPath := filepath.Join(util.DataDir, "assets")
+ var uploadBoxID string // 记录上传目标 boxID,供 writeAssetFile 判断是否需加密
if nil != form.Value["id"] {
id := form.Value["id"][0]
bt := treenode.GetBlockTree(id)
@@ -148,6 +149,7 @@ func Upload(c *gin.Context) {
ret.Msg = Conf.Language(71)
return
}
+ uploadBoxID = bt.BoxID
docDirLocalPath := filepath.Join(util.DataDir, bt.BoxID, path.Dir(bt.Path))
assetsDirPath = getAssetsDir(filepath.Join(util.DataDir, bt.BoxID), docDirLocalPath)
}
@@ -276,7 +278,7 @@ func Upload(c *gin.Context) {
f.Close()
break
}
- if err = filelock.WriteFileByReader(writePath, f); err != nil {
+ if err = writeAssetFile(writePath, f, uploadBoxID); err != nil {
logging.LogErrorf("write file failed: %s", err)
errFiles = append(errFiles, fName)
ret.Msg = err.Error()
@@ -357,8 +359,34 @@ func getAssetsDir(boxLocalPath, docDirLocalPath string) (assets string) {
if !filelock.IsExist(assets) {
assets = filepath.Join(boxLocalPath, "assets")
if !filelock.IsExist(assets) {
+ // 加密笔记本禁用全局 data/assets 回退,强制使用笔记本级 assets,避免明文资源泄漏到全局
+ boxID := filepath.Base(boxLocalPath)
+ if IsEncryptedBox(boxID) {
+ _ = os.MkdirAll(assets, 0755)
+ return
+ }
assets = filepath.Join(util.DataDir, "assets")
}
}
return
}
+
+// writeAssetFile 把 src 的内容写入 writePath。若 boxID 是已解锁的加密 box,先加密字节流再落盘;
+// 否则直接按 reader 写(走 filelock.WriteFileByReader 原路径,保留锁语义)。
+func writeAssetFile(writePath string, src io.Reader, boxID string) (err error) {
+ if boxID != "" {
+ if dek, decErr := GetDEK(boxID); decErr == nil && dek != nil {
+ // 已解锁的加密 box:全读 → 加密 → 落盘
+ raw, readErr := io.ReadAll(src)
+ if readErr != nil {
+ return readErr
+ }
+ enc, encErr := util.Encrypt(dek, raw)
+ if encErr != nil {
+ return encErr
+ }
+ return filelock.WriteFile(writePath, enc)
+ }
+ }
+ return filelock.WriteFileByReader(writePath, src)
+}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index a03730d094..9212b6555f 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -689,6 +689,11 @@ func serveAssets(ginServer *gin.Engine) {
return
}
+ // 加密笔记本的 assets 是密文,需先解密再输出
+ if serveEncryptedAsset(context, p) {
+ return
+ }
+
// 返回原始文件
setAssetsAttachmentDisposition(context, p)
http.ServeFile(context.Writer, context.Request, p)
@@ -702,7 +707,7 @@ func serveAssets(ginServer *gin.Engine) {
func serveSVG(context *gin.Context, assetAbsPath string) bool {
if strings.HasSuffix(assetAbsPath, ".svg") {
- data, err := os.ReadFile(assetAbsPath)
+ data, err := readAssetBytes(assetAbsPath)
if err != nil {
logging.LogErrorf("read svg file failed: %s", err)
return false
@@ -719,6 +724,54 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {
return false
}
+// readAssetBytes 读取 asset 文件字节。加密笔记本的 asset 是密文,自动解密后返回明文。
+func readAssetBytes(absPath string) ([]byte, error) {
+ data, err := os.ReadFile(absPath)
+ if err != nil {
+ return nil, err
+ }
+ if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" {
+ if dek, decErr := model.GetDEK(boxID); decErr == nil && dek != nil {
+ if plain, decErr := util.Decrypt(dek, data); decErr == nil {
+ return plain, nil
+ }
+ }
+ }
+ return data, nil
+}
+
+// serveEncryptedAsset 处理加密笔记本 asset 的 HTTP 输出。
+// 若 absPath 在已解锁的加密 box 下,读密文→解密→按扩展名设置 Content-Type→输出,返回 true;
+// 否则返回 false,由调用方走原 http.ServeFile 路径。
+func serveEncryptedAsset(context *gin.Context, absPath string) bool {
+ boxID := model.ExtractBoxIDFromAssetsPath(absPath)
+ if boxID == "" {
+ return false
+ }
+ dek, err := model.GetDEK(boxID)
+ if err != nil || dek == nil {
+ return false // 非加密 box 或未解锁,走原路径
+ }
+ ciphertext, readErr := os.ReadFile(absPath)
+ if readErr != nil {
+ context.Status(http.StatusNotFound)
+ return true
+ }
+ plain, decErr := util.Decrypt(dek, ciphertext)
+ if decErr != nil {
+ logging.LogErrorf("decrypt asset [%s] failed: %s", absPath, decErr)
+ context.Status(http.StatusInternalServerError)
+ return true
+ }
+ setAssetsAttachmentDisposition(context, absPath)
+ contentType := mime.TypeByExtension(filepath.Ext(absPath))
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ context.Data(200, contentType, plain)
+ return true
+}
+
func serveThumbnail(context *gin.Context, assetAbsPath, requestPath string) bool {
if style := context.Query("style"); style == "thumb" && model.NeedGenerateAssetsThumbnail(assetAbsPath) { // 请求缩略图
thumbnailPath := filepath.Join(util.TempDir, "thumbnails", "assets", requestPath)