Skip to content

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

:bug: Open encrypted notebook assets externally with confirmation

Danielf4a2768538af
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 4b6a157a4f..99870a4b50 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "سيتم فتح نسخة مؤقتة مفكوك تشفيرها. لن تُحفظ التغييرات في المرفق الأصلي. قد تُحذف النسخة عند قفل دفتر الملاحظات. للاحتفاظ بالتغييرات، احفظ الملف في موقع آخر.",
"linuxInputMethod": "وضع توافق طرق الإدخال في Linux",
"linuxInputMethodTip": "استخدام X11/XWayland لتحسين توافق طرق الإدخال؛ قد يؤثر على تحجيم العرض، وينطبق على جميع مساحات العمل على هذا الجهاز، ويسري بعد إغلاق SiYuan بالكامل وإعادة تشغيله",
"linuxInputMethodError": "تعذرت قراءة إعدادات توافق طرق الإدخال أو حفظها",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index e95f92d3fd..a00717dc88 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Es wird eine temporäre entschlüsselte Kopie geöffnet. Änderungen werden nicht im ursprünglichen Anhang gespeichert. Die Kopie kann beim Sperren des Notizbuchs gelöscht werden. Speichern Sie die Datei an einem anderen Ort, um Ihre Änderungen zu behalten.",
"linuxInputMethod": "Linux-Eingabemethoden-Kompatibilitätsmodus",
"linuxInputMethodTip": "X11/XWayland zur Verbesserung der Eingabemethoden-Kompatibilität verwenden; kann die Anzeigeskalierung beeinflussen, gilt für alle Arbeitsbereiche auf diesem Gerät und wird nach vollständigem Beenden und Neustarten von SiYuan wirksam",
"linuxInputMethodError": "Die Kompatibilitätseinstellungen für Eingabemethoden konnten nicht gelesen oder gespeichert werden",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 2030788412..7906eff571 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "This will open a temporary decrypted copy. Changes will not be saved to the original attachment. The copy may be cleaned up when the notebook is locked. To keep your changes, save the file to another location.",
"linuxInputMethod": "Linux input method compatibility mode",
"linuxInputMethodTip": "Use X11/XWayland to address input method issues; may affect display scaling, applies to all workspaces on this device, and takes effect after fully quitting and restarting SiYuan",
"linuxInputMethodError": "Unable to read or save input method compatibility settings",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index f01c8e38c0..3a3813510c 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Se abrirá una copia temporal descifrada. Los cambios no se guardarán en el archivo adjunto original. La copia puede eliminarse al bloquear el cuaderno. Para conservar los cambios, guarde el archivo en otra ubicación.",
"linuxInputMethod": "Modo de compatibilidad de métodos de entrada de Linux",
"linuxInputMethodTip": "Usar X11/XWayland para mejorar la compatibilidad de los métodos de entrada; puede afectar al escalado, se aplica a todos los espacios de trabajo de este dispositivo y requiere cerrar completamente y reiniciar SiYuan",
"linuxInputMethodError": "No se pueden leer o guardar los ajustes de compatibilidad de métodos de entrada",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 84df752aff..97dff66817 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Une copie temporaire déchiffrée va être ouverte. Les modifications ne seront pas enregistrées dans la pièce jointe d’origine. La copie peut être supprimée lors du verrouillage du carnet. Pour conserver vos modifications, enregistrez le fichier à un autre emplacement.",
"linuxInputMethod": "Mode de compatibilité des méthodes de saisie Linux",
"linuxInputMethodTip": "Utiliser X11/XWayland pour améliorer la compatibilité des méthodes de saisie ; peut affecter la mise à l’échelle, s’applique à tous les espaces de travail de cet appareil et prend effet après avoir complètement quitté puis redémarré SiYuan",
"linuxInputMethodError": "Impossible de lire ou d’enregistrer les paramètres de compatibilité des méthodes de saisie",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 2e8038aee6..7e4e8d5132 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "ייפתח עותק זמני מפוענח. השינויים לא יישמרו בקובץ המצורף המקורי. העותק עשוי להימחק בעת נעילת המחברת. כדי לשמור את השינויים, יש לשמור את הקובץ במיקום אחר.",
"linuxInputMethod": "מצב תאימות לשיטות קלט ב־Linux",
"linuxInputMethodTip": "שימוש ב־X11/XWayland לשיפור תאימות שיטות הקלט; עשוי להשפיע על קנה המידה של התצוגה, חל על כל סביבות העבודה במכשיר זה ונכנס לתוקף לאחר סגירה מלאה והפעלה מחדש של SiYuan",
"linuxInputMethodError": "לא ניתן לקרוא או לשמור את הגדרות התאימות של שיטות הקלט",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 266d56f310..8b877cbf5b 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "एक अस्थायी डिक्रिप्ट की गई प्रतिलिपि खुलेगी। बदलाव मूल संलग्नक में सहेजे नहीं जाएँगे। नोटबुक लॉक होने पर यह प्रतिलिपि हटाई जा सकती है। बदलाव बनाए रखने के लिए फ़ाइल को किसी अन्य स्थान पर सहेजें।",
"linuxInputMethod": "Linux इनपुट विधि संगतता मोड",
"linuxInputMethodTip": "इनपुट विधि की संगतता सुधारने के लिए X11/XWayland का उपयोग करें; इससे स्क्रीन स्केलिंग प्रभावित हो सकती है, यह इस डिवाइस के सभी कार्यस्थानों पर लागू होता है और SiYuan को पूरी तरह बंद करके दोबारा शुरू करने के बाद प्रभावी होता है",
"linuxInputMethodError": "इनपुट विधि संगतता सेटिंग पढ़ी या सहेजी नहीं जा सकी",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index b129cc3af8..3ebc1dde41 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Salinan sementara yang telah didekripsi akan dibuka. Perubahan tidak akan disimpan ke lampiran asli. Salinan dapat dihapus saat buku catatan dikunci. Untuk mempertahankan perubahan, simpan berkas ke lokasi lain.",
"linuxInputMethod": "Mode kompatibilitas metode masukan Linux",
"linuxInputMethodTip": "Gunakan X11/XWayland untuk meningkatkan kompatibilitas metode masukan; dapat memengaruhi skala tampilan, berlaku untuk semua ruang kerja di perangkat ini, dan aktif setelah SiYuan ditutup sepenuhnya lalu dimulai ulang",
"linuxInputMethodError": "Tidak dapat membaca atau menyimpan pengaturan kompatibilitas metode masukan",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index f64722dbe1..a2445fc55a 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Verrà aperta una copia temporanea decrittografata. Le modifiche non verranno salvate nell’allegato originale. La copia potrebbe essere eliminata quando il quaderno viene bloccato. Per conservare le modifiche, salvare il file in un’altra posizione.",
"linuxInputMethod": "Modalità di compatibilità dei metodi di input Linux",
"linuxInputMethodTip": "Usa X11/XWayland per migliorare la compatibilità dei metodi di input; può influire sul ridimensionamento, si applica a tutti gli spazi di lavoro su questo dispositivo e richiede la chiusura completa e il riavvio di SiYuan",
"linuxInputMethodError": "Impossibile leggere o salvare le impostazioni di compatibilità dei metodi di input",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 2dc7596c73..0ba3a45a0e 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "一時的に復号したコピーを開きます。変更は元の添付ファイルには保存されません。ノートブックをロックすると、コピーが削除される場合があります。変更を保持するには、別の場所に保存してください。",
"linuxInputMethod": "Linux 入力メソッド互換モード",
"linuxInputMethodTip": "X11/XWayland を使用して入力メソッドの互換性を改善します。表示倍率に影響する場合があります。この端末のすべてのワークスペースに適用され、SiYuan を完全に終了して再起動すると有効になります",
"linuxInputMethodError": "入力メソッドの互換設定を読み取りまたは保存できません",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 9c5c528520..cce759ad32 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "임시로 복호화된 사본을 엽니다. 변경 사항은 원본 첨부 파일에 저장되지 않습니다. 노트북을 잠그면 사본이 삭제될 수 있습니다. 변경 사항을 유지하려면 파일을 다른 위치에 저장하세요.",
"linuxInputMethod": "Linux 입력기 호환 모드",
"linuxInputMethodTip": "X11/XWayland를 사용하여 입력기 호환성을 개선합니다. 화면 배율에 영향을 줄 수 있으며 이 기기의 모든 작업 공간에 적용됩니다. SiYuan을 완전히 종료한 후 다시 시작하면 적용됩니다",
"linuxInputMethodError": "입력기 호환 설정을 읽거나 저장할 수 없습니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 3af7fd4a72..e07ccac3a7 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Er wordt een tijdelijke ontsleutelde kopie geopend. Wijzigingen worden niet opgeslagen in de oorspronkelijke bijlage. De kopie kan worden verwijderd wanneer het notitieboek wordt vergrendeld. Sla het bestand op een andere locatie op om uw wijzigingen te behouden.",
"linuxInputMethod": "Compatibiliteitsmodus voor Linux-invoermethoden",
"linuxInputMethodTip": "Gebruik X11/XWayland om de compatibiliteit van invoermethoden te verbeteren; kan de beeldschermschaal beïnvloeden, geldt voor alle werkruimten op dit apparaat en wordt actief nadat SiYuan volledig is afgesloten en opnieuw gestart",
"linuxInputMethodError": "Kan de compatibiliteitsinstellingen voor invoermethoden niet lezen of opslaan",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index dcee252565..39e11d870a 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Zostanie otwarta tymczasowa odszyfrowana kopia. Zmiany nie zostaną zapisane w oryginalnym załączniku. Kopia może zostać usunięta po zablokowaniu notatnika. Aby zachować zmiany, zapisz plik w innym miejscu.",
"linuxInputMethod": "Tryb zgodności metod wprowadzania w systemie Linux",
"linuxInputMethodTip": "Używaj X11/XWayland, aby poprawić zgodność metod wprowadzania; może wpływać na skalowanie ekranu, dotyczy wszystkich przestrzeni roboczych na tym urządzeniu i wymaga całkowitego zamknięcia oraz ponownego uruchomienia SiYuan",
"linuxInputMethodError": "Nie można odczytać lub zapisać ustawień zgodności metod wprowadzania",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 45eab19397..3b790300e7 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Será aberta uma cópia temporária descriptografada. As alterações não serão salvas no anexo original. A cópia poderá ser removida quando o caderno for bloqueado. Para manter as alterações, salve o arquivo em outro local.",
"linuxInputMethod": "Modo de compatibilidade dos métodos de entrada do Linux",
"linuxInputMethodTip": "Usar X11/XWayland para melhorar a compatibilidade dos métodos de entrada; pode afetar a escala da tela, aplica-se a todos os espaços de trabalho neste dispositivo e exige encerrar completamente e reiniciar o SiYuan",
"linuxInputMethodError": "Não foi possível ler ou salvar as configurações de compatibilidade dos métodos de entrada",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index da5ebd887b..8d93ad5078 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Будет открыта временная расшифрованная копия. Изменения не сохранятся в исходном вложении. При блокировке блокнота копия может быть удалена. Чтобы сохранить изменения, сохраните файл в другом месте.",
"linuxInputMethod": "Режим совместимости методов ввода Linux",
"linuxInputMethodTip": "Использовать X11/XWayland для улучшения совместимости методов ввода; может влиять на масштабирование экрана, применяется ко всем рабочим пространствам на этом устройстве и вступает в силу после полного закрытия и перезапуска SiYuan",
"linuxInputMethodError": "Не удалось прочитать или сохранить настройки совместимости методов ввода",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 738a32e0a4..1f92a8b96a 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Otvorí sa dočasná dešifrovaná kópia. Zmeny sa neuložia do pôvodnej prílohy. Kópia môže byť odstránená pri uzamknutí zápisníka. Ak chcete zachovať zmeny, uložte súbor na iné miesto.",
"linuxInputMethod": "Režim kompatibility vstupných metód systému Linux",
"linuxInputMethodTip": "Použiť X11/XWayland na zlepšenie kompatibility vstupných metód; môže ovplyvniť mierku zobrazenia, platí pre všetky pracovné priestory na tomto zariadení a prejaví sa po úplnom ukončení a opätovnom spustení SiYuan",
"linuxInputMethodError": "Nastavenia kompatibility vstupných metód sa nepodarilo načítať alebo uložiť",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 5af17db94e..ec4c17049b 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Отвориће се привремена дешифрована копија. Измене неће бити сачуване у оригиналном прилогу. Копија може бити обрисана када се бележница закључа. Да бисте задржали измене, сачувајте датотеку на другом месту.",
"linuxInputMethod": "Режим компатибилности метода уноса за Linux",
"linuxInputMethodTip": "Користи X11/XWayland за бољу компатибилност метода уноса; може утицати на скалирање приказа, важи за све радне просторе на овом уређају и примењује се након потпуног затварања и поновног покретања SiYuan-а",
"linuxInputMethodError": "Није могуће прочитати или сачувати подешавања компатибилности метода уноса",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 441fa8702e..257079e9a5 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "จะเปิดสำเนาชั่วคราวที่ถอดรหัสแล้ว การเปลี่ยนแปลงจะไม่ถูกบันทึกลงในไฟล์แนบต้นฉบับ สำเนาอาจถูกลบเมื่อล็อกสมุดบันทึก หากต้องการเก็บการเปลี่ยนแปลงไว้ โปรดบันทึกไฟล์ไปยังตำแหน่งอื่น",
"linuxInputMethod": "โหมดความเข้ากันได้ของวิธีป้อนข้อมูลบน Linux",
"linuxInputMethodTip": "ใช้ X11/XWayland เพื่อปรับปรุงความเข้ากันได้ของวิธีป้อนข้อมูล อาจส่งผลต่อการปรับขนาดหน้าจอ มีผลกับพื้นที่ทำงานทั้งหมดบนอุปกรณ์นี้ และมีผลหลังจากปิด SiYuan อย่างสมบูรณ์แล้วเปิดใหม่",
"linuxInputMethodError": "ไม่สามารถอ่านหรือบันทึกการตั้งค่าความเข้ากันได้ของวิธีป้อนข้อมูล",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 0b55b58857..cbbb490b34 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Geçici olarak şifresi çözülmüş bir kopya açılacak. Değişiklikler özgün eke kaydedilmeyecek. Not defteri kilitlendiğinde kopya silinebilir. Değişikliklerinizi korumak için dosyayı başka bir konuma kaydedin.",
"linuxInputMethod": "Linux giriş yöntemi uyumluluk modu",
"linuxInputMethodTip": "Giriş yöntemi uyumluluğunu iyileştirmek için X11/XWayland kullanır; ekran ölçeklendirmesini etkileyebilir, bu cihazdaki tüm çalışma alanlarına uygulanır ve SiYuan tamamen kapatılıp yeniden başlatıldığında etkinleşir",
"linuxInputMethodError": "Giriş yöntemi uyumluluk ayarları okunamadı veya kaydedilemedi",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index c1e385c97d..ce32b5bf19 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "Буде відкрито тимчасову розшифровану копію. Зміни не збережуться у вихідному вкладенні. Після блокування записника копію може бути видалено. Щоб зберегти зміни, збережіть файл в іншому місці.",
"linuxInputMethod": "Режим сумісності методів введення Linux",
"linuxInputMethodTip": "Використовувати X11/XWayland для покращення сумісності методів введення; може впливати на масштабування екрана, застосовується до всіх робочих просторів на цьому пристрої та набуває чинності після повного закриття й перезапуску SiYuan",
"linuxInputMethodError": "Не вдалося прочитати або зберегти налаштування сумісності методів введення",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index be761b3c3e..beec00bdef 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "将打开临时解密副本,修改不会保存到原附件。锁定笔记本后副本可能被清理,如需保留修改,请另存到其他位置。",
"linuxInputMethod": "Linux 输入法兼容模式",
"linuxInputMethodTip": "通过 X11/XWayland 改善输入法兼容性,可能影响显示缩放,作用于本机所有工作空间,完全退出并重新启动思源后生效",
"linuxInputMethodError": "无法读取或保存输入法兼容设置",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index fd1fb61c3f..a3ff21f943 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "encryptedAssetExternalOpenTip": "將開啟暫時解密的副本,修改不會儲存至原附件。鎖定筆記本後副本可能會被清除,如需保留修改,請另存至其他位置。",
"linuxInputMethod": "Linux 輸入法相容模式",
"linuxInputMethodTip": "透過 X11/XWayland 改善輸入法相容性,可能影響顯示縮放,套用至本機所有工作空間,完全結束並重新啟動思源後生效",
"linuxInputMethodError": "無法讀取或儲存輸入法相容設定",
diff --git a/app/src/editor/util.ts b/app/src/editor/util.ts
index 8dab0dbed9..b9d64e5292 100644
--- a/app/src/editor/util.ts
+++ b/app/src/editor/util.ts
@@ -41,6 +41,7 @@ import {forEachPluginSubscriber} from "../plugin/EventBusCore";
import {getHostCapabilities} from "../util/hostCapabilities";
import {revealTabsForTarget} from "../protyle/render/tabsRender";
import {isHiddenTabContent} from "../protyle/render/tabsVisibility";
+import {confirmDialog} from "../dialog/confirmDialog";
import {shouldCheckOtherWindows} from "./openFileWindow";
const isSameCustomTab = (type: string, data: any, options: IOpenFileOptions) => {
@@ -837,13 +838,20 @@ export const openBy = (url: string, type: "folder" | "app") => {
}
/// #if !BROWSER
if (url.startsWith("assets/")) {
- fetchPost("/api/asset/resolveAssetPath", {path: url.replace(/\.pdf\?page=\d{1,}$/, ".pdf")}, (response) => {
- if (type === "app") {
- useShell("openPath", response.data);
- } else if (type === "folder") {
- useShell("showItemInFolder", response.data);
- }
- });
+ const open = () => {
+ fetchPost("/api/asset/resolveAssetPath", {path: url.replace(/\.pdf\?page=\d{1,}$/, ".pdf")}, (response) => {
+ if (type === "app") {
+ useShell("openPath", response.data);
+ } else if (type === "folder") {
+ useShell("showItemInFolder", response.data);
+ }
+ });
+ };
+ if (isEncryptedBox(new URL(url, window.location.origin).searchParams.get("box"))) {
+ confirmDialog(window.siyuan.languages.openBy, window.siyuan.languages.encryptedAssetExternalOpenTip, open);
+ } else {
+ open();
+ }
return;
}
let address = "";
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index b3895a18fe..f148316e10 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -154,6 +154,8 @@ Dynamic multipart endpoints use `MultipartFields` to retain every text value and
## Generation and verification
+`/api/asset/resolveAssetPath` preserves its path-string response and administrator authorization. Unlocked encrypted assets return an authenticated temporary plaintext copy with the original filename; ordinary assets retain their existing paths. The request holds the encrypted notebook lease through response serialization. External edits do not write back to the encrypted source. `TestAPIContractNotebookSystemLock` includes external-asset response validation, original-name preservation, source preservation, authentication-failure cleanup, locked rejection, and lock cleanup; it runs in the full kernel CI selection. Run `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(APIContractNotebookSystemLock|AssetAdminEndpointsRejectReader|MobileExportLease)' -count=1` and `go test ./apicontract/...` for the affected behavior and route coverage.
+
HTML clipboard conversion preserves literal backslashes and marker characters while retaining HTML formatting when Markdown syntax is disabled. `TestHTML2BlockDOMContractEscapedText` covers both source-format modes, actual response schemas, editing round trips, HTML entities, and style/link boundaries. Run it with the related conversion regressions using `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(.*HTML.*|.*Clipboard.*|.*IFrame.*|SpinBlockDOM.*|WPSPresentation.*|NormalizeMSWord.*|NormalizeWPS.*)' -count=1`. The full kernel command below includes these tests, and `app/tests/luteHtmlEscapes.test.js` checks the generated Lute JavaScript through the full frontend suite. Lute source changes also require `go test ./...` in the Lute repository and regeneration of the bundled JavaScript.
Custom block search uses the optional `customBlock` type filter. Explicit API type maps select only their enabled types; omitted type maps use search settings, which enable custom blocks by default. Saved criteria preserve omission separately from `false` so older frontend search configurations can inherit the setting. `TestCustomBlockSearch` regressions cover configuration compatibility, saved criteria, filtering, and FTS updates; `TestAPIContractSettingConfigCompatibility` and `TestAPIContractSettingCompletePayloads` cover the setting contract. All are included in the full kernel command below.
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index d2e0b4cf81..9f1de92c2c 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -471,6 +471,8 @@ Exports have two classes: a user-selected external destination may contain plain
The in-memory `managedEncryptedExports` tokens manage download-link expiry and lifecycle; they are not a security boundary against local files, administrator APIs, or trusted plugins. Lock, delete, cancellation, failure, and normal exit revoke related tokens and best-effort remove `temp/export/<boxID>`. At application startup, entries whose first-level name is a valid boxID are at least scanned and removed; generic desktop temporary-directory initialization also clears the entire `temp/export` directory. No caller may rely on files under `temp/` surviving across processes. Deletion failure only records diagnostics without plaintext and does not prevent the notebook from entering `Locked`; exit or the next startup retries cleanup. Logs, error reports, thumbnails, OCR/conversion output, and clipboard handling contain no plaintext by default unless the user explicitly sends content to an external program.
+When the desktop opens an unlocked encrypted asset externally or reveals its file location, `/api/asset/resolveAssetPath` authenticates the asset and returns a plaintext copy under `temp/export/<boxID>/external/<exportID>/<original filename>`, preserving its extension for system file associations. Revealing the location selects this copy; external edits are not written back to the encrypted attachment. The request holds a notebook lifecycle lease through response completion. Locking and startup perform best-effort cleanup under the managed temporary-directory rules. Locked notebooks and authentication failures still reject access and preserve source ciphertext.
+
Native mobile save flows must call `AcquireExportFile` to obtain a lease containing the path, name, size, and lease ID, then call `ReleaseExportFile` from a `finally` path after copying and verification finish. Encrypted exports must not use legacy path-only or name-only interfaces because those calls cannot cover the native copy phase with a lifecycle lease.
## Compatibility and recovery
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 7dcf3b904a..829dbbbc38 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -467,6 +467,8 @@ assets 加密:
#### 临时明文生命周期
+桌面端对已解锁加密资源执行外部打开或打开文件位置时,`/api/asset/resolveAssetPath` 在认证资源内容后返回 `temp/export/<boxID>/external/<exportID>/<原始文件名>` 下的明文副本路径,保留原始扩展名供系统关联程序识别。打开文件位置定位的是该副本,外部编辑不会写回加密附件。请求持有笔记本生命周期租约直到响应完成;锁定和启动时按受管临时目录规则尽力清理副本。锁定或认证失败仍拒绝访问,并保留源密文。
+
导出分为两类:用户主动选择的外部目的地允许产生明文,但开始前必须提示风险;内核管理的预览、转换、下载和中间产物统一放在 `temp/export/<boxID>/<kind>/<exportID>/`。第一层 boxID 是清理归属标识,不是访问权限;普通导出和插件临时文件不得使用合法 boxID 作为 `temp/export/` 的第一层名称。
内存态导出令牌 `managedEncryptedExports` 用于管理下载链接的有效期和生命周期,不作为本机文件、管理员 API 或受信任插件的安全隔离。锁定、删除、取消、失败和正常退出时必须撤销相关令牌,并尽力删除 `temp/export/<boxID>`;应用启动时至少扫描并删除第一层名称为合法 boxID 的残留目录,桌面端的通用临时目录初始化还会清空整个 `temp/export`。任何调用方都不得依赖 `temp/` 中的文件跨进程存续。删除失败只记录不含明文的诊断,不阻止笔记本进入 `Locked`,后续退出或启动时继续尝试。日志、错误报告、缩略图、OCR/转换产物和剪贴板同样默认不得含明文,除非用户明确交给外部程序。
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 0d694943b3..21a468e3b0 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -375,7 +375,14 @@ var resolveAssetPath = contractHandler(apicontract.ResolveAssetPath, func(c *gin
return apicontract.FailureWithTimeout[string](-1, err.Error(), 3000)
}
if model.IsEncryptedAssetPath(p) {
- return apicontract.FailureWithTimeout[string](-1, model.Conf.Language(314), 3000)
+ if err = holdEncryptedBoxRequest(c, model.ExtractBoxIDFromAssetsPath(p)); err != nil {
+ return apicontract.FailureWithTimeout[string](-1, err.Error(), 3000)
+ }
+ p, err = model.PrepareEncryptedAssetForExternalOpen(path)
+ if err != nil {
+ return apicontract.FailureWithTimeout[string](-1, err.Error(), 3000)
+ }
+ return apicontract.Success(p)
}
if err = model.EnsureAssetPrefixLocal(p); err != nil {
return apicontract.FailureWithTimeout[string](-1, err.Error(), 7000)
diff --git a/kernel/api/asset_crypto_test.go b/kernel/api/asset_crypto_test.go
index 31e23e675e..bdc43dd83a 100644
--- a/kernel/api/asset_crypto_test.go
+++ b/kernel/api/asset_crypto_test.go
@@ -17,6 +17,7 @@
package api
import (
+ "bytes"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -27,9 +28,90 @@ import (
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
+func testResolveEncryptedAssetPath(t *testing.T, boxID string, key []byte) func() {
+ t.Helper()
+ const diskName = "asset-20260918000000-abcdefg.docx"
+ const originalName = "外部文档.docx"
+ plaintext := []byte("external document content")
+ ciphertext, err := model.EncryptAsset(boxID, diskName, originalName, key, plaintext)
+ if err != nil {
+ t.Fatal(err)
+ }
+ source := filepath.Join(util.DataDir, boxID, "assets", diskName)
+ if err = os.MkdirAll(filepath.Dir(source), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(source, ciphertext, 0600); err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ engine.Use(boxLeaseMiddleware)
+ engine.POST("/api/asset/resolveAssetPath", model.CheckAuth, model.CheckAdminRole, resolveAssetPath)
+ resolve := func(assetPath string, wantSuccess bool) string {
+ t.Helper()
+ body, _ := json.Marshal(map[string]string{"path": assetPath})
+ request := httptest.NewRequest(http.MethodPost, "/api/asset/resolveAssetPath", bytes.NewReader(body))
+ request.Header.Set("Authorization", "Token system-lock-test")
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ requireAPIContract(t, http.MethodPost, request.URL.Path, recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data json.RawMessage `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || (response.Code == 0) != wantSuccess {
+ t.Fatalf("resolve asset: %s, %v", recorder.Body.String(), err)
+ }
+ var resolved string
+ if wantSuccess {
+ if err := json.Unmarshal(response.Data, &resolved); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return resolved
+ }
+ assetPath := "assets/" + diskName + "?box=" + boxID
+ exported := resolve(assetPath, true)
+ wantRoot := filepath.Join(util.TempDir, "export", boxID, "external") + string(filepath.Separator)
+ if !strings.HasPrefix(exported, wantRoot) || filepath.Base(exported) != originalName {
+ t.Fatalf("unexpected external asset path: %s", exported)
+ }
+ if data, err := os.ReadFile(exported); err != nil || !bytes.Equal(data, plaintext) {
+ t.Fatalf("unexpected external asset content: %v", err)
+ }
+ if data, err := os.ReadFile(source); err != nil || !bytes.Equal(data, ciphertext) {
+ t.Fatalf("source ciphertext changed: %v", err)
+ }
+ // 认证失败不得发布新副本,也不得删除或改写损坏的源文件。
+ corrupt := append([]byte(nil), ciphertext...)
+ corrupt[len(corrupt)-1] ^= 1
+ if err := os.WriteFile(source, corrupt, 0600); err != nil {
+ t.Fatal(err)
+ }
+ resolve(assetPath, false)
+ if data, err := os.ReadFile(source); err != nil || !bytes.Equal(data, corrupt) {
+ t.Fatalf("corrupt ciphertext changed: %v", err)
+ }
+ entries, err := os.ReadDir(filepath.Dir(filepath.Dir(exported)))
+ if err != nil || len(entries) != 1 {
+ t.Fatalf("failed export left temporary data: %v, %d", err, len(entries))
+ }
+ if err = os.WriteFile(source, ciphertext, 0600); err != nil {
+ t.Fatal(err)
+ }
+ return func() {
+ t.Helper()
+ resolve(assetPath, false)
+ if _, err := os.Stat(exported); !os.IsNotExist(err) {
+ t.Fatalf("locking did not clean external asset: %v", err)
+ }
+ }
+}
+
func TestSetFileAnnotationDoesNotDeleteFromLockedEncryptedNotebook(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/kernel/api/contract_notebook_system_lock_test.go b/kernel/api/contract_notebook_system_lock_test.go
index fcd0ed4b94..a584940c65 100644
--- a/kernel/api/contract_notebook_system_lock_test.go
+++ b/kernel/api/contract_notebook_system_lock_test.go
@@ -88,6 +88,7 @@ func TestAPIContractNotebookSystemLock(t *testing.T) {
t.Fatal(err)
}
gin.SetMode(gin.TestMode)
+ checkExternalAssetLocked := testResolveEncryptedAssetPath(t, boxIDs[0], key)
engine := gin.New()
engine.Use(boxLeaseMiddleware)
engine.POST("/api/notebook/setEncryptedNotebookFollowSystemLock", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setEncryptedNotebookFollowSystemLock)
@@ -165,6 +166,7 @@ func TestAPIContractNotebookSystemLock(t *testing.T) {
t.Fatal("locked notebook admitted a read")
}
}
+ checkExternalAssetLocked()
boxConf = (&model.Box{ID: boxIDs[0]}).GetConf()
if err = model.UnlockBox(boxIDs[0], password, boxConf.BoxCrypt); err != nil {
t.Fatal(err)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index aceb9a5b3b..8d4f7232d1 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -832,6 +832,8 @@ var RemoveUnusedAsset = define[AssetPathRequest, AssetPathData]("removeUnusedAss
var RemoveUnusedAssets = define[EmptyRequest, AssetPathsData]("removeUnusedAssets", "/api/asset/removeUnusedAssets", NoBody, ResponseOptions{}, "POST")
var GetUnusedAssets = define[EmptyRequest, []*AssetUnusedItem]("getUnusedAssets", "/api/asset/getUnusedAssets", NoBody, ResponseOptions{}, "POST")
var GetMissingAssets = define[EmptyRequest, []*AssetUnusedItem]("getMissingAssets", "/api/asset/getMissingAssets", NoBody, ResponseOptions{}, "POST")
+
+// ResolveAssetPath 返回普通资源路径;已解锁的加密资源返回保留原始名称的受管临时明文副本路径。
var ResolveAssetPath = define[AssetPathRequest, string]("resolveAssetPath", "/api/asset/resolveAssetPath", JSONBody, ResponseOptions{}, "POST")
var AssetUploadCloud = define[AssetCloudUploadRequest, Null]("uploadCloud", "/api/asset/uploadCloud", JSONBody, ResponseOptions{}, "POST")
var AssetUploadCloudByAssetsPaths = define[AssetPathsCloudUploadRequest, Null]("uploadCloudByAssetsPaths", "/api/asset/uploadCloudByAssetsPaths", JSONBody, ResponseOptions{}, "POST")
diff --git a/kernel/model/encrypted_export.go b/kernel/model/encrypted_export.go
index 1eb9dfd02d..d0f1d05e66 100644
--- a/kernel/model/encrypted_export.go
+++ b/kernel/model/encrypted_export.go
@@ -238,6 +238,27 @@ func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease,
}
return registerMobileExportLease("", artifact, filepath.Base(artifact), "")
}
+ return prepareEncryptedAssetExport(relativePath, boxID, false)
+}
+
+// PrepareEncryptedAssetForExternalOpen 生成保留原始名称的受管明文副本,供外部程序打开或定位。
+// 副本随笔记本锁定清理,外部程序的修改不会写回加密资源。
+func PrepareEncryptedAssetForExternalOpen(assetPath string) (string, error) {
+ relativePath, boxID, err := assetPathAndBox(assetPath, "")
+ if err != nil {
+ return "", err
+ }
+ if boxID == "" || !IsEncryptedBox(boxID) {
+ return "", errors.New("source is not an encrypted asset")
+ }
+ artifact, err := prepareEncryptedAssetExport(relativePath, boxID, true)
+ if err != nil {
+ return "", err
+ }
+ return artifact.Path, nil
+}
+
+func prepareEncryptedAssetExport(relativePath, boxID string, external bool) (lease *ExportArtifactLease, err error) {
if !IsBoxUnlocked(boxID) {
return nil, errors.New(Conf.Language(314))
}
@@ -269,7 +290,11 @@ func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease,
if idErr != nil {
return nil, idErr
}
- cleanupDir := filepath.Join(util.TempDir, "export", boxID, "mobile", leaseID)
+ kind := "mobile"
+ if external {
+ kind = "external"
+ }
+ cleanupDir := filepath.Join(util.TempDir, "export", boxID, kind, leaseID)
if mkErr := os.MkdirAll(cleanupDir, 0700); mkErr != nil {
return nil, mkErr
}
@@ -311,6 +336,16 @@ func AcquireExportArtifactLease(exportPath string) (lease *ExportArtifactLease,
if originalName == "" || originalName == "." {
originalName = diskName
}
+ if external {
+ namedPath := filepath.Join(cleanupDir, originalName)
+ if plainPath != namedPath {
+ if err = os.Rename(plainPath, namedPath); err != nil {
+ return nil, err
+ }
+ }
+ cleanup = false
+ return &ExportArtifactLease{Path: namedPath, Name: originalName}, nil
+ }
lease, err = registerMobileExportLeaseWithID(leaseID, boxID, plainPath, originalName, cleanupDir)
if err != nil {
_ = os.RemoveAll(cleanupDir)