Skip to content

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

:bug: Keep encrypted notebook mount state device-local https://github.com/siyuan-note/siyuan/issues/18034

Daniele398518f4e26
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index 17124db68b..407789e01e 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -449,6 +449,8 @@ Go to **Settings → Authentication → Encrypted Notebook → Change master pas
### Multi-device sync
Encrypted-notebook ciphertext `.sy`/assets/database files sync along with the data (ciphertext in, ciphertext out, self-consistent); the global key material (MasterSalt etc.) is also automatically backed up to the sync directory. **No manual "enable" is needed on a new device after sync**:
+An encrypted notebook's open state is never inherited across devices. Even if the synchronized `conf.json` records that another device had the notebook open, the UI and kernel must treat it as closed and skip indexing whenever the local process has no DEK for that notebook; entering the master password unlocks and mounts it locally.
+
1. Configure the same sync account on the new device and complete a sync
2. Sync pulls the key backup to the local machine; the kernel auto-restores the "enabled" state
3. Just click the encrypted notebook and enter the master password to unlock and use it
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 1a1f505fe5..edf1368801 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -449,6 +449,8 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
### 多设备同步
加密笔记本的密文 `.sy`/assets/数据库文件会随数据同步(密文进密文出,闭环自洽);全局密钥材料(MasterSalt 等)也会自动备份到同步目录。**新设备同步后无需手动"启用"**:
+加密笔记本的打开状态不能跨设备继承。即使同步到本机的 `conf.json` 记录了其他设备上的打开状态,只要本机内存中没有该笔记本的 DEK,界面和内核都必须将其视为已关闭,并跳过索引;输入主密码后由本机完成解锁和挂载。
+
1. 在新设备配置好相同的同步账号并完成同步
2. 同步会把密钥备份拉到本地,内核自动恢复"已启用"状态
3. 直接点击加密笔记本,输入主密码即可解锁使用
diff --git a/kernel/model/box.go b/kernel/model/box.go
index 8e9d690706..df42db291f 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -164,15 +164,21 @@ func ListNotebooks() (ret []*Box, err error) {
}
}
+ unlocked := boxConf.Encrypted && IsBoxUnlocked(id)
+ closed := boxConf.Closed
+ if boxConf.Encrypted {
+ // 加密笔记本的打开状态不能从其他设备继承,仅本机已挂载且持有 DEK 时才视为打开。
+ closed = !unlocked || !isEncryptedBoxMounted(id)
+ }
box := &Box{
ID: id,
Name: boxConf.Name,
Icon: filterBoxIcon(boxConf.Icon),
Sort: boxConf.Sort,
SortMode: boxConf.SortMode,
- Closed: boxConf.Closed,
+ Closed: closed,
Encrypted: boxConf.Encrypted,
- Unlocked: IsBoxUnlocked(id),
+ Unlocked: unlocked,
}
if box.Encrypted {
box.State = GetEncryptedBoxState(id)
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 2cca387012..c8ebfb9f62 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -168,24 +168,6 @@ func InitConf() {
Conf.Save()
logging.LogInfof("migrated AI config [%s]", confPath)
}
-
- // 重启后加密笔记本的 DEK 丢失(仅内存),必须重新解锁。
- // 强制把所有加密笔记本标记为已关闭,避免启动索引读到无法解密的密文 .sy。
- // 使用 IsEncryptedBox 统一判定(含 backup fallback)。
- changed := false
- for _, box := range Conf.GetBoxes() {
- if IsEncryptedBox(box.ID) && !box.Closed {
- boxConf := box.GetConf()
- 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 38b7d9ea0d..6c84ef96c6 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -1226,6 +1226,7 @@ func lockBoxHeld(boxID string) {
delete(cachedDEKs, boxID)
}
cachedDEKsLock.Unlock()
+ mountedEncryptedBoxes.Delete(boxID)
// 清理自动锁定访问时间戳
boxLastAccess.Delete(boxID)
@@ -1514,6 +1515,9 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
// IsEncryptedBox 判断给定 boxID 是否为加密笔记本。
// 优先读 conf.json,若缺失/损坏则 fallback 到独立备份,避免 fail-open。
func IsEncryptedBox(boxID string) bool {
+ if boxID == "" {
+ return false
+ }
box := &Box{ID: boxID}
boxConf := box.GetConf()
if boxConf != nil && boxConf.Encrypted {
@@ -2062,6 +2066,9 @@ func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {
// readNotebookCryptBackup 读取加密笔记本的 BoxCrypt 备份。
// 备份文件不存在时返回 (nil, nil),调用方据此区分"非加密笔记本"和"备份不存在"。
func readNotebookCryptBackup(boxID string) (*conf.BoxEncryption, error) {
+ if boxID == "" {
+ return nil, nil
+ }
backupPath := notebookCryptoBackupPath(boxID)
if !filelock.IsExist(backupPath) {
return nil, nil
diff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.go
index 850032d6fd..843d457375 100644
--- a/kernel/model/crypto_lifecycle_test.go
+++ b/kernel/model/crypto_lifecycle_test.go
@@ -86,6 +86,7 @@ func TestEncryptedBoxLockPreparationWaitsForActiveOperations(t *testing.T) {
defer cleanup()
setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)
+ mountedEncryptedBoxes.Store(boxID, true)
if err := AcquireEncryptedBoxOperation(boxID); err != nil {
t.Fatalf("acquire encrypted notebook operation failed: %v", err)
}
@@ -129,6 +130,9 @@ func TestEncryptedBoxLockPreparationWaitsForActiveOperations(t *testing.T) {
if IsBoxUnlocked(boxID) {
t.Fatal("locked notebook retained its DEK")
}
+ if isEncryptedBoxMounted(boxID) {
+ t.Fatal("locked notebook retained its local mount state")
+ }
}
func TestEncryptedBoxOperationReleaseSurvivesNotebookRemoval(t *testing.T) {
@@ -202,6 +206,64 @@ func TestEncryptedBoxMetadataIsNotStoredInPlaintext(t *testing.T) {
}
}
+func TestListNotebooksDoesNotInheritEncryptedOpenState(t *testing.T) {
+ oldConf := Conf
+ Conf = NewAppConf()
+ Conf.FileTree = conf.NewFileTree()
+ defer func() {
+ Conf = oldConf
+ }()
+
+ boxID := "20260731160007-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ boxConf.Closed = true
+ if err := box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ mountedEncryptedBoxes.Store(boxID, true)
+
+ boxes, err := ListNotebooks()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(boxes) != 1 || boxes[0].Closed || !boxes[0].Unlocked {
+ t.Fatalf("expected locally unlocked notebook to be open, got %+v", boxes)
+ }
+ boxConf.Closed = false
+ if err = box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+
+ cachedDEKsLock.Lock()
+ if cached, ok := cachedDEKs[boxID]; ok {
+ zeroAndClear(cached)
+ delete(cachedDEKs, boxID)
+ }
+ cachedDEKsLock.Unlock()
+ mountedEncryptedBoxes.Delete(boxID)
+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)
+
+ boxes, err = ListNotebooks()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(boxes) != 1 || !boxes[0].Closed || boxes[0].Unlocked {
+ t.Fatalf("expected encrypted notebook without a local DEK to be closed, got %+v", boxes)
+ }
+
+ raw, err := readRawBoxConf(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if raw.Closed {
+ t.Fatal("test precondition failed: synchronized configuration should still contain closed=false")
+ }
+}
+
func TestEncryptedBoxMetadataAuthenticationFailureEntersErrorState(t *testing.T) {
boxID := "20260731160003-abcdefg"
cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
@@ -439,6 +501,7 @@ func prepareEncryptedBoxLifecycleTest(t *testing.T, boxID string) func() {
}
return func() {
+ mountedEncryptedBoxes.Delete(boxID)
cachedDEKsLock.Lock()
if cached, ok := cachedDEKs[boxID]; ok {
zeroAndClear(cached)
diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.go
index 0ffc137a5a..c1a42f999a 100644
--- a/kernel/model/crypto_test.go
+++ b/kernel/model/crypto_test.go
@@ -38,6 +38,25 @@ func setDEKForTest(boxID string, dek []byte) {
cachedDEKs[boxID] = dek
}
+func TestIsEncryptedBoxRejectsEmptyID(t *testing.T) {
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ defer func() {
+ util.DataDir = oldDataDir
+ }()
+
+ backupDir := filepath.Join(util.DataDir, ".siyuan")
+ if err := os.MkdirAll(backupDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(backupDir, "notebook-crypto-backup.json"), []byte("{}"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if IsEncryptedBox("") {
+ t.Fatal("empty notebook ID must not resolve to the data-level backup path")
+ }
+}
+
func TestEncryptedAssetRoundTrip(t *testing.T) {
boxID := "20260731103900-asset01"
diskName := "asset-20260731103900-abcdefg.bin"
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index acc3766d4a..daf8e83661 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -137,7 +137,16 @@ func normalizeBoxName(name string) string {
return name
}
-var boxLock = sync.Map{}
+var (
+ boxLock = sync.Map{}
+ // mountedEncryptedBoxes 只记录当前进程完成挂载的加密笔记本,不能从同步配置恢复。
+ mountedEncryptedBoxes = sync.Map{}
+)
+
+func isEncryptedBoxMounted(boxID string) bool {
+ _, mounted := mountedEncryptedBoxes.Load(boxID)
+ return mounted
+}
// removeBoxDir 重试删除刚完成读写的笔记本目录,避免 Windows 延迟释放句柄导致瞬时失败。
func removeBoxDir(p string) (err error) {
@@ -404,6 +413,9 @@ func Mount(boxID string) (alreadyMount bool, err error) {
if err := box.SaveConf(boxConf); err != nil {
logging.LogErrorf("save box conf [%s] failed: %s", boxID, err)
}
+ if boxConf.Encrypted {
+ mountedEncryptedBoxes.Store(boxID, true)
+ }
if _, ensureErr := EnsureBoxDoc(boxID); nil != ensureErr {
logging.LogErrorf("ensure box document [%s] failed: %s", boxID, ensureErr)
}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index b258e9fbc8..9c078ddb91 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -2440,6 +2440,9 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
}
for boxID := range needIndexBoxes {
if box := Conf.GetBox(boxID); nil != box {
+ if box.Encrypted && box.Closed {
+ continue
+ }
if _, err := EnsureBoxDoc(boxID); nil != err {
logging.LogErrorf("ensure box document [%s] after sync failed: %s", boxID, err)
}
diff --git a/kernel/model/sync.go b/kernel/model/sync.go
index e229bfa25e..23945e0453 100644
--- a/kernel/model/sync.go
+++ b/kernel/model/sync.go
@@ -367,6 +367,9 @@ func upsertIndexes(upsertFilePaths []string) (upsertRootIDs []string) {
// .sy 直接出现在 data 文件夹下,没有出现在笔记本文件夹下的情况
continue
}
+ if IsEncryptedBox(box) && (!IsBoxUnlocked(box) || !isEncryptedBoxMounted(box)) {
+ continue
+ }
p := strings.TrimPrefix(upsertFile, box)
msg := fmt.Sprintf(Conf.Language(40), util.GetTreeID(p))