Skip to content

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

:lock: Harden encrypted notebook lifecycle and recovery https://github.com/siyuan-note/siyuan/issues/18034

Daniel37820739f20d
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 93f302f18e..f9ae2bf739 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -324,7 +324,8 @@ const editKeydown = (app: App, event: KeyboardEvent) => {
event.preventDefault();
return true;
}
- if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition.custom, event) && !window.siyuan.config.readonly) {
+ if (!isFileFocus && matchHotKey(window.siyuan.config.keymap.editor.general.spaceRepetition.custom, event) &&
+ !window.siyuan.config.readonly && !isEncryptedBox(protyle.notebookId)) {
fetchPost("/api/riff/getTreeRiffDueCards", {rootID: protyle.block.rootID}, (response) => {
openCardByData(app, response.data, "doc", protyle.block.rootID, protyle.title?.editElement.textContent || window.siyuan.languages.untitled);
});
diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.ts
index 65080a4065..21a6979954 100644
--- a/app/src/config/tabs/accessTab.ts
+++ b/app/src/config/tabs/accessTab.ts
@@ -417,11 +417,10 @@ const mountEncryptedNotebook = (root: HTMLElement) => {
const migrationAlertElement = root.querySelector("#encryptedNotebookMigrationAlert");
const refresh = () => {
fetchPost("/api/notebook/getEncryptedNotebookStatus", {}, (response) => {
- const enabled = response.data.enabled;
+ const enabled = response.data.state === "Enabled";
switchElement.checked = enabled;
window.siyuan.config.notebookCrypto.enabled = enabled;
- // 修改主密码/导出密钥仅在启用时可见;导入密钥仅在未启用时可见(详见设计 §4.1,
- // 已启用时导入会用导入备份的 MasterSalt/KEKVerifier 覆盖当前配置,孤立现有 WrappedDEK)
+ // 修改主密码和导出密钥仅在配置完整时可见;Disabled 或 RecoveryRequired 状态提供导入恢复入口。
enabledActionsElement.classList.toggle("fn__none", !enabled);
importCryptoBackupBtnElement.classList.toggle("fn__none", enabled);
actionsElement.classList.remove("fn__none");
diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.ts
index 7469024283..002e9a7b1a 100644
--- a/app/src/menus/navigation.ts
+++ b/app/src/menus/navigation.ts
@@ -118,7 +118,7 @@ const initMultiMenu = (selectItemElements: NodeListOf<Element>, app: App) => {
return window.siyuan.menus.menu;
}
window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);
- if (!window.siyuan.config.readonly) {
+ if (!window.siyuan.config.readonly && !isEncryptedBox(notebookId)) {
const riffCardMenu = [{
id: "quickMakeCard",
iconHTML: "",
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 25c9d2b604..eb615fcd0f 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -546,6 +546,8 @@ interface INotebook {
flashcardCount?: string;
sortMode: number;
encrypted?: boolean;
+ unlocked?: boolean;
+ state?: "Locked" | "Unlocking" | "Unlocked" | "Locking" | "Error";
}
interface ISiyuan {
diff --git a/app/src/util/mount.ts b/app/src/util/mount.ts
index 3342705bb3..8a3daf0c51 100644
--- a/app/src/util/mount.ts
+++ b/app/src/util/mount.ts
@@ -211,7 +211,7 @@ export const newNotebook = () => {
export const newEncryptedNotebook = () => {
// 先检查加密功能是否已启用;未启用则提示去设置页启用
fetchPost("/api/notebook/getEncryptedNotebookStatus", {}, (response) => {
- if (!response.data.enabled) {
+ if (response.data.state !== "Enabled") {
showMessage(window.siyuan.languages.encryptedNotebookTip, 6000);
return;
}
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index 7f360078a5..4cce9245f3 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -107,14 +107,14 @@ MasterSalt is the global root of KEK derivation — the master password + Master
**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 |
|---|---|---|
| Export key | Shown when enabled | Copies `notebook-crypto-backup.json` to the export directory for download; the user keeps it (API: `/api/notebook/exportNotebookCryptoBackup`) |
-| Import key | Shown when not enabled | Uploads a local backup file; after validation it is written back to `<DataDir>/.siyuan/` and the local config is restored (`Enabled=true`). Use the master password matching that key to unlock afterwards (API: `/api/notebook/importNotebookCryptoBackup`) |
+| Import key | Shown in `Disabled` or `RecoveryRequired` | Uploads a local backup file; after validation it is written back to `<DataDir>/.siyuan/` and the local config is restored (`Enabled=true`). Use the master password matching that key to unlock afterwards (API: `/api/notebook/importNotebookCryptoBackup`) |
-Import guard: when the local machine is already enabled, import is rejected (to avoid overwriting the existing salt and orphaning WrappedDEKs); the import entry is shown only when not enabled. The backup file itself does not contain the master password (salt is not secret, verifier is ciphertext), so export/import does not leak plaintext data; unlocking still requires the master password.
+Import 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.
@@ -266,6 +266,7 @@ Encrypted notebooks forbid moving documents across the encrypted boundary (norma
- `.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)
@@ -397,6 +398,8 @@ Exports have two classes: a user-selected external destination may contain plain
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.
+
## 21. Security Acceptance Matrix
| Scenario | Expected result |
@@ -459,7 +462,7 @@ Sync recovery can validate backup integrity but cannot prove that a backup is th
**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 `notebook-crypto-backup.json` from another synced device or a previously exported key file, you can import it via the "Import key" button (shown when not enabled), or manually put it back at `<workspace>/data/.siyuan/` and re-enable, then unlock with the master password matching that key.
+If both `conf/conf.json` and the key backup in the sync directory are lost (an extreme case), re-enabling the encrypted-notebook feature will be rejected with a prompt to restore the backup file. As long as you can recover `notebook-crypto-backup.json` from another synced device or a previously exported key file, you can import it via the "Import key" button shown 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.
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 94e56958e0..2c8dec2eab 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -107,14 +107,14 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
**配置恢复 vs 密钥恢复分离**:配置恢复只需读备份文件、装回 salt/verifier(不需主密码,因 salt 不保密、没主密码仍解不开数据);密钥恢复才需主密码派生 KEK 并校验 verifier。这让同步/导入后能自动进入"已启用"状态,用户输主密码即可解锁。
-**手动导出/导入密钥**:除自动同步外,用户可在 **设置 → 鉴权 → 加密笔记本** 手动导出/导入密钥备份,作为同步之外的独立恢复途径(如同步不可用、跨账号迁移、物理离线转存)。
+**手动导出与导入密钥**:除自动同步外,用户可在 **设置 - 鉴权 - 加密笔记本** 手动导出与导入密钥备份,作为同步之外的独立恢复途径(如同步不可用、跨账号迁移、物理离线转存)。
| 操作 | 入口 | 说明 |
|---|---|---|
| 导出密钥 | 已启用状态下显示 | 把 `notebook-crypto-backup.json` 复制到 export 目录供下载,用户自行保管(API:`/api/notebook/exportNotebookCryptoBackup`) |
-| 导入密钥 | 未启用状态下显示 | 选本地备份文件上传,校验合法后写回 `<DataDir>/.siyuan/` 并装回本机配置(`Enabled=true`)。后续用该密钥对应的主密码解锁(API:`/api/notebook/importNotebookCryptoBackup`) |
+| 导入密钥 | `Disabled` 或 `RecoveryRequired` 状态下显示 | 选本地备份文件上传,校验合法后写回 `<DataDir>/.siyuan/` 并装回本机配置(`Enabled=true`)。后续用该密钥对应的主密码解锁(API:`/api/notebook/importNotebookCryptoBackup`) |
-导入防呆:本机已启用时拒绝导入(避免覆盖现有 salt 孤立 WrappedDEK),导入入口仅在未启用时露出。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出/导入不涉及明文数据泄漏,解锁仍需主密码。
+导入防呆:完整的 `Enabled` 配置拒绝导入,避免覆盖现有 salt 并孤立 WrappedDEK;`RecoveryRequired` 仅在候选密钥通过认证且能解开全部现存加密笔记本及内核可枚举的已删除笔记本历史依赖时允许导入。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出和导入不涉及明文数据泄漏,解锁仍需主密码。
**防呆守卫**:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的笔记本)或内核可枚举的加密恢复数据时,**禁止重新生成 MasterSalt**(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。`DisableEncryptedNotebook` 对称地扫描现存笔记本、已删除笔记本历史和本地恢复快照;存在依赖时必须拒绝禁用,除非用户明确选择永久清除这些恢复数据。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。
@@ -266,6 +266,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
- `.sy` 文档正文(已加密)
- assets 二进制文件(已加密)
- assets 文件名(脱敏,原始名加密存储)
+- 笔记本图标、列表排序权重和排序方式(保存在 `BoxCrypt.Metadata` 的认证密文中)
- 数据库文件(列/行/cell 值/视图配置/内容快照,已加密)
- content SQLite 数据库(blocks/FTS/attributes/refs,SQLCipher 加密)
- blocktree SQLite 数据库(块树元数据:ID/路径/标题,SQLCipher 加密)
@@ -397,6 +398,8 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
内存态导出令牌 `managedEncryptedExports` 用于管理下载链接的有效期和生命周期,不作为本机文件、管理员 API 或受信任插件的安全隔离。锁定、删除、取消、失败和正常退出时必须撤销相关令牌,并尽力删除 `temp/export/<boxID>`;应用启动时至少扫描并删除第一层名称为合法 boxID 的残留目录,桌面端的通用临时目录初始化还会清空整个 `temp/export`。任何调用方都不得依赖 `temp/` 中的文件跨进程存续。删除失败只记录不含明文的诊断,不阻止笔记本进入 `Locked`,后续退出或启动时继续尝试。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。
+移动端原生保存流程必须通过 `AcquireExportFile` 取得包含路径、名称、大小和租约 ID 的导出租约,在复制及校验完成后的 `finally` 路径调用 `ReleaseExportFile`;加密导出不得使用只返回路径或名称的旧接口,因为它们不能覆盖原生复制阶段的生命周期。
+
## 21. 安全验收矩阵
| 场景 | 预期结果 |
@@ -459,7 +462,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
**无法恢复**——这是设计使然(没有后门)。即使密文已同步到云端,没有主密码也解不开。**务必牢记主密码,建议使用密码管理器保存**。
### 密钥备份丢失的恢复
-若 `conf/conf.json` 与同步目录里的密钥备份同时丢失(极端情况),重新启用加密笔记本会被拒绝并提示恢复备份文件。只要能从其他已同步的设备或之前导出的密钥文件找回 `notebook-crypto-backup.json`,可通过未启用状态下显示的"导入密钥"按钮导入,或手动放回 `<工作区>/data/.siyuan/` 后重新启用,即可用该密钥对应的主密码解锁。
+若 `conf/conf.json` 与同步目录里的密钥备份同时丢失(极端情况),重新启用加密笔记本会被拒绝并提示恢复备份文件。只要能从其他已同步的设备或之前导出的密钥文件找回 `notebook-crypto-backup.json`,可通过 `Disabled` 或 `RecoveryRequired` 状态下显示的「导入密钥」按钮导入,或手动放回 `<工作区>/data/.siyuan/` 后重新启用,即可用该密钥对应的主密码解锁。
恢复已删除加密笔记本的历史同样需要与其 WrappedDEK 匹配的全局密钥备份和主密码。只要仍要保留这类本地恢复能力,就不要永久清除其历史或匹配的密钥备份;禁用流程应在发现这类依赖时拒绝继续。
diff --git a/docs/WORKSPACE.md b/docs/WORKSPACE.md
index e35ede56ea..d620ee0e13 100644
--- a/docs/WORKSPACE.md
+++ b/docs/WORKSPACE.md
@@ -182,6 +182,8 @@ The `BoxConf` struct:
| `encrypted` | bool | Whether this is an encrypted notebook |
| `boxCrypt` | object or null | Wrapped notebook data-encryption key and envelope metadata; non-null for encrypted notebooks |
+An encrypted notebook still stores its name, closed state, and key-recovery envelope in plaintext, but top-level `icon`, `sort`, and `sortMode` contain only neutral values. Their real values are authenticated ciphertext in `boxCrypt.metadata` and are restored in memory by `GetConf` only after the notebook is unlocked.
+
> ⚠️ **The notebook ID is NOT in `conf.json`** — the ID is the notebook directory name itself (see §3).
Read/write sites: `GetConf` / `SaveConf`. The path is hard-coded as `<DataDir>/<boxID>/.siyuan/conf.json`.
diff --git a/docs/WORKSPACE.zh-CN.md b/docs/WORKSPACE.zh-CN.md
index 1c9714982a..d19070a262 100644
--- a/docs/WORKSPACE.zh-CN.md
+++ b/docs/WORKSPACE.zh-CN.md
@@ -182,6 +182,8 @@ data/<boxID>/
| `encrypted` | bool | 是否为加密笔记本 |
| `boxCrypt` | object 或 null | 已封装的笔记本数据加密密钥及包络元数据,在加密笔记本中为非空 |
+加密笔记本仍以明文保存名称、关闭状态和恢复所需的密钥包络,但 `icon`、`sort`、`sortMode` 在顶层只保存中性值,真实值位于 `boxCrypt.metadata` 的认证密文中;笔记本解锁后 `GetConf` 才会在内存中恢复这些值。
+
> ⚠️ **笔记本 ID 不在 `conf.json` 里**——ID 就是笔记本目录名本身(见 §3 的判定规则)。
读写位置:`GetConf` / `SaveConf`。路径硬编码为 `<DataDir>/<boxID>/.siyuan/conf.json`。
diff --git a/kernel/agent/tools.go b/kernel/agent/tools.go
index a51cca338c..23196b39c7 100644
--- a/kernel/agent/tools.go
+++ b/kernel/agent/tools.go
@@ -24,6 +24,7 @@ import (
"github.com/sashabaranov/go-openai"
"github.com/siyuan-note/siyuan/kernel/mcp/tools"
+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"
)
func convertMCPToolsToOpenAI() []openai.Tool {
@@ -79,15 +80,32 @@ func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) exec
err error
}
executionCh := make(chan executionResult, 1)
+ executionLifetimeDone := make(chan struct{})
+ defer close(executionLifetimeDone)
go func() {
var result tools.CallToolResult
var err error
+ releaseBoxLeases := func() {}
+ if t.BoxLeaseResolver != nil {
+ releaseBoxLeases, err = kernelModel.AcquireEncryptedBoxOperations(ctx, t.BoxLeaseResolver(args))
+ if err != nil {
+ executionCh <- executionResult{
+ result: tools.CallToolResult{
+ Content: []tools.ContentItem{{Type: "text", Text: "encrypted notebook is locked, please unlock it first"}},
+ IsError: true,
+ },
+ }
+ return
+ }
+ }
+ defer releaseBoxLeases()
if t.ContextHandler != nil {
result, err = t.ContextHandler(ctx, args)
} else {
result, err = t.Handler(args)
}
executionCh <- executionResult{result: result, err: err}
+ <-executionLifetimeDone
}()
var execution executionResult
diff --git a/kernel/api/av.go b/kernel/api/av.go
index 306d22457c..cc75265693 100644
--- a/kernel/api/av.go
+++ b/kernel/api/av.go
@@ -1016,6 +1016,23 @@ func renderSnapshotAttributeView(c *gin.Context) {
index := arg["snapshot"].(string)
id := arg["id"].(string)
+ blockID, _ := arg["blockID"].(string)
+ if err := holdAttributeViewRequest(c, blockID, id); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ boxID, err := model.ResolveRepoSnapshotAttributeViewBoxID(index, id)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if err = holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
view, attrView, err := model.RenderRepoSnapshotAttributeView(index, id)
if err != nil {
ret.Code = -1
@@ -1093,6 +1110,22 @@ func renderHistoryAttributeView(c *gin.Context) {
if nil != groupPagingArg {
groupPaging = groupPagingArg.(map[string]any)
}
+ if err := holdAttributeViewRequest(c, blockID, id); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ boxID, err := model.ResolveHistoryAttributeViewBoxID(id, created)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if err = holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
view, attrView, err := model.RenderHistoryAttributeView(blockID, id, viewID, query, page, pageSize, groupPaging, created)
if err != nil {
@@ -1198,6 +1231,12 @@ func renderAttributeView(c *gin.Context) {
if persistViewArg := arg["persistView"]; nil != persistViewArg {
persistView = persistViewArg.(bool)
}
+ if err := holdAttributeViewRequest(c, blockID, id); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ c.JSON(http.StatusOK, ret)
+ return
+ }
readOnlyRole := model.IsReadOnlyRoleContext(c)
if readOnlyRole {
@@ -1229,6 +1268,18 @@ func renderAttributeView(c *gin.Context) {
c.Data(http.StatusOK, "application/json; charset=utf-8", marshalBytes)
}
+func holdAttributeViewRequest(c *gin.Context, blockID, avID string) error {
+ if blockID != "" {
+ if block := treenode.GetBlockTree(blockID); block != nil && model.IsEncryptedBox(block.BoxID) {
+ return holdEncryptedBoxRequest(c, block.BoxID)
+ }
+ }
+ if _, boxID := av.FindAttributeViewPath(avID); boxID != "" {
+ return holdEncryptedBoxRequest(c, boxID)
+ }
+ return nil
+}
+
func renderAttrView(blockID, avID, viewID, query string, page, pageSize int, groupPaging map[string]any, initialLayout av.LayoutType, createIfNotExist, ignoreRows, persistView bool, targetItemID, targetGroupID string) (ret *gulu.Result) {
ret = gulu.Ret.NewResult()
view, attrView, target, err := model.RenderAttributeViewWithTarget(blockID, avID, viewID, query, page, pageSize, groupPaging, initialLayout, createIfNotExist, ignoreRows, persistView, targetItemID, targetGroupID)
diff --git a/kernel/api/box_lease.go b/kernel/api/box_lease.go
index a201664dc3..2e030a02b9 100644
--- a/kernel/api/box_lease.go
+++ b/kernel/api/box_lease.go
@@ -41,9 +41,7 @@ func holdEncryptedBoxRequest(c *gin.Context, boxID string) error {
}
}
- model.HoldBoxReadLock(boxID)
- if !model.IsBoxUnlocked(boxID) {
- model.ReleaseBoxReadLock(boxID)
+ if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
return errors.New("encrypted notebook is locked, please unlock it first")
}
leases = append(leases, boxID)
@@ -60,10 +58,23 @@ func requestBoxLeases(c *gin.Context) []string {
return leases
}
+func releaseEncryptedBoxRequest(c *gin.Context, boxID string) {
+ leases := requestBoxLeases(c)
+ for i := len(leases) - 1; i >= 0; i-- {
+ if leases[i] != boxID {
+ continue
+ }
+ leases = append(leases[:i], leases[i+1:]...)
+ c.Set(requestBoxLeasesKey, leases)
+ model.ReleaseEncryptedBoxOperation(boxID)
+ return
+ }
+}
+
func releaseRequestBoxLeases(c *gin.Context) {
leases := requestBoxLeases(c)
for i := len(leases) - 1; i >= 0; i-- {
- model.ReleaseBoxReadLock(leases[i])
+ model.ReleaseEncryptedBoxOperation(leases[i])
}
c.Set(requestBoxLeasesKey, []string{})
}
diff --git a/kernel/api/export.go b/kernel/api/export.go
index a9a3bb3e70..f2b7289710 100644
--- a/kernel/api/export.go
+++ b/kernel/api/export.go
@@ -53,6 +53,9 @@ func exportCodeBlock(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
filePath, err := model.ExportCodeBlock(id)
if err != nil {
ret.Code = 1
@@ -82,6 +85,9 @@ func exportAttributeView(c *gin.Context) {
) {
return
}
+ if !holdEncryptedExportRequest(c, blockID, ret) {
+ return
+ }
zipPath, err := model.ExportAv2CSV(avID, blockID)
if err != nil {
ret.Code = 1
@@ -108,6 +114,9 @@ func exportEPUB(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "epub", ".epub")
ret.Data = map[string]any{
"name": name,
@@ -128,6 +137,9 @@ func exportRTF(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "rtf", ".rtf")
ret.Data = map[string]any{
"name": name,
@@ -148,6 +160,9 @@ func exportODT(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "odt", ".odt")
ret.Data = map[string]any{
"name": name,
@@ -168,6 +183,9 @@ func exportMediaWiki(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "mediawiki", ".wiki")
ret.Data = map[string]any{
"name": name,
@@ -188,6 +206,9 @@ func exportOrgMode(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "org", ".org")
ret.Data = map[string]any{
"name": name,
@@ -208,6 +229,9 @@ func exportOPML(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "opml", ".opml")
ret.Data = map[string]any{
"name": name,
@@ -228,6 +252,9 @@ func exportTextile(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "textile", ".textile")
ret.Data = map[string]any{
"name": name,
@@ -248,6 +275,9 @@ func exportAsciiDoc(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "asciidoc", ".adoc")
ret.Data = map[string]any{
"name": name,
@@ -268,6 +298,9 @@ func exportReStructuredText(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZip([]string{id}, "rst", ".rst")
ret.Data = map[string]any{
"name": name,
@@ -391,6 +424,11 @@ func exportNotebookMd(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("notebook", &notebook, true, true)) {
return
}
+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
zipPath := model.ExportNotebookMarkdownWithOptions(notebook, model.ParseExportOptions(arg))
ret.Data = map[string]any{
"name": path.Base(zipPath),
@@ -412,6 +450,9 @@ func exportMds(c *gin.Context) {
for _, id := range idsArg {
ids = append(ids, id.(string))
}
+ if !holdEncryptedExportRequests(c, ids, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZipWithOptions(ids, "", ".md", model.ParseExportOptions(arg))
ret.Data = map[string]any{
@@ -433,6 +474,9 @@ func exportMd(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, zipPath := model.ExportPandocConvertZipWithOptions([]string{id}, "", ".md", model.ParseExportOptions(arg))
ret.Data = map[string]any{
"name": name,
@@ -453,6 +497,11 @@ func exportNotebookSY(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if err := holdEncryptedBoxRequest(c, id); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
zipPath := model.ExportNotebookSY(id)
ret.Data = map[string]any{
"zip": zipPath,
@@ -473,6 +522,9 @@ func exportSYs(c *gin.Context) {
for _, id := range idsArg {
ids = append(ids, id.(string))
}
+ if !holdEncryptedExportRequests(c, ids, ret) {
+ return
+ }
zipPath := model.ExportSYs(ids)
ret.Data = map[string]any{
@@ -493,6 +545,9 @@ func exportSY(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
zipPath := model.ExportSYs([]string{id})
ret.Data = map[string]any{
"zip": zipPath,
@@ -515,6 +570,9 @@ func exportMdContent(c *gin.Context) {
if util.InvalidIDPattern(id, ret) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
refMode := model.Conf.Export.BlockRefMode
if nil != arg["refMode"] {
@@ -575,6 +633,9 @@ func exportDocx(c *gin.Context) {
) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
// savePath 由客户端指定,禁止写入加密笔记本目录(明文导出物会绕过加密、锁定后残留)
if rejectEncryptedBoxPath(savePath) {
@@ -611,6 +672,9 @@ func exportMdHTML(c *gin.Context) {
) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
savePath = strings.TrimSpace(savePath)
if savePath == "" {
@@ -661,6 +725,9 @@ func exportTempContent(c *gin.Context) {
) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
tmpExport := filepath.Join(util.TempDir, "export")
// 加密笔记本的临时导出归入 boxID 子目录,确保 LockBox 清理和服务端校验锁定状态
if id != "" {
@@ -721,8 +788,20 @@ func exportBrowserHTML(c *gin.Context) {
return
}
- tmpDir := filepath.Join(util.TempDir, "export", folder)
+ // 检测是否来自加密笔记本:folder 形如 <boxID>/<folderName>
+ boxID := ""
+ if parts := strings.SplitN(folder, "/", 2); len(parts) >= 1 && ast.IsNodeIDPattern(parts[0]) && model.IsEncryptedBox(parts[0]) {
+ boxID = parts[0]
+ }
+ if boxID != "" {
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ }
+ tmpDir := filepath.Join(util.TempDir, "export", folder)
htmlPath := filepath.Join(tmpDir, "index.html")
if err := filelock.WriteFile(htmlPath, []byte(htmlContent)); err != nil {
ret.Code = -1
@@ -731,12 +810,6 @@ func exportBrowserHTML(c *gin.Context) {
return
}
- // 检测是否来自加密笔记本:folder 形如 <boxID>/<folderName>
- boxID := ""
- if parts := strings.SplitN(folder, "/", 2); len(parts) >= 1 && ast.IsNodeIDPattern(parts[0]) && model.IsEncryptedBox(parts[0]) {
- boxID = parts[0]
- }
-
zipFileName := util.FilterFileName(name) + ".zip"
var zipAbsPath string
if boxID != "" {
@@ -761,6 +834,8 @@ func exportBrowserHTML(c *gin.Context) {
err = zip.AddDirectory("", tmpDir, func(string) {})
if err != nil {
+ _ = zip.Close()
+ _ = os.Remove(zipAbsPath)
ret.Code = -1
ret.Msg = err.Error()
ret.Data = nil
@@ -768,6 +843,7 @@ func exportBrowserHTML(c *gin.Context) {
}
if err = zip.Close(); err != nil {
+ _ = os.Remove(zipAbsPath)
ret.Code = -1
ret.Msg = err.Error()
ret.Data = nil
@@ -806,6 +882,9 @@ func exportPreviewHTML(c *gin.Context) {
) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
name, content, node := model.ExportHTML(id, "", true, keepFold, merge)
// 导出 PDF 预览时点击块引转换后的脚注跳转不正确 https://github.com/siyuan-note/siyuan/issues/5894
content = strings.ReplaceAll(content, "http://"+util.LocalHost+":"+util.ServerPort+"/#", "#")
@@ -847,6 +926,9 @@ func exportHTML(c *gin.Context) {
) {
return
}
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return
+ }
savePath = strings.TrimSpace(savePath)
if savePath == "" {
@@ -881,6 +963,28 @@ func exportHTML(c *gin.Context) {
}
}
+func holdEncryptedExportRequest(c *gin.Context, id string, ret *gulu.Result) bool {
+ block := treenode.GetBlockTree(id)
+ if block == nil || !model.IsEncryptedBox(block.BoxID) {
+ return true
+ }
+ if err := holdEncryptedBoxRequest(c, block.BoxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return false
+ }
+ return true
+}
+
+func holdEncryptedExportRequests(c *gin.Context, ids []string, ret *gulu.Result) bool {
+ for _, id := range ids {
+ if !holdEncryptedExportRequest(c, id, ret) {
+ return false
+ }
+ }
+ return true
+}
+
func processPDF(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
@@ -1057,6 +1161,11 @@ func copyExportFile(c *gin.Context) {
ret.Msg = "export file is not available"
return
}
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
model.HoldBoxReadLock(boxID)
if _, dekErr := model.GetDEKIfUnlocked(boxID); dekErr != nil {
model.ReleaseBoxReadLock(boxID)
diff --git a/kernel/api/file.go b/kernel/api/file.go
index bbfdfb7b18..eef781f4ff 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -379,6 +379,12 @@ func copyFile(c *gin.Context) {
if rejectEncryptedBoxPath(src) || rejectEncryptedBoxPath(dest) {
if !rejectEncryptedBoxPath(dest) && !gulu.File.IsSubPath(util.WorkspaceDir, dest) {
// dest 在工作区外且非加密 box,允许解密后复制
+ boxID := model.ExtractBoxIDFromAssetsPath(src)
+ if err = holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
if err = copyDecryptedAsset(src, dest); err != nil {
ret.Code = -1
ret.Msg = err.Error()
diff --git a/kernel/api/history.go b/kernel/api/history.go
index 563c6651fc..3592d29261 100644
--- a/kernel/api/history.go
+++ b/kernel/api/history.go
@@ -18,6 +18,8 @@ package api
import (
"net/http"
+ "path/filepath"
+ "sort"
"time"
"github.com/88250/gulu"
@@ -161,6 +163,9 @@ func getDocHistoryContent(c *gin.Context) {
}
highlight = highlightVal
}
+ if !holdHistoryRequest(c, historyPath, ret) {
+ return
+ }
id, rootID, content, isLargeDoc, err := model.GetDocHistoryContent(historyPath, keyword, highlight)
if err != nil {
ret.Code = -1
@@ -205,6 +210,30 @@ func diffDocVersions(c *gin.Context) {
if !ok {
return
}
+ boxIDs := map[string]struct{}{}
+ for _, ref := range []*model.DocVersionRef{left, right} {
+ boxID, resolveErr := model.ResolveDocVersionBoxID(ref)
+ if resolveErr != nil {
+ ret.Code = -1
+ ret.Msg = resolveErr.Error()
+ return
+ }
+ if boxID != "" {
+ boxIDs[boxID] = struct{}{}
+ }
+ }
+ sortedBoxIDs := make([]string, 0, len(boxIDs))
+ for boxID := range boxIDs {
+ sortedBoxIDs = append(sortedBoxIDs, boxID)
+ }
+ sort.Strings(sortedBoxIDs)
+ for _, boxID := range sortedBoxIDs {
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ }
diff, err := model.DiffDocVersions(left, right)
if err != nil {
@@ -243,6 +272,9 @@ func rollbackDocHistory(c *gin.Context) {
) {
return
}
+ if !holdHistoryRequest(c, historyPath, ret) {
+ return
+ }
err := model.RollbackDocHistory(historyPath)
if err != nil {
ret.Code = -1
@@ -264,6 +296,9 @@ func rollbackAssetsHistory(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("historyPath", &historyPath, true, true)) {
return
}
+ if !holdHistoryRequest(c, historyPath, ret) {
+ return
+ }
err := model.RollbackAssetsHistory(historyPath)
if err != nil {
ret.Code = -1
@@ -306,6 +341,9 @@ func rollbackAttributeViewHistory(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("historyPath", &historyPath, true, true)) {
return
}
+ if !holdHistoryRequest(c, historyPath, ret) {
+ return
+ }
err := model.RollbackAttributeViewHistory(historyPath)
if err != nil {
ret.Code = -1
@@ -314,6 +352,17 @@ func rollbackAttributeViewHistory(c *gin.Context) {
}
}
+func holdHistoryRequest(c *gin.Context, historyPath string, ret *gulu.Result) bool {
+ absolutePath := filepath.Join(util.WorkspaceDir, historyPath)
+ boxID := model.ExtractBoxIDFromHistoryPath(absolutePath)
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return false
+ }
+ return true
+}
+
func createDocHistory(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go
index fbfad84fcc..3878c90b03 100644
--- a/kernel/api/notebook.go
+++ b/kernel/api/notebook.go
@@ -57,6 +57,11 @@ func getNotebookInfo(c *gin.Context) {
ret.Msg = "notebook [" + boxID + "] not found"
return
}
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
boxInfo := box.GetInfo()
ret.Data = map[string]any{
@@ -80,6 +85,11 @@ func setNotebookIcon(c *gin.Context) {
) {
return
}
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
model.SetBoxIcon(boxID, icon)
}
@@ -97,6 +107,13 @@ func changeSortNotebook(c *gin.Context) {
for _, p := range idsArg {
ids = append(ids, p.(string))
}
+ for _, id := range ids {
+ if err := holdEncryptedBoxRequest(c, id); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ }
model.ChangeBoxSort(ids)
}
@@ -119,6 +136,11 @@ func renameNotebook(c *gin.Context) {
if util.InvalidIDPattern(notebook, ret) {
return
}
+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
err := model.RenameBox(notebook, name)
if err != nil {
ret.Code = -1
@@ -244,6 +266,11 @@ func openNotebook(c *gin.Context) {
ret.Data = map[string]any{"closeTimeout": 5000}
return
}
+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
msgId := util.PushMsg(model.Conf.Language(45), 1000*60*15)
defer util.PushClearMsg(msgId)
@@ -339,6 +366,13 @@ func getNotebookConf(c *gin.Context) {
ret.Msg = "notebook [" + notebook + "] not found"
return
}
+ if model.IsBoxUnlocked(notebook) {
+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ }
boxConf := box.GetConf()
if !model.IsAdminRoleContext(c) {
@@ -371,6 +405,13 @@ func setNotebookConf(c *gin.Context) {
ret.Msg = "notebook [" + notebook + "] not found"
return
}
+ if model.IsBoxUnlocked(notebook) {
+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ }
param, err := gulu.JSON.MarshalJSON(arg["conf"])
if err != nil {
@@ -439,6 +480,16 @@ func lsNotebooks(c *gin.Context) {
if flashcard {
notebooks = model.GetFlashcardNotebooks()
} else {
+ for _, boxID := range model.ListAllEncryptedBoxIDs() {
+ if !model.IsBoxUnlocked(boxID) {
+ continue
+ }
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ }
var err error
notebooks, err = model.ListNotebooks()
if err != nil {
@@ -549,10 +600,16 @@ func createEncryptedNotebook(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ if err = holdEncryptedBoxRequest(c, id); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
// 创建时 DEK 已缓存 + 加密 db 已打开,此处直接挂载;失败则锁定回滚,避免 DEK 残留
existed, err := model.Mount(id)
if err != nil {
+ releaseEncryptedBoxRequest(c, id)
model.LockBox(id)
ret.Code = -1
ret.Msg = err.Error()
@@ -612,6 +669,11 @@ func unlockNotebook(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ if err = holdEncryptedBoxRequest(c, notebook); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
}
// unlockAndOpenNotebook 原子化解锁并挂载加密笔记本:UnlockBox 成功后立即 Mount,
@@ -654,12 +716,18 @@ func unlockAndOpenNotebook(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ if err = holdEncryptedBoxRequest(c, notebook); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
// 解锁成功后立即挂载;失败则回滚锁定,清除 DEK 避免残留
msgId := util.PushMsg(model.Conf.Language(45), 1000*60*15)
defer util.PushClearMsg(msgId)
existed, err := model.Mount(notebook)
if err != nil {
+ releaseEncryptedBoxRequest(c, notebook)
model.LockBox(notebook)
ret.Code = -1
ret.Msg = err.Error()
@@ -668,6 +736,7 @@ func unlockAndOpenNotebook(c *gin.Context) {
box := model.Conf.Box(notebook)
if nil == box {
+ releaseEncryptedBoxRequest(c, notebook)
model.LockBox(notebook)
ret.Code = -1
ret.Msg = "opened notebook [" + notebook + "] not found"
@@ -773,12 +842,12 @@ func getEncryptedNotebookStatus(c *gin.Context) {
model.NotebookCryptoMuLock()
boxIDs := model.ListAllEncryptedBoxIDs()
- enabled := model.NotebookCryptoEnabled()
model.NotebookCryptoMuUnlock()
pendingMigration, migrationBoxes := model.MasterPasswordMigrationStatus()
// 历史目录中是否存在已删除加密笔记本的历史快照:其恢复依赖当前密钥备份,
// 存在时前端禁用入口应拦截(与 DisableEncryptedNotebook 的后端检查对齐)
hasHistoryDependency := model.HasEncryptedNotebookHistory()
+ state := model.NotebookCryptoLifecycleState(len(boxIDs) > 0 || hasHistoryDependency)
boxes := make([]map[string]any, 0, len(boxIDs))
for _, id := range boxIDs {
@@ -791,11 +860,13 @@ func getEncryptedNotebookStatus(c *gin.Context) {
"id": id,
"name": name,
"unlocked": model.IsBoxUnlocked(id),
+ "state": model.GetEncryptedBoxState(id),
})
}
ret.Data = map[string]any{
- "enabled": enabled,
+ "enabled": state == model.NotebookCryptoStateEnabled,
+ "state": state,
"count": len(boxIDs),
"boxes": boxes,
"migrationPending": pendingMigration,
@@ -822,7 +893,7 @@ func exportNotebookCryptoBackup(c *gin.Context) {
}
// importNotebookCryptoBackup 导入密钥备份文件,恢复加密配置。
-// 用于新设备/重装后不依赖同步、手动恢复。本机已启用时拒绝(避免覆盖孤立数据)。
+// 用于新设备、重装或 RecoveryRequired 状态下手动恢复;完整且已启用的配置拒绝覆盖。
func importNotebookCryptoBackup(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/api/repo.go b/kernel/api/repo.go
index 1c70c6c5b0..865e942d0a 100644
--- a/kernel/api/repo.go
+++ b/kernel/api/repo.go
@@ -28,6 +28,7 @@ import (
"github.com/gabriel-vasile/mimetype"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -90,6 +91,9 @@ func getRepoFile(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdRepoFileRequest(c, id, ret) {
+ return
+ }
data, p, err := model.GetRepoFile(id)
if err != nil {
ret.Code = -1
@@ -122,6 +126,9 @@ func rollbackRepoSnapshotFile(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdRepoFileRequest(c, id, ret) {
+ return
+ }
err := model.RollbackRepoSnapshotFile(id)
if nil != err {
@@ -144,6 +151,9 @@ func openRepoSnapshotFile(c *gin.Context) {
if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
return
}
+ if !holdRepoFileRequest(c, id, ret) {
+ return
+ }
title, content, displayInText, updated, err := model.OpenRepoSnapshotFile(id)
if err != nil {
@@ -374,6 +384,13 @@ func getRepoDocHistory(c *gin.Context) {
) || util.InvalidIDPattern(id, ret) {
return
}
+ if block := treenode.GetBlockTree(id); block != nil {
+ if err := holdEncryptedBoxRequest(c, block.BoxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
+ }
files, pageCount, totalCount, err := model.GetRepoDocHistory(id, int(page))
if err != nil {
@@ -404,6 +421,9 @@ func exportRepoFile(c *gin.Context) {
) {
return
}
+ if !holdRepoFileRequest(c, id, ret) {
+ return
+ }
exportPath, err := model.ExportRepoFile(id)
if err != nil {
@@ -417,6 +437,21 @@ func exportRepoFile(c *gin.Context) {
}
}
+func holdRepoFileRequest(c *gin.Context, id string, ret *gulu.Result) bool {
+ boxID, err := model.ResolveRepoFileBoxID(id)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return false
+ }
+ if err = holdEncryptedBoxRequest(c, boxID); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return false
+ }
+ return true
+}
+
func getCloudRepoSnapshots(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/api/riff.go b/kernel/api/riff.go
index 4338b09383..363e43077f 100644
--- a/kernel/api/riff.go
+++ b/kernel/api/riff.go
@@ -40,6 +40,11 @@ func getRiffCardsByBlockIDs(c *gin.Context) {
for _, blockID := range blockIDsArg {
blockIDs = append(blockIDs, blockID.(string))
}
+ if err := model.ValidateFlashcardBlockIDs(blockIDs); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
blocks := model.GetFlashcardsByBlockIDs(blockIDs)
ret.Data = map[string]any{
@@ -92,7 +97,10 @@ func resetRiffCards(c *gin.Context) {
}
}
- model.ResetFlashcards(typ, id, deckID, blockIDs)
+ if err := model.ResetFlashcards(typ, id, deckID, blockIDs); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ }
}
func getNotebookRiffCards(c *gin.Context) {
@@ -105,6 +113,11 @@ func getNotebookRiffCards(c *gin.Context) {
}
notebookID := arg["id"].(string)
+ if model.IsEncryptedBox(notebookID) {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(313)
+ return
+ }
page := int(arg["page"].(float64))
pageSize := 20
if nil != arg["pageSize"] {
@@ -128,6 +141,11 @@ func getTreeRiffCards(c *gin.Context) {
}
rootID := arg["id"].(string)
+ if err := model.ValidateFlashcardBlockIDs([]string{rootID}); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
page := int(arg["page"].(float64))
pageSize := 20
if nil != arg["pageSize"] {
@@ -311,6 +329,11 @@ func removeRiffCards(c *gin.Context) {
for _, blockID := range blockIDsArg {
blockIDs = append(blockIDs, blockID.(string))
}
+ if err := model.ValidateFlashcardBlockIDs(blockIDs); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
transactions := []*model.Transaction{
{
@@ -349,6 +372,11 @@ func addRiffCards(c *gin.Context) {
for _, blockID := range blockIDsArg {
blockIDs = append(blockIDs, blockID.(string))
}
+ if err := model.ValidateFlashcardBlockIDs(blockIDs); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
transactions := []*model.Transaction{
{
@@ -444,7 +472,7 @@ func deckData(deck *riff.Deck) map[string]any {
return map[string]any{
"id": deck.ID,
"name": deck.Name,
- "size": deck.CountCards(),
+ "size": model.CountSupportedFlashcards(deck),
"created": time.UnixMilli(deck.Created).Format("2006-01-02 15:04:05"),
"updated": time.UnixMilli(deck.Updated).Format("2006-01-02 15:04:05"),
}
diff --git a/kernel/api/transaction.go b/kernel/api/transaction.go
index 2fac8736a0..20f9eb1877 100644
--- a/kernel/api/transaction.go
+++ b/kernel/api/transaction.go
@@ -19,12 +19,15 @@ package api
import (
"fmt"
"net/http"
+ "sort"
"strings"
"time"
"github.com/88250/gulu"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -71,6 +74,16 @@ func performTransactions(c *gin.Context) {
ret.Msg = "parses request failed"
return
}
+ if err = model.ValidateFlashcardTransactions(transactions); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if err = holdTransactionEncryptedBoxRequests(c, transactions); err != nil {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(314)
+ return
+ }
for _, transaction := range transactions {
transaction.Timestamp = timestamp
transaction.MarkFromAPI() // 标记来自 HTTP 入口,供全局撤销日志捕获判别
@@ -92,6 +105,71 @@ func performTransactions(c *gin.Context) {
c.Header("Server-Timing", fmt.Sprintf("total;dur=%d", elapsed))
}
+func holdTransactionEncryptedBoxRequests(c *gin.Context, transactions []*model.Transaction) error {
+ boxIDs := map[string]struct{}{}
+ addBoxID := func(boxID string) {
+ if boxID != "" && model.IsEncryptedBox(boxID) {
+ boxIDs[boxID] = struct{}{}
+ }
+ }
+ addBlockID := func(blockID string) {
+ if blockID == "" {
+ return
+ }
+ if block := treenode.GetBlockTree(blockID); block != nil {
+ addBoxID(block.BoxID)
+ return
+ }
+ addBoxID(blockID)
+ }
+ for _, transaction := range transactions {
+ for _, operation := range transaction.DoOperations {
+ if operation == nil {
+ continue
+ }
+ for _, id := range []string{
+ operation.ID, operation.RootID, operation.ParentID, operation.PreviousID, operation.NextID, operation.BlockID,
+ } {
+ addBlockID(id)
+ }
+ for _, id := range operation.BlockIDs {
+ addBlockID(id)
+ }
+ for _, id := range operation.SrcIDs {
+ addBlockID(id)
+ }
+ for _, src := range operation.Srcs {
+ if id, ok := src["id"].(string); ok {
+ addBlockID(id)
+ }
+ }
+ if operation.Tree != nil {
+ addBoxID(operation.Tree.Box)
+ }
+ if _, boxID := av.FindAttributeViewPath(operation.AvID); boxID != "" {
+ addBoxID(boxID)
+ }
+ for _, key := range []string{"notebook", "box", "boxID", "rootID", "blockID"} {
+ if id, ok := operation.Context[key].(string); ok {
+ addBlockID(id)
+ }
+ }
+ }
+ }
+
+ sortedBoxIDs := make([]string, 0, len(boxIDs))
+ for boxID := range boxIDs {
+ sortedBoxIDs = append(sortedBoxIDs, boxID)
+ }
+ sort.Strings(sortedBoxIDs)
+ for _, boxID := range sortedBoxIDs {
+ if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func pushTransactions(app, session string, transactions []*model.Transaction) {
pushMode := util.PushModeBroadcastExcludeSelf
if 0 < len(transactions) && 0 < len(transactions[0].DoOperations) {
diff --git a/kernel/conf/box.go b/kernel/conf/box.go
index 6282488ac3..0612cc1d6e 100644
--- a/kernel/conf/box.go
+++ b/kernel/conf/box.go
@@ -38,10 +38,11 @@ type BoxConf struct {
// BoxEncryption 维护单个加密笔记本的密钥包络参数。WrappedDEK 是用全局 KEK 加密后的 DEK,本身可落盘。
type BoxEncryption struct {
- Spec int `json:"spec,omitempty"` // 包络规范版本,1 表示 WrappedDEK 已绑定 boxID AAD
- WrappedDEK []byte `json:"wrappedDEK"` // 用 KEK 经 AES-GCM 加密后的 DEK
- WrapNonce []byte `json:"wrapNonce"` // 包络用的 GCM nonce(从加密信封中提取)
- CreatedAt int64 `json:"createdAt"` // 创建时间,单位毫秒,便于未来按时间轮换密钥
+ Spec int `json:"spec"` // 当前包络规范标识,WrappedDEK 绑定 boxID AAD
+ WrappedDEK []byte `json:"wrappedDEK"` // 用 KEK 经 AES-GCM 加密后的 DEK
+ WrapNonce []byte `json:"wrapNonce"` // 包络用的 GCM nonce(从加密信封中提取)
+ Metadata []byte `json:"metadata,omitempty"` // 用 DEK 加密的图标和排序元数据
+ CreatedAt int64 `json:"createdAt"` // 创建时间,单位毫秒,便于未来按时间轮换密钥
}
func NewBoxConf() *BoxConf {
diff --git a/kernel/conf/notebook_crypto.go b/kernel/conf/notebook_crypto.go
index ade0b87c3d..f54e1eda68 100644
--- a/kernel/conf/notebook_crypto.go
+++ b/kernel/conf/notebook_crypto.go
@@ -28,9 +28,8 @@ type NotebookCrypto struct {
VerifierNonce []byte `json:"verifierNonce"` // verifier 的 GCM nonce(从加密信封中提取)
AutoLockMinutes int `json:"autoLockMinutes"` // 加密笔记本自动锁定闲置分钟数,0 表示禁用,默认 5
- // 备份完整性字段(Spec>=1)
- // Spec 表示备份规范版本。Checksum 防损坏。KEKMAC 需主密码验证。
- Spec int `json:"spec,omitempty"` // 备份规范版本(见 CurrentNotebookCryptoSpec)
+ // 当前备份的完整性字段。Checksum 防损坏,KEKMAC 需主密码验证。
+ Spec int `json:"spec"` // 当前备份规范标识(见 CurrentNotebookCryptoSpec)
BackupID string `json:"backupID,omitempty"` // 备份唯一标识(UUID)
CreatedAt int64 `json:"createdAt,omitempty"` // 备份创建/更新时间(unix 秒)
Checksum string `json:"checksum,omitempty"` // SHA-256 校验和
@@ -48,8 +47,3 @@ func NewNotebookCrypto() *NotebookCrypto {
// CurrentNotebookCryptoSpec 是当前备份规范版本号。
const CurrentNotebookCryptoSpec = 1
-
-// UpgradeSpec 当前不执行迁移。
-func UpgradeSpec(*NotebookCrypto) bool {
- return false
-}
diff --git a/kernel/harmony/kernel.go b/kernel/harmony/kernel.go
index 547a68d9f6..3837a16c65 100644
--- a/kernel/harmony/kernel.go
+++ b/kernel/harmony/kernel.go
@@ -60,6 +60,8 @@ func ReleaseExportFile(leaseID *C.char) {
model.ReleaseMobileExportLease(C.GoString(leaseID))
}
+// GetExportFileName 返回普通导出的资源名称;加密导出应读取 AcquireExportFile 返回的 Name。
+//
//export GetExportFileName
func GetExportFileName(exportPath *C.char) *C.char {
name := model.GetMobileExportName(C.GoString(exportPath))
@@ -206,14 +208,10 @@ func GetExportFilePath(exportPath *C.char) *C.char {
logging.LogWarnf("get export file path [%s] blocked: path traversal attempt [%s]", pathStr, fileName)
return nil
}
- // 加密导出受控路径(<boxID>/<kind>/<file>):必须经注册表校验且 box 已解锁,否则 fail-closed
+ // 加密导出需要持有覆盖原生复制过程的租约,旧路径解析接口不再返回其明文地址。
if model.IsManagedEncryptedExportPath(fileName) {
- artifact, ok := model.ResolveManagedExportForMobile(fileName)
- if !ok {
- logging.LogWarnf("get export file path [%s] blocked: managed export not available or box locked", pathStr)
- return nil
- }
- return C.CString(artifact)
+ logging.LogWarnf("get export file path [%s] blocked: use AcquireExportFile for encrypted exports", pathStr)
+ return nil
}
absPath = filepath.Join(util.TempDir, "export", fileName)
exportBaseDir := filepath.Join(util.TempDir, "export")
diff --git a/kernel/mcp/server.go b/kernel/mcp/server.go
index d435ddcc52..1d8ef992c4 100644
--- a/kernel/mcp/server.go
+++ b/kernel/mcp/server.go
@@ -123,8 +123,11 @@ func isModernRequest(request *http.Request) bool {
}
func serveHTTP(handler http.Handler) gin.HandlerFunc {
- return func(context *gin.Context) {
- handler.ServeHTTP(context.Writer, context.Request)
+ return func(ginContext *gin.Context) {
+ requestContext, release := model.WithEncryptedBoxOperationScope(ginContext.Request.Context())
+ defer release()
+ request := ginContext.Request.WithContext(requestContext)
+ handler.ServeHTTP(ginContext.Writer, request)
}
}
@@ -170,6 +173,14 @@ func syncTool(server *mcpsdk.Server, name string, tool *tools.Tool) {
if err := validator.ValidateInputContext(ctx, arguments); err != nil {
return toolErrorResult(fmt.Sprintf("invalid tool arguments: %v", err)), nil
}
+ releaseBoxLeases := func() {}
+ if tool.BoxLeaseResolver != nil {
+ releaseBoxLeases, err = model.AcquireEncryptedBoxOperations(ctx, tool.BoxLeaseResolver(arguments))
+ if err != nil {
+ return toolErrorResult("encrypted notebook is locked, please unlock it first"), nil
+ }
+ }
+ defer releaseBoxLeases()
var (
result tools.CallToolResult
diff --git a/kernel/mcp/tools/box_lease.go b/kernel/mcp/tools/box_lease.go
new file mode 100644
index 0000000000..a5755787f1
--- /dev/null
+++ b/kernel/mcp/tools/box_lease.go
@@ -0,0 +1,167 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package tools
+
+import (
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+var encryptedBoxScopedToolNames = map[string]struct{}{
+ "asset": {},
+ "attr": {},
+ "block": {},
+ "dailynote": {},
+ "database": {},
+ "document": {},
+ "export": {},
+ "history": {},
+ "image": {},
+ "import": {},
+ "outline": {},
+ "ref": {},
+ "repo": {},
+ "search": {},
+ "template": {},
+}
+
+func attachEncryptedBoxLeaseResolver(tool *Tool) {
+ if tool == nil || tool.BoxLeaseResolver != nil {
+ return
+ }
+ if tool.Name == "notebook" {
+ tool.BoxLeaseResolver = resolveNotebookToolBoxLeases
+ return
+ }
+ if tool.Name == "repo" {
+ tool.BoxLeaseResolver = resolveRepoToolBoxLeases
+ return
+ }
+ if _, ok := encryptedBoxScopedToolNames[tool.Name]; ok {
+ tool.BoxLeaseResolver = resolveEncryptedBoxLeases
+ }
+}
+
+func resolveNotebookToolBoxLeases(args map[string]any) []string {
+ action, _ := args["action"].(string)
+ switch action {
+ case "list":
+ var ret []string
+ for _, boxID := range model.ListAllEncryptedBoxIDs() {
+ if model.IsBoxUnlocked(boxID) {
+ ret = append(ret, boxID)
+ }
+ }
+ return ret
+ case "open", "rename", "set_icon":
+ id, _ := args["id"].(string)
+ return []string{id}
+ case "random_icon":
+ if id, _ := args["id"].(string); id != "" {
+ return []string{id}
+ }
+ return model.ListAllEncryptedBoxIDs()
+ default:
+ return nil
+ }
+}
+
+func resolveRepoToolBoxLeases(args map[string]any) []string {
+ action, _ := args["action"].(string)
+ if !strings.HasPrefix(action, "file_") {
+ return nil
+ }
+ id, _ := args["id"].(string)
+ if id == "" {
+ return nil
+ }
+ boxID, err := model.ResolveRepoFileBoxID(id)
+ if err != nil || boxID == "" {
+ return nil
+ }
+ return []string{boxID}
+}
+
+func resolveEncryptedBoxLeases(args map[string]any) []string {
+ boxIDs := map[string]struct{}{}
+ addBoxID := func(boxID string) {
+ boxID = strings.TrimSpace(boxID)
+ if boxID != "" && model.IsEncryptedBox(boxID) {
+ boxIDs[boxID] = struct{}{}
+ }
+ }
+ addObjectID := func(id string) {
+ id = strings.TrimSpace(id)
+ if !ast.IsNodeIDPattern(id) {
+ return
+ }
+ addBoxID(id)
+ if block := treenode.GetBlockTree(id); block != nil {
+ addBoxID(block.BoxID)
+ }
+ if _, boxID := av.FindAttributeViewPath(id); boxID != "" {
+ addBoxID(boxID)
+ }
+ }
+ addValue := func(value any, add func(string)) {
+ switch typed := value.(type) {
+ case string:
+ for _, item := range strings.Split(typed, ",") {
+ add(item)
+ }
+ case []string:
+ for _, item := range typed {
+ add(item)
+ }
+ case []any:
+ for _, item := range typed {
+ if text, ok := item.(string); ok {
+ add(text)
+ }
+ }
+ }
+ }
+
+ for _, key := range []string{"notebook", "notebooks", "box", "boxID", "boxIDs"} {
+ addValue(args[key], addBoxID)
+ }
+ for _, key := range []string{
+ "id", "ids", "blockID", "blockIDs", "documentID", "documentIDs", "parentID", "parentIDs", "rootID", "rootIDs",
+ "nextID", "previousID",
+ } {
+ addValue(args[key], addObjectID)
+ }
+ for _, key := range []string{"path", "historyPath"} {
+ pathValue, _ := args[key].(string)
+ for _, segment := range strings.Split(filepath.ToSlash(pathValue), "/") {
+ addBoxID(segment)
+ }
+ }
+
+ ret := make([]string, 0, len(boxIDs))
+ for boxID := range boxIDs {
+ ret = append(ret, boxID)
+ }
+ sort.Strings(ret)
+ return ret
+}
diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.go
index c3719a96da..cf3303804f 100644
--- a/kernel/mcp/tools/register.go
+++ b/kernel/mcp/tools/register.go
@@ -150,6 +150,7 @@ func register(t *Tool) {
if t.Source == "" {
t.Source = "native"
}
+ attachEncryptedBoxLeaseResolver(t)
if err := SetTool(t.Name, t); err != nil {
panic(fmt.Sprintf("register MCP tool [%s]: %v", t.Name, err))
}
diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.go
index f06c3e246b..230a401f32 100644
--- a/kernel/mcp/tools/types.go
+++ b/kernel/mcp/tools/types.go
@@ -44,8 +44,9 @@ type Tool struct {
// ActionEffects 按 action 描述本地读写、数据外发与外部计费,供智能体精确执行确认和快照策略。
ActionEffects map[string]ToolEffects `json:"-"`
- Handler func(args map[string]any) (CallToolResult, error) `json:"-"`
- ContextHandler func(ctx context.Context, args map[string]any) (CallToolResult, error) `json:"-"`
+ Handler func(args map[string]any) (CallToolResult, error) `json:"-"`
+ ContextHandler func(ctx context.Context, args map[string]any) (CallToolResult, error) `json:"-"`
+ BoxLeaseResolver func(args map[string]any) []string `json:"-"`
}
type ToolEffects struct {
diff --git a/kernel/mobile/kernel.go b/kernel/mobile/kernel.go
index b5c6eceabf..fde847c194 100644
--- a/kernel/mobile/kernel.go
+++ b/kernel/mobile/kernel.go
@@ -62,7 +62,7 @@ func ReleaseExportFile(leaseID string) {
model.ReleaseMobileExportLease(leaseID)
}
-// GetExportFileName 返回移动端保存对话框使用的资源名称。
+// GetExportFileName 返回普通导出的资源名称;加密导出应读取 AcquireExportFile 返回的 Name。
func GetExportFileName(exportPath string) string {
return model.GetMobileExportName(exportPath)
}
@@ -350,14 +350,10 @@ func GetExportFilePath(exportPath string) (ret string) {
logging.LogWarnf("get export file path [%s] blocked: path traversal attempt [%s]", exportPath, fileName)
return
}
- // 加密导出受控路径(<boxID>/<kind>/<file>):必须经注册表校验且 box 已解锁,否则 fail-closed
+ // 加密导出需要持有覆盖原生复制过程的租约,旧路径解析接口不再返回其明文地址。
if model.IsManagedEncryptedExportPath(fileName) {
- artifact, ok := model.ResolveManagedExportForMobile(fileName)
- if !ok {
- logging.LogWarnf("get export file path [%s] blocked: managed export not available or box locked", exportPath)
- return
- }
- return artifact
+ logging.LogWarnf("get export file path [%s] blocked: use AcquireExportFile for encrypted exports", exportPath)
+ return
}
absPath = filepath.Join(util.TempDir, "export", fileName)
exportBaseDir := filepath.Join(util.TempDir, "export")
diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.go
index cb08434abd..980bfd4f63 100644
--- a/kernel/model/attribute_view_render.go
+++ b/kernel/model/attribute_view_render.go
@@ -17,6 +17,7 @@
package model
import (
+ "errors"
"fmt"
"math"
"os"
@@ -1007,6 +1008,84 @@ func avBoxIDFromRepoPath(repoPath string) string {
return ""
}
+// ResolveRepoSnapshotAttributeViewBoxID 返回快照属性视图的唯一加密笔记本上下文。
+func ResolveRepoSnapshotAttributeViewBoxID(indexID, avID string) (string, error) {
+ if !ast.IsNodeIDPattern(avID) {
+ return "", ErrInvalidID
+ }
+ repo, err := newRepository()
+ if err != nil {
+ return "", err
+ }
+ index, err := repo.GetIndex(indexID)
+ if err != nil {
+ return "", err
+ }
+ files, err := repo.GetFiles(index)
+ if err != nil {
+ return "", err
+ }
+ var matches []*entity.File
+ for _, file := range files {
+ if strings.HasSuffix(file.Path, "/storage/av/"+avID+".json") {
+ matches = append(matches, file)
+ }
+ }
+ if len(matches) == 0 {
+ return "", av.ErrAttributeViewNotFound
+ }
+ if len(matches) != 1 {
+ return "", fmt.Errorf("attribute view snapshot context is ambiguous [%s]", avID)
+ }
+ boxID := avBoxIDFromRepoPath(matches[0].Path)
+ if IsEncryptedBox(boxID) {
+ return boxID, nil
+ }
+ return "", nil
+}
+
+// ResolveHistoryAttributeViewBoxID 返回历史属性视图的唯一加密笔记本上下文。
+func ResolveHistoryAttributeViewBoxID(avID, created string) (string, error) {
+ if !ast.IsNodeIDPattern(avID) {
+ return "", ErrInvalidID
+ }
+ createdUnix, err := strconv.ParseInt(created, 10, 64)
+ if err != nil {
+ return "", fmt.Errorf("parse created [%s] failed: %w", created, err)
+ }
+ dirPrefix := time.Unix(createdUnix, 0).Format("2006-01-02-150405")
+ matches, err := filepath.Glob(filepath.Join(util.HistoryDir, dirPrefix+"*"))
+ if err != nil {
+ return "", err
+ }
+ var boxIDs []string
+ for _, historyDir := range matches {
+ if gulu.File.IsExist(filepath.Join(historyDir, "storage", "av", avID+".json")) {
+ boxIDs = append(boxIDs, "")
+ }
+ entries, _ := os.ReadDir(historyDir)
+ for _, entry := range entries {
+ if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {
+ continue
+ }
+ candidate := filepath.Join(historyDir, entry.Name(), "storage", "av", avID+".json")
+ if gulu.File.IsExist(candidate) {
+ boxIDs = append(boxIDs, entry.Name())
+ }
+ }
+ }
+ if len(boxIDs) == 0 {
+ return "", av.ErrAttributeViewNotFound
+ }
+ if len(boxIDs) != 1 {
+ return "", fmt.Errorf("attribute view history context is ambiguous [%s]", avID)
+ }
+ if IsEncryptedBox(boxIDs[0]) {
+ return boxIDs[0], nil
+ }
+ return "", nil
+}
+
func RenderRepoSnapshotAttributeView(indexID, avID string) (viewable av.Viewable, attrView *av.AttributeView, err error) {
if !ast.IsNodeIDPattern(avID) {
err = ErrInvalidID
@@ -1027,20 +1106,24 @@ func RenderRepoSnapshotAttributeView(indexID, avID string) (viewable av.Viewable
if err != nil {
return
}
- var avFile *entity.File
+ var avFiles []*entity.File
for _, f := range files {
// 匹配全局 /storage/av/<avID>.json 或加密笔记本/<boxID>/storage/av/<avID>.json
if strings.HasSuffix(f.Path, "/storage/av/"+avID+".json") {
- avFile = f
- break
+ avFiles = append(avFiles, f)
}
}
- if nil == avFile {
+ if len(avFiles) == 0 {
attrView = av.NewAttributeView(avID)
err = av.ErrAttributeViewNotFound
return
}
+ if len(avFiles) != 1 {
+ err = fmt.Errorf("attribute view snapshot context is ambiguous [%s]", avID)
+ return
+ }
+ avFile := avFiles[0]
data, readErr := repo.OpenFile(avFile)
if nil != readErr {
@@ -1049,15 +1132,10 @@ func RenderRepoSnapshotAttributeView(indexID, avID string) (viewable av.Viewable
return
}
- // 加密笔记本的 AV 在快照中是密文,按路径反查 boxID 后解密
- if histBoxID := avBoxIDFromRepoPath(avFile.Path); histBoxID != "" && IsEncryptedBox(histBoxID) {
- dec, decErr := av.DecryptAVData(histBoxID, avID, data)
- if decErr != nil {
- logging.LogErrorf("decrypt snapshot attribute view [%s] failed: %s", avID, decErr)
- err = decErr
- return
- }
- data = dec
+ data, err = decryptHistoricalAttributeView(avBoxIDFromRepoPath(avFile.Path), avID, data)
+ if err != nil {
+ logging.LogErrorf("decrypt snapshot attribute view [%s] failed: %s", avID, err)
+ return
}
attrView = av.NewAttributeView(avID)
@@ -1095,73 +1173,48 @@ func RenderHistoryAttributeView(blockID, avID, viewID, query string, page, pageS
return
}
- historyDir := matches[0]
- avJSONPath := filepath.Join(historyDir, "storage", "av", avID+".json")
- if !gulu.File.IsExist(avJSONPath) {
- // 加密笔记本的 AV 定义可能在历史目录的 boxID 子目录下
+ type historyAttributeViewSource struct {
+ path string
+ boxID string
+ }
+ var sources []historyAttributeViewSource
+ for _, historyDir := range matches {
+ globalPath := filepath.Join(historyDir, "storage", "av", avID+".json")
+ if gulu.File.IsExist(globalPath) {
+ sources = append(sources, historyAttributeViewSource{path: globalPath})
+ }
entries, _ := os.ReadDir(historyDir)
for _, entry := range entries {
if entry.IsDir() && ast.IsNodeIDPattern(entry.Name()) {
candidate := filepath.Join(historyDir, entry.Name(), "storage", "av", avID+".json")
if gulu.File.IsExist(candidate) {
- avJSONPath = candidate
- break
+ sources = append(sources, historyAttributeViewSource{path: candidate, boxID: entry.Name()})
}
}
}
}
- if !gulu.File.IsExist(avJSONPath) {
- logging.LogWarnf("attribute view [%s] not found in history data [%s], use current data instead", avID, historyDir)
- // 加密笔记本的 AV 定义在 notebook 级目录
- _, boxID := av.FindAttributeViewPath(avID)
- if boxID != "" {
- avJSONPath = filepath.Join(util.DataDir, boxID, "storage", "av", avID+".json")
- } else {
- avJSONPath = filepath.Join(util.DataDir, "storage", "av", avID+".json")
- }
- }
- if !gulu.File.IsExist(avJSONPath) {
- logging.LogWarnf("attribute view [%s] not found in current data", avID)
+ if len(sources) == 0 {
attrView = av.NewAttributeView(avID)
err = av.ErrAttributeViewNotFound
return
}
+ if len(sources) != 1 {
+ err = fmt.Errorf("attribute view history context is ambiguous [%s]", avID)
+ return
+ }
+ source := sources[0]
- data, readErr := os.ReadFile(avJSONPath)
+ data, readErr := os.ReadFile(source.path)
if nil != readErr {
logging.LogErrorf("read attribute view [%s] failed: %s", avID, readErr)
err = readErr
return
}
- // 加密笔记本的历史 AV 定义是密文,需要解密后才能解析。
- // 从路径提取 boxID,提取不到时遍历所有已打开的加密笔记本尝试解密。
- avAbsSlash := filepath.ToSlash(avJSONPath)
- var histBoxID string
- if idx := strings.Index(avAbsSlash, "/storage/av/"); idx > 0 {
- prefix := avAbsSlash[:idx]
- segs := strings.Split(prefix, "/")
- for i := len(segs) - 1; i >= 0; i-- {
- if ast.IsNodeIDPattern(segs[i]) {
- histBoxID = segs[i]
- break
- }
- }
- }
- if histBoxID != "" && IsEncryptedBox(histBoxID) {
- data, err = av.DecryptAVData(histBoxID, avID, data)
- if err != nil {
- logging.LogErrorf("decrypt history AV [%s] failed: %s", avID, err)
- return
- }
- } else {
- // 路径没提取到 boxID(如历史目录无 boxID 前缀的旧路径),尝试遍历已打开的加密笔记本解密
- for _, encBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
- if dec, decErr := av.DecryptAVData(encBoxID, avID, data); decErr == nil {
- data = dec
- break
- }
- }
+ data, err = decryptHistoricalAttributeView(source.boxID, avID, data)
+ if err != nil {
+ logging.LogErrorf("decrypt history attribute view [%s] failed: %s", avID, err)
+ return
}
attrView = av.NewAttributeView(avID)
@@ -1173,3 +1226,23 @@ func RenderHistoryAttributeView(blockID, avID, viewID, query string, page, pageS
viewable, err = renderAttributeView(attrView, blockID, viewID, query, page, pageSize, groupPaging, false, false, nil, "")
return
}
+
+func decryptHistoricalAttributeView(boxID, avID string, data []byte) ([]byte, error) {
+ ciphertext := util.IsCiphertext(data)
+ if boxID == "" {
+ if ciphertext {
+ return nil, errors.New("encrypted attribute view snapshot is missing notebook context")
+ }
+ return data, nil
+ }
+ if !IsEncryptedBox(boxID) {
+ if ciphertext {
+ return nil, fmt.Errorf("encrypted attribute view snapshot has no matching notebook [%s]", boxID)
+ }
+ return data, nil
+ }
+ if !ciphertext {
+ return nil, fmt.Errorf("encrypted notebook attribute view snapshot is plaintext [%s]", boxID)
+ }
+ return av.DecryptAVData(boxID, avID, data)
+}
diff --git a/kernel/model/box.go b/kernel/model/box.go
index 0f6ae02574..8e9d690706 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -61,8 +61,9 @@ type Box struct {
DueFlashcardCount int `json:"dueFlashcardCount"`
FlashcardCount int `json:"flashcardCount"`
- Encrypted bool `json:"encrypted"` // 是否为加密笔记本
- Unlocked bool `json:"unlocked"` // 加密笔记本是否已解锁(DEK 在内存),非加密笔记本恒为 false
+ Encrypted bool `json:"encrypted"` // 是否为加密笔记本
+ Unlocked bool `json:"unlocked"` // 加密笔记本是否已解锁(DEK 在内存),非加密笔记本恒为 false
+ State EncryptedBoxState `json:"state,omitempty"`
}
func StatJob() {
@@ -157,6 +158,11 @@ func ListNotebooks() (ret []*Box, err error) {
continue
}
}
+ if boxConf.Encrypted {
+ if metadataErr := revealBoxMetadataIfUnlocked(id, boxConf); metadataErr != nil {
+ logging.LogErrorf("decrypt encrypted notebook metadata [%s] failed: %s", id, metadataErr)
+ }
+ }
box := &Box{
ID: id,
@@ -168,6 +174,9 @@ func ListNotebooks() (ret []*Box, err error) {
Encrypted: boxConf.Encrypted,
Unlocked: IsBoxUnlocked(id),
}
+ if box.Encrypted {
+ box.State = GetEncryptedBoxState(id)
+ }
if !isExistConf {
// Automatically create notebook conf.json if not found it https://github.com/siyuan-note/siyuan/issues/9647
@@ -226,27 +235,53 @@ func (box *Box) GetConf() (ret *conf.BoxConf) {
return
}
- ret.Icon = filterBoxIcon(ret.Icon)
+ if ret.Encrypted {
+ if err = revealBoxMetadataIfUnlocked(box.ID, ret); err != nil {
+ logging.LogErrorf("decrypt encrypted notebook metadata [%s] failed: %s", box.ID, err)
+ }
+ } else {
+ ret.Icon = filterBoxIcon(ret.Icon)
+ }
return
}
func (box *Box) SaveConf(conf *conf.BoxConf) error {
confPath := filepath.Join(util.DataDir, box.ID, ".siyuan/conf.json")
- newData, err := gulu.JSON.MarshalIndentJSON(conf, "", " ")
+ persisted, err := prepareBoxConfForSave(box.ID, conf)
+ if err != nil {
+ return fmt.Errorf("prepare box conf [%s] failed: %w", confPath, err)
+ }
+ newData, err := gulu.JSON.MarshalIndentJSON(persisted, "", " ")
if err != nil {
return fmt.Errorf("marshal box conf [%s] failed: %w", confPath, err)
}
oldData, err := filelock.ReadFile(confPath)
if err != nil {
- return box.saveConf0(newData)
+ if err = box.saveConf0(newData); err != nil {
+ return err
+ }
+ return syncBoxConfCryptoBackup(box.ID, persisted)
}
if bytes.Equal(newData, oldData) {
- return nil
+ return syncBoxConfCryptoBackup(box.ID, persisted)
}
- return box.saveConf0(newData)
+ if err = box.saveConf0(newData); err != nil {
+ return err
+ }
+ return syncBoxConfCryptoBackup(box.ID, persisted)
+}
+
+func syncBoxConfCryptoBackup(boxID string, boxConf *conf.BoxConf) error {
+ if !boxConf.Encrypted || boxConf.BoxCrypt == nil {
+ return nil
+ }
+ if needWriteNotebookCryptBackup(boxID, boxConf.BoxCrypt) {
+ return writeNotebookCryptBackup(boxID, boxConf.BoxCrypt)
+ }
+ return nil
}
func (box *Box) saveConf0(data []byte) error {
diff --git a/kernel/model/box_conf_crypto.go b/kernel/model/box_conf_crypto.go
new file mode 100644
index 0000000000..547a5ae870
--- /dev/null
+++ b/kernel/model/box_conf_crypto.go
@@ -0,0 +1,161 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "errors"
+ "path/filepath"
+
+ "github.com/88250/gulu"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type encryptedBoxMetadata struct {
+ Icon string `json:"icon"`
+ Sort int `json:"sort"`
+ SortMode int `json:"sortMode"`
+}
+
+func encryptBoxMetadata(boxID string, boxConf *conf.BoxConf, dek []byte) error {
+ if boxConf == nil || boxConf.BoxCrypt == nil {
+ return errors.New("encrypted notebook key material is missing")
+ }
+ metadata := &encryptedBoxMetadata{
+ Icon: filterBoxIcon(boxConf.Icon),
+ Sort: boxConf.Sort,
+ SortMode: boxConf.SortMode,
+ }
+ plaintext, err := gulu.JSON.MarshalJSON(metadata)
+ if err != nil {
+ return err
+ }
+ key := util.DeriveSubKey(dek, "siyuan/box-metadata")
+ defer zeroAndClear(key)
+ boxConf.BoxCrypt.Metadata, err = util.EncryptWithAAD(key, plaintext, boxMetadataAAD(boxID))
+ return err
+}
+
+func decryptBoxMetadata(boxID string, boxConf *conf.BoxConf, dek []byte) error {
+ if boxConf == nil || boxConf.BoxCrypt == nil || len(boxConf.BoxCrypt.Metadata) == 0 {
+ return errors.New("encrypted notebook metadata is missing")
+ }
+ key := util.DeriveSubKey(dek, "siyuan/box-metadata")
+ defer zeroAndClear(key)
+ plaintext, err := util.DecryptWithAAD(key, boxConf.BoxCrypt.Metadata, boxMetadataAAD(boxID))
+ if err != nil {
+ return err
+ }
+ metadata := &encryptedBoxMetadata{}
+ if err = gulu.JSON.UnmarshalJSON(plaintext, metadata); err != nil {
+ return err
+ }
+ boxConf.Icon = filterBoxIcon(metadata.Icon)
+ boxConf.Sort = metadata.Sort
+ boxConf.SortMode = metadata.SortMode
+ return nil
+}
+
+func revealBoxMetadataIfUnlocked(boxID string, boxConf *conf.BoxConf) error {
+ clearBoxMetadata(boxConf)
+ dek, ok := cachedDEKCopy(boxID)
+ if !ok {
+ return nil
+ }
+ defer zeroAndClear(dek)
+ if err := decryptBoxMetadata(boxID, boxConf, dek); err != nil {
+ setEncryptedBoxState(boxID, EncryptedBoxStateError)
+ return err
+ }
+ return nil
+}
+
+func prepareBoxConfForSave(boxID string, boxConf *conf.BoxConf) (*conf.BoxConf, error) {
+ if boxConf == nil {
+ return nil, errors.New("notebook configuration is missing")
+ }
+ persisted := *boxConf
+ persisted.BoxCrypt = DeepCopyBoxEncryption(boxConf.BoxCrypt)
+ if !persisted.Encrypted {
+ return &persisted, nil
+ }
+ if persisted.BoxCrypt == nil {
+ clearBoxMetadata(&persisted)
+ return &persisted, nil
+ }
+ if GetEncryptedBoxState(boxID) == EncryptedBoxStateError {
+ return nil, errors.New("encrypted notebook is in an error state")
+ }
+
+ if dek, ok := cachedDEKCopy(boxID); ok {
+ defer zeroAndClear(dek)
+ if err := encryptBoxMetadata(boxID, &persisted, dek); err != nil {
+ return nil, err
+ }
+ } else if len(persisted.BoxCrypt.Metadata) == 0 {
+ existing, err := readRawBoxConf(boxID)
+ if err != nil {
+ return nil, err
+ }
+ if existing == nil || existing.BoxCrypt == nil || len(existing.BoxCrypt.Metadata) == 0 {
+ return nil, errors.New("encrypted notebook metadata is missing")
+ }
+ persisted.BoxCrypt.Metadata = append([]byte(nil), existing.BoxCrypt.Metadata...)
+ }
+ if err := validateBoxEncryption(persisted.BoxCrypt); err != nil {
+ return nil, err
+ }
+ clearBoxMetadata(&persisted)
+ return &persisted, nil
+}
+
+func clearBoxMetadata(boxConf *conf.BoxConf) {
+ boxConf.Icon = ""
+ boxConf.Sort = 0
+ boxConf.SortMode = util.SortModeFileTree
+}
+
+func cachedDEKCopy(boxID string) ([]byte, bool) {
+ cachedDEKsLock.RLock()
+ defer cachedDEKsLock.RUnlock()
+ dek, ok := cachedDEKs[boxID]
+ if !ok {
+ return nil, false
+ }
+ return append([]byte(nil), dek...), true
+}
+
+func boxMetadataAAD(boxID string) []byte {
+ return []byte("siyuan:box-metadata:" + boxID)
+}
+
+func readRawBoxConf(boxID string) (*conf.BoxConf, error) {
+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")
+ if !filelock.IsExist(confPath) {
+ return nil, nil
+ }
+ data, err := filelock.ReadFile(confPath)
+ if err != nil {
+ return nil, err
+ }
+ ret := conf.NewBoxConf()
+ if err = gulu.JSON.UnmarshalJSON(data, ret); err != nil {
+ return nil, err
+ }
+ return ret, nil
+}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 9fdb6c2a97..2cca387012 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -1269,8 +1269,9 @@ func HideConfSecret(c *AppConf) {
c.Secrets = &conf.Secrets{}
c.Variables = &conf.Variables{}
if nil != c.NotebookCrypto {
+ enabled := c.NotebookCrypto.Enabled && notebookCryptoConfigurationComplete(c.NotebookCrypto)
c.NotebookCrypto = &conf.NotebookCrypto{
- Enabled: c.NotebookCrypto.Enabled,
+ Enabled: enabled,
AutoLockMinutes: c.NotebookCrypto.AutoLockMinutes,
}
}
@@ -1496,9 +1497,13 @@ func closeUserGuide() {
}
}
-// NotebookCryptoEnabled 返回加密笔记本功能是否已启用(线程安全)。
+// NotebookCryptoEnabled 返回加密笔记本功能是否处于可用的启用状态(线程安全)。
func NotebookCryptoEnabled() bool {
Conf.m.RLock()
defer Conf.m.RUnlock()
- return Conf.NotebookCrypto.Enabled
+ if nil == Conf.NotebookCrypto {
+ return false
+ }
+ notebookCrypto := *Conf.NotebookCrypto
+ return notebookCrypto.Enabled && notebookCryptoConfigurationComplete(&notebookCrypto)
}
diff --git a/kernel/model/conf_secret_test.go b/kernel/model/conf_secret_test.go
index 2118c4903a..678b51b15b 100644
--- a/kernel/model/conf_secret_test.go
+++ b/kernel/model/conf_secret_test.go
@@ -17,6 +17,7 @@
package model
import (
+ "bytes"
"testing"
"github.com/siyuan-note/siyuan/kernel/conf"
@@ -50,19 +51,23 @@ func TestHideConfSecretPreservesNotebookCryptoSettings(t *testing.T) {
appConf := NewAppConf()
appConf.CookieKey = "session-cookie-signing-key"
appConf.System = &conf.System{}
- appConf.NotebookCrypto = &conf.NotebookCrypto{
- Enabled: true,
- MasterSalt: []byte("master-salt"),
- KDFParams: util.DefaultArgon2Params(),
- KEKVerifier: []byte("kek-verifier"),
- VerifierNonce: []byte("verifier-nonce"),
- AutoLockMinutes: 17,
- Spec: conf.CurrentNotebookCryptoSpec,
- BackupID: "backup-id",
- CreatedAt: 123,
- Checksum: "checksum",
- KEKMAC: []byte("kek-mac"),
+ kek := bytes.Repeat([]byte{1}, 32)
+ verifier, err := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ if err != nil {
+ t.Fatal(err)
}
+ nonce, err := util.EncryptionNonce(verifier)
+ if err != nil {
+ t.Fatal(err)
+ }
+ appConf.NotebookCrypto = conf.NewNotebookCrypto()
+ appConf.NotebookCrypto.Enabled = true
+ appConf.NotebookCrypto.MasterSalt = bytes.Repeat([]byte{2}, 16)
+ appConf.NotebookCrypto.KEKVerifier = verifier
+ appConf.NotebookCrypto.VerifierNonce = nonce
+ appConf.NotebookCrypto.AutoLockMinutes = 17
+ prepareBackupForWrite(appConf.NotebookCrypto)
+ appConf.NotebookCrypto.KEKMAC = computeKEKMAC(appConf.NotebookCrypto, kek)
HideConfSecret(appConf)
@@ -89,6 +94,19 @@ func TestHideConfSecretPreservesNotebookCryptoSettings(t *testing.T) {
}
}
+func TestHideConfSecretMasksIncompleteNotebookCryptoAsDisabled(t *testing.T) {
+ appConf := NewAppConf()
+ appConf.System = &conf.System{}
+ appConf.NotebookCrypto = conf.NewNotebookCrypto()
+ appConf.NotebookCrypto.Enabled = true
+
+ HideConfSecret(appConf)
+
+ if appConf.NotebookCrypto.Enabled {
+ t.Fatal("incomplete notebook crypto configuration should not be exposed as enabled")
+ }
+}
+
func TestHideConfSecretHidesAbsolutePaths(t *testing.T) {
appConf := NewAppConf()
appConf.Export = &conf.Export{
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 968a3cd3ee..cca3b928dd 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -53,6 +53,11 @@ const boxEncryptionSpec = 1
var encryptedAssetMagic = []byte{'S', 'Y', 'A', 'E'}
+// IsEncryptedNotebookData 判断数据是否以当前文档或资源密文标识开头。
+func IsEncryptedNotebookData(data []byte) bool {
+ return util.IsCiphertext(data) || bytes.HasPrefix(data, encryptedAssetMagic)
+}
+
const encryptedAssetMetadataMaxSize = 1024 * 1024
const encryptedAssetChunkSize = 1024 * 1024
const encryptedAssetChunkMaxCiphertextSize = encryptedAssetChunkSize + 1024
@@ -204,39 +209,26 @@ func ExportNotebookCryptoBackup() (downloadPath string, err error) {
// 校验为合法 NotebookCrypto 后写回 <DataDir>/.siyuan/notebook-crypto-backup.json 并装回本机 Conf。
// 用于新设备/重装后不依赖同步、手动恢复加密配置(详见设计文档 §4.1)。
// 安全:备份文件不含主密码(salt 不保密、verifier 是密文),导入只恢复配置,解锁仍需主密码。
-// 防呆:本机已启用加密笔记本时拒绝导入,避免覆盖现有 salt/verifier 孤立现有 WrappedDEK。
+// 防呆:本机已有完整且已启用的加密配置时拒绝导入,避免覆盖现有 salt/verifier 孤立现有 WrappedDEK。
// ImportNotebookCryptoBackup 接收用户导入的密钥备份文件内容(JSON 字节)+ 主密码,
// 校验主密码能解开备份里的 verifier 后才写回配置。防止 crafted 备份设置弱 KDFParams 等攻击。
-// 本机已启用时拒绝(详见设计 §4.1):导入会用导入备份的 MasterSalt/KEKVerifier 覆盖当前配置,
-// 若有现存加密笔记本其 WrappedDEK 将被新 KEK 孤立(数据锁死);即使无现存笔记本也拒绝,
-// 避免覆盖后旧主密码失效造成用户困惑。换密钥材料应走“先禁用再导入”。
+// RecoveryRequired 状态允许导入,但候选 KEK 必须能解开所有现存笔记本和已删除笔记本历史。
func ImportNotebookCryptoBackup(data []byte, password string) error {
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
- // 已启用即拒绝(对齐设计 §4.1,与 api handler 注释一致)
Conf.m.RLock()
- enabled := Conf.NotebookCrypto.Enabled
+ current := *Conf.NotebookCrypto
Conf.m.RUnlock()
- if enabled {
+ if current.Enabled && notebookCryptoConfigurationComplete(&current) {
return errors.New(Conf.Language(324))
}
- // 历史目录中存在已删除加密笔记本的历史时拒绝导入:导入会用新 MasterSalt 覆盖当前配置,
- // 这些历史的恢复仍依赖原 MasterSalt,覆盖后永久锁死(与 EnableEncryptedNotebook 的对称守卫一致)
- hasHistory, historyErr := scanEncryptedNotebookHistory()
- if historyErr != nil {
- return fmt.Errorf("check encrypted notebook history failed: %w", historyErr)
- }
- if hasHistory {
- return errors.New(Conf.Language(323))
- }
-
nc := &conf.NotebookCrypto{}
if err := json.Unmarshal(data, nc); err != nil {
return errors.New(Conf.Language(317))
}
- if len(nc.MasterSalt) == 0 || len(nc.KEKVerifier) == 0 {
+ if !notebookCryptoConfigurationComplete(nc) {
return errors.New(Conf.Language(317))
}
@@ -245,9 +237,6 @@ func ImportNotebookCryptoBackup(data []byte, password string) error {
if validErr != nil {
return errors.New(Conf.Language(317))
}
- if nc.Spec != conf.CurrentNotebookCryptoSpec || nc.Checksum == "" || len(nc.KEKMAC) == 0 {
- return errors.New(Conf.Language(317))
- }
kek := util.DeriveKey(password, nc.MasterSalt, params)
defer zeroAndClear(kek)
if nc.Checksum != computeBackupChecksum(nc) {
@@ -261,12 +250,12 @@ func ImportNotebookCryptoBackup(data []byte, password string) error {
return errors.New(Conf.Language(311)) // 主密码错误
}
- // 若已有加密笔记本,校验 KEK 能解密其 WrappedDEK(防止导入 salt 不同的旧备份导致现有数据锁死)
- if !verifyKEKAgainstExistingBoxes(kek) {
+ // 校验 KEK 能解密现存笔记本和已删除笔记本历史中的 WrappedDEK,避免导入不匹配的备份。
+ if !verifyKEKAgainstExistingBoxes(kek) || !verifyKEKAgainstEncryptedHistory(kek) {
return errors.New(Conf.Language(316)) // 密钥不匹配
}
- nc.KDFParams = params // 归一化:确保写回 Conf 的是校验后的参数(含默认值回退)
+ nc.KDFParams = params // 确保写回 Conf 的参数已经通过完整校验。
nc.Enabled = true
// 先写 backup,再提交 conf;backup 失败时 conf 尚未改变,可重试
@@ -293,6 +282,10 @@ func saveNotebookCryptoBackup(kek []byte) error {
nc := *Conf.NotebookCrypto // 值拷贝
prepareBackupForWrite(&nc)
nc.KEKMAC = computeKEKMAC(&nc, kek)
+ if !notebookCryptoConfigurationComplete(&nc) {
+ Conf.m.Unlock()
+ return errors.New("cannot save incomplete notebook crypto configuration")
+ }
Conf.NotebookCrypto.Spec = nc.Spec
Conf.NotebookCrypto.BackupID = nc.BackupID
Conf.NotebookCrypto.CreatedAt = nc.CreatedAt
@@ -321,6 +314,9 @@ func writeNotebookCryptoBackupData(nc *conf.NotebookCrypto, kek []byte) error {
}
prepareBackupForWrite(nc)
nc.KEKMAC = computeKEKMAC(nc, kek)
+ if !notebookCryptoConfigurationComplete(nc) {
+ return errors.New("cannot write incomplete notebook crypto backup")
+ }
backupPath := notebookCryptoBackupPath()
if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {
return fmt.Errorf("mkdir notebook crypto backup dir failed: %w", err)
@@ -382,17 +378,11 @@ func loadNotebookCryptoBackup() (*conf.NotebookCrypto, error) {
if err := json.Unmarshal(data, nc); err != nil {
return nil, err
}
- conf.UpgradeSpec(nc)
if nc.Spec != conf.CurrentNotebookCryptoSpec {
return nil, fmt.Errorf("unsupported notebook crypto backup spec [%d]", nc.Spec)
}
- if nc.Checksum == "" {
- return nil, errors.New("notebook crypto backup checksum is missing")
- }
- expected := computeBackupChecksum(nc)
- if nc.Checksum != expected {
- logging.LogWarnf("notebook crypto backup checksum mismatch: expected %s, got %s", expected, nc.Checksum)
- return nil, errors.New("notebook crypto backup is corrupted (checksum mismatch)")
+ if !notebookCryptoConfigurationComplete(nc) {
+ return nil, errors.New("notebook crypto backup is incomplete or corrupted")
}
return nc, nil
}
@@ -418,6 +408,7 @@ type migrationBoxEntry struct {
NewSpec int `json:"newSpec"`
NewWrappedDEK []byte `json:"newWrappedDEK"`
NewWrapNonce []byte `json:"newWrapNonce"`
+ Metadata []byte `json:"metadata"`
}
func masterPasswordMigrationPath() string {
@@ -514,6 +505,7 @@ func recoverMasterPasswordMigration() {
WrappedDEK: entry.NewWrappedDEK,
WrapNonce: entry.NewWrapNonce,
Spec: entry.NewSpec,
+ Metadata: entry.Metadata,
CreatedAt: time.Now().UnixMilli(),
}
if saveErr := box.SaveConf(boxConf); saveErr != nil {
@@ -523,7 +515,8 @@ func recoverMasterPasswordMigration() {
}
}
// 若 WrappedDEK 已匹配则跳过写 conf,但仍需确保 per-notebook backup 是最新的
- if bytes.Equal(boxConf.BoxCrypt.WrappedDEK, entry.NewWrappedDEK) {
+ if bytes.Equal(boxConf.BoxCrypt.WrappedDEK, entry.NewWrappedDEK) &&
+ bytes.Equal(boxConf.BoxCrypt.Metadata, entry.Metadata) {
if writeErr := writeNotebookCryptBackup(entry.BoxID, boxConf.BoxCrypt); writeErr != nil {
logging.LogErrorf("refresh box crypt backup [%s] failed: %s", entry.BoxID, writeErr)
return // 保留 manifest
@@ -533,6 +526,7 @@ func recoverMasterPasswordMigration() {
boxConf.BoxCrypt.WrappedDEK = entry.NewWrappedDEK
boxConf.BoxCrypt.Spec = entry.NewSpec
boxConf.BoxCrypt.WrapNonce = entry.NewWrapNonce
+ boxConf.BoxCrypt.Metadata = append([]byte(nil), entry.Metadata...)
if saveErr := box.SaveConf(boxConf); saveErr != nil {
logging.LogErrorf("recover box conf [%s] failed: %s", entry.BoxID, saveErr)
return // 保留 manifest
@@ -571,12 +565,17 @@ func hasEncryptedNotebook() (bool, error) {
// notebook-crypt-backup.json(专为 box 删除后的恢复设计),或 conf.json 标记 Encrypted=true。
// boxID 用 ast.IsNodeIDPattern 校验,避免误判 assets/storage 等非 box 目录。
func scanEncryptedNotebookHistory() (bool, error) {
+ boxDirs, err := encryptedNotebookHistoryBoxDirs()
+ return len(boxDirs) > 0, err
+}
+
+func encryptedNotebookHistoryBoxDirs() (ret []string, err error) {
entries, err := os.ReadDir(util.HistoryDir)
if err != nil {
if os.IsNotExist(err) {
- return false, nil
+ return nil, nil
}
- return false, fmt.Errorf("read history dir failed: %w", err)
+ return nil, fmt.Errorf("read history dir failed: %w", err)
}
for _, entry := range entries {
if !entry.IsDir() {
@@ -586,7 +585,7 @@ func scanEncryptedNotebookHistory() (bool, error) {
snapshotDir := filepath.Join(util.HistoryDir, entry.Name())
boxEntries, readErr := os.ReadDir(snapshotDir)
if readErr != nil {
- return false, fmt.Errorf("read history snapshot [%s] failed: %w", entry.Name(), readErr)
+ return nil, fmt.Errorf("read history snapshot [%s] failed: %w", entry.Name(), readErr)
}
for _, boxEntry := range boxEntries {
if !boxEntry.IsDir() || !ast.IsNodeIDPattern(boxEntry.Name()) {
@@ -594,14 +593,81 @@ func scanEncryptedNotebookHistory() (bool, error) {
}
encrypted, checkErr := isEncryptedHistoryBoxDir(filepath.Join(snapshotDir, boxEntry.Name()))
if checkErr != nil {
- return false, checkErr
+ return nil, checkErr
}
if encrypted {
- return true, nil
+ ret = append(ret, filepath.Join(snapshotDir, boxEntry.Name()))
}
}
}
- return false, nil
+ return ret, nil
+}
+
+func verifyKEKAgainstEncryptedHistory(kek []byte) bool {
+ boxDirs, err := encryptedNotebookHistoryBoxDirs()
+ if err != nil {
+ logging.LogErrorf("list encrypted notebook history failed: %s", err)
+ return false
+ }
+ for _, boxDir := range boxDirs {
+ boxID := filepath.Base(boxDir)
+ candidates, readErr := readEncryptedHistoryBoxEncryptionCandidates(boxDir)
+ if readErr != nil {
+ logging.LogErrorf("read encrypted notebook history [%s] failed: %s", boxID, readErr)
+ return false
+ }
+ matched := false
+ for _, candidate := range candidates {
+ dek, decryptErr := decryptWrappedDEK(boxID, candidate, kek)
+ if decryptErr == nil {
+ zeroAndClear(dek)
+ matched = true
+ break
+ }
+ }
+ if !matched {
+ return false
+ }
+ }
+ return true
+}
+
+func readEncryptedHistoryBoxEncryptionCandidates(boxDir string) (ret []*conf.BoxEncryption, err error) {
+ var candidateErrors []error
+ backupPath := filepath.Join(boxDir, ".siyuan", "notebook-crypt-backup.json")
+ if filelock.IsExist(backupPath) {
+ if candidate, readErr := readBoxEncryptionFile(backupPath); readErr == nil {
+ ret = append(ret, candidate)
+ } else {
+ candidateErrors = append(candidateErrors, readErr)
+ }
+ }
+
+ confPath := filepath.Join(boxDir, ".siyuan", "conf.json")
+ if filelock.IsExist(confPath) {
+ data, readErr := filelock.ReadFile(confPath)
+ if readErr != nil {
+ candidateErrors = append(candidateErrors, readErr)
+ } else {
+ boxConf := conf.NewBoxConf()
+ if readErr = gulu.JSON.UnmarshalJSON(data, boxConf); readErr != nil {
+ candidateErrors = append(candidateErrors, readErr)
+ } else if boxConf.Encrypted && boxConf.BoxCrypt != nil {
+ if readErr = validateBoxEncryption(boxConf.BoxCrypt); readErr != nil {
+ candidateErrors = append(candidateErrors, readErr)
+ } else {
+ ret = append(ret, boxConf.BoxCrypt)
+ }
+ }
+ }
+ }
+ if len(ret) > 0 {
+ return ret, nil
+ }
+ if len(candidateErrors) > 0 {
+ return nil, errors.Join(candidateErrors...)
+ }
+ return nil, errors.New("encrypted notebook history has no valid key material")
}
// HasEncryptedNotebookHistory 在扫描失败时按存在依赖处理,避免调用方因 I/O 或权限错误删除恢复材料。
@@ -666,44 +732,35 @@ func EnableEncryptedNotebook(password string) error {
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
- Conf.m.Lock()
- if Conf.NotebookCrypto.Enabled {
- Conf.m.Unlock()
+ Conf.m.RLock()
+ current := *Conf.NotebookCrypto
+ Conf.m.RUnlock()
+ if current.Enabled && notebookCryptoConfigurationComplete(&current) {
return errors.New(Conf.Language(312))
}
- Conf.m.Unlock()
- // 防呆:若已存在加密笔记本(磁盘上有 Encrypted=true 的 box),不能重新生成 MasterSalt。
- // conf.json 丢失后重新启用会派生新 KEK,导致旧 WrappedDEK 用相同主密码也无法解开(数据永久锁死)。
- // 此时必须从 DataDir 备份恢复原 MasterSalt/KEKVerifier,并用主密码校验通过后才算恢复成功。
hasEncrypted, listErr := hasEncryptedNotebook()
if listErr != nil {
return fmt.Errorf("list encrypted notebooks failed: %w", listErr)
}
- if hasEncrypted {
+ hasHistory, historyErr := scanEncryptedNotebookHistory()
+ if historyErr != nil {
+ return fmt.Errorf("check encrypted notebook history failed: %w", historyErr)
+ }
+ hasBackup := filelock.IsExist(notebookCryptoBackupPath())
+ if hasEncrypted || hasHistory || hasBackup {
+ // 现存笔记本、已删除笔记本历史或全局备份均表示已有密钥域,必须恢复并认证,不能生成新 MasterSalt。
if _, restoreErr := tryRestoreNotebookCryptoFromBackupLocked(password); restoreErr != nil {
- // 恢复失败:主密码错(恢复函数返回 311 文案)保持原提示;其余(备份缺失/损坏)提示需恢复备份
if strings.Contains(restoreErr.Error(), Conf.Language(311)) {
- return errors.New(Conf.Language(311)) // 主密码错误
+ return errors.New(Conf.Language(311))
}
return errors.New(Conf.Language(315))
}
- logging.LogInfof("encrypted notebook re-enabled with restored master key material from backup")
+ logging.LogInfof("encrypted notebook re-enabled with authenticated recovery key material")
return nil
}
- // 防呆:历史目录中存在已删除加密笔记本的历史快照时,禁止重新生成 MasterSalt。
- // 这些历史的恢复仍依赖原 MasterSalt/KEKVerifier,生成新 salt 会让其永久锁死(违反设计 §4.1
- // “内核可枚举的加密恢复数据存在时禁止重新生成 MasterSalt”)。此时应先恢复全局密钥备份或清除历史。
- hasHistory, historyErr := scanEncryptedNotebookHistory()
- if historyErr != nil {
- return fmt.Errorf("check encrypted notebook history failed: %w", historyErr)
- }
- if hasHistory {
- return errors.New(Conf.Language(323))
- }
-
- // 不存在加密笔记本且无历史依赖:正常生成新 MasterSalt
+ // 不存在任何密钥依赖或备份时生成新的 MasterSalt。
salt, err := util.GenerateSalt()
if err != nil {
return err
@@ -837,14 +894,14 @@ func tryRestoreNotebookCryptoFromBackupLocked(password string) (kek []byte, err
}
params, _ := util.ValidateArgon2Params(backup.KDFParams)
- backup.KDFParams = params // 归一化:确保写回 Conf 的是校验后的参数(含默认值回退)
+ backup.KDFParams = params // 确保写回 Conf 的参数已经通过完整校验。
backup.Enabled = true
Conf.m.Lock()
backup.AutoLockMinutes = Conf.NotebookCrypto.AutoLockMinutes
*Conf.NotebookCrypto = *backup
Conf.m.Unlock()
Conf.Save()
- // 恢复成功后同步重写备份(补全 KEKMAC,升级旧备份为 Spec=1)。
+ // 恢复成功后同步重写备份,确保配置和备份内容一致。
// 调用方已持有 notebookCryptoMu,且 writeNotebookCryptoBackupData 不再申请该锁,故无死锁;
// 同步写避免与 ChangeMasterPassword 的并发备份写竞争同一文件(lost update 导致 verifier 被回退)。
nc := *backup
@@ -876,7 +933,7 @@ func deriveNotebookCryptoBackupCandidate(password string) (backup *conf.Notebook
zeroAndClear(kek)
return nil, nil, errors.New(Conf.Language(316))
}
- if !verifyKEKAgainstExistingBoxes(kek) {
+ if !verifyKEKAgainstExistingBoxes(kek) || !verifyKEKAgainstEncryptedHistory(kek) {
zeroAndClear(kek)
return nil, nil, errors.New(Conf.Language(316))
}
@@ -935,8 +992,7 @@ func deriveKEK(password string) ([]byte, error) {
bytes.Equal(backup.MasterSalt, nc.MasterSalt) &&
bytes.Equal(backup.KEKVerifier, nc.KEKVerifier) &&
backup.KDFParams == nc.KDFParams
- localAuthenticated := nc.Spec == conf.CurrentNotebookCryptoSpec && nc.Checksum != "" &&
- len(nc.KEKMAC) > 0 && verifyKEKMAC(&nc, kek)
+ localAuthenticated := notebookCryptoConfigurationComplete(&nc) && verifyKEKMAC(&nc, kek)
backupAuthenticated := backupMatchesConf && backup.Spec == conf.CurrentNotebookCryptoSpec &&
backup.Checksum != "" && len(backup.KEKMAC) > 0 && verifyKEKMAC(backup, kek)
if !localAuthenticated && !backupAuthenticated {
@@ -947,7 +1003,15 @@ func deriveKEK(password string) ([]byte, error) {
zeroAndClear(kek)
return nil, errors.New(Conf.Language(315))
}
- if !backupAuthenticated {
+ if !localAuthenticated {
+ backup.Enabled = true
+ backup.AutoLockMinutes = nc.AutoLockMinutes
+ Conf.m.Lock()
+ *Conf.NotebookCrypto = *backup
+ Conf.m.Unlock()
+ Conf.Save()
+ logging.LogInfof("repaired notebook crypto configuration from authenticated backup")
+ } else if !backupAuthenticated {
// 同步备份可能属于另一轮完整改密;只要本地配置仍与全部笔记本一致,就继续使用本地配置,
// 不覆盖候选备份,等待其余 WrappedDEK 同步完成后由新密码采用。
logging.LogWarnf("notebook crypto backup differs from usable local configuration; keeping both candidates")
@@ -1011,20 +1075,38 @@ func decryptBoxCrypt(boxID string, kek []byte) (dek []byte, boxCrypt *conf.BoxEn
// UnlockBox 用主密码派生 KEK,解出该笔记本的 DEK 并缓存。KEK 用完即弃,不全局缓存。
// 每次调用都跑一次 Argon2id(约 1 秒),严格满足"每笔记本单独解锁"语义。
-func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error {
- if boxEnc == nil || len(boxEnc.WrappedDEK) == 0 {
- return errors.New("no encrypted key material for box")
- }
+func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) (err error) {
invalidateEncryptedPublishAccessCache()
// 全局配置锁先于笔记本生命周期锁获取(设计 §17 锁顺序约定),避免与持子系统锁后回取配置锁的路径死锁。
// notebookCryptoMu 持锁期间调用的 deriveKEK/conf 修复只申请 Conf.m/cachedDEKsLock,不回取 box 生命周期锁。
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
+ releaseTransition := holdEncryptedBoxTransition(boxID)
+ defer releaseTransition()
+ if _, busy := boxLock.Load(boxID); busy {
+ return errors.New(Conf.language(239))
+ }
+ if boxEnc == nil || len(boxEnc.WrappedDEK) == 0 {
+ setEncryptedBoxState(boxID, EncryptedBoxStateError)
+ return errors.New("no encrypted key material for box")
+ }
+ if IsBoxUnlocked(boxID) {
+ if GetEncryptedBoxState(boxID) == EncryptedBoxStateError {
+ return errors.New(Conf.Language(316))
+ }
+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)
+ return nil
+ }
+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocking)
// 获取 box 写锁,与 LockBox/unmount0 串行化,防止并发锁/解锁导致 db/DEK 状态不一致
acquireBoxWriteLock(boxID)
- defer releaseBoxWriteLock(boxID)
+ finalState := EncryptedBoxStateLocked
+ defer func() {
+ releaseBoxWriteLock(boxID)
+ setEncryptedBoxState(boxID, finalState)
+ }()
kek, err := deriveKEK(password)
if err != nil {
@@ -1035,21 +1117,38 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error
// 用 decryptBoxCrypt 统一处理解密 + backup fallback + conf 修复
dek, trustedCrypt, err := decryptBoxCrypt(boxID, kek)
if err != nil {
+ finalState = EncryptedBoxStateError
return errors.New(Conf.Language(316))
}
+ dekCached := false
+ defer func() {
+ if !dekCached {
+ zeroAndClear(dek)
+ }
+ }()
boxEnc = trustedCrypt
+ metadataConf := &conf.BoxConf{Encrypted: true, BoxCrypt: boxEnc}
+ if err = decryptBoxMetadata(boxID, metadataConf, dek); err != nil {
+ finalState = EncryptedBoxStateError
+ return errors.New(Conf.Language(316))
+ }
// 持锁保护"开 db + 缓存 DEK"的原子性,避免与并发的 LockBox 导致 db/DEK 不一致
cachedDEKsLock.Lock()
- defer cachedDEKsLock.Unlock()
if err = sql.OpenEncryptedDB(boxID, dek); err != nil {
+ cachedDEKsLock.Unlock()
+ finalState = EncryptedBoxStateError
return err
}
if err = treenode.OpenEncryptedBlockTreeDB(boxID, dek); err != nil {
sql.RemoveEncryptedDBFile(boxID) // 清理已创建的 content db 文件,避免遗留空加密库
+ cachedDEKsLock.Unlock()
+ finalState = EncryptedBoxStateError
return err
}
cachedDEKs[boxID] = dek
+ dekCached = true
+ cachedDEKsLock.Unlock()
// 初始化自动锁定访问时间戳,记录解锁时刻
newVal := &atomic.Int64{}
@@ -1075,6 +1174,7 @@ func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error
logging.LogWarnf("write notebook crypt backup [%s] failed: %s", boxID, err)
}
}
+ finalState = EncryptedBoxStateUnlocked
return nil
}
@@ -1088,9 +1188,23 @@ func IsBoxUnlocked(boxID string) bool {
// LockBox 清除指定笔记本的 DEK 并删除其加密 db 文件。Unmount 单个加密笔记本或手动锁定时调用。
func LockBox(boxID string) {
+ lockBoxWithPreparation(boxID, nil)
+}
+
+// lockBoxWithPreparation 在关闭新操作并等待在途操作结束后执行锁定前准备,随后清除密钥和加密数据库。
+func lockBoxWithPreparation(boxID string, prepare func()) {
+ releaseTransition := holdEncryptedBoxTransition(boxID)
+ defer releaseTransition()
+ beginEncryptedBoxLock(boxID)
FlushTxQueue()
+ if prepare != nil {
+ prepare()
+ }
acquireBoxWriteLock(boxID)
- defer releaseBoxWriteLock(boxID)
+ defer func() {
+ releaseBoxWriteLock(boxID)
+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)
+ }()
lockBoxHeld(boxID)
// 单 box 锁定时需要在写锁保护下刷新全局缓存,避免锁定与缓存读取之间出现明文窗口。
cache.ClearTreeCache()
@@ -1182,9 +1296,39 @@ func wrappedDEKAAD(boxID string) []byte {
}
func decryptWrappedDEK(boxID string, enc *conf.BoxEncryption, kek []byte) ([]byte, error) {
+ if err := validateWrappedDEKEnvelope(enc); err != nil {
+ return nil, err
+ }
return util.DecryptWithAAD(kek, enc.WrappedDEK, wrappedDEKAAD(boxID))
}
+func validateWrappedDEKEnvelope(enc *conf.BoxEncryption) error {
+ if enc == nil || enc.Spec != boxEncryptionSpec {
+ return errors.New("unsupported encrypted notebook key envelope")
+ }
+ if enc.CreatedAt <= 0 {
+ return errors.New("encrypted notebook key envelope creation time is missing")
+ }
+ nonce, err := util.EncryptionNonce(enc.WrappedDEK)
+ if err != nil {
+ return fmt.Errorf("invalid encrypted notebook key envelope: %w", err)
+ }
+ if !bytes.Equal(nonce, enc.WrapNonce) {
+ return errors.New("encrypted notebook key envelope nonce mismatch")
+ }
+ return nil
+}
+
+func validateBoxEncryption(enc *conf.BoxEncryption) error {
+ if err := validateWrappedDEKEnvelope(enc); err != nil {
+ return err
+ }
+ if _, err := util.EncryptionNonce(enc.Metadata); err != nil {
+ return fmt.Errorf("invalid encrypted notebook metadata envelope: %w", err)
+ }
+ return nil
+}
+
// mustEncryptionNonce 从刚刚成功生成的密文中提取 nonce。生成密文格式错误属于内部不变量被破坏,直接终止执行。
func mustEncryptionNonce(ciphertext []byte) []byte {
nonce, err := util.EncryptionNonce(ciphertext)
@@ -1270,7 +1414,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
}
var entries []migrationBoxEntry
for _, id := range encBoxIDs {
- dek, _, dErr := decryptBoxCrypt(id, oldKEK)
+ dek, boxCrypt, dErr := decryptBoxCrypt(id, oldKEK)
if dErr != nil {
return errors.New(Conf.Language(316) + " [box=" + id + "]")
}
@@ -1283,6 +1427,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
NewSpec: boxEncryptionSpec,
NewWrappedDEK: newWrapped,
NewWrapNonce: mustEncryptionNonce(newWrapped),
+ Metadata: append([]byte(nil), boxCrypt.Metadata...),
})
}
@@ -1334,6 +1479,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
WrappedDEK: entry.NewWrappedDEK,
WrapNonce: entry.NewWrapNonce,
Spec: entry.NewSpec,
+ Metadata: entry.Metadata,
CreatedAt: time.Now().UnixMilli(),
}
if saveErr := box.SaveConf(boxConf); saveErr != nil {
@@ -1345,6 +1491,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
boxConf.BoxCrypt.WrappedDEK = entry.NewWrappedDEK
boxConf.BoxCrypt.Spec = entry.NewSpec
boxConf.BoxCrypt.WrapNonce = entry.NewWrapNonce
+ boxConf.BoxCrypt.Metadata = append([]byte(nil), entry.Metadata...)
if err = box.SaveConf(boxConf); err != nil {
return fmt.Errorf("%w: %s", errMasterPasswordMigrationPending,
fmt.Sprintf(Conf.Language(320), entry.BoxID+": save conf failed: "+err.Error()))
@@ -1424,6 +1571,8 @@ func needWriteNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) bool
}
return !bytes.Equal(existing.WrappedDEK, crypt.WrappedDEK) ||
!bytes.Equal(existing.WrapNonce, crypt.WrapNonce) ||
+ !bytes.Equal(existing.Metadata, crypt.Metadata) ||
+ existing.Spec != crypt.Spec ||
existing.CreatedAt != crypt.CreatedAt
}
@@ -1437,6 +1586,7 @@ func DeepCopyBoxEncryption(src *conf.BoxEncryption) *conf.BoxEncryption {
Spec: src.Spec,
WrappedDEK: append([]byte(nil), src.WrappedDEK...),
WrapNonce: append([]byte(nil), src.WrapNonce...),
+ Metadata: append([]byte(nil), src.Metadata...),
CreatedAt: src.CreatedAt,
}
}
@@ -1892,6 +2042,9 @@ func notebookCryptBackupPath(boxID string) string {
// writeNotebookCryptBackup 写入加密笔记本的 BoxCrypt 备份。
// 仅在 Encrypted=true 的笔记本上调用,配合 CreateEncryptedBox / ChangeMasterPassword 写入。
func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {
+ if err := validateBoxEncryption(crypt); err != nil {
+ return err
+ }
backupPath := notebookCryptBackupPath(boxID)
if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {
return fmt.Errorf("mkdir notebook crypt backup dir failed: %w", err)
@@ -1913,6 +2066,10 @@ func readNotebookCryptBackup(boxID string) (*conf.BoxEncryption, error) {
if !filelock.IsExist(backupPath) {
return nil, nil
}
+ return readBoxEncryptionFile(backupPath)
+}
+
+func readBoxEncryptionFile(backupPath string) (*conf.BoxEncryption, error) {
data, err := filelock.ReadFile(backupPath)
if err != nil {
return nil, fmt.Errorf("read notebook crypt backup failed: %w", err)
@@ -1921,6 +2078,9 @@ func readNotebookCryptBackup(boxID string) (*conf.BoxEncryption, error) {
if err = gulu.JSON.UnmarshalJSON(data, &crypt); err != nil {
return nil, fmt.Errorf("unmarshal notebook crypt backup failed: %w", err)
}
+ if err = validateBoxEncryption(&crypt); err != nil {
+ return nil, err
+ }
return &crypt, nil
}
@@ -1962,9 +2122,9 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
defer notebookCryptoMu.Unlock()
Conf.m.RLock()
- enabled := Conf.NotebookCrypto.Enabled
+ notebookCrypto := *Conf.NotebookCrypto
Conf.m.RUnlock()
- if !enabled {
+ if !notebookCrypto.Enabled || !notebookCryptoConfigurationComplete(&notebookCrypto) {
return "", errors.New(Conf.Language(310))
}
@@ -1978,6 +2138,7 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
if err != nil {
return "", err
}
+ setEncryptedBoxState(id, EncryptedBoxStateUnlocking)
// 若后续步骤失败,清理已创建的 box 目录和加密 db 文件,避免半创建状态
createdBoxID := id
@@ -1997,6 +2158,9 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
boxConf := box.GetConf()
boxConf.Encrypted = true
boxConf.BoxCrypt = enc
+ if err = encryptBoxMetadata(id, boxConf, dek); err != nil {
+ return "", fmt.Errorf("encrypt notebook metadata failed: %w", err)
+ }
if err = box.SaveConf(boxConf); err != nil {
return "", fmt.Errorf("save encrypted notebook conf failed: %w", err)
}
@@ -2034,6 +2198,7 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
newVal.Store(time.Now().UnixNano())
boxLastAccess.Store(id, newVal)
+ setEncryptedBoxState(id, EncryptedBoxStateUnlocked)
IncSync()
return id, nil
}
@@ -2060,6 +2225,7 @@ func cleanupFailedEncryptedBox(boxID string) {
cachedDEKsLock.Unlock()
sql.RemoveEncryptedDBFile(boxID)
treenode.RemoveEncryptedBlockTreeDBFile(boxID)
+ removeEncryptedBoxLifecycle(boxID)
if err := filelock.Remove(boxDir); err != nil {
logging.LogErrorf("cleanup failed encrypted box [%s]: %s", boxID, err)
}
diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.go
new file mode 100644
index 0000000000..6bbd534f3e
--- /dev/null
+++ b/kernel/model/crypto_lifecycle.go
@@ -0,0 +1,259 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "sort"
+ "sync"
+
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type NotebookCryptoState string
+
+const (
+ NotebookCryptoStateDisabled NotebookCryptoState = "Disabled"
+ NotebookCryptoStateEnabled NotebookCryptoState = "Enabled"
+ NotebookCryptoStateRecoveryRequired NotebookCryptoState = "RecoveryRequired"
+)
+
+type EncryptedBoxState string
+
+const (
+ EncryptedBoxStateLocked EncryptedBoxState = "Locked"
+ EncryptedBoxStateUnlocking EncryptedBoxState = "Unlocking"
+ EncryptedBoxStateUnlocked EncryptedBoxState = "Unlocked"
+ EncryptedBoxStateLocking EncryptedBoxState = "Locking"
+ EncryptedBoxStateError EncryptedBoxState = "Error"
+)
+
+type encryptedBoxLifecycle struct {
+ transition sync.Mutex
+ lock sync.Mutex
+ condition *sync.Cond
+ state EncryptedBoxState
+ activeOperations int
+}
+
+func holdEncryptedBoxTransition(boxID string) func() {
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.transition.Lock()
+ return lifecycle.transition.Unlock
+}
+
+var encryptedBoxLifecycles sync.Map
+
+func getEncryptedBoxLifecycle(boxID string) *encryptedBoxLifecycle {
+ created := &encryptedBoxLifecycle{state: EncryptedBoxStateLocked}
+ created.condition = sync.NewCond(&created.lock)
+ actual, _ := encryptedBoxLifecycles.LoadOrStore(boxID, created)
+ return actual.(*encryptedBoxLifecycle)
+}
+
+func setEncryptedBoxState(boxID string, state EncryptedBoxState) {
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ lifecycle.state = state
+ lifecycle.condition.Broadcast()
+ lifecycle.lock.Unlock()
+}
+
+func removeEncryptedBoxLifecycle(boxID string) {
+ encryptedBoxLifecycles.Delete(boxID)
+}
+
+// GetEncryptedBoxState 返回加密笔记本当前的显式生命周期状态。
+func GetEncryptedBoxState(boxID string) EncryptedBoxState {
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ defer lifecycle.lock.Unlock()
+ if lifecycle.state == EncryptedBoxStateLocked && IsBoxUnlocked(boxID) {
+ lifecycle.state = EncryptedBoxStateUnlocked
+ }
+ return lifecycle.state
+}
+
+// NotebookCryptoLifecycleState 返回全局加密功能状态。
+func NotebookCryptoLifecycleState(hasRecoveryDependency bool) NotebookCryptoState {
+ Conf.m.RLock()
+ notebookCrypto := *Conf.NotebookCrypto
+ Conf.m.RUnlock()
+ if notebookCrypto.Enabled {
+ if notebookCryptoConfigurationComplete(&notebookCrypto) {
+ return NotebookCryptoStateEnabled
+ }
+ return NotebookCryptoStateRecoveryRequired
+ }
+ if hasRecoveryDependency || filelock.IsExist(notebookCryptoBackupPath()) {
+ return NotebookCryptoStateRecoveryRequired
+ }
+ return NotebookCryptoStateDisabled
+}
+
+func notebookCryptoConfigurationComplete(notebookCrypto *conf.NotebookCrypto) bool {
+ if notebookCrypto == nil ||
+ notebookCrypto.Spec != conf.CurrentNotebookCryptoSpec ||
+ len(notebookCrypto.MasterSalt) != 16 ||
+ notebookCrypto.BackupID == "" ||
+ notebookCrypto.CreatedAt <= 0 ||
+ notebookCrypto.Checksum == "" ||
+ len(notebookCrypto.KEKMAC) != 32 {
+ return false
+ }
+ if _, err := util.ValidateArgon2Params(notebookCrypto.KDFParams); err != nil {
+ return false
+ }
+ nonce, err := util.EncryptionNonce(notebookCrypto.KEKVerifier)
+ if err != nil || !bytes.Equal(nonce, notebookCrypto.VerifierNonce) {
+ return false
+ }
+ return notebookCrypto.Checksum == computeBackupChecksum(notebookCrypto)
+}
+
+// AcquireEncryptedBoxOperation 为需要把明文结果保留到响应结束的操作取得准入租约。
+func AcquireEncryptedBoxOperation(boxID string) error {
+ if boxID == "" || !IsEncryptedBox(boxID) {
+ return nil
+ }
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ defer lifecycle.lock.Unlock()
+ if lifecycle.state == EncryptedBoxStateLocked && IsBoxUnlocked(boxID) {
+ lifecycle.state = EncryptedBoxStateUnlocked
+ }
+ if lifecycle.state != EncryptedBoxStateUnlocked {
+ return errors.New("encrypted notebook is not unlocked")
+ }
+ lifecycle.activeOperations++
+ return nil
+}
+
+// ReleaseEncryptedBoxOperation 释放响应级准入租约。
+func ReleaseEncryptedBoxOperation(boxID string) {
+ if boxID == "" {
+ return
+ }
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ if lifecycle.activeOperations > 0 {
+ lifecycle.activeOperations--
+ }
+ lifecycle.condition.Broadcast()
+ lifecycle.lock.Unlock()
+}
+
+func beginEncryptedBoxLock(boxID string) {
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ lifecycle.state = EncryptedBoxStateLocking
+ for lifecycle.activeOperations > 0 {
+ lifecycle.condition.Wait()
+ }
+ lifecycle.lock.Unlock()
+}
+
+type encryptedBoxOperationScope struct {
+ lock sync.Mutex
+ boxIDs []string
+ boxIDSet map[string]struct{}
+ closed bool
+}
+
+type encryptedBoxOperationScopeKey struct{}
+
+// WithEncryptedBoxOperationScope 创建覆盖整个外层响应过程的租约作用域。
+func WithEncryptedBoxOperationScope(ctx context.Context) (context.Context, func()) {
+ scope := &encryptedBoxOperationScope{boxIDSet: map[string]struct{}{}}
+ scopedContext := context.WithValue(ctx, encryptedBoxOperationScopeKey{}, scope)
+ return scopedContext, scope.release
+}
+
+// AcquireEncryptedBoxOperations 按固定顺序取得多个笔记本的响应级租约。
+func AcquireEncryptedBoxOperations(ctx context.Context, boxIDs []string) (release func(), err error) {
+ unique := map[string]struct{}{}
+ for _, boxID := range boxIDs {
+ if boxID != "" && IsEncryptedBox(boxID) {
+ unique[boxID] = struct{}{}
+ }
+ }
+ sortedBoxIDs := make([]string, 0, len(unique))
+ for boxID := range unique {
+ sortedBoxIDs = append(sortedBoxIDs, boxID)
+ }
+ sort.Strings(sortedBoxIDs)
+
+ if scope, ok := ctx.Value(encryptedBoxOperationScopeKey{}).(*encryptedBoxOperationScope); ok {
+ err = scope.acquire(sortedBoxIDs)
+ return func() {}, err
+ }
+
+ var acquired []string
+ for _, boxID := range sortedBoxIDs {
+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {
+ for i := len(acquired) - 1; i >= 0; i-- {
+ ReleaseEncryptedBoxOperation(acquired[i])
+ }
+ return func() {}, err
+ }
+ acquired = append(acquired, boxID)
+ }
+ return func() {
+ for i := len(acquired) - 1; i >= 0; i-- {
+ ReleaseEncryptedBoxOperation(acquired[i])
+ }
+ }, nil
+}
+
+func (scope *encryptedBoxOperationScope) acquire(boxIDs []string) error {
+ scope.lock.Lock()
+ defer scope.lock.Unlock()
+ if scope.closed {
+ return errors.New("encrypted notebook operation scope is closed")
+ }
+ for _, boxID := range boxIDs {
+ if _, exists := scope.boxIDSet[boxID]; exists {
+ continue
+ }
+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {
+ return err
+ }
+ scope.boxIDSet[boxID] = struct{}{}
+ scope.boxIDs = append(scope.boxIDs, boxID)
+ }
+ return nil
+}
+
+func (scope *encryptedBoxOperationScope) release() {
+ scope.lock.Lock()
+ if scope.closed {
+ scope.lock.Unlock()
+ return
+ }
+ scope.closed = true
+ boxIDs := append([]string(nil), scope.boxIDs...)
+ scope.boxIDs = nil
+ scope.boxIDSet = nil
+ scope.lock.Unlock()
+ for i := len(boxIDs) - 1; i >= 0; i-- {
+ ReleaseEncryptedBoxOperation(boxIDs[i])
+ }
+}
diff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.go
new file mode 100644
index 0000000000..cd13cae43f
--- /dev/null
+++ b/kernel/model/crypto_lifecycle_test.go
@@ -0,0 +1,452 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/88250/gulu"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestEncryptedBoxLifecycleWaitsForActiveOperations(t *testing.T) {
+ boxID := "20260731160000-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+
+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)
+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {
+ t.Fatalf("acquire encrypted notebook operation failed: %v", err)
+ }
+
+ done := make(chan struct{})
+ go func() {
+ releaseTransition := holdEncryptedBoxTransition(boxID)
+ beginEncryptedBoxLock(boxID)
+ cachedDEKsLock.Lock()
+ if cached, ok := cachedDEKs[boxID]; ok {
+ zeroAndClear(cached)
+ delete(cachedDEKs, boxID)
+ }
+ cachedDEKsLock.Unlock()
+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)
+ releaseTransition()
+ close(done)
+ }()
+
+ deadline := time.Now().Add(time.Second)
+ for GetEncryptedBoxState(boxID) != EncryptedBoxStateLocking && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateLocking {
+ t.Fatalf("expected Locking state, got %s", state)
+ }
+ select {
+ case <-done:
+ t.Fatal("lock transition completed before the active operation was released")
+ default:
+ }
+ if err := AcquireEncryptedBoxOperation(boxID); err == nil {
+ t.Fatal("Locking state admitted a new operation")
+ }
+
+ ReleaseEncryptedBoxOperation(boxID)
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("lock transition did not resume after the active operation ended")
+ }
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateLocked {
+ t.Fatalf("expected Locked state, got %s", state)
+ }
+}
+
+func TestEncryptedBoxLockPreparationWaitsForActiveOperations(t *testing.T) {
+ boxID := "20260731160005-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+
+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)
+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {
+ t.Fatalf("acquire encrypted notebook operation failed: %v", err)
+ }
+
+ prepared := make(chan struct{})
+ done := make(chan struct{})
+ go func() {
+ lockBoxWithPreparation(boxID, func() {
+ close(prepared)
+ })
+ close(done)
+ }()
+
+ deadline := time.Now().Add(time.Second)
+ for GetEncryptedBoxState(boxID) != EncryptedBoxStateLocking && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateLocking {
+ t.Fatalf("expected Locking state, got %s", state)
+ }
+ select {
+ case <-prepared:
+ t.Fatal("lock preparation ran before the active operation was released")
+ default:
+ }
+
+ ReleaseEncryptedBoxOperation(boxID)
+ select {
+ case <-prepared:
+ case <-time.After(time.Second):
+ t.Fatal("lock preparation did not run after the active operation ended")
+ }
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("lock transition did not finish after preparation")
+ }
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateLocked {
+ t.Fatalf("expected Locked state, got %s", state)
+ }
+ if IsBoxUnlocked(boxID) {
+ t.Fatal("locked notebook retained its DEK")
+ }
+}
+
+func TestEncryptedBoxOperationReleaseSurvivesNotebookRemoval(t *testing.T) {
+ boxID := "20260731160004-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+
+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)
+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {
+ t.Fatalf("acquire encrypted notebook operation failed: %v", err)
+ }
+ if err := os.RemoveAll(filepath.Join(util.DataDir, boxID)); err != nil {
+ t.Fatal(err)
+ }
+ ReleaseEncryptedBoxOperation(boxID)
+
+ lifecycle := getEncryptedBoxLifecycle(boxID)
+ lifecycle.lock.Lock()
+ activeOperations := lifecycle.activeOperations
+ lifecycle.lock.Unlock()
+ if activeOperations != 0 {
+ t.Fatalf("expected no active operations after release, got %d", activeOperations)
+ }
+}
+
+func TestEncryptedBoxMetadataIsNotStoredInPlaintext(t *testing.T) {
+ boxID := "20260731160001-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ boxConf.Icon = "1f512"
+ boxConf.Sort = 42
+ boxConf.SortMode = util.SortModeCustom
+ if err := box.SaveConf(boxConf); err != nil {
+ t.Fatalf("save encrypted notebook configuration failed: %v", err)
+ }
+
+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")
+ data, err := os.ReadFile(confPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(data, []byte("1f512")) {
+ t.Fatal("encrypted notebook icon was stored in plaintext")
+ }
+ raw := conf.NewBoxConf()
+ if err = gulu.JSON.UnmarshalJSON(data, raw); err != nil {
+ t.Fatal(err)
+ }
+ if raw.Icon != "" || raw.Sort != 0 || raw.SortMode != util.SortModeFileTree {
+ t.Fatalf("plaintext metadata was not neutralized: icon=%q sort=%d sortMode=%d", raw.Icon, raw.Sort, raw.SortMode)
+ }
+ if raw.BoxCrypt == nil || len(raw.BoxCrypt.Metadata) == 0 {
+ t.Fatal("encrypted notebook metadata ciphertext is missing")
+ }
+
+ unlocked := box.GetConf()
+ if unlocked.Icon != "1f512" || unlocked.Sort != 42 || unlocked.SortMode != util.SortModeCustom {
+ t.Fatalf("decrypted metadata mismatch: icon=%q sort=%d sortMode=%d", unlocked.Icon, unlocked.Sort, unlocked.SortMode)
+ }
+
+ cachedDEKsLock.Lock()
+ delete(cachedDEKs, boxID)
+ cachedDEKsLock.Unlock()
+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)
+ locked := box.GetConf()
+ if locked.Icon != "" || locked.Sort != 0 || locked.SortMode != util.SortModeFileTree {
+ t.Fatalf("locked metadata was exposed: icon=%q sort=%d sortMode=%d", locked.Icon, locked.Sort, locked.SortMode)
+ }
+}
+
+func TestEncryptedBoxMetadataAuthenticationFailureEntersErrorState(t *testing.T) {
+ boxID := "20260731160003-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ boxConf.Icon = "1f512"
+ if err := box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+
+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")
+ data, err := os.ReadFile(confPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw := conf.NewBoxConf()
+ if err = gulu.JSON.UnmarshalJSON(data, raw); err != nil {
+ t.Fatal(err)
+ }
+ raw.BoxCrypt.Metadata[len(raw.BoxCrypt.Metadata)-1] ^= 0xff
+ data, err = gulu.JSON.MarshalIndentJSON(raw, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(confPath, data, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ loaded := box.GetConf()
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateError {
+ t.Fatalf("expected Error state after metadata authentication failure, got %s", state)
+ }
+ if loaded.Icon != "" {
+ t.Fatalf("unauthenticated metadata was exposed: %q", loaded.Icon)
+ }
+ if err = box.SaveConf(loaded); err == nil {
+ t.Fatal("saving an encrypted notebook in the Error state should be rejected")
+ }
+ if err = AcquireEncryptedBoxOperation(boxID); err == nil {
+ t.Fatal("an encrypted notebook in the Error state should reject new operations")
+ }
+}
+
+func TestNotebookCryptoLifecycleStateRequiresCompleteCurrentConfiguration(t *testing.T) {
+ oldDataDir := util.DataDir
+ oldConf := Conf
+ util.DataDir = t.TempDir()
+ Conf = NewAppConf()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ defer func() {
+ Conf = oldConf
+ util.DataDir = oldDataDir
+ }()
+
+ incomplete := conf.NewNotebookCrypto()
+ incomplete.Enabled = true
+ Conf.m.Lock()
+ *Conf.NotebookCrypto = *incomplete
+ Conf.m.Unlock()
+ if state := NotebookCryptoLifecycleState(false); state != NotebookCryptoStateRecoveryRequired {
+ t.Fatalf("expected RecoveryRequired for incomplete enabled configuration, got %s", state)
+ }
+
+ kek, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(kek)
+ verifier, err := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ nonce, err := util.EncryptionNonce(verifier)
+ if err != nil {
+ t.Fatal(err)
+ }
+ current := conf.NewNotebookCrypto()
+ current.Enabled = true
+ current.MasterSalt = bytes.Repeat([]byte{1}, 16)
+ current.KEKVerifier = verifier
+ current.VerifierNonce = nonce
+ prepareBackupForWrite(current)
+ current.KEKMAC = computeKEKMAC(current, kek)
+ Conf.m.Lock()
+ *Conf.NotebookCrypto = *current
+ Conf.m.Unlock()
+ if state := NotebookCryptoLifecycleState(false); state != NotebookCryptoStateEnabled {
+ t.Fatalf("expected Enabled for complete current configuration, got %s", state)
+ }
+}
+
+func TestRecoveryRequiredHistoryRestoresAuthenticatedBackup(t *testing.T) {
+ oldDataDir := util.DataDir
+ oldHistoryDir := util.HistoryDir
+ oldConfDir := util.ConfDir
+ oldConf := Conf
+ root := t.TempDir()
+ util.DataDir = filepath.Join(root, "data")
+ util.HistoryDir = filepath.Join(root, "history")
+ util.ConfDir = filepath.Join(root, "conf")
+ for _, dir := range []string{util.DataDir, util.HistoryDir, util.ConfDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ Conf = NewAppConf()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ defer func() {
+ Conf = oldConf
+ util.DataDir = oldDataDir
+ util.HistoryDir = oldHistoryDir
+ util.ConfDir = oldConfDir
+ }()
+
+ password := "restore-history-key-backup"
+ salt, err := util.GenerateSalt()
+ if err != nil {
+ t.Fatal(err)
+ }
+ params := util.DefaultArgon2Params()
+ kek := util.DeriveKey(password, salt, params)
+ defer zeroAndClear(kek)
+ verifier, err := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ verifierNonce, err := util.EncryptionNonce(verifier)
+ if err != nil {
+ t.Fatal(err)
+ }
+ backup := &conf.NotebookCrypto{
+ Enabled: true,
+ MasterSalt: salt,
+ KDFParams: params,
+ KEKVerifier: verifier,
+ VerifierNonce: verifierNonce,
+ }
+ if err = writeNotebookCryptoBackupData(backup, kek); err != nil {
+ t.Fatal(err)
+ }
+
+ boxID := "20260731160006-abcdefg"
+ dek, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(dek)
+ wrappedDEK, err := util.EncryptWithAAD(kek, dek, wrappedDEKAAD(boxID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ boxConf.BoxCrypt = &conf.BoxEncryption{
+ Spec: boxEncryptionSpec,
+ WrappedDEK: wrappedDEK,
+ WrapNonce: mustEncryptionNonce(wrappedDEK),
+ CreatedAt: time.Now().UnixMilli(),
+ }
+ if err = encryptBoxMetadata(boxID, boxConf, dek); err != nil {
+ t.Fatal(err)
+ }
+ historyBoxDir := filepath.Join(util.HistoryDir, "2026-07-31-160006-delete", boxID, ".siyuan")
+ if err = os.MkdirAll(historyBoxDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ boxCryptData, err := gulu.JSON.MarshalIndentJSON(boxConf.BoxCrypt, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(historyBoxDir, "notebook-crypt-backup.json"), boxCryptData, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ if state := NotebookCryptoLifecycleState(true); state != NotebookCryptoStateRecoveryRequired {
+ t.Fatalf("expected RecoveryRequired before restoring history key material, got %s", state)
+ }
+ if err = EnableEncryptedNotebook(password); err != nil {
+ t.Fatalf("restore encrypted notebook configuration from history dependency failed: %v", err)
+ }
+ if state := NotebookCryptoLifecycleState(true); state != NotebookCryptoStateEnabled {
+ t.Fatalf("expected Enabled after restoring history key material, got %s", state)
+ }
+}
+
+func TestHistoricalAttributeViewRejectsMissingEncryptedContext(t *testing.T) {
+ key, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ciphertext, err := util.EncryptWithAAD(key, []byte("{}"), []byte("test"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = decryptHistoricalAttributeView("", "20260731160002-abcdefg", ciphertext); err == nil {
+ t.Fatal("encrypted attribute view history without notebook context should be rejected")
+ }
+}
+
+func prepareEncryptedBoxLifecycleTest(t *testing.T, boxID string) func() {
+ t.Helper()
+ oldDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+
+ dek, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cachedDEKsLock.Lock()
+ cachedDEKs[boxID] = append([]byte(nil), dek...)
+ cachedDEKsLock.Unlock()
+
+ kek, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wrappedDEK, err := util.EncryptWithAAD(kek, dek, wrappedDEKAAD(boxID))
+ zeroAndClear(kek)
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxConf := conf.NewBoxConf()
+ boxConf.Name = "Encrypted"
+ boxConf.Encrypted = true
+ boxConf.BoxCrypt = &conf.BoxEncryption{
+ Spec: boxEncryptionSpec,
+ WrappedDEK: wrappedDEK,
+ WrapNonce: mustEncryptionNonce(wrappedDEK),
+ CreatedAt: time.Now().UnixMilli(),
+ }
+ if err = (&Box{ID: boxID}).SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+
+ return func() {
+ cachedDEKsLock.Lock()
+ if cached, ok := cachedDEKs[boxID]; ok {
+ zeroAndClear(cached)
+ delete(cachedDEKs, boxID)
+ }
+ cachedDEKsLock.Unlock()
+ zeroAndClear(dek)
+ removeEncryptedBoxLifecycle(boxID)
+ util.DataDir = oldDataDir
+ }
+}
diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.go
index c699a58993..401f0ce7e0 100644
--- a/kernel/model/crypto_test.go
+++ b/kernel/model/crypto_test.go
@@ -211,8 +211,10 @@ func TestBoxEncryptionRoundTripViaUtil(t *testing.T) {
wrapped, _ := util.EncryptWithAAD(kek, originalDEK, wrappedDEKAAD(""))
boxEnc := &conf.BoxEncryption{
+ Spec: boxEncryptionSpec,
WrappedDEK: wrapped,
- WrapNonce: wrapped[:12],
+ WrapNonce: mustEncryptionNonce(wrapped),
+ CreatedAt: time.Now().UnixMilli(),
}
recoveredDEK, err := decryptWrappedDEK("", boxEnc, kek)
@@ -224,6 +226,32 @@ func TestBoxEncryptionRoundTripViaUtil(t *testing.T) {
}
}
+// TestBoxEncryptionMissingSpecRejected 验证缺少当前包络规范标识的密钥材料被拒绝。
+func TestBoxEncryptionMissingSpecRejected(t *testing.T) {
+ kek, _ := util.GenerateDEK()
+ dek, _ := util.GenerateDEK()
+ wrapped, _ := util.EncryptWithAAD(kek, dek, wrappedDEKAAD("missing-spec-box"))
+ boxEnc := &conf.BoxEncryption{WrappedDEK: wrapped}
+ if _, err := decryptWrappedDEK("missing-spec-box", boxEnc, kek); err == nil {
+ t.Fatal("key envelope without the current spec should be rejected")
+ }
+}
+
+func TestBoxEncryptionNonceMismatchRejected(t *testing.T) {
+ kek, _ := util.GenerateDEK()
+ dek, _ := util.GenerateDEK()
+ wrapped, _ := util.EncryptWithAAD(kek, dek, wrappedDEKAAD("nonce-mismatch-box"))
+ boxEnc := &conf.BoxEncryption{
+ Spec: boxEncryptionSpec,
+ WrappedDEK: wrapped,
+ WrapNonce: bytes.Repeat([]byte{0x7f}, 12),
+ CreatedAt: time.Now().UnixMilli(),
+ }
+ if _, err := decryptWrappedDEK("nonce-mismatch-box", boxEnc, kek); err == nil {
+ t.Fatal("key envelope with a mismatched nonce should be rejected")
+ }
+}
+
// TestUnmount0ClearsDEKForUnmountedEncryptedBox 验证安全修复:加密笔记本在
// "已解锁(DEK 在内存)但未挂载(不在 GetOpenedBoxes)"的状态下调用 unmount0,
// DEK 仍应被清除,否则锁定后认证 API 仍可读取明文。
@@ -300,6 +328,30 @@ func TestBackupRejectsUnsupportedSpec(t *testing.T) {
}
}
+func TestBackupRejectsIncompleteCurrentSpec(t *testing.T) {
+ originalDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ defer func() { util.DataDir = originalDataDir }()
+
+ backup := conf.NewNotebookCrypto()
+ backup.Enabled = true
+ prepareBackupForWrite(backup)
+ backupPath := filepath.Join(util.DataDir, ".siyuan", "notebook-crypto-backup.json")
+ if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ data, err := json.Marshal(backup)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(backupPath, data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = loadNotebookCryptoBackup(); err == nil {
+ t.Fatal("incomplete current notebook crypto backup should be rejected")
+ }
+}
+
// TestBackupChecksumCorruption 验证校验和可检测备份损坏。
func TestBackupChecksumCorruption(t *testing.T) {
origDataDir := util.DataDir
@@ -307,12 +359,22 @@ func TestBackupChecksumCorruption(t *testing.T) {
util.DataDir = tempDir
defer func() { util.DataDir = origDataDir }()
- // 创建有效备份
+ password := "checksum-corruption-test"
+ salt, _ := util.GenerateSalt()
+ params := util.DefaultArgon2Params()
+ kek := util.DeriveKey(password, salt, params)
+ defer zeroAndClear(kek)
+ verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ verifierNonce, _ := util.EncryptionNonce(verifier)
nc := &conf.NotebookCrypto{
- Enabled: true,
- MasterSalt: []byte("corrupt-test-salt12"),
+ Enabled: true,
+ MasterSalt: salt,
+ KDFParams: params,
+ KEKVerifier: verifier,
+ VerifierNonce: verifierNonce,
}
prepareBackupForWrite(nc)
+ nc.KEKMAC = computeKEKMAC(nc, kek)
backupPath := filepath.Join(tempDir, ".siyuan", "notebook-crypto-backup.json")
os.MkdirAll(filepath.Dir(backupPath), 0755)
data, _ := json.Marshal(nc)
@@ -374,16 +436,18 @@ func TestDeriveKEKRejectsTamperedBackupMAC(t *testing.T) {
params := util.DefaultArgon2Params()
kek := util.DeriveKey(password, salt, params)
verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ verifierNonce, _ := util.EncryptionNonce(verifier)
nc := conf.NotebookCrypto{
- Enabled: true,
- MasterSalt: salt,
- KDFParams: params,
- KEKVerifier: verifier,
- Spec: 1,
- KEKMAC: []byte("tampered"),
+ Enabled: true,
+ MasterSalt: salt,
+ KDFParams: params,
+ KEKVerifier: verifier,
+ VerifierNonce: verifierNonce,
+ Spec: 1,
+ KEKMAC: bytes.Repeat([]byte{0x7f}, 32),
}
prepareBackupForWrite(&nc)
- nc.KEKMAC = []byte("tampered")
+ nc.KEKMAC = bytes.Repeat([]byte{0x7f}, 32)
backupPath := filepath.Join(util.DataDir, ".siyuan", "notebook-crypto-backup.json")
if err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {
t.Fatal(err)
@@ -416,11 +480,13 @@ func TestDeriveKEKAllowsLocalAutoLockChange(t *testing.T) {
kek := util.DeriveKey(password, salt, params)
defer zeroAndClear(kek)
verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ verifierNonce, _ := util.EncryptionNonce(verifier)
backup := &conf.NotebookCrypto{
Enabled: true,
MasterSalt: salt,
KDFParams: params,
KEKVerifier: verifier,
+ VerifierNonce: verifierNonce,
AutoLockMinutes: 5,
}
if err := writeNotebookCryptoBackupData(backup, kek); err != nil {
@@ -441,6 +507,63 @@ func TestDeriveKEKAllowsLocalAutoLockChange(t *testing.T) {
zeroAndClear(derived)
}
+func TestDeriveKEKRepairsIncompleteLocalConfiguration(t *testing.T) {
+ originalDataDir := util.DataDir
+ originalConfDir := util.ConfDir
+ originalConf := Conf
+ testDir := t.TempDir()
+ util.DataDir = testDir
+ util.ConfDir = filepath.Join(testDir, "conf")
+ if err := os.MkdirAll(util.ConfDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ util.DataDir = originalDataDir
+ util.ConfDir = originalConfDir
+ Conf = originalConf
+ }()
+
+ password := "repair-incomplete-configuration"
+ salt, _ := util.GenerateSalt()
+ params := util.DefaultArgon2Params()
+ kek := util.DeriveKey(password, salt, params)
+ defer zeroAndClear(kek)
+ verifier, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ verifierNonce, _ := util.EncryptionNonce(verifier)
+ backup := &conf.NotebookCrypto{
+ Enabled: true,
+ MasterSalt: salt,
+ KDFParams: params,
+ KEKVerifier: verifier,
+ VerifierNonce: verifierNonce,
+ AutoLockMinutes: 5,
+ }
+ if err := writeNotebookCryptoBackupData(backup, kek); err != nil {
+ t.Fatal(err)
+ }
+
+ local := *backup
+ local.KEKMAC = nil
+ local.AutoLockMinutes = 30
+ Conf = NewAppConf()
+ Conf.NotebookCrypto = &local
+
+ derived, err := deriveKEK(password)
+ if err != nil {
+ t.Fatalf("deriveKEK rejected the authenticated recovery backup: %v", err)
+ }
+ zeroAndClear(derived)
+ if !notebookCryptoConfigurationComplete(Conf.NotebookCrypto) {
+ t.Fatal("deriveKEK did not repair the incomplete local configuration")
+ }
+ if Conf.NotebookCrypto.AutoLockMinutes != 30 {
+ t.Fatal("deriveKEK replaced the local auto-lock policy during repair")
+ }
+ if state := NotebookCryptoLifecycleState(false); state != NotebookCryptoStateEnabled {
+ t.Fatalf("expected Enabled after repair, got %s", state)
+ }
+}
+
func TestDeriveKEKKeepsAuthenticatedLocalCandidateWithDifferentBackup(t *testing.T) {
origDataDir := util.DataDir
util.DataDir = t.TempDir()
@@ -452,11 +575,13 @@ func TestDeriveKEKKeepsAuthenticatedLocalCandidateWithDifferentBackup(t *testing
localKEK := util.DeriveKey(localPassword, localSalt, params)
defer zeroAndClear(localKEK)
localVerifier, _ := util.EncryptWithAAD(localKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ localVerifierNonce, _ := util.EncryptionNonce(localVerifier)
local := &conf.NotebookCrypto{
Enabled: true,
MasterSalt: localSalt,
KDFParams: params,
KEKVerifier: localVerifier,
+ VerifierNonce: localVerifierNonce,
AutoLockMinutes: 5,
}
prepareBackupForWrite(local)
@@ -468,11 +593,13 @@ func TestDeriveKEKKeepsAuthenticatedLocalCandidateWithDifferentBackup(t *testing
backupKEK := util.DeriveKey(backupPassword, backupSalt, params)
defer zeroAndClear(backupKEK)
backupVerifier, _ := util.EncryptWithAAD(backupKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ backupVerifierNonce, _ := util.EncryptionNonce(backupVerifier)
backup := &conf.NotebookCrypto{
Enabled: true,
MasterSalt: backupSalt,
KDFParams: params,
KEKVerifier: backupVerifier,
+ VerifierNonce: backupVerifierNonce,
AutoLockMinutes: 5,
}
if err := writeNotebookCryptoBackupData(backup, backupKEK); err != nil {
@@ -512,11 +639,13 @@ func TestDeriveKEKAdoptsCompleteSynchronizedCandidate(t *testing.T) {
newKEK := util.DeriveKey(newPassword, newSalt, params)
defer zeroAndClear(newKEK)
newVerifier, _ := util.EncryptWithAAD(newKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ newVerifierNonce, _ := util.EncryptionNonce(newVerifier)
newConfig := &conf.NotebookCrypto{
- Enabled: true,
- MasterSalt: newSalt,
- KDFParams: params,
- KEKVerifier: newVerifier,
+ Enabled: true,
+ MasterSalt: newSalt,
+ KDFParams: params,
+ KEKVerifier: newVerifier,
+ VerifierNonce: newVerifierNonce,
}
if err := writeNotebookCryptoBackupData(newConfig, newKEK); err != nil {
t.Fatal(err)
@@ -526,7 +655,15 @@ func TestDeriveKEKAdoptsCompleteSynchronizedCandidate(t *testing.T) {
wrappedDEK, _ := util.EncryptWithAAD(newKEK, dek, wrappedDEKAAD(boxID))
boxConfig := conf.NewBoxConf()
boxConfig.Encrypted = true
- boxConfig.BoxCrypt = &conf.BoxEncryption{Spec: boxEncryptionSpec, WrappedDEK: wrappedDEK}
+ boxConfig.BoxCrypt = &conf.BoxEncryption{
+ Spec: boxEncryptionSpec,
+ WrappedDEK: wrappedDEK,
+ WrapNonce: mustEncryptionNonce(wrappedDEK),
+ CreatedAt: time.Now().UnixMilli(),
+ }
+ if err := encryptBoxMetadata(boxID, boxConfig, dek); err != nil {
+ t.Fatal(err)
+ }
boxConfigData, _ := gulu.JSON.MarshalIndentJSON(boxConfig, "", " ")
boxConfigPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")
if err := os.MkdirAll(filepath.Dir(boxConfigPath), 0755); err != nil {
@@ -540,11 +677,13 @@ func TestDeriveKEKAdoptsCompleteSynchronizedCandidate(t *testing.T) {
oldKEK := util.DeriveKey("old-device-password", oldSalt, params)
defer zeroAndClear(oldKEK)
oldVerifier, _ := util.EncryptWithAAD(oldKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ oldVerifierNonce, _ := util.EncryptionNonce(oldVerifier)
localConfig := &conf.NotebookCrypto{
Enabled: true,
MasterSalt: oldSalt,
KDFParams: params,
KEKVerifier: oldVerifier,
+ VerifierNonce: oldVerifierNonce,
AutoLockMinutes: 30,
}
prepareBackupForWrite(localConfig)
@@ -570,11 +709,24 @@ func TestDeriveKEKAdoptsCompleteSynchronizedCandidate(t *testing.T) {
// TestDeepCopyBoxEncryptionPreservesSpec 验证保存笔记本配置前的深拷贝不会丢失包络版本。
func TestDeepCopyBoxEncryptionPreservesSpec(t *testing.T) {
- src := &conf.BoxEncryption{Spec: 1, WrappedDEK: []byte{1, 2}, WrapNonce: []byte{3, 4}, CreatedAt: 5}
+ src := &conf.BoxEncryption{
+ Spec: 1,
+ WrappedDEK: []byte{1, 2},
+ WrapNonce: []byte{3, 4},
+ Metadata: []byte{5, 6},
+ CreatedAt: 7,
+ }
got := DeepCopyBoxEncryption(src)
if got.Spec != src.Spec {
t.Fatalf("BoxEncryption.Spec changed during deep copy: got %d want %d", got.Spec, src.Spec)
}
+ if !bytes.Equal(got.Metadata, src.Metadata) {
+ t.Fatal("BoxEncryption.Metadata changed during deep copy")
+ }
+ got.Metadata[0] = 0
+ if src.Metadata[0] == 0 {
+ t.Fatal("BoxEncryption.Metadata was not deeply copied")
+ }
}
// TestUnknownBlockRefFailsClosed 验证普通库无法定位定义块时按跨边界处理,防止锁定加密块 ID 被写入全局库。
@@ -599,11 +751,13 @@ func TestBackupMACRoundTrip(t *testing.T) {
defer zeroAndClear(kek)
verifierCT, _ := util.EncryptWithAAD(kek, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ verifierNonce, _ := util.EncryptionNonce(verifierCT)
nc := &conf.NotebookCrypto{
- Enabled: true,
- MasterSalt: salt,
- KDFParams: params,
- KEKVerifier: verifierCT,
+ Enabled: true,
+ MasterSalt: salt,
+ KDFParams: params,
+ KEKVerifier: verifierCT,
+ VerifierNonce: verifierNonce,
}
// 通过 writeNotebookCryptoBackupData 写入(内部 prepareBackupForWrite 后计算 MAC)
diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.go
index 59a33b6465..cdffa20b12 100644
--- a/kernel/model/encrypted_export.go
+++ b/kernel/model/encrypted_export.go
@@ -163,19 +163,6 @@ func IsManagedEncryptedExportPath(relativePath string) bool {
return len(parts) >= 1 && ast.IsNodeIDPattern(parts[0])
}
-// ResolveManagedExportForMobile 供移动端 GetExportFilePath 调用,校验托管 token 有效且 box 已解锁。
-// 任一条件不满足返回 ("", false)(fail-closed),防止移动端绕过注册表直接读取明文导出产物。
-func ResolveManagedExportForMobile(relativePath string) (absPath string, ok bool) {
- boxID, artifact, resolved := ResolveManagedEncryptedExport(relativePath)
- if !resolved {
- return "", false
- }
- if _, dekErr := GetDEKIfUnlocked(boxID); dekErr != nil {
- return "", false
- }
- return artifact, true
-}
-
// AcquireMobileExportLease 为移动端导出取得覆盖整个原生复制过程的生命周期租约。
func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, err error) {
if after, ok := strings.CutPrefix(exportPath, "/export/"); ok {
@@ -192,11 +179,15 @@ func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, err
if !resolved {
return nil, errors.New("managed export is unavailable")
}
+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {
+ return nil, err
+ }
HoldBoxReadLock(boxID)
release := true
defer func() {
if release {
ReleaseBoxReadLock(boxID)
+ ReleaseEncryptedBoxOperation(boxID)
}
}()
_, artifact, resolved = ResolveManagedEncryptedExport(fileName)
@@ -234,11 +225,15 @@ func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, err
return registerMobileExportLease("", artifact, filepath.Base(artifact), "")
}
+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {
+ return nil, err
+ }
HoldBoxReadLock(boxID)
release := true
defer func() {
if release {
ReleaseBoxReadLock(boxID)
+ ReleaseEncryptedBoxOperation(boxID)
}
}()
dek, dekErr := GetDEKIfUnlocked(boxID)
@@ -310,6 +305,9 @@ func AcquireMobileExportLease(exportPath string) (lease *MobileExportLease, err
func GetMobileExportName(exportPath string) string {
if after, ok := strings.CutPrefix(exportPath, "/export/"); ok {
if decoded, err := url.PathUnescape(after); err == nil {
+ if IsManagedEncryptedExportPath(decoded) {
+ return ""
+ }
return util.FilterFileName(filepath.Base(decoded))
}
return ""
@@ -325,26 +323,7 @@ func GetMobileExportName(exportPath string) string {
if boxID == "" || !IsEncryptedBox(boxID) {
return util.FilterFileName(diskName)
}
- HoldBoxReadLock(boxID)
- defer ReleaseBoxReadLock(boxID)
- dek, err := GetDEKIfUnlocked(boxID)
- if err != nil {
- return ""
- }
- artifact, err := GetAssetAbsPathInBox(relativePath, boxID)
- if err != nil {
- return ""
- }
- source, err := filelock.OpenFile(artifact, os.O_RDONLY, 0)
- if err != nil {
- return ""
- }
- defer filelock.CloseFile(source)
- originalName, err := DecryptAssetNameFromReader(boxID, diskName, dek, source)
- if err != nil {
- return ""
- }
- return util.FilterFileName(filepath.Base(originalName))
+ return ""
}
func registerMobileExportLease(boxID, artifact, name, cleanupDir string) (*MobileExportLease, error) {
@@ -406,6 +385,7 @@ func releaseMobileExportLease(leaseID string, expired bool) {
}
if state.boxID != "" {
ReleaseBoxReadLock(state.boxID)
+ ReleaseEncryptedBoxOperation(state.boxID)
}
if expired {
logging.LogWarnf("mobile export lease [%s] expired at [%s]", leaseID, state.expiresAt.Format(time.RFC3339))
diff --git a/kernel/model/encrypted_export_test.go b/kernel/model/encrypted_export_test.go
index fc56dc3240..605643129e 100644
--- a/kernel/model/encrypted_export_test.go
+++ b/kernel/model/encrypted_export_test.go
@@ -133,8 +133,30 @@ func TestMobileExportLeaseStreamsEncryptedAsset(t *testing.T) {
util.WorkspaceDir = originalWorkspaceDir
}()
+ dek, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ kek, err := util.GenerateDEK()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wrappedDEK, err := util.EncryptWithAAD(kek, dek, wrappedDEKAAD(boxID))
+ zeroAndClear(kek)
+ if err != nil {
+ t.Fatal(err)
+ }
boxConf := conf.NewBoxConf()
boxConf.Encrypted = true
+ boxConf.BoxCrypt = &conf.BoxEncryption{
+ Spec: boxEncryptionSpec,
+ WrappedDEK: wrappedDEK,
+ WrapNonce: mustEncryptionNonce(wrappedDEK),
+ CreatedAt: time.Now().UnixMilli(),
+ }
+ if err = encryptBoxMetadata(boxID, boxConf, dek); err != nil {
+ t.Fatal(err)
+ }
confDir := filepath.Join(util.DataDir, boxID, ".siyuan")
if err := os.MkdirAll(confDir, 0755); err != nil {
t.Fatal(err)
@@ -147,10 +169,6 @@ func TestMobileExportLeaseStreamsEncryptedAsset(t *testing.T) {
t.Fatal(err)
}
- dek, err := util.GenerateDEK()
- if err != nil {
- t.Fatal(err)
- }
setDEKForTest(boxID, dek)
diskName := "asset-20260731153001-abcdefg.bin"
originalName := "移动端大附件.bin"
diff --git a/kernel/model/export.go b/kernel/model/export.go
index b3b0ec3cf5..a3555aa7c7 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -2448,6 +2448,9 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i
// (不可 filelock.ReadFile 直接读盘,加密笔记本的磁盘 .sy 是密文)。
total := len(trees) + len(refTrees)
for _, tree := range trees {
+ if encrypted {
+ removeFlashcardAttrs(tree)
+ }
writePath := strings.TrimPrefix(tree.Path, rootDirPath)
writePath = filepath.Join(exportDir, writePath)
writeFolder := filepath.Dir(writePath)
@@ -2467,6 +2470,9 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i
count = 0
// 引用树放在导出文件夹根路径下
for treeID, tree := range refTrees {
+ if IsEncryptedBox(tree.Box) {
+ removeFlashcardAttrs(tree)
+ }
writePath := filepath.Join(exportDir, treeID+".sy")
if writeErr := os.WriteFile(writePath, treeToSYJSON(tree), 0644); nil != writeErr {
logging.LogErrorf("write export file [%s] failed: %s", writePath, writeErr)
@@ -2593,22 +2599,24 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i
exportAv(avID, avBoxes[avID], exportStorageAvDir, exportDir, assetPathMap)
}
- // 导出闪卡 Export related flashcard data when exporting .sy.zip https://github.com/siyuan-note/siyuan/issues/9372
- exportStorageRiffDir := filepath.Join(exportDir, "storage", "riff")
- deck, loadErr := riff.LoadDeck(exportStorageRiffDir, builtinDeckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)
- if nil != loadErr {
- logging.LogErrorf("load deck [%s] failed: %s", name, loadErr)
- } else {
- for _, tree := range trees {
- cards := getTreeFlashcards(tree.ID)
+ if !IsEncryptedBox(box.ID) {
+ // 导出闪卡 Export related flashcard data when exporting .sy.zip https://github.com/siyuan-note/siyuan/issues/9372
+ exportStorageRiffDir := filepath.Join(exportDir, "storage", "riff")
+ deck, loadErr := riff.LoadDeck(exportStorageRiffDir, builtinDeckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)
+ if nil != loadErr {
+ logging.LogErrorf("load deck [%s] failed: %s", name, loadErr)
+ } else {
+ for _, tree := range trees {
+ cards := getTreeFlashcards(tree.ID)
- for _, card := range cards {
- deck.AddCard(card.ID(), card.BlockID())
+ for _, card := range cards {
+ deck.AddCard(card.ID(), card.BlockID())
+ }
}
- }
- if 0 < deck.CountCards() {
- if saveErr := deck.Save(); nil != saveErr {
- logging.LogErrorf("save deck [%s] failed: %s", name, saveErr)
+ if 0 < deck.CountCards() {
+ if saveErr := deck.Save(); nil != saveErr {
+ logging.LogErrorf("save deck [%s] failed: %s", name, saveErr)
+ }
}
}
}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index c4cc0de8df..a4faeff5b5 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -179,6 +179,9 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[
openedBoxes := Conf.GetOpenedBoxes()
boxes := map[string]*Box{}
for _, box := range openedBoxes {
+ if flashcard && IsEncryptedBox(box.ID) {
+ continue
+ }
boxes[box.ID] = box
}
@@ -346,6 +349,9 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden boo
//defer pprof.StopCPUProfile()
ret = []*File{}
+ if flashcard && IsEncryptedBox(boxID) {
+ return nil, 0, errors.New(Conf.Language(313))
+ }
var deck *riff.Deck
var deckBlockIDs []string
diff --git a/kernel/model/flashcard.go b/kernel/model/flashcard.go
index 431d7cc9c5..03858e5916 100644
--- a/kernel/model/flashcard.go
+++ b/kernel/model/flashcard.go
@@ -17,6 +17,7 @@
package model
import (
+ "errors"
"math"
"os"
"path/filepath"
@@ -39,6 +40,73 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
+// ValidateFlashcardBlockIDs 只允许普通笔记本中可确认存在的块进入全局闪卡存储。
+func ValidateFlashcardBlockIDs(blockIDs []string) error {
+ for _, blockID := range blockIDs {
+ if !isSupportedFlashcardBlock(blockID) {
+ return errors.New(Conf.Language(313))
+ }
+ }
+ return nil
+}
+
+func validateFlashcardTree(rootID string) error {
+ return ValidateFlashcardBlockIDs([]string{rootID})
+}
+
+func isSupportedFlashcardBlock(blockID string) bool {
+ bt := treenode.GetBlockTreeInExactBox(blockID, "")
+ return bt != nil && !IsEncryptedBox(bt.BoxID)
+}
+
+func filterSupportedFlashcards(cards []riff.Card) (ret []riff.Card) {
+ for _, card := range cards {
+ if card == nil || !isSupportedFlashcardBlock(card.BlockID()) {
+ continue
+ }
+ ret = append(ret, card)
+ }
+ return
+}
+
+func removeFlashcardAttrs(tree *parse.Tree) {
+ if tree == nil || tree.Root == nil {
+ return
+ }
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && node.IsBlock() {
+ node.RemoveIALAttr(NodeAttrRiffDecks)
+ }
+ return ast.WalkContinue
+ })
+}
+
+func validateFlashcardCard(deck *riff.Deck, cardID string) error {
+ if deck == nil {
+ return nil
+ }
+ card := deck.GetCard(cardID)
+ if card == nil {
+ return nil
+ }
+ return ValidateFlashcardBlockIDs([]string{card.BlockID()})
+}
+
+// ValidateFlashcardTransactions 在事务入队前校验所有闪卡操作。
+func ValidateFlashcardTransactions(transactions []*Transaction) error {
+ for _, transaction := range transactions {
+ for _, operation := range transaction.DoOperations {
+ if operation.Action != "addFlashcards" && operation.Action != "removeFlashcards" {
+ continue
+ }
+ if err := ValidateFlashcardBlockIDs(operation.BlockIDs); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
func GetFlashcardsByBlockIDs(blockIDs []string) (ret []*Block) {
deckLock.Lock()
defer deckLock.Unlock()
@@ -91,6 +159,15 @@ func SetFlashcardsDueTime(cardDues []*SetFlashcardDueTime) (err error) {
return
}
+ for _, cardDue := range cardDues {
+ card := deck.GetCard(cardDue.ID)
+ if card == nil {
+ continue
+ }
+ if err = ValidateFlashcardBlockIDs([]string{card.BlockID()}); err != nil {
+ return
+ }
+ }
for _, cardDue := range cardDues {
card := deck.GetCard(cardDue.ID)
if nil == card {
@@ -113,9 +190,23 @@ func SetFlashcardsDueTime(cardDues []*SetFlashcardDueTime) (err error) {
return
}
-func ResetFlashcards(typ, id, deckID string, blockIDs []string) {
+func ResetFlashcards(typ, id, deckID string, blockIDs []string) error {
// Support resetting the learning progress of flashcards https://github.com/siyuan-note/siyuan/issues/9564
+ if err := ValidateFlashcardBlockIDs(blockIDs); err != nil {
+ return err
+ }
+ switch typ {
+ case "notebook":
+ if IsEncryptedBox(id) {
+ return errors.New(Conf.Language(313))
+ }
+ case "tree":
+ if err := validateFlashcardTree(id); err != nil {
+ return err
+ }
+ }
+
if 0 < len(blockIDs) {
if "" == deckID {
// 从全局管理进入时不会指定卡包 ID,这时需要遍历所有卡包
@@ -133,11 +224,11 @@ func ResetFlashcards(typ, id, deckID string, blockIDs []string) {
}
resetFlashcards(deckID, blockIDs)
}
- return
+ return nil
}
resetFlashcards(deckID, blockIDs)
- return
+ return nil
}
var blocks []*Block
@@ -178,6 +269,7 @@ func ResetFlashcards(typ, id, deckID string, blockIDs []string) {
blockIDs = gulu.Str.RemoveDuplicatedElem(blockIDs)
resetFlashcards(deckID, blockIDs)
+ return nil
}
func resetFlashcards(deckID string, blockIDs []string) {
@@ -231,6 +323,9 @@ func GetFlashcardNotebooks() (ret []*Box) {
}
func countTreeFlashcard(rootID string, deck *riff.Deck, deckBlockIDs []string) (newFlashcardCount, dueFlashcardCount, flashcardCount int) {
+ if validateFlashcardTree(rootID) != nil {
+ return
+ }
blockIDsMap, blockIDs := getTreeSubTreeChildBlocks(rootID)
for _, deckBlockID := range deckBlockIDs {
if blockIDsMap[deckBlockID] {
@@ -249,6 +344,9 @@ func countTreeFlashcard(rootID string, deck *riff.Deck, deckBlockIDs []string) (
}
func countBoxFlashcard(boxID string, deck *riff.Deck, deckBlockIDs []string) (newFlashcardCount, dueFlashcardCount, flashcardCount int) {
+ if IsEncryptedBox(boxID) {
+ return
+ }
blockIDsMap, blockIDs := getBoxBlocks(boxID)
for _, deckBlockID := range deckBlockIDs {
if blockIDsMap[deckBlockID] {
@@ -273,6 +371,9 @@ var (
func GetNotebookFlashcards(boxID string, page, pageSize int) (blocks []*Block, total, pageCount int) {
blocks = []*Block{}
+ if IsEncryptedBox(boxID) {
+ return
+ }
entries, err := os.ReadDir(filepath.Join(util.DataDir, boxID))
if err != nil {
@@ -321,12 +422,18 @@ func GetNotebookFlashcards(boxID string, page, pageSize int) (blocks []*Block, t
func GetTreeFlashcards(rootID string, page, pageSize int) (blocks []*Block, total, pageCount int) {
blocks = []*Block{}
+ if validateFlashcardTree(rootID) != nil {
+ return
+ }
cards := getTreeSubTreeFlashcards(rootID)
blocks, total, pageCount = getCardsBlocks(cards, page, pageSize)
return
}
func getTreeSubTreeFlashcards(rootID string) (ret []riff.Card) {
+ if validateFlashcardTree(rootID) != nil {
+ return
+ }
deck := Decks[builtinDeckID]
if nil == deck {
return
@@ -346,6 +453,9 @@ func getTreeSubTreeFlashcards(rootID string) (ret []riff.Card) {
}
func getTreeFlashcards(rootID string) (ret []riff.Card) {
+ if validateFlashcardTree(rootID) != nil {
+ return
+ }
deck := Decks[builtinDeckID]
if nil == deck {
return
@@ -382,11 +492,13 @@ func GetDeckFlashcards(deckID string, page, pageSize int) (blocks []*Block, tota
cards = append(cards, deck.GetCardsByBlockIDs(blockIDs)...)
}
+ cards = filterSupportedFlashcards(cards)
blocks, total, pageCount = getCardsBlocks(cards, page, pageSize)
return
}
func getCardsBlocks(cards []riff.Card, page, pageSize int) (blocks []*Block, total, pageCount int) {
+ cards = filterSupportedFlashcards(cards)
// sort by due date asc https://github.com/siyuan-note/siyuan/pull/9673
sort.Slice(cards, func(i, j int) bool {
due1 := cards[i].(*riff.FSRSCard).C.Due
@@ -475,6 +587,12 @@ func ReviewFlashcard(deckID, cardID string, rating riff.Rating, reviewedCardIDs
waitForSyncingStorages()
deck := Decks[deckID]
+ if deck == nil {
+ return
+ }
+ if err = validateFlashcardCard(deck, cardID); err != nil {
+ return
+ }
card := deck.GetCard(cardID)
if nil == card {
return
@@ -519,6 +637,12 @@ func SkipReviewFlashcard(deckID, cardID string) (err error) {
waitForSyncingStorages()
deck := Decks[deckID]
+ if deck == nil {
+ return
+ }
+ if err = validateFlashcardCard(deck, cardID); err != nil {
+ return
+ }
card := deck.GetCard(cardID)
if nil == card {
return
@@ -558,6 +682,10 @@ func newFlashcard(card riff.Card, deckID string, now time.Time) *Flashcard {
}
func GetNotebookDueFlashcards(boxID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int, err error) {
+ if IsEncryptedBox(boxID) {
+ err = errors.New(Conf.Language(313))
+ return
+ }
deckLock.Lock()
defer deckLock.Unlock()
@@ -610,6 +738,9 @@ func GetNotebookDueFlashcards(boxID string, reviewedCardIDs []string) (ret []*Fl
}
func GetTreeDueFlashcards(rootID string, reviewedCardIDs []string) (ret []*Flashcard, unreviewedCount, unreviewedNewCardCount, unreviewedOldCardCount int, err error) {
+ if err = validateFlashcardTree(rootID); err != nil {
+ return
+ }
deckLock.Lock()
defer deckLock.Unlock()
@@ -762,6 +893,9 @@ func (tx *Transaction) doRemoveFlashcards(operation *Operation) (ret *TxErr) {
deckID := operation.DeckID
blockIDs := operation.BlockIDs
+ if err := ValidateFlashcardBlockIDs(blockIDs); err != nil {
+ return &TxErr{code: TxErrCodePushMsg, msg: err.Error()}
+ }
if err := tx.removeBlocksDeckAttr(blockIDs, deckID); err != nil {
return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: deckID}
@@ -876,6 +1010,9 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {
deckID := operation.DeckID
blockIDs := operation.BlockIDs
+ if err := ValidateFlashcardBlockIDs(blockIDs); err != nil {
+ return &TxErr{code: TxErrCodePushMsg, msg: err.Error()}
+ }
foundDeck := false
for _, deck := range Decks {
@@ -892,17 +1029,19 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {
}
blockRoots := map[string]string{}
+ var eligibleBlockIDs []string
for _, blockID := range blockIDs {
bt := treenode.GetBlockTree(blockID)
if nil == bt {
continue
}
- // 闪卡是全局调度与存储,加密笔记本不支持闪卡,跳过其块避免明文复习计划落盘全局 riff
+ // 闪卡是全局调度与存储,只允许可解析的普通笔记本块写入。
if IsEncryptedBox(bt.BoxID) {
continue
}
blockRoots[blockID] = bt.RootID
+ eligibleBlockIDs = append(eligibleBlockIDs, blockID)
}
trees := map[string]*parse.Tree{}
@@ -946,7 +1085,7 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {
return
}
- for _, blockID := range blockIDs {
+ for _, blockID := range eligibleBlockIDs {
cards := deck.GetCardsByBlockID(blockID)
if 0 < len(cards) {
// 一个块只能添加生成一张闪卡 https://github.com/siyuan-note/siyuan/issues/7476
@@ -993,7 +1132,6 @@ func LoadFlashcards() {
if 0 == deck.Updated {
deck.Updated = deck.Created
}
-
Decks[deckID] = deck
}
}
@@ -1094,6 +1232,16 @@ func GetDecks() (decks []*riff.Deck) {
return
}
+func CountSupportedFlashcards(deck *riff.Deck) int {
+ deckLock.Lock()
+ defer deckLock.Unlock()
+
+ if deck == nil {
+ return 0
+ }
+ return len(filterSupportedFlashcards(deck.GetCardsByBlockIDs(deck.GetBlockIDs())))
+}
+
func getRiffDir() string {
return filepath.Join(util.DataDir, "storage", "riff")
}
@@ -1112,6 +1260,9 @@ func getDeckDueCards(deck *riff.Deck, reviewedCardIDs, blockIDs []string, newCar
dues := deck.Dues()
toChecks := map[string]riff.Card{}
for _, c := range dues {
+ if !isSupportedFlashcardBlock(c.BlockID()) {
+ continue
+ }
if 0 < len(blockIDs) && !gulu.Str.Contains(c.BlockID(), blockIDs) {
continue
}
diff --git a/kernel/model/history.go b/kernel/model/history.go
index be149e7dbc..237a39a321 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -17,6 +17,7 @@
package model
import (
+ "bytes"
"encoding/json"
"errors"
"fmt"
@@ -160,16 +161,8 @@ func ClearWorkspaceHistory() (err error) {
}
func GetDocHistoryContent(historyPath, keyword string, highlight bool) (id, rootID, content string, isLargeDoc bool, err error) {
- historyPath = filepath.Join(util.WorkspaceDir, historyPath)
- if !util.IsAbsPathInWorkspace(historyPath) {
- msg := "Path [" + historyPath + "] is not in workspace"
- logging.LogError(msg)
- err = errors.New(msg)
- return
- }
-
- if !gulu.File.IsExist(historyPath) {
- logging.LogWarnf("doc history [%s] not exist", historyPath)
+ historyPath, err = validateHistoryPath(historyPath)
+ if err != nil {
return
}
@@ -183,29 +176,32 @@ func GetDocHistoryContent(historyPath, keyword string, highlight bool) (id, root
relPath := strings.TrimPrefix(filepath.ToSlash(historyPath), filepath.ToSlash(util.HistoryDir))
relPath = strings.TrimPrefix(relPath, "/")
pathParts := strings.SplitN(relPath, "/", 3)
- if len(pathParts) >= 2 {
+ ciphertext := util.IsCiphertext(data)
+ if ciphertext {
+ if len(pathParts) < 3 || !ast.IsNodeIDPattern(pathParts[1]) {
+ err = errors.New("encrypted document history is missing notebook context")
+ return
+ }
histBoxID := pathParts[1]
- if IsEncryptedBox(histBoxID) {
- HoldBoxReadLock(histBoxID)
- defer ReleaseBoxReadLock(histBoxID)
- dek, dekErr := GetDEKIfUnlocked(histBoxID)
- if dekErr != nil {
- err = errors.New(Conf.Language(314))
- return
- }
- var decErr error
- // 历史路径格式:<historyDir>/<datePrefix>/<boxID>/<relativePath>
- filePath := ""
- if len(pathParts) >= 3 {
- filePath = pathParts[2]
- }
- data, decErr = DecryptFile(histBoxID, filePath, dek, data)
- if decErr != nil {
- logging.LogErrorf("decrypt history [%s] failed: %s", historyPath, decErr)
- err = decErr
- return
- }
+ if !IsEncryptedBox(histBoxID) {
+ err = fmt.Errorf("encrypted document history has no matching notebook [%s]", histBoxID)
+ return
+ }
+ HoldBoxReadLock(histBoxID)
+ defer ReleaseBoxReadLock(histBoxID)
+ dek, dekErr := GetDEKIfUnlocked(histBoxID)
+ if dekErr != nil {
+ err = errors.New(Conf.Language(314))
+ return
}
+ data, err = DecryptFile(histBoxID, pathParts[2], dek, data)
+ if err != nil {
+ logging.LogErrorf("decrypt history [%s] failed: %s", historyPath, err)
+ return
+ }
+ } else if len(pathParts) >= 2 && IsEncryptedBox(pathParts[1]) {
+ err = fmt.Errorf("encrypted notebook document history is plaintext [%s]", pathParts[1])
+ return
}
isLargeDoc = 1024*1024*1 <= len(data)
@@ -282,7 +278,7 @@ func RollbackDocHistory(historyPath string) (err error) {
parts := strings.SplitN(relPath, "/", 3)
if len(parts) < 3 {
logging.LogWarnf("invalid history path [%s]", historyPath)
- return
+ return fmt.Errorf("history path is missing notebook context [%s]", historyPath)
}
boxID := parts[1]
origBoxID := boxID // 保留原始 boxID 用于解密(getRollbackBox 可能返回不同的 box)
@@ -322,7 +318,14 @@ func RollbackDocHistory(historyPath string) (err error) {
srcData, srcReadErr := filelock.ReadFile(srcPath)
if srcReadErr != nil {
logging.LogErrorf("read history [%s] failed: %s", srcPath, srcReadErr)
- return
+ return srcReadErr
+ }
+ ciphertext := util.IsCiphertext(srcData)
+ if ciphertext && !IsEncryptedBox(origBoxID) {
+ return fmt.Errorf("encrypted document history has no matching notebook [%s]", origBoxID)
+ }
+ if !ciphertext && IsEncryptedBox(origBoxID) {
+ return fmt.Errorf("encrypted notebook document history is plaintext [%s]", origBoxID)
}
if IsEncryptedBox(origBoxID) {
HoldBoxReadLock(origBoxID)
@@ -343,7 +346,13 @@ func RollbackDocHistory(historyPath string) (err error) {
return
}
}
- tree, _ := loadTreeByData0(srcData)
+ tree, parseErr := loadTreeByData0(srcData)
+ if parseErr != nil {
+ return fmt.Errorf("parse document history failed: %w", parseErr)
+ }
+ if tree == nil {
+ return errors.New("parse document history failed")
+ }
if nil != tree {
historyDir := filepath.Join(util.HistoryDir, parts[0])
@@ -355,9 +364,10 @@ func RollbackDocHistory(historyPath string) (err error) {
if IsEncryptedBox(boxID) {
// 历史目录里 AV 也可能在 boxID 子目录下
boxSrcAvPath := filepath.Join(historyDir, boxID, "storage", "av", avNode.AttributeViewID+".json")
- if gulu.File.IsExist(boxSrcAvPath) {
- srcAvPath = boxSrcAvPath
+ if !gulu.File.IsExist(boxSrcAvPath) {
+ return fmt.Errorf("encrypted attribute view history is missing notebook context [%s]", avNode.AttributeViewID)
}
+ srcAvPath = boxSrcAvPath
destAvPath = filepath.Join(util.DataDir, boxID, "storage", "av", avNode.AttributeViewID+".json")
}
if gulu.File.IsExist(destAvPath) {
@@ -516,8 +526,19 @@ func RollbackAssetsHistory(historyPath string) (err error) {
relPath := strings.TrimPrefix(filepath.ToSlash(historyPath), filepath.ToSlash(util.HistoryDir))
relPath = strings.TrimPrefix(relPath, "/")
pathParts := strings.SplitN(relPath, "/", 3)
+ data, readErr := filelock.ReadFile(from)
+ if readErr != nil {
+ return readErr
+ }
+ encrypted := bytes.HasPrefix(data, encryptedAssetMagic)
+ if encrypted && (len(pathParts) < 3 || !ast.IsNodeIDPattern(pathParts[1]) || !IsEncryptedBox(pathParts[1])) {
+ return errors.New("encrypted asset history is missing valid notebook context")
+ }
to := filepath.Join(util.DataDir, "assets", filepath.Base(historyPath))
if len(pathParts) >= 2 && IsEncryptedBox(pathParts[1]) {
+ if !encrypted {
+ return fmt.Errorf("encrypted notebook asset history is plaintext [%s]", pathParts[1])
+ }
// 加密笔记本的资源回滚到笔记本级 assets 目录
to = filepath.Join(util.DataDir, pathParts[1], "assets", filepath.Base(historyPath))
if err = os.MkdirAll(filepath.Dir(to), 0755); err != nil {
@@ -551,6 +572,31 @@ func validateHistoryPath(historyPath string) (string, error) {
return p, nil
}
+// IsEncryptedHistoryPath 判断历史路径是否明确属于加密笔记本。
+func IsEncryptedHistoryPath(absPath string) bool {
+ boxID := ExtractBoxIDFromHistoryPath(absPath)
+ if boxID == "" {
+ return false
+ }
+ if IsEncryptedBox(boxID) {
+ return true
+ }
+ rel, err := filepath.Rel(util.HistoryDir, absPath)
+ if err != nil {
+ return false
+ }
+ parts := strings.SplitN(filepath.ToSlash(rel), "/", 3)
+ if len(parts) < 2 || parts[1] != boxID {
+ return false
+ }
+ encrypted, err := isEncryptedHistoryBoxDir(filepath.Join(util.HistoryDir, parts[0], boxID))
+ if err != nil {
+ logging.LogErrorf("inspect encrypted history path [%s] failed: %s", absPath, err)
+ return true
+ }
+ return encrypted
+}
+
func RollbackNotebookHistory(historyPath string) (err error) {
historyPath, err = validateHistoryPath(historyPath)
if err != nil {
@@ -585,8 +631,19 @@ func RollbackAttributeViewHistory(historyPath string) (err error) {
relPath := strings.TrimPrefix(filepath.ToSlash(historyPath), filepath.ToSlash(util.HistoryDir))
relPath = strings.TrimPrefix(relPath, "/")
pathParts := strings.SplitN(relPath, "/", 3)
+ data, readErr := filelock.ReadFile(from)
+ if readErr != nil {
+ return readErr
+ }
+ ciphertext := util.IsCiphertext(data)
+ if ciphertext && (len(pathParts) < 3 || !ast.IsNodeIDPattern(pathParts[1]) || !IsEncryptedBox(pathParts[1])) {
+ return errors.New("encrypted attribute view history is missing valid notebook context")
+ }
to := filepath.Join(util.DataDir, "storage", "av", filepath.Base(historyPath))
if len(pathParts) >= 2 && IsEncryptedBox(pathParts[1]) {
+ if !ciphertext {
+ return fmt.Errorf("encrypted notebook attribute view history is plaintext [%s]", pathParts[1])
+ }
// 加密笔记本的 AV 定义回滚到笔记本级目录
to = filepath.Join(util.DataDir, pathParts[1], "storage", "av", filepath.Base(historyPath))
if err = os.MkdirAll(filepath.Dir(to), 0755); err != nil {
diff --git a/kernel/model/history_diff.go b/kernel/model/history_diff.go
index c598c0e2ff..7e60c201b0 100644
--- a/kernel/model/history_diff.go
+++ b/kernel/model/history_diff.go
@@ -34,6 +34,7 @@ import (
"github.com/88250/lute/parse"
"github.com/88250/lute/render"
"github.com/siyuan-note/dataparser"
+ "github.com/siyuan-note/dejavu/entity"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/filesys"
@@ -110,6 +111,41 @@ type docDiffLCSBudget struct {
remaining int
}
+// ResolveDocVersionBoxID 返回文档版本引用中明确记录的加密笔记本 ID。
+func ResolveDocVersionBoxID(ref *DocVersionRef) (string, error) {
+ if ref == nil {
+ return "", errors.New("document version is required")
+ }
+ switch ref.Type {
+ case docVersionCurrent:
+ if !ast.IsNodeIDPattern(ref.ID) {
+ return "", errors.New("current document ID is invalid")
+ }
+ blockTree := treenode.GetBlockTree(ref.ID)
+ if blockTree == nil {
+ return "", ErrTreeNotFound
+ }
+ if IsEncryptedBox(blockTree.BoxID) {
+ return blockTree.BoxID, nil
+ }
+ return "", nil
+ case docVersionHistory:
+ absPath, err := validateHistoryPath(ref.Path)
+ if err != nil {
+ return "", err
+ }
+ boxID := ExtractBoxIDFromHistoryPath(absPath)
+ if IsEncryptedBox(boxID) {
+ return boxID, nil
+ }
+ return "", nil
+ case docVersionSnapshot:
+ return ResolveRepoFileBoxID(ref.ID)
+ default:
+ return "", fmt.Errorf("unsupported document version type [%s]", ref.Type)
+ }
+}
+
// DiffDocVersions 比较同一文档的两个版本,并返回带临时差异标记的只读块 DOM。
func DiffDocVersions(leftRef, rightRef *DocVersionRef) (ret *DocVersionDiffResult, err error) {
if (nil != leftRef && docVersionCurrent == leftRef.Type) || (nil != rightRef && docVersionCurrent == rightRef.Type) {
@@ -306,27 +342,27 @@ func loadHistoryDocVersion(historyPath string) (ret *loadedDocVersion, err error
return nil, err
}
parts := strings.SplitN(filepath.ToSlash(relPath), "/", 3)
- if len(parts) >= 2 && IsEncryptedBox(parts[1]) {
- HoldBoxReadLock(parts[1])
- defer ReleaseBoxReadLock(parts[1])
- }
data, err := filelock.ReadFile(absPath)
if err != nil {
return nil, err
}
- if len(parts) >= 2 && IsEncryptedBox(parts[1]) {
+ ciphertext := util.IsCiphertext(data)
+ if ciphertext {
+ if len(parts) < 3 || !ast.IsNodeIDPattern(parts[1]) || !IsEncryptedBox(parts[1]) {
+ return nil, errors.New("encrypted document history is missing valid notebook context")
+ }
+ HoldBoxReadLock(parts[1])
+ defer ReleaseBoxReadLock(parts[1])
dek, dekErr := GetDEKIfUnlocked(parts[1])
if dekErr != nil {
return nil, errors.New(Conf.Language(314))
}
- filePath := ""
- if len(parts) >= 3 {
- filePath = parts[2]
- }
- data, err = DecryptFile(parts[1], filePath, dek, data)
+ data, err = DecryptFile(parts[1], parts[2], dek, data)
if err != nil {
return nil, err
}
+ } else if len(parts) >= 2 && IsEncryptedBox(parts[1]) {
+ return nil, fmt.Errorf("encrypted notebook document history is plaintext [%s]", parts[1])
}
rootID := strings.TrimSuffix(filepath.Base(absPath), filepath.Ext(absPath))
@@ -382,20 +418,23 @@ func loadSnapshotDocVersion(fileID string) (ret *loadedDocVersion, err error) {
if err != nil {
return nil, err
}
- if 0 < len(pathParts) && IsEncryptedBox(pathParts[0]) {
+ ciphertext := util.IsCiphertext(data)
+ if ciphertext {
+ if len(pathParts) < 2 || !ast.IsNodeIDPattern(pathParts[0]) || !IsEncryptedBox(pathParts[0]) {
+ return nil, errors.New("encrypted snapshot document is missing valid notebook context")
+ }
HoldBoxReadLock(pathParts[0])
defer ReleaseBoxReadLock(pathParts[0])
dek, unlockErr := GetDEKIfUnlocked(pathParts[0])
if unlockErr != nil {
return nil, errors.New(Conf.Language(314))
}
- if 2 > len(pathParts) {
- return nil, errors.New("snapshot document path is invalid")
- }
data, err = DecryptFile(pathParts[0], pathParts[1], dek, data)
if err != nil {
return nil, err
}
+ } else if len(pathParts) > 0 && IsEncryptedBox(pathParts[0]) {
+ return nil, fmt.Errorf("encrypted notebook snapshot document is plaintext [%s]", pathParts[0])
}
rootID := strings.TrimSuffix(filepath.Base(file.Path), filepath.Ext(file.Path))
tree, err := parseDocVersionTree(data, rootID)
@@ -465,32 +504,20 @@ func loadDocVersionAttributeViewSignatures(ref *DocVersionRef, version *loadedDo
}
case docVersionHistory:
readData = func(id string) ([]byte, error) {
- candidates := []string{}
- if "" != version.boxID {
- candidates = append(candidates, filepath.Join(version.history, version.boxID, "storage", "av", id+".json"))
- }
- candidates = append(candidates, filepath.Join(version.history, "storage", "av", id+".json"))
- for _, candidate := range candidates {
- data, readErr := filelock.ReadFile(candidate)
- if nil != readErr {
- if os.IsNotExist(readErr) {
- continue
- }
- return nil, readErr
- }
- if "" != version.boxID && IsEncryptedBox(version.boxID) {
- data, readErr = av.DecryptAVData(version.boxID, id, data)
- if nil != readErr {
- return nil, readErr
- }
- }
- return data, nil
- }
boxID := ""
+ candidate := filepath.Join(version.history, "storage", "av", id+".json")
if IsEncryptedBox(version.boxID) {
boxID = version.boxID
+ candidate = filepath.Join(version.history, boxID, "storage", "av", id+".json")
}
- return av.ReadAttributeViewDataInBox(id, boxID)
+ data, readErr := filelock.ReadFile(candidate)
+ if nil != readErr {
+ if os.IsNotExist(readErr) {
+ return nil, nil
+ }
+ return nil, readErr
+ }
+ return decryptHistoricalAttributeView(boxID, id, data)
}
case docVersionSnapshot:
if "" == ref.Snapshot {
@@ -509,23 +536,24 @@ func loadDocVersionAttributeViewSignatures(ref *DocVersionRef, version *loadedDo
return nil, filesErr
}
readData = func(id string) ([]byte, error) {
+ var matchingFiles []*entity.File
for _, file := range files {
- if !strings.HasSuffix(filepath.ToSlash(file.Path), "/storage/av/"+id+".json") {
- continue
- }
- data, readErr := repo.OpenFile(file)
- if nil != readErr {
- return nil, readErr
+ if strings.HasSuffix(filepath.ToSlash(file.Path), "/storage/av/"+id+".json") {
+ matchingFiles = append(matchingFiles, file)
}
- if boxID := avBoxIDFromRepoPath(file.Path); "" != boxID && IsEncryptedBox(boxID) {
- data, readErr = av.DecryptAVData(boxID, id, data)
- if nil != readErr {
- return nil, readErr
- }
- }
- return data, nil
}
- return nil, nil
+ if len(matchingFiles) == 0 {
+ return nil, nil
+ }
+ if len(matchingFiles) != 1 {
+ return nil, fmt.Errorf("attribute view snapshot context is ambiguous [%s]", id)
+ }
+ file := matchingFiles[0]
+ data, readErr := repo.OpenFile(file)
+ if nil != readErr {
+ return nil, readErr
+ }
+ return decryptHistoricalAttributeView(avBoxIDFromRepoPath(file.Path), id, data)
}
}
if nil == readData {
diff --git a/kernel/model/import.go b/kernel/model/import.go
index d64f2e7913..7794c67d03 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -281,12 +281,18 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
} else {
createdBoxID = boxID
}
+ encryptedTarget := IsEncryptedBox(boxID)
+ storageRiffDir := filepath.Join(unzipRootPath, "storage", "riff")
+ if encryptedTarget && gulu.File.IsExist(storageRiffDir) {
+ return createdBoxID, errors.New(Conf.Language(313))
+ }
toPath = normalizeBoxDocTarget(boxID, toPath)
luteEngine := util.NewLute()
blockIDs := map[string]string{}
trees := map[string]*parse.Tree{}
importedBoxDoc := false
+ containsFlashcardAttrs := false
// 重新生成块 ID
for i, syPath := range syPaths {
@@ -304,7 +310,13 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
}
oldRootID := tree.Root.ID
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
- if !entering || "" == n.ID {
+ if !entering {
+ return ast.WalkContinue
+ }
+ if encryptedTarget && n.IsBlock() && n.IALAttr(NodeAttrRiffDecks) != "" {
+ containsFlashcardAttrs = true
+ }
+ if "" == n.ID {
return ast.WalkContinue
}
@@ -337,6 +349,9 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
trees[tree.ID] = tree
util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d", i+1, len(syPaths))))
}
+ if containsFlashcardAttrs {
+ return createdBoxID, errors.New(Conf.Language(313))
+ }
if importedBoxDoc {
if err = writeBoxDocID(boxID); err != nil {
return
@@ -515,7 +530,7 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c
}
// 将关联的闪卡数据合并到默认卡包 data/storage/riff/20230218211946-2kw8jgx 中
- storageRiffDir := filepath.Join(storage, "riff")
+ storageRiffDir = filepath.Join(storage, "riff")
if gulu.File.IsExist(storageRiffDir) {
deckToImport, loadErr := riff.LoadDeck(storageRiffDir, builtinDeckID, Conf.Flashcard.RequestRetention, Conf.Flashcard.MaximumInterval, Conf.Flashcard.Weights)
if nil != loadErr {
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index 67d673538d..acc3766d4a 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -226,6 +226,7 @@ func RemoveBox(boxID string) (err error) {
if isEncrypted {
sql.RemoveEncryptedDBFile(boxID)
treenode.RemoveEncryptedBlockTreeDBFile(boxID)
+ removeEncryptedBoxLifecycle(boxID)
}
if isUserGuide {
@@ -288,24 +289,26 @@ func unmount0(boxID string) {
return
}
+ if IsEncryptedBox(box.ID) {
+ // 先关闭生命周期准入并等待在途操作,再保存配置和历史,避免锁定准备期间继续产生明文响应或新写入。
+ lockBoxWithPreparation(boxID, func() {
+ boxConf := box.GetConf()
+ boxConf.Closed = true
+ if err := box.SaveConf(boxConf); err != nil {
+ logging.LogErrorf("save box conf [%s] failed: %s", box.ID, err)
+ }
+ sql.FlushQueue()
+ GenerateFileHistoryForBox(box)
+ })
+ return
+ }
+
boxConf := box.GetConf()
boxConf.Closed = true
if err := box.SaveConf(boxConf); err != nil {
logging.LogErrorf("save box conf [%s] failed: %s", box.ID, err)
}
- if IsEncryptedBox(box.ID) {
- // 加密笔记本关闭:跳过 Unindex(索引 db 马上要删,逐条删是白费),
- // 先等待事务队列和 SQL 索引队列落盘(确保 pending 写入已持久化到加密 .sy),
- // 生成文件历史,再 ClearDEK(=LockBox)清除 DEK 并删除加密 db 文件。
- // 加密索引可由 box.Index() 全量重建,关闭即删文件避免残留旧索引数据导致下次解锁叠加重复行。
- FlushTxQueue()
- sql.FlushQueue()
- // 关闭前生成一次文件历史:锁定后定时器无法为加密笔记本生成历史(不在 GetOpenedBoxes 里)
- GenerateFileHistoryForBox(box)
- ClearDEK(boxID)
- } else {
- box.Unindex()
- }
+ box.Unindex()
}
func Mount(boxID string) (alreadyMount bool, err error) {
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 5a8097ca5a..eac35b753d 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -213,10 +213,39 @@ func GetRepoFile(fileID string) (ret []byte, p string, err error) {
}
ret, err = repo.OpenFile(file)
+ if err != nil {
+ return
+ }
+ ret, err = decryptRepoDataIfNeeded(ret, file.Path)
p = file.Path
return
}
+// ResolveRepoFileBoxID 返回仓库文件路径中明确记录的加密笔记本 ID。
+func ResolveRepoFileBoxID(fileID string) (boxID string, err error) {
+ if 1 > len(Conf.Repo.Key) {
+ return "", errors.New(Conf.Language(26))
+ }
+ repo, err := newRepository()
+ if err != nil {
+ return "", err
+ }
+ file, err := repo.GetFile(fileID)
+ if err != nil {
+ return "", err
+ }
+ return encryptedBoxIDFromRepoPath(file.Path), nil
+}
+
+func encryptedBoxIDFromRepoPath(repoPath string) string {
+ repoPath = strings.TrimPrefix(filepath.ToSlash(repoPath), "/")
+ parts := strings.SplitN(repoPath, "/", 2)
+ if len(parts) == 2 && ast.IsNodeIDPattern(parts[0]) && IsEncryptedBox(parts[0]) {
+ return parts[0]
+ }
+ return ""
+}
+
func RollbackRepoSnapshotFile(fileID string) (err error) {
if 1 > len(Conf.Repo.Key) {
err = errors.New(Conf.Language(26))
@@ -260,10 +289,9 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {
from := filepath.Join(tempRepoDiffDir, f)
// 加密笔记本的快照数据是密文,写入临时文件前先解密
if strings.HasSuffix(file.Path, ".sy") {
- boxID := strings.TrimPrefix(file.Path, "/")
- boxID = strings.Split(boxID, "/")[0]
- if IsEncryptedBox(boxID) {
- data = decryptRepoDataIfNeeded(data, file.Path)
+ data, err = decryptRepoDataIfNeeded(data, file.Path)
+ if err != nil {
+ return
}
}
if err = os.WriteFile(from, data, 0644); nil != err {
@@ -386,10 +414,24 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
}
updated = file.Updated
+ repoPath := strings.TrimPrefix(file.Path, "/")
+ repoPathParts := strings.SplitN(repoPath, "/", 2)
+ payloadBoxID := ""
+ if len(repoPathParts) == 2 && ast.IsNodeIDPattern(repoPathParts[0]) {
+ payloadBoxID = repoPathParts[0]
+ }
+ if (util.IsCiphertext(data) || bytes.HasPrefix(data, encryptedAssetMagic)) &&
+ (payloadBoxID == "" || !IsEncryptedBox(payloadBoxID)) {
+ err = errors.New("encrypted repository data is missing valid notebook context")
+ return
+ }
if strings.HasSuffix(file.Path, ".sy") {
// 加密笔记本的 .sy 在仓库里是密文,按路径提取 boxID 解密
- data = decryptRepoDataIfNeeded(data, file.Path)
+ data, err = decryptRepoDataIfNeeded(data, file.Path)
+ if err != nil {
+ return
+ }
luteEngine := NewLute()
var snapshotTree *parse.Tree
displayInText, snapshotTree, err = parseTreeInSnapshot(data, luteEngine)
@@ -454,11 +496,11 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
data = plainData
} else {
logging.LogWarnf("decrypt repo snapshot AV [%s] failed: %s", file.Path, decErr)
- content = file.Path
+ err = decErr
return
}
} else {
- content = file.Path
+ err = errors.New(Conf.Language(314))
return
}
}
@@ -486,11 +528,11 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText b
data = plainData
} else {
logging.LogWarnf("decrypt repo snapshot asset [%s] failed: %s", file.Path, decErr)
- content = file.Path
+ err = decErr
return
}
} else {
- content = file.Path
+ err = errors.New(Conf.Language(314))
return
}
}
@@ -576,10 +618,7 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
luteEngine := NewLute()
for _, removeRight := range diff.RemovesRight {
- title, _, _ := parseTitleInSnapshot(removeRight.ID, repo, luteEngine)
- if "" == title {
- continue
- }
+ title, _ := parseTitleInSnapshotForListing(removeRight, repo, luteEngine)
ret.AddsLeft = append(ret.AddsLeft, &DiffFile{
FileID: removeRight.ID,
@@ -594,10 +633,7 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
for _, addLeft := range diff.AddsLeft {
- title, _, _ := parseTitleInSnapshot(addLeft.ID, repo, luteEngine)
- if "" == title {
- continue
- }
+ title, _ := parseTitleInSnapshotForListing(addLeft, repo, luteEngine)
ret.RemovesRight = append(ret.RemovesRight, &DiffFile{
FileID: addLeft.ID,
@@ -612,10 +648,7 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
for _, updateLeft := range diff.UpdatesLeft {
- title, _, _ := parseTitleInSnapshot(updateLeft.ID, repo, luteEngine)
- if "" == title {
- continue
- }
+ title, _ := parseTitleInSnapshotForListing(updateLeft, repo, luteEngine)
ret.UpdatesLeft = append(ret.UpdatesLeft, &DiffFile{
FileID: updateLeft.ID,
@@ -630,10 +663,7 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
for _, updateRight := range diff.UpdatesRight {
- title, _, _ := parseTitleInSnapshot(updateRight.ID, repo, luteEngine)
- if "" == title {
- continue
- }
+ title, _ := parseTitleInSnapshotForListing(updateRight, repo, luteEngine)
ret.UpdatesRight = append(ret.UpdatesRight, &DiffFile{
FileID: updateRight.ID,
@@ -649,6 +679,20 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
return
}
+func parseTitleInSnapshotForListing(file *entity.File, repo *dejavu.Repo, luteEngine *lute.Lute) (title, rootID string) {
+ if file == nil {
+ return
+ }
+ if encryptedBoxIDFromRepoPath(file.Path) != "" {
+ return path.Base(file.Path), ""
+ }
+ title, rootID, err := parseTitleInSnapshot(file.ID, repo, luteEngine)
+ if err != nil || title == "" {
+ return path.Base(file.Path), ""
+ }
+ return
+}
+
func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lute) (title, rootID string, err error) {
file, err := repo.GetFile(fileID)
if err != nil {
@@ -666,7 +710,10 @@ func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lut
}
// 加密笔记本的 .sy 在仓库里是密文,按路径提取 boxID 解密
- data = decryptRepoDataIfNeeded(data, file.Path)
+ data, err = decryptRepoDataIfNeeded(data, file.Path)
+ if err != nil {
+ return
+ }
var tree *parse.Tree
tree, err = dataparser.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
@@ -684,26 +731,30 @@ func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lut
// decryptRepoDataIfNeeded 判断仓库数据是否属于加密笔记本,如果是则按路径类型分流解密。
// file.Path 格式:/<boxID>/...
// .sy → DecryptFile,assets/* → DecryptAsset,storage/av/*.json → av.DecryptAVData。
-// 其他文件或解锁失败时返回原数据(调用方 fallback)。
-func decryptRepoDataIfNeeded(data []byte, filePath string) []byte {
+// 密文缺少有效路径上下文、笔记本未解锁或认证失败时返回错误,不允许调用方按明文继续处理。
+func decryptRepoDataIfNeeded(data []byte, filePath string) ([]byte, error) {
relPath := strings.TrimPrefix(filePath, "/")
parts := strings.SplitN(relPath, "/", 2)
- if len(parts) < 1 || !ast.IsNodeIDPattern(parts[0]) {
- return data
+ encryptedPayload := util.IsCiphertext(data) || bytes.HasPrefix(data, encryptedAssetMagic)
+ if len(parts) < 2 || !ast.IsNodeIDPattern(parts[0]) {
+ if encryptedPayload {
+ return nil, errors.New("encrypted repository data is missing notebook context")
+ }
+ return data, nil
}
boxID := parts[0]
if !IsEncryptedBox(boxID) {
- return data
+ if encryptedPayload {
+ return nil, fmt.Errorf("encrypted repository data has no matching notebook [%s]", boxID)
+ }
+ return data, nil
}
// 持读锁,防止 LockBox 在解密期间清 DEK/缓存
HoldBoxReadLock(boxID)
defer ReleaseBoxReadLock(boxID)
dek, err := GetDEKIfUnlocked(boxID)
if err != nil {
- return data // 加密笔记本未解锁:返回原数据
- }
- if len(parts) < 2 {
- return data
+ return nil, errors.New(Conf.Language(314))
}
boxRelPath := parts[1]
// 按路径类型分流
@@ -711,30 +762,29 @@ func decryptRepoDataIfNeeded(data []byte, filePath string) []byte {
diskName := filepath.Base(boxRelPath)
plain, decErr := DecryptAsset(boxID, diskName, dek, data)
if decErr != nil {
- return data
+ return nil, decErr
}
- return plain
+ return plain, nil
}
if strings.HasPrefix(boxRelPath, "storage/av/") && strings.HasSuffix(boxRelPath, ".json") {
avID := strings.TrimSuffix(filepath.Base(boxRelPath), ".json")
plain, decErr := av.DecryptAVDataLocked(boxID, avID, data)
if decErr != nil {
- return data
+ return nil, decErr
}
- return plain
+ return plain, nil
}
// .sy 和其他文件用 file 子密钥 + 相对路径 AAD
plain, decErr := DecryptFile(boxID, boxRelPath, dek, data)
if decErr != nil {
- return data
+ return nil, decErr
}
- return plain
+ return plain, nil
}
func parseTreeInSnapshot(data []byte, luteEngine *lute.Lute) (isLargeDoc bool, tree *parse.Tree, err error) {
isLargeDoc = 1024*1024*1 <= len(data)
- // data 可能是加密笔记本的密文,但 parseTreeInSnapshot 没有 file.Path 上下文
- // 密文解析会失败返回 err,调用方会 fallback 到文件名
+ // 调用方必须先根据快照路径完成解密,解析层不处理密文。
tree, err = dataparser.ParseJSONWithoutFix(data, luteEngine.ParseOptions)
if err != nil {
return
@@ -766,10 +816,7 @@ func SearchRepoFile(keyword string, page int) (ret []*DiffFile, pageCount, total
luteEngine := NewLute()
for _, file := range files {
- title, rootID, parseErr := parseTitleInSnapshot(file.ID, repo, luteEngine)
- if "" == title || nil != parseErr {
- title = path.Base(file.Path)
- }
+ title, rootID := parseTitleInSnapshotForListing(file, repo, luteEngine)
var hpath string
if "" != rootID && treenode.ExistBlockTree(rootID) {
@@ -810,10 +857,7 @@ func GetRepoDocHistory(id string, page int) (ret []*RepoDocHistory, pageCount, t
luteEngine := NewLute()
for _, file := range files {
- title, _, parseErr := parseTitleInSnapshot(file.ID, repo, luteEngine)
- if "" == title || nil != parseErr {
- title = path.Base(file.Path)
- }
+ title, _ := parseTitleInSnapshotForListing(file, repo, luteEngine)
ret = append(ret, &RepoDocHistory{
FileID: file.ID,
IndexID: fileIndexIDs[file.ID],
@@ -846,16 +890,13 @@ func ExportRepoFile(id string) (exportPath string, err error) {
return
}
- repoRel := strings.TrimPrefix(file.Path, "/")
- repoParts := strings.SplitN(repoRel, "/", 2)
- var encryptedBoxID string
- if len(repoParts) >= 1 && ast.IsNodeIDPattern(repoParts[0]) && IsEncryptedBox(repoParts[0]) {
- encryptedBoxID = repoParts[0]
- }
+ encryptedBoxID := encryptedBoxIDFromRepoPath(file.Path)
// 加密笔记本的 .sy 在仓库里是密文,按路径提取 boxID 解密
- data = decryptRepoDataIfNeeded(data, file.Path)
- // 如果加密 box 已锁定,decryptRepoDataIfNeeded 返回原密文,应拒绝导出
+ data, err = decryptRepoDataIfNeeded(data, file.Path)
+ if err != nil {
+ return
+ }
if encryptedBoxID != "" {
HoldBoxReadLock(encryptedBoxID)
defer ReleaseBoxReadLock(encryptedBoxID)
@@ -2161,7 +2202,11 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,
if IsEncryptedBox(boxID) {
raw, readErr := os.ReadFile(absPath)
if readErr == nil {
- data := decryptRepoDataIfNeeded(raw, file.Path)
+ data, decryptErr := decryptRepoDataIfNeeded(raw, file.Path)
+ if decryptErr != nil {
+ logging.LogErrorf("decrypt conflicted file [%s] failed: %s", absPath, decryptErr)
+ continue
+ }
if writeErr := os.WriteFile(absPath, data, 0644); writeErr != nil {
logging.LogErrorf("decrypt conflicted file [%s] failed: %s", absPath, writeErr)
continue
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 5343ef7b8c..2ef00b376a 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -377,6 +377,11 @@ func serveExport(ginServer *gin.Engine) {
c.Status(http.StatusForbidden)
return
}
+ if acquireErr := model.AcquireEncryptedBoxOperation(boxID); acquireErr != nil {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ defer model.ReleaseEncryptedBoxOperation(boxID)
model.HoldBoxReadLock(boxID)
defer model.ReleaseBoxReadLock(boxID)
if _, dekErr := model.GetDEKIfUnlocked(boxID); dekErr != nil {
@@ -934,6 +939,11 @@ func serveSVG(context *gin.Context, assetAbsPath string) bool {
boxID := model.ExtractBoxIDFromAssetsPath(assetAbsPath)
var dek []byte
if boxID != "" && model.IsEncryptedBox(boxID) {
+ if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
+ context.Status(http.StatusForbidden)
+ return true
+ }
+ defer model.ReleaseEncryptedBoxOperation(boxID)
model.HoldBoxReadLock(boxID)
var err error
dek, err = model.GetDEKIfUnlocked(boxID)
@@ -998,6 +1008,11 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
if boxID == "" || !model.IsEncryptedBox(boxID) {
return false // 非加密 box,走原路径
}
+ if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
+ context.Status(http.StatusForbidden)
+ return true
+ }
+ defer model.ReleaseEncryptedBoxOperation(boxID)
model.HoldBoxReadLock(boxID)
dek, err := model.GetDEKIfUnlocked(boxID)
if err != nil {
@@ -1039,9 +1054,32 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {
// 否则返回 false,由调用方走原 http.ServeFile 路径。
func serveEncryptedHistory(context *gin.Context, absPath string) bool {
boxID := model.ExtractBoxIDFromHistoryPath(absPath)
- if boxID == "" || !model.IsEncryptedBox(boxID) {
+ if boxID == "" {
return false // 非加密 box,走原路径
}
+ if !model.IsEncryptedHistoryPath(absPath) {
+ source, err := os.Open(absPath)
+ if err != nil {
+ return false
+ }
+ header := make([]byte, 4)
+ n, _ := source.Read(header)
+ _ = source.Close()
+ if model.IsEncryptedNotebookData(header[:n]) {
+ context.Status(http.StatusForbidden)
+ return true
+ }
+ return false
+ }
+ if !model.IsEncryptedBox(boxID) {
+ context.Status(http.StatusForbidden)
+ return true
+ }
+ if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {
+ context.Status(http.StatusForbidden)
+ return true
+ }
+ defer model.ReleaseEncryptedBoxOperation(boxID)
model.HoldBoxReadLock(boxID)
dek, err := model.GetDEKIfUnlocked(boxID)
if err != nil {
@@ -1140,6 +1178,11 @@ func serveRepoDiff(ginServer *gin.Engine) {
// 从路径提取 boxID,加密笔记本已锁定时拒绝访问(锁定后 repo 预览解密文件仍存在磁盘上)
parts := strings.SplitN(strings.TrimPrefix(requestPath, "/"), "/", 2)
if len(parts) >= 1 && model.IsEncryptedBox(parts[0]) {
+ if err := model.AcquireEncryptedBoxOperation(parts[0]); err != nil {
+ context.Status(http.StatusForbidden)
+ return
+ }
+ defer model.ReleaseEncryptedBoxOperation(parts[0])
model.HoldBoxReadLock(parts[0])
defer model.ReleaseBoxReadLock(parts[0])
if _, dekErr := model.GetDEKIfUnlocked(parts[0]); dekErr != nil {
diff --git a/kernel/util/kdf.go b/kernel/util/kdf.go
index 994f5d6dd2..0ee1957540 100644
--- a/kernel/util/kdf.go
+++ b/kernel/util/kdf.go
@@ -32,7 +32,7 @@ import (
var encryptionMagic = [4]byte{'S', 'E', 'N', 'C'}
const (
- // EncryptionSpec 表示 AES-GCM 密文信封规范版本。旧版密文没有信封头,读取时保持兼容。
+ // EncryptionSpec 表示 AES-GCM 密文信封规范版本。
EncryptionSpec byte = 1
encryptionAlgorithmAES256GCM byte = 1
@@ -58,13 +58,9 @@ func DefaultArgon2Params() Argon2Params {
}
}
-// ValidateArgon2Params 校验 Argon2id 参数是否在合理范围内。
-// KeyLength 为 0 时视为旧配置,返回默认值;非零但不合法的参数返回错误。
-// 防止恶意备份设置极大内存导致 OOM,或过弱参数降低安全性。
+// ValidateArgon2Params 校验 Argon2id 参数是否在合理范围内,防止恶意备份设置极大内存导致 OOM,
+// 或过弱参数降低安全性。
func ValidateArgon2Params(p Argon2Params) (Argon2Params, error) {
- if p.KeyLength == 0 {
- return DefaultArgon2Params(), nil
- }
if p.KeyLength != 32 {
return p, errors.New("Argon2id KeyLength must be 32")
}
@@ -97,34 +93,30 @@ func Encrypt(key, plaintext []byte) ([]byte, error) {
return encryptGCM(key, plaintext, nil, "Encrypt")
}
-// Decrypt 对应 Encrypt 的解密。兼容旧版 nonce||ciphertext||tag 格式。
-// 密钥错误或密文被篡改时返回错误(GCM 自带完整性校验)。
+// Decrypt 对应 Encrypt 的解密。密钥错误、格式无效或密文被篡改时返回错误。
func Decrypt(key, ciphertext []byte) ([]byte, error) {
return decryptGCM(key, ciphertext, nil, "Decrypt")
}
-// EncryptionNonce 从 AES-GCM 密文中提取 nonce,兼容旧版无信封头格式。
+// EncryptionNonce 从 AES-GCM 密文信封中提取 nonce。
func EncryptionNonce(ciphertext []byte) ([]byte, error) {
- if hasEncryptionMagic(ciphertext) {
- if len(ciphertext) < encryptionEnvelopeHeaderSize {
- return nil, errors.New("encrypted envelope too short")
- }
- if ciphertext[len(encryptionMagic)] != EncryptionSpec {
- return nil, errors.New("unsupported encrypted envelope spec")
- }
- if ciphertext[len(encryptionMagic)+1] != encryptionAlgorithmAES256GCM {
- return nil, errors.New("unsupported encrypted envelope algorithm")
- }
- nonceLength := int(ciphertext[len(encryptionMagic)+2])
- if nonceLength == 0 || len(ciphertext) < encryptionEnvelopeHeaderSize+nonceLength {
- return nil, errors.New("invalid encrypted envelope nonce length")
- }
- return append([]byte(nil), ciphertext[encryptionEnvelopeHeaderSize:encryptionEnvelopeHeaderSize+nonceLength]...), nil
+ if !hasEncryptionMagic(ciphertext) {
+ return nil, errors.New("invalid encrypted envelope magic")
+ }
+ if len(ciphertext) < encryptionEnvelopeHeaderSize {
+ return nil, errors.New("encrypted envelope too short")
+ }
+ if ciphertext[len(encryptionMagic)] != EncryptionSpec {
+ return nil, errors.New("unsupported encrypted envelope spec")
+ }
+ if ciphertext[len(encryptionMagic)+1] != encryptionAlgorithmAES256GCM {
+ return nil, errors.New("unsupported encrypted envelope algorithm")
}
- if len(ciphertext) < 12 {
- return nil, errors.New("ciphertext too short to extract nonce")
+ nonceLength := int(ciphertext[len(encryptionMagic)+2])
+ if nonceLength == 0 || len(ciphertext) < encryptionEnvelopeHeaderSize+nonceLength {
+ return nil, errors.New("invalid encrypted envelope nonce length")
}
- return append([]byte(nil), ciphertext[:12]...), nil
+ return append([]byte(nil), ciphertext[encryptionEnvelopeHeaderSize:encryptionEnvelopeHeaderSize+nonceLength]...), nil
}
// DeriveSubKey 用 HKDF-SHA256 从主 DEK 派生用途隔离的子密钥。
@@ -149,8 +141,7 @@ func EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error) {
return encryptGCM(key, plaintext, aad, "EncryptWithAAD")
}
-// DecryptWithAAD 对应 EncryptWithAAD 的解密,兼容旧版 nonce||ciphertext||tag 格式。
-// AAD 不匹配或密文被篡改时返回错误。
+// DecryptWithAAD 对应 EncryptWithAAD 的解密。格式无效、AAD 不匹配或密文被篡改时返回错误。
func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error) {
return decryptGCM(key, ciphertext, aad, "DecryptWithAAD")
}
@@ -194,31 +185,27 @@ func decryptGCM(key, ciphertext, aad []byte, operation string) ([]byte, error) {
return nil, err
}
nonceSize := gcm.NonceSize()
- if hasEncryptionMagic(ciphertext) {
- if len(ciphertext) < encryptionEnvelopeHeaderSize {
- return nil, errors.New("encrypted envelope too short")
- }
- if ciphertext[len(encryptionMagic)] != EncryptionSpec {
- return nil, errors.New("unsupported encrypted envelope spec")
- }
- if ciphertext[len(encryptionMagic)+1] != encryptionAlgorithmAES256GCM {
- return nil, errors.New("unsupported encrypted envelope algorithm")
- }
- if int(ciphertext[len(encryptionMagic)+2]) != nonceSize {
- return nil, errors.New("invalid encrypted envelope nonce length")
- }
- if len(ciphertext) < encryptionEnvelopeHeaderSize+nonceSize+gcm.Overhead() {
- return nil, errors.New("encrypted envelope too short")
- }
- nonce := ciphertext[encryptionEnvelopeHeaderSize : encryptionEnvelopeHeaderSize+nonceSize]
- ct := ciphertext[encryptionEnvelopeHeaderSize+nonceSize:]
- return gcm.Open(nil, nonce, ct, envelopeAAD(ciphertext[:encryptionEnvelopeHeaderSize], aad))
+ if !hasEncryptionMagic(ciphertext) {
+ return nil, errors.New("invalid encrypted envelope magic")
+ }
+ if len(ciphertext) < encryptionEnvelopeHeaderSize {
+ return nil, errors.New("encrypted envelope too short")
+ }
+ if ciphertext[len(encryptionMagic)] != EncryptionSpec {
+ return nil, errors.New("unsupported encrypted envelope spec")
+ }
+ if ciphertext[len(encryptionMagic)+1] != encryptionAlgorithmAES256GCM {
+ return nil, errors.New("unsupported encrypted envelope algorithm")
+ }
+ if int(ciphertext[len(encryptionMagic)+2]) != nonceSize {
+ return nil, errors.New("invalid encrypted envelope nonce length")
}
- if len(ciphertext) < nonceSize+gcm.Overhead() {
- return nil, errors.New("ciphertext too short")
+ if len(ciphertext) < encryptionEnvelopeHeaderSize+nonceSize+gcm.Overhead() {
+ return nil, errors.New("encrypted envelope too short")
}
- nonce, ct := ciphertext[:nonceSize], ciphertext[nonceSize:]
- return gcm.Open(nil, nonce, ct, aad)
+ nonce := ciphertext[encryptionEnvelopeHeaderSize : encryptionEnvelopeHeaderSize+nonceSize]
+ ct := ciphertext[encryptionEnvelopeHeaderSize+nonceSize:]
+ return gcm.Open(nil, nonce, ct, envelopeAAD(ciphertext[:encryptionEnvelopeHeaderSize], aad))
}
func hasEncryptionMagic(ciphertext []byte) bool {
diff --git a/kernel/util/kdf_test.go b/kernel/util/kdf_test.go
index bb17408171..170a769527 100644
--- a/kernel/util/kdf_test.go
+++ b/kernel/util/kdf_test.go
@@ -49,6 +49,15 @@ func TestArgon2KDFDifferentPasswords(t *testing.T) {
}
}
+// TestArgon2KDFMissingKeyLengthRejected 验证缺少密钥长度的配置不会套用隐式默认值。
+func TestArgon2KDFMissingKeyLengthRejected(t *testing.T) {
+ params := DefaultArgon2Params()
+ params.KeyLength = 0
+ if _, err := ValidateArgon2Params(params); err == nil {
+ t.Fatal("Argon2id parameters without KeyLength should be rejected")
+ }
+}
+
// TestAESGCMRoundTrip 验证加密→解密还原原文。
func TestAESGCMRoundTrip(t *testing.T) {
key, err := GenerateDEK()
@@ -138,42 +147,32 @@ func TestAESGCMInvalidKeyLength(t *testing.T) {
}
}
-// TestAESGCMLegacyCiphertextCompatibility 验证旧 nonce||ciphertext||tag 格式仍可解密,保证升级后已有数据可读。
-func TestAESGCMLegacyCiphertextCompatibility(t *testing.T) {
+// TestAESGCMHeaderlessCiphertextRejected 验证缺少信封头的密文被拒绝。
+func TestAESGCMHeaderlessCiphertextRejected(t *testing.T) {
key, _ := GenerateDEK()
- plaintext := []byte("legacy encrypted notebook data")
- legacy, err := encryptLegacyForTest(key, plaintext, nil)
+ ciphertext, err := encryptHeaderlessForTest(key, []byte("encrypted notebook data"), nil)
if err != nil {
- t.Fatalf("create legacy ciphertext failed: %v", err)
+ t.Fatalf("create headerless ciphertext failed: %v", err)
}
- got, err := Decrypt(key, legacy)
- if err != nil {
- t.Fatalf("decrypt legacy ciphertext failed: %v", err)
- }
- if !bytes.Equal(got, plaintext) {
- t.Fatalf("legacy round-trip mismatch")
+ if _, err = Decrypt(key, ciphertext); err == nil {
+ t.Fatalf("Decrypt should reject ciphertext without an envelope")
}
}
-// TestAESGCMLegacyCiphertextWithAADCompatibility 验证旧版带 AAD 的通用密文仍可读取。
-func TestAESGCMLegacyCiphertextWithAADCompatibility(t *testing.T) {
+// TestAESGCMHeaderlessCiphertextWithAADRejected 验证带 AAD 但缺少信封头的密文被拒绝。
+func TestAESGCMHeaderlessCiphertextWithAADRejected(t *testing.T) {
key, _ := GenerateDEK()
- plaintext := []byte("legacy encrypted data")
aad := []byte("siyuan:test:object")
- legacy, err := encryptLegacyForTest(key, plaintext, aad)
- if err != nil {
- t.Fatalf("create legacy ciphertext failed: %v", err)
- }
- got, err := DecryptWithAAD(key, legacy, aad)
+ ciphertext, err := encryptHeaderlessForTest(key, []byte("encrypted data"), aad)
if err != nil {
- t.Fatalf("decrypt legacy ciphertext with AAD failed: %v", err)
+ t.Fatalf("create headerless ciphertext failed: %v", err)
}
- if !bytes.Equal(got, plaintext) {
- t.Fatalf("legacy AAD round-trip mismatch")
+ if _, err = DecryptWithAAD(key, ciphertext, aad); err == nil {
+ t.Fatalf("DecryptWithAAD should reject ciphertext without an envelope")
}
}
-func encryptLegacyForTest(key, plaintext, aad []byte) ([]byte, error) {
+func encryptHeaderlessForTest(key, plaintext, aad []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err