Unverified Commit 1a7ccf48 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Re-enable AVIF image optimization (#97931)

Reverts #97875 and bumps `sharp` from `^0.35.3` to `^0.35.4`,
re-enabling AVIF image optimization.


`minimumReleaseAge` interplay (verified with pnpm 10.33.0 and 11.22.0 in
a standalone repo with a `file:` dependency declaring sharp as an
optional dependency):

- sharp 0.35.4 was published on 2026-08-26 and is younger than this
repo's 48h `minimumReleaseAge`.
- pnpm aborts the whole install with
`ERR_PNPM_NO_MATURE_MATCHING_VERSION` when no in-range release satisfies
the age gate. This applies to `optionalDependencies` (no warn-and-skip)
and through `file:` dependencies alike.
- The gate also covers the `@img/sharp-*` binary packages sharp 0.35.4
depends on, so excluding only `sharp@0.35.4` is not enough.
- `pnpm-workspace.yaml` therefore exempts `sharp@0.35.4` and
`@img/sharp-*` (pnpm does not allow version qualifiers on name patterns
in this setting). Both entries can be dropped once 0.35.4 is older than
48 hours.
- Downstream users who configure their own `minimumReleaseAge` will hit
the same hard install failure when installing a release with this bump
until 0.35.4 ages out, unless they add the same excludes. Keeping
`^0.35.3` is not a safer alternative: age-gated installs would then
silently resolve the vulnerable 0.35.3.

Part of https://linear.app/vercel/issue/VOC-34654/

---------
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 0c7f81e6
......@@ -130,7 +130,7 @@
}
},
"optionalDependencies": {
"sharp": "^0.35.3"
"sharp": "^0.35.4"
},
"devDependencies": {
"@babel/core": "7.26.10",
......
......@@ -1822,8 +1822,6 @@ export default async function getBaseWebpackConfig(
basePath: config.basePath,
assetPrefix: config.assetPrefix,
outputHashSalt: config.outputHashSalt,
imgOptDangerouslyAllowAVIF:
config.experimental.imgOptDangerouslyAllowAVIF,
},
},
]
......
......@@ -3,7 +3,7 @@ import { optimizeImage } from '../../../../server/image-optimizer'
const BLUR_IMG_SIZE = 8
const BLUR_QUALITY = 70
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match other usages
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match other usages
export async function getBlurImage(
content: Buffer,
......@@ -13,7 +13,6 @@ export async function getBlurImage(
basePath,
outputPath,
isDev,
imgOptDangerouslyAllowAVIF = false,
tracing = () => ({
traceFn:
(fn) =>
......@@ -28,7 +27,6 @@ export async function getBlurImage(
basePath: string
outputPath: string
isDev: boolean
imgOptDangerouslyAllowAVIF?: boolean
tracing: (name?: string) => {
traceFn(fn: Function): any
traceAsyncFn(fn: Function): any
......@@ -39,11 +37,7 @@ export async function getBlurImage(
let blurWidth: number = 0
let blurHeight: number = 0
const isValidBlurExtension =
VALID_BLUR_EXT.includes(extension) ||
(extension === 'avif' && imgOptDangerouslyAllowAVIF)
if (isValidBlurExtension && !isAnimated(content)) {
if (VALID_BLUR_EXT.includes(extension) && !isAnimated(content)) {
// Shrink the image's largest dimension
if (imageSize.width >= imageSize.height) {
blurWidth = BLUR_IMG_SIZE
......@@ -78,7 +72,6 @@ export async function getBlurImage(
height: blurHeight,
contentType: `image/${extension}`,
quality: BLUR_QUALITY,
dangerouslyAllowAVIF: imgOptDangerouslyAllowAVIF,
})
)
const blurDataURLSpan = tracing('image-base64-tostring')
......
......@@ -11,21 +11,14 @@ interface Options {
assetPrefix: string
basePath: string
outputHashSalt: string
imgOptDangerouslyAllowAVIF: boolean
}
function nextImageLoader(this: any, content: Buffer) {
const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader')
return imageLoaderSpan.traceAsyncFn(async () => {
const options: Options = this.getOptions()
const {
compilerType,
isDev,
assetPrefix,
basePath,
outputHashSalt,
imgOptDangerouslyAllowAVIF,
} = options
const { compilerType, isDev, assetPrefix, basePath, outputHashSalt } =
options
const context = this.rootContext
// Prepend the hash salt to the content for filename hash computation, so
......@@ -65,7 +58,6 @@ function nextImageLoader(this: any, content: Buffer) {
basePath,
outputPath,
isDev,
imgOptDangerouslyAllowAVIF,
tracing: imageLoaderSpan.traceChild.bind(imageLoaderSpan),
})
......
......@@ -748,7 +748,6 @@ export default function Image({
}
let staticSrc = ''
let isStaticAvif = false
if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src
......@@ -761,7 +760,6 @@ export default function Image({
}
blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!layout || layout !== 'fill') {
height = height || staticImageData.height
width = width || staticImageData.width
......@@ -776,12 +774,6 @@ export default function Image({
}
src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
warnOnce(
`Image with src "${src}" is using next/legacy/image which is deprecated and will be removed in a future version of Next.js.`
)
......@@ -916,7 +908,7 @@ export default function Image({
)
}
if (!blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
......@@ -266,7 +266,6 @@ export const experimentalSchema = {
forceSwcTransforms: z.boolean().optional(),
fullySpecified: z.boolean().optional(),
gzipSize: z.boolean().optional(),
imgOptDangerouslyAllowAVIF: z.boolean().optional(),
imgOptConcurrency: z.number().int().optional().nullable(),
imgOptOperationCache: z.boolean().optional().nullable(),
imgOptTimeoutInSeconds: z.number().int().optional(),
......
......@@ -597,11 +597,6 @@ export interface ExperimentalConfig {
extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string
/**
* Re-enables AVIF input optimization and automatic blur generation.
* This may expose applications to security risks in native image decoders.
*/
imgOptDangerouslyAllowAVIF?: boolean
imgOptConcurrency?: number | null
imgOptOperationCache?: boolean | null
imgOptTimeoutInSeconds?: number
......@@ -2286,7 +2281,6 @@ export const defaultConfig = Object.freeze({
(os.cpus() || { length: 1 }).length) - 1
),
memoryBasedWorkersCount: false,
imgOptDangerouslyAllowAVIF: false,
imgOptConcurrency: null,
imgOptOperationCache: null,
imgOptTimeoutInSeconds: 7,
......@@ -2447,7 +2441,6 @@ export interface NextConfigRuntime {
| 'preloadEntriesOnStart'
| 'hideLogsAfterAbort'
| 'removeUncaughtErrorAndRejectionListeners'
| 'imgOptDangerouslyAllowAVIF'
| 'imgOptConcurrency'
| 'imgOptOperationCache'
| 'imgOptMaxInputPixels'
......@@ -2516,7 +2509,6 @@ export function getNextConfigRuntime(
hideLogsAfterAbort: ex.hideLogsAfterAbort,
removeUncaughtErrorAndRejectionListeners:
ex.removeUncaughtErrorAndRejectionListeners,
imgOptDangerouslyAllowAVIF: ex.imgOptDangerouslyAllowAVIF,
imgOptConcurrency: ex.imgOptConcurrency,
imgOptOperationCache: ex.imgOptOperationCache,
imgOptMaxInputPixels: ex.imgOptMaxInputPixels,
......
......@@ -85,8 +85,7 @@ async function initCacheEntries(
export function getSharp(
concurrency: number | null | undefined,
operationCache: boolean | null | undefined,
dangerouslyAllowAVIF = false
operationCache: boolean | null | undefined
) {
if (_sharp) {
return _sharp
......@@ -96,6 +95,7 @@ export function getSharp(
_sharp.block({ operation: ['VipsForeignLoad'] })
_sharp.unblock({
operation: [
'VipsForeignLoadHeif', // avif
'VipsForeignLoadJpeg',
'VipsForeignLoadNsgif',
'VipsForeignLoadPng',
......@@ -104,9 +104,6 @@ export function getSharp(
'VipsForeignLoadWebp',
],
})
if (dangerouslyAllowAVIF) {
_sharp.unblock({ operation: ['VipsForeignLoadHeif'] })
}
if (typeof operationCache === 'boolean') {
_sharp.cache(operationCache)
}
......@@ -810,7 +807,6 @@ export async function optimizeImage({
limitInputPixels,
sequentialRead,
timeoutInSeconds,
dangerouslyAllowAVIF,
}: {
buffer: Buffer
contentType: string
......@@ -822,9 +818,8 @@ export async function optimizeImage({
limitInputPixels?: number
sequentialRead?: boolean | null
timeoutInSeconds?: number
dangerouslyAllowAVIF?: boolean
}): Promise<Buffer> {
const sharp = getSharp(concurrency, operationCache, dangerouslyAllowAVIF)
const sharp = getSharp(concurrency, operationCache)
const transformer = sharp(buffer, {
limitInputPixels,
sequentialRead: sequentialRead ?? undefined,
......@@ -1061,7 +1056,6 @@ export async function imageOptimizer(
experimental: Pick<
NextConfigComplete['experimental'],
| 'imgOptConcurrency'
| 'imgOptDangerouslyAllowAVIF'
| 'imgOptOperationCache'
| 'imgOptMaxInputPixels'
| 'imgOptSequentialRead'
......@@ -1137,11 +1131,7 @@ export async function imageOptimizer(
upstreamEtag,
}
}
if (
BYPASS_TYPES.includes(upstreamType) ||
(upstreamType === AVIF &&
!nextConfig.experimental.imgOptDangerouslyAllowAVIF)
) {
if (BYPASS_TYPES.includes(upstreamType)) {
return {
buffer: upstreamBuffer,
contentType: upstreamType,
......@@ -1185,7 +1175,6 @@ export async function imageOptimizer(
quality,
width,
concurrency: nextConfig.experimental.imgOptConcurrency,
dangerouslyAllowAVIF: nextConfig.experimental.imgOptDangerouslyAllowAVIF,
operationCache: nextConfig.experimental.imgOptOperationCache,
limitInputPixels: nextConfig.experimental.imgOptMaxInputPixels,
sequentialRead: nextConfig.experimental.imgOptSequentialRead,
......
......@@ -398,7 +398,6 @@ export function getImgProps(
let heightInt = getInt(height)
let blurWidth: number | undefined
let blurHeight: number | undefined
let isStaticAvif = false
if (isStaticImport(src)) {
const staticImageData = isStaticRequire(src) ? src.default : src
......@@ -421,7 +420,6 @@ export function getImgProps(
blurHeight = staticImageData.blurHeight
blurDataURL = blurDataURL || staticImageData.blurDataURL
staticSrc = staticImageData.src
isStaticAvif = /\.avif(?:\?|$)/i.test(staticSrc)
if (!fill) {
if (!widthInt && !heightInt) {
......@@ -438,12 +436,6 @@ export function getImgProps(
}
src = typeof src === 'string' ? src : staticSrc
// Generating a blurDataURL requires decoding the source image, so static AVIF
// imports do not receive one while AVIF input optimization is disabled.
if (isStaticAvif && placeholder === 'blur' && !blurDataURL) {
placeholder = 'empty'
}
let isLazy =
!priority &&
!preload &&
......@@ -594,7 +586,7 @@ export function getImgProps(
)
}
if (placeholder === 'blur' && !blurDataURL) {
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp'] // should match next-image-loader
const VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match next-image-loader
throw new Error(
`Image with src "${src}" has "placeholder='blur'" property but is missing the "blurDataURL" property.
......
This diff is collapsed.
......@@ -36,6 +36,35 @@ ignoredBuiltDependencies:
blockExoticSubdeps: true
minimumReleaseAge: 2880 # 48 hrs
minimumReleaseAgeExclude:
# sharp 0.35.4 and its @img/* binaries fix a security vulnerability, so they
# are exempt from the 48h release age gate.
# These exemptions should be removed on 2026-08-28
- '@img/sharp-darwin-arm64@0.35.4'
- '@img/sharp-darwin-x64@0.35.4'
- '@img/sharp-freebsd-wasm32@0.35.4'
- '@img/sharp-libvips-darwin-arm64@1.3.3'
- '@img/sharp-libvips-darwin-x64@1.3.3'
- '@img/sharp-libvips-linux-arm64@1.3.3'
- '@img/sharp-libvips-linux-arm@1.3.3'
- '@img/sharp-libvips-linux-ppc64@1.3.3'
- '@img/sharp-libvips-linux-riscv64@1.3.3'
- '@img/sharp-libvips-linux-s390x@1.3.3'
- '@img/sharp-libvips-linux-x64@1.3.3'
- '@img/sharp-libvips-linuxmusl-arm64@1.3.3'
- '@img/sharp-libvips-linuxmusl-x64@1.3.3'
- '@img/sharp-linux-arm64@0.35.4'
- '@img/sharp-linux-arm@0.35.4'
- '@img/sharp-linux-ppc64@0.35.4'
- '@img/sharp-linux-riscv64@0.35.4'
- '@img/sharp-linux-s390x@0.35.4'
- '@img/sharp-linux-x64@0.35.4'
- '@img/sharp-linuxmusl-arm64@0.35.4'
- '@img/sharp-linuxmusl-x64@0.35.4'
- '@img/sharp-wasm32@0.35.4'
- '@img/sharp-webcontainers-wasm32@0.35.4'
- '@img/sharp-win32-arm64@0.35.4'
- '@img/sharp-win32-ia32@0.35.4'
- '@img/sharp-win32-x64@0.35.4'
- '@mswjs/interceptors@0.42.0'
- '@next/*'
- '@turbo/*'
......@@ -51,4 +80,5 @@ minimumReleaseAgeExclude:
- react-is
- react-server-dom-*
- scheduler
- sharp@0.35.4
- turbo
......@@ -445,26 +445,6 @@ describe('Image Optimizer', () => {
})
}
)
describe('experimental.imgOptDangerouslyAllowAVIF in next.config.js', () => {
const { next, skipped } = nextTestSetup({
files: join(__dirname, 'app'),
nextConfig: {
experimental: { imgOptDangerouslyAllowAVIF: true },
},
skipDeployment: true,
})
if (skipped) return
it('should optimize avif input when enabled', async () => {
const query = { w: 256, q: 75, url: '/test.avif' }
const opts = { headers: { accept: 'image/webp' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/webp')
await expectWidth(res, 256)
})
})
;(isNextStart ? describe : describe.skip)(
'External rewrite support with for serving static content in images',
() => {
......
import fs from 'fs-extra'
import { join } from 'path'
import { optimizeImage } from 'next/dist/server/image-optimizer'
import { setupTests } from './util'
describe('with latest sharp', () => {
it('should block avif decoding below the optimizer bypass', async () => {
const buffer = await fs.readFile(join(__dirname, 'app/public/test.avif'))
await expect(
optimizeImage({
buffer,
contentType: 'image/webp',
quality: 75,
width: 100,
})
).rejects.toThrow()
})
setupTests({})
})
......@@ -122,15 +122,6 @@ export async function expectWidth(res, w, { expectAnimated = false } = {}) {
expect(isAnimated(buffer)).toBe(expectAnimated)
}
async function expectUnoptimizedImage(res, filename: string) {
const buffer = Buffer.from(await res.arrayBuffer())
const source = await fs.readFile(join(__dirname, 'app/public', filename))
expect(buffer).toEqual(source)
expect(res.headers.get('Content-Length')).toBe(
Buffer.byteLength(source).toString()
)
}
export const cleanImagesDir = async (imagesDir) => {
console.warn('Cleaning', imagesDir)
await fs.remove(imagesDir)
......@@ -614,23 +605,23 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w)
})
it('should bypass avif input for old Safari', async () => {
it('should downlevel avif format to jpeg for old Safari', async () => {
const accept =
'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5'
const query = { w: ctx.w, q: ctx.q, url: '/test.avif' }
const opts = { headers: { accept } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toContain('image/avif')
expect(res.headers.get('Content-Type')).toContain('image/jpeg')
expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
)
expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"`
`${contentDispositionType}; filename="test.jpeg"`
)
await expectUnoptimizedImage(res, 'test.avif')
await expectWidth(res, ctx.w)
})
it('should fail when url is missing', async () => {
......@@ -941,21 +932,21 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w)
})
it('should bypass optimization for avif input', async () => {
it('should resize avif', async () => {
const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/webp' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('image/avif')
expect(res.headers.get('Content-Type')).toBe('image/webp')
expect(res.headers.get('Cache-Control')).toBe(
`public, max-age=${isDev ? 0 : minimumCacheTTL}, must-revalidate`
)
expect(res.headers.get('Vary')).toBe('Accept')
expect(res.headers.get('etag')).toBeTruthy()
expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"`
`${contentDispositionType}; filename="test.webp"`
)
await expectUnoptimizedImage(res, 'test.avif')
await expectWidth(res, ctx.w)
})
it('should resize relative url and old Chrome accept header as webp', async () => {
......@@ -999,7 +990,7 @@ export function runTests(ctx: RunTestsCtx) {
await expectWidth(res, ctx.w)
})
it('should bypass avif input when avif output is enabled', async () => {
it('should resize avif and maintain format', async () => {
const query = { url: '/test.avif', w: ctx.w, q: ctx.q }
const opts = { headers: { accept: 'image/avif' } }
const res = await next.fetch(`/_next/image?${toQueryString(query)}`, opts)
......@@ -1013,7 +1004,7 @@ export function runTests(ctx: RunTestsCtx) {
expect(res.headers.get('Content-Disposition')).toBe(
`${contentDispositionType}; filename="test.avif"`
)
await expectUnoptimizedImage(res, 'test.avif')
await expectWidth(res, ctx.w)
})
it('should compress avif smaller than webp at q=100', async () => {
......
......@@ -90,36 +90,6 @@ describe('getImageProps()', () => {
expect(props.srcSet).toBeString()
})
it('should disable an automatic blur placeholder for a static avif', () => {
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
})
expect(props.style).toStrictEqual({ color: 'transparent' })
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const { props } = getImageProps({
alt: 'a nice desc',
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
})
expect(props.style?.backgroundImage).toContain(blurDataURL)
})
it('should handle preload', async () => {
const { props } = getImageProps({
alt: 'a nice desc',
......
......@@ -103,40 +103,6 @@ describe('Image Legacy Rendering', () => {
expect($3('noscript').length).toBe(1)
})
it('should disable an automatic blur placeholder for a static avif', () => {
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(0)
expect($.html()).not.toContain('background-image')
})
it('should preserve a custom blur placeholder for a static avif', () => {
const blurDataURL = 'data:image/png;base64,custom'
const element = React.createElement(Image, {
src: {
src: '/_next/static/media/test.abc123.avif',
width: 100,
height: 200,
},
placeholder: 'blur',
blurDataURL,
loading: 'eager',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
expect($('noscript').length).toBe(1)
expect($.html()).toContain(blurDataURL)
})
it('should render the correct sizes passed when a noscript element is rendered', async () => {
const element = React.createElement(Image, {
src: '/test.png',
......
......@@ -35,42 +35,4 @@ describe('getBlurImage', () => {
expect(result).toBeObject()
expect(result.dataURL).toBeUndefined()
})
it('should not generate a blur placeholder for avif', async () => {
const buffer = await getImage('../image-optimizer/images/test.avif')
const result = await getBlurImage(
buffer,
'avif',
{ width: 400, height: 400 },
{
...context,
outputPath: '/_next/static/media/test.avif',
}
)
expect(result).toBeObject()
expect(result).toStrictEqual({
dataURL: undefined,
width: 0,
height: 0,
})
})
it('should generate a blur placeholder for avif when enabled', async () => {
jest.resetModules()
const { getBlurImage: getBlurImageWithAVIF } = await import(
'next/dist/build/webpack/loaders/next-image-loader/blur'
)
const buffer = await getImage('../image-optimizer/images/test.avif')
const result = await getBlurImageWithAVIF(
buffer,
'avif',
{ width: 400, height: 400 },
{
...context,
imgOptDangerouslyAllowAVIF: true,
}
)
expect(result).toBeObject()
expect(result.dataURL).toStartWith('data:image/avif;base64,')
expect(result.width).toBe(8)
expect(result.height).toBe(8)
})
})
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