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: Encrypted-notebook review fixes: block-ref boundary degradation, atomic asset mapping, §20 doc note
Danield18786c214cc
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 4d2f2e9105..76dd157839 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -386,6 +386,8 @@ Every raw entry point that might bypass dedicated read/write paths is registered### Locally Persistent Global Deny-Access Records+> **Implementation status**: The persistent `encrypted-deny-access.json` registry and the periodic cleanup janitor described below are not yet implemented. The current release relies on (1) an in-memory export-token map (`managedEncryptedExports`, with a 1-hour expiry, revoked on lock or notebook deletion), and (2) the WebDAV layer unconditionally denying the entire `temp/` directory. Leftover plaintext in `temp/export/` after a kernel crash has no persistent tracking or retry cleanup for the time being; this is a known limitation. The specification below describes the intended design.+“Global” means that a record remains effective independently of a notebook lifecycle after that notebook has been deleted; it does not mean cross-device synchronization. Records persist at `<ConfDir>/encrypted-deny-access.json`, outside `DataDir` and the dejavu synchronization scope, and manage only local controlled temporary artifacts. Each record contains at least a format version, random artifact ID, boxID, canonical path relative to a controlled root, purpose, creation time, most recent retry time, retry count, and an error class containing no original content or sensitive absolute path. Updates use a temporary write, file sync, atomic replacement, and directory sync. A recorded path is revalidated as a descendant of a controlled temporary root; an escaping or malformed record is never used to delete an arbitrary path and instead raises a security error and triggers a controlled-root rescan.A deny record stores cleanup state and diagnostics; it is not the access-control authority. File APIs, downloads, previews, plugins, MCP, WebDAV, and background tasks unconditionally deny the entire controlled-plaintext temporary namespace by canonical path even when the notebook, registry file, or individual record no longer exists. The janitor runs at application startup, immediately after lock or delete and after export completion or failure, and periodically retries with capped exponential backoff. It atomically removes a record only after cleanup succeeds and the path is confirmed absent. Persistent failure retains the record and the `Error` or global-denial state; exhausting retries never opens access. If the registry is manually deleted, loses entries, or cannot be parsed, access remains denied, and startup and periodic scans reconstruct records from residual controlled-root entries before cleanup continues. Cleanup is complete only after the artifact is confirmed absent and record deletion is committed.diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex 4470ba75de..9f97f438e4 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -386,6 +386,8 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明### 本机持久化的全局拒绝访问记录+> **当前实现状态**:下文描述的持久化 `encrypted-deny-access.json` 注册表与周期性清理 janitor 尚未实现。当前版本依赖(1)内存态导出令牌(`managedEncryptedExports`,1 小时过期,锁定或删除笔记本时撤销);(2)WebDAV 层对整个 `temp/` 目录的无条件拒绝。内核崩溃后 `temp/export/` 残留明文暂无持久化追踪与重试清理,属已知限制。下文规格描述的是目标设计。+“全局”表示记录在笔记本已删除后仍独立于该笔记本生命周期生效,不表示跨设备同步。记录持久化在 `<ConfDir>/encrypted-deny-access.json`,位于 `DataDir` 和 dejavu 同步范围之外,仅管理本机受控临时产物。每项记录至少包含格式版本、随机产物 ID、boxID、受控根目录下的规范相对路径、用途、创建时间、最近重试时间、重试次数和不含原始内容或敏感路径的错误类别;文件使用临时写入、同步落盘、原子替换和目录同步更新。记录中的路径必须重新校验为受控临时根目录的后代,越界或格式损坏的记录不得用于删除任意文件,并触发安全错误和受控根目录重新扫描。拒绝记录只保存清理状态和诊断信息,不是访问控制依据。文件 API、下载、预览、插件、MCP、WebDAV 和后台任务按规范路径无条件拒绝整个受控明文临时命名空间,即使笔记本、记录文件或单项记录已经不存在。清理器在应用启动、锁定或删除、导出结束或失败后立即运行,并周期性按有上限的指数退避重试;清理成功且确认路径不存在后原子删除对应记录,持续失败则保留记录并维持 `Error` 或全局拒绝状态,不得因超过重试次数自动放行。记录文件被人为删除、部分条目丢失或文件无法解析时,访问仍保持拒绝;启动和周期扫描从受控根目录残留重建记录后继续清理。只有产物已确认不存在且记录已提交删除,才算清理完成。diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 73e8b7729d..1c6edad8ef 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -374,7 +374,12 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,continue}f.Close()- writeAssetNameMapping(tree.Box, diskName, name)+ // 映射写失败则回滚已写的 asset 密文,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMapping(tree.Box, diskName, name); mapErr != nil {+ logging.LogErrorf("write asset name mapping for [%s] failed: %s", name, mapErr)+ _ = filelock.Remove(writePath)+ continue+ }name = diskName} else {name = util.AssetName(name, ast.NewNodeID())@@ -501,7 +506,12 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,logging.LogErrorf("write encrypted network asset [%s] failed: %s", writePath, err)continue}- writeAssetNameMapping(tree.Box, diskName, name)+ // 映射写失败则回滚已写的 asset 密文,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMapping(tree.Box, diskName, name); mapErr != nil {+ logging.LogErrorf("write asset name mapping for [%s] failed: %s", name, mapErr)+ _ = filelock.Remove(writePath)+ continue+ }name = diskName} else {name = util.AssetName(name, ast.NewNodeID())diff --git a/kernel/model/import.go b/kernel/model/import.goindex 0e53eb526c..ab6326e898 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -610,7 +610,10 @@ func ImportSY(zipPath, boxID, toPath string) (err error) {ext := filepath.Ext(originalName)blockID := ast.NewNodeID()diskName := encryptedAssetName(ext, blockID)- writeAssetNameMapping(boxID, diskName, originalName)+ // 映射写入失败则不写 asset,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMapping(boxID, diskName, originalName); mapErr != nil {+ return mapErr+ }assetNameMap[originalName] = diskName// 读取明文内容 → 加密 → 写入脱敏文件名src, readErr := filelock.ReadFile(path)@@ -1158,7 +1161,11 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {ext := filepath.Ext(baseName)blockID := ast.NewNodeID()name = encryptedAssetName(ext, blockID)- writeAssetNameMapping(boxID, name, baseName)+ // 映射写入失败则不写 asset,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMapping(boxID, name, baseName); mapErr != nil {+ logging.LogErrorf("write asset name mapping for [%s] failed: %s", baseName, mapErr)+ return ast.WalkContinue+ }assetTargetPath := filepath.Join(assetDirPath, name)src, readErr := filelock.ReadFile(absolutePath)if readErr != nil {@@ -1311,7 +1318,11 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {ext := filepath.Ext(baseName)blockID := ast.NewNodeID()name = encryptedAssetName(ext, blockID)- writeAssetNameMapping(boxID, name, baseName)+ // 映射写入失败则不写 asset,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMapping(boxID, name, baseName); mapErr != nil {+ logging.LogErrorf("write asset name mapping for [%s] failed: %s", baseName, mapErr)+ return ast.WalkContinue+ }assetTargetPath := filepath.Join(assetDirPath, name)src, readErr := filelock.ReadFile(absolutePath)if readErr != nil {@@ -1352,6 +1363,8 @@ func ImportFromLocalPath(boxID, localPath string, toPath string) (err error) {})reassignIDUpdated(tree, id, updated)+ // 兜底校验:禁止跨加密边界块引(导入的 Markdown 可能含跨边界引用)+ degradeCrossBoundaryBlockRefs(tree.Root, tree.Box)importTrees = append(importTrees, tree)}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 6a84e2c017..ae2a44d334 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -703,6 +703,9 @@ func (tx *Transaction) doPrependInsert(operation *Operation) (ret *TxErr) {data := strings.ReplaceAll(operation.Data.(string), editor.FrontEndCaret, "")subTree := tx.luteEngine.BlockDOM2Tree(data)+ // 兜底校验:禁止跨加密边界块引(粘贴/拖拽/API 直调可能携带跨边界引用)+ // subTree.Box 此时尚未设置,用目标树所在 box 作为 srcBox+ degradeCrossBoundaryBlockRefs(subTree.Root, tree.Box)insertedNode := subTree.Root.FirstChildif nil == insertedNode {return &TxErr{code: TxErrCodeBlockNotFound, msg: "invalid data tree", id: block.ID}@@ -799,6 +802,9 @@ func (tx *Transaction) doAppendInsert(operation *Operation) (ret *TxErr) {data := strings.ReplaceAll(operation.Data.(string), editor.FrontEndCaret, "")subTree := tx.luteEngine.BlockDOM2Tree(data)+ // 兜底校验:禁止跨加密边界块引(粘贴/拖拽/API 直调可能携带跨边界引用)+ // subTree.Box 此时尚未设置,用目标树所在 box 作为 srcBox+ degradeCrossBoundaryBlockRefs(subTree.Root, tree.Box)insertedNode := subTree.Root.FirstChildif nil == insertedNode {return &TxErr{code: TxErrCodeBlockNotFound, msg: "invalid data tree", id: block.ID}@@ -1880,6 +1886,9 @@ func (tx *Transaction) doUpdateUpdated(operation *Operation) (ret *TxErr) {func (tx *Transaction) doCreate(operation *Operation) (ret *TxErr) {tree := operation.Data.(*parse.Tree)+ // 兜底校验:禁止跨加密边界块引(创建文档可能携带跨边界引用)+ // 必须在 getRefDefIDs 之前,避免跨边界引用被收集进引用缓存+ degradeCrossBoundaryBlockRefs(tree.Root, tree.Box)tx.writeTree(tree)// 新建文档中的引用均为本次新增,刷新其最近引用时间用于块引"最近引用"排序TouchRefUsed(getRefDefIDs(tree.Root))diff --git a/kernel/model/upload.go b/kernel/model/upload.goindex da0bfcd032..b1f085a6a8 100644--- a/kernel/model/upload.go+++ b/kernel/model/upload.go@@ -114,7 +114,12 @@ func InsertLocalAssets(id string, assetAbsPaths []string, isUpload bool) (succMaif IsEncryptedBox(bt.BoxID) {// 加密 box:磁盘文件名脱敏为 uuid-blockID.ext,原始名存加密映射fName = encryptedAssetName(util.Ext(fName), blockID)- writeAssetNameMapping(bt.BoxID, fName, baseName)+ // 映射写入失败则不写 asset,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMapping(bt.BoxID, fName, baseName); mapErr != nil {+ err = mapErr+ f.Close()+ return+ }} else {fName = util.AssetName(fName, blockID)}@@ -295,7 +300,13 @@ func Upload(c *gin.Context) {if IsEncryptedBox(uploadBoxID) {// 加密 box:磁盘文件名脱敏为 uuid-blockID.ext,原始名存加密映射fName = encryptedAssetName(util.Ext(fName), lastID)- writeAssetNameMapping(uploadBoxID, fName, baseName)+ // 映射写入失败则不写 asset,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMapping(uploadBoxID, fName, baseName); mapErr != nil {+ errFiles = append(errFiles, fName)+ ret.Msg = mapErr.Error()+ f.Close()+ break+ }} else {fName = util.AssetName(fName, lastID)}@@ -477,7 +488,10 @@ func storeAssetForBox(boxID, assetDirPath, originalName string, data []byte) (diext := filepath.Ext(originalName)blockID := ast.NewNodeID()diskName = encryptedAssetName(ext, blockID)- writeAssetNameMappingLocked(boxID, diskName, originalName)+ // 映射写入失败则不写 asset,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)+ if mapErr := writeAssetNameMappingLocked(boxID, diskName, originalName); mapErr != nil {+ return "", mapErr+ }dek, dekErr := GetDEKIfUnlocked(boxID)if dekErr != nil {@@ -518,16 +532,17 @@ func assetNameMappingPath(boxID string) string {var assetNameMappingLocks sync.Map // map[string]*sync.Mutex// writeAssetNameMapping 把"磁盘文件名 -> 原始文件名"映射写入加密笔记本的 .names.json(DEK 加密落盘)。-func writeAssetNameMapping(boxID, diskName, originalName string) {+// 返回错误时调用方不得继续写 asset 密文,避免产出"孤儿密文 asset 无映射"(详见设计文档 §7)。+func writeAssetNameMapping(boxID, diskName, originalName string) error {if boxID == "" || !IsEncryptedBox(boxID) {- return+ return nil}HoldBoxReadLock(boxID)defer ReleaseBoxReadLock(boxID)- writeAssetNameMappingLocked(boxID, diskName, originalName)+ return writeAssetNameMappingLocked(boxID, diskName, originalName)}-func writeAssetNameMappingLocked(boxID, diskName, originalName string) {+func writeAssetNameMappingLocked(boxID, diskName, originalName string) error {muI, _ := assetNameMappingLocks.LoadOrStore(boxID, &sync.Mutex{})mu := muI.(*sync.Mutex)mu.Lock()@@ -537,22 +552,21 @@ func writeAssetNameMappingLocked(boxID, diskName, originalName string) {mapping[diskName] = originalNamedata, err := json.Marshal(mapping)if err != nil {- logging.LogErrorf("marshal asset name mapping failed: %s", err)- return+ return fmt.Errorf("marshal asset name mapping failed: %w", err)}dek, err := GetDEK(boxID)if err != nil || dek == nil {- logging.LogErrorf("get DEK for asset name mapping failed: %s", err)- return+ return fmt.Errorf("get DEK for asset name mapping failed: %w", err)}enc, err := EncryptAssetNameMapping(boxID, dek, data)if err != nil {- logging.LogErrorf("encrypt asset name mapping failed: %s", err)- return+ return fmt.Errorf("encrypt asset name mapping failed: %w", err)}- if err = filelock.WriteFile(assetNameMappingPath(boxID), enc); err != nil {- logging.LogErrorf("write asset name mapping failed: %s", err)+ // 原子写入(temp+rename):防止半写映射残留,并避免与并发写者竞争同一文件造成 lost update+ if err = atomicWriteFile(assetNameMappingPath(boxID), enc); err != nil {+ return fmt.Errorf("write asset name mapping failed: %w", err)}+ return nil}// readAssetNameMapping 读取加密笔记本的资源名映射(DEK 解密)。未解锁或文件不存在时返回空 map。