Skip to content

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

:sparkles: Support encrypted notebook archives and recovery https://github.com/siyuan-note/siyuan/issues/19850

Daniel742361fe7c90
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index d3e53ef385..33706e78a9 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "أرشفة وإزالة",
+ "archiveEncryptedNotebooksTip": "حدد دفاتر الملاحظات المشفرة المقفلة وبيانات استعادتها؛ لا يلزم إدخال كلمة المرور الرئيسية",
+ "restoreEncryptedNotebooks": "استعادة أرشيف مشفر",
+ "restoreEncryptedNotebooksTip": "استخدم مساحة عمل مستقلة بلا مفاتيح تشفير مع إيقاف المزامنة؛ أدخل كلمة المرور الرئيسية القديمة واختر نسخة مفتاح احتياطية مسترجعة إن وجدت",
+ "confirmArchiveSaved": "حفظت الأرشيف خارج مساحة العمل هذه. إزالة دفاتر الملاحظات المحددة وسجلها المرتبط؛ ستنتقل الإزالة إلى الأجهزة الأخرى عبر المزامنة",
+ "archivedEncryptedNotebooks": "تمت الأرشفة والإزالة. بعد أرشفة جميع بيانات الاستعادة القديمة، عطّل دفاتر الملاحظات المشفرة ثم أعد تفعيلها لتعيين كلمة مرور رئيسية جديدة",
+ "archiveKeyFile": "نسخة احتياطية للمفتاح (اختياري)",
+ "archiveHistoryOnly": "السجل واللقطات فقط",
"openContextMenu": "فتح قائمة السياق",
"mobileSlashMenu": "قائمة الشرطة المائلة على الهاتف",
"mobileSlashMenuTip": "عند التفعيل، اكتب / في محرر الهاتف للبحث عن كتل المحتوى وإدراجها",
@@ -2947,6 +2955,13 @@
"397": "لا يمكن لهذا الجهاز إنشاء الملف المتزامن. أعد تسميته في SiYuan على جهاز يمكنه الوصول إليه، ثم أعد المزامنة: %s",
"398": "جارٍ فحص الموارد واللقطات السابقة...",
"399": "جارٍ تنزيل الموارد ومحتوى اللقطات السابقة المفقود...",
- "400": "تعذّر فحص الموارد واللقطات السابقة أو استكمالها. لم يتغير مزوّد المزامنة: %s"
+ "400": "تعذّر فحص الموارد واللقطات السابقة أو استكمالها. لم يتغير مزوّد المزامنة: %s",
+ "401": "أرشيف دفاتر الملاحظات المشفرة غير صالح أو تالف أو يستخدم إصدارًا غير مدعوم",
+ "402": "تغيرت البيانات أو مواد الاستعادة. أنشئ أرشيفًا جديدًا واحفظه قبل الإزالة",
+ "403": "أغلق دفاتر الملاحظات واقفلها وأكمل عمليات الاستعادة المعلقة قبل المحاولة مجددًا",
+ "404": "استعد إلى مساحة عمل مستقلة بلا مفاتيح أو بيانات مشفرة مع إيقاف المزامنة",
+ "405": "فشلت المصادقة. تحقق من كلمة المرور الرئيسية القديمة ونسخة المفتاح المطابقة؛ تم الاحتفاظ بالأرشيف",
+ "406": "فشلت الأرشفة. تم الاحتفاظ بالبيانات الأصلية؛ تحقق من المساحة المتاحة والأذونات وتنزيل الموارد",
+ "407": "أرشف جميع بيانات استعادة دفاتر الملاحظات المشفرة قبل تعطيل التشفير"
}
}
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index e59ce48d23..d5d2a84baf 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archivieren und entfernen",
+ "archiveEncryptedNotebooksTip": "Gesperrte verschlüsselte Notizbücher und ihre Wiederherstellungsdaten auswählen; das Hauptpasswort ist nicht erforderlich",
+ "restoreEncryptedNotebooks": "Verschlüsseltes Archiv wiederherstellen",
+ "restoreEncryptedNotebooksTip": "Einen separaten Arbeitsbereich ohne Verschlüsselungsschlüssel und mit deaktivierter Synchronisierung verwenden; altes Hauptpasswort eingeben und optional eine wiedergefundene Schlüsselsicherung auswählen",
+ "confirmArchiveSaved": "Ich habe das Archiv außerhalb dieses Arbeitsbereichs gespeichert. Die ausgewählten Notizbücher und zugehörigen Verläufe entfernen; dies wird auch auf andere Geräte synchronisiert",
+ "archivedEncryptedNotebooks": "Archiviert und entfernt. Nach der Archivierung aller alten Wiederherstellungsdaten die verschlüsselten Notizbücher deaktivieren und erneut aktivieren, um ein neues Hauptpasswort festzulegen",
+ "archiveKeyFile": "Schlüsselsicherung (optional)",
+ "archiveHistoryOnly": "Nur Verlauf und Schnappschüsse",
"openContextMenu": "Kontextmenü öffnen",
"mobileSlashMenu": "Slash-Menü auf Mobilgeräten",
"mobileSlashMenuTip": "Nach dem Aktivieren / im mobilen Editor eingeben, um Inhaltsblöcke zu suchen und einzufügen",
@@ -2947,6 +2955,13 @@
"397": "Dieses Gerät kann die synchronisierte Datei nicht erstellen. Benennen Sie sie in SiYuan auf einem Gerät um, auf dem sie zugänglich ist, und synchronisieren Sie erneut: %s",
"398": "Ressourcen und frühere Schnappschüsse werden geprüft...",
"399": "Fehlende Ressourcen und Inhalte früherer Schnappschüsse werden heruntergeladen...",
- "400": "Ressourcen und frühere Schnappschüsse konnten nicht geprüft oder vervollständigt werden. Der Synchronisierungsanbieter wurde nicht geändert: %s"
+ "400": "Ressourcen und frühere Schnappschüsse konnten nicht geprüft oder vervollständigt werden. Der Synchronisierungsanbieter wurde nicht geändert: %s",
+ "401": "Das verschlüsselte Notizbucharchiv ist ungültig, beschädigt oder hat eine nicht unterstützte Version",
+ "402": "Daten oder Wiederherstellungsinformationen wurden geändert. Vor dem Entfernen ein neues Archiv erstellen und speichern",
+ "403": "Notizbücher schließen und sperren sowie ausstehende Wiederherstellungen abschließen, dann erneut versuchen",
+ "404": "In einem separaten Arbeitsbereich ohne Verschlüsselungsschlüssel oder verschlüsselte Daten und mit deaktivierter Synchronisierung wiederherstellen",
+ "405": "Authentifizierung fehlgeschlagen. Altes Hauptpasswort und passende Schlüsselsicherung prüfen; das Archiv bleibt erhalten",
+ "406": "Archivierung fehlgeschlagen. Die Originaldaten bleiben erhalten; freien Speicherplatz, Berechtigungen und Ressourcendownloads prüfen",
+ "407": "Vor dem Deaktivieren der Verschlüsselung alle Wiederherstellungsdaten verschlüsselter Notizbücher archivieren"
}
}
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 5878618602..edbca5fa0d 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archive and remove",
+ "archiveEncryptedNotebooksTip": "Select locked encrypted notebooks and their recovery data; no master password is required",
+ "restoreEncryptedNotebooks": "Restore encrypted archive",
+ "restoreEncryptedNotebooksTip": "Use a separate workspace with no encryption keys and sync turned off; enter the old master password and optionally select a recovered key backup",
+ "confirmArchiveSaved": "I have saved the archive outside this workspace. Remove the selected notebooks and related history; removal also propagates through sync",
+ "archivedEncryptedNotebooks": "Archived and removed. After all old recovery dependencies are archived, disable and re-enable encrypted notebooks to set a new master password",
+ "archiveKeyFile": "Key backup (optional)",
+ "archiveHistoryOnly": "History and snapshots only",
"openContextMenu": "Open context menu",
"mobileSlashMenu": "Mobile slash menu",
"mobileSlashMenuTip": "When enabled, type / in the mobile editor to search for and insert content blocks",
@@ -2947,6 +2955,13 @@
"397": "This device cannot create the synced file. Rename it in SiYuan on a device where it is accessible, then sync again: %s",
"398": "Checking resources and historical snapshots...",
"399": "Downloading missing resources and historical snapshot content...",
- "400": "Unable to check or complete resources and historical snapshots. The sync provider was not changed: %s"
+ "400": "Unable to check or complete resources and historical snapshots. The sync provider was not changed: %s",
+ "401": "The encrypted notebook archive is invalid, damaged, or uses an unsupported version",
+ "402": "Data or recovery material changed. Generate and save a new archive before removing it",
+ "403": "Close and lock the notebooks and finish pending recovery operations before trying again",
+ "404": "Restore into a separate workspace with no encryption keys or encrypted data and sync turned off",
+ "405": "Authentication failed. Check the old master password and matching key backup; the archive has been preserved",
+ "406": "The archive operation failed. Original data has been preserved; check available space, permissions, and resource downloads",
+ "407": "Archive all encrypted notebook recovery dependencies before disabling encryption"
}
}
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index eb7ffb6ca4..ce3f263092 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archivar y retirar",
+ "archiveEncryptedNotebooksTip": "Seleccione cuadernos cifrados bloqueados y sus datos de recuperación; no se necesita la contraseña maestra",
+ "restoreEncryptedNotebooks": "Restaurar archivo cifrado",
+ "restoreEncryptedNotebooksTip": "Use un espacio de trabajo independiente sin claves de cifrado y con la sincronización desactivada; introduzca la contraseña maestra anterior y, opcionalmente, una copia recuperada de la clave",
+ "confirmArchiveSaved": "He guardado el archivo fuera de este espacio de trabajo. Retirar los cuadernos seleccionados y su historial; la retirada también se sincronizará con otros dispositivos",
+ "archivedEncryptedNotebooks": "Archivado y retirado. Tras archivar todos los datos de recuperación anteriores, desactive y reactive los cuadernos cifrados para establecer una nueva contraseña maestra",
+ "archiveKeyFile": "Copia de la clave (opcional)",
+ "archiveHistoryOnly": "Solo historial e instantáneas",
"openContextMenu": "Abrir menú contextual",
"mobileSlashMenu": "Menú de barra diagonal en móvil",
"mobileSlashMenuTip": "Al activarlo, escribe / en el editor móvil para buscar e insertar bloques de contenido",
@@ -2947,6 +2955,13 @@
"397": "Este dispositivo no puede crear el archivo sincronizado. Cámbiele el nombre en SiYuan desde un dispositivo donde sea accesible y vuelva a sincronizar: %s",
"398": "Comprobando recursos e instantáneas anteriores...",
"399": "Descargando recursos y contenido de instantáneas anteriores que faltan...",
- "400": "No se pudieron comprobar o completar los recursos y las instantáneas anteriores. El proveedor de sincronización no ha cambiado: %s"
+ "400": "No se pudieron comprobar o completar los recursos y las instantáneas anteriores. El proveedor de sincronización no ha cambiado: %s",
+ "401": "El archivo de cuadernos cifrados no es válido, está dañado o usa una versión no compatible",
+ "402": "Los datos o el material de recuperación han cambiado. Genere y guarde un nuevo archivo antes de retirarlos",
+ "403": "Cierre y bloquee los cuadernos y finalice las recuperaciones pendientes antes de volver a intentarlo",
+ "404": "Restaure en un espacio de trabajo independiente sin claves ni datos cifrados y con la sincronización desactivada",
+ "405": "Error de autenticación. Compruebe la contraseña maestra anterior y la copia de clave correspondiente; el archivo se ha conservado",
+ "406": "Error al archivar. Se han conservado los datos originales; compruebe el espacio libre, los permisos y las descargas de recursos",
+ "407": "Archive todos los datos de recuperación de cuadernos cifrados antes de desactivar el cifrado"
}
}
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 1fe1b379e2..d6e67dfc34 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archiver et retirer",
+ "archiveEncryptedNotebooksTip": "Sélectionnez les carnets chiffrés verrouillés et leurs données de récupération ; le mot de passe principal n’est pas nécessaire",
+ "restoreEncryptedNotebooks": "Restaurer une archive chiffrée",
+ "restoreEncryptedNotebooksTip": "Utilisez un espace de travail distinct sans clés de chiffrement et sans synchronisation ; saisissez l’ancien mot de passe principal et sélectionnez éventuellement une sauvegarde de clé retrouvée",
+ "confirmArchiveSaved": "J’ai enregistré l’archive hors de cet espace de travail. Retirer les carnets sélectionnés et leur historique ; ce retrait sera aussi synchronisé avec les autres appareils",
+ "archivedEncryptedNotebooks": "Archivage et retrait terminés. Après avoir archivé toutes les anciennes données de récupération, désactivez puis réactivez les carnets chiffrés pour définir un nouveau mot de passe principal",
+ "archiveKeyFile": "Sauvegarde de clé (facultatif)",
+ "archiveHistoryOnly": "Historique et instantanés uniquement",
"openContextMenu": "Ouvrir le menu contextuel",
"mobileSlashMenu": "Menu barre oblique sur mobile",
"mobileSlashMenuTip": "Une fois activé, saisissez / dans l’éditeur mobile pour rechercher et insérer des blocs de contenu",
@@ -2947,6 +2955,13 @@
"397": "Cet appareil ne peut pas créer le fichier synchronisé. Renommez-le dans SiYuan sur un appareil où il est accessible, puis relancez la synchronisation : %s",
"398": "Vérification des ressources et des anciens instantanés...",
"399": "Téléchargement des ressources et du contenu manquant des anciens instantanés...",
- "400": "Impossible de vérifier ou de compléter les ressources et les anciens instantanés. Le fournisseur de synchronisation n’a pas été modifié : %s"
+ "400": "Impossible de vérifier ou de compléter les ressources et les anciens instantanés. Le fournisseur de synchronisation n’a pas été modifié : %s",
+ "401": "L’archive de carnets chiffrés est invalide, endommagée ou utilise une version non prise en charge",
+ "402": "Les données ou éléments de récupération ont changé. Créez et enregistrez une nouvelle archive avant le retrait",
+ "403": "Fermez et verrouillez les carnets, puis terminez les opérations de récupération en attente avant de réessayer",
+ "404": "Restaurez dans un espace de travail distinct sans clés ni données chiffrées, avec la synchronisation désactivée",
+ "405": "Échec de l’authentification. Vérifiez l’ancien mot de passe principal et la sauvegarde de clé correspondante ; l’archive est conservée",
+ "406": "Échec de l’archivage. Les données originales sont conservées ; vérifiez l’espace disponible, les autorisations et les téléchargements de ressources",
+ "407": "Archivez toutes les données de récupération des carnets chiffrés avant de désactiver le chiffrement"
}
}
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 97b4f78912..40e7d97faa 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "ארכוב והסרה",
+ "archiveEncryptedNotebooksTip": "יש לבחור מחברות מוצפנות נעולות ואת נתוני השחזור שלהן; אין צורך בסיסמה הראשית",
+ "restoreEncryptedNotebooks": "שחזור ארכיון מוצפן",
+ "restoreEncryptedNotebooksTip": "יש להשתמש במרחב עבודה נפרד ללא מפתחות הצפנה ועם סנכרון כבוי; להזין את הסיסמה הראשית הישנה ולבחור גיבוי מפתח שנמצא, אם יש",
+ "confirmArchiveSaved": "שמרתי את הארכיון מחוץ למרחב העבודה הזה. להסיר את המחברות שנבחרו ואת ההיסטוריה שלהן; ההסרה תועבר גם למכשירים אחרים באמצעות סנכרון",
+ "archivedEncryptedNotebooks": "הארכוב וההסרה הושלמו. לאחר ארכוב כל נתוני השחזור הישנים, יש להשבית ולהפעיל מחדש מחברות מוצפנות כדי להגדיר סיסמה ראשית חדשה",
+ "archiveKeyFile": "גיבוי מפתח (לא חובה)",
+ "archiveHistoryOnly": "היסטוריה ותמונות מצב בלבד",
"openContextMenu": "פתיחת תפריט ההקשר",
"mobileSlashMenu": "תפריט לוכסן בנייד",
"mobileSlashMenuTip": "לאחר ההפעלה, הקלידו / בעורך לנייד כדי לחפש ולהוסיף בלוקי תוכן",
@@ -2947,6 +2955,13 @@
"397": "מכשיר זה אינו יכול ליצור את הקובץ המסונכרן. יש לשנות את שמו ב-SiYuan במכשיר שבו הוא נגיש, ואז לסנכרן שוב: %s",
"398": "בודק משאבים ותמונות מצב קודמות...",
"399": "מוריד משאבים ותוכן חסר של תמונות מצב קודמות...",
- "400": "לא ניתן לבדוק או להשלים משאבים ותמונות מצב קודמות. ספק הסנכרון לא השתנה: %s"
+ "400": "לא ניתן לבדוק או להשלים משאבים ותמונות מצב קודמות. ספק הסנכרון לא השתנה: %s",
+ "401": "ארכיון המחברות המוצפנות אינו תקין, פגום או משתמש בגרסה שאינה נתמכת",
+ "402": "הנתונים או חומרי השחזור השתנו. יש ליצור ולשמור ארכיון חדש לפני ההסרה",
+ "403": "יש לסגור ולנעול את המחברות ולהשלים פעולות שחזור ממתינות לפני ניסיון נוסף",
+ "404": "יש לשחזר במרחב עבודה נפרד ללא מפתחות או נתונים מוצפנים ועם סנכרון כבוי",
+ "405": "האימות נכשל. יש לבדוק את הסיסמה הראשית הישנה ואת גיבוי המפתח התואם; הארכיון נשמר",
+ "406": "הארכוב נכשל. הנתונים המקוריים נשמרו; יש לבדוק מקום פנוי, הרשאות והורדת משאבים",
+ "407": "יש לארכב את כל נתוני השחזור של המחברות המוצפנות לפני השבתת ההצפנה"
}
}
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 5121ae5096..c5533f2345 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "संग्रहित करके हटाएँ",
+ "archiveEncryptedNotebooksTip": "लॉक की गई एन्क्रिप्टेड नोटबुक और उनका पुनर्प्राप्ति डेटा चुनें; मास्टर पासवर्ड की आवश्यकता नहीं है",
+ "restoreEncryptedNotebooks": "एन्क्रिप्टेड संग्रह पुनर्स्थापित करें",
+ "restoreEncryptedNotebooksTip": "बिना एन्क्रिप्शन कुंजी वाले अलग कार्यक्षेत्र में सिंक बंद करके पुराना मास्टर पासवर्ड दर्ज करें; मिली हुई कुंजी का बैकअप भी चुन सकते हैं",
+ "confirmArchiveSaved": "मैंने संग्रह इस कार्यक्षेत्र से बाहर सहेज लिया है। चुनी गई नोटबुक और संबंधित इतिहास हटाएँ; यह बदलाव सिंक के माध्यम से अन्य उपकरणों पर भी लागू होगा",
+ "archivedEncryptedNotebooks": "संग्रहित करके हटा दिया गया। सभी पुराने पुनर्प्राप्ति डेटा का संग्रह बनाने के बाद नया मास्टर पासवर्ड सेट करने के लिए एन्क्रिप्टेड नोटबुक बंद करके दोबारा चालू करें",
+ "archiveKeyFile": "कुंजी का बैकअप (वैकल्पिक)",
+ "archiveHistoryOnly": "केवल इतिहास और स्नैपशॉट",
"openContextMenu": "संदर्भ मेनू खोलें",
"mobileSlashMenu": "मोबाइल स्लैश मेनू",
"mobileSlashMenuTip": "चालू होने पर, सामग्री ब्लॉक खोजने और डालने के लिए मोबाइल संपादक में / टाइप करें",
@@ -2947,6 +2955,13 @@
"397": "यह डिवाइस सिंक की गई फ़ाइल नहीं बना सकता। जिस डिवाइस पर फ़ाइल उपलब्ध है, वहाँ SiYuan में उसका नाम बदलें और फिर से सिंक करें: %s",
"398": "संसाधनों और पुराने स्नैपशॉट की जाँच हो रही है...",
"399": "अनुपलब्ध संसाधन और पुराने स्नैपशॉट की सामग्री डाउनलोड हो रही है...",
- "400": "संसाधनों और पुराने स्नैपशॉट की जाँच या पूर्ति नहीं हो सकी। सिंक प्रदाता नहीं बदला गया: %s"
+ "400": "संसाधनों और पुराने स्नैपशॉट की जाँच या पूर्ति नहीं हो सकी। सिंक प्रदाता नहीं बदला गया: %s",
+ "401": "एन्क्रिप्टेड नोटबुक संग्रह अमान्य या क्षतिग्रस्त है, या उसका संस्करण समर्थित नहीं है",
+ "402": "डेटा या पुनर्प्राप्ति सामग्री बदल गई है। हटाने से पहले नया संग्रह बनाएँ और सहेजें",
+ "403": "दोबारा प्रयास करने से पहले नोटबुक बंद करके लॉक करें और लंबित पुनर्प्राप्ति पूरी करें",
+ "404": "बिना एन्क्रिप्शन कुंजी या एन्क्रिप्टेड डेटा वाले अलग कार्यक्षेत्र में सिंक बंद करके पुनर्स्थापित करें",
+ "405": "प्रमाणीकरण विफल रहा। पुराना मास्टर पासवर्ड और संबंधित कुंजी बैकअप जाँचें; संग्रह सुरक्षित रखा गया है",
+ "406": "संग्रह प्रक्रिया विफल रही। मूल डेटा सुरक्षित है; खाली जगह, अनुमतियाँ और संसाधन डाउनलोड जाँचें",
+ "407": "एन्क्रिप्शन बंद करने से पहले सभी एन्क्रिप्टेड नोटबुक का पुनर्प्राप्ति डेटा संग्रहित करें"
}
}
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index f9fe3e4549..902e3b0663 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Arsipkan dan keluarkan",
+ "archiveEncryptedNotebooksTip": "Pilih buku catatan terenkripsi yang terkunci beserta data pemulihannya; kata sandi utama tidak diperlukan",
+ "restoreEncryptedNotebooks": "Pulihkan arsip terenkripsi",
+ "restoreEncryptedNotebooksTip": "Gunakan ruang kerja terpisah tanpa kunci enkripsi dan dengan sinkronisasi dimatikan; masukkan kata sandi utama lama dan pilih cadangan kunci yang ditemukan jika ada",
+ "confirmArchiveSaved": "Saya telah menyimpan arsip di luar ruang kerja ini. Keluarkan buku catatan terpilih dan riwayat terkait; penghapusan juga disinkronkan ke perangkat lain",
+ "archivedEncryptedNotebooks": "Pengarsipan dan pengeluaran selesai. Setelah semua data pemulihan lama diarsipkan, nonaktifkan lalu aktifkan kembali buku catatan terenkripsi untuk menetapkan kata sandi utama baru",
+ "archiveKeyFile": "Cadangan kunci (opsional)",
+ "archiveHistoryOnly": "Hanya riwayat dan snapshot",
"openContextMenu": "Buka menu konteks",
"mobileSlashMenu": "Menu garis miring di ponsel",
"mobileSlashMenuTip": "Jika diaktifkan, ketik / di editor ponsel untuk mencari dan menyisipkan blok konten",
@@ -2947,6 +2955,13 @@
"397": "Perangkat ini tidak dapat membuat berkas yang disinkronkan. Ubah namanya di SiYuan pada perangkat yang dapat mengaksesnya, lalu sinkronkan kembali: %s",
"398": "Memeriksa sumber daya dan snapshot lama...",
"399": "Mengunduh sumber daya dan konten snapshot lama yang hilang...",
- "400": "Tidak dapat memeriksa atau melengkapi sumber daya dan snapshot lama. Penyedia sinkronisasi tidak diubah: %s"
+ "400": "Tidak dapat memeriksa atau melengkapi sumber daya dan snapshot lama. Penyedia sinkronisasi tidak diubah: %s",
+ "401": "Arsip buku catatan terenkripsi tidak valid, rusak, atau menggunakan versi yang tidak didukung",
+ "402": "Data atau bahan pemulihan telah berubah. Buat dan simpan arsip baru sebelum mengeluarkannya",
+ "403": "Tutup dan kunci buku catatan serta selesaikan pemulihan tertunda sebelum mencoba lagi",
+ "404": "Pulihkan ke ruang kerja terpisah tanpa kunci atau data terenkripsi dan dengan sinkronisasi dimatikan",
+ "405": "Autentikasi gagal. Periksa kata sandi utama lama dan cadangan kunci yang sesuai; arsip tetap disimpan",
+ "406": "Pengarsipan gagal. Data asli tetap disimpan; periksa ruang kosong, izin, dan unduhan sumber daya",
+ "407": "Arsipkan semua data pemulihan buku catatan terenkripsi sebelum menonaktifkan enkripsi"
}
}
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 703c160415..319c5416b2 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archivia e rimuovi",
+ "archiveEncryptedNotebooksTip": "Seleziona i quaderni cifrati bloccati e i relativi dati di recupero; non è necessaria la password principale",
+ "restoreEncryptedNotebooks": "Ripristina archivio cifrato",
+ "restoreEncryptedNotebooksTip": "Usa uno spazio di lavoro separato senza chiavi di cifratura e con sincronizzazione disattivata; inserisci la vecchia password principale e, facoltativamente, un backup della chiave ritrovato",
+ "confirmArchiveSaved": "Ho salvato l’archivio fuori da questo spazio di lavoro. Rimuovi i quaderni selezionati e la relativa cronologia; la rimozione verrà sincronizzata anche con gli altri dispositivi",
+ "archivedEncryptedNotebooks": "Archiviato e rimosso. Dopo aver archiviato tutti i vecchi dati di recupero, disattiva e riattiva i quaderni cifrati per impostare una nuova password principale",
+ "archiveKeyFile": "Backup della chiave (facoltativo)",
+ "archiveHistoryOnly": "Solo cronologia e istantanee",
"openContextMenu": "Apri menu contestuale",
"mobileSlashMenu": "Menu barra nell'editor mobile",
"mobileSlashMenuTip": "Quando è attivo, digita / nell'editor mobile per cercare e inserire blocchi di contenuto",
@@ -2947,6 +2955,13 @@
"397": "Questo dispositivo non può creare il file sincronizzato. Rinominalo in SiYuan su un dispositivo da cui è accessibile, quindi sincronizza di nuovo: %s",
"398": "Verifica delle risorse e delle istantanee precedenti...",
"399": "Download delle risorse e dei contenuti mancanti delle istantanee precedenti...",
- "400": "Impossibile verificare o completare le risorse e le istantanee precedenti. Il provider di sincronizzazione non è stato modificato: %s"
+ "400": "Impossibile verificare o completare le risorse e le istantanee precedenti. Il provider di sincronizzazione non è stato modificato: %s",
+ "401": "L’archivio dei quaderni cifrati non è valido, è danneggiato o usa una versione non supportata",
+ "402": "I dati o il materiale di recupero sono cambiati. Genera e salva un nuovo archivio prima della rimozione",
+ "403": "Chiudi e blocca i quaderni e completa i recuperi in sospeso prima di riprovare",
+ "404": "Ripristina in uno spazio di lavoro separato senza chiavi o dati cifrati e con sincronizzazione disattivata",
+ "405": "Autenticazione non riuscita. Controlla la vecchia password principale e il backup della chiave corrispondente; l’archivio è stato conservato",
+ "406": "Archiviazione non riuscita. I dati originali sono stati conservati; controlla spazio disponibile, autorizzazioni e download delle risorse",
+ "407": "Archivia tutti i dati di recupero dei quaderni cifrati prima di disattivare la cifratura"
}
}
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 83c89572e8..8f88c93a45 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "アーカイブして移出",
+ "archiveEncryptedNotebooksTip": "ロック済みの暗号化ノートブックと復元データを選択します。マスターパスワードは不要です",
+ "restoreEncryptedNotebooks": "暗号化アーカイブを復元",
+ "restoreEncryptedNotebooksTip": "暗号鍵が未設定で同期が無効の別のワークスペースを使用し、以前のマスターパスワードを入力してください。見つかった鍵のバックアップも選択できます",
+ "confirmArchiveSaved": "アーカイブをこのワークスペースの外に保存しました。選択したノートブックと関連履歴の移出を確認します。移出は同期を通じて他の端末にも反映されます",
+ "archivedEncryptedNotebooks": "アーカイブして移出しました。以前の復元データをすべてアーカイブした後、暗号化ノートブックを無効化して再度有効化すると、新しいマスターパスワードを設定できます",
+ "archiveKeyFile": "鍵のバックアップ(任意)",
+ "archiveHistoryOnly": "履歴とスナップショットのみ",
"openContextMenu": "コンテキストメニューを開く",
"mobileSlashMenu": "モバイルのスラッシュメニュー",
"mobileSlashMenuTip": "有効にすると、モバイルエディターで / を入力してコンテンツブロックを検索、挿入できます",
@@ -2947,6 +2955,13 @@
"397": "このデバイスでは同期ファイルを作成できません。ファイルにアクセスできるデバイスの SiYuan で名前を変更してから、再度同期してください:%s",
"398": "リソースと過去のスナップショットの完全性を確認しています...",
"399": "不足しているリソースと過去のスナップショットの内容をダウンロードしています...",
- "400": "リソースと過去のスナップショットを確認または補完できませんでした。同期プロバイダーは変更されていません:%s"
+ "400": "リソースと過去のスナップショットを確認または補完できませんでした。同期プロバイダーは変更されていません:%s",
+ "401": "暗号化ノートブックのアーカイブが無効、破損、または未対応のバージョンです",
+ "402": "データまたは復元情報が変更されました。新しいアーカイブを作成して保存してから移出してください",
+ "403": "ノートブックを閉じてロックし、保留中の復元処理を完了してから再試行してください",
+ "404": "暗号鍵と暗号化データがなく、同期が無効の別のワークスペースで復元してください",
+ "405": "認証に失敗しました。以前のマスターパスワードと対応する鍵のバックアップを確認してください。アーカイブは保持されています",
+ "406": "アーカイブ処理に失敗しました。元のデータは保持されています。空き容量、権限、リソースのダウンロードを確認してください",
+ "407": "暗号化を無効にする前に、暗号化ノートブックの復元に必要なデータをすべてアーカイブしてください"
}
}
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index a39f78eb11..767fd9c6b6 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "보관 후 내보내기",
+ "archiveEncryptedNotebooksTip": "잠긴 암호화 노트북과 복구 데이터를 선택하세요. 마스터 비밀번호는 필요하지 않습니다",
+ "restoreEncryptedNotebooks": "암호화 보관 파일 복원",
+ "restoreEncryptedNotebooksTip": "암호화 키가 설정되지 않고 동기화가 꺼진 별도 작업 공간에서 이전 마스터 비밀번호를 입력하세요. 찾은 키 백업도 선택할 수 있습니다",
+ "confirmArchiveSaved": "보관 파일을 이 작업 공간 외부에 저장했습니다. 선택한 노트북과 관련 기록을 제거합니다. 이 변경은 동기화를 통해 다른 기기에도 적용됩니다",
+ "archivedEncryptedNotebooks": "보관 후 제거했습니다. 이전 복구 데이터를 모두 보관한 뒤 암호화 노트북을 껐다가 다시 켜면 새 마스터 비밀번호를 설정할 수 있습니다",
+ "archiveKeyFile": "키 백업(선택 사항)",
+ "archiveHistoryOnly": "기록과 스냅샷만",
"openContextMenu": "컨텍스트 메뉴 열기",
"mobileSlashMenu": "모바일 슬래시 메뉴",
"mobileSlashMenuTip": "활성화하면 모바일 편집기에서 /를 입력해 콘텐츠 블록을 검색하고 삽입할 수 있습니다",
@@ -2947,6 +2955,13 @@
"397": "이 기기에서는 동기화된 파일을 만들 수 없습니다. 파일에 접근할 수 있는 기기의 SiYuan에서 이름을 변경한 후 다시 동기화하세요: %s",
"398": "리소스와 과거 스냅샷의 무결성을 확인하는 중...",
"399": "누락된 리소스와 과거 스냅샷 내용을 다운로드하는 중...",
- "400": "리소스와 과거 스냅샷을 확인하거나 보완할 수 없습니다. 동기화 제공업체는 변경되지 않았습니다: %s"
+ "400": "리소스와 과거 스냅샷을 확인하거나 보완할 수 없습니다. 동기화 제공업체는 변경되지 않았습니다: %s",
+ "401": "암호화 노트북 보관 파일이 잘못되었거나 손상되었거나 지원하지 않는 버전입니다",
+ "402": "데이터 또는 복구 정보가 변경되었습니다. 새 보관 파일을 생성하고 저장한 후 제거하세요",
+ "403": "노트북을 닫고 잠근 다음 진행 중인 복구 작업을 완료한 후 다시 시도하세요",
+ "404": "암호화 키와 암호화 데이터가 없고 동기화가 꺼진 별도 작업 공간에서 복원하세요",
+ "405": "인증에 실패했습니다. 이전 마스터 비밀번호와 일치하는 키 백업을 확인하세요. 원본 보관 파일은 유지됩니다",
+ "406": "보관 작업에 실패했습니다. 원본 데이터는 유지됩니다. 여유 공간, 권한, 리소스 다운로드를 확인하세요",
+ "407": "암호화를 끄기 전에 모든 암호화 노트북 복구 데이터를 보관하세요"
}
}
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 5df309a8ce..a21fd927d3 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archiveren en verwijderen",
+ "archiveEncryptedNotebooksTip": "Selecteer vergrendelde versleutelde notitieboeken en hun herstelgegevens; het hoofdwachtwoord is niet nodig",
+ "restoreEncryptedNotebooks": "Versleuteld archief herstellen",
+ "restoreEncryptedNotebooksTip": "Gebruik een aparte werkruimte zonder versleutelingssleutels en met synchronisatie uitgeschakeld; voer het oude hoofdwachtwoord in en selecteer eventueel een teruggevonden sleutelback-up",
+ "confirmArchiveSaved": "Ik heb het archief buiten deze werkruimte opgeslagen. Verwijder de geselecteerde notitieboeken en bijbehorende geschiedenis; dit wordt ook met andere apparaten gesynchroniseerd",
+ "archivedEncryptedNotebooks": "Gearchiveerd en verwijderd. Schakel versleutelde notitieboeken uit en weer in nadat alle oude herstelgegevens zijn gearchiveerd om een nieuw hoofdwachtwoord in te stellen",
+ "archiveKeyFile": "Sleutelback-up (optioneel)",
+ "archiveHistoryOnly": "Alleen geschiedenis en momentopnamen",
"openContextMenu": "Contextmenu openen",
"mobileSlashMenu": "Slashmenu op mobiel",
"mobileSlashMenuTip": "Typ na inschakelen / in de mobiele editor om inhoudsblokken te zoeken en in te voegen",
@@ -2947,6 +2955,13 @@
"397": "Dit apparaat kan het gesynchroniseerde bestand niet aanmaken. Hernoem het in SiYuan op een apparaat waarop het toegankelijk is en synchroniseer opnieuw: %s",
"398": "Bronnen en eerdere momentopnamen controleren...",
"399": "Ontbrekende bronnen en inhoud van eerdere momentopnamen downloaden...",
- "400": "Bronnen en eerdere momentopnamen konden niet worden gecontroleerd of aangevuld. De synchronisatieprovider is niet gewijzigd: %s"
+ "400": "Bronnen en eerdere momentopnamen konden niet worden gecontroleerd of aangevuld. De synchronisatieprovider is niet gewijzigd: %s",
+ "401": "Het archief met versleutelde notitieboeken is ongeldig, beschadigd of heeft een niet-ondersteunde versie",
+ "402": "Gegevens of herstelmateriaal zijn gewijzigd. Maak en bewaar een nieuw archief voordat u ze verwijdert",
+ "403": "Sluit en vergrendel de notitieboeken en voltooi openstaande herstelbewerkingen voordat u het opnieuw probeert",
+ "404": "Herstel in een aparte werkruimte zonder sleutels of versleutelde gegevens en met synchronisatie uitgeschakeld",
+ "405": "Authenticatie mislukt. Controleer het oude hoofdwachtwoord en de bijbehorende sleutelback-up; het archief is bewaard",
+ "406": "Archivering mislukt. De oorspronkelijke gegevens zijn bewaard; controleer vrije ruimte, machtigingen en het downloaden van bronnen",
+ "407": "Archiveer alle herstelgegevens van versleutelde notitieboeken voordat u versleuteling uitschakelt"
}
}
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index c8ff594b5a..7299ed5d05 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archiwizuj i usuń",
+ "archiveEncryptedNotebooksTip": "Wybierz zablokowane zaszyfrowane notesy i ich dane odzyskiwania; hasło główne nie jest wymagane",
+ "restoreEncryptedNotebooks": "Przywróć zaszyfrowane archiwum",
+ "restoreEncryptedNotebooksTip": "Użyj osobnego obszaru roboczego bez kluczy szyfrowania i z wyłączoną synchronizacją; wpisz stare hasło główne i opcjonalnie wybierz odzyskaną kopię klucza",
+ "confirmArchiveSaved": "Archiwum zapisano poza tym obszarem roboczym. Usuń wybrane notesy i ich historię; usunięcie zostanie również zsynchronizowane z innymi urządzeniami",
+ "archivedEncryptedNotebooks": "Zarchiwizowano i usunięto. Po zarchiwizowaniu wszystkich starych danych odzyskiwania wyłącz i włącz ponownie zaszyfrowane notesy, aby ustawić nowe hasło główne",
+ "archiveKeyFile": "Kopia klucza (opcjonalnie)",
+ "archiveHistoryOnly": "Tylko historia i migawki",
"openContextMenu": "Otwórz menu kontekstowe",
"mobileSlashMenu": "Menu ukośnika na urządzeniu mobilnym",
"mobileSlashMenuTip": "Po włączeniu wpisz / w edytorze mobilnym, aby wyszukać i wstawić bloki treści",
@@ -2947,6 +2955,13 @@
"397": "To urządzenie nie może utworzyć synchronizowanego pliku. Zmień jego nazwę w SiYuan na urządzeniu, na którym jest dostępny, a następnie zsynchronizuj ponownie: %s",
"398": "Sprawdzanie zasobów i wcześniejszych migawek...",
"399": "Pobieranie brakujących zasobów i zawartości wcześniejszych migawek...",
- "400": "Nie można sprawdzić ani uzupełnić zasobów i wcześniejszych migawek. Dostawca synchronizacji nie został zmieniony: %s"
+ "400": "Nie można sprawdzić ani uzupełnić zasobów i wcześniejszych migawek. Dostawca synchronizacji nie został zmieniony: %s",
+ "401": "Archiwum zaszyfrowanych notesów jest nieprawidłowe, uszkodzone lub ma nieobsługiwaną wersję",
+ "402": "Dane lub materiały odzyskiwania uległy zmianie. Utwórz i zapisz nowe archiwum przed usunięciem",
+ "403": "Zamknij i zablokuj notesy oraz zakończ oczekujące operacje odzyskiwania przed ponowną próbą",
+ "404": "Przywróć w osobnym obszarze roboczym bez kluczy i zaszyfrowanych danych, z wyłączoną synchronizacją",
+ "405": "Uwierzytelnianie nie powiodło się. Sprawdź stare hasło główne i pasującą kopię klucza; archiwum zachowano",
+ "406": "Archiwizacja nie powiodła się. Zachowano dane źródłowe; sprawdź wolne miejsce, uprawnienia i pobieranie zasobów",
+ "407": "Przed wyłączeniem szyfrowania zarchiwizuj wszystkie dane odzyskiwania zaszyfrowanych notesów"
}
}
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index c87b026f62..6c0099ac48 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Arquivar e remover",
+ "archiveEncryptedNotebooksTip": "Selecione os cadernos criptografados bloqueados e seus dados de recuperação; a senha mestra não é necessária",
+ "restoreEncryptedNotebooks": "Restaurar arquivo criptografado",
+ "restoreEncryptedNotebooksTip": "Use um espaço de trabalho separado sem chaves de criptografia e com sincronização desativada; informe a senha mestra antiga e, opcionalmente, um backup de chave recuperado",
+ "confirmArchiveSaved": "Salvei o arquivo fora deste espaço de trabalho. Remover os cadernos selecionados e seu histórico; a remoção também será sincronizada com outros dispositivos",
+ "archivedEncryptedNotebooks": "Arquivamento e remoção concluídos. Após arquivar todos os dados de recuperação antigos, desative e reative os cadernos criptografados para definir uma nova senha mestra",
+ "archiveKeyFile": "Backup da chave (opcional)",
+ "archiveHistoryOnly": "Somente histórico e instantâneos",
"openContextMenu": "Abrir menu de contexto",
"mobileSlashMenu": "Menu de barra no celular",
"mobileSlashMenuTip": "Quando ativado, digite / no editor móvel para pesquisar e inserir blocos de conteúdo",
@@ -2947,6 +2955,13 @@
"397": "Este dispositivo não pode criar o arquivo sincronizado. Renomeie-o no SiYuan em um dispositivo onde ele esteja acessível e sincronize novamente: %s",
"398": "Verificando recursos e snapshots anteriores...",
"399": "Baixando recursos e conteúdo ausente de snapshots anteriores...",
- "400": "Não foi possível verificar ou completar os recursos e os snapshots anteriores. O provedor de sincronização não foi alterado: %s"
+ "400": "Não foi possível verificar ou completar os recursos e os snapshots anteriores. O provedor de sincronização não foi alterado: %s",
+ "401": "O arquivo de cadernos criptografados é inválido, está danificado ou usa uma versão não compatível",
+ "402": "Os dados ou materiais de recuperação mudaram. Gere e salve um novo arquivo antes de removê-los",
+ "403": "Feche e bloqueie os cadernos e conclua as recuperações pendentes antes de tentar novamente",
+ "404": "Restaure em um espaço de trabalho separado sem chaves ou dados criptografados e com sincronização desativada",
+ "405": "Falha na autenticação. Confira a senha mestra antiga e o backup de chave correspondente; o arquivo foi preservado",
+ "406": "Falha no arquivamento. Os dados originais foram preservados; verifique espaço livre, permissões e downloads de recursos",
+ "407": "Arquive todos os dados de recuperação dos cadernos criptografados antes de desativar a criptografia"
}
}
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 7c22d1a275..4f37391f29 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Архивировать и убрать",
+ "archiveEncryptedNotebooksTip": "Выберите заблокированные зашифрованные блокноты и данные восстановления; мастер-пароль не требуется",
+ "restoreEncryptedNotebooks": "Восстановить зашифрованный архив",
+ "restoreEncryptedNotebooksTip": "Используйте отдельное рабочее пространство без ключей шифрования с отключённой синхронизацией; введите старый мастер-пароль и при необходимости выберите найденную копию ключа",
+ "confirmArchiveSaved": "Я сохранил архив вне этого рабочего пространства. Убрать выбранные блокноты и их историю; удаление также будет синхронизировано с другими устройствами",
+ "archivedEncryptedNotebooks": "Архивирование и удаление завершены. После архивации всех старых данных восстановления отключите и снова включите зашифрованные блокноты, чтобы задать новый мастер-пароль",
+ "archiveKeyFile": "Резервная копия ключа (необязательно)",
+ "archiveHistoryOnly": "Только история и снимки",
"openContextMenu": "Открыть контекстное меню",
"mobileSlashMenu": "Меню косой черты на мобильном устройстве",
"mobileSlashMenuTip": "После включения введите / в мобильном редакторе, чтобы найти и вставить блоки содержимого",
@@ -2947,6 +2955,13 @@
"397": "На этом устройстве невозможно создать синхронизируемый файл. Переименуйте его в SiYuan на устройстве, где он доступен, затем повторите синхронизацию: %s",
"398": "Проверка ресурсов и предыдущих снимков...",
"399": "Загрузка недостающих ресурсов и содержимого предыдущих снимков...",
- "400": "Не удалось проверить или восстановить ресурсы и предыдущие снимки. Провайдер синхронизации не изменён: %s"
+ "400": "Не удалось проверить или восстановить ресурсы и предыдущие снимки. Провайдер синхронизации не изменён: %s",
+ "401": "Архив зашифрованных блокнотов недействителен, повреждён или имеет неподдерживаемую версию",
+ "402": "Данные или материалы восстановления изменились. Создайте и сохраните новый архив перед удалением",
+ "403": "Закройте и заблокируйте блокноты, завершите ожидающие операции восстановления и повторите попытку",
+ "404": "Восстанавливайте в отдельном рабочем пространстве без ключей и зашифрованных данных с отключённой синхронизацией",
+ "405": "Ошибка аутентификации. Проверьте старый мастер-пароль и соответствующую копию ключа; архив сохранён",
+ "406": "Не удалось выполнить архивацию. Исходные данные сохранены; проверьте свободное место, права доступа и загрузку ресурсов",
+ "407": "Перед отключением шифрования архивируйте все данные восстановления зашифрованных блокнотов"
}
}
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 63792677ff..74965b91b6 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Archivovať a odstrániť",
+ "archiveEncryptedNotebooksTip": "Vyberte zamknuté šifrované poznámkové bloky a ich údaje na obnovu; hlavné heslo nie je potrebné",
+ "restoreEncryptedNotebooks": "Obnoviť šifrovaný archív",
+ "restoreEncryptedNotebooksTip": "Použite samostatný pracovný priestor bez šifrovacích kľúčov a s vypnutou synchronizáciou; zadajte staré hlavné heslo a prípadne vyberte nájdenú zálohu kľúča",
+ "confirmArchiveSaved": "Archív som uložil mimo tohto pracovného priestoru. Odstrániť vybrané poznámkové bloky a ich históriu; odstránenie sa zosynchronizuje aj s ostatnými zariadeniami",
+ "archivedEncryptedNotebooks": "Archivácia a odstránenie dokončené. Po archivácii všetkých starých údajov na obnovu vypnite a znova zapnite šifrované poznámkové bloky a nastavte nové hlavné heslo",
+ "archiveKeyFile": "Záloha kľúča (voliteľné)",
+ "archiveHistoryOnly": "Iba história a snímky",
"openContextMenu": "Otvoriť kontextové menu",
"mobileSlashMenu": "Ponuka lomky v mobile",
"mobileSlashMenuTip": "Po zapnutí zadajte / v mobilnom editore na vyhľadanie a vloženie blokov obsahu",
@@ -2947,6 +2955,13 @@
"397": "Toto zariadenie nemôže vytvoriť synchronizovaný súbor. Premenujte ho v SiYuan na zariadení, kde je dostupný, a potom zopakujte synchronizáciu: %s",
"398": "Kontrolujú sa zdroje a staršie snímky...",
"399": "Sťahujú sa chýbajúce zdroje a obsah starších snímok...",
- "400": "Zdroje a staršie snímky sa nepodarilo skontrolovať alebo doplniť. Poskytovateľ synchronizácie sa nezmenil: %s"
+ "400": "Zdroje a staršie snímky sa nepodarilo skontrolovať alebo doplniť. Poskytovateľ synchronizácie sa nezmenil: %s",
+ "401": "Archív šifrovaných poznámkových blokov je neplatný, poškodený alebo má nepodporovanú verziu",
+ "402": "Údaje alebo podklady na obnovu sa zmenili. Pred odstránením vytvorte a uložte nový archív",
+ "403": "Zatvorte a zamknite poznámkové bloky a dokončite prebiehajúce obnovenia pred ďalším pokusom",
+ "404": "Obnovte v samostatnom pracovnom priestore bez kľúčov a šifrovaných údajov s vypnutou synchronizáciou",
+ "405": "Overenie zlyhalo. Skontrolujte staré hlavné heslo a zodpovedajúcu zálohu kľúča; archív zostal zachovaný",
+ "406": "Archivácia zlyhala. Pôvodné údaje zostali zachované; skontrolujte voľné miesto, oprávnenia a sťahovanie zdrojov",
+ "407": "Pred vypnutím šifrovania archivujte všetky údaje na obnovu šifrovaných poznámkových blokov"
}
}
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 49a9fb4ecc..d27d8cd2bc 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Архивирај и уклони",
+ "archiveEncryptedNotebooksTip": "Изаберите закључане шифроване бележнице и податке за опоравак; главна лозинка није потребна",
+ "restoreEncryptedNotebooks": "Врати шифровану архиву",
+ "restoreEncryptedNotebooksTip": "Користите засебан радни простор без кључева за шифровање и са искљученом синхронизацијом; унесите стару главну лозинку и по потреби изаберите пронађену резервну копију кључа",
+ "confirmArchiveSaved": "Сачувао сам архиву ван овог радног простора. Уклонити изабране бележнице и њихову историју; уклањање ће се синхронизовати и са другим уређајима",
+ "archivedEncryptedNotebooks": "Архивирање и уклањање су завршени. Након архивирања свих старих података за опоравак, искључите и поново укључите шифроване бележнице да поставите нову главну лозинку",
+ "archiveKeyFile": "Резервна копија кључа (опционо)",
+ "archiveHistoryOnly": "Само историја и снимци",
"openContextMenu": "Отвори контекстни мени",
"mobileSlashMenu": "Мени косе црте на мобилном уређају",
"mobileSlashMenuTip": "Када је укључен, унесите / у мобилном уређивачу да бисте претражили и уметнули блокове садржаја",
@@ -2947,6 +2955,13 @@
"397": "Овај уређај не може да направи синхронизовану датотеку. Преименујте је у SiYuan на уређају на ком је доступна, па поново синхронизујте: %s",
"398": "Провера ресурса и претходних снимака...",
"399": "Преузимање недостајућих ресурса и садржаја претходних снимака...",
- "400": "Није могуће проверити или допунити ресурсе и претходне снимке. Провајдер синхронизације није промењен: %s"
+ "400": "Није могуће проверити или допунити ресурсе и претходне снимке. Провајдер синхронизације није промењен: %s",
+ "401": "Архива шифрованих бележница је неисправна, оштећена или користи неподржану верзију",
+ "402": "Подаци или материјал за опоравак су промењени. Направите и сачувајте нову архиву пре уклањања",
+ "403": "Затворите и закључајте бележнице и довршите започете опоравке пре поновног покушаја",
+ "404": "Вратите у засебан радни простор без кључева и шифрованих података, са искљученом синхронизацијом",
+ "405": "Провера идентитета није успела. Проверите стару главну лозинку и одговарајућу копију кључа; архива је сачувана",
+ "406": "Архивирање није успело. Изворни подаци су сачувани; проверите слободан простор, дозволе и преузимање ресурса",
+ "407": "Пре искључивања шифровања архивирајте све податке за опоравак шифрованих бележница"
}
}
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index a92d3856ae..b536e0d8fe 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "เก็บถาวรและนำออก",
+ "archiveEncryptedNotebooksTip": "เลือกสมุดบันทึกที่เข้ารหัสและล็อกไว้พร้อมข้อมูลกู้คืน โดยไม่ต้องใช้รหัสผ่านหลัก",
+ "restoreEncryptedNotebooks": "กู้คืนไฟล์เก็บถาวรที่เข้ารหัส",
+ "restoreEncryptedNotebooksTip": "ใช้พื้นที่ทำงานแยกที่ยังไม่มีคีย์เข้ารหัสและปิดการซิงค์ ป้อนรหัสผ่านหลักเดิมและเลือกไฟล์สำรองคีย์ที่พบได้ตามต้องการ",
+ "confirmArchiveSaved": "ฉันบันทึกไฟล์เก็บถาวรไว้นอกพื้นที่ทำงานนี้แล้ว ยืนยันนำสมุดบันทึกที่เลือกและประวัติที่เกี่ยวข้องออก การนำออกจะซิงค์ไปยังอุปกรณ์อื่นด้วย",
+ "archivedEncryptedNotebooks": "เก็บถาวรและนำออกแล้ว หลังเก็บข้อมูลกู้คืนเดิมทั้งหมด ให้ปิดแล้วเปิดสมุดบันทึกที่เข้ารหัสอีกครั้งเพื่อตั้งรหัสผ่านหลักใหม่",
+ "archiveKeyFile": "ไฟล์สำรองคีย์ (ไม่บังคับ)",
+ "archiveHistoryOnly": "เฉพาะประวัติและสแนปช็อต",
"openContextMenu": "เปิดเมนูบริบท",
"mobileSlashMenu": "เมนูเครื่องหมายทับบนมือถือ",
"mobileSlashMenuTip": "เมื่อเปิดใช้งาน ให้พิมพ์ / ในตัวแก้ไขบนมือถือเพื่อค้นหาและแทรกบล็อกเนื้อหา",
@@ -2947,6 +2955,13 @@
"397": "อุปกรณ์นี้ไม่สามารถสร้างไฟล์ที่ซิงค์ได้ โปรดเปลี่ยนชื่อไฟล์ใน SiYuan บนอุปกรณ์ที่เข้าถึงไฟล์ได้ แล้วซิงค์อีกครั้ง: %s",
"398": "กำลังตรวจสอบทรัพยากรและสแนปช็อตย้อนหลัง...",
"399": "กำลังดาวน์โหลดทรัพยากรและเนื้อหาสแนปช็อตย้อนหลังที่ขาดหาย...",
- "400": "ไม่สามารถตรวจสอบหรือเติมทรัพยากรและสแนปช็อตย้อนหลังให้ครบได้ ผู้ให้บริการซิงค์ยังไม่เปลี่ยนแปลง: %s"
+ "400": "ไม่สามารถตรวจสอบหรือเติมทรัพยากรและสแนปช็อตย้อนหลังให้ครบได้ ผู้ให้บริการซิงค์ยังไม่เปลี่ยนแปลง: %s",
+ "401": "ไฟล์เก็บถาวรของสมุดบันทึกที่เข้ารหัสไม่ถูกต้อง เสียหาย หรือเป็นเวอร์ชันที่ไม่รองรับ",
+ "402": "ข้อมูลหรือข้อมูลกู้คืนเปลี่ยนแปลงแล้ว โปรดสร้างและบันทึกไฟล์เก็บถาวรใหม่ก่อนนำออก",
+ "403": "โปรดปิดและล็อกสมุดบันทึก และดำเนินการกู้คืนที่ค้างอยู่ให้เสร็จก่อนลองอีกครั้ง",
+ "404": "โปรดกู้คืนในพื้นที่ทำงานแยกที่ไม่มีคีย์หรือข้อมูลเข้ารหัสและปิดการซิงค์",
+ "405": "การยืนยันตัวตนล้มเหลว โปรดตรวจสอบรหัสผ่านหลักเดิมและไฟล์สำรองคีย์ที่ตรงกัน ไฟล์เก็บถาวรยังคงอยู่",
+ "406": "การเก็บถาวรล้มเหลว ข้อมูลต้นฉบับยังคงอยู่ โปรดตรวจสอบพื้นที่ว่าง สิทธิ์ และการดาวน์โหลดทรัพยากร",
+ "407": "โปรดเก็บข้อมูลกู้คืนของสมุดบันทึกที่เข้ารหัสทั้งหมดก่อนปิดการเข้ารหัส"
}
}
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 878faf7210..996198a038 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Arşivle ve kaldır",
+ "archiveEncryptedNotebooksTip": "Kilitli şifreli not defterlerini ve kurtarma verilerini seçin; ana parola gerekmez",
+ "restoreEncryptedNotebooks": "Şifreli arşivi geri yükle",
+ "restoreEncryptedNotebooksTip": "Şifreleme anahtarı olmayan ve eşitlemesi kapalı ayrı bir çalışma alanı kullanın; eski ana parolayı girin ve gerekirse bulunan anahtar yedeğini seçin",
+ "confirmArchiveSaved": "Arşivi bu çalışma alanının dışına kaydettim. Seçili not defterlerini ve ilgili geçmişi kaldır; bu işlem eşitleme yoluyla diğer cihazlara da uygulanır",
+ "archivedEncryptedNotebooks": "Arşivlendi ve kaldırıldı. Tüm eski kurtarma verilerini arşivledikten sonra yeni ana parola belirlemek için şifreli not defterlerini kapatıp yeniden açın",
+ "archiveKeyFile": "Anahtar yedeği (isteğe bağlı)",
+ "archiveHistoryOnly": "Yalnızca geçmiş ve anlık görüntüler",
"openContextMenu": "Bağlam menüsünü aç",
"mobileSlashMenu": "Mobil eğik çizgi menüsü",
"mobileSlashMenuTip": "Etkinleştirildiğinde içerik bloklarını aramak ve eklemek için mobil düzenleyicide / yazın",
@@ -2947,6 +2955,13 @@
"397": "Bu cihaz eşitlenen dosyayı oluşturamıyor. Dosyaya erişilebilen bir cihazda SiYuan üzerinden dosyayı yeniden adlandırıp tekrar eşitleyin: %s",
"398": "Kaynaklar ve geçmiş anlık görüntüler kontrol ediliyor...",
"399": "Eksik kaynaklar ve geçmiş anlık görüntü içerikleri indiriliyor...",
- "400": "Kaynaklar ve geçmiş anlık görüntüler kontrol edilemedi veya tamamlanamadı. Senkronizasyon sağlayıcısı değiştirilmedi: %s"
+ "400": "Kaynaklar ve geçmiş anlık görüntüler kontrol edilemedi veya tamamlanamadı. Senkronizasyon sağlayıcısı değiştirilmedi: %s",
+ "401": "Şifreli not defteri arşivi geçersiz, bozuk veya desteklenmeyen bir sürümde",
+ "402": "Veriler veya kurtarma malzemeleri değişti. Kaldırmadan önce yeni bir arşiv oluşturup kaydedin",
+ "403": "Yeniden denemeden önce not defterlerini kapatıp kilitleyin ve bekleyen kurtarma işlemlerini tamamlayın",
+ "404": "Anahtar veya şifreli veri olmayan, eşitlemesi kapalı ayrı bir çalışma alanına geri yükleyin",
+ "405": "Kimlik doğrulama başarısız. Eski ana parolayı ve eşleşen anahtar yedeğini kontrol edin; arşiv korundu",
+ "406": "Arşivleme başarısız. Özgün veriler korundu; boş alanı, izinleri ve kaynak indirmelerini kontrol edin",
+ "407": "Şifrelemeyi kapatmadan önce tüm şifreli not defteri kurtarma verilerini arşivleyin"
}
}
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 6b8588bd66..0cdd5dc4a2 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "Архівувати та вилучити",
+ "archiveEncryptedNotebooksTip": "Виберіть заблоковані зашифровані блокноти й дані відновлення; головний пароль не потрібен",
+ "restoreEncryptedNotebooks": "Відновити зашифрований архів",
+ "restoreEncryptedNotebooksTip": "Використовуйте окремий робочий простір без ключів шифрування з вимкненою синхронізацією; введіть старий головний пароль і за потреби виберіть знайдену копію ключа",
+ "confirmArchiveSaved": "Я зберіг архів поза цим робочим простором. Вилучити вибрані блокноти та їхню історію; вилучення також синхронізується з іншими пристроями",
+ "archivedEncryptedNotebooks": "Архівування та вилучення завершено. Після архівування всіх старих даних відновлення вимкніть і знову ввімкніть зашифровані блокноти, щоб установити новий головний пароль",
+ "archiveKeyFile": "Резервна копія ключа (необов’язково)",
+ "archiveHistoryOnly": "Лише історія та знімки",
"openContextMenu": "Відкрити контекстне меню",
"mobileSlashMenu": "Меню косої риски на мобільному пристрої",
"mobileSlashMenuTip": "Після ввімкнення введіть / у мобільному редакторі, щоб знайти та вставити блоки вмісту",
@@ -2947,6 +2955,13 @@
"397": "На цьому пристрої неможливо створити синхронізований файл. Перейменуйте його в SiYuan на пристрої, де він доступний, а потім повторіть синхронізацію: %s",
"398": "Перевірка ресурсів і попередніх знімків...",
"399": "Завантаження відсутніх ресурсів і вмісту попередніх знімків...",
- "400": "Не вдалося перевірити або доповнити ресурси та попередні знімки. Постачальника синхронізації не змінено: %s"
+ "400": "Не вдалося перевірити або доповнити ресурси та попередні знімки. Постачальника синхронізації не змінено: %s",
+ "401": "Архів зашифрованих блокнотів недійсний, пошкоджений або має непідтримувану версію",
+ "402": "Дані або матеріали відновлення змінилися. Створіть і збережіть новий архів перед вилученням",
+ "403": "Закрийте й заблокуйте блокноти та завершіть незавершені операції відновлення перед повторною спробою",
+ "404": "Відновлюйте в окремому робочому просторі без ключів і зашифрованих даних із вимкненою синхронізацією",
+ "405": "Помилка автентифікації. Перевірте старий головний пароль і відповідну копію ключа; архів збережено",
+ "406": "Не вдалося виконати архівування. Початкові дані збережено; перевірте вільне місце, дозволи та завантаження ресурсів",
+ "407": "Перед вимкненням шифрування архівуйте всі дані відновлення зашифрованих блокнотів"
}
}
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index a648161d6a..7d7f506567 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "打包移出",
+ "archiveEncryptedNotebooksTip": "选择已锁定的加密笔记本及其恢复数据,无需输入主密码",
+ "restoreEncryptedNotebooks": "恢复加密归档",
+ "restoreEncryptedNotebooksTip": "请在未配置加密密钥且已关闭同步的独立工作区恢复,输入旧主密码,可另选找回的密钥备份",
+ "confirmArchiveSaved": "我已将归档保存到本工作区以外的位置,确认移出所选笔记本及相关历史;移出操作也会通过同步影响其他设备",
+ "archivedEncryptedNotebooks": "已打包移出。全部旧恢复依赖归档后,可关闭再重新启用加密笔记本,设置新主密码",
+ "archiveKeyFile": "密钥备份(可选)",
+ "archiveHistoryOnly": "仅历史和快照",
"openContextMenu": "打开上下文菜单",
"mobileSlashMenu": "移动端斜杠菜单",
"mobileSlashMenuTip": "开启后,在移动端编辑器输入 / 可搜索并插入内容块",
@@ -2947,6 +2955,13 @@
"397": "当前设备无法创建同步文件,请在能够访问该文件的设备上通过思源重命名后重新同步:%s",
"398": "正在检查资源和历史快照的完整性...",
"399": "正在下载缺失资源和历史快照内容...",
- "400": "无法检查或补齐资源和历史快照,同步提供商未更改:%s"
+ "400": "无法检查或补齐资源和历史快照,同步提供商未更改:%s",
+ "401": "加密笔记本归档无效、已损坏或版本不受支持",
+ "402": "数据或恢复材料已变化,请重新生成并保存归档后再移出",
+ "403": "请先关闭并锁定笔记本,完成尚未结束的恢复操作后重试",
+ "404": "请在未配置加密密钥、没有加密数据且已关闭同步的独立工作区恢复",
+ "405": "认证失败,请检查旧主密码和匹配的密钥备份,原归档已保留",
+ "406": "归档操作失败,原始数据已保留,请检查可用空间、权限和资源下载情况",
+ "407": "请先归档全部加密笔记本恢复依赖,再关闭加密功能"
}
}
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 44965ebff4..99748dd1dd 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,12 @@
{
+ "archiveEncryptedNotebooks": "封存並移出",
+ "archiveEncryptedNotebooksTip": "選擇已鎖定的加密筆記本及其復原資料,無需輸入主密碼",
+ "restoreEncryptedNotebooks": "復原加密封存檔",
+ "restoreEncryptedNotebooksTip": "請在尚未設定加密金鑰且已關閉同步的獨立工作空間復原,輸入舊主密碼,可另選找回的金鑰備份",
+ "confirmArchiveSaved": "我已將封存檔儲存到此工作空間以外的位置,確認移出所選筆記本及相關歷史;移出操作也會透過同步影響其他裝置",
+ "archivedEncryptedNotebooks": "已封存並移出。全部舊復原相依資料封存後,可關閉再重新啟用加密筆記本,設定新主密碼",
+ "archiveKeyFile": "金鑰備份(選填)",
+ "archiveHistoryOnly": "僅歷史和快照",
"openContextMenu": "開啟快顯功能表",
"mobileSlashMenu": "行動端斜線選單",
"mobileSlashMenuTip": "啟用後,在行動端編輯器輸入 / 可搜尋並插入內容區塊",
@@ -2947,6 +2955,13 @@
"397": "目前裝置無法建立同步檔案,請在能夠存取該檔案的裝置上透過思源重新命名後再次同步:%s",
"398": "正在檢查資源和歷史快照的完整性...",
"399": "正在下載缺失資源和歷史快照內容...",
- "400": "無法檢查或補齊資源和歷史快照,同步服務提供者未變更:%s"
+ "400": "無法檢查或補齊資源和歷史快照,同步服務提供者未變更:%s",
+ "401": "加密筆記本封存檔無效、已損毀或版本不受支援",
+ "402": "資料或復原材料已變更,請重新產生並儲存封存檔後再移出",
+ "403": "請先關閉並鎖定筆記本,完成尚未結束的復原操作後重試",
+ "404": "請在尚未設定加密金鑰、沒有加密資料且已關閉同步的獨立工作空間復原",
+ "405": "驗證失敗,請檢查舊主密碼及相符的金鑰備份,原封存檔已保留",
+ "406": "封存操作失敗,原始資料已保留,請檢查可用空間、權限及資源下載情況",
+ "407": "請先封存全部加密筆記本復原相依資料,再關閉加密功能"
}
}
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.sy
index 135f04cd74..5a36f2da05 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": "20260908162209"
+ "updated": "20260925180231"
},
"Children": [
{
@@ -1203,6 +1203,163 @@
}
]
},
+ {
+ "ID": "20260925180231-tsba9iv",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20260925180231-tsba9iv",
+ "updated": "20260925180231"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Archive and recover locked notebooks"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-e14557m",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-e14557m",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Open "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Settings"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Authentication"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Encrypted notebooks"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Archive and remove"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " and select the locked notebooks to archive. No master password is required. The archive includes the original ciphertext, related history, local repository snapshots, and available key recovery material."
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-d8i6s9h",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-d8i6s9h",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Save the archive outside the workspace, then explicitly confirm that it has been saved before removing the selected notebooks. Canceling the save does not remove data. Removal propagates through normal synchronization; repository snapshots are not automatically deleted."
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-0c0gpz5",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-0c0gpz5",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Removing three of five locked notebooks leaves the other two and the old key configuration in place. After all old notebook and recovery dependencies are archived, turn encrypted notebooks off and on again to set a new master password. The application also retains recovery copies; keep your independently saved archive."
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-s02q6ja",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-s02q6ja",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "After recovering the matching key and password, create a separate workspace without encryption keys, turn off synchronization, and open "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Settings"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Authentication"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Encrypted notebooks"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Restore encrypted archive"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ". Select the archive and enter the old master password. If the archive lacks a usable key backup, also select the matching key backup you recovered. A workspace that already has encryption keys cannot import this archive."
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-cj1nt43",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-cj1nt43",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Restoration verifies the key and ciphertext before writing data and keeps the notebooks locked. Related history is restored; archived repository snapshots appear as notebook deletion history. Damaged archives, incorrect passwords, and unsupported versions do not overwrite existing data. Archiving cannot replace a lost password or missing recovery material."
+ }
+ ]
+ },
{
"ID": "20260907120000-en00050",
"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.sy
index 70926521f6..a180824385 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": "20260908162209"
+ "updated": "20260925180231"
},
"Children": [
{
@@ -1203,6 +1203,163 @@
}
]
},
+ {
+ "ID": "20260925180231-wqj5mq8",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20260925180231-wqj5mq8",
+ "updated": "20260925180231"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "无法解锁的笔记本的归档与恢复"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-cw38cp8",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-cw38cp8",
+ "updated": "20260925180231"
+ },
+ "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": "20260925180231-ipq0n2f",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-ipq0n2f",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "将归档保存到工作区以外的位置,明确确认已保存后,再移出所选笔记本。取消保存不会移除数据。移出会通过正常同步影响其他设备,不会自动删除数据仓库快照。"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-3htujkf",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-3htujkf",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "5 个无法解锁的笔记本只移出 3 个时,另外 2 个和旧密钥配置仍保留。全部旧笔记本及恢复依赖归档后,可关闭再重新启用加密笔记本,设置新主密码。软件也会保留恢复副本,请同时妥善保存自行导出的归档。"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-jsu1bwe",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-jsu1bwe",
+ "updated": "20260925180231"
+ },
+ "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": "20260925180231-7whxd48",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-7whxd48",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "恢复会先验证密钥和密文,全部通过后再写入数据,笔记本仍保持锁定。相关历史一并恢复,归档中的仓库快照作为笔记本删除历史提供恢复。损坏的归档、错误密码和不支持的版本不会覆盖已有数据。归档不能替代丢失的密码或恢复材料。"
+ }
+ ]
+ },
{
"ID": "20260907120000-cn00050",
"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.sy
index ceb40a1265..edddfe7ff7 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": "20260908162209"
+ "updated": "20260925180231"
},
"Children": [
{
@@ -1203,6 +1203,163 @@
}
]
},
+ {
+ "ID": "20260925180231-gsybyqh",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20260925180231-gsybyqh",
+ "updated": "20260925180231"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "無法解鎖的筆記本的封存與復原"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-72oyis6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-72oyis6",
+ "updated": "20260925180231"
+ },
+ "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": "20260925180231-3pdlb4x",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-3pdlb4x",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "將封存檔儲存到工作空間以外的位置,明確確認已儲存後,再移出所選筆記本。取消儲存不會移除資料。移出會透過正常同步影響其他裝置,不會自動刪除資料倉庫快照。"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-2z2rtvy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-2z2rtvy",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "5 個無法解鎖的筆記本只移出 3 個時,另外 2 個和舊金鑰設定仍保留。全部舊筆記本及復原相依資料封存後,可關閉再重新啟用加密筆記本,設定新主密碼。軟體也會保留復原副本,請同時妥善保存自行匯出的封存檔。"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-s6h50ap",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-s6h50ap",
+ "updated": "20260925180231"
+ },
+ "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": "20260925180231-i3fp12z",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-i3fp12z",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "復原會先驗證金鑰及密文,全部通過後再寫入資料,筆記本仍保持鎖定。相關歷史一併復原,封存檔中的倉庫快照會作為筆記本刪除歷史提供復原。損毀的封存檔、錯誤密碼及不支援的版本不會覆寫既有資料。封存不能取代遺失的密碼或復原材料。"
+ }
+ ]
+ },
{
"ID": "20260907120000-tw00050",
"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.sy
index e913e8db88..f3414f063b 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": "20260908162209"
+ "updated": "20260925180231"
},
"Children": [
{
@@ -1203,6 +1203,159 @@
}
]
},
+ {
+ "ID": "20260925180231-8huz7ss",
+ "Type": "NodeHeading",
+ "Properties": {
+ "id": "20260925180231-8huz7ss",
+ "updated": "20260925180231"
+ },
+ "HeadingLevel": 2,
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "ロック解除できないノートブックのアーカイブと復元"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-j889vl7",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-j889vl7",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "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": "20260925180231-88n6f8g",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-88n6f8g",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "アーカイブをワークスペースの外に保存し、保存済みであることを明示的に確認してから、選択したノートブックを移出します。保存を取り消してもデータは削除されません。移出は通常の同期で他の端末にも反映されますが、リポジトリのスナップショットは自動削除されません。"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-e9r5qdu",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-e9r5qdu",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "ロック解除できない5冊のうち3冊を移出した場合、残りの2冊と以前の鍵の設定は保持されます。以前のノートブックと復元に必要なデータをすべてアーカイブした後、暗号化ノートブックを無効化して再度有効化すると、新しいマスターパスワードを設定できます。アプリにも復元用コピーが保持されますが、別途保存したアーカイブを大切に保管してください。"
+ }
+ ]
+ },
+ {
+ "ID": "20260925180231-93bxvo7",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-93bxvo7",
+ "updated": "20260925180231"
+ },
+ "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": "20260925180231-78557m3",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260925180231-78557m3",
+ "updated": "20260925180231"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "復元では鍵と暗号文を検証し、すべて成功した後にデータを書き込みます。ノートブックはロックされたままです。関連履歴も復元され、アーカイブされたリポジトリのスナップショットはノートブックの削除履歴として復元できます。破損したアーカイブ、誤ったパスワード、未対応のバージョンでは既存データを上書きしません。アーカイブは失われたパスワードや復元情報の代わりにはなりません。"
+ }
+ ]
+ },
{
"ID": "20260907120000-ja00050",
"Type": "NodeHeading",
diff --git a/app/src/config/notebookArchive.test.ts b/app/src/config/notebookArchive.test.ts
new file mode 100644
index 0000000000..d46a72ca58
--- /dev/null
+++ b/app/src/config/notebookArchive.test.ts
@@ -0,0 +1,86 @@
+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/notebookArchive.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+class Control {
+ checked = false;
+ disabled = false;
+ value = "20260925120001-archive";
+ listeners = new Map<string, () => Promise<void> | void>();
+ classList = {remove: () => {}};
+ addEventListener(event: string, handler: () => Promise<void> | void) {
+ this.listeners.set(event, handler);
+ }
+ async dispatch(event: string) {
+ await this.listeners.get(event)?.();
+ }
+}
+
+test("archive removal requires a saved copy and explicit confirmation after download", async () => {
+ const boxes = [new Control()];
+ const controls = new Map<string, Control>();
+ for (const name of ["export", "commit", "saved", "cancel"]) {
+ controls.set(`[data-type="${name}"]`, new Control());
+ }
+ const saved = new Control();
+ controls.set('[data-type="saved"] input', saved);
+ let destroyed = 0;
+ const requests: Array<{url: string, data: {id?: string, saved?: boolean}}> = [];
+ let saveStatus = "canceled";
+ const exports = {} as {openNotebookArchiveDialog: (refresh: () => void) => Promise<void>};
+ const dependencies = {
+ Dialog: class {
+ element = {
+ isConnected: true,
+ querySelector: (selector: string) => controls.get(selector),
+ querySelectorAll: () => boxes,
+ };
+ destroy() {
+ this.element.isConnected = false;
+ destroyed++;
+ }
+ },
+ fetchSyncPost: async (url: string, data: {id?: string, saved?: boolean}) => {
+ requests.push({url, data});
+ if (url.endsWith("getNotebookArchiveCandidates")) {
+ return {code: 0, data: {notebooks: [{id: boxes[0].value, current: true}]}};
+ }
+ if (url.endsWith("prepareNotebookArchive")) {
+ return {code: 0, data: {id: "archive-id", file: "/export/archive.zip"}};
+ }
+ return {code: 0};
+ },
+ saveExportFile: async () => ({status: saveStatus}),
+ escapeHtml: (value: string) => value,
+ isMobile: () => true,
+ showMessage: () => {},
+ };
+ runInNewContext(compiled, {exports, require: () => dependencies, window: {siyuan: {languages: {}}}});
+ let refreshed = 0;
+ await exports.openNotebookArchiveDialog(() => refreshed++);
+ boxes[0].checked = true;
+ await boxes[0].dispatch("change");
+ await controls.get('[data-type="export"]').dispatch("click");
+ assert.equal(controls.get('[data-type="commit"]').disabled, true);
+ assert.equal(requests.filter((r) => r.url.endsWith("commitNotebookArchive")).length, 0);
+ saveStatus = "success";
+ await controls.get('[data-type="export"]').dispatch("click");
+ await controls.get('[data-type="commit"]').dispatch("click");
+ assert.equal(requests.filter((r) => r.url.endsWith("commitNotebookArchive")).length, 0);
+ saved.checked = true;
+ await saved.dispatch("change");
+ await controls.get('[data-type="commit"]').dispatch("click");
+ const commits = requests.filter((r) => r.url.endsWith("commitNotebookArchive"));
+ assert.equal(commits.length, 1);
+ assert.equal(commits[0].data.id, "archive-id");
+ assert.equal(commits[0].data.saved, true);
+ assert.equal(refreshed, 1);
+ assert.equal(destroyed, 1);
+ assert.equal(requests.filter((r) => r.url.endsWith("prepareNotebookArchive")).length, 1);
+});
diff --git a/app/src/config/notebookArchive.ts b/app/src/config/notebookArchive.ts
new file mode 100644
index 0000000000..fb4caaffd3
--- /dev/null
+++ b/app/src/config/notebookArchive.ts
@@ -0,0 +1,152 @@
+import {Dialog} from "../dialog";
+import {showMessage} from "../dialog/message";
+import {fetchSyncPost} from "../util/fetch";
+import {ContractFormData} from "../util/contractFormData";
+import {saveExportFile} from "../protyle/util/compatibility";
+import {escapeHtml} from "../util/escape";
+import {isMobile} from "../util/functions";
+
+export const openNotebookArchiveDialog = async (refresh: () => void) => {
+ const response = await fetchSyncPost("/api/notebook/getNotebookArchiveCandidates", {});
+ if (response.code !== 0) {
+ return;
+ }
+ const lang = window.siyuan.languages;
+ const dialog = new Dialog({
+ title: lang.archiveEncryptedNotebooks,
+ width: isMobile() ? "92vw" : "560px",
+ content: `<div class="b3-dialog__content">
+ <div class="ft__secondary">${lang.archiveEncryptedNotebooksTip}</div>
+ <div class="fn__hr"></div>
+ <div data-type="notebooks">${response.data.notebooks.map((item) => `<label class="b3-label fn__flex">
+ <input class="b3-switch" type="checkbox" value="${escapeHtml(item.id)}">
+ <span class="fn__space"></span><span class="ft__breakword">${escapeHtml(item.id)}${item.current ? "" : ` (${lang.archiveHistoryOnly})`}</span>
+ </label>`).join("")}</div>
+ <label class="b3-label fn__flex fn__none" data-type="saved">
+ <input class="b3-switch" type="checkbox"><span class="fn__space"></span>
+ <span class="ft__breakword">${lang.confirmArchiveSaved}</span>
+ </label>
+</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--text" data-type="export" disabled>${lang.export}</button>
+ <div class="fn__space"></div>
+ <button class="b3-button b3-button--remove fn__none" data-type="commit" disabled>${lang.archiveEncryptedNotebooks}</button>
+</div>`,
+ });
+ const boxes = dialog.element.querySelectorAll<HTMLInputElement>('[data-type="notebooks"] input');
+ const exportButton = dialog.element.querySelector<HTMLButtonElement>('[data-type="export"]');
+ const commitButton = dialog.element.querySelector<HTMLButtonElement>('[data-type="commit"]');
+ const saved = dialog.element.querySelector<HTMLInputElement>('[data-type="saved"] input');
+ let archive: {id: string, file: string} | undefined;
+ let busy = false;
+ const update = () => {
+ exportButton.disabled = busy || !Array.from(boxes).some((box) => box.checked);
+ commitButton.disabled = busy || !archive || !saved.checked;
+ };
+ boxes.forEach((box) => box.addEventListener("change", update));
+ saved.addEventListener("change", update);
+ dialog.element.querySelector('[data-type="cancel"]').addEventListener("click", () => dialog.destroy());
+ exportButton.addEventListener("click", async () => {
+ if (busy) {
+ return;
+ }
+ busy = true;
+ update();
+ try {
+ if (!archive) {
+ const prepared = await fetchSyncPost("/api/notebook/prepareNotebookArchive", {
+ notebooks: Array.from(boxes).filter((box) => box.checked).map((box) => box.value),
+ });
+ if (prepared.code !== 0) {
+ return;
+ }
+ archive = prepared.data;
+ boxes.forEach((box) => box.disabled = true);
+ }
+ const result = await saveExportFile(archive.file);
+ if (result.status !== "success" || !dialog.element.isConnected) {
+ return;
+ }
+ // 下载回调不代替用户确认,浏览器及旧版移动端可能仅报告已发起下载。
+ dialog.element.querySelector('[data-type="saved"]').classList.remove("fn__none");
+ commitButton.classList.remove("fn__none");
+ } finally {
+ busy = false;
+ update();
+ }
+ });
+ commitButton.addEventListener("click", async () => {
+ if (busy || !archive || !saved.checked) {
+ return;
+ }
+ busy = true;
+ update();
+ try {
+ const result = await fetchSyncPost("/api/notebook/commitNotebookArchive", {id: archive.id, saved: true});
+ if (result.code !== 0) {
+ return;
+ }
+ dialog.destroy();
+ showMessage(lang.archivedEncryptedNotebooks, 10000);
+ refresh();
+ } finally {
+ busy = false;
+ update();
+ }
+ });
+};
+
+export const openNotebookArchiveImportDialog = (refresh: () => void) => {
+ const lang = window.siyuan.languages;
+ const dialog = new Dialog({
+ title: lang.restoreEncryptedNotebooks,
+ width: isMobile() ? "92vw" : "560px",
+ content: `<div class="b3-dialog__content">
+ <div class="ft__secondary">${lang.restoreEncryptedNotebooksTip}</div>
+ <label class="b3-label fn__block">${lang.restoreEncryptedNotebooks}
+ <div class="fn__hr"></div><input class="b3-text-field fn__block" data-type="archive" type="file" accept=".zip,application/zip" required>
+ </label>
+ <label class="b3-label fn__block">${lang.archiveKeyFile}
+ <div class="fn__hr"></div><input class="b3-text-field fn__block" data-type="key" type="file" accept=".json,application/json">
+ </label>
+ <label class="b3-label fn__block">${lang.masterPassword}
+ <div class="fn__hr"></div><input class="b3-text-field fn__block" data-type="password" type="password" autocomplete="off" required>
+ </label>
+</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--text" data-type="import">${lang.import}</button>
+</div>`,
+ });
+ dialog.element.querySelector('[data-type="cancel"]').addEventListener("click", () => dialog.destroy());
+ const button = dialog.element.querySelector<HTMLButtonElement>('[data-type="import"]');
+ button.addEventListener("click", async () => {
+ if (button.disabled) {
+ return;
+ }
+ const file = dialog.element.querySelector<HTMLInputElement>('[data-type="archive"]').files?.[0];
+ const key = dialog.element.querySelector<HTMLInputElement>('[data-type="key"]').files?.[0];
+ const password = dialog.element.querySelector<HTMLInputElement>('[data-type="password"]').value.trim();
+ if (!file || !password) {
+ dialog.element.querySelector<HTMLInputElement>(`[data-type="${file ? "password" : "archive"}"]`).reportValidity();
+ return;
+ }
+ button.disabled = true;
+ try {
+ const response = await fetchSyncPost("/api/notebook/importNotebookArchive", new ContractFormData({file, key, password}), undefined, false);
+ if (response.code !== 0) {
+ showMessage(response.msg, 7000, "error");
+ return;
+ }
+ dialog.destroy();
+ showMessage(lang.imported);
+ refresh();
+ // 导入保留锁定状态,刷新导航即可显示新恢复的笔记本。
+ window.location.reload();
+ } finally {
+ button.disabled = false;
+ }
+ });
+};
diff --git a/app/src/config/tabs/accessTab.test.ts b/app/src/config/tabs/accessTab.test.ts
index 52f78873d0..606a62d09e 100644
--- a/app/src/config/tabs/accessTab.test.ts
+++ b/app/src/config/tabs/accessTab.test.ts
@@ -34,6 +34,7 @@ test("encrypted notebook system lock is offered only for supported local desktop
});
exports.registerEncryptedNotebookGroup({group: () => ({
slot: () => {},
+ button: () => {},
number: () => {},
switch: (id: string, spec: {save: (value: unknown) => void}) => switches.push({id, save: spec.save}),
})});
@@ -102,3 +103,39 @@ test("crypto backup import trims passwords and rejects whitespace-only input", a
}
assert.equal(destroyed, 3);
});
+
+test("recovery-required key configuration can be disabled and cannot import another archive", () => {
+ const compiled = transpileModule(readFileSync("src/config/tabs/accessTab.ts", "utf8") +
+ "\nexport {refreshEncryptedNotebookStatus};", {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const controls = new Map<string, {checked: boolean, disabled: boolean, classList: {toggle: () => void, remove: () => void}}>();
+ const root = {
+ querySelector: (selector: string) => {
+ if (!controls.has(selector)) {
+ controls.set(selector, {checked: false, disabled: false, classList: {toggle: () => {}, remove: () => {}}});
+ }
+ return controls.get(selector);
+ },
+ };
+ let state = "RecoveryRequired";
+ const dependencies = {
+ getHostCapabilities: () => ({importExport: true}),
+ fetchPost: (url: string, data: object, callback: (response: unknown) => void) => {
+ assert.equal(url, "/api/notebook/getEncryptedNotebookStatus");
+ assert.equal(Object.keys(data).length, 0);
+ callback({data: {state, migrationPending: false}});
+ },
+ };
+ const config = {notebookCrypto: {enabled: false}};
+ const exports = {} as {refreshEncryptedNotebookStatus: (element: typeof root) => void};
+ runInNewContext(compiled, {exports, require: () => dependencies, window: {siyuan: {config}}});
+ exports.refreshEncryptedNotebookStatus(root);
+ assert.equal(root.querySelector("#encryptedNotebookSwitch").checked, true);
+ assert.equal(root.querySelector("#restoreEncryptedNotebooks").disabled, true);
+ assert.equal(config.notebookCrypto.enabled, false);
+ state = "Disabled";
+ exports.refreshEncryptedNotebookStatus(root);
+ assert.equal(root.querySelector("#encryptedNotebookSwitch").checked, false);
+ assert.equal(root.querySelector("#restoreEncryptedNotebooks").disabled, false);
+});
diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.ts
index d5594f0672..9bec3e87ad 100644
--- a/app/src/config/tabs/accessTab.ts
+++ b/app/src/config/tabs/accessTab.ts
@@ -23,6 +23,7 @@ import {
import {sendAppSetting} from "./appRuntime";
import zxcvbn = require("zxcvbn");
import {canOpenExternalURL, getHostCapabilities} from "../../util/hostCapabilities";
+import {openNotebookArchiveDialog, openNotebookArchiveImportDialog} from "../notebookArchive";
const getPasswordStrength = (password: string) => {
const score = zxcvbn(password).score;
@@ -732,6 +733,28 @@ const registerEncryptedNotebookGroup = (tab: SettingTabBuilder) => {
</div>`,
afterMount: mountEncryptedNotebook,
});
+ if (!disableImportExport) {
+ group.button({
+ id: "archiveEncryptedNotebooks",
+ title: window.siyuan.languages.archiveEncryptedNotebooks,
+ desc: window.siyuan.languages.archiveEncryptedNotebooksTip,
+ label: window.siyuan.languages.archiveEncryptedNotebooks,
+ icon: "iconUpload",
+ afterMount: (root) => root.querySelector("#archiveEncryptedNotebooks")?.addEventListener("click", () => {
+ openNotebookArchiveDialog(() => refreshEncryptedNotebookStatus(root));
+ }),
+ });
+ group.button({
+ id: "restoreEncryptedNotebooks",
+ title: window.siyuan.languages.restoreEncryptedNotebooks,
+ desc: window.siyuan.languages.restoreEncryptedNotebooksTip,
+ label: window.siyuan.languages.import,
+ icon: "iconDownload",
+ afterMount: (root) => root.querySelector("#restoreEncryptedNotebooks")?.addEventListener("click", () => {
+ openNotebookArchiveImportDialog(() => {});
+ }),
+ });
+ }
group.number("notebookCrypto.autoLockMinutes", {
title: window.siyuan.languages.encryptedNotebookAutoLock,
desc: window.siyuan.languages.encryptedNotebookAutoLockDesc,
@@ -758,24 +781,31 @@ const registerEncryptedNotebookGroup = (tab: SettingTabBuilder) => {
}
};
+const refreshEncryptedNotebookStatus = (root: HTMLElement) => {
+ fetchPost("/api/notebook/getEncryptedNotebookStatus", {}, (response) => {
+ const enabled = response.data.state === "Enabled";
+ const switchElement = root.querySelector<HTMLInputElement>("#encryptedNotebookSwitch");
+ if (!switchElement) {
+ return;
+ }
+ // 待恢复配置也允许关闭;内核仍会阻止清除尚有笔记本或历史依赖的密钥。
+ switchElement.checked = response.data.state !== "Disabled";
+ window.siyuan.config.notebookCrypto.enabled = enabled;
+ root.querySelector("#encryptedNotebookEnabledActions").classList.toggle("fn__none", !enabled);
+ root.querySelector("#importCryptoBackupBtn").classList.toggle("fn__none", enabled || !getHostCapabilities().importExport);
+ root.querySelector("#encryptedNotebookActions").classList.remove("fn__none");
+ root.querySelector("#encryptedNotebookMigrationAlert").classList.toggle("fn__none", !response.data.migrationPending);
+ const restoreButton = root.querySelector<HTMLButtonElement>("#restoreEncryptedNotebooks");
+ if (restoreButton) {
+ restoreButton.disabled = response.data.state !== "Disabled";
+ }
+ });
+};
+
const mountEncryptedNotebook = (root: HTMLElement) => {
const switchElement = root.querySelector("#encryptedNotebookSwitch") as HTMLInputElement;
const actionsElement = root.querySelector("#encryptedNotebookActions");
- const enabledActionsElement = root.querySelector("#encryptedNotebookEnabledActions");
- const importCryptoBackupBtnElement = root.querySelector("#importCryptoBackupBtn");
- const migrationAlertElement = root.querySelector("#encryptedNotebookMigrationAlert");
- const refresh = () => {
- fetchPost("/api/notebook/getEncryptedNotebookStatus", {}, (response) => {
- const enabled = response.data.state === "Enabled";
- switchElement.checked = enabled;
- window.siyuan.config.notebookCrypto.enabled = enabled;
- // 修改主密码和导出密钥仅在配置完整时可见;Disabled 或 RecoveryRequired 状态提供导入恢复入口。
- enabledActionsElement.classList.toggle("fn__none", !enabled);
- importCryptoBackupBtnElement.classList.toggle("fn__none", enabled || !getHostCapabilities().importExport);
- actionsElement.classList.remove("fn__none");
- migrationAlertElement.classList.toggle("fn__none", !response.data.migrationPending);
- });
- };
+ const refresh = () => refreshEncryptedNotebookStatus(root);
refresh();
actionsElement.querySelector("#changeMasterPasswordBtn")?.addEventListener("click", () => {
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index df59e44c1e..6c30edfe15 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -778,6 +778,8 @@ export type CloudSyncDir = { "cloudName": string; "hSize": string; "saveDir": st
export type CloudSyncDirsData = { "checkedSyncDir": string; "hSize": string; "syncDirs": Array<CloudSyncDir | null> | null; };
+export type CommitNotebookArchiveRequestInput = { "id": string; "saved": boolean; };
+
export type ContentWordCountRequestInput = { "content": string; "reqId"?: JSONValue | null; };
export type ContinueImportSYRequestInput = { "notebook": string; "token": string; };
@@ -1208,6 +1210,8 @@ export type ImportDocumentData = { "type": "document"; };
export type ImportMarkdownRequestInput = { "localPath": string; "notebook": string; "skipRoot"?: boolean | null; "toPath": string; };
+export type ImportNotebookArchiveRequestInput = { "file": Blob; "key"?: Blob; "password": string; };
+
export type ImportNotebookCryptoBackupRequestInput = { "file": Blob; "password"?: string; };
export type ImportRepoKeyRequestInput = { "key": string; };
@@ -1376,6 +1380,12 @@ export type NetworkServeTLSRequestInput = { "networkServeTLS": boolean; };
export type Notebook = { "closed": boolean; "dueFlashcardCount": number; "encrypted": boolean; "flashcardCount": number; "icon": string; "id": string; "name": string; "newFlashcardCount": number; "sort": number; "sortMode": number; "state"?: "Locked" | "Unlocking" | "Unlocked" | "Locking" | "Error"; "subFileCount": number; "unlocked": boolean; };
+export type NotebookArchiveCandidate = { "current": boolean; "id": string; };
+
+export type NotebookArchiveCandidatesData = { "notebooks": Array<NotebookArchiveCandidate>; };
+
+export type NotebookArchiveData = { "file": string; "id": string; };
+
export type NotebookConf = { "boxCrypt": NotebookEncryption | null; "closed": boolean; "dailyNoteSavePath": string; "dailyNoteTemplatePath": string; "docCreateSaveBox": string; "docCreateSavePath": string; "docCreateTemplatePath": string; "encrypted": boolean; "icon": string; "name": string; "refCreateSaveBox": string; "refCreateSavePath": string; "sort": number; "sortMode": number; };
export type NotebookConfData = { "box": string; "conf": NotebookConf | null; "name": string; };
@@ -1456,6 +1466,8 @@ export type PluginRPCRequestFieldsInput = { "id"?: string | number | null; "json
export type PluginRPCSuccess = { "id": string | number | null; "jsonrpc": "2.0"; "result": JSONValue; };
+export type PrepareNotebookArchiveRequestInput = { "notebooks": Array<string>; };
+
export type PrepareRichTextRequestInput = { "assets": Array<RichClipboardAssetInput>; };
export type PrependBlockRequestInput = { "data": string; "dataType": string; "parentID": string; };
@@ -4261,6 +4273,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/notebook/commitNotebookArchive": {
+ request: CommitNotebookArchiveRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/notebook/createEncryptedNotebook": {
request: CreateEncryptedNotebookRequestInput;
response: { "code": 0; "data": CreateNotebookData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -4291,6 +4308,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": EncryptedNotebookStatusData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
};
+ "/api/notebook/getNotebookArchiveCandidates": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": NotebookArchiveCandidatesData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "none";
+ };
"/api/notebook/getNotebookConf": {
request: CloseNotebookRequestInput;
response: { "code": 0; "data": NotebookConfData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -4301,6 +4323,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": NotebookInfoData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/notebook/importNotebookArchive": {
+ request: ImportNotebookArchiveRequestInput;
+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "multipart";
+ };
"/api/notebook/importNotebookCryptoBackup": {
request: ImportNotebookCryptoBackupRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -4326,6 +4353,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/notebook/prepareNotebookArchive": {
+ request: PrepareNotebookArchiveRequestInput;
+ response: { "code": 0; "data": NotebookArchiveData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/notebook/removeNotebook": {
request: NotebookIDRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index 9f1de92c2c..53fccae4de 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -31,7 +31,7 @@ Encrypted notebooks are maintained as a released feature.
| Bookmarks | Not supported (feature limitation) |
| Tags | Not supported (feature limitation) |
| Import | Supported — imported .sy.zip and Markdown are DEK-encrypted before writing to disk, identical to manually created documents |
-| Enable / Disable | Enabling requires setting a master password; disabling requires no live encrypted notebook and no kernel-enumerable history or recovery snapshot that depends on the current key backup, unless those recovery artifacts are explicitly purged permanently |
+| Enable / Disable | Enabling requires setting a master password; disabling requires all active notebook and recovery dependencies to be removed or covered by verified archives that preserve the original ciphertext and key material |
| Restart behavior | All encrypted notebooks force-closed on startup (managed DEK handles exist only in process memory and must be derived again after restart); user must re-unlock |
| Existing normal notebooks | Completely untouched, zero migration |
| Existing encrypted data | Remains readable and recoverable after upgrades; format changes retain authenticated legacy reads or provide recoverable migration without requiring users to delete or recreate their data |
@@ -111,7 +111,7 @@ The preference is persisted as `system.encryptedNotebookFollowSystemLock`, outsi
| Scenario | Interaction |
|---|---|
| Enable | Settings - Authentication - Encrypted Notebook, then enable the toggle and set a master password (double input + risk confirmation) |
-| Disable | Supported only when no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on the current key backup; otherwise reject, or require explicit permanent purge of those recovery artifacts before deleting global config and backup |
+| Disable | Reject while encrypted notebooks or related history remain in active data; local repository snapshots require verified archives before retiring their key configuration. Explicit permanent purge remains a separate operation |
| Create | File panel - "more" menu - "New encrypted notebook"; enter a name and master password to unlock and open automatically |
| Icon | Shows lock icon when closed (locked); restores user emoji when opened (unlocked) |
| Unlock | Click a closed encrypted notebook, enter the password in the master-password prompt (🔓 Unlock xxx), and wait about one second for it to open |
@@ -259,7 +259,7 @@ User master password
MasterSalt is the global root of KEK derivation — the master password + MasterSalt derive the KEK via Argon2id, and the KEK then unwraps each notebook's WrappedDEK. Losing MasterSalt permanently locks the data: even with the same master password, a changed salt derives a different KEK, so old WrappedDEKs cannot be unwrapped. A backup-and-recovery mechanism is therefore introduced.
-Backup: `<DataDir>/.siyuan/data-crypto-backup.json`, storing the full NotebookCrypto (MasterSalt/KEKVerifier/KDFParams/HistoryKEKs). Located inside DataDir, it therefore enters the dejavu sync scope. It is refreshed when enabling encrypted notebooks and when changing the master password. It may be deleted on disable only after confirming that no live encrypted notebook and no kernel-enumerable history or recovery snapshot depends on it, or after the user explicitly chooses to purge those recovery artifacts permanently. The file uses plaintext JSON, with the verifier and historical KEKs stored as ciphertext, matching their representation in `conf/conf.json`.
+Backup: `<DataDir>/.siyuan/data-crypto-backup.json`, storing the full NotebookCrypto (MasterSalt/KEKVerifier/KDFParams/HistoryKEKs). Located inside DataDir, it therefore enters the dejavu sync scope. It is refreshed when enabling encrypted notebooks and when changing the master password. Disabling first checks active notebook and history dependencies and verified archive coverage for local recovery snapshots, then preserves versioned key material before removing the active backup. The file uses plaintext JSON, with the verifier and historical KEKs stored as ciphertext, matching their representation in `conf/conf.json`.
Each encrypted notebook separately stores `<DataDir>/<boxID>/.siyuan/notebook-crypto-backup.json`, containing that notebook's BoxEncryption key envelope (WrappedDEK/WrapNonce and authenticated metadata). The global `data-crypto-backup.json` supplies the KEK derivation identity, while the per-notebook `notebook-crypto-backup.json` supplies the wrapped DEK; therefore, neither file can replace the other.
@@ -283,7 +283,7 @@ Manual key export/import: Beyond auto-sync, users can manually export/import the
Import guard: a complete `Enabled` configuration rejects import to avoid overwriting the existing salt and orphaning WrappedDEKs. `RecoveryRequired` permits import only when the authenticated candidate key can unwrap every live encrypted notebook and every kernel-enumerable deleted-notebook history dependency. The backup file itself does not contain the master password (salt is not secret, verifier is ciphertext), so export/import does not leak plaintext data; unlocking still requires the master password.
-Recovery guard: When encrypted notebooks already exist on disk (notebooks with `Encrypted=true`) or kernel-enumerable encrypted recovery artifacts exist, `EnableEncryptedNotebook` refuses to regenerate MasterSalt (which would orphan old WrappedDEKs) and instead recovers from backup first; only if the backup is missing does it error out and guide the user to restore `conf.json` or the backup file. Symmetrically, `DisableEncryptedNotebook` scans live notebooks, deleted-notebook history, and local recovery snapshots; it refuses to disable while a dependency exists unless the user explicitly chooses to purge those recovery artifacts permanently. Sync endpoints, offline media, and external snapshots cannot be enumerated reliably, so users who may need those copies later must retain an independently exported matching key backup before disabling.
+Recovery guard: When encrypted notebooks or encrypted history remain in active data, `EnableEncryptedNotebook` recovers existing key material instead of regenerating MasterSalt, which would orphan old WrappedDEKs. Missing or unauthenticated material requires recovery. `DisableEncryptedNotebook` checks live notebooks, related history, and local recovery snapshots; active directories must be explicitly archived and removed or purged, and remaining encrypted snapshots must have verified archive coverage. Original ciphertext and keys remain in the archives, and current key variants are preserved separately before reset. Sync endpoints, offline media, and external snapshots cannot be enumerated reliably, so users who may need those copies later must retain an independently exported matching key backup before disabling.
Prerequisite: `restoreNotebookCryptoConfigFromBackup` only takes effect when the local `Enabled=false`; it never overwrites an in-use local config.
@@ -477,6 +477,14 @@ Native mobile save flows must call `AcquireExportFile` to obtain a lease contain
## Compatibility and recovery
+### Archiving notebooks that cannot be unlocked
+
+Encrypted notebook archives use the separate `siyuan-encrypted-notebooks` container, version 1. Existing document, asset, attribute-view, AAD, and key-envelope formats remain unchanged. Archives include the selected notebook directories, related local history, their files from local repository snapshots, and available global encryption configuration, key backups, and password-migration records. Deferred assets and missing local snapshot chunks must be completed before removal can be committed. File lists, sizes, and SHA-256 digests verify copying completeness, not ciphertext authentication or guaranteed recoverability.
+
+Archive preparation and removal confirmation are separate operations. Before confirmation is committed, source directories, history, key material, and remaining relevant snapshots are checked again; changes require a new archive. Starting a download in a browser or older mobile client does not establish that saving completed, so the user must explicitly confirm an independently saved copy. A persistent operation record moves selected source directories to `<workspace>/conf/notebook-archives/<operation ID>/removed/`, preserving the archive and original recovery material. Uncommitted moves are rolled back at startup without generating new deletion history. Partial removal preserves global keys, and removal propagates through normal data synchronization. Repository snapshots are not automatically deleted. Before retiring the old key configuration, encrypted recovery dependencies must be covered by complete archives, and versioned key material is preserved before clearing old key fields, including `HistoryKEKs`.
+
+The first recovery version accepts only a separate workspace without encryption keys or encrypted data and with synchronization disabled. Users supply the original master password and may provide a matching key backup recovered later. Recovery first validates the archive version, paths, file inventory, key-backup HMAC, historical keys, notebook envelopes, metadata, and document, asset, and attribute-view ciphertext in an isolated staging directory. Only successful authentication permits installation; notebooks remain locked. Existing global encryption configuration and backup variants are retained as recovery candidates; enabled configurations are never overwritten, and invalid or missing authenticated material is never replaced with fabricated keys. Archived repository snapshots become notebook deletion history, while the original archive preserves snapshot IDs and paths. Failures and interruptions retain the uploaded original and roll back uncommitted destination directories. Recovery never discards old ciphertext, bypasses authentication, or promises to recover data after losing the master password or all matching key material.
+
### Existing-data compatibility policy
Existing encrypted data is the compatibility baseline. Format and key-management changes must preserve access to existing data and its recovery paths; development status must never justify requiring users to delete or recreate their data. This covers documents, assets and their original names, attribute-view definitions, key envelopes, backups, history, and sync snapshots.
@@ -577,7 +585,7 @@ Backup persistence follows the project's existing file-write semantics. The glob
An HMAC proves only that a party without the KEK did not alter the backup; it does not prove that the backup is the latest version. The current scope introduces no trusted external monotonic counter, so an authenticated historical backup or ciphertext may pass validation. `BackupID` and `CreatedAt` are information for diagnostics and manual comparison, not rollback anchors. Sync, history, and recovery flows must not describe successful authentication as proof of freshness or source trust. Strong rollback prevention requires independent trusted state and is outside this design's scope.
-Sync endpoints and offline backups are storage that may be lost, copied, or rolled back but cannot read plaintext. Trustworthy KEK-based authentication cannot be established before the master password is entered. Therefore, users keep at least one independent, versioned key backup and understand that losing the master password or every matching MasterSalt backup is unrecoverable. While a live encrypted notebook, deleted-notebook history, or kernel-enumerable local recovery snapshot depends on the current NotebookCrypto, disabling must refuse to delete global configuration and backup; only an explicit permanent purge of those recovery artifacts removes the dependency. External and remote copies cannot be enumerated reliably, so retaining their matching key backup is the user's responsibility.
+Sync endpoints and offline backups are storage that may be lost, copied, or rolled back but cannot read plaintext. Trustworthy KEK-based authentication cannot be established before the master password is entered. Therefore, users keep at least one independent, versioned key backup and understand that losing the master password or every matching MasterSalt backup is unrecoverable. Disabling must reject unresolved active notebook, history, or local snapshot dependencies. Explicit verified archiving preserves ciphertext and key material outside active data before retiring the key configuration; permanent purging is a separate user action. External and remote copies cannot be enumerated reliably, so retaining their matching key backup is the user's responsibility.
| Category | May be exposed |
|---|---|
@@ -599,7 +607,7 @@ File history:
Deleted-notebook history:
before deletion → entire directory backed up as ciphertext to history dir
restore → copy the ciphertext directory back verbatim without opening it; authenticate WrappedDEK with the matching global key backup and master password when unlocking
- key retention → while kernel-managed history remains recoverable, deletion of the global key backup it depends on is forbidden; permanently purging the history removes the dependency
+ key retention: active history prevents key removal; verified archiving preserves history and matching keys outside active data before removing the dependency
database history:
generate → encrypted-notebook database files copied from notebook-level dir to history dir
@@ -626,7 +634,7 @@ Parent directories below the history root are not part of AAD. Every history ent
| Swap chunks or name metadata between different writes of a same-named version 2 asset, or mix metadata and chunks from old and new formats | Content authentication fails without falling back to another version; unknown versions, explicit null versions, and incomplete new metadata are rejected by both name and content reads |
| An archive source parent, archive entry path, or symbolic link points into an encrypted notebook | Check every source entry before packing and every target entry before extraction; an invalid archive must not write other entries first; ordinary archives remain usable |
| A block read omits the notebook parameter, or a batch spans encrypted notebooks | Acquire response leases for every notebook based on actual block ownership and hold them until the response is written; reject unknown ownership rather than returning content without a lease after a later unlock |
-| Delete an encrypted notebook while retaining history, then disable or restore | A key dependency prevents deletion of global config and backup; the matching backup and master password restore the notebook, and only explicit permanent purge removes the dependency |
+| Delete an encrypted notebook while retaining history, then disable or restore | Active history prevents key removal; the matching backup and master password restore it. Verified archiving preserves ciphertext and keys outside active data before removing the dependency; permanent purging is a separate action |
| Move a document's parent directory or change its basename after creating history, then view or restore the old entry | Authenticate and decrypt with the snapshot boxID, object type, and stable basename recorded by the history entry; rollback serializes the restored tree and re-envelopes it with the target basename while preserving the historical ciphertext, while missing snapshot context rejects the operation |
| Disk inspection of files, assets, databases, WAL/SHM, history, snapshots, and logs | No readable body, asset contents, original asset names, or plaintext SQLite pages exist in encrypted-notebook persistent locations; `temp/` may contain plaintext during export or after cleanup failure |
| Restart after an abnormal exit | Startup removes at least entries under `temp/export/` whose first-level name is a valid boxID; generic temporary-directory initialization may also remove other exports and plugin temporary files |
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 829dbbbc38..42b46f21e0 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -31,7 +31,7 @@
| 书签 | 不支持(功能限制) |
| 标签 | 不支持(功能限制) |
| 导入 | 支持——导入的 .sy.zip 和 Markdown 在落盘前用 DEK 加密,与手动创建的文档一致 |
-| 启用/禁用 | 启用需设主密码;禁用需确认无现存加密笔记本,且无依赖当前密钥备份的内核可枚举历史或恢复快照;否则必须先明确永久清除这些恢复数据 |
+| 启用/禁用 | 启用需设主密码;禁用需处理全部活动笔记本和恢复依赖,或以经过完整校验的归档保留原始密文与密钥材料 |
| 重启行为 | 启动时强制关闭所有加密笔记本(受管 DEK 句柄仅存在于进程内存,重启后需重新派生),用户需重新解锁 |
| 已有普通笔记本 | 完全不动,零迁移 |
| 已有加密数据 | 升级后继续可读、可恢复;格式变更保留旧版认证读取或提供可恢复迁移,不要求删除或重建用户数据 |
@@ -111,7 +111,7 @@ Windows 和 macOS 桌面端在 设置 - 鉴权 - 加密笔记本 中提供「跟
| 场景 | 交互 |
|---|---|
| 启用 | 设置 - 鉴权 - 加密笔记本,打开开关并设置主密码(双输入 + 风险确认) |
-| 禁用 | 仅在无现存加密笔记本且无依赖当前密钥备份的内核可枚举历史或恢复快照时支持关闭;否则拒绝,或要求用户明确永久清除这些恢复数据后再删除全局配置与备份 |
+| 禁用 | 活动数据中仍有加密笔记本或相关历史时拒绝关闭;本地仓库快照须有完整校验的归档,才能结束其密钥配置。显式永久清除仍是独立操作 |
| 创建 | 文件面板 - 「更多」菜单 - 「新建加密笔记本」,输入名字和主密码后自动解锁并打开 |
| 图标 | 关闭(锁定)时显示锁图标;打开(解锁)后恢复用户 emoji |
| 解锁 | 点击已关闭的加密笔记本,在主密码框(🔓 解锁 xxx)中输入密码,等待约 1 秒后打开 |
@@ -259,7 +259,7 @@ Windows 和 macOS 桌面端在 设置 - 鉴权 - 加密笔记本 中提供「跟
MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各笔记本的 WrappedDEK。MasterSalt 丢失等于数据永久锁死:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。
-备份:`<DataDir>/.siyuan/data-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams/HistoryKEKs)。位于 DataDir 内,因此进入 dejavu 同步范围。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储,其中 verifier 和历史 KEK 均为密文,与 `conf/conf.json` 的存储方式一致。
+备份:`<DataDir>/.siyuan/data-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams/HistoryKEKs)。位于 DataDir 内,因此进入 dejavu 同步范围。启用加密笔记本、修改主密码时刷新。禁用先检查活动笔记本和历史依赖,以及本地恢复快照的完整归档覆盖情况,再另存版本化密钥材料,最后删除活动备份。备份文件按明文 JSON 存储,其中 verifier 和历史 KEK 均为密文,与 `conf/conf.json` 的存储方式一致。
每个加密笔记本另行保存 `<DataDir>/<boxID>/.siyuan/notebook-crypto-backup.json`,其中包含该笔记本的 BoxEncryption 密钥包络(WrappedDEK/WrapNonce 和认证元数据)。全局 `data-crypto-backup.json` 提供 KEK 派生身份,单笔记本 `notebook-crypto-backup.json` 提供已封装 DEK,因此两者不能相互替代。
@@ -283,7 +283,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
导入恢复保护:完整的 `Enabled` 配置拒绝导入,避免覆盖现有 salt 并孤立 WrappedDEK;`RecoveryRequired` 仅在候选密钥通过认证且能解开全部现存加密笔记本及内核可枚举的已删除笔记本历史依赖时允许导入。备份文件本身不含主密码(salt 不保密、verifier 是密文),导出和导入不涉及明文数据泄漏,解锁仍需主密码。
-恢复保护守卫:`EnableEncryptedNotebook` 在磁盘上已存在加密笔记本(`Encrypted=true` 的笔记本)或内核可枚举的加密恢复数据时,禁止重新生成 MasterSalt(否则会孤立旧 WrappedDEK),改为优先从备份恢复;备份缺失才报错引导用户恢复 `conf.json` 或备份文件。`DisableEncryptedNotebook` 对称地扫描现存笔记本、已删除笔记本历史和本地恢复快照;存在依赖时必须拒绝禁用,除非用户明确选择永久清除这些恢复数据。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。
+恢复保护守卫:活动数据中仍有加密笔记本或加密历史时,`EnableEncryptedNotebook` 恢复既有密钥材料,不重新生成会孤立旧 WrappedDEK 的 MasterSalt;材料缺失或无法认证时要求恢复。`DisableEncryptedNotebook` 检查现存笔记本、相关历史和本地恢复快照;活动目录须显式归档移出或清除,保留的加密快照须有完整归档覆盖。原始密文与密钥留在归档中,重置前还会另存当前密钥配置的各个副本。同步端、离线介质和外部快照无法可靠枚举,用户若希望以后恢复这些副本,禁用前必须另行保留导出的匹配密钥备份。
前提条件:`restoreNotebookCryptoConfigFromBackup` 仅在本机 `Enabled=false` 时生效,不覆盖正在使用的本机配置。
@@ -477,6 +477,14 @@ assets 加密:
## 兼容与恢复
+### 无法解锁的笔记本归档
+
+加密笔记本归档使用独立容器 `siyuan-encrypted-notebooks` 第 1 版,不改变已有文档、资源、数据库定义、AAD 或密钥包络格式。归档包含所选笔记本的原始目录、关联本地历史、本地仓库快照中的对应文件,以及现存全局加密配置、密钥备份和改密迁移记录。按需资源和缺失的本地快照分块必须先补齐,失败时不提交移出。文件清单、大小和 SHA-256 摘要仅用于验证复制完整性,不表示密文已认证或材料必然可恢复。
+
+生成归档与确认移出分开执行。确认前复核源目录、历史、密钥材料和仍存在的相关快照;变化时要求重新归档。浏览器或旧版移动端发起下载不等于保存完成,用户必须明确确认已另行保存。提交通过持久化记录把所选源目录移动到 `<工作区>/conf/notebook-archives/<操作 ID>/removed/`,保留归档和原始恢复材料;未提交的移动在启动时回滚,不生成新的删除历史。部分移出不修改全局密钥,移出随正常数据同步传播。仓库快照不自动删除;结束旧密钥配置前,必须确认其加密恢复依赖已由完整归档覆盖,另存版本化密钥材料后再清空旧密钥字段,包括 `HistoryKEKs`。
+
+首版恢复只面向没有加密密钥或加密数据、且关闭同步的独立工作区。用户提供原主密码,并可补充后来找回的匹配密钥备份。恢复先在独立暂存目录校验归档版本、路径、文件清单、密钥备份 HMAC、历史密钥、笔记本包络、元数据及文档、资源、数据库密文;全部认证成功后提交,笔记本保持锁定。现存全局加密配置与备份均作为候选恢复材料保留,不覆盖已启用配置,不为无效或缺失的认证材料制造替代密钥。归档中的仓库快照转换为笔记本删除历史供恢复,原归档保留快照 ID 和原路径。失败或中断保留上传原件并回滚未提交的目标目录;不丢弃旧密文、不绕过认证,也不承诺从已丢失的主密码或全部匹配密钥材料恢复数据。
+
### 已有数据兼容策略
当前已写入的加密数据作为兼容基线。格式和密钥管理变更必须保留已有数据的可读性与恢复能力,不得再以开发阶段为由要求用户删除或重建数据。兼容范围包括文档、资源及其原始名称、数据库定义、密钥包络、备份、历史和同步快照。
@@ -577,7 +585,7 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明它是最新版本。当前范围不引入可信外部单调计数器,因此一个认证有效的历史备份或历史密文可能通过校验;`BackupID` 和 `CreatedAt` 只是供诊断和人工比较的信息,不是防回滚锚点。同步、历史或恢复流程不得把“认证成功”表述为“最新”或“来源可信”;真正防回滚需要独立可信状态,超出本设计范围。
-同步端和离线备份被视为可丢失、可复制、可回滚但不能读取明文的存储。输入主密码前不能建立基于 KEK 的可信认证;因此用户应保留至少一份独立、版本化的密钥备份,并理解丢失主密码或全部匹配的 MasterSalt 备份均不可恢复。只要现存加密笔记本、已删除笔记本历史或内核可枚举的本地恢复快照仍依赖当前 NotebookCrypto,禁用功能就必须拒绝删除全局配置和备份;用户明确永久清除这些恢复数据后才可解除依赖。外部与远端副本无法可靠枚举,是否保留其匹配密钥备份由用户负责。
+同步端和离线备份被视为可丢失、可复制、可回滚但不能读取明文的存储。输入主密码前不能建立基于 KEK 的可信认证;因此用户应保留至少一份独立、版本化的密钥备份,并理解丢失主密码或全部匹配的 MasterSalt 备份均不可恢复。活动笔记本、历史或本地快照的依赖尚未处理时,禁用必须被拒绝。显式校验并移出归档后,密文和密钥材料保留在活动数据之外,再结束旧密钥配置;永久清除仍须由用户另行操作。外部与远端副本无法可靠枚举,是否保留其匹配密钥备份由用户负责。
| 类别 | 是否可泄露 |
|---|---|
@@ -599,7 +607,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
已删除笔记本历史:
删除前 → 整个目录密文备份到历史目录
恢复 → 将密文目录原样拷回并保持关闭,解锁时再使用匹配的全局密钥备份和主密码验证 WrappedDEK
- 密钥保留 → 只要内核管理的该类历史仍可恢复,就禁止删除其依赖的全局密钥备份;永久清除历史后才解除依赖
+ 密钥保留:活动历史阻止清除密钥;校验并移出归档后,历史和匹配密钥保留在活动数据之外,再解除依赖
数据库历史:
生成 → 加密笔记本的数据库文件从笔记本级目录拷到历史目录
@@ -626,7 +634,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
| 将同名第 2 版资源的不同写入版本互换分块或名称元数据,或混用新旧格式的元数据与分块 | 内容认证失败且不回退其他版本;未知版本、显式空版本或不完整的新版元数据在名称读取和内容读取时均被拒绝 |
| 通用归档入口的父目录、压缩包内部路径及符号链接指向加密笔记本 | 打包前检查全部源条目,解压前检查全部目标条目;非法归档不得先写入其他条目,正常归档仍可使用 |
| 块读取省略 notebook 参数,或批量请求跨多个加密笔记本 | 根据块的实际归属取得所有相关笔记本的响应租约,锁定等到响应写入完成;无法确定归属时拒绝读取,不在后续解锁后无租约返回内容 |
-| 删除加密笔记本后保留历史,再尝试禁用或恢复 | 存在密钥依赖时拒绝删除全局配置和备份;使用匹配备份与主密码可恢复,只有明确永久清除恢复数据后才允许解除依赖 |
+| 删除加密笔记本后保留历史,再尝试禁用或恢复 | 活动历史阻止清除密钥,使用匹配备份与主密码可恢复;校验并移出归档后,密文和密钥保留在活动数据之外,再解除依赖;永久清除仍是独立操作 |
| 文档生成历史后移动父目录或改变文件基名,再查看或回滚旧历史 | 使用历史条目记录的快照 boxID、对象类型和稳定文件基名认证解密;序列化恢复后的树并按目标基名重新封装,保留历史源密文,缺失快照上下文时拒绝操作 |
| 文件、资源、数据库、WAL/SHM、历史、快照和日志的磁盘检查 | 加密笔记本持久化范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页;`temp/` 可能在导出期间或清理失败后包含明文 |
| 异常退出后重启 | 启动时至少删除 `temp/export/` 下第一层名称为合法 boxID 的残留目录;通用临时目录初始化可以同时清理其他导出和插件临时文件 |
diff --git a/kernel/api/contract_notebook_archive_test.go b/kernel/api/contract_notebook_archive_test.go
new file mode 100644
index 0000000000..3750ed0506
--- /dev/null
+++ b/kernel/api/contract_notebook_archive_test.go
@@ -0,0 +1,37 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+func TestAPIContractNotebookArchiveAdmission(t *testing.T) {
+ oldConf := model.Conf
+ model.Conf = model.NewAppConf()
+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ t.Cleanup(func() { model.Conf = oldConf })
+ engine := gin.New()
+ engine.POST("/api/notebook/commitNotebookArchive", commitNotebookArchive)
+ engine.POST("/api/notebook/importNotebookArchive", importNotebookArchive)
+ for _, item := range []struct{ path, body string }{
+ {"/api/notebook/commitNotebookArchive", `{"id":"../../outside","saved":false}`},
+ {"/api/notebook/commitNotebookArchive", `{"id":"../../outside","saved":true}`},
+ {"/api/notebook/commitNotebookArchive", `{"id":"id","saved":"true"}`},
+ {"/api/notebook/importNotebookArchive", `{}`},
+ } {
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, item.path, strings.NewReader(item.body))
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+ requireAPIContract(t, http.MethodPost, item.path, recorder)
+ if !strings.Contains(recorder.Body.String(), `"code":-1`) {
+ t.Fatalf("invalid request admitted: %s", recorder.Body.String())
+ }
+ }
+}
diff --git a/kernel/api/contract_notebook_test.go b/kernel/api/contract_notebook_test.go
index 9a4c923b50..61278e982a 100644
--- a/kernel/api/contract_notebook_test.go
+++ b/kernel/api/contract_notebook_test.go
@@ -82,7 +82,7 @@ func TestAPIContractNotebookCryptoAuthorization(t *testing.T) {
c.Next()
})
ServeAPI(engine)
- for _, name := range []string{"enableEncryptedNotebooks", "disableEncryptedNotebooks", "createEncryptedNotebook", "unlockNotebook", "unlockAndOpenNotebook", "lockNotebook", "setNotebookCryptoAutoLock", "setEncryptedNotebookFollowSystemLock", "lockEncryptedNotebooksOnSystemLock", "changeMasterPassword", "exportNotebookCryptoBackup", "importNotebookCryptoBackup"} {
+ for _, name := range []string{"enableEncryptedNotebooks", "disableEncryptedNotebooks", "createEncryptedNotebook", "unlockNotebook", "unlockAndOpenNotebook", "lockNotebook", "setNotebookCryptoAutoLock", "setEncryptedNotebookFollowSystemLock", "lockEncryptedNotebooksOnSystemLock", "changeMasterPassword", "exportNotebookCryptoBackup", "importNotebookCryptoBackup", "getNotebookArchiveCandidates", "prepareNotebookArchive", "commitNotebookArchive", "importNotebookArchive"} {
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/notebook/"+name, strings.NewReader(`{}`)))
if recorder.Code != http.StatusForbidden {
diff --git a/kernel/api/notebook_archive.go b/kernel/api/notebook_archive.go
new file mode 100644
index 0000000000..2daa7e3d11
--- /dev/null
+++ b/kernel/api/notebook_archive.go
@@ -0,0 +1,96 @@
+package api
+
+import (
+ "errors"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func notebookArchiveFailure[Data any](err error) apicontract.Response[Data] {
+ logging.LogErrorf("encrypted notebook archive failed: %s", err)
+ key := 406
+ switch {
+ case errors.Is(err, model.ErrNotebookArchiveInvalid):
+ key = 401
+ case errors.Is(err, model.ErrNotebookArchiveChanged):
+ key = 402
+ case errors.Is(err, model.ErrNotebookArchiveBusy):
+ key = 403
+ case errors.Is(err, model.ErrNotebookArchiveConfigured):
+ key = 404
+ case errors.Is(err, model.ErrNotebookArchiveAuthentication):
+ key = 405
+ }
+ return apicontract.FailureWithTimeout[Data](-1, model.Conf.Language(key), 7000)
+}
+
+var getNotebookArchiveCandidates = contractHandler(apicontract.GetNotebookArchiveCandidates, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.NotebookArchiveCandidatesData] {
+ candidates, err := model.ListNotebookArchiveCandidates()
+ if err != nil {
+ return notebookArchiveFailure[apicontract.NotebookArchiveCandidatesData](err)
+ }
+ notebooks := make([]apicontract.NotebookArchiveCandidate, 0, len(candidates))
+ for _, candidate := range candidates {
+ notebooks = append(notebooks, apicontract.NotebookArchiveCandidate{ID: candidate.ID, Current: candidate.Current})
+ }
+ return apicontract.Success(apicontract.NotebookArchiveCandidatesData{Notebooks: notebooks})
+})
+
+var prepareNotebookArchive = contractHandler(apicontract.PrepareNotebookArchive, func(c *gin.Context, request apicontract.PrepareNotebookArchiveRequest) apicontract.Response[apicontract.NotebookArchiveData] {
+ id, file, err := model.PrepareNotebookArchive(request.Notebooks)
+ if err != nil {
+ return notebookArchiveFailure[apicontract.NotebookArchiveData](err)
+ }
+ return apicontract.Success(apicontract.NotebookArchiveData{ID: id, File: file})
+})
+
+var commitNotebookArchive = contractHandler(apicontract.CommitNotebookArchive, func(c *gin.Context, request apicontract.CommitNotebookArchiveRequest) apicontract.Response[apicontract.Null] {
+ if err := model.CommitNotebookArchive(request.ID, request.Saved); err != nil {
+ return notebookArchiveFailure[apicontract.Null](err)
+ }
+ return apicontract.Success(apicontract.Null{})
+})
+
+var importNotebookArchive = contractHandler(apicontract.ImportNotebookArchive, func(c *gin.Context, request apicontract.ImportNotebookArchiveRequest) apicontract.Response[apicontract.Null] {
+ input, err := request.File.Open()
+ if err != nil {
+ return notebookArchiveFailure[apicontract.Null](err)
+ }
+ defer input.Close()
+ file, err := os.CreateTemp(util.TempDir, "notebook-archive-upload-*.zip")
+ if err != nil {
+ return notebookArchiveFailure[apicontract.Null](err)
+ }
+ defer os.Remove(file.Name())
+ _, err = io.Copy(file, input)
+ closeErr := file.Close()
+ if err == nil {
+ err = closeErr
+ }
+ if err != nil {
+ return notebookArchiveFailure[apicontract.Null](err)
+ }
+ var keyData []byte
+ if request.Key != nil {
+ key, openErr := request.Key.Open()
+ if openErr != nil {
+ return notebookArchiveFailure[apicontract.Null](openErr)
+ }
+ keyData, err = io.ReadAll(io.LimitReader(key, 4*1024*1024+1))
+ key.Close()
+ if err != nil || len(keyData) > 4*1024*1024 {
+ return notebookArchiveFailure[apicontract.Null](model.ErrNotebookArchiveInvalid)
+ }
+ }
+ if err = model.ImportNotebookArchive(file.Name(), strings.TrimSpace(request.Password), keyData); err != nil {
+ return notebookArchiveFailure[apicontract.Null](err)
+ }
+ return apicontract.Success(apicontract.Null{})
+})
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 065696f8a9..4c99fc043e 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -157,6 +157,10 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/notebook/getEncryptedNotebookStatus", model.CheckAuth, model.CheckAdminRole, getEncryptedNotebookStatus)
ginServer.Handle("POST", "/api/notebook/exportNotebookCryptoBackup", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, exportNotebookCryptoBackup)
ginServer.Handle("POST", "/api/notebook/importNotebookCryptoBackup", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importNotebookCryptoBackup)
+ ginServer.Handle("POST", "/api/notebook/getNotebookArchiveCandidates", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getNotebookArchiveCandidates)
+ ginServer.Handle("POST", "/api/notebook/prepareNotebookArchive", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, prepareNotebookArchive)
+ ginServer.Handle("POST", "/api/notebook/commitNotebookArchive", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, commitNotebookArchive)
+ ginServer.Handle("POST", "/api/notebook/importNotebookArchive", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importNotebookArchive)
ginServer.Handle("POST", "/api/notebook/setNotebookCryptoAutoLock", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setNotebookCryptoAutoLock)
ginServer.Handle("POST", "/api/notebook/setEncryptedNotebookFollowSystemLock", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setEncryptedNotebookFollowSystemLock)
ginServer.Handle("POST", "/api/notebook/lockEncryptedNotebooksOnSystemLock", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, lockEncryptedNotebooksOnSystemLock)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index f0c18a60c7..42086b36ed 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -310,6 +310,10 @@ var (
ChangeMasterPassword = define[ChangeMasterPasswordRequest, Null]("changeMasterPassword", "/api/notebook/changeMasterPassword", JSONBody, ResponseOptions{}, "POST")
ExportNotebookCryptoBackup = define[EmptyRequest, NotebookCryptoBackupData]("exportNotebookCryptoBackup", "/api/notebook/exportNotebookCryptoBackup", NoBody, ResponseOptions{}, "POST")
TouchEncryptedNotebooks = define[EmptyRequest, Null]("touchEncryptedNotebooks", "/api/notebook/touchEncryptedNotebooks", NoBody, ResponseOptions{}, "POST")
+ GetNotebookArchiveCandidates = define[EmptyRequest, NotebookArchiveCandidatesData]("getNotebookArchiveCandidates", "/api/notebook/getNotebookArchiveCandidates", NoBody, ResponseOptions{}, "POST")
+ PrepareNotebookArchive = define[PrepareNotebookArchiveRequest, NotebookArchiveData]("prepareNotebookArchive", "/api/notebook/prepareNotebookArchive", JSONBody, ResponseOptions{}, "POST")
+ CommitNotebookArchive = define[CommitNotebookArchiveRequest, Null]("commitNotebookArchive", "/api/notebook/commitNotebookArchive", JSONBody, ResponseOptions{}, "POST")
+ ImportNotebookArchive = define[ImportNotebookArchiveRequest, Null]("importNotebookArchive", "/api/notebook/importNotebookArchive", MultipartBody, ResponseOptions{}, "POST")
)
var (
diff --git a/kernel/apicontract/notebook_archive.go b/kernel/apicontract/notebook_archive.go
new file mode 100644
index 0000000000..1d7f2cf2e9
--- /dev/null
+++ b/kernel/apicontract/notebook_archive.go
@@ -0,0 +1,41 @@
+package apicontract
+
+import "mime/multipart"
+
+// NotebookArchiveCandidate 包含现存加密笔记本及只有本地历史或仓库快照的笔记本,不包含解密后的名称。
+type NotebookArchiveCandidate struct {
+ ID string `json:"id"`
+ Current bool `json:"current"`
+}
+
+type NotebookArchiveCandidatesData struct {
+ Notebooks []NotebookArchiveCandidate `json:"notebooks" api:"nonnullable"`
+}
+
+// PrepareNotebookArchiveRequest 必须显式选择至少一个笔记本;只接受已锁定的笔记本,不需要主密码。
+// 归档保留原始密文、关联历史、本地仓库快照和现存密钥材料。成功仅生成归档,不移除任何源数据。
+type PrepareNotebookArchiveRequest struct {
+ Notebooks []string `json:"notebooks" api:"nonnullable"`
+}
+
+type NotebookArchiveData struct {
+ ID string `json:"id"`
+ File string `json:"file"`
+}
+
+// CommitNotebookArchiveRequest 必须确认归档已另行保存;浏览器发起下载不等于保存成功。
+// 内核复核源数据未变化后移出所选笔记本及关联历史;仓库快照不删除,原件留在工作区的独立恢复目录。
+// 同一 ID 的成功提交可重复调用。部分移出保留全局密钥;全部依赖归档后仍需单独禁用再启用。
+type CommitNotebookArchiveRequest struct {
+ ID string `json:"id"`
+ Saved bool `json:"saved"`
+}
+
+// ImportNotebookArchiveRequest 只接受尚无加密配置和加密数据、且未开启同步的独立工作区。
+// Password 用于认证恢复材料和密文;Key 可提供后来找回的匹配密钥备份,不提供时使用归档内的材料。
+// 导入保持原始标识与密文格式,完成后仍处于锁定状态;未知版本、认证失败或标识冲突不会覆盖已有数据。
+type ImportNotebookArchiveRequest struct {
+ File *multipart.FileHeader `json:"file" api:"nonnullable"`
+ Key *multipart.FileHeader `json:"key" api:"optional,nonnullable"`
+ Password string `json:"password"`
+}
diff --git a/kernel/apicontract/notebook_archive_test.go b/kernel/apicontract/notebook_archive_test.go
new file mode 100644
index 0000000000..20497dc5a7
--- /dev/null
+++ b/kernel/apicontract/notebook_archive_test.go
@@ -0,0 +1,23 @@
+package apicontract
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestNotebookArchiveContract(t *testing.T) {
+ for _, body := range []string{`{}`, `{"id":"archive"}`, `{"id":"archive","saved":null}`, `{"id":"archive","saved":"true"}`} {
+ if _, err := CommitNotebookArchive.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("accepted invalid confirmation: %s", body)
+ }
+ }
+ request, err := CommitNotebookArchive.Decode(strings.NewReader(`{"id":"archive","saved":false}`))
+ if err != nil || request.Saved {
+ t.Fatalf("false confirmation changed: %+v %v", request, err)
+ }
+ for _, body := range []string{`{}`, `{"notebooks":null}`, `{"notebooks":[null]}`, `{"notebooks":"id"}`} {
+ if _, err := PrepareNotebookArchive.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("accepted invalid notebook selection: %s", body)
+ }
+ }
+}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 4a727988ce..3b2762ca90 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -19579,6 +19579,22 @@
],
"additionalProperties": false
},
+ "CommitNotebookArchiveRequestInput": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "saved": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "id",
+ "saved"
+ ],
+ "additionalProperties": false
+ },
"ContentWordCountRequestInput": {
"type": "object",
"properties": {
@@ -27604,6 +27620,27 @@
],
"additionalProperties": false
},
+ "ImportNotebookArchiveRequestInput": {
+ "type": "object",
+ "properties": {
+ "file": {
+ "type": "string",
+ "format": "binary"
+ },
+ "key": {
+ "type": "string",
+ "format": "binary"
+ },
+ "password": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "file",
+ "password"
+ ],
+ "additionalProperties": false
+ },
"ImportNotebookCryptoBackupRequestInput": {
"type": "object",
"properties": {
@@ -31571,6 +31608,53 @@
],
"additionalProperties": false
},
+ "NotebookArchiveCandidate": {
+ "type": "object",
+ "properties": {
+ "current": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "current",
+ "id"
+ ],
+ "additionalProperties": false
+ },
+ "NotebookArchiveCandidatesData": {
+ "type": "object",
+ "properties": {
+ "notebooks": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/NotebookArchiveCandidate"
+ }
+ }
+ },
+ "required": [
+ "notebooks"
+ ],
+ "additionalProperties": false
+ },
+ "NotebookArchiveData": {
+ "type": "object",
+ "properties": {
+ "file": {
+ "type": "string"
+ },
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "file",
+ "id"
+ ],
+ "additionalProperties": false
+ },
"NotebookConf": {
"type": "object",
"properties": {
@@ -32930,6 +33014,21 @@
],
"additionalProperties": false
},
+ "PrepareNotebookArchiveRequestInput": {
+ "type": "object",
+ "properties": {
+ "notebooks": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ },
+ "required": [
+ "notebooks"
+ ],
+ "additionalProperties": false
+ },
"PrepareRichTextRequestInput": {
"type": "object",
"properties": {
@@ -138527,6 +138626,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/notebook/commitNotebookArchive",
+ "handler": "commitNotebookArchive",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/CommitNotebookArchiveRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "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/notebook/createEncryptedNotebook",
@@ -138977,6 +139151,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/notebook/getNotebookArchiveCandidates",
+ "handler": "getNotebookArchiveCandidates",
+ "body": "none",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/NotebookArchiveCandidatesData"
+ },
+ "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/notebook/getNotebookConf",
@@ -139127,6 +139376,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/notebook/importNotebookArchive",
+ "handler": "importNotebookArchive",
+ "body": "multipart",
+ "request": {
+ "$ref": "#/$defs/ImportNotebookArchiveRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "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/notebook/importNotebookCryptoBackup",
@@ -139509,6 +139833,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/notebook/prepareNotebookArchive",
+ "handler": "prepareNotebookArchive",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/PrepareNotebookArchiveRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/NotebookArchiveData"
+ },
+ "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/notebook/removeNotebook",
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 2a88f071f0..3a7c863315 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -240,6 +240,10 @@ func InitConf() {
initLang()
Conf = NewAppConf()
+ // 先回滚未提交的目录移动,即使配置文件丢失也必须在挂载和同步之前恢复。
+ if err := recoverNotebookArchiveOperations(); err != nil {
+ logging.LogErrorf("recover notebook archive operations failed: %s", err)
+ }
clearEncryptedExportTempOnBoot()
clearOldInstallPackages("")
confPath := filepath.Join(util.ConfDir, "conf.json")
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 65dd67684d..2b3ff4a4a2 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -318,6 +318,9 @@ func ExportNotebookCryptoBackup() (downloadPath string, err error) {
func ImportNotebookCryptoBackup(data []byte, password string) error {
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
+ if err := checkPendingNotebookArchives(); err != nil {
+ return err
+ }
Conf.m.RLock()
current := *Conf.NotebookCrypto
@@ -1000,6 +1003,9 @@ func EnableEncryptedNotebook(password string) error {
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
+ if err := checkPendingNotebookArchives(); err != nil {
+ return err
+ }
Conf.m.RLock()
current := *Conf.NotebookCrypto
@@ -1087,8 +1093,13 @@ func EnableEncryptedNotebook(password string) error {
// 且不能有依赖当前密钥备份的已删除笔记本历史(否则禁用并删除备份会让这些历史永久锁死,违反 §19)。
// 清除全局加密配置(MasterSalt/KEKVerifier),KEK/DEK 不再可用。
func DisableEncryptedNotebook() error {
+ lockSync()
+ defer unlockSync()
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
+ if err := checkPendingNotebookArchives(); err != nil {
+ return err
+ }
// 检查是否还有加密笔记本(含 conf 损坏但存在备份的)
ids, listErr := listAllEncryptedBoxIDs()
@@ -1107,12 +1118,15 @@ func DisableEncryptedNotebook() error {
if hasHistory {
return errors.New(Conf.Language(323))
}
+ if err := preserveNotebookCryptoBeforeDisable(); err != nil {
+ logging.LogErrorf("preserve notebook crypto before disabling failed: %s", err)
+ return errors.New(Conf.Language(407))
+ }
Conf.m.Lock()
- Conf.NotebookCrypto.Enabled = false
- Conf.NotebookCrypto.MasterSalt = nil
- Conf.NotebookCrypto.KEKVerifier = nil
- Conf.NotebookCrypto.VerifierNonce = nil
+ autoLockMinutes := Conf.NotebookCrypto.AutoLockMinutes
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.NotebookCrypto.AutoLockMinutes = autoLockMinutes
Conf.m.Unlock()
Conf.Save()
@@ -1218,6 +1232,9 @@ func deriveNotebookCryptoBackupCandidate(password string) (backup *conf.Notebook
// deriveKEK 从主密码派生 KEK 并校验。校验失败返回错误。KEK 仅在函数作用域内有效,调用方负责使用。
func deriveKEK(password string) ([]byte, error) {
+ if err := checkPendingNotebookArchives(); err != nil {
+ return nil, err
+ }
Conf.m.RLock()
nc := *Conf.NotebookCrypto
Conf.m.RUnlock()
diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.go
index 21da66ea20..e783250cdf 100644
--- a/kernel/model/crypto_lifecycle.go
+++ b/kernel/model/crypto_lifecycle.go
@@ -118,7 +118,8 @@ func NotebookCryptoLifecycleState(hasRecoveryDependency bool) NotebookCryptoStat
}
return NotebookCryptoStateRecoveryRequired
}
- if hasRecoveryDependency || filelock.IsExist(dataCryptoBackupPath()) {
+ if hasRecoveryDependency || filelock.IsExist(dataCryptoBackupPath()) || len(notebookCrypto.MasterSalt) != 0 ||
+ len(notebookCrypto.KEKVerifier) != 0 || len(notebookCrypto.HistoryKEKs) != 0 || notebookCrypto.BackupID != "" || len(notebookCrypto.KEKMAC) != 0 {
return NotebookCryptoStateRecoveryRequired
}
return NotebookCryptoStateDisabled
diff --git a/kernel/model/history.go b/kernel/model/history.go
index 6a32efc0f9..6a0467be16 100644
--- a/kernel/model/history.go
+++ b/kernel/model/history.go
@@ -110,6 +110,8 @@ func ChangeHistoryTick(minutes int) {
}
func ClearWorkspaceHistory() (err error) {
+ notebookArchiveHistoryMu.Lock()
+ defer notebookArchiveHistoryMu.Unlock()
historyDir := util.HistoryDir
if gulu.File.IsDir(historyDir) {
if err = os.RemoveAll(historyDir); err != nil {
@@ -1027,6 +1029,8 @@ func ClearOutdatedHistoryDirJob() {
}
func clearOutdatedHistoryDir() {
+ notebookArchiveHistoryMu.Lock()
+ defer notebookArchiveHistoryMu.Unlock()
historyDir := util.HistoryDir
if !gulu.File.IsExist(historyDir) {
return
@@ -1222,6 +1226,8 @@ func ReindexHistory() {
}
func fullReindexHistory() {
+ notebookArchiveHistoryMu.Lock()
+ defer notebookArchiveHistoryMu.Unlock()
historyDirs, err := os.ReadDir(util.HistoryDir)
if err != nil {
logging.LogErrorf("read history dir [%s] failed: %s", util.HistoryDir, err)
diff --git a/kernel/model/notebook_archive.go b/kernel/model/notebook_archive.go
new file mode 100644
index 0000000000..b87e66d2ed
--- /dev/null
+++ b/kernel/model/notebook_archive.go
@@ -0,0 +1,776 @@
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/dejavu"
+ "github.com/siyuan-note/dejavu/entity"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var notebookArchiveMu sync.Mutex
+var notebookArchiveHistoryMu sync.Mutex
+
+type NotebookArchiveCandidate struct {
+ ID string
+ Current bool
+}
+
+type notebookArchiveOperation struct {
+ State string `json:"state"`
+ Roots []string `json:"roots"`
+}
+
+func (operation *notebookArchiveOperation) valid() bool {
+ switch operation.State {
+ case "prepared", "committing", "committed", "importing", "imported", "import-failed":
+ default:
+ return false
+ }
+ seen := map[string]bool{}
+ for _, root := range operation.Roots {
+ if _, err := archiveSourcePath(root); err != nil || seen[root] {
+ return false
+ }
+ seen[root] = true
+ }
+ return true
+}
+
+// ListNotebookArchiveCandidates 同时列出现存密文和只有历史的笔记本,不要求解锁或派生密钥。
+func ListNotebookArchiveCandidates() ([]NotebookArchiveCandidate, error) {
+ lockSync()
+ defer unlockSync()
+ notebookCryptoMu.Lock()
+ defer notebookCryptoMu.Unlock()
+ notebookArchiveHistoryMu.Lock()
+ defer notebookArchiveHistoryMu.Unlock()
+ return listNotebookArchiveCandidates()
+}
+
+func listNotebookArchiveCandidates() ([]NotebookArchiveCandidate, error) {
+ ids := map[string]bool{}
+ dirs, err := os.ReadDir(util.DataDir)
+ if err != nil {
+ return nil, err
+ }
+ for _, dir := range dirs {
+ if dir.IsDir() && ast.IsNodeIDPattern(dir.Name()) && IsEncryptedBox(dir.Name()) {
+ ids[dir.Name()] = true
+ }
+ }
+ histories, err := encryptedNotebookHistoryBoxDirs()
+ if err != nil {
+ return nil, err
+ }
+ for _, history := range histories {
+ id := filepath.Base(history)
+ if _, exists := ids[id]; !exists {
+ ids[id] = false
+ }
+ }
+ err = walkNotebookArchiveSnapshots(func(repo *dejavu.Repo, index *entity.Index, files []*entity.File) error {
+ for _, file := range files {
+ parts := strings.Split(strings.TrimPrefix(file.Path, "/"), "/")
+ if len(parts) != 3 || !ast.IsNodeIDPattern(parts[0]) || parts[1] != ".siyuan" {
+ continue
+ }
+ encrypted := parts[2] == notebookCryptoBackupFilename
+ if parts[2] == "conf.json" {
+ data, err := openRepoFileWithAssets(repo, file)
+ if err != nil {
+ return err
+ }
+ var boxConf conf.BoxConf
+ encrypted = json.Unmarshal(data, &boxConf) == nil && boxConf.Encrypted
+ }
+ if encrypted {
+ if _, exists := ids[parts[0]]; !exists {
+ ids[parts[0]] = false
+ }
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ ret := make([]NotebookArchiveCandidate, 0, len(ids))
+ for id, current := range ids {
+ ret = append(ret, NotebookArchiveCandidate{ID: id, Current: current})
+ }
+ sort.Slice(ret, func(i, j int) bool { return ret[i].ID < ret[j].ID })
+ return ret, nil
+}
+
+func walkNotebookArchiveSnapshots(visit func(*dejavu.Repo, *entity.Index, []*entity.File) error) error {
+ if util.RepoDir == "" {
+ return nil
+ }
+ entries, err := os.ReadDir(filepath.Join(util.RepoDir, "indexes"))
+ if os.IsNotExist(err) || err == nil && len(entries) == 0 {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if Conf.Repo == nil || len(Conf.Repo.Key) == 0 {
+ return ErrNotebookArchiveBusy
+ }
+ assetDownloadSourceMu.RLock()
+ defer assetDownloadSourceMu.RUnlock()
+ repo, err := newRepositoryWithAssetSourceLocked()
+ if err != nil {
+ return err
+ }
+ for _, entry := range entries {
+ if len(entry.Name()) != 40 {
+ continue
+ }
+ index, err := repo.GetIndex(entry.Name())
+ if err != nil {
+ return err
+ }
+ files, err := repo.GetFiles(index)
+ if err != nil {
+ return err
+ }
+ if err = visit(repo, index, files); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func notebookArchiveKeys() (map[string][]byte, error) {
+ keys := map[string][]byte{}
+ data, err := json.Marshal(currentNotebookCrypto())
+ if err != nil {
+ return nil, err
+ }
+ keys["keys/conf.json"] = data
+ data, err = os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))
+ if err == nil {
+ var persisted struct {
+ NotebookCrypto json.RawMessage `json:"notebookCrypto"`
+ }
+ if json.Unmarshal(data, &persisted) != nil {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ if len(persisted.NotebookCrypto) != 0 {
+ keys["keys/persisted-conf.json"] = persisted.NotebookCrypto
+ }
+ } else if !os.IsNotExist(err) {
+ return nil, err
+ }
+ for name, source := range map[string]string{"keys/backup.json": dataCryptoBackupPath(), "keys/migration.json": masterPasswordMigrationPath()} {
+ data, err = os.ReadFile(source)
+ if os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ return nil, err
+ }
+ keys[name] = data
+ }
+ return keys, nil
+}
+
+func notebookArchiveRoots(ids []string) ([]string, error) {
+ roots := []string{}
+ for _, id := range ids {
+ if !ast.IsNodeIDPattern(id) {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ if info, err := os.Lstat(filepath.Join(util.DataDir, id)); err == nil {
+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 || !IsEncryptedBox(id) {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ roots = append(roots, "data/"+id)
+ } else if !os.IsNotExist(err) {
+ return nil, err
+ }
+ }
+ histories, err := os.ReadDir(util.HistoryDir)
+ if os.IsNotExist(err) {
+ return roots, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ for _, history := range histories {
+ if !history.IsDir() {
+ continue
+ }
+ for _, id := range ids {
+ root := "history/" + history.Name() + "/" + id
+ source, err := archiveSourcePath(root)
+ if err != nil {
+ return nil, err
+ }
+ if info, statErr := os.Lstat(source); statErr == nil {
+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ roots = append(roots, root)
+ } else if !os.IsNotExist(statErr) {
+ return nil, statErr
+ }
+ }
+ }
+ sort.Strings(roots)
+ return roots, nil
+}
+
+// holdNotebookArchiveBoxes 与普通删除共享准入锁,只处理已经锁定的笔记本,避免为了归档生成新历史。
+func holdNotebookArchiveBoxes(ids []string) (func(), error) {
+ var releases []func()
+ release := func() {
+ for i := len(releases) - 1; i >= 0; i-- {
+ releases[i]()
+ }
+ }
+ for _, id := range ids {
+ if _, busy := boxLock.LoadOrStore(id, true); busy {
+ release()
+ return nil, ErrNotebookArchiveBusy
+ }
+ releases = append(releases, func() { boxLock.Delete(id) })
+ releases = append(releases, holdEncryptedBoxTransition(id))
+ if IsBoxUnlocked(id) {
+ release()
+ return nil, ErrNotebookArchiveBusy
+ }
+ }
+ return release, nil
+}
+
+func writeNotebookArchiveOperation(directory string, operation *notebookArchiveOperation) error {
+ data, err := json.Marshal(operation)
+ if err != nil {
+ return err
+ }
+ return atomicWriteFile(filepath.Join(directory, "operation.json"), data)
+}
+
+// PrepareNotebookArchive 先保存可独立读取的完整归档,下载取消时不改变任何源文件。
+func PrepareNotebookArchive(ids []string) (archiveID, downloadPath string, err error) {
+ notebookArchiveMu.Lock()
+ defer notebookArchiveMu.Unlock()
+ lockSync()
+ defer unlockSync()
+ notebookCryptoMu.Lock()
+ defer notebookCryptoMu.Unlock()
+ notebookArchiveHistoryMu.Lock()
+ defer notebookArchiveHistoryMu.Unlock()
+ if err = recoverNotebookArchiveOperations(); err != nil {
+ return
+ }
+ if len(ids) == 0 {
+ return "", "", ErrNotebookArchiveInvalid
+ }
+ ids = append([]string(nil), ids...)
+ sort.Strings(ids)
+ candidates, err := listNotebookArchiveCandidates()
+ if err != nil {
+ return
+ }
+ known := map[string]bool{}
+ for _, candidate := range candidates {
+ known[candidate.ID] = true
+ }
+ for i, id := range ids {
+ if !known[id] || i > 0 && ids[i-1] == id {
+ return "", "", ErrNotebookArchiveInvalid
+ }
+ }
+ release, err := holdNotebookArchiveBoxes(ids)
+ if err != nil {
+ return
+ }
+ defer release()
+ for _, id := range ids {
+ if err = EnsureAssetPrefixLocal(filepath.Join(util.DataDir, id)); err != nil {
+ return
+ }
+ }
+ roots, err := notebookArchiveRoots(ids)
+ if err != nil {
+ return
+ }
+ archiveID = ast.NewNodeID()
+ directory, _ := notebookArchiveDirectory(archiveID)
+ payload := filepath.Join(directory, "payload")
+ if err = os.MkdirAll(payload, 0700); err != nil {
+ return
+ }
+ for _, root := range roots {
+ source, _ := archiveSourcePath(root)
+ err = archiveWalk(source, func(name, fullPath string) error {
+ return archiveCopyFile(fullPath, filepath.Join(payload, filepath.FromSlash(root), filepath.FromSlash(name)))
+ })
+ if err != nil {
+ return
+ }
+ }
+ keys, err := notebookArchiveKeys()
+ if err != nil {
+ return
+ }
+ if err = os.MkdirAll(filepath.Join(payload, "keys"), 0700); err != nil {
+ return
+ }
+ for name, data := range keys {
+ if err = os.WriteFile(filepath.Join(payload, filepath.FromSlash(name)), data, 0600); err != nil {
+ return
+ }
+ }
+ err = collectNotebookArchiveSnapshots(payload, ids)
+ if err != nil {
+ return
+ }
+ manifest := &notebookArchiveManifest{Format: notebookArchiveFormat, Version: 1, ID: archiveID, Notebooks: ids, Roots: roots}
+ if err = writeNotebookArchive(directory, manifest); err != nil {
+ return
+ }
+ if _, err = readNotebookArchive(filepath.Join(directory, "archive.zip"), ""); err != nil {
+ return
+ }
+ if err = checkNotebookArchiveSources(manifest); err != nil {
+ return
+ }
+ if err = writeNotebookArchiveOperation(directory, &notebookArchiveOperation{State: "prepared", Roots: roots}); err != nil {
+ return
+ }
+ name := "encrypted-notebooks-" + archiveID + ".zip"
+ if err = archiveCopyFile(filepath.Join(directory, "archive.zip"), filepath.Join(util.TempDir, "export", name)); err != nil {
+ return
+ }
+ return archiveID, "/export/" + name, nil
+}
+
+func collectNotebookArchiveSnapshots(payload string, ids []string) error {
+ selected := map[string]bool{}
+ for _, id := range ids {
+ selected[id] = true
+ }
+ return walkNotebookArchiveSnapshots(func(repo *dejavu.Repo, index *entity.Index, files []*entity.File) error {
+ var selectedFiles []*entity.File
+ for _, file := range files {
+ name := strings.TrimPrefix(file.Path, "/")
+ parts := strings.Split(name, "/")
+ if len(parts) > 1 && selected[parts[0]] {
+ selectedFiles = append(selectedFiles, file)
+ }
+ }
+ if len(selectedFiles) == 0 {
+ return nil
+ }
+ for _, file := range files {
+ name := strings.TrimPrefix(file.Path, "/")
+ if name == ".siyuan/data-crypto-backup.json" || name == ".siyuan/master-password-migration.json" {
+ selectedFiles = append(selectedFiles, file)
+ }
+ }
+ for _, file := range selectedFiles {
+ name := strings.TrimPrefix(file.Path, "/")
+ if name == ".siyuan/data-crypto-backup.json" {
+ name = "keys/backup.json"
+ }
+ if name == ".siyuan/master-password-migration.json" {
+ name = "keys/migration.json"
+ }
+ if !archiveRelativePath(name) {
+ return ErrNotebookArchiveInvalid
+ }
+ data, err := openRepoFileWithAssets(repo, file)
+ if err != nil {
+ return err
+ }
+ destination := filepath.Join(payload, "snapshots", index.ID, filepath.FromSlash(name))
+ if err = os.MkdirAll(filepath.Dir(destination), 0700); err != nil {
+ return err
+ }
+ if err = os.WriteFile(destination, data, 0600); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
+func checkNotebookArchiveSources(manifest *notebookArchiveManifest) error {
+ roots, err := notebookArchiveRoots(manifest.Notebooks)
+ if err != nil {
+ return err
+ }
+ if !reflect.DeepEqual(roots, manifest.Roots) {
+ return ErrNotebookArchiveChanged
+ }
+ for _, root := range roots {
+ source, _ := archiveSourcePath(root)
+ files, err := archiveDirectoryFiles(source)
+ if err != nil {
+ return err
+ }
+ expected := map[string]notebookArchiveFile{}
+ for name, file := range manifest.Files {
+ if strings.HasPrefix(name, root+"/") {
+ expected[strings.TrimPrefix(name, root+"/")] = file
+ }
+ }
+ if !reflect.DeepEqual(files, expected) {
+ return ErrNotebookArchiveChanged
+ }
+ }
+ keys, err := notebookArchiveKeys()
+ if err != nil {
+ return err
+ }
+ for name, file := range manifest.Files {
+ if strings.HasPrefix(name, "keys/") {
+ actual, exists := keys[name]
+ fingerprint, _ := archiveFingerprint(bytes.NewReader(actual))
+ if !exists || fingerprint != file {
+ return ErrNotebookArchiveChanged
+ }
+ delete(keys, name)
+ }
+ }
+ if len(keys) != 0 {
+ return ErrNotebookArchiveChanged
+ }
+ return checkNotebookArchiveSnapshots(manifest)
+}
+
+func checkNotebookArchiveSnapshots(manifest *notebookArchiveManifest) error {
+ selected := map[string]bool{}
+ for _, id := range manifest.Notebooks {
+ selected[id] = true
+ }
+ return walkNotebookArchiveSnapshots(func(repo *dejavu.Repo, index *entity.Index, files []*entity.File) error {
+ for _, file := range files {
+ name := strings.TrimPrefix(file.Path, "/")
+ parts := strings.Split(name, "/")
+ if len(parts) < 2 || !selected[parts[0]] {
+ continue
+ }
+ expected, exists := manifest.Files["snapshots/"+index.ID+"/"+name]
+ if !exists {
+ return ErrNotebookArchiveChanged
+ }
+ data, err := openRepoFileWithAssets(repo, file)
+ if err != nil {
+ return err
+ }
+ actual, err := archiveFingerprint(bytes.NewReader(data))
+ if err != nil {
+ return err
+ }
+ if actual != expected {
+ return ErrNotebookArchiveChanged
+ }
+ }
+ return nil
+ })
+}
+
+// CommitNotebookArchive 将源目录移到归档旁的恢复目录,整个过程不调用会创建删除历史的普通删除接口。
+func CommitNotebookArchive(id string, saved bool) error {
+ if !saved {
+ return ErrNotebookArchiveInvalid
+ }
+ notebookArchiveMu.Lock()
+ defer notebookArchiveMu.Unlock()
+ lockSync()
+ defer unlockSync()
+ notebookCryptoMu.Lock()
+ defer notebookCryptoMu.Unlock()
+ notebookArchiveHistoryMu.Lock()
+ defer notebookArchiveHistoryMu.Unlock()
+ if err := recoverNotebookArchiveOperations(); err != nil {
+ return err
+ }
+ directory, err := notebookArchiveDirectory(id)
+ if err != nil {
+ return err
+ }
+ data, err := os.ReadFile(filepath.Join(directory, "operation.json"))
+ if err != nil {
+ return err
+ }
+ operation := &notebookArchiveOperation{}
+ if json.Unmarshal(data, operation) != nil || !operation.valid() {
+ return ErrNotebookArchiveInvalid
+ }
+ if operation.State == "committed" {
+ return nil
+ }
+ if operation.State != "prepared" {
+ return ErrNotebookArchiveBusy
+ }
+ manifest, err := readNotebookArchive(filepath.Join(directory, "archive.zip"), "")
+ if err != nil {
+ return err
+ }
+ if manifest.ID != id || !reflect.DeepEqual(operation.Roots, manifest.Roots) {
+ return ErrNotebookArchiveInvalid
+ }
+ release, err := holdNotebookArchiveBoxes(manifest.Notebooks)
+ if err != nil {
+ return err
+ }
+ defer release()
+ if err = checkNotebookArchiveSources(manifest); err != nil {
+ return err
+ }
+ operation.State = "committing"
+ if err = writeNotebookArchiveOperation(directory, operation); err != nil {
+ return err
+ }
+ for _, root := range operation.Roots {
+ source, _ := archiveSourcePath(root)
+ destination := filepath.Join(directory, "removed", filepath.FromSlash(root))
+ if err = os.MkdirAll(filepath.Dir(destination), 0700); err == nil {
+ err = os.Rename(source, destination)
+ }
+ if err != nil {
+ if rollbackErr := rollbackNotebookArchive(directory, operation); rollbackErr != nil {
+ return fmt.Errorf("%w: %v; %v", ErrNotebookArchiveBusy, err, rollbackErr)
+ }
+ return err
+ }
+ }
+ operation.State = "committed"
+ if err = writeNotebookArchiveOperation(directory, operation); err != nil {
+ operation.State = "committing"
+ _ = rollbackNotebookArchive(directory, operation)
+ return err
+ }
+ for _, boxID := range manifest.Notebooks {
+ removeHPathRefreshBox(boxID)
+ maintainPinnedDocs(nil, boxID, "")
+ ClearRichClipboardBox(boxID)
+ RevokeManagedEncryptedExportsForBox(boxID)
+ sql.RemoveEncryptedDBFile(boxID)
+ treenode.RemoveEncryptedBlockTreeDBFile(boxID)
+ forgetRuntimeEncryptedBox(boxID)
+ removeEncryptedBoxLifecycle(boxID)
+ evt := util.NewCmdResult("removeBox", 0, util.PushModeBroadcast)
+ evt.Data = map[string]string{"box": boxID}
+ util.PushEvent(evt)
+ }
+ IncSync()
+ ReindexHistory()
+ return nil
+}
+
+func rollbackNotebookArchive(directory string, operation *notebookArchiveOperation) error {
+ for i := len(operation.Roots) - 1; i >= 0; i-- {
+ root := operation.Roots[i]
+ source, err := archiveSourcePath(root)
+ if err != nil {
+ return err
+ }
+ removed := filepath.Join(directory, "removed", filepath.FromSlash(root))
+ if _, err = os.Lstat(removed); os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ if _, err = os.Lstat(source); !os.IsNotExist(err) {
+ return ErrNotebookArchiveBusy
+ }
+ if err = os.MkdirAll(filepath.Dir(source), 0700); err != nil {
+ return err
+ }
+ if err = os.Rename(removed, source); err != nil {
+ return err
+ }
+ }
+ operation.State = "prepared"
+ return writeNotebookArchiveOperation(directory, operation)
+}
+
+// recoverNotebookArchiveOperations 在启动挂载和同步之前回滚未提交的移动,保留全部原始文件。
+func recoverNotebookArchiveOperations() error {
+ entries, err := os.ReadDir(notebookArchiveBase())
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ for _, entry := range entries {
+ if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {
+ continue
+ }
+ directory, _ := notebookArchiveDirectory(entry.Name())
+ data, err := os.ReadFile(filepath.Join(directory, "operation.json"))
+ if os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ operation := &notebookArchiveOperation{}
+ if json.Unmarshal(data, operation) != nil || !operation.valid() {
+ return ErrNotebookArchiveInvalid
+ }
+ if operation.State == "committing" {
+ if err = rollbackNotebookArchive(directory, operation); err != nil {
+ logging.LogErrorf("recover encrypted notebook archive [%s] failed: %s", entry.Name(), err)
+ return err
+ }
+ }
+ if operation.State == "importing" {
+ if err = rollbackNotebookArchiveImport(directory, operation); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func checkPendingNotebookArchives() error {
+ entries, err := os.ReadDir(notebookArchiveBase())
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ for _, entry := range entries {
+ if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {
+ continue
+ }
+ data, err := os.ReadFile(filepath.Join(notebookArchiveBase(), entry.Name(), "operation.json"))
+ if os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ var operation notebookArchiveOperation
+ if json.Unmarshal(data, &operation) != nil || !operation.valid() || operation.State == "committing" || operation.State == "importing" {
+ return ErrNotebookArchiveBusy
+ }
+ }
+ return nil
+}
+
+// preserveNotebookCryptoBeforeDisable 确认本地快照已有完整离线归档,另存旧配置后才允许结束旧密钥域。
+func preserveNotebookCryptoBeforeDisable() error {
+ covered := map[string]notebookArchiveFile{}
+ keys, err := notebookArchiveKeys()
+ if err != nil {
+ return err
+ }
+ entries, err := os.ReadDir(notebookArchiveBase())
+ if err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ for _, entry := range entries {
+ if !entry.IsDir() || !ast.IsNodeIDPattern(entry.Name()) {
+ continue
+ }
+ directory, _ := notebookArchiveDirectory(entry.Name())
+ data, readErr := os.ReadFile(filepath.Join(directory, "operation.json"))
+ if os.IsNotExist(readErr) {
+ continue
+ }
+ if readErr != nil {
+ return readErr
+ }
+ var operation notebookArchiveOperation
+ if json.Unmarshal(data, &operation) != nil || !operation.valid() {
+ return ErrNotebookArchiveInvalid
+ }
+ if operation.State != "committed" {
+ continue
+ }
+ manifest, readErr := readNotebookArchive(filepath.Join(directory, "archive.zip"), "")
+ if readErr != nil {
+ return readErr
+ }
+ // 已提交归档保留其生成时的密钥;之后重新启用或改密不影响这些旧快照的归档覆盖。
+ for name, fingerprint := range manifest.Files {
+ covered[name] = fingerprint
+ }
+ }
+ err = walkNotebookArchiveSnapshots(func(repo *dejavu.Repo, index *entity.Index, files []*entity.File) error {
+ encrypted := map[string]bool{}
+ for _, file := range files {
+ name := strings.TrimPrefix(file.Path, "/")
+ parts := strings.Split(name, "/")
+ if len(parts) != 3 || !ast.IsNodeIDPattern(parts[0]) || parts[1] != ".siyuan" {
+ continue
+ }
+ if parts[2] == notebookCryptoBackupFilename {
+ encrypted[parts[0]] = true
+ }
+ if parts[2] == "conf.json" {
+ data, readErr := openRepoFileWithAssets(repo, file)
+ if readErr != nil {
+ return readErr
+ }
+ var boxConf conf.BoxConf
+ if json.Unmarshal(data, &boxConf) == nil && boxConf.Encrypted {
+ encrypted[parts[0]] = true
+ }
+ }
+ }
+ for _, file := range files {
+ name := strings.TrimPrefix(file.Path, "/")
+ if !encrypted[strings.Split(name, "/")[0]] {
+ continue
+ }
+ expected, exists := covered["snapshots/"+index.ID+"/"+name]
+ if !exists {
+ return ErrNotebookArchiveChanged
+ }
+ data, readErr := openRepoFileWithAssets(repo, file)
+ if readErr != nil {
+ return readErr
+ }
+ actual, _ := archiveFingerprint(bytes.NewReader(data))
+ if actual != expected {
+ return ErrNotebookArchiveChanged
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ directory, _ := notebookArchiveDirectory(ast.NewNodeID())
+ if err = os.MkdirAll(filepath.Join(directory, "keys"), 0700); err != nil {
+ return err
+ }
+ for name, data := range keys {
+ if err = atomicWriteFile(filepath.Join(directory, filepath.FromSlash(name)), data); err != nil {
+ return err
+ }
+ }
+ // 全部现存笔记本和历史已经移出;中断改密的原始恢复记录保存在上面的版本化密钥目录中。
+ if _, exists := keys["keys/migration.json"]; exists {
+ if err = os.Remove(masterPasswordMigrationPath()); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/kernel/model/notebook_archive_file.go b/kernel/model/notebook_archive_file.go
new file mode 100644
index 0000000000..0b662bcf10
--- /dev/null
+++ b/kernel/model/notebook_archive_file.go
@@ -0,0 +1,334 @@
+package model
+
+import (
+ "archive/zip"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var (
+ ErrNotebookArchiveInvalid = errors.New("invalid encrypted notebook archive")
+ ErrNotebookArchiveChanged = errors.New("encrypted notebook archive sources changed")
+ ErrNotebookArchiveBusy = errors.New("encrypted notebook archive operation is busy")
+ ErrNotebookArchiveConfigured = errors.New("encrypted notebook recovery requires an unconfigured workspace")
+ ErrNotebookArchiveAuthentication = errors.New("encrypted notebook archive authentication failed")
+)
+
+const notebookArchiveFormat = "siyuan-encrypted-notebooks"
+const notebookArchiveMaxEntries = 1000000
+const notebookArchiveMaxManifestSize = 128 * 1024 * 1024
+
+type notebookArchiveFile struct {
+ Size int64 `json:"size"`
+ SHA256 string `json:"sha256"`
+}
+
+// notebookArchiveManifest 仅封装原始密文,不改变密文、AAD、文件名或密钥包络的既有格式。
+type notebookArchiveManifest struct {
+ Format string `json:"format"`
+ Version int `json:"version"`
+ ID string `json:"id"`
+ Notebooks []string `json:"notebooks"`
+ Roots []string `json:"roots"`
+ Files map[string]notebookArchiveFile `json:"files"`
+}
+
+func notebookArchiveBase() string {
+ return filepath.Join(util.ConfDir, "notebook-archives")
+}
+
+func notebookArchiveDirectory(id string) (string, error) {
+ if !ast.IsNodeIDPattern(id) {
+ return "", ErrNotebookArchiveInvalid
+ }
+ return filepath.Join(notebookArchiveBase(), id), nil
+}
+
+// archiveRelativePath 拒绝跨平台路径歧义、目录穿越和符号链接目标,不把归档路径当作任意磁盘路径。
+func archiveRelativePath(name string) bool {
+ if name == "" || path.Clean(name) != name || strings.HasPrefix(name, "/") || strings.ContainsAny(name, "\\:\x00<>\"|?*") {
+ return false
+ }
+ for _, part := range strings.Split(name, "/") {
+ base := strings.ToUpper(strings.SplitN(part, ".", 2)[0])
+ reserved := base == "CON" || base == "PRN" || base == "AUX" || base == "NUL" ||
+ (len(base) == 4 && (strings.HasPrefix(base, "COM") || strings.HasPrefix(base, "LPT")) && base[3] >= '1' && base[3] <= '9')
+ if part == "." || part == ".." || strings.TrimRight(part, ". ") != part || reserved {
+ return false
+ }
+ }
+ return true
+}
+
+func archiveSourcePath(root string) (string, error) {
+ if !archiveRelativePath(root) {
+ return "", ErrNotebookArchiveInvalid
+ }
+ parts := strings.Split(root, "/")
+ if len(parts) == 2 && parts[0] == "data" && ast.IsNodeIDPattern(parts[1]) {
+ return filepath.Join(util.DataDir, parts[1]), nil
+ }
+ if len(parts) == 3 && parts[0] == "history" && ast.IsNodeIDPattern(parts[2]) {
+ return filepath.Join(util.HistoryDir, parts[1], parts[2]), nil
+ }
+ return "", ErrNotebookArchiveInvalid
+}
+
+func archiveFingerprint(reader io.Reader) (notebookArchiveFile, error) {
+ hash := sha256.New()
+ size, err := io.Copy(hash, reader)
+ return notebookArchiveFile{Size: size, SHA256: hex.EncodeToString(hash.Sum(nil))}, err
+}
+
+func archiveCopyFile(source, destination string) error {
+ info, err := os.Lstat(source)
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() {
+ return ErrNotebookArchiveInvalid
+ }
+ if err = os.MkdirAll(filepath.Dir(destination), 0700); err != nil {
+ return err
+ }
+ input, err := os.Open(source)
+ if err != nil {
+ return err
+ }
+ defer input.Close()
+ output, err := os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ return err
+ }
+ _, copyErr := io.Copy(output, input)
+ if copyErr == nil {
+ copyErr = output.Sync()
+ }
+ closeErr := output.Close()
+ if copyErr != nil {
+ return copyErr
+ }
+ return closeErr
+}
+
+func archiveWalk(root string, visit func(string, string) error) error {
+ return filepath.WalkDir(root, func(fullPath string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if entry.Type()&os.ModeSymlink != 0 {
+ return ErrNotebookArchiveInvalid
+ }
+ if entry.IsDir() {
+ return nil
+ }
+ if !entry.Type().IsRegular() {
+ return ErrNotebookArchiveInvalid
+ }
+ rel, err := filepath.Rel(root, fullPath)
+ if err != nil || !archiveRelativePath(filepath.ToSlash(rel)) {
+ return ErrNotebookArchiveInvalid
+ }
+ return visit(filepath.ToSlash(rel), fullPath)
+ })
+}
+
+func archiveDirectoryFiles(root string) (map[string]notebookArchiveFile, error) {
+ files := map[string]notebookArchiveFile{}
+ err := archiveWalk(root, func(name, fullPath string) error {
+ file, err := os.Open(fullPath)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ fingerprint, err := archiveFingerprint(file)
+ files[name] = fingerprint
+ return err
+ })
+ return files, err
+}
+
+func writeNotebookArchive(directory string, manifest *notebookArchiveManifest) error {
+ payload := filepath.Join(directory, "payload")
+ var err error
+ manifest.Files, err = archiveDirectoryFiles(payload)
+ if err != nil {
+ return err
+ }
+ if len(manifest.Files) > notebookArchiveMaxEntries {
+ return ErrNotebookArchiveInvalid
+ }
+ data, err := json.Marshal(manifest)
+ if err != nil || len(data) > notebookArchiveMaxManifestSize {
+ return ErrNotebookArchiveInvalid
+ }
+ file, err := os.OpenFile(filepath.Join(directory, "archive.zip"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ writer := zip.NewWriter(file)
+ entry, err := writer.Create("manifest.json")
+ if err != nil {
+ return err
+ }
+ if _, err = entry.Write(data); err != nil {
+ return err
+ }
+ names := make([]string, 0, len(manifest.Files))
+ for name := range manifest.Files {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ for _, name := range names {
+ entry, err = writer.Create(name)
+ if err != nil {
+ return err
+ }
+ input, openErr := os.Open(filepath.Join(payload, filepath.FromSlash(name)))
+ if openErr != nil {
+ return openErr
+ }
+ _, err = io.Copy(entry, input)
+ input.Close()
+ if err != nil {
+ return err
+ }
+ }
+ if err = writer.Close(); err != nil {
+ return err
+ }
+ return file.Sync()
+}
+
+// readNotebookArchive 完整校验清单与所有条目,再向独立暂存目录写入;摘要只证明复制完整性。
+func readNotebookArchive(archivePath, destination string) (*notebookArchiveManifest, error) {
+ reader, err := zip.OpenReader(archivePath)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrNotebookArchiveInvalid, err)
+ }
+ defer reader.Close()
+ if len(reader.File) > notebookArchiveMaxEntries+1 {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ entries := map[string]*zip.File{}
+ caseNames := map[string]bool{}
+ for _, file := range reader.File {
+ if !archiveRelativePath(file.Name) || !file.Mode().IsRegular() || caseNames[strings.ToLower(file.Name)] {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ entries[file.Name] = file
+ caseNames[strings.ToLower(file.Name)] = true
+ }
+ metadata := entries["manifest.json"]
+ if metadata == nil || metadata.UncompressedSize64 > notebookArchiveMaxManifestSize {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ input, err := metadata.Open()
+ if err != nil {
+ return nil, err
+ }
+ data, readErr := io.ReadAll(io.LimitReader(input, notebookArchiveMaxManifestSize+1))
+ input.Close()
+ manifest := &notebookArchiveManifest{}
+ if readErr != nil || json.Unmarshal(data, manifest) != nil || validateNotebookArchiveManifest(manifest) != nil || len(entries) != len(manifest.Files)+1 {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ for name, expected := range manifest.Files {
+ file := entries[name]
+ if file == nil || expected.Size < 0 || uint64(expected.Size) != file.UncompressedSize64 {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ input, err = file.Open()
+ if err != nil {
+ return nil, err
+ }
+ var output *os.File
+ var target io.Writer = io.Discard
+ if destination != "" {
+ fullPath := filepath.Join(destination, filepath.FromSlash(name))
+ if err = os.MkdirAll(filepath.Dir(fullPath), 0700); err == nil {
+ output, err = os.OpenFile(fullPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ }
+ if err != nil {
+ input.Close()
+ return nil, err
+ }
+ target = output
+ }
+ actual, copyErr := archiveFingerprint(io.TeeReader(io.LimitReader(input, expected.Size+1), target))
+ closeErr := input.Close()
+ if output != nil {
+ if syncErr := output.Sync(); copyErr == nil {
+ copyErr = syncErr
+ }
+ if outputErr := output.Close(); copyErr == nil {
+ copyErr = outputErr
+ }
+ }
+ if copyErr != nil || closeErr != nil || actual != expected {
+ return nil, ErrNotebookArchiveInvalid
+ }
+ }
+ return manifest, nil
+}
+
+func validateNotebookArchiveManifest(manifest *notebookArchiveManifest) error {
+ if manifest.Format != notebookArchiveFormat || manifest.Version != 1 || !ast.IsNodeIDPattern(manifest.ID) || len(manifest.Notebooks) == 0 || len(manifest.Files) == 0 {
+ return ErrNotebookArchiveInvalid
+ }
+ ids := map[string]bool{}
+ for _, id := range manifest.Notebooks {
+ if !ast.IsNodeIDPattern(id) || ids[id] {
+ return ErrNotebookArchiveInvalid
+ }
+ ids[id] = true
+ }
+ roots := map[string]bool{}
+ covered := map[string]bool{}
+ for _, root := range manifest.Roots {
+ if _, err := archiveSourcePath(root); err != nil || roots[root] || !ids[path.Base(root)] {
+ return ErrNotebookArchiveInvalid
+ }
+ roots[root] = true
+ covered[path.Base(root)] = true
+ }
+ for name, file := range manifest.Files {
+ if !archiveRelativePath(name) || file.Size < 0 || len(file.SHA256) != 64 {
+ return ErrNotebookArchiveInvalid
+ }
+ valid := name == "keys/conf.json" || name == "keys/persisted-conf.json" || name == "keys/backup.json" || name == "keys/migration.json"
+ for root := range roots {
+ valid = valid || strings.HasPrefix(name, root+"/")
+ }
+ parts := strings.Split(name, "/")
+ if len(parts) >= 4 && parts[0] == "snapshots" && len(parts[1]) == 40 {
+ valid = ids[parts[2]] || (parts[2] == "keys" && len(parts) == 4 && (parts[3] == "backup.json" || parts[3] == "migration.json"))
+ if ids[parts[2]] {
+ covered[parts[2]] = true
+ }
+ }
+ if !valid {
+ return ErrNotebookArchiveInvalid
+ }
+ }
+ for id := range ids {
+ if !covered[id] {
+ return ErrNotebookArchiveInvalid
+ }
+ }
+ return nil
+}
diff --git a/kernel/model/notebook_archive_import.go b/kernel/model/notebook_archive_import.go
new file mode 100644
index 0000000000..f45476bdb2
--- /dev/null
+++ b/kernel/model/notebook_archive_import.go
@@ -0,0 +1,424 @@
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "path"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func checkNotebookArchiveImportTarget() error {
+ if NotebookCryptoLifecycleState(false) != NotebookCryptoStateDisabled {
+ return ErrNotebookArchiveConfigured
+ }
+ for _, name := range []string{dataCryptoBackupPath(), masterPasswordMigrationPath()} {
+ if _, err := os.Lstat(name); !os.IsNotExist(err) {
+ return ErrNotebookArchiveConfigured
+ }
+ }
+ ids, err := listAllEncryptedBoxIDs()
+ if err != nil {
+ return err
+ }
+ history, err := scanEncryptedNotebookHistory()
+ if err != nil {
+ return err
+ }
+ if len(ids) != 0 || history || Conf.Sync != nil && Conf.Sync.Enabled {
+ return ErrNotebookArchiveConfigured
+ }
+ candidates, err := listNotebookArchiveCandidates()
+ if err != nil {
+ return err
+ }
+ if len(candidates) != 0 {
+ return ErrNotebookArchiveConfigured
+ }
+ return nil
+}
+
+// ImportNotebookArchive 在独立暂存区认证恢复材料,所有校验成功后才把密文放入未配置密钥的工作区。
+func ImportNotebookArchive(archivePath, password string, keyData []byte) error {
+ notebookArchiveMu.Lock()
+ defer notebookArchiveMu.Unlock()
+ lockSync()
+ defer unlockSync()
+ notebookCryptoMu.Lock()
+ defer notebookCryptoMu.Unlock()
+ notebookArchiveHistoryMu.Lock()
+ defer notebookArchiveHistoryMu.Unlock()
+ if err := recoverNotebookArchiveOperations(); err != nil {
+ return err
+ }
+ if err := checkNotebookArchiveImportTarget(); err != nil {
+ return err
+ }
+ if password == "" {
+ return ErrNotebookArchiveAuthentication
+ }
+ directory, _ := notebookArchiveDirectory(ast.NewNodeID())
+ if err := os.MkdirAll(directory, 0700); err != nil {
+ return err
+ }
+ // 上传原件始终保留在独立恢复目录中,失败时不修改或删除用户提供的归档。
+ if err := archiveCopyFile(archivePath, filepath.Join(directory, "archive.zip")); err != nil {
+ return err
+ }
+ payload := filepath.Join(directory, "payload")
+ manifest, err := readNotebookArchive(filepath.Join(directory, "archive.zip"), payload)
+ if err != nil {
+ return err
+ }
+ nc, kek, err := authenticateNotebookArchive(payload, manifest, password, keyData)
+ if err != nil {
+ return err
+ }
+ defer zeroAndClear(kek)
+ install := filepath.Join(directory, "install")
+ roots, err := stageNotebookArchiveImport(payload, install, manifest)
+ if err != nil {
+ return err
+ }
+ for _, root := range roots {
+ destination, err := archiveSourcePath(root)
+ if err != nil {
+ return err
+ }
+ if _, err = os.Lstat(destination); !os.IsNotExist(err) {
+ return ErrNotebookArchiveConfigured
+ }
+ }
+ // 密钥备份与密文目录共同登记。重启时回滚尚未提交的导入,不挂载部分恢复的数据。
+ nc.Enabled = true
+ nc.AutoLockMinutes = currentNotebookCrypto().AutoLockMinutes
+ prepareBackupForWrite(nc)
+ nc.KEKMAC = computeKEKMAC(nc, kek)
+ backup, err := json.Marshal(nc)
+ if err != nil {
+ return err
+ }
+ if err = os.WriteFile(filepath.Join(directory, "import-key.json"), backup, 0600); err != nil {
+ return err
+ }
+ operation := &notebookArchiveOperation{State: "importing", Roots: roots}
+ if err = writeNotebookArchiveOperation(directory, operation); err != nil {
+ return err
+ }
+ for _, root := range roots {
+ destination, _ := archiveSourcePath(root)
+ if err = os.MkdirAll(filepath.Dir(destination), 0700); err == nil {
+ err = os.Rename(filepath.Join(install, filepath.FromSlash(root)), destination)
+ }
+ if err != nil {
+ if rollbackErr := rollbackNotebookArchiveImport(directory, operation); rollbackErr != nil {
+ return fmt.Errorf("%w: %v; %v", ErrNotebookArchiveBusy, err, rollbackErr)
+ }
+ return err
+ }
+ }
+ if err = os.MkdirAll(filepath.Dir(dataCryptoBackupPath()), 0700); err == nil {
+ err = atomicWriteFile(dataCryptoBackupPath(), backup)
+ }
+ if err != nil {
+ _ = rollbackNotebookArchiveImport(directory, operation)
+ return err
+ }
+ operation.State = "imported"
+ if err = writeNotebookArchiveOperation(directory, operation); err != nil {
+ operation.State = "importing"
+ _ = rollbackNotebookArchiveImport(directory, operation)
+ return err
+ }
+ Conf.m.Lock()
+ Conf.NotebookCrypto = nc
+ Conf.m.Unlock()
+ Conf.Save()
+ for _, root := range roots {
+ if strings.HasPrefix(root, "data/") {
+ id := path.Base(root)
+ forgetRuntimeNormalBox(id)
+ markRuntimeEncryptedBox(id)
+ }
+ }
+ IncSync()
+ ReindexHistory()
+ return nil
+}
+
+func authenticateNotebookArchive(payload string, manifest *notebookArchiveManifest, password string, keyData []byte) (*conf.NotebookCrypto, []byte, error) {
+ candidates := [][]byte{}
+ if len(keyData) != 0 {
+ candidates = append(candidates, keyData)
+ }
+ for _, name := range []string{"keys/conf.json", "keys/persisted-conf.json", "keys/backup.json"} {
+ if data, err := os.ReadFile(filepath.Join(payload, filepath.FromSlash(name))); err == nil {
+ candidates = append(candidates, data)
+ }
+ }
+ var snapshotKeys []string
+ for name := range manifest.Files {
+ if strings.HasPrefix(name, "snapshots/") && strings.HasSuffix(name, "/keys/backup.json") {
+ snapshotKeys = append(snapshotKeys, name)
+ }
+ }
+ sort.Strings(snapshotKeys)
+ for _, name := range snapshotKeys {
+ if data, err := os.ReadFile(filepath.Join(payload, filepath.FromSlash(name))); err == nil {
+ candidates = append(candidates, data)
+ }
+ }
+ seen := map[string]bool{}
+ for _, data := range candidates {
+ if seen[string(data)] {
+ continue
+ }
+ seen[string(data)] = true
+ nc := &conf.NotebookCrypto{}
+ if json.Unmarshal(data, nc) != nil || !notebookCryptoConfigurationComplete(nc) {
+ continue
+ }
+ params, err := util.ValidateArgon2Params(nc.KDFParams)
+ if err != nil {
+ continue
+ }
+ kek := util.DeriveKey(password, nc.MasterSalt, params)
+ verifier, err := util.DecryptWithAAD(kek, nc.KEKVerifier, []byte("siyuan:kek-verifier"))
+ if err != nil || !bytes.Equal(verifier, kekVerifierMagic) || !verifyKEKMAC(nc, kek) {
+ zeroAndClear(kek)
+ continue
+ }
+ keys, err := decryptHistoryKEKs(kek, nc.HistoryKEKs)
+ clearHistoryKEKs(keys)
+ if err == nil {
+ err = authenticateNotebookArchivePayload(payload, manifest, nc, kek)
+ }
+ if err == nil {
+ return nc, kek, nil
+ }
+ zeroAndClear(kek)
+ }
+ return nil, nil, ErrNotebookArchiveAuthentication
+}
+
+func notebookArchiveBoxRoots(manifest *notebookArchiveManifest) []string {
+ roots := append([]string(nil), manifest.Roots...)
+ seen := map[string]bool{}
+ for name := range manifest.Files {
+ parts := strings.Split(name, "/")
+ if len(parts) >= 4 && parts[0] == "snapshots" && ast.IsNodeIDPattern(parts[2]) {
+ root := strings.Join(parts[:3], "/")
+ if !seen[root] {
+ roots = append(roots, root)
+ seen[root] = true
+ }
+ }
+ }
+ sort.Strings(roots)
+ return roots
+}
+
+func authenticateNotebookArchivePayload(payload string, manifest *notebookArchiveManifest, nc *conf.NotebookCrypto, kek []byte) error {
+ roots := notebookArchiveBoxRoots(manifest)
+ identities := map[string][]*conf.BoxEncryption{}
+ rootIdentities := map[string][]*conf.BoxEncryption{}
+ for _, root := range roots {
+ boxDir := filepath.Join(payload, filepath.FromSlash(root))
+ // 普通文档和资源历史只存密文,密钥包络保存在现存笔记本、删除历史或仓库快照中。
+ hasIdentity := false
+ for _, name := range []string{"conf.json", notebookCryptoBackupFilename} {
+ if _, err := os.Stat(filepath.Join(boxDir, ".siyuan", name)); err == nil {
+ hasIdentity = true
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+ }
+ if !hasIdentity && strings.HasPrefix(root, "history/") {
+ continue
+ }
+ candidates, err := readEncryptedHistoryBoxEncryptionCandidates(boxDir)
+ if err != nil {
+ return err
+ }
+ rootIdentities[root] = candidates
+ identities[path.Base(root)] = append(identities[path.Base(root)], candidates...)
+ }
+ for _, root := range roots {
+ boxID := path.Base(root)
+ boxDir := filepath.Join(payload, filepath.FromSlash(root))
+ candidates := rootIdentities[root]
+ if len(candidates) == 0 {
+ candidates = identities[boxID]
+ }
+ authenticated := false
+ for _, candidate := range candidates {
+ dek, err := decryptWrappedDEKWithHistory(boxID, candidate, kek, nc)
+ if err == nil {
+ err = authenticateNotebookArchiveBox(boxDir, boxID, dek, candidate)
+ }
+ zeroAndClear(dek)
+ if err == nil {
+ authenticated = true
+ break
+ }
+ }
+ if !authenticated {
+ return ErrNotebookArchiveAuthentication
+ }
+ }
+ return nil
+}
+
+func authenticateNotebookArchiveBox(boxDir, boxID string, dek []byte, encryption *conf.BoxEncryption) error {
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted, boxConf.BoxCrypt = true, encryption
+ if err := decryptBoxMetadata(boxID, boxConf, dek); err != nil {
+ return err
+ }
+ documentIDs := map[string]bool{}
+ return archiveWalk(boxDir, func(name, fullPath string) error {
+ if strings.HasPrefix(name, "assets/") {
+ input, err := os.Open(fullPath)
+ if err != nil {
+ return err
+ }
+ defer input.Close()
+ _, err = DecryptAssetToWriter(boxID, path.Base(name), dek, input, io.Discard)
+ return err
+ }
+ isDoc := strings.HasSuffix(name, ".sy")
+ isAV := strings.HasPrefix(name, "storage/av/") && strings.HasSuffix(name, ".json")
+ if !isDoc && !isAV {
+ return nil
+ }
+ data, err := os.ReadFile(fullPath)
+ if err != nil {
+ return err
+ }
+ purpose, aad := "siyuan/file", ""
+ if isDoc {
+ aad, err = filesys.SyAAD(boxID, name)
+ if err != nil {
+ return err
+ }
+ } else {
+ purpose = "siyuan/av"
+ avID := strings.TrimSuffix(path.Base(name), ".json")
+ aad = "siyuan:av:" + boxID + ":" + avID
+ if avID == "mirror" || avID == "relation" {
+ aad = "siyuan:av-" + avID + ":" + boxID
+ }
+ }
+ key := util.DeriveSubKey(dek, purpose)
+ defer zeroAndClear(key)
+ plain, err := util.DecryptWithAAD(key, data, []byte(aad))
+ defer zeroAndClear(plain)
+ if err != nil {
+ return err
+ }
+ if isDoc {
+ tree, parseErr := loadTreeByData0(plain)
+ if parseErr != nil || tree == nil || tree.Root == nil || tree.Root.ID+".sy" != path.Base(name) || documentIDs[tree.Root.ID] {
+ return ErrNotebookArchiveInvalid
+ }
+ documentIDs[tree.Root.ID] = true
+ } else if !json.Valid(plain) {
+ return ErrNotebookArchiveInvalid
+ } else if avID := strings.TrimSuffix(path.Base(name), ".json"); avID != "mirror" && avID != "relation" {
+ definition, parseErr := av.ParseAttributeViewData(avID, plain)
+ if parseErr != nil || definition.ID != avID {
+ return ErrNotebookArchiveInvalid
+ }
+ }
+ return nil
+ })
+}
+
+// stageNotebookArchiveImport 将仓库快照转换为独立的笔记本删除历史,原归档仍保留原快照标识和路径。
+func stageNotebookArchiveImport(payload, install string, manifest *notebookArchiveManifest) ([]string, error) {
+ roots := []string{}
+ used := map[string]bool{}
+ for _, root := range manifest.Roots {
+ used[root] = true
+ }
+ nextTime := time.Now()
+ for _, root := range notebookArchiveBoxRoots(manifest) {
+ destinationRoot := root
+ if strings.HasPrefix(root, "snapshots/") {
+ for {
+ destinationRoot = "history/" + nextTime.Format("2006-01-02-150405") + "-delete/" + path.Base(root)
+ nextTime = nextTime.Add(-time.Second)
+ if !used[destinationRoot] {
+ break
+ }
+ }
+ }
+ used[destinationRoot] = true
+ source := filepath.Join(payload, filepath.FromSlash(root))
+ destination := filepath.Join(install, filepath.FromSlash(destinationRoot))
+ if err := os.MkdirAll(destination, 0700); err != nil {
+ return nil, err
+ }
+ if err := archiveWalk(source, func(name, fullPath string) error {
+ return archiveCopyFile(fullPath, filepath.Join(destination, filepath.FromSlash(name)))
+ }); err != nil {
+ return nil, err
+ }
+ roots = append(roots, destinationRoot)
+ }
+ return roots, nil
+}
+
+func rollbackNotebookArchiveImport(directory string, operation *notebookArchiveOperation) error {
+ for i := len(operation.Roots) - 1; i >= 0; i-- {
+ root := operation.Roots[i]
+ destination, err := archiveSourcePath(root)
+ if err != nil {
+ return err
+ }
+ staged := filepath.Join(directory, "install", filepath.FromSlash(root))
+ if _, err = os.Lstat(staged); err == nil {
+ continue
+ }
+ if !os.IsNotExist(err) {
+ return err
+ }
+ if _, err = os.Lstat(destination); os.IsNotExist(err) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ if err = os.MkdirAll(filepath.Dir(staged), 0700); err != nil {
+ return err
+ }
+ if err = os.Rename(destination, staged); err != nil {
+ return err
+ }
+ }
+ backup, err := os.ReadFile(dataCryptoBackupPath())
+ if err == nil {
+ expected, readErr := os.ReadFile(filepath.Join(directory, "import-key.json"))
+ if readErr != nil || !bytes.Equal(backup, expected) {
+ return ErrNotebookArchiveBusy
+ }
+ if err = os.Remove(dataCryptoBackupPath()); err != nil {
+ return err
+ }
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+ operation.State = "import-failed"
+ return writeNotebookArchiveOperation(directory, operation)
+}
diff --git a/kernel/model/notebook_archive_test.go b/kernel/model/notebook_archive_test.go
new file mode 100644
index 0000000000..4cf42f55bd
--- /dev/null
+++ b/kernel/model/notebook_archive_test.go
@@ -0,0 +1,645 @@
+package model
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func notebookArchiveTestWorkspace(t *testing.T) {
+ t.Helper()
+ oldConf := Conf
+ oldWorkspace, oldData, oldHistory, oldConfig, oldTemp, oldRepo := util.WorkspaceDir, util.DataDir, util.HistoryDir, util.ConfDir, util.TempDir, util.RepoDir
+ t.Cleanup(func() {
+ Conf = oldConf
+ util.WorkspaceDir, util.DataDir, util.HistoryDir, util.ConfDir, util.TempDir, util.RepoDir = oldWorkspace, oldData, oldHistory, oldConfig, oldTemp, oldRepo
+ })
+ root := t.TempDir()
+ util.WorkspaceDir = root
+ util.DataDir, util.HistoryDir, util.ConfDir, util.TempDir, util.RepoDir = filepath.Join(root, "data"), filepath.Join(root, "history"), filepath.Join(root, "conf"), filepath.Join(root, "temp"), filepath.Join(root, "repo")
+ for _, dir := range []string{util.DataDir, util.HistoryDir, util.ConfDir, util.TempDir} {
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ Conf = NewAppConf()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ Conf.Sync.Enabled = false
+}
+
+func notebookArchiveTestBox(t *testing.T, boxID string, kek []byte) []byte {
+ t.Helper()
+ crypt, dek, err := WrapNewDEK(boxID, kek)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(dek)
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted, boxConf.Closed, boxConf.BoxCrypt = true, true, crypt
+ if err = encryptBoxMetadata(boxID, boxConf, dek); err != nil {
+ t.Fatal(err)
+ }
+ directory := filepath.Join(util.DataDir, boxID)
+ if err = os.MkdirAll(filepath.Join(directory, ".siyuan"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ for name, value := range map[string]interface{}{"conf.json": boxConf, notebookCryptoBackupFilename: crypt} {
+ data, _ := json.Marshal(value)
+ if err = os.WriteFile(filepath.Join(directory, ".siyuan", name), data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fileKey := util.DeriveSubKey(dek, "siyuan/file")
+ defer zeroAndClear(fileKey)
+ name := boxID + ".sy"
+ aad, _ := filesys.SyAAD(boxID, name)
+ data, err := util.EncryptWithAAD(fileKey, []byte(`{"ID":"`+boxID+`","Spec":"2","Type":"NodeDocument"}`), []byte(aad))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(directory, name), data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ asset, err := EncryptAsset(boxID, "resource.bin", "source.bin", dek, []byte("protected asset"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.MkdirAll(filepath.Join(directory, "assets"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(directory, "assets", "resource.bin"), asset, 0600); err != nil {
+ t.Fatal(err)
+ }
+ legacy := legacyEncryptedAssetFixture(t, boxID, "legacy.bin", "legacy.bin", dek, []byte("legacy asset"))
+ if err = os.WriteFile(filepath.Join(directory, "assets", "legacy.bin"), legacy, 0600); err != nil {
+ t.Fatal(err)
+ }
+ avKey := util.DeriveSubKey(dek, "siyuan/av")
+ defer zeroAndClear(avKey)
+ if err = os.MkdirAll(filepath.Join(directory, "storage", "av"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ for _, avID := range []string{boxID, "mirror", "relation"} {
+ aad := "siyuan:av:" + boxID + ":" + avID
+ if avID == "mirror" || avID == "relation" {
+ aad = "siyuan:av-" + avID + ":" + boxID
+ }
+ definition, encryptErr := util.EncryptWithAAD(avKey, []byte(`{"id":"`+avID+`","spec":8}`), []byte(aad))
+ if encryptErr != nil {
+ t.Fatal(encryptErr)
+ }
+ if err = os.WriteFile(filepath.Join(directory, "storage", "av", avID+".json"), definition, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ t.Cleanup(func() {
+ forgetRuntimeEncryptedBox(boxID)
+ forgetRuntimeNormalBox(boxID)
+ removeEncryptedBoxLifecycle(boxID)
+ })
+ return data
+}
+
+func TestNotebookArchivePartialRemovalAndAuthenticatedRecovery(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := EnableEncryptedNotebook("archive-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, err := deriveKEK("archive-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(kek)
+ ids := []string{"20260925120001-archive", "20260925120002-archive", "20260925120003-archive", "20260925120004-archive", "20260925120005-archive"}
+ original := map[string][]byte{}
+ for _, id := range ids {
+ original[id] = notebookArchiveTestBox(t, id, kek)
+ }
+ oldSalt := append([]byte(nil), Conf.NotebookCrypto.MasterSalt...)
+ archiveID, _, err := PrepareNotebookArchive(ids[:3])
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ archivePath := filepath.Join(directory, "archive.zip")
+ if err = CommitNotebookArchive(archiveID, false); !errors.Is(err, ErrNotebookArchiveInvalid) {
+ t.Fatalf("missing save confirmation: %v", err)
+ }
+ if err = CommitNotebookArchive(archiveID, true); err != nil {
+ t.Fatal(err)
+ }
+ if err = CommitNotebookArchive(archiveID, true); err != nil {
+ t.Fatalf("commit retry: %v", err)
+ }
+ for i, id := range ids {
+ _, err = os.Stat(filepath.Join(util.DataDir, id))
+ if (i < 3) != os.IsNotExist(err) {
+ t.Fatalf("unexpected presence for %s: %v", id, err)
+ }
+ }
+ if !bytes.Equal(oldSalt, Conf.NotebookCrypto.MasterSalt) {
+ t.Fatal("partial removal changed master salt")
+ }
+ if err = DisableEncryptedNotebook(); err == nil {
+ t.Fatal("disabled with two remaining notebooks")
+ }
+ if err = ImportNotebookArchive(archivePath, "archive-password", nil); !errors.Is(err, ErrNotebookArchiveConfigured) {
+ t.Fatalf("import overwrote configured workspace: %v", err)
+ }
+ t.Run("restore in independent workspace", func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := ImportNotebookArchive(archivePath, "wrong", nil); !errors.Is(err, ErrNotebookArchiveAuthentication) {
+ t.Fatalf("wrong password: %v", err)
+ }
+ entries, _ := os.ReadDir(util.DataDir)
+ if len(entries) != 0 || Conf.NotebookCrypto.Enabled {
+ t.Fatal("failed authentication mutated target")
+ }
+ if err := ImportNotebookArchive(archivePath, "archive-password", nil); err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range ids[:3] {
+ data, err := os.ReadFile(filepath.Join(util.DataDir, id, id+".sy"))
+ if err != nil || !bytes.Equal(data, original[id]) {
+ t.Fatalf("ciphertext changed: %s %v", id, err)
+ }
+ if IsBoxUnlocked(id) {
+ t.Fatal("recovery exposed plaintext")
+ }
+ }
+ key, err := deriveKEK("archive-password")
+ defer zeroAndClear(key)
+ if err != nil {
+ t.Fatalf("restored key cannot authenticate: %v", err)
+ }
+ })
+}
+
+func TestNotebookArchiveRejectsChangedSourcesAndRollsBackInterruptedMove(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := EnableEncryptedNotebook("archive-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, _ := deriveKEK("archive-password")
+ defer zeroAndClear(kek)
+ id := "20260925120006-archive"
+ original := notebookArchiveTestBox(t, id, kek)
+ archiveID, _, err := PrepareNotebookArchive([]string{id})
+ if err != nil {
+ t.Fatal(err)
+ }
+ source := filepath.Join(util.DataDir, id)
+ if err = os.WriteFile(filepath.Join(source, id+".sy"), []byte("changed"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err = CommitNotebookArchive(archiveID, true); !errors.Is(err, ErrNotebookArchiveChanged) {
+ t.Fatalf("accepted stale archive: %v", err)
+ }
+ if err = os.WriteFile(filepath.Join(source, id+".sy"), original, 0600); err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ operation := &notebookArchiveOperation{State: "committing", Roots: []string{"data/" + id}}
+ if err = writeNotebookArchiveOperation(directory, operation); err != nil {
+ t.Fatal(err)
+ }
+ removed := filepath.Join(directory, "removed", "data", id)
+ if err = os.MkdirAll(filepath.Dir(removed), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Rename(source, removed); err != nil {
+ t.Fatal(err)
+ }
+ if err = checkPendingNotebookArchives(); !errors.Is(err, ErrNotebookArchiveBusy) {
+ t.Fatalf("pending transaction allowed key changes: %v", err)
+ }
+ if err = ChangeMasterPassword("archive-password", "new-password"); !errors.Is(err, ErrNotebookArchiveBusy) {
+ t.Fatalf("pending transaction allowed password changes: %v", err)
+ }
+ if err = recoverNotebookArchiveOperations(); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(filepath.Join(source, id+".sy"))
+ if err != nil || !bytes.Equal(data, original) {
+ t.Fatalf("crash recovery lost ciphertext: %v", err)
+ }
+ if err = CommitNotebookArchive(archiveID, true); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestNotebookArchiveMissingBackupAndLaterRecoveredKey(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := EnableEncryptedNotebook("archive-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, _ := deriveKEK("archive-password")
+ defer zeroAndClear(kek)
+ id := "20260925120007-archive"
+ notebookArchiveTestBox(t, id, kek)
+ backup, err := os.ReadFile(dataCryptoBackupPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.NotebookCrypto.MasterSalt = []byte("partial old configuration")
+ if err = os.Remove(filepath.Join(util.ConfDir, "conf.json")); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Remove(dataCryptoBackupPath()); err != nil {
+ t.Fatal(err)
+ }
+ if state := NotebookCryptoLifecycleState(false); state != NotebookCryptoStateRecoveryRequired {
+ t.Fatalf("partial key material did not expose the recovery state: %s", state)
+ }
+ archiveID, _, err := PrepareNotebookArchive([]string{id})
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ t.Run("recover after finding backup", func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := ImportNotebookArchive(filepath.Join(directory, "archive.zip"), "archive-password", nil); !errors.Is(err, ErrNotebookArchiveAuthentication) {
+ t.Fatalf("missing key was fabricated: %v", err)
+ }
+ if err := ImportNotebookArchive(filepath.Join(directory, "archive.zip"), "archive-password", backup); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if err = CommitNotebookArchive(archiveID, true); err != nil {
+ t.Fatal(err)
+ }
+ if err = DisableEncryptedNotebook(); err != nil {
+ t.Fatalf("cannot retire incomplete key configuration after archiving: %v", err)
+ }
+ if err = EnableEncryptedNotebook("new-password"); err != nil {
+ t.Fatalf("cannot enable independent keys after archiving: %v", err)
+ }
+}
+
+func TestNotebookArchiveResetDoesNotRetainOldHistoryKeys(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := EnableEncryptedNotebook("first-password"); err != nil {
+ t.Fatal(err)
+ }
+ if err := ChangeMasterPassword("first-password", "second-password"); err != nil {
+ t.Fatal(err)
+ }
+ if len(Conf.NotebookCrypto.HistoryKEKs) == 0 {
+ t.Fatal("missing history-key fixture")
+ }
+ if err := DisableEncryptedNotebook(); err != nil {
+ t.Fatal(err)
+ }
+ if len(Conf.NotebookCrypto.HistoryKEKs) != 0 {
+ t.Fatal("old wrapped keys survived reset")
+ }
+ if err := EnableEncryptedNotebook("new-password"); err != nil {
+ t.Fatal(err)
+ }
+ key, err := deriveKEK("new-password")
+ defer zeroAndClear(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestNotebookArchiveRejectsTraversalAndUnknownVersion(t *testing.T) {
+ for _, name := range []string{"../outside", "/outside", "data/../outside", "C:/outside", "data\\outside", "data/file.", "data/CON"} {
+ if archiveRelativePath(name) {
+ t.Fatalf("accepted unsafe path %q", name)
+ }
+ }
+ manifest := &notebookArchiveManifest{Format: notebookArchiveFormat, Version: 2, ID: "20260925120008-archive", Notebooks: []string{"20260925120007-archive"}}
+ if validateNotebookArchiveManifest(manifest) == nil {
+ t.Fatal("accepted unknown archive version")
+ }
+ archivePath := filepath.Join(t.TempDir(), "traversal.zip")
+ file, _ := os.Create(archivePath)
+ writer := zip.NewWriter(file)
+ entry, _ := writer.Create("../outside")
+ entry.Write([]byte("data"))
+ writer.Close()
+ file.Close()
+ if _, err := readNotebookArchive(archivePath, t.TempDir()); !errors.Is(err, ErrNotebookArchiveInvalid) {
+ t.Fatalf("unsafe extraction: %v", err)
+ }
+}
+
+func TestNotebookArchiveHistoryAndRepositorySnapshots(t *testing.T) {
+ _, repo, _ := prepareAssetDownloadRepoTest(t)
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ if err := EnableEncryptedNotebook("snapshot-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, err := deriveKEK("snapshot-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(kek)
+ id := "20260925120101-archive"
+ notebookArchiveTestBox(t, id, kek)
+ historyRoot := filepath.Join(util.HistoryDir, "2026-09-25-120101-delete")
+ if err = archiveWalk(filepath.Join(util.DataDir, id), func(name, source string) error {
+ return archiveCopyFile(source, filepath.Join(historyRoot, id, filepath.FromSlash(name)))
+ }); err != nil {
+ t.Fatal(err)
+ }
+ ordinaryHistory := filepath.Join(historyRoot, "20260925120102-normalx", "note.txt")
+ if err = os.MkdirAll(filepath.Dir(ordinaryHistory), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(ordinaryHistory, []byte("ordinary history"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ index, err := repo.Index("encrypted snapshot", true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ archiveID, _, err := PrepareNotebookArchive([]string{id})
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ archivePath := filepath.Join(directory, "archive.zip")
+ manifest, err := readNotebookArchive(archivePath, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, exists := manifest.Files["snapshots/"+index.ID+"/"+id+"/"+id+".sy"]; !exists {
+ t.Fatal("repository ciphertext missing from archive")
+ }
+ if err = CommitNotebookArchive(archiveID, true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = os.Stat(filepath.Join(historyRoot, id)); !os.IsNotExist(err) {
+ t.Fatalf("selected history remains: %v", err)
+ }
+ if _, err = os.Stat(ordinaryHistory); err != nil {
+ t.Fatalf("ordinary history removed: %v", err)
+ }
+ if _, err = repo.GetIndex(index.ID); err != nil {
+ t.Fatalf("repository snapshot removed: %v", err)
+ }
+ if err = DisableEncryptedNotebook(); err != nil {
+ t.Fatalf("archived dependencies still block reset: %v", err)
+ }
+ if err = EnableEncryptedNotebook("new-key-domain"); err != nil {
+ t.Fatal(err)
+ }
+ if err = DisableEncryptedNotebook(); err != nil {
+ t.Fatalf("archived snapshots blocked an unrelated key domain: %v", err)
+ }
+ t.Run("restore current notebook and both histories", func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := ImportNotebookArchive(archivePath, "snapshot-password", nil); err != nil {
+ t.Fatal(err)
+ }
+ histories, err := encryptedNotebookHistoryBoxDirs()
+ if err != nil || len(histories) != 2 {
+ t.Fatalf("history recovery incomplete: %v %v", histories, err)
+ }
+ if _, err = os.Stat(filepath.Join(util.DataDir, id)); err != nil {
+ t.Fatal(err)
+ }
+ })
+}
+
+func TestNotebookArchiveRejectsCiphertextWithRecomputedArchiveChecksum(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := EnableEncryptedNotebook("archive-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, _ := deriveKEK("archive-password")
+ defer zeroAndClear(kek)
+ id := "20260925120103-archive"
+ notebookArchiveTestBox(t, id, kek)
+ archiveID, _, err := PrepareNotebookArchive([]string{id})
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ tampered := t.TempDir()
+ manifest, err := readNotebookArchive(filepath.Join(directory, "archive.zip"), filepath.Join(tampered, "payload"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(tampered, "payload", "data", id, id+".sy")
+ data, _ := os.ReadFile(file)
+ data[len(data)-1] ^= 1
+ if err = os.WriteFile(file, data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err = writeNotebookArchive(tampered, manifest); err != nil {
+ t.Fatal(err)
+ }
+ t.Run("authentication is required beyond zip checksums", func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := ImportNotebookArchive(filepath.Join(tampered, "archive.zip"), "archive-password", nil); !errors.Is(err, ErrNotebookArchiveAuthentication) {
+ t.Fatalf("unauthenticated ciphertext accepted: %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(util.DataDir, id)); !os.IsNotExist(err) {
+ t.Fatal("failed import published ciphertext")
+ }
+ })
+}
+
+func TestNotebookArchiveInterruptedImportRollsBack(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ id := "20260925120104-archive"
+ directory, _ := notebookArchiveDirectory("20260925120105-archive")
+ root := "data/" + id
+ operation := &notebookArchiveOperation{State: "importing", Roots: []string{root}}
+ if err := os.MkdirAll(directory, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := writeNotebookArchiveOperation(directory, operation); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Join(util.DataDir, id), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(util.DataDir, id, "source"), []byte("original"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(dataCryptoBackupPath()), 0700); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{dataCryptoBackupPath(), filepath.Join(directory, "import-key.json")} {
+ if err := os.WriteFile(name, []byte("recovery material"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := recoverNotebookArchiveOperations(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(util.DataDir, id)); !os.IsNotExist(err) {
+ t.Fatal("partial import remained visible")
+ }
+ if _, err := os.Stat(dataCryptoBackupPath()); !os.IsNotExist(err) {
+ t.Fatal("partial import left active key backup")
+ }
+ data, err := os.ReadFile(filepath.Join(directory, "install", "data", id, "source"))
+ if err != nil || string(data) != "original" {
+ t.Fatalf("recovery destroyed original bytes: %v", err)
+ }
+}
+
+func TestNotebookArchiveRecoversDocumentHistoryWithoutSeparateEnvelope(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := EnableEncryptedNotebook("history-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, _ := deriveKEK("history-password")
+ defer zeroAndClear(kek)
+ id := "20260925120106-archive"
+ notebookArchiveTestBox(t, id, kek)
+ history := filepath.Join(util.HistoryDir, "2026-09-25-120106-update", id)
+ if err := archiveWalk(filepath.Join(util.DataDir, id), func(name, source string) error {
+ if strings.HasPrefix(name, ".siyuan/") {
+ return nil
+ }
+ return archiveCopyFile(source, filepath.Join(history, filepath.FromSlash(name)))
+ }); err != nil {
+ t.Fatal(err)
+ }
+ archiveID, _, err := PrepareNotebookArchive([]string{id})
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ archivePath := filepath.Join(directory, "archive.zip")
+ t.Run("restore ordinary document and asset history", func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := ImportNotebookArchive(archivePath, "history-password", nil); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{id + ".sy", "assets/resource.bin", "assets/legacy.bin", "storage/av/" + id + ".json"} {
+ if _, err := os.Stat(filepath.Join(util.HistoryDir, "2026-09-25-120106-update", id, filepath.FromSlash(name))); err != nil {
+ t.Fatal(err)
+ }
+ }
+ })
+}
+
+func TestNotebookArchiveHistoryOnlyAndTargetCollisions(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := EnableEncryptedNotebook("history-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, _ := deriveKEK("history-password")
+ defer zeroAndClear(kek)
+ id := "20260925120107-archive"
+ notebookArchiveTestBox(t, id, kek)
+ history := filepath.Join(util.HistoryDir, "2026-09-25-120107-delete", id)
+ if err := os.MkdirAll(filepath.Dir(history), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(filepath.Join(util.DataDir, id), history); err != nil {
+ t.Fatal(err)
+ }
+ candidates, err := ListNotebookArchiveCandidates()
+ if err != nil || len(candidates) != 1 || candidates[0].Current {
+ t.Fatalf("missing history-only candidate: %v %v", candidates, err)
+ }
+ archiveID, _, err := PrepareNotebookArchive([]string{id})
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ archivePath := filepath.Join(directory, "archive.zip")
+ if err = CommitNotebookArchive(archiveID, true); err != nil {
+ t.Fatal(err)
+ }
+ if err = DisableEncryptedNotebook(); err != nil {
+ t.Fatal(err)
+ }
+ t.Run("history remains unmounted", func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ if err := ImportNotebookArchive(archivePath, "history-password", nil); err != nil {
+ t.Fatal(err)
+ }
+ if ids, err := listAllEncryptedBoxIDs(); err != nil || len(ids) != 0 {
+ t.Fatalf("history became a current notebook: %v %v", ids, err)
+ }
+ if histories, err := encryptedNotebookHistoryBoxDirs(); err != nil || len(histories) != 1 {
+ t.Fatalf("history missing: %v %v", histories, err)
+ }
+ })
+ t.Run("existing history is never overwritten", func(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ destination := filepath.Join(util.HistoryDir, "2026-09-25-120107-delete", id, "ordinary.txt")
+ if err := os.MkdirAll(filepath.Dir(destination), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(destination, []byte("keep"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := ImportNotebookArchive(archivePath, "history-password", nil); !errors.Is(err, ErrNotebookArchiveConfigured) {
+ t.Fatalf("accepted colliding history: %v", err)
+ }
+ if data, err := os.ReadFile(destination); err != nil || string(data) != "keep" {
+ t.Fatalf("overwrote target: %v", err)
+ }
+ })
+}
+
+func TestNotebookArchiveDownloadsDeferredEncryptedAssets(t *testing.T) {
+ full, partial, fullData := prepareAssetDownloadRepoTest(t)
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ if err := EnableEncryptedNotebook("deferred-password"); err != nil {
+ t.Fatal(err)
+ }
+ kek, _ := deriveKEK("deferred-password")
+ defer zeroAndClear(kek)
+ id := "20260925120108-archive"
+ localData := util.DataDir
+ util.DataDir = fullData
+ func() {
+ defer func() { util.DataDir = localData }()
+ notebookArchiveTestBox(t, id, kek)
+ }()
+ if err := archiveCopyFile(dataCryptoBackupPath(), filepath.Join(fullData, ".siyuan", "data-crypto-backup.json")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := full.Index("encrypted assets", true, nil); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := full.Sync(nil); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := partial.Sync(nil); err != nil {
+ t.Fatal(err)
+ }
+ asset := filepath.Join(localData, id, "assets", "legacy.bin")
+ if _, err := os.Stat(asset); !os.IsNotExist(err) {
+ t.Fatalf("fixture asset was not deferred: %v", err)
+ }
+ archiveID, _, err := PrepareNotebookArchive([]string{id})
+ if err != nil {
+ t.Fatal(err)
+ }
+ directory, _ := notebookArchiveDirectory(archiveID)
+ manifest, err := readNotebookArchive(filepath.Join(directory, "archive.zip"), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, exists := manifest.Files["data/"+id+"/assets/legacy.bin"]; !exists {
+ t.Fatal("deferred asset missing from archive")
+ }
+ data, err := os.ReadFile(asset)
+ expected, expectedErr := os.ReadFile(filepath.Join(fullData, id, "assets", "legacy.bin"))
+ if err != nil || expectedErr != nil || !bytes.Equal(data, expected) {
+ t.Fatalf("download changed ciphertext: %v %v", err, expectedErr)
+ }
+}