diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 007cff8..9d56606 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -6,5 +6,6 @@ Closes # - [ ] Each new or changed entry's package was reviewed, mirrored as a release asset of this repository, and its `sha256` and `size` match - [ ] `permissions` and `hosts` match the package's manifest +- [ ] `author`, `homepage`, `category`, icon and screenshots describe the extension accurately - [ ] A removed package is listed in `revoked` - [ ] No secrets, credentials or personal data in the diff diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 0398320..65b6fb3 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -18,7 +18,8 @@ env: jobs: # Signs the catalog with a throwaway key, which runs the same checks Tarn applies to the index, - # and checks every package against its entry. No secret is used. + # checks every package and the store fields against its entry, and builds the store website from + # the fixtures. No secret is used. check: runs-on: ubuntu-24.04 permissions: @@ -45,6 +46,23 @@ jobs: umask 077 tarn/target/release/filter-bundle keygen | sed -n 's/^FILTER_SIGNING_KEY=//p' > "$RUNNER_TEMP/throwaway.key" tarn/target/release/filter-bundle catalog --kind extension --in index.json --key "$RUNNER_TEMP/throwaway.key" --out out + - name: The store checks refuse bad entries + run: python3 -I -m unittest discover -s catalog/site + - name: Every entry's store fields are valid + run: python3 -I catalog/site/store.py check catalog/catalog.json --root catalog + - name: The store website builds from the fixtures + run: | + python3 -I catalog/site/store.py check catalog/site/fixtures/catalog.json --root catalog/site/fixtures + now="$(date -u +%s)" + jq --argjson now "$now" '{kind, version: $now, created: $now, extensions, revoked}' catalog/site/fixtures/catalog.json > fixture-index.json + tarn/target/release/filter-bundle catalog --kind extension --in fixture-index.json --key "$RUNNER_TEMP/throwaway.key" --out fixture-signed + python3 -I catalog/site/store.py build --index fixture-signed/index.json --sig fixture-signed/index.sig --root catalog/site/fixtures --out fixture-site + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fixture-site + path: fixture-site/ + if-no-files-found: error + retention-days: 7 - name: Every package matches its entry run: | jq -r '.extensions[] | [.id, .url, .sha256, (.size | tostring)] | @tsv' catalog/catalog.json | diff --git a/.github/workflows/sign.yml b/.github/workflows/sign.yml index d503523..31e579a 100644 --- a/.github/workflows/sign.yml +++ b/.github/workflows/sign.yml @@ -3,7 +3,7 @@ name: Sign catalog on: push: branches: [main] - paths: [catalog.json] + paths: [catalog.json, "assets/**", "site/**"] schedule: - cron: "23 5 * * 1" workflow_dispatch: @@ -119,6 +119,39 @@ jobs: fi gh release upload catalog --repo "$REPO" --clobber signed/index.json signed/index.sig + # The store website is built from the files the sign job produced; only deploy can write to Pages. + site: + needs: publish + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: signed + path: signed + - name: Build the store website + run: python3 -I site/store.py build --index signed/index.json --sig signed/index.sig --root . --out _site + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 + with: + path: _site/ + + deploy: + needs: site + runs-on: ubuntu-24.04 + environment: + name: github-pages + url: ${{ steps.deploy.outputs.page_url }} + permissions: + pages: write + id-token: write + steps: + - id: deploy + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 + # GitHub turns off scheduled workflows after 60 days without a commit; Tarn refuses an index older # than 30 days. Enabling the workflow again through the API keeps the weekly signing on. keepalive: diff --git a/README.md b/README.md index 1007cc3..6974c9f 100644 --- a/README.md +++ b/README.md @@ -43,10 +43,88 @@ only `main` may use; the maintainer keeps an offline copy. "size": 12345, "permissions": ["storage"], "optional_permissions": [], - "hosts": ["*://*.example.com/*"] + "hosts": ["*://*.example.com/*"], + "author": "Example Author", + "homepage": "https://example.com/", + "category": "productivity", + "icon": "assets/example/icon.png", + "screenshots": ["assets/example/main.png"] } ``` `id` uses lowercase letters, digits and `-` (at most 64). `permissions` and `hosts` must match the manifest; Tarn shows them in its consent sheet. -4. Open a pull request. Once it is merged into `main`, the workflow signs and publishes the new index. + + The last five fields are for the store website only; Tarn ignores them. + + | Field | Rule | + |---|---| + | `author` | Who publishes the extension | + | `homepage` | An `https` URL with a lowercase ASCII host (punycode for other scripts) and no user, password or port | + | `category` | One of the categories below | + | `icon` | Exactly `assets//icon.png`: a square PNG, 128 to 512 px, at most 256 KiB | + | `screenshots` | 0 to 5 paths `assets//.png` or `.jpg` (`` in lowercase letters, digits, `-` and `_`), each a complete file of at most 1 MiB and 2560 × 2560 px | + + Images must be complete PNG or JPEG files without metadata: no Exif, XMP, IPTC or comments, and at + most 4 KiB of PNG text chunks. Export them again without metadata if the check refuses one. + + `name` (at most 64 characters), `description` (300), `author` (80), `version` (64) and `homepage` + (300) are one line of visible text without control or invisible characters and with at most two + combining marks on a character; Tarn rejects an index above 256 KiB. + `hosts` lists every match pattern the package asks for, required or optional, word for word as Tarn + reads it: ``, `://` (scheme `*`, `http`, `https`, `ws`, `wss` or `ftp`; + host `*`, `*.`, `` or an IP literal, with an optional port; no user or password) + `file:///`, `data:…` or `urn:…`. The store shows them as the sites the extension may ask for. + + | `category` | Shown as | + |---|---| + | `privacy-security` | Privacy & Security | + | `productivity` | Productivity | + | `reading` | Reading | + | `appearance` | Appearance | + | `accessibility` | Accessibility | + | `developer` | Developer Tools | + | `shopping` | Shopping | + | `social` | Social & Communication | + | `other` | Other | + +4. Add the icon and screenshots under `assets//`. +5. Open a pull request. The **Check** workflow validates every entry. Once it is merged into `main`, + the workflow signs and publishes the new index and rebuilds the store website. + +## Store website + +[extensions.tarnbrowser.com](https://extensions.tarnbrowser.com) lists the catalog with categories, +search and an **Install in Tarn** button per extension, which links to +`https://extensions.tarnbrowser.com/install/`. Tarn recognises that link when you click it and +opens its own consent sheet for the extension from its verified catalog copy; the website has no +other channel into the browser. + +After every signing run, the **Sign catalog** workflow builds the site from the index it just +signed and deploys it to GitHub Pages. `site/store.py` (Python 3, standard library only) checks the +store fields and writes plain HTML, the stylesheet and a small search script; `/index.json` and +`/index.sig` are the signed files, byte for byte, and `/search.json` lists id, name, description, +author and category. The pages load nothing from other sites: the Geist and Funnel Display fonts +are served from `site/static/fonts/` under the SIL Open Font License, whose text sits next to them. + +GitHub Pages cannot send response headers, so each page sets its Content Security Policy in a +`` tag. Browsers ignore `frame-ancestors` there, so another site can frame the store; that +gives it nothing, because Tarn acts only on an install link the user opens in a top-level tab and +never on one inside a frame. + +Build it locally from a signed index: + +```sh +python3 -I -m unittest discover -s site +python3 -I site/store.py check catalog.json +python3 -I site/store.py build --index index.json --sig index.sig --root . --out _site +python3 -m http.server --bind 127.0.0.1 --directory _site +``` + +`site/fixtures/` holds a catalog of fictional extensions that the **Check** workflow signs with a +throwaway key and builds as a preview (the `fixture-site` artifact). It is never published. + +## Trademarks + +"Tarn" and the Tarn logo (`site/static/mark.svg`) are trademarks of Quavon UG +(haftungsbeschränkt) that this repository's licence does not cover; see [`TRADEMARKS.md`](TRADEMARKS.md). diff --git a/TRADEMARKS.md b/TRADEMARKS.md new file mode 100644 index 0000000..c101b95 --- /dev/null +++ b/TRADEMARKS.md @@ -0,0 +1,10 @@ +# Trademarks + +"Tarn" and the Tarn logo (`site/static/mark.svg`) are trademarks of Quavon UG +(haftungsbeschränkt). The licence of this repository ([`LICENSE`](LICENSE)) covers the code, not +these marks: as section 7(e) of the GNU General Public License version 3 allows, it grants no rights +under trademark law. + +The rules for using them are Tarn's trademark policy: +[tarn-browser `TRADEMARKS.md`](https://github.com/Quavon-dev/tarn-browser/blob/main/TRADEMARKS.md). +A copy of this repository needs its own name and logo instead of `site/static/mark.svg`. diff --git a/site/fixtures/README.md b/site/fixtures/README.md new file mode 100644 index 0000000..84df64a --- /dev/null +++ b/site/fixtures/README.md @@ -0,0 +1,5 @@ +# Store fixtures + +Fictional extensions used only to test the store: `check.yml` validates this catalog, signs it with a +throwaway key and builds a preview site from it. None of it is published to +`extensions.tarnbrowser.com`, and the package URLs and hashes point at nothing. diff --git a/site/fixtures/assets/quiet-reader/dark.jpg b/site/fixtures/assets/quiet-reader/dark.jpg new file mode 100644 index 0000000..c3283bc Binary files /dev/null and b/site/fixtures/assets/quiet-reader/dark.jpg differ diff --git a/site/fixtures/assets/quiet-reader/icon.png b/site/fixtures/assets/quiet-reader/icon.png new file mode 100644 index 0000000..802b6ed Binary files /dev/null and b/site/fixtures/assets/quiet-reader/icon.png differ diff --git a/site/fixtures/assets/quiet-reader/light.png b/site/fixtures/assets/quiet-reader/light.png new file mode 100644 index 0000000..f536ce9 Binary files /dev/null and b/site/fixtures/assets/quiet-reader/light.png differ diff --git a/site/fixtures/assets/tab-tidy/icon.png b/site/fixtures/assets/tab-tidy/icon.png new file mode 100644 index 0000000..cf5c512 Binary files /dev/null and b/site/fixtures/assets/tab-tidy/icon.png differ diff --git a/site/fixtures/assets/tracker-lens/icon.png b/site/fixtures/assets/tracker-lens/icon.png new file mode 100644 index 0000000..ca93067 Binary files /dev/null and b/site/fixtures/assets/tracker-lens/icon.png differ diff --git a/site/fixtures/assets/tracker-lens/panel.png b/site/fixtures/assets/tracker-lens/panel.png new file mode 100644 index 0000000..0d16fd4 Binary files /dev/null and b/site/fixtures/assets/tracker-lens/panel.png differ diff --git a/site/fixtures/catalog.json b/site/fixtures/catalog.json new file mode 100644 index 0000000..7d9929e --- /dev/null +++ b/site/fixtures/catalog.json @@ -0,0 +1,57 @@ +{ + "kind": "tarn-extension-catalog", + "extensions": [ + { + "id": "quiet-reader", + "name": "Quiet Reader", + "description": "Turns cluttered articles into a calm, readable page with your choice of font and width.", + "version": "1.2.0", + "url": "https://github.com/Quavon-dev/tarn-extensions/releases/download/quiet-reader-1.2.0/quiet-reader.zip", + "sha256": "1111111111111111111111111111111111111111111111111111111111111111", + "size": 48213, + "permissions": ["activeTab", "storage"], + "optional_permissions": [], + "hosts": [], + "author": "Fixture Labs", + "homepage": "https://example.com/quiet-reader", + "category": "reading", + "icon": "assets/quiet-reader/icon.png", + "screenshots": ["assets/quiet-reader/light.png", "assets/quiet-reader/dark.jpg"] + }, + { + "id": "tracker-lens", + "name": "Tracker Lens", + "description": "Shows which trackers a page tried to load and blocks the ones you pick.", + "version": "0.9.1", + "url": "https://github.com/Quavon-dev/tarn-extensions/releases/download/tracker-lens-0.9.1/tracker-lens.zip", + "sha256": "2222222222222222222222222222222222222222222222222222222222222222", + "size": 91540, + "permissions": ["declarativeNetRequest", "storage"], + "optional_permissions": [], + "hosts": ["*://*/*"], + "author": "Fixture Labs", + "homepage": "https://example.com/tracker-lens", + "category": "privacy-security", + "icon": "assets/tracker-lens/icon.png", + "screenshots": ["assets/tracker-lens/panel.png"] + }, + { + "id": "tab-tidy", + "name": "Tab Tidy", + "description": "Groups open tabs by site and closes duplicates with one click.", + "version": "2.0.0", + "url": "https://github.com/Quavon-dev/tarn-extensions/releases/download/tab-tidy-2.0.0/tab-tidy.zip", + "sha256": "3333333333333333333333333333333333333333333333333333333333333333", + "size": 20480, + "permissions": ["storage"], + "optional_permissions": ["activeTab"], + "hosts": ["*://*.example.org/*"], + "author": "Example & Co", + "homepage": "https://example.org/tab-tidy", + "category": "productivity", + "icon": "assets/tab-tidy/icon.png", + "screenshots": [] + } + ], + "revoked": [] +} diff --git a/site/static/fonts/FunnelDisplay-OFL.txt b/site/static/fonts/FunnelDisplay-OFL.txt new file mode 100644 index 0000000..a3449bf --- /dev/null +++ b/site/static/fonts/FunnelDisplay-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2024 The Funnel Project Authors (https://github.com/Dicotype/Funnel) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/site/static/fonts/Geist-OFL.txt b/site/static/fonts/Geist-OFL.txt new file mode 100644 index 0000000..999fa23 --- /dev/null +++ b/site/static/fonts/Geist-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2026 The Geist Project Authors (https://github.com/vercel/geist-font) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/site/static/fonts/funnel-display-latin-ext.woff2 b/site/static/fonts/funnel-display-latin-ext.woff2 new file mode 100644 index 0000000..f22bf80 Binary files /dev/null and b/site/static/fonts/funnel-display-latin-ext.woff2 differ diff --git a/site/static/fonts/funnel-display-latin.woff2 b/site/static/fonts/funnel-display-latin.woff2 new file mode 100644 index 0000000..9d9829b Binary files /dev/null and b/site/static/fonts/funnel-display-latin.woff2 differ diff --git a/site/static/fonts/geist-latin-ext.woff2 b/site/static/fonts/geist-latin-ext.woff2 new file mode 100644 index 0000000..8a1d3df Binary files /dev/null and b/site/static/fonts/geist-latin-ext.woff2 differ diff --git a/site/static/fonts/geist-latin.woff2 b/site/static/fonts/geist-latin.woff2 new file mode 100644 index 0000000..8f01e76 Binary files /dev/null and b/site/static/fonts/geist-latin.woff2 differ diff --git a/site/static/mark.svg b/site/static/mark.svg new file mode 100644 index 0000000..9e7437a --- /dev/null +++ b/site/static/mark.svg @@ -0,0 +1,155 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/site/static/search.js b/site/static/search.js new file mode 100644 index 0000000..c000409 --- /dev/null +++ b/site/static/search.js @@ -0,0 +1,106 @@ +"use strict"; + +(function () { + const script = document.currentScript; + const searchUrl = new URL("search.json", script.src); + + function normalize(text) { + return text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase(); + } + + function start() { + const form = document.querySelector("form.search"); + const input = document.getElementById("q"); + const results = document.getElementById("results"); + const status = document.getElementById("status"); + if (!form || !input || !results || !status) { + return; + } + + const params = new URLSearchParams(location.search); + const fixed = form.querySelector('input[name="category"]'); + const chips = document.querySelectorAll("a.chip[data-category]"); + const labels = new Map(Array.from(chips, (chip) => [chip.dataset.category, chip.textContent])); + const requested = params.get("category"); + const category = fixed ? fixed.value : labels.has(requested) ? requested : ""; + const cards = Array.from(results.querySelectorAll("li[data-id]")); + let haystacks = null; + + if (!fixed && category) { + document.querySelectorAll('a.chip[aria-current="page"]').forEach((chip) => chip.removeAttribute("aria-current")); + chips.forEach((chip) => { + if (chip.dataset.category === category) { + chip.setAttribute("aria-current", "page"); + } + }); + } + + function remember(query) { + const next = new URLSearchParams(); + if (query) { + next.set("q", query); + } + if (!fixed && category) { + next.set("category", category); + } + const search = next.toString(); + history.replaceState(null, "", search ? "?" + search : location.pathname); + } + + function apply() { + const query = input.value.trim(); + const terms = normalize(query).split(/\s+/).filter(Boolean); + let shown = 0; + for (const card of cards) { + const haystack = haystacks.get(card.dataset.id) || ""; + const visible = (!category || card.dataset.category === category) && terms.every((term) => haystack.includes(term)); + card.hidden = !visible; + shown += visible ? 1 : 0; + } + const scope = category && !fixed ? " in " + labels.get(category) : ""; + if (!query && !scope) { + status.textContent = ""; + } else if (shown === 0) { + status.textContent = "No extensions match" + (query ? " \u201c" + query + "\u201d" : "") + scope + "."; + } else { + status.textContent = shown + (shown === 1 ? " extension" : " extensions") + scope + "."; + } + remember(query); + } + + fetch(searchUrl, { credentials: "omit" }) + .then((response) => (response.ok ? response.json() : Promise.reject(new Error(response.statusText)))) + .then((entries) => { + haystacks = new Map( + entries.map((entry) => [ + entry.id, + normalize([entry.name, entry.description, entry.author, entry.category, labels.get(entry.category) || ""].join(" ")), + ]) + ); + if (!input.value) { + input.value = params.get("q") || ""; + } + input.addEventListener("input", apply); + form.addEventListener("submit", (event) => { + event.preventDefault(); + apply(); + }); + document.addEventListener("keydown", (event) => { + const target = event.target; + const typing = target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target.isContentEditable; + if (event.key === "/" && !typing && !event.metaKey && !event.ctrlKey && !event.altKey) { + event.preventDefault(); + input.focus(); + } + }); + apply(); + }) + .catch(() => {}); + } + + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", start); + } else { + start(); + } +})(); diff --git a/site/static/style.css b/site/static/style.css new file mode 100644 index 0000000..f3e32c9 --- /dev/null +++ b/site/static/style.css @@ -0,0 +1,371 @@ +@font-face { + font-family: Geist; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url("fonts/geist-latin.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + +@font-face { + font-family: Geist; + font-style: normal; + font-weight: 100 900; + font-display: swap; + src: url("fonts/geist-latin-ext.woff2") format("woff2"); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF; +} + +@font-face { + font-family: "Funnel Display"; + font-style: normal; + font-weight: 500 600; + font-display: swap; + src: url("fonts/funnel-display-latin.woff2") format("woff2"); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + +@font-face { + font-family: "Funnel Display"; + font-style: normal; + font-weight: 500 600; + font-display: swap; + src: url("fonts/funnel-display-latin-ext.woff2") format("woff2"); + unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF; +} + +:root { + color-scheme: light dark; + --font-body: Geist, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-display: "Funnel Display", Geist, system-ui, sans-serif; + --background: #f5f1ee; + --foreground: #0c1d31; + --muted: #4c5d75; + --border: rgb(12 29 49 / 12%); + --ring: rgb(12 29 49 / 10%); + --outline: rgb(12 29 49 / 20%); + --surface: #ffffff; + --raised: #ece3df; + --lake: #1f75b0; + --link: #17639a; + --solid: #0c1d31; + --on-solid: #e2d8d2; + --arrow: rgb(226 216 210 / 10%); + --chip: rgb(12 29 49 / 6%); + --chip-hover: rgb(12 29 49 / 11%); + --shadow: rgb(12 29 49 / 22%); + --ease: cubic-bezier(0.32, 0.72, 0, 1); +} + +@media (prefers-color-scheme: dark) { + :root { + --background: #0c1d31; + --foreground: #f4f9fd; + --muted: #a1a9bd; + --border: rgb(244 249 253 / 12%); + --ring: rgb(244 249 253 / 10%); + --outline: rgb(244 249 253 / 24%); + --surface: #10243a; + --raised: #153049; + --lake: #8ed1f7; + --link: #8ed1f7; + --solid: #f4f9fd; + --on-solid: #0c1d31; + --arrow: rgb(12 29 49 / 10%); + --chip: rgb(244 249 253 / 8%); + --chip-hover: rgb(244 249 253 / 14%); + --shadow: rgb(0 0 0 / 55%); + } +} + +* { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; } + +body { + margin: 0; + min-height: 100vh; + font: 16px/1.5 var(--font-body); + color: var(--foreground); + background: var(--background); + overflow-wrap: anywhere; + -webkit-font-smoothing: antialiased; +} + +a { color: var(--link); text-underline-offset: 3px; } + +:focus-visible { + outline: 2px solid var(--lake); + outline-offset: 3px; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +.skip { position: absolute; left: -999px; top: 8px; } +.skip:focus { left: 16px; padding: 8px 12px; background: var(--surface); color: var(--foreground); z-index: 1; } + +.wrap { + width: 100%; + max-width: 80rem; + margin: 0 auto; + padding-inline: 16px; +} + +@media (min-width: 640px) { + .wrap { padding-inline: 32px; } +} + +.top { border-bottom: 1px solid var(--border); } + +.bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding-block: 18px; +} + +.brand { + display: inline-flex; + align-items: center; + gap: 10px; + margin: 0; + font: 600 1.25rem/1 var(--font-display); + letter-spacing: -0.025em; + color: var(--foreground); + text-decoration: none; +} + +.brand img { border-radius: 7px; } +.brand span { color: var(--muted); font-weight: 500; } + +h1, h2 { + font-family: var(--font-display); + font-weight: 600; + color: var(--foreground); +} + +h1 { + font-size: clamp(2.5rem, 7vw, 4.75rem); + line-height: 0.95; + letter-spacing: -0.045em; + margin: 56px 0 16px; +} + +h2 { font-size: 1.375rem; letter-spacing: -0.02em; margin: 40px 0 14px; } + +.lake { color: var(--lake); } + +.lead { color: var(--muted); font-size: 1.125rem; margin: 0 0 28px; max-width: 40rem; } + +.pill { + display: inline-flex; + align-items: center; + gap: 12px; + min-height: 44px; + padding: 6px 20px; + border: 0; + border-radius: 999px; + font: 500 0.875rem/1 var(--font-body); + text-decoration: none; + white-space: nowrap; + cursor: pointer; +} + +.pill.solid { background: var(--solid); color: var(--on-solid); } +.pill.solid:has(.arrow) { padding-right: 6px; } +.pill.solid:hover { opacity: 0.92; } +.pill.solid:active { transform: scale(0.98); } + +.pill.outline { color: var(--foreground); box-shadow: inset 0 0 0 1px var(--outline); } +.pill.outline:hover { background: var(--chip); } + +.arrow { + display: grid; + place-items: center; + width: 32px; + height: 32px; + border-radius: 999px; + background: var(--arrow); +} + +.search { display: flex; gap: 8px; margin: 8px 0 16px; max-width: 44rem; } + +.search input { + flex: 1; + min-width: 0; + min-height: 48px; + font: inherit; + color: var(--foreground); + padding: 10px 20px; + border: 0; + border-radius: 999px; + background: var(--surface); + box-shadow: inset 0 0 0 1px var(--outline); +} + +.search input::placeholder { color: var(--muted); opacity: 1; } +.search .pill { min-height: 48px; } + +.chips { + list-style: none; + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 0; + margin: 0 0 8px; +} + +.chip { + display: inline-block; + padding: 8px 14px; + border-radius: 999px; + background: var(--chip); + color: var(--muted); + text-decoration: none; + font-size: 0.875rem; +} + +.chip:hover { background: var(--chip-hover); color: var(--foreground); } +.chip[aria-current="page"] { background: var(--solid); color: var(--on-solid); } + +.status { color: var(--muted); min-height: 1.5em; margin: 12px 0; font-size: 0.875rem; } + +.grid { + list-style: none; + padding: 0; + margin: 0 0 64px; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); + gap: 16px; +} + +.card a { + display: flex; + gap: 16px; + height: 100%; + padding: 20px; + border-radius: 20px; + background: var(--surface); + box-shadow: 0 0 0 1px var(--ring), 0 2rem 4rem -2rem var(--shadow); + color: var(--foreground); + text-decoration: none; +} + +.card a:hover { background: var(--raised); } + +.card img, .hero img, .install-page img { border-radius: 22.5%; flex: none; } + +.card-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.card strong { font: 600 1.125rem/1.2 var(--font-display); letter-spacing: -0.015em; } +.desc { color: var(--muted); font-size: 0.9375rem; } +.cat, .tag { color: var(--link); font-size: 0.8125rem; font-weight: 500; margin-top: 4px; } + +.empty { color: var(--muted); margin-bottom: 64px; } + +.hero { --title: clamp(2.25rem, 5vw, 3.5rem); display: flex; gap: clamp(16px, 3vw, 24px); align-items: flex-start; margin-top: 48px; } +.hero > div { flex: 1; min-width: 0; } +.hero h1 { margin: 0; font-size: var(--title); } +.hero img { margin-top: calc(var(--title) * 0.16); } +.byline { color: var(--muted); margin: 8px 0 18px; } +.detail .lead { margin-top: 28px; } + +.shots { + overflow-x: auto; + scroll-snap-type: x mandatory; + scroll-padding-inline: 2px; + overscroll-behavior-x: contain; + padding: 2px 2px 12px; + border-radius: 20px; + scrollbar-width: thin; +} + +.shots ul { + list-style: none; + display: flex; + gap: 16px; + margin: 0; + padding: 0; +} + +.shots li { flex: 0 0 min(480px, 78%); scroll-snap-align: start; } + +.shots a { display: block; border-radius: 16px; } + +.shots img { + display: block; + width: 100%; + height: auto; + border-radius: 16px; + box-shadow: 0 0 0 1px var(--ring); +} + +.facts { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); + gap: 16px; + margin: 32px 0 64px; +} + +.facts section { + padding: 4px 20px 16px; + border-radius: 20px; + background: var(--surface); + box-shadow: 0 0 0 1px var(--ring); +} + +.facts h2 { margin: 16px 0 10px; font-size: 1.0625rem; } +.facts ul { margin: 0; padding-left: 1.1em; } +.facts dl { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 0; } +.facts dt { color: var(--muted); } +.facts dd { margin: 0; } +.facts .note { color: var(--muted); font-size: 0.875rem; margin: 10px 0 0; } + +.install-page { text-align: center; max-width: 40rem; margin: 64px auto 96px; } +.install-page h1 { font-size: clamp(2rem, 5vw, 3rem); margin-top: 24px; } +.install-page p { color: var(--muted); } +.url code { padding: 4px 10px; border-radius: 8px; background: var(--chip); color: var(--foreground); } +.actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; margin-top: 32px; } + +.bottom { border-top: 1px solid var(--border); font-size: 0.875rem; color: var(--muted); } + +.columns { + display: grid; + gap: 32px; + padding-block: 48px; +} + +@media (min-width: 640px) { + .columns { grid-template-columns: 1fr auto auto; gap: 64px; } +} + +.about p { margin: 12px 0 0; max-width: 22rem; } +.about .brand { margin: 0; } + +.bottom h2 { font: 500 0.875rem/1.4 var(--font-body); letter-spacing: 0; margin: 0; } +.bottom ul { list-style: none; margin: 12px 0 0; padding: 0; display: grid; gap: 8px; } +.bottom ul a, .fine a { color: var(--muted); text-decoration: none; } +.bottom ul a:hover, .fine a:hover { color: var(--foreground); text-decoration: underline; } + +.fine { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 8px 24px; + margin: 0; + padding-block: 20px 32px; + border-top: 1px solid var(--border); +} + +[hidden] { display: none !important; } + +@media (prefers-reduced-motion: no-preference) { + .card a, .chip, .pill { transition: background-color 150ms var(--ease), opacity 150ms var(--ease), transform 150ms var(--ease); } +} diff --git a/site/store.py b/site/store.py new file mode 100644 index 0000000..cf5bed4 --- /dev/null +++ b/site/store.py @@ -0,0 +1,517 @@ +import argparse +import html +import json +import re +import shutil +import struct +import sys +import unicodedata +import zlib +from pathlib import Path +from urllib.parse import urlsplit + +SITE = "https://extensions.tarnbrowser.com" +DOMAIN = "extensions.tarnbrowser.com" +KIND = "tarn-extension-catalog" +STATIC = Path(__file__).resolve().parent / "static" +LANDING = "https://tarnbrowser.com/" +GET_TARN = LANDING + "#get-tarn" +PRIVACY = LANDING + "privacy#extension-store" +IMPRINT = LANDING + "imprint" +ARROW = '' + +CATEGORIES = { + "privacy-security": "Privacy & Security", + "productivity": "Productivity", + "reading": "Reading", + "appearance": "Appearance", + "accessibility": "Accessibility", + "developer": "Developer Tools", + "shopping": "Shopping", + "social": "Social & Communication", + "other": "Other", +} + +PERMISSIONS = { + "activeTab": "Clicking its toolbar button gives it the page you are on, in that tab", + "alarms": "Run tasks on a schedule", + "clipboardRead": "Read what you copy", + "clipboardWrite": "Put text on your clipboard", + "contextMenus": "Add items to the right-click menu", + "cookies": "Read and change cookies on the sites you allow", + "declarativeNetRequest": "Block or change network requests by rules", + "declarativeNetRequestFeedback": "See which of its blocking rules matched", + "declarativeNetRequestWithHostAccess": "Block or change network requests on the sites you allow", + "menus": "Add items to the right-click menu", + "nativeMessaging": "Talk to an app installed on your device", + "notifications": "Show notifications", + "scripting": "Run scripts on the sites you allow", + "storage": "Keep its own data on this device", + "tabs": "See the titles and addresses of your tabs", + "unlimitedStorage": "Keep more data on this device than usual", + "webNavigation": "See when pages load in your tabs", + "webRequest": "See network requests on the sites you allow", +} + +ID = re.compile(r"[a-z0-9-]{1,64}") +HOST = re.compile(r"(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}") +MATCH = re.compile(r"(\*|https?|wss?|ftp)://(\*|(\*\.)?([^\s/*@:\\\[\]?#]+|\[[0-9A-Fa-f:.]+\]))(?::(\*|[0-9]{1,5}))?/\S*") +LOCAL_FILES = re.compile(r"file://(?:localhost)?/\S*") +OPAQUE = re.compile(r"(?:data|urn):\S+") +PERMISSION = re.compile(r"[A-Za-z][A-Za-z0-9._]{0,63}") +INVISIBLE = {"Cc", "Cf", "Cs", "Co", "Cn", "Zl", "Zp"} +FILLERS = {0x034F, 0x115F, 0x1160, 0x17B4, 0x17B5, 0x2800, 0x3164, 0xFFA0, *range(0x180B, 0x1810), *range(0xFE00, 0xFE10), *range(0xE0100, 0xE01F0)} +MARKS = {"Mn", "Me"} +MAX_MARKS = 2 +LIMITS = {"name": 64, "description": 300, "author": 80, "version": 64, "homepage": 300} +ITEM_LIMIT = 256 +FIELDS = { + "id": str, "name": str, "description": str, "version": str, "url": str, "sha256": str, "size": int, + "author": str, "homepage": str, "category": str, "icon": str, +} +LISTS = ("permissions", "optional_permissions", "hosts", "screenshots") +ICON_BYTES = 256 << 10 +ICON_PX = (128, 512) +SHOT_BYTES = 1 << 20 +SHOT_PX = 2560 +MAX_SHOTS = 5 +PNG_DEPTHS = {0: {1, 2, 4, 8, 16}, 2: {8, 16}, 3: {1, 2, 4, 8}, 4: {8, 16}, 6: {8, 16}} +PNG_TEXT = {b"tEXt", b"zTXt", b"iTXt"} +PNG_TEXT_BYTES = 4096 +JPEG_METADATA = {0xE1: "Exif or XMP", 0xED: "IPTC", 0xFE: "a comment"} +STRIP = "export the image again without metadata (Exif, XMP, IPTC, comments), which can hold the camera, place or author" +CSP = "default-src 'self'; img-src 'self'; script-src 'self'; style-src 'self'; base-uri 'none'; form-action 'self'" + + +class Invalid(Exception): + pass + + +def png_size(data): + if data[:8] != b"\x89PNG\r\n\x1a\n": + raise Invalid("not a PNG") + i, size, chunk, text, idat = 8, None, b"", 0, False + while chunk != b"IEND": + if i + 12 > len(data): + raise Invalid("PNG ends before its IEND chunk") + length, chunk = struct.unpack(">I4s", data[i : i + 8]) + end = i + 12 + length + if end > len(data) or zlib.crc32(data[i + 4 : end - 4]) != struct.unpack(">I", data[end - 4 : end])[0]: + raise Invalid("damaged PNG chunk") + if (i == 8) != (chunk == b"IHDR"): + raise Invalid("PNG must start with one IHDR chunk") + if chunk == b"IHDR": + if length != 13: + raise Invalid("PNG IHDR must be 13 bytes") + size = struct.unpack(">II", data[i + 8 : i + 16]) + depth, colour, compression, filtering, interlace = data[i + 16 : i + 21] + if depth not in PNG_DEPTHS.get(colour, ()) or compression or filtering or interlace > 1: + raise Invalid("PNG has an invalid bit depth, colour type, compression, filter or interlace method") + body = data[i + 8 : end - 4] + if chunk == b"eXIf" or (chunk == b"iTXt" and body.startswith(b"XML:com.adobe.xmp\x00")): + raise Invalid(f"PNG has metadata ({chunk.decode()}); {STRIP}") + text += length if chunk in PNG_TEXT else 0 + idat = idat or chunk == b"IDAT" + i = end + if i != len(data): + raise Invalid("data after the PNG's IEND chunk") + if not idat: + raise Invalid("PNG has no IDAT image data") + if text > PNG_TEXT_BYTES: + raise Invalid(f"PNG text chunks must total at most {PNG_TEXT_BYTES // 1024} KiB") + return size + + +def jpeg_size(data): + if data[:2] != b"\xff\xd8": + raise Invalid("not a JPEG") + i, size, scan = 2, None, False + while True: + if i + 2 > len(data) or data[i] != 0xFF: + raise Invalid("damaged JPEG") + marker = data[i + 1] + if marker == 0xFF: + i += 1 + continue + if marker == 0xD9: + break + if 0xD0 <= marker <= 0xD7 or marker == 0x01: + i += 2 + continue + if i + 4 > len(data): + raise Invalid("damaged JPEG") + length = struct.unpack(">H", data[i + 2 : i + 4])[0] + if length < 2 or i + 2 + length > len(data): + raise Invalid("damaged JPEG segment") + if marker in JPEG_METADATA: + raise Invalid(f"JPEG has metadata ({JPEG_METADATA[marker]}); {STRIP}") + if 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC): + if size is not None or length < 7: + raise Invalid("JPEG must have exactly one frame header") + height, width = struct.unpack(">HH", data[i + 5 : i + 9]) + size = (width, height) + i += 2 + length + if marker == 0xDA: + if size is None: + raise Invalid("JPEG scan before its frame header") + scan = True + while i + 1 < len(data) and not (data[i] == 0xFF and data[i + 1] not in (0x00, *range(0xD0, 0xD8))): + i += 1 + if size is None: + raise Invalid("JPEG without a frame header") + if not scan: + raise Invalid("JPEG has no scan") + if i + 2 != len(data): + raise Invalid("data after the JPEG's end marker") + return size + + +def image(root, entry_id, rel, pattern, max_bytes): + if not re.fullmatch(rf"assets/{entry_id}/{pattern}", rel): + raise Invalid(f"{rel!r} must match assets/{entry_id}/{pattern}") + path = root / rel + if path.is_symlink() or not path.is_file() or root.resolve() not in path.resolve().parents: + raise Invalid(f"{rel} is missing or not a regular file") + if path.stat().st_size > max_bytes: + raise Invalid(f"{rel} must be at most {max_bytes // 1024} KiB") + data = path.read_bytes() + try: + width, height = (png_size if rel.endswith(".png") else jpeg_size)(data) + except (struct.error, IndexError, ValueError) as err: + raise Invalid(f"{rel} is damaged") from err + if not width or not height: + raise Invalid(f"{rel} has no size") + return {"path": rel, "bytes": len(data), "width": width, "height": height} + + +def hidden(c): + return ord(c) in FILLERS or unicodedata.category(c) in INVISIBLE + + +def clean(value, key, limit): + if not value.strip() or len(value) > limit or any(hidden(c) for c in value): + raise Invalid(f"{key} must be one line of at most {limit} characters without control or invisible characters") + text = unicodedata.normalize("NFD", value) + if all(c.isspace() or unicodedata.category(c) in MARKS for c in text): + raise Invalid(f"{key} must contain visible characters") + marks = 0 + for c in text: + marks = marks + 1 if unicodedata.category(c) in MARKS else 0 + if marks > MAX_MARKS: + raise Invalid(f"{key} may have at most {MAX_MARKS} combining marks on one character") + return value + + +def homepage_host(url): + parts = urlsplit(url) if url.isascii() and "\\" not in url and not any(c.isspace() for c in url) else None + host = parts and parts.hostname + if not host or parts.scheme != "https" or host != parts.netloc or not HOST.fullmatch(host): + raise Invalid("homepage must be an https URL with a plain ASCII host (punycode for others), no user, password or port") + return host + + +def types(entry): + for key, kind in FIELDS.items(): + value = entry.get(key) + if not isinstance(value, kind) or isinstance(value, bool): + raise Invalid(f"{key} must be {'text' if kind is str else 'a whole number'}") + for key in LISTS: + value = entry.get(key, []) + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise Invalid(f"{key} must be a list of strings") + + +def store_fields(entry, root): + types(entry) + entry_id = entry["id"] + for key, limit in LIMITS.items(): + clean(entry[key], key, limit) + for key in LISTS: + for value in entry.get(key, []): + clean(value, key, ITEM_LIMIT) + for value in entry.get("hosts", []): + plain_host(value) + for key in ("permissions", "optional_permissions"): + for value in entry.get(key, []): + if not PERMISSION.fullmatch(value) and (key == "permissions" or not is_pattern(value)): + raise Invalid(f"{key} must list permission names" + (" or host match patterns" if key != "permissions" else "")) + host = homepage_host(entry["homepage"]) + if entry["category"] not in CATEGORIES: + raise Invalid(f"category must be one of {', '.join(CATEGORIES)}") + if entry["icon"] != f"assets/{entry_id}/icon.png": + raise Invalid(f"icon must be assets/{entry_id}/icon.png") + icon = image(root, entry_id, entry["icon"], r"icon\.png", ICON_BYTES) + if icon["width"] != icon["height"] or not ICON_PX[0] <= icon["width"] <= ICON_PX[1]: + raise Invalid(f"icon must be square, {ICON_PX[0]} to {ICON_PX[1]} px") + shots = entry.get("screenshots", []) + if len(shots) > MAX_SHOTS or len(set(shots)) != len(shots): + raise Invalid(f"screenshots must list at most {MAX_SHOTS} distinct paths") + checked = [image(root, entry_id, s, r"[a-z0-9][a-z0-9_-]*\.(png|jpg)", SHOT_BYTES) for s in shots] + for shot in checked: + if shot["width"] > SHOT_PX or shot["height"] > SHOT_PX: + raise Invalid(f"{shot['path']} must be at most {SHOT_PX} px wide and high") + return {"icon": icon, "shots": checked, "host": host} + + +def check(catalog, root): + if not isinstance(catalog, dict) or catalog.get("kind") != KIND or not isinstance(catalog.get("extensions"), list): + raise Invalid(f"kind must be {KIND} with an extensions list") + revoked = catalog.get("revoked", []) + if not isinstance(revoked, list) or not all(isinstance(r, dict) and isinstance(r.get("id"), str) and isinstance(r.get("sha256"), str) for r in revoked): + raise Invalid("revoked must list objects with a string id and sha256") + seen, errors, checked = set(), [], {} + for n, entry in enumerate(catalog["extensions"]): + entry_id = entry.get("id") if isinstance(entry, dict) else None + valid_id = isinstance(entry_id, str) and ID.fullmatch(entry_id) + label = entry_id if valid_id else f"entry #{n + 1}" + try: + if not isinstance(entry, dict): + raise Invalid("an entry must be an object") + if not valid_id: + raise Invalid("id must be lowercase letters, digits and - (at most 64)") + if entry_id in seen: + raise Invalid("duplicate id") + seen.add(entry_id) + checked[entry_id] = store_fields(entry, root) + except (Invalid, ValueError) as err: + errors.append(f"{label}: {err}") + if errors: + raise Invalid("\n".join(errors)) + return checked + + +def e(value): + return html.escape(str(value), quote=True) + + +def is_pattern(value): + try: + plain_host(value) + except Invalid: + return False + return True + + +def plain_host(pattern): + if pattern == "": + return "every site" + if LOCAL_FILES.fullmatch(pattern): + return "local files" + match = MATCH.fullmatch(pattern) + if not match and OPAQUE.fullmatch(pattern): + return pattern + if not match or (match.group(5) not in (None, "*") and int(match.group(5)) > 65535): + raise Invalid(f"{pattern!r} is not a match pattern: , :// with host *, *. or and an optional port, or file:///") + scheme, host, subdomains, name, port = match.groups() + if scheme not in ("*", "http", "https"): + return pattern + site = "every site" if host == "*" else f"{name} and its subdomains" if subdomains else name + return site + ("" if port is None else " (any port)" if port == "*" else f" (port {port})") + + +def describe(permission): + return PERMISSIONS.get(permission, f"Uses the {permission} API") + + +def page(root, title, body, description=""): + return f""" + + + + + + + + +{e(title)} + + + + + +
+
+{body} +
+ + + +""" + + +def search_form(root, category=None): + hidden = f'' if category else "" + return f"""""" + + +def chips(root, current): + items = [f'
  • All
  • '] + for cat, label in CATEGORIES.items(): + mark = " aria-current=page" if cat == current else "" + items.append(f'
  • {e(label)}
  • ') + return f'' + + +def card(root, entry): + i = entry["id"] + return f"""
  • + + +{e(entry['name'])} +{e(entry['description'])} +{e(CATEGORIES[entry['category']])} + +
  • """ + + +def listing(root, entries, category=None): + cards = "".join(card(root, x) for x in entries) + empty = "" if entries else '

    No extensions here yet.

    ' + return f"""{search_form(root, category)} +{chips(root, category)} +

    +
      {cards}
    {empty}""" + + +def detail(entry, checked): + icon, shots = checked["icon"], checked["shots"] + i, name = entry["id"], entry["name"] + perms = [describe(p) for p in entry.get("permissions", [])] + optional = [describe(p) for p in entry.get("optional_permissions", []) if not is_pattern(p)] + patterns = entry.get("hosts", []) + [p for p in entry.get("optional_permissions", []) if is_pattern(p)] + hosts = list(dict.fromkeys(plain_host(h) for h in patterns)) + rows = "".join(f"
  • {e(p)}
  • " for p in perms) or "
  • No special permissions
  • " + rows += "".join(f"
  • {e(p)} if you allow it
  • " for p in optional) + sites = "".join(f"
  • {e(h)}
  • " for h in hosts) or "
  • No sites
  • " + gallery = "".join( + f'
  • {e(name)}, screenshot {n} of {len(shots)}
  • ' + for n, s in enumerate(shots, 1) + ) + screenshots = ( + f'

    Screenshots

    ' + f'
      {gallery}
    ' + ) + size = f"{entry['size'] / 1024:.0f} KB" if isinstance(entry.get("size"), int) else "" + body = f"""""" + return page("../../", f"{name} · Tarn Extensions", body, entry["description"]) + + +def install(entry): + i, name = entry["id"], entry["name"] + body = f"""
    + +

    Open this link in Tarn to install {e(name)}

    +

    Tarn asks before it installs anything and shows what the extension can do. This page offers no download.

    +

    {SITE}/install/{i}

    +

    Get Tarn{ARROW}About {e(name)}

    +
    """ + return page("../../", f"Install {name} · Tarn Extensions", body) + + +def write(path, content): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + + +def build(index_path, sig_path, root, out): + raw = index_path.read_bytes() + index = json.loads(raw) + checked = check(index, root) + revoked = {(r.get("id"), r.get("sha256")) for r in index.get("revoked", [])} + entries = sorted((x for x in index["extensions"] if (x["id"], x.get("sha256")) not in revoked), key=lambda x: (x["name"].casefold(), x["id"])) + if out.exists() and any(out.iterdir()): + raise Invalid(f"{out} must be empty") + out.mkdir(parents=True, exist_ok=True) + (out / "index.json").write_bytes(raw) + (out / "index.sig").write_bytes(sig_path.read_bytes()) + (out / "CNAME").write_text(DOMAIN + "\n") + shutil.copytree(STATIC, out, dirs_exist_ok=True) + search = [{k: x[k] for k in ("id", "name", "description", "author", "category")} for x in entries] + write(out / "search.json", json.dumps(search, ensure_ascii=False, indent=1) + "\n") + intro = "

    Extensions for Tarn.

    Reviewed and signed by the Tarn maintainers. Install with one click in Tarn.

    " + write(out / "index.html", page("./", "Tarn Extensions", intro + listing("./", entries))) + for cat, label in CATEGORIES.items(): + members = [x for x in entries if x["category"] == cat] + write(out / "category" / cat / "index.html", page("../../", f"{label} · Tarn Extensions", f"

    {e(label)}

    " + listing("../../", members, cat))) + for x in entries: + for asset in [checked[x["id"]]["icon"], *checked[x["id"]]["shots"]]: + (out / asset["path"]).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(root / asset["path"], out / asset["path"]) + write(out / "extension" / x["id"] / "index.html", detail(x, checked[x["id"]])) + write(out / "install" / x["id"] / "index.html", install(x)) + write(out / "404.html", page("/", "Not found · Tarn Extensions", '

    Not found

    This page does not exist. All extensions

    ')) + return len(entries) + + +def main(): + parser = argparse.ArgumentParser(description="Check the catalog's store fields and build the store website.") + sub = parser.add_subparsers(dest="command", required=True) + c = sub.add_parser("check") + c.add_argument("catalog", type=Path) + c.add_argument("--root", type=Path, default=Path(".")) + b = sub.add_parser("build") + b.add_argument("--index", type=Path, required=True) + b.add_argument("--sig", type=Path, required=True) + b.add_argument("--root", type=Path, default=Path(".")) + b.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + try: + if args.command == "check": + n = len(check(json.loads(args.catalog.read_text(encoding="utf-8")), args.root)) + print(f"{n} entries ok") + else: + print(f"built {build(args.index, args.sig, args.root, args.out)} extensions into {args.out}") + except (Invalid, ValueError, KeyError, OSError) as err: + print(f"::error::{err}".replace("\n", "%0A"), file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/site/test_store.py b/site/test_store.py new file mode 100644 index 0000000..4917293 --- /dev/null +++ b/site/test_store.py @@ -0,0 +1,343 @@ +import copy +import json +import shutil +import struct +import subprocess +import sys +import tempfile +import unittest +import zlib +from pathlib import Path + +import store + +FIXTURES = Path(__file__).resolve().parent / "fixtures" + + +def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + + +def png(width, height, pixels=True): + rows = b"".join(b"\x00" + b"\x00" * width for _ in range(height)) if pixels else b"" + header = chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0)) + return b"\x89PNG\r\n\x1a\n" + header + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"") + + +def field(key, value): + return lambda c, root: c["extensions"][2].__setitem__(key, value) + + +def screenshot(name, data): + def apply(c, root): + (root / "assets/tab-tidy" / name).write_bytes(data) + c["extensions"][2]["screenshots"] = [f"assets/tab-tidy/{name}"] + + return apply + + +def icon(data): + return lambda c, root: (root / "assets/tab-tidy/icon.png").write_bytes(data) + + +def symlink(c, root): + (root / "assets/tab-tidy/evil.png").symlink_to("/etc/hosts") + c["extensions"][2]["screenshots"] = ["assets/tab-tidy/evil.png"] + + +def fixture_bytes(path): + return (FIXTURES / path).read_bytes() + + +def jpeg_frame(width, height): + return b"\xff\xc0" + struct.pack(">HBHHB", 11, 8, height, width, 1) + b"\x01\x11\x00" + + +def six_distinct(c, root): + names = [f"assets/tab-tidy/shot{n}.png" for n in range(6)] + for name in names: + (root / name).write_bytes(png(16, 16)) + c["extensions"][2]["screenshots"] = names + + +EMPTY_IHDR = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", b"") + + +def png_with(*chunks, depth=8, colour=0, idat=True): + header = chunk(b"IHDR", struct.pack(">IIBBBBB", 16, 16, depth, colour, 0, 0, 0)) + data = chunk(b"IDAT", zlib.compress(b"\x00" * 17 * 16)) if idat else b"" + return b"\x89PNG\r\n\x1a\n" + header + b"".join(chunks) + data + chunk(b"IEND", b"") + + +def segment(marker, payload): + return bytes([0xFF, marker]) + struct.pack(">H", len(payload) + 2) + payload + + +def jpeg_with(*segments): + data = fixture_bytes("assets/quiet-reader/dark.jpg") + return data[:2] + b"".join(segments) + data[2:] + + +VALID_PATTERNS = { + "": "every site", + "*://*/*": "every site", + "https://*/*": "every site", + "*://*.example.org/*": "example.org and its subdomains", + "*://*.example.org:8443/*": "example.org and its subdomains (port 8443)", + "https://example.org/path/*": "example.org", + "*://Example.com/*": "Example.com", + "http://localhost/*": "localhost", + "*://localhost:3000/*": "localhost (port 3000)", + "http://localhost:*/*": "localhost (any port)", + "http://127.0.0.1/*": "127.0.0.1", + "http://[::1]:8080/*": "[::1] (port 8080)", + "file:///*": "local files", + "file:///Users/*": "local files", + "wss://example.com/*": "wss://example.com/*", + "ws://localhost:8080/socket": "ws://localhost:8080/socket", + "ftp://example.com/*": "ftp://example.com/*", + "urn:*": "urn:*", +} + +KNOWN_PERMISSIONS = [ + "activeTab", "alarms", "clipboardRead", "clipboardWrite", "contextMenus", "cookies", "declarativeNetRequest", + "declarativeNetRequestFeedback", "declarativeNetRequestWithHostAccess", "menus", "nativeMessaging", + "notifications", "scripting", "storage", "tabs", "unlimitedStorage", "webNavigation", "webRequest", +] + +VALID_TEXT = ["Cafe\u0301", "Vi\u1ec7t", "\u0e17\u0e35\u0e48", "Tab Tidy"] + + +INVALID = { + "category outside the list": field("category", "games"), + "category of the wrong type": field("category", ["reading"]), + "http homepage": field("homepage", "http://example.com/"), + "javascript homepage": field("homepage", "javascript:alert(1)"), + "homepage with a user": field("homepage", "https://a@b.example/"), + "homepage with a port": field("homepage", "https://example.com:8443/"), + "homepage with a Cyrillic host": field("homepage", "https://\u0435xample.com/"), + "homepage with a backslash": field("homepage", "https://evil.com\\.example.com/"), + "homepage with U+2028": field("homepage", "https://example.com/\u2028x"), + "homepage too long": field("homepage", "https://example.com/" + "a" * 281), + "icon outside its folder": field("icon", "assets/tab-tidy/../quiet-reader/icon.png"), + "icon not square": icon(fixture_bytes("assets/tracker-lens/panel.png")), + "icon with data after IEND": icon(fixture_bytes("assets/tab-tidy/icon.png") + b""), + "PNG with data after IEND": screenshot("extra.png", fixture_bytes("assets/quiet-reader/light.png") + b"