Unverified Commit 6dda4371 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Emit the Turbopack shared-runtime bootstrap in the PPR resume so it gets the CSP nonce (#100102)

### What?

With `cacheComponents` and the default
`experimental.turbopackSharedRuntime`, a Turbopack production build
breaks hydration under a nonce-based CSP (`script-src 'self'
'nonce-…'`). The route's inlined chunk-group bootstrap ends up in the
prerendered static shell without a nonce. The browser blocks it, the
Turbopack runtime never starts the entry, and the page stays
non-interactive.

This PR emits that bootstrap from the per-request part of the response
instead, where the request's nonce is known. The shared runtime stays on
by default.

### Why?

Since 16.4 the shared runtime replaces the per-route evaluate chunk with
an inline `globalThis.TURBOPACK.push({ otherChunks, runtimeModuleIds })`
script, passed to React as `bootstrapScriptContent`. A PPR static shell
is rendered at build time: there is no request, so React has no nonce to
put on it.

The shell can't be fixed when it's served either. On Vercel the proxy
serves the cached shell before any Next.js code runs, and only the
resumed dynamic stream is rendered per request. So the bootstrap has to
come from that stream.

### How?

**Server.** Cache Components prerenders now keep the Turbopack bootstrap
separate from the other bootstrap content, such as the Instant
Navigation testing script, and leave it out of the shell.
- For a postponed shell, the resume emits it as an inline script with
the request nonce, right before the inlined Flight data. This reuses the
existing data-injection pipeline, so the ordering is the same as today:
after the first HTML chunk for empty preludes, and for HTML- and
data-postponed state on both the Node and web stream paths.
- A complete prerender emits it the same way, as part of the stored
response.
- Fully dynamic renders and non-Cache-Components prerenders keep using
React's `bootstrapScriptContent`.
- The paths that serve a postponed shell without a resume (the Instant
Navigation testing lock and `__nextppronly` shell debugging) append the
bootstrap themselves.

**Client.** A bootstrap pushed after the shared runtime has loaded is
registered from inside that inline script. There,
`document.currentScript` has no `src`, so `appBootstrap()` threw
`Invalid URL` while deriving the asset prefix. That prefix is only used
by the dev server's HMR WebSocket, so it's now only derived on the dev
server. Dev behavior is unchanged.

**Not covered:**
- React's own `$RT` timing script in the static shell still has no
nonce, so a nonce CSP still reports that one violation. It doesn't
affect hydration, and it was already blocked before 16.4.
- Fully static pages under a nonce CSP are unchanged; their inline
Flight data has no nonce either.

### Tests

New e2e suite `test/e2e/app-dir/ppr-shared-runtime-csp-nonce`. It runs
on Turbopack production builds only (`@force-gate !dev && turbopack`)
and covers:
- the shell contains no bootstrap, and the resume contains it exactly
once with the request nonce
- the nonce is also picked up from a report-only CSP, and there is no
nonce without a CSP
- the page hydrates under a nonce CSP
- the page hydrates when the bootstrap runs after the shared runtime and
all entry chunks have loaded. The test forces that ordering
deterministically, and it fails without the client change.
- fully static pages keep the inline bootstrap and hydrate

It fails on `canary` because the bootstrap is in the shell without a
nonce and the page doesn't hydrate.

Existing suites run to check behavior didn't change:
- Turbopack start: `instant-navigation-testing-api` (this suite caught
the late-bootstrap `Invalid URL` issue), `ppr-partial-hydration`,
`partial-fallback-root-blocking`, `partial-fallback-shell-upgrade`,
`csp-nonce-segment-scripts`, `next-dynamic-csp-nonce`,
`static-shell-debugging`
- Webpack start: `csp-nonce-segment-scripts`
- Dev (Turbopack): `csp-nonce-segment-scripts`

I also checked by hand with the issue's reproduction (nonce CSP from
`proxy.ts`): the page hydrates and only the `$RT` violation remains.

Not run: Vercel deploy and edge-runtime tests.

Fixes #99800

<!-- NEXT_JS_LLM -->


<!-- fleet 551793ce-4e56-41fa-ab7b-183f9c45ac27 -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 2e559938
......@@ -101,6 +101,8 @@ import { RedirectStatusCode } from '../../client/components/redirect-status-code
import { InvariantError } from '../../shared/lib/invariant-error' with { 'turbopack-transition': 'next-server-utility' }
import { scheduleOnNextTick } from '../../lib/scheduler' with { 'turbopack-transition': 'next-server-utility' }
import { getSegmentParam } from '../../shared/lib/router/utils/get-segment-param' with { 'turbopack-transition': 'next-server-utility' }
import { createTurbopackBootstrapScriptStreamForPage } from '../../server/app-render/turbopack-bootstrap-script' with { 'turbopack-transition': 'next-server-utility' }
import { getScriptNonceFromHeaders } from '../../server/app-render/get-script-nonce-from-header' with { 'turbopack-transition': 'next-server-utility' }
type AppPageRenderOperation = 'render' | 'prerender'
......@@ -1970,6 +1972,19 @@ export function createAppPageEntrypoint({
const didPostpone = typeof cacheEntry.value.postponed === 'string'
// A static shell with postponed parts doesn't include the Turbopack
// bootstrap: the resume emits it with the request's CSP nonce. When
// such a shell is served without a resume, it has to be added.
const pushTurbopackBootstrapScript = (result: RenderResult) => {
if (!didPostpone) return
const bootstrapScript = createTurbopackBootstrapScriptStreamForPage(
buildManifest,
srcPage,
getScriptNonceFromHeaders(req.headers)
)
if (bootstrapScript) result.push(bootstrapScript)
}
// Set the build ID header for RSC navigation requests when deploymentId is configured. This
// corresponds with maybeAppendBuildIdToRSCPayload in app-render.tsx which omits the build ID
// from the RSC payload when deploymentId is set (relying on this header instead). Server
......@@ -2292,8 +2307,11 @@ export function createAppPageEntrypoint({
// Non-empty shell: the cookie-guarded bootstrap that sets
// self.__next_instant_test is embedded in the prerendered shell via
// `bootstrapScriptContent`, so it is already present (in the served
// shell for a fresh render, or in the cached prelude on deploy). Append
// the closing tags so the browser can parse a complete document.
// shell for a fresh render, or in the cached prelude on deploy). The
// Turbopack bootstrap is left out of the shell for the resume to
// emit, so add it here. Append the closing tags so the browser can
// parse a complete document.
pushTurbopackBootstrapScript(body)
body.push(
new ReadableStream({
start(controller) {
......@@ -2346,8 +2364,11 @@ export function createAppPageEntrypoint({
// HTML will be the static shell so all the Dynamic API's will be used
// during static generation.
if (isDebugStaticShell || isDebugDynamicAccesses) {
// Since we're not resuming the render, we need to at least add the
// closing body and html tags to create valid HTML.
// The Turbopack bootstrap is left out of the shell for the resume to
// emit, so add it here. Since we're not resuming the render, we need
// to at least add the closing body and html tags to create valid
// HTML.
pushTurbopackBootstrapScript(body)
body.push(
new ReadableStream({
start(controller) {
......
......@@ -5,9 +5,19 @@
* - next/script with `beforeInteractive` strategy
*/
import { getAssetPrefix } from './asset-prefix'
import { setAttributesFromProps } from './set-attributes-from-props'
if (process.env.__NEXT_DEV_SERVER) {
// Capture the asset prefix for the dev server's WebSocket while
// `document.currentScript` still is the entry script.
require('./dev/hot-reloader/app/asset-prefix') as typeof import('./dev/hot-reloader/app/asset-prefix')
} else {
// Only the dev server needs the asset prefix. In production,
// `document.currentScript` isn't reliable: the Turbopack shared runtime can
// run this module from the inline chunk-group bootstrap script, e.g. when a
// resumed response emits that bootstrap after the runtime has loaded.
}
const version = process.env.__NEXT_VERSION
window.next = {
......@@ -55,9 +65,7 @@ function loadScriptsInSequence(
})
}
export function appBootstrap(hydrate: (assetPrefix: string) => void) {
const assetPrefix = getAssetPrefix()
export function appBootstrap(hydrate: () => void) {
loadScriptsInSequence((self as any).__next_s, () => {
// If the static shell is being debugged, skip hydration if the
// `__nextppronly` query is present. This is only enabled when the
......@@ -76,6 +84,6 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) {
}
}
hydrate(assetPrefix)
hydrate()
})
}
......@@ -344,8 +344,7 @@ const reactRootOptions: ReactDOMClient.RootOptions = {
}
export async function hydrate(
instrumentationModules: ClientInstrumentationModules,
assetPrefix: string
instrumentationModules: ClientInstrumentationModules
) {
let staticIndicatorState: StaticIndicatorState | undefined
let webSocket: WebSocket | undefined
......@@ -355,7 +354,7 @@ export async function hydrate(
require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket')
staticIndicatorState = { pathname: null, appIsrManifest: null }
webSocket = createWebSocket(assetPrefix, staticIndicatorState)
webSocket = createWebSocket(staticIndicatorState)
}
const initialRSCPayload = await initialServerResponse
......
......@@ -10,12 +10,12 @@ import { isRecoverableError } from './react-client-callbacks/on-recoverable-erro
// eslint-disable-next-line @next/internal/typechecked-require
const instrumentationModules = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
appBootstrap(() => {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationModules, assetPrefix)
hydrate(instrumentationModules)
} finally {
renderAppDevOverlay(
getOwnerStack,
......
......@@ -8,10 +8,10 @@ window.next.turbopack = true
// eslint-disable-next-line @next/internal/typechecked-require
const instrumentationModules = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
appBootstrap(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationModules, assetPrefix)
hydrate(instrumentationModules)
} finally {
if (process.env.__NEXT_DEV_SERVER) {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
......
......@@ -7,12 +7,12 @@ const instrumentationModules =
// eslint-disable-next-line @next/internal/typechecked-require -- not a module
require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
appBootstrap(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index')
// Include app-router and layout-router in the main chunk
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
require('next/dist/client/components/app-router')
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
require('next/dist/client/components/layout-router')
hydrate(instrumentationModules, assetPrefix)
hydrate(instrumentationModules)
})
import { getAssetPrefix } from '../../../asset-prefix'
/**
* The asset prefix the dev server's WebSocket connects with.
*
* It's read from `document.currentScript`, which is only set while the entry
* script is being evaluated. So this module has to be evaluated then: it's
* required at the top level of `app-bootstrap.ts`, before any lazily required
* module (such as the WebSocket) runs. The dev overlay also imports the
* WebSocket module during server rendering, where there's no document.
*/
export const assetPrefix = typeof window === 'undefined' ? '' : getAssetPrefix()
......@@ -15,16 +15,14 @@ import {
import { logQueue } from '../../../../next-devtools/userspace/app/forward-logs'
import { InvariantError } from '../../../../shared/lib/invariant-error'
import { WEB_SOCKET_MAX_RECONNECTIONS } from '../../../../lib/constants'
import { assetPrefix } from './asset-prefix'
let reconnections = 0
let reloading = false
let serverSessionId: number | null = null
let mostRecentCompilationHash: string | null = null
export function createWebSocket(
assetPrefix: string,
staticIndicatorState: StaticIndicatorState
) {
export function createWebSocket(staticIndicatorState: StaticIndicatorState) {
if (!self.__next_r) {
throw new InvariantError(
`Expected a request ID to be defined for the document via self.__next_r.`
......
import { getScriptNonceFromHeader } from './get-script-nonce-from-header'
import {
getScriptNonceFromHeader,
getScriptNonceFromHeaders,
} from './get-script-nonce-from-header'
describe('getScriptNonceFromHeader', () => {
it('returns the first valid nonce from the script-src directive', () => {
......@@ -26,3 +29,44 @@ describe('getScriptNonceFromHeader', () => {
).toBe('cmFuZG9tCg==')
})
})
describe('getScriptNonceFromHeaders', () => {
it('returns the nonce from the Content-Security-Policy header', () => {
expect(
getScriptNonceFromHeaders({
'content-security-policy': `script-src 'nonce-cmFuZG9tCg=='`,
})
).toBe('cmFuZG9tCg==')
})
it('falls back to the Content-Security-Policy-Report-Only header', () => {
expect(
getScriptNonceFromHeaders({
'content-security-policy-report-only': `script-src 'nonce-cmVwb3J0'`,
})
).toBe('cmVwb3J0')
})
it('prefers the Content-Security-Policy header over the report-only one', () => {
expect(
getScriptNonceFromHeaders({
'content-security-policy': `script-src 'nonce-ZW5mb3JjZWQ='`,
'content-security-policy-report-only': `script-src 'nonce-cmVwb3J0'`,
})
).toBe('ZW5mb3JjZWQ=')
})
it('returns undefined without a CSP header', () => {
expect(getScriptNonceFromHeaders({})).toBeUndefined()
})
it('ignores non-string header values', () => {
expect(
getScriptNonceFromHeaders({
'content-security-policy': [
`script-src 'nonce-cmFuZG9tCg=='`,
] as unknown as string,
})
).toBeUndefined()
})
})
import type { IncomingHttpHeaders } from 'http'
const CSP_NONCE_SOURCE_REGEX = /^'nonce-([A-Za-z0-9+/_-]+={0,2})'$/
/**
* Returns the script nonce from the request's `Content-Security-Policy`
* header, falling back to `Content-Security-Policy-Report-Only`.
*/
export function getScriptNonceFromHeaders(
headers: IncomingHttpHeaders
): string | undefined {
const csp =
headers['content-security-policy'] ||
headers['content-security-policy-report-only']
return typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined
}
export function getScriptNonceFromHeader(
cspHeaderValue: string
): string | undefined {
......
import {
htmlEscapeAttributeString,
htmlEscapeJsonString,
} from '../../shared/lib/htmlescape'
import {
getTurbopackChunkGroupBootstrap,
type BuildManifest,
} from '../get-page-files'
import { streamFromString } from '../stream-utils/node-web-streams-helper'
/**
* Renders the Turbopack chunk-group bootstrap (see
* `getTurbopackChunkGroupBootstrap`) as an inline `<script>` tag.
*
* Under Cache Components, a static shell is prerendered without a request, so
* it can never carry the per-request CSP nonce. A static shell that is resumed
* therefore leaves the bootstrap out, and the per-request resume emits it with
* this helper instead, so that a nonce-based CSP allows it. The resume can't
* add it to the shell, since on Vercel the shell is served before any Next.js
* code runs. The shared runtime picks up a bootstrap pushed after it has
* loaded: once it runs it replaces the queue with `{ push: registerChunk }`.
* The entry's runtime modules can then be instantiated from within this inline
* script, so they mustn't depend on `document.currentScript` being one of the
* chunk scripts (see `appBootstrap`).
*/
export function getTurbopackBootstrapScriptTag(
scriptContent: string,
nonce: string | undefined
): string {
const startScriptTag = nonce
? `<script nonce="${htmlEscapeAttributeString(nonce)}">`
: '<script>'
// The bootstrap is `globalThis[<JSON string>].push(<JSON params>)`: the only
// characters that need escaping can only appear inside its JSON string
// literals, where the `\uXXXX` escapes keep their value.
return `${startScriptTag}${htmlEscapeJsonString(scriptContent)}</script>`
}
export function createTurbopackBootstrapScriptStream(
scriptContent: string,
nonce: string | undefined
): ReadableStream<Uint8Array> {
return streamFromString(getTurbopackBootstrapScriptTag(scriptContent, nonce))
}
/**
* The Turbopack bootstrap script for `page`, for serving a Cache Components
* static shell on its own, without the resume that would otherwise emit it.
* Returns undefined when the build doesn't inline a bootstrap for the page.
*/
export function createTurbopackBootstrapScriptStreamForPage(
buildManifest: BuildManifest,
page: string,
nonce: string | undefined
): ReadableStream<Uint8Array> | undefined {
if (
!buildManifest.pagesChunkGroupBootstrapParams ||
!buildManifest.chunkLoadingGlobal
) {
return undefined
}
const scriptContent = getTurbopackChunkGroupBootstrap(
buildManifest.pagesChunkGroupBootstrapParams,
buildManifest.chunkLoadingGlobal,
[page]
)
return scriptContent
? createTurbopackBootstrapScriptStream(scriptContent, nonce)
: undefined
}
......@@ -105,7 +105,7 @@ import { getCacheControlHeader } from './lib/cache-control'
import { getErrorSource } from '../shared/lib/error-source'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup'
import { getScriptNonceFromHeader } from './app-render/get-script-nonce-from-header'
import { getScriptNonceFromHeaders } from './app-render/get-script-nonce-from-header'
let tryGetPreviewData: typeof import('./api-utils/node/try-get-preview-data').tryGetPreviewData
let warn: typeof import('../build/output/log').warn
......@@ -738,12 +738,7 @@ export async function renderToHTMLImpl(
.map((script: any) => script.props)
}
const csp =
req.headers['content-security-policy'] ||
req.headers['content-security-policy-report-only']
const nonce =
typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined
const nonce = getScriptNonceFromHeaders(req.headers)
const AppContainer = ({ children }: { children: JSX.Element }) => (
<AppRouterContext.Provider value={appRouter}>
......
......@@ -10,7 +10,7 @@ import {
NEXT_HTML_REQUEST_ID_HEADER,
} from '../../../client/components/app-router-headers'
import { isRSCRequestHeader } from '../../lib/is-rsc-request'
import { getScriptNonceFromHeader } from '../../app-render/get-script-nonce-from-header'
import { getScriptNonceFromHeaders } from '../../app-render/get-script-nonce-from-header'
import { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
import { getPreviouslyRevalidatedTags } from '../../server-utils'
......@@ -77,12 +77,7 @@ export function parseRequestHeaders(
const isRouteTreePrefetchRequest =
isRSCRequest && headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] === '/_tree'
const csp =
headers['content-security-policy'] ||
headers['content-security-policy-report-only']
const nonce =
typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined
const nonce = getScriptNonceFromHeaders(headers)
const previouslyRevalidatedTags = getPreviouslyRevalidatedTags(
headers,
......
import { nextTestSetup } from 'e2e-utils'
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('app-dir assetPrefix handling', () => {
const { next } = nextTestSetup({
......@@ -32,6 +33,36 @@ describe('app-dir assetPrefix handling', () => {
expect(await browser.waitForElementByCss('#a-page').text()).toBe('A page')
})
if (isNextDev) {
it('should apply HMR updates', async () => {
// The HMR WebSocket connects to a URL derived from the asset prefix.
const webSocketUrls: string[] = []
const browser = await next.browser('/a', {
beforePageLoad(page) {
page.on('websocket', (ws) => webSocketUrls.push(ws.url()))
},
})
expect(await browser.waitForElementByCss('#a-page').text()).toBe('A page')
await retry(async () => {
expect(webSocketUrls).toContainEqual(
expect.stringContaining('/custom-asset-prefix/_next/hmr?')
)
})
await next.patchFile(
'app/a/page.js',
(content) => content.replace('A page', 'A page (updated)'),
async () => {
await retry(async () => {
expect(await browser.elementByCss('#a-page').text()).toBe(
'A page (updated)'
)
})
}
)
})
}
it('bundles should return 200 on served assetPrefix', async () => {
const $ = await next.render$('/')
......
'use client'
import { useEffect, useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
const [hydrated, setHydrated] = useState(false)
useEffect(() => setHydrated(true), [])
return (
<button
id="counter"
data-hydrated={hydrated ? 'true' : 'false'}
onClick={() => setCount((c) => c + 1)}
>
{count}
</button>
)
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { Counter } from './counter'
async function Dynamic() {
await connection()
return <p id="dynamic">dynamic</p>
}
// A static shell with a dynamic hole: prerendered with a postponed state and
// resumed per request.
export default function Page() {
return (
<main>
<h1 id="shell">shell</h1>
<Counter />
<Suspense fallback={<p id="fallback">loading</p>}>
<Dynamic />
</Suspense>
</main>
)
}
import { Counter } from '../counter'
// Fully static: prerendered without a postponed state.
export default function Page() {
return (
<main>
<h1 id="static">static</h1>
<Counter />
</main>
)
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
// This is the default, but pin it since the suite is about the inlined
// Turbopack chunk-group bootstrap that the shared runtime produces.
turbopackSharedRuntime: true,
},
}
export default nextConfig
import { nextTestSetup, type Playwright } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { splitResponseWithPPRSentinel } from 'e2e-utils/ppr'
import cheerio from 'cheerio'
// The inlined chunk-group bootstrap that `experimental.turbopackSharedRuntime`
// emits: `(globalThis["TURBOPACK"] || ...).push({"otherChunks":...})`.
const BOOTSTRAP_MARKER = '"otherChunks"'
function getNonce(csp: string | null): string {
const match = csp?.match(/'nonce-([^']+)'/)
if (!match) throw new Error(`Expected a nonce in the CSP header: ${csp}`)
return match[1]
}
function getBootstrapScripts(html: string) {
const $ = cheerio.load(html)
return $('script:not([src])')
.toArray()
.filter((element) => $(element).html()!.includes(BOOTSTRAP_MARKER))
.map((element) => ({ nonce: $(element).attr('nonce') }))
}
// The params of the (single) bootstrap `globalThis[...].push(<params>)`.
function getBootstrapParams(html: string): {
otherChunks: Array<string | { path: string }>
} {
const $ = cheerio.load(html)
const script = $('script:not([src])')
.toArray()
.map((element) => $(element).html()!)
.find((content) => content.includes(BOOTSTRAP_MARKER))!
const start = script.indexOf('.push(') + '.push('.length
return JSON.parse(script.slice(start, script.lastIndexOf(')')))
}
async function expectNoUnexpectedCspViolations(browser: Playwright) {
if (global.browserName !== 'chrome') return
const logs = await browser.log()
const cspViolations = logs.filter(
(log) =>
log.message.includes('Content Security Policy') &&
// React's `$RT` timing script in the static shell has no nonce
// either. It doesn't affect hydration, so only the inline scripts
// that matter are checked below.
!log.message.includes('Executing inline script')
)
expect(cspViolations).toEqual([])
const inlineViolations = logs.filter((log) =>
log.message.includes('Executing inline script')
)
// At most the `$RT` script may be blocked.
expect(inlineViolations.length).toBeLessThanOrEqual(1)
}
// The shared runtime (and thus the inlined bootstrap) only exists in Turbopack
// production builds.
// @force-gate !dev && turbopack
describe('ppr-shared-runtime-csp-nonce', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should emit the bootstrap with the request nonce in the resumed dynamic part, not in the static shell', async () => {
let csp: string | null = null
const [staticPart, dynamicPart] = await splitResponseWithPPRSentinel(
async () => {
const res = await next.fetch('/')
csp = res.headers.get('content-security-policy')
return res.body
}
)
const nonce = getNonce(csp)
// The fixture allows the Vercel toolbar that preview deployments inject.
expect(csp).toContain(
`script-src 'self' 'nonce-${nonce}' https://vercel.live;`
)
expect(dynamicPart).not.toBe('')
expect(getBootstrapScripts(staticPart)).toEqual([])
expect(getBootstrapScripts(dynamicPart)).toEqual([{ nonce }])
})
it('should emit the bootstrap with the nonce of a report-only CSP in the resumed dynamic part', async () => {
let csp: string | null = null
const [staticPart, dynamicPart] = await splitResponseWithPPRSentinel(
async () => {
const res = await next.fetch('/?csp=report-only')
expect(res.headers.get('content-security-policy')).toBeNull()
csp = res.headers.get('content-security-policy-report-only')
return res.body
}
)
const nonce = getNonce(csp)
expect(getBootstrapScripts(staticPart)).toEqual([])
expect(getBootstrapScripts(dynamicPart)).toEqual([{ nonce }])
})
it('should emit the bootstrap without a nonce in the resumed dynamic part when there is no CSP', async () => {
const [staticPart, dynamicPart] = await splitResponseWithPPRSentinel(
async () => {
const res = await next.fetch('/?csp=none')
expect(res.headers.get('content-security-policy')).toBeNull()
return res.body
}
)
expect(getBootstrapScripts(staticPart)).toEqual([])
expect(getBootstrapScripts(dynamicPart)).toEqual([{ nonce: undefined }])
})
it('should hydrate under a nonce-based CSP without CSP violations for the bootstrap', async () => {
const browser = await next.browser('/')
await browser.waitForElementByCss('#counter[data-hydrated="true"]')
await browser.elementByCss('#counter').click()
await retry(async () => {
expect(await browser.elementByCss('#counter').text()).toBe('1')
})
expect(await browser.elementByCss('#dynamic').text()).toBe('dynamic')
await expectNoUnexpectedCspViolations(browser)
})
it('should hydrate when the resumed bootstrap runs after the shared runtime has loaded', async () => {
// The resume usually reaches the browser after the static shell, e.g. when
// a CDN serves the shell and the resume comes from a function, by which
// point the (cached) shared runtime and the entry's chunks may already
// have run. Make that ordering deterministic: load every chunk of the
// entry with blocking scripts in the head, so they all run before the
// parser reaches the bootstrap in the resumed part. The runtime then
// instantiates the entry from within the inline bootstrap script.
const browser = await next.browser('/', {
pushErrorAsConsoleLog: true,
async beforePageLoad(page) {
await page.route(
(url) => url.pathname === '/',
async (route) => {
const response = await route.fetch()
let html = await response.text()
const blockingScripts = getBootstrapParams(html)
.otherChunks.map((chunk) =>
typeof chunk === 'string' ? chunk : chunk.path
)
.filter((path) => path.endsWith('.js'))
.map((path) => `<script src="/_next/${path}"></script>`)
.join('')
html = html
.replace(/(<script src="[^"]+") async=""/g, '$1')
.replace('</head>', `${blockingScripts}</head>`)
await route.fulfill({ response, body: html })
}
)
},
})
await browser.waitForElementByCss('#counter[data-hydrated="true"]')
await browser.elementByCss('#counter').click()
await retry(async () => {
expect(await browser.elementByCss('#counter').text()).toBe('1')
})
const pageErrors = (await browser.log()).filter(
(log) =>
log.source === 'error' &&
// React's `$RT` timing script in the static shell has no nonce.
!log.message.includes('Content Security Policy')
)
expect(pageErrors).toEqual([])
})
it('should keep the bootstrap inline in fully static pages', async () => {
const html = await next.render('/static')
expect(getBootstrapScripts(html)).toEqual([{ nonce: undefined }])
const browser = await next.browser('/static')
await browser.waitForElementByCss('#counter[data-hydrated="true"]')
await browser.elementByCss('#counter').click()
await retry(async () => {
expect(await browser.elementByCss('#counter').text()).toBe('1')
})
})
})
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const mode = request.nextUrl.searchParams.get('csp')
if (mode === 'none') {
return NextResponse.next()
}
const nonce = Buffer.from(crypto.randomUUID()).toString('base64')
// Vercel preview deployments inject the Vercel toolbar (served from
// vercel.live), so allow it to keep the CSP violation checks meaningful when
// deployed.
const vercelLive = 'https://vercel.live'
const csp = [
`default-src 'self'`,
`script-src 'self' 'nonce-${nonce}' ${vercelLive}`,
`style-src 'self' 'unsafe-inline' ${vercelLive}`,
`img-src 'self' ${vercelLive}`,
`font-src 'self' ${vercelLive}`,
`connect-src 'self' ${vercelLive}`,
`frame-src 'self' ${vercelLive}`,
`object-src 'none'`,
`base-uri 'self'`,
].join('; ')
const header =
mode === 'report-only'
? 'content-security-policy-report-only'
: 'content-security-policy'
const requestHeaders = new Headers(request.headers)
requestHeaders.set(header, csp)
const response = NextResponse.next({ request: { headers: requestHeaders } })
response.headers.set(header, csp)
return response
}
export const config = {
// Fully static pages are not compatible with a nonce-based CSP (their inline
// Flight data can't carry a per-request nonce), so `/static` is served
// without one.
matcher: ['/((?!static|_next).*)'],
}
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