An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Make encrypted notebook SY archives portable
Danielb501a389305a
diff --git a/kernel/model/asset_reference.go b/kernel/model/asset_reference.gonew file mode 100644index 0000000000..77ffadca35--- /dev/null+++ b/kernel/model/asset_reference.go@@ -0,0 +1,270 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "bytes"+ stdhtml "html"+ "net/url"+ "path"+ "strings"++ "github.com/88250/gulu"+ "github.com/88250/lute/ast"+ lutehtml "github.com/88250/lute/html"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type assetReferenceRewriteOptions struct {+ pathMap map[string]string+ targetBoxID string+ bindTargetBox bool+ rewriteUnmapped bool+}++func canonicalAssetReferencePath(rawPath string) string {+ rawPath = strings.TrimSpace(stdhtml.UnescapeString(rawPath))+ if decoded, err := url.PathUnescape(rawPath); err == nil {+ rawPath = decoded+ }+ rawPath = strings.TrimPrefix(path.Clean(rawPath), "/")+ if rawPath == "." || !strings.HasPrefix(rawPath, "assets/") {+ return ""+ }+ return rawPath+}++func splitAssetReference(rawReference string) (rawPath, rawQuery, fragment string) {+ rawPath = strings.TrimSpace(rawReference)+ if index := strings.Index(rawPath, "#"); index >= 0 {+ fragment = rawPath[index:]+ rawPath = rawPath[:index]+ }+ if index := strings.Index(rawPath, "?"); index >= 0 {+ rawQuery = rawPath[index+1:]+ rawPath = rawPath[:index]+ }+ return+}++func lookupRewrittenAssetPath(sourcePath string, options assetReferenceRewriteOptions) (targetPath string, found bool) {+ if targetPath, found = options.pathMap[sourcePath]; found {+ return+ }++ // PDF 标注引用形如 assets/document.pdf/<annotationID>,资源映射只记录 PDF 文件本身。+ longestSourcePath := ""+ for candidateSourcePath, candidateTargetPath := range options.pathMap {+ if len(candidateSourcePath) <= len(longestSourcePath) ||+ !strings.HasPrefix(sourcePath, candidateSourcePath+"/") {+ continue+ }+ longestSourcePath = candidateSourcePath+ targetPath = candidateTargetPath + strings.TrimPrefix(sourcePath, candidateSourcePath)+ found = true+ }+ return+}++func rewriteAssetReference(rawReference string, options assetReferenceRewriteOptions) string {+ rawPath, rawQuery, fragment := splitAssetReference(rawReference)+ sourcePath := canonicalAssetReferencePath(rawPath)+ if sourcePath == "" {+ return rawReference+ }++ targetPath, found := lookupRewrittenAssetPath(sourcePath, options)+ if !found {+ if !options.rewriteUnmapped {+ return rawReference+ }+ targetPath = sourcePath+ }+ if targetPath == sourcePath {+ // 仅修改查询参数时保留原始路径编码。+ targetPath = rawPath+ }++ queryValues, err := url.ParseQuery(stdhtml.UnescapeString(rawQuery))+ if err != nil {+ return rawReference+ }+ if options.bindTargetBox {+ queryValues.Set("box", options.targetBoxID)+ } else {+ queryValues.Del("box")+ }++ ret := targetPath+ if encodedQuery := queryValues.Encode(); encodedQuery != "" {+ ret += "?" + encodedQuery+ }+ return ret + fragment+}++func rewriteHTMLAssetReferences(tokens []byte, options assetReferenceRewriteOptions) []byte {+ nodes, err := lutehtml.ParseFragment(bytes.NewReader(tokens), &lutehtml.Node{Type: lutehtml.ElementNode})+ if err != nil || len(nodes) == 0 {+ return tokens+ }++ updated := false+ var walk func(*lutehtml.Node)+ walk = func(node *lutehtml.Node) {+ for i := range node.Attr {+ rewritten := rewriteAssetReference(node.Attr[i].Val, options)+ if rewritten != node.Attr[i].Val {+ node.Attr[i].Val = rewritten+ updated = true+ }+ }+ for child := node.FirstChild; child != nil; child = child.NextSibling {+ walk(child)+ }+ }+ for _, node := range nodes {+ walk(node)+ }+ if !updated {+ return tokens+ }++ buf := bytes.Buffer{}+ for _, node := range nodes {+ if err = lutehtml.Render(&buf, node); err != nil {+ return tokens+ }+ }+ return buf.Bytes()+}++func rewriteTreeAssetReferences(tree *parse.Tree, options assetReferenceRewriteOptions) {+ if tree == nil || tree.Root == nil {+ return+ }++ titleImgPath := treenode.GetDocTitleImgPath(tree.Root)+ if rewritten := rewriteAssetReference(titleImgPath, options); titleImgPath != "" && rewritten != titleImgPath {+ titleImg := stdhtml.UnescapeString(tree.Root.IALAttr("title-img"))+ tree.Root.SetIALAttr("title-img", strings.Replace(titleImg, titleImgPath, rewritten, 1))+ }++ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering {+ return ast.WalkContinue+ }++ if node.IsBlock() {+ var assetAttrKeys []string+ for _, kv := range node.KramdownIAL {+ if strings.HasPrefix(kv[0], "custom-data-assets") || kv[0] == "data-assets" {+ assetAttrKeys = append(assetAttrKeys, kv[0])+ }+ }+ for _, key := range assetAttrKeys {+ value := node.IALAttr(key)+ if rewritten := rewriteAssetReference(value, options); rewritten != value {+ node.SetIALAttr(key, rewritten)+ }+ }+ }++ switch node.Type {+ case ast.NodeLinkDest:+ reference := node.TokensStr()+ if rewritten := rewriteAssetReference(reference, options); rewritten != reference {+ node.Tokens = []byte(rewritten)+ }+ case ast.NodeTextMark:+ if node.IsTextMarkType("a") {+ node.TextMarkAHref = rewriteAssetReference(node.TextMarkAHref, options)+ }+ if node.IsTextMarkType("file-annotation-ref") {+ node.TextMarkFileAnnotationRefID = rewriteAssetReference(node.TextMarkFileAnnotationRefID, options)+ }+ case ast.NodeHTMLBlock, ast.NodeInlineHTML, ast.NodeIFrame, ast.NodeWidget, ast.NodeAudio, ast.NodeVideo:+ node.Tokens = rewriteHTMLAssetReferences(node.Tokens, options)+ }+ return ast.WalkContinue+ })+}++func rewriteAttributeViewValueAssetReferences(value *av.Value, options assetReferenceRewriteOptions) (updated bool) {+ if value == nil {+ return+ }+ if value.URL != nil {+ rewritten := rewriteAssetReference(value.URL.Content, options)+ if rewritten != value.URL.Content {+ value.URL.Content = rewritten+ updated = true+ }+ }+ for _, asset := range value.MAsset {+ if asset == nil {+ continue+ }+ rewritten := rewriteAssetReference(asset.Content, options)+ if rewritten != asset.Content {+ asset.Content = rewritten+ updated = true+ }+ }+ if value.Relation != nil {+ for _, content := range value.Relation.Contents {+ updated = rewriteAttributeViewValueAssetReferences(content, options) || updated+ }+ }+ if value.Rollup != nil {+ for _, content := range value.Rollup.Contents {+ updated = rewriteAttributeViewValueAssetReferences(content, options) || updated+ }+ }+ return+}++func rewriteAttributeViewAssetReferences(attrView *av.AttributeView, options assetReferenceRewriteOptions) (updated bool) {+ if attrView == nil {+ return+ }+ for _, keyValues := range attrView.KeyValues {+ if keyValues == nil {+ continue+ }+ for _, value := range keyValues.Values {+ updated = rewriteAttributeViewValueAssetReferences(value, options) || updated+ }+ }+ return+}++func rewriteAttributeViewDataAssetReferences(data []byte, options assetReferenceRewriteOptions) ([]byte, error) {+ attrView := &av.AttributeView{}+ if err := gulu.JSON.UnmarshalJSON(data, attrView); err != nil {+ return nil, err+ }+ if !rewriteAttributeViewAssetReferences(attrView, options) {+ return data, nil+ }+ if util.UseSingleLineSave {+ return gulu.JSON.MarshalJSON(attrView)+ }+ return gulu.JSON.MarshalIndentJSON(attrView, "", "\t")+}diff --git a/kernel/model/asset_reference_test.go b/kernel/model/asset_reference_test.gonew file mode 100644index 0000000000..a8dd99fa13--- /dev/null+++ b/kernel/model/asset_reference_test.go@@ -0,0 +1,166 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ stdhtml "html"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestRewritePortableAssetReference(t *testing.T) {+ got := rewriteAssetReference("assets/image.png?box=20260812000000-source0&style=thumb#preview",+ assetReferenceRewriteOptions{rewriteUnmapped: true})+ want := "assets/image.png?style=thumb#preview"+ if got != want {+ t.Fatalf("rewrite portable asset reference = %q, want %q", got, want)+ }+}++func TestRewriteTreeAssetReferences(t *testing.T) {+ const targetBoxID = "20260812000001-target0"+ tree := treenode.NewTree(targetBoxID, "/20260812000002-doc0000.sy", "/Document", "Document")+ tree.Root.SetIALAttr("title-img", `background-image: url("assets/title.png?box=20260812000000-source0&style=cover")`)++ paragraph := treenode.NewParagraph("20260812000003-block00")+ paragraph.SetIALAttr("custom-data-assets", "assets/custom.png?box=20260812000000-source0")+ linkDest := &ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("assets/image.png?box=20260812000000-source0")}+ linkTextMark := &ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: "a",+ TextMarkAHref: "assets/link.pdf?page=2&box=20260812000000-source0",+ TextMarkTextContent: "Link",+ }+ annotationTextMark := &ast.Node{+ Type: ast.NodeTextMark,+ TextMarkType: "file-annotation-ref",+ TextMarkFileAnnotationRefID: "assets/link.pdf/20260812000004-annotat?box=20260812000000-source0",+ TextMarkTextContent: "Annotation",+ }+ paragraph.AppendChild(linkDest)+ paragraph.AppendChild(linkTextMark)+ paragraph.AppendChild(annotationTextMark)+ tree.Root.AppendChild(paragraph)++ htmlNodes := []*ast.Node{+ {Type: ast.NodeHTMLBlock, Tokens: []byte(`<div data-src="assets/component.html?box=20260812000000-source0&mode=block"></div>`)},+ {Type: ast.NodeInlineHTML, Tokens: []byte(`<span data-src="assets/component.html?box=20260812000000-source0&mode=inline"></span>`)},+ {Type: ast.NodeIFrame, Tokens: []byte(`<iframe src="assets/component.html?box=20260812000000-source0&mode=iframe"></iframe>`)},+ {Type: ast.NodeWidget, Tokens: []byte(`<iframe src="assets/component.html?box=20260812000000-source0&mode=widget"></iframe>`)},+ {Type: ast.NodeAudio, Tokens: []byte(`<audio src="assets/media.mp3?box=20260812000000-source0"></audio>`)},+ {Type: ast.NodeVideo, Tokens: []byte(`<video src="assets/media.mp4?box=20260812000000-source0"></video>`)},+ }+ for _, node := range htmlNodes {+ tree.Root.AppendChild(node)+ }++ options := assetReferenceRewriteOptions{+ pathMap: map[string]string{+ "assets/title.png": "assets/encrypted-title.png",+ "assets/custom.png": "assets/encrypted-custom.png",+ "assets/image.png": "assets/encrypted-image.png",+ "assets/link.pdf": "assets/encrypted-link.pdf",+ "assets/component.html": "assets/encrypted-component.html",+ "assets/media.mp3": "assets/encrypted-media.mp3",+ "assets/media.mp4": "assets/encrypted-media.mp4",+ },+ targetBoxID: targetBoxID,+ bindTargetBox: true,+ }+ rewriteTreeAssetReferences(tree, options)++ assertAssetReferenceContains(t, tree.Root.IALAttr("title-img"),+ "assets/encrypted-title.png?box="+targetBoxID+"&style=cover")+ if got, want := paragraph.IALAttr("custom-data-assets"), "assets/encrypted-custom.png?box="+targetBoxID; got != want {+ t.Fatalf("custom asset reference = %q, want %q", got, want)+ }+ if got, want := linkDest.TokensStr(), "assets/encrypted-image.png?box="+targetBoxID; got != want {+ t.Fatalf("link destination = %q, want %q", got, want)+ }+ if got, want := linkTextMark.TextMarkAHref, "assets/encrypted-link.pdf?box="+targetBoxID+"&page=2"; got != want {+ t.Fatalf("text mark link = %q, want %q", got, want)+ }+ if got, want := annotationTextMark.TextMarkFileAnnotationRefID,+ "assets/encrypted-link.pdf/20260812000004-annotat?box="+targetBoxID; got != want {+ t.Fatalf("PDF annotation reference = %q, want %q", got, want)+ }++ htmlWants := []string{+ "assets/encrypted-component.html?box=" + targetBoxID + "&mode=block",+ "assets/encrypted-component.html?box=" + targetBoxID + "&mode=inline",+ "assets/encrypted-component.html?box=" + targetBoxID + "&mode=iframe",+ "assets/encrypted-component.html?box=" + targetBoxID + "&mode=widget",+ "assets/encrypted-media.mp3?box=" + targetBoxID,+ "assets/encrypted-media.mp4?box=" + targetBoxID,+ }+ for i, node := range htmlNodes {+ assertAssetReferenceContains(t, string(node.Tokens), htmlWants[i])+ }+}++func TestRewriteAttributeViewAssetReferences(t *testing.T) {+ const (+ sourceBoxID = "20260812000000-source0"+ targetBoxID = "20260812000001-target0"+ )+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{{Values: []*av.Value{+ {URL: &av.ValueURL{Content: "assets/url.png?box=" + sourceBoxID}},+ {MAsset: []*av.ValueAsset{{Content: "assets/file.pdf?page=3&box=" + sourceBoxID}}},+ {Relation: &av.ValueRelation{Contents: []*av.Value{{URL: &av.ValueURL{Content: "assets/relation.png?box=" + sourceBoxID}}}}},+ {Rollup: &av.ValueRollup{Contents: []*av.Value{{MAsset: []*av.ValueAsset{{Content: "assets/rollup.png?box=" + sourceBoxID}}}}}},+ }}}}+ options := assetReferenceRewriteOptions{+ pathMap: map[string]string{+ "assets/url.png": "assets/encrypted-url.png",+ "assets/file.pdf": "assets/encrypted-file.pdf",+ "assets/relation.png": "assets/encrypted-relation.png",+ "assets/rollup.png": "assets/encrypted-rollup.png",+ },+ targetBoxID: targetBoxID,+ bindTargetBox: true,+ }+ if !rewriteAttributeViewAssetReferences(attrView, options) {+ t.Fatal("attribute view asset references were not updated")+ }++ values := attrView.KeyValues[0].Values+ assertEqualAssetReference(t, values[0].URL.Content, "assets/encrypted-url.png?box="+targetBoxID)+ assertEqualAssetReference(t, values[1].MAsset[0].Content, "assets/encrypted-file.pdf?box="+targetBoxID+"&page=3")+ assertEqualAssetReference(t, values[2].Relation.Contents[0].URL.Content,+ "assets/encrypted-relation.png?box="+targetBoxID)+ assertEqualAssetReference(t, values[3].Rollup.Contents[0].MAsset[0].Content,+ "assets/encrypted-rollup.png?box="+targetBoxID)+}++func assertAssetReferenceContains(t *testing.T, got, want string) {+ t.Helper()+ got = stdhtml.UnescapeString(got)+ if !strings.Contains(got, want) {+ t.Fatalf("asset reference %q does not contain %q", got, want)+ }+}++func assertEqualAssetReference(t *testing.T, got, want string) {+ t.Helper()+ if got != want {+ t.Fatalf("asset reference = %q, want %q", got, want)+ }+}diff --git a/kernel/model/export.go b/kernel/model/export.goindex 7bb573c3aa..40830d68ad 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -2487,9 +2487,11 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i// 按文件夹结构复制选择的树// 注意:tree 已被 filesys.LoadTree 透明解密成明文,这里序列化为明文 JSON 写盘// (不可 filelock.ReadFile 直接读盘,加密笔记本的磁盘 .sy 是密文)。+ portableAssetOptions := assetReferenceRewriteOptions{rewriteUnmapped: true}total := len(trees) + len(refTrees)for _, tree := range trees {if encrypted {+ rewriteTreeAssetReferences(tree, portableAssetOptions)removeFlashcardAttrs(tree)}writePath := strings.TrimPrefix(tree.Path, rootDirPath)@@ -2512,6 +2514,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i// 引用树放在导出文件夹根路径下for treeID, tree := range refTrees {if IsEncryptedBox(tree.Box) {+ rewriteTreeAssetReferences(tree, portableAssetOptions)removeFlashcardAttrs(tree)}writePath := filepath.Join(exportDir, treeID+".sy")@@ -2759,6 +2762,13 @@ func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMaplogging.LogErrorf("read attribute view [%s] failed: %s", avID, readErr)return}+ if boxID != "" && avData != nil {+ avData, readErr = rewriteAttributeViewDataAssetReferences(avData, assetReferenceRewriteOptions{rewriteUnmapped: true})+ if readErr != nil {+ logging.LogErrorf("rewrite exported attribute view assets [%s] failed: %s", avID, readErr)+ return+ }+ }if avData != nil {if mkdirErr := os.MkdirAll(exportStorageAvDir, 0755); mkdirErr != nil {logging.LogErrorf("create export av folder [%s] failed: %s", exportStorageAvDir, mkdirErr)@@ -2781,46 +2791,43 @@ func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMapreturn}- for _, keyValues := range attrView.KeyValues {- switch keyValues.Key.Type {- case av.KeyTypeMAsset: // 导出资源文件列 https://github.com/siyuan-note/siyuan/issues/9919- for _, value := range keyValues.Values {- for _, asset := range value.MAsset {- if !util.IsAssetLinkDest([]byte(asset.Content), false) {- continue- }+ copyExportAttributeViewAssets(attrView, boxID, exportFolder, assetPathMap)- destPath := filepath.Join(exportFolder, AssetPathWithoutQuery(asset.Content))- srcPath := ""- if boxID != "" {- srcPath, _ = GetAssetAbsPathInBox(asset.Content, boxID)- }- if "" == srcPath {- _, srcPath, _ = lookupAssetPath(assetPathMap, AssetPathWithoutQuery(asset.Content))- }- if "" == srcPath {- logging.LogWarnf("get asset [%s] abs path failed", asset.Content)- continue- }+ // 级联导出关联列关联的数据库+ exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder, assetPathMap)+}- if copyErr := copyAssetDecryptIfEncrypted(srcPath, destPath); nil != copyErr {- logging.LogErrorf("copy asset failed: %s", copyErr)- }- }- }+func copyExportAttributeViewAssets(attrView *av.AttributeView, boxID, exportFolder string, assetPathMap map[string]string) {+ // 导出资源文件列和指向本地资源的 URL 列 https://github.com/siyuan-note/siyuan/issues/9919+ for _, assetPath := range getAttributeViewAssetsLinkDests(attrView, false, nil) {+ destPath := filepath.Join(exportFolder, AssetPathWithoutQuery(assetPath))+ srcPath := ""+ if boxID != "" {+ srcPath, _ = GetAssetAbsPathInBox(assetPath, boxID)+ }+ if "" == srcPath {+ _, srcPath, _ = lookupAssetPath(assetPathMap, AssetPathWithoutQuery(assetPath))+ }+ if "" == srcPath {+ logging.LogWarnf("get asset [%s] abs path failed", assetPath)+ continue}- }- // 级联导出关联列关联的数据库- exportRelationAvs(avID, boxID, exportStorageAvDir)+ if copyErr := copyAssetDecryptIfEncrypted(srcPath, destPath); nil != copyErr {+ logging.LogErrorf("copy asset failed: %s", copyErr)+ }+ }}-func exportRelationAvs(avID, boxID, exportStorageAvDir string) {+func exportRelationAvs(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) {avIDs := hashset.New()walkRelationAvs(avID, boxID, avIDs)for _, v := range avIDs.Values() {relAvID := v.(string)+ if relAvID == avID {+ continue+ }var relAvData []bytevar readErr errorif boxID != "" {@@ -2832,12 +2839,33 @@ func exportRelationAvs(avID, boxID, exportStorageAvDir string) {logging.LogErrorf("read relation attribute view [%s] failed: %s", relAvID, readErr)continue}+ if boxID != "" && relAvData != nil {+ relAvData, readErr = rewriteAttributeViewDataAssetReferences(relAvData,+ assetReferenceRewriteOptions{rewriteUnmapped: true})+ if readErr != nil {+ logging.LogErrorf("rewrite exported relation attribute view assets [%s] failed: %s", relAvID, readErr)+ continue+ }+ }if relAvData == nil {continue}if writeErr := os.WriteFile(filepath.Join(exportStorageAvDir, relAvID+".json"), relAvData, 0644); writeErr != nil {logging.LogErrorf("write av json failed: %s", writeErr)}++ var attrView *av.AttributeView+ var parseErr error+ if boxID != "" {+ attrView, parseErr = av.ParseAttributeViewInBox(relAvID, boxID)+ } else {+ attrView, parseErr = av.ParseAttributeView(relAvID)+ }+ if parseErr != nil {+ logging.LogErrorf("parse relation attribute view [%s] failed: %s", relAvID, parseErr)+ continue+ }+ copyExportAttributeViewAssets(attrView, boxID, exportFolder, assetPathMap)}}diff --git a/kernel/model/import.go b/kernel/model/import.goindex fcdef4977a..55f0bc36ea 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -400,6 +400,20 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c}blockIDReplacer := strings.NewReplacer(replacements...)+ assetPathMap, err := importSYAssets(unzipRootPath, boxID)+ if err != nil {+ return createdBoxID, err+ }++ assetRewriteOptions := assetReferenceRewriteOptions{+ pathMap: assetPathMap,+ targetBoxID: boxID,+ bindTargetBox: IsEncryptedBox(boxID),+ }+ for _, tree := range trees {+ rewriteTreeAssetReferences(tree, assetRewriteOptions)+ }+// 将关联的数据库文件移动到 data/storage/av/ 下storage := filepath.Join(unzipRootPath, "storage")storageAvDir := filepath.Join(storage, "av")@@ -450,6 +464,11 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (cnewData = bytes.ReplaceAll(newData, []byte(oldAvID), []byte(newAvID))}newData = []byte(blockIDReplacer.Replace(string(newData)))+ newData, err = rewriteAttributeViewDataAssetReferences(newData, assetRewriteOptions)+ if err != nil {+ logging.LogErrorf("rewrite imported attribute view assets [%s] failed: %s", oldPath, err)+ return+ }if !bytes.Equal(data, newData) {if writeErr := os.WriteFile(oldPath, newData, 0644); nil != writeErr {logging.LogErrorf("write av file [%s] failed: %s", oldPath, writeErr)@@ -736,69 +755,6 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (c}}- // 将包含的资源文件统一移动到 assets 下- // 加密笔记本拷到 <boxID>/assets/,普通笔记本拷到全局 data/assets/- // 加密笔记本同时收集「原始名 → 脱敏名」映射,用于后续更新文档内的引用路径- assetNameMap := map[string]string{} // 原始文件名 → 脱敏文件名- var assetsDirs []string- filelock.Walk(unzipRootPath, func(path string, d fs.DirEntry, err error) error {- if err != nil {- return err- }- if d == nil || unzipRootPath == path {- return nil- }- if d.Name() == "assets" && d.IsDir() {- assetsDirs = append(assetsDirs, path)- }- return nil- })- dataAssets := filepath.Join(util.DataDir, "assets")- if IsEncryptedBox(boxID) {- // 加密笔记本的资源文件拷到笔记本级 assets 目录,文件名脱敏 + 内容加密- boxAssetsDir := filepath.Join(util.DataDir, boxID, "assets")- if err = os.MkdirAll(boxAssetsDir, 0755); err != nil {- return- }- for _, assets := range assetsDirs {- if gulu.File.IsDir(assets) {- filelock.Walk(assets, func(path string, d fs.DirEntry, err error) error {- if err != nil || d == nil || d.IsDir() {- return err- }- originalName := d.Name()- ext := filepath.Ext(originalName)- blockID := ast.NewNodeID()- diskName := encryptedAssetName(ext, blockID)- assetNameMap[originalName] = diskName- // 读取明文内容 → 加密 → 写入脱敏文件名- src, readErr := filelock.ReadFile(path)- if readErr != nil {- return readErr- }- if err = writeAssetFile(filepath.Join(boxAssetsDir, diskName), bytes.NewReader(src), boxID, originalName); err != nil {- return err- }- return nil- })- if err != nil {- return- }- }- os.RemoveAll(assets)- }- } else {- for _, assets := range assetsDirs {- if gulu.File.IsDir(assets) {- if err = filelock.Copy(assets, dataAssets); err != nil {- logging.LogErrorf("copy assets from [%s] to [%s] failed: %s", assets, dataAssets, err)- return- }- }- os.RemoveAll(assets)- }- }-// AV 定义已在 storage 删除前处理(加密笔记本DEK 加密拷到笔记本级,// 普通 box 拷到全局 storage/av/),这里不再重复处理@@ -911,12 +867,6 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (ccontinue}- // 加密笔记本:更新文档内的 assets 引用路径(原始名 → 脱敏名)- if IsEncryptedBox(boxID) && 0 < len(assetNameMap) {- updateImportedAssetRefs(tree, assetNameMap)- indexWriteTreeIndexQueue(tree)- }-treenode.IndexBlockTree(tree)cache.PutDocIALInBox(tree.Path, tree.Box, parse.IAL2Map(tree.Root.KramdownIAL))var avNodes []*ast.Node@@ -936,6 +886,112 @@ func importSY(zipPath, boxID, toPath string, createNotebook, autoDetect bool) (creturn}+// importSYAssets 将包内资源写入目标存储,并建立包内路径到目标路径的精确映射。+// 普通笔记本也保留恒等映射,用于清除旧版加密笔记本导出包中残留的 box 查询参数。+func importSYAssets(unzipRootPath, boxID string) (assetPathMap map[string]string, err error) {+ assetPathMap = map[string]string{}+ var assetsDirs []string+ if err = filelock.Walk(unzipRootPath, func(currentPath string, d fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if d == nil || unzipRootPath == currentPath {+ return nil+ }+ if d.Name() == "assets" && d.IsDir() {+ assetsDirs = append(assetsDirs, currentPath)+ return filepath.SkipDir+ }+ return nil+ }); err != nil {+ return nil, err+ }++ if IsEncryptedBox(boxID) {+ boxAssetsDir := filepath.Join(util.DataDir, boxID, "assets")+ if err = os.MkdirAll(boxAssetsDir, 0755); err != nil {+ return nil, err+ }+ for _, assetsDir := range assetsDirs {+ var assetFiles []string+ if err = filelock.Walk(assetsDir, func(currentPath string, d fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if d != nil && !d.IsDir() && !strings.HasSuffix(strings.ToLower(d.Name()), ".sya") {+ assetFiles = append(assetFiles, currentPath)+ }+ return nil+ }); err != nil {+ return nil, err+ }+ sort.Strings(assetFiles)+ for _, assetFile := range assetFiles {+ relPath, relErr := filepath.Rel(assetsDir, assetFile)+ if relErr != nil {+ return nil, relErr+ }+ sourceAssetPath := canonicalAssetReferencePath(path.Join("assets", filepath.ToSlash(relPath)))+ data, readErr := filelock.ReadFile(assetFile)+ if readErr != nil {+ return nil, readErr+ }+ diskName, storeErr := storeAssetForBox(boxID, boxAssetsDir, filepath.Base(assetFile), data)+ if storeErr != nil {+ return nil, storeErr+ }+ assetPathMap[sourceAssetPath] = path.Join("assets", diskName)++ annotationPath := assetFile + ".sya"+ if filelock.IsExist(annotationPath) {+ annotationData, annotationReadErr := filelock.ReadFile(annotationPath)+ if annotationReadErr != nil {+ return nil, annotationReadErr+ }+ annotationTargetPath := filepath.Join(boxAssetsDir, diskName+".sya")+ if writeErr := writeAssetFile(annotationTargetPath, bytes.NewReader(annotationData), boxID,+ filepath.Base(annotationPath)); writeErr != nil {+ return nil, writeErr+ }+ }+ }+ if removeErr := os.RemoveAll(assetsDir); removeErr != nil {+ return nil, removeErr+ }+ }+ return assetPathMap, nil+ }++ dataAssets := filepath.Join(util.DataDir, "assets")+ for _, assetsDir := range assetsDirs {+ if err = filelock.Walk(assetsDir, func(currentPath string, d fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if d == nil || d.IsDir() || strings.HasSuffix(strings.ToLower(d.Name()), ".sya") {+ return nil+ }+ relPath, relErr := filepath.Rel(assetsDir, currentPath)+ if relErr != nil {+ return relErr+ }+ assetPath := canonicalAssetReferencePath(path.Join("assets", filepath.ToSlash(relPath)))+ assetPathMap[assetPath] = assetPath+ return nil+ }); err != nil {+ return nil, err+ }+ if err = filelock.Copy(assetsDir, dataAssets); err != nil {+ logging.LogErrorf("copy assets from [%s] to [%s] failed: %s", assetsDir, dataAssets, err)+ return nil, err+ }+ if removeErr := os.RemoveAll(assetsDir); removeErr != nil {+ return nil, removeErr+ }+ }+ return assetPathMap, nil+}+func writeImportedTree(boxID, syPath, newSyPath, relPath string, data []byte) error {if IsEncryptedBox(boxID) {HoldBoxReadLock(boxID)@@ -956,72 +1012,6 @@ func writeImportedTree(boxID, syPath, newSyPath, relPath string, data []byte) erreturn filelock.Rename(syPath, newSyPath)}-// updateImportedAssetRefs 遍历树的 assets 引用路径,将原始文件名替换为脱敏文件名。-// 覆盖:链接 href、图片 src、data-src、音视频 src、文件标注等。-func updateImportedAssetRefs(tree *parse.Tree, assetNameMap map[string]string) {- boxSuffix := ""- if IsEncryptedBox(tree.Box) {- boxSuffix = "?box=" + tree.Box- }- ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {- if !entering {- return ast.WalkContinue- }- switch n.Type {- case ast.NodeLink:- // 链接 dest- dest := string(n.Tokens)- if updated := replaceAssetName(dest, assetNameMap, boxSuffix); updated != dest {- n.Tokens = []byte(updated)- }- case ast.NodeImage:- // 图片 src 在 LinkDest 子节点- if dest := n.ChildByType(ast.NodeLinkDest); nil != dest {- src := string(dest.Tokens)- if updated := replaceAssetName(src, assetNameMap, boxSuffix); updated != src {- dest.Tokens = []byte(updated)- }- }- case ast.NodeAudio, ast.NodeVideo:- src := n.TokensStr()- if updated := replaceAssetName(src, assetNameMap, boxSuffix); updated != src {- n.Tokens = []byte(updated)- }- case ast.NodeTextMark:- // 行级文本标记里的 data-href(附件链接)- if "" != n.TextMarkAHref {- if updated := replaceAssetName(n.TextMarkAHref, assetNameMap, boxSuffix); updated != n.TextMarkAHref {- n.TextMarkAHref = updated- }- }- }- return ast.WalkContinue- })-}--// replaceAssetName 在 assets 路径中替换原始文件名为脱敏文件名,并按需追加 box query。-func replaceAssetName(path string, assetNameMap map[string]string, boxSuffix string) string {- if !strings.Contains(path, "assets/") {- return path- }- for original, diskName := range assetNameMap {- // 匹配 assets/originalName(路径末尾的文件名)- idx := strings.LastIndex(path, original)- if idx > 0 && strings.Contains(path[idx:], original) {- path = path[:idx] + diskName + path[idx+len(original):]- // 替换后如果没有 box query,补上- if boxSuffix != "" && !strings.Contains(path, "?box=") {- if strings.Contains(path, "?") {- path += "&" + strings.TrimPrefix(boxSuffix, "?")- } else {- path += boxSuffix- }- }- }- }- return path-}-func validateImportedNotebookIdentities(tmpDataPath string) ([]string, error) {dirs, err := os.ReadDir(tmpDataPath)if err != nil {diff --git a/kernel/model/import_test.go b/kernel/model/import_test.goindex 56e283ab5b..1ecf5115d7 100644--- a/kernel/model/import_test.go+++ b/kernel/model/import_test.go@@ -17,9 +17,11 @@package modelimport (+ "bytes""errors""os""path/filepath"+ "strings""testing""github.com/siyuan-note/siyuan/kernel/util"@@ -137,30 +139,154 @@ func TestStoreAssetForBoxAvoidsGlobalNameCollision(t *testing.T) {}}-func TestReplaceAssetNamePreservesExistingQuery(t *testing.T) {- assetNameMap := map[string]string{"document.pdf": "encrypted.pdf"}- boxSuffix := "?box=20260731190414-j45dgmm"+func TestRewriteImportedAssetReference(t *testing.T) {+ const targetBoxID = "20260731190414-j45dgmm"+ options := assetReferenceRewriteOptions{+ pathMap: map[string]string{"assets/document.pdf": "assets/encrypted.pdf"},+ targetBoxID: targetBoxID,+ bindTargetBox: true,+ rewriteUnmapped: false,+ }tests := []struct {- path string- want string+ reference string+ want string}{{- path: "assets/document.pdf",- want: "assets/encrypted.pdf?box=20260731190414-j45dgmm",+ reference: "assets/document.pdf",+ want: "assets/encrypted.pdf?box=" + targetBoxID,+ },+ {+ reference: "assets/document.pdf?page=2",+ want: "assets/encrypted.pdf?box=" + targetBoxID + "&page=2",},{- path: "assets/document.pdf?page=2",- want: "assets/encrypted.pdf?page=2&box=20260731190414-j45dgmm",+ reference: "assets/document.pdf?box=20260701000000-source0&page=2",+ want: "assets/encrypted.pdf?box=" + targetBoxID + "&page=2",},{- path: "assets/document.pdf?box=20260731190414-j45dgmm",- want: "assets/encrypted.pdf?box=20260731190414-j45dgmm",+ reference: "assets/document.pdf/20260731190415-annotat?box=20260701000000-source0",+ want: "assets/encrypted.pdf/20260731190415-annotat?box=" + targetBoxID,+ },+ {+ reference: "assets/not-in-package.pdf?box=20260701000000-source0",+ want: "assets/not-in-package.pdf?box=20260701000000-source0",},}for _, test := range tests {- if got := replaceAssetName(test.path, assetNameMap, boxSuffix); got != test.want {- t.Fatalf("replaceAssetName(%q) = %q, want %q", test.path, got, test.want)+ if got := rewriteAssetReference(test.reference, options); got != test.want {+ t.Fatalf("rewriteAssetReference(%q) = %q, want %q", test.reference, got, test.want)+ }+ }+}++func TestRewriteImportedAssetReferenceForNormalNotebook(t *testing.T) {+ options := assetReferenceRewriteOptions{+ pathMap: map[string]string{"assets/image.png": "assets/image.png"},+ }+ got := rewriteAssetReference("assets/image.png?box=20260701000000-source0&style=thumb", options)+ want := "assets/image.png?style=thumb"+ if got != want {+ t.Fatalf("rewrite normal notebook asset reference = %q, want %q", got, want)+ }+}++func TestImportSYAssets(t *testing.T) {+ assetData := []byte("PDF data")+ annotationData := []byte(`{"annotations":[]}`)++ t.Run("normal notebook", func(t *testing.T) {+ originalDataDir := util.DataDir+ util.DataDir = filepath.Join(t.TempDir(), "data")+ t.Cleanup(func() {+ util.DataDir = originalDataDir+ })++ unzipRootPath, sourceAssetPath := writeImportSYAssetFixture(t, assetData, annotationData)+ assetPathMap, err := importSYAssets(unzipRootPath, "")+ if err != nil {+ t.Fatal(err)+ }+ if got := assetPathMap[sourceAssetPath]; got != sourceAssetPath {+ t.Fatalf("normal asset mapping = %q, want %q", got, sourceAssetPath)+ }+ assertFileContent(t, filepath.Join(util.DataDir, filepath.FromSlash(sourceAssetPath)), assetData)+ assertFileContent(t, filepath.Join(util.DataDir, filepath.FromSlash(sourceAssetPath+".sya")), annotationData)+ })++ t.Run("encrypted notebook", func(t *testing.T) {+ const boxID = "20260812000005-encrypt"+ originalDataDir := util.DataDir+ originalWorkspaceDir := util.WorkspaceDir+ util.WorkspaceDir = t.TempDir()+ util.DataDir = filepath.Join(util.WorkspaceDir, "data")+ markRuntimeEncryptedBox(boxID)+ dek, err := util.GenerateDEK()+ if err != nil {+ t.Fatal(err)+ }+ setDEKForTest(boxID, dek)+ t.Cleanup(func() {+ cachedDEKsLock.Lock()+ if cachedDEK := cachedDEKs[boxID]; cachedDEK != nil {+ zeroAndClear(cachedDEK)+ }+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ forgetRuntimeEncryptedBox(boxID)+ util.DataDir = originalDataDir+ util.WorkspaceDir = originalWorkspaceDir+ })++ unzipRootPath, sourceAssetPath := writeImportSYAssetFixture(t, assetData, annotationData)+ assetPathMap, err := importSYAssets(unzipRootPath, boxID)+ if err != nil {+ t.Fatal(err)+ }+ targetAssetPath := assetPathMap[sourceAssetPath]+ if targetAssetPath == "" || targetAssetPath == sourceAssetPath {+ t.Fatalf("encrypted asset mapping = %q", targetAssetPath)+ }+ if !strings.HasPrefix(targetAssetPath, "assets/") {+ t.Fatalf("encrypted asset path = %q", targetAssetPath)+ }+ if got, readErr := ReadAssetBytesInBox(boxID, targetAssetPath); readErr != nil {+ t.Fatal(readErr)+ } else if !bytes.Equal(got, assetData) {+ t.Fatalf("encrypted asset plaintext = %q, want %q", got, assetData)}+ if got, readErr := ReadAssetBytesInBox(boxID, targetAssetPath+".sya"); readErr != nil {+ t.Fatal(readErr)+ } else if !bytes.Equal(got, annotationData) {+ t.Fatalf("encrypted annotation plaintext = %q, want %q", got, annotationData)+ }+ })+}++func writeImportSYAssetFixture(t *testing.T, assetData, annotationData []byte) (unzipRootPath, assetPath string) {+ t.Helper()+ unzipRootPath = t.TempDir()+ assetPath = "assets/nested/document.pdf"+ absoluteAssetPath := filepath.Join(unzipRootPath, filepath.FromSlash(assetPath))+ if err := os.MkdirAll(filepath.Dir(absoluteAssetPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(absoluteAssetPath, assetData, 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(absoluteAssetPath+".sya", annotationData, 0644); err != nil {+ t.Fatal(err)+ }+ return+}++func assertFileContent(t *testing.T, path string, want []byte) {+ t.Helper()+ got, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(got, want) {+ t.Fatalf("file [%s] content = %q, want %q", path, got, want)}}