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