Unverified Commit 56ea9e9c authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Add SRI support for Node.js Runtime (#73891)

> [!NOTE]  
> This PR is best reviewed with hidden whitespace changes.

Support for setting [Subresource
Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)
attributes on app router scripts was added in
https://github.com/vercel/next.js/pull/39729. But this only covered
pages using the Edge Runtime.

With this PR, we're adding support for app pages using the Node.js
Runtime. The only change that's needed for that, and which was probably
just an oversight in the original PR, is reading the generated manifest
file in `loadComponents`.

In a follow-up we should also add support for adding the `integrity`
attribute to client component chunks that are injected into the head
during server-side rendering, but that needs a change in React first.

fixes #66901
parent 98dc3855
......@@ -1864,6 +1864,7 @@ export default async function build(
const { configFileName, publicRuntimeConfig, serverRuntimeConfig } =
config
const runtimeEnvConfig = { publicRuntimeConfig, serverRuntimeConfig }
const sriEnabled = Boolean(config.experimental.sri?.algorithm)
const nonStaticErrorPageSpan = staticCheckSpan.traceChild(
'check-static-error-page'
......@@ -1877,6 +1878,7 @@ export default async function build(
distDir,
runtimeEnvConfig,
checkingApp: false,
sriEnabled,
}))
)
......@@ -1898,6 +1900,7 @@ export default async function build(
pprConfig: config.experimental.ppr,
cacheLifeProfiles: config.experimental.cacheLife,
buildId,
sriEnabled,
})
)
......@@ -1909,6 +1912,7 @@ export default async function build(
distDir,
runtimeEnvConfig,
checkingApp: true,
sriEnabled,
}
)
......@@ -1916,6 +1920,7 @@ export default async function build(
page: appPageToCheck,
distDir,
runtimeEnvConfig,
sriEnabled,
})
// eslint-disable-next-line @typescript-eslint/no-shadow
......@@ -2125,6 +2130,7 @@ export default async function build(
pprConfig: config.experimental.ppr,
cacheLifeProfiles: config.experimental.cacheLife,
buildId,
sriEnabled,
})
}
)
......
......@@ -972,6 +972,7 @@ export async function isPageStatic({
cacheLifeProfiles,
pprConfig,
buildId,
sriEnabled,
}: {
dir: string
page: string
......@@ -998,6 +999,7 @@ export async function isPageStatic({
nextConfigOutput: 'standalone' | 'export' | undefined
pprConfig: ExperimentalPPRConfig | undefined
buildId: string
sriEnabled: boolean
}): Promise<PageIsStaticResult> {
await createIncrementalCache({
cacheHandler,
......@@ -1069,6 +1071,7 @@ export async function isPageStatic({
page: originalAppPath || page,
isAppPath: pageType === 'app',
isDev: false,
sriEnabled,
})
}
const Comp = componentsResult.Component as NextComponentType | undefined
......@@ -1316,11 +1319,13 @@ export async function hasCustomGetInitialProps({
distDir,
runtimeEnvConfig,
checkingApp,
sriEnabled,
}: {
page: string
distDir: string
runtimeEnvConfig: any
checkingApp: boolean
sriEnabled: boolean
}): Promise<boolean> {
require('../shared/lib/runtime-config.external').setConfig(runtimeEnvConfig)
......@@ -1329,6 +1334,7 @@ export async function hasCustomGetInitialProps({
page: page,
isAppPath: false,
isDev: false,
sriEnabled,
})
let mod = components.ComponentMod
......@@ -1345,10 +1351,12 @@ export async function getDefinedNamedExports({
page,
distDir,
runtimeEnvConfig,
sriEnabled,
}: {
page: string
distDir: string
runtimeEnvConfig: any
sriEnabled: boolean
}): Promise<ReadonlyArray<string>> {
require('../shared/lib/runtime-config.external').setConfig(runtimeEnvConfig)
const components = await loadComponents({
......@@ -1356,6 +1364,7 @@ export async function getDefinedNamedExports({
page: page,
isAppPath: false,
isDev: false,
sriEnabled,
})
return Object.keys(components.ComponentMod).filter((key) => {
......
......@@ -73,6 +73,7 @@ export interface ExportPageInput {
debugOutput?: boolean
nextConfigOutput?: NextConfigComplete['output']
enableExperimentalReact?: boolean
sriEnabled: boolean
}
export type ExportedPageFile = {
......
......@@ -81,6 +81,7 @@ async function exportPageImpl(
enableExperimentalReact,
ampValidatorPath,
trailingSlash,
sriEnabled,
} = input
if (enableExperimentalReact) {
......@@ -234,6 +235,7 @@ async function exportPageImpl(
page,
isAppPath: isAppDir,
isDev: false,
sriEnabled,
})
// Handle App Routes.
......@@ -396,6 +398,7 @@ export async function exportPages(
httpAgentOptions: nextConfig.httpAgentOptions,
debugOutput: options.debugOutput,
enableExperimentalReact: needsExperimentalReact(nextConfig),
sriEnabled: Boolean(nextConfig.experimental.sri?.algorithm),
}),
// If exporting the page takes longer than the timeout, reject the promise.
new Promise((_, reject) => {
......
......@@ -775,7 +775,8 @@ export default class DevServer extends Server {
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
nextConfigOutput: this.nextConfig.output,
buildId: this.renderOpts.buildId,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),
sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),
})
return pathsResult
} finally {
......
......@@ -49,6 +49,7 @@ export async function loadStaticPaths({
nextConfigOutput,
buildId,
authInterrupts,
sriEnabled,
}: {
dir: string
distDir: string
......@@ -70,6 +71,7 @@ export async function loadStaticPaths({
nextConfigOutput: 'standalone' | 'export' | undefined
buildId: string
authInterrupts: boolean
sriEnabled: boolean
}): Promise<Partial<StaticPathsResult>> {
// update work memory runtime-config
require('../../shared/lib/runtime-config.external').setConfig(config)
......@@ -83,6 +85,7 @@ export async function loadStaticPaths({
page: page || pathname,
isAppPath,
isDev: true,
sriEnabled,
})
if (isAppPath) {
......
......@@ -20,6 +20,7 @@ import {
CLIENT_REFERENCE_MANIFEST,
SERVER_REFERENCE_MANIFEST,
DYNAMIC_CSS_MANIFEST,
SUBRESOURCE_INTEGRITY_MANIFEST,
} from '../shared/lib/constants'
import { join } from 'path'
import { requirePage } from './require'
......@@ -136,11 +137,13 @@ async function loadComponentsImpl<N = any>({
page,
isAppPath,
isDev,
sriEnabled,
}: {
distDir: string
page: string
isAppPath: boolean
isDev: boolean
sriEnabled: boolean
}): Promise<LoadComponentsReturnType<N>> {
let DocumentMod = {}
let AppMod = {}
......@@ -167,6 +170,7 @@ async function loadComponentsImpl<N = any>({
dynamicCssManifest,
clientReferenceManifest,
serverActionsManifest,
subresourceIntegrityManifest,
] = await Promise.all([
loadManifestWithRetries<BuildManifest>(
join(distDir, BUILD_MANIFEST),
......@@ -201,6 +205,11 @@ async function loadComponentsImpl<N = any>({
manifestLoadAttempts
).catch(() => null)
: null,
sriEnabled
? loadManifestWithRetries<DeepReadonly<Record<string, string>>>(
join(distDir, 'server', SUBRESOURCE_INTEGRITY_MANIFEST + '.json')
).catch(() => undefined)
: undefined,
])
// Before requiring the actual page module, we have to set the reference
......@@ -231,6 +240,7 @@ async function loadComponentsImpl<N = any>({
Document,
Component,
buildManifest,
subresourceIntegrityManifest,
reactLoadableManifest,
dynamicCssManifest,
pageConfig: ComponentMod.config || {},
......
......@@ -179,12 +179,14 @@ export default class NextNodeServer extends BaseServer<
protected cleanupListeners = new AsyncCallbackSet()
protected internalWaitUntil: WaitUntil | undefined
private isDev: boolean
private sriEnabled: boolean
constructor(options: Options) {
// Initialize super class
super(options)
this.isDev = options.dev ?? false
this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm)
/**
* This sets environment variable to be used at the time of SSR by head.tsx.
......@@ -218,12 +220,14 @@ export default class NextNodeServer extends BaseServer<
page: '/_document',
isAppPath: false,
isDev: this.isDev,
sriEnabled: this.sriEnabled,
}).catch(() => {})
loadComponents({
distDir: this.distDir,
page: '/_app',
isAppPath: false,
isDev: this.isDev,
sriEnabled: this.sriEnabled,
}).catch(() => {})
}
......@@ -285,6 +289,7 @@ export default class NextNodeServer extends BaseServer<
page,
isAppPath: false,
isDev: this.isDev,
sriEnabled: this.sriEnabled,
}).catch(() => {})
}
......@@ -294,6 +299,7 @@ export default class NextNodeServer extends BaseServer<
page,
isAppPath: true,
isDev: this.isDev,
sriEnabled: this.sriEnabled,
})
.then(async ({ ComponentMod }) => {
// we need to ensure fetch is patched before we require the page,
......@@ -805,6 +811,7 @@ export default class NextNodeServer extends BaseServer<
page: pagePath,
isAppPath,
isDev: this.isDev,
sriEnabled: this.sriEnabled,
})
if (
......
'use client'
import styles from './client-comp.module.css'
import { useEffect, useState } from 'react'
export default function ClientComp() {
const [state, setState] = useState({})
useEffect(() => {
setState({ test: 'HELLOOOO' })
}, [])
return (
<>
<p className={styles.client}>Hello</p>
{state.test}
</>
)
}
import './style.css'
import './global.css'
export default function DashboardLayout(props) {
return (
<div className="dangerous-text">
<h1 className="green">Dashboard</h1>
{props.children}
</div>
)
}
export const preferredRegion = 'iad1'
import ClientComp from './client-comp-client'
export default function DashboardPage(props) {
if (typeof WebSocket === 'undefined') {
throw new Error('missing WebSocket constructor!!')
}
return (
<>
<p id="from-dashboard" className="p">
hello from app/dashboard
</p>
<p className="bold">BOLD</p>
<p className="green">this is green</p>
<ClientComp />
</>
)
}
export const runtime = 'edge'
export { default } from '../node/page'
export const runtime = 'edge'
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