Skip to content

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

:memo: Improve encrypted notebook design https://github.com/siyuan-note/siyuan/issues/18034

Danielf02b3d637781
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index 1e62eb3126..909eeb0a6f 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -17,15 +17,15 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d
| **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) |
-| AI / LLM | No functional-layer isolation — when unlocked, AI/LLM can read/search just like a normal notebook; when locked, physically unreachable without DEK (see §13) |
+| 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 |
| 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 |
+| Enable / Disable | Enabling requires setting a master password; disabling requires no live encrypted notebook and no kernel-enumerable history or recovery snapshot that depends on the current key backup, unless those recovery artifacts are explicitly purged permanently |
+| Restart behavior | All encrypted notebooks force-closed on startup (managed DEK handles exist only in process memory and must be derived again after restart); user must re-unlock |
| Existing notebooks | Completely untouched, zero migration |
## 3. Encrypted Notebook vs Normal Notebook
@@ -33,8 +33,8 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d
| 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 SQLite database deleted + all plaintext caches cleared) |
+| **Open (Mount)** | Direct open | Must first enter master password to unlock (~1s Argon2id each time); the application obtains a managed DEK handle |
+| **Close (Unmount)** | Closing makes it invisible | Close = lock (stop new access + wait for or cancel in-flight work + remove DEK from the managed key cache + delete encrypted SQLite databases + best-effort cleanup of kernel-managed plaintext caches and temporary files) |
| **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 |
@@ -53,8 +53,8 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d
| **Backlinks panel** | Via global SQLite database | Via encrypted SQLite database (incl. mention subquery) |
| **Open doc / outline / breadcrumb / block info / float preview** | Via global SQLite database | Via encrypted SQLite database |
| **Database** | Via global storage + global SQLite database | Via notebook-level storage (DEK-encrypted) + encrypted SQLite database |
-| **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) |
+| **File history** | Supported | Supported (ciphertext .sy copied verbatim to history dir; each history entry retains the boxID, object type, and stable file basename at snapshot creation, and viewing or rollback uses all three as the AAD context) |
+| **Deleted notebook history** | Supported | Supported (entire directory backed up as ciphertext before deletion and restored verbatim; recovery also requires the matching global key backup and master password) |
| **Embedding vectorization / semantic search** | Participates | Does not participate (encrypted data never enters the global block_embeddings table; the embedding pipeline reads only the global SQLite database — independent of lock state) |
| **Agents / AI chat / MCP** | Can read content, can search | Available when unlocked (can read blocks, list docs, search within notebook); unreachable when locked (see §13). Global search / semantic search not included |
| **Kernel CLI** | Can operate on workspace data | Does not support encrypted notebooks or their files, whether locked or unlocked |
@@ -66,7 +66,7 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d
| **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); legitimate reads/writes go through dedicated APIs (encryption-aware) |
+| **/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) |
**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.
@@ -92,7 +92,7 @@ User master password
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.
-**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, and deleted on disable. Stored as plaintext JSON (salt is not secret, verifier is ciphertext — identical to how they are stored in `conf/conf.json`).
+**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`).
**Recovery triggers** (covering scenarios such as conf.json loss, sync to a new device, importing Data.zip):
@@ -114,7 +114,7 @@ MasterSalt is the global root of KEK derivation — the master password + Master
Import 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`), `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. This guard mirrors `DisableEncryptedNotebook`'s "cannot disable while encrypted notebooks exist".
+**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.
**Prerequisite**: `restoreNotebookCryptoConfigFromBackup` only takes effect when the local `Enabled=false`; it never overwrites an in-use local config.
@@ -129,6 +129,7 @@ Import guard: when the local machine is already enabled, import is rejected (to
│ │ └── notebook-crypto-backup.json ← NotebookCrypto backup (MasterSalt/KEKVerifier, synced; see §4.1)
│ ├── <boxID>/ ← encrypted notebook directory
│ │ ├── .siyuan/conf.json ← BoxConf (Encrypted=true + WrappedDEK)
+│ │ ├── .siyuan/hierarchy.enc ← encrypted and authenticated document-object-ID → parent-object-ID hierarchy manifest
│ │ ├── *.sy ← AES-256-GCM ciphertext
│ │ ├── assets/
│ │ │ ├── <uuid>-<blockID>.ext ← AES-256-GCM ciphertext, filename desensitized
@@ -171,6 +172,8 @@ Encrypted-notebook operations (dedicated read path, with boxID):
- `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-child topology is authenticated by `.siyuan/hierarchy.enc`, not by content-ciphertext AAD. Notebook open, full reindex, and post-sync application compare the physical directory relation with the manifest; a missing entry, duplicate object ID, or parent mismatch enters `Error` and is never repaired automatically from unauthenticated directory structure
**assets encryption**:
- On upload, fully read into memory + encrypt + write (cannot stream-encrypt)
@@ -178,6 +181,7 @@ Encrypted-notebook operations (dedicated read path, with boxID):
- 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)
+- 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/`
@@ -193,19 +197,22 @@ File history:
edit triggers history generation → ciphertext .sy copied verbatim to history dir
auto-generated before close/exit → ensures history is captured even after locking
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
+ view history → read the snapshot boxID, object type, and stable file basename, then reconstruct the original AAD for decryption (notebook must be unlocked)
+ roll back → decrypt with the snapshot AAD → verify that the root-block ID matches the basename → load tree → restore ciphertext verbatim when the basename is unchanged, or let WriteTree re-envelope it when the basename changes
Deleted-notebook history:
before deletion → entire directory backed up as ciphertext to history dir
- restore → ciphertext directory copied back verbatim
+ restore → verify WrappedDEK with the matching global key backup and master password, then copy the ciphertext directory back verbatim
+ key retention → while kernel-managed history remains recoverable, deletion of the global key backup it depends on is forbidden; permanently purging the history removes the dependency
database history:
generate → encrypted-box database files copied from notebook-level dir to history dir
- view → decrypt by path boxID
+ view → 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
```
+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 commits the target parent relation to the hierarchy manifest as one transaction. Re-enveloping is required only when the target basename changes. Missing, malformed, or mismatched snapshot context rejects viewing and rollback; the implementation must not guess from the current parent path, parse ciphertext as plaintext, or restore while bypassing the hierarchy manifest.
+
## 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:
@@ -220,6 +227,8 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma
**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.
+**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 may Rename ciphertext verbatim without re-enveloping the root or descendants, but directory topology is not unauthenticated state: the filesystem Rename and update of parent-object relations in `.siyuan/hierarchy.enc` form one journaled recoverable transaction. Before commit, the operation verifies unique object IDs, basename-to-decrypted-root-ID equality, an acyclic target relation, and agreement between the target layout and new manifest. It syncs the Rename and manifest before updating indexes and clearing the journal, and does not open the notebook before crash recovery completes. Only a basename change verifies and decrypts with the old basename and re-envelopes with the new one. Failure must not leave the directory structure, hierarchy manifest, and indexes inconsistent.
+
**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**: 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).
@@ -229,26 +238,27 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma
| 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 |
+| Disable | Supported only when no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on the current key backup; otherwise reject, or require explicit permanent purge of those recovery artifacts before deleting global config and backup |
| Create | File panel "more" menu → "New encrypted notebook" → enter name + master password → auto-unlock and open |
| 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 + encrypted SQLite database deleted + all plaintext caches cleared). Unsaved edits and file history are automatically saved before locking |
+| 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 |
| 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 |
+| Move document | A parent-only move within an encrypted box moves ciphertext verbatim and transactionally updates the encrypted hierarchy manifest; a basename change re-envelopes content. Moves between normal boxes 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 |
| 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) |
+| Deleted notebook | Supported (ciphertext backup; recovery requires the matching global key backup and master password; retaining this history prevents direct deletion of its key backup) |
| 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 SQLite database has been deleted, all plaintext caches have been cleared, and only ciphertext remains on disk — no path (including authenticated APIs, plugins, AI/LLM, MCP) can read plaintext. **When open (unlocked), the DEK is in memory**, and at that point authenticated application callers — APIs, third-party plugins, AI/LLM (including MCP, agents, semantic search) — can read plaintext content just like a normal notebook. The kernel CLI is an explicit exception: it rejects encrypted notebooks and their raw files regardless of lock state. Encryption protects "data at rest" and "unreachability when locked"; it **does not protect "visibility to authenticated callers while unlocked"**. Therefore: while unlocked, treat it as "a normal notebook in use"; the only protection is **locking after use**.
+**Security premise**: An encrypted notebook provides its strongest application-level protection while closed (locked). After locking completes, new operations are denied, managed DEK handles and database connections are removed, and kernel-managed plaintext caches, temporary files, and tokens are cleaned on a best-effort basis; this does not promise erasure of every transient copy in the Go runtime, OS swap, crash dumps, or storage media. **When open (unlocked), the application holds a usable DEK handle**, and authenticated application callers — APIs, third-party plugins, AI/LLM (including MCP, agents, semantic search) — can read plaintext content just like a normal notebook. The kernel CLI is an explicit exception: it rejects encrypted notebooks and their raw files regardless of lock state. Encryption protects data at rest and unreachability through supported entry points after locking; it **does not protect visibility to authenticated callers while unlocked**. Treat an unlocked encrypted notebook as a normal notebook in active use and lock it immediately afterwards.
**Protected (ciphertext on disk)**:
- `.sy` document body (encrypted)
@@ -262,7 +272,7 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma
**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)
+- 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.
@@ -274,11 +284,11 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma
The visibility of encrypted notebooks to AI/LLM is determined entirely by the **lock state**; there is no functional-layer isolation.
-**When locked**: the DEK is not in memory, so AI/LLM (including MCP, agents, semantic search, embedding vectorization) cannot read any encrypted content — the data lives in an independent encrypted SQLite database and is ciphertext on disk, unreadable without the key.
+**When locked**: AI/LLM (including MCP, agents, semantic search, embedding vectorization) cannot obtain a usable DEK handle, and every encrypted-notebook entry point denies access. Dedicated databases are closed and disk content is ciphertext, so these callers cannot read encrypted content.
**When unlocked**: the DEK is in memory, so AI/LLM can read encrypted-notebook content and search within a notebook — MCP tools can list encrypted notebooks and their documents, read block content, run in-notebook FTS search, etc. However, global search, semantic search, and embedding vectorization still do not include encrypted content (encrypted data never enters the global `block_embeddings`/`blocks` tables; physically unreachable), see §3 comparison table.
-Design stance: there is no "hide from AI" isolation at the functional layer, because such isolation is neither thorough nor easy to reason about. **The only reliable protection is locking** — once locked, the data is physically unreachable to any caller. Users only need to understand one rule: **lock sensitive content after use**.
+Design stance: there is no "hide from AI" isolation at the functional layer, because such isolation is neither thorough nor easy to reason about. Supported entry points cannot access content after locking, but locking does not replace process- and OS-level protection. Users only need to understand one rule: **lock sensitive content after use**.
## 14. Feature Limitations
@@ -304,16 +314,16 @@ An encrypted notebook is an island; some features are unimplemented because of t
| **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 |
-| **When locked** | No extra overhead | All caches cleared | Cold-start latency on next operation |
+| **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.
-## 17. Threat Model and Security Scope
+## 16. Threat Model and Security Scope
-This feature protects data-at-rest confidentiality and the inaccessibility of a locked notebook. The design assumes an attacker may obtain current or historical ciphertext from the workspace, sync service, or backup media, but does not know the master password and cannot control the running application or operating system while the user has unlocked a notebook. AES-GCM provides confidentiality and integrity verification for an individual encrypted object; it does not by itself provide availability, rollback protection, or deletion of retained ciphertext copies.
+This feature protects data-at-rest confidentiality and inaccessibility through supported entry points after a notebook is locked. The design assumes an attacker may obtain current or historical ciphertext from the workspace, sync service, or backup media, but does not know the master password and cannot control the running application or operating system while the user has unlocked a notebook. AES-GCM provides confidentiality, integrity, and origin-context authentication for an individual encrypted object; it does not provide availability, version freshness, rollback protection, or deletion of retained ciphertext copies.
The following are outside this feature's security boundary and must be stated in product UI and user documentation:
@@ -322,34 +332,43 @@ The following are outside this feature's security boundary and must be stated in
- OS swap, hibernation images, crash dumps, filesystem snapshots, and malware are not absolutely protected by clearing application memory; locking performs best-effort cleanup only within the application's control.
- A sync service or backup holder may retain, delete, replace, or roll back ciphertext. Replacement and rollback can cause denial of service or data rollback; they cannot decrypt valid ciphertext without the master password.
-"Only ciphertext remains after locking" applies only to kernel-managed workspace files, temporary files, and caches. It does not include files deliberately exported to an external location or promise erasure of historical blocks retained by the underlying storage medium.
+"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.
-## 18. State Machine and Concurrency Rules
+## 17. State Machine and Concurrency Rules
-Each encrypted notebook independently has one of these states: `Locked`, `Unlocking`, `Unlocked`, `Locking`, and `Error`. Every encrypted notebook must start as `Locked`; encrypted notebooks must not exist while the global encryption feature is disabled.
+The global state is `Disabled`, `Enabled`, or `RecoveryRequired`. In normal steady state, `Disabled` has no live encrypted notebook or kernel-enumerable key dependency. If startup discovers encrypted notebooks or recovery artifacts while global configuration is missing or disabled, it enters `RecoveryRequired`, never treats them as normal notebooks, and waits for a matching key backup to be restored. Under `Enabled`, each encrypted notebook independently has one of these states: `Locked`, `Unlocking`, `Unlocked`, `Locking`, or `Error`, and starts as `Locked` after application startup.
| Transition | Preconditions | Invariants after success | Failure handling |
|---|---|---|---|
-| `Locked → Unlocking → Unlocked` | Master password verification succeeds | DEK exists only in memory; dedicated databases are open; notebook-specific entry points are allowed | Clear derived KEK/DEK, close opened handles, return to `Locked` |
-| `Unlocked → Locking → Locked` | Stop accepting new requests for the notebook | Tasks have completed or been cancelled; caches, plaintext temporary files, database connections, and DEK are cleared | Continue to deny access if cleanup partly fails; record the error and retry before the next startup |
+| `Locked → Unlocking → Unlocked` | Master-password verification succeeds and ciphertext configuration matches | A usable DEK handle exists only in managed memory; dedicated databases are open; notebook-specific entry points are allowed | Revoke derived KEK/DEK handles, close opened resources, and return to `Locked` |
+| `Unlocked → Locking → Locked` | Atomically close admission to new operations and wait for or cancel in-flight operations | No usable managed DEK handle or database connection remains; kernel-managed plaintext caches, temporary files, and tokens have undergone best-effort cleanup | Continue to deny access and enter `Error`; record diagnostics without plaintext and retry cleanup without reopening until invariants are restored |
| `Unlocked → Error` | Ciphertext authentication fails, database opening fails, or an invariant is violated | Immediately deny reads and writes; never fall back to a normal-notebook path | Close resources and retain diagnostics without plaintext; the user can only lock or unlock again |
-| Change master password | All encrypted notebooks are `Locked` | All WrappedDEKs and the backup update as one transaction | Keep old configuration and backup usable; no notebook becomes unlockable only by the new password |
+| 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.
-Unlock, lock, export, sync, indexing, history restore, and deletion of the same notebook must be serialized by one boxID-scoped mutex. Once locking starts, running tasks must be cancelled or finish at a safe boundary; they must not create plaintext temporary files, publish plaintext results, or reopen database connections after locking completes.
+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.
-## 19. Ciphertext, Key, and Database Format
+## 18. Ciphertext, Key, and Database Format
-Every persistent encrypted object must use a versioned envelope containing at least a format version, algorithm identifier, cryptographically random nonce unique for the same DEK, ciphertext, and authentication tag. Additional authenticated data binds boxID, object type, and logical relative path, preventing valid ciphertext from being substituted into another notebook, type, or path. Rename or migration creates a new envelope rather than merely moving ciphertext.
+Persistent formats are layered; global KDF configuration, key envelopes, and per-object data envelopes are not conflated:
-The implementation derives purpose-separated subkeys from each box's DEK through a KDF with fixed domain separators, at least for file content, asset-name mappings, database files, and the WrappedDEK authentication context. KDF parameters, envelope version, and database configuration are stored with ciphertext to enable migration; a new version is written only after old data verifies successfully, and a failed migration must not delete the old copy.
+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.
+4. **Hierarchy integrity**: `.siyuan/hierarchy.enc` uses an independent purpose subkey and fixed AAD to map every document stable object ID to its parent object ID. The filesystem directory structure is only a physical projection of the manifest, not trusted input. Creation, move, deletion, and history rollback use a transaction journal to update files and the manifest atomically. An authenticated historical manifest can still be replayed, consistent with this design's explicit lack of rollback prevention.
+5. **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.
+6. **Migration and rename**: A legacy envelope bound to the full logical relative path is first authenticated and decrypted with that old path, then transactionally migrated to the stable-object-ID format. Migration validates every object and the current directory relation before creating the initial hierarchy manifest, and retains old copies until every new envelope and the manifest are verified and synced. In the new format, a parent-only move does not re-envelope content; it transactionally updates the directory projection and hierarchy manifest. A stable-basename or format-version change creates a new envelope. Access remains closed until crash recovery completes, and failure neither deletes old data nor publishes partial indexes.
-The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and backup copies are protected objects. They must remain in controlled directories and use the same key domain. Locking, crash recovery, and history snapshots enumerate these companion files; unencrypted SQLite pages, query results, or diagnostics must never be written to a global temporary directory.
+The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and backup copies are protected objects. They remain in controlled directories and use their corresponding purpose key. Locking, crash recovery, and history snapshots enumerate these companion files; unencrypted SQLite pages, query results, or diagnostics must never be written to a global temporary directory.
-## 20. Backup, Recovery, and Metadata Policy
+## 19. Backup, Recovery, and Metadata Policy
-`notebook-crypto-backup.json` is recovery material, not a secret, but its integrity and freshness must be handled separately. It contains a format version, backup ID, creation time, content digest, and KEK-based HMAC. The current format requires the HMAC: after the master password derives the KEK, a missing or mismatched HMAC rejects recovery instead of being treated 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.
+`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.
-Sync endpoints and offline backups are storage that may be lost, copied, or rolled back but cannot read plaintext. Before the master password is entered, trustworthy authentication based on the KEK cannot be established; the system can validate structure and the verifier after unlock only. A successful sync restore must not be presented as proof that the source is trusted. Users should keep at least one independent, versioned key backup and understand that losing the master password or every matching MasterSalt backup is unrecoverable.
+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.
| Category | May be exposed |
|---|---|
@@ -358,27 +377,42 @@ Sync endpoints and offline backups are storage that may be lost, copied, or roll
| Notebook name | Yes. The notebook list and encrypted-notebook status API retain the name while locked so users can identify the notebook they intend to unlock; the name is therefore outside the confidentiality boundary |
| Icon, sorting, document title/count, relation count, tags, bookmarks, history and snapshot names | Must not be exposed while locked by default; if compatibility requires exposure, list each field here and explain it in the UI |
-## 21. Feature Boundaries, Plaintext Temporaries, and Interface Rules
+## 20. Feature Boundaries, Plaintext Temporaries, and Interface Rules
Unsupported flashcards, bookmarks, tags, asset rename, unused-asset cleanup, and unused-database cleanup must be handled uniformly by the frontend, HTTP API, plugin API, MCP, and import paths: return an explicit "unsupported" error for encrypted-notebook targets and create no global index, global attribute, or deferred task. Existing legacy data must not be loaded, aggregated, or written back. Error codes and localized messages remain stable for callers.
-Every raw entry point that might bypass dedicated read/write paths must be registered and reject encrypted-notebook directories, including file APIs, kernel CLI, MCP file tools, WebDAV, plugin file interfaces, export download URLs, preview URLs, and background tasks. Adding an entry point requires review of whether it can read, write, copy, rename, delete, or enumerate an encrypted directory.
+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.
+
+### Locally Persistent Global Deny-Access Records
-Exports have two classes: a user-selected external destination may contain plaintext after a risk prompt; kernel-managed previews, conversions, downloads, and intermediates may exist only in a boxID-scoped controlled temporary directory and be served with minimum privilege. Locking, cancellation, failure, application exit, and export completion must clean up kernel-managed plaintext; after locking, prior download URLs, preview URLs, and asynchronous results become invalid. Logs, error reports, thumbnails, OCR/conversion output, and clipboard handling follow the same rule: do not contain plaintext by default unless the user explicitly sends content to an external program.
+“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.
-## 22. Security Acceptance Matrix
+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.
+
+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.
+
+## 21. Security Acceptance Matrix
| Scenario | Expected result |
|---|---|
| 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 | DEK and database connections exist only in `Unlocked`; no plaintext cache or usable handle remains after failure or restart |
-| Lock concurrent with export, preview, sync, indexing, or history restore | No plaintext task continues after lock; controlled temporary files and access tokens are removed or invalidated |
+| 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 hierarchy manifest agrees with the directory relation, the old directory location is absent, and failure leaves no partial file, manifest, or index |
+| Manually move a valid `.sy` with an unchanged basename to another parent directory without updating the hierarchy manifest | Notebook open, post-sync validation, or full reindex detects disagreement with the authenticated manifest and enters `Error`; it neither loads the new topology nor rewrites the manifest automatically |
| Refs, moves, mirrors, assets, and database operations between an encrypted box and a normal box or another encrypted box | Island boundaries hold; rejection creates no partial files, global indexes, or relation data |
-| Disk inspection of files, assets, databases, WAL/SHM, history, snapshots, logs, and temporary directories | No readable body, asset contents, original asset names, or plaintext SQLite pages in kernel-managed locations |
-| Ciphertext tampering, path substitution, nonce reuse, and backup corruption | Authentication or format validation fails safely; never fall back to a normal path, generate replacement key material, or silently overwrite configuration |
-| Master-password change and KEK rewrapping | WrappedDEKs and backup update atomically; an interrupted update remains pending until the new password authenticates the backup; the old-password exposure warning is accurate; data and history are verifiably readable before and after migration |
-
-## 16. Usage Guide
+| 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 transactionally updates the hierarchy manifest and re-envelopes only when the target basename changes, while missing snapshot context rejects the operation |
+| Disk inspection of files, assets, databases, WAL/SHM, history, snapshots, logs, and temporary directories | No readable body, asset contents, original asset names, or plaintext SQLite pages exist in kernel-managed locations; temporary paths whose cleanup failed remain denied to every entry point |
+| Delete or corrupt the global deny-access registry after cleanup failure, then restart and access the residual path | The controlled-plaintext temporary namespace remains unconditionally denied; scanning reconstructs records and resumes cleanup, and missing or malformed records never fail open |
+| Ciphertext tampering, path substitution, and backup corruption | Authentication or format validation fails safely; never fall back to a normal path, generate replacement key material, or silently overwrite configuration |
+| 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 |
+
+## 22. Usage Guide
### First-time enablement
1. Go to **Settings → Access authorization → Encrypted notebooks** and toggle it on
@@ -389,10 +423,10 @@ Exports have two classes: a user-selected external destination may contain plain
### Daily use: unlock and lock
- **Unlock**: Click a closed encrypted notebook → enter the master password → wait ~1 second (Argon2id derivation) → opens. Unlocking only affects that notebook; other encrypted notebooks stay locked
-- **Lock**: Closing the notebook equals locking (DEK cleared + encrypted SQLite database deleted + plaintext caches cleared). **Locking after use** is the most important security habit — it minimizes the key's exposure time in memory
-- **After restart**: All encrypted notebooks are force-closed; you must re-enter the master password to unlock (the DEK lives only in memory and is lost on restart)
+- **Lock**: Closing the notebook equals locking. The kernel stops new access, waits for or cancels in-flight work, revokes managed DEK handles and database connections, and best-effort cleans kernel-managed plaintext caches, temporary files, and tokens. **Locking after use** is the most important security habit because it minimizes key and plaintext exposure
+- **After restart**: All encrypted notebooks are force-closed; you must re-enter the master password to unlock (managed DEK handles exist only in process memory and must be derived again after restart)
-> Important: An encrypted notebook is **only fully secure when locked**. 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).
+> 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.
@@ -408,6 +442,8 @@ Encrypted-notebook ciphertext `.sy`/assets/database files sync along with the da
If the notebook still shows as locked on the new device after sync, that is normal — click it and enter the master password.
+Sync recovery can validate backup integrity but cannot prove that a backup is the newest version. Keep an independently versioned key backup. When historical copies conflict, the system cannot determine freshness automatically; before recovery, the user confirms a version from trusted source and time information.
+
### Import and export
- **Import**: Supports importing `.sy.zip` and Markdown; content is automatically DEK-encrypted before writing to disk, identical to manually created documents
- **Export**: Identical to normal notebooks (must unlock first; exports plaintext). `.sy.zip`, HTML, Word, PDF, Markdown, etc. are all supported; export is rejected while locked
@@ -418,6 +454,8 @@ If the notebook still shows as locked on the new device after sync, that is norm
### Recovering from a lost key backup
If both `conf/conf.json` and the key backup in the sync directory are lost (an extreme case), re-enabling the encrypted-notebook feature will be rejected with a prompt to restore the backup file. As long as you can recover `notebook-crypto-backup.json` from another synced device or a previously exported key file, you can import it via the "Import key" button (shown when not enabled), or manually put it back at `<workspace>/data/.siyuan/` and re-enable, then unlock with the master password matching that key.
+Restoring deleted encrypted-notebook history also requires the global key backup matching its WrappedDEK and the master password. While you still need that local recovery path, do not permanently purge either the history or its matching key backup; disabling must refuse to proceed when it discovers such a dependency.
+
### Suitable scenarios for encrypted notebooks
- Private diary, financial records, medical information
- Work secrets, business plans, contracts
@@ -439,4 +477,4 @@ If both `conf/conf.json` and the key backup in the sync directory are lost (an e
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 too
+5. **Backup**: Keep versioned ciphertext backups and their matching key backups separately; losing the master password or every matching key backup makes the ciphertext unrecoverable
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index fbfd2642c4..ac772dca72 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -17,15 +17,15 @@
| **隔离原则** | **每个加密笔记本是一个独立孤岛——与普通笔记本隔离,加密笔记本之间也互相隔离。数据、块引、数据库镜像、移动都不跨加密笔记本边界。解锁一个加密笔记本不影响其他加密笔记本的锁定状态。** |
| 全局功能 | 加密笔记本完全不参与(全局搜索/关系图/块引都看不到它) |
| 块引 | box 内部正常引用;禁止跨加密边界引用(双向:普通↔加密、加密 A↔加密 B) |
-| AI / LLM | 不做功能层隔离——解锁后与普通笔记本一样可读可搜;锁定后因无 DEK 物理上不可达(详见 §13) |
+| AI / LLM | 不做功能层隔离——解锁后与普通笔记本一样可读可搜;锁定后无可用 DEK 句柄且专用入口拒绝访问(详见 §13) |
| 跨边界移动 | 禁止——会破坏数据一致性且泄漏 |
| 数据库 | 笔记本级存储——加密 box 的 数据库文件跟随 box 目录,DEK 加密;禁止跨边界镜像 |
| 闪卡 / 间隔重复 | 不支持(功能限制) |
| 书签 | 不支持(功能限制) |
| 标签 | 不支持(功能限制) |
| 导入 | 支持——导入的 .sy.zip 和 Markdown 在落盘前用 DEK 加密,与手动创建的文档一致 |
-| 启用/禁用 | 启用需设主密码;禁用需确认无加密笔记本存在 |
-| 重启行为 | 启动时强制关闭所有加密笔记本(DEK 仅内存,重启后丢失),用户需重新解锁 |
+| 启用/禁用 | 启用需设主密码;禁用需确认无现存加密笔记本,且无依赖当前密钥备份的内核可枚举历史或恢复快照;否则必须先明确永久清除这些恢复数据 |
+| 重启行为 | 启动时强制关闭所有加密笔记本(受管 DEK 句柄仅存在于进程内存,重启后需重新派生),用户需重新解锁 |
| 已有笔记本 | 完全不动,零迁移 |
## 3. 加密笔记本 vs 普通笔记本
@@ -33,8 +33,8 @@
| 维度 | 普通笔记本 | 加密笔记本 |
|---|---|---|
| **创建** | 随时创建,无限制 | 需先启用加密功能(设主密码),创建时需验证主密码 |
-| **打开(Mount)** | 直接打开 | 需先输主密码解锁(每次 ~1 秒 Argon2id),DEK 进内存 |
-| **关闭(Unmount)** | 关闭即不可见 | 关闭 = 锁定(DEK 清除 + 加密 SQLite 数据库 删除 + 所有明文缓存清空) |
+| **打开(Mount)** | 直接打开 | 需先输主密码解锁(每次 ~1 秒 Argon2id),应用取得受管 DEK 句柄 |
+| **关闭(Unmount)** | 关闭即不可见 | 关闭 = 锁定(停止新访问 + 等待或取消在途任务 + 从受管密钥缓存移除 DEK + 删除加密 SQLite 数据库 + 尽力清理内核管理的明文缓存和临时文件) |
| **重启后** | 保持上次打开状态 | 强制关闭,需重新输主密码解锁 |
| **.sy 文件** | 明文 JSON 落盘 | AES-256-GCM 密文落盘,读时透明解密 |
| **assets 文件** | 明文二进制,原始文件名 | AES-256-GCM 密文,文件名脱敏,原始名加密存储 |
@@ -53,8 +53,8 @@
| **反链面板** | 走全局 SQLite 数据库 | 走加密 SQLite 数据库(含 mention 子查询) |
| **打开文档 / 大纲 / 面包屑 / 块信息 / 悬浮预览** | 走全局 SQLite 数据库 | 走加密 SQLite 数据库 |
| **数据库** | 走全局存储 + 全局 SQLite 数据库 | 走笔记本级存储(DEK 加密)+ 加密 SQLite 数据库 |
-| **文件历史** | 支持 | 支持(密文 .sy 原样存历史目录,查看/回滚时按路径 boxID 解密) |
-| **已删除笔记本历史** | 支持 | 支持(删除前整个目录密文备份,恢复时原样拷回) |
+| **文件历史** | 支持 | 支持(密文 .sy 原样存历史目录;历史条目保留快照写入时的 boxID、对象类型和稳定文件基名,查看/回滚以三者作为 AAD 上下文解密) |
+| **已删除笔记本历史** | 支持 | 支持(删除前整个目录密文备份,恢复时原样拷回;恢复还需要匹配的全局密钥备份和主密码) |
| **嵌入向量化 / 语义搜索** | 参与 | 不参与(加密数据不进全局 block_embeddings 表,嵌入流水线只读全局库;与解锁状态无关) |
| **智能体 / AI 对话 / MCP** | 可读内容、可搜索 | 解锁后可用(可读块内容、列文档、笔记本内搜索);锁定后不可达(详见 §13)。全局搜索/语义搜索不参与 |
| **内核 CLI** | 可操作工作区数据 | 无论锁定或解锁,均不支持加密笔记本及其文件 |
@@ -66,7 +66,7 @@
| **数据同步** | dejavu 同步明文 | 不改(密文进密文出,闭环自洽) |
| **删除笔记本** | 删目录 | 删目录 + 删加密 SQLite 数据库 文件 + 删笔记本级数据库存储 |
| **重建索引** | 全量 | 启动时跳过(已关闭);打开时 box.Index() 全量重建到加密 SQLite 数据库 |
-| **/api/file/getFile + putFile** | 可读写任意文件 | 拒绝读写加密 box 下的任何文件(不只 .sy),防止密文泄漏或明文破坏;合法读写走专用 API |
+| **/api/file/getFile + putFile** | 可读写任意文件 | 拒绝读写加密 box 下的任何文件(不只 .sy)以及内核管理的加密笔记本明文临时目录,防止密文泄漏或明文破坏;合法读写走专用 API |
**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、文档和 数据库文件不进出边界。box 内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 也可用(与普通笔记本一致)。加密笔记本之间也互相隔离。普通笔记本完全不受影响。
@@ -92,7 +92,7 @@
MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各 box 的 WrappedDEK。**MasterSalt 丢失等于数据永久锁死**:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。
-**备份**:`<DataDir>/.siyuan/notebook-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;禁用时删除。备份文件按明文 JSON 存储(salt 不保密、verifier 是密文,与 `conf/conf.json` 的存储方式一致)。
+**备份**:`<DataDir>/.siyuan/notebook-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储(salt 不保密、verifier 是密文,与 `conf/conf.json` 的存储方式一致)。
**恢复触发点**(覆盖 conf.json 丢失 / 同步到新设备 / 导入 Data.zip 等场景):
@@ -114,7 +114,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
导入防呆:本机已启用时拒绝导入(避免覆盖现有 salt 孤立 WrappedDEK),导入入口仅在未启用时露出。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出/导入不涉及明文数据泄漏,解锁仍需主密码。
-**防呆守卫**:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的 box)时,**禁止重新生成 MasterSalt**(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。此守卫与 `DisableEncryptedNotebook` 的"有加密笔记本时禁止禁用"对称。
+**防呆守卫**:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的 box)或内核可枚举的加密恢复数据时,**禁止重新生成 MasterSalt**(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。`DisableEncryptedNotebook` 对称地扫描现存笔记本、已删除笔记本历史和本地恢复快照;存在依赖时必须拒绝禁用,除非用户明确选择永久清除这些恢复数据。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。
**前提条件**:`restoreNotebookCryptoConfigFromBackup` 仅在本机 `Enabled=false` 时生效,不覆盖正在使用的本机配置。
@@ -129,6 +129,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
│ │ └── notebook-crypto-backup.json ← NotebookCrypto 备份(MasterSalt/KEKVerifier,进同步范围,详见 §4.1)
│ ├── <boxID>/ ← 加密笔记本目录
│ │ ├── .siyuan/conf.json ← BoxConf(Encrypted=true + WrappedDEK)
+│ │ ├── .siyuan/hierarchy.enc ← 加密并认证的文档对象 ID → 父对象 ID 层级清单
│ │ ├── *.sy ← AES-256-GCM 密文
│ │ ├── assets/
│ │ │ ├── <uuid>-<blockID>.ext ← AES-256-GCM 密文,文件名已脱敏
@@ -171,6 +172,8 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
- `DEKProvider` 回调注入(避免循环依赖)
- 读盘后解密,写盘前加密,缓存存明文
- 加密 box 的标题读取需整体读 + 解密再解析
+- `.sy` AAD 绑定 boxID、对象类型和稳定文件基名 `<rootID>.sy`,不包含父目录;文件基名必须与解密后根块 ID 一致,并在 box 内全局唯一
+- 父子层级不依赖内容密文 AAD,而由 `.siyuan/hierarchy.enc` 认证;打开、重建索引和同步落地后都校验磁盘目录关系与清单一致,缺项、重复对象 ID 或父关系不匹配时进入 `Error`,不得从未认证目录结构自动修复
**assets 加密**:
- 上传时全量读入内存 + 加密 + 写盘(无法流式加密)
@@ -178,6 +181,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
- 读取时解密后输出,下载时查映射用原始名
- 加密 box 禁用全局 assets 回退,强制笔记本级
- 资源文件重命名禁止(脱敏文件名重命名会破坏映射)
+- 资源密文与加密名称映射作为一个带日志的可恢复事务提交:先写同目录临时文件并同步落盘,再写不含明文名称的事务日志,随后替换两个目标并同步目录,最后清除日志;崩溃恢复必须在开放访问前完成前滚或回滚,任何失败都向调用方返回错误,不得留下对外可见的孤儿资源或缺失映射
**数据库文件加密**:
- 路径 fallback:加密 box 的 数据库文件存 `<boxID>/storage/av/<avID>.json`,普通 box 仍存全局 `storage/av/`
@@ -193,19 +197,22 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
编辑触发历史生成 → 密文 .sy 原样拷到历史目录
关闭/退出前自动生成历史 → 确保锁定后定时器无法生成时不丢历史
历史索引 → content 留空(密文不进搜索索引)
- 查看历史 → 按路径 boxID 解密(需笔记本已解锁)
- 回滚 → 解密历史 → 加载 tree → WriteTree 自动加密写回
+ 查看历史 → 读取快照 boxID + 对象类型 + 稳定文件基名,以三者构造原 AAD 解密(需笔记本已解锁)
+ 回滚 → 按快照 AAD 解密历史 → 校验根块 ID 与文件基名一致 → 加载 tree → 文件基名不变时可原样恢复密文,变化时由 WriteTree 重新封装
已删除笔记本历史:
删除前 → 整个目录密文备份到历史目录
- 恢复 → 密文目录原样拷回
+ 恢复 → 使用匹配的全局密钥备份和主密码验证 WrappedDEK 后,将密文目录原样拷回
+ 密钥保留 → 只要内核管理的该类历史仍可恢复,就禁止删除其依赖的全局密钥备份;永久清除历史后才解除依赖
数据库历史:
生成 → 加密 box 的 数据库文件从笔记本级目录拷到历史目录
- 查看 → 按路径 boxID 解密
+ 查看 → 按快照记录的 boxID 与对象用途/标识解密,不使用历史目录绝对路径作为 AAD
回滚 → 加密 box 的数据库文件/资源回滚到笔记本级目录
```
+历史文件在历史目录中的父路径不是 AAD 的组成部分。每个历史条目必须以不可歧义的规范格式保留快照写入时的 `boxID`、对象类型和稳定文件基名或对象标识;可由固定历史目录布局编码,也可由随快照提交的元数据记录。文档只改变父目录时 AAD 上下文保持不变;文件基名改变时,既有历史仍使用旧基名认证解密。回滚时先验证密文、文件基名与解密后对象 ID 一致,再把目标父关系作为一个事务写入层级清单;仅当目标文件基名变化时才按新基名重新封装。快照上下文缺失、格式不合法或与密文不匹配时必须拒绝查看和回滚,不得从当前父路径猜测、把密文当明文解析或绕过层级清单直接恢复。
+
## 9. 块引跨加密边界防护
加密笔记本的块引:box 内部正常使用,跨加密边界被禁止。三层防御:
@@ -220,6 +227,8 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
**数据损坏风险**:跨 box 移动用文件系统 Rename 直搬 `.sy` 字节流,不经加解密转换。密文搬到普通目录不可读,明文搬到加密目录不可读。索引也无法跨库迁移。
+**同一加密 box 内移动**:`.sy` 密文 AAD 只绑定稳定文件基名,不绑定父目录。文件基名不变的移动允许原样 Rename 密文,不需要重新封装根文档或子文档;但目录层级不是无认证状态,移动必须把文件系统 Rename 与 `.siyuan/hierarchy.enc` 的父对象关系更新组成一个带日志的可恢复事务。提交前验证所有对象 ID 唯一、文件基名与解密后根块 ID 一致、目标父关系无环且目录布局与新清单一致;同步落盘 Rename 和新清单后才更新索引并清除日志,崩溃恢复完成前不开放笔记本。只有文件基名本身变化时才使用旧基名验证解密并按新基名重新封装。失败不得留下目录结构、层级清单和索引互相不一致的状态。
+
**安全泄漏风险**(更关键):从加密 box 移动到普通 box 时——文档正文脱离加密保护;关联 resources 必须一起搬出解密;绑定块与子文档的引用网被割裂或连带泄漏;索引元数据跨库迁移破坏隔离。
**设计立场**:加密笔记本是孤岛,内容不进出(从加密笔记本移出到普通 box 会泄漏明文;反之会损坏密文)。
@@ -229,26 +238,27 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
| 场景 | 交互 |
|---|---|
| 启用 | 设置 → 访问授权 → 加密笔记本区块 → 开关 → 设主密码(双输入 + 风险确认) |
-| 禁用 | 无加密笔记本时支持关闭,清除全局加密配置 |
+| 禁用 | 仅在无现存加密笔记本且无依赖当前密钥备份的内核可枚举历史或恢复快照时支持关闭;否则拒绝,或要求用户明确永久清除这些恢复数据后再删除全局配置与备份 |
| 创建 | 文件面板"更多"菜单 → "新建加密笔记本" → 输名字 + 主密码 → 自动解锁并打开 |
| 图标 | 关闭(锁定)时显示锁图标;打开(解锁)后恢复用户 emoji |
| 解锁 | 点已关闭的加密笔记本 → 弹主密码框(🔓 解锁 xxx)→ 等 ~1 秒 → 打开 |
-| 锁定 | 等于关闭(DEK 清除 + 加密 SQLite 数据库 删除 + 所有明文缓存清空)。关闭前会自动保存未写入的编辑和文件历史 |
+| 锁定 | 等于关闭:先阻止新操作,等待或取消在途任务,再移除受管 DEK 句柄、删除加密 SQLite 数据库,并尽力清理内核管理的明文缓存、临时文件和访问令牌。关闭前会自动保存未写入的编辑和文件历史 |
+| 自动锁定 | 按 box 单独计时;只有成功访问该加密 box 内容的操作才刷新其计时,普通笔记本活动、全局界面输入或其他 box 的访问不得刷新;无界面的保活请求必须显式携带 boxID 并通过认证与授权 |
| 改密 | 设置 → 访问授权 → "修改主密码" |
-| 移动文档 | 加密 box 内部或普通 box 之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 |
+| 移动文档 | 加密 box 内部仅改变父目录时原样移动密文并事务更新加密层级清单;文件基名变化时重新封装;普通 box 之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 |
| 文档转标题 | 跨加密边界被拒绝并提示 |
| 块引 | 加密 box 内部正常引用(搜索 `((` 只搜本 box,反链面板正常显示);跨加密边界(普通↔加密、加密 A↔加密 B)被阻止 |
| 数据库镜像 | 加密 box 内部正常镜像;跨加密边界被禁止 |
| 资源文件重命名 | 不支持(脱敏文件名重命名会破坏映射) |
| 导入 | 支持:导入的 .sy.zip 或 Markdown 文件落盘前自动 DEK 加密 |
| 文件历史 | 支持(查看时需先解锁对应加密笔记本;历史索引不存明文内容) |
-| 已删除笔记本 | 支持(密文备份,恢复时原样拷回) |
+| 已删除笔记本 | 支持(密文备份,恢复需匹配的全局密钥备份与主密码;保留该历史时不得直接删除所依赖的密钥备份) |
| 导出 | 支持(与普通笔记本一致;需先解锁,导出的是明文。锁定状态下拒绝导出) |
| 同步 | 不改(密文进密文出,闭环自洽) |
## 12. 安全边界
-**安全前提**:加密笔记本**只有在关闭(锁定)状态下才是安全的**。关闭时 DEK 不在内存、加密 SQLite 数据库 已删除、所有明文缓存已清空,磁盘上仅剩密文,任何途径(包括已认证 API、插件、AI/LLM、MCP)都读不到明文。**打开(解锁)状态下,DEK 在内存**,此时已认证的应用内调用方——API、第三方插件、AI/LLM(含 MCP、智能体、语义搜索)——都可像读取普通笔记本一样读到明文内容。内核 CLI 是明确例外:无论锁定或解锁,都会拒绝加密笔记本及其原始文件。加密保护的是"落盘数据"和"锁定时的不可达性",**不保护"解锁后对已认证调用方的可见性"**。因此:解锁期间应视为"普通笔记本在使用",唯一的保护手段是**用完即锁**。
+**安全前提**:加密笔记本在关闭(锁定)状态下提供最强的应用级保护。锁定完成后,新操作被拒绝,受管 DEK 句柄和数据库连接已移除,内核管理的明文缓存、临时文件与令牌已尽力清理;这不承诺抹除 Go 运行时、操作系统交换区、崩溃转储或存储介质中的所有瞬时副本。**打开(解锁)状态下,应用持有可用 DEK 句柄**,此时已认证的应用内调用方——API、第三方插件、AI/LLM(含 MCP、智能体、语义搜索)——都可像读取普通笔记本一样读到明文内容。内核 CLI 是明确例外:无论锁定或解锁,都会拒绝加密笔记本及其原始文件。加密保护的是“静态数据”和“锁定后经受支持入口的不可达性”,**不保护“解锁后对已认证调用方的可见性”**。因此:解锁期间应视为“普通笔记本在使用”,并在用完后立即锁定。
**保护(磁盘上密文)**:
- `.sy` 文档正文(已加密)
@@ -262,7 +272,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
**不保护**:
- `conf.json` 里的 MasterSalt/KEKVerifier(设计可明文:salt 不保密,verifier 是密文)
- BoxConf.WrappedDEK(密文,需 KEK 解开)
-- 内存中的 DEK/明文缓存(锁定时清空)
+- 进程和操作系统可能产生的 DEK 派生值、明文瞬时副本、交换区、休眠映像或崩溃转储;锁定只保证撤销受管密钥句柄和尽力清理应用可控缓存
- 历史索引的 content 字段(留空,不存明文也不存密文)
- **元数据泄漏**(加密不掩盖以下信息):文件数量、目录结构、文件大小、修改时间(mtime)、asset 文件扩展名、blockID 时间戳。加密 box 的 asset 文件名虽脱敏为 `uuid-blockID.ext`,但扩展名可见;同步端/历史快照中的旧密文也由各存储方自行保管,加密笔记本无法吊销其副本
@@ -274,11 +284,11 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
加密笔记本对 AI/LLM 的可见性完全由**解锁状态**决定,不做功能层隔离。
-**锁定状态下**:DEK 不在内存,AI/LLM(含 MCP、智能体、语义搜索、嵌入向量化)读不到任何加密内容——因为数据在独立加密库、磁盘是密文,无密钥无法解读。
+**锁定状态下**:AI/LLM(含 MCP、智能体、语义搜索、嵌入向量化)无法取得可用 DEK 句柄,所有加密笔记本专用入口都拒绝访问;独立数据库已关闭,磁盘内容为密文,因此这些调用方读不到加密内容。
**解锁状态下**:DEK 在内存,AI/LLM 可读加密笔记本内容、搜索笔记本内全文——MCP 工具能列出加密笔记本及其文档、读取块内容、笔记本内 FTS 搜索等。但全局搜索、语义搜索、嵌入向量化仍不参与(加密数据不进全局 `block_embeddings`/`blocks` 表,物理不可达),详见 §3 对比表。
-设计立场:不在功能层做"对 AI 隐藏"的隔离,因为这种隔离既不彻底,又会让安全模型复杂难懂。**唯一可靠的保护是锁定**——锁定后物理上不可达,任何调用方都读不到。用户只需理解一条规则:**敏感内容用完即锁**。
+设计立场:不在功能层做“对 AI 隐藏”的隔离,因为这种隔离既不彻底,又会让安全模型复杂难懂。锁定后受支持入口无法访问内容,但锁定不替代进程与操作系统层面的防护。用户只需理解一条规则:**敏感内容用完即锁**。
## 14. 功能限制
@@ -304,16 +314,16 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
| **数据库保存** | 明文 JSON 写盘 | DEK 加密 + 写盘 | 多一次加密 |
| **笔记本内搜索** | FTS 查全局 SQLite 数据库 | FTS 查独立加密 SQLite 数据库 | SQLCipher page 级解密 ~5-10% 开销 |
| **数据库连接** | 1 个全局 | 1 个全局 + 每个解锁的加密 box 2 个 | 每加密 SQLite 数据库 连接池约 20 连接 |
-| **锁定时** | 无额外开销 | 所有缓存清空 | 下次操作冷启动延迟 |
+| **锁定时** | 无额外开销 | 受管密钥句柄撤销,并尽力清理缓存与临时文件 | 下次操作冷启动延迟 |
**性能影响总结**:
- **日常编辑体验**:几乎无感知。AES-GCM 加解密是微秒级,文档读写瓶颈在磁盘 IO。
- **感知明显的延迟**:解锁 ~1 秒、大 assets 浏览(每次解密无缓存)、锁定后首次访问(冷启动)。
- **对普通笔记本零影响**:加解密与路由逻辑对非加密 box 短路跳过。
-## 17. 威胁模型与安全范围
+## 16. 威胁模型与安全范围
-本特性保护静态数据机密性和笔记本锁定后的不可访问性。设计假设攻击者可以取得工作空间、同步端或备份介质中的当前或历史密文,但不知道主密码,也不能在用户解锁期间控制运行中的应用或操作系统。AES-GCM 只提供单个加密对象的机密性和完整性校验,不解决可用性、回滚或已保留密文副本的删除。
+本特性保护静态数据机密性和笔记本锁定后经受支持入口的不可访问性。设计假设攻击者可以取得工作空间、同步端或备份介质中的当前或历史密文,但不知道主密码,也不能在用户解锁期间控制运行中的应用或操作系统。AES-GCM 只提供单个加密对象的机密性、完整性和来源上下文认证,不提供可用性、版本新鲜度、回滚防护或已保留密文副本的删除。
下列场景不在本特性的保护范围内,界面和用户指南必须明确提示:
@@ -322,34 +332,43 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
- 操作系统交换分区、休眠映像、崩溃转储、文件系统快照和恶意软件不因“清除内存”而获得绝对保护;锁定仅做应用可控范围内的尽力清除。
- 同步服务或备份持有者可以保留、删除、替换或回滚密文;这些行为可能造成拒绝服务或数据回退,但不能在不知道主密码时解密有效密文。
-“锁定后仅剩密文”只指内核管理的工作空间、临时目录和缓存中不应残留可读明文;不包括用户明确导出到外部位置的文件,也不承诺抹除底层存储介质已经保留的历史块。
+“锁定后仅剩密文”只表示内核管理的持久化工作空间中不应存在可读明文,并且受管临时文件、缓存和密钥句柄已经完成尽力清理;不包括用户明确导出到外部位置的文件,也不承诺抹除进程、操作系统或底层存储介质已经保留的瞬时或历史副本。
-## 18. 状态机与并发规则
+## 17. 状态机与并发规则
-每个加密笔记本独立处于 `Locked`、`Unlocking`、`Unlocked`、`Locking` 或 `Error` 状态。应用启动后所有加密笔记本必须为 `Locked`;全局加密功能未启用时不得存在加密笔记本。
+全局状态为 `Disabled`、`Enabled` 或 `RecoveryRequired`。正常稳态下,`Disabled` 不得存在现存加密笔记本或内核可枚举的密钥依赖;如果启动时在全局配置缺失或禁用的情况下发现加密笔记本或恢复数据,必须进入 `RecoveryRequired`,拒绝把它们当作普通笔记本,直到恢复匹配的密钥备份。`Enabled` 下每个加密笔记本独立处于 `Locked`、`Unlocking`、`Unlocked`、`Locking` 或 `Error`,应用启动后均从 `Locked` 开始。
| 转换 | 前置条件 | 成功后的不变量 | 失败处理 |
|---|---|---|---|
-| `Locked → Unlocking → Unlocked` | 主密码验证成功 | DEK 仅在内存;专属数据库已打开;允许笔记本专用入口 | 清除派生的 KEK/DEK、关闭句柄并回到 `Locked` |
-| `Unlocked → Locking → Locked` | 停止接受该笔记本的新请求 | 任务完成或取消;缓存、临时明文、数据库连接和 DEK 已清理 | 即使部分清理失败仍拒绝访问,记录错误并在下次启动前重试 |
+| `Locked → Unlocking → Unlocked` | 主密码验证成功且密文配置匹配 | 可用 DEK 句柄仅存在于受管内存;专属数据库已打开;允许笔记本专用入口 | 撤销派生的 KEK/DEK 句柄、关闭已打开资源并回到 `Locked` |
+| `Unlocked → Locking → Locked` | 原子地关闭新操作准入,并等待在途操作结束或取消 | 无可用受管 DEK 句柄或数据库连接;内核管理的明文缓存、临时文件与令牌已尽力清理 | 保持拒绝访问并进入 `Error`,记录不含明文的诊断;继续重试清理,未恢复不变量前不得重新开放 |
| `Unlocked → Error` | 密文认证失败、数据库打开失败或不变量被破坏 | 立即拒绝读写,绝不回退到普通笔记本路径 | 关闭资源,诊断信息不得含明文;用户只能锁定或重新解锁 |
-| 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK 和备份作为一个事务更新 | 保留旧配置和备份;不得出现仅能用新密码解锁的部分笔记本 |
+| 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK、全局配置和备份作为一个可恢复事务更新 | 保留旧配置和备份可用;不得出现仅能用新密码解锁的部分笔记本 |
+
+每个 box 使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、清理缓存和临时产物并撤销受管 DEK 句柄;只有清理成功才发布 `Locked`。因此锁定完成后,不得再出现晚到的明文响应、缓存回填、临时文件或数据库重连。
-同一笔记本的解锁、锁定、导出、同步、索引、历史恢复和删除必须由同一把按 boxID 分组的互斥锁串行化。锁定开始后,运行中的任务必须取消或在安全边界完成;锁定完成后不得继续创建明文临时文件、推送明文结果或重新建立数据库连接。
+全局配置锁必须先于任何 box 生命周期锁获取;同时涉及多个 box 时按 boxID 字典序获取生命周期锁;DEK 缓存、数据库、文件和其他子系统锁只能在生命周期锁之后获取,并在释放生命周期锁前释放。禁止逆序获取,禁止持有子系统锁时回取全局配置锁或其他较低层级锁。自动锁定使用单调时钟按 box 计算,只有持有该 box 有效租约并成功访问内容的操作才能刷新计时。
-## 19. 密文、密钥与数据库格式
+## 18. 密文、密钥与数据库格式
-所有持久化加密对象都必须使用带版本号的封装格式,至少包含格式版本、算法标识、密码学安全随机生成且对同一 DEK 唯一的 nonce、密文和认证标签。附加认证数据必须绑定 boxID、对象类型及逻辑相对路径,防止把有效密文替换到其他笔记本、类型或路径。改名和迁移必须创建新的封装,不能只移动密文。
+持久化格式分层,不能把全局 KDF 配置、密钥包络和每个数据对象的封装混为一体:
-实现必须由每个 box 的 DEK 通过有固定域分隔符的 KDF 派生用途隔离的子密钥,至少区分文件内容、资源名称映射、数据库文件和 WrappedDEK 的认证上下文。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 域。
+4. **层级完整性**:`.siyuan/hierarchy.enc` 使用独立用途子密钥和固定 AAD,记录每个文档稳定对象 ID 对应的父对象 ID。文件系统目录结构只是清单的物理投影,不是可信输入;创建、移动、删除和历史回滚使用事务日志原子更新文件与清单。认证有效但历史版本的清单仍可能被回放,遵循本设计不提供回滚防护的边界。
+5. **数据库兼容信息**:SQLCipher 版本、cipher 参数和 schema 版本保存在数据库头部可验证位置或对应的加密配置边界,不写入每个数据对象。content 与 blocktree 索引可重建;源密文认证通过后,版本不兼容的索引应关闭并重建,而不是降低 cipher 参数或回退到明文 SQLite。
+6. **迁移与改名**:旧版按完整逻辑相对路径绑定的封装只能先用旧路径认证解密,再事务迁移为按稳定对象 ID 绑定的新格式;迁移验证全部对象及当前目录关系后生成初始层级清单,新封装和清单全部验证并同步落盘前保留旧副本。新格式中只改变父目录不重新封装内容,只事务更新目录投影和层级清单;稳定文件基名或格式版本变化时才生成新封装。崩溃恢复完成前不开放访问,失败不得删除旧数据或发布部分索引。
-SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副本都是受保护对象,必须放在受控目录并使用相同密钥域。锁定、崩溃恢复和历史快照必须枚举这些伴随文件;未加密 SQLite 页面、查询结果或诊断转储不得写入全局临时目录。
+SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副本都是受保护对象,必须放在受控目录并使用对应的用途密钥。锁定、崩溃恢复和历史快照必须枚举这些伴随文件;未加密 SQLite 页面、查询结果或诊断转储不得写入全局临时目录。
-## 20. 备份、恢复与元数据策略
+## 19. 备份、恢复与元数据策略
-`notebook-crypto-backup.json` 是恢复材料而非秘密,但必须处理完整性和新鲜度。文件必须带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC。当前格式强制要求 HMAC:主密码派生 KEK 后,HMAC 缺失或不匹配均拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。
+`notebook-crypto-backup.json` 是恢复材料而非秘密。文件带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC;主密码派生 KEK 后,HMAC 缺失或不匹配必须拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。
-同步端和离线备份被视为可丢失、可复制、可回滚但不能读取明文的存储。输入主密码前不能建立基于 KEK 的可信认证,因此“同步恢复成功”不得表述为来源可信;系统只能验证结构和用户解锁后的 verifier。用户应保留至少一份独立、版本化的密钥备份,并理解丢失主密码或全部匹配的 MasterSalt 备份均不可恢复。
+HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明它是最新版本。当前范围不引入可信外部单调计数器,因此一个认证有效的历史备份或历史密文可能通过校验;`BackupID` 和 `CreatedAt` 只是供诊断和人工比较的信息,不是防回滚锚点。同步、历史或恢复流程不得把“认证成功”表述为“最新”或“来源可信”;真正防回滚需要独立可信状态,超出本设计范围。
+
+同步端和离线备份被视为可丢失、可复制、可回滚但不能读取明文的存储。输入主密码前不能建立基于 KEK 的可信认证;用户应保留至少一份独立、版本化的密钥备份,并理解丢失主密码或全部匹配的 MasterSalt 备份均不可恢复。只要现存加密笔记本、已删除笔记本历史或内核可枚举的本地恢复快照仍依赖当前 NotebookCrypto,禁用功能就必须拒绝删除全局配置和备份;用户明确永久清除这些恢复数据后才可解除依赖。外部与远端副本无法可靠枚举,是否保留其匹配密钥备份由用户负责。
| 类别 | 是否可泄露 |
|---|---|
@@ -358,27 +377,42 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
| 笔记本名称 | 是。笔记本列表与加密笔记本状态 API 在锁定时保留名称,以便用户识别要解锁的笔记本,因此笔记本名称不属于机密性保护边界 |
| 图标、排序、文档标题和数量、关系数量、标签、书签、历史与快照名称 | 锁定时默认不得暴露;若兼容性要求暴露,必须逐项在本表及界面中说明 |
-## 21. 功能边界、临时明文与接口规则
+## 20. 功能边界、临时明文与接口规则
不支持的闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。错误码和本地化文案应稳定,供调用方识别。
-所有可能绕过专用读写路径的原始入口必须登记并拒绝加密笔记本目录,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。新增入口时必须评审其是否可读取、写入、复制、重命名、删除或列举加密目录。
+所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。登记表同时覆盖加密 box 目录和内核管理的明文临时根目录;临时目录必须位于通用原始文件命名空间之外,或被所有原始文件 API 无条件拒绝,不能依赖当前 box 是否仍存在或 `Encrypted` 标志是否仍可查询。新增入口时必须评审其是否可读取、写入、复制、重命名、删除或列举加密目录与受控临时目录。
+
+### 本机持久化的全局拒绝访问记录
-导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物只能位于带 boxID 的受控临时目录,并按最小权限提供访问。锁定、取消、失败、应用退出和导出完成后都必须清理内核管理的明文;锁定后旧下载链接、预览链接和异步结果必须失效。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。
+“全局”表示记录在 box 已删除后仍独立于该 box 生命周期生效,不表示跨设备同步。记录持久化在 `<ConfDir>/encrypted-deny-access.json`,位于 `DataDir` 和 dejavu 同步范围之外,仅管理本机受控临时产物。每项记录至少包含格式版本、随机产物 ID、boxID、受控根目录下的规范相对路径、用途、创建时间、最近重试时间、重试次数和不含原始内容或敏感路径的错误类别;文件使用临时写入、同步落盘、原子替换和目录同步更新。记录中的路径必须重新校验为受控临时根目录的后代,越界或格式损坏的记录不得用于删除任意文件,并触发安全错误和受控根目录重新扫描。
-## 22. 安全验收矩阵
+拒绝记录只保存清理状态和诊断信息,不是访问控制依据。文件 API、下载、预览、插件、MCP、WebDAV 和后台任务按规范路径无条件拒绝整个受控明文临时命名空间,即使 box、记录文件或单项记录已经不存在。清理器在应用启动、锁定或删除、导出结束或失败后立即运行,并周期性按有上限的指数退避重试;清理成功且确认路径不存在后原子删除对应记录,持续失败则保留记录并维持 `Error` 或全局拒绝状态,不得因超过重试次数自动放行。记录文件被人为删除、部分条目丢失或文件无法解析时,访问仍保持拒绝;启动和周期扫描从受控根目录残留重建记录后继续清理。只有产物已确认不存在且记录已提交删除,才算清理完成。
+
+导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物只能位于带 boxID 的受控临时目录,并通过绑定用户、boxID、用途和有效期的最小权限令牌访问。锁定、取消、失败、应用退出和导出完成后都必须使令牌与异步结果立即失效,再尽力清理内核管理的明文;清理失败时,box 仍存在则进入 `Error`,box 已删除则保留全局拒绝访问标记,并由后台清理器重试,不能因 box 已删除或锁定而让通用文件入口重新暴露该路径。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。
+
+## 21. 安全验收矩阵
| 场景 | 预期结果 |
|---|---|
| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问 | 除明确允许暴露的笔记本名称外,不能读取、写入、复制、删除或列举加密内容;错误不返回明文、密文或可推断文档标题的信息 |
-| 解锁、锁定、应用重启和认证失败 | DEK 与数据库连接只在 `Unlocked` 存在;失败和重启后没有明文缓存或可用句柄 |
-| 锁定与导出、预览、同步、索引、历史恢复并发 | 无明文任务在锁定后继续执行;受控临时文件及访问令牌被清理或失效 |
-| 加密盒与普通盒、两个加密盒之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 |
-| 文件、资源、数据库、WAL/SHM、历史、快照、日志和临时目录的磁盘检查 | 内核管理范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页 |
-| 密文篡改、路径替换、nonce 重复、备份损坏 | 认证或格式校验失败并安全拒绝;不回退普通路径、不生成新密钥材料、不静默覆盖配置 |
-| 改主密码和 KEK 重新包络 | WrappedDEK 与备份原子更新;更新中断后保持待完成状态,直到新密码认证备份;旧密码泄露风险提示正确;迁移前后数据与历史均可验证读取 |
-
-## 16. 使用指南
+| 解锁、锁定、应用重启和认证失败 | 只有 `Unlocked` 才能取得受管 DEK 句柄和数据库连接;失败和重启后入口拒绝访问,内核可控的明文缓存、临时文件与句柄完成尽力清理 |
+| 锁定与响应生成、缓存发布、导出、预览、同步、索引或历史恢复并发 | 锁定在所有在途生命周期租约结束后才成功;成功后无晚到的明文响应、缓存回填、临时文件、可用令牌或数据库重连 |
+| 同一加密 box 内移动文档,随后清空缓存并重启 | 文件基名不变时密文保持不变并可按稳定对象 ID 认证解密;层级清单与目录关系一致,旧目录位置不存在,失败时没有半完成文件、清单或索引 |
+| 在文件系统中把认证有效且文件基名不变的 `.sy` 手工移动到另一父目录,但不更新层级清单 | 打开、同步落地检查或重建索引时发现目录关系与认证清单不一致并进入 `Error`;不得按新目录关系加载或自动改写清单 |
+| 加密 box 与普通 box、两个加密 box 之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 |
+| 资源密文写入与名称映射更新任一步失败 | 整个逻辑事务失败并回滚;调用方收到错误,不留下可访问的孤儿资源、缺失映射或明文临时文件 |
+| 删除加密笔记本后保留历史,再尝试禁用或恢复 | 存在密钥依赖时拒绝删除全局配置和备份;使用匹配备份与主密码可恢复,只有明确永久清除恢复数据后才允许解除依赖 |
+| 文档生成历史后移动父目录或改变文件基名,再查看或回滚旧历史 | 使用历史条目记录的快照 boxID、对象类型和稳定文件基名认证解密;回滚事务更新层级清单,仅在目标基名变化时重新封装,缺失快照上下文时拒绝操作 |
+| 文件、资源、数据库、WAL/SHM、历史、快照、日志和临时目录的磁盘检查 | 内核管理范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页;清理失败的临时路径仍被所有入口拒绝 |
+| 清理失败后删除或损坏全局拒绝访问记录,再重启和访问残留路径 | 受控明文临时命名空间仍被无条件拒绝;扫描重建记录并继续清理,记录缺失或损坏不会使路径失效放行 |
+| 密文篡改、路径替换和备份损坏 | 认证或格式校验失败并安全拒绝;不回退普通路径、不生成新密钥材料、不静默覆盖配置 |
+| nonce 随机源失败、达到用途密钥调用限制或事后发现 nonce 重用 | 随机源失败或达到限制时在加密前拒绝写入;AES-GCM 认证本身不能发现已发生的 nonce 重用,发现后必须按密钥泄露事件处理并轮换 DEK 后重新加密 |
+| 回放认证有效的历史密文或密钥备份 | 可能被识别为有效旧版本,但不得被宣称为最新或来源可信;数据回退风险明确,当前设计不声称提供回滚防护 |
+| 改主密码和 KEK 重新包络 | WrappedDEK 与备份原子更新;更新中断后旧配置仍可恢复使用;旧密码暴露风险提示正确;迁移前后数据与历史均可验证读取 |
+| 多个 box 并发操作与自动锁定 | 锁顺序无死锁;一个 box 的全局界面活动或内容访问不刷新另一个 box 的计时,锁定中的 box 不再接受新租约 |
+
+## 22. 使用指南
### 首次启用
1. 进入 **设置 → 访问授权 → 加密笔记本**,打开开关
@@ -389,10 +423,10 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
### 日常使用:解锁与锁定
- **解锁**:点击已关闭的加密笔记本 → 输主密码 → 等约 1 秒(Argon2id 派生)→ 打开。解锁仅作用于该笔记本,其他加密笔记本保持锁定
-- **锁定**:关闭该笔记本即等于锁定(DEK 清除 + 加密 SQLite 数据库 删除 + 明文缓存清空)。**用完即锁**是最重要的安全习惯,能最大程度减少密钥在内存的暴露时间
-- **重启后**:所有加密笔记本强制关闭,需重新输主密码解锁(DEK 仅存内存,重启即丢失)
+- **锁定**:关闭该笔记本即等于锁定。内核停止新访问,等待或取消在途任务,撤销受管 DEK 句柄和数据库连接,并尽力清理内核管理的明文缓存、临时文件与令牌。**用完即锁**是最重要的安全习惯,能最大程度减少密钥和明文的暴露时间
+- **重启后**:所有加密笔记本强制关闭,需重新输主密码解锁(受管 DEK 句柄只存在于进程内存,重启后需重新派生)
-> 重要:加密笔记本**只有在锁定状态下才是全面安全的**。解锁期间,已认证的应用内调用方(API、插件、AI/LLM 含 MCP)都能像读普通笔记本一样读到明文;内核 CLI 始终拒绝操作加密笔记本(详见 §12 安全前提)。
+> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,已认证的应用内调用方(API、插件、AI/LLM 含 MCP)都能像读普通笔记本一样读到明文;内核 CLI 始终拒绝操作加密笔记本(详见 §12 安全前提)。
### 修改主密码
进入 **设置 → 访问授权 → 修改主密码**。改密只需重新包络各 box 的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。
@@ -408,6 +442,8 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
若新设备同步后笔记本仍显示锁定属正常——点开输主密码即可。
+同步恢复可以校验备份完整性,但不能证明它是最新版本。请另外保留版本化的密钥备份;出现多个历史副本时,系统无法自动判定新鲜度,恢复前应由用户根据可信来源和时间信息确认版本。
+
### 导入与导出
- **导入**:支持导入 `.sy.zip` 和 Markdown,内容在落盘前自动用 DEK 加密,与手动创建的文档一致
- **导出**:与普通笔记本一致(需先解锁,导出明文)。`.sy.zip`、HTML、Word、PDF、Markdown 等格式均支持;锁定状态下拒绝导出
@@ -418,6 +454,8 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
### 密钥备份丢失的恢复
若 `conf/conf.json` 与同步目录里的密钥备份同时丢失(极端情况),重新启用加密笔记本会被拒绝并提示恢复备份文件。只要能从其他已同步的设备或之前导出的密钥文件找回 `notebook-crypto-backup.json`,可通过未启用状态下显示的"导入密钥"按钮导入,或手动放回 `<工作区>/data/.siyuan/` 后重新启用,即可用该密钥对应的主密码解锁。
+恢复已删除加密笔记本的历史同样需要与其 WrappedDEK 匹配的全局密钥备份和主密码。只要仍要保留这类本地恢复能力,就不要永久清除其历史或匹配的密钥备份;禁用流程应在发现这类依赖时拒绝继续。
+
### 适合用加密笔记本的场景
- 隐私日记、财务记录、医疗信息
- 工作机密、商业方案、合同
@@ -439,4 +477,4 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
2. **用完即锁**:减少 DEK 在内存的暴露时间
3. **不要把所有笔记都放加密笔记本**:只放真正敏感的
4. **主密码强度**:建议 12 位以上,混合大小写 + 数字 + 符号
-5. **备份**:密文同步到云端是安全的,但密码丢了备份也没用
+5. **备份**:分别保留版本化的密文备份和匹配的密钥备份;主密码或全部匹配密钥备份丢失后,密文无法恢复