An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Improve plugin publishing permissions and data access https://github.com/siyuan-note/siyuan/issues/18354
Danield122dee55e8d
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.ymlindex b91e433ffb..8961e92f9e 100644--- a/.github/workflows/cd.yml+++ b/.github/workflows/cd.yml@@ -165,7 +165,7 @@ jobs:- name: Test path fixtures with custom temporary directories# 测试失败只记录结果,不阻塞后续发布构建。continue-on-error: true- run: go test -tags "fts5 sqlcipher" ./internal/testutil ./util ./model ./server -run 'Test(PublicDataDir|IsSensitivePath|.*Obsidian|RegisterStaticFileHandlers|StaticFile|WidgetResponseCacheControl|TemplatesAndExportRequireAdministrator|SnippetPublishAccess|PluginPublishAccess)' -count=1+ run: go test -tags "fts5 sqlcipher" ./internal/testutil ./util ./model ./server -run 'Test(PublicDataDir|IsSensitivePath|.*Obsidian|RegisterStaticFileHandlers|StaticFile|WidgetResponseCacheControl|TemplatesAndExportRequireAdministrator|SnippetPublishAccess|PluginPublish|PublishFile)' -count=1working-directory: kernelenv:TMPDIR: /tmpdiff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 086d5bc1ff..5f1b34cf95 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "بيانات الإضافة المنشورة",+ "pluginPublishDataGrantTip": "هل تسمح لزوار خدمة النشر بقراءة هذه الحقول؟ انشر فقط المحتوى المناسب للإفصاح عنه. ستُحذف البيانات المنشورة الحالية",+ "pluginPublishDataRevokeTip": "إلغاء الوصول وحذف البيانات المنشورة لهذه الإضافة",+ "pluginPublishDataUnavailable": "لم تعلن هذه الإضافة عن أي حقول بيانات قابلة للنشر","newTabItem": "إنشاء كتلة عنصر تبويب","encryptedNotebookFollowSystemLock": "اتباع قفل شاشة النظام","encryptedNotebookFollowSystemLockDesc": "قفل جميع دفاتر الملاحظات المشفرة المفتوحة عند قفل النظام، بغض النظر عن مهلة الخمول؛ وتبقى مقفلة بعد فتح النظام",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 0f908dcc83..af18b328db 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Veröffentlichte Plugin-Daten",+ "pluginPublishDataGrantTip": "Besuchern des Veröffentlichungsdienstes Zugriff auf diese Felder erlauben? Veröffentlichen Sie nur dafür geeignete Inhalte. Bisher veröffentlichte Daten werden gelöscht",+ "pluginPublishDataRevokeTip": "Zugriff widerrufen und die veröffentlichten Daten dieses Plugins löschen",+ "pluginPublishDataUnavailable": "Dieses Plugin hat keine veröffentlichbaren Datenfelder deklariert","newTabItem": "Neuen Registerkartenblock erstellen","encryptedNotebookFollowSystemLock": "Der Systemsperre folgen","encryptedNotebookFollowSystemLockDesc": "Alle entsperrten verschlüsselten Notizbücher beim Sperren des Systems unabhängig vom Inaktivitätszeitlimit sperren; sie bleiben nach dem Entsperren des Systems gesperrt",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex bc7307e33a..a46192c76d 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Plugin published data",+ "pluginPublishDataGrantTip": "Allow publishing-service visitors to read these fields? Only publish content suitable for disclosure. Existing published data will be cleared",+ "pluginPublishDataRevokeTip": "Revoke access and delete this plugin's published data",+ "pluginPublishDataUnavailable": "This plugin has not declared any publishable data fields","newTabItem": "New tab item block","encryptedNotebookFollowSystemLock": "Follow system screen lock","encryptedNotebookFollowSystemLockDesc": "Lock all unlocked encrypted notebooks when the system locks, independently of the idle timeout; notebooks remain locked after the system unlocks",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 9d130b085c..c662bf6e80 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Datos publicados del complemento",+ "pluginPublishDataGrantTip": "¿Permitir que los visitantes del servicio de publicación lean estos campos? Publique solo contenido apto para divulgar. Se borrarán los datos publicados existentes",+ "pluginPublishDataRevokeTip": "Revocar el acceso y eliminar los datos publicados de este complemento",+ "pluginPublishDataUnavailable": "Este complemento no ha declarado campos de datos publicables","newTabItem": "Crear bloque de elemento de pestaña","encryptedNotebookFollowSystemLock": "Seguir el bloqueo de pantalla del sistema","encryptedNotebookFollowSystemLockDesc": "Bloquear todos los cuadernos cifrados desbloqueados al bloquear el sistema, independientemente del tiempo de inactividad; permanecen bloqueados al desbloquear el sistema",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex c55eae1d15..69c54bc77b 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Données publiées du greffon",+ "pluginPublishDataGrantTip": "Autoriser les visiteurs du service de publication à lire ces champs ? Ne publiez que du contenu destiné à être divulgué. Les données déjà publiées seront effacées",+ "pluginPublishDataRevokeTip": "Révoquer l’accès et supprimer les données publiées de ce greffon",+ "pluginPublishDataUnavailable": "Ce greffon n’a déclaré aucun champ de données publiable","newTabItem": "Créer un bloc d’onglet","encryptedNotebookFollowSystemLock": "Suivre le verrouillage de l’écran du système","encryptedNotebookFollowSystemLockDesc": "Verrouiller tous les carnets chiffrés déverrouillés lorsque le système se verrouille, indépendamment du délai d’inactivité ; ils restent verrouillés après le déverrouillage du système",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex cf8212a9e1..0d6d62d222 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "הנתונים שפורסמו מהתוסף",+ "pluginPublishDataGrantTip": "לאפשר למבקרים בשירות הפרסום לקרוא שדות אלה? יש לפרסם רק תוכן המתאים לחשיפה. הנתונים שכבר פורסמו יימחקו",+ "pluginPublishDataRevokeTip": "ביטול הגישה ומחיקת הנתונים שפורסמו מתוסף זה",+ "pluginPublishDataUnavailable": "תוסף זה לא הצהיר על שדות נתונים שניתן לפרסם","newTabItem": "יצירת בלוק פריט כרטיסייה","encryptedNotebookFollowSystemLock": "נעילה בהתאם לנעילת מסך המערכת","encryptedNotebookFollowSystemLockDesc": "נעילת כל המחברות המוצפנות הפתוחות בעת נעילת המערכת, ללא תלות בזמן חוסר הפעילות; המחברות נשארות נעולות לאחר ביטול נעילת המערכת",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex c549098b2b..86658953af 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "प्लगइन का प्रकाशित डेटा",+ "pluginPublishDataGrantTip": "क्या प्रकाशन सेवा के आगंतुकों को ये फ़ील्ड पढ़ने की अनुमति दें? केवल साझा करने योग्य सामग्री प्रकाशित करें। मौजूदा प्रकाशित डेटा मिटा दिया जाएगा",+ "pluginPublishDataRevokeTip": "पहुँच रद्द करें और इस प्लगइन का प्रकाशित डेटा हटाएँ",+ "pluginPublishDataUnavailable": "इस प्लगइन ने प्रकाशित किए जा सकने वाले डेटा फ़ील्ड घोषित नहीं किए हैं","newTabItem": "नया टैब आइटम ब्लॉक बनाएँ","encryptedNotebookFollowSystemLock": "सिस्टम स्क्रीन लॉक का पालन करें","encryptedNotebookFollowSystemLockDesc": "सिस्टम लॉक होने पर सभी अनलॉक की गई एन्क्रिप्टेड नोटबुक लॉक करें, निष्क्रियता की समय सीमा से स्वतंत्र; सिस्टम अनलॉक होने के बाद भी नोटबुक लॉक रहेंगी",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex ffd30ea3bc..222634e19e 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Data plugin yang dipublikasikan",+ "pluginPublishDataGrantTip": "Izinkan pengunjung layanan publikasi membaca kolom ini? Publikasikan hanya konten yang layak diungkapkan. Data publikasi yang ada akan dihapus",+ "pluginPublishDataRevokeTip": "Cabut akses dan hapus data publikasi plugin ini",+ "pluginPublishDataUnavailable": "Plugin ini belum mendeklarasikan kolom data yang dapat dipublikasikan","newTabItem": "Buat blok item tab","encryptedNotebookFollowSystemLock": "Ikuti penguncian layar sistem","encryptedNotebookFollowSystemLockDesc": "Kunci semua buku catatan terenkripsi yang terbuka saat sistem terkunci, terlepas dari batas waktu tidak aktif; buku catatan tetap terkunci setelah sistem dibuka",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 40fd448aab..7ba7b1e545 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Dati pubblicati del componente aggiuntivo",+ "pluginPublishDataGrantTip": "Consentire ai visitatori del servizio di pubblicazione di leggere questi campi? Pubblicare solo contenuti adatti alla divulgazione. I dati già pubblicati verranno cancellati",+ "pluginPublishDataRevokeTip": "Revocare l’accesso ed eliminare i dati pubblicati di questo componente aggiuntivo",+ "pluginPublishDataUnavailable": "Questo componente aggiuntivo non ha dichiarato campi dati pubblicabili","newTabItem": "Crea blocco elemento di scheda","encryptedNotebookFollowSystemLock": "Segui il blocco schermo del sistema","encryptedNotebookFollowSystemLockDesc": "Blocca tutti i quaderni crittografati sbloccati quando il sistema si blocca, indipendentemente dal tempo di inattività; restano bloccati dopo lo sblocco del sistema",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex afd3cf9cba..670066815f 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "プラグインの公開データ",+ "pluginPublishDataGrantTip": "公開サービスの閲覧者に以下のフィールドの読み取りを許可しますか?公開してよい内容のみを含めてください。既存の公開データは消去されます",+ "pluginPublishDataRevokeTip": "許可を取り消し、このプラグインの公開データを削除する",+ "pluginPublishDataUnavailable": "このプラグインは公開可能なデータフィールドを宣言していません","newTabItem": "タブ項目ブロックを新規作成","encryptedNotebookFollowSystemLock": "システムの画面ロックに連動","encryptedNotebookFollowSystemLockDesc": "システムの画面ロック時に、アイドル時間の設定に関係なく、ロック解除済みの暗号化ノートブックをすべてロックします。システムのロック解除後もノートブックはロックされたままです",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 01a716bddb..83577edccb 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "플러그인 공개 데이터",+ "pluginPublishDataGrantTip": "게시 서비스 방문자가 다음 필드를 읽도록 허용할까요? 공개해도 되는 내용만 게시하세요. 기존 공개 데이터는 삭제됩니다",+ "pluginPublishDataRevokeTip": "접근 권한을 취소하고 이 플러그인의 공개 데이터 삭제",+ "pluginPublishDataUnavailable": "이 플러그인은 공개 가능한 데이터 필드를 선언하지 않았습니다","newTabItem": "새 탭 항목 블록 만들기","encryptedNotebookFollowSystemLock": "시스템 화면 잠금에 따라 잠금","encryptedNotebookFollowSystemLockDesc": "시스템이 잠기면 유휴 시간 설정과 관계없이 잠금 해제된 모든 암호화 노트북을 잠그며, 시스템 잠금을 해제해도 노트북은 잠금 상태를 유지합니다",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 91650c99e3..d9c5561e45 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Gepubliceerde plug-ingegevens",+ "pluginPublishDataGrantTip": "Bezoekers van de publicatiedienst toestaan deze velden te lezen? Publiceer alleen inhoud die openbaar mag worden. Bestaande gepubliceerde gegevens worden gewist",+ "pluginPublishDataRevokeTip": "Toegang intrekken en de gepubliceerde gegevens van deze plug-in verwijderen",+ "pluginPublishDataUnavailable": "Deze plug-in heeft geen publiceerbare gegevensvelden opgegeven","newTabItem": "Nieuw tabbladitemblok maken","encryptedNotebookFollowSystemLock": "Systeemschermvergrendeling volgen","encryptedNotebookFollowSystemLockDesc": "Vergrendel alle ontgrendelde versleutelde notitieboeken wanneer het systeem wordt vergrendeld, ongeacht de inactiviteitsduur; ze blijven vergrendeld nadat het systeem is ontgrendeld",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex f80c6fc08f..0f93d1326a 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Opublikowane dane wtyczki",+ "pluginPublishDataGrantTip": "Zezwolić odwiedzającym usługę publikowania na odczyt tych pól? Publikuj tylko treści odpowiednie do ujawnienia. Dotychczas opublikowane dane zostaną usunięte",+ "pluginPublishDataRevokeTip": "Cofnij dostęp i usuń opublikowane dane tej wtyczki",+ "pluginPublishDataUnavailable": "Ta wtyczka nie zadeklarowała pól danych do publikacji","newTabItem": "Utwórz blok elementu karty","encryptedNotebookFollowSystemLock": "Blokuj wraz z ekranem systemu","encryptedNotebookFollowSystemLockDesc": "Blokuj wszystkie odblokowane zaszyfrowane notatniki przy blokowaniu systemu, niezależnie od czasu bezczynności; pozostają zablokowane po odblokowaniu systemu",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 1dc9e98f33..6723915173 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Dados publicados do plugin",+ "pluginPublishDataGrantTip": "Permitir que visitantes do serviço de publicação leiam estes campos? Publique apenas conteúdo adequado para divulgação. Os dados já publicados serão apagados",+ "pluginPublishDataRevokeTip": "Revogar o acesso e excluir os dados publicados deste plugin",+ "pluginPublishDataUnavailable": "Este plugin não declarou campos de dados publicáveis","newTabItem": "Criar bloco de item de aba","encryptedNotebookFollowSystemLock": "Seguir o bloqueio de tela do sistema","encryptedNotebookFollowSystemLockDesc": "Bloquear todos os cadernos criptografados desbloqueados quando o sistema for bloqueado, independentemente do tempo de inatividade; eles permanecem bloqueados após desbloquear o sistema",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 23d44ca1c7..7f17fb947d 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Опубликованные данные плагина",+ "pluginPublishDataGrantTip": "Разрешить посетителям сервиса публикации читать эти поля? Публикуйте только сведения, подходящие для раскрытия. Ранее опубликованные данные будут удалены",+ "pluginPublishDataRevokeTip": "Отозвать доступ и удалить опубликованные данные этого плагина",+ "pluginPublishDataUnavailable": "Этот плагин не объявил поля данных для публикации","newTabItem": "Создать блок элемента вкладки","encryptedNotebookFollowSystemLock": "Блокировать вместе с экраном системы","encryptedNotebookFollowSystemLockDesc": "Блокировать все разблокированные зашифрованные блокноты при блокировке системы независимо от времени бездействия; после разблокировки системы блокноты остаются заблокированными",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 29aba0bac0..e076ec24cd 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Zverejnené údaje doplnku",+ "pluginPublishDataGrantTip": "Povoliť návštevníkom publikačnej služby čítať tieto polia? Zverejňujte iba obsah vhodný na sprístupnenie. Doteraz zverejnené údaje sa vymažú",+ "pluginPublishDataRevokeTip": "Odvolať prístup a odstrániť zverejnené údaje tohto doplnku",+ "pluginPublishDataUnavailable": "Tento doplnok nedeklaroval žiadne dátové polia na zverejnenie","newTabItem": "Vytvoriť blok položky karty","encryptedNotebookFollowSystemLock": "Sledovať uzamknutie obrazovky systému","encryptedNotebookFollowSystemLockDesc": "Pri uzamknutí systému uzamknúť všetky odomknuté šifrované zápisníky bez ohľadu na čas nečinnosti; po odomknutí systému zostanú uzamknuté",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex d785d730ca..c02cf9c4cb 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Објављени подаци додатка",+ "pluginPublishDataGrantTip": "Дозволити посетиоцима услуге објављивања да читају ова поља? Објављујте само садржај погодан за откривање. Постојећи објављени подаци биће обрисани",+ "pluginPublishDataRevokeTip": "Опозови приступ и избриши објављене податке овог додатка",+ "pluginPublishDataUnavailable": "Овај додатак није декларисао поља података за објављивање","newTabItem": "Napravi novi blok kartice","encryptedNotebookFollowSystemLock": "Прати закључавање екрана система","encryptedNotebookFollowSystemLockDesc": "Закључај све откључане шифроване бележнице када се систем закључа, независно од времена неактивности; бележнице остају закључане након откључавања система",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex f34600b890..773ecdd6b7 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "ข้อมูลที่เผยแพร่ของปลั๊กอิน",+ "pluginPublishDataGrantTip": "อนุญาตให้ผู้เข้าชมบริการเผยแพร่อ่านฟิลด์เหล่านี้หรือไม่? เผยแพร่เฉพาะเนื้อหาที่เปิดเผยได้ ข้อมูลที่เผยแพร่อยู่จะถูกล้าง",+ "pluginPublishDataRevokeTip": "เพิกถอนสิทธิ์เข้าถึงและลบข้อมูลที่เผยแพร่ของปลั๊กอินนี้",+ "pluginPublishDataUnavailable": "ปลั๊กอินนี้ยังไม่ได้ประกาศฟิลด์ข้อมูลที่เผยแพร่ได้","newTabItem": "สร้างบล็อกแท็บย่อย","encryptedNotebookFollowSystemLock": "ล็อกตามหน้าจอระบบ","encryptedNotebookFollowSystemLockDesc": "ล็อกสมุดบันทึกที่เข้ารหัสและปลดล็อกอยู่ทั้งหมดเมื่อระบบล็อก โดยไม่ขึ้นกับระยะเวลาที่ไม่ได้ใช้งาน สมุดบันทึกจะยังคงล็อกอยู่หลังจากปลดล็อกระบบ",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex efcc582742..519e83e674 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Eklentinin yayımlanan verileri",+ "pluginPublishDataGrantTip": "Yayın hizmeti ziyaretçilerinin bu alanları okumasına izin verilsin mi? Yalnızca açıklanmaya uygun içerikleri yayımlayın. Mevcut yayımlanmış veriler silinecek",+ "pluginPublishDataRevokeTip": "Erişimi iptal et ve bu eklentinin yayımlanan verilerini sil",+ "pluginPublishDataUnavailable": "Bu eklenti yayımlanabilir veri alanları bildirmedi","newTabItem": "Yeni sekme öğesi bloğu oluştur","encryptedNotebookFollowSystemLock": "Sistem ekran kilidini takip et","encryptedNotebookFollowSystemLockDesc": "Sistem kilitlendiğinde boşta kalma süresinden bağımsız olarak kilidi açık tüm şifreli not defterlerini kilitle; sistemin kilidi açıldıktan sonra defterler kilitli kalır",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex ccf48c7fe6..f322c3e3c1 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "Опубліковані дані плагіна",+ "pluginPublishDataGrantTip": "Дозволити відвідувачам сервісу публікації читати ці поля? Публікуйте лише відомості, придатні для розкриття. Раніше опубліковані дані буде видалено",+ "pluginPublishDataRevokeTip": "Скасувати доступ і видалити опубліковані дані цього плагіна",+ "pluginPublishDataUnavailable": "Цей плагін не оголосив поля даних для публікації","newTabItem": "Створити блок елемента вкладки","encryptedNotebookFollowSystemLock": "Блокувати разом з екраном системи","encryptedNotebookFollowSystemLockDesc": "Блокувати всі розблоковані зашифровані записники під час блокування системи незалежно від часу бездіяльності; після розблокування системи записники залишаються заблокованими",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 68386a04f7..efe66b8e96 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "插件发布数据",+ "pluginPublishDataGrantTip": "允许发布服务访问者读取以下字段?请仅公开适合披露的内容,现有发布数据将被清空",+ "pluginPublishDataRevokeTip": "撤销授权并删除此插件的发布数据",+ "pluginPublishDataUnavailable": "此插件尚未声明可公开的数据字段","newTabItem": "新建页签项块","encryptedNotebookFollowSystemLock": "跟随系统锁屏","encryptedNotebookFollowSystemLockDesc": "系统锁屏时锁定所有已解锁的加密笔记本,不受闲置自动锁定时间影响;系统解锁后仍需输入主密码",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 9d7d4399a5..2df0bd0be0 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,8 @@{+ "pluginPublishData": "外掛程式發佈資料",+ "pluginPublishDataGrantTip": "允許發佈服務訪客讀取下列欄位?請僅公開適合披露的內容,現有發佈資料將被清空",+ "pluginPublishDataRevokeTip": "撤銷授權並刪除此外掛程式的發佈資料",+ "pluginPublishDataUnavailable": "此外掛程式尚未宣告可公開的資料欄位","newTabItem": "新增頁籤項區塊","encryptedNotebookFollowSystemLock": "跟隨系統鎖定螢幕","encryptedNotebookFollowSystemLockDesc": "系統鎖定螢幕時鎖定所有已解鎖的加密筆記本,不受閒置自動鎖定時間影響;系統解鎖後仍需輸入主密碼",diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.tsindex 7a843eff12..439c28e4fe 100644--- a/app/src/config/bazaar.ts+++ b/app/src/config/bazaar.ts@@ -827,7 +827,8 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}<input data-type="plugin-publish-enable" data-position="north" class="b3-switch fn__flex-center" type="checkbox"${publishEnabled ? " checked" : ""}${bazaarItem.disabledInPublish ? " disabled" : ""}><span class="fn__space--small"></span><span class="fn__flex-center ft__on-surface">${window.siyuan.languages.publishService}</span>- </label>` : "";+ </label>+ <button data-type="plugin-publish-data" class="b3-button b3-button--outline">${window.siyuan.languages.pluginPublishData}</button>` : "";const available = bazaar._getUpdatedItem(bazaarType, bazaarItem.name)?.available;const ratingKey = getRatingKey(bazaarType, bazaarItem.name);return `<div data-name="${escapeAttr(bazaarItem.name)}" data-package-type="${bazaarType}" data-package-source="downloaded" class="b3-card${bazaarItem.current ? " b3-card--current" : ""}">diff --git a/app/src/config/bazaar/events.ts b/app/src/config/bazaar/events.tsindex 0df1693df6..4cec4472e0 100644--- a/app/src/config/bazaar/events.ts+++ b/app/src/config/bazaar/events.ts@@ -1,4 +1,5 @@import {showMessage} from "../../dialog/message";+import {openPluginPublishData} from "./pluginPublish";import {fetchPost} from "../../util/fetch";import {confirmDialog} from "../../dialog/confirmDialog";/// #if !BROWSER@@ -332,6 +333,12 @@ const ACTION_HANDLERS = {return HANDLED_NATIVE;}) satisfies TBazaarActionHandler,"plugin-publish-enable-label": (() => HANDLED_NATIVE) satisfies TBazaarActionHandler,+ "plugin-publish-data": ((context) => {+ if (context.installedItem) {+ void openPluginPublishData(context.installedItem.name);+ }+ return HANDLED;+ }) satisfies TBazaarActionHandler,"plugin-publish-enable": ((context, target) => {const {controller, app, mount, installedItem} = context;if (!installedItem) {diff --git a/app/src/config/bazaar/pluginPublish.ts b/app/src/config/bazaar/pluginPublish.tsnew file mode 100644index 0000000000..5c9bd209c0--- /dev/null+++ b/app/src/config/bazaar/pluginPublish.ts@@ -0,0 +1,27 @@+import {confirmDialog} from "../../dialog/confirmDialog";+import {showMessage} from "../../dialog/message";+import {escapeHtml} from "../../util/escape";+import {fetchSyncPost} from "../../util/fetch";++export const openPluginPublishData = async (packageName: string) => {+ const response = await fetchSyncPost("/api/petal/getPluginPublishInfo", {packageName});+ if (response.code !== 0 || !response.data) {+ return;+ }+ const {fields, granted} = response.data;+ if (fields.length === 0) {+ showMessage(window.siyuan.languages.pluginPublishDataUnavailable);+ return;+ }+ confirmDialog(window.siyuan.languages.pluginPublishData,+ `<div>${escapeHtml(packageName)}</div>` ++ escapeHtml(granted ? window.siyuan.languages.pluginPublishDataRevokeTip :+ window.siyuan.languages.pluginPublishDataGrantTip) ++ `<ul>${fields.map(field => `<li>${escapeHtml(field)}</li>`).join("")}</ul>`, () => {+ void fetchSyncPost("/api/petal/setPluginPublishDataGrant", {+ packageName,+ fields,+ enabled: !granted,+ });+ });+};diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex 1d50add825..ca44a3d593 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -1,7 +1,7 @@import {sendGlobalShortcut} from "../boot/globalEvent/globalShortcut";import type {App} from "../index";import {EventBus} from "./EventBus";-import {fetchPost} from "../util/fetch";+import {fetchPost, fetchSyncPost} from "../util/fetch";import {ContractFormData} from "../util/contractFormData";import {isMobile, isWindow} from "../util/functions";import {getAllEditor, getAllModels} from "../layout/getAll";@@ -412,6 +412,27 @@ export class Plugin {this.setting.open(this.displayName || this.name);}+ public async loadPublishData(): Promise<Record<string, string | number | boolean | null>> {+ if (isPluginDisposed(this)) {+ throw {code: 410, msg: "Plugin lifecycle has ended", data: null};+ }+ const response = await fetchSyncPost("/api/petal/loadPluginPublishData", {packageName: this.name}, undefined, false);+ if (response.code !== 0 || !response.data) {+ throw response;+ }+ return response.data;+ }++ public async savePublishData(data: Record<string, string | number | boolean | null>): Promise<void> {+ if (isPluginDisposed(this)) {+ throw {code: 410, msg: "Plugin lifecycle has ended", data: null};+ }+ const response = await fetchSyncPost("/api/petal/savePluginPublishData", {packageName: this.name, data}, undefined, false);+ if (response.code !== 0) {+ throw response;+ }+ }+public loadData(storageName: string): Promise<any> {if (isPluginDisposed(this)) {return Promise.reject({code: 410, msg: "Plugin lifecycle has ended", data: null});diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex b2c1bbfa9d..74972ec0dc 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1396,6 +1396,10 @@ export type Petal = { "css": string; "disabledInPublish": boolean; "disallowInstexport type PinnedDoc = { "childrenSortMode": number | null; "icon": string; "id": string; "name": string; "notebook": string; "path": string; "subFileCount": number; "unavailable": boolean; };+export type PluginPublishInfo = { "fields": Array<string>; "granted": boolean; "resources": Array<string>; };++export type PluginPublishRequestInput = { "packageName": string; };+export type PluginRPCError = { "code": number; "data"?: JSONValue; "message": string; };export type PluginRPCFailure = { "error": PluginRPCError | null; "id": string | number | null; "jsonrpc": "2.0"; };@@ -1574,6 +1578,8 @@ export type RollbackRepoSnapshotFileRequestInput = { "id": string; };export type SQLQueryRequestInput = { "mode"?: string | null; "stmt": string; };+export type SavePluginPublishDataRequestInput = { "data": Record<string, null | string | number | boolean>; "packageName": string; };+export type SaveTemplateRequestInput = { "databaseMode"?: string; "directory"?: string; "id": string; "name": string; "overwrite": boolean; };export type SearchAsset = { "hName": string; "path": string; "updated": number; };@@ -1694,6 +1700,8 @@ export type SetPetalEnabledRequestInput = { "app"?: string | null; "enabled": boexport type SetPetalPublishEnabledRequestInput = { "enabled": boolean; "packageName": string; };+export type SetPluginPublishDataGrantRequestInput = { "enabled": boolean; "fields": Array<string>; "packageName": string; };+export type SetPublishRequestInput = { "auth"?: SettingBasicAuthInput | null; "enable"?: boolean | null; "port"?: number | null; };export type SetRepoIndexRetentionDaysRequestInput = { "days": number; };@@ -4307,11 +4315,26 @@ export interface APIPOSTRoutes {response: { "code": 0; "data": Array<SearchPath | null> | null; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "json";};+ "/api/petal/getPluginPublishInfo": {+ request: PluginPublishRequestInput;+ response: { "code": 0; "data": PluginPublishInfo; "msg": string; } | { "code": -1 | 400 | 403 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/petal/loadPetals": {request: LoadPetalsRequestInput;response: { "code": 0; "data": Array<Petal | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "json";};+ "/api/petal/loadPluginPublishData": {+ request: PluginPublishRequestInput;+ response: { "code": 0; "data": Record<string, null | string | number | boolean>; "msg": string; } | { "code": -1 | 400 | 403 | 404 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/petal/savePluginPublishData": {+ request: SavePluginPublishDataRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | 400 | 403 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/petal/setPetalEnabled": {request: SetPetalEnabledRequestInput;response: { "code": 0; "data": Petal | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -4322,6 +4345,11 @@ export interface APIPOSTRoutes {response: { "code": 0; "data": Petal | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "json";};+ "/api/petal/setPluginPublishDataGrant": {+ request: SetPluginPublishDataGrantRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1 | 400 | 403 | 500; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/plugin/getLoadedPlugin": {request: LoadedPluginRequestInput;response: { "code": 0; "data": LoadedPlugin | null; "msg": string; } | { "code": -1 | 1 | 2 | 3 | 4; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.tsindex 00d243f9e7..95b95bf499 100644--- a/app/tests/api-contract.types.ts+++ b/app/tests/api-contract.types.ts@@ -6,6 +6,21 @@ declare const fetchGet: FetchGet;declare const fetchSyncPost: FetchSyncPost;declare const dynamicURL: string;+fetchPost("/api/petal/savePluginPublishData", {packageName: "example", data: {theme: "dark", enabled: true, count: 1, empty: null}});+fetchPost("/api/petal/setPluginPublishDataGrant", {packageName: "example", fields: ["theme"], enabled: true});+// @ts-expect-error 公开字段不能包含未经独立授权的嵌套对象。+fetchPost("/api/petal/savePluginPublishData", {packageName: "example", data: {settings: {token: "secret"}}});+// @ts-expect-error 授权必须携带管理员实际查看的字段清单。+fetchPost("/api/petal/setPluginPublishDataGrant", {packageName: "example", enabled: true});+// @ts-expect-error 发布数据接口只支持 POST。+fetchGet("/api/petal/loadPluginPublishData", () => undefined);+fetchPost("/api/petal/loadPluginPublishData", {packageName: "example"}, response => {+ if (response.code === 0) {+ const value: string | number | boolean | null = response.data.theme;+ void value;+ }+});+fetchPost("/api/setting/setEditor", {markdown: {inlineMath: null}, fontFamilies: null});fetchPost("/api/setting/setAI", {mcp: {servers: [{name: "server", env: {KEY: "value"}}]}});fetchPost("/api/setting/setKeymap", {data: {extension: {items: [null, false, 1, "text", {}]}}});diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdindex b47765d27c..26055a5948 100644--- a/docs/API-CONTRACTS.md+++ b/docs/API-CONTRACTS.md@@ -156,6 +156,8 @@ Asset-reference scans report missing attribute-view definitions and invalid defiAsset-reference query and replacement contracts preserve scalar requests and also accept batches. Batch results retain input order and report each mapping's status, reason, references, and changed-file count; the top-level count includes each shared file once. Empty batches, duplicate sources, and chained or cyclic mappings are rejected. Independent mappings may succeed when another mapping fails; a shared-file write failure belongs to every affected mapping. Scans allow editing and validate the workspace snapshot before saving; cancellation and unchanged retries preserve source data. `TestAssetRelink` regressions cover scalar compatibility, batch validation, shared document/database/OCR persistence, history, and concurrent edits and are included in the full kernel command below.+Plugin publishing contracts separate administrator-only grants and snapshot writes from authenticated public reads. Public data is limited to declared scalar fields; grants and snapshots use a local versioned store outside synced private plugin data. Static and file reads share plugin availability and secure file-opening rules, while publish loading excludes kernel code. `TestAPIContractPluginPublish`, `TestPluginPublishContracts`, `TestPluginPublish*`, and `TestPublishFile*` cover actual responses, admission, scope changes, revocation, reinstall, corruption, and path boundaries. They run in the full kernel suite; run the affected subset with `go test -tags "fts5 sqlcipher" ./api ./model ./server ./util ./apicontract -run 'Test(APIContractPluginPublish|PluginPublish|PublishFile|RouteCoverage)' -count=1`. The path-fixture CI selection also includes the model, static, and file-boundary regressions. See [Plugin publishing](PLUGIN-PUBLISH.md) for public API documentation and migration examples.+Run from `app/`:```textdiff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.mdindex 0b223ab207..1e60a88fa5 100644--- a/docs/API-CONTRACTS.zh-CN.md+++ b/docs/API-CONTRACTS.zh-CN.md@@ -154,6 +154,8 @@ JSON SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷资源引用查询和替换契约保留单资源请求,同时支持批量参数。批量结果按输入顺序返回每项状态、原因、引用和改动文件数;顶层计数对共享文件去重。空批次、重复源路径、链式和循环映射会被拒绝。独立映射可以在其他项失败时完成,共享文件写入失败归属所有受影响映射。扫描期间允许编辑,保存前校验工作区快照;取消和无变化重试保留源数据。`TestAssetRelink` 回归覆盖单资源兼容、批量校验、共享文档、数据库及 OCR 保存、历史和并发编辑,已包含在下方完整内核测试命令中。+插件发布契约将仅管理员可用的授权、快照写入与已认证访问者的公开读取分离。公开数据仅包含声明的标量字段,授权和快照使用独立于同步插件私有存储的本地版本化文件。静态路由与文件接口共用插件状态和安全文件打开规则,发布加载响应排除内核代码。`TestAPIContractPluginPublish`、`TestPluginPublishContracts`、`TestPluginPublish*` 和 `TestPublishFile*` 覆盖实际响应、准入、范围变化、撤销、重装、损坏及路径边界,均包含在完整内核测试中。可运行 `go test -tags "fts5 sqlcipher" ./api ./model ./server ./util ./apicontract -run 'Test(APIContractPluginPublish|PluginPublish|PublishFile|RouteCoverage)' -count=1` 单独验证。路径测试的 CI 筛选也包含模型、静态路由与文件边界回归。接口说明和迁移示例见[插件发布](PLUGIN-PUBLISH.zh-CN.md)。+在 `app/` 下运行:```textdiff --git a/docs/API.md b/docs/API.mdindex 56943309f3..e622b0ebe6 100644--- a/docs/API.md+++ b/docs/API.md@@ -2,6 +2,8 @@| [中文](API.zh-CN.md)| [日本語](API.ja.md)+Plugin resource declarations, data authorization, and publishing APIs are documented in [Plugin publishing](PLUGIN-PUBLISH.md).+* [Specification](#Specification)* [Parameters and return values](#Parameters-and-return-values)* [TypeScript contracts](#TypeScript-contracts)diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 42dd62480a..903d416c04 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -2,6 +2,8 @@| **中文**| [日本語](API.ja.md)+插件资源声明、数据授权与相关接口详见[插件发布](PLUGIN-PUBLISH.zh-CN.md)。+* [规范](#规范)* [参数和返回值](#参数和返回值)* [TypeScript 类型契约](#typescript-类型契约)diff --git a/docs/PLUGIN-PUBLISH.md b/docs/PLUGIN-PUBLISH.mdnew file mode 100644index 0000000000..2518c2dd63--- /dev/null+++ b/docs/PLUGIN-PUBLISH.md@@ -0,0 +1,62 @@+# Plugin publishing++[中文](PLUGIN-PUBLISH.zh-CN.md)++Publish permissions apply to visitors, not individual browser plugins. Published data can be downloaded by visitors and read by other code in the same page. Never publish tokens, passwords, registration codes, or private notebook content.++## Resource declaration++Standard frontend entries (`index.js`, `index.css`, and direct `i18n/*.json` language files) remain available for enabled plugins. Declare every additional frontend file in `plugin.json`:++```json+{+ "name": "example",+ "version": "1.0.0",+ "minAppVersion": "3.8.4",+ "publish": {+ "resources": ["images/logo.png", "views/index.html"],+ "data": ["theme", "showAuthor"]+ }+}+```++Resources are exact relative filenames using `/`, without directories, wildcards, absolute paths, parent traversal, percent encoding, or links. `plugin.json` and `kernel.js` cannot be published. The limits are 4,096 resource files and 128 data fields. Plugins loading extra script chunks, images, fonts, or HTML must list them; plugins using only the standard entries need no resource declaration.++Static routes, the file API, and plugin loading apply the same plugin availability checks. Global disablement, plugin disablement, uninstall, author publish disablement, or user publish disablement denies subsequent reads. Published loading responses exclude kernel code. Links inside the data directory, including linked package directories and Windows junctions, are rejected for publishing; administrator access retains its existing behavior.++Published documents retain their existing permissions. Widgets retain publish availability and accessible-document reference checks. `data/public` remains explicitly public, independently of document passwords. `/api/file/readDir` remains administrator-only, and `data/storage/petal` remains private.++## Data authorization and migration++`publish.data` lists public scalar fields. Names may contain ASCII letters, digits, `_`, or `-`, up to 128 characters. Values must be strings, numbers, booleans, or `null`; objects and arrays are rejected. Flatten selected public values so adding a nested field cannot silently enlarge a grant. Do not serialize private objects into strings as a substitute for selecting public content. Encoded values may total at most 1 MiB per snapshot.++Use **Plugin published data** on the downloaded plugin card to review and authorize fields. This permission is separate from the publishing-service switch and starts disabled. New fields need authorization again; updates within the approved fields do not. Granting or revoking clears the previous snapshot. The plugin must generate a fresh one after authorization.++The SDK provides `loadPublishData(): Promise<Record<string, string | number | boolean | null>>` and `savePublishData(data: Record<string, string | number | boolean | null>): Promise<void>`. Saving requires administrator access and replaces the entire snapshot, removing omitted fields. An empty object publishes an empty snapshot. Reading requires an installed, enabled, publish-enabled plugin and a valid grant. Both methods reject on failure and never fall back to private storage. Existing `loadData` and `saveData` retain their private-storage semantics.++After authorization, select public values in the administrator environment:++```typescript+const settings = await this.loadData("settings.json");+await this.savePublishData({+ theme: settings.theme === "dark" ? "dark" : "light",+ showAuthor: settings.showAuthor === true,+});+```++In published pages, use `await this.loadPublishData()` instead of reading private settings. Provide a plugin action or regenerate after a settings change or administrator-side reload. Handle a missing snapshot before the first successful generation without failing the entire plugin or falling back to private storage.++Versioned grants and snapshots live in `conf/plugin-publish/<name>.json`, separate from public files and synced plugin storage. Do not edit or expose them directly. Authorization is local to the workspace installation and is not transferred by data synchronization. Removed declaration fields are pruned when state is next accessed. Uninstall removes grants and snapshots; reinstall cannot inherit them. Unknown formats, corruption, and failed updates preserve the source and return an error. Revocation cannot recover copies already downloaded.++## HTTP APIs++All endpoints use POST and the standard `{code, msg, data}` envelope. Success is `0`; strict decoding failures use `-1`; invalid declarations, scopes, or values use `400`; missing authorization or unavailable plugins use `403`; a valid grant without a snapshot uses `404`; storage failures use `500`. Authentication, administrator, and read-only middleware preserve their existing HTTP admission responses.++| Endpoint | Access | Request | Success data |+| --- | --- | --- | --- |+| `/api/petal/getPluginPublishInfo` | Administrator | `{ "packageName": "example" }` | `{ "resources": ["images/logo.png", "views/index.html"], "fields": ["showAuthor", "theme"], "granted": false }` |+| `/api/petal/setPluginPublishDataGrant` | Administrator, writable | `{ "packageName": "example", "fields": ["showAuthor", "theme"], "enabled": true }` | `null` |+| `/api/petal/savePluginPublishData` | Administrator, writable | `{ "packageName": "example", "data": { "theme": "dark" } }` | `null` |+| `/api/petal/loadPluginPublishData` | Authenticated; plugin publishing and data grant required | `{ "packageName": "example" }` | `{ "theme": "dark" }` |++The information response lists additional resources; standard entries are implicit. Enabling a grant requires the exact current field set, preventing approval of a changed declaration from an outdated dialog. To revoke, send `enabled: false` and `fields: []`. Administrators reading the snapshot use the same public view. Generated request and response types are exported by `siyuan`.diff --git a/docs/PLUGIN-PUBLISH.zh-CN.md b/docs/PLUGIN-PUBLISH.zh-CN.mdnew file mode 100644index 0000000000..bb2d07ed76--- /dev/null+++ b/docs/PLUGIN-PUBLISH.zh-CN.md@@ -0,0 +1,62 @@+# 插件发布++[English](PLUGIN-PUBLISH.md)++发布权限授予访问者,不区分同一页面中的浏览器插件。公开数据也能被访问者下载或被页面中的其他代码读取。不要公开令牌、密码、注册码或私有笔记本内容。++## 资源声明++已启用插件的标准前端入口 `index.js`、`index.css` 及 `i18n` 下直接存放的 `.json` 语言文件继续可用。额外的前端文件必须在 `plugin.json` 中声明:++```json+{+ "name": "example",+ "version": "1.0.0",+ "minAppVersion": "3.8.4",+ "publish": {+ "resources": ["images/logo.png", "views/index.html"],+ "data": ["theme", "showAuthor"]+ }+}+```++资源采用完整相对文件名,分隔符为 `/`,不支持目录、通配符、绝对路径、上级目录跳转、百分号编码及链接。不得声明 `plugin.json` 或 `kernel.js`。最多声明 4096 个资源文件及 128 个数据字段。加载额外脚本、图片、字体或 HTML 的插件需列出文件,只使用标准入口的插件无需补充资源声明。++静态路由、文件接口和插件加载接口使用一致的发布状态检查。关闭插件总开关、禁用插件、卸载、作者禁止发布或用户关闭发布后,拒绝后续读取。发布加载响应不包含内核代码。发布读取拒绝数据目录内的资源链接,包括插件目录链接和 Windows 目录联接;管理员原有访问行为保持兼容。++已发布文档保留现有权限。挂件保留发布状态及可访问文档引用检查。`data/public` 保持明确公开的语义,不受单篇文档密码保护。`/api/file/readDir` 仍仅允许管理员调用,`data/storage/petal` 仍为私有存储。++## 数据授权与迁移++`publish.data` 声明公开的标量字段。字段名只包含 ASCII 字母、数字、`_` 或 `-`,最多 128 个字符。值只允许字符串、数字、布尔值或 `null`,不允许对象和数组。请把选择的公开内容整理成独立字段,避免嵌套对象增加字段时悄悄扩大授权;不要把私有对象序列化成字符串来代替筛选公开内容。单个快照的字段值编码后总大小不得超过 1 MiB。++在已下载插件卡片中点击「插件发布数据」,查看字段清单并授权。该权限与发布服务开关独立,默认关闭。新增字段需要重新授权,已授权字段的日常更新无需反复确认。授权或撤销会清空旧快照,插件需在授权后重新生成。++插件接口提供 `loadPublishData(): Promise<Record<string, string | number | boolean | null>>` 与 `savePublishData(data: Record<string, string | number | boolean | null>): Promise<void>`。保存要求管理员权限,完整替换快照,省略的字段会被移除,空对象表示发布空快照。读取要求插件已安装、已启用、允许发布且授权有效。失败时拒绝 Promise,不会回退读取私有存储。现有 `loadData` 和 `saveData` 的私有存储语义不变。++管理员授权后,在管理员环境中选择公开值:++```typescript+const settings = await this.loadData("settings.json");+await this.savePublishData({+ theme: settings.theme === "dark" ? "dark" : "light",+ showAuthor: settings.showAuthor === true,+});+```++发布页面改为调用 `await this.loadPublishData()`,不再读取私有配置。插件可以提供生成操作,或在设置变化、管理员端重新加载时生成。首次成功生成前应处理「尚未生成」错误,避免整个插件加载失败,也不要尝试回退到私有存储。++带版本号的授权与快照保存在 `conf/plugin-publish/<name>.json`,与公开目录及同步的插件存储分离,不应直接编辑或暴露。授权属于当前工作空间安装,不随数据同步转移。声明移除的字段在下次访问状态时清理。卸载会删除授权与快照,重装不能继承。未知格式、损坏及更新失败时保留原始数据并返回错误。撤销无法收回已经下载的副本。++## HTTP 接口++以下接口均使用 POST 和标准的 `{code, msg, data}` 信封。成功为 `0`,严格参数解析失败为 `-1`,声明、范围或值无效为 `400`,未授权或插件不可发布为 `403`,已授权但尚未生成快照为 `404`,存储失败为 `500`。认证、管理员及只读中间件保留既有 HTTP 拒绝响应。++| 接口 | 权限 | 请求 | 成功数据 |+| --- | --- | --- | --- |+| `/api/petal/getPluginPublishInfo` | 管理员 | `{ "packageName": "example" }` | `{ "resources": ["images/logo.png", "views/index.html"], "fields": ["showAuthor", "theme"], "granted": false }` |+| `/api/petal/setPluginPublishDataGrant` | 管理员、可写 | `{ "packageName": "example", "fields": ["showAuthor", "theme"], "enabled": true }` | `null` |+| `/api/petal/savePluginPublishData` | 管理员、可写 | `{ "packageName": "example", "data": { "theme": "dark" } }` | `null` |+| `/api/petal/loadPluginPublishData` | 已认证,插件允许发布且数据已授权 | `{ "packageName": "example" }` | `{ "theme": "dark" }` |++信息响应只列出额外资源,标准入口隐式提供。启用授权时必须提交与当前声明完全一致的字段集合,防止通过过期对话框批准已变化的范围。撤销时提交 `enabled: false` 和 `fields: []`。管理员读取快照也使用同一公开视图。请求和响应类型由 `siyuan` 导出。diff --git a/kernel/api/file.go b/kernel/api/file.goindex 36c8cc1846..9b39ce288a 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -410,6 +410,24 @@ var copyFile = contractHandler(apicontract.CopyFile, func(c *gin.Context, requesvar getFile = contractHandler(apicontract.GetFile, func(c *gin.Context, request apicontract.FilePathRequest) apicontract.Response[apicontract.BinaryContent] {ret := gulu.Ret.NewResult()filePath := request.Path+ if !model.IsAdminRoleContext(c) {+ c.Header("Cache-Control", "private, no-store")+ if file, handled, err := model.OpenPublishPackageFile(c, filePath); handled {+ if err != nil {+ return apicontract.Failure[apicontract.BinaryContent](http.StatusForbidden, http.StatusText(http.StatusForbidden))+ }+ defer file.Close()+ data, readErr := io.ReadAll(file)+ if readErr != nil {+ return apicontract.Failure[apicontract.BinaryContent](http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError))+ }+ contentType := mime.TypeByExtension(filepath.Ext(filePath))+ if contentType == "" {+ contentType = mimetype.Detect(data).String()+ }+ return apicontract.SuccessBinary(contentType, data)+ }+ }fileAbsPath, err := util.GetAbsPathInWorkspace(filePath)if err != nil {diff --git a/kernel/api/petal.go b/kernel/api/petal.goindex 5c97997244..023321f459 100644--- a/kernel/api/petal.go+++ b/kernel/api/petal.go@@ -25,6 +25,9 @@ import ()var loadPetals = contractHandler(apicontract.LoadPetals, func(c *gin.Context, request apicontract.LoadPetalsRequest) apicontract.Response[[]*apicontract.Petal] {+ if model.IsReadOnlyRoleContext(c) {+ c.Header("Cache-Control", "private, no-store")+ }values := model.LoadPetals(request.Frontend, model.IsReadOnlyRoleContext(c))var result []*apicontract.Petalif values != nil {diff --git a/kernel/api/plugin_publish.go b/kernel/api/plugin_publish.gonew file mode 100644index 0000000000..31815ff9d8--- /dev/null+++ b/kernel/api/plugin_publish.go@@ -0,0 +1,72 @@+package api++import (+ "encoding/json"+ "errors"+ "net/http"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func pluginPublishFailure[T any](err error) apicontract.Response[T] {+ code := http.StatusInternalServerError+ switch {+ case errors.Is(err, model.ErrPluginPublishDenied):+ code = http.StatusForbidden+ case errors.Is(err, model.ErrPluginPublishMissing):+ code = http.StatusNotFound+ case errors.Is(err, model.ErrPluginPublishInvalid):+ code = http.StatusBadRequest+ }+ return apicontract.Failure[T](code, http.StatusText(code))+}++var getPluginPublishInfo = contractHandler(apicontract.GetPluginPublishInfo, func(c *gin.Context, request apicontract.PluginPublishRequest) apicontract.Response[apicontract.PluginPublishInfo] {+ c.Header("Cache-Control", "private, no-store")+ info, err := model.GetPluginPublishInfo(request.PackageName)+ if err != nil {+ return pluginPublishFailure[apicontract.PluginPublishInfo](err)+ }+ return apicontract.Success(apicontract.PluginPublishInfo{Resources: info.Resources, Fields: info.Fields, Granted: info.Granted})+})++var setPluginPublishDataGrant = contractHandler(apicontract.SetPluginPublishDataGrant, func(c *gin.Context, request apicontract.SetPluginPublishDataGrantRequest) apicontract.Response[apicontract.Null] {+ if err := model.SetPluginPublishDataGrant(request.PackageName, request.Fields, request.Enabled); err != nil {+ return pluginPublishFailure[apicontract.Null](err)+ }+ return apicontract.Success(apicontract.Null{})+})++var savePluginPublishData = contractHandler(apicontract.SavePluginPublishData, func(c *gin.Context, request apicontract.SavePluginPublishDataRequest) apicontract.Response[apicontract.Null] {+ data := map[string]json.RawMessage{}+ for key, value := range request.Data {+ raw, err := value.MarshalJSON()+ if err != nil {+ return pluginPublishFailure[apicontract.Null](err)+ }+ data[key] = raw+ }+ if err := model.SavePluginPublishData(request.PackageName, data); err != nil {+ return pluginPublishFailure[apicontract.Null](err)+ }+ return apicontract.Success(apicontract.Null{})+})++var loadPluginPublishData = contractHandler(apicontract.LoadPluginPublishData, func(c *gin.Context, request apicontract.PluginPublishRequest) apicontract.Response[map[string]apicontract.PublishDataValue] {+ c.Header("Cache-Control", "private, no-store")+ data, err := model.LoadPluginPublishData(request.PackageName)+ if err != nil {+ return pluginPublishFailure[map[string]apicontract.PublishDataValue](err)+ }+ result := map[string]apicontract.PublishDataValue{}+ for key, raw := range data {+ var value apicontract.PublishDataValue+ if err = value.UnmarshalJSON(raw); err != nil {+ return pluginPublishFailure[map[string]apicontract.PublishDataValue](err)+ }+ result[key] = value+ }+ return apicontract.Success(result)+})diff --git a/kernel/api/plugin_publish_test.go b/kernel/api/plugin_publish_test.gonew file mode 100644index 0000000000..01da7b010e--- /dev/null+++ b/kernel/api/plugin_publish_test.go@@ -0,0 +1,134 @@+package api++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractPluginPublish(t *testing.T) {+ oldWorkspace, oldData, oldConfDir, oldConf := util.WorkspaceDir, util.DataDir, util.ConfDir, model.Conf+ util.WorkspaceDir = t.TempDir()+ util.DataDir, util.ConfDir = filepath.Join(util.WorkspaceDir, "data"), filepath.Join(util.WorkspaceDir, "conf")+ model.Conf = model.NewAppConf()+ model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ t.Cleanup(func() {+ util.WorkspaceDir, util.DataDir, util.ConfDir, model.Conf = oldWorkspace, oldData, oldConfDir, oldConf+ })+ files := map[string]string{+ "data/plugins/example/plugin.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":{"resources":["logo.txt"],"data":["theme"]}}`,+ "data/plugins/example/index.js": "frontend",+ "data/plugins/example/kernel.js": "kernel secret",+ "data/plugins/example/logo.txt": "logo",+ "data/plugins/example/private.json": "secret",+ "data/storage/petal/example/private.json": "private token",+ "data/public/file.txt": "public",+ "data/private.json": "private data root",+ "conf/private.json": "conf secret",+ "temp/private.json": "temp secret",+ "repo/private.json": "repo secret",+ "history/private.json": "history secret",+ }+ for path, content := range files {+ path = filepath.Join(util.WorkspaceDir, filepath.FromSlash(path))+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := model.SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ request := func(role model.Role, path, body string) *httptest.ResponseRecorder {+ t.Helper()+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role); c.Next() })+ ServeAPI(engine)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(body)))+ if recorder.Body.Len() > 0 {+ requireAPIContract(t, "POST", path, recorder)+ }+ return recorder+ }+ code := func(recorder *httptest.ResponseRecorder) int {+ t.Helper()+ var value struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &value); err != nil {+ t.Fatal(err)+ }+ return value.Code+ }+ for _, role := range []model.Role{model.RoleReader, model.RoleEditor} {+ for _, path := range []string{"getPluginPublishInfo", "setPluginPublishDataGrant", "savePluginPublishData"} {+ if response := request(role, "/api/petal/"+path, `{}`); response.Code != http.StatusForbidden {+ t.Fatalf("non-admin %s admitted: %s", path, response.Body)+ }+ }+ if response := request(role, "/api/file/readDir", `{"path":"data/plugins/example"}`); response.Code != http.StatusForbidden {+ t.Fatal("directory enumeration admitted")+ }+ }+ if response := request(model.RoleReader, "/api/petal/loadPluginPublishData", `{"packageName":"example"}`); code(response) != 403 {+ t.Fatalf("ungranted read: %s", response.Body)+ }+ if response := request(model.RoleAdministrator, "/api/petal/setPluginPublishDataGrant", `{"packageName":"example","fields":["theme"],"enabled":true}`); code(response) != 0 {+ t.Fatal(response.Body)+ }+ if response := request(model.RoleReader, "/api/petal/loadPluginPublishData", `{"packageName":"example"}`); code(response) != 404 {+ t.Fatalf("missing snapshot: %s", response.Body)+ }+ if response := request(model.RoleAdministrator, "/api/petal/savePluginPublishData", `{"packageName":"example","data":{"theme":"dark"}}`); code(response) != 0 {+ t.Fatal(response.Body)+ }+ if response := request(model.RoleReader, "/api/petal/loadPluginPublishData", `{"packageName":"example"}`); code(response) != 0 || !strings.Contains(response.Body.String(), `"theme":"dark"`) || response.Header().Get("Cache-Control") != "private, no-store" {+ t.Fatal(response.Body)+ }+ if response := request(model.RoleAdministrator, "/api/petal/savePluginPublishData", `{"packageName":"example","data":{"theme":{"token":"secret"}}}`); code(response) == 0 {+ t.Fatal("nested data accepted")+ }+ for path, want := range map[string]string{"data/public/file.txt": "public", "data/plugins/example/index.js": "frontend", "data/plugins/example/logo.txt": "logo"} {+ body, _ := json.Marshal(map[string]string{"path": path})+ response := request(model.RoleReader, "/api/file/getFile", string(body))+ if response.Code != 200 || response.Body.String() != want {+ t.Fatalf("allowed %s: %d %s", path, response.Code, response.Body)+ }+ }+ for _, path := range []string{"data/plugins/example/kernel.js", "data/plugins/example/private.json", "data/storage/petal/example/private.json", "data/private.json", "conf/private.json", "temp/private.json", "repo/private.json", "history/private.json", "conf/plugin-publish/example.json", "data/public/../storage/petal/example/private.json", "data/plugins/example/%2e%2e/private.json"} {+ body, _ := json.Marshal(map[string]string{"path": path})+ response := request(model.RoleReader, "/api/file/getFile", string(body))+ if response.Code != 202 || code(response) != 403 {+ t.Fatalf("denied %s: %d %s", path, response.Code, response.Body)+ }+ }+ response := request(model.RoleReader, "/api/petal/loadPetals", `{"frontend":"browser-desktop"}`)+ if bytes.Contains(response.Body.Bytes(), []byte("kernel secret")) || !bytes.Contains(response.Body.Bytes(), []byte("frontend")) {+ t.Fatal(response.Body)+ }+ if _, err := model.SetPetalPublishEnabled("example", false); err != nil {+ t.Fatal(err)+ }+ if response := request(model.RoleReader, "/api/petal/loadPluginPublishData", `{"packageName":"example"}`); code(response) != 403 {+ t.Fatal("disabled data admitted")+ }+ if response := request(model.RoleReader, "/api/file/getFile", `{"path":"data/plugins/example/logo.txt"}`); code(response) != 403 {+ t.Fatal("disabled resource admitted")+ }+ if response := request(model.RoleAdministrator, "/api/file/getFile", `{"path":"data/storage/petal/example/private.json"}`); response.Body.String() != "private token" {+ t.Fatalf("admin regression: %s", response.Body)+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 31833fdc23..6931f309b1 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -673,6 +673,10 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/petal/loadPetals", model.CheckAuth, loadPetals)ginServer.Handle("POST", "/api/petal/setPetalEnabled", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPetalEnabled)ginServer.Handle("POST", "/api/petal/setPetalPublishEnabled", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPetalPublishEnabled)+ ginServer.Handle("POST", "/api/petal/getPluginPublishInfo", model.CheckAuth, model.CheckAdminRole, getPluginPublishInfo)+ ginServer.Handle("POST", "/api/petal/setPluginPublishDataGrant", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setPluginPublishDataGrant)+ ginServer.Handle("POST", "/api/petal/savePluginPublishData", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, savePluginPublishData)+ ginServer.Handle("POST", "/api/petal/loadPluginPublishData", model.CheckAuth, loadPluginPublishData)ginServer.Handle("GET", "/api/plugin/rpc", model.CheckAuth, getLoadedPluginRPC)ginServer.Handle("GET", "/api/plugin/rpc/:name", model.CheckAuth, getLoadedPluginRPCByName)diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex f3808730ba..8f73311200 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -462,6 +462,11 @@ var SetPetalEnabled = define[SetPetalEnabledRequest, *Petal]("setPetalEnabled",var SetPetalPublishEnabled = define[SetPetalPublishEnabledRequest, *Petal]("setPetalPublishEnabled", "/api/petal/setPetalPublishEnabled", JSONBody, ResponseOptions{}, "POST")+var GetPluginPublishInfo = define[PluginPublishRequest, PluginPublishInfo]("getPluginPublishInfo", "/api/petal/getPluginPublishInfo", JSONBody, ResponseOptions{AdditionalCodes: []int{400, 403, 500}}, "POST")+var SetPluginPublishDataGrant = define[SetPluginPublishDataGrantRequest, Null]("setPluginPublishDataGrant", "/api/petal/setPluginPublishDataGrant", JSONBody, ResponseOptions{AdditionalCodes: []int{400, 403, 500}}, "POST")+var SavePluginPublishData = define[SavePluginPublishDataRequest, Null]("savePluginPublishData", "/api/petal/savePluginPublishData", JSONBody, ResponseOptions{AdditionalCodes: []int{400, 403, 500}}, "POST")+var LoadPluginPublishData = define[PluginPublishRequest, map[string]PublishDataValue]("loadPluginPublishData", "/api/petal/loadPluginPublishData", JSONBody, ResponseOptions{NonNullable: true, AdditionalCodes: []int{400, 403, 404, 500}}, "POST")+var Pandoc = define[PandocRequest, PandocData]("pandoc", "/api/convert/pandoc", JSONBody, ResponseOptions{}, "POST")var PostBroadcastMessage = define[BroadcastMessageRequest, BroadcastChannelData]("postMessage", "/api/broadcast/postMessage", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")diff --git a/kernel/apicontract/decode.go b/kernel/apicontract/decode.goindex d8a19be77d..13c2be3d6e 100644--- a/kernel/apicontract/decode.go+++ b/kernel/apicontract/decode.go@@ -159,7 +159,7 @@ func decodeRequestFields(value reflect.Value, fields map[string]json.RawMessage)// decodeRequestValue 递归绑定复合参数,避免数组元素和嵌套字段绕过空值及必填检查。func decodeRequestValue(raw json.RawMessage, value reflect.Value) error {- if value.Type() == reflect.TypeFor[JSONValue]() {+ if value.Type() == reflect.TypeFor[JSONValue]() || value.Type() == reflect.TypeFor[PublishDataValue]() {return json.Unmarshal(raw, value.Addr().Interface())}if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {diff --git a/kernel/apicontract/plugin_publish.go b/kernel/apicontract/plugin_publish.gonew file mode 100644index 0000000000..03f4cb1575--- /dev/null+++ b/kernel/apicontract/plugin_publish.go@@ -0,0 +1,46 @@+package apicontract++import (+ "bytes"+ "encoding/json"+ "errors"+)++// PublishDataValue 限定公开字段为标量,避免嵌套对象扩展绕过字段授权。+type PublishDataValue struct{ raw json.RawMessage }++func (v PublishDataValue) MarshalJSON() ([]byte, error) {+ if len(v.raw) == 0 {+ return []byte("null"), nil+ }+ return v.raw, nil+}+func (v *PublishDataValue) UnmarshalJSON(data []byte) error {+ data = bytes.TrimSpace(data)+ if !json.Valid(data) || data[0] == '{' || data[0] == '[' {+ return errors.New("published data fields must be JSON scalars")+ }+ v.raw = append(v.raw[:0], data...)+ return nil+}++type PluginPublishRequest struct {+ PackageName string `json:"packageName"`+}++type PluginPublishInfo struct {+ Resources []string `json:"resources" api:"nonnullable"`+ Fields []string `json:"fields" api:"nonnullable"`+ Granted bool `json:"granted"`+}++type SetPluginPublishDataGrantRequest struct {+ PackageName string `json:"packageName"`+ Fields []string `json:"fields"`+ Enabled bool `json:"enabled"`+}++type SavePluginPublishDataRequest struct {+ PackageName string `json:"packageName"`+ Data map[string]PublishDataValue `json:"data"`+}diff --git a/kernel/apicontract/plugin_publish_test.go b/kernel/apicontract/plugin_publish_test.gonew file mode 100644index 0000000000..7e0029a3b0--- /dev/null+++ b/kernel/apicontract/plugin_publish_test.go@@ -0,0 +1,20 @@+package apicontract++import (+ "strings"+ "testing"+)++func TestPluginPublishContracts(t *testing.T) {+ for _, body := range []string{`{}`, `{"packageName":"example","data":null}`, `{"packageName":"example","data":{"x":[]}}`, `{"packageName":"example","data":{"x":{}}}`} {+ if _, err := SavePluginPublishData.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("invalid snapshot accepted: %s", body)+ }+ }+ if _, err := SavePluginPublishData.Decode(strings.NewReader(`{"packageName":"example","data":{"text":"a","number":1234567890123456789,"bool":true,"nil":null}}`)); err != nil {+ t.Fatal(err)+ }+ if _, err := SetPluginPublishDataGrant.Decode(strings.NewReader(`{"packageName":"example","fields":["x"],"enabled":"true"}`)); err == nil {+ t.Fatal("non-boolean grant accepted")+ }+}diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.goindex e0bb95b820..6998dd6d18 100644--- a/kernel/apicontract/schema.go+++ b/kernel/apicontract/schema.go@@ -277,7 +277,7 @@ func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {}return &Schema{AnyOf: append(variants, &Schema{Type: "null"})}, nil}- if t == reflect.TypeFor[SQLValue]() {+ if t == reflect.TypeFor[SQLValue]() || t == reflect.TypeFor[PublishDataValue]() {return &Schema{AnyOf: []*Schema{{Type: "null"}, {Type: "string"}, {Type: "number"}, {Type: "boolean"}}}, nil}if t == reflect.TypeFor[BinaryContent]() {diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 1c5d848e31..42c25afbe4 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -31767,6 +31767,44 @@],"additionalProperties": false},+ "PluginPublishInfo": {+ "type": "object",+ "properties": {+ "fields": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "granted": {+ "type": "boolean"+ },+ "resources": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "fields",+ "granted",+ "resources"+ ],+ "additionalProperties": false+ },+ "PluginPublishRequestInput": {+ "type": "object",+ "properties": {+ "packageName": {+ "type": "string"+ }+ },+ "required": [+ "packageName"+ ],+ "additionalProperties": false+ },"PluginRPCError": {"type": "object","properties": {@@ -34294,6 +34332,38 @@],"additionalProperties": false},+ "SavePluginPublishDataRequestInput": {+ "type": "object",+ "properties": {+ "data": {+ "type": "object",+ "additionalProperties": {+ "anyOf": [+ {+ "type": "null"+ },+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ }+ },+ "packageName": {+ "type": "string"+ }+ },+ "required": [+ "data",+ "packageName"+ ],+ "additionalProperties": false+ },"SaveTemplateRequestInput": {"type": "object","properties": {@@ -37850,6 +37920,29 @@],"additionalProperties": false},+ "SetPluginPublishDataGrantRequestInput": {+ "type": "object",+ "properties": {+ "enabled": {+ "type": "boolean"+ },+ "fields": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "packageName": {+ "type": "string"+ }+ },+ "required": [+ "enabled",+ "fields",+ "packageName"+ ],+ "additionalProperties": false+ },"SetPublishRequestInput": {"type": "object","properties": {@@ -138346,6 +138439,84 @@]}},+ {+ "method": "POST",+ "path": "/api/petal/getPluginPublishInfo",+ "handler": "getPluginPublishInfo",+ "body": "json",+ "request": {+ "$ref": "#/$defs/PluginPublishRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/PluginPublishInfo"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ 400,+ 403,+ 500+ ]+ },+ "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/petal/loadPetals",@@ -138438,6 +138609,179 @@]}},+ {+ "method": "POST",+ "path": "/api/petal/loadPluginPublishData",+ "handler": "loadPluginPublishData",+ "body": "json",+ "request": {+ "$ref": "#/$defs/PluginPublishRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "object",+ "additionalProperties": {+ "anyOf": [+ {+ "type": "null"+ },+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "boolean"+ }+ ]+ }+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ 400,+ 403,+ 404,+ 500+ ]+ },+ "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/petal/savePluginPublishData",+ "handler": "savePluginPublishData",+ "body": "json",+ "request": {+ "$ref": "#/$defs/SavePluginPublishDataRequestInput"+ },+ "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,+ 400,+ 403,+ 500+ ]+ },+ "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/petal/setPetalEnabled",@@ -138602,6 +138946,84 @@]}},+ {+ "method": "POST",+ "path": "/api/petal/setPluginPublishDataGrant",+ "handler": "setPluginPublishDataGrant",+ "body": "json",+ "request": {+ "$ref": "#/$defs/SetPluginPublishDataGrantRequestInput"+ },+ "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,+ 400,+ 403,+ 500+ ]+ },+ "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/plugin/getLoadedPlugin",diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.goindex cba668ae1e..9600a97fd3 100644--- a/kernel/model/bazaar.go+++ b/kernel/model/bazaar.go@@ -702,6 +702,13 @@ func UninstallPackage(pkgType, packageName string) error {return err}+ if pkgType == "plugins" {+ pluginPublishLock.Lock()+ defer pluginPublishLock.Unlock()+ if err = removePluginPublishData(packageName); err != nil {+ return err+ }+ }err = bazaar.UninstallPackage(installPath)if err != nil {return fmt.Errorf(Conf.Language(47), err.Error())diff --git a/kernel/model/plugin.go b/kernel/model/plugin.goindex 6ab02073ec..d038557170 100644--- a/kernel/model/plugin.go+++ b/kernel/model/plugin.go@@ -245,7 +245,13 @@ func loadPetals(frontend string, isPublish, isKernel bool) (ret []*Petal) {continue}- loadCode(petal)+ if isPublish {+ if !loadPluginPublishCode(petal) {+ continue+ }+ } else {+ loadCode(petal)+ }if isKernel {if !petal.Kernel.Existed {logging.LogWarnf("plugin [%s] kernel.js not found, skip loading as kernel plugin", petal.Name)diff --git a/kernel/model/plugin_publish.go b/kernel/model/plugin_publish.gonew file mode 100644index 0000000000..efc1bb5d91--- /dev/null+++ b/kernel/model/plugin_publish.go@@ -0,0 +1,345 @@+package model++import (+ "bytes"+ "encoding/json"+ "errors"+ "io"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "sync"++ "github.com/88250/gulu"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/bazaar"+ "github.com/siyuan-note/siyuan/kernel/util"+)++var (+ ErrPluginPublishDenied = errors.New("plugin publish access denied")+ ErrPluginPublishMissing = errors.New("plugin publish data has not been generated")+ ErrPluginPublishInvalid = errors.New("invalid plugin publish declaration or data")+ pluginPublishLock sync.Mutex+)++// PluginPublishDeclaration 的资源为精确文件名,数据为可公开的顶层标量字段,不支持目录或通配符。+type PluginPublishDeclaration struct {+ Resources []string `json:"resources"`+ Data []string `json:"data"`+}++type PluginPublishInfo struct {+ Resources []string `json:"resources"`+ Fields []string `json:"fields"`+ Granted bool `json:"granted"`+}++type pluginPublishState struct {+ Version int `json:"version"`+ Granted []string `json:"granted"`+ Data map[string]json.RawMessage `json:"data"`+}++func pluginPublishDeclaration(name string) (PluginPublishDeclaration, error) {+ ret := PluginPublishDeclaration{Resources: []string{}, Data: []string{}}+ if !bazaar.IsValidPackageName(name) {+ return ret, ErrPluginPublishDenied+ }+ file, err := util.OpenPublishFile(util.DataDir, "plugins/"+name+"/plugin.json")+ if err != nil {+ return ret, err+ }+ defer file.Close()+ var manifest struct {+ Name string `json:"name"`+ Publish *PluginPublishDeclaration `json:"publish"`+ }+ content, err := io.ReadAll(io.LimitReader(file, 1024*1024+1))+ if err != nil || len(content) > 1024*1024 || json.Unmarshal(content, &manifest) != nil || manifest.Name != name {+ return ret, ErrPluginPublishInvalid+ }+ if manifest.Publish == nil {+ return ret, nil+ }+ ret = *manifest.Publish+ if len(ret.Resources) > 4096 || len(ret.Data) > 128 {+ return ret, ErrPluginPublishInvalid+ }+ for _, resource := range ret.Resources {+ if !util.IsPublishRelativePath(resource) || strings.EqualFold(resource, "plugin.json") || strings.EqualFold(resource, "kernel.js") {+ return ret, ErrPluginPublishInvalid+ }+ }+ for _, field := range ret.Data {+ if len(field) == 0 || len(field) > 128 {+ return ret, ErrPluginPublishInvalid+ }+ for _, char := range field {+ if !(char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char >= '0' && char <= '9' || char == '_' || char == '-') {+ return ret, ErrPluginPublishInvalid+ }+ }+ }+ slices.Sort(ret.Resources)+ ret.Resources = slices.Compact(ret.Resources)+ slices.Sort(ret.Data)+ ret.Data = slices.Compact(ret.Data)+ return ret, nil+}++func isPluginPublishResource(declaration PluginPublishDeclaration, resource string) bool {+ // 标准入口及语言包属于插件既有的前端文件约定,其余文件必须显式声明。+ return resource == "index.js" || resource == "index.css" ||+ strings.HasPrefix(resource, "i18n/") && strings.Count(resource, "/") == 1 && strings.HasSuffix(resource, ".json") ||+ slices.Contains(declaration.Resources, resource)+}++func OpenPluginPublishResource(name, resource string) (*os.File, error) {+ if !CheckPluginAccessableInPublish(name) || !util.IsPublishRelativePath(resource) {+ return nil, ErrPluginPublishDenied+ }+ declaration, err := pluginPublishDeclaration(name)+ if err != nil || !isPluginPublishResource(declaration, resource) {+ return nil, ErrPluginPublishDenied+ }+ return util.OpenPublishFile(util.DataDir, "plugins/"+name+"/"+resource)+}++func loadPluginPublishCode(petal *Petal) bool {+ read := func(resource string) ([]byte, error) {+ file, err := OpenPluginPublishResource(petal.Name, resource)+ if err != nil {+ return nil, err+ }+ defer file.Close()+ return io.ReadAll(file)+ }+ data, err := read("index.js")+ if err != nil {+ return false+ }+ petal.JS, petal.CSS, petal.I18n, petal.Kernel = string(data), "", nil, KernelPetal{}+ if data, err = read("index.css"); err == nil {+ petal.CSS = string(data)+ }+ for _, lang := range []string{Conf.Lang, util.LangToLegacy(Conf.Lang), "en", "zh-CN", "zh_CN"} {+ if data, err = read("i18n/" + lang + ".json"); err == nil && json.Unmarshal(data, &petal.I18n) == nil {+ break+ }+ }+ return true+}++// OpenPublishPackageFile 在文件接口中处理公开文件和包资源,私有存储仍由默认拒绝策略保护。+func OpenPublishPackageFile(c *gin.Context, requestPath string) (file *os.File, handled bool, err error) {+ relative := strings.TrimPrefix(strings.ReplaceAll(requestPath, "\\", "/"), "/")+ for _, prefix := range []string{"data/public/", "data/plugins/", "data/widgets/"} {+ if !strings.HasPrefix(relative, prefix) {+ continue+ }+ if !util.IsPublishRelativePath(relative) {+ return nil, true, ErrPluginPublishDenied+ }+ resource := strings.TrimPrefix(relative, prefix)+ switch prefix {+ case "data/public/":+ file, err = util.OpenPublishFile(util.DataDir, "public/"+resource)+ case "data/plugins/":+ name, path, ok := strings.Cut(resource, "/")+ if !ok {+ return nil, true, ErrPluginPublishDenied+ }+ file, err = OpenPluginPublishResource(name, path)+ case "data/widgets/":+ name, _, ok := strings.Cut(resource, "/")+ if !ok || !CheckWidgetAccessableByPublishAccess(c, name, GetPublishAccess()) {+ return nil, true, ErrPluginPublishDenied+ }+ file, err = util.OpenPublishFile(util.DataDir, "widgets/"+resource)+ }+ return file, true, err+ }+ return nil, false, nil+}++func pluginPublishStatePath(name string) string {+ return filepath.Join(util.ConfDir, "plugin-publish", name+".json")+}++func readPluginPublishState(name string) (pluginPublishState, error) {+ state := pluginPublishState{Version: 1}+ file, err := util.OpenPublishFile(util.ConfDir, "plugin-publish/"+name+".json")+ if errors.Is(err, os.ErrNotExist) {+ return state, nil+ }+ if err != nil {+ return state, err+ }+ defer file.Close()+ content, err := io.ReadAll(io.LimitReader(file, 2*1024*1024+1))+ if err != nil {+ return state, err+ }+ state = pluginPublishState{}+ if len(content) > 2*1024*1024 || json.Unmarshal(content, &state) != nil || state.Version != 1 {+ return state, ErrPluginPublishInvalid+ }+ for field, value := range state.Data {+ value = bytes.TrimSpace(value)+ if !slices.Contains(state.Granted, field) || !json.Valid(value) || value[0] == '{' || value[0] == '[' {+ return state, ErrPluginPublishInvalid+ }+ }+ return state, nil+}++func writePluginPublishState(name string, state pluginPublishState) error {+ data, err := json.Marshal(state)+ if err != nil {+ return err+ }+ if err = os.MkdirAll(filepath.Join(util.ConfDir, "plugin-publish"), 0700); err != nil {+ return err+ }+ return gulu.File.WriteFileSafer(pluginPublishStatePath(name), data, 0600)+}++func publishFieldsGranted(declaration PluginPublishDeclaration, state pluginPublishState) bool {+ if len(declaration.Data) == 0 {+ return false+ }+ for _, field := range declaration.Data {+ if !slices.Contains(state.Granted, field) {+ return false+ }+ }+ return true+}++// 收窄声明时同步删除授权和快照中的字段,避免字段重新加入声明后恢复旧数据。+func reconcilePluginPublishState(name string, declaration PluginPublishDeclaration) (pluginPublishState, error) {+ state, err := readPluginPublishState(name)+ if err != nil {+ return state, err+ }+ changed := false+ granted := make([]string, 0, len(state.Granted))+ for _, field := range state.Granted {+ if slices.Contains(declaration.Data, field) {+ granted = append(granted, field)+ } else {+ changed = true+ delete(state.Data, field)+ }+ }+ state.Granted = granted+ if changed {+ err = writePluginPublishState(name, state)+ }+ return state, err+}++func GetPluginPublishInfo(name string) (PluginPublishInfo, error) {+ pluginPublishLock.Lock()+ defer pluginPublishLock.Unlock()+ declaration, err := pluginPublishDeclaration(name)+ if err != nil {+ return PluginPublishInfo{}, err+ }+ state, err := reconcilePluginPublishState(name, declaration)+ return PluginPublishInfo{Resources: append([]string{}, declaration.Resources...), Fields: append([]string{}, declaration.Data...),+ Granted: err == nil && publishFieldsGranted(declaration, state)}, err+}++func SetPluginPublishDataGrant(name string, fields []string, enabled bool) error {+ pluginPublishLock.Lock()+ defer pluginPublishLock.Unlock()+ declaration, err := pluginPublishDeclaration(name)+ if err != nil {+ return err+ }+ if _, err = readPluginPublishState(name); err != nil {+ return err+ }+ state := pluginPublishState{Version: 1}+ if enabled {+ slices.Sort(fields)+ if len(fields) == 0 || !slices.Equal(fields, declaration.Data) {+ return ErrPluginPublishInvalid+ }+ state.Granted = fields+ }+ return writePluginPublishState(name, state)+}++func SavePluginPublishData(name string, data map[string]json.RawMessage) error {+ pluginPublishLock.Lock()+ defer pluginPublishLock.Unlock()+ declaration, err := pluginPublishDeclaration(name)+ if err != nil {+ return err+ }+ state, err := reconcilePluginPublishState(name, declaration)+ if err != nil {+ return err+ }+ if !publishFieldsGranted(declaration, state) {+ return ErrPluginPublishDenied+ }+ if data == nil {+ return ErrPluginPublishInvalid+ }+ total := 0+ for field, value := range data {+ value = bytes.TrimSpace(value)+ total += len(value)+ if !slices.Contains(declaration.Data, field) || !json.Valid(value) || value[0] == '{' || value[0] == '[' || total > 1024*1024 {+ return ErrPluginPublishInvalid+ }+ }+ state.Data = data+ return writePluginPublishState(name, state)+}++func LoadPluginPublishData(name string) (map[string]json.RawMessage, error) {+ pluginPublishLock.Lock()+ defer pluginPublishLock.Unlock()+ if !CheckPluginAccessableInPublish(name) {+ return nil, ErrPluginPublishDenied+ }+ declaration, err := pluginPublishDeclaration(name)+ if err != nil {+ return nil, err+ }+ state, err := reconcilePluginPublishState(name, declaration)+ if err != nil {+ return nil, err+ }+ if !publishFieldsGranted(declaration, state) {+ return nil, ErrPluginPublishDenied+ }+ if state.Data == nil {+ return nil, ErrPluginPublishMissing+ }+ data := map[string]json.RawMessage{}+ for _, field := range declaration.Data {+ if value, ok := state.Data[field]; ok {+ data[field] = value+ }+ }+ return data, nil+}++// removePluginPublishData 在持有发布状态锁的卸载流程中撤销授权并删除副本,删除失败时中止卸载。+func removePluginPublishData(name string) error {+ if !bazaar.IsValidPackageName(name) {+ return ErrPluginPublishDenied+ }+ err := os.Remove(pluginPublishStatePath(name))+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ return err+}diff --git a/kernel/model/plugin_publish_test.go b/kernel/model/plugin_publish_test.gonew file mode 100644index 0000000000..96d0abb162--- /dev/null+++ b/kernel/model/plugin_publish_test.go@@ -0,0 +1,217 @@+package model++import (+ "encoding/json"+ "errors"+ "io"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func setupPluginPublishTest(t *testing.T) func(string) {+ t.Helper()+ originalData, originalConfDir, originalConf := util.DataDir, util.ConfDir, Conf+ root := t.TempDir()+ util.DataDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "conf")+ Conf = NewAppConf()+ Conf.Bazaar = &conf.Bazaar{Trust: true}+ Conf.Lang = "en"+ t.Cleanup(func() { util.DataDir, util.ConfDir, Conf = originalData, originalConfDir, originalConf })+ write := func(declaration string) {+ t.Helper()+ dir := filepath.Join(util.DataDir, "plugins", "example")+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ manifest := `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":` + declaration + `}`+ if err := os.WriteFile(filepath.Join(dir, "plugin.json"), []byte(manifest), 0644); err != nil {+ t.Fatal(err)+ }+ }+ write(`{"resources":["image.png"],"data":["theme","showAuthor"]}`)+ for name, value := range map[string]string{"index.js": "frontend", "kernel.js": "private kernel", "index.css": "body {}", "image.png": "image", "private.json": "secret"} {+ if err := os.WriteFile(filepath.Join(util.DataDir, "plugins", "example", name), []byte(value), 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ return write+}++func TestPluginPublishDataLifecycle(t *testing.T) {+ write := setupPluginPublishTest(t)+ data := map[string]json.RawMessage{"theme": json.RawMessage(`"dark"`), "showAuthor": json.RawMessage(`true`)}+ if err := SavePluginPublishData("example", data); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("ungranted write: %v", err)+ }+ if err := SetPluginPublishDataGrant("example", []string{"theme"}, true); !errors.Is(err, ErrPluginPublishInvalid) {+ t.Fatalf("stale grant: %v", err)+ }+ grant := func() {+ t.Helper()+ if err := SetPluginPublishDataGrant("example", []string{"showAuthor", "theme"}, true); err != nil {+ t.Fatal(err)+ }+ }+ grant()+ if _, err := LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishMissing) {+ t.Fatalf("missing snapshot: %v", err)+ }+ if err := SavePluginPublishData("example", data); err != nil {+ t.Fatal(err)+ }+ if err := SavePluginPublishData("example", map[string]json.RawMessage{"theme": json.RawMessage(`"light"`)}); err != nil {+ t.Fatal(err)+ }+ actual, err := LoadPluginPublishData("example")+ if err != nil || len(actual) != 1 || string(actual["theme"]) != `"light"` {+ t.Fatalf("snapshot replacement: %s %v", actual, err)+ }+ for _, invalid := range []map[string]json.RawMessage{+ {"token": json.RawMessage(`"secret"`)}, {"theme": json.RawMessage(`{"token":"secret"}`)}, {"theme": json.RawMessage(`[]`)}, {"theme": json.RawMessage(`invalid`)},+ } {+ if err := SavePluginPublishData("example", invalid); !errors.Is(err, ErrPluginPublishInvalid) {+ t.Fatalf("invalid snapshot accepted: %v", err)+ }+ }+ if actual, err = LoadPluginPublishData("example"); err != nil || string(actual["theme"]) != `"light"` {+ t.Fatalf("failed write damaged snapshot: %v", err)+ }+ if _, err = SetPetalPublishEnabled("example", false); err != nil {+ t.Fatal(err)+ }+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("disabled publish read: %v", err)+ }+ if _, err = SetPetalPublishEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ Conf.Bazaar.PetalDisabled = true+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("global disable read: %v", err)+ }+ Conf.Bazaar.PetalDisabled = false+ if _, err = SetPetalEnabled("example", false); err != nil {+ t.Fatal(err)+ }+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("disabled plugin read: %v", err)+ }+ if _, err = SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ write(`{"data":["theme","showAuthor","newField"]}`)+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("expanded scope read: %v", err)+ }+ write(`{"data":["showAuthor"]}`)+ if actual, err = LoadPluginPublishData("example"); err != nil || len(actual) != 0 {+ t.Fatalf("removed field still exposed: %v %v", actual, err)+ }+ write(`{"data":["theme","showAuthor"]}`)+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("restored field inherited removed authorization: %v", err)+ }+ if err = SetPluginPublishDataGrant("example", nil, false); err != nil {+ t.Fatal(err)+ }+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("revoked read: %v", err)+ }+ grant()+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishMissing) {+ t.Fatalf("regrant resurrected snapshot: %v", err)+ }+ if err = SavePluginPublishData("example", data); err != nil {+ t.Fatal(err)+ }+ if err = UninstallPackage("plugins", "example"); err != nil {+ t.Fatal(err)+ }+ if _, err = os.Stat(pluginPublishStatePath("example")); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("uninstall retained data: %v", err)+ }+ write(`{"data":["theme","showAuthor"]}`)+ if _, err = SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ if _, err = LoadPluginPublishData("example"); !errors.Is(err, ErrPluginPublishDenied) {+ t.Fatalf("reinstall inherited grant: %v", err)+ }+}++func TestPluginPublishCorruptionPreserved(t *testing.T) {+ setupPluginPublishTest(t)+ if err := os.MkdirAll(filepath.Dir(pluginPublishStatePath("example")), 0700); err != nil {+ t.Fatal(err)+ }+ for _, content := range []string{`{"version":99}`, `{broken`, `{}`, `{"version":1,"granted":["theme"],"data":{"theme":{"secret":1}}}`} {+ if err := os.WriteFile(pluginPublishStatePath("example"), []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+ if _, err := LoadPluginPublishData("example"); err == nil {+ t.Fatal("corrupt data accepted")+ }+ if err := SetPluginPublishDataGrant("example", []string{"theme", "showAuthor"}, true); err == nil {+ t.Fatal("corrupt state overwritten")+ }+ actual, err := os.ReadFile(pluginPublishStatePath("example"))+ if err != nil || string(actual) != content {+ t.Fatalf("original not preserved: %v", err)+ }+ }+}++func TestPluginPublishResources(t *testing.T) {+ write := setupPluginPublishTest(t)+ for _, resource := range []string{"index.js", "index.css", "image.png"} {+ file, err := OpenPluginPublishResource("example", resource)+ if err != nil {+ t.Fatalf("%s: %v", resource, err)+ }+ file.Close()+ }+ for _, resource := range []string{"kernel.js", "private.json", "plugin.json", "../example/private.json", "%2e%2e/private.json", "image.png:secret"} {+ file, err := OpenPluginPublishResource("example", resource)+ if err == nil {+ file.Close()+ t.Fatalf("unauthorized resource %s", resource)+ }+ }+ petals := LoadPetals("browser-desktop", true)+ if len(petals) != 1 || petals[0].JS != "frontend" || petals[0].Kernel.JS != "" {+ t.Fatalf("unexpected publish payload: %+v", petals)+ }+ if err := os.Remove(filepath.Join(util.DataDir, "plugins", "example", "image.png")); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(filepath.Join(util.DataDir, "plugins", "example", "private.json"), filepath.Join(util.DataDir, "plugins", "example", "image.png")); err == nil {+ if file, err := OpenPluginPublishResource("example", "image.png"); err == nil {+ file.Close()+ t.Fatal("link exposed private resource")+ }+ } else {+ t.Logf("symlink creation unavailable: %v", err)+ }+ write(`{"resources":["kernel.js"]}`)+ if file, err := OpenPluginPublishResource("example", "kernel.js"); err == nil {+ file.Close()+ t.Fatal("kernel code can be declared public")+ }+ write(`null`)+ file, err := OpenPluginPublishResource("example", "index.js")+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ data, err := io.ReadAll(file)+ if err != nil || string(data) != "frontend" {+ t.Fatal("legacy entry unavailable")+ }+}diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.goindex ef5e936371..630d10db10 100644--- a/kernel/model/publish_access.go+++ b/kernel/model/publish_access.go@@ -501,14 +501,14 @@ func CheckAbsPathAccessableByPublishAccess(c *gin.Context, absPath string, publiif gulu.File.IsSubPath(util.DataDir, absPath) {relPath, err := filepath.Rel(util.DataDir, absPath)if err != nil {- return true+ return false}relPath = strings.ReplaceAll(relPath, "\\", "/")pathParts := strings.Split(relPath, "/")if len(pathParts) <= 1 {- return true+ return false}if assetPath, box, ok := AssetPathFromDataRelativePath(relPath); ok {diff --git a/kernel/server/plugin_publish_test.go b/kernel/server/plugin_publish_test.gonew file mode 100644index 0000000000..e16d5704ef--- /dev/null+++ b/kernel/server/plugin_publish_test.go@@ -0,0 +1,75 @@+package server++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestPluginPublishStaticBoundaries(t *testing.T) {+ oldData, oldConf := util.DataDir, model.Conf+ util.DataDir = t.TempDir()+ model.Conf = model.NewAppConf()+ model.Conf.Bazaar = &conf.Bazaar{Trust: true}+ t.Cleanup(func() { util.DataDir, model.Conf = oldData, oldConf })+ for name, data := range map[string]string{+ "plugins/example/plugin.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":{"resources":["index.html","logo.txt"]}}`,+ "plugins/example/index.js": "entry", "plugins/example/index.html": "page", "plugins/example/logo.txt": "logo", "plugins/example/kernel.js": "secret",+ "public/file.txt": "public", "storage/petal/example/private.json": "token",+ } {+ path := filepath.Join(util.DataDir, filepath.FromSlash(name))+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(data), 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := model.SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleReader); c.Next() })+ servePlugins(engine)+ servePublic(engine)+ request := func(method, path string) *httptest.ResponseRecorder {+ r := httptest.NewRecorder()+ engine.ServeHTTP(r, httptest.NewRequest(method, path, nil))+ return r+ }+ for path, want := range map[string]string{"/plugins/example/index.js": "entry", "/plugins/example/": "page", "/plugins/example/logo.txt": "logo", "/public/file.txt": "public"} {+ if r := request("GET", path); r.Code != 200 || r.Body.String() != want {+ t.Fatalf("%s: %d %s", path, r.Code, r.Body)+ }+ if r := request("HEAD", path); r.Code != 200 || r.Body.Len() != 0 {+ t.Fatalf("HEAD %s: %d %s", path, r.Code, r.Body)+ }+ }+ for _, path := range []string{"/plugins/example/kernel.js", "/plugins/example/plugin.json", "/plugins/example/../example/kernel.js", "/plugins/example/%2e%2e/example/kernel.js", "/plugins/example/%252e%252e/example/kernel.js", "/plugins/example/logo.txt:stream"} {+ if r := request("GET", path); r.Code != http.StatusForbidden {+ t.Fatalf("denied %s: %d %s", path, r.Code, r.Body)+ }+ }+ if err := os.Symlink(filepath.Join(util.DataDir, "storage", "petal", "example", "private.json"), filepath.Join(util.DataDir, "public", "link.txt")); err == nil {+ if r := request("GET", "/public/link.txt"); r.Code != 404 {+ t.Fatalf("public link: %d %s", r.Code, r.Body)+ }+ } else {+ t.Logf("symlinks unavailable: %v", err)+ }+ if _, err := model.SetPetalPublishEnabled("example", false); err != nil {+ t.Fatal(err)+ }+ for _, method := range []string{"GET", "HEAD"} {+ if r := request(method, "/plugins/example/logo.txt"); r.Code != 403 || r.Header().Get("Cache-Control") != "private, no-store" {+ t.Fatalf("disabled static resource: %d", r.Code)+ }+ }+}diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex a556ef6a6d..8f1883d46e 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -447,11 +447,20 @@ func serveWidgets(ginServer *gin.Engine) {widgets := ginServer.Group("/widgets/", model.CheckAuth)registerStaticFileHandlers(widgets, filepath.Join(util.DataDir, "widgets"), true, func(c *gin.Context, relativePath string) bool {if model.IsReadOnlyRoleContext(c) {- name, _, _ := strings.Cut(filepath.ToSlash(relativePath), "/")+ c.Header("Cache-Control", "private, no-store")+ resource := strings.TrimPrefix(c.Param("filepath"), "/")+ if strings.HasSuffix(resource, "/") {+ resource += "index.html"+ }+ name, _, _ := strings.Cut(resource, "/")if !model.CheckWidgetAccessableByPublishAccess(c, name, model.GetPublishAccess()) {- c.Header("Cache-Control", "private, no-store")return false}+ file, err := util.OpenPublishFile(util.DataDir, "widgets/"+resource)+ if err != nil {+ return false+ }+ return serveOpenedPublishFile(c, file, resource)}setWidgetCacheControl(c, relativePath)return true@@ -473,11 +482,34 @@ func servePlugins(ginServer *gin.Engine) {if !model.IsReadOnlyRoleContext(c) {return true}- name, _, _ := strings.Cut(filepath.ToSlash(relativePath), "/")- return model.CheckPluginAccessableInPublish(name)+ c.Header("Cache-Control", "private, no-store")+ requestPath := strings.TrimPrefix(c.Param("filepath"), "/")+ if strings.HasSuffix(requestPath, "/") {+ requestPath += "index.html"+ }+ name, resource, ok := strings.Cut(requestPath, "/")+ if !ok {+ return false+ }+ file, err := model.OpenPluginPublishResource(name, resource)+ if err != nil {+ return false+ }+ return serveOpenedPublishFile(c, file, resource)})}+func serveOpenedPublishFile(c *gin.Context, file *os.File, resource string) bool {+ defer file.Close()+ info, err := file.Stat()+ if err != nil {+ return false+ }+ http.ServeContent(c.Writer, c.Request, resource, info.ModTime(), file)+ c.Abort()+ return true+}+func serveBootAppearanceAssets(ginServer *gin.Engine) {handler := func(c *gin.Context) {c.Header("Cache-Control", "no-store")@@ -520,7 +552,26 @@ func serveTemplates(ginServer *gin.Engine) {func servePublic(ginServer *gin.Engine) {// Support directly access `data/public/*` contents via URL link https://github.com/siyuan-note/siyuan/issues/8593- ginServer.Static("/public/", filepath.Join(util.DataDir, "public"))+ handler := func(c *gin.Context) {+ relative := strings.TrimPrefix(c.Param("filepath"), "/")+ if relative == "" || strings.HasSuffix(relative, "/") {+ relative += "index.html"+ }+ file, err := util.OpenPublishFile(util.DataDir, "public/"+relative)+ if err != nil {+ c.Status(http.StatusNotFound)+ return+ }+ defer file.Close()+ info, err := file.Stat()+ if err != nil {+ c.Status(http.StatusNotFound)+ return+ }+ http.ServeContent(c.Writer, c.Request, relative, info.ModTime(), file)+ }+ ginServer.GET("/public/*filepath", handler)+ ginServer.HEAD("/public/*filepath", handler)}func serveSnippets(ginServer *gin.Engine) {@@ -585,6 +636,9 @@ func registerStaticFileHandlers(group *gin.RouterGroup, root string, packageScopc.Status(http.StatusForbidden)return}+ if c.IsAborted() {+ return+ }serveStaticFile(c, root, relativePath, packageScoped)}group.GET("/*filepath", handler)diff --git a/kernel/util/path_guard.go b/kernel/util/path_guard.goindex 260ed1f687..b85df322c6 100644--- a/kernel/util/path_guard.go+++ b/kernel/util/path_guard.go@@ -31,6 +31,11 @@ import (// data/.siyuan/publishAccess.json、笔记本目录下的 .siyuan 内部文件以及 temp 目录下的 siyuan.log 日志文件。func IsForbiddenAbsPath(abs string) bool {fileNorm := NormalizeAndResolve(abs)+ // 插件发布授权及快照只能通过专用接口读取,其他原始文件和静态资源入口不得暴露它们。+ publishRoot := NormalizeAndResolve(filepath.Join(ConfDir, "plugin-publish"))+ if fileNorm == publishRoot || strings.HasPrefix(fileNorm, publishRoot+string(filepath.Separator)) {+ return true+ }// 禁止访问日志文件 siyuan.log:Timing 中间件可能把含 API token 的查询串写入日志(如慢查询告警),// 日志被任意已认证用户读取即等于泄露管理员凭据,因此即使日志不再记录查询串也保持拦截diff --git a/kernel/util/publish_file.go b/kernel/util/publish_file.gonew file mode 100644index 0000000000..42f38a068f--- /dev/null+++ b/kernel/util/publish_file.go@@ -0,0 +1,72 @@+package util++import (+ "io/fs"+ "os"+ "strings"+)++// IsPublishRelativePath 限定发布资源使用无歧义的相对路径,各平台采用相同的分段规则。+func IsPublishRelativePath(name string) bool {+ if name == "" || strings.ContainsAny(name, "\\:%\x00") {+ return false+ }+ for _, part := range strings.Split(name, "/") {+ if part == "" || part == "." || part == ".." || strings.TrimSpace(part) != part || strings.HasSuffix(part, ".") {+ return false+ }+ }+ return true+}++// OpenPublishFile 在已打开的目录句柄内逐级读取,拒绝链接和非普通文件,并校验打开前后的文件身份。+// 即使路径在检查后被替换,读取也不会转向链接目标或授权目录之外。+func OpenPublishFile(rootPath, name string) (*os.File, error) {+ if !IsPublishRelativePath(name) {+ return nil, fs.ErrPermission+ }+ root, err := os.OpenRoot(rootPath)+ if err != nil {+ return nil, err+ }+ defer func() { root.Close() }()+ parts := strings.Split(name, "/")+ for _, part := range parts[:len(parts)-1] {+ info, statErr := root.Lstat(part)+ if statErr != nil {+ return nil, statErr+ }+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {+ return nil, fs.ErrPermission+ }+ next, openErr := root.OpenRoot(part)+ if openErr != nil {+ return nil, openErr+ }+ actual, actualErr := next.Stat(".")+ if actualErr != nil || !os.SameFile(info, actual) {+ next.Close()+ return nil, fs.ErrPermission+ }+ root.Close()+ root = next+ }+ leaf := parts[len(parts)-1]+ info, err := root.Lstat(leaf)+ if err != nil {+ return nil, err+ }+ if !info.Mode().IsRegular() {+ return nil, fs.ErrPermission+ }+ file, err := root.Open(leaf)+ if err != nil {+ return nil, err+ }+ actual, err := file.Stat()+ if err != nil || !actual.Mode().IsRegular() || !os.SameFile(info, actual) {+ file.Close()+ return nil, fs.ErrPermission+ }+ return file, nil+}diff --git a/kernel/util/publish_file_test.go b/kernel/util/publish_file_test.gonew file mode 100644index 0000000000..f1a456b389--- /dev/null+++ b/kernel/util/publish_file_test.go@@ -0,0 +1,52 @@+package util++import (+ "io"+ "os"+ "path/filepath"+ "testing"+)++func TestPublishFileBoundary(t *testing.T) {+ root := t.TempDir()+ if err := os.MkdirAll(filepath.Join(root, "public", "nested"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(root, "public", "nested", "ok.txt"), []byte("ok"), 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(root, "private.txt"), []byte("secret"), 0644); err != nil {+ t.Fatal(err)+ }+ file, err := OpenPublishFile(root, "public/nested/ok.txt")+ if err != nil {+ t.Fatal(err)+ }+ data, err := io.ReadAll(file)+ file.Close()+ if err != nil || string(data) != "ok" {+ t.Fatal("regular read failed")+ }+ for _, name := range []string{"../private.txt", "public/../private.txt", "/private.txt", "public//nested/ok.txt", "public/nested/ok.txt:stream", "public/%2e%2e/private.txt", "public\\nested\\ok.txt", "public/nested/ok.txt.", "public/nested/ok.txt ", "public/nested"} {+ if file, err := OpenPublishFile(root, name); err == nil {+ file.Close()+ t.Fatalf("accepted %q", name)+ }+ }+ t.Run("symlinks", func(t *testing.T) {+ if err := os.Symlink(filepath.Join(root, "private.txt"), filepath.Join(root, "public", "link")); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ if file, err := OpenPublishFile(root, "public/link"); err == nil {+ file.Close()+ t.Fatal("file link accepted")+ }+ if err := os.Symlink(filepath.Join(root, "public", "nested"), filepath.Join(root, "public", "dirlink")); err != nil {+ t.Fatal(err)+ }+ if file, err := OpenPublishFile(root, "public/dirlink/ok.txt"); err == nil {+ file.Close()+ t.Fatal("directory link accepted")+ }+ })+}diff --git a/kernel/util/publish_file_windows_test.go b/kernel/util/publish_file_windows_test.gonew file mode 100644index 0000000000..e71b78a697--- /dev/null+++ b/kernel/util/publish_file_windows_test.go@@ -0,0 +1,28 @@+//go:build windows++package util++import (+ "os"+ "os/exec"+ "path/filepath"+ "testing"+)++func TestPublishFileJunctionBoundary(t *testing.T) {+ root, outside := t.TempDir(), t.TempDir()+ if err := os.MkdirAll(filepath.Join(root, "public"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0644); err != nil {+ t.Fatal(err)+ }+ junction := filepath.Join(root, "public", "linked")+ if out, err := exec.Command("cmd", "/c", "mklink", "/J", junction, outside).CombinedOutput(); err != nil {+ t.Skipf("junction creation unavailable: %v %s", err, out)+ }+ if file, err := OpenPublishFile(root, "public/linked/secret.txt"); err == nil {+ file.Close()+ t.Fatal("junction target was exposed")+ }+}