An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:memo: Add encrypted notebook design docs https://github.com/siyuan-note/siyuan/issues/18034
Daniel11d3a39e2776
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdnew file mode 100644index 0000000000..5a16965bae--- /dev/null+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -0,0 +1,301 @@+# SiYuan Encrypted Notebook++## 1. Design Goals++Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` documents, assets (including filenames), attribute-view definitions, and SQLite index databases (content + blocktree) are all stored encrypted on disk, requiring a master password to unlock and view the content. Existing normal notebooks are completely unaffected.++## 2. Core Constraints++| Aspect | Design Decision |+|---|---|+| Encryption scope | `.sy` + assets (incl. filenames) + AV definitions + db (content + blocktree) all encrypted |+| Notebook identity | Dynamic boxID + `BoxConf.Encrypted: true` flag |+| Quantity | Multiple encrypted notebooks supported |+| Password | Shared master password (KEK envelope, per-notebook independent DEK) |+| Unlock granularity | Strictly per-notebook unlock (KEK used and discarded, ~1s Argon2id per unlock) |+| DB scheme | Each encrypted notebook has its own physical SQLCipher db, isolated from the global siyuan.db |+| **Isolation principle** | **Each encrypted notebook is an independent island — isolated from normal notebooks, and encrypted notebooks are also isolated from each other. Data, block refs, AV mirroring, and moves never cross the encrypted-notebook boundary. Unlocking one encrypted notebook does not affect the locked state of other encrypted notebooks.** |+| Global features | Encrypted notebooks never participate (global search / graph / block refs cannot see them) |+| Block refs | Normal refs within the box; cross-boundary refs forbidden (bidirectional: normal↔encrypted, encrypted A↔encrypted B) |+| AI / LLM | Fully isolated — agents, AI chat, embedding vectorization, semantic search, MCP never enter encrypted notebooks |+| Cross-boundary move | Forbidden — would break data consistency and leak |+| AV / Attribute View | Notebook-level storage — encrypted box AV definitions follow the box directory, DEK-encrypted; cross-boundary mirroring forbidden |+| Flashcards / spaced repetition | Not supported (feature limitation) |+| Bookmarks | Not supported (feature limitation) |+| Tags | Not supported (feature limitation) |+| Import | Supported — imported .sy.zip and Markdown are DEK-encrypted before writing to disk, identical to manually created documents |+| Enable / Disable | Enabling requires setting a master password; disabling requires confirming no encrypted notebooks exist |+| Restart behavior | All encrypted notebooks force-closed on startup (DEK is memory-only, lost after restart); user must re-unlock |+| Existing notebooks | Completely untouched, zero migration |++## 3. Encrypted Notebook vs Normal Notebook++| Aspect | Normal Notebook | Encrypted Notebook |+|---|---|---|+| **Create** | Anytime, no restrictions | Must first enable encryption (set master password); creating requires verifying master password |+| **Open (Mount)** | Direct open | Must first enter master password to unlock (~1s Argon2id each time); DEK enters memory |+| **Close (Unmount)** | Closing makes it invisible | Close = lock (DEK cleared + encrypted db closed + all plaintext caches cleared) |+| **After restart** | Keeps last open state | Force-closed; must re-enter master password to unlock |+| **.sy files** | Plaintext JSON on disk | AES-256-GCM ciphertext on disk, transparently decrypted on read |+| **assets files** | Plaintext binary, original filename | AES-256-GCM ciphertext, filename desensitized, original name encrypted |+| **AV definitions** | Global `storage/av/<avID>.json` (plaintext) | Notebook-level `<boxID>/storage/av/<avID>.json` (DEK-encrypted) |+| **content db** | Written to global siyuan.db (plaintext) | Written to independent siyuan-encrypted-`<boxID>`.db (SQLCipher) |+| **blocktree db** | Written to global blocktree.db (plaintext) | Written to independent siyuan-encrypted-`<boxID>`-blocktree.db (SQLCipher) |+| **Global search** | Participates (FTS hits) | Does not participate (data not in global db) |+| **Graph** | Participates | Does not participate |+| **Block refs** | Referrable by any notebook | Normal refs within box; cross-boundary refs forbidden (bidirectional) |+| **Move doc (cross-notebook)** | Supported | Forbidden across encrypted boundary |+| **Doc to heading (Doc2Heading)** | Supported | Forbidden across encrypted boundary |+| **AV mirroring (cross-notebook)** | Supported | Forbidden across encrypted boundary |+| **Asset file rename** | Supported | Not supported (desensitized filename rename breaks the mapping) |+| **Import** | Supported | Supported (.sy.zip and Markdown, auto DEK-encrypted before writing to disk) |+| **In-notebook search** | Via global db | Via encrypted db |+| **Backlinks panel** | Via global db | Via encrypted db (incl. mention subquery) |+| **Open doc / outline / breadcrumb / block info / float preview** | Via global db | Via encrypted db |+| **Attribute View (database)** | Via global storage + global db | Via notebook-level storage (DEK-encrypted) + encrypted db |+| **File history** | Supported | Supported (ciphertext .sy copied verbatim to history dir; decrypt by path boxID when viewing/rolling back) |+| **Deleted notebook history** | Supported | Supported (entire directory backed up as ciphertext before deletion; restored verbatim) |+| **Embedding vectorization / semantic search** | Participates | Does not participate (AI does not enter encrypted notebooks) |+| **Agents / AI chat / MCP** | Can read content, can search | Fully isolated: AI cannot read content, cannot even perceive the encrypted box's existence |+| **Flashcards / spaced repetition** | Participates | Not supported (feature limitation) |+| **Bookmarks** | Participates (global aggregation) | Not supported (feature limitation) |+| **Tags** | Participates (global aggregation) | Not supported (feature limitation) |+| **List icon** | User-custom emoji | Shows lock icon when closed; restores emoji when opened |+| **Export (.sy.zip)** | Supported | Supported (exports plaintext when unlocked; rejected when locked; see §12 Security Premise) |+| **Data sync** | dejavu syncs plaintext | Unchanged (ciphertext in, ciphertext out, self-consistent) |+| **Delete notebook** | Delete directory | Delete directory + delete encrypted db files + delete notebook-level AV storage |+| **Rebuild index** | Full | Skipped on startup (closed); on open box.Index() fully rebuilds into the encrypted db |+| **/api/file/getFile + putFile** | Can read/write any file | Refuses .sy reads/writes on encrypted boxes (prevent ciphertext leak or plaintext corruption) |++**Core difference summary**: An encrypted notebook is an "island" — data is physically isolated, operations have dedicated entry points, it never participates in global features, is completely invisible to AI/LLM, and documents/AV definitions do not cross the boundary. In-box features (editing, block refs, backlinks, search, AV, outline, history, etc.) work normally. Encrypted notebooks are also isolated from each other. Normal notebooks are completely unaffected.++## 4. Key Architecture++```+User master password+ │ Argon2id(global MasterSalt, 64MB/3 passes/4 threads)+ ▼+ KEK (key-encryption key, memory-only, used and discarded)+ │ AES-256-GCM envelope+ ├─→ unwrap BoxConf.WrappedDEK → DEK₁ → encrypts notebook 1's .sy/assets/AV/db+ ├─→ unwrap BoxConf.WrappedDEK → DEK₂ → encrypts notebook 2+ └─→ unwrap BoxConf.WrappedDEK → DEK₃ → encrypts notebook 3+```++- **Argon2id**: OWASP 2023 recommended parameters, brute-force resistant (memory-hard)+- **DEK**: Per-notebook independent 32-byte random key; the key that actually encrypts data+- **KEK envelope**: Changing the password only re-wraps the DEK; data is not re-encrypted+- **KEK not cached**: Derived on every unlock; strict per-box isolation++## 5. Encrypted File Layout++```+<workspace>/+├── conf/conf.json ← global encryption config (MasterSalt/KEKVerifier)+├── storage/av/ ← normal-box AV definitions (plaintext)+├── data/+│ ├── <boxID>/ ← encrypted notebook directory+│ │ ├── .siyuan/conf.json ← BoxConf (Encrypted=true + WrappedDEK)+│ │ ├── *.sy ← AES-256-GCM ciphertext+│ │ ├── assets/+│ │ │ ├── <uuid>-<blockID>.ext ← AES-256-GCM ciphertext, filename desensitized+│ │ │ └── .names.json ← original filename mapping (DEK-encrypted)+│ │ └── storage/av/+│ │ └── <avID>.json ← AV definition (DEK-encrypted)+│ └── <normal-boxID>/ ← normal notebook (plaintext, untouched)+├── history/ ← history directory (ciphertext stored verbatim)+│ └── <timestamp>-update/+│ └── <boxID>/ ← encrypted-box history (ciphertext .sy + ciphertext AV)+└── temp/+ ├── siyuan.db ← global SQLite (plaintext, no encrypted-box data)+ ├── blocktree.db ← global blocktree (plaintext, no encrypted-box data)+ ├── siyuan-encrypted-<boxID>.db ← encrypted-notebook content db (SQLCipher)+ └── siyuan-encrypted-<boxID>-blocktree.db ← encrypted-notebook blocktree db (SQLCipher)+```++## 6. Database Isolation Design++```+Normal-notebook operations:+ frontend → API → original function → global blocktree.db → global siyuan.db++Encrypted-notebook operations (dedicated read path, with boxID):+ frontend(with notebook) → API handler dispatch → InBox function+ → encrypted blocktree db → encrypted content db+```++**Write path**: Centralized funnel; selects db by box. Index queue, blocktree writers, index corrections are all routed by box.++**Read path**: Three-layer fall-through — the handler layer dispatches by the `notebook` parameter; original functions forward to the InBox variant (normal path passes empty boxID); the low-level wrapper decides routing by whether the encrypted db is open, with empty boxID always going to the global db.++**Deep full-routing principle**: Every SQL call on the read path of an encrypted box (including deep helpers: ref counts, block name/alias, child-block recursion, FTS counts, highlighting, mention search, refs definition queries, etc.) is routed to the encrypted db and never leaks to the global db.++**Generic-entry fallback**: Core functions like `GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` automatically iterate opened encrypted boxes when a global lookup misses.++## 7. .sy / assets / AV Encryption++**`.sy` transparent encryption** (filesys layer):+- `DEKProvider` callback injected (avoids circular dependency)+- Decrypts after read, encrypts before write; cache holds plaintext+- Reading an encrypted box's title requires a full read + decrypt before parsing++**assets encryption**:+- On upload, fully read into memory + encrypt + write (cannot stream-encrypt)+- Filename desensitization: encrypted-box asset filenames are `<uuid>-<blockID>.<ext>`; the original name is stored in an encrypted mapping file+- On read, decrypt then output; on download, look up the mapping for the original name+- Encrypted boxes disable the global assets fallback; notebook-level is mandatory+- Asset file rename is forbidden (desensitized-filename rename breaks the mapping)++**AV definition encryption**:+- Path fallback: encrypted-box AV definitions are stored at `<boxID>/storage/av/<avID>.json`; normal boxes still use global `storage/av/`+- Read: first check the global path; on miss, iterate opened encrypted boxes; after finding, DEK-decrypt then JSON-parse+- Save: after JSON serialization, route by path (global plaintext / encrypted-box DEK-encrypted)+- First creation: `RenderAttributeView` looks up the boxID from the blockID and presets ownership+- Mirroring: encrypted boxes are forbidden from cross-boundary mirroring; in-box mirroring stores notebook-level `blocks.msgpack`++## 8. Security Design of History Features++```+File history:+ edit triggers history generation → ciphertext .sy copied verbatim to history dir+ history index → content left empty (ciphertext not indexed for search)+ view history → decrypt by path boxID (notebook must be unlocked)+ roll back → decrypt history → load tree → WriteTree auto-encrypts on write-back++Deleted-notebook history:+ before deletion → entire directory backed up as ciphertext to history dir+ restore → ciphertext directory copied back verbatim++AV history:+ generate → encrypted-box AV definitions copied from notebook-level dir to history dir+ view → decrypt by path boxID+ roll back → encrypted-box AV/resources rolled back to notebook-level dir+```++## 9. Block-Ref Cross-Boundary Protection++Block refs of an encrypted notebook: normal within the box, forbidden across the encrypted boundary. Three layers of defense:++1. **Frontend search dispatch**: When typing `((` or `{{` in an encrypted box triggers a search, the request carries a `notebook` parameter; the kernel only searches that box's own encrypted db, so results exclude other boxes' blocks.+2. **Handler dispatch**: Encrypted boxes call a dedicated search variant.+3. **Write-time fallback check**: Before a transaction commits, the tree is walked and each block-ref node is checked for crossing the boundary; if so, it is downgraded to plain text (ref attributes cleared, anchor text kept). Defends against hand-entered block IDs, drag-and-drop, paste, direct API calls.++## 10. Cross-Boundary Move: Why Forbidden++Encrypted notebooks forbid moving documents across the encrypted boundary (normal ↔ encrypted, bidirectional).++**Data-corruption risk**: Cross-box moves use a filesystem Rename to directly move `.sy` bytes, with no encrypt/decrypt conversion. Ciphertext moved to a normal directory is unreadable; plaintext moved to an encrypted directory is unreadable. Indexes also cannot be migrated across dbs.++**Security-leak risk** (more critical): When moving from an encrypted box to a normal box — the document body escapes encryption protection; associated resources must be moved out and decrypted together; the reference network binding blocks to subdocuments is split or leaked along with it; index-metadata cross-db migration breaks isolation.++**Design stance**: Consistent with disabling export — an encrypted notebook is an island; content does not enter or leave.++## 11. Interaction Design++| Scenario | Interaction |+|---|---|+| Enable | Settings → Access authorization → Encrypted-notebook section → toggle → set master password (double input + risk confirmation) |+| Disable | Supported when no encrypted notebooks exist; clears global encryption config |+| Create | File panel "more" menu → "New encrypted notebook" → enter name + master password → auto-unlock and open |+| 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 |+| Lock | Equals close (DEK cleared + db closed + all plaintext caches cleared) |+| Change password | Settings → Access authorization → "Change master password" |+| Move document | Normal within an encrypted box or between normal boxes; cross-boundary (normal↔encrypted) rejected with a prompt |+| Doc to heading | Cross-boundary rejected with a prompt |+| Block ref | Normal refs within an encrypted box (searching `((` only searches this box; backlinks panel displays normally); cross-boundary (normal↔encrypted, encrypted A↔encrypted B) blocked |+| AV mirroring | Normal mirroring within an encrypted box; cross-boundary forbidden |+| Asset file rename | Not supported (desensitized-filename rename breaks the mapping) |+| Import | Supported: imported .sy.zip or Markdown files are auto DEK-encrypted before writing to disk |+| File history | Supported (must unlock the corresponding encrypted notebook before viewing; the history index stores no plaintext content) |+| Deleted notebook | Supported (ciphertext backup; restored verbatim) |+| Export | Supported (identical to normal notebooks; must unlock first, exports plaintext. Rejected when locked) |+| Sync | Unchanged (ciphertext in, ciphertext out, self-consistent) |++## 12. Security Boundary++**Security premise**: An encrypted notebook is **only secure when it is closed (locked)**. When closed, the DEK is not in memory, the encrypted db has been deleted, all plaintext caches have been cleared, and only ciphertext remains on disk — no path (including authenticated APIs, plugins, MCP, AI) can read plaintext. **When open (unlocked), the DEK is in memory**, and at that point authenticated API requests (including third-party plugins and MCP tools via interfaces exposed by the kernel) can read plaintext content just like a normal notebook — encryption protects "data at rest" and "unreachability when locked", not "visibility to authenticated callers while unlocked". Therefore: while unlocked, treat it as "a normal notebook in use"; isolation of sensitive operations (e.g. AI/LLM isolation, cross-boundary protection) is implemented via functional-layer routing, not ciphertext. **Locking after use** is the only operation that restores full protection.++**Protected (ciphertext on disk)**:+- `.sy` document body ✅+- assets binary files ✅+- assets filenames ✅ (desensitized, original name encrypted)+- AV definitions (columns/rows/cell values/view config/content snapshots) ✅+- content db (blocks/FTS/attributes/refs) ✅+- blocktree db (block-tree metadata: ID/path/title) ✅+- .sy and AV definitions in the history directory ✅ (ciphertext stored verbatim)++**Not protected**:+- MasterSalt/KEKVerifier in `conf.json` (designed to be plaintext: salt is not secret, verifier is ciphertext)+- BoxConf.WrappedDEK (ciphertext, requires KEK to unwrap)+- DEK / plaintext caches in memory (cleared on lock)+- The content field of history indexes (left empty; neither plaintext nor ciphertext)++**API protection**:+- `/api/file/getFile`: refuses to read encrypted-box .sy (ciphertext is meaningless; prevents plugin mis-parsing)+- `/api/file/putFile`: refuses to write encrypted-box .sy (plaintext writes corrupt the ciphertext format)+- MCP `fileRead`: refuses to read encrypted-box files (AI does not enter encrypted notebooks)++## 13. AI / LLM Isolation++Encrypted notebooks are completely invisible and unreachable to all AI/LLM features.++**Layer 1: Physical data isolation (at the content layer, naturally effective)** — encrypted-box content lives in an independent SQLCipher db, and all AI code paths only read the global db → features silently no-op, zero content leakage.++**Layer 2: Metadata filtering (explicit interception)** — MCP notebook list filters out encrypted boxes, document list rejects encrypted boxes, the agent-editor context does not deliver encrypted-box notebookIDs or document titles.++Affected features (all no-op for encrypted boxes): embedding vectorization, semantic search, similar-block recommendation, AI chat/continuation/translation, agent read/write, MCP tools.++## 14. Feature Limitations++An encrypted notebook is an island; some features are unimplemented because of their cross-notebook nature or dependence on global aggregation. These are feature boundaries, not performance or security trade-offs.++- **Flashcards / spaced repetition**: Decks and scheduling are cross-notebook and depend on the global db; not implemented.+- **Bookmarks**: Global aggregation view (scans the global siyuan.db); encrypted notebooks not integrated.+- **Tags**: Global aggregation view (scans the global spans table); encrypted notebooks not integrated.+- **Asset file rename**: Encrypted-box asset filenames are already desensitized to `uuid-blockID.ext`; renaming breaks the original-name mapping.++## 15. Performance Differences++| Operation | Normal Notebook | Encrypted Notebook | Reason |+|---|---|---|---|+| **Unlock (Mount)** | Instant | **~1 second delay** | Argon2id key derivation (intentionally slow for brute-force resistance) |+| **Open document** | Read disk + parse JSON | Read disk + AES-GCM decrypt + parse + encrypted-db query | Extra decrypt + encrypted-db query |+| **Save document** | Render JSON + write disk | Render JSON + AES-GCM encrypt + write disk | Extra encrypt |+| **Upload assets** | Stream to disk | Fully read into memory + encrypt + write | Cannot stream-encrypt; large files cause memory pressure |+| **Browse assets** | Direct ServeFile | Read disk + decrypt + output | Decrypts on every request, no browser cache |+| **AV render** | Global blocktree + plaintext JSON | Encrypted blocktree + DEK-decrypt JSON | Extra JSON decrypt; batch IAL load routed by box |+| **AV save** | Plaintext JSON to disk | DEK-encrypt + write | Extra encrypt |+| **In-notebook search** | FTS query on global db | FTS query on independent encrypted db | SQLCipher page-level decrypt ~5-10% overhead |+| **DB connections** | 1 global | 1 global + 2 per unlocked encrypted box | Each encrypted-db connection pool ~20 connections |+| **When locked** | No extra overhead | All caches cleared | Cold-start latency on next operation |++**Performance summary**:+- **Daily editing experience**: Nearly imperceptible. AES-GCM encryption/decryption is microsecond-level; document read/write is bottlenecked by disk IO.+- **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.++## 16. Usage Recommendations++### Suitable scenarios for encrypted notebooks+- Private diary, financial records, medical information+- Work secrets, business plans, contracts+- Multi-user shared computer where each person has their own encrypted notebook++### Unsuitable scenarios for encrypted notebooks+- Daily notes, study notes (the extra encryption overhead is not worth it)+- Content that needs global search (encrypted notebooks do not participate)+- Knowledge networks needing cross-notebook block refs (cross-boundary forbidden)+- Documents needing cross-notebook move/reorganize (cross-boundary forbidden)+- Scenarios needing cross-notebook AV mirroring (cross-boundary forbidden)+- Content needing flashcard review (not supported)+- Content needing bookmark/tag management (not supported)+- Content needing AI assistance (AI fully isolated)+- Large numbers of large files (assets fully decrypt on every browse)++### Daily usage habits+1. **You must remember the master password**: Forgetting it = data permanently unrecoverable (no backdoor)+2. **Lock after use**: Reduce the DEK's exposure time in memory+3. **Don't put all your notes in encrypted notebooks**: Only put what is truly sensitive+4. **Master password strength**: Recommend 12+ characters, mixed case + digits + symbols+5. **Backup**: Syncing ciphertext to the cloud is safe, but if the password is lost the backup is useless toodiff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdnew file mode 100644index 0000000000..72f93ac2be--- /dev/null+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -0,0 +1,301 @@+# SiYuan 加密笔记本特性++## 1. 设计目标++在 SiYuan 中实现"加密笔记本"——一种特殊笔记本,其 `.sy` 文档、assets 资源文件(含文件名)、属性视图定义、SQLite 索引数据库(content + blocktree)都在磁盘上加密存储,需要主密码解锁才能查看内容。已有的普通笔记本完全不受影响。++## 2. 核心约束++| 维度 | 设计决策 |+|---|---|+| 加密范围 | `.sy` + assets(含文件名)+ AV 定义 + db(content + blocktree)全部加密 |+| 笔记本身份 | 动态 boxID + `BoxConf.Encrypted: true` 标志位 |+| 数量 | 支持多个加密笔记本 |+| 密码 | 共用主密码(KEK 包络,每个笔记本独立 DEK) |+| 解锁粒度 | 严格每笔记本单独解锁(KEK 用完即弃,每次跑 Argon2id ~1 秒) |+| db 方案 | 每个加密笔记本物理独立 SQLCipher db,与全局 siyuan.db 隔离 |+| **隔离原则** | **每个加密笔记本是一个独立孤岛——与普通笔记本隔离,加密笔记本之间也互相隔离。数据、块引、AV 镜像、移动都不跨加密笔记本边界。解锁一个加密笔记本不影响其他加密笔记本的锁定状态。** |+| 全局功能 | 加密笔记本完全不参与(全局搜索/关系图/块引都看不到它) |+| 块引 | box 内部正常引用;禁止跨加密边界引用(双向:普通↔加密、加密 A↔加密 B) |+| AI / LLM | 完全隔离——智能体、AI 对话、嵌入向量化、语义搜索、MCP 都不进入加密笔记本 |+| 跨边界移动 | 禁止——会破坏数据一致性且泄漏 |+| AV / 属性视图 | 笔记本级存储——加密 box 的 AV 定义跟随 box 目录,DEK 加密;禁止跨边界镜像 |+| 闪卡 / 间隔重复 | 不支持(功能限制) |+| 书签 | 不支持(功能限制) |+| 标签 | 不支持(功能限制) |+| 导入 | 支持——导入的 .sy.zip 和 Markdown 在落盘前用 DEK 加密,与手动创建的文档一致 |+| 启用/禁用 | 启用需设主密码;禁用需确认无加密笔记本存在 |+| 重启行为 | 启动时强制关闭所有加密笔记本(DEK 仅内存,重启后丢失),用户需重新解锁 |+| 已有笔记本 | 完全不动,零迁移 |++## 3. 加密笔记本 vs 普通笔记本++| 维度 | 普通笔记本 | 加密笔记本 |+|---|---|---|+| **创建** | 随时创建,无限制 | 需先启用加密功能(设主密码),创建时需验证主密码 |+| **打开(Mount)** | 直接打开 | 需先输主密码解锁(每次 ~1 秒 Argon2id),DEK 进内存 |+| **关闭(Unmount)** | 关闭即不可见 | 关闭 = 锁定(DEK 清除 + 加密 db 关闭 + 所有明文缓存清空) |+| **重启后** | 保持上次打开状态 | 强制关闭,需重新输主密码解锁 |+| **.sy 文件** | 明文 JSON 落盘 | AES-256-GCM 密文落盘,读时透明解密 |+| **assets 文件** | 明文二进制,原始文件名 | AES-256-GCM 密文,文件名脱敏,原始名加密存储 |+| **AV 定义** | 全局 `storage/av/<avID>.json`(明文) | 笔记本级 `<boxID>/storage/av/<avID>.json`(DEK 加密) |+| **content db** | 写入全局 siyuan.db(明文) | 写入独立 siyuan-encrypted-`<boxID>`.db(SQLCipher 加密) |+| **blocktree db** | 写入全局 blocktree.db(明文) | 写入独立 siyuan-encrypted-`<boxID>`-blocktree.db(SQLCipher 加密) |+| **全局搜索** | 参与(FTS 命中) | 不参与(数据不在全局 db) |+| **关系图** | 参与 | 不参与 |+| **块引** | 可被任意笔记本引用 | box 内部正常引用;禁止跨加密边界引用(双向) |+| **移动文档(跨笔记本)** | 支持 | 禁止跨加密边界 |+| **文档转标题(Doc2Heading)** | 支持 | 禁止跨加密边界 |+| **AV 镜像(跨笔记本)** | 支持 | 禁止跨加密边界 |+| **资源文件重命名** | 支持 | 不支持(脱敏文件名重命名会破坏映射) |+| **导入** | 支持 | 支持(.sy.zip 和 Markdown,落盘前自动 DEK 加密) |+| **笔记本内搜索** | 走全局 db | 走加密 db |+| **反链面板** | 走全局 db | 走加密 db(含 mention 子查询) |+| **打开文档 / 大纲 / 面包屑 / 块信息 / 悬浮预览** | 走全局 db | 走加密 db |+| **属性视图(数据库)** | 走全局存储 + 全局 db | 走笔记本级存储(DEK 加密)+ 加密 db |+| **文件历史** | 支持 | 支持(密文 .sy 原样存历史目录,查看/回滚时按路径 boxID 解密) |+| **已删除笔记本历史** | 支持 | 支持(删除前整个目录密文备份,恢复时原样拷回) |+| **嵌入向量化 / 语义搜索** | 参与 | 不参与(AI 不进入加密笔记本) |+| **智能体 / AI 对话 / MCP** | 可读内容、可搜索 | 完全隔离:AI 读不到正文,也感知不到加密 box 的存在 |+| **闪卡 / 间隔重复** | 参与 | 不支持(功能限制) |+| **书签** | 参与(全局聚合) | 不支持(功能限制) |+| **标签** | 参与(全局聚合) | 不支持(功能限制) |+| **列表图标** | 用户自定义 emoji | 关闭时显示锁图标,打开后恢复 emoji |+| **导出(.sy.zip)** | 支持 | 支持(解锁状态下导出明文,未解锁时拒绝;详见 §12 安全前提) |+| **数据同步** | dejavu 同步明文 | 不改(密文进密文出,闭环自洽) |+| **删除笔记本** | 删目录 | 删目录 + 删加密 db 文件 + 删笔记本级 AV 存储 |+| **重建索引** | 全量 | 启动时跳过(已关闭);打开时 box.Index() 全量重建到加密 db |+| **/api/file/getFile + putFile** | 可读写任意文件 | 拒绝加密 box 的 .sy 读写(防止密文泄漏或明文破坏) |++**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能、对 AI/LLM 完全不可见、文档和 AV 定义不进出边界。box 内部功能(编辑、块引、反链、搜索、AV、大纲、历史等)正常使用。加密笔记本之间也互相隔离。普通笔记本完全不受影响。++## 4. 密钥架构++```+用户主密码+ │ Argon2id(全局 MasterSalt, 64MB/3次/4线程)+ ▼+ KEK(密钥加密密钥,仅内存,用完即弃)+ │ AES-256-GCM 包络+ ├─→ 解 BoxConf.WrappedDEK → DEK₁ → 加密笔记本 1 的 .sy/assets/AV/db+ ├─→ 解 BoxConf.WrappedDEK → DEK₂ → 加密笔记本 2+ └─→ 解 BoxConf.WrappedDEK → DEK₃ → 加密笔记本 3+```++- **Argon2id**:OWASP 2023 推荐参数,抗暴力破解(内存硬度)+- **DEK**:每笔记本独立 32 字节随机密钥,真正加密数据的密钥+- **KEK 包络**:改密码只需重新包络 DEK,不重新加密数据+- **不缓存 KEK**:每次解锁都派生,严格 per-box 隔离++## 5. 加密文件布局++```+<workspace>/+├── conf/conf.json ← 全局加密配置(MasterSalt/KEKVerifier)+├── storage/av/ ← 普通 box 的 AV 定义(明文)+├── data/+│ ├── <boxID>/ ← 加密笔记本目录+│ │ ├── .siyuan/conf.json ← BoxConf(Encrypted=true + WrappedDEK)+│ │ ├── *.sy ← AES-256-GCM 密文+│ │ ├── assets/+│ │ │ ├── <uuid>-<blockID>.ext ← AES-256-GCM 密文,文件名已脱敏+│ │ │ └── .names.json ← 原始文件名映射(DEK 加密)+│ │ └── storage/av/+│ │ └── <avID>.json ← AV 定义(DEK 加密)+│ └── <normal-boxID>/ ← 普通笔记本(明文,不动)+├── history/ ← 历史目录(密文原样存储)+│ └── <timestamp>-update/+│ └── <boxID>/ ← 加密 box 的历史(密文 .sy + 密文 AV)+└── temp/+ ├── siyuan.db ← 全局 SQLite(明文,不含加密 box 数据)+ ├── blocktree.db ← 全局 blocktree(明文,不含加密 box 数据)+ ├── siyuan-encrypted-<boxID>.db ← 加密笔记本 content db(SQLCipher)+ └── siyuan-encrypted-<boxID>-blocktree.db ← 加密笔记本 blocktree db(SQLCipher)+```++## 6. 数据库隔离设计++```+普通笔记本操作:+ 前端 → API → 原函数 → 全局 blocktree.db → 全局 siyuan.db++加密笔记本操作(专用读路径,带 boxID):+ 前端(带 notebook) → API handler 分流 → InBox 函数+ → 加密 blocktree db → 加密 content db+```++**写路径**:集中收口,按 box 选 db。索引队列、blocktree 写函数、索引订正全部按 box 路由。++**读路径**:三层 fall-through——handler 层按 `notebook` 参数分流;原函数转发到 InBox 版(普通路径传空 boxID);底层 wrapper 按加密 db 是否打开决定路由,空 boxID 必走全局 db。++**深度全路由原则**:加密 box 的读操作经过的每一个 sql 调用(含深层 helper:引用计数、块名/别名、子块递归、FTS 计数、高亮、mention 搜索、refs 定义查询等)都路由到加密 db,绝不泄漏到全局 db。++**通用入口 fallback**:`GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` 等核心函数全局查不到时自动遍历已打开的加密 box。++## 7. .sy / assets / AV 加解密++**`.sy` 透明加解密**(filesys 层):+- `DEKProvider` 回调注入(避免循环依赖)+- 读盘后解密,写盘前加密,缓存存明文+- 加密 box 的标题读取需整体读 + 解密再解析++**assets 加密**:+- 上传时全量读入内存 + 加密 + 写盘(无法流式加密)+- 文件名脱敏:加密 box 的 asset 文件名为 `<uuid>-<blockID>.<ext>`,原始名存加密映射文件+- 读取时解密后输出,下载时查映射用原始名+- 加密 box 禁用全局 assets 回退,强制笔记本级+- 资源文件重命名禁止(脱敏文件名重命名会破坏映射)++**AV 定义加密**:+- 路径 fallback:加密 box 的 AV 定义存 `<boxID>/storage/av/<avID>.json`,普通 box 仍存全局 `storage/av/`+- 读取:先查全局路径,找不到时遍历已打开的加密 box;找到后 DEK 解密再 JSON 解析+- 保存:JSON 序列化后按路径路由(全局明文 / 加密 box DEK 加密)+- 首次创建:`RenderAttributeView` 从 blockID 反查 boxID 并预设归属+- 镜像:禁止加密 box 参与跨边界镜像;加密 box 内部镜像存笔记本级 `blocks.msgpack`++## 8. 历史功能的安全设计++```+文件历史:+ 编辑触发历史生成 → 密文 .sy 原样拷到历史目录+ 历史索引 → content 留空(密文不进搜索索引)+ 查看历史 → 按路径 boxID 解密(需笔记本已解锁)+ 回滚 → 解密历史 → 加载 tree → WriteTree 自动加密写回++已删除笔记本历史:+ 删除前 → 整个目录密文备份到历史目录+ 恢复 → 密文目录原样拷回++AV 历史:+ 生成 → 加密 box 的 AV 定义从笔记本级目录拷到历史目录+ 查看 → 按路径 boxID 解密+ 回滚 → 加密 box 的 AV/资源回滚到笔记本级目录+```++## 9. 块引跨加密边界防护++加密笔记本的块引:box 内部正常使用,跨加密边界被禁止。三层防御:++1. **前端搜索分流**:加密 box 内输入 `((` 或 `{{` 触发搜索时,请求带 `notebook` 参数,内核只搜该 box 自己的加密 db,结果不含其他 box 的块。+2. **handler 分流**:加密 box 调专用搜索版。+3. **落库兜底校验**:事务落库前遍历树,对每个块引节点判定是否跨边界,跨边界则降级为纯文本(清空引用属性,保留锚文本)。防御手工输入块 ID、拖拽、粘贴、API 直调。++## 10. 跨加密边界移动:为何禁止++加密笔记本禁止文档跨加密边界移动(普通 ↔ 加密,双向)。++**数据损坏风险**:跨 box 移动用文件系统 Rename 直搬 `.sy` 字节流,不经加解密转换。密文搬到普通目录不可读,明文搬到加密目录不可读。索引也无法跨库迁移。++**安全泄漏风险**(更关键):从加密 box 移动到普通 box 时——文档正文脱离加密保护;关联 resources 必须一起搬出解密;绑定块与子文档的引用网被割裂或连带泄漏;索引元数据跨库迁移破坏隔离。++**设计立场**:与禁用导出一致——加密笔记本是孤岛,内容不进出。++## 11. 交互设计++| 场景 | 交互 |+|---|---|+| 启用 | 设置 → 访问授权 → 加密笔记本区块 → 开关 → 设主密码(双输入 + 风险确认) |+| 禁用 | 无加密笔记本时支持关闭,清除全局加密配置 |+| 创建 | 文件面板"更多"菜单 → "新建加密笔记本" → 输名字 + 主密码 → 自动解锁并打开 |+| 图标 | 关闭(锁定)时显示锁图标;打开(解锁)后恢复用户 emoji |+| 解锁 | 点已关闭的加密笔记本 → 弹主密码框(🔓 解锁 xxx)→ 等 ~1 秒 → 打开 |+| 锁定 | 等于关闭(DEK 清除 + db 关闭 + 所有明文缓存清空) |+| 改密 | 设置 → 访问授权 → "修改主密码" |+| 移动文档 | 加密 box 内部或普通 box 之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 |+| 文档转标题 | 跨加密边界被拒绝并提示 |+| 块引 | 加密 box 内部正常引用(搜索 `((` 只搜本 box,反链面板正常显示);跨加密边界(普通↔加密、加密 A↔加密 B)被阻止 |+| AV 镜像 | 加密 box 内部正常镜像;跨加密边界被禁止 |+| 资源文件重命名 | 不支持(脱敏文件名重命名会破坏映射) |+| 导入 | 支持:导入的 .sy.zip 或 Markdown 文件落盘前自动 DEK 加密 |+| 文件历史 | 支持(查看时需先解锁对应加密笔记本;历史索引不存明文内容) |+| 已删除笔记本 | 支持(密文备份,恢复时原样拷回) |+| 导出 | 支持(与普通笔记本一致;需先解锁,导出的是明文。锁定状态下拒绝导出) |+| 同步 | 不改(密文进密文出,闭环自洽) |++## 12. 安全边界++**安全前提**:加密笔记本**只有在关闭(锁定)状态下才是安全的**。关闭时 DEK 不在内存、加密 db 已删除、所有明文缓存已清空,磁盘上仅剩密文,任何途径(包括已认证 API、插件、MCP、AI)都读不到明文。**打开(解锁)状态下,DEK 在内存**,此时已认证的 API 请求(含第三方插件、MCP 工具通过 kernel 暴露的接口)可像读取普通笔记本一样读到明文内容——加密保护的是"落盘数据"和"锁定时的不可达性",不保护"解锁后对已认证调用方的可见性"。因此:解锁期间应视为"普通笔记本在使用",敏感操作的隔离(如 AI/LLM 隔离、跨边界防护)依靠功能层路由实现,而非密文。**用完即锁**是唯一能恢复全面保护的操作。++**保护(磁盘上密文)**:+- `.sy` 文档正文 ✅+- assets 二进制文件 ✅+- assets 文件名 ✅(脱敏,原始名加密存储)+- AV 定义(列/行/cell 值/视图配置/内容快照)✅+- content db(blocks/FTS/attributes/refs)✅+- blocktree db(块树元数据:ID/路径/标题)✅+- 历史目录中的 .sy 和 AV 定义 ✅(密文原样存储)++**不保护**:+- `conf.json` 里的 MasterSalt/KEKVerifier(设计可明文:salt 不保密,verifier 是密文)+- BoxConf.WrappedDEK(密文,需 KEK 解开)+- 内存中的 DEK/明文缓存(锁定时清空)+- 历史索引的 content 字段(留空,不存明文也不存密文)++**API 防护**:+- `/api/file/getFile`:拒绝读取加密 box 的 .sy(密文无意义,防止插件误解析)+- `/api/file/putFile`:拒绝写入加密 box 的 .sy(明文写入会破坏密文格式)+- MCP `fileRead`:拒绝读取加密 box 的文件(AI 不进入加密笔记本)++## 13. AI / LLM 隔离++加密笔记本对一切 AI/LLM 功能完全不可见、不可达。++**第一层:物理数据隔离(正文层面,天然生效)**——加密 box 的内容在独立 SQLCipher 库,所有 AI 代码路径只读全局库 → 功能静默失效,正文零泄漏。++**第二层:元数据过滤(显式拦截)**——MCP notebook 列表过滤加密 box、document 列表拒绝加密 box、智能体编辑器上下文不下发加密 box 的 notebookID 与文档标题。++受影响功能(全部对加密 box 失效):嵌入向量化、语义搜索、相似块推荐、AI 对话/续写/翻译、智能体读写、MCP 工具。++## 14. 功能限制++加密笔记本是孤岛,部分功能因其跨 notebook 特性或依赖全局聚合而未实现,属于功能边界,非性能或安全取舍。++- **闪卡 / 间隔重复**:牌组与调度跨 notebook 且依赖全局 db,未实现。+- **书签**:全局聚合视图(扫全局 siyuan.db),加密 notebook 未接入。+- **标签**:全局聚合视图(扫全局 spans 表),加密 notebook 未接入。+- **资源文件重命名**:加密 box 的 asset 文件名已脱敏为 `uuid-blockID.ext`,重命名会破坏原始名映射。++## 15. 性能区别++| 操作 | 普通笔记本 | 加密笔记本 | 差异原因 |+|---|---|---|---|+| **解锁(Mount)** | 即时 | **~1 秒延迟** | Argon2id 密钥派生(故意慢以抗暴力破解) |+| **打开文档** | 读盘 + 解析 JSON | 读盘 + AES-GCM 解密 + 解析 + 加密 db 查询 | 多一次解密 + 加密 db 查询 |+| **保存文档** | 渲染 JSON + 写盘 | 渲染 JSON + AES-GCM 加密 + 写盘 | 多一次加密 |+| **上传 assets** | 流式写盘 | 全量读入内存 + 加密 + 写盘 | 无法流式加密;大文件有内存压力 |+| **浏览 assets** | 直接 ServeFile | 读盘 + 解密 + 输出 | 每次请求都解密,无浏览器缓存 |+| **AV 渲染** | 全局 blocktree + 明文 JSON | 加密 blocktree + DEK 解密 JSON | 多一次 JSON 解密;批量 IAL 加载按 box 路由 |+| **AV 保存** | 明文 JSON 写盘 | DEK 加密 + 写盘 | 多一次加密 |+| **笔记本内搜索** | FTS 查全局 db | FTS 查独立加密 db | SQLCipher page 级解密 ~5-10% 开销 |+| **数据库连接** | 1 个全局 | 1 个全局 + 每个解锁的加密 box 2 个 | 每加密 db 连接池约 20 连接 |+| **锁定时** | 无额外开销 | 所有缓存清空 | 下次操作冷启动延迟 |++**性能影响总结**:+- **日常编辑体验**:几乎无感知。AES-GCM 加解密是微秒级,文档读写瓶颈在磁盘 IO。+- **感知明显的延迟**:解锁 ~1 秒、大 assets 浏览(每次解密无缓存)、锁定后首次访问(冷启动)。+- **对普通笔记本零影响**:加解密与路由逻辑对非加密 box 短路跳过。++## 16. 使用建议++### 适合用加密笔记本的场景+- 隐私日记、财务记录、医疗信息+- 工作机密、商业方案、合同+- 多用户共享电脑,每人有自己的加密笔记本++### 不适合用加密笔记本的场景+- 日常笔记、学习笔记(加密的额外开销不值得)+- 需要全局搜索的内容(加密笔记本不参与)+- 需要跨笔记本块引的知识网络(禁止跨边界)+- 需要跨笔记本移动整理的文档(禁止跨边界)+- 需要跨笔记本镜像 AV 的场景(禁止跨边界)+- 需要闪卡复习的内容(不支持)+- 需要书签/标签管理的内容(不支持)+- 需要 AI 辅助的内容(AI 完全隔离)+- 大量大文件(assets 每次浏览都全量解密)++### 日常使用习惯建议+1. **主密码必须牢记**:忘记密码 = 数据永久不可恢复(没有后门)+2. **用完即锁**:减少 DEK 在内存的暴露时间+3. **不要把所有笔记都放加密笔记本**:只放真正敏感的+4. **主密码强度**:建议 12 位以上,混合大小写 + 数字 + 符号+5. **备份**:密文同步到云端是安全的,但密码丢了备份也没用