Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/webext: open a verified document with Bento ID, in a sandbox (bento/connect W2) (#844)
nyblnet6490ff56f546
diff --git a/.github/actions/validate-home-webext/action.yml b/.github/actions/validate-home-webext/action.ymlindex b906300d..9f3de6af 100644--- a/.github/actions/validate-home-webext/action.yml+++ b/.github/actions/validate-home-webext/action.yml@@ -149,6 +149,16 @@ runs:shell: bento-step {0}run: node scripts/test-webext-id.ts+ - name: WebExtension served-document rig+ # Opening a file WITH identity (bento/connect W2): the signed release+ # histories are verified, anti-rollback held and fetched no more than+ # daily, never before first use; a file is GENUINE only if exactly one+ # held history matches it (every held history is tried, never one the+ # document names); only the scanner's executable elements become blob:+ # scripts; and the host acts only on fixed-shape requests on its port.+ shell: bento-step {0}+ run: node scripts/test-webext-serve.ts+- name: WebExtension localisation rig# Every failure mode of a message catalogue is silent: a key the code# uses but English lacks renders as the key name, a locale missing a keydiff --git a/home/webext/_locales/ar/messages.json b/home/webext/_locales/ar/messages.jsonindex afe05904..e875de82 100644--- a/home/webext/_locales/ar/messages.json+++ b/home/webext/_locales/ar/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "لم يُعدّ شيء: لا يستطيع مفتاح المرور فتح Bento ID ولا يستطيع هذا الجهاز إنشاء رمز استرداد، فلن يكون هناك طريق للعودة."+ },+ "setIdServe": {+ "message": "الفتح باستخدام Bento ID (معاينة)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "يضيف «الفتح باستخدام Bento ID» إلى قائمة المستند: يُفتح المستند في صفحة محمية يمكنها استخدام Bento ID. لا يتأثر فتح الملف بالنقر المزدوج.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "الفتح باستخدام Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/bn/messages.json b/home/webext/_locales/bn/messages.jsonindex b058714b..d2b90cb8 100644--- a/home/webext/_locales/bn/messages.json+++ b/home/webext/_locales/bn/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "কিছুই সেট আপ হয়নি: আপনার পাসকি Bento ID খুলতে পারে না এবং এই ডিভাইস রিকভারি কোড তৈরি করতে পারে না, তাই ফিরে আসার কোনো পথ থাকত না।"+ },+ "setIdServe": {+ "message": "Bento ID দিয়ে খুলুন (প্রিভিউ)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "ডকুমেন্টের মেনুতে “Bento ID দিয়ে খুলুন” যোগ করে: ডকুমেন্টটি একটি সুরক্ষিত পাতায় খোলে যা আপনার Bento ID ব্যবহার করতে পারে। ফাইলে ডাবল-ক্লিক করায় কোনো পরিবর্তন হয় না।",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Bento ID দিয়ে খুলুন",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/da/messages.json b/home/webext/_locales/da/messages.jsonindex 43038e9d..2fb69143 100644--- a/home/webext/_locales/da/messages.json+++ b/home/webext/_locales/da/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Intet blev sat op: din adgangsnøgle kan ikke låse dit Bento ID op, og denne enhed kan ikke lave en gendannelseskode, så der ville ikke være nogen vej tilbage."+ },+ "setIdServe": {+ "message": "Åbn med Bento ID (forhåndsvisning)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Tilføjer “Åbn med Bento ID” til et dokuments menu: dokumentet åbnes på en beskyttet side, der kan bruge dit Bento ID. Dobbeltklik på en fil påvirkes ikke.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Åbn med Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/de/messages.json b/home/webext/_locales/de/messages.jsonindex 8637b0b8..70f11811 100644--- a/home/webext/_locales/de/messages.json+++ b/home/webext/_locales/de/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "Nichts wurde eingerichtet: Ihr Passkey kann Ihre Bento ID nicht entsperren und dieses Gerät kann keinen Wiederherstellungscode erstellen – es gäbe keinen Weg zurück."+ },+ "setIdServe": {+ "message": "Mit Bento ID öffnen (Vorschau)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Fügt dem Menü eines Dokuments „Mit Bento ID öffnen“ hinzu: Das Dokument öffnet sich auf einer geschützten Seite, die deine Bento ID verwenden kann. Doppelklicken auf eine Datei bleibt unverändert.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Mit Bento ID öffnen",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/en/messages.json b/home/webext/_locales/en/messages.jsonindex afa9df91..a6da73a8 100644--- a/home/webext/_locales/en/messages.json+++ b/home/webext/_locales/en/messages.json@@ -1142,5 +1142,17 @@"idErrNoWayBack": {"message": "Nothing was set up: your passkey can't unlock your Bento ID and this device can't make a recovery code, so there would be no way back.","description": "Setup error: neither recovery path is available."+ },+ "setIdServe": {+ "message": "Open with Bento ID (preview)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Adds “Open with Bento ID” to a document's menu: the document opens in a protected page that can use your Bento ID. Double-clicking a file is not affected.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Open with Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/es/messages.json b/home/webext/_locales/es/messages.jsonindex 0c159979..015904b5 100644--- a/home/webext/_locales/es/messages.json+++ b/home/webext/_locales/es/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "No se ha configurado nada: tu llave de acceso no puede desbloquear tu Bento ID y este dispositivo no puede crear un código de recuperación, así que no habría forma de volver."+ },+ "setIdServe": {+ "message": "Abrir con Bento ID (vista previa)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Añade «Abrir con Bento ID» al menú de un documento: el documento se abre en una página protegida que puede usar tu Bento ID. Hacer doble clic en un archivo no cambia.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Abrir con Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/fa/messages.json b/home/webext/_locales/fa/messages.jsonindex 637754c5..adb833f3 100644--- a/home/webext/_locales/fa/messages.json+++ b/home/webext/_locales/fa/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "چیزی راهاندازی نشد: گذرکلید شما نمیتواند Bento ID را باز کند و این دستگاه نمیتواند کد بازیابی بسازد، پس راه بازگشتی نمیماند."+ },+ "setIdServe": {+ "message": "باز کردن با Bento ID (پیشنمایش)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "گزینهٔ «باز کردن با Bento ID» را به منوی سند اضافه میکند: سند در صفحهای محافظتشده باز میشود که میتواند از Bento ID شما استفاده کند. دوبار کلیک روی فایل تغییری نمیکند.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "باز کردن با Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/fi/messages.json b/home/webext/_locales/fi/messages.jsonindex 3cc00d07..28efb7ef 100644--- a/home/webext/_locales/fi/messages.json+++ b/home/webext/_locales/fi/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Mitään ei otettu käyttöön: pääsyavaimesi ei voi avata Bento ID:täsi eikä tämä laite voi luoda palautuskoodia, joten takaisin ei olisi mitään tietä."+ },+ "setIdServe": {+ "message": "Avaa Bento ID:llä (esikatselu)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Lisää asiakirjan valikkoon ”Avaa Bento ID:llä”: asiakirja avautuu suojatulle sivulle, joka voi käyttää Bento ID:täsi. Tiedoston kaksoisnapsautus ei muutu.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Avaa Bento ID:llä",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/fil/messages.json b/home/webext/_locales/fil/messages.jsonindex 1a6ff944..66dd22fb 100644--- a/home/webext/_locales/fil/messages.json+++ b/home/webext/_locales/fil/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Walang na-set up: hindi kayang i-unlock ng iyong passkey ang Bento ID at hindi makagawa ng recovery code ang device na ito, kaya walang magiging daan pabalik."+ },+ "setIdServe": {+ "message": "Buksan gamit ang Bento ID (preview)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Nagdadagdag ng “Buksan gamit ang Bento ID” sa menu ng dokumento: bubukas ang dokumento sa isang protektadong page na puwedeng gumamit ng iyong Bento ID. Hindi naaapektuhan ang pag-double-click sa file.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Buksan gamit ang Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/fr/messages.json b/home/webext/_locales/fr/messages.jsonindex 7661766b..71eb03b9 100644--- a/home/webext/_locales/fr/messages.json+++ b/home/webext/_locales/fr/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "Rien n’a été configuré : votre clé d’accès ne peut pas déverrouiller votre Bento ID et cet appareil ne peut pas créer de code de récupération, il n’y aurait donc aucun moyen de revenir."+ },+ "setIdServe": {+ "message": "Ouvrir avec Bento ID (aperçu)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Ajoute « Ouvrir avec Bento ID » au menu d’un document : le document s’ouvre dans une page protégée qui peut utiliser votre Bento ID. Le double-clic sur un fichier n’est pas modifié.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Ouvrir avec Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/he/messages.json b/home/webext/_locales/he/messages.jsonindex 4355b315..2ac35ee6 100644--- a/home/webext/_locales/he/messages.json+++ b/home/webext/_locales/he/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "שום דבר לא הוגדר: מפתח הגישה לא יכול לפתוח את ה־Bento ID והמכשיר הזה לא יכול ליצור קוד שחזור, כך שלא הייתה דרך חזרה."+ },+ "setIdServe": {+ "message": "פתיחה עם Bento ID (תצוגה מקדימה)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "מוסיף „פתיחה עם Bento ID” לתפריט של מסמך: המסמך נפתח בדף מוגן שיכול להשתמש ב-Bento ID שלך. לחיצה כפולה על קובץ לא משתנה.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "פתיחה עם Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/hi/messages.json b/home/webext/_locales/hi/messages.jsonindex 755c17fb..d6f55ef8 100644--- a/home/webext/_locales/hi/messages.json+++ b/home/webext/_locales/hi/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "कुछ सेट नहीं हुआ: आपकी पासकी Bento ID नहीं खोल सकती और यह डिवाइस रिकवरी कोड नहीं बना सकता, इसलिए वापसी का कोई रास्ता नहीं रहता।"+ },+ "setIdServe": {+ "message": "Bento ID से खोलें (प्रीव्यू)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "दस्तावेज़ के मेनू में “Bento ID से खोलें” जोड़ता है: दस्तावेज़ एक सुरक्षित पेज में खुलता है जो आपकी Bento ID का उपयोग कर सकता है। फ़ाइल पर डबल-क्लिक करने पर कोई असर नहीं पड़ता।",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Bento ID से खोलें",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/id/messages.json b/home/webext/_locales/id/messages.jsonindex 1e9b55f8..3aff471a 100644--- a/home/webext/_locales/id/messages.json+++ b/home/webext/_locales/id/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Tidak ada yang disiapkan: kunci sandi Anda tidak dapat membuka Bento ID dan perangkat ini tidak dapat membuat kode pemulihan, jadi tidak akan ada jalan kembali."+ },+ "setIdServe": {+ "message": "Buka dengan Bento ID (pratinjau)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Menambahkan “Buka dengan Bento ID” ke menu dokumen: dokumen terbuka di halaman terlindungi yang dapat memakai Bento ID Anda. Klik dua kali pada file tidak berubah.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Buka dengan Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/it/messages.json b/home/webext/_locales/it/messages.jsonindex eafbf38e..be0d2aaa 100644--- a/home/webext/_locales/it/messages.json+++ b/home/webext/_locales/it/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "Non è stato configurato nulla: la tua passkey non può sbloccare il tuo Bento ID e questo dispositivo non può creare un codice di recupero, quindi non ci sarebbe modo di tornare."+ },+ "setIdServe": {+ "message": "Apri con Bento ID (anteprima)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Aggiunge «Apri con Bento ID» al menu di un documento: il documento si apre in una pagina protetta che può usare il tuo Bento ID. Il doppio clic su un file non cambia.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Apri con Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/ja/messages.json b/home/webext/_locales/ja/messages.jsonindex 0ffb6038..76cf3acf 100644--- a/home/webext/_locales/ja/messages.json+++ b/home/webext/_locales/ja/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "何も設定されていません。このパスキーでは Bento ID のロックを解除できず、このデバイスでは復元コードも作れないため、取り戻す手段がなくなってしまいます。"+ },+ "setIdServe": {+ "message": "Bento ID で開く(プレビュー)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "書類のメニューに「Bento ID で開く」を追加します。書類は Bento ID を使える保護されたページで開きます。ファイルのダブルクリックは変わりません。",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Bento ID で開く",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/ko/messages.json b/home/webext/_locales/ko/messages.jsonindex e0545acc..71fa69a8 100644--- a/home/webext/_locales/ko/messages.json+++ b/home/webext/_locales/ko/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "아무것도 설정되지 않았습니다. 이 패스키로는 Bento ID를 잠금 해제할 수 없고 이 기기에서는 복구 코드도 만들 수 없어, 되찾을 방법이 없게 됩니다."+ },+ "setIdServe": {+ "message": "Bento ID로 열기(미리 보기)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "문서 메뉴에 ‘Bento ID로 열기’를 추가합니다. 문서가 Bento ID를 사용할 수 있는 보호된 페이지에서 열립니다. 파일을 더블클릭하는 동작은 바뀌지 않습니다.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Bento ID로 열기",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/ms/messages.json b/home/webext/_locales/ms/messages.jsonindex 8012c2f1..34cf96d7 100644--- a/home/webext/_locales/ms/messages.json+++ b/home/webext/_locales/ms/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Tiada apa-apa disediakan: kunci laluan anda tidak dapat membuka Bento ID dan peranti ini tidak dapat mencipta kod pemulihan, jadi tiada jalan kembali."+ },+ "setIdServe": {+ "message": "Buka dengan Bento ID (pratonton)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Menambah “Buka dengan Bento ID” pada menu dokumen: dokumen dibuka dalam halaman terlindung yang boleh menggunakan Bento ID anda. Klik dua kali pada fail tidak terjejas.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Buka dengan Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/nb/messages.json b/home/webext/_locales/nb/messages.jsonindex e7b8b88b..9fa5d6b6 100644--- a/home/webext/_locales/nb/messages.json+++ b/home/webext/_locales/nb/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Ingenting ble satt opp: tilgangsnøkkelen din kan ikke låse opp Bento ID-en, og denne enheten kan ikke lage en gjenopprettingskode, så det ville ikke vært noen vei tilbake."+ },+ "setIdServe": {+ "message": "Åpne med Bento ID (forhåndsvisning)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Legger til «Åpne med Bento ID» i menyen til et dokument: dokumentet åpnes på en beskyttet side som kan bruke Bento ID-en din. Dobbeltklikk på en fil endres ikke.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Åpne med Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/nl/messages.json b/home/webext/_locales/nl/messages.jsonindex 9424b206..81b37f99 100644--- a/home/webext/_locales/nl/messages.json+++ b/home/webext/_locales/nl/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Er is niets ingesteld: je toegangssleutel kan je Bento ID niet ontgrendelen en dit apparaat kan geen herstelcode maken, dus er zou geen weg terug zijn."+ },+ "setIdServe": {+ "message": "Openen met Bento ID (preview)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Voegt ‘Openen met Bento ID’ toe aan het menu van een document: het document opent in een beschermde pagina die je Bento ID kan gebruiken. Dubbelklikken op een bestand verandert niet.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Openen met Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/pl/messages.json b/home/webext/_locales/pl/messages.jsonindex 57d793e2..15dcf440 100644--- a/home/webext/_locales/pl/messages.json+++ b/home/webext/_locales/pl/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Nic nie zostało skonfigurowane: klucz dostępu nie może odblokować Bento ID, a to urządzenie nie może utworzyć kodu odzyskiwania, więc nie byłoby drogi powrotu."+ },+ "setIdServe": {+ "message": "Otwórz z Bento ID (wersja próbna)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Dodaje „Otwórz z Bento ID” do menu dokumentu: dokument otwiera się na chronionej stronie, która może używać Twojego Bento ID. Dwukrotne kliknięcie pliku działa bez zmian.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Otwórz z Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/pt_BR/messages.json b/home/webext/_locales/pt_BR/messages.jsonindex cb7d6b9e..456a45d1 100644--- a/home/webext/_locales/pt_BR/messages.json+++ b/home/webext/_locales/pt_BR/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "Nada foi configurado: sua chave de acesso não consegue desbloquear seu Bento ID e este dispositivo não consegue criar um código de recuperação, então não haveria caminho de volta."+ },+ "setIdServe": {+ "message": "Abrir com Bento ID (prévia)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Adiciona “Abrir com Bento ID” ao menu de um documento: o documento abre em uma página protegida que pode usar seu Bento ID. Clicar duas vezes em um arquivo não muda.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Abrir com Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/ru/messages.json b/home/webext/_locales/ru/messages.jsonindex dc64eb43..7c95f741 100644--- a/home/webext/_locales/ru/messages.json+++ b/home/webext/_locales/ru/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Ничего не настроено: ключ доступа не может разблокировать Bento ID, а это устройство не может создать код восстановления, поэтому пути назад не было бы."+ },+ "setIdServe": {+ "message": "Открыть с Bento ID (предварительная версия)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Добавляет «Открыть с Bento ID» в меню документа: документ открывается на защищённой странице, которая может использовать ваш Bento ID. Двойной щелчок по файлу работает как прежде.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Открыть с Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/sv/messages.json b/home/webext/_locales/sv/messages.jsonindex 405f10eb..98924cab 100644--- a/home/webext/_locales/sv/messages.json+++ b/home/webext/_locales/sv/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Inget konfigurerades: din nyckel kan inte låsa upp ditt Bento ID och den här enheten kan inte skapa en återställningskod, så det skulle inte finnas någon väg tillbaka."+ },+ "setIdServe": {+ "message": "Öppna med Bento ID (förhandsversion)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Lägger till ”Öppna med Bento ID” i ett dokuments meny: dokumentet öppnas på en skyddad sida som kan använda ditt Bento ID. Att dubbelklicka på en fil påverkas inte.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Öppna med Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/th/messages.json b/home/webext/_locales/th/messages.jsonindex b703c48e..43d3ca50 100644--- a/home/webext/_locales/th/messages.json+++ b/home/webext/_locales/th/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "ไม่ได้ตั้งค่าอะไรเลย: พาสคีย์ของคุณปลดล็อก Bento ID ไม่ได้ และอุปกรณ์นี้สร้างรหัสกู้คืนไม่ได้ จึงจะไม่มีทางกลับ"+ },+ "setIdServe": {+ "message": "เปิดด้วย Bento ID (ตัวอย่าง)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "เพิ่ม “เปิดด้วย Bento ID” ในเมนูของเอกสาร: เอกสารจะเปิดในหน้าที่ได้รับการป้องกันซึ่งใช้ Bento ID ของคุณได้ การดับเบิลคลิกไฟล์ไม่เปลี่ยนแปลง",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "เปิดด้วย Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/tr/messages.json b/home/webext/_locales/tr/messages.jsonindex 8a6aff9c..3c02b4fd 100644--- a/home/webext/_locales/tr/messages.json+++ b/home/webext/_locales/tr/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Hiçbir şey kurulmadı: geçiş anahtarınız Bento ID'nizin kilidini açamıyor ve bu cihaz kurtarma kodu oluşturamıyor, dolayısıyla geri dönüş yolu olmazdı."+ },+ "setIdServe": {+ "message": "Bento ID ile aç (önizleme)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Bir belgenin menüsüne “Bento ID ile aç” ekler: belge, Bento ID’nizi kullanabilen korumalı bir sayfada açılır. Bir dosyaya çift tıklamak değişmez.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Bento ID ile aç",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/uk/messages.json b/home/webext/_locales/uk/messages.jsonindex d6a51e13..06b5ff6d 100644--- a/home/webext/_locales/uk/messages.json+++ b/home/webext/_locales/uk/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Нічого не налаштовано: ключ доступу не може розблокувати Bento ID, а цей пристрій не може створити код відновлення, тож шляху назад не було б."+ },+ "setIdServe": {+ "message": "Відкрити з Bento ID (попередня версія)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Додає «Відкрити з Bento ID» до меню документа: документ відкривається на захищеній сторінці, яка може використовувати ваш Bento ID. Подвійне клацання по файлу працює як раніше.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Відкрити з Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/ur/messages.json b/home/webext/_locales/ur/messages.jsonindex 70e32049..52e059f5 100644--- a/home/webext/_locales/ur/messages.json+++ b/home/webext/_locales/ur/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "کچھ سیٹ اپ نہیں ہوا: آپ کی پاس کی Bento ID نہیں کھول سکتی اور یہ آلہ ریکوری کوڈ نہیں بنا سکتا، اس لیے واپسی کا کوئی راستہ نہ رہتا۔"+ },+ "setIdServe": {+ "message": "Bento ID کے ساتھ کھولیں (پیش نظارہ)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "دستاویز کے مینو میں “Bento ID کے ساتھ کھولیں” شامل کرتا ہے: دستاویز ایک محفوظ صفحے میں کھلتی ہے جو آپ کی Bento ID استعمال کر سکتا ہے۔ فائل پر ڈبل کلک کرنے پر کوئی فرق نہیں پڑتا۔",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Bento ID کے ساتھ کھولیں",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/vi/messages.json b/home/webext/_locales/vi/messages.jsonindex 605b3395..7a3f3892 100644--- a/home/webext/_locales/vi/messages.json+++ b/home/webext/_locales/vi/messages.json@@ -934,5 +934,17 @@},"idErrNoWayBack": {"message": "Chưa thiết lập gì: khóa truy cập của bạn không mở được Bento ID và thiết bị này không tạo được mã khôi phục, nên sẽ không có cách quay lại."+ },+ "setIdServe": {+ "message": "Mở bằng Bento ID (xem trước)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "Thêm “Mở bằng Bento ID” vào menu của tài liệu: tài liệu mở trong một trang được bảo vệ có thể dùng Bento ID của bạn. Nhấp đúp vào tệp không thay đổi.",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "Mở bằng Bento ID",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/zh_CN/messages.json b/home/webext/_locales/zh_CN/messages.jsonindex 8d1123ac..23263e68 100644--- a/home/webext/_locales/zh_CN/messages.json+++ b/home/webext/_locales/zh_CN/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "没有完成设置:你的通行密钥无法解锁 Bento ID,而此设备也无法生成恢复码,这样将无法找回。"+ },+ "setIdServe": {+ "message": "使用 Bento ID 打开(预览)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "在文档菜单中添加“使用 Bento ID 打开”:文档会在可使用你的 Bento ID 的受保护页面中打开。双击文件的行为不变。",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "使用 Bento ID 打开",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/_locales/zh_TW/messages.json b/home/webext/_locales/zh_TW/messages.jsonindex aed48087..5ab2ca8f 100644--- a/home/webext/_locales/zh_TW/messages.json+++ b/home/webext/_locales/zh_TW/messages.json@@ -967,5 +967,17 @@},"idErrNoWayBack": {"message": "沒有完成設定:你的密碼金鑰無法解鎖 Bento ID,而此裝置也無法產生復原碼,這樣將無法找回。"+ },+ "setIdServe": {+ "message": "使用 Bento ID 開啟(預覽)",+ "description": "Library settings, Bento ID section: checkbox, off by default; turns on the preview of opening documents with a Bento ID."+ },+ "setIdServeNote": {+ "message": "在文件選單中加入「使用 Bento ID 開啟」:文件會在可使用你的 Bento ID 的受保護頁面中開啟。按兩下檔案的行為不變。",+ "description": "Library settings: note under that checkbox."+ },+ "menuOpenWithId": {+ "message": "使用 Bento ID 開啟",+ "description": "Library: an item in a document card's menu (only when the preview is on)."}}diff --git a/home/webext/manifest.json b/home/webext/manifest.jsonindex c6f32a61..1ebef029 100644--- a/home/webext/manifest.json+++ b/home/webext/manifest.json@@ -78,5 +78,14 @@"default_locale": "en","host_permissions": ["file:///*"- ]+ ],+ "sandbox": {+ "pages": [+ "src/serve/sandbox.html"+ ]+ },+ "content_security_policy": {+ "extension_pages": "script-src 'self'; object-src 'self'",+ "sandbox": "sandbox allow-scripts allow-modals allow-popups allow-popups-to-escape-sandbox; default-src 'none'; script-src 'self' blob:; style-src 'unsafe-inline'; img-src data: blob: https:; media-src data: blob: https:; font-src data: blob:; connect-src https://bento.page https://sync.bento.page wss://sync.bento.page; frame-src https:; object-src 'none'; base-uri 'none'; form-action 'none'; worker-src 'none'"+ }}diff --git a/home/webext/src/background.js b/home/webext/src/background.jsindex 0d6ff097..26ee7d92 100644--- a/home/webext/src/background.js+++ b/home/webext/src/background.js@@ -643,6 +643,26 @@ export function serveAssistantPort(port) {})}+// ---------------------------------------------------------------- served documents+//+// bento/connect W2: a document opened WITH identity runs in the extension's+// sandbox page, so its ⌘S reaches the worker from the host page+// (serve/serve.js), not from a file:// content script. Only that page may ask,+// and it names the path it opened; the write then goes exactly as a file://+// page's would (resolveAny on that path's URL), so the same grants and doors+// apply and nothing new is reachable.+async function serveWrite(sender, payload) {+ const ours = sender?.id === chrome.runtime.id && typeof sender.url === 'string' && sender.url.startsWith(chrome.runtime.getURL('src/serve/serve.html'))+ if (!ours) return { ok: false, reason: 'not the served-document host' }+ const path = payload?.path+ if (typeof path !== 'string' || !path.startsWith('/') || !path.endsWith('.bento.html') || path.includes('\u0000')) return { ok: false, reason: 'bad path' }+ const as = { url: 'file://' + path.split('/').map(encodeURIComponent).join('/'), frameId: 0 }+ const text = typeof payload?.text === 'string' ? payload.text : ''+ const r = await write(as, text)+ if (r?.ok) noteSaved(as, text)+ return r+}+// ---------------------------------------------------------------- the offer//// A ⌘S that nothing covers is the moment to ask, once: the page's `claim`@@ -817,6 +837,7 @@ if (typeof chrome !== 'undefined' && chrome.runtime?.onMessage) {: msg?.op === 'save.status' ? saveStatus(sender, msg.url): msg?.op === 'save.rebadge' ? (async () => { const tabs = await chrome.tabs.query({ url: 'file:///*.bento.html' }).catch(() => []); for (const tb of tabs) await badgeTab(tb.id, { url: tb.url, frameId: 0, tab: tb }); return { ok: true } })(): msg?.op === 'write' ? write(sender, msg.payload?.text ?? '').then((r) => { if (r?.ok) noteSaved(sender, msg.payload?.text ?? ''); return r })+ : msg?.op === 'serve.write' ? serveWrite(sender, msg.payload): msg?.op === 'backup' ? backup(sender, msg.payload?.text ?? '', msg.payload?.name): msg?.op === 'assistant.consent' ? recordConsent(sender, msg): typeof msg?.op === 'string' && msg.op.startsWith('assistant.') ? assistantOp(msg.op, sender, msg.payload)diff --git a/home/webext/src/home.js b/home/webext/src/home.jsindex 34f36546..5efc6547 100644--- a/home/webext/src/home.js+++ b/home/webext/src/home.js@@ -12,6 +12,7 @@// (enumeration is fine here, resolution never enumerates; the absolute path is// learned, not derived) live there and are explained there.+import { servedOpenEnabled, SETTING_KEY as SERVE_KEY } from './serve/gate.js'import { getGrants, putGrants, status } from './status.js'import { listDocuments, describe, newDocument, duplicate, rename, APPS } from './library.js'import { prefixFor } from './route.js'@@ -866,6 +867,9 @@ function openDoc(d) {}// --------------------------------------------------------------------- menu+// "Open with Bento ID" (serve/gate.js): an unpacked install AND the setting+let serveOn = false+servedOpenEnabled().then((on) => { serveOn = on })let menuEl = nullconst closeMenu = () => { menuEl?.remove(); menuEl = null }addEventListener('click', (e) => { if (menuEl && !menuEl.contains(e.target)) closeMenu() })@@ -886,6 +890,7 @@ function openMenu(d, ev) {}if (d.path) item(t('menuOpen'), () => openDoc(d))+ if (d.path && serveOn) item(t('menuOpenWithId'), () => chrome.tabs.create({ url: chrome.runtime.getURL(`src/serve/serve.html?path=${encodeURIComponent(d.path)}`) }))if (d.scanned && !d.granted) item(t('menuAddFolder'), () => addFolderFor(d))if (!d.scanned) item(t('menuDuplicate'), async () => {const made = await duplicate(d)@@ -1685,6 +1690,20 @@ async function renderSettings() {p.textContent = t('setIdLocal')idSec.append(p)}+ // the served-document preview: OFF unless turned on here+ const serveRow = document.createElement('label')+ serveRow.className = 'check'+ const serveBox = document.createElement('input')+ serveBox.type = 'checkbox'+ serveBox.checked = (await chrome.storage.local.get(SERVE_KEY))[SERVE_KEY] === true+ const serveNote = document.createElement('small')+ serveNote.textContent = t('setIdServeNote')+ serveRow.append(serveBox, document.createTextNode(` ${t('setIdServe')}`), serveNote)+ serveBox.addEventListener('change', async () => {+ await chrome.storage.local.set({ [SERVE_KEY]: serveBox.checked })+ serveOn = await servedOpenEnabled()+ })+ idSec.append(serveRow)}// --- the assistant: where a chat about a deck goes, and which decks may askdiff --git a/home/webext/src/id/gen/gate1.js b/home/webext/src/id/gen/gate1.jsnew file mode 100644index 00000000..989729f3--- /dev/null+++ b/home/webext/src/id/gen/gate1.js@@ -0,0 +1,500 @@+// GENERATED from kernel/src/gate1.ts by scripts/gen-webext-id.mjs — do not edit.+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// GATE 1: is this file's runtime a genuine Bento release? (bento/connect K5,+// security §13–§18, §36, and the 2026-10-21 grammar ruling.) ONE shared+// implementation for every JavaScript host (the extension, the hosted runtime,+// release tooling). Native hosts (Swift, Kotlin, Rust) port it and must agree+// with it on every row of the conformance corpus in home/fixtures/gate1/.+//+// Two paths, by what the host can do:+// - verifyServed(): for a host that SERVES the bytes it verified (iOS,+// Android, desktop, the hosted runtime). It checks the file against the+// signed release history: ONE release must match EVERY code block, under+// the grammar below. It answers with the CSP to serve the file under. This+// is the PRIMARY path, immune to serializer drift (security §17).+// - verifyStrict(): the file:// fallback, where no CSP can be set. An exact+// string check against a release's saved skeleton (vault's strict verifier,+// signed off in security §15). It can only ever hold a RESULT: identity is+// never exposed in a bare file:// tab (security §16).+//+// "Unknown" is never "tampered": it means "not provably one of ours", and the+// host shows the document without identity, or offers an update. It never+// borrows a pinned CSP for a file it couldn't match.+//+// Pure: no DOM, and WebCrypto for hashing, so it runs in a page, a worker, an+// extension and node alike.++/** A release's pins, as signed into its manifest and its history entry. */+++++++++++// --- the scanner ---------------------------------------------------------------+++++++++++++++++++++++/**+ * A start tag's attributes, read the way the HTML tokenizer reads them (security,+ * #825 review). Names are separated by whitespace (tab, LF, FF, CR, space) OR by+ * "/". A quoted value ends the attribute even with no separator after it. Names+ * are case-insensitive, and the FIRST of duplicate names wins. Reading them any+ * other way lets `<script/type="module" type="application/bento+json">` look+ * inert when a browser runs it. `duplicate` and `slash` are reported because+ * Bento never writes either, so a script tag with either is refused outright+ * (markupProblems). Values are taken literally: a browser decodes character+ * references in them, but a literal read can only make a block look EXECUTABLE,+ * never inert (no data type contains "&").+ */++/**+ * ASCII-only case fold: the HTML spec's, and LENGTH-PRESERVING. Never use+ * toLowerCase() on a file and index the original with its offsets: it changes+ * length ('İ' becomes two UTF-16 units). Every İ before a block then shifts the+ * offsets, so a genuine Turkish document reads as unknown and, worse, a <style>+ * close can land late enough to skip over an injected <script>, and a file+ * carrying foreign code reads as genuine (home-desktop, measured).+ */+export const asciiLower = (s ) => s.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32))++const WS = (c ) => c === '\t' || c === '\n' || c === '\f' || c === '\r' || c === ' '+export function parseStartTag(html , i ) {+ return html[i] === '<' ? readTag(html, i + 1) : null+}++/**+ * An END tag, read exactly like a start tag. The tokenizer parses attributes in+ * end tags too, quoted values included, and then drops them, so+ * `</p a="><b c='">` ends at its SECOND ">". Skipping an end tag to its first ">"+ * instead read `<b c='">'<script>` as one tag and missed the script after it+ * (both engines ran it). null if `i` isn't "</" and a letter, or it's unterminated.+ */+export function parseEndTag(html , i ) {+ return html[i] === '<' && html[i + 1] === '/' ? readTag(html, i + 2) : null+}++/** A tag's name and attributes, from its name's first character. */+function readTag(html , at ) {+ const m = /^([a-zA-Z][^\t\n\f\r />]*)/.exec(html.slice(at, at + 256))+ if (!m) return null+ const attrs = new Map ()+ let duplicate = false, slash = false+ let j = at + m[0].length+ while (j < html.length) {+ const c = html[j]+ if (WS(c)) { j++; continue }+ if (c === '/') { slash = true; j++; continue } // a separator, or a self-closing mark+ if (c === '>') return { name: asciiLower(m[1]), attrs, duplicate, slash, end: j + 1 }+ // the name: a leading "=" is part of it; it ends at whitespace, "/", ">" or "="+ let k = j, name = ''+ if (html[k] === '=') { name = '='; k++ }+ while (k < html.length && !WS(html[k]) && html[k] !== '/' && html[k] !== '>' && html[k] !== '=') name += html[k++]+ name = asciiLower(name).replace(/\u0000/g, '�')+ let value = ''+ let p = k+ while (WS(html[p])) p+++ if (html[p] === '=') {+ p+++ while (WS(html[p])) p+++ if (html[p] === '"' || html[p] === "'") {+ const close = html.indexOf(html[p], p + 1)+ if (close < 0) return null+ value = html.slice(p + 1, close)+ k = close + 1+ } else {+ let e = p+ while (e < html.length && !WS(html[e]) && html[e] !== '>') e+++ value = html.slice(p, e)+ k = e+ }+ }+ if (attrs.has(name)) duplicate = true+ else attrs.set(name, value)+ j = k+ }+ return null // unterminated+}++/**+ * ONE walk over the file, in document order, tag by tag, as a browser's+ * tokenizer meets them. Both scanBlocks and markupProblems read it, so the+ * blocks gate1 hashes and the markup it judges come from the SAME reading.+ * Searching for "<script" or "<style" instead finds them where a browser never+ * would: inside another tag's name. In `<meta<style><script>…` a browser sees ONE+ * tag, named "meta<style", and then a real <script> that runs. A search saw a+ * <style> whose close swallowed the script (home-ios, found by a WebKit oracle).+ */++const TAG_NAME = /^[a-z][a-z0-9-]*$/+/** Elements whose content is TEXT to a browser, never tags, up to their real end tag. */+const RAW_TEXT = ['script', 'style', 'textarea', 'title']++/**+ * Where a raw-text element really ends: "</name" (ASCII case-insensitive)+ * followed by whitespace, "/" or ">", as the tokenizer requires. "</scriptx>"+ * is text inside the script, not its end. -1 if it never ends.+ */+function rawTextEnd(lower , name , from ) {+ let at = from+ while ((at = lower.indexOf(`</${name}`, at)) !== -1) {+ const c = lower[at + 2 + name.length]+ if (c === undefined || WS(c) || c === '/' || c === '>') return at+ at += 2+ }+ return -1+}+function walk(html ) {+ const blocks = [], problems = []+ const lower = asciiLower(html)+ let i = 0+ while ((i = html.indexOf('<', i)) !== -1) {+ if (html.startsWith('<!--', i)) {+ // "<!-->" and "<!--->" are whole (empty) comments to a browser+ if (html.startsWith('<!-->', i)) { i += 5; continue }+ if (html.startsWith('<!--->', i)) { i += 6; continue }+ const end = html.indexOf('-->', i + 4)+ if (lower.slice(i + 4, end < 0 ? html.length : end).includes('<script')) problems.push('a comment holds a <script>')+ if (end < 0) { problems.push('an unterminated comment'); break }+ i = end + 3; continue+ }+ if (html[i + 1] === '/' && /[a-zA-Z]/.test(html[i + 2] ?? '')) {+ // an end tag: tokenized with the start tag's attribute rules (see parseEndTag)+ const et = parseEndTag(html, i)+ if (!et) { problems.push('an unterminated end tag'); break }+ if (!TAG_NAME.test(et.name)) problems.push(`an end tag named ${JSON.stringify(et.name)}`)+ // a browser drops them, but they move where the tag ends: Bento writes none+ if (et.attrs.size) problems.push(`an end tag </${et.name}> carrying attributes`)+ i = et.end; continue+ }+ if (html.startsWith('</>', i)) { i += 3; continue } // ignored entirely+ if (html[i + 1] === '/' || html[i + 1] === '!' || html[i + 1] === '?') {+ // a doctype or a bogus comment: it ends at the first ">", quotes or not+ const end = html.indexOf('>', i + 2)+ if (end < 0) { problems.push('an unterminated tag'); break }+ i = end + 1; continue+ }+ if (!/^<[a-zA-Z]/.test(html.slice(i, i + 2))) { i++; continue } // a "<" that starts no tag is text+ const tag = parseStartTag(html, i)+ if (!tag) { problems.push('an unterminated start tag'); break }+ const name = tag.name+ // Bento writes only plain tag names. Anything else ("meta<style", a NUL, a+ // non-ASCII letter) is a tag a scanner and a browser may read differently.+ if (!TAG_NAME.test(name)) problems.push(`a start tag named ${JSON.stringify(name)}`)+ if (['iframe', 'object', 'embed', 'base'].includes(name)) problems.push(`a <${name}>`)+ if (name === 'meta' && /^\s*(refresh|content-security-policy)\s*$/i.test(tag.attrs.get('http-equiv') ?? '')) problems.push('a <meta> refresh or CSP')+ if ([...tag.attrs.keys()].some((n) => n.startsWith('on'))) problems.push(`an on*= attribute on <${name}>`)+ if (name === 'script' && (tag.duplicate || tag.slash)) problems.push(`a <script> start tag with a ${tag.duplicate ? 'duplicate attribute' : '"/" between attributes'} (Bento writes neither)`)+ if (RAW_TEXT.includes(name)) {+ const close = rawTextEnd(lower, name, tag.end)+ if (close < 0) { problems.push(`an unterminated <${name}>`); break }+ // inert to a browser, but a scanner that doesn't treat these as text+ // would count it: refuse, so every host's scanner reaches the same verdict+ if (name !== 'script' && lower.slice(tag.end, close).includes('<script')) problems.push(`a <${name}> holds a <script>`)+ if (name === 'textarea' || name === 'title') { i = close; continue }+ const et = parseEndTag(html, close)+ if (!et) { problems.push(`an unterminated </${name}>`); break }+ const get = (n ) => tag.attrs.has(n) ? tag.attrs.get(n) : null+ blocks.push({+ tag: name , attrs: html.slice(i, tag.end), text: html.slice(tag.end, close),+ tagStart: i, start: tag.end, end: et.end,+ type: get('type'), id: get('id'), src: get('src'), preview: tag.attrs.has('data-bento-preview'),+ duplicate: tag.duplicate, slash: tag.slash,+ })+ i = close; continue // its end tag is judged next, as an end tag+ }+ i = tag.end+ }+ return { blocks, problems }+}++/** Every <script> and <style> element in the file, with its raw text, in document order. */+export function scanBlocks(html ) {+ return walk(html).blocks+}++// --- the grammar (security, 2026-10-21) ------------------------------------------++/**+ * A <script> is inert ONLY if its type is exactly one of the data types Bento+ * writes. Everything else is executable: no type, a JavaScript type, "module",+ * an unknown type, a differently cased data type, and ANY src=. An executable+ * script must be exactly the pinned loader or remover by hash, or the file is+ * UNKNOWN. An allowlist, so a type browsers start running tomorrow can't pass as+ * data.+ */+export const DATA_TYPES = new Set(['application/bento+json', 'application/bento+lang', 'bento/deflate-b64', 'bento/deflate-b86'])+export const isDataScript = (b ) => b.tag === 'script' && b.src === null && b.type !== null && DATA_TYPES.has(b.type)++/** Every script that isn't one of Bento's data blocks: each must be the pinned loader or remover. */+export const executableScripts = (blocks ) => blocks.filter((b) => b.tag === 'script' && !isDataScript(b))++/**+ * Markup a genuine Bento file never carries, anywhere outside a script or style+ * element's own text:+ * - <iframe>, <object>, <embed> or <base>;+ * - a <meta> refresh or CSP;+ * - any on*= attribute;+ * - a comment or <style> holding a <script>;+ * - a data block containing "<".+ * Bento's data never contains "<": the JSON and language packs escape it, and+ * the b64/b86 alphabets exclude it. That also closes the "<!--<script"+ * double-escape state, where a later close tag doesn't end the element.+ * Returns the problems; [] = none.+ */+export function markupProblems(html ) {+ const { blocks, problems } = walk(html)+ for (const b of blocks) if (isDataScript(b) && b.text.includes('<')) problems.push(`the ${b.type} block contains "<"`)+ return problems+}++// --- hashing ---------------------------------------------------------------------++const enc = new TextEncoder()+async function digest(s ) {+ return new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(s) ))+}+/** sha256 HEX of a string's UTF-8 bytes: the encoding of every `blocks` pin. */+export async function sha256hex(s ) {+ return Array.from(await digest(s), (b) => b.toString(16).padStart(2, '0')).join('')+}+/** 'sha256-' + BASE64: the CSP encoding of every `scriptSrc` pin. Never compare it to a hex pin. */+export async function cspHash(s ) {+ let bin = ''+ for (const b of await digest(s)) bin += String.fromCharCode(b)+ return `sha256-${btoa(bin)}`+}++const CODE_IDS = ['bento-rt', 'bento-rt-css']++/**+ * Check a file against ONE release's pins: no foreign markup, exactly one block+ * per code id with a matching hash, and every executable script exactly the+ * pinned loader or remover. Returns the problems; [] = this release's file.+ */+export async function checkAgainstPins(html , pins ) {+ const problems = [...markupProblems(html)]+ const blocks = scanBlocks(html)+ for (const id of CODE_IDS) {+ const found = blocks.filter((b) => b.id === id)+ if (found.length !== 1) problems.push(`${found.length} #${id} blocks (exactly one expected)`)+ else if ((await sha256hex(found[0].text)) !== pins.blocks[id]) problems.push(`#${id} does not match`)+ }+ const exec = executableScripts(blocks)+ const hashes = await Promise.all(exec.map((s) => sha256hex(s.text)))+ const allowed = new Set([pins.blocks.loader, pins.blocks.remover].filter(Boolean))+ exec.forEach((s, k) => {+ if (s.src !== null || !allowed.has(hashes[k])) problems.push(`an executable script that is neither the pinned loader nor the remover (${s.src !== null ? 'src=' + s.src : s.text.length + 'B'})`)+ })+ const n = (h ) => hashes.filter((x) => x === h).length+ if (n(pins.blocks.loader) === 0) problems.push('no pinned loader')+ if (n(pins.blocks.loader) > 1) problems.push('more than one loader')+ if (pins.blocks.remover && n(pins.blocks.remover) > 1) problems.push('more than one remover')+ return problems+}++// --- the release history --------------------------------------------------------++const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/+export function cmpVersion(a , b ) {+ const x = SEMVER.exec(a), y = SEMVER.exec(b)+ if (!x || !y) throw new Error(`gate1: not a version: ${!x ? a : b}`)+ for (let i = 1; i <= 3; i++) { const d = Number(x[i]) - Number(y[i]); if (d) return d }+ return 0+}+const entryOk = (e ) => !!e && typeof e.version === 'string' && SEMVER.test(e.version) &&+ /^[0-9a-f]{64}$/.test(e.sha256 ?? '') && typeof e.at === 'string' && e.pins?.v === 1 && typeof e.pins.blocks === 'object'++/** A history payload's shape problems; [] = well-formed (versions unique, newest first). */+export function historyProblems(h ) {+ const p = []+ if (!h || h.v !== 1) p.push(`version ${h?.v} (expected 1)`)+ if (typeof h?.app !== 'string' || !h.app) p.push('no app')+ if (!Array.isArray(h?.releases)) { p.push('no releases'); return p }+ const seen = new Set ()+ h.releases.forEach((e, i) => {+ if (!entryOk(e)) { p.push(`entry ${i} is malformed`); return }+ if (seen.has(e.version)) p.push(`version ${e.version} appears twice`)+ seen.add(e.version)+ const prev = h.releases[i - 1]+ if (i > 0 && entryOk(prev) && cmpVersion(prev.version, e.version) <= 0) p.push(`entries are not newest-first at ${e.version}`)+ })+ return p+}++const same = (a , b ) => JSON.stringify(a) === JSON.stringify(b)++/**+ * A HOST's acceptance of an incoming, already signature-verified history, given+ * the newest it holds: ANTI-ROLLBACK. It refuses one that lacks a held entry,+ * changes one, or rolls the newest version back. (With a well-formed history+ * the last is implied by the first, and is kept as defence in depth.)+ */+export function acceptHistory(held , incoming , app ) {+ const problems = historyProblems(incoming)+ if (problems.length) return { ok: false, reason: `malformed: ${problems[0]}` }+ if (incoming.app !== app) return { ok: false, reason: `for ${incoming.app}, not ${app}` }+ if (!held) return { ok: true }+ if (!incoming.releases.length || (held.releases.length && cmpVersion(incoming.releases[0].version, held.releases[0].version) < 0)) {+ return { ok: false, reason: 'rollback: its newest release is older than the newest already held' }+ }+ for (const e of held.releases) {+ const there = incoming.releases.find((x) => x.version === e.version)+ if (!there) return { ok: false, reason: `rollback: it lacks ${e.version}, which is already held` }+ if (!same(there, e)) return { ok: false, reason: `${e.version} changed: a history never changes an entry` }+ }+ return { ok: true }+}++/** The ONE entry matching every block of the file, or null (none, or more than one: UNKNOWN). */+export async function matchRelease(history , html ) {+ const rt = scanBlocks(html).filter((b) => b.id === 'bento-rt')+ if (rt.length !== 1) return null+ const rtHash = await sha256hex(rt[0].text)+ const full = []+ for (const e of history.releases.filter((x) => x.pins.blocks['bento-rt'] === rtHash)) {+ if ((await checkAgainstPins(html, e.pins)).length === 0) full.push(e)+ }+ return full.length === 1 ? full[0] : null+}++// --- the served path ----------------------------------------------------------------++/**+ * The CSP a host serves a verified document under (security §17/§18, §36a):+ * scripts hash-pinned to the release's loader and remover, plus blob: for the+ * runtime the loader imports; styles 'unsafe-inline' (the sanitizer is the style+ * control); everything else closed. `frameAncestors` is the host's own value.+ */+export function hostPolicy(pins , frameAncestors = "'none'") {+ return [+ "default-src 'none'",+ `script-src ${pins.scriptSrc.map((h) => `'${h}'`).join(' ')} blob:`,+ "style-src 'unsafe-inline'",+ 'img-src data: blob: https:',+ 'media-src data: blob: https:',+ 'font-src data: blob:',+ 'connect-src https://bento.page https://sync.bento.page wss://sync.bento.page',+ 'frame-src https:',+ "object-src 'none'",+ "base-uri 'none'",+ "form-action 'none'",+ "worker-src 'none'",+ `frame-ancestors ${frameAncestors}`,+ ].join('; ')+}++++++/**+ * THE served-path gate: is this file one genuine release's? The history must+ * already have passed the release-key signature check and acceptHistory().+ */+export async function verifyServed(html , history , opts = {}) {+ const problems = historyProblems(history)+ if (problems.length) return { verdict: 'unknown', reason: `the history is malformed: ${problems[0]}` }+ const release = await matchRelease(history, html)+ if (!release) {+ const markup = markupProblems(html)+ return { verdict: 'unknown', reason: markup.length ? markup[0] : 'no single release matches every block' }+ }+ return { verdict: 'genuine', release, csp: hostPolicy(release.pins, opts.frameAncestors) }+}++/**+ * A served file, judged against EVERY history the host holds. A fresh shell (as+ * New writes it, and as a release publishes it) has an empty document block, so+ * nothing in the file says which app it is: never pick the history by a name read+ * from the file or by a directory name. Exactly one app's history must match;+ * none, or more than one, is UNKNOWN. The verdict names the app that matched.+ */+export async function verifyServedHeld(html , held , opts = {}) {+ const hits = []+ for (const h of held) {+ const v = await verifyServed(html, h, opts)+ if (v.verdict === 'genuine') hits.push({ app: h.app, v })+ }+ if (hits.length === 1) return { ...hits[0].v, app: hits[0].app }+ return { verdict: 'unknown', reason: hits.length ? `${hits.length} held histories match (${hits.map((x) => x.app).join(', ')})` : 'no held history matches' }+}++// --- the strict file:// fallback (vault's strict verifier; security §15) ------------++const CLOSE = '</' + 'script>'+const DOC_ANCHOR = ' id="bento-doc"'+const DOC_OPEN = '<script type="application/bento+json" id="bento-doc">'++/** What the strict check compares against, taken from a GENUINE saved file of a release. */++++++++function collapse(h , remover ) {+ const count = (n ) => h.split(n).length - 1+ if (count(DOC_ANCHOR) !== 1) return { refuse: `doc anchor count ${count(DOC_ANCHOR)}` }+ const di = h.indexOf(DOC_ANCHOR), dOpen = h.lastIndexOf('<', di), dTagEnd = h.indexOf('>', di) + 1, dEnd = h.indexOf(CLOSE, di) + CLOSE.length+ if (h.slice(dOpen, dTagEnd) !== DOC_OPEN) return { refuse: 'doc block opening tag altered' }+ if (dEnd < CLOSE.length || h.slice(dTagEnd, dEnd - CLOSE.length).includes('<')) return { refuse: '"<" inside the doc block' }+ h = h.slice(0, dOpen) + '<!--DOC-->' + h.slice(dEnd)+ if (count('data-bento-preview') > 0) {+ if (!remover || count('<script data-bento-preview') !== 1 || count(remover) !== 1) return { refuse: 'remover missing, altered or repeated' }+ const pOpen = h.lastIndexOf('<', h.indexOf('data-bento-preview')), rem = h.indexOf(remover), body = h.slice(pOpen, rem)+ if (/<script/i.test(body)) return { refuse: 'script inside the preview markup' }+ if (/\son[a-z]+\s*=/i.test(body) || /javascript:/i.test(body)) return { refuse: 'handler or javascript: in the preview markup' }+ h = h.slice(0, pOpen) + '<!--PREVIEW-->' + h.slice(rem + remover.length)+ }+ return h.replace(/<title>[^<]*<\/title>/, '<title><!--TITLE--></title>')+}++/** The strict expectation from a GENUINE saved file of a release. */+export function strictExpectedFrom(genuineSave ) {+ const at = genuineSave.indexOf('<script data-bento-preview')+ const remover = at < 0 ? null : genuineSave.slice(at, genuineSave.indexOf(CLOSE, at) + CLOSE.length)+ const skeleton = collapse(genuineSave, remover)+ if (typeof skeleton !== 'string') throw new Error(`gate1: the genuine save fails its own strict check: ${skeleton.refuse}`)+ return { skeleton, remover }+}++/**+ * The strict check: each variable span (the doc block, the preview, the title)+ * is type-checked to its exact allowed form and collapsed. Then EVERYTHING else+ * must equal the release's saved skeleton, byte for byte, over the WHOLE string,+ * bound at both ends. That final compare is what's load-bearing: it caught every+ * one of security's adversarial rows (§15). The span guards are defence in+ * depth that let the variable spans legitimately vary.+ */+export function verifyStrict(html , expected ) {+ const c = collapse(html, expected.remover)+ if (typeof c !== 'string') return { ok: false, reason: c.refuse }+ return c === expected.skeleton ? { ok: true } : { ok: false, reason: 'skeleton differs from the release\'s saved form' }+}diff --git a/home/webext/src/serve/gate.js b/home/webext/src/serve/gate.jsnew file mode 100644index 00000000..04088f2a--- /dev/null+++ b/home/webext/src/serve/gate.js@@ -0,0 +1,25 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/connect W2 — whether "Open with Bento ID" exists at all.+//+// TWO gates, both required: an UNPACKED install (the same gate as Bento ID+// setup) AND a setting that is OFF unless someone turned it on. Even then it+// is an explicit action on a document, never a change to how files open:+// double-clicking a file, and the library's own Open, are untouched. Store+// users get nothing until the directory exists and a Bento ID is real.++export const SETTING_KEY = 'serveWithIdentity'++/** Pure: only exactly 'development' and exactly true. Absent is off. */+export function servedOpenAllowed(installType, setting) {+ return installType === 'development' && setting === true+}++export async function servedOpenEnabled() {+ let installType = null+ try { installType = (await chrome.management.getSelf())?.installType ?? null } catch { installType = null }+ let setting = null+ try { setting = (await chrome.storage.local.get(SETTING_KEY))[SETTING_KEY] ?? null } catch { setting = null }+ return servedOpenAllowed(installType, setting)+}diff --git a/home/webext/src/serve/history.js b/home/webext/src/serve/history.jsnew file mode 100644index 00000000..284f3030--- /dev/null+++ b/home/webext/src/serve/history.js@@ -0,0 +1,71 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/connect W2 — the signed release histories the extension checks a file+// against before it serves it with identity (gate 1, kernel/src/gate1.ts).+//+// Each app publishes releases/<app>/history.json on bento.page: every release+// still in the wild with its script and block pins, signed by the release key+// (the same key and envelope as the update channel: release.js verifySigned).+//+// WHEN IT IS FETCHED — never on each open (an open must not phone home, and+// must work offline):+// · not at all, for a person who has never opened a document with identity;+// · after that, at most once a day, at browser start;+// · and once at an open only when NOTHING is held for any app yet.+// Offline with nothing held → no history → every file is UNKNOWN (opens+// without identity). Never a guess.+//+// WHAT IS HELD: per app, the newest history that verified, replaced only by one+// kernel's acceptHistory() accepts — append-only, so a replayed older signed+// history can't hide a release (anti-rollback).+//+// Pure: storage, fetch, time and the key come in as deps.++import { verifySigned } from '../release.js'+import { acceptHistory, historyProblems } from '../id/gen/gate1.js'++export const STORE_KEY = 'gate1History'+export const USED_KEY = 'gate1Used'+export const DAY = 86_400_000+export const BASE = 'https://bento.page/releases'++/** The apps whose histories are fetched: [{ id: 'slides', appId: 'bento-slides' }, …]. */+export async function refresh(apps, deps, { force = false } = {}) {+ const held = (await deps.get(STORE_KEY)) ?? {}+ const now = deps.now()+ const report = {}+ for (const { id, appId } of apps) {+ const mine = held[appId]+ if (!force && mine && now - mine.fetchedAt < DAY) { report[appId] = 'fresh'; continue }+ let incoming+ try {+ const r = await deps.fetch(`${BASE}/${id}/history.json`, { cache: 'no-store' })+ if (!r.ok) { report[appId] = `http ${r.status}`; continue }+ incoming = await verifySigned(await r.text(), 'release history', deps.jwk)+ } catch (e) {+ report[appId] = `refused: ${e?.message ?? e}`; continue+ }+ if (incoming?.app !== appId) { report[appId] = 'refused: history for another app'; continue }+ const problems = historyProblems(incoming)+ if (problems.length) { report[appId] = `refused: ${problems[0]}`; continue }+ const ok = acceptHistory(mine?.history ?? null, incoming, appId)+ if (!ok.ok) { report[appId] = `refused: ${ok.reason}`; continue }+ held[appId] = { history: incoming, fetchedAt: now }+ report[appId] = 'updated'+ }+ await deps.set(STORE_KEY, held)+ return report+}++/** The held histories, { appId: history }. */+export async function heldHistories(deps) {+ const held = (await deps.get(STORE_KEY)) ?? {}+ return Object.fromEntries(Object.entries(held).map(([k, v]) => [k, v.history]))+}++/** For the browser-start refresh: only for someone who has used identity opening. */+export async function refreshIfUsed(apps, deps) {+ if (!(await deps.get(USED_KEY))) return { skipped: 'never used' }+ return refresh(apps, deps)+}diff --git a/home/webext/src/serve/host.js b/home/webext/src/serve/host.jsnew file mode 100644index 00000000..6a6bbc8b--- /dev/null+++ b/home/webext/src/serve/host.js@@ -0,0 +1,54 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/connect W2 — what the host answers on the port (pure: deps injected).+//+// The ONLY entry point for anything the served document asks. A message is+// acted on only if it has exactly the fixed shape — { id: short string,+// op: one of OPS, args: that op's typed fields, nothing else } — and the host+// never acts on a message that claims a consent outcome: consent is asked and+// answered in host chrome, never reported by the frame.+//+// Identity answers come from the extension's Bento ID (W1). Until the+// directory binds it to an address, there is no verified identity to give:+// whoami → null, sign → 'no-identity', resolve → null.++export const OPS = Object.freeze(['identity.whoami', 'identity.sign', 'identity.resolve', 'save.write', 'serve.failed'])+const SIGN_PURPOSES = ['frame', 'prove', 'delegate', 'show', 'invite', 'revoke']+const MAX_TEXT = 256 * 1024 * 1024++/** The fixed shape, or null. */+export function parseRequest(d) {+ if (!d || typeof d !== 'object' || Array.isArray(d)) return null+ const keys = Object.keys(d).sort().join()+ if (keys !== 'args,id,op') return null+ if (typeof d.id !== 'string' || !/^[a-z0-9]{1,24}$/.test(d.id) || !OPS.includes(d.op)) return null+ const a = d.args+ const exact = (o, want) => o && typeof o === 'object' && !Array.isArray(o) && Object.keys(o).sort().join() === want+ switch (d.op) {+ case 'identity.whoami': return a === null ? { id: d.id, op: d.op, args: null } : null+ case 'identity.sign':+ return exact(a, 'payload,purpose') && SIGN_PURPOSES.includes(a.purpose) && typeof a.payload === 'string' && a.payload.length <= 4096 ? { id: d.id, op: d.op, args: { purpose: a.purpose, payload: a.payload } } : null+ case 'identity.resolve':+ return exact(a, 'email,pub') && (a.pub === null || typeof a.pub === 'string') && (a.email === null || typeof a.email === 'string') ? { id: d.id, op: d.op, args: { pub: a.pub, email: a.email } } : null+ case 'save.write':+ return exact(a, 'text') && typeof a.text === 'string' && a.text.length <= MAX_TEXT ? { id: d.id, op: d.op, args: { text: a.text } } : null+ case 'serve.failed':+ return exact(a, 'reason') && typeof a.reason === 'string' ? { id: d.id, op: d.op, args: { reason: a.reason.slice(0, 64) } } : null+ }+ return null+}++/** Answer one parsed request. deps: { writeFile(text) → {ok, reason?} }. */+export async function answer(req, deps) {+ switch (req.op) {+ // a Bento ID not yet bound to a verified address is no identity to give;+ // the directory slice fills these in+ case 'identity.whoami': return null+ case 'identity.sign': return { ok: false, reason: 'no-identity' }+ case 'identity.resolve': return null+ case 'save.write': return deps.writeFile(req.args.text)+ case 'serve.failed': return null+ }+ return null+}diff --git a/home/webext/src/serve/prepare.js b/home/webext/src/serve/prepare.jsnew file mode 100644index 00000000..cc213f85--- /dev/null+++ b/home/webext/src/serve/prepare.js@@ -0,0 +1,59 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/connect W2 — deciding whether a file may be served with identity, and+// what the sandbox may turn into running script.+//+// THE RULE (security §16–§18, §2c): identity only where the host SERVES the+// bytes it verified. So the host reads the file itself, gate 1 decides+// (kernel's verifyServed against the held signed histories), and:+// · GENUINE → served into the extension's sandbox page, where ONLY the+// executable blocks gate 1's own scanner reported become blob: scripts,+// spliced by the scanner's own element offsets (Block.tagStart..end) —+// never a second regex, never a re-serialisation;+// · UNKNOWN (no single release matches every block, a markup problem, no+// history held) → never enters the sandbox; the file opens as itself, in+// a plain file:// tab, without identity.+// The sandbox's FIXED CSP (script-src 'self' blob:, no inline) is the second+// wall: anything the scanner did NOT report stays inline and does not run.++import { verifyServedHeld, scanBlocks, executableScripts } from '../id/gen/gate1.js'++/**+ * `histories` is { appId: history } (serve/history.js heldHistories). Returns+ * { verdict: 'genuine', appId, release, plan } — plan = the executable+ * elements in document order: { tagStart, end, text, module } — or+ * { verdict: 'unknown', reason }.+ */+export async function prepare(html, histories) {+ // kernel's verifyServedHeld: EVERY held history is tried (never one the+ // document names — a fresh shell's document block names no app), and the+ // file is genuine only if exactly one matches+ const held = Object.values(histories ?? {})+ if (!held.length) return { verdict: 'unknown', reason: 'no release history held' }+ const v = await verifyServedHeld(html, held)+ if (v.verdict !== 'genuine') return { verdict: 'unknown', reason: v.reason }+ const plan = executableScripts(scanBlocks(html)).map((b) => ({+ tagStart: b.tagStart, end: b.end, text: b.text, module: (b.type ?? '').toLowerCase() === 'module',+ }))+ return { verdict: 'genuine', appId: v.app, release: v.release, plan }+}++/**+ * The sandbox's splice: each planned element, and ONLY those, replaced by a+ * script loading `urlFor(text, module)` (a blob: URL in the sandbox). Pure.+ * Refuses a plan that isn't in document order, overlaps, or doesn't line up+ * with the html it came with — the plan and the bytes must be the verified pair.+ */+export function splice(html, plan, urlFor) {+ let out = ''+ let at = 0+ for (const p of plan) {+ if (!(Number.isInteger(p.tagStart) && Number.isInteger(p.end) && p.tagStart >= at && p.end > p.tagStart && p.end <= html.length)) throw new Error('the plan does not line up with the file')+ if (!html.slice(p.tagStart, p.end).includes(p.text)) throw new Error('the plan does not line up with the file')+ out += html.slice(at, p.tagStart)+ out += `<script${p.module ? ' type="module"' : ''} src="${urlFor(p.text, p.module)}"></` + 'script>'+ at = p.end+ }+ return out + html.slice(at)+}diff --git a/home/webext/src/serve/sandbox.html b/home/webext/src/serve/sandbox.htmlnew file mode 100644index 00000000..2ed2fe7a--- /dev/null+++ b/home/webext/src/serve/sandbox.html@@ -0,0 +1 @@+<!doctype html><meta charset="utf-8"><title>Bento</title><script src="sandbox.js"></script>diff --git a/home/webext/src/serve/sandbox.js b/home/webext/src/serve/sandbox.jsnew file mode 100644index 00000000..af08a486--- /dev/null+++ b/home/webext/src/serve/sandbox.js@@ -0,0 +1,164 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/connect W2 — the TRUSTED script of the extension's sandbox page.+//+// The host page (serve.js) has read a file, verified it (gate 1), and sends it+// here with the plan of its executable elements and ONE MessagePort. This+// script turns exactly those elements into blob: scripts, defines the identity+// agent and the save bridge, and writes the document in. The sandbox's fixed+// CSP (script-src 'self' blob:, no inline) refuses everything else.+//+// THE REALM IS SHARED. Document script runs in this same JavaScript realm, so+// it can patch any prototype — MessagePort.prototype.postMessage,+// EventTarget.prototype.addEventListener, the MessageEvent data getter,+// Function.prototype.call/bind, Object.defineProperty… If this script called+// any of those AFTER the document loaded, a patched one would receive the+// port (as `this`, or through the event) and could send anything on it or+// transfer it into a child frame (security, 2026-10-24: CRITICAL). So every+// built-in used after the document starts is CAPTURED HERE, before any+// document byte runs, and only ever called through the captured copies. The+// port lives only inside these closures; no agent method returns it, an event,+// or any host object — plain data only.+//+// The handshake is ONE-SHOT: the first message from `parent` carrying a port+// is accepted, before the document is written; any later one is ignored.++(() => {+ 'use strict'+ // --- captured before any document byte exists -------------------------------+ const FnCall = Function.prototype.call+ const FnBind = Function.prototype.bind+ const uncurry = (f) => FnBind.call(FnCall, f)+ const gp = Object.getOwnPropertyDescriptor+ const defineProperty = Object.defineProperty+ const freeze = Object.freeze+ const isArray = Array.isArray+ const PromiseCtor = Promise+ const then = uncurry(Promise.prototype.then)+ const promiseResolve = Promise.resolve.bind(Promise)+ const promiseReject = Promise.reject.bind(Promise)+ const blobText = uncurry(Blob.prototype.text)+ const MapCtor = Map+ const mapSet = uncurry(Map.prototype.set)+ const mapGet = uncurry(Map.prototype.get)+ const mapDelete = uncurry(Map.prototype.delete)+ const portPost = uncurry(MessagePort.prototype.postMessage)+ const portStart = uncurry(MessagePort.prototype.start)+ const listen = uncurry(EventTarget.prototype.addEventListener)+ const unlisten = uncurry(EventTarget.prototype.removeEventListener)+ const evData = uncurry(gp(MessageEvent.prototype, 'data').get)+ const evSource = uncurry(gp(MessageEvent.prototype, 'source').get)+ const evPorts = uncurry(gp(MessageEvent.prototype, 'ports').get)+ const docOpen = uncurry(Document.prototype.open)+ const docWrite = uncurry(Document.prototype.write)+ const docClose = uncurry(Document.prototype.close)+ const BlobCtor = Blob+ const createURL = URL.createObjectURL+ const strSlice = uncurry(String.prototype.slice)+ const strIncludes = uncurry(String.prototype.includes)+ const DOMExceptionCtor = DOMException+ const win = window+ const doc = document+ const PARENT = window.parent++ let handshakeDone = false+ let port = null+ let seq = 0+ const pending = new MapCtor()++ // one request on the port; the reply is plain data, matched by id+ const ask = (op, args) => new PromiseCtor((resolve) => {+ const id = 's' + (++seq)+ mapSet(pending, id, resolve)+ portPost(port, { id, op, args })+ })+ const onReply = (ev) => {+ const d = evData(ev)+ if (!d || typeof d !== 'object' || typeof d.id !== 'string') return+ const resolve = mapGet(pending, d.id)+ if (!resolve) return+ mapDelete(pending, d.id)+ resolve(d.result)+ }+ // copy a reply into fresh plain data: nothing host-side ever reaches the document+ const JSONparse = JSON.parse+ const JSONstringify = JSON.stringify+ const clone = (v) => (v === undefined || v === null ? null : JSONparse(JSONstringify(v)))++ // --- the identity agent (kernel/src/identity.ts contract 1) -------------------+ const agent = freeze({+ contract: 1,+ whoami: () => then(ask('identity.whoami', null), clone),+ sign: (purpose, payload) => then(ask('identity.sign', { purpose: String(purpose), payload: String(payload) }), clone),+ resolve: (query) => then(ask('identity.resolve', { pub: query && typeof query.pub === 'string' ? query.pub : null, email: query && typeof query.email === 'string' ? query.email : null }), clone),+ })++ // --- the save bridge: ⌘S writes the file the host opened ----------------------+ const handle = (name) => freeze({+ name, kind: 'file',+ createWritable: () => {+ const parts = []+ return promiseResolve(freeze({+ write: (data) => { parts[parts.length] = data; return promiseResolve() },+ close: () => then(then(blobText(new BlobCtor(parts)), (text) => ask('save.write', { text })), (r) => {+ if (!r || r.ok !== true) throw new DOMExceptionCtor((r && r.reason) || 'write failed', 'NotAllowedError')+ }),+ }))+ },+ queryPermission: () => promiseResolve('granted'),+ requestPermission: () => promiseResolve('granted'),+ isSameEntry: () => promiseResolve(false),+ })+ let docName = 'document.bento.html'+ const showSaveFilePicker = (opts) => {+ const id = opts && typeof opts.id === 'string' ? opts.id : ''+ // ⌘S of the open document only, for now; copies and exports in a later slice+ if (id === 'bento-doc') return promiseResolve(handle(docName))+ return promiseReject(new DOMExceptionCtor('Save a copy and exports are not available here yet', 'AbortError'))+ }++ const define = (name, value) => defineProperty(win, name, { value, writable: false, configurable: false, enumerable: false })++ const onHandshake = (ev) => {+ if (handshakeDone) return+ if (evSource(ev) !== PARENT) return+ const d = evData(ev)+ const ports = evPorts(ev)+ if (!d || d.kind !== 'bento-serve' || typeof d.html !== 'string' || !isArray(d.plan) || !ports || ports.length !== 1) return+ handshakeDone = true+ unlisten(win, 'message', onHandshake)+ port = ports[0]+ listen(port, 'message', onReply)+ portStart(port)+ if (typeof d.name === 'string') docName = d.name++ // the splice, by the plan's offsets (serve/prepare.js splice, inlined so+ // this file loads no module the document could reach)+ const html = d.html+ let out = ''+ let at = 0+ for (let i = 0; i < d.plan.length; i++) {+ const p = d.plan[i]+ if (!(p && p.tagStart >= at && p.end > p.tagStart && p.end <= html.length && strIncludes(strSlice(html, p.tagStart, p.end), p.text))) {+ portPost(port, { id: 'boot', op: 'serve.failed', args: { reason: 'plan' } })+ return+ }+ const url = createURL(new BlobCtor([p.text], { type: 'text/javascript' }))+ out += strSlice(html, at, p.tagStart) + '<script' + (p.module ? ' type="module"' : '') + ' src="' + url + '"></' + 'script>'+ at = p.end+ }+ out += strSlice(html, at)++ // the agent and the bridge exist before ANY document byte does+ define('__bentoIdentity', agent)+ define('showSaveFilePicker', showSaveFilePicker)+ define('__bentoHost', freeze({ name: 'home/webext (served)', ops: freeze(['claim', 'write']) }))+ docOpen(doc)+ docWrite(doc, out)+ docClose(doc)+ }+ listen(win, 'message', onHandshake)+ // tell the host this frame is ready for the handshake+ PARENT.postMessage({ kind: 'bento-serve-ready' }, '*')+})()diff --git a/home/webext/src/serve/serve.html b/home/webext/src/serve/serve.htmlnew file mode 100644index 00000000..c3717f11--- /dev/null+++ b/home/webext/src/serve/serve.html@@ -0,0 +1,12 @@+<!doctype html>+<meta charset="utf-8">+<title>Bento</title>+<link rel="icon" href="../../icons/icon.svg">+<link rel="stylesheet" href="../ui.css">+<style>+ /* The host page: the verified document fills it, in the sandbox frame.+ * Consent and identity prompts are drawn HERE, outside that frame. */+ html, body { margin: 0; height: 100%; background: var(--bg) }+ iframe { border: 0; width: 100%; height: 100%; display: block }+</style>+<body><script type="module" src="serve.js"></script></body>diff --git a/home/webext/src/serve/serve.js b/home/webext/src/serve/serve.jsnew file mode 100644index 00000000..199c5dbf--- /dev/null+++ b/home/webext/src/serve/serve.js@@ -0,0 +1,71 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// bento/connect W2 — the host page: open a file WITH identity.+//+// serve.html?path=/Users/you/Decks/Q3.bento.html+//+// 1. Read the file's bytes ourselves (file access) — what is verified is what+// is served, so there is no gap between the check and the use.+// 2. Gate 1 against the held signed histories (serve/history.js — fetched+// here only if NONE is held yet; otherwise on its own daily cadence).+// 3. UNKNOWN → open the file as itself, in this tab, without identity.+// GENUINE → serve it into the sandbox frame with its plan and ONE port.+// 4. Answer only on that port, only fixed-shape requests (serve/host.js).++import { prepare } from './prepare.js'+import { heldHistories, refresh, USED_KEY } from './history.js'+import { parseRequest, answer } from './host.js'+import { RELEASE_KEY } from '../release.js'+import { APPS } from '../library.js'+import { servedOpenEnabled } from './gate.js'++const path = new URLSearchParams(location.search).get('path') ?? ''+const fileUrl = 'file://' + path.split('/').map(encodeURIComponent).join('/')+const asItself = (why) => { console.info('[bento/connect] opening without identity:', why); location.replace(fileUrl) }++const storage = {+ get: async (k) => (await chrome.storage.local.get(k))[k] ?? null,+ set: async (k, v) => { await chrome.storage.local.set({ [k]: v }) },+}+const histDeps = { ...storage, fetch: (u, o) => fetch(u, o), now: () => Date.now(), jwk: RELEASE_KEY }+const apps = APPS.map(({ id, appId }) => ({ id, appId }))++async function main() {+ // both gates (serve/gate.js), checked HERE too: the page is reachable by URL+ if (!(await servedOpenEnabled())) return asItself('Open with Bento ID is off')+ if (!path.startsWith('/') || !path.endsWith('.bento.html')) return asItself('not a Bento document path')+ let html+ try {+ const r = await fetch(fileUrl)+ if (!r.ok) return asItself(`could not read it (${r.status})`)+ html = await r.text()+ } catch (e) { return asItself(`could not read it (${e?.message})`) }++ await storage.set(USED_KEY, true)+ let held = await heldHistories(histDeps)+ if (!Object.keys(held).length) { await refresh(apps, histDeps).catch(() => {}); held = await heldHistories(histDeps) }+ const v = await prepare(html, held)+ if (v.verdict !== 'genuine') return asItself(v.reason)++ document.title = path.split('/').pop()+ const frame = document.createElement('iframe')+ frame.src = chrome.runtime.getURL('src/serve/sandbox.html')+ const onReady = (ev) => {+ if (ev.source !== frame.contentWindow || ev.data?.kind !== 'bento-serve-ready') return+ removeEventListener('message', onReady)+ const { port1, port2 } = new MessageChannel()+ port1.onmessage = async (e) => {+ const req = parseRequest(e.data)+ if (!req) { console.info('[bento/connect] refused a malformed request'); return }+ const result = await answer(req, {+ writeFile: (text) => chrome.runtime.sendMessage({ op: 'serve.write', payload: { path, text } }),+ }).catch((err) => ({ ok: false, reason: String(err?.message ?? err) }))+ port1.postMessage({ id: req.id, result: result ?? null })+ }+ frame.contentWindow.postMessage({ kind: 'bento-serve', html, plan: v.plan, name: path.split('/').pop() }, '*', [port2])+ }+ addEventListener('message', onReady)+ document.body.appendChild(frame)+}+main()diff --git a/scripts/gen-webext-id.mjs b/scripts/gen-webext-id.mjsindex da0ff205..4218a877 100644--- a/scripts/gen-webext-id.mjs+++ b/scripts/gen-webext-id.mjs@@ -23,7 +23,7 @@ import { stripTypeScriptTypes } from 'node:module'const root = join(dirname(fileURLToPath(import.meta.url)), '..')const OUT = join(root, 'home/webext/src/id/gen')// The entry points; every module they import from kernel/src comes with them.-const ENTRY = ['statements.ts', 'address.ts', 'recovery.ts']+const ENTRY = ['statements.ts', 'address.ts', 'recovery.ts', 'gate1.ts']const VALUE_IMPORT = /^import (?!type )[^;]*?from '\.\/([a-z0-9-]+)\.ts'/gmexport function generate() {diff --git a/scripts/pack-webext.mjs b/scripts/pack-webext.mjsindex d2aa5b7d..7f2b171b 100644--- a/scripts/pack-webext.mjs+++ b/scripts/pack-webext.mjs@@ -52,6 +52,8 @@ const INCLUDE = [// (scripts/gen-webext-id.mjs), and the vendored Argon2id with its licence/^src\/id\/(gen\/)?[^/]+\.js$/,/^src\/id\/vendor\/noble-hashes\/([^/]+\.js|LICENSE)$/,+ // bento/connect W2: the served-document host page and its sandbox page+ /^src\/serve\/[^/]+\.(js|html)$/,/^_locales\/[a-zA-Z_]+\/messages\.json$/,]/** Present on purpose, deliberately NOT shipped. */diff --git a/scripts/qa-webext-live-gate1.mjs b/scripts/qa-webext-live-gate1.mjsnew file mode 100644index 00000000..d6d183c6--- /dev/null+++ b/scripts/qa-webext-live-gate1.mjs@@ -0,0 +1,102 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/connect W2 — the extension's gate 1 against the LIVE release (manual).+//+// node scripts/qa-webext-live-gate1.mjs # against bento.page, live+// node scripts/qa-webext-live-gate1.mjs --offline # against kernel's frozen+// # real/slides-1.2.10 snapshot+// (CHROME_PATH picks a browser build)+//+// Not a CI rig: it needs a browser (and, live, bento.page). The fixtures can't catch+// what the real channel does (home-ios found two such bugs: the history names+// the app "bento-slides", and a fresh shell's empty document block names no+// app, so every held history must be tried). This runs the extension's OWN+// code — serve/history.js with the pinned release key, serve/prepare.js — on:+// · the live signed histories for every app;+// · the current fresh shell, exactly as New writes it → GENUINE;+// · a real deck saved by that release (edited via window.bento) → GENUINE;+// · that deck with ONE runtime byte changed → UNKNOWN (the control);+// · that deck with one DOCUMENT byte changed → GENUINE (content is free).+// Exit status is the verdict.++const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')+import { readdirSync, mkdtempSync, existsSync } from 'node:fs'+import { join, dirname } from 'node:path'+import { homedir, tmpdir } from 'node:os'+import { fileURLToPath } from 'node:url'+import { readFileSync } from 'node:fs'++const H = await import('../home/webext/src/serve/history.js')+const P = await import('../home/webext/src/serve/prepare.js')+const { RELEASE_KEY } = await import('../home/webext/src/release.js')+const { APPS } = await import('../home/webext/src/library.js')++function chromePath() {+ if (process.env.CHROME_PATH) return process.env.CHROME_PATH+ const base = join(homedir(), '.cache/puppeteer/chrome')+ for (const b of existsSync(base) ? readdirSync(base).sort().reverse() : []) {+ for (const p of ['chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing', 'chrome-linux64/chrome'])+ if (existsSync(join(base, b, p))) return join(base, b, p)+ }+ return undefined+}++let failures = 0+const ok = (cond, msg) => { if (!cond) failures++; console.log(` ${cond ? 'ok ' : 'FAIL'} ${msg}`) }+const OFFLINE = process.argv.includes('--offline')+const SNAP = join(dirname(fileURLToPath(import.meta.url)), '../home/fixtures/gate1/real/slides-1.2.10')+let get = (u) => fetch(u)+if (OFFLINE) {+ // the frozen snapshot, served as bento.page would: the slides history and+ // shell; every other app 404s, as they do live today+ const snapKey = JSON.parse(readFileSync(join(SNAP, 'release-public-key.json'), 'utf8'))+ ok(snapKey.x === RELEASE_KEY.x && snapKey.y === RELEASE_KEY.y, "the snapshot's release key IS the extension's pinned key (so the pinned key, not a test key, verifies it)")+ const files = {+ 'https://bento.page/releases/slides/history.json': readFileSync(join(SNAP, 'history.json'), 'utf8'),+ 'https://bento.page/releases/slides/Bento_Slides.bento.html': readFileSync(join(SNAP, 'Bento_Slides.bento.html'), 'utf8'),+ }+ get = async (u) => (u in files ? new Response(files[u]) : new Response('', { status: 404 }))+}+console.log(OFFLINE ? 'source: frozen snapshot real/slides-1.2.10' : 'source: bento.page, live')+const m = new Map()+const deps = { get: async (k) => m.get(k) ?? null, set: async (k, v) => { m.set(k, v) }, fetch: (u, o) => get(u, o), now: () => Date.now(), jwk: RELEASE_KEY }+const report = await H.refresh(APPS.map(({ id, appId }) => ({ id, appId })), deps)+console.log('histories:', JSON.stringify(report))+const held = await H.heldHistories(deps)+ok(Object.keys(held).length > 0, `at least one history verifies under the pinned release key (${Object.keys(held).join(', ')})`)++for (const app of APPS) {+ if (!held[app.appId]) continue+ // live: the signed manifest names the current shell; offline: the+ // snapshot's newest release, at the same address+ const man = OFFLINE+ ? { version: held[app.appId].releases[0].version, url: `https://bento.page/releases/${app.id}/Bento_Slides.bento.html` }+ : JSON.parse(JSON.parse(await (await fetch(app.manifest)).text()).payload)+ const fresh = await (await get(man.url)).text()+ const v = await P.prepare(fresh, held)+ ok(v.verdict === 'genuine' && v.appId === app.appId && v.release.version === man.version, `${app.id} ${man.version}: the fresh shell (as New writes it) is GENUINE`)+ const ctx = await chromium.launchPersistentContext(mkdtempSync(join(tmpdir(), 'live-')), { executablePath: chromePath(), headless: true })+ const page = await ctx.newPage()+ await page.setContent('<p>loading</p>')+ const dir = mkdtempSync(join(tmpdir(), 'shell-'))+ const { writeFileSync } = await import('node:fs')+ writeFileSync(join(dir, 'fresh.bento.html'), fresh)+ await page.goto('file://' + join(dir, 'fresh.bento.html'))+ await page.waitForFunction(() => window.bento && typeof window.bento.serialize === 'function', null, { timeout: 30000 })+ const saved = await page.evaluate(async () => {+ const d = JSON.parse(JSON.stringify(window.bento.doc))+ d.title = 'A real saved deck'+ if (window.bento.loadDoc) await window.bento.loadDoc(JSON.stringify(d))+ return await window.bento.serialize()+ })+ await ctx.close()+ ok((await P.prepare(saved, held)).verdict === 'genuine', `${app.id}: a real deck saved by that release is GENUINE`)+ const rt = saved.indexOf('id="bento-rt"')+ const at = saved.indexOf('>', rt) + 20+ ok((await P.prepare(saved.slice(0, at) + (saved[at] === 'A' ? 'B' : 'A') + saved.slice(at + 1), held)).verdict === 'unknown', `${app.id}: CONTROL — one runtime byte changed is UNKNOWN`)+ const d1 = saved.indexOf('A real saved deck', saved.indexOf('id="bento-doc"'))+ ok((await P.prepare(saved.slice(0, d1) + 'B' + saved.slice(d1 + 1), held)).verdict === 'genuine', `${app.id}: one document byte changed is still GENUINE (content is free)`)+}+console.log(failures ? `\n${failures} FAILED` : '\nall passed')+process.exit(failures ? 1 : 0)diff --git a/scripts/qa-webext-serve.mjs b/scripts/qa-webext-serve.mjsnew file mode 100644index 00000000..11b73590--- /dev/null+++ b/scripts/qa-webext-serve.mjs@@ -0,0 +1,251 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/connect W2 — the served-document sandbox, in a real browser (manual).+//+// node scripts/qa-webext-serve.mjs [path/to/genuine.bento.html]+//+// Not a CI rig: CI's headless shell can't load extensions. It loads the+// unpacked extension into Chrome for Testing and opens a GENUINE document+// through serve.html, then plays the document's part with frame.evaluate+// (which runs as page script in the sandbox's realm):+// · the real deck boots in the sandbox; the identity agent answers over the port;+// · CRITICAL (security 2026-10-24): page script patches+// MessagePort.prototype.postMessage/start, EventTarget.prototype.addEventListener,+// the MessageEvent data getter and Function.prototype.call/bind, then calls the+// agent — the patches never see the port, and the call still works;+// · __bentoIdentity can't be replaced (assign, defineProperty, delete);+// · a well-formed request posted on window, or from a child frame, reaches nothing;+// · a second handshake is ignored;+// · an inline script the plan did not list does NOT run (the sandbox CSP).+// Defaults to the frozen real 1.2.10 deck if present, else fetches the live shell.++const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')+import { readdirSync, mkdtempSync, existsSync, cpSync, writeFileSync, readFileSync } from 'node:fs'+import { join, dirname } from 'node:path'+import { homedir, tmpdir } from 'node:os'+import { fileURLToPath } from 'node:url'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+let failures = 0+const ok = (c, m) => { if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }+function chromePath() {+ if (process.env.CHROME_PATH) return process.env.CHROME_PATH+ const base = join(homedir(), '.cache/puppeteer/chrome')+ for (const b of existsSync(base) ? readdirSync(base).sort().reverse() : []) {+ for (const p of ['chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing', 'chrome-linux64/chrome'])+ if (existsSync(join(base, b, p))) return join(base, b, p)+ }+}++const work = mkdtempSync(join(tmpdir(), 'serve-qa-'))+const ext = join(work, 'ext'); cpSync(join(root, 'home/webext'), ext, { recursive: true })+// a harness page for the sandbox-only rows (a plan that omits a script)+writeFileSync(join(ext, 'src/serve/qa-harness.html'), '<!doctype html><meta charset="utf-8"><body><script type="module" src="qa-harness.js"></script></body>')+writeFileSync(join(ext, 'src/serve/qa-harness.js'), `+const f = document.createElement('iframe'); f.src = 'sandbox.html'; document.body.appendChild(f)+window.__qa = new Promise((res) => {+ addEventListener('message', (ev) => {+ if (ev.source !== f.contentWindow || ev.data?.kind !== 'bento-serve-ready') return+ const html = '<!doctype html><body><p id="p">x</p><script>document.title = "INLINE RAN"</' + 'script><script>window.planned = 1</' + 'script></body>'+ const at = html.indexOf('<script>window.planned')+ const end = html.indexOf('</' + 'script>', at) + 9+ const { port1, port2 } = new MessageChannel()+ f.contentWindow.postMessage({ kind: 'bento-serve', html, plan: [{ tagStart: at, end, text: 'window.planned = 1', module: false }], name: 'qa.bento.html' }, '*', [port2])+ // ONE-SHOT: a second handshake, with another document and another port, must be ignored+ setTimeout(() => {+ const second = '<!doctype html><body><p id="second">SECOND</p><script>window.second = 1</' + 'script></body>'+ const s0 = second.indexOf('<script>'), s1 = second.indexOf('</' + 'script>') + 9+ const c = new MessageChannel()+ window.__secondPortHits = 0+ c.port1.onmessage = () => { window.__secondPortHits++ }+ f.contentWindow.postMessage({ kind: 'bento-serve', html: second, plan: [{ tagStart: s0, end: s1, text: 'window.second = 1', module: false }], name: 'x' }, '*', [c.port2])+ }, 600)+ setTimeout(() => res(f), 1500)+ })+})`)+// Count, on the HOST side, every message that arrives on its port (QA copy+// only), so 'reached the host' is measured rather than inferred.+{+ const f = join(ext, 'src/serve/serve.js')+ const src = readFileSync(f, 'utf8')+ const out = src.replace(' const req = parseRequest(e.data)', ' ;(window.__qaPort ??= []).push(e.data?.op ?? null)\n const req = parseRequest(e.data)')+ if (out === src) throw new Error('host counter: the parseRequest line moved; update the replace')+ writeFileSync(f, out)+}+// POSITIVE CONTROL for the CRITICAL row: a copy of the sandbox whose bridge calls+// port.postMessage the naive way. The same probe MUST catch it, or a clean+// result on the real sandbox would prove nothing.+{+ const src = readFileSync(join(ext, 'src/serve/sandbox.js'), 'utf8')+ const naive = src.replace(' portPost(port, { id, op, args })', ' port.postMessage({ id, op, args })')+ if (naive === src) throw new Error('positive control: the ask() line moved; update the replace')+ writeFileSync(join(ext, 'src/serve/sandbox-naive.js'), naive)+ writeFileSync(join(ext, 'src/serve/sandbox-naive.html'), '<!doctype html><meta charset="utf-8"><script src="sandbox-naive.js"></script>')+ const mf = JSON.parse(readFileSync(join(ext, 'manifest.json'), 'utf8'))+ mf.sandbox.pages.push('src/serve/sandbox-naive.html')+ writeFileSync(join(ext, 'manifest.json'), JSON.stringify(mf, null, 2))+ writeFileSync(join(ext, 'src/serve/qa-naive.html'), '<!doctype html><meta charset="utf-8"><body><script type="module" src="qa-naive.js"></script></body>')+ writeFileSync(join(ext, 'src/serve/qa-naive.js'), `+const f = document.createElement('iframe'); f.src = 'sandbox-naive.html'; document.body.appendChild(f)+addEventListener('message', (ev) => {+ if (ev.source !== f.contentWindow || ev.data?.kind !== 'bento-serve-ready') return+ const { port1, port2 } = new MessageChannel()+ port1.onmessage = (e) => port1.postMessage({ id: e.data.id, result: null })+ f.contentWindow.postMessage({ kind: 'bento-serve', html: '<!doctype html><body>naive</body>', plan: [], name: 'n' }, '*', [port2])+})`)+}+const PROBE = async () => {+ const seen = []+ const mp = MessagePort.prototype, et = EventTarget.prototype, fp = Function.prototype+ const oPost = mp.postMessage, oStart = mp.start, oAdd = et.addEventListener, oCall = fp.call, oBind = fp.bind+ const dataDesc = Object.getOwnPropertyDescriptor(MessageEvent.prototype, 'data')+ mp.postMessage = function (...a) { seen.push('postMessage'); return oPost.apply(this, a) }+ mp.start = function (...a) { seen.push('start'); return oStart.apply(this, a) }+ et.addEventListener = function (...a) { if (this instanceof MessagePort) seen.push('addEventListener on a port'); return oAdd.apply(this, a) }+ Object.defineProperty(MessageEvent.prototype, 'data', { configurable: true, get() { if (this.target instanceof MessagePort || this.currentTarget instanceof MessagePort) seen.push('data getter on a port event'); return dataDesc.get.call(this) } })+ fp.call = function (...a) { if (a[0] instanceof MessagePort) seen.push('call with a port'); return oCall.apply(this, a) }+ fp.bind = function (...a) { if (a[0] instanceof MessagePort) seen.push('bind with a port'); return oBind.apply(this, a) }+ const r1 = await window.__bentoIdentity.whoami()+ const r2 = await window.__bentoIdentity.sign('frame', '1.y')+ return { seen, r1, r2 }+}+let docPath = process.argv[2]+if (!docPath) {+ const dir = mkdtempSync(join(tmpdir(), 'serve-doc-'))+ const man = JSON.parse(JSON.parse(await (await fetch('https://bento.page/releases/slides/manifest.json')).text()).payload)+ docPath = join(dir, 'Real deck.bento.html')+ writeFileSync(docPath, await (await fetch(man.url)).text())+}++const ctx = await chromium.launchPersistentContext(join(work, 'profile'), { executablePath: chromePath(), headless: true, args: [`--disable-extensions-except=${ext}`, `--load-extension=${ext}`] })+let [sw] = ctx.serviceWorkers(); if (!sw) sw = await ctx.waitForEvent('serviceworker')+const id = new URL(sw.url()).host++// 0. both gates: with the setting at its default (absent), the host page refuses+{+ const off = await ctx.newPage()+ await off.goto(`chrome-extension://${id}/src/serve/serve.html?path=${encodeURIComponent(docPath)}`).catch(() => {})+ await off.waitForTimeout(1200)+ ok(off.url().startsWith('file://') && !off.frames().some((fr) => fr.url().includes('sandbox.html')), 'with the setting at its default (off), even a GENUINE file opens as itself, never in the sandbox')+ await off.close()+ await sw.evaluate(() => chrome.storage.local.set({ serveWithIdentity: true }))+}++// 1. a genuine document, served+const page = await ctx.newPage()+const logs = []; page.on('console', (m) => logs.push(m.text()))+await page.goto(`chrome-extension://${id}/src/serve/serve.html?path=${encodeURIComponent(docPath)}`)+await page.waitForTimeout(500)+const servedUrl = page.url()+ok(servedUrl.startsWith(`chrome-extension://${id}/src/serve/serve.html`), `a genuine document stays on the host page (${servedUrl.slice(0, 60)}…) — ${logs.filter((l) => l.includes('bento/connect')).join(' | ')}`)+const frame = await (async () => { for (let i = 0; i < 100; i++) { const f = page.frames().find((fr) => fr.url().includes('sandbox.html')); if (f) return f; await page.waitForTimeout(100) } })()+ok(!!frame, 'the sandbox frame exists')+await frame.waitForFunction(() => window.bento && typeof window.bento.serialize === 'function', null, { timeout: 30000 }).catch(() => {})+ok(await frame.evaluate(() => !!(window.bento && window.bento.doc)), 'the real deck boots in the sandbox (window.bento is there)')+ok(await frame.evaluate(() => { try { localStorage.getItem('x'); return false } catch { return true } }), 'and has no storage of its own (opaque origin)')+ok(await frame.evaluate(async () => (await window.__bentoIdentity.whoami()) === null), 'the agent answers over the port: whoami → null (no verified Bento ID yet)')+ok(await frame.evaluate(async () => JSON.stringify(await window.__bentoIdentity.sign('frame', '0.x')) === '{"ok":false,"reason":"no-identity"}'), 'sign → no-identity')++// 2. CRITICAL: page script patches every prototype the bridge could touch, then calls the agent+const crit = await frame.evaluate(PROBE)+ok(crit.seen.length === 0, `with postMessage/start/addEventListener/the data getter/call/bind all patched, the patches never saw the port (${crit.seen.join(', ') || 'nothing'})`)+ok(crit.r1 === null && crit.r2?.reason === 'no-identity', 'and the agent still works through the captured functions')++// 2b. security's further probes: Object.prototype accessors that cloning, JSON or+// promise resolution might consult, and a re-entrant call from a patched then+const more = await frame.evaluate(async () => {+ const bad = []+ const hits = Object.create(null)+ const suspicious = (v) => v instanceof MessagePort || v instanceof MessageEvent || (typeof Window !== 'undefined' && v instanceof Window && v !== window)+ const keys = ['id', 'op', 'args', 'result', 'ok', 'reason', 'data', 'ports', 'source', 'then', 'toJSON', 'text', 'kind', 'plan', 'html', 'name', 'payload', 'purpose', 'pub', 'email']+ for (const k of keys) {+ if (Object.prototype.hasOwnProperty(k)) continue+ Object.defineProperty(Object.prototype, k, {+ configurable: true,+ get() { hits[k] = (hits[k] ?? 0) + 1; if (suspicious(this)) bad.push(`get ${k} on ${this?.constructor?.name}`); return undefined },+ set(v) { if (suspicious(this) || suspicious(v)) bad.push(`set ${k}`); Object.defineProperty(this, k, { value: v, writable: true, enumerable: true, configurable: true }) },+ })+ }+ let thenCalls = 0, reentered = []+ const oThen = Promise.prototype.then+ Promise.prototype.then = function (f, r) {+ thenCalls+++ if (thenCalls < 4) reentered.push(window.__bentoIdentity.whoami())+ for (const a of [f, r]) if (suspicious(a)) bad.push('then got a port/event')+ return oThen.call(this, f, r)+ }+ const out = await Promise.all([window.__bentoIdentity.whoami(), window.__bentoIdentity.sign('frame', '2.z'), window.__bentoIdentity.resolve({ pub: null, email: '[email protected]' })])+ Promise.resolve(1).then(() => {}) // the page's own use: proves the patch is live+ const re = await Promise.all(reentered)+ Promise.prototype.then = oThen+ for (const k of keys) { const d = Object.getOwnPropertyDescriptor(Object.prototype, k); if (d && d.get) delete Object.prototype[k] }+ return { bad, hits: Object.entries(hits).map(([k, n]) => `${k}×${n}`).join(' '), thenCalls, out: JSON.stringify(out), re: JSON.stringify(re) }+})+ok(more.hits.length > 0, `(live) the patched Object.prototype accessors WERE consulted during the agent calls: ${more.hits}`)+ok(more.bad.length === 0, `and on 20 keys that cloning, JSON and promise resolution might touch, they never saw a port, an event or another window (${more.bad.join(', ') || 'nothing'})`)+ok(more.thenCalls > 0 && more.out === '[null,{"ok":false,"reason":"no-identity"},null]' && /^\[(null,?)+\]$/.test(more.re), `re-entrant agent calls from inside a patched Promise.prototype.then (live: ${more.thenCalls} calls) all answer correctly (${more.re})`)++// 3. the agent can't be replaced+const rep = await frame.evaluate(() => {+ const a = window.__bentoIdentity+ const tries = []+ try { window.__bentoIdentity = { contract: 1, whoami: () => 'EVIL' } } catch (e) { tries.push('assign:' + e.name) }+ try { Object.defineProperty(window, '__bentoIdentity', { value: { evil: 1 } }) } catch (e) { tries.push('define:' + e.name) }+ try { delete window.__bentoIdentity } catch (e) { tries.push('delete:' + e.name) }+ try { a.whoami = () => 'EVIL' } catch (e) { tries.push('member:' + e.name) }+ return { same: window.__bentoIdentity === a, frozen: Object.isFrozen(a), desc: JSON.stringify(Object.getOwnPropertyDescriptor(window, '__bentoIdentity') && { w: Object.getOwnPropertyDescriptor(window, '__bentoIdentity').writable, c: Object.getOwnPropertyDescriptor(window, '__bentoIdentity').configurable }), tries }+})+ok(rep.same && rep.frozen && rep.desc === '{"w":false,"c":false}', `__bentoIdentity can't be replaced, redefined, deleted or edited (${rep.tries.join(', ')})`)++// 4. requests that don't come through the port reach nothing+const portBefore = await page.evaluate(() => [...(window.__qaPort ?? [])])+const strays = await frame.evaluate(async () => {+ const req = { id: 's999', op: 'save.write', args: { text: 'EVIL' } }+ window.postMessage(req, '*')+ window.parent.postMessage(req, '*')+ window.top.postMessage(req, '*')+ const child = document.createElement('iframe'); document.body.appendChild(child)+ try { child.contentWindow.parent.postMessage(req, '*') } catch {}+ window.parent.postMessage({ kind: 'bento-serve-ready' }, '*')+ await new Promise((r) => setTimeout(r, 500))+ return true+})+await page.waitForTimeout(300)+ok(strays, 'a well-formed save request posted on window, to parent, to top and from a child frame was sent')+const portAfter = await page.evaluate(() => [...(window.__qaPort ?? [])])+ok(portBefore.filter((o) => o?.startsWith('identity.')).length >= 4, `(control) the host's counter does see the agent's own calls on the port: ${portBefore.join(', ')}`)+ok(portAfter.length === portBefore.length && !portAfter.includes('save.write'), `and none of the strays reached the host: nothing new arrived on its port (${portAfter.length - portBefore.length} new)`)++// 5. the sandbox-only rows: an inline script the plan did not list does not run+const h = await ctx.newPage()+await h.goto(`chrome-extension://${id}/src/serve/qa-harness.html`)+await h.waitForTimeout(2000)+const sb = h.frames().find((fr) => fr.url().includes('sandbox.html'))+const res = sb ? await sb.evaluate(() => ({ planned: window.planned, title: document.title })) : null+ok(res && res.planned === 1, 'a script IN the plan runs (as a blob: script)')+const second = sb ? await sb.evaluate(() => ({ second: window.second, el: !!document.getElementById('second'), first: !!document.getElementById('p') })) : null+ok(second && second.second === undefined && !second.el && second.first, 'ONE-SHOT: a second handshake (another document, another port) is ignored — the first document stays, the second never runs')+ok((await h.evaluate(() => window.__secondPortHits)) === 0, 'and the agent never talks on the second port')+const n = await ctx.newPage()+await n.goto(`chrome-extension://${id}/src/serve/qa-naive.html`)+await n.waitForTimeout(1200)+const nf = n.frames().find((fr) => fr.url().includes('sandbox-naive.html'))+const naive = nf ? await nf.evaluate(PROBE) : null+ok(naive && naive.seen.includes('postMessage'), `POSITIVE CONTROL: the same probe CATCHES a naive bridge that calls port.postMessage (${naive?.seen.join(', ')})`)+ok(res && res.title !== 'INLINE RAN', `an inline script NOT in the plan does not run — the fixed CSP refuses it (title "${res?.title}")`)++// 6. an UNKNOWN file opens as itself, without identity+const dir = mkdtempSync(join(tmpdir(), 'serve-unknown-'))+const genuine = readFileSync(docPath, 'utf8')+const rt = genuine.indexOf('id="bento-rt"'); const at = genuine.indexOf('>', rt) + 20+const tampered = join(dir, 'Tampered.bento.html')+writeFileSync(tampered, genuine.slice(0, at) + (genuine[at] === 'A' ? 'B' : 'A') + genuine.slice(at + 1))+const u = await ctx.newPage()+await u.goto(`chrome-extension://${id}/src/serve/serve.html?path=${encodeURIComponent(tampered)}`).catch(() => {})+await u.waitForTimeout(1500)+ok(u.url().startsWith('file://') && !u.frames().some((fr) => fr.url().includes('sandbox.html')), `a one-byte-tampered copy is UNKNOWN: it opens as itself (${u.url().slice(0, 40)}…), never in the sandbox`)++await ctx.close()+console.log(failures ? `\n${failures} FAILED` : '\nall passed')+process.exit(failures ? 1 : 0)diff --git a/scripts/test-webext-id.ts b/scripts/test-webext-id.tsindex 8a53915d..785c5559 100644--- a/scripts/test-webext-id.ts+++ b/scripts/test-webext-id.ts@@ -7,10 +7,10 @@//// WHAT THIS PROVES. The extension's bento/connect code IS the kernel reference,// unaltered: home/webext/src/id/gen/ is a current type-strip of kernel/src-// (statements, address, display table, recovery), with no leftovers, and-// kernel's own rigs, re-pointed at that copy, pass every row of-// kernel/fixtures/identity-v1.json and recovery-v1.json, exactly as many rows-// as on kernel's source.+// (statements, address, display table, recovery, gate1), with no leftovers,+// and kernel's own rigs, re-pointed at that copy, pass every row of+// kernel/fixtures/identity-v1.json, recovery-v1.json and the gate-1 corpus+// (home/fixtures/gate1), exactly as many rows as on kernel's source.import { readFileSync, writeFileSync, mkdtempSync, readdirSync } from 'node:fs'import { join, dirname } from 'node:path'@@ -50,15 +50,15 @@ const run = (file: string) => {const m = tail.match(/^(\d+)\/(\d+) checks passed$/)return { ok: r.status === 0 && !!m && m[1] === m[2], total: m ? Number(m[2]) : 0, tail: tail || r.stderr.trim().split('\n').slice(-3).join(' | ') }}-for (const [rig, contract] of [['test-statements.ts', 'kernel/fixtures/identity-v1.json'], ['test-recovery.ts', 'kernel/fixtures/recovery-v1.json']]) {+for (const [rig, contract] of [['test-statements.ts', 'kernel/fixtures/identity-v1.json'], ['test-recovery.ts', 'kernel/fixtures/recovery-v1.json'], ['test-gate1.ts', 'home/fixtures/gate1']]) {console.log(`\n— ${contract}, against the extension's copy (scripts/${rig})`)const src = readFileSync(join(root, 'scripts', rig), 'utf8')const gen = (f: string) => pathToFileURL(join(root, 'home/webext/src/id/gen', f)).hrefconst swapped = src- .replace(/from '\.\.\/kernel\/src\/(statements|address|recovery)\.ts'/g, (_m, f) => `from '${gen(f + '.js')}'`)+ .replace(/from '\.\.\/kernel\/src\/(statements|address|recovery|gate1)\.ts'/g, (_m, f) => `from '${gen(f + '.js')}'`).replace("from '../kernel/src/identity.ts'", `from '${pathToFileURL(join(root, 'kernel/src/identity.ts')).href}'`).replace(/join\(dirname\(fileURLToPath\(import\.meta\.url\)\), '\.\.'/g, `join(${JSON.stringify(root)}`)- ok(swapped !== src && !/from '\.\.\/kernel\/src\/(statements|address|recovery)\.ts'/.test(swapped), `${rig} is re-pointed at the extension's generated files`)+ ok(swapped !== src && !/from '\.\.\/kernel\/src\/(statements|address|recovery|gate1)\.ts'/.test(swapped), `${rig} is re-pointed at the extension's generated files`)const f = join(dir, rig)writeFileSync(f, swapped)const kernel = run(join(root, 'scripts', rig))diff --git a/scripts/test-webext-serve.ts b/scripts/test-webext-serve.tsnew file mode 100644index 00000000..0cc069e7--- /dev/null+++ b/scripts/test-webext-serve.ts@@ -0,0 +1,238 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// home/webext — serving a verified document with identity (bento/connect W2).+//+// node scripts/test-webext-serve.ts+//+// WHAT THIS PROVES (so far: the release histories gate 1 checks against, and+// what may become running script in the sandbox).+// · A history is held only if it verifies under the release key, names the+// right app, is well-formed, and kernel's acceptHistory accepts it over+// what is held (anti-rollback: an older signed history can't hide a release).+// · It is fetched at most daily, never for someone who hasn't used identity+// opening, and a failed fetch keeps what is held.+// The corpus's signed history (home/fixtures/gate1/history.json) and its+// throwaway test key stand in for the real ones.++import { readFileSync } from 'node:fs'+import { join, dirname } from 'node:path'+import { fileURLToPath } from 'node:url'++const root = join(dirname(fileURLToPath(import.meta.url)), '..')+const H = await import('../home/webext/src/serve/history.js')+const G = await import('../home/webext/src/id/gen/gate1.js')++let failures = 0+let checks = 0+function ok(cond: boolean, msg: string) {+ checks+++ if (!cond) { failures++; console.log(` FAIL ${msg}`) }+ else console.log(` ok ${msg}`)+}++const FIX = join(root, 'home/fixtures/gate1')+const signed = readFileSync(join(FIX, 'history.json'), 'utf8')+const jwk = JSON.parse(readFileSync(join(FIX, 'test-public-key.json'), 'utf8'))+const payload = JSON.parse(JSON.parse(signed).payload)+const APPS = [{ id: 'test', appId: payload.app }]+const DAY = H.DAY+let clock = Date.UTC(2026, 9, 21)+const storage = () => { const m = new Map<string, any>(); return { m, get: async (k: string) => m.get(k) ?? null, set: async (k: string, v: any) => { m.set(k, structuredClone(v)) } } }+const net = (body: string | null, status = 200) => { const calls: string[] = []; return { calls, fetch: async (u: string) => { calls.push(u); if (body === null) throw new TypeError('offline'); return { ok: status === 200, status, text: async () => body } } } }+const deps = (s: any, n: any) => ({ get: s.get, set: s.set, fetch: n.fetch, now: () => clock, jwk })++console.log('\n— holding a verified history')+{+ const s = storage(), n = net(signed)+ const r = await H.refresh(APPS, deps(s, n))+ ok(r[payload.app] === 'updated' && n.calls[0] === `${H.BASE}/test/history.json`, 'a signed, well-formed history for the app is fetched from bento.page and held')+ const held = await H.heldHistories(deps(s, n))+ ok(JSON.stringify(held[payload.app]) === JSON.stringify(payload), 'what is held is exactly the signed payload')+ // and gate 1 can use it: a genuine corpus file is genuine against the held history+ const genuine = readFileSync(join(FIX, 'served/genuine-1.2.0.html'), 'utf8')+ const v = await G.verifyServed(genuine, held[payload.app])+ ok(v.verdict === 'genuine' && v.release.version === '1.2.0', 'gate 1 matches a genuine file against the held history')+ // fresh: no refetch inside a day+ clock += DAY / 2+ const again = await H.refresh(APPS, deps(s, n))+ ok(again[payload.app] === 'fresh' && n.calls.length === 1, 'not fetched again within a day')+ clock += DAY+ await H.refresh(APPS, deps(s, n))+ ok(n.calls.length === 2, 'fetched again after a day')+}++console.log('\n— refusing what must not be held')+{+ const bad = (mut: (o: any) => void) => { const o = JSON.parse(signed); mut(o); return JSON.stringify(o) }+ const cases: [string, string, string][] = [+ ['a payload changed after signing', bad((o) => { o.payload = o.payload.replace('1.2.0', '1.2.9') }), 'signature'],+ ['a missing signature', bad((o) => { delete o.sig }), 'not signed'],+ ['not JSON', 'nope', 'not valid JSON'],+ ]+ for (const [label, body, why] of cases) {+ const s = storage()+ const r = await H.refresh(APPS, deps(s, net(body)))+ ok(String(r[payload.app]).startsWith('refused') && String(r[payload.app]).includes(why) && !(await H.heldHistories(deps(s, net(body))))[payload.app], `${label} is refused and nothing is held`)+ }+ const s = storage()+ const r = await H.refresh([{ id: 'test', appId: 'bento-slides' }], deps(s, net(signed)))+ ok(r['bento-slides'] === 'refused: history for another app', 'a genuine history for ANOTHER app is refused (sibling channels on one origin)')+}++console.log('\n— anti-rollback, and failures keep what is held')+{+ const s = storage()+ await H.refresh(APPS, deps(s, net(signed)))+ // a REPLAYED older history, validly signed: the rig signs with its own key+ // pair, so refresh's own anti-rollback check is what's under test+ const kp = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])+ const pubJwk = await crypto.subtle.exportKey('jwk', kp.publicKey)+ const sign = async (p: any) => {+ const text = JSON.stringify(p)+ const sig = new Uint8Array(await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, kp.privateKey, new TextEncoder().encode(text)))+ return JSON.stringify({ payload: text, sig: Buffer.from(sig).toString('base64') })+ }+ const own = storage()+ const ownDeps = (n: any) => ({ ...deps(own, n), jwk: pubJwk })+ ok((await H.refresh(APPS, ownDeps(net(await sign(payload)))))[payload.app] === 'updated', 'a history signed by the (rig\'s) release key is held')+ clock += 2 * DAY+ const older = { ...payload, releases: payload.releases.slice(1) }+ const replay = await H.refresh(APPS, ownDeps(net(await sign(older))))+ ok(String(replay[payload.app]).startsWith('refused') && (await H.heldHistories(ownDeps(net(null))))[payload.app].releases.length === payload.releases.length,+ `a REPLAYED older history, validly signed, is refused by refresh and the newer one stays held (${replay[payload.app]})`)+ clock += 2 * DAY+ const r = await H.refresh(APPS, deps(s, net(null)))+ ok(String(r[payload.app]).startsWith('refused') && (await H.heldHistories(deps(s, net(null))))[payload.app]?.releases.length === payload.releases.length, 'offline: the refresh fails and what is held stays')+ const r2 = await H.refresh(APPS, deps(s, net('x', 503)))+ ok(r2[payload.app] === 'http 503' && !!(await H.heldHistories(deps(s, net(null))))[payload.app], 'a server error keeps what is held')+}++console.log('\n— no phone-home for someone who never used it')+{+ const s = storage(), n = net(signed)+ const r = await H.refreshIfUsed(APPS, deps(s, n))+ ok(r.skipped === 'never used' && n.calls.length === 0, 'the browser-start refresh makes NO request until identity opening has been used')+ await s.set(H.USED_KEY, true)+ await H.refreshIfUsed(APPS, deps(s, n))+ ok(n.calls.length === 1, 'after it has been used, the browser-start refresh fetches')+}++console.log('\n— prepare: gate 1 decides, against the held histories (every served corpus row)')+const P = await import('../home/webext/src/serve/prepare.js')+const EXP = JSON.parse(readFileSync(join(FIX, 'expected.json'), 'utf8'))+const histories = { [payload.app]: payload }+{+ let agree = 0+ for (const row of EXP.served) {+ const html = readFileSync(join(FIX, row.case), 'utf8')+ const r = await P.prepare(html, histories)+ const want = row.verdict === 'genuine' ? 'genuine' : 'unknown'+ if (r.verdict === want && (want === 'unknown' || r.release.version === row.release)) agree+++ else console.log(` ${row.case}: got ${r.verdict}, expected ${want}`)+ }+ ok(agree === EXP.served.length, `prepare reaches the corpus verdict on every served row (${agree}/${EXP.served.length})`)+ const genuine = readFileSync(join(FIX, 'served/genuine-1.2.0.html'), 'utf8')+ ok((await P.prepare(genuine, {})).verdict === 'unknown', 'with NO history held, even a genuine file is UNKNOWN (never a guess)')+ const two = await P.prepare(genuine, { a: payload, b: payload })+ ok(two.verdict === 'unknown' && /^2 held histories match/.test(two.reason), `a file matching two apps is UNKNOWN (${two.reason})`)+}++console.log('\n— splice: only the planned elements become blob: scripts')+{+ for (const name of ['genuine-1.0.0.html', 'genuine-1.2.0.html', 'genuine-1.1.0-shared-runtime.html']) {+ const html = readFileSync(join(FIX, 'served', name), 'utf8')+ const r = await P.prepare(html, histories)+ const urls: string[] = []+ const out = P.splice(html, r.plan, (text: string) => { urls.push(text); return `blob:test/${urls.length}` })+ const scripts = G.scanBlocks(out).filter((b: any) => b.tag === 'script')+ const exec = G.executableScripts(G.scanBlocks(out))+ ok(r.plan.length >= 1 && urls.length === r.plan.length && exec.length === r.plan.length && exec.every((b: any) => b.text === '' && /^blob:test\/\d+$/.test(b.src)), `${name}: each executable element (${r.plan.length}) became an EMPTY script loading a blob:, and nothing else became one`)+ const before = G.scanBlocks(html).filter((b: any) => !G.executableScripts([b]).length).map((b: any) => b.text)+ const after = scripts.filter((b: any) => !b.src).map((b: any) => b.text).concat(G.scanBlocks(out).filter((b: any) => b.tag === 'style').map((b: any) => b.text))+ ok(before.every((t: string) => after.includes(t)), `${name}: data blocks and styles pass through byte for byte`)+ ok(urls.join('\u0000') === r.plan.map((p: any) => p.text).join('\u0000'), `${name}: the blob: contents are exactly the verified texts, in document order`)+ }+ const html = readFileSync(join(FIX, 'served/genuine-1.2.0.html'), 'utf8')+ const r = await P.prepare(html, histories)+ const throws = (f: () => unknown) => { try { f(); return false } catch { return true } }+ ok(throws(() => P.splice(html + ' ', [...r.plan].reverse(), () => 'blob:x')) || r.plan.length < 2, 'a plan out of document order is refused')+ ok(throws(() => P.splice('<p>other</p>' + html, r.plan, () => 'blob:x')), 'a plan that does not line up with the bytes is refused')+}++// --- the REAL release, frozen (kernel real/slides-1.2.10): the extension's own+// refresh with its PINNED release key, then prepare, exactly as on bento.page+{+ const SNAP = join(FIX, 'real/slides-1.2.10')+ const { RELEASE_KEY } = await import('../home/webext/src/release.js')+ const files: Record<string, string> = { 'https://bento.page/releases/slides/history.json': readFileSync(join(SNAP, 'history.json'), 'utf8') }+ const m = new Map()+ const deps = { get: async (k: string) => m.get(k) ?? null, set: async (k: string, v: unknown) => { m.set(k, v) }, fetch: async (u: string) => (u in files ? new Response(files[u]) : new Response('', { status: 404 })), now: () => Date.now(), jwk: RELEASE_KEY }+ const rep = await H.refresh([{ id: 'slides', appId: 'bento-slides' }, { id: 'spaces', appId: 'bento-spaces' }, { id: 'dash', appId: 'bento-dash' }], deps)+ ok(rep['bento-slides'] === 'updated', `the real slides history verifies under the extension's PINNED release key (${JSON.stringify(rep)})`)+ const held = await H.heldHistories(deps)+ const shell = readFileSync(join(SNAP, 'Bento_Slides.bento.html'), 'utf8')+ const v = await P.prepare(shell, held)+ ok(v.verdict === 'genuine' && v.appId === 'bento-slides' && v.release.version === '1.2.10', `the real 1.2.10 shell (an EMPTY document block, naming no app) is GENUINE as bento-slides 1.2.10 (${v.verdict} ${v.appId ?? v.reason})`)+ const rt = shell.indexOf('id="bento-rt"'); const at = shell.indexOf('>', rt) + 20+ ok((await P.prepare(shell.slice(0, at) + (shell[at] === 'A' ? 'B' : 'A') + shell.slice(at + 1), held)).verdict === 'unknown', 'CONTROL: the same shell with one runtime byte changed is UNKNOWN')+ const wrong = await H.refresh([{ id: 'slides', appId: 'bento-dash' }], { ...deps, get: async () => null, set: async () => {} })+ ok(wrong['bento-dash'] !== 'updated', `the real slides history is refused when offered as another app's (${JSON.stringify(wrong)})`)+}++// --- the host's port: only the fixed shape is acted on ------------------------+{+ const { parseRequest, answer } = await import('../home/webext/src/serve/host.js')+ const good = [+ { id: 's1', op: 'identity.whoami', args: null },+ { id: 's2', op: 'identity.sign', args: { purpose: 'frame', payload: '0.x' } },+ { id: 's3', op: 'identity.resolve', args: { pub: null, email: '[email protected]' } },+ { id: 's4', op: 'save.write', args: { text: '<!doctype html>' } },+ ]+ ok(good.every((g) => JSON.stringify(parseRequest(g)) === JSON.stringify(g)), 'each well-formed request parses to exactly itself')+ const bad: [string, unknown][] = [+ ['not an object', 'identity.whoami'],+ ['an array', [1, 2]],+ ['an unknown op', { id: 's1', op: 'identity.export', args: null }],+ ['an extra top-level field', { id: 's1', op: 'identity.whoami', args: null, consent: 'granted' }],+ ['a consent outcome dressed as an op', { id: 's1', op: 'consent.granted', args: null }],+ ['a missing id', { op: 'identity.whoami', args: null }],+ ['an id that is not a short token', { id: 'x'.repeat(40), op: 'identity.whoami', args: null }],+ ['whoami with arguments', { id: 's1', op: 'identity.whoami', args: { who: 1 } }],+ ['sign with an unknown purpose', { id: 's1', op: 'identity.sign', args: { purpose: 'anything', payload: 'x' } }],+ ['sign with an extra field', { id: 's1', op: 'identity.sign', args: { purpose: 'frame', payload: 'x', approved: true } }],+ ['sign with a non-string payload', { id: 's1', op: 'identity.sign', args: { purpose: 'frame', payload: { a: 1 } } }],+ ['sign with an oversized payload', { id: 's1', op: 'identity.sign', args: { purpose: 'frame', payload: 'x'.repeat(5000) } }],+ ['resolve with a missing field', { id: 's1', op: 'identity.resolve', args: { pub: null } }],+ ['save.write naming its own path', { id: 's1', op: 'save.write', args: { text: 'x', path: '/etc/passwd' } }],+ ['save.write with a non-string text', { id: 's1', op: 'save.write', args: { text: 42 } }],+ ]+ for (const [why, m] of bad) ok(parseRequest(m) === null, `refused: ${why}`)+ // a request's object never reaches answer() — only the parsed copy does+ const proto = Object.create({ inherited: 1 })+ ok(parseRequest(Object.assign(proto, { id: 's1', op: 'identity.whoami', args: null }))?.hasOwnProperty('inherited') === false, 'the parsed request is a fresh plain object')+ let wrote = ''+ const deps = { writeFile: async (t: string) => { wrote = t; return { ok: true } } }+ ok((await answer(parseRequest(good[0])!, deps)) === null, 'whoami answers null (no verified Bento ID yet)')+ ok(JSON.stringify(await answer(parseRequest(good[1])!, deps)) === '{"ok":false,"reason":"no-identity"}', 'sign answers no-identity')+ ok(JSON.stringify(await answer(parseRequest(good[3])!, deps)) === '{"ok":true}' && wrote === '<!doctype html>', 'save.write writes exactly the text, to the path the HOST opened (none is accepted from the frame)')+}++// --- "Open with Bento ID" exists only behind BOTH gates ------------------------+{+ const { servedOpenAllowed, SETTING_KEY } = await import('../home/webext/src/serve/gate.js')+ ok(servedOpenAllowed('development', true) === true, 'an unpacked install with the setting turned on: offered')+ ok(servedOpenAllowed('development', undefined) === false && servedOpenAllowed('development', null) === false, 'an unpacked install with the setting ABSENT (the default): not offered')+ ok(servedOpenAllowed('development', false) === false, 'an unpacked install with the setting off: not offered')+ for (const it of ['normal', 'sideload', 'admin', 'other', null, undefined])+ ok(servedOpenAllowed(it, true) === false, `a ${String(it)} install with the setting on: not offered`)+ for (const v of ['true', 1, {}, [true]]) ok(servedOpenAllowed('development', v) === false, `a setting of ${JSON.stringify(v)} is not true: not offered`)+ ok(SETTING_KEY === 'serveWithIdentity', 'the setting has one name')+ const serve = readFileSync(join(root, 'home/webext/src/serve/serve.js'), 'utf8')+ ok(/if \(!\(await servedOpenEnabled\(\)\)\) return asItself/.test(serve) && serve.indexOf('servedOpenEnabled()') < serve.indexOf('await fetch(fileUrl)'), 'the host page checks both gates itself, before it reads the file (it is reachable by URL)')+ const home = readFileSync(join(root, 'home/webext/src/home.js'), 'utf8')+ ok(!/function openDoc[^}]*serve\.html/.test(home), "the library's own Open is untouched: it never routes to the served path")+}++console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)