Skip to content

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

:memo: Add threat model, state machine, and security acceptance matrix to encrypted notebook design doc #18034

Daniel0c44ec8e5ac0
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index ab78da443d..38b3f0b47b 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -311,6 +311,72 @@ An encrypted notebook is an island; some features are unimplemented because of t
- **Noticeable latency**: Unlock ~1s, large-asset browsing (full decrypt per request with no cache), first access after lock (cold start).
- **Zero impact on normal notebooks**: Encryption and routing logic short-circuits for non-encrypted boxes.
+## 17. Threat Model and Security Scope
+
+This feature protects data-at-rest confidentiality and the inaccessibility of a locked notebook. The design assumes an attacker may obtain current or historical ciphertext from the workspace, sync service, or backup media, but does not know the master password and cannot control the running application or operating system while the user has unlocked a notebook. AES-GCM provides confidentiality and integrity verification for an individual encrypted object; it does not by itself provide availability, rollback protection, or deletion of retained ciphertext copies.
+
+The following are outside this feature's security boundary and must be stated in product UI and user documentation:
+
+- While a notebook is unlocked, authenticated application callers such as APIs, plugins, MCP, and AI/LLM, as well as a local attacker able to read the application process memory, may obtain plaintext.
+- Files intentionally exported by the user, clipboard contents, screenshots, printouts, content shared with third parties, and plaintext files saved outside the workspace are protected by the user.
+- OS swap, hibernation images, crash dumps, filesystem snapshots, and malware are not absolutely protected by clearing application memory; locking performs best-effort cleanup only within the application's control.
+- A sync service or backup holder may retain, delete, replace, or roll back ciphertext. Replacement and rollback can cause denial of service or data rollback; they cannot decrypt valid ciphertext without the master password.
+
+"Only ciphertext remains after locking" applies only to kernel-managed workspace files, temporary files, and caches. It does not include files deliberately exported to an external location or promise erasure of historical blocks retained by the underlying storage medium.
+
+## 18. State Machine and Concurrency Rules
+
+Each encrypted notebook independently has one of these states: `Locked`, `Unlocking`, `Unlocked`, `Locking`, and `Error`. Every encrypted notebook must start as `Locked`; encrypted notebooks must not exist while the global encryption feature is disabled.
+
+| Transition | Preconditions | Invariants after success | Failure handling |
+|---|---|---|---|
+| `Locked → Unlocking → Unlocked` | Master password verification succeeds | DEK exists only in memory; dedicated databases are open; notebook-specific entry points are allowed | Clear derived KEK/DEK, close opened handles, return to `Locked` |
+| `Unlocked → Locking → Locked` | Stop accepting new requests for the notebook | Tasks have completed or been cancelled; caches, plaintext temporary files, database connections, and DEK are cleared | Continue to deny access if cleanup partly fails; record the error and retry before the next startup |
+| `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 and the backup update as one transaction | Keep old configuration and backup usable; no notebook becomes unlockable only by the new password |
+
+Unlock, lock, export, sync, indexing, history restore, and deletion of the same notebook must be serialized by one boxID-scoped mutex. Once locking starts, running tasks must be cancelled or finish at a safe boundary; they must not create plaintext temporary files, publish plaintext results, or reopen database connections after locking completes.
+
+## 19. Ciphertext, Key, and Database Format
+
+Every persistent encrypted object must use a versioned envelope containing at least a format version, algorithm identifier, cryptographically random nonce unique for the same DEK, ciphertext, and authentication tag. Additional authenticated data binds boxID, object type, and logical relative path, preventing valid ciphertext from being substituted into another notebook, type, or path. Rename or migration creates a new envelope rather than merely moving ciphertext.
+
+The implementation derives purpose-separated subkeys from each box's DEK through a KDF with fixed domain separators, at least for file content, asset-name mappings, database files, and the WrappedDEK authentication context. KDF parameters, envelope version, and database configuration are stored with ciphertext to enable migration; a new version is written only after old data verifies successfully, and a failed migration must not delete the old copy.
+
+The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and backup copies are protected objects. They must remain in controlled directories and use the same key domain. 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.
+
+## 20. Backup, Recovery, and Metadata Policy
+
+`notebook-crypto-backup.json` is recovery material, not a secret, but its integrity and freshness must be handled separately. It contains a format version, backup ID, creation time, monotonic generation, and content digest. Recovery must not silently overwrite enabled configuration; when disabled and several candidates exist, display their origin and generation for the user to choose. A malformed backup, generation rollback, or backup incompatible with existing encrypted notebooks enters an error state instead of generating a new MasterSalt.
+
+Sync endpoints and offline backups are storage that may be lost, copied, or rolled back but cannot read plaintext. Before the master password is entered, trustworthy authentication based on the KEK cannot be established; the system can validate structure and the verifier after unlock only. A successful sync restore must not be presented as proof that the source is trusted. Users should keep at least one independent, versioned key backup and understand that losing the master password or every matching MasterSalt backup is unrecoverable.
+
+| Category | May be exposed |
+|---|---|
+| Document body, attribute values, original asset names, database cells, index text | No |
+| boxID, directory structure, file count, ciphertext size, modification time, asset extension, block-ID time information | Yes |
+| Notebook name, icon, sorting, document title/count, relation count, tags, bookmarks, history and snapshot names | Must not be exposed while locked by default; if compatibility requires exposure, list each field here and explain it in the UI |
+
+## 21. Feature Boundaries, Plaintext Temporaries, and Interface Rules
+
+Unsupported flashcards, bookmarks, tags, asset rename, unused-asset cleanup, and unused-database cleanup must be handled uniformly by the frontend, HTTP API, plugin API, MCP, and import paths: return an explicit "unsupported" error for encrypted-notebook targets and create no global index, global attribute, or deferred task. Existing legacy data must not be loaded, aggregated, or written back. Error codes and localized messages remain stable for callers.
+
+Every raw entry point that might bypass dedicated read/write paths must be registered and reject encrypted-notebook directories, including file APIs, kernel CLI, MCP file tools, WebDAV, plugin file interfaces, export download URLs, preview URLs, and background tasks. Adding an entry point requires review of whether it can read, write, copy, rename, delete, or enumerate an encrypted directory.
+
+Exports have two classes: a user-selected external destination may contain plaintext after a risk prompt; kernel-managed previews, conversions, downloads, and intermediates may exist only in a boxID-scoped controlled temporary directory and be served with minimum privilege. Locking, cancellation, failure, application exit, and export completion must clean up kernel-managed plaintext; after locking, prior download URLs, preview URLs, and asynchronous results become invalid. Logs, error reports, thumbnails, OCR/conversion output, and clipboard handling follow the same rule: do not contain plaintext by default unless the user explicitly sends content to an external program.
+
+## 22. Security Acceptance Matrix
+
+| Scenario | Expected result |
+|---|---|
+| Access while locked through UI, HTTP, file APIs, CLI, MCP, WebDAV, plugins, and background tasks | Cannot read, write, copy, delete, or enumerate encrypted content; returns no plaintext, ciphertext, or title-inferable error |
+| Unlock, lock, application restart, and authentication failure | DEK and database connections exist only in `Unlocked`; no plaintext cache or usable handle remains after failure or restart |
+| Lock concurrent with export, preview, sync, indexing, or history restore | No plaintext task continues after lock; controlled temporary files and access tokens are removed or invalidated |
+| Refs, moves, mirrors, assets, and database operations between an encrypted box and a normal box or another encrypted box | Island boundaries hold; rejection creates no partial files, global indexes, or relation data |
+| Disk inspection of files, assets, databases, WAL/SHM, history, snapshots, logs, and temporary directories | No readable body, asset contents, original asset names, or plaintext SQLite pages in kernel-managed locations |
+| Ciphertext tampering, path substitution, nonce reuse, backup corruption/rollback, and multi-device conflicts | Authentication or format validation fails safely; never fall back to a normal path, generate replacement key material, or silently overwrite configuration |
+| Master-password change and migration to a new DEK | WrappedDEKs and backup update atomically; old-password exposure warning is accurate; data and history are verifiably readable before and after migration |
+
## 16. Usage Guide
### First-time enablement
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 01a5707e19..da8261a6e1 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -311,6 +311,72 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
- **感知明显的延迟**:解锁 ~1 秒、大 assets 浏览(每次解密无缓存)、锁定后首次访问(冷启动)。
- **对普通笔记本零影响**:加解密与路由逻辑对非加密 box 短路跳过。
+## 17. 威胁模型与安全范围
+
+本特性保护静态数据机密性和笔记本锁定后的不可访问性。设计假设攻击者可以取得工作空间、同步端或备份介质中的当前或历史密文,但不知道主密码,也不能在用户解锁期间控制运行中的应用或操作系统。AES-GCM 只提供单个加密对象的机密性和完整性校验,不解决可用性、回滚或已保留密文副本的删除。
+
+下列场景不在本特性的保护范围内,界面和用户指南必须明确提示:
+
+- 笔记本解锁期间,已获应用授权的 API、插件、MCP、AI/LLM,以及能读取应用进程内存的本机攻击者,均可能取得明文。
+- 用户主动导出的文件、剪贴板、截图、打印件、分享给第三方的内容,以及保存在工作区外的明文文件,由用户负责保护。
+- 操作系统交换分区、休眠映像、崩溃转储、文件系统快照和恶意软件不因“清除内存”而获得绝对保护;锁定仅做应用可控范围内的尽力清除。
+- 同步服务或备份持有者可以保留、删除、替换或回滚密文;这些行为可能造成拒绝服务或数据回退,但不能在不知道主密码时解密有效密文。
+
+“锁定后仅剩密文”只指内核管理的工作空间、临时目录和缓存中不应残留可读明文;不包括用户明确导出到外部位置的文件,也不承诺抹除底层存储介质已经保留的历史块。
+
+## 18. 状态机与并发规则
+
+每个加密笔记本独立处于 `Locked`、`Unlocking`、`Unlocked`、`Locking` 或 `Error` 状态。应用启动后所有加密笔记本必须为 `Locked`;全局加密功能未启用时不得存在加密笔记本。
+
+| 转换 | 前置条件 | 成功后的不变量 | 失败处理 |
+|---|---|---|---|
+| `Locked → Unlocking → Unlocked` | 主密码验证成功 | DEK 仅在内存;专属数据库已打开;允许笔记本专用入口 | 清除派生的 KEK/DEK、关闭句柄并回到 `Locked` |
+| `Unlocked → Locking → Locked` | 停止接受该笔记本的新请求 | 任务完成或取消;缓存、临时明文、数据库连接和 DEK 已清理 | 即使部分清理失败仍拒绝访问,记录错误并在下次启动前重试 |
+| `Unlocked → Error` | 密文认证失败、数据库打开失败或不变量被破坏 | 立即拒绝读写,绝不回退到普通笔记本路径 | 关闭资源,诊断信息不得含明文;用户只能锁定或重新解锁 |
+| 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK 和备份作为一个事务更新 | 保留旧配置和备份;不得出现仅能用新密码解锁的部分笔记本 |
+
+同一笔记本的解锁、锁定、导出、同步、索引、历史恢复和删除必须由同一把按 boxID 分组的互斥锁串行化。锁定开始后,运行中的任务必须取消或在安全边界完成;锁定完成后不得继续创建明文临时文件、推送明文结果或重新建立数据库连接。
+
+## 19. 密文、密钥与数据库格式
+
+所有持久化加密对象都必须使用带版本号的封装格式,至少包含格式版本、算法标识、密码学安全随机生成且对同一 DEK 唯一的 nonce、密文和认证标签。附加认证数据必须绑定 boxID、对象类型及逻辑相对路径,防止把有效密文替换到其他笔记本、类型或路径。改名和迁移必须创建新的封装,不能只移动密文。
+
+实现必须由每个 box 的 DEK 通过有固定域分隔符的 KDF 派生用途隔离的子密钥,至少区分文件内容、资源名称映射、数据库文件和 WrappedDEK 的认证上下文。KDF 参数、封装版本和数据库配置需随密文保存以支持迁移;只有在旧数据验证成功后才能写入新版本,迁移失败不得删除旧副本。
+
+SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副本都是受保护对象,必须放在受控目录并使用相同密钥域。锁定、崩溃恢复和历史快照必须枚举这些伴随文件;未加密 SQLite 页面、查询结果或诊断转储不得写入全局临时目录。
+
+## 20. 备份、恢复与元数据策略
+
+`notebook-crypto-backup.json` 是恢复材料而非秘密,但必须处理完整性和新鲜度。文件必须带格式版本、备份 ID、创建时间、单调递增世代和内容摘要。恢复不得静默覆盖已启用配置;本地未启用且存在多个候选备份时,必须展示来源与世代供用户选择。格式无效、世代回退或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。
+
+同步端和离线备份被视为可丢失、可复制、可回滚但不能读取明文的存储。输入主密码前不能建立基于 KEK 的可信认证,因此“同步恢复成功”不得表述为来源可信;系统只能验证结构和用户解锁后的 verifier。用户应保留至少一份独立、版本化的密钥备份,并理解丢失主密码或全部匹配的 MasterSalt 备份均不可恢复。
+
+| 类别 | 是否可泄露 |
+|---|---|
+| 文档正文、属性值、资源原始名称、数据库单元格、索引文本 | 否 |
+| boxID、目录结构、文件数量、密文大小、修改时间、资源扩展名、块 ID 时间信息 | 是 |
+| 笔记本名称、图标、排序、文档标题和数量、关系数量、标签、书签、历史与快照名称 | 锁定时默认不得暴露;若兼容性要求暴露,必须逐项在本表及界面中说明 |
+
+## 21. 功能边界、临时明文与接口规则
+
+不支持的闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。错误码和本地化文案应稳定,供调用方识别。
+
+所有可能绕过专用读写路径的原始入口必须登记并拒绝加密笔记本目录,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。新增入口时必须评审其是否可读取、写入、复制、重命名、删除或列举加密目录。
+
+导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物只能位于带 boxID 的受控临时目录,并按最小权限提供访问。锁定、取消、失败、应用退出和导出完成后都必须清理内核管理的明文;锁定后旧下载链接、预览链接和异步结果必须失效。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。
+
+## 22. 安全验收矩阵
+
+| 场景 | 预期结果 |
+|---|---|
+| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问 | 不能读取、写入、复制、删除或列举加密内容;错误不返回明文、密文或可推断标题的信息 |
+| 解锁、锁定、应用重启和认证失败 | DEK 与数据库连接只在 `Unlocked` 存在;失败和重启后没有明文缓存或可用句柄 |
+| 锁定与导出、预览、同步、索引、历史恢复并发 | 无明文任务在锁定后继续执行;受控临时文件及访问令牌被清理或失效 |
+| 加密盒与普通盒、两个加密盒之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 |
+| 文件、资源、数据库、WAL/SHM、历史、快照、日志和临时目录的磁盘检查 | 内核管理范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页 |
+| 密文篡改、路径替换、nonce 重复、备份损坏/回滚、多端冲突 | 认证或格式校验失败并安全拒绝;不回退普通路径、不生成新密钥材料、不静默覆盖配置 |
+| 改主密码和迁移到新 DEK | WrappedDEK 与备份原子更新;旧密码泄露风险提示正确;迁移前后数据与历史均可验证读取 |
+
## 16. 使用指南
### 首次启用