Unverified Commit c5b3a7a6 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Use focused npm advisories and nudge only for ready upgrades (#99222)

Stacked on #99230.

### Why?

Simplify the advisory check by querying only the versions we need
instead of sending a bulk audit request.

### How?

Query npm advisories for the installed version and relevant upgrade
candidates. Remove the GHSA lookup and fallback. Only show a nudge when
the assessment finds a ready target; otherwise, skip it.

<!-- NEXT_JS_LLM -->

Closes NAR-948
parent 0423222b
......@@ -11,9 +11,18 @@ const { target } = JSON.parse(
globalThis.fetch = async (input, init) => {
const url = String(input)
let value
let versions
if (url.startsWith('https://api.github.com/advisories?')) {
value = []
if (url === 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk') {
versions = JSON.parse(init.body).next
if (
!Array.isArray(versions) ||
versions.length === 0 ||
versions.some((version) => typeof version !== 'string')
) {
throw new Error('Expected Next.js advisory versions')
}
value = {}
} else if (url === 'https://registry.npmjs.org/next/latest') {
value = {
version: target,
......@@ -25,7 +34,7 @@ globalThis.fetch = async (input, init) => {
appendFileSync(
join(tools, 'assessment.jsonl'),
JSON.stringify({ url, value }) + '\n'
JSON.stringify({ url, versions, value }) + '\n'
)
return Response.json(value)
}
......@@ -10,22 +10,31 @@ const { target } = JSON.parse(
globalThis.fetch = async (input, init) => {
const url = String(input)
let value
let versions
if (url.startsWith('https://api.github.com/advisories?')) {
return Response.json([])
}
if (url !== 'https://registry.npmjs.org/next/latest') {
if (url === 'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk') {
versions = JSON.parse(init.body).next
if (
!Array.isArray(versions) ||
versions.length === 0 ||
versions.some((version) => typeof version !== 'string')
) {
throw new Error('Expected Next.js advisory versions')
}
value = {}
} else if (url === 'https://registry.npmjs.org/next/latest') {
value = {
version: target,
engines: { node: '>=20.9.0' },
}
} else {
return realFetch(input, init)
}
const value = {
version: target,
engines: { node: '>=20.9.0' },
}
appendFileSync(
join(tools, 'assessment.jsonl'),
JSON.stringify({ url, value }) + '\n'
JSON.stringify({ url, versions, value }) + '\n'
)
return Response.json(value)
}
......@@ -10,7 +10,7 @@ import type { NextConfigComplete } from '../../server/config-shared'
import semver from 'next/dist/compiled/semver'
import type { UpgradeAction } from './prompt'
import { getAgentName } from '../../telemetry/agent-name'
import { futureDefaults, getPendingFutureDefaults } from './future-defaults'
import { getPendingFutureDefaults } from './future-defaults'
import { isCI } from '../../server/ci-info'
type NudgeOptions = {
......@@ -125,8 +125,7 @@ type UpgradeReminder = {
| {
kind: 'security'
reference: string | null
targetVersion: string | null
unavailableReason: string | null
targetVersion: string
}
| { kind: 'latest'; latestVersion: string | null; names: string[] }
| { kind: 'future'; targetVersion: string; names: string[] }
......@@ -186,24 +185,21 @@ export async function assessUpgrade(
return null
}
const { upgrade } = assessment
if (upgrade.status !== 'ready') {
// TODO: Record affected and upgrade.status in telemetry so we can see when
// an advisory applies but no ready target was available to nudge.
return null
}
if (assessment.affected) {
return {
kind: 'security',
policy,
installedVersion,
reference: assessment.reference,
targetVersion: upgrade.status === 'ready' ? upgrade.targetVersion : null,
unavailableReason:
upgrade.status === 'ready'
? null
: `${upgrade.status === 'unknown' ? 'Upgrade availability could not be checked.' : 'No safe newer target is available for the configured upgrade policy.'} ${upgrade.reason}`,
targetVersion: upgrade.targetVersion,
}
}
if (
upgrade.status !== 'ready' ||
policy === 'security' ||
stopBefore === 'latest'
) {
if (policy === 'security' || stopBefore === 'latest') {
return null
}
const latestVersion = getLatestUpgradeVersion(
......@@ -248,8 +244,7 @@ export async function assessUpgrade(
async function nudgeUpgradeForAgent(
options: NudgeOptions,
reminder: UpgradeReminder,
preview: boolean
reminder: UpgradeReminder
): Promise<void> {
let summary: string
let recommendation: string
......@@ -271,15 +266,11 @@ async function nudgeUpgradeForAgent(
recommendation = 'We recommend you adopt these Future Defaults.'
break
}
const unavailableReason =
reminder.kind === 'security' ? reminder.unavailableReason : null
const command = unavailableReason
? null
: `next upgrade --ai=${reminder.policy}`
const command = `next upgrade --ai=${reminder.policy}`
const note = getRequestedUpgrade()
? `Note: This reminder is enabled by \`__NEXT_AGENTIC_AUTO_UPGRADE=${reminder.policy}\`.`
: `Note: This reminder is enabled by \`experimental.agenticAutoUpgrade: '${reminder.policy}'\`.`
let message = `${summary}
const message = `${summary}
**${recommendation}**
......@@ -287,20 +278,13 @@ This command stopped so the reminder you configured is not missed. Retry the sam
When you report back to the user, include this upgrade recommendation even if the retry succeeds.
${
command
? `At the end of the task, ask the user whether they want you to run the upgrade using the configured '${reminder.policy}' policy in the background. If the app is in a Git repository, use a separate Git worktree unless they request otherwise. If the app is not in a Git repository, upgrade it in place. Run this command from this app's directory:
At the end of the task, ask the user whether they want you to run the upgrade using the configured '${reminder.policy}' policy in the background. If the app is in a Git repository, use a separate Git worktree unless they request otherwise. If the app is not in a Git repository, upgrade it in place. Run this command from this app's directory:
\`\`\`
${command}
\`\`\``
: unavailableReason
}
\`\`\`
${reference ? `Reference: ${reference}\n\n` : ''}${note}`
if (preview) {
message = `Forced preview: this reminder does not establish upgrade eligibility.\n\n${message}`
}
let retryAllowed = false
try {
retryAllowed = await allowNudgeRetry(
......@@ -315,7 +299,7 @@ ${reference ? `Reference: ${reference}\n\n` : ''}${note}`
}
if (retryAllowed) {
Log.warn(
`${summary} This command is continuing after the reminder you configured.${unavailableReason ? `\n${unavailableReason}` : ''}${reference ? `\nReference: ${reference}` : ''}`
`${summary} This command is continuing after the reminder you configured.${reference ? `\nReference: ${reference}` : ''}`
)
return
}
......@@ -389,18 +373,15 @@ async function getUpgradeDismissal(
async function nudgeUpgradeForHuman(
directory: string,
reminder: UpgradeReminder,
signal: AbortSignal,
preview: boolean
signal: AbortSignal
): Promise<UpgradeAction> {
if (signal.aborted) {
return 'skip'
}
let message: string
let canUpgrade = true
if (reminder.kind === 'security') {
message = `⚠ Installed Next.js version ${reminder.installedVersion} is affected by a known security vulnerability.`
canUpgrade = reminder.unavailableReason === null
message += `\n\n${reminder.unavailableReason ?? `Next.js security version upgrade available: ${reminder.installedVersion} -> ${reminder.targetVersion ?? '[target version]'}`}`
message += `\n\nNext.js security version upgrade available: ${reminder.installedVersion} -> ${reminder.targetVersion}`
} else if (reminder.policy === 'future') {
const targetVersion =
reminder.kind === 'latest'
......@@ -419,11 +400,8 @@ async function nudgeUpgradeForHuman(
} else {
return 'skip'
}
if (preview) {
message = `Forced preview: __NEXT_AGENTIC_AUTO_UPGRADE=${reminder.policy}. Upgrade eligibility has not been established.\n\n${message}`
}
const { promptUpgrade } = require('./prompt') as typeof import('./prompt')
const action = await promptUpgrade(message, signal, canUpgrade)
const action = await promptUpgrade(message, signal, true)
if (signal.aborted) {
return 'skip'
}
......@@ -495,56 +473,22 @@ export async function nudgeUpgrade(
return
}
}
let reminder = await assessUpgrade(
const reminder = await assessUpgrade(
directory,
{ ...config, experimental: { agenticAutoUpgrade: policy } },
installedVersion,
stopBefore,
requested !== null
)
const preview = !reminder && requested !== null
if (preview) {
// Exercise the real template without inventing an advisory or release.
// Update still runs the normal eligibility checks against this installation.
const context = { policy, installedVersion }
switch (requested) {
case 'security':
reminder = {
...context,
kind: 'security',
reference: null,
targetVersion: null,
unavailableReason: null,
}
break
case 'latest':
reminder = {
...context,
kind: 'latest',
latestVersion: null,
names: [],
}
break
case 'future':
reminder = {
...context,
kind: 'future',
targetVersion: installedVersion,
names: futureDefaults.map((entry) => entry.name),
}
break
}
}
if (!reminder || signal?.aborted) {
return
}
if (agent) {
await nudgeUpgradeForAgent(
{ directory, distDir: config.distDir, command },
reminder,
preview
reminder
)
} else if (signal) {
return nudgeUpgradeForHuman(directory, reminder, signal, preview)
return nudgeUpgradeForHuman(directory, reminder, signal)
}
}
This diff is collapsed.
......@@ -192,33 +192,15 @@ describe('security upgrade nudge', () => {
})
it.each(['blocked', 'unknown'] as const)(
'preserves the advisory and retry behavior when target eligibility is %s',
'skips the security nudge when target eligibility is %s',
async (status) => {
jest.mocked(getUpgradeAssessment).mockResolvedValue({
reference: 'https://api.github.com/advisories?affects=next',
affected: true,
upgrade: { status, reason: 'Target assessment detail.' },
})
let message = ''
try {
await run()
} catch (error) {
expect(error).toMatchObject({ name: 'SecurityFatalError', exitCode: 1 })
message = (error as Error).message
}
expect(message).toContain('affected by a published security advisory')
expect(message).toContain('Target assessment detail.')
expect(message.includes('next upgrade --ai')).toBe(false)
expect(message.includes('can be automatically upgraded')).toBe(false)
expect(message).toContain(
status === 'unknown'
? 'Upgrade availability could not be checked.'
: 'No safe newer target is available'
)
await expect(run()).resolves.toBeUndefined()
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('Target assessment detail.')
)
expect(warn).not.toHaveBeenCalled()
}
)
......@@ -353,7 +335,9 @@ describe('latest nudge release selection', () => {
['17.2.0-canary.4', '17.3.0-rc.1', null],
['17.2.0-rc.1', '17.3.0', '17.3.0'],
['17.2.0-rc.1', '17.2.0', '17.2.0'],
['17.2.0-rc.1', '17.2.0-rc.2', null],
['17.2.0-beta.1', '17.2.0', '17.2.0'],
['17.2.0-beta.1', '18.0.0-beta.1', null],
['17.2.0-preview.1', '17.2.0', '17.2.0'],
['17.2.0-rc.1', '17.3.0-rc.1', null],
['17.2.0-beta.1', '17.3.0-beta.1', null],
......@@ -400,7 +384,7 @@ describe('latest upgrade nudge', () => {
)
it.each(['rc', 'beta', 'preview'] as const)(
'links a configured %s reminder to stable latest',
'links a verified %s latest reminder to stable latest',
async (channel) => {
process.env.__NEXT_VERSION = `17.2.0-${channel}.1`
mockUpgrade('17.2.0')
......@@ -412,6 +396,11 @@ describe('latest upgrade nudge', () => {
'Reference: https://registry.npmjs.org/next/latest'
),
})
expect(getUpgradeAssessment).toHaveBeenCalledWith(
`17.2.0-${channel}.1`,
'latest',
false
)
}
)
......@@ -786,36 +775,37 @@ describe('human upgrade nudge', () => {
)
it.each(['security', 'latest', 'future'] as const)(
'forces a %s request without changing installed-version eligibility',
'does not force a %s nudge without a valid installed version',
async (policy) => {
process.env.__NEXT_AGENTIC_AUTO_UPGRADE = policy
process.env.__NEXT_VERSION = '16.4.0-preview-test'
process.env.__NEXT_VERSION = 'not-a-version'
processEnv([], directory)
updateInitialEnv({ __NEXT_AGENTIC_AUTO_UPGRADE: policy })
jest.mocked(promptUpgrade).mockResolvedValue('update')
for (const configured of [false, 'future'] as const) {
const original = config(configured)
const context = getUpgradeContext(original)
expect(context.experimental.agenticAutoUpgrade).toBe(policy)
await expect(
nudgeUpgrade(directory, context, 'dev', new AbortController().signal)
).resolves.toBe('update')
).resolves.toBeUndefined()
}
expect(promptUpgrade).toHaveBeenCalledWith(
expect.stringContaining(`__NEXT_AGENTIC_AUTO_UPGRADE=${policy}`),
expect.any(AbortSignal),
true
)
expect(promptUpgrade).not.toHaveBeenCalled()
expect(getUpgradeAssessment).not.toHaveBeenCalled()
const message = jest.mocked(promptUpgrade).mock.calls[0][0]
expect(message).toContain('Forced preview:')
expect(message).not.toContain(`next upgrade --ai`)
expect(message).not.toContain('You requested')
jest.mocked(getAgentName).mockResolvedValue('codex')
await expect(run(policy)).rejects.toMatchObject({
message: expect.stringContaining(`next upgrade --ai=${policy}`),
})
await expect(run(policy)).resolves.toBeUndefined()
}
)
it.each(['security', 'latest', 'future'] as const)(
'runs an explicitly requested %s upgrade',
async (policy) => {
process.env.__NEXT_AGENTIC_AUTO_UPGRADE = policy
process.env.__NEXT_VERSION = '16.4.0-preview-test'
processEnv([], directory)
updateInitialEnv({
__NEXT_AGENTIC_AUTO_UPGRADE: policy,
__NEXT_VERSION: '16.4.0-preview-test',
})
jest.mocked(spawnNextUpgrade).mockImplementationOnce(async () => {
expect(process.env.__NEXT_AGENTIC_AUTO_UPGRADE).toBeUndefined()
// Future upgrade preparation reloads config and resets the environment.
......@@ -832,6 +822,22 @@ describe('human upgrade nudge', () => {
}
)
it.each(['blocked', 'unknown'] as const)(
'does not force a nudge when the target is %s',
async (status) => {
process.env.__NEXT_AGENTIC_AUTO_UPGRADE = 'security'
jest.mocked(getUpgradeAssessment).mockResolvedValue({
affected: true,
reference:
'https://registry.npmjs.org/-/npm/v1/security/advisories/bulk',
upgrade: { status, reason: 'No verified target.' },
})
await expect(run('security')).resolves.toBeUndefined()
expect(promptUpgrade).not.toHaveBeenCalled()
expect(warn).not.toHaveBeenCalled()
}
)
it('lets an explicit request bypass a saved dismissal', async () => {
jest.mocked(promptUpgrade).mockResolvedValue('dismiss')
await run('security')
......@@ -1030,18 +1036,14 @@ describe('human upgrade nudge', () => {
})
it.each(['blocked', 'unknown'] as const)(
'omits Update when security target availability is %s',
'does not prompt when security target availability is %s',
async (status) => {
jest.mocked(getUpgradeAssessment).mockResolvedValue({
...securityAssessment,
upgrade: { status, reason: 'No eligible target.' },
})
await run()
expect(promptUpgrade).toHaveBeenCalledWith(
expect.stringContaining('No eligible target.'),
expect.any(AbortSignal),
false
)
expect(promptUpgrade).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