An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:memo: Standardize bilingual documentation and API contract guidelines
Daniel77182c50104f
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdindex 97237c262f..c8ca4e7ca4 100644--- a/docs/API-CONTRACTS.md+++ b/docs/API-CONTRACTS.md@@ -1,52 +1,54 @@-# 内核接口类型契约+# Kernel API type contracts-首批覆盖 `/api/system/version`、`/api/attr/getBlockAttrs`、`/api/attr/setBlockAttrs`、`/api/search/searchTag`、`/api/notebook/lsNotebooks`、`/api/history/searchHistory` 和 `/api/block/getBlockInfo`。版本接口同时支持 GET 和 POST,因此共登记 8 个方法与路径组合。+[中文](API-CONTRACTS.zh-CN.md)-截至本次迁移,契约覆盖 53 个接口、55 个方法与路径组合,存量清单仍有 572 条路由记录。后续已覆盖的范围包括快照创建与备注、系统基础查询和部分设置、属性批量读写、标签查询与标签/书签改名删除、部分编辑器设置,以及块位置、折叠状态和标题子节点查询。完整名单以 `kernel/apicontract/contracts.go` 为准;剩余工作以 `legacy_routes.json` 为准,全量迁移尚未完成。+## Scope-## 契约与实现+This document defines type declarations, compatibility requirements, generated artifacts, and verification for kernel HTTP APIs. Endpoint definitions are maintained in `kernel/apicontract/contracts.go`. `kernel/apicontract/legacy_routes.json` records routes that use existing handling, including non-JSON responses, dynamic paths, and `ANY` registrations. New endpoints must define type contracts and must not be added to the legacy list.-`kernel/apicontract/contracts.go` 定义请求、响应和端点。契约包独立于内核启动、数据库和持久化模型,生成器可以单独运行。API 入口通过 `contractHandler` 绑定端点,请求参数和成功返回值受到 Go 泛型签名约束;响应载荷通过构造函数设置,不能直接给通用 `ret.Data` 赋值。业务校验继续使用现有辅助函数,`contractFailure` 保留其错误码、消息和已支持的错误载荷。+## Contracts and implementation-生成器从同一组 Go 类型生成 `app/src/types/api/index.d.ts` 和 `kernel/apicontract/schema.json`。后者包含共享的 `$defs` 和每个端点的请求、响应 schema,测试使用同一套 schema 检查实际 HTTP 响应。类型声明不会在运行时验证 JSON,CI 中的处理函数测试负责验证序列化结果。+`kernel/apicontract/contracts.go` defines requests, responses, and endpoints. The contract package is independent of kernel startup, databases, and persistence models, so the generator runs independently. API entry points bind endpoints through `contractHandler`; Go generic signatures constrain request parameters and successful return values. Constructors set response payloads rather than assigning directly to generic `ret.Data`. Existing helpers continue to validate business rules, and `contractFailure` preserves their error codes, messages, and supported error payloads.-输入和输出分别处理。`json` tag 控制线协议字段名;请求字段默认必填,`api:"optional"` 表示可缺省,`nullable` 表示接受 `null`,指针保留可空语义。输出字段的 `omitempty` 只控制输出省略,不推导请求必填性。嵌入结构体展平,递归类型通过引用表示;接口联合、常量字段和自定义编解码需要显式建模。未支持的类型、字段冲突和未知 JSON tag 会使生成失败,不会降级为 `any`。+The generator produces `app/src/types/api/index.d.ts` and `kernel/apicontract/schema.json` from the same Go types. The schema contains shared `$defs` and each endpoint's request and response schemas. Tests validate actual HTTP responses against those same schemas. Type declarations do not validate JSON at runtime; handler tests in CI validate serialized results.-数组、字典和嵌套结构体递归检查请求约束,字符串数组中的 `null` 不会被转换为空字符串,批量属性中的 `null` 值仍表示删除属性。标签树单独定义递归传输结构;前端共享树节点中的笔记本和文档路径字段为可选,反映标签节点不返回这些字段的实际行为。+Input and output are handled separately. The `json` tag determines wire field names. Request fields are required by default; `api:"optional"` permits omission, `nullable` accepts `null`, and pointers preserve nullability. Output `omitempty` controls omission only and does not determine request requirements. Embedded structs are flattened, and recursive types use references. Interface unions, constant fields, and custom encoding or decoding require explicit modeling. Unsupported types, conflicting fields, and unknown JSON tags fail generation without falling back to `any`.-`Notebook` 是接口载荷,业务模型通过显式转换映射到该载荷,回归测试比较完整 JSON,包括各个加密状态。修改契约不会改变 `.sy`、数据库、历史、同步或加密格式。+Arrays, maps, and nested structs recursively validate request constraints. A `null` in a string array is not converted to an empty string; `null` values in batch attributes still mean deletion. The tag tree has a dedicated recursive transport structure. Notebook and document-path fields are optional in shared frontend tree nodes because tag nodes do not return them.-## 保留的兼容行为+`Notebook` is an API payload. Business models map to it explicitly, and regression tests compare complete JSON across encryption states. Contract changes do not alter `.sy`, database, history, sync, or encryption formats.-| 接口 | 兼容边界 |-|---|---|-| `version` | 不要求请求体,响应数据是字符串 |-| `getBlockAttrs` | 必须有 ID,成功时始终返回属性字典,没有属性时保持 `{}` |-| `setBlockAttrs` | 属性值为字符串或 `null`;`null` 删除属性,成功时数据为 `null` |-| `searchTag` | 允许空关键词,空结果保持 `[]` |-| `lsNotebooks` | 保留空请求体、`null` 和旧解析失败时的默认分支;合法对象中的错误布尔类型返回错误;保留业务失败时原有的成功码与空数据 |-| `searchHistory` | 数字先按 JSON 浮点值解码,再沿用原有整数转换;缺省或 `null` 保留默认值,数字字符串不作为数字接受 |-| `getBlockInfo` | 保留 ID 去空白、可选笔记本参数和附带 ID 的租约检查;分别声明完整信息、发布密码提示和错误响应 |+## Compatibility requirements-`ignoretype` 和 `filterstrings` 仅用于声明过的旧参数兼容行为。生成的请求类型描述规范调用形式;兼容解码可能接受并忽略更宽的旧输入,兼容测试明确覆盖这些例外。不存在全局“绑定失败后回退旧解析”的开关。+Contract maintenance must preserve existing observable API behavior. Changes to type definitions or handler structure alone must not change call semantics:-只读中间件仍可返回带 `closeTimeout` 的提示对象。`fetchPost` 的普通回调只接收消息处理后保留的非负错误码,块信息接口的 `3` 仍须处理;`fetchSyncPost` 和 `fetchGet` 保留完整响应。动态 URL 保留存量签名;静态 POST 路径必须来自契约或存量路由,错误参数不能通过重载回退。拼接出开放范围的模板 URL 时使用显式 `string` 变量。+- Request semantics: preserve body requirements, field optionality, and distinctions between an empty body, missing fields, `null`, empty strings, empty objects, and empty arrays+- Parameter handling: preserve defaults, whitespace handling, numeric conversions, and supported historical input rules; do not implicitly widen or narrow accepted inputs+- Response structure: preserve field names, types, nullability, and omission rules; distinguish `{}`, `[]`, and `null`, and fully declare success, prompt, and failure variants+- Error behavior: preserve HTTP statuses, business error codes, messages, additional error payloads, and message display duration; do not reinterpret existing business failures as success+- Permissions and lifecycle: preserve authentication, roles, read-only and publish-access checks, and encrypted-notebook admission, lease scope, and release timing; compatibility handling must not bypass authorization or authenticated decryption-业务错误需要保留提示显示时长时使用 `FailureWithTimeout`。块查询迁移后通过 `holdContractBlockRequest` 保留显式笔记本及附带 ID 的租约检查;状态查询允许已删除 ID 的行为仍由对应入口明确指定。+Endpoint-specific behavior is recorded jointly in contract definitions, compatibility decoding, and regression tests. Tests must cover actual HTTP serialization, boundary inputs, and permission scenarios rather than only checking whether types compile.-## 新增与迁移+`ignoretype` and `filterstrings` apply only to explicitly declared historical parameter compatibility. Generated request types describe canonical calls; compatibility decoding may accept and ignore a wider set of old inputs, with tests covering those exceptions. There is no global switch to fall back to old parsing after binding fails.-1. 在契约包中定义传输类型与端点,并明确请求体、错误码、空值、默认值和历史输入兼容规则-2. 用 `contractHandler` 接入业务入口,保持路由中间件顺序、授权和租约范围-3. 已有接口迁移完成后,从 `legacy_routes.json` 删除对应记录;新接口不能加入该清单-4. 更新实际响应、兼容输入和严格类型测试,运行生成器,再修正编译器指出的调用问题-5. 同步 `petal` 的生成声明和相关公共声明;已公开接口同步更新接口文档+Read-only middleware may still return a prompt object containing `closeTimeout`. Ordinary `fetchPost` callbacks receive only nonnegative codes retained after message processing; block-info code `3` still requires handling. `fetchSyncPost` and `fetchGet` preserve complete responses. Dynamic URLs retain existing signatures. Static POST paths must come from contracts or recorded legacy routes, and invalid parameters cannot fall back through another overload. Use an explicit `string` variable when constructing a template URL with an open-ended range.-`legacy_routes.json` 记录尚未迁移的路由,包括非 JSON、动态路径和 `ANY` 注册。生成检查读取实际路由与处理函数声明,验证方法、路径、处理函数和契约适配器的对应关系。CI 对照合入前的清单阻止增加存量记录。+Use `FailureWithTimeout` when a business error must preserve its message display duration. Contract-based block queries use `holdContractBlockRequest` to retain lease checks for explicit notebooks and accompanying IDs. Individual entry points still specify whether state queries permit deleted IDs.-## 生成与验证+## Endpoint maintenance-在 `app/` 下运行:+1. Define or update transport types and endpoints in the contract package, specifying request bodies, error codes, null values, defaults, and historical input compatibility+2. Bind business entry points through `contractHandler`, preserving route middleware order, authorization, and lease scope+3. Routes with type contracts must not also appear in `legacy_routes.json`; remove records for deleted endpoints, and never add new endpoints to the list+4. Update actual-response, input-compatibility, and strict type tests; run generation and correct calls identified by the compiler+5. Synchronize generated and related public declarations in `petal`; update API documentation for public endpoints++Generation checks inspect actual route and handler declarations to verify methods, paths, handlers, and contract adapters. CI compares the legacy list with the pre-change list and prevents additional records. Do not bypass contract checks with `any`, type assertions, or changes to the legacy list.++## Generation and verification++Run from `app/`:```textpnpm run api:generate@@ -56,13 +58,13 @@ pnpm run lintpnpm exec tsx --test src/util/fetch.test.ts src/util/fetchTimeout.test.ts```-`--petal` 路径相对于生成器的工作目录 `kernel/`,示例对应同级仓库。CI 只检查本仓库产物,本地跨仓库同步须使用该参数核对插件声明。+The `--petal` path is relative to the generator's working directory, `kernel/`; the example refers to a sibling repository. CI checks only this repository's artifacts. Local synchronization across repositories uses this option to verify plugin declarations.-在 `kernel/` 下运行:+Run from `kernel/`:```textgo test ./apicontract/...go test -tags "fts5 sqlcipher" ./api -run "TestAPIContract|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1```-`tsconfig.api.json` 单独启用严格检查并检查声明文件,覆盖参数错误、字段拼写、必填请求体、成功与失败分支、可空值和方法不匹配。主应用继续沿用现有配置,因此存量调用的严格空值检查并未全量开启。处理函数测试使用临时工作区和独立测试进程,不启动或重启运行中的内核。+`tsconfig.api.json` separately enables strict checks and declaration-file checking for invalid parameters, misspelled fields, required bodies, success and failure branches, nullability, and method mismatches. The main application retains its existing configuration; do not assume strict null checks apply to every call. Handler tests use temporary workspaces and isolated test processes without starting or restarting the running kernel.diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.mdnew file mode 100644index 0000000000..d4b0f7c714--- /dev/null+++ b/docs/API-CONTRACTS.zh-CN.md@@ -0,0 +1,70 @@+# 内核接口类型契约++[English](API-CONTRACTS.md)++## 适用范围++本文规定内核 HTTP 接口的类型定义、兼容要求、生成产物和验证流程。端点定义以 `kernel/apicontract/contracts.go` 为准;`kernel/apicontract/legacy_routes.json` 登记使用既有处理方式的路由,包括非 JSON、动态路径和 `ANY` 注册。新增接口必须定义类型契约,不得加入存量清单。++## 契约与实现++`kernel/apicontract/contracts.go` 定义请求、响应和端点。契约包独立于内核启动、数据库和持久化模型,生成器可以单独运行。API 入口通过 `contractHandler` 绑定端点,请求参数和成功返回值受到 Go 泛型签名约束;响应载荷通过构造函数设置,不能直接给通用 `ret.Data` 赋值。业务校验继续使用现有辅助函数,`contractFailure` 保留其错误码、消息和已支持的错误载荷。++生成器从同一组 Go 类型生成 `app/src/types/api/index.d.ts` 和 `kernel/apicontract/schema.json`。后者包含共享的 `$defs` 和每个端点的请求、响应 schema,测试使用同一套 schema 检查实际 HTTP 响应。类型声明不会在运行时验证 JSON,CI 中的处理函数测试负责验证序列化结果。++输入和输出分别处理。`json` tag 控制线协议字段名;请求字段默认必填,`api:"optional"` 表示可缺省,`nullable` 表示接受 `null`,指针保留可空语义。输出字段的 `omitempty` 只控制输出省略,不推导请求必填性。嵌入结构体展平,递归类型通过引用表示;接口联合、常量字段和自定义编解码需要显式建模。未支持的类型、字段冲突和未知 JSON tag 会使生成失败,不会降级为 `any`。++数组、字典和嵌套结构体递归检查请求约束,字符串数组中的 `null` 不会被转换为空字符串,批量属性中的 `null` 值仍表示删除属性。标签树单独定义递归传输结构;前端共享树节点中的笔记本和文档路径字段为可选,反映标签节点不返回这些字段的实际行为。++`Notebook` 是接口载荷,业务模型通过显式转换映射到该载荷,回归测试比较完整 JSON,包括各个加密状态。修改契约不会改变 `.sy`、数据库、历史、同步或加密格式。++## 兼容要求++契约维护必须保留接口已有的可观察行为,不能仅因类型定义或处理函数重构而改变调用语义:++- 请求语义:保持请求体是否必需、字段是否可缺省,以及空请求体、缺失字段、`null`、空字符串、空对象和空数组的区别+- 参数处理:保持默认值、空白处理、数字转换和已支持的历史输入规则;不得隐式扩大或缩小接受范围+- 响应结构:保持字段名称、类型、可空性和省略规则,区分 `{}`、`[]` 与 `null`,完整声明成功、提示和失败等响应分支+- 错误行为:保持 HTTP 状态、业务错误码、消息、附加错误载荷和提示显示时长,不将已有业务失败重新解释为成功+- 权限与生命周期:保持认证、角色、只读和发布权限校验,以及加密笔记本的操作准入、租约范围与释放时机;兼容处理不得绕过授权或认证解密++具体接口的特殊行为由契约定义、兼容解码和回归测试共同记录。测试应覆盖实际 HTTP 序列化结果、边界输入和权限场景,不能只验证类型能否编译。++`ignoretype` 和 `filterstrings` 仅用于声明过的旧参数兼容行为。生成的请求类型描述规范调用形式;兼容解码可能接受并忽略更宽的旧输入,兼容测试明确覆盖这些例外。不存在全局「绑定失败后回退旧解析」的开关。++只读中间件仍可返回带 `closeTimeout` 的提示对象。`fetchPost` 的普通回调只接收消息处理后保留的非负错误码,块信息接口的 `3` 仍须处理;`fetchSyncPost` 和 `fetchGet` 保留完整响应。动态 URL 保留存量签名;静态 POST 路径必须来自契约或存量路由,错误参数不能通过重载回退。拼接出开放范围的模板 URL 时使用显式 `string` 变量。++业务错误需要保留提示显示时长时使用 `FailureWithTimeout`。使用契约的块查询通过 `holdContractBlockRequest` 保留显式笔记本及附带 ID 的租约检查;状态查询允许已删除 ID 的行为仍由对应入口明确指定。++## 接口维护流程++1. 在契约包中定义或更新传输类型与端点,明确请求体、错误码、空值、默认值和历史输入兼容规则+2. 用 `contractHandler` 绑定业务入口,保持路由中间件顺序、授权和租约范围+3. 使用类型契约的路由不得同时出现在 `legacy_routes.json`;删除接口时同步移除对应记录,新增接口不得加入该清单+4. 更新实际响应、兼容输入和严格类型测试,运行生成器,再修正编译器指出的调用问题+5. 同步 `petal` 的生成声明和相关公共声明;公开接口同步更新接口文档++生成检查读取实际路由与处理函数声明,验证方法、路径、处理函数和契约适配器的对应关系。CI 对照变更前的清单阻止增加存量记录。不得通过 `any`、类型断言或修改存量清单绕过契约检查。++## 生成与验证++在 `app/` 下运行:++```text+pnpm run api:generate+pnpm run api:generate --petal ../../petal+pnpm run api:check --petal ../../petal+pnpm run lint+pnpm exec tsx --test src/util/fetch.test.ts src/util/fetchTimeout.test.ts+```++`--petal` 路径相对于生成器的工作目录 `kernel/`,示例对应同级仓库。CI 只检查本仓库产物,本地跨仓库同步须使用该参数核对插件声明。++在 `kernel/` 下运行:++```text+go test ./apicontract/...+go test -tags "fts5 sqlcipher" ./api -run "TestAPIContract|TestBlockAttrsRespectPublishAccess|TestGetBlockInfoRecovery|TestGetBlockInfoPublishAccess|TestListNotebooksSortsBySubDocCount|TestContract.*NotebookResponseLease" -count=1+```++`tsconfig.api.json` 单独启用严格检查并检查声明文件,覆盖参数错误、字段拼写、必填请求体、成功与失败分支、可空值和方法不匹配。主应用继续沿用现有配置,不假定全部调用都启用了严格空值检查。处理函数测试使用临时工作区和独立测试进程,不启动或重启运行中的内核。diff --git a/docs/ASSET-DOWNLOAD.md b/docs/ASSET-DOWNLOAD.mdindex bfde9efbb5..bf874276dc 100644--- a/docs/ASSET-DOWNLOAD.md+++ b/docs/ASSET-DOWNLOAD.md@@ -1,47 +1,53 @@-# 资源文件按需下载+# On-demand asset downloads-对应需求:https://github.com/siyuan-note/siyuan/issues/19149+[中文](ASSET-DOWNLOAD.zh-CN.md)-## 功能边界+Related issue: https://github.com/siyuan-note/siyuan/issues/19149-`sync.assetDownloadMode` 是设备配置,`0` 为全部下载,`1` 为按需下载,默认值为 `0`。桌面端和移动端共用设置及内核实现,适用于官方云、S3、WebDAV 和本地文件系统同步。+## Feature scope-按需模式始终同步完整文件元数据以及文档、数据库、配置、密钥等非资源内容。资源目录中的 `ocr-texts.json`、PDF 批注 `.sya` 文件和隐藏辅助文件也保持完整同步。没有自动清理已下载资源的策略;在已有完整数据的设备上启用按需模式,不会立即减少磁盘占用。+`sync.assetDownloadMode` is a device setting: `0` downloads everything and `1` downloads on demand; the default is `0`. Desktop and mobile clients share the setting and kernel implementation. It applies to official cloud, S3, WebDAV, and local filesystem sync.-首次访问未下载资源时,先复用本地仓库已有的分块,再按需下载缺少的分块。下载成功后,该资源在后续同步中继续更新。已有本地内容不依赖联网、账号登录或同步开关。需要访问云端时沿用数据同步的账号及服务权限。+On-demand mode always synchronizes complete file metadata and non-asset content, including documents, databases, configuration, and keys. Asset-directory `ocr-texts.json`, PDF annotation `.sya` files, and hidden helper files also remain fully synchronized. Downloaded assets are not automatically evicted. Enabling on-demand mode on a device that already has all content does not immediately reduce disk usage.-## 逻辑数据与本地内容+## User interaction-`dejavu` 在工作空间的 `conf/asset-downloads.json` 中保存经过仓库密钥认证加密的设备状态,包含显式版本、来源标识、未下载资源的完整文件版本,以及未完成应用操作的恢复日志。状态不参与数据同步。仓库中的 `asset-downloads-v1` 标记用于检测当前实现遗漏配置或丢失状态;状态丢失、未知版本或认证失败均返回错误并保留原始材料。+The first access to an undownloaded asset reuses chunks already in the local repository and downloads only the missing chunks. Once downloaded, the asset continues to receive updates during subsequent syncs. Existing local content does not require a network connection, account login, or enabled sync. Cloud access uses the account and service permissions of data sync.-未下载资源仍属于当前数据和快照的逻辑文件清单。索引不能将其本地缺席解释为删除,同步不能上传尚未下载的旧版本分块。已经物化的文件由普通索引继续跟踪;资源删除、改名和移动入口先补齐相关内容,再执行原有文件操作。+## Data and storage-修改同步忽略规则时,先补齐新被忽略的未下载资源,再停止跟踪,保留本地内容和历史分块;无法获取内容时保留原状态并报错。仅上传模式只补齐实际上传候选所需的分块,不将未访问的资源物化到工作区。+`dejavu` stores device state in the workspace's `conf/asset-downloads.json`, authenticated and encrypted with the repository key. It contains an explicit version, a source identity, complete file versions for undownloaded assets, and a recovery journal for unfinished apply operations. This state is not synchronized. The repository's `asset-downloads-v1` marker detects missing configuration or lost state in the current implementation. Missing state, unknown versions, and authentication failures return errors and preserve the original material.-同步合并采用可恢复的应用日志,记录目标资源清单、变更前版本和云端基线。应用前检查本地文件是否仍符合预期,保留下载期间的本地额外修改。恢复只能由同步流程显式发起,创建仓库实例和读取资源不会顺带改写文档。文件及引用更新后,另行保留待确认的变更记录,直到内核完成缓存、索引和界面更新;中途失败也按磁盘实际状态处理已经落盘的部分,重试不会遗漏这些变更。待确认记录是设备状态第一版中的可选字段,现有不含该字段的已认证状态和应用日志仍可读取并恢复,不改变加密格式。来源切换与资源物化串行化,仓库内部操作共享原有互斥锁,并重新读取已认证的设备状态,避免旧实例覆盖新状态。+Undownloaded assets remain part of the logical file inventory of current data and snapshots. Indexing must not interpret their absence from local disk as deletion, and sync must not upload chunks from an undownloaded old version. Ordinary indexing continues to track materialized files. Asset deletion, rename, and move operations fetch the relevant content before performing the existing file operation.-按需读取和历史分块补齐会上报实际发生的云端下载流量与请求次数,批量补齐合并上报;复用本地分块和局域网下载不计入云端流量,重复读取不会重复上报。+Changing sync ignore rules first fetches newly ignored undownloaded assets, then stops tracking them while retaining local content and historical chunks. If content cannot be obtained, the previous state is retained and an error is returned. Upload-only mode fetches only chunks required by actual upload candidates and does not materialize unvisited assets in the workspace.-## 读取、导出与加密+Sync merge uses a recoverable apply journal that records the target asset inventory, previous versions, and cloud baseline. Before applying changes, it verifies that local files still match expectations and preserves additional local edits made during downloading. Only sync explicitly initiates recovery; creating a repository instance or reading an asset does not rewrite documents as a side effect. After files and references are updated, pending change records remain until the kernel finishes cache, index, and UI updates. Partial failures use the actual disk state to account for changes already written, so retries do not omit them. Pending records are an optional field in device-state version 1. Existing authenticated state and journals without that field remain readable and recoverable without changing the encryption format. Source switching and asset materialization are serialized. Repository operations share the existing mutex and reload authenticated device state so an old instance cannot overwrite newer state.-内部逻辑路径解析、资源搜索、缺失检查和文件大小查询只读取逻辑元数据,不触发下载。实际显示图片、播放音视频、打开 PDF、访问资源链接、复制资源或导出时才补齐内容。用于为外部打开准备实际文件路径的 `/api/asset/resolveAssetPath` 也会先补齐资源。HTTP 和原始文件 API 先完成路径、符号链接、发布权限及加密笔记本权限检查,再执行下载。+On-demand reads and historical chunk retrieval report actual cloud download traffic and request counts, aggregating batch retrieval. Local chunk reuse and LAN downloads do not count as cloud traffic, and repeated reads do not report the same traffic again.-导出在持有笔记本读锁和创建产物之前预取引用资源,按每个文档实际所属的笔记本和完整路径读取,范围包含子文档、关联文档、脚注、查询嵌入、题头图、数据库及关联数据库中的资源。单文件导出中的脚注资源不受是否另行导出关联文档影响。目录资源根据逻辑清单补齐,不能只依靠磁盘遍历。下载或复制失败向上传播,不将缺少资源的产物报告为成功。+## Implementation and interfaces-加密资源下载后仍保持原始密文,读取和导出继续由现有认证解密流程处理,兼容已发布的资源格式。不改变密钥信封、主盐、AAD 或密钥派生,不通过明文回退处理认证错误。读取和明文导出前检查笔记本准入,不在持有笔记本读锁期间等待网络。锁定笔记本的资源读取请求和仅枚举文件名不会触发下载;完整同步、密文备份及删除前保存历史可以补齐原始密文。+### Reads and exports-## 快照与来源变更+Internal logical-path resolution, asset search, missing-asset checks, and file-size queries use logical metadata without downloading content. Displaying images, playing audio or video, opening PDFs, following asset links, copying assets, and exporting fetch content when needed. `/api/asset/resolveAssetPath`, which prepares a physical path for external opening, also fetches the asset first. HTTP and raw file APIs validate paths, symbolic links, publish permissions, and encrypted-notebook permissions before downloading.-按需设备的本地快照可能只有部分资源内容,界面通过 `requiresDownload` 独立提示。读取历史资源按该快照的精确文件版本补齐分块,不覆盖工作区当前资源。完整云端快照下载检查所有目标文件的分块,即使其元数据已经存在也不跳过检查;失败时不创建成功标签。+Exports prefetch referenced assets before holding notebook read locks and creating output artifacts. Reads use each document's actual notebook and complete path. The scope includes child and related documents, footnotes, query embeds, title images, databases, and related-database assets. Footnote assets in single-file exports are included independently of whether related documents are exported separately. Directory assets are completed from the logical inventory rather than disk traversal alone. Download and copy failures propagate to the caller; an output with missing assets is not reported as successful.-恢复快照前,先补齐当前工作区和目标快照所需的资源。切回全部下载时,同时补齐当前资源和所有保留快照缺少的历史内容;失败则保留原设置。切换同步来源、云端清理、删除当前云目录及重置仓库或密钥前检查这些依赖,未完成时保留原来源。重建仓库前,只有旧状态认证成功且依赖完整,才能清除设备状态和标记。+Downloaded encrypted assets retain their original ciphertext. Existing authenticated decryption handles reads and exports, preserving compatibility with released asset formats. Key envelopes, MasterSalt, AAD, and key derivation do not change, and authentication errors never fall back to plaintext. Notebook admission is checked before reading or plaintext export, and network waits do not occur while holding a notebook read lock. Reading an asset in a locked notebook or merely enumerating filenames does not download content. Full sync, ciphertext backups, and history preservation before deletion may fetch original ciphertext.-官方云登出允许保留原来源标识,以便本地索引和已下载快照继续使用,随后重新认证原账号。存在未完成依赖时,跨区登录、换账号和注销账号受完整性检查保护。+## Compatibility and recovery-未补齐的历史快照仍依赖对应云端内容的保留。其他设备清理云端或外部删除云对象可能使历史版本无法下载,因此部分本地快照不等价于完整离线备份。需要离线备份或更换来源时,应先完成全部下载。旧版本客户端不了解设备状态标记,降级前也必须完成全部下载;标记不能阻止旧版本把未下载文件当作本地删除。+Local snapshots on on-demand devices may contain only part of the asset content; the UI indicates this separately through `requiresDownload`. Historical asset reads retrieve chunks for that snapshot's exact file version without overwriting current workspace assets. Downloading a complete cloud snapshot checks every target file's chunks even when its metadata already exists. Failure does not create a success tag.-## 开发与验证+Before restoring a snapshot, fetch the assets required by both the current workspace and the target snapshot. Switching back to full download fetches current assets and missing historical content in all retained snapshots; failure preserves the previous setting. Source switching, cloud cleanup, deletion of the current cloud directory, and repository or key resets check these dependencies and retain the previous source while they are incomplete. Repository rebuilding may clear device state and its marker only after authenticating the old state and completing its dependencies.-实现同时涉及 `siyuan`、`dejavu` 和 `petal`。内核调用新增的 `dejavu` 资源下载及快照完整性接口,发布时应先发布依赖并更新模块版本。本地开发可使用临时 `replace` 指向 `dejavu` 检出,该替换不能提交。+Signing out of the official cloud can retain the original source identity so local indexing and downloaded snapshots remain usable, followed by reauthentication with the original account. While dependencies remain incomplete, changing regions, changing accounts, and deleting the account are protected by integrity checks.-回归覆盖完整与按需设备互相同步、单向同步、重复索引、远端版本更新、并发物化、本地修改保护、应用中断恢复、状态认证失败、来源变更、历史快照补齐、目录资源导出和已有加密资源格式。前端执行 `pnpm run lint`,语言执行 `python scripts/check-lang-keys.py`;不通过构建前端产物或编译运行内核进行验证。+Incomplete historical snapshots still depend on retention of the corresponding cloud content. Cloud cleanup by another device or external deletion of cloud objects may make old versions unavailable. A partial local snapshot is therefore not a complete offline backup. Complete all downloads before making an offline backup or changing sources. Older clients do not understand the device-state marker, so full download is also required before downgrading; the marker cannot prevent an old client from treating undownloaded files as local deletions.++## Verification++Implementation spans `siyuan`, `dejavu`, and `petal`. The kernel uses `dejavu` asset-download and snapshot-completeness APIs. Publish the dependency and update the module version before release. Local development may use a temporary `replace` pointing to the `dejavu` checkout; do not commit it.++Regression coverage includes sync between full and on-demand devices, one-way sync, repeated indexing, remote version updates, concurrent materialization, local-edit protection, interrupted apply recovery, state authentication failures, source changes, historical snapshot completion, directory-asset exports, and existing encrypted asset formats. Run `pnpm run lint` for the frontend and `python scripts/check-lang-keys.py` for translations. Do not verify by building frontend artifacts or compiling and running the kernel.diff --git a/docs/ASSET-DOWNLOAD.zh-CN.md b/docs/ASSET-DOWNLOAD.zh-CN.mdnew file mode 100644index 0000000000..7d12f710bd--- /dev/null+++ b/docs/ASSET-DOWNLOAD.zh-CN.md@@ -0,0 +1,53 @@+# 资源文件按需下载++[English](ASSET-DOWNLOAD.md)++对应需求:https://github.com/siyuan-note/siyuan/issues/19149++## 功能范围++`sync.assetDownloadMode` 是设备配置,`0` 为全部下载,`1` 为按需下载,默认值为 `0`。桌面端和移动端共用设置及内核实现,适用于官方云、S3、WebDAV 和本地文件系统同步。++按需模式始终同步完整文件元数据以及文档、数据库、配置、密钥等非资源内容。资源目录中的 `ocr-texts.json`、PDF 批注 `.sya` 文件和隐藏辅助文件也保持完整同步。没有自动清理已下载资源的策略;在已有完整数据的设备上启用按需模式,不会立即减少磁盘占用。++## 用户交互++首次访问未下载资源时,先复用本地仓库已有的分块,再按需下载缺少的分块。下载成功后,该资源在后续同步中继续更新。已有本地内容不依赖联网、账号登录或同步开关。需要访问云端时沿用数据同步的账号及服务权限。++## 数据与存储++`dejavu` 在工作空间的 `conf/asset-downloads.json` 中保存经过仓库密钥认证加密的设备状态,包含显式版本、来源标识、未下载资源的完整文件版本,以及未完成应用操作的恢复日志。状态不参与数据同步。仓库中的 `asset-downloads-v1` 标记用于检测当前实现遗漏配置或丢失状态;状态丢失、未知版本或认证失败均返回错误并保留原始材料。++未下载资源仍属于当前数据和快照的逻辑文件清单。索引不能将其本地缺席解释为删除,同步不能上传尚未下载的旧版本分块。已经物化的文件由普通索引继续跟踪;资源删除、改名和移动入口先补齐相关内容,再执行原有文件操作。++修改同步忽略规则时,先补齐新被忽略的未下载资源,再停止跟踪,保留本地内容和历史分块;无法获取内容时保留原状态并报错。仅上传模式只补齐实际上传候选所需的分块,不将未访问的资源物化到工作区。++同步合并采用可恢复的应用日志,记录目标资源清单、变更前版本和云端基线。应用前检查本地文件是否仍符合预期,保留下载期间的本地额外修改。恢复只能由同步流程显式发起,创建仓库实例和读取资源不会顺带改写文档。文件及引用更新后,另行保留待确认的变更记录,直到内核完成缓存、索引和界面更新;中途失败也按磁盘实际状态处理已经落盘的部分,重试不会遗漏这些变更。待确认记录是设备状态第一版中的可选字段,现有不含该字段的已认证状态和应用日志仍可读取并恢复,不改变加密格式。来源切换与资源物化串行化,仓库内部操作共享原有互斥锁,并重新读取已认证的设备状态,避免旧实例覆盖新状态。++按需读取和历史分块补齐会上报实际发生的云端下载流量与请求次数,批量补齐合并上报;复用本地分块和局域网下载不计入云端流量,重复读取不会重复上报。++## 实现与接口++### 读取与导出++内部逻辑路径解析、资源搜索、缺失检查和文件大小查询只读取逻辑元数据,不触发下载。实际显示图片、播放音视频、打开 PDF、访问资源链接、复制资源或导出时才补齐内容。用于为外部打开准备实际文件路径的 `/api/asset/resolveAssetPath` 也会先补齐资源。HTTP 和原始文件 API 先完成路径、符号链接、发布权限及加密笔记本权限检查,再执行下载。++导出在持有笔记本读锁和创建产物之前预取引用资源,按每个文档实际所属的笔记本和完整路径读取,范围包含子文档、关联文档、脚注、查询嵌入、题头图、数据库及关联数据库中的资源。单文件导出中的脚注资源不受是否另行导出关联文档影响。目录资源根据逻辑清单补齐,不能只依靠磁盘遍历。下载或复制失败向上传播,不将缺少资源的产物报告为成功。++加密资源下载后仍保持原始密文,读取和导出继续由现有认证解密流程处理,兼容已发布的资源格式。不改变密钥信封、主盐、AAD 或密钥派生,不通过明文回退处理认证错误。读取和明文导出前检查笔记本准入,不在持有笔记本读锁期间等待网络。锁定笔记本的资源读取请求和仅枚举文件名不会触发下载;完整同步、密文备份及删除前保存历史可以补齐原始密文。++## 兼容与恢复++按需设备的本地快照可能只有部分资源内容,界面通过 `requiresDownload` 独立提示。读取历史资源按该快照的精确文件版本补齐分块,不覆盖工作区当前资源。完整云端快照下载检查所有目标文件的分块,即使其元数据已经存在也不跳过检查;失败时不创建成功标签。++恢复快照前,先补齐当前工作区和目标快照所需的资源。切回全部下载时,同时补齐当前资源和所有保留快照缺少的历史内容;失败则保留原设置。切换同步来源、云端清理、删除当前云目录及重置仓库或密钥前检查这些依赖,未完成时保留原来源。重建仓库前,只有旧状态认证成功且依赖完整,才能清除设备状态和标记。++官方云登出允许保留原来源标识,以便本地索引和已下载快照继续使用,随后重新认证原账号。存在未完成依赖时,跨区登录、换账号和注销账号受完整性检查保护。++未补齐的历史快照仍依赖对应云端内容的保留。其他设备清理云端或外部删除云对象可能使历史版本无法下载,因此部分本地快照不等价于完整离线备份。需要离线备份或更换来源时,应先完成全部下载。旧版本客户端不了解设备状态标记,降级前也必须完成全部下载;标记不能阻止旧版本把未下载文件当作本地删除。++## 验证范围++实现同时涉及 `siyuan`、`dejavu` 和 `petal`。内核调用新增的 `dejavu` 资源下载及快照完整性接口,发布时应先发布依赖并更新模块版本。本地开发可使用临时 `replace` 指向 `dejavu` 检出,该替换不能提交。++回归覆盖完整与按需设备互相同步、单向同步、重复索引、远端版本更新、并发物化、本地修改保护、应用中断恢复、状态认证失败、来源变更、历史快照补齐、目录资源导出和已有加密资源格式。前端执行 `pnpm run lint`,语言执行 `python scripts/check-lang-keys.py`;不通过构建前端产物或编译运行内核进行验证。diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex b6d9ed20e5..c3433bbc56 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -1,20 +1,16 @@-# SiYuan Encrypted Notebook+# Encrypted notebooks-## 1. Design Goals+[中文](ENCRYPTED-NOTEBOOK.zh-CN.md)-Implement an "encrypted notebook" in SiYuan — a special notebook whose `.sy` documents, assets (including filenames), attribute-view definitions, and SQLite index databases (content + blocktree) are all stored encrypted on disk, requiring a master password to unlock and view the content. Existing normal notebooks are completely unaffected.+## Feature scope-**Maintenance status**: Encrypted notebook development is complete, and the feature is maintained as released.+### Design goals-Existing encrypted data is the compatibility baseline. Format and key-management changes must preserve access to existing data and its recovery paths; development status must never justify requiring users to delete or recreate their data. This covers documents, assets and their original names, attribute-view definitions, key envelopes, backups, history, and sync snapshots.--Database bindings follow the same isolation boundary. When importing a `.sy.zip` into an encrypted notebook, bindings to blocks included in that import are remapped to the imported blocks; bindings to blocks outside the import become detached rows, preserving row IDs, stored text, and other field values. Imported document backlinks retain only databases included in the archive. Import must not write database backlinks into documents outside the target boundary. Ordinary imports retain bindings to existing ordinary documents. Adding or replacing bound rows and editing a bound primary key must validate the boundary before changing either the row or the document.+Encrypted notebooks store `.sy` documents, assets and their original names, attribute-view definitions, and SQLite index databases as encrypted data. Users enter a master password to unlock and access each notebook independently. Ordinary notebooks require no migration.-Existing invalid database backlinks are not silently deleted or resolved across encryption boundaries during export. Export reports the affected database ID and preserves the source data. To diagnose an affected document, compare its `custom-avs` entries with the databases in its permitted storage scope, retain a backup, and explicitly remove only confirmed invalid bindings. Missing files, corrupt data, and authentication failures remain errors; merely unlocking another encrypted notebook does not make its databases part of the document's export scope. This binding correction does not change ciphertext formats, AAD, keys, or legacy authenticated readers.--Table-cell rich text uses document `Spec: "4"` and an optional `TableCellRich` source envelope inside the authenticated plaintext AST. Existing document versions remain readable without converting their cells. Document encryption envelopes, AAD, subkey derivation, and recovery keys are unchanged. Reads, exports, history, snapshots, and recovery authenticate ciphertext first, then validate the document and rich text versions; unknown or damaged source is rejected while preserving the original data. Inline projections may be rebuilt only after authentication and source validation succeed.+Encrypted notebooks are maintained as a released feature.-## 2. Core Constraints+### Core constraints| Aspect | Design Decision ||---|---|@@ -24,10 +20,10 @@ Table-cell rich text uses document `Spec: "4"` and an optional `TableCellRich` s| Password | Shared master password (KEK envelope, per-notebook independent DEK) || Unlock granularity | Strictly per-notebook unlock (KEK used and discarded, ~1s Argon2id per unlock) || SQLite database scheme | Each encrypted notebook has its own physical SQLCipher SQLite database, isolated from the global siyuan.db |-| **Isolation principle** | **Each encrypted notebook is an independent island — isolated from normal notebooks, and encrypted notebooks are also isolated from each other. Data, block refs, database mirroring, and moves never cross the encrypted-notebook boundary. Unlocking one encrypted notebook does not affect the locked state of other encrypted notebooks.** |+| Isolation principle | Each encrypted notebook is an independent island — isolated from normal notebooks, and encrypted notebooks are also isolated from each other. Data, block refs, database mirroring, and moves never cross the encrypted-notebook boundary. Unlocking one encrypted notebook does not affect the locked state of other encrypted notebooks. || Global features | Encrypted notebooks never participate (global search / graph / block refs cannot see them) || Block refs | Normal refs within the notebook; cross-boundary refs forbidden (bidirectional: normal↔encrypted, encrypted A↔encrypted B) |-| AI / LLM | No functional-layer isolation — when unlocked, AI/LLM can read content directly and use in-notebook search; when locked, no usable DEK handle exists and dedicated entry points deny access. Global search, semantic search, and embedding vectorization never participate (see §13) |+| AI / LLM | No functional-layer isolation — when unlocked, AI/LLM can read content directly and use in-notebook search; when locked, no usable DEK handle exists and dedicated entry points deny access. Global search, semantic search, and embedding vectorization never participate (see "AI / LLM Reachability") || 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 |@@ -40,51 +36,199 @@ Table-cell rich text uses document `Spec: "4"` and an optional `TableCellRich` s| Existing normal notebooks | Completely untouched, zero migration || Existing encrypted data | Remains readable and recoverable after upgrades; format changes retain authenticated legacy reads or provide recoverable migration without requiring users to delete or recreate their data |-## 3. Encrypted Notebook vs Normal Notebook+### Comparison with ordinary notebooks| Aspect | Normal Notebook | Encrypted Notebook ||---|---|---|-| **Create** | Anytime, no restrictions | Must first enable encryption (set master password); creating requires verifying master password |-| **Open (Mount)** | Direct open | Must first enter master password to unlock (~1s Argon2id each time); the application obtains a managed DEK handle |-| **Close (Unmount)** | Closing makes it invisible | Close = lock (stop new access + wait for or cancel in-flight work + remove DEK from the managed key cache + delete encrypted SQLite databases + best-effort cleanup of kernel-managed plaintext caches and temporary files) |-| **After restart** | Keeps last open state | Force-closed; must re-enter master password to unlock |-| **.sy files** | Plaintext JSON on disk | AES-256-GCM ciphertext on disk, transparently decrypted on read |-| **assets files** | Plaintext binary, original filename | AES-256-GCM ciphertext, filename desensitized, original name encrypted |-| **database files** | Global `storage/av/<avID>.json` (plaintext) | Notebook-level `<boxID>/storage/av/<avID>.json` (DEK-encrypted) |-| **content SQLite database** | Written to global siyuan.db (plaintext) | Written to independent siyuan-encrypted-`<boxID>`.db (SQLCipher) |-| **blocktree SQLite database** | Written to global blocktree.db (plaintext) | Written to independent siyuan-encrypted-`<boxID>`-blocktree.db (SQLCipher) |-| **Global search** | Participates (FTS hits) | Does not participate (data not in global SQLite database) |-| **Graph** | Participates | Does not participate |-| **Block refs** | Referrable by any notebook | Normal refs within notebook; cross-boundary refs forbidden (bidirectional) |-| **Move doc (cross-notebook)** | Supported | Forbidden across encrypted boundary |-| **Doc to heading (Doc2Heading)** | Supported | Forbidden across encrypted boundary |-| **database mirroring (cross-notebook)** | Supported | Forbidden across encrypted boundary |-| **Asset file rename** | Supported | Not supported (desensitized filename rename breaks the mapping) |-| **Asset text recognition (OCR)** | Supported | Not supported, regardless of lock state |-| **Import** | Supported | Supported (.sy.zip and Markdown, auto DEK-encrypted before writing to disk) |-| **In-notebook search** | Via global SQLite database | Via encrypted SQLite database |-| **Backlinks panel** | Via global SQLite database | Via encrypted SQLite database (incl. mention subquery) |-| **Open doc / outline / breadcrumb / block info / float preview** | Via global SQLite database | Via encrypted SQLite database |-| **Database** | Via global storage + global SQLite database | Via notebook-level storage (DEK-encrypted) + encrypted SQLite database |-| **File history** | Supported | Supported (ciphertext .sy copied verbatim to history dir; each history entry retains the boxID, object type, and stable file basename at snapshot creation, and viewing or rollback uses all three as the AAD context) |-| **Deleted notebook history** | Supported | Supported (entire directory backed up as ciphertext before deletion and restored verbatim; recovery also requires the matching global key backup and master password) |-| **Embedding vectorization / semantic search** | Participates | Does not participate (encrypted data never enters the global block_embeddings table; the embedding pipeline reads only the global SQLite database — independent of lock state) |-| **Agents / AI chat / MCP** | Can read content, can search | Available when unlocked (can read blocks, list docs, search within notebook); unreachable when locked (see §13). Global search / semantic search not included |-| **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) |-| **Tags** | Participates (global aggregation) | Not supported (feature limitation) |-| **List icon** | User-custom emoji | Shows lock icon when closed; restores emoji when opened |-| **Export (.sy.zip)** | Supported | Supported (exports plaintext when unlocked; rejected when locked; see §12 Security Premise) |-| **Data sync** | dejavu syncs plaintext | Unchanged (ciphertext in, ciphertext out, self-consistent) |-| **Delete notebook** | Delete directory | Delete directory + delete encrypted SQLite database files + delete notebook-level database storage |-| **Rebuild index** | Full | Skipped on startup (closed); 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), 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; when unlocked, AI/LLM can read content directly and use in-notebook search. Encrypted notebooks are also isolated from each other. Normal notebooks are completely unaffected.--## 4. Key Architecture+| Create | Anytime, no restrictions | Must first enable encryption (set master password); creating requires verifying master password |+| Open (Mount) | Direct open | Must first enter master password to unlock (~1s Argon2id each time); the application obtains a managed DEK handle |+| Close (Unmount) | Closing makes it invisible | Close = lock (stop new access + wait for or cancel in-flight work + remove DEK from the managed key cache + delete encrypted SQLite databases + best-effort cleanup of kernel-managed plaintext caches and temporary files) |+| After restart | Keeps last open state | Force-closed; must re-enter master password to unlock |+| .sy files | Plaintext JSON on disk | AES-256-GCM ciphertext on disk, transparently decrypted on read |+| assets files | Plaintext binary, original filename | AES-256-GCM ciphertext, filename desensitized, original name encrypted |+| database files | Global `storage/av/<avID>.json` (plaintext) | Notebook-level `<boxID>/storage/av/<avID>.json` (DEK-encrypted) |+| content SQLite database | Written to global siyuan.db (plaintext) | Written to independent siyuan-encrypted-`<boxID>`.db (SQLCipher) |+| blocktree SQLite database | Written to global blocktree.db (plaintext) | Written to independent siyuan-encrypted-`<boxID>`-blocktree.db (SQLCipher) |+| Global search | Participates (FTS hits) | Does not participate (data not in global SQLite database) |+| Graph | Participates | Does not participate |+| Block refs | Referrable by any notebook | Normal refs within notebook; cross-boundary refs forbidden (bidirectional) |+| Move doc (cross-notebook) | Supported | Forbidden across encrypted boundary |+| Doc to heading (Doc2Heading) | Supported | Forbidden across encrypted boundary |+| database mirroring (cross-notebook) | Supported | Forbidden across encrypted boundary |+| Asset file rename | Supported | Not supported (desensitized filename rename breaks the mapping) |+| Asset text recognition (OCR) | Supported | Not supported, regardless of lock state |+| Import | Supported | Supported (.sy.zip and Markdown, auto DEK-encrypted before writing to disk) |+| In-notebook search | Via global SQLite database | Via encrypted SQLite database |+| Backlinks panel | Via global SQLite database | Via encrypted SQLite database (incl. mention subquery) |+| Open doc / outline / breadcrumb / block info / float preview | Via global SQLite database | Via encrypted SQLite database |+| Database | Via global storage + global SQLite database | Via notebook-level storage (DEK-encrypted) + encrypted SQLite database |+| File history | Supported | Supported (ciphertext .sy copied verbatim to history dir; each history entry retains the boxID, object type, and stable file basename at snapshot creation, and viewing or rollback uses all three as the AAD context) |+| Deleted notebook history | Supported | Supported (entire directory backed up as ciphertext before deletion and restored verbatim; recovery also requires the matching global key backup and master password) |+| Embedding vectorization / semantic search | Participates | Does not participate (encrypted data never enters the global block_embeddings table; the embedding pipeline reads only the global SQLite database — independent of lock state) |+| Agents / AI chat / MCP | Can read content, can search | Available when unlocked (can read blocks, list docs, search within notebook); unreachable when locked (see "AI / LLM Reachability"). 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) |+| Tags | Participates (global aggregation) | Not supported (feature limitation) |+| List icon | User-custom emoji | Shows lock icon when closed; restores emoji when opened |+| Export (.sy.zip) | Supported | Supported (exports plaintext when unlocked; rejected when locked; see "Security Boundary" Security Premise) |+| Data sync | dejavu syncs plaintext | Unchanged (ciphertext in, ciphertext out, preserving ciphertext) |+| 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/\* | 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 |++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; when unlocked, AI/LLM can read content directly and use in-notebook search. Encrypted notebooks are also isolated from each other. Normal notebooks are completely unaffected.++### Feature limitations++An encrypted notebook is an island; some features are unsupported because of their cross-notebook nature or dependence on global aggregation. These are explicit feature boundaries.++- Flashcards / spaced repetition: Decks and scheduling are cross-notebook and depend on the global SQLite database; not supported++- 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 are not supported++- Tags: Global aggregation view (scans the global spans table); encrypted notebooks are not supported++- Asset file rename: Encrypted-notebook asset filenames are already desensitized to `uuid-blockID.ext`; the disk filename participates in AAD, so renaming requires re-enveloping the whole asset++- Unused asset cleanup: Encrypted-notebook assets are excluded from global unused-asset cleanup (island, assets do not cross boundaries), preventing false deletion when locked and document references cannot be scanned++- Unused database cleanup: Encrypted-notebook database definitions are excluded from global unused-database cleanup, preventing false deletion when locked and reference relationships cannot be confirmed++## User interaction++### Interaction design++| Scenario | Interaction |+|---|---|+| Enable | Settings - Authentication - Encrypted Notebook, then enable the toggle and set a master password (double input + risk confirmation) |+| Disable | Supported only when no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on the current key backup; otherwise reject, or require explicit permanent purge of those recovery artifacts before deleting global config and backup |+| Create | File panel - "more" menu - "New encrypted notebook"; enter a name and master password to unlock and open automatically |+| Icon | Shows lock icon when closed (locked); restores user emoji when opened (unlocked) |+| Unlock | Click a closed encrypted notebook, enter the password in the master-password prompt (🔓 Unlock xxx), and wait about one second for it to open |+| Lock | Equals close: first block new operations, wait for or cancel in-flight work, then remove managed DEK handles, delete encrypted SQLite databases, and best-effort clean kernel-managed plaintext caches, temporary files, and access tokens. Unsaved edits and file history are automatically saved before locking |+| Auto-lock | Each unlocked notebook stores its own last-activity time. Real UI interaction by an authenticated user in the current workspace refreshes all currently unlocked encrypted notebooks together. A headless client can perform the same refresh through an explicit keepalive endpoint that requires authentication and the administrator role; background reads, sync, indexing, and other non-user activity do not keep notebooks alive automatically |+| Change password | Settings - Authentication - Encrypted Notebook - "Change master password" |+| Move document | A parent-only move within an encrypted notebook moves ciphertext verbatim and updates indexes; a basename change re-envelopes content. Moves between normal notebooks remain normal; cross-boundary (normal↔encrypted) moves are rejected with a prompt |+| Doc to heading | Cross-boundary rejected with a prompt |+| Block ref | Normal refs within an encrypted notebook (searching `((` only searches this notebook; backlinks panel displays normally); cross-boundary (normal↔encrypted, encrypted A↔encrypted B) blocked |+| database mirroring | Normal mirroring within an encrypted notebook; cross-boundary forbidden |+| Asset file rename | Not supported (desensitized-filename rename breaks the mapping) |+| Import | Supported: imported .sy.zip or Markdown files are auto DEK-encrypted before writing to disk |+| File history | Supported (must unlock the corresponding encrypted notebook before viewing; the history index stores no plaintext content) |+| 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, preserving ciphertext) |++### Usage guide++#### First-time enablement++1. Go to Settings - Authentication - Encrypted Notebook and toggle it on++2. Set a master password (double input + risk confirmation). The master password is the unified key for all encrypted notebooks — you must remember it; there is no recovery backdoor++3. Once enabled, you can create a new encrypted notebook from the file-panel "more" menu; enter a name and master password to unlock and open it automatically++> Strength recommendation: 12+ characters, mixed case + digits + symbols. The stronger the master password, the higher the brute-force resistance (there is no password-recovery backdoor).++#### Daily use: unlock and lock++- Unlock: Click a closed encrypted notebook, enter the master password, and wait about one second for Argon2id derivation before it opens. Unlocking only affects that notebook; other encrypted notebooks stay locked++- 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, 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 "Security Boundary" Security premise).++#### Changing the master password+Go to Settings - Authentication - Encrypted Notebook - Change master password. The operation rewraps each notebook's WrappedDEK and protects historical recovery keys with the new password without re-encrypting document data. Key backups are refreshed and synchronized. The current backup and password can still recover deleted-notebook history created before the password change.++> Important semantics: password change uses the KEK envelope model — the DEK itself does not change; only a new KEK (derived from the new password) re-wraps the WrappedDEK. This means changing the password does not revoke the old password's decryption ability: if the old password and an old WrappedDEK (retained in sync endpoints, backups, or historical snapshots) leak together, the same DEK can still be unwrapped, decrypting current data. If you suspect the old password has leaked, export the content as plaintext, import it into a freshly created encrypted notebook (new DEK), and securely delete the plaintext files after confirming the migration rather than only changing the password.++#### Multi-device sync+Encrypted-notebook ciphertext `.sy`/assets/database files sync along with the data (ciphertext in, ciphertext out, preserving ciphertext); the global key material (MasterSalt etc.) is also automatically backed up to the sync directory. No manual "enable" is needed on a new device after sync:++An encrypted notebook's open state is never inherited across devices. Even if the synchronized `conf.json` records that another device had the notebook open, the UI and kernel must treat it as closed and skip indexing whenever the local process has no DEK for that notebook; entering the master password unlocks and mounts it locally.++When sync removes an encrypted notebook currently mounted on this device, the kernel completes the local deletion transition before any full-reindex branch, exit early-return, or UI reload: it closes admission, drains active leases, clears the DEK and mount state, deletes dedicated index databases, and completes global-index cleanup. The now-missing disk configuration is never used to decide whether cleanup is required.++1. Configure the same sync account on the new device and complete a sync++2. Sync pulls the key backup to the local machine; the kernel auto-restores the "enabled" state++3. Just click the encrypted notebook and enter the master password to unlock and use it++If the notebook still shows as locked on the new device after sync, that is normal — click it and enter the master password.++Sync recovery can validate backup integrity but cannot prove that a backup is the newest version. Keep an independently versioned key backup. When historical copies conflict, the system cannot determine freshness automatically; before recovery, the user confirms a version from trusted source and time information.++#### Import and export++- Import: Supports importing `.sy.zip` and Markdown; content is automatically DEK-encrypted before writing to disk, identical to manually created documents++- Export: Identical to normal notebooks (must unlock first; exports plaintext). `.sy.zip`, HTML, Word, PDF, Markdown, etc. are all supported; export is rejected while locked++- 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.++#### Recovering from a lost key backup+If both `conf/conf.json` and the key backup in the sync directory are lost (an extreme case), re-enabling the encrypted-notebook feature will be rejected with a prompt to restore the backup file. As long as you can recover `data-crypto-backup.json` from another synced device or a previously exported key file, you can import it via the "Import key" button shown in `Disabled` or `RecoveryRequired`, or manually put it back at `<workspace>/data/.siyuan/` and re-enable, then unlock with the master password matching that key.++Restoring deleted encrypted-notebook history also requires the global key backup matching its WrappedDEK and the master password. While you still need that local recovery path, do not permanently purge either the history or its matching key backup; disabling must refuse to proceed when it discovers such a dependency.++#### Suitable scenarios for encrypted notebooks++- Private diary, financial records, medical information++- Work secrets, business plans, contracts++- Concern about device loss or theft — once encrypted, even if the disk data is recovered, it remains ciphertext without the master password++#### 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)++- Content needing flashcard review (not supported)++- Content needing bookmark/tag management (not supported)++- Content you do not want AI/LLM to touch (AI can read it when unlocked; keep it locked if that matters)++- Large numbers of large files (assets fully decrypt on every browse)++#### Daily usage habits++1. You must remember the master password: Forgetting it = data permanently unrecoverable (no backdoor)++2. Lock after use: Reduce the DEK's exposure time in memory++3. Don't put all your notes in encrypted notebooks: Only put what is truly sensitive++4. Master password strength: Recommend 12+ characters, mixed case + digits + symbols++5. Backup: Keep versioned ciphertext backups and their matching key backups separately; losing the master password or every matching key backup makes the ciphertext unrecoverable++## Data and storage++### Key architecture```User master password@@ -97,31 +241,34 @@ User master password└─→ unwrap BoxConf.WrappedDEK → DEK₃ → encrypts notebook 3```-- **Argon2id**: OWASP 2023 recommended parameters, brute-force resistant (memory-hard)-- **DEK**: Per-notebook independent 32-byte random key; the key that actually encrypts data-- **KEK envelope**: Changing the password only re-wraps the DEK; data is not re-encrypted-- **KEK not cached**: Derived on every unlock; strict per-notebook isolation+- Argon2id: Memory-hard key derivation configured with 64 MB, 3 passes, and 4 threads++- DEK: Per-notebook independent 32-byte random key; the key that actually encrypts data-### 4.1 MasterSalt Backup and Cross-Device Recovery+- KEK envelope: Changing the password only re-wraps the DEK; data is not re-encrypted-MasterSalt is the global root of KEK derivation — the master password + MasterSalt derive the KEK via Argon2id, and the KEK then unwraps each notebook's WrappedDEK. **Losing MasterSalt permanently locks the data**: even with the same master password, a changed salt derives a different KEK, so old WrappedDEKs cannot be unwrapped. A backup-and-recovery mechanism is therefore introduced.+- KEK not cached: Derived on every unlock; strict per-notebook isolation-**Backup**: `<DataDir>/.siyuan/data-crypto-backup.json`, holding the full NotebookCrypto (MasterSalt/KEKVerifier/KDFParams). Located inside DataDir, it **enters the dejavu sync scope**. It is refreshed when enabling encrypted notebooks and when changing the master password. It may be deleted on disable only after confirming that no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on it, or after the user explicitly chooses to purge those recovery artifacts permanently. Stored as plaintext JSON (salt is not secret, verifier is ciphertext — identical to how they are stored in `conf/conf.json`).+#### MasterSalt Backup and Cross-Device Recovery++MasterSalt is the global root of KEK derivation — the master password + MasterSalt derive the KEK via Argon2id, and the KEK then unwraps each notebook's WrappedDEK. Losing MasterSalt permanently locks the data: even with the same master password, a changed salt derives a different KEK, so old WrappedDEKs cannot be unwrapped. A backup-and-recovery mechanism is therefore introduced.++Backup: `<DataDir>/.siyuan/data-crypto-backup.json`, holding the full NotebookCrypto (MasterSalt/KEKVerifier/KDFParams/HistoryKEKs). Located inside DataDir, it enters the dejavu sync scope. It is refreshed when enabling encrypted notebooks and when changing the master password. It may be deleted on disable only after confirming that no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on it, or after the user explicitly chooses to purge those recovery artifacts permanently. The file uses plaintext JSON, with the verifier and historical KEKs stored as ciphertext, matching their representation in `conf/conf.json`.Each encrypted notebook separately stores `<DataDir>/<boxID>/.siyuan/notebook-crypto-backup.json`, containing that notebook's BoxEncryption key envelope (WrappedDEK/WrapNonce and authenticated metadata). The global `data-crypto-backup.json` supplies the KEK derivation identity, while the per-notebook `notebook-crypto-backup.json` supplies the wrapped DEK; neither file can replace the other.-**Recovery triggers** (covering scenarios such as conf.json loss, sync to a new device, importing Data.zip):+Recovery triggers (covering scenarios such as conf.json loss, sync to a new device, importing Data.zip):| Trigger scenario | Function | Password required? | Notes ||---|---|---|---|| After sync completes (backup file pulled down) | `restoreNotebookCryptoConfigFromBackup` | No | Loads the config back into the local conf.json and sets `Enabled=true`; UI shows "enabled, locked" || After importing Data.zip | `restoreNotebookCryptoConfigFromBackup` | No | Same; covers "backup arrived with Data.zip but the local machine is not enabled" || User enters master password to unlock (fallback) | `tryRestoreNotebookCryptoFromBackup` | Yes | `deriveKEK` attempts recovery when the local `Enabled=false`; returns the KEK after verifying the password |-| User manually enables (fool-proof guard) | `tryRestoreNotebookCryptoFromBackup` | Yes | When encrypted notebooks already exist, refuses to regenerate salt and instead recovers from backup, verifying the password |+| User manually enables (recovery guard) | `tryRestoreNotebookCryptoFromBackup` | Yes | When encrypted notebooks already exist, refuses to regenerate salt and instead recovers from backup, verifying the password |-**Config recovery vs key recovery, separated**: Config recovery only needs to read the backup file and load back the salt/verifier (no password required, since salt is not secret and data remains undecryptable without the password); key recovery requires the password to derive the KEK and verify against the verifier. This allows the "enabled" state to be reached automatically after sync/import, so the user can unlock by entering the master password.+Config recovery vs key recovery, separated: Config recovery only needs to read the backup file and load back the salt/verifier (no password required, since salt is not secret and data remains undecryptable without the password); key recovery requires the password to derive the KEK and verify against the verifier. This allows the "enabled" state to be reached automatically after sync/import, so the user can unlock by entering the master password.-**Manual key export/import**: Beyond auto-sync, users can manually export/import the key backup under **Settings - Authentication - Encrypted Notebook**, as an independent recovery channel outside sync (e.g. when sync is unavailable, for cross-account migration, or offline physical transfer).+Manual key export/import: Beyond auto-sync, users can manually export/import the key backup under Settings - Authentication - Encrypted Notebook, as an independent recovery channel outside sync (e.g. when sync is unavailable, for cross-account migration, or offline physical transfer).| Operation | Entry | Notes ||---|---|---|@@ -130,11 +277,11 @@ Each encrypted notebook separately stores `<DataDir>/<boxID>/.siyuan/notebook-crImport guard: a complete `Enabled` configuration rejects import to avoid overwriting the existing salt and orphaning WrappedDEKs. `RecoveryRequired` permits import only when the authenticated candidate key can unwrap every live encrypted notebook and every kernel-enumerable deleted-notebook history dependency. The backup file itself does not contain the master password (salt is not secret, verifier is ciphertext), so export/import does not leak plaintext data; unlocking still requires the master password.-**Fool-proof guard**: When encrypted notebooks already exist on disk (notebooks with `Encrypted=true`) or kernel-enumerable encrypted recovery artifacts exist, `EnableEncryptedNotebook` **refuses to regenerate MasterSalt** (which would orphan old WrappedDEKs) and instead recovers from backup first; only if the backup is missing does it error out and guide the user to restore `conf.json` or the backup file. Symmetrically, `DisableEncryptedNotebook` scans live notebooks, deleted-notebook history, and local recovery snapshots; it refuses to disable while a dependency exists unless the user explicitly chooses to purge those recovery artifacts permanently. Sync endpoints, offline media, and external snapshots cannot be enumerated reliably, so users who may need those copies later must retain an independently exported matching key backup before disabling.+Recovery guard: When encrypted notebooks already exist on disk (notebooks with `Encrypted=true`) or kernel-enumerable encrypted recovery artifacts exist, `EnableEncryptedNotebook` refuses to regenerate MasterSalt (which would orphan old WrappedDEKs) and instead recovers from backup first; only if the backup is missing does it error out and guide the user to restore `conf.json` or the backup file. Symmetrically, `DisableEncryptedNotebook` scans live notebooks, deleted-notebook history, and local recovery snapshots; it refuses to disable while a dependency exists unless the user explicitly chooses to purge those recovery artifacts permanently. Sync endpoints, offline media, and external snapshots cannot be enumerated reliably, so users who may need those copies later must retain an independently exported matching key backup before disabling.-**Prerequisite**: `restoreNotebookCryptoConfigFromBackup` only takes effect when the local `Enabled=false`; it never overwrites an in-use local config.+Prerequisite: `restoreNotebookCryptoConfigFromBackup` only takes effect when the local `Enabled=false`; it never overwrites an in-use local config.-## 5. Encrypted File Layout+### Encrypted file layout```<workspace>/@@ -142,7 +289,7 @@ Import guard: a complete `Enabled` configuration rejects import to avoid overwri├── storage/av/ ← normal-notebook database files (plaintext)├── data/│ ├── .siyuan/-│ │ └── data-crypto-backup.json ← NotebookCrypto backup (MasterSalt/KEKVerifier, synced; see §4.1)+│ │ └── data-crypto-backup.json ← NotebookCrypto backup (MasterSalt/KEKVerifier, synced; see MasterSalt backup and cross-device recovery)│ ├── <boxID>/ ← encrypted notebook directory│ │ ├── .siyuan/│ │ │ ├── conf.json ← BoxConf (Encrypted=true + WrappedDEK)@@ -163,233 +310,256 @@ Import guard: a complete `Enabled` configuration rejects import to avoid overwri└── siyuan-encrypted-<boxID>-blocktree.db ← encrypted-notebook blocktree SQLite database (SQLCipher)```-## 6. SQLite Database Isolation Design--```-Normal-notebook operations:- frontend → API → original function → global blocktree.db → global siyuan.db--Encrypted-notebook operations (dedicated read path, with boxID):- frontend(with notebook) → API handler dispatch → InBox function- → encrypted blocktree SQLite database → encrypted content SQLite database-```--**Write path**: Centralized funnel; selects db by notebook. Index queue, blocktree writers, index corrections are all routed by notebook.--**Read path**: Three-layer fall-through — the handler layer dispatches by the `notebook` parameter; original functions forward to the InBox variant (normal path passes empty boxID); the low-level wrapper decides routing by whether the encrypted SQLite database is open, with empty boxID always going to the global SQLite database.--**Deep full-routing principle**: Every SQL call on the read path of an encrypted notebook (including deep helpers: ref counts, block name/alias, child-block recursion, FTS counts, highlighting, mention search, refs definition queries, etc.) is routed to the encrypted SQLite database and never leaks to the global SQLite database.+### .sy / assets / database file encryption-**Generic-entry fallback**: Core functions like `GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` automatically iterate opened encrypted notebooks when a global lookup misses.+`.sy` transparent encryption (filesys layer):-## 7. .sy / assets / Database File Encryption--**`.sy` transparent encryption** (filesys layer):- `DEKProvider` callback injected (avoids circular dependency)+- Decrypts after read, encrypts before write; cache holds plaintext+- Reading an encrypted notebook's title requires a full read + decrypt before parsing+- `.sy` AAD binds the boxID, object type, and stable file basename `<rootID>.sy`, excluding every parent-directory component. The basename matches the decrypted root-block ID and is globally unique within the notebook+- Parent directories are outside AAD, and the application continues to build document topology from the existing directory structure. Loading verifies that the basename matches the decrypted root-block ID and rejects duplicate object IDs within one notebook, invalid paths, and hierarchy cycles, but does not provide cryptographic integrity for parent-directory relations-**assets encryption**:+assets encryption:+- On upload, fully read into memory + encrypt + write (cannot stream-encrypt)+- Filename desensitization: encrypted-notebook asset filenames are `<uuid>-<blockID>.<ext>`; the original name, plaintext size, and chunk count are authenticated encrypted metadata in the same asset container+- New containers start with `SYAE`; authenticated encrypted metadata contains `spec=2`, a 32-byte `containerID` generated by the operating system CSPRNG for each write, the original name, plaintext size, and chunk count. Content-chunk AAD is `siyuan:asset:<boxID>:assets/<diskName>:content:v2:<lowercase hexadecimal containerID>:<zero-based chunk index>`; name metadata uses the same asset prefix followed by `:metadata`. Chunks or metadata from different writes cannot be interchanged; rollback of an entire old container remains outside the protection boundary+- On read, authenticate and decrypt the name metadata first, then authenticate and decrypt each content chunk; downloads use the original name stored in the container+- Legacy `SYAE` assets whose metadata omits both `spec` and `containerID` remain readable, using `siyuan:asset:<boxID>:assets/<diskName>:content:<chunk index>` for chunk authentication. Name reads, content reads, export, and historical snapshots support this format. Explicit null versions, missing required new-format fields, unknown versions, and authentication failures are rejected without trying another version's AAD+- New or re-saved assets use version 2. Opening, previewing, downloading, or exporting does not rewrite the original file or require users to recreate assets. The legacy format retains its original per-chunk authentication and cannot retrospectively detect whether chunks from different writes were spliced. Re-saving creates a version 2 container with chunk binding but does not prove that the old content was never spliced. Compatible reads provide no downgrade or rollback protection; a replacement in the legacy format is checked under that format's rules+- Encrypted notebooks disable the global assets fallback; notebook-level is mandatory+- Asset file rename is forbidden because the desensitized disk filename participates in AAD and renaming requires re-enveloping the whole asset+- The original name and content reside in one encrypted container, so there is no cross-file name-mapping transaction; write failures are returned to the caller-**database file encryption**:+database file encryption:+- Path fallback: encrypted-notebook database files are stored at `<boxID>/storage/av/<avID>.json`; normal notebooks still use global `storage/av/`+- Read: first check the global path; on miss, iterate opened encrypted notebooks; after finding, DEK-decrypt then JSON-parse+- Save: after JSON serialization, route by path (global plaintext / encrypted-notebook DEK-encrypted)+- First creation: `RenderAttributeView` looks up the boxID from the blockID and presets ownership+- Mirroring: encrypted notebooks are forbidden from cross-boundary mirroring; within-notebook mirroring stores notebook-level `blocks.msgpack`-## 8. Security Design of History Features+## Implementation and interfaces-```-File history:- edit triggers history generation → ciphertext .sy copied verbatim to history dir- auto-generated before close/exit → ensures history is captured even after locking- history index → content left empty (ciphertext not indexed for search)- view history → read the snapshot boxID, object type, and stable file basename, then reconstruct the original AAD for decryption (notebook must be unlocked)- roll back → decrypt with the snapshot AAD → verify that the root-block ID matches the basename → load tree → let WriteTree serialize the restored content and re-envelope it with the target basename+### SQLite database isolation-Deleted-notebook history:- before deletion → entire directory backed up as ciphertext to history dir- restore → copy the ciphertext directory back verbatim without opening it; authenticate WrappedDEK with the matching global key backup and master password when unlocking- key retention → while kernel-managed history remains recoverable, deletion of the global key backup it depends on is forbidden; permanently purging the history removes the dependency+```+Normal-notebook operations:+ frontend → API → original function → global blocktree.db → global siyuan.db-database history:- generate → encrypted-notebook database files copied from notebook-level dir to history dir- view → decrypt with the boxID and object purpose/identifier recorded by the snapshot, never with the absolute history-directory path as AAD- roll back → encrypted-notebook database file/resources rolled back to notebook-level dir+Encrypted-notebook operations (dedicated read path, with boxID):+ frontend(with notebook) → API handler dispatch → InBox function+ → encrypted blocktree SQLite database → encrypted content SQLite database```-Parent directories below the history root are not part of AAD. Every history entry retains, in an unambiguous canonical form, the `boxID`, object type, and stable file basename or object identifier at snapshot creation; these values may be encoded by a fixed history layout or stored as metadata committed with the snapshot. Changing only a live document's parent directory leaves its AAD context unchanged; if its basename changes, existing history continues to authenticate with the old basename. Rollback first verifies the ciphertext and that the basename matches the decrypted object ID, then restores under the target parent directory. Document rollback also normalizes the tree and resolves duplicate block IDs, so WriteTree serializes the restored content and creates a fresh envelope even when the basename is unchanged. The historical ciphertext remains intact. Copying a deleted notebook back is a closed-state restoration, not proof that the current key backup matches; authentication happens on unlock, and a missing matching backup may be supplied later. Missing, malformed, or mismatched snapshot context rejects viewing and rollback; the implementation must not parse ciphertext as plaintext or replace the snapshot basename with the current basename.+Write path: Centralized funnel; selects db by notebook. Index queue, blocktree writers, index corrections are all routed by notebook.++Read path: Three-layer fall-through — the handler layer dispatches by the `notebook` parameter; original functions forward to the InBox variant (normal path passes empty boxID); the low-level wrapper decides routing by whether the encrypted SQLite database is open, with empty boxID always going to the global SQLite database.++Deep full-routing principle: Every SQL call on the read path of an encrypted notebook (including deep helpers: ref counts, block name/alias, child-block recursion, FTS counts, highlighting, mention search, refs definition queries, etc.) is routed to the encrypted SQLite database and never leaks to the global SQLite database.-## 9. Block-Ref Cross-Boundary Protection+Generic-entry fallback: Core functions like `GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` automatically iterate opened encrypted notebooks when a global lookup misses.++### Block-reference boundary checksBlock refs of an encrypted notebook: normal within the notebook, forbidden across the encrypted boundary. Three layers of defense:-1. **Frontend search dispatch**: When typing `((` or `{{` in an encrypted notebook triggers a search, the request carries a `notebook` parameter; the kernel only searches that notebook's own encrypted SQLite database, so results exclude other notebooks' blocks.-2. **Handler dispatch**: Encrypted notebooks call a dedicated search variant.-3. **Write-time fallback check**: Before a transaction commits, the tree is walked and each block-ref node is checked for crossing the boundary; if so, it is downgraded to plain text (ref attributes cleared, anchor text kept). Defends against hand-entered block IDs, drag-and-drop, paste, direct API calls.+1. Frontend search dispatch: When typing `((` or `{{` in an encrypted notebook triggers a search, the request carries a `notebook` parameter; the kernel only searches that notebook's own encrypted SQLite database, so results exclude other notebooks' blocks++2. Handler dispatch: Encrypted notebooks call a dedicated search variant++3. Write-time fallback check: Before a transaction commits, the tree is walked and each block-ref node is checked for crossing the boundary; if so, it is downgraded to plain text (ref attributes cleared, anchor text kept). Defends against hand-entered block IDs, drag-and-drop, paste, direct API calls-## 10. Cross-Boundary Move: Why Forbidden+### Cross-boundary move rulesEncrypted notebooks forbid moving documents across the encrypted boundary (normal ↔ encrypted, bidirectional).-**Data-corruption risk**: Cross-notebook moves use a filesystem Rename to directly move `.sy` bytes, with no encrypt/decrypt conversion. Ciphertext moved to a normal directory is unreadable; plaintext moved to an encrypted directory is unreadable. Indexes also cannot be migrated across dbs.+Data-corruption risk: Cross-notebook moves use a filesystem Rename to directly move `.sy` bytes, with no encrypt/decrypt conversion. Ciphertext moved to a normal directory is unreadable; plaintext moved to an encrypted directory is unreadable. Indexes also cannot be migrated across dbs.-**Move within the same encrypted notebook**: A `.sy` ciphertext object's AAD binds only its stable basename, not its parent directory. A move that preserves the basename follows normal within-notebook move semantics and may Rename ciphertext verbatim without re-enveloping the root or descendants. Only a basename change verifies and decrypts with the old basename and re-envelopes with the new one. Indexes are updated after the move, and failure handling remains the same as for a normal notebook; no additional encrypted hierarchy metadata is introduced.+Move within the same encrypted notebook: A `.sy` ciphertext object's AAD binds only its stable basename, not its parent directory. A move that preserves the basename follows normal within-notebook move semantics and may Rename ciphertext verbatim without re-enveloping the root or descendants. Only a basename change verifies and decrypts with the old basename and re-envelopes with the new one. Indexes are updated after the move, and failure handling remains the same as for a normal notebook; no additional encrypted hierarchy metadata is introduced.-**Security-leak risk** (more critical): When moving from an encrypted notebook to a normal notebook — the document body escapes encryption protection; associated resources must be moved out and decrypted together; the reference network binding blocks to subdocuments is split or leaked along with it; index-metadata cross-db migration breaks isolation.+Security-leak risk: When moving from an encrypted notebook to a normal notebook — the document body escapes encryption protection; associated resources must be moved out and decrypted together; the reference network binding blocks to subdocuments is split or leaked along with it; index-metadata cross-db migration breaks isolation.-**Design stance**: An encrypted notebook is an island; content does not enter or leave (moving out of an encrypted notebook to a normal one would leak plaintext; the reverse would corrupt the ciphertext).+Design stance: An encrypted notebook is an island; content does not enter or leave (moving out of an encrypted notebook to a normal one would leak plaintext; the reverse would corrupt the ciphertext).-## 11. Interaction Design+### AI / LLM reachability-| Scenario | Interaction |-|---|---|-| Enable | Settings - Authentication - Encrypted Notebook, then enable the toggle and set a master password (double input + risk confirmation) |-| Disable | Supported only when no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on the current key backup; otherwise reject, or require explicit permanent purge of those recovery artifacts before deleting global config and backup |-| Create | File panel - "more" menu - "New encrypted notebook"; enter a name and master password to unlock and open automatically |-| Icon | Shows lock icon when closed (locked); restores user emoji when opened (unlocked) |-| Unlock | Click a closed encrypted notebook, enter the password in the master-password prompt (🔓 Unlock xxx), and wait about one second for it to open |-| Lock | Equals close: first block new operations, wait for or cancel in-flight work, then remove managed DEK handles, delete encrypted SQLite databases, and best-effort clean kernel-managed plaintext caches, temporary files, and access tokens. Unsaved edits and file history are automatically saved before locking |-| Auto-lock | Each unlocked notebook stores its own last-activity time. Real UI interaction by an authenticated user in the current workspace refreshes all currently unlocked encrypted notebooks together. A headless client can perform the same refresh through an explicit keepalive endpoint that requires authentication and the administrator role; background reads, sync, indexing, and other non-user activity do not keep notebooks alive automatically |-| Change password | Settings - Authentication - Encrypted Notebook - "Change master password" |-| Move document | A parent-only move within an encrypted notebook moves ciphertext verbatim and updates indexes; a basename change re-envelopes content. Moves between normal notebooks remain normal; cross-boundary (normal↔encrypted) moves are rejected with a prompt |-| Doc to heading | Cross-boundary rejected with a prompt |-| Block ref | Normal refs within an encrypted notebook (searching `((` only searches this notebook; backlinks panel displays normally); cross-boundary (normal↔encrypted, encrypted A↔encrypted B) blocked |-| database mirroring | Normal mirroring within an encrypted notebook; cross-boundary forbidden |-| Asset file rename | Not supported (desensitized-filename rename breaks the mapping) |-| Import | Supported: imported .sy.zip or Markdown files are auto DEK-encrypted before writing to disk |-| File history | Supported (must unlock the corresponding encrypted notebook before viewing; the history index stores no plaintext content) |-| 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) |+The visibility of encrypted notebooks to AI/LLM through supported notebook-specific entry points is determined by the lock state; there is no separate functional-layer switch to hide content from AI. Global search, semantic search, and embedding vectorization never include encrypted content.++When locked: AI/LLM (including MCP and agents) cannot obtain a usable DEK handle, and every encrypted-notebook entry point denies access. Dedicated databases are closed and disk content is ciphertext, so these callers cannot read encrypted content.++When unlocked: the DEK is in memory, so AI/LLM can read encrypted-notebook content and search within a notebook — MCP tools can list encrypted notebooks and their documents, read block content, run in-notebook FTS search, etc. However, global search, semantic search, and embedding vectorization still do not include encrypted content (encrypted data never enters the global `block_embeddings`/`blocks` tables; physically unreachable), see "Encrypted Notebook vs Normal Notebook" comparison table.++Design stance: there is no "hide from AI" isolation at the functional layer, because such isolation is neither thorough nor easy to reason about. Supported entry points cannot access content after locking, but locking does not replace process- and OS-level protection. Users only need to understand one rule: lock sensitive content after use.++### Performance differences-## 12. Security Boundary+| Operation | Normal Notebook | Encrypted Notebook | Reason |+|---|---|---|---|+| Unlock (Mount) | Instant | ~1 second delay | Argon2id key derivation (intentionally slow for brute-force resistance) |+| Open document | Read disk + parse JSON | Read disk + AES-GCM decrypt + parse + encrypted-db query | Extra decrypt + encrypted-db query |+| Save document | Render JSON + write disk | Render JSON + AES-GCM encrypt + write disk | Extra encrypt |+| Upload assets | Stream to disk | Fully read into memory + encrypt + write | Cannot stream-encrypt; large files cause memory pressure |+| Browse assets | Direct ServeFile | Read disk + decrypt + output | Decrypts on every request, no browser cache |+| database render | Global blocktree + plaintext JSON | Encrypted blocktree + DEK-decrypt JSON | Extra JSON decrypt; batch IAL load routed by notebook |+| database save | Plaintext JSON to disk | DEK-encrypt + write | Extra encrypt |+| In-notebook search | FTS query on global SQLite database | FTS query on independent encrypted SQLite database | SQLCipher page-level decrypt ~5-10% overhead |+| DB connections | 1 global | 1 global + 2 per unlocked encrypted notebook | Each encrypted-db connection pool ~20 connections |+| When locked | No extra overhead | Managed key handles revoked; caches and temporary files cleaned on a best-effort basis | Cold-start latency on next operation |++Performance summary:++- Daily editing experience: Nearly imperceptible. AES-GCM encryption/decryption is microsecond-level; document read/write is bottlenecked by disk IO++- Noticeable latency: Unlock ~1s, large-asset browsing (full decrypt per request with no cache), first access after lock (cold start)++- Zero impact on normal notebooks: Encryption and routing logic short-circuits for non-encrypted notebooks++### State machine and concurrency rules++The global state is `Disabled`, `Enabled`, or `RecoveryRequired`. In normal steady state, `Disabled` has no live encrypted notebook or kernel-enumerable key dependency. If startup discovers encrypted notebooks or recovery artifacts while global configuration is missing or disabled, it enters `RecoveryRequired`, never treats them as normal notebooks, and waits for a matching key backup to be restored. Under `Enabled`, each encrypted notebook independently has one of these states: `Locked`, `Unlocking`, `Unlocked`, `Locking`, or `Error`, and starts as `Locked` after application startup.++Encrypted identity detection is fail-closed. If a valid boxID has a missing or damaged `conf.json` or notebook key backup, the presence of a current ciphertext marker or an encryption identity already confirmed by the current process puts the notebook in `Error` and denies normal-notebook reads and writes; the kernel never auto-creates an `Encrypted=false` configuration. Only the notebook-deletion flow may remove the runtime identity, after draining lifecycle leases and clearing the local DEK, mount marker, dedicated databases, and caches.++| 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 | 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. Unlock-and-open completes under one per-notebook transition lock; a mount failure rolls back only an unlock created by that operation and never locks a DEK or mount already used by a concurrent request. 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.-**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 and agents) — can read plaintext content and use in-notebook search through supported notebook-specific entry points; global search, semantic search, and embedding vectorization do not participate. 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.+### Feature boundaries, plaintext temporaries, and interface rules++Text recognition (OCR) is not supported for assets in encrypted notebooks, regardless of lock state. Manual recognition returns a localized "unsupported" message, and automatic recognition skips encrypted-notebook assets. No OCR text may be generated for these assets or written to the global OCR store or search index.++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.++A rejection must state the concrete reason and the available remedy, and one generic message must not cover unrelated reasons: importing a `.sy.zip` that contains flashcards must name the affected documents or deck and point to removing the flashcards in the source notebook or importing into a regular notebook; a locked notebook must ask for unlocking; a cross-boundary move or reference must explain that an encrypted notebook is an isolated space instead of returning "operation not supported".++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.++#### Temporary Plaintext Lifecycle++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/`.++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.++Native mobile save flows must call `AcquireExportFile` to obtain a lease containing the path, name, size, and lease ID, then call `ReleaseExportFile` from a `finally` path after copying and verification finish. Encrypted exports must not use legacy path-only or name-only interfaces because those calls cannot cover the native copy phase with a lifecycle lease.++## Compatibility and recovery++### Existing-data compatibility policy++Existing encrypted data is the compatibility baseline. Format and key-management changes must preserve access to existing data and its recovery paths; development status must never justify requiring users to delete or recreate their data. This covers documents, assets and their original names, attribute-view definitions, key envelopes, backups, history, and sync snapshots.++Database bindings follow the same isolation boundary. When importing a `.sy.zip` into an encrypted notebook, bindings to blocks included in that import are remapped to the imported blocks; bindings to blocks outside the import become detached rows, preserving row IDs, stored text, and other field values. Imported document backlinks retain only databases included in the archive. Import must not write database backlinks into documents outside the target boundary. Ordinary imports retain bindings to existing ordinary documents. Adding or replacing bound rows and editing a bound primary key must validate the boundary before changing either the row or the document.++Existing invalid database backlinks are not silently deleted or resolved across encryption boundaries during export. Export reports the affected database ID and preserves the source data. To diagnose an affected document, compare its `custom-avs` entries with the databases in its permitted storage scope, retain a backup, and explicitly remove only confirmed invalid bindings. Missing files, corrupt data, and authentication failures remain errors; merely unlocking another encrypted notebook does not make its databases part of the document's export scope. This binding correction does not change ciphertext formats, AAD, keys, or legacy authenticated readers.++Table-cell rich text uses document `Spec: "4"` and an optional `TableCellRich` source envelope inside the authenticated plaintext AST. Existing document versions remain readable without converting their cells. Document encryption envelopes, AAD, subkey derivation, and recovery keys are unchanged. Reads, exports, history, snapshots, and recovery authenticate ciphertext first, then validate the document and rich text versions; unknown or damaged source is rejected while preserving the original data. Inline projections may be rebuilt only after authentication and source validation succeed.++### 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 callers authorized by the main application — APIs, third-party plugins, AI/LLM (including MCP and agents) — can read plaintext content and use in-notebook search through supported notebook-specific entry points; global search, semantic search, and embedding vectorization do not participate. 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):-**Protected (ciphertext on disk)**:- `.sy` document body (encrypted)+- assets binary files (encrypted)+- assets filenames (desensitized, original name encrypted)+- notebook icon, list sort weight, and sort mode (authenticated ciphertext in `BoxCrypt.Metadata`)+- database files (columns/rows/cell values/view config/content snapshots, encrypted)+- content SQLite database (blocks/FTS/attributes/refs, SQLCipher-encrypted)+- blocktree SQLite database (block-tree metadata: ID/path/title, SQLCipher-encrypted)+- .sy and database files in the history directory (ciphertext stored verbatim)-**Not protected**:+Not protected:+- MasterSalt/KEKVerifier in `conf.json` (designed to be plaintext: salt is not secret, verifier is ciphertext)+- BoxConf.WrappedDEK (ciphertext, requires KEK to unwrap)+- DEK-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/*`: 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.+- 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-## 13. AI / LLM Reachability+API protection:-The visibility of encrypted notebooks to AI/LLM through supported notebook-specific entry points is determined by the **lock state**; there is no separate functional-layer switch to hide content from AI. Global search, semantic search, and embedding vectorization never include encrypted content.+- `/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-**When locked**: AI/LLM (including MCP and agents) cannot obtain a usable DEK handle, and every encrypted-notebook entry point denies access. Dedicated databases are closed and disk content is ciphertext, so these callers cannot read encrypted content.+- 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-**When unlocked**: the DEK is in memory, so AI/LLM can read encrypted-notebook content and search within a notebook — MCP tools can list encrypted notebooks and their documents, read block content, run in-notebook FTS search, etc. However, global search, semantic search, and embedding vectorization still do not include encrypted content (encrypted data never enters the global `block_embeddings`/`blocks` tables; physically unreachable), see §3 comparison table.+- 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-Design stance: there is no "hide from AI" isolation at the functional layer, because such isolation is neither thorough nor easy to reason about. Supported entry points cannot access content after locking, but locking does not replace process- and OS-level protection. Users only need to understand one rule: **lock sensitive content after use**.+### Threat model and security scope-## 14. Feature Limitations+This feature protects data-at-rest confidentiality and inaccessibility through supported entry points after a notebook is locked. The design assumes an attacker may obtain current or historical ciphertext from the workspace, sync service, or backup media, but does not know the master password and cannot control the running application or operating system while the user has unlocked a notebook. AES-GCM provides confidentiality, integrity, and origin-context authentication for an individual encrypted object; it does not provide availability, version freshness, rollback protection, or deletion of retained ciphertext copies.-An encrypted notebook is an island; some features are unsupported because of their cross-notebook nature or dependence on global aggregation. These are explicit feature boundaries.+The following are outside this feature's security boundary and must be stated in product UI and user documentation:-- **Flashcards / spaced repetition**: Decks and scheduling are cross-notebook and depend on the global SQLite database; not supported.-- **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 are not supported.-- **Tags**: Global aggregation view (scans the global spans table); encrypted notebooks are not supported.-- **Asset file rename**: Encrypted-notebook asset filenames are already desensitized to `uuid-blockID.ext`; the disk filename participates in AAD, so renaming requires re-enveloping the whole asset.-- **Unused asset cleanup**: Encrypted-notebook assets are excluded from global unused-asset cleanup (island, assets do not cross boundaries), preventing false deletion when locked and document references cannot be scanned.-- **Unused database cleanup**: Encrypted-notebook database definitions are excluded from global unused-database cleanup, preventing false deletion when locked and reference relationships cannot be confirmed.+- 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-## 15. Performance Differences+- 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-| Operation | Normal Notebook | Encrypted Notebook | Reason |-|---|---|---|---|-| **Unlock (Mount)** | Instant | **~1 second delay** | Argon2id key derivation (intentionally slow for brute-force resistance) |-| **Open document** | Read disk + parse JSON | Read disk + AES-GCM decrypt + parse + encrypted-db query | Extra decrypt + encrypted-db query |-| **Save document** | Render JSON + write disk | Render JSON + AES-GCM encrypt + write disk | Extra encrypt |-| **Upload assets** | Stream to disk | Fully read into memory + encrypt + write | Cannot stream-encrypt; large files cause memory pressure |-| **Browse assets** | Direct ServeFile | Read disk + decrypt + output | Decrypts on every request, no browser cache |-| **database render** | Global blocktree + plaintext JSON | Encrypted blocktree + DEK-decrypt JSON | Extra JSON decrypt; batch IAL load routed by notebook |-| **database save** | Plaintext JSON to disk | DEK-encrypt + write | Extra encrypt |-| **In-notebook search** | FTS query on global SQLite database | FTS query on independent encrypted SQLite database | SQLCipher page-level decrypt ~5-10% overhead |-| **DB connections** | 1 global | 1 global + 2 per unlocked encrypted notebook | Each encrypted-db connection pool ~20 connections |-| **When locked** | No extra overhead | Managed key handles revoked; caches and temporary files cleaned on a best-effort basis | Cold-start latency on next operation |--**Performance summary**:-- **Daily editing experience**: Nearly imperceptible. AES-GCM encryption/decryption is microsecond-level; document read/write is bottlenecked by disk IO.-- **Noticeable latency**: Unlock ~1s, large-asset browsing (full decrypt per request with no cache), first access after lock (cold start).-- **Zero impact on normal notebooks**: Encryption and routing logic short-circuits for non-encrypted notebooks.--## 16. Threat Model and Security Scope+- 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-This feature protects data-at-rest confidentiality and inaccessibility through supported entry points after a notebook is locked. The design assumes an attacker may obtain current or historical ciphertext from the workspace, sync service, or backup media, but does not know the master password and cannot control the running application or operating system while the user has unlocked a notebook. AES-GCM provides confidentiality, integrity, and origin-context authentication for an individual encrypted object; it does not provide availability, version freshness, rollback protection, or deletion of retained ciphertext copies.+- 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-The following are outside this feature's security boundary and must be stated in product UI and user documentation:+- 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-- 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.-- 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.+- 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 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--The global state is `Disabled`, `Enabled`, or `RecoveryRequired`. In normal steady state, `Disabled` has no live encrypted notebook or kernel-enumerable key dependency. If startup discovers encrypted notebooks or recovery artifacts while global configuration is missing or disabled, it enters `RecoveryRequired`, never treats them as normal notebooks, and waits for a matching key backup to be restored. Under `Enabled`, each encrypted notebook independently has one of these states: `Locked`, `Unlocking`, `Unlocked`, `Locking`, or `Error`, and starts as `Locked` after application startup.+### Ciphertext, key, and database format-Encrypted identity detection is fail-closed. If a valid boxID has a missing or damaged `conf.json` or notebook key backup, the presence of a current ciphertext marker or an encryption identity already confirmed by the current process puts the notebook in `Error` and denies normal-notebook reads and writes; the kernel never auto-creates an `Encrypted=false` configuration. Only the notebook-deletion flow may remove the runtime identity, after draining lifecycle leases and clearing the local DEK, mount marker, dedicated databases, and caches.--| 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 | 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 |+Persistent formats are layered; global KDF configuration, key envelopes, and per-object data envelopes are not conflated:-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. Unlock-and-open completes under one per-notebook transition lock; a mount failure rolls back only an unlock created by that operation and never locks a DEK or mount already used by a concurrent request. 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.+1. Data-object envelope: Every `.sy`, asset, and database-definition object contains at least a format marker or version, an algorithm identifier, a 96-bit nonce generated by the operating system CSPRNG, ciphertext, and an authentication tag. The current format constructs AAD deterministically as `format domain + boxID + object type + stable object ID`, excluding parent directories and absolute paths. A `.sy` stable object ID is its canonical basename `<rootID>.sy`; an asset uses its desensitized disk basename, a database definition uses its avID, and a fixed singleton file uses a versioned constant ID. An asset's original name is authenticated encrypted metadata in the same asset container. After decryption, the internal object ID matches the AAD object ID, and duplicate object IDs within one notebook are rejected. Randomness failure aborts the write. Nonce uniqueness is probabilistic: the current implementation has no persistent per-purpose-key invocation counter shared across restarts, devices, and restored backups, and therefore does not enforce a lifetime invocation bound. This is a limitation, not a guarantee of unlimited safe use. Adding such enforcement requires a versioned multi-device key-lifecycle and recovery design that preserves access to existing data. An authentication tag cannot retrospectively identify nonce reuse, so the design never claims such reuse will automatically cause authentication failure-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.+2. Global key and envelope metadata: `NotebookCrypto` stores the KDF algorithm and parameters, MasterSalt, verifier format, KEK-envelope version, and backup-HMAC version; `BoxConf.WrappedDEK` stores each notebook's DEK envelope. They are not duplicated in every data object-## 18. Ciphertext, Key, and Database Format+3. Purpose separation: Each notebook's DEK derives subkeys with fixed domain separators for file content, assets, database definitions, content SQLCipher, and blocktree SQLCipher. Asset-name metadata and content chunks share the asset subkey and are separated by distinct AAD suffixes; a separate subkey for every object type is not required. The KEK may be used directly for the verifier, DEK wrapping, and backup HMAC, with those uses separated by different algorithms, versioned AAD, or authenticated data formats. WrappedDEK authentication is not incorrectly placed in a DEK domain-Persistent formats are layered; global KDF configuration, key envelopes, and per-object data envelopes are not conflated:+4. Database compatibility metadata: SQLCipher version, cipher parameters, index kind, and schema version are stored in the SQLCipher-authenticated encrypted_index_meta table and checked before the index is reused. Content and blocktree indexes are rebuildable; an index without compatibility metadata, with incompatible settings, or that fails to open is closed; after the notebook key and metadata and all source documents authenticate, both indexes may be recreated and populated by mounting. Failure to authenticate a source document preserves the source and residual indexes and returns an error. Rebuilding never weakens cipher parameters or falls back to plaintext SQLite-1. **Data-object envelope**: Every `.sy`, asset, and database-definition object contains at least a format marker or version, an algorithm identifier, a 96-bit nonce generated by the operating system CSPRNG, ciphertext, and an authentication tag. The current format constructs AAD deterministically as `format domain + boxID + object type + stable object ID`, excluding parent directories and absolute paths. A `.sy` stable object ID is its canonical basename `<rootID>.sy`; an asset uses its desensitized disk basename, a database definition uses its avID, and a fixed singleton file uses a versioned constant ID. An asset's original name is authenticated encrypted metadata in the same asset container. After decryption, the internal object ID matches the AAD object ID, and duplicate object IDs within one notebook are rejected. Randomness failure aborts the write. Nonce uniqueness is probabilistic: the current implementation has no persistent per-purpose-key invocation counter shared across restarts, devices, and restored backups, and therefore does not enforce a lifetime invocation bound. This is a limitation, not a guarantee of unlimited safe use. Adding such enforcement requires a versioned multi-device key-lifecycle and recovery design that preserves access to existing data. An authentication tag cannot retrospectively identify nonce reuse, so the design never claims such reuse will automatically cause authentication failure.-2. **Global key and envelope metadata**: `NotebookCrypto` stores the KDF algorithm and parameters, MasterSalt, verifier format, KEK-envelope version, and backup-HMAC version; `BoxConf.WrappedDEK` stores each notebook's DEK envelope. They are not duplicated in every data object.-3. **Purpose separation**: Each notebook's DEK derives subkeys with fixed domain separators for file content, assets, database definitions, content SQLCipher, and blocktree SQLCipher. Asset-name metadata and content chunks share the asset subkey and are separated by distinct AAD suffixes; a separate subkey for every object type is not required. The KEK may be used directly for the verifier, DEK wrapping, and backup HMAC, with those uses separated by different algorithms, versioned AAD, or authenticated data formats. WrappedDEK authentication is not incorrectly placed in a DEK domain.-4. **Database compatibility metadata**: SQLCipher version, cipher parameters, index kind, and schema version are stored in the SQLCipher-authenticated encrypted_index_meta table and checked before the index is reused. Content and blocktree indexes are rebuildable; an index without compatibility metadata, with incompatible settings, or that fails to open is closed; after the notebook key and metadata and all source documents authenticate, both indexes may be recreated and populated by mounting. Failure to authenticate a source document preserves the source and residual indexes and returns an error. Rebuilding never weakens cipher parameters or falls back to plaintext SQLite.-5. **Rename and format stability**: The current document format constructs AAD from the stable object ID and is already frozen as a compatibility baseline. Existing unversioned `SYAE` assets remain readable without requiring users to delete or recreate attachments when upgrading to version 2. Writes use version 2; reads do not force migration of files or historical snapshots. A parent-only move does not re-envelope content. A stable-basename change authenticates and decrypts with the old basename and creates a new envelope with the new basename. Future changes to envelopes, AAD semantics, or key derivation require an explicit format version and authenticated legacy reads, or a recoverable migration before the legacy reader is removed. Migration authenticates source data first and preserves the original data and matching recovery material so failure or interruption remains recoverable; resetting MasterSalt, discarding keys, or deleting data must never resolve format incompatibility. Unknown formats, corruption, and authentication failures preserve the original files and return an error without falling back to plaintext or bypassing authentication. Every format change requires fixtures from the supported previous format to verify affected read, export, history, backup, and recovery paths.+5. Rename and format stability: The current document format constructs AAD from the stable object ID and is already frozen as a compatibility baseline. Existing unversioned `SYAE` assets remain readable without requiring users to delete or recreate attachments when upgrading to version 2. Writes use version 2; reads do not force migration of files or historical snapshots. A parent-only move does not re-envelope content. A stable-basename change authenticates and decrypts with the old basename and creates a new envelope with the new basename. Future changes to envelopes, AAD semantics, or key derivation require an explicit format version and authenticated legacy reads, or a recoverable migration before the legacy reader is removed. Migration authenticates source data first and preserves the original data and matching recovery material so failure or interruption remains recoverable; resetting MasterSalt, discarding keys, or deleting data must never resolve format incompatibility. Unknown formats, corruption, and authentication failures preserve the original files and return an error without falling back to plaintext or bypassing authentication. Every format change requires fixtures from the supported previous format to verify affected read, export, history, backup, and recovery pathsThe SQLCipher main database, WAL, SHM, rollback journal, temporary files, and backup copies are protected objects. They remain in controlled directories and use their corresponding purpose key. Locking, crash recovery, and history snapshots enumerate these companion files; unencrypted SQLite pages, query results, or diagnostics must never be written to a global temporary directory.-## 19. Backup, Recovery, and Metadata Policy+### Backup, recovery, and metadata policy`data-crypto-backup.json` is recovery material, not a secret. It contains a format version, backup ID, creation time, content digest, and KEK-based HMAC. After the master password derives the KEK, a missing or mismatched HMAC rejects recovery rather than acting as a compatibility fallback. Recovery must not silently overwrite enabled configuration. A malformed backup or a backup incompatible with existing encrypted notebooks enters an error state instead of generating a new MasterSalt.@@ -408,25 +578,32 @@ Sync endpoints and offline backups are storage that may be lost, copied, or roll| Notebook name | Yes. The notebook list and encrypted-notebook status API retain the name while locked so users can identify the notebook they intend to unlock; the name is therefore outside the confidentiality boundary || Icon, sorting, document title/count, relation count, tags, bookmarks, history and snapshot names | Must not be exposed while locked by default; if compatibility requires exposure, list each field here and explain it in the UI |-## 20. Feature Boundaries, Plaintext Temporaries, and Interface Rules--Text recognition (OCR) is not supported for assets in encrypted notebooks, regardless of lock state. Manual recognition returns a localized "unsupported" message, and automatic recognition skips encrypted-notebook assets. No OCR text may be generated for these assets or written to the global OCR store or search index.--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.+### Security design of history features-A rejection must state the concrete reason and the available remedy, and one generic message must not cover unrelated reasons: importing a `.sy.zip` that contains flashcards must name the affected documents or deck and point to removing the flashcards in the source notebook or importing into a regular notebook; a locked notebook must ask for unlocking; a cross-boundary move or reference must explain that an encrypted notebook is an isolated space instead of returning "operation not supported".+```+File history:+ edit triggers history generation → ciphertext .sy copied verbatim to history dir+ auto-generated before close/exit → ensures history is captured even after locking+ history index → content left empty (ciphertext not indexed for search)+ view history → read the snapshot boxID, object type, and stable file basename, then reconstruct the original AAD for decryption (notebook must be unlocked)+ roll back → decrypt with the snapshot AAD → verify that the root-block ID matches the basename → load tree → let WriteTree serialize the restored content and re-envelope it with the target basename-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.+Deleted-notebook history:+ before deletion → entire directory backed up as ciphertext to history dir+ restore → copy the ciphertext directory back verbatim without opening it; authenticate WrappedDEK with the matching global key backup and master password when unlocking+ key retention → while kernel-managed history remains recoverable, deletion of the global key backup it depends on is forbidden; permanently purging the history removes the dependency-### Temporary Plaintext Lifecycle+database history:+ generate → encrypted-notebook database files copied from notebook-level dir to history dir+ view → decrypt with the boxID and object purpose/identifier recorded by the snapshot, never with the absolute history-directory path as AAD+ roll back → encrypted-notebook database file/resources rolled back to notebook-level dir+```-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/`.+Parent directories below the history root are not part of AAD. Every history entry retains, in an unambiguous canonical form, the `boxID`, object type, and stable file basename or object identifier at snapshot creation; these values may be encoded by a fixed history layout or stored as metadata committed with the snapshot. Changing only a live document's parent directory leaves its AAD context unchanged; if its basename changes, existing history continues to authenticate with the old basename. Rollback first verifies the ciphertext and that the basename matches the decrypted object ID, then restores under the target parent directory. Document rollback also normalizes the tree and resolves duplicate block IDs, so WriteTree serializes the restored content and creates a fresh envelope even when the basename is unchanged. The historical ciphertext remains intact. Copying a deleted notebook back is a closed-state restoration, not proof that the current key backup matches; authentication happens on unlock, and a missing matching backup may be supplied later. Missing, malformed, or mismatched snapshot context rejects viewing and rollback; the implementation must not parse ciphertext as plaintext or replace the snapshot basename with the current basename.-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.+## Verification-Native mobile save flows must call `AcquireExportFile` to obtain a lease containing the path, name, size, and lease ID, then call `ReleaseExportFile` from a `finally` path after copying and verification finish. Encrypted exports must not use legacy path-only or name-only interfaces because those calls cannot cover the native copy phase with a lifecycle lease.--## 21. Security Acceptance Matrix+### Security acceptance matrix| Scenario | Expected result ||---|---|@@ -437,6 +614,10 @@ Native mobile save flows must call `AcquireExportFile` to obtain a lease contain| 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 || Encrypted asset-container write fails | The caller receives an error, no separate name mapping or plaintext temporary file is created, and an incomplete target file cannot be read as a valid asset |+| Open an unversioned legacy asset after upgrading, or read a historical snapshot containing it | Original names and content remain readable; preview, download, and export work without rewriting source ciphertext; re-saving writes version 2 |+| Swap chunks or name metadata between different writes of a same-named version 2 asset, or mix metadata and chunks from old and new formats | Content authentication fails without falling back to another version; unknown versions, explicit null versions, and incomplete new metadata are rejected by both name and content reads |+| An archive source parent, archive entry path, or symbolic link points into an encrypted notebook | Check every source entry before packing and every target entry before extraction; an invalid archive must not write other entries first; ordinary archives remain usable |+| A block read omits the notebook parameter, or a batch spans encrypted notebooks | Acquire response leases for every notebook based on actual block ownership and hold them until the response is written; reject unknown ownership rather than returning content without a lease after a later unlock || 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 serializes the restored tree and re-envelopes it with the target basename while preserving the historical ciphertext, while missing snapshot context rejects the operation || 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 |@@ -445,78 +626,5 @@ Native mobile save flows must call `AcquireExportFile` to obtain a lease contain| Both an encrypted notebook's `conf.json` and notebook key backup are missing, or sync removes an encrypted notebook that is currently open locally | Ciphertext or runtime identity puts the former in `Error` without creating a normal configuration; the latter drains in-flight leases and clears the DEK, mount, dedicated databases, caches, and indexes even though `Conf.GetBox` is empty after deletion || Nonce randomness failure or discovering nonce reuse afterwards | Reject before encryption on randomness failure; no persistent lifetime invocation bound is currently enforced. AES-GCM authentication cannot detect nonce reuse that already occurred; discovery requires migration to a new DEK, not merely changing the master password || Replay an authenticated historical ciphertext object or key backup | It may validate as an authentic old version but is never claimed to be freshest or from a trusted source; rollback risk is explicit, and the current design does not claim rollback prevention |-| Master-password change and KEK rewrapping | WrappedDEKs and backup update atomically; an interrupted update leaves the old configuration recoverably usable; the old-password exposure warning is accurate; data and history are verifiably readable before and after migration |+| Master-password change and KEK rewrapping | WrappedDEKs, historical KEKs, and backups update through a recoverable transaction; the current password can recover old envelopes after repeated password changes, notebook deletion, backup import, and interrupted migration; old-password exposure warnings remain accurate || Concurrent multi-notebook operations and auto-lock | Lock order has no deadlock; authenticated UI activity or an explicit keepalive refreshes all currently unlocked notebooks, while background work does not refresh them automatically; a locking notebook admits no new lease |--## 22. Usage Guide--### First-time enablement-1. Go to **Settings - Authentication - Encrypted Notebook** and toggle it on-2. Set a master password (double input + risk confirmation). The master password is the unified key for all encrypted notebooks — **you must remember it; there is no recovery backdoor**-3. Once enabled, you can **create a new encrypted notebook** from the file-panel "more" menu; enter a name and master password to unlock and open it automatically--> Strength recommendation: 12+ characters, mixed case + digits + symbols. The stronger the master password, the higher the brute-force resistance (password strength is the only line of defense; there is no backdoor).--### Daily use: unlock and lock-- **Unlock**: Click a closed encrypted notebook, enter the master password, and wait about one second for Argon2id derivation before it opens. Unlocking only affects that notebook; other encrypted notebooks stay locked-- **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, 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 - Authentication - Encrypted Notebook - Change master password**. Changing the password only re-wraps each notebook's WrappedDEK — **document data is not re-encrypted**, so it completes instantly. The key backup is auto-refreshed and synced after a password change.--> Important semantics: password change uses the KEK envelope model — the DEK itself does not change; only a new KEK (derived from the new password) re-wraps the WrappedDEK. This means **changing the password does not revoke the old password's decryption ability**: if the old password and an old WrappedDEK (retained in sync endpoints, backups, or historical snapshots) leak together, the same DEK can still be unwrapped, decrypting current data. If you suspect the old password has leaked, export the content as plaintext, import it into a freshly created encrypted notebook (new DEK), and securely delete the plaintext files after confirming the migration rather than only changing the password.--### Multi-device sync-Encrypted-notebook ciphertext `.sy`/assets/database files sync along with the data (ciphertext in, ciphertext out, self-consistent); the global key material (MasterSalt etc.) is also automatically backed up to the sync directory. **No manual "enable" is needed on a new device after sync**:--An encrypted notebook's open state is never inherited across devices. Even if the synchronized `conf.json` records that another device had the notebook open, the UI and kernel must treat it as closed and skip indexing whenever the local process has no DEK for that notebook; entering the master password unlocks and mounts it locally.--When sync removes an encrypted notebook currently mounted on this device, the kernel completes the local deletion transition before any full-reindex branch, exit early-return, or UI reload: it closes admission, drains active leases, clears the DEK and mount state, deletes dedicated index databases, and completes global-index cleanup. The now-missing disk configuration is never used to decide whether cleanup is required.--1. Configure the same sync account on the new device and complete a sync-2. Sync pulls the key backup to the local machine; the kernel auto-restores the "enabled" state-3. Just click the encrypted notebook and enter the master password to unlock and use it--If the notebook still shows as locked on the new device after sync, that is normal — click it and enter the master password.--Sync recovery can validate backup integrity but cannot prove that a backup is the newest version. Keep an independently versioned key backup. When historical copies conflict, the system cannot determine freshness automatically; before recovery, the user confirms a version from trusted source and time information.--### Import and export-- **Import**: Supports importing `.sy.zip` and Markdown; content is automatically DEK-encrypted before writing to disk, identical to manually created documents-- **Export**: Identical to normal notebooks (must unlock first; exports plaintext). `.sy.zip`, HTML, Word, PDF, Markdown, etc. are all supported; export is rejected while locked-- **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.**--### Recovering from a lost key backup-If both `conf/conf.json` and the key backup in the sync directory are lost (an extreme case), re-enabling the encrypted-notebook feature will be rejected with a prompt to restore the backup file. As long as you can recover `data-crypto-backup.json` from another synced device or a previously exported key file, you can import it via the "Import key" button shown in `Disabled` or `RecoveryRequired`, or manually put it back at `<workspace>/data/.siyuan/` and re-enable, then unlock with the master password matching that key.--Restoring deleted encrypted-notebook history also requires the global key backup matching its WrappedDEK and the master password. While you still need that local recovery path, do not permanently purge either the history or its matching key backup; disabling must refuse to proceed when it discovers such a dependency.--### Suitable scenarios for encrypted notebooks-- Private diary, financial records, medical information-- Work secrets, business plans, contracts-- Concern about device loss or theft — once encrypted, even if the disk data is recovered, it remains ciphertext without the master password--### 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)-- Content needing flashcard review (not supported)-- Content needing bookmark/tag management (not supported)-- Content you do not want AI/LLM to touch (AI can read it when unlocked; keep it locked if that matters)-- Large numbers of large files (assets fully decrypt on every browse)--### Daily usage habits-1. **You must remember the master password**: Forgetting it = data permanently unrecoverable (no backdoor)-2. **Lock after use**: Reduce the DEK's exposure time in memory-3. **Don't put all your notes in encrypted notebooks**: Only put what is truly sensitive-4. **Master password strength**: Recommend 12+ characters, mixed case + digits + symbols-5. **Backup**: Keep versioned ciphertext backups and their matching key backups separately; losing the master password or every matching key backup makes the ciphertext unrecoverablediff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex 6c567de1ad..3d3c881867 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -1,20 +1,16 @@-# SiYuan 加密笔记本特性+# 加密笔记本-## 1. 设计目标+[English](ENCRYPTED-NOTEBOOK.md)-在 SiYuan 中实现"加密笔记本"——一种特殊笔记本,其 `.sy` 文档、assets 资源文件(含文件名)、数据库文件、SQLite 索引数据库(content + blocktree)都在磁盘上加密存储,需要主密码解锁才能查看内容。已有的普通笔记本完全不受影响。+## 功能范围-**维护状态**:加密笔记本开发已完成,按已上线功能维护。+### 设计目标-当前已写入的加密数据作为兼容基线。格式和密钥管理变更必须保留已有数据的可读性与恢复能力,不得再以开发阶段为由要求用户删除或重建数据。兼容范围包括文档、资源及其原始名称、数据库定义、密钥包络、备份、历史和同步快照。--数据库绑定遵循相同的隔离边界。向加密笔记本导入 `.sy.zip` 时,指向本次导入块的绑定重映射到新块;指向包外块的绑定转为非绑定条目,保留条目 ID、已存文本和其他字段值。导入文档的反向绑定仅保留包内数据库。导入不得向目标边界外的文档回写数据库绑定。普通导入保留指向现有普通文档的绑定。新增绑定条目、换绑及编辑绑定主键时,必须在修改条目或文档前校验边界。+加密笔记本将 `.sy` 文档、资源文件及其原始名称、数据库定义和 SQLite 索引数据库加密存储。用户输入主密码后,按笔记本独立解锁并访问内容。普通笔记本无需迁移。-导出时不得静默删除已有的无效数据库反向绑定,也不得跨加密边界解析。导出错误应指出受影响的数据库 ID,并保留源数据。排查受影响文档时,应将其 `custom-avs` 与允许存储范围内的数据库逐项核对,保留备份后仅显式移除已确认无效的绑定。文件缺失、数据损坏和认证失败仍须报错;解锁其他加密笔记本不会将其数据库纳入该文档的导出范围。本次绑定修正不改变密文格式、AAD、密钥或旧格式认证读取路径。--表格单元格富文本使用文档 `Spec: "4"`,在经过认证的明文语法树中增加可选的 `TableCellRich` 源数据包络。已有文档版本继续可读,单元格不会自动转换。文档加密包络、AAD、子密钥派生和恢复密钥均保持不变。读取、导出、历史、快照和恢复均先认证密文,再校验文档及富文本版本;未知格式或损坏的源数据必须报错并保留原始数据。只有认证和源数据校验成功后,才可重建行级投影。+加密笔记本作为已发布功能维护。-## 2. 核心约束+### 核心约束| 维度 | 设计决策 ||---|---|@@ -24,13 +20,13 @@| 密码 | 共用主密码(KEK 包络,每个笔记本独立 DEK) || 解锁粒度 | 严格每笔记本单独解锁(KEK 用完即弃,每次跑 Argon2id ~1 秒) || SQLite 数据库方案 | 每个加密笔记本物理独立 SQLCipher SQLite 数据库,与全局 siyuan.db 隔离 |-| **隔离原则** | **每个加密笔记本是一个独立孤岛——与普通笔记本隔离,加密笔记本之间也互相隔离。数据、块引、数据库镜像、移动都不跨加密笔记本边界。解锁一个加密笔记本不影响其他加密笔记本的锁定状态。** |+| 隔离原则 | 每个加密笔记本是一个独立孤岛——与普通笔记本隔离,加密笔记本之间也互相隔离。数据、块引、数据库镜像、移动都不跨加密笔记本边界。解锁一个加密笔记本不影响其他加密笔记本的锁定状态。 || 全局功能 | 加密笔记本完全不参与(全局搜索/关系图/块引都看不到它) || 块引 |笔记本内部正常引用;禁止跨加密边界引用(双向:普通↔加密、加密 A↔加密 B) |-| AI / LLM | 不做功能层隔离——解锁后可直接读取内容并使用笔记本内搜索;锁定后无可用 DEK 句柄且专用入口拒绝访问。全局搜索、语义搜索和嵌入向量化均不参与(详见 §13) |+| AI / LLM | 不做功能层隔离——解锁后可直接读取内容并使用笔记本内搜索;锁定后无可用 DEK 句柄且专用入口拒绝访问。全局搜索、语义搜索和嵌入向量化均不参与(详见 「AI / LLM 可达性」) || 发布 | 不支持——发布服务的读者与匿名访问者无论笔记本是否解锁、是否配置发布密码或可见性,均不可列举或读取加密笔记本 || 跨边界移动 | 禁止——会破坏数据一致性且泄漏 |-| 数据库 | 笔记本级存储——加密笔记本的 数据库文件跟随笔记本目录,DEK 加密;禁止跨边界镜像 |+| 数据库 | 笔记本级存储——加密笔记本的数据库文件跟随笔记本目录,DEK 加密;禁止跨边界镜像 || 闪卡 / 间隔重复 | 不支持(功能限制) || 书签 | 不支持(功能限制) || 标签 | 不支持(功能限制) |@@ -40,51 +36,199 @@| 已有普通笔记本 | 完全不动,零迁移 || 已有加密数据 | 升级后继续可读、可恢复;格式变更保留旧版认证读取或提供可恢复迁移,不要求删除或重建用户数据 |-## 3. 加密笔记本 vs 普通笔记本+### 与普通笔记本的对比| 维度 | 普通笔记本 | 加密笔记本 ||---|---|---|-| **创建** | 随时创建,无限制 | 需先启用加密功能(设主密码),创建时需验证主密码 |-| **打开(Mount)** | 直接打开 | 需先输主密码解锁(每次 ~1 秒 Argon2id),应用取得受管 DEK 句柄 |-| **关闭(Unmount)** | 关闭即不可见 | 关闭 = 锁定(停止新访问 + 等待或取消在途任务 + 从受管密钥缓存移除 DEK + 删除加密 SQLite 数据库 + 尽力清理内核管理的明文缓存和临时文件) |-| **重启后** | 保持上次打开状态 | 强制关闭,需重新输主密码解锁 |-| **.sy 文件** | 明文 JSON 落盘 | AES-256-GCM 密文落盘,读时透明解密 |-| **assets 文件** | 明文二进制,原始文件名 | AES-256-GCM 密文,文件名脱敏,原始名加密存储 |-| **数据库文件** | 全局 `storage/av/<avID>.json`(明文) | 笔记本级 `<boxID>/storage/av/<avID>.json`(DEK 加密) |-| **content SQLite 数据库** | 写入全局 siyuan.db(明文) | 写入独立 siyuan-encrypted-`<boxID>`.db(SQLCipher 加密) |-| **blocktree SQLite 数据库** | 写入全局 blocktree.db(明文) | 写入独立 siyuan-encrypted-`<boxID>`-blocktree.db(SQLCipher 加密) |-| **全局搜索** | 参与(FTS 命中) | 不参与(数据不在全局 SQLite 数据库) |-| **关系图** | 参与 | 不参与 |-| **块引** | 可被任意笔记本引用 |笔记本内部正常引用;禁止跨加密边界引用(双向) |-| **移动文档(跨笔记本)** | 支持 | 禁止跨加密边界 |-| **文档转标题(Doc2Heading)** | 支持 | 禁止跨加密边界 |-| **数据库镜像(跨笔记本)** | 支持 | 禁止跨加密边界 |-| **资源文件重命名** | 支持 | 不支持(脱敏文件名重命名会破坏映射) |-| **资源文件文字识别(OCR)** | 支持 | 不支持,与解锁状态无关 |-| **导入** | 支持 | 支持(.sy.zip 和 Markdown,落盘前自动 DEK 加密) |-| **笔记本内搜索** | 走全局 SQLite 数据库 | 走加密 SQLite 数据库 |-| **反链面板** | 走全局 SQLite 数据库 | 走加密 SQLite 数据库(含 mention 子查询) |-| **打开文档 / 大纲 / 面包屑 / 块信息 / 悬浮预览** | 走全局 SQLite 数据库 | 走加密 SQLite 数据库 |-| **数据库** | 走全局存储 + 全局 SQLite 数据库 | 走笔记本级存储(DEK 加密)+ 加密 SQLite 数据库 |-| **文件历史** | 支持 | 支持(密文 .sy 原样存历史目录;历史条目保留快照写入时的 boxID、对象类型和稳定文件基名,查看/回滚以三者作为 AAD 上下文解密) |-| **已删除笔记本历史** | 支持 | 支持(删除前整个目录密文备份,恢复时原样拷回;恢复还需要匹配的全局密钥备份和主密码) |-| **嵌入向量化 / 语义搜索** | 参与 | 不参与(加密数据不进全局 block_embeddings 表,嵌入流水线只读全局库;与解锁状态无关) |-| **智能体 / AI 对话 / MCP** | 可读内容、可搜索 | 解锁后可用(可读块内容、列文档、笔记本内搜索);锁定后不可达(详见 §13)。全局搜索/语义搜索不参与 |-| **发布** | 支持通过 `publishAccess.json` 配置可见性、密码和禁止访问 | 不支持;发布服务的读者与匿名访问者始终不可列举或读取,`publishAccess.json` 不能覆盖该规则 |-| **内核 CLI** | 可操作工作区数据 | 无论锁定或解锁,均不支持加密笔记本及其文件 |-| **闪卡 / 间隔重复** | 参与 | 不支持(功能限制) |-| **书签** | 参与(全局聚合) | 不支持(功能限制) |-| **标签** | 参与(全局聚合) | 不支持(功能限制) |-| **列表图标** | 用户自定义 emoji | 关闭时显示锁图标,打开后恢复 emoji |-| **导出(.sy.zip)** | 支持 | 支持(解锁状态下导出明文,未解锁时拒绝;详见 §12 安全前提) |-| **数据同步** | dejavu 同步明文 | 不改(密文进密文出,闭环自洽) |-| **删除笔记本** | 删目录 | 删目录 + 删加密 SQLite 数据库 文件 + 删笔记本级数据库存储 |-| **重建索引** | 全量 | 启动时跳过(已关闭);打开时全量重建到加密 SQLite 数据库 |-| **/api/file/\*** | 可读写、复制、重命名、删除或列举工作空间文件 | 拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),防止密文泄漏或绕过加密层写入;`temp/` 仍可由管理员文件 API 和受信任插件访问 |--**核心区别总结**:加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、不支持发布、文档和 数据库文件不进出边界。笔记本内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 可直接读取内容并使用笔记本内搜索。加密笔记本之间也互相隔离。普通笔记本完全不受影响。--## 4. 密钥架构+| 创建 | 随时创建,无限制 | 需先启用加密功能(设主密码),创建时需验证主密码 |+| 打开(Mount) | 直接打开 | 需先输主密码解锁(每次 ~1 秒 Argon2id),应用取得受管 DEK 句柄 |+| 关闭(Unmount) | 关闭即不可见 | 关闭 = 锁定(停止新访问 + 等待或取消在途任务 + 从受管密钥缓存移除 DEK + 删除加密 SQLite 数据库 + 尽力清理内核管理的明文缓存和临时文件) |+| 重启后 | 保持上次打开状态 | 强制关闭,需重新输主密码解锁 |+| .sy 文件 | 明文 JSON 落盘 | AES-256-GCM 密文落盘,读时透明解密 |+| assets 文件 | 明文二进制,原始文件名 | AES-256-GCM 密文,文件名脱敏,原始名加密存储 |+| 数据库文件 | 全局 `storage/av/<avID>.json`(明文) | 笔记本级 `<boxID>/storage/av/<avID>.json`(DEK 加密) |+| content SQLite 数据库 | 写入全局 siyuan.db(明文) | 写入独立 siyuan-encrypted-`<boxID>`.db(SQLCipher 加密) |+| blocktree SQLite 数据库 | 写入全局 blocktree.db(明文) | 写入独立 siyuan-encrypted-`<boxID>`-blocktree.db(SQLCipher 加密) |+| 全局搜索 | 参与(FTS 命中) | 不参与(数据不在全局 SQLite 数据库) |+| 关系图 | 参与 | 不参与 |+| 块引 | 可被任意笔记本引用 |笔记本内部正常引用;禁止跨加密边界引用(双向) |+| 移动文档(跨笔记本) | 支持 | 禁止跨加密边界 |+| 文档转标题(Doc2Heading) | 支持 | 禁止跨加密边界 |+| 数据库镜像(跨笔记本) | 支持 | 禁止跨加密边界 |+| 资源文件重命名 | 支持 | 不支持(脱敏文件名重命名会破坏映射) |+| 资源文件文字识别(OCR) | 支持 | 不支持,与解锁状态无关 |+| 导入 | 支持 | 支持(.sy.zip 和 Markdown,落盘前自动 DEK 加密) |+| 笔记本内搜索 | 走全局 SQLite 数据库 | 走加密 SQLite 数据库 |+| 反链面板 | 走全局 SQLite 数据库 | 走加密 SQLite 数据库(含 mention 子查询) |+| 打开文档 / 大纲 / 面包屑 / 块信息 / 悬浮预览 | 走全局 SQLite 数据库 | 走加密 SQLite 数据库 |+| 数据库 | 走全局存储 + 全局 SQLite 数据库 | 走笔记本级存储(DEK 加密)+ 加密 SQLite 数据库 |+| 文件历史 | 支持 | 支持(密文 .sy 原样存历史目录;历史条目保留快照写入时的 boxID、对象类型和稳定文件基名,查看/回滚以三者作为 AAD 上下文解密) |+| 已删除笔记本历史 | 支持 | 支持(删除前整个目录密文备份,恢复时原样拷回;恢复还需要匹配的全局密钥备份和主密码) |+| 嵌入向量化 / 语义搜索 | 参与 | 不参与(加密数据不进全局 block_embeddings 表,嵌入流水线只读全局库;与解锁状态无关) |+| 智能体 / AI 对话 / MCP | 可读内容、可搜索 | 解锁后可用(可读块内容、列文档、笔记本内搜索);锁定后不可达(详见 「AI / LLM 可达性」)。全局搜索/语义搜索不参与 |+| 发布 | 支持通过 `publishAccess.json` 配置可见性、密码和禁止访问 | 不支持;发布服务的读者与匿名访问者始终不可列举或读取,`publishAccess.json` 不能覆盖该规则 |+| 内核 CLI | 可操作工作区数据 | 无论锁定或解锁,均不支持加密笔记本及其文件 |+| 闪卡 / 间隔重复 | 参与 | 不支持(功能限制) |+| 书签 | 参与(全局聚合) | 不支持(功能限制) |+| 标签 | 参与(全局聚合) | 不支持(功能限制) |+| 列表图标 | 用户自定义 emoji | 关闭时显示锁图标,打开后恢复 emoji |+| 导出(.sy.zip) | 支持 | 支持(解锁状态下导出明文,未解锁时拒绝;详见 「安全边界」 安全前提) |+| 数据同步 | dejavu 同步明文 | 不改(密文进密文出,保持密文形式) |+| 删除笔记本 | 删目录 | 删目录 + 删加密 SQLite 数据库 文件 + 删笔记本级数据库存储 |+| 重建索引 | 全量 | 启动时跳过(已关闭);打开时全量重建到加密 SQLite 数据库 |+| /api/file/\* | 可读写、复制、重命名、删除或列举工作空间文件 | 拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),防止密文泄漏或绕过加密层写入;`temp/` 仍可由管理员文件 API 和受信任插件访问 |++加密笔记本是"孤岛"——数据物理隔离、操作专用入口、完全不参与全局功能(全局搜索/关系图)、不支持发布、文档和数据库文件不进出边界。笔记本内部功能(编辑、块引、反链、搜索、数据库、大纲、历史等)正常使用;解锁后 AI/LLM 可直接读取内容并使用笔记本内搜索。加密笔记本之间也互相隔离。普通笔记本完全不受影响。++### 功能限制++加密笔记本是孤岛,部分功能因其跨 notebook 特性或依赖全局聚合而不支持,属于明确的功能边界。++- 闪卡 / 间隔重复:牌组与调度跨 notebook 且依赖全局 SQLite 数据库,不支持++- 发布:发布服务面向只读或匿名访问者,加密笔记本无论锁定或解锁均不参与发布,且不能通过发布密码或可见性配置启用++- 书签:全局聚合视图(扫全局 siyuan.db),加密笔记本不支持++- 标签:全局聚合视图(扫全局 spans 表),加密笔记本不支持++- 资源文件重命名:加密笔记本的 asset 文件名已脱敏为 `uuid-blockID.ext`,磁盘文件名参与 AAD,重命名需要重新封装整个资源++- 未引用资源清理:加密笔记本的资源不参与全局未引用清理(孤岛,资源不跨边界),避免锁定时因无法扫描文档引用而误删++- 未引用数据库清理:加密笔记本的数据库定义不参与全局未引用清理,避免锁定时因无法确认引用关系而误删++## 用户交互++### 交互设计++| 场景 | 交互 |+|---|---|+| 启用 | 设置 - 鉴权 - 加密笔记本,打开开关并设置主密码(双输入 + 风险确认) |+| 禁用 | 仅在无现存加密笔记本且无依赖当前密钥备份的内核可枚举历史或恢复快照时支持关闭;否则拒绝,或要求用户明确永久清除这些恢复数据后再删除全局配置与备份 |+| 创建 | 文件面板 - 「更多」菜单 - 「新建加密笔记本」,输入名字和主密码后自动解锁并打开 |+| 图标 | 关闭(锁定)时显示锁图标;打开(解锁)后恢复用户 emoji |+| 解锁 | 点击已关闭的加密笔记本,在主密码框(🔓 解锁 xxx)中输入密码,等待约 1 秒后打开 |+| 锁定 | 等于关闭:先阻止新操作,等待或取消在途任务,再移除受管 DEK 句柄、删除加密 SQLite 数据库,并尽力清理内核管理的明文缓存、临时文件和访问令牌。关闭前会自动保存未写入的编辑和文件历史 |+| 自动锁定 | 每个已解锁笔记本独立保存最近活动时间;认证用户在当前工作区产生真实界面交互时,统一刷新所有当前已解锁加密笔记本的活动时间。无界面客户端也可通过需要认证与管理员权限的显式保活接口执行同样的刷新;后台读取、同步、索引等非用户活动不自动保活 |+| 改密 | 设置 - 鉴权 - 加密笔记本 - 「修改主密码」 |+| 移动文档 | 加密笔记本内部仅改变父目录时原样移动密文并更新索引;文件基名变化时重新封装;普通笔记本之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 |+| 文档转标题 | 跨加密边界被拒绝并提示 |+| 块引 | 加密笔记本内部正常引用(搜索 `((` 只搜本笔记本,反链面板正常显示);跨加密边界(普通↔加密、加密 A↔加密 B)被阻止 |+| 数据库镜像 | 加密笔记本内部正常镜像;跨加密边界被禁止 |+| 资源文件重命名 | 不支持(脱敏文件名重命名会破坏映射) |+| 导入 | 支持:导入的 .sy.zip 或 Markdown 文件落盘前自动 DEK 加密 |+| 文件历史 | 支持(查看时需先解锁对应加密笔记本;历史索引不存明文内容) |+| 已删除笔记本 | 支持(密文备份,恢复需匹配的全局密钥备份与主密码;保留该历史时不得直接删除所依赖的密钥备份) |+| 发布 | 不支持;发布权限编辑界面不提供加密笔记本及其文档的配置入口,发布服务无论认证状态如何均不可见 |+| 导出 | 支持(与普通笔记本一致;需先解锁,导出的是明文。锁定状态下拒绝导出) |+| 同步 | 不改(密文进密文出,保持密文形式) |++### 使用指南++#### 首次启用++1. 进入 设置 - 鉴权 - 加密笔记本,打开开关++2. 设置主密码(双输入确认 + 风险确认)。主密码是所有加密笔记本的统一钥匙,必须牢记——没有找回后门++3. 启用后即可在文件面板「更多」菜单里 新建加密笔记本,输入名字和主密码后自动解锁并打开++> 强度建议:12 位以上,混合大小写 + 数字 + 符号。主密码越强,抗暴力破解能力越高(不提供密码找回后门)。++#### 日常使用:解锁与锁定++- 解锁:点击已关闭的加密笔记本,输入主密码并等待约 1 秒(Argon2id 派生)后打开。解锁仅作用于该笔记本,其他加密笔记本保持锁定++- 锁定:关闭该笔记本即等于锁定。内核停止新访问,等待或取消在途任务,撤销受管 DEK 句柄和数据库连接,并尽力清理内核管理的明文缓存、临时文件与令牌。用完即锁是最重要的安全习惯,能最大程度减少密钥和明文的暴露时间++- 重启后:所有加密笔记本强制关闭,需重新输主密码解锁(受管 DEK 句柄只存在于进程内存,重启后需重新派生)++> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,获得主应用授权的调用方(API、插件、AI/LLM 含 MCP)能像读普通笔记本一样读到明文;发布服务的读者与匿名访问者以及内核 CLI 始终被拒绝(详见 「安全边界」 安全前提)。++#### 修改主密码+进入 设置 - 鉴权 - 加密笔记本 - 修改主密码。改密会重新包络各笔记本的 WrappedDEK,并用新密码保护历史恢复密钥,不重新加密文档数据。改密后密钥备份会自动刷新并同步;使用当前备份和当前密码仍可恢复改密前的已删除笔记本历史。++> 重要语义:改密采用 KEK 包络模式——DEK 本身不变,只是用新主密码派生的新 KEK 重新包络 WrappedDEK。这意味着改密不能吊销旧主密码的解密能力:如果旧主密码和旧 WrappedDEK(如同步端、备份、历史快照中保留的)同时泄露,仍能解出同一个 DEK,进而解当前数据。如果怀疑旧主密码已泄露,应将内容导出为明文后导入新建的加密笔记本(新 DEK),确认迁移成功后安全删除明文文件,而非仅改密。++#### 多设备同步+加密笔记本的密文 `.sy`/assets/数据库文件会随数据同步(密文进密文出,保持密文形式);全局密钥材料(MasterSalt 等)也会自动备份到同步目录。新设备同步后无需手动"启用":++加密笔记本的打开状态不能跨设备继承。即使同步到本机的 `conf.json` 记录了其他设备上的打开状态,只要本机内存中没有该笔记本的 DEK,界面和内核都必须将其视为已关闭,并跳过索引;输入主密码后由本机完成解锁和挂载。++同步删除本机当前已挂载的加密笔记本时,内核必须在处理全量重建索引、退出早返回或界面刷新之前完成本机删除转换:关闭新操作准入、等待在途租约结束、清除 DEK 与挂载状态、删除专属索引数据库并完成全局索引清理。删除后的磁盘配置不再作为判断是否需要清理的依据。++1. 在新设备配置好相同的同步账号并完成同步++2. 同步会把密钥备份拉到本地,内核自动恢复"已启用"状态++3. 直接点击加密笔记本,输入主密码即可解锁使用++若新设备同步后笔记本仍显示锁定属正常——点开输主密码即可。++同步恢复可以校验备份完整性,但不能证明它是最新版本。请另外保留版本化的密钥备份;出现多个历史副本时,系统无法自动判定新鲜度,恢复前应由用户根据可信来源和时间信息确认版本。++#### 导入与导出++- 导入:支持导入 `.sy.zip` 和 Markdown,内容在落盘前自动用 DEK 加密,与手动创建的文档一致++- 导出:与普通笔记本一致(需先解锁,导出明文)。`.sy.zip`、HTML、Word、PDF、Markdown 等格式均支持;锁定状态下拒绝导出++- 发布:不支持。加密笔记本及其文档不会出现在发布服务中,解锁或设置发布密码也不能启用++#### 忘记密码怎么办+无法恢复——这是设计使然(没有后门)。即使密文已同步到云端,没有主密码也解不开。务必牢记主密码,建议使用密码管理器保存。++#### 密钥备份丢失的恢复+若 `conf/conf.json` 与同步目录里的密钥备份同时丢失(极端情况),重新启用加密笔记本会被拒绝并提示恢复备份文件。只要能从其他已同步的设备或之前导出的密钥文件找回 `data-crypto-backup.json`,可通过 `Disabled` 或 `RecoveryRequired` 状态下显示的「导入密钥」按钮导入,或手动放回 `<工作区>/data/.siyuan/` 后重新启用,即可用该密钥对应的主密码解锁。++恢复已删除加密笔记本的历史同样需要与其 WrappedDEK 匹配的全局密钥备份和主密码。只要仍要保留这类本地恢复能力,就不要永久清除其历史或匹配的密钥备份;禁用流程应在发现这类依赖时拒绝继续。++#### 适合用加密笔记本的场景++- 隐私日记、财务记录、医疗信息++- 工作机密、商业方案、合同++- 担心设备遗失或被盗——加密后即使磁盘数据被恢复,没有主密码也只是密文++#### 不适合用加密笔记本的场景++- 日常笔记、学习笔记(加密的额外开销不值得)++- 需要全局搜索的内容(加密笔记本不参与)++- 需要通过发布服务对外提供的内容(加密笔记本不支持发布)++- 需要跨笔记本块引的知识网络(禁止跨边界)++- 需要跨笔记本移动整理的文档(禁止跨边界)++- 需要跨笔记本镜像数据库的场景(禁止跨边界)++- 需要闪卡复习的内容(不支持)++- 需要书签/标签管理的内容(不支持)++- 不希望 AI/LLM 接触的内容(解锁后 AI 可读;若介意,需保持锁定)++- 大量大文件(assets 每次浏览都全量解密)++#### 日常使用习惯建议++1. 主密码必须牢记:忘记密码 = 数据永久不可恢复(没有后门)++2. 用完即锁:减少 DEK 在内存的暴露时间++3. 不要把所有笔记都放加密笔记本:只放真正敏感的++4. 主密码强度:建议 12 位以上,混合大小写 + 数字 + 符号++5. 备份:分别保留版本化的密文备份和匹配的密钥备份;主密码或全部匹配密钥备份丢失后,密文无法恢复++## 数据与存储++### 密钥架构```用户主密码@@ -97,44 +241,47 @@└─→ 解 BoxConf.WrappedDEK → DEK₃ → 加密笔记本 3```-- **Argon2id**:OWASP 2023 推荐参数,抗暴力破解(内存硬度)-- **DEK**:每笔记本独立 32 字节随机密钥,真正加密数据的密钥-- **KEK 包络**:改密码只需重新包络 DEK,不重新加密数据-- **不缓存 KEK**:每次解锁都派生,保持严格的笔记本间隔离+- Argon2id:使用内存困难的密钥派生,参数为 64 MB、3 次迭代、4 个线程++- DEK:每笔记本独立 32 字节随机密钥,用于加密数据的密钥++- KEK 包络:改密码只需重新包络 DEK,不重新加密数据-### 4.1 MasterSalt 备份与跨设备恢复+- 不缓存 KEK:每次解锁都派生,保持严格的笔记本间隔离-MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各笔记本的 WrappedDEK。**MasterSalt 丢失等于数据永久锁死**:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。+#### MasterSalt 备份与跨设备恢复-**备份**:`<DataDir>/.siyuan/data-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams/HistoryKEKs)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储,其中 verifier 和历史 KEK 均为密文,与 `conf/conf.json` 的存储方式一致。+MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各笔记本的 WrappedDEK。MasterSalt 丢失等于数据永久锁死:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。++备份:`<DataDir>/.siyuan/data-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams/HistoryKEKs)。位于 DataDir 内,进入 dejavu 同步范围。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储,其中 verifier 和历史 KEK 均为密文,与 `conf/conf.json` 的存储方式一致。每个加密笔记本另行保存 `<DataDir>/<boxID>/.siyuan/notebook-crypto-backup.json`,其中包含该笔记本的 BoxEncryption 密钥包络(WrappedDEK/WrapNonce 和认证元数据)。全局 `data-crypto-backup.json` 提供 KEK 派生身份,单笔记本 `notebook-crypto-backup.json` 提供已封装 DEK,两者不能相互替代。-**恢复触发点**(覆盖 conf.json 丢失 / 同步到新设备 / 导入 Data.zip 等场景):+恢复触发点(覆盖 conf.json 丢失 / 同步到新设备 / 导入 Data.zip 等场景):| 触发场景 | 函数 | 需要主密码? | 说明 ||---|---|---|---|| 同步完成后(拉取到备份文件) | `restoreNotebookCryptoConfigFromBackup` | 否 | 把配置装回本机 conf.json 并置 `Enabled=true`,UI 显示"已启用、锁定" || 导入 Data.zip 后 | `restoreNotebookCryptoConfigFromBackup` | 否 | 同上,覆盖"备份随 Data.zip 到达本机但本机未启用"的情况 || 用户输主密码解锁(兜底) | `tryRestoreNotebookCryptoFromBackup` | 是 | `deriveKEK` 在本机 `Enabled=false` 时尝试恢复,校验主密码后返回 KEK |-| 用户手动启用(防呆) | `tryRestoreNotebookCryptoFromBackup` | 是 | 已存在加密笔记本时拒绝生成新 salt,改为从备份恢复并校验主密码 |+| 用户手动启用(恢复保护) | `tryRestoreNotebookCryptoFromBackup` | 是 | 已存在加密笔记本时拒绝生成新 salt,改为从备份恢复并校验主密码 |-**配置恢复 vs 密钥恢复分离**:配置恢复只需读备份文件、装回 salt/verifier(不需主密码,因 salt 不保密、没主密码仍解不开数据);密钥恢复才需主密码派生 KEK 并校验 verifier。这让同步/导入后能自动进入"已启用"状态,用户输主密码即可解锁。+配置恢复 vs 密钥恢复分离:配置恢复只需读备份文件、装回 salt/verifier(不需主密码,因 salt 不保密、没主密码仍解不开数据);密钥恢复才需主密码派生 KEK 并校验 verifier。这让同步/导入后能自动进入"已启用"状态,用户输主密码即可解锁。-**手动导出与导入密钥**:除自动同步外,用户可在 **设置 - 鉴权 - 加密笔记本** 手动导出与导入密钥备份,作为同步之外的独立恢复途径(如同步不可用、跨账号迁移、物理离线转存)。+手动导出与导入密钥:除自动同步外,用户可在 设置 - 鉴权 - 加密笔记本 手动导出与导入密钥备份,作为同步之外的独立恢复途径(如同步不可用、跨账号迁移、物理离线转存)。| 操作 | 入口 | 说明 ||---|---|---|| 导出密钥 | 已启用状态下显示 | 把 `data-crypto-backup.json` 复制到 export 目录供下载,用户自行保管(API:`/api/notebook/exportNotebookCryptoBackup`) || 导入密钥 | `Disabled` 或 `RecoveryRequired` 状态下显示 | 选本地备份文件上传,校验合法后写回 `<DataDir>/.siyuan/` 并装回本机配置(`Enabled=true`)。后续用该密钥对应的主密码解锁(API:`/api/notebook/importNotebookCryptoBackup`) |-导入防呆:完整的 `Enabled` 配置拒绝导入,避免覆盖现有 salt 并孤立 WrappedDEK;`RecoveryRequired` 仅在候选密钥通过认证且能解开全部现存加密笔记本及内核可枚举的已删除笔记本历史依赖时允许导入。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出和导入不涉及明文数据泄漏,解锁仍需主密码。+导入恢复保护:完整的 `Enabled` 配置拒绝导入,避免覆盖现有 salt 并孤立 WrappedDEK;`RecoveryRequired` 仅在候选密钥通过认证且能解开全部现存加密笔记本及内核可枚举的已删除笔记本历史依赖时允许导入。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出和导入不涉及明文数据泄漏,解锁仍需主密码。-**防呆守卫**:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的笔记本)或内核可枚举的加密恢复数据时,**禁止重新生成 MasterSalt**(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。`DisableEncryptedNotebook` 对称地扫描现存笔记本、已删除笔记本历史和本地恢复快照;存在依赖时必须拒绝禁用,除非用户明确选择永久清除这些恢复数据。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。+恢复保护守卫:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的笔记本)或内核可枚举的加密恢复数据时,禁止重新生成 MasterSalt(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。`DisableEncryptedNotebook` 对称地扫描现存笔记本、已删除笔记本历史和本地恢复快照;存在依赖时必须拒绝禁用,除非用户明确选择永久清除这些恢复数据。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。-**前提条件**:`restoreNotebookCryptoConfigFromBackup` 仅在本机 `Enabled=false` 时生效,不覆盖正在使用的本机配置。+前提条件:`restoreNotebookCryptoConfigFromBackup` 仅在本机 `Enabled=false` 时生效,不覆盖正在使用的本机配置。-## 5. 加密文件布局+### 加密文件布局```<workspace>/@@ -142,7 +289,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i├── storage/av/ ← 普通笔记本的 数据库文件(明文)├── data/│ ├── .siyuan/-│ │ └── data-crypto-backup.json ← NotebookCrypto 备份(MasterSalt/KEKVerifier,进同步范围,详见 §4.1)+│ │ └── data-crypto-backup.json ← NotebookCrypto 备份(MasterSalt/KEKVerifier,进同步范围,详见 MasterSalt 备份与跨设备恢复)│ ├── <boxID>/ ← 加密笔记本目录│ │ ├── .siyuan/│ │ │ ├── conf.json ← BoxConf(Encrypted=true + WrappedDEK)@@ -163,233 +310,256 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i└── siyuan-encrypted-<boxID>-blocktree.db ← 加密笔记本 blocktree SQLite 数据库(SQLCipher)```-## 6. SQLite 数据库隔离设计--```-普通笔记本操作:- 前端 → API → 原函数 → 全局 blocktree.db → 全局 siyuan.db--加密笔记本操作(专用读路径,带 boxID):- 前端(带 notebook) → API handler 分流 → InBox 函数- → 加密 blocktree SQLite 数据库 → 加密 content SQLite 数据库-```--**写路径**:集中收口,按笔记本选 SQLite 数据库。索引队列、blocktree 写函数、索引订正全部按笔记本路由。--**读路径**:三层 fall-through——handler 层按 `notebook` 参数分流;原函数转发到 InBox 版(普通路径传空 boxID);底层 wrapper 按加密 SQLite 数据库 是否打开决定路由,空 boxID 必走全局 SQLite 数据库。--**深度全路由原则**:加密笔记本的读操作经过的每一个 sql 调用(含深层 helper:引用计数、块名/别名、子块递归、FTS 计数、高亮、mention 搜索、refs 定义查询等)都路由到加密 SQLite 数据库,绝不泄漏到全局 SQLite 数据库。--**通用入口 fallback**:`GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` 等核心函数全局查不到时自动遍历已打开的加密笔记本。+### .sy / assets / 数据库文件加解密-## 7. .sy / assets / 数据库文件加解密+`.sy` 透明加解密(filesys 层):-**`.sy` 透明加解密**(filesys 层):- `DEKProvider` 回调注入(避免循环依赖)+- 读盘后解密,写盘前加密,缓存存明文+- 加密笔记本的标题读取需整体读 + 解密再解析+- `.sy` AAD 绑定 boxID、对象类型和稳定文件基名 `<rootID>.sy`,不包含父目录;文件基名必须与解密后根块 ID 一致,并在笔记本内全局唯一+- 父目录不属于 AAD,应用仍按现有目录结构构建文档层级;加载时校验文件基名与解密后根块 ID 一致,并拒绝同一笔记本内的重复对象 ID、非法路径和循环层级,但不提供父目录关系的密码学完整性-**assets 加密**:+assets 加密:+- 上传时全量读入内存 + 加密 + 写盘(无法流式加密)+- 文件名脱敏:加密笔记本的 asset 文件名为 `<uuid>-<blockID>.<ext>`,原始名、明文大小和分块数量作为认证加密元数据存入同一个资源容器+- 新写入的容器以 `SYAE` 标识开头,认证加密元数据包含 `spec=2`、每次写入由操作系统 CSPRNG 生成的 32 字节 `containerID`、原始名称、明文大小及分块数量;内容分块的 AAD 为 `siyuan:asset:<boxID>:assets/<diskName>:content:v2:<containerID 的小写十六进制>:<从零开始的分块序号>`,名称元数据使用同一前缀加 `:metadata` 认证。不同写入版本的分块或元数据不能互换,整份旧容器回滚仍不在防护范围内+- 读取时先认证并解密名称元数据,再逐块认证解密内容;下载时使用容器中的原始名+- 兼容元数据同时不含 `spec` 和 `containerID` 的旧 `SYAE` 资源,分块使用 `siyuan:asset:<boxID>:assets/<diskName>:content:<分块序号>` 认证;名称读取、内容读取、导出及历史快照均支持该格式。显式空版本、缺少新版必需字段、未知版本和认证失败均拒绝处理,不尝试其他版本的 AAD+- 新增或重新保存资源统一写入第 2 版;仅打开、预览、下载或导出不会改写原文件,也不要求用户重建资源。旧格式只有原有的逐块认证,不能事后验证不同写入版本的分块是否曾被拼接;重新保存生成的第 2 版容器具备分块绑定,不能据此证明旧内容此前未被拼接。兼容读取不提供防降级或防回滚保证,替换为旧格式的数据仍按旧格式校验+- 加密笔记本禁用全局 assets 回退,强制笔记本级+- 资源文件重命名禁止(脱敏磁盘文件名参与 AAD,改名需要重新封装整个资源)+- 原始名称和资源内容位于同一个加密容器,不存在跨文件名称映射事务;写入失败必须向调用方返回错误-**数据库文件加密**:+数据库文件加密:+- 路径 fallback:加密笔记本的数据库文件存 `<boxID>/storage/av/<avID>.json`,普通笔记本仍存全局 `storage/av/`+- 读取:先查全局路径,找不到时遍历已打开的加密笔记本;找到后 DEK 解密再 JSON 解析+- 保存:JSON 序列化后按路径路由(全局明文 / 加密笔记本 DEK 加密)+- 首次创建:`RenderAttributeView` 从 blockID 反查 boxID 并预设归属+- 镜像:禁止加密笔记本参与跨边界镜像;加密笔记本内部镜像存笔记本级 `blocks.msgpack`-## 8. 历史功能的安全设计+## 实现与接口-```-文件历史:- 编辑触发历史生成 → 密文 .sy 原样拷到历史目录- 关闭/退出前自动生成历史 → 确保锁定后定时器无法生成时不丢历史- 历史索引 → content 留空(密文不进搜索索引)- 查看历史 → 读取快照 boxID + 对象类型 + 稳定文件基名,以三者构造原 AAD 解密(需笔记本已解锁)- 回滚 → 按快照 AAD 解密历史 → 校验根块 ID 与文件基名一致 → 加载 tree → 由 WriteTree 序列化恢复后的内容,并按目标文件基名重新封装+### SQLite 数据库隔离设计-已删除笔记本历史:- 删除前 → 整个目录密文备份到历史目录- 恢复 → 将密文目录原样拷回并保持关闭,解锁时再使用匹配的全局密钥备份和主密码验证 WrappedDEK- 密钥保留 → 只要内核管理的该类历史仍可恢复,就禁止删除其依赖的全局密钥备份;永久清除历史后才解除依赖+```+普通笔记本操作:+ 前端 → API → 原函数 → 全局 blocktree.db → 全局 siyuan.db-数据库历史:- 生成 → 加密笔记本的 数据库文件从笔记本级目录拷到历史目录- 查看 → 按快照记录的 boxID 与对象用途/标识解密,不使用历史目录绝对路径作为 AAD- 回滚 → 加密笔记本的数据库文件/资源回滚到笔记本级目录+加密笔记本操作(专用读路径,带 boxID):+ 前端(带 notebook) → API handler 分流 → InBox 函数+ → 加密 blocktree SQLite 数据库 → 加密 content SQLite 数据库```-历史文件在历史目录中的父路径不是 AAD 的组成部分。每个历史条目必须以不可歧义的规范格式保留快照写入时的 `boxID`、对象类型和稳定文件基名或对象标识;可由固定历史目录布局编码,也可由随快照提交的元数据记录。文档只改变父目录时 AAD 上下文保持不变;文件基名改变时,既有历史仍使用旧基名认证解密。回滚时先验证密文、文件基名与解密后对象 ID 一致,再按目标父目录恢复;文档回滚还会规范化树结构并处理重复块 ID,因此即使文件基名不变,也由 WriteTree 序列化恢复后的内容并生成新封装,历史源密文保持不变。已删除笔记本的目录拷回属于关闭状态的恢复,不代表当前密钥备份已匹配;认证在解锁时执行,缺少匹配备份时可在之后补充恢复材料。快照上下文缺失、格式不合法或与密文不匹配时必须拒绝查看和回滚,不得把密文当明文解析或使用当前文件基名替代快照基名。+写路径:集中收口,按笔记本选 SQLite 数据库。索引队列、blocktree 写函数、索引订正全部按笔记本路由。++读路径:三层 fall-through——handler 层按 `notebook` 参数分流;原函数转发到 InBox 版(普通路径传空 boxID);底层 wrapper 按加密 SQLite 数据库 是否打开决定路由,空 boxID 必走全局 SQLite 数据库。++深度全路由原则:加密笔记本的读操作经过的每一个 sql 调用(含深层 helper:引用计数、块名/别名、子块递归、FTS 计数、高亮、mention 搜索、refs 定义查询等)都路由到加密 SQLite 数据库,绝不泄漏到全局 SQLite 数据库。-## 9. 块引跨加密边界防护+通用入口 fallback:`GetBlockTree` / `ExistBlockTree` / `GetBlockTrees` / `LoadTreeByBlockID` 等核心函数全局查不到时自动遍历已打开的加密笔记本。++### 块引跨加密边界防护加密笔记本的块引:笔记本内部正常使用,跨加密边界被禁止。三层防御:-1. **前端搜索分流**:加密笔记本内输入 `((` 或 `{{` 触发搜索时,请求带 `notebook` 参数,内核只搜该笔记本自己的加密 SQLite 数据库,结果不含其他笔记本的块。-2. **handler 分流**:加密笔记本调专用搜索版。-3. **落库兜底校验**:事务落库前遍历树,对每个块引节点判定是否跨边界,跨边界则降级为纯文本(清空引用属性,保留锚文本)。防御手工输入块 ID、拖拽、粘贴、API 直调。+1. 前端搜索分流:加密笔记本内输入 `((` 或 `{{` 触发搜索时,请求带 `notebook` 参数,内核只搜该笔记本自己的加密 SQLite 数据库,结果不含其他笔记本的块++2. handler 分流:加密笔记本调专用搜索版++3. 落库兜底校验:事务落库前遍历树,对每个块引节点判定是否跨边界,跨边界则降级为纯文本(清空引用属性,保留锚文本)。防御手工输入块 ID、拖拽、粘贴、API 直调-## 10. 跨加密边界移动:为何禁止+### 跨边界移动规则加密笔记本禁止文档跨加密边界移动(普通 ↔ 加密,双向)。-**数据损坏风险**:跨笔记本移动用文件系统 Rename 直搬 `.sy` 字节流,不经加解密转换。密文搬到普通目录不可读,明文搬到加密目录不可读。索引也无法跨库迁移。+数据损坏风险:跨笔记本移动用文件系统 Rename 直搬 `.sy` 字节流,不经加解密转换。密文搬到普通目录不可读,明文搬到加密目录不可读。索引也无法跨库迁移。-**同一加密笔记本内移动**:`.sy` 密文 AAD 只绑定稳定文件基名,不绑定父目录。文件基名不变的移动按普通笔记本的同箱移动语义原样 Rename 密文,不需要重新封装根文档或子文档;只有文件基名本身变化时才使用旧基名验证解密并按新基名重新封装。移动完成后更新索引,失败处理与普通笔记本一致,不额外引入加密层级元数据。+同一加密笔记本内移动:`.sy` 密文 AAD 只绑定稳定文件基名,不绑定父目录。文件基名不变的移动按普通笔记本的同箱移动语义原样 Rename 密文,不需要重新封装根文档或子文档;只有文件基名本身变化时才使用旧基名验证解密并按新基名重新封装。移动完成后更新索引,失败处理与普通笔记本一致,不额外引入加密层级元数据。-**安全泄漏风险**(更关键):从加密笔记本移动到普通笔记本时——文档正文脱离加密保护;关联 resources 必须一起搬出解密;绑定块与子文档的引用网被割裂或连带泄漏;索引元数据跨库迁移破坏隔离。+安全泄漏风险:从加密笔记本移动到普通笔记本时——文档正文脱离加密保护;关联 resources 必须一起搬出解密;绑定块与子文档的引用网被割裂或连带泄漏;索引元数据跨库迁移破坏隔离。-**设计立场**:加密笔记本是孤岛,内容不进出(从加密笔记本移出到普通笔记本会泄漏明文;反之会损坏密文)。+设计立场:加密笔记本是孤岛,内容不进出(从加密笔记本移出到普通笔记本会泄漏明文;反之会损坏密文)。-## 11. 交互设计+### AI / LLM 可达性-| 场景 | 交互 |-|---|---|-| 启用 | 设置 - 鉴权 - 加密笔记本,打开开关并设置主密码(双输入 + 风险确认) |-| 禁用 | 仅在无现存加密笔记本且无依赖当前密钥备份的内核可枚举历史或恢复快照时支持关闭;否则拒绝,或要求用户明确永久清除这些恢复数据后再删除全局配置与备份 |-| 创建 | 文件面板 - 「更多」菜单 - 「新建加密笔记本」,输入名字和主密码后自动解锁并打开 |-| 图标 | 关闭(锁定)时显示锁图标;打开(解锁)后恢复用户 emoji |-| 解锁 | 点击已关闭的加密笔记本,在主密码框(🔓 解锁 xxx)中输入密码,等待约 1 秒后打开 |-| 锁定 | 等于关闭:先阻止新操作,等待或取消在途任务,再移除受管 DEK 句柄、删除加密 SQLite 数据库,并尽力清理内核管理的明文缓存、临时文件和访问令牌。关闭前会自动保存未写入的编辑和文件历史 |-| 自动锁定 | 每个已解锁笔记本独立保存最近活动时间;认证用户在当前工作区产生真实界面交互时,统一刷新所有当前已解锁加密笔记本的活动时间。无界面客户端也可通过需要认证与管理员权限的显式保活接口执行同样的刷新;后台读取、同步、索引等非用户活动不自动保活 |-| 改密 | 设置 - 鉴权 - 加密笔记本 - 「修改主密码」 |-| 移动文档 | 加密笔记本内部仅改变父目录时原样移动密文并更新索引;文件基名变化时重新封装;普通笔记本之间正常移动;跨加密边界(普通↔加密)被拒绝并提示 |-| 文档转标题 | 跨加密边界被拒绝并提示 |-| 块引 | 加密笔记本内部正常引用(搜索 `((` 只搜本笔记本,反链面板正常显示);跨加密边界(普通↔加密、加密 A↔加密 B)被阻止 |-| 数据库镜像 | 加密笔记本内部正常镜像;跨加密边界被禁止 |-| 资源文件重命名 | 不支持(脱敏文件名重命名会破坏映射) |-| 导入 | 支持:导入的 .sy.zip 或 Markdown 文件落盘前自动 DEK 加密 |-| 文件历史 | 支持(查看时需先解锁对应加密笔记本;历史索引不存明文内容) |-| 已删除笔记本 | 支持(密文备份,恢复需匹配的全局密钥备份与主密码;保留该历史时不得直接删除所依赖的密钥备份) |-| 发布 | 不支持;发布权限编辑界面不提供加密笔记本及其文档的配置入口,发布服务无论认证状态如何均不可见 |-| 导出 | 支持(与普通笔记本一致;需先解锁,导出的是明文。锁定状态下拒绝导出) |-| 同步 | 不改(密文进密文出,闭环自洽) |+加密笔记本通过支持的专用入口对 AI/LLM 的可见性由解锁状态决定,不另设“对 AI 隐藏”的功能层开关。全局搜索、语义搜索和嵌入向量化始终不纳入加密内容。++锁定状态下:AI/LLM(含 MCP、智能体)无法取得可用 DEK 句柄,所有加密笔记本专用入口都拒绝访问;独立数据库已关闭,磁盘内容为密文,因此这些调用方读不到加密内容。++解锁状态下:DEK 在内存,AI/LLM 可读加密笔记本内容、搜索笔记本内全文——MCP 工具能列出加密笔记本及其文档、读取块内容、笔记本内 FTS 搜索等。但全局搜索、语义搜索、嵌入向量化仍不参与(加密数据不进全局 `block_embeddings`/`blocks` 表,物理不可达),详见 「加密笔记本 vs 普通笔记本」 对比表。++设计立场:不在功能层做“对 AI 隐藏”的隔离,因为这种隔离既不彻底,又会让安全模型复杂难懂。锁定后受支持入口无法访问内容,但锁定不替代进程与操作系统层面的防护。用户只需理解一条规则:敏感内容用完即锁。++### 性能区别++| 操作 | 普通笔记本 | 加密笔记本 | 差异原因 |+|---|---|---|---|+| 解锁(Mount) | 即时 | ~1 秒延迟 | Argon2id 密钥派生(故意慢以抗暴力破解) |+| 打开文档 | 读盘 + 解析 JSON | 读盘 + AES-GCM 解密 + 解析 + 加密 SQLite 数据库 查询 | 多一次解密 + 加密 SQLite 数据库 查询 |+| 保存文档 | 渲染 JSON + 写盘 | 渲染 JSON + AES-GCM 加密 + 写盘 | 多一次加密 |+| 上传 assets | 流式写盘 | 全量读入内存 + 加密 + 写盘 | 无法流式加密;大文件有内存压力 |+| 浏览 assets | 直接 ServeFile | 读盘 + 解密 + 输出 | 每次请求都解密,无浏览器缓存 |+| 数据库渲染 | 全局 blocktree + 明文 JSON | 加密 blocktree + DEK 解密 JSON | 多一次 JSON 解密;批量 IAL 加载按笔记本路由 |+| 数据库保存 | 明文 JSON 写盘 | DEK 加密 + 写盘 | 多一次加密 |+| 笔记本内搜索 | FTS 查全局 SQLite 数据库 | FTS 查独立加密 SQLite 数据库 | SQLCipher page 级解密 ~5-10% 开销 |+| 数据库连接 | 1 个全局 | 1 个全局 + 每个解锁的加密笔记本 2 个 | 每加密 SQLite 数据库 连接池约 20 连接 |+| 锁定时 | 无额外开销 | 受管密钥句柄撤销,并尽力清理缓存与临时文件 | 下次操作冷启动延迟 |++性能说明:++- 日常编辑体验:几乎无感知。AES-GCM 加解密是微秒级,文档读写瓶颈在磁盘 IO++- 感知明显的延迟:解锁 ~1 秒、大 assets 浏览(每次解密无缓存)、锁定后首次访问(冷启动)++- 对普通笔记本零影响:加解密与路由逻辑对非加密笔记本短路跳过++### 状态机与并发规则++全局状态为 `Disabled`、`Enabled` 或 `RecoveryRequired`。正常稳态下,`Disabled` 不得存在现存加密笔记本或内核可枚举的密钥依赖;如果启动时在全局配置缺失或禁用的情况下发现加密笔记本或恢复数据,必须进入 `RecoveryRequired`,拒绝把它们当作普通笔记本,直到恢复匹配的密钥备份。`Enabled` 下每个加密笔记本独立处于 `Locked`、`Unlocking`、`Unlocked`、`Locking` 或 `Error`,应用启动后均从 `Locked` 开始。++加密身份判定必须 fail-closed。合法 boxID 的 `conf.json` 或笔记本密钥备份缺失、损坏时,只要磁盘上存在当前密文格式标识,或当前进程已经确认过该笔记本的加密身份,就必须把笔记本置为 `Error` 并拒绝普通笔记本读写,不能自动生成 `Encrypted=false` 的配置。只有笔记本删除流程在排空生命周期租约并清除本机 DEK、挂载标记、专属数据库和缓存后,才能移除运行时加密身份。++| 转换 | 前置条件 | 成功后的不变量 | 失败处理 |+|---|---|---|---|+| `Locked → Unlocking → Unlocked` | 主密码验证成功且密文配置匹配 | 可用 DEK 句柄仅存在于受管内存;专属数据库已打开;允许笔记本专用入口 | 撤销派生的 KEK/DEK 句柄、关闭已打开资源并回到 `Locked` |+| `Unlocked → Locking → Locked` | 原子地关闭新操作准入,并等待在途操作结束或取消 | 无可用受管 DEK 句柄或数据库连接;内核管理的明文缓存、临时文件与令牌已尽力清理 | 密钥和数据库清理完成后仍进入 `Locked`;临时文件清理失败只记录不含明文的诊断,并在退出或下次启动时重试 |+| `Unlocked → Error` | 密文认证失败、数据库打开失败或不变量被破坏 | 立即拒绝读写,绝不回退到普通笔记本路径 | 关闭资源,诊断信息不得含明文;用户只能锁定或重新解锁 |+| 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK、全局配置和备份作为一个可恢复事务更新 | 保留旧配置和备份可用;不得出现仅能用新密码解锁的部分笔记本 |++每个笔记本使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。解锁并打开必须在同一个笔记本转换锁内完成;挂载失败只能回滚本次新建的解锁状态,不能锁定由其他并发请求已经使用的 DEK 或挂载。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、撤销受管 DEK 句柄,并尽力清理缓存和临时产物。密钥句柄和数据库连接清理完成后发布 `Locked`;临时文件删除失败不阻止锁定,但必须记录诊断并在退出或下次启动时重试。因此锁定完成后不得再出现新的明文响应、缓存回填或数据库重连,但磁盘上可能保留清理失败的临时明文副本。++全局配置锁必须先于任何笔记本生命周期锁获取;同时涉及多个笔记本时按 boxID 字典序获取生命周期锁;DEK 缓存、数据库、文件和其他子系统锁只能在生命周期锁之后获取,并在释放生命周期锁前释放。禁止逆序获取,禁止持有子系统锁时回取全局配置锁或其他较低层级锁。自动锁定按每个笔记本保存活动时间,但当前工作区的一次认证用户交互或显式保活会统一刷新所有已解锁笔记本;计时采用系统时钟并由周期任务检查,系统时钟调整可能相应提前或推迟触发时间,自动锁定是便利性保护而不是精确的安全计时边界。++### 功能边界、临时明文与接口规则++加密笔记本中的资源文件不支持文字识别(OCR),与解锁状态无关。手动识别返回本地化的“不支持”提示,自动识别跳过加密笔记本资源;不得为这些资源生成 OCR 文本或写入全局 OCR 存储和搜索索引。++不支持的发布、闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。发布访问判定必须独立于锁定状态并优先于 `publishAccess.json`,已存在的发布配置不得使加密笔记本重新可见。错误码和本地化文案应稳定,供调用方识别。++拒绝操作时必须说明具体原因和可行的处理方式,不得用同一句笼统文案覆盖互不相关的原因:例如导入带闪卡的 `.sy.zip` 时,应指出命中闪卡的文档或牌组,并提示在源笔记本移除闪卡后重新导出或改为导入普通笔记本;未解锁时应提示解锁;跨加密边界移动或引用时应说明加密笔记本是隔离空间,而不是返回“不支持该操作”。++所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。加密笔记本的持久化目录始终拒绝原始入口直接访问,避免密文泄漏或绕过加密层写入;工作空间 `temp/` 是管理员文件 API、归档 API 和受信任插件可访问的通用临时空间,不属于加密访问控制边界。WebDAV 继续无条件拒绝整个 `temp/`,避免通过远程文件服务暴露临时数据。新增入口时必须分别评审其是否接触加密笔记本持久化目录或临时明文。++#### 临时明文生命周期++导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物统一放在 `temp/export/<boxID>/<kind>/<exportID>/`。第一层 boxID 是清理归属标识,不是访问权限;普通导出和插件临时文件不得使用合法 boxID 作为 `temp/export/` 的第一层名称。++内存态导出令牌 `managedEncryptedExports` 用于管理下载链接的有效期和生命周期,不作为本机文件、管理员 API 或受信任插件的安全隔离。锁定、删除、取消、失败和正常退出时必须撤销相关令牌,并尽力删除 `temp/export/<boxID>`;应用启动时至少扫描并删除第一层名称为合法 boxID 的残留目录,桌面端的通用临时目录初始化还会清空整个 `temp/export`。任何调用方都不得依赖 `temp/` 中的文件跨进程存续。删除失败只记录不含明文的诊断,不阻止笔记本进入 `Locked`,后续退出或启动时继续尝试。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。++移动端原生保存流程必须通过 `AcquireExportFile` 取得包含路径、名称、大小和租约 ID 的导出租约,在复制及校验完成后的 `finally` 路径调用 `ReleaseExportFile`;加密导出不得使用只返回路径或名称的旧接口,因为它们不能覆盖原生复制阶段的生命周期。++## 兼容与恢复++### 已有数据兼容策略++当前已写入的加密数据作为兼容基线。格式和密钥管理变更必须保留已有数据的可读性与恢复能力,不得再以开发阶段为由要求用户删除或重建数据。兼容范围包括文档、资源及其原始名称、数据库定义、密钥包络、备份、历史和同步快照。++数据库绑定遵循相同的隔离边界。向加密笔记本导入 `.sy.zip` 时,指向本次导入块的绑定重映射到新块;指向包外块的绑定转为非绑定条目,保留条目 ID、已存文本和其他字段值。导入文档的反向绑定仅保留包内数据库。导入不得向目标边界外的文档回写数据库绑定。普通导入保留指向现有普通文档的绑定。新增绑定条目、换绑及编辑绑定主键时,必须在修改条目或文档前校验边界。++导出时不得静默删除已有的无效数据库反向绑定,也不得跨加密边界解析。导出错误应指出受影响的数据库 ID,并保留源数据。排查受影响文档时,应将其 `custom-avs` 与允许存储范围内的数据库逐项核对,保留备份后仅显式移除已确认无效的绑定。文件缺失、数据损坏和认证失败仍须报错;解锁其他加密笔记本不会将其数据库纳入该文档的导出范围。本次绑定修正不改变密文格式、AAD、密钥或旧格式认证读取路径。-## 12. 安全边界+表格单元格富文本使用文档 `Spec: "4"`,在经过认证的明文语法树中增加可选的 `TableCellRich` 源数据包络。已有文档版本继续可读,单元格不会自动转换。文档加密包络、AAD、子密钥派生和恢复密钥均保持不变。读取、导出、历史、快照和恢复均先认证密文,再校验文档及富文本版本;未知格式或损坏的源数据必须报错并保留原始数据。只有认证和源数据校验成功后,才可重建行级投影。++### 安全边界++安全前提:加密笔记本在关闭(锁定)状态下提供最强的应用级保护。锁定完成后,新操作被拒绝,受管 DEK 句柄和数据库连接已移除,内核管理的明文缓存、临时文件与令牌已尽力清理;这不承诺抹除 Go 运行时、操作系统交换区、崩溃转储或存储介质中的所有瞬时副本。打开(解锁)状态下,应用持有可用 DEK 句柄,此时获得主应用授权的 API、第三方插件、AI/LLM(含 MCP、智能体)可通过支持的笔记本专用入口读取明文内容和使用笔记本内搜索;全局搜索、语义搜索和嵌入向量化不参与。发布服务是明确例外:发布读者与匿名访问者无论笔记本是否解锁均不可列举或读取加密笔记本,发布密码、可见性配置和 `publishAccess.json` 均不能覆盖该规则。内核 CLI 同样无论锁定或解锁都会拒绝加密笔记本及其原始文件。加密保护的是“静态数据”和“锁定后经受支持入口的不可达性”,不保护“解锁后对主应用授权调用方的可见性”。因此:解锁期间应视为“普通笔记本在主应用中使用”,并在用完后立即锁定。-**安全前提**:加密笔记本在关闭(锁定)状态下提供最强的应用级保护。锁定完成后,新操作被拒绝,受管 DEK 句柄和数据库连接已移除,内核管理的明文缓存、临时文件与令牌已尽力清理;这不承诺抹除 Go 运行时、操作系统交换区、崩溃转储或存储介质中的所有瞬时副本。**打开(解锁)状态下,应用持有可用 DEK 句柄**,此时获得主应用授权的 API、第三方插件、AI/LLM(含 MCP、智能体)可通过支持的笔记本专用入口读取明文内容和使用笔记本内搜索;全局搜索、语义搜索和嵌入向量化不参与。发布服务是明确例外:发布读者与匿名访问者无论笔记本是否解锁均不可列举或读取加密笔记本,发布密码、可见性配置和 `publishAccess.json` 均不能覆盖该规则。内核 CLI 同样无论锁定或解锁都会拒绝加密笔记本及其原始文件。加密保护的是“静态数据”和“锁定后经受支持入口的不可达性”,**不保护“解锁后对主应用授权调用方的可见性”**。因此:解锁期间应视为“普通笔记本在主应用中使用”,并在用完后立即锁定。+保护(磁盘上密文):-**保护(磁盘上密文)**:- `.sy` 文档正文(已加密)+- assets 二进制文件(已加密)+- assets 文件名(脱敏,原始名加密存储)+- 笔记本图标、列表排序权重和排序方式(保存在 `BoxCrypt.Metadata` 的认证密文中)+- 数据库文件(列/行/cell 值/视图配置/内容快照,已加密)+- content SQLite 数据库(blocks/FTS/attributes/refs,SQLCipher 加密)+- blocktree SQLite 数据库(块树元数据:ID/路径/标题,SQLCipher 加密)-- 历史目录中的 .sy 和 数据库文件(密文原样存储)-**不保护**:+- 历史目录中的 .sy 和数据库文件(密文原样存储)++不保护:+- `conf.json` 里的 MasterSalt/KEKVerifier(设计可明文:salt 不保密,verifier 是密文)+- BoxConf.WrappedDEK(密文,需 KEK 解开)+- 进程和操作系统可能产生的 DEK 派生值、明文瞬时副本、交换区、休眠映像或崩溃转储;锁定只保证撤销受管密钥句柄和尽力清理应用可控缓存+- `temp/` 中尚未清理的明文导出物;管理员文件 API、归档 API、受信任插件和本机进程均可访问+- 历史索引的 content 字段(留空,不存明文也不存密文)-- **元数据泄漏**(加密不掩盖以下信息):文件数量、目录结构、文件大小、修改时间(mtime)、asset 文件扩展名、blockID 时间戳。加密笔记本的 asset 文件名虽脱敏为 `uuid-blockID.ext`,但扩展名可见;同步端/历史快照中的旧密文也由各存储方自行保管,加密笔记本无法吊销其副本-**API 防护**:-- `/api/file/*`:拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),避免密文泄漏或绕过加密层写入;工作空间 `temp/` 保持可访问-- 发布服务:`RoleReader` 与 `RoleVisitor` 对加密笔记本及其文档、块、属性视图和资源始终不可访问;解锁状态和发布访问配置不改变该结果-- 内核 CLI:拒绝以加密笔记本或块 ID 为目标的命令,以及 `<工作区>/data/<加密笔记本 ID>/` 下的直接路径;不能用于解锁、读写、导出或操作加密笔记本数据+- 元数据泄漏(加密不掩盖以下信息):文件数量、目录结构、文件大小、修改时间(mtime)、asset 文件扩展名、blockID 时间戳。加密笔记本的 asset 文件名虽脱敏为 `uuid-blockID.ext`,但扩展名可见;同步端/历史快照中的旧密文也由各存储方自行保管,加密笔记本无法吊销其副本-## 13. AI / LLM 可达性+API 防护:-加密笔记本通过支持的专用入口对 AI/LLM 的可见性由**解锁状态**决定,不另设“对 AI 隐藏”的功能层开关。全局搜索、语义搜索和嵌入向量化始终不纳入加密内容。+- `/api/file/*`:拒绝访问加密笔记本持久化目录下的任何文件(不只 .sy),避免密文泄漏或绕过加密层写入;工作空间 `temp/` 保持可访问-**锁定状态下**:AI/LLM(含 MCP、智能体)无法取得可用 DEK 句柄,所有加密笔记本专用入口都拒绝访问;独立数据库已关闭,磁盘内容为密文,因此这些调用方读不到加密内容。+- 发布服务:`RoleReader` 与 `RoleVisitor` 对加密笔记本及其文档、块、属性视图和资源始终不可访问;解锁状态和发布访问配置不改变该结果-**解锁状态下**:DEK 在内存,AI/LLM 可读加密笔记本内容、搜索笔记本内全文——MCP 工具能列出加密笔记本及其文档、读取块内容、笔记本内 FTS 搜索等。但全局搜索、语义搜索、嵌入向量化仍不参与(加密数据不进全局 `block_embeddings`/`blocks` 表,物理不可达),详见 §3 对比表。+- 内核 CLI:拒绝以加密笔记本或块 ID 为目标的命令,以及 `<工作区>/data/<加密笔记本 ID>/` 下的直接路径;不能用于解锁、读写、导出或操作加密笔记本数据-设计立场:不在功能层做“对 AI 隐藏”的隔离,因为这种隔离既不彻底,又会让安全模型复杂难懂。锁定后受支持入口无法访问内容,但锁定不替代进程与操作系统层面的防护。用户只需理解一条规则:**敏感内容用完即锁**。+### 威胁模型与安全范围-## 14. 功能限制+本特性保护静态数据机密性和笔记本锁定后经受支持入口的不可访问性。设计假设攻击者可以取得工作空间、同步端或备份介质中的当前或历史密文,但不知道主密码,也不能在用户解锁期间控制运行中的应用或操作系统。AES-GCM 只提供单个加密对象的机密性、完整性和来源上下文认证,不提供可用性、版本新鲜度、回滚防护或已保留密文副本的删除。-加密笔记本是孤岛,部分功能因其跨 notebook 特性或依赖全局聚合而不支持,属于明确的功能边界。+下列场景不在本特性的保护范围内,界面和用户指南必须明确提示:-- **闪卡 / 间隔重复**:牌组与调度跨 notebook 且依赖全局 SQLite 数据库,不支持。-- **发布**:发布服务面向只读或匿名访问者,加密笔记本无论锁定或解锁均不参与发布,且不能通过发布密码或可见性配置启用。-- **书签**:全局聚合视图(扫全局 siyuan.db),加密笔记本不支持。-- **标签**:全局聚合视图(扫全局 spans 表),加密笔记本不支持。-- **资源文件重命名**:加密笔记本的 asset 文件名已脱敏为 `uuid-blockID.ext`,磁盘文件名参与 AAD,重命名需要重新封装整个资源。-- **未引用资源清理**:加密笔记本的资源不参与全局未引用清理(孤岛,资源不跨边界),避免锁定时因无法扫描文档引用而误删。-- **未引用数据库清理**:加密笔记本的数据库定义不参与全局未引用清理,避免锁定时因无法确认引用关系而误删。+- 笔记本解锁期间,获得主应用授权的 API、插件、MCP、AI/LLM,以及能读取应用进程内存的本机攻击者,均可能取得明文;发布服务的读者与匿名访问者不属于该范围并始终被拒绝-## 15. 性能区别+- 能读取工作空间文件的本机进程、管理员文件 API 和受信任插件可以读取尚未清理的临时明文导出物;临时目录不作为访问控制边界-| 操作 | 普通笔记本 | 加密笔记本 | 差异原因 |-|---|---|---|---|-| **解锁(Mount)** | 即时 | **~1 秒延迟** | Argon2id 密钥派生(故意慢以抗暴力破解) |-| **打开文档** | 读盘 + 解析 JSON | 读盘 + AES-GCM 解密 + 解析 + 加密 SQLite 数据库 查询 | 多一次解密 + 加密 SQLite 数据库 查询 |-| **保存文档** | 渲染 JSON + 写盘 | 渲染 JSON + AES-GCM 加密 + 写盘 | 多一次加密 |-| **上传 assets** | 流式写盘 | 全量读入内存 + 加密 + 写盘 | 无法流式加密;大文件有内存压力 |-| **浏览 assets** | 直接 ServeFile | 读盘 + 解密 + 输出 | 每次请求都解密,无浏览器缓存 |-| **数据库渲染** | 全局 blocktree + 明文 JSON | 加密 blocktree + DEK 解密 JSON | 多一次 JSON 解密;批量 IAL 加载按笔记本路由 |-| **数据库保存** | 明文 JSON 写盘 | DEK 加密 + 写盘 | 多一次加密 |-| **笔记本内搜索** | FTS 查全局 SQLite 数据库 | FTS 查独立加密 SQLite 数据库 | SQLCipher page 级解密 ~5-10% 开销 |-| **数据库连接** | 1 个全局 | 1 个全局 + 每个解锁的加密笔记本 2 个 | 每加密 SQLite 数据库 连接池约 20 连接 |-| **锁定时** | 无额外开销 | 受管密钥句柄撤销,并尽力清理缓存与临时文件 | 下次操作冷启动延迟 |--**性能影响总结**:-- **日常编辑体验**:几乎无感知。AES-GCM 加解密是微秒级,文档读写瓶颈在磁盘 IO。-- **感知明显的延迟**:解锁 ~1 秒、大 assets 浏览(每次解密无缓存)、锁定后首次访问(冷启动)。-- **对普通笔记本零影响**:加解密与路由逻辑对非加密笔记本短路跳过。--## 16. 威胁模型与安全范围+- 用户主动导出的文件、剪贴板、截图、打印件、分享给第三方的内容,以及保存在工作区外的明文文件,由用户负责保护-本特性保护静态数据机密性和笔记本锁定后经受支持入口的不可访问性。设计假设攻击者可以取得工作空间、同步端或备份介质中的当前或历史密文,但不知道主密码,也不能在用户解锁期间控制运行中的应用或操作系统。AES-GCM 只提供单个加密对象的机密性、完整性和来源上下文认证,不提供可用性、版本新鲜度、回滚防护或已保留密文副本的删除。+- 操作系统交换分区、休眠映像、崩溃转储、文件系统快照和恶意软件不因“清除内存”而获得绝对保护;锁定仅做应用可控范围内的尽力清除-下列场景不在本特性的保护范围内,界面和用户指南必须明确提示:+- 同步服务或备份持有者可以保留、删除、替换或回滚密文;这些行为可能造成拒绝服务或数据回退,但不能在不知道主密码时解密有效密文-- 笔记本解锁期间,获得主应用授权的 API、插件、MCP、AI/LLM,以及能读取应用进程内存的本机攻击者,均可能取得明文;发布服务的读者与匿名访问者不属于该范围并始终被拒绝。-- 能读取工作空间文件的本机进程、管理员文件 API 和受信任插件可以读取尚未清理的临时明文导出物;临时目录不作为访问控制边界。-- 用户主动导出的文件、剪贴板、截图、打印件、分享给第三方的内容,以及保存在工作区外的明文文件,由用户负责保护。-- 操作系统交换分区、休眠映像、崩溃转储、文件系统快照和恶意软件不因“清除内存”而获得绝对保护;锁定仅做应用可控范围内的尽力清除。-- 同步服务或备份持有者可以保留、删除、替换或回滚密文;这些行为可能造成拒绝服务或数据回退,但不能在不知道主密码时解密有效密文。-- 父目录不进入 AAD,因此能够写工作空间密文的攻击者可以在同一笔记本内移动一个文件基名不变的有效密文,应用会把新父目录视为当前文档层级;内容、笔记本、对象类型和稳定对象 ID 仍受认证,但父目录层级本身不提供密码学完整性。+- 父目录不进入 AAD,因此能够写工作空间密文的攻击者可以在同一笔记本内移动一个文件基名不变的有效密文,应用会把新父目录视为当前文档层级;内容、笔记本、对象类型和稳定对象 ID 仍受认证,但父目录层级本身不提供密码学完整性“锁定后仅剩密文”只表示加密笔记本的持久化数据保持加密,并且受管临时文件、缓存和密钥句柄已经执行尽力清理;它不保证工作空间 `temp/` 中不存在因崩溃、文件占用或权限错误而残留的明文,也不包括用户明确导出到外部位置的文件,且不承诺抹除进程、操作系统或底层存储介质已经保留的瞬时或历史副本。-## 17. 状态机与并发规则+### 密文、密钥与数据库格式-全局状态为 `Disabled`、`Enabled` 或 `RecoveryRequired`。正常稳态下,`Disabled` 不得存在现存加密笔记本或内核可枚举的密钥依赖;如果启动时在全局配置缺失或禁用的情况下发现加密笔记本或恢复数据,必须进入 `RecoveryRequired`,拒绝把它们当作普通笔记本,直到恢复匹配的密钥备份。`Enabled` 下每个加密笔记本独立处于 `Locked`、`Unlocking`、`Unlocked`、`Locking` 或 `Error`,应用启动后均从 `Locked` 开始。--加密身份判定必须 fail-closed。合法 boxID 的 `conf.json` 或笔记本密钥备份缺失、损坏时,只要磁盘上存在当前密文格式标识,或当前进程已经确认过该笔记本的加密身份,就必须把笔记本置为 `Error` 并拒绝普通笔记本读写,不能自动生成 `Encrypted=false` 的配置。只有笔记本删除流程在排空生命周期租约并清除本机 DEK、挂载标记、专属数据库和缓存后,才能移除运行时加密身份。--| 转换 | 前置条件 | 成功后的不变量 | 失败处理 |-|---|---|---|---|-| `Locked → Unlocking → Unlocked` | 主密码验证成功且密文配置匹配 | 可用 DEK 句柄仅存在于受管内存;专属数据库已打开;允许笔记本专用入口 | 撤销派生的 KEK/DEK 句柄、关闭已打开资源并回到 `Locked` |-| `Unlocked → Locking → Locked` | 原子地关闭新操作准入,并等待在途操作结束或取消 | 无可用受管 DEK 句柄或数据库连接;内核管理的明文缓存、临时文件与令牌已尽力清理 | 密钥和数据库清理完成后仍进入 `Locked`;临时文件清理失败只记录不含明文的诊断,并在退出或下次启动时重试 |-| `Unlocked → Error` | 密文认证失败、数据库打开失败或不变量被破坏 | 立即拒绝读写,绝不回退到普通笔记本路径 | 关闭资源,诊断信息不得含明文;用户只能锁定或重新解锁 |-| 改主密码 | 所有加密笔记本均为 `Locked` | 所有 WrappedDEK、全局配置和备份作为一个可恢复事务更新 | 保留旧配置和备份可用;不得出现仅能用新密码解锁的部分笔记本 |+持久化格式分层,不能把全局 KDF 配置、密钥包络和每个数据对象的封装混为一体:-每个笔记本使用同一个生命周期控制器管理状态、操作准入和活跃操作计数。读取、编辑、导出、预览、同步、索引、历史查看或恢复、AI/MCP 访问等操作只能在 `Unlocked` 时取得只读生命周期租约,并持有到解析完成、缓存发布、HTTP 响应或下载结束,以及异步结果登记完成。解锁并打开必须在同一个笔记本转换锁内完成;挂载失败只能回滚本次新建的解锁状态,不能锁定由其他并发请求已经使用的 DEK 或挂载。锁定与删除原子地把状态改为 `Locking` 并关闭新租约准入,然后取得排他租约,取消或等待所有在途操作,在排他租约内关闭数据库、撤销受管 DEK 句柄,并尽力清理缓存和临时产物。密钥句柄和数据库连接清理完成后发布 `Locked`;临时文件删除失败不阻止锁定,但必须记录诊断并在退出或下次启动时重试。因此锁定完成后不得再出现新的明文响应、缓存回填或数据库重连,但磁盘上可能保留清理失败的临时明文副本。+1. 数据对象封装:每个 `.sy`、资源和数据库定义对象至少包含格式标识或版本、算法标识、由操作系统 CSPRNG 生成的 96 位 nonce、密文和认证标签。当前格式的 AAD 按 `格式域 + boxID + 对象类型 + 稳定对象 ID` 确定性构造,不包含父目录或绝对路径;`.sy` 的稳定对象 ID 是规范化文件基名 `<rootID>.sy`,资源使用脱敏磁盘文件基名,数据库定义使用 avID,固定单例文件使用版本化常量 ID。资源的原始名称作为同一资源容器内的认证加密元数据保存。解密后必须验证对象内部 ID 与 AAD 对象 ID 一致,并拒绝同一笔记本内的重复对象 ID。随机源失败必须终止写入。nonce 唯一性依赖概率保证:当前实现没有跨重启、设备和备份恢复共享的持久化用途密钥调用计数,不能强制限制密钥整个生命周期的调用规模。这是现有限制,不代表可以无限量安全使用;后续实施强制限制需要版本化的多设备密钥生命周期与恢复方案,并保留现有数据的访问能力。认证标签不能事后识别已经发生的 nonce 重用,因此不得宣称此类重用会被认证失败自动发现-全局配置锁必须先于任何笔记本生命周期锁获取;同时涉及多个笔记本时按 boxID 字典序获取生命周期锁;DEK 缓存、数据库、文件和其他子系统锁只能在生命周期锁之后获取,并在释放生命周期锁前释放。禁止逆序获取,禁止持有子系统锁时回取全局配置锁或其他较低层级锁。自动锁定按每个笔记本保存活动时间,但当前工作区的一次认证用户交互或显式保活会统一刷新所有已解锁笔记本;计时采用系统时钟并由周期任务检查,系统时钟调整可能相应提前或推迟触发时间,自动锁定是便利性保护而不是精确的安全计时边界。+2. 全局密钥与包络元数据:`NotebookCrypto` 保存 KDF 算法、参数、MasterSalt、verifier 格式、KEK 包络版本和备份 HMAC 版本;`BoxConf.WrappedDEK` 保存每个笔记本的 DEK 包络。它们不随每个数据对象重复保存-## 18. 密文、密钥与数据库格式+3. 用途隔离:每个笔记本的 DEK 通过固定域分隔符派生文件内容、资源、数据库定义、content SQLCipher 和 blocktree SQLCipher 子密钥。资源名称元数据与内容分块共用资源子密钥,并通过不同的 AAD 后缀隔离;不要求为每一种对象再派生独立子密钥。KEK 可以直接用于 verifier、DEK 包络和备份 HMAC,这些用途由不同算法、版本化 AAD 或被认证的数据格式隔离;不得把 WrappedDEK 认证错误地归入 DEK 域-持久化格式分层,不能把全局 KDF 配置、密钥包络和每个数据对象的封装混为一体:+4. 数据库兼容信息:SQLCipher 版本、cipher 参数、索引类型和 schema 版本保存在受 SQLCipher 认证的 encrypted_index_meta 表中,复用索引前必须校验。content 与 blocktree 索引可重建;缺少兼容信息、参数不兼容或打开失败时关闭索引,在笔记本密钥、元数据及全部源文档认证通过后,可以重新创建两个索引并在挂载时填充。源文档认证失败时保留源密文和残留索引并报错,重建不得降低 cipher 参数或回退到明文 SQLite-1. **数据对象封装**:每个 `.sy`、资源和数据库定义对象至少包含格式标识或版本、算法标识、由操作系统 CSPRNG 生成的 96 位 nonce、密文和认证标签。当前格式的 AAD 按 `格式域 + boxID + 对象类型 + 稳定对象 ID` 确定性构造,不包含父目录或绝对路径;`.sy` 的稳定对象 ID 是规范化文件基名 `<rootID>.sy`,资源使用脱敏磁盘文件基名,数据库定义使用 avID,固定单例文件使用版本化常量 ID。资源的原始名称作为同一资源容器内的认证加密元数据保存。解密后必须验证对象内部 ID 与 AAD 对象 ID 一致,并拒绝同一笔记本内的重复对象 ID。随机源失败必须终止写入。nonce 唯一性依赖概率保证:当前实现没有跨重启、设备和备份恢复共享的持久化用途密钥调用计数,不能强制限制密钥整个生命周期的调用规模。这是现有限制,不代表可以无限量安全使用;后续实施强制限制需要版本化的多设备密钥生命周期与恢复方案,并保留现有数据的访问能力。认证标签不能事后识别已经发生的 nonce 重用,因此不得宣称此类重用会被认证失败自动发现。-2. **全局密钥与包络元数据**:`NotebookCrypto` 保存 KDF 算法、参数、MasterSalt、verifier 格式、KEK 包络版本和备份 HMAC 版本;`BoxConf.WrappedDEK` 保存每个笔记本的 DEK 包络。它们不随每个数据对象重复保存。-3. **用途隔离**:每个笔记本的 DEK 通过固定域分隔符派生文件内容、资源、数据库定义、content SQLCipher 和 blocktree SQLCipher 子密钥。资源名称元数据与内容分块共用资源子密钥,并通过不同的 AAD 后缀隔离;不要求为每一种对象再派生独立子密钥。KEK 可以直接用于 verifier、DEK 包络和备份 HMAC,这些用途由不同算法、版本化 AAD 或被认证的数据格式隔离;不得把 WrappedDEK 认证错误地归入 DEK 域。-4. **数据库兼容信息**:SQLCipher 版本、cipher 参数、索引类型和 schema 版本保存在受 SQLCipher 认证的 encrypted_index_meta 表中,复用索引前必须校验。content 与 blocktree 索引可重建;缺少兼容信息、参数不兼容或打开失败时关闭索引,在笔记本密钥、元数据及全部源文档认证通过后,可以重新创建两个索引并在挂载时填充。源文档认证失败时保留源密文和残留索引并报错,重建不得降低 cipher 参数或回退到明文 SQLite。-5. **改名与格式稳定性**:当前文档格式以稳定对象 ID 构造 AAD,已经冻结为兼容基线。已写入的无版本字段 `SYAE` 资源继续按旧格式读取,不得因升级第 2 版而要求用户删除或重建附件;写入统一使用第 2 版,读取不强制迁移磁盘或历史快照。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。未来修改信封、AAD 语义或密钥派生方式必须使用明确的格式版本,保留旧版认证读取路径,或在移除旧版读取前提供可恢复迁移。迁移必须先认证源数据,保留原始数据和匹配的恢复材料,失败或中断后仍可恢复;不得通过重置 MasterSalt、丢弃密钥或删除数据解决格式不兼容。未知格式、损坏或认证失败必须保留原文件并报错,不得回退到明文或绕过认证。每次格式变更都必须以受支持旧格式的样本验证受影响的读取、导出、历史、备份和恢复路径。+5. 改名与格式稳定性:当前文档格式以稳定对象 ID 构造 AAD,已经冻结为兼容基线。已写入的无版本字段 `SYAE` 资源继续按旧格式读取,不得因升级第 2 版而要求用户删除或重建附件;写入统一使用第 2 版,读取不强制迁移磁盘或历史快照。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。未来修改信封、AAD 语义或密钥派生方式必须使用明确的格式版本,保留旧版认证读取路径,或在移除旧版读取前提供可恢复迁移。迁移必须先认证源数据,保留原始数据和匹配的恢复材料,失败或中断后仍可恢复;不得通过重置 MasterSalt、丢弃密钥或删除数据解决格式不兼容。未知格式、损坏或认证失败必须保留原文件并报错,不得回退到明文或绕过认证。每次格式变更都必须以受支持旧格式的样本验证受影响的读取、导出、历史、备份和恢复路径SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副本都是受保护对象,必须放在受控目录并使用对应的用途密钥。锁定、崩溃恢复和历史快照必须枚举这些伴随文件;未加密 SQLite 页面、查询结果或诊断转储不得写入全局临时目录。-## 19. 备份、恢复与元数据策略+### 备份、恢复与元数据策略`data-crypto-backup.json` 是恢复材料而非秘密。文件带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC;主密码派生 KEK 后,HMAC 缺失或不匹配必须拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。@@ -408,25 +578,32 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明| 笔记本名称 | 是。笔记本列表与加密笔记本状态 API 在锁定时保留名称,以便用户识别要解锁的笔记本,因此笔记本名称不属于机密性保护边界 || 图标、排序、文档标题和数量、关系数量、标签、书签、历史与快照名称 | 锁定时默认不得暴露;若兼容性要求暴露,必须逐项在本表及界面中说明 |-## 20. 功能边界、临时明文与接口规则--加密笔记本中的资源文件不支持文字识别(OCR),与解锁状态无关。手动识别返回本地化的“不支持”提示,自动识别跳过加密笔记本资源;不得为这些资源生成 OCR 文本或写入全局 OCR 存储和搜索索引。--不支持的发布、闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。发布访问判定必须独立于锁定状态并优先于 `publishAccess.json`,已存在的发布配置不得使加密笔记本重新可见。错误码和本地化文案应稳定,供调用方识别。--拒绝操作时必须说明具体原因和可行的处理方式,不得用同一句笼统文案覆盖互不相关的原因:例如导入带闪卡的 `.sy.zip` 时,应指出命中闪卡的文档或牌组,并提示在源笔记本移除闪卡后重新导出或改为导入普通笔记本;未解锁时应提示解锁;跨加密边界移动或引用时应说明加密笔记本是隔离空间,而不是返回“不支持该操作”。+### 历史功能的安全设计-所有可能绕过专用读写路径的原始入口必须登记,包括文件 API、内核 CLI、MCP 文件工具、WebDAV、插件文件接口、导出下载 URL、预览 URL 和后台任务。加密笔记本的持久化目录始终拒绝原始入口直接访问,避免密文泄漏或绕过加密层写入;工作空间 `temp/` 是管理员文件 API、归档 API 和受信任插件可访问的通用临时空间,不属于加密访问控制边界。WebDAV 继续无条件拒绝整个 `temp/`,避免通过远程文件服务暴露临时数据。新增入口时必须分别评审其是否接触加密笔记本持久化目录或临时明文。+```+文件历史:+ 编辑触发历史生成 → 密文 .sy 原样拷到历史目录+ 关闭/退出前自动生成历史 → 确保锁定后定时器无法生成时不丢历史+ 历史索引 → content 留空(密文不进搜索索引)+ 查看历史 → 读取快照 boxID + 对象类型 + 稳定文件基名,以三者构造原 AAD 解密(需笔记本已解锁)+ 回滚 → 按快照 AAD 解密历史 → 校验根块 ID 与文件基名一致 → 加载 tree → 由 WriteTree 序列化恢复后的内容,并按目标文件基名重新封装-### 临时明文生命周期+已删除笔记本历史:+ 删除前 → 整个目录密文备份到历史目录+ 恢复 → 将密文目录原样拷回并保持关闭,解锁时再使用匹配的全局密钥备份和主密码验证 WrappedDEK+ 密钥保留 → 只要内核管理的该类历史仍可恢复,就禁止删除其依赖的全局密钥备份;永久清除历史后才解除依赖-导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物统一放在 `temp/export/<boxID>/<kind>/<exportID>/`。第一层 boxID 是清理归属标识,不是访问权限;普通导出和插件临时文件不得使用合法 boxID 作为 `temp/export/` 的第一层名称。+数据库历史:+ 生成 → 加密笔记本的数据库文件从笔记本级目录拷到历史目录+ 查看 → 按快照记录的 boxID 与对象用途/标识解密,不使用历史目录绝对路径作为 AAD+ 回滚 → 加密笔记本的数据库文件/资源回滚到笔记本级目录+```-内存态导出令牌 `managedEncryptedExports` 用于管理下载链接的有效期和生命周期,不作为本机文件、管理员 API 或受信任插件的安全隔离。锁定、删除、取消、失败和正常退出时必须撤销相关令牌,并尽力删除 `temp/export/<boxID>`;应用启动时至少扫描并删除第一层名称为合法 boxID 的残留目录,桌面端的通用临时目录初始化还会清空整个 `temp/export`。任何调用方都不得依赖 `temp/` 中的文件跨进程存续。删除失败只记录不含明文的诊断,不阻止笔记本进入 `Locked`,后续退出或启动时继续尝试。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。+历史文件在历史目录中的父路径不是 AAD 的组成部分。每个历史条目必须以不可歧义的规范格式保留快照写入时的 `boxID`、对象类型和稳定文件基名或对象标识;可由固定历史目录布局编码,也可由随快照提交的元数据记录。文档只改变父目录时 AAD 上下文保持不变;文件基名改变时,既有历史仍使用旧基名认证解密。回滚时先验证密文、文件基名与解密后对象 ID 一致,再按目标父目录恢复;文档回滚还会规范化树结构并处理重复块 ID,因此即使文件基名不变,也由 WriteTree 序列化恢复后的内容并生成新封装,历史源密文保持不变。已删除笔记本的目录拷回属于关闭状态的恢复,不代表当前密钥备份已匹配;认证在解锁时执行,缺少匹配备份时可在之后补充恢复材料。快照上下文缺失、格式不合法或与密文不匹配时必须拒绝查看和回滚,不得把密文当明文解析或使用当前文件基名替代快照基名。-移动端原生保存流程必须通过 `AcquireExportFile` 取得包含路径、名称、大小和租约 ID 的导出租约,在复制及校验完成后的 `finally` 路径调用 `ReleaseExportFile`;加密导出不得使用只返回路径或名称的旧接口,因为它们不能覆盖原生复制阶段的生命周期。+## 验证范围-## 21. 安全验收矩阵+### 安全验收矩阵| 场景 | 预期结果 ||---|---|@@ -451,76 +628,3 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明| 回放认证有效的历史密文或密钥备份 | 可能被识别为有效旧版本,但不得被宣称为最新或来源可信;数据回退风险明确,当前设计不声称提供回滚防护 || 改主密码和 KEK 重新包络 | WrappedDEK、历史 KEK 和备份通过可恢复事务更新;连续改密、删除笔记本、备份导入与迁移中断后仍可用当前密码恢复旧包络;旧密码暴露风险提示正确 || 多个笔记本并发操作与自动锁定 | 锁顺序无死锁;认证用户界面活动或显式保活统一刷新所有当前已解锁笔记本,后台任务不自动刷新;锁定中的笔记本不再接受新租约 |--## 22. 使用指南--### 首次启用-1. 进入 **设置 - 鉴权 - 加密笔记本**,打开开关-2. 设置主密码(双输入确认 + 风险确认)。主密码是所有加密笔记本的统一钥匙,**必须牢记——没有找回后门**-3. 启用后即可在文件面板「更多」菜单里 **新建加密笔记本**,输入名字和主密码后自动解锁并打开--> 强度建议:12 位以上,混合大小写 + 数字 + 符号。主密码越强,抗暴力破解能力越高(密码强度是唯一的安全防线,没有后门)。--### 日常使用:解锁与锁定-- **解锁**:点击已关闭的加密笔记本,输入主密码并等待约 1 秒(Argon2id 派生)后打开。解锁仅作用于该笔记本,其他加密笔记本保持锁定-- **锁定**:关闭该笔记本即等于锁定。内核停止新访问,等待或取消在途任务,撤销受管 DEK 句柄和数据库连接,并尽力清理内核管理的明文缓存、临时文件与令牌。**用完即锁**是最重要的安全习惯,能最大程度减少密钥和明文的暴露时间-- **重启后**:所有加密笔记本强制关闭,需重新输主密码解锁(受管 DEK 句柄只存在于进程内存,重启后需重新派生)--> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,获得主应用授权的调用方(API、插件、AI/LLM 含 MCP)能像读普通笔记本一样读到明文;发布服务的读者与匿名访问者以及内核 CLI 始终被拒绝(详见 §12 安全前提)。--### 修改主密码-进入 **设置 - 鉴权 - 加密笔记本 - 修改主密码**。改密会重新包络各笔记本的 WrappedDEK,并用新密码保护历史恢复密钥,**不重新加密文档数据**。改密后密钥备份会自动刷新并同步;使用当前备份和当前密码仍可恢复改密前的已删除笔记本历史。--> 重要语义:改密采用 KEK 包络模式——DEK 本身不变,只是用新主密码派生的新 KEK 重新包络 WrappedDEK。这意味着**改密不能吊销旧主密码的解密能力**:如果旧主密码和旧 WrappedDEK(如同步端、备份、历史快照中保留的)同时泄露,仍能解出同一个 DEK,进而解当前数据。如果怀疑旧主密码已泄露,应将内容导出为明文后导入新建的加密笔记本(新 DEK),确认迁移成功后安全删除明文文件,而非仅改密。--### 多设备同步-加密笔记本的密文 `.sy`/assets/数据库文件会随数据同步(密文进密文出,闭环自洽);全局密钥材料(MasterSalt 等)也会自动备份到同步目录。**新设备同步后无需手动"启用"**:--加密笔记本的打开状态不能跨设备继承。即使同步到本机的 `conf.json` 记录了其他设备上的打开状态,只要本机内存中没有该笔记本的 DEK,界面和内核都必须将其视为已关闭,并跳过索引;输入主密码后由本机完成解锁和挂载。--同步删除本机当前已挂载的加密笔记本时,内核必须在处理全量重建索引、退出早返回或界面刷新之前完成本机删除转换:关闭新操作准入、等待在途租约结束、清除 DEK 与挂载状态、删除专属索引数据库并完成全局索引清理。删除后的磁盘配置不再作为判断是否需要清理的依据。--1. 在新设备配置好相同的同步账号并完成同步-2. 同步会把密钥备份拉到本地,内核自动恢复"已启用"状态-3. 直接点击加密笔记本,输入主密码即可解锁使用--若新设备同步后笔记本仍显示锁定属正常——点开输主密码即可。--同步恢复可以校验备份完整性,但不能证明它是最新版本。请另外保留版本化的密钥备份;出现多个历史副本时,系统无法自动判定新鲜度,恢复前应由用户根据可信来源和时间信息确认版本。--### 导入与导出-- **导入**:支持导入 `.sy.zip` 和 Markdown,内容在落盘前自动用 DEK 加密,与手动创建的文档一致-- **导出**:与普通笔记本一致(需先解锁,导出明文)。`.sy.zip`、HTML、Word、PDF、Markdown 等格式均支持;锁定状态下拒绝导出-- **发布**:不支持。加密笔记本及其文档不会出现在发布服务中,解锁或设置发布密码也不能启用--### 忘记密码怎么办-**无法恢复**——这是设计使然(没有后门)。即使密文已同步到云端,没有主密码也解不开。**务必牢记主密码,建议使用密码管理器保存**。--### 密钥备份丢失的恢复-若 `conf/conf.json` 与同步目录里的密钥备份同时丢失(极端情况),重新启用加密笔记本会被拒绝并提示恢复备份文件。只要能从其他已同步的设备或之前导出的密钥文件找回 `data-crypto-backup.json`,可通过 `Disabled` 或 `RecoveryRequired` 状态下显示的「导入密钥」按钮导入,或手动放回 `<工作区>/data/.siyuan/` 后重新启用,即可用该密钥对应的主密码解锁。--恢复已删除加密笔记本的历史同样需要与其 WrappedDEK 匹配的全局密钥备份和主密码。只要仍要保留这类本地恢复能力,就不要永久清除其历史或匹配的密钥备份;禁用流程应在发现这类依赖时拒绝继续。--### 适合用加密笔记本的场景-- 隐私日记、财务记录、医疗信息-- 工作机密、商业方案、合同-- 担心设备遗失或被盗——加密后即使磁盘数据被恢复,没有主密码也只是密文--### 不适合用加密笔记本的场景-- 日常笔记、学习笔记(加密的额外开销不值得)-- 需要全局搜索的内容(加密笔记本不参与)-- 需要通过发布服务对外提供的内容(加密笔记本不支持发布)-- 需要跨笔记本块引的知识网络(禁止跨边界)-- 需要跨笔记本移动整理的文档(禁止跨边界)-- 需要跨笔记本镜像数据库的场景(禁止跨边界)-- 需要闪卡复习的内容(不支持)-- 需要书签/标签管理的内容(不支持)-- 不希望 AI/LLM 接触的内容(解锁后 AI 可读;若介意,需保持锁定)-- 大量大文件(assets 每次浏览都全量解密)--### 日常使用习惯建议-1. **主密码必须牢记**:忘记密码 = 数据永久不可恢复(没有后门)-2. **用完即锁**:减少 DEK 在内存的暴露时间-3. **不要把所有笔记都放加密笔记本**:只放真正敏感的-4. **主密码强度**:建议 12 位以上,混合大小写 + 数字 + 符号-5. **备份**:分别保留版本化的密文备份和匹配的密钥备份;主密码或全部匹配密钥备份丢失后,密文无法恢复diff --git a/docs/PINNED-DOCUMENTS.md b/docs/PINNED-DOCUMENTS.mdindex d07a570119..7a121b09d2 100644--- a/docs/PINNED-DOCUMENTS.md+++ b/docs/PINNED-DOCUMENTS.md@@ -1,46 +1,54 @@-# 文档树面板置顶区+# Pinned documents in the document tree-对应议题:https://github.com/siyuan-note/siyuan/issues/19401+[中文](PINNED-DOCUMENTS.zh-CN.md)-## 设计评审+Related issue: https://github.com/siyuan-note/siyuan/issues/19401-置顶区位于文档树面板顶部,以置顶文档为根展示真实子文档。根入口的顺序独立于文档层级和源文档排序;展开后的子文档直接使用源文档数据。桌面端和移动端共享置顶区实现,区域可折叠并限制最大高度,内部独立滚动。+## Feature scope-置顶区域默认隐藏,可通过文档面板 - 更多 - 置顶开启,界面显隐配置中的文档面板分组也可调整该开关,包括移动端。用户主动置顶文档成功后自动开启置顶区域并保存开关状态;置顶失败、取消置顶或同步收到置顶数据时不改变该开关。隐藏时不占用布局空间,不取消任何置顶,也不重置顺序或展开状态;重新显示后刷新源文档数据。区域显隐使用独立配置标识 `documentPanel.pinnedDocs`,与侧栏图标显隐及菜单项显隐分别保存,保留用户明确保存的显隐选择。+The pinned section appears at the top of the document tree panel and uses pinned documents as roots for their actual child documents. Root entry order is independent of document hierarchy and source-document sorting. Expanded children use source-document data directly. Desktop and mobile clients share the implementation. The section can collapse, has a maximum height, and scrolls independently.-| 操作 | 行为 |+## User interaction++The section is hidden by default. Enable it through Document panel - More - Pinned or the document-panel group in entry visibility settings, including on mobile. Successfully pinning a document explicitly enables the section and saves that setting. A failed pin, unpin, or incoming synchronized pin data does not change visibility. Hiding the section removes its layout space without unpinning documents or resetting order or expansion state. Showing it again refreshes source-document data. Visibility uses the independent configuration identifier `documentPanel.pinnedDocs`, separate from dock-icon and menu-item visibility, and preserves the user's saved choice.++| Operation | Behavior ||---|---|-| 菜单置顶 | 新入口放在最顶部;已置顶时同一菜单项切换为取消置顶 |-| 根层插入线拖放 | 创建或调整置顶入口,源文档位置不变 |-| 子文档之间插入线拖放 | 调整真实文档顺序,沿用现有排序冲突确认 |-| 拖放到文档行中部 | 移入真实文档,沿用现有移动校验 |-| 取消父文档置顶 | 只移除该根入口,单独置顶的子文档保留 |-| 重命名或移动 | 所有入口重新读取源文档,跨笔记本移动维护笔记本标识 |-| 关闭普通笔记本 | 保留不可用入口,允许取消置顶;当前会话保留已读取的标题,无法读取标题时显示文档 ID |-| 删除文档或笔记本 | 清理相关入口;读取列表时也过滤不存在的源文档 |-| 加密笔记本 | 不显示置顶操作,服务端拒绝新增,也不返回已有异常入口 |+| Pin from a menu | Insert the entry at the top; the same menu item becomes Unpin for an already pinned document |+| Drop on a root insertion line | Create or reorder a pinned entry without moving the source document |+| Drop between child documents | Reorder actual documents, using the existing sort-conflict confirmation |+| Drop in the middle of a document row | Move into the actual document, using existing move validation |+| Unpin a parent document | Remove only that root entry; independently pinned children remain |+| Rename or move | Reload the source document for every entry; cross-notebook moves maintain the notebook identifier |+| Close an ordinary notebook | Retain unavailable entries and allow unpinning; keep titles already read in the current session, or show the document ID when the title is unavailable |+| Delete a document or notebook | Remove related entries; list reads also filter missing source documents |+| Encrypted notebook | Hide the pin operation; the server rejects additions and filters any existing invalid entries |-根层的拖放提示使用插入线,行中部使用文档高亮,明确区分创建入口和移动源文档。移动到自身或后代的校验交由已有文档移动接口执行。子文档列表按照源文档的有效排序加载;置顶操作不写入 `sort.json`,不改变排序继承。+Root drops show an insertion line, while row-center drops highlight the document, distinguishing entry creation from source-document moves. Existing document-move APIs validate moves into the source itself or its descendants. Child lists use the source document's effective sort mode. Pinning does not write `sort.json` or change sort inheritance.-## 持久化与同步+## Data and storage-`data/storage/pinned-docs.json` 使用版本 1 格式:`{"version":1,"docs":[{"id":"文档 ID","notebook":"笔记本 ID"}]}`。数组顺序即根层顺序,仅保存标识,不缓存文档内容。文件进入现有数据同步和快照流程,服从工作区同步忽略规则;仅此文件发生同步变更时也刷新文档树面板。跨设备同时编辑沿用现有同步文件冲突处理机制。+`data/storage/pinned-docs.json` uses version 1: `{"version":1,"docs":[{"id":"document ID","notebook":"notebook ID"}]}`. Array order determines root order. Only identifiers are stored; document content is not cached. The file participates in existing data sync and snapshots and follows workspace sync ignore rules. A sync change to this file alone also refreshes the document tree panel. Concurrent edits across devices use existing file-sync conflict handling.-同一内核内的更新由互斥锁串行处理,接口接受相对位置操作,避免客户端提交整份旧列表覆盖其他窗口新增的入口。未知版本、错误结构或损坏文件返回错误并保留原文件。现有文档、加密、历史和备份格式均无变更。+A mutex serializes updates within one kernel. APIs accept relative-position operations so a stale full list from one window cannot overwrite entries added in another.-区域折叠和子树展开状态保存在本设备的浏览器存储中,不写入同步文件。不同置顶根下的同一子文档具有独立展开状态。+Section collapse and subtree expansion are stored in this device's browser storage rather than the synchronized file. The same child document under different pinned roots has independent expansion state.-## HTTP 接口+## Implementation and interfaces-两个接口均使用 POST,要求认证和管理员角色;写接口还检查只读状态。接口成功时 `code` 为 `0`,业务或参数错误为 `-1`。类型契约位于 `kernel/apicontract/`,生成声明同步到插件声明仓库。+Both endpoints use POST and require authentication and the administrator role. The write endpoint also checks read-only state. Success uses `code: 0`; business and parameter errors use `-1`. Type contracts reside in `kernel/apicontract/`, and generated declarations are synchronized to the plugin declaration repository.-| 接口 | 请求 | 成功数据 |+| Endpoint | Request | Success data ||---|---|---|-| `/api/filetree/getPinnedDocs` | 无需请求体 | 数组,每项包含 `id`、`notebook`、`name`、`path`、`icon`、`subFileCount`、`unavailable`、`childrenSortMode` |-| `/api/filetree/updatePinnedDocs` | `ids: string[]`、`action: "pin"或"unpin"`,可选 `targetID: string`、`after: boolean` | `null` |+| `/api/filetree/getPinnedDocs` | No request body required | Array of entries with `id`, `notebook`, `name`, `path`, `icon`, `subFileCount`, `unavailable`, and `childrenSortMode` |+| `/api/filetree/updatePinnedDocs` | `ids: string[]`, `action: "pin" or "unpin"`; optional `targetID: string` and `after: boolean` | `null` |++Without a target, pinning inserts at the top. With a target, it inserts before that entry, or after it when `after: true`. Unpinning ignores position parameters. Batch requests validate every source document before writing and produce no partial result on failure. Pinned subtrees continue to use existing document-list, move, and sort APIs without creating document copies.++## Compatibility and recovery-未指定目标时,置顶操作放到最顶部;指定目标时插入其前面,`after: true` 则插入其后面。取消置顶忽略位置参数。批量请求先校验所有源文档,失败时不写入部分结果。置顶区子树继续通过现有文档列表、移动和排序接口操作,不新增文档副本。+Unknown versions, invalid structures, and damaged files return errors and preserve the original file. Existing document, encryption, history, and backup formats remain unchanged.-## 验证范围+## Verification-回归覆盖入口去重和顺序、源排序不变、无效批量请求不产生部分更新、未知版本和损坏数据保留、关闭笔记本入口保留、加密笔记本拒绝和过滤、引用维护、同步路径纳入、根层与子树拖放分类、菜单目录及旧配置顺序迁移。接口测试使用真实处理函数检查响应契约,并执行已有接口兼容和路由覆盖测试。+Regression coverage includes deduplication and ordering, unchanged source sorting, invalid batches without partial updates, preservation of unknown or damaged data, closed-notebook entries, rejection and filtering of encrypted notebooks, reference maintenance, sync-path inclusion, root versus subtree drop classification, menu catalogs, and order migration for existing configuration. API tests exercise actual handlers against response contracts and run existing API compatibility and route-coverage tests.diff --git a/docs/PINNED-DOCUMENTS.zh-CN.md b/docs/PINNED-DOCUMENTS.zh-CN.mdnew file mode 100644index 0000000000..31cd454b22--- /dev/null+++ b/docs/PINNED-DOCUMENTS.zh-CN.md@@ -0,0 +1,54 @@+# 文档树面板置顶区++[English](PINNED-DOCUMENTS.md)++对应议题:https://github.com/siyuan-note/siyuan/issues/19401++## 功能范围++置顶区位于文档树面板顶部,以置顶文档为根展示真实子文档。根入口的顺序独立于文档层级和源文档排序;展开后的子文档直接使用源文档数据。桌面端和移动端共享置顶区实现,区域可折叠并限制最大高度,内部独立滚动。++## 用户交互++置顶区域默认隐藏,可通过文档面板 - 更多 - 置顶开启,界面显隐配置中的文档面板分组也可调整该开关,包括移动端。用户主动置顶文档成功后自动开启置顶区域并保存开关状态;置顶失败、取消置顶或同步收到置顶数据时不改变该开关。隐藏时不占用布局空间,不取消任何置顶,也不重置顺序或展开状态;重新显示后刷新源文档数据。区域显隐使用独立配置标识 `documentPanel.pinnedDocs`,与侧栏图标显隐及菜单项显隐分别保存,保留用户明确保存的显隐选择。++| 操作 | 行为 |+|---|---|+| 菜单置顶 | 新入口放在最顶部;已置顶时同一菜单项切换为取消置顶 |+| 根层插入线拖放 | 创建或调整置顶入口,源文档位置不变 |+| 子文档之间插入线拖放 | 调整真实文档顺序,沿用现有排序冲突确认 |+| 拖放到文档行中部 | 移入真实文档,沿用现有移动校验 |+| 取消父文档置顶 | 只移除该根入口,单独置顶的子文档保留 |+| 重命名或移动 | 所有入口重新读取源文档,跨笔记本移动维护笔记本标识 |+| 关闭普通笔记本 | 保留不可用入口,允许取消置顶;当前会话保留已读取的标题,无法读取标题时显示文档 ID |+| 删除文档或笔记本 | 清理相关入口;读取列表时也过滤不存在的源文档 |+| 加密笔记本 | 不显示置顶操作,服务端拒绝新增,也不返回已有异常入口 |++根层的拖放提示使用插入线,行中部使用文档高亮,明确区分创建入口和移动源文档。移动到自身或后代的校验交由已有文档移动接口执行。子文档列表按照源文档的有效排序加载;置顶操作不写入 `sort.json`,不改变排序继承。++## 数据与存储++`data/storage/pinned-docs.json` 使用版本 1 格式:`{"version":1,"docs":[{"id":"文档 ID","notebook":"笔记本 ID"}]}`。数组顺序即根层顺序,仅保存标识,不缓存文档内容。文件进入现有数据同步和快照流程,服从工作区同步忽略规则;仅此文件发生同步变更时也刷新文档树面板。跨设备同时编辑沿用现有同步文件冲突处理机制。++同一内核内的更新由互斥锁串行处理,接口接受相对位置操作,避免客户端提交整份旧列表覆盖其他窗口新增的入口。++区域折叠和子树展开状态保存在本设备的浏览器存储中,不写入同步文件。不同置顶根下的同一子文档具有独立展开状态。++## 实现与接口++两个接口均使用 POST,要求认证和管理员角色;写接口还检查只读状态。接口成功时 `code` 为 `0`,业务或参数错误为 `-1`。类型契约位于 `kernel/apicontract/`,生成声明同步到插件声明仓库。++| 接口 | 请求 | 成功数据 |+|---|---|---|+| `/api/filetree/getPinnedDocs` | 无需请求体 | 数组,每项包含 `id`、`notebook`、`name`、`path`、`icon`、`subFileCount`、`unavailable`、`childrenSortMode` |+| `/api/filetree/updatePinnedDocs` | `ids: string[]`、`action: "pin"或"unpin"`,可选 `targetID: string`、`after: boolean` | `null` |++未指定目标时,置顶操作放到最顶部;指定目标时插入其前面,`after: true` 则插入其后面。取消置顶忽略位置参数。批量请求先校验所有源文档,失败时不写入部分结果。置顶区子树继续通过现有文档列表、移动和排序接口操作,不新增文档副本。++## 兼容与恢复++未知版本、错误结构或损坏文件返回错误并保留原文件。现有文档、加密、历史和备份格式均无变更。++## 验证范围++回归覆盖入口去重和顺序、源排序不变、无效批量请求不产生部分更新、未知版本和损坏数据保留、关闭笔记本入口保留、加密笔记本拒绝和过滤、引用维护、同步路径纳入、根层与子树拖放分类、菜单目录及旧配置顺序迁移。接口测试使用真实处理函数检查响应契约,并执行已有接口兼容和路由覆盖测试。diff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 0000000000..0de423eef6--- /dev/null+++ b/docs/README.md@@ -0,0 +1,45 @@+# Documentation index and writing conventions++[中文](README.zh-CN.md)++## Documentation index++| Document | English | 中文 |+|---|---|---|+| Kernel API type contracts | [API-CONTRACTS.md](API-CONTRACTS.md) | [API-CONTRACTS.zh-CN.md](API-CONTRACTS.zh-CN.md) |+| On-demand asset downloads | [ASSET-DOWNLOAD.md](ASSET-DOWNLOAD.md) | [ASSET-DOWNLOAD.zh-CN.md](ASSET-DOWNLOAD.zh-CN.md) |+| Encrypted notebooks | [ENCRYPTED-NOTEBOOK.md](ENCRYPTED-NOTEBOOK.md) | [ENCRYPTED-NOTEBOOK.zh-CN.md](ENCRYPTED-NOTEBOOK.zh-CN.md) |+| Pinned documents | [PINNED-DOCUMENTS.md](PINNED-DOCUMENTS.md) | [PINNED-DOCUMENTS.zh-CN.md](PINNED-DOCUMENTS.zh-CN.md) |+| Tab blocks | [TAB-BLOCK.md](TAB-BLOCK.md) | [TAB-BLOCK.zh-CN.md](TAB-BLOCK.zh-CN.md) |+| Template manager | [TEMPLATE-MANAGER.md](TEMPLATE-MANAGER.md) | [TEMPLATE-MANAGER.zh-CN.md](TEMPLATE-MANAGER.zh-CN.md) |+| `.sy` file structure | [SY-FORMAT.md](SY-FORMAT.md) | [SY-FORMAT.zh-CN.md](SY-FORMAT.zh-CN.md) |+| Workspace file layout | [WORKSPACE.md](WORKSPACE.md) | [WORKSPACE.zh-CN.md](WORKSPACE.zh-CN.md) |++Public API documentation retains its existing language editions: [English](API.md), [中文](API.zh-CN.md), and [日本語](API.ja.md).++## Bilingual conventions++Except for public API documentation, maintain paired English `NAME.md` and Simplified Chinese `NAME.zh-CN.md` files, with a relative link to the other language below the title. Both editions use corresponding section order and matching interfaces, paths, fields, compatibility requirements, and verification scope. Update both when behavior changes; a short summary does not replace a full translation.++## Feature design structure++On-demand assets, encrypted notebooks, pinned documents, tab blocks, and template management use these second-level sections. Place topic-specific details under third-level headings within the appropriate section.++| Section | Content |+|---|---|+| Feature scope | Purpose, supported platforms, prerequisites, and unsupported use cases |+| User interaction | Entry points, operation results, state changes, and user-visible failures |+| Data and storage | Data model, persistence paths, identifiers, sync scope, and local state |+| Implementation and interfaces | Implementation rules, key entry points, permissions, concurrency, and API behavior |+| Compatibility and recovery | Existing-data support, version rules, failure preservation, interruption recovery, and security boundaries |+| Verification | Required checks for normal, error, concurrent, cross-platform, and existing-data scenarios |++API contract maintenance, file formats, and workspace layout are maintenance specifications or reference manuals. Organize them by topic rather than imposing the feature design structure.++## Style and formatting++Describe existing behavior objectively. Use “must” and “must not” for requirements, distinguishing supported behavior, limitations, and verification requirements. Avoid review history, staged progress reports, promotional conclusions, and repeated emphasis. State the scope of counts, versions, and performance values; refer to source code for API coverage that it determines directly.++Use code formatting for identifiers, fields, paths, and commands; tables for operation comparisons; and numbered lists for ordered steps. Separate UI navigation levels with ` - `. Use punctuation appropriate to each language. Keep each paragraph or list item on a single line without manual wrapping.++Editorial changes must not reduce authenticated-read or recovery guarantees for existing data. For encryption formats, keys, history, and backups, both editions must preserve the compatibility baseline, failure handling, and recovery-material requirements.diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.mdnew file mode 100644index 0000000000..2e667d93f0--- /dev/null+++ b/docs/README.zh-CN.md@@ -0,0 +1,45 @@+# 文档索引与写作约定++[English](README.md)++## 文档索引++| 文档 | English | 中文 |+|---|---|---|+| 内核接口类型契约 | [API-CONTRACTS.md](API-CONTRACTS.md) | [API-CONTRACTS.zh-CN.md](API-CONTRACTS.zh-CN.md) |+| 资源文件按需下载 | [ASSET-DOWNLOAD.md](ASSET-DOWNLOAD.md) | [ASSET-DOWNLOAD.zh-CN.md](ASSET-DOWNLOAD.zh-CN.md) |+| 加密笔记本 | [ENCRYPTED-NOTEBOOK.md](ENCRYPTED-NOTEBOOK.md) | [ENCRYPTED-NOTEBOOK.zh-CN.md](ENCRYPTED-NOTEBOOK.zh-CN.md) |+| 文档树面板置顶区 | [PINNED-DOCUMENTS.md](PINNED-DOCUMENTS.md) | [PINNED-DOCUMENTS.zh-CN.md](PINNED-DOCUMENTS.zh-CN.md) |+| 页签块 | [TAB-BLOCK.md](TAB-BLOCK.md) | [TAB-BLOCK.zh-CN.md](TAB-BLOCK.zh-CN.md) |+| 模板管理 | [TEMPLATE-MANAGER.md](TEMPLATE-MANAGER.md) | [TEMPLATE-MANAGER.zh-CN.md](TEMPLATE-MANAGER.zh-CN.md) |+| `.sy` 文件结构 | [SY-FORMAT.md](SY-FORMAT.md) | [SY-FORMAT.zh-CN.md](SY-FORMAT.zh-CN.md) |+| 工作区文件布局 | [WORKSPACE.md](WORKSPACE.md) | [WORKSPACE.zh-CN.md](WORKSPACE.zh-CN.md) |++公开 API 文档保留现有语言版本:[English](API.md)、[中文](API.zh-CN.md)、[日本語](API.ja.md)。++## 双语约定++除公开 API 文档外,文档以英文 `NAME.md` 和简体中文 `NAME.zh-CN.md` 成对维护,并在标题下提供另一语言的相对链接。两版使用对应的章节顺序,接口、路径、字段、兼容要求和验证范围保持一致。修改功能语义时同时更新两版,不以简写摘要替代完整译文。++## 功能设计文档结构++资源按需下载、加密笔记本、文档置顶、页签块和模板管理使用以下二级章节,专题细节放在对应章节的三级标题下。++| 章节 | 内容 |+|---|---|+| 功能范围 | 功能目的、适用平台、前提条件和不支持的范围 |+| 用户交互 | 入口、操作结果、状态变化和用户可见的失败行为 |+| 数据与存储 | 数据模型、持久化位置、标识、同步范围和本地状态 |+| 实现与接口 | 实现规则、关键调用入口、权限、并发及接口行为 |+| 兼容与恢复 | 已有数据支持、版本规则、失败保留、中断恢复和安全边界 |+| 验证范围 | 正常、异常、并发、跨端和旧数据场景的检查要求 |++接口契约维护、文件格式和工作区布局属于维护规范或参考手册,按主题组织章节,不套用功能设计结构。++## 文风与格式++使用客观陈述说明现有行为,使用「必须」「不得」表达约束,并明确区分支持能力、限制和验证要求。避免评审过程、阶段性进度、宣传性结论和重复强调。数量、版本和性能值需说明适用范围;可由源码直接确定的接口覆盖范围以源码为准。++标识、字段、文件路径和命令使用代码格式,操作对比使用表格,顺序步骤使用编号列表。界面导航层级使用 ` - ` 分隔。中文采用中文标点,英文采用英文标点;每个段落或列表项保持在单行,不手工折行。++整理文档不得缩减已有数据的认证读取和恢复保证。涉及加密格式、密钥、历史或备份时,中英文必须同时保留兼容基线、失败处理和恢复材料要求。diff --git a/docs/SY-FORMAT.md b/docs/SY-FORMAT.mdindex 19dcef94fe..deaf83bd89 100644--- a/docs/SY-FORMAT.md+++ b/docs/SY-FORMAT.md@@ -1,4 +1,6 @@-# SiYuan `.sy` File JSON Structure — AI Read/Write Guide+# SiYuan `.sy` File JSON Structure — Read/write reference++[中文](SY-FORMAT.zh-CN.md)> Canonical Spec baseline: `2` for ordinary documents, `3` for documents containing tabs, `4` for documents using table-cell rich text; compatible readers may upgrade older or missing versions.> Verified against samples: `20200825162036-4dx365o.sy` (formatting elements), `20200905090211-2vixtlf.sy` (block types).@@ -6,7 +8,7 @@> This guide describes plaintext `.sy` JSON in an ordinary notebook, or the decrypted AST of an unlocked encrypted notebook. An encrypted notebook's on-disk `.sy` file is ciphertext and must not be edited as JSON.> Companion document: [`WORKSPACE.md`](./WORKSPACE.md) covers the overall on-disk layout of the workspace (how notebooks, parent/child documents, and assets are organized); this document focuses on the **internal** JSON structure of a `.sy` file.-## 0. In one sentence+## 0. OverviewA plaintext `.sy` file is a Lute AST tree serialized to JSON. The root node is `NodeDocument`; the body is the recursively nested `Children` array. There is no separately maintained JSON Schema — the Lute `ast.Node` and `ListData` Go structs are the serialization source of truth. The tree contains the document AST and its IAL, while assets, AttributeView definitions, and rebuildable indexes live outside the tree.@@ -218,7 +220,7 @@ NodeList NodeList] }```-### 5.4 `ListData` fields in full (★ easiest to get wrong)+### 5.4 `ListData` fields in full| Field | Type (code) | JSON form | Meaning ||---|---|---|---|@@ -509,7 +511,7 @@ Samples:- Strikethrough **supports only double-tilde `~~x~~`**, not single-tilde `~x~` (`SetGFMStrikethrough1(false)`).- Backslash escape is **not** a `NodeTextMark` subtype: it maps to the separate `NodeBackslash` node and never appears as a `TextMarkType` value.-### 6.3 Styled inline text (★ must be paired)+### 6.3 Styled inline text: pairing rulesA `NodeTextMark` carrying color/effects (with `Properties.style`) **must be immediately followed by a** `NodeKramdownSpanIAL`, and the two must share the exact same style text:@@ -556,7 +558,7 @@ A `NodeTextMark` carrying color/effects (with `Properties.style`) **must be imme----## 7. base64 encoding convention (★ must-read)+## 7. base64 encoding convention| Field | Encoding | Example ||---|---|---|diff --git a/docs/SY-FORMAT.zh-CN.md b/docs/SY-FORMAT.zh-CN.mdindex 316dcbef55..2b7afc5829 100644--- a/docs/SY-FORMAT.zh-CN.md+++ b/docs/SY-FORMAT.zh-CN.md@@ -1,4 +1,6 @@-# SiYuan `.sy` 文件 JSON 结构规范 —— AI 读写指南+# SiYuan `.sy` 文件 JSON 结构规范:读写参考++[English](SY-FORMAT.md)> 规范写入基准:普通文档为 Spec `2`,包含页签的文档为 Spec `3`,使用表格单元格富文本的文档为 Spec `4`;兼容读取器可以升级旧版或缺少 `Spec` 的数据。> 核验样本:`20200825162036-4dx365o.sy`(排版元素)、`20200905090211-2vixtlf.sy`(内容块类型)。@@ -6,7 +8,7 @@> 本指南描述普通笔记本中的明文 `.sy` JSON,或已解锁加密笔记本的解密后 AST。加密笔记本磁盘上的 `.sy` 文件是密文,不能当作 JSON 直接编辑。> 配套文档:[`WORKSPACE.zh-CN.md`](./WORKSPACE.zh-CN.md) 讲工作区在磁盘上的整体布局(笔记本、父子文档、资源文件的组织方式);本文档专注 `.sy` 文件**内部**的 JSON 结构。-## 0. 一句话本质+## 0. 概述明文 `.sy` 文件是序列化为 JSON 的 Lute AST 树。根节点为 `NodeDocument`,正文是递归嵌套的 `Children` 数组。不存在单独维护的 JSON Schema;Lute 的 `ast.Node` 和 `ListData` Go 结构体是序列化格式的事实来源。树中保存文档 AST 及其 IAL,资源文件、属性视图定义和可重建索引则位于树外。@@ -218,7 +220,7 @@ NodeList NodeList] }```-### 5.4 `ListData` 字段全解(★ 最易踩坑)+### 5.4 `ListData` 字段全解| 字段 | 类型(代码) | JSON 表现 | 说明 ||---|---|---|---|@@ -508,7 +510,7 @@ NodeList NodeList- 删除线**仅支持双波浪 `~~x~~`**,不支持单波浪 `~x~`(`SetGFMStrikethrough1(false)`)。- 反斜杠转义不是 `NodeTextMark` 子类型:它对应独立的 `NodeBackslash` 节点,不会出现在 `TextMarkType` 取值中。-### 6.3 带样式的内联文本(★ 必须成对)+### 6.3 带样式的内联文本:配对规则带颜色/特效的 `NodeTextMark`(带 `Properties.style`)**后面必须紧跟一个** `NodeKramdownSpanIAL`,且二者 style 文本一致:@@ -555,7 +557,7 @@ NodeList NodeList----## 7. base64 编码约定(★ 必读)+## 7. base64 编码约定| 字段 | 编码 | 例 ||---|---|---|diff --git a/docs/TAB-BLOCK.md b/docs/TAB-BLOCK.mdindex fccd069ffd..8bd5d8bc8d 100644--- a/docs/TAB-BLOCK.md+++ b/docs/TAB-BLOCK.md@@ -2,11 +2,57 @@[中文](TAB-BLOCK.zh-CN.md)+Related issue: https://github.com/siyuan-note/siyuan/issues/17642++## Feature scope+A tab block groups content in a single container and switches between groups through top or left navigation. Each tab item is a container with its own block ID and can contain ordinary blocks and nested tab blocks.-Related issue: https://github.com/siyuan-note/siyuan/issues/17642+## User interaction++### Menus and editing++The block icon operates on the whole container. Block icon menu - Tabbed container contains the top and left layout choices, followed by a separator and Task. All three options display their selection indicators on the right. These entries and the separator are registered in the configurable menu catalog for visibility and ordering.++A title's context menu operates on that item. It offers copying a block reference and, when editable, renaming, duplication and deletion. Task items also offer Custom task status. The header has no separate More button. Whole-container conversion is available through block icon menu - Turn into, including unordered lists, ordered lists, task lists and super blocks.++Clicking a title selects its item. Double-clicking or choosing Rename edits rich text directly at the title location, reusing callout-title inline formatting, selection and IME handling. The navigation copy is display-only; saving and reverse parsing use the original title inside the item. Font colors and other inline styles remain title content; renaming does not first expose an encoded string for the user to edit. Finishing editing preserves navigation scroll position and hides the inline toolbar. A hidden title selection cannot open the toolbar at the top of the document.++A new tab block starts with two items, each containing an empty paragraph. Adding an item appends it, selects it and starts title editing. Navigation truncates long titles visually and shows a title tooltip on hover; stored text has no fixed character cutoff. Navigation and the add button cannot be selected as body text.++#### Task state++A single ASCII space in `tabs-task` means incomplete. `X` or `x` displays the completed icon; other supported single-character states display their exact character. Custom-state input uses task-list marker validation, accepting a single ASCII character other than square brackets. State is independent of title and selection and is saved and synced with the document.++Task in the block menu is a group toggle. It is checked if any direct item has `tabs-task`. Turning it off removes the attribute from every direct item; turning it on initializes all items as incomplete. A new item is an incomplete task whenever the group contains any task item. Moving between groups retains each item's state, so mixed groups remain possible and can be normalized through the group toggle.++Clicking a state icon does not select the tab or start renaming: incomplete becomes `X`, while any other state becomes a space. Right-clicking the icon or choosing Custom task status in the title menu edits the current item's state. The icon has no separate Task List tooltip.++#### List and super-block conversion-## Data model+List-to-tabs conversion affects only the current level. Each direct list item's first paragraph becomes its title, retaining the complete text, inline formatting, references, links, ID and attributes without duplicating it in the body. If the first block is not a paragraph, the title is empty and that block stays in the body. Nested lists and tabs are not flattened. Conversion selects the first tab.++Converting back places a separate title paragraph first, removes `tabs-title` and appends the body. A nonempty string title creates a new paragraph. Identical title and body text is not deduplicated. A list item containing only a title receives a body placeholder on conversion to tabs. Conversion back omits only a `tabs-placeholder` paragraph that is still empty and has no inline elements, user attributes or reference count.++Task-list conversion preserves incomplete, complete and custom states. Converting to a task list restores the current `tabs-task`; items without that attribute become incomplete. Conversion to an ordinary list removes the task attribute. Ordered lists restart at 1. Layout and selection are not retained as backups for reverse conversion.++Converting to a super block turns the container and its items into vertical super blocks, converts titles into paragraphs and retains container, item and body IDs. List and super-block conversions use ordinary editing transactions and support undo.++### Selection, navigation and dragging++In editable editors, explicit selection and selection triggered by search or block-reference navigation save `tabs-active-id` through the attribute API after queued editing transactions. Selection does not occupy the body undo stack or update body modification timestamps, but is written to disk and synced. Read-only pages, embedded previews, history previews and exported HTML allow temporary switching without saving selection.++When restoring position after refresh or restart, persisted selection takes precedence over a stale caret in a hidden item. Focus moves to the selected body without reusing the stale text offset. Explicit navigation to hidden content activates each containing tab. An incoming selection that would hide content currently being edited is deferred to avoid interrupting focus and IME composition.++Items use ordinary block-reference syntax, such as `((20260905120000-item001 'Tab title'))`, without a dedicated reference syntax. The target is the item ID, and navigation selects that item. Reference hover previews include the parent container for rendering. References and resources in string titles belong to the item; those in separate title paragraphs belong to the original paragraph ID.++Dragging a navigation title moves the entire item; dragging a body block moves content. Sorting previews move adjacent buttons out of the drop position, fade the dragged button and scroll near navigation edges, using the appropriate axis for each layout. Dropping commits one transaction; canceling or returning to the original position commits none. Cross-group moves update both groups in one transaction. Read-only targets and descendants of the dragged item reject drops.++Deleting the active item selects the next item if available, otherwise the previous one. Deleting the last item produces an empty paragraph. Ordinary text selection excludes hidden bodies; whole-container copying and deletion include every item. Backspace and Delete at body boundaries do not automatically merge adjacent items.++## Data and storage++### Data model| Node or attribute | Meaning || --- | --- |@@ -25,7 +71,7 @@ Canonical data contains at least one item and at least one body block per item,Moving preserves IDs. When copying, inserting templates, importing or restoring regenerates IDs, it also remaps `tabs-active-id` and internal block references and block links in titles; external references retain their targets. A standalone item is a valid editing fragment and receives a tab container when pasted into ordinary content. Internal Markdown round trips temporarily wrap such fragments and restore their original fragment identity afterward.-## Markdown syntax+### Markdown syntax```markdown::: tabs@@ -78,47 +124,9 @@ Body.Internal Markdown emits a separate title paragraph as the first paragraph, retaining `tabs-title="true"`, its ID and attributes. The `@tab` line then omits duplicate title text. Structured clipboard Markdown instead puts the complete title on the `@tab` line and omits the duplicate title paragraph.-## Menus and editing+## Implementation and interfaces-The block icon operates on the whole container. Block icon menu - Tabbed container contains the top and left layout choices, followed by a separator and Task. All three options display their selection indicators on the right. These entries and the separator are registered in the configurable menu catalog for visibility and ordering.--A title's context menu operates on that item. It offers copying a block reference and, when editable, renaming, duplication and deletion. Task items also offer Custom task status. The header has no separate More button. Whole-container conversion is available through block icon menu - Turn into, including unordered lists, ordered lists, task lists and super blocks.--Clicking a title selects its item. Double-clicking or choosing Rename edits rich text directly at the title location, reusing callout-title inline formatting, selection and IME handling. The navigation copy is display-only; saving and reverse parsing use the original title inside the item. Font colors and other inline styles remain title content; renaming does not first expose an encoded string for the user to edit. Finishing editing preserves navigation scroll position and hides the inline toolbar. A hidden title selection cannot open the toolbar at the top of the document.--A new tab block starts with two items, each containing an empty paragraph. Adding an item appends it, selects it and starts title editing. Navigation truncates long titles visually and shows a title tooltip on hover; stored text has no fixed character cutoff. Navigation and the add button cannot be selected as body text.--### Task state--A single ASCII space in `tabs-task` means incomplete. `X` or `x` displays the completed icon; other supported single-character states display their exact character. Custom-state input uses task-list marker validation, accepting a single ASCII character other than square brackets. State is independent of title and selection and is saved and synced with the document.--Task in the block menu is a group toggle. It is checked if any direct item has `tabs-task`. Turning it off removes the attribute from every direct item; turning it on initializes all items as incomplete. A new item is an incomplete task whenever the group contains any task item. Moving between groups retains each item's state, so mixed groups remain possible and can be normalized through the group toggle.--Clicking a state icon does not select the tab or start renaming: incomplete becomes `X`, while any other state becomes a space. Right-clicking the icon or choosing Custom task status in the title menu edits the current item's state. The icon has no separate Task List tooltip.--### List and super-block conversion--List-to-tabs conversion affects only the current level. Each direct list item's first paragraph becomes its title, retaining the complete text, inline formatting, references, links, ID and attributes without duplicating it in the body. If the first block is not a paragraph, the title is empty and that block stays in the body. Nested lists and tabs are not flattened. Conversion selects the first tab.--Converting back places a separate title paragraph first, removes `tabs-title` and appends the body. A nonempty string title creates a new paragraph. Identical title and body text is not deduplicated. A list item containing only a title receives a body placeholder on conversion to tabs. Conversion back omits only a `tabs-placeholder` paragraph that is still empty and has no inline elements, user attributes or reference count.--Task-list conversion preserves incomplete, complete and custom states. Converting to a task list restores the current `tabs-task`; items without that attribute become incomplete. Conversion to an ordinary list removes the task attribute. Ordered lists restart at 1. Layout and selection are not retained as backups for reverse conversion.--Converting to a super block turns the container and its items into vertical super blocks, converts titles into paragraphs and retains container, item and body IDs. List and super-block conversions use ordinary editing transactions and support undo.--## Selection, navigation and dragging--In editable editors, explicit selection and selection triggered by search or block-reference navigation save `tabs-active-id` through the attribute API after queued editing transactions. Selection does not occupy the body undo stack or update body modification timestamps, but is written to disk and synced. Read-only pages, embedded previews, history previews and exported HTML allow temporary switching without saving selection.--When restoring position after refresh or restart, persisted selection takes precedence over a stale caret in a hidden item. Focus moves to the selected body without reusing the stale text offset. Explicit navigation to hidden content activates each containing tab. An incoming selection that would hide content currently being edited is deferred to avoid interrupting focus and IME composition.--Items use ordinary block-reference syntax, such as `((20260905120000-item001 'Tab title'))`, without a dedicated reference syntax. The target is the item ID, and navigation selects that item. Reference hover previews include the parent container for rendering. References and resources in string titles belong to the item; those in separate title paragraphs belong to the original paragraph ID.--Dragging a navigation title moves the entire item; dragging a body block moves content. Sorting previews move adjacent buttons out of the drop position, fade the dragged button and scroll near navigation edges, using the appropriate axis for each layout. Dropping commits one transaction; canceling or returning to the original position commits none. Cross-group moves update both groups in one transaction. Read-only targets and descendants of the dragged item reject drops.--Deleting the active item selects the next item if available, otherwise the previous one. Deleting the last item produces an empty paragraph. Ordinary text selection excludes hidden bodies; whole-container copying and deletion include every item. Backspace and Delete at body boundaries do not automatically merge adjacent items.--## Rendering and layout+### Rendering and layout`NodeTabs` renders as `.tabs` with direct `.tab-item` children. Navigation lives in `.tabs-header.protyle-action` and has no content block ID. The original title is `.tab-item-title.callout-title` inside `.tab-item-info`; the body is `.tab-item-content`, without reusing the callout body class. During editing, `.tabs-title-editor` overlays the corresponding navigation button.@@ -126,7 +134,7 @@ The container uses a theme border and rounded corners. Top navigation scrolls hoNavigation provides `tablist`, `tab` and `tabpanel` semantics with independent DOM IDs for each rendering instance. Arrow keys, Home and End move navigation focus; Enter or Space activates an item. Title editing follows text-editing key handling. Hidden items continue receiving data updates, and becoming visible reprocesses size-dependent render nodes and databases.-## Indexing, export and format compatibility+### Indexing and exportTitles participate in full-text indexing, reference and resource scanning, dynamic anchor text and history differences. String titles use temporary inline trees; separate title paragraphs use ordinary paragraph processing without duplicate scanning. Block names take precedence over titles as reference anchor text. Headings inside tabs do not participate in document heading numbering, and folding does not cross item boundaries.@@ -134,9 +142,7 @@ Internal Markdown retains full structure and attributes. Structured output withHTML initially shows all content and hides inactive items only after interactive initialization succeeds. Printing, PDF and Word expand all items, including nested content.-Documents containing tab nodes use `Spec 3`; ordinary documents use `Spec 2`, and upgraded documents are not automatically downgraded. JSON readers reject unsupported future versions before parsing and repair. Import paths in old clients that bypass version checks do not have this protection and must not process new-format documents. Lute supplies the nodes and syntax, so both the generated frontend script and the kernel dependency must include that support. `kernel/go.mod` records the actual dependency version.--## Code entry points+### Code entry points| Area | Entry points || --- | --- |@@ -146,3 +152,11 @@ Documents containing tab nodes use `Spec 3`; ordinary documents use `Spec 2`, an| Block menu and configuration catalog | [`gutter/index.ts`](../app/src/protyle/gutter/index.ts), [`catalog.ts`](../app/src/config/entryVisibility/catalog.ts) || Kernel normalization and title traversal | [`treenode/tabs.go`](../kernel/treenode/tabs.go), [`model/tabs.go`](../kernel/model/tabs.go) || JSON format | [`SY-FORMAT.md`](SY-FORMAT.md) |++## Compatibility and recovery++Documents containing tab nodes use `Spec 3`; ordinary documents use `Spec 2`, and upgraded documents are not automatically downgraded. JSON readers reject unsupported future versions before parsing and repair. Import paths in old clients that bypass version checks do not have this protection and must not process new-format documents. Lute supplies the nodes and syntax, so both the generated frontend script and the kernel dependency must include that support. `kernel/go.mod` records the actual dependency version.++## Verification++Verify empty-container normalization, round trips for string titles and separate title paragraphs, selection repair, ID remapping during copying and import, and Markdown fences at different nesting depths. Editing checks cover title formatting, IME composition, task state, list and super-block conversion, undo, deletion of the last item, and moves across groups. UI checks cover top and left layouts, narrow-container fallback, keyboard navigation, temporary read-only selection, and updates to hidden items. Export checks cover structured and flattened Markdown, printing every item, title-resource scanning, and rejection of unsupported document versions.diff --git a/docs/TAB-BLOCK.zh-CN.md b/docs/TAB-BLOCK.zh-CN.mdindex 5ad11199b5..0724fbade5 100644--- a/docs/TAB-BLOCK.zh-CN.md+++ b/docs/TAB-BLOCK.zh-CN.md@@ -2,11 +2,57 @@[English](TAB-BLOCK.md)+关联问题:https://github.com/siyuan-note/siyuan/issues/17642++## 功能范围+页签块将多个内容分组放在同一容器内,通过顶部或左侧的标题导航切换显示。每个页签项都是具有独立块 ID 的容器,可包含普通块和嵌套页签块。-关联问题:https://github.com/siyuan-note/siyuan/issues/17642+## 用户交互++### 菜单与编辑++块标操作整个页签块。块标菜单 - 页签块包含“顶部页签”“左侧页签”,分隔线后为“任务”;三个选项的选中标记均位于右侧。这些入口及分隔线登记在可配置菜单目录中,支持显示和排序设置。++标题右键菜单作用于当前页签,提供复制块引用,以及可写状态下的重命名、创建副本、删除;任务页签另有“自定义任务状态”。标题栏没有独立的“更多”按钮。整组转换入口位于块标菜单 - 转换为,包括无序列表、有序列表、任务列表和超级块。++单击标题切页,双击或选择“重命名”直接在标题位置编辑富文本,复用提示块标题的行级格式、选区和输入法处理。导航中的标题副本只负责展示,保存和反向解析以页签项内的原始标题为准。字体颜色等样式属于标题内容,重命名不会先转换成供用户编辑的代码字符串。结束编辑保留页签栏滚动位置并隐藏行级工具栏,隐藏标题选区不能在文档顶部触发工具栏。++新建页签块默认包含两个页签,各有一个空段落。新增页签追加到组末尾、选中并进入标题编辑。长标题在导航中按宽度省略,悬浮显示标题提示;全文不截断为固定字符数。导航和新增按钮不可作为正文文字选中。++#### 任务状态++`tabs-task` 为一个 ASCII 空格时表示未完成,`X` 或 `x` 显示完成图标,其他受支持的单字符状态按原字符显示。自定义状态输入沿用任务列表标记校验,接受单个 ASCII 字符但不接受方括号。状态独立于标题和选中项,写入文档并同步。++块标菜单中的“任务”是整组开关:组内只要有一项具有 `tabs-task`,开关即显示选中;关闭时移除所有直属项的任务属性,开启时全部设为未完成。组内存在任务项时,新建页签也为未完成任务。跨组移动保留页签自身状态,因此混合组仍可能存在,整组开关可统一处理。++点击状态图标不会切页或进入重命名:未完成变为 `X`,其他状态变为空格。右键点击图标或使用标题菜单中的“自定义任务状态”可设置当前页签状态。状态图标不显示单独的“任务列表”悬浮提示。++#### 列表和超级块转换-## 数据模型+列表转页签只转换当前层级。每个直属列表项的首个段落成为标题,保留全文、行级格式、引用、链接、ID 和属性,不在正文中重复保留。首个块不是段落时使用空标题,原块保留在正文。子列表和嵌套页签不展开;转换后选中第一页。++转回列表时将独立标题段落移回首部,移除 `tabs-title`,正文接在后面;非空字符串标题生成新段落。标题与正文即使文字相同也不去重。只有标题的列表项转页签时会补正文落点,转回时仅省略仍为空且没有行级元素、用户属性或引用计数的 `tabs-placeholder` 段落。++任务列表转页签保留未完成、完成和自定义状态;转为任务列表时恢复当前 `tabs-task`,没有任务属性的项默认为未完成。转为普通列表移除任务属性。有序列表重新从 1 编号,布局和选择状态不作为反向转换的备份保存。++转换为超级块将页签容器和各页签项转换为纵向超级块,标题成为段落,保留原容器、页签项和正文 ID。列表转换及超级块转换通过普通编辑事务支持撤销。++### 选择、定位与拖动++可写编辑器的主动切换,以及搜索和块引用定位触发的切换,通过属性接口保存 `tabs-active-id`,并排在编辑事务之后。切页不占用正文撤销栈,不更新正文修改时间,但会落盘并同步。只读页面、嵌入预览、历史预览和导出 HTML 可临时切换,不写回选择。++刷新或重启恢复位置时,持久化的页签选择优先于隐藏页中的旧光标;焦点转到当前页正文,不复用过期文本偏移。主动定位隐藏内容时逐层激活所属页签。外部选择更新若会隐藏正在编辑的正文,延后界面切换,避免打断焦点和输入法组合。++页签项使用普通块引用语法,例如 `((20260905120000-item001 '页签标题'))`,不引入专用引用语法。引用目标是页签项 ID,定位时切到对应页签;引用悬浮预览补齐父页签容器以正常渲染。字符串标题的引用和资源归属于页签项,独立标题段落的引用和资源归属于其原段落 ID。++拖动导航标题移动整页,拖动正文块移动内容。排序预览让相邻按钮让出落点,淡化被拖动按钮,并在导航边缘自动滚动;横向和纵向布局使用相应方向。松开后提交一次事务,取消或拖回原位不提交。跨组移动在同一事务中调整两组状态,只读目标和自身后代不接受落入。++删除当前页优先选择后一个页签,否则选择前一个;删除最后一页转为空段落。普通文字选区不包含隐藏正文,整组块的复制和删除涵盖全部页签。正文边界的退格和删除不自动合并相邻页签。++## 数据与存储++### 数据模型| 节点或属性 | 含义 || --- | --- |@@ -25,7 +71,7 @@移动保留 ID。复制、模板插入、导入和恢复中重建 ID 时,同步映射 `tabs-active-id` 及标题中的内部块引用和块链接,外部引用保持原目标。独立页签项是合法编辑片段,粘贴到普通正文时补齐页签容器;片段经过内部 Markdown 转换时使用临时包装,并按片段身份恢复。-## Markdown 语法+### Markdown 语法```markdown::: tabs@@ -78,47 +124,9 @@ Linux 下的说明。独立标题段落在内部 Markdown 中作为首个段落输出,并保留 `tabs-title="true"`、ID 和属性;此时 `@tab` 行不重复标题文字。剪贴板的结构化 Markdown 则把完整标题放到 `@tab` 行,不再重复输出标题段落。-## 菜单与编辑+## 实现与接口-块标操作整个页签块。块标菜单 - 页签块包含“顶部页签”“左侧页签”,分隔线后为“任务”;三个选项的选中标记均位于右侧。这些入口及分隔线登记在可配置菜单目录中,支持显示和排序设置。--标题右键菜单作用于当前页签,提供复制块引用,以及可写状态下的重命名、创建副本、删除;任务页签另有“自定义任务状态”。标题栏没有独立的“更多”按钮。整组转换入口位于块标菜单 - 转换为,包括无序列表、有序列表、任务列表和超级块。--单击标题切页,双击或选择“重命名”直接在标题位置编辑富文本,复用提示块标题的行级格式、选区和输入法处理。导航中的标题副本只负责展示,保存和反向解析以页签项内的原始标题为准。字体颜色等样式属于标题内容,重命名不会先转换成供用户编辑的代码字符串。结束编辑保留页签栏滚动位置并隐藏行级工具栏,隐藏标题选区不能在文档顶部触发工具栏。--新建页签块默认包含两个页签,各有一个空段落。新增页签追加到组末尾、选中并进入标题编辑。长标题在导航中按宽度省略,悬浮显示标题提示;全文不截断为固定字符数。导航和新增按钮不可作为正文文字选中。--### 任务状态--`tabs-task` 为一个 ASCII 空格时表示未完成,`X` 或 `x` 显示完成图标,其他受支持的单字符状态按原字符显示。自定义状态输入沿用任务列表标记校验,接受单个 ASCII 字符但不接受方括号。状态独立于标题和选中项,写入文档并同步。--块标菜单中的“任务”是整组开关:组内只要有一项具有 `tabs-task`,开关即显示选中;关闭时移除所有直属项的任务属性,开启时全部设为未完成。组内存在任务项时,新建页签也为未完成任务。跨组移动保留页签自身状态,因此混合组仍可能存在,整组开关可统一处理。--点击状态图标不会切页或进入重命名:未完成变为 `X`,其他状态变为空格。右键点击图标或使用标题菜单中的“自定义任务状态”可设置当前页签状态。状态图标不显示单独的“任务列表”悬浮提示。--### 列表和超级块转换--列表转页签只转换当前层级。每个直属列表项的首个段落成为标题,保留全文、行级格式、引用、链接、ID 和属性,不在正文中重复保留。首个块不是段落时使用空标题,原块保留在正文。子列表和嵌套页签不展开;转换后选中第一页。--转回列表时将独立标题段落移回首部,移除 `tabs-title`,正文接在后面;非空字符串标题生成新段落。标题与正文即使文字相同也不去重。只有标题的列表项转页签时会补正文落点,转回时仅省略仍为空且没有行级元素、用户属性或引用计数的 `tabs-placeholder` 段落。--任务列表转页签保留未完成、完成和自定义状态;转为任务列表时恢复当前 `tabs-task`,没有任务属性的项默认为未完成。转为普通列表移除任务属性。有序列表重新从 1 编号,布局和选择状态不作为反向转换的备份保存。--转换为超级块将页签容器和各页签项转换为纵向超级块,标题成为段落,保留原容器、页签项和正文 ID。列表转换及超级块转换通过普通编辑事务支持撤销。--## 选择、定位与拖动--可写编辑器的主动切换,以及搜索和块引用定位触发的切换,通过属性接口保存 `tabs-active-id`,并排在编辑事务之后。切页不占用正文撤销栈,不更新正文修改时间,但会落盘并同步。只读页面、嵌入预览、历史预览和导出 HTML 可临时切换,不写回选择。--刷新或重启恢复位置时,持久化的页签选择优先于隐藏页中的旧光标;焦点转到当前页正文,不复用过期文本偏移。主动定位隐藏内容时逐层激活所属页签。外部选择更新若会隐藏正在编辑的正文,延后界面切换,避免打断焦点和输入法组合。--页签项使用普通块引用语法,例如 `((20260905120000-item001 '页签标题'))`,不引入专用引用语法。引用目标是页签项 ID,定位时切到对应页签;引用悬浮预览补齐父页签容器以正常渲染。字符串标题的引用和资源归属于页签项,独立标题段落的引用和资源归属于其原段落 ID。--拖动导航标题移动整页,拖动正文块移动内容。排序预览让相邻按钮让出落点,淡化被拖动按钮,并在导航边缘自动滚动;横向和纵向布局使用相应方向。松开后提交一次事务,取消或拖回原位不提交。跨组移动在同一事务中调整两组状态,只读目标和自身后代不接受落入。--删除当前页优先选择后一个页签,否则选择前一个;删除最后一页转为空段落。普通文字选区不包含隐藏正文,整组块的复制和删除涵盖全部页签。正文边界的退格和删除不自动合并相邻页签。--## 渲染与布局+### 渲染与布局`NodeTabs` 对应 `.tabs`,直属项为 `.tab-item`;导航位于 `.tabs-header.protyle-action`,没有内容块 ID。原始标题位于 `.tab-item-info` 内的 `.tab-item-title.callout-title`,正文位于 `.tab-item-content`,不复用提示块正文类。标题编辑时使用 `.tabs-title-editor` 覆盖到对应导航按钮位置。@@ -126,7 +134,7 @@ Linux 下的说明。导航提供 `tablist`、`tab`、`tabpanel` 语义,各渲染实例使用独立 DOM 标识。方向键、Home 和 End 移动导航焦点,Enter 或空格激活;标题编辑时按文本编辑规则处理。隐藏页继续接收数据更新,显示时重新处理依赖尺寸的渲染节点和数据库。-## 索引、导出与格式兼容+### 索引与导出标题参与全文索引、引用及资源扫描、动态锚文本和历史差异。字符串标题通过临时行级树处理,独立标题段落按普通段落处理,避免重复扫描。块命名优先于标题作为引用锚文本。页签内的标题块不参与文档标题编号,折叠不跨越页签项边界。@@ -134,9 +142,7 @@ Linux 下的说明。HTML 在初始化前显示全部内容,交互初始化成功后才隐藏未选中的页。打印、PDF 和 Word 展开全部页签,包括嵌套内容。-包含页签节点的文档使用 `Spec 3`,普通文档使用 `Spec 2`,已升级文档不自动降级。JSON 读取入口在解析和修复前拒绝不支持的未来版本。旧客户端中绕过版本检查的导入入口不具备这种保护,不能用于处理新格式文档。节点和语法由 Lute 提供,前端生成脚本与内核依赖需要包含对应能力;仓库实际依赖版本以 `kernel/go.mod` 为准。--## 代码入口+### 代码入口| 范围 | 入口 || --- | --- |@@ -146,3 +152,11 @@ HTML 在初始化前显示全部内容,交互初始化成功后才隐藏未选| 块标菜单及配置目录 | [`gutter/index.ts`](../app/src/protyle/gutter/index.ts)、[`catalog.ts`](../app/src/config/entryVisibility/catalog.ts) || 内核规范化和标题遍历 | [`treenode/tabs.go`](../kernel/treenode/tabs.go)、[`model/tabs.go`](../kernel/model/tabs.go) || JSON 格式 | [`SY-FORMAT.zh-CN.md`](SY-FORMAT.zh-CN.md) |++## 兼容与恢复++包含页签节点的文档使用 `Spec 3`,普通文档使用 `Spec 2`,已升级文档不自动降级。JSON 读取入口在解析和修复前拒绝不支持的未来版本。旧客户端中绕过版本检查的导入入口不具备这种保护,不能用于处理新格式文档。节点和语法由 Lute 提供,前端生成脚本与内核依赖需要包含对应能力;仓库实际依赖版本以 `kernel/go.mod` 为准。++## 验证范围++验证空容器规范化、标题内容与独立标题段落的往返转换、选中项修复、复制和导入时的 ID 重映射,以及不同嵌套深度的 Markdown 围栏。编辑检查标题格式、输入法组合、任务状态、列表和超级块转换、撤销、删除最后一页和跨组拖动。界面检查顶部与左侧布局、窄容器回退、键盘导航、只读临时切换和隐藏页更新。导出检查结构化与平铺 Markdown、全部页签的打印输出、标题资源扫描和不支持的文档版本拒绝。diff --git a/docs/TEMPLATE-MANAGER.md b/docs/TEMPLATE-MANAGER.mdindex 6d040ed3af..f1f41b1f0a 100644--- a/docs/TEMPLATE-MANAGER.md+++ b/docs/TEMPLATE-MANAGER.md@@ -1,30 +1,44 @@-# 模板管理+# Template manager-在编辑器的模板选择面板中点击模板条目的「模板管理」按钮,打开管理窗口并自动选中该模板;也可以从文档的「导出 - 模板」窗口进入。桌面端和浏览器端还可以从左上角主菜单直接打开模板管理,模板列表为空时也能使用。桌面、浏览器和移动端共用同一管理窗口;没有打开文档时仍可管理模板,选择预览上下文后才能预览。连接本地内核的桌面端在管理窗口提供「打开文件位置」,未选中项目时打开模板根目录。+[中文](TEMPLATE-MANAGER.zh-CN.md)-左侧以可折叠的文件夹树列出 `data/templates` 中的目录和 Markdown 文件,目录优先排列。搜索框匹配模板名称或完整路径,搜索结果自动展开父目录,清空搜索后恢复原来的展开状态。点击目录名称选中目录并展开或收起子项,右侧编辑内容和预览保持不变;选中目录后,新建模板或文件夹默认放入该目录,保存和预览仍作用于右侧正在编辑的模板。重命名只修改名称并保留父目录,跨目录移动使用目录选择器;已有目标不会被覆盖。新建、重命名和移动成功后清空搜索并展开目标的父目录。重命名或移动不会自动改写其他模板、笔记本配置或文档中引用的模板路径,需要相应调整。+## Feature scope-包含 `template.json` 的模板包目录不支持重命名或移动,以保留包身份和集市更新能力;包内模板仍可编辑。访问已有文件时保留原始文件名,不因单引号等合法字符而拒绝访问。+The template manager browses, edits, and organizes templates under `data/templates`, and previews template content using a selected document as context.-右侧使用纯文本框编辑源码。保存前会核对读取时的文件版本;如果同步或另一个窗口已经修改了文件,会拒绝覆盖,需要保留当前编辑内容并刷新后处理。切换文件、刷新或关闭窗口时,有未保存的修改会要求确认放弃。已有 Windows 换行的模板保存时继续使用 Windows 换行。+## User interaction-删除会直接移除选中的文件或整个目录及其内容,不再写入独立垃圾箱,此操作无法撤销。模板没有接入文件历史,不能依赖文件历史恢复。旧版本已经保留在 `data/templates/.trash/` 中的内容不会自动清理,该隐藏目录仍不出现在模板搜索和管理列表中。+Open the manager from a template entry's Template manager button in the editor's template picker to select that template automatically, or from a document's Export - Template dialog. Desktop and browser clients also provide an entry in the top-left main menu, available even when the template list is empty. Desktop, browser, and mobile clients share the same manager. Templates can be managed without an open document; preview requires selecting a context. On desktop clients connected to a local kernel, Open file location opens the selected item's location, or the template root when nothing is selected.-## 预览+### File management-点击「预览模板」执行当前文本框中的内容,无须先保存或插入文档。默认使用打开窗口时的文档或块作为上下文;「预览上下文」直接显示当前选择的名称、用途说明和文档选择控件,可以搜索并选择其他文档。此处搜索的是上下文文档,不是左侧模板列表。预览使用所选文档的标题、ID 等信息运行模板,不会修改该文档;标题、ID、路径和 SQL 查询等结果取决于所选上下文及当前数据。+The left pane displays a collapsible tree of directories and Markdown files under `data/templates`, with directories first. Search matches template names or full paths and expands parent directories of matches. Clearing search restores the previous expansion state. Clicking a directory selects it and toggles its children without changing the editor or preview. New templates and folders default to the selected directory, while Save and Preview still apply to the template being edited. Rename changes only the name and retains the parent directory; moving across directories uses a directory picker. Existing targets are not overwritten. Successful creation, rename, or move clears search and expands the target parent. Rename and move do not rewrite template paths referenced by other templates, notebook configuration, or documents; those references require corresponding updates.-预览使用现有只读渲染模式,不保存当前源码,也不提交文档树创建计划。预览区域使用编辑器的主题背景色,随明暗主题切换,不固定为白色。数据库预览仍使用表格展示,不能等同于实际插入后的全部交互效果。+Template package directories containing `template.json` cannot be renamed or moved, preserving package identity and marketplace updates. Templates inside a package remain editable. Existing files retain their original names and are not rejected because of valid characters such as single quotes.-使用 `createDocTree` 的模板会在预览区显示将创建的文档名称、层级和数量,即使模板没有正文,也能查看创建计划。+### Editing and saving-## 导出与文档属性+The right pane edits source in a plain text field. Saving checks the file version recorded when reading. If sync or another window changed the file, the manager rejects the overwrite; retain current edits and refresh before resolving the conflict. Switching files, refreshing, or closing asks for confirmation before discarding unsaved changes. Templates with Windows line endings retain them when saved.-导出窗口可以选择已有模板子目录。需要新目录时,可以先打开模板管理创建目录,关闭管理窗口后目录列表会刷新。成功导出后会在源文档中记住模板名称和存放目录,再次导出该文档或其中的标题子树时自动恢复;目录不存在时回退到模板根目录。重名但未确认覆盖、导出失败或取消导出时不会更新记忆。内部记忆属性不会写入导出的模板。+Deletion directly removes the selected file or directory and all its contents without writing to a separate trash folder. This cannot be undone. Templates do not participate in file history, so file history cannot restore them. Existing content under `data/templates/.trash/` is not automatically cleaned up, and that hidden directory remains absent from template search and management lists.-只有实际导出范围中包含数据库块时,导出窗口才显示数据库副本选项。文档其他标题范围、子文档或查询嵌入结果中的数据库不计入当前导出范围。+### Preview-文档顶层的独立 `template` 或 `siyuan-template` 代码块可以声明文档属性,例如:+Preview template runs the current editor content without saving it or inserting it into a document. The default context is the document or block used to open the manager. Preview context shows the selected name, an explanation of its purpose, and a document picker that can search for another context document. This search selects the context document, not templates in the left pane. Rendering uses the selected document's title, ID, and other information without modifying that document. Title, ID, path, and SQL results depend on the selected context and current data.++Preview uses existing read-only rendering. It neither saves source nor commits a document-tree creation plan. The preview background follows the editor theme in light and dark modes rather than using a fixed white background. Database previews use tables and do not reproduce every interaction available after insertion.++Templates using `createDocTree` display the planned document names, hierarchy, and count in the preview, including templates with no body.++## Data and storage++### Export memory and document attributes++The export dialog can select an existing template subdirectory. To create one, open the template manager; closing it refreshes the directory list. After a successful export, the source document remembers the template name and directory. Exporting that document or a heading subtree again restores them. A missing directory falls back to the template root. An unconfirmed name collision, failure, or cancellation does not update this memory. Internal memory attributes are omitted from exported templates.++The database-copy option appears only when the actual export range contains a database block. Databases in other heading ranges, child documents, or query-embed results do not count as part of that range.++A standalone top-level `template` or `siyuan-template` code block can declare document attributes:````markdown```template@@ -32,18 +46,28 @@```````-这种代码块的属性仍在原来的模板位置求值,完成渲染后再合并到文档根节点,因此可以引用跨代码块的条件分支、循环和模板定义中的局部变量。实际执行的显式声明优先,未执行的分支不会覆盖源文档属性;文档 ID 仍由导出流程维护,更新时间不导出。包含其他正文、条件语句或嵌套在容器中的属性代码块继续按普通模板内容导出,不进行属性提取。+These attributes are evaluated at their original template position and merged into the document root after rendering. They can therefore use local variables from conditional branches, loops, and template definitions spanning code blocks. Explicit declarations that actually execute take precedence; unexecuted branches do not override source attributes. The export flow continues to maintain document IDs, and update timestamps are not exported. Attribute blocks containing other body content or conditional statements, or nested in containers, remain ordinary template content without attribute extraction.++New exports preserve the original evaluation position of standalone attribute declarations in a code block marked `siyuan-template-doc-attrs-v1`. The renderer merges attributes and removes that block when parsing template results. Existing templates that declare document attributes directly at the end of the file remain supported without conversion.++## Implementation and interfaces++`POST /api/template/manage` requires administrator privileges and is unavailable in read-only mode. Supported `action` values are `list`, `read`, `write`, `mkdir`, `move`, and `remove`. `path` and `target` are relative to the template directory. Writing, moving, or deleting an existing item requires the `revision` returned when it was read. A new file uses an empty `revision` and must have a `.md` extension.++UI renaming reuses existing filename handling: ASCII slash `/` becomes full-width slash `/`, then the name is validated and combined with its original parent before calling `move`. The name is not interpreted as a path. Backslashes, colons, `.`, `..`, and other invalid names are rejected. New-template and new-folder paths retain `/` as the directory separator and do not apply this name conversion. `remove` validates path boundaries, symbolic links, and revisions before deleting, recursively for directories. Success returns `data: null` without a `recoveryPath`. Deletion creates no template file history and does not clean up existing hidden recovery directories.++`POST /api/template/render` accepts optional `content` in `mode: "preview"` to preview unsaved source. `path` still identifies the actual template file for resolving subtemplates in the same package. Other rendering modes reject `content`.-新导出的独立属性声明使用语言标记为 `siyuan-template-doc-attrs-v1` 的代码块保存原始求值位置;渲染器在解析模板结果时合并属性并移除该代码块。已有直接在文件末尾声明文档属性的模板继续受支持,无须转换文件。+`POST /api/template/docSaveAsTemplate` accepts an optional relative `directory`; omission retains the template-root default.-## 接口+`POST /api/template/getDocSaveAsTemplateInfo` takes a document or block `id` and returns the document's remembered template name and relative directory, plus whether the actual export range contains a database. A successful template export from the UI updates the owning document's name and directory memory through `docSaveAsTemplate`.-`POST /api/template/manage` 需要管理员权限,且只读模式不可用。`action` 支持 `list`、`read`、`write`、`mkdir`、`move` 和 `remove`。`path` 和 `target` 使用模板目录内的相对路径;写入、移动、删除已有项目需要提供读取时返回的 `revision`。新文件的 `revision` 为空,扩展名必须为 `.md`。+## Compatibility and recovery-界面的重命名复用现有文件名处理,将名称中的半角斜杠 `/` 自动转换为全角斜杠 `/`,再校验名称并与原父目录组合后调用 `move`,不会将名称解释为路径;反斜杠、冒号及 `.`、`..` 等非法名称仍被拒绝。新建模板和文件夹的存放路径保留 `/` 作为目录分隔符,不进行上述名称转换。`remove` 在完成路径边界、符号链接和版本校验后直接删除项目,目录递归删除;成功时 `data` 为 `null`,不再返回 `recoveryPath`。删除不生成模板文件历史,也不会清理已有的隐藏恢复目录。+Existing templates retain their original filenames, Windows line endings, and support for document attributes declared directly at the end of the file. New standalone attribute exports use `siyuan-template-doc-attrs-v1` to preserve evaluation position. Moving and renaming do not migrate external template references; callers must update those paths.-`POST /api/template/render` 在 `mode: "preview"` 下支持可选的 `content`,用于预览未保存的源码;`path` 仍指向实际模板文件,用于解析同包子模板。其他渲染模式不接受 `content`。+File-version conflicts preserve current editor content and reject overwrites. Deletion creates no file history and cannot be undone through the manager. Existing `data/templates/.trash/` content remains and is not automatically cleaned up.-`POST /api/template/docSaveAsTemplate` 支持可选的 `directory` 相对目录,省略时继续保存到模板根目录。+## Verification-`POST /api/template/getDocSaveAsTemplateInfo` 接收文档或块 `id`,返回该文档记忆的模板名称、相对目录,以及实际导出范围中是否包含数据库。应用界面的模板导出成功后,`docSaveAsTemplate` 会更新所属文档的名称和目录记忆。+Verify file-tree ordering, expansion state after search, target directories for creation and moves, valid filename access, package-directory protection, version conflicts, and unsaved-change confirmation. Preview checks cover unsaved source, context changes, read-only rendering, document-tree plans, and theme changes. Export checks cover directory fallback, memory updates only after success, database-range detection, attribute evaluation position, and old-template compatibility. Deletion checks cover path boundaries, symbolic links, revisions, and preservation of existing hidden recovery directories.diff --git a/docs/TEMPLATE-MANAGER.zh-CN.md b/docs/TEMPLATE-MANAGER.zh-CN.mdnew file mode 100644index 0000000000..1d5f680a6d--- /dev/null+++ b/docs/TEMPLATE-MANAGER.zh-CN.md@@ -0,0 +1,73 @@+# 模板管理++[English](TEMPLATE-MANAGER.md)++## 功能范围++模板管理用于浏览、编辑和整理 `data/templates` 中的模板,并以指定文档作为上下文预览模板内容。++## 用户交互++在编辑器的模板选择面板中点击模板条目的「模板管理」按钮,打开管理窗口并自动选中该模板;也可以从文档的「导出 - 模板」窗口进入。桌面端和浏览器端还可以从左上角主菜单直接打开模板管理,模板列表为空时也能使用。桌面、浏览器和移动端共用同一管理窗口;没有打开文档时仍可管理模板,选择预览上下文后才能预览。连接本地内核的桌面端在管理窗口提供「打开文件位置」,未选中项目时打开模板根目录。++### 文件管理++左侧以可折叠的文件夹树列出 `data/templates` 中的目录和 Markdown 文件,目录优先排列。搜索框匹配模板名称或完整路径,搜索结果自动展开父目录,清空搜索后恢复原来的展开状态。点击目录名称选中目录并展开或收起子项,右侧编辑内容和预览保持不变;选中目录后,新建模板或文件夹默认放入该目录,保存和预览仍作用于右侧正在编辑的模板。重命名只修改名称并保留父目录,跨目录移动使用目录选择器;已有目标不会被覆盖。新建、重命名和移动成功后清空搜索并展开目标的父目录。重命名或移动不会自动改写其他模板、笔记本配置或文档中引用的模板路径,需要相应调整。++包含 `template.json` 的模板包目录不支持重命名或移动,以保留包身份和集市更新能力;包内模板仍可编辑。访问已有文件时保留原始文件名,不因单引号等合法字符而拒绝访问。++### 编辑与保存++右侧使用纯文本框编辑源码。保存前会核对读取时的文件版本;如果同步或另一个窗口已经修改了文件,会拒绝覆盖,需要保留当前编辑内容并刷新后处理。切换文件、刷新或关闭窗口时,有未保存的修改会要求确认放弃。已有 Windows 换行的模板保存时继续使用 Windows 换行。++删除会直接移除选中的文件或整个目录及其内容,不再写入独立垃圾箱,此操作无法撤销。模板没有接入文件历史,不能依赖文件历史恢复。旧版本已经保留在 `data/templates/.trash/` 中的内容不会自动清理,该隐藏目录仍不出现在模板搜索和管理列表中。++### 预览++点击「预览模板」执行当前文本框中的内容,无须先保存或插入文档。默认使用打开窗口时的文档或块作为上下文;「预览上下文」直接显示当前选择的名称、用途说明和文档选择控件,可以搜索并选择其他文档。此处搜索的是上下文文档,不是左侧模板列表。预览使用所选文档的标题、ID 等信息运行模板,不会修改该文档;标题、ID、路径和 SQL 查询等结果取决于所选上下文及当前数据。++预览使用现有只读渲染模式,不保存当前源码,也不提交文档树创建计划。预览区域使用编辑器的主题背景色,随明暗主题切换,不固定为白色。数据库预览仍使用表格展示,不能等同于实际插入后的全部交互效果。++使用 `createDocTree` 的模板会在预览区显示将创建的文档名称、层级和数量,即使模板没有正文,也能查看创建计划。++## 数据与存储++### 导出记忆与文档属性++导出窗口可以选择已有模板子目录。需要新目录时,可以先打开模板管理创建目录,关闭管理窗口后目录列表会刷新。成功导出后会在源文档中记住模板名称和存放目录,再次导出该文档或其中的标题子树时自动恢复;目录不存在时回退到模板根目录。重名但未确认覆盖、导出失败或取消导出时不会更新记忆。内部记忆属性不会写入导出的模板。++只有实际导出范围中包含数据库块时,导出窗口才显示数据库副本选项。文档其他标题范围、子文档或查询嵌入结果中的数据库不计入当前导出范围。++文档顶层的独立 `template` 或 `siyuan-template` 代码块可以声明文档属性,例如:++````markdown+```template+{: icon="api/icon/getDynamicIcon?type=5&date=.action{now | date "2006-01-02"}" type="doc"}+```+````++这种代码块的属性仍在原来的模板位置求值,完成渲染后再合并到文档根节点,因此可以引用跨代码块的条件分支、循环和模板定义中的局部变量。实际执行的显式声明优先,未执行的分支不会覆盖源文档属性;文档 ID 仍由导出流程维护,更新时间不导出。包含其他正文、条件语句或嵌套在容器中的属性代码块继续按普通模板内容导出,不进行属性提取。++新导出的独立属性声明使用语言标记为 `siyuan-template-doc-attrs-v1` 的代码块保存原始求值位置;渲染器在解析模板结果时合并属性并移除该代码块。已有直接在文件末尾声明文档属性的模板继续受支持,无须转换文件。++## 实现与接口++`POST /api/template/manage` 需要管理员权限,且只读模式不可用。`action` 支持 `list`、`read`、`write`、`mkdir`、`move` 和 `remove`。`path` 和 `target` 使用模板目录内的相对路径;写入、移动、删除已有项目需要提供读取时返回的 `revision`。新文件的 `revision` 为空,扩展名必须为 `.md`。++界面的重命名复用现有文件名处理,将名称中的半角斜杠 `/` 自动转换为全角斜杠 `/`,再校验名称并与原父目录组合后调用 `move`,不会将名称解释为路径;反斜杠、冒号及 `.`、`..` 等非法名称仍被拒绝。新建模板和文件夹的存放路径保留 `/` 作为目录分隔符,不进行上述名称转换。`remove` 在完成路径边界、符号链接和版本校验后直接删除项目,目录递归删除;成功时 `data` 为 `null`,不再返回 `recoveryPath`。删除不生成模板文件历史,也不会清理已有的隐藏恢复目录。++`POST /api/template/render` 在 `mode: "preview"` 下支持可选的 `content`,用于预览未保存的源码;`path` 仍指向实际模板文件,用于解析同包子模板。其他渲染模式不接受 `content`。++`POST /api/template/docSaveAsTemplate` 支持可选的 `directory` 相对目录,省略时继续保存到模板根目录。++`POST /api/template/getDocSaveAsTemplateInfo` 接收文档或块 `id`,返回该文档记忆的模板名称、相对目录,以及实际导出范围中是否包含数据库。应用界面的模板导出成功后,`docSaveAsTemplate` 会更新所属文档的名称和目录记忆。++## 兼容与恢复++已有模板继续按原文件名读取,保留 Windows 换行及直接在文件末尾声明文档属性的旧写法。新导出的独立属性声明使用 `siyuan-template-doc-attrs-v1` 保存求值位置。移动和重命名不自动迁移外部模板引用,调用方需要同步调整引用路径。++文件版本冲突时保留当前编辑内容并拒绝覆盖。删除操作不生成文件历史,无法通过模板管理撤销;已有 `data/templates/.trash/` 内容继续保留且不自动清理。++## 验证范围++验证文件树排序、搜索后的展开状态、新建与移动的目标目录、合法文件名读取、模板包目录保护、版本冲突和未保存修改确认。预览检查未保存源码、上下文切换、只读渲染、文档树创建计划及主题切换。导出检查目录回退、成功后记忆、数据库范围判断、属性求值位置和旧模板兼容。删除检查路径边界、符号链接、版本校验及旧隐藏恢复目录保留。diff --git a/docs/WORKSPACE.md b/docs/WORKSPACE.mdindex 5680fd3f4f..f6027a96bb 100644--- a/docs/WORKSPACE.md+++ b/docs/WORKSPACE.md@@ -1,10 +1,12 @@-# SiYuan Workspace File-System Layout — Reference+# SiYuan Workspace File-System Layout++[中文](WORKSPACE.zh-CN.md)> This document describes how a SiYuan workspace is organized on disk.> It complements [`SY-FORMAT.md`](./SY-FORMAT.md): the latter covers the **internal** JSON structure of a `.sy` file, while this one covers the **overall** file-system layout of the workspace.> All conclusions are verified against a real workspace and the kernel source.-## 0. In one sentence+## 0. OverviewA SiYuan workspace is a **self-describing** directory tree: notebooks, documents, and assets live on disk as files and directories. **The filename is the ID; the directory structure is the document hierarchy.** The file system contains the authoritative source content, while SQLite databases under `temp/` are rebuildable indexes and caches. Normal-notebook content is readable directly; encrypted-notebook content is ciphertext and must be accessed through the unlocked kernel.@@ -81,7 +83,7 @@ The first level of `data/` mixes two kinds of entries:1. **Fixed data directories:** `.siyuan/`, `assets/`, `templates/`, `widgets/`, `plugins/`, `emojis/`, `snippets/`, `public/`, `storage/`.2. **Notebook directories:** each is a folder named with the notebook ID.-### Reserved-filename list (★ avoid when writing files)+### Reserved-filename list`IsReservedFilename`:@@ -109,7 +111,7 @@ That is, the physical path segments `assets` / `templates` / `widgets` / `emojis----## 4. Inside a notebook (★ core: parent-child document pairing)+## 4. Inside a notebook: parent-child document pairingThis is the single most important convention in the whole layout:@@ -238,7 +240,7 @@ Two coexisting locations:Asset-link prefix recognition: only `assets/`, `emojis/`, `plugins/`, `public/`, and `widgets/` are accepted as legal asset-link prefixes.-Encrypted notebooks must use notebook-local assets. Asset content and its original name reside in the same encrypted container, and physical filenames use a desensitized `<16-random-characters>-<blockID>.<ext>` form; direct inspection does not recover the original asset name. See [ENCRYPTED-NOTEBOOK.md §7](./ENCRYPTED-NOTEBOOK.md#7-sy--assets--database-file-encryption).+Encrypted notebooks must use notebook-local assets. Asset content and its original name reside in the same encrypted container, and physical filenames use a desensitized `<16-random-characters>-<blockID>.<ext>` form; direct inspection does not recover the original asset name. See [encrypted file formats](./ENCRYPTED-NOTEBOOK.md#sy--assets--database-file-encryption).---diff --git a/docs/WORKSPACE.zh-CN.md b/docs/WORKSPACE.zh-CN.mdindex d57e9fc7da..8935130d35 100644--- a/docs/WORKSPACE.zh-CN.md+++ b/docs/WORKSPACE.zh-CN.md@@ -1,10 +1,12 @@-# SiYuan 工作区文件系统布局 —— 参考文档+# SiYuan 工作区文件系统布局++[English](WORKSPACE.md)> 本文档描述 SiYuan 工作区在磁盘上的目录与文件组织。> 它与 [`SY-FORMAT.zh-CN.md`](./SY-FORMAT.zh-CN.md) 互补:后者讲 `.sy` 文件**内部**的 JSON 结构,本文档讲工作区**整体**在文件系统中的布局。> 所有结论基于真实工作区与内核代码核验。-## 0. 一句话本质+## 0. 概述SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源文件以文件或目录形式存在磁盘上。**文件名即 ID,目录结构即文档层级**。文件系统保存权威的原始内容,`temp/` 下的 SQLite 数据库则是可重建的索引和缓存。普通笔记本内容可以直接读取;加密笔记本内容以密文落盘,必须通过已解锁的内核访问。@@ -81,7 +83,7 @@ SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源1. **固定数据目录**:`.siyuan/`、`assets/`、`templates/`、`widgets/`、`plugins/`、`emojis/`、`snippets/`、`public/`、`storage/`。2. **笔记本目录**:每个是一个以笔记本 ID 命名的文件夹。-### 保留文件名清单(★ AI 落盘时务必避开)+### 保留文件名清单`IsReservedFilename`:@@ -109,7 +111,7 @@ func IsReservedFilename(baseName string) bool {----## 4. 笔记本内部布局(★ 核心:父子文档配对)+## 4. 笔记本内部布局:父子文档配对这是整个布局最关键的约定:@@ -238,7 +240,7 @@ data/<boxID>/资源文件链接前缀识别:仅认 `assets/`、`emojis/`、`plugins/`、`public/`、`widgets/` 这几个前缀为合法资源文件链接。-加密笔记本必须使用笔记本本地资源文件。资源内容和原始名称存放在同一个加密容器中,物理文件名采用脱敏的 `<16 位随机字符>-<blockID>.<ext>` 格式,因此直接检查磁盘无法还原原始资源文件名称。详见 [ENCRYPTED-NOTEBOOK.zh-CN.md §7](./ENCRYPTED-NOTEBOOK.zh-CN.md#7-sy--assets--数据库文件加解密)。+加密笔记本必须使用笔记本本地资源文件。资源内容和原始名称存放在同一个加密容器中,物理文件名采用脱敏的 `<16 位随机字符>-<blockID>.<ext>` 格式,因此直接检查磁盘无法还原原始资源文件名称。详见 [加密文件格式](./ENCRYPTED-NOTEBOOK.zh-CN.md#sy--assets--数据库文件加解密)。---