From 47aefc1845e4d7abf12affb02e3f836a506ad024 Mon Sep 17 00:00:00 2001 From: poli0981 <127664709+poli0981@users.noreply.github.com> Date: Thu, 29 Oct 2026 03:05:51 +0700 Subject: [PATCH] fix(security): typed diagnostics, wider gates, default-src 'none', Sonar job split MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Findings 5–9 of the security review of 1.1.0. None broke the zero-network or permission promises of the shipped build; each made a claim stronger than the code behind it. - Diagnostics: every DiagEvent string field is now a union of fixed values (import phases, FileFormat, the ErrorKeys describeError returns, the two edit actions, the three storage issues), and error names pass an allowlist, logged as 'other' otherwise. `@ts-expect-error` cases keep a title from compiling instead of trusting review. - guard.mjs: optional-chained computed access on globals, `Reflect`, and member names assembled from strings or templates (`el['inner' + 'HTML']`) all got past it. - check-manifest.mjs: the bundle is scanned for the same identifiers as the source, as bare words — `fetch.call`, aliases, RTCPeerConnection and importScripts shipped unseen — and every src/href in the built pages must exist inside the package. - CSP: `default-src 'none'` closes everything unlisted. Every directive the pages use is listed, so nothing changes for them; the harness pages load with no violation. - screenshots.mjs: listens on 127.0.0.1 only, checks `OUT + sep` rather than a bare prefix, decodes paths safely, and runs Chrome asynchronously — the synchronous exec blocked the very server Chrome was waiting on, so `--shoot` hung forever. - SonarCloud: coverage runs in a job with no secret; the scan job installs nothing and receives lcov as an artifact. A job's secrets are readable by every step on its runner. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/sonarcloud.yml | 45 ++++++++++-- scripts/check-manifest.mjs | 51 +++++++++++--- scripts/guard.mjs | 23 +++++- scripts/screenshots.mjs | 85 ++++++++++++++++------- src/lib/browser/describe-error.ts | 31 ++++++--- src/lib/browser/diagnostics.ts | 82 ++++++++++++++++++---- tests/unit/browser/diagnostics.test.ts | 33 ++++++++- tests/unit/manifest.test.ts | 5 +- tests/unit/scripts/check-manifest.test.ts | 33 +++++++-- tests/unit/scripts/guard.test.ts | 23 ++++++ wxt.config.ts | 10 +-- 11 files changed, 345 insertions(+), 76 deletions(-) diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 28e4d1e..57981c2 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -5,6 +5,13 @@ # protection reads ("Quality gates", "Build + package / build"). The verdict # reaches the PR through the SonarCloud GitHub App's own check. # +# Two jobs, so the token never shares a runner with dependency code. Secrets +# are loaded into the runner for the whole job, and a step can read them from +# the runner process whatever its own `env:` says — the shape of the March 2025 +# tj-actions compromise. So `coverage` installs and runs the dev dependencies +# with no secret at all, and `scan` installs nothing: it gets the lcov report as +# an artifact. +# # ⚠️ Prerequisite: Automatic Analysis is OFF in the SonarCloud project # (Administration → Analysis Method). With it on, the scanner refuses to run. name: SonarCloud @@ -22,8 +29,8 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - analyze: - name: SonarCloud analysis + coverage: + name: Coverage for SonarCloud runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -31,8 +38,6 @@ jobs: steps: - uses: actions/checkout@v7 with: - # Full history: Sonar's new-code detection and blame need it. - fetch-depth: 0 persist-credentials: false - uses: actions/setup-node@v7 with: @@ -48,13 +53,39 @@ jobs: # lcov for Sonar; the docs/11 §1 thresholds still gate core here too. - run: npm run coverage + - uses: actions/upload-artifact@v7 + with: + name: lcov + path: coverage/lcov.info + retention-days: 1 + if-no-files-found: error + + scan: + name: SonarCloud analysis + needs: coverage + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@v7 + with: + # Full history: Sonar's new-code detection and blame need it. + fetch-depth: 0 + persist-credentials: false + + - uses: actions/download-artifact@v8 + with: + name: lcov + path: coverage + + # No npm here: the runner's own Node reads one field of a JSON file. - name: Read the package version id: pkg run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT" - # The token is scoped to the two steps that need it, so the install and - # the test run above never see it. Dependabot and fork PRs get no repo - # secrets at all: they skip the scan with a notice instead of failing. + # Dependabot and fork PRs get no repo secrets at all: they skip the scan + # with a notice instead of failing. - name: Check for SONAR_TOKEN id: token env: diff --git a/scripts/check-manifest.mjs b/scripts/check-manifest.mjs index 1dac300..5da83e5 100644 --- a/scripts/check-manifest.mjs +++ b/scripts/check-manifest.mjs @@ -13,8 +13,10 @@ * 1. the manifest: MV3, the exact permission list, the exact top-level key * set, the Chrome floor, and the exact extension-page CSP; * 2. the file inventory: every file the manifest or the pages point at exists - * (WXT drops `_locales/` and `icon/` silently when publicDir is wrong); - * 3. the bundle: no network API anywhere in the shipped JavaScript. + * (WXT drops `_locales/` and `icon/` silently when publicDir is wrong), + * and no page points anywhere but inside the package; + * 3. the bundle: none of the network identifiers `npm run guard` bans in the + * source, anywhere in the shipped JavaScript. * * Usage: node scripts/check-manifest.mjs — checks /.output/chrome-mv3, * resolved from this file, not the cwd. It takes no arguments on purpose: a @@ -36,9 +38,9 @@ const CHROME_FLOOR = '136'; * It may only ever get stricter. Never add 'unsafe-eval' or a remote source. */ const EXPECTED_CSP = - "script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:; " + - "style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none'; " + - "worker-src 'self'; form-action 'none'; base-uri 'none'"; + "default-src 'none'; script-src 'self'; object-src 'none'; connect-src 'none'; " + + "img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self'; " + + "media-src 'none'; frame-src 'none'; worker-src 'self'; form-action 'none'; base-uri 'none'"; /** * The exact top-level key set the build is expected to emit. @@ -95,10 +97,16 @@ const REQUIRED_FILES = [ /** * Network APIs that must not appear in the shipped JavaScript — including code * that arrived through a dependency, which `npm run guard` (source only) never - * sees. The CSP would refuse these at runtime; this refuses to ship them. + * sees. The same identifiers the source gate bans, matched as bare words: until + * v1.1.0 only `fetch(` counted, so `fetch.call(…)`, an alias, WebRTC and + * `importScripts` shipped unseen. WebRTC matters most — no CSP directive Chrome + * enforces governs it. */ const NETWORK_IN_BUNDLE = - /\bfetch\s*\(|\bXMLHttpRequest\b|\bWebSocket\b|\bEventSource\b|\bsendBeacon\b|\bWebTransport\b/; + /\b(?:fetch|XMLHttpRequest|WebSocket|WebTransport|EventSource|sendBeacon|RTCPeerConnection|importScripts)\b/; + +/** `src`/`href` values in a built page. Vite writes them double-quoted. */ +const PAGE_REFS = /\b(?:src|href)="([^"]*)"/g; /** @param {string} a @param {string} b */ const byName = (a, b) => a.localeCompare(b, 'en'); @@ -175,9 +183,36 @@ function referencedFiles(manifest) { ); } +/** + * What the built pages load: every `src`/`href` must be a path inside the + * package. A page pointing outside it would be a remote load (which the CSP + * refuses at runtime) or a file the build forgot (a blank page). + * + * @param {string} outDir @param {string[]} problems @returns {string[]} + */ +function pageReferences(outDir, problems) { + const refs = []; + for (const page of listFiles(outDir).filter((f) => f.endsWith('.html'))) { + const rel = relative(outDir, page).replace(/\\/g, '/'); + for (const [, ref = ''] of readFileSync(page, 'utf8').matchAll(PAGE_REFS)) { + if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(ref)) { + problems.push(`${rel} loads "${ref}" from outside the package (docs/08 §3)`); + } else if (ref !== '' && !ref.startsWith('#')) { + refs.push(ref.split(/[?#]/)[0] ?? ''); + } + } + } + return refs; +} + /** @param {string} outDir @param {Record} manifest @param {string[]} problems */ function checkInventory(outDir, manifest, problems) { - for (const file of [...REQUIRED_FILES, ...referencedFiles(manifest)]) { + const files = [ + ...REQUIRED_FILES, + ...referencedFiles(manifest), + ...pageReferences(outDir, problems), + ]; + for (const file of new Set(files)) { const path = join(outDir, file.replace(/^\//, '')); if (!existsSync(path)) problems.push(`missing file in the build: ${file}`); } diff --git a/scripts/guard.mjs b/scripts/guard.mjs index 44e4e3a..5e1cef7 100644 --- a/scripts/guard.mjs +++ b/scripts/guard.mjs @@ -75,8 +75,13 @@ const RULES = [ ['network', 'RTCPeerConnection', /\bRTCPeerConnection\b/g], ['network', 'importScripts', /\bimportScripts\b/g], // `globalThis['fe' + 'tch']` — computed access on a global is how every - // identifier rule above is evaded, so it is banned as a shape. - ['network', 'computed global access', /\b(?:globalThis|window|self|navigator|document)\s*\[/g], + // identifier rule above is evaded, so it is banned as a shape, optional + // chaining included (`globalThis?.['fe' + 'tch']` got through until v1.1.0). + [ + 'network', + 'computed global access', + /\b(?:globalThis|window|self|navigator|document)(?:\s*\?\.)?\s*\[/g, + ], // Resource hints fetch ahead of time. These words have no use in this // extension, so they are banned outright; `preload` is ordinary English, so // only as a rel value. @@ -119,6 +124,20 @@ const RULES = [ ['raw HTML', 'createContextualFragment', /\bcreateContextualFragment\b/g], ['raw HTML', 'srcdoc', /\bsrcdoc\b/gi], ['raw HTML', 'document.write', /\bdocument\s*\.\s*write(?:ln)?\b/g], + // Evasion. Every rule above matches a NAME; these are the ways of using a + // member without writing its name. `Reflect.get(globalThis, 'fe' + 'tch')` + // and `Reflect.set(el, 'outer' + 'HTML', h)` reach anything, and nothing + // here needs Reflect at all. + ['evasion', 'Reflect', /\bReflect\b/g], + // `el['inner' + 'HTML']`, `el?.[`inner${x}`]`: a member name assembled at + // runtime is only ever written to hide it. Only after something a member + // access can follow (an identifier, `)`, `]`, `?.`), so array literals such + // as `[`.${ext}`]` stay allowed. + [ + 'evasion', + 'assembled member name', + /[\w$)\].]\s*\[\s*(?:(?:'[^'\n]*'|"[^"\n]*"|`[^`\n]*`)\s*\+|`[^`\n]*\$\{)/g, + ], ]; /** @param {string[]} argv */ diff --git a/scripts/screenshots.mjs b/scripts/screenshots.mjs index 6a428b4..5a9e791 100644 --- a/scripts/screenshots.mjs +++ b/scripts/screenshots.mjs @@ -20,19 +20,24 @@ * install paths) headless, on a throwaway profile — never the user's own: * every route × theme × language at 1280×800 into `.output/qa-screens/` (for * review, git-ignored), the README set into `capture/`, and the store set into - * `store/screenshots/`. Dev tool only: nothing here ships, and it never touches - * the network beyond localhost. + * `store/screenshots/`. Dev tool only: nothing here ships, the server listens + * on 127.0.0.1 alone, and it never touches the network beyond it. */ -import { execFileSync } from 'node:child_process'; +import { execFile } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { createServer } from 'node:http'; import { tmpdir } from 'node:os'; -import { extname, join, normalize, resolve } from 'node:path'; +import { extname, join, normalize, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +const run = promisify(execFile); const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); const OUT = join(ROOT, '.output', 'chrome-mv3'); const PORT = Number(process.env.PORT ?? 4318); +/** Loopback only: the harness serves the build and a fake API to this machine, nobody else. */ +const HOST = '127.0.0.1'; const TYPES = /** @type {Record} */ ({ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', @@ -100,7 +105,7 @@ function shim() { bookmarks, storage, runtime: { id: 'harness', getManifest: () => manifest, getURL: (p) => location.origin + (p.startsWith('/') ? p : '/' + p), getContexts: async () => [], lastError: undefined }, i18n: { getUILanguage: () => lang, getMessage: (k) => k }, - tabs: { create: async () => ({}), update: async () => ({}) }, + tabs: { create: async () => ({}), update: async () => ({}), getCurrent: async () => ({ id: 1 }) }, windows: { update: async () => ({}) }, }; })();`; @@ -109,13 +114,22 @@ function shim() { function serve() { const csp = productionCsp(); const server = createServer((req, res) => { - const url = new URL(req.url ?? '/', `http://localhost:${PORT}`); + const url = new URL(req.url ?? '/', `http://${HOST}:${PORT}`); if (url.pathname === '/__shim.js') { res.writeHead(200, { 'content-type': TYPES['.js'] ?? '' }).end(shim()); return; } - const path = normalize(join(OUT, decodeURIComponent(url.pathname))); - if (!path.startsWith(OUT) || !existsSync(path)) { + let decoded; + try { + decoded = decodeURIComponent(url.pathname); + } catch { + // A malformed escape (`%E0%A4%A`) used to throw out of the handler. + res.writeHead(400).end('bad request'); + return; + } + const path = normalize(join(OUT, decoded)); + // `OUT + sep`, not `OUT`: a bare prefix test also let `chrome-mv3-evil/…` through. + if ((path !== OUT && !path.startsWith(OUT + sep)) || !existsSync(path)) { res.writeHead(404).end('not found'); return; } @@ -127,7 +141,9 @@ function serve() { } res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }).end(body); }); - server.listen(PORT, () => console.log(`harness: http://localhost:${PORT}/manager.html#import`)); + server.listen(PORT, HOST, () => + console.log(`harness: http://${HOST}:${PORT}/manager.html#import`), + ); return server; } @@ -144,21 +160,30 @@ function findChrome() { } /** + * One headless screenshot. Asynchronous on purpose: the server answering + * Chrome's requests runs in this same process, and 1.1.0's first cut used + * `execFileSync`, which blocked the event loop — Chrome waited for a page the + * blocked server could never send, and `--shoot` hung forever. + * * @param {string} chrome @param {string} profile @param {string} url * @param {string} file @param {string} size */ -function shoot(chrome, profile, url, file, size) { - execFileSync(chrome, [ - '--headless=new', - `--user-data-dir=${profile}`, - '--no-first-run', - '--disable-gpu', - '--hide-scrollbars', - `--window-size=${size}`, - '--virtual-time-budget=4000', - `--screenshot=${file}`, - url, - ]); +async function shoot(chrome, profile, url, file, size) { + await run( + chrome, + [ + '--headless=new', + `--user-data-dir=${profile}`, + '--no-first-run', + '--disable-gpu', + '--hide-scrollbars', + `--window-size=${size}`, + '--virtual-time-budget=4000', + `--screenshot=${file}`, + url, + ], + { timeout: 60_000 }, + ); } if (!existsSync(join(OUT, 'manifest.json'))) { @@ -179,19 +204,25 @@ if (!existsSync(join(OUT, 'manifest.json'))) { for (const dir of [qa, capture, store]) mkdirSync(dir, { recursive: true }); const profile = mkdtempSync(join(tmpdir(), 'bookmarkmagic-harness-')); const page = (/** @type {string} */ query, /** @type {string} */ route) => - `http://localhost:${PORT}/manager.html?${query}#${route}`; + `http://${HOST}:${PORT}/manager.html?${query}#${route}`; const ROUTES = ['import', 'export', 'edit', 'settings', 'about']; try { for (const lang of ['en', 'vi', 'ja']) { for (const theme of ['light', 'dark']) { for (const route of ROUTES) { const file = join(qa, `${route}-${theme}-${lang}.png`); - shoot(chrome, profile, page(`theme=${theme}&lang=${lang}`, route), file, '1280,800'); + await shoot( + chrome, + profile, + page(`theme=${theme}&lang=${lang}`, route), + file, + '1280,800', + ); } } } for (const route of ROUTES) { - shoot( + await shoot( chrome, profile, page('theme=light&lang=en', route), @@ -200,7 +231,7 @@ if (!existsSync(join(OUT, 'manifest.json'))) { ); } for (const route of ['edit', 'export', 'import']) { - shoot( + await shoot( chrome, profile, page('theme=dark&lang=en', route), @@ -208,10 +239,10 @@ if (!existsSync(join(OUT, 'manifest.json'))) { '1280,800', ); } - shoot( + await shoot( chrome, profile, - `http://localhost:${PORT}/popup.html?theme=light&lang=en`, + `http://${HOST}:${PORT}/popup.html?theme=light&lang=en`, join(capture, 'popup.png'), '360,420', ); diff --git a/src/lib/browser/describe-error.ts b/src/lib/browser/describe-error.ts index 1046eef..abdcac1 100644 --- a/src/lib/browser/describe-error.ts +++ b/src/lib/browser/describe-error.ts @@ -20,13 +20,30 @@ * Lives in `browser/` because that is where the error taxonomy lives; * `browser/` may import `core/`, not the reverse (docs/02 §3). */ -import { BmParseError } from '../core/model'; -import { record } from './diagnostics'; -import { BmBackupError, BmBrowserError, BmEnvError, BmPartialWrite } from './errors'; +import { BmParseError, type BmParseErrorCode } from '../core/model'; +import { errorName, record } from './diagnostics'; +import { + BmBackupError, + type BmBackupErrorCode, + BmBrowserError, + type BmEnvCode, + BmEnvError, + BmPartialWrite, +} from './errors'; + +/** Every key `describeError` can return — and so every code the diagnostics log can hold. */ +export type ErrorKey = `errors.${ + | BmParseErrorCode + | BmBackupErrorCode + | BmEnvCode + | 'PARTIAL_CLEAR' + | 'PARTIAL_WRITE' + | 'BROWSER' + | 'UNKNOWN'}`; export interface DescribedError { /** Dotted i18n path, e.g. `errors.TOO_DEEP`. */ - messageKey: string; + messageKey: ErrorKey; /** Raw, untranslated technical text for the copyable detail block. */ detail?: string | undefined; /** Nodes written before a partial failure, when the failure knows. */ @@ -39,11 +56,7 @@ export function describeError(err: unknown): DescribedError { const described = describe(err); // Every failure the UI shows passes through here, so this is where the // diagnostics log learns of it — by code, never by its detail text. - record({ - kind: 'failure', - where: err instanceof Error ? err.name : typeof err, - code: described.messageKey, - }); + record({ kind: 'failure', where: errorName(err), code: described.messageKey }); return described; } diff --git a/src/lib/browser/diagnostics.ts b/src/lib/browser/diagnostics.ts index ed4a738..7ebf9dc 100644 --- a/src/lib/browser/diagnostics.ts +++ b/src/lib/browser/diagnostics.ts @@ -7,18 +7,79 @@ * issue themselves. * Guarantees: in memory only, never written to storage, never sent anywhere * (there is no network). Entries are an allowlist of codes, counts and - * phase names: an event type cannot carry a title, an address or a file - * path, and free-text `detail` strings from the browser are never recorded — + * phase names, and the TYPES enforce it: every string field is a union of + * fixed values, so a title, an address or a file path does not compile — + * 1.1.0's first cut typed them all `string` and only promised it (v1.1.0 + * review). Free-text `detail` strings from the browser are never recorded; * they can quote a URL. */ +import type { FileFormat, MergeMode } from '../core/model'; +import type { ErrorKey } from './describe-error'; + +/** The import pipeline's milestones (`import/run-import.ts`). */ +type ImportPhase = 'parsed' | `planned:${MergeMode}` | 'backup-proven' | 'cleared' | 'written'; +type EditAction = 'keep-first' | 'sort'; +type StorageIssue = 'settings-read-failed' | 'legal-read-failed' | 'change-decode-failed'; + +/** + * Error names worth telling apart. Any other is recorded as `'other'`: a + * name is an ordinary string property, and nothing stops code from putting + * data in it. + */ +const KNOWN_ERROR_NAMES = [ + 'Error', + 'TypeError', + 'RangeError', + 'SyntaxError', + 'ReferenceError', + 'URIError', + 'AggregateError', + 'AbortError', + 'NotAllowedError', + 'NotFoundError', + 'SecurityError', + 'QuotaExceededError', + 'InvalidStateError', + 'DataCloneError', + 'BmParseError', + 'BmBackupError', + 'BmBrowserError', + 'BmEnvError', + 'BmPartialWrite', + 'BmAborted', +] as const; +const KNOWN: ReadonlySet = new Set(KNOWN_ERROR_NAMES); + +/** An allowlisted error name, `'other'`, or — for a non-Error throw — its `typeof`. */ +export type ErrorName = + | (typeof KNOWN_ERROR_NAMES)[number] + | 'other' + | 'string' + | 'number' + | 'bigint' + | 'boolean' + | 'symbol' + | 'undefined' + | 'object' + | 'function'; + +function isKnownName(name: string): name is (typeof KNOWN_ERROR_NAMES)[number] { + return KNOWN.has(name); +} + +/** What a thrown value is called in the log — never its message. */ +export function errorName(err: unknown): ErrorName { + if (err instanceof Error) return isKnownName(err.name) ? err.name : 'other'; + return typeof err; +} /** What may be recorded — nothing else type-checks. */ export type DiagEvent = - | { kind: 'import'; phase: string; format?: string; nodes?: number } - | { kind: 'failure'; where: string; code: string } - | { kind: 'edit'; action: string; count?: number } - | { kind: 'storage'; issue: string } - | { kind: 'crash'; name: string }; + | { kind: 'import'; phase: ImportPhase; format?: FileFormat; nodes?: number } + | { kind: 'failure'; where: ErrorName; code: ErrorKey } + | { kind: 'edit'; action: EditAction; count?: number } + | { kind: 'storage'; issue: StorageIssue } + | { kind: 'crash'; name: ErrorName }; interface Entry { /** Milliseconds since the page loaded — no wall-clock time is kept. */ @@ -64,13 +125,10 @@ export function installCrashHooks( target: Pick, ): () => void { const onError = (event: ErrorEvent): void => { - record({ kind: 'crash', name: event.error instanceof Error ? event.error.name : 'Error' }); + record({ kind: 'crash', name: event.error === undefined ? 'Error' : errorName(event.error) }); }; const onRejection = (event: PromiseRejectionEvent): void => { - record({ - kind: 'crash', - name: event.reason instanceof Error ? event.reason.name : typeof event.reason, - }); + record({ kind: 'crash', name: errorName(event.reason) }); }; target.addEventListener('error', onError); target.addEventListener('unhandledrejection', onRejection); diff --git a/tests/unit/browser/diagnostics.test.ts b/tests/unit/browser/diagnostics.test.ts index fbe2e89..982b299 100644 --- a/tests/unit/browser/diagnostics.test.ts +++ b/tests/unit/browser/diagnostics.test.ts @@ -1,6 +1,12 @@ import { afterEach, describe, expect, it } from 'vitest'; import { describeError } from '@/lib/browser/describe-error'; -import { clearDiagnostics, installCrashHooks, record, snapshot } from '@/lib/browser/diagnostics'; +import { + clearDiagnostics, + errorName, + installCrashHooks, + record, + snapshot, +} from '@/lib/browser/diagnostics'; import { BmParseError } from '@/lib/core/model'; const CONTEXT = { version: '1.1.0', locale: 'vi', theme: 'dark' }; @@ -59,4 +65,29 @@ describe('diagnostics', () => { ]); expect(snapshot(CONTEXT)).not.toContain('x.example'); }); + + it('names an error only from the allowlist (v1.1.0 review)', () => { + const custom = new Error('m'); + custom.name = 'https://leak.example/Jane Doe'; + expect(errorName(custom)).toBe('other'); + expect(errorName(new TypeError('x'))).toBe('TypeError'); + expect(errorName(new BmParseError('INVALID_NODE'))).toBe('BmParseError'); + expect(errorName('a string')).toBe('string'); + expect(errorName(undefined)).toBe('undefined'); + }); + + it('refuses free text at compile time — the allowlist is the type (v1.1.0 review)', () => { + const title = 'Jane Doe — payroll'; + // @ts-expect-error a title is not an import phase + record({ kind: 'import', phase: `parsed:${title}` }); + // @ts-expect-error nor a file format + record({ kind: 'import', phase: 'parsed', format: title }); + // @ts-expect-error nor an error key + record({ kind: 'failure', where: 'TypeError', code: 'https://leak.example/' }); + // @ts-expect-error nor an edit action + record({ kind: 'edit', action: title }); + // @ts-expect-error nor an error name + record({ kind: 'crash', name: title }); + expect(events()).toHaveLength(5); + }); }); diff --git a/tests/unit/manifest.test.ts b/tests/unit/manifest.test.ts index ee7831f..35a0387 100644 --- a/tests/unit/manifest.test.ts +++ b/tests/unit/manifest.test.ts @@ -100,6 +100,7 @@ describe('manifest', () => { CONFIG.indexOf("].join('; ')"), ); for (const directive of [ + "default-src 'none'", "script-src 'self'", "object-src 'none'", "connect-src 'none'", @@ -113,7 +114,9 @@ describe('manifest', () => { // never for script. expect(csp).toContain(`"style-src 'self' 'unsafe-inline'"`); const withoutInlineStyle = csp.replace(`"style-src 'self' 'unsafe-inline'"`, ''); - expect(withoutInlineStyle).not.toMatch(/unsafe-|https?:|\*|default-src/); + expect(withoutInlineStyle).not.toMatch(/unsafe-|https?:|\*/); + // `default-src` exists only to close everything unlisted — so only as 'none'. + expect(csp.match(/default-src[^"]*/g)).toEqual(["default-src 'none'"]); }); it('keeps the manifest at v3 by not overriding WXT’s default', () => { diff --git a/tests/unit/scripts/check-manifest.test.ts b/tests/unit/scripts/check-manifest.test.ts index 02faff0..55cf9e0 100644 --- a/tests/unit/scripts/check-manifest.test.ts +++ b/tests/unit/scripts/check-manifest.test.ts @@ -15,9 +15,9 @@ import { checkExtension } from '../../../scripts/check-manifest.mjs'; const SCRIPT = join(process.cwd(), 'scripts', 'check-manifest.mjs'); const CSP = - "script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:; " + - "style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none'; " + - "worker-src 'self'; form-action 'none'; base-uri 'none'"; + "default-src 'none'; script-src 'self'; object-src 'none'; connect-src 'none'; " + + "img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self'; " + + "media-src 'none'; frame-src 'none'; worker-src 'self'; form-action 'none'; base-uri 'none'"; const MANIFEST = { manifest_version: 3, @@ -35,8 +35,11 @@ const MANIFEST = { }; const FILES: Record = { - 'manager.html': '', + 'manager.html': + '' + + '', 'popup.html': '', + 'assets/manager.css': 'body{}', 'THIRD_PARTY_NOTICES.txt': 'notices', '_locales/en/messages.json': '{}', '_locales/vi/messages.json': '{}', @@ -130,14 +133,33 @@ describe('check-manifest.mjs', () => { it.each([ ['fetch', 'chunks/x.js', 'fetch("https://x.example")'], + ['fetch', 'chunks/x.js', 'const g=fetch;g.call(null,u)'], ['XMLHttpRequest', 'chunks/x.js', 'new XMLHttpRequest'], ['sendBeacon', 'assets/deep/y.js', 'navigator.sendBeacon(u)'], + ['RTCPeerConnection', 'chunks/x.js', 'new RTCPeerConnection({iceServers:[]})'], + ['importScripts', 'chunks/x.js', 'importScripts("x.js")'], ])('fails on %s anywhere in the shipped JavaScript', (api, file, code) => { const { status, output } = check(build(MANIFEST, { [file]: code })); expect(status).toBe(1); expect(output).toContain(`network API "${api}`); }); + it('fails when a page loads a file the build does not contain', () => { + const { status, output } = check(build(MANIFEST, { 'assets/manager.css': null })); + expect(status).toBe(1); + expect(output).toContain('missing file in the build: /assets/manager.css'); + }); + + it.each(['https://cdn.example/x.js', '//cdn.example/x.js'])( + 'fails when a page loads %s from outside the package', + (url) => { + const page = ``; + const { status, output } = check(build(MANIFEST, { 'popup.html': page })); + expect(status).toBe(1); + expect(output).toContain('from outside the package'); + }, + ); + it('fails clearly when there is no build at all', () => { const empty = mkdtempSync(join(tmpdir(), 'check-manifest-empty-')); dirs.push(empty); @@ -152,7 +174,8 @@ describe('check-manifest.mjs', () => { const result = spawnSync(process.execPath, [SCRIPT, '/etc'], { encoding: 'utf8' }); const output = `${result.stdout}${result.stderr}`; expect([0, 1]).toContain(result.status); - expect(output).toMatch(/check-manifest: (clean|cannot read|.*permissions)/); + // Any stated outcome: a stale build legitimately fails on whatever changed. + expect(output).toMatch(/check-manifest: \S/); expect(output).not.toContain('/etc'); }); }); diff --git a/tests/unit/scripts/guard.test.ts b/tests/unit/scripts/guard.test.ts index fcf557f..52b22c9 100644 --- a/tests/unit/scripts/guard.test.ts +++ b/tests/unit/scripts/guard.test.ts @@ -64,6 +64,23 @@ const BANNED: readonly (readonly [string, string, string, string])[] = [ "new (window['XMLHttp' + 'Request'])();", 'computed global access', ], + [ + 'optional-chained computed access', + 'a.ts', + "globalThis?.['fe' + 'tch'](u);", + 'computed global access', + ], + ['Reflect.get on a global', 'a.ts', "Reflect.get(globalThis, 'fe' + 'tch')(u);", 'Reflect'], + ['Reflect.set of a raw-HTML sink', 'a.ts', "Reflect.set(el, 'outer' + 'HTML', h);", 'Reflect'], + ['an assembled member name', 'a.ts', "el['inner' + 'HTML'] = h;", 'assembled member name'], + [ + 'an assembled member name behind ?.', + 'a.ts', + "el?.['inner' + 'HTML'] = h;", + 'assembled member name', + ], + // biome-ignore lint/suspicious/noTemplateCurlyInString: source text for the guard to scan + ['a template member name', 'a.ts', 'el[`inner${kind}`] = h;', 'assembled member name'], ['a prefetch hint in markup', 'a.svelte', '', 'resource hint'], ['a prefetch hint in code', 'a.ts', "link.rel = 'prefetch';", 'resource hint'], ['a preload rel', 'a.ts', "link.rel = 'preload';", 'resource hint'], @@ -138,6 +155,12 @@ describe('guard.mjs — things that must stay allowed', () => { 'function myFunction() {}', 'const transport = "web";', '// "network calls are banned" — prose without the API names', + // biome-ignore lint/suspicious/noTemplateCurlyInString: source text for the guard to scan + 'const accept = { [mime]: [`.${ext}`] };', + // biome-ignore lint/suspicious/noTemplateCurlyInString: source text for the guard to scan + "const lines = [`# ${title}`, ''];", + 'const first = rows?.[0];', + "const key = map[prefix + 'x'];", ].join('\n'), }; diff --git a/wxt.config.ts b/wxt.config.ts index f081722..04d0ef4 100644 --- a/wxt.config.ts +++ b/wxt.config.ts @@ -26,20 +26,22 @@ const CHROME_FLOOR = 136; * thing between the product and its "no network" claim. `connect-src 'none'` * makes Chrome itself refuse every fetch, XHR, WebSocket, EventSource and * beacon; the other directives close remote images, fonts, media, frames and - * form posts. There is deliberately no `default-src`, so Svelte's styles are - * untouched. `scripts/check-manifest.mjs` pins this exact string in the built - * manifest. + * form posts, and `default-src 'none'` closes whatever is left unlisted (web + * app manifests, prefetches). Every directive the pages use is listed, so it + * changes nothing for them — styles included. `scripts/check-manifest.mjs` + * pins this exact string in the built manifest. * * Production builds only: the dev server (`wxt`, command "serve") reloads the * extension over a localhost websocket that `connect-src 'none'` would block. */ const EXTENSION_PAGE_CSP = [ + "default-src 'none'", "script-src 'self'", "object-src 'none'", "connect-src 'none'", "img-src 'self' data: blob:", // Inline styles stay allowed (Svelte sets style attributes); remote - // stylesheets do not — with no default-src, style-src was otherwise open. + // stylesheets do not. "style-src 'self' 'unsafe-inline'", "font-src 'self'", "media-src 'none'",