An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Return DEK copy from cache, guard readDir against encrypted box, decrypt history static serve https://github.com/siyuan-note/siyuan/issues/18034
Daniel4d1b0f0690dc
diff --git a/kernel/api/file.go b/kernel/api/file.goindex 3f65f63dca..7e66fd7a03 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -41,9 +41,9 @@ import (// errMsgSeeKernelLog 接在 API 错误提示末尾,引导用户查看内核日志以获取完整信息(避免在 Msg 暴露工作空间绝对路径)。const errMsgSeeKernelLog = ". For details, see the SiYuan kernel log."-// rejectEncryptedBoxPath 检查 absPath 是否落在加密 box 目录下(含 symlink 绕过),是则返回 true。+// rejectEncryptedBoxPath 检查 absPath 是否落在加密笔记本目录下(含 symlink 绕过),是则返回 true。// 原始文件 API(getFile/putFile/copyFile/renameFile/removeFile)是绕过加密层的逃生口,-// 对加密 box 的任何文件读写都应拒绝——合法读写走专用 API(upload/getBlockKramdown 等,已加密感知),+// 对加密笔记本的任何文件读写都应拒绝——合法读写走专用 API(upload/getBlockKramdown 等,已加密感知),// 避免密文泄漏给插件或明文破坏加密格式。// 防止 symlink 绕过:找到最长已存在的父路径,解析 symlink 后拼回剩余路径,再检查是否落入加密 box。func rejectEncryptedBoxPath(absPath string) bool {@@ -191,7 +191,7 @@ func globalCopyFiles(c *gin.Context) {ret.Msg = err.Error()return}- // 在 MkdirAll 前拒绝加密 box 目录,避免在加密 box 内创建明文目录+ // 在 MkdirAll 前拒绝加密笔记本目录,避免在加密笔记本内创建明文目录if rejectEncryptedBoxPath(destDir) {ret.Code = -1ret.Msg = "copying encrypted notebook files is not supported via this API"@@ -225,7 +225,7 @@ func globalCopyFiles(c *gin.Context) {ret.Msg = "copying encrypted notebook files is not supported via this API"return}- // 拒绝目标已存在的 symlink:os.Create 会跟随 symlink,可能写入加密 box 内部+ // 拒绝目标已存在的 symlink:os.Create 会跟随 symlink,可能写入加密笔记本内部if li, lerr := os.Lstat(dest); lerr == nil && li.Mode()&os.ModeSymlink != 0 {ret.Code = -1ret.Msg = "destination path is a symlink, which is not supported"@@ -311,7 +311,7 @@ func workspaceCopyFiles(c *gin.Context) {ret.Msg = err.Error()return}- // 在 MkdirAll 前拒绝加密 box 目录,避免在加密 box 内创建明文目录+ // 在 MkdirAll 前拒绝加密笔记本目录,避免在加密笔记本内创建明文目录if rejectEncryptedBoxPath(destDir) {ret.Code = -1ret.Msg = "copying encrypted notebook files is not supported via this API"@@ -395,7 +395,7 @@ func copyFile(c *gin.Context) {return}- // 加密 box 的文件不允许通过原始文件 API 复制(src 读出密文/明文,dest 写入破坏加密存储)+ // 加密笔记本的文件不允许通过原始文件 API 复制(src 读出密文/明文,dest 写入破坏加密存储)if rejectEncryptedBoxPath(src) || rejectEncryptedBoxPath(dest) {ret.Code = -1ret.Msg = "copying encrypted notebook files is not supported via this API"@@ -461,7 +461,7 @@ func getFile(c *gin.Context) {c.JSON(http.StatusAccepted, ret)return}- // 加密 box 的任何文件都不允许通过原始文件 API 读取(不只 .sy):+ // 加密笔记本的任何文件都不允许通过原始文件 API 读取(不只 .sy):// 密文对插件无意义,且可能被误解析或泄漏;合法读取走专用 API(已加密感知)if rejectEncryptedBoxPath(fileAbsPath) {ret.Code = -1@@ -627,6 +627,13 @@ func readDir(c *gin.Context) {ret.Msg = err.Error()return}+ // 加密笔记本的任何目录都不允许通过原始文件 API 枚举(不只 .sy):+ // 目录结构、文档 ID、随机化资产名和时间戳可能泄漏信息;合法读取走专用 API(已加密感知)+ if rejectEncryptedBoxPath(dirAbsPath) {+ ret.Code = -1+ ret.Msg = "access to encrypted notebook files is not supported via this API"+ return+ }info, err := os.Stat(dirAbsPath)if os.IsNotExist(err) {ret.Code = http.StatusNotFound@@ -718,7 +725,7 @@ func renameFile(c *gin.Context) {ret.Msg = err.Error()return}- // 加密 box 的文件不允许通过原始文件 API 重命名(会破坏加密存储结构/跨 box 搬运密文)+ // 加密笔记本的文件不允许通过原始文件 API 重命名(会破坏加密存储结构/跨 box 搬运密文)if rejectEncryptedBoxPath(srcAbsPath) || rejectEncryptedBoxPath(destAbsPath) {ret.Code = -1ret.Msg = "renaming encrypted notebook files is not supported via this API"@@ -792,7 +799,7 @@ func removeFile(c *gin.Context) {ret.Msg = err.Error()return}- // 加密 box 的文件不允许通过原始文件 API 删除(破坏加密存储结构)+ // 加密笔记本的文件不允许通过原始文件 API 删除(破坏加密存储结构)if rejectEncryptedBoxPath(fileAbsPath) {ret.Code = -1ret.Msg = "removing encrypted notebook files is not supported via this API"@@ -843,7 +850,7 @@ func putFile(c *gin.Context) {return}- // 加密 box 的任何文件都不允许通过原始文件 API 写入(不只 .sy):+ // 加密笔记本的任何文件都不允许通过原始文件 API 写入(不只 .sy):// 明文写入会破坏密文格式或污染加密存储;合法写入走专用 API(已加密感知)if rejectEncryptedBoxPath(fileAbsPath) {ret.Code = -1diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex 6c4c6785ac..8d4c40a099 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -433,7 +433,7 @@ func LockBox(boxID string) {cachedDEKsLock.Unlock()sql.RemoveEncryptedDBFile(boxID)treenode.RemoveEncryptedBlockTreeDBFile(boxID)- // 清空明文缓存:锁定后任何加密 box 的明文都不应残留内存+ // 清空明文缓存:锁定后任何加密笔记本的明文都不应残留内存cache.ClearTreeCache()sql.ClearCache()cache.ClearDocsIAL()@@ -495,7 +495,8 @@ func UnwrapDEK(boxID string, enc *conf.BoxEncryption, kek []byte) error {return nil}-// GetDEK 取已缓存的 DEK。filesys/assets/db 加解密时调用。+// GetDEK 取已缓存的 DEK。返回副本,避免外部零化影响缓存。+// filesys/assets/db 加解密时调用。func GetDEK(boxID string) ([]byte, error) {cachedDEKsLock.RLock()defer cachedDEKsLock.RUnlock()@@ -503,7 +504,9 @@ func GetDEK(boxID string) ([]byte, error) {if !ok {return nil, errors.New("no DEK cached for box " + boxID)}- return dek, nil+ ret := make([]byte, len(dek))+ copy(ret, dek)+ return ret, nil}// ClearDEK 清除指定笔记本的 DEK。Unmount 单个加密笔记本时调用。@@ -590,7 +593,7 @@ func IsEncryptedBox(boxID string) bool {}// IsSameCryptoBoundary 判断 srcBox 与 dstBox 是否处于同一加密边界(跨 box 操作是否安全)。-// 普通笔记本之间允许(都不加密);加密笔记本仅允许同一 box 内部操作——两个不同的加密 box 各有独立 DEK,+// 普通笔记本之间允许(都不加密);加密笔记本仅允许同一 box 内部操作——两个不同的加密笔记本各有独立 DEK,// 之间互为"加密边界外",跨 box 移动/合并会用错 DEK 导致密文损坏。供 MoveDocs/Doc2Heading 等跨 box 操作校验。func IsSameCryptoBoundary(srcBox, dstBox string) bool {srcEnc := IsEncryptedBox(srcBox)@@ -602,7 +605,7 @@ func IsSameCryptoBoundary(srcBox, dstBox string) bool {}// IsBlockRefCrossingBoundary 判断从 srcBoxID 引用 defBlockID 是否跨越加密边界。-// 加密笔记本禁止跨边界块引(双向):加密 box 的块只能引用同一加密 box 内的块,普通 box 的块不能引用加密 box 的块。+// 加密笔记本禁止跨边界块引(双向):加密笔记本的块只能引用同一加密笔记本内的块,普通 box 的块不能引用加密笔记本的块。// 供 transaction 落库时兜底校验,防止手工输入/拖拽/粘贴/API 直调绕过前端搜索分流。func IsBlockRefCrossingBoundary(srcBoxID, defBlockID string) bool {if "" == defBlockID {@@ -616,7 +619,7 @@ func IsBlockRefCrossingBoundary(srcBoxID, defBlockID string) bool {// 源在普通 box:def 块必须在普通 box(查全局 blocktree,且其 box 非加密)bt := treenode.GetBlockTree(defBlockID)if nil == bt {- // 全局查不到时遍历加密 box 查找,防止对向漏判(普通 box 引用加密 box 块)+ // 全局查不到时遍历加密笔记本查找,防止对向漏判(普通 box 引用加密笔记本块)for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {if encBT := treenode.GetBlockTreeInBox(defBlockID, encBoxID); nil != encBT {bt = encBT@@ -637,8 +640,8 @@ func IsEncryptedAssetPath(absPath string) bool {return boxID != "" && IsEncryptedBox(boxID)}-// GetDEKIfUnlocked 返回已解锁加密 box 的 DEK。-// 非加密 box 返回 (nil, nil)——filesys 据此原样读写,对普通笔记本透明。+// GetDEKIfUnlocked 返回已解锁加密笔记本的 DEK(副本)。+// 非加密笔记本返回 (nil, nil)——filesys 据此原样读写,对普通笔记本透明。// 加密但未解锁(DEK 不在内存)返回 (nil, error)——filesys 的加解密函数遇 error 后拒绝读写,// 避免加密笔记本在未解锁状态下静默以明文落盘(深度防御,见 issue #18034)。func GetDEKIfUnlocked(boxID string) ([]byte, error) {@@ -651,7 +654,9 @@ func GetDEKIfUnlocked(boxID string) ([]byte, error) {if !ok {return nil, errors.New("encrypted notebook is locked, please unlock it first")}- return dek, nil+ ret := make([]byte, len(dek))+ copy(ret, dek)+ return ret, nil}// extractBoxIDFromPath 从 data 目录下的绝对路径反推 boxID。@@ -683,8 +688,34 @@ func ExtractBoxIDFromAssetsPath(absPath string) string {return boxID}+// ExtractBoxIDFromHistoryPath 从历史目录下的绝对路径反推 boxID。+// 路径形如 <HistoryDir>/<timestamp>-<op>/<boxID>/...,切出紧跟在时间戳目录后的一段。+// 若路径不在 HistoryDir 下或 boxID 非合法 ID 模式,返回空串。+func ExtractBoxIDFromHistoryPath(absPath string) string {+ absPath = filepath.ToSlash(absPath)+ historyDir := filepath.ToSlash(util.HistoryDir)+ rel, err := filepath.Rel(historyDir, absPath)+ if err != nil {+ return ""+ }+ rel = filepath.ToSlash(rel)+ if strings.HasPrefix(rel, "..") || rel == "." || rel == "" {+ return ""+ }+ parts := strings.SplitN(rel, "/", 3)+ if len(parts) < 2 {+ return ""+ }+ // parts[0] = timestamp-op, parts[1] = boxID+ boxID := parts[1]+ if !ast.IsNodeIDPattern(boxID) {+ return ""+ }+ return boxID+}+// copyAssetDecryptIfEncrypted 把 srcPath 的 asset 复制到 destPath。-// 若 srcPath 在已解锁的加密 box 下,读密文→解密→写明文到 destPath(导出目录);+// 若 srcPath 在已解锁的加密笔记本下,读密文→解密→写明文到 destPath(导出目录);// 否则走 filelock.Copy 原路径(字节级复制,密文/明文均可)。// EncryptFile 用 fileKey(DEK 派生子密钥)加密 .sy 文档字节,AAD 绑定 boxID。// 与 filesys.encryptData/decryptData 使用相同的 AAD(boxID 级),保证读写一致。@@ -717,7 +748,7 @@ func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {if boxID != "" && IsEncryptedBox(boxID) {dek, err := GetDEKIfUnlocked(boxID)if err != nil {- // 加密 box 未解锁:fail-closed,拒绝复制(不复制密文,避免泄漏无效文件)+ // 加密笔记本未解锁:fail-closed,拒绝复制(不复制密文,避免泄漏无效文件)return errors.New(Conf.Language(314))}raw, readErr := filelock.ReadFile(srcPath)diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex cdb46b6375..c195cb133d 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -704,6 +704,10 @@ func serveAssets(ginServer *gin.Engine) {ginServer.GET("/history/*path", model.CheckAuth, model.CheckAdminRole, func(context *gin.Context) {p := filepath.Join(util.HistoryDir, context.Param("path"))+ // 加密笔记本的历史是密文(.sy/assets/AV),需先解密再输出+ if serveEncryptedHistory(context, p) {+ return+ }http.ServeFile(context.Writer, context.Request, p)})}@@ -736,7 +740,7 @@ func readAssetBytes(absPath string) ([]byte, error) {if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" && model.IsEncryptedBox(boxID) {dek, dekErr := model.GetDEKIfUnlocked(boxID)if dekErr != nil {- return nil, dekErr // 加密 box 未解锁:fail-closed,不返回密文+ return nil, dekErr // 加密笔记本未解锁:fail-closed,不返回密文}plain, decErr := model.DecryptAsset(boxID, dek, data)if decErr != nil {@@ -748,7 +752,7 @@ func readAssetBytes(absPath string) ([]byte, error) {}// serveEncryptedAsset 处理加密笔记本 asset 的 HTTP 输出。-// 若 absPath 在已解锁的加密 box 下,读密文→解密→按扩展名设置 Content-Type→输出,返回 true;+// 若 absPath 在已解锁的加密笔记本下,读密文→解密→按扩展名设置 Content-Type→输出,返回 true;// 否则返回 false,由调用方走原 http.ServeFile 路径。func serveEncryptedAsset(context *gin.Context, absPath string) bool {boxID := model.ExtractBoxIDFromAssetsPath(absPath)@@ -757,7 +761,7 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {}dek, err := model.GetDEKIfUnlocked(boxID)if err != nil {- // 加密 box 未解锁:fail-closed,返回 403,不走 ServeFile(避免返回密文)+ // 加密笔记本未解锁:fail-closed,返回 403,不走 ServeFile(避免返回密文)context.Status(http.StatusForbidden)return true}@@ -787,6 +791,53 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {return true}+// serveEncryptedHistory 处理加密笔记本历史文件的 HTTP 输出。+// 若 absPath 在已解锁的加密笔记本下,读密文→解密→按扩展名设置 Content-Type→输出,返回 true;+// 若加密但未解锁,返回 403,返回 true,不走 ServeFile(避免返回密文);+// 否则返回 false,由调用方走原 http.ServeFile 路径。+func serveEncryptedHistory(context *gin.Context, absPath string) bool {+ boxID := model.ExtractBoxIDFromHistoryPath(absPath)+ if boxID == "" || !model.IsEncryptedBox(boxID) {+ return false // 非加密 box,走原路径+ }+ dek, err := model.GetDEKIfUnlocked(boxID)+ if err != nil {+ // 加密笔记本未解锁:fail-closed,返回 403,不走 ServeFile(避免返回密文)+ context.Status(http.StatusForbidden)+ return true+ }+ ciphertext, readErr := os.ReadFile(absPath)+ if readErr != nil {+ context.Status(http.StatusNotFound)+ return true+ }+ var plain []byte+ var decErr error+ if strings.HasSuffix(absPath, ".sy") {+ plain, decErr = model.DecryptFile(boxID, dek, ciphertext)+ } else if strings.Contains(absPath, "assets"+string(os.PathSeparator)) {+ plain, decErr = model.DecryptAsset(boxID, dek, ciphertext)+ } else if strings.Contains(absPath, "storage"+string(os.PathSeparator)+"av"+string(os.PathSeparator)) {+ // AV 定义在历史中也用加密存储,暂用 DecryptAsset 解密(与 assets 同模式),+ // 后续可切换为专用 AV 解密函数+ plain, decErr = model.DecryptAsset(boxID, dek, ciphertext)+ } else {+ // 其他历史文件(如 JSON 元数据等)尝试用 asset 解密方式+ plain, decErr = model.DecryptAsset(boxID, dek, ciphertext)+ }+ if decErr != nil {+ logging.LogErrorf("decrypt history [%s] failed: %s", absPath, decErr)+ context.Status(http.StatusInternalServerError)+ return true+ }+ 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 {// 加密笔记本的资源是密文,imaging.Open 无法解析,跳过缩略图生成(由 serveEncryptedAsset 解密输出原图)if model.IsEncryptedAssetPath(assetAbsPath) {