diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 02228a9..a465d0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,8 +17,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 with: node-version: 24 cache: npm @@ -37,12 +37,12 @@ jobs: run: npm run test:e2e - name: Package run: node scripts/package.mjs - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 with: name: shieldfix-extension path: release/*.zip if-no-files-found: error - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 if: failure() with: name: playwright-report diff --git a/docs/RELEASE.md b/docs/RELEASE.md index b95e78a..1882f04 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -31,8 +31,8 @@ listing, and is a major version. - [ ] Brave’s extension page shows no errors for ShieldFix. 7. **Package:** `npm run package` → `release/shieldfix-.zip` and `.sha256`. The script refuses version mismatches and test builds. -8. **Store assets (if UI changed):** `npm run build:e2e && node scripts/store-assets.mjs` regenerates - `store-assets/` (1280×800 screenshots plus popup/dashboard previews). +8. **Store assets (if UI changed):** `npm run store-assets` regenerates + `store-assets/` (five 1280×800 screenshots and the promo tiles). 9. **Tag and publish:** tag `v`, attach the zip and checksum to the release, and submit the zip to stores. ## Chrome Web Store submission notes @@ -45,7 +45,7 @@ ShieldFix is prepared for, but has not been through, Chrome Web Store review. Wh - **Data usage:** no data collected; certify compliance with the developer program policies only after reviewing them for the current submission. - **Privacy policy URL:** host [PRIVACY.md](../PRIVACY.md) at a public URL. -- Listing text: see [STORE_LISTING.md](STORE_LISTING.md). +- Field-by-field values and listing text: see [STORE_LISTING.md](STORE_LISTING.md). Store policies change; review the current Chrome Web Store program policies (in particular those on ad blockers and on modifying third-party sites) before each submission. Brave installs extensions from the Chrome Web Store. diff --git a/docs/STORE_LISTING.md b/docs/STORE_LISTING.md index cb6e061..526e7cb 100644 --- a/docs/STORE_LISTING.md +++ b/docs/STORE_LISTING.md @@ -1,33 +1,112 @@ -# Store listing (draft) +# Chrome Web Store submission sheet -**Name:** ShieldFix +Copy-paste values for every field of the Chrome Web Store developer dashboard. Brave installs extensions from the +Chrome Web Store, so this one listing serves Brave, Chrome and other Chromium browsers. -**Short description (≤ 132 characters):** -Detects anti-adblock warnings and offers reversible, user-approved fixes. Private by design: everything stays on your device. +## Before you start (one time) -**Category:** Privacy & Security +1. Sign in at with the Google account that will own the listing. +2. Accept the developer agreement and pay the one-time registration fee. +3. Turn on 2-Step Verification for the account (required to publish). +4. Fill in the **Account** tab (publisher name, contact email — verify it). -**Detailed description:** +## 1. Package -Websites increasingly react to ad and tracker blocking with full-screen “please disable your ad blocker” walls, banners -and broken players. ShieldFix helps you keep your protection on. +- **New item → upload** `release/shieldfix-.zip` (`npm run package`), or the zip attached to the + [GitHub release](https://github.com/Dszae/ShieldFix/releases/latest). +- Never upload `dist-e2e/` — it is a test build (the package script refuses to zip it). -- Recognises anti-adblock warnings and tells them apart from cookie banners, sign-in dialogs, subscription prompts and - ordinary pop-ups. -- Explains what it found and why, with a clear confidence level. -- Offers the least invasive fix: hide the warning, restore scrolling and remove blur — only when you approve it, and - always reversible with one click. Ads and trackers stay blocked. -- Remembers fixes for sites you choose, with rules you can review, edit, roll back, export or delete. -- Explains how to adjust Brave Shields for a single site when a cosmetic fix is not enough. ShieldFix never changes your - protection itself. -- Optional automatic detection for the sites you pick. +## 2. Store listing tab -Privacy: no data collection, no analytics, no network requests, no account. Everything runs and stays on your device. +| Field | Value | +| ------------------ | --------------------------------------------------------------- | +| Title | from the package: `ShieldFix` | +| Summary | from the package (manifest description, ≤ 132 characters) | +| Category | Privacy & Security | +| Language | English | +| Store icon | `public/icons/icon-128.png` | +| Screenshots (1–5) | `store-assets/screenshot-1.png` … `screenshot-5.png` (1280×800) | +| Small promo tile | `store-assets/promo-small.png` (440×280) | +| Marquee promo tile | `store-assets/promo-marquee.png` (1400×560) | +| Homepage URL | `https://github.com/Dszae/ShieldFix` | +| Support URL | `https://github.com/Dszae/ShieldFix/issues` | -ShieldFix does not bypass paywalls, logins or subscription requirements. +Regenerate the images with `npm run store-assets`. -**Screenshots (1280×800):** `store-assets/store-1-detect.png`, `store-assets/store-2-rules.png`, -`store-assets/store-3-privacy.png`. +**Description** (paste as-is): -**Icon:** `public/icons/icon-128.png`. Promotional imagery: `docs/images/banner.png`, `docs/images/before-after.png`, -`docs/images/demo.gif` (regenerate with `npm run media`). +```text +Websites increasingly answer ad and tracker blocking with full-screen "Ad blocker detected — please disable your ad blocker" walls, blurred articles and locked scrolling. ShieldFix lets you keep your protection on and still use the page. + +WHAT IT DOES +• Detects anti-adblock walls, banners and video-player warnings, with a clear confidence score. +• Tells them apart from cookie banners, sign-in dialogs, subscription prompts and ordinary pop-ups — those are never touched. +• Offers the least invasive fix: hide the warning, restore scrolling and remove the blur. You review exactly what changes before anything happens. +• Fully reversible: one click on Undo (or a page reload) restores the page exactly. Nothing is deleted, and ads and trackers stay blocked. +• "Always apply on this site" saves a local rule you can review, edit, roll back, export or delete. +• Optional automatic detection for the sites you choose, with a small in-page notice. +• Explains how to adjust Brave Shields for a single site when a cosmetic fix is not enough. ShieldFix never changes your protection itself. + +PRIVATE BY DESIGN +• No data collection, no analytics, no account, no network requests. +• No access to any website at install — ShieldFix only reads a page when you click its button, or on sites you choose to watch. +• Open source: https://github.com/Dszae/ShieldFix + +WHAT IT DOES NOT DO +ShieldFix does not bypass paywalls, logins, subscription requirements or DRM, and it cannot restore content a site never loaded. +``` + +## 3. Privacy practices tab + +**Single purpose description** + +```text +ShieldFix detects anti-adblock warnings on web pages (messages asking the user to disable their ad blocker) and, with the user's approval, hides them with a reversible cosmetic change. +``` + +**Permission justifications** + +| Permission | Justification (paste) | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `storage` | Stores the user's settings, per-site preferences, compatibility rules and an optional local history on the device. Nothing is transmitted. | +| `activeTab` | When the user clicks the toolbar button, ShieldFix scans the current tab for an anti-adblock warning and, if the user approves, hides it. No access to any other tab. | +| `scripting` | Injects the detection script into the active tab after the user clicks the toolbar button, and registers it for sites the user explicitly chose to watch. | +| Host permissions | Optional only, never requested at install. Requested at runtime when the user turns on "Watch this site" (that site only) or "Watch all sites", so warnings can be detected automatically as pages load. Revocable at any time. | + +**Are you using remote code?** No, I am not using remote code. + +**Data usage:** tick **none** of the data categories (ShieldFix collects no user data). Then tick all three +certifications (no selling to third parties; no use unrelated to the single purpose; no use for creditworthiness or +lending) — they are true for ShieldFix. + +**Privacy policy URL:** `https://github.com/Dszae/ShieldFix/blob/main/PRIVACY.md` + +## 4. Distribution tab + +- Payments: **Free** +- Visibility: **Public** +- Regions: **All regions** + +## 5. Test instructions (optional, helps reviewers) + +```text +1. Open any news page that shows an "Ad blocker detected" wall while an ad blocker or Brave Shields is active. +2. Click the ShieldFix toolbar button. The popup reports the warning and its confidence. +3. Click "Review suggested fix" to see the planned changes, then "Apply reversible fix". The wall is hidden and scrolling restored. +4. Click "Undo fix" — the page is restored exactly. +On pages without a warning (or with only a cookie banner or login form) ShieldFix reports "No issue detected" and offers no fix. +No account or login is required. +``` + +## 6. Submit + +Click **Submit for review**. Leave “publish automatically after review” on if you want it live as soon as it passes. + +Notes: + +- Extensions with broad (even optional) host permissions may receive an in-depth review, which can take longer. +- Answer reviewer questions using [PERMISSIONS.md](PERMISSIONS.md) and [PRIVACY.md](../PRIVACY.md). +- **Updates:** bump `version` in `package.json`, run `npm run package`, and upload the new zip on the item's + **Package** tab. The version must increase with every upload. +- **Microsoft Edge Add-ons** () accepts the same zip and + the same texts. diff --git a/eslint.config.js b/eslint.config.js index c5cb5a2..6f734d9 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -57,14 +57,12 @@ export default tseslint.config( rules: { 'no-restricted-properties': 'off', '@typescript-eslint/no-non-null-assertion': 'off' }, }, { - // Playwright fixtures call `use()`, which is not a React hook. files: ['tests/e2e/**/*.ts'], - rules: { 'react-hooks/rules-of-hooks': 'off' }, + rules: { 'react-hooks/rules-of-hooks': 'off', 'no-empty-pattern': 'off' }, }, { files: ['scripts/**/*.mjs', 'tests/e2e/**/*.mjs', '*.config.{js,ts}'], extends: [js.configs.recommended], - // Callbacks passed to Playwright's page.evaluate() run in the browser. languageOptions: { globals: { ...globals.node, ...globals.browser, ...globals.webextensions } }, }, ); diff --git a/package.json b/package.json index 580cb36..64e6493 100644 --- a/package.json +++ b/package.json @@ -40,10 +40,10 @@ "test:watch": "vitest", "test:e2e": "npm run build && npm run build:e2e && playwright test", "icons": "node scripts/generate-icons.mjs", - "assets": "npm run build:e2e && node scripts/store-assets.mjs", "package": "npm run build && node scripts/package.mjs", "check": "npm run typecheck && npm run lint && npm run format:check && npm run test && npm run build", - "media": "npm run build:e2e && node scripts/readme-media.mjs" + "media": "npm run build:e2e && node scripts/readme-media.mjs", + "store-assets": "npm run build:e2e && node scripts/store-assets.mjs" }, "dependencies": { "lucide-react": "1.74.0", diff --git a/playwright.config.ts b/playwright.config.ts index a7cdf17..f81aced 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,9 +1,5 @@ import { defineConfig } from '@playwright/test'; -/** - * Browser tests load the E2E build (dist-e2e/, created by `npm run build:e2e`) - * into Playwright's Chromium. Set BRAVE_PATH to also run the suite in Brave. - */ const projects: NonNullable[0]['projects']> = [ { name: 'chromium', use: { browserName: 'chromium' } }, ]; diff --git a/scripts/build.mjs b/scripts/build.mjs index 900763f..50e0bea 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -1,15 +1,4 @@ #!/usr/bin/env node -/** - * Builds the extension with Vite in three passes: - * 1. extension pages (popup, dashboard) — ES modules with shared chunks - * 2. background service worker — single ES module, no shared chunks - * 3. content script — single IIFE (content scripts cannot be modules) - * then writes manifest.json with the version from package.json. - * - * node scripts/build.mjs production build -> dist/ - * node scripts/build.mjs --e2e test build -> dist-e2e/ (adds host access to 127.0.0.1 only) - * node scripts/build.mjs --watch rebuild on change - */ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -93,9 +82,6 @@ async function writeManifest() { const manifest = JSON.parse(await readFile(resolve(root, 'src/manifest.json'), 'utf8')); manifest.version = pkg.version; if (e2e) { - // Test builds only: grant access to the local fixture server (and the reserved - // example.com domain, mapped to it when recording README media) so automated - // tests can inject without a toolbar click. Never used for release builds. manifest.name = 'ShieldFix (E2E test build)'; manifest.host_permissions = ['*://127.0.0.1/*', '*://*.example.com/*']; } diff --git a/scripts/generate-icons.mjs b/scripts/generate-icons.mjs index c653b07..d802555 100644 --- a/scripts/generate-icons.mjs +++ b/scripts/generate-icons.mjs @@ -1,9 +1,4 @@ #!/usr/bin/env node -/** - * Renders the ShieldFix icon (vector source below) to PNG at every size the - * manifest needs, using Playwright's Chromium. Run with `npm run icons`. - * Small sizes use a simplified, heavier mark so they stay legible. - */ import { mkdir } from 'node:fs/promises'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; diff --git a/scripts/package.mjs b/scripts/package.mjs index ea40e5d..4ab3c8c 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -1,8 +1,4 @@ #!/usr/bin/env node -/** - * Packages dist/ into release/shieldfix-.zip for distribution and prints - * its SHA-256. Refuses to package a test build. Pure Node (no zip dependency). - */ import { createHash } from 'node:crypto'; import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'; import { dirname, join, relative, resolve, sep } from 'node:path'; @@ -46,7 +42,6 @@ async function walk(dir) { return out; } -// Fixed timestamp (2025-01-01 00:00) so identical inputs produce identical archives. const DOS_TIME = 0; const DOS_DATE = ((2025 - 1980) << 9) | (1 << 5) | 1; @@ -61,8 +56,8 @@ for (const file of await walk(dist)) { const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); - local.writeUInt16LE(0x0800, 6); // UTF-8 names - local.writeUInt16LE(8, 8); // deflate + local.writeUInt16LE(0x0800, 6); + local.writeUInt16LE(8, 8); local.writeUInt16LE(DOS_TIME, 10); local.writeUInt16LE(DOS_DATE, 12); local.writeUInt32LE(crc, 14); diff --git a/scripts/readme-media.mjs b/scripts/readme-media.mjs index 53ee847..872663b 100644 --- a/scripts/readme-media.mjs +++ b/scripts/readme-media.mjs @@ -1,15 +1,4 @@ #!/usr/bin/env node -/** - * Generates the README media in docs/images/ from the real extension (E2E build): - * demo.gif popup flow: detect -> review -> apply -> scroll - * auto-detect.gif watched site: warning appears, in-page notice, one-click hide - * *.png popup, dashboard, before/after, banner (also used as social preview) - * - * Pages are the local test fixtures, served under the reserved example.com domain via - * Chromium's host resolver rules. Requires ffmpeg on PATH for the GIFs. - * - * npm run build:e2e && node scripts/readme-media.mjs - */ import { execFileSync, spawn } from 'node:child_process'; import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { dirname, join, resolve } from 'node:path'; @@ -23,7 +12,6 @@ const ext = resolve(root, 'dist-e2e'); const PORT = 4173; const site = (host, page) => `http://${host}.example.com:${PORT}/${page}.html`; -/* ----------------------------------------------------------------- server */ async function up() { try { return (await fetch(`http://127.0.0.1:${PORT}/health`)).ok; @@ -69,7 +57,6 @@ try { await send({ type: 'settings/update', patch: { theme: 'light' } }); const icon = `data:image/png;base64,${(await readFile(resolve(root, 'public/icons/icon-32.png'))).toString('base64')}`; - /* ------------------------------------------------- 1. demo.gif (popup) */ const page = await context.newPage(); await page.setViewportSize({ width: 1280, height: 751 }); const demoUrl = site('news', 'fullscreen-modal'); @@ -217,7 +204,6 @@ try { ); gif(['-f', 'concat', '-safe', '0', '-i', join(work, 'demo.txt')], join(out, 'demo.gif')); - // Before / after stills from the same page. await page.evaluate(() => window.scrollTo(0, 0)); await sleep(150); const after = await page.screenshot(); @@ -241,7 +227,6 @@ try { await sleep(200); await stage.screenshot({ path: join(out, 'before-after.png') }); - /* ------------------------------------- 2. auto-detect.gif (monitoring) */ await send({ type: 'site/update', hostname: 'recipes.example.com', patch: { monitor: true } }); await send({ type: 'monitoring/sync' }); const live = await context.newPage(); @@ -287,10 +272,8 @@ try { const liveVideo = live.video(); await live.close(); const webm = await liveVideo.path(); - // Skip the blank frames recorded before the first paint. gif(['-ss', '0.6', '-i', webm], join(out, 'auto-detect.gif')); - /* ----------------------------------------- 3. data for dashboard shots */ for (const [host, name] of [ ['tech', 'banner'], ['video', 'video-error'], @@ -312,7 +295,6 @@ try { } await p.close(); } - // A rule arriving through the real import path (validated, disabled, marked "Imported"). await send({ type: 'rules/import', payload: { @@ -329,7 +311,6 @@ try { }, }); - /* ----------------------------------------------------- 4. screenshots */ const popupShot = async (url, file, prepare) => { const p = await context.newPage(); await p.setViewportSize({ width: 368, height: 640 }); @@ -360,7 +341,6 @@ try { await p.getByRole('heading', { name: 'Diagnosis' }).waitFor(); }); await send({ type: 'settings/update', patch: { developerMode: false } }); - // The popup shots above undid the saved fix; re-enable its rule for the dashboard shots. const rules = await send({ type: 'rules/list' }); for (const r of rules.data.filter((x) => x.domain === 'news.example.com')) { await send({ type: 'rules/setEnabled', id: r.id, enabled: true }); @@ -380,7 +360,6 @@ try { await helper.screenshot({ path: join(out, `dashboard-${section}-${theme}.png`) }); } - /* ------------------------------------------------- 5. banner (1280x640) */ await send({ type: 'settings/update', patch: { theme: 'dark' } }); const darkPopup = await readFile(join(out, 'popup-dark.png')); const logo = (await readFile(resolve(root, 'public/icons/icon-128.png'))).toString('base64'); diff --git a/scripts/store-assets.mjs b/scripts/store-assets.mjs index 183a4ef..389195f 100644 --- a/scripts/store-assets.mjs +++ b/scripts/store-assets.mjs @@ -1,139 +1,195 @@ #!/usr/bin/env node -/** - * Captures store-listing screenshots (1280x800) and UI previews from the real - * extension (E2E build) using the local fixture pages. - * - * npm run build:e2e && node tests/e2e/server.mjs & (or let this script start it) - * node scripts/store-assets.mjs - */ import { spawn } from 'node:child_process'; -import { mkdir } from 'node:fs/promises'; -import { dirname, resolve } from 'node:path'; +import { mkdir, readFile, rm } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { chromium } from '@playwright/test'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const out = resolve(root, 'store-assets'); const ext = resolve(root, 'dist-e2e'); -const BASE = 'http://127.0.0.1:4173'; +const PORT = 4173; +const site = (host, page) => `http://${host}.example.com:${PORT}/${page}.html`; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); -async function serverUp() { +async function up() { try { - return (await fetch(`${BASE}/health`)).ok; + return (await fetch(`http://127.0.0.1:${PORT}/health`)).ok; } catch { return false; } } - let server = null; -if (!(await serverUp())) { +if (!(await up())) { server = spawn(process.execPath, [resolve(root, 'tests/e2e/server.mjs')], { stdio: 'ignore' }); - for (let i = 0; i < 50 && !(await serverUp()); i++) await new Promise((r) => setTimeout(r, 100)); + for (let i = 0; i < 50 && !(await up()); i++) await sleep(100); } +await rm(out, { recursive: true, force: true }); await mkdir(out, { recursive: true }); + const context = await chromium.launchPersistentContext('', { channel: 'chromium', headless: true, - viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1, - args: [`--disable-extensions-except=${ext}`, `--load-extension=${ext}`], + viewport: { width: 1280, height: 800 }, + args: [ + `--disable-extensions-except=${ext}`, + `--load-extension=${ext}`, + '--host-resolver-rules=MAP *.example.com 127.0.0.1', + ], }); +const b64 = (buf) => `data:image/png;base64,${buf.toString('base64')}`; +const icon32 = b64(await readFile(resolve(root, 'public/icons/icon-32.png'))); +const icon128 = b64(await readFile(resolve(root, 'public/icons/icon-128.png'))); + +function windowHtml({ host, path, page, popup, badge }) { + const badgeHtml = badge + ? `${badge}` + : ''; + return ` +
+ + ‹ › ⟳ + + 🔒${host}${path} + ${badgeHtml} +
+ + ${popup ? `` : ''} + `; +} + try { let [worker] = context.serviceWorkers(); worker ??= await context.waitForEvent('serviceworker'); const id = new URL(worker.url()).host; const extUrl = (p) => `chrome-extension://${id}/${p}`; - const helper = await context.newPage(); await helper.goto(extUrl('dashboard.html#/about')); const send = (m) => helper.evaluate((msg) => chrome.runtime.sendMessage(msg), m); + const tabIdOf = (url) => + helper.evaluate(async (u) => (await chrome.tabs.query({ url: u }))[0].id, url); await send({ type: 'onboarding/complete' }); + await send({ type: 'settings/update', patch: { theme: 'light' } }); + + const stage = await context.newPage(); + const render = async (html, file, size = { width: 1280, height: 800 }) => { + await stage.setViewportSize(size); + await stage.setContent(html); + await stage.evaluate(() => Promise.all(Array.from(document.images).map((i) => i.decode()))); + await stage.screenshot({ path: join(out, file) }); + }; const page = await context.newPage(); - await page.goto(`${BASE}/fullscreen-modal.html`); - const tabId = await helper.evaluate( - async (u) => (await chrome.tabs.query({ url: u }))[0].id, - `${BASE}/fullscreen-modal.html`, + await page.setViewportSize({ width: 1280, height: 751 }); + const url = site('news', 'fullscreen-modal'); + await page.goto(url); + const tabId = await tabIdOf(url); + const popup = await context.newPage(); + await popup.setViewportSize({ width: 368, height: 620 }); + const popupShot = async () => b64(await popup.locator('#root').screenshot()); + const win = { host: 'news.example.com', path: '/city-council-approves-new-park' }; + + await popup.goto(extUrl(`popup.html?tabId=${tabId}`)); + await popup.getByText('Action required').waitFor(); + await sleep(450); + const blocked = b64(await page.screenshot()); + await render( + windowHtml({ ...win, page: blocked, popup: await popupShot(), badge: '!' }), + 'screenshot-1.png', ); - // Popup previews in both themes. - for (const theme of ['light', 'dark']) { - await send({ type: 'settings/update', patch: { theme } }); - const popup = await context.newPage(); - await popup.setViewportSize({ width: 368, height: 640 }); - await popup.goto(extUrl(`popup.html?tabId=${tabId}`)); - await popup.getByText('Action required').waitFor(); - await popup.waitForTimeout(400); // let enter animations finish - await popup.screenshot({ path: resolve(out, `popup-detected-${theme}.png`), fullPage: true }); - await popup.getByRole('button', { name: 'Review suggested fix' }).click(); - await popup.getByRole('button', { name: 'Apply reversible fix' }).waitFor(); - await popup.waitForTimeout(300); - await popup.screenshot({ path: resolve(out, `popup-review-${theme}.png`), fullPage: true }); - await popup.getByRole('button', { name: 'Back' }).click(); - await popup.getByRole('button', { name: 'Diagnose' }).click(); - await popup.getByRole('heading', { name: 'Diagnosis' }).waitFor(); - await popup.waitForTimeout(300); - await popup.screenshot({ path: resolve(out, `popup-diagnosis-${theme}.png`), fullPage: true }); - await popup.close(); - } + await popup.getByRole('button', { name: 'Review suggested fix' }).click(); + await popup.getByRole('button', { name: 'Apply reversible fix' }).waitFor(); + await sleep(350); + await render( + windowHtml({ ...win, page: blocked, popup: await popupShot(), badge: '!' }), + 'screenshot-2.png', + ); + + await popup.getByRole('button', { name: 'Apply reversible fix' }).click(); + await popup.getByLabel('Page status').getByText('Fix applied', { exact: true }).waitFor(); + await sleep(450); + await render( + windowHtml({ + ...win, + page: b64(await page.screenshot()), + popup: await popupShot(), + badge: '✓', + }), + 'screenshot-3.png', + ); + + await send({ type: 'site/update', hostname: 'recipes.example.com', patch: { monitor: true } }); + await send({ type: 'monitoring/sync' }); + const live = await context.newPage(); + await live.setViewportSize({ width: 1280, height: 751 }); + await live.goto(site('recipes', 'dynamic-overlay')); + await live + .locator('shieldfix-notice') + .getByRole('button', { name: 'Hide warning' }) + .waitFor({ timeout: 15_000 }); + await sleep(500); + await render( + windowHtml({ + host: 'recipes.example.com', + path: '/weeknight-lemon-pasta', + page: b64(await live.screenshot()), + badge: '!', + }), + 'screenshot-4.png', + ); - // Dashboard previews. - await send({ - type: 'rules/upsert', - rule: { - domain: 'news.example.com', - selector: '#adb-wall', - enabled: true, - description: 'Saved from a fix you approved.', - }, - }); await send({ - type: 'rules/upsert', - rule: { - domain: 'video.example.org', - selector: '.adblock-overlay', - ruleType: 'cosmetic-overlay', - enabled: false, + type: 'rules/import', + payload: { + format: 'shieldfix-rules', + formatVersion: 1, + rules: [ + { + domain: 'video.example.com', + selector: '.player-error', + ruleType: 'cosmetic-hide', + description: "Hides the player's ad-blocker message.", + }, + ], }, }); - for (const theme of ['light', 'dark']) { - await send({ type: 'settings/update', patch: { theme } }); - for (const section of ['overview', 'rules', 'privacy']) { - await helper.goto(extUrl(`dashboard.html#/${section}`)); - await helper.waitForTimeout(400); - await helper.screenshot({ path: resolve(out, `dashboard-${section}-${theme}.png`) }); - } - } + await helper.setViewportSize({ width: 1280, height: 800 }); + await helper.goto(extUrl('dashboard.html#/rules')); + await sleep(500); + await helper.screenshot({ path: join(out, 'screenshot-5.png') }); - // Store screenshot: the page with the popup composited at the toolbar position. - await send({ type: 'settings/update', patch: { theme: 'light' } }); - const popup = await context.newPage(); - await popup.setViewportSize({ width: 368, height: 560 }); + await send({ type: 'settings/update', patch: { theme: 'dark' } }); await popup.goto(extUrl(`popup.html?tabId=${tabId}`)); - await popup.getByText('Action required').waitFor(); - await popup.waitForTimeout(400); - const shot = (await popup.screenshot({ fullPage: true })).toString('base64'); - await page.bringToFront(); - await page.evaluate((b64) => { - const img = document.createElement('img'); - img.src = `data:image/png;base64,${b64}`; - img.setAttribute( - 'style', - 'position:fixed;top:12px;right:16px;z-index:2147483647;border-radius:12px;box-shadow:0 16px 48px rgba(0,0,0,.35);width:368px', - ); - document.documentElement.appendChild(img); - }, shot); - await page.waitForTimeout(300); - await page.screenshot({ path: resolve(out, 'store-1-detect.png') }); - await helper.goto(extUrl('dashboard.html#/rules')); - await helper.waitForTimeout(400); - await helper.screenshot({ path: resolve(out, 'store-2-rules.png') }); - await helper.goto(extUrl('dashboard.html#/privacy')); - await helper.waitForTimeout(400); - await helper.screenshot({ path: resolve(out, 'store-3-privacy.png') }); - console.log(`Screenshots written to ${out}`); + await popup.getByLabel('Page status').getByText('Fix applied', { exact: true }).waitFor(); + await sleep(450); + const darkPopup = await popupShot(); + const grid = + 'background-image:linear-gradient(rgba(94,234,212,.06) 1px,transparent 1px),linear-gradient(90deg,rgba(94,234,212,.06) 1px,transparent 1px);background-size:40px 40px'; + await render( + ` +
ShieldFix
+

Fix “Ad blocker detected” walls.
Keep your Shields up.

+ `, + 'promo-small.png', + { width: 440, height: 280 }, + ); + await render( + ` +
+
ShieldFix
+

Fix “Ad blocker detected” walls
without turning your protection off.

+

One reversible click · 100% local · No tracking

+
+ + `, + 'promo-marquee.png', + { width: 1400, height: 560 }, + ); + console.log(`Store assets written to ${out}`); } finally { await context.close(); server?.kill(); diff --git a/src/background/gateways.ts b/src/background/gateways.ts index c6b2ae3..fba899c 100644 --- a/src/background/gateways.ts +++ b/src/background/gateways.ts @@ -6,11 +6,6 @@ import { type ToContentResponseMap, } from '../shared/messages'; -/** - * Thin wrappers around browser APIs. The router depends on these interfaces, so - * its logic can be tested without a browser. - */ - export interface TabsGateway { getUrl(tabId: number): Promise; send( @@ -132,13 +127,12 @@ const BADGE = { export const chromeBadge: BadgeGateway = { async set(tabId, state) { const b = BADGE[state]; - try { - await chrome.action.setBadgeText({ tabId, text: b.text }); - if (b.text) await chrome.action.setBadgeBackgroundColor({ tabId, color: b.color }); - await chrome.action.setTitle({ tabId, title: b.title }); - } catch { - // Tab closed meanwhile. + const ignoreClosedTab = () => undefined; + await chrome.action.setBadgeText({ tabId, text: b.text }).catch(ignoreClosedTab); + if (b.text) { + await chrome.action.setBadgeBackgroundColor({ tabId, color: b.color }).catch(ignoreClosedTab); } + await chrome.action.setTitle({ tabId, title: b.title }).catch(ignoreClosedTab); }, }; diff --git a/src/background/index.ts b/src/background/index.ts index 2919730..e487b1e 100644 --- a/src/background/index.ts +++ b/src/background/index.ts @@ -10,11 +10,6 @@ import { chromeTabs, } from './gateways'; -/** - * Service worker entry point. All listeners are registered synchronously at the - * top level, as Manifest V3 requires, so events wake the worker reliably. - */ - const repo = new Repository(chromeArea(chrome.storage.local)); const router = createRouter({ extensionId: chrome.runtime.id, @@ -58,7 +53,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { .handle(message, sender) .then(sendResponse) .catch((err) => sendResponse({ ok: false, error: { code: 'internal', message: String(err) } })); - return true; // async response + return true; }); chrome.permissions.onAdded.addListener((permissions) => { diff --git a/src/background/router.ts b/src/background/router.ts index 45e39ac..ae27623 100644 --- a/src/background/router.ts +++ b/src/background/router.ts @@ -39,7 +39,7 @@ import type { export interface RouterDeps { extensionId: string; - extensionOrigin: string; // e.g. chrome-extension:/// + extensionOrigin: string; version: string; repo: Repository; tabsState: TabStateStore; @@ -62,7 +62,6 @@ const BRAVE_PAGES: Record<'shields' | 'content-filtering', string[]> = { 'content-filtering': ['brave://settings/shields/filters', 'brave://adblock'], }; -/** "*://example.com/*" -> "example.com"; wildcard-host patterns return null. */ export function hostFromPattern(pattern: string): string | null { const m = pattern.match(/^(?:\*|https?):\/\/([^/*]+)\/\*$/); if (!m?.[1]) return null; @@ -73,8 +72,6 @@ export function hostFromPattern(pattern: string): string | null { export function createRouter(deps: RouterDeps) { const { repo } = deps; - /* ------------------------------ monitoring ------------------------------ */ - async function computeMonitoring(): Promise< Pick & { matches: string[]; @@ -139,8 +136,6 @@ export function createRouter(deps: RouterDeps) { return state.monitoredHosts.some((h) => hostMatchesDomain(hostname, h)); } - /* -------------------------------- tabs ---------------------------------- */ - async function tabHostname(tabId: number): Promise { const info = describeUrl(await deps.tabs.getUrl(tabId)); if (!info.supported || !info.hostname) { @@ -150,12 +145,11 @@ export function createRouter(deps: RouterDeps) { } async function ensureContent(tabId: number): Promise { - try { - await deps.tabs.send(tabId, { type: 'cs/ping' }); - return; - } catch { - // Not injected yet. - } + const alreadyInjected = await deps.tabs.send(tabId, { type: 'cs/ping' }).then( + () => true, + () => false, + ); + if (alreadyInjected) return; await deps.tabs.inject(tabId); await deps.tabs.send(tabId, { type: 'cs/ping' }); } @@ -168,7 +162,6 @@ export function createRouter(deps: RouterDeps) { else await deps.badge.set(tabId, 'clear'); } - /** Persist report, badge, site summary and (de-duplicated) history. */ async function ingestReport( tabId: number, report: DetectionReport, @@ -214,15 +207,12 @@ export function createRouter(deps: RouterDeps) { }); await deps.tabsState.markRecorded(tabId, { recordedLevel: report.level }); } else if (report.level === 'none') { - // Keep an existing site summary current without creating new records. if (await repo.getSite(report.hostname)) { await repo.recordScan(report.hostname, { level: 'none', confidence: report.confidence }); } } } - /* --------------------------- UI request handlers ------------------------- */ - async function handleUi(req: UiRequest): Promise { switch (req.type) { case 'tab/state': { @@ -405,8 +395,6 @@ export function createRouter(deps: RouterDeps) { } } - /* ------------------------ content request handlers ----------------------- */ - async function handleContent( req: ContentRequest, tabId: number, @@ -455,8 +443,6 @@ export function createRouter(deps: RouterDeps) { } } - /* -------------------------------- entry --------------------------------- */ - async function handle(message: unknown, sender: Sender): Promise> { try { if (sender.id !== deps.extensionId) return fail('forbidden', 'Unknown sender.'); @@ -482,11 +468,6 @@ export function createRouter(deps: RouterDeps) { } } - /** - * Monitoring follows the permissions the user actually granted (through - * ShieldFix's UI or the browser's site-access menu), so a closed popup or a - * revoked permission can never leave the stored preference out of sync. - */ async function onPermissionsChanged(change: { added?: string[]; removed?: string[]; diff --git a/src/background/tabState.ts b/src/background/tabState.ts index ea7a09e..45e4015 100644 --- a/src/background/tabState.ts +++ b/src/background/tabState.ts @@ -9,16 +9,11 @@ import type { StorageArea } from '../storage/area'; const TabRecordSchema = z.object({ hostname: z.string(), report: DetectionReportSchema.nullable(), - /** Last level written to history for this page load (de-duplicates history). */ recordedLevel: DetectionLevelSchema.nullable(), recordedFix: z.boolean(), }); export type TabRecord = z.infer; -/** - * Per-tab state kept in chrome.storage.session (memory only, cleared when the - * browser closes) so it survives service-worker restarts. - */ export class TabStateStore { constructor(private readonly area: StorageArea) {} diff --git a/src/compat/rules.ts b/src/compat/rules.ts index 796ed66..52da8cf 100644 --- a/src/compat/rules.ts +++ b/src/compat/rules.ts @@ -11,14 +11,6 @@ import { } from '../shared/schemas'; import type { ContentRuleConfig } from '../shared/messages'; -/** - * Compatibility rule engine (pure functions; persistence lives in the repository). - * - * Rules are declarative: a domain, a validated CSS selector and a cosmetic rule - * type. They never contain code. Imported and community rules always arrive - * disabled and must be enabled by the user. - */ - export function newRuleId(): string { const bytes = new Uint8Array(12); crypto.getRandomValues(bytes); @@ -47,7 +39,6 @@ export function createRule(input: RuleInput, source: RuleSource, now: number): R }); } -/** Produces the next version of a rule. The caller archives the previous one. */ export function reviseRule(existing: Rule, input: RuleInput, now: number): Rule { const parsed = RuleInputSchema.parse(input); return RuleSchema.parse({ @@ -84,7 +75,6 @@ export interface ParsedImport { rejected: { index: number; reason: string }[]; } -/** Validate an exported rules file. Every rule is re-validated individually. */ export function parseRulesImport(payload: unknown): ParsedImport { const envelope = RulesExportSchema.safeParse(payload); if (!envelope.success) { @@ -115,7 +105,6 @@ export function parseRulesImport(payload: unknown): ParsedImport { rejected.push({ index, reason: 'Rule is not an object.' }); return; } - // Imported rules never carry their enabled state or id across. const result = RuleInputSchema.safeParse({ ...candidate.data, enabled: false }); if (result.success) accepted.push(result.data); else rejected.push({ index, reason: result.error.issues.map((i) => i.message).join('; ') }); diff --git a/src/compat/selectorSafety.ts b/src/compat/selectorSafety.ts index e331141..acc059f 100644 --- a/src/compat/selectorSafety.ts +++ b/src/compat/selectorSafety.ts @@ -1,13 +1,3 @@ -/** - * Static safety checks for CSS selectors stored in compatibility rules. - * - * CSS selectors cannot execute code, but an overly broad or expensive selector could - * hide important content or slow pages down. Rules must therefore target a specific, - * identifiable element (class, id or attribute), use a restricted character set, and - * avoid costly or structural pseudo-classes. Syntax validity is checked separately - * against a real DOM where one is available (see `isSyntacticallyValidSelector`). - */ - export type SelectorCheck = { ok: true } | { ok: false; reason: string }; export const MAX_SELECTOR_LENGTH = 200; @@ -49,7 +39,6 @@ function splitTopLevel(selector: string, separator: string): string[] { return parts; } -/** The last compound selector of a complex selector (after the final combinator). */ function lastCompound(part: string): string { const pieces = splitTopLevel(part.replace(/\s*([>+~])\s*/g, ' ').trim(), ' ').filter(Boolean); return pieces[pieces.length - 1] ?? ''; @@ -107,7 +96,6 @@ export function checkSelectorSafety(input: string): SelectorCheck { return { ok: true }; } -/** Syntax check using the DOM, when one exists (UI pages and content scripts). */ export function isSyntacticallyValidSelector(selector: string, doc?: Document): boolean { const d = doc ?? (typeof document !== 'undefined' ? document : undefined); if (!d) return true; diff --git a/src/content/controller.ts b/src/content/controller.ts index 4a52602..a39f75e 100644 --- a/src/content/controller.ts +++ b/src/content/controller.ts @@ -26,7 +26,6 @@ import { stableSelector } from '../fixer/selector'; import { Notice } from './notice'; import { buildReport, EMPTY_FIX, toSummary } from './report'; -/** Messages the controller sends to the background service worker. */ export interface Bridge { getConfig(): Promise; report(report: DetectionReport): void; @@ -58,7 +57,6 @@ export class ContentController { private readonly lateInserted = new WeakSet(); private readonly notice: Notice; - // Monitoring state private observer: MutationObserver | null = null; private monitoring = false; private deadline = 0; @@ -73,7 +71,6 @@ export class ContentController { constructor( private readonly win: Window & typeof globalThis, private readonly bridge: Bridge, - /** Layout access; injectable so the controller can be tested without a layout engine. */ private readonly probeFactory: ( win: Window & typeof globalThis, ) => LayoutProbe = createDomProbe, @@ -94,14 +91,9 @@ export class ContentController { return normalizeHostname(this.win.location.hostname); } - /* ------------------------------- config ------------------------------- */ - async refreshConfig(): Promise { - try { - this.config = await this.bridge.getConfig(); - } catch { - // Keep the previous config if the background is momentarily unavailable. - } + const keepPreviousConfig = () => this.config; + this.config = await this.bridge.getConfig().catch(keepPreviousConfig); return this.config; } @@ -109,8 +101,6 @@ export class ContentController { return this.monitoring; } - /* -------------------------------- scan -------------------------------- */ - private idFor = (el: Element): string => { let id = this.ids.get(el); if (!id) { @@ -134,7 +124,6 @@ export class ContentController { }; } - /** Runs detection synchronously against the current DOM. */ private runScan(trigger: ScanTrigger): DetectionReport { const started = performance.now(); const probe = this.probeFactory(this.win); @@ -186,12 +175,9 @@ export class ContentController { ); } - /** Auto-apply remembered fixes and show the in-page notice when appropriate. */ private async afterScan(report: DetectionReport, trigger: ScanTrigger): Promise { const config = this.config; - // A fix is active. If the page inserted a *new* warning, re-apply under the - // same approval, a bounded number of times. if (this.fix) { const fixedEl = this.elementFor(this.fix.candidateId); const fresh = this.lastScan?.candidates.find( @@ -246,8 +232,6 @@ export class ContentController { return this.elements.get(id)?.deref() ?? null; } - /* -------------------------------- fixes ------------------------------- */ - previewFix(candidateId: string): ContentFixPreview { const candidate = this.freshCandidate(candidateId); const actions = planFix(candidate, this.lastScan!.page, this.win.document); @@ -258,7 +242,6 @@ export class ContentController { }; } - /** Re-scan and return the candidate only if it is still present and fixable. */ private freshCandidate(candidateId: string): CandidateResult { const el = this.elementFor(candidateId); if (!el || !el.isConnected) { @@ -395,9 +378,6 @@ export class ContentController { } } - /* ------------------------------ monitoring ----------------------------- */ - - /** Start automatic detection for a monitored site (called once after config). */ startMonitoring(): void { if (this.monitoring) return; this.monitoring = true; @@ -456,7 +436,6 @@ export class ContentController { return; } if (this.win.location.href !== this.lastHref) { - // Single-page navigation: treat as a new page view. this.lastHref = this.win.location.href; this.noticeDismissed = false; this.mutationScans = 0; @@ -485,11 +464,10 @@ export class ContentController { }, LIMITS.mutationDebounceMs); } - /** Cheap pre-filter: only run a full scan if a changed element looks relevant. */ private isRelevant(el: Element): boolean { if (!el.isConnected) return false; const doc = this.win.document; - if (el === doc.documentElement || el === doc.body) return true; // scroll locks + if (el === doc.documentElement || el === doc.body) return true; try { if (el.matches(SEED_SELECTOR) || el.querySelector(SEED_SELECTOR)) return true; } catch { @@ -530,7 +508,6 @@ export class ContentController { if (changed) this.bridge.report(report); } - /** Stop all observation and undo any active fix (used on teardown). */ destroy(): void { this.disconnect(); this.win.document.removeEventListener('visibilitychange', this.onVisibility); diff --git a/src/content/index.ts b/src/content/index.ts index 047089c..57e1a34 100644 --- a/src/content/index.ts +++ b/src/content/index.ts @@ -8,14 +8,6 @@ import type { import { ContentController, type Bridge } from './controller'; import { parseToContent } from './validate'; -/** - * Content script entry. Runs in the isolated world of top-level http(s) pages: - * - injected on demand (activeTab) when the user opens the popup, or - * - registered at document_start for sites the user chose to monitor. - * It never communicates with page scripts and accepts messages only from the - * ShieldFix extension itself. - */ - declare global { var __shieldfixController: ContentController | undefined; } @@ -63,12 +55,11 @@ async function handle(controller: ContentController, msg: ToContent): Promise (interacting = true)); box.addEventListener('mouseleave', () => (interacting = false)); diff --git a/src/content/report.ts b/src/content/report.ts index f1a2edc..d3aad85 100644 --- a/src/content/report.ts +++ b/src/content/report.ts @@ -48,7 +48,6 @@ export interface BuildReportInput { idFor: (el: Element) => string; resources: BlockedResources; fix: FixState; - /** Summary of the candidate a fix is currently hiding (it is no longer visible to scans). */ fixedCandidate: CandidateSummary | null; monitoring: boolean; now: number; diff --git a/src/content/validate.ts b/src/content/validate.ts index 96911e3..9d13a22 100644 --- a/src/content/validate.ts +++ b/src/content/validate.ts @@ -1,12 +1,6 @@ import type { ToContent } from '../shared/messages'; import type { ScanTrigger } from '../shared/schemas'; -/** - * Dependency-free validation of messages sent to the content script. Mirrors - * `ToContentSchema` in shared/messages.ts (kept in sync by unit tests) so the - * content script does not need to bundle Zod. - */ - const TRIGGERS: ReadonlySet = new Set(['popup', 'manual', 'monitor', 'mutation']); const CANDIDATE_ID = /^c\d{1,6}$/; diff --git a/src/detection/adHosts.ts b/src/detection/adHosts.ts index c079c62..f41b926 100644 --- a/src/detection/adHosts.ts +++ b/src/detection/adHosts.ts @@ -1,8 +1,3 @@ -/** - * A small list of widely known advertising / analytics domains, used only to - * label failed resource loads in diagnostics ("expected: ad or tracking resource"). - * It is not a blocklist and ShieldFix never blocks or unblocks anything with it. - */ const AD_TRACKING_DOMAINS = [ 'doubleclick.net', 'googlesyndication.com', diff --git a/src/detection/engine.ts b/src/detection/engine.ts index 3af15c6..88d4a06 100644 --- a/src/detection/engine.ts +++ b/src/detection/engine.ts @@ -61,10 +61,8 @@ export interface ScanResult { export interface ScanOptions { doc: Document; probe: LayoutProbe; - /** Elements to ignore entirely (ShieldFix's own in-page UI). */ ignore?: (el: Element) => boolean; rules?: ContentRuleConfig[]; - /** Elements inserted after the initial page load. */ lateInserted?: WeakSet; } @@ -84,10 +82,6 @@ export function isAntiAdblock(c: Classification): boolean { return c.startsWith('anti-adblock'); } -/* ------------------------------------------------------------------ */ -/* Seed collection */ -/* ------------------------------------------------------------------ */ - function addSeed(seeds: Map, el: Element, patch?: Partial): void { let info = seeds.get(el); if (!info) { @@ -108,7 +102,6 @@ function collectSeeds( const body = doc.body; if (!body) return seeds; - // 1. Text mentions (bounded walk over text nodes). const walker = doc.createTreeWalker(body, NodeFilter.SHOW_TEXT); let chars = 0; let textSeeds = 0; @@ -125,15 +118,12 @@ function collectSeeds( } } - // 2. Anti-adblock class / id patterns. const attrMatches = Array.from(doc.querySelectorAll(ATTRIBUTE_SEED_SELECTOR)).slice(0, 100); for (const el of attrMatches) if (!ignore(el)) addSeed(seeds, el); - // 3. Dialogs, so ordinary dialogs can be recognised and excluded. const dialogs = Array.from(doc.querySelectorAll(DIALOG_SEED_SELECTOR)).slice(0, 50); for (const el of dialogs) if (!ignore(el)) addSeed(seeds, el); - // 4. Whatever sits on top of the viewport at a few sample points. const { width: vw, height: vh } = probe.viewport(); const points: [number, number][] = [ [0.5, 0.5], @@ -148,14 +138,12 @@ function collectSeeds( if (top) addSeed(seeds, top); } - // 5. Vendor signatures. for (const v of VENDOR_SIGNATURES) { for (const el of Array.from(doc.querySelectorAll(v.selector)).slice(0, 3)) { if (!ignore(el)) addSeed(seeds, el, { vendor: v.id }); } } - // 6. User-enabled compatibility rules for this site. for (const rule of opts.rules ?? []) { let matches: Element[]; try { @@ -173,10 +161,6 @@ function collectSeeds( return seeds; } -/* ------------------------------------------------------------------ */ -/* Root resolution */ -/* ------------------------------------------------------------------ */ - function isDialogLike(el: Element): boolean { return ( el.tagName === 'DIALOG' || @@ -186,8 +170,6 @@ function isDialogLike(el: Element): boolean { ); } -// Per-scan memo: ancestors are shared by many seeds, and measuring a large -// subtree is O(n), so each element is measured at most once per scan. let textLengthMemo = new Map(); let shellMemo = new Map(); @@ -200,7 +182,6 @@ function textLength(el: Element): number { return n; } -/** An element that hosts the page's main content (app shells, layout wrappers). */ function isContentShell(el: Element): boolean { let shell = shellMemo.get(el); if (shell === undefined) { @@ -218,7 +199,7 @@ function resolveRoot(seed: Element, opts: ScanOptions): Element | null { const { doc, probe } = opts; const html = doc.documentElement; const body = doc.body; - const positioned: Element[] = []; // innermost first + const positioned: Element[] = []; let dialog: Element | null = null; let largeAbsolute: Element | null = null; const { width: vw, height: vh } = probe.viewport(); @@ -235,7 +216,6 @@ function resolveRoot(seed: Element, opts: ScanOptions): Element | null { el = el.parentElement; } - // Prefer the outermost fixed/sticky ancestor that is not an app shell. for (let i = positioned.length - 1; i >= 0; i--) { const candidate = positioned[i]!; if (isRendered(candidate, probe) && !isContentShell(candidate)) return candidate; @@ -243,7 +223,6 @@ function resolveRoot(seed: Element, opts: ScanOptions): Element | null { if (largeAbsolute && !isContentShell(largeAbsolute)) return largeAbsolute; if (dialog && !isContentShell(dialog)) return dialog; - // Inline: grow from the seed to a small containing block. let root: Element = seed; for (let depth = 0; depth < 4; depth++) { const parent: Element | null = root.parentElement; @@ -254,10 +233,6 @@ function resolveRoot(seed: Element, opts: ScanOptions): Element | null { return root === body || root === html ? null : root; } -/* ------------------------------------------------------------------ */ -/* Scoring */ -/* ------------------------------------------------------------------ */ - function geometryOf(el: Element, probe: LayoutProbe): { geometry: Geometry; z: number } { const s = probe.style(el); const pos = s.position; @@ -340,7 +315,7 @@ function findBackdrops(root: Element, opts: ScanOptions): Element[] { const opacity = Number.parseFloat(s.opacity || '1'); const hasBackdropFilter = !!s.backdropFilter && s.backdropFilter !== 'none'; if (alpha < 0.05 && !hasBackdropFilter) continue; - if (alpha >= 0.99 && opacity >= 0.99 && !hasBackdropFilter) continue; // opaque: a page layer, not a scrim + if (alpha >= 0.99 && opacity >= 0.99 && !hasBackdropFilter) continue; result.push(el); } return result; @@ -363,7 +338,6 @@ function scoreRoot(root: Element, ctx: ScoreContext): CandidateResult { const { geometry, z } = geometryOf(root, probe); const isOverlay = geometry === 'fullscreen' || geometry === 'modal'; - // Positive evidence ----------------------------------------------------- const strong = STRONG_PHRASES.filter((p) => p.re.test(text)); if (strong.length > 0) { add('phrase-strong', strong[0]!.label, 50); @@ -397,13 +371,11 @@ function scoreRoot(root: Element, ctx: ScoreContext): CandidateResult { add('late-insert', 'Appeared after the page loaded', 5); } - // Media players often show the warning in place of the video. const media = root.querySelector('video, audio, iframe, canvas, object, embed'); if (media && strong.length > 0) add('media-player', 'Shown in a media player', 10); const failedVideo = Array.from(root.querySelectorAll('video')).some((v) => v.error !== null); if (failedVideo) add('video-error', 'The video failed to load', 10); - // Negative evidence and vetoes ------------------------------------------ if (NEGATED_RE.test(text)) add('negated', 'Says ad blockers are fine', -40); const consent = CONSENT_RE.test(text); @@ -442,7 +414,6 @@ function scoreRoot(root: Element, ctx: ScoreContext): CandidateResult { vetoes.push({ id: 'main-content', label: 'Contains the main page content' }); } if (fullLength > 1500) add('long-text', 'Long text (likely an article)', -30); - // Prose about ad blockers inside an article is not a warning; a player widget is not prose. if (geometry === 'inline' && !media && root.closest('article, main, [role="main"]')) { add('in-article', 'Part of the article text', -30); } @@ -455,7 +426,6 @@ function scoreRoot(root: Element, ctx: ScoreContext): CandidateResult { ), ); - // User-enabled rule -------------------------------------------------------- let ruleId: string | null = null; const ruleConfig = (ctx.opts.rules ?? []).find((r) => ctx.seed.ruleIds.has(r.id)); if (ruleConfig) { @@ -465,7 +435,6 @@ function scoreRoot(root: Element, ctx: ScoreContext): CandidateResult { confidence = Math.max(confidence, Math.min(100, ruleConfig.confidence)); } - // Classification ------------------------------------------------------------- const evidence = anyEvidence || !!ruleId; let classification: Classification; if (evidence && confidence >= THRESHOLDS.possible && !subscription && !ageGate) { @@ -485,7 +454,6 @@ function scoreRoot(root: Element, ctx: ScoreContext): CandidateResult { const antiAdblock = isAntiAdblock(classification); if (!antiAdblock) confidence = Math.min(confidence, THRESHOLDS.possible - 1); - // Fixability ------------------------------------------------------------------ let fixBlockedReason: string | null = null; if (!antiAdblock) fixBlockedReason = 'Not identified as an anti-adblock warning.'; else if (vetoes.length > 0) @@ -519,10 +487,6 @@ function isLate(el: Element, late: WeakSet): boolean { return false; } -/* ------------------------------------------------------------------ */ -/* Page state */ -/* ------------------------------------------------------------------ */ - export function readPageState(opts: ScanOptions): PageState { const { doc, probe } = opts; const ignore = opts.ignore ?? (() => false); @@ -568,10 +532,6 @@ export function readPageState(opts: ScanOptions): PageState { return { scrollLocked, blurred, inert, pointerBlocked, videoErrors }; } -/* ------------------------------------------------------------------ */ -/* Entry point */ -/* ------------------------------------------------------------------ */ - export function scanDocument(opts: ScanOptions): ScanResult { textLengthMemo = new Map(); shellMemo = new Map(); @@ -602,7 +562,6 @@ function runScan(opts: ScanOptions): ScanResult { } } - // Merge nested roots into their outermost container. const rootList = Array.from(roots.keys()); for (const inner of rootList) { const outer = rootList.find((o) => o !== inner && roots.has(o) && o.contains(inner)); @@ -619,7 +578,6 @@ function runScan(opts: ScanOptions): ScanResult { .slice(0, 60) .map(([root, seed]) => scoreRoot(root, { opts, page, seed })); - // A warning's own backdrop is part of that warning, not a separate dialog. const warningBackdrops = new Set( scored.filter((c) => isAntiAdblock(c.classification)).flatMap((c) => c.backdrops), ); diff --git a/src/detection/layout.ts b/src/detection/layout.ts index 2f040b1..cdd7052 100644 --- a/src/detection/layout.ts +++ b/src/detection/layout.ts @@ -1,9 +1,3 @@ -/** - * Layout probe: the only place the detection engine touches layout APIs. - * Abstracting it keeps the engine unit-testable in DOM environments that do not - * perform layout, and lets each scan cache computed styles. - */ - export interface Rect { x: number; y: number; @@ -16,9 +10,7 @@ export interface LayoutProbe { documentHeight(): number; rect(el: Element): Rect; style(el: Element): CSSStyleDeclaration; - /** Visible text of an element, truncated to `max` characters. */ text(el: Element, max: number): string; - /** Elements at a viewport point, topmost first. Empty when unsupported. */ elementsAtPoint(x: number, y: number): Element[]; } @@ -49,8 +41,6 @@ export function createDomProbe(win: Window & typeof globalThis): LayoutProbe { }, text(el, max) { const raw = el.textContent ?? ''; - // innerText forces layout and is expensive on large subtrees; only use it - // for reasonably sized elements, where it correctly excludes hidden text. if (raw.length <= 20_000 && 'innerText' in el) { return ((el as HTMLElement).innerText ?? raw).slice(0, max); } @@ -87,7 +77,6 @@ export function zIndexOf(el: Element, probe: LayoutProbe): number { return Number.isFinite(z) ? z : 0; } -/** Parse the alpha channel of a computed `rgb()/rgba()` colour. */ export function colorAlpha(color: string): number { const m = color.match(/rgba?\(([^)]+)\)/); if (!m?.[1]) return color === 'transparent' ? 0 : 1; diff --git a/src/detection/resources.ts b/src/detection/resources.ts index 47d26f0..0050b0a 100644 --- a/src/detection/resources.ts +++ b/src/detection/resources.ts @@ -2,20 +2,6 @@ import { isSameSite, normalizeHostname } from '../shared/domain'; import type { BlockedResources, ResourceCategory } from '../shared/schemas'; import { isAdTrackingHost } from './adHosts'; -/** - * Failed / blocked resource analysis. - * - * Browsers do not expose to extensions *why* a request failed, so ShieldFix uses - * two evidence sources: - * - `error-events`: when the content script runs at document_start on monitored - * sites, it records `error` events for scripts, stylesheets and images. - * - `heuristic`: for on-demand scans, it compares script elements with the - * Resource Timing buffer (blocked requests have no timing entry) and checks - * images that finished without decoding. This is approximate and is labelled - * as such in the UI. - * Only hostnames are reported; URLs and paths are discarded. - */ - export type ResourceKind = 'script' | 'stylesheet' | 'image' | 'other'; export interface FailedResource { @@ -89,7 +75,6 @@ function describeFailedElement(el: Element, base: string): FailedResource | null const RESOURCE_TIMING_DEFAULT_BUFFER = 250; -/** Heuristic for pages scanned after load (no error events captured). */ export function heuristicFailures(win: Window): { failures: FailedResource[]; reliable: boolean } { const doc = win.document; const base = win.location.href; @@ -105,7 +90,7 @@ export function heuristicFailures(win: Window): { failures: FailedResource[]; re ); for (const script of scripts) { const type = (script.getAttribute('type') ?? '').trim().toLowerCase(); - if (!EXECUTABLE_SCRIPT_TYPES.has(type)) continue; // consent-gated or data scripts + if (!EXECUTABLE_SCRIPT_TYPES.has(type)) continue; let abs: string; try { abs = new URL(script.src, base).href; diff --git a/src/detection/signatures.ts b/src/detection/signatures.ts index b2fe3ac..9ba5e45 100644 --- a/src/detection/signatures.ts +++ b/src/detection/signatures.ts @@ -1,11 +1,3 @@ -/** - * Detection signatures. Text is normalised (lower case, collapsed whitespace, - * typographic apostrophes replaced) before matching. - * - * Text matching alone never produces a high-confidence result; it is combined - * with structural, geometric and page-state signals in `scoring.ts`. - */ - export interface PhraseSignature { id: string; label: string; @@ -26,7 +18,7 @@ export const STRONG_PHRASES: PhraseSignature[] = [ id: 'disable-adblock', label: 'Asks to disable an ad blocker', re: new RegExp( - String.raw`\b(?:disable|turn off|deactivate|pause|switch off|remove|uninstall)\b[^.!?]{0,30}\b${AB}`, + String.raw`\b(?:disabl(?:e|ing)|turn(?:ing)? ?off|deactivat(?:e|ing)|paus(?:e|ing)|switch(?:ing)? off|remov(?:e|ing)|uninstall(?:ing)?)\b[^.!?]{0,30}\b${AB}`, ), }, { @@ -63,7 +55,7 @@ export const STRONG_PHRASES: PhraseSignature[] = [ { id: 'lower-shields', label: 'Asks to lower browser privacy protection', - re: /\b(?:disable|turn off|lower|drop|switch off)\b[^.!?]{0,30}\b(?:shields|tracker blocking|tracking protection|privacy protection|content blocker)\b/, + re: /\b(?:disabl(?:e|ing)|turn(?:ing)? ?off|lower(?:ing)?|drop|switch(?:ing)? off)\b[^.!?]{0,30}\b(?:shields|tracker blocking|tracking protection|privacy protection|content blocker)\b/, }, { id: 'adblock-detected-de', @@ -82,15 +74,12 @@ export const STRONG_PHRASES: PhraseSignature[] = [ }, ]; -/** Weak mention: the text talks about ad blocking, but not necessarily as a warning. */ export const MENTION_RE = /ad[\s\u00a0_-]?block|werbeblock|bloqueur de pub|bloqueador de anuncios|whitelist|allowlist|allow ads|\bshields\b|tracking protection|content blocker/i; -/** Text the user is invited to click on anti-adblock walls. */ export const CTA_RE = /\b(?:i(?:'ve| have) (?:disabled|turned off|whitelisted|allowed)|i disabled|disabled (?:it|my)|allow ads|whitelist|allowlist|continue without|turn off|try again|refresh|reload|i understand|ok,? i(?:'ll| will)|how (?:do i|to) disable)\b/; -/** Negated or reassuring wording ("we don't mind ad blockers"). */ export const NEGATED_RE = new RegExp( String.raw`\b(?:don't|do not|doesn't|does not|no need to|won't|will not|never)\b(?: have to| need to| ask you to| mind| require you to)?[^.!?]{0,20}\b(?:disable|turn off|mind|block|ask)\b[^.!?]{0,30}${AB}|\b${AB}s? (?:are|is) (?:fine|ok|okay|welcome)\b`, ); @@ -107,14 +96,9 @@ export const SUBSCRIPTION_RE = export const AGE_GATE_RE = /\b(?:are you (?:over )?(?:18|21)|verify your age|age verification|date of birth|you must be (?:18|21))\b/; -/** - * Class / id fragments used by anti-adblock scripts. The leading boundary avoids - * matches like "head-block". - */ export const ANTI_ADBLOCK_ATTR_RE = - /(?:^|[^a-z])(?:anti[-_]?)?ad[-_]?block(?:er)?(?:[-_]?(?:notice|wall|modal|overlay|detect(?:ed|or)?|message|popup|warning|msg|alert))?(?:$|[^a-z])|(?:^|[^a-z])adb[-_](?:modal|overlay|notice|wall|popup|detect|message|warning)|blockadblock|detect[-_]?adblock|adblock[-_]?detect|(?:^|[^a-z])ab[-_](?:overlay|modal|wall)(?:$|[^a-z])/i; + /(?:^|[^a-z])(?:anti[-_]?)?ad[-_]?block(?:er)?(?:[-_]?(?:notice|wall|modal|overlay|detect(?:ed|or)?|message|popup|warning|msg|alert))?(?:$|[^a-z])|(?:^|[^a-z])adb[-_](?:modal|overlay|notice|wall|popup|detect|message|msg|note|warning|alert)|blockadblock|detect[-_]?adblock|adblock[-_]?detect|(?:^|[^a-z])ab[-_](?:overlay|modal|wall)(?:$|[^a-z])/i; -/** Selectors for candidate discovery (attribute substring matches are cheap). */ export const ATTRIBUTE_SEED_SELECTOR = [ '[class*="adblock" i]', '[id*="adblock" i]', @@ -131,11 +115,6 @@ export const ATTRIBUTE_SEED_SELECTOR = [ export const DIALOG_SEED_SELECTOR = 'dialog[open],[role="dialog"],[role="alertdialog"],[aria-modal="true"]'; -/** - * Generic vendor signatures. These identify the anti-adblock component of widely - * used ad-recovery products by their published root element. They are structural - * hints only and are always combined with other signals. - */ export const VENDOR_SIGNATURES: { id: string; label: string; selector: string }[] = [ { id: 'vendor-funding-choices', @@ -144,7 +123,6 @@ export const VENDOR_SIGNATURES: { id: string; label: string; selector: string }[ }, ]; -/** Elements whose text is never page content worth scanning. */ export const SKIP_TEXT_PARENTS = new Set([ 'SCRIPT', 'STYLE', diff --git a/src/fixer/fixer.ts b/src/fixer/fixer.ts index 546bde5..62b188e 100644 --- a/src/fixer/fixer.ts +++ b/src/fixer/fixer.ts @@ -3,16 +3,6 @@ import type { FixActionKind, FixActionSummary } from '../shared/schemas'; import type { CandidateResult, PageState } from '../detection/engine'; import { describeElement } from '../detection/layout'; -/** - * Reversible cosmetic fixes. - * - * Every change is an inline style property set with `!important` (or a dialog - * close / `inert` removal). The previous value and priority of each property are - * recorded so that `revert()` restores exactly what was there — without touching - * properties the page changed for its own reasons in the meantime. Nothing is - * removed from the DOM, so page scripts and event listeners keep working. - */ - export interface PlannedAction { kind: FixActionKind; el: Element; @@ -51,7 +41,6 @@ export function planFix( }); } - // Page-level side effects only accompany overlays, which are what cause them. const isOverlay = candidate.geometry === 'fullscreen' || candidate.geometry === 'modal'; if (isOverlay) { if (page.scrollLocked) { @@ -167,7 +156,6 @@ export class FixSession { } break; case 'unlock-scroll': - // Only the vertical axis: horizontal clipping is usually intentional. this.setStyle(el, 'overflow-y', 'auto'); break; case 'unfix-body': { @@ -213,7 +201,6 @@ export class FixSession { el.style.setProperty(prop, target, 'important'); } - /** Pages sometimes undo cosmetic fixes; re-assert ours (bounded) while active. */ private observe(): void { const targets = new Set(); for (const c of this.changes) targets.add(c.type === 'style' ? c.record.el : c.el); @@ -301,7 +288,6 @@ export class FixSession { function isRenderedFresh(el: Element, win: Window & typeof globalThis): boolean { const s = win.getComputedStyle(el); if (s.display === 'none' || s.visibility === 'hidden') return false; - // Also hidden if any ancestor is display:none. for (let cur = el.parentElement; cur; cur = cur.parentElement) { if (win.getComputedStyle(cur).display === 'none') return false; } diff --git a/src/fixer/selector.ts b/src/fixer/selector.ts index 331fe6e..f60f73d 100644 --- a/src/fixer/selector.ts +++ b/src/fixer/selector.ts @@ -1,12 +1,5 @@ import { checkSelectorSafety } from '../compat/selectorSafety'; -/** - * Builds a selector that identifies an element across page loads, for saving a - * user-approved fix as a compatibility rule. Generated class names (CSS modules, - * styled-components, hashes) change between builds, so they are skipped; when no - * stable, unique selector exists, `null` is returned and no rule is offered. - */ - const PROTECTED = new Set(['html', 'head', 'body', 'main']); export function isStableToken(token: string): boolean { @@ -17,7 +10,7 @@ export function isStableToken(token: string): boolean { if (/^(?:css|sc|jsx|emotion|svelte|tw)-/i.test(token)) return false; if (/(?:^|[_-])[A-Za-z0-9]{5,}$/.test(token) && /[A-Z]/.test(token) && /\d/.test(token)) return false; - if (/__[A-Za-z0-9]{5}$/.test(token)) return false; // CSS modules: name__hash5 + if (/__[A-Za-z0-9]{5}$/.test(token)) return false; return true; } @@ -55,7 +48,6 @@ export function stableSelector(el: Element, doc: Document): string | null { } } else if (parent && own) { const combined = `${parent.tagName.toLowerCase()} > ${own}`; - // e.g. "body > div.adblock-wall" — allowed because the final compound has a class. if (accept(combined)) return combined; } return null; diff --git a/src/shared/constants.ts b/src/shared/constants.ts index f470fa6..9ca06bd 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -1,11 +1,9 @@ -/** Confidence thresholds (initial engineering defaults — see docs/ARCHITECTURE.md). */ export const THRESHOLDS = { possible: 40, likely: 70, high: 90, } as const; -/** A cosmetic fix is only offered at or above this confidence. */ export const FIX_THRESHOLD = THRESHOLDS.high; export const LIMITS = { @@ -16,9 +14,7 @@ export const LIMITS = { maxCandidatesReported: 10, maxTextChars: 4000, maxScanTextChars: 400_000, - /** How long the monitor keeps observing DOM mutations after page load (ms). */ observeWindowMs: 120_000, - /** Minimum time between mutation-triggered rescans (ms). */ rescanThrottleMs: 1_000, mutationDebounceMs: 350, maxMutationScans: 30, @@ -29,7 +25,6 @@ export const LIMITS = { export const MONITOR_SCRIPT_ID = 'shieldfix-monitor'; export const CONTENT_SCRIPT_FILE = 'content.js'; -/** Host patterns declared in manifest `optional_host_permissions`. */ export const ALL_SITES_ORIGINS = ['http://*/*', 'https://*/*'] as const; export const NOTICE_HOST_ATTR = 'data-shieldfix-ui'; diff --git a/src/shared/domain.ts b/src/shared/domain.ts index d0d75ef..79eea3d 100644 --- a/src/shared/domain.ts +++ b/src/shared/domain.ts @@ -1,11 +1,5 @@ -/** - * Hostname utilities. ShieldFix keys all site data by hostname (with a leading - * "www." removed). Full URLs, paths and query strings are never stored. - */ - const HOSTNAME_RE = /^(?=.{3,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/; -/** Common multi-label public suffixes. Not a full Public Suffix List — see docs/ARCHITECTURE.md. */ const MULTI_PART_SUFFIXES = new Set([ 'co.uk', 'org.uk', @@ -46,7 +40,6 @@ export function isValidHostname(value: string): boolean { return HOSTNAME_RE.test(value); } -/** Lower-case, strip a trailing dot and a leading "www.". */ export function normalizeHostname(hostname: string): string { let host = hostname.trim().toLowerCase(); if (host.endsWith('.')) host = host.slice(0, -1); @@ -62,7 +55,6 @@ export interface UrlInfo { const RESTRICTED_HOSTS = ['chromewebstore.google.com', 'chrome.google.com']; -/** Decide whether ShieldFix can work on a URL (http/https pages only). */ export function describeUrl(url: string | undefined | null): UrlInfo { if (!url) return { supported: false, hostname: null, reason: 'No page is open in this tab.' }; let parsed: URL; @@ -89,25 +81,22 @@ export function describeUrl(url: string | undefined | null): UrlInfo { return { supported: true, hostname, reason: null }; } -/** True when `host` equals `domain` or is a subdomain of it. */ export function hostMatchesDomain(host: string, domain: string): boolean { const h = normalizeHostname(host); const d = normalizeHostname(domain); return h === d || h.endsWith(`.${d}`); } -/** Match patterns covering a site and its subdomains, for permissions and content scripts. */ export function originPatternsFor(hostname: string): string[] { const host = normalizeHostname(hostname); if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(host)) return [`*://${host}/*`]; return [`*://${host}/*`, `*://*.${host}/*`]; } -/** Approximate registrable domain ("site"), used only to label resources first/third-party. */ export function approximateSite(hostname: string): string { const labels = normalizeHostname(hostname).split('.'); if (labels.length <= 2) return labels.join('.'); - if (/^\d+$/.test(labels[labels.length - 1] ?? '')) return labels.join('.'); // IPv4 + if (/^\d+$/.test(labels[labels.length - 1] ?? '')) return labels.join('.'); const lastTwo = labels.slice(-2).join('.'); if (MULTI_PART_SUFFIXES.has(lastTwo)) return labels.slice(-3).join('.'); return lastTwo; diff --git a/src/shared/envelope.ts b/src/shared/envelope.ts index 3f11740..4826fba 100644 --- a/src/shared/envelope.ts +++ b/src/shared/envelope.ts @@ -1,8 +1,3 @@ -/** - * Response envelope shared by all extension messaging. Kept free of runtime - * dependencies so the content script stays small. - */ - export type ErrorCode = | 'invalid-request' | 'forbidden' diff --git a/src/shared/messages.ts b/src/shared/messages.ts index 3f18731..bff4106 100644 --- a/src/shared/messages.ts +++ b/src/shared/messages.ts @@ -18,10 +18,6 @@ import { import type { UrlInfo } from './domain'; import { errorEnvelope, fail, type Envelope } from './envelope'; -/* ------------------------------------------------------------------ */ -/* Extension pages (popup, dashboard) -> background */ -/* ------------------------------------------------------------------ */ - const TabId = z.number().int().min(0); const CandidateId = z.string().regex(/^c\d{1,6}$/); @@ -147,10 +143,6 @@ export interface UiResponseMap { 'brave/open': { opened: string }; } -/* ------------------------------------------------------------------ */ -/* Content script -> background */ -/* ------------------------------------------------------------------ */ - export const ContentRequestSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('content/config') }), z.object({ type: z.literal('content/report'), report: DetectionReportSchema }), @@ -186,10 +178,6 @@ export interface ContentResponseMap { 'content/openPopup': { opened: boolean }; } -/* ------------------------------------------------------------------ */ -/* Background -> content script */ -/* ------------------------------------------------------------------ */ - export const ToContentSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('cs/ping') }), z.object({ type: z.literal('cs/scan'), trigger: ScanTriggerSchema }), @@ -234,10 +222,6 @@ export interface ToContentResponseMap { 'cs/configChanged': null; } -/* ------------------------------------------------------------------ */ -/* Envelope */ -/* ------------------------------------------------------------------ */ - export { ShieldFixError, ok, fail, type ErrorCode, type Envelope } from './envelope'; export function toEnvelopeError(err: unknown): Envelope { diff --git a/src/shared/schemas.ts b/src/shared/schemas.ts index 248e366..bd99656 100644 --- a/src/shared/schemas.ts +++ b/src/shared/schemas.ts @@ -2,10 +2,6 @@ import { z } from 'zod'; import { checkSelectorSafety } from '../compat/selectorSafety'; import { isValidHostname, normalizeHostname } from './domain'; -/* ------------------------------------------------------------------ */ -/* Detection */ -/* ------------------------------------------------------------------ */ - export const DetectionLevelSchema = z.enum(['none', 'possible', 'likely', 'high']); export type DetectionLevel = z.infer; @@ -44,7 +40,6 @@ export const CandidateSummarySchema = z.object({ vetoes: z.array(VetoSchema).max(20), fixable: z.boolean(), fixBlockedReason: z.string().max(300).nullable(), - /** Structural description such as `div#adb-wall.modal` — never page text. */ descriptor: z.string().max(200), ruleId: z.string().max(64).nullable(), geometry: z.enum(['fullscreen', 'modal', 'banner', 'inline']), @@ -138,10 +133,6 @@ export const DetectionReportSchema = z.object({ }); export type DetectionReport = z.infer; -/* ------------------------------------------------------------------ */ -/* Compatibility rules */ -/* ------------------------------------------------------------------ */ - export const DomainSchema = z .string() .transform((v) => normalizeHostname(v)) @@ -179,7 +170,6 @@ export const RuleSchema = z.object({ }); export type Rule = z.infer; -/** What a user (or an import) supplies when creating or editing a rule. */ export const RuleInputSchema = z.object({ id: RuleIdSchema.optional(), domain: DomainSchema, @@ -199,10 +189,6 @@ export const RulesExportSchema = z.object({ rules: z.array(z.unknown()).max(500), }); -/* ------------------------------------------------------------------ */ -/* Settings, sites and history */ -/* ------------------------------------------------------------------ */ - export const ThemeSchema = z.enum(['system', 'light', 'dark']); export type Theme = z.infer; @@ -230,10 +216,6 @@ export const SettingsSchema = z.object({ export type Settings = z.infer; export const DEFAULT_SETTINGS: Settings = SettingsSchema.parse({}); -/** - * Built from the default-free fields: in Zod 4, `.partial()` of a field with a - * default still fills the default in, which would reset every other setting. - */ export const SettingsPatchSchema = z.object(SETTINGS_FIELDS).partial().strict(); export type SettingsPatch = z.infer; @@ -275,7 +257,6 @@ export const HistoryEntrySchema = z.object({ event: HistoryEventSchema, level: DetectionLevelSchema, confidence: z.number().min(0).max(100), - /** Signal ids only (for example "phrase-strong"); never page text. */ signals: z.array(z.string().max(64)).max(40), }); export type HistoryEntry = z.infer; diff --git a/src/storage/area.ts b/src/storage/area.ts index c9c707f..eaf076a 100644 --- a/src/storage/area.ts +++ b/src/storage/area.ts @@ -1,4 +1,3 @@ -/** Minimal key-value storage contract (chrome.storage.local / .session or in-memory). */ export interface StorageArea { get(keys: string[]): Promise>; set(items: Record): Promise; @@ -36,13 +35,11 @@ export class MemoryArea implements StorageArea { this.data.clear(); } - /** Test helper. */ raw(key: string): unknown { return this.data.get(key); } } -/** Serialises async read-modify-write operations. */ export class Mutex { private tail: Promise = Promise.resolve(); diff --git a/src/storage/repository.ts b/src/storage/repository.ts index fe78a28..074c649 100644 --- a/src/storage/repository.ts +++ b/src/storage/repository.ts @@ -35,11 +35,6 @@ const KEYS = { type Clock = () => number; -/** - * Typed, validated access to persistent extension data (chrome.storage.local). - * Everything is stored locally; nothing here is synchronised or uploaded. - * Corrupt or outdated records are dropped individually rather than failing reads. - */ export class Repository { private readonly mutex = new Mutex(); @@ -48,14 +43,11 @@ export class Repository { private readonly now: Clock = Date.now, ) {} - /* -------------------------------- lifecycle ------------------------------- */ - async migrate(): Promise { await this.mutex.run(async () => { const raw = await this.area.get([KEYS.schemaVersion]); const version = typeof raw[KEYS.schemaVersion] === 'number' ? raw[KEYS.schemaVersion] : 0; if (version === SCHEMA_VERSION) return; - // Version 0 -> 1: initial schema. Future migrations go here, in order. await this.area.set({ [KEYS.schemaVersion]: SCHEMA_VERSION }); }); } @@ -67,8 +59,6 @@ export class Repository { }); } - /* -------------------------------- settings -------------------------------- */ - async getSettings(): Promise { const raw = await this.area.get([KEYS.settings]); const parsed = SettingsSchema.safeParse(raw[KEYS.settings] ?? {}); @@ -84,8 +74,6 @@ export class Repository { }); } - /* ---------------------------------- sites --------------------------------- */ - private async readSites(): Promise> { const raw = (await this.area.get([KEYS.sites]))[KEYS.sites]; const out: Record = {}; @@ -129,10 +117,6 @@ export class Repository { }); } - /** - * Records a scan outcome on the site's summary. Sites without saved preferences - * are only recorded when history is enabled and something was detected. - */ async recordScan( hostname: string, scan: { level: SiteRecord['lastLevel']; confidence: number; fixApplied?: boolean }, @@ -169,8 +153,6 @@ export class Repository { await this.mutex.run(() => this.area.set({ [KEYS.sites]: {} })); } - /* ---------------------------------- rules --------------------------------- */ - private async readRules(): Promise { const raw = (await this.area.get([KEYS.rules]))[KEYS.rules]; if (!Array.isArray(raw)) return []; @@ -206,7 +188,6 @@ export class Repository { return this.readRules(); } - /** Create a rule, or save a new version of an existing one (keeping history). */ async upsertRule(input: RuleInput, source: Rule['source'] = 'user'): Promise { return this.mutex.run(async () => { const rules = await this.readRules(); @@ -246,7 +227,6 @@ export class Repository { }); } - /** Restore the most recent previous version of a rule. */ async rollbackRule(id: string): Promise { return this.mutex.run(async () => { const rules = await this.readRules(); @@ -321,8 +301,6 @@ export class Repository { }; } - /* --------------------------------- history -------------------------------- */ - async listHistory(): Promise { const raw = (await this.area.get([KEYS.history]))[KEYS.history]; if (!Array.isArray(raw)) return []; @@ -357,8 +335,6 @@ export class Repository { await this.mutex.run(() => this.area.set({ [KEYS.history]: [] })); } - /* -------------------------------- onboarding ------------------------------- */ - async getOnboarding(): Promise { const raw = (await this.area.get([KEYS.onboarding]))[KEYS.onboarding]; const parsed = OnboardingSchema.safeParse(raw ?? {}); diff --git a/src/ui/components/Announcer.tsx b/src/ui/components/Announcer.tsx index 6095627..e062c7b 100644 --- a/src/ui/components/Announcer.tsx +++ b/src/ui/components/Announcer.tsx @@ -1,7 +1,6 @@ import { useCallback, useRef, useState, type ReactNode } from 'react'; import { AnnouncerContext, type Announce } from './announcerContext'; -/** Screen-reader status announcements through visually hidden live regions. */ export function AnnouncerProvider({ children }: { children: ReactNode }) { const [polite, setPolite] = useState(''); const [assertive, setAssertive] = useState(''); @@ -10,7 +9,6 @@ export function AnnouncerProvider({ children }: { children: ReactNode }) { const announce = useCallback((message, tone = 'polite') => { const set = tone === 'assertive' ? setAssertive : setPolite; set(''); - // Re-setting after a tick makes repeated identical messages announce again. if (timer.current !== null) window.clearTimeout(timer.current); timer.current = window.setTimeout(() => set(message), 60); }, []); diff --git a/src/ui/components/Dialog.tsx b/src/ui/components/Dialog.tsx index 8872305..8290953 100644 --- a/src/ui/components/Dialog.tsx +++ b/src/ui/components/Dialog.tsx @@ -1,10 +1,6 @@ import { useEffect, useId, useRef, useState, type ReactNode } from 'react'; import { Button } from './Button'; -/** - * Modal built on the native element: focus trapping, Escape to close - * and inert background are provided by the browser. - */ export function Modal({ open, onClose, @@ -43,7 +39,7 @@ export function Modal({ onClose(); }} onClick={(e) => { - if (e.target === ref.current) onClose(); // click on backdrop + if (e.target === ref.current) onClose(); }} className={`m-auto w-[calc(100%-32px)] ${width} rounded-xl border border-line bg-surface p-0 text-fg shadow-pop backdrop:backdrop-blur-[1px]`} > diff --git a/src/ui/components/Switch.tsx b/src/ui/components/Switch.tsx index 3d8ab1b..cf2afa2 100644 --- a/src/ui/components/Switch.tsx +++ b/src/ui/components/Switch.tsx @@ -9,7 +9,6 @@ export interface SwitchProps { busy?: boolean; } -/** Accessible toggle: a button with role="switch", labelled and described. */ export function Switch({ checked, onChange, label, description, disabled, busy }: SwitchProps) { const id = useId(); return ( diff --git a/src/ui/components/announcerContext.ts b/src/ui/components/announcerContext.ts index aa6b68c..2b72800 100644 --- a/src/ui/components/announcerContext.ts +++ b/src/ui/components/announcerContext.ts @@ -4,7 +4,6 @@ export type Announce = (message: string, tone?: 'polite' | 'assertive') => void; export const AnnouncerContext = createContext(() => undefined); -/** Announce a status message to screen readers. */ export function useAnnounce(): Announce { return useContext(AnnouncerContext); } diff --git a/src/ui/dashboard/Dashboard.tsx b/src/ui/dashboard/Dashboard.tsx index 6cf4038..7fcb5f8 100644 --- a/src/ui/dashboard/Dashboard.tsx +++ b/src/ui/dashboard/Dashboard.tsx @@ -76,7 +76,7 @@ export function Dashboard() { const navigate = useCallback((id: string) => { location.hash = `#/${id}`; - document.getElementById('main')?.focus(); // move focus to the new section for keyboard users + document.getElementById('main')?.focus(); }, []); const { data: loaded, reload } = data; diff --git a/src/ui/dashboard/context.tsx b/src/ui/dashboard/context.tsx index aa87436..a81621b 100644 --- a/src/ui/dashboard/context.tsx +++ b/src/ui/dashboard/context.tsx @@ -5,7 +5,6 @@ import type { Settings } from '../../shared/schemas'; export interface DashboardContextValue { settings: Settings; info: AppInfo; - /** Increments whenever stored data changes. */ version: number; refresh: () => void; navigate: (section: string) => void; diff --git a/src/ui/dashboard/sections/Privacy.tsx b/src/ui/dashboard/sections/Privacy.tsx index 4ce626f..71b0f9c 100644 --- a/src/ui/dashboard/sections/Privacy.tsx +++ b/src/ui/dashboard/sections/Privacy.tsx @@ -25,7 +25,6 @@ export function Privacy() { const announce = useAnnounce(); const { update, error, setError, busy } = useSettingsUpdater(); const [confirm, setConfirm] = useState<'reset' | 'revoke' | null>(null); - // Required host permissions (none in release builds) cannot be revoked at runtime. const required = new Set(chrome.runtime.getManifest().host_permissions ?? []); const siteOrigins = info.grantedOrigins.filter((o) => o.includes('://') && !required.has(o)); diff --git a/src/ui/dashboard/sections/Settings.tsx b/src/ui/dashboard/sections/Settings.tsx index afa8c82..53c414f 100644 --- a/src/ui/dashboard/sections/Settings.tsx +++ b/src/ui/dashboard/sections/Settings.tsx @@ -24,7 +24,7 @@ export function SettingsSection() { const setAllSites = (enable: boolean) => { setBusy('monitorAllSites'); setError(null); - const permission = enable ? requestOrigins([...ALL_SITES_ORIGINS]) : Promise.resolve(true); // in the click + const permission = enable ? requestOrigins([...ALL_SITES_ORIGINS]) : Promise.resolve(true); void permission .then(async (granted) => { if (!granted) { diff --git a/src/ui/dashboard/sections/Sites.tsx b/src/ui/dashboard/sections/Sites.tsx index d64c635..9c05b1d 100644 --- a/src/ui/dashboard/sections/Sites.tsx +++ b/src/ui/dashboard/sections/Sites.tsx @@ -33,7 +33,7 @@ export function Sites() { const patterns = originPatternsFor(site.hostname); setBusy(`${site.hostname}:monitor`); setError(null); - const permission = enable ? requestOrigins(patterns) : Promise.resolve(true); // must start in the click + const permission = enable ? requestOrigins(patterns) : Promise.resolve(true); void permission .then(async (granted) => { if (!granted) { diff --git a/src/ui/dashboard/sections/Welcome.tsx b/src/ui/dashboard/sections/Welcome.tsx index 0055490..29a1d1b 100644 --- a/src/ui/dashboard/sections/Welcome.tsx +++ b/src/ui/dashboard/sections/Welcome.tsx @@ -41,7 +41,7 @@ export function Welcome() { setBusy(true); setError(null); const permission = - mode === 'all-sites' ? requestOrigins([...ALL_SITES_ORIGINS]) : Promise.resolve(true); // in the click + mode === 'all-sites' ? requestOrigins([...ALL_SITES_ORIGINS]) : Promise.resolve(true); void permission .then(async (granted) => { if (mode === 'all-sites') { diff --git a/src/ui/dashboard/useSettingsUpdater.ts b/src/ui/dashboard/useSettingsUpdater.ts index 4fadb8c..c3ccc50 100644 --- a/src/ui/dashboard/useSettingsUpdater.ts +++ b/src/ui/dashboard/useSettingsUpdater.ts @@ -3,7 +3,6 @@ import type { SettingsPatch } from '../../shared/schemas'; import { errorMessage, send } from '../lib/api'; import { useAnnounce } from '../components/announcerContext'; -/** Saves a settings patch with busy/error state and a screen-reader announcement. */ export function useSettingsUpdater() { const announce = useAnnounce(); const [error, setError] = useState(null); diff --git a/src/ui/lib/api.ts b/src/ui/lib/api.ts index c2bb4af..e95096d 100644 --- a/src/ui/lib/api.ts +++ b/src/ui/lib/api.ts @@ -13,7 +13,6 @@ export class ApiError extends Error { } } -/** Typed request to the background service worker. */ export async function send( message: Extract, ): Promise { @@ -38,7 +37,6 @@ export function errorMessage(err: unknown): string { return 'Something went wrong.'; } -/** Permission requests must run synchronously inside a click handler. */ export function requestOrigins(origins: string[]): Promise { return chrome.permissions.request({ origins }).catch(() => false); } diff --git a/src/ui/lib/hooks.ts b/src/ui/lib/hooks.ts index 3b5678f..72cfd9f 100644 --- a/src/ui/lib/hooks.ts +++ b/src/ui/lib/hooks.ts @@ -1,20 +1,14 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useEffectEvent, useState } from 'react'; import type { Theme } from '../../shared/schemas'; import { errorMessage } from './api'; export interface AsyncState { status: 'loading' | 'ready' | 'error'; - /** Latest successfully loaded data; kept while a refresh is in flight. */ data: T | null; error: string | null; reload: () => void; } -/** - * Loads data and reloads whenever `deps` (primitives) change. Loading state is - * derived from whether the last result belongs to the current dependencies, so - * no state is set synchronously inside the effect. - */ export function useAsync(load: () => Promise, deps: unknown[]): AsyncState { const [tick, setTick] = useState(0); const key = JSON.stringify([...deps, tick]); @@ -28,9 +22,11 @@ export function useAsync(load: () => Promise, deps: unknown[]): AsyncState error: null, }); + const runLoad = useEffectEvent(() => load()); + useEffect(() => { let cancelled = false; - load() + runLoad() .then((data) => { if (!cancelled) setResult({ key, data, error: null }); }) @@ -40,8 +36,6 @@ export function useAsync(load: () => Promise, deps: unknown[]): AsyncState return () => { cancelled = true; }; - // `load` is intentionally excluded: callers pass inline functions keyed by `deps`. - // eslint-disable-next-line react-hooks/exhaustive-deps }, [key]); const reload = useCallback(() => setTick((t) => t + 1), []); @@ -54,7 +48,6 @@ export function useAsync(load: () => Promise, deps: unknown[]): AsyncState }; } -/** Increments whenever extension storage changes, so views can refresh live. */ export function useStorageVersion(): number { const [version, setVersion] = useState(0); useEffect(() => { @@ -76,7 +69,6 @@ export function applyTheme(theme: Theme): void { document.documentElement.dataset.theme = resolveTheme(theme); } -/** Applies the theme to and follows the OS setting when theme is "system". */ export function useTheme(theme: Theme | undefined): void { useEffect(() => { const t = theme ?? 'system'; @@ -95,7 +87,6 @@ declare global { } } -/** Brave exposes `navigator.brave.isBrave()`; also check UA client hints. Never essential. */ export function useIsBrave(): boolean | null { const [isBrave, setIsBrave] = useState(null); useEffect(() => { diff --git a/src/ui/popup/BraveView.tsx b/src/ui/popup/BraveView.tsx index dcf84b9..926725b 100644 --- a/src/ui/popup/BraveView.tsx +++ b/src/ui/popup/BraveView.tsx @@ -6,10 +6,6 @@ import { Button } from '../components/Button'; import { Alert } from '../components/Feedback'; import { ViewHeader } from './ViewHeader'; -/** - * Guidance for native browser controls. Extensions cannot read or change Brave - * Shields, so ShieldFix explains the steps instead of pretending to act. - */ export function BraveView({ hostname, hasFix, diff --git a/src/ui/popup/Popup.tsx b/src/ui/popup/Popup.tsx index aa0ffb1..f2ded74 100644 --- a/src/ui/popup/Popup.tsx +++ b/src/ui/popup/Popup.tsx @@ -234,7 +234,6 @@ export function Popup() { if (!host) return; const patterns = originPatternsFor(host); setBusy('monitor'); - // The permission request must start synchronously in the click handler. const permission = enable ? requestOrigins(patterns) : Promise.resolve(true); void permission .then(async (granted) => { diff --git a/src/ui/popup/main.tsx b/src/ui/popup/main.tsx index 748dab4..89b2bd4 100644 --- a/src/ui/popup/main.tsx +++ b/src/ui/popup/main.tsx @@ -5,7 +5,7 @@ import { AnnouncerProvider } from '../components/Announcer'; import { applyTheme } from '../lib/hooks'; import { Popup } from './Popup'; -applyTheme('system'); // until settings load, avoid a flash of the wrong theme +applyTheme('system'); createRoot(document.getElementById('root')!).render( diff --git a/src/ui/popup/status.ts b/src/ui/popup/status.ts index fcd0e95..94eb1ec 100644 --- a/src/ui/popup/status.ts +++ b/src/ui/popup/status.ts @@ -13,7 +13,6 @@ export function primaryOf(report: DetectionReport | null): CandidateSummary | nu return report.candidates.find((c) => c.id === report.primaryCandidateId) ?? null; } -/** Maps a report to the main popup status. Wording never overstates what happened. */ export function statusFor(report: DetectionReport | null, scanning: boolean): StatusView { if (!report) { return scanning diff --git a/src/ui/styles.css b/src/ui/styles.css index 0ee3a46..e781fc6 100644 --- a/src/ui/styles.css +++ b/src/ui/styles.css @@ -2,10 +2,6 @@ @custom-variant dark (&:where([data-theme='dark'], [data-theme='dark'] *)); -/* - * Design tokens. Every colour pair used for text meets WCAG 2.2 AA contrast - * (4.5:1) against the surface it is placed on, in both themes. - */ :root { color-scheme: light; --sf-bg: #f6f6f7; diff --git a/store-assets/dashboard-overview-dark.png b/store-assets/dashboard-overview-dark.png deleted file mode 100644 index 93ed661..0000000 Binary files a/store-assets/dashboard-overview-dark.png and /dev/null differ diff --git a/store-assets/dashboard-overview-light.png b/store-assets/dashboard-overview-light.png deleted file mode 100644 index c0db823..0000000 Binary files a/store-assets/dashboard-overview-light.png and /dev/null differ diff --git a/store-assets/dashboard-privacy-dark.png b/store-assets/dashboard-privacy-dark.png deleted file mode 100644 index 327d565..0000000 Binary files a/store-assets/dashboard-privacy-dark.png and /dev/null differ diff --git a/store-assets/dashboard-privacy-light.png b/store-assets/dashboard-privacy-light.png deleted file mode 100644 index e63ea86..0000000 Binary files a/store-assets/dashboard-privacy-light.png and /dev/null differ diff --git a/store-assets/dashboard-rules-dark.png b/store-assets/dashboard-rules-dark.png deleted file mode 100644 index 300b3a1..0000000 Binary files a/store-assets/dashboard-rules-dark.png and /dev/null differ diff --git a/store-assets/dashboard-rules-light.png b/store-assets/dashboard-rules-light.png deleted file mode 100644 index 0d84e7e..0000000 Binary files a/store-assets/dashboard-rules-light.png and /dev/null differ diff --git a/store-assets/popup-detected-dark.png b/store-assets/popup-detected-dark.png deleted file mode 100644 index e54dcb7..0000000 Binary files a/store-assets/popup-detected-dark.png and /dev/null differ diff --git a/store-assets/popup-detected-light.png b/store-assets/popup-detected-light.png deleted file mode 100644 index 62ef11f..0000000 Binary files a/store-assets/popup-detected-light.png and /dev/null differ diff --git a/store-assets/popup-diagnosis-dark.png b/store-assets/popup-diagnosis-dark.png deleted file mode 100644 index 388c9ac..0000000 Binary files a/store-assets/popup-diagnosis-dark.png and /dev/null differ diff --git a/store-assets/popup-diagnosis-light.png b/store-assets/popup-diagnosis-light.png deleted file mode 100644 index a15ce1b..0000000 Binary files a/store-assets/popup-diagnosis-light.png and /dev/null differ diff --git a/store-assets/popup-review-dark.png b/store-assets/popup-review-dark.png deleted file mode 100644 index 78dc800..0000000 Binary files a/store-assets/popup-review-dark.png and /dev/null differ diff --git a/store-assets/popup-review-light.png b/store-assets/popup-review-light.png deleted file mode 100644 index 73a5bfd..0000000 Binary files a/store-assets/popup-review-light.png and /dev/null differ diff --git a/store-assets/promo-marquee.png b/store-assets/promo-marquee.png new file mode 100644 index 0000000..bbc2af1 Binary files /dev/null and b/store-assets/promo-marquee.png differ diff --git a/store-assets/promo-small.png b/store-assets/promo-small.png new file mode 100644 index 0000000..5f80638 Binary files /dev/null and b/store-assets/promo-small.png differ diff --git a/store-assets/screenshot-1.png b/store-assets/screenshot-1.png new file mode 100644 index 0000000..26f1839 Binary files /dev/null and b/store-assets/screenshot-1.png differ diff --git a/store-assets/screenshot-2.png b/store-assets/screenshot-2.png new file mode 100644 index 0000000..bc91dcf Binary files /dev/null and b/store-assets/screenshot-2.png differ diff --git a/store-assets/screenshot-3.png b/store-assets/screenshot-3.png new file mode 100644 index 0000000..71cdcc4 Binary files /dev/null and b/store-assets/screenshot-3.png differ diff --git a/store-assets/screenshot-4.png b/store-assets/screenshot-4.png new file mode 100644 index 0000000..3c82248 Binary files /dev/null and b/store-assets/screenshot-4.png differ diff --git a/store-assets/screenshot-5.png b/store-assets/screenshot-5.png new file mode 100644 index 0000000..d95fd1f Binary files /dev/null and b/store-assets/screenshot-5.png differ diff --git a/store-assets/store-1-detect.png b/store-assets/store-1-detect.png deleted file mode 100644 index 69a37de..0000000 Binary files a/store-assets/store-1-detect.png and /dev/null differ diff --git a/store-assets/store-2-rules.png b/store-assets/store-2-rules.png deleted file mode 100644 index 5a34911..0000000 Binary files a/store-assets/store-2-rules.png and /dev/null differ diff --git a/store-assets/store-3-privacy.png b/store-assets/store-3-privacy.png deleted file mode 100644 index e63ea86..0000000 Binary files a/store-assets/store-3-privacy.png and /dev/null differ diff --git a/tests/e2e/dashboard.spec.ts b/tests/e2e/dashboard.spec.ts index 83dde58..756e127 100644 --- a/tests/e2e/dashboard.spec.ts +++ b/tests/e2e/dashboard.spec.ts @@ -132,7 +132,6 @@ test.describe('dashboard', () => { context, ext, }) => { - // Create some data first. const page0 = await context.newPage(); await page0.goto('http://127.0.0.1:4173/fullscreen-modal.html'); const tabId = await ext.tabIdFor('http://127.0.0.1:4173/fullscreen-modal.html'); diff --git a/tests/e2e/detection.spec.ts b/tests/e2e/detection.spec.ts index db8a9ff..17ca7aa 100644 --- a/tests/e2e/detection.spec.ts +++ b/tests/e2e/detection.spec.ts @@ -18,7 +18,7 @@ test.describe('anti-adblock warnings are detected and fixed reversibly', () => { expect(primary.fixable).toBe(true); expect(report.page.scrollLocked).toBe(true); expect(report.page.blurredElements).toBeGreaterThan(0); - expect(report.ordinaryDialogs).toBe(0); // its backdrop is part of the warning + expect(report.ordinaryDialogs).toBe(0); const preview = await ext.data<{ actions: { kind: string }[]; rememberSelector: string }>({ type: 'tab/previewFix', @@ -73,7 +73,6 @@ test.describe('anti-adblock warnings are detected and fixed reversibly', () => { }); expect(outcome.applied).toBe(true); await expect(page.locator('#adblock-notice')).toBeHidden(); - // Banners don't lock the page, so no scroll changes are made. expect(outcome.verified.scrollRestored).toBeNull(); }); @@ -113,7 +112,6 @@ test.describe('ordinary page elements are never treated as anti-adblock warnings expect(report.primaryCandidateId).toBeNull(); expect(report.level).toBe('none'); expect(report.candidates.every((c) => !c.fixable)).toBe(true); - // Even a forged request to fix any element it saw is refused. for (const c of report.candidates) { const res = await ext.send({ type: 'tab/applyFix', diff --git a/tests/e2e/fixtures.ts b/tests/e2e/fixtures.ts index 1db77df..be0fba7 100644 --- a/tests/e2e/fixtures.ts +++ b/tests/e2e/fixtures.ts @@ -8,7 +8,6 @@ export const fixture = (name: string) => `${FIXTURES}/${name}.html`; interface ExtensionFixtures { context: BrowserContext; extensionId: string; - /** An extension page used to talk to the background worker like the real UI does. */ ext: ExtensionClient; } @@ -45,14 +44,12 @@ export class ExtensionClient { } export const test = base.extend({ - // eslint-disable-next-line no-empty-pattern context: async ({}, use, testInfo) => { const extensionPath = resolve('dist-e2e'); const executablePath = testInfo.project.use.launchOptions?.executablePath; const context = await chromium.launchPersistentContext('', { channel: executablePath ? undefined : 'chromium', executablePath, - // Brave runs headless unless BRAVE_HEADED=1 (useful when debugging). headless: !(executablePath && process.env.BRAVE_HEADED === '1'), viewport: { width: 1280, height: 800 }, args: [`--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`], @@ -74,7 +71,6 @@ export const test = base.extend({ export { expect } from '@playwright/test'; -/** Open a fixture page and return it with its tab id. */ export async function openFixture(context: BrowserContext, ext: ExtensionClient, name: string) { const page = await context.newPage(); await page.goto(fixture(name)); diff --git a/tests/e2e/monitoring.spec.ts b/tests/e2e/monitoring.spec.ts index 55393be..6bb60c3 100644 --- a/tests/e2e/monitoring.spec.ts +++ b/tests/e2e/monitoring.spec.ts @@ -17,7 +17,7 @@ test.describe('automatic monitoring', () => { await page.goto(fixture('dynamic-overlay')); const notice = page.locator('shieldfix-notice'); await expect(notice.getByText('Ad-blocker warning detected')).toBeVisible({ timeout: 10_000 }); - await expect(page.locator('#dyn-wall')).toBeVisible(); // nothing changes without approval + await expect(page.locator('#dyn-wall')).toBeVisible(); await notice.getByRole('button', { name: 'Hide warning' }).click(); await expect(page.locator('#dyn-wall')).toBeHidden(); @@ -33,7 +33,6 @@ test.describe('automatic monitoring', () => { expect.arrayContaining(['detected', 'fix-applied', 'fix-reverted']), ); expect(history.every((h) => h.hostname === '127.0.0.1')).toBe(true); - // History holds no URLs or page text. expect(JSON.stringify(history)).not.toContain('dynamic-overlay'); expect(JSON.stringify(history)).not.toContain('adblocker'); }); diff --git a/tests/e2e/performance.spec.ts b/tests/e2e/performance.spec.ts index 258ca08..234b957 100644 --- a/tests/e2e/performance.spec.ts +++ b/tests/e2e/performance.spec.ts @@ -1,10 +1,6 @@ import type { DetectionReport } from '../../src/shared/schemas'; import { expect, fixture, openFixture, test } from './fixtures'; -/** - * Measured, not assumed. Budgets are deliberately generous to avoid flaky CI; - * the measured values are printed and recorded in docs/TESTING.md. - */ test.describe('performance', () => { test('scan time on typical and large pages', async ({ context, ext }, testInfo) => { const results: Record = {}; @@ -48,7 +44,7 @@ test.describe('performance', () => { 'content state ok:', ping?.ok, ); - expect(ping?.ok).toBe(true); // the monitor really was running + expect(ping?.ok).toBe(true); if (longTasks !== null) expect(longTasks.length).toBe(0); }); }); diff --git a/tests/e2e/popup.spec.ts b/tests/e2e/popup.spec.ts index 7927ff7..eeb8141 100644 --- a/tests/e2e/popup.spec.ts +++ b/tests/e2e/popup.spec.ts @@ -1,10 +1,5 @@ import { expect, openFixture, test } from './fixtures'; -/** - * The popup is opened as a tab with ?tabId= pointing at the fixture page. In real - * use the toolbar button opens it and grants activeTab; the E2E build instead has - * host access to 127.0.0.1 (see docs/TESTING.md). - */ test.describe('popup', () => { test('scans on open, reviews and applies a fix, then undoes it', async ({ context, ext }) => { const { page, tabId } = await openFixture(context, ext, 'fullscreen-modal'); @@ -20,7 +15,6 @@ test.describe('popup', () => { const changes = popup.getByRole('list', { name: 'Proposed changes' }); await expect(changes.getByText(/Hide the overlay div#adb-wall/)).toBeVisible(); await expect(changes.getByText(/Restore scrolling/).first()).toBeVisible(); - // Nothing is changed before approval. await expect(page.locator('#adb-wall')).toBeVisible(); await popup.getByRole('button', { name: 'Apply reversible fix' }).click(); @@ -60,12 +54,11 @@ test.describe('popup', () => { ]); await page.reload(); - await expect(page.locator('#adb-wall')).toBeVisible(); // reload restores the page + await expect(page.locator('#adb-wall')).toBeVisible(); await popup.reload(); await expect(popup.getByLabel('Page status').getByText('Saved fix applied')).toBeVisible(); await expect(page.locator('#adb-wall')).toBeHidden(); - // "Undo and stop fixing this site" disables the rule. await popup.getByRole('button', { name: 'Undo and stop fixing this site' }).click(); await expect(page.locator('#adb-wall')).toBeVisible(); const after = await ext.data<{ enabled: boolean }[]>({ type: 'rules/list' }); diff --git a/tests/e2e/release.spec.ts b/tests/e2e/release.spec.ts index 803eefc..13e780c 100644 --- a/tests/e2e/release.spec.ts +++ b/tests/e2e/release.spec.ts @@ -3,12 +3,7 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { fixture } from './fixtures'; -/** - * Smoke test of the production build in dist/ (built by `npm run build`), which - * has no host permissions at all. - */ test.describe('release build', () => { - // eslint-disable-next-line no-empty-pattern test('installs cleanly, opens onboarding, and cannot touch pages without the user', async ({}, testInfo) => { const extensionPath = resolve('dist'); const manifest = JSON.parse(readFileSync(resolve(extensionPath, 'manifest.json'), 'utf8')); @@ -30,7 +25,6 @@ test.describe('release build', () => { worker ??= await context.waitForEvent('serviceworker'); const id = new URL(worker.url()).host; - // Onboarding opens on first install. await expect .poll(() => context.pages().some((p) => p.url().includes(`${id}/dashboard.html#/welcome`))) .toBe(true); @@ -38,11 +32,9 @@ test.describe('release build', () => { const page = await context.newPage(); await page.goto(fixture('fullscreen-modal')); const popup = await context.newPage(); - // Without a toolbar click there is no activeTab grant, so the page is out of reach. await popup.goto(`chrome-extension://${id}/popup.html`); const target = await popup.evaluate(async () => { const tabs = await chrome.tabs.query({}); - // URLs of other tabs are hidden without host permission or the tabs permission. return { visibleUrls: tabs.filter((t) => t.url?.startsWith('http')).length, ids: tabs.map((t) => t.id!), @@ -57,7 +49,6 @@ test.describe('release build', () => { ); expect(res.ok).toBe(false); } - // The page was not modified. await expect(page.locator('#adb-wall')).toBeVisible(); expect(await page.locator('shieldfix-notice').count()).toBe(0); expect(errors).toEqual([]); diff --git a/tests/e2e/server.mjs b/tests/e2e/server.mjs index a7a29ae..7c2b61e 100644 --- a/tests/e2e/server.mjs +++ b/tests/e2e/server.mjs @@ -1,5 +1,4 @@ #!/usr/bin/env node -/** Minimal static server for browser-test fixtures (127.0.0.1 only). */ import { createServer } from 'node:http'; import { readFile } from 'node:fs/promises'; import { dirname, extname, join, normalize, resolve } from 'node:path'; diff --git a/tests/fixtures/churn.html b/tests/fixtures/churn.html index 680aee7..4b407dd 100644 --- a/tests/fixtures/churn.html +++ b/tests/fixtures/churn.html @@ -9,7 +9,6 @@
Live Ticker