An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Block CLI operations on encrypted notebooks #18034
Danielee1a4c646c87
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 16b2312683..ab78da443d 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -57,6 +57,7 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d| **Deleted notebook history** | Supported | Supported (entire directory backed up as ciphertext before deletion; restored verbatim) || **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 || **Flashcards / spaced repetition** | Participates | Not supported (feature limitation) || **Bookmarks** | Participates (global aggregation) | Not supported (feature limitation) || **Tags** | Participates (global aggregation) | Not supported (feature limitation) |@@ -247,7 +248,7 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma## 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 every authenticated caller — APIs, third-party plugins, AI/LLM (including MCP, agents, semantic search) — can read plaintext content just like a normal notebook. 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 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**.**Protected (ciphertext on disk)**:- `.sy` document body (encrypted)@@ -267,6 +268,7 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma**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.## 13. AI / LLM Reachability@@ -323,7 +325,7 @@ An encrypted notebook is an island; some features are unimplemented because of t- **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)-> Important: An encrypted notebook is **only fully secure when locked**. While unlocked, every authenticated caller (APIs, plugins, AI/LLM including MCP) can read plaintext just like a normal notebook (see §12 Security premise).+> 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).### Changing the master passwordGo 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.diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex b66c11f8de..01a5707e19 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -57,6 +57,7 @@| **已删除笔记本历史** | 支持 | 支持(删除前整个目录密文备份,恢复时原样拷回) || **嵌入向量化 / 语义搜索** | 参与 | 不参与(加密数据不进全局 block_embeddings 表,嵌入流水线只读全局库;与解锁状态无关) || **智能体 / AI 对话 / MCP** | 可读内容、可搜索 | 解锁后可用(可读块内容、列文档、笔记本内搜索);锁定后不可达(详见 §13)。全局搜索/语义搜索不参与 |+| **内核 CLI** | 可操作工作区数据 | 无论锁定或解锁,均不支持加密笔记本及其文件 || **闪卡 / 间隔重复** | 参与 | 不支持(功能限制) || **书签** | 参与(全局聚合) | 不支持(功能限制) || **标签** | 参与(全局聚合) | 不支持(功能限制) |@@ -247,7 +248,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i## 12. 安全边界-**安全前提**:加密笔记本**只有在关闭(锁定)状态下才是安全的**。关闭时 DEK 不在内存、加密 SQLite 数据库 已删除、所有明文缓存已清空,磁盘上仅剩密文,任何途径(包括已认证 API、插件、AI/LLM、MCP)都读不到明文。**打开(解锁)状态下,DEK 在内存**,此时所有已认证调用方——API、第三方插件、AI/LLM(含 MCP、智能体、语义搜索)——都可像读取普通笔记本一样读到明文内容。加密保护的是"落盘数据"和"锁定时的不可达性",**不保护"解锁后对已认证调用方的可见性"**。因此:解锁期间应视为"普通笔记本在使用",唯一的保护手段是**用完即锁**。+**安全前提**:加密笔记本**只有在关闭(锁定)状态下才是安全的**。关闭时 DEK 不在内存、加密 SQLite 数据库 已删除、所有明文缓存已清空,磁盘上仅剩密文,任何途径(包括已认证 API、插件、AI/LLM、MCP)都读不到明文。**打开(解锁)状态下,DEK 在内存**,此时已认证的应用内调用方——API、第三方插件、AI/LLM(含 MCP、智能体、语义搜索)——都可像读取普通笔记本一样读到明文内容。内核 CLI 是明确例外:无论锁定或解锁,都会拒绝加密笔记本及其原始文件。加密保护的是"落盘数据"和"锁定时的不可达性",**不保护"解锁后对已认证调用方的可见性"**。因此:解锁期间应视为"普通笔记本在使用",唯一的保护手段是**用完即锁**。**保护(磁盘上密文)**:- `.sy` 文档正文(已加密)@@ -267,6 +268,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i**API 防护**:- `/api/file/getFile`、`/api/file/putFile`、`/api/file/copyFile`、`/api/file/renameFile`、`/api/file/removeFile`:拒绝读写加密 box 下的任何文件(不只 .sy),避免密文泄漏或明文破坏;合法读写走专用 API(已加密感知)+- 内核 CLI:拒绝以加密笔记本或块 ID 为目标的命令,以及 `<工作区>/data/<加密-boxID>/` 下的直接路径;不能用于解锁、读写、导出或操作加密笔记本数据## 13. AI / LLM 可达性@@ -323,7 +325,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i- **锁定**:关闭该笔记本即等于锁定(DEK 清除 + 加密 SQLite 数据库 删除 + 明文缓存清空)。**用完即锁**是最重要的安全习惯,能最大程度减少密钥在内存的暴露时间- **重启后**:所有加密笔记本强制关闭,需重新输主密码解锁(DEK 仅存内存,重启即丢失)-> 重要:加密笔记本**只有在锁定状态下才是全面安全的**。解锁期间,所有已认证调用方(API、插件、AI/LLM 含 MCP)都能像读普通笔记本一样读到明文(详见 §12 安全前提)。+> 重要:加密笔记本**只有在锁定状态下才是全面安全的**。解锁期间,已认证的应用内调用方(API、插件、AI/LLM 含 MCP)都能像读普通笔记本一样读到明文;内核 CLI 始终拒绝操作加密笔记本(详见 §12 安全前提)。### 修改主密码进入 **设置 → 访问授权 → 修改主密码**。改密只需重新包络各 box 的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。diff --git a/kernel/cli/cmd/root.go b/kernel/cli/cmd/root.goindex 6d48a667b1..fbd12aaaad 100644--- a/kernel/cli/cmd/root.go+++ b/kernel/cli/cmd/root.go@@ -26,6 +26,7 @@ import ("github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util""github.com/spf13/cobra"@@ -112,10 +113,115 @@ var rootCmd = &cobra.Command{sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)// 让 CLI 一次性命令(如 search -m 4)也能命中语义搜索:StartEmbeddingIndexer 是死循环不能用于会立即退出的进程,这里只把开关置真model.PrepareEmbeddingSearch()+ if err := rejectEncryptedNotebookCLI(cmd, args); err != nil {+ return err+ }return nil},}+// rejectEncryptedNotebookCLI 拒绝 CLI 对加密笔记本及其块的操作。+// 加密笔记本只能通过应用内专用流程解锁和操作,避免 CLI 进程成为明文或密文文件的旁路入口。+func rejectEncryptedNotebookCLI(cmd *cobra.Command, args []string) error {+ if cmd == serveCmd {+ return nil+ }+ if (cmd == notebookRandomIconCmd && !cmd.Flags().Changed("id")) || cmd == exportDataCmd {+ boxID, err := firstEncryptedNotebookID()+ if err != nil {+ return err+ }+ if boxID != "" {+ return fmt.Errorf("CLI does not support encrypted notebook [%s]", boxID)+ }+ }++ var encryptedTarget string+ checkID := func(id string) bool {+ if id == "" {+ return false+ }+ if model.IsEncryptedBox(id) {+ encryptedTarget = id+ return true+ }+ if bt := treenode.GetBlockTree(id); bt != nil && model.IsEncryptedBox(bt.BoxID) {+ encryptedTarget = bt.BoxID+ return true+ }+ return false+ }++ for _, flagName := range []string{"notebook", "box", "id", "ids", "parent", "previous", "block"} {+ flag := cmd.Flags().Lookup(flagName)+ if flag == nil {+ continue+ }+ values := []string{flag.Value.String()}+ if flag.Value.Type() == "stringArray" {+ values, _ = cmd.Flags().GetStringArray(flagName)+ }+ for _, value := range values {+ for _, id := range strings.Split(value, ",") {+ if checkID(strings.TrimSpace(id)) {+ return fmt.Errorf("CLI does not support encrypted notebook [%s]", encryptedTarget)+ }+ }+ }+ }++ if cmd.Parent() == fileCmd {+ for _, arg := range args {+ if isEncryptedNotebookWorkspacePath(arg) {+ return fmt.Errorf("CLI does not support files in encrypted notebooks")+ }+ }+ }+ if cmd.Parent() == assetCmd {+ if pathFlag := cmd.Flags().Lookup("path"); pathFlag != nil && pathFlag.Value.String() != "" {+ assetPath := pathFlag.Value.String()+ if !filepath.IsAbs(assetPath) {+ assetPath = filepath.Join("data", assetPath)+ }+ if isEncryptedNotebookWorkspacePath(assetPath) {+ return fmt.Errorf("CLI does not support files in encrypted notebooks")+ }+ }+ }+ return nil+}++func firstEncryptedNotebookID() (string, error) {+ boxes, err := model.ListNotebooks()+ if err != nil {+ return "", err+ }+ for _, box := range boxes {+ if model.IsEncryptedBox(box.ID) {+ return box.ID, nil+ }+ }+ return "", nil+}++// isEncryptedNotebookWorkspacePath 判断工作区内路径是否位于加密笔记本目录。+func isEncryptedNotebookWorkspacePath(p string) bool {+ return isEncryptedNotebookWorkspacePathWith(p, util.WorkspaceDir, util.DataDir, model.IsEncryptedBox)+}++func isEncryptedNotebookWorkspacePathWith(p, workspaceDir, dataDir string, isEncryptedBox func(string) bool) bool {+ abs := p+ if !filepath.IsAbs(abs) {+ abs = filepath.Join(workspaceDir, p)+ }+ rel, err := filepath.Rel(dataDir, filepath.Clean(abs))+ if err != nil || rel == "." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || rel == ".." {+ return false+ }+ boxID := strings.Split(rel, string(filepath.Separator))[0]+ return isEncryptedBox(boxID)+}+// resolveWorkingDir 从内核可执行文件路径出发,探测若干候选目录,返回首个包含 appearance/langs 的目录作为// 工作目录(打包后为 resources/,开发态视目录布局而定);找不到返回空串。rootCmd.PersistentPreRunE 与// serve 子命令的 --wd 默认值都走这个函数,确保两条启动路径行为一致。diff --git a/kernel/cli/cmd/root_test.go b/kernel/cli/cmd/root_test.gonew file mode 100644index 0000000000..c799ad93ac--- /dev/null+++ b/kernel/cli/cmd/root_test.go@@ -0,0 +1,40 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package cmd++import (+ "path/filepath"+ "testing"+)++func TestIsEncryptedNotebookWorkspacePathWith(t *testing.T) {+ workspace := filepath.Join(string(filepath.Separator), "workspace")+ data := filepath.Join(workspace, "data")+ isEncryptedBox := func(boxID string) bool { return boxID == "encrypted-box" }++ tests := []struct {+ name string+ path string+ want bool+ }{+ {name: "encrypted notebook root", path: filepath.Join("data", "encrypted-box"), want: true},+ {name: "encrypted notebook file", path: filepath.Join("data", "encrypted-box", "20240101000000-abcdefg.sy"), want: true},+ {name: "normal notebook", path: filepath.Join("data", "normal-box", "20240101000000-abcdefg.sy"), want: false},+ {name: "workspace data directory", path: "data", want: false},+ {name: "outside data directory", path: "temp", want: false},+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ if got := isEncryptedNotebookWorkspacePathWith(test.path, workspace, data, isEncryptedBox); got != test.want {+ t.Fatalf("isEncryptedNotebookWorkspacePathWith(%q) = %v, want %v", test.path, got, test.want)+ }+ })+ }+}