diff --git a/PRIVACY.md b/PRIVACY.md index 7fe32e2..a067b13 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -1,25 +1,34 @@ # SourceBraid Privacy -Last updated: October 12, 2026 +Last updated: November 26, 2026 SourceBraid is open-source software that stores captured sources in a GitHub -repository selected and controlled by the user. The Chrome/iOS capture clients, -local Codex plugin, and prepared hosted ChatGPT service have different data -flows, described below. The hosted service is not yet deployed; this notice +repository selected and controlled by the user. The browser and iOS capture +clients, local Codex plugin, and prepared hosted ChatGPT service have different +data flows, described below. The hosted service is not yet deployed; this notice describes the implementation prepared for its release. ## Data handled by SourceBraid -- The Chrome extension and iOS app process the page, document, selected text, - notes, tags, and images that the user chooses to save. -- The Chrome extension reads the active page only after the user starts a Save - or Download capture and accepts the first-use disclosure. A fallback download - remains on the user's device. +- The Chrome and Firefox extensions and iOS app process the page, document, + selected text, notes, tags, and images that the user chooses to save. +- The browser extension reads the active page content after the user starts a + Save or Download capture and accepts the first-use disclosure. A fallback + download stores the resulting Markdown on the user's device. Source requests + may still be needed to prepare it. - Captured Markdown, metadata, original PDFs, and related assets are sent directly to the GitHub repository configured by the user. -- Chrome/iOS credentials and configuration are stored by the relevant client - using browser storage or iOS Keychain. Users should restrict each fine-grained - GitHub token to the intended archive repository. +- The browser extensions store credentials and configuration in the local + browser profile. The iOS client uses Keychain for credentials. Users should + restrict each fine-grained GitHub token to the intended archive repository. +- Firefox shows its data permissions during installation. Authentication + information covers the configured account and credentials. Browsing activity + covers the URL of the page the user chooses to capture. Website content covers + the selected page or PDF and its assets. A GitHub save sends these captured + materials, source metadata, and user-entered tags or notes over HTTPS to the + configured repository through GitHub's API. Capture starts from a user action. + Firefox extension requests for source APIs, PDFs, and assets also use HTTPS. + SourceBraid servers receive no browser captures or telemetry. - The local Codex plugin reads the configured archive, stores cached Markdown and a disposable SQLite index locally, and can perform explicitly confirmed deletion or metadata migration through GitHub. Its credentials come from the @@ -111,8 +120,9 @@ OpenAI. These providers process connection or requested content data according to their respective service terms and privacy policies. The GitHub repository and Git history remain the authoritative archive. -If the user configures Ghost or Blogger source APIs, the Chrome extension sends -the necessary request and configured API credential directly to that service. +If the user configures Ghost or Blogger source APIs, the browser extension sends +the necessary request and configured API credential directly to that service over +HTTPS. Some protected sources use the browser's existing session with that site. SourceBraid does not include GitHub tokens or optional API credentials in its exported plugin configuration. @@ -134,10 +144,27 @@ public issue. ## Deutsch SourceBraid speichert Captures in einem vom Nutzer kontrollierten -GitHub-Repository. Chrome und iOS schreiben direkt dorthin; ihre Zugangsdaten -liegen im Browser-Speicher beziehungsweise iOS-Schlüsselbund. Das lokale -Codex-Plugin nutzt lokale Zugangsdaten, Markdown-Kopien und einen neu -aufbaubaren SQLite-Index. Es kann nach Vorschau und neuer ausdrücklicher +GitHub-Repository. Die Erweiterungen für Chrome und Firefox sowie die iOS-App +schreiben direkt dorthin. Die Zugangsdaten liegen lokal im Browserprofil +beziehungsweise im iOS-Schlüsselbund. + +Firefox zeigt bei der Installation die Datenberechtigungen an. Dazu gehören +Authentifizierungsdaten für Konto und Zugangsdaten, Browsing-Aktivität für die +URL der zur Erfassung ausgewählten Seite und Website-Inhalte für den gewählten +Seiteninhalt oder das PDF und zugehörige Dateien. Beim Speichern sendet die +Erweiterung die erfassten Inhalte, Quellmetadaten, Tags und Notizen über die +GitHub-API per HTTPS an das konfigurierte Repository. Die Erfassung beginnt +durch eine Nutzeraktion. Die Firefox-Erweiterung lädt auch PDFs und zugehörige +Dateien per HTTPS und nutzt HTTPS für Quell-APIs. SourceBraid-Server erhalten +keine Captures oder Telemetrie aus dem Browser. Der Fallback speichert die +Markdown-Datei lokal. +Zum Erstellen der Datei können Quellabfragen erforderlich sein. Wenn Ghost +oder Blogger konfiguriert ist, sendet SourceBraid die nötigen Anfragen und +API-Zugangsdaten direkt per HTTPS an den jeweiligen Dienst. Manche geschützte +Quellen nutzen die bestehende Browser-Sitzung mit der Website. + +Das lokale Codex-Plugin nutzt lokale Zugangsdaten, Markdown-Kopien und einen +neu aufbaubaren SQLite-Index. Es kann nach Vorschau und neuer ausdrücklicher Bestätigung Clips löschen oder Metadaten migrieren. Der noch unveröffentlichte iOS-Reader liest Markdown und Assets per diff --git a/README.de.md b/README.de.md index a5e6a50..54b8d7a 100644 --- a/README.de.md +++ b/README.de.md @@ -23,7 +23,7 @@ SourceBraid verbindet Capture-Clients, ein privates GitHub-Repository als dauerhaft maßgebliche Datenquelle und zwei Zugriffswege. Das lokale Codex-Plugin unterstützt Suche und Archivverwaltung. Die gehostete ChatGPT-Integration mit reinem Lesezugriff ist für Bereitstellung und Prüfung vorbereitet; sie ist noch -kein öffentlich verfügbarer Dienst. Chrome-Erweiterung und iOS-App schreiben +kein öffentlich verfügbarer Dienst. Die Erweiterungen für Chrome und Firefox sowie die iOS-App schreiben Captures direkt in das konfigurierte GitHub-Repository. Gehostete ChatGPT-Anfragen laufen künftig über den SourceBraid-Worker bei Cloudflare, ohne eine dauerhafte Inhaltsdatenbank anzulegen. @@ -34,7 +34,7 @@ Maßgeblich bleiben die Markdown-Dateien und die Git-Historie. ```mermaid flowchart TD A["Webseite, Wiki, Gist, arXiv-Paper oder PDF"] --> B{"Capture-Client"} - B -->|Chrome| C["Browser-Erweiterung"] + B -->|Chrome oder Firefox| C["Browser-Erweiterung"] B -->|iOS| D["App und Share Extension"] C --> E["Besten Extraktionsadapter wählen"] D --> E @@ -99,7 +99,7 @@ Rebuild oder eine Indexreparatur nötig. | Quelle oder Format | Bevorzugte Extraktion | Ergebnis in Markdown | Bilder und Anhänge | Fallback | | --- | --- | --- | --- | --- | | **arXiv-Paper** | Experimentelle arXiv-HTML-Version des vollständigen Papers | Gliederung, Fließtext, Tabellen, Zitate und LaTeX-Formeln; Autoren, arXiv-ID/-Version, DOI, Fachgebiete und Journalreferenz im Frontmatter | Abbildungen werden in den Asset-Ordner kopiert und relativ verlinkt | PDF herunterladen und mit Docling konvertieren | -| **PDF über HTTP(S) oder lokale Datei** | Original-PDF plus asynchroner Docling-Workflow in GitHub Actions | Lesereihenfolge, Tabellen, OCR-Text und referenzierte Abbildungen; zunächst Status `pending`, danach fertiges Markdown | Original bleibt als `source.pdf` erhalten; extrahierte Abbildungen liegen daneben | Lokale PDFs benötigen in Chrome **Zugriff auf Datei-URLs zulassen**; verschlüsselte oder sitzungsgebundene PDFs werden nicht unterstützt | +| **Web-PDF oder lokale PDF-Datei in Chrome** | Original-PDF plus asynchroner Docling-Workflow in GitHub Actions | Lesereihenfolge, Tabellen, OCR-Text und referenzierte Abbildungen; zunächst Status `pending`, danach fertiges Markdown | Original bleibt als `source.pdf` erhalten; extrahierte Abbildungen liegen daneben | Firefox benötigt eine HTTPS-PDF-URL. Lokale PDFs benötigen in Chrome **Zugriff auf Datei-URLs zulassen**. Verschlüsselte oder sitzungsgebundene PDFs werden nicht unterstützt. | | **Azure DevOps Wiki** | Authentifizierte Wiki-REST-API liefert das Quell-Markdown | Azure-Makros werden normalisiert, Mermaid bleibt als `mermaid`-Codeblock erhalten, interne Wiki-Links werden absolut | Geschützte Anhänge werden über den weiterhin authentifizierten Quell-Tab geladen und lokal abgelegt | Gerenderter `.markdown-content`-Bereich, falls die API nicht erreichbar ist | | **GitHub Gist** | GitHub Gist API, bei privaten Gists mit dem konfigurierten Token | Einzelne Markdown-Datei direkt; mehrere Dateien als Abschnitte; Quellcode in Codeblöcken mit Sprachkennung | Öffentliche Bilder direkt, geschützte GitHub-Bilder über den Gist-Tab mit aktiver GitHub-Sitzung | Die Revision einer revisionsspezifischen URL bleibt erhalten | | **Natives Markdown** | HTTP-Antwort auf `Accept: text/markdown`, z. B. bei Hashnode oder entsprechend konfigurierten Cloudflare-Seiten | Quell-Frontmatter und doppeltes H1 werden entfernt; relative Links werden absolut | Relevante Bilder werden lokal gespeichert und relativ verlinkt | Danach greifen die spezifischen APIs oder die DOM-Extraktion | @@ -183,9 +183,9 @@ Konvertierung. ### Allgemeine PDFs -SourceBraid unterstützt sowohl PDF-URLs über HTTP(S) als auch lokale, in Chrome -geöffnete `.pdf`-Dateien. Für lokale Dateien muss unter `chrome://extensions` in -den Details von SourceBraid einmalig **Zugriff auf Datei-URLs zulassen** +SourceBraid unterstützt in Firefox PDFs über HTTPS und in Chrome PDFs über +HTTP(S) oder lokale `.pdf`-Dateien. Für lokale Dateien muss unter +`chrome://extensions` in den Details von SourceBraid einmalig **Zugriff auf Datei-URLs zulassen** aktiviert sein. Ist die Berechtigung nicht gesetzt, zeigt die Erweiterung eine konkrete Anleitung an und legt keinen leeren HTML-Clip an. @@ -249,7 +249,34 @@ zusätzlich den konfigurierten GitHub-Token, sofern dieser Leserechte für Gists besitzt. Zugriffsgeschützte GitHub-Bilder können über den weiterhin geöffneten Gist-Tab mit aktiver GitHub-Sitzung geladen werden. -## Chrome-Installation aus dem Quellcode +## Browser-Erweiterung installieren + +### Firefox für Desktop + +SourceBraid läuft ab Version **140** in regulären Firefox-Desktopfenstern. Vor +der Veröffentlichung auf Mozilla Add-ons kannst du das ZIP aus diesem Checkout bauen. + +```bash +python3 scripts/build_firefox_package.py +``` + +1. `about:debugging#/runtime/this-firefox` in einem regulären Firefox-Fenster öffnen. +2. **Temporäres Add-on laden** wählen und `dist/sourcebraid-firefox-v1.1.1.zip` auswählen. +3. Eine Webseite öffnen und im Erweiterungsmenü **SourceBraid** wählen. Im + Popup das private GitHub-Repository und den Token eintragen, dann **Save to + GitHub** wählen. Auf HTML-Seiten lädt **Download Fallback** eine lokale + Markdown-Datei herunter. + +Firefox entfernt das temporäre Add-on beim Neustart. Sobald der Eintrag auf +Mozilla Add-ons verfügbar ist, installiere für die reguläre Nutzung die von +Mozilla signierte Version. Firefox zeigt bei dieser Installation die +erforderlichen Datenberechtigungen an. SourceBraid kann in Firefox Text aus +einer geöffneten HTTP-Seite erfassen. Anfragen für PDFs, Quell-APIs und +Dateien stellt die Firefox-Erweiterung per HTTPS. Die +[Release-Anleitung](RELEASING.md#firefox-package-and-mozilla-add-ons) beschreibt +die Einreichung. + +### Chrome-Installation aus dem Quellcode Bis der Eintrag im Chrome Web Store live ist, lässt sich die geprüfte Erweiterung aus diesem Checkout laden: @@ -312,7 +339,7 @@ Workflows: Read and write PDF-Upload installiert SourceBraid den mitgelieferten Docling-Workflow, das Konvertierungsskript und die Requirements-Datei, sofern diese Pfade noch nicht existieren. Bestehende Dateien werden nicht überschrieben. Der Token wird lokal -im Chrome-Erweiterungsspeicher abgelegt. +im Browserprofil für die Erweiterung abgelegt. Optionale API-Einstellungen: @@ -469,11 +496,10 @@ Plugin und gehostetem Dienst sowie die Lizenzgrenzen. ## Technische Hinweise -Der Quellcode der Chrome-Erweiterung liegt unter -[`chrome-extension/sourcebraid`](chrome-extension/sourcebraid). Die Erweiterung -benötigt keinen Build-Schritt und bindet keine Laufzeitkomponenten von -Drittanbietern ein. Docling läuft ausschließlich in der GitHub Action des -Ziel-Repositorys. Die -HTML-Konvertierung erfolgt lokal in der Erweiterung; API- und Bildzugriffe -nutzen je nach Quelle entweder normale HTTP-Anfragen oder die bestehende -authentifizierte Browser-Sitzung. +Chrome und Firefox verwenden den gemeinsamen Quellcode unter +[`chrome-extension/sourcebraid`](chrome-extension/sourcebraid). Das Firefox-Paket +verwendet eigene Manifest-Einstellungen. Beide Pakete enthalten lesbaren +Erweiterungscode und kommen ohne Laufzeitkomponenten von Drittanbietern aus. +Docling läuft ausschließlich in der GitHub Action des Ziel-Repositorys. +Die HTML-Konvertierung erfolgt lokal in der Erweiterung. Quellabfragen können +bei Bedarf die bestehende Browser-Sitzung nutzen. diff --git a/README.md b/README.md index c9ea136..b2141d9 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,9 @@ SourceBraid combines capture clients, a private GitHub repository as the durable source of truth, and two archive-access paths. The local Codex plugin supports search and archive management. The hosted, read-only ChatGPT integration is prepared for deployment and review; it is not yet a live public service. The -Chrome extension and iOS app write captures directly to the configured GitHub -repository. Hosted ChatGPT requests will pass through SourceBraid's Cloudflare -Worker without creating a permanent content database. +Chrome and Firefox extensions and the iOS app write captures directly to the +configured GitHub repository. Hosted ChatGPT requests will pass through +SourceBraid's Cloudflare Worker without creating a permanent content database. The local SQLite index is only a rebuildable search cache. Markdown files and Git history remain authoritative. @@ -31,7 +31,7 @@ Git history remain authoritative. ```mermaid flowchart TD A["Web page, wiki, Gist, arXiv paper, or PDF"] --> B{"Capture client"} - B -->|Chrome| C["Browser extension"] + B -->|Chrome or Firefox| C["Browser extension"] B -->|iOS| D["App and Share Extension"] C --> E["Select the best extraction adapter"] D --> E @@ -90,7 +90,7 @@ index repair. | Source or format | Preferred extraction | Markdown result | Images and attachments | Fallback | | --- | --- | --- | --- | --- | | **arXiv paper** | Experimental full-paper arXiv HTML | Sections, prose, tables, citations, and LaTeX formulas; authors, arXiv ID/version, DOI, categories, and journal reference in frontmatter | Figures are copied into the asset folder and linked relatively | Download the PDF and convert it with Docling | -| **Remote or local PDF** | Original PDF plus asynchronous Docling workflow in GitHub Actions | Reading order, tables, OCR text, and referenced figures; starts as `pending`, then becomes finished Markdown | The original remains as `source.pdf`; extracted figures sit beside it | Local PDFs require Chrome's **Allow access to file URLs** setting; encrypted or session-only PDFs are unsupported | +| **Web PDF or local PDF in Chrome** | Original PDF plus asynchronous Docling workflow in GitHub Actions | Reading order, tables, OCR text, and referenced figures; starts as `pending`, then becomes finished Markdown | The original remains as `source.pdf`; extracted figures sit beside it | Firefox requires an HTTPS PDF URL. Local PDFs require Chrome's **Allow access to file URLs** setting. Encrypted or session-only PDFs are unsupported. | | **Azure DevOps Wiki** | Authenticated Wiki REST API returns source Markdown | Azure macros are normalized, Mermaid remains a `mermaid` code block, internal wiki links become absolute | Protected attachments are loaded through the still-authenticated source tab | Rendered `.markdown-content` area | | **GitHub Gist** | GitHub Gist API, with the configured token for private Gists | A single Markdown file directly; multiple files as sections; source code in language-tagged fences | Public images directly, protected GitHub images through the signed-in Gist tab | Revision-specific URLs keep their revision | | **Native Markdown** | HTTP response to `Accept: text/markdown`, for example from Hashnode or appropriately configured Cloudflare sites | Source frontmatter and duplicate H1 removed; relative links made absolute | Relevant images are stored locally and linked relatively | Continue through dedicated APIs, then DOM extraction | @@ -170,7 +170,8 @@ the Docling workflow converts it automatically. ### General PDFs -SourceBraid accepts remote HTTP(S) PDFs and local `.pdf` files opened in Chrome. +SourceBraid accepts HTTPS PDFs in Firefox and HTTP(S) PDFs or local `.pdf` files +in Chrome. For local files, enable **Allow access to file URLs** in SourceBraid's extension details at `chrome://extensions`. Without that permission, the extension shows a concrete instruction instead of producing an empty HTML clip. @@ -228,7 +229,31 @@ Public Gists work anonymously. For private Gists, SourceBraid uses the configure GitHub token when it has Gist read permission. Signed-in GitHub image assets can be loaded through the still-open Gist tab. -## Chrome installation from source +## Install the browser extension + +### Firefox desktop + +SourceBraid runs in regular Firefox desktop windows from version **140**. Build +the ZIP from this checkout to try it before the Mozilla Add-ons listing is available. + +```bash +python3 scripts/build_firefox_package.py +``` + +1. Open `about:debugging#/runtime/this-firefox` in a regular Firefox window. +2. Choose **Load Temporary Add-on** and select `dist/sourcebraid-firefox-v1.1.1.zip`. +3. Open a web page and choose **SourceBraid** in the extensions menu. Configure + your private GitHub repository and token in the popup, then choose **Save to + GitHub**. Try **Download Fallback** on an HTML page for a local Markdown file. + +Firefox removes the temporary installation when it restarts. Once the add-on is +available on Mozilla Add-ons, install the Mozilla-signed version for regular +use. Firefox displays the required data permissions during that installation. +SourceBraid can capture text from an open HTTP page in Firefox. Requests made by +the Firefox extension for PDFs, source APIs, or assets use HTTPS. +See the [release guide](RELEASING.md#firefox-package-and-mozilla-add-ons) for submission. + +### Chrome installation from source Until the Chrome Web Store listing is live, load the reviewed extension from this checkout: @@ -287,7 +312,7 @@ Workflows: Read and write `Workflows` is needed only for PDF support. On the first PDF upload, SourceBraid installs the bundled Docling workflow, conversion script, and requirements file when those paths do not already exist. Existing files are never overwritten. -The token is stored locally in Chrome extension storage. +The token is stored locally in the browser profile for the extension. Optional API configuration: @@ -431,9 +456,9 @@ the capture, local-plugin, and hosted-service data flows and licensing boundarie ## Technical notes -The Chrome extension source lives under -[`chrome-extension/sourcebraid`](chrome-extension/sourcebraid). It has no build -step and bundles no third-party runtime. Docling runs only inside the target -repository's GitHub Action. HTML conversion happens locally in the extension; -API and image requests use either ordinary HTTP or the browser's existing -authenticated session, depending on the source. +Chrome and Firefox share the extension source under +[`chrome-extension/sourcebraid`](chrome-extension/sourcebraid). The Firefox +package uses its own Firefox manifest settings. Both bundles ship readable +extension code and have no third-party runtime. Docling runs only inside the +target repository's GitHub Action. HTML conversion happens locally in the +extension. Source requests can use the existing browser session where needed. diff --git a/RELEASING.md b/RELEASING.md index 1c58809..f4b9516 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -25,10 +25,11 @@ clients start from the same customer-facing version. ## Version alignment -Before creating the first release candidate, align these customer-facing -versions: +Before creating a coordinated release candidate, review these customer-facing +versions. Firefox uses its own version for Mozilla Add-ons. - Chrome: `version` in `chrome-extension/sourcebraid/manifest.json`. +- Firefox: `version` in `firefox-extension/manifest-overrides.json`. - Local Codex/optional skills package: `version` in `codex-plugin/sourcebraid/.codex-plugin/plugin.json`. - Hosted ChatGPT MCP: `version` in `chatgpt-mcp/package.json` and its server @@ -92,6 +93,43 @@ ZIP must contain `manifest.json` at its root and must not contain source archive the private website, plugin configuration, iOS sources, tests, Git metadata, or local settings. +## Firefox package and Mozilla Add-ons + +From the repository root, build the add-on and its matching reviewer source ZIP +with Python 3.10 or later. Use the clean public release commit for submission. + +```bash +python3 scripts/build_firefox_package.py --require-clean \ + --source-output dist/sourcebraid-firefox-source-v1.1.1.zip +unzip -t dist/sourcebraid-firefox-v1.1.1.zip +unzip -t dist/sourcebraid-firefox-source-v1.1.1.zip +``` + +Validate the add-on ZIP with Mozilla's `web-ext`. + +```bash +web-ext lint --source-dir dist/sourcebraid-firefox-v1.1.1.zip +``` + +The linter can report an [Android version warning](https://github.com/mozilla/web-ext/issues/3561) +for the data consent declaration in this desktop build. The two bundled Python +files are reviewable source copied to GitHub when installing the PDF workflow. + +Open `about:debugging#/runtime/this-firefox` in Firefox 140 or later and load the +add-on ZIP temporarily. Follow the test cases in the [Mozilla Add-ons listing +kit](firefox-extension/STORE_LISTING.md#reviewer-testing) and check that the +browser identifies SourceBraid as `@sourcebraid`. Preserve that ID for updates. + +Open [Submit a New Add-on](https://addons.mozilla.org/developers/addon/submit/) +in the Mozilla developer account. Choose **On this site**, upload the add-on +ZIP, select Firefox desktop, and complete the listing details. Use the +[listing kit](firefox-extension/STORE_LISTING.md) for the English and German +copy, privacy policy, and private reviewer instructions. Attach the matching +source ZIP in the source code step after the listing form. To attach it later, +open the version under **Manage Status & Versions** and use **Source code**. Verify the signed add-on from its public listing +before sharing the install link. See Mozilla's [submission guide](https://extensionworkshop.com/documentation/publish/submitting-an-add-on/) +and [source upload instructions](https://extensionworkshop.com/documentation/publish/source-code-submission/#upload-source-for-an-existing-version). + ## Optional local skills package Build the optional local-runtime archive: diff --git a/chrome-extension/sourcebraid/background.js b/chrome-extension/sourcebraid/background.js index f984788..0b7cd41 100644 --- a/chrome-extension/sourcebraid/background.js +++ b/chrome-extension/sourcebraid/background.js @@ -1,6 +1,10 @@ -importScripts("capture-utils.js"); +if (typeof importScripts === "function") { + importScripts("capture-utils.js"); +} const Core = globalThis.SourceBraidCore; +const WebExtension = globalThis.browser ?? globalThis.chrome; +const isFirefox = WebExtension.runtime?.getURL?.("").startsWith("moz-extension:"); const MAX_TEXT_RESPONSE_BYTES = 5 * 1024 * 1024; const MAX_PDF_BYTES = 25 * 1024 * 1024; const PDF_WORKFLOW_FILES = [ @@ -10,15 +14,15 @@ const PDF_WORKFLOW_FILES = [ ".github/workflows/convert-pdfs.yml" ]; -// Content scripts need the capture APIs, but never direct access to saved tokens. -chrome.storage?.local?.setAccessLevel?.({ accessLevel: "TRUSTED_CONTEXTS" }); +// Firefox stores credentials in extension-origin localStorage. Chrome can restrict storage.local. +WebExtension.storage?.local?.setAccessLevel?.({ accessLevel: "TRUSTED_CONTEXTS" }); -chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { - if (sender.id !== chrome.runtime.id) { +WebExtension.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (sender.id !== WebExtension.runtime.id) { return false; } if (["save-to-github", "save-pdf-to-github"].includes(message?.type) - && (sender.tab || sender.url !== chrome.runtime.getURL("popup.html"))) { + && (sender.tab || sender.url !== WebExtension.runtime.getURL("popup.html"))) { sendResponse({ ok: false, error: "GitHub saves must be started from the SourceBraid popup." }); return false; } @@ -69,11 +73,14 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { async function fetchResource(request) { const url = validateRemoteUrl(request?.url); + if (request?.authenticated && !url.startsWith("https:")) { + throw new Error("Source API credentials require HTTPS."); + } const headers = sanitizeFetchHeaders(request?.headers); const response = await fetch(url, { method: "GET", credentials: "omit", - redirect: "follow", + redirect: request?.authenticated ? "error" : "follow", cache: "no-store", headers }); @@ -170,7 +177,7 @@ async function fetchGist(value, revisionValue) { async function fetchGistRaw(value) { const url = new URL(validateRemoteUrl(value)); - if (url.hostname.toLowerCase() !== "gist.githubusercontent.com") { + if (url.origin !== "https://gist.githubusercontent.com") { throw new Error("Unsupported GitHub Gist raw-content host."); } @@ -193,11 +200,16 @@ async function fetchGistRaw(value) { } async function gistRequestHeaders(accept, includeToken = true) { - const stored = await chrome.storage.local.get({ githubToken: "" }); + let token; + if (includeToken) { + token = isFirefox + ? localStorage.getItem("githubToken") + : (await WebExtension.storage.local.get({ githubToken: "" })).githubToken; + } return { Accept: accept, "X-GitHub-Api-Version": "2022-11-28", - ...(includeToken && stored.githubToken ? { Authorization: `Bearer ${stored.githubToken}` } : {}) + ...(token ? { Authorization: `Bearer ${token}` } : {}) }; } @@ -218,6 +230,9 @@ function validateRemoteUrl(value) { if (!["http:", "https:"].includes(url.protocol)) { throw new Error(`Unsupported URL protocol: ${url.protocol}`); } + if (isFirefox && url.protocol !== "https:") { + throw new Error("Firefox capture requests require HTTPS."); + } return url.href; } @@ -273,16 +288,19 @@ async function saveToGitHub(settings, clip) { async function savePdfToGitHub(settings, pdf) { validatePdfSave(settings, pdf); - await ensureGitHubRepository(settings); - await ensurePdfWorkflow(settings); const source = Core.parsePdfSourceUrl(pdf.url); if (!source || (source.isLocal && !source.hasPdfExtension)) { throw new Error("Unsupported PDF URL. Use an HTTP(S) URL or a local file ending in .pdf."); } + if (isFirefox && !source.url.startsWith("https:")) { + throw new Error("Firefox captures PDFs from HTTPS addresses. Open the HTTPS URL of this PDF and try again."); + } if (source.isLocal) { await requireLocalFileAccess(); } + await ensureGitHubRepository(settings); + await ensurePdfWorkflow(settings); let response; try { @@ -442,7 +460,7 @@ async function ensurePdfWorkflow(settings) { continue; } - const packaged = await fetch(chrome.runtime.getURL(path)); + const packaged = await fetch(WebExtension.runtime.getURL(path)); if (!packaged.ok) { throw new Error(`Bundled PDF workflow file is unavailable: ${path}`); } @@ -471,8 +489,7 @@ function validatePdfSave(settings, pdf) { } async function requireLocalFileAccess() { - const checker = chrome.extension?.isAllowedFileSchemeAccess; - const allowed = typeof checker === "function" && await checker.call(chrome.extension); + const allowed = await WebExtension.extension?.isAllowedFileSchemeAccess?.(); if (!allowed) { throw new Error(`Local PDF access is disabled. ${localFileAccessHint()}`); } @@ -559,7 +576,7 @@ async function fetchImageAsset(image, clip) { if (!Number.isInteger(clip?.tabId)) { throw new Error("The source tab is unavailable for authenticated image capture."); } - const result = await chrome.tabs.sendMessage(clip.tabId, { + const result = await WebExtension.tabs.sendMessage(clip.tabId, { type: "fetch-authenticated-image", url }); @@ -806,6 +823,8 @@ async function ensureGitHubRepository(settings) { function githubFetch(settings, url, options = {}) { return fetch(url, { ...options, + credentials: "omit", + redirect: options.body === undefined ? "follow" : "error", headers: { Accept: "application/vnd.github+json", Authorization: `Bearer ${settings.token}`, diff --git a/chrome-extension/sourcebraid/content.js b/chrome-extension/sourcebraid/content.js index 1a2b96d..5b2d408 100644 --- a/chrome-extension/sourcebraid/content.js +++ b/chrome-extension/sourcebraid/content.js @@ -1,10 +1,11 @@ const Core = globalThis.SourceBraidCore; +const WebExtension = globalThis.browser ?? globalThis.chrome; if (!Core) { throw new Error("SourceBraidCore was not loaded before content.js."); } -chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { +WebExtension.runtime.onMessage.addListener((message, _sender, sendResponse) => { if (message?.type === "ping") { sendResponse({ ok: true }); return true; @@ -283,22 +284,24 @@ async function tryAzureDevOpsWiki(metadata) { let revision = ""; let captureMethod = "azure-devops-wiki-api"; const editor = document.querySelector("textarea[aria-label*='supports markdown']"); - try { - const response = await fetch(apiUrl.href, { - method: "GET", - credentials: "include", - cache: "no-store", - headers: { Accept: "application/json" } - }); - if (response.ok) { - const result = await response.json(); - if (typeof result?.content === "string" && result.content.trim()) { - markdown = result.content; - revision = (response.headers.get("etag") || "").replace(/^W\//, "").replace(/^"|"$/g, ""); + if (apiUrl.protocol === "https:") { + try { + const response = await fetch(apiUrl.href, { + method: "GET", + credentials: "include", + cache: "no-store", + headers: { Accept: "application/json" } + }); + if (response.ok) { + const result = await response.json(); + if (typeof result?.content === "string" && result.content.trim()) { + markdown = result.content; + revision = (response.headers.get("etag") || "").replace(/^W\//, "").replace(/^"|"$/g, ""); + } } + } catch (_error) { + // The editor or rendered wiki body below are fallbacks for restricted sessions. } - } catch (_error) { - // The editor or rendered wiki body below are fallbacks for restricted sessions. } if (!markdown && editor?.value?.trim()) { markdown = editor.value; @@ -366,7 +369,7 @@ async function tryGitHubGist(metadata) { } try { - const response = await chrome.runtime.sendMessage({ + const response = await WebExtension.runtime.sendMessage({ type: "fetch-gist", gistId: parsed.id, revision: parsed.revision @@ -380,7 +383,7 @@ async function tryGitHubGist(metadata) { for (const file of Object.values(gist.files)) { let content = typeof file.content === "string" ? file.content : ""; if (file.truncated && file.raw_url) { - const raw = await chrome.runtime.sendMessage({ type: "fetch-gist-raw", url: file.raw_url }); + const raw = await WebExtension.runtime.sendMessage({ type: "fetch-gist-raw", url: file.raw_url }); if (raw?.ok) { content = raw.text; } @@ -698,7 +701,7 @@ async function tryGhostApi(metadata, settings) { const response = await fetchResource(endpoint, { Accept: "application/json", "Accept-Version": "v5.0" - }); + }, { authenticated: true }); if (!response.ok) { return null; } @@ -743,7 +746,7 @@ async function tryBloggerApi(metadata, settings) { endpoint.searchParams.set("key", settings.bloggerApiKey); } - const response = await fetchResource(endpoint.href, { Accept: "application/json" }); + const response = await fetchResource(endpoint.href, { Accept: "application/json" }, { authenticated: true }); if (!response.ok) { return null; } @@ -1031,7 +1034,7 @@ async function fetchAuthenticatedImage(value) { "user-images.githubusercontent.com", "private-user-images.githubusercontent.com" ].includes(targetHost); - if (!isAzureWikiAsset && !isGitHubGistAsset) { + if (location.protocol !== "https:" || url.protocol !== "https:" || (!isAzureWikiAsset && !isGitHubGistAsset)) { throw new Error("Authenticated image host is not allowed for this source page."); } @@ -1074,10 +1077,10 @@ function bytesToBase64(bytes) { return btoa(binary); } -async function fetchResource(url, headers = {}) { - const response = await chrome.runtime.sendMessage({ +async function fetchResource(url, headers = {}, { authenticated = false } = {}) { + const response = await WebExtension.runtime.sendMessage({ type: "fetch-resource", - request: { url, headers } + request: { url, headers, authenticated } }); if (!response || response.error) { throw new Error(response?.error || "Resource fetch failed."); diff --git a/chrome-extension/sourcebraid/popup.html b/chrome-extension/sourcebraid/popup.html index 9dd5839..bf1b8a1 100644 --- a/chrome-extension/sourcebraid/popup.html +++ b/chrome-extension/sourcebraid/popup.html @@ -102,7 +102,7 @@

