Unverified Commit c0031816 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Handle invalid sourcemaps (#75713)

parent bcca20b1
...@@ -632,5 +632,6 @@ ...@@ -632,5 +632,6 @@
"631": "Invariant (SlowModuleDetectionPlugin): Circular dependency detected in module graph. This is a Next.js internal bug.", "631": "Invariant (SlowModuleDetectionPlugin): Circular dependency detected in module graph. This is a Next.js internal bug.",
"632": "Invariant (SlowModuleDetectionPlugin): Module is missing a required debugId. This is a Next.js internal bug.", "632": "Invariant (SlowModuleDetectionPlugin): Module is missing a required debugId. This is a Next.js internal bug.",
"633": "Dynamic route not found", "633": "Dynamic route not found",
"634": "Route %s used \"searchParams\" inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \"searchParams\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache" "634": "Route %s used \"searchParams\" inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \"searchParams\" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"635": "%s: Invalid source map. Only conformant source maps can be used to find the original code."
} }
...@@ -16,7 +16,11 @@ import path from 'path' ...@@ -16,7 +16,11 @@ import path from 'path'
import url from 'url' import url from 'url'
import { launchEditor } from '../internal/helpers/launchEditor' import { launchEditor } from '../internal/helpers/launchEditor'
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import { SourceMapConsumer } from 'next/dist/compiled/source-map08' import {
SourceMapConsumer,
type BasicSourceMapConsumer,
type NullableMappedPosition,
} from 'next/dist/compiled/source-map08'
import type { Project, TurbopackStackFrame } from '../../../../build/swc/types' import type { Project, TurbopackStackFrame } from '../../../../build/swc/types'
import { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file' import { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file'
import { findSourceMap, type SourceMapPayload } from 'node:module' import { findSourceMap, type SourceMapPayload } from 'node:module'
...@@ -230,39 +234,58 @@ function findApplicableSourceMapPayload( ...@@ -230,39 +234,58 @@ function findApplicableSourceMapPayload(
async function nativeTraceSource( async function nativeTraceSource(
frame: TurbopackStackFrame frame: TurbopackStackFrame
): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> { ): Promise<{ frame: IgnorableStackFrame; source: string | null } | undefined> {
const sourceMap = findSourceMap( const sourceURL = // TODO(veil): Why are the frames sent encoded?
// TODO(veil): Why are the frames sent encoded?
decodeURIComponent(frame.file) decodeURIComponent(frame.file)
) let sourceMapPayload: ModernSourceMapPayload | undefined
if (sourceMap !== undefined) { try {
const traced = await SourceMapConsumer.with( sourceMapPayload = findSourceMap(sourceURL)?.payload
sourceMap.payload, } catch (cause) {
null, throw new Error(
async (consumer) => { `${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,
const originalPosition = consumer.originalPositionFor({ { cause }
line: frame.line ?? 1, )
column: frame.column ?? 1, }
})
if (originalPosition.source === null) { if (sourceMapPayload !== undefined) {
return null let consumer: BasicSourceMapConsumer
} try {
consumer = await new SourceMapConsumer(sourceMapPayload)
} catch (cause) {
throw new Error(
`${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code.`,
{ cause }
)
}
let traced: {
originalPosition: NullableMappedPosition
sourceContent: string | null
} | null
try {
const originalPosition = consumer.originalPositionFor({
line: frame.line ?? 1,
column: frame.column ?? 1,
})
if (originalPosition.source === null) {
traced = null
} else {
const sourceContent: string | null = const sourceContent: string | null =
consumer.sourceContentFor( consumer.sourceContentFor(
originalPosition.source, originalPosition.source,
/* returnNullOnMissing */ true /* returnNullOnMissing */ true
) ?? null ) ?? null
return { originalPosition, sourceContent } traced = { originalPosition, sourceContent }
} }
) } finally {
consumer.destroy()
}
if (traced !== null) { if (traced !== null) {
const { originalPosition, sourceContent } = traced const { originalPosition, sourceContent } = traced
const applicableSourceMap = findApplicableSourceMapPayload( const applicableSourceMap = findApplicableSourceMapPayload(
frame, frame,
sourceMap.payload sourceMapPayload
) )
// TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not. // TODO(veil): Upstream a method to sourcemap consumer that immediately says if a frame is ignored or not.
......
import { constants as FS, promises as fs } from 'fs' import { constants as FS, promises as fs } from 'fs'
import path from 'path' import path from 'path'
import url from 'url' import url from 'url'
import { SourceMapConsumer } from 'next/dist/compiled/source-map08' import {
SourceMapConsumer,
type BasicSourceMapConsumer,
} from 'next/dist/compiled/source-map08'
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file' import { getSourceMapFromFile } from '../internal/helpers/get-source-map-from-file'
import { launchEditor } from '../internal/helpers/launchEditor' import { launchEditor } from '../internal/helpers/launchEditor'
...@@ -86,7 +89,16 @@ async function findOriginalSourcePositionAndContent( ...@@ -86,7 +89,16 @@ async function findOriginalSourcePositionAndContent(
sourceMap: RawSourceMap, sourceMap: RawSourceMap,
position: { line: number; column: number | null } position: { line: number; column: number | null }
): Promise<SourceAttributes | null> { ): Promise<SourceAttributes | null> {
const consumer = await new SourceMapConsumer(sourceMap) let consumer: BasicSourceMapConsumer
try {
consumer = await new SourceMapConsumer(sourceMap)
} catch (cause) {
throw new Error(
`${sourceMap.file}: Invalid source map. Only conformant source maps can be used to find the original code.`,
{ cause }
)
}
try { try {
const sourcePosition = consumer.originalPositionFor({ const sourcePosition = consumer.originalPositionFor({
line: position.line, line: position.line,
...@@ -533,8 +545,8 @@ export function getOverlayMiddleware(options: { ...@@ -533,8 +545,8 @@ export function getOverlayMiddleware(options: {
rootDirectory, rootDirectory,
}) })
) )
} catch (error) { } catch (err) {
return internalServerError(res, error) return badRequest(res)
} }
} else if (pathname === '/__nextjs_launch-editor') { } else if (pathname === '/__nextjs_launch-editor') {
const frame = { const frame = {
......
...@@ -151,6 +151,28 @@ interface SourcemappableStackFrame extends StackFrame { ...@@ -151,6 +151,28 @@ interface SourcemappableStackFrame extends StackFrame {
file: NonNullable<StackFrame['file']> file: NonNullable<StackFrame['file']>
} }
interface SourceMappedFrame {
stack: IgnoreableStackFrame
// DEV only
code: string | null
}
function createUnsourcemappedFrame(
frame: SourcemappableStackFrame
): SourceMappedFrame {
return {
stack: {
arguments: frame.arguments,
column: frame.column,
file: frame.file,
lineNumber: frame.lineNumber,
methodName: frame.methodName,
ignored: shouldIgnoreListGeneratedFrame(frame.file),
},
code: null,
}
}
/** /**
* @param frame * @param frame
* @param sourceMapCache * @param sourceMapCache
...@@ -176,27 +198,45 @@ function getSourcemappedFrameIfPossible( ...@@ -176,27 +198,45 @@ function getSourcemappedFrameIfPossible(
if (sourceURL.startsWith('/')) { if (sourceURL.startsWith('/')) {
sourceURL = url.pathToFileURL(frame.file).toString() sourceURL = url.pathToFileURL(frame.file).toString()
} }
const maybeSourceMapPayload = let maybeSourceMapPayload: ModernSourceMapPayload | undefined
nativeFindSourceMap(sourceURL)?.payload ?? try {
bundlerFindSourceMapPayload(sourceURL) const sourceMap = nativeFindSourceMap(sourceURL)
maybeSourceMapPayload = sourceMap?.payload
} catch (cause) {
// We should not log an actual error instance here because that will re-enter
// this codepath during error inspection and could lead to infinite recursion.
console.error(
`${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`
)
// Don't even fall back to the bundler because it might be not as strict
// with regards to parsing and then we fail later once we consume the
// source map payload.
// This essentially avoids a redundant error where we fail here and then
// later on consumption because the bundler just handed back an invalid
// source map.
return createUnsourcemappedFrame(frame)
}
if (maybeSourceMapPayload === undefined) { if (maybeSourceMapPayload === undefined) {
return { maybeSourceMapPayload = bundlerFindSourceMapPayload(sourceURL)
stack: { }
arguments: frame.arguments,
column: frame.column, if (maybeSourceMapPayload === undefined) {
file: frame.file, return createUnsourcemappedFrame(frame)
lineNumber: frame.lineNumber,
methodName: frame.methodName,
ignored: shouldIgnoreListGeneratedFrame(frame.file),
},
code: null,
}
} }
sourceMapPayload = maybeSourceMapPayload sourceMapPayload = maybeSourceMapPayload
sourceMapConsumer = new SyncSourceMapConsumer( try {
// @ts-expect-error -- Module.SourceMap['version'] is number but SyncSourceMapConsumer wants a string sourceMapConsumer = new SyncSourceMapConsumer(
sourceMapPayload // @ts-expect-error -- Module.SourceMap['version'] is number but SyncSourceMapConsumer wants a string
) sourceMapPayload
)
} catch (cause) {
// We should not log an actual error instance here because that will re-enter
// this codepath during error inspection and could lead to infinite recursion.
console.error(
`${sourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`
)
return createUnsourcemappedFrame(frame)
}
sourceMapCache.set(frame.file, { sourceMapCache.set(frame.file, {
map: sourceMapConsumer, map: sourceMapConsumer,
payload: sourceMapPayload, payload: sourceMapPayload,
......
// Compile with pnpm tsc test/e2e/app-dir/server-source-maps/fixtures/default/bad-sourcemap/page.js --allowJs --sourceMap --target esnext --outDir test/e2e/app-dir/server-source-maps/fixtures/default/app/bad-sourcemap
// Then change the `sources` entry in the sourcemap to `["custom://[badhost]/app/bad-sourcemap/page.js"]`
// tsc compile errors can be ignored
import { connection } from 'next/server'
export default async function Page() {
await connection()
console.error(new Error('Boom!'))
return <p>Hello, Dave!</p>
}
//# sourceMappingURL=page.js.map
{
"version": 3,
"file": "page.js",
"sourceRoot": "",
"sources": [
"custom://[badhost]/app/bad-sourcemap/page.js"
],
"names": [],
"mappings": "AAAA,yNAAyN;AACzN,yGAAyG;AACzG,oCAAoC;AAEpC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,MAAM,CAAC,OAAO,CAAC,KAAK,UAAU,IAAI;IAChC,MAAM,UAAU,EAAE,CAAA;IAClB,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAA;IACjC,OAAO,CAAC,CAAC,CAAC,YAAY,EAAE,CAAC,CAAC,CAAA;AAC5B,CAAC"
}
// Compile with pnpm tsc test/e2e/app-dir/server-source-maps/fixtures/default/bad-sourcemap/page.js --allowJs --sourceMap --target esnext --outDir test/e2e/app-dir/server-source-maps/fixtures/default/app/bad-sourcemap
// Then change the `sources` entry in the sourcemap to `["custom://[badhost]/app/bad-sourcemap/page.js"]`
// tsc compile errors can be ignored
import { connection } from 'next/server'
export default async function Page() {
await connection()
console.error(new Error('Boom!'))
return <p>Hello, Dave!</p>
}
...@@ -200,4 +200,42 @@ describe('app-dir - server source maps', () => { ...@@ -200,4 +200,42 @@ describe('app-dir - server source maps', () => {
isNextDev ? 'Error [MyError]: Bar' : 'Error [MyError]: Bar' isNextDev ? 'Error [MyError]: Bar' : 'Error [MyError]: Bar'
) )
}) })
it('handles invalid sourcemaps gracefully', async () => {
const outputIndex = next.cliOutput.length
await next.render('/bad-sourcemap')
await retry(() => {
expect(normalizeCliOutput(next.cliOutput.slice(outputIndex))).toContain(
'Error: Boom!'
)
})
if (isNextDev) {
if (isTurbopack) {
expect(normalizeCliOutput(next.cliOutput.slice(outputIndex))).toContain(
// Node.js is fine with invalid URLs in index maps apparently.
'' +
'\nError: Boom!' +
// TODO(veil): Turbopack's sourcemap loader generates a wrong source entry here
// Should not be sourcemapped or "custom://[badhost]/app/bad-sourcemap/page.js"
'\n at Page (app/bad-sourcemap/custom:/[badhost]/app/bad-sourcemap/page.js:9:15)' +
// TODO: Remove blank line
'\n'
)
} else {
expect(normalizeCliOutput(next.cliOutput.slice(outputIndex))).toContain(
// Node.js is not fine with invalid URLs in vanilla source maps.
// Feel free to adjust these locations. They're just here to showcase
// sourcemapping is broken on invalid sources.
'' +
`\nwebpack-internal:///(rsc)/./app/bad-sourcemap/page.js: Invalid source map. Only conformant source maps can be used to find the original code. Cause: TypeError [ERR_INVALID_ARG_TYPE]: The "payload" argument must be of type object. Received null` +
'\nError: Boom!' +
'\n at Page (webpack-internal:///(rsc)/./app/bad-sourcemap/page.js:15:19)'
)
}
} else {
// TODO: test `next start` with `--enable-source-maps`
}
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment