Unverified Commit 57d29635 authored by Steven's avatar Steven Committed by GitHub

feat: add `contentDispositionType` config to Image Optimization API (#46254)

Add `contentDispositionType` config to Image Optimization API so the user can configure `inline` vs `attachment`.

This is recommended when `dangerouslyAllowSVG` is enabled but can also be used when its disabled.
parent 3d73366a
...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component. ...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component.
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `v13.2.0` | `contentDispositionType` configuration added. |
| `v13.0.6` | `ref` prop added. | | `v13.0.6` | `ref` prop added. |
| `v13.0.0` | `<span>` wrapper removed. `layout`, `objectFit`, `objectPosition`, `lazyBoundary`, `lazyRoot` props removed. `alt` is required. `onLoadingComplete` receives reference to `img` element. Built-in loader config removed. | | `v13.0.0` | `<span>` wrapper removed. `layout`, `objectFit`, `objectPosition`, `lazyBoundary`, `lazyRoot` props removed. `alt` is required. `onLoadingComplete` receives reference to `img` element. Built-in loader config removed. |
| `v12.3.0` | `remotePatterns` and `unoptimized` configuration is stable. | | `v12.3.0` | `remotePatterns` and `unoptimized` configuration is stable. |
...@@ -503,17 +504,20 @@ module.exports = { ...@@ -503,17 +504,20 @@ module.exports = {
The default [loader](#loader) does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/advanced-features/security-headers.md). The default [loader](#loader) does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/advanced-features/security-headers.md).
If you need to serve SVG images with the default Image Optimization API, you can set `dangerouslyAllowSVG` and `contentSecurityPolicy` inside your `next.config.js`: If you need to serve SVG images with the default Image Optimization API, you can set `dangerouslyAllowSVG` inside your `next.config.js`:
```js ```js
module.exports = { module.exports = {
images: { images: {
dangerouslyAllowSVG: true, dangerouslyAllowSVG: true,
contentDispositionType: 'attachment',
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
}, },
} }
``` ```
In addition, it is strongly recommended to also set `contentDispositionType` to force the browser to download the image, as well as `contentSecurityPolicy` to prevent scripts embedded in the image from executing.
### Animated Images ### Animated Images
The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is. The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is.
......
...@@ -571,17 +571,20 @@ module.exports = { ...@@ -571,17 +571,20 @@ module.exports = {
The default [loader](#loader) does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/advanced-features/security-headers.md). The default [loader](#loader) does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper [Content Security Policy (CSP) headers](/docs/advanced-features/security-headers.md).
If you need to serve SVG images with the default Image Optimization API, you can set `dangerouslyAllowSVG` and `contentSecurityPolicy` inside your `next.config.js`: If you need to serve SVG images with the default Image Optimization API, you can set `dangerouslyAllowSVG` inside your `next.config.js`:
```js ```js
module.exports = { module.exports = {
images: { images: {
dangerouslyAllowSVG: true, dangerouslyAllowSVG: true,
contentDispositionType: 'attachment',
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
}, },
} }
``` ```
In addition, it is strongly recommended to also set `contentDispositionType` to force the browser to download the image, as well as `contentSecurityPolicy` to prevent scripts embedded in the image from executing.
### Animated Images ### Animated Images
The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is. The default [loader](#loader) will automatically bypass Image Optimization for animated images and serve the image as-is.
......
...@@ -33,6 +33,8 @@ module.exports = { ...@@ -33,6 +33,8 @@ module.exports = {
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
// set the Content-Security-Policy header // set the Content-Security-Policy header
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;", contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
// sets the Content-Disposition header (inline or attachment)
contentDispositionType: 'inline',
// limit of 50 objects // limit of 50 objects
remotePatterns: [], remotePatterns: [],
// when true, every image will be unoptimized // when true, every image will be unoptimized
......
...@@ -598,6 +598,10 @@ const configSchema = { ...@@ -598,6 +598,10 @@ const configSchema = {
minLength: 1, minLength: 1,
type: 'string', type: 'string',
}, },
contentDispositionType: {
enum: ['inline', 'attachment'] as any, // automatic typing does not like enum
type: 'string',
},
dangerouslyAllowSVG: { dangerouslyAllowSVG: {
type: 'boolean', type: 'boolean',
}, },
......
...@@ -23,6 +23,7 @@ import { IncrementalCacheEntry, IncrementalCacheValue } from './response-cache' ...@@ -23,6 +23,7 @@ import { IncrementalCacheEntry, IncrementalCacheValue } from './response-cache'
import { mockRequest } from './lib/mock-request' import { mockRequest } from './lib/mock-request'
import { hasMatch } from '../shared/lib/match-remote-pattern' import { hasMatch } from '../shared/lib/match-remote-pattern'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg' import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import { ImageConfigComplete } from '../shared/lib/image-config'
type XCacheHeader = 'MISS' | 'HIT' | 'STALE' type XCacheHeader = 'MISS' | 'HIT' | 'STALE'
...@@ -672,11 +673,11 @@ export async function imageOptimizer( ...@@ -672,11 +673,11 @@ export async function imageOptimizer(
function getFileNameWithExtension( function getFileNameWithExtension(
url: string, url: string,
contentType: string | null contentType: string | null
): string | void { ): string {
const [urlWithoutQueryParams] = url.split('?') const [urlWithoutQueryParams] = url.split('?')
const fileNameWithExtension = urlWithoutQueryParams.split('/').pop() const fileNameWithExtension = urlWithoutQueryParams.split('/').pop()
if (!contentType || !fileNameWithExtension) { if (!contentType || !fileNameWithExtension) {
return return 'image.bin'
} }
const [fileName] = fileNameWithExtension.split('.') const [fileName] = fileNameWithExtension.split('.')
...@@ -692,7 +693,7 @@ function setResponseHeaders( ...@@ -692,7 +693,7 @@ function setResponseHeaders(
contentType: string | null, contentType: string | null,
isStatic: boolean, isStatic: boolean,
xCache: XCacheHeader, xCache: XCacheHeader,
contentSecurityPolicy: string, imagesConfig: ImageConfigComplete,
maxAge: number, maxAge: number,
isDev: boolean isDev: boolean
) { ) {
...@@ -712,16 +713,12 @@ function setResponseHeaders( ...@@ -712,16 +713,12 @@ function setResponseHeaders(
} }
const fileName = getFileNameWithExtension(url, contentType) const fileName = getFileNameWithExtension(url, contentType)
if (fileName) {
res.setHeader( res.setHeader(
'Content-Disposition', 'Content-Disposition',
contentDisposition(fileName, { type: 'inline' }) contentDisposition(fileName, { type: imagesConfig.contentDispositionType })
) )
}
if (contentSecurityPolicy) { res.setHeader('Content-Security-Policy', imagesConfig.contentSecurityPolicy)
res.setHeader('Content-Security-Policy', contentSecurityPolicy)
}
res.setHeader('X-Nextjs-Cache', xCache) res.setHeader('X-Nextjs-Cache', xCache)
return { finished: false } return { finished: false }
...@@ -735,7 +732,7 @@ export function sendResponse( ...@@ -735,7 +732,7 @@ export function sendResponse(
buffer: Buffer, buffer: Buffer,
isStatic: boolean, isStatic: boolean,
xCache: XCacheHeader, xCache: XCacheHeader,
contentSecurityPolicy: string, imagesConfig: ImageConfigComplete,
maxAge: number, maxAge: number,
isDev: boolean isDev: boolean
) { ) {
...@@ -749,7 +746,7 @@ export function sendResponse( ...@@ -749,7 +746,7 @@ export function sendResponse(
contentType, contentType,
isStatic, isStatic,
xCache, xCache,
contentSecurityPolicy, imagesConfig,
maxAge, maxAge,
isDev isDev
) )
......
...@@ -466,7 +466,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -466,7 +466,7 @@ export default class NextNodeServer extends BaseServer {
cacheEntry.value.buffer, cacheEntry.value.buffer,
paramsResult.isStatic, paramsResult.isStatic,
cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT', cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',
imagesConfig.contentSecurityPolicy, imagesConfig,
cacheEntry.revalidate || 0, cacheEntry.revalidate || 0,
Boolean(this.renderOpts.dev) Boolean(this.renderOpts.dev)
) )
......
...@@ -88,6 +88,9 @@ export type ImageConfigComplete = { ...@@ -88,6 +88,9 @@ export type ImageConfigComplete = {
/** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */ /** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */
contentSecurityPolicy: string contentSecurityPolicy: string
/** @see [Dangerously Allow SVG](https://nextjs.org/docs/api-reference/next/image#dangerously-allow-svg) */
contentDispositionType: 'inline' | 'attachment'
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remote-patterns) */ /** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remote-patterns) */
remotePatterns: RemotePattern[] remotePatterns: RemotePattern[]
...@@ -109,6 +112,7 @@ export const imageConfigDefault: ImageConfigComplete = { ...@@ -109,6 +112,7 @@ export const imageConfigDefault: ImageConfigComplete = {
formats: ['image/webp'], formats: ['image/webp'],
dangerouslyAllowSVG: false, dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`, contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
contentDispositionType: 'inline',
remotePatterns: [], remotePatterns: [],
unoptimized: false, unoptimized: false,
} }
import { join } from 'path'
import { setupTests } from './util'
const appDir = join(__dirname, '../app')
const imagesDir = join(appDir, '.next', 'cache', 'images')
describe('with contentDispositionType attachment', () => {
setupTests({
nextConfigImages: { contentDispositionType: 'attachment' },
appDir,
imagesDir,
})
})
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