diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 443e7af0..f8a632ff 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1310,6 +1310,17 @@ recorded" was false. Still open from #120: WebKit/Firefox projects, the 22-secret smoke, `document.open`. #119 (other masking-option gaps on re-observed observers) is untouched. +### 2026-11-11 — `node --enable-source-maps` vs debug-ID stamping (#185) + +Reproduced through the real crash builder (esbuild bundle + CLI-shaped stub, real node/bun processes, +`instrumentation-tests/test/sourcemaps-runtime.e2e.ts`): with the flag and a map on disk Node maps the registration +key's top frame to `src/main.js`, so a frame at `src/main.js:3:3` was stamped with the bundle's id (wrong line after the +backend remaps). A global skip on the flag was rejected (review): with the plugin-default deleted maps, or the flag +enabled after load, nothing is mapped and the join is correct. Fix: `applyDebugIds` validates each registration while +`process.sourceMapsEnabled` through an injected verifier (`setDebugIdRegistrationVerifier`; `@bugsee/node` installs +`createStampedBundleVerifier`, which requires the top-frame file's tail to carry `//# debugId=`). The verifier decodes the percent-encoded ESM frames core leaves (`./dist/my%20chunk.mjs`, `?v=1`), caches verdicts (4096), and old Node (no `process.sourceMapsEnabled`) falls back to `--enable-source-maps` in `execArgv`/`NODE_OPTIONS`. Bun does not map +`Error.stack` (measured), unaffected. Design: `docs/design/source-maps.md` §7.2. + ### 2026-11-09 — Replay moves onto upstream rrweb 2.2.1 → `krassx/rrweb-2.2.1-a625` Fork `bugsee-port-2.2.1` (merge of rrweb-io/rrweb tag `rrweb@2.2.1` into `bugsee-port-2.2.0-iframe-block`; one diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 96776315..3af7db68 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -191,6 +191,47 @@ is a change to the spawn model in §4 and is tracked as OPEN-FINDINGS D3. --- +## 7.2 Runtime-mapped stacks (`node --enable-source-maps`, #185) + +With `node --enable-source-maps` Node rewrites `Error.stack` to ORIGINAL positions before the SDK sees it, but only +when the bundle's `.map` is readable AND source maps were enabled before the bundle loaded +(`process.setSourceMapsEnabled(true)` affects only modules loaded afterwards). Then the stack the injected stub +registers is mapped too: its top frame becomes e.g. `src/main.js:4:1` (the appended stub has no mapping of its own), +so the `file -> debugId` join stamps the bundle's id onto already-mapped frames (measured: `src/main.js:3:3` got the +id; the backend remaps it again, a wrong line). + +Two cases look the same from `process.sourceMapsEnabled` but are different, so a global switch is wrong: +- the plugin DELETES `*.map` after upload by default; with the flag on and no map on disk nothing is mapped, the + registration key and the error frames both stay on `dist/app.js`, and the plain join is correct; +- the flag turned on after the bundle loaded: same, frames are unmapped and the join is correct. + +So the guard is PER REGISTRATION. While `process.sourceMapsEnabled === true` (`runtimeMapsStacks`, read through a +`globalThis` cast), `applyDebugIds` keeps a registration only if the injected verifier proves its top-frame file is the +stamped bundle. `@bugsee/node` installs that verifier at launch (`createStampedBundleVerifier`): the file's tail must +carry `//# debugId=` (the same marker `bundler-plugin-core` reads). A mapped registration points at +`src/main.js`, which has no stamp, so it is dropped and the frames stay unstamped (already original, no id needed). +Core stays runtime-portable: no `node:fs`, the verifier is injected (`setDebugIdRegistrationVerifier` / the +`verifyRegistration` option). With no verifier (browsers, Electron renderers: Chromium does not map `Error.stack` +even where `process.sourceMapsEnabled` reads true) every registration is kept, i.e. the previous behaviour. +The verifier reads the path the way core scrubs it, which is not always a plain path: ESM frames arrive +percent-encoded (core strips `file://` without URL-decoding): `/…/my%20app/dist/app.mjs` outside the app root, +`./dist/my%20chunk.mjs` UNDER it (the common case: `launch()` sets the app root to the cwd), possibly with an import +`?v=1`/`#hash`, and on Windows as `/C:/…`. It tries the literal path first, then the decoded form with the query +stripped, then the stripped literal. Answers are cached per (file, id), bounded to 4096 registrations (reports cost no +file I/O after the first for any realistic build; a build with more stamped chunks than that re-reads). Old Node +(18.0-18.18, 20.0-20.6) has no `process.sourceMapsEnabled`, so the probe falls back to `--enable-source-maps` in +`execArgv` / `NODE_OPTIONS` (tokenized on whitespace, double quotes stripped as Node does; `=true`/`=1` forms count, `=false`/`=0` do not); an explicit property always wins. A runtime +`process.setSourceMapsEnabled(true)` on those old versions cannot be observed. With no verifier installed the runtime is +not probed at all. Not handled: a FIFO-backed path (`/dev/fd/N`) would block the synchronous open; a bundle rewritten in +place during a deploy keeps its cached verdict until restart. Known limits: a path scrubbed to +`node_modules/...` has no `./` prefix and is resolved against `process.cwd()`, not the app root, so it verifies when +the first `node_modules` sits in the cwd and is not joined (flag on) in a hoisted monorepo or when `appRoot` differs +from the cwd. Separately (pre-existing): encoded ESM paths never match the app root, so they ship as absolute paths. +Windows hosts were not run. Bun does not map `Error.stack` and has no +`process.sourceMapsEnabled` (Bun 1.4.4, measured), so it keeps stamping, which is correct. + +--- + ## 8. Deferred - A real-`bugsee-cli` integration e2e (needs the built Rust binary in the harness) — follow-up once CI has it. - Turbopack loader for Next.js (`turbopack.rules`) — Next-adapter follow-up. diff --git a/packages/core/src/debug-id.test.ts b/packages/core/src/debug-id.test.ts index f0d943ad..6aaa4d15 100644 --- a/packages/core/src/debug-id.test.ts +++ b/packages/core/src/debug-id.test.ts @@ -1,5 +1,12 @@ import { describe, expect, it } from 'vitest'; -import { applyDebugIds, attachDebugIds, buildDebugIdMap, readDebugIds } from './debug-id'; +import { + applyDebugIds, + attachDebugIds, + buildDebugIdMap, + readDebugIds, + runtimeMapsStacks, + setDebugIdRegistrationVerifier, +} from './debug-id'; import { parseV8Stack, type StackFrame } from './stack'; // A V8 `Error().stack` whose TOP frame is the bundle's own file (what the injected stub captures). @@ -94,3 +101,232 @@ describe('applyDebugIds', () => { } }); }); + +describe('runtimeMapsStacks', () => { + it('is true only when the runtime reports `process.sourceMapsEnabled === true`', () => { + expect(runtimeMapsStacks({ sourceMapsEnabled: true })).toBe(true); + expect(runtimeMapsStacks({ sourceMapsEnabled: false })).toBe(false); + expect(runtimeMapsStacks({})).toBe(false); // Bun / browser polyfills: property absent + expect(runtimeMapsStacks({ sourceMapsEnabled: 'yes' })).toBe(false); + }); + + it('falls back to the launch flags where `sourceMapsEnabled` does not exist (Node < 18.19 / 20.7)', () => { + expect(runtimeMapsStacks({ execArgv: ['--no-warnings', '--enable-source-maps'] })).toBe(true); + expect( + runtimeMapsStacks({ env: { NODE_OPTIONS: '--max-old-space-size=4 --enable-source-maps' } }), + ).toBe(true); + expect(runtimeMapsStacks({ execArgv: ['--no-warnings'], env: { NODE_OPTIONS: '--x' } })).toBe( + false, + ); + expect( + runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps-extra --enable' } }), + ).toBe(false); + expect(runtimeMapsStacks({ execArgv: 'nope', env: null })).toBe(false); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: 7 } })).toBe(false); + // an explicit answer always wins over the launch flags (setSourceMapsEnabled(false) after start) + expect( + runtimeMapsStacks({ sourceMapsEnabled: false, execArgv: ['--enable-source-maps'] }), + ).toBe(false); + }); + + it('reads NODE_OPTIONS like Node: whitespace-separated tokens, DOUBLE quotes only (single quotes are not stripped)', () => { + const opts = (NODE_OPTIONS: string) => runtimeMapsStacks({ env: { NODE_OPTIONS } }); + expect(opts('--x\t--enable-source-maps')).toBe(true); + expect(opts('--x --enable-source-maps')).toBe(true); + expect(opts('"--enable-source-maps"')).toBe(true); + expect(opts("--x '--enable-source-maps'")).toBe(false); + expect(opts('"--enable-source-maps-extra"')).toBe(false); + }); + + it('recognizes the `=true` form of the flag, and not `=false`/`=0`, in execArgv and NODE_OPTIONS', () => { + expect(runtimeMapsStacks({ execArgv: ['--enable-source-maps=true'] })).toBe(true); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=true' } })).toBe(true); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '"--enable-source-maps=1"' } })).toBe(true); + expect(runtimeMapsStacks({ execArgv: ['--enable-source-maps=false'] })).toBe(false); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=0' } })).toBe(false); + expect(runtimeMapsStacks({ env: { NODE_OPTIONS: '--enable-source-maps=maybe' } })).toBe(false); + }); + + it('never throws: a hostile process object answers false', () => { + const hostile = { + get sourceMapsEnabled(): never { + throw new Error('getter'); + }, + }; + expect(runtimeMapsStacks(hostile)).toBe(false); + const envThrows = { + get env(): never { + throw new Error('env getter'); + }, + }; + expect(runtimeMapsStacks(envThrows)).toBe(false); + }); + + it('is false without a process object (browsers, workers, edge)', () => { + expect(runtimeMapsStacks(undefined)).toBe(false); + expect(runtimeMapsStacks(null)).toBe(false); + expect(runtimeMapsStacks(1)).toBe(false); + }); + + it('defaults to the live `globalThis.process`', () => { + const g = globalThis as unknown as { process?: { sourceMapsEnabled?: boolean } }; + const real = g.process; + try { + g.process = { sourceMapsEnabled: true }; + expect(runtimeMapsStacks()).toBe(true); + g.process = {}; + expect(runtimeMapsStacks()).toBe(false); + g.process = undefined; + expect(runtimeMapsStacks()).toBe(false); + } finally { + g.process = real; + } + }); +}); + +describe('buildDebugIdMap with an accept predicate', () => { + it('keeps only registrations the predicate accepts, passing (top-frame file, debugId)', () => { + const seen: [string, string][] = []; + const map = buildDebugIdMap( + { + [bundleStack('/app/src/main.js')]: 'mapped-id', + [bundleStack('/app/dist/app.js')]: 'real-id', + }, + parseV8Stack, + (file, id) => { + seen.push([file, id]); + return file.includes('dist'); + }, + ); + expect([...map]).toEqual([['/app/dist/app.js', 'real-id']]); + expect(seen).toEqual([ + ['/app/src/main.js', 'mapped-id'], + ['/app/dist/app.js', 'real-id'], + ]); + }); +}); + +describe('buildDebugIdMap with a throwing predicate', () => { + it('treats a throw as a rejection of that registration only', () => { + const map = buildDebugIdMap( + { + [bundleStack('/app/dist/bad.js')]: 'bad-id', + [bundleStack('/app/dist/good.js')]: 'good-id', + }, + parseV8Stack, + (file) => { + if (file.includes('bad')) throw new Error('verifier blew up'); + return true; + }, + ); + expect([...map]).toEqual([['/app/dist/good.js', 'good-id']]); + }); +}); + +describe('applyDebugIds under runtime source-map support (#185)', () => { + // With `node --enable-source-maps` AND a map on disk, the registration key's top frame is mapped to an + // ORIGINAL file (`src/main.js`). Joining on it stamps the bundle's id onto already-mapped frames -> the + // backend remaps them again -> a wrong line. Without the map on disk (the plugin default: maps are deleted + // after upload) nothing is mapped and the plain join is correct. So the guard is PER REGISTRATION. + const registry = { + [bundleStack('/app/src/main.js')]: 'mapped-id', // registered under a mapping runtime + [bundleStack('/app/dist/other.js')]: 'other-id', // a bundle whose map is absent + }; + const verify = (file: string, id: string): boolean => + file === '/app/dist/other.js' && id === 'other-id'; + const frames = (): StackFrame[] => [ + { file: '/app/src/main.js', line: 3, column: 3 }, + { file: '/app/dist/other.js', line: 1, column: 9 }, + ]; + + it('while the runtime maps stacks, drops registrations the verifier rejects and keeps verified ones', () => { + const f = frames(); + applyDebugIds(f, { + globalObject: { _bugseeDebugIds: registry }, + parseStack: parseV8Stack, + runtimeMapsStacks: true, + verifyRegistration: verify, + }); + expect(f[0]?.debugId).toBeUndefined(); + expect(f[1]?.debugId).toBe('other-id'); + }); + + it('does not consult the verifier when the runtime does not map stacks', () => { + const f = frames(); + applyDebugIds(f, { + globalObject: { _bugseeDebugIds: registry }, + parseStack: parseV8Stack, + runtimeMapsStacks: false, + verifyRegistration: () => false, + }); + expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + }); + + it('keeps every registration when mapping is on but no verifier exists (browser / Electron renderer)', () => { + const f = frames(); + applyDebugIds(f, { + globalObject: { _bugseeDebugIds: registry }, + parseStack: parseV8Stack, + runtimeMapsStacks: true, + }); + expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + }); + + it('with no verifier at all, never even probes the runtime (identical to the pre-#185 path)', () => { + const g = globalThis as unknown as { + process?: unknown; + _bugseeDebugIds?: Record; + }; + const real = g.process; + const prev = g._bugseeDebugIds; + let probed = 0; + g._bugseeDebugIds = registry; + g.process = { + get sourceMapsEnabled(): boolean { + probed++; + return true; + }, + }; + try { + const f = frames(); + applyDebugIds(f); + expect(f.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + expect(probed).toBe(0); + } finally { + g.process = real; + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); + + it('uses the installed process-wide verifier by default, and the live process probe', () => { + const g = globalThis as unknown as { + process?: { sourceMapsEnabled?: boolean }; + _bugseeDebugIds?: Record; + }; + const real = g.process; + const prev = g._bugseeDebugIds; + g._bugseeDebugIds = registry; + setDebugIdRegistrationVerifier(verify); + try { + g.process = { sourceMapsEnabled: true }; + const mapped = frames(); + applyDebugIds(mapped); + expect(mapped.map((x) => x.debugId)).toEqual([undefined, 'other-id']); + g.process = { sourceMapsEnabled: false }; + const plain = frames(); + applyDebugIds(plain); + expect(plain.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + setDebugIdRegistrationVerifier(undefined); + g.process = { sourceMapsEnabled: true }; + const none = frames(); + applyDebugIds(none); + expect(none.map((x) => x.debugId)).toEqual(['mapped-id', 'other-id']); + } finally { + setDebugIdRegistrationVerifier(undefined); + g.process = real; + if (prev === undefined) delete g._bugseeDebugIds; + else g._bugseeDebugIds = prev; + } + }); +}); diff --git a/packages/core/src/debug-id.ts b/packages/core/src/debug-id.ts index b51c2687..ebd096b0 100644 --- a/packages/core/src/debug-id.ts +++ b/packages/core/src/debug-id.ts @@ -19,6 +19,19 @@ export function readDebugIds(globalObject: unknown): Record { return typeof ids === 'object' && ids !== null ? (ids as Record) : {}; } +/** An injected predicate must never take a report down: a throw is a rejection. */ +function accepts( + accept: (file: string, debugId: string) => boolean, + file: string, + debugId: string, +): boolean { + try { + return accept(file, debugId); + } catch { + return false; + } +} + /** * Build a `file → debugId` map from the registration map: parse each registered stack and key the debug-ID * by its TOP frame's file (the bundle that registered it). @@ -26,11 +39,12 @@ export function readDebugIds(globalObject: unknown): Record { export function buildDebugIdMap( debugIds: Record, parseStack: (stack: string) => StackFrame[], + accept?: (file: string, debugId: string) => boolean, ): Map { const map = new Map(); for (const [stack, debugId] of Object.entries(debugIds)) { const file = parseStack(stack)[0]?.file; - if (file !== undefined) { + if (file !== undefined && (accept === undefined || accepts(accept, file, debugId))) { map.set(file, debugId); } } @@ -49,14 +63,90 @@ export function attachDebugIds(frames: StackFrame[], debugIdMap: Map token.replace(/^"|"$/g, '')) // Node strips double quotes only + .some(isFlagOn) + ); +} + +/** Does this registration (its top-frame file + debug-id) really belong to the stamped bundle? */ +export type RegistrationVerifier = (file: string, debugId: string) => boolean; + +let installedVerifier: RegistrationVerifier | undefined; + +/** + * Install the process-wide registration verifier (a platform with a filesystem: `@bugsee/node`). Module state, + * like `setStackAppRoot`: core is runtime-portable and cannot read files itself. `undefined` removes it. + */ +export function setDebugIdRegistrationVerifier(verifier: RegistrationVerifier | undefined): void { + installedVerifier = verifier; +} + /** * Resolve + stamp debug-IDs onto `frames` in place, reading the registration global (default `globalThis`) * and parsing registered stacks with `parseStack` (default {@link parseV8Stack}). A no-op when no build * injected debug-IDs. + * + * When the runtime maps stacks itself ({@link runtimeMapsStacks}; override via `options.runtimeMapsStacks`) AND a + * verifier is available (`options.verifyRegistration`, else the installed one), each registration is checked: one + * whose top-frame file is NOT the stamped bundle was source-mapped to an ORIGINAL file, and joining on it would + * stamp the bundle's id onto already-mapped frames (the backend remaps them again: a wrong line, #185). The check is + * per registration, never a global switch: the flag only says the process CAN map, not that this bundle's map is on + * disk (the plugin deletes maps after upload by default) or was enabled before the bundle loaded; in those cases + * the registration is intact and the plain join is correct. Without a verifier every registration is kept. */ export function applyDebugIds( frames: StackFrame[], - options: { globalObject?: unknown; parseStack?: (stack: string) => StackFrame[] } = {}, + options: { + globalObject?: unknown; + parseStack?: (stack: string) => StackFrame[]; + runtimeMapsStacks?: boolean; + verifyRegistration?: RegistrationVerifier; + } = {}, ): void { const globalObject = options.globalObject ?? (globalThis as unknown); const debugIds = readDebugIds(globalObject); @@ -64,5 +154,12 @@ export function applyDebugIds( return; } const parseStack = options.parseStack ?? parseV8Stack; - attachDebugIds(frames, buildDebugIdMap(debugIds, parseStack)); + const verifier = options.verifyRegistration ?? installedVerifier; + // No verifier (browsers, Electron renderers, a node process that never launched): exactly the pre-#185 join, and the + // runtime is not even probed. + const verify = + verifier !== undefined && (options.runtimeMapsStacks ?? runtimeMapsStacks()) + ? verifier + : undefined; + attachDebugIds(frames, buildDebugIdMap(debugIds, parseStack, verify)); } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4c3735b5..1d1b1bc6 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -178,7 +178,10 @@ export { applyDebugIds, attachDebugIds, buildDebugIdMap, + type RegistrationVerifier, readDebugIds, + runtimeMapsStacks, + setDebugIdRegistrationVerifier, } from './debug-id'; export { checkOrSetAlreadyCaught } from './dedup'; export { diff --git a/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts new file mode 100644 index 00000000..4a42ce2f --- /dev/null +++ b/packages/instrumentation-tests/app/sourcemaps-runtime-scenario.ts @@ -0,0 +1,51 @@ +// Child process for sourcemaps-runtime.e2e.ts: loads a bundle stamped like `bugsee-cli sourcemaps inject`, +// throws from it, and prints what the SDK's crash builder produces (frames + debug-ids) plus the registration keys. +// SOURCE_MAPS: `on` / `off` pin runtime source-map support BEFORE the bundle loads; `late` enables it AFTER the +// bundle loaded (Node only maps modules loaded afterwards); unset leaves the process flags alone. +import { createRequire } from 'node:module'; +import process from 'node:process'; +import { pathToFileURL } from 'node:url'; +import { buildCrashJson, setDebugIdRegistrationVerifier, setStackAppRoot } from '@bugsee/core'; +// Internal to @bugsee/node (installed by its launch); imported by path so the public export surface stays unchanged. +import { createStampedBundleVerifier } from '../../node/src/debug-id-verifier'; + +const proc = process as unknown as { + setSourceMapsEnabled?: (on: boolean) => void; + sourceMapsEnabled?: boolean; +}; +const mode = process.env.SOURCE_MAPS; +const setMaps = (on: boolean): void => proc.setSourceMapsEnabled?.call(process, on); +// tsx turns source maps on for its own TS transform, so the harness pins the mode explicitly. +if (mode === 'on') setMaps(true); +if (mode === 'off' || mode === 'late') setMaps(false); + +// What `launch()` does for the app: scrub frame paths to the app root + install the stamp verifier. +const appRoot = process.env.APP_ROOT as string; +setStackAppRoot(appRoot); +setDebugIdRegistrationVerifier(createStampedBundleVerifier({ appRoot })); + +const require = createRequire(import.meta.url); +const bundlePath = process.env.BUNDLE_PATH as string; +const app = ( + bundlePath.endsWith('.mjs') + ? await import(pathToFileURL(bundlePath).href + (process.env.IMPORT_QUERY ?? '')) + : require(bundlePath) +) as { fail: () => never }; +if (mode === 'late') setMaps(true); +let thrown: unknown; +try { + app.fail(); +} catch (error) { + thrown = error; +} +const registry = (globalThis as { _bugseeDebugIds?: Record })._bugseeDebugIds ?? {}; +const crash = buildCrashJson(thrown); +process.stdout.write( + `${JSON.stringify({ + sourceMapsEnabled: proc.sourceMapsEnabled, + registrationTopFrames: Object.keys(registry).map((k) => (k.split('\n')[1] ?? '').trim()), + frames: crash.exception.frames + .filter((f) => f.user && !f.trace.includes('sourcemaps-runtime-scenario')) + .map((f) => ({ at: f.trace, debug_id: f.debug_id })), + })}\n`, +); diff --git a/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts new file mode 100644 index 00000000..d31ea37a --- /dev/null +++ b/packages/instrumentation-tests/test/sourcemaps-runtime.e2e.ts @@ -0,0 +1,235 @@ +// Issue #185 — `node --enable-source-maps` vs the debug-ID -> file lookup. +// +// Builds a REAL minified-position bundle with esbuild (+ external map), stamps it the way +// `bugsee-cli sourcemaps inject` does (the runtime stub and the `//# debugId=` comment APPENDED after the whole bundle, +// so the stub has no source-map mapping of its own), then runs it in a real node/bun process through the REAL crash +// builder (`buildCrashJson`) and reads back which frames got a debug-ID. +// +// A debug-ID tells the backend "this position is in the stamped bundle, remap it". Stamping a frame the runtime already +// mapped to an original `src/*.js` position makes the backend remap it AGAIN -> a wrong line. But the flag alone does +// not mean frames are mapped: the plugin deletes `*.map` after upload by default (then Node cannot map anything), and +// `process.setSourceMapsEnabled(true)` only affects modules loaded afterwards. Those cases must stay stamped. +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { runtimeTargets } from './runtimes'; + +const DEBUG_ID = '11111111-2222-5333-8444-555555555555'; +const pkgRoot = fileURLToPath(new URL('..', import.meta.url)); +const SCENARIO = join(pkgRoot, 'app', 'sourcemaps-runtime-scenario.ts'); + +/** The stub `bugsee-cli sourcemaps inject` appends (same shape: registers `Error().stack` -> debug-id). */ +const STUB = `;!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._bugseeDebugIds=e._bugseeDebugIds||{},e._bugseeDebugIds[n]="${DEBUG_ID}")}catch(e){}}();`; + +interface Result { + sourceMapsEnabled: boolean | undefined; + registrationTopFrames: string[]; + frames: { at: string; debug_id?: string }[]; +} + +describe('debug-ID stamping under runtime source-map support (#185)', () => { + let dir: string; + /** Build roots: one keeps `app.js.map` on disk, one has it deleted (the plugin's default after upload). */ + let withMap: string; + let noMap: string; + let esmMap: string; + let esmNoMap: string; + let underSpace: string; + let underQuery: string; + + function build(root: string, keepMap: boolean, esm = false, name?: string): void { + mkdirSync(join(root, 'src'), { recursive: true }); + mkdirSync(join(root, 'dist')); + writeFileSync( + join(root, 'src', 'a.js'), + "export function boom() {\n throw new Error('boom from a');\n}\n", + ); + writeFileSync( + join(root, 'src', 'main.js'), + "import { boom } from './a.js';\nexport function fail() {\n boom();\n}\n", + ); + const bundle = join(root, 'dist', name ?? (esm ? 'app.mjs' : 'app.js')); + execFileSync( + join(pkgRoot, 'node_modules', '.bin', 'esbuild'), + [ + join(root, 'src', 'main.js'), + '--bundle', + '--platform=node', + `--format=${esm ? 'esm' : 'cjs'}`, + '--sourcemap', + `--outfile=${bundle}`, + '--log-level=warning', + ], + { stdio: 'inherit' }, + ); + // inject: stub, then the id comment LAST, appended after the whole bundle (bugsee-cli inject/mod.rs). + const source = readFileSync(bundle, 'utf8'); + writeFileSync(bundle, `${source.replace(/\n$/, '')}\n${STUB}\n//# debugId=${DEBUG_ID}\n`); + if (!keepMap) rmSync(`${bundle}.map`); + } + + beforeAll(() => { + // realpath: macOS tmpdir is a symlink; Node would map frames to a nonexistent `/private/private/...` path and the + // verifier would reject for 'file missing' rather than 'no stamp', which makes the map-present cases tautological. + dir = realpathSync(mkdtempSync(join(tmpdir(), 'bugsee-sm-rt-'))); + withMap = join(dir, 'with-map'); + noMap = join(dir, 'no-map'); + mkdirSync(withMap); + mkdirSync(noMap); + build(withMap, true); + build(noMap, false); + // ESM bundles under a directory with a SPACE: Node prints the frame as `file:///…/my%20app/dist/app.mjs`. + esmMap = join(dir, 'my app', 'esm-map'); + esmNoMap = join(dir, 'my app', 'esm-no-map'); + mkdirSync(esmMap, { recursive: true }); + mkdirSync(esmNoMap, { recursive: true }); + build(esmMap, true, true); + build(esmNoMap, false, true); + // ESM bundles UNDER the app root (the common case: appRoot = cwd). Core scrubs the frame to `./dist/...` WITHOUT + // decoding it, so a space in the file name stays `%20`, and an import query stays in the path. + underSpace = join(dir, 'under-space'); + underQuery = join(dir, 'under-query'); + mkdirSync(underSpace); + mkdirSync(underQuery); + build(underSpace, false, true, 'my chunk.mjs'); + build(underQuery, false, true); + }); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + function run( + bin: string, + root: string, + args: string[], + sourceMaps: 'on' | 'off' | 'late', + bundleName?: string, + importQuery = '', + ): Result { + const out = execFileSync(bin, [...args, SCENARIO], { + encoding: 'utf8', + env: { + ...process.env, + BUNDLE_PATH: join( + root, + 'dist', + bundleName ?? (root.includes('esm') ? 'app.mjs' : 'app.js'), + ), + IMPORT_QUERY: importQuery, + APP_ROOT: root, + SOURCE_MAPS: sourceMaps, + }, + }); + return JSON.parse(out.trim().split('\n').at(-1) as string) as Result; + } + + const bundleFrames = (r: Result) => r.frames.filter((f) => f.at.includes('dist/')); + const originalFrames = (r: Result) => r.frames.filter((f) => f.at.includes('src/')); + + for (const target of runtimeTargets()) { + const { bin, name } = target; + it.skipIf(bin === undefined)( + `${name}: ESM bundle under a path with a space, flag on, map deleted -> stays stamped`, + () => { + const r = run(bin as string, esmNoMap, ['--enable-source-maps'], 'on'); + // Node prints the ESM frame as a percent-encoded file URL; Bun prints the plain path. + expect(r.registrationTopFrames[0]).toContain(name === 'node' ? 'my%20app' : 'my app'); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + + it.skipIf(bin === undefined)( + `${name}: ESM bundle UNDER the app root with a space in its NAME, flag on, map deleted -> stays stamped`, + () => { + const r = run(bin as string, underSpace, ['--enable-source-maps'], 'on', 'my chunk.mjs'); + // Node: the frame is scrubbed to `./dist/my%20chunk.mjs` (relative, still encoded); Bun: the plain relative path. + expect(bundleFrames(r)[0]?.at).toContain( + name === 'node' ? './dist/my%20chunk.mjs' : './dist/my chunk.mjs', + ); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + + it.skipIf(bin === undefined)( + `${name}: ESM bundle UNDER the app root imported with a ?v=1 query, flag on, map deleted -> stays stamped`, + () => { + const r = run(bin as string, underQuery, ['--enable-source-maps'], 'on', 'app.mjs', '?v=1'); + expect(bundleFrames(r)[0]?.at).toContain('./dist/app.mjs'); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + + it.skipIf(bin === undefined)( + `${name}: ESM bundle under a path with a space, flag on, map present -> mapped frames are not stamped`, + () => { + const r = run(bin as string, esmMap, ['--enable-source-maps'], 'on'); + if (name === 'node') { + expect(originalFrames(r).length).toBeGreaterThanOrEqual(2); + expect(r.frames.map((f) => f.debug_id)).not.toContain(DEBUG_ID); + } else { + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); // Bun does not map + } + }, + ); + + const flag = ['--enable-source-maps']; + + it.skipIf(bin === undefined)(`${name}: source maps off -> bundle frames are stamped`, () => { + const r = run(bin as string, withMap, [], 'off'); + expect(r.sourceMapsEnabled).not.toBe(true); + expect(r.registrationTopFrames[0]).toContain('dist/app.js'); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }); + + it.skipIf(bin === undefined)( + `${name}: --enable-source-maps never stamps an already-mapped frame`, + () => { + const r = run(bin as string, withMap, flag, 'on'); + if (name === 'node') { + // Node maps the stacks BEFORE the SDK sees them: error frames AND the registration key's top frame are + // original `src/*.js` positions, so the bundle's id would be wrong for every one of them. + expect(r.sourceMapsEnabled).toBe(true); + expect(r.registrationTopFrames[0]).toContain('/src/'); + expect(originalFrames(r).length).toBeGreaterThanOrEqual(2); + expect(r.frames.map((f) => f.debug_id)).not.toContain(DEBUG_ID); + } else { + // Measured (Bun 1.4.4): Bun does NOT apply source maps to Error.stack and has no + // `process.sourceMapsEnabled`, so frames stay on the bundle and stamping them is correct. + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + } + }, + ); + + it.skipIf(bin === undefined)( + `${name}: flag on but the map was deleted (plugin default) -> nothing is mapped, frames stay stamped`, + () => { + const r = run(bin as string, noMap, flag, 'on'); + expect(r.registrationTopFrames[0]).toContain('dist/app.js'); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + + it.skipIf(bin === undefined)( + `${name}: source maps enabled AFTER the bundle loaded -> frames are unmapped and stay stamped`, + () => { + const r = run(bin as string, withMap, [], 'late'); + if (name === 'node') expect(r.sourceMapsEnabled).toBe(true); + expect(r.registrationTopFrames[0]).toContain('dist/app.js'); + expect(originalFrames(r)).toHaveLength(0); + expect(bundleFrames(r).length).toBeGreaterThan(0); + for (const f of bundleFrames(r)) expect(f.debug_id).toBe(DEBUG_ID); + }, + ); + } +}); diff --git a/packages/node/src/debug-id-verifier.test.ts b/packages/node/src/debug-id-verifier.test.ts new file mode 100644 index 00000000..f182dde9 --- /dev/null +++ b/packages/node/src/debug-id-verifier.test.ts @@ -0,0 +1,365 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { parseV8Stack, setStackAppRoot } from '@bugsee/core'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createStampedBundleVerifier, readStampedDebugId } from './debug-id-verifier'; + +// Hex LETTERS on purpose: an all-digit id cannot tell a case-folding mutation from the original. +const ID = 'abcdef12-2222-5ABC-8444-55555555dEaD'; +const LOWER = ID.toLowerCase(); +const enoent = (): Error => Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); + +describe('readStampedDebugId', () => { + it('returns the LAST stamp, lower-cased, only when it is a UUID', () => { + expect(readStampedDebugId(`x\n//# debugId=${ID}\n//# sourceMappingURL=a.map`)).toBe(LOWER); + expect(readStampedDebugId(`//# debugId=${ID}\n//# debugId=${LOWER.replace('a', 'b')}`)).toBe( + LOWER.replace('a', 'b'), + ); + expect(readStampedDebugId('//# debugId=not-a-uuid')).toBeUndefined(); + expect(readStampedDebugId('no stamp')).toBeUndefined(); + }); +}); + +describe('createStampedBundleVerifier', () => { + let dir: string | undefined; + afterEach(() => { + if (dir) rmSync(dir, { recursive: true, force: true }); + dir = undefined; + }); + const fixture = (): string => { + dir = realpathSync(mkdtempSync(join(tmpdir(), 'bugsee-verify-'))); + mkdirSync(join(dir, 'dist')); + mkdirSync(join(dir, 'src')); + writeFileSync(join(dir, 'dist', 'app.js'), `console.log(1);\n//# debugId=${ID}\n`); + writeFileSync(join(dir, 'src', 'main.js'), 'export const a = 1;\n'); + return dir; + }; + + it('accepts a file whose tail carries the registered id, rejects an unstamped or differently stamped one', () => { + const root = fixture(); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify(join(root, 'dist', 'app.js'), ID)).toBe(true); + expect(verify(join(root, 'dist', 'app.js'), LOWER)).toBe(true); + expect(verify(join(root, 'dist', 'app.js'), ID.toUpperCase())).toBe(true); + expect(verify(join(root, 'dist', 'app.js'), 'other')).toBe(false); + expect(verify(join(root, 'src', 'main.js'), ID)).toBe(false); + }); + + it('resolves app-relative (scrubbed) paths and file:// URLs', () => { + const root = fixture(); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify('./dist/app.js', ID)).toBe(true); + expect(verify('./src/main.js', ID)).toBe(false); + expect(verify(pathToFileURL(join(root, 'dist', 'app.js')).href, ID)).toBe(true); + }); + + it('rejects (never throws) for an unreadable file or a malformed URL', () => { + const root = fixture(); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify(join(root, 'missing.js'), ID)).toBe(false); + expect(verify('file://bad host/x', ID)).toBe(false); + expect(verify('/%zz/not-decodable.mjs', ID)).toBe(false); + }); + + it('reads only the tail of a large file', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'big.js'), `${'a'.repeat(100_000)}\n//# debugId=${ID}\n`); + writeFileSync(join(root, 'dist', 'head.js'), `//# debugId=${ID}\n${'a'.repeat(100_000)}`); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify('./dist/big.js', ID)).toBe(true); + expect(verify('./dist/head.js', ID)).toBe(false); + }); + + it('defaults the app root to the working directory', () => { + const verify = createStampedBundleVerifier(); + expect(verify('./definitely/not/here.js', ID)).toBe(false); + }); + + describe('ESM frames as the REAL parse pipeline delivers them (parseV8Stack output)', () => { + // Node prints ESM frames as `file:///…` URLs; core's scrubber strips the scheme WITHOUT decoding, so the + // verifier sees `/…/my%20app/dist/app.mjs`, not a file:// URL. + const topFile = (url: string): string => { + const frame = parseV8Stack(`Error\n at (${url}:1:479)`)[0]; + return frame?.file as string; + }; + + it('opens a path with a space (percent-encoded in the stack)', () => { + const root = fixture(); + const spaced = join(root, 'my app', 'dist'); + mkdirSync(spaced, { recursive: true }); + writeFileSync(join(spaced, 'app.mjs'), `export {};\n//# debugId=${ID}\n`); + const url = pathToFileURL(join(spaced, 'app.mjs')).href; + expect(url).toContain('my%20app'); + const file = topFile(url); + expect(file).toContain('my%20app'); // the scrubber really leaves it encoded + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('strips an import query / hash', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'app.mjs'), `export {};\n//# debugId=${ID}\n`); + const url = `${pathToFileURL(join(root, 'dist', 'app.mjs')).href}?v=1#x`; + const file = topFile(url); + expect(file.endsWith('app.mjs?v=1#x')).toBe(true); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('prefers a file literally named with a query/percent over the decoded reading', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'a%20b.js'), `//# debugId=${ID}\n`); + expect( + createStampedBundleVerifier({ appRoot: root })(join(root, 'dist', 'a%20b.js'), ID), + ).toBe(true); + }); + + it('Windows drive form: tries the decoded URL reading of `/C:/…` (verified through the read seam)', () => { + const file = topFile('file:///C:/my%20app/dist/app.mjs'); + expect(file).toBe('/C:/my%20app/dist/app.mjs'); + const opened: string[] = []; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: (path) => { + opened.push(path); + if (path.includes('my app')) return `//# debugId=${ID}`; + throw enoent(); + }, + }); + expect(verify(file, ID)).toBe(true); + // literal first (fails), then the decoded form (what a win32 host turns into `C:\my app\dist\app.mjs`) + expect(opened[0]).toBe('/C:/my%20app/dist/app.mjs'); + expect(opened[1]).toContain('C:'); + expect(opened[1]).toContain('my app'); + }); + }); + + it('falls back to the literal path when a real directory name is not a valid file-URL reading', () => { + const root = fixture(); + for (const name of ['100%', 'a%2Fb']) { + mkdirSync(join(root, name, 'dist'), { recursive: true }); + writeFileSync(join(root, name, 'dist', 'app.js'), `//# debugId=${ID}\n`); + expect( + createStampedBundleVerifier({ appRoot: root })(join(root, name, 'dist', 'app.js'), ID), + ).toBe(true); + } + }); + + describe('transient read errors', () => { + it('are rejected but NOT cached: the next call asks again', () => { + let reads = 0; + let failing = true; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + if (failing) throw Object.assign(new Error('too many open files'), { code: 'EMFILE' }); + return `//# debugId=${ID}`; + }, + }); + expect(verify('/x/a.js', ID)).toBe(false); + expect(verify('/x/a.js', ID)).toBe(false); + expect(reads).toBe(2); // one distinct reading per ask, asked twice + failing = false; + expect(verify('/x/a.js', ID)).toBe(true); + expect(verify('/x/a.js', ID)).toBe(true); + expect(reads).toBe(3); // the success is cached + }); + + it('an error without a code is transient too; a malformed URL is rejected uncached', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + throw new Error('mystery'); + }, + }); + expect(verify('/x/a.js', ID)).toBe(false); + expect(verify('/x/a.js', ID)).toBe(false); + expect(reads).toBe(2); + expect(verify('file://bad host/x', ID)).toBe(false); + }); + }); + + describe('ESM frames UNDER the app root (scrubbed to `./…`, still percent-encoded)', () => { + afterEach(() => setStackAppRoot(undefined)); + // The common case: launch() sets appRoot = cwd, so core rewrites `file:////dist/x.mjs` to `./dist/x.mjs` + // WITHOUT decoding. Every test here feeds the verifier the real output of parseV8Stack with that root set. + const frameFile = (root: string, rel: string, suffix = ''): string => { + setStackAppRoot(root); + const url = `${pathToFileURL(join(root, rel)).href}${suffix}`; + return parseV8Stack(`Error\n at (${url}:1:479)`)[0]?.file as string; + }; + const stamped = (root: string, rel: string): void => { + mkdirSync(join(root, rel, '..'), { recursive: true }); + writeFileSync(join(root, rel), `export {};\n//# debugId=${ID}\n`); + }; + + it('decodes a space in the file name', () => { + const root = fixture(); + stamped(root, 'dist/my chunk.mjs'); + const file = frameFile(root, 'dist/my chunk.mjs'); + expect(file).toBe('./dist/my%20chunk.mjs'); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('decodes braces / brackets / percent-encoded characters', () => { + const root = fixture(); + stamped(root, 'dist/[id]-{x}.mjs'); + const file = frameFile(root, 'dist/[id]-{x}.mjs'); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + }); + + it('strips an import query and a hash', () => { + const root = fixture(); + stamped(root, 'dist/a.mjs'); + for (const suffix of ['?v=1', '#h', '?v=1#h']) { + const file = frameFile(root, 'dist/a.mjs', suffix); + expect(file).toBe(`./dist/a.mjs${suffix}`); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + } + }); + + it('decodes AND strips together; rejects an unstamped file', () => { + const root = fixture(); + stamped(root, 'dist/my chunk.mjs'); + const file = frameFile(root, 'dist/my chunk.mjs', '?v=2'); + expect(createStampedBundleVerifier({ appRoot: root })(file, ID)).toBe(true); + writeFileSync(join(root, 'dist', 'plain.mjs'), 'export {};\n'); + expect( + createStampedBundleVerifier({ appRoot: root })( + frameFile(root, 'dist/plain.mjs', '?v=1'), + ID, + ), + ).toBe(false); + }); + + it('a relative path that is not a valid percent-encoding stays literal', () => { + const root = fixture(); + stamped(root, 'dist/100%.mjs'); + expect(createStampedBundleVerifier({ appRoot: root })('./dist/100%.mjs', ID)).toBe(true); + }); + }); + + it('after stripping a query, tries the literal stripped path (a file really named with a percent)', () => { + const root = fixture(); + writeFileSync(join(root, 'dist', 'a%20b.mjs'), `//# debugId=${ID}\n`); + const verify = createStampedBundleVerifier({ appRoot: root }); + // literal `…/a%20b.mjs?v=1` and decoded `…/a b.mjs` do not exist; only the stripped literal does + expect(verify(`${join(root, 'dist', 'a%20b.mjs')}?v=1`, ID)).toBe(true); + expect(verify('./dist/a%20b.mjs?v=1', ID)).toBe(true); + }); + + it('keeps trying later candidates when an UNRELATED file sits at the literal reading', () => { + const root = fixture(); + // the stamped bundle is `a b.mjs`; an unrelated, unstamped file is literally named `a%20b.mjs` + writeFileSync(join(root, 'dist', 'a b.mjs'), `export {};\n//# debugId=${ID}\n`); + writeFileSync(join(root, 'dist', 'a%20b.mjs'), 'export {};\n'); + // likewise an unrelated file literally named `q.mjs?v=1` next to the stamped `q.mjs` + writeFileSync(join(root, 'dist', 'q.mjs'), `export {};\n//# debugId=${ID}\n`); + writeFileSync(join(root, 'dist', 'q.mjs?v=1'), 'export {};\n'); + const verify = createStampedBundleVerifier({ appRoot: root }); + expect(verify('./dist/a%20b.mjs', ID)).toBe(true); + expect(verify('./dist/q.mjs?v=1', ID)).toBe(true); + // ...and a file that is genuinely not stamped under any reading is still rejected + expect(verify('./dist/plain-missing%20x.mjs', ID)).toBe(false); + }); + + it('opens each distinct reading once (deduped), and treats NUL / invalid-arg paths as a definitive miss', () => { + const opened: string[] = []; + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: (path) => { + reads++; + opened.push(path); + throw Object.assign(new Error('bad path'), { code: 'ERR_INVALID_ARG_VALUE' }); + }, + }); + expect(verify('/x/plain.js', ID)).toBe(false); + expect(opened).toEqual(['/x/plain.js']); // literal === decoded: opened once + const after = reads; + expect(verify('/x/plain.js', ID)).toBe(false); + expect(reads).toBe(after); // cached as definitive + expect(verify('./dist/a%00b.mjs', ID)).toBe(false); + const nul = reads; + expect(verify('./dist/a%00b.mjs', ID)).toBe(false); + expect(reads).toBe(nul); + }); + + describe('NODE_OPTIONS token handling is delegated to core; verifier cache', () => { + it('caches a definitive miss for every no-such-file code, including EINVAL (the win32 `/C:/` literal)', () => { + for (const code of ['ENOENT', 'ENOTDIR', 'ENAMETOOLONG', 'EISDIR', 'EINVAL']) { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + throw Object.assign(new Error(code), { code }); + }, + }); + expect(verify('/x/a.js', ID)).toBe(false); + const first = reads; + expect(verify('/x/a.js', ID)).toBe(false); + expect(reads).toBe(first); + } + }); + + it('holds a realistic number of registrations without evicting (no re-reads at 1000 chunks)', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + return `//# debugId=${ID}`; + }, + }); + for (let i = 0; i < 1000; i++) verify(`/x/c${i}.js`, ID); + const before = reads; + for (let i = 0; i < 1000; i++) verify(`/x/c${i}.js`, ID); + expect(reads).toBe(before); + }); + }); + + describe('cache', () => { + it('answers a repeated (file, id) with no further I/O, and caches rejections too', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: (path) => { + reads++; + if (path.endsWith('good.js')) return `//# debugId=${ID}`; + throw enoent(); + }, + }); + expect(verify('/x/good.js', ID)).toBe(true); + const afterFirst = reads; + expect(verify('/x/good.js', ID)).toBe(true); + expect(reads).toBe(afterFirst); + expect(verify('/x/bad.js', ID)).toBe(false); + const afterBad = reads; + expect(verify('/x/bad.js', ID)).toBe(false); + expect(reads).toBe(afterBad); + // a different id for the same file is a different question + expect(verify('/x/good.js', 'other-id')).toBe(false); + }); + + it('is bounded: after many distinct keys it still answers correctly', () => { + let reads = 0; + const verify = createStampedBundleVerifier({ + appRoot: '/x', + readTail: () => { + reads++; + return `//# debugId=${ID}`; + }, + }); + for (let i = 0; i < 5000; i++) expect(verify(`/x/f${i}.js`, ID)).toBe(true); + const before = reads; + expect(verify('/x/f4999.js', ID)).toBe(true); // recent: still cached + expect(reads).toBe(before); + expect(verify('/x/f0.js', ID)).toBe(true); // evicted: re-read, same answer + expect(reads).toBe(before + 1); + }); + }); +}); diff --git a/packages/node/src/debug-id-verifier.ts b/packages/node/src/debug-id-verifier.ts new file mode 100644 index 00000000..742c4213 --- /dev/null +++ b/packages/node/src/debug-id-verifier.ts @@ -0,0 +1,144 @@ +import { closeSync, fstatSync, openSync, readSync } from 'node:fs'; +import process from 'node:process'; +import { fileURLToPath } from 'node:url'; +import type { RegistrationVerifier } from '@bugsee/core'; +import { resolveFramePath } from './source-context'; + +// #185. Under `--enable-source-maps` a debug-ID registration's top frame may have been mapped to an ORIGINAL file +// (`src/main.js`) instead of the stamped bundle. The bundle a registration belongs to is proven by the file +// itself: `sourcemaps inject` leaves `//# debugId=` in its tail (same marker the bundler plugin reads, see +// `bundler-plugin-core/src/debug-ids.ts`; duplicated here because node must not depend on the build tooling), so a +// registration is genuine only if its top-frame file still carries that id. Core cannot read files; node supplies this. + +const MARKER = '//# debugId='; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const TAIL_BYTES = 16 * 1024; +/** A registration's file does not change during a process, so answers are cached (bounded; emptied when full). */ +const CACHE_MAX = 4096; + +/** The LAST `//# debugId=` stamp in `content` when it is a UUID (the bundler plugin's `readDebugId` rule). */ +export function readStampedDebugId(content: string): string | undefined { + const at = content.lastIndexOf(MARKER); + if (at === -1) { + return undefined; + } + const token = content + .slice(at + MARKER.length) + .trimStart() + .slice(0, 36) + .toLowerCase(); + return UUID_RE.test(token) ? token : undefined; +} + +function readTail(path: string): string { + const fd = openSync(path, 'r'); + try { + const { size } = fstatSync(fd); + const length = Math.min(size, TAIL_BYTES); + const buffer = Buffer.alloc(length); + readSync(fd, buffer, 0, length, size - length); + return buffer.toString('utf8'); + } finally { + closeSync(fd); + } +} + +/** + * The filesystem paths a scrubbed frame `file` may denote, most literal first. + * + * Core's scrubber strips `file://` by slicing WITHOUT URL-decoding, so an ESM frame arrives percent-encoded and may + * carry the import's `?v=1` / `#hash`: `/…/my%20app/dist/a.mjs` (posix), `/C:/app/dist/a.mjs` (Windows), and, for the + * common case of a file UNDER the app root, `./dist/my%20chunk.mjs?v=1`. The literal path is tried first (a file + * really named `a%20b`), then the decoded reading with the query/hash stripped, then the stripped literal. + */ +function candidatePaths(file: string, appRoot: string): string[] { + if (file.startsWith('file://')) { + return [fileURLToPath(file)]; + } + const candidates = [resolveFramePath(file, appRoot)]; + const bare = file.replace(/[?#].*$/, ''); + let decoded: string | undefined; + try { + // An absolute posix/`/C:/` path goes through the file-URL reading (it also yields `C:\…` on a win32 host); a + // relative one is a plain percent-decode. + decoded = file.startsWith('/') + ? fileURLToPath(`file://${bare}`) + : resolveFramePath(decodeURIComponent(bare), appRoot); + } catch { + // a literal `%` / `%2F` in a real name is not a valid encoding; the literal path stands + } + if (decoded !== undefined) { + candidates.push(decoded); + } + if (bare !== file) { + candidates.push(resolveFramePath(bare, appRoot)); + } + return candidates; +} + +/** Errors that mean "there is no such file" (a stable answer), as opposed to a transient EMFILE / EACCES / EIO. */ +const NO_SUCH_FILE = new Set([ + 'ENOENT', + 'ENOTDIR', + 'ENAMETOOLONG', + 'EISDIR', + 'EINVAL', + 'ERR_INVALID_ARG_VALUE', // a NUL byte (a decoded `%00`) in the path +]); + +/** + * A {@link RegistrationVerifier}: true only when `file` (a scrubbed frame path: absolute, app-relative `./x`, a + * URL-encoded ESM path or a `file://` URL) exists and ends with the registered debug-id stamp. Any failure (missing + * file, bad URL) is a rejection, never a throw: a registration that cannot be proven is not joined on. Definitive + * answers are cached per (file, id), so a report costs no file I/O after the first; an INCONCLUSIVE one (a transient + * read error such as EMFILE) is not cached and is asked again next time. + */ +export function createStampedBundleVerifier( + options: { appRoot?: string; readTail?: (path: string) => string } = {}, +): RegistrationVerifier { + const read = options.readTail ?? readTail; + const cache = new Map(); + /** true / false when definitive, undefined when a transient error stopped the check. */ + const check = (file: string, debugId: string): boolean | undefined => { + const wanted = debugId.toLowerCase(); + let transient = false; + // Every distinct reading is tried and ANY carrying the id accepts: a mapped original file never carries the + // stamp, so a wrong accept is impossible, while an unrelated file sitting at the literal reading (`a%20b.mjs` + // next to the stamped `a b.mjs`) must not hide the genuine one. + for (const path of new Set(candidatePaths(file, options.appRoot ?? process.cwd()))) { + try { + if (readStampedDebugId(read(path)) === wanted) { + return true; + } + } catch (error) { + // not openable under this reading; try the next + const code = (error as { code?: unknown }).code; + if (typeof code !== 'string' || !NO_SUCH_FILE.has(code)) { + transient = true; + } + } + } + return transient ? undefined : false; + }; + return (file, debugId) => { + const key = `${file}\0${debugId}`; + const hit = cache.get(key); + if (hit !== undefined) { + return hit; + } + let verdict: boolean | undefined; + try { + verdict = check(file, debugId); + } catch { + verdict = undefined; // a malformed file URL / cwd failure: reject now, ask again later + } + if (verdict === undefined) { + return false; + } + if (cache.size >= CACHE_MAX) { + cache.clear(); + } + cache.set(key, verdict); + return verdict; + }; +} diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index d12cb80e..dbb11740 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -17,6 +17,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { TraceProducer } from '@bugsee/capture'; import { + applyDebugIds, type BundleStore, BundleStoreToken, CaptureDataEntryBase, @@ -39,9 +40,11 @@ import { type NativeCrashSource, parseLocation, ReportMarkerStoreToken, + type StackFrame, type StoredEntry, serializeBundle, serviceToken, + setDebugIdRegistrationVerifier, setStackAppRoot, TransportToken, } from '@bugsee/core'; @@ -4054,3 +4057,32 @@ describe('launch — environment.app.uptime_s (snapshot at session start)', () = expect(onError).toHaveBeenCalledWith(boom); }); }); + +describe('launch — debug-ID registrations under runtime source-map support (#185)', () => { + afterEach(() => { + setStackAppRoot(undefined); + setDebugIdRegistrationVerifier(undefined); + }); + + it('installs a verifier that accepts the stamped bundle and rejects a mapped original file', () => { + const root = mkdtempSync(join(tmpdir(), 'bugsee-sm-launch-')); + try { + const id = '11111111-2222-5333-8444-555555555555'; + mkdirSync(join(root, 'dist')); + mkdirSync(join(root, 'src')); + writeFileSync(join(root, 'dist', 'app.js'), `x\n//# debugId=${id}\n`); + writeFileSync(join(root, 'src', 'main.js'), 'export {};\n'); + launchTracked('tok', baseOptions({ carrier: {}, appRoot: root })); + const stack = (file: string) => `Error\n at (${file}:1:1)`; + const registry = { [stack(`${root}/dist/app.js`)]: id, [stack(`${root}/src/main.js`)]: id }; + const frames = [{ file: './dist/app.js' }, { file: './src/main.js' }] as StackFrame[]; + applyDebugIds(frames, { + globalObject: { _bugseeDebugIds: registry }, + runtimeMapsStacks: true, + }); + expect(frames.map((f) => f.debugId)).toEqual([id, undefined]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index 56b8ef36..2fb72b97 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -66,6 +66,7 @@ import { setCarrierClient, setCarrierLastLaunch, setCarrierStatus, + setDebugIdRegistrationVerifier, setStackAppRoot, TransportToken, withTransportHeaders, @@ -92,6 +93,7 @@ import { createRequestScopedActiveSpanStore } from './active-span-store'; import { createNodeAppIdentitySource } from './app-identity-source'; import { type CpuProfiler, createCpuProfiler } from './cpu-profiler'; import { type CapturedDataStore, ensureSecureDataRoot, resolveDataLocation } from './data-location'; +import { createStampedBundleVerifier } from './debug-id-verifier'; import { createUncaughtExceptionProvider, createUnhandledRejectionProvider, @@ -637,6 +639,11 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc // capture. Dependency frames are already handled without this — they truncate at `node_modules` — // but application frames have no such landmark. setStackAppRoot(options.appRoot ?? safeCwd()); + // #185: under `--enable-source-maps` a debug-ID registration can be mapped to an original file; core only joins + // on registrations whose top-frame file still carries the stamp (the filesystem half core cannot have). + setDebugIdRegistrationVerifier( + createStampedBundleVerifier({ appRoot: options.appRoot ?? safeCwd() }), + ); const sdkVersion = options.sdkVersion ?? SDK_VERSION; const baseUrl = options.endpoint ?? DEFAULT_ENDPOINT;