Optional source APIs

- Credentials are stored in Chrome local storage and sent only to GitHub or, + Credentials are stored locally by the extension and sent only to GitHub or, when configured, Ghost or Blogger endpoints. Exported plugin configs never contain tokens.

diff --git a/chrome-extension/sourcebraid/popup.js b/chrome-extension/sourcebraid/popup.js index 081fb47..f6706e5 100644 --- a/chrome-extension/sourcebraid/popup.js +++ b/chrome-extension/sourcebraid/popup.js @@ -1,4 +1,6 @@ const Core = globalThis.SourceBraidCore; +const WebExtension = globalThis.browser ?? globalThis.chrome; +const isFirefox = WebExtension?.runtime?.getURL?.("").startsWith("moz-extension:"); const saveButton = document.querySelector("#save"); const downloadButton = document.querySelector("#download"); const saveSettingsButton = document.querySelector("#save-settings"); @@ -75,7 +77,7 @@ async function saveCurrentTab() { pdfMode = await isPdfTab(tab); if (pdfMode) { setBusy(true, "Uploading PDF and queuing Docling conversion..."); - const result = await chrome.runtime.sendMessage({ + const result = await WebExtension.runtime.sendMessage({ type: "save-pdf-to-github", settings, pdf: { @@ -98,7 +100,7 @@ async function saveCurrentTab() { if (clip.pdfFallback) { pdfMode = true; setBusy(true, "arXiv HTML unavailable; uploading PDF for Docling conversion..."); - const result = await chrome.runtime.sendMessage({ + const result = await WebExtension.runtime.sendMessage({ type: "save-pdf-to-github", settings, pdf: clip.pdfFallback @@ -112,11 +114,11 @@ async function saveCurrentTab() { lastClip = clip; setBusy(true, `Uploading ${clip.path}...`); - if (!hasChromeApi("runtime", "sendMessage")) { - throw new Error("Chrome runtime API is unavailable. Reload the extension in chrome://extensions."); + if (!hasWebExtensionApi("runtime", "sendMessage")) { + throw new Error("Extension runtime API is unavailable. Reload SourceBraid from your browser's extension manager."); } - const result = await chrome.runtime.sendMessage({ + const result = await WebExtension.runtime.sendMessage({ type: "save-to-github", settings, clip @@ -215,14 +217,14 @@ function downloadBlobFile(filename, content, type) { } async function ensureContentScript(tabId) { - if (!hasChromeApi("scripting", "executeScript")) { - throw new Error("Chrome scripting API is unavailable. Reload the extension in chrome://extensions."); + if (!hasWebExtensionApi("scripting", "executeScript")) { + throw new Error("Extension scripting API is unavailable. Reload SourceBraid from your browser's extension manager."); } try { await sendTabMessage(tabId, { type: "ping" }); } catch (_error) { - await chrome.scripting.executeScript({ + await WebExtension.scripting.executeScript({ target: { tabId }, files: ["capture-utils.js", "content.js"] }); @@ -230,22 +232,22 @@ async function ensureContentScript(tabId) { } function sendTabMessage(tabId, message) { - if (!hasChromeApi("tabs", "sendMessage")) { - throw new Error("Chrome tabs API is unavailable. Open the clipper from the extension toolbar, not as a standalone HTML file."); + if (!hasWebExtensionApi("tabs", "sendMessage")) { + throw new Error("Extension tabs API is unavailable. Open SourceBraid from the browser toolbar."); } - return chrome.tabs.sendMessage(tabId, message); + return WebExtension.tabs.sendMessage(tabId, message); } async function getActiveTab(options = {}) { - if (!hasChromeApi("tabs", "query")) { + if (!hasWebExtensionApi("tabs", "query")) { if (options.optional) { return null; } - throw new Error("Chrome tabs API is unavailable. Open the clipper from the extension toolbar, not as a standalone HTML file."); + throw new Error("Extension tabs API is unavailable. Open SourceBraid from the browser toolbar."); } - const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + const [tab] = await WebExtension.tabs.query({ active: true, currentWindow: true }); return tab; } @@ -255,7 +257,7 @@ async function isPdfTab(tab) { return false; } - if (source.isLocal) { + if (source.isLocal || (isFirefox && !source.url.startsWith("https:"))) { return source.hasPdfExtension; } @@ -263,7 +265,7 @@ async function isPdfTab(tab) { if (source.hasPdfExtension) { return true; } - const result = await chrome.runtime.sendMessage({ type: "probe-resource", url: source.url }); + const result = await WebExtension.runtime.sendMessage({ type: "probe-resource", url: source.url }); return Boolean(result?.contentType?.toLowerCase().startsWith("application/pdf")); } catch (_error) { return false; @@ -283,7 +285,7 @@ async function loadSettings() { dataDisclosureAcceptedVersion: "" }; const settings = await storageGet(defaults); - if (settings.githubRepo === "codex-knowledge") { + if (!isFirefox && settings.githubRepo === "codex-knowledge") { settings.githubRepo = "sourcebraid-private"; await storageSet({ githubRepo: settings.githubRepo }); } @@ -393,8 +395,9 @@ function validateSettings(settings) { } async function storageGet(defaults) { - if (hasChromeApi("storage", "local") && typeof chrome.storage.local.get === "function") { - return chrome.storage.local.get(defaults); + // Firefox storage.local is also exposed to content scripts. Use the extension origin instead. + if (!isFirefox && typeof WebExtension?.storage?.local?.get === "function") { + return WebExtension.storage.local.get(defaults); } return { @@ -411,8 +414,8 @@ async function storageGet(defaults) { } async function storageSet(values) { - if (hasChromeApi("storage", "local") && typeof chrome.storage.local.set === "function") { - await chrome.storage.local.set(values); + if (!isFirefox && typeof WebExtension?.storage?.local?.set === "function") { + await WebExtension.storage.local.set(values); return; } @@ -421,17 +424,8 @@ async function storageSet(values) { } } -function hasChromeApi(namespace, member) { - const root = globalThis.chrome?.[namespace]; - if (!root) { - return false; - } - - if (member === "local") { - return Boolean(root.local); - } - - return member ? Boolean(root[member]) : true; +function hasWebExtensionApi(namespace, member) { + return typeof WebExtension?.[namespace]?.[member] === "function"; } function normalizeRootFolder(value) { diff --git a/firefox-extension/BUILD.md b/firefox-extension/BUILD.md new file mode 100644 index 0000000..4de5033 --- /dev/null +++ b/firefox-extension/BUILD.md @@ -0,0 +1,20 @@ +# Build SourceBraid for Firefox + +This source archive contains the original JavaScript, HTML, CSS, localization +files, icons, and the original and bundled PDF workflow resources. It also includes the Python scripts +used to package the extension and its Firefox manifest settings. + +Extract the source ZIP and run this command from its root with Python 3.10 or +later. + +```bash +python3 scripts/build_firefox_package.py --output dist/sourcebraid-firefox.zip +``` + +The builder copies the allowlisted files from `chrome-extension/sourcebraid` +and applies `firefox-extension/manifest-overrides.json` to the shared manifest. +The override sets the version of the Firefox add-on independently of Chrome. +The build requires only the Python standard library and runs offline. It does +not transpile, bundle, or minify JavaScript. The bundled Python and YAML files +are resources the extension can copy to the user's GitHub archive for PDF +conversion in GitHub Actions. diff --git a/firefox-extension/STORE_LISTING.md b/firefox-extension/STORE_LISTING.md new file mode 100644 index 0000000..679c5aa --- /dev/null +++ b/firefox-extension/STORE_LISTING.md @@ -0,0 +1,138 @@ +# SourceBraid on Mozilla Add-ons + +| Field | Value | +| --- | --- | +| Name | SourceBraid | +| Category | Bookmarks | +| Compatibility | Firefox desktop 140 and later | +| License | MIT | +| Homepage | https://sourcebraid.com | +| Support | https://github.com/patrickschiller/sourcebraid/issues | +| Privacy policy | https://github.com/patrickschiller/sourcebraid/blob/main/PRIVACY.md | + +## English listing + +**Summary** + +Save web pages and PDFs as Markdown in your private GitHub repository. + +**Description** + +Use SourceBraid to save an article, research paper, wiki page, GitHub Gist, or +HTTPS PDF from the active Firefox tab. Add tags and notes, then save the capture +to a private GitHub repository you control. SourceBraid preserves the source URL +and available metadata in the Markdown file and saves relevant images alongside +it. A GitHub Actions workflow can convert web PDFs to Markdown and retain the +original PDFs. You can also download Markdown from an HTML page to your device. + +SourceBraid reads page content when you choose to capture the page. Saving sends +the selected URL, content and assets, tags, and notes directly to GitHub over +HTTPS. The add-on may make HTTPS requests to prepare the capture. It stores +your credentials in your local Firefox profile and sends them to the services +they authorize. SourceBraid servers receive no captures or telemetry. + +GitHub saving requires a GitHub account, a private repository, and a fine-grained +token with **Contents: Read and write** for that repository. The first PDF +workflow installation also requires **Workflows: Read and write**. SourceBraid +runs in regular Firefox desktop windows. The extension interface is in English. + +## Deutsche Store-Beschreibung + +**Kurzbeschreibung** + +Speichere Webseiten und PDFs als Markdown in deinem privaten GitHub-Repository. + +**Beschreibung** + +Erfasse Artikel, wissenschaftliche Papers, Wiki-Seiten, GitHub Gists oder +PDFs über HTTPS aus dem aktiven Firefox-Tab. Ergänze Tags und Notizen und speichere das +Ergebnis in einem privaten GitHub-Repository, das du kontrollierst. SourceBraid +bewahrt die Quell-URL und verfügbare Metadaten in der Markdown-Datei und legt +relevante Bilder daneben ab. Ein GitHub-Actions-Workflow kann Web-PDFs in +Markdown umwandeln und die Originale erhalten. Markdown aus HTML-Seiten kannst +du auch direkt auf dein Gerät herunterladen. + +SourceBraid liest Seiteninhalte, wenn du eine Erfassung startest. Beim Speichern +sendet die Erweiterung die gewählte URL, Inhalte und Dateien, Tags und Notizen +direkt per HTTPS an GitHub. Für die Erfassung können HTTPS-Anfragen an die +Quelle erforderlich sein. Das Add-on speichert Zugangsdaten lokal im Firefox-Profil und sendet sie +an die Dienste, für die sie bestimmt sind. SourceBraid-Server erhalten keine +Captures oder Telemetrie. + +Zum Speichern in GitHub brauchst du ein GitHub-Konto, ein privates Repository +und einen Fine-grained Token mit **Contents: Read and write** für genau dieses +Repository. Die erste Installation des PDF-Workflows benötigt zusätzlich +**Workflows: Read and write**. SourceBraid läuft in regulären +Firefox-Desktopfenstern. Die Oberfläche der Erweiterung ist auf Englisch. + +## Permissions and privacy + +| Firefox permission | Purpose | +| --- | --- | +| `activeTab` | Read the active capture target and show its title in the popup. | +| `scripting` | Inject bundled capture code into the active tab on Save or Download. | +| `https://*/*` | Fetch source APIs, related assets and HTTPS PDFs during capture, and write to the selected repository through GitHub's API. | +| `authenticationInfo` | Authenticate requests using the configured GitHub token and any configured Ghost or Blogger API credentials. Protected source requests can use the source site's existing browser session. | +| `browsingActivity` | Include the URL of the page chosen for capture in its archived metadata. | +| `websiteContent` | Save captured HTML-derived content, PDFs, images, source metadata, and accompanying tags or notes. | + +Enable the privacy policy field in the Developer Hub and supply the browser +and external-services disclosures from [PRIVACY.md](../PRIVACY.md). Firefox +asks the user to accept the required data permissions during installation. +Capture code runs locally. Packaged Python and YAML resources are copied to +the user's GitHub repository for the optional PDF conversion workflow. + +## Reviewer testing + +### Prepare private review access + +Set up a dedicated private GitHub repository with an initial commit and only +synthetic test content. The [GitHub setup script](https://github.com/patrickschiller/sourcebraid/blob/main/scripts/setup_github.py) +initializes it and installs the optional PDF support files. Use the review +account's GitHub username for `OWNER`. + +```bash +python3 scripts/setup_github.py --repo OWNER/sourcebraid-firefox-review --no-config +``` + +Create a fine-grained PAT for that repository alone with **Contents: Read and +write** and an expiry that covers the review window. The setup script installs +the PDF workflow so the browser's review token only needs repository contents +access. Give reviewers the owner, repository, branch, and PAT through the +private **Notes for Reviewers** field. Revoke the token when review is complete +and provision fresh access for later reviews. See Mozilla's [review policy](https://extensionworkshop.com/documentation/publish/add-on-policies/#3-submission-guidelines). + +### Steps for reviewers + +1. On Firefox desktop, open `https://example.com/` in a regular window and + choose SourceBraid from the extensions menu. Tick the first-capture consent + checkbox and choose **Download Fallback**. This produces a local `.md` file + containing the example page and source URL, without GitHub setup. +2. Open the settings gear and enter the supplied owner, repository, branch, + root folder `web-clips`, and fine-grained token. Leave the optional Ghost + and Blogger inputs empty and click **Save Settings**. +3. Add the tag `amo-review` and the note `Synthetic Firefox review`. Choose + **Save to GitHub**. The popup shows the saved path. Check the Markdown under + `web-clips/YYYY/MM/` and its corresponding entry in `web-clips/index/` + using the supplied repository access. +4. Choose **Export Plugin Config**. The downloaded JSON contains the repository + settings and omits credentials. +5. Open the [W3C dummy PDF](https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf) + and choose **Save to GitHub**. The popup reports the queued file. Check for + `source.pdf` and pending Markdown in the review repository, then confirm + that **Convert PDFs to Markdown** completes and updates the Markdown. + +## Submission + +In [Submit a New Add-on](https://addons.mozilla.org/developers/addon/submit/), +choose **On this site**, upload `sourcebraid-firefox-v1.1.1.zip`, select +Firefox desktop, and complete the listing details. Attach the matching +`sourcebraid-firefox-source-v1.1.1.zip` in the source code step. To attach +it later, open the version under **Manage Status & Versions** and use **Source +code**. Rebuild instructions are in +`firefox-extension/BUILD.md` inside the archive. See Mozilla's [source upload +instructions](https://extensionworkshop.com/documentation/publish/source-code-submission/#upload-source-for-an-existing-version). + +For listing screenshots, use the actual Firefox popup with synthetic data. +The packaged SourceBraid icon is at `icons/icon-128.png`. See Mozilla's +[listing guidance](https://extensionworkshop.com/documentation/develop/create-an-appealing-listing/). diff --git a/firefox-extension/manifest-overrides.json b/firefox-extension/manifest-overrides.json new file mode 100644 index 0000000..2728a8b --- /dev/null +++ b/firefox-extension/manifest-overrides.json @@ -0,0 +1,21 @@ +{ + "version": "1.1.1", + "background": { + "scripts": ["capture-utils.js", "background.js"] + }, + "permissions": ["activeTab", "scripting"], + "host_permissions": ["https://*/*"], + "content_security_policy": { + "extension_pages": "script-src 'self'; object-src 'self'; connect-src 'self' https:" + }, + "incognito": "not_allowed", + "browser_specific_settings": { + "gecko": { + "id": "@sourcebraid", + "strict_min_version": "140.0", + "data_collection_permissions": { + "required": ["authenticationInfo", "browsingActivity", "websiteContent"] + } + } + } +} diff --git a/scripts/build_chrome_package.py b/scripts/build_chrome_package.py index 57b6808..486ab2d 100644 --- a/scripts/build_chrome_package.py +++ b/scripts/build_chrome_package.py @@ -41,10 +41,26 @@ VERSION_PATTERN = re.compile(r"^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){0,3}$") +SECRET_PATTERNS = ( + ("GitHub credential", re.compile(rb"(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})")), + ("private key", re.compile(rb"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----")), + ("personal absolute path", re.compile(rb"/(?:Users|home)/[A-Za-z0-9_.-]+/")), +) + + class PackageError(RuntimeError): """Raised when a safe release archive cannot be created.""" + +def private_content_reason(content: bytes) -> str | None: + for label, pattern in SECRET_PATTERNS: + if pattern.search(content): + # Never include the matching secret in diagnostics. + return label + return None + + def package_source(root: Path, relative: PurePosixPath) -> Path: if relative.is_absolute() or ".." in relative.parts: raise PackageError(f"unsafe package path: {relative}") @@ -85,9 +101,7 @@ def validated_package_files(repository_root: Path) -> list[tuple[Path, str]]: return files -def build_package(repository_root: Path, output_path: Path) -> tuple[str, str]: - manifest = validated_manifest(repository_root) - files = validated_package_files(repository_root) +def write_package(output_path: Path, files: dict[str, bytes]) -> str: output_path.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile( @@ -96,21 +110,26 @@ def build_package(repository_root: Path, output_path: Path) -> tuple[str, str]: compression=zipfile.ZIP_DEFLATED, compresslevel=9, ) as archive: - for source, archive_name in files: + for archive_name, content in files.items(): info = zipfile.ZipInfo(archive_name, date_time=(1980, 1, 1, 0, 0, 0)) info.compress_type = zipfile.ZIP_DEFLATED info.external_attr = 0o100644 << 16 - archive.writestr(info, source.read_bytes()) + archive.writestr(info, content) with zipfile.ZipFile(output_path) as archive: packaged_names = tuple(sorted(archive.namelist())) - expected_names = tuple(sorted(PACKAGE_FILES)) + expected_names = tuple(sorted(files)) if packaged_names != expected_names: output_path.unlink(missing_ok=True) raise PackageError("release archive does not match the explicit allowlist") - digest = hashlib.sha256(output_path.read_bytes()).hexdigest() - return str(manifest["version"]), digest + return hashlib.sha256(output_path.read_bytes()).hexdigest() + + +def build_package(repository_root: Path, output_path: Path) -> tuple[str, str]: + manifest = validated_manifest(repository_root) + files = {name: path.read_bytes() for path, name in validated_package_files(repository_root)} + return str(manifest["version"]), write_package(output_path, files) def parser() -> argparse.ArgumentParser: diff --git a/scripts/build_firefox_package.py b/scripts/build_firefox_package.py new file mode 100644 index 0000000..1f9b511 --- /dev/null +++ b/scripts/build_firefox_package.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Build a Mozilla Add-ons ZIP and optional reviewer source ZIP from allowlists.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from pathlib import Path, PurePosixPath + +import build_chrome_package as shared + + +MANIFEST_OVERRIDES = "firefox-extension/manifest-overrides.json" +LICENSE_FILES = ("LICENSE", "NOTICE") +EXTENSION_FILES = {name: str(shared.EXTENSION_DIRECTORY / name) for name in shared.PACKAGE_FILES} +PACKAGE_FILES = (*EXTENSION_FILES, *LICENSE_FILES) +SOURCE_FILES = ( + *LICENSE_FILES, + *shared.PDF_SUPPORT_FILES, + *EXTENSION_FILES.values(), + MANIFEST_OVERRIDES, + "firefox-extension/BUILD.md", + "scripts/build_chrome_package.py", + "scripts/build_firefox_package.py", +) + + +def read_sources(root: Path) -> dict[str, bytes]: + sources = {} + for name in SOURCE_FILES: + content = shared.package_source(root, PurePosixPath(name)).read_bytes() + reason = shared.private_content_reason(content) + if reason: + raise shared.PackageError(f"potential {reason} in {name}") + sources[name] = content + for name in shared.PDF_SUPPORT_FILES: + if sources[name] != sources[EXTENSION_FILES[name]]: + raise shared.PackageError(f"bundled PDF support differs from the canonical source: {name}") + return sources + + +def package_files(sources: dict[str, bytes]) -> tuple[str, dict[str, bytes]]: + manifest = json.loads(sources[EXTENSION_FILES["manifest.json"]]) + overrides = json.loads(sources[MANIFEST_OVERRIDES]) + if not isinstance(manifest, dict) or not isinstance(overrides, dict): + raise shared.PackageError("Firefox manifest inputs must be JSON objects") + version = overrides.get("version") + if not isinstance(version, str) or not shared.VERSION_PATTERN.fullmatch(version): + raise shared.PackageError("Firefox manifest overrides must specify a valid extension version") + manifest.update(overrides) + if manifest.get("manifest_version") != 3 or manifest.get("name") != "SourceBraid": + raise shared.PackageError("Firefox package must identify SourceBraid and use Manifest V3") + files = {name: sources[path] for name, path in EXTENSION_FILES.items()} + files["manifest.json"] = (json.dumps(manifest, indent=2, ensure_ascii=False) + "\n").encode("utf-8") + files.update({name: sources[name] for name in LICENSE_FILES}) + return version, files + + +def require_clean_inputs(root: Path) -> str: + def git(*args: str) -> str: + return subprocess.run( + ["git", "-C", str(root), *args], check=True, capture_output=True, text=True, + ).stdout.strip() + + try: + commit = git("rev-parse", "HEAD") + changes = git("status", "--porcelain", "--untracked-files=all", "--", *SOURCE_FILES) + except (OSError, subprocess.CalledProcessError) as error: + raise shared.PackageError("could not verify Firefox release inputs against a Git commit") from error + if changes: + raise shared.PackageError("Firefox release inputs must be committed and clean before building") + return commit + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repository-root", type=Path, default=Path(__file__).resolve().parents[1]) + parser.add_argument("--output", type=Path, help="Defaults to dist/sourcebraid-firefox-vVERSION.zip.") + parser.add_argument("--source-output", type=Path, help="Also write a source ZIP for Mozilla review.") + parser.add_argument("--require-clean", action="store_true", help="Require committed, unchanged Firefox inputs.") + args = parser.parse_args(argv) + root = args.repository_root.resolve() + try: + commit = require_clean_inputs(root) if args.require_clean else None + sources = read_sources(root) + version, files = package_files(sources) + output = (args.output or root / "dist" / f"sourcebraid-firefox-v{version}.zip").resolve() + source_output = args.source_output.resolve() if args.source_output else None + if source_output == output: + raise shared.PackageError("choose different paths for the add-on ZIP and source ZIP") + if commit and (require_clean_inputs(root) != commit or read_sources(root) != sources): + raise shared.PackageError("Firefox release inputs changed during the build") + digest = shared.write_package(output, files) + print(f"package: {output}\nversion: {version}\nsha256: {digest}") + if source_output: + source_digest = shared.write_package(source_output, sources) + print(f"source package: {source_output}\nsha256: {source_digest}") + if commit: + print(f"source commit: {commit}") + except (shared.PackageError, OSError, ValueError) as error: + print(f"error: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/build_release.py b/scripts/build_release.py index df8f94b..ed91e69 100644 --- a/scripts/build_release.py +++ b/scripts/build_release.py @@ -6,7 +6,6 @@ import argparse import hashlib import json -import re import subprocess import sys import tempfile @@ -38,11 +37,6 @@ ) MANIFEST_NAME = "RELEASE_MANIFEST.json" CHECKSUMS_NAME = "SHA256SUMS" -SECRET_PATTERNS = ( - ("GitHub credential", re.compile(rb"(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,})")), - ("private key", re.compile(rb"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----")), - ("personal absolute path", re.compile(rb"/(?:Users|home)/[A-Za-z0-9_.-]+/")), -) class ReleaseError(RuntimeError): @@ -68,10 +62,9 @@ def safe_source(root: Path, relative: str) -> Path: def scan_content(name: str, content: bytes) -> None: - for label, pattern in SECRET_PATTERNS: - if pattern.search(content): - # Never include the matching secret itself in diagnostics. - raise ReleaseError(f"potential {label} in {name}") + reason = chrome.private_content_reason(content) + if reason: + raise ReleaseError(f"potential {reason} in {name}") def artifact_names(version: str) -> dict[str, str]: diff --git a/tests/capture-utils.test.js b/tests/capture-utils.test.js index d334468..0572916 100644 --- a/tests/capture-utils.test.js +++ b/tests/capture-utils.test.js @@ -392,6 +392,56 @@ test("a login page returned from a PDF URL is rejected before archive writes", a }), /not a PDF document/); }); +test("Firefox background starts without a worker and reads Gist credentials from its extension origin", async () => { + const context = backgroundContext({ + importScripts: undefined, + browser: { + runtime: { + getURL: (file) => `moz-extension://sourcebraid-test/${file}`, + onMessage: { addListener() {} } + } + }, + localStorage: { getItem: (key) => key === "githubToken" ? "test-token" : null } + }); + + const headers = await context.gistRequestHeaders("application/vnd.github+json"); + assert.equal(headers.Authorization, "Bearer test-token"); + const anonymousHeaders = await context.gistRequestHeaders("application/vnd.github+json", false); + assert.equal(anonymousHeaders.Authorization, undefined); + + await assert.rejects(context.fetchResource({ url: "http://example.com/" }), /Firefox capture requests require HTTPS/); + const settings = { owner: "example", repo: "archive", branch: "main", rootFolder: "web-clips", token: "test-token" }; + for (const url of ["file:///synthetic-paper.pdf", "http://example.com/synthetic-paper.pdf"]) { + await assert.rejects(context.savePdfToGitHub(settings, { url, title: "Paper" }), /Firefox captures PDFs from HTTPS addresses/); + } +}); + +test("source API keys require HTTPS and GitHub uploads reject redirects", async () => { + const requests = []; + const context = backgroundContext({ + fetch: async (url, options) => { + requests.push({ url, options }); + return { + url, + headers: { get() { return null; } }, + async text() { return "{}"; } + }; + } + }); + + await assert.rejects(context.fetchResource({ url: "http://example.com/api", authenticated: true }), /require HTTPS/); + await assert.rejects(context.fetchGistRaw("http://gist.githubusercontent.com/example/test/raw/file.txt"), /Unsupported GitHub Gist/); + assert.equal(requests.length, 0); + await context.fetchResource({ url: "https://example.com/api", authenticated: true }); + await context.fetchResource({ url: "http://example.com/" }); + await context.githubFetch({ token: "test-token" }, "https://api.github.com/repos/example/archive", { + method: "PUT", body: '{"content":"synthetic"}' + }); + + assert.deepEqual(requests.map(({ options }) => options.redirect), ["error", "follow", "error"]); + assert.equal(requests[1].options.credentials, "omit"); +}); + test("first capture requires consent before tab access or capture requests", async () => { const elements = new Map(); const requests = []; diff --git a/tests/test_release_bundle.py b/tests/test_release_bundle.py index 121a8f4..658b797 100644 --- a/tests/test_release_bundle.py +++ b/tests/test_release_bundle.py @@ -1,5 +1,6 @@ import importlib.util import json +import subprocess import sys import tempfile import unittest @@ -9,6 +10,8 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) +import build_chrome_package as chrome +import build_firefox_package as firefox import build_release as release import build_review_fixture as review sys.path.pop(0) @@ -135,5 +138,58 @@ def test_mcp_package_is_deterministic_and_excludes_runtime_secrets(self): self.assertFalse((root / "mismatched.zip").exists()) +class FirefoxPackageTests(unittest.TestCase): + def test_reviewer_source_reproduces_the_allowlisted_firefox_package(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + addon = root / "firefox.zip" + source = root / "source.zip" + subprocess.run( + [ + sys.executable, str(ROOT / "scripts/build_firefox_package.py"), + "--output", str(addon), "--source-output", str(source), + ], + check=True, capture_output=True, + ) + with zipfile.ZipFile(addon) as archive: + self.assertEqual(set(archive.namelist()), set(firefox.PACKAGE_FILES)) + manifest = json.loads(archive.read("manifest.json")) + version = json.loads((ROOT / firefox.MANIFEST_OVERRIDES).read_bytes())["version"] + self.assertEqual(manifest["version"], version) + self.assertEqual(manifest["background"], {"scripts": ["capture-utils.js", "background.js"]}) + self.assertEqual(manifest["incognito"], "not_allowed") + self.assertEqual(manifest["host_permissions"], ["https://*/*"]) + self.assertIn("connect-src 'self' https:", manifest["content_security_policy"]["extension_pages"]) + self.assertNotIn("gecko_android", manifest["browser_specific_settings"]) + self.assertEqual(manifest["browser_specific_settings"]["gecko"], { + "id": "@sourcebraid", + "strict_min_version": "140.0", + "data_collection_permissions": { + "required": ["authenticationInfo", "browsingActivity", "websiteContent"], + }, + }) + + reviewer = root / "reviewer-source" + with zipfile.ZipFile(source) as archive: + self.assertEqual(set(archive.namelist()), set(firefox.SOURCE_FILES)) + archive.extractall(reviewer) + chrome_manifest = reviewer / firefox.EXTENSION_FILES["manifest.json"] + original_chrome = json.loads(chrome_manifest.read_bytes()) + original_chrome["version"] = "0.0.0" + chrome_manifest.write_text(json.dumps(original_chrome), encoding="utf-8") + rebuilt = reviewer / "dist" / "sourcebraid-firefox.zip" + subprocess.run( + [sys.executable, "scripts/build_firefox_package.py", "--output", str(rebuilt)], + cwd=reviewer, check=True, capture_output=True, + ) + self.assertEqual(rebuilt.read_bytes(), addon.read_bytes()) + + synthetic_secret = b"github_pat_" + b"x" * 50 + (reviewer / firefox.EXTENSION_FILES["background.js"]).write_bytes(synthetic_secret) + with self.assertRaisesRegex(chrome.PackageError, "potential GitHub credential") as raised: + firefox.read_sources(reviewer) + self.assertNotIn(synthetic_secret.decode(), str(raised.exception)) + + if __name__ == "__main__": unittest.main()