Skip to content

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

:lock: Make SaveConf return error, add per-notebook BoxCrypt backup, verify encrypted conf on write, detect missing conf from backup https://github.com/siyuan-note/siyuan/issues/18034

Danielda065a6a2e8a
diff --git a/kernel/model/box.go b/kernel/model/box.go
index 22ed8ce48a..9d118fe25c 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -110,28 +110,51 @@ func ListNotebooks() (ret []*Box, err error) {
}
boxConf := conf.NewBoxConf()
- boxDirPath := filepath.Join(util.DataDir, id)
- boxConfPath := filepath.Join(boxDirPath, ".siyuan", "conf.json")
- isExistConf := filelock.IsExist(boxConfPath)
- if !isExistConf {
- if !IsUserGuide(id) {
- // 数据同步时展开文档树操作可能导致数据丢失 https://github.com/siyuan-note/siyuan/issues/7129
- logging.LogWarnf("found a corrupted box [%s]", boxDirPath)
+ boxDirPath := filepath.Join(util.DataDir, id)
+ boxConfPath := filepath.Join(boxDirPath, ".siyuan", "conf.json")
+ isExistConf := filelock.IsExist(boxConfPath)
+ if !isExistConf {
+ if !IsUserGuide(id) {
+ // conf.json 缺失时检查加密备份,确认是否为加密笔记本
+ backup, backupErr := readNotebookCryptBackup(id)
+ if backupErr != nil {
+ logging.LogErrorf("read notebook crypt backup [%s] failed: %s", boxDirPath, backupErr)
+ continue
+ }
+ if backup != nil {
+ // 从备份恢复 conf.json,避免加密笔记本被当作普通笔记本处理
+ boxConf.Encrypted = true
+ boxConf.BoxCrypt = backup
+ tmpBox := &Box{ID: id}
+ if saveErr := tmpBox.SaveConf(boxConf); saveErr != nil {
+ logging.LogErrorf("restore encrypted notebook conf from backup failed [%s]: %s", boxDirPath, saveErr)
+ continue
+ }
+ logging.LogWarnf("restored encrypted notebook conf from backup [%s]", boxDirPath)
+ } else {
+ // 数据同步时展开文档树操作可能导致数据丢失 https://github.com/siyuan-note/siyuan/issues/7129
+ logging.LogWarnf("found a corrupted box [%s]", boxDirPath)
+ }
+ } else {
+ continue
+ }
} else {
- continue
- }
- } else {
- data, readErr := filelock.ReadFile(boxConfPath)
- if nil != readErr {
- logging.LogErrorf("read box conf [%s] failed: %s", boxConfPath, readErr)
- continue
- }
- if readErr = gulu.JSON.UnmarshalJSON(data, boxConf); nil != readErr {
- logging.LogErrorf("parse box conf [%s] failed: %s", boxConfPath, readErr)
- filelock.Remove(boxConfPath)
- continue
+ data, readErr := filelock.ReadFile(boxConfPath)
+ if nil != readErr {
+ logging.LogErrorf("read box conf [%s] failed: %s", boxConfPath, readErr)
+ continue
+ }
+ if readErr = gulu.JSON.UnmarshalJSON(data, boxConf); nil != readErr {
+ logging.LogErrorf("parse box conf [%s] failed: %s", boxConfPath, readErr)
+ // 检查加密备份,有备份则保留损坏 conf 不删(避免标记为缺失后自动恢复旧数据)
+ backup, backupErr := readNotebookCryptBackup(id)
+ if backupErr == nil && backup != nil {
+ continue
+ }
+ filelock.Remove(boxConfPath)
+ continue
+ }
}
- }
icon := boxConf.Icon
if strings.Contains(icon, ".") { // 说明是自定义图标
@@ -150,11 +173,13 @@ func ListNotebooks() (ret []*Box, err error) {
}
if !isExistConf {
- // Automatically create notebook conf.json if not found it https://github.com/siyuan-note/siyuan/issues/9647
- box.SaveConf(boxConf)
- box.Unindex()
- logging.LogWarnf("fixed a corrupted box [%s]", boxDirPath)
- }
+ // Automatically create notebook conf.json if not found it https://github.com/siyuan-note/siyuan/issues/9647
+ if err := box.SaveConf(boxConf); err != nil {
+ logging.LogErrorf("save box conf [%s] failed: %s", boxDirPath, err)
+ }
+ box.Unindex()
+ logging.LogWarnf("fixed a corrupted box [%s]", boxDirPath)
+ }
ret = append(ret, box)
}
@@ -213,37 +238,35 @@ func (box *Box) GetConf() (ret *conf.BoxConf) {
return
}
-func (box *Box) SaveConf(conf *conf.BoxConf) {
+func (box *Box) SaveConf(conf *conf.BoxConf) error {
confPath := filepath.Join(util.DataDir, box.ID, ".siyuan/conf.json")
newData, err := gulu.JSON.MarshalIndentJSON(conf, "", " ")
if err != nil {
- logging.LogErrorf("marshal box conf [%s] failed: %s", confPath, err)
- return
+ return fmt.Errorf("marshal box conf [%s] failed: %w", confPath, err)
}
oldData, err := filelock.ReadFile(confPath)
if err != nil {
- box.saveConf0(newData)
- return
+ return box.saveConf0(newData)
}
if bytes.Equal(newData, oldData) {
- return
+ return nil
}
- box.saveConf0(newData)
+ return box.saveConf0(newData)
}
-func (box *Box) saveConf0(data []byte) {
+func (box *Box) saveConf0(data []byte) error {
confPath := filepath.Join(util.DataDir, box.ID, ".siyuan/conf.json")
if err := os.MkdirAll(filepath.Join(util.DataDir, box.ID, ".siyuan"), 0755); err != nil {
- logging.LogErrorf("save box conf [%s] failed: %s", confPath, err)
+ return fmt.Errorf("mkdir box conf dir failed: %w", err)
}
if err := filelock.WriteFile(confPath, data); err != nil {
- logging.LogErrorf("write box conf [%s] failed: %s", confPath, err)
util.ReportFileSysFatalError(err)
- return
+ return fmt.Errorf("write box conf [%s] failed: %w", confPath, err)
}
+ return nil
}
func (box *Box) Ls(p string) (ret []*FileInfo, totals int, err error) {
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 2de0e871bc..98be639997 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -146,15 +146,17 @@ func InitConf() {
// 重启后加密笔记本的 DEK 丢失(仅内存),必须重新解锁。
// 强制把所有加密笔记本标记为已关闭,避免启动索引读到无法解密的密文 .sy。
- changed := false
- for _, box := range Conf.GetBoxes() {
- boxConf := box.GetConf()
- if boxConf.Encrypted && !boxConf.Closed {
- boxConf.Closed = true
- box.SaveConf(boxConf)
- changed = true
+ changed := false
+ for _, box := range Conf.GetBoxes() {
+ boxConf := box.GetConf()
+ if boxConf.Encrypted && !boxConf.Closed {
+ boxConf.Closed = true
+ if err := box.SaveConf(boxConf); err != nil {
+ logging.LogErrorf("close encrypted notebook on boot [%s] failed: %s", box.ID, err)
+ }
+ changed = true
+ }
}
- }
if changed {
logging.LogInfof("closed encrypted notebooks on boot (DEK not in memory)")
}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 8d4c40a099..431251ca06 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -19,6 +19,7 @@ package model
import (
"encoding/json"
"errors"
+ "fmt"
"net/url"
"os"
"path/filepath"
@@ -568,9 +569,14 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
if err != nil {
return err
}
- boxConf.BoxCrypt.WrappedDEK = newWrapped
- boxConf.BoxCrypt.WrapNonce = newWrapped[:12]
- b.SaveConf(boxConf)
+ boxConf.BoxCrypt.WrappedDEK = newWrapped
+ boxConf.BoxCrypt.WrapNonce = newWrapped[:12]
+ if err = b.SaveConf(boxConf); err != nil {
+ return fmt.Errorf("save conf for notebook [%s] failed: %w", b.ID, err)
+ }
+ if err = writeNotebookCryptBackup(b.ID, boxConf.BoxCrypt); err != nil {
+ return fmt.Errorf("update notebook crypt backup [%s] failed: %w", b.ID, err)
+ }
}
Conf.m.Lock()
@@ -743,6 +749,58 @@ func DecryptAsset(boxID string, dek, ciphertext []byte) ([]byte, error) {
return util.DecryptWithAAD(assetKey, ciphertext, []byte(boxID))
}
+// notebookCryptBackupPath 返回加密笔记本的独立 BoxCrypt 备份路径。
+// 该文件在主 conf.json 丢失时用作"此笔记本是加密笔记本"的标识和降级恢复源。
+// 与全局 NotebookCrypto 备份(<DataDir>/.siyuan/notebook-crypto-backup.json)配合使用,
+// 全局备份存 MasterSalt/KEKVerifier,per-notebook 备份存 WrappedDEK/WrapNonce。
+func notebookCryptBackupPath(boxID string) string {
+ return filepath.Join(util.DataDir, boxID, ".siyuan", "notebook-crypt-backup.json")
+}
+
+// writeNotebookCryptBackup 写入加密笔记本的 BoxCrypt 备份。
+// 仅在 Encrypted=true 的笔记本上调用,配合 CreateEncryptedBox / ChangeMasterPassword 写入。
+func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {
+ backupPath := notebookCryptBackupPath(boxID)
+ if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {
+ return fmt.Errorf("mkdir notebook crypt backup dir failed: %w", err)
+ }
+ data, err := gulu.JSON.MarshalIndentJSON(crypt, "", " ")
+ if err != nil {
+ return fmt.Errorf("marshal notebook crypt backup failed: %w", err)
+ }
+ if err := filelock.WriteFile(backupPath, data); err != nil {
+ return fmt.Errorf("write notebook crypt backup failed: %w", err)
+ }
+ return nil
+}
+
+// readNotebookCryptBackup 读取加密笔记本的 BoxCrypt 备份。
+// 备份文件不存在时返回 (nil, nil),调用方据此区分"非加密笔记本"和"备份不存在"。
+func readNotebookCryptBackup(boxID string) (*conf.BoxEncryption, error) {
+ backupPath := notebookCryptBackupPath(boxID)
+ if !filelock.IsExist(backupPath) {
+ return nil, nil
+ }
+ data, err := filelock.ReadFile(backupPath)
+ if err != nil {
+ return nil, fmt.Errorf("read notebook crypt backup failed: %w", err)
+ }
+ var crypt conf.BoxEncryption
+ if err = gulu.JSON.UnmarshalJSON(data, &crypt); err != nil {
+ return nil, fmt.Errorf("unmarshal notebook crypt backup failed: %w", err)
+ }
+ return &crypt, nil
+}
+
+// removeNotebookCryptBackup 清除加密笔记本的 BoxCrypt 备份。
+// 关闭/锁定/删除加密笔记本时调用,避免残留过期备份数据。
+func removeNotebookCryptBackup(boxID string) {
+ backupPath := notebookCryptBackupPath(boxID)
+ if err := filelock.Remove(backupPath); err != nil && !os.IsNotExist(err) {
+ logging.LogErrorf("remove notebook crypt backup [%s] failed: %s", backupPath, err)
+ }
+}
+
func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {
boxID := ExtractBoxIDFromAssetsPath(srcPath)
if boxID != "" && IsEncryptedBox(boxID) {
@@ -797,7 +855,17 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
boxConf := box.GetConf()
boxConf.Encrypted = true
boxConf.BoxCrypt = enc
- box.SaveConf(boxConf)
+ if err = box.SaveConf(boxConf); err != nil {
+ return "", fmt.Errorf("save encrypted notebook conf failed: %w", err)
+ }
+ if err = writeNotebookCryptBackup(id, enc); err != nil {
+ return "", fmt.Errorf("write notebook crypt backup failed: %w", err)
+ }
+ // 回读校验加密配置已落盘,避免写失败后按普通笔记本处理
+ verifyConf := box.GetConf()
+ if verifyConf == nil || !verifyConf.Encrypted || verifyConf.BoxCrypt == nil {
+ return "", errors.New("encrypted notebook metadata verification failed after write")
+ }
// 复用刚派生的 DEK 直接开 db + 缓存,省去再次 Argon2id 解锁
cachedDEKsLock.Lock()
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index 0966cefe5b..9b2aa90c7e 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -221,7 +221,9 @@ func unmount0(boxID string) {
boxConf := box.GetConf()
boxConf.Closed = true
- box.SaveConf(boxConf)
+ if err := box.SaveConf(boxConf); err != nil {
+ logging.LogErrorf("save box conf [%s] failed: %s", box.ID, err)
+ }
if boxConf.Encrypted {
// 加密笔记本关闭:跳过 Unindex(索引 db 马上要删,逐条删是白费),
// 先等待事务队列和 SQL 索引队列落盘(确保 pending 写入已持久化到加密 .sy),
@@ -325,9 +327,11 @@ func Mount(boxID string) (alreadyMount bool, err error) {
}
box := &Box{ID: boxID}
- boxConf := box.GetConf()
- boxConf.Closed = false
- box.SaveConf(boxConf)
+ boxConf := box.GetConf()
+ boxConf.Closed = false
+ if err := box.SaveConf(boxConf); err != nil {
+ logging.LogErrorf("save box conf [%s] failed: %s", boxID, err)
+ }
// 缓存根一级的文档树展开
files, _, _ := ListDocTree(box.ID, "/", util.SortModeUnassigned, false, false, Conf.FileTree.MaxListCount)