diff --git a/.changeset/sourcemaps-doctor.md b/.changeset/sourcemaps-doctor.md new file mode 100644 index 00000000..6567f716 --- /dev/null +++ b/.changeset/sourcemaps-doctor.md @@ -0,0 +1,5 @@ +--- +'@bugsee/bundler-plugin-core': minor +--- + +Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`; `--json`, `--strict`, `--deployed`, `--ignore `, `--exclude `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c909a11c..fa805d79 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1532,5 +1532,8 @@ Verified against current majors, all green with no adapter code changes: `@bugse ### Debug-ID stamping inside the build for Vite, Rollup and Rspack; verified stamps; safe map deletion (2026-11-23) `@bugsee/bundler-plugin-core` now stamps INSIDE the build wherever the bundler has a pre-write hook, so Subresource Integrity hashes taken later describe the stamped bytes: webpack 5 and **Rspack** at `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1` (shared `tapProcessAssetsStamp`), **Vite and Rollup** in `generateBundle` (`order: 'pre'`; `rollupAssetStore` over chunks + `.map` assets; the stamped id is also put on `chunk.map` because Vite regenerates the map of a lazy-loading chunk after user hooks). esbuild and the standalone CLI stay post-emit with the SRI refusal (its message now names the workaround). Every stamp is verified (`verify-stamp.ts`: parses, sourceMappingURL intact, map debugId matches, original bytes + appended stamp): in-build all-or-nothing, post-emit snapshot + restore of the failing pair (`stamp-files.ts`); an in-build stamp is re-checked on disk (`verifyStampedPairs`) and against the HTML (`findIntegrityMismatches`). `.map` deletion now requires a confirmed upload AND a debugId on the map (`partitionByKeyed`). Real-build proof: `plugin.in-build.real-build.test.ts` (Vite 7 + 8, Rollup, Rspack with its built-in SRI plugin) and a Chromium run in `instrumentation-tests/test/sri-vite-rollup.e2e.ts`. Measured ordering limits and what the guards do not see: `docs/design/source-maps.md` §7.1. +### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 36 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 8: the SRI page walk follows the doctor's fence (full walk for an output directory, reported fence otherwise); docs always use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor`. Round 7: `--exclude` applies to SRI pins and map pointers, unmatched patterns are reported (`output.exclude-unmatched`), an all-unreadable output cannot pass, reads are bounded by bytes in flight, maps need `mappings`/`sections`, every distinct SRI pin is kept for the doctor, `passed` lists only checks that had input. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). + ### Next.js build integration: `withBugsee` (`@bugsee/nextjs/config`), webpack AND Turbopack (2026-11-23) `withBugsee(nextConfig, options)` makes `next build` stamp debug-IDs and upload source maps (gap #1 of the source-map gap analysis). Design + measured limits: `docs/design/source-maps.md` §7.3; user docs: `packages/nextjs/README.md`. **webpack** (`--webpack`, default <= 15): one per-compilation plugin (client, server, edge) stamping inside the compilation (`PROCESS_ASSETS_STAGE_DEV_TOOLING + 1`, SRI-safe) and uploading exactly the files that compilation emitted (`files` mode, nothing walks `.next`). The generic `@bugsee/webpack-plugin` was NOT reused for Next: measured against a real build it cannot stamp the server compilation (assets named `../app/page.js`, output path `.next/server/chunks`) and its directory-wide upload of `.next` collides across the three compilations. **Turbopack** (default 16; `--turbopack` 15.x): `compiler.runAfterProductionCompile` (15.4.0+) runs the real `inject` + upload over `.next/static` and `.next/server`, bundles paired with maps by the `sourceMappingURL` pointer (Turbopack does not name a map after its bundle; Next 15.5 shares one map between two runtime chunks, which are left unstamped with a notice). Measured limits: Turbopack writes the SRI hashes BEFORE the hook, so an `experimental.sri` Turbopack build is left unmodified with a notice (webpack handles SRI); Next 16 errors on a `webpack` function without a `turbopack` config, so none is added on Turbopack builds; `compiler.define` (not `defineServer`) bakes the app identity. Policy: browser maps deleted after a confirmed upload, server/edge maps kept (`deleteServerMaps`). Composes with a user's `webpack`, `compiler.runAfterProductionCompile`, `compiler.define`, `productionBrowserSourceMaps`, function/async configs; inert for dev/start/export. Core change: `@bugsee/bundler-plugin-core` now also exports `stampAssets`, `AssetStore`, `notify`, `resolveIdentity`, `loadBuildPluginEnv`, `mergeBuildPluginEnv`. Found by the independent reviews and fixed: stamped webpack assets are written as STRING sources (a Buffer is opaque to webpack's RealContentHashPlugin, which renames `[contenthash]` chunks after the stamp, so every lazy chunk 404'd; the e2e now opens each build in headless Chromium and asserts the lazy chunk runs), the baked define is the RAW value (Next JSON-encodes `compiler.define` itself; a JSON string arrived double-quoted), own-files-only deletion on Turbopack, contained post-build hook, version floors (hook 15.4.0, define 15.1.0), idempotent application. Real builds (`@bugsee/nextjs-e2e`, `test/source-maps.e2e.ts`, `next` 15.5.28 and 16.4.6 x webpack/Turbopack + SRI cases, real `bugsee-cli`, mock collector, `next start` smoke): see the PR for the run. diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 8a8afa48..3f0d1fa9 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -220,3 +220,35 @@ stub the SDK reads. This is exactly what the plugins automate; the CLI is the sa - **Not covered: bytecode targets.** React-Native/Hermes compiles JS → bytecode, which drops the injected comment and stub, so the running code reports no debug-ID. That needs a Hermes-specific compose flow and is handled by the separate React-Native SDK, not this (web/node/bun) SDK. + +## 4. Check a build: `bugsee-sourcemaps-doctor` + +When a production crash does not de-minify, run the doctor against the build output you actually deployed (or are about to). It is offline: it reads the files and makes no network call. The token is only looked up (never printed) so the report can say where it comes from; a missing token is a warning, not an error. + +```bash +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist # readable report, fix hint per finding +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --json # for CI (schemaVersion 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exit 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn +``` + +The binary ships in `@bugsee/bundler-plugin-core`, so always name the package as above (a bare `npx bugsee-sourcemaps-doctor` is only safe when it is already linked into `node_modules/.bin`, which pnpm and Yarn do for direct dependencies only; otherwise npx asks the public registry for an unrelated name). + +`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped) when the directory holds only what the build emitted. Scripts copied in (Vite `publicDir`, a copy plugin) are never stamped by the plugin and are indistinguishable from a bundle that lost its stamp: exclude them by path, relative to the checked directory (Vite copies `public/` to the ROOT of the output, so `--exclude sw.js --exclude 'pdf.worker.min.mjs*'`; repeatable; listed as `output.excluded`, and a pattern that matches nothing is reported as `output.exclude-unmatched`). `--exclude` only removes files from the audit, not from what you deploy. A directory that is a project (has a `package.json`) and is the working directory is walked fenced (no `src`, `test`, dot-directories, depth > 6), and the skipped directories are listed as `output.walk-fenced`. Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. + +Exit codes: `0` ok, `1` warnings only (with `--strict`), `2` errors. The package is `@bugsee/bundler-plugin-core`; the same report is available in code as `diagnoseBuildOutput(dir, options)`. + +Typical findings and what to do: + +| ID | Meaning | +|---|---| +| `stamp.missing-debug-id` / `stamp.missing-registration` | A bundle is not stamped (or only has the comment, not the runtime registration). Add the plugin, or run `bugsee-cli sourcemaps inject ` after the build. | +| `stamp.map-id-mismatch` / `stamp.map-no-debug-id` | The map's `debugId` is not the bundle's. A step ran after stamping; stamp last. | +| `map.pointer-dangling` | The bundle's `sourceMappingURL` points at a map that is not on disk. A note when no `.map` is left and every bundle is stamped (maps removed after upload); otherwise a warning. Use hidden maps to avoid the 404. | +| `map.inline` | The map is a `data:` URL inside the bundle: nothing to upload, and it ships to every visitor. | +| `map.sources-unresolvable` | No `sourcesContent` and the sources are not on disk: frames will have no source lines. | +| `map.public-leftover` | `.map` files are in the directory. A note by default; a warning with `--deployed` (you serve this directory). Keep `deleteMaps` on, or remove the maps / leave them out of the deploy (`--exclude` does not help: it only hides them from this audit). | +| `sri.unstamped-hazard` / `sri.mismatch` / `sri.manifest-hashes` | Subresource Integrity hashes pin these scripts; stamping after hashing makes the browser block them. | +| `env.token-missing` | No app token is visible to the build (a warning): the plugin is disabled and uploads nothing, which is fine if you upload with `bugsee-cli` by hand. `env.token-source` says where a found token comes from, never its value. | + +The doctor reports which source supplied the token (`env.token-source`: option, environment variable or `.env.bugsee-build-plugin`), never the token. It reads only regular files inside the directory you give it and checks a map's size before reading it. Checks that need the backend (is the map for this ID uploaded? does the deployed URL serve a stamped bundle?) are not part of this command yet. diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 7292cecf..a08d9de2 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -20,7 +20,23 @@ npm install --save-dev @bugsee/vite-plugin - Settings lookup order: plugin option, then the process environment, then the nearest `.env.bugsee-build-plugin` (only `BUGSEE_APP_TOKEN` / `BUGSEE_APP_VERSION` / `BUGSEE_APP_BUILD` are read from it; searched from the bundler's project directory up to the repo/workspace root, never in or above the home directory; fills gaps only, a blank variable counts as unset; a missing or malformed file never fails the build). Details: `docs/source-maps-usage.md`. - Option resolution (`appToken`, `appVersion`, `appBuild`, `endpoint`, `deleteMaps`, `dryRun`, `disabled`, with environment fallbacks such as `BUGSEE_APP_TOKEN`; the version also falls back to the nearest `package.json` above the bundler's project directory (blank values count as unset; Rollup, which reports no project directory, walks up from the output directory and skips a name-less, version-less marker such as a `dist/cjs/package.json` holding only `{"type":"commonjs"}`), the build to a CI commit id, and a real value is baked into the app bundle as `__BUGSEE_APP_VERSION__` / `__BUGSEE_APP_BUILD__` for the runtime SDK: through `define` on Vite, esbuild, webpack 5 and Rspack, and by rewriting each rendered chunk (with a source map) on Rollup; webpack 4 cannot bake, so there only an explicit value is recorded; a constant you define yourself is what gets recorded when it is a plain string), build-commit detection and the CLI runner. -The programmatic API beyond the plugins is internal and may change between releases. +## `bugsee-sourcemaps-doctor` + +An offline check of a build output directory: why would a crash from this build not symbolicate? No network call; a token is not required (a missing one is only a warning). + +```bash +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist # human report +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVersion 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too +``` + +The binary ships in `@bugsee/bundler-plugin-core`, not in a package of its own name, so always name the package (a bare `npx bugsee-sourcemaps-doctor` asks the public registry for an unrelated, unclaimed name unless it happens to be linked into `node_modules/.bin`; pnpm and Yarn link only the bins of direct dependencies). With the package as a direct dependency, `pnpm exec bugsee-sourcemaps-doctor dist` works too. + +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--exclude ` (files the build did not emit, e.g. `sw.js` or `pdf.worker.min.mjs*` for scripts copied from Vite's `publicDir` (it lands at the ROOT of the output) or by a copy plugin, relative to the checked directory, a leading `./` is fine; a pattern that matches nothing is reported as `output.exclude-unmatched`: the plugin never stamps those and a doctor cannot tell them from a bundle that lost its stamp; repeatable; `*` stays in a directory, `**` crosses them; matches are listed as `output.excluded`), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes for a build whose output directory holds only what the build emitted (add `--exclude` for copied-in scripts): leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. + +It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (pages and `*manifest*.json` inside the directory only; a page larger than 8 MiB is reported, not scanned); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. When the checked directory is itself a project directory (has a `package.json`) and is, or contains, the working directory, the walk skips `src`/`test`/dot-directories and stops below depth 6 so it stays out of a source tree; the skipped directories are listed as `output.walk-fenced`, never silent. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never opens a FIFO, socket or device (they are reported), reads a symlink only when its real path stays inside the checked directory (a pnpm-style `assets/app.js -> ../.store/app.js` is fine; one that leads out, dangles or loops is reported), judges type and size on the open file descriptor, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. + +The rest of the programmatic API beyond the plugins and the doctor is internal and may change between releases. ## Links diff --git a/packages/bundler-plugin-core/package.json b/packages/bundler-plugin-core/package.json index cdb887ae..a9905236 100644 --- a/packages/bundler-plugin-core/package.json +++ b/packages/bundler-plugin-core/package.json @@ -22,7 +22,7 @@ ], "sideEffects": false, "scripts": { - "build": "tsup", + "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup", "typecheck": "tsc --noEmit", "test": "vitest run", "test:coverage": "vitest run --coverage" @@ -44,6 +44,9 @@ "vite7": "npm:vite@7.3.6" }, "publishConfig": { + "bin": { + "bugsee-sourcemaps-doctor": "./dist/doctor-cli.js" + }, "main": "./dist/index.cjs", "module": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts new file mode 100644 index 00000000..5fd416d8 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -0,0 +1,285 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { DOCTOR_USAGE, runDoctorCli } from './doctor-cli'; + +const ID = '11111111-1111-4111-8111-111111111111'; +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-cli-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), '{"name":"a","version":"1.0.0"}'); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const stamped = `x\n!function(){globalThis._bugseeDebugIds={}}();\n//# debugId=${ID}\n`; + +async function cli(argv: string[], env = { BUGSEE_APP_TOKEN: 't', BUGSEE_APP_BUILD: 'b' }) { + let out = ''; + let err = ''; + const code = await runDoctorCli(argv, { + stdout: (t) => (out += t), + stderr: (t) => (err += t), + env, + }); + return { code, out, err }; +} + +describe('runDoctorCli --exclude', () => { + it('drops matching files before analysis; repeatable; needs a value', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + mkdirSync(join(dist, 'public')); + writeFileSync(join(dist, 'public', 'sw.js'), 'x'); + writeFileSync(join(dist, 'vendor.js'), 'x'); + expect((await cli([dist, '--no-env', '--json'])).code).toBe(0); + const ids = async (args: string[]) => + JSON.parse((await cli([dist, '--no-env', '--json', ...args])).out).findings.map( + (f: { id: string }) => f.id, + ); + expect(await ids(['--exclude', 'public/**'])).toContain('output.excluded'); + expect(await ids(['--exclude', 'public/**'])).toContain('stamp.missing-debug-id'); // vendor.js remains + const both = await ids(['--exclude=public/**', '--exclude', 'vendor.js']); + expect(both).not.toContain('stamp.missing-debug-id'); + expect(both).not.toContain('stamp.mixed'); + expect((await cli([dist, '--exclude'])).code).toBe(2); + }); +}); + +describe('runDoctorCli', () => { + it('prints the text report and exits 0 for a clean build', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code, out, err } = await cli([dist, '--project-root', root]); + expect(code).toBe(0); + expect(out).toContain('The app token comes from the BUGSEE_APP_TOKEN environment variable.'); + expect(out).not.toContain('t,'); // the value is never printed + expect(err).toBe(''); + }); + + it('--json prints a parseable report; exit 2 on errors', async () => { + writeFileSync(join(dist, 'a.js'), 'x\n//# sourceMappingURL=a.js.map'); + writeFileSync(join(dist, 'a.js.map'), '{"version":3,"sources":["a"]}'); + const { code, out } = await cli([dist, '--json', '--no-env']); + expect(code).toBe(2); + const report = JSON.parse(out); + expect(report.schemaVersion).toBe(1); + expect(report.findings.map((f: { id: string }) => f.id)).toContain('stamp.missing-debug-id'); + }); + + it('--strict turns warnings into exit 1; without it they are exit 0', async () => { + writeFileSync(join(dist, 'vendor.js'), 'x'); + expect((await cli([dist, '--no-env'])).code).toBe(0); + expect((await cli([dist, '--no-env', '--strict'])).code).toBe(1); + }); + + it('a missing token is a warning (exit 0; 1 under --strict); --no-env drops the check', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const base = [dist, '--project-root', root, '--json']; + const warned = await cli(base, {} as never); + expect(warned.code).toBe(0); + expect(JSON.parse(warned.out).findings.map((f: { id: string }) => f.id)).toContain( + 'env.token-missing', + ); + expect((await cli([...base, '--strict'], {} as never)).code).toBe(1); + const skipped = await cli([...base, '--no-env', '--strict'], {} as never); + expect(skipped.code).toBe(0); + }); + + it('--strict passes straight after a plugin run: stamped bundle, maps removed, pointer left', async () => { + writeFileSync(join(dist, 'a.js'), `x\n//# sourceMappingURL=a.js.map${stamped}`); + const { code } = await cli([dist, '--project-root', root, '--strict']); + expect(code).toBe(0); + }); + + it('--deployed makes leftover maps a warning; --ignore drops an ID (repeatable)', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'], + mappings: 'AAAA', + }), + ); + const args = [dist, '--no-env', '--strict']; + expect((await cli(args)).code).toBe(0); + expect((await cli([...args, '--deployed'])).code).toBe(1); + const ignored = await cli([ + ...args, + '--deployed', + '--ignore', + 'map.public-leftover', + '--ignore', + 'x', + '--json', + ]); + expect(ignored.code).toBe(0); + expect(JSON.parse(ignored.out).ignored).toEqual(['map.public-leftover']); + }); + + it('`--` ends options, so a directory can start with a dash', async () => { + const odd = join(root, '-odd'); + mkdirSync(odd); + writeFileSync(join(odd, 'a.js'), stamped); + const { code, out } = await cli(['--no-env', '--', odd]); + expect(code).toBe(0); + expect(out).toContain('1 bundle(s)'); + expect((await cli(['--', odd, 'second'])).code).toBe(2); + }); + + it('a single-dash unknown flag is rejected, not taken for the directory', async () => { + const { code, err } = await cli(['-x', dist]); + expect(code).toBe(2); + expect(err).toContain('Unknown option -x'); + }); + + it('--max-map-mb sets the large-map threshold', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'.repeat(2000)], + }), + ); + const small = await cli([dist, '--no-env', '--max-map-mb', '0.001', '--json']); + expect(JSON.parse(small.out).findings.map((f: { id: string }) => f.id)).toContain( + 'map.too-large', + ); + // 2000 bytes against 1 MiB: only the right unit (MiB, not KiB) leaves it unflagged + const oneMb = await cli([dist, '--no-env', '--max-map-mb', '1', '--json']); + expect(JSON.parse(oneMb.out).findings.map((f: { id: string }) => f.id)).not.toContain( + 'map.too-large', + ); + const big = await cli([dist, '--no-env', '--json']); + expect(JSON.parse(big.out).findings.map((f: { id: string }) => f.id)).not.toContain( + 'map.too-large', + ); + }); + + it('--key=value forms work for every option that takes a value', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'.repeat(2000)], + }), + ); + const small = await cli([dist, '--no-env', '--max-map-mb=0.001', '--json']); + expect(JSON.parse(small.out).findings.map((f: { id: string }) => f.id)).toContain( + 'map.too-large', + ); + const ignored = await cli([ + dist, + '--no-env', + '--ignore=map.public-leftover', + `--project-root=${root}`, + '--json', + ]); + expect(JSON.parse(ignored.out).ignored).toEqual(['map.public-leftover']); + expect((await cli([dist, '--max-map-mb='])).code).toBe(2); + }); + + it('`--=x` is an unknown option, not the end-of-options marker', async () => { + const { code, err } = await cli(['--=x', dist]); + expect(code).toBe(2); + expect(err).toContain('Unknown option --'); + }); + + it.each([ + '--json', + '--strict', + '--no-env', + '--deployed', + '--help', + ])('%s takes no value: `=value` is a usage error, not silently dropped', async (flag) => { + const { code, out, err } = await cli([dist, `${flag}=false`]); + expect(code).toBe(2); + expect(out).toBe(''); + expect(err).toContain(`${flag} does not take a value`); + }); + + it('after `--`, an argument containing `=` is a plain directory name', async () => { + const odd = join(root, '--odd=dir'); + mkdirSync(odd); + writeFileSync(join(odd, 'a.js'), stamped); + const here = process.cwd(); + process.chdir(root); + try { + const { code, out } = await cli(['--no-env', '--', '--odd=dir']); + expect(code).toBe(0); + expect(out).toContain('--odd=dir'); + expect(out).toContain('1 bundle(s)'); + } finally { + process.chdir(here); + } + }); + + it('`--project-root=--x` takes the value; `-- --a=b` is one directory (not truncated at `=`)', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code } = await cli([dist, '--project-root=--x', '--json']); + expect(code).toBe(0); + const here = process.cwd(); + process.chdir(root); + try { + mkdirSync(join(root, '--a=b')); + const out = await cli(['--no-env', '--', '--a=b']); + expect(out.out).toContain('--a=b'); + expect(out.out).toContain('0 bundle(s)'); + } finally { + process.chdir(here); + } + }); + + it('--ignore of a hard-failure ID warns that it cannot be ignored and still fails', async () => { + const { code, err } = await cli([ + join(root, 'nope'), + '--no-env', + '--ignore', + 'output.dir-missing', + ]); + expect(code).toBe(2); + expect(err).toContain('output.dir-missing cannot be ignored'); + }); + + it('an unknown --ignore ID is warned about on stderr but not fatal', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code, err } = await cli([dist, '--no-env', '--ignore', 'map.public-leftvoer']); + expect(code).toBe(0); + expect(err).toContain('map.public-leftvoer is not a known check ID'); + expect((await cli([dist, '--no-env', '--ignore', 'map.public-leftover'])).err).toBe(''); + }); + + it('--help prints usage and exits 0', async () => { + for (const flag of ['--help', '-h']) { + const { code, out } = await cli([flag]); + expect(code).toBe(0); + expect(out).toBe(`${DOCTOR_USAGE}\n`); + } + }); + + it.each([ + [[], 'Missing the build output directory'], + [['a', 'b'], 'Unexpected argument b'], + [['a', '--bogus'], 'Unknown option --bogus'], + [['a', '--project-root'], '--project-root needs a value'], + [['a', '--max-map-mb', '--json'], '--max-map-mb needs a value'], + [['a', '--max-map-mb', 'abc'], 'positive number, got "abc"'], + [['a', '--max-map-mb', '0'], 'positive number, got "0"'], + ])('usage error for %j', async (argv, message) => { + const { code, out, err } = await cli(argv as string[]); + expect(code).toBe(2); + expect(out).toBe(''); + expect(err).toContain(message); + expect(err).toContain('Usage: bugsee-sourcemaps-doctor'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts new file mode 100644 index 00000000..e1bd06e8 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -0,0 +1,170 @@ +#!/usr/bin/env node +// `bugsee-sourcemaps-doctor` — the command-line face of `diagnoseBuildOutput`. +// +// bugsee-sourcemaps-doctor [--json] [--strict] [--project-root ] [--max-map-mb ] [--no-env] [--exclude ] +// +// Exit codes: 0 ok, 1 warnings only with --strict, 2 errors (or a usage error). +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { + DOCTOR_CHECK_IDS, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, + NON_IGNORABLE_CHECK_IDS, +} from './doctor'; +import type { EnvRecord } from './run-cli'; + +export const DOCTOR_USAGE = `Usage: bugsee-sourcemaps-doctor [options] + +Audits a build output directory for everything that stops Bugsee from symbolicating a crash. + +Options: + --json Print the machine-readable report (schemaVersion 1) instead of text. + --strict Exit 1 when there are warnings (and no errors). + --project-root Where .env.bugsee-build-plugin and package.json are looked up (default: cwd). + --max-map-mb Flag source maps larger than n MiB (default 50). + --no-env Skip the token / version / build / NODE_ENV checks. + --deployed The directory is (about to be) served: leftover .map files become a warning. + --ignore Drop a check ID from the report; repeatable. + --exclude Do not check files the build did not emit (e.g. sw.js; relative to ); repeatable. + -- End of options (a directory may start with a dash after it). + -h, --help Show this help. + +Exit codes: 0 ok, 1 warnings only (with --strict), 2 errors.`; + +/** Flags that take no value: `--strict=false` must be refused, not read as `--strict`. */ +const BOOLEAN_FLAGS: ReadonlySet = new Set([ + '--json', + '--strict', + '--no-env', + '--deployed', + '--help', +]); + +export interface DoctorCliIo { + stdout: (text: string) => void; + stderr: (text: string) => void; + env: EnvRecord; +} + +/** Run the CLI in-process: returns the exit code, writes only through `io`. */ +export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Promise { + let dir: string | undefined; + let json = false; + let strict = false; + let skipEnv = false; + let deployed = false; + let onlyPositionals = false; + const ignore: string[] = []; + const exclude: string[] = []; + let projectRoot: string | undefined; + let maxMapBytes: number | undefined; + const usage = (message: string): number => { + io.stderr(`${message}\n\n${DOCTOR_USAGE}\n`); + return 2; + }; + for (let i = 0; i < argv.length; i++) { + let arg = argv[i] as string; + // `--key=value` is the same as `--key value` + let inline: string | undefined; + const eq = !onlyPositionals && arg.startsWith('--') ? arg.indexOf('=') : -1; + if (eq > 2) { + inline = arg.slice(eq + 1); + arg = arg.slice(0, eq); + } + if (inline !== undefined && BOOLEAN_FLAGS.has(arg)) { + return usage(`${arg} does not take a value`); + } + if (onlyPositionals) { + if (dir !== undefined) { + return usage(`Unexpected argument ${arg}`); + } + dir = arg; + } else if (arg === '--') { + onlyPositionals = true; + } else if (arg === '-h' || arg === '--help') { + io.stdout(`${DOCTOR_USAGE}\n`); + return 0; + } else if (arg === '--json') { + json = true; + } else if (arg === '--strict') { + strict = true; + } else if (arg === '--no-env') { + skipEnv = true; + } else if (arg === '--deployed') { + deployed = true; + } else if ( + arg === '--project-root' || + arg === '--max-map-mb' || + arg === '--ignore' || + arg === '--exclude' + ) { + const value = inline ?? argv[++i]; + if (value === undefined || (inline === undefined && value.startsWith('--'))) { + return usage(`${arg} needs a value`); + } + if (arg === '--project-root') { + projectRoot = value; + } else if (arg === '--exclude') { + exclude.push(value); + } else if (arg === '--ignore') { + if (NON_IGNORABLE_CHECK_IDS.has(value)) { + io.stderr( + `Warning: ${value} cannot be ignored (it means nothing was checked); it stays in the report.\n`, + ); + } else if (!(DOCTOR_CHECK_IDS as readonly string[]).includes(value)) { + io.stderr( + `Warning: --ignore ${value} is not a known check ID (see DOCTOR_CHECK_IDS); ignored.\n`, + ); + } + ignore.push(value); + } else { + const mb = Number(value); + if (!Number.isFinite(mb) || mb <= 0) { + return usage(`--max-map-mb needs a positive number, got "${value}"`); + } + maxMapBytes = mb * 1024 * 1024; + } + } else if (arg.startsWith('-')) { + return usage(`Unknown option ${arg}`); + } else if (dir === undefined) { + dir = arg; + } else { + return usage(`Unexpected argument ${arg}`); + } + } + if (dir === undefined) { + return usage('Missing the build output directory'); + } + const report = await diagnoseBuildOutput(dir, { + env: io.env, + skipEnv, + deployed, + ignore, + exclude, + ...(projectRoot !== undefined ? { projectRoot } : {}), + ...(maxMapBytes !== undefined ? { maxMapBytes } : {}), + }); + io.stdout(`${json ? JSON.stringify(report, null, 2) : formatDoctorReport(report)}\n`); + return doctorExitCode(report, strict); +} + +/* v8 ignore start -- process entry point: the logic above is what is tested */ +const self = process.argv[1]; +if (self !== undefined && realpathSync(self) === realpathSync(fileURLToPath(import.meta.url))) { + runDoctorCli(process.argv.slice(2), { + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + env: process.env, + }).then( + (code) => { + process.exitCode = code; + }, + (error: unknown) => { + process.stderr.write(`bugsee-sourcemaps-doctor: ${String(error)}\n`); + process.exitCode = 2; + }, + ); +} +/* v8 ignore stop */ diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts new file mode 100644 index 00000000..f05010c5 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -0,0 +1,1370 @@ +// Robustness of the doctor: it must never throw, never read what it should not, never be quadratic, and must +// resolve sources the way the build did. Each test pins one reviewed failure mode. +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + truncateSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, win32 } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + batchEnd, + type DoctorReport, + diagnoseBuildOutput, + doctorExitCode, + sourcePath, + walk, +} from './doctor'; +import { listOutputMaps } from './stamp-files'; + +const ID_A = '11111111-1111-4111-8111-111111111111'; +const ID_B = '22222222-2222-4222-8222-222222222222'; + +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-hard-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'app', version: '1.0.0' })); +}); +afterEach(() => rmSync(root, { recursive: true, force: true }), 120_000); // removing 130k files is slow + +const put = (rel: string, content: string | Buffer): string => { + const path = join(dist, rel); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); + return path; +}; +const stamp = (id: string): string => + `\n!function(){var g=globalThis;g._bugseeDebugIds=g._bugseeDebugIds||{};g._bugseeDebugIds["x"]="${id}"}();\n//# debugId=${id}\n`; +const mapJson = (extra: Record = {}): string => + JSON.stringify({ + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + names: [], + mappings: 'AAAA', + ...extra, + }); +const run = (options: Parameters[1] = {}): Promise => + diagnoseBuildOutput(dist, { projectRoot: root, skipEnv: true, ...options }); +const ids = (report: DoctorReport): string[] => report.findings.map((f) => f.id); +const find = (report: DoctorReport, id: string) => report.findings.find((f) => f.id === id); + +describe('never throws', () => { + it('a source with a bad percent-escape is unknowable, not an exception', async () => { + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ debugId: ID_A, sourcesContent: undefined, sources: ['file:///x/%zz.ts'] }), + ); + const report = await run(); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('an unexpected internal error becomes a doctor.internal-error finding', async () => { + put('a.js', `a${stamp(ID_A)}`); + const env = new Proxy( + {}, + { + ownKeys() { + throw new Error('boom'); + }, + }, + ); + const report = await diagnoseBuildOutput(dist, { env, projectRoot: root }); + expect(report.findings).toHaveLength(1); + expect(report.findings[0]).toMatchObject({ + id: 'doctor.internal-error', + severity: 'error', + }); + expect(report.findings[0]?.message).toContain('boom'); + expect(report.summary.errors).toBe(1); + expect(report.dir).toBe(dist); + // a hard failure cannot be ignored away + const ignored = await diagnoseBuildOutput(dist, { + env, + projectRoot: root, + ignore: ['doctor.internal-error'], + }); + expect(ignored.findings.map((f) => f.id)).toEqual(['doctor.internal-error']); + expect(ignored.ignored).toBeUndefined(); + }); + + it('a non-Error throw is stringified', async () => { + const env = new Proxy( + {}, + { + ownKeys() { + throw 'plain string'; + }, + }, + ); + put('a.js', 'x'); + const report = await diagnoseBuildOutput(dist, { env, projectRoot: root }); + expect(report.findings[0]?.message).toContain('plain string'); + }); +}); + +describe('a directory with very many files', () => { + it('the walks do not overflow the stack (130k files in one directory)', async () => { + const big = join(dist, 'chunks'); + mkdirSync(big); + for (let i = 0; i < 130_000; i++) { + writeFileSync(join(big, i % 2 === 0 ? `c${i}.js` : `c${i}.map`), ''); + } + expect((await walk(dist)).length).toBe(130_000); + expect((await listOutputMaps(dist)).length).toBe(65_000); + }, 120_000); + + it('20k bundles are checked in bounded time with correct counts', async () => { + for (let i = 0; i < 20_000; i++) { + const id = `${(i + 1).toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`assets/c${i}.js`, `${i}${stamp(id)}`); + } + const started = Date.now(); + const report = await run(); + expect(Date.now() - started).toBeLessThan(60_000); + expect(report.summary).toMatchObject({ bundles: 20_000, errors: 0, warnings: 0 }); + }, 120_000); +}); + +describe('reads', () => { + const mkfifo = (path: string): boolean => spawnSync('mkfifo', [path]).status === 0; + + it('a pointer outside the output directory is reported and never read (a FIFO would hang)', async () => { + const fifo = join(root, 'pipe.map'); + if (!mkfifo(fifo)) { + return; + } + put('a.js', `a\n//# sourceMappingURL=../pipe.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=../../../../../../dev/zero${stamp(ID_B)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')).toMatchObject({ + severity: 'warning', + details: { pointers: ['a.js -> ../pipe.map', 'b.js -> ../../../../../../dev/zero'] }, + }); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('a FIFO named as a map is map.unreadable, not opened; a symlink to a map inside the directory is read', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + if (!mkfifo(join(dist, 'a.js.map'))) { + return; + } + put('real.map', mapJson({ debugId: ID_B })); + put('b.js', `b\n//# sourceMappingURL=link.map${stamp(ID_B)}`); + symlinkSync(join(dist, 'real.map'), join(dist, 'link.map')); + const report = await run(); + const unreadable = report.findings.filter((f) => f.id === 'map.unreadable'); + // the FIFO is refused; the symlink to a map INSIDE the directory is simply read + expect(unreadable.map((f) => f.file)).toEqual(['a.js.map']); + expect(unreadable[0]?.message).toContain('not a regular file'); + expect(unreadable[0]?.severity).toBe('error'); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + }); + + it('a map larger than the limit is judged by its size, before it is read (a sparse 3 GiB file)', async () => { + put('a.js', `a${stamp(ID_A)}`); + const big = put('a.js.map', ''); + truncateSync(big, 3 * 1024 ** 3); + const report = await run(); + expect(find(report, 'map.too-large')).toMatchObject({ + severity: 'warning', + file: 'a.js.map', + details: { bytes: 3 * 1024 ** 3, limit: 50 * 1024 * 1024 }, + }); + expect(find(report, 'map.too-large')?.message).toContain('not read'); + expect(ids(report)).not.toContain('map.invalid'); + }); + + it('map.too-large is exact at the boundary: equal is fine, one byte over is not', async () => { + put('a.js', `a${stamp(ID_A)}`); + const text = mapJson({ debugId: ID_A }); + put('a.js.map', text); + const size = Buffer.byteLength(text); + expect(ids(await run({ maxMapBytes: size }))).not.toContain('map.too-large'); + expect(ids(await run({ maxMapBytes: size - 1 }))).toContain('map.too-large'); + // far over the limit also reports (kills a `>= limit * 2` comparison) + expect(ids(await run({ maxMapBytes: Math.floor(size / 2) }))).toContain('map.too-large'); + expect(find(await run({ maxMapBytes: size - 1 }), 'map.too-large')?.details).toEqual({ + bytes: size, + limit: size - 1, + }); + }); + + it('an oversized or non-regular orphan map is reported too', async () => { + put('style.css.map', mapJson()); + put('big.css.map', 'x'.repeat(100)); + const report = await run({ maxMapBytes: 50 }); + expect(find(report, 'map.too-large')?.file).toBe('big.css.map'); + }); + + it.skipIf(process.getuid?.() === 0)('a read error is a finding, not silence', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + const map = put('a.js.map', mapJson({ debugId: ID_A })); + put('b.js', 'b'); + const locked = put('locked.js', 'x'); + chmodSync(map, 0o000); + chmodSync(locked, 0o000); + try { + const report = await run(); + expect(find(report, 'map.unreadable')?.message).toContain('EACCES'); + expect(find(report, 'output.unreadable')).toMatchObject({ + severity: 'error', + details: { files: ['locked.js could not be read (EACCES)'] }, + }); + } finally { + chmodSync(map, 0o600); + chmodSync(locked, 0o600); + } + }); + + it('a script over the size limit is not read and is reported', async () => { + put('huge.js', 'x'.repeat(1000)); + put('ok.js', `a${stamp(ID_A)}`); + const report = await run({ maxBundleBytes: 999 }); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['huge.js is too large to read'], + }); + expect(report.summary.bundles).toBe(2); + expect(ids(await run({ maxBundleBytes: 1000 }))).not.toContain('output.unreadable'); + }); + + it('a map inside the directory but outside the walked set (node_modules) is still paired by its pointer', async () => { + put('a.js', `a\n//# sourceMappingURL=node_modules/a.map${stamp(ID_A)}`); + put('node_modules/a.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('node_modules/a.map'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('an indented sourceMappingURL comment is honoured', async () => { + put('a.js', `a\n \t//# sourceMappingURL=maps/x.map${stamp(ID_A)}`); + put('maps/x.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/x.map'); + }); + + it('a map that starts with a UTF-8 BOM is map.invalid and the message says BOM', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', `\uFEFF${mapJson({ debugId: ID_A })}`); + const report = await run(); + expect(find(report, 'map.invalid')?.message).toContain('BOM'); + expect(find(report, 'map.invalid')?.severity).toBe('error'); + }); +}); + +describe('source resolution', () => { + it('bundler-scheme sources resolve against the project root, not the map directory', async () => { + mkdirSync(join(root, 'src')); + writeFileSync(join(root, 'src', 'x.ts'), 'x'); + put('a.js', `a${stamp(ID_A)}`); + put( + 'deep/a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sources: ['webpack://app/./src/x.ts', 'webpack://app/./src/missing.ts'], + }), + ); + const report = await run(); + expect(find(report, 'map.sources-unresolvable')?.message).toContain('missing.ts'); + expect(find(report, 'map.sources-unresolvable')?.details).toEqual({ unresolved: 1, total: 2 }); + }); + + it('sourcePath: posix, project root, file URLs, virtual and malformed sources', () => { + expect(sourcePath('/m', '', 'webpack://app/./src/x.ts', '/proj')).toBe('/proj/src/x.ts'); + expect(sourcePath('/m', '', 'webpack://app/./src/x.ts')).toBe('/m/src/x.ts'); + expect(sourcePath('/m/d', '../s', 'a.ts', '/proj')).toBe('/m/s/a.ts'); + expect(sourcePath('/m', '', '/abs/a.ts')).toBe('/abs/a.ts'); + expect(sourcePath('/m', '', 'file:///x/a%20b.ts')).toBe('/x/a b.ts'); + expect(sourcePath('/m', '', 'file:///x/%zz.ts')).toBeUndefined(); + expect(sourcePath('/m', '', 'webpack/runtime/x')).toBeUndefined(); + expect(sourcePath('/m', '', '')).toBeUndefined(); + }); + + it('sourcePath on Windows: drive-letter file URLs and project-relative bundler paths', () => { + expect(sourcePath('C:\\m', '', 'file:///C:/x/a.ts', 'C:\\p', win32)).toBe('C:\\x\\a.ts'); + expect(sourcePath('C:\\m', '', 'webpack://app/./src/x.ts', 'C:\\p', win32)).toBe( + 'C:\\p\\src\\x.ts', + ); + expect(sourcePath('C:\\m', '..\\s', 'a.ts', 'C:\\p', win32)).toBe('C:\\s\\a.ts'); + expect(sourcePath('C:\\m', '', 'D:\\abs\\a.ts', 'C:\\p', win32)).toBe('D:\\abs\\a.ts'); + }); +}); + +describe('pointer reading and pairing (round 2)', () => { + it('a pointer with an unencoded space is read whole (the stamper reads to the end of the line)', async () => { + put('a.js', `a\n//# sourceMappingURL=maps/my map.map${stamp(ID_A)}`); + put('maps/my map.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/my map.map'); + }); + + it('the LAST sourceMappingURL comment wins', async () => { + put('a.js', `a\n//# sourceMappingURL=gone.map\n//# sourceMappingURL=real.map${stamp(ID_A)}`); + put('real.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('real.map'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('uppercase extensions are scripts and maps too, like the stamper', async () => { + put('A.JS', `a${stamp(ID_A)}`); + put('A.JS.map', mapJson({ debugId: ID_B })); + put('C.MAP', mapJson()); + const report = await run(); + expect(report.summary).toMatchObject({ bundles: 1, maps: 2 }); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('A.JS.map'); + }); + + it('a map shared by two bundles is validated once', async () => { + put('a.js', `a\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('shared.map', mapJson({ debugId: ID_A, sources: [] })); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.no-sources')).toHaveLength(1); + }); + + it('isInside: the parent itself is outside, a `..`-prefixed NAME inside the directory is not', async () => { + put('a.js', `a\n//# sourceMappingURL=..${stamp(ID_A)}`); + put('..b/x.map', mapJson({ debugId: ID_B })); + put('b.js', `b\n//# sourceMappingURL=..b/x.map${stamp(ID_B)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')?.details).toEqual({ pointers: ['a.js -> ..'] }); + expect(ids(report)).not.toContain('map.unreadable'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('virtual sources never name a file; look-alikes do', () => { + for (const virtual of [ + 'webpack/runtime/x', + '(webpack)/buildin/x.js', + '\0virtual', + 'a\0b.ts', + '', + 'rollup:plugin/x', + 'vite/preload-helper.js', + ]) { + expect(sourcePath('/m', '', virtual), virtual).toBeUndefined(); + } + for (const real of ['webpackx/a.ts', 'viteish/a.ts', 'rollupx.ts', 'webpack.config.js']) { + expect(sourcePath('/m', '', real), real).toBe(`/m/${real}`); + } + }); +}); + +describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () => { + it('reports output.no-js and does not throw', async () => { + put('a.js', 'x'); + chmodSync(dist, 0o000); + try { + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(find(report, 'output.dir-unreadable')?.details).toEqual({ directories: ['.'] }); + } finally { + chmodSync(dist, 0o700); + } + }); + + it('an unreadable SUB-directory is an error naming it, never a silent pass', async () => { + put('registerSW.js', `a${stamp(ID_A)}`); + put('assets/index.js', 'unstamped'); + put('assets/deeper/x.js', 'x'); + chmodSync(join(dist, 'assets'), 0o000); + try { + const report = await run(); + expect(find(report, 'output.dir-unreadable')).toMatchObject({ + severity: 'error', + details: { directories: ['assets'] }, + }); + expect(report.passed).not.toContain('output.dir-unreadable'); + expect(doctorExitCode(report, false)).toBe(2); + } finally { + chmodSync(join(dist, 'assets'), 0o700); + } + expect(ids(await run())).not.toContain('output.dir-unreadable'); + }); + + it('--exclude can name an unreadable directory: it leaves output.dir-unreadable, is listed as excluded, and its pattern is matched', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('vendor/x.js', 'x'); + put('assets/y.js', 'y'); + chmodSync(join(dist, 'vendor'), 0o000); + chmodSync(join(dist, 'assets'), 0o000); + try { + for (const pattern of ['vendor/**', 'vendor/', '**/vendor/**', '**']) { + const report = await run({ exclude: [pattern] }); + const left = find(report, 'output.dir-unreadable')?.details?.directories; + expect(left, pattern).toEqual(pattern === '**' ? undefined : ['assets']); + expect(ids(report), pattern).not.toContain('output.exclude-unmatched'); + } + const report = await run({ exclude: ['vendor/**'] }); + expect( + report.findings.some( + (f) => + f.id === 'output.excluded' && + (f.details?.directories as string[] | undefined)?.includes('vendor'), + ), + ).toBe(true); + // a glob that would NOT hide the directory's files if it could be listed must not hide the directory either + for (const pattern of ['vendor', 'vendor*', 'vendor/*', '*', 'assets/*']) { + const kept = find(await run({ exclude: [pattern] }), 'output.dir-unreadable')?.details; + expect(kept, pattern).toEqual({ directories: ['assets', 'vendor'] }); + } + expect(find(await run({ exclude: ['nope/**'] }), 'output.dir-unreadable')?.details).toEqual({ + directories: ['assets', 'vendor'], + }); + } finally { + chmodSync(join(dist, 'vendor'), 0o700); + chmodSync(join(dist, 'assets'), 0o700); + } + }); + + it('several unreadable directories are listed, sorted', async () => { + put('a.js', `a${stamp(ID_A)}`); + for (let i = 2; i >= 0; i--) { + put(`d${i}/p.js`, 'x'); + chmodSync(join(dist, `d${i}`), 0o000); + } + try { + const finding = find(await run(), 'output.dir-unreadable'); + expect(finding?.details).toEqual({ directories: ['d0', 'd1', 'd2'] }); + } finally { + for (let i = 0; i < 3; i++) { + chmodSync(join(dist, `d${i}`), 0o700); + } + } + }); + + it('a directory only the HTML page walk enters (src/, which the fenced script walk skips) is reported too', async () => { + put('package.json', '{"name":"p"}'); + put('a.js', `a${stamp(ID_A)}`); + put('src/p.html', '

'); + chmodSync(join(dist, 'src'), 0o000); + const here = process.cwd(); + process.chdir(dist); + try { + const finding = find(await run(), 'output.dir-unreadable'); + expect(finding?.details).toEqual({ directories: ['src'] }); + } finally { + process.chdir(here); + chmodSync(join(dist, 'src'), 0o700); + } + }); +}); + +describe('CRLF bundles (a Windows toolchain)', () => { + it('an inline map after a CRLF line is still map.inline, and a pointer with CR is paired', async () => { + put('a.js', `a\r\n//# sourceMappingURL=data:application/json;base64,e30=\r\n${stamp(ID_A)}`); + put('b.js', `b\r\n//# sourceMappingURL=maps/b.map\r\n${stamp(ID_B)}`); + put('maps/b.map', mapJson({ debugId: ID_A })); + const report = await run(); + expect(find(report, 'map.inline')?.details).toEqual({ files: ['a.js'] }); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/b.map'); + expect(ids(report)).not.toContain('map.hidden'); + }); +}); + +describe('symlinks never lead outside the output directory (round 3)', () => { + const secretMap = (): string => + JSON.stringify({ + version: 3, + debugId: ID_B, + sources: ['TOP-SECRET-SOURCE-PATH.ts'], + sourcesContent: ['TOP-SECRET-CONTENT'], + mappings: 'AAAA', + }); + + it('a pointer through a symlinked DIRECTORY is not read: no outside content in any output', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'secret.json'), secretMap()); + symlinkSync(outside, join(dist, 'link')); + put('app.js', `a\n//# sourceMappingURL=link/secret.json${stamp(ID_A)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')?.details).toEqual({ + pointers: ['app.js -> link/secret.json'], + }); + const everything = JSON.stringify(report); + expect(everything).not.toContain('TOP-SECRET'); + expect(everything).not.toContain(ID_B); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('a pointer through a symlinked directory that stays INSIDE the directory is read normally', async () => { + put('real/x.map', mapJson({ debugId: ID_B })); + symlinkSync(join(dist, 'real'), join(dist, 'alias')); + put('app.js', `a\n//# sourceMappingURL=alias/x.map${stamp(ID_A)}`); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')).toBeDefined(); + }); + + it('a symlinked directory is never descended into by the walk', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'o.js'), 'x'); + symlinkSync(outside, join(dist, 'linkdir')); + put('a.js', `a${stamp(ID_A)}`); + expect((await walk(dist)).map((f) => f.slice(dist.length + 1))).toEqual(['a.js']); + }); + + it('a symlinked bundle that leads OUTSIDE is reported, not silently invisible (no misleading output.no-js)', async () => { + const real = join(root, 'real.js'); + writeFileSync(real, `a${stamp(ID_A)}`); + symlinkSync(real, join(dist, 'app.js')); + const report = await run(); + // not the misleading "No .js files found": the script IS there, and nothing could be read + expect(find(report, 'output.no-js')?.message).toContain('could be read'); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['app.js resolves outside the output directory'], + }); + expect(report.summary.bundles).toBe(1); + }); + + it('a manifest that is a symlink to a file outside is not read', async () => { + const outside = join(root, 'outside-manifest.json'); + writeFileSync(outside, '{"integrity":"x"}'); + symlinkSync(outside, join(dist, 'asset-manifest.json')); + put('a.js', `a${stamp(ID_A)}`); + expect(ids(await run())).not.toContain('sri.manifest-hashes'); + }); + + it('an uppercase MANIFEST.JSON is still a manifest', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('ASSET-MANIFEST.JSON', '{"integrity":"x"}'); + expect(ids(await run())).toContain('sri.manifest-hashes'); + }); +}); + +describe('--ignore cannot hide a hard failure (round 3)', () => { + it('output.dir-missing, output.no-js and doctor.internal-error stay in the report', async () => { + const missing = await diagnoseBuildOutput(join(root, 'nope'), { + ignore: ['output.dir-missing'], + skipEnv: true, + }); + expect(ids(missing)).toEqual(['output.dir-missing']); + expect(missing.summary.errors).toBe(1); + expect(missing.ignored).toBeUndefined(); + const empty = await run({ ignore: ['output.no-js', 'map.public-leftover'] }); + expect(ids(empty)).toEqual(['output.no-js']); + expect(empty.ignored).toBeUndefined(); + }); +}); + +describe('SRI reads are as guarded as every other read (review thread)', () => { + const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const page = (src: string, integrity: string): string => + ``; + + it('a pinned script that is a FIFO never hangs the doctor', async () => { + if (spawnSync('mkfifo', [join(dist, 'app.js')]).status !== 0) { + return; + } + put('index.html', page('app.js', sri('x'))); + const report = await run(); + // a FIFO named like a script is listed and refused (never opened), and the pin does not open it either + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['app.js is not a regular file'], + }); + expect(find(report, 'output.no-js')?.message).toContain('could be read'); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(find(report, 'sri.pin-unreadable')?.details).toEqual({ + scripts: ['app.js is not a regular file'], + }); + }, 10_000); + + it('a pinned symlink to /dev/zero is refused, never read', async () => { + symlinkSync('/dev/zero', join(dist, 'zero.js')); + put('index.html', page('zero.js', sri('x'))); + const report = await run(); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['zero.js resolves outside the output directory'], + }); + expect(find(report, 'sri.pin-unreadable')?.details).toEqual({ + scripts: ['zero.js resolves outside the output directory'], + }); + expect(ids(report)).not.toContain('sri.mismatch'); + }, 10_000); + + it('a pinned script reached through a symlinked directory is not read or hashed', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'app.js'), `x${stamp(ID_A)}`); + symlinkSync(outside, join(dist, 'vendor')); + put('index.html', page('vendor/app.js', sri('something else'))); + const report = await run(); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + }); + + it('a pinned regular script whose bytes no longer match is still sri.mismatch (read once)', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('index.html', page('app.js', sri('c'))); + const report = await run(); + expect(find(report, 'sri.mismatch')?.details).toEqual({ scripts: ['app.js'] }); + }); +}); + +describe('symlinks that stay inside the directory (round 4)', () => { + it('a pnpm-style symlinked bundle and map are read through their real path: no error, no double report', async () => { + put('.store/app.js', `c\n//# sourceMappingURL=app.js.map${stamp(ID_A)}`); + put('.store/app.js.map', mapJson({ debugId: ID_A })); + mkdirSync(join(dist, 'assets')); + symlinkSync(join(dist, '.store', 'app.js'), join(dist, 'assets', 'app.js')); + symlinkSync(join(dist, '.store', 'app.js.map'), join(dist, 'assets', 'app.js.map')); + const report = await run(); + expect(report.summary.errors).toBe(0); + expect(ids(report)).not.toContain('output.unreadable'); + expect(ids(report)).not.toContain('map.unreadable'); + expect(ids(report)).not.toContain('stamp.duplicate-debug-id'); + }); + + it('a symlink to a file inside whose map id differs is judged like the real file', async () => { + put('.store/app.js', `c${stamp(ID_A)}`); + put('.store/app.js.map', mapJson({ debugId: ID_B })); + symlinkSync(join(dist, '.store', 'app.js'), join(dist, 'app.js')); + symlinkSync(join(dist, '.store', 'app.js.map'), join(dist, 'app.js.map')); + const report = await run(); + expect(ids(report)).toContain('stamp.map-id-mismatch'); + }); + + it('a dangling or looping symlink is still reported, never read', async () => { + symlinkSync(join(dist, 'nowhere.js'), join(dist, 'dangling.js')); + symlinkSync(join(dist, 'loop-b.js'), join(dist, 'loop-a.js')); + symlinkSync(join(dist, 'loop-a.js'), join(dist, 'loop-b.js')); + put('ok.js', `a${stamp(ID_A)}`); + const report = await run(); + const files = (find(report, 'output.unreadable')?.details?.files as string[]).sort(); + expect(files).toEqual([ + 'dangling.js could not be resolved (ENOENT)', + 'loop-a.js could not be resolved (ELOOP)', + 'loop-b.js could not be resolved (ELOOP)', + ]); + }); + + it('a pinned script that is a symlink INSIDE the directory is read: a mismatch is not silently skipped', async () => { + put('.store/app.js', `c${stamp(ID_A)}`); + symlinkSync(join(dist, '.store', 'app.js'), join(dist, 'app.js')); + put('index.html', ``); + const report = await run(); + expect(find(report, 'sri.mismatch')?.details).toEqual({ scripts: ['app.js'] }); + expect(ids(report)).not.toContain('sri.pin-unreadable'); + }); + + it('a map reached through two names is validated once', async () => { + put('real/x.map', 'not json'); + symlinkSync(join(dist, 'real'), join(dist, 'alias')); + put('a.js', `a\n//# sourceMappingURL=real/x.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=alias/x.map${stamp(ID_B)}`); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.invalid')).toHaveLength(1); + }); +}); + +describe('big outputs stay readable (round 4)', () => { + it('sources-content notes: a few are listed, many become ONE finding with counts', async () => { + for (let i = 0; i < 3; i++) { + put(`s${i}.js`, `a${stamp(`0000000${i}-1111-4111-8111-111111111111`)}`); + put(`s${i}.js.map`, mapJson({ debugId: `0000000${i}-1111-4111-8111-111111111111` })); + } + const few = await run(); + expect(few.findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(3); + // 10 notes (2 x the listing cap) are still listed one by one; the 11th folds them into one finding. + for (let i = 3; i < 10; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + const ten = await run(); + expect(ten.findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(10); + for (let i = 10; i < 11; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + expect((await run()).findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(1); + for (let i = 11; i < 14; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + const many = await run(); + const notes = many.findings.filter((f) => f.id === 'map.sources-content'); + expect(notes).toHaveLength(1); + expect(notes[0]?.details).toEqual({ maps: 14, embedded: 14, resolvableOnDisk: 0 }); + expect(notes[0]?.file).toBeUndefined(); + }); + + it('a list of exactly 100 is not capped and carries no total', async () => { + for (let i = 0; i < 100; i++) { + put(`e${i}.js`, `x${i}`); + } + const finding = find(await run(), 'stamp.missing-debug-id'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details).not.toHaveProperty('total'); + }); + + it('long file lists in details are capped, with the total', async () => { + for (let i = 0; i < 130; i++) { + put(`v${i}.js`, `x${i}`); + } + const report = await run(); + const finding = find(report, 'stamp.missing-debug-id'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details?.total).toBe(130); + put('w.js', 'x'); + const exact = await run(); + expect(find(exact, 'stamp.missing-debug-id')?.details?.total).toBe(131); + }); + + it('an oversized page is reported as sri.html-skipped, and the rest of the audit goes on', async () => { + put('a.js', `a${stamp(ID_A)}`); + const big = put('huge.html', ''); + truncateSync(big, 8 * 1024 * 1024 + 1); + const report = await run(); + expect(find(report, 'sri.html-skipped')).toMatchObject({ + severity: 'warning', + details: { files: ['huge.html'] }, + }); + expect(report.summary.bundles).toBe(1); + }); + + it('--exclude applies to HTML pages too: an oversized or unreadable excluded page is not reported, and its pattern is matched', async () => { + put('a.js', `a${stamp(ID_A)}`); + truncateSync(put('huge.html', ''), 8 * 1024 * 1024 + 1); + truncateSync(put('keep/huge2.html', ''), 8 * 1024 * 1024 + 1); + const report = await run({ exclude: ['huge.html'] }); + expect(find(report, 'sri.html-skipped')?.details).toEqual({ files: ['keep/huge2.html'] }); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + expect(ids(await run({ exclude: ['**/*.html'] }))).not.toContain('sri.html-skipped'); + }); + + it.skipIf(process.getuid?.() === 0)( + 'an unreadable excluded page is not reported either', + async () => { + put('a.js', `a${stamp(ID_A)}`); + const page = put('locked.html', '

'); + chmodSync(page, 0o000); + try { + expect(ids(await run())).toContain('sri.html-skipped'); + const report = await run({ exclude: ['locked.html'] }); + expect(ids(report)).not.toContain('sri.html-skipped'); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + } finally { + chmodSync(page, 0o600); + } + }, + ); + + it('a page of pathological unterminated tags does not stall the doctor', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('index.html', '`); + const before = await run(); + expect(ids(before)).toContain('sri.mismatch'); + const after = await run({ exclude: ['vendor.js'] }); + expect(ids(after)).not.toContain('sri.mismatch'); + expect(ids(after)).not.toContain('sri.unstamped-hazard'); + }); + + it('a pointer to an excluded map is neither read nor reported', async () => { + put('a.js', `a\n//# sourceMappingURL=maps/a.js.map${stamp(ID_A)}`); + put('maps/a.js.map', mapJson({ debugId: ID_B })); + expect(ids(await run())).toContain('stamp.map-id-mismatch'); + const report = await run({ exclude: ['maps/**'] }); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(find(report, 'output.excluded')?.details).toEqual({ files: ['maps/a.js.map'] }); + }); + + it('a pattern that matches only an SRI pin outside the walked files still counts as matched', async () => { + put('package.json', '{"name":"p"}'); + put('app.js', `a${stamp(ID_A)}`); + put('tests/vendor.js', 'v'); // in a fenced (skipped) directory: not in the walk + put('index.html', ``); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run({ exclude: ['tests/vendor.js'] }); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + expect(ids(report)).not.toContain('sri.mismatch'); + } finally { + process.chdir(here); + } + }); + + it('the new info-only IDs are facts, never "passed"', async () => { + healthy(); + put('public/x.js', 'x'); + const report = await run({ exclude: ['public/**'] }); + expect(report.passed).not.toContain('output.excluded'); + expect(report.passed).not.toContain('output.exclude-unmatched'); + expect(report.passed).not.toContain('output.walk-fenced'); + }); + + it('glob semantics: * stays in a directory, ** crosses them, ? is one character, a trailing / is a directory', async () => { + healthy(); + put('a1.js', 'x'); + put('sub/a2.js', 'x'); + put('sub/deep/a3.js', 'x'); + put('vendor/v.js', 'x'); + put('vendor/xv.js', 'x'); + const excluded = async (pattern: string): Promise => + (find(await run({ exclude: [pattern] }), 'output.excluded')?.details?.files as string[]) ?? + []; + expect(await excluded('a?.js')).toEqual(['a1.js']); + expect(await excluded('*.js')).toEqual(['a1.js', 'app.js']); + expect(await excluded('**/*.js')).toEqual([ + 'a1.js', + 'app.js', + 'sub/a2.js', + 'sub/deep/a3.js', + 'vendor/v.js', + 'vendor/xv.js', + ]); + expect(await excluded('sub/*.js')).toEqual(['sub/a2.js']); + expect(await excluded('sub/**')).toEqual(['sub/a2.js', 'sub/deep/a3.js']); + expect(await excluded('vendor/')).toEqual(['vendor/v.js', 'vendor/xv.js']); + expect(await excluded('a.js')).toEqual([]); // `.` is a literal dot, not "any character" + expect(await excluded('a1+js')).toEqual([]); + expect(await excluded('[a]1.js')).toEqual([]); // regex syntax in a glob is literal + expect(await excluded('sub?a2.js')).toEqual([]); // `?` is never a slash + expect(await excluded('**/v.js')).toEqual(['vendor/v.js']); // `**/` is whole path segments: xv.js is not v.js + expect(await excluded('**/a2.js')).toEqual(['sub/a2.js']); + expect(await excluded('**/p.js')).toEqual([]); + }); + + it('excluding every script leaves output.no-js, which cannot be hidden', async () => { + put('public/sw.js', 's'); + const report = await run({ exclude: ['**'] }); + expect(ids(report)).toContain('output.no-js'); + }); + + it('a long exclusion list is capped, with the total', async () => { + healthy(); + for (let i = 0; i < 120; i++) { + put(`public/f${i}.js`, 'x'); + } + const finding = find(await run({ exclude: ['public/**'] }), 'output.excluded'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details?.total).toBe(120); + }); +}); + +describe('the walk fence is reported, and needs a real project directory (round 6)', () => { + const inDist = async (options: Parameters[0] = {}): Promise => { + const here = process.cwd(); + process.chdir(dist); + try { + return await run(options); + } finally { + process.chdir(here); + } + }; + + it('run from inside an output directory WITHOUT a package.json, src/ and dot-directories are audited', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + const report = await inDist(); + expect(report.summary.bundles).toBe(4); + expect(ids(report)).not.toContain('output.walk-fenced'); + }); + + it('a directory that is the project (has a package.json) is fenced, and the report lists what was skipped', async () => { + put('package.json', '{"name":"p"}'); + put('a.js', `a${stamp(ID_A)}`); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('tests/t.js', 'x'); + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + const report = await inDist(); + expect(report.summary.bundles).toBe(1); + expect(find(report, 'output.walk-fenced')).toMatchObject({ + severity: 'info', + details: { directories: ['.cache', 'a/b/c/d/e/f/g', 'src', 'tests'] }, + }); + }); + + it('a project directory that is not the working directory is not fenced', async () => { + put('package.json', '{"name":"p"}'); + put('src/s.js', 'x'); + put('a.js', `a${stamp(ID_A)}`); + expect((await run()).summary.bundles).toBe(2); + }); +}); + +describe('round 7 review findings', () => { + const mkfifo = (path: string): boolean => spawnSync('mkfifo', [path]).status === 0; + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + + it('when EVERY script is unreadable the audit cannot pass, even with --ignore output.unreadable', async () => { + if (!mkfifo(join(dist, 'a.js'))) { + return; + } + const report = await run({ ignore: ['output.unreadable'] }); + expect(find(report, 'output.no-js')).toMatchObject({ severity: 'error' }); + expect(find(report, 'output.no-js')?.message).toContain('could be read'); + }); + + it('some unreadable scripts are an ordinary, ignorable finding', async () => { + put('ok.js', `a${stamp(ID_A)}`); + if (!mkfifo(join(dist, 'a.js'))) { + return; + } + const report = await run({ ignore: ['output.unreadable'] }); + expect(ids(report)).not.toContain('output.no-js'); + }); + + it('a version-3 map without mappings (or sections) is map.invalid', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put( + 'a.js.map', + JSON.stringify({ version: 3, sources: ['a.ts'], sourcesContent: ['x'], debugId: ID_A }), + ); + const report = await run(); + expect(find(report, 'map.invalid')?.message).toContain('mappings'); + const sectioned = { + debugId: ID_A, + mappings: undefined, + sources: undefined, + sourcesContent: undefined, + sections: [ + { + offset: { line: 0, column: 0 }, + map: { + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + names: [], + mappings: 'AAAA', + }, + }, + ], + }; + put('a.js.map', mapJson(sectioned)); + expect(ids(await run())).not.toContain('map.invalid'); + put('a.js.map', mapJson({ debugId: ID_A, mappings: 5 })); + expect(ids(await run())).toContain('map.invalid'); + }); + + it('an unreadable HTML page is reported as not scanned, never silently passed', async () => { + put('a.js', `a${stamp(ID_A)}`); + const page = put('index.html', ``); + chmodSync(page, 0o000); + try { + if (spawnSync('sh', ['-c', `cat '${page}' >/dev/null 2>&1`]).status === 0) { + return; // running as root: the permission does not bite + } + const finding = find(await run(), 'sri.html-skipped'); + expect(finding).toMatchObject({ severity: 'warning', details: { files: ['index.html'] } }); + expect(finding?.message).toContain('could not be read'); + } finally { + chmodSync(page, 0o600); + } + }); + + it('the same script pinned by two pages with different hashes: the stale pin is reported', async () => { + const js = `console.log(1);${stamp(ID_A)}`; + put('a.js', js); + put('a.html', ``); + put('b.html', ``); + const report = await run(); + expect(find(report, 'sri.mismatch')).toMatchObject({ details: { scripts: ['a.js'] } }); + }); + + it('passed lists only checks that had input: nothing for the stamp/map checks of an empty directory', async () => { + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + for (const id of [ + 'stamp.missing-registration', + 'stamp.map-id-mismatch', + 'map.invalid', + 'build.dev-bundle', + ]) { + expect(report.passed).not.toContain(id); + } + put('a.js', `a${stamp(ID_A)}`); + const healthy = await run(); + expect(healthy.passed).toContain('stamp.missing-registration'); + expect(healthy.passed).not.toContain('map.invalid'); // a bundle but no map: nothing to validate + put('a.js.map', mapJson({ debugId: ID_A })); + expect((await run()).passed).toContain('map.invalid'); + }); +}); + +describe('batchEnd bounds the bytes read at once', () => { + it('stops at the count limit, at the byte budget, and always takes at least one', () => { + expect(batchEnd([1, 1, 1, 1], 0, 2, 100)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 25)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 20)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 40)).toBe(4); + expect(batchEnd([500, 1, 1], 0, 16, 100)).toBe(1); + expect(batchEnd([1, 500, 1], 1, 16, 100)).toBe(2); + expect(batchEnd([1, 1], 1, 16, 100)).toBe(2); + }); +}); + +describe('the SRI page walk follows the doctor fence (round 8)', () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const pin = (): void => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + }; + + it('an output directory is scanned for pages in test/, dot-directories and deep paths too', async () => { + pin(); + put( + 'tests/index.html', + '', + ); + expect(ids(await run())).toContain('sri.mismatch'); + rmSync(join(dist, 'tests'), { recursive: true }); + put('.well/p.html', ''); + expect(ids(await run())).toContain('sri.mismatch'); + rmSync(join(dist, '.well'), { recursive: true }); + put( + 'a/b/c/d/e/f/g/h/p.html', + '', + ); + expect(ids(await run())).toContain('sri.mismatch'); + }); + + it('a fenced project directory keeps the fence for pages too, and the walk-fenced finding says what was skipped', async () => { + put('package.json', '{"name":"p"}'); + pin(); + put( + 'tests/index.html', + '', + ); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run(); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(find(report, 'output.walk-fenced')?.details).toEqual({ directories: ['tests'] }); + } finally { + process.chdir(here); + } + }); +}); + +describe('a pointer with a ?query (webpack / Rspack [name].js?[contenthash]) (round 9)', () => { + it('pairs the map the query-less path names, and does not call the pointer dangling', async () => { + // NOT a sibling: only following the pointer (query cut) can find it, so the mismatch proves the pairing + put('main.js', `a\n//# sourceMappingURL=maps/main.js.map?3872346a403b27a7${stamp(ID_A)}`); + put('maps/main.js.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.hidden'); + }); + + it('a query on a pointer to a map that is not there is still dangling, reported as written', async () => { + put('main.js', `a\n//# sourceMappingURL=gone.js.map?abc${stamp(ID_A)}`); + expect(find(await run(), 'map.pointer-dangling')?.details).toEqual({ + pointers: ['main.js -> gone.js.map?abc'], + }); + }); + + it('an excluded map named with a query is neither read nor dangling', async () => { + put('main.js', `a\n//# sourceMappingURL=maps/main.js.map?x${stamp(ID_A)}`); + put('maps/main.js.map', mapJson({ debugId: ID_B })); + const report = await run({ exclude: ['maps/**'] }); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + }); +}); + +describe('index (sectioned) source maps (round 10)', () => { + const index = (sections: unknown[], extra: Record = {}): string => + JSON.stringify({ version: 3, sections, ...extra }); + const section = (sources: string[], content?: string[]) => ({ + offset: { line: 0, column: 0 }, + map: { + version: 3, + sources, + ...(content ? { sourcesContent: content } : {}), + names: [], + mappings: 'AAAA', + }, + }); + const pair = (map: string): void => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put('a.js.map', map); + }; + + it('sources live inside the sections: not map.no-sources, and the embedded content is counted', async () => { + pair(index([section(['a.ts'], ['x']), section(['b.ts'], ['y'])], { debugId: ID_A })); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('map.invalid'); + expect(find(report, 'map.sources-content')?.message).toContain('all 2 sources'); + }); + + it('sections without sourcesContent and with sources not on disk: map.sources-unresolvable', async () => { + pair(index([section(['a.ts']), section(['b.ts'], ['y'])], { debugId: ID_A })); + const report = await run(); + expect(find(report, 'map.sources-unresolvable')?.details).toEqual({ unresolved: 1, total: 2 }); + }); + + it('an index map whose sections carry no sources is still map.no-sources', async () => { + pair(index([section([]), { offset: { line: 1, column: 0 }, url: 'x.map' }], { debugId: ID_A })); + expect(ids(await run())).toContain('map.no-sources'); + pair(index([], { debugId: ID_A })); + expect(ids(await run())).toContain('map.no-sources'); + }); + + it('content stays aligned per section: a second source without content is the one reported', async () => { + pair(index([section(['a.ts', 'b.ts'], ['x'])], { debugId: ID_A })); + expect(find(await run(), 'map.sources-unresolvable')?.details).toEqual({ + unresolved: 1, + total: 2, + }); + }); + + it('an empty top-level sources array falls through to the sections; a section without a map or sources is skipped', async () => { + pair( + index( + [section(['a.ts'], ['x']), { offset: { line: 1, column: 0 }, map: { version: 3 } }, null], + { debugId: ID_A, sources: [] }, + ), + ); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(find(report, 'map.sources-content')?.message).toContain('all 1 sources'); + }); + + it("each section's sources are resolved with the section's own sourceRoot", async () => { + put('src/a.ts', 'x'); + const withRoot = { + offset: { line: 0, column: 0 }, + map: { version: 3, sourceRoot: 'src/', sources: ['a.ts'], names: [], mappings: 'AAAA' }, + }; + pair(index([withRoot], { debugId: ID_A })); + expect(ids(await run())).not.toContain('map.sources-unresolvable'); + put('src/a.ts', 'x'); + const wrongRoot = { ...withRoot, map: { ...withRoot.map, sourceRoot: 'nope/' } }; + pair(index([wrongRoot], { debugId: ID_A })); + expect(ids(await run())).toContain('map.sources-unresolvable'); + }); + + it('nested index maps: leaves are found at any depth, each with its own sourceRoot and content', async () => { + put('lib/b.ts', 'y'); + const leaf = (root: string, sources: string[], content?: string[]) => ({ + offset: { line: 0, column: 0 }, + map: { + version: 3, + sourceRoot: root, + sources, + ...(content ? { sourcesContent: content } : {}), + names: [], + mappings: 'AAAA', + }, + }); + const inner = { + offset: { line: 5, column: 0 }, + map: { version: 3, sections: [leaf('lib/', ['b.ts'])] }, + }; + pair(index([leaf('', ['a.ts'], ['x']), inner], { debugId: ID_A })); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); // b.ts is under lib/, via the leaf's root + const wrong = { + offset: { line: 5, column: 0 }, + map: { version: 3, sections: [leaf('nope/', ['b.ts'])] }, + }; + pair(index([leaf('', ['a.ts'], ['x']), wrong], { debugId: ID_A })); + expect(find(await run(), 'map.sources-unresolvable')?.details).toEqual({ + unresolved: 1, + total: 2, + }); + }); + + it('index maps are followed to a bounded depth (32): a leaf within it is found, one beyond it is not', async () => { + const chain = (depth: number): string => { + let map: Record = { + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + mappings: 'A', + }; + for (let i = 0; i < depth; i++) { + map = { version: 3, sections: [{ offset: { line: 0, column: 0 }, map }] }; + } + return JSON.stringify({ ...map, debugId: ID_A }); + }; + pair(chain(30)); + expect(ids(await run())).not.toContain('map.no-sources'); + pair(chain(40)); + const report = await run(); + expect(ids(report)).toContain('map.no-sources'); + expect(ids(report)).not.toContain('doctor.internal-error'); + }); + + it('top-level sources win over sections', async () => { + pair( + index([section(['z.ts'], ['z'])], { + debugId: ID_A, + sources: ['a.ts'], + sourcesContent: ['x'], + }), + ); + expect(find(await run(), 'map.sources-content')?.message).toContain('all 1 sources'); + }); +}); + +// Windows does not allow a `?` in a path component: the fixture cannot be created there +describe.skipIf(process.platform === 'win32')( + 'a ? in the checked directory path (round 11)', + () => { + it('the pointer is judged on its own query, not on a ? anywhere in the absolute path', async () => { + const weird = join(root, 'we?ird'); + mkdirSync(weird); + const out = join(weird, 'dist'); + mkdirSync(out); + writeFileSync(join(out, 'a.js'), `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + writeFileSync(join(out, 'a.js.map'), mapJson({ debugId: ID_A })); + const report = await diagnoseBuildOutput(out, { projectRoot: root, skipEnv: true }); + expect(ids(report)).not.toContain('map.pointer-outside-dir'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).not.toContain('map.hidden'); // the pointer paired a.js.map + expect(report.summary.errors + report.summary.warnings).toBe(0); + }); + }, +); + +describe('a scheme in sourceRoot (round 12)', () => { + it('sourceRoot + source is one URL: webpack:/// + src/x.ts names /src/x.ts', async () => { + put('../src/x.ts', 'x'); + const body = { debugId: ID_A, sourcesContent: undefined, sources: ['src/x.ts'] }; + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + for (const sourceRoot of ['webpack:///', 'webpack://app/', 'webpack://app']) { + put('a.js.map', mapJson({ ...body, sourceRoot })); + expect(ids(await run()), sourceRoot).not.toContain('map.sources-unresolvable'); + } + put('a.js.map', mapJson({ ...body, sourceRoot: 'webpack:///', sources: ['src/missing.ts'] })); + expect(ids(await run())).toContain('map.sources-unresolvable'); + }); +}); + +describe('symlinked HTML pages are scanned, or reported, never skipped silently (round 12)', () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const stalePage = ``; + + it('a link to a page inside the directory is read through its real path (stale pin found)', async () => { + put('a.js', `console.log(1);${stamp(ID_A)}`); + put('pages/real.html', stalePage.replace('a.js', '../a.js')); + symlinkSync(join(dist, 'pages', 'real.html'), join(dist, 'index.html')); + const report = await run(); + expect(ids(report)).toContain('sri.mismatch'); + }); + + it('a link that leads outside the directory (or dangles) is reported as not scanned', async () => { + put('a.js', `a${stamp(ID_A)}`); + writeFileSync(join(root, 'outside.html'), stalePage); + symlinkSync(join(root, 'outside.html'), join(dist, 'out.html')); + symlinkSync(join(root, 'nowhere.html'), join(dist, 'dangling.html')); + const finding = find(await run(), 'sri.html-skipped'); + expect(finding).toMatchObject({ + severity: 'warning', + details: { files: ['dangling.html', 'out.html'] }, + }); + expect(ids(await run())).not.toContain('sri.mismatch'); + }); +}); + +describe('sourcePath with a scheme sourceRoot (unit)', () => { + it('a source that already carries its own scheme or is absolute ignores the root', () => { + const map = '/p/dist'; + const proj = '/p'; + expect(sourcePath(map, 'webpack:///', 'src/x.ts', proj)).toBe('/p/src/x.ts'); + expect(sourcePath(map, 'webpack:///', 'webpack://app/src/x.ts', proj)).toBe('/p/src/x.ts'); + expect(sourcePath(map, 'webpack:///', 'file:///tmp/y.ts', proj)).toBe('/tmp/y.ts'); + expect(sourcePath(map, 'webpack:///', '/abs/z.ts', proj)).toBe('/abs/z.ts'); + expect(sourcePath(map, 'https://h/r', '/abs/z.ts', proj)).toBe('/abs/z.ts'); + // a non-URL source with a single-colon scheme is not joined to the root either: it resolves from the map + expect(sourcePath(map, 'webpack:///', 'node:fs', proj)).toBe('/p/dist/webpack:/node:fs'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.real-build.test.ts b/packages/bundler-plugin-core/src/doctor.real-build.test.ts new file mode 100644 index 00000000..f30dc4b9 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.real-build.test.ts @@ -0,0 +1,383 @@ +// The doctor against REAL build output: Vite 8 (Rolldown), Vite 7 (Rollup), Rollup and Rspack (webpack's +// processAssets stamping path) stamped by the real plugin + the real bugsee-cli, an unstamped build, an +// inline-map build, and SRI builds (stamped-first = fine; stamped-after-hash = the browser-blocking mismatch). +// Webpack itself is not a dependency of this package; Rspack exercises the same in-build stamp code. +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { rspack } from '@rspack/core'; +import { rollup } from 'rollup'; +import { type Plugin as VitePlugin, build as viteBuild } from 'vite'; +import { build as vite7Build } from 'vite7'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { type DoctorReport, diagnoseBuildOutput, doctorExitCode } from './doctor'; +import { bugseeRollupPlugin, bugseeRspackPlugin, bugseeUnplugin } from './plugin'; +import { resolveBugseeCli, runBugseeCli } from './run-cli'; + +let server: Server; +let endpoint: string; +let root: string; + +const cli = resolveBugseeCli(); +const probe = cli.endsWith('.js') + ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) + : spawnSync(cli, ['--version'], { encoding: 'utf8' }); +const cliAvailable = probe.status === 0; +const cliRequired = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; +const describeReal = cliAvailable || cliRequired ? describe : describe.skip; + +beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-real-')); + server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }), + ); + }); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}`; +}); +afterAll(async () => { + await new Promise((r) => server.close(() => r())); + rmSync(root, { recursive: true, force: true }); +}); + +const pluginOptions = (extra: object = {}) => ({ + appToken: 'doctor-token', + endpoint, + vcs: false, + registerBuild: false as const, + failOnError: true, + deleteMaps: false, // keep the maps on disk so the doctor has pairs to check + ...extra, +}); + +function makeApp(name: string, options: { lazy?: boolean } = {}): { dir: string; out: string } { + const dir = join(realpathSync(root), name); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, 'index.html'), + '\n', + ); + writeFileSync(join(dir, 'greet.js'), "export const greet = (n) => 'hello ' + n;\n"); + writeFileSync(join(dir, 'lazy.js'), "export default 'lazy chunk ' + Date.now();\n"); + writeFileSync( + join(dir, 'index.js'), + `import { greet } from './greet.js';\nconsole.log(greet('world'));\n${ + options.lazy === false ? '' : "import('./lazy.js').then((m) => console.log(m.default));\n" + }`, + ); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, version: '1.2.3' })); + return { dir, out: join(dir, 'dist') }; +} + +const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + +const viteConfig = (app: { dir: string; out: string }, plugins: unknown[], build: object = {}) => + ({ + root: app.dir, + configFile: false, + logLevel: 'silent', + base: './', + plugins, + build: { outDir: app.out, emptyOutDir: true, minify: false, sourcemap: 'hidden', ...build }, + }) as never; + +/** Pins every emitted chunk in the page, hashing in generateBundle (post), like an SRI plugin does. */ +const viteSri = (): VitePlugin => ({ + name: 'doctor-sri', + enforce: 'post', + generateBundle: { + order: 'post', + handler(_options, bundle) { + const page = bundle['index.html']; + if (page?.type === 'asset') { + page.source = String(page.source).replace( + /]*?src="\.?\/?([^"]+\.js)"[^>]*>/g, + (tag, file: string) => { + const entry = bundle[file]; + return entry?.type === 'chunk' + ? tag.replace(/>$/, ` integrity="${sri(entry.code)}">`) + : tag; + }, + ); + } + }, + }, +}); + +const doctor = (out: string, extra: { deployed?: boolean } = {}): Promise => + diagnoseBuildOutput(out, { + ...extra, + env: { BUGSEE_APP_TOKEN: 't', BUGSEE_APP_BUILD: 'b' }, + projectRoot: dirname(out), + }); +const idsOf = (report: DoctorReport, severity?: string): string[] => + report.findings.filter((f) => severity === undefined || f.severity === severity).map((f) => f.id); + +/** The only non-error findings a correctly stamped, maps-kept, hidden-map build is allowed to have. */ +function expectHealthyStamped(report: DoctorReport): void { + expect(idsOf(report, 'error')).toEqual([]); + expect(report.summary.bundles).toBeGreaterThanOrEqual(1); + expect(report.summary.maps).toBe(report.summary.bundles); + expect(idsOf(report).sort()).toEqual( + expect.arrayContaining(['map.hidden', 'map.public-leftover', 'map.sources-content']), + ); + // Straight after a plugin run nothing warns (so `--strict` passes); the leftover maps are a note... + expect(idsOf(report, 'warning')).toEqual([]); + expect(idsOf(report, 'info')).toContain('map.public-leftover'); + expect(report.passed).toEqual( + expect.arrayContaining([ + 'stamp.missing-debug-id', + 'stamp.map-id-mismatch', + 'stamp.missing-registration', + ]), + ); +} + +describeReal('doctor on real, stamped build output', () => { + it('Vite 8 (Rolldown) with hidden maps is healthy', async () => { + const app = makeApp('vite8'); + await viteBuild(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Vite 7 (Rollup) with hidden maps is healthy', async () => { + const app = makeApp('vite7'); + await vite7Build(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Rollup is healthy', async () => { + const app = makeApp('rollup'); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await bundle.write({ dir: app.out, sourcemap: 'hidden' }); + await bundle.close(); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Rollup with maps moved by sourcemapFileNames has no errors (and reports the wrong pointer Rollup writes)', async () => { + const app = makeApp('rollup-moved'); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await bundle.write({ + dir: app.out, + sourcemap: true, + sourcemapFileNames: 'maps/[name].map', + }); + await bundle.close(); + const report = await doctor(app.out, { deployed: true }); + expect(idsOf(report, 'error')).toEqual([]); + expect(report.summary.maps).toBe(report.summary.bundles); + expect(report.findings.some((f) => f.file?.startsWith('maps/'))).toBe(true); + // Rollup writes the pointer as `index.map` (relative to the file NAME, ignoring the `maps/` directory), so the + // browser's request 404s: the doctor says so, truthfully. The moved maps are still read and validated. + expect(idsOf(report, 'warning').sort()).toEqual([ + 'map.pointer-dangling', + 'map.public-leftover', + ]); + }); + + it('Rspack (webpack in-build stamping path) with hidden maps is healthy', async () => { + const app = makeApp('rspack'); + await new Promise((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: 'hidden-source-map', + output: { path: app.out }, + plugins: [bugseeRspackPlugin(pluginOptions())], + }); + compiler.run((err) => compiler.close(() => (err ? reject(err) : resolve()))); + }); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Vite with visible maps and the default deleteMaps leaves a dangling pointer (a note, and --strict passes)', async () => { + const app = makeApp('vite8-dangling'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ deleteMaps: true })) as VitePlugin], { + sourcemap: true, + }), + ); + const report = await doctor(app.out); + expect(report.summary.maps).toBe(0); + expect(idsOf(report, 'error')).toEqual([]); + // maps removed on purpose and every bundle stamped: a note, so --strict passes right after the plugin + expect(idsOf(report, 'warning')).toEqual([]); + expect(idsOf(report, 'info')).toContain('map.pointer-dangling'); + expect(doctorExitCode(report, true)).toBe(0); + }); +}); + +describeReal('doctor on Vite worker builds (stamped by the upload catch-up)', () => { + const workerApp = (name: string, form: 'url' | 'query'): { dir: string; out: string } => { + const app = makeApp(name); + writeFileSync(join(app.dir, 'w.js'), "postMessage('worker-ok');\n"); + writeFileSync( + join(app.dir, 'index.js'), + form === 'url' + ? "const w = new Worker(new URL('./w.js', import.meta.url), { type: 'module' });\nw.onmessage = (e) => console.log(e.data);\n" + : "import W from './w.js?worker';\nconst w = new W();\nw.onmessage = (e) => console.log(e.data);\n", + ); + return app; + }; + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + for (const form of ['url', 'query'] as const) { + it(`${label}, ${form} worker: main and worker bundles are stamped and their maps carry the same id`, async () => { + const app = workerApp(`doc-worker-${label.replace(/\W+/g, '')}-${form}`, form); + await build(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + const report = await doctor(app.out); + expect(report.summary.bundles).toBeGreaterThanOrEqual(2); // main + worker + expect(report.summary.maps).toBe(report.summary.bundles); + expect(idsOf(report, 'error')).toEqual([]); + expect(idsOf(report, 'warning')).toEqual([]); + expect(report.passed).toEqual( + expect.arrayContaining(['stamp.map-id-mismatch', 'stamp.map-no-debug-id', 'stamp.mixed']), + ); + }); + } + } +}); + +describeReal('doctor on multi-output and nested-directory Rollup builds', () => { + it('six outputs into one directory (maps kept) are all stamped, paired and clean', async () => { + const app = makeApp('doc-many-outputs', { lazy: false }); + const names = ['a', 'b', 'c', 'd', 'e', 'f']; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await Promise.all( + names.map((n) => + bundle.write({ + file: join(app.out, `${n}.js`), + format: 'iife', + name: `app_${n}`, + sourcemap: 'hidden', + }), + ), + ); + await bundle.close(); + const report = await doctor(app.out); + expect(report.summary).toMatchObject({ bundles: 6, maps: 6, errors: 0, warnings: 0 }); + expect(report.passed).toEqual( + expect.arrayContaining(['stamp.map-id-mismatch', 'stamp.duplicate-debug-id']), + ); + }); + + it('an output nested inside another: checking the parent walks both and finds no problem', async () => { + const app = makeApp('doc-nested-outputs', { lazy: false }); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await Promise.all([ + bundle.write({ + dir: app.out, + entryFileNames: 'p.js', + format: 'iife', + name: 'p', + sourcemap: 'hidden', + }), + bundle.write({ + dir: join(app.out, 'b'), + entryFileNames: 'c.js', + format: 'iife', + name: 'c', + sourcemap: 'hidden', + }), + ]); + await bundle.close(); + const parent = await doctor(app.out); + expect(parent.summary).toMatchObject({ bundles: 2, maps: 2, errors: 0, warnings: 0 }); + const nested = await doctor(join(app.out, 'b')); + expect(nested.summary).toMatchObject({ bundles: 1, maps: 1, errors: 0, warnings: 0 }); + }); +}); + +describeReal('doctor on real, problematic build output', () => { + it('an unstamped Vite build (plugin disabled) is an error per bundle', async () => { + const app = makeApp('vite8-unstamped'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin], { + sourcemap: true, + }), + ); + const report = await doctor(app.out); + const errors = report.findings.filter((f) => f.severity === 'error'); + expect(errors.length).toBeGreaterThan(0); + expect(errors.every((f) => f.id === 'stamp.missing-debug-id')).toBe(true); + expect(report.summary.errors).toBe(report.summary.bundles); + }); + + it('an inline-map Vite build is reported as map.inline', async () => { + const app = makeApp('vite8-inline'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin], { + sourcemap: 'inline', + }), + ); + const report = await doctor(app.out); + expect(idsOf(report, 'error')).toContain('map.inline'); + expect(report.summary.maps).toBe(0); + }); + + it('SRI: an unstamped build pinning hashes is flagged as a hazard; stamped-first is clean; stamped-after-hash is a mismatch', async () => { + const plain = makeApp('vite8-sri-plain'); + await viteBuild( + viteConfig(plain, [ + bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin, + viteSri(), + ]), + ); + const hazard = await doctor(plain.out); + expect(idsOf(hazard)).toContain('sri.unstamped-hazard'); + expect(idsOf(hazard)).not.toContain('sri.mismatch'); + + const first = makeApp('vite8-sri-first'); + await viteBuild( + viteConfig(first, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin, viteSri()]), + ); + const clean = await doctor(first.out); + expect(idsOf(clean)).not.toContain('sri.unstamped-hazard'); + expect(idsOf(clean)).not.toContain('sri.mismatch'); + expect(idsOf(clean, 'error')).toEqual([]); + expect(clean.passed).toContain('sri.mismatch'); + + // The post-emit stamp the in-build design exists to avoid: the page was hashed before the stamp. + const result = await runBugseeCli(['sourcemaps', 'inject', plain.out, '--allow-sri'], { + cwd: plain.dir, + }); + expect(result.code).toBe(0); + const broken = await doctor(plain.out); + expect(idsOf(broken, 'error')).toContain('sri.mismatch'); + expect(idsOf(broken)).not.toContain('sri.unstamped-hazard'); + expect(readdirSync(plain.out).length).toBeGreaterThan(0); + expect(readFileSync(join(plain.out, 'index.html'), 'utf8')).toContain('integrity='); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts new file mode 100644 index 00000000..4d307b29 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -0,0 +1,652 @@ +import { createHash } from 'node:crypto'; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + DOCTOR_CHECK_IDS, + DOCTOR_SCHEMA_VERSION, + type DoctorReport, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, +} from './doctor'; + +const ID_A = '11111111-1111-4111-8111-111111111111'; +const ID_B = '22222222-2222-4222-8222-222222222222'; +const ID_L = 'abcdef12-3456-4abc-8def-abcdefabcdef'; + +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'app', version: '1.0.0' })); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const put = (rel: string, content: string | Buffer): string => { + const path = join(dist, rel); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); + return path; +}; + +const stamp = (id: string): string => + `\n!function(){var g=globalThis;g._bugseeDebugIds=g._bugseeDebugIds||{};g._bugseeDebugIds["x"]="${id}"}();\n//# debugId=${id}\n`; + +const mapJson = (extra: Record = {}): string => + JSON.stringify({ + version: 3, + sources: ['a.ts'], + sourcesContent: ['export const a = 1;'], + names: [], + mappings: 'AAAA', + ...extra, + }); + +/** A fully stamped bundle + matching hidden map. */ +const goodPair = (name = 'app.js', id = ID_A): void => { + put(name, `console.log(1);${stamp(id)}`); + put(`${name}.map`, mapJson({ debugId: id })); +}; + +const ENV = { BUGSEE_APP_TOKEN: 'secret-token-value', BUGSEE_APP_BUILD: 'abc' }; +const run = (options: Parameters[1] = {}): Promise => + diagnoseBuildOutput(dist, { env: ENV, projectRoot: root, ...options }); +const ids = (report: DoctorReport): string[] => report.findings.map((f) => f.id); +const sev = (report: DoctorReport, id: string): string | undefined => + report.findings.find((f) => f.id === id)?.severity; + +describe('diagnoseBuildOutput', () => { + it('a stamped bundle with a matching hidden map has no warnings, only notes (even under --strict)', async () => { + goodPair(); + const report = await run(); + expect(report.schemaVersion).toBe(DOCTOR_SCHEMA_VERSION); + expect(report.tool).toBe('bugsee-sourcemaps-doctor'); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0, bundles: 1, maps: 1 }); + expect(ids(report).sort()).toEqual([ + 'env.token-source', + 'map.hidden', + 'map.public-leftover', + 'map.sources-content', + ]); + expect(sev(report, 'map.public-leftover')).toBe('info'); + expect(doctorExitCode(report, true)).toBe(0); + expect(report.passed).toContain('stamp.missing-debug-id'); + expect(report.passed).not.toContain('map.public-leftover'); + // info-only facts are not "passed" checks + expect(report.passed).not.toContain('map.hidden'); + expect(report.passed).not.toContain('env.token-source'); + }); + + it('map.public-leftover is a warning when the directory is deployed', async () => { + goodPair(); + const report = await run({ deployed: true }); + expect(sev(report, 'map.public-leftover')).toBe('warning'); + expect(report.findings.find((f) => f.id === 'map.public-leftover')?.fix).toContain( + '--deployed', + ); + expect(doctorExitCode(report, true)).toBe(1); + }); + + it('ignore drops the listed IDs from findings and passed, and reports what it dropped', async () => { + goodPair(); + const report = await run({ + deployed: true, + ignore: ['map.public-leftover', 'stamp.mixed', 'env.token-source'], + }); + expect(ids(report)).not.toContain('map.public-leftover'); + expect(report.summary.warnings).toBe(0); + expect(report.ignored).toEqual(['map.public-leftover', 'env.token-source']); + expect(report.passed).not.toContain('stamp.mixed'); + expect((await run()).ignored).toBeUndefined(); + }); + + it('after deleteMaps (bundle stamped, no maps) nothing is wrong', async () => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + const report = await run(); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0 }); + expect(ids(report)).toEqual(['env.token-source']); + expect(doctorExitCode(report)).toBe(0); + expect(doctorExitCode(report, true)).toBe(0); + }); + + it('output.dir-missing: a path that is not a directory', async () => { + const report = await diagnoseBuildOutput(join(root, 'nope'), { env: ENV }); + expect(ids(report)).toEqual(['output.dir-missing']); + expect(report.passed).toEqual([]); + expect(doctorExitCode(report)).toBe(2); + const asFile = await diagnoseBuildOutput(join(root, 'package.json'), { env: ENV }); + expect(ids(asFile)).toEqual(['output.dir-missing']); + }); + + it('output.no-js: a directory with no scripts; node_modules and .git are never searched', async () => { + put('index.html', ''); + put('node_modules/x/y.js', 'x'); + put('.git/z.js', 'x'); + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + expect(sev(report, 'output.no-js')).toBe('error'); + expect(report.summary.bundles).toBe(0); + }); + + it('preserveModules-style layouts (dist/src/a.js, dist/test/b.js, dot-dirs) are walked, not dropped', async () => { + put('src/a.js', `a${stamp(ID_A)}`); + put('test/b.js', `b${stamp(ID_B)}`); + put('.hidden/c.js', 'c'); + const report = await run(); + expect(report.summary.bundles).toBe(3); + expect(ids(report)).not.toContain('output.no-js'); + }); + + it('stamp.missing-debug-id: an unstamped bundle WITH a map is an error', async () => { + put('app.js', 'console.log(1);\n//# sourceMappingURL=app.js.map'); + put('app.js.map', mapJson()); + const report = await run(); + const finding = report.findings.find((f) => f.id === 'stamp.missing-debug-id'); + expect(finding).toMatchObject({ severity: 'error', file: 'app.js' }); + expect(finding?.fix).toContain('sourcemaps inject'); + expect(doctorExitCode(report)).toBe(2); + }); + + it('stamp.missing-debug-id: an unstamped bundle with NO map is only a warning', async () => { + put('vendor.js', 'console.log(1);'); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.missing-debug-id')).toMatchObject({ + severity: 'warning', + details: { files: ['vendor.js'] }, + }); + expect(doctorExitCode(report)).toBe(0); + expect(doctorExitCode(report, true)).toBe(1); + }); + + it('stamp.missing-debug-id: a bundle that lost its stamp while its map kept the id', async () => { + put('app.js', 'console.log(1);'); + put('app.js.map', mapJson({ debugId: ID_A })); + const report = await run(); + const found = report.findings.filter((f) => f.id === 'stamp.missing-debug-id'); + expect(found).toHaveLength(1); + expect(found[0]).toMatchObject({ severity: 'error', details: { mapDebugId: ID_A } }); + }); + + it('stamp.missing-registration: a comment alone is not a stamp', async () => { + put('app.js', `console.log(1);\n//# debugId=${ID_A}\n`); + const report = await run(); + expect(sev(report, 'stamp.missing-registration')).toBe('error'); + expect(report.findings.find((f) => f.id === 'stamp.missing-registration')?.details).toEqual({ + files: ['app.js'], + }); + }); + + it('stamp.map-id-mismatch / stamp.map-no-debug-id', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_B })); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', mapJson()); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')).toMatchObject({ + severity: 'error', + file: 'a.js.map', + details: { bundleDebugId: ID_A, mapDebugId: ID_B }, + }); + expect(report.findings.find((f) => f.id === 'stamp.map-no-debug-id')).toMatchObject({ + severity: 'error', + file: 'b.js.map', + }); + }); + + it('accepts the snake_case debug_id spelling in the map and compares case-insensitively', async () => { + put('a.js', `a${stamp(ID_L)}`); + put('a.js.map', mapJson({ debug_id: ID_L.toUpperCase() })); + const report = await run(); + expect(ID_L.toUpperCase()).not.toBe(ID_L); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('stamp.map-no-debug-id'); + }); + + it('stamp.mixed: some bundles stamped, some not', async () => { + goodPair('a.js', ID_A); + put('b.js', 'b\n//# sourceMappingURL=b.js.map'); + put('b.js.map', mapJson()); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.mixed')).toMatchObject({ + severity: 'warning', + details: { stamped: 1, unstamped: 1 }, + }); + }); + + it('stamp.duplicate-debug-id: same id, different contents; identical copies are fine', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('b.js', `different${stamp(ID_A)}`); + put('c.js', `same${stamp(ID_B)}`); + put('d.js', `same${stamp(ID_B)}`); + const report = await run(); + const dup = report.findings.filter((f) => f.id === 'stamp.duplicate-debug-id'); + expect(dup).toHaveLength(1); + expect(dup[0]).toMatchObject({ + severity: 'error', + details: { debugId: ID_A, files: ['a.js', 'b.js'] }, + }); + }); + + it('map.pointer-dangling: a note when the maps were removed on purpose; a warning otherwise', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=https://cdn.example/b.js.map${stamp(ID_B)}`); + const note = await run(); + const found = note.findings.find((f) => f.id === 'map.pointer-dangling'); + expect(found).toMatchObject({ severity: 'info', details: { pointers: ['a.js -> a.js.map'] } }); + expect(doctorExitCode(note, true)).toBe(0); + // a map file elsewhere in the output: the removal was not complete / deliberate + put('other.css.map', mapJson()); + expect(sev(await run(), 'map.pointer-dangling')).toBe('warning'); + rmSync(join(dist, 'other.css.map')); + // an unstamped bundle: nothing says the removal was deliberate + put('c.js', 'c'); + expect(sev(await run(), 'map.pointer-dangling')).toBe('warning'); + }); + + it('a pointer to a map in another directory resolves relative to the bundle', async () => { + put('js/a.js', `a\n//# sourceMappingURL=../maps/a.js.map${stamp(ID_A)}`); + put('maps/a.js.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')?.file).toBe( + 'maps/a.js.map', + ); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('a root-absolute or malformed pointer pairs nothing and is not reported dangling (the stamp rule)', async () => { + put('a.js', `a\n//# sourceMappingURL=/a.js.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=%E0%A4%A.map${stamp(ID_B)}`); + const report = await run(); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(report.summary.bundles).toBe(2); + }); + + it('a pointer with an unencoded space or percent-escape resolves like the stamp does', async () => { + put('a b.js', `a\n//# sourceMappingURL=a b.js.map${stamp(ID_A)}`); + put('a b.js.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')?.file).toBe('a b.js.map'); + }); + + it('map.inline: a data: map has nothing to upload', async () => { + put('a.js', `a\n//# sourceMappingURL=data:application/json;base64,e30=${stamp(ID_A)}`); + put('b.js', 'b\n//# sourceMappingURL=data:application/json;base64,e30='); + const report = await run(); + expect(report.findings.find((f) => f.id === 'map.inline')).toMatchObject({ + severity: 'error', + details: { files: ['a.js', 'b.js'] }, + }); + // the unstamped inline bundle is an error even though it has no .map file + expect(report.findings.find((f) => f.id === 'stamp.missing-debug-id')).toMatchObject({ + severity: 'error', + file: 'b.js', + }); + }); + + it('map.invalid: not JSON, not an object, wrong version; also for a map nothing points at', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', '{not json'); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', '[]'); + put('c.js', 'c'); + put('c.js.map', mapJson({ version: 2 })); + put('style.css.map', 'nope'); + put('other.css.map', mapJson({ version: 2 })); + const report = await run(); + const invalid = report.findings.filter((f) => f.id === 'map.invalid'); + expect(invalid.map((f) => f.file).sort()).toEqual([ + 'a.js.map', + 'b.js.map', + 'c.js.map', + 'other.css.map', + 'style.css.map', + ]); + expect(invalid.find((f) => f.file === 'a.js.map')?.message).toContain('not valid JSON'); + expect(invalid.find((f) => f.file === 'b.js.map')?.message).toContain('not a JSON object'); + expect(invalid.find((f) => f.file === 'c.js.map')?.message).toContain('version is 2'); + }); + + it('map.no-sources: missing or empty `sources`', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_A, sources: [] })); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', JSON.stringify({ version: 3, debugId: ID_B, mappings: '' })); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.no-sources').map((f) => f.file)).toEqual([ + 'a.js.map', + 'b.js.map', + ]); + }); + + it('map.sources-content: embedded is a fact; absent AND unresolvable is a warning; absent but on disk is a fact', async () => { + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sources: ['../src/gone.ts', 'webpack/runtime/x'], + }), + ); + put('b.js', `b${stamp(ID_B)}`); + mkdirSync(join(root, 'src'), { recursive: true }); + writeFileSync(join(root, 'src', 'here.ts'), 'x'); + put( + 'b.js.map', + mapJson({ debugId: ID_B, sourcesContent: [null], sources: ['../src/here.ts'] }), + ); + const report = await run(); + const a = report.findings.find((f) => f.id === 'map.sources-unresolvable'); + expect(a).toMatchObject({ + severity: 'warning', + file: 'a.js.map', + details: { unresolved: 1, total: 2 }, + }); + expect(a?.message).toContain('../src/gone.ts'); + const b = report.findings.find((f) => f.id === 'map.sources-content' && f.file === 'b.js.map'); + expect(b).toMatchObject({ severity: 'info', details: { embedded: 0, total: 1 } }); + }); + + it('sources resolve through sourceRoot, file:// and bundler-scheme prefixes', async () => { + mkdirSync(join(root, 'src'), { recursive: true }); + writeFileSync(join(root, 'src', 'a.ts'), 'x'); + writeFileSync(join(root, 'src', 'b.ts'), 'x'); + writeFileSync(join(root, 'src', 'c.ts'), 'x'); + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sourceRoot: '../src/', + sources: ['a.ts'], + }), + ); + put('b.js', `b${stamp(ID_B)}`); + put( + 'b.js.map', + mapJson({ + debugId: ID_B, + sourcesContent: undefined, + sources: [`file://${join(root, 'src', 'b.ts')}`], + }), + ); + put('c.js', 'c'); + put( + 'c.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sourceRoot: '..', + sources: ['webpack://app/src/c.ts', '\0virtual', ''], + }), + ); + const report = await run(); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('map.too-large: warns above the threshold', async () => { + goodPair(); + const report = await run({ maxMapBytes: 10 }); + expect(report.findings.find((f) => f.id === 'map.too-large')).toMatchObject({ + severity: 'warning', + file: 'app.js.map', + }); + expect((await run()).findings.map((f) => f.id)).not.toContain('map.too-large'); + }); + + it('build.dev-bundle: webpack eval-style output', async () => { + put('main.js', `eval("x\\n//# sourceURL=webpack-internal:///./src/a.ts");`); + const report = await run(); + expect(report.findings.find((f) => f.id === 'build.dev-bundle')).toMatchObject({ + severity: 'warning', + details: { files: ['main.js'] }, + }); + }); + + describe('SRI', () => { + const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + + it('sri.unstamped-hazard: a pinned script that would be broken by stamping', async () => { + const js = 'console.log(1);'; + put('app.js', js); + put('index.html', ``); + const report = await run(); + expect(report.findings.find((f) => f.id === 'sri.unstamped-hazard')).toMatchObject({ + severity: 'warning', + details: { scripts: ['app.js'] }, + }); + expect(ids(report)).not.toContain('sri.mismatch'); + }); + + it('a pin to a script that is not on disk is ignored', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('index.html', ``); + const report = await run(); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(report.summary.errors).toBe(0); + }); + + it('a stamped script whose pin matches its bytes is fine', async () => { + const js = `console.log(1);${stamp(ID_A)}`; + put('app.js', js); + put('index.html', ``); + const report = await run(); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(report.passed).toContain('sri.mismatch'); + }); + + it('sri.mismatch: stamped AFTER the page was hashed', async () => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + put('index.html', ``); + const report = await run(); + expect(report.findings.find((f) => f.id === 'sri.mismatch')).toMatchObject({ + severity: 'error', + details: { scripts: ['app.js'] }, + }); + expect(report.findings.find((f) => f.id === 'sri.mismatch')?.message).toContain('refuses'); + }); + + it('sri.manifest-hashes: a manifest in the directory pins hashes; the parent directory is never read', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('asset-manifest.json', JSON.stringify({ 'app.js': { integrity: sri('x') } })); + put('plain-manifest.json', '{}'); + put('readme.txt', 'integrity'); + // a page and a manifest in the PARENT (e.g. a CDN script with integrity) are not this build's business + writeFileSync( + join(root, 'index.html'), + ``, + ); + writeFileSync(join(root, 'pins-manifest.json'), `{"h":"${sri('y')}"}`); + const report = await run(); + const found = report.findings.find((f) => f.id === 'sri.manifest-hashes'); + expect(found?.severity).toBe('warning'); + expect(found?.details?.files).toEqual(['asset-manifest.json']); + }); + + it('a FIFO or oversized file named like a manifest is skipped, never opened', async () => { + put('app.js', `c${stamp(ID_A)}`); + const { spawnSync } = await import('node:child_process'); + if (spawnSync('mkfifo', [join(dist, 'x-manifest.json')]).status !== 0) { + return; + } + put('big-manifest.json', `{"integrity":"${'x'.repeat(100)}"}`); + const report = await run({ maxMapBytes: 50 }); + expect(ids(report)).not.toContain('sri.manifest-hashes'); + }); + }); + + describe('environment', () => { + it('env.token-missing is a warning; the token value is never printed, only where it came from', async () => { + goodPair(); + const report = await run({ env: {} }); + expect(report.findings.find((f) => f.id === 'env.token-missing')?.severity).toBe('warning'); + expect(ids(report)).not.toContain('env.token-source'); + const withToken = await run({ appToken: 'super-secret' }); + expect(JSON.stringify(withToken)).not.toContain('super-secret'); + expect(JSON.stringify(withToken)).not.toContain('secret-token-value'); + expect(ids(withToken)).not.toContain('env.token-missing'); + expect(withToken.findings.find((f) => f.id === 'env.token-source')).toMatchObject({ + severity: 'info', + details: { source: 'option' }, + }); + const fromEnv = await run(); + expect(fromEnv.findings.find((f) => f.id === 'env.token-source')?.details).toEqual({ + source: 'env', + }); + expect(JSON.stringify(fromEnv)).not.toContain('secret-token-value'); + // whitespace-only counts as unset + expect(ids(await run({ env: { BUGSEE_APP_TOKEN: ' ' } }))).toContain('env.token-missing'); + expect(ids(await run({ env: {}, appToken: ' ' }))).toContain('env.token-missing'); + }); + + it('env.version-unresolved / env.build-unresolved', async () => { + goodPair(); + const lonely = mkdtempSync(join(tmpdir(), 'bugsee-doctor-lonely-')); + try { + const report = await run({ env: { BUGSEE_APP_TOKEN: 't' }, projectRoot: lonely }); + expect(sev(report, 'env.version-unresolved')).toBe('warning'); + expect(sev(report, 'env.build-unresolved')).toBe('info'); + const explicit = await run({ + env: { BUGSEE_APP_TOKEN: 't' }, + projectRoot: lonely, + appVersion: '9.9.9', + appBuild: '7', + }); + expect(ids(explicit)).not.toContain('env.version-unresolved'); + expect(ids(explicit)).not.toContain('env.build-unresolved'); + } finally { + rmSync(lonely, { recursive: true, force: true }); + } + }); + + it('env.node-env-development', async () => { + goodPair(); + expect( + sev(await run({ env: { ...ENV, NODE_ENV: 'development' } }), 'env.node-env-development'), + ).toBe('warning'); + expect(ids(await run({ env: { ...ENV, NODE_ENV: 'production' } }))).not.toContain( + 'env.node-env-development', + ); + }); + + it('skipEnv drops every env.* check', async () => { + goodPair(); + const report = await run({ env: {}, skipEnv: true }); + expect(ids(report).filter((id) => id.startsWith('env.'))).toEqual([]); + expect(report.passed.filter((id) => id.startsWith('env.'))).toEqual([]); + }); + }); + + it('an output directory is walked at any depth', async () => { + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + put('a/b/c/d/e/f/ok.js', 'x'); + const report = await run(); + expect(report.summary.bundles).toBe(2); + }); + + it('only a project directory that is (or contains) the working directory is fenced and depth-capped', async () => { + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + put('a/ok.js', 'x'); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('package.json', '{"name":"p"}'); // a directory that IS a project; see doctor.hardening.test.ts + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run({ skipEnv: true }); + expect(report.summary.bundles).toBe(1); + } finally { + process.chdir(here); + } + }); + + it('a map pointer that resolves to a directory is skipped, not a crash', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + mkdirSync(join(dist, 'a.js.map')); + const report = await run(); + expect(report.summary.bundles).toBe(1); + expect(ids(report)).not.toContain('map.invalid'); + }); + + const describePerm = process.getuid?.() === 0 ? describe.skip : describe; + describePerm('unreadable paths', () => { + it('an unreadable sub-directory contributes nothing (and is reported, see doctor.hardening.test.ts); an unreadable parent is harmless', async () => { + put('a.js', `a${stamp(ID_A)}`); + mkdirSync(join(dist, 'locked')); + writeFileSync(join(dist, 'locked', 'x.js'), 'x'); + chmodSync(join(dist, 'locked'), 0o000); + chmodSync(root, 0o300); + try { + const report = await run({ skipEnv: true }); + expect(report.summary.bundles).toBe(1); + expect(ids(report)).not.toContain('sri.manifest-hashes'); + } finally { + chmodSync(root, 0o700); + chmodSync(join(dist, 'locked'), 0o700); + } + }); + + it('an unreadable manifest is ignored', async () => { + put('a.js', `a${stamp(ID_A)}`); + const manifest = put('asset-manifest.json', '{"integrity":1}'); + chmodSync(manifest, 0o000); + try { + expect(ids(await run({ skipEnv: true }))).not.toContain('sri.manifest-hashes'); + } finally { + chmodSync(manifest, 0o600); + } + }); + }); + + it('every check ID is unique and namespaced', () => { + expect(new Set(DOCTOR_CHECK_IDS).size).toBe(DOCTOR_CHECK_IDS.length); + for (const id of DOCTOR_CHECK_IDS) { + expect(id).toMatch(/^(output|stamp|map|sri|build|env|doctor)\.[a-z-]+$/); + } + }); +}); + +describe('doctorExitCode / formatDoctorReport', () => { + const report = (errors: number, warnings: number): DoctorReport => ({ + schemaVersion: 1, + tool: 'bugsee-sourcemaps-doctor', + dir: '/d', + summary: { errors, warnings, infos: 0, bundles: 0, maps: 0 }, + passed: [], + findings: [], + }); + + it('exit codes: 2 on errors, 1 on warnings only under strict, else 0', () => { + expect(doctorExitCode(report(1, 1), true)).toBe(2); + expect(doctorExitCode(report(0, 1), true)).toBe(1); + expect(doctorExitCode(report(0, 1))).toBe(0); + expect(doctorExitCode(report(0, 0), true)).toBe(0); + }); + + it('renders errors before warnings before notes, with fix hints', async () => { + put('vendor.js', 'x'); + put('app.js', `c${stamp(ID_A)}`); + put('app.js.map', mapJson({ debugId: ID_B })); + const text = formatDoctorReport(await run()); + const error = text.indexOf('ERROR [stamp.map-id-mismatch]'); + const warn = text.indexOf('WARN [stamp.missing-debug-id]'); + const info = text.indexOf('info [map.sources-content]'); + expect(error).toBeGreaterThan(-1); + expect(warn).toBeGreaterThan(error); + expect(info).toBeGreaterThan(warn); + expect(text).toContain(' fix: '); + expect(text).toContain('2 bundle(s), 1 map(s): 1 error(s)'); + }); + + it('says so when there is nothing to report', () => { + expect(formatDoctorReport(report(0, 0))).toContain('No problems found.'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts new file mode 100644 index 00000000..a9b9bbd0 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -0,0 +1,1322 @@ +// `sourcemaps doctor` — the OFFLINE half. Reads a build output directory exactly as it sits on disk and says +// why a crash from it would (not) symbolicate, without a network call, a token, or a backend. +// +// Every finding has a stable check ID, a severity, a human message and a fix hint, and the report has one +// versioned JSON shape (`DoctorReport`) that the Rust `bugsee-cli sourcemaps doctor` is specified to emit +// too (see the design hand-off), so a CI step can consume either. Pure reads: nothing is written or deleted. +import { createHash } from 'node:crypto'; +import type { Dirent } from 'node:fs'; +import { existsSync } from 'node:fs'; +import { readdir, realpath, stat } from 'node:fs/promises'; +import nodePath, { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { findAppIdentity } from './app-identity'; +import { readDebugId } from './debug-ids'; +import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; +import type { EnvRecord } from './run-cli'; +import { type ReadResult, readRegularFile } from './safe-read'; +import { findSriProtectedScriptsDetailed, MAX_HTML_BYTES, passesIntegrity } from './sri'; +import { cutAtQuery, isProjectRootOrAbove, MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; +import { lastSourceMappingUrl, localPointerTarget } from './verify-stamp'; + +/** Bumped on any incompatible change to `DoctorReport`; the Rust command emits the same number. */ +export const DOCTOR_SCHEMA_VERSION = 1; + +export type DoctorSeverity = 'error' | 'warning' | 'info'; + +/** One thing the doctor found. `id` is stable across releases and is what tooling should match on. */ +export interface DoctorFinding { + id: string; + severity: DoctorSeverity; + message: string; + /** What to do about it. Omitted for purely informational findings. */ + fix?: string; + /** The file concerned, relative to the checked directory (POSIX separators). */ + file?: string; + /** Machine-readable specifics (counts, ids, paths); never contains a secret. */ + details?: Record; +} + +export interface DoctorReport { + schemaVersion: typeof DOCTOR_SCHEMA_VERSION; + tool: 'bugsee-sourcemaps-doctor'; + /** Absolute path of the checked directory. */ + dir: string; + summary: { errors: number; warnings: number; infos: number; bundles: number; maps: number }; + /** Check IDs that ran and found nothing wrong. */ + passed: string[]; + findings: DoctorFinding[]; + /** Check IDs dropped by `ignore`; omitted when none were. */ + ignored?: string[]; +} + +export interface DoctorOptions { + /** Environment to resolve the token / version / build from. Defaults to `process.env`. */ + env?: EnvRecord; + /** An explicit token (the `appToken` plugin option). Never echoed. */ + appToken?: string; + appVersion?: string; + appBuild?: string; + /** Where `.env.bugsee-build-plugin` and `package.json` are looked up from. Defaults to the working directory. */ + projectRoot?: string; + /** A map larger than this many bytes is flagged. Default 50 MiB. */ + maxMapBytes?: number; + /** Skip the `env.*` checks (an output-only audit, e.g. in a container with no token). */ + skipEnv?: boolean; + /** + * The directory is (about to be) served to the public: leftover `.map` files are then a WARNING (they expose + * source) instead of a note. Off by default so `--strict` works straight after a plugin run. + */ + deployed?: boolean; + /** Check IDs to drop from the report (repeatable `--ignore`). */ + ignore?: readonly string[]; + /** A script larger than this many bytes is not read (default 512 MiB). */ + maxBundleBytes?: number; + /** + * Globs (relative to the checked directory, POSIX separators; `*` stays in a directory, `**` crosses them, `?` is + * one character, a trailing `/` means the directory) of files the build did NOT emit: a doctor cannot tell a + * script copied in (Vite `publicDir`, a copy plugin) from a bundle that lost its stamp, and the plugin never stamps + * the former. Matching files are dropped before analysis and listed as `output.excluded`. + */ + exclude?: readonly string[]; +} + +const DEFAULT_MAX_MAP_BYTES = 50 * 1024 * 1024; +const DEFAULT_MAX_BUNDLE_BYTES = 512 * 1024 * 1024; +/** Files read at once: bounds open handles. */ +const READ_CONCURRENCY = 16; +/** Bytes read at once (a batch of sixteen 512 MiB scripts is 8 GiB): a single larger file is still read, alone. */ +const READ_BYTE_BUDGET = 256 * 1024 * 1024; + +/** + * Where the batch starting at `start` ends (exclusive): at most `maxCount` files and `budget` bytes, but always at + * least one file. `sizes` are what `stat` reported. + */ +export function batchEnd( + sizes: readonly number[], + start: number, + maxCount: number, + budget: number, +): number { + let end = start + 1; + let total = sizes[start] ?? 0; + while (end < sizes.length && end - start < maxCount && total + (sizes[end] ?? 0) <= budget) { + total += sizes[end] ?? 0; + end++; + } + return end; +} +const BUNDLE = /\.[cm]?js$/i; +const MAP = /\.map$/i; +/** The global the runtime stub writes the id into (`@bugsee/browser` reads it at crash time). */ +const REGISTRATION = '_bugseeDebugIds'; +const MAX_LISTED = 5; + +/** Every ID the doctor can emit, in report order. Exported so docs / the Rust port can be checked against it. */ +export const DOCTOR_CHECK_IDS = [ + 'output.dir-missing', + 'output.no-js', + 'output.unreadable', + 'output.dir-unreadable', + 'output.excluded', + 'output.exclude-unmatched', + 'output.walk-fenced', + 'stamp.missing-debug-id', + 'stamp.missing-registration', + 'stamp.map-id-mismatch', + 'stamp.map-no-debug-id', + 'stamp.mixed', + 'stamp.duplicate-debug-id', + 'map.pointer-dangling', + 'map.hidden', + 'map.inline', + 'map.invalid', + 'map.no-sources', + 'map.sources-content', + 'map.sources-unresolvable', + 'map.too-large', + 'map.unreadable', + 'map.pointer-outside-dir', + 'map.public-leftover', + 'sri.unstamped-hazard', + 'sri.mismatch', + 'sri.html-skipped', + 'sri.pin-unreadable', + 'sri.manifest-hashes', + 'build.dev-bundle', + 'env.token-source', + 'env.token-missing', + 'env.version-unresolved', + 'env.build-unresolved', + 'env.node-env-development', + 'doctor.internal-error', +] as const; +export type DoctorCheckId = (typeof DOCTOR_CHECK_IDS)[number]; + +/** Hard failures: `--ignore` never hides these (it would turn "nothing was checked" into a pass). */ +export const NON_IGNORABLE_CHECK_IDS: ReadonlySet = new Set([ + 'output.dir-missing', + 'output.no-js', + 'doctor.internal-error', +]); + +const posix = (path: string): string => path.split('\\').join('/'); + +/** `bundle.js.map` -> the same name as written in the report; always relative to `dir`. */ +const rel = (dir: string, path: string): string => posix(relative(dir, path)); + +/** + * Every script and map under `root`, and the directories the fence skipped. An output directory is walked in full + * (Rollup `preserveModules` writes `dist/src/*.js`; a build may emit `dist/test/`), skipping only `node_modules` + * and `.git`; the fence on `src`/`test`/dot-directories and the depth cap apply ONLY when `root` is a project + * directory (has a `package.json`) that is, or contains, the working directory, where they keep the walk out of the + * source tree. What the fence skipped is returned, never silent. Iterative, and never spreads a result list (a + * directory with 100k files must not overflow the call stack). + */ +export async function walkDetailed( + root: string, +): Promise<{ files: string[]; skipped: string[]; fenced: boolean; unreadable: string[] }> { + const fenced = (await isProjectRootOrAbove(root)) && existsSync(join(root, 'package.json')); + const found: string[] = []; + const skipped: string[] = []; + const unreadable: string[] = []; + const pending: Array<{ dir: string; depth: number }> = [{ dir: root, depth: 0 }]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + if (fenced && next.depth > MAX_WALK_DEPTH) { + skipped.push(rel(root, next.dir)); + continue; + } + let entries: Dirent[]; + try { + entries = await readdir(next.dir, { withFileTypes: true }); + } catch { + // A directory whose scripts and maps were NOT seen: reported, never a silent pass. + unreadable.push(rel(root, next.dir) || '.'); + continue; + } + for (const entry of entries) { + const full = join(next.dir, entry.name); + if (entry.isDirectory()) { + if (entry.name === 'node_modules' || entry.name === '.git') { + continue; + } + if (fenced && (NEVER_WALK.has(entry.name) || entry.name.startsWith('.'))) { + skipped.push(rel(root, full)); + continue; + } + pending.push({ dir: full, depth: next.depth + 1 }); + } else if (BUNDLE.test(entry.name) || MAP.test(entry.name)) { + found.push(full); + } + } + } + return { files: found.sort(), skipped: skipped.sort(), fenced, unreadable: unreadable.sort() }; +} + +export async function walk(root: string): Promise { + return (await walkDetailed(root)).files; +} + +/** A glob (see {@link DoctorOptions.exclude}) as an anchored regular expression over a POSIX relative path. */ +export function globToRegExp(glob: string): RegExp { + const pattern = glob.endsWith('/') ? `${glob}**` : glob; + let source = ''; + for (let i = 0; i < pattern.length; i++) { + const c = pattern.charAt(i); + if (c === '*') { + if (pattern.charAt(i + 1) === '*') { + const slash = pattern.charAt(i + 2) === '/'; + source += slash ? '(?:.*/)?' : '.*'; + i += slash ? 2 : 1; + } else { + source += '[^/]*'; + } + } else if (c === '?') { + source += '[^/]'; + } else { + source += c.replace(/[\\^$.|+()[\]{}]/g, '\\$&'); + } + } + return new RegExp(`^${source}$`); +} + +/** + * The `sources` and their embedded `sourcesContent` (aligned by index) of a map. An ordinary map has them at the top + * level; an INDEX map keeps them inside `sections[].map`, so those are concatenated, each section's content padded to + * its own sources so the alignment survives. + */ +export function mapSources(json: Record): { + sources: unknown[]; + content: unknown[]; + roots: string[]; +} { + const sources: unknown[] = []; + const content: unknown[] = []; + const roots: string[] = []; + const collect = (map: Record, depth: number): void => { + if (Array.isArray(map.sources) && map.sources.length > 0) { + // A leaf map: its content and sourceRoot belong to ITS sources only (aligned by index). + const own = map.sources as unknown[]; + const embedded = Array.isArray(map.sourcesContent) ? (map.sourcesContent as unknown[]) : []; + const root = typeof map.sourceRoot === 'string' ? map.sourceRoot : ''; + own.forEach((source, i) => { + sources.push(source); + content.push(embedded[i]); + roots.push(root); + }); + return; + } + if (depth >= MAX_INDEX_DEPTH) { + return; + } + // An INDEX map keeps its maps inside `sections[].map`, which may be index maps themselves. + for (const section of Array.isArray(map.sections) ? (map.sections as unknown[]) : []) { + const inner = (section as { map?: unknown } | null)?.map; + if (typeof inner === 'object' && inner !== null) { + collect(inner as Record, depth + 1); + } + } + }; + collect(json, 0); + return { sources, content, roots }; +} + +/** Nested index maps are followed this deep (a real one is 1-2 levels); a hostile chain must not overflow the stack. */ +const MAX_INDEX_DEPTH = 32; + +interface ParsedMap { + ok: true; + json: Record; + debugId: string | undefined; +} + +function parseMap(text: string): ParsedMap | { ok: false; why: string } { + if (text.startsWith('\uFEFF')) { + return { + ok: false, + why: 'not valid JSON: it starts with a UTF-8 byte order mark (BOM), which the upload rejects', + }; + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return { ok: false, why: 'not valid JSON' }; + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return { ok: false, why: 'not a JSON object' }; + } + const json = parsed as Record; + const id = [json.debugId, json.debug_id].find((v) => typeof v === 'string' && v !== ''); + return { ok: true, json, debugId: typeof id === 'string' ? id.toLowerCase() : undefined }; +} + +/** `scheme://...`: a URL, not a directory name. */ +const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//i; + +/** Sources that name no file on disk by construction (bundler runtime, virtual modules). */ +const VIRTUAL_SOURCE = /^(webpack\/|\(webpack\)|\0|<|rollup:|vite\/)|\0/; + +/** + * Resolve a map `sources` entry as a debugger would. `file://` URLs follow `fileURLToPath` (so `file:///C:/x` + * is `C:\x` on Windows and a bad escape is "unknowable", not an exception). A bundler-scheme path + * (`webpack://app/./src/x.ts`) is relative to the PROJECT root, not to the map. Anything else is resolved from + * the map's directory and its `sourceRoot`. Undefined means "names no file on disk" (virtual / unparseable). + */ +export function sourcePath( + mapDir: string, + sourceRoot: string, + source: string, + projectRoot: string = mapDir, + api: typeof nodePath = nodePath, +): string | undefined { + let path = source; + let fromProject = false; + // ECMA-426: the source URL is `sourceRoot + source`. A scheme in the root (`webpack:///` + `src/x.ts`) is the + // same URL as the scheme written into `source`, so it takes the same rule below. + if ( + SCHEME_URL.test(sourceRoot) && + !/^[a-z][a-z0-9+.-]*:/i.test(source) && + !api.isAbsolute(source) + ) { + path = sourceRoot.endsWith('/') ? `${sourceRoot}${source}` : `${sourceRoot}/${source}`; + } + if (/^file:\/\//i.test(path)) { + try { + return fileURLToPath(path, api === nodePath.win32 ? { windows: true } : undefined); + } catch { + return undefined; + } + } + if (SCHEME_URL.test(path)) { + // `webpack://app/./src/x.ts` and friends: the scheme/namespace is not a directory; drop it. + path = path.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*\//i, ''); + fromProject = true; + } + if (VIRTUAL_SOURCE.test(path) || path === '') { + return undefined; + } + if (api.isAbsolute(path)) { + return path; + } + return fromProject ? api.resolve(projectRoot, path) : api.resolve(mapDir, sourceRoot, path); +} + +type InsideRead = { ok: true; bytes: Buffer; real: string } | Extract; + +/** + * Read `path` if, and only if, it is a regular file whose REAL path is inside `realRoot`. A symlink that resolves + * inside the directory (pnpm-style `assets/app.js -> ../.store/app.js`) is read through its real path; one that + * leads outside, dangles or loops is a value describing why, never a read. The open itself refuses a symlink, + * blocks on nothing and judges type and size on the descriptor (see safe-read.ts), so there is no + * check-then-use gap on the file. + */ +async function readInside(path: string, limit: number, realRoot: string): Promise { + let real: string; + try { + real = await realpath(path); + } catch (error) { + return { + ok: false, + reason: `could not be resolved (${(error as NodeJS.ErrnoException).code ?? 'error'})`, + }; + } + if (!isInside(realRoot, real)) { + return { ok: false, reason: 'resolves outside the output directory' }; + } + const read = await readRegularFile(real, limit); + return read.ok ? { ...read, real } : read; +} + +/** Most entries a `details` list carries; `total` says how many there were. */ +const MAX_DETAIL = 100; +const listDetails = (key: string, list: readonly unknown[]): Record => ({ + [key]: list.slice(0, MAX_DETAIL), + ...(list.length > MAX_DETAIL ? { total: list.length } : {}), +}); + +/** Whether `target` is `root` itself or inside it. */ +function isInside(root: string, target: string): boolean { + const path = relative(root, target); + return ( + path === '' || + !(path === '..' || path.startsWith(`..${nodePath.sep}`) || nodePath.isAbsolute(path)) + ); +} + +const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex'); + +/** + * `*manifest*.json` files directly in `dir` that mention integrity hashes. Only the checked directory is ever read + * (a page in the parent is not this build's to judge, and may be anything), through the bounded regular-file + * reader, so a FIFO or a `/dev/zero` symlink named like a manifest is skipped, not opened. + */ +async function manifestsWithIntegrity( + dir: string, + limit: number, + realRoot: string, +): Promise { + let names: string[]; + try { + names = await readdir(dir); + } catch { + return []; + } + const hits: string[] = []; + for (const name of names.sort()) { + if (!/manifest.*\.json$/i.test(name)) { + continue; + } + const read = await readInside(join(dir, name), limit, realRoot); + if ( + read.ok && + /\bintegrity\b|["'](sha(256|384|512))-[A-Za-z0-9+/=]{20,}/i.test(read.bytes.toString('utf8')) + ) { + hits.push(join(dir, name)); + } + } + return hits; +} + +/** + * Audit the build output in `dirInput`. Never throws for a problem with the directory (that is a finding); + * never writes; reads each script and map once, bounded by size, through the guarded reader (a duplicate-ID candidate is read a second time to compare contents). + */ +export async function diagnoseBuildOutput( + dirInput: string, + options: DoctorOptions = {}, +): Promise { + try { + return await diagnose(dirInput, options); + } catch (error) { + // The contract is "never throws": whatever went wrong is the finding. + return finish( + resolve(String(dirInput)), + [ + { + id: 'doctor.internal-error', + severity: 'error', + message: `The doctor failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`, + fix: 'This is a bug in the doctor; re-run with --json and report it with the directory layout.', + }, + ], + 0, + 0, + [], + options.ignore, + ); + } +} + +async function diagnose(dirInput: string, options: DoctorOptions): Promise { + const dir = resolve(dirInput); + const findings: DoctorFinding[] = []; + const failed = new Set(); + const add = (finding: DoctorFinding): void => { + findings.push(finding); + failed.add(finding.id); + }; + const env = options.env ?? (process.env as EnvRecord); + const maxMapBytes = options.maxMapBytes ?? DEFAULT_MAX_MAP_BYTES; + const maxBundleBytes = options.maxBundleBytes ?? DEFAULT_MAX_BUNDLE_BYTES; + const projectRoot = resolve(options.projectRoot ?? process.cwd()); + + let isDir = false; + try { + isDir = (await stat(dir)).isDirectory(); + } catch { + isDir = false; + } + if (!isDir) { + add({ + id: 'output.dir-missing', + severity: 'error', + message: `${dir} does not exist or is not a directory.`, + fix: 'Run the build first, and pass the bundler output directory (e.g. dist, build, .output/public).', + }); + return finish(dir, findings, 0, 0, [], options.ignore); + } + + const realDir = await realpath(dir); + const walked = await walkDetailed(dir); + // `./public/**` is `public/**`: a leading `./` would otherwise match nothing, silently. + const excludeGlobs = (options.exclude ?? []).map((glob) => glob.replace(/^(\.\/)+/, '')); + const patterns = excludeGlobs.map(globToRegExp); + const matchedPatterns = new Set(); + const isExcludedName = (name: string): boolean => { + let hit = false; + patterns.forEach((pattern, i) => { + if (pattern.test(name)) { + matchedPatterns.add(i); + hit = true; + } + }); + return hit; + }; + const isExcluded = (path: string): boolean => isExcludedName(rel(dir, path)); + const excluded: string[] = []; + const files = walked.files.filter((file) => { + if (isExcluded(file)) { + excluded.push(rel(dir, file)); + return false; + } + return true; + }); + const bundles = files.filter((f) => BUNDLE.test(f)); + const maps = files.filter((f) => MAP.test(f)); + if (bundles.length === 0) { + add({ + id: 'output.no-js', + severity: 'error', + message: `No .js/.cjs/.mjs files found under ${dir} (node_modules and .git are not searched).`, + fix: 'Point the doctor at the bundler output directory, not the project root or a source tree.', + }); + } + + if (excluded.length > 0) { + add({ + id: 'output.excluded', + severity: 'info', + message: `${excluded.length} file(s) matched --exclude and were not checked (${excluded.slice(0, MAX_LISTED).join(', ')}${excluded.length > MAX_LISTED ? ', …' : ''}).`, + details: listDetails('files', excluded), + }); + } + if (walked.skipped.length > 0) { + add({ + id: 'output.walk-fenced', + severity: 'info', + message: `${walked.skipped.length} director${walked.skipped.length === 1 ? 'y was' : 'ies were'} not searched because ${dir} looks like a project directory (${walked.skipped.slice(0, MAX_LISTED).join(', ')}${walked.skipped.length > MAX_LISTED ? ', …' : ''}).`, + fix: 'To audit them, run the doctor on the build output directory from the project root (not from inside a directory that has a package.json).', + details: listDetails('directories', walked.skipped), + }); + } + + const mapSet = new Set(maps); + // A map reached through two names (a symlinked directory, a case-variant pointer) is the same file: judged once. + const seenMaps = new Set(); + const markSeen = (real: string): boolean => { + if (seenMaps.has(real)) { + return false; + } + seenMaps.add(real); + return true; + }; + const contentFacts: Array<{ + file: string; + embeddedAll: boolean; + message: string; + details?: Record; + }> = []; + const claimedMaps = new Set(); + const stampedIds = new Map>(); + let stamped = 0; + const unstamped = new Set(); + const unstampedWithoutMap: string[] = []; + const noRegistration: string[] = []; + const dangling: string[] = []; + const outsideDir: string[] = []; + const devBundles: string[] = []; + const inline = new Set(); + const hidden: string[] = []; + const unreadable: string[] = []; + + // Reads happen in bounded batches; analysis stays sequential so findings keep a deterministic order. + const reads = new Map(); + const readBatch = async (batch: readonly string[]): Promise => { + const results = await Promise.all( + batch.map((path) => readInside(path, maxBundleBytes, realDir)), + ); + batch.forEach((path, i) => { + reads.set(path, results[i] as InsideRead); + }); + }; + + // What `stat` says each script weighs, to bound the bytes held at once (a failed stat weighs nothing: the read reports it). + const sizes = await Promise.all( + bundles.map((path) => + stat(path).then( + (info) => info.size, + () => 0, + ), + ), + ); + let readEnd = 0; + for (let at = 0; at < bundles.length; at++) { + if (at >= readEnd) { + reads.clear(); + readEnd = batchEnd(sizes, at, READ_CONCURRENCY, READ_BYTE_BUDGET); + await readBatch(bundles.slice(at, readEnd)); + } + const bundle = bundles[at] as string; + const name = rel(dir, bundle); + const read = reads.get(bundle) as InsideRead; + if (!read.ok) { + unreadable.push(`${name} ${read.reason}`); + continue; + } + const code = read.bytes.toString('utf8'); + const id = readDebugId(code); + + if (code.includes('webpack-internal:///')) { + devBundles.push(name); + } + + // Which map belongs to this bundle: the one its pointer names, else the sibling `.map`. + const pointer = lastSourceMappingUrl(code); + let mapPath: string | undefined; + if (pointer !== undefined && pointer !== '') { + if (/^data:/i.test(pointer)) { + inline.add(name); + } else { + // The pairing rule the stamp itself uses (verify-stamp.ts): a LOCAL pointer, resolved from the + // bundle's directory; remote / root-absolute / malformed pointers pair nothing. + const raw = localPointerTarget(bundle, code, nodePath); + // webpack / Rspack write `main.js?[hash]` to disk as `main.js` and keep the query in the pointer + // (`main.js.map?[hash]`): a server drops the query when it maps the URL to a file, so does the doctor + // (a file named with a `?` is not a `.map` file, so it could not have been paired anyway). + const bundleDir = nodePath.dirname(bundle); + const target = + raw === undefined + ? undefined + : nodePath.join(bundleDir, cutAtQuery(nodePath.relative(bundleDir, raw))); + if (target !== undefined) { + if (!isInside(dir, target)) { + // Never read it: a pointer can name `/dev/zero`, a FIFO or someone else's file. + outsideDir.push(`${name} -> ${pointer}`); + } else if (mapSet.has(target)) { + mapPath = target; + } else if (isExcluded(target)) { + // an excluded map is not the build's: neither read nor reported as dangling + } else { + // A symlinked DIRECTORY on the way can lead out although the path looks inside: judge the + // real path, never read through it. + const real = await realpath(target).catch(() => undefined); + if (real === undefined) { + dangling.push(`${name} -> ${pointer}`); + } else if (!isInside(realDir, real)) { + outsideDir.push(`${name} -> ${pointer}`); + } else { + mapPath = target; + } + } + } + } + } + if (mapPath === undefined && mapSet.has(`${bundle}.map`)) { + mapPath = `${bundle}.map`; + if (pointer === undefined) { + hidden.push(name); + } + } + + if (id === undefined) { + unstamped.add(name); + if (mapPath === undefined && !inline.has(name)) { + unstampedWithoutMap.push(name); + } + } else { + stamped++; + const list = stampedIds.get(id) ?? []; + list.push({ file: name, path: bundle }); + stampedIds.set(id, list); + if (!code.includes(REGISTRATION)) { + noRegistration.push(name); + } + } + + if (mapPath !== undefined) { + claimedMaps.add(mapPath); + const mapName = rel(dir, mapPath); + const mapRead = await readInside(mapPath, maxMapBytes, realDir); + if (!mapRead.ok) { + reportUnreadableMap(mapName, mapRead); + continue; + } + const parsed = parseMap(mapRead.bytes.toString('utf8')); + if (!parsed.ok) { + if (markSeen(mapRead.real)) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is ${parsed.why}, so it cannot be uploaded or used to symbolicate.`, + fix: 'Check the build is not truncating or post-processing the map; rebuild.', + }); + } + continue; + } + if (id !== undefined && parsed.debugId === undefined) { + add({ + id: 'stamp.map-no-debug-id', + severity: 'error', + file: mapName, + message: `${mapName} has no debugId, but its bundle ${name} carries ${id}; a crash cannot be matched to this map.`, + fix: 'Stamp the bundle and map together (the Bugsee plugin or `bugsee-cli sourcemaps inject`), and make sure no later step regenerates the map.', + details: { bundleDebugId: id }, + }); + } else if (id !== undefined && parsed.debugId !== undefined && parsed.debugId !== id) { + add({ + id: 'stamp.map-id-mismatch', + severity: 'error', + file: mapName, + message: `${mapName} has debugId ${parsed.debugId} but its bundle ${name} carries ${id}.`, + fix: 'Re-run the stamp over the final files; a minifier or copy step ran after stamping.', + details: { bundleDebugId: id, mapDebugId: parsed.debugId }, + }); + } else if (id === undefined && parsed.debugId !== undefined) { + add({ + id: 'stamp.missing-debug-id', + severity: 'error', + file: name, + message: `${name} has no debugId comment, but its map carries ${parsed.debugId}; the bundle lost its stamp.`, + fix: 'Something rewrote the bundle after stamping. Stamp last, or use the in-build stamping plugin.', + details: { mapDebugId: parsed.debugId }, + }); + // Counted once as unstamped above; do not double report below. + unstamped.delete(name); + } + validateMap(mapPath, mapName, parsed.json, mapRead.real); + } + } + + // Maps nothing points at (hidden maps of bundles are claimed above; this is the rest, e.g. css maps). + for (const map of maps) { + if (!claimedMaps.has(map)) { + const mapName = rel(dir, map); + const mapRead = await readInside(map, maxMapBytes, realDir); + if (!mapRead.ok) { + reportUnreadableMap(mapName, mapRead); + continue; + } + const parsed = parseMap(mapRead.bytes.toString('utf8')); + if (!parsed.ok) { + if (markSeen(mapRead.real)) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is ${parsed.why}.`, + fix: 'Check the build is not truncating or post-processing the map; rebuild.', + }); + } + } else { + validateMap(map, mapName, parsed.json, mapRead.real); + } + } + } + + function reportUnreadableMap(mapName: string, read: Extract): void { + if (read.tooLarge !== undefined) { + add({ + id: 'map.too-large', + severity: 'warning', + file: mapName, + message: `${mapName} is ${(read.tooLarge.size / 1024 / 1024).toFixed(1)} MiB (limit checked: ${(maxMapBytes / 1024 / 1024).toFixed(0)} MiB), so it was not read or validated; the upload may be slow or rejected.`, + fix: 'Split the bundle, strip sourcesContent (`stripSourcesContent`) or exclude vendor chunks; raise --max-map-mb to validate it.', + details: { bytes: read.tooLarge.size, limit: maxMapBytes }, + }); + } else { + add({ + id: 'map.unreadable', + severity: 'error', + file: mapName, + message: `${mapName} ${read.reason}, so it cannot be validated or uploaded.`, + fix: 'Make it a regular file inside the output directory (no symlink, FIFO or device).', + }); + } + } + + function validateMap( + mapPath: string, + mapName: string, + json: Record, + real: string, + ): void { + if (!markSeen(real)) { + return; // a map shared by several bundles is validated once + } + if (json.version !== 3) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is not a source map v3 (version is ${JSON.stringify(json.version)}).`, + fix: 'Only version 3 maps are supported; check the bundler/minifier output.', + }); + return; + } + if (typeof json.mappings !== 'string' && !Array.isArray(json.sections)) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} has neither \`mappings\` nor \`sections\`: it carries no position data, so no frame can be mapped.`, + fix: 'Check the build is not stripping the map; rebuild.', + }); + return; + } + const { sources, content, roots } = mapSources(json); + if (sources.length === 0) { + add({ + id: 'map.no-sources', + severity: 'error', + file: mapName, + message: `${mapName} has no \`sources\`; it can map nothing back to your code.`, + fix: 'Enable full source maps in the bundler (not a stripped / empty map).', + }); + return; + } + const missingAt = sources.flatMap((_, i) => (typeof content[i] !== 'string' ? [i] : [])); + const missing = missingAt.map((i) => String(sources[i])); + if (missing.length === 0) { + contentFacts.push({ + file: mapName, + embeddedAll: true, + message: `${mapName} embeds sourcesContent for all ${sources.length} sources.`, + }); + return; + } + const mapDir = dirname(mapPath); + const unresolved = missingAt.flatMap((i) => { + const path = sourcePath(mapDir, roots[i] as string, String(sources[i]), projectRoot); + return path !== undefined && !existsSync(path) ? [String(sources[i])] : []; + }); + if (unresolved.length > 0) { + add({ + id: 'map.sources-unresolvable', + severity: 'warning', + file: mapName, + message: `${mapName} embeds no sourcesContent for ${unresolved.length} of ${sources.length} sources and they are not on disk (${unresolved.slice(0, MAX_LISTED).join(', ')}${unresolved.length > MAX_LISTED ? ', …' : ''}); frames will show names but no source lines.`, + fix: 'Build with sourcesContent embedded (inlineSources / `sourcesContent: true`), or upload from a machine that still has the sources.', + details: { unresolved: unresolved.length, total: sources.length }, + }); + } else { + contentFacts.push({ + file: mapName, + embeddedAll: false, + message: `${mapName} does not embed sourcesContent for ${missing.length} sources, but they are resolvable on disk.`, + details: { embedded: sources.length - missing.length, total: sources.length }, + }); + } + } + + // --- aggregate findings ------------------------------------------------------------------------- + // One note per map is useful for a handful of maps and noise for thousands (a 20k-bundle build was 3.6 MB of JSON). + if (contentFacts.length <= MAX_LISTED * 2) { + for (const fact of contentFacts) { + findings.push({ + id: 'map.sources-content', + severity: 'info', + file: fact.file, + message: fact.message, + ...(fact.details !== undefined ? { details: fact.details } : {}), + }); + } + } else { + const embedded = contentFacts.filter((f) => f.embeddedAll).length; + findings.push({ + id: 'map.sources-content', + severity: 'info', + message: `${contentFacts.length} maps carry no sourcesContent problem: ${embedded} embed it for all sources, ${contentFacts.length - embedded} do not but their sources are resolvable on disk.`, + details: { + maps: contentFacts.length, + embedded, + resolvableOnDisk: contentFacts.length - embedded, + }, + }); + } + const withoutMap = new Set(unstampedWithoutMap); + if (bundles.length > 0 && unreadable.length === bundles.length) { + // Nothing was audited: that must not be ignorable into a pass (`--ignore output.unreadable`). + add({ + id: 'output.no-js', + severity: 'error', + message: `None of the ${bundles.length} script(s) under ${dir} could be read, so nothing was checked.`, + fix: 'Make the scripts regular files that the current user can read, and run the doctor again.', + }); + } + if (unreadable.length > 0) { + add({ + id: 'output.unreadable', + severity: 'error', + message: `${unreadable.length} script(s) could not be read (${unreadable.slice(0, MAX_LISTED).join('; ')}${unreadable.length > MAX_LISTED ? '; …' : ''}); they were not checked.`, + fix: 'Make them regular files under the size limit, or exclude them from the output directory.', + details: listDetails('files', unreadable), + }); + } + for (const name of unstamped) { + if (!withoutMap.has(name)) { + add({ + id: 'stamp.missing-debug-id', + severity: 'error', + file: name, + message: `${name} has no debugId comment: crashes from it cannot be matched to a source map.`, + fix: 'Add the Bugsee plugin (it stamps inside the build) or run `bugsee-cli sourcemaps inject

` after the build.', + }); + } + } + if (unstampedWithoutMap.length > 0) { + add({ + id: 'stamp.missing-debug-id', + severity: 'warning', + message: `${unstampedWithoutMap.length} bundle(s) are not stamped and have no map on disk (${unstampedWithoutMap.slice(0, MAX_LISTED).join(', ')}${unstampedWithoutMap.length > MAX_LISTED ? ', …' : ''}); they will not symbolicate.`, + fix: 'Emit source maps and stamp the build; ignore for vendor files you do not want symbolicated.', + details: listDetails('files', unstampedWithoutMap), + }); + } + if (noRegistration.length > 0) { + add({ + id: 'stamp.missing-registration', + severity: 'error', + message: `${noRegistration.length} bundle(s) have a debugId comment but no ${REGISTRATION} registration (${noRegistration.slice(0, MAX_LISTED).join(', ')}); the runtime cannot report the id with a crash.`, + fix: 'Re-stamp with `bugsee-cli sourcemaps inject` (it appends the registration); a hand-added comment is not enough.', + details: listDetails('files', noRegistration), + }); + } + if (stamped > 0 && unstamped.size > 0) { + add({ + id: 'stamp.mixed', + severity: 'warning', + message: `${stamped} bundle(s) are stamped but ${unstamped.size} are not (${[...unstamped].slice(0, MAX_LISTED).join(', ')}${unstamped.size > MAX_LISTED ? ', …' : ''}): a partial stamp usually means a second build output or a late-emitted file was missed.`, + fix: 'Run the stamp over the whole output directory after the last emit step.', + details: { stamped, unstamped: unstamped.size }, + }); + } + for (const [id, entries] of stampedIds) { + if (entries.length < 2) { + continue; // hashing is only worth it for an id that appears more than once + } + const hashes = new Set(); + for (const entry of entries) { + const read = await readInside(entry.path, maxBundleBytes, realDir); + hashes.add(read.ok ? sha(read.bytes) : `unreadable:${entry.path}`); + } + if (hashes.size > 1) { + add({ + id: 'stamp.duplicate-debug-id', + severity: 'error', + message: `debugId ${id} appears on ${entries.length} bundles with different contents (${entries.map((e) => e.file).join(', ')}); one will symbolicate with the other's map.`, + fix: 'Strip the old stamps and re-stamp (a copied or cached stamped file was edited), or clean the output dir before building.', + details: { debugId: id, files: entries.map((e) => e.file) }, + }); + } + } + if (dangling.length > 0) { + // No map file anywhere and every bundle stamped: the maps were removed on purpose (the plugin's + // `deleteMaps` after a confirmed upload), so the leftover comment is a note, not a defect to fail on. + const removedOnPurpose = maps.length === 0 && unstamped.size === 0; + add({ + id: 'map.pointer-dangling', + severity: removedOnPurpose ? 'info' : 'warning', + message: `${dangling.length} bundle(s) point at a source map that is not on disk (${dangling.slice(0, MAX_LISTED).join(', ')}${dangling.length > MAX_LISTED ? ', …' : ''}); browsers request it and get a 404${removedOnPurpose ? ' (harmless for symbolication: the maps were removed and the bundles are stamped)' : ''}.`, + fix: 'Emit hidden source maps (sourcemap: "hidden") so no pointer is written, or keep the maps until deploy.', + details: listDetails('pointers', dangling), + }); + } + if (outsideDir.length > 0) { + add({ + id: 'map.pointer-outside-dir', + severity: 'warning', + message: `${outsideDir.length} bundle(s) point at a source map outside ${dir} (${outsideDir.slice(0, MAX_LISTED).join(', ')}${outsideDir.length > MAX_LISTED ? ', …' : ''}); it was not read and cannot be paired.`, + fix: 'Emit the map inside the output directory, or check the sourceMappingURL.', + details: listDetails('pointers', outsideDir), + }); + } + if (hidden.length > 0) { + findings.push({ + id: 'map.hidden', + severity: 'info', + message: `${hidden.length} bundle(s) have a map but no sourceMappingURL comment (hidden maps): good for privacy.`, + details: listDetails('files', hidden), + }); + } + if (inline.size > 0) { + add({ + id: 'map.inline', + severity: 'error', + message: `${inline.size} bundle(s) carry an inline (data:) source map (${[...inline].slice(0, MAX_LISTED).join(', ')}); there is no .map file to upload and the map ships to every visitor.`, + fix: 'Switch to external hidden maps (Vite `build.sourcemap: "hidden"`, webpack `devtool: "hidden-source-map"`, esbuild `sourcemap: "external"`).', + details: listDetails('files', [...inline]), + }); + } + if (devBundles.length > 0) { + add({ + id: 'build.dev-bundle', + severity: 'warning', + message: `${devBundles.length} bundle(s) look like a development build (webpack eval-style sourceURL markers: ${devBundles.slice(0, MAX_LISTED).join(', ')}); eval maps are not uploadable and bundles are unminified.`, + fix: 'Build in production mode (mode: "production", NODE_ENV=production) before uploading.', + details: listDetails('files', devBundles), + }); + } + if (maps.length > 0) { + add({ + id: 'map.public-leftover', + severity: options.deployed === true ? 'warning' : 'info', + message: `${maps.length} .map file(s) are on disk in ${dir}; if this directory is deployed they are served publicly and expose your source.`, + fix: 'Keep `deleteMaps` on (default) so maps are removed after a confirmed upload, or emit hidden maps and exclude *.map from deploys. Run with --deployed on the directory you actually serve to make this a warning.', + details: { count: maps.length, files: maps.slice(0, MAX_LISTED).map((m) => rel(dir, m)) }, + }); + } + + // --- SRI ------------------------------------------------------------------------------------------ + const sriScan = await findSriProtectedScriptsDetailed(dir, MAX_HTML_BYTES, walked.fenced); + const allUnreadable = [ + ...new Set([...walked.unreadable, ...sriScan.unreadableDirs.map((d) => rel(dir, d) || '.')]), + ].sort(); + // `--exclude vendor/**` (or `vendor/`) names a directory too. + // Excluded only if a pattern would hide the files INSIDE (probed with a deep path, so `vendor/*` or `vendor*` do not + // hide a directory that, if it could be listed, would still be audited): never broader than for a readable one. + const excludedDirs = allUnreadable.filter((d) => isExcludedName(`${d}/a/b/c.js`)); + const unreadableDirs = allUnreadable.filter((d) => !excludedDirs.includes(d)); + if (excludedDirs.length > 0) { + add({ + id: 'output.excluded', + severity: 'info', + message: `${excludedDirs.length} unreadable director${excludedDirs.length === 1 ? 'y' : 'ies'} matched --exclude and ${excludedDirs.length === 1 ? 'was' : 'were'} not checked (${excludedDirs.slice(0, MAX_LISTED).join(', ')}${excludedDirs.length > MAX_LISTED ? ', …' : ''}).`, + details: listDetails('directories', excludedDirs), + }); + } + if (unreadableDirs.length > 0) { + // Scripts, maps and pages in them were NOT checked: a pass would be false. + add({ + id: 'output.dir-unreadable', + severity: 'error', + message: `${unreadableDirs.length} director${unreadableDirs.length === 1 ? 'y' : 'ies'} could not be listed, so nothing in ${unreadableDirs.length === 1 ? 'it was' : 'them was'} checked (${unreadableDirs.slice(0, MAX_LISTED).join(', ')}${unreadableDirs.length > MAX_LISTED ? ', …' : ''}).`, + fix: 'Make the directories readable by the user running the doctor (a build run as root in a container, then checked as another user, is the usual cause) and run it again.', + details: listDetails('directories', unreadableDirs), + }); + } + const pinned = sriScan.scripts.filter((pin) => !isExcluded(pin.script)); + // Pages named by `--exclude` are not the build's to judge either (oversized or unreadable alike). + const skippedPages = sriScan.skippedPages.filter((page) => !isExcluded(page.html)); + const unreadablePages = sriScan.unreadablePages.filter((page) => !isExcluded(page)); + const unmatched = excludeGlobs.filter((_, i) => !matchedPatterns.has(i)); + if (unmatched.length > 0) { + add({ + id: 'output.exclude-unmatched', + severity: 'info', + message: `${unmatched.length} --exclude pattern(s) matched no file (${unmatched.join(', ')}); patterns are relative to ${dir} (Vite copies publicDir to its ROOT: write sw.js, not public/sw.js).`, + details: { patterns: unmatched }, + }); + } + if (skippedPages.length > 0) { + const names = skippedPages.map((page) => rel(dir, page.html)); + add({ + id: 'sri.html-skipped', + severity: 'warning', + message: `${names.length} page(s) are larger than ${MAX_HTML_BYTES / 1024 / 1024} MiB and were not scanned for integrity pins (${names.slice(0, MAX_LISTED).join(', ')}${names.length > MAX_LISTED ? ', …' : ''}); a script they pin would not be noticed.`, + fix: 'A real page is a few KB; check that this is not a data file named .html. Stamping still sees pins in such a page.', + details: listDetails('files', names), + }); + } + if (unreadablePages.length > 0) { + const names = unreadablePages.map((page) => rel(dir, page)); + add({ + id: 'sri.html-skipped', + severity: 'warning', + message: `${names.length} page(s) could not be read and were not scanned for integrity pins (${names.slice(0, MAX_LISTED).join(', ')}${names.length > MAX_LISTED ? ', …' : ''}); a script they pin would not be noticed.`, + fix: 'Make the pages readable and run the doctor again.', + details: listDetails('files', names), + }); + } + if (pinned.length > 0) { + const unstampedPinned: typeof pinned = []; + const mismatches: typeof pinned = []; + const pinsUnread: string[] = []; + for (const p of pinned) { + // The same guarded reader as every other read (symlinks resolved only if they stay inside the directory, + // regular files of bounded size only). The bytes read here are also what the integrity check judges. + const read = await readInside(p.script, maxBundleBytes, realDir); + if (!read.ok) { + // A pin to a file that is not there is stale, not something stamping would break; anything else (it + // leads outside, is a FIFO, is too large) is a pin we could not judge, and that is said. + if (!read.reason.includes('(ENOENT)')) { + pinsUnread.push(`${rel(dir, p.script)} ${read.reason}`); + } + continue; + } + if (!passesIntegrity(p.integrity, read.bytes)) { + mismatches.push(p); + } + if (readDebugId(read.bytes.toString('utf8')) === undefined) { + unstampedPinned.push(p); + } + } + if (pinsUnread.length > 0) { + add({ + id: 'sri.pin-unreadable', + severity: 'warning', + message: `${pinsUnread.length} script(s) pinned by an integrity hash could not be checked (${pinsUnread.slice(0, MAX_LISTED).join('; ')}${pinsUnread.length > MAX_LISTED ? '; …' : ''}).`, + fix: 'Make the pinned scripts regular files inside the output directory.', + details: listDetails('scripts', pinsUnread), + }); + } + if (unstampedPinned.length > 0) { + add({ + id: 'sri.unstamped-hazard', + severity: 'warning', + message: `${unstampedPinned.length} script(s) are pinned by an integrity hash in ${rel(dir, unstampedPinned[0]?.html ?? dir)} and are not stamped; stamping them AFTER the page was written would make the browser block them.`, + fix: 'Use the Bugsee plugin (stamps before the SRI plugin hashes; list it first), or re-generate the integrity hashes after `sourcemaps inject`.', + details: { scripts: unstampedPinned.map((p) => rel(dir, p.script)) }, + }); + } + if (mismatches.length > 0) { + add({ + id: 'sri.mismatch', + severity: 'error', + message: `${mismatches.length} script(s) no longer match the integrity hash pinning them (${mismatches + .slice(0, MAX_LISTED) + .map((m) => rel(dir, m.script)) + .join(', ')}); the browser refuses to run them and the page loads nothing.`, + fix: 'Something rewrote the files after the hashes were computed (usually a post-build stamp). Stamp first, hash last.', + details: { scripts: mismatches.map((m) => rel(dir, m.script)) }, + }); + } + } + const manifests = await manifestsWithIntegrity(dir, maxMapBytes, realDir); + if (manifests.length > 0) { + const names = manifests.map((p) => rel(dir, p)); + add({ + id: 'sri.manifest-hashes', + severity: 'warning', + message: `${names.join(', ')} mention integrity hashes the doctor cannot tie to a script; if they pin these bundles, stamping them afterwards breaks the page.`, + fix: 'Check whether the manifest pins hashes of these files; if so make stamping happen before they are computed, or regenerate them. (A page outside this directory is not read: run the doctor on the directory that holds it.)', + details: { files: names }, + }); + } + + // --- environment ---------------------------------------------------------------------------------- + if (options.skipEnv !== true) { + const root = projectRoot; + const fromFile = loadBuildPluginEnv(root); + const merged = mergeBuildPluginEnv(env, fromFile.values); + const optionToken = options.appToken?.trim() ?? ''; + const envToken = merged.BUGSEE_APP_TOKEN?.trim() ?? ''; + if (optionToken === '' && envToken === '') { + add({ + id: 'env.token-missing', + severity: 'warning', + message: + 'No Bugsee app token is resolvable (BUGSEE_APP_TOKEN, .env.bugsee-build-plugin, or the appToken option): the bundler plugin is disabled and uploads nothing (fine if you upload with bugsee-cli by hand).' + + (fromFile.problem !== undefined ? ` ${fromFile.problem}` : ''), + fix: 'Set BUGSEE_APP_TOKEN in the build environment or in .env.bugsee-build-plugin next to your project.', + }); + } else { + // Where it came from, never the value: the same precedence the plugin applies (option, env, file). + const source = + optionToken !== '' + ? ('option' as const) + : (env.BUGSEE_APP_TOKEN?.trim() ?? '') !== '' + ? ('env' as const) + : ('env-file' as const); + const label = { + option: 'the appToken option', + env: 'the BUGSEE_APP_TOKEN environment variable', + 'env-file': '.env.bugsee-build-plugin', + }[source]; + findings.push({ + id: 'env.token-source', + severity: 'info', + message: `The app token comes from ${label}.`, + details: { source }, + }); + } + const identity = findAppIdentity( + { appVersion: options.appVersion, appBuild: options.appBuild }, + merged, + {}, + root, + ); + if (identity.version === undefined) { + add({ + id: 'env.version-unresolved', + severity: 'warning', + message: `No app version is resolvable (BUGSEE_APP_VERSION or a package.json version at or above ${root}); the upload is labelled 0.0.0.`, + fix: 'Set BUGSEE_APP_VERSION, or pass --project-root to the directory holding package.json.', + }); + } + if (identity.build === undefined) { + add({ + id: 'env.build-unresolved', + severity: 'info', + message: + 'No app build id is resolvable (BUGSEE_APP_BUILD or a CI commit variable); the build is labelled 0.', + fix: 'Set BUGSEE_APP_BUILD (e.g. the commit SHA) so builds can be told apart.', + }); + } + if (merged.NODE_ENV === 'development') { + add({ + id: 'env.node-env-development', + severity: 'warning', + message: + 'NODE_ENV is "development": the Bugsee plugins skip the upload for development builds (unless uploadInDevelopment is set).', + fix: 'Build with NODE_ENV=production for the build you deploy.', + }); + } + } + + // A check with no input did not run: no scripts means no stamp / pointer checks, no maps no map-content checks. + const needsBundles = (id: string): boolean => id.startsWith('stamp.') || NEEDS_BUNDLES.has(id); + const passed = DOCTOR_CHECK_IDS.filter( + (id) => + !failed.has(id) && + !INFO_ONLY.has(id) && + !(options.skipEnv === true && id.startsWith('env.')) && + !(bundles.length === 0 && needsBundles(id)) && + !(maps.length === 0 && NEEDS_MAPS.has(id)), + ); + return finish(dir, findings, bundles.length, maps.length, passed, options.ignore); +} + +const NEEDS_BUNDLES: ReadonlySet = new Set([ + 'build.dev-bundle', + 'map.pointer-dangling', + 'map.pointer-outside-dir', + 'map.inline', +]); +const NEEDS_MAPS: ReadonlySet = new Set([ + 'map.invalid', + 'map.no-sources', + 'map.sources-unresolvable', + 'map.too-large', + 'map.unreadable', +]); + +/** Checks that only ever produce an `info` finding: they are not "passed", they are facts. */ +const INFO_ONLY: ReadonlySet = new Set([ + 'output.excluded', + 'output.exclude-unmatched', + 'output.walk-fenced', + 'map.hidden', + 'map.sources-content', + 'env.token-source', + 'doctor.internal-error', +]); + +function finish( + dir: string, + findings: DoctorFinding[], + bundles: number, + maps: number, + passed: readonly string[], + ignore: readonly string[] = [], +): DoctorReport { + ignore = ignore.filter((id) => !NON_IGNORABLE_CHECK_IDS.has(id)); + const dropped = ignore.filter((id) => findings.some((f) => f.id === id)); + if (dropped.length > 0) { + findings = findings.filter((f) => !ignore.includes(f.id)); + } + const count = (severity: DoctorSeverity): number => + findings.filter((f) => f.severity === severity).length; + return { + schemaVersion: DOCTOR_SCHEMA_VERSION, + tool: 'bugsee-sourcemaps-doctor', + dir, + summary: { + errors: count('error'), + warnings: count('warning'), + infos: count('info'), + bundles, + maps, + }, + passed: passed.filter((id) => !ignore.includes(id)), + findings, + ...(dropped.length > 0 ? { ignored: [...new Set(dropped)] } : {}), + }; +} + +/** 0 clean, 2 errors, 1 warnings only under `strict`. */ +export function doctorExitCode(report: DoctorReport, strict = false): 0 | 1 | 2 { + if (report.summary.errors > 0) { + return 2; + } + return strict && report.summary.warnings > 0 ? 1 : 0; +} + +const MARK: Record = { + error: 'ERROR ', + warning: 'WARN ', + info: 'info ', +}; + +/** The human rendering. Stable enough to read; machines should use the JSON report. */ +export function formatDoctorReport(report: DoctorReport): string { + const lines = [ + `Bugsee source-map doctor: ${report.dir}`, + `${report.summary.bundles} bundle(s), ${report.summary.maps} map(s): ${report.summary.errors} error(s), ${report.summary.warnings} warning(s), ${report.summary.infos} note(s)`, + '', + ]; + const order: DoctorSeverity[] = ['error', 'warning', 'info']; + for (const severity of order) { + for (const finding of report.findings.filter((f) => f.severity === severity)) { + lines.push(`${MARK[severity]}[${finding.id}] ${finding.message}`); + if (finding.fix !== undefined) { + lines.push(` fix: ${finding.fix}`); + } + } + } + if (report.findings.length === 0) { + lines.push('No problems found.'); + } + return lines.join('\n'); +} diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index 3d4be951..0f624d75 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -10,6 +10,18 @@ export { findPackageVersion, } from './app-identity'; export { deriveBuildUuid } from './build-id'; +export { + DOCTOR_CHECK_IDS, + DOCTOR_SCHEMA_VERSION, + type DoctorCheckId, + type DoctorFinding, + type DoctorOptions, + type DoctorReport, + type DoctorSeverity, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, +} from './doctor'; export { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; export { defaultDeleteMapFiles, diff --git a/packages/bundler-plugin-core/src/safe-read.test.ts b/packages/bundler-plugin-core/src/safe-read.test.ts new file mode 100644 index 00000000..5a4f9977 --- /dev/null +++ b/packages/bundler-plugin-core/src/safe-read.test.ts @@ -0,0 +1,75 @@ +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { readRegularFile } from './safe-read'; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'bugsee-safe-read-')); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('readRegularFile', () => { + it('reads a regular file, including an empty one', async () => { + writeFileSync(join(dir, 'a'), 'hello'); + writeFileSync(join(dir, 'empty'), ''); + const read = await readRegularFile(join(dir, 'a'), 100); + expect(read.ok && read.bytes.toString()).toBe('hello'); + const empty = await readRegularFile(join(dir, 'empty'), 100); + expect(empty.ok && empty.bytes.length).toBe(0); + }); + + it('the limit is exact: equal reads, one over is too large (judged by the size, before reading)', async () => { + writeFileSync(join(dir, 'a'), 'hello'); + expect((await readRegularFile(join(dir, 'a'), 5)).ok).toBe(true); + expect(await readRegularFile(join(dir, 'a'), 4)).toEqual({ + ok: false, + reason: 'is too large to read', + tooLarge: { size: 5 }, + }); + }); + + it('a symlink in the last component is refused, not followed', async () => { + writeFileSync(join(dir, 'real'), 'x'); + symlinkSync(join(dir, 'real'), join(dir, 'link')); + expect(await readRegularFile(join(dir, 'link'), 100)).toEqual({ + ok: false, + reason: 'is a symbolic link', + }); + }); + + it('a FIFO is refused without blocking; a device is refused without reading', async () => { + if (spawnSync('mkfifo', [join(dir, 'pipe')]).status === 0) { + expect(await readRegularFile(join(dir, 'pipe'), 100)).toEqual({ + ok: false, + reason: 'is not a regular file', + }); + } + expect(await readRegularFile('/dev/zero', 100)).toEqual({ + ok: false, + reason: 'is not a regular file', + }); + }, 10_000); + + it('a directory is not a regular file; a missing or unreadable file is a value, not a throw', async () => { + mkdirSync(join(dir, 'd')); + expect(await readRegularFile(join(dir, 'd'), 100)).toEqual({ + ok: false, + reason: 'is not a regular file', + }); + expect(await readRegularFile(join(dir, 'missing'), 100)).toEqual({ + ok: false, + reason: 'could not be read (ENOENT)', + }); + if (process.getuid?.() !== 0) { + writeFileSync(join(dir, 'locked'), 'x'); + chmodSync(join(dir, 'locked'), 0o000); + expect(await readRegularFile(join(dir, 'locked'), 100)).toEqual({ + ok: false, + reason: 'could not be read (EACCES)', + }); + } + }); +}); diff --git a/packages/bundler-plugin-core/src/safe-read.ts b/packages/bundler-plugin-core/src/safe-read.ts new file mode 100644 index 00000000..7185718e --- /dev/null +++ b/packages/bundler-plugin-core/src/safe-read.ts @@ -0,0 +1,66 @@ +// Bounded, race-resistant reads of build-output files. +// +// A path in a build output is untrusted input to a diagnostic: it can be a FIFO (opening it blocks for ever), a +// device (`/dev/zero` never ends), a symlink out of the tree, or a file that is swapped between a check and the +// read. So the file is OPENED first (without following a symlink in the last component, and without blocking on a +// FIFO), and every judgement (regular file? how big?) is made on the open descriptor, not on the path. +import { constants } from 'node:fs'; +import { open } from 'node:fs/promises'; + +export type ReadResult = + | { ok: true; bytes: Buffer } + | { ok: false; reason: string; tooLarge?: { size: number } }; + +/** + * `O_NOFOLLOW` / `O_NONBLOCK` are absent on some platforms (Windows). There the "never follows a symlink in the last + * component" guarantee is WEAKER: only the descriptor checks (regular file, size) apply, and callers that must stay + * inside a directory (`readInside` in doctor.ts) additionally resolve the real path and check containment first. + */ +const OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0); + +/** + * Read a regular file of at most `limit` bytes. Never follows a symlink in the last component (ELOOP is "is a + * symbolic link"), never blocks on a FIFO, never reads a device, and never reads more than the size the open + * descriptor reported. A failure is a value, not a throw. + */ +export async function readRegularFile(path: string, limit: number): Promise { + let handle: Awaited>; + try { + handle = await open(path, OPEN_FLAGS); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code ?? 'error'; + return { + ok: false, + reason: code === 'ELOOP' ? 'is a symbolic link' : `could not be read (${code})`, + }; + } + try { + const info = await handle.stat(); + if (!info.isFile()) { + return { ok: false, reason: 'is not a regular file' }; + } + if (info.size > limit) { + return { ok: false, reason: 'is too large to read', tooLarge: { size: info.size } }; + } + const bytes = Buffer.alloc(info.size); + let filled = 0; + while (filled < bytes.length) { + const { bytesRead } = await handle.read(bytes, filled, bytes.length - filled, filled); + /* v8 ignore next 3 -- a file truncated between the stat and the read; not reproducible deterministically */ + if (bytesRead === 0) { + break; // the file shrank after the stat: judge what is there + } + filled += bytesRead; + } + return { ok: true, bytes: filled === bytes.length ? bytes : bytes.subarray(0, filled) }; + /* v8 ignore start -- an I/O error on an already open regular file (EIO); not reproducible in a test */ + } catch (error) { + return { + ok: false, + reason: `could not be read (${(error as NodeJS.ErrnoException).code ?? 'error'})`, + }; + /* v8 ignore stop */ + } finally { + await handle.close(); + } +} diff --git a/packages/bundler-plugin-core/src/sri.scan.test.ts b/packages/bundler-plugin-core/src/sri.scan.test.ts new file mode 100644 index 00000000..4d1ed3b1 --- /dev/null +++ b/packages/bundler-plugin-core/src/sri.scan.test.ts @@ -0,0 +1,214 @@ +// The HTML scan must be linear and bounded on hostile input, and must find exactly what the regexes it replaced +// found on ordinary input. +import { mkdir, mkdtemp, rm, symlink, truncate, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + findSriProtectedScripts, + findSriProtectedScriptsDetailed, + findTags, + MAX_HTML_BYTES, + stripComments, +} from './sri'; + +const made: string[] = []; +const fixture = async () => { + const dir = await mkdtemp(join(tmpdir(), 'bugsee-sri-scan-')); + made.push(dir); + return dir; +}; +afterEach(async () => { + await Promise.all(made.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +// The implementations this replaced, kept as the reference the new scanners must agree with. +const SCRIPT_TAG = /]*>/gi; +const PRELOAD_TAG = /]*>/gi; +const HTML_COMMENT = //g; + +it('the detailed scan keeps every distinct pin of a script; the stamp wrapper one per script', async () => { + const dir = await fixture(); + await writeFile(join(dir, 'a.html'), ''); + await writeFile(join(dir, 'b.html'), ''); + await writeFile(join(dir, 'c.html'), ''); + const detailed = await findSriProtectedScriptsDetailed(dir); + expect(detailed.scripts.map((s) => s.integrity)).toEqual(['sha384-AAA', 'sha384-BBB']); + expect(await findSriProtectedScripts(dir)).toHaveLength(1); +}); + +it('MAX_HTML_BYTES is 8 MiB', () => { + expect(MAX_HTML_BYTES).toBe(8 * 1024 * 1024); +}); + +/** + * The reference the linear scanner must agree with: every `` removed by the regex it replaced. Spliced from + * the match positions (not `String.replace`, which is also what a sanitiser would use: this is a test oracle). + */ +const referenceStrip = (text: string): string => { + let out = ''; + let at = 0; + for (const match of text.matchAll(HTML_COMMENT)) { + out += text.slice(at, match.index); + at = (match.index ?? 0) + match[0].length; + } + return out + text.slice(at); +}; + +describe('findTags / stripComments agree with the regexes they replaced', () => { + const pieces = [ + '', + '', + '', + '', + '', + '', + '', + ''.repeat(20_000); + const started = Date.now(); + expect(findTags(stripComments(text), 'script')).toHaveLength(20_000); + expect(Date.now() - started).toBeLessThan(FAST_MS); + }); + + it('end to end: a page of unterminated repeats is scanned fast and finds nothing', async () => { + const dir = await fixture(); + await writeFile(join(dir, 'index.html'), ''); + await writeFile(join(dir, 'sub', 'huge.html'), ''); + await truncate(join(dir, 'sub', 'huge.html'), MAX_HTML_BYTES + 1); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.scripts.map((s) => s.script)).toEqual([join(dir, 'a.js')]); + expect(scan.skippedPages).toEqual([ + { html: join(dir, 'sub', 'huge.html'), size: MAX_HTML_BYTES + 1 }, + ]); + }); + + it('the stamp guard (findSriProtectedScripts) still sees a pin in a page over the doctor cap', async () => { + const dir = await fixture(); + const tag = ''; + await writeFile(join(dir, 'big.html'), tag + ' '.repeat(MAX_HTML_BYTES + 10)); + expect((await findSriProtectedScripts(dir)).map((s) => s.script)).toEqual([join(dir, 'a.js')]); + }); + + it('a page of exactly MAX_HTML_BYTES is scanned', async () => { + const dir = await fixture(); + const tag = ''; + await writeFile(join(dir, 'p.html'), tag + ' '.repeat(MAX_HTML_BYTES - tag.length)); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.skippedPages).toEqual([]); + expect(scan.scripts).toHaveLength(1); + }); +}); + +describe('the page walk fence is optional', () => { + it('fenced (the default) skips test/ and dot-directories; unfenced scans them, still never node_modules', async () => { + const dir = await fixture(); + const page = ''; + for (const sub of ['tests', '.well', 'node_modules', 'ok']) { + await mkdir(join(dir, sub)); + await writeFile(join(dir, sub, 'p.html'), page.replace('/a.js', `../${sub}.js`)); + } + const fenced = await findSriProtectedScriptsDetailed(dir); + expect(fenced.scripts.map((s) => s.html)).toEqual([join(dir, 'ok', 'p.html')]); + const open = await findSriProtectedScriptsDetailed(dir, MAX_HTML_BYTES, false); + expect(open.scripts.map((s) => s.html).sort()).toEqual( + [ + join(dir, '.well', 'p.html'), + join(dir, 'ok', 'p.html'), + join(dir, 'tests', 'p.html'), + ].sort(), + ); + }); +}); + +describe('symlinked pages', () => { + it('a link inside the directory is scanned; one outside or dangling is listed as unreadable', async () => { + const dir = await fixture(); + const outside = await fixture(); + const page = ''; + await mkdir(join(dir, 'tests')); // a directory the (default) fence skips: only the link can reach this page + await writeFile(join(dir, 'tests', 'p.html'), page); + await symlink(join(dir, 'tests', 'p.html'), join(dir, 'in.html')); + await writeFile(join(outside, 'o.html'), page); + await symlink(join(outside, 'o.html'), join(dir, 'out.html')); + await symlink(join(outside, 'none.html'), join(dir, 'dangling.html')); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.scripts.map((s) => s.html)).toEqual([join(dir, 'in.html')]); + expect(scan.unreadablePages.sort()).toEqual( + [join(dir, 'dangling.html'), join(dir, 'out.html')].sort(), + ); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 3641731b..72636478 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -16,8 +16,12 @@ // every dynamic import. import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; -import { readdir, readFile } from 'node:fs/promises'; +import { readdir, readFile, realpath } from 'node:fs/promises'; import { isAbsolute, join, normalize, resolve, sep } from 'node:path'; +import { readRegularFile } from './safe-read'; + +/** A page larger than this is not scanned (a real page is a few KB): the scan must stay bounded on hostile input. */ +export const MAX_HTML_BYTES = 8 * 1024 * 1024; /** One `