Unverified Commit 22e51c12 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[lts-active] Emit the Turbopack shared-runtime bootstrap in the PPR resume so it…

[lts-active] Emit the Turbopack shared-runtime bootstrap in the PPR resume so it gets the CSP nonce (#100907)

Backports #100102 to `releases/lts/active`.

Fixes #100906

The cherry-pick applied cleanly.

## Verification

- `pnpm --filter=next types`
- `get-script-nonce-from-header.test.ts` unit test
- Not run locally: the new `ppr-shared-runtime-csp-nonce` e2e suite
(this checkout's `node_modules` is installed for canary, and LTS needs a
full reinstall). CI runs it.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
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 9f930cef
...@@ -100,6 +100,8 @@ import { RedirectStatusCode } from '../../client/components/redirect-status-code ...@@ -100,6 +100,8 @@ import { RedirectStatusCode } from '../../client/components/redirect-status-code
import { InvariantError } from '../../shared/lib/invariant-error' with { 'turbopack-transition': 'next-server-utility' } 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 { 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 { 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' type AppPageRenderOperation = 'render' | 'prerender'
...@@ -2006,6 +2008,19 @@ export function createAppPageEntrypoint({ ...@@ -2006,6 +2008,19 @@ export function createAppPageEntrypoint({
const didPostpone = typeof cacheEntry.value.postponed === 'string' 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 // 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 // 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 // from the RSC payload when deploymentId is set (relying on this header instead). Server
...@@ -2328,8 +2343,11 @@ export function createAppPageEntrypoint({ ...@@ -2328,8 +2343,11 @@ export function createAppPageEntrypoint({
// Non-empty shell: the cookie-guarded bootstrap that sets // Non-empty shell: the cookie-guarded bootstrap that sets
// self.__next_instant_test is embedded in the prerendered shell via // self.__next_instant_test is embedded in the prerendered shell via
// `bootstrapScriptContent`, so it is already present (in the served // `bootstrapScriptContent`, so it is already present (in the served
// shell for a fresh render, or in the cached prelude on deploy). Append // shell for a fresh render, or in the cached prelude on deploy). The
// the closing tags so the browser can parse a complete document. // 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( body.push(
new ReadableStream({ new ReadableStream({
start(controller) { start(controller) {
...@@ -2382,8 +2400,11 @@ export function createAppPageEntrypoint({ ...@@ -2382,8 +2400,11 @@ export function createAppPageEntrypoint({
// HTML will be the static shell so all the Dynamic API's will be used // HTML will be the static shell so all the Dynamic API's will be used
// during static generation. // during static generation.
if (isDebugStaticShell || isDebugDynamicAccesses) { if (isDebugStaticShell || isDebugDynamicAccesses) {
// Since we're not resuming the render, we need to at least add the // The Turbopack bootstrap is left out of the shell for the resume to
// closing body and html tags to create valid HTML. // 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( body.push(
new ReadableStream({ new ReadableStream({
start(controller) { start(controller) {
......
...@@ -5,9 +5,19 @@ ...@@ -5,9 +5,19 @@
* - next/script with `beforeInteractive` strategy * - next/script with `beforeInteractive` strategy
*/ */
import { getAssetPrefix } from './asset-prefix'
import { setAttributesFromProps } from './set-attributes-from-props' 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 const version = process.env.__NEXT_VERSION
window.next = { window.next = {
...@@ -55,9 +65,7 @@ function loadScriptsInSequence( ...@@ -55,9 +65,7 @@ function loadScriptsInSequence(
}) })
} }
export function appBootstrap(hydrate: (assetPrefix: string) => void) { export function appBootstrap(hydrate: () => void) {
const assetPrefix = getAssetPrefix()
loadScriptsInSequence((self as any).__next_s, () => { loadScriptsInSequence((self as any).__next_s, () => {
// If the static shell is being debugged, skip hydration if the // If the static shell is being debugged, skip hydration if the
// `__nextppronly` query is present. This is only enabled when the // `__nextppronly` query is present. This is only enabled when the
...@@ -76,6 +84,6 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) { ...@@ -76,6 +84,6 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) {
} }
} }
hydrate(assetPrefix) hydrate()
}) })
} }
...@@ -344,8 +344,7 @@ const reactRootOptions: ReactDOMClient.RootOptions = { ...@@ -344,8 +344,7 @@ const reactRootOptions: ReactDOMClient.RootOptions = {
} }
export async function hydrate( export async function hydrate(
instrumentationModules: ClientInstrumentationModules, instrumentationModules: ClientInstrumentationModules
assetPrefix: string
) { ) {
let staticIndicatorState: StaticIndicatorState | undefined let staticIndicatorState: StaticIndicatorState | undefined
let webSocket: WebSocket | undefined let webSocket: WebSocket | undefined
...@@ -355,7 +354,7 @@ export async function hydrate( ...@@ -355,7 +354,7 @@ export async function hydrate(
require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket') require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket')
staticIndicatorState = { pathname: null, appIsrManifest: null } staticIndicatorState = { pathname: null, appIsrManifest: null }
webSocket = createWebSocket(assetPrefix, staticIndicatorState) webSocket = createWebSocket(staticIndicatorState)
} }
const initialRSCPayload = await initialServerResponse const initialRSCPayload = await initialServerResponse
......
...@@ -10,12 +10,12 @@ import { isRecoverableError } from './react-client-callbacks/on-recoverable-erro ...@@ -10,12 +10,12 @@ import { isRecoverableError } from './react-client-callbacks/on-recoverable-erro
// eslint-disable-next-line @next/internal/typechecked-require // eslint-disable-next-line @next/internal/typechecked-require
const instrumentationModules = require('../lib/require-instrumentation-client') const instrumentationModules = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => { appBootstrap(() => {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
const { hydrate } = require('./app-index') as typeof import('./app-index') const { hydrate } = require('./app-index') as typeof import('./app-index')
try { try {
hydrate(instrumentationModules, assetPrefix) hydrate(instrumentationModules)
} finally { } finally {
renderAppDevOverlay( renderAppDevOverlay(
getOwnerStack, getOwnerStack,
......
...@@ -8,10 +8,10 @@ window.next.turbopack = true ...@@ -8,10 +8,10 @@ window.next.turbopack = true
// eslint-disable-next-line @next/internal/typechecked-require // eslint-disable-next-line @next/internal/typechecked-require
const instrumentationModules = require('../lib/require-instrumentation-client') const instrumentationModules = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => { appBootstrap(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index') const { hydrate } = require('./app-index') as typeof import('./app-index')
try { try {
hydrate(instrumentationModules, assetPrefix) hydrate(instrumentationModules)
} finally { } finally {
if (process.env.__NEXT_DEV_SERVER) { if (process.env.__NEXT_DEV_SERVER) {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
......
...@@ -7,12 +7,12 @@ const instrumentationModules = ...@@ -7,12 +7,12 @@ const instrumentationModules =
// eslint-disable-next-line @next/internal/typechecked-require -- not a module // eslint-disable-next-line @next/internal/typechecked-require -- not a module
require('../lib/require-instrumentation-client') require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => { appBootstrap(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index') const { hydrate } = require('./app-index') as typeof import('./app-index')
// Include app-router and layout-router in the main chunk // Include app-router and layout-router in the main chunk
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports? // eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
require('next/dist/client/components/app-router') require('next/dist/client/components/app-router')
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports? // eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
require('next/dist/client/components/layout-router') 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 { ...@@ -15,16 +15,14 @@ import {
import { logQueue } from '../../../../next-devtools/userspace/app/forward-logs' import { logQueue } from '../../../../next-devtools/userspace/app/forward-logs'
import { InvariantError } from '../../../../shared/lib/invariant-error' import { InvariantError } from '../../../../shared/lib/invariant-error'
import { WEB_SOCKET_MAX_RECONNECTIONS } from '../../../../lib/constants' import { WEB_SOCKET_MAX_RECONNECTIONS } from '../../../../lib/constants'
import { assetPrefix } from './asset-prefix'
let reconnections = 0 let reconnections = 0
let reloading = false let reloading = false
let serverSessionId: number | null = null let serverSessionId: number | null = null
let mostRecentCompilationHash: string | null = null let mostRecentCompilationHash: string | null = null
export function createWebSocket( export function createWebSocket(staticIndicatorState: StaticIndicatorState) {
assetPrefix: string,
staticIndicatorState: StaticIndicatorState
) {
if (!self.__next_r) { if (!self.__next_r) {
throw new InvariantError( throw new InvariantError(
`Expected a request ID to be defined for the document via self.__next_r.` `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', () => { describe('getScriptNonceFromHeader', () => {
it('returns the first valid nonce from the script-src directive', () => { it('returns the first valid nonce from the script-src directive', () => {
...@@ -26,3 +29,44 @@ describe('getScriptNonceFromHeader', () => { ...@@ -26,3 +29,44 @@ describe('getScriptNonceFromHeader', () => {
).toBe('cmFuZG9tCg==') ).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})'$/ 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( export function getScriptNonceFromHeader(
cspHeaderValue: string cspHeaderValue: string
): string | undefined { ): 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' ...@@ -105,7 +105,7 @@ import { getCacheControlHeader } from './lib/cache-control'
import { getErrorSource } from '../shared/lib/error-source' import { getErrorSource } from '../shared/lib/error-source'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import type { PagesDevOverlayBridgeType } from '../next-devtools/userspace/pages/pages-dev-overlay-setup' 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 tryGetPreviewData: typeof import('./api-utils/node/try-get-preview-data').tryGetPreviewData
let warn: typeof import('../build/output/log').warn let warn: typeof import('../build/output/log').warn
...@@ -738,12 +738,7 @@ export async function renderToHTMLImpl( ...@@ -738,12 +738,7 @@ export async function renderToHTMLImpl(
.map((script: any) => script.props) .map((script: any) => script.props)
} }
const csp = const nonce = getScriptNonceFromHeaders(req.headers)
req.headers['content-security-policy'] ||
req.headers['content-security-policy-report-only']
const nonce =
typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined
const AppContainer = ({ children }: { children: JSX.Element }) => ( const AppContainer = ({ children }: { children: JSX.Element }) => (
<AppRouterContext.Provider value={appRouter}> <AppRouterContext.Provider value={appRouter}>
......
...@@ -10,7 +10,7 @@ import { ...@@ -10,7 +10,7 @@ import {
NEXT_HTML_REQUEST_ID_HEADER, NEXT_HTML_REQUEST_ID_HEADER,
} from '../../../client/components/app-router-headers' } from '../../../client/components/app-router-headers'
import { isRSCRequestHeader } from '../../lib/is-rsc-request' 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 { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
import { getPreviouslyRevalidatedTags } from '../../server-utils' import { getPreviouslyRevalidatedTags } from '../../server-utils'
...@@ -77,12 +77,7 @@ export function parseRequestHeaders( ...@@ -77,12 +77,7 @@ export function parseRequestHeaders(
const isRouteTreePrefetchRequest = const isRouteTreePrefetchRequest =
isRSCRequest && headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] === '/_tree' isRSCRequest && headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] === '/_tree'
const csp = const nonce = getScriptNonceFromHeaders(headers)
headers['content-security-policy'] ||
headers['content-security-policy-report-only']
const nonce =
typeof csp === 'string' ? getScriptNonceFromHeader(csp) : undefined
const previouslyRevalidatedTags = getPreviouslyRevalidatedTags( const previouslyRevalidatedTags = getPreviouslyRevalidatedTags(
headers, headers,
......
import { nextTestSetup } from 'e2e-utils' import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('app-dir assetPrefix handling', () => { describe('app-dir assetPrefix handling', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -32,6 +33,36 @@ describe('app-dir assetPrefix handling', () => { ...@@ -32,6 +33,36 @@ describe('app-dir assetPrefix handling', () => {
expect(await browser.waitForElementByCss('#a-page').text()).toBe('A page') 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 () => { it('bundles should return 200 on served assetPrefix', async () => {
const $ = await next.render$('/') 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