Skip to content

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

:bug: Reject raw slash titles with insufficient document specs https://github.com/siyuan-note/siyuan/issues/20843

Danieleb392cc0d529
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index ab253c9fb9..65b056ddfc 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -5280,6 +5280,7 @@ export interface APIPOSTRoutes {
/**
* 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。
* 目标为文档 ID 路径时,未知格式和标题冲突均返回 -1;实际写入在文件锁内重新校验现有源,不规范化内容。
+ * 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有源的读取和恢复不受此写入检查影响。
* 工作空间外的加密资源解密导出仍要求既有授权和操作租约。
*/
"/api/file/copyFile": {
@@ -5306,6 +5307,7 @@ export interface APIPOSTRoutes {
};
/**
* 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+ * 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
* 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
* 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
*/
@@ -5319,6 +5321,7 @@ export interface APIPOSTRoutes {
/**
* 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。
* 文档 ID 路径检查传入内容及现有源的格式和标题;未知格式或标题冲突返回 -1,原文件和时间保持不变。
+ * 新传入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有低 Spec 源仍可读取并由合法内容替换。
* 实际文档写入在同一文件锁内重新校验现有源,保留请求字节;附件和插件文件不按文档格式解释。
* 不允许覆盖本机 conf/document-addressing.json,恢复设置时须使用 importConf 的逐身份合并流程。
*/
@@ -5350,6 +5353,7 @@ export interface APIPOSTRoutes {
/**
* 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。
* 移入由笔记本及文档 ID 组成的 .sy 路径时检查全部源文档;未知格式或标题冲突返回 -1,保留来源。
+ * 新移入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
* 不能借重命名覆盖、移动或删除本机 conf/document-addressing.json;既有加密边界不变。
*/
"/api/file/renameFile": {
@@ -5361,6 +5365,7 @@ export interface APIPOSTRoutes {
};
/**
* 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+ * 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
* 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
* 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
*/
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 9b30df5147..cb1b836885 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -1491,6 +1491,8 @@ if (response.code === 0 && response.data) {
ノートブック ID とドキュメント ID で構成される `.sy` ドキュメントパスへの書き込みでは、入力内容と既存のドキュメントを検証します。未知の形式、不正なドキュメントデータ、互換モードと競合するタイトルは `code: -1` を返し、元のファイルと更新日時を保持します。成功時はタイトルを正規化せず、要求されたバイト列をそのまま保存します。アセットやプラグインのディレクトリ内にある `.sy` ファイルはドキュメントとして解析しません。
+新しく書き込むタイトルに ASCII `/` が含まれる場合、`Spec` は `6` 以上である必要があります。満たさない場合は `code: -1`、`msg: "document title requires spec 6"` を返し、入力内容を自動変更しません。既存の低い Spec のデータは引き続き読み取り可能で、正しいバージョンを指定した内容で置き換えられます。
+
* パラメータはHTTP Multipartフォーム
* `path`: ワークスペースパス配下のファイルパス
@@ -1538,6 +1540,8 @@ if (response.code === 0 && response.data) {
移動先にノートブック ID とドキュメント ID で構成される `.sy` ドキュメントパスが含まれる場合、対象となるすべての入力ドキュメントも検証します。未知の形式、不正なドキュメントデータ、タイトルの競合は `code: -1` を返し、移動先ディレクトリを作成せず、移動元も変更しません。
+移動するタイトルに ASCII `/` が含まれる場合、`Spec` は `6` 以上である必要があります。満たさない場合は `code: -1`、`msg: "document title requires spec 6"` を返し、移動元と移動先を保持します。
+
* パラメータ
```json
diff --git a/docs/API.md b/docs/API.md
index 37644fb1d1..41dd93b76d 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1499,6 +1499,8 @@ Unsupported notebook addressing modes return `code: -1` before creating director
For `.sy` document paths composed of notebook and document IDs, both the incoming content and any existing document are checked. Unknown formats, invalid document sources, or titles conflicting with compatibility mode return `code: -1`, preserving the original file and modification time. Successful writes retain the request bytes without normalizing titles. Files ending in `.sy` inside asset or plugin directories are not parsed as documents.
+An incoming title containing ASCII `/` must declare `Spec` at least `6`; otherwise the endpoint returns `code: -1` and `msg: "document title requires spec 6"` without rewriting the input. Existing lower-spec sources remain readable and can be replaced with valid versioned content.
+
* The parameter is an HTTP Multipart form
* `path`: the file path under the workspace path
@@ -1546,6 +1548,8 @@ The complete move is checked for notebook addressing compatibility before creati
When the destination includes `.sy` document paths composed of notebook and document IDs, all incoming documents are also checked. Unknown formats, invalid document sources, or conflicting titles return `code: -1` without creating the destination directory or moving the sources.
+Incoming titles containing ASCII `/` must declare `Spec` at least `6`; otherwise the endpoint returns `code: -1` and `msg: "document title requires spec 6"`, preserving the sources and destination.
+
* Parameters
```json
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index 30d52c0779..ac73da9ee6 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -1497,6 +1497,8 @@ if (response.code === 0 && response.data) {
写入由笔记本及文档 ID 组成的 `.sy` 文档路径时,同时检查传入内容和已有文档。未知格式、损坏的文档源或标题与兼容模式冲突时返回 `code: -1`,保留原文件及修改时间;成功写入保留请求中的原始字节,不规范化标题。附件或插件目录中的 `.sy` 文件不作为文档解析。
+新传入的标题含 ASCII `/` 时,必须声明 `Spec` 至少为 `6`,否则返回 `code: -1`、`msg: "document title requires spec 6"`,不自动改写内容。已有低 Spec 源仍可读取,也可以由版本标记合法的内容替换。
+
* 参数为 HTTP Multipart 表单
* `path`:工作空间路径下的文件路径
@@ -1544,6 +1546,8 @@ if (response.code === 0 && response.data) {
目标包含由笔记本及文档 ID 组成的 `.sy` 文档路径时,也会预检全部传入文档;未知格式、损坏的文档源或标题冲突返回 `code: -1`,不创建目标目录,也不移动来源。
+新移入的标题含 ASCII `/` 时,必须声明 `Spec` 至少为 `6`,否则返回 `code: -1`、`msg: "document title requires spec 6"`,保留来源和目标。
+
* 参数
```json
diff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.md
index 1f5843e0e6..bbba661b6a 100644
--- a/docs/DOCUMENT-ADDRESSING.md
+++ b/docs/DOCUMENT-ADDRESSING.md
@@ -389,6 +389,8 @@ Tree writes validate both the replacement and the current on-disk source. Authen
Raw file endpoints apply the same source-format checks to paths composed of notebook and document IDs; uploads, copies, and moves into those paths cannot bypass them. Validate the complete batch before creating destination directories or copying any files. Actual document copies use the validated source bytes and recheck the current destination under the file lock. Concurrent changes or I/O failures after preflight can leave completed copies; batch rollback is not promised. Files ending in `.sy` inside ordinary asset and plugin directories retain raw-file semantics, and encrypted notebooks remain inaccessible through raw file endpoints.
+For incoming raw document writes, copies, and renames, a decoded root title containing ASCII `/` requires `Spec >= 6`. Under-versioned input returns `document title requires spec 6` before any destination write; raw endpoints never upgrade or reserialize request bytes. This is a write-only consistency check: existing supported low-spec sources retain authenticated reads, history, backups, sync and recovery, and valid replacements may repair their version marker. Ordinary tree writes continue upgrading the specification as needed.
+
Mixing older clients with upgraded data can produce inconsistent behavior rather than a reliable refusal to open: some Spec `6` documents may be rejected while documents retaining an older specification remain readable or writable. An older editing snapshot may overwrite newer source data; old title normalization or path parsing may remove a literal `/` or treat it as hierarchy. Synchronization may then propagate those incorrect changes to upgraded devices. This can cause lost edits or incorrect titles and paths, requiring recovery from history or backups. These are reasons to stop using older clients against the same data, not a promise that every older operation will fail safely.
An isolated probe of the published `v3.8.9-alpha.4` source verified rejection of direct Spec `6` reads, continued reads of legacy-specification documents in mode `2`, and a stale editing snapshot overwriting source data. It did not establish the behavior of every old-version operation or a complete mixed-device sync scenario; the additional normalization, hierarchy, and propagation consequences above are risks, not reported results of that probe. Local mode `1` overlay builds are limited-reader regressions of the current source, not candidates for a planned transitional release, and they do not verify an actual release package. Preserve checks and regression coverage for ordinary and encrypted legacy data, unsupported modes and formats, stale writes, sync, and recovery. Keep `minimumReaderVersion` nullable until an actual feature release has been verified; neither a separate protective release nor assignment of that field is required to close this issue.
diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.md
index 115cf1c130..5700382eaa 100644
--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md
+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md
@@ -389,6 +389,8 @@
原始文件接口中的笔记本及文档 ID 路径同样受源格式检查保护,不能通过上传、复制或移入文件绕过。整批预检在创建目标目录及首次复制前完成,实际文档复制使用已经校验的读取字节,并在文件锁内重新检查目标源;检查后的并发变化或 I/O 失败仍可能留下已完成的复制,不承诺整批回滚。普通附件和插件目录下的 `.sy` 文件保持原始文件语义,加密笔记本仍禁止通过原始文件接口读写。
+新传入的原始文档写入、复制和重命名,在解码后的根标题含 ASCII `/` 时要求 `Spec >= 6`。低版本输入在任何目标写入前返回 `document title requires spec 6`;原始文件接口不自动升级或重新序列化请求字节。此项一致性检查仅约束新写入:已有受支持的低 Spec 源保留认证读取、历史、备份、同步和恢复能力,并允许用合法内容替换以修复版本标记。普通树写入继续按需升级版本。
+
兼容判定依据为文档 Spec 和笔记本有效模式,两者均须在相关读写、同步与恢复入口执行;不混用旧版不构成删除这些检查的理由。已发布且忽略模式标记或缺少写入前检查的旧客户端,无法被新增字段追溯约束,系统也无法证明离线设备已经升级。发布说明及用户指南必须明确全设备统一升级和混用可能损坏数据的后果,不承诺旧版一定被安全拦截。`minimumReaderVersion` 如需登记,须以实际功能发行包的读写与兼容测试为依据;暂为 `null` 不表示支持旧客户端,也不再以过渡保护版本发布或登记其版本号作为本议题关闭条件。
已发布 `v3.8.9-alpha.4` 源码的隔离验证表明:它拒绝直接读取 Spec 6 文档,但仍能读取模式 `2` 中保留旧规格的文档,并将旧编辑快照写回。这些已验证行为说明不能概括为“旧版本一定无法打开”;标题清理、层级误解及错误同步传播是混用风险,不能将其写成该探针已逐项验证的结果。本地临时模式 `1` 构建及回归用于验证能力受限读取器的拒绝行为,不代表一个已发布或必须发布的过渡版本。功能版本仍需遵守常规发行包核对与发布验证,维护者负责发布。
diff --git a/kernel/api/contract_document_addressing_test.go b/kernel/api/contract_document_addressing_test.go
index 72c14f873a..eef4733cb7 100644
--- a/kernel/api/contract_document_addressing_test.go
+++ b/kernel/api/contract_document_addressing_test.go
@@ -66,7 +66,17 @@ func addressingAPIRequest(t *testing.T, route string, handler gin.HandlerFunc, p
return response.Code
}
+type addressingAPIPutResponse struct {
+ Code int
+ Msg string
+}
+
func addressingAPIPut(t *testing.T, name, value string, directory bool) int {
+ t.Helper()
+ return addressingAPIPutResult(t, name, value, directory).Code
+}
+
+func addressingAPIPutResult(t *testing.T, name, value string, directory bool) addressingAPIPutResponse {
t.Helper()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
@@ -87,11 +97,74 @@ func addressingAPIPut(t *testing.T, name, value string, directory bool) int {
c.Request.Header.Set("Content-Type", writer.FormDataContentType())
putFile(c)
requireAPIContract(t, "POST", "/api/file/putFile", recorder)
- var response struct{ Code int }
+ var response addressingAPIPutResponse
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
- return response.Code
+ return response
+}
+
+func TestAPIContractDocumentAddressingRawTitleSpec(t *testing.T) {
+ addressingAPIWorkspace(t)
+ addressingAPIWrite(t, filepath.Join(util.DataDir, addressingAPIBox, documentaddressing.ConfigPath), `{"documentAddressingVersion":2}`)
+ const document = "20261022130000-rawdoc1.sy"
+ name := "data/" + addressingAPIBox + "/" + document
+ abs := filepath.Join(util.WorkspaceDir, name)
+ ordinary := `{"Spec":"2","Properties":{"title":"Ordinary"}}`
+ underVersioned := `{"Spec":"2","Properties":{"title":"A/B"}}`
+ valid := "\xef\xbb\xbf" + "{\n \"Spec\":\"6\",\"Properties\":{\"title\":\"A/B\"}\n}\n"
+ addressingAPIWrite(t, abs, ordinary)
+ before, _ := os.Stat(abs)
+ result := addressingAPIPutResult(t, name, underVersioned, false)
+ if result.Code != -1 || result.Msg != "document title requires spec 6" {
+ t.Fatalf("put did not expose the title spec requirement: %+v", result)
+ }
+ after, _ := os.Stat(abs)
+ if data, _ := os.ReadFile(abs); string(data) != ordinary || !before.ModTime().Equal(after.ModTime()) {
+ t.Fatal("rejected title changed the destination")
+ }
+ source := filepath.Join(util.DataDir, "assets", document)
+ addressingAPIWrite(t, source, underVersioned)
+ first := filepath.Join(util.DataDir, "assets", "first.txt")
+ addressingAPIWrite(t, first, "attachment")
+ renamed := "data/" + addressingAPIBox + "/20261022130000-parent1/" + document
+ for _, request := range []struct {
+ name string
+ handler gin.HandlerFunc
+ body interface{}
+ }{
+ {"copyFile", copyFile, apicontract.CopyFileRequest{Src: "assets/" + document, Dest: abs}},
+ {"renameFile", renameFile, apicontract.RenameFileRequest{Path: "data/assets/" + document, NewPath: renamed}},
+ {"globalCopyFiles", globalCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{first, source}, DestDir: "data/" + addressingAPIBox}},
+ {"workspaceCopyFiles", workspaceCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{"data/assets/first.txt", "data/assets/" + document}, DestDir: "data/" + addressingAPIBox}},
+ } {
+ if code := addressingAPIRequest(t, request.name, request.handler, request.body); code != -1 {
+ t.Fatalf("%s accepted a low-spec slash title: %d", request.name, code)
+ }
+ }
+ if data, _ := os.ReadFile(source); string(data) != underVersioned {
+ t.Fatal("rejected rename changed the original source")
+ }
+ for _, path := range []string{filepath.Join(util.DataDir, addressingAPIBox, "first.txt"), filepath.Dir(filepath.Join(util.WorkspaceDir, renamed))} {
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatal("rejected batch created destination entries", path, err)
+ }
+ }
+ // 已有低 Spec 源仍可读取,合法替换可以修复版本,原始字节不被重新序列化。
+ addressingAPIWrite(t, abs, underVersioned)
+ if code := addressingAPIPut(t, name, valid, false); code != 0 {
+ t.Fatalf("valid replacement could not repair an existing source: %d", code)
+ }
+ if data, _ := os.ReadFile(abs); string(data) != valid {
+ t.Fatal("valid title write changed request bytes")
+ }
+ addressingAPIWrite(t, source, valid)
+ if code := addressingAPIRequest(t, "copyFile", copyFile, apicontract.CopyFileRequest{Src: "assets/" + document, Dest: abs}); code != 0 {
+ t.Fatalf("valid title copy failed: %d", code)
+ }
+ if data, _ := os.ReadFile(abs); string(data) != valid {
+ t.Fatal("valid title copy changed source bytes")
+ }
}
func TestAPIContractDocumentAddressingRawWrites(t *testing.T) {
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 64383b9bfd..bcac00d2aa 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -632,6 +632,7 @@ var ReadDirectory = define[ReadDirectoryRequest, []DirectoryEntry]("readDir", "/
// RenameFile 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。
// 移入由笔记本及文档 ID 组成的 .sy 路径时检查全部源文档;未知格式或标题冲突返回 -1,保留来源。
+// 新移入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
// 不能借重命名覆盖、移动或删除本机 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")
@@ -640,22 +641,26 @@ var RenameFile = define[RenameFileRequest, Null]("renameFile", "/api/file/rename
var RemoveFile = define[RemoveFileRequest, Null]("removeFile", "/api/file/removeFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 500}}, "POST")
// GlobalCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+// 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
// 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
var GlobalCopyFiles = define[CopyFilesRequest, Null]("globalCopyFiles", "/api/file/globalCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")
// WorkspaceCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+// 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
// 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
var WorkspaceCopyFiles = define[CopyFilesRequest, Null]("workspaceCopyFiles", "/api/file/workspaceCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")
// CopyFile 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。
// 目标为文档 ID 路径时,未知格式和标题冲突均返回 -1;实际写入在文件锁内重新校验现有源,不规范化内容。
+// 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有源的读取和恢复不受此写入检查影响。
// 工作空间外的加密资源解密导出仍要求既有授权和操作租约。
var CopyFile = define[CopyFileRequest, Null]("copyFile", "/api/file/copyFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2}}, "POST")
// PutFile 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。
// 文档 ID 路径检查传入内容及现有源的格式和标题;未知格式或标题冲突返回 -1,原文件和时间保持不变。
+// 新传入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有低 Spec 源仍可读取并由合法内容替换。
// 实际文档写入在同一文件锁内重新校验现有源,保留请求字节;附件和插件文件不按文档格式解释。
// 不允许覆盖本机 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")
diff --git a/kernel/model/document_addressing_source.go b/kernel/model/document_addressing_source.go
index 0a9385e7fe..f93b44b58e 100644
--- a/kernel/model/document_addressing_source.go
+++ b/kernel/model/document_addressing_source.go
@@ -1,6 +1,7 @@
package model
import (
+ "bytes"
"errors"
"io/fs"
"os"
@@ -55,6 +56,15 @@ func checkDocumentAddressingSourceOverwrite(absPath string, data []byte) error {
if err := checkDocumentAddressingSource(absPath, data); err != nil {
return err
}
+ paths, err := documentAddressingDataPaths(absPath)
+ if err != nil {
+ return err
+ }
+ if isDocumentAddressingSource(paths) {
+ if err = treenode.CheckDocumentTitleWriteSpecJSON(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))); err != nil {
+ return err
+ }
+ }
current, err := filelock.ReadFile(absPath)
if errors.Is(err, os.ErrNotExist) {
return nil
diff --git a/kernel/model/document_addressing_source_test.go b/kernel/model/document_addressing_source_test.go
index 4dc0f9e41f..5b720240cc 100644
--- a/kernel/model/document_addressing_source_test.go
+++ b/kernel/model/document_addressing_source_test.go
@@ -87,6 +87,55 @@ func TestDocumentAddressingRawSourceChanges(t *testing.T) {
}
}
+func TestDocumentAddressingRawTitleWriteSpec(t *testing.T) {
+ box := documentAddressingSourceWorkspace(t)
+ writeDocumentAddressingSource(t, filepath.Join(box, documentaddressing.ConfigPath), []byte(`{"documentAddressingVersion":2}`))
+ destination := filepath.Join(box, "20261022130000-target1.sy")
+ underVersioned := []byte(`{"Spec":"2","Properties":{"title":"A/B"}}`)
+ valid := []byte("\xef\xbb\xbf" + "{\n \"Spec\": \"6\", \"Properties\": {\"title\": \"A/B\"}\n}\n")
+ writeDocumentAddressingSource(t, destination, underVersioned)
+ if err := checkDocumentAddressingSource(destination, underVersioned); err != nil {
+ t.Fatal("existing source can no longer be read or recovered", err)
+ }
+ before, _ := os.Stat(destination)
+ if err := WriteFileWithDocumentAddressing(destination, underVersioned); !errors.Is(err, treenode.ErrDocumentTitleSpec) {
+ t.Fatal("under-versioned raw write was accepted", err)
+ }
+ after, _ := os.Stat(destination)
+ if data, _ := os.ReadFile(destination); !bytes.Equal(data, underVersioned) || !before.ModTime().Equal(after.ModTime()) {
+ t.Fatal("rejected write changed existing source bytes or timestamp")
+ }
+ missing := filepath.Join(box, "20261022130000-parent1", "20261022130000-child01.sy")
+ if err := CheckDocumentAddressingFileWrite(missing, underVersioned, false); !errors.Is(err, treenode.ErrDocumentTitleSpec) {
+ t.Fatal("new document did not require title spec", err)
+ }
+ if _, err := os.Stat(filepath.Dir(missing)); !os.IsNotExist(err) {
+ t.Fatal("preflight created a directory", err)
+ }
+ if err := WriteFileWithDocumentAddressing(destination, valid); err != nil {
+ t.Fatal("a valid raw replacement could not repair an existing low-spec source", err)
+ }
+ if data, _ := os.ReadFile(destination); !bytes.Equal(data, valid) {
+ t.Fatal("valid raw write changed request bytes")
+ }
+ source := filepath.Join(t.TempDir(), "incoming")
+ writeDocumentAddressingSource(t, filepath.Join(source, "000-first.txt"), []byte("attachment"))
+ writeDocumentAddressingSource(t, filepath.Join(source, "20261022130000-other01.sy"), underVersioned)
+ if err := CopyFileWithDocumentAddressing(source, box); !errors.Is(err, treenode.ErrDocumentTitleSpec) {
+ t.Fatal("directory copy accepted an under-versioned descendant", err)
+ }
+ if _, err := os.Stat(filepath.Join(box, "000-first.txt")); !os.IsNotExist(err) {
+ t.Fatal("directory copy wrote an earlier attachment before rejecting", err)
+ }
+ writeDocumentAddressingSource(t, filepath.Join(source, "20261022130000-other01.sy"), valid)
+ if err := CopyFileWithDocumentAddressing(source, box); err != nil {
+ t.Fatal("valid versioned copy was rejected", err)
+ }
+ if data, _ := os.ReadFile(filepath.Join(box, "20261022130000-other01.sy")); !bytes.Equal(data, valid) {
+ t.Fatal("valid copy changed source bytes")
+ }
+}
+
func TestDocumentAddressingRawSourceDirectoryCopy(t *testing.T) {
box := documentAddressingSourceWorkspace(t)
source := t.TempDir()
diff --git a/kernel/treenode/document_source.go b/kernel/treenode/document_source.go
index f27886d6fd..18d600ae1d 100644
--- a/kernel/treenode/document_source.go
+++ b/kernel/treenode/document_source.go
@@ -4,12 +4,50 @@ import (
"bytes"
"encoding/json"
"errors"
+ "strconv"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
"github.com/siyuan-note/siyuan/kernel/documentaddressing"
)
+var ErrDocumentTitleSpec = errors.New("document title requires spec " + DocumentTitleSpec)
+
+func documentTitleSpecUpgradeRequired(spec string) bool {
+ version, err := strconv.Atoi(spec)
+ required, _ := strconv.Atoi(DocumentTitleSpec)
+ return spec == "" || err == nil && version < required
+}
+
+// CheckDocumentTitleWriteSpecJSON 仅用于已通过源格式检查的原始文件写入,不收紧既有源的读取及恢复。
+// 不改写请求字节;含斜杠标题必须声明足够的 Spec,重复属性不能遮盖版本要求。
+func CheckDocumentTitleWriteSpecJSON(data []byte) error {
+ var root struct {
+ Spec string
+ Properties documentTitleSpecProperties
+ }
+ if err := json.Unmarshal(data, &root); err != nil {
+ return err
+ }
+ if root.Properties.requiresStructured && documentTitleSpecUpgradeRequired(root.Spec) {
+ return ErrDocumentTitleSpec
+ }
+ return nil
+}
+
+type documentTitleSpecProperties struct {
+ requiresStructured bool
+}
+
+func (properties *documentTitleSpecProperties) UnmarshalJSON(data []byte) error {
+ err := documentaddressing.CheckTitleProperties(data, 1)
+ if errors.Is(err, documentaddressing.ErrModeConflict) {
+ properties.requiresStructured = true
+ return nil
+ }
+ return err
+}
+
// checkDocumentSourceJSON 保留重复字段中遇到的兼容错误,在容错解析前确定标题和源版本能否处理。
func checkDocumentSourceJSON(data []byte, mode int) (string, error) {
if !bytes.HasPrefix(bytes.TrimSpace(data), []byte("{")) {
diff --git a/kernel/treenode/document_source_test.go b/kernel/treenode/document_source_test.go
index be548c5eae..f5f77567d1 100644
--- a/kernel/treenode/document_source_test.go
+++ b/kernel/treenode/document_source_test.go
@@ -71,3 +71,49 @@ func TestDocumentSourceVersionCannotBeShadowed(t *testing.T) {
}
}
}
+
+func TestDocumentTitleWriteSpec(t *testing.T) {
+ for _, source := range []string{
+ `{"Spec":"2","Properties":{"title":"A/B"}}`,
+ `{"Spec":"5","Properties":{"title":"A\u002fB"}}`,
+ `{"Properties":{"title":"A&#47;B"}}`,
+ `{"Spec":"2","Properties":{"title":"A&#x2F;B"}}`,
+ `{"Spec":"2","Properties":{"title":"A/B","title":"Ordinary"}}`,
+ `{"Spec":"2","Properties":{"title":"A/B"},"Properties":{"title":"Ordinary"}}`,
+ `{"Spec":"6","Spec":"2","Properties":{"title":"A/B"}}`,
+ } {
+ if err := CheckSpecJSONForMode([]byte(source), 2); err != nil {
+ t.Fatalf("existing low-spec source is no longer readable: %v", err)
+ }
+ if err := CheckDocumentTitleWriteSpecJSON([]byte(source)); !errors.Is(err, ErrDocumentTitleSpec) {
+ t.Fatalf("raw write accepted an under-versioned title: %s, %v", source, err)
+ }
+ }
+ for _, source := range []string{
+ `{"Spec":"6","Properties":{"title":"A/B"}}`,
+ `{"Spec":"6","Properties":{"title":"A&#47;B"}}`,
+ `{"Spec":"2","Spec":"6","Properties":{"title":"A/B"}}`,
+ `{"Spec":"2","Properties":{"title":"A%2FB A/B A&amp;#47;B"}}`,
+ `{"Spec":"2","Properties":{"title":"Ordinary"},"Children":[{"Properties":{"title":"A/B"}}]}`,
+ } {
+ if err := CheckDocumentTitleWriteSpecJSON([]byte(source)); err != nil {
+ t.Fatalf("compatible raw title was rejected: %s, %v", source, err)
+ }
+ }
+}
+
+func TestDocumentTitleSpecUpgrade(t *testing.T) {
+ for _, test := range []struct {
+ title string
+ want string
+ }{
+ {"A/B", DocumentTitleSpec}, {"A&#47;B", DocumentTitleSpec}, {"A&#x2F;B", DocumentTitleSpec},
+ {"A&amp;#47;B", BaseSpec}, {"A%2FB", BaseSpec}, {"A/B", BaseSpec},
+ } {
+ root := &ast.Node{Type: ast.NodeDocument, Spec: BaseSpec, KramdownIAL: [][]string{{"title", test.title}}}
+ UpgradeSpec(&parse.Tree{Root: root})
+ if root.Spec != test.want || root.KramdownIAL[0][1] != test.title {
+ t.Fatalf("title spec upgrade changed source semantics: %q, %q", root.Spec, root.KramdownIAL[0][1])
+ }
+ }
+}
diff --git a/kernel/treenode/tree.go b/kernel/treenode/tree.go
index 5b28989077..4a9d2d17d9 100644
--- a/kernel/treenode/tree.go
+++ b/kernel/treenode/tree.go
@@ -236,8 +236,8 @@ func UpgradeSpec(tree *parse.Tree) (upgraded bool) {
return ast.WalkContinue
})
}
- if version, err := strconv.Atoi(tree.Root.Spec); err == nil && version < 6 &&
- strings.Contains(tree.Root.IALAttr("title"), "/") {
+ if documentTitleSpecUpgradeRequired(tree.Root.Spec) &&
+ documentaddressing.CheckLegacyTitle(tree.Root.IALAttr("title")) != nil {
tree.Root.Spec = DocumentTitleSpec
}
return oldSpec != tree.Root.Spec