An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support encrypted notebook asset cleanup https://github.com/siyuan-note/siyuan/issues/20633
Daniel7f5c04d1f134
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 88e8c7257d..8dc3e083d0 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "تنظيف الموارد غير المشار إليها","tableSelectRange": "تحديد نطاق خلايا","tableSelectionDone": "تم","listMindmapConnectors": "خطوط التوصيل",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex e35590b6f8..f9a1f5fe45 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Nicht referenzierte Ressourcen bereinigen","tableSelectRange": "Zellbereich auswählen","tableSelectionDone": "Fertig","listMindmapConnectors": "Verbindungslinien",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 0f2ad963a1..ec53387105 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Clean up unreferenced assets","tableSelectRange": "Select cell range","tableSelectionDone": "Done","listMindmapConnectors": "Connectors",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex b2002cdae8..85688d894b 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Limpiar recursos sin referencias","tableSelectRange": "Seleccionar rango de celdas","tableSelectionDone": "Listo","listMindmapConnectors": "Conectores",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex f0b445bbd2..24fc25c612 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Nettoyer les ressources non référencées","tableSelectRange": "Sélectionner une plage de cellules","tableSelectionDone": "Terminé","listMindmapConnectors": "Connecteurs",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 2930255fc1..5d86908236 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "ניקוי משאבים ללא הפניות","tableSelectRange": "בחירת טווח תאים","tableSelectionDone": "סיום","listMindmapConnectors": "קווי חיבור",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 284d3f106f..f74929367e 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "असंदर्भित संसाधनों को साफ़ करें","tableSelectRange": "सेल श्रेणी चुनें","tableSelectionDone": "पूर्ण","listMindmapConnectors": "कनेक्टर",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 30a9848c12..b63a8f3ca0 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Bersihkan aset tanpa referensi","tableSelectRange": "Pilih rentang sel","tableSelectionDone": "Selesai","listMindmapConnectors": "Penghubung",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex f68826b4f8..cdd1654ed7 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Pulisci le risorse senza riferimenti","tableSelectRange": "Seleziona intervallo di celle","tableSelectionDone": "Fine","listMindmapConnectors": "Collegamenti",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 0c7de2c227..3145143b16 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "未参照のリソースをクリーンアップ","tableSelectRange": "セル範囲を選択","tableSelectionDone": "完了","listMindmapConnectors": "接続線",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex dffc0b7f36..8791b6ca3c 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "참조되지 않은 리소스 정리","tableSelectRange": "셀 범위 선택","tableSelectionDone": "완료","listMindmapConnectors": "연결선",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex efecd6e5ba..bf43a0bcf1 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Niet-verwezen bronnen opruimen","tableSelectRange": "Celbereik selecteren","tableSelectionDone": "Gereed","listMindmapConnectors": "Verbindingslijnen",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 69ab61e0e6..9694259e0b 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Usuń nieużywane zasoby","tableSelectRange": "Wybierz zakres komórek","tableSelectionDone": "Gotowe","listMindmapConnectors": "Łączniki",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 7dc4b69891..4570069d22 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Limpar recursos sem referências","tableSelectRange": "Selecionar intervalo de células","tableSelectionDone": "Concluído","listMindmapConnectors": "Conectores",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 511aa8aa65..ecf5a970aa 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Очистить ресурсы без ссылок","tableSelectRange": "Выбрать диапазон ячеек","tableSelectionDone": "Готово","listMindmapConnectors": "Соединительные линии",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 2ef344a284..fc05f41a60 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Vyčistiť neodkazované zdroje","tableSelectRange": "Vybrať rozsah buniek","tableSelectionDone": "Hotovo","listMindmapConnectors": "Spojnice",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 78feac1693..0940a9363f 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Очисти ресурсе без референци","tableSelectRange": "Изабери опсег ћелија","tableSelectionDone": "Готово","listMindmapConnectors": "Линије повезивања",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 33fce3f199..7c5e070aae 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "ล้างทรัพยากรที่ไม่มีการอ้างอิง","tableSelectRange": "เลือกช่วงเซลล์","tableSelectionDone": "เสร็จสิ้น","listMindmapConnectors": "เส้นเชื่อม",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 9c0c8bc7ad..8becfc1324 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Başvurulmayan kaynakları temizle","tableSelectRange": "Hücre aralığı seç","tableSelectionDone": "Bitti","listMindmapConnectors": "Bağlantı çizgileri",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 23b985a1b9..3e3bd082b2 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "Очистити ресурси без посилань","tableSelectRange": "Вибрати діапазон клітинок","tableSelectionDone": "Готово","listMindmapConnectors": "З’єднувальні лінії",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 39f91c03a5..a4393a5e09 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "清理未引用资源","tableSelectRange": "选择区域","tableSelectionDone": "完成","listMindmapConnectors": "连线",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex b76cbf5296..3fad90499d 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "cleanUnusedAssets": "清理未引用資源","tableSelectRange": "選取區域","tableSelectionDone": "完成","listMindmapConnectors": "連線",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260907120000-cryen01.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260907120000-cryen01.syindex 18feb97d79..89d10b4429 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260907120000-cryen01.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260907120000-cryen01.sy@@ -6,7 +6,7 @@"id": "20260907120000-cryen01","title": "Encrypted Notebook","type": "doc",- "updated": "20261012014930"+ "updated": "20261017144106"},"Children": [{@@ -1014,7 +1014,7 @@"Type": "NodeHeading","Properties": {"id": "20261012014537-5ru0ol2",- "updated": "20261012014859"+ "updated": "20261017144106"},"Children": [{@@ -1038,6 +1038,85 @@}]},+ {+ "ID": "20261017144106-ls2hwxk",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261017144106-ls2hwxk",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Clean up unreferenced assets"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261017144106-4haij5x",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-4haij5x",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "After unlocking the target notebook, open "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Document panel"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Notebook"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "More"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Clean up unreferenced assets"+ },+ {+ "Type": "NodeText",+ "Data": ", review the scan results, select the assets to clean up, and confirm deletion. On desktop, right-clicking the notebook opens the same menu."+ }+ ]+ },+ {+ "ID": "20261017144106-0r98a62",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-0r98a62",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "The scan covers only the current encrypted notebook. If any document or database cannot be read, cleanup stops. Assets are fully backed up as ciphertext before deletion and can be restored after unlocking through the asset cleanup records in Data history, subject to the history retention period. Global cleanup continues to exclude encrypted notebooks."+ }+ ]+ },{"ID": "20260907120000-en00042","Type": "NodeHeading",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260907120000-crycn01.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260907120000-crycn01.syindex e89e49d471..4ced3d0a4c 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260907120000-crycn01.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260907120000-crycn01.sy@@ -6,7 +6,7 @@"id": "20260907120000-crycn01","title": "加密笔记本","type": "doc",- "updated": "20261012014930"+ "updated": "20261017144106"},"Children": [{@@ -1014,7 +1014,7 @@"Type": "NodeHeading","Properties": {"id": "20261012014537-7v78dj5",- "updated": "20261012014859"+ "updated": "20261017144106"},"Children": [{@@ -1038,6 +1038,85 @@}]},+ {+ "ID": "20261017144106-76oanrr",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261017144106-76oanrr",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "清理未引用资源"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261017144106-eyzvkv2",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-eyzvkv2",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "解锁目标笔记本后,打开 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "文档面板"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "笔记本"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "更多"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "清理未引用资源"+ },+ {+ "Type": "NodeText",+ "Data": ",查看扫描结果,勾选需要清理的资源,再确认删除。桌面端也可以右键单击笔记本打开同一菜单。"+ }+ ]+ },+ {+ "ID": "20261017144106-kp6get0",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-kp6get0",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "扫描仅针对当前加密笔记本,任何文档或数据库读取失败都会中止清理。删除前完整备份资源密文,可在解锁后通过数据历史的资源文件清理记录恢复;历史受保留天数限制。全局清理继续排除加密笔记本。"+ }+ ]+ },{"ID": "20260907120000-cn00042","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260907120000-crytw01.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260907120000-crytw01.syindex 34f9e477a2..c677bbc4a6 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260907120000-crytw01.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260907120000-crytw01.sy@@ -6,7 +6,7 @@"id": "20260907120000-crytw01","title": "加密筆記本","type": "doc",- "updated": "20261012014930"+ "updated": "20261017144106"},"Children": [{@@ -1014,7 +1014,7 @@"Type": "NodeHeading","Properties": {"id": "20261012014537-eewtudq",- "updated": "20261012014859"+ "updated": "20261017144106"},"Children": [{@@ -1038,6 +1038,85 @@}]},+ {+ "ID": "20261017144106-wmu7o58",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261017144106-wmu7o58",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "清理未引用資源"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261017144106-kqu3kct",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-kqu3kct",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "解鎖目標筆記本後,開啟 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "文件面板"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "筆記本"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "更多"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "清理未引用資源"+ },+ {+ "Type": "NodeText",+ "Data": ",檢視掃描結果,勾選需要清理的資源,再確認刪除。桌面端也可以在筆記本上按滑鼠右鍵開啟同一選單。"+ }+ ]+ },+ {+ "ID": "20261017144106-4r0arxr",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-4r0arxr",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "掃描僅針對目前的加密筆記本,任何文件或資料庫讀取失敗都會中止清理。刪除前完整備份資源密文,可在解鎖後透過資料歷史的資源檔案清理記錄復原;歷史受保留天數限制。全域清理繼續排除加密筆記本。"+ }+ ]+ },{"ID": "20260907120000-tw00042","Type": "NodeHeading",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260907120000-cryja01.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260907120000-cryja01.syindex 5456bf2029..3341fbb06b 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260907120000-cryja01.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260907120000-cryja01.sy@@ -6,7 +6,7 @@"id": "20260907120000-cryja01","title": "暗号化ノートブック","type": "doc",- "updated": "20261012014930"+ "updated": "20261017144106"},"Children": [{@@ -1014,7 +1014,7 @@"Type": "NodeHeading","Properties": {"id": "20261012014537-493zsvt",- "updated": "20261012014859"+ "updated": "20261017144106"},"Children": [{@@ -1038,6 +1038,85 @@}]},+ {+ "ID": "20261017144106-2nu4tzr",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261017144106-2nu4tzr",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "未参照のリソースをクリーンアップ"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261017144106-mgslbo5",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-mgslbo5",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "対象のノートブックをロック解除した後、"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "ドキュメントパネル"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "ノートブック"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "詳細"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "未参照のリソースをクリーンアップ"+ },+ {+ "Type": "NodeText",+ "Data": " を開き、スキャン結果を確認して、削除するリソースを選択し、削除を確定します。デスクトップでは、ノートブックを右クリックして同じメニューを開くこともできます。"+ }+ ]+ },+ {+ "ID": "20261017144106-64yu457",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261017144106-64yu457",+ "updated": "20261017144106"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "スキャン対象は現在の暗号化ノートブックだけです。ドキュメントやデータベースを読み取れない場合は、クリーンアップを中止します。削除前にリソースの暗号文をすべてバックアップし、ロック解除後にデータ履歴のリソースクリーンアップ記録から復元できます。履歴の保存期間に注意してください。暗号化ノートブックは引き続きグローバルクリーンアップの対象外です。"+ }+ ]+ },{"ID": "20260907120000-ja00042","Type": "NodeHeading",diff --git a/app/src/config/encryptedAssets.test.ts b/app/src/config/encryptedAssets.test.tsnew file mode 100644index 0000000000..ae6107a15c--- /dev/null+++ b/app/src/config/encryptedAssets.test.ts@@ -0,0 +1,163 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const compiled = transpileModule(readFileSync("src/config/encryptedAssets.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++class Control {+ checked = false;+ indeterminate = false;+ disabled = false;+ textContent = "";+ dataset: Record<string, string> = {};+ classList = {add: () => {}, remove: () => {}};+ listeners = new Map<string, (event?: unknown) => unknown>();+ inputs: Control[] = [];+ html = "";+ set innerHTML(html: string) {+ this.html = html;+ this.inputs = Array.from(html.matchAll(/data-index="(\d+)"/g), match => {+ const input = new Control();+ input.dataset.index = match[1];+ return input;+ });+ }+ querySelectorAll() { return this.inputs; }+ closest() { return this; }+ addEventListener(name: string, handler: (event?: unknown) => unknown) { this.listeners.set(name, handler); }+ dispatch(name: string) { return this.listeners.get(name)?.(); }+}++const setup = (mobile = false) => {+ const controls = Object.fromEntries(["list", "all", "delete", "refresh", "preview", "cancel", "count"]+ .map(key => [key, new Control()]));+ const pending: Promise<unknown>[] = [];+ const requests: Array<{url: string, data: {notebook: string, paths?: string[]}}> = [];+ const callbacks: Array<() => void> = [];+ let current: {element: {isConnected: boolean, dataset: Record<string, string>}, destroy: () => void};+ let response = {code: 0, data: [+ {item: "assets/a.png", name: "<private name>.png", path: "assets/a.png?box=secret"},+ {item: "assets/b.png", name: "private-b.png", path: "assets/b.png?box=secret"},+ ]};+ let releaseScan: (() => void) | undefined;+ let delay = false;+ let previewClears = 0;+ const previews: string[][] = [];+ const siyuan = {config: {readonly: false}, notebooks: [{id: "secret", encrypted: true, closed: false}],+ languages: {loading: "Loading", emptyContent: "Empty", clearAll: "Confirm cleanup"}};+ const exports = {} as typeof import("./encryptedAssets");+ const dependencies = {+ Dialog: class {+ element = {isConnected: true, dataset: {} as Record<string, string>,+ querySelector: (selector: string) => controls[selector.match(/data-type="([^"]+)"/)[1]]};+ constructor(private options: {destroyCallback: () => void}) {+ current = {element: this.element, destroy: () => this.destroy()};+ }+ destroy() {+ this.element.dataset.dialogClosing = "true";+ this.element.isConnected = false;+ this.options.destroyCallback();+ }+ },+ AssetPreview: class {+ clear() { previewClears++; }+ show(...args: string[]) { previews.push(args); }+ },+ fetchSyncPost: async (url: string, data: typeof requests[number]["data"]) => {+ requests.push({url, data});+ if (delay) {+ await new Promise<void>(resolve => { releaseScan = resolve; });+ }+ return response;+ },+ confirmDialog: (_title: string, _content: string, confirm: () => void) => { callbacks.push(confirm); },+ showMessage: () => {},+ trackNotebookHistoryDialog: () => {},+ forgetNotebookHistoryDialog: () => {},+ escapeHtml: (text: string) => text.replaceAll("<", "<").replaceAll(">", ">"),+ getNotebookName: () => "Private notebook",+ isMobile: () => mobile,+ runSettingsMaintenance: (action: () => Promise<unknown>) => { const task = action(); pending.push(task); return task; },+ };+ runInNewContext(compiled, {exports, require: () => dependencies,+ window: {siyuan}});+ return {+ controls, requests, callbacks, previews, siyuan,+ canClean: () => exports.canCleanEncryptedNotebookAssets("secret"),+ open: () => exports.openEncryptedAssetsCleanup("secret"),+ settle: async () => { await Promise.all(pending); await new Promise(resolve => setImmediate(resolve)); },+ close: () => current.destroy(),+ delay: () => { delay = true; },+ release: () => { delay = false; releaseScan?.(); },+ fail: () => { response = {code: -1, data: []}; },+ previewClears: () => previewClears,+ };+};++for (const mobile of [false, true]) {+ test(`${mobile ? "mobile" : "desktop"} cleanup previews and deletes only explicitly confirmed selections`, async () => {+ const state = setup(mobile);+ state.open();+ await state.settle();+ assert.equal(state.requests.length, 1);+ assert.equal(state.requests[0].data.notebook, "secret");+ assert.ok(state.controls.list.html.includes("<private name>"));+ assert.equal(state.controls.delete.disabled, true);+ state.controls.list.inputs[1].checked = true;+ state.controls.list.dispatch("change");+ assert.equal(state.controls.delete.disabled, false);+ state.controls.delete.dispatch("click");+ assert.equal(state.requests.length, 1);+ assert.equal(state.callbacks.length, 1);+ state.callbacks[0]();+ await state.settle();+ const deletion = state.requests.find(request => request.url.endsWith("removeUnusedEncryptedBoxAssets"));+ assert.deepEqual(JSON.parse(JSON.stringify(deletion.data)), {notebook: "secret", paths: ["assets/b.png"]});+ assert.equal(state.requests.filter(request => request.url.endsWith("getUnusedEncryptedBoxAssets")).length, 2);+ state.close();+ assert.ok(state.previewClears() >= 2);+ });+}++test("closing during a scan prevents publishing late decrypted filenames", async () => {+ const state = setup();+ state.delay();+ state.open();+ state.close();+ state.release();+ await state.settle();+ assert.equal(state.controls.list.html, "");+ assert.equal(state.requests.length, 1);+});++test("a confirmation cannot delete after the notebook dialog closes", async () => {+ const state = setup();+ state.open();+ await state.settle();+ state.controls.all.checked = true;+ state.controls.all.dispatch("change");+ state.controls.delete.dispatch("click");+ state.close();+ state.callbacks[0]();+ await state.settle();+ assert.equal(state.requests.length, 1);+});++test("cleanup is available only for an unlocked encrypted notebook in a writable workspace", () => {+ const state = setup();+ assert.equal(state.canClean(), true);+ state.siyuan.notebooks[0].closed = true;+ assert.equal(state.canClean(), false);+ state.open();+ assert.equal(state.requests.length, 0);+ state.siyuan.notebooks[0].closed = false;+ state.siyuan.notebooks[0].encrypted = false;+ assert.equal(state.canClean(), false);+ state.siyuan.notebooks[0].encrypted = true;+ state.siyuan.config.readonly = true;+ assert.equal(state.canClean(), false);+});diff --git a/app/src/config/encryptedAssets.ts b/app/src/config/encryptedAssets.tsnew file mode 100644index 0000000000..c7273a7b91--- /dev/null+++ b/app/src/config/encryptedAssets.ts@@ -0,0 +1,151 @@+import {Dialog} from "../dialog";+import {confirmDialog} from "../dialog/confirmDialog";+import {showMessage} from "../dialog/message";+import {forgetNotebookHistoryDialog, trackNotebookHistoryDialog} from "../history/notebookDialogs";+import {escapeHtml} from "../util/escape";+import {fetchSyncPost} from "../util/fetch";+import {isMobile} from "../util/functions";+import {getNotebookName} from "../util/pathName";+import {AssetPreview} from "./assetPreview";+import {runSettingsMaintenance} from "./setting/maintenance";+import type {AssetUnusedItem} from "../types/api";++export const canCleanEncryptedNotebookAssets = (notebook: string) => !window.siyuan.config.readonly &&+ window.siyuan.notebooks.some(item => item.id === notebook && item.encrypted && !item.closed);++export const openEncryptedAssetsCleanup = (notebook: string) => {+ if (!canCleanEncryptedNotebookAssets(notebook)) {+ return;+ }+ const lang = window.siyuan.languages;+ let busy = false;+ let disposed = false;+ let items: AssetUnusedItem[] = [];+ const dialog = new Dialog({+ title: `${escapeHtml(getNotebookName(notebook))} - ${lang.cleanUnusedAssets}`,+ width: isMobile() ? "92vw" : "720px",+ height: "72vh",+ content: `<div class="b3-dialog__content fn__flex-column">+ <div class="fn__flex">+ <label class="fn__flex"><input class="b3-switch" type="checkbox" data-type="all"><span class="fn__space"></span>${lang.selectAll}</label>+ <span class="fn__flex-1"></span><span class="ft__secondary" data-type="count"></span>+ </div>+ <div class="fn__hr"></div>+ <div class="b3-list b3-list--background config-assets__list" data-type="list"></div>+ <div class="config-assets__preview fn__none" data-type="preview"></div>+</div>+<div class="b3-dialog__action">+ <button class="b3-button b3-button--cancel" data-type="cancel">${lang.cancel}</button>+ <div class="fn__space"></div><button class="b3-button b3-button--outline" data-type="refresh">${lang.refresh}</button>+ <div class="fn__space"></div><button class="b3-button b3-button--remove" data-type="delete" disabled>${lang.delete}</button>+</div>`,+ destroyCallback: () => {+ disposed = true;+ items = [];+ preview.clear();+ forgetNotebookHistoryDialog(dialog);+ },+ });+ trackNotebookHistoryDialog(dialog, [notebook]);+ const list = dialog.element.querySelector<HTMLElement>('[data-type="list"]');+ const all = dialog.element.querySelector<HTMLInputElement>('[data-type="all"]');+ const remove = dialog.element.querySelector<HTMLButtonElement>('[data-type="delete"]');+ const refresh = dialog.element.querySelector<HTMLButtonElement>('[data-type="refresh"]');+ const previewElement = dialog.element.querySelector<HTMLElement>('[data-type="preview"]');+ const preview = new AssetPreview(previewElement);+ const active = () => !disposed && dialog.element.isConnected && dialog.element.dataset.dialogClosing !== "true";+ const boxes = () => Array.from(list.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'));+ const update = () => {+ const inputs = boxes();+ const selected = inputs.filter(input => input.checked).length;+ all.checked = inputs.length > 0 && selected === inputs.length;+ all.indeterminate = selected > 0 && selected < inputs.length;+ all.disabled = busy || inputs.length === 0;+ inputs.forEach(input => input.disabled = busy);+ remove.disabled = busy || selected === 0;+ refresh.disabled = busy;+ dialog.element.querySelector('[data-type="count"]').textContent = `${selected} / ${items.length}`;+ };+ const scan = async () => {+ if (busy || !active()) {+ return;+ }+ busy = true;+ items = [];+ preview.clear();+ previewElement.classList.add("fn__none");+ list.textContent = lang.loading;+ update();+ try {+ const response = await fetchSyncPost("/api/asset/getUnusedEncryptedBoxAssets", {notebook});+ if (!active()) {+ return;+ }+ if (response.code !== 0) {+ list.textContent = response.msg;+ return;+ }+ items = response.data;+ list.innerHTML = items.length ? items.map((item, index) => `<div class="b3-list-item" data-index="${index}">+ <input class="b3-switch" type="checkbox" aria-label="${escapeHtml(item.name)}"><span class="fn__space"></span>+ <button class="b3-button b3-button--text fn__flex-1" data-type="preview-item">${escapeHtml(item.name)}</button>+</div>`).join("") : `<div class="b3-list--empty">${lang.emptyContent}</div>`;+ } catch (error) {+ if (active()) {+ list.textContent = String(error);+ }+ } finally {+ busy = false;+ if (active()) {+ update();+ }+ }+ };+ all.addEventListener("change", () => {+ boxes().forEach(input => input.checked = all.checked);+ update();+ });+ list.addEventListener("change", update);+ list.addEventListener("click", event => {+ const target = (event.target as HTMLElement).closest<HTMLElement>('[data-type="preview-item"]');+ if (busy || !target) {+ return;+ }+ const item = items[Number(target.closest<HTMLElement>("[data-index]").dataset.index)];+ previewElement.classList.remove("fn__none");+ preview.show(item.path, `${notebook}/${item.item}`);+ });+ refresh.addEventListener("click", () => void scan());+ dialog.element.querySelector('[data-type="cancel"]').addEventListener("click", () => dialog.destroy());+ remove.addEventListener("click", () => {+ if (busy || !active()) {+ return;+ }+ const paths = boxes().filter(input => input.checked)+ .map(input => items[Number(input.closest<HTMLElement>("[data-index]").dataset.index)].item);+ if (!paths.length) {+ return;+ }+ confirmDialog(lang.deleteOpConfirm, `${escapeHtml(getNotebookName(notebook))} - ${lang.clearAll}`, () => {+ if (!active() || busy) {+ return;+ }+ busy = true;+ update();+ void runSettingsMaintenance(async () => {+ try {+ const response = await fetchSyncPost("/api/asset/removeUnusedEncryptedBoxAssets", {notebook, paths});+ if (response.code === 0 && active()) {+ showMessage(lang.deleted);+ }+ } finally {+ busy = false;+ if (active()) {+ await scan();+ }+ }+ });+ });+ });+ void runSettingsMaintenance(scan);+};diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex 31dfff94d9..7ebbebe7b1 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -1213,6 +1213,13 @@ test("notebook pin entries follow settings and precede sorting", () => {}});+test("encrypted notebook cleanup follows replace and precedes close", () => {+ const keys = getEntryCatalogChildren("docTree.notebook").map(item => item.key);+ assert.deepEqual(keys.slice(keys.indexOf("replace"), keys.indexOf("close") + 1),+ ["replace", "cleanUnusedAssets", "separator_1", "close"]);+ assert.equal(getEntryCatalogNode("docTree.notebook.cleanUnusedAssets")?.simple, true);+});+test("document tree pin entries follow attributes and precede sorting", () => {const keys = getEntryCatalogChildren("docTree.document").map(item => item.key);assert.deepEqual(keys.slice(keys.indexOf("attr"), keys.indexOf("sort") + 1), ["attr", "pinDoc", "unpinDoc", "sort"]);diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex d5624316a8..288740b02c 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -757,6 +757,7 @@ export const entryCatalog: IEntryCatalogSection[] = [node("riffCard", lang("riffCard"), false),node("search", lang("search")),node("replace", lang("replace")),+ node("cleanUnusedAssets", lang("cleanUnusedAssets")),separator("separator_1"),node("close", lang("close")),node("delete", lang("delete")),diff --git a/app/src/menus/navigation.ts b/app/src/menus/navigation.tsindex 3785a61d68..adba74cdbd 100644--- a/app/src/menus/navigation.ts+++ b/app/src/menus/navigation.ts@@ -13,6 +13,7 @@ import {confirmDialog} from "../dialog/confirmDialog";import {fetchPost, fetchSyncPost} from "../util/fetch";import {ContractFormData} from "../util/contractFormData";import {onGetnotebookconf} from "./onGetnotebookconf";+import {canCleanEncryptedNotebookAssets, openEncryptedAssetsCleanup} from "../config/encryptedAssets";/// #if !MOBILEimport {openSearch} from "../search/spread";/// #else@@ -643,6 +644,19 @@ export const initNavigationMenu = (app: App, liElement: HTMLElement) => {}).element);}if (!window.siyuan.config.readonly) {+ if (isEncryptedBox(notebookId) && canCleanEncryptedNotebookAssets(notebookId)) {+ window.siyuan.menus.menu.append(new MenuItem({+ id: "cleanUnusedAssets",+ label: window.siyuan.languages.cleanUnusedAssets,+ icon: "iconTrashcan",+ click: () => {+ openEncryptedAssetsCleanup(notebookId);+ /// #if MOBILE+ closePanel();+ /// #endif+ },+ }).element);+ }window.siyuan.menus.menu.append(new MenuItem({id: "separator_1", type: "separator"}).element);if (!Object.values(Constants.HELP_PATH).includes(notebookId)) {window.siyuan.menus.menu.append(new MenuItem({diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 1a16982f6d..4a1825068a 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -976,6 +976,8 @@ export type EmbedStat = { "complete": boolean; "cycleCount": number; "depthLimitexport type EmptyRequestInput = Record<string, never>;+export type EncryptedBoxAssetsRequestInput = { "notebook": string; };+export type EncryptedNotebookFollowSystemLockRequestInput = { "enabled": boolean; };export type EncryptedNotebookStatus = { "id": string; "name": string; "state": "Locked" | "Unlocking" | "Unlocked" | "Locking" | "Error"; "unlocked": boolean; };@@ -1650,6 +1652,8 @@ export type RemoveCloudRepoTagSnapshotRequestInput = { "tag": string; };export type RemoveCriterionRequestInput = { "name": string; };+export type RemoveEncryptedBoxAssetsRequestInput = { "notebook": string; "paths": Array<string>; };+export type RemoveFileRequestInput = { "app"?: string | null; "path": string; };export type RemoveRepoTagSnapshotRequestInput = { "tag": string; };@@ -3261,6 +3265,18 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin"];};+ /**+ * 扫描单个已解锁加密笔记本的文档、全部数据库定义及智能体会话引用。+ * 任意扫描失败返回 -1,不返回不完整候选。锁定目标使用既有 314 语言消息;结果不截断。+ * name 为响应期间可见的原始文件名,item 为 assets 相对路径,path 带目标 box 查询参数。+ */+ "/api/asset/getUnusedEncryptedBoxAssets": {+ request: EncryptedBoxAssetsRequestInput;+ response: { "code": 0; "data": Array<AssetUnusedItem | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin"];+ };"/api/asset/importOCRModels": {request: ImportOCRModelsRequestInput;response: { "code": 0; "data": OCRModel; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -3327,6 +3343,18 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 重新验证用户确认的候选,备份认证后的原始密文后整批删除。+ * 失败补偿恢复源文件,未提交的中断批次在启动同步前恢复;清理历史只索引脱敏元数据。+ * 不改变现有全局清理行为,不修改加密格式,不生成全局资源索引或明文缓存。+ */+ "/api/asset/removeUnusedEncryptedBoxAssets": {+ request: RemoveEncryptedBoxAssetsRequestInput;+ response: { "code": 0; "data": AssetPathsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin","writable"];+ };/*** 重命名普通笔记本资源,并同步字面量及百分号编码的文档、数据库引用。* 引用及成功返回的 data.newPath 保留查询参数和片段;源资源解析失败返回 code=-1 和 5000 毫秒错误提示。diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.mdindex 39ee41147a..54030aba26 100644--- a/docs/ENCRYPTED-NOTEBOOK.md+++ b/docs/ENCRYPTED-NOTEBOOK.md@@ -96,7 +96,7 @@ An encrypted notebook is an island; some features are unsupported because of the- Asset file rename: Encrypted-notebook asset filenames are already desensitized to `uuid-blockID.ext`; the disk filename participates in AAD, so renaming requires re-enveloping the whole asset-- Unused asset cleanup: Encrypted-notebook assets are excluded from global unused-asset cleanup (island, assets do not cross boundaries), preventing false deletion when locked and document references cannot be scanned+- Unused asset cleanup: Encrypted-notebook assets remain excluded from global cleanup. An unlocked notebook has its own Document panel - Notebook - More - Clean up unreferenced assets entry, with scanning and deletion restricted to that notebook- Unused database cleanup: Encrypted-notebook database definitions are excluded from global unused-database cleanup, preventing false deletion when locked and reference relationships cannot be confirmed@@ -461,7 +461,9 @@ The global configuration lock is acquired before any notebook lifecycle lock. AnText recognition (OCR) is not supported for assets in encrypted notebooks, regardless of lock state. Manual recognition returns a localized "unsupported" message, and automatic recognition skips encrypted-notebook assets. No OCR text may be generated for these assets or written to the global OCR store or search index.-Unsupported publishing, flashcards, bookmarks, tags, asset rename, unused-asset cleanup, and unused-database cleanup must be handled uniformly by the frontend, HTTP API, plugin API, MCP, and import paths: return an explicit "unsupported" error for encrypted-notebook targets and create no global index, global attribute, or deferred task. Existing legacy data must not be loaded, aggregated, or written back. Publish authorization is independent of lock state and takes precedence over `publishAccess.json`; existing publish configuration cannot make an encrypted notebook visible again. Error codes and localized messages remain stable for callers.+Unsupported publishing, flashcards, bookmarks, tags, asset rename, global unused-asset cleanup, and unused-database cleanup must be handled uniformly by the frontend, HTTP API, plugin API, MCP, and import paths: return an explicit "unsupported" error for encrypted-notebook targets and create no global index, global attribute, or deferred task. Existing legacy data must not be loaded, aggregated, or written back. Publish authorization is independent of lock state and takes precedence over `publishAccess.json`; existing publish configuration cannot make an encrypted notebook visible again. Error codes and localized messages remain stable for callers.++The dedicated `/api/asset/getUnusedEncryptedBoxAssets` and `/api/asset/removeUnusedEncryptedBoxAssets` endpoints require an explicit unlocked encrypted notebook. The scan authenticates all notebook documents and database definitions, includes static agent-session and tool-attachment references, and protects a referenced PDF's `.sya` companion. Any read, authentication, parsing, or traversal failure aborts the scan. Deletion revalidates only the confirmed candidates while coordinating notebook admission, editing transactions, and synchronization; active competing requests require a retry. Ciphertext is authenticated and completely backed up before removal. Failure restores source files; uncommitted cleanup journals under the workspace's `.siyuan/asset-cleanup/` are recovered before startup synchronization. Historical ciphertext keeps its original format and basename. The existing global history index may store desensitized filenames, paths, and timestamps, including after locking, but never original filenames or plaintext contents. No global asset-content index, OCR data, or plaintext cache is populated.A rejection must state the concrete reason and the available remedy, and one generic message must not cover unrelated reasons: importing a `.sy.zip` that contains flashcards must name the affected documents or deck and point to removing the flashcards in the source notebook or importing into a regular notebook; a locked notebook must ask for unlocking; a cross-boundary move or reference must explain that an encrypted notebook is an isolated space instead of returning "operation not supported".diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.mdindex 18d3f12cb8..45da623fee 100644--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md@@ -96,7 +96,7 @@- 资源文件重命名:加密笔记本的 asset 文件名已脱敏为 `uuid-blockID.ext`,磁盘文件名参与 AAD,重命名需要重新封装整个资源-- 未引用资源清理:加密笔记本的资源不参与全局未引用清理(孤岛,资源不跨边界),避免锁定时因无法扫描文档引用而误删+- 未引用资源清理:加密笔记本的资源仍不参与全局清理。已解锁笔记本提供独立的 文档面板 - 笔记本 - 更多 - 清理未引用资源 入口,扫描与删除严格限定在当前笔记本内- 未引用数据库清理:加密笔记本的数据库定义不参与全局未引用清理,避免锁定时因无法确认引用关系而误删@@ -461,7 +461,9 @@ assets 加密:加密笔记本中的资源文件不支持文字识别(OCR),与解锁状态无关。手动识别返回本地化的“不支持”提示,自动识别跳过加密笔记本资源;不得为这些资源生成 OCR 文本或写入全局 OCR 存储和搜索索引。-不支持的发布、闪卡、书签、标签、资源重命名、未使用资源清理和未使用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。发布访问判定必须独立于锁定状态并优先于 `publishAccess.json`,已存在的发布配置不得使加密笔记本重新可见。错误码和本地化文案应稳定,供调用方识别。+不支持的发布、闪卡、书签、标签、资源重命名、全局未引用资源清理和未引用数据库清理,必须在前端、HTTP API、插件 API、MCP 和导入流程中一致处理:对加密笔记本目标返回明确的“不支持”错误,不创建全局索引、全局属性或延迟任务;已有遗留数据不得被加载、聚合或写回。发布访问判定必须独立于锁定状态并优先于 `publishAccess.json`,已存在的发布配置不得使加密笔记本重新可见。错误码和本地化文案应稳定,供调用方识别。++专用接口 `/api/asset/getUnusedEncryptedBoxAssets` 和 `/api/asset/removeUnusedEncryptedBoxAssets` 必须显式指定一个已解锁的加密笔记本。扫描认证该笔记本的全部文档与数据库定义,包含智能体会话和工具附件中的静态引用,并保护被引用 PDF 的 `.sya` 伴生文件。任意读取、认证、解析或目录遍历失败都会中止扫描。删除时只重新验证用户确认的候选,同时协调笔记本准入、编辑事务和同步;存在其他活动请求时需重试。资源密文完成认证和整批备份后才开始删除。失败时恢复原文件;启动同步前恢复工作空间 `.siyuan/asset-cleanup/` 下未提交的清理日志。历史密文保留原格式和稳定基名。既有全局历史索引可记录脱敏文件名、路径和时间,锁定后仍保留这些元数据,但不得记录原始文件名或明文内容。不生成全局资源内容索引、OCR 数据或明文缓存。拒绝操作时必须说明具体原因和可行的处理方式,不得用同一句笼统文案覆盖互不相关的原因:例如导入带闪卡的 `.sy.zip` 时,应指出命中闪卡的文档或牌组,并提示在源笔记本移除闪卡后重新导出或改为导入普通笔记本;未解锁时应提示解锁;跨加密边界移动或引用时应说明加密笔记本是隔离空间,而不是返回“不支持该操作”。diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex c3151458ff..26d2ac720a 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -362,6 +362,28 @@ var getUnusedAssets = contractHandler(apicontract.GetUnusedAssets, func(c *gin.Creturn apicontract.Success(assetUnusedItems(unusedAssets))})+var getUnusedEncryptedBoxAssets = contractHandler(apicontract.GetUnusedEncryptedBoxAssets, func(c *gin.Context, request apicontract.EncryptedBoxAssetsRequest) apicontract.Response[[]*apicontract.AssetUnusedItem] {+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {+ return apicontract.Failure[[]*apicontract.AssetUnusedItem](-1, model.Conf.Language(314))+ }+ items, err := model.UnusedEncryptedBoxAssets(c.Request.Context(), request.Notebook)+ if err != nil {+ return apicontract.Failure[[]*apicontract.AssetUnusedItem](-1, err.Error())+ }+ return apicontract.Success(assetUnusedItems(items))+})++var removeUnusedEncryptedBoxAssets = contractHandler(apicontract.RemoveUnusedEncryptedBoxAssets, func(c *gin.Context, request apicontract.RemoveEncryptedBoxAssetsRequest) apicontract.Response[apicontract.AssetPathsData] {+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {+ return apicontract.Failure[apicontract.AssetPathsData](-1, model.Conf.Language(314))+ }+ paths, err := model.RemoveUnusedEncryptedBoxAssets(c.Request.Context(), request.Notebook, request.Paths)+ if err != nil {+ return apicontract.Failure[apicontract.AssetPathsData](-1, err.Error())+ }+ return apicontract.Success(apicontract.AssetPathsData{Paths: paths})+})+var getMissingAssets = contractHandler(apicontract.GetMissingAssets, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[[]*apicontract.AssetUnusedItem] {missingAssets := model.MissingAssets()diff --git a/kernel/api/contract_encrypted_assets_cleanup_test.go b/kernel/api/contract_encrypted_assets_cleanup_test.gonew file mode 100644index 0000000000..cfb0781215--- /dev/null+++ b/kernel/api/contract_encrypted_assets_cleanup_test.go@@ -0,0 +1,160 @@+package api++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractEncryptedAssetCleanupAdmission(t *testing.T) {+ _, boxID := setupArchiveWorkspace(t)+ previous := model.Conf+ model.Conf = model.NewAppConf()+ t.Cleanup(func() { model.Conf = previous })+ engine := gin.New()+ engine.POST("/api/asset/getUnusedEncryptedBoxAssets", getUnusedEncryptedBoxAssets)+ engine.POST("/api/asset/removeUnusedEncryptedBoxAssets", removeUnusedEncryptedBoxAssets)+ for _, endpoint := range []string{"getUnusedEncryptedBoxAssets", "removeUnusedEncryptedBoxAssets"} {+ url := "/api/asset/" + endpoint+ for _, notebook := range []string{boxID, "", "../assets"} {+ body := `{"notebook":"` + notebook + `","paths":[]}`+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", url, strings.NewReader(body)))+ requireAPIContract(t, "POST", url, recorder)+ var response struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data json.RawMessage `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != -1 || string(response.Data) != "null" {+ t.Fatalf("invalid cleanup admission: %s, %v", recorder.Body.String(), err)+ }+ if notebook == boxID && response.Msg != model.Conf.Language(314) {+ t.Fatalf("locked notebook message changed: %s", response.Msg)+ }+ }+ }+}++func TestAPIContractEncryptedAssetCleanupRoundTrip(t *testing.T) {+ const child = "SIYUAN_TEST_ENCRYPTED_ASSET_CLEANUP"+ if os.Getenv(child) != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAPIContractEncryptedAssetCleanupRoundTrip$", "-test.timeout=55s", "-test.v")+ cmd.Env = append(os.Environ(), child+"=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("isolated encrypted asset API test: %v\n%s", err, output)+ }+ return+ }+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "conf"), filepath.Join(root, "history")+ util.QueueDir = filepath.Join(util.TempDir, "queue")+ util.DBPath, util.HistoryDBPath = filepath.Join(util.TempDir, util.DBName), filepath.Join(util.TempDir, "history.db")+ util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, "asset_content.db"), filepath.Join(util.TempDir, "blocktree.db")+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir} {+ if err := os.MkdirAll(dir, 0700); err != nil {+ t.Fatal(err)+ }+ }+ model.Conf = model.NewAppConf()+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Export.Store(conf.NewExport())+ model.Conf.Search.Store(conf.NewSearch())+ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ defer sql.CloseDatabase()+ if err := model.EnableEncryptedNotebook("cleanup-test-password"); err != nil {+ t.Fatal(err)+ }+ boxID, err := model.CreateEncryptedBox("Cleanup", "cleanup-test-password")+ if err != nil {+ t.Fatal(err)+ }+ defer model.LockBox(boxID)+ dek, err := model.GetDEKIfUnlocked(boxID)+ if err != nil {+ t.Fatal(err)+ }+ defer clear(dek)+ ciphertext, err := model.EncryptAsset(boxID, "unused.png", "private-name.png", dek, []byte("private-content"))+ if err != nil {+ t.Fatal(err)+ }+ asset := filepath.Join(util.DataDir, boxID, "assets", "unused.png")+ if err = os.MkdirAll(filepath.Dir(asset), 0700); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(asset, ciphertext, 0600); err != nil {+ t.Fatal(err)+ }+ engine := gin.New()+ engine.Use(boxLeaseMiddleware)+ engine.POST("/api/asset/getUnusedEncryptedBoxAssets", getUnusedEncryptedBoxAssets)+ engine.POST("/api/asset/removeUnusedEncryptedBoxAssets", removeUnusedEncryptedBoxAssets)+ call := func(endpoint, body string) []byte {+ t.Helper()+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", endpoint, strings.NewReader(body)))+ requireAPIContract(t, "POST", endpoint, recorder)+ return recorder.Body.Bytes()+ }+ var listed struct {+ Code int `json:"code"`+ Data []*apicontract.AssetUnusedItem `json:"data"`+ }+ data := call("/api/asset/getUnusedEncryptedBoxAssets", `{"notebook":"`+boxID+`"}`)+ if err = json.Unmarshal(data, &listed); err != nil || listed.Code != 0 || len(listed.Data) != 1 || listed.Data[0].Name != "private-name.png" {+ t.Fatalf("scoped scan response: %s, %v", data, err)+ }+ var removed struct {+ Code int `json:"code"`+ Data apicontract.AssetPathsData `json:"data"`+ }+ data = call("/api/asset/removeUnusedEncryptedBoxAssets", `{"notebook":"`+boxID+`","paths":["assets/unused.png"]}`)+ if err = json.Unmarshal(data, &removed); err != nil || removed.Code != 0 || len(removed.Data.Paths) != 1 {+ t.Fatalf("scoped cleanup response: %s, %v", data, err)+ }+ if _, err = os.Stat(asset); !os.IsNotExist(err) {+ t.Fatal("cleanup did not remove the confirmed resource")+ }+ history, _ := filepath.Glob(filepath.Join(util.HistoryDir, "*-clean", boxID, "assets", "unused.png"))+ if len(history) != 1 {+ t.Fatalf("missing history: %v", history)+ }+ stored, err := os.ReadFile(history[0])+ if err != nil || !bytes.Equal(stored, ciphertext) {+ t.Fatal("cleanup history did not preserve ciphertext")+ }+ sql.FlushHistoryQueue()+ rows, err := sql.QueryHistory("SELECT title, content, path FROM histories_fts_case_insensitive")+ if err != nil || len(rows) != 1 || rows[0]["title"] != "unused.png" || rows[0]["content"] != "" ||+ !strings.Contains(rows[0]["path"].(string), "/"+boxID+"/assets/unused.png") {+ t.Fatalf("unexpected global history metadata: %v, %v", rows, err)+ }+ model.LockBox(boxID)+ rows, err = sql.QueryHistory("SELECT title, content FROM histories_fts_case_insensitive")+ if err != nil || len(rows) != 1 || rows[0]["title"] != "unused.png" || rows[0]["content"] != "" {+ t.Fatalf("locking changed metadata retention: %v, %v", rows, err)+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 7c323bdd82..8104229645 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -587,6 +587,8 @@ func registerAssetRoutes(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/asset/setFileAnnotation", contractRouteHandlers(apicontract.SetFileAnnotation, setFileAnnotation)...)ginServer.Handle("POST", "/api/asset/getFileAnnotation", contractRouteHandlers(apicontract.GetFileAnnotation, getFileAnnotation)...)ginServer.Handle("POST", "/api/asset/getUnusedAssets", contractRouteHandlers(apicontract.GetUnusedAssets, getUnusedAssets)...)+ ginServer.Handle("POST", "/api/asset/getUnusedEncryptedBoxAssets", contractRouteHandlers(apicontract.GetUnusedEncryptedBoxAssets, getUnusedEncryptedBoxAssets)...)+ ginServer.Handle("POST", "/api/asset/removeUnusedEncryptedBoxAssets", contractRouteHandlers(apicontract.RemoveUnusedEncryptedBoxAssets, removeUnusedEncryptedBoxAssets)...)ginServer.Handle("POST", "/api/asset/getMissingAssets", contractRouteHandlers(apicontract.GetMissingAssets, getMissingAssets)...)ginServer.Handle("POST", "/api/asset/removeUnusedAsset", contractRouteHandlers(apicontract.RemoveUnusedAsset, removeUnusedAsset)...)ginServer.Handle("POST", "/api/asset/removeUnusedAssets", contractRouteHandlers(apicontract.RemoveUnusedAssets, removeUnusedAssets)...)diff --git a/kernel/apicontract/asset.go b/kernel/apicontract/asset.goindex c025b55553..cf356b2ab3 100644--- a/kernel/apicontract/asset.go+++ b/kernel/apicontract/asset.go@@ -12,6 +12,18 @@ type AssetPathRequest struct {Path string `json:"path"`}+// EncryptedBoxAssetsRequest 只接受当前已解锁的加密笔记本,不回退到全局资源。+type EncryptedBoxAssetsRequest struct {+ Notebook string `json:"notebook"`+}++// RemoveEncryptedBoxAssetsRequest 仅删除用户确认的 assets 相对路径,空列表不删除任何资源。+// 删除前完整重新扫描;新增引用或任意读取、认证、解析错误均中止整批操作。+type RemoveEncryptedBoxAssetsRequest struct {+ Notebook string `json:"notebook"`+ Paths []string `json:"paths"`+}+type AssetOCRTextRequest struct {Path *string `json:"path" api:"optional"`}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex fde5455a81..91e53eaef9 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1083,6 +1083,16 @@ var RemoveUnusedAssets = define[EmptyRequest, AssetPathsData]("removeUnusedAsset// 扫描失败返回标准错误,不将失败表示为成功的空列表。// 可选请求头 X-SiYuan-App-ID 将截断提示限定到对应前端,未提供时保留广播行为。var GetUnusedAssets = define[EmptyRequest, []*AssetUnusedItem]("getUnusedAssets", "/api/asset/getUnusedAssets", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")++// GetUnusedEncryptedBoxAssets 扫描单个已解锁加密笔记本的文档、全部数据库定义及智能体会话引用。+// 任意扫描失败返回 -1,不返回不完整候选。锁定目标使用既有 314 语言消息;结果不截断。+// name 为响应期间可见的原始文件名,item 为 assets 相对路径,path 带目标 box 查询参数。+var GetUnusedEncryptedBoxAssets = define[EncryptedBoxAssetsRequest, []*AssetUnusedItem]("getUnusedEncryptedBoxAssets", "/api/asset/getUnusedEncryptedBoxAssets", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")++// RemoveUnusedEncryptedBoxAssets 重新验证用户确认的候选,备份认证后的原始密文后整批删除。+// 失败补偿恢复源文件,未提交的中断批次在启动同步前恢复;清理历史只索引脱敏元数据。+// 不改变现有全局清理行为,不修改加密格式,不生成全局资源索引或明文缓存。+var RemoveUnusedEncryptedBoxAssets = define[RemoveEncryptedBoxAssetsRequest, AssetPathsData]("removeUnusedEncryptedBoxAssets", "/api/asset/removeUnusedEncryptedBoxAssets", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var GetMissingAssets = define[EmptyRequest, []*AssetUnusedItem]("getMissingAssets", "/api/asset/getMissingAssets", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")// ResolveAssetPath 返回普通资源路径;已解锁的加密资源返回保留原始名称的受管临时明文副本路径。diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 8dd11586f6..ca2cf84155 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -23225,6 +23225,18 @@"type": "object","additionalProperties": false},+ "EncryptedBoxAssetsRequestInput": {+ "type": "object",+ "properties": {+ "notebook": {+ "type": "string"+ }+ },+ "required": [+ "notebook"+ ],+ "additionalProperties": false+ },"EncryptedNotebookFollowSystemLockRequestInput": {"type": "object","properties": {@@ -36005,6 +36017,25 @@],"additionalProperties": false},+ "RemoveEncryptedBoxAssetsRequestInput": {+ "type": "object",+ "properties": {+ "notebook": {+ "type": "string"+ },+ "paths": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "notebook",+ "paths"+ ],+ "additionalProperties": false+ },"RemoveFileRequestInput": {"type": "object","properties": {@@ -124741,6 +124772,102 @@]}},+ {+ "method": "POST",+ "path": "/api/asset/getUnusedEncryptedBoxAssets",+ "handler": "getUnusedEncryptedBoxAssets",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/EncryptedBoxAssetsRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AssetUnusedItem"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },{"method": "POST","path": "/api/asset/importOCRModels",@@ -125307,6 +125434,86 @@]}},+ {+ "method": "POST",+ "path": "/api/asset/removeUnusedEncryptedBoxAssets",+ "handler": "removeUnusedEncryptedBoxAssets",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/RemoveEncryptedBoxAssetsRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AssetPathsData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },{"method": "POST","path": "/api/asset/renameAsset",diff --git a/kernel/av/av.go b/kernel/av/av.goindex 6821a7b45b..8cd30ab56d 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -1092,6 +1092,11 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {// 缓存与待写入数据一致时跳过落盘;缓存未命中时再读盘比对,避免无变更的重复写入// 通过 fallback 查找 AV 定义的实际路径(普通 box 全局,加密笔记本笔记本级)avJSONPath, avBoxID := FindAttributeViewPath(av.ID)+ releaseBox, lockErr := holdAVBoxReadLock(avBoxID)+ if lockErr != nil {+ return lockErr+ }+ defer releaseBox()if avJSONPath == "" {// 文件不存在(首次创建),使用全局路径,boxID 为空(普通 box)// 加密笔记本的首次创建由 handler 层通过 SetAVBoxID 预设路径@@ -1119,7 +1124,7 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {if diskData, readErr := filelock.ReadFile(avJSONPath); nil == readErr {// 加密笔记本的磁盘数据是密文,需先解密再比对if avBoxID != "" {- diskData, _ = decryptAVData(avBoxID, av.ID, diskData)+ diskData, _ = decryptAVDataLocked(avBoxID, av.ID, diskData)}if len(diskData) == len(data) && bytes.Equal(diskData, data) {cacheAttributeViewData(av, avBoxID, data)@@ -1131,7 +1136,7 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {// 加密笔记本的数据需加密后再写盘writeData := dataif avBoxID != "" {- writeData, err = encryptAVData(avBoxID, av.ID, data)+ writeData, err = encryptAVDataLocked(avBoxID, av.ID, data)if err != nil {logging.LogErrorf("encrypt attribute view [%s] failed: %s", av.ID, err)returndiff --git a/kernel/av/encrypted_hook.go b/kernel/av/encrypted_hook.goindex 9cb98fa150..3a28504d09 100644--- a/kernel/av/encrypted_hook.go+++ b/kernel/av/encrypted_hook.go@@ -295,6 +295,14 @@ func encryptAVData(boxID, avID string, data []byte) ([]byte, error) {AVLockAcquire(boxID)defer AVLockRelease(boxID)}+ return encryptAVDataLocked(boxID, avID, data)+}++// encryptAVDataLocked 在调用方持有笔记本读锁时加密数据库定义。+func encryptAVDataLocked(boxID, avID string, data []byte) ([]byte, error) {+ if AVDEKProvider == nil {+ return data, nil+ }dek, err := AVDEKProvider(boxID)if err != nil {return nil, err // 加密但未解锁,拒绝写盘避免明文泄漏@@ -303,6 +311,7 @@ func encryptAVData(boxID, avID string, data []byte) ([]byte, error) {return data, nil // 非加密 box}avKey := util.DeriveSubKey(dek, "siyuan/av")+ defer clear(avKey)aad := avAAD(boxID, avID)return util.EncryptWithAAD(avKey, data, []byte(aad))}@@ -329,7 +338,13 @@ func decryptAVDataLocked(boxID, avID string, data []byte) ([]byte, error) {if dek == nil {return data, nil // 非加密 box}+ return DecryptAVDataWithDEK(boxID, avID, dek, data)+}++// DecryptAVDataWithDEK 使用已取得的密钥认证数据库定义,不重新取得笔记本锁或发布明文缓存。+func DecryptAVDataWithDEK(boxID, avID string, dek, data []byte) ([]byte, error) {avKey := util.DeriveSubKey(dek, "siyuan/av")+ defer clear(avKey)aad := avAAD(boxID, avID)return util.DecryptWithAAD(avKey, data, []byte(aad))}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 5ab01c4406..0ddf59adfc 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -2613,6 +2613,14 @@ func getAssetsLinkDestsWithAttributeViewItemFilter(includeServePath bool,itemFilter attributeViewItemFilter,normalize ...func(string) string,+) (ret []string) {+ return getAssetsLinkDestsWithOptions(node, includeServePath, itemFilter, true, normalize...)+}++// getAssetsLinkDestsWithOptions 允许独立扫描数据库定义的调用方关闭节点中的数据库加载。+func getAssetsLinkDestsWithOptions(+ node *ast.Node, includeServePath bool, itemFilter attributeViewItemFilter, resolveAttributeViews bool,+ normalize ...func(string) string,) (ret []string) {ret = []string{}treenode.WalkWithInlineTitles(node, func(n *ast.Node, entering bool) ast.WalkStatus {@@ -2664,6 +2672,9 @@ func getAssetsLinkDestsWithAttributeViewItemFilter(ret = append(ret, dest)}} else if ast.NodeAttributeView == n.Type {+ if !resolveAttributeViews {+ return ast.WalkContinue+ }attrView, _ := av.ParseAttributeView(n.AttributeViewID)if nil == attrView {return ast.WalkContinuediff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 0b1169fc8c..e75d53ec45 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -276,6 +276,9 @@ func (conf *AppConf) SetUser(user *conf.User) {}func InitConf() {+ if err := recoverEncryptedAssetCleanupOperations(); err != nil {+ logging.LogFatalf(logging.ExitCodeFileSysErr, "recover encrypted asset cleanup failed: %s", err)+ }initLang()if err := recoverSettingsReset(); err != nil {logging.LogFatalf(logging.ExitCodeFileSysErr, "recover settings reset failed: %s", err)diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex 5cf88099f4..a71c2aa47f 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -197,6 +197,11 @@ func acquireBoxWriteLock(boxID string) {muI.(*sync.RWMutex).Lock()}+func tryAcquireBoxWriteLock(boxID string) bool {+ muI, _ := boxLifecycleLocks.LoadOrStore(boxID, &sync.RWMutex{})+ return muI.(*sync.RWMutex).TryLock()+}+func releaseBoxWriteLock(boxID string) {if muI, ok := boxLifecycleLocks.Load(boxID); ok {muI.(*sync.RWMutex).Unlock()diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.goindex 3ff822472a..f9e47ac4a1 100644--- a/kernel/model/crypto_lifecycle.go+++ b/kernel/model/crypto_lifecycle.go@@ -54,6 +54,7 @@ type encryptedBoxLifecycle struct {state EncryptedBoxStateacceptOperations boolactiveOperations int+ assetCleanup bool}func holdEncryptedBoxTransition(boxID string) func() {@@ -154,6 +155,9 @@ func AcquireEncryptedBoxOperation(boxID string) error {lifecycle := getEncryptedBoxLifecycle(boxID)lifecycle.lock.Lock()defer lifecycle.lock.Unlock()+ for lifecycle.assetCleanup && lifecycle.state == EncryptedBoxStateUnlocked {+ lifecycle.condition.Wait()+ }if lifecycle.state == EncryptedBoxStateLocked && IsBoxUnlocked(boxID) {lifecycle.state = EncryptedBoxStateUnlockedlifecycle.acceptOperations = truediff --git a/kernel/model/encrypted_assets_cleanup.go b/kernel/model/encrypted_assets_cleanup.gonew file mode 100644index 0000000000..7eb487d1b4--- /dev/null+++ b/kernel/model/encrypted_assets_cleanup.go@@ -0,0 +1,766 @@+package model++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "net/url"+ "os"+ "path"+ "path/filepath"+ "sort"+ "strings"+ "time"++ "github.com/88250/lute"+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/dataparser"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/av"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// UnusedEncryptedBoxAssets 只扫描目标加密笔记本,明文解析结果不写入全局缓存。+func UnusedEncryptedBoxAssets(ctx context.Context, boxID string) (items []*UnusedItem, err error) {+ err = withEncryptedAssetCleanup(ctx, boxID, func(dek []byte) error {+ items, err = scanEncryptedBoxUnusedAssets(ctx, boxID, dek)+ return err+ })+ return+}++// RemoveUnusedEncryptedBoxAssets 重新扫描用户确认的候选,完整备份后删除,失败时恢复全部原文件。+func RemoveUnusedEncryptedBoxAssets(ctx context.Context, boxID string, paths []string) (removed []string, err error) {+ removed = []string{}+ err = withEncryptedAssetCleanup(ctx, boxID, func(dek []byte) error {+ inventory, inventoryErr := encryptedCleanupSourceDigest(ctx, boxID)+ if inventoryErr != nil {+ return inventoryErr+ }+ items, scanErr := scanEncryptedBoxUnusedAssets(ctx, boxID, dek)+ if scanErr != nil {+ return scanErr+ }+ candidates := map[string]*UnusedItem{}+ for _, item := range items {+ candidates[item.Item] = item+ }+ selected := []*UnusedItem{}+ seen := map[string]bool{}+ for _, p := range paths {+ item := candidates[p]+ if item == nil {+ return fmt.Errorf("asset is not unused in notebook [%s]: %s", boxID, p)+ }+ if !seen[p] {+ selected = append(selected, item)+ seen[p] = true+ }+ }+ if len(selected) == 0 {+ return nil+ }+ verify := func() error {+ current, readErr := encryptedCleanupSourceDigest(ctx, boxID)+ if readErr != nil {+ return readErr+ }+ if current != inventory || txQueueSize() != 0 {+ return errors.New("asset references changed during cleanup; retry the request")+ }+ return nil+ }+ if err := deleteEncryptedBoxAssets(ctx, boxID, dek, selected, os.Remove, verify); err != nil {+ return err+ }+ for _, item := range selected {+ removed = append(removed, item.Item)+ }+ IncSync()+ return nil+ })+ return+}++// encryptedCleanupSourceDigest 校验完整引用源集合,包含扫描过程中新增或修改的智能体会话。+func encryptedCleanupSourceDigest(ctx context.Context, boxID string) (string, error) {+ hash := sha256.New()+ boxRoot := filepath.Join(util.DataDir, boxID)+ roots := []string{boxRoot, filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions")}+ for _, root := range roots {+ err := walkEncryptedCleanupFiles(ctx, root, root != boxRoot, func(p string, entry fs.DirEntry) error {+ rel, _ := filepath.Rel(root, p)+ if root == boxRoot && entry.IsDir() && (entry.Name() == "assets" || strings.HasPrefix(entry.Name(), ".")) {+ return filepath.SkipDir+ }+ if entry.IsDir() {+ fmt.Fprintln(hash, root, rel)+ return nil+ }+ if root == boxRoot && !strings.HasSuffix(entry.Name(), ".sy") &&+ !(strings.HasPrefix(filepath.ToSlash(rel), "storage/av/") && strings.HasSuffix(entry.Name(), ".json")) {+ return nil+ }+ if root != boxRoot && entry.Name() != "session.json" && entry.Name() != "runtime.json" {+ return nil+ }+ data, readErr := os.ReadFile(p)+ if readErr != nil {+ return readErr+ }+ fmt.Fprintln(hash, rel, sha256.Sum256(data))+ return nil+ })+ if err != nil {+ return "", err+ }+ }+ return hex.EncodeToString(hash.Sum(nil)), nil+}++// withEncryptedAssetCleanup 排空已提交编辑,并串行化同步、事务和目标笔记本的持久化读写。+// 先取得密钥副本,再持笔记本写锁;锁内只解析磁盘快照,不重入读锁或发布明文缓存。+func withEncryptedAssetCleanup(ctx context.Context, boxID string, operation func([]byte) error) (err error) {+ if !ast.IsNodeIDPattern(boxID) || !IsEncryptedBox(boxID) {+ return errors.New("an encrypted notebook ID is required")+ }+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ return errors.New(Conf.Language(314))+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ if err := lockAssetRelink(ctx, &syncLock); err != nil {+ return err+ }+ defer syncLock.Unlock()+ FlushTxQueue()+ if err := lockAssetRelink(ctx, &flushLock); err != nil {+ return err+ }+ defer flushLock.Unlock()+ if txQueueSize() != 0 {+ return errors.New(Conf.Language(239))+ }+ dek, err := GetDEKIfUnlocked(boxID)+ if err != nil {+ return errors.New(Conf.Language(314))+ }+ defer zeroAndClear(dek)+ releaseAdmission, err := admitEncryptedAssetCleanup(boxID)+ if err != nil {+ return err+ }+ defer releaseAdmission()+ if !tryAcquireBoxWriteLock(boxID) {+ return errors.New(Conf.Language(239))+ }+ defer func() {+ releaseBoxWriteLock(boxID)+ if errors.Is(err, errEncryptedAssetCleanupRecovery) {+ setEncryptedBoxState(boxID, EncryptedBoxStateError)+ }+ }()+ if err = recoverEncryptedAssetCleanup(boxID); err != nil {+ return err+ }+ return operation(dek)+}++// admitEncryptedAssetCleanup 暂停新请求,已有读写冲突时由笔记本写锁立即拒绝清理,避免读锁重入死锁。+func admitEncryptedAssetCleanup(boxID string) (func(), error) {+ lifecycle := getEncryptedBoxLifecycle(boxID)+ lifecycle.lock.Lock()+ defer lifecycle.lock.Unlock()+ if lifecycle.assetCleanup {+ return nil, errors.New(Conf.Language(239))+ }+ lifecycle.assetCleanup = true+ return func() {+ lifecycle.lock.Lock()+ lifecycle.assetCleanup = false+ lifecycle.condition.Broadcast()+ lifecycle.lock.Unlock()+ }, nil+}++func walkEncryptedCleanupFiles(ctx context.Context, root string, optional bool, visit func(string, fs.DirEntry) error) error {+ return filepath.WalkDir(root, func(p string, entry fs.DirEntry, walkErr error) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ if walkErr != nil {+ if optional && p == root && errors.Is(walkErr, os.ErrNotExist) {+ return nil+ }+ return walkErr+ }+ if entry.Type()&os.ModeSymlink != 0 {+ return fmt.Errorf("symbolic links are not supported during encrypted asset cleanup: %s", p)+ }+ if p == root && !entry.IsDir() {+ return fmt.Errorf("asset reference scan root must be a directory: %s", p)+ }+ return visit(p, entry)+ })+}++func scanEncryptedBoxUnusedAssets(ctx context.Context, boxID string, dek []byte) (ret []*UnusedItem, err error) {+ defer func() {+ if recovered := recover(); recovered != nil {+ ret, err = nil, fmt.Errorf("scan encrypted asset references failed: %v", recovered)+ }+ }()+ root := filepath.Join(util.DataDir, boxID)+ for _, p := range []string{root, filepath.Join(root, "assets"), filepath.Join(root, "storage", "av")} {+ if err = validateEncryptedCleanupPath(util.DataDir, p); err != nil {+ return nil, err+ }+ }+ assets := map[string]string{}+ assetRoot := filepath.Join(root, "assets")+ err = walkEncryptedCleanupFiles(ctx, assetRoot, true, func(p string, entry fs.DirEntry) error {+ if entry.IsDir() {+ if p == assetRoot {+ return nil+ }+ if isSkipFile(entry.Name()) || filelock.IsHidden(p) {+ return filepath.SkipDir+ }+ key, keyErr := assetPathMapKey(assetRoot, p, true)+ if keyErr == nil {+ assets[key] = p+ }+ return keyErr+ }+ if !entry.Type().IsRegular() {+ return fmt.Errorf("asset must be a regular file: %s", p)+ }+ if isSkipFile(entry.Name()) || filelock.IsHidden(p) {+ return nil+ }+ key, keyErr := assetPathMapKey(assetRoot, p, false)+ if keyErr == nil {+ assets[key] = p+ }+ return keyErr+ })+ if err != nil {+ return nil, err+ }+ luteEngine := util.NewLute()+ dests := map[string]bool{}+ collect := func(dest string) {+ if parsed, parseErr := url.Parse(dest); parseErr == nil {+ if box := parsed.Query().Get("box"); box != "" && box != boxID {+ return+ }+ }+ if normalized := normalizeAssetScanLinkDest(dest); normalized != "" {+ dests[normalized] = true+ }+ }+ err = walkEncryptedCleanupFiles(ctx, root, false, func(p string, entry fs.DirEntry) error {+ if entry.IsDir() {+ if p != root && (isSkipFile(entry.Name()) || entry.Name() == "assets" || entry.Name() == "storage") {+ return filepath.SkipDir+ }+ return nil+ }+ if !strings.HasSuffix(entry.Name(), ".sy") {+ return nil+ }+ data, readErr := os.ReadFile(p)+ if readErr != nil {+ return readErr+ }+ relative, _ := filepath.Rel(root, p)+ plain, decryptErr := DecryptFile(boxID, filepath.ToSlash(relative), dek, data)+ if decryptErr != nil {+ return decryptErr+ }+ defer clear(plain)+ if specErr := treenode.CheckSpecJSON(plain); specErr != nil {+ return specErr+ }+ tree, _, parseErr := dataparser.ParseJSON(plain, luteEngine.ParseOptions)+ if parseErr != nil {+ return parseErr+ }+ if tree == nil || tree.Root == nil || tree.Root.ID+".sy" != entry.Name() {+ return fmt.Errorf("document ID does not match its basename: %s", p)+ }+ if specErr := treenode.CheckSpec(tree); specErr != nil {+ return specErr+ }+ if projectionErr := treenode.RefreshTableCellRichProjection(tree.Root); projectionErr != nil {+ return projectionErr+ }+ for _, dest := range getAssetsLinkDestsWithOptions(tree.Root, false, nil, false, normalizeAssetScanLinkDest) {+ collect(dest)+ }+ collect(treenode.GetDocTitleImgPath(tree.Root))+ return nil+ })+ if err != nil {+ return nil, fmt.Errorf("read notebook asset references failed: %w", err)+ }+ err = walkEncryptedCleanupFiles(ctx, filepath.Join(root, "storage", "av"), true, func(p string, entry fs.DirEntry) error {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {+ return nil+ }+ id := strings.TrimSuffix(entry.Name(), ".json")+ if !ast.IsNodeIDPattern(id) {+ return nil+ }+ data, readErr := os.ReadFile(p)+ if readErr != nil {+ return readErr+ }+ plain, decryptErr := av.DecryptAVDataWithDEK(boxID, id, dek, data)+ if decryptErr != nil {+ return decryptErr+ }+ defer clear(plain)+ view, parseErr := av.ParseAttributeViewData(id, plain)+ if parseErr != nil {+ return parseErr+ }+ if view.ID != id {+ return fmt.Errorf("database ID does not match its basename: %s", p)+ }+ return collectEncryptedCleanupJSON(plain, luteEngine, collect)+ })+ if err != nil {+ return nil, fmt.Errorf("read notebook database references failed: %w", err)+ }+ // 会话正文、工具附件及在途轮次都可能保留资源引用;不加载其他笔记本或执行工具。+ err = walkEncryptedCleanupFiles(ctx, filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions"), true,+ func(p string, entry fs.DirEntry) error {+ if entry.IsDir() || (entry.Name() != "session.json" && entry.Name() != "runtime.json") {+ return nil+ }+ filelock.Lock(p)+ data, readErr := os.ReadFile(p)+ filelock.Unlock(p)+ if readErr != nil {+ return readErr+ }+ return collectEncryptedCleanupJSON(data, luteEngine, collect)+ })+ if err != nil {+ return nil, fmt.Errorf("read agent asset references failed: %w", err)+ }+ for _, dest := range removeReferencedAssetPaths(assets, dests) {+ if strings.HasSuffix(strings.ToLower(dest), ".pdf") {+ delete(assets, dest+".sya")+ }+ delete(assets, dest)+ }+ ret = []*UnusedItem{}+ for p, absPath := range assets {+ if strings.HasSuffix(p, "/") {+ continue+ }+ file, openErr := os.Open(absPath)+ if openErr != nil {+ return nil, openErr+ }+ name, nameErr := DecryptAssetNameFromReader(boxID, path.Base(p), dek, file)+ file.Close()+ if nameErr != nil {+ return nil, nameErr+ }+ ret = append(ret, &UnusedItem{Item: p, Name: name, Path: p + "?box=" + boxID, AbsPath: absPath})+ }+ sort.Slice(ret, func(i, j int) bool { return ret[i].Item < ret[j].Item })+ return ret, nil+}++// collectEncryptedCleanupJSON 保守收集全部持久化字符串中的资源链接,包含数据库模板、富文本与工具附件。+func collectEncryptedCleanupJSON(data []byte, luteEngine *lute.Lute, collect func(string)) error {+ var value any+ if err := json.Unmarshal(data, &value); err != nil {+ return err+ }+ var visit func(any)+ visit = func(v any) {+ switch typed := v.(type) {+ case string:+ if !strings.Contains(typed, "assets/") {+ return+ }+ collect(typed)+ tree := parse.Parse("", []byte(typed), luteEngine.ParseOptions)+ for _, dest := range getAssetsLinkDestsWithOptions(tree.Root, false, nil, false) {+ collect(dest)+ }+ case []any:+ for _, child := range typed {+ visit(child)+ }+ case map[string]any:+ for _, child := range typed {+ visit(child)+ }+ }+ }+ visit(value)+ return nil+}++type encryptedAssetCleanupFile struct {+ Path string `json:"path"`+ Hash string `json:"hash"`+}++type encryptedAssetCleanupJournal struct {+ Spec int `json:"spec"`+ Committed bool `json:"committed"`+ Files []encryptedAssetCleanupFile `json:"files"`+ Checksum string `json:"checksum"`+}++func encryptedCleanupJournalChecksum(journal *encryptedAssetCleanupJournal) string {+ copy := *journal+ copy.Checksum = ""+ data, _ := json.Marshal(©)+ hash := sha256.Sum256(data)+ return hex.EncodeToString(hash[:])+}++var errEncryptedAssetCleanupRecovery = errors.New("encrypted asset cleanup recovery is required")++func encryptedAssetCleanupDir(boxID string) string {+ return filepath.Join(util.WorkspaceDir, ".siyuan", "asset-cleanup", boxID)+}++func deleteEncryptedBoxAssets(ctx context.Context, boxID string, dek []byte, items []*UnusedItem, remove func(string) error, verify func() error) (err error) {+ journalDir := encryptedAssetCleanupDir(boxID)+ if err = os.MkdirAll(filepath.Dir(journalDir), 0700); err != nil {+ return+ }+ if err = os.Mkdir(journalDir, 0700); err != nil {+ return+ }+ journal := &encryptedAssetCleanupJournal{Spec: 1}+ deleting := false+ defer func() {+ if err != nil && deleting {+ if rollbackErr := recoverEncryptedAssetCleanup(boxID, journal); rollbackErr != nil {+ // 恢复失败后拒绝后续解密访问,保留清理日志,启动恢复完成前不进入同步。+ err = errors.Join(err, errEncryptedAssetCleanupRecovery, fmt.Errorf("restore encrypted assets failed: %w", rollbackErr))+ }+ } else if !deleting || err == nil {+ // 已提交标记保证清理日志删除失败不会撤销成功的操作。+ if cleanupErr := os.RemoveAll(journalDir); cleanupErr != nil && err == nil {+ // 下次启动或清理时继续回收已提交日志。+ return+ }+ }+ }()+ for _, item := range items {+ if err = ctx.Err(); err != nil {+ return+ }+ if err = EnsureAssetPrefixLocal(item.AbsPath); err != nil {+ return+ }+ file, openErr := os.Open(item.AbsPath)+ if openErr != nil {+ return openErr+ }+ _, err = DecryptAssetToWriter(boxID, path.Base(item.Item), dek, file, io.Discard)+ file.Close()+ if err != nil {+ return+ }+ backup := filepath.Join(journalDir, filepath.FromSlash(item.Item))+ if err = copyEncryptedCleanupFile(item.AbsPath, backup); err != nil {+ return+ }+ if err = syncEncryptedCleanupFile(backup); err != nil {+ return+ }+ hash, hashErr := encryptedCleanupFileHash(backup)+ if hashErr != nil {+ return hashErr+ }+ journal.Files = append(journal.Files, encryptedAssetCleanupFile{Path: item.Item, Hash: hash})+ }+ writeJournal := func() error {+ journal.Checksum = encryptedCleanupJournalChecksum(journal)+ data, marshalErr := json.Marshal(journal)+ if marshalErr != nil {+ return marshalErr+ }+ manifest := filepath.Join(journalDir, "manifest.json")+ return writeEncryptedCleanupData(manifest, data)+ }+ if err = writeJournal(); err != nil {+ return+ }+ if verify != nil {+ if err = verify(); err != nil {+ return+ }+ }+ var historyDir string+ if err = os.MkdirAll(util.HistoryDir, 0700); err != nil {+ return+ }+ for offset := 0; offset < 100; offset++ {+ historyDir = filepath.Join(util.HistoryDir, time.Now().Add(time.Duration(offset)*time.Second).Format("2006-01-02-150405")+"-clean")+ err = os.Mkdir(historyDir, 0700)+ if !errors.Is(err, os.ErrExist) {+ break+ }+ }+ if err != nil {+ return+ }+ for _, file := range journal.Files {+ historyPath := filepath.Join(historyDir, boxID, filepath.FromSlash(file.Path))+ if err = copyEncryptedCleanupFile(filepath.Join(journalDir, filepath.FromSlash(file.Path)), historyPath); err != nil {+ return+ }+ if err = syncEncryptedCleanupFile(historyPath); err != nil {+ return+ }+ }+ deleting = true+ for _, item := range items {+ if err = ctx.Err(); err != nil {+ return+ }+ if err = remove(item.AbsPath); err != nil {+ return+ }+ }+ if verify != nil {+ if err = verify(); err != nil {+ return+ }+ }+ journal.Committed = true+ if err = writeJournal(); err != nil {+ return+ }+ for _, item := range items {+ removeAssetThumbnail(item.AbsPath)+ }+ indexHistoryDir(filepath.Base(historyDir), util.NewLute())+ return nil+}++func encryptedCleanupFileHash(p string) (string, error) {+ file, err := os.Open(p)+ if err != nil {+ return "", err+ }+ defer file.Close()+ hash := sha256.New()+ if _, err = io.Copy(hash, file); err != nil {+ return "", err+ }+ return hex.EncodeToString(hash.Sum(nil)), nil+}++func syncEncryptedCleanupFile(p string) error {+ file, err := os.OpenFile(p, os.O_RDWR, 0)+ if err != nil {+ return err+ }+ defer file.Close()+ return file.Sync()+}++// writeEncryptedCleanupData 原子写入并刷盘已验证的数据,写入失败返回调用方进行补偿,不退出内核。+func writeEncryptedCleanupData(p string, data []byte) (err error) {+ file, err := os.CreateTemp(filepath.Dir(p), ".asset-cleanup-*.tmp")+ if err != nil {+ return err+ }+ tmp := file.Name()+ defer func() {+ file.Close()+ os.Remove(tmp)+ }()+ if _, err = file.Write(data); err != nil {+ return err+ }+ if err = file.Sync(); err != nil {+ return err+ }+ if err = file.Close(); err != nil {+ return err+ }+ return os.Rename(tmp, p)+}++// recoverEncryptedAssetCleanup 在挂载和同步前原样恢复未提交批次;解锁时继续认证恢复的密文。+func recoverEncryptedAssetCleanup(boxID string, rollback ...*encryptedAssetCleanupJournal) error {+ root := encryptedAssetCleanupDir(boxID)+ if err := validateEncryptedCleanupPath(util.WorkspaceDir, filepath.Join(root, "manifest.json")); err != nil {+ return err+ }+ journal := &encryptedAssetCleanupJournal{}+ var err error+ if len(rollback) > 0 {+ // 当前批次保留内存清单,提交标记写入或刷盘失败时也能恢复源文件。+ journal = rollback[0]+ journal.Committed = false+ } else {+ data, readErr := os.ReadFile(filepath.Join(root, "manifest.json"))+ if errors.Is(readErr, os.ErrNotExist) {+ // 清单落盘前不会删除源文件,留下的预备副本可直接回收。+ return os.RemoveAll(root)+ }+ if readErr != nil {+ return readErr+ }+ if err = json.Unmarshal(data, journal); err != nil {+ return err+ }+ if journal.Checksum != encryptedCleanupJournalChecksum(journal) {+ return errors.New("invalid encrypted asset cleanup journal checksum")+ }+ }+ if journal.Spec != 1 || len(journal.Files) == 0 {+ return errors.New("unsupported encrypted asset cleanup journal")+ }+ for _, file := range journal.Files {+ if !strings.HasPrefix(file.Path, "assets/") || path.Clean(file.Path) != file.Path || strings.Contains(file.Path, "\\") ||+ strings.Contains(file.Path, ":") || len(file.Hash) != 64 {+ return errors.New("invalid encrypted asset cleanup journal path")+ }+ if err = validateEncryptedCleanupPath(util.WorkspaceDir, filepath.Join(root, filepath.FromSlash(file.Path))); err != nil {+ return err+ }+ if err = validateEncryptedCleanupPath(util.DataDir, filepath.Join(util.DataDir, boxID, filepath.FromSlash(file.Path))); err != nil {+ return err+ }+ }+ if journal.Committed {+ return os.RemoveAll(root)+ }+ // 在复制前校验整批备份,损坏或冲突时保留恢复材料,不覆盖当前数据。+ for _, file := range journal.Files {+ backup := filepath.Join(root, filepath.FromSlash(file.Path))+ hash, hashErr := encryptedCleanupFileHash(backup)+ if hashErr != nil || hash != file.Hash {+ return fmt.Errorf("invalid encrypted asset cleanup backup: %s", file.Path)+ }+ live := filepath.Join(util.DataDir, boxID, filepath.FromSlash(file.Path))+ if hash, hashErr = encryptedCleanupFileHash(live); !errors.Is(hashErr, os.ErrNotExist) && (hashErr != nil || hash != file.Hash) {+ return fmt.Errorf("encrypted asset cleanup recovery conflicts with current file: %s", file.Path)+ }+ }+ for _, file := range journal.Files {+ live := filepath.Join(util.DataDir, boxID, filepath.FromSlash(file.Path))+ if _, statErr := os.Lstat(live); errors.Is(statErr, os.ErrNotExist) {+ if err = copyEncryptedCleanupFile(filepath.Join(root, filepath.FromSlash(file.Path)), live); err != nil {+ return err+ }+ }+ }+ return os.RemoveAll(root)+}++// copyEncryptedCleanupFile 原子复制密文并保留修改时间,复制失败只返回错误,不退出内核或覆盖源文件。+func copyEncryptedCleanupFile(source, target string) error {+ filelock.Lock(source)+ defer filelock.Unlock(source)+ input, err := os.Open(source)+ if err != nil {+ return err+ }+ defer input.Close()+ info, err := input.Stat()+ if err != nil {+ return err+ }+ if !info.Mode().IsRegular() {+ return errors.New("encrypted asset copy source must be a regular file")+ }+ if err = os.MkdirAll(filepath.Dir(target), 0700); err != nil {+ return err+ }+ output, err := os.CreateTemp(filepath.Dir(target), ".asset-copy-*.tmp")+ if err != nil {+ return err+ }+ tmp := output.Name()+ defer func() {+ output.Close()+ os.Remove(tmp)+ }()+ if _, err = io.Copy(output, input); err != nil {+ return err+ }+ if err = output.Chmod(info.Mode().Perm()); err != nil {+ return err+ }+ if err = output.Sync(); err != nil {+ return err+ }+ if err = output.Close(); err != nil {+ return err+ }+ if err = os.Chtimes(tmp, info.ModTime(), info.ModTime()); err != nil {+ return err+ }+ return os.Rename(tmp, target)+}++// validateEncryptedCleanupPath 拒绝恢复路径中的符号链接和非目录祖先,保留未认证的源文件与恢复材料。+func validateEncryptedCleanupPath(base, target string) error {+ rel, err := filepath.Rel(base, target)+ if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {+ return errors.New("encrypted cleanup path escapes its root")+ }+ current := base+ parts := strings.Split(rel, string(filepath.Separator))+ for i, part := range parts {+ current = filepath.Join(current, part)+ info, statErr := os.Lstat(current)+ if errors.Is(statErr, os.ErrNotExist) {+ return nil+ }+ if statErr != nil {+ return statErr+ }+ if info.Mode()&os.ModeSymlink != 0 || (i < len(parts)-1 && !info.IsDir()) {+ return fmt.Errorf("invalid encrypted cleanup path: %s", current)+ }+ }+ return nil+}++func recoverEncryptedAssetCleanupOperations() error {+ root := filepath.Dir(encryptedAssetCleanupDir("unused"))+ if err := validateEncryptedCleanupPath(util.WorkspaceDir, root); err != nil {+ return err+ }+ entries, err := os.ReadDir(root)+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ if err != nil {+ return err+ }+ for _, entry := range entries {+ if !entry.IsDir() || entry.Type()&os.ModeSymlink != 0 || !ast.IsNodeIDPattern(entry.Name()) {+ return errors.New("invalid encrypted asset cleanup directory")+ }+ if err = recoverEncryptedAssetCleanup(entry.Name()); err != nil {+ return err+ }+ }+ return nil+}diff --git a/kernel/model/encrypted_assets_cleanup_test.go b/kernel/model/encrypted_assets_cleanup_test.gonew file mode 100644index 0000000000..a64ca39fc3--- /dev/null+++ b/kernel/model/encrypted_assets_cleanup_test.go@@ -0,0 +1,416 @@+package model++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func setupEncryptedCleanupTest(t *testing.T) (boxID, docPath string, dek []byte) {+ boxID, docPath = setupUnusedAssetWorkspace(t)+ oldHistory := util.HistoryDir+ util.HistoryDir = filepath.Join(util.WorkspaceDir, "history")+ markRuntimeEncryptedBox(boxID)+ dek = bytes.Repeat([]byte{0x31}, 32)+ setDEKForTest(boxID, append([]byte(nil), dek...))+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)+ t.Cleanup(func() {+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ forgetRuntimeEncryptedBox(boxID)+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)+ util.HistoryDir = oldHistory+ })+ writeEncryptedCleanupDoc(t, boxID, docPath, dek, "")+ return+}++func writeEncryptedCleanupDoc(t *testing.T, boxID, docPath string, dek []byte, children string) {+ t.Helper()+ id := strings.TrimSuffix(filepath.Base(docPath), ".sy")+ if children == "" {+ children = `{"Type":"NodeParagraph","ID":"20261017000001-abcdefg","Children":[]}`+ }+ data := []byte(`{"Type":"NodeDocument","ID":"` + id + `","Spec":"2","Properties":{"id":"` + id + `","title":"fixture"},"Children":[` + children + `]}`)+ rel, _ := filepath.Rel(filepath.Join(util.DataDir, boxID), docPath)+ ciphertext, err := EncryptFile(boxID, filepath.ToSlash(rel), dek, data)+ if err != nil {+ t.Fatal(err)+ }+ writeEncryptedCleanupFile(t, docPath, ciphertext)+}++func writeEncryptedCleanupFile(t *testing.T, p string, data []byte) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(p, data, 0600); err != nil {+ t.Fatal(err)+ }+}++func writeEncryptedCleanupAsset(t *testing.T, boxID, name string, dek []byte, legacy bool) []byte {+ t.Helper()+ data, err := EncryptAsset(boxID, filepath.Base(name), "original-"+filepath.Base(name), dek, []byte("secret content"))+ if err != nil {+ t.Fatal(err)+ }+ if legacy {+ data = legacyEncryptedAssetFixture(t, boxID, filepath.Base(name), "original-"+filepath.Base(name), dek, []byte("secret content"))+ }+ writeEncryptedCleanupFile(t, filepath.Join(util.DataDir, boxID, "assets", name), data)+ return data+}++func TestEncryptedAssetCleanupReferences(t *testing.T) {+ boxID, docPath, dek := setupEncryptedCleanupTest(t)+ for _, name := range []string{"linked.pdf", "linked.pdf.sya", "cover.png", "custom.png", "database.png", "template.png", "agent.png", "runtime.png", "folder/child.png", "unused.png"} {+ writeEncryptedCleanupAsset(t, boxID, name, dek, false)+ }+ writeEncryptedCleanupDoc(t, boxID, docPath, dek,+ `{"Type":"NodeParagraph","ID":"20261017000001-abcdefg","Properties":{"custom-data-assets-extra":"assets/custom.png"},"Children":[{"Type":"NodeTextMark","TextMarkType":"a","TextMarkTextContent":"PDF","TextMarkAHref":"/assets/linked.pdf?page=2"},{"Type":"NodeTextMark","TextMarkType":"a","TextMarkAHref":"assets/folder/"}]}`)+ // 题头图和未挂载数据库都属于持久化引用,不能依赖全局索引或已打开的数据库缓存。+ data, _ := os.ReadFile(docPath)+ plain, _ := DecryptFile(boxID, filepath.Base(docPath), dek, data)+ plain = bytes.Replace(plain, []byte(`"title":"fixture"`), []byte(`"title":"fixture","title-img":"background-image:url(assets/cover.png)"`), 1)+ data, _ = EncryptFile(boxID, filepath.Base(docPath), dek, plain)+ writeEncryptedCleanupFile(t, docPath, data)+ avID := "20261017000002-abcdefg"+ avData := []byte(`{"spec":1,"id":"` + avID + `","keyValues":[],"views":[],"newItemTemplates":[{"name":"assets/template.png"}],"name":"assets/database.png"}`)+ key := util.DeriveSubKey(dek, "siyuan/av")+ avData, err := util.EncryptWithAAD(key, avData, []byte("siyuan:av:"+boxID+":"+avID))+ if err != nil {+ t.Fatal(err)+ }+ writeEncryptedCleanupFile(t, filepath.Join(util.DataDir, boxID, "storage", "av", avID+".json"), avData)+ session := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", "fixture")+ writeEncryptedCleanupFile(t, filepath.Join(session, "session.json"), []byte(`{"entries":[{"type":"assistant","toolCalls":[{"attachments":[{"path":"assets/agent.png","documentId":"`+strings.TrimSuffix(filepath.Base(docPath), ".sy")+`"}]}]}]}`))+ writeEncryptedCleanupFile(t, filepath.Join(session, "runtime.json"), []byte(`{"activeTurn":{"userContent":""}}`))+ items, err := UnusedEncryptedBoxAssets(context.Background(), boxID)+ if err != nil || len(items) != 1 || items[0].Item != "assets/unused.png" || items[0].Name != "original-unused.png" {+ t.Fatalf("wrong unused candidates: %+v, %v", items, err)+ }+ // 全局清理继续跳过目标笔记本。+ if global, err := UnusedAssets(false); err != nil || len(global) != 0 {+ t.Fatalf("global cleanup included encrypted assets: %+v, %v", global, err)+ }+}++func TestEncryptedAssetCleanupAbortUnreadable(t *testing.T) {+ for _, kind := range []string{"document authentication", "document JSON", "new spec", "database authentication", "database spec", "database directory", "agent JSON", "asset authentication"} {+ t.Run(kind, func(t *testing.T) {+ boxID, docPath, dek := setupEncryptedCleanupTest(t)+ original := writeEncryptedCleanupAsset(t, boxID, "unused.png", dek, false)+ switch kind {+ case "document authentication":+ writeEncryptedCleanupFile(t, docPath, []byte("corrupt"))+ case "document JSON", "new spec":+ plain := []byte(`{"Type":`)+ if kind == "new spec" {+ plain = []byte(`{"Type":"NodeDocument","Spec":"99"}`)+ }+ data, _ := EncryptFile(boxID, filepath.Base(docPath), dek, plain)+ writeEncryptedCleanupFile(t, docPath, data)+ case "database authentication", "database spec":+ id := "20261017000002-abcdefg"+ data := []byte("corrupt")+ if kind == "database spec" {+ key := util.DeriveSubKey(dek, "siyuan/av")+ data, _ = util.EncryptWithAAD(key, []byte(`{"id":"`+id+`","spec":999}`), []byte("siyuan:av:"+boxID+":"+id))+ }+ writeEncryptedCleanupFile(t, filepath.Join(util.DataDir, boxID, "storage", "av", id+".json"), data)+ case "agent JSON":+ writeEncryptedCleanupFile(t, filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", "fixture", "runtime.json"), []byte("{"))+ case "database directory":+ writeEncryptedCleanupFile(t, filepath.Join(util.DataDir, boxID, "storage", "av"), []byte("not a directory"))+ case "asset authentication":+ original[len(original)-1] ^= 1+ writeEncryptedCleanupFile(t, filepath.Join(util.DataDir, boxID, "assets", "unused.png"), original)+ }+ removed, err := RemoveUnusedEncryptedBoxAssets(context.Background(), boxID, []string{"assets/unused.png"})+ if err == nil || len(removed) != 0 {+ t.Fatalf("incomplete scan deleted data: %v, %v", removed, err)+ }+ got, _ := os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", "unused.png"))+ if !bytes.Equal(got, original) {+ t.Fatal("failed cleanup modified source ciphertext")+ }+ if _, err = os.Stat(util.HistoryDir); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("failed preflight created cleanup history")+ }+ })+ }+}++func TestEncryptedAssetCleanupRevalidatesCandidates(t *testing.T) {+ boxID, docPath, dek := setupEncryptedCleanupTest(t)+ writeEncryptedCleanupAsset(t, boxID, "unused.png", dek, false)+ if items, err := UnusedEncryptedBoxAssets(context.Background(), boxID); err != nil || len(items) != 1 {+ t.Fatalf("initial scan: %v, %v", items, err)+ }+ writeEncryptedCleanupDoc(t, boxID, docPath, dek, `{"Type":"NodeParagraph","Children":[{"Type":"NodeTextMark","TextMarkType":"a","TextMarkAHref":"assets/unused.png","TextMarkTextContent":"reference"}]}`)+ for _, paths := range [][]string{{"assets/unused.png"}, {"assets/../outside"}, {"assets/unused.png?box=other"}} {+ if _, err := RemoveUnusedEncryptedBoxAssets(context.Background(), boxID, paths); err == nil {+ t.Fatalf("accepted stale or invalid candidates: %v", paths)+ }+ }+ if _, err := UnusedEncryptedBoxAssets(context.Background(), ""); err == nil {+ t.Fatal("empty notebook fell back to global cleanup")+ }+ setEncryptedBoxState(boxID, EncryptedBoxStateLocked)+ cachedDEKsLock.Lock()+ delete(cachedDEKs, boxID)+ cachedDEKsLock.Unlock()+ if _, err := UnusedEncryptedBoxAssets(context.Background(), boxID); err == nil {+ t.Fatal("locked notebook was scanned")+ }+}++func TestEncryptedAssetCleanupFailureRollsBack(t *testing.T) {+ boxID, _, dek := setupEncryptedCleanupTest(t)+ originals := map[string][]byte{}+ for _, name := range []string{"a.png", "b.png"} {+ originals[name] = writeEncryptedCleanupAsset(t, boxID, name, dek, false)+ }+ items, err := UnusedEncryptedBoxAssets(context.Background(), boxID)+ if err != nil {+ t.Fatal(err)+ }+ calls := 0+ err = deleteEncryptedBoxAssets(context.Background(), boxID, dek, items, func(p string) error {+ calls+++ if calls == 2 {+ return errors.New("injected delete failure")+ }+ return os.Remove(p)+ }, nil)+ if err == nil {+ t.Fatal("delete failure was hidden")+ }+ for name, original := range originals {+ data, err := os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", name))+ if err != nil || !bytes.Equal(data, original) {+ t.Fatalf("rollback lost %s: %v", name, err)+ }+ }+}++func TestEncryptedAssetCleanupHistoryCompatibility(t *testing.T) {+ for _, legacy := range []bool{false, true} {+ t.Run(map[bool]string{false: "current", true: "legacy"}[legacy], func(t *testing.T) {+ boxID, _, dek := setupEncryptedCleanupTest(t)+ original := writeEncryptedCleanupAsset(t, boxID, "sub/unused.png", dek, legacy)+ removed, err := RemoveUnusedEncryptedBoxAssets(context.Background(), boxID, []string{"assets/sub/unused.png"})+ if err != nil || !reflect.DeepEqual(removed, []string{"assets/sub/unused.png"}) {+ t.Fatalf("cleanup failed: %v, %v", removed, err)+ }+ histories, _ := filepath.Glob(filepath.Join(util.HistoryDir, "*-clean", boxID, "assets", "sub", "unused.png"))+ if len(histories) != 1 {+ t.Fatalf("missing ciphertext history: %v", histories)+ }+ data, _ := os.ReadFile(histories[0])+ if !bytes.Equal(data, original) {+ t.Fatal("history was re-encrypted or corrupted")+ }+ rel, _ := filepath.Rel(util.WorkspaceDir, histories[0])+ if err = RollbackAssetsHistory(filepath.ToSlash(rel)); err != nil {+ t.Fatal(err)+ }+ data, _ = os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", "sub", "unused.png"))+ if !bytes.Equal(data, original) {+ t.Fatal("history restore changed ciphertext or target path")+ }+ data[len(data)-1] ^= 1+ writeEncryptedCleanupFile(t, histories[0], data)+ if err = RollbackAssetsHistory(filepath.ToSlash(rel)); err == nil {+ t.Fatal("unauthenticated history was restored")+ }+ })+ }+}++func TestEncryptedAssetCleanupInterruptedRecovery(t *testing.T) {+ boxID, _, dek := setupEncryptedCleanupTest(t)+ original := writeEncryptedCleanupAsset(t, boxID, "unused.png", dek, false)+ root := encryptedAssetCleanupDir(boxID)+ backup := filepath.Join(root, "assets", "unused.png")+ writeEncryptedCleanupFile(t, backup, original)+ hash, _ := encryptedCleanupFileHash(backup)+ journal := encryptedAssetCleanupJournal{Spec: 1, Files: []encryptedAssetCleanupFile{{Path: "assets/unused.png", Hash: hash}}}+ journal.Checksum = encryptedCleanupJournalChecksum(&journal)+ data, _ := json.Marshal(journal)+ writeEncryptedCleanupFile(t, filepath.Join(root, "manifest.json"), data)+ live := filepath.Join(util.DataDir, boxID, "assets", "unused.png")+ if err := os.Remove(live); err != nil {+ t.Fatal(err)+ }+ if err := recoverEncryptedAssetCleanupOperations(); err != nil {+ t.Fatal(err)+ }+ got, _ := os.ReadFile(live)+ if !bytes.Equal(got, original) {+ t.Fatal("interrupted cleanup did not restore ciphertext")+ }+ // 错误清单不得改写笔记本目录之外的数据。+ journal.Files[0].Path = "assets/../../outside"+ journal.Checksum = encryptedCleanupJournalChecksum(&journal)+ data, _ = json.Marshal(journal)+ writeEncryptedCleanupFile(t, filepath.Join(root, "manifest.json"), data)+ if err := recoverEncryptedAssetCleanupOperations(); err == nil {+ t.Fatal("invalid recovery path accepted")+ }+}++func TestEncryptedAssetCleanupCommitFailureRollsBack(t *testing.T) {+ boxID, _, dek := setupEncryptedCleanupTest(t)+ original := writeEncryptedCleanupAsset(t, boxID, "unused.png", dek, false)+ items, err := UnusedEncryptedBoxAssets(context.Background(), boxID)+ if err != nil {+ t.Fatal(err)+ }+ err = deleteEncryptedBoxAssets(context.Background(), boxID, dek, items, func(p string) error {+ if err := os.Remove(p); err != nil {+ return err+ }+ // 用目录阻止提交标记落盘,验证失败不能把已删除批次当成成功。+ manifest := filepath.Join(encryptedAssetCleanupDir(boxID), "manifest.json")+ if err := os.Remove(manifest); err != nil {+ return err+ }+ return os.Mkdir(manifest, 0700)+ }, nil)+ if err == nil {+ t.Fatal("commit failure was hidden")+ }+ got, readErr := os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", "unused.png"))+ if readErr != nil || !bytes.Equal(got, original) {+ t.Fatalf("commit failure lost source ciphertext: %v", readErr)+ }+}++func TestEncryptedAssetCleanupSourceChangeRollsBack(t *testing.T) {+ boxID, docPath, dek := setupEncryptedCleanupTest(t)+ original := writeEncryptedCleanupAsset(t, boxID, "unused.png", dek, false)+ items, err := UnusedEncryptedBoxAssets(context.Background(), boxID)+ if err != nil {+ t.Fatal(err)+ }+ before, _ := encryptedCleanupSourceDigest(context.Background(), boxID)+ err = deleteEncryptedBoxAssets(context.Background(), boxID, dek, items, func(p string) error {+ if err := os.Remove(p); err != nil {+ return err+ }+ writeEncryptedCleanupDoc(t, boxID, docPath, dek, `{"Type":"NodeParagraph","Children":[{"Type":"NodeTextMark","TextMarkType":"a","TextMarkAHref":"assets/unused.png"}]}`)+ return nil+ }, func() error {+ after, err := encryptedCleanupSourceDigest(context.Background(), boxID)+ if err != nil {+ return err+ }+ if before != after {+ return errors.New("references changed")+ }+ return nil+ })+ if err == nil {+ t.Fatal("changed references were ignored")+ }+ got, _ := os.ReadFile(filepath.Join(util.DataDir, boxID, "assets", "unused.png"))+ if !bytes.Equal(got, original) {+ t.Fatal("changed references did not restore source asset")+ }+}++func TestEncryptedAssetCleanupLockWaits(t *testing.T) {+ boxID, _, _ := setupEncryptedCleanupTest(t)+ entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})+ go func() {+ _ = withEncryptedAssetCleanup(context.Background(), boxID, func([]byte) error {+ close(entered)+ <-release+ return nil+ })+ close(done)+ }()+ <-entered+ locked := make(chan struct{})+ go func() {+ beginEncryptedBoxLock(boxID)+ close(locked)+ }()+ select {+ case <-locked:+ t.Fatal("locking did not wait for cleanup")+ case <-time.After(20 * time.Millisecond):+ }+ close(release)+ select {+ case <-locked:+ case <-time.After(3 * time.Second):+ t.Fatal("cleanup leaked operation lease")+ }+ <-done+}++func TestEncryptedAssetCleanupPausesNewOperations(t *testing.T) {+ boxID, _, _ := setupEncryptedCleanupTest(t)+ entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})+ go func() {+ _ = withEncryptedAssetCleanup(context.Background(), boxID, func([]byte) error {+ close(entered)+ <-release+ return nil+ })+ close(done)+ }()+ <-entered+ admitted := make(chan error, 1)+ go func() {+ err := AcquireEncryptedBoxOperation(boxID)+ if err == nil {+ ReleaseEncryptedBoxOperation(boxID)+ }+ admitted <- err+ }()+ select {+ case <-admitted:+ close(release)+ <-done+ t.Fatal("new operation entered during cleanup")+ case <-time.After(20 * time.Millisecond):+ }+ close(release)+ select {+ case err := <-admitted:+ if err != nil {+ t.Fatal(err)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("cleanup did not reopen operation admission")+ }+ <-done+}++func TestEncryptedAssetCleanupReadConflictReturnsWithoutWaiting(t *testing.T) {+ boxID, _, _ := setupEncryptedCleanupTest(t)+ HoldBoxReadLock(boxID)+ if _, err := UnusedEncryptedBoxAssets(context.Background(), boxID); err == nil {+ ReleaseBoxReadLock(boxID)+ t.Fatal("cleanup admitted a conflicting notebook reader")+ }+ ReleaseBoxReadLock(boxID)+ if _, err := UnusedEncryptedBoxAssets(context.Background(), boxID); err != nil {+ t.Fatalf("failed cleanup did not reopen admission: %v", err)+ }+}diff --git a/kernel/model/history.go b/kernel/model/history.goindex 3870ecfa5e..61c0e519e3 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -21,6 +21,7 @@ import ("encoding/json""errors""fmt"+ "io""io/fs""math""os"@@ -571,7 +572,9 @@ func RollbackAssetsHistory(historyPath string) (err error) {relPath := strings.TrimPrefix(filepath.ToSlash(historyPath), filepath.ToSlash(util.HistoryDir))relPath = strings.TrimPrefix(relPath, "/")pathParts := strings.SplitN(relPath, "/", 3)- data, readErr := filelock.ReadFile(from)+ filelock.Lock(from)+ data, readErr := os.ReadFile(from)+ filelock.Unlock(from)if readErr != nil {return readErr}@@ -585,13 +588,36 @@ func RollbackAssetsHistory(historyPath string) (err error) {return fmt.Errorf("encrypted notebook asset history is plaintext [%s]", pathParts[1])}// 加密笔记本的资源回滚到笔记本级 assets 目录- to = filepath.Join(util.DataDir, pathParts[1], "assets", filepath.Base(historyPath))+ assetPath := pathParts[2]+ if !strings.HasPrefix(assetPath, "assets/") || path.Clean(assetPath) != assetPath || strings.Contains(assetPath, "\\") {+ return errors.New("invalid encrypted asset history path")+ }+ boxID := pathParts[1]+ HoldBoxReadLock(boxID)+ defer ReleaseBoxReadLock(boxID)+ dek, dekErr := GetDEKIfUnlocked(boxID)+ if dekErr != nil {+ return errors.New(Conf.Language(314))+ }+ defer zeroAndClear(dek)+ if _, err = DecryptAssetToWriter(boxID, filepath.Base(historyPath), dek, bytes.NewReader(data), io.Discard); err != nil {+ return err+ }+ to = filepath.Join(util.DataDir, boxID, filepath.FromSlash(assetPath))+ if err = validateEncryptedCleanupPath(util.DataDir, to); err != nil {+ return err+ }if err = os.MkdirAll(filepath.Dir(to), 0755); err != nil {return}}- if err = filelock.CopyNewtimes(from, to); err != nil {+ if encrypted {+ err = writeEncryptedCleanupData(to, data)+ } else {+ err = filelock.CopyNewtimes(from, to)+ }+ if err != nil {logging.LogErrorf("copy file [%s] to [%s] failed: %s", from, to, err)return}