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: Fix encrypted asset external operations https://github.com/siyuan-note/siyuan/issues/18034
Daniel0c25b9c918b1
diff --git a/app/src/asset/renderAssets.ts b/app/src/asset/renderAssets.tsindex fd76ce862f..3582feb225 100644--- a/app/src/asset/renderAssets.ts+++ b/app/src/asset/renderAssets.ts@@ -2,14 +2,14 @@ import {Constants} from "../constants";/// #if !MOBILEimport {getAllModels} from "../layout/getAll";/// #endif-import {pathPosix} from "../util/pathName";+import {getAssetExtension} from "../util/pathName";import * as dayjs from "dayjs";export const renderAssetsPreview = (pathString: string) => {if (!pathString) {return "";}- const type = pathPosix().extname(pathString).toLowerCase();+ const type = getAssetExtension(pathString).toLowerCase();if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {return `<img style="max-height: 100%" src="${pathString}">`;} else if (Constants.SIYUAN_ASSETS_AUDIO.includes(type)) {diff --git a/app/src/editor/openLink.ts b/app/src/editor/openLink.tsindex 9504f2e70b..5d2f613f72 100644--- a/app/src/editor/openLink.ts+++ b/app/src/editor/openLink.ts@@ -1,4 +1,4 @@-import {isLocalPath, pathPosix} from "../util/pathName";+import {getAssetExtension, isLocalPath} from "../util/pathName";/// #if !BROWSERimport {shell} from "electron";/// #endif@@ -32,11 +32,12 @@ export const openLink = (app: App, aLink: string, event?: MouseEvent, ctrlIsPresopenByMobile(linkAddress);/// #elseif (isLocalPath(linkAddress)) {- if (Constants.SIYUAN_ASSETS_EXTS.includes(pathPosix().extname(linkAddress)) &&+ const extension = getAssetExtension(linkAddress);+ if (Constants.SIYUAN_ASSETS_EXTS.includes(extension) &&(- !linkAddress.endsWith(".pdf") ||+ extension !== ".pdf" ||// 本地 pdf 仅 assets/ 开头的才使用 siyuan 打开- (linkAddress.endsWith(".pdf") && linkAddress.startsWith("assets/"))+ (extension === ".pdf" && linkAddress.startsWith("assets/")))) {if (event && event.altKey) {diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex 5632060a73..b9f70d5b05 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -5,7 +5,7 @@ import {getInstanceById, getWndByLayout, newModelByInitData, pdfIsLoading, setPaimport {getDockByType} from "../layout/tabUtil";import {getAllModels, getAllTabs} from "../layout/getAll";import {highlightById, scrollCenter} from "../util/highlightById";-import {getDisplayName, getDocDisplayName, isEncryptedBox, pathPosix, useShell} from "../util/pathName";+import {getAssetExtension, getDisplayName, getDocDisplayName, isEncryptedBox, useShell} from "../util/pathName";import {Constants} from "../constants";import {Files} from "../layout/dock/Files";import {fetchPost, fetchSyncPost} from "../util/fetch";@@ -90,7 +90,7 @@ export const openFileById = async (options: {};export const openAsset = (app: App, assetPath: string, page: number | string, position?: string) => {- const suffix = pathPosix().extname(assetPath).split("?")[0];+ const suffix = getAssetExtension(assetPath);if (!Constants.SIYUAN_ASSETS_EXTS.includes(suffix)) {return;}@@ -491,7 +491,7 @@ const switchEditor = (editor: Editor, options: IOpenFileOptions, allModels: IModconst newTab = (options: IOpenFileOptions) => {let tab: Tab;if (options.assetPath) {- const suffix = pathPosix().extname(options.assetPath).split("?")[0];+ const suffix = getAssetExtension(options.assetPath);if (Constants.SIYUAN_ASSETS_EXTS.includes(suffix)) {let icon = "iconPDF";if (Constants.SIYUAN_ASSETS_IMAGE.includes(suffix)) {diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.tsindex fd1375f091..b673ae9860 100644--- a/app/src/menus/commonMenuItem.ts+++ b/app/src/menus/commonMenuItem.ts@@ -3,7 +3,7 @@ import {shell} from "electron";/// #endifimport {confirmDialog} from "../dialog/confirmDialog";import {getSearch, isMobile, isValidCustomAttrName} from "../util/functions";-import {isEncryptedBox, isLocalPath, movePathTo, moveToPath, pathPosix} from "../util/pathName";+import {getAssetExtension, isEncryptedBox, isLocalPath, movePathTo, moveToPath, pathPosix} from "../util/pathName";import {MenuItem} from "./Menu";import {onExport, saveExport} from "../protyle/export";import {exportMarkdownZip} from "../protyle/export/exportMd";@@ -853,9 +853,10 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAccelerat});/// #elseif (isLocalPath(src)) {- if (Constants.SIYUAN_ASSETS_EXTS.includes(pathPosix().extname(src).split("?")[0]) &&- (!src.endsWith(".pdf") ||- (src.endsWith(".pdf") && !src.startsWith("file://")))+ const extension = getAssetExtension(src);+ if (Constants.SIYUAN_ASSETS_EXTS.includes(extension) &&+ (extension !== ".pdf" ||+ (extension === ".pdf" && !src.startsWith("file://")))) {submenu.push({id: "insertRight",diff --git a/app/src/menus/util.ts b/app/src/menus/util.tsindex 001e08a922..5b827c185c 100644--- a/app/src/menus/util.ts+++ b/app/src/menus/util.ts@@ -3,7 +3,7 @@ import {ipcRenderer} from "electron";import * as path from "path";/// #endifimport {fetchPost} from "../util/fetch";-import {getAssetName, pathPosix, useShell} from "../util/pathName";+import {getAssetExtension, getAssetName, useShell} from "../util/pathName";import {openFileById} from "../editor/util";import {Constants} from "../constants";import {openNewWindowById} from "../window/openNewWindow";@@ -26,7 +26,7 @@ export const exportAsset = (src: string) => {/// #elseconst result = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "showSaveDialog",- defaultPath: getAssetName(src) + pathPosix().extname(src),+ defaultPath: getAssetName(src) + getAssetExtension(src),properties: ["showOverwriteConfirmation"],});if (!result.canceled) {diff --git a/app/src/protyle/hint/extend.ts b/app/src/protyle/hint/extend.tsindex 393c1c283a..6b77623e4a 100644--- a/app/src/protyle/hint/extend.ts+++ b/app/src/protyle/hint/extend.ts@@ -11,7 +11,7 @@ import {hasClosestBlock, hasClosestByClassName} from "../util/hasClosest";import {getContenteditableElement, getTopAloneElement} from "../wysiwyg/getBlock";import {replaceFileName} from "../../editor/rename";import {transaction} from "../wysiwyg/transaction";-import {getAssetName, getDisplayName, isEncryptedBox, pathPosix} from "../../util/pathName";+import {getAssetExtension, getAssetName, getDisplayName, isEncryptedBox} from "../../util/pathName";import {genEmptyElement} from "../../block/util";import {updateListOrder} from "../wysiwyg/list";import {escapeHtml} from "../../util/escape";@@ -604,7 +604,7 @@ export const hintRenderWidget = (value: string, protyle: IProtyle) => {export const hintRenderAssets = (value: string, protyle: IProtyle) => {focusByRange(protyle.toolbar.range);- const type = pathPosix().extname(value).toLowerCase();+ const type = getAssetExtension(value).toLowerCase();const filename = value.startsWith("assets/") ? getAssetName(value) : value;insertHTML(genAssetHTML(type, value, filename, value.startsWith("assets/") ? filename + type : value), protyle);hideElements(["util"], protyle);diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.tsindex 6893a0c3d6..5c517d15b5 100644--- a/app/src/protyle/render/av/asset.ts+++ b/app/src/protyle/render/av/asset.ts@@ -4,7 +4,7 @@ import {updateAttrViewCellAnimation} from "./action";import {isMobile} from "../../../util/functions";import {Constants} from "../../../constants";import {uploadFiles} from "../../upload";-import {pathPosix} from "../../../util/pathName";+import {getAssetExtension, pathPosix} from "../../../util/pathName";import {openMenu} from "../../../menus/commonMenuItem";import {MenuItem} from "../../../menus/Menu";import {copyPNGByLink, exportAsset, writeAssetToClipboard} from "../../../menus/util";@@ -46,7 +46,7 @@ export const bindAssetEvent = (options: {value.push({name: key,content: resData.data.succMap[key],- type: Constants.SIYUAN_ASSETS_IMAGE.includes(pathPosix().extname(resData.data.succMap[key]).toLowerCase()) ? "image" : "file"+ type: Constants.SIYUAN_ASSETS_IMAGE.includes(getAssetExtension(resData.data.succMap[key]).toLowerCase()) ? "image" : "file"});});updateAssetCell({diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.tsindex cbff072c15..9a5373058b 100644--- a/app/src/protyle/render/av/cell.ts+++ b/app/src/protyle/render/av/cell.ts@@ -12,7 +12,7 @@ import {getColIconByType, getColId} from "./col";import {genAVValueHTML, getAVTemplateHTML} from "./attributeValue";import {Constants} from "../../../constants";import {hintRef} from "../../hint/extend";-import {getAssetName, pathPosix} from "../../../util/pathName";+import {getAssetExtension, getAssetName} from "../../../util/pathName";import {mergeAddOption} from "./select";import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";import {electronUndo} from "../../undo";@@ -230,7 +230,7 @@ const transformCellValue = (colType: TAVCol, value: IAVCellValue): IAVCellValue} else if (colType === "mAsset") {const content = getCellValueContent(value).toString();newValue.mAsset = [{- type: Constants.SIYUAN_ASSETS_IMAGE.includes(pathPosix().extname(content).toLowerCase()) ? "image" : "file",+ type: Constants.SIYUAN_ASSETS_IMAGE.includes(getAssetExtension(content).toLowerCase()) ? "image" : "file",content,name: "",}];@@ -302,7 +302,7 @@ export const genCellValue = (colType: TAVCol, value: string | any, dateFormat: Trelation: {blockIDs: [value], contents: []}};} else if (colType === "mAsset") {- const type = pathPosix().extname(value).toLowerCase();+ const type = getAssetExtension(value).toLowerCase();cellValue = {type: colType,mAsset: [{@@ -842,7 +842,7 @@ export const updateCellsValue = async (protyle: IProtyle, nodeElement: HTMLEleme// https://github.com/siyuan-note/siyuan/issues/13892if (!link && value.startsWith("assets/")) {link = value;- name = getAssetName(value) + pathPosix().extname(value);+ name = getAssetName(value) + getAssetExtension(value);}// https://github.com/siyuan-note/siyuan/issues/12308if (html) {diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex 9ecf465a02..f020678443 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -38,7 +38,7 @@ import {updateAttrViewCellAnimation} from "./action";import {addAssetLink, bindAssetEvent, editAssetItem, getAssetHTML, updateAssetCell} from "./asset";import {Constants} from "../../../constants";import {hideElements} from "../../ui/hideElements";-import {pathPosix} from "../../../util/pathName";+import {getAssetExtension} from "../../../util/pathName";import {openEmojiPanel, unicode2Emoji} from "../../../emoji";import {isMobile} from "../../../util/functions";import {openLink} from "../../../editor/openLink";@@ -1751,7 +1751,7 @@ export const openMenuPanel = (options: {h: rect.height}, (url, name) => {let value: IAVCellAssetValue;- if (Constants.SIYUAN_ASSETS_IMAGE.includes(pathPosix().extname(url).toLowerCase())) {+ if (Constants.SIYUAN_ASSETS_IMAGE.includes(getAssetExtension(url).toLowerCase())) {value = {type: "image",content: url,diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex c3e48fbd8c..c7b1dc1ff3 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -154,8 +154,17 @@ export const getDocDisplayName = (name: string, titleEmpty?: boolean, escape?: breturn displayName;};+export const getAssetPathWithoutQuery = (assetPath: string) => {+ return assetPath.split("?", 1)[0];+};++export const getAssetExtension = (assetPath: string) => {+ return pathPosix().extname(getAssetPathWithoutQuery(assetPath));+};+export const getAssetName = (assetPath: string) => {- return pathPosix().basename(assetPath, pathPosix().extname(assetPath)).replace(/-\d{14}-\w{7}/, "");+ const pathWithoutQuery = getAssetPathWithoutQuery(assetPath);+ return pathPosix().basename(pathWithoutQuery, getAssetExtension(pathWithoutQuery)).replace(/-\d{14}-\w{7}/, "");};export const isLocalPath = (link: string) => {diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.tsindex bf6b9e0b91..85c415fdef 100644--- a/app/src/window/openNewWindow.ts+++ b/app/src/window/openNewWindow.ts@@ -6,7 +6,7 @@ import {Constants} from "../constants";import {Tab} from "../layout/Tab";import {fetchSyncPost} from "../util/fetch";import {showMessage} from "../dialog/message";-import {getDisplayName, pathPosix} from "../util/pathName";+import {getAssetExtension, getDisplayName} from "../util/pathName";import {getSearch} from "../util/functions";interface windowOptions {@@ -77,7 +77,7 @@ export const openNewWindowById = async (id: string | string[], options: windowOpexport const openAssetNewWindow = (assetPath: string, options: windowOptions = {}) => {/// #if !BROWSER- const suffix = pathPosix().extname(assetPath).split("?")[0];+ const suffix = getAssetExtension(assetPath);if (Constants.SIYUAN_ASSETS_EXTS.includes(suffix)) {let docIcon = "iconPDF";if (Constants.SIYUAN_ASSETS_IMAGE.includes(suffix)) {diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex ce89b8c2a5..3b55c76c74 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -478,19 +478,13 @@ func resolveAssetPath(c *gin.Context) {}path := arg["path"].(string)- p, err := model.GetAssetAbsPathInBox(path, "")+ p, err := model.PrepareAssetForOpen(path)if err != nil {ret.Code = -1ret.Msg = err.Error()ret.Data = map[string]any{"closeTimeout": 3000}return}- if model.IsEncryptedAssetPath(p) {- ret.Code = -1- ret.Msg = model.Conf.Language(314)- ret.Data = map[string]any{"closeTimeout": 3000}- return- }ret.Data = preturn}diff --git a/kernel/api/clipboard.go b/kernel/api/clipboard.goindex 58598c74f7..c40c07a4cf 100644--- a/kernel/api/clipboard.go+++ b/kernel/api/clipboard.go@@ -72,7 +72,7 @@ func writeFilePath(c *gin.Context) {return}- absPath, err := model.GetAssetAbsPathInBox(pathArg, "")+ absPath, err := model.PrepareAssetForOpen(pathArg)if err != nil {logging.LogErrorf("get asset [%s] abs path failed: %s", pathArg, err)ret.Code = -1@@ -80,12 +80,6 @@ func writeFilePath(c *gin.Context) {ret.Data = map[string]any{"closeTimeout": 5000}return}- if model.IsEncryptedAssetPath(absPath) {- ret.Code = -1- ret.Msg = model.Conf.Language(314)- ret.Data = map[string]any{"closeTimeout": 5000}- return- }if err = util.WriteFilePaths([]string{absPath}); err != nil {logging.LogErrorf("write file path to clipboard failed: %s", err)diff --git a/kernel/model/asset_open.go b/kernel/model/asset_open.gonew file mode 100644index 0000000000..9c076d0f34--- /dev/null+++ b/kernel/model/asset_open.go@@ -0,0 +1,117 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "errors"+ "os"+ "path/filepath"+ "strings"++ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// PrepareAssetForOpen 返回可交给系统应用打开的资源绝对路径。+// 加密资源会流式解密到按 box 隔离的临时目录,该目录在笔记本锁定或内核下次启动时清理。+func PrepareAssetForOpen(assetPath string) (ret string, err error) {+ assetAbsPath, err := GetAssetAbsPathInBox(assetPath, "")+ if err != nil {+ return "", err+ }+ if !IsEncryptedAssetPath(assetAbsPath) {+ return assetAbsPath, nil+ }++ boxID := ExtractBoxIDFromAssetsPath(assetAbsPath)+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {+ return "", errors.New(Conf.Language(314))+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ HoldBoxReadLock(boxID)+ defer ReleaseBoxReadLock(boxID)++ dek, err := GetDEKIfUnlocked(boxID)+ if err != nil {+ return "", errors.New(Conf.Language(314))+ }+ defer zeroAndClear(dek)+ if strings.TrimSpace(util.TempDir) == "" {+ return "", errors.New("temporary directory is not initialized")+ }++ openID, err := newManagedEncryptedExportID()+ if err != nil {+ return "", err+ }+ tempDir := filepath.Join(util.TempDir, "export", boxID, "asset-open", openID)+ if err = os.MkdirAll(tempDir, 0700); err != nil {+ return "", err+ }+ cleanup := true+ defer func() {+ if cleanup {+ _ = os.RemoveAll(tempDir)+ }+ }()++ source, err := filelock.OpenFile(assetAbsPath, os.O_RDONLY, 0)+ if err != nil {+ return "", err+ }+ sourceOpen := true+ defer func() {+ if sourceOpen {+ _ = filelock.CloseFile(source)+ }+ }()++ payloadPath := filepath.Join(tempDir, "payload")+ destination, err := os.OpenFile(payloadPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)+ if err != nil {+ return "", err+ }+ originalName, decryptErr := DecryptAssetToWriter(boxID, filepath.Base(assetAbsPath), dek, source, destination)+ sourceCloseErr := filelock.CloseFile(source)+ sourceOpen = false+ destinationCloseErr := destination.Close()+ if decryptErr != nil {+ return "", decryptErr+ }+ if sourceCloseErr != nil {+ return "", sourceCloseErr+ }+ if destinationCloseErr != nil {+ return "", destinationCloseErr+ }++ originalName = util.FilterFileName(filepath.Base(originalName))+ if originalName == "" || originalName == "." {+ originalName = filepath.Base(assetAbsPath)+ }+ ret = filepath.Join(tempDir, originalName)+ if ret != payloadPath {+ if err = os.Rename(payloadPath, ret); err != nil {+ return "", err+ }+ }+ if err = os.Chmod(ret, 0600); err != nil {+ return "", err+ }+ cleanup = false+ return ret, nil+}diff --git a/kernel/model/asset_open_test.go b/kernel/model/asset_open_test.gonew file mode 100644index 0000000000..b3665017f9--- /dev/null+++ b/kernel/model/asset_open_test.go@@ -0,0 +1,112 @@+package model++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/gulu"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPrepareAssetForOpen(t *testing.T) {+ originalWorkspaceDir := util.WorkspaceDir+ originalDataDir := util.DataDir+ originalTempDir := util.TempDir+ originalConf := Conf+ workspaceDir := t.TempDir()+ util.WorkspaceDir = workspaceDir+ util.DataDir = filepath.Join(workspaceDir, "data")+ util.TempDir = filepath.Join(workspaceDir, "temp")+ Conf = NewAppConf()+ Conf.Editor = conf.NewEditor()+ Conf.Editor.VirtualBlockRef = false+ boxID := "20260801120000-assetop"+ defer func() {+ LockBox(boxID)+ util.WorkspaceDir = originalWorkspaceDir+ util.DataDir = originalDataDir+ util.TempDir = originalTempDir+ Conf = originalConf+ }()++ plainAssetPath := filepath.Join(util.DataDir, "assets", "plain.png")+ if err := os.MkdirAll(filepath.Dir(plainAssetPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(plainAssetPath, []byte("plain image"), 0600); err != nil {+ t.Fatal(err)+ }+ preparedPlainPath, err := PrepareAssetForOpen("assets/plain.png")+ if err != nil {+ t.Fatal(err)+ }+ if preparedPlainPath != plainAssetPath {+ t.Fatalf("plain asset path changed: got %q, want %q", preparedPlainPath, plainAssetPath)+ }++ boxConf := conf.NewBoxConf()+ boxConf.Encrypted = true+ confData, err := gulu.JSON.MarshalIndentJSON(boxConf, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ if err = os.MkdirAll(filepath.Dir(confPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(confPath, confData, 0600); err != nil {+ t.Fatal(err)+ }++ dek, err := util.GenerateDEK()+ if err != nil {+ t.Fatal(err)+ }+ setDEKForTest(boxID, dek)+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)+ diskName := "asset-20260801120001-abcdefg.png"+ originalName := "机密图片.png"+ plaintext := []byte("encrypted image")+ ciphertext, err := EncryptAsset(boxID, diskName, originalName, dek, plaintext)+ if err != nil {+ t.Fatal(err)+ }+ encryptedAssetPath := filepath.Join(util.DataDir, boxID, "assets", diskName)+ if err = os.MkdirAll(filepath.Dir(encryptedAssetPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(encryptedAssetPath, ciphertext, 0600); err != nil {+ t.Fatal(err)+ }++ preparedEncryptedPath, err := PrepareAssetForOpen("assets/" + diskName + "?box=" + boxID)+ if err != nil {+ t.Fatal(err)+ }+ wantTempRoot := filepath.Join(util.TempDir, "export", boxID, "asset-open")+ if rel, relErr := filepath.Rel(wantTempRoot, preparedEncryptedPath); relErr != nil || rel == ".." ||+ strings.HasPrefix(rel, ".."+string(filepath.Separator)) {+ t.Fatalf("prepared encrypted asset escaped its temporary root: %q", preparedEncryptedPath)+ }+ if filepath.Base(preparedEncryptedPath) != originalName {+ t.Fatalf("prepared encrypted asset name: got %q, want %q", filepath.Base(preparedEncryptedPath), originalName)+ }+ preparedContent, err := os.ReadFile(preparedEncryptedPath)+ if err != nil {+ t.Fatal(err)+ }+ if string(preparedContent) != string(plaintext) {+ t.Fatalf("prepared encrypted asset content: got %q, want %q", preparedContent, plaintext)+ }++ LockBox(boxID)+ if _, err = os.Stat(preparedEncryptedPath); !os.IsNotExist(err) {+ t.Fatalf("locking the notebook should remove the prepared asset: %v", err)+ }+ if _, err = PrepareAssetForOpen("assets/" + diskName + "?box=" + boxID); err == nil {+ t.Fatal("locked encrypted asset was prepared")+ }+}diff --git a/kernel/model/import.go b/kernel/model/import.goindex 29d15cd333..4afd10eeaf 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -1006,7 +1006,11 @@ func replaceAssetName(path string, assetNameMap map[string]string, boxSuffix strpath = path[:idx] + diskName + path[idx+len(original):]// 替换后如果没有 box query,补上if boxSuffix != "" && !strings.Contains(path, "?box=") {- path += boxSuffix+ if strings.Contains(path, "?") {+ path += "&" + strings.TrimPrefix(boxSuffix, "?")+ } else {+ path += boxSuffix+ }}}}diff --git a/kernel/model/import_test.go b/kernel/model/import_test.goindex 8f73dd6b3a..afbbda4f8b 100644--- a/kernel/model/import_test.go+++ b/kernel/model/import_test.go@@ -38,3 +38,31 @@ func TestIsSYNotebookExport(t *testing.T) {})}}++func TestReplaceAssetNamePreservesExistingQuery(t *testing.T) {+ assetNameMap := map[string]string{"document.pdf": "encrypted.pdf"}+ boxSuffix := "?box=20260731190414-j45dgmm"+ tests := []struct {+ path string+ want string+ }{+ {+ path: "assets/document.pdf",+ want: "assets/encrypted.pdf?box=20260731190414-j45dgmm",+ },+ {+ path: "assets/document.pdf?page=2",+ want: "assets/encrypted.pdf?page=2&box=20260731190414-j45dgmm",+ },+ {+ path: "assets/document.pdf?box=20260731190414-j45dgmm",+ want: "assets/encrypted.pdf?box=20260731190414-j45dgmm",+ },+ }++ 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)+ }+ }+}