Skip to content

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

:memo: Require encrypted notebook backward compatibility https://github.com/siyuan-note/siyuan/issues/18034

Daniel917f1bfdd7a2
diff --git a/AGENTS.md b/AGENTS.md
index 95d9f7e2f1..814287dab9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,6 +21,14 @@ SiYuan repository guide. Module path `github.com/siyuan-note/siyuan`, license AG
3. **Kernel development:** After modifying Go code, run `gofmt`, but do not compile the kernel binary or restart a running kernel; the developer handles both manually
4. **Git:** **NEVER** run `git commit` / `git push` unless explicitly asked — no exceptions
+### Encrypted notebook compatibility
+
+- Encrypted notebooks are preparing for release. Existing encrypted data is a compatibility baseline, not disposable development data; do not require users to delete or recreate it after an upgrade
+- Changes to document, asset, attribute-view, key-envelope, backup, history, or sync formats must retain authenticated reads of supported existing formats or provide a recoverable migration before removing a reader
+- Changes to envelopes, AAD semantics, or key derivation must use an explicit format version and a compatibility plan. Migration must authenticate the source, preserve recovery material, and remain recoverable after failure or interruption; never regenerate MasterSalt or discard keys to work around incompatibility
+- Unknown formats, corruption, and authentication failures must preserve the original data and return an error; compatibility must not bypass authentication or fall back to plaintext. Derived indexes may be rebuilt after the source ciphertext authenticates
+- Format changes require regression coverage using fixtures from the supported previous format, including the affected read, export, history, backup, and recovery paths. See `docs/ENCRYPTED-NOTEBOOK.md` and `docs/ENCRYPTED-NOTEBOOK.zh-CN.md`; keep their compatibility policies aligned
+
---
## 2. Project-specific rules
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index e61274cfda..6da57d0f02 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -4,6 +4,8 @@
Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` documents, assets (including filenames), attribute-view definitions, and SQLite index databases (content + blocktree) are all stored encrypted on disk, requiring a master password to unlock and view the content. Existing normal notebooks are completely unaffected.
+Encrypted notebooks are preparing for release, and existing encrypted data is the compatibility baseline. From this point on, format and key-management changes must preserve access to existing data and its recovery paths; development status must never justify requiring users to delete or recreate their data. This covers documents, assets and their original names, attribute-view definitions, key envelopes, backups, history, and sync snapshots.
+
## 2. Core Constraints
| Aspect | Design Decision |
@@ -27,7 +29,8 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d
| Import | Supported — imported .sy.zip and Markdown are DEK-encrypted before writing to disk, identical to manually created documents |
| Enable / Disable | Enabling requires setting a master password; disabling requires no live encrypted notebook and no kernel-enumerable history or recovery snapshot that depends on the current key backup, unless those recovery artifacts are explicitly purged permanently |
| Restart behavior | All encrypted notebooks force-closed on startup (managed DEK handles exist only in process memory and must be derived again after restart); user must re-unlock |
-| Existing notebooks | Completely untouched, zero migration |
+| Existing normal notebooks | Completely untouched, zero migration |
+| Existing encrypted data | Remains readable and recoverable after upgrades; format changes retain authenticated legacy reads or provide recoverable migration without requiring users to delete or recreate their data |
## 3. Encrypted Notebook vs Normal Notebook
@@ -182,8 +185,10 @@ Encrypted-notebook operations (dedicated read path, with boxID):
**assets encryption**:
- On upload, fully read into memory + encrypt + write (cannot stream-encrypt)
- Filename desensitization: encrypted-notebook asset filenames are `<uuid>-<blockID>.<ext>`; the original name, plaintext size, and chunk count are authenticated encrypted metadata in the same asset container
-- The container starts with the fixed `SYAE` marker; name metadata and content chunks are authenticated separately with AAD binding the boxID, disk filename, and chunk index
+- New containers start with `SYAE`; authenticated encrypted metadata contains `spec=2`, a 32-byte `containerID` generated by the operating system CSPRNG for each write, the original name, plaintext size, and chunk count. Content-chunk AAD is `siyuan:asset:<boxID>:assets/<diskName>:content:v2:<lowercase hexadecimal containerID>:<zero-based chunk index>`; name metadata uses the same asset prefix followed by `:metadata`. Chunks or metadata from different writes cannot be interchanged; rollback of an entire old container remains outside the protection boundary
- On read, authenticate and decrypt the name metadata first, then authenticate and decrypt each content chunk; downloads use the original name stored in the container
+- Legacy `SYAE` assets whose metadata omits both `spec` and `containerID` remain readable, using `siyuan:asset:<boxID>:assets/<diskName>:content:<chunk index>` for chunk authentication. Name reads, content reads, export, and historical snapshots support this format. Explicit null versions, missing required new-format fields, unknown versions, and authentication failures are rejected without trying another version's AAD
+- New or re-saved assets use version 2. Opening, previewing, downloading, or exporting does not rewrite the original file or require users to recreate assets. The legacy format retains its original per-chunk authentication and cannot retrospectively detect whether chunks from different writes were spliced. Re-saving creates a version 2 container with chunk binding but does not prove that the old content was never spliced. Compatible reads provide no downgrade or rollback protection; a replacement in the legacy format is checked under that format's rules
- Encrypted notebooks disable the global assets fallback; notebook-level is mandatory
- Asset file rename is forbidden because the desensitized disk filename participates in AAD and renaming requires re-enveloping the whole asset
- The original name and content reside in one encrypted container, so there is no cross-file name-mapping transaction; write failures are returned to the caller
@@ -371,7 +376,7 @@ Persistent formats are layered; global KDF configuration, key envelopes, and per
2. **Global key and envelope metadata**: `NotebookCrypto` stores the KDF algorithm and parameters, MasterSalt, verifier format, KEK-envelope version, and backup-HMAC version; `BoxConf.WrappedDEK` stores each notebook's DEK envelope. They are not duplicated in every data object.
3. **Purpose separation**: Each notebook's DEK derives subkeys with fixed domain separators for file content, assets, database definitions, content SQLCipher, and blocktree SQLCipher. Asset-name metadata and content chunks share the asset subkey and are separated by distinct AAD suffixes; a separate subkey for every object type is not required. The KEK may be used directly for the verifier, DEK wrapping, and backup HMAC, with those uses separated by different algorithms, versioned AAD, or authenticated data formats. WrappedDEK authentication is not incorrectly placed in a DEK domain.
4. **Database compatibility metadata**: SQLCipher version, cipher parameters, and schema version live in a verifiable database header or the corresponding encrypted configuration boundary, not every data object. Content and blocktree indexes are rebuildable; after source ciphertext authenticates, an incompatible index is closed and rebuilt rather than weakening cipher parameters or falling back to plaintext SQLite.
-5. **Rename and format stability**: The first released format constructs AAD directly from the stable object ID. It is intentionally incompatible with experimental development ciphertext bound to the full logical relative path and provides neither dual-format reads nor migration; development data is deleted and rebuilt after the format switch. A parent-only move does not re-envelope content. A stable-basename change authenticates and decrypts with the old basename and creates a new envelope with the new basename. After the first released version freezes the format, any future envelope or AAD semantic change increments the format version and requires a separately designed migration.
+5. **Rename and format stability**: The current document format constructs AAD from the stable object ID and is frozen as a compatibility baseline during release preparation. Existing unversioned `SYAE` assets remain readable without requiring users to delete or recreate attachments when upgrading to version 2. Writes use version 2; reads do not force migration of files or historical snapshots. A parent-only move does not re-envelope content. A stable-basename change authenticates and decrypts with the old basename and creates a new envelope with the new basename. Future changes to envelopes, AAD semantics, or key derivation require an explicit format version and authenticated legacy reads, or a recoverable migration before the legacy reader is removed. Migration authenticates source data first and preserves the original data and matching recovery material so failure or interruption remains recoverable; resetting MasterSalt, discarding keys, or deleting data must never resolve format incompatibility. Unknown formats, corruption, and authentication failures preserve the original files and return an error without falling back to plaintext or bypassing authentication. Every format change requires fixtures from the supported previous format to verify affected read, export, history, backup, and recovery paths.
The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and backup copies are protected objects. They remain in controlled directories and use their corresponding purpose key. Locking, crash recovery, and history snapshots enumerate these companion files; unencrypted SQLite pages, query results, or diagnostics must never be written to a global temporary directory.
@@ -379,6 +384,8 @@ The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and ba
`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.
+On a password change, live notebooks' WrappedDEKs are rewrapped under the new KEK. Previous KEKs and the outgoing KEK are deduplicated, individually authenticated and encrypted under the new KEK with the versioned AAD `siyuan:history-kek:v1`, and stored in `HistoryKEKs`. The global backup digest and HMAC protect this field, and the password-change migration manifest retains it for recovery. Removing the last notebook involved in migration must not discard historical keys before the backup transition completes. Recovery and unlock try the current KEK, then historical KEKs unwrapped from authenticated configuration; plaintext KEKs are cleared after use and not cached. Historical ciphertext directories need no rewriting. The current backup and password can recover envelopes retained through earlier password changes, including directories later restored from another device or an offline snapshot.
+
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.
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index e7c0dd7a56..9422aaaeb1 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -4,6 +4,8 @@
在 SiYuan 中实现"加密笔记本"——一种特殊笔记本,其 `.sy` 文档、assets 资源文件(含文件名)、数据库文件、SQLite 索引数据库(content + blocktree)都在磁盘上加密存储,需要主密码解锁才能查看内容。已有的普通笔记本完全不受影响。
+加密笔记本已进入上线准备阶段,当前已写入的加密数据作为兼容基线。从现在起,格式和密钥管理变更必须保留已有数据的可读性与恢复能力,不得再以开发阶段为由要求用户删除或重建数据。兼容范围包括文档、资源及其原始名称、数据库定义、密钥包络、备份、历史和同步快照。
+
## 2. 核心约束
| 维度 | 设计决策 |
@@ -27,7 +29,8 @@
| 导入 | 支持——导入的 .sy.zip 和 Markdown 在落盘前用 DEK 加密,与手动创建的文档一致 |
| 启用/禁用 | 启用需设主密码;禁用需确认无现存加密笔记本,且无依赖当前密钥备份的内核可枚举历史或恢复快照;否则必须先明确永久清除这些恢复数据 |
| 重启行为 | 启动时强制关闭所有加密笔记本(受管 DEK 句柄仅存在于进程内存,重启后需重新派生),用户需重新解锁 |
-| 已有笔记本 | 完全不动,零迁移 |
+| 已有普通笔记本 | 完全不动,零迁移 |
+| 已有加密数据 | 升级后继续可读、可恢复;格式变更保留旧版认证读取或提供可恢复迁移,不要求删除或重建用户数据 |
## 3. 加密笔记本 vs 普通笔记本
@@ -373,7 +376,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
2. **全局密钥与包络元数据**:`NotebookCrypto` 保存 KDF 算法、参数、MasterSalt、verifier 格式、KEK 包络版本和备份 HMAC 版本;`BoxConf.WrappedDEK` 保存每个笔记本的 DEK 包络。它们不随每个数据对象重复保存。
3. **用途隔离**:每个笔记本的 DEK 通过固定域分隔符派生文件内容、资源、数据库定义、content SQLCipher 和 blocktree SQLCipher 子密钥。资源名称元数据与内容分块共用资源子密钥,并通过不同的 AAD 后缀隔离;不要求为每一种对象再派生独立子密钥。KEK 可以直接用于 verifier、DEK 包络和备份 HMAC,这些用途由不同算法、版本化 AAD 或被认证的数据格式隔离;不得把 WrappedDEK 认证错误地归入 DEK 域。
4. **数据库兼容信息**:SQLCipher 版本、cipher 参数和 schema 版本保存在数据库头部可验证位置或对应的加密配置边界,不写入每个数据对象。content 与 blocktree 索引可重建;源密文认证通过后,版本不兼容的索引应关闭并重建,而不是降低 cipher 参数或回退到明文 SQLite。
-5. **改名与格式稳定性**:首个发布格式直接以稳定对象 ID 构造 AAD,开发阶段按完整逻辑相对路径生成的试验文档密文不在兼容范围内。已写入的无版本字段 `SYAE` 资源继续按旧格式读取,不得因升级第 2 版而要求用户删除或重建附件;写入统一使用第 2 版,读取不强制迁移磁盘或历史快照。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。未来再修改信封或 AAD 语义必须提升格式版本,并保留明确的旧版读取路径或提供可恢复迁移。
+5. **改名与格式稳定性**:当前文档格式以稳定对象 ID 构造 AAD,并从上线准备阶段起冻结为兼容基线。已写入的无版本字段 `SYAE` 资源继续按旧格式读取,不得因升级第 2 版而要求用户删除或重建附件;写入统一使用第 2 版,读取不强制迁移磁盘或历史快照。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。未来修改信封、AAD 语义或密钥派生方式必须使用明确的格式版本,保留旧版认证读取路径,或在移除旧版读取前提供可恢复迁移。迁移必须先认证源数据,保留原始数据和匹配的恢复材料,失败或中断后仍可恢复;不得通过重置 MasterSalt、丢弃密钥或删除数据解决格式不兼容。未知格式、损坏或认证失败必须保留原文件并报错,不得回退到明文或绕过认证。每次格式变更都必须以受支持旧格式的样本验证受影响的读取、导出、历史、备份和恢复路径。
SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副本都是受保护对象,必须放在受控目录并使用对应的用途密钥。锁定、崩溃恢复和历史快照必须枚举这些伴随文件;未加密 SQLite 页面、查询结果或诊断转储不得写入全局临时目录。