An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Restore workspace temp access for file APIs https://github.com/siyuan-note/siyuan/issues/18309
Daniel99f8e07992d9
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 76dd157839..b9b08257ca 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -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); opening performs a full rebuild into the encrypted SQLite database |-| **/api/file/getFile + putFile** | Can read/write any file | Refuses reads/writes of any file under encrypted notebooks (not just .sy) and kernel-managed encrypted-notebook plaintext temporary directories; legitimate reads/writes go through dedicated APIs (encryption-aware) |+| **/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.@@ -272,11 +272,12 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma- MasterSalt/KEKVerifier in `conf.json` (designed to be plaintext: salt is not secret, verifier is ciphertext)- BoxConf.WrappedDEK (ciphertext, requires KEK to unwrap)- DEK-derived values and transient plaintext copies that may be created by the process or operating system, including swap, hibernation images, and crash dumps; locking revokes managed key handles and best-effort clears application-controlled caches only+- Plaintext exports under `temp/` that have not yet been cleaned up; administrator file APIs, archive APIs, trusted plugins, and local processes can access them- 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-notebook asset filenames are desensitized to `uuid-blockID.ext` but the extension is visible; old ciphertext retained in sync endpoints or historical snapshots is held by those storage providers, and the encrypted notebook cannot revoke their copies.**API protection**:-- `/api/file/getFile`, `/api/file/putFile`, `/api/file/copyFile`, `/api/file/renameFile`, `/api/file/removeFile`: refuse to read/write any file under an encrypted notebook (not just .sy), preventing ciphertext leakage or plaintext corruption; legitimate reads/writes go through dedicated APIs (encryption-aware).+- `/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.- 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@@ -327,12 +328,13 @@ This feature protects data-at-rest confidentiality and inaccessibility through sThe 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.+- 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.- A sync service or backup holder may retain, delete, replace, or roll back ciphertext. Replacement and rollback can cause denial of service or data rollback; they cannot decrypt valid ciphertext without the master password.- Parent directories are excluded from AAD, so an attacker who can write workspace ciphertext may move valid ciphertext with an unchanged basename within the same notebook, and the application treats the new parent as the current document topology. Content, notebook, object type, and stable object ID remain authenticated, but parent-directory topology has no cryptographic integrity guarantee.-"Only ciphertext remains after locking" means that kernel-managed persistent workspace storage should contain no readable plaintext and that managed temporary files, caches, and key handles have undergone best-effort cleanup. It excludes files deliberately exported to an external location and does not promise erasure of transient or historical copies retained by the process, operating system, or underlying storage medium.+"Only ciphertext remains after locking" means that encrypted-notebook persistent data remains encrypted and that managed temporary files, caches, and key handles have undergone best-effort cleanup. It does not guarantee that workspace `temp/` contains no plaintext left by a crash, file lock, or permission error. It also 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.## 17. State Machine and Concurrency Rules@@ -341,11 +343,11 @@ The global state is `Disabled`, `Enabled`, or `RecoveryRequired`. In normal stea| Transition | Preconditions | Invariants after success | Failure handling ||---|---|---|---|| `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 → 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 | Enter `Locked` after key and database cleanup; a temporary-file cleanup failure only records diagnostics without plaintext and is retried on exit or next startup || `Unlocked → Error` | Ciphertext authentication fails, database opening fails, or an invariant is violated | Immediately deny reads and writes; never fall back to a normal-notebook path | Close resources and retain diagnostics without plaintext; the user can only lock or unlock again || Change master password | All encrypted notebooks are `Locked` | All WrappedDEKs, global configuration, and backup update as one recoverable transaction | Keep old configuration and backup usable; no subset of notebooks becomes unlockable only with the new password |-One lifecycle controller per notebook manages state, operation admission, and the active-operation count. Reads, edits, exports, previews, sync, indexing, history view or restore, and AI/MCP access obtain a shared lifecycle lease only while `Unlocked`, and hold it through parsing, cache publication, HTTP response or download completion, and asynchronous-result registration. Lock and delete atomically change the state to `Locking` and close admission, acquire the exclusive lifecycle lease after cancelling or draining active work, then close databases, clean caches and temporary artifacts, and revoke managed DEK handles while exclusive. They publish `Locked` only after cleanup succeeds. No late plaintext response, cache refill, temporary file, or database reconnection may occur after locking completes.+One lifecycle controller per notebook manages state, operation admission, and the active-operation count. Reads, edits, exports, previews, sync, indexing, history view or restore, and AI/MCP access obtain a shared lifecycle lease only while `Unlocked`, and hold it through parsing, cache publication, HTTP response or download completion, and asynchronous-result registration. Lock and delete atomically change the state to `Locking` and close admission, acquire the exclusive lifecycle lease after cancelling or draining active work, then close databases, revoke managed DEK handles, and best-effort clean caches and temporary artifacts while exclusive. They publish `Locked` after key handles and database connections are removed; a temporary-file deletion failure does not block locking, but it is logged and retried on exit or next startup. No new plaintext response, cache refill, or database reconnection may occur after locking completes, but a temporary plaintext copy whose deletion failed may remain on disk.The global configuration lock is acquired before any notebook lifecycle lock. An operation involving multiple notebooks acquires lifecycle locks in lexicographic boxID order. DEK-cache, database, file, and other subsystem locks are acquired only after lifecycle locks and released before them. Reverse acquisition, reacquiring the global configuration lock while holding a subsystem lock, and acquiring a lower-level lock while holding a higher-level one are forbidden. Auto-lock stores activity time per notebook, but one authenticated user interaction in the current workspace or an explicit keepalive refreshes every unlocked notebook together. A periodic job checks elapsed time using the system clock, so a system-clock adjustment can advance or delay the trigger accordingly; auto-lock is a convenience protection, not a precise security timing boundary.@@ -382,32 +384,28 @@ Sync endpoints and offline backups are storage that may be lost, copied, or rollUnsupported flashcards, bookmarks, tags, asset rename, unused-asset cleanup, and unused-database cleanup must be handled uniformly by the frontend, HTTP API, plugin API, MCP, and import paths: return an explicit "unsupported" error for encrypted-notebook targets and create no global index, global attribute, or deferred task. Existing legacy data must not be loaded, aggregated, or written back. Error codes and localized messages remain stable for callers.-Every raw entry point that might bypass dedicated read/write paths is registered, including file APIs, kernel CLI, MCP file tools, WebDAV, plugin file interfaces, export download URLs, preview URLs, and background tasks. The registry covers encrypted-notebook directories and kernel-managed plaintext temporary roots. A temporary root is outside the generic raw-file namespace or denied unconditionally by every raw file API; denial must not depend on whether the notebook still exists or whether its `Encrypted` flag remains queryable. Adding an entry point requires review of whether it can read, write, copy, rename, delete, or enumerate encrypted and controlled-temporary directories.+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.-### Locally Persistent Global Deny-Access Records+### Temporary Plaintext Lifecycle-> **Implementation status**: The persistent `encrypted-deny-access.json` registry and the periodic cleanup janitor described below are not yet implemented. The current release relies on (1) an in-memory export-token map (`managedEncryptedExports`, with a 1-hour expiry, revoked on lock or notebook deletion), and (2) the WebDAV layer unconditionally denying the entire `temp/` directory. Leftover plaintext in `temp/export/` after a kernel crash has no persistent tracking or retry cleanup for the time being; this is a known limitation. The specification below describes the intended design.+Exports have two classes: a user-selected external destination may contain plaintext after a risk prompt; kernel-managed previews, conversions, downloads, and intermediates use `temp/export/<boxID>/<kind>/<exportID>/`. The first-level boxID identifies cleanup ownership, not access permission. Normal exports and plugin temporary files must not use a valid boxID as their first-level name under `temp/export/`.-“Global” means that a record remains effective independently of a notebook lifecycle after that notebook has been deleted; it does not mean cross-device synchronization. Records persist at `<ConfDir>/encrypted-deny-access.json`, outside `DataDir` and the dejavu synchronization scope, and manage only local controlled temporary artifacts. Each record contains at least a format version, random artifact ID, boxID, canonical path relative to a controlled root, purpose, creation time, most recent retry time, retry count, and an error class containing no original content or sensitive absolute path. Updates use a temporary write, file sync, atomic replacement, and directory sync. A recorded path is revalidated as a descendant of a controlled temporary root; an escaping or malformed record is never used to delete an arbitrary path and instead raises a security error and triggers a controlled-root rescan.--A deny record stores cleanup state and diagnostics; it is not the access-control authority. File APIs, downloads, previews, plugins, MCP, WebDAV, and background tasks unconditionally deny the entire controlled-plaintext temporary namespace by canonical path even when the notebook, registry file, or individual record no longer exists. The janitor runs at application startup, immediately after lock or delete and after export completion or failure, and periodically retries with capped exponential backoff. It atomically removes a record only after cleanup succeeds and the path is confirmed absent. Persistent failure retains the record and the `Error` or global-denial state; exhausting retries never opens access. If the registry is manually deleted, loses entries, or cannot be parsed, access remains denied, and startup and periodic scans reconstruct records from residual controlled-root entries before cleanup continues. Cleanup is complete only after the artifact is confirmed absent and record deletion is committed.--Exports have two classes: a user-selected external destination may contain plaintext after a risk prompt; kernel-managed previews, conversions, downloads, and intermediates exist only in a controlled temporary directory scoped by `boxID` and are accessed through minimum-privilege tokens bound to the user, `boxID`, purpose, and expiration. Locking, cancellation, failure, application exit, and export completion invalidate tokens and asynchronous results immediately, then best-effort clean kernel-managed plaintext. On cleanup failure, an existing notebook enters `Error`; a deleted notebook leaves a global deny-access marker while a janitor retries. Deletion or locking of a notebook must never expose that path through a generic file entry point. Logs, error reports, thumbnails, OCR/conversion output, and clipboard handling follow the same rule: no plaintext by default unless the user explicitly sends content to an external program.+The in-memory `managedEncryptedExports` tokens manage download-link expiry and lifecycle; they are not a security boundary against local files, administrator APIs, or trusted plugins. Lock, delete, cancellation, failure, and normal exit revoke related tokens and best-effort remove `temp/export/<boxID>`. At application startup, entries whose first-level name is a valid boxID are at least scanned and removed; generic desktop temporary-directory initialization also clears the entire `temp/export` directory. No caller may rely on files under `temp/` surviving across processes. Deletion failure only records diagnostics without plaintext and does not prevent the notebook from entering `Locked`; exit or the next startup retries cleanup. Logs, error reports, thumbnails, OCR/conversion output, and clipboard handling contain 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 |+| 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 || 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 |+| 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 || Refs, moves, mirrors, assets, and database operations between an encrypted notebook and a normal notebook or another encrypted notebook | Island boundaries hold; rejection creates no partial files, global indexes, or relation data || Asset-ciphertext write or name-mapping update fails | The whole logical transaction fails and rolls back; the caller receives an error, with no accessible orphan, missing mapping, or plaintext temporary file || Delete an encrypted notebook while retaining history, then disable or restore | A key dependency prevents deletion of global config and backup; the matching backup and master password restore the notebook, and only explicit permanent purge removes the dependency || Move a document's parent directory or change its basename after creating history, then view or restore the old entry | Authenticate and decrypt with the snapshot boxID, object type, and stable basename recorded by the history entry; rollback re-envelopes only when the target basename changes, while missing snapshot context rejects the operation |-| 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 |+| Disk inspection of files, assets, databases, WAL/SHM, history, snapshots, and logs | No readable body, asset contents, original asset names, or plaintext SQLite pages exist in encrypted-notebook persistent locations; `temp/` may contain plaintext during export or after cleanup failure |+| Restart after an abnormal exit | Startup removes at least entries under `temp/export/` whose first-level name is a valid boxID; generic temporary-directory initialization may also remove other exports and plugin temporary files || 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 |diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex 9f97f438e4..c7b2b8aca6 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -66,7 +66,7 @@| **数据同步** | dejavu 同步明文 | 不改(密文进密文出,闭环自洽) || **删除笔记本** | 删目录 | 删目录 + 删加密 SQLite 数据库 文件 + 删笔记本级数据库存储 || **重建索引** | 全量 | 启动时跳过(已关闭);打开时全量重建到加密 SQLite 数据库 |-| **/api/file/getFile + putFile** | 可读写任意文件 | 拒绝读写加密笔记本下的任何文件(不只 .sy)以及内核管理的加密笔记本明文临时目录,防止密文泄漏或明文破坏;合法读写走专用 API |+| **/api/file/\*** | 可读写、复制、重命名、删除或列举工作空间文件 | 拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),防止密文泄漏或绕过加密层写入;`temp/` 仍可由管理员文件 API 和受信任插件访问 |**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、文档和 数据库文件不进出边界。笔记本内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 也可用(与普通笔记本一致)。加密笔记本之间也互相隔离。普通笔记本完全不受影响。@@ -272,11 +272,12 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i- `conf.json` 里的 MasterSalt/KEKVerifier(设计可明文:salt 不保密,verifier 是密文)- BoxConf.WrappedDEK(密文,需 KEK 解开)- 进程和操作系统可能产生的 DEK 派生值、明文瞬时副本、交换区、休眠映像或崩溃转储;锁定只保证撤销受管密钥句柄和尽力清理应用可控缓存+- `temp/` 中尚未清理的明文导出物;管理员文件 API、归档 API、受信任插件和本机进程均可访问- 历史索引的 content 字段(留空,不存明文也不存密文)- **元数据泄漏**(加密不掩盖以下信息):文件数量、目录结构、文件大小、修改时间(mtime)、asset 文件扩展名、blockID 时间戳。加密笔记本的 asset 文件名虽脱敏为 `uuid-blockID.ext`,但扩展名可见;同步端/历史快照中的旧密文也由各存储方自行保管,加密笔记本无法吊销其副本**API 防护**:-- `/api/file/getFile`、`/api/file/putFile`、`/api/file/copyFile`、`/api/file/renameFile`、`/api/file/removeFile`:拒绝读写加密笔记本下的任何文件(不只 .sy),避免密文泄漏或明文破坏;合法读写走专用 API(已加密感知)+- `/api/file/*`:拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),避免密文泄漏或绕过加密层写入;工作空间 `temp/` 保持可访问- 内核 CLI:拒绝以加密笔记本或块 ID 为目标的命令,以及 `<工作区>/data/<加密笔记本 ID>/` 下的直接路径;不能用于解锁、读写、导出或操作加密笔记本数据## 13. AI / LLM 可达性@@ -327,12 +328,13 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i下列场景不在本特性的保护范围内,界面和用户指南必须明确提示:- 笔记本解锁期间,已获应用授权的 API、插件、MCP、AI/LLM,以及能读取应用进程内存的本机攻击者,均可能取得明文。+- 能读取工作空间文件的本机进程、管理员文件 API 和受信任插件可以读取尚未清理的临时明文导出物;临时目录不作为访问控制边界。- 用户主动导出的文件、剪贴板、截图、打印件、分享给第三方的内容,以及保存在工作区外的明文文件,由用户负责保护。- 操作系统交换分区、休眠映像、崩溃转储、文件系统快照和恶意软件不因“清除内存”而获得绝对保护;锁定仅做应用可控范围内的尽力清除。- 同步服务或备份持有者可以保留、删除、替换或回滚密文;这些行为可能造成拒绝服务或数据回退,但不能在不知道主密码时解密有效密文。- 父目录不进入 AAD,因此能够写工作空间密文的攻击者可以在同一笔记本内移动一个文件基名不变的有效密文,应用会把新父目录视为当前文档层级;内容、笔记本、对象类型和稳定对象 ID 仍受认证,但父目录层级本身不提供密码学完整性。-“锁定后仅剩密文”只表示内核管理的持久化工作空间中不应存在可读明文,并且受管临时文件、缓存和密钥句柄已经完成尽力清理;不包括用户明确导出到外部位置的文件,也不承诺抹除进程、操作系统或底层存储介质已经保留的瞬时或历史副本。+“锁定后仅剩密文”只表示加密笔记本的持久化数据保持加密,并且受管临时文件、缓存和密钥句柄已经执行尽力清理;它不保证工作空间 `temp/` 中不存在因崩溃、文件占用或权限错误而残留的明文,也不包括用户明确导出到外部位置的文件,且不承诺抹除进程、操作系统或底层存储介质已经保留的瞬时或历史副本。## 17. 状态机与并发规则@@ -341,11 +343,11 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i| 转换 | 前置条件 | 成功后的不变量 | 失败处理 ||---|---|---|---|| `Locked → Unlocking → Unlocked` | 主密码验证成功且密文配置匹配 | 可用 DEK 句柄仅存在于受管内存;专属数据库已打开;允许笔记本专用入口 | 撤销派生的 KEK/DEK 句柄、关闭已打开资源并回到 `Locked` |-| `Unlocked → Locking → Locked` | 原子地关闭新操作准入,并等待在途操作结束或取消 | 无可用受管 DEK 句柄或数据库连接;内核管理的明文缓存、临时文件与令牌已尽力清理 | 保持拒绝访问并进入 `Error`,记录不含明文的诊断;继续重试清理,未恢复不变量前不得重新开放 |+| `Unlocked → Locking → Locked` | 原子地关闭新操作准入,并等待在途操作结束或取消 | 无可用受管 DEK 句柄或数据库连接;内核管理的明文缓存、临时文件与令牌已尽力清理 | 密钥和数据库清理完成后仍进入 `Locked`;临时文件清理失败只记录不含明文的诊断,并在退出或下次启动时重试 || `Unlocked → Error` | 密文认证失败、数据库打开失败或不变量被破坏 | 立即拒绝读写,绝不回退到普通笔记本路径 | 关闭资源,诊断信息不得含明文;用户只能锁定或重新解锁 || 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK、全局配置和备份作为一个可恢复事务更新 | 保留旧配置和备份可用;不得出现仅能用新密码解锁的部分笔记本 |-每个笔记本使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、清理缓存和临时产物并撤销受管 DEK 句柄;只有清理成功才发布 `Locked`。因此锁定完成后,不得再出现晚到的明文响应、缓存回填、临时文件或数据库重连。+每个笔记本使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、撤销受管 DEK 句柄,并尽力清理缓存和临时产物。密钥句柄和数据库连接清理完成后发布 `Locked`;临时文件删除失败不阻止锁定,但必须记录诊断并在退出或下次启动时重试。因此锁定完成后不得再出现新的明文响应、缓存回填或数据库重连,但磁盘上可能保留清理失败的临时明文副本。全局配置锁必须先于任何笔记本生命周期锁获取;同时涉及多个笔记本时按 boxID 字典序获取生命周期锁;DEK 缓存、数据库、文件和其他子系统锁只能在生命周期锁之后获取,并在释放生命周期锁前释放。禁止逆序获取,禁止持有子系统锁时回取全局配置锁或其他较低层级锁。自动锁定按每个笔记本保存活动时间,但当前工作区的一次认证用户交互或显式保活会统一刷新所有已解锁笔记本;计时采用系统时钟并由周期任务检查,系统时钟调整可能相应提前或推迟触发时间,自动锁定是便利性保护而不是精确的安全计时边界。@@ -382,32 +384,28 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明不支持的闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。错误码和本地化文案应稳定,供调用方识别。-所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。登记表同时覆盖加密笔记本目录和内核管理的明文临时根目录;临时目录必须位于通用原始文件命名空间之外,或被所有原始文件 API 无条件拒绝,不能依赖当前笔记本是否仍存在或 `Encrypted` 标志是否仍可查询。新增入口时必须评审其是否可读取、写入、复制、重命名、删除或列举加密目录与受控临时目录。+所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。加密笔记本的持久化目录始终拒绝原始入口直接访问,避免密文泄漏或绕过加密层写入;工作空间 `temp/` 是管理员文件 API、归档 API 和受信任插件可访问的通用临时空间,不属于加密访问控制边界。WebDAV 继续无条件拒绝整个 `temp/`,避免通过远程文件服务暴露临时数据。新增入口时必须分别评审其是否接触加密笔记本持久化目录或临时明文。-### 本机持久化的全局拒绝访问记录+### 临时明文生命周期-> **当前实现状态**:下文描述的持久化 `encrypted-deny-access.json` 注册表与周期性清理 janitor 尚未实现。当前版本依赖(1)内存态导出令牌(`managedEncryptedExports`,1 小时过期,锁定或删除笔记本时撤销);(2)WebDAV 层对整个 `temp/` 目录的无条件拒绝。内核崩溃后 `temp/export/` 残留明文暂无持久化追踪与重试清理,属已知限制。下文规格描述的是目标设计。+导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物统一放在 `temp/export/<boxID>/<kind>/<exportID>/`。第一层 boxID 是清理归属标识,不是访问权限;普通导出和插件临时文件不得使用合法 boxID 作为 `temp/export/` 的第一层名称。-“全局”表示记录在笔记本已删除后仍独立于该笔记本生命周期生效,不表示跨设备同步。记录持久化在 `<ConfDir>/encrypted-deny-access.json`,位于 `DataDir` 和 dejavu 同步范围之外,仅管理本机受控临时产物。每项记录至少包含格式版本、随机产物 ID、boxID、受控根目录下的规范相对路径、用途、创建时间、最近重试时间、重试次数和不含原始内容或敏感路径的错误类别;文件使用临时写入、同步落盘、原子替换和目录同步更新。记录中的路径必须重新校验为受控临时根目录的后代,越界或格式损坏的记录不得用于删除任意文件,并触发安全错误和受控根目录重新扫描。--拒绝记录只保存清理状态和诊断信息,不是访问控制依据。文件 API、下载、预览、插件、MCP、WebDAV 和后台任务按规范路径无条件拒绝整个受控明文临时命名空间,即使笔记本、记录文件或单项记录已经不存在。清理器在应用启动、锁定或删除、导出结束或失败后立即运行,并周期性按有上限的指数退避重试;清理成功且确认路径不存在后原子删除对应记录,持续失败则保留记录并维持 `Error` 或全局拒绝状态,不得因超过重试次数自动放行。记录文件被人为删除、部分条目丢失或文件无法解析时,访问仍保持拒绝;启动和周期扫描从受控根目录残留重建记录后继续清理。只有产物已确认不存在且记录已提交删除,才算清理完成。--导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物只能位于带 boxID 的受控临时目录,并通过绑定用户、boxID、用途和有效期的最小权限令牌访问。锁定、取消、失败、应用退出和导出完成后都必须使令牌与异步结果立即失效,再尽力清理内核管理的明文;清理失败时,笔记本仍存在则进入 `Error`,笔记本已删除则保留全局拒绝访问标记,并由后台清理器重试,不能因笔记本已删除或锁定而让通用文件入口重新暴露该路径。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。+内存态导出令牌 `managedEncryptedExports` 用于管理下载链接的有效期和生命周期,不作为本机文件、管理员 API 或受信任插件的安全隔离。锁定、删除、取消、失败和正常退出时必须撤销相关令牌,并尽力删除 `temp/export/<boxID>`;应用启动时至少扫描并删除第一层名称为合法 boxID 的残留目录,桌面端的通用临时目录初始化还会清空整个 `temp/export`。任何调用方都不得依赖 `temp/` 中的文件跨进程存续。删除失败只记录不含明文的诊断,不阻止笔记本进入 `Locked`,后续退出或启动时继续尝试。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。## 21. 安全验收矩阵| 场景 | 预期结果 ||---|---|-| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问 | 除明确允许暴露的笔记本名称外,不能读取、写入、复制、删除或列举加密内容;错误不返回明文、密文或可推断文档标题的信息 |+| 锁定后经 UI、HTTP、文件 API、CLI、MCP、WebDAV、插件、后台任务访问加密笔记本持久化目录 | 除明确允许暴露的笔记本名称外,不能解密、写入、复制、删除或列举加密内容;管理员文件 API 与受信任插件仍可访问 `temp/` 中尚未清理的导出副本 || 解锁、锁定、应用重启和认证失败 | 只有 `Unlocked` 才能取得受管 DEK 句柄和数据库连接;失败和重启后入口拒绝访问,内核可控的明文缓存、临时文件与句柄完成尽力清理 |-| 锁定与响应生成、缓存发布、导出、预览、同步、索引或历史恢复并发 | 锁定在所有在途生命周期租约结束后才成功;成功后无晚到的明文响应、缓存回填、临时文件、可用令牌或数据库重连 |+| 锁定与响应生成、缓存发布、导出、预览、同步、索引或历史恢复并发 | 锁定在所有在途生命周期租约结束后才成功;成功后无晚到的明文响应、缓存回填、新建临时文件、可用令牌或数据库重连,删除失败的既有临时文件除外 || 同一加密笔记本内移动文档,随后清空缓存并重启 | 文件基名不变时密文保持不变并可按稳定对象 ID 认证解密;新父目录按普通笔记本语义生效,旧目录位置不存在,失败处理与普通笔记本一致 || 加密笔记本与普通笔记本、两个加密笔记本之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 || 资源密文写入与名称映射更新任一步失败 | 整个逻辑事务失败并回滚;调用方收到错误,不留下可访问的孤儿资源、缺失映射或明文临时文件 || 删除加密笔记本后保留历史,再尝试禁用或恢复 | 存在密钥依赖时拒绝删除全局配置和备份;使用匹配备份与主密码可恢复,只有明确永久清除恢复数据后才允许解除依赖 || 文档生成历史后移动父目录或改变文件基名,再查看或回滚旧历史 | 使用历史条目记录的快照 boxID、对象类型和稳定文件基名认证解密;仅在目标基名变化时重新封装,缺失快照上下文时拒绝操作 |-| 文件、资源、数据库、WAL/SHM、历史、快照、日志和临时目录的磁盘检查 | 内核管理范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页;清理失败的临时路径仍被所有入口拒绝 |-| 清理失败后删除或损坏全局拒绝访问记录,再重启和访问残留路径 | 受控明文临时命名空间仍被无条件拒绝;扫描重建记录并继续清理,记录缺失或损坏不会使路径失效放行 |+| 文件、资源、数据库、WAL/SHM、历史、快照和日志的磁盘检查 | 加密笔记本持久化范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页;`temp/` 可能在导出期间或清理失败后包含明文 |+| 异常退出后重启 | 启动时至少删除 `temp/export/` 下第一层名称为合法 boxID 的残留目录;通用临时目录初始化可以同时清理其他导出和插件临时文件 || 密文篡改、路径替换和备份损坏 | 认证或格式校验失败并安全拒绝;不回退普通路径、不生成新密钥材料、不静默覆盖配置 || nonce 随机源失败、达到用途密钥调用限制或事后发现 nonce 重用 | 随机源失败或达到限制时在加密前拒绝写入;AES-GCM 认证本身不能发现已发生的 nonce 重用,发现后必须按密钥泄露事件处理并轮换 DEK 后重新加密 || 回放认证有效的历史密文或密钥备份 | 可能被识别为有效旧版本,但不得被宣称为最新或来源可信;数据回退风险明确,当前设计不声称提供回滚防护 |diff --git a/kernel/api/file.go b/kernel/api/file.goindex 50b1cc658b..bbfdfb7b18 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -50,34 +50,6 @@ func rejectEncryptedBoxPath(absPath string) bool {return model.EncryptedRawPathBoxID(absPath) != ""}-// rejectWorkspaceTempPath 检查路径是否位于工作空间临时目录,包含经符号链接解析后的目标路径。-// 原始文件 API 不允许访问该目录,避免内核管理的导出、转换和仓库临时明文绕过专用下载守卫。-func rejectWorkspaceTempPath(p string) bool {- if !filepath.IsAbs(p) {- p = filepath.Join(util.WorkspaceDir, p)- }- isTempPath := func(candidate string) bool {- tempDir := normalizeAndResolve(util.TempDir)- candidate = normalizeAndResolve(candidate)- return candidate == tempDir || gulu.File.IsSubPath(tempDir, candidate)- }- if isTempPath(p) {- return true- }- return isTempPath(util.ResolveLongestExistingParent(p))-}--func rejectWorkspaceTempPaths(ret *gulu.Result, paths ...string) bool {- for _, p := range paths {- if rejectWorkspaceTempPath(p) {- ret.Code = http.StatusForbidden- ret.Msg = "access to workspace temp files is not supported via this API"- return true- }- }- return false-}-// copyDecryptedAsset 将加密 asset 解密后复制到目标路径(dest 必须在工作区外)。func copyDecryptedAsset(src, dest string) error {// 安全守卫:dest 必须在工作区外,防止解密后的明文落入工作区普通目录@@ -124,9 +96,6 @@ func getUniqueFilename(c *gin.Context) {) {return}- if rejectWorkspaceTempPaths(ret, filePath) {- return- }ret.Data = map[string]any{"path": util.GetUniqueFilename(filePath),@@ -185,9 +154,6 @@ func globalCopyFiles(c *gin.Context) {ret.Msg = fmt.Sprintf("refuse to copy sensitive file [%s]", src)return}- if rejectWorkspaceTempPaths(ret, absSrc) {- return- }if rejectEncryptedBoxPath(absSrc) {ret.Code = -3@@ -204,9 +170,6 @@ func globalCopyFiles(c *gin.Context) {ret.Msg = err.Error()return}- if rejectWorkspaceTempPaths(ret, destDir) {- return- }// 在 MkdirAll 前拒绝加密笔记本目录,避免在加密笔记本内创建明文目录if rejectEncryptedBoxPath(destDir) {ret.Code = -1@@ -236,9 +199,6 @@ func globalCopyFiles(c *gin.Context) {for _, src := range srcs {dest := filepath.Join(destDir, filepath.Base(src))- if rejectWorkspaceTempPaths(ret, dest) {- return- }if rejectEncryptedBoxPath(dest) {ret.Code = -3ret.Msg = model.Conf.Language(321)@@ -316,9 +276,6 @@ func workspaceCopyFiles(c *gin.Context) {ret.Msg = fmt.Sprintf("refuse to copy sensitive file [%s]", src)return}- if rejectWorkspaceTempPaths(ret, absSrc) {- return- }if rejectEncryptedBoxPath(absSrc) {ret.Code = -3ret.Msg = model.Conf.Language(321)@@ -333,9 +290,6 @@ func workspaceCopyFiles(c *gin.Context) {ret.Msg = err.Error()return}- if rejectWorkspaceTempPaths(ret, destDir) {- return- }// 在 MkdirAll 前拒绝加密笔记本目录,避免在加密笔记本内创建明文目录if rejectEncryptedBoxPath(destDir) {ret.Code = -1@@ -365,9 +319,6 @@ func workspaceCopyFiles(c *gin.Context) {for _, absSrc := range absSrcs {dest := filepath.Join(destDir, filepath.Base(absSrc))- if rejectWorkspaceTempPaths(ret, dest) {- return- }if rejectEncryptedBoxPath(dest) {ret.Code = -3ret.Msg = model.Conf.Language(321)@@ -422,9 +373,6 @@ func copyFile(c *gin.Context) {ret.Data = map[string]any{"closeTimeout": 5000}return}- if rejectWorkspaceTempPaths(ret, src, dest) {- return- }// 加密笔记本的文件不允许通过原始文件 API 复制(src 读出密文/明文,dest 写入破坏加密存储)// 例外:dest 在工作区外且非加密 box 时允许解密复制(用户导出的场景)@@ -503,10 +451,6 @@ func getFile(c *gin.Context) {c.JSON(http.StatusAccepted, ret)return}- if rejectWorkspaceTempPaths(ret, fileAbsPath) {- c.JSON(http.StatusAccepted, ret)- return- }// 加密笔记本的任何文件都不允许通过原始文件 API 读取(不只 .sy):// 密文对插件无意义,且可能被误解析或泄漏;合法读取走专用 API(已加密感知)if rejectEncryptedBoxPath(fileAbsPath) {@@ -673,9 +617,6 @@ func readDir(c *gin.Context) {ret.Msg = err.Error()return}- if rejectWorkspaceTempPaths(ret, dirAbsPath) {- return- }// 加密笔记本的任何目录都不允许通过原始文件 API 枚举(不只 .sy):// 目录结构、文档 ID、随机化资产名和时间戳可能泄漏信息;合法读取走专用 API(已加密感知)if rejectEncryptedBoxPath(dirAbsPath) {@@ -755,9 +696,6 @@ func renameFile(c *gin.Context) {ret.Msg = err.Error()return}- if rejectWorkspaceTempPaths(ret, srcAbsPath) {- return- }srcInfo, srcStatErr := os.Stat(srcAbsPath)if os.IsNotExist(srcStatErr) {ret.Code = http.StatusNotFound@@ -777,9 +715,6 @@ func renameFile(c *gin.Context) {ret.Msg = err.Error()return}- if rejectWorkspaceTempPaths(ret, destAbsPath) {- return- }// 加密笔记本的文件不允许通过原始文件 API 重命名(会破坏加密存储结构/跨 box 搬运密文)if rejectEncryptedBoxPath(srcAbsPath) || rejectEncryptedBoxPath(destAbsPath) {ret.Code = -3@@ -854,9 +789,6 @@ func removeFile(c *gin.Context) {ret.Msg = err.Error()return}- if rejectWorkspaceTempPaths(ret, fileAbsPath) {- return- }// 加密笔记本的文件不允许通过原始文件 API 删除(破坏加密存储结构)if rejectEncryptedBoxPath(fileAbsPath) {ret.Code = -3@@ -907,9 +839,6 @@ func putFile(c *gin.Context) {ret.Msg = err.Error()return}- if rejectWorkspaceTempPaths(ret, fileAbsPath) {- return- }// 加密笔记本的任何文件都不允许通过原始文件 API 写入(不只 .sy):// 明文写入会破坏密文格式或污染加密存储;合法写入走专用 API(已加密感知)diff --git a/kernel/api/file_test.go b/kernel/api/file_test.goindex a247372817..9c6df71e68 100644--- a/kernel/api/file_test.go+++ b/kernel/api/file_test.go@@ -1,7 +1,6 @@package apiimport (- "encoding/json""net/http""net/http/httptest""os"@@ -10,10 +9,11 @@ import ("testing""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util")-func TestRejectWorkspaceTempPath(t *testing.T) {+func TestGetFileAllowsWorkspaceTemp(t *testing.T) {originalWorkspaceDir := util.WorkspaceDiroriginalTempDir := util.TempDirworkspaceDir := t.TempDir()@@ -24,91 +24,27 @@ func TestRejectWorkspaceTempPath(t *testing.T) {util.TempDir = originalTempDir}()- if err := os.MkdirAll(filepath.Join(util.TempDir, "export"), 0755); err != nil {- t.Fatal(err)- }- if err := os.MkdirAll(filepath.Join(workspaceDir, "data"), 0755); err != nil {- t.Fatal(err)- }-- for _, p := range []string{- util.TempDir,- filepath.Join(util.TempDir, "export", "artifact.zip"),- filepath.Join("temp", "export", "artifact.zip"),- } {- if !rejectWorkspaceTempPath(p) {- t.Fatalf("workspace temp path [%s] should be rejected", p)- }- }-- for _, p := range []string{- filepath.Join(workspaceDir, "data", "document.sy"),- filepath.Join(workspaceDir, "temp-other", "artifact.zip"),- } {- if rejectWorkspaceTempPath(p) {- t.Fatalf("non-temp path [%s] should not be rejected", p)- }- }-}--func TestRejectWorkspaceTempPathThroughSymlink(t *testing.T) {- originalWorkspaceDir := util.WorkspaceDir- originalTempDir := util.TempDir- workspaceDir := t.TempDir()- util.WorkspaceDir = workspaceDir- util.TempDir = filepath.Join(workspaceDir, "temp")- defer func() {- util.WorkspaceDir = originalWorkspaceDir- util.TempDir = originalTempDir- }()-- targetDir := filepath.Join(util.TempDir, "export")- if err := os.MkdirAll(targetDir, 0755); err != nil {- t.Fatal(err)- }- linkPath := filepath.Join(workspaceDir, "export-link")- if err := os.Symlink(targetDir, linkPath); err != nil {- t.Skipf("create symlink failed: %s", err)- }-- if !rejectWorkspaceTempPath(filepath.Join(linkPath, "new", "artifact.zip")) {- t.Fatal("path resolving through a symlink into workspace temp should be rejected")- }-}--func TestGetFileRejectsWorkspaceTemp(t *testing.T) {- originalWorkspaceDir := util.WorkspaceDir- originalTempDir := util.TempDir- workspaceDir := t.TempDir()- util.WorkspaceDir = workspaceDir- util.TempDir = filepath.Join(workspaceDir, "temp")- defer func() {- util.WorkspaceDir = originalWorkspaceDir- util.TempDir = originalTempDir- }()-- artifact := filepath.Join(util.TempDir, "export", "plaintext.zip")+ artifact := filepath.Join(util.TempDir, "export", "plugin-package.zip")if err := os.MkdirAll(filepath.Dir(artifact), 0755); err != nil {t.Fatal(err)}- if err := os.WriteFile(artifact, []byte("plaintext"), 0600); err != nil {+ content := []byte("plugin package")+ if err := os.WriteFile(artifact, content, 0644); err != nil {t.Fatal(err)}recorder := httptest.NewRecorder()context, _ := gin.CreateTestContext(recorder)- request := httptest.NewRequest(http.MethodPost, "/api/file/getFile", strings.NewReader(`{"path":"temp/export/plaintext.zip"}`))+ context.Set(model.RoleContextKey, model.RoleAdministrator)+ request := httptest.NewRequest(http.MethodPost, "/api/file/getFile", strings.NewReader(`{"path":"temp/export/plugin-package.zip"}`))request.Header.Set("Content-Type", "application/json")context.Request = requestgetFile(context)- var result struct {- Code int `json:"code"`- }- if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {- t.Fatal(err)+ if recorder.Code != http.StatusOK {+ t.Fatalf("workspace temp file should be accessible, got status %d: %s", recorder.Code, recorder.Body.String())}- if result.Code != http.StatusForbidden {- t.Fatalf("workspace temp file should be rejected, got code %d: %s", result.Code, recorder.Body.String())+ if recorder.Body.String() != string(content) {+ t.Fatalf("unexpected workspace temp file content: %q", recorder.Body.String())}}diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 85d139740a..ac8bb89eb1 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -148,6 +148,7 @@ func InitConf() {initLang()Conf = NewAppConf()+ clearEncryptedExportTempOnBoot()confPath := filepath.Join(util.ConfDir, "conf.json")if gulu.File.IsExist(confPath) {if data, err := os.ReadFile(confPath); err != nil {diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.goindex f4ae3bbeb2..bde746d535 100644--- a/kernel/model/encrypted_export.go+++ b/kernel/model/encrypted_export.go@@ -27,6 +27,8 @@ import ("time""github.com/88250/lute/ast"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util")type managedEncryptedExport struct {@@ -99,6 +101,33 @@ func RevokeManagedEncryptedExportsForBox(boxID string) {}}+// clearEncryptedExportTempOnBoot 清理异常退出后残留的加密笔记本明文导出目录。+// 加密导出的第一层目录固定为 boxID,普通导出和插件临时目录不使用该命名形式。+func clearEncryptedExportTempOnBoot() {+ if strings.TrimSpace(util.TempDir) == "" {+ logging.LogWarnf("skip clearing stale encrypted export temp: temp dir is not initialized")+ return+ }+ exportDir := filepath.Join(util.TempDir, "export")+ entries, err := os.ReadDir(exportDir)+ if os.IsNotExist(err) {+ return+ }+ if err != nil {+ logging.LogWarnf("read export temp dir [%s] failed: %s", exportDir, err)+ return+ }+ for _, entry := range entries {+ if !ast.IsNodeIDPattern(entry.Name()) {+ continue+ }+ entryPath := filepath.Join(exportDir, entry.Name())+ if err = os.RemoveAll(entryPath); err != nil {+ logging.LogWarnf("remove stale encrypted export temp [%s] failed: %s", entryPath, err)+ }+ }+}+// IsManagedEncryptedExportPath 判断相对路径是否属于加密导出受控范围(<boxID>/<kind>/<file> 结构)。// 只要路径首段是合法 boxID 格式即视为受控,不依赖 box 是否仍存在(笔记本删除后仍需按注册表拒绝,// 避免因 IsEncryptedBox 返回 false 而 fail-open 暴露明文产物)。diff --git a/kernel/model/encrypted_export_test.go b/kernel/model/encrypted_export_test.goindex 88620e2a25..f51cec37d7 100644--- a/kernel/model/encrypted_export_test.go+++ b/kernel/model/encrypted_export_test.go@@ -63,6 +63,35 @@ func TestLockBoxRevokesAndRemovesManagedExport(t *testing.T) {}}+func TestClearEncryptedExportTempOnBoot(t *testing.T) {+ originalTempDir := util.TempDir+ util.TempDir = t.TempDir()+ defer func() {+ util.TempDir = originalTempDir+ }()++ staleEncryptedExport := filepath.Join(util.TempDir, "export", "20260720120000-abcdefg", "markdown", "artifact.zip")+ pluginTemp := filepath.Join(util.TempDir, "export", "temp_plugin_package.zip")+ if err := os.MkdirAll(filepath.Dir(staleEncryptedExport), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(staleEncryptedExport, []byte("plaintext"), 0600); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(pluginTemp, []byte("plugin"), 0600); err != nil {+ t.Fatal(err)+ }++ clearEncryptedExportTempOnBoot()++ if _, err := os.Stat(filepath.Join(util.TempDir, "export", "20260720120000-abcdefg")); !os.IsNotExist(err) {+ t.Fatalf("stale encrypted export temp should be removed: %v", err)+ }+ if _, err := os.Stat(pluginTemp); err != nil {+ t.Fatalf("plugin temp should be preserved: %v", err)+ }+}+func TestCopyExportResourceDirectory(t *testing.T) {source := filepath.Join(t.TempDir(), "assets")nested := filepath.Join(source, "nested")diff --git a/kernel/util/working.go b/kernel/util/working.goindex 3708984462..5f1bc220c3 100644--- a/kernel/util/working.go+++ b/kernel/util/working.go@@ -365,7 +365,7 @@ func initWorkspaceDir(workspaceArg string) {os.Exit(logging.ExitCodeInitWorkspaceErr)}os.RemoveAll(filepath.Join(TempDir, "repo"))- // export 目录仅保存内核管理的临时导出文件。启动后所有加密笔记本均为锁定状态,不能保留上次异常退出的明文导出。+ // export 目录只保存临时文件,启动时统一清理;插件不得依赖其中的文件跨进程存续。os.RemoveAll(filepath.Join(TempDir, "export"))os.Setenv("TMPDIR", osTmpDir)os.Setenv("TEMP", osTmpDir)