Skip to content

Commit

Permalink
feat(next/image): add images.localPatterns config (#70529)
Browse files Browse the repository at this point in the history
This adds support for `images.localPatterns` config to allow specific
local images to be optimized and (more importantly) block anything that
doesn't match a pattern.
  • Loading branch information
styfle committed Oct 4, 2024
1 parent f1fc357 commit 2d168b6
Show file tree
Hide file tree
Showing 33 changed files with 596 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,21 @@ export default function Page() {

> **Warning:** Dynamic `await import()` or `require()` are _not_ supported. The `import` must be static so it can be analyzed at build time.
You can optionally configure `localPatterns` in your `next.config.js` file in order to allow specific images and block all others.

```js filename="next.config.js"
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/images/**',
search: '',
},
],
},
}
```

### Remote Images

To use a remote image, the `src` property should be a URL string.
Expand Down
19 changes: 19 additions & 0 deletions docs/02-app/02-api-reference/01-components/image.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,25 @@ Other properties on the `<Image />` component will be passed to the underlying

In addition to props, you can configure the Image Component in `next.config.js`. The following options are available:

## `localPatterns`

You can optionally configure `localPatterns` in your `next.config.js` file in order to allow specific paths to be optimized and block all others paths.

```js filename="next.config.js"
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/images/**',
search: '',
},
],
},
}
```

> **Good to know**: The example above will ensure the `src` property of `next/image` must start with `/assets/images/` and must not have a query string. Attempting to optimize any other path will respond with 400 Bad Request.
### `remotePatterns`

To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the `remotePatterns` property in your `next.config.js` file, as shown below:
Expand Down
2 changes: 2 additions & 0 deletions errors/invalid-images-config.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ module.exports = {
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
// sets the Content-Disposition header (inline or attachment)
contentDispositionType: 'inline',
// limit of 25 objects
localPatterns: [],
// limit of 50 objects
remotePatterns: [],
// when true, every image will be unoptimized
Expand Down
29 changes: 29 additions & 0 deletions errors/next-image-unconfigured-localpatterns.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
title: '`next/image` Un-configured localPatterns'
---

## Why This Error Occurred

One of your pages that leverages the `next/image` component, passed a `src` value that uses a URL that isn't defined in the `images.localPatterns` property in `next.config.js`.

## Possible Ways to Fix It

Add an entry to `images.localPatterns` array in `next.config.js` with the expected URL pattern. For example:

```js filename="next.config.js"
module.exports = {
images: {
localPatterns: [
{
pathname: '/assets/**',
search: '',
},
],
},
}
```

## Useful Links

- [Image Optimization Documentation](/docs/pages/building-your-application/optimizing/images)
- [Local Patterns Documentation](/docs/pages/api-reference/components/image#localpatterns)
29 changes: 17 additions & 12 deletions packages/next/src/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,11 @@ async function writeImagesManifest(
port: p.port,
pathname: makeRe(p.pathname ?? '**').source,
}))
images.localPatterns = (config?.images?.localPatterns || []).map((p) => ({
// Modifying the manifest should also modify matchLocalPattern()
pathname: makeRe(p.pathname ?? '**', { dot: true }).source,
search: p.search,
}))

await writeManifest(path.join(distDir, IMAGES_MANIFEST), {
version: 1,
Expand Down Expand Up @@ -1653,18 +1658,18 @@ export default async function build(
config.experimental.gzipSize
)

const middlewareManifest: MiddlewareManifest = require(path.join(
distDir,
SERVER_DIRECTORY,
MIDDLEWARE_MANIFEST
))
const middlewareManifest: MiddlewareManifest = require(
path.join(distDir, SERVER_DIRECTORY, MIDDLEWARE_MANIFEST)
)

const actionManifest = appDir
? (require(path.join(
distDir,
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json'
)) as ActionManifest)
? (require(
path.join(
distDir,
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json'
)
) as ActionManifest)
: null
const entriesWithAction = actionManifest ? new Set() : null
if (actionManifest && entriesWithAction) {
Expand Down Expand Up @@ -3023,8 +3028,8 @@ export default async function build(
fallback: ssgBlockingFallbackPages.has(tbdRoute)
? null
: ssgStaticFallbackPages.has(tbdRoute)
? `${normalizedRoute}.html`
: false,
? `${normalizedRoute}.html`
: false,
dataRouteRegex: normalizeRouteRegex(
getNamedRouteRegex(
dataRoute.replace(/\.json$/, ''),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ export function getDefineEnv({
// pass domains in development to allow validating on the client
domains: config.images.domains,
remotePatterns: config.images?.remotePatterns,
localPatterns: config.images?.localPatterns,
output: config.output,
}
: {}),
Expand Down
25 changes: 23 additions & 2 deletions packages/next/src/client/legacy/image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,25 @@ function defaultLoader({
)
}

if (src.startsWith('/') && config.localPatterns) {
if (
process.env.NODE_ENV !== 'test' &&
// micromatch isn't compatible with edge runtime
process.env.NEXT_RUNTIME !== 'edge'
) {
// We use dynamic require because this should only error in development
const {
hasLocalMatch,
} = require('../../shared/lib/match-local-pattern')
if (!hasLocalMatch(config.localPatterns, src)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\` does not match \`images.localPatterns\` configured in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
}
}

if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
Expand All @@ -156,8 +175,10 @@ function defaultLoader({
process.env.NEXT_RUNTIME !== 'edge'
) {
// We use dynamic require because this should only error in development
const { hasMatch } = require('../../shared/lib/match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
const {
hasRemoteMatch,
} = require('../../shared/lib/match-remote-pattern')
if (!hasRemoteMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
Expand Down
9 changes: 9 additions & 0 deletions packages/next/src/server/config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,15 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(),
images: z
.strictObject({
localPatterns: z
.array(
z.strictObject({
pathname: z.string().optional(),
search: z.string().optional(),
})
)
.max(25)
.optional(),
remotePatterns: z
.array(
z.strictObject({
Expand Down
13 changes: 13 additions & 0 deletions packages/next/src/server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,19 @@ function assignDefaults(
)
}

if (images.localPatterns) {
if (!Array.isArray(images.localPatterns)) {
throw new Error(
`Specified images.localPatterns should be an Array received ${typeof images.localPatterns}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`
)
}
// static import images are automatically allowed
images.localPatterns.push({
pathname: '/_next/static/media/**',
search: '',
})
}

if (images.remotePatterns) {
if (!Array.isArray(images.remotePatterns)) {
throw new Error(
Expand Down
9 changes: 7 additions & 2 deletions packages/next/src/server/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import nodeUrl, { type UrlWithParsedQuery } from 'url'

import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
import type { ImageConfigComplete } from '../shared/lib/image-config'
import { hasMatch } from '../shared/lib/match-remote-pattern'
import { hasLocalMatch } from '../shared/lib/match-local-pattern'
import { hasRemoteMatch } from '../shared/lib/match-remote-pattern'
import type { NextConfigComplete } from './config-shared'
import { createRequestResponseMocks } from './lib/mock-request'
// Do not import anything other than types from this module
Expand Down Expand Up @@ -172,6 +173,7 @@ export class ImageOptimizerCache {
formats = ['image/webp'],
} = imageData
const remotePatterns = nextConfig.images?.remotePatterns || []
const localPatterns = nextConfig.images?.localPatterns
const { url, w, q } = query
let href: string

Expand All @@ -192,6 +194,9 @@ export class ImageOptimizerCache {
if (url.startsWith('/')) {
href = url
isAbsolute = false
if (!hasLocalMatch(localPatterns, url)) {
return { errorMessage: '"url" parameter is not allowed' }
}
} else {
let hrefParsed: URL

Expand All @@ -207,7 +212,7 @@ export class ImageOptimizerCache {
return { errorMessage: '"url" parameter is invalid' }
}

if (!hasMatch(domains, remotePatterns, hrefParsed)) {
if (!hasRemoteMatch(domains, remotePatterns, hrefParsed)) {
return { errorMessage: '"url" parameter is not allowed' }
}
}
Expand Down
21 changes: 20 additions & 1 deletion packages/next/src/shared/lib/image-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@ export type ImageLoaderPropsWithConfig = ImageLoaderProps & {
config: Readonly<ImageConfig>
}

export type LocalPattern = {
/**
* Can be literal or wildcard.
* Single `*` matches a single path segment.
* Double `**` matches any number of path segments.
*/
pathname?: string

/**
* Can be literal query string such as `?v=1` or
* empty string meaning no query string.
*/
search?: string
}

export type RemotePattern = {
/**
* Must be `http` or `https`.
Expand Down Expand Up @@ -94,6 +109,9 @@ export type ImageConfigComplete = {
/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#remotepatterns) */
remotePatterns: RemotePattern[]

/** @see [Remote Patterns](https://nextjs.org/docs/api-reference/next/image#localPatterns) */
localPatterns: LocalPattern[] | undefined

/** @see [Unoptimized](https://nextjs.org/docs/api-reference/next/image#unoptimized) */
unoptimized: boolean
}
Expand All @@ -113,6 +131,7 @@ export const imageConfigDefault: ImageConfigComplete = {
dangerouslyAllowSVG: false,
contentSecurityPolicy: `script-src 'none'; frame-src 'none'; sandbox;`,
contentDispositionType: 'inline',
remotePatterns: [],
localPatterns: undefined, // default: allow all local images
remotePatterns: [], // default: allow no remote images
unoptimized: false,
}
21 changes: 19 additions & 2 deletions packages/next/src/shared/lib/image-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,23 @@ function defaultLoader({
)
}

if (src.startsWith('/') && config.localPatterns) {
if (
process.env.NODE_ENV !== 'test' &&
// micromatch isn't compatible with edge runtime
process.env.NEXT_RUNTIME !== 'edge'
) {
// We use dynamic require because this should only error in development
const { hasLocalMatch } = require('./match-local-pattern')
if (!hasLocalMatch(config.localPatterns, src)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\` does not match \`images.localPatterns\` configured in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns`
)
}
}
}

if (!src.startsWith('/') && (config.domains || config.remotePatterns)) {
let parsedSrc: URL
try {
Expand All @@ -46,8 +63,8 @@ function defaultLoader({
process.env.NEXT_RUNTIME !== 'edge'
) {
// We use dynamic require because this should only error in development
const { hasMatch } = require('./match-remote-pattern')
if (!hasMatch(config.domains, config.remotePatterns, parsedSrc)) {
const { hasRemoteMatch } = require('./match-remote-pattern')
if (!hasRemoteMatch(config.domains, config.remotePatterns, parsedSrc)) {
throw new Error(
`Invalid src prop (${src}) on \`next/image\`, hostname "${parsedSrc.hostname}" is not configured under images in your \`next.config.js\`\n` +
`See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host`
Expand Down
29 changes: 29 additions & 0 deletions packages/next/src/shared/lib/match-local-pattern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { LocalPattern } from './image-config'
import { makeRe } from 'next/dist/compiled/picomatch'

// Modifying this function should also modify writeImagesManifest()
export function matchLocalPattern(pattern: LocalPattern, url: URL): boolean {
if (pattern.search !== undefined) {
if (pattern.search !== url.search) {
return false
}
}

if (!makeRe(pattern.pathname ?? '**', { dot: true }).test(url.pathname)) {
return false
}

return true
}

export function hasLocalMatch(
localPatterns: LocalPattern[] | undefined,
urlPathAndQuery: string
): boolean {
if (!localPatterns) {
// if the user didn't define "localPatterns", we allow all local images
return true
}
const url = new URL(urlPathAndQuery, 'http://n')
return localPatterns.some((p) => matchLocalPattern(p, url))
}
2 changes: 1 addition & 1 deletion packages/next/src/shared/lib/match-remote-pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function matchRemotePattern(pattern: RemotePattern, url: URL): boolean {
return true
}

export function hasMatch(
export function hasRemoteMatch(
domains: string[],
remotePatterns: RemotePattern[],
url: URL
Expand Down
5 changes: 5 additions & 0 deletions packages/next/src/telemetry/events/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type EventCliSessionStarted = {
localeDetectionEnabled: boolean | null
imageDomainsCount: number | null
imageRemotePatternsCount: number | null
imageLocalPatternsCount: number | null
imageSizes: string | null
imageLoader: string | null
imageFormats: string | null
Expand Down Expand Up @@ -73,6 +74,7 @@ export function eventCliSession(
| 'localeDetectionEnabled'
| 'imageDomainsCount'
| 'imageRemotePatternsCount'
| 'imageLocalPatternsCount'
| 'imageSizes'
| 'imageLoader'
| 'imageFormats'
Expand Down Expand Up @@ -110,6 +112,9 @@ export function eventCliSession(
imageRemotePatternsCount: images?.remotePatterns
? images.remotePatterns.length
: null,
imageLocalPatternsCount: images?.localPatterns
? images.localPatterns.length
: null,
imageSizes: images?.imageSizes ? images.imageSizes.join(',') : null,
imageLoader: images?.loader,
imageFormats: images?.formats ? images.formats.join(',') : null,
Expand Down
Loading

0 comments on commit 2d168b6

Please sign in to comment.