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: Clean up decrypted repo temp files on LockBox (diff/rollback/sync/conflicts), add defer Remove for rollback and conflict temp files, check box lock on /repo/diff route, add repo to ClearTempFiles https://github.com/siyuan-note/siyuan/issues/18034
Daniel4e575cbfa06c
diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex b3adbae9c0..fe6af49be2 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -705,6 +705,20 @@ func GetAssetAbsPathInBox(relativePath, boxID string) (string, error) {if !gulu.File.IsSubPath(util.WorkspaceDir, p) {return "", fmt.Errorf("[%s] is not sub path of workspace", p)}+ // 解析符号链接/目录联接,防止软链接跳出资产根目录+ if realP, evalErr := filepath.EvalSymlinks(p); evalErr == nil && realP != p {+ if !gulu.File.IsSubPath(util.WorkspaceDir, realP) {+ return "", fmt.Errorf("symlink [%s] resolves outside workspace: [%s]", p, realP)+ }+ // 验证解析后的路径仍在 <boxID>/assets/ 或全局 data/assets/ 下+ expectedPrefix := filepath.Join(util.DataDir, "assets")+ if boxID != "" {+ expectedPrefix = filepath.Join(util.DataDir, boxID, "assets")+ }+ if !gulu.File.IsSubPath(expectedPrefix, realP) {+ return "", fmt.Errorf("symlink [%s] resolves outside assets directory: [%s]", p, realP)+ }+ }return p, nil}// 非加密 box 的资源可能回退到全局 data/assets(兼容旧笔记本结构)@@ -741,6 +755,12 @@ func getAssetAbsPath(relativePath string, includeEncrypted bool) (absPath stringif !gulu.File.IsSubPath(util.WorkspaceDir, p) {return "", fmt.Errorf("[%s] is not sub path of workspace", p)}+ // 解析符号链接,防止软链接跳出工作区+ if realP, evalErr := filepath.EvalSymlinks(p); evalErr == nil && realP != p {+ if !gulu.File.IsSubPath(util.WorkspaceDir, realP) {+ return "", fmt.Errorf("symlink [%s] resolves outside workspace: [%s]", p, realP)+ }+ }return p, nil}diff --git a/kernel/model/box.go b/kernel/model/box.goindex 9c0cfb76c1..b6d1e284de 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -768,6 +768,9 @@ func ClearTempFiles() {thumbnailsTmp := filepath.Join(util.TempDir, "thumbnails")clearTempDir(thumbnailsTmp, &count, &size)++ repoTmp := filepath.Join(util.TempDir, "repo")+ clearTempDir(repoTmp, &count, &size)}func clearTempDir(dir string, count *int, size *int64) {diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex ade4608693..a2ebae2ce3 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -732,6 +732,24 @@ func LockBox(boxID string) {cache.ClearDocsIAL()cache.ClearBlocksIAL()cache.ClearAVCache()+ // 清理 repo 临时目录中该加密 box 的解密文件(diff/rollback/sync conflicts)+ repoDirs := []string{+ filepath.Join(util.TempDir, "repo", "diff", boxID),+ filepath.Join(util.TempDir, "repo", "rollback", boxID),+ }+ for _, d := range repoDirs {+ if rmErr := os.RemoveAll(d); rmErr != nil {+ logging.LogWarnf("remove repo dir for box [%s] failed: %s", boxID, rmErr)+ }+ }+ // sync/conflicts 路径带时间戳前缀,用通配匹配+ if matches, globErr := filepath.Glob(filepath.Join(util.TempDir, "repo", "sync", "conflicts", "*", boxID)); globErr == nil {+ for _, m := range matches {+ if rmErr := os.RemoveAll(m); rmErr != nil {+ logging.LogWarnf("remove repo sync conflict dir for box [%s] failed: %s", boxID, rmErr)+ }+ }+ }}// LockAllBoxes 清除所有已缓存的 DEK 并删除所有加密 db 文件。退出登录或全局锁定时调用。@@ -751,6 +769,10 @@ func LockAllBoxes() {cache.ClearDocsIAL()cache.ClearBlocksIAL()cache.ClearAVCache()+ // 清理所有 repo 临时目录中的解密文件+ if rmErr := os.RemoveAll(filepath.Join(util.TempDir, "repo")); rmErr != nil {+ logging.LogErrorf("remove repo directory failed: %s", rmErr)+ }}// WrapNewDEK 用给定 KEK 生成随机 DEK 并包络,返回 BoxEncryption 元数据。diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 8293d66181..350effca68 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -271,6 +271,8 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {logging.LogErrorf("write file [%s] failed: %v", filepath.Join(tempRepoDiffDir, file.Path), err)return}+ // 解密后的临时文件在函数返回时清理,避免加密文档明文残留在磁盘+ defer os.Remove(from)if strings.HasSuffix(file.Path, ".sy") {boxID := strings.TrimPrefix(file.Path, "/")@@ -1998,6 +2000,8 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,continue}}+ // 解密后的冲突文件在函数返回时清理+ defer os.Remove(absPath)}tree, loadTreeErr := loadTree(absPath, luteEngine)if nil != loadTreeErr {diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 12eec0a9a5..97ec35301f 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -18,6 +18,7 @@ package serverimport ("bytes"+ "context""errors""fmt""html/template"@@ -940,6 +941,14 @@ func serveRepoDiff(ginServer *gin.Engine) {context.Status(http.StatusUnauthorized)return}+ // 从路径提取 boxID,加密笔记本已锁定时拒绝访问(锁定后 repo 预览解密文件仍存在磁盘上)+ parts := strings.SplitN(strings.TrimPrefix(requestPath, "/"), "/", 2)+ if len(parts) >= 1 && model.IsEncryptedBox(parts[0]) {+ if _, dekErr := model.GetDEKIfUnlocked(parts[0]); dekErr != nil {+ context.Status(http.StatusForbidden)+ return+ }+ }p := filepath.Join(repoDiffBaseDir, requestPath)if !gulu.File.IsSubPath(repoDiffBaseDir, p) {context.Status(http.StatusUnauthorized)@@ -1124,11 +1133,69 @@ func serveWebSocket(ginServer *gin.Engine) {})}+// encryptedBoxAwareWebdavFS 包装 webdav.Dir,拦截所有指向加密笔记本的访问。+// 加密笔记本的文件只能通过 assets/serve 路由访问,WebDAV 直接暴露原始磁盘会绕过所有加密流程。+type encryptedBoxAwareWebdavFS struct {+ inner webdav.FileSystem+}++func (fs *encryptedBoxAwareWebdavFS) isEncryptedBoxPath(name string) bool {+ rel := filepath.ToSlash(name)+ if idx := strings.Index(rel, "/data/"); idx >= 0 {+ candidate := rel[idx+len("/data/"):]+ if slashIdx := strings.Index(candidate, "/"); slashIdx > 0 {+ boxID := candidate[:slashIdx]+ if model.IsEncryptedBox(boxID) {+ return true+ }+ }+ }+ return false+}++func (fs *encryptedBoxAwareWebdavFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error {+ if fs.isEncryptedBoxPath(name) {+ return os.ErrPermission+ }+ return fs.inner.Mkdir(ctx, name, perm)+}++func (fs *encryptedBoxAwareWebdavFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {+ if fs.isEncryptedBoxPath(name) {+ return nil, os.ErrPermission+ }+ return fs.inner.OpenFile(ctx, name, flag, perm)+}++func (fs *encryptedBoxAwareWebdavFS) RemoveAll(ctx context.Context, name string) error {+ if fs.isEncryptedBoxPath(name) {+ return os.ErrPermission+ }+ return fs.inner.RemoveAll(ctx, name)+}++func (fs *encryptedBoxAwareWebdavFS) Rename(ctx context.Context, oldName, newName string) error {+ if fs.isEncryptedBoxPath(oldName) || fs.isEncryptedBoxPath(newName) {+ return os.ErrPermission+ }+ return fs.inner.Rename(ctx, oldName, newName)+}++func (fs *encryptedBoxAwareWebdavFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {+ if fs.isEncryptedBoxPath(name) {+ return nil, os.ErrPermission+ }+ return fs.inner.Stat(ctx, name)+}+func serveWebDAV(ginServer *gin.Engine) {- // REF: https://github.com/fungaren/gin-webdav+ // 自定义 WebDAV 文件系统包装——拒绝加密笔记本的所有访问+ // 加密笔记本的读写必须通过 assets/serve 路由的 box-aware + 解密流程,+ // WebDAV 直接访问原始文件系统会绕过所有这些安全控制+ encBoxAwareFS := &encryptedBoxAwareWebdavFS{inner: webdav.Dir(util.WorkspaceDir)}handler := webdav.Handler{Prefix: "/webdav/",- FileSystem: webdav.Dir(util.WorkspaceDir),+ FileSystem: encBoxAwareFS,LockSystem: webdav.NewMemLS(),Logger: func(r *http.Request, err error) {if nil != err {