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: Align encrypted notebook design with implementation semantics https://github.com/siyuan-note/siyuan/issues/18034
Daniel2ea0868f68c1
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 060064b8c7..4d2f2e9105 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -16,10 +16,10 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d| SQLite database scheme | Each encrypted notebook has its own physical SQLCipher SQLite database, 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, database 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) |+| Block refs | Normal refs within the notebook; cross-boundary refs forbidden (bidirectional: normal↔encrypted, encrypted A↔encrypted B) || AI / LLM | No functional-layer isolation — when unlocked, AI/LLM can read/search just like a normal notebook; when locked, no usable DEK handle exists and dedicated entry points deny access (see §13) || Cross-boundary move | Forbidden — would break data consistency and leak |-| Database | Notebook-level storage — encrypted box database files follow the box directory, DEK-encrypted; cross-boundary mirroring forbidden |+| Database | Notebook-level storage — encrypted notebook database files follow the notebook directory, DEK-encrypted; cross-boundary mirroring forbidden || Flashcards / spaced repetition | Not supported (feature limitation) || Bookmarks | Not supported (feature limitation) || Tags | Not supported (feature limitation) |@@ -43,7 +43,7 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d| **blocktree SQLite database** | 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 SQLite database) || **Graph** | Participates | Does not participate |-| **Block refs** | Referrable by any notebook | Normal refs within box; cross-boundary refs forbidden (bidirectional) |+| **Block refs** | Referrable by any notebook | Normal refs within notebook; cross-boundary refs forbidden (bidirectional) || **Move doc (cross-notebook)** | Supported | Forbidden across encrypted boundary || **Doc to heading (Doc2Heading)** | Supported | Forbidden across encrypted boundary || **database mirroring (cross-notebook)** | Supported | Forbidden across encrypted boundary |@@ -65,10 +65,10 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d| **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 SQLite database files + delete notebook-level database storage |-| **Rebuild index** | Full | Skipped on startup (closed); on open box.Index() fully rebuilds into the encrypted SQLite database |-| **/api/file/getFile + putFile** | Can read/write any file | Refuses reads/writes of any file under encrypted boxes (not just .sy) and kernel-managed encrypted-notebook plaintext temporary directories; legitimate reads/writes go through dedicated APIs (encryption-aware) |+| **Rebuild index** | Full | Skipped on startup (closed); opening performs a full rebuild into the encrypted SQLite database |+| **/api/file/getFile + putFile** | Can read/write any file | Refuses reads/writes of any file under encrypted notebooks (not just .sy) and kernel-managed encrypted-notebook plaintext temporary directories; legitimate reads/writes go through dedicated APIs (encryption-aware) |-**Core difference summary**: An encrypted notebook is an "island" — data is physically isolated, operations have dedicated entry points, it never participates in global features (global search/graph), and documents/database files do not cross the boundary. In-box features (editing, block refs, backlinks, search, database, outline, history, etc.) work normally; AI/LLM is also usable when unlocked (same as a normal notebook). Encrypted notebooks are also isolated from each other. Normal notebooks are completely unaffected.+**Core difference summary**: An encrypted notebook is an "island" — data is physically isolated, operations have dedicated entry points, it never participates in global features (global search/graph), and documents/database files do not cross the boundary. In-notebook features (editing, block refs, backlinks, search, database, outline, history, etc.) work normally; AI/LLM is also usable when unlocked (same as a normal notebook). Encrypted notebooks are also isolated from each other. Normal notebooks are completely unaffected.## 4. Key Architecture@@ -86,11 +86,11 @@ User master password- **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+- **KEK not cached**: Derived on every unlock; strict per-notebook isolation### 4.1 MasterSalt Backup and Cross-Device Recovery-MasterSalt is the global root of KEK derivation — the master password + MasterSalt derive the KEK via Argon2id, and the KEK then unwraps each box's WrappedDEK. **Losing MasterSalt permanently locks the data**: even with the same master password, a changed salt derives a different KEK, so old WrappedDEKs cannot be unwrapped. A backup-and-recovery mechanism is therefore introduced.+MasterSalt is the global root of KEK derivation — the master password + MasterSalt derive the KEK via Argon2id, and the KEK then unwraps each notebook's WrappedDEK. **Losing MasterSalt permanently locks the data**: even with the same master password, a changed salt derives a different KEK, so old WrappedDEKs cannot be unwrapped. A backup-and-recovery mechanism is therefore introduced.**Backup**: `<DataDir>/.siyuan/notebook-crypto-backup.json`, holding the full NotebookCrypto (MasterSalt/KEKVerifier/KDFParams). Located inside DataDir, it **enters the dejavu sync scope**. It is refreshed when enabling encrypted notebooks and when changing the master password. It may be deleted on disable only after confirming that no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on it, or after the user explicitly chooses to purge those recovery artifacts permanently. Stored as plaintext JSON (salt is not secret, verifier is ciphertext — identical to how they are stored in `conf/conf.json`).@@ -114,7 +114,7 @@ MasterSalt is the global root of KEK derivation — the master password + MasterImport guard: when the local machine is already enabled, import is rejected (to avoid overwriting the existing salt and orphaning WrappedDEKs); the import entry is shown only when not enabled. The backup file itself does not contain the master password (salt is not secret, verifier is ciphertext), so export/import does not leak plaintext data; unlocking still requires the master password.-**Fool-proof guard**: When encrypted notebooks already exist on disk (boxes with `Encrypted=true`) or kernel-enumerable encrypted recovery artifacts exist, `EnableEncryptedNotebook` **refuses to regenerate MasterSalt** (which would orphan old WrappedDEKs) and instead recovers from backup first; only if the backup is missing does it error out and guide the user to restore `conf.json` or the backup file. Symmetrically, `DisableEncryptedNotebook` scans live notebooks, deleted-notebook history, and local recovery snapshots; it refuses to disable while a dependency exists unless the user explicitly chooses to purge those recovery artifacts permanently. Sync endpoints, offline media, and external snapshots cannot be enumerated reliably, so users who may need those copies later must retain an independently exported matching key backup before disabling.+**Fool-proof guard**: When encrypted notebooks already exist on disk (notebooks with `Encrypted=true`) or kernel-enumerable encrypted recovery artifacts exist, `EnableEncryptedNotebook` **refuses to regenerate MasterSalt** (which would orphan old WrappedDEKs) and instead recovers from backup first; only if the backup is missing does it error out and guide the user to restore `conf.json` or the backup file. Symmetrically, `DisableEncryptedNotebook` scans live notebooks, deleted-notebook history, and local recovery snapshots; it refuses to disable while a dependency exists unless the user explicitly chooses to purge those recovery artifacts permanently. Sync endpoints, offline media, and external snapshots cannot be enumerated reliably, so users who may need those copies later must retain an independently exported matching key backup before disabling.**Prerequisite**: `restoreNotebookCryptoConfigFromBackup` only takes effect when the local `Enabled=false`; it never overwrites an in-use local config.@@ -123,7 +123,7 @@ Import guard: when the local machine is already enabled, import is rejected (to```<workspace>/├── conf/conf.json ← global encryption config (MasterSalt/KEKVerifier)-├── storage/av/ ← normal-box database files (plaintext)+├── storage/av/ ← normal-notebook database files (plaintext)├── data/│ ├── .siyuan/│ │ └── notebook-crypto-backup.json ← NotebookCrypto backup (MasterSalt/KEKVerifier, synced; see §4.1)@@ -135,13 +135,13 @@ Import guard: when the local machine is already enabled, import is rejected (to│ │ │ └── .names.json ← original filename mapping (DEK-encrypted)│ │ └── storage/av/│ │ └── <avID>.json ← database file (DEK-encrypted)-│ └── <normal-boxID>/ ← normal notebook (plaintext, untouched)+│ └── <normal-notebookID>/ ← normal notebook (plaintext, untouched)├── history/ ← history directory (ciphertext stored verbatim)│ └── <timestamp>-update/-│ └── <boxID>/ ← encrypted-box history (ciphertext .sy + ciphertext database files)+│ └── <boxID>/ ← encrypted-notebook history (ciphertext .sy + ciphertext database files)└── temp/- ├── siyuan.db ← global SQLite (plaintext, no encrypted-box data)- ├── blocktree.db ← global blocktree (plaintext, no encrypted-box data)+ ├── siyuan.db ← global SQLite (plaintext, no encrypted-notebook data)+ ├── blocktree.db ← global blocktree (plaintext, no encrypted-notebook data)├── siyuan-encrypted-<boxID>.db ← encrypted-notebook content SQLite database (SQLCipher)└── siyuan-encrypted-<boxID>-blocktree.db ← encrypted-notebook blocktree SQLite database (SQLCipher)```@@ -157,37 +157,37 @@ Encrypted-notebook operations (dedicated read path, with boxID):→ encrypted blocktree SQLite database → encrypted content SQLite database```-**Write path**: Centralized funnel; selects db by box. Index queue, blocktree writers, index corrections are all routed by box.+**Write path**: Centralized funnel; selects db by notebook. Index queue, blocktree writers, index corrections are all routed by notebook.**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 SQLite database is open, with empty boxID always going to the global SQLite database.-**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 SQLite database and never leaks to the global SQLite database.+**Deep full-routing principle**: Every SQL call on the read path of an encrypted notebook (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 SQLite database and never leaks to the global SQLite database.-**Generic-entry fallback**: Core functions like `GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` automatically iterate opened encrypted boxes when a global lookup misses.+**Generic-entry fallback**: Core functions like `GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` automatically iterate opened encrypted notebooks when a global lookup misses.## 7. .sy / assets / Database File 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-- `.sy` AAD binds the boxID, object type, and stable file basename `<rootID>.sy`, excluding every parent-directory component. The basename matches the decrypted root-block ID and is globally unique within the box-- Parent directories are outside AAD, and the application continues to build document topology from the existing directory structure. Loading verifies that the basename matches the decrypted root-block ID and rejects duplicate object IDs within one box, invalid paths, and hierarchy cycles, but does not provide cryptographic integrity for parent-directory relations+- Reading an encrypted notebook's title requires a full read + decrypt before parsing+- `.sy` AAD binds the boxID, object type, and stable file basename `<rootID>.sy`, excluding every parent-directory component. The basename matches the decrypted root-block ID and is globally unique within the notebook+- Parent directories are outside AAD, and the application continues to build document topology from the existing directory structure. Loading verifies that the basename matches the decrypted root-block ID and rejects duplicate object IDs within one notebook, invalid paths, and hierarchy cycles, but does not provide cryptographic integrity for parent-directory relations**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+- Filename desensitization: encrypted-notebook 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+- Encrypted notebooks disable the global assets fallback; notebook-level is mandatory- Asset file rename is forbidden (desensitized-filename rename breaks the mapping)- The asset ciphertext and encrypted name mapping commit as one journaled recoverable transaction: write and sync same-directory temporary files, write a transaction journal containing no plaintext name, replace both targets and sync their directories, then clear the journal. Crash recovery rolls forward or back before opening access; any failure is returned to the caller and leaves no externally visible orphaned asset or missing mapping**database file encryption**:-- Path fallback: encrypted-box database files 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)+- Path fallback: encrypted-notebook database files are stored at `<boxID>/storage/av/<avID>.json`; normal notebooks still use global `storage/av/`+- Read: first check the global path; on miss, iterate opened encrypted notebooks; after finding, DEK-decrypt then JSON-parse+- Save: after JSON serialization, route by path (global plaintext / encrypted-notebook 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`+- Mirroring: encrypted notebooks are forbidden from cross-boundary mirroring; within-notebook mirroring stores notebook-level `blocks.msgpack`## 8. Security Design of History Features@@ -205,32 +205,32 @@ Deleted-notebook history:key retention → while kernel-managed history remains recoverable, deletion of the global key backup it depends on is forbidden; permanently purging the history removes the dependencydatabase history:- generate → encrypted-box database files copied from notebook-level dir to history dir+ generate → encrypted-notebook database files copied from notebook-level dir to history dirview → decrypt with the boxID and object purpose/identifier recorded by the snapshot, never with the absolute history-directory path as AAD- roll back → encrypted-box database file/resources rolled back to notebook-level dir+ roll back → encrypted-notebook database file/resources rolled back to notebook-level dir```Parent directories below the history root are not part of AAD. Every history entry retains, in an unambiguous canonical form, the `boxID`, object type, and stable file basename or object identifier at snapshot creation; these values may be encoded by a fixed history layout or stored as metadata committed with the snapshot. Changing only a live document's parent directory leaves its AAD context unchanged; if its basename changes, existing history continues to authenticate with the old basename. Rollback first verifies the ciphertext and that the basename matches the decrypted object ID, then restores under the target parent directory. Re-enveloping is required only when the target basename changes. Missing, malformed, or mismatched snapshot context rejects viewing and rollback; the implementation must not parse ciphertext as plaintext or replace the snapshot basename with the current basename.## 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:+Block refs of an encrypted notebook: normal within the notebook, 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 SQLite database, so results exclude other boxes' blocks.-2. **Handler dispatch**: Encrypted boxes call a dedicated search variant.+1. **Frontend search dispatch**: When typing `((` or `{{` in an encrypted notebook triggers a search, the request carries a `notebook` parameter; the kernel only searches that notebook's own encrypted SQLite database, so results exclude other notebooks' blocks.+2. **Handler dispatch**: Encrypted notebooks 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 ForbiddenEncrypted 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.+**Data-corruption risk**: Cross-notebook 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.-**Move within the same encrypted box**: A `.sy` ciphertext object's AAD binds only its stable basename, not its parent directory. A move that preserves the basename follows normal in-box move semantics and may Rename ciphertext verbatim without re-enveloping the root or descendants. Only a basename change verifies and decrypts with the old basename and re-envelopes with the new one. Indexes are updated after the move, and failure handling remains the same as for a normal notebook; no additional encrypted hierarchy metadata is introduced.+**Move within the same encrypted notebook**: A `.sy` ciphertext object's AAD binds only its stable basename, not its parent directory. A move that preserves the basename follows normal within-notebook move semantics and may Rename ciphertext verbatim without re-enveloping the root or descendants. Only a basename change verifies and decrypts with the old basename and re-envelopes with the new one. Indexes are updated after the move, and failure handling remains the same as for a normal notebook; no additional encrypted hierarchy metadata is introduced.-**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.+**Security-leak risk** (more critical): When moving from an encrypted notebook to a normal notebook — 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**: An encrypted notebook is an island; content does not enter or leave (moving out of an encrypted box to a normal one would leak plaintext; the reverse would corrupt the ciphertext).+**Design stance**: An encrypted notebook is an island; content does not enter or leave (moving out of an encrypted notebook to a normal one would leak plaintext; the reverse would corrupt the ciphertext).## 11. Interaction Design@@ -242,12 +242,12 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma| 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: 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 | Timed independently per box; only a successful content access to that encrypted box refreshes its timer. Normal-notebook activity, global UI input, or access to another box does not refresh it; headless keepalive requests explicitly name a boxID and pass authentication and authorization |+| 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 → Access authorization → "Change master password" |-| Move document | A parent-only move within an encrypted box moves ciphertext verbatim and updates indexes; a basename change re-envelopes content. Moves between normal boxes remain normal; cross-boundary (normal↔encrypted) moves are rejected with a prompt |+| 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 box (searching `((` only searches this box; backlinks panel displays normally); cross-boundary (normal↔encrypted, encrypted A↔encrypted B) blocked |-| database mirroring | Normal mirroring within an encrypted box; cross-boundary forbidden |+| 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 |+| database mirroring | Normal mirroring within an encrypted notebook; 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) |@@ -273,11 +273,11 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma- BoxConf.WrappedDEK (ciphertext, requires KEK to unwrap)- DEK-derived values and transient plaintext copies that may be created by the process or operating system, including swap, hibernation images, and crash dumps; locking revokes managed key handles and best-effort clears application-controlled caches only- The content field of history indexes (left empty; neither plaintext nor ciphertext)-- **Metadata leakage** (encryption does not conceal): file count, directory structure, file sizes, modification times (mtime), asset file extensions, blockID timestamps. Encrypted-box asset filenames are desensitized to `uuid-blockID.ext` but the extension is visible; old ciphertext retained in sync endpoints or historical snapshots is held by those storage providers, and the encrypted notebook cannot revoke their copies.+- **Metadata leakage** (encryption does not conceal): file count, directory structure, file sizes, modification times (mtime), asset file extensions, blockID timestamps. Encrypted-notebook asset filenames are desensitized to `uuid-blockID.ext` but the extension is visible; old ciphertext retained in sync endpoints or historical snapshots is held by those storage providers, and the encrypted notebook cannot revoke their copies.**API protection**:-- `/api/file/getFile`, `/api/file/putFile`, `/api/file/copyFile`, `/api/file/renameFile`, `/api/file/removeFile`: refuse to read/write any file under an encrypted box (not just .sy), preventing ciphertext leakage or plaintext corruption; legitimate reads/writes go through dedicated APIs (encryption-aware).-- Kernel CLI: rejects encrypted notebook/block targets and direct paths below `<workspace>/data/<encrypted-boxID>/`; it cannot be used to unlock, read, write, export, or manipulate encrypted notebook data.+- `/api/file/getFile`, `/api/file/putFile`, `/api/file/copyFile`, `/api/file/renameFile`, `/api/file/removeFile`: refuse to read/write any file under an encrypted notebook (not just .sy), preventing ciphertext leakage or plaintext corruption; legitimate reads/writes go through dedicated APIs (encryption-aware).+- Kernel CLI: rejects encrypted notebook/block targets and direct paths below `<workspace>/data/<encrypted-notebookID>/`; it cannot be used to unlock, read, write, export, or manipulate encrypted notebook data.## 13. AI / LLM Reachability@@ -296,7 +296,7 @@ An encrypted notebook is an island; some features are unimplemented because of t- **Flashcards / spaced repetition**: Decks and scheduling are cross-notebook and depend on the global SQLite database; 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.+- **Asset file rename**: Encrypted-notebook asset filenames are already desensitized to `uuid-blockID.ext`; renaming breaks the original-name mapping.- **Unused asset cleanup**: Encrypted-notebook assets are excluded from global unused-asset cleanup (island, assets do not cross boundaries), preventing false deletion when locked and document references cannot be scanned.- **Unused database cleanup**: Encrypted-notebook database definitions are excluded from global unused-database cleanup, preventing false deletion when locked and reference relationships cannot be confirmed.@@ -309,16 +309,16 @@ An encrypted notebook is an island; some features are unimplemented because of t| **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 |-| **database render** | Global blocktree + plaintext JSON | Encrypted blocktree + DEK-decrypt JSON | Extra JSON decrypt; batch IAL load routed by box |+| **database render** | Global blocktree + plaintext JSON | Encrypted blocktree + DEK-decrypt JSON | Extra JSON decrypt; batch IAL load routed by notebook || **database save** | Plaintext JSON to disk | DEK-encrypt + write | Extra encrypt || **In-notebook search** | FTS query on global SQLite database | FTS query on independent encrypted SQLite database | 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 |+| **DB connections** | 1 global | 1 global + 2 per unlocked encrypted notebook | Each encrypted-db connection pool ~20 connections || **When locked** | No extra overhead | Managed key handles revoked; caches and temporary files cleaned on a best-effort basis | 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.+- **Zero impact on normal notebooks**: Encryption and routing logic short-circuits for non-encrypted notebooks.## 16. Threat Model and Security Scope@@ -330,7 +330,7 @@ The following are outside this feature's security boundary and must be stated in- 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.-- Parent directories are excluded from AAD, so an attacker who can write workspace ciphertext may move valid ciphertext with an unchanged basename within the same box, and the application treats the new parent as the current document topology. Content, box, object type, and stable object ID remain authenticated, but parent-directory topology has no cryptographic integrity guarantee.+- Parent directories are excluded from AAD, so an attacker who can write workspace ciphertext may move valid ciphertext with an unchanged basename within the same notebook, and the application treats the new parent as the current document topology. Content, notebook, object type, and stable object ID remain authenticated, but parent-directory topology has no cryptographic integrity guarantee."Only ciphertext remains after locking" means that kernel-managed persistent workspace storage should contain no readable plaintext and that managed temporary files, caches, and key handles have undergone best-effort cleanup. It excludes files deliberately exported to an external location and does not promise erasure of transient or historical copies retained by the process, operating system, or underlying storage medium.@@ -345,17 +345,17 @@ 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 box 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, clean caches and temporary artifacts, and revoke managed DEK handles while exclusive. They publish `Locked` only after cleanup succeeds. No late plaintext response, cache refill, temporary file, or database reconnection may occur after locking completes.+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, clean caches and temporary artifacts, and revoke managed DEK handles while exclusive. They publish `Locked` only after cleanup succeeds. No late plaintext response, cache refill, temporary file, or database reconnection may occur after locking completes.-The global configuration lock is acquired before any box lifecycle lock. An operation involving multiple boxes 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 uses a monotonic clock per box; only an operation holding that box's valid lease and successfully accessing content may refresh its timer.+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.## 18. Ciphertext, Key, and Database FormatPersistent formats are layered; global KDF configuration, key envelopes, and per-object data envelopes are not conflated:-1. **Data-object envelope**: Every `.sy`, asset, asset-name mapping, and database-definition object contains at least a format version, algorithm identifier, cryptographically random nonce unique for the same purpose key, ciphertext, and authentication tag. The current format constructs AAD deterministically as `format version + boxID + object type + stable object ID`, excluding parent directories and absolute paths. A `.sy` stable object ID is its canonical basename `<rootID>.sy`; an asset uses its desensitized disk basename, a database definition uses its avID, and a fixed singleton file uses a versioned constant ID. After decryption, the internal object ID matches the AAD object ID, and duplicate object IDs within one box are rejected. AES-GCM nonces come from the operating system CSPRNG; randomness failure aborts the write, and the standard per-purpose-key invocation bound is enforced. An authentication tag cannot retrospectively identify nonce reuse, so the design never claims such reuse will automatically cause authentication failure.-2. **Global key and envelope metadata**: `NotebookCrypto` stores the KDF algorithm and parameters, MasterSalt, verifier format, KEK-envelope version, and backup-HMAC version; `BoxConf.WrappedDEK` stores each box's DEK envelope. They are not duplicated in every data object.-3. **Purpose separation**: Each box's DEK derives independent subkeys with fixed domain separators for file content, asset content, asset-name mappings, database definitions, content SQLCipher, and blocktree SQLCipher. The KEK separately derives DEK-wrapping, verifier, and backup-HMAC contexts; WrappedDEK authentication is not incorrectly placed in a DEK domain.+1. **Data-object envelope**: Every `.sy`, asset, asset-name mapping, and database-definition object contains at least a format version, algorithm identifier, cryptographically random nonce unique for the same purpose key, ciphertext, and authentication tag. The current format constructs AAD deterministically as `format version + boxID + object type + stable object ID`, excluding parent directories and absolute paths. A `.sy` stable object ID is its canonical basename `<rootID>.sy`; an asset uses its desensitized disk basename, a database definition uses its avID, and a fixed singleton file uses a versioned constant ID. After decryption, the internal object ID matches the AAD object ID, and duplicate object IDs within one notebook are rejected. AES-GCM nonces come from the operating system CSPRNG; randomness failure aborts the write, and the standard per-purpose-key invocation bound is enforced. An authentication tag cannot retrospectively identify nonce reuse, so the design never claims such reuse will automatically cause authentication failure.+2. **Global key and envelope metadata**: `NotebookCrypto` stores the KDF algorithm and parameters, MasterSalt, verifier format, KEK-envelope version, and backup-HMAC version; `BoxConf.WrappedDEK` stores each notebook's DEK envelope. They are not duplicated in every data object.+3. **Purpose separation**: Each notebook's DEK derives subkeys with fixed domain separators for file content, assets, database definitions, content SQLCipher, and blocktree SQLCipher. Asset content and asset-name mappings may share the asset subkey because their versioned AAD object types differ; a separate subkey for every object type is not required. The KEK may be used directly for the verifier, DEK wrapping, and backup HMAC, with those uses separated by different algorithms, versioned AAD, or authenticated data formats. WrappedDEK authentication is not incorrectly placed in a DEK domain.4. **Database compatibility metadata**: SQLCipher version, cipher parameters, and schema version live in a verifiable database header or the corresponding encrypted configuration boundary, not every data object. Content and blocktree indexes are rebuildable; after source ciphertext authenticates, an incompatible index is closed and rebuilt rather than weakening cipher parameters or falling back to plaintext SQLite.5. **Rename and format stability**: The first released format constructs AAD directly from the stable object ID. It is intentionally incompatible with experimental development ciphertext bound to the full logical relative path and provides neither dual-format reads nor migration; development data is deleted and rebuilt after the format switch. A parent-only move does not re-envelope content. A stable-basename change authenticates and decrypts with the old basename and creates a new envelope with the new basename. After the first released version freezes the format, any future envelope or AAD semantic change increments the format version and requires a separately designed migration.@@ -365,6 +365,8 @@ The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and ba`notebook-crypto-backup.json` is recovery material, not a secret. It contains a format version, backup ID, creation time, content digest, and KEK-based HMAC. After the master password derives the KEK, a missing or mismatched HMAC rejects recovery rather than acting as a compatibility fallback. Recovery must not silently overwrite enabled configuration. A malformed backup or a backup incompatible with existing encrypted notebooks enters an error state instead of generating a new MasterSalt.+Backup persistence follows the project's existing file-write semantics. The global `notebook-crypto-backup.json` is written to a random temporary file in the same directory and then atomically replaced; each notebook's `notebook-crypt-backup.json` uses the ordinary file-lock-protected configuration write. Neither path makes an additional power-loss durability guarantee through file or directory `fsync`. Startup validates the structure and digest that can be checked without a key; recovery validates the HMAC and key-envelope compatibility after the master password is entered. Corruption or mismatch is safely rejected instead of generating replacement key material.+An HMAC proves only that a party without the KEK did not alter the backup; it does not prove that the backup is the latest version. The current scope introduces no trusted external monotonic counter, so an authenticated historical backup or ciphertext may pass validation. `BackupID` and `CreatedAt` are information for diagnostics and manual comparison, not rollback anchors. Sync, history, and recovery flows must not describe successful authentication as proof of freshness or source trust. Strong rollback prevention requires independent trusted state and is outside this design's scope.Sync endpoints and offline backups are storage that may be lost, copied, or rolled back but cannot read plaintext. Trustworthy KEK-based authentication cannot be established before the master password is entered. Users keep at least one independent, versioned key backup and understand that losing the master password or every matching MasterSalt backup is unrecoverable. While a live encrypted notebook, deleted-notebook history, or kernel-enumerable local recovery snapshot depends on the current NotebookCrypto, disabling must refuse to delete global configuration and backup; only an explicit permanent purge of those recovery artifacts removes the dependency. External and remote copies cannot be enumerated reliably, so retaining their matching key backup is the user's responsibility.@@ -380,15 +382,15 @@ Sync endpoints and offline backups are storage that may be lost, copied, or rollUnsupported 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 is registered, including file APIs, kernel CLI, MCP file tools, WebDAV, plugin file interfaces, export download URLs, preview URLs, and background tasks. The registry covers encrypted-box directories and kernel-managed plaintext temporary roots. A temporary root is outside the generic raw-file namespace or denied unconditionally by every raw file API; denial must not depend on whether the box still exists or whether its `Encrypted` flag remains queryable. Adding an entry point requires review of whether it can read, write, copy, rename, delete, or enumerate encrypted and controlled-temporary directories.+Every raw entry point that might bypass dedicated read/write paths is registered, including file APIs, kernel CLI, MCP file tools, WebDAV, plugin file interfaces, export download URLs, preview URLs, and background tasks. The registry covers encrypted-notebook directories and kernel-managed plaintext temporary roots. A temporary root is outside the generic raw-file namespace or denied unconditionally by every raw file API; denial must not depend on whether the notebook still exists or whether its `Encrypted` flag remains queryable. Adding an entry point requires review of whether it can read, write, copy, rename, delete, or enumerate encrypted and controlled-temporary directories.### Locally Persistent Global Deny-Access Records-“Global” means that a record remains effective independently of a box lifecycle after that box has been deleted; it does not mean cross-device synchronization. Records persist at `<ConfDir>/encrypted-deny-access.json`, outside `DataDir` and the dejavu synchronization scope, and manage only local controlled temporary artifacts. Each record contains at least a format version, random artifact ID, boxID, canonical path relative to a controlled root, purpose, creation time, most recent retry time, retry count, and an error class containing no original content or sensitive absolute path. Updates use a temporary write, file sync, atomic replacement, and directory sync. A recorded path is revalidated as a descendant of a controlled temporary root; an escaping or malformed record is never used to delete an arbitrary path and instead raises a security error and triggers a controlled-root rescan.+“Global” means that a record remains effective independently of a notebook lifecycle after that notebook has been deleted; it does not mean cross-device synchronization. Records persist at `<ConfDir>/encrypted-deny-access.json`, outside `DataDir` and the dejavu synchronization scope, and manage only local controlled temporary artifacts. Each record contains at least a format version, random artifact ID, boxID, canonical path relative to a controlled root, purpose, creation time, most recent retry time, retry count, and an error class containing no original content or sensitive absolute path. Updates use a temporary write, file sync, atomic replacement, and directory sync. A recorded path is revalidated as a descendant of a controlled temporary root; an escaping or malformed record is never used to delete an arbitrary path and instead raises a security error and triggers a controlled-root rescan.-A deny record stores cleanup state and diagnostics; it is not the access-control authority. File APIs, downloads, previews, plugins, MCP, WebDAV, and background tasks unconditionally deny the entire controlled-plaintext temporary namespace by canonical path even when the box, registry file, or individual record no longer exists. The janitor runs at application startup, immediately after lock or delete and after export completion or failure, and periodically retries with capped exponential backoff. It atomically removes a record only after cleanup succeeds and the path is confirmed absent. Persistent failure retains the record and the `Error` or global-denial state; exhausting retries never opens access. If the registry is manually deleted, loses entries, or cannot be parsed, access remains denied, and startup and periodic scans reconstruct records from residual controlled-root entries before cleanup continues. Cleanup is complete only after the artifact is confirmed absent and record deletion is committed.+A deny record stores cleanup state and diagnostics; it is not the access-control authority. File APIs, downloads, previews, plugins, MCP, WebDAV, and background tasks unconditionally deny the entire controlled-plaintext temporary namespace by canonical path even when the notebook, registry file, or individual record no longer exists. The janitor runs at application startup, immediately after lock or delete and after export completion or failure, and periodically retries with capped exponential backoff. It atomically removes a record only after cleanup succeeds and the path is confirmed absent. Persistent failure retains the record and the `Error` or global-denial state; exhausting retries never opens access. If the registry is manually deleted, loses entries, or cannot be parsed, access remains denied, and startup and periodic scans reconstruct records from residual controlled-root entries before cleanup continues. Cleanup is complete only after the artifact is confirmed absent and record deletion is committed.-Exports have two classes: a user-selected external destination may contain plaintext after a risk prompt; kernel-managed previews, conversions, downloads, and intermediates exist only in a boxID-scoped controlled temporary directory and are accessed through minimum-privilege tokens bound to the user, boxID, purpose, and expiration. Locking, cancellation, failure, application exit, and export completion invalidate tokens and asynchronous results immediately, then best-effort clean kernel-managed plaintext. On cleanup failure, an existing box enters `Error`; a deleted box leaves a global deny-access marker while a janitor retries. Deletion or locking of a box must never expose that path through a generic file entry point. Logs, error reports, thumbnails, OCR/conversion output, and clipboard handling follow the same rule: no plaintext by default unless the user explicitly sends content to an external program.+Exports have two classes: a user-selected external destination may contain plaintext after a risk prompt; kernel-managed previews, conversions, downloads, and intermediates exist only in a controlled temporary directory scoped by `boxID` and are accessed through minimum-privilege tokens bound to the user, `boxID`, purpose, and expiration. Locking, cancellation, failure, application exit, and export completion invalidate tokens and asynchronous results immediately, then best-effort clean kernel-managed plaintext. On cleanup failure, an existing notebook enters `Error`; a deleted notebook leaves a global deny-access marker while a janitor retries. Deletion or locking of a notebook must never expose that path through a generic file entry point. Logs, error reports, thumbnails, OCR/conversion output, and clipboard handling follow the same rule: no plaintext by default unless the user explicitly sends content to an external program.## 21. Security Acceptance Matrix@@ -397,8 +399,8 @@ Exports have two classes: a user-selected external destination may contain plain| Access while locked through UI, HTTP, file APIs, CLI, MCP, WebDAV, plugins, and background tasks | Other than the explicitly exposed notebook name, cannot read, write, copy, delete, or enumerate encrypted content; returns no plaintext, ciphertext, or document-title-inferable error || Unlock, lock, application restart, and authentication failure | Only `Unlocked` permits a managed DEK handle and database connections; after failure or restart, entry points deny access and application-controlled plaintext caches, temporary files, and handles undergo best-effort cleanup || Lock concurrent with response generation, cache publication, export, preview, sync, indexing, or history restore | Lock succeeds only after all in-flight lifecycle leases end; no late plaintext response, cache refill, temporary file, usable token, or database reconnection follows success |-| Move a document within one encrypted box, then clear caches and restart | When the basename is unchanged, ciphertext remains unchanged and authenticates with the stable object ID; the new parent takes effect under normal-notebook semantics, the old directory location is absent, and failure handling matches a normal notebook |-| 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 |+| Move a document within one encrypted notebook, then clear caches and restart | When the basename is unchanged, ciphertext remains unchanged and authenticates with the stable object ID; the new parent takes effect under normal-notebook semantics, the old directory location is absent, and failure handling matches a normal notebook |+| Refs, moves, mirrors, assets, and database operations between an encrypted notebook and a normal notebook or another encrypted notebook | Island boundaries hold; rejection creates no partial files, global indexes, or relation data || Asset-ciphertext write or name-mapping update fails | The whole logical transaction fails and rolls back; the caller receives an error, with no accessible orphan, missing mapping, or plaintext temporary file || Delete an encrypted notebook while retaining history, then disable or restore | A key dependency prevents deletion of global config and backup; the matching backup and master password restore the notebook, and only explicit permanent purge removes the dependency || Move a document's parent directory or change its basename after creating history, then view or restore the old entry | Authenticate and decrypt with the snapshot boxID, object type, and stable basename recorded by the history entry; rollback re-envelopes only when the target basename changes, while missing snapshot context rejects the operation |@@ -408,7 +410,7 @@ Exports have two classes: a user-selected external destination may contain plain| 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 |-| Concurrent multi-box operations and auto-lock | Lock order has no deadlock; global UI activity or content access in one box does not refresh another box's timer, and a locking box admits no new lease |+| Concurrent multi-notebook operations and auto-lock | Lock order has no deadlock; authenticated UI activity or an explicit keepalive refreshes all currently unlocked notebooks, while background work does not refresh them automatically; a locking notebook admits no new lease |## 22. Usage Guide@@ -427,7 +429,7 @@ Exports have two classes: a user-selected external destination may contain plain> 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, authenticated application callers (APIs, plugins, AI/LLM including MCP) can read plaintext just like a normal notebook; the kernel CLI always rejects encrypted-notebook operations (see §12 Security premise).### Changing the master password-Go to **Settings → Access authorization → Change master password**. Changing the password only re-wraps each box'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 → Access authorization → 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.diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex efddf8bcde..4470ba75de 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -16,10 +16,10 @@| SQLite 数据库方案 | 每个加密笔记本物理独立 SQLCipher SQLite 数据库,与全局 siyuan.db 隔离 || **隔离原则** | **每个加密笔记本是一个独立孤岛——与普通笔记本隔离,加密笔记本之间也互相隔离。数据、块引、数据库镜像、移动都不跨加密笔记本边界。解锁一个加密笔记本不影响其他加密笔记本的锁定状态。** || 全局功能 | 加密笔记本完全不参与(全局搜索/关系图/块引都看不到它) |-| 块引 | box 内部正常引用;禁止跨加密边界引用(双向:普通↔加密、加密 A↔加密 B) |+| 块引 |笔记本内部正常引用;禁止跨加密边界引用(双向:普通↔加密、加密 A↔加密 B) || AI / LLM | 不做功能层隔离——解锁后与普通笔记本一样可读可搜;锁定后无可用 DEK 句柄且专用入口拒绝访问(详见 §13) || 跨边界移动 | 禁止——会破坏数据一致性且泄漏 |-| 数据库 | 笔记本级存储——加密 box 的 数据库文件跟随 box 目录,DEK 加密;禁止跨边界镜像 |+| 数据库 | 笔记本级存储——加密笔记本的 数据库文件跟随笔记本目录,DEK 加密;禁止跨边界镜像 || 闪卡 / 间隔重复 | 不支持(功能限制) || 书签 | 不支持(功能限制) || 标签 | 不支持(功能限制) |@@ -43,7 +43,7 @@| **blocktree SQLite 数据库** | 写入全局 blocktree.db(明文) | 写入独立 siyuan-encrypted-`<boxID>`-blocktree.db(SQLCipher 加密) || **全局搜索** | 参与(FTS 命中) | 不参与(数据不在全局 SQLite 数据库) || **关系图** | 参与 | 不参与 |-| **块引** | 可被任意笔记本引用 | box 内部正常引用;禁止跨加密边界引用(双向) |+| **块引** | 可被任意笔记本引用 |笔记本内部正常引用;禁止跨加密边界引用(双向) || **移动文档(跨笔记本)** | 支持 | 禁止跨加密边界 || **文档转标题(Doc2Heading)** | 支持 | 禁止跨加密边界 || **数据库镜像(跨笔记本)** | 支持 | 禁止跨加密边界 |@@ -65,10 +65,10 @@| **导出(.sy.zip)** | 支持 | 支持(解锁状态下导出明文,未解锁时拒绝;详见 §12 安全前提) || **数据同步** | dejavu 同步明文 | 不改(密文进密文出,闭环自洽) || **删除笔记本** | 删目录 | 删目录 + 删加密 SQLite 数据库 文件 + 删笔记本级数据库存储 |-| **重建索引** | 全量 | 启动时跳过(已关闭);打开时 box.Index() 全量重建到加密 SQLite 数据库 |-| **/api/file/getFile + putFile** | 可读写任意文件 | 拒绝读写加密 box 下的任何文件(不只 .sy)以及内核管理的加密笔记本明文临时目录,防止密文泄漏或明文破坏;合法读写走专用 API |+| **重建索引** | 全量 | 启动时跳过(已关闭);打开时全量重建到加密 SQLite 数据库 |+| **/api/file/getFile + putFile** | 可读写任意文件 | 拒绝读写加密笔记本下的任何文件(不只 .sy)以及内核管理的加密笔记本明文临时目录,防止密文泄漏或明文破坏;合法读写走专用 API |-**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、文档和 数据库文件不进出边界。box 内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 也可用(与普通笔记本一致)。加密笔记本之间也互相隔离。普通笔记本完全不受影响。+**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、文档和 数据库文件不进出边界。笔记本内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 也可用(与普通笔记本一致)。加密笔记本之间也互相隔离。普通笔记本完全不受影响。## 4. 密钥架构@@ -86,11 +86,11 @@- **Argon2id**:OWASP 2023 推荐参数,抗暴力破解(内存硬度)- **DEK**:每笔记本独立 32 字节随机密钥,真正加密数据的密钥- **KEK 包络**:改密码只需重新包络 DEK,不重新加密数据-- **不缓存 KEK**:每次解锁都派生,严格 per-box 隔离+- **不缓存 KEK**:每次解锁都派生,保持严格的笔记本间隔离### 4.1 MasterSalt 备份与跨设备恢复-MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各 box 的 WrappedDEK。**MasterSalt 丢失等于数据永久锁死**:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。+MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各笔记本的 WrappedDEK。**MasterSalt 丢失等于数据永久锁死**:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。**备份**:`<DataDir>/.siyuan/notebook-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储(salt 不保密、verifier 是密文,与 `conf/conf.json` 的存储方式一致)。@@ -114,7 +114,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i导入防呆:本机已启用时拒绝导入(避免覆盖现有 salt 孤立 WrappedDEK),导入入口仅在未启用时露出。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出/导入不涉及明文数据泄漏,解锁仍需主密码。-**防呆守卫**:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的 box)或内核可枚举的加密恢复数据时,**禁止重新生成 MasterSalt**(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。`DisableEncryptedNotebook` 对称地扫描现存笔记本、已删除笔记本历史和本地恢复快照;存在依赖时必须拒绝禁用,除非用户明确选择永久清除这些恢复数据。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。+**防呆守卫**:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的笔记本)或内核可枚举的加密恢复数据时,**禁止重新生成 MasterSalt**(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。`DisableEncryptedNotebook` 对称地扫描现存笔记本、已删除笔记本历史和本地恢复快照;存在依赖时必须拒绝禁用,除非用户明确选择永久清除这些恢复数据。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。**前提条件**:`restoreNotebookCryptoConfigFromBackup` 仅在本机 `Enabled=false` 时生效,不覆盖正在使用的本机配置。@@ -123,7 +123,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i```<workspace>/├── conf/conf.json ← 全局加密配置(MasterSalt/KEKVerifier)-├── storage/av/ ← 普通 box 的 数据库文件(明文)+├── storage/av/ ← 普通笔记本的 数据库文件(明文)├── data/│ ├── .siyuan/│ │ └── notebook-crypto-backup.json ← NotebookCrypto 备份(MasterSalt/KEKVerifier,进同步范围,详见 §4.1)@@ -135,13 +135,13 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i│ │ │ └── .names.json ← 原始文件名映射(DEK 加密)│ │ └── storage/av/│ │ └── <avID>.json ← 数据库文件(DEK 加密)-│ └── <normal-boxID>/ ← 普通笔记本(明文,不动)+│ └── <normalNotebookID>/ ← 普通笔记本(明文,不动)├── history/ ← 历史目录(密文原样存储)│ └── <timestamp>-update/-│ └── <boxID>/ ← 加密 box 的历史(密文 .sy + 密文数据库文件)+│ └── <boxID>/ ← 加密笔记本的历史(密文 .sy + 密文数据库文件)└── temp/- ├── siyuan.db ← 全局 SQLite(明文,不含加密 box 数据)- ├── blocktree.db ← 全局 blocktree(明文,不含加密 box 数据)+ ├── siyuan.db ← 全局 SQLite(明文,不含加密笔记本数据)+ ├── blocktree.db ← 全局 blocktree(明文,不含加密笔记本数据)├── siyuan-encrypted-<boxID>.db ← 加密笔记本 content SQLite 数据库(SQLCipher)└── siyuan-encrypted-<boxID>-blocktree.db ← 加密笔记本 blocktree SQLite 数据库(SQLCipher)```@@ -157,37 +157,37 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i→ 加密 blocktree SQLite 数据库 → 加密 content SQLite 数据库```-**写路径**:集中收口,按 box 选 SQLite 数据库。索引队列、blocktree 写函数、索引订正全部按 box 路由。+**写路径**:集中收口,按笔记本选 SQLite 数据库。索引队列、blocktree 写函数、索引订正全部按笔记本路由。**读路径**:三层 fall-through——handler 层按 `notebook` 参数分流;原函数转发到 InBox 版(普通路径传空 boxID);底层 wrapper 按加密 SQLite 数据库 是否打开决定路由,空 boxID 必走全局 SQLite 数据库。-**深度全路由原则**:加密 box 的读操作经过的每一个 sql 调用(含深层 helper:引用计数、块名/别名、子块递归、FTS 计数、高亮、mention 搜索、refs 定义查询等)都路由到加密 SQLite 数据库,绝不泄漏到全局 SQLite 数据库。+**深度全路由原则**:加密笔记本的读操作经过的每一个 sql 调用(含深层 helper:引用计数、块名/别名、子块递归、FTS 计数、高亮、mention 搜索、refs 定义查询等)都路由到加密 SQLite 数据库,绝不泄漏到全局 SQLite 数据库。-**通用入口 fallback**:`GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` 等核心函数全局查不到时自动遍历已打开的加密 box。+**通用入口 fallback**:`GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` 等核心函数全局查不到时自动遍历已打开的加密笔记本。## 7. .sy / assets / 数据库文件加解密**`.sy` 透明加解密**(filesys 层):- `DEKProvider` 回调注入(避免循环依赖)- 读盘后解密,写盘前加密,缓存存明文-- 加密 box 的标题读取需整体读 + 解密再解析-- `.sy` AAD 绑定 boxID、对象类型和稳定文件基名 `<rootID>.sy`,不包含父目录;文件基名必须与解密后根块 ID 一致,并在 box 内全局唯一-- 父目录不属于 AAD,应用仍按现有目录结构构建文档层级;加载时校验文件基名与解密后根块 ID 一致,并拒绝同一 box 内的重复对象 ID、非法路径和循环层级,但不提供父目录关系的密码学完整性+- 加密笔记本的标题读取需整体读 + 解密再解析+- `.sy` AAD 绑定 boxID、对象类型和稳定文件基名 `<rootID>.sy`,不包含父目录;文件基名必须与解密后根块 ID 一致,并在笔记本内全局唯一+- 父目录不属于 AAD,应用仍按现有目录结构构建文档层级;加载时校验文件基名与解密后根块 ID 一致,并拒绝同一笔记本内的重复对象 ID、非法路径和循环层级,但不提供父目录关系的密码学完整性**assets 加密**:- 上传时全量读入内存 + 加密 + 写盘(无法流式加密)-- 文件名脱敏:加密 box 的 asset 文件名为 `<uuid>-<blockID>.<ext>`,原始名存加密映射文件+- 文件名脱敏:加密笔记本的 asset 文件名为 `<uuid>-<blockID>.<ext>`,原始名存加密映射文件- 读取时解密后输出,下载时查映射用原始名-- 加密 box 禁用全局 assets 回退,强制笔记本级+- 加密笔记本禁用全局 assets 回退,强制笔记本级- 资源文件重命名禁止(脱敏文件名重命名会破坏映射)- 资源密文与加密名称映射作为一个带日志的可恢复事务提交:先写同目录临时文件并同步落盘,再写不含明文名称的事务日志,随后替换两个目标并同步目录,最后清除日志;崩溃恢复必须在开放访问前完成前滚或回滚,任何失败都向调用方返回错误,不得留下对外可见的孤儿资源或缺失映射**数据库文件加密**:-- 路径 fallback:加密 box 的 数据库文件存 `<boxID>/storage/av/<avID>.json`,普通 box 仍存全局 `storage/av/`-- 读取:先查全局路径,找不到时遍历已打开的加密 box;找到后 DEK 解密再 JSON 解析-- 保存:JSON 序列化后按路径路由(全局明文 / 加密 box DEK 加密)+- 路径 fallback:加密笔记本的数据库文件存 `<boxID>/storage/av/<avID>.json`,普通笔记本仍存全局 `storage/av/`+- 读取:先查全局路径,找不到时遍历已打开的加密笔记本;找到后 DEK 解密再 JSON 解析+- 保存:JSON 序列化后按路径路由(全局明文 / 加密笔记本 DEK 加密)- 首次创建:`RenderAttributeView` 从 blockID 反查 boxID 并预设归属-- 镜像:禁止加密 box 参与跨边界镜像;加密 box 内部镜像存笔记本级 `blocks.msgpack`+- 镜像:禁止加密笔记本参与跨边界镜像;加密笔记本内部镜像存笔记本级 `blocks.msgpack`## 8. 历史功能的安全设计@@ -205,32 +205,32 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i密钥保留 → 只要内核管理的该类历史仍可恢复,就禁止删除其依赖的全局密钥备份;永久清除历史后才解除依赖数据库历史:- 生成 → 加密 box 的 数据库文件从笔记本级目录拷到历史目录+ 生成 → 加密笔记本的 数据库文件从笔记本级目录拷到历史目录查看 → 按快照记录的 boxID 与对象用途/标识解密,不使用历史目录绝对路径作为 AAD- 回滚 → 加密 box 的数据库文件/资源回滚到笔记本级目录+ 回滚 → 加密笔记本的数据库文件/资源回滚到笔记本级目录```历史文件在历史目录中的父路径不是 AAD 的组成部分。每个历史条目必须以不可歧义的规范格式保留快照写入时的 `boxID`、对象类型和稳定文件基名或对象标识;可由固定历史目录布局编码,也可由随快照提交的元数据记录。文档只改变父目录时 AAD 上下文保持不变;文件基名改变时,既有历史仍使用旧基名认证解密。回滚时先验证密文、文件基名与解密后对象 ID 一致,再按目标父目录恢复;仅当目标文件基名变化时才按新基名重新封装。快照上下文缺失、格式不合法或与密文不匹配时必须拒绝查看和回滚,不得把密文当明文解析或使用当前文件基名替代快照基名。## 9. 块引跨加密边界防护-加密笔记本的块引:box 内部正常使用,跨加密边界被禁止。三层防御:+加密笔记本的块引:笔记本内部正常使用,跨加密边界被禁止。三层防御:-1. **前端搜索分流**:加密 box 内输入 `((` 或 `{{` 触发搜索时,请求带 `notebook` 参数,内核只搜该 box 自己的加密 SQLite 数据库,结果不含其他 box 的块。-2. **handler 分流**:加密 box 调专用搜索版。+1. **前端搜索分流**:加密笔记本内输入 `((` 或 `{{` 触发搜索时,请求带 `notebook` 参数,内核只搜该笔记本自己的加密 SQLite 数据库,结果不含其他笔记本的块。+2. **handler 分流**:加密笔记本调专用搜索版。3. **落库兜底校验**:事务落库前遍历树,对每个块引节点判定是否跨边界,跨边界则降级为纯文本(清空引用属性,保留锚文本)。防御手工输入块 ID、拖拽、粘贴、API 直调。## 10. 跨加密边界移动:为何禁止加密笔记本禁止文档跨加密边界移动(普通 ↔ 加密,双向)。-**数据损坏风险**:跨 box 移动用文件系统 Rename 直搬 `.sy` 字节流,不经加解密转换。密文搬到普通目录不可读,明文搬到加密目录不可读。索引也无法跨库迁移。+**数据损坏风险**:跨笔记本移动用文件系统 Rename 直搬 `.sy` 字节流,不经加解密转换。密文搬到普通目录不可读,明文搬到加密目录不可读。索引也无法跨库迁移。-**同一加密 box 内移动**:`.sy` 密文 AAD 只绑定稳定文件基名,不绑定父目录。文件基名不变的移动按普通笔记本的同箱移动语义原样 Rename 密文,不需要重新封装根文档或子文档;只有文件基名本身变化时才使用旧基名验证解密并按新基名重新封装。移动完成后更新索引,失败处理与普通笔记本一致,不额外引入加密层级元数据。+**同一加密笔记本内移动**:`.sy` 密文 AAD 只绑定稳定文件基名,不绑定父目录。文件基名不变的移动按普通笔记本的同箱移动语义原样 Rename 密文,不需要重新封装根文档或子文档;只有文件基名本身变化时才使用旧基名验证解密并按新基名重新封装。移动完成后更新索引,失败处理与普通笔记本一致,不额外引入加密层级元数据。-**安全泄漏风险**(更关键):从加密 box 移动到普通 box 时——文档正文脱离加密保护;关联 resources 必须一起搬出解密;绑定块与子文档的引用网被割裂或连带泄漏;索引元数据跨库迁移破坏隔离。+**安全泄漏风险**(更关键):从加密笔记本移动到普通笔记本时——文档正文脱离加密保护;关联 resources 必须一起搬出解密;绑定块与子文档的引用网被割裂或连带泄漏;索引元数据跨库迁移破坏隔离。-**设计立场**:加密笔记本是孤岛,内容不进出(从加密笔记本移出到普通 box 会泄漏明文;反之会损坏密文)。+**设计立场**:加密笔记本是孤岛,内容不进出(从加密笔记本移出到普通笔记本会泄漏明文;反之会损坏密文)。## 11. 交互设计@@ -242,12 +242,12 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i| 图标 | 关闭(锁定)时显示锁图标;打开(解锁)后恢复用户 emoji || 解锁 | 点已关闭的加密笔记本 → 弹主密码框(🔓 解锁 xxx)→ 等 ~1 秒 → 打开 || 锁定 | 等于关闭:先阻止新操作,等待或取消在途任务,再移除受管 DEK 句柄、删除加密 SQLite 数据库,并尽力清理内核管理的明文缓存、临时文件和访问令牌。关闭前会自动保存未写入的编辑和文件历史 |-| 自动锁定 | 按 box 单独计时;只有成功访问该加密 box 内容的操作才刷新其计时,普通笔记本活动、全局界面输入或其他 box 的访问不得刷新;无界面的保活请求必须显式携带 boxID 并通过认证与授权 |+| 自动锁定 | 每个已解锁笔记本独立保存最近活动时间;认证用户在当前工作区产生真实界面交互时,统一刷新所有当前已解锁加密笔记本的活动时间。无界面客户端也可通过需要认证与管理员权限的显式保活接口执行同样的刷新;后台读取、同步、索引等非用户活动不自动保活 || 改密 | 设置 → 访问授权 → "修改主密码" |-| 移动文档 | 加密 box 内部仅改变父目录时原样移动密文并更新索引;文件基名变化时重新封装;普通 box 之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 |+| 移动文档 | 加密笔记本内部仅改变父目录时原样移动密文并更新索引;文件基名变化时重新封装;普通笔记本之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 || 文档转标题 | 跨加密边界被拒绝并提示 |-| 块引 | 加密 box 内部正常引用(搜索 `((` 只搜本 box,反链面板正常显示);跨加密边界(普通↔加密、加密 A↔加密 B)被阻止 |-| 数据库镜像 | 加密 box 内部正常镜像;跨加密边界被禁止 |+| 块引 | 加密笔记本内部正常引用(搜索 `((` 只搜本笔记本,反链面板正常显示);跨加密边界(普通↔加密、加密 A↔加密 B)被阻止 |+| 数据库镜像 | 加密笔记本内部正常镜像;跨加密边界被禁止 || 资源文件重命名 | 不支持(脱敏文件名重命名会破坏映射) || 导入 | 支持:导入的 .sy.zip 或 Markdown 文件落盘前自动 DEK 加密 || 文件历史 | 支持(查看时需先解锁对应加密笔记本;历史索引不存明文内容) |@@ -273,11 +273,11 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i- BoxConf.WrappedDEK(密文,需 KEK 解开)- 进程和操作系统可能产生的 DEK 派生值、明文瞬时副本、交换区、休眠映像或崩溃转储;锁定只保证撤销受管密钥句柄和尽力清理应用可控缓存- 历史索引的 content 字段(留空,不存明文也不存密文)-- **元数据泄漏**(加密不掩盖以下信息):文件数量、目录结构、文件大小、修改时间(mtime)、asset 文件扩展名、blockID 时间戳。加密 box 的 asset 文件名虽脱敏为 `uuid-blockID.ext`,但扩展名可见;同步端/历史快照中的旧密文也由各存储方自行保管,加密笔记本无法吊销其副本+- **元数据泄漏**(加密不掩盖以下信息):文件数量、目录结构、文件大小、修改时间(mtime)、asset 文件扩展名、blockID 时间戳。加密笔记本的 asset 文件名虽脱敏为 `uuid-blockID.ext`,但扩展名可见;同步端/历史快照中的旧密文也由各存储方自行保管,加密笔记本无法吊销其副本**API 防护**:-- `/api/file/getFile`、`/api/file/putFile`、`/api/file/copyFile`、`/api/file/renameFile`、`/api/file/removeFile`:拒绝读写加密 box 下的任何文件(不只 .sy),避免密文泄漏或明文破坏;合法读写走专用 API(已加密感知)-- 内核 CLI:拒绝以加密笔记本或块 ID 为目标的命令,以及 `<工作区>/data/<加密-boxID>/` 下的直接路径;不能用于解锁、读写、导出或操作加密笔记本数据+- `/api/file/getFile`、`/api/file/putFile`、`/api/file/copyFile`、`/api/file/renameFile`、`/api/file/removeFile`:拒绝读写加密笔记本下的任何文件(不只 .sy),避免密文泄漏或明文破坏;合法读写走专用 API(已加密感知)+- 内核 CLI:拒绝以加密笔记本或块 ID 为目标的命令,以及 `<工作区>/data/<加密笔记本 ID>/` 下的直接路径;不能用于解锁、读写、导出或操作加密笔记本数据## 13. AI / LLM 可达性@@ -296,7 +296,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i- **闪卡 / 间隔重复**:牌组与调度跨 notebook 且依赖全局 SQLite 数据库,未实现。- **书签**:全局聚合视图(扫全局 siyuan.db),加密笔记本 未接入。- **标签**:全局聚合视图(扫全局 spans 表),加密笔记本 未接入。-- **资源文件重命名**:加密 box 的 asset 文件名已脱敏为 `uuid-blockID.ext`,重命名会破坏原始名映射。+- **资源文件重命名**:加密笔记本的 asset 文件名已脱敏为 `uuid-blockID.ext`,重命名会破坏原始名映射。- **未引用资源清理**:加密笔记本的资源不参与全局未引用清理(孤岛,资源不跨边界),避免锁定时因无法扫描文档引用而误删。- **未引用数据库清理**:加密笔记本的数据库定义不参与全局未引用清理,避免锁定时因无法确认引用关系而误删。@@ -309,16 +309,16 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i| **保存文档** | 渲染 JSON + 写盘 | 渲染 JSON + AES-GCM 加密 + 写盘 | 多一次加密 || **上传 assets** | 流式写盘 | 全量读入内存 + 加密 + 写盘 | 无法流式加密;大文件有内存压力 || **浏览 assets** | 直接 ServeFile | 读盘 + 解密 + 输出 | 每次请求都解密,无浏览器缓存 |-| **数据库渲染** | 全局 blocktree + 明文 JSON | 加密 blocktree + DEK 解密 JSON | 多一次 JSON 解密;批量 IAL 加载按 box 路由 |+| **数据库渲染** | 全局 blocktree + 明文 JSON | 加密 blocktree + DEK 解密 JSON | 多一次 JSON 解密;批量 IAL 加载按笔记本路由 || **数据库保存** | 明文 JSON 写盘 | DEK 加密 + 写盘 | 多一次加密 || **笔记本内搜索** | FTS 查全局 SQLite 数据库 | FTS 查独立加密 SQLite 数据库 | SQLCipher page 级解密 ~5-10% 开销 |-| **数据库连接** | 1 个全局 | 1 个全局 + 每个解锁的加密 box 2 个 | 每加密 SQLite 数据库 连接池约 20 连接 |+| **数据库连接** | 1 个全局 | 1 个全局 + 每个解锁的加密笔记本 2 个 | 每加密 SQLite 数据库 连接池约 20 连接 || **锁定时** | 无额外开销 | 受管密钥句柄撤销,并尽力清理缓存与临时文件 | 下次操作冷启动延迟 |**性能影响总结**:- **日常编辑体验**:几乎无感知。AES-GCM 加解密是微秒级,文档读写瓶颈在磁盘 IO。- **感知明显的延迟**:解锁 ~1 秒、大 assets 浏览(每次解密无缓存)、锁定后首次访问(冷启动)。-- **对普通笔记本零影响**:加解密与路由逻辑对非加密 box 短路跳过。+- **对普通笔记本零影响**:加解密与路由逻辑对非加密笔记本短路跳过。## 16. 威胁模型与安全范围@@ -330,7 +330,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i- 用户主动导出的文件、剪贴板、截图、打印件、分享给第三方的内容,以及保存在工作区外的明文文件,由用户负责保护。- 操作系统交换分区、休眠映像、崩溃转储、文件系统快照和恶意软件不因“清除内存”而获得绝对保护;锁定仅做应用可控范围内的尽力清除。- 同步服务或备份持有者可以保留、删除、替换或回滚密文;这些行为可能造成拒绝服务或数据回退,但不能在不知道主密码时解密有效密文。-- 父目录不进入 AAD,因此能够写工作空间密文的攻击者可以在同一 box 内移动一个文件基名不变的有效密文,应用会把新父目录视为当前文档层级;内容、box、对象类型和稳定对象 ID 仍受认证,但父目录层级本身不提供密码学完整性。+- 父目录不进入 AAD,因此能够写工作空间密文的攻击者可以在同一笔记本内移动一个文件基名不变的有效密文,应用会把新父目录视为当前文档层级;内容、笔记本、对象类型和稳定对象 ID 仍受认证,但父目录层级本身不提供密码学完整性。“锁定后仅剩密文”只表示内核管理的持久化工作空间中不应存在可读明文,并且受管临时文件、缓存和密钥句柄已经完成尽力清理;不包括用户明确导出到外部位置的文件,也不承诺抹除进程、操作系统或底层存储介质已经保留的瞬时或历史副本。@@ -345,17 +345,17 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i| `Unlocked → Error` | 密文认证失败、数据库打开失败或不变量被破坏 | 立即拒绝读写,绝不回退到普通笔记本路径 | 关闭资源,诊断信息不得含明文;用户只能锁定或重新解锁 || 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK、全局配置和备份作为一个可恢复事务更新 | 保留旧配置和备份可用;不得出现仅能用新密码解锁的部分笔记本 |-每个 box 使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、清理缓存和临时产物并撤销受管 DEK 句柄;只有清理成功才发布 `Locked`。因此锁定完成后,不得再出现晚到的明文响应、缓存回填、临时文件或数据库重连。+每个笔记本使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、清理缓存和临时产物并撤销受管 DEK 句柄;只有清理成功才发布 `Locked`。因此锁定完成后,不得再出现晚到的明文响应、缓存回填、临时文件或数据库重连。-全局配置锁必须先于任何 box 生命周期锁获取;同时涉及多个 box 时按 boxID 字典序获取生命周期锁;DEK 缓存、数据库、文件和其他子系统锁只能在生命周期锁之后获取,并在释放生命周期锁前释放。禁止逆序获取,禁止持有子系统锁时回取全局配置锁或其他较低层级锁。自动锁定使用单调时钟按 box 计算,只有持有该 box 有效租约并成功访问内容的操作才能刷新计时。+全局配置锁必须先于任何笔记本生命周期锁获取;同时涉及多个笔记本时按 boxID 字典序获取生命周期锁;DEK 缓存、数据库、文件和其他子系统锁只能在生命周期锁之后获取,并在释放生命周期锁前释放。禁止逆序获取,禁止持有子系统锁时回取全局配置锁或其他较低层级锁。自动锁定按每个笔记本保存活动时间,但当前工作区的一次认证用户交互或显式保活会统一刷新所有已解锁笔记本;计时采用系统时钟并由周期任务检查,系统时钟调整可能相应提前或推迟触发时间,自动锁定是便利性保护而不是精确的安全计时边界。## 18. 密文、密钥与数据库格式持久化格式分层,不能把全局 KDF 配置、密钥包络和每个数据对象的封装混为一体:-1. **数据对象封装**:每个 `.sy`、资源、资源名称映射和数据库定义对象至少包含格式版本、算法标识、密码学安全随机生成且对同一用途密钥唯一的 nonce、密文和认证标签。当前格式的 AAD 按 `格式版本 + boxID + 对象类型 + 稳定对象 ID` 确定性构造,不包含父目录或绝对路径;`.sy` 的稳定对象 ID 是规范化文件基名 `<rootID>.sy`,资源使用脱敏磁盘文件基名,数据库定义使用 avID,固定单例文件使用版本化常量 ID。解密后必须验证对象内部 ID 与 AAD 对象 ID 一致,并拒绝同一 box 内的重复对象 ID。AES-GCM nonce 由操作系统 CSPRNG 生成,随机源失败必须终止写入,并按标准规定限制每个用途密钥的调用规模;认证标签不能事后识别已经发生的 nonce 重用,因此不得宣称此类重用会被认证失败自动发现。-2. **全局密钥与包络元数据**:`NotebookCrypto` 保存 KDF 算法、参数、MasterSalt、verifier 格式、KEK 包络版本和备份 HMAC 版本;`BoxConf.WrappedDEK` 保存每个 box 的 DEK 包络。它们不随每个数据对象重复保存。-3. **用途隔离**:每个 box 的 DEK 通过固定域分隔符派生彼此独立的文件内容、资源内容、资源名称映射、数据库定义、content SQLCipher 和 blocktree SQLCipher 子密钥;KEK 另行派生 DEK 包络、verifier 和备份 HMAC 上下文,不得把 WrappedDEK 认证错误地归入 DEK 域。+1. **数据对象封装**:每个 `.sy`、资源、资源名称映射和数据库定义对象至少包含格式版本、算法标识、密码学安全随机生成且对同一用途密钥唯一的 nonce、密文和认证标签。当前格式的 AAD 按 `格式版本 + boxID + 对象类型 + 稳定对象 ID` 确定性构造,不包含父目录或绝对路径;`.sy` 的稳定对象 ID 是规范化文件基名 `<rootID>.sy`,资源使用脱敏磁盘文件基名,数据库定义使用 avID,固定单例文件使用版本化常量 ID。解密后必须验证对象内部 ID 与 AAD 对象 ID 一致,并拒绝同一笔记本内的重复对象 ID。AES-GCM nonce 由操作系统 CSPRNG 生成,随机源失败必须终止写入,并按标准规定限制每个用途密钥的调用规模;认证标签不能事后识别已经发生的 nonce 重用,因此不得宣称此类重用会被认证失败自动发现。+2. **全局密钥与包络元数据**:`NotebookCrypto` 保存 KDF 算法、参数、MasterSalt、verifier 格式、KEK 包络版本和备份 HMAC 版本;`BoxConf.WrappedDEK` 保存每个笔记本的 DEK 包络。它们不随每个数据对象重复保存。+3. **用途隔离**:每个笔记本的 DEK 通过固定域分隔符派生文件内容、资源、数据库定义、content SQLCipher 和 blocktree SQLCipher 子密钥。资源内容与资源名称映射可以共用资源子密钥,因为二者的版本化 AAD 对象类型不同;不要求为每一种对象再派生独立子密钥。KEK 可以直接用于 verifier、DEK 包络和备份 HMAC,这些用途由不同算法、版本化 AAD 或被认证的数据格式隔离;不得把 WrappedDEK 认证错误地归入 DEK 域。4. **数据库兼容信息**:SQLCipher 版本、cipher 参数和 schema 版本保存在数据库头部可验证位置或对应的加密配置边界,不写入每个数据对象。content 与 blocktree 索引可重建;源密文认证通过后,版本不兼容的索引应关闭并重建,而不是降低 cipher 参数或回退到明文 SQLite。5. **改名与格式稳定性**:首个发布格式直接以稳定对象 ID 构造 AAD,不兼容开发阶段按完整逻辑相对路径生成的试验密文,也不提供双格式读取或迁移;开发数据在格式切换后删除并重建。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。首个发布版本冻结后,未来再修改信封或 AAD 语义必须提升格式版本并另行设计迁移。@@ -365,6 +365,8 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副`notebook-crypto-backup.json` 是恢复材料而非秘密。文件带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC;主密码派生 KEK 后,HMAC 缺失或不匹配必须拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。+备份持久化遵循项目现有文件写入语义:全局 `notebook-crypto-backup.json` 通过同目录随机临时文件写入后原子替换,每个笔记本的 `notebook-crypt-backup.json` 使用文件锁保护的常规配置写入。两者都不额外承诺断电场景下的文件或目录 `fsync` 持久性;启动时校验无需密钥即可验证的结构和摘要,输入主密码后的恢复再校验 HMAC 以及密钥包络匹配关系。损坏或不匹配时安全拒绝,而不是生成替代密钥材料。+HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明它是最新版本。当前范围不引入可信外部单调计数器,因此一个认证有效的历史备份或历史密文可能通过校验;`BackupID` 和 `CreatedAt` 只是供诊断和人工比较的信息,不是防回滚锚点。同步、历史或恢复流程不得把“认证成功”表述为“最新”或“来源可信”;真正防回滚需要独立可信状态,超出本设计范围。同步端和离线备份被视为可丢失、可复制、可回滚但不能读取明文的存储。输入主密码前不能建立基于 KEK 的可信认证;用户应保留至少一份独立、版本化的密钥备份,并理解丢失主密码或全部匹配的 MasterSalt 备份均不可恢复。只要现存加密笔记本、已删除笔记本历史或内核可枚举的本地恢复快照仍依赖当前 NotebookCrypto,禁用功能就必须拒绝删除全局配置和备份;用户明确永久清除这些恢复数据后才可解除依赖。外部与远端副本无法可靠枚举,是否保留其匹配密钥备份由用户负责。@@ -380,15 +382,15 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明不支持的闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。错误码和本地化文案应稳定,供调用方识别。-所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。登记表同时覆盖加密 box 目录和内核管理的明文临时根目录;临时目录必须位于通用原始文件命名空间之外,或被所有原始文件 API 无条件拒绝,不能依赖当前 box 是否仍存在或 `Encrypted` 标志是否仍可查询。新增入口时必须评审其是否可读取、写入、复制、重命名、删除或列举加密目录与受控临时目录。+所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。登记表同时覆盖加密笔记本目录和内核管理的明文临时根目录;临时目录必须位于通用原始文件命名空间之外,或被所有原始文件 API 无条件拒绝,不能依赖当前笔记本是否仍存在或 `Encrypted` 标志是否仍可查询。新增入口时必须评审其是否可读取、写入、复制、重命名、删除或列举加密目录与受控临时目录。### 本机持久化的全局拒绝访问记录-“全局”表示记录在 box 已删除后仍独立于该 box 生命周期生效,不表示跨设备同步。记录持久化在 `<ConfDir>/encrypted-deny-access.json`,位于 `DataDir` 和 dejavu 同步范围之外,仅管理本机受控临时产物。每项记录至少包含格式版本、随机产物 ID、boxID、受控根目录下的规范相对路径、用途、创建时间、最近重试时间、重试次数和不含原始内容或敏感路径的错误类别;文件使用临时写入、同步落盘、原子替换和目录同步更新。记录中的路径必须重新校验为受控临时根目录的后代,越界或格式损坏的记录不得用于删除任意文件,并触发安全错误和受控根目录重新扫描。+“全局”表示记录在笔记本已删除后仍独立于该笔记本生命周期生效,不表示跨设备同步。记录持久化在 `<ConfDir>/encrypted-deny-access.json`,位于 `DataDir` 和 dejavu 同步范围之外,仅管理本机受控临时产物。每项记录至少包含格式版本、随机产物 ID、boxID、受控根目录下的规范相对路径、用途、创建时间、最近重试时间、重试次数和不含原始内容或敏感路径的错误类别;文件使用临时写入、同步落盘、原子替换和目录同步更新。记录中的路径必须重新校验为受控临时根目录的后代,越界或格式损坏的记录不得用于删除任意文件,并触发安全错误和受控根目录重新扫描。-拒绝记录只保存清理状态和诊断信息,不是访问控制依据。文件 API、下载、预览、插件、MCP、WebDAV 和后台任务按规范路径无条件拒绝整个受控明文临时命名空间,即使 box、记录文件或单项记录已经不存在。清理器在应用启动、锁定或删除、导出结束或失败后立即运行,并周期性按有上限的指数退避重试;清理成功且确认路径不存在后原子删除对应记录,持续失败则保留记录并维持 `Error` 或全局拒绝状态,不得因超过重试次数自动放行。记录文件被人为删除、部分条目丢失或文件无法解析时,访问仍保持拒绝;启动和周期扫描从受控根目录残留重建记录后继续清理。只有产物已确认不存在且记录已提交删除,才算清理完成。+拒绝记录只保存清理状态和诊断信息,不是访问控制依据。文件 API、下载、预览、插件、MCP、WebDAV 和后台任务按规范路径无条件拒绝整个受控明文临时命名空间,即使笔记本、记录文件或单项记录已经不存在。清理器在应用启动、锁定或删除、导出结束或失败后立即运行,并周期性按有上限的指数退避重试;清理成功且确认路径不存在后原子删除对应记录,持续失败则保留记录并维持 `Error` 或全局拒绝状态,不得因超过重试次数自动放行。记录文件被人为删除、部分条目丢失或文件无法解析时,访问仍保持拒绝;启动和周期扫描从受控根目录残留重建记录后继续清理。只有产物已确认不存在且记录已提交删除,才算清理完成。-导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物只能位于带 boxID 的受控临时目录,并通过绑定用户、boxID、用途和有效期的最小权限令牌访问。锁定、取消、失败、应用退出和导出完成后都必须使令牌与异步结果立即失效,再尽力清理内核管理的明文;清理失败时,box 仍存在则进入 `Error`,box 已删除则保留全局拒绝访问标记,并由后台清理器重试,不能因 box 已删除或锁定而让通用文件入口重新暴露该路径。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。+导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物只能位于带 boxID 的受控临时目录,并通过绑定用户、boxID、用途和有效期的最小权限令牌访问。锁定、取消、失败、应用退出和导出完成后都必须使令牌与异步结果立即失效,再尽力清理内核管理的明文;清理失败时,笔记本仍存在则进入 `Error`,笔记本已删除则保留全局拒绝访问标记,并由后台清理器重试,不能因笔记本已删除或锁定而让通用文件入口重新暴露该路径。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。## 21. 安全验收矩阵@@ -397,8 +399,8 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问 | 除明确允许暴露的笔记本名称外,不能读取、写入、复制、删除或列举加密内容;错误不返回明文、密文或可推断文档标题的信息 || 解锁、锁定、应用重启和认证失败 | 只有 `Unlocked` 才能取得受管 DEK 句柄和数据库连接;失败和重启后入口拒绝访问,内核可控的明文缓存、临时文件与句柄完成尽力清理 || 锁定与响应生成、缓存发布、导出、预览、同步、索引或历史恢复并发 | 锁定在所有在途生命周期租约结束后才成功;成功后无晚到的明文响应、缓存回填、临时文件、可用令牌或数据库重连 |-| 同一加密 box 内移动文档,随后清空缓存并重启 | 文件基名不变时密文保持不变并可按稳定对象 ID 认证解密;新父目录按普通笔记本语义生效,旧目录位置不存在,失败处理与普通笔记本一致 |-| 加密 box 与普通 box、两个加密 box 之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 |+| 同一加密笔记本内移动文档,随后清空缓存并重启 | 文件基名不变时密文保持不变并可按稳定对象 ID 认证解密;新父目录按普通笔记本语义生效,旧目录位置不存在,失败处理与普通笔记本一致 |+| 加密笔记本与普通笔记本、两个加密笔记本之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 || 资源密文写入与名称映射更新任一步失败 | 整个逻辑事务失败并回滚;调用方收到错误,不留下可访问的孤儿资源、缺失映射或明文临时文件 || 删除加密笔记本后保留历史,再尝试禁用或恢复 | 存在密钥依赖时拒绝删除全局配置和备份;使用匹配备份与主密码可恢复,只有明确永久清除恢复数据后才允许解除依赖 || 文档生成历史后移动父目录或改变文件基名,再查看或回滚旧历史 | 使用历史条目记录的快照 boxID、对象类型和稳定文件基名认证解密;仅在目标基名变化时重新封装,缺失快照上下文时拒绝操作 |@@ -408,7 +410,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明| nonce 随机源失败、达到用途密钥调用限制或事后发现 nonce 重用 | 随机源失败或达到限制时在加密前拒绝写入;AES-GCM 认证本身不能发现已发生的 nonce 重用,发现后必须按密钥泄露事件处理并轮换 DEK 后重新加密 || 回放认证有效的历史密文或密钥备份 | 可能被识别为有效旧版本,但不得被宣称为最新或来源可信;数据回退风险明确,当前设计不声称提供回滚防护 || 改主密码和 KEK 重新包络 | WrappedDEK 与备份原子更新;更新中断后旧配置仍可恢复使用;旧密码暴露风险提示正确;迁移前后数据与历史均可验证读取 |-| 多个 box 并发操作与自动锁定 | 锁顺序无死锁;一个 box 的全局界面活动或内容访问不刷新另一个 box 的计时,锁定中的 box 不再接受新租约 |+| 多个笔记本并发操作与自动锁定 | 锁顺序无死锁;认证用户界面活动或显式保活统一刷新所有当前已解锁笔记本,后台任务不自动刷新;锁定中的笔记本不再接受新租约 |## 22. 使用指南@@ -427,7 +429,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,已认证的应用内调用方(API、插件、AI/LLM 含 MCP)都能像读普通笔记本一样读到明文;内核 CLI 始终拒绝操作加密笔记本(详见 §12 安全前提)。### 修改主密码-进入 **设置 → 访问授权 → 修改主密码**。改密只需重新包络各 box 的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。+进入 **设置 → 访问授权 → 修改主密码**。改密只需重新包络各笔记本的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。> 重要语义:改密采用 KEK 包络模式——DEK 本身不变,只是用新主密码派生的新 KEK 重新包络 WrappedDEK。这意味着**改密不能吊销旧主密码的解密能力**:如果旧主密码和旧 WrappedDEK(如同步端、备份、历史快照中保留的)同时泄露,仍能解出同一个 DEK,进而解当前数据。如果怀疑旧主密码已泄露,应迁移内容到新建的加密笔记本(新 DEK)而非仅改密。