Unverified Commit 1a6a32cc authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Show security upgrade insights in DevTools (#99002)

Stacked on #99222.

### Why?

Developers running `next dev` with `agenticAutoUpgrade` enabled need a
browser reminder when their installed Next.js version is affected by a
security advisory.

### How?

Assess upgrades once during dev startup and share the result with the
CLI nudge. The existing HMR `SYNC` message carries the security advisory
to DevTools, which shows a Vulnerability Insight in the existing
Insights overlay with a copyable upgrade prompt.

The Insight applies to the `security`, `latest`, and `future` policies
when the assessment finds an affected version and a safe target. A
private test override previews the UI without a vulnerable fixture or
live advisory data.

### Screenshots

These show the badge and overlay layout. The current copied prompt runs
`next upgrade --ai=security` from the app directory.

**DevTools badge**

![DevTools
badge](https://github.com/user-attachments/assets/d6af6daf-0501-497c-aa3f-fe0f95351bc1)

| Light | Dark |
| --- | --- |
| ![Overlay in light
mode](https://github.com/user-attachments/assets/e7a7e194-0595-41e6-97b6-b54c05c14aa7)
| ![Overlay in dark
mode](https://github.com/user-attachments/assets/1b80b7d7-376b-4883-a8d1-3ee7354c92ab)
|

<!-- NEXT_JS_LLM -->

Closes NAR-939
parent c5b3a7a6
......@@ -34,6 +34,7 @@ import {
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
ACTION_VERSION_INFO,
ACTION_VULNERABILITY_INSIGHT,
INITIAL_OVERLAY_STATE,
} from '../../src/next-devtools/dev-overlay/shared'
......@@ -61,6 +62,12 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) {
case ACTION_ERROR_OVERLAY_TOGGLE: {
return { ...state, isErrorOverlayOpen: !state.isErrorOverlayOpen }
}
case ACTION_VULNERABILITY_INSIGHT: {
return {
...state,
hasVulnerabilityInsight: action.hasVulnerabilityInsight,
}
}
case ACTION_DEVTOOLS_POSITION: {
return { ...state, devToolsPosition: action.devToolsPosition }
}
......
......@@ -309,6 +309,10 @@ export function processMessage(
}
break
}
case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT: {
dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight)
break
}
case HMR_MESSAGE_SENT_TO_BROWSER.BUILT:
case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: {
dispatcher.buildingIndicatorHide()
......@@ -322,6 +326,9 @@ export function processMessage(
// Is undefined when it's a 'built' event
if ('versionInfo' in message)
dispatcher.onVersionInfo(message.versionInfo)
if ('hasVulnerabilityInsight' in message) {
dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight)
}
if ('debug' in message && message.debug)
dispatcher.onDebugInfo(message.debug)
if ('devIndicator' in message)
......
......@@ -290,6 +290,10 @@ function processMessage(message: HmrMessageSentToBrowser) {
}
break
}
case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT: {
dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight)
break
}
case HMR_MESSAGE_SENT_TO_BROWSER.BUILT:
case HMR_MESSAGE_SENT_TO_BROWSER.SYNC: {
dispatcher.buildingIndicatorHide()
......@@ -301,6 +305,9 @@ function processMessage(message: HmrMessageSentToBrowser) {
// Is undefined when it's a 'built' event
if ('versionInfo' in message)
dispatcher.onVersionInfo(message.versionInfo)
if ('hasVulnerabilityInsight' in message) {
dispatcher.onVulnerabilityInsight(message.hasVulnerabilityInsight)
}
if ('devIndicator' in message)
dispatcher.onDevIndicator(message.devIndicator)
if ('devToolsConfig' in message)
......
......@@ -121,6 +121,7 @@ export function pageBootstrap(assetPrefix: string) {
case HMR_MESSAGE_SENT_TO_BROWSER.TURBOPACK_CONNECTED:
case HMR_MESSAGE_SENT_TO_BROWSER.ISR_MANIFEST:
case HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG:
case HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT:
case HMR_MESSAGE_SENT_TO_BROWSER.REACT_DEBUG_CHUNK:
case HMR_MESSAGE_SENT_TO_BROWSER.REQUEST_CURRENT_ERROR_STATE:
case HMR_MESSAGE_SENT_TO_BROWSER.RUNTIME_ERRORS:
......
......@@ -252,7 +252,7 @@ async function nudgeUpgradeForAgent(
switch (reminder.kind) {
case 'security':
summary =
'Your version of Next.js is affected by a published security advisory.'
'Your version of Next.js is affected by a known security vulnerability.'
recommendation = 'We strongly recommend you upgrade Next.js.'
reference = reminder.reference
break
......
......@@ -31,6 +31,7 @@ import {
ACTION_INSTANT_NAVS_TOGGLE,
ACTION_REQUEST_INSIGHTS_SNAPSHOT,
ACTION_REQUEST_INSIGHTS_UPDATE,
ACTION_VULNERABILITY_INSIGHT,
} from './dev-overlay/shared'
import type { FlightRouterState } from '../shared/lib/app-router-types'
......@@ -67,6 +68,7 @@ export interface Dispatcher {
onBuildOk(): void
onBuildError(message: string): void
onVersionInfo(versionInfo: VersionInfo): void
onVulnerabilityInsight(hasVulnerabilityInsight: boolean): void
onDebugInfo(debugInfo: DebugInfo): void
onBeforeRefresh(): void
onRefresh(): void
......@@ -216,6 +218,11 @@ export const dispatcher: Dispatcher = {
dispatch({ type: ACTION_VERSION_INFO, versionInfo })
}
),
onVulnerabilityInsight: createQueuable(
(dispatch: Dispatch, hasVulnerabilityInsight: boolean) => {
dispatch({ type: ACTION_VULNERABILITY_INSIGHT, hasVulnerabilityInsight })
}
),
onCacheIndicator: createQueuable(
(dispatch: Dispatch, status: CacheIndicatorState) => {
dispatch({ type: ACTION_CACHE_INDICATOR, cacheIndicator: status })
......
......@@ -60,8 +60,8 @@ export function ErrorOverlay({
)
}
// No Runtime Errors.
if (!runtimeErrors.length) {
// No runtime errors or upgrade insight to display.
if (!runtimeErrors.length && !state.hasVulnerabilityInsight) {
return null
}
......@@ -83,6 +83,7 @@ export function ErrorOverlay({
debugInfo={state.debugInfo}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
runtimeErrors={runtimeErrors}
hasVulnerabilityInsight={state.hasVulnerabilityInsight}
onClose={() => {
dispatch({ type: ACTION_ERROR_OVERLAY_CLOSE })
}}
......
import * as React from 'react'
import type { ErrorBaseProps } from '../errors/error-overlay/error-overlay'
import type { ErrorOverlayTabBarRenderer } from '../errors/error-overlay-pagination/error-overlay-pagination'
import { ErrorOverlayNav } from '../errors/error-overlay-nav/error-overlay-nav'
import { ErrorOverlayOverlay } from '../errors/overlay/overlay'
import { ErrorOverlayDialog } from '../errors/dialog/dialog'
import { ErrorOverlayDialogHeader } from '../errors/dialog/header'
import { ErrorOverlayDialogBody } from '../errors/dialog/body'
import { OverlayBackdrop } from '../overlay'
import { DialogContent } from '../dialog'
import { Resizer } from '../resizer'
import { useFocusTrap } from '../errors/dev-tools-indicator/utils'
import { CopyButton } from '../copy-button'
import { CodeFrameShell } from '../code-frame/code-frame-shell'
import { css } from '../../utils/css'
export function VulnerabilityInsight({
renderTabBar,
canGoPrevious,
canGoNext,
onPrevious,
onNext,
onClose,
rendered,
transitionDurationMs,
versionInfo,
}: ErrorBaseProps & {
renderTabBar: ErrorOverlayTabBarRenderer | undefined
canGoPrevious: boolean
canGoNext: boolean
onPrevious: (() => void) | undefined
onNext: (() => void) | undefined
onClose: (() => void) | undefined
}) {
const prompt = 'Run `next upgrade --ai=security` and follow its instructions.'
const animationProps = {
'data-rendered': rendered,
style: {
'--transition-duration': `${transitionDurationMs}ms`,
} as React.CSSProperties,
}
const [animating, setAnimating] = React.useState(
Boolean(transitionDurationMs)
)
const dialogRef = React.useRef<HTMLDivElement | null>(null)
useFocusTrap(dialogRef, null, rendered)
function onTransitionEnd({ propertyName, target }: React.TransitionEvent) {
if (propertyName === 'scale' && target === dialogRef.current) {
setAnimating(false)
}
}
return (
<ErrorOverlayOverlay {...animationProps}>
<OverlayBackdrop fixed={false} />
<div
data-nextjs-dialog-root
onTransitionEnd={onTransitionEnd}
ref={dialogRef}
{...animationProps}
>
<ErrorOverlayNav
versionInfo={versionInfo}
renderTabBar={renderTabBar}
canGoPrevious={canGoPrevious}
canGoNext={canGoNext}
onPrevious={onPrevious}
onNext={onNext}
/>
<ErrorOverlayDialog onClose={onClose}>
<Resizer measure={!animating} data-nextjs-dialog-sizer>
<DialogContent>
<ErrorOverlayDialogHeader>
<div data-nextjs-vulnerability-insight>
<span
id="nextjs__container_errors_label"
className="nextjs__container_errors_label nextjs__container_errors_label_instant"
data-nextjs-vulnerability-label
>
Vulnerability Insight
</span>
<h2 id="nextjs__container_errors_desc">
Upgrade Next.js to a safe version.
</h2>
<p>
Next.js {versionInfo.installed} is affected by a known
security vulnerability. We strongly recommend upgrading.
</p>
</div>
</ErrorOverlayDialogHeader>
<ErrorOverlayDialogBody>
<div data-nextjs-vulnerability-action>
<p>
Copy the prompt and paste it into your coding agent to
upgrade this app.
</p>
<CodeFrameShell
header={
<>
<span data-text>Upgrade prompt</span>
<CopyButton
content={prompt}
actionLabel="Copy upgrade prompt"
successLabel="Copied"
data-nextjs-vulnerability-copy
/>
</>
}
>
<code data-nextjs-vulnerability-prompt>{prompt}</code>
</CodeFrameShell>
</div>
</ErrorOverlayDialogBody>
</DialogContent>
</Resizer>
</ErrorOverlayDialog>
</div>
<style>{styles}</style>
</ErrorOverlayOverlay>
)
}
const styles = css`
[data-nextjs-dialog-header]:has([data-nextjs-vulnerability-insight]) {
padding-bottom: 0;
}
[data-nextjs-vulnerability-insight] h2 {
margin: 16px 0 8px;
font-size: var(--size-20);
font-weight: 500;
color: var(--color-gray-1000);
}
[data-nextjs-vulnerability-insight] p,
[data-nextjs-vulnerability-action] > p {
margin: 8px 0;
font-size: var(--size-14);
line-height: var(--size-20);
color: var(--color-gray-900);
}
[data-nextjs-vulnerability-action] {
display: flex;
flex-direction: column;
gap: 8px;
}
[data-nextjs-vulnerability-action] .code-frame-lines {
min-width: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
[data-nextjs-vulnerability-copy] {
display: inline-flex;
align-items: center;
justify-content: center;
margin-left: auto;
width: var(--size-24);
height: var(--size-24);
padding: 4px;
border: none;
border-radius: var(--rounded-md-2);
background: transparent;
color: var(--color-gray-1000);
cursor: pointer;
}
[data-nextjs-vulnerability-copy]:hover {
background: var(--color-gray-alpha-100);
}
[data-nextjs-vulnerability-copy]:focus-visible {
outline: var(--focus-ring);
outline-offset: 2px;
}
[data-nextjs-vulnerability-copy][aria-disabled='true'] {
opacity: 0.5;
}
`
......@@ -6,6 +6,7 @@ import React, {
useRef,
useState,
} from 'react'
import { VulnerabilityInsight } from '../components/vulnerability-insight/vulnerability-insight'
import type { DebugInfo } from '../../shared/types'
import { Overlay, OverlayBackdrop } from '../components/overlay'
import { RuntimeError } from './runtime-error'
......@@ -51,6 +52,7 @@ interface ErrorsProps extends ErrorBaseProps {
runtimeErrors: ReadyRuntimeError[]
debugInfo: DebugInfo
onClose: () => void
hasVulnerabilityInsight: boolean
}
function matchLinkType(text: string): string | null {
......@@ -632,6 +634,7 @@ export function Errors({
runtimeErrors,
debugInfo,
onClose,
hasVulnerabilityInsight,
...props
}: ErrorsProps) {
const dialogResizerRef = useRef<HTMLDivElement | null>(null)
......@@ -649,6 +652,8 @@ export function Errors({
return { normalErrors: normal, instantErrors: instant }
}, [runtimeErrors])
const insightCount = instantErrors.length + (hasVulnerabilityInsight ? 1 : 0)
const [activeTab, setActiveTab] = useState<ErrorTab>(() =>
normalErrors.length > 0 ? 'errors' : 'instant'
)
......@@ -661,7 +666,7 @@ export function Errors({
? normalErrors.length > 0
? 'errors'
: 'instant'
: instantErrors.length > 0
: insightCount > 0
? 'instant'
: 'errors'
const activeErrors =
......@@ -672,7 +677,7 @@ export function Errors({
)
const instantActiveIdx = Math.max(
0,
Math.min(activeIndices.instant, Math.max(0, instantErrors.length - 1))
Math.min(activeIndices.instant, Math.max(0, insightCount - 1))
)
const activeIdxForTab =
effectiveActiveTab === 'instant' ? instantActiveIdx : errorActiveIdx
......@@ -707,29 +712,11 @@ export function Errors({
[activeError, errorType, props.versionInfo]
)
if (isLoading) {
// TODO: better loading state
return (
<Overlay>
<OverlayBackdrop />
</Overlay>
)
}
if (!activeError) {
return null
}
const error = activeError.error
const isServerError = ['server', 'edge-server'].includes(
getErrorSource(error) || ''
)
// Show the tab bar only when at least one Insight is present. When the only
// bucket with content is Issues, the red pill already conveys the count and a
// single-tab bar would be redundant. When Insights exist (alone or alongside
// Issues), the bar is shown so the user can switch between buckets.
const showTabBar = instantErrors.length > 0
const showTabBar = insightCount > 0
const renderTabBar = showTabBar
? ({
previousButton,
......@@ -744,7 +731,7 @@ export function Errors({
})
}}
errorCount={normalErrors.length}
instantCount={instantErrors.length}
instantCount={insightCount}
errorActiveIdx={errorActiveIdx}
instantActiveIdx={instantActiveIdx}
previousButton={previousButton}
......@@ -761,8 +748,8 @@ export function Errors({
: activeIdx > 0
const canGoNext = showTabBar
? effectiveActiveTab === 'errors'
? errorActiveIdx < normalErrors.length - 1 || instantErrors.length > 0
: instantActiveIdx < instantErrors.length - 1
? errorActiveIdx < normalErrors.length - 1 || insightCount > 0
: instantActiveIdx < insightCount - 1
: activeIdx < activeErrors.length - 1
const handlePrevious = showTabBar
......@@ -800,7 +787,7 @@ export function Errors({
return
}
if (instantErrors.length > 0) {
if (insightCount > 0) {
setActiveTab('instant')
setActiveIndices((previous) => ({
...previous,
......@@ -810,13 +797,52 @@ export function Errors({
return
}
if (instantActiveIdx < instantErrors.length - 1) {
if (instantActiveIdx < insightCount - 1) {
setActiveIndex(instantActiveIdx + 1)
}
})
}
: undefined
if (
hasVulnerabilityInsight &&
effectiveActiveTab === 'instant' &&
instantActiveIdx === instantErrors.length
) {
const hasServerError = runtimeErrors.some(({ error }) =>
['server', 'edge-server'].includes(getErrorSource(error) || '')
)
return (
<VulnerabilityInsight
{...props}
renderTabBar={renderTabBar}
canGoPrevious={canGoPrevious}
canGoNext={canGoNext}
onPrevious={handlePrevious}
onNext={handleNext}
onClose={hasServerError ? undefined : onClose}
/>
)
}
if (isLoading) {
// TODO: better loading state
return (
<Overlay>
<OverlayBackdrop />
</Overlay>
)
}
if (!activeError) {
return null
}
const error = activeError.error
const isServerError = ['server', 'edge-server'].includes(
getErrorSource(error) || ''
)
let errorMessage: React.ReactNode
let maybeNotes: React.ReactNode = null
let maybeDiff: React.ReactNode = null
......
......@@ -70,9 +70,13 @@ export function DevOverlay() {
<RenderErrorContext
value={{
runtimeErrors,
totalErrorCount,
totalErrorCount:
totalErrorCount +
(state.hasVulnerabilityInsight ? 1 : 0),
normalErrorCount,
instantErrorCount,
instantErrorCount:
instantErrorCount +
(state.hasVulnerabilityInsight ? 1 : 0),
}}
>
<PanelRouterContext
......
......@@ -95,6 +95,7 @@ export interface OverlayState {
showInternal: boolean
verbose: boolean
}>
readonly hasVulnerabilityInsight: boolean
}
type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent>
......@@ -131,6 +132,7 @@ export const ACTION_INSTANT_NAVS_RESET = 'instant-navs-reset'
export const ACTION_INSTANT_ERRORS_CLEAR = 'instant-errors-clear'
export const ACTION_REQUEST_INSIGHTS_SNAPSHOT = 'request-insights-snapshot'
export const ACTION_REQUEST_INSIGHTS_UPDATE = 'request-insights-update'
export const ACTION_VULNERABILITY_INSIGHT = 'vulnerability-insight'
export function updateRequestInsights(
currentRequests: readonly RequestInsight[],
......@@ -284,6 +286,11 @@ interface RequestInsightsUpdateAction {
insight: RequestInsight
}
interface VulnerabilityInsightAction {
type: typeof ACTION_VULNERABILITY_INSIGHT
hasVulnerabilityInsight: boolean
}
export type DispatcherEvent =
| BuildOkAction
| BuildErrorAction
......@@ -314,6 +321,7 @@ export type DispatcherEvent =
| InstantErrorsClearAction
| RequestInsightsSnapshotAction
| RequestInsightsUpdateAction
| VulnerabilityInsightAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8
......@@ -401,6 +409,7 @@ export const INITIAL_OVERLAY_STATE: Omit<
instantNavs: hasInstantNavsCookie,
requestInsights: [],
requestInsightsConfig: { showInternal: false, verbose: false },
hasVulnerabilityInsight: false,
}
function getInitialState(
......@@ -701,6 +710,12 @@ export function useErrorOverlayReducer(
case ACTION_REQUEST_INSIGHTS_SNAPSHOT: {
return { ...state, requestInsights: action.snapshot.requests }
}
case ACTION_VULNERABILITY_INSIGHT: {
return {
...state,
hasVulnerabilityInsight: action.hasVulnerabilityInsight,
}
}
case ACTION_REQUEST_INSIGHTS_UPDATE: {
return {
...state,
......
......@@ -90,14 +90,25 @@ export class WebpackHotMiddleware {
private middlewareLatestStats: { ts: number; stats: webpack.Stats } | null =
null
private serverLatestStats: { ts: number; stats: webpack.Stats } | null = null
private hasVulnerabilityInsight = false
constructor(
compilers: webpack.Compiler[],
private versionInfo: VersionInfo,
private devtoolsFrontendUrl: string | undefined,
private config: NextConfigComplete,
private devToolsConfig: DevToolsConfig
private devToolsConfig: DevToolsConfig,
hasVulnerabilityInsight: Promise<boolean>
) {
hasVulnerabilityInsight.then((enabled) => {
if (enabled) {
this.hasVulnerabilityInsight = true
this.publish({
type: HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT,
hasVulnerabilityInsight: true,
})
}
})
compilers[0].hooks.invalid.tap(
'webpack-hot-middleware',
this.onClientInvalid
......@@ -220,6 +231,7 @@ export class WebpackHotMiddleware {
...(middlewareStats.warnings || []),
],
versionInfo: this.versionInfo,
hasVulnerabilityInsight: this.hasVulnerabilityInsight,
debug: {
devtoolsFrontendUrl: this.devtoolsFrontendUrl,
},
......
......@@ -891,6 +891,22 @@ export async function createHotReloaderTurbopack(
client.send(data)
}
let hasVulnerabilityInsight = false
opts.hasVulnerabilityInsight.then((enabled) => {
if (enabled) {
hasVulnerabilityInsight = true
for (const client of [
...clientsWithoutHtmlRequestId,
...clientsByHtmlRequestId.values(),
]) {
sendToClient(client, {
type: HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT,
hasVulnerabilityInsight: true,
})
}
}
})
let updateInProgress = false
let pendingServerComponentChanges = false
......@@ -1757,6 +1773,7 @@ export async function createHotReloaderTurbopack(
warnings: [],
hash: '',
versionInfo,
hasVulnerabilityInsight,
debug: {
devtoolsFrontendUrl,
},
......
......@@ -41,6 +41,7 @@ export const enum HMR_MESSAGE_SENT_TO_BROWSER {
CACHE_INDICATOR = 'cacheIndicator',
DEV_INDICATOR = 'devIndicator',
DEVTOOLS_CONFIG = 'devtoolsConfig',
VULNERABILITY_INSIGHT = 'vulnerabilityInsight',
REQUEST_CURRENT_ERROR_STATE = 'requestCurrentErrorState',
RUNTIME_ERRORS = 'runtimeErrors',
REQUEST_PAGE_METADATA = 'requestPageMetadata',
......@@ -88,6 +89,7 @@ export interface SyncMessage {
errors: ReadonlyArray<CompilationError>
warnings: ReadonlyArray<CompilationError>
versionInfo: VersionInfo
hasVulnerabilityInsight: boolean
updatedModules?: ReadonlyArray<string>
debug?: DebugInfo
devIndicator: DevIndicatorServerState
......@@ -264,6 +266,11 @@ export interface RequestInsightsUpdateMessage {
insight: RequestInsight
}
export interface VulnerabilityInsightMessage {
type: HMR_MESSAGE_SENT_TO_BROWSER.VULNERABILITY_INSIGHT
hasVulnerabilityInsight: boolean
}
export type HmrMessageSentToBrowser =
| TurbopackMessage
| TurbopackConnectedMessage
......@@ -289,6 +296,7 @@ export type HmrMessageSentToBrowser =
| RequestPageMetadataMessage
| CacheIndicatorMessage
| RequestInsightsUpdateMessage
| VulnerabilityInsightMessage
export type BinaryHmrMessageSentToBrowser = Extract<
HmrMessageSentToBrowser,
......
......@@ -266,6 +266,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
private reloadAfterInvalidation: boolean = false
private isSrcDir: boolean
private cacheStatusesByRequestId = new Map<string, ServerCacheStatus>()
private hasVulnerabilityInsight: Promise<boolean>
public serverStats: webpack.Stats | null
public edgeServerStats: webpack.Stats | null
......@@ -290,6 +291,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
resetFetch,
lockfile,
onDevServerCleanup,
hasVulnerabilityInsight,
}: {
config: NextConfigComplete
isSrcDir: boolean
......@@ -304,6 +306,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
resetFetch: () => void
lockfile: Lockfile | undefined
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined
hasVulnerabilityInsight: Promise<boolean>
}
) {
this.hasAppRouterEntrypoints = false
......@@ -323,6 +326,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
this.telemetry = telemetry
this.resetFetch = resetFetch
this.lockfile = lockfile
this.hasVulnerabilityInsight = hasVulnerabilityInsight
this.config = config
this.previewProps = previewProps
......@@ -1648,7 +1652,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
this.versionInfo,
this.devtoolsFrontendUrl,
this.config,
initialDevToolsConfig
initialDevToolsConfig,
this.hasVulnerabilityInsight
)
let booted = false
......
......@@ -68,6 +68,7 @@ import {
isChromeDevtoolsWorkspaceUrl,
} from './chrome-devtools-workspace'
import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'
import { isCI } from '../ci-info'
import {
getRequestInsightsSnapshot,
isRequestInsightsEnabled,
......@@ -191,6 +192,7 @@ export async function initialize(opts: {
| undefined = undefined
let originalFetch = globalThis.fetch
let hasVulnerabilityInsight: Promise<boolean> = Promise.resolve(false)
if (opts.dev) {
const { Telemetry } =
......@@ -223,10 +225,34 @@ export async function initialize(opts: {
developmentConfig.experimental.agenticAutoUpgrade === 'security' ||
developmentConfig.experimental.agenticAutoUpgrade === 'latest' ||
developmentConfig.experimental.agenticAutoUpgrade === 'future' ||
process.env.__NEXT_AGENTIC_AUTO_UPGRADE
process.env.__NEXT_AGENTIC_AUTO_UPGRADE ||
process.env.__NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING === '1'
) {
const { nudgeUpgrade, getUpgradeContext } =
const { nudgeUpgrade, getUpgradeContext, assessUpgrade } =
require('../../lib/upgrade/nudge') as typeof import('../../lib/upgrade/nudge')
const upgradeContext = getUpgradeContext(developmentConfig)
const installedVersion = process.env.__NEXT_VERSION || 'unknown'
const policy = upgradeContext.experimental.agenticAutoUpgrade
const forced = process.env.__NEXT_AGENTIC_AUTO_UPGRADE === policy
const forceDevToolsForTesting =
process.env.__NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING === '1'
const assessment: ReturnType<typeof assessUpgrade> =
isCI || forceDevToolsForTesting
? Promise.resolve(null)
: assessUpgrade(
opts.dir,
upgradeContext,
installedVersion,
null,
forced
)
hasVulnerabilityInsight = assessment.then(
(result) => result?.kind === 'security' || forceDevToolsForTesting,
(error) => {
Log.warn(`Could not check the DevTools security insight: ${error}`)
return false
}
)
if (process.env.NEXT_PRIVATE_UPGRADE_PROMPT === '1' && process.send) {
// TODO: Do not block dev startup while prompting for an upgrade.
// Preserve all logs for display after the prompt and stop dev before Update.
......@@ -242,7 +268,7 @@ export async function initialize(opts: {
}
process.on('message', resume)
process.send!({
nextUpgradeContext: getUpgradeContext(developmentConfig),
nextUpgradeContext: upgradeContext,
})
})
} else {
......@@ -298,6 +324,7 @@ export async function initialize(opts: {
onDevServerCleanup: opts.onDevServerCleanup,
resetFetch,
serverFastRefresh: effectiveServerFastRefresh,
hasVulnerabilityInsight,
})
)
......
......@@ -141,6 +141,7 @@ export type SetupOpts = {
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined
resetFetch: () => void
serverFastRefresh?: boolean
hasVulnerabilityInsight: Promise<boolean>
}
export interface DevRoutesManifest {
......@@ -294,6 +295,7 @@ async function startWatcher(
resetFetch,
lockfile,
onDevServerCleanup: opts.onDevServerCleanup,
hasVulnerabilityInsight: opts.hasVulnerabilityInsight,
})
})()
......
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
import { nextTestSetup, type Playwright } from 'e2e-utils'
import { retry } from 'next-test-utils'
function portalText(
browser: Playwright,
selector: string
): Promise<string | null> {
return browser.eval(`document.querySelector('nextjs-portal')?.shadowRoot
?.querySelector(${JSON.stringify(selector)})?.textContent?.trim() ?? null`)
}
function clickInPortal(browser: Playwright, selector: string): Promise<void> {
return browser.eval(`document.querySelector('nextjs-portal')?.shadowRoot
?.querySelector(${JSON.stringify(selector)})?.click()`)
}
describe('vulnerability insight', () => {
const { next } = nextTestSetup({
files: __dirname,
env: { __NEXT_AGENT_UPGRADE_FORCE_DEVTOOLS_FOR_TESTING: '1' },
})
it('shows an insight, opens it, and copies the upgrade prompt', async () => {
const browser = await next.browser('/', {
beforePageLoad: async (page) => {
await page
.context()
.grantPermissions(['clipboard-read', 'clipboard-write'])
},
})
await retry(async () => {
expect(await portalText(browser, '[data-next-badge]')).toMatch(
/1\s*Insight/
)
})
await clickInPortal(browser, '[data-issues-open]')
await retry(async () => {
expect(
await portalText(browser, '[data-nextjs-vulnerability-label]')
).toBe('Vulnerability Insight')
})
const displayedPrompt = await portalText(
browser,
'[data-nextjs-vulnerability-prompt]'
)
await clickInPortal(browser, '[aria-label="Copy upgrade prompt"]')
let copiedPrompt = ''
await retry(async () => {
copiedPrompt = await browser.eval(() => navigator.clipboard.readText())
expect(copiedPrompt).toBe(displayedPrompt)
})
expect(copiedPrompt).toMatchInlineSnapshot(
`"Run \`next upgrade --ai=security\` and follow its instructions."`
)
})
})
......@@ -162,7 +162,7 @@ describe('security upgrade nudge', () => {
name: 'SecurityFatalError',
exitCode: 1,
message: expect.stringMatching(
/affected by a published security advisory[\s\S]*\*\*We strongly recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*If the app is in a Git repository, use a separate Git worktree unless they request otherwise\.[\s\S]*If the app is not in a Git repository, upgrade it in place\. Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```/
/affected by a known security vulnerability[\s\S]*\*\*We strongly recommend you upgrade Next\.js\.\*\*[\s\S]*reminder you configured is not missed\. Retry the same command to continue the original task\.[\s\S]*include this upgrade recommendation even if the retry succeeds\.[\s\S]*If the app is in a Git repository, use a separate Git worktree unless they request otherwise\.[\s\S]*If the app is not in a Git repository, upgrade it in place\. Run this command from this app's directory:[\s\S]*```\nnext upgrade --ai=(?:security|latest|future)\n```/
),
})
expect(warn).not.toHaveBeenCalled()
......@@ -185,7 +185,7 @@ describe('security upgrade nudge', () => {
name: 'SecurityFatalError',
exitCode: 1,
message: expect.stringMatching(
/affected by a published security advisory[\s\S]*registry\.npmjs\.org/
/affected by a known security vulnerability[\s\S]*registry\.npmjs\.org/
),
})
expect(warn).not.toHaveBeenCalled()
......
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