Skip to content

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

:lock: Unify encryption paths, partition assets by box, fix nil panic https://github.com/siyuan-note/siyuan/issues/18034

Danielffc005e3cd9d
diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.go
index 6736aa15bd..d0a22573da 100644
--- a/kernel/av/encrypted_hook.go
+++ b/kernel/av/encrypted_hook.go
@@ -255,3 +255,13 @@ func decryptAVData(boxID string, data []byte) ([]byte, error) {
avKey := util.DeriveSubKey(dek, "siyuan/av")
return util.DecryptWithAAD(avKey, data, []byte(boxID))
}
+
+// EncryptAVData 是 encryptAVData 的导出版本,供 model 层(导入/复制数据库等)统一加密 AV 定义。
+func EncryptAVData(boxID string, data []byte) ([]byte, error) {
+ return encryptAVData(boxID, data)
+}
+
+// DecryptAVData 是 decryptAVData 的导出版本。
+func DecryptAVData(boxID string, data []byte) ([]byte, error) {
+ return decryptAVData(boxID, data)
+}
diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.go
index 5ea2ab4a68..37ea5161c4 100644
--- a/kernel/filesys/tree.go
+++ b/kernel/filesys/tree.go
@@ -257,7 +257,7 @@ func DocIAL(absPath string) (ret map[string]string) {
logging.LogErrorf("read file [%s] failed: %s", absPath, readErr)
return nil
}
- plain, decErr := util.Decrypt(dek, raw)
+ plain, decErr := decryptData(boxID, raw)
if decErr != nil {
// 解密失败(可能文件损坏或密钥不匹配):返回空 map 而非 nil,
// 避免 LoadTreeByData 的父文档补全逻辑把 nil 误判为"文档缺失"而凭空创建文档
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 0e3c119fa6..541ce0cbbd 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -69,7 +69,12 @@ func GetAssetImgSize(assetPath string) (width, height int) {
return
}
-func GetAssetPathByHash(hash string) string {
+// GetAssetPathByHash 按 hash 查已存在的 asset 路径用于去重。boxID 非空且为加密 box 时返回空——
+// 加密 box 不参与全局去重(避免复用普通明文 asset);普通 box 走全局 cache/SQL(加密 box 数据不在全局表)。
+func GetAssetPathByHash(hash, boxID string) string {
+ if boxID != "" && IsEncryptedBox(boxID) {
+ return "" // 加密 box:跳过全局去重,强制新写(防跨边界复用明文 asset)
+ }
assetHash := cache.GetAssetHash(hash)
if nil == assetHash {
sqlAsset := sql.QueryAssetByHash(hash)
@@ -306,11 +311,31 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,
name = filepath.Base(u)
name = util.FilterUploadFileName(name)
name = "network-asset-" + name
- name = util.AssetName(name, ast.NewNodeID())
- writePath := filepath.Join(assetsDirPath, name)
- if err = filelock.Copy(u, writePath); err != nil {
- logging.LogErrorf("copy [%s] to [%s] failed: %s", u, writePath, err)
- continue
+ var writePath string
+ if IsEncryptedBox(tree.Box) {
+ // 加密 box:脱敏文件名 + 加密内容(writeAssetFile 内部按路径反查 box 加密)+ 写映射
+ diskName := encryptedAssetName(util.Ext(name), ast.NewNodeID())
+ writePath = filepath.Join(assetsDirPath, diskName)
+ f, openErr := os.Open(u)
+ if openErr != nil {
+ logging.LogErrorf("open [%s] failed: %s", u, openErr)
+ continue
+ }
+ if err = writeAssetFile(writePath, f, tree.Box); err != nil {
+ logging.LogErrorf("write encrypted asset [%s] failed: %s", writePath, err)
+ f.Close()
+ continue
+ }
+ f.Close()
+ writeAssetNameMapping(tree.Box, diskName, name)
+ name = diskName
+ } else {
+ name = util.AssetName(name, ast.NewNodeID())
+ writePath = filepath.Join(assetsDirPath, name)
+ if err = filelock.Copy(u, writePath); err != nil {
+ logging.LogErrorf("copy [%s] to [%s] failed: %s", u, writePath, err)
+ continue
+ }
}
setAssetsLinkDest(destNode, dest, "assets/"+name)
@@ -416,12 +441,25 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,
name += ext
}
}
- name = util.AssetName(name, ast.NewNodeID())
- name = "network-asset-" + name
- writePath := filepath.Join(assetsDirPath, name)
- if err = filelock.WriteFile(writePath, data); err != nil {
- logging.LogErrorf("write downloaded network asset [%s] to local asset [%s] failed: %s", u, writePath, err)
- continue
+ if IsEncryptedBox(tree.Box) {
+ // 加密 box:脱敏文件名 + 加密内容 + 写映射
+ name = "network-asset-" + name
+ diskName := encryptedAssetName(util.Ext(name), ast.NewNodeID())
+ writePath := filepath.Join(assetsDirPath, diskName)
+ if err = writeAssetFile(writePath, bytes.NewReader(data), tree.Box); err != nil {
+ logging.LogErrorf("write encrypted network asset [%s] failed: %s", writePath, err)
+ continue
+ }
+ writeAssetNameMapping(tree.Box, diskName, name)
+ name = diskName
+ } else {
+ name = util.AssetName(name, ast.NewNodeID())
+ name = "network-asset-" + name
+ writePath := filepath.Join(assetsDirPath, name)
+ if err = filelock.WriteFile(writePath, data); err != nil {
+ logging.LogErrorf("write downloaded network asset [%s] to local asset [%s] failed: %s", u, writePath, err)
+ continue
+ }
}
setAssetsLinkDest(destNode, dest, "assets/"+name)
@@ -589,6 +627,9 @@ func getAssetAbsPath(relativePath string) (absPath string, err error) {
return "", errors.New(Conf.Language(0))
}
for _, notebook := range notebooks {
+ if IsEncryptedBox(notebook.ID) {
+ continue // 加密 box 的资源不参与全局路径解析(孤岛,资源不跨边界)
+ }
notebookAbsPath := filepath.Join(util.DataDir, notebook.ID)
filelock.Walk(notebookAbsPath, func(path string, d fs.DirEntry, err error) error {
if isSkipFile(d.Name()) {
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 8a9fdd6566..a81bd789d9 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -1656,14 +1656,14 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error)
return
}
- // 加密 box 的 AV 是密文,需先解密再处理
- if avBoxID != "" {
- if dek, decErr := GetDEK(avBoxID); decErr == nil && dek != nil {
- if data, decErr = util.Decrypt(dek, data); decErr != nil {
- logging.LogErrorf("decrypt attribute view [%s] failed: %s", avID, decErr)
- err = decErr
- return
- }
+ // 加密 box 的 AV 是密文,需先解密再处理(av.DecryptAVData 内部按 box 加密/已解锁路由)
+ if avBoxID != "" && IsEncryptedBox(avBoxID) {
+ var decErr error
+ data, decErr = av.DecryptAVData(avBoxID, data)
+ if decErr != nil {
+ logging.LogErrorf("decrypt attribute view [%s] failed: %s", avID, decErr)
+ err = decErr
+ return
}
}
@@ -1694,16 +1694,16 @@ func DuplicateDatabaseBlock(avID string) (newAvID, newBlockID string, err error)
return
}
- // 加密 box 的新 AV 定义也存笔记本级目录,且需 DEK 加密
+ // 加密 box 的新 AV 定义也存笔记本级目录,且需 avKey 加密
newAvPath := filepath.Join(util.DataDir, "storage", "av", newAvID+".json")
if avBoxID != "" {
newAvPath = filepath.Join(util.DataDir, avBoxID, "storage", "av", newAvID+".json")
- if dek, decErr := GetDEK(avBoxID); decErr == nil && dek != nil {
- if data, decErr = util.Encrypt(dek, data); decErr != nil {
- logging.LogErrorf("encrypt attribute view [%s] failed: %s", newAvID, decErr)
- err = decErr
- return
- }
+ var encErr error
+ data, encErr = av.EncryptAVData(avBoxID, data)
+ if encErr != nil {
+ logging.LogErrorf("encrypt attribute view [%s] failed: %s", newAvID, encErr)
+ err = encErr
+ return
}
av.SetAVBoxID(newAvID, avBoxID)
}
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index 14a9ee23d2..a902aa85e4 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -17,7 +17,6 @@
package model
import (
- "errors"
"fmt"
"os"
"path/filepath"
@@ -682,12 +681,9 @@ func RenderHistoryAttributeView(blockID, avID, viewID, query string, page, pageS
}
}
if histBoxID != "" && IsEncryptedBox(histBoxID) {
- dek, decErr := GetDEK(histBoxID)
- if decErr != nil || dek == nil {
- err = errors.New(Conf.Language(314))
- return
- }
- if data, decErr = util.Decrypt(dek, data); decErr != nil {
+ var decErr error
+ data, decErr = av.DecryptAVData(histBoxID, data)
+ if decErr != nil {
logging.LogErrorf("decrypt history AV [%s] failed: %s", avID, decErr)
err = decErr
return
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 0d0f524ae8..33f6368c5c 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -655,6 +655,19 @@ func ExtractBoxIDFromAssetsPath(absPath string) string {
// copyAssetDecryptIfEncrypted 把 srcPath 的 asset 复制到 destPath。
// 若 srcPath 在已解锁的加密 box 下,读密文→解密→写明文到 destPath(导出目录);
// 否则走 filelock.Copy 原路径(字节级复制,密文/明文均可)。
+// EncryptFile 用 fileKey(DEK 派生子密钥)加密 .sy 文档字节,AAD 绑定 boxID。
+// 与 filesys.encryptData/decryptData 使用相同的 AAD(boxID 级),保证读写一致。
+func EncryptFile(boxID string, dek, plaintext []byte) ([]byte, error) {
+ fileKey := util.DeriveSubKey(dek, "siyuan/file")
+ return util.EncryptWithAAD(fileKey, plaintext, []byte(boxID))
+}
+
+// DecryptFile 对应解密。
+func DecryptFile(boxID string, dek, ciphertext []byte) ([]byte, error) {
+ fileKey := util.DeriveSubKey(dek, "siyuan/file")
+ return util.DecryptWithAAD(fileKey, ciphertext, []byte(boxID))
+}
+
// EncryptAsset 用 assetKey(DEK 派生子密钥)加密 asset 字节,AAD 绑定 boxID。
// 供 assets/.names.json/.sya 等资源类数据统一加密,与 .sy(fileKey)和 AV(avKey)用途分离。
func EncryptAsset(boxID string, dek, plaintext []byte) ([]byte, error) {
diff --git a/kernel/model/history.go b/kernel/model/history.go
index 91a7e60db4..362b70d72c 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -176,12 +176,14 @@ func GetDocHistoryContent(historyPath, keyword string, highlight bool) (id, root
if len(pathParts) >= 2 {
histBoxID := pathParts[1]
if IsEncryptedBox(histBoxID) {
- dek, decErr := GetDEK(histBoxID)
- if decErr != nil || dek == nil {
+ dek, dekErr := GetDEKIfUnlocked(histBoxID)
+ if dekErr != nil {
err = errors.New(Conf.Language(314))
return
}
- if data, decErr = util.Decrypt(dek, data); decErr != nil {
+ var decErr error
+ data, decErr = DecryptFile(histBoxID, dek, data)
+ if decErr != nil {
logging.LogErrorf("decrypt history [%s] failed: %s", historyPath, decErr)
err = decErr
return
@@ -296,12 +298,17 @@ func RollbackDocHistory(historyPath string) (err error) {
return
}
if IsEncryptedBox(boxID) {
- if dek, decErr := GetDEK(boxID); decErr == nil && dek != nil {
- srcData, srcReadErr = util.Decrypt(dek, srcData)
- if srcReadErr != nil {
- logging.LogErrorf("decrypt history [%s] failed: %s", srcPath, srcReadErr)
- return
- }
+ dek, dekErr := GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ err = errors.New(Conf.Language(314))
+ return
+ }
+ var decErr error
+ srcData, decErr = DecryptFile(boxID, dek, srcData)
+ if decErr != nil {
+ logging.LogErrorf("decrypt history [%s] failed: %s", srcPath, decErr)
+ err = decErr
+ return
}
}
tree, _ := loadTreeByData0(srcData)
diff --git a/kernel/model/import.go b/kernel/model/import.go
index d7b10eb9fb..c2e1b79526 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -402,11 +402,6 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
if err = os.MkdirAll(boxAVDir, 0755); err != nil {
return
}
- dek, dekErr := GetDEK(boxID)
- if dekErr != nil || dek == nil {
- err = errors.New("encrypted box not unlocked")
- return
- }
filelock.Walk(storageAvDir, func(path string, d fs.DirEntry, walkErr error) error {
if walkErr != nil || d == nil || d.IsDir() {
return walkErr
@@ -418,7 +413,8 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
if readErr != nil {
return readErr
}
- enc, encErr := util.Encrypt(dek, src)
+ // av.EncryptAVData 内部按 box 是否加密/已解锁路由,加密 box 用 avKey+AAD
+ enc, encErr := av.EncryptAVData(boxID, src)
if encErr != nil {
return encErr
}
@@ -470,14 +466,15 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {
// 加密笔记本的数据需先加密再落盘,导入的 .sy 原文是明文 JSON
if IsEncryptedBox(boxID) {
- dek, decErr := GetDEK(boxID)
- if decErr != nil || dek == nil {
+ dek, dekErr := GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
err = errors.New(Conf.Language(314))
return
}
- data, decErr = util.Encrypt(dek, data)
- if decErr != nil {
- logging.LogErrorf("encrypt import .sy failed: %s", decErr)
+ var encErr error
+ data, encErr = EncryptFile(boxID, dek, data)
+ if encErr != nil {
+ logging.LogErrorf("encrypt import .sy failed: %s", encErr)
return
}
}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index ba967d9e66..caa5048a3f 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -614,11 +614,11 @@ func decryptRepoDataIfNeeded(data []byte, filePath string) []byte {
if !IsEncryptedBox(boxID) {
return data
}
- dek, err := GetDEK(boxID)
- if err != nil || dek == nil {
- return data
+ dek, err := GetDEKIfUnlocked(boxID)
+ if err != nil {
+ return data // 加密 box 未解锁:同步快照解析返回原数据(调用方解析失败时按文件名回退)
}
- plain, err := util.Decrypt(dek, data)
+ plain, err := DecryptFile(boxID, dek, data)
if err != nil {
return data
}
diff --git a/kernel/model/tree.go b/kernel/model/tree.go
index 18f0b7fe61..fa40a269cc 100644
--- a/kernel/model/tree.go
+++ b/kernel/model/tree.go
@@ -168,14 +168,17 @@ func loadTree(localPath string, luteEngine *lute.Lute) (ret *parse.Tree, err err
return
}
- // 加密笔记本的 .sy 是密文,需先解密。从路径反推 boxID,已解锁的加密 box 才解密;
- // 非加密 box 或未解锁的加密 box 原样 data(非加密 box 的 .sy 是明文,能正常解析)。
- if boxID := extractBoxIDFromPath(localPath); boxID != "" {
- if dek, decErr := GetDEK(boxID); decErr == nil && dek != nil {
- if data, err = util.Decrypt(dek, data); err != nil {
- logging.LogErrorf("decrypt tree [path=%s] failed: %s", localPath, err)
- return
- }
+ // 加密笔记本的 .sy 是密文,需先解密。从路径反推 boxID,已解锁的加密 box 用 fileKey 解密;
+ // 加密 box 未解锁时返回错误(fail-closed);非加密 box 原样 data。
+ if boxID := extractBoxIDFromPath(localPath); boxID != "" && IsEncryptedBox(boxID) {
+ dek, dekErr := GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ err = dekErr
+ return
+ }
+ if data, err = DecryptFile(boxID, 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 5f26649dac..9eb322d649 100644
--- a/kernel/model/upload.go
+++ b/kernel/model/upload.go
@@ -96,7 +96,7 @@ func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMa
hash = "random_1_" + gulu.Rand.String(12)
}
- existAssetPath := GetAssetPathByHash(hash)
+ existAssetPath := GetAssetPathByHash(hash, bt.BoxID)
if "" != existAssetPath {
originalName := util.RemoveID(filepath.Base(existAssetPath))
if strings.ToLower(fName) != strings.ToLower(originalName) {
@@ -180,6 +180,10 @@ func Upload(c *gin.Context) {
ret.Msg = "Path [" + assetsDirPath + "] is not in workspace"
return
}
+ // assetsDirPath 可能指向加密 box(调用方未传 id),反查 boxID 让文件名脱敏/.names.json 生效
+ if pathBox := ExtractBoxIDFromAssetsPath(assetsDirPath); pathBox != "" && IsEncryptedBox(pathBox) {
+ uploadBoxID = pathBox
+ }
}
if !gulu.File.IsExist(assetsDirPath) {
if err = os.MkdirAll(assetsDirPath, 0755); err != nil {
@@ -236,7 +240,7 @@ func Upload(c *gin.Context) {
hash = "random_1_" + gulu.Rand.String(12)
}
- existAssetPath := GetAssetPathByHash(hash)
+ existAssetPath := GetAssetPathByHash(hash, uploadBoxID)
if "" != existAssetPath {
originalName := util.RemoveID(filepath.Base(existAssetPath))
if strings.ToLower(fName) != strings.ToLower(originalName) {
@@ -394,12 +398,19 @@ func getAssetsDir(boxLocalPath, docDirLocalPath string) (assets string) {
return
}
-// writeAssetFile 把 src 的内容写入 writePath。加密 box 必须已解锁(DEK 在内存)才写入——
-// 先全读 → 加密 → 落盘;加密但未解锁时返回错误(fail-closed,避免明文落盘到加密 box)。
+// writeAssetFile 把 src 的内容写入 writePath。从 writePath 反查真实 boxID 决定是否加密——
+// 不轻信传入的 boxID(调用方可能未传,或 assetsDirPath 指向加密 box 但 id 为空)。
+// 加密 box 必须已解锁(DEK 在内存)才写入;加密但未解锁返回错误(fail-closed,避免明文落盘)。
// 非加密 box 按 reader 直接写(走 filelock.WriteFileByReader 原路径,保留锁语义)。
func writeAssetFile(writePath string, src io.Reader, boxID string) (err error) {
- if boxID != "" && IsEncryptedBox(boxID) {
- dek, dekErr := GetDEKIfUnlocked(boxID)
+ // 以路径反查的 boxID 为准(防绕过):传入 boxID 与路径 box 不一致时以路径为准
+ pathBoxID := ExtractBoxIDFromAssetsPath(writePath)
+ actualBoxID := pathBoxID
+ if actualBoxID == "" {
+ actualBoxID = boxID // 路径不在 box 下(如全局 assets),回退传入值
+ }
+ if actualBoxID != "" && IsEncryptedBox(actualBoxID) {
+ dek, dekErr := GetDEKIfUnlocked(actualBoxID)
if dekErr != nil {
// 加密 box 未解锁:拒绝写入,避免明文落盘(深度防御,见 issue #18034)
return dekErr
@@ -409,7 +420,7 @@ func writeAssetFile(writePath string, src io.Reader, boxID string) (err error) {
if readErr != nil {
return readErr
}
- enc, encErr := EncryptAsset(boxID, dek, raw)
+ enc, encErr := EncryptAsset(actualBoxID, dek, raw)
if encErr != nil {
return encErr
}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index d6a772ae8d..c80528e5da 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -733,12 +733,16 @@ func readAssetBytes(absPath string) ([]byte, error) {
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
- }
+ if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" && model.IsEncryptedBox(boxID) {
+ dek, dekErr := model.GetDEKIfUnlocked(boxID)
+ if dekErr != nil {
+ return nil, dekErr // 加密 box 未解锁:fail-closed,不返回密文
+ }
+ plain, decErr := model.DecryptAsset(boxID, dek, data)
+ if decErr != nil {
+ return nil, decErr
}
+ return plain, nil
}
return data, nil
}
@@ -748,19 +752,21 @@ func readAssetBytes(absPath string) ([]byte, error) {
// 否则返回 false,由调用方走原 http.ServeFile 路径。
func serveEncryptedAsset(context *gin.Context, absPath string) bool {
boxID := model.ExtractBoxIDFromAssetsPath(absPath)
- if boxID == "" {
- return false
+ if boxID == "" || !model.IsEncryptedBox(boxID) {
+ return false // 非加密 box,走原路径
}
- dek, err := model.GetDEK(boxID)
- if err != nil || dek == nil {
- return false // 非加密 box 或未解锁,走原路径
+ dek, err := model.GetDEKIfUnlocked(boxID)
+ if err != nil {
+ // 加密 box 未解锁:fail-closed,返回 403,不走 ServeFile(避免返回密文)
+ context.Status(http.StatusForbidden)
+ return true
}
ciphertext, readErr := os.ReadFile(absPath)
if readErr != nil {
context.Status(http.StatusNotFound)
return true
}
- plain, decErr := util.Decrypt(dek, ciphertext)
+ plain, decErr := model.DecryptAsset(boxID, dek, ciphertext)
if decErr != nil {
logging.LogErrorf("decrypt asset [%s] failed: %s", absPath, decErr)
context.Status(http.StatusInternalServerError)
diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go
index 0735c91557..0e3c38646e 100644
--- a/kernel/treenode/blocktree.go
+++ b/kernel/treenode/blocktree.go
@@ -167,7 +167,9 @@ func GetBlockTreesByType(typ string) (ret []*BlockTree) {
func GetBlockTreeByBoxPath(boxID, path string) (ret *BlockTree) {
ret = &BlockTree{}
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND path = ?"
- err := queryRowForBox(boxID, sqlStmt, boxID, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
+ row := queryRowForBox(boxID, sqlStmt, boxID, path)
+ if row == nil { return }
+ err := row.Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
if err != nil {
ret = nil
if errors.Is(err, sql.ErrNoRows) {
@@ -206,7 +208,9 @@ func CountBlocks() (ret int) {
func GetBlockTreeRootByPath(boxID, path string) (ret *BlockTree) {
ret = &BlockTree{}
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND path = ? AND type = 'd'"
- err := queryRowForBox(boxID, sqlStmt, boxID, path).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
+ row := queryRowForBox(boxID, sqlStmt, boxID, path)
+ if row == nil { return }
+ err := row.Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
if err != nil {
ret = nil
if errors.Is(err, sql.ErrNoRows) {
@@ -222,7 +226,9 @@ func GetBlockTreeRootByHPath(boxID, hPath string) (ret *BlockTree) {
ret = &BlockTree{}
hPath = gulu.Str.RemoveInvisible(hPath)
sqlStmt := "SELECT * FROM blocktrees WHERE box_id = ? AND hpath = ? AND type = 'd'"
- err := queryRowForBox(boxID, sqlStmt, boxID, hPath).Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
+ row := queryRowForBox(boxID, sqlStmt, boxID, hPath)
+ if row == nil { return }
+ err := row.Scan(&ret.ID, &ret.RootID, &ret.ParentID, &ret.BoxID, &ret.Path, &ret.HPath, &ret.Updated, &ret.Type)
if err != nil {
ret = nil
if errors.Is(err, sql.ErrNoRows) {
@@ -523,7 +529,9 @@ func RemoveBlockTreesByRootID(boxID, rootID string) {
func CountBlockTreesByPathPrefix(boxID, pathPrefix string) (ret int) {
sqlStmt := "SELECT COUNT(*) FROM blocktrees WHERE path LIKE ? AND box_id = ?"
- err := queryRowForBox(boxID, sqlStmt, pathPrefix+"%", boxID).Scan(&ret)
+ row := queryRowForBox(boxID, sqlStmt, pathPrefix+"%", boxID)
+ if row == nil { return }
+ err := row.Scan(&ret)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0
@@ -1062,6 +1070,9 @@ func GetBlockTreesInBox(ids []string, boxID string) (ret map[string]*BlockTree)
func ExistBlockTreeInBox(id, boxID string) bool {
sqlStmt := "SELECT 1 FROM blocktrees WHERE id = ? LIMIT 1"
row := queryRowForBox(boxID, sqlStmt, id)
+ if row == nil {
+ return false // 加密 box 未解锁,视作不存在
+ }
var tmp any
return row.Scan(&tmp) == nil
}