An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Rename encrypted backup files by scope https://github.com/siyuan-note/siyuan/issues/18034
Danielb3ccfa8b7080
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 4cce9245f3..17124db68b 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -94,7 +94,9 @@ User master passwordMasterSalt is the global root of KEK derivation — the master password + MasterSalt derive the KEK via Argon2id, and the KEK then unwraps each notebook's WrappedDEK. **Losing MasterSalt permanently locks the data**: even with the same master password, a changed salt derives a different KEK, so old WrappedDEKs cannot be unwrapped. A backup-and-recovery mechanism is therefore introduced.-**Backup**: `<DataDir>/.siyuan/notebook-crypto-backup.json`, holding the full NotebookCrypto (MasterSalt/KEKVerifier/KDFParams). Located inside DataDir, it **enters the dejavu sync scope**. It is refreshed when enabling encrypted notebooks and when changing the master password. It may be deleted on disable only after confirming that no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on it, or after the user explicitly chooses to purge those recovery artifacts permanently. Stored as plaintext JSON (salt is not secret, verifier is ciphertext — identical to how they are stored in `conf/conf.json`).+**Backup**: `<DataDir>/.siyuan/data-crypto-backup.json`, holding the full NotebookCrypto (MasterSalt/KEKVerifier/KDFParams). Located inside DataDir, it **enters the dejavu sync scope**. It is refreshed when enabling encrypted notebooks and when changing the master password. It may be deleted on disable only after confirming that no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on it, or after the user explicitly chooses to purge those recovery artifacts permanently. Stored as plaintext JSON (salt is not secret, verifier is ciphertext — identical to how they are stored in `conf/conf.json`).++Each encrypted notebook separately stores `<DataDir>/<boxID>/.siyuan/notebook-crypto-backup.json`, containing that notebook's BoxEncryption key envelope (WrappedDEK/WrapNonce and authenticated metadata). The global `data-crypto-backup.json` supplies the KEK derivation identity, while the per-notebook `notebook-crypto-backup.json` supplies the wrapped DEK; neither file can replace the other.**Recovery triggers** (covering scenarios such as conf.json loss, sync to a new device, importing Data.zip):@@ -111,7 +113,7 @@ MasterSalt is the global root of KEK derivation — the master password + Master| Operation | Entry | Notes ||---|---|---|-| Export key | Shown when enabled | Copies `notebook-crypto-backup.json` to the export directory for download; the user keeps it (API: `/api/notebook/exportNotebookCryptoBackup`) |+| Export key | Shown when enabled | Copies `data-crypto-backup.json` to the export directory for download; the user keeps it (API: `/api/notebook/exportNotebookCryptoBackup`) || Import key | Shown in `Disabled` or `RecoveryRequired` | Uploads a local backup file; after validation it is written back to `<DataDir>/.siyuan/` and the local config is restored (`Enabled=true`). Use the master password matching that key to unlock afterwards (API: `/api/notebook/importNotebookCryptoBackup`) |Import guard: a complete `Enabled` configuration rejects import to avoid overwriting the existing salt and orphaning WrappedDEKs. `RecoveryRequired` permits import only when the authenticated candidate key can unwrap every live encrypted notebook and every kernel-enumerable deleted-notebook history dependency. The backup file itself does not contain the master password (salt is not secret, verifier is ciphertext), so export/import does not leak plaintext data; unlocking still requires the master password.@@ -128,9 +130,11 @@ Import guard: a complete `Enabled` configuration rejects import to avoid overwri├── storage/av/ ← normal-notebook database files (plaintext)├── data/│ ├── .siyuan/-│ │ └── notebook-crypto-backup.json ← NotebookCrypto backup (MasterSalt/KEKVerifier, synced; see §4.1)+│ │ └── data-crypto-backup.json ← NotebookCrypto backup (MasterSalt/KEKVerifier, synced; see §4.1)│ ├── <boxID>/ ← encrypted notebook directory-│ │ ├── .siyuan/conf.json ← BoxConf (Encrypted=true + WrappedDEK)+│ │ ├── .siyuan/+│ │ │ ├── conf.json ← BoxConf (Encrypted=true + WrappedDEK)+│ │ │ └── notebook-crypto-backup.json ← per-notebook BoxEncryption backup│ │ ├── *.sy ← AES-256-GCM ciphertext│ │ ├── assets/│ │ │ └── <uuid>-<blockID>.ext ← single-file encrypted container, filename desensitized@@ -371,9 +375,9 @@ The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and ba## 19. Backup, Recovery, and Metadata Policy-`notebook-crypto-backup.json` is recovery material, not a secret. It contains a format version, backup ID, creation time, content digest, and KEK-based HMAC. After the master password derives the KEK, a missing or mismatched HMAC rejects recovery rather than acting as a compatibility fallback. Recovery must not silently overwrite enabled configuration. A malformed backup or a backup incompatible with existing encrypted notebooks enters an error state instead of generating a new MasterSalt.+`data-crypto-backup.json` is recovery material, not a secret. It contains a format version, backup ID, creation time, content digest, and KEK-based HMAC. After the master password derives the KEK, a missing or mismatched HMAC rejects recovery rather than acting as a compatibility fallback. Recovery must not silently overwrite enabled configuration. A malformed backup or a backup incompatible with existing encrypted notebooks enters an error state instead of generating a new MasterSalt.-Backup persistence follows the project's existing file-write semantics. The global `notebook-crypto-backup.json` is written to a random temporary file in the same directory and then atomically replaced; each notebook's `notebook-crypt-backup.json` uses the ordinary file-lock-protected configuration write. Neither path makes an additional power-loss durability guarantee through file or directory `fsync`. Startup validates the structure and digest that can be checked without a key; recovery validates the HMAC and key-envelope compatibility after the master password is entered. Corruption or mismatch is safely rejected instead of generating replacement key material.+Backup persistence follows the project's existing file-write semantics. The global `data-crypto-backup.json` is written to a random temporary file in the same directory and then atomically replaced; each notebook's `notebook-crypto-backup.json` uses the ordinary file-lock-protected configuration write. Neither path makes an additional power-loss durability guarantee through file or directory `fsync`. Startup validates the structure and digest that can be checked without a key; recovery validates the HMAC and key-envelope compatibility after the master password is entered. Corruption or mismatch is safely rejected instead of generating replacement key material.An HMAC proves only that a party without the KEK did not alter the backup; it does not prove that the backup is the latest version. The current scope introduces no trusted external monotonic counter, so an authenticated historical backup or ciphertext may pass validation. `BackupID` and `CreatedAt` are information for diagnostics and manual comparison, not rollback anchors. Sync, history, and recovery flows must not describe successful authentication as proof of freshness or source trust. Strong rollback prevention requires independent trusted state and is outside this design's scope.@@ -462,7 +466,7 @@ Sync recovery can validate backup integrity but cannot prove that a backup is th**It cannot be recovered** — by design (no backdoor). Even if the ciphertext has been synced to the cloud, it cannot be decrypted without the master password. **You must remember the master password; using a password manager is recommended.**### Recovering from a lost key backup-If both `conf/conf.json` and the key backup in the sync directory are lost (an extreme case), re-enabling the encrypted-notebook feature will be rejected with a prompt to restore the backup file. As long as you can recover `notebook-crypto-backup.json` from another synced device or a previously exported key file, you can import it via the "Import key" button shown in `Disabled` or `RecoveryRequired`, or manually put it back at `<workspace>/data/.siyuan/` and re-enable, then unlock with the master password matching that key.+If both `conf/conf.json` and the key backup in the sync directory are lost (an extreme case), re-enabling the encrypted-notebook feature will be rejected with a prompt to restore the backup file. As long as you can recover `data-crypto-backup.json` from another synced device or a previously exported key file, you can import it via the "Import key" button shown in `Disabled` or `RecoveryRequired`, or manually put it back at `<workspace>/data/.siyuan/` and re-enable, then unlock with the master password matching that key.Restoring deleted encrypted-notebook history also requires the global key backup matching its WrappedDEK and the master password. While you still need that local recovery path, do not permanently purge either the history or its matching key backup; disabling must refuse to proceed when it discovers such a dependency.diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex 2c8dec2eab..1a1f505fe5 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -94,7 +94,9 @@MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各笔记本的 WrappedDEK。**MasterSalt 丢失等于数据永久锁死**:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。-**备份**:`<DataDir>/.siyuan/notebook-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储(salt 不保密、verifier 是密文,与 `conf/conf.json` 的存储方式一致)。+**备份**:`<DataDir>/.siyuan/data-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储(salt 不保密、verifier 是密文,与 `conf/conf.json` 的存储方式一致)。++每个加密笔记本另行保存 `<DataDir>/<boxID>/.siyuan/notebook-crypto-backup.json`,其中包含该笔记本的 BoxEncryption 密钥包络(WrappedDEK/WrapNonce 和认证元数据)。全局 `data-crypto-backup.json` 提供 KEK 派生身份,单笔记本 `notebook-crypto-backup.json` 提供已封装 DEK,两者不能相互替代。**恢复触发点**(覆盖 conf.json 丢失 / 同步到新设备 / 导入 Data.zip 等场景):@@ -111,7 +113,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i| 操作 | 入口 | 说明 ||---|---|---|-| 导出密钥 | 已启用状态下显示 | 把 `notebook-crypto-backup.json` 复制到 export 目录供下载,用户自行保管(API:`/api/notebook/exportNotebookCryptoBackup`) |+| 导出密钥 | 已启用状态下显示 | 把 `data-crypto-backup.json` 复制到 export 目录供下载,用户自行保管(API:`/api/notebook/exportNotebookCryptoBackup`) || 导入密钥 | `Disabled` 或 `RecoveryRequired` 状态下显示 | 选本地备份文件上传,校验合法后写回 `<DataDir>/.siyuan/` 并装回本机配置(`Enabled=true`)。后续用该密钥对应的主密码解锁(API:`/api/notebook/importNotebookCryptoBackup`) |导入防呆:完整的 `Enabled` 配置拒绝导入,避免覆盖现有 salt 并孤立 WrappedDEK;`RecoveryRequired` 仅在候选密钥通过认证且能解开全部现存加密笔记本及内核可枚举的已删除笔记本历史依赖时允许导入。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出和导入不涉及明文数据泄漏,解锁仍需主密码。@@ -128,9 +130,11 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i├── storage/av/ ← 普通笔记本的 数据库文件(明文)├── data/│ ├── .siyuan/-│ │ └── notebook-crypto-backup.json ← NotebookCrypto 备份(MasterSalt/KEKVerifier,进同步范围,详见 §4.1)+│ │ └── data-crypto-backup.json ← NotebookCrypto 备份(MasterSalt/KEKVerifier,进同步范围,详见 §4.1)│ ├── <boxID>/ ← 加密笔记本目录-│ │ ├── .siyuan/conf.json ← BoxConf(Encrypted=true + WrappedDEK)+│ │ ├── .siyuan/+│ │ │ ├── conf.json ← BoxConf(Encrypted=true + WrappedDEK)+│ │ │ └── notebook-crypto-backup.json ← 单笔记本 BoxEncryption 备份│ │ ├── *.sy ← AES-256-GCM 密文│ │ ├── assets/│ │ │ └── <uuid>-<blockID>.ext ← 单文件加密容器,文件名已脱敏@@ -371,9 +375,9 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副## 19. 备份、恢复与元数据策略-`notebook-crypto-backup.json` 是恢复材料而非秘密。文件带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC;主密码派生 KEK 后,HMAC 缺失或不匹配必须拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。+`data-crypto-backup.json` 是恢复材料而非秘密。文件带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC;主密码派生 KEK 后,HMAC 缺失或不匹配必须拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。-备份持久化遵循项目现有文件写入语义:全局 `notebook-crypto-backup.json` 通过同目录随机临时文件写入后原子替换,每个笔记本的 `notebook-crypt-backup.json` 使用文件锁保护的常规配置写入。两者都不额外承诺断电场景下的文件或目录 `fsync` 持久性;启动时校验无需密钥即可验证的结构和摘要,输入主密码后的恢复再校验 HMAC 以及密钥包络匹配关系。损坏或不匹配时安全拒绝,而不是生成替代密钥材料。+备份持久化遵循项目现有文件写入语义:全局 `data-crypto-backup.json` 通过同目录随机临时文件写入后原子替换,每个笔记本的 `notebook-crypto-backup.json` 使用文件锁保护的常规配置写入。两者都不额外承诺断电场景下的文件或目录 `fsync` 持久性;启动时校验无需密钥即可验证的结构和摘要,输入主密码后的恢复再校验 HMAC 以及密钥包络匹配关系。损坏或不匹配时安全拒绝,而不是生成替代密钥材料。HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明它是最新版本。当前范围不引入可信外部单调计数器,因此一个认证有效的历史备份或历史密文可能通过校验;`BackupID` 和 `CreatedAt` 只是供诊断和人工比较的信息,不是防回滚锚点。同步、历史或恢复流程不得把“认证成功”表述为“最新”或“来源可信”;真正防回滚需要独立可信状态,超出本设计范围。@@ -462,7 +466,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明**无法恢复**——这是设计使然(没有后门)。即使密文已同步到云端,没有主密码也解不开。**务必牢记主密码,建议使用密码管理器保存**。### 密钥备份丢失的恢复-若 `conf/conf.json` 与同步目录里的密钥备份同时丢失(极端情况),重新启用加密笔记本会被拒绝并提示恢复备份文件。只要能从其他已同步的设备或之前导出的密钥文件找回 `notebook-crypto-backup.json`,可通过 `Disabled` 或 `RecoveryRequired` 状态下显示的「导入密钥」按钮导入,或手动放回 `<工作区>/data/.siyuan/` 后重新启用,即可用该密钥对应的主密码解锁。+若 `conf/conf.json` 与同步目录里的密钥备份同时丢失(极端情况),重新启用加密笔记本会被拒绝并提示恢复备份文件。只要能从其他已同步的设备或之前导出的密钥文件找回 `data-crypto-backup.json`,可通过 `Disabled` 或 `RecoveryRequired` 状态下显示的「导入密钥」按钮导入,或手动放回 `<工作区>/data/.siyuan/` 后重新启用,即可用该密钥对应的主密码解锁。恢复已删除加密笔记本的历史同样需要与其 WrappedDEK 匹配的全局密钥备份和主密码。只要仍要保留这类本地恢复能力,就不要永久清除其历史或匹配的密钥备份;禁用流程应在发现这类依赖时拒绝继续。diff --git a/docs/WORKSPACE.md b/docs/WORKSPACE.mdindex d620ee0e13..5680fd3f4f 100644--- a/docs/WORKSPACE.md+++ b/docs/WORKSPACE.md@@ -23,7 +23,7 @@ A SiYuan workspace is a **self-describing** directory tree: notebooks, documents├── data/ # DataDir — root of all notebook data│ ├── .siyuan/ # Workspace-level hidden config│ │ ├── syncignore / searchignore / embeddingignore / indexignore / refsearchignore-│ │ └── notebook-crypto-backup.json # Optional encrypted-notebook global recovery metadata+│ │ └── data-crypto-backup.json # Optional encrypted-data global recovery metadata│ ├── assets/ # ★Global assets (images/audio/video/files)│ ├── templates/ # Global templates (.md)│ ├── widgets/ # Widgets@@ -37,7 +37,7 @@ A SiYuan workspace is a **self-describing** directory tree: notebooks, documents│ │ ├── conf.json # ★Notebook config (BoxConf: name/icon/closed...)│ │ ├── sort.json # Optional custom sort mapping {docID: order}│ │ ├── boxDoc.json # Optional top-level notebook document marker for .sy.zip import/export-│ │ └── notebook-crypt-backup.json # Optional encrypted-notebook key-envelope backup+│ │ └── notebook-crypto-backup.json # Optional encrypted-notebook key-envelope backup│ ├── <boxID>.sy # Optional top-level notebook document (rootID = notebook ID)│ ├── <docID>.sy # Document (JSON tree; filename = doc rootID)│ ├── <docID>/ # ★Children of that document (same-named pair)@@ -162,7 +162,7 @@ Each notebook directory contains a `.siyuan/` hidden folder, which can contain:| `conf.json` | Notebook config (BoxConf) || `sort.json` | Optional custom sort mapping `{docID: order}` || `boxDoc.json` | Optional; identifies the top-level notebook document in `.sy.zip` notebook exports/imports |-| `notebook-crypt-backup.json` | Optional; encrypted-notebook backup of the wrapped notebook data-encryption key |+| `notebook-crypto-backup.json` | Optional; encrypted-notebook backup of the wrapped notebook data-encryption key |The `BoxConf` struct:@@ -190,7 +190,7 @@ Read/write sites: `GetConf` / `SaveConf`. The path is hard-coded as `<DataDir>/<`boxDoc.json` contains a metadata spec version and the top-level document ID. At runtime the kernel derives that document ID directly from `box.ID`; the metadata file is retained so `.sy.zip` import can identify the source notebook's top-level document and remap it to the destination notebook ID.-Encrypted notebooks retain recovery metadata in `conf.json` and `notebook-crypt-backup.json`, but their `.sy`, notebook-local assets, and attribute-view definitions are ciphertext. See [ENCRYPTED-NOTEBOOK.md](./ENCRYPTED-NOTEBOOK.md) for the encryption boundary, database isolation, and recovery design.+Encrypted notebooks retain recovery metadata in `conf.json` and `notebook-crypto-backup.json`, but their `.sy`, notebook-local assets, and attribute-view definitions are ciphertext. See [ENCRYPTED-NOTEBOOK.md](./ENCRYPTED-NOTEBOOK.md) for the encryption boundary, database isolation, and recovery design.---@@ -220,7 +220,7 @@ Be careful to distinguish the two `conf.json` files:| `refsearchignore` | Ref-search ignore rules || `publishAccess.json` | Publishing access control || `filesys_status_check/` | File-system consistency-check state |-| `notebook-crypto-backup.json` | Global encrypted-notebook KDF and verifier backup used for sync/recovery |+| `data-crypto-backup.json` | Global encrypted-data KDF and verifier backup used for sync/recovery || `master-password-migration.json` | Temporary crash-recovery state during master-password migration |Most entries are optional and are created only when the corresponding feature is used.diff --git a/docs/WORKSPACE.zh-CN.md b/docs/WORKSPACE.zh-CN.mdindex d19070a262..d57e9fc7da 100644--- a/docs/WORKSPACE.zh-CN.md+++ b/docs/WORKSPACE.zh-CN.md@@ -23,7 +23,7 @@ SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源├── data/ # DataDir — 所有笔记本数据的根│ ├── .siyuan/ # 工作区级隐藏配置│ │ ├── syncignore / searchignore / embeddingignore / indexignore / refsearchignore-│ │ └── notebook-crypto-backup.json # 可选的加密笔记本全局恢复元数据+│ │ └── data-crypto-backup.json # 可选的加密数据全局恢复元数据│ ├── assets/ # ★全局资源文件(图片/音视频/文件)│ ├── templates/ # 全局模板(.md)│ ├── widgets/ # 挂件@@ -37,7 +37,7 @@ SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源│ │ ├── conf.json # ★笔记本配置(BoxConf:name/icon/closed...)│ │ ├── sort.json # 可选的自定义排序映射 {docID: order}│ │ ├── boxDoc.json # 可选的顶层笔记本文档标记,用于 .sy.zip 导入导出-│ │ └── notebook-crypt-backup.json # 可选的加密笔记本密钥包络备份+│ │ └── notebook-crypto-backup.json # 可选的加密笔记本密钥包络备份│ ├── <boxID>.sy # 可选的顶层笔记本文档(rootID = 笔记本 ID)│ ├── <docID>.sy # 文档(JSON 树;文件名 = 文档 rootID)│ ├── <docID>/ # ★该文档的子文档目录(同名配对)@@ -162,7 +162,7 @@ data/<boxID>/| `conf.json` | 笔记本配置(BoxConf) || `sort.json` | 可选的文档自定义排序映射 `{docID: order}` || `boxDoc.json` | 可选;在笔记本 `.sy.zip` 导入导出中标识顶层笔记本文档 |-| `notebook-crypt-backup.json` | 可选;加密笔记本中已封装数据加密密钥的备份 |+| `notebook-crypto-backup.json` | 可选;加密笔记本中已封装数据加密密钥的备份 |`BoxConf` 结构:@@ -190,7 +190,7 @@ data/<boxID>/`boxDoc.json` 包含元数据规范版本和顶层文档 ID。运行时内核直接从 `box.ID` 推导该文档 ID;保留此元数据文件是为了让 `.sy.zip` 导入过程能够识别源笔记本的顶层文档,并将其重新映射为目标笔记本 ID。-加密笔记本在 `conf.json` 和 `notebook-crypt-backup.json` 中保留恢复元数据,但其 `.sy`、笔记本本地资源文件和属性视图定义均以密文落盘。加密边界、数据库隔离和恢复设计详见 [ENCRYPTED-NOTEBOOK.zh-CN.md](./ENCRYPTED-NOTEBOOK.zh-CN.md)。+加密笔记本在 `conf.json` 和 `notebook-crypto-backup.json` 中保留恢复元数据,但其 `.sy`、笔记本本地资源文件和属性视图定义均以密文落盘。加密边界、数据库隔离和恢复设计详见 [ENCRYPTED-NOTEBOOK.zh-CN.md](./ENCRYPTED-NOTEBOOK.zh-CN.md)。---@@ -220,7 +220,7 @@ data/<boxID>/| `refsearchignore` | 反链搜索忽略 || `publishAccess.json` | 发布访问控制 || `filesys_status_check/` | 文件系统一致性检查状态 |-| `notebook-crypto-backup.json` | 用于同步和恢复的全局加密笔记本 KDF 及校验器备份 |+| `data-crypto-backup.json` | 用于同步和恢复的全局加密数据 KDF 及校验器备份 || `master-password-migration.json` | 修改主密码期间临时使用的崩溃恢复状态 |其中大多数条目都是可选的,仅在使用相应功能时创建。diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex cca3b928dd..38b7d9ea0d 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -107,13 +107,13 @@ func NotebookCryptoMuLock() { notebookCryptoMu.Lock() }// NotebookCryptoMuUnlock 解锁 notebookCryptoMu。func NotebookCryptoMuUnlock() { notebookCryptoMu.Unlock() }-// notebookCryptoBackupPath 是 NotebookCrypto 的备份路径,位于 DataDir/.siyuan/ 下(进入 dejavu 同步范围)。+// dataCryptoBackupPath 是全局 NotebookCrypto 的备份路径,位于 DataDir/.siyuan/ 下(进入 dejavu 同步范围)。// MasterSalt 是加密体系的全局根基:conf/conf.json 丢失后若重新启用会生成新 salt,// 导致旧 WrappedDEK 无法用相同主密码解开(KEK 随 salt 改变)。把整套 NotebookCrypto 备份到// 同步目录,conf.json 丢失时通过同步恢复或本地备份即可重新解锁已有加密笔记本。// MasterSalt/KEKVerifier 设计为可明文(salt 不保密,verifier 是密文),备份文件按明文 JSON 存储。-func notebookCryptoBackupPath() string {- return filepath.Join(util.DataDir, ".siyuan", "notebook-crypto-backup.json")+func dataCryptoBackupPath() string {+ return filepath.Join(util.DataDir, ".siyuan", "data-crypto-backup.json")}// notebookCryptoAuthPayload 生成密钥身份认证载荷。@@ -180,7 +180,7 @@ func ExportNotebookCryptoBackup() (downloadPath string, err error) {notebookCryptoMu.Lock()defer notebookCryptoMu.Unlock()- backupPath := notebookCryptoBackupPath()+ backupPath := dataCryptoBackupPath()data, readErr := filelock.ReadFile(backupPath)if readErr != nil {if os.IsNotExist(readErr) {@@ -206,7 +206,7 @@ func ExportNotebookCryptoBackup() (downloadPath string, err error) {}// ImportNotebookCryptoBackup 接收用户导入的密钥备份文件内容(JSON 字节),-// 校验为合法 NotebookCrypto 后写回 <DataDir>/.siyuan/notebook-crypto-backup.json 并装回本机 Conf。+// 校验为合法 NotebookCrypto 后写回 <DataDir>/.siyuan/data-crypto-backup.json 并装回本机 Conf。// 用于新设备/重装后不依赖同步、手动恢复加密配置(详见设计文档 §4.1)。// 安全:备份文件不含主密码(salt 不保密、verifier 是密文),导入只恢复配置,解锁仍需主密码。// 防呆:本机已有完整且已启用的加密配置时拒绝导入,避免覆盖现有 salt/verifier 孤立现有 WrappedDEK。@@ -292,7 +292,7 @@ func saveNotebookCryptoBackup(kek []byte) error {Conf.NotebookCrypto.Checksum = nc.ChecksumConf.NotebookCrypto.KEKMAC = nc.KEKMAC // 保持 Conf 与备份文件的 KEKMAC 一致Conf.m.Unlock()- backupPath := notebookCryptoBackupPath()+ backupPath := dataCryptoBackupPath()if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {return fmt.Errorf("mkdir notebook crypto backup dir failed: %w", err)}@@ -317,7 +317,7 @@ func writeNotebookCryptoBackupData(nc *conf.NotebookCrypto, kek []byte) error {if !notebookCryptoConfigurationComplete(nc) {return errors.New("cannot write incomplete notebook crypto backup")}- backupPath := notebookCryptoBackupPath()+ backupPath := dataCryptoBackupPath()if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {return fmt.Errorf("mkdir notebook crypto backup dir failed: %w", err)}@@ -367,7 +367,7 @@ func verifyKEKAgainstExistingBoxes(kek []byte) bool {// loadNotebookCryptoBackup 从 DataDir 读取 NotebookCrypto 备份。文件不存在返回 (nil, nil)。func loadNotebookCryptoBackup() (*conf.NotebookCrypto, error) {- data, err := filelock.ReadFile(notebookCryptoBackupPath())+ data, err := filelock.ReadFile(dataCryptoBackupPath())if err != nil {if os.IsNotExist(err) {return nil, nil@@ -389,7 +389,7 @@ func loadNotebookCryptoBackup() (*conf.NotebookCrypto, error) {// removeNotebookCryptoBackup 删除备份文件(禁用加密功能时调用)。文件不存在视为成功。func removeNotebookCryptoBackup() {- if err := os.Remove(notebookCryptoBackupPath()); err != nil && !os.IsNotExist(err) {+ if err := os.Remove(dataCryptoBackupPath()); err != nil && !os.IsNotExist(err) {logging.LogErrorf("remove notebook crypto backup failed: %s", err)}}@@ -555,14 +555,14 @@ func hasEncryptedNotebook() (bool, error) {}// HasEncryptedNotebookHistory 检查历史目录中是否存在加密笔记本的历史快照。-// 笔记本删除后其 box 目录(含 .siyuan/conf.json 和 notebook-crypt-backup.json)会被+// 笔记本删除后其 box 目录(含 .siyuan/conf.json 和 notebook-crypto-backup.json)会被// 原样密文备份到历史目录(RemoveBox 的 filelock.Copy),但此时 IsEncryptedBox 已返回 false// (box 目录已删)。因此 DisableEncryptedNotebook 不能只靠 ListAllEncryptedBoxIDs 判定——// 已删除加密笔记本的历史仍依赖当前 MasterSalt/KEKVerifier 才能恢复,禁用并删除备份会让这些// 历史永久锁死,违反设计 §19。本函数扫描历史目录识别这类依赖。//// 判定信号:历史条目 <HistoryDir>/<ts>-<op>/<boxID>/.siyuan/ 下存在-// notebook-crypt-backup.json(专为 box 删除后的恢复设计),或 conf.json 标记 Encrypted=true。+// notebook-crypto-backup.json(专为 box 删除后的恢复设计),或 conf.json 标记 Encrypted=true。// boxID 用 ast.IsNodeIDPattern 校验,避免误判 assets/storage 等非 box 目录。func scanEncryptedNotebookHistory() (bool, error) {boxDirs, err := encryptedNotebookHistoryBoxDirs()@@ -634,7 +634,7 @@ func verifyKEKAgainstEncryptedHistory(kek []byte) bool {func readEncryptedHistoryBoxEncryptionCandidates(boxDir string) (ret []*conf.BoxEncryption, err error) {var candidateErrors []error- backupPath := filepath.Join(boxDir, ".siyuan", "notebook-crypt-backup.json")+ backupPath := filepath.Join(boxDir, ".siyuan", "notebook-crypto-backup.json")if filelock.IsExist(backupPath) {if candidate, readErr := readBoxEncryptionFile(backupPath); readErr == nil {ret = append(ret, candidate)@@ -681,11 +681,11 @@ func HasEncryptedNotebookHistory() bool {}// isEncryptedHistoryBoxDir 判断历史目录中的 boxID 子目录是否属于加密笔记本。-// 优先看 notebook-crypt-backup.json(删除前随 box 目录整体备份,是加密身份的权威标识),+// 优先看 notebook-crypto-backup.json(删除前随 box 目录整体备份,是加密身份的权威标识),// 再 fallback 到 conf.json 的 Encrypted 标志。func isEncryptedHistoryBoxDir(boxDir string) (bool, error) {siyuanDir := filepath.Join(boxDir, ".siyuan")- backupPath := filepath.Join(siyuanDir, "notebook-crypt-backup.json")+ backupPath := filepath.Join(siyuanDir, "notebook-crypto-backup.json")if _, err := os.Stat(backupPath); err == nil {return true, nil} else if !os.IsNotExist(err) {@@ -747,7 +747,7 @@ func EnableEncryptedNotebook(password string) error {if historyErr != nil {return fmt.Errorf("check encrypted notebook history failed: %w", historyErr)}- hasBackup := filelock.IsExist(notebookCryptoBackupPath())+ hasBackup := filelock.IsExist(dataCryptoBackupPath())if hasEncrypted || hasHistory || hasBackup {// 现存笔记本、已删除笔记本历史或全局备份均表示已有密钥域,必须恢复并认证,不能生成新 MasterSalt。if _, restoreErr := tryRestoreNotebookCryptoFromBackupLocked(password); restoreErr != nil {@@ -1233,7 +1233,7 @@ func lockBoxHeld(boxID string) {// 仅在 backup 缺失时从 conf 补写。正常流程中 CreateEncryptedBox/UnlockBox/ChangeMasterPassword// 已刷新 backup,此处不再用未经解密验证的 BoxCrypt 覆盖已有 backup,// 避免 conf 中的坏 WrappedDEK 覆盖有效恢复源。- if !filelock.IsExist(notebookCryptBackupPath(boxID)) {+ if !filelock.IsExist(notebookCryptoBackupPath(boxID)) {box := &Box{ID: boxID}boxConf := box.GetConf()if boxConf != nil && boxConf.Encrypted && boxConf.BoxCrypt != nil && len(boxConf.BoxCrypt.WrappedDEK) > 0 {@@ -1520,7 +1520,7 @@ func IsEncryptedBox(boxID string) bool {return true}// 主 conf 缺失/损坏时检查独立备份,确认是否为加密笔记本- backupPath := notebookCryptBackupPath(boxID)+ backupPath := notebookCryptoBackupPath(boxID)if !filelock.IsExist(backupPath) {return false // 无备份文件 → 非加密}@@ -1592,7 +1592,7 @@ func DeepCopyBoxEncryption(src *conf.BoxEncryption) *conf.BoxEncryption {}// listAllEncryptedBoxIDs 直接扫描笔记本配置及密钥备份,不触发配置修复等副作用。-// conf 损坏或缺失时以 notebook-crypt-backup.json 为准,供候选密钥验证、改密和禁用等关键路径使用。+// conf 损坏或缺失时以 notebook-crypto-backup.json 为准,供候选密钥验证、改密和禁用等关键路径使用。func listAllEncryptedBoxIDs() ([]string, error) {var ids []stringdirs, err := os.ReadDir(util.DataDir)@@ -2031,12 +2031,12 @@ func DecryptAsset(boxID, diskName string, dek, ciphertext []byte) ([]byte, errorreturn plaintext, err}-// notebookCryptBackupPath 返回加密笔记本的独立 BoxCrypt 备份路径。+// notebookCryptoBackupPath 返回加密笔记本的独立 BoxCrypt 备份路径。// 该文件在主 conf.json 丢失时用作"此笔记本是加密笔记本"的标识和降级恢复源。-// 与全局 NotebookCrypto 备份(<DataDir>/.siyuan/notebook-crypto-backup.json)配合使用,+// 与全局 NotebookCrypto 备份(<DataDir>/.siyuan/data-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")+func notebookCryptoBackupPath(boxID string) string {+ return filepath.Join(util.DataDir, boxID, ".siyuan", "notebook-crypto-backup.json")}// writeNotebookCryptBackup 写入加密笔记本的 BoxCrypt 备份。@@ -2045,7 +2045,7 @@ func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {if err := validateBoxEncryption(crypt); err != nil {return err}- backupPath := notebookCryptBackupPath(boxID)+ backupPath := notebookCryptoBackupPath(boxID)if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {return fmt.Errorf("mkdir notebook crypt backup dir failed: %w", err)}@@ -2062,7 +2062,7 @@ func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {// readNotebookCryptBackup 读取加密笔记本的 BoxCrypt 备份。// 备份文件不存在时返回 (nil, nil),调用方据此区分"非加密笔记本"和"备份不存在"。func readNotebookCryptBackup(boxID string) (*conf.BoxEncryption, error) {- backupPath := notebookCryptBackupPath(boxID)+ backupPath := notebookCryptoBackupPath(boxID)if !filelock.IsExist(backupPath) {return nil, nil}diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.goindex 6bbd534f3e..af3da96ed9 100644--- a/kernel/model/crypto_lifecycle.go+++ b/kernel/model/crypto_lifecycle.go@@ -103,7 +103,7 @@ func NotebookCryptoLifecycleState(hasRecoveryDependency bool) NotebookCryptoStat}return NotebookCryptoStateRecoveryRequired}- if hasRecoveryDependency || filelock.IsExist(notebookCryptoBackupPath()) {+ if hasRecoveryDependency || filelock.IsExist(dataCryptoBackupPath()) {return NotebookCryptoStateRecoveryRequired}return NotebookCryptoStateDisableddiff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.goindex cd13cae43f..850032d6fd 100644--- a/kernel/model/crypto_lifecycle_test.go+++ b/kernel/model/crypto_lifecycle_test.go@@ -374,7 +374,7 @@ func TestRecoveryRequiredHistoryRestoresAuthenticatedBackup(t *testing.T) {if err != nil {t.Fatal(err)}- if err = os.WriteFile(filepath.Join(historyBoxDir, "notebook-crypt-backup.json"), boxCryptData, 0644); err != nil {+ if err = os.WriteFile(filepath.Join(historyBoxDir, "notebook-crypto-backup.json"), boxCryptData, 0644); err != nil {t.Fatal(err)}diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.goindex 401f0ce7e0..0ffc137a5a 100644--- a/kernel/model/crypto_test.go+++ b/kernel/model/crypto_test.go@@ -312,7 +312,7 @@ func TestBackupRejectsUnsupportedSpec(t *testing.T) {defer func() { util.DataDir = origDataDir }()backup := &conf.NotebookCrypto{Spec: spec}- backupPath := filepath.Join(util.DataDir, ".siyuan", "notebook-crypto-backup.json")+ backupPath := filepath.Join(util.DataDir, ".siyuan", "data-crypto-backup.json")if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {t.Fatal(err)}@@ -328,6 +328,20 @@ func TestBackupRejectsUnsupportedSpec(t *testing.T) {}}+func TestCryptoBackupPathNames(t *testing.T) {+ originalDataDir := util.DataDir+ util.DataDir = t.TempDir()+ defer func() { util.DataDir = originalDataDir }()++ if got, want := dataCryptoBackupPath(), filepath.Join(util.DataDir, ".siyuan", "data-crypto-backup.json"); got != want {+ t.Fatalf("unexpected data crypto backup path: got %q, want %q", got, want)+ }+ boxID := "20260731120000-abcdefg"+ if got, want := notebookCryptoBackupPath(boxID), filepath.Join(util.DataDir, boxID, ".siyuan", "notebook-crypto-backup.json"); got != want {+ t.Fatalf("unexpected notebook crypto backup path: got %q, want %q", got, want)+ }+}+func TestBackupRejectsIncompleteCurrentSpec(t *testing.T) {originalDataDir := util.DataDirutil.DataDir = t.TempDir()@@ -336,7 +350,7 @@ func TestBackupRejectsIncompleteCurrentSpec(t *testing.T) {backup := conf.NewNotebookCrypto()backup.Enabled = trueprepareBackupForWrite(backup)- backupPath := filepath.Join(util.DataDir, ".siyuan", "notebook-crypto-backup.json")+ backupPath := filepath.Join(util.DataDir, ".siyuan", "data-crypto-backup.json")if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {t.Fatal(err)}@@ -375,7 +389,7 @@ func TestBackupChecksumCorruption(t *testing.T) {}prepareBackupForWrite(nc)nc.KEKMAC = computeKEKMAC(nc, kek)- backupPath := filepath.Join(tempDir, ".siyuan", "notebook-crypto-backup.json")+ backupPath := filepath.Join(tempDir, ".siyuan", "data-crypto-backup.json")os.MkdirAll(filepath.Dir(backupPath), 0755)data, _ := json.Marshal(nc)os.WriteFile(backupPath, data, 0644)@@ -448,7 +462,7 @@ func TestDeriveKEKRejectsTamperedBackupMAC(t *testing.T) {}prepareBackupForWrite(&nc)nc.KEKMAC = bytes.Repeat([]byte{0x7f}, 32)- backupPath := filepath.Join(util.DataDir, ".siyuan", "notebook-crypto-backup.json")+ backupPath := filepath.Join(util.DataDir, ".siyuan", "data-crypto-backup.json")if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {t.Fatal(err)}@@ -953,7 +967,7 @@ func TestEnabledWithoutBackupReturnsRecoveryError(t *testing.T) {}// 关键:不在磁盘制造无效备份——备份文件应仍不存在- if _, statErr := os.Stat(notebookCryptoBackupPath()); !os.IsNotExist(statErr) {+ if _, statErr := os.Stat(dataCryptoBackupPath()); !os.IsNotExist(statErr) {t.Fatalf("backup file should not be generated during deriveKEK; stat err=%v", statErr)}}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex eac35b753d..b258e9fbc8 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -2286,7 +2286,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,needIndexBoxes[boxID] = true}- if file.Path == "/.siyuan/notebook-crypto-backup.json" {+ if file.Path == "/.siyuan/data-crypto-backup.json" {needRestoreNotebookCrypto = true}