Skip to content

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

:bug: Harden encrypted notebook history and index recovery https://github.com/siyuan-note/siyuan/issues/19180

Daniel68e7225e3e6b
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index a92f60716f..d780382ecd 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -210,11 +210,11 @@ File history:
auto-generated before close/exit → ensures history is captured even after locking
history index → content left empty (ciphertext not indexed for search)
view history → read the snapshot boxID, object type, and stable file basename, then reconstruct the original AAD for decryption (notebook must be unlocked)
- roll back → decrypt with the snapshot AAD → verify that the root-block ID matches the basename → load tree → restore ciphertext verbatim when the basename is unchanged, or let WriteTree re-envelope it when the basename changes
+ roll back → decrypt with the snapshot AAD → verify that the root-block ID matches the basename → load tree → let WriteTree serialize the restored content and re-envelope it with the target basename
Deleted-notebook history:
before deletion → entire directory backed up as ciphertext to history dir
- restore → verify WrappedDEK with the matching global key backup and master password, then copy the ciphertext directory back verbatim
+ restore → copy the ciphertext directory back verbatim without opening it; authenticate WrappedDEK with the matching global key backup and master password when unlocking
key retention → while kernel-managed history remains recoverable, deletion of the global key backup it depends on is forbidden; permanently purging the history removes the dependency
database history:
@@ -223,7 +223,7 @@ database history:
roll back → encrypted-notebook database file/resources rolled back to notebook-level dir
```
-Parent directories below the history root are not part of AAD. Every history entry retains, in an unambiguous canonical form, the `boxID`, object type, and stable file basename or object identifier at snapshot creation; these values may be encoded by a fixed history layout or stored as metadata committed with the snapshot. Changing only a live document's parent directory leaves its AAD context unchanged; if its basename changes, existing history continues to authenticate with the old basename. Rollback first verifies the ciphertext and that the basename matches the decrypted object ID, then restores under the target parent directory. Re-enveloping is required only when the target basename changes. Missing, malformed, or mismatched snapshot context rejects viewing and rollback; the implementation must not parse ciphertext as plaintext or replace the snapshot basename with the current basename.
+Parent directories below the history root are not part of AAD. Every history entry retains, in an unambiguous canonical form, the `boxID`, object type, and stable file basename or object identifier at snapshot creation; these values may be encoded by a fixed history layout or stored as metadata committed with the snapshot. Changing only a live document's parent directory leaves its AAD context unchanged; if its basename changes, existing history continues to authenticate with the old basename. Rollback first verifies the ciphertext and that the basename matches the decrypted object ID, then restores under the target parent directory. Document rollback also normalizes the tree and resolves duplicate block IDs, so WriteTree serializes the restored content and creates a fresh envelope even when the basename is unchanged. The historical ciphertext remains intact. Copying a deleted notebook back is a closed-state restoration, not proof that the current key backup matches; authentication happens on unlock, and a missing matching backup may be supplied later. Missing, malformed, or mismatched snapshot context rejects viewing and rollback; the implementation must not parse ciphertext as plaintext or replace the snapshot basename with the current basename.
## 9. Block-Ref Cross-Boundary Protection
@@ -374,10 +374,10 @@ The global configuration lock is acquired before any notebook lifecycle lock. An
Persistent formats are layered; global KDF configuration, key envelopes, and per-object data envelopes are not conflated:
-1. **Data-object envelope**: Every `.sy`, asset, and database-definition object contains at least a format marker or version, an algorithm identifier, a cryptographically random nonce unique for the same purpose key, ciphertext, and an authentication tag. The current format constructs AAD deterministically as `format domain + boxID + object type + stable object ID`, excluding parent directories and absolute paths. A `.sy` stable object ID is its canonical basename `<rootID>.sy`; an asset uses its desensitized disk basename, a database definition uses its avID, and a fixed singleton file uses a versioned constant ID. An asset's original name is authenticated encrypted metadata in the same asset container. After decryption, the internal object ID matches the AAD object ID, and duplicate object IDs within one notebook are rejected. AES-GCM nonces come from the operating system CSPRNG; randomness failure aborts the write, and the standard per-purpose-key invocation bound is enforced. An authentication tag cannot retrospectively identify nonce reuse, so the design never claims such reuse will automatically cause authentication failure.
+1. **Data-object envelope**: Every `.sy`, asset, and database-definition object contains at least a format marker or version, an algorithm identifier, a 96-bit nonce generated by the operating system CSPRNG, ciphertext, and an authentication tag. The current format constructs AAD deterministically as `format domain + boxID + object type + stable object ID`, excluding parent directories and absolute paths. A `.sy` stable object ID is its canonical basename `<rootID>.sy`; an asset uses its desensitized disk basename, a database definition uses its avID, and a fixed singleton file uses a versioned constant ID. An asset's original name is authenticated encrypted metadata in the same asset container. After decryption, the internal object ID matches the AAD object ID, and duplicate object IDs within one notebook are rejected. Randomness failure aborts the write. Nonce uniqueness is probabilistic: the current implementation has no persistent per-purpose-key invocation counter shared across restarts, devices, and restored backups, and therefore does not enforce a lifetime invocation bound. This is a limitation, not a guarantee of unlimited safe use. Adding such enforcement requires a versioned multi-device key-lifecycle and recovery design that preserves access to existing data. An authentication tag cannot retrospectively identify nonce reuse, so the design never claims such reuse will automatically cause authentication failure.
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.
+4. **Database compatibility metadata**: SQLCipher version, cipher parameters, index kind, and schema version are stored in the SQLCipher-authenticated encrypted_index_meta table and checked before the index is reused. Content and blocktree indexes are rebuildable; an index without compatibility metadata, with incompatible settings, or that fails to open is closed; after the notebook key and metadata and all source documents authenticate, both indexes may be recreated and populated by mounting. Failure to authenticate a source document preserves the source and residual indexes and returns an error. Rebuilding never weakens cipher parameters or falls back to plaintext SQLite.
5. **Rename and format stability**: The current document format constructs AAD from the stable object ID and is already frozen as a compatibility baseline. 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.
@@ -427,12 +427,12 @@ Native mobile save flows must call `AcquireExportFile` to obtain a lease contain
| Refs, moves, mirrors, assets, and database operations between an encrypted notebook and a normal notebook or another encrypted notebook | Island boundaries hold; rejection creates no partial files, global indexes, or relation data |
| Encrypted asset-container write fails | The caller receives an error, no separate name mapping or plaintext temporary file is created, and an incomplete target file cannot be read as a valid asset |
| Delete an encrypted notebook while retaining history, then disable or restore | A key dependency prevents deletion of global config and backup; the matching backup and master password restore the notebook, and only explicit permanent purge removes the dependency |
-| Move a document's parent directory or change its basename after creating history, then view or restore the old entry | Authenticate and decrypt with the snapshot boxID, object type, and stable basename recorded by the history entry; rollback re-envelopes only when the target basename changes, while missing snapshot context rejects the operation |
+| Move a document's parent directory or change its basename after creating history, then view or restore the old entry | Authenticate and decrypt with the snapshot boxID, object type, and stable basename recorded by the history entry; rollback serializes the restored tree and re-envelopes it with the target basename while preserving the historical ciphertext, while missing snapshot context rejects the operation |
| Disk inspection of files, assets, databases, WAL/SHM, history, snapshots, and logs | No readable body, asset contents, original asset names, or plaintext SQLite pages exist in encrypted-notebook persistent locations; `temp/` may contain plaintext during export or after cleanup failure |
| Restart after an abnormal exit | Startup removes at least entries under `temp/export/` whose first-level name is a valid boxID; generic temporary-directory initialization may also remove other exports and plugin temporary files |
| Ciphertext tampering, path substitution, and backup corruption | Authentication or format validation fails safely; never fall back to a normal path, generate replacement key material, or silently overwrite configuration |
| Both an encrypted notebook's `conf.json` and notebook key backup are missing, or sync removes an encrypted notebook that is currently open locally | Ciphertext or runtime identity puts the former in `Error` without creating a normal configuration; the latter drains in-flight leases and clears the DEK, mount, dedicated databases, caches, and indexes even though `Conf.GetBox` is empty after deletion |
-| Nonce randomness failure, reaching a purpose-key invocation bound, or discovering nonce reuse afterwards | Reject before encryption on randomness failure or bound exhaustion; AES-GCM authentication cannot detect nonce reuse that already occurred, so discovery is handled as a key-compromise incident by rotating the DEK and re-encrypting data |
+| Nonce randomness failure or discovering nonce reuse afterwards | Reject before encryption on randomness failure; no persistent lifetime invocation bound is currently enforced. AES-GCM authentication cannot detect nonce reuse that already occurred; discovery requires migration to a new DEK, not merely changing the master password |
| Replay an authenticated historical ciphertext object or key backup | It may validate as an authentic old version but is never claimed to be freshest or from a trusted source; rollback risk is explicit, and the current design does not claim rollback prevention |
| Master-password change and KEK rewrapping | WrappedDEKs and backup update atomically; an interrupted update leaves the old configuration recoverably usable; the old-password exposure warning is accurate; data and history are verifiably readable before and after migration |
| Concurrent multi-notebook operations and auto-lock | Lock order has no deadlock; authenticated UI activity or an explicit keepalive refreshes all currently unlocked notebooks, while background work does not refresh them automatically; a locking notebook admits no new lease |
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 3f7472cf18..d4b436129b 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -210,11 +210,11 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
关闭/退出前自动生成历史 → 确保锁定后定时器无法生成时不丢历史
历史索引 → content 留空(密文不进搜索索引)
查看历史 → 读取快照 boxID + 对象类型 + 稳定文件基名,以三者构造原 AAD 解密(需笔记本已解锁)
- 回滚 → 按快照 AAD 解密历史 → 校验根块 ID 与文件基名一致 → 加载 tree → 文件基名不变时可原样恢复密文,变化时由 WriteTree 重新封装
+ 回滚 → 按快照 AAD 解密历史 → 校验根块 ID 与文件基名一致 → 加载 tree → 由 WriteTree 序列化恢复后的内容,并按目标文件基名重新封装
已删除笔记本历史:
删除前 → 整个目录密文备份到历史目录
- 恢复 → 使用匹配的全局密钥备份和主密码验证 WrappedDEK 后,将密文目录原样拷回
+ 恢复 → 将密文目录原样拷回并保持关闭,解锁时再使用匹配的全局密钥备份和主密码验证 WrappedDEK
密钥保留 → 只要内核管理的该类历史仍可恢复,就禁止删除其依赖的全局密钥备份;永久清除历史后才解除依赖
数据库历史:
@@ -223,7 +223,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
回滚 → 加密笔记本的数据库文件/资源回滚到笔记本级目录
```
-历史文件在历史目录中的父路径不是 AAD 的组成部分。每个历史条目必须以不可歧义的规范格式保留快照写入时的 `boxID`、对象类型和稳定文件基名或对象标识;可由固定历史目录布局编码,也可由随快照提交的元数据记录。文档只改变父目录时 AAD 上下文保持不变;文件基名改变时,既有历史仍使用旧基名认证解密。回滚时先验证密文、文件基名与解密后对象 ID 一致,再按目标父目录恢复;仅当目标文件基名变化时才按新基名重新封装。快照上下文缺失、格式不合法或与密文不匹配时必须拒绝查看和回滚,不得把密文当明文解析或使用当前文件基名替代快照基名。
+历史文件在历史目录中的父路径不是 AAD 的组成部分。每个历史条目必须以不可歧义的规范格式保留快照写入时的 `boxID`、对象类型和稳定文件基名或对象标识;可由固定历史目录布局编码,也可由随快照提交的元数据记录。文档只改变父目录时 AAD 上下文保持不变;文件基名改变时,既有历史仍使用旧基名认证解密。回滚时先验证密文、文件基名与解密后对象 ID 一致,再按目标父目录恢复;文档回滚还会规范化树结构并处理重复块 ID,因此即使文件基名不变,也由 WriteTree 序列化恢复后的内容并生成新封装,历史源密文保持不变。已删除笔记本的目录拷回属于关闭状态的恢复,不代表当前密钥备份已匹配;认证在解锁时执行,缺少匹配备份时可在之后补充恢复材料。快照上下文缺失、格式不合法或与密文不匹配时必须拒绝查看和回滚,不得把密文当明文解析或使用当前文件基名替代快照基名。
## 9. 块引跨加密边界防护
@@ -374,10 +374,10 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
持久化格式分层,不能把全局 KDF 配置、密钥包络和每个数据对象的封装混为一体:
-1. **数据对象封装**:每个 `.sy`、资源和数据库定义对象至少包含格式标识或版本、算法标识、密码学安全随机生成且对同一用途密钥唯一的 nonce、密文和认证标签。当前格式的 AAD 按 `格式域 + boxID + 对象类型 + 稳定对象 ID` 确定性构造,不包含父目录或绝对路径;`.sy` 的稳定对象 ID 是规范化文件基名 `<rootID>.sy`,资源使用脱敏磁盘文件基名,数据库定义使用 avID,固定单例文件使用版本化常量 ID。资源的原始名称作为同一资源容器内的认证加密元数据保存。解密后必须验证对象内部 ID 与 AAD 对象 ID 一致,并拒绝同一笔记本内的重复对象 ID。AES-GCM nonce 由操作系统 CSPRNG 生成,随机源失败必须终止写入,并按标准规定限制每个用途密钥的调用规模;认证标签不能事后识别已经发生的 nonce 重用,因此不得宣称此类重用会被认证失败自动发现。
+1. **数据对象封装**:每个 `.sy`、资源和数据库定义对象至少包含格式标识或版本、算法标识、由操作系统 CSPRNG 生成的 96 位 nonce、密文和认证标签。当前格式的 AAD 按 `格式域 + boxID + 对象类型 + 稳定对象 ID` 确定性构造,不包含父目录或绝对路径;`.sy` 的稳定对象 ID 是规范化文件基名 `<rootID>.sy`,资源使用脱敏磁盘文件基名,数据库定义使用 avID,固定单例文件使用版本化常量 ID。资源的原始名称作为同一资源容器内的认证加密元数据保存。解密后必须验证对象内部 ID 与 AAD 对象 ID 一致,并拒绝同一笔记本内的重复对象 ID。随机源失败必须终止写入。nonce 唯一性依赖概率保证:当前实现没有跨重启、设备和备份恢复共享的持久化用途密钥调用计数,不能强制限制密钥整个生命周期的调用规模。这是现有限制,不代表可以无限量安全使用;后续实施强制限制需要版本化的多设备密钥生命周期与恢复方案,并保留现有数据的访问能力。认证标签不能事后识别已经发生的 nonce 重用,因此不得宣称此类重用会被认证失败自动发现。
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。
+4. **数据库兼容信息**:SQLCipher 版本、cipher 参数、索引类型和 schema 版本保存在受 SQLCipher 认证的 encrypted_index_meta 表中,复用索引前必须校验。content 与 blocktree 索引可重建;缺少兼容信息、参数不兼容或打开失败时关闭索引,在笔记本密钥、元数据及全部源文档认证通过后,可以重新创建两个索引并在挂载时填充。源文档认证失败时保留源密文和残留索引并报错,重建不得降低 cipher 参数或回退到明文 SQLite。
5. **改名与格式稳定性**:当前文档格式以稳定对象 ID 构造 AAD,已经冻结为兼容基线。已写入的无版本字段 `SYAE` 资源继续按旧格式读取,不得因升级第 2 版而要求用户删除或重建附件;写入统一使用第 2 版,读取不强制迁移磁盘或历史快照。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。未来修改信封、AAD 语义或密钥派生方式必须使用明确的格式版本,保留旧版认证读取路径,或在移除旧版读取前提供可恢复迁移。迁移必须先认证源数据,保留原始数据和匹配的恢复材料,失败或中断后仍可恢复;不得通过重置 MasterSalt、丢弃密钥或删除数据解决格式不兼容。未知格式、损坏或认证失败必须保留原文件并报错,不得回退到明文或绕过认证。每次格式变更都必须以受支持旧格式的样本验证受影响的读取、导出、历史、备份和恢复路径。
SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副本都是受保护对象,必须放在受控目录并使用对应的用途密钥。锁定、崩溃恢复和历史快照必须枚举这些伴随文件;未加密 SQLite 页面、查询结果或诊断转储不得写入全局临时目录。
@@ -431,12 +431,12 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
| 通用归档入口的父目录、压缩包内部路径及符号链接指向加密笔记本 | 打包前检查全部源条目,解压前检查全部目标条目;非法归档不得先写入其他条目,正常归档仍可使用 |
| 块读取省略 notebook 参数,或批量请求跨多个加密笔记本 | 根据块的实际归属取得所有相关笔记本的响应租约,锁定等到响应写入完成;无法确定归属时拒绝读取,不在后续解锁后无租约返回内容 |
| 删除加密笔记本后保留历史,再尝试禁用或恢复 | 存在密钥依赖时拒绝删除全局配置和备份;使用匹配备份与主密码可恢复,只有明确永久清除恢复数据后才允许解除依赖 |
-| 文档生成历史后移动父目录或改变文件基名,再查看或回滚旧历史 | 使用历史条目记录的快照 boxID、对象类型和稳定文件基名认证解密;仅在目标基名变化时重新封装,缺失快照上下文时拒绝操作 |
+| 文档生成历史后移动父目录或改变文件基名,再查看或回滚旧历史 | 使用历史条目记录的快照 boxID、对象类型和稳定文件基名认证解密;序列化恢复后的树并按目标基名重新封装,保留历史源密文,缺失快照上下文时拒绝操作 |
| 文件、资源、数据库、WAL/SHM、历史、快照和日志的磁盘检查 | 加密笔记本持久化范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页;`temp/` 可能在导出期间或清理失败后包含明文 |
| 异常退出后重启 | 启动时至少删除 `temp/export/` 下第一层名称为合法 boxID 的残留目录;通用临时目录初始化可以同时清理其他导出和插件临时文件 |
| 密文篡改、路径替换和备份损坏 | 认证或格式校验失败并安全拒绝;不回退普通路径、不生成新密钥材料、不静默覆盖配置 |
| 加密笔记本的 `conf.json` 与笔记本密钥备份同时缺失,或同步删除当前已打开的加密笔记本 | 密文或运行时身份使前者进入 `Error` 且不生成普通配置;后者先排空在途租约,再清除 DEK、挂载、专属数据库、缓存和索引,不受删除后 `Conf.GetBox` 为空影响 |
-| nonce 随机源失败、达到用途密钥调用限制或事后发现 nonce 重用 | 随机源失败或达到限制时在加密前拒绝写入;AES-GCM 认证本身不能发现已发生的 nonce 重用,发现后必须按密钥泄露事件处理并轮换 DEK 后重新加密 |
+| nonce 随机源失败或事后发现 nonce 重用 | 随机源失败时在加密前拒绝写入;当前未强制实施持久化的生命周期调用限制。AES-GCM 认证本身不能发现已发生的 nonce 重用,发现后需要迁移到新 DEK,仅修改主密码无效 |
| 回放认证有效的历史密文或密钥备份 | 可能被识别为有效旧版本,但不得被宣称为最新或来源可信;数据回退风险明确,当前设计不声称提供回滚防护 |
| 改主密码和 KEK 重新包络 | WrappedDEK、历史 KEK 和备份通过可恢复事务更新;连续改密、删除笔记本、备份导入与迁移中断后仍可用当前密码恢复旧包络;旧密码暴露风险提示正确 |
| 多个笔记本并发操作与自动锁定 | 锁顺序无死锁;认证用户界面活动或显式保活统一刷新所有当前已解锁笔记本,后台任务不自动刷新;锁定中的笔记本不再接受新租约 |
diff --git a/kernel/api/archive.go b/kernel/api/archive.go
index a577c7d14e..1731c92add 100644
--- a/kernel/api/archive.go
+++ b/kernel/api/archive.go
@@ -139,7 +139,18 @@ func zip(c *gin.Context) {
return
}
- zipFile, err := gulu.Zip.Create(zipAbsFilePath)
+ resolvedZipPath, err := resolveArchivePath(zipAbsFilePath)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if err = rejectEncryptedArchivePath(resolvedZipPath); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ zipFile, err := gulu.Zip.Create(resolvedZipPath)
if err != nil {
logging.LogErrorf("create zip [%s] failed: %s", zipAbsFilePath, err)
ret.Code = -1
@@ -148,10 +159,10 @@ func zip(c *gin.Context) {
}
base := filepath.Base(entryAbsPath)
- if gulu.File.IsDir(entryAbsPath) {
- err = zipFile.AddDirectory(base, entryAbsPath)
+ if gulu.File.IsDir(resolvedEntryPath) {
+ err = zipFile.AddDirectory(base, resolvedEntryPath)
} else {
- err = zipFile.AddEntry(base, entryAbsPath)
+ err = zipFile.AddEntry(base, resolvedEntryPath)
}
if err != nil {
logging.LogErrorf("zip add entry [%s] failed: %s", entryAbsPath, err)
diff --git a/kernel/api/file.go b/kernel/api/file.go
index 56e8fc3e3e..288a4e53c1 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -102,6 +102,11 @@ func getUniqueFilename(c *gin.Context) {
return
}
+ if rejectEncryptedBoxPath(filePath) {
+ ret.Code = -3
+ ret.Msg = model.Conf.Language(321)
+ return
+ }
ret.Data = map[string]any{
"path": util.GetUniqueFilename(filePath),
}
diff --git a/kernel/api/file_authorization_test.go b/kernel/api/file_authorization_test.go
index 32036caa9b..6d68cff218 100644
--- a/kernel/api/file_authorization_test.go
+++ b/kernel/api/file_authorization_test.go
@@ -21,11 +21,13 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestGetUniqueFilenameAuthorization(t *testing.T) {
@@ -81,3 +83,38 @@ func TestGetUniqueFilenameAuthorization(t *testing.T) {
})
}
}
+
+func TestGetUniqueFilenameRejectsEncryptedNotebook(t *testing.T) {
+ root, boxID := setupArchiveWorkspace(t)
+ oldConf := model.Conf
+ model.Conf = model.NewAppConf()
+ t.Cleanup(func() { model.Conf = oldConf })
+ for _, name := range []string{"existing.sy", "missing.sy"} {
+ filePath := filepath.Join(util.DataDir, boxID, name)
+ if name == "existing.sy" {
+ if err := os.WriteFile(filePath, []byte("ciphertext"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ body, err := json.Marshal(map[string]string{"path": filePath})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result := callArchiveAPI(t, getUniqueFilename, string(body))
+ if result.Code != -3 || result.Data != nil {
+ t.Fatalf("encrypted filename existence was exposed: %+v", result)
+ }
+ }
+ filePath := filepath.Join(root, "normal.txt")
+ if err := os.WriteFile(filePath, []byte("normal"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ body, err := json.Marshal(map[string]string{"path": filePath})
+ if err != nil {
+ t.Fatal(err)
+ }
+ result := callArchiveAPI(t, getUniqueFilename, string(body))
+ if result.Code != 0 || result.Data.(map[string]any)["path"] != filepath.Join(root, "normal (1).txt") {
+ t.Fatalf("normal filename allocation failed: %+v", result)
+ }
+}
diff --git a/kernel/cli/cmd/root.go b/kernel/cli/cmd/root.go
index da7b5a38e1..0118b68476 100644
--- a/kernel/cli/cmd/root.go
+++ b/kernel/cli/cmd/root.go
@@ -190,6 +190,29 @@ func rejectEncryptedNotebookCLI(cmd *cobra.Command, args []string) error {
}
}
}
+ if cmd == historyGetCmd || cmd == historyRollbackCmd {
+ historyPath, _ := cmd.Flags().GetString("path")
+ if historyPath != "" {
+ if !filepath.IsAbs(historyPath) {
+ historyPath = filepath.Join(util.WorkspaceDir, historyPath)
+ }
+ if model.IsEncryptedHistoryPath(filepath.Clean(historyPath)) {
+ return fmt.Errorf("CLI does not support encrypted notebook history")
+ }
+ }
+ }
+ if cmd.Parent() == repoFileCmd {
+ fileID, _ := cmd.Flags().GetString("id")
+ if fileID != "" {
+ boxID, err := model.ResolveRepoFileBoxID(fileID)
+ if err != nil {
+ return err
+ }
+ if boxID != "" {
+ return fmt.Errorf("CLI does not support encrypted notebook [%s]", boxID)
+ }
+ }
+ }
return nil
}
diff --git a/kernel/cli/cmd/root_test.go b/kernel/cli/cmd/root_test.go
index e288df9e0b..a8a8c0cbd2 100644
--- a/kernel/cli/cmd/root_test.go
+++ b/kernel/cli/cmd/root_test.go
@@ -9,8 +9,12 @@
package cmd
import (
+ "os"
"path/filepath"
"testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+ "github.com/spf13/cobra"
)
func TestIsEncryptedNotebookWorkspacePathWith(t *testing.T) {
@@ -38,3 +42,43 @@ func TestIsEncryptedNotebookWorkspacePathWith(t *testing.T) {
})
}
}
+
+func TestCLIRejectsEncryptedHistoryPaths(t *testing.T) {
+ oldWorkspace, oldData, oldHistory := util.WorkspaceDir, util.DataDir, util.HistoryDir
+ util.WorkspaceDir = t.TempDir()
+ util.DataDir = filepath.Join(util.WorkspaceDir, "data")
+ util.HistoryDir = filepath.Join(util.WorkspaceDir, "history")
+ t.Cleanup(func() {
+ util.WorkspaceDir, util.DataDir, util.HistoryDir = oldWorkspace, oldData, oldHistory
+ })
+ boxID := "20260907120000-history"
+ historyDir := filepath.Join(util.HistoryDir, "2026-09-07-120000-delete", boxID)
+ if err := os.MkdirAll(filepath.Join(historyDir, ".siyuan"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(historyDir, ".siyuan", "conf.json"), []byte(`{"encrypted":true}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ for _, cmd := range []*cobra.Command{historyGetCmd, historyRollbackCmd} {
+ flag := cmd.Flags().Lookup("path")
+ oldValue := flag.Value.String()
+ t.Cleanup(func() { _ = flag.Value.Set(oldValue) })
+ for _, historyPath := range []string{
+ filepath.Join(historyDir, "20260907120001-history.sy"),
+ filepath.Join("history", "2026-09-07-120000-delete", boxID, "20260907120001-history.sy"),
+ } {
+ if err := flag.Value.Set(historyPath); err != nil {
+ t.Fatal(err)
+ }
+ if err := rejectEncryptedNotebookCLI(cmd, nil); err == nil {
+ t.Fatalf("%s accepted encrypted history: %s", cmd.Name(), historyPath)
+ }
+ }
+ if err := flag.Value.Set(filepath.Join("history", "2026-09-07-120000-update", "20260907130000-normal1", "20260907120001-history.sy")); err != nil {
+ t.Fatal(err)
+ }
+ if err := rejectEncryptedNotebookCLI(cmd, nil); err != nil {
+ t.Fatalf("%s rejected ordinary history: %v", cmd.Name(), err)
+ }
+ }
+}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 3b0d538d08..2671326b54 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -1448,13 +1448,7 @@ func unlockBoxHeld(boxID string, password string, boxEnc *conf.BoxEncryption) (e
// 持锁保护"开 db + 缓存 DEK"的原子性,避免与并发的 LockBox 导致 db/DEK 不一致
cachedDEKsLock.Lock()
- if err = sql.OpenEncryptedDB(boxID, dek); err != nil {
- cachedDEKsLock.Unlock()
- finalState = EncryptedBoxStateError
- return err
- }
- if err = treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {
- sql.RemoveEncryptedDBFile(boxID) // 清理已创建的 content db 文件,避免遗留空加密库
+ if err = openEncryptedBoxIndexes(boxID, dek); err != nil {
cachedDEKsLock.Unlock()
finalState = EncryptedBoxStateError
return err
@@ -2220,6 +2214,7 @@ func ExtractBoxIDFromHistoryPath(absPath string) string {
// 与 filesys.encryptData/decryptData 共用同一 AAD 构造入口,保证加解密一致。
func EncryptFile(boxID, relativePath string, dek, plaintext []byte) ([]byte, error) {
fileKey := util.DeriveSubKey(dek, "siyuan/file")
+ defer zeroAndClear(fileKey)
aad, err := filesys.SyAAD(boxID, relativePath)
if err != nil {
return nil, err
@@ -2230,6 +2225,7 @@ func EncryptFile(boxID, relativePath string, dek, plaintext []byte) ([]byte, err
// DecryptFile 对应解密。
func DecryptFile(boxID, relativePath string, dek, ciphertext []byte) ([]byte, error) {
fileKey := util.DeriveSubKey(dek, "siyuan/file")
+ defer zeroAndClear(fileKey)
aad, err := filesys.SyAAD(boxID, relativePath)
if err != nil {
return nil, err
diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.go
index ba31057580..1eb9dfd02d 100644
--- a/kernel/model/encrypted_export.go
+++ b/kernel/model/encrypted_export.go
@@ -165,6 +165,15 @@ func IsManagedEncryptedExportPath(relativePath string) bool {
return len(parts) >= 1 && ast.IsNodeIDPattern(parts[0])
}
+// normalExportTempName 避免普通导出使用加密导出的第一层归属目录,保留归档内部的原始名称。
+func normalExportTempName(name string) string {
+ parts := strings.SplitN(filepath.ToSlash(filepath.Clean(name)), "/", 2)
+ if ast.IsNodeIDPattern(parts[0]) {
+ parts[0] = "export-" + parts[0]
+ }
+ return filepath.FromSlash(strings.Join(parts, "/"))
+}
+
// AcquireExportArtifactLease 为导出产物取得覆盖整个复制过程的生命周期租约。
func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease, err error) {
if after, ok := strings.CutPrefix(exportPath, "/export/"); ok {
diff --git a/kernel/model/encrypted_export_test.go b/kernel/model/encrypted_export_test.go
index d752821f0a..95b3207b4c 100644
--- a/kernel/model/encrypted_export_test.go
+++ b/kernel/model/encrypted_export_test.go
@@ -31,6 +31,30 @@ func TestManagedEncryptedExportRevocation(t *testing.T) {
}
}
+func TestNormalExportAvoidsEncryptedNamespace(t *testing.T) {
+ oldTempDir := util.TempDir
+ util.TempDir = t.TempDir()
+ t.Cleanup(func() { util.TempDir = oldTempDir })
+ boxID := "20260907120000-export1"
+ for _, name := range []string{boxID, boxID + "/nested", "./" + boxID, "ordinary", boxID + ".md"} {
+ safeName := normalExportTempName(name)
+ if IsManagedEncryptedExportPath(filepath.ToSlash(safeName)) {
+ t.Fatalf("ordinary export entered the encrypted namespace: %q", safeName)
+ }
+ filePath := filepath.Join(util.TempDir, "export", safeName, "result.txt")
+ if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filePath, []byte("ordinary export"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ clearEncryptedExportTempOnBoot()
+ if _, err := os.Stat(filePath); err != nil {
+ t.Fatalf("encrypted export cleanup removed ordinary export: %v", err)
+ }
+ }
+}
+
func TestMobileExportLeaseLifecycle(t *testing.T) {
originalTempDir := util.TempDir
util.TempDir = t.TempDir()
diff --git a/kernel/model/encrypted_history_index_test.go b/kernel/model/encrypted_history_index_test.go
new file mode 100644
index 0000000000..d0f0ffd88d
--- /dev/null
+++ b/kernel/model/encrypted_history_index_test.go
@@ -0,0 +1,269 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+//go:build sqlcipher || libsqlcipher
+
+package model
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestEncryptedHistoryAndIndexRecovery(t *testing.T) {
+ const helperEnv = "SIYUAN_TEST_ENCRYPTED_HISTORY_INDEX"
+ if os.Getenv(helperEnv) != "1" {
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestEncryptedHistoryAndIndexRecovery$", "-test.v")
+ cmd.Env = append(os.Environ(), helperEnv+"=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("encrypted history/index regression failed: %v\n%s", err, output)
+ }
+ return
+ }
+
+ root := t.TempDir()
+ util.WorkspaceDir = root
+ util.DataDir = filepath.Join(root, "data")
+ util.TempDir = filepath.Join(root, "temp")
+ util.ConfDir = filepath.Join(root, "conf")
+ util.HistoryDir = filepath.Join(root, "history")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ Conf = NewAppConf()
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ Conf.Search = conf.NewSearch()
+ Conf.FileTree = conf.NewFileTree()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ password := "history-index-regression-password"
+ if err := EnableEncryptedNotebook(password); err != nil {
+ t.Fatal(err)
+ }
+ boxID, err := CreateEncryptedBox("Encrypted history", password)
+ if err != nil {
+ t.Fatal(err)
+ }
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ boxConf.Closed = false
+ if err = box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ mountedEncryptedBoxes.Store(boxID, true)
+ dek, err := GetDEKIfUnlocked(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dek = bytes.Clone(dek)
+ defer clear(dek)
+ rootID := "20260907100000-history"
+ tree := treenode.NewTree(boxID, "/"+rootID+".sy", "/History", "History")
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.IndexBlockTree(tree)
+ sourcePath := filepath.Join(util.DataDir, boxID, rootID+".sy")
+ historicalData, err := os.ReadFile(sourcePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ relHistory := filepath.Join("history", "2026-09-07-100000-update", boxID, rootID+".sy")
+ historyPath := filepath.Join(root, relHistory)
+ if err = os.MkdirAll(filepath.Dir(historyPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(historyPath, historicalData, 0600); err != nil {
+ t.Fatal(err)
+ }
+ tree.Root.SetIALAttr("title", "Current")
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ currentData, err := os.ReadFile(sourcePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ t.Run("reject mismatched authenticated root ID", func(t *testing.T) {
+ plain, err := DecryptFile(boxID, tree.Path, dek, historicalData)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain = bytes.ReplaceAll(plain, []byte(rootID), []byte("20260907100001-history"))
+ badHistory, err := EncryptFile(boxID, tree.Path, dek, plain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(historyPath, badHistory, 0600); err != nil {
+ t.Fatal(err)
+ }
+ defer os.WriteFile(historyPath, historicalData, 0600)
+ if _, _, _, _, err = GetDocHistoryContent(relHistory, "", false); err == nil {
+ t.Fatal("history preview accepted a mismatched root ID")
+ }
+ if err = RollbackDocHistory(relHistory); err == nil || !strings.Contains(err.Error(), "root ID") {
+ t.Fatalf("history rollback did not validate the authenticated root ID: %v", err)
+ }
+ assertEncryptedFileBytes(t, sourcePath, currentData)
+ })
+
+ t.Run("write failure preserves current document and index", func(t *testing.T) {
+ provider := filesys.DEKProvider
+ defer func() { filesys.DEKProvider = provider }()
+ failure := errors.New("injected history write failure")
+ filesys.DEKProvider = func(string) ([]byte, error) { return nil, failure }
+ if err := RollbackDocHistory(relHistory); !errors.Is(err, failure) {
+ t.Fatalf("write failure was not propagated: %v", err)
+ }
+ assertEncryptedFileBytes(t, sourcePath, currentData)
+ if treenode.GetBlockTree(rootID) == nil {
+ t.Fatal("failed rollback removed the current index")
+ }
+ })
+
+ t.Run("rollback finishes while lock waits", func(t *testing.T) {
+ acquire := filesys.DEKLockAcquire
+ defer func() { filesys.DEKLockAcquire = acquire }()
+ var once sync.Once
+ locked := make(chan struct{})
+ filesys.DEKLockAcquire = func(id string) {
+ once.Do(func() {
+ go func() {
+ LockBox(boxID)
+ close(locked)
+ }()
+ deadline := time.Now().Add(time.Second)
+ for GetEncryptedBoxState(boxID) != EncryptedBoxStateLocking && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if GetEncryptedBoxState(boxID) != EncryptedBoxStateLocking {
+ t.Error("lock did not wait for rollback")
+ }
+ })
+ acquire(id)
+ }
+ if err := RollbackDocHistory(relHistory); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-locked:
+ case <-time.After(3 * time.Second):
+ t.Fatal("lock did not finish after rollback")
+ }
+ data, err := os.ReadFile(sourcePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain, err := DecryptFile(boxID, tree.Path, dek, data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ restored, err := loadTreeByData0(plain)
+ if err != nil || restored.Root.ID != rootID || restored.Root.IALAttr("title") != "History" {
+ t.Fatalf("unexpected restored document: %v", err)
+ }
+ assertEncryptedFileBytes(t, historyPath, historicalData)
+ })
+
+ t.Run("corrupt indexes rebuild after source authentication", func(t *testing.T) {
+ for _, dbPath := range []string{util.EncryptedDBPath(boxID), util.EncryptedBlockTreeDBPath(boxID)} {
+ if err := os.WriteFile(dbPath, []byte("damaged index"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ crypt, err := GetBoxEncryption(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := UnlockBox(boxID, password, crypt); err != nil {
+ t.Fatalf("unlock could not rebuild damaged indexes: %v", err)
+ }
+ if err := util.CheckEncryptedIndexCompatibility(sql.GetEncryptedDB(boxID), "content", 1); err != nil {
+ t.Fatal(err)
+ }
+ })
+
+ for _, mutation := range []string{
+ "DROP TABLE encrypted_index_meta",
+ "UPDATE encrypted_index_meta SET schema_version = 2",
+ "UPDATE encrypted_index_meta SET kind = 'blocktree'",
+ "UPDATE encrypted_index_meta SET cipher_settings = '{}'",
+ } {
+ t.Run("incompatible index preserves source: "+mutation, func(t *testing.T) {
+ db := sql.GetEncryptedDB(boxID)
+ if _, err := db.Exec(mutation); err != nil {
+ t.Fatal(err)
+ }
+ sql.CloseEncryptedDB(boxID)
+ treenode.CloseEncryptedBlockTreeDB(boxID)
+ before, err := os.ReadFile(sourcePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = openEncryptedBoxIndexes(boxID, dek); err != nil {
+ t.Fatal(err)
+ }
+ assertEncryptedFileBytes(t, sourcePath, before)
+ })
+ }
+
+ t.Run("source authentication failure preserves residual indexes", func(t *testing.T) {
+ sql.CloseEncryptedDB(boxID)
+ treenode.CloseEncryptedBlockTreeDB(boxID)
+ for _, dbPath := range []string{util.EncryptedDBPath(boxID), util.EncryptedBlockTreeDBPath(boxID)} {
+ if err := os.WriteFile(dbPath, []byte("preserve damaged index"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(sourcePath, []byte("invalid source ciphertext"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := openEncryptedBoxIndexes(boxID, dek); err == nil {
+ t.Fatal("index recovery accepted unauthenticated source data")
+ }
+ assertEncryptedFileBytes(t, sourcePath, []byte("invalid source ciphertext"))
+ for _, dbPath := range []string{util.EncryptedDBPath(boxID), util.EncryptedBlockTreeDBPath(boxID)} {
+ assertEncryptedFileBytes(t, dbPath, []byte("preserve damaged index"))
+ }
+ })
+ cache.ClearTreeCache()
+}
+
+func assertEncryptedFileBytes(t *testing.T, filePath string, expected []byte) {
+ t.Helper()
+ actual, err := os.ReadFile(filePath)
+ if err != nil || !bytes.Equal(actual, expected) {
+ t.Fatalf("unexpected file change [%s]: %v", filepath.Base(filePath), err)
+ }
+}
diff --git a/kernel/model/encrypted_index.go b/kernel/model/encrypted_index.go
new file mode 100644
index 0000000000..10713e7449
--- /dev/null
+++ b/kernel/model/encrypted_index.go
@@ -0,0 +1,87 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package model
+
+import (
+ "fmt"
+ "io/fs"
+ "path/filepath"
+ "strings"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// openEncryptedBoxIndexes 只在源文档认证成功后重建不兼容或损坏的派生索引,保留源密文和密钥材料。
+// 调用方持有笔记本写锁,且已验证密钥包络和笔记本元数据。
+func openEncryptedBoxIndexes(boxID string, dek []byte) error {
+ open := func() error {
+ if err := sql.OpenEncryptedDB(boxID, dek); err != nil {
+ return err
+ }
+ return treenode.OpenEncryptedBlockTreeDB(boxID, dek)
+ }
+ if err := open(); err == nil {
+ return nil
+ }
+ sql.CloseEncryptedDB(boxID)
+ treenode.CloseEncryptedBlockTreeDB(boxID)
+ if err := authenticateEncryptedIndexDocuments(boxID, dek); err != nil {
+ return fmt.Errorf("cannot rebuild encrypted indexes: %w", err)
+ }
+ sql.RemoveEncryptedDBFile(boxID)
+ treenode.RemoveEncryptedBlockTreeDBFile(boxID)
+ if err := open(); err != nil {
+ sql.RemoveEncryptedDBFile(boxID)
+ treenode.RemoveEncryptedBlockTreeDBFile(boxID)
+ return err
+ }
+ return nil
+}
+
+func authenticateEncryptedIndexDocuments(boxID string, dek []byte) error {
+ boxDir := filepath.Join(util.DataDir, boxID)
+ ids := map[string]struct{}{}
+ return filepath.WalkDir(boxDir, func(filePath string, entry fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ if entry.IsDir() {
+ if filePath != boxDir && !ast.IsNodeIDPattern(entry.Name()) {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(entry.Name(), ".sy") {
+ return nil
+ }
+ if entry.Type()&fs.ModeSymlink != 0 {
+ return fmt.Errorf("encrypted document is a symbolic link [%s]", entry.Name())
+ }
+ data, err := filelock.ReadFile(filePath)
+ if err != nil {
+ return err
+ }
+ plain, err := DecryptFile(boxID, entry.Name(), dek, data)
+ if err != nil {
+ return err
+ }
+ tree, err := loadTreeByData0(plain)
+ if err != nil {
+ return err
+ }
+ if tree == nil || tree.Root == nil || tree.Root.ID+".sy" != entry.Name() {
+ return fmt.Errorf("encrypted document root ID does not match filename [%s]", entry.Name())
+ }
+ if _, exists := ids[tree.Root.ID]; exists {
+ return fmt.Errorf("duplicate encrypted document ID [%s]", tree.Root.ID)
+ }
+ ids[tree.Root.ID] = struct{}{}
+ return nil
+ })
+}
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 78529e963e..60ed55aefb 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -2621,7 +2621,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i
return
}
}
- exportDir := filepath.Join(util.TempDir, "export", baseFolderName)
+ exportDir := filepath.Join(util.TempDir, "export", normalExportTempName(baseFolderName))
if encrypted {
exportDir = filepath.Join(util.TempDir, "export", boxID, "sy", exportID)
}
@@ -4377,7 +4377,7 @@ func exportPandocConvertZip0(boxID, baseFolderName string, docPaths, defBlockIDs
return
}
}
- exportFolder := filepath.Join(util.TempDir, "export", baseFolderName+ext)
+ exportFolder := filepath.Join(util.TempDir, "export", normalExportTempName(baseFolderName+ext))
if encrypted {
exportFolder = filepath.Join(util.TempDir, "export", boxID, "markdown", exportID)
}
diff --git a/kernel/model/history.go b/kernel/model/history.go
index 2bf5ea2fe8..d343fd1538 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -43,6 +43,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/search"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
@@ -216,6 +217,9 @@ func GetDocHistoryContent(historyPath, keyword string, highlight bool) (id, root
}
id = historyTree.Root.ID
rootID = historyTree.Root.ID
+ if ciphertext && rootID+".sy" != filepath.Base(historyPath) {
+ return "", "", "", false, errors.New("encrypted document history root ID does not match its filename")
+ }
if !isLargeDoc {
renderTree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument}}
@@ -285,6 +289,14 @@ func RollbackDocHistory(historyPath string) (err error) {
}
boxID := parts[1]
origBoxID := boxID // 保留原始 boxID 用于解密(getRollbackBox 可能返回不同的 box)
+ encrypted := IsEncryptedBox(origBoxID)
+ if encrypted {
+ // 整个回滚持有操作租约,内部文件读写可独立获取读锁,锁定等待租约结束后再申请写锁。
+ if err = AcquireEncryptedBoxOperation(origBoxID); err != nil {
+ return
+ }
+ defer ReleaseEncryptedBoxOperation(origBoxID)
+ }
// 加密笔记本的历史回滚要求原笔记本已挂载:
// WriteTree 根据 tree.Box 判断是否加密落盘。若原笔记本未挂载导致
@@ -330,9 +342,7 @@ func RollbackDocHistory(historyPath string) (err error) {
if !ciphertext && IsEncryptedBox(origBoxID) {
return fmt.Errorf("encrypted notebook document history is plaintext [%s]", origBoxID)
}
- if IsEncryptedBox(origBoxID) {
- HoldBoxReadLock(origBoxID)
- defer ReleaseBoxReadLock(origBoxID)
+ if encrypted {
dek, dekErr := GetDEKIfUnlocked(origBoxID)
if dekErr != nil {
err = errors.New(Conf.Language(314))
@@ -356,6 +366,9 @@ func RollbackDocHistory(historyPath string) (err error) {
if tree == nil {
return errors.New("parse document history failed")
}
+ if encrypted && tree.Root.ID+".sy" != filepath.Base(historyPath) {
+ return errors.New("encrypted document history root ID does not match its filename")
+ }
if nil != tree {
historyDir := filepath.Join(util.HistoryDir, parts[0])
@@ -394,16 +407,6 @@ func RollbackDocHistory(historyPath string) (err error) {
}
// 重置重复的块 ID https://github.com/siyuan-note/siyuan/issues/14358
- if nil != workingDoc && "d" == workingDoc.Type {
- workingDocPath := filepath.Join(util.DataDir, boxID, workingDoc.Path)
- if err = filelock.Remove(workingDocPath); err != nil {
- return
- }
- logging.LogInfof("removed working doc file [%s]", workingDocPath)
- }
- if nil != workingDoc {
- treenode.RemoveBlockTreesByRootID(boxID, rootID)
- }
nodes := map[string]*ast.Node{}
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering || !n.IsBlock() {
@@ -421,6 +424,13 @@ func RollbackDocHistory(historyPath string) (err error) {
var duplicatedIDs []string
for nodeID, exist := range idMap {
if exist {
+ // 被替换文档自身的块保留 ID,其他文档中的重复块才需要重新分配 ID。
+ if workingDoc != nil && workingDoc.Type == "d" {
+ bt := treenode.GetBlockTree(nodeID)
+ if bt != nil && bt.BoxID == boxID && bt.RootID == workingDoc.RootID {
+ continue
+ }
+ }
duplicatedIDs = append(duplicatedIDs, nodeID)
}
}
@@ -435,10 +445,21 @@ func RollbackDocHistory(historyPath string) (err error) {
// 仅重新索引该文档,不进行全量索引
// Reindex only the current document after rolling back the document https://github.com/siyuan-note/siyuan/issues/12320
- sql.RemoveTreeQueue(boxID, rootID)
- if writeErr := indexWriteTreeIndexQueue(tree); nil != writeErr {
+ // 写回成功后再替换索引和清理旧路径,失败时保留当前文档并向调用方返回错误。
+ if _, err = filesys.WriteTree(tree); err != nil {
return
}
+ if workingDoc != nil {
+ if workingDoc.Type == "d" && workingDoc.Path != tree.Path {
+ if err = filelock.Remove(filepath.Join(util.DataDir, boxID, workingDoc.Path)); err != nil {
+ return
+ }
+ }
+ treenode.RemoveBlockTreesByRootID(boxID, rootID)
+ }
+ sql.RemoveTreeQueue(boxID, rootID)
+ treenode.IndexBlockTree(tree)
+ sql.IndexTreeQueue(tree)
ReloadFiletree()
ReloadProtyle(rootID)
@@ -1339,7 +1360,7 @@ func indexHistoryDir(name string, luteEngine *lute.Lute) {
p := strings.TrimPrefix(database, util.HistoryDir)
p = filepath.ToSlash(p[1:])
- // 加密笔记本的 AV 历史是密文,直接存密文作为 content
+ // 加密笔记本的 AV 历史不向全局历史索引写入内容。
relDb := strings.TrimPrefix(database, entryPath+string(os.PathSeparator))
relDb = filepath.ToSlash(relDb)
dbParts := strings.SplitN(relDb, "/", 2)
diff --git a/kernel/sql/database.go b/kernel/sql/database.go
index 26bf72b6d1..a31689a7b1 100644
--- a/kernel/sql/database.go
+++ b/kernel/sql/database.go
@@ -1967,6 +1967,7 @@ func OpenEncryptedDB(boxID string, dek []byte) (err error) {
dbPath := util.EncryptedDBPath(boxID)
// 派生 content 子密钥,与 blocktree/assets/file/AV 用途分离
contentKey := util.DeriveSubKey(dek, "siyuan/sqlcipher/content")
+ defer clear(contentKey)
// SQLCipher DSN:_key=x'<hex>' 让 go-sqlite3 执行 PRAGMA key;其余 PRAGMA 与全局 siyuan.db 对齐
dsn := dbPath + "?_journal_mode=WAL&_synchronous=OFF&_mmap_size=4294967296&_secure_delete=OFF" +
"&_cache_size=-128000&_page_size=32768&_busy_timeout=7000&_ignore_check_constraints=ON" +
@@ -1977,6 +1978,10 @@ func OpenEncryptedDB(boxID string, dek []byte) (err error) {
}
boxDB.SetMaxOpenConns(20)
boxDB.SetMaxIdleConns(4)
+ if err = util.CheckEncryptedIndexCompatibility(boxDB, "content", 1); err != nil {
+ boxDB.Close()
+ return err
+ }
if err = initEncryptedDBTables(boxDB); err != nil {
boxDB.Close()
return err
@@ -2020,7 +2025,7 @@ func GetEncryptedBoxIDs() (ret []string) {
func RemoveEncryptedDBFile(boxID string) {
CloseEncryptedDB(boxID)
dbPath := util.EncryptedDBPath(boxID)
- for _, suffix := range []string{"", "-wal", "-shm"} {
+ for _, suffix := range []string{"", "-wal", "-shm", "-journal"} {
if err := os.Remove(dbPath + suffix); err != nil && !os.IsNotExist(err) {
logging.LogErrorf("remove encrypted db file [%s] failed: %s", dbPath+suffix, err)
}
diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go
index e886a77337..80fbb93449 100644
--- a/kernel/treenode/blocktree.go
+++ b/kernel/treenode/blocktree.go
@@ -949,6 +949,7 @@ func OpenEncryptedBlockTreeDB(boxID string, dek []byte) (err error) {
}
dbPath := util.EncryptedBlockTreeDBPath(boxID)
blocktreeKey := util.DeriveSubKey(dek, "siyuan/sqlcipher/blocktree")
+ defer clear(blocktreeKey)
dsn := dbPath + "?_journal_mode=WAL&_synchronous=OFF&_mmap_size=4294967296&_secure_delete=OFF" +
"&_cache_size=-128000&_page_size=32768&_busy_timeout=7000&_ignore_check_constraints=ON" +
"&_temp_store=MEMORY&_case_sensitive_like=OFF&_key=x'" + hex.EncodeToString(blocktreeKey) + "'"
@@ -959,6 +960,10 @@ func OpenEncryptedBlockTreeDB(boxID string, dek []byte) (err error) {
boxDB.SetMaxOpenConns(7)
boxDB.SetMaxIdleConns(3)
boxDB.SetConnMaxLifetime(365 * 24 * time.Hour)
+ if err = util.CheckEncryptedIndexCompatibility(boxDB, "blocktree", 1); err != nil {
+ boxDB.Close()
+ return err
+ }
if err = initEncryptedBlockTreeTables(boxDB); err != nil {
boxDB.Close()
return err
@@ -993,7 +998,7 @@ func GetOpenedEncryptedBoxIDs() (ret []string) {
func RemoveEncryptedBlockTreeDBFile(boxID string) {
CloseEncryptedBlockTreeDB(boxID)
dbPath := util.EncryptedBlockTreeDBPath(boxID)
- for _, suffix := range []string{"", "-wal", "-shm"} {
+ for _, suffix := range []string{"", "-wal", "-shm", "-journal"} {
if err := os.Remove(dbPath + suffix); err != nil && !os.IsNotExist(err) {
logging.LogErrorf("remove encrypted blocktree db file [%s] failed: %s", dbPath+suffix, err)
}
diff --git a/kernel/util/encrypted_index.go b/kernel/util/encrypted_index.go
new file mode 100644
index 0000000000..7d0151b6bf
--- /dev/null
+++ b/kernel/util/encrypted_index.go
@@ -0,0 +1,65 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package util
+
+import (
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+)
+
+// CheckEncryptedIndexCompatibility 将索引版本保存在受 SQLCipher 认证的表中,拒绝复用缺少版本或参数不匹配的旧索引。
+// schema 由各索引维护,修改表结构时递增;索引重建由已认证源文档的调用方负责。
+func CheckEncryptedIndexCompatibility(db *sql.DB, kind string, schema int) error {
+ settings := map[string]string{}
+ for _, name := range []string{"cipher_version", "cipher_page_size", "kdf_iter", "cipher_hmac_algorithm", "cipher_kdf_algorithm", "cipher_use_hmac"} {
+ var value string
+ if err := db.QueryRow("PRAGMA " + name).Scan(&value); err != nil {
+ return fmt.Errorf("read encrypted index setting %s: %w", name, err)
+ }
+ if value == "" {
+ return fmt.Errorf("missing encrypted index setting %s", name)
+ }
+ settings[name] = value
+ }
+ encoded, err := json.Marshal(settings)
+ if err != nil {
+ return err
+ }
+ var metadataTables int
+ if err = db.QueryRow("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'encrypted_index_meta'").Scan(&metadataTables); err != nil {
+ return err
+ }
+ if metadataTables == 0 {
+ var tables int
+ if err = db.QueryRow("SELECT count(*) FROM sqlite_master WHERE type = 'table'").Scan(&tables); err != nil {
+ return err
+ }
+ if tables != 0 {
+ return errors.New("encrypted index has no compatibility metadata")
+ }
+ if _, err = db.Exec("CREATE TABLE encrypted_index_meta (kind TEXT NOT NULL, schema_version INTEGER NOT NULL, cipher_settings TEXT NOT NULL)"); err != nil {
+ return err
+ }
+ _, err = db.Exec("INSERT INTO encrypted_index_meta VALUES (?, ?, ?)", kind, schema, string(encoded))
+ return err
+ }
+ var storedKind, storedSettings string
+ var storedSchema, rows int
+ if err = db.QueryRow("SELECT count(*) FROM encrypted_index_meta").Scan(&rows); err != nil {
+ return err
+ }
+ if rows != 1 {
+ return errors.New("invalid encrypted index compatibility metadata")
+ }
+ if err = db.QueryRow("SELECT kind, schema_version, cipher_settings FROM encrypted_index_meta").Scan(&storedKind, &storedSchema, &storedSettings); err != nil {
+ return err
+ }
+ if storedKind != kind || storedSchema != schema || storedSettings != string(encoded) {
+ return errors.New("incompatible encrypted index")
+ }
+ return nil
+}