Skip to content

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

:sparkles: Extend document addressing compatibility guards https://github.com/siyuan-note/siyuan/issues/19938

Danielada5d9b0d369
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 04ee05f93f..780b8ead2f 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -5190,6 +5190,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。
+ * 工作空间外的加密资源解密导出仍要求既有授权和操作租约。
+ */
"/api/file/copyFile": {
request: CopyFileRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -2; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -5212,6 +5216,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin"];
};
+ /**
+ * 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。
+ * 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
+ */
"/api/file/globalCopyFiles": {
request: CopyFilesRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -2 | -3 | 403; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -5219,6 +5227,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。
+ * 不允许覆盖本机 conf/document-addressing.json,恢复设置时须使用 importConf 的逐身份合并流程。
+ */
"/api/file/putFile": {
request: PutFileRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -3 | 400 | 403 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -5233,6 +5245,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin"];
};
+ /**
+ * 对不支持寻址模式的笔记本拒绝部分删除,返回 -1;整本删除保留已确认的本机能力下界。
+ * 不能删除本机 conf/document-addressing.json 或其父目录,既有加密笔记本删除限制不变。
+ */
"/api/file/removeFile": {
request: RemoveFileRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -3 | 403 | 404 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -5240,6 +5256,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。
+ * 不能借重命名覆盖、移动或删除本机 conf/document-addressing.json;既有加密边界不变。
+ */
"/api/file/renameFile": {
request: RenameFileRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -3 | 403 | 404 | 409 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -5247,6 +5267,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。
+ * 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
+ */
"/api/file/workspaceCopyFiles": {
request: CopyFilesRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | -2 | -3 | 403; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -6013,6 +6037,9 @@ export interface APIPOSTRoutes {
output: "proxy";
proxy: {"kind":"http","contentType":"application/octet-stream","upstreamStatuses":true};
};
+ /**
+ * 在改密恢复、密钥切换及迁移记录写入前预检全部现存加密笔记本,不支持的寻址模式返回 -1。
+ */
"/api/notebook/changeMasterPassword": {
request: ChangeMasterPasswordRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -6037,6 +6064,7 @@ export interface APIPOSTRoutes {
/**
* 移出已导出的加密笔记本,要求管理员权限并禁止只读模式;saved: true 表示用户确认已保存归档。
* 提交前重新检查源文件,内容变化需重新导出;重复提交同一归档不会重复移出,未选择的笔记本不受影响。
+ * 移出前重新检查笔记本寻址能力,不支持的模式返回 -1,保留原归档及源目录。
*/
"/api/notebook/commitNotebookArchive": {
request: CommitNotebookArchiveRequestInput;
@@ -6111,6 +6139,7 @@ export interface APIPOSTRoutes {
/**
* 接收 multipart 的 file、旧 password 和可选密钥备份 key,要求管理员权限并禁止只读模式。
* 恢复目标必须关闭同步,且没有加密密钥配置或加密数据;密文全部通过认证后才发布,恢复后保持锁定。
+ * 认证后、安装任何数据或密钥前检查全部源身份的寻址能力;不能通过旧归档降低本机已确认的要求。
*/
"/api/notebook/importNotebookArchive": {
request: ImportNotebookArchiveRequestInput;
@@ -6157,6 +6186,7 @@ export interface APIPOSTRoutes {
/**
* 接收已锁定的加密笔记本 ID,返回归档 ID 和下载路径,不删除源数据,要求管理员权限。
* 下载完成后,必须由用户确认已保存归档,再调用 `/api/notebook/commitNotebookArchive` 并传入 saved: true。
+ * 不支持笔记本寻址模式时返回 -1,保留源目录及密钥材料。
*/
"/api/notebook/prepareNotebookArchive": {
request: PrepareNotebookArchiveRequestInput;
@@ -6227,6 +6257,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin"];
};
+ /**
+ * 解锁及挂载均检查笔记本寻址能力;不支持的模式不会发布解锁状态或修复源数据。
+ */
"/api/notebook/unlockAndOpenNotebook": {
request: UnlockNotebookRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -6234,6 +6267,9 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
+ /**
+ * 在密钥恢复和解锁转换前拒绝不支持的笔记本寻址模式,保留原密文和恢复材料。
+ */
"/api/notebook/unlockNotebook": {
request: UnlockNotebookRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -7814,6 +7850,10 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin"];
};
+ /**
+ * 保持单个 JSON 文件的设置压缩包,存在本机寻址能力下界时附加 documentAddressing 记录。
+ * 记录仅含版本及笔记本身份的最低模式,不导出标题、正文或密钥;无能力记录的旧设置格式不变。
+ */
"/api/system/exportConf": {
request: EmptyRequestInput;
response: { "code": 0; "data": SystemExportConfData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -7940,6 +7980,7 @@ export interface APIPOSTRoutes {
* 主题、图标和代码片段内容等独立资源不随设置包迁移,外观资源列表使用目标工作空间的可用资源。
* 账号、API token、同步、锁屏密码、数据仓库和加密笔记本密钥保持不变;沿用本机代理及更新通道。
* ChatGPT 账户引用从本机工作空间绑定加载,忽略导入文件中的引用;本机绑定读取失败时中止导入。
+ * documentAddressing 按笔记本身份合并最高要求,缺失字段不清除本机记录;未知或损坏记录在采用设置前返回 -1。
*/
"/api/system/importConf": {
request: SystemImportConfRequestInput;
diff --git a/docs/API.ja.md b/docs/API.ja.md
index cd974bbe28..2c72e813c4 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -1475,6 +1475,8 @@ if (response.code === 0 && response.data) {
### ファイルを配置
* `/api/file/putFile`
+
+ノートブックのアドレス指定モードが未対応の場合、ディレクトリの作成、内容の書き込み、更新日時の変更を行う前に `code: -1` を返します。この API ではローカルの機能要件記録 `conf/document-addressing.json` を上書きできません。
* パラメータはHTTP Multipartフォーム
* `path`: ワークスペースパス配下のファイルパス
@@ -1494,6 +1496,8 @@ if (response.code === 0 && response.data) {
### ファイルを削除
* `/api/file/removeFile`
+
+未対応のアドレス指定モードを使うノートブックの一部を削除すると `code: -1` を返します。ノートブック全体を削除しても、ローカルで確認済みの機能要件は保持されます。`conf/document-addressing.json` またはその親ディレクトリの削除は禁止され、暗号化ノートブックの既存の制限も引き続き適用されます。
* パラメータ
```json
@@ -1515,6 +1519,8 @@ if (response.code === 0 && response.data) {
### ファイルの名前を変更
* `/api/file/renameFile`
+
+移動先ディレクトリの作成やファイルの移動前に、操作全体のノートブックのアドレス指定互換性を検証します。未対応のモード、および `conf/document-addressing.json` の移動や上書きは `code: -1` を返します。
* パラメータ
```json
diff --git a/docs/API.md b/docs/API.md
index 7cb86a3166..3258ef10e2 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1483,6 +1483,8 @@ Block-writing APIs can return after their block-tree transaction is committed bu
### Put file
* `/api/file/putFile`
+
+Unsupported notebook addressing modes return `code: -1` before creating directories, writing content, or changing timestamps. This endpoint cannot overwrite the local `conf/document-addressing.json` capability record.
* The parameter is an HTTP Multipart form
* `path`: the file path under the workspace path
@@ -1502,6 +1504,8 @@ Block-writing APIs can return after their block-tree transaction is committed bu
### Remove file
* `/api/file/removeFile`
+
+Partial deletion in a notebook with an unsupported addressing mode returns `code: -1`. Whole-notebook deletion retains its locally confirmed capability requirement. Deleting `conf/document-addressing.json` or its parent directory is rejected; existing encrypted-notebook restrictions still apply.
* Parameters
```json
@@ -1523,6 +1527,8 @@ Block-writing APIs can return after their block-tree transaction is committed bu
### Rename file
* `/api/file/renameFile`
+
+The complete move is checked for notebook addressing compatibility before creating the destination directory or moving files. Unsupported modes and attempts to move or overwrite `conf/document-addressing.json` return `code: -1`.
* Parameters
```json
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index a08d4a3995..83ab11e979 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -1481,6 +1481,8 @@ if (response.code === 0 && response.data) {
### 写入文件
* `/api/file/putFile`
+
+笔记本寻址模式不受支持时返回 `code: -1`,不会创建目录、写入内容或更新时间。此接口不能覆盖本机 `conf/document-addressing.json` 能力记录。
* 参数为 HTTP Multipart 表单
* `path`:工作空间路径下的文件路径
@@ -1500,6 +1502,8 @@ if (response.code === 0 && response.data) {
### 删除文件
* `/api/file/removeFile`
+
+笔记本寻址模式不受支持时,部分删除返回 `code: -1`;整本删除保留本机已确认的能力要求。禁止删除 `conf/document-addressing.json` 或其父目录,既有加密笔记本限制继续生效。
* 参数
```json
@@ -1521,6 +1525,8 @@ if (response.code === 0 && response.data) {
### 重命名文件
* `/api/file/renameFile`
+
+创建目标目录或移动文件之前会检查完整操作的笔记本寻址兼容性。不支持的模式,以及移动或覆盖 `conf/document-addressing.json` 的操作,返回 `code: -1`。
* 参数
```json
diff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.md
index 18681a82e7..8fb2dd2fea 100644
--- a/docs/DOCUMENT-ADDRESSING.md
+++ b/docs/DOCUMENT-ADDRESSING.md
@@ -374,6 +374,8 @@ Activation writes a separate capability floor record `{version: 1, notebook, min
The local record uses `{version: 1, notebooks: {"<notebookID>": 2}}`, omitting notebooks with no higher requirement. Reading ordinary compatibility-mode data creates no record and rewrites no source data. Replace the record atomically and merge by taking the maximum for each identity, never by overwriting it with an older record. Once a local read or sync or snapshot preflight has observed a valid higher requirement, retain it even if insufficient capability rejects that batch, so the next read of older local configuration cannot resume ordinary writes. Remembering a capability requirement does not activate structured titles. Inspecting a standalone native notebook import does not record a source identity that has not been adopted into the workspace.
+Settings export remains an archive containing one JSON file. When confirmed capability requirements exist, that JSON carries a top-level `documentAddressing` field with the same structure as the local record. Import validates and merges the maximum requirement per identity before adopting ordinary settings; an older backup without this field does not clear the local record, and invalid or unknown record versions fail before settings are adopted. This field only transfers backup information: restoration keeps it in `conf/document-addressing.json`, outside ordinary `conf.json`, and includes no titles, content, or keys. Raw file APIs must not overwrite, rename, or delete the local record. Notebook writes and copies preflight incoming configuration and all destinations; sort recovery preserves original files and pending recovery records for unsupported modes.
+
The protective release recognizes both configuration and capability floor records, rejecting unsupported modes before processing source files. Sync application and snapshot restoration check affected notebooks' capability requirements before replacing configuration or files. Once mode `2` is confirmed, incoming old configuration, missing new fields, or deletion of a capability record cannot lower the effective mode; restore configuration projections and floor records before reopening access. If checks can occur only after files are persisted, or the dependency cannot expose required configuration before application, stage A is incomplete. Complete sync and recovery entry points first; index rebuilding does not substitute for pre-application protection.
Deleting an entire notebook retains existing semantics; do not recreate it merely to restore a capability record. Keep the locally confirmed floor for that identity and apply it when the same identity is restored. Native imports of whole notebooks validate the source identity and capability record before allocating or reusing the destination identity under existing import rules, then bind the floor to that destination identity. Identity remapping must not lower the source notebook's confirmed mode. Importing selected documents into an existing notebook instead checks the complete operation set described above without copying the source notebook's mode configuration.
diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.md
index 70942a9f9d..4333f8b43c 100644
--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md
+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md
@@ -374,6 +374,8 @@
本机记录采用 `{version: 1, notebooks: {"<notebookID>": 2}}`,省略尚无较高要求的笔记本;普通兼容模式读取不创建记录或改写源数据。记录写入必须原子替换,合并时逐个身份取最大值,不能用较旧记录整体覆盖。本机或同步、快照预检已经读到合法的较高要求时,即使本次批次因能力不足被拒绝,也保留该要求,防止下一次读取旧的本地配置时恢复普通写入;记住能力要求不等于启用结构化标题。导入时尚未采用的独立原生笔记本身份不因此写入本机记录。
+设置导出仍为包含一个 JSON 文件的压缩包,有已确认的能力下界时,在该 JSON 顶层附加 `documentAddressing`,内容与本机记录同构。导入在采用普通设置之前校验并逐身份合并最高要求;旧设置缺少此字段时不清除本机记录,损坏或未知版本在采用设置前报错。该字段只用于备份传递,恢复后仍独立保存在 `conf/document-addressing.json`,不写入普通 `conf.json`,也不包含标题、正文或密钥。原始文件接口不得直接覆盖、重命名或删除本机记录;笔记本写入及复制须预检待写配置和整批目标,排序恢复须保留不支持模式的原文件及恢复记录。
+
保护版本同时识别配置及能力下界记录;不支持的模式在实际处理源文件前拒绝。同步应用和快照恢复先核对受影响笔记本的能力要求,再替换配置或文件。已确认模式 `2` 时,传入旧配置、缺少新字段或删除能力记录都不能降低有效模式;恢复配置投影和下界记录后再开放访问。若只能在文件落盘后检查,或依赖层不能在应用前提供所需配置数据,阶段 A 尚未完成,须先补齐同步和恢复入口,不能以重建索引代替前置保护。
删除整个笔记本仍按现有语义执行,不为补齐能力记录而重新创建已删除的笔记本;本机保留该身份的已确认下界,恢复同一身份时继续生效。完整笔记本的原生导入先校验源身份与能力记录,再按既有导入规则分配或复用目标身份,并将能力下界绑定到目标身份;不得借身份重映射降低源笔记本已确认的模式。向既有笔记本导入部分文档则按前述完整操作集合检查,不直接复制源笔记本的模式配置。
diff --git a/kernel/api/contract_document_addressing_test.go b/kernel/api/contract_document_addressing_test.go
new file mode 100644
index 0000000000..e20d0ba909
--- /dev/null
+++ b/kernel/api/contract_document_addressing_test.go
@@ -0,0 +1,234 @@
+package api
+
+import (
+ archivezip "archive/zip"
+ "bytes"
+ "encoding/json"
+ "io"
+ "mime/multipart"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/internal/testutil"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const addressingAPIBox = "20261022120000-rawbox1"
+
+func addressingAPIWorkspace(t *testing.T) {
+ t.Helper()
+ importedPreferencesFixture(t)
+ data, repo := util.DataDir, util.RepoDir
+ t.Cleanup(func() { util.DataDir, util.RepoDir = data, repo })
+ util.WorkspaceDir = testutil.PublicDataDir(t)
+ util.DataDir, util.ConfDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "conf")
+ util.RepoDir, util.TempDir = filepath.Join(util.WorkspaceDir, "repo"), filepath.Join(util.WorkspaceDir, "temp")
+ for _, dir := range []string{util.DataDir, util.ConfDir, util.TempDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func addressingAPIWrite(t *testing.T, name, value string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(name, []byte(value), 0600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func addressingAPIRequest(t *testing.T, route string, handler gin.HandlerFunc, payload interface{}) int {
+ t.Helper()
+ data, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Set(model.RoleContextKey, model.RoleAdministrator)
+ c.Request = httptest.NewRequest("POST", "/api/file/"+route, bytes.NewReader(data))
+ c.Request.Header.Set("Content-Type", "application/json")
+ handler(c)
+ requireAPIContract(t, "POST", "/api/file/"+route, recorder)
+ var response struct{ Code int }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ return response.Code
+}
+
+func addressingAPIPut(t *testing.T, name, value string, directory bool) int {
+ t.Helper()
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ _ = writer.WriteField("path", name)
+ if directory {
+ _ = writer.WriteField("isDir", "true")
+ } else {
+ part, err := writer.CreateFormFile("file", "document.sy")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = io.WriteString(part, value)
+ }
+ _ = writer.Close()
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest("POST", "/api/file/putFile", &body)
+ c.Request.Header.Set("Content-Type", writer.FormDataContentType())
+ putFile(c)
+ requireAPIContract(t, "POST", "/api/file/putFile", recorder)
+ var response struct{ Code int }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ return response.Code
+}
+
+func TestAPIContractDocumentAddressingRawWrites(t *testing.T) {
+ addressingAPIWorkspace(t)
+ confPath := filepath.Join(util.DataDir, addressingAPIBox, ".siyuan", "conf.json")
+ addressingAPIWrite(t, confPath, `{"documentAddressingVersion":2}`)
+ name := "data/" + addressingAPIBox + "/original.sy"
+ abs := filepath.Join(util.WorkspaceDir, name)
+ addressingAPIWrite(t, abs, "future source")
+ addressingAPIWrite(t, filepath.Join(util.DataDir, "assets", "source.txt"), "asset")
+ before, _ := os.Stat(abs)
+ if code := addressingAPIPut(t, name, "overwrite", false); code != -1 {
+ t.Fatalf("put accepted unsupported notebook: %d", code)
+ }
+ if code := addressingAPIPut(t, "data/"+addressingAPIBox+"/new/child", "", true); code != -1 {
+ t.Fatalf("mkdir accepted unsupported notebook: %d", code)
+ }
+ for _, test := range []struct {
+ route string
+ handler gin.HandlerFunc
+ body interface{}
+ }{
+ {"removeFile", removeFile, apicontract.RemoveFileRequest{Path: name}},
+ {"removeFile", removeFile, apicontract.RemoveFileRequest{Path: "data/" + addressingAPIBox + "/.siyuan"}},
+ {"renameFile", renameFile, apicontract.RenameFileRequest{Path: name, NewPath: "new-parent/moved.sy"}},
+ {"workspaceCopyFiles", workspaceCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{name}, DestDir: "new-parent"}},
+ {"globalCopyFiles", globalCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{abs}, DestDir: "new-parent"}},
+ {"copyFile", copyFile, apicontract.CopyFileRequest{Src: "assets/source.txt", Dest: abs}},
+ } {
+ if code := addressingAPIRequest(t, test.route, test.handler, test.body); code != -1 {
+ t.Fatalf("%s accepted unsupported notebook: %d", test.route, code)
+ }
+ }
+ after, _ := os.Stat(abs)
+ data, _ := os.ReadFile(abs)
+ if string(data) != "future source" || !before.ModTime().Equal(after.ModTime()) {
+ t.Fatal("rejected operations modified the source")
+ }
+ for _, path := range []string{filepath.Join(util.WorkspaceDir, "new-parent"), filepath.Join(util.DataDir, addressingAPIBox, "new")} {
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("rejected operation created directory: %s, %v", path, err)
+ }
+ }
+ if code := addressingAPIRequest(t, "removeFile", removeFile, apicontract.RemoveFileRequest{Path: "data/" + addressingAPIBox}); code != 0 {
+ t.Fatalf("whole notebook deletion failed: %d", code)
+ }
+ if code := addressingAPIPut(t, name, "old restored source", false); code != -1 {
+ t.Fatalf("same identity lost its remembered requirement: %d", code)
+ }
+ if _, err := os.Stat(filepath.Dir(abs)); !os.IsNotExist(err) {
+ t.Fatal("rejected restore recreated the deleted notebook")
+ }
+ for path, expected := range map[string]int{"conf/document-addressing.json": -1, "conf": 403} {
+ if code := addressingAPIRequest(t, "removeFile", removeFile, apicontract.RemoveFileRequest{Path: path}); code != expected {
+ t.Fatalf("local floor protection changed for %s: %d", path, code)
+ }
+ }
+ if code := addressingAPIPut(t, "conf/document-addressing.json", `{"version":1,"notebooks":{}}`, false); code != -1 {
+ t.Fatalf("local floor overwritten: %d", code)
+ }
+}
+
+func TestAPIContractDocumentAddressingIncomingBatch(t *testing.T) {
+ addressingAPIWorkspace(t)
+ source := testutil.PublicDataDir(t)
+ plain := filepath.Join(source, "first.txt")
+ future := filepath.Join(source, addressingAPIBox)
+ addressingAPIWrite(t, plain, "first")
+ addressingAPIWrite(t, filepath.Join(future, ".siyuan", "conf.json"), `{"documentAddressingVersion":2}`)
+ addressingAPIWrite(t, filepath.Join(future, "document.sy"), "future source")
+ if code := addressingAPIRequest(t, "globalCopyFiles", globalCopyFiles,
+ apicontract.CopyFilesRequest{Srcs: []string{plain, future}, DestDir: "data"}); code != -1 {
+ t.Fatalf("incoming unsupported batch accepted: %d", code)
+ }
+ entries, _ := os.ReadDir(util.DataDir)
+ if len(entries) != 0 {
+ t.Fatalf("batch wrote files before checking all notebooks: %v", entries)
+ }
+ if code := addressingAPIPut(t, "data/20261022120000-rawbox2/.siyuan/conf.json", `{"documentAddressingVersion":2}`, false); code != -1 {
+ t.Fatalf("incoming mode accepted: %d", code)
+ }
+ entries, _ = os.ReadDir(util.DataDir)
+ if len(entries) != 0 {
+ t.Fatal("rejected put created the notebook directory")
+ }
+ if code := addressingAPIPut(t, "data/20261022120000-rawbox3/document.sy", "legacy raw data", false); code != 0 {
+ t.Fatalf("legacy write changed: %d", code)
+ }
+}
+
+func TestAPIContractDocumentAddressingSettingsBackup(t *testing.T) {
+ addressingAPIWorkspace(t)
+ addressingAPIWrite(t, filepath.Join(util.DataDir, addressingAPIBox, ".siyuan", "conf.json"), `{"documentAddressingVersion":2}`)
+ _ = documentaddressing.CheckBox(util.DataDir, util.ConfDir, addressingAPIBox)
+ recorder := systemContractRequest(t, "POST", "exportConf", exportConf, nil)
+ var response struct {
+ Code int
+ Data apicontract.SystemExportConfData
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {
+ t.Fatalf("export failed: %s, %v", recorder.Body.String(), err)
+ }
+ archive, err := archivezip.OpenReader(filepath.Join(util.TempDir, filepath.FromSlash(response.Data.Zip)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer archive.Close()
+ if len(archive.File) != 1 {
+ t.Fatal("settings export changed the single-file package")
+ }
+ file, err := archive.File[0].Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := io.ReadAll(file)
+ file.Close()
+ if err != nil || !bytes.Contains(data, []byte(`"documentAddressing"`)) {
+ t.Fatalf("settings backup omitted the floor: %s, %v", data, err)
+ }
+ if code := importPreferencesRequest(t, "old.json", []byte(`{"editor":{"fontSize":18}}`)); code != 0 {
+ t.Fatalf("legacy settings import changed: %d", code)
+ }
+ if err = documentaddressing.CheckBox(util.DataDir, util.ConfDir, addressingAPIBox); err == nil {
+ t.Fatal("legacy settings lowered the floor")
+ }
+ before := model.Conf.Editor.Load().FontSize
+ if code := importPreferencesRequest(t, "invalid.json", []byte(`{"editor":{"fontSize":27},"documentAddressing":{"version":99,"notebooks":{}}}`)); code != -1 {
+ t.Fatalf("invalid backup accepted: %d", code)
+ }
+ if model.Conf.Editor.Load().FontSize != before {
+ t.Fatal("invalid backup partially applied ordinary settings")
+ }
+ util.ConfDir = t.TempDir()
+ if code := importPreferencesRequest(t, "backup.json", data); code != 0 {
+ t.Fatalf("backed up floor could not be restored: %d", code)
+ }
+ if _, err = os.Stat(filepath.Join(util.ConfDir, "document-addressing.json")); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/kernel/api/file.go b/kernel/api/file.go
index 0cc3fa4249..848a3c2f46 100644
--- a/kernel/api/file.go
+++ b/kernel/api/file.go
@@ -84,6 +84,9 @@ func copyDecryptedAsset(src, dest string) error {
if decErr != nil {
return decErr
}
+ if err := model.CheckDocumentAddressingFileWrite(dest, plain, false); err != nil {
+ return err
+ }
if writeErr := os.WriteFile(dest, plain, 0644); writeErr != nil {
return writeErr
}
@@ -185,6 +188,13 @@ var globalCopyFiles = contractHandler(apicontract.GlobalCopyFiles, func(c *gin.C
ret.Msg = "copying encrypted notebook files is not supported via this API"
return contractFailure[apicontract.Null](ret)
}
+ var destinations []string
+ for _, src := range srcs {
+ destinations = append(destinations, filepath.Join(destDir, filepath.Base(src)))
+ }
+ if err = model.CheckDocumentAddressingFileCopies(srcs, destinations); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
if filelock.IsExist(destDir) {
destInfo, statErr := os.Stat(destDir)
if statErr != nil {
@@ -291,6 +301,13 @@ var workspaceCopyFiles = contractHandler(apicontract.WorkspaceCopyFiles, func(c
ret.Msg = "copying encrypted notebook files is not supported via this API"
return contractFailure[apicontract.Null](ret)
}
+ var destinations []string
+ for _, src := range absSrcs {
+ destinations = append(destinations, filepath.Join(destDir, filepath.Base(src)))
+ }
+ if err = model.CheckDocumentAddressingFileCopies(absSrcs, destinations); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
if filelock.IsExist(destDir) {
destInfo, err := os.Stat(destDir)
if err != nil {
@@ -409,6 +426,9 @@ var copyFile = contractHandler(apicontract.CopyFile, func(c *gin.Context, reques
return contractFailure[apicontract.Null](ret)
}
+ if err = model.CheckDocumentAddressingFileCopies([]string{src}, []string{dest}); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
if err = filelock.Copy(src, dest); err != nil {
logging.LogErrorf("copy file [%s] to [%s] failed: %s", src, dest, err)
ret.Code = -1
@@ -686,6 +706,12 @@ var renameFile = contractHandler(apicontract.RenameFile, func(c *gin.Context, re
ret.Msg = "Field [newPath]: cannot rename a directory into its own subdirectory"
return contractFailure[apicontract.Null](ret)
}
+ if err = model.CheckDocumentAddressingFileCopies([]string{srcAbsPath}, []string{destAbsPath}); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
+ if err = model.CheckDocumentAddressingFileRemoval(srcAbsPath); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
affectsSync := model.PathsAffectSync(srcAbsPath)
destParent := filepath.Dir(destAbsPath)
@@ -744,10 +770,15 @@ var removeFile = contractHandler(apicontract.RemoveFile, func(c *gin.Context, re
ret.Msg = model.Conf.Language(321)
return contractFailure[apicontract.Null](ret)
}
- if err = prepareFileAssets(fileAbsPath); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return contractFailure[apicontract.Null](ret)
+ if err = model.CheckDocumentAddressingFileRemoval(fileAbsPath); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
+ if model.CheckDocumentAddressingPath(fileAbsPath) == nil {
+ if err = prepareFileAssets(fileAbsPath); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return contractFailure[apicontract.Null](ret)
+ }
}
_, err = os.Stat(fileAbsPath)
if os.IsNotExist(err) {
@@ -839,6 +870,9 @@ var putFile = contractHandler(apicontract.PutFile, func(c *gin.Context, request
}
if isDir {
+ if err = model.CheckDocumentAddressingFileWrite(fileAbsPath, nil, true); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
err = os.MkdirAll(fileAbsPath, 0755)
if err != nil {
logging.LogErrorf("make dir [%s] failed: %s", fileAbsPath, err)
@@ -853,12 +887,6 @@ var putFile = contractHandler(apicontract.PutFile, func(c *gin.Context, request
}
for range 1 {
- dir := filepath.Dir(fileAbsPath)
- if err = os.MkdirAll(dir, 0755); err != nil {
- logging.LogErrorf("put file [%s] make dir [%s] failed: %s", fileAbsPath, dir, err)
- break
- }
-
var f multipart.File
f, err = fileHeader.Open()
if err != nil {
@@ -868,11 +896,20 @@ var putFile = contractHandler(apicontract.PutFile, func(c *gin.Context, request
var data []byte
data, err = io.ReadAll(f)
+ f.Close()
if err != nil {
logging.LogErrorf("read file failed: %s", err)
break
}
+ if err = model.CheckDocumentAddressingFileWrite(fileAbsPath, data, false); err != nil {
+ break
+ }
+ dir := filepath.Dir(fileAbsPath)
+ if err = os.MkdirAll(dir, 0755); err != nil {
+ logging.LogErrorf("put file [%s] make dir [%s] failed: %s", fileAbsPath, dir, err)
+ break
+ }
err = filelock.WriteFile(fileAbsPath, data)
if err != nil {
logging.LogErrorf("write file [%s] failed: %s", fileAbsPath, err)
diff --git a/kernel/api/system.go b/kernel/api/system.go
index 9aa1856fc8..c6261ebd26 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -39,6 +39,7 @@ import (
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
"golang.org/x/mod/semver"
@@ -567,6 +568,10 @@ var exportConf = contractHandler(apicontract.SystemExportConf, func(c *gin.Conte
return
}
+ data, err = documentaddressing.ExportBackup(util.ConfDir, data)
+ if err != nil {
+ return apicontract.Failure[apicontract.SystemExportConfData](-1, err.Error())
+ }
tmp := filepath.Join(tmpDir, name)
if err = os.WriteFile(tmp, data, 0644); err != nil {
logging.LogErrorf("export conf failed: %s", err)
@@ -718,6 +723,9 @@ var importConf = contractHandler(apicontract.SystemImportConf, func(c *gin.Conte
if err = model.LoadChatGPTAccountBindings(importedConf.AI.Load()); err != nil {
return apicontract.Failure[apicontract.Null](-1, err.Error())
}
+ if err = documentaddressing.RestoreBackup(util.ConfDir, data); err != nil {
+ return apicontract.Failure[apicontract.Null](-1, err.Error())
+ }
// 旧版包缺失的新增配置段保持不变;外观资源列表仍以目标工作空间为准。
if importAppearance {
appearance := importedConf.Appearance.Load()
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index b30510e58b..f7ccb69d69 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -347,26 +347,32 @@ var (
EnableEncryptedNotebooks = define[NotebookPasswordRequest, Null]("enableEncryptedNotebooks", "/api/notebook/enableEncryptedNotebooks", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
DisableEncryptedNotebooks = define[EmptyRequest, Null]("disableEncryptedNotebooks", "/api/notebook/disableEncryptedNotebooks", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
CreateEncryptedNotebook = define[CreateEncryptedNotebookRequest, CreateNotebookData]("createEncryptedNotebook", "/api/notebook/createEncryptedNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
- UnlockNotebook = define[UnlockNotebookRequest, Null]("unlockNotebook", "/api/notebook/unlockNotebook", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
- UnlockAndOpenNotebook = define[UnlockNotebookRequest, Null]("unlockAndOpenNotebook", "/api/notebook/unlockAndOpenNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
- LockNotebook = define[NotebookIDRequest, Null]("lockNotebook", "/api/notebook/lockNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
+ // 在密钥恢复和解锁转换前拒绝不支持的笔记本寻址模式,保留原密文和恢复材料。
+ UnlockNotebook = define[UnlockNotebookRequest, Null]("unlockNotebook", "/api/notebook/unlockNotebook", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
+ // 解锁及挂载均检查笔记本寻址能力;不支持的模式不会发布解锁状态或修复源数据。
+ UnlockAndOpenNotebook = define[UnlockNotebookRequest, Null]("unlockAndOpenNotebook", "/api/notebook/unlockAndOpenNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
+ LockNotebook = define[NotebookIDRequest, Null]("lockNotebook", "/api/notebook/lockNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 保存本机加密笔记本锁屏策略,成功后广播 system 设置变更通知,供其他客户端重新读取配置。
SetEncryptedNotebookFollowSystemLock = define[EncryptedNotebookFollowSystemLockRequest, Null]("setEncryptedNotebookFollowSystemLock", "/api/notebook/setEncryptedNotebookFollowSystemLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "system"}}, "POST")
LockEncryptedNotebooksOnSystemLock = define[EmptyRequest, Null]("lockEncryptedNotebooksOnSystemLock", "/api/notebook/lockEncryptedNotebooksOnSystemLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 自动锁定分钟数由内核内存值驱动锁定行为,写入后无需广播供其他客户端重读。
- SetNotebookCryptoAutoLock = define[NotebookCryptoAutoLockRequest, Null]("setNotebookCryptoAutoLock", "/api/notebook/setNotebookCryptoAutoLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "notebookCrypto", Mode: SettingSilent}}, "POST")
+ SetNotebookCryptoAutoLock = define[NotebookCryptoAutoLockRequest, Null]("setNotebookCryptoAutoLock", "/api/notebook/setNotebookCryptoAutoLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "notebookCrypto", Mode: SettingSilent}}, "POST")
+ // 在改密恢复、密钥切换及迁移记录写入前预检全部现存加密笔记本,不支持的寻址模式返回 -1。
ChangeMasterPassword = define[ChangeMasterPasswordRequest, Null]("changeMasterPassword", "/api/notebook/changeMasterPassword", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
ExportNotebookCryptoBackup = define[EmptyRequest, NotebookCryptoBackupData]("exportNotebookCryptoBackup", "/api/notebook/exportNotebookCryptoBackup", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
TouchEncryptedNotebooks = define[EmptyRequest, Null]("touchEncryptedNotebooks", "/api/notebook/touchEncryptedNotebooks", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
GetNotebookArchiveCandidates = define[EmptyRequest, NotebookArchiveCandidatesData]("getNotebookArchiveCandidates", "/api/notebook/getNotebookArchiveCandidates", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
// 接收已锁定的加密笔记本 ID,返回归档 ID 和下载路径,不删除源数据,要求管理员权限。
// 下载完成后,必须由用户确认已保存归档,再调用 `/api/notebook/commitNotebookArchive` 并传入 saved: true。
+ // 不支持笔记本寻址模式时返回 -1,保留源目录及密钥材料。
PrepareNotebookArchive = define[PrepareNotebookArchiveRequest, NotebookArchiveData]("prepareNotebookArchive", "/api/notebook/prepareNotebookArchive", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 移出已导出的加密笔记本,要求管理员权限并禁止只读模式;saved: true 表示用户确认已保存归档。
// 提交前重新检查源文件,内容变化需重新导出;重复提交同一归档不会重复移出,未选择的笔记本不受影响。
+ // 移出前重新检查笔记本寻址能力,不支持的模式返回 -1,保留原归档及源目录。
CommitNotebookArchive = define[CommitNotebookArchiveRequest, Null]("commitNotebookArchive", "/api/notebook/commitNotebookArchive", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 接收 multipart 的 file、旧 password 和可选密钥备份 key,要求管理员权限并禁止只读模式。
// 恢复目标必须关闭同步,且没有加密密钥配置或加密数据;密文全部通过认证后才发布,恢复后保持锁定。
+ // 认证后、安装任何数据或密钥前检查全部源身份的寻址能力;不能通过旧归档降低本机已确认的要求。
ImportNotebookArchive = define[ImportNotebookArchiveRequest, Null]("importNotebookArchive", "/api/notebook/importNotebookArchive", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")
)
@@ -611,16 +617,28 @@ var GetUniqueFilename = define[FilePathRequest, FilePathData]("getUniqueFilename
var ReadDirectory = define[ReadDirectoryRequest, []DirectoryEntry]("readDir", "/api/file/readDir", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}, NonNullable: true}, "POST")
+// RenameFile 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。
+// 不能借重命名覆盖、移动或删除本机 conf/document-addressing.json;既有加密边界不变。
var RenameFile = define[RenameFileRequest, Null]("renameFile", "/api/file/renameFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}}, "POST")
+// RemoveFile 对不支持寻址模式的笔记本拒绝部分删除,返回 -1;整本删除保留已确认的本机能力下界。
+// 不能删除本机 conf/document-addressing.json 或其父目录,既有加密笔记本删除限制不变。
var RemoveFile = define[RemoveFileRequest, Null]("removeFile", "/api/file/removeFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 500}}, "POST")
+// GlobalCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。
+// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
var GlobalCopyFiles = define[CopyFilesRequest, Null]("globalCopyFiles", "/api/file/globalCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")
+// WorkspaceCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。
+// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
var WorkspaceCopyFiles = define[CopyFilesRequest, Null]("workspaceCopyFiles", "/api/file/workspaceCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")
+// CopyFile 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。
+// 工作空间外的加密资源解密导出仍要求既有授权和操作租约。
var CopyFile = define[CopyFileRequest, Null]("copyFile", "/api/file/copyFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2}}, "POST")
+// PutFile 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。
+// 不允许覆盖本机 conf/document-addressing.json,恢复设置时须使用 importConf 的逐身份合并流程。
var PutFile = define[PutFileRequest, Null]("putFile", "/api/file/putFile", AuthenticatedAccess|AdminAccess|WritableAccess, FormBody, ResponseOptions{AdditionalCodes: []int{-3, 400, 403, 500}}, "POST")
var GetFile = define[FilePathRequest, BinaryContent]("getFile", "/api/file/getFile", AuthenticatedAccess, JSONBody,
@@ -1552,6 +1570,9 @@ var SystemEnsureOnboarding = define[EmptyRequest, *SystemOnboarding]("ensureOnbo
// 顶层 force、execInstallPkg、setCurrentWorkspace 在接管时忽略;省略 recoverExit.force 保持正常同步。
// 省略或传入 null 时保持原行为及数字截断规则,认证、管理员权限及加密笔记本关闭流程不变。
var SystemExit = define[SystemExitRequest, SystemExitData]("exit", "/api/system/exit", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1, 2, 3}, DataOnError: true}, "POST")
+
+// SystemExportConf 保持单个 JSON 文件的设置压缩包,存在本机寻址能力下界时附加 documentAddressing 记录。
+// 记录仅含版本及笔记本身份的最低模式,不导出标题、正文或密钥;无能力记录的旧设置格式不变。
var SystemExportConf = define[EmptyRequest, SystemExportConfData]("exportConf", "/api/system/exportConf", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var SystemExportLog = define[EmptyRequest, SystemZipData]("exportLog", "/api/system/exportLog", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var SystemExportTLSCABundle = define[EmptyRequest, SystemPathData]("exportTLSCABundle", "/api/system/exportTLSCABundle", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
@@ -1569,6 +1590,7 @@ var SystemGetWorkspaces = define[EmptyRequest, []*SystemWorkspace]("getWorkspace
// 主题、图标和代码片段内容等独立资源不随设置包迁移,外观资源列表使用目标工作空间的可用资源。
// 账号、API token、同步、锁屏密码、数据仓库和加密笔记本密钥保持不变;沿用本机代理及更新通道。
// ChatGPT 账户引用从本机工作空间绑定加载,忽略导入文件中的引用;本机绑定读取失败时中止导入。
+// documentAddressing 按笔记本身份合并最高要求,缺失字段不清除本机记录;未知或损坏记录在采用设置前返回 -1。
var SystemImportConf = define[SystemImportConfRequest, Null]("importConf", "/api/system/importConf", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{Setting: SettingWrite{Namespace: "*"}}, "POST")
var SystemImportCustomFont = define[SystemImportFileRequest, *SystemCustomFont]("importCustomFont", "/api/system/importCustomFont", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{AdditionalCodes: []int{400, 413}}, "POST")
var SystemImportTLSCABundle = define[SystemImportFileRequest, SystemMessageData]("importTLSCABundle", "/api/system/importTLSCABundle", AuthenticatedAccess|AdminAccess|WritableAccess, MultipartBody, ResponseOptions{}, "POST")
diff --git a/kernel/documentaddressing/backup.go b/kernel/documentaddressing/backup.go
new file mode 100644
index 0000000000..205df8e14b
--- /dev/null
+++ b/kernel/documentaddressing/backup.go
@@ -0,0 +1,66 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package documentaddressing
+
+import (
+ "encoding/json"
+ "path/filepath"
+)
+
+// ExportBackup 将已确认的能力下界附在设置导出副本中,不改变普通设置或本机记录。
+func ExportBackup(confDir string, configuration []byte) ([]byte, error) {
+ storeLock.Lock()
+ defer storeLock.Unlock()
+ store, err := backupStore(confDir)
+ if err != nil {
+ return nil, err
+ }
+ if len(store.Notebooks) == 0 {
+ return configuration, nil
+ }
+ fields, err := object(configuration, false)
+ if err != nil {
+ return nil, err
+ }
+ fields["documentAddressing"], err = json.Marshal(store)
+ if err != nil {
+ return nil, err
+ }
+ return json.MarshalIndent(fields, "", " ")
+}
+
+// RestoreBackup 在采用设置前合并能力下界;旧设置没有该字段时保持本机记录不变。
+// 高版本要求只被记住,不代表当前客户端能够处理对应的笔记本。
+func RestoreBackup(confDir string, configuration []byte) error {
+ fields, err := object(configuration, true)
+ if err != nil {
+ return err
+ }
+ data, exists := fields["documentaddressing"]
+ if !exists {
+ return nil
+ }
+ notebooks, err := parseStore(data)
+ if err != nil {
+ return err
+ }
+ storeLock.Lock()
+ defer storeLock.Unlock()
+ store, err := backupStore(confDir)
+ if err != nil {
+ return err
+ }
+ for id, mode := range notebooks {
+ store.confirm(id, mode)
+ }
+ return store.save()
+}
+
+func backupStore(confDir string) (*localStore, error) {
+ if !filepath.IsAbs(confDir) {
+ return nil, ErrInvalid
+ }
+ return readStore(&localStore{Version: 1, Notebooks: map[string]int{}, path: filepath.Join(confDir, "document-addressing.json")})
+}
diff --git a/kernel/documentaddressing/backup_test.go b/kernel/documentaddressing/backup_test.go
new file mode 100644
index 0000000000..fd24ef19de
--- /dev/null
+++ b/kernel/documentaddressing/backup_test.go
@@ -0,0 +1,84 @@
+package documentaddressing
+
+import (
+ "bytes"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestBackupRetainsMaximumRequirements(t *testing.T) {
+ confDir := t.TempDir()
+ name := filepath.Join(confDir, "document-addressing.json")
+ old := []byte(`{"documentAddressing":{"version":1,"notebooks":{"20261022120000-noteb01":2}}}`)
+ newer := []byte(`{"documentAddressing":{"version":1,"notebooks":{"20261022120000-noteb01":3,"20261022120000-noteb02":2}}}`)
+ for _, data := range [][]byte{old, newer, old, []byte(`{"editor":{}}`)} {
+ if err := RestoreBackup(confDir, data); err != nil {
+ t.Fatal(err)
+ }
+ }
+ source, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ record, err := parseStore(source)
+ if err != nil || record["20261022120000-noteb01"] != 3 || record["20261022120000-noteb02"] != 2 {
+ t.Fatalf("capability requirements were lost: %s, %v", source, err)
+ }
+ backup, err := ExportBackup(confDir, []byte(`{"editor":{"fontSize":16}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ restoredDir := t.TempDir()
+ if err = RestoreBackup(restoredDir, backup); err != nil {
+ t.Fatal(err)
+ }
+ restored, err := os.ReadFile(filepath.Join(restoredDir, "document-addressing.json"))
+ if err != nil || !bytes.Equal(restored, source) {
+ t.Fatalf("backup did not preserve requirements: %s, %v", restored, err)
+ }
+ for _, invalid := range []string{
+ `{"documentAddressing":null}`,
+ `{"documentAddressing":{"version":2,"notebooks":{}}}`,
+ `{"documentAddressing":{"version":1,"notebooks":{"invalid":2}}}`,
+ `{"documentAddressing":{"version":1,"notebooks":{}},"DocumentAddressing":{}}`,
+ } {
+ if err = RestoreBackup(confDir, []byte(invalid)); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("invalid backup accepted: %s, %v", invalid, err)
+ }
+ after, _ := os.ReadFile(name)
+ if !bytes.Equal(after, source) {
+ t.Fatal("invalid backup changed the local record")
+ }
+ }
+ if err = os.WriteFile(name, []byte(`{"version":99}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = ExportBackup(confDir, []byte(`{}`)); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("invalid local record exported: %v", err)
+ }
+ if err = RestoreBackup(confDir, old); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("invalid local record overwritten: %v", err)
+ }
+ unchanged, _ := os.ReadFile(name)
+ if string(unchanged) != `{"version":99}` {
+ t.Fatal("invalid local record changed")
+ }
+}
+
+func TestBackupDoesNotMigrateLegacySettings(t *testing.T) {
+ confDir := t.TempDir()
+ data := []byte(`{"editor":{"fontSize":16}}`)
+ backup, err := ExportBackup(confDir, data)
+ if err != nil || !bytes.Equal(backup, data) {
+ t.Fatalf("legacy export changed: %s, %v", backup, err)
+ }
+ if err = RestoreBackup(confDir, backup); err != nil {
+ t.Fatal(err)
+ }
+ entries, _ := os.ReadDir(confDir)
+ if len(entries) != 0 {
+ t.Fatal("legacy settings created a capability record")
+ }
+}
diff --git a/kernel/documentaddressing/mode.go b/kernel/documentaddressing/mode.go
index e21cd4b91b..ba79fd690a 100644
--- a/kernel/documentaddressing/mode.go
+++ b/kernel/documentaddressing/mode.go
@@ -319,6 +319,10 @@ func loadStore(dataDir, confDir string) (*localStore, error) {
return nil, ErrInvalid
}
ret := &localStore{Version: 1, Notebooks: map[string]int{}, path: filepath.Join(confDir, "document-addressing.json")}
+ return readStore(ret)
+}
+
+func readStore(ret *localStore) (*localStore, error) {
data, err := filelock.ReadFile(ret.path)
if errors.Is(err, os.ErrNotExist) {
return ret, nil
@@ -326,6 +330,15 @@ func loadStore(dataDir, confDir string) (*localStore, error) {
if err != nil {
return nil, err
}
+ notebooks, err := parseStore(data)
+ if err != nil {
+ return nil, err
+ }
+ ret.Notebooks = notebooks
+ return ret, nil
+}
+
+func parseStore(data []byte) (map[string]int, error) {
fields, err := versionedObject(data)
if err != nil || len(fields) != 2 {
return nil, ErrInvalid
@@ -334,6 +347,7 @@ func loadStore(dataDir, confDir string) (*localStore, error) {
if err != nil {
return nil, err
}
+ ret := map[string]int{}
for id, value := range notebooks {
if !ast.IsNodeIDPattern(id) {
return nil, ErrInvalid
@@ -342,7 +356,7 @@ func loadStore(dataDir, confDir string) (*localStore, error) {
if err != nil {
return nil, err
}
- ret.Notebooks[id] = mode
+ ret[id] = mode
}
return ret, nil
}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 438b0e6f06..e55522438d 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -1350,6 +1350,9 @@ func deriveKEK(password string) ([]byte, error) {
// 返回解密后的 DEK 和实际使用的 BoxCrypt(可能来自 backup)。
// 若 backup 被使用会自动修复 conf.json 和刷新 backup。
func decryptBoxCrypt(boxID string, kek []byte) (dek []byte, boxCrypt *conf.BoxEncryption, err error) {
+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {
+ return nil, nil, err
+ }
boxCrypt, err = GetBoxEncryption(boxID)
if err != nil || boxCrypt == nil || len(boxCrypt.WrappedDEK) == 0 {
return nil, nil, fmt.Errorf("no encrypted key material for box [%s]", boxID)
@@ -1427,6 +1430,9 @@ func UnlockAndMountBox(boxID, password string, boxEnc *conf.BoxEncryption) (alre
}
func unlockBoxHeld(boxID string, password string, boxEnc *conf.BoxEncryption) (err error) {
+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {
+ return
+ }
if _, busy := boxLock.Load(boxID); busy {
return errors.New(Conf.language(239))
}
@@ -1754,6 +1760,15 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
if dekCount > 0 {
return errors.New("cannot change master password while encrypted notebooks are unlocked (DEKs in memory), lock them first")
}
+ encBoxIDs, listErr := listAllEncryptedBoxIDs()
+ if listErr != nil {
+ return fmt.Errorf("list encrypted notebooks failed: %w", listErr)
+ }
+ for _, id := range encBoxIDs {
+ if err := filesys.CheckDocumentAddressing(id); err != nil {
+ return err
+ }
+ }
oldKEK, err := deriveKEK(oldPassword)
if err != nil {
@@ -1780,10 +1795,6 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
// Phase 0: 遍历所有加密笔记本(含 conf 损坏但存在备份的),预计算新 WrappedDEK(内存操作)
// 允许 entries 为空:用户可能已启用加密功能但尚未创建加密笔记本,此时仍需更新全局 verifier 和 backup。
- encBoxIDs, listErr := listAllEncryptedBoxIDs()
- if listErr != nil {
- return fmt.Errorf("list encrypted notebooks failed: %w", listErr)
- }
var entries []migrationBoxEntry
for _, id := range encBoxIDs {
dek, boxCrypt, dErr := decryptBoxCrypt(id, oldKEK)
@@ -2579,6 +2590,9 @@ func writeNotebookCryptBackup(boxID string, crypt *conf.BoxEncryption) error {
if !ast.IsNodeIDPattern(boxID) {
return errors.New("invalid notebook ID")
}
+ if err := filesys.CheckDocumentAddressing(boxID); err != nil {
+ return err
+ }
if err := validateBoxEncryption(crypt); err != nil {
return err
}
diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.go
index 4ce01f4d14..b4d2681f3a 100644
--- a/kernel/model/crypto_lifecycle.go
+++ b/kernel/model/crypto_lifecycle.go
@@ -26,6 +26,7 @@ import (
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -155,6 +156,9 @@ func AcquireEncryptedBoxOperation(boxID string) error {
if boxID == "" || !IsEncryptedBox(boxID) {
return nil
}
+ if err := filesys.CheckDocumentAddressing(boxID); err != nil {
+ return err
+ }
lifecycle := getEncryptedBoxLifecycle(boxID)
lifecycle.lock.Lock()
defer lifecycle.lock.Unlock()
diff --git a/kernel/model/document_addressing_crypto_test.go b/kernel/model/document_addressing_crypto_test.go
new file mode 100644
index 0000000000..c35ef600fb
--- /dev/null
+++ b/kernel/model/document_addressing_crypto_test.go
@@ -0,0 +1,150 @@
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func setDocumentAddressingTestMode(t *testing.T, boxDirectory string, mode int) {
+ t.Helper()
+ name := filepath.Join(boxDirectory, ".siyuan", "conf.json")
+ data, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]json.RawMessage
+ if err = json.Unmarshal(data, &fields); err != nil {
+ t.Fatal(err)
+ }
+ fields["documentAddressingVersion"], _ = json.Marshal(mode)
+ data, err = json.Marshal(fields)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(name, data, 0600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDocumentAddressingEncryptedRecoveryPreservesKeys(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ password := "addressing-password"
+ if err := EnableEncryptedNotebook(password); err != nil {
+ t.Fatal(err)
+ }
+ kek, err := deriveKEK(password)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(kek)
+ boxID := "20261022120000-crypto1"
+ _ = notebookArchiveTestBox(t, boxID, kek)
+ crypt, err := GetBoxEncryption(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ setDocumentAddressingTestMode(t, filepath.Join(util.DataDir, boxID), 2)
+ original, err := archiveDirectoryFiles(util.DataDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keyState, _ := json.Marshal(currentNotebookCrypto())
+ for _, operation := range []func() error{
+ func() error { return UnlockBox(boxID, password, crypt) },
+ func() error { _, err := UnlockAndMountBox(boxID, password, crypt); return err },
+ func() error { return AcquireEncryptedBoxOperation(boxID) },
+ func() error { return writeNotebookCryptBackup(boxID, crypt) },
+ func() error { return ChangeMasterPassword(password, "different-password") },
+ func() error { _, _, err := PrepareNotebookArchive([]string{boxID}); return err },
+ } {
+ if err = operation(); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ t.Fatalf("encrypted operation admitted unsupported mode: %v", err)
+ }
+ }
+ after, err := archiveDirectoryFiles(util.DataDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ beforeJSON, _ := json.Marshal(original)
+ afterJSON, _ := json.Marshal(after)
+ if !bytes.Equal(beforeJSON, afterJSON) {
+ t.Fatal("rejected recovery changed ciphertext or key backups")
+ }
+ currentKeys, _ := json.Marshal(currentNotebookCrypto())
+ if !bytes.Equal(currentKeys, keyState) || IsBoxUnlocked(boxID) {
+ t.Fatal("rejected recovery changed keys or published a DEK")
+ }
+ if _, err = os.Stat(masterPasswordMigrationPath()); !os.IsNotExist(err) {
+ t.Fatalf("rejected password change wrote a migration: %v", err)
+ }
+}
+
+func TestDocumentAddressingEncryptedArchiveImportPreflight(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ password := "addressing-archive-password"
+ if err := EnableEncryptedNotebook(password); err != nil {
+ t.Fatal(err)
+ }
+ kek, err := deriveKEK(password)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(kek)
+ boxID := "20261022120000-crypto2"
+ _ = notebookArchiveTestBox(t, boxID, kek)
+ archiveID, _, err := PrepareNotebookArchive([]string{boxID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ legacyArchive := filepath.Join(directory, "archive.zip")
+ futureDirectory := t.TempDir()
+ manifest, err := readNotebookArchive(legacyArchive, filepath.Join(futureDirectory, "payload"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ setDocumentAddressingTestMode(t, filepath.Join(futureDirectory, "payload", "data", boxID), 2)
+ if err = writeNotebookArchive(futureDirectory, manifest); err != nil {
+ t.Fatal(err)
+ }
+ futureArchive := filepath.Join(futureDirectory, "archive.zip")
+ for _, test := range []struct {
+ name, archive string
+ remembered bool
+ }{
+ {"incoming-mode", futureArchive, false},
+ {"remembered-source-identity", legacyArchive, true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if test.remembered {
+ backup := []byte(`{"documentAddressing":{"version":1,"notebooks":{"` + boxID + `":2}}}`)
+ if err := documentaddressing.RestoreBackup(util.ConfDir, backup); err != nil {
+ t.Fatal(err)
+ }
+ }
+ original, _ := os.ReadFile(test.archive)
+ if err := ImportNotebookArchive(test.archive, "wrong-password", nil); !errors.Is(err, ErrNotebookArchiveAuthentication) {
+ t.Fatalf("mode check bypassed authentication: %v", err)
+ }
+ if err := ImportNotebookArchive(test.archive, password, nil); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ t.Fatalf("archive restored unsupported notebook: %v", err)
+ }
+ entries, _ := os.ReadDir(util.DataDir)
+ if len(entries) != 0 || currentNotebookCrypto().Enabled {
+ t.Fatal("rejected archive partially installed data or keys")
+ }
+ current, _ := os.ReadFile(test.archive)
+ if !bytes.Equal(current, original) {
+ t.Fatal("rejected archive changed its source")
+ }
+ })
+ }
+}
diff --git a/kernel/model/document_addressing_file.go b/kernel/model/document_addressing_file.go
new file mode 100644
index 0000000000..9985e66086
--- /dev/null
+++ b/kernel/model/document_addressing_file.go
@@ -0,0 +1,209 @@
+package model
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// CheckDocumentAddressingPath 在原始文件访问和修复前检查所属笔记本,也检查父目录覆盖的笔记本。
+func CheckDocumentAddressingPath(absPath string) error {
+ paths, err := documentAddressingDataPaths(absPath)
+ if err != nil {
+ return err
+ }
+ checked := map[string]bool{}
+ for _, name := range paths {
+ boxID, _, _ := strings.Cut(name, "/")
+ boxID = strings.ToLower(boxID)
+ if name == "" {
+ entries, readErr := os.ReadDir(util.DataDir)
+ if errors.Is(readErr, os.ErrNotExist) {
+ continue
+ }
+ if readErr != nil {
+ return readErr
+ }
+ for _, entry := range entries {
+ if entry.IsDir() && ast.IsNodeIDPattern(entry.Name()) && !checked[entry.Name()] {
+ if err = filesys.CheckDocumentAddressing(entry.Name()); err != nil {
+ return err
+ }
+ checked[entry.Name()] = true
+ }
+ }
+ } else if ast.IsNodeIDPattern(boxID) && !checked[boxID] {
+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {
+ return err
+ }
+ checked[boxID] = true
+ }
+ }
+ return nil
+}
+
+// documentAddressingDataPaths 同时保留逻辑路径和符号链接目标,尚不存在的尾部也参与检查。
+func documentAddressingDataPaths(absPath string) ([]string, error) {
+ if !filepath.IsAbs(util.DataDir) {
+ return nil, nil
+ }
+ resolved, err := ResolveAssetPathWithMissingLeaf(absPath)
+ if err != nil {
+ return nil, err
+ }
+ root, err := ResolveAssetPathWithMissingLeaf(util.DataDir)
+ if err != nil {
+ return nil, err
+ }
+ var ret []string
+ for _, pair := range [][2]string{{util.DataDir, absPath}, {root, resolved}} {
+ base, name := filepath.Clean(pair[0]), filepath.Clean(pair[1])
+ if rel, inside := dataRelativePath(base, name); inside {
+ rel = strings.TrimPrefix(rel, "/")
+ id, _, _ := strings.Cut(rel, "/")
+ if rel == "" || ast.IsNodeIDPattern(strings.ToLower(id)) {
+ ret = append(ret, rel)
+ }
+ } else if _, ancestor := dataRelativePath(name, base); ancestor {
+ ret = append(ret, "")
+ }
+ }
+ return ret, nil
+}
+
+// 本机能力下界只能通过专用合并写入,原始文件接口不能覆盖、移动或删除它及其父目录。
+func checkDocumentAddressingLocalFile(absPath string, ancestors bool) error {
+ confDir := util.ConfDir
+ if confDir == "" && filepath.IsAbs(util.DataDir) {
+ confDir = filepath.Join(filepath.Dir(util.DataDir), "conf")
+ }
+ if !filepath.IsAbs(confDir) {
+ return nil
+ }
+ record := util.NormalizeAndResolve(util.ResolveLongestExistingParent(filepath.Join(confDir, "document-addressing.json")))
+ name := util.NormalizeAndResolve(util.ResolveLongestExistingParent(absPath))
+ if _, inside := dataRelativePath(record, name); inside {
+ return documentaddressing.ErrInvalid
+ }
+ if _, ancestor := dataRelativePath(name, record); ancestors && ancestor {
+ return documentaddressing.ErrInvalid
+ }
+ return nil
+}
+
+// CheckDocumentAddressingFileWrite 在创建目录、覆盖配置或调整时间之前检查待写内容。
+func CheckDocumentAddressingFileWrite(absPath string, data []byte, directory bool) error {
+ if err := checkDocumentAddressingLocalFile(absPath, false); err != nil {
+ return err
+ }
+ if err := CheckDocumentAddressingPath(absPath); err != nil {
+ return err
+ }
+ if directory {
+ return nil
+ }
+ paths, err := documentAddressingDataPaths(absPath)
+ if err != nil || len(paths) == 0 {
+ return err
+ }
+ return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,
+ func(string) ([]byte, error) { return data, nil })
+}
+
+// CheckDocumentAddressingFileCopies 预检全部目标内容,拒绝不兼容批次时不复制任何文件。
+// sources 与 destinations 一一对应;目录内的文件使用复制后的相对位置检查。
+func CheckDocumentAddressingFileCopies(sources, destinations []string) error {
+ if len(sources) != len(destinations) {
+ return documentaddressing.ErrInvalid
+ }
+ upserts := map[string]string{}
+ for i, source := range sources {
+ if err := CheckDocumentAddressingPath(source); err != nil {
+ return err
+ }
+ if err := CheckDocumentAddressingPath(destinations[i]); err != nil {
+ return err
+ }
+ // 复制工具遍历根目录链接,但忽略目录中的链接文件,预检保持相同范围。
+ resolved, err := ResolveAssetPathWithMissingLeaf(source)
+ if err != nil {
+ return err
+ }
+ err = filepath.WalkDir(resolved, func(name string, entry os.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ if entry.Type()&os.ModeSymlink != 0 {
+ return nil
+ }
+ rel, relErr := filepath.Rel(resolved, name)
+ if relErr != nil {
+ return relErr
+ }
+ dest := filepath.Join(destinations[i], rel)
+ if err := checkDocumentAddressingLocalFile(dest, false); err != nil {
+ return err
+ }
+ if entry.IsDir() {
+ return CheckDocumentAddressingPath(dest)
+ }
+ paths, pathErr := documentAddressingDataPaths(dest)
+ if pathErr != nil {
+ return pathErr
+ }
+ for _, path := range paths {
+ if previous := upserts[path]; previous != "" && previous != name &&
+ (strings.HasSuffix(path, "/"+documentaddressing.ConfigPath) || strings.HasSuffix(path, "/"+documentaddressing.FloorPath)) {
+ return documentaddressing.ErrInvalid
+ }
+ upserts[path] = name
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ }
+ if len(upserts) == 0 {
+ return nil
+ }
+ var paths []string
+ for path := range upserts {
+ paths = append(paths, path)
+ }
+ return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,
+ func(name string) ([]byte, error) { return filelock.ReadFile(upserts[name]) })
+}
+
+// CheckDocumentAddressingFileRemoval 保留整本删除语义;部分删除不能抹去能力记录。
+func CheckDocumentAddressingFileRemoval(absPath string) error {
+ if err := checkDocumentAddressingLocalFile(absPath, true); err != nil {
+ return err
+ }
+ var removes []string
+ err := filepath.WalkDir(absPath, func(name string, entry os.DirEntry, err error) error {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil || entry.IsDir() {
+ return err
+ }
+ paths, err := documentAddressingDataPaths(name)
+ removes = append(removes, paths...)
+ return err
+ })
+ if err != nil || len(removes) == 0 {
+ if err != nil {
+ return err
+ }
+ return CheckDocumentAddressingPath(absPath)
+ }
+ return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, nil, removes, nil)
+}
diff --git a/kernel/model/document_addressing_file_test.go b/kernel/model/document_addressing_file_test.go
new file mode 100644
index 0000000000..e23411bbe9
--- /dev/null
+++ b/kernel/model/document_addressing_file_test.go
@@ -0,0 +1,98 @@
+package model
+
+import (
+ "bytes"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestDocumentAddressingSortRecoveryPreservesPendingWrite(t *testing.T) {
+ initial := []byte(`{"` + appendSortOldID + `":7}`)
+ confPath := prepareSortConfAppendTest(t, initial)
+ previousConfDir := util.ConfDir
+ util.ConfDir = filepath.Join(filepath.Dir(util.DataDir), "conf")
+ t.Cleanup(func() { util.ConfDir = previousConfDir })
+ record, err := newSortConfAppendRecord(initial, map[string]int{appendSortNewID: 8})
+ if err != nil {
+ t.Fatal(err)
+ }
+ recordPath := saveSortConfAppendTestRecord(t, confPath, record)
+ journal, _ := os.ReadFile(recordPath)
+ partial := append(bytes.Clone(initial[:record.Offset]), record.Suffix[:len(record.Suffix)/2]...)
+ if err = os.WriteFile(confPath, partial, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(filepath.Dir(confPath), "conf.json"), []byte(`{"documentAddressingVersion":2}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ for _, operation := range []func() error{
+ func() error { return recoverSortConfAppend(confPath) },
+ func() error { _, err := readSortConfMap(confPath); return err },
+ func() error { return writeSortConfMap(confPath, map[string]int{appendSortOldID: 99}) },
+ func() error { return appendSortConfMap(confPath, initial, map[string]int{appendSortNewID: 9}) },
+ func() error { _, err := recoverSortConfMap(confPath, partial); return err },
+ } {
+ if err = operation(); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ t.Fatalf("sort operation entered unsupported notebook: %v", err)
+ }
+ }
+ if err = recoverSortConfAppends(); err != nil {
+ t.Fatalf("unavailable notebook prevented startup: %v", err)
+ }
+ for name, expected := range map[string][]byte{confPath: partial, recordPath: journal} {
+ data, readErr := os.ReadFile(name)
+ if readErr != nil || !bytes.Equal(data, expected) {
+ t.Fatalf("sort recovery changed %s: %s, %v", name, data, readErr)
+ }
+ }
+}
+
+func TestDocumentAddressingRawPathAliases(t *testing.T) {
+ documentAddressingRawPathAliases(t, func(link, target string) {
+ if err := os.Symlink(target, link); err != nil {
+ t.Skipf("symbolic links unavailable: %v", err)
+ }
+ })
+}
+
+func documentAddressingRawPathAliases(t *testing.T, linkDirectory func(string, string)) {
+ t.Helper()
+ previousData, previousConf := util.DataDir, util.ConfDir
+ root := t.TempDir()
+ util.DataDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "conf")
+ t.Cleanup(func() { util.DataDir, util.ConfDir = previousData, previousConf })
+ boxID := "20261022120000-alias01"
+ box := filepath.Join(util.DataDir, boxID)
+ if err := os.MkdirAll(filepath.Join(box, ".siyuan"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(box, ".siyuan", "conf.json"), []byte(`{"documentAddressingVersion":2}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ alias := filepath.Join(root, "alias")
+ linkDirectory(alias, box)
+ if err := CheckDocumentAddressingFileWrite(filepath.Join(alias, "new", "child.sy"), []byte("raw"), false); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ t.Fatalf("linked destination bypassed protection: %v", err)
+ }
+ outside := t.TempDir()
+ linkDirectory(filepath.Join(box, "outside"), outside)
+ if err := CheckDocumentAddressingPath(filepath.Join(box, "outside", "new.sy")); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ t.Fatalf("logical notebook path bypassed protection: %v", err)
+ }
+ confAlias := filepath.Join(root, "conf-alias")
+ linkDirectory(confAlias, util.ConfDir)
+ if err := CheckDocumentAddressingFileWrite(filepath.Join(confAlias, "document-addressing.json"), []byte(`{}`), false); !errors.Is(err, documentaddressing.ErrInvalid) {
+ t.Fatalf("local capability alias bypassed protection: %v", err)
+ }
+ dataAlias := filepath.Join(root, "data-alias")
+ linkDirectory(dataAlias, util.DataDir)
+ util.DataDir = dataAlias
+ if err := CheckDocumentAddressingFileWrite(filepath.Join(box, "new.sy"), []byte("raw"), false); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ t.Fatalf("physical path of linked data directory bypassed protection: %v", err)
+ }
+}
diff --git a/kernel/model/document_addressing_file_windows_test.go b/kernel/model/document_addressing_file_windows_test.go
new file mode 100644
index 0000000000..b54b442b9e
--- /dev/null
+++ b/kernel/model/document_addressing_file_windows_test.go
@@ -0,0 +1,13 @@
+package model
+
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/internal/testutil"
+)
+
+func TestDocumentAddressingRawPathJunctions(t *testing.T) {
+ documentAddressingRawPathAliases(t, func(link, target string) {
+ testutil.Junction(t, link, target)
+ })
+}
diff --git a/kernel/model/notebook_archive.go b/kernel/model/notebook_archive.go
index 6f558a101e..000cf13aae 100644
--- a/kernel/model/notebook_archive.go
+++ b/kernel/model/notebook_archive.go
@@ -18,6 +18,7 @@ import (
"github.com/siyuan-note/dejavu/entity"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -249,6 +250,10 @@ func holdNotebookArchiveBoxes(ids []string) (func(), error) {
}
}
for _, id := range ids {
+ if err := filesys.CheckDocumentAddressing(id); err != nil {
+ release()
+ return nil, err
+ }
if _, busy := boxLock.LoadOrStore(id, true); busy {
release()
return nil, ErrNotebookArchiveBusy
diff --git a/kernel/model/notebook_archive_import.go b/kernel/model/notebook_archive_import.go
index f03f983d1d..0e87ae7a4c 100644
--- a/kernel/model/notebook_archive_import.go
+++ b/kernel/model/notebook_archive_import.go
@@ -16,6 +16,7 @@ import (
"github.com/88250/lute/ast"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -89,6 +90,11 @@ func ImportNotebookArchive(archivePath, password string, keyData []byte) error {
return err
}
defer zeroAndClear(kek)
+ for _, root := range notebookArchiveBoxRoots(manifest) {
+ if err = documentaddressing.CheckImport(util.DataDir, util.ConfDir, path.Base(root), filepath.Join(payload, filepath.FromSlash(root))); err != nil {
+ return err
+ }
+ }
install := filepath.Join(directory, "install")
roots, err := stageNotebookArchiveImport(payload, install, manifest)
if err != nil {
diff --git a/kernel/model/sort_conf.go b/kernel/model/sort_conf.go
index 35d7a2db91..0346a1ab2f 100644
--- a/kernel/model/sort_conf.go
+++ b/kernel/model/sort_conf.go
@@ -18,6 +18,9 @@ var sortConfRecoveryLock sync.Mutex
// recoverSortConfMap 先保存损坏原文,再从同路径快照或可用整数条目恢复排序。
func recoverSortConfMap(confPath string, data []byte) (map[string]int, error) {
+ if err := CheckDocumentAddressingPath(confPath); err != nil {
+ return nil, err
+ }
relPath, ok := dataRelativePath(util.DataDir, confPath)
if !ok {
return nil, fmt.Errorf("sort conf outside data directory [%s]", confPath)
diff --git a/kernel/model/sort_conf_append.go b/kernel/model/sort_conf_append.go
index 5c12d8ec53..f0c4047f54 100644
--- a/kernel/model/sort_conf_append.go
+++ b/kernel/model/sort_conf_append.go
@@ -15,6 +15,7 @@ import (
"github.com/88250/lute/ast"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -242,6 +243,9 @@ func removeSortConfAppendRecord(recordPath string) error {
}
func recoverSortConfAppend(confPath string) (err error) {
+ if err = CheckDocumentAddressingPath(confPath); err != nil {
+ return
+ }
recordPath, pathErr := sortConfAppendPath(confPath)
if pathErr != nil {
return nil
@@ -306,6 +310,10 @@ func recoverSortConfAppends() error {
return fmt.Errorf("invalid sort recovery notebook [%s]", boxID)
}
if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {
+ if errors.Is(err, documentaddressing.ErrUnsupported) || errors.Is(err, documentaddressing.ErrInvalid) {
+ logging.LogWarnf("keep sort recovery for unavailable notebook [%s]: %s", boxID, err)
+ continue
+ }
return err
}
}