An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Add box-aware AV routing and cache, box-scoped asset resolution in export/API, separate AAD for asset name mapping, reject directory assets in encrypted boxes, harden /assets route boundary https://github.com/siyuan-note/siyuan/issues/18034
Danielc7264f8e2e7c
diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex efdb5680dc..2687a8aeff 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -46,7 +46,7 @@ func statAsset(c *gin.Context) {var p stringif strings.HasPrefix(path, "assets/") {var err error- p, err = model.GetAssetAbsPath(path)+ p, err = model.GetAssetAbsPathInBox(path, "")if err != nil {ret.Code = 1return@@ -360,7 +360,7 @@ func getFileAnnotation(c *gin.Context) {func resolveFileAnnotationAbsPath(assetRelPath string) (ret string, err error) {filePath := strings.TrimSuffix(assetRelPath, ".sya")- absPath, err := model.GetAssetAbsPath(filePath)+ absPath, err := model.GetAssetAbsPathInBox(filePath, "")if err != nil {return}@@ -431,13 +431,19 @@ func resolveAssetPath(c *gin.Context) {}path := arg["path"].(string)- p, err := model.GetAssetAbsPath(path)+ p, err := model.GetAssetAbsPathInBox(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 d4b7ab9c68..f2fff973fd 100644--- a/kernel/api/clipboard.go+++ b/kernel/api/clipboard.go@@ -70,7 +70,7 @@ func writeFilePath(c *gin.Context) {return}- absPath, err := model.GetAssetAbsPath(pathArg)+ absPath, err := model.GetAssetAbsPathInBox(pathArg, "")if err != nil {logging.LogErrorf("get asset [%s] abs path failed: %s", pathArg, err)ret.Code = -1@@ -78,6 +78,12 @@ 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/api/file.go b/kernel/api/file.goindex 7e66fd7a03..b9ae89c216 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -386,7 +386,7 @@ func copyFile(c *gin.Context) {return}- src, err := model.GetAssetAbsPath(src)+ src, err := model.GetAssetAbsPathInBox(src, "")if err != nil {logging.LogErrorf("get asset [%s] abs path failed: %s", src, err)ret.Code = -1diff --git a/kernel/av/av.go b/kernel/av/av.goindex 5e9b1ff076..485d40f5de 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -501,16 +501,35 @@ func IsAttributeViewExist(avID string) bool {func ParseAttributeView(avID string) (ret *AttributeView, err error) {// 加密笔记本的 AV 定义存笔记本级路径,通过 fallback 自动查找并解密- avJSONPath, _ := FindAttributeViewPath(avID)+ avJSONPath, boxID := FindAttributeViewPath(avID)if avJSONPath == "" {// 文件不存在,可能是首次创建,按全局路径返回(由调用方处理)avJSONPath = GetAttributeViewDataPath(avID)- return ParseAttributeViewByPath(avJSONPath)+ return parseAttributeViewByPathInBox(avJSONPath, "")}- return ParseAttributeViewByPath(avJSONPath)+ if boxID != "" {+ SetAVBoxID(avID, boxID)+ }+ return parseAttributeViewByPathInBox(avJSONPath, boxID)+}++func ParseAttributeViewInBox(avID, boxID string) (ret *AttributeView, err error) {+ if boxID != "" {+ SetAVBoxID(avID, boxID)+ }+ avJSONPath, avBoxID := FindAttributeViewPathInBox(avID, boxID)+ if avJSONPath == "" {+ avJSONPath = attributeViewDataPathByBox(avID, boxID)+ avBoxID = boxID+ }+ return parseAttributeViewByPathInBox(avJSONPath, avBoxID)}func ParseAttributeViewByPath(avJSONPath string) (ret *AttributeView, err error) {+ return parseAttributeViewByPathInBox(avJSONPath, avBoxIDFromPath(avJSONPath))+}++func parseAttributeViewByPathInBox(avJSONPath, boxID string) (ret *AttributeView, err error) {if !filelock.IsExist(avJSONPath) {err = ErrViewNotFoundreturn@@ -520,7 +539,7 @@ func ParseAttributeViewByPath(avJSONPath string) (ret *AttributeView, err error)avID = strings.TrimSuffix(avID, filepath.Ext(avID))var data []byte- if cached, ok := cache.GetAVData(avID); ok {+ if cached, ok := cache.GetAVDataInBox(avID, boxID); ok {data = cached} else {var readErr error@@ -530,14 +549,14 @@ func ParseAttributeViewByPath(avJSONPath string) (ret *AttributeView, err error)return}// 加密笔记本的 AV 定义是密文,按路径反查 boxID 后解密- if boxID := avBoxIDFromPath(avJSONPath); boxID != "" {- data, readErr = decryptAVData(boxID, avID, data)+ if boxID != "" {+ data, readErr = decryptAVData(boxID, avID, data)if readErr != nil {logging.LogErrorf("decrypt attribute view [%s] failed: %s", avID, readErr)return}}- cache.SetAVData(avID, data)+ cache.SetAVDataInBox(avID, boxID, data)}ret = &AttributeView{RenderedViewables: map[string]Viewable{}}@@ -673,7 +692,7 @@ func SaveAttributeView(av *AttributeView) (err error) {// 加密笔记本的首次创建由 handler 层通过 SetAVBoxID 预设路径avJSONPath = GetAttributeViewDataPath(av.ID)}- if cachedData, ok := cache.GetAVData(av.ID); ok {+ if cachedData, ok := cache.GetAVDataInBox(av.ID, avBoxID); ok {if len(cachedData) == len(data) && bytes.Equal(cachedData, data) {return}@@ -681,10 +700,10 @@ func SaveAttributeView(av *AttributeView) (err error) {if diskData, readErr := filelock.ReadFile(avJSONPath); nil == readErr {// 加密笔记本的磁盘数据是密文,需先解密再比对if avBoxID != "" {- diskData, _ = decryptAVData(avBoxID, av.ID, diskData)+ diskData, _ = decryptAVData(avBoxID, av.ID, diskData)}if len(diskData) == len(data) && bytes.Equal(diskData, data) {- cache.SetAVData(av.ID, data)+ cache.SetAVDataInBox(av.ID, avBoxID, data)return}}@@ -692,8 +711,8 @@ func SaveAttributeView(av *AttributeView) (err error) {// 加密笔记本的数据需加密后再写盘writeData := data- if avBoxID != "" {- writeData, err = encryptAVData(avBoxID, av.ID, data)+ if avBoxID != "" {+ writeData, err = encryptAVData(avBoxID, av.ID, data)if err != nil {logging.LogErrorf("encrypt attribute view [%s] failed: %s", av.ID, err)return@@ -711,7 +730,7 @@ func SaveAttributeView(av *AttributeView) (err error) {}}- cache.SetAVData(av.ID, data)+ cache.SetAVDataInBox(av.ID, avBoxID, data)if util.ExceedLargeFileWarningSize(len(data)) {msg := fmt.Sprintf(util.Langs[util.Lang][268], av.Name+" "+filepath.Base(avJSONPath), util.LargeFileWarningSize)diff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.goindex e3631deba6..6a23efb06d 100644--- a/kernel/av/encrypted_hook.go+++ b/kernel/av/encrypted_hook.go@@ -91,6 +91,21 @@ func FindAttributeViewPath(avID string) (path string, boxID string) {return "", ""}+// FindAttributeViewPathInBox 只在指定 box 内查找 AV 定义,避免加密上下文落回全局路径。+func FindAttributeViewPathInBox(avID, boxID string) (path string, retBoxID string) {+ if pendingBoxID := GetAVBoxID(avID); pendingBoxID != "" {+ if pendingBoxID == boxID {+ return attributeViewDataPathByBox(avID, pendingBoxID), pendingBoxID+ }+ return "", boxID+ }+ avPath := attributeViewDataPathByBox(avID, boxID)+ if filelock.IsExist(avPath) {+ return avPath, boxID+ }+ return "", boxID+}+// readAttributeViewData 按 fallback 逻辑读取 AV 定义数据(自动解密)。func readAttributeViewData(avID string) ([]byte, error) {path, boxID := FindAttributeViewPath(avID)@@ -117,6 +132,25 @@ func ReadAttributeViewData(avID string) ([]byte, error) {return readAttributeViewData(avID)}+// ReadAttributeViewDataInBox 只读取指定 box 内的 AV 定义明文。+func ReadAttributeViewDataInBox(avID, boxID string) ([]byte, error) {+ path, retBoxID := FindAttributeViewPathInBox(avID, boxID)+ if path == "" {+ return nil, nil+ }+ data, err := filelock.ReadFile(path)+ if err != nil {+ return nil, err+ }+ if retBoxID != "" {+ data, err = decryptAVData(retBoxID, avID, data)+ if err != nil {+ return nil, err+ }+ }+ return data, nil+}+// writeAttributeViewData 写入 AV 定义数据(自动加密)。// boxID 为空时写全局路径(普通 box),非空时写加密笔记本路径并加密。func writeAttributeViewData(avID, boxID string, data []byte) error {@@ -168,9 +202,9 @@ func readMirrorBlocks(boxID string) (ret map[string][]string) {logging.LogErrorf("read attribute view blocks failed: %s", err)return}- if boxID != "" {- // 加密笔记本的镜像索引是密文,解密后再反序列化- dec, decErr := decryptAVData(boxID, "mirror", data)+ if boxID != "" {+ // 加密笔记本的镜像索引是密文,解密后再反序列化+ dec, decErr := decryptAVData(boxID, "mirror", data)if decErr != nil {logging.LogErrorf("decrypt attribute view blocks failed: %s", decErr)return@@ -195,9 +229,9 @@ func writeMirrorBlocks(boxID string, data map[string][]string) error {if err != nil {return err}- if boxID != "" {- // 加密笔记本的镜像索引写入前加密- enc, encErr := encryptAVData(boxID, "mirror", raw)+ if boxID != "" {+ // 加密笔记本的镜像索引写入前加密+ enc, encErr := encryptAVData(boxID, "mirror", raw)if encErr != nil {return encErr}@@ -238,7 +272,7 @@ func encryptAVData(boxID, avID string, data []byte) ([]byte, error) {return data, nil // 非加密 box}avKey := util.DeriveSubKey(dek, "siyuan/av")- aad := "siyuan:v1:av:" + boxID + ":" + avID+ aad := avAAD(boxID, avID)return util.EncryptWithAAD(avKey, data, []byte(aad))}@@ -254,10 +288,21 @@ func decryptAVData(boxID, avID string, data []byte) ([]byte, error) {return data, nil // 非加密 box}avKey := util.DeriveSubKey(dek, "siyuan/av")- aad := "siyuan:v1:av:" + boxID + ":" + avID+ aad := avAAD(boxID, avID)return util.DecryptWithAAD(avKey, data, []byte(aad))}+func avAAD(boxID, avID string) string {+ switch avID {+ case "mirror":+ return "siyuan:v1:av-mirror:" + boxID+ case "relation":+ return "siyuan:v1:av-relation:" + boxID+ default:+ return "siyuan:v1:av:" + boxID + ":" + avID+ }+}+// EncryptAVData 是 encryptAVData 的导出版本,供 model 层(导入/复制数据库等)统一加密 AV 定义。func EncryptAVData(boxID, avID string, data []byte) ([]byte, error) {return encryptAVData(boxID, avID, data)diff --git a/kernel/cache/av.go b/kernel/cache/av.goindex 77abaaac2d..dce61a9e58 100644--- a/kernel/cache/av.go+++ b/kernel/cache/av.go@@ -17,6 +17,8 @@package cacheimport (+ "sync"+"github.com/dgraph-io/ristretto")@@ -26,8 +28,19 @@ var avCache, _ = ristretto.NewCache(&ristretto.Config{BufferItems: 64,})+var avCacheKeys = map[string]map[string]struct{}{}+var avCacheKeysLock sync.Mutex++func avCacheKey(avID, boxID string) string {+ return boxID + "\x00" + avID+}+func GetAVData(avID string) (raw []byte, ok bool) {- v, _ := avCache.Get(avID)+ return GetAVDataInBox(avID, "")+}++func GetAVDataInBox(avID, boxID string) (raw []byte, ok bool) {+ v, _ := avCache.Get(avCacheKey(avID, boxID))if nil == v {return nil, false}@@ -35,16 +48,56 @@ func GetAVData(avID string) (raw []byte, ok bool) {}func SetAVData(avID string, raw []byte) {+ SetAVDataInBox(avID, "", raw)+}++func SetAVDataInBox(avID, boxID string, raw []byte) {if raw == nil {return}- avCache.Set(avID, raw, int64(len(raw)))+ key := avCacheKey(avID, boxID)+ avCache.Set(key, raw, int64(len(raw)))++ avCacheKeysLock.Lock()+ defer avCacheKeysLock.Unlock()+ keys := avCacheKeys[avID]+ if keys == nil {+ keys = map[string]struct{}{}+ avCacheKeys[avID] = keys+ }+ keys[key] = struct{}{}+}++func RemoveAVDataInBox(avID, boxID string) {+ key := avCacheKey(avID, boxID)+ avCache.Del(key)++ avCacheKeysLock.Lock()+ defer avCacheKeysLock.Unlock()+ if keys := avCacheKeys[avID]; keys != nil {+ delete(keys, key)+ if len(keys) == 0 {+ delete(avCacheKeys, avID)+ }+ }}func RemoveAVData(avID string) {+ avCacheKeysLock.Lock()+ keys := avCacheKeys[avID]+ delete(avCacheKeys, avID)+ avCacheKeysLock.Unlock()+avCache.Del(avID)+ avCache.Del(avCacheKey(avID, ""))+ for key := range keys {+ avCache.Del(key)+ }}func ClearAVCache() {+ avCacheKeysLock.Lock()+ avCacheKeys = map[string]map[string]struct{}{}+ avCacheKeysLock.Unlock()avCache.Clear()}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 7d3817d6d4..dba1cfb413 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -52,15 +52,19 @@ import ()func GetAssetImgSize(assetPath string) (width, height int) {- absPath, err := GetAssetAbsPath(assetPath)+ return GetAssetImgSizeInBox(assetPath, "")+}++func GetAssetImgSizeInBox(assetPath, boxID string) (width, height int) {+ data, err := ReadAssetBytesInBox(boxID, assetPath)if err != nil {logging.LogErrorf("get asset [%s] abs path failed: %s", assetPath, err)return}- img, err := imaging.Open(absPath)+ img, err := imaging.Decode(bytes.NewReader(data))if err != nil {- logging.LogErrorf("open asset image [%s] failed: %s", absPath, err)+ logging.LogErrorf("open asset image [%s] failed: %s", assetPath, err)return}@@ -632,18 +636,46 @@ func GetAssetAbsPath(relativePath string) (string, error) {return GetAssetAbsPathWithOpt(relativePath, false)}-// GetAssetAbsPathInBox 在指定 box 内解析资源绝对路径,不进行全局遍历。-// boxID 为空时退化为全局搜索 GetAssetAbsPathWithOpt(..., true)。-// 加密 box 直接从 <boxID>/assets/ 查找,不依赖后缀匹配。-func GetAssetAbsPathInBox(relativePath, boxID string) (string, error) {+// AssetPathWithoutQuery 返回去掉查询参数后的资源路径,用于复制到导出目录等磁盘路径场景。+func AssetPathWithoutQuery(relativePath string) string {relativePath = strings.TrimSpace(relativePath)if idx := strings.Index(relativePath, "?"); idx >= 0 {relativePath = relativePath[:idx]}- relativePath = filepath.ToSlash(relativePath)+ return filepath.ToSlash(relativePath)+}++func assetPathAndBox(relativePath, defaultBoxID string) (cleanPath, boxID string) {+ relativePath = strings.TrimSpace(relativePath)+ boxID = defaultBoxID+ if idx := strings.Index(relativePath, "?"); idx >= 0 {+ query := relativePath[idx+1:]+ relativePath = relativePath[:idx]+ if values, err := url.ParseQuery(query); err == nil {+ if queryBoxID := strings.TrimSpace(values.Get("box")); queryBoxID != "" {+ boxID = queryBoxID+ }+ }+ }+ cleanPath = filepath.ToSlash(relativePath)+ return+}++// GetAssetAbsPathInBox 在指定 box 内解析资源绝对路径,不进行全局遍历。+// boxID 为空且路径没有 box 查询参数时只解析普通/全局资源,不遍历加密 box。+// 加密 box 直接从 <boxID>/assets/ 查找,不依赖后缀匹配。+func GetAssetAbsPathInBox(relativePath, boxID string) (string, error) {+ relativePath, boxID = assetPathAndBox(relativePath, boxID)+ relativePath = path.Clean(relativePath)+ if relativePath == "." || strings.HasPrefix(relativePath, "../") || relativePath == ".." || path.IsAbs(relativePath) {+ return "", fmt.Errorf("[%s] is not an asset path", relativePath)+ }+ if boxID != "" && !ast.IsNodeIDPattern(boxID) {+ return "", fmt.Errorf("[%s] is not a box id", boxID)+ }if boxID == "" {- return GetAssetAbsPathWithOpt(relativePath, true)+ return GetAssetAbsPathWithOpt(relativePath, false)}p := filepath.Join(util.DataDir, boxID, relativePath)@@ -1014,12 +1046,10 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {util.PushEndlessProgress(Conf.Language(110))defer util.PushClearProgress()- if idx := strings.Index(oldPath, "?"); idx >= 0 {- oldPath = oldPath[:idx]- }+ oldCleanPath := AssetPathWithoutQuery(oldPath)// 加密笔记本的资源文件名已脱敏,重命名会破坏映射关系,禁止- if absPath, absErr := GetAssetAbsPath(oldPath); absErr == nil {+ if absPath, absErr := GetAssetAbsPathInBox(oldPath, ""); absErr == nil {if IsEncryptedAssetPath(absPath) {err = errors.New("renaming assets in encrypted notebooks is not supported")return@@ -1028,7 +1058,7 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {newName = strings.TrimSpace(newName)newName = util.FilterUploadFileName(newName)- if path.Base(oldPath) == newName {+ if path.Base(oldCleanPath) == newName {return}if "" == newName {@@ -1040,10 +1070,10 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {return}- newName = util.AssetName(newName+filepath.Ext(oldPath), ast.NewNodeID())- parentDir := path.Dir(oldPath)+ newName = util.AssetName(newName+filepath.Ext(oldCleanPath), ast.NewNodeID())+ parentDir := path.Dir(oldCleanPath)newPath = path.Join(parentDir, newName)- oldAbsPath, getErr := GetAssetAbsPath(oldPath)+ oldAbsPath, getErr := GetAssetAbsPathInBox(oldPath, "")if getErr != nil {logging.LogErrorf("get asset [%s] abs path failed: %s", oldPath, getErr)returndiff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex 06d818108e..0b5d884988 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -1195,6 +1195,18 @@ func DecryptAsset(boxID, diskName string, dek, ciphertext []byte) ([]byte, errorreturn util.DecryptWithAAD(assetKey, ciphertext, []byte(aad))}+func EncryptAssetNameMapping(boxID string, dek, plaintext []byte) ([]byte, error) {+ assetKey := util.DeriveSubKey(dek, "siyuan/asset")+ aad := "siyuan:v1:asset-names:" + boxID+ return util.EncryptWithAAD(assetKey, plaintext, []byte(aad))+}++func DecryptAssetNameMapping(boxID string, dek, ciphertext []byte) ([]byte, error) {+ assetKey := util.DeriveSubKey(dek, "siyuan/asset")+ aad := "siyuan:v1:asset-names:" + boxID+ return util.DecryptWithAAD(assetKey, ciphertext, []byte(aad))+}+// notebookCryptBackupPath 返回加密笔记本的独立 BoxCrypt 备份路径。// 该文件在主 conf.json 丢失时用作"此笔记本是加密笔记本"的标识和降级恢复源。// 与全局 NotebookCrypto 备份(<DataDir>/.siyuan/notebook-crypto-backup.json)配合使用,diff --git a/kernel/model/export.go b/kernel/model/export.goindex 4228235896..0ac1791dbf 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -114,7 +114,16 @@ func ExportCodeBlock(blockID string) (filePath string, err error) {func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {// Database block supports export as CSV https://github.com/siyuan-note/siyuan/issues/10072+ avBoxID := ""+ if bt := treenode.GetBlockTree(blockID); nil != bt && IsEncryptedBox(bt.BoxID) {+ avBoxID = bt.BoxID+ av.SetAVBoxID(avID, avBoxID)+ }+attrView, err := av.ParseAttributeView(avID)+ if avBoxID != "" {+ attrView, err = av.ParseAttributeViewInBox(avID, avBoxID)+ }if err != nil {return}@@ -280,12 +289,12 @@ func ExportAv2CSV(avID, blockID string) (zipPath string, err error) {writer.Flush()for _, asset := range assets {- srcAbsPath, getErr := GetAssetAbsPath(asset)+ srcAbsPath, getErr := GetAssetAbsPathInBox(asset, avBoxID)if getErr != nil {logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, getErr)continue}- targetAbsPath := filepath.Join(exportFolder, asset)+ targetAbsPath := filepath.Join(exportFolder, AssetPathWithoutQuery(asset))if copyErr := copyAssetDecryptIfEncrypted(srcAbsPath, targetAbsPath); copyErr != nil {logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, copyErr)}@@ -919,16 +928,12 @@ func ExportMarkdownHTML(id, savePath string, docx, merge bool) (name, dom stringcontinue}- if strings.Contains(asset, "?") {- asset = asset[:strings.LastIndex(asset, "?")]- }-- srcAbsPath, err := GetAssetAbsPath(asset)+ srcAbsPath, err := GetAssetAbsPathInBox(asset, tree.Box)if err != nil {logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err)continue}- targetAbsPath := filepath.Join(savePath, asset)+ targetAbsPath := filepath.Join(savePath, AssetPathWithoutQuery(asset))if err = copyAssetDecryptIfEncrypted(srcAbsPath, targetAbsPath); err != nil {logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)}@@ -1119,16 +1124,12 @@ func ExportHTML(id, savePath string, pdf, keepFold, merge bool) (name, dom strinassets := getAssetsLinkDests(tree.Root, false)for _, asset := range assets {- if strings.Contains(asset, "?") {- asset = asset[:strings.LastIndex(asset, "?")]- }-- srcAbsPath, err := GetAssetAbsPath(asset)+ srcAbsPath, err := GetAssetAbsPathInBox(asset, tree.Box)if err != nil {logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err)continue}- targetAbsPath := filepath.Join(savePath, asset)+ targetAbsPath := filepath.Join(savePath, AssetPathWithoutQuery(asset))if err = copyAssetDecryptIfEncrypted(srcAbsPath, targetAbsPath); err != nil {logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)}@@ -1330,7 +1331,7 @@ func ProcessPDF(id, p string, merge, removeAssets, watermark bool) (err error) {}processPDFBookmarks(pdfCtx, headings)- processPDFLinkEmbedAssets(pdfCtx, assetDests, removeAssets)+ processPDFLinkEmbedAssets(pdfCtx, assetDests, tree.Box, removeAssets)processPDFWatermark(pdfCtx, watermark)pdfcpuVer := model.VersionStr@@ -1527,10 +1528,10 @@ func processPDFBookmarks(pdfCtx *model.Context, headings []*ast.Node) {// processPDFLinkEmbedAssets 处理资源文件超链接,根据 removeAssets 参数决定是否将资源文件嵌入到 PDF 中。// 导出 PDF 时支持将资源文件作为附件嵌入 https://github.com/siyuan-note/siyuan/issues/7414-func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, removeAssets bool) {+func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, boxID string, removeAssets bool) {var assetAbsPaths []stringfor _, dest := range assetDests {- if absPath, _ := GetAssetAbsPath(dest); "" != absPath {+ if absPath, _ := GetAssetAbsPathInBox(dest, boxID); "" != absPath {assetAbsPaths = append(assetAbsPaths, absPath)}}@@ -1571,6 +1572,7 @@ func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, removlink.URI = strings.ReplaceAll(link.URI, "http://"+util.LocalHost+":"+util.ServerPort+"/", "") // Exporting PDF embedded asset files as attachments fails https://github.com/siyuan-note/siyuan/issues/7414#issuecomment-1704573557link.URI = strings.ReplaceAll(link.URI, "http://"+util.LocalHost+":6806/", "")link.URI, _ = url.PathUnescape(link.URI)+ sourceURI := link.URIif idx := strings.Index(link.URI, "?"); 0 < idx {link.URI = link.URI[:idx]}@@ -1588,18 +1590,33 @@ func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, remov// 移除资源文件夹的话使用内嵌附件- absPath, getErr := GetAssetAbsPath(link.URI)+ absPath, getErr := GetAssetAbsPathInBox(sourceURI, boxID)if nil != getErr {continue}+ embedPath := absPath+ if IsEncryptedAssetPath(absPath) {+ assetBoxID := ExtractBoxIDFromAssetsPath(absPath)+ plain, readErr := ReadAssetBytesInBox(assetBoxID, sourceURI)+ if nil != readErr {+ logging.LogWarnf("read encrypted asset [%s] failed: %s", sourceURI, readErr)+ continue+ }+ embedPath = filepath.Join(util.TempDir, "export", "pdf-assets", gulu.Rand.String(7)+"-"+filepath.Base(AssetPathWithoutQuery(sourceURI)))+ if writeErr := filelock.WriteFile(embedPath, plain); nil != writeErr {+ logging.LogWarnf("write temp embedded asset [%s] failed: %s", embedPath, writeErr)+ continue+ }+ defer os.Remove(embedPath)+ }- ir, newErr := pdfCtx.XRefTable.NewEmbeddedFileStreamDict(absPath)+ ir, newErr := pdfCtx.XRefTable.NewEmbeddedFileStreamDict(embedPath)if nil != newErr {logging.LogWarnf("new embedded file stream dict failed: %s", newErr)continue}- fn := filepath.Base(absPath)+ fn := filepath.Base(AssetPathWithoutQuery(sourceURI))fileSpecDict, newErr := pdfCtx.XRefTable.NewFileSpecDict(fn, fn, "attached by SiYuan", *ir)if nil != newErr {logging.LogWarnf("new file spec dict failed: %s", newErr)@@ -2179,26 +2196,35 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), asset))asset = string(html.DecodeDestination([]byte(asset)))- if strings.Contains(asset, "?") {- asset = asset[:strings.LastIndex(asset, "?")]- }+ cleanAsset := AssetPathWithoutQuery(asset)- if copiedAssets.Contains(asset) {+ copyKey := tree.Box + "\x00" + cleanAsset+ if copiedAssets.Contains(copyKey) {continue}- srcPath := assetPathMap[asset]+ srcPath := ""+ if IsEncryptedBox(tree.Box) {+ srcPath, _ = GetAssetAbsPathInBox(asset, tree.Box)+ }+ if "" == srcPath {+ srcPath = assetPathMap[cleanAsset]+ }+ if "" == srcPath {+ srcPath, _ = GetAssetAbsPathInBox(asset, tree.Box)+ }if "" == srcPath {logging.LogWarnf("get asset [%s] abs path failed", asset)continue}- destPath := filepath.Join(exportDir, asset)+ destPath := filepath.Join(exportDir, cleanAsset)assetErr := copyAssetDecryptIfEncrypted(srcPath, destPath)if nil != assetErr {logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, assetErr)continue}+ copiedAssets.Add(copyKey)if !gulu.File.IsDir(srcPath) && strings.HasSuffix(strings.ToLower(srcPath), ".pdf") {sya := srcPath + ".sya"@@ -2227,6 +2253,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (// 导出数据库 Attribute View export https://github.com/siyuan-note/siyuan/issues/8710exportStorageAvDir := filepath.Join(exportDir, "storage", "av")var avIDs []string+ avBoxes := map[string]string{}for _, tree := range trees {ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering || !n.IsBlock() {@@ -2235,6 +2262,9 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (if ast.NodeAttributeView == n.Type {avIDs = append(avIDs, n.AttributeViewID)+ if IsEncryptedBox(tree.Box) {+ avBoxes[n.AttributeViewID] = tree.Box+ }}avs := n.IALAttr(av.NodeAttrNameAvs)@@ -2243,7 +2273,11 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (}for _, avID := range strings.Split(avs, ",") {- avIDs = append(avIDs, strings.TrimSpace(avID))+ avID = strings.TrimSpace(avID)+ avIDs = append(avIDs, avID)+ if IsEncryptedBox(tree.Box) {+ avBoxes[avID] = tree.Box+ }}return ast.WalkContinue})@@ -2254,7 +2288,7 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (continue}- exportAv(avID, exportStorageAvDir, exportDir, assetPathMap)+ exportAv(avID, avBoxes[avID], exportStorageAvDir, exportDir, assetPathMap)}// 导出闪卡 Export related flashcard data when exporting .sy.zip https://github.com/siyuan-note/siyuan/issues/9372@@ -2345,10 +2379,13 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (return}-func exportAv(avID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) {+func exportAv(avID, boxID, exportStorageAvDir, exportFolder string, assetPathMap map[string]string) {// 用 box-aware 路径解析 + 自动解密读取 AV 定义明文(加密笔记本的 AV 在 <boxID>/storage/av/,// GetAttributeViewDataPath 只查全局路径会漏;filelock.Copy 会拷密文)。avData, readErr := av.ReadAttributeViewData(avID)+ if boxID != "" {+ avData, readErr = av.ReadAttributeViewDataInBox(avID, boxID)+ }if readErr != nil {logging.LogErrorf("read attribute view [%s] failed: %s", avID, readErr)return@@ -2360,6 +2397,9 @@ func exportAv(avID, exportStorageAvDir, exportFolder string, assetPathMap map[st}attrView, err := av.ParseAttributeView(avID)+ if boxID != "" {+ attrView, err = av.ParseAttributeViewInBox(avID, boxID)+ }if err != nil {logging.LogErrorf("parse attribute view [%s] failed: %s", avID, err)return@@ -2374,8 +2414,17 @@ func exportAv(avID, exportStorageAvDir, exportFolder string, assetPathMap map[stcontinue}- destPath := filepath.Join(exportFolder, asset.Content)- srcPath := assetPathMap[asset.Content]+ destPath := filepath.Join(exportFolder, AssetPathWithoutQuery(asset.Content))+ srcPath := ""+ if boxID != "" {+ srcPath, _ = GetAssetAbsPathInBox(asset.Content, boxID)+ }+ if "" == srcPath {+ srcPath = assetPathMap[AssetPathWithoutQuery(asset.Content)]+ }+ if "" == srcPath {+ srcPath, _ = GetAssetAbsPathInBox(asset.Content, boxID)+ }if "" == srcPath {logging.LogWarnf("get asset [%s] abs path failed", asset.Content)continue@@ -3132,7 +3181,7 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,mdTableCell.AppendChild(img)img.SetIALAttr("style", "max-height: 128px;")- width, height := GetAssetImgSize(a.Content)+ width, height := GetAssetImgSizeInBox(a.Content, tree.Box)if height > 128 {img.SetIALAttr("height", "128px")newWidth := int(float64(width) * (128.0 / float64(height)))@@ -3531,7 +3580,7 @@ type refAsFootnotes struct {func processFileAnnotationRef(refID string, n *ast.Node, fileAnnotationRefMode int) ast.WalkStatus {p := refID[:strings.LastIndex(refID, "/")]- absPath, err := GetAssetAbsPath(p)+ absPath, err := GetAssetAbsPathInBox(p, "")if err != nil {logging.LogWarnf("get assets abs path by rel path [%s] failed: %s", p, err)return ast.WalkSkipChildren@@ -3646,17 +3695,16 @@ func exportPandocConvertZip(baseFolderName string, docPaths, defBlockIDs []strin}// 解析导出后的标准 Markdown,汇总 assets+ boxID := tree.Boxtree = parse.Parse("", gulu.Str.ToBytes(md), luteEngine.ParseOptions)removeAssetsID(tree, assetsOldNew, assetsNewOld)newAssets := getAssetsLinkDests(tree.Root, false)for _, newAsset := range newAssets {newAsset = string(html.DecodeDestination([]byte(newAsset)))- if strings.Contains(newAsset, "?") {- newAsset = newAsset[:strings.LastIndex(newAsset, "?")]- }+ cleanNewAsset := AssetPathWithoutQuery(newAsset)- if !strings.HasPrefix(newAsset, "assets/") {+ if !strings.HasPrefix(cleanNewAsset, "assets/") {continue}@@ -3665,19 +3713,32 @@ func exportPandocConvertZip(baseFolderName string, docPaths, defBlockIDs []strin// No assets were exported when exporting Markdown https://github.com/siyuan-note/siyuan/issues/17046spaceEncodedNewAsset := strings.ReplaceAll(newAsset, " ", "%20")oldAsset := assetsNewOld[spaceEncodedNewAsset]+ if "" == oldAsset {+ spaceEncodedCleanNewAsset := strings.ReplaceAll(cleanNewAsset, " ", "%20")+ oldAsset = assetsNewOld[spaceEncodedCleanNewAsset]+ }if "" == oldAsset {logging.LogWarnf("get asset old path for new asset [%s] failed", spaceEncodedNewAsset)continue}spaceDecodedOldAsset := strings.ReplaceAll(oldAsset, "%20", " ")- srcPath := assetsPathMap[spaceDecodedOldAsset]+ srcPath := ""+ if IsEncryptedBox(boxID) {+ srcPath, _ = GetAssetAbsPathInBox(spaceDecodedOldAsset, boxID)+ }+ if "" == srcPath {+ srcPath = assetsPathMap[AssetPathWithoutQuery(spaceDecodedOldAsset)]+ }+ if "" == srcPath {+ srcPath, _ = GetAssetAbsPathInBox(spaceDecodedOldAsset, boxID)+ }if "" == srcPath {logging.LogWarnf("get asset [%s] abs path failed", spaceDecodedOldAsset)continue}- destPath := filepath.Join(writeFolder, newAsset)+ destPath := filepath.Join(writeFolder, cleanNewAsset)if copyErr := copyAssetDecryptIfEncrypted(srcPath, destPath); copyErr != nil {logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, copyErr)continuediff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 6a57a9136d..12b97bf47f 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -1462,7 +1462,7 @@ func (tx *Transaction) processGlobalAssets(tree *parse.Tree) {if ast.NodeLinkDest == n.Type && bytes.HasPrefix(n.Tokens, []byte("assets/")) {assetP := gulu.Str.FromBytes(n.Tokens)- assetPath, e := GetAssetAbsPath(assetP)+ assetPath, e := GetAssetAbsPathInBox(assetP, tree.Box)if nil != e {logging.LogErrorf("get path of asset [%s] failed: %s", assetP, e)return ast.WalkContinuediff --git a/kernel/model/upload.go b/kernel/model/upload.goindex 8c78a7d277..521ac6a650 100644--- a/kernel/model/upload.go+++ b/kernel/model/upload.go@@ -234,6 +234,12 @@ func Upload(c *gin.Context) {ret.Msg = openErr.Error()break}+ if needUnzip2Dir && IsEncryptedBox(uploadBoxID) {+ errFiles = append(errFiles, fName)+ ret.Msg = "directory assets are not supported in encrypted notebooks"+ f.Close()+ break+ }hash, hashErr := util.GetEtagByHandle(f, file.Size)if nil != hashErr {@@ -520,7 +526,7 @@ func writeAssetNameMapping(boxID, diskName, originalName string) {logging.LogErrorf("get DEK for asset name mapping failed: %s", err)return}- enc, err := EncryptAsset(boxID, ".names.json", dek, data)+ enc, err := EncryptAssetNameMapping(boxID, dek, data)if err != nil {logging.LogErrorf("encrypt asset name mapping failed: %s", err)return@@ -545,7 +551,7 @@ func readAssetNameMapping(boxID string) map[string]string {if err != nil || dek == nil {return ret}- data, err := DecryptAsset(boxID, ".names.json", dek, enc)+ data, err := DecryptAssetNameMapping(boxID, dek, enc)if err != nil {logging.LogErrorf("decrypt asset name mapping failed: %s", err)return retdiff --git a/kernel/server/serve.go b/kernel/server/serve.goindex c8936b5543..28d4f7c44e 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -688,7 +688,7 @@ func serveAssets(ginServer *gin.Engine) {if boxID != "" {p, err = model.GetAssetAbsPathInBox(cleanPath, boxID)} else {- p, err = model.GetAssetAbsPathWithOpt(cleanPath, true)+ p, err = model.GetAssetAbsPath(cleanPath)}if err != nil || p == "" {context.Status(http.StatusNotFound)@@ -696,7 +696,20 @@ func serveAssets(ginServer *gin.Engine) {}// 验证最终绝对路径必须在 data/assets 或 <boxID>/assets 下- if !strings.HasSuffix(filepath.ToSlash(p), "/"+strings.TrimPrefix(cleanPath, "/")) {+ boxIDFromPath := model.ExtractBoxIDFromAssetsPath(p)+ assetsRoot := filepath.Join(util.DataDir, "assets")+ if boxIDFromPath != "" {+ assetsRoot = filepath.Join(util.DataDir, boxIDFromPath, "assets")+ }+ if boxID != "" && boxID != boxIDFromPath {+ context.Status(http.StatusForbidden)+ return+ }+ if boxID == "" && model.IsEncryptedAssetPath(p) {+ context.Status(http.StatusForbidden)+ return+ }+ if !gulu.File.IsSubPath(assetsRoot, p) {context.Status(http.StatusForbidden)return}@@ -764,13 +777,13 @@ func readAssetBytes(absPath string) ([]byte, error) {if err != nil {return nil, err}- if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" && model.IsEncryptedBox(boxID) {- dek, dekErr := model.GetDEKIfUnlocked(boxID)- if dekErr != nil {- return nil, dekErr // 加密笔记本未解锁:fail-closed,不返回密文- }- diskName := filepath.Base(absPath)- plain, decErr := model.DecryptAsset(boxID, diskName, dek, data)+ if boxID := model.ExtractBoxIDFromAssetsPath(absPath); boxID != "" && model.IsEncryptedBox(boxID) {+ dek, dekErr := model.GetDEKIfUnlocked(boxID)+ if dekErr != nil {+ return nil, dekErr // 加密笔记本未解锁:fail-closed,不返回密文+ }+ diskName := filepath.Base(absPath)+ plain, decErr := model.DecryptAsset(boxID, diskName, dek, data)if decErr != nil {return nil, decErr}@@ -798,15 +811,15 @@ func serveEncryptedAsset(context *gin.Context, absPath string) bool {context.Status(http.StatusNotFound)return true}- diskName := filepath.Base(absPath)- plain, decErr := model.DecryptAsset(boxID, diskName, dek, ciphertext)- if decErr != nil {- logging.LogErrorf("decrypt asset [%s] failed: %s", absPath, decErr)- context.Status(http.StatusInternalServerError)- return true- }- // 下载时用原始文件名(查加密映射),查不到则退回磁盘名- if originalName := model.LookupAssetOriginalName(boxID, diskName); originalName != "" {+ diskName := filepath.Base(absPath)+ plain, decErr := model.DecryptAsset(boxID, diskName, dek, ciphertext)+ if decErr != nil {+ logging.LogErrorf("decrypt asset [%s] failed: %s", absPath, decErr)+ context.Status(http.StatusInternalServerError)+ return true+ }+ // 下载时用原始文件名(查加密映射),查不到则退回磁盘名+ if originalName := model.LookupAssetOriginalName(boxID, diskName); originalName != "" {setAssetsAttachmentDisposition(context, originalName)} else {setAssetsAttachmentDisposition(context, absPath)