Unverified Commit 544f5212 authored by Trevor Burnham's avatar Trevor Burnham Committed by GitHub

fix: Include CSP nonce in next/dynamic preload (#81999)

Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent 1bfe63a6
......@@ -1982,7 +1982,8 @@ export const renderToHTMLOrFlight: AppPageRender = (
previewModeId: renderOpts.previewProps?.previewModeId,
})
const { isPrefetchRequest, previouslyRevalidatedTags } = parsedRequestHeaders
const { isPrefetchRequest, previouslyRevalidatedTags, nonce } =
parsedRequestHeaders
let postponedState: PostponedState | null = null
......@@ -2018,6 +2019,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
isPrefetchRequest,
buildId: sharedContext.buildId,
previouslyRevalidatedTags,
nonce,
})
return workAsyncStorage.run(
......
......@@ -97,6 +97,7 @@ export interface WorkStore {
Record<string, { files: string[] }>
>
readonly assetPrefix?: string
readonly nonce?: string
cacheComponentsEnabled: boolean
dev: boolean
......
......@@ -20,6 +20,7 @@ export type WorkStoreContext = {
page: string
isPrefetchRequest?: boolean
nonce?: string
renderOpts: {
cacheLifeProfiles?: { [profile: string]: CacheLife }
incrementalCache?: IncrementalCache
......@@ -79,6 +80,7 @@ export function createWorkStore({
isPrefetchRequest,
buildId,
previouslyRevalidatedTags,
nonce,
}: WorkStoreContext): WorkStore {
/**
* Rules of Static & Dynamic HTML:
......@@ -135,6 +137,7 @@ export function createWorkStore({
buildId,
reactLoadableManifest: renderOpts?.reactLoadableManifest || {},
assetPrefix: renderOpts?.assetPrefix || '',
nonce,
afterContext: createAfterContext(renderOpts),
cacheComponentsEnabled: renderOpts.experimental.cacheComponents,
......
......@@ -58,6 +58,7 @@ export function PreloadChunks({
href={href}
rel="stylesheet"
as="style"
nonce={workStore.nonce}
/>
)
} else {
......@@ -65,6 +66,7 @@ export function PreloadChunks({
preload(href, {
as: 'script',
fetchPriority: 'low',
nonce: workStore.nonce,
})
return null
}
......
'use client'
export default function DynamicComponent() {
return (
<div id="dynamic-component-loaded">
Dynamic component loaded successfully
</div>
)
}
import { headers } from 'next/headers'
import { Suspense } from 'react'
async function CSPMetatag({ children }) {
const resolvedHeaders = await headers()
const nonce = resolvedHeaders.get('x-nonce') || 'test-nonce'
return (
<meta
httpEquiv="Content-Security-Policy"
content={`default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'`}
/>
)
}
export default async function RootLayout({ children }) {
return (
<html>
<Suspense>
<head>
<CSPMetatag />
</head>
<body>
<div id="csp-nonce-test">{children}</div>
</body>
</Suspense>
</html>
)
}
'use client'
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('./dynamic-component'), {
loading: () => <div id="loading">Loading...</div>,
})
export default function CSPNoncePage() {
return (
<div>
<h1 id="page-title">CSP Nonce Test Page</h1>
<DynamicComponent />
</div>
)
}
import { NextResponse } from 'next/server'
export function middleware(request) {
const response = NextResponse.next()
const nonce = 'test-nonce'
response.headers.set('x-nonce', nonce)
response.headers.set(
'Content-Security-Policy',
`default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'`
)
return response
}
export const config = {
matcher: '/:path*',
}
import { nextTestSetup } from 'e2e-utils'
describe('next/dynamic with CSP nonce', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should include nonce attribute on preload links generated by next/dynamic', async () => {
const $ = await next.render$('/')
// Check that preload links have the nonce attribute
const preloadLinks = $('link[rel="preload"]')
const dynamicPreloadLinks = preloadLinks.filter((_, element) => {
const $element = $(element)
const href = $element.attr('href')
return href && href.includes('_next/static/chunks/')
})
// There should be at least one preload link for dynamic chunks
expect(dynamicPreloadLinks.length).toBeGreaterThan(0)
dynamicPreloadLinks.each((_, element) => {
const $element = $(element)
const href = $element.attr('href')
// Only check preload links for dynamic chunks
if (href && href.includes('_next/static/chunks/')) {
expect($element.attr('nonce')).toBe('test-nonce')
}
})
})
it('should not generate CSP violations when using next/dynamic with nonce', async () => {
const browser = await next.browser('/')
// Wait for the dynamic component to load
await browser.waitForElementByCss('#dynamic-component-loaded')
// OPTIMIZATION: Get both text values concurrently
const [pageTitle, componentText] = await Promise.all([
browser.elementByCss('#page-title').then((el) => el.text()),
browser.elementByCss('#dynamic-component-loaded').then((el) => el.text()),
])
expect(pageTitle).toBe('CSP Nonce Test Page')
expect(componentText).toBe('Dynamic component loaded successfully')
// Check for CSP violations in Chrome (most expensive operation)
if (global.browserName === 'chrome') {
const logs = await browser.log()
const cspViolations = logs.filter(
(log) =>
log.source === 'security' &&
log.message.includes('Content Security Policy')
)
expect(cspViolations).toEqual([])
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
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