Skip to content

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

:lock: Prevent publishing encrypted notebooks

Daniela25c2dd06aae
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index a8034b2940..453b6dbace 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -265,6 +265,9 @@ export class Files extends Model {
} else if (target.classList.contains("b3-list-item__switch")) {
event.preventDefault();
event.stopPropagation();
+ if (target.closest("[data-encrypted=true]")) {
+ break;
+ }
const rect = target.getBoundingClientRect();
openPublishAccessDialog(target.parentElement.getAttribute("data-type") === "navigation-root" ?
notebookId : target.parentElement.getAttribute("data-node-id"), {
@@ -1073,8 +1076,8 @@ export class Files extends Model {
const actionClasses = `${iconUsesDocAction && hasChildren && !editingPublishAccess ? " file-tree__item--icon-expand" : ""}${
iconUsesDocAction && !hasChildren && !editingPublishAccess ? " file-tree__item--icon-open" : ""}${
hasChildren && window.siyuan.config.fileTree.parentDocClickExpand ? " file-tree__item--title-expand" : ""}`;
- const emojiHTML = `<span class="b3-list-item__icon ariaLabel${isBoxDoc ? " popover__block" : ""}${editingPublishAccess ? " fn__none" : ""}" data-position="8east"${isBoxDoc ? ` data-id="${item.id}"` : ""} aria-label="${iconAriaLabel}">${iconContent}</span>`;
- const switchHTML = `<span class="b3-list-item__switch b3-tooltips b3-tooltips__e${editingPublishAccess ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>`;
+ const emojiHTML = `<span class="b3-list-item__icon ariaLabel${isBoxDoc ? " popover__block" : ""}${editingPublishAccess && !item.encrypted ? " fn__none" : ""}" data-position="8east"${isBoxDoc ? ` data-id="${item.id}"` : ""} aria-label="${iconAriaLabel}">${iconContent}</span>`;
+ const switchHTML = `<span class="b3-list-item__switch b3-tooltips b3-tooltips__e${editingPublishAccess && !item.encrypted ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>`;
if (item.closed) {
return `<li data-url="${item.id}" class="b3-list-item b3-list-item--hide-action"${item.encrypted ? ' data-encrypted="true"' : ""}>
<span class="b3-list-item__toggle fn__hidden">
@@ -1088,7 +1091,7 @@ export class Files extends Model {
</span>
</li>`;
} else {
- return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sort="${item.sort}" data-sortmode="${item.sortMode}">
+ return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sort="${item.sort}" data-sortmode="${item.sortMode}"${item.encrypted ? " data-encrypted=\"true\"" : ""}>
<li class="b3-list-item b3-list-item--hide-action${actionClasses}" ${window.siyuan.config.fileTree.sort === 6 ? 'draggable="true"' : ""}
style="--file-toggle-width:22px;--file-action-offset:22px"
data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? item.id : ""}">
@@ -1692,11 +1695,6 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}
checked: this.element.classList.contains("file-tree__publish-access--active"),
click: () => {
this.element.classList.toggle("file-tree__publish-access--active");
- const editingPublishAccess = this.element.classList.contains("file-tree__publish-access--active");
- this.element.querySelectorAll(".b3-list-item__icon").forEach(item => {
- item.classList.toggle("fn__none", editingPublishAccess);
- item.nextElementSibling.classList.toggle("fn__none", !editingPublishAccess);
- });
this.updateDocActions();
this.refreshPublishAccessSwitch();
}
@@ -1705,14 +1703,34 @@ aria-label="${ariaLabel}">${getDocDisplayName(item.name, item.titleEmpty, true)}
return window.siyuan.menus.menu;
}
+ private updatePublishAccessControls(editingPublishAccess: boolean) {
+ this.element.querySelectorAll(".b3-list-item__icon").forEach(item => {
+ const encrypted = Boolean(item.closest("[data-encrypted=true]"));
+ item.classList.toggle("fn__none", editingPublishAccess && !encrypted);
+ const switchElement = item.nextElementSibling;
+ if (switchElement) {
+ switchElement.classList.toggle("fn__none", !editingPublishAccess || encrypted);
+ }
+ });
+ }
+
private refreshPublishAccessSwitch() {
- if (window.siyuan.config.readonly || window.siyuan.isPublish ||
- !this.element.classList.contains("file-tree__publish-access--active")) {
+ const editingPublishAccess = this.element.classList.contains("file-tree__publish-access--active");
+ this.updatePublishAccessControls(editingPublishAccess);
+ if (window.siyuan.config.readonly || window.siyuan.isPublish || !editingPublishAccess) {
return;
}
const ids: string[] = [];
- this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-url")));
- this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-node-id")));
+ this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => {
+ if (!element.closest("[data-encrypted=true]")) {
+ ids.push(element.getAttribute("data-url"));
+ }
+ });
+ this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => {
+ if (!element.closest("[data-encrypted=true]")) {
+ ids.push(element.getAttribute("data-node-id"));
+ }
+ });
fetchPost("/api/filetree/getPublishAccess", {
ids
}, response => {
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index 268c38b4fa..a09d4b5bd0 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -117,6 +117,11 @@ export class MobileFiles extends Model {
event.preventDefault();
break;
} else if (target.classList.contains("b3-list-item__switch")) {
+ if (target.closest("[data-encrypted=true]")) {
+ event.preventDefault();
+ event.stopPropagation();
+ break;
+ }
const rect = target.getBoundingClientRect();
const rootUL = hasTopClosestByTag(target, "UL");
openPublishAccessDialog(target.parentElement.getAttribute("data-type") === "navigation-root" ?
@@ -140,11 +145,7 @@ export class MobileFiles extends Model {
} else if (type === "publish-access") {
// 顶部栏中的按钮
target.classList.toggle("block__icon--active");
- const editingPublishAccess = target.classList.contains("block__icon--active");
- this.element.querySelectorAll(".b3-list-item__icon").forEach(item => {
- item.classList.toggle("fn__none", editingPublishAccess);
- item.nextElementSibling.classList.toggle("fn__none", !editingPublishAccess);
- });
+ this.refreshPublishAccessSwitch();
event.preventDefault();
event.stopPropagation();
break;
@@ -725,8 +726,8 @@ export class MobileFiles extends Model {
const iconAriaLabel = isBoxDoc ?
(hasChildren ? window.siyuan.languages.docIconClickExpand : window.siyuan.languages.openDocument) :
window.siyuan.languages.changeIcon;
- const emojiHTML = `<span class="b3-list-item__icon b3-tooltips b3-tooltips__e${editingPublishAccess ? " fn__none" : ""}" aria-label="${iconAriaLabel}">${iconContent}</span>`;
- const switchHTML = `<span class="b3-list-item__switch b3-tooltips b3-tooltips__e${editingPublishAccess ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>`;
+ const emojiHTML = `<span class="b3-list-item__icon b3-tooltips b3-tooltips__e${editingPublishAccess && !item.encrypted ? " fn__none" : ""}" aria-label="${iconAriaLabel}">${iconContent}</span>`;
+ const switchHTML = `<span class="b3-list-item__switch b3-tooltips b3-tooltips__e${editingPublishAccess && !item.encrypted ? "" : " fn__none"}" aria-label="${window.siyuan.languages.publishAccess}">${getPublishAccessOptionByLevel("public").iconHTML}</span>`;
if (item.closed) {
return `<li data-url="${item.id}" class="b3-list-item"${item.encrypted ? ' data-encrypted="true"' : ""}>
<span class="b3-list-item__toggle fn__hidden">
@@ -740,7 +741,7 @@ export class MobileFiles extends Model {
</span>
</li>`;
} else {
- return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sortmode="${item.sortMode}">
+ return `<ul class="b3-list b3-list--background" data-url="${item.id}" data-sortmode="${item.sortMode}"${item.encrypted ? " data-encrypted=\"true\"" : ""}>
<li class="b3-list-item" data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}" data-node-id="${window.siyuan.config.fileTree.boxDocEnabled ? item.id : ""}" style="--file-toggle-width:24px">
<span class="b3-list-item__toggle${isBoxDoc && !hasChildren ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
@@ -1259,14 +1260,34 @@ class="b3-list-item" data-path="${item.path}" style="--file-toggle-width:${paddi
</li>`;
};
+ private updatePublishAccessControls(editingPublishAccess: boolean) {
+ this.element.querySelectorAll(".b3-list-item__icon").forEach(item => {
+ const encrypted = Boolean(item.closest("[data-encrypted=true]"));
+ item.classList.toggle("fn__none", editingPublishAccess && !encrypted);
+ const switchElement = item.nextElementSibling;
+ if (switchElement) {
+ switchElement.classList.toggle("fn__none", !editingPublishAccess || encrypted);
+ }
+ });
+ }
+
private refreshPublishAccessSwitch() {
- if (window.siyuan.config.readonly || window.siyuan.isPublish ||
- !this.actionsElement.querySelector('[data-type="publish-access"]').classList.contains("block__icon--active")) {
+ const editingPublishAccess = this.actionsElement.querySelector('[data-type="publish-access"]').classList.contains("block__icon--active");
+ this.updatePublishAccessControls(editingPublishAccess);
+ if (window.siyuan.config.readonly || window.siyuan.isPublish || !editingPublishAccess) {
return;
}
const ids: string[] = [];
- this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-url")));
- this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => ids.push(element.getAttribute("data-node-id")));
+ this.element.querySelectorAll("[data-url]").forEach((element: HTMLElement) => {
+ if (!element.closest("[data-encrypted=true]")) {
+ ids.push(element.getAttribute("data-url"));
+ }
+ });
+ this.element.querySelectorAll("[data-type=\"navigation-file\"][data-node-id]").forEach((element: HTMLElement) => {
+ if (!element.closest("[data-encrypted=true]")) {
+ ids.push(element.getAttribute("data-node-id"));
+ }
+ });
fetchPost("/api/filetree/getPublishAccess", {
ids
}, response => {
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index b9b08257ca..b830a7aeaa 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -18,6 +18,7 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d
| Global features | Encrypted notebooks never participate (global search / graph / block refs cannot see them) |
| Block refs | Normal refs within the notebook; cross-boundary refs forbidden (bidirectional: normal↔encrypted, encrypted A↔encrypted B) |
| AI / LLM | No functional-layer isolation — when unlocked, AI/LLM can read/search just like a normal notebook; when locked, no usable DEK handle exists and dedicated entry points deny access (see §13) |
+| Publish | Unsupported — publish readers and anonymous visitors cannot enumerate or read an encrypted notebook regardless of unlock state, publish password, or visibility configuration |
| Cross-boundary move | Forbidden — would break data consistency and leak |
| Database | Notebook-level storage — encrypted notebook database files follow the notebook directory, DEK-encrypted; cross-boundary mirroring forbidden |
| Flashcards / spaced repetition | Not supported (feature limitation) |
@@ -57,6 +58,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 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 |
+| **Publish** | Supports visibility, password, and deny configuration through `publishAccess.json` | Unsupported; publish readers and anonymous visitors can never enumerate or read it, and `publishAccess.json` cannot override this rule |
| **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) |
@@ -68,7 +70,7 @@ Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` d
| **Rebuild index** | Full | Skipped on startup (closed); opening performs a full rebuild into the encrypted SQLite database |
| **/api/file/\*** | Can read, write, copy, rename, delete, or enumerate workspace files | Refuses access to any file in encrypted-notebook persistent directories (not just .sy) to prevent ciphertext disclosure or writes that bypass the encryption layer; `temp/` remains accessible to administrator file APIs and trusted plugins |
-**Core difference summary**: An encrypted notebook is an "island" — data is physically isolated, operations have dedicated entry points, it never participates in global features (global search/graph), and documents/database files do not cross the boundary. In-notebook features (editing, block refs, backlinks, search, database, outline, history, etc.) work normally; AI/LLM is also usable when unlocked (same as a normal notebook). Encrypted notebooks are also isolated from each other. Normal notebooks are completely unaffected.
+**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), it cannot be published, and documents/database files do not cross the boundary. In-notebook features (editing, block refs, backlinks, search, database, outline, history, etc.) work normally; AI/LLM is also usable when unlocked (same as a normal notebook). Encrypted notebooks are also isolated from each other. Normal notebooks are completely unaffected.
## 4. Key Architecture
@@ -252,12 +254,13 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma
| 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; recovery requires the matching global key backup and master password; retaining this history prevents direct deletion of its key backup) |
+| Publish | Unsupported; publish-access editing offers no configuration entry for an encrypted notebook or any of its documents, and the publish service never exposes them regardless of authentication state |
| 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 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.
+**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 callers authorized by the main application — APIs, third-party plugins, AI/LLM (including MCP, agents, semantic search) — can read plaintext content just like a normal notebook. The publish service is an explicit exception: publish readers and anonymous visitors cannot enumerate or read encrypted notebooks regardless of unlock state, and publish passwords, visibility configuration, and `publishAccess.json` cannot override this rule. The kernel CLI likewise 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 callers authorized by the main application while unlocked**. Treat an unlocked encrypted notebook as a normal notebook in active use within the main application and lock it immediately afterwards.
**Protected (ciphertext on disk)**:
- `.sy` document body (encrypted)
@@ -278,6 +281,7 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma
**API protection**:
- `/api/file/*`: refuses access to any file in encrypted-notebook persistent directories (not just .sy), preventing ciphertext disclosure or writes that bypass the encryption layer; workspace `temp/` remains accessible.
+- Publish service: `RoleReader` and `RoleVisitor` can never access an encrypted notebook or its documents, blocks, attribute views, and resources; unlock state and publish-access configuration do not change the result.
- Kernel CLI: rejects encrypted notebook/block targets and direct paths below `<workspace>/data/<encrypted-notebookID>/`; it cannot be used to unlock, read, write, export, or manipulate encrypted notebook data.
## 13. AI / LLM Reachability
@@ -295,6 +299,7 @@ Design stance: there is no "hide from AI" isolation at the functional layer, bec
An encrypted notebook is an island; some features are unimplemented because of their cross-notebook nature or dependence on global aggregation. These are feature boundaries, not performance or security trade-offs.
- **Flashcards / spaced repetition**: Decks and scheduling are cross-notebook and depend on the global SQLite database; not implemented.
+- **Publish**: The publish service targets read-only or anonymous visitors, so encrypted notebooks never participate whether locked or unlocked and cannot be enabled through publish passwords or visibility configuration.
- **Bookmarks**: Global aggregation view (scans the global siyuan.db); encrypted notebooks not integrated.
- **Tags**: Global aggregation view (scans the global spans table); encrypted notebooks not integrated.
- **Asset file rename**: Encrypted-notebook asset filenames are already desensitized to `uuid-blockID.ext`; renaming breaks the original-name mapping.
@@ -327,7 +332,7 @@ This feature protects data-at-rest confidentiality and inaccessibility through s
The following are outside this feature's security boundary and must be stated in product UI and user documentation:
-- While a notebook is unlocked, authenticated application callers such as APIs, plugins, MCP, and AI/LLM, as well as a local attacker able to read the application process memory, may obtain plaintext.
+- While a notebook is unlocked, APIs, plugins, MCP, and AI/LLM authorized by the main application, as well as a local attacker able to read the application process memory, may obtain plaintext; publish readers and anonymous visitors are outside this scope and are always denied.
- Local processes that can read workspace files, administrator file APIs, and trusted plugins can read temporary plaintext exports that have not yet been cleaned up; the temporary directory is not an access-control boundary.
- Files intentionally exported by the user, clipboard contents, screenshots, printouts, content shared with third parties, and plaintext files saved outside the workspace are protected by the user.
- OS swap, hibernation images, crash dumps, filesystem snapshots, and malware are not absolutely protected by clearing application memory; locking performs best-effort cleanup only within the application's control.
@@ -382,7 +387,7 @@ Sync endpoints and offline backups are storage that may be lost, copied, or roll
## 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.
+Unsupported publishing, 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. Publish authorization is independent of lock state and takes precedence over `publishAccess.json`; existing publish configuration cannot make an encrypted notebook visible again. Error codes and localized messages remain stable for callers.
Every raw entry point that might bypass dedicated read/write paths is registered, including file APIs, kernel CLI, MCP file tools, WebDAV, plugin file interfaces, export download URLs, preview URLs, and background tasks. Encrypted-notebook persistent directories always reject direct access through raw entry points to avoid ciphertext disclosure or writes that bypass the encryption layer. Workspace `temp/` is general temporary storage accessible to administrator file APIs, archive APIs, and trusted plugins, so it is not part of the encrypted access-control boundary. WebDAV continues to deny the entire `temp/` directory unconditionally to avoid exposing temporary data through a remote file service. Adding an entry point requires separate review of whether it touches encrypted-notebook persistent directories or temporary plaintext.
@@ -397,6 +402,7 @@ The in-memory `managedEncryptedExports` tokens manage download-link expiry and l
| Scenario | Expected result |
|---|---|
| Access to encrypted-notebook persistent directories while locked through UI, HTTP, file APIs, CLI, MCP, WebDAV, plugins, and background tasks | Other than the explicitly exposed notebook name, cannot decrypt, write, copy, delete, or enumerate encrypted content; administrator file APIs and trusted plugins may still access an export copy in `temp/` that has not yet been cleaned up |
+| Access a locked or unlocked encrypted notebook through the publish service using anonymous access, a publish-reader account, and public/protected/private/forbidden configuration | Cannot enumerate notebooks, documents, blocks, attribute views, or resources and cannot obtain plaintext; lock state, publish authentication, and `publishAccess.json` do not change the result |
| 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, newly created temporary file, usable token, or database reconnection follows success, except for an existing temporary file whose deletion failed |
| Move a document within one encrypted notebook, then clear caches and restart | When the basename is unchanged, ciphertext remains unchanged and authenticates with the stable object ID; the new parent takes effect under normal-notebook semantics, the old directory location is absent, and failure handling matches a normal notebook |
@@ -426,7 +432,7 @@ The in-memory `managedEncryptedExports` tokens manage download-link expiry and l
- **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 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).
+> 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, callers authorized by the main application (APIs, plugins, AI/LLM including MCP) can read plaintext just like a normal notebook; publish readers, anonymous visitors, and the kernel CLI are always denied (see §12 Security premise).
### Changing the master password
Go to **Settings → Access authorization → Change master password**. Changing the password only re-wraps each notebook's WrappedDEK — **document data is not re-encrypted**, so it completes instantly. The key backup is auto-refreshed and synced after a password change.
@@ -447,6 +453,7 @@ Sync recovery can validate backup integrity but cannot prove that a backup is th
### 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
+- **Publish**: Unsupported. Encrypted notebooks and their documents never appear through the publish service, and unlocking or setting a publish password cannot enable them
### What if I forget the password
**It cannot be recovered** — by design (no backdoor). Even if the ciphertext has been synced to the cloud, it cannot be decrypted without the master password. **You must remember the master password; using a password manager is recommended.**
@@ -464,6 +471,7 @@ Restoring deleted encrypted-notebook history also requires the global key backup
### Unsuitable scenarios for encrypted notebooks
- Daily notes, study notes (the extra encryption overhead is not worth it)
- Content that needs global search (encrypted notebooks do not participate)
+- Content that must be made available through the publish service (encrypted notebooks cannot be published)
- Knowledge networks needing cross-notebook block refs (cross-boundary forbidden)
- Documents needing cross-notebook move/reorganize (cross-boundary forbidden)
- Scenarios needing cross-notebook database mirroring (cross-boundary forbidden)
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index c7b2b8aca6..6cb6d5e047 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -18,6 +18,7 @@
| 全局功能 | 加密笔记本完全不参与(全局搜索/关系图/块引都看不到它) |
| 块引 |笔记本内部正常引用;禁止跨加密边界引用(双向:普通↔加密、加密 A↔加密 B) |
| AI / LLM | 不做功能层隔离——解锁后与普通笔记本一样可读可搜;锁定后无可用 DEK 句柄且专用入口拒绝访问(详见 §13) |
+| 发布 | 不支持——发布服务的读者与匿名访问者无论笔记本是否解锁、是否配置发布密码或可见性,均不可列举或读取加密笔记本 |
| 跨边界移动 | 禁止——会破坏数据一致性且泄漏 |
| 数据库 | 笔记本级存储——加密笔记本的 数据库文件跟随笔记本目录,DEK 加密;禁止跨边界镜像 |
| 闪卡 / 间隔重复 | 不支持(功能限制) |
@@ -57,6 +58,7 @@
| **已删除笔记本历史** | 支持 | 支持(删除前整个目录密文备份,恢复时原样拷回;恢复还需要匹配的全局密钥备份和主密码) |
| **嵌入向量化 / 语义搜索** | 参与 | 不参与(加密数据不进全局 block_embeddings 表,嵌入流水线只读全局库;与解锁状态无关) |
| **智能体 / AI 对话 / MCP** | 可读内容、可搜索 | 解锁后可用(可读块内容、列文档、笔记本内搜索);锁定后不可达(详见 §13)。全局搜索/语义搜索不参与 |
+| **发布** | 支持通过 `publishAccess.json` 配置可见性、密码和禁止访问 | 不支持;发布服务的读者与匿名访问者始终不可列举或读取,`publishAccess.json` 不能覆盖该规则 |
| **内核 CLI** | 可操作工作区数据 | 无论锁定或解锁,均不支持加密笔记本及其文件 |
| **闪卡 / 间隔重复** | 参与 | 不支持(功能限制) |
| **书签** | 参与(全局聚合) | 不支持(功能限制) |
@@ -68,7 +70,7 @@
| **重建索引** | 全量 | 启动时跳过(已关闭);打开时全量重建到加密 SQLite 数据库 |
| **/api/file/\*** | 可读写、复制、重命名、删除或列举工作空间文件 | 拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),防止密文泄漏或绕过加密层写入;`temp/` 仍可由管理员文件 API 和受信任插件访问 |
-**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、文档和 数据库文件不进出边界。笔记本内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 也可用(与普通笔记本一致)。加密笔记本之间也互相隔离。普通笔记本完全不受影响。
+**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、不支持发布、文档和 数据库文件不进出边界。笔记本内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 也可用(与普通笔记本一致)。加密笔记本之间也互相隔离。普通笔记本完全不受影响。
## 4. 密钥架构
@@ -252,12 +254,13 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
| 导入 | 支持:导入的 .sy.zip 或 Markdown 文件落盘前自动 DEK 加密 |
| 文件历史 | 支持(查看时需先解锁对应加密笔记本;历史索引不存明文内容) |
| 已删除笔记本 | 支持(密文备份,恢复需匹配的全局密钥备份与主密码;保留该历史时不得直接删除所依赖的密钥备份) |
+| 发布 | 不支持;发布权限编辑界面不提供加密笔记本及其文档的配置入口,发布服务无论认证状态如何均不可见 |
| 导出 | 支持(与普通笔记本一致;需先解锁,导出的是明文。锁定状态下拒绝导出) |
| 同步 | 不改(密文进密文出,闭环自洽) |
## 12. 安全边界
-**安全前提**:加密笔记本在关闭(锁定)状态下提供最强的应用级保护。锁定完成后,新操作被拒绝,受管 DEK 句柄和数据库连接已移除,内核管理的明文缓存、临时文件与令牌已尽力清理;这不承诺抹除 Go 运行时、操作系统交换区、崩溃转储或存储介质中的所有瞬时副本。**打开(解锁)状态下,应用持有可用 DEK 句柄**,此时已认证的应用内调用方——API、第三方插件、AI/LLM(含 MCP、智能体、语义搜索)——都可像读取普通笔记本一样读到明文内容。内核 CLI 是明确例外:无论锁定或解锁,都会拒绝加密笔记本及其原始文件。加密保护的是“静态数据”和“锁定后经受支持入口的不可达性”,**不保护“解锁后对已认证调用方的可见性”**。因此:解锁期间应视为“普通笔记本在使用”,并在用完后立即锁定。
+**安全前提**:加密笔记本在关闭(锁定)状态下提供最强的应用级保护。锁定完成后,新操作被拒绝,受管 DEK 句柄和数据库连接已移除,内核管理的明文缓存、临时文件与令牌已尽力清理;这不承诺抹除 Go 运行时、操作系统交换区、崩溃转储或存储介质中的所有瞬时副本。**打开(解锁)状态下,应用持有可用 DEK 句柄**,此时获得主应用授权的 API、第三方插件、AI/LLM(含 MCP、智能体、语义搜索)可像读取普通笔记本一样读到明文内容。发布服务是明确例外:发布读者与匿名访问者无论笔记本是否解锁均不可列举或读取加密笔记本,发布密码、可见性配置和 `publishAccess.json` 均不能覆盖该规则。内核 CLI 同样无论锁定或解锁都会拒绝加密笔记本及其原始文件。加密保护的是“静态数据”和“锁定后经受支持入口的不可达性”,**不保护“解锁后对主应用授权调用方的可见性”**。因此:解锁期间应视为“普通笔记本在主应用中使用”,并在用完后立即锁定。
**保护(磁盘上密文)**:
- `.sy` 文档正文(已加密)
@@ -278,6 +281,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
**API 防护**:
- `/api/file/*`:拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),避免密文泄漏或绕过加密层写入;工作空间 `temp/` 保持可访问
+- 发布服务:`RoleReader` 与 `RoleVisitor` 对加密笔记本及其文档、块、属性视图和资源始终不可访问;解锁状态和发布访问配置不改变该结果
- 内核 CLI:拒绝以加密笔记本或块 ID 为目标的命令,以及 `<工作区>/data/<加密笔记本 ID>/` 下的直接路径;不能用于解锁、读写、导出或操作加密笔记本数据
## 13. AI / LLM 可达性
@@ -295,6 +299,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
加密笔记本是孤岛,部分功能因其跨 notebook 特性或依赖全局聚合而未实现,属于功能边界,非性能或安全取舍。
- **闪卡 / 间隔重复**:牌组与调度跨 notebook 且依赖全局 SQLite 数据库,未实现。
+- **发布**:发布服务面向只读或匿名访问者,加密笔记本无论锁定或解锁均不参与发布,且不能通过发布密码或可见性配置启用。
- **书签**:全局聚合视图(扫全局 siyuan.db),加密笔记本 未接入。
- **标签**:全局聚合视图(扫全局 spans 表),加密笔记本 未接入。
- **资源文件重命名**:加密笔记本的 asset 文件名已脱敏为 `uuid-blockID.ext`,重命名会破坏原始名映射。
@@ -327,7 +332,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
下列场景不在本特性的保护范围内,界面和用户指南必须明确提示:
-- 笔记本解锁期间,已获应用授权的 API、插件、MCP、AI/LLM,以及能读取应用进程内存的本机攻击者,均可能取得明文。
+- 笔记本解锁期间,获得主应用授权的 API、插件、MCP、AI/LLM,以及能读取应用进程内存的本机攻击者,均可能取得明文;发布服务的读者与匿名访问者不属于该范围并始终被拒绝。
- 能读取工作空间文件的本机进程、管理员文件 API 和受信任插件可以读取尚未清理的临时明文导出物;临时目录不作为访问控制边界。
- 用户主动导出的文件、剪贴板、截图、打印件、分享给第三方的内容,以及保存在工作区外的明文文件,由用户负责保护。
- 操作系统交换分区、休眠映像、崩溃转储、文件系统快照和恶意软件不因“清除内存”而获得绝对保护;锁定仅做应用可控范围内的尽力清除。
@@ -382,7 +387,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
## 20. 功能边界、临时明文与接口规则
-不支持的闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。错误码和本地化文案应稳定,供调用方识别。
+不支持的发布、闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。发布访问判定必须独立于锁定状态并优先于 `publishAccess.json`,已存在的发布配置不得使加密笔记本重新可见。错误码和本地化文案应稳定,供调用方识别。
所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。加密笔记本的持久化目录始终拒绝原始入口直接访问,避免密文泄漏或绕过加密层写入;工作空间 `temp/` 是管理员文件 API、归档 API 和受信任插件可访问的通用临时空间,不属于加密访问控制边界。WebDAV 继续无条件拒绝整个 `temp/`,避免通过远程文件服务暴露临时数据。新增入口时必须分别评审其是否接触加密笔记本持久化目录或临时明文。
@@ -397,6 +402,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
| 场景 | 预期结果 |
|---|---|
| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问加密笔记本持久化目录 | 除明确允许暴露的笔记本名称外,不能解密、写入、复制、删除或列举加密内容;管理员文件 API 与受信任插件仍可访问 `temp/` 中尚未清理的导出副本 |
+| 通过发布服务访问锁定或解锁的加密笔记本,并分别使用匿名访问、发布读者账号以及 public/protected/private/forbidden 配置 | 均不可列举笔记本、文档、块、属性视图或资源,不能取得明文;锁定状态、发布认证和 `publishAccess.json` 不改变结果 |
| 解锁、锁定、应用重启和认证失败 | 只有 `Unlocked` 才能取得受管 DEK 句柄和数据库连接;失败和重启后入口拒绝访问,内核可控的明文缓存、临时文件与句柄完成尽力清理 |
| 锁定与响应生成、缓存发布、导出、预览、同步、索引或历史恢复并发 | 锁定在所有在途生命周期租约结束后才成功;成功后无晚到的明文响应、缓存回填、新建临时文件、可用令牌或数据库重连,删除失败的既有临时文件除外 |
| 同一加密笔记本内移动文档,随后清空缓存并重启 | 文件基名不变时密文保持不变并可按稳定对象 ID 认证解密;新父目录按普通笔记本语义生效,旧目录位置不存在,失败处理与普通笔记本一致 |
@@ -426,7 +432,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
- **锁定**:关闭该笔记本即等于锁定。内核停止新访问,等待或取消在途任务,撤销受管 DEK 句柄和数据库连接,并尽力清理内核管理的明文缓存、临时文件与令牌。**用完即锁**是最重要的安全习惯,能最大程度减少密钥和明文的暴露时间
- **重启后**:所有加密笔记本强制关闭,需重新输主密码解锁(受管 DEK 句柄只存在于进程内存,重启后需重新派生)
-> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,已认证的应用内调用方(API、插件、AI/LLM 含 MCP)都能像读普通笔记本一样读到明文;内核 CLI 始终拒绝操作加密笔记本(详见 §12 安全前提)。
+> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,获得主应用授权的调用方(API、插件、AI/LLM 含 MCP)能像读普通笔记本一样读到明文;发布服务的读者与匿名访问者以及内核 CLI 始终被拒绝(详见 §12 安全前提)。
### 修改主密码
进入 **设置 → 访问授权 → 修改主密码**。改密只需重新包络各笔记本的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。
@@ -447,6 +453,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
### 导入与导出
- **导入**:支持导入 `.sy.zip` 和 Markdown,内容在落盘前自动用 DEK 加密,与手动创建的文档一致
- **导出**:与普通笔记本一致(需先解锁,导出明文)。`.sy.zip`、HTML、Word、PDF、Markdown 等格式均支持;锁定状态下拒绝导出
+- **发布**:不支持。加密笔记本及其文档不会出现在发布服务中,解锁或设置发布密码也不能启用
### 忘记密码怎么办
**无法恢复**——这是设计使然(没有后门)。即使密文已同步到云端,没有主密码也解不开。**务必牢记主密码,建议使用密码管理器保存**。
@@ -464,6 +471,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
### 不适合用加密笔记本的场景
- 日常笔记、学习笔记(加密的额外开销不值得)
- 需要全局搜索的内容(加密笔记本不参与)
+- 需要通过发布服务对外提供的内容(加密笔记本不支持发布)
- 需要跨笔记本块引的知识网络(禁止跨边界)
- 需要跨笔记本移动整理的文档(禁止跨边界)
- 需要跨笔记本镜像数据库的场景(禁止跨边界)
diff --git a/kernel/api/block.go b/kernel/api/block.go
index 4f5b9ae231..6474c145df 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -642,6 +642,14 @@ func getRefIDs(c *gin.Context) {
}
id := arg["id"].(string)
+ requestedNotebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, requestedNotebook) {
+ ret.Data = map[string]any{
+ "refDefs": []model.RefDefs{},
+ "originalRefBlockIDs": map[string]string{},
+ }
+ return
+ }
refDefs, originalRefBlockIDs := model.GetBlockRefsInBox(id, encryptedNotebookFromArg(arg))
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
@@ -918,6 +926,11 @@ func getBlockDOM(c *gin.Context) {
}
id := arg["id"].(string)
+ requestedNotebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, requestedNotebook) {
+ ret.Data = map[string]string{"id": id, "dom": ""}
+ return
+ }
boxID := encryptedNotebookFromArg(arg)
dom := model.GetBlockDOMInBox(id, boxID)
@@ -956,6 +969,11 @@ func getBlockDOMs(c *gin.Context) {
ids = append(ids, id.(string))
}
+ requestedNotebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, requestedNotebook) {
+ ret.Data = map[string]string{}
+ return
+ }
boxID := encryptedNotebookFromArg(arg)
doms := model.GetBlockDOMsInBox(ids, boxID)
@@ -978,6 +996,11 @@ func getBlockDOMWithEmbed(c *gin.Context) {
}
id := arg["id"].(string)
+ requestedNotebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, requestedNotebook) {
+ ret.Data = map[string]string{"id": id, "dom": ""}
+ return
+ }
boxID := encryptedNotebookFromArg(arg)
isReadOnlyRole := model.IsReadOnlyRoleContext(c)
var publishAccess model.PublishAccess
@@ -1024,6 +1047,11 @@ func getBlockDOMsWithEmbed(c *gin.Context) {
ids = append(ids, id.(string))
}
+ requestedNotebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, requestedNotebook) {
+ ret.Data = map[string]string{}
+ return
+ }
boxID := encryptedNotebookFromArg(arg)
isReadOnlyRole := model.IsReadOnlyRoleContext(c)
var publishAccess model.PublishAccess
@@ -1052,6 +1080,10 @@ func encryptedNotebookFromArg(arg map[string]any) string {
return ""
}
+func isEncryptedNotebookDeniedForPublish(c *gin.Context, notebook string) bool {
+ return notebook != "" && model.IsReadOnlyRoleContext(c) && model.IsEncryptedBoxDeniedByPublishAccess(notebook)
+}
+
func filterBlockDOMsByPublishAccess(c *gin.Context, doms map[string]string, ids []string, boxID string, publishAccess model.PublishAccess, publishIgnore model.PublishAccess) {
for _, id := range ids {
if _, ok := doms[id]; !ok {
@@ -1096,6 +1128,11 @@ func getBlockKramdown(c *gin.Context) {
}
}
+ requestedNotebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, requestedNotebook) {
+ ret.Data = map[string]string{"id": id, "kramdown": ""}
+ return
+ }
boxID := encryptedNotebookFromArg(arg)
var kramdown string
if boxID != "" {
@@ -1156,6 +1193,11 @@ func getBlockKramdowns(c *gin.Context) {
}
}
+ requestedNotebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, requestedNotebook) {
+ ret.Data = map[string]string{}
+ return
+ }
boxID := encryptedNotebookFromArg(arg)
var kramdowns map[string]string
if boxID != "" {
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index ef8111b6da..403c168c3f 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -1270,6 +1270,15 @@ func listDocsByPath(c *gin.Context) {
return
}
+ if isEncryptedNotebookDeniedForPublish(c, notebook) {
+ ret.Data = map[string]any{
+ "box": notebook,
+ "path": p,
+ "files": []*model.File{},
+ }
+ return
+ }
+
sortParam := arg["sort"]
sortMode := util.SortModeUnassigned
if nil != sortParam {
@@ -1347,6 +1356,13 @@ func getDoc(c *gin.Context) {
if util.InvalidIDPattern(id, ret) {
return
}
+ requestedNotebook, _ := arg["notebook"].(string)
+ if model.IsReadOnlyRoleContext(c) &&
+ ((requestedNotebook != "" && model.IsEncryptedBoxDeniedByPublishAccess(requestedNotebook)) ||
+ model.IsEncryptedPublishRuntimeTarget(id)) {
+ ret.Code = 3
+ return
+ }
idx := arg["index"]
index := 0
if nil != idx {
@@ -1425,9 +1441,9 @@ func getDoc(c *gin.Context) {
var headingNumbers map[string]string
var err error
// 加密笔记本的打开文档走 InBox 版(查加密 blocktree + content db)
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ if requestedNotebook != "" && model.IsEncryptedBox(requestedNotebook) {
blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, err =
- model.GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, notebook)
+ model.GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, requestedNotebook)
} else {
blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, err =
model.GetDoc(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight)
@@ -1488,6 +1504,11 @@ func setPublishAccess(c *gin.Context) {
publishAccess := model.GetPublishAccess()
ID := arg["id"].(string)
+ if model.IsEncryptedPublishAccessTarget(ID) {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(313)
+ return
+ }
visible := arg["visible"].(bool)
password := arg["password"].(string)
disable := arg["disable"].(bool)
@@ -1544,7 +1565,13 @@ func getPublishAccess(c *gin.Context) {
var IDs []string
for _, ID := range arg["ids"].([]any) {
- IDs = append(IDs, ID.(string))
+ id := ID.(string)
+ if model.IsEncryptedPublishAccessTarget(id) {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(313)
+ return
+ }
+ IDs = append(IDs, id)
}
publishAccess := model.GetPublishAccess()
@@ -1586,6 +1613,11 @@ func authFilePublishAccess(c *gin.Context) {
if util.InvalidIDPattern(ID, ret) {
return
}
+ if model.IsEncryptedPublishRuntimeTarget(ID) {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(313)
+ return
+ }
password := arg["password"].(string)
publishAccess := model.GetPublishAccess()
diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.go
index 2e05361fef..dc4d009116 100644
--- a/kernel/api/filetree_test.go
+++ b/kernel/api/filetree_test.go
@@ -20,6 +20,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
"path/filepath"
"slices"
"strings"
@@ -28,6 +29,7 @@ import (
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -69,6 +71,177 @@ func TestSetSortRejectsInvalidRequest(t *testing.T) {
}
}
+func TestPublishAccessConfigurationRejectsEncryptedNotebook(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ const (
+ boxID = "20260726000000-encrypt"
+ docID = "20260726000001-encrypt"
+ )
+ oldDataDir := util.DataDir
+ oldPublishAccess := model.PublishAccess{}
+ if oldDataDir != "" {
+ oldPublishAccess = model.GetPublishAccess()
+ }
+ oldConf := model.Conf
+ oldLangs := util.Langs
+ util.DataDir = t.TempDir()
+ model.Conf = model.NewAppConf()
+ model.Conf.Lang = "test"
+ util.Langs = map[string]map[int]string{
+ "test": {313: "Encrypted notebooks do not support this operation"},
+ "en": {313: "Encrypted notebooks do not support this operation"},
+ }
+ if err := model.SetPublishAccess(model.PublishAccess{}); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ model.Conf = oldConf
+ util.Langs = oldLangs
+ if oldDataDir != "" {
+ if err := model.SetPublishAccess(oldPublishAccess); err != nil {
+ t.Errorf("restore publish access failed: %v", err)
+ }
+ }
+ })
+
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ if err := (&model.Box{ID: boxID}).SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(util.DataDir, boxID, docID+".sy"), []byte("{}"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ engine := gin.New()
+ engine.POST("/api/filetree/setPublishAccess", setPublishAccess)
+ engine.POST("/api/filetree/getPublishAccess", getPublishAccess)
+ engine.POST("/api/filetree/authFilePublishAccess", authFilePublishAccess)
+ tests := []struct {
+ name string
+ path string
+ body string
+ }{
+ {
+ name: "set",
+ path: "/api/filetree/setPublishAccess",
+ body: `{"id":"` + boxID + `","visible":true,"password":"","disable":false}`,
+ },
+ {
+ name: "get",
+ path: "/api/filetree/getPublishAccess",
+ body: `{"ids":["` + boxID + `"]}`,
+ },
+ {
+ name: "authenticate",
+ path: "/api/filetree/authFilePublishAccess",
+ body: `{"id":"` + boxID + `","password":""}`,
+ },
+ {
+ name: "set locked document",
+ path: "/api/filetree/setPublishAccess",
+ body: `{"id":"` + docID + `","visible":true,"password":"","disable":false}`,
+ },
+ {
+ name: "get locked document",
+ path: "/api/filetree/getPublishAccess",
+ body: `{"ids":["` + docID + `"]}`,
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, test.path, strings.NewReader(test.body))
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+
+ response := &struct {
+ Code int `json:"code"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal response failed: %v", err)
+ }
+ if response.Code != -1 {
+ t.Fatalf("encrypted notebook publish access returned code %d: %s", response.Code, recorder.Body.String())
+ }
+ })
+ }
+ if len(model.GetPublishAccess()) != 0 {
+ t.Fatal("encrypted notebook publish access should not be persisted")
+ }
+}
+
+func TestPublishReaderCannotBrowseEncryptedNotebook(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ const (
+ boxID = "20260726000000-encrypt"
+ docID = "20260726000001-encrypt"
+ )
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ })
+
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ if err := (&model.Box{ID: boxID}).SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, model.RoleReader)
+ c.Next()
+ })
+ engine.POST("/api/filetree/listDocsByPath", listDocsByPath)
+ engine.POST("/api/filetree/getDoc", getDoc)
+
+ listRecorder := httptest.NewRecorder()
+ listRequest := httptest.NewRequest(
+ http.MethodPost,
+ "/api/filetree/listDocsByPath",
+ strings.NewReader(`{"notebook":"`+boxID+`","path":"/"}`),
+ )
+ listRequest.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(listRecorder, listRequest)
+
+ listResponse := &struct {
+ Code int `json:"code"`
+ Data struct {
+ Files []any `json:"files"`
+ } `json:"data"`
+ }{}
+ if err := json.Unmarshal(listRecorder.Body.Bytes(), listResponse); err != nil {
+ t.Fatalf("unmarshal list response failed: %v", err)
+ }
+ if listResponse.Code != 0 || len(listResponse.Data.Files) != 0 {
+ t.Fatalf("publish reader enumerated encrypted notebook: %s", listRecorder.Body.String())
+ }
+
+ docRecorder := httptest.NewRecorder()
+ docRequest := httptest.NewRequest(
+ http.MethodPost,
+ "/api/filetree/getDoc",
+ strings.NewReader(`{"id":"`+docID+`","notebook":"`+boxID+`"}`),
+ )
+ docRequest.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(docRecorder, docRequest)
+
+ docResponse := &struct {
+ Code int `json:"code"`
+ }{}
+ if err := json.Unmarshal(docRecorder.Body.Bytes(), docResponse); err != nil {
+ t.Fatalf("unmarshal document response failed: %v", err)
+ }
+ if docResponse.Code != 3 {
+ t.Fatalf("publish reader accessed encrypted document: %s", docRecorder.Body.String())
+ }
+}
+
func TestFilterFileTreePublishAccess(t *testing.T) {
const (
boxID = "20260725000000-boxid01"
diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go
index f26eafe287..54f4ec56c4 100644
--- a/kernel/api/notebook.go
+++ b/kernel/api/notebook.go
@@ -334,6 +334,11 @@ func getNotebookConf(c *gin.Context) {
ret.Msg = "notebook [" + notebook + "] not found"
return
}
+ if model.IsReadOnlyRoleContext(c) && !isNotebookVisibleByPublishAccess(box, model.GetPublishAccess()) {
+ ret.Code = -1
+ ret.Msg = "notebook [" + notebook + "] not found"
+ return
+ }
boxConf := box.GetConf()
if !model.IsAdminRoleContext(c) {
@@ -479,7 +484,7 @@ func lsNotebooks(c *gin.Context) {
}
func isNotebookVisibleByPublishAccess(notebook *model.Box, publishAccess model.PublishAccess) bool {
- if nil == notebook || notebook.Closed {
+ if nil == notebook || notebook.Closed || notebook.Encrypted {
return false
}
diff --git a/kernel/api/notebook_security_test.go b/kernel/api/notebook_security_test.go
index f78f9d20f7..8ac2a3884b 100644
--- a/kernel/api/notebook_security_test.go
+++ b/kernel/api/notebook_security_test.go
@@ -41,6 +41,12 @@ func TestNotebookPublishVisibility(t *testing.T) {
}{
{name: "missing notebook", expected: false},
{name: "closed notebook", notebook: &model.Box{ID: boxID, Closed: true}, expected: false},
+ {
+ name: "encrypted notebook",
+ notebook: &model.Box{ID: boxID, Encrypted: true},
+ publishAccess: model.PublishAccess{{ID: boxID, Visible: true}},
+ expected: false,
+ },
{name: "default visible", notebook: &model.Box{ID: boxID}, expected: true},
{
name: "explicitly visible",
@@ -180,7 +186,7 @@ func TestGetNotebookInfoHidesInvisibleNotebookFromReader(t *testing.T) {
}
}
-func TestGetNotebookConfHidesBoxCryptFromReader(t *testing.T) {
+func TestGetNotebookConfHidesEncryptedNotebookFromReader(t *testing.T) {
gin.SetMode(gin.TestMode)
oldConf, oldDataDir := model.Conf, util.DataDir
@@ -214,12 +220,12 @@ func TestGetNotebookConfHidesBoxCryptFromReader(t *testing.T) {
}
tests := []struct {
- name string
- role model.Role
- expectBoxCrypt bool
+ name string
+ role model.Role
+ expectCode int
}{
- {name: "reader", role: model.RoleReader, expectBoxCrypt: false},
- {name: "administrator", role: model.RoleAdministrator, expectBoxCrypt: true},
+ {name: "reader", role: model.RoleReader, expectCode: -1},
+ {name: "administrator", role: model.RoleAdministrator, expectCode: 0},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -248,16 +254,25 @@ func TestGetNotebookConfHidesBoxCryptFromReader(t *testing.T) {
if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
t.Fatalf("unmarshal response failed: %v", err)
}
- if 0 != response.Code || nil == response.Data.Conf {
- t.Fatalf("unexpected response: %s", recorder.Body.String())
+ if test.expectCode != response.Code {
+ t.Fatalf("unexpected response code: %s", recorder.Body.String())
+ }
+ if model.RoleReader == test.role {
+ if nil != response.Data.Conf {
+ t.Fatalf("reader received encrypted notebook configuration: %s", recorder.Body.String())
+ }
+ return
+ }
+ if nil == response.Data.Conf {
+ t.Fatalf("administrator did not receive notebook configuration: %s", recorder.Body.String())
}
if response.Data.Conf.Encrypted != boxConf.Encrypted ||
response.Data.Conf.Name != boxConf.Name ||
response.Data.Conf.SortMode != boxConf.SortMode {
t.Fatalf("functional notebook settings were changed: %#v", response.Data.Conf)
}
- if test.expectBoxCrypt != (nil != response.Data.Conf.BoxCrypt) {
- t.Fatalf("unexpected box crypt visibility: %#v", response.Data.Conf.BoxCrypt)
+ if nil == response.Data.Conf.BoxCrypt {
+ t.Fatal("administrator did not receive encrypted notebook key metadata")
}
})
}
diff --git a/kernel/api/outline.go b/kernel/api/outline.go
index baa1ff142c..a12c7e8b7c 100644
--- a/kernel/api/outline.go
+++ b/kernel/api/outline.go
@@ -49,9 +49,14 @@ func getDocOutline(c *gin.Context) {
return
}
+ notebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, notebook) {
+ ret.Data = []*model.Path{}
+ return
+ }
var headings []*model.Path
var err error
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ if notebook != "" && model.IsEncryptedBox(notebook) {
headings, err = model.OutlineInBox(rootID, preview, notebook)
} else {
headings, err = model.Outline(rootID, preview)
@@ -92,9 +97,14 @@ func getDocHeadingNumbers(c *gin.Context) {
return
}
+ notebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, notebook) {
+ ret.Data = map[string]string{}
+ return
+ }
numbers := map[string]string{}
var err error
- if notebook, ok := arg["notebook"].(string); ok && "" != notebook && model.IsEncryptedBox(notebook) {
+ if notebook != "" && model.IsEncryptedBox(notebook) {
numbers, err = model.GetHeadingNumbers(rootID, notebook)
} else {
numbers, err = model.GetHeadingNumbers(rootID, "")
diff --git a/kernel/api/publish_encrypted_test.go b/kernel/api/publish_encrypted_test.go
new file mode 100644
index 0000000000..86185578f8
--- /dev/null
+++ b/kernel/api/publish_encrypted_test.go
@@ -0,0 +1,115 @@
+// 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.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestPublishReaderSearchAndBacklinkEncryptedNotebook(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ const boxID = "20260726000003-encrypt"
+ oldConf, oldDataDir := model.Conf, util.DataDir
+ util.DataDir = t.TempDir()
+ model.Conf = model.NewAppConf()
+ model.Conf.Editor = conf.NewEditor()
+ t.Cleanup(func() {
+ model.Conf, util.DataDir = oldConf, oldDataDir
+ })
+
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ if err := (&model.Box{ID: boxID}).SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, model.RoleReader)
+ c.Next()
+ })
+ engine.POST("/api/search/fullTextSearchBlock", fullTextSearchBlock)
+ engine.POST("/api/ref/getBacklink2", getBacklink2)
+
+ t.Run("search", func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(
+ http.MethodPost,
+ "/api/search/fullTextSearchBlock",
+ strings.NewReader(`{"query":"secret","notebook":"`+boxID+`"}`),
+ )
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+
+ response := &struct {
+ Code int `json:"code"`
+ Data struct {
+ Blocks []any `json:"blocks"`
+ MatchedBlockCount int `json:"matchedBlockCount"`
+ MatchedRootCount int `json:"matchedRootCount"`
+ PageCount int `json:"pageCount"`
+ DocMode bool `json:"docMode"`
+ } `json:"data"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal search response failed: %v", err)
+ }
+ if response.Code != 0 || len(response.Data.Blocks) != 0 || response.Data.MatchedBlockCount != 0 ||
+ response.Data.MatchedRootCount != 0 || response.Data.PageCount != 0 || response.Data.DocMode {
+ t.Fatalf("publish search exposed encrypted notebook metadata: %s", recorder.Body.String())
+ }
+ })
+
+ t.Run("backlink", func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(
+ http.MethodPost,
+ "/api/ref/getBacklink2",
+ strings.NewReader(`{"id":"20260726000004-encrypt","k":"","mk":"","notebook":"`+boxID+`"}`),
+ )
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+
+ response := &struct {
+ Code int `json:"code"`
+ Data struct {
+ Backlinks []any `json:"backlinks"`
+ LinkRefsCount int `json:"linkRefsCount"`
+ Backmentions []any `json:"backmentions"`
+ MentionsCount int `json:"mentionsCount"`
+ Box string `json:"box"`
+ } `json:"data"`
+ }{}
+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {
+ t.Fatalf("unmarshal backlink response failed: %v", err)
+ }
+ if response.Code != 0 || len(response.Data.Backlinks) != 0 || response.Data.LinkRefsCount != 0 ||
+ len(response.Data.Backmentions) != 0 || response.Data.MentionsCount != 0 || response.Data.Box != "" {
+ t.Fatalf("publish backlinks exposed encrypted notebook metadata: %s", recorder.Body.String())
+ }
+ })
+}
diff --git a/kernel/api/ref.go b/kernel/api/ref.go
index bde5ee43d2..3ee30c3e33 100644
--- a/kernel/api/ref.go
+++ b/kernel/api/ref.go
@@ -68,6 +68,7 @@ func getBackmentionDoc(c *gin.Context) {
if val, ok := arg["notebook"]; ok {
notebook = val.(string)
}
+ encryptedNotebookDenied := isEncryptedNotebookDeniedForPublish(c, notebook)
if notebook != "" && !model.IsEncryptedBox(notebook) {
notebook = ""
}
@@ -82,7 +83,7 @@ func getBackmentionDoc(c *gin.Context) {
var backlinks []*model.Backlink
var keywords []string
- if !isBacklinkDocAccessible(c, refTreeID) {
+ if encryptedNotebookDenied || !isBacklinkDocAccessible(c, refTreeID) {
backlinks, keywords = []*model.Backlink{}, []string{}
} else if notebook != "" && model.IsEncryptedBox(notebook) {
backlinks, keywords = model.GetBackmentionDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)
@@ -125,6 +126,7 @@ func getBacklinkDoc(c *gin.Context) {
if val, ok := arg["notebook"]; ok {
notebook = val.(string)
}
+ encryptedNotebookDenied := isEncryptedNotebookDeniedForPublish(c, notebook)
if notebook != "" && !model.IsEncryptedBox(notebook) {
notebook = ""
}
@@ -139,7 +141,7 @@ func getBacklinkDoc(c *gin.Context) {
var backlinks []*model.Backlink
var keywords []string
- if !isBacklinkDocAccessible(c, refTreeID) {
+ if encryptedNotebookDenied || !isBacklinkDocAccessible(c, refTreeID) {
backlinks, keywords = []*model.Backlink{}, []string{}
} else if notebook != "" && model.IsEncryptedBox(notebook) {
backlinks, keywords = model.GetBacklinkDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)
@@ -201,10 +203,12 @@ func getBacklink2(c *gin.Context) {
var linkRefsCount, mentionsCount int
// 加密笔记本的反链面板走 InBox 版(查加密 content db)
notebook, _ := arg["notebook"].(string)
- if notebook != "" && model.IsEncryptedBox(notebook) {
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBox(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook)
- } else {
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2(id, keyword, mentionKeyword, sort, mentionSort, containChildren)
+ if !isEncryptedNotebookDeniedForPublish(c, notebook) {
+ if notebook != "" && model.IsEncryptedBox(notebook) {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2InBox(id, keyword, mentionKeyword, sort, mentionSort, containChildren, notebook)
+ } else {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink2(id, keyword, mentionKeyword, sort, mentionSort, containChildren)
+ }
}
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
@@ -286,15 +290,20 @@ func getBacklink(c *gin.Context) {
var backlinks, backmentions []*model.Path
var linkRefsCount, mentionsCount int
// 加密笔记本的反链面板走 InBox 版(查加密 content db)
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklinkInBox(id, keyword, mentionKeyword, beforeLen, containChildren, notebook)
- } else {
- boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink(id, keyword, mentionKeyword, beforeLen, containChildren)
+ notebook, _ := arg["notebook"].(string)
+ if !isEncryptedNotebookDeniedForPublish(c, notebook) {
+ if notebook != "" && model.IsEncryptedBox(notebook) {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklinkInBox(id, keyword, mentionKeyword, beforeLen, containChildren, notebook)
+ } else {
+ boxID, backlinks, backmentions, linkRefsCount, mentionsCount = model.GetBacklink(id, keyword, mentionKeyword, beforeLen, containChildren)
+ }
}
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
backlinks = model.FilterPathsByPublishAccess(c, publishAccess, backlinks)
backmentions = model.FilterPathsByPublishAccess(c, publishAccess, backmentions)
+ linkRefsCount = countBacklinkPaths(backlinks)
+ mentionsCount = countBacklinkPaths(backmentions)
}
ret.Data = map[string]any{
"backlinks": backlinks,
diff --git a/kernel/api/search.go b/kernel/api/search.go
index 826df16e59..2403de0aca 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -468,6 +468,17 @@ func searchRefBlock(c *gin.Context) {
return
}
+ notebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, notebook) {
+ ret.Data = map[string]any{
+ "blocks": []*model.Block{},
+ "newDoc": false,
+ "k": util.EscapeHTML(arg["k"].(string)),
+ "reqId": reqId,
+ }
+ return
+ }
+
isSquareBrackets := false
if isSquareBracketsArg := arg["isSquareBrackets"]; nil != isSquareBracketsArg {
isSquareBrackets = isSquareBracketsArg.(bool)
@@ -485,7 +496,7 @@ func searchRefBlock(c *gin.Context) {
// 加密笔记本内的块引搜索走 InBox 版(只搜该 box 自己的加密 db,阻止跨加密边界引用)
var blocks []*model.Block
var newDoc bool
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ if notebook != "" && model.IsEncryptedBox(notebook) {
blocks, newDoc = model.SearchRefBlockInBox(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase, notebook)
} else {
blocks, newDoc = model.SearchRefBlock(id, rootID, keyword, beforeLen, isSquareBrackets, isDatabase)
@@ -520,11 +531,23 @@ func fullTextSearchBlock(c *gin.Context) {
return
}
+ notebook, _ := arg["notebook"].(string)
+ if isEncryptedNotebookDeniedForPublish(c, notebook) {
+ ret.Data = map[string]any{
+ "blocks": []*model.Block{},
+ "matchedBlockCount": 0,
+ "matchedRootCount": 0,
+ "pageCount": 0,
+ "docMode": false,
+ }
+ return
+ }
+
var blocks []*model.Block
var matchedBlockCount, matchedRootCount, pageCount int
var docMode bool
// 加密笔记本的全文搜索走 InBox 版(查加密 content db + blocks_fts)
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
+ if notebook != "" && model.IsEncryptedBox(notebook) {
if !model.IsBoxUnlocked(notebook) {
ret.Code = -1
ret.Msg = "encrypted notebook locked"
diff --git a/kernel/model/box.go b/kernel/model/box.go
index 37c2bcfbf6..045133f718 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -269,6 +269,7 @@ func (box *Box) saveConf0(data []byte) error {
util.ReportFileSysFatalError(err)
return fmt.Errorf("write box conf [%s] failed: %w", confPath, err)
}
+ invalidateEncryptedPublishAccessCache()
return nil
}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index d2f3cd32bf..fc0769088f 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -966,6 +966,7 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error
if boxEnc == nil || len(boxEnc.WrappedDEK) == 0 {
return errors.New("no encrypted key material for box")
}
+ invalidateEncryptedPublishAccessCache()
// 全局配置锁先于笔记本生命周期锁获取(设计 §17 锁顺序约定),避免与持子系统锁后回取配置锁的路径死锁。
// notebookCryptoMu 持锁期间调用的 deriveKEK/conf 修复只申请 Conf.m/cachedDEKsLock,不回取 box 生命周期锁。
@@ -1754,6 +1755,7 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
err = errors.New("encrypted notebook metadata verification failed after write")
return "", err
}
+ invalidateEncryptedPublishAccessCache()
// 复用刚派生的 DEK 直接开 db + 缓存,省去再次 Argon2id 解锁
cachedDEKsLock.Lock()
diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.go
index bfbb64ab46..54595c61a4 100644
--- a/kernel/model/publish_access.go
+++ b/kernel/model/publish_access.go
@@ -19,6 +19,7 @@ package model
import (
"errors"
"fmt"
+ "io/fs"
"math"
"net/http"
"os"
@@ -57,6 +58,17 @@ var (
publishAccessLock = sync.Mutex{}
)
+const publishAccessDenyAllID = "\x00"
+const encryptedPublishAccessCacheTTL = 5 * time.Second
+
+var encryptedPublishAccessCache = struct {
+ sync.Mutex
+ dataDir string
+ updatedAt time.Time
+ boxIDs map[string]struct{}
+ denyAll bool
+}{}
+
func GetPublishAccess() (ret PublishAccess) {
ret = PublishAccess{}
now := time.Now().UnixMilli()
@@ -126,6 +138,12 @@ func SetPublishAccess(inputPublishAccess PublishAccess) (err error) {
}
func GetInvisiblePublishAccess(inputPublishAccess PublishAccess) (outputPublishAccess PublishAccess) {
+ outputPublishAccess = filterInvisiblePublishAccess(inputPublishAccess)
+ outputPublishAccess = appendEncryptedBoxesToPublishAccess(outputPublishAccess)
+ return
+}
+
+func filterInvisiblePublishAccess(inputPublishAccess PublishAccess) (outputPublishAccess PublishAccess) {
outputPublishAccess = PublishAccess{}
for _, item := range inputPublishAccess {
if !item.Visible {
@@ -136,6 +154,12 @@ func GetInvisiblePublishAccess(inputPublishAccess PublishAccess) (outputPublishA
}
func GetDisablePublishAccess(inputPublishAccess PublishAccess) (outputPublishAccess PublishAccess) {
+ outputPublishAccess = filterDisablePublishAccess(inputPublishAccess)
+ outputPublishAccess = appendEncryptedBoxesToPublishAccess(outputPublishAccess)
+ return
+}
+
+func filterDisablePublishAccess(inputPublishAccess PublishAccess) (outputPublishAccess PublishAccess) {
outputPublishAccess = PublishAccess{}
for _, item := range inputPublishAccess {
if item.Disable {
@@ -145,6 +169,89 @@ func GetDisablePublishAccess(inputPublishAccess PublishAccess) (outputPublishAcc
return
}
+// appendEncryptedBoxesToPublishAccess 将加密笔记本加入发布拒绝列表,使发布访问规则独立于持久化配置和锁定状态。
+func appendEncryptedBoxesToPublishAccess(inputPublishAccess PublishAccess) PublishAccess {
+ ret := append(PublishAccess{}, inputPublishAccess...)
+ existing := map[string]struct{}{}
+ for _, item := range ret {
+ existing[item.ID] = struct{}{}
+ }
+
+ boxIDs, denyAll := encryptedBoxIDsForPublishAccess()
+ if denyAll {
+ return append(ret, &PublishAccessItem{ID: publishAccessDenyAllID, Disable: true})
+ }
+ for boxID := range boxIDs {
+ if _, ok := existing[boxID]; ok {
+ continue
+ }
+ ret = append(ret, &PublishAccessItem{ID: boxID, Disable: true})
+ }
+ return ret
+}
+
+// encryptedBoxIDsForPublishAccess 返回发布门禁使用的加密笔记本快照,避免在块和属性视图过滤热路径中重复读取配置。
+func encryptedBoxIDsForPublishAccess() (map[string]struct{}, bool) {
+ encryptedPublishAccessCache.Lock()
+ defer encryptedPublishAccessCache.Unlock()
+
+ now := time.Now()
+ if encryptedPublishAccessCache.boxIDs != nil &&
+ encryptedPublishAccessCache.dataDir == util.DataDir &&
+ now.Sub(encryptedPublishAccessCache.updatedAt) < encryptedPublishAccessCacheTTL {
+ return encryptedPublishAccessCache.boxIDs, encryptedPublishAccessCache.denyAll
+ }
+
+ boxIDs, err := listEncryptedBoxIDsForPublishAccess()
+ snapshot := map[string]struct{}{}
+ for _, boxID := range boxIDs {
+ snapshot[boxID] = struct{}{}
+ }
+ encryptedPublishAccessCache.dataDir = util.DataDir
+ encryptedPublishAccessCache.updatedAt = now
+ encryptedPublishAccessCache.boxIDs = snapshot
+ encryptedPublishAccessCache.denyAll = err != nil
+ if err != nil {
+ logging.LogErrorf("list encrypted notebooks for publish access failed: %s", err)
+ }
+ return snapshot, err != nil
+}
+
+func invalidateEncryptedPublishAccessCache() {
+ encryptedPublishAccessCache.Lock()
+ encryptedPublishAccessCache.updatedAt = time.Time{}
+ encryptedPublishAccessCache.boxIDs = nil
+ encryptedPublishAccessCache.Unlock()
+}
+
+// IsEncryptedBoxDeniedByPublishAccess 判断笔记本是否应被发布门禁拒绝。
+func IsEncryptedBoxDeniedByPublishAccess(boxID string) bool {
+ boxIDs, denyAll := encryptedBoxIDsForPublishAccess()
+ if denyAll {
+ return true
+ }
+ _, encrypted := boxIDs[boxID]
+ return encrypted
+}
+
+func listEncryptedBoxIDsForPublishAccess() ([]string, error) {
+ if util.DataDir == "" {
+ return []string{}, nil
+ }
+ dirs, err := os.ReadDir(util.DataDir)
+ if err != nil {
+ return nil, err
+ }
+
+ ret := []string{}
+ for _, dir := range dirs {
+ if dir.IsDir() && ast.IsNodeIDPattern(dir.Name()) && IsEncryptedBox(dir.Name()) {
+ ret = append(ret, dir.Name())
+ }
+ }
+ return ret, nil
+}
+
func PurgePublishAccess() {
publishAccess := GetPublishAccess()
IDs := []string{}
@@ -183,13 +290,66 @@ func PurgePublishAccess() {
func CheckPathAccessableByPublishIgnore(box string, path string, publishIgnore PublishAccess) bool {
for _, item := range publishIgnore {
- if item.ID == box || strings.Contains(path, item.ID) {
+ if item.ID == publishAccessDenyAllID || item.ID == box || strings.Contains(path, item.ID) {
return false
}
}
return true
}
+// IsEncryptedPublishRuntimeTarget 判断发布读取目标是否属于当前可解析的加密笔记本。
+func IsEncryptedPublishRuntimeTarget(id string) bool {
+ boxIDs, denyAll := encryptedBoxIDsForPublishAccess()
+ if denyAll {
+ return true
+ }
+ if _, ok := boxIDs[id]; ok {
+ return true
+ }
+ for boxID := range boxIDs {
+ if nil != treenode.GetBlockTreeInBox(id, boxID) {
+ return true
+ }
+ }
+ return false
+}
+
+// IsEncryptedPublishAccessTarget 判断发布访问配置目标是否属于加密笔记本,包括锁定笔记本中的文档。
+func IsEncryptedPublishAccessTarget(id string) bool {
+ if IsEncryptedPublishRuntimeTarget(id) {
+ return true
+ }
+
+ boxIDs, denyAll := encryptedBoxIDsForPublishAccess()
+ if denyAll {
+ return true
+ }
+ targetName := id + ".sy"
+ for boxID := range boxIDs {
+ found := false
+ err := filepath.WalkDir(filepath.Join(util.DataDir, boxID), func(_ string, entry os.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ if entry.IsDir() && (entry.Name() == ".siyuan" || entry.Name() == "assets") {
+ return fs.SkipDir
+ }
+ if !entry.IsDir() && entry.Name() == targetName {
+ found = true
+ return fs.SkipAll
+ }
+ return nil
+ })
+ if err != nil {
+ return true
+ }
+ if found {
+ return true
+ }
+ }
+ return false
+}
+
func GetPathPasswordByPublishAccess(box string, blockPath string, publishAccess PublishAccess) (passwordID string, password string) {
currentPath := blockPath
password = ""
@@ -236,16 +396,16 @@ func CheckBlockIdMetadataAccessableByPublishAccessInBox(c *gin.Context, publishA
}
func CheckBlockTreeMetadataAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, bt *treenode.BlockTree) bool {
- if bt == nil {
+ if bt == nil || IsEncryptedBoxDeniedByPublishAccess(bt.BoxID) {
return false
}
- publishDisable := GetDisablePublishAccess(publishAccess)
+ publishDisable := filterDisablePublishAccess(publishAccess)
if !CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishDisable) {
return false
}
- publishInvisible := GetInvisiblePublishAccess(publishAccess)
+ publishInvisible := filterInvisiblePublishAccess(publishAccess)
if CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishInvisible) {
return true
}
@@ -260,22 +420,22 @@ func CheckBlockIdDiscoverableByPublishAccessInBox(publishAccess PublishAccess, b
}
func CheckBlockTreeDiscoverableByPublishAccess(publishAccess PublishAccess, bt *treenode.BlockTree) bool {
- if bt == nil {
+ if bt == nil || IsEncryptedBoxDeniedByPublishAccess(bt.BoxID) {
return false
}
- publishInvisible := GetInvisiblePublishAccess(publishAccess)
- publishDisable := GetDisablePublishAccess(publishAccess)
+ publishInvisible := filterInvisiblePublishAccess(publishAccess)
+ publishDisable := filterDisablePublishAccess(publishAccess)
return CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishInvisible) &&
CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishDisable)
}
func checkBlockTreeAccessableByPublishAccess(c *gin.Context, publishAccess PublishAccess, bt *treenode.BlockTree) bool {
- if bt == nil {
+ if bt == nil || IsEncryptedBoxDeniedByPublishAccess(bt.BoxID) {
return false
}
- publishIgnore := GetDisablePublishAccess(publishAccess)
+ publishIgnore := filterDisablePublishAccess(publishAccess)
passwordID, password := GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)
return CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) && (password == "" || CheckPublishAuthCookie(c, passwordID, password))
}
@@ -1064,13 +1224,13 @@ func FilterContentByPublishAccess(c *gin.Context, publishAccess PublishAccess, b
func FilterEmbedBlocksByPublishAccess(c *gin.Context, publishAccess PublishAccess, embedBlocks []*EmbedBlock) (ret []*EmbedBlock) {
ret = []*EmbedBlock{}
+ publishIgnore := GetDisablePublishAccess(publishAccess)
for _, embedBlock := range embedBlocks {
if nil == embedBlock || nil == embedBlock.Block {
continue
}
block := embedBlock.Block
- publishIgnore := GetDisablePublishAccess(publishAccess)
passwordID, password := GetPathPasswordByPublishAccess(block.Box, block.Path, publishAccess)
accessible := CheckPathAccessableByPublishIgnore(block.Box, block.Path, publishIgnore) &&
(password == "" || CheckPublishAuthCookie(c, passwordID, password))
diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.go
index 2cda88eacd..9a78c06863 100644
--- a/kernel/model/publish_access_test.go
+++ b/kernel/model/publish_access_test.go
@@ -17,12 +17,16 @@
package model
import (
+ "encoding/json"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -64,6 +68,88 @@ func TestCheckBlockTreeAccessableByPublishAccess(t *testing.T) {
}
}
+func TestEncryptedNotebookDeniedByPublishAccess(t *testing.T) {
+ const (
+ boxID = "20260726000000-encrypt"
+ docID = "20260726000001-encrypt"
+ )
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ invalidateEncryptedPublishAccessCache()
+ })
+
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ if err := (&Box{ID: boxID}).SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+
+ bt := &treenode.BlockTree{
+ ID: docID,
+ BoxID: boxID,
+ Path: "/" + docID + ".sy",
+ }
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
+ publishAccess := PublishAccess{{ID: boxID, Visible: true, Password: "password"}}
+
+ if CheckPathAccessableByPublishIgnore(boxID, bt.Path, GetInvisiblePublishAccess(publishAccess)) {
+ t.Fatal("encrypted notebook should be invisible to publish readers")
+ }
+ if CheckPathAccessableByPublishIgnore(boxID, bt.Path, GetDisablePublishAccess(publishAccess)) {
+ t.Fatal("encrypted notebook should be disabled for publish access")
+ }
+ if checkBlockTreeAccessableByPublishAccess(c, publishAccess, bt) {
+ t.Fatal("encrypted notebook content should not be accessible through publish")
+ }
+ if CheckBlockTreeMetadataAccessableByPublishAccess(c, publishAccess, bt) {
+ t.Fatal("encrypted notebook metadata should not be accessible through publish")
+ }
+ if CheckBlockTreeDiscoverableByPublishAccess(publishAccess, bt) {
+ t.Fatal("encrypted notebook should not be discoverable through publish")
+ }
+}
+
+func TestEncryptedPublishAccessCacheInvalidation(t *testing.T) {
+ const boxID = "20260726000002-encrypt"
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ invalidateEncryptedPublishAccessCache()
+ t.Cleanup(func() {
+ util.DataDir = oldDataDir
+ invalidateEncryptedPublishAccessCache()
+ })
+
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ box := &Box{ID: boxID}
+ if err := box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ if !IsEncryptedBoxDeniedByPublishAccess(boxID) {
+ t.Fatal("encrypted notebook should be present in publish access cache")
+ }
+
+ boxConf.Encrypted = false
+ data, err := json.MarshalIndent(boxConf, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"), data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if !IsEncryptedBoxDeniedByPublishAccess(boxID) {
+ t.Fatal("publish access should reuse its cached encrypted notebook snapshot")
+ }
+
+ invalidateEncryptedPublishAccessCache()
+ if IsEncryptedBoxDeniedByPublishAccess(boxID) {
+ t.Fatal("invalidated publish access cache should reload notebook encryption state")
+ }
+}
+
func TestCheckBlockTreeMetadataAccessableByPublishAccess(t *testing.T) {
const (
boxID = "20260725000000-boxid01"