Skip to content

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

:bug: Preview unreferenced notebook assets correctly https://github.com/siyuan-note/siyuan/issues/18900

Danield2085a754d15
diff --git a/app/src/asset/previewPath.ts b/app/src/asset/previewPath.ts
new file mode 100644
index 0000000000..19e9a408f3
--- /dev/null
+++ b/app/src/asset/previewPath.ts
@@ -0,0 +1,6 @@
+export const getAssetsPreviewPath = (pathString: string, dataPath?: string) => {
+ if (!dataPath) {
+ return pathString;
+ }
+ return `${pathString}${pathString.includes("?") ? "&" : "?"}dataPath=${encodeURIComponent(dataPath)}`;
+};
diff --git a/app/src/asset/renderAssets.test.ts b/app/src/asset/renderAssets.test.ts
new file mode 100644
index 0000000000..1c4b51a948
--- /dev/null
+++ b/app/src/asset/renderAssets.test.ts
@@ -0,0 +1,21 @@
+import * as assert from "node:assert/strict";
+import test from "node:test";
+import {getAssetsPreviewPath} from "./previewPath";
+
+test("keeps regular asset preview paths unchanged", () => {
+ assert.equal(getAssetsPreviewPath("assets/image.png"), "assets/image.png");
+});
+
+test("adds an exact data path for notebook and document asset previews", () => {
+ assert.equal(
+ getAssetsPreviewPath("assets/video.mp4", "20260821000000-abcdefg/20260821000001-hijklmn/assets/video.mp4"),
+ "assets/video.mp4?dataPath=20260821000000-abcdefg%2F20260821000001-hijklmn%2Fassets%2Fvideo.mp4"
+ );
+});
+
+test("preserves existing asset query parameters", () => {
+ assert.equal(
+ getAssetsPreviewPath("assets/image.png?thumbnail=256", "20260821000000-abcdefg/assets/image.png"),
+ "assets/image.png?thumbnail=256&dataPath=20260821000000-abcdefg%2Fassets%2Fimage.png"
+ );
+});
diff --git a/app/src/asset/renderAssets.ts b/app/src/asset/renderAssets.ts
index 681fe51912..c1a24e1e49 100644
--- a/app/src/asset/renderAssets.ts
+++ b/app/src/asset/renderAssets.ts
@@ -7,18 +7,20 @@ import * as dayjs from "dayjs";
import {escapeAttr} from "../util/escape";
import {getHTMLAssetIFrameSrc, isHTMLFilePath} from "./html";
import {isBrowserRenderableImagePath} from "../util/imageURL";
+import {getAssetsPreviewPath} from "./previewPath";
-export const renderAssetsPreview = (pathString: string) => {
+export const renderAssetsPreview = (pathString: string, dataPath?: string) => {
if (!pathString) {
return "";
}
const type = getAssetExtension(pathString).toLowerCase();
+ const previewPath = escapeAttr(getAssetsPreviewPath(pathString, dataPath));
if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {
- return `<img style="max-height: 100%" src="${pathString}">`;
+ return `<img style="max-height: 100%" src="${previewPath}">`;
} else if (Constants.SIYUAN_ASSETS_AUDIO.includes(type)) {
- return `<audio style="max-width: 100%" controls="controls" src="${pathString}"></audio>`;
+ return `<audio style="max-width: 100%" controls="controls" src="${previewPath}"></audio>`;
} else if (Constants.SIYUAN_ASSETS_VIDEO.includes(type)) {
- return `<video style="max-width: 100%" controls="controls" src="${pathString}"></video>`;
+ return `<video style="max-width: 100%" controls="controls" src="${previewPath}"></video>`;
} else {
return pathString;
}
diff --git a/app/src/config/assets.ts b/app/src/config/assets.ts
index 546652fcf2..8549e9c4bc 100644
--- a/app/src/config/assets.ts
+++ b/app/src/config/assets.ts
@@ -309,7 +309,7 @@ const assets = {
if (liElement && liElement.getAttribute("data-item") !== assetsListElement.nextElementSibling.getAttribute("data-item")) {
const item = liElement.getAttribute("data-item");
assetsListElement.nextElementSibling.setAttribute("data-item", item);
- assetsListElement.nextElementSibling.innerHTML = renderAssetsPreview(item);
+ assetsListElement.nextElementSibling.innerHTML = renderAssetsPreview(liElement.getAttribute("data-path"), item);
}
});
fetchPost("/api/asset/getUnusedAssets", {}, response => {
@@ -319,6 +319,7 @@ const assets = {
_renderList: (data: {
item: string,
name: string,
+ path?: string,
blockIDs?: string[]
}[], element: Element, type: "unRefAV" | "unrefAssets" | "lostAssets") => {
let html = "";
@@ -341,7 +342,7 @@ const assets = {
<svg><use xlink:href="#iconPictureInPicture"></use></svg>
</span>`
: "";
- html += `<li data-tab-type="${type}" data-item="${item.item}" class="b3-list-item${mobile ? "" : " b3-list-item--hide-action"}">
+ html += `<li data-tab-type="${type}" data-item="${escapeAttr(item.item)}" data-path="${escapeAttr(item.path || item.item)}" class="b3-list-item${mobile ? "" : " b3-list-item--hide-action"}">
<span class="b3-list-item__text">${escapeHtml(item.name || item.item)}</span>
${blockPopoverHTML}
<span data-type="copy" class="ariaLabel b3-list-item__action" aria-label="${type === "unRefAV" ? window.siyuan.languages.copyMirror : window.siyuan.languages.copy}">
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 1adfd9b05d..f674bf453e 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -1693,6 +1693,7 @@ func replaceAttributeViewAssetPath(avJSONPath, avID, oldPath, newPath string) (u
type UnusedItem struct {
Item string `json:"item"`
Name string `json:"name"`
+ Path string `json:"path,omitempty"`
BlockIDs []string `json:"blockIDs,omitempty"`
ModTime time.Time `json:"-"`
AbsPath string `json:"-"`
@@ -1897,7 +1898,7 @@ func UnusedAssets(sorted bool) (ret []*UnusedItem) {
}
}
- ret = append(ret, &UnusedItem{Item: p, Name: name, ModTime: modTime, AbsPath: assetAbsPath})
+ ret = append(ret, &UnusedItem{Item: p, Name: name, Path: dest, ModTime: modTime, AbsPath: assetAbsPath})
}
if sorted {
diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.go
index ed5a373355..2eb8665d35 100644
--- a/kernel/model/publish_access.go
+++ b/kernel/model/publish_access.go
@@ -474,7 +474,8 @@ func CheckPublishAuthCookie(c *gin.Context, ID string, password string) bool {
return err == nil && authCookie.Value == util.SHA256Hash([]byte(ID+password))
}
-func assetPathFromDataRelativePath(relPath string) (assetPath, boxID string, ok bool) {
+// AssetPathFromDataRelativePath 从 data 相对路径提取文档中使用的资源路径和笔记本 ID。
+func AssetPathFromDataRelativePath(relPath string) (assetPath, boxID string, ok bool) {
pathParts := strings.Split(relPath, "/")
if 1 < len(pathParts) && pathParts[0] == "assets" {
return strings.Join(pathParts, "/"), "", true
@@ -510,7 +511,7 @@ func CheckAbsPathAccessableByPublishAccess(c *gin.Context, absPath string, publi
return true
}
- if assetPath, box, ok := assetPathFromDataRelativePath(relPath); ok {
+ if assetPath, box, ok := AssetPathFromDataRelativePath(relPath); ok {
return checkAssetPathAccessableByPublishAccess(c, publishAccess, assetPath, box)
}
diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.go
index 0f67ab1da8..49a762175e 100644
--- a/kernel/model/publish_access_test.go
+++ b/kernel/model/publish_access_test.go
@@ -86,9 +86,9 @@ func TestAssetPathFromDataRelativePath(t *testing.T) {
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
- assetPath, actualBoxID, ok := assetPathFromDataRelativePath(test.relativePath)
+ assetPath, actualBoxID, ok := AssetPathFromDataRelativePath(test.relativePath)
if assetPath != test.wantAssetPath || actualBoxID != test.wantBoxID || ok != test.wantOK {
- t.Fatalf("assetPathFromDataRelativePath(%q) = [%q, %q, %v], want [%q, %q, %v]",
+ t.Fatalf("AssetPathFromDataRelativePath(%q) = [%q, %q, %v], want [%q, %q, %v]",
test.relativePath, assetPath, actualBoxID, ok, test.wantAssetPath, test.wantBoxID, test.wantOK)
}
})
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index f4da39b900..7928466626 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -930,6 +930,27 @@ func isValidResolvedAssetPath(assetAbsPath, requestBoxID string) bool {
return err == nil && filepath.Clean(validatedAbsPath) == filepath.Clean(assetAbsPath)
}
+func resolveAssetRequestPath(cleanPath, boxID, dataPath string) (string, error) {
+ if dataPath != "" {
+ if boxID != "" {
+ return "", errors.New("box and dataPath cannot be used together")
+ }
+ dataRelativePath, assetAbsPath, err := model.ResolveDataAssetPath(dataPath)
+ if err != nil {
+ return "", err
+ }
+ assetPath, _, ok := model.AssetPathFromDataRelativePath(dataRelativePath)
+ if !ok || assetPath != cleanPath {
+ return "", fmt.Errorf("asset path [%s] does not match data path [%s]", cleanPath, dataPath)
+ }
+ return assetAbsPath, nil
+ }
+ if boxID != "" {
+ return model.GetAssetAbsPathInBox(cleanPath, boxID)
+ }
+ return model.GetAssetAbsPath(cleanPath)
+}
+
func serveAssets(ginServer *gin.Engine) {
ginServer.POST("/upload", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, model.Upload)
@@ -954,15 +975,14 @@ func serveAssets(ginServer *gin.Engine) {
return
}
- // 解析 box 查询参数,加密 box 资源按 box 内精确查找(不全局搜索)
+ // dataPath 用于精确预览普通笔记本或文档下的未引用资源,仅管理员可用
boxID := context.Query("box")
- var p string
- var err error
- if boxID != "" {
- p, err = model.GetAssetAbsPathInBox(cleanPath, boxID)
- } else {
- p, err = model.GetAssetAbsPath(cleanPath)
+ dataPath := context.Query("dataPath")
+ if dataPath != "" && !model.IsAdminRoleContext(context) {
+ context.Status(http.StatusForbidden)
+ return
}
+ p, err := resolveAssetRequestPath(cleanPath, boxID, dataPath)
if err != nil || p == "" {
context.Status(http.StatusNotFound)
return
diff --git a/kernel/server/serve_assets_test.go b/kernel/server/serve_assets_test.go
index 214148c0ec..529f0b9b0b 100644
--- a/kernel/server/serve_assets_test.go
+++ b/kernel/server/serve_assets_test.go
@@ -13,6 +13,7 @@ import (
"net/http"
"net/http/httptest"
"os"
+ "path"
"path/filepath"
"runtime"
"strings"
@@ -150,6 +151,68 @@ func TestIsValidResolvedAssetPath(t *testing.T) {
}
}
+func TestResolveAssetRequestPathByDataPath(t *testing.T) {
+ originalDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = originalDataDir
+ })
+
+ const (
+ boxID = "20260821000000-abcdefg"
+ docID = "20260821000001-hijklmn"
+ encryptedBoxID = "20260821000002-opqrstu"
+ )
+ writeFile := func(filePath string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filePath, []byte("asset"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writeFile(filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json"))
+ writeFile(filepath.Join(util.DataDir, encryptedBoxID, ".siyuan", "conf.json"))
+ if err := os.WriteFile(filepath.Join(util.DataDir, encryptedBoxID, ".siyuan", "conf.json"),
+ []byte(`{"encrypted":true}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+ documentAssetPath := filepath.Join(util.DataDir, boxID, docID, "assets", "video.mp4")
+ writeFile(documentAssetPath)
+ encryptedAssetPath := filepath.Join(util.DataDir, encryptedBoxID, "assets", "encrypted.mp4")
+ writeFile(encryptedAssetPath)
+
+ dataPath := path.Join(boxID, docID, "assets", "video.mp4")
+ resolvedPath, err := resolveAssetRequestPath("assets/video.mp4", "", dataPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resolvedPath != documentAssetPath {
+ t.Fatalf("resolve asset by data path: got %q, want %q", resolvedPath, documentAssetPath)
+ }
+
+ invalidRequests := []struct {
+ name string
+ assetPath string
+ boxID string
+ dataPath string
+ }{
+ {name: "mismatched asset path", assetPath: "assets/other.mp4", dataPath: dataPath},
+ {name: "box and data path", assetPath: "assets/video.mp4", boxID: boxID, dataPath: dataPath},
+ {name: "non asset data path", assetPath: "assets/document.sy", dataPath: path.Join(boxID, docID+".sy")},
+ {name: "encrypted asset data path", assetPath: "assets/encrypted.mp4",
+ dataPath: path.Join(encryptedBoxID, "assets", "encrypted.mp4")},
+ }
+ for _, test := range invalidRequests {
+ t.Run(test.name, func(t *testing.T) {
+ if _, resolveErr := resolveAssetRequestPath(test.assetPath, test.boxID, test.dataPath); resolveErr == nil {
+ t.Fatalf("resolveAssetRequestPath(%q, %q, %q) should fail", test.assetPath, test.boxID, test.dataPath)
+ }
+ })
+ }
+}
+
func TestSecureAssetContentHeadersForcesAttachmentOnScriptCapableAssets(t *testing.T) {
// 可执行脚本的资产必须强制附件下载,禁止浏览器同源内联渲染
// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-mjf3-jwmf-r6wf