An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Harden encrypted notebook lifecycle boundaries https://github.com/siyuan-note/siyuan/issues/18034
Daniel9726f5d230b6
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 407789e01e..e61274cfda 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -242,14 +242,14 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma| Scenario | Interaction ||---|---|-| Enable | Settings → Authentication → Encrypted Notebook → toggle → set master password (double input + risk confirmation) |+| Enable | Settings - Authentication - Encrypted Notebook, then enable the toggle and set a master password (double input + risk confirmation) || Disable | Supported only when no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on the current key backup; otherwise reject, or require explicit permanent purge of those recovery artifacts before deleting global config and backup |-| Create | File panel "more" menu → "New encrypted notebook" → enter name + master password → auto-unlock and open |+| Create | File panel - "more" menu - "New encrypted notebook"; enter a name and master password to unlock and open automatically || Icon | Shows lock icon when closed (locked); restores user emoji when opened (unlocked) |-| Unlock | Click a closed encrypted notebook → master-password prompt (🔓 Unlock xxx) → wait ~1s → opens |+| Unlock | Click a closed encrypted notebook, enter the password in the master-password prompt (🔓 Unlock xxx), and wait about one second for it to open || Lock | Equals close: first block new operations, wait for or cancel in-flight work, then remove managed DEK handles, delete encrypted SQLite databases, and best-effort clean kernel-managed plaintext caches, temporary files, and access tokens. Unsaved edits and file history are automatically saved before locking || Auto-lock | Each unlocked notebook stores its own last-activity time. Real UI interaction by an authenticated user in the current workspace refreshes all currently unlocked encrypted notebooks together. A headless client can perform the same refresh through an explicit keepalive endpoint that requires authentication and the administrator role; background reads, sync, indexing, and other non-user activity do not keep notebooks alive automatically |-| Change password | Settings → Authentication → Encrypted Notebook → "Change master password" |+| Change password | Settings - Authentication - Encrypted Notebook - "Change master password" || Move document | A parent-only move within an encrypted notebook moves ciphertext verbatim and updates indexes; a basename change re-envelopes content. Moves between normal notebooks remain normal; cross-boundary (normal↔encrypted) moves are rejected with a prompt || Doc to heading | Cross-boundary rejected with a prompt || Block ref | Normal refs within an encrypted notebook (searching `((` only searches this notebook; backlinks panel displays normally); cross-boundary (normal↔encrypted, encrypted A↔encrypted B) blocked |@@ -350,6 +350,8 @@ The following are outside this feature's security boundary and must be stated inThe global state is `Disabled`, `Enabled`, or `RecoveryRequired`. In normal steady state, `Disabled` has no live encrypted notebook or kernel-enumerable key dependency. If startup discovers encrypted notebooks or recovery artifacts while global configuration is missing or disabled, it enters `RecoveryRequired`, never treats them as normal notebooks, and waits for a matching key backup to be restored. Under `Enabled`, each encrypted notebook independently has one of these states: `Locked`, `Unlocking`, `Unlocked`, `Locking`, or `Error`, and starts as `Locked` after application startup.+Encrypted identity detection is fail-closed. If a valid boxID has a missing or damaged `conf.json` or notebook key backup, the presence of a current ciphertext marker or an encryption identity already confirmed by the current process puts the notebook in `Error` and denies normal-notebook reads and writes; the kernel never auto-creates an `Encrypted=false` configuration. Only the notebook-deletion flow may remove the runtime identity, after draining lifecycle leases and clearing the local DEK, mount marker, dedicated databases, and caches.+| Transition | Preconditions | Invariants after success | Failure handling ||---|---|---|---|| `Locked → Unlocking → Unlocked` | Master-password verification succeeds and ciphertext configuration matches | A usable DEK handle exists only in managed memory; dedicated databases are open; notebook-specific entry points are allowed | Revoke derived KEK/DEK handles, close opened resources, and return to `Locked` |@@ -357,7 +359,7 @@ The global state is `Disabled`, `Enabled`, or `RecoveryRequired`. In normal stea| `Unlocked → Error` | Ciphertext authentication fails, database opening fails, or an invariant is violated | Immediately deny reads and writes; never fall back to a normal-notebook path | Close resources and retain diagnostics without plaintext; the user can only lock or unlock again || Change master password | All encrypted notebooks are `Locked` | All WrappedDEKs, global configuration, and backup update as one recoverable transaction | Keep old configuration and backup usable; no subset of notebooks becomes unlockable only with the new password |-One lifecycle controller per notebook manages state, operation admission, and the active-operation count. Reads, edits, exports, previews, sync, indexing, history view or restore, and AI/MCP access obtain a shared lifecycle lease only while `Unlocked`, and hold it through parsing, cache publication, HTTP response or download completion, and asynchronous-result registration. Lock and delete atomically change the state to `Locking` and close admission, acquire the exclusive lifecycle lease after cancelling or draining active work, then close databases, revoke managed DEK handles, and best-effort clean caches and temporary artifacts while exclusive. They publish `Locked` after key handles and database connections are removed; a temporary-file deletion failure does not block locking, but it is logged and retried on exit or next startup. No new plaintext response, cache refill, or database reconnection may occur after locking completes, but a temporary plaintext copy whose deletion failed may remain on disk.+One lifecycle controller per notebook manages state, operation admission, and the active-operation count. Reads, edits, exports, previews, sync, indexing, history view or restore, and AI/MCP access obtain a shared lifecycle lease only while `Unlocked`, and hold it through parsing, cache publication, HTTP response or download completion, and asynchronous-result registration. Unlock-and-open completes under one per-notebook transition lock; a mount failure rolls back only an unlock created by that operation and never locks a DEK or mount already used by a concurrent request. Lock and delete atomically change the state to `Locking` and close admission, acquire the exclusive lifecycle lease after cancelling or draining active work, then close databases, revoke managed DEK handles, and best-effort clean caches and temporary artifacts while exclusive. They publish `Locked` after key handles and database connections are removed; a temporary-file deletion failure does not block locking, but it is logged and retried on exit or next startup. No new plaintext response, cache refill, or database reconnection may occur after locking completes, but a temporary plaintext copy whose deletion failed may remain on disk.The global configuration lock is acquired before any notebook lifecycle lock. An operation involving multiple notebooks acquires lifecycle locks in lexicographic boxID order. DEK-cache, database, file, and other subsystem locks are acquired only after lifecycle locks and released before them. Reverse acquisition, reacquiring the global configuration lock while holding a subsystem lock, and acquiring a lower-level lock while holding a higher-level one are forbidden. Auto-lock stores activity time per notebook, but one authenticated user interaction in the current workspace or an explicit keepalive refreshes every unlocked notebook together. A periodic job checks elapsed time using the system clock, so a system-clock adjustment can advance or delay the trigger accordingly; auto-lock is a convenience protection, not a precise security timing boundary.@@ -420,6 +422,7 @@ Native mobile save flows must call `AcquireExportFile` to obtain a lease contain| 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 || 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 |@@ -428,21 +431,21 @@ Native mobile save flows must call `AcquireExportFile` to obtain a lease contain## 22. Usage Guide### First-time enablement-1. Go to **Settings → Authentication → Encrypted Notebook** and toggle it on+1. Go to **Settings - Authentication - Encrypted Notebook** and toggle it on2. Set a master password (double input + risk confirmation). The master password is the unified key for all encrypted notebooks — **you must remember it; there is no recovery backdoor**-3. Once enabled, you can **create a new encrypted notebook** from the file-panel "more" menu (enter a name + master password → auto-unlocks and opens)+3. Once enabled, you can **create a new encrypted notebook** from the file-panel "more" menu; enter a name and master password to unlock and open it automatically> Strength recommendation: 12+ characters, mixed case + digits + symbols. The stronger the master password, the higher the brute-force resistance (password strength is the only line of defense; there is no backdoor).### Daily use: unlock and lock-- **Unlock**: Click a closed encrypted notebook → enter the master password → wait ~1 second (Argon2id derivation) → opens. Unlocking only affects that notebook; other encrypted notebooks stay locked+- **Unlock**: Click a closed encrypted notebook, enter the master password, and wait about one second for Argon2id derivation before it opens. Unlocking only affects that notebook; other encrypted notebooks stay locked- **Lock**: Closing the notebook equals locking. The kernel stops new access, waits for or cancels in-flight work, revokes managed DEK handles and database connections, and best-effort cleans kernel-managed plaintext caches, temporary files, and tokens. **Locking after use** is the most important security habit because it minimizes key and plaintext exposure- **After restart**: All encrypted notebooks are force-closed; you must re-enter the master password to unlock (managed DEK handles exist only in process memory and must be derived again after restart)> Important: An encrypted notebook provides its strongest application-level protection while locked, but locking only best-effort cleans application-controlled memory and temporary data; it does not promise erasure of every transient copy in the operating system or storage media. While unlocked, callers authorized by the main application (APIs, plugins, AI/LLM including MCP) can read plaintext just like a normal notebook; publish readers, anonymous visitors, and the kernel CLI are always denied (see §12 Security premise).### Changing the master password-Go to **Settings → Authentication → Encrypted Notebook → Change master password**. Changing the password only re-wraps each notebook's WrappedDEK — **document data is not re-encrypted**, so it completes instantly. The key backup is auto-refreshed and synced after a password change.+Go to **Settings - Authentication - Encrypted Notebook - Change master password**. Changing the password only re-wraps each notebook's WrappedDEK — **document data is not re-encrypted**, so it completes instantly. The key backup is auto-refreshed and synced after a password change.> Important semantics: password change uses the KEK envelope model — the DEK itself does not change; only a new KEK (derived from the new password) re-wraps the WrappedDEK. This means **changing the password does not revoke the old password's decryption ability**: if the old password and an old WrappedDEK (retained in sync endpoints, backups, or historical snapshots) leak together, the same DEK can still be unwrapped, decrypting current data. If you suspect the old password has leaked, migrate content to a freshly created encrypted notebook (new DEK) rather than just changing the password.@@ -451,6 +454,8 @@ Encrypted-notebook ciphertext `.sy`/assets/database files sync along with the daAn encrypted notebook's open state is never inherited across devices. Even if the synchronized `conf.json` records that another device had the notebook open, the UI and kernel must treat it as closed and skip indexing whenever the local process has no DEK for that notebook; entering the master password unlocks and mounts it locally.+When sync removes an encrypted notebook currently mounted on this device, the kernel completes the local deletion transition before any full-reindex branch, exit early-return, or UI reload: it closes admission, drains active leases, clears the DEK and mount state, deletes dedicated index databases, and completes global-index cleanup. The now-missing disk configuration is never used to decide whether cleanup is required.+1. Configure the same sync account on the new device and complete a sync2. Sync pulls the key backup to the local machine; the kernel auto-restores the "enabled" state3. Just click the encrypted notebook and enter the master password to unlock and use itdiff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex edf1368801..8c56b3baf7 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -242,14 +242,14 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i| 场景 | 交互 ||---|---|-| 启用 | 设置 → 鉴权 → 加密笔记本 → 开关 → 设置主密码(双输入 + 风险确认) |+| 启用 | 设置 - 鉴权 - 加密笔记本,打开开关并设置主密码(双输入 + 风险确认) || 禁用 | 仅在无现存加密笔记本且无依赖当前密钥备份的内核可枚举历史或恢复快照时支持关闭;否则拒绝,或要求用户明确永久清除这些恢复数据后再删除全局配置与备份 |-| 创建 | 文件面板"更多"菜单 → "新建加密笔记本" → 输名字 + 主密码 → 自动解锁并打开 |+| 创建 | 文件面板 - 「更多」菜单 - 「新建加密笔记本」,输入名字和主密码后自动解锁并打开 || 图标 | 关闭(锁定)时显示锁图标;打开(解锁)后恢复用户 emoji |-| 解锁 | 点已关闭的加密笔记本 → 弹主密码框(🔓 解锁 xxx)→ 等 ~1 秒 → 打开 |+| 解锁 | 点击已关闭的加密笔记本,在主密码框(🔓 解锁 xxx)中输入密码,等待约 1 秒后打开 || 锁定 | 等于关闭:先阻止新操作,等待或取消在途任务,再移除受管 DEK 句柄、删除加密 SQLite 数据库,并尽力清理内核管理的明文缓存、临时文件和访问令牌。关闭前会自动保存未写入的编辑和文件历史 || 自动锁定 | 每个已解锁笔记本独立保存最近活动时间;认证用户在当前工作区产生真实界面交互时,统一刷新所有当前已解锁加密笔记本的活动时间。无界面客户端也可通过需要认证与管理员权限的显式保活接口执行同样的刷新;后台读取、同步、索引等非用户活动不自动保活 |-| 改密 | 设置 → 鉴权 → 加密笔记本 → 「修改主密码」 |+| 改密 | 设置 - 鉴权 - 加密笔记本 - 「修改主密码」 || 移动文档 | 加密笔记本内部仅改变父目录时原样移动密文并更新索引;文件基名变化时重新封装;普通笔记本之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 || 文档转标题 | 跨加密边界被拒绝并提示 || 块引 | 加密笔记本内部正常引用(搜索 `((` 只搜本笔记本,反链面板正常显示);跨加密边界(普通↔加密、加密 A↔加密 B)被阻止 |@@ -350,6 +350,8 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i全局状态为 `Disabled`、`Enabled` 或 `RecoveryRequired`。正常稳态下,`Disabled` 不得存在现存加密笔记本或内核可枚举的密钥依赖;如果启动时在全局配置缺失或禁用的情况下发现加密笔记本或恢复数据,必须进入 `RecoveryRequired`,拒绝把它们当作普通笔记本,直到恢复匹配的密钥备份。`Enabled` 下每个加密笔记本独立处于 `Locked`、`Unlocking`、`Unlocked`、`Locking` 或 `Error`,应用启动后均从 `Locked` 开始。+加密身份判定必须 fail-closed。合法 boxID 的 `conf.json` 或笔记本密钥备份缺失、损坏时,只要磁盘上存在当前密文格式标识,或当前进程已经确认过该笔记本的加密身份,就必须把笔记本置为 `Error` 并拒绝普通笔记本读写,不能自动生成 `Encrypted=false` 的配置。只有笔记本删除流程在排空生命周期租约并清除本机 DEK、挂载标记、专属数据库和缓存后,才能移除运行时加密身份。+| 转换 | 前置条件 | 成功后的不变量 | 失败处理 ||---|---|---|---|| `Locked → Unlocking → Unlocked` | 主密码验证成功且密文配置匹配 | 可用 DEK 句柄仅存在于受管内存;专属数据库已打开;允许笔记本专用入口 | 撤销派生的 KEK/DEK 句柄、关闭已打开资源并回到 `Locked` |@@ -357,7 +359,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i| `Unlocked → Error` | 密文认证失败、数据库打开失败或不变量被破坏 | 立即拒绝读写,绝不回退到普通笔记本路径 | 关闭资源,诊断信息不得含明文;用户只能锁定或重新解锁 || 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK、全局配置和备份作为一个可恢复事务更新 | 保留旧配置和备份可用;不得出现仅能用新密码解锁的部分笔记本 |-每个笔记本使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、撤销受管 DEK 句柄,并尽力清理缓存和临时产物。密钥句柄和数据库连接清理完成后发布 `Locked`;临时文件删除失败不阻止锁定,但必须记录诊断并在退出或下次启动时重试。因此锁定完成后不得再出现新的明文响应、缓存回填或数据库重连,但磁盘上可能保留清理失败的临时明文副本。+每个笔记本使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。解锁并打开必须在同一个笔记本转换锁内完成;挂载失败只能回滚本次新建的解锁状态,不能锁定由其他并发请求已经使用的 DEK 或挂载。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、撤销受管 DEK 句柄,并尽力清理缓存和临时产物。密钥句柄和数据库连接清理完成后发布 `Locked`;临时文件删除失败不阻止锁定,但必须记录诊断并在退出或下次启动时重试。因此锁定完成后不得再出现新的明文响应、缓存回填或数据库重连,但磁盘上可能保留清理失败的临时明文副本。全局配置锁必须先于任何笔记本生命周期锁获取;同时涉及多个笔记本时按 boxID 字典序获取生命周期锁;DEK 缓存、数据库、文件和其他子系统锁只能在生命周期锁之后获取,并在释放生命周期锁前释放。禁止逆序获取,禁止持有子系统锁时回取全局配置锁或其他较低层级锁。自动锁定按每个笔记本保存活动时间,但当前工作区的一次认证用户交互或显式保活会统一刷新所有已解锁笔记本;计时采用系统时钟并由周期任务检查,系统时钟调整可能相应提前或推迟触发时间,自动锁定是便利性保护而不是精确的安全计时边界。@@ -420,6 +422,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明| 文件、资源、数据库、WAL/SHM、历史、快照和日志的磁盘检查 | 加密笔记本持久化范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页;`temp/` 可能在导出期间或清理失败后包含明文 || 异常退出后重启 | 启动时至少删除 `temp/export/` 下第一层名称为合法 boxID 的残留目录;通用临时目录初始化可以同时清理其他导出和插件临时文件 || 密文篡改、路径替换和备份损坏 | 认证或格式校验失败并安全拒绝;不回退普通路径、不生成新密钥材料、不静默覆盖配置 |+| 加密笔记本的 `conf.json` 与笔记本密钥备份同时缺失,或同步删除当前已打开的加密笔记本 | 密文或运行时身份使前者进入 `Error` 且不生成普通配置;后者先排空在途租约,再清除 DEK、挂载、专属数据库、缓存和索引,不受删除后 `Conf.GetBox` 为空影响 || nonce 随机源失败、达到用途密钥调用限制或事后发现 nonce 重用 | 随机源失败或达到限制时在加密前拒绝写入;AES-GCM 认证本身不能发现已发生的 nonce 重用,发现后必须按密钥泄露事件处理并轮换 DEK 后重新加密 || 回放认证有效的历史密文或密钥备份 | 可能被识别为有效旧版本,但不得被宣称为最新或来源可信;数据回退风险明确,当前设计不声称提供回滚防护 || 改主密码和 KEK 重新包络 | WrappedDEK 与备份原子更新;更新中断后旧配置仍可恢复使用;旧密码暴露风险提示正确;迁移前后数据与历史均可验证读取 |@@ -428,21 +431,21 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明## 22. 使用指南### 首次启用-1. 进入 **设置 → 鉴权 → 加密笔记本**,打开开关+1. 进入 **设置 - 鉴权 - 加密笔记本**,打开开关2. 设置主密码(双输入确认 + 风险确认)。主密码是所有加密笔记本的统一钥匙,**必须牢记——没有找回后门**-3. 启用后即可在文件面板"更多"菜单里 **新建加密笔记本**(输入名字 + 主密码 → 自动解锁并打开)+3. 启用后即可在文件面板「更多」菜单里 **新建加密笔记本**,输入名字和主密码后自动解锁并打开> 强度建议:12 位以上,混合大小写 + 数字 + 符号。主密码越强,抗暴力破解能力越高(密码强度是唯一的安全防线,没有后门)。### 日常使用:解锁与锁定-- **解锁**:点击已关闭的加密笔记本 → 输主密码 → 等约 1 秒(Argon2id 派生)→ 打开。解锁仅作用于该笔记本,其他加密笔记本保持锁定+- **解锁**:点击已关闭的加密笔记本,输入主密码并等待约 1 秒(Argon2id 派生)后打开。解锁仅作用于该笔记本,其他加密笔记本保持锁定- **锁定**:关闭该笔记本即等于锁定。内核停止新访问,等待或取消在途任务,撤销受管 DEK 句柄和数据库连接,并尽力清理内核管理的明文缓存、临时文件与令牌。**用完即锁**是最重要的安全习惯,能最大程度减少密钥和明文的暴露时间- **重启后**:所有加密笔记本强制关闭,需重新输主密码解锁(受管 DEK 句柄只存在于进程内存,重启后需重新派生)> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,获得主应用授权的调用方(API、插件、AI/LLM 含 MCP)能像读普通笔记本一样读到明文;发布服务的读者与匿名访问者以及内核 CLI 始终被拒绝(详见 §12 安全前提)。### 修改主密码-进入 **设置 → 鉴权 → 加密笔记本 → 修改主密码**。改密只需重新包络各笔记本的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。+进入 **设置 - 鉴权 - 加密笔记本 - 修改主密码**。改密只需重新包络各笔记本的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。> 重要语义:改密采用 KEK 包络模式——DEK 本身不变,只是用新主密码派生的新 KEK 重新包络 WrappedDEK。这意味着**改密不能吊销旧主密码的解密能力**:如果旧主密码和旧 WrappedDEK(如同步端、备份、历史快照中保留的)同时泄露,仍能解出同一个 DEK,进而解当前数据。如果怀疑旧主密码已泄露,应迁移内容到新建的加密笔记本(新 DEK)而非仅改密。@@ -451,6 +454,8 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明加密笔记本的打开状态不能跨设备继承。即使同步到本机的 `conf.json` 记录了其他设备上的打开状态,只要本机内存中没有该笔记本的 DEK,界面和内核都必须将其视为已关闭,并跳过索引;输入主密码后由本机完成解锁和挂载。+同步删除本机当前已挂载的加密笔记本时,内核必须在处理全量重建索引、退出早返回或界面刷新之前完成本机删除转换:关闭新操作准入、等待在途租约结束、清除 DEK 与挂载状态、删除专属索引数据库并完成全局索引清理。删除后的磁盘配置不再作为判断是否需要清理的依据。+1. 在新设备配置好相同的同步账号并完成同步2. 同步会把密钥备份拉到本地,内核自动恢复"已启用"状态3. 直接点击加密笔记本,输入主密码即可解锁使用diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 3878c90b03..35e3ad9e83 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -676,8 +676,7 @@ func unlockNotebook(c *gin.Context) {}}-// unlockAndOpenNotebook 原子化解锁并挂载加密笔记本:UnlockBox 成功后立即 Mount,-// Mount 失败则 LockBox 回滚(清除 DEK),避免 DEK 残留在内存但笔记本未挂载的不一致状态。+// unlockAndOpenNotebook 原子化解锁并挂载加密笔记本,挂载失败时由模型层在同一转换锁内回滚本次解锁。func unlockAndOpenNotebook(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)@@ -711,7 +710,10 @@ func unlockAndOpenNotebook(c *gin.Context) {return}- if err := model.UnlockBox(notebook, password, boxCrypt); err != nil {+ msgId := util.PushMsg(model.Conf.Language(45), 1000*60*15)+ defer util.PushClearMsg(msgId)+ existed, err := model.UnlockAndMountBox(notebook, password, boxCrypt)+ if err != nil {ret.Code = -1ret.Msg = err.Error()return@@ -722,18 +724,6 @@ func unlockAndOpenNotebook(c *gin.Context) {return}- // 解锁成功后立即挂载;失败则回滚锁定,清除 DEK 避免残留- msgId := util.PushMsg(model.Conf.Language(45), 1000*60*15)- defer util.PushClearMsg(msgId)- existed, err := model.Mount(notebook)- if err != nil {- releaseEncryptedBoxRequest(c, notebook)- model.LockBox(notebook)- ret.Code = -1- ret.Msg = err.Error()- return- }-box := model.Conf.Box(notebook)if nil == box {releaseEncryptedBoxRequest(c, notebook)diff --git a/kernel/model/box.go b/kernel/model/box.goindex df42db291f..c0f8e8040e 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -116,16 +116,20 @@ func ListNotebooks() (ret []*Box, err error) {boxDirPath := filepath.Join(util.DataDir, id)boxConfPath := filepath.Join(boxDirPath, ".siyuan", "conf.json")isExistConf := filelock.IsExist(boxConfPath)+ missingEncryptedIdentity := falseif !isExistConf {if !IsUserGuide(id) {// conf.json 缺失时检查加密备份,确认是否为加密笔记本backup, backupErr := readNotebookCryptBackup(id)if backupErr != nil {logging.LogErrorf("read notebook crypt backup [%s] failed: %s", boxDirPath, backupErr)- continue- }- if backup != nil {+ markRuntimeEncryptedBox(id)+ boxConf.Encrypted = true+ missingEncryptedIdentity = true+ setEncryptedBoxState(id, EncryptedBoxStateError)+ } else if backup != nil {// 从备份恢复 conf.json,避免加密笔记本被当作普通笔记本处理+ markRuntimeEncryptedBox(id)boxConf.Encrypted = trueboxConf.BoxCrypt = backuptmpBox := &Box{ID: id}@@ -134,6 +138,11 @@ func ListNotebooks() (ret []*Box, err error) {continue}logging.LogWarnf("restored encrypted notebook conf from backup [%s]", boxDirPath)+ } else if IsEncryptedBox(id) {+ boxConf.Encrypted = true+ missingEncryptedIdentity = true+ setEncryptedBoxState(id, EncryptedBoxStateError)+ logging.LogErrorf("encrypted notebook key identity is missing [%s]", boxDirPath)} else {// 数据同步时展开文档树操作可能导致数据丢失 https://github.com/siyuan-note/siyuan/issues/7129logging.LogWarnf("found a corrupted box [%s]", boxDirPath)@@ -151,20 +160,35 @@ func ListNotebooks() (ret []*Box, err error) {logging.LogErrorf("parse box conf [%s] failed: %s", boxConfPath, readErr)// 检查加密备份,有备份则保留损坏 conf 不删(避免标记为缺失后自动恢复旧数据)backup, backupErr := readNotebookCryptBackup(id)- if backupErr == nil && backup != nil {+ if backupErr != nil || backup != nil {+ markRuntimeEncryptedBox(id)continue}filelock.Remove(boxConfPath)continue}}+ if !boxConf.Encrypted && IsEncryptedBox(id) {+ backup, backupErr := readNotebookCryptBackup(id)+ boxConf.Encrypted = true+ if backupErr == nil && backup != nil {+ boxConf.BoxCrypt = backup+ } else {+ missingEncryptedIdentity = true+ setEncryptedBoxState(id, EncryptedBoxStateError)+ }+ logging.LogWarnf("normal notebook configuration conflicts with encrypted identity [%s]", boxDirPath)+ }if boxConf.Encrypted {+ markRuntimeEncryptedBox(id)+ }+ if boxConf.Encrypted && !missingEncryptedIdentity {if metadataErr := revealBoxMetadataIfUnlocked(id, boxConf); metadataErr != nil {logging.LogErrorf("decrypt encrypted notebook metadata [%s] failed: %s", id, metadataErr)}}- unlocked := boxConf.Encrypted && IsBoxUnlocked(id)+ unlocked := boxConf.Encrypted && !missingEncryptedIdentity && isBoxUnlockedForAccess(id)closed := boxConf.Closedif boxConf.Encrypted {// 加密笔记本的打开状态不能从其他设备继承,仅本机已挂载且持有 DEK 时才视为打开。@@ -181,10 +205,14 @@ func ListNotebooks() (ret []*Box, err error) {Unlocked: unlocked,}if box.Encrypted {- box.State = GetEncryptedBoxState(id)+ if missingEncryptedIdentity {+ box.State = EncryptedBoxStateError+ } else {+ box.State = GetEncryptedBoxState(id)+ }}- if !isExistConf {+ if !isExistConf && !missingEncryptedIdentity {// Automatically create notebook conf.json if not found it https://github.com/siyuan-note/siyuan/issues/9647if err := box.SaveConf(boxConf); err != nil {logging.LogErrorf("save box conf [%s] failed: %s", boxDirPath, err)diff --git a/kernel/model/box_conf_crypto.go b/kernel/model/box_conf_crypto.goindex 547a5ae870..88134f016c 100644--- a/kernel/model/box_conf_crypto.go+++ b/kernel/model/box_conf_crypto.go@@ -92,6 +92,9 @@ func prepareBoxConfForSave(boxID string, boxConf *conf.BoxConf) (*conf.BoxConf,persisted := *boxConfpersisted.BoxCrypt = DeepCopyBoxEncryption(boxConf.BoxCrypt)if !persisted.Encrypted {+ if IsEncryptedBox(boxID) {+ return nil, errors.New("encrypted notebook cannot be saved as a normal notebook")+ }return &persisted, nil}if persisted.BoxCrypt == nil {diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex 6c84ef96c6..002dbb73d8 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -26,9 +26,11 @@ import ("errors""fmt""io"+ "io/fs""net/url""os""path/filepath"+ "sort""strings""sync""sync/atomic"@@ -53,11 +55,76 @@ const boxEncryptionSpec = 1var encryptedAssetMagic = []byte{'S', 'Y', 'A', 'E'}+var errEncryptedNotebookPayloadFound = errors.New("encrypted notebook payload found")++// runtimeEncryptedBoxes 记录当前工作空间进程内已确认的加密笔记本身份,避免同步或外部删除配置后降级为普通笔记本。+// value 为确认身份时的 DataDir,防止测试或切换工作空间时复用其他工作空间的运行时状态。+var runtimeEncryptedBoxes sync.Map // map[string]string+// IsEncryptedNotebookData 判断数据是否以当前文档或资源密文标识开头。func IsEncryptedNotebookData(data []byte) bool {return util.IsCiphertext(data) || bytes.HasPrefix(data, encryptedAssetMagic)}+func markRuntimeEncryptedBox(boxID string) {+ if ast.IsNodeIDPattern(boxID) {+ runtimeEncryptedBoxes.Store(boxID, filepath.Clean(util.DataDir))+ }+}++func forgetRuntimeEncryptedBox(boxID string) {+ dataDir, ok := runtimeEncryptedBoxes.Load(boxID)+ if ok && dataDir == filepath.Clean(util.DataDir) {+ runtimeEncryptedBoxes.Delete(boxID)+ }+}++func isRuntimeEncryptedBox(boxID string) bool {+ dataDir, ok := runtimeEncryptedBoxes.Load(boxID)+ return ok && dataDir == filepath.Clean(util.DataDir)+}++// hasEncryptedNotebookPayload 在密钥身份文件缺失或损坏时检查磁盘密文标识,防止自动修复为普通笔记本。+func hasEncryptedNotebookPayload(boxID string) (bool, error) {+ if !ast.IsNodeIDPattern(boxID) {+ return false, errors.New("invalid notebook ID")+ }+ boxDir := filepath.Join(util.DataDir, boxID)+ if !filelock.IsExist(boxDir) {+ return false, nil+ }+ err := filepath.WalkDir(boxDir, func(path string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if entry.IsDir() || entry.Type()&os.ModeType != 0 {+ return nil+ }++ file, openErr := os.Open(path)+ if openErr != nil {+ return openErr+ }+ var header [4]byte+ n, readErr := io.ReadFull(file, header[:])+ closeErr := file.Close()+ if readErr != nil && readErr != io.EOF && readErr != io.ErrUnexpectedEOF {+ return readErr+ }+ if closeErr != nil {+ return closeErr+ }+ if IsEncryptedNotebookData(header[:n]) {+ return errEncryptedNotebookPayloadFound+ }+ return nil+ })+ if errors.Is(err, errEncryptedNotebookPayloadFound) {+ return true, nil+ }+ return false, err+}+const encryptedAssetMetadataMaxSize = 1024 * 1024const encryptedAssetChunkSize = 1024 * 1024const encryptedAssetChunkMaxCiphertextSize = encryptedAssetChunkSize + 1024@@ -1077,6 +1144,9 @@ func decryptBoxCrypt(boxID string, kek []byte) (dek []byte, boxCrypt *conf.BoxEn// 每次调用都跑一次 Argon2id(约 1 秒),严格满足"每笔记本单独解锁"语义。func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) (err error) {invalidateEncryptedPublishAccessCache()+ if !ast.IsNodeIDPattern(boxID) {+ return errors.New("invalid notebook ID")+ }// 全局配置锁先于笔记本生命周期锁获取(设计 §17 锁顺序约定),避免与持子系统锁后回取配置锁的路径死锁。// notebookCryptoMu 持锁期间调用的 deriveKEK/conf 修复只申请 Conf.m/cachedDEKsLock,不回取 box 生命周期锁。@@ -1084,6 +1154,33 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) (err edefer notebookCryptoMu.Unlock()releaseTransition := holdEncryptedBoxTransition(boxID)defer releaseTransition()+ return unlockBoxHeld(boxID, password, boxEnc)+}++// UnlockAndMountBox 在同一个笔记本转换锁内完成解锁和挂载,挂载失败时回滚本次新建的解锁状态。+func UnlockAndMountBox(boxID, password string, boxEnc *conf.BoxEncryption) (alreadyMount bool, err error) {+ invalidateEncryptedPublishAccessCache()+ if !ast.IsNodeIDPattern(boxID) {+ return false, errors.New("invalid notebook ID")+ }++ notebookCryptoMu.Lock()+ defer notebookCryptoMu.Unlock()+ releaseTransition := holdEncryptedBoxTransition(boxID)+ defer releaseTransition()++ wasUnlocked := IsBoxUnlocked(boxID)+ if err = unlockBoxHeld(boxID, password, boxEnc); err != nil {+ return false, err+ }+ alreadyMount, err = mountBox(boxID)+ if err != nil && !wasUnlocked {+ lockBoxWithPreparationHeld(boxID, nil)+ }+ return alreadyMount, err+}++func unlockBoxHeld(boxID string, password string, boxEnc *conf.BoxEncryption) (err error) {if _, busy := boxLock.Load(boxID); busy {return errors.New(Conf.language(239))}@@ -1127,6 +1224,7 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) (err e}}()boxEnc = trustedCrypt+ markRuntimeEncryptedBox(boxID)metadataConf := &conf.BoxConf{Encrypted: true, BoxCrypt: boxEnc}if err = decryptBoxMetadata(boxID, metadataConf, dek); err != nil {finalState = EncryptedBoxStateError@@ -1180,14 +1278,29 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) (err e// IsBoxUnlocked 返回该笔记本的 DEK 是否在内存(是否已解锁)。func IsBoxUnlocked(boxID string) bool {+ if !ast.IsNodeIDPattern(boxID) {+ return false+ }cachedDEKsLock.RLock()defer cachedDEKsLock.RUnlock()_, ok := cachedDEKs[boxID]return ok}+func isBoxUnlockedForAccess(boxID string) bool {+ if !IsBoxUnlocked(boxID) {+ return false+ }+ state := GetEncryptedBoxState(boxID)+ return state == EncryptedBoxStateUnlocked || state == EncryptedBoxStateLocking+}+// LockBox 清除指定笔记本的 DEK 并删除其加密 db 文件。Unmount 单个加密笔记本或手动锁定时调用。func LockBox(boxID string) {+ if !ast.IsNodeIDPattern(boxID) {+ logging.LogWarnf("refuse to lock encrypted notebook with invalid ID [%s]", boxID)+ return+ }lockBoxWithPreparation(boxID, nil)}@@ -1195,8 +1308,13 @@ func LockBox(boxID string) {func lockBoxWithPreparation(boxID string, prepare func()) {releaseTransition := holdEncryptedBoxTransition(boxID)defer releaseTransition()+ lockBoxWithPreparationHeld(boxID, prepare)+}++func lockBoxWithPreparationHeld(boxID string, prepare func()) {beginEncryptedBoxLock(boxID)FlushTxQueue()+ sql.FlushQueue()if prepare != nil {prepare()}@@ -1342,6 +1460,12 @@ func mustEncryptionNonce(ciphertext []byte) []byte {// GetDEK 取已缓存的 DEK。返回副本,避免外部零化影响缓存。// filesys/assets/db 加解密时调用。func GetDEK(boxID string) ([]byte, error) {+ if !ast.IsNodeIDPattern(boxID) {+ return nil, errors.New("invalid notebook ID")+ }+ if IsEncryptedBox(boxID) && !isBoxUnlockedForAccess(boxID) {+ return nil, errors.New("encrypted notebook is not accessible")+ }cachedDEKsLock.RLock()defer cachedDEKsLock.RUnlock()dek, ok := cachedDEKs[boxID]@@ -1513,36 +1637,73 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {}// IsEncryptedBox 判断给定 boxID 是否为加密笔记本。-// 优先读 conf.json,若缺失/损坏则 fallback 到独立备份,避免 fail-open。+// 配置缺失或损坏时依次检查运行时身份、独立备份和密文标识,任何检查错误都按加密笔记本处理。func IsEncryptedBox(boxID string) bool {- if boxID == "" {+ if !ast.IsNodeIDPattern(boxID) {return false}- box := &Box{ID: boxID}- boxConf := box.GetConf()- if boxConf != nil && boxConf.Encrypted {+ if isRuntimeEncryptedBox(boxID) {return true}- // 主 conf 缺失/损坏时检查独立备份,确认是否为加密笔记本++ normalConf := false+ boxConfPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ if filelock.IsExist(boxConfPath) {+ data, readErr := filelock.ReadFile(boxConfPath)+ if readErr == nil {+ boxConf := conf.NewBoxConf()+ if unmarshalErr := gulu.JSON.UnmarshalJSON(data, boxConf); unmarshalErr == nil {+ if boxConf.Encrypted {+ markRuntimeEncryptedBox(boxID)+ return true+ }+ normalConf = true+ }+ }+ }+backupPath := notebookCryptoBackupPath(boxID)- if !filelock.IsExist(backupPath) {- return false // 无备份文件 → 非加密+ if filelock.IsExist(backupPath) {+ backup, err := readNotebookCryptBackup(boxID)+ if err != nil {+ logging.LogWarnf("failed to read notebook crypt backup for [%s]: %s", boxID, err)+ markRuntimeEncryptedBox(boxID)+ return true+ }+ if backup != nil && len(backup.WrappedDEK) > 0 {+ markRuntimeEncryptedBox(boxID)+ return true+ }}- backup, err := readNotebookCryptBackup(boxID)+ if normalConf {+ return false+ }++ found, err := hasEncryptedNotebookPayload(boxID)if err != nil {- logging.LogWarnf("failed to read notebook crypt backup for [%s]: %s", boxID, err)- return true // 备份存在但不可读 → fail-closed+ logging.LogWarnf("failed to inspect notebook encryption identity for [%s]: %s", boxID, err)+ markRuntimeEncryptedBox(boxID)+ return true+ }+ if found {+ markRuntimeEncryptedBox(boxID)}- return backup != nil && len(backup.WrappedDEK) > 0+ return found}// GetBoxEncryption 获取加密笔记本的 BoxEncryption(含 WrappedDEK)。// 优先读 conf.json,若缺失/损坏则 fallback 到 per-notebook backup。// 返回 nil 表示该 box 非加密;conf 标记加密但密钥材料缺失时返回明确错误。func GetBoxEncryption(boxID string) (*conf.BoxEncryption, error) {+ if !ast.IsNodeIDPattern(boxID) {+ return nil, errors.New("invalid notebook ID")+ }box := &Box{ID: boxID}boxConf := box.GetConf()confMarkedEncrypted := boxConf != nil && boxConf.Encrypted+ if confMarkedEncrypted {+ markRuntimeEncryptedBox(boxID)+ }// conf 中有完整的 BoxCryptif confMarkedEncrypted && boxConf.BoxCrypt != nil && len(boxConf.BoxCrypt.WrappedDEK) > 0 {@@ -1555,11 +1716,12 @@ func GetBoxEncryption(boxID string) (*conf.BoxEncryption, error) {return nil, err}if backup != nil && len(backup.WrappedDEK) > 0 {+ markRuntimeEncryptedBox(boxID)return backup, nil}// backup 也不可用- if confMarkedEncrypted {+ if confMarkedEncrypted || IsEncryptedBox(boxID) {// conf 标记为加密但密钥材料缺失 → 明确错误(而非误报"未加密")return nil, errors.New("encrypted notebook has no valid key material")}@@ -1595,10 +1757,9 @@ func DeepCopyBoxEncryption(src *conf.BoxEncryption) *conf.BoxEncryption {}}-// listAllEncryptedBoxIDs 直接扫描笔记本配置及密钥备份,不触发配置修复等副作用。-// conf 损坏或缺失时以 notebook-crypto-backup.json 为准,供候选密钥验证、改密和禁用等关键路径使用。+// listAllEncryptedBoxIDs 直接扫描笔记本配置、密钥备份、密文标识及当前进程身份,不触发配置修复等副作用。func listAllEncryptedBoxIDs() ([]string, error) {- var ids []string+ ids := map[string]struct{}{}dirs, err := os.ReadDir(util.DataDir)if err != nil {return nil, err@@ -1608,12 +1769,17 @@ func listAllEncryptedBoxIDs() ([]string, error) {continue}boxID := dir.Name()- encrypted := false+ encrypted := isRuntimeEncryptedBox(boxID)+ normalConf := falseboxConfPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")- if data, readErr := filelock.ReadFile(boxConfPath); readErr == nil {- boxConf := conf.NewBoxConf()- if unmarshalErr := gulu.JSON.UnmarshalJSON(data, boxConf); unmarshalErr == nil {- encrypted = boxConf.Encrypted+ if !encrypted {+ data, readErr := filelock.ReadFile(boxConfPath)+ if readErr == nil {+ boxConf := conf.NewBoxConf()+ if unmarshalErr := gulu.JSON.UnmarshalJSON(data, boxConf); unmarshalErr == nil {+ encrypted = boxConf.Encrypted+ normalConf = !boxConf.Encrypted+ }}}if !encrypted {@@ -1623,11 +1789,32 @@ func listAllEncryptedBoxIDs() ([]string, error) {}encrypted = backup != nil && len(backup.WrappedDEK) > 0}+ if !encrypted && !normalConf {+ found, inspectErr := hasEncryptedNotebookPayload(boxID)+ if inspectErr != nil {+ return nil, inspectErr+ }+ encrypted = found+ }if encrypted {- ids = append(ids, dir.Name())+ markRuntimeEncryptedBox(boxID)+ ids[boxID] = struct{}{}+ }+ }+ runtimeEncryptedBoxes.Range(func(key, value any) bool {+ boxID, idOK := key.(string)+ dataDir, dirOK := value.(string)+ if idOK && dirOK && ast.IsNodeIDPattern(boxID) && dataDir == filepath.Clean(util.DataDir) {+ ids[boxID] = struct{}{}}+ return true+ })+ ret := make([]string, 0, len(ids))+ for boxID := range ids {+ ret = append(ret, boxID)}- return ids, nil+ sort.Strings(ret)+ return ret, nil}// ListAllEncryptedBoxIDs 返回所有可枚举的加密笔记本。扫描失败时记录错误并返回空列表;@@ -1700,9 +1887,15 @@ func IsEncryptedAssetPath(absPath string) bool {// 加密但未解锁(DEK 不在内存)返回 (nil, error)——filesys 的加解密函数遇 error 后拒绝读写,// 避免加密笔记本在未解锁状态下静默以明文落盘(深度防御,见 issue #18034)。func GetDEKIfUnlocked(boxID string) ([]byte, error) {+ if boxID != "" && !ast.IsNodeIDPattern(boxID) {+ return nil, errors.New("invalid notebook ID")+ }if !IsEncryptedBox(boxID) {return nil, nil}+ if !isBoxUnlockedForAccess(boxID) {+ return nil, errors.New("encrypted notebook is locked, please unlock it first")+ }cachedDEKsLock.RLock()defer cachedDEKsLock.RUnlock()dek, ok := cachedDEKs[boxID]@@ -2039,13 +2232,18 @@ func DecryptAsset(boxID, diskName string, dek, ciphertext []byte) ([]byte, error// 该文件在主 conf.json 丢失时用作"此笔记本是加密笔记本"的标识和降级恢复源。// 与全局 NotebookCrypto 备份(<DataDir>/.siyuan/data-crypto-backup.json)配合使用,// 全局备份存 MasterSalt/KEKVerifier,per-notebook 备份存 WrappedDEK/WrapNonce。+const notebookCryptoBackupFilename = "notebook-crypto-backup.json"+func notebookCryptoBackupPath(boxID string) string {- return filepath.Join(util.DataDir, boxID, ".siyuan", "notebook-crypto-backup.json")+ return filepath.Join(util.DataDir, boxID, ".siyuan", notebookCryptoBackupFilename)}// writeNotebookCryptBackup 写入加密笔记本的 BoxCrypt 备份。// 仅在 Encrypted=true 的笔记本上调用,配合 CreateEncryptedBox / ChangeMasterPassword 写入。func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {+ if !ast.IsNodeIDPattern(boxID) {+ return errors.New("invalid notebook ID")+ }if err := validateBoxEncryption(crypt); err != nil {return err}@@ -2066,8 +2264,8 @@ func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {// readNotebookCryptBackup 读取加密笔记本的 BoxCrypt 备份。// 备份文件不存在时返回 (nil, nil),调用方据此区分"非加密笔记本"和"备份不存在"。func readNotebookCryptBackup(boxID string) (*conf.BoxEncryption, error) {- if boxID == "" {- return nil, nil+ if !ast.IsNodeIDPattern(boxID) {+ return nil, errors.New("invalid notebook ID")}backupPath := notebookCryptoBackupPath(boxID)if !filelock.IsExist(backupPath) {@@ -2180,6 +2378,7 @@ func CreateEncryptedBox(name, password string) (id string, err error) {err = errors.New("encrypted notebook metadata verification failed after write")return "", err}+ markRuntimeEncryptedBox(id)invalidateEncryptedPublishAccessCache()// 复用刚派生的 DEK 直接开 db + 缓存,省去再次 Argon2id 解锁@@ -2230,14 +2429,27 @@ func cleanupFailedEncryptedBox(boxID string) {delete(cachedDEKs, boxID)}cachedDEKsLock.Unlock()+ mountedEncryptedBoxes.Delete(boxID)sql.RemoveEncryptedDBFile(boxID)treenode.RemoveEncryptedBlockTreeDBFile(boxID)removeEncryptedBoxLifecycle(boxID)+ forgetRuntimeEncryptedBox(boxID)if err := filelock.Remove(boxDir); err != nil {logging.LogErrorf("cleanup failed encrypted box [%s]: %s", boxID, err)}}+// finalizeSyncedEncryptedBoxRemoval 在同步删除身份文件后等待在途操作结束,再清除本机密钥、挂载和索引生命周期。+func finalizeSyncedEncryptedBoxRemoval(boxID string) {+ if !ast.IsNodeIDPattern(boxID) {+ return+ }+ LockBox(boxID)+ removeEncryptedBoxLifecycle(boxID)+ forgetRuntimeEncryptedBox(boxID)+ invalidateEncryptedPublishAccessCache()+}+// zeroAndClear 把密钥字节清零后再置空,尽量减少密钥在内存中的残留时间。func zeroAndClear(key []byte) {for i := range key {diff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.goindex 843d457375..4825e1a22b 100644--- a/kernel/model/crypto_lifecycle_test.go+++ b/kernel/model/crypto_lifecycle_test.go@@ -158,6 +158,142 @@ func TestEncryptedBoxOperationReleaseSurvivesNotebookRemoval(t *testing.T) {}}+func TestMissingEncryptedIdentityNeverFallsBackToNormalNotebook(t *testing.T) {+ oldDataDir := util.DataDir+ oldConf := Conf+ util.DataDir = t.TempDir()+ Conf = NewAppConf()+ Conf.FileTree = conf.NewFileTree()+ boxID := "20260731160100-abcdefg"+ defer func() {+ forgetRuntimeEncryptedBox(boxID)+ removeEncryptedBoxLifecycle(boxID)+ Conf = oldConf+ util.DataDir = oldDataDir+ }()++ boxDir := filepath.Join(util.DataDir, boxID)+ if err := os.MkdirAll(boxDir, 0755); err != nil {+ t.Fatal(err)+ }+ key, err := util.GenerateDEK()+ if err != nil {+ t.Fatal(err)+ }+ defer zeroAndClear(key)+ ciphertext, err := util.EncryptWithAAD(key, []byte(`{"ID":"20260731160101-abcdefg"}`), []byte("identity-test"))+ if err != nil {+ t.Fatal(err)+ }+ rootPath := filepath.Join(boxDir, "20260731160101-abcdefg.sy")+ if err = os.WriteFile(rootPath, ciphertext, 0644); err != nil {+ t.Fatal(err)+ }++ boxes, err := ListNotebooks()+ if err != nil {+ t.Fatal(err)+ }+ if len(boxes) != 1 || !boxes[0].Encrypted || boxes[0].Unlocked || boxes[0].State != EncryptedBoxStateError {+ t.Fatalf("expected a quarantined encrypted notebook, got %+v", boxes)+ }+ confPath := filepath.Join(boxDir, ".siyuan", "conf.json")+ if _, statErr := os.Stat(confPath); !os.IsNotExist(statErr) {+ t.Fatalf("missing encrypted identity must not create a normal configuration: %v", statErr)+ }+ if _, keyErr := GetBoxEncryption(boxID); keyErr == nil {+ t.Fatal("ciphertext without key identity should report missing encrypted key material")+ }+ if saveErr := (&Box{ID: boxID}).SaveConf(conf.NewBoxConf()); saveErr == nil {+ t.Fatal("quarantined encrypted notebook must not be saved as a normal notebook")+ }+}++func TestNotebookBackupPreventsNormalIdentityDowngrade(t *testing.T) {+ oldConf := Conf+ Conf = NewAppConf()+ Conf.FileTree = conf.NewFileTree()+ defer func() {+ Conf = oldConf+ }()++ boxID := "20260731160104-abcdefg"+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)+ defer cleanup()+ normalConf := conf.NewBoxConf()+ data, err := gulu.JSON.MarshalIndentJSON(normalConf, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ if err = os.WriteFile(confPath, data, 0644); err != nil {+ t.Fatal(err)+ }+ forgetRuntimeEncryptedBox(boxID)++ if !IsEncryptedBox(boxID) {+ t.Fatal("a notebook key backup must prevent an encrypted notebook from being downgraded by a normal configuration")+ }+ boxes, err := ListNotebooks()+ if err != nil {+ t.Fatal(err)+ }+ if len(boxes) != 1 || !boxes[0].Encrypted {+ t.Fatalf("expected backup identity to quarantine the notebook, got %+v", boxes)+ }+}++func TestSyncedEncryptedNotebookRemovalClearsRuntimeState(t *testing.T) {+ boxID := "20260731160102-abcdefg"+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)+ defer cleanup()++ if !IsEncryptedBox(boxID) {+ t.Fatal("encrypted notebook identity was not detected")+ }+ mountedEncryptedBoxes.Store(boxID, true)+ if err := os.RemoveAll(filepath.Join(util.DataDir, boxID)); err != nil {+ t.Fatal(err)+ }+ if !IsEncryptedBox(boxID) {+ t.Fatal("runtime identity should survive synchronized identity-file removal until cleanup")+ }++ finalizeSyncedEncryptedBoxRemoval(boxID)+ if IsBoxUnlocked(boxID) {+ t.Fatal("synchronized notebook removal retained its DEK")+ }+ if isEncryptedBoxMounted(boxID) {+ t.Fatal("synchronized notebook removal retained its mount marker")+ }+ if isRuntimeEncryptedBox(boxID) || IsEncryptedBox(boxID) {+ t.Fatal("completed synchronized notebook removal retained its encryption identity")+ }+ if _, exists := encryptedBoxLifecycles.Load(boxID); exists {+ t.Fatal("completed synchronized notebook removal retained its lifecycle")+ }+}++func TestUnlockAndMountFailureKeepsPreexistingUnlock(t *testing.T) {+ boxID := "20260731160103-abcdefg"+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)+ defer cleanup()++ boxCrypt, err := GetBoxEncryption(boxID)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.RemoveAll(filepath.Join(util.DataDir, boxID)); err != nil {+ t.Fatal(err)+ }+ if _, err = UnlockAndMountBox(boxID, "unused", boxCrypt); err == nil {+ t.Fatal("mounting a removed notebook should fail")+ }+ if !IsBoxUnlocked(boxID) {+ t.Fatal("a mount failure must not roll back a preexisting unlock")+ }+}+func TestEncryptedBoxMetadataIsNotStoredInPlaintext(t *testing.T) {boxID := "20260731160001-abcdefg"cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)@@ -510,6 +646,7 @@ func prepareEncryptedBoxLifecycleTest(t *testing.T, boxID string) func() {cachedDEKsLock.Unlock()zeroAndClear(dek)removeEncryptedBoxLifecycle(boxID)+ forgetRuntimeEncryptedBox(boxID)util.DataDir = oldDataDir}}diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.goindex c1a42f999a..21934c5d62 100644--- a/kernel/model/crypto_test.go+++ b/kernel/model/crypto_test.go@@ -38,7 +38,7 @@ func setDEKForTest(boxID string, dek []byte) {cachedDEKs[boxID] = dek}-func TestIsEncryptedBoxRejectsEmptyID(t *testing.T) {+func TestEncryptedBoxIdentityRejectsInvalidIDs(t *testing.T) {oldDataDir := util.DataDirutil.DataDir = t.TempDir()defer func() {@@ -52,8 +52,16 @@ func TestIsEncryptedBoxRejectsEmptyID(t *testing.T) {if err := os.WriteFile(filepath.Join(backupDir, "notebook-crypto-backup.json"), []byte("{}"), 0644); err != nil {t.Fatal(err)}- if IsEncryptedBox("") {- t.Fatal("empty notebook ID must not resolve to the data-level backup path")+ for _, boxID := range []string{"", ".", "..", "not-a-node-id"} {+ if IsEncryptedBox(boxID) {+ t.Fatalf("invalid notebook ID %q must not resolve to a backup path", boxID)+ }+ if _, err := readNotebookCryptBackup(boxID); err == nil {+ t.Fatalf("invalid notebook ID %q should be rejected by backup reads", boxID)+ }+ if _, err := GetBoxEncryption(boxID); err == nil {+ t.Fatalf("invalid notebook ID %q should be rejected by key lookup", boxID)+ }}}@@ -137,8 +145,8 @@ func TestEncryptedAssetRejectsUnknownFormat(t *testing.T) {// TestIsBoxUnlockedLifecycle 验证 DEK 缓存的存在/缺失状态。func TestIsBoxUnlockedLifecycle(t *testing.T) {- LockBox("lifecycle-test-box") // 确保初始干净- boxID := "lifecycle-test-box"+ boxID := "20260731121000-lifecyc"+ LockBox(boxID) // 确保初始干净if IsBoxUnlocked(boxID) {t.Fatalf("box should not be unlocked after LockBox")}@@ -156,7 +164,7 @@ func TestIsBoxUnlockedLifecycle(t *testing.T) {// TestGetDEKReturnsErrorAfterLock 验证 LockBox 后 GetDEK 报错。func TestGetDEKReturnsErrorAfterLock(t *testing.T) {dek, _ := util.GenerateDEK()- boxID := "get-dek-test-box"+ boxID := "20260731121001-getdekk"setDEKForTest(boxID, dek)got, err := GetDEK(boxID)@@ -176,9 +184,10 @@ func TestGetDEKReturnsErrorAfterLock(t *testing.T) {// TestWrapNewDEKRoundTrip 验证用 KEK 生成 DEK → 包络 → 解包 → 还原。func TestWrapNewDEKRoundTrip(t *testing.T) {kek, _ := util.GenerateDEK()- defer LockBox("wrap-roundtrip-box")+ boxID := "20260731121002-wrapbox"+ defer LockBox(boxID)- boxEnc, _, err := WrapNewDEK("wrap-roundtrip-box", kek)+ boxEnc, _, err := WrapNewDEK(boxID, kek)if err != nil {t.Fatalf("WrapNewDEK failed: %v", err)}@@ -186,7 +195,7 @@ func TestWrapNewDEKRoundTrip(t *testing.T) {t.Fatalf("BoxEncryption fields malformed: wrappedDEK=%d wrapNonce=%d", len(boxEnc.WrappedDEK), len(boxEnc.WrapNonce))}- dek, err := decryptWrappedDEK("wrap-roundtrip-box", boxEnc, kek)+ dek, err := decryptWrappedDEK(boxID, boxEnc, kek)if err != nil {t.Fatalf("decryptWrappedDEK failed: %v", err)}@@ -197,13 +206,14 @@ func TestWrapNewDEKRoundTrip(t *testing.T) {// TestDecryptWrappedDEKWithWrongKEK 验证用错误的 KEK 解密 WrappedDEK 失败(GCM MAC 校验)。func TestDecryptWrappedDEKWithWrongKEK(t *testing.T) {+ boxID := "20260731121003-wrongkk"kek1, _ := util.GenerateDEK()- boxEnc, _, _ := WrapNewDEK("wrong-kek-box", kek1)+ boxEnc, _, _ := WrapNewDEK(boxID, kek1)kek2, _ := util.GenerateDEK()- defer LockBox("wrong-kek-box")+ defer LockBox(boxID)- if _, err := decryptWrappedDEK("wrong-kek-box", boxEnc, kek2); err == nil {+ if _, err := decryptWrappedDEK(boxID, boxEnc, kek2); err == nil {t.Fatalf("decryptWrappedDEK with wrong KEK should fail")}}@@ -211,11 +221,13 @@ func TestDecryptWrappedDEKWithWrongKEK(t *testing.T) {// TestWrapNewDEKProducesUniqueDEKs 验证两次调用 WrapNewDEK 生成不同的 DEK(随机性)。func TestWrapNewDEKProducesUniqueDEKs(t *testing.T) {kek, _ := util.GenerateDEK()- defer LockBox("uniq-box-1")- defer LockBox("uniq-box-2")+ boxID1 := "20260731121004-uniquea"+ boxID2 := "20260731121005-uniqueb"+ defer LockBox(boxID1)+ defer LockBox(boxID2)- _, dek1, _ := WrapNewDEK("uniq-box-1", kek)- _, dek2, _ := WrapNewDEK("uniq-box-2", kek)+ _, dek1, _ := WrapNewDEK(boxID1, kek)+ _, dek2, _ := WrapNewDEK(boxID2, kek)// WrapNewDEK 同时返回原始 DEK,可直接比对随机性if bytes.Equal(dek1, dek2) {@@ -277,15 +289,16 @@ func TestBoxEncryptionNonceMismatchRejected(t *testing.T) {// 直接测试 clearDEKIfUnlockedEncryptedBox(unmount0 在 box==nil 分支调用的清理逻辑),// 避免依赖未初始化的全局 Conf。func TestUnmount0ClearsDEKForUnmountedEncryptedBox(t *testing.T) {- boxID := "unmount-unlocked-test-box"+ boxID := "20260731120000-unmount"// 临时替换 DataDir,创建加密 box 的 conf.json,让 IsEncryptedBox 返回 trueorigDataDir := util.DataDirtempDir := t.TempDir()util.DataDir = tempDirdefer func() {+ LockBox(boxID) // 测试后清理 DEK 缓存+ forgetRuntimeEncryptedBox(boxID)util.DataDir = origDataDir- LockBox("unmount-unlocked-test-box") // 测试后清理 DEK 缓存}()// 写入加密 box 的 conf.json@@ -810,8 +823,8 @@ func TestBackupMACRoundTrip(t *testing.T) {// TestLockBoxConcurrentReads 验证 LockBox(单 box)能与在途读锁正确串行化。func TestLockBoxConcurrentReads(t *testing.T) {- LockBox("concurrent-single-box") // 清理初始状态- boxID := "concurrent-single-box"+ boxID := "20260731121006-concurr"+ LockBox(boxID) // 清理初始状态dek, _ := util.GenerateDEK()setDEKForTest(boxID, dek)@@ -844,7 +857,7 @@ func TestLockBoxConcurrentReads(t *testing.T) {// TestLockBoxClearsTempDirs 验证 LockBox 删除 per-box 临时目录。func TestLockBoxClearsTempDirs(t *testing.T) {- boxID := "temp-cleanup-box"+ boxID := "20260731121007-tempcln"dek, _ := util.GenerateDEK()setDEKForTest(boxID, dek)@@ -852,8 +865,8 @@ func TestLockBoxClearsTempDirs(t *testing.T) {tempDir := t.TempDir()util.TempDir = tempDirdefer func() {+ LockBox(boxID)util.TempDir = origTempDir- LockBox("temp-cleanup-box")}()// 创建模拟临时目录和文件diff --git a/kernel/model/filesys_init.go b/kernel/model/filesys_init.goindex 27a5de53e6..28e64c7a20 100644--- a/kernel/model/filesys_init.go+++ b/kernel/model/filesys_init.go@@ -36,7 +36,7 @@ func init() {av.AVLockRelease = ReleaseBoxReadLockav.AVEncryptedBoxIDs = treenode.GetOpenedEncryptedBoxIDsav.AVIsEncryptedBox = IsEncryptedBox- av.AVIsBoxUnlocked = IsBoxUnlocked+ av.AVIsBoxUnlocked = isBoxUnlockedForAccessav.AVGetBlockBoxID = func(blockID string) string {bt := treenode.GetBlockTree(blockID)if nil == bt {@@ -45,13 +45,13 @@ func init() {return bt.BoxID}sql.IsEncryptedBoxFn = IsEncryptedBox- sql.IsBoxUnlockedFn = IsBoxUnlocked+ sql.IsBoxUnlockedFn = isBoxUnlockedForAccesstreenode.IsEncryptedBoxFn = IsEncryptedBoxutil.ReloadDocInfoGuard = func(boxID string) bool {// 加密笔记本锁定后丢弃延迟 reloadDocInfo 广播,防止明文元数据泄漏if !IsEncryptedBox(boxID) {return true}- return IsBoxUnlocked(boxID)+ return isBoxUnlockedForAccess(boxID)}}diff --git a/kernel/model/index.go b/kernel/model/index.goindex 70c9d39bec..c462231257 100644--- a/kernel/model/index.go+++ b/kernel/model/index.go@@ -18,6 +18,7 @@ package modelimport ("bytes"+ "context""fmt""io/fs""path/filepath"@@ -131,10 +132,28 @@ func (box *Box) Index() {}func removeBoxRefs(boxID string) {+ if IsEncryptedBox(boxID) {+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ return+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ }sql.DeleteBoxRefsQueue(boxID)}func indexBox(boxID string) {+ encrypted := IsEncryptedBox(boxID)+ if encrypted {+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ logging.LogWarnf("skip indexing encrypted notebook [%s]: %s", boxID, err)+ return+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ if !isEncryptedBoxMounted(boxID) {+ return+ }+ }+databaseIndexDataLock.Lock()defer databaseIndexDataLock.Unlock()@@ -228,6 +247,18 @@ func indexBox(boxID string) {}func IndexRefs() {+ boxes := Conf.GetOpenedBoxes()+ boxIDs := make([]string, 0, len(boxes))+ for _, box := range boxes {+ boxIDs = append(boxIDs, box.ID)+ }+ release, err := AcquireEncryptedBoxOperations(context.Background(), boxIDs)+ if err != nil {+ logging.LogWarnf("skip resolving references while an encrypted notebook is unavailable: %s", err)+ return+ }+ defer release()+databaseIndexDataLock.Lock()defer databaseIndexDataLock.Unlock()@@ -239,7 +270,6 @@ func IndexRefs() {var defBlockIDs []stringdefBlockBoxes := map[string]string{} // defBlockID -> boxID,加密笔记本下需按 box 路由后续加载luteEngine := util.NewLute()- boxes := Conf.GetOpenedBoxes()for _, box := range boxes {encryptedBox := IsEncryptedBox(box.ID)pages := pagedPaths(filepath.Join(util.DataDir, box.ID), 32)diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex daf8e83661..e3cd00bb4f 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -162,12 +162,13 @@ func removeBoxDir(p string) (err error) {}func RemoveBox(boxID string) (err error) {- if _, ok := boxLock.Load(boxID); ok {+ if !ast.IsNodeIDPattern(boxID) {+ return errors.New("invalid notebook ID")+ }+ if _, loaded := boxLock.LoadOrStore(boxID, true); loaded {err = errors.New(Conf.language(239))return}-- boxLock.Store(boxID, true)defer boxLock.Delete(boxID)if util.IsReservedFilename(boxID) {@@ -176,11 +177,6 @@ func RemoveBox(boxID string) (err error) {FlushTxQueue()isUserGuide := IsUserGuide(boxID)- databaseIndexDataLock.Lock()- defer databaseIndexDataLock.Unlock()- createDocLock.Lock()- defer createDocLock.Unlock()-localPath := filepath.Join(util.DataDir, boxID)if !filelock.IsExist(localPath) {return@@ -189,9 +185,20 @@ func RemoveBox(boxID string) (err error) {return fmt.Errorf("can not remove [%s] caused by it is not a dir", boxID)}- // 删目录前缓存加密状态:删目录后 conf.json 不复存在,IsEncryptedBox 会返回 false+ // 删目录前固定加密状态,确保后续历史、资源和索引清理始终使用同一个安全边界。isEncrypted := IsEncryptedBox(boxID)- unmount0(boxID)+ if isEncrypted {+ // 加密索引先持有生命周期租约再获取索引锁,因此删除也必须先结束生命周期,保持锁顺序一致。+ unmount0(boxID)+ }++ databaseIndexDataLock.Lock()+ defer databaseIndexDataLock.Unlock()+ createDocLock.Lock()+ defer createDocLock.Unlock()+ if !isEncrypted {+ unmount0(boxID)+ }ClearRichClipboardBox(boxID)if !isEncrypted {unindex(boxID)@@ -236,6 +243,7 @@ func RemoveBox(boxID string) (err error) {sql.RemoveEncryptedDBFile(boxID)treenode.RemoveEncryptedBlockTreeDBFile(boxID)removeEncryptedBoxLifecycle(boxID)+ forgetRuntimeEncryptedBox(boxID)}if isUserGuide {@@ -258,6 +266,10 @@ func RemoveBox(boxID string) (err error) {}func Unmount(boxID string) {+ if !ast.IsNodeIDPattern(boxID) {+ logging.LogWarnf("refuse to unmount notebook with invalid ID [%s]", boxID)+ return+ }FlushTxQueue()unmount0(boxID)@@ -306,7 +318,6 @@ func unmount0(boxID string) {if err := box.SaveConf(boxConf); err != nil {logging.LogErrorf("save box conf [%s] failed: %s", box.ID, err)}- sql.FlushQueue()GenerateFileHistoryForBox(box)})return@@ -321,12 +332,21 @@ func unmount0(boxID string) {}func Mount(boxID string) (alreadyMount bool, err error) {- if _, ok := boxLock.Load(boxID); ok {+ if !ast.IsNodeIDPattern(boxID) {+ return false, errors.New("invalid notebook ID")+ }+ if IsEncryptedBox(boxID) {+ releaseTransition := holdEncryptedBoxTransition(boxID)+ defer releaseTransition()+ }+ return mountBox(boxID)+}++func mountBox(boxID string) (alreadyMount bool, err error) {+ if _, loaded := boxLock.LoadOrStore(boxID, true); loaded {err = errors.New(Conf.language(239))return}-- boxLock.Store(boxID, true)defer boxLock.Delete(boxID)FlushTxQueue()@@ -414,6 +434,7 @@ func Mount(boxID string) (alreadyMount bool, err error) {logging.LogErrorf("save box conf [%s] failed: %s", boxID, err)}if boxConf.Encrypted {+ markRuntimeEncryptedBox(boxID)mountedEncryptedBoxes.Store(boxID, true)}if _, ensureErr := EnsureBoxDoc(boxID); nil != ensureErr {diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.goindex 8ce9edacd9..8c407a53d7 100644--- a/kernel/model/publish_access_test.go+++ b/kernel/model/publish_access_test.go@@ -311,6 +311,7 @@ func TestEncryptedPublishAccessCacheInvalidation(t *testing.T) {util.DataDir = t.TempDir()invalidateEncryptedPublishAccessCache()t.Cleanup(func() {+ forgetRuntimeEncryptedBox(boxID)util.DataDir = oldDataDirinvalidateEncryptedPublishAccessCache()})@@ -333,6 +334,7 @@ func TestEncryptedPublishAccessCacheInvalidation(t *testing.T) {if err = os.WriteFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), data, 0644); err != nil {t.Fatal(err)}+ forgetRuntimeEncryptedBox(boxID)if !IsEncryptedBoxDeniedByPublishAccess(boxID) {t.Fatal("publish access should reuse its cached encrypted notebook snapshot")}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 9c078ddb91..9ae6a215f4 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -2262,6 +2262,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,reloadPluginSet := hashset.New() // 插件代码变更 data/plugins/dataChangePluginSet := hashset.New() // 插件存储数据变更 data/storage/petal/needUnindexBoxes, needIndexBoxes := map[string]bool{}, map[string]bool{}+ removedBoxConfs, removedBoxCryptoBackups := map[string]bool{}, map[string]bool{}needRestoreNotebookCrypto := false // 加密笔记本备份文件随同步到达,需恢复本机启用状态for _, file := range mergeResult.Upserts {upserts = append(upserts, file.Path)@@ -2276,14 +2277,18 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,if strings.HasSuffix(file.Path, "/.siyuan/conf.json") {needReloadFiletree = trueboxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/conf.json")- needUnindexBoxes[boxID] = true- needIndexBoxes[boxID] = true+ if ast.IsNodeIDPattern(boxID) {+ needUnindexBoxes[boxID] = true+ needIndexBoxes[boxID] = true+ }}if strings.HasSuffix(file.Path, "/.siyuan/boxDoc.json") {needReloadFiletree = trueboxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/boxDoc.json")- needUnindexBoxes[boxID] = true- needIndexBoxes[boxID] = true+ if ast.IsNodeIDPattern(boxID) {+ needUnindexBoxes[boxID] = true+ needIndexBoxes[boxID] = true+ }}if file.Path == "/.siyuan/data-crypto-backup.json" {@@ -2344,13 +2349,24 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,if strings.HasSuffix(file.Path, "/.siyuan/conf.json") {needReloadFiletree = trueboxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/conf.json")- needUnindexBoxes[boxID] = true+ if ast.IsNodeIDPattern(boxID) {+ needUnindexBoxes[boxID] = true+ removedBoxConfs[boxID] = true+ }+ }+ if strings.HasSuffix(file.Path, "/.siyuan/"+notebookCryptoBackupFilename) {+ boxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/"+notebookCryptoBackupFilename)+ if ast.IsNodeIDPattern(boxID) {+ removedBoxCryptoBackups[boxID] = true+ }}if strings.HasSuffix(file.Path, "/.siyuan/boxDoc.json") {needReloadFiletree = trueboxID := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/"), "/.siyuan/boxDoc.json")- needUnindexBoxes[boxID] = true- needIndexBoxes[boxID] = true+ if ast.IsNodeIDPattern(boxID) {+ needUnindexBoxes[boxID] = true+ needIndexBoxes[boxID] = true+ }}if strings.HasPrefix(file.Path, "/storage/petal/") {@@ -2423,6 +2439,19 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,syncingFiles = sync.Map{}syncingStorages.Store(false)+ removedEncryptedBox := false+ for boxID := range removedBoxConfs {+ if IsEncryptedBox(boxID) || removedBoxCryptoBackups[boxID] {+ finalizeSyncedEncryptedBoxRemoval(boxID)+ unindex(boxID)+ removedEncryptedBox = true+ needUnindexBoxes[boxID] = true+ delete(needIndexBoxes, boxID)+ }+ }+ if removedEncryptedBox {+ sql.FlushQueue()+ }if needFullReindex(upsertTrees) { // 改进同步后全量重建索引判断 https://github.com/siyuan-note/siyuan/issues/5764FullReindex(false)@@ -2434,9 +2463,7 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,}for boxID := range needUnindexBoxes {- if box := Conf.GetBox(boxID); nil != box {- box.Unindex()- }+ (&Box{ID: boxID}).Unindex()}for boxID := range needIndexBoxes {if box := Conf.GetBox(boxID); nil != box {diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex 23945e0453..1e15215979 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -355,43 +355,53 @@ func upsertIndexes(upsertFilePaths []string) (upsertRootIDs []string) {luteEngine := util.NewLute()bootProgressPart := int32(10 / float64(len(upsertFilePaths)))for _, upsertFile := range upsertFilePaths {- if !strings.HasSuffix(upsertFile, ".sy") {- continue- }+ rootID, indexed := func() (string, bool) {+ if !strings.HasSuffix(upsertFile, ".sy") {+ return "", false+ }- upsertFile = filepath.ToSlash(upsertFile)- upsertFile = strings.TrimPrefix(upsertFile, "/")+ upsertFile = filepath.ToSlash(upsertFile)+ upsertFile = strings.TrimPrefix(upsertFile, "/")- box, _, found := strings.Cut(upsertFile, "/")- if !found {- // .sy 直接出现在 data 文件夹下,没有出现在笔记本文件夹下的情况- continue- }- if IsEncryptedBox(box) && (!IsBoxUnlocked(box) || !isEncryptedBoxMounted(box)) {- continue- }+ box, _, found := strings.Cut(upsertFile, "/")+ if !found {+ // .sy 直接出现在 data 文件夹下,没有出现在笔记本文件夹下的情况+ return "", false+ }+ if IsEncryptedBox(box) {+ if !isBoxUnlockedForAccess(box) || !isEncryptedBoxMounted(box) {+ return "", false+ }+ if acquireErr := AcquireEncryptedBoxOperation(box); acquireErr != nil {+ return "", false+ }+ defer ReleaseEncryptedBoxOperation(box)+ }- p := strings.TrimPrefix(upsertFile, box)- msg := fmt.Sprintf(Conf.Language(40), util.GetTreeID(p))- util.IncBootProgress(bootProgressPart, msg)- util.PushStatusBar(msg)+ p := strings.TrimPrefix(upsertFile, box)+ msg := fmt.Sprintf(Conf.Language(40), util.GetTreeID(p))+ util.IncBootProgress(bootProgressPart, msg)+ util.PushStatusBar(msg)- rootID := util.GetTreeID(p)- cache.RemoveTreeData(rootID)- tree, err0 := filesys.LoadTree(box, p, luteEngine)- if nil != err0 {- continue- }- treenode.UpsertBlockTree(tree)- sql.UpsertTreeQueue(tree)+ rootID := util.GetTreeID(p)+ cache.RemoveTreeData(rootID)+ tree, err0 := filesys.LoadTree(box, p, luteEngine)+ if nil != err0 {+ return "", false+ }+ treenode.UpsertBlockTree(tree)+ sql.UpsertTreeQueue(tree)- bts := treenode.GetBlockTreesByRootIDInBox(rootID, tree.Box)- for _, b := range bts {- cache.RemoveBlockIAL(b.ID)+ bts := treenode.GetBlockTreesByRootIDInBox(rootID, tree.Box)+ for _, b := range bts {+ cache.RemoveBlockIAL(b.ID)+ }+ cache.RemoveDocIAL(tree.Path)+ return rootID, true+ }()+ if indexed {+ upsertRootIDs = append(upsertRootIDs, rootID)}- cache.RemoveDocIAL(tree.Path)-- upsertRootIDs = append(upsertRootIDs, rootID)}if 1 > len(upsertRootIDs) {