//nefariousplan

CVE-2026-44577: Next.js Wired maximumResponseBody to One Branch of the Ternary. fetchInternalImage Was the Other.

vendor

pattern

cve

proof of concept

PR #88183 landed in Next.js on January 6, 2026. It introduced images.maximumResponseBody, a 50 MB default cap on bytes the image optimizer would buffer before handing the result to Sharp. The cap was wired into one branch of a ternary in next-server.ts. The other branch of the same ternary, four lines below, was fetchInternalImage. It had no parameter for the cap to land in. CVE-2026-44577 is the patch from one hundred days later that adds the parameter.

The cap existed. fetchInternalImage was not asked for it.

The Next.js image optimizer is /_next/image?url=...&w=...&q=.... The handler routes to one of two functions in packages/next/src/server/image-optimizer.ts, depending on whether the url is absolute or path-relative. Absolute URLs (https://cdn.example.com/photo.jpg) go through fetchExternalImage. Path-relative URLs (/photo.jpg, /api/preview/123.png) go through fetchInternalImage. Both ultimately produce a Buffer that is handed to Sharp for re-encoding.

The capability the two functions implement is identical: fetch the upstream bytes for href, buffer them into a Buffer, return the buffer with content type and ETag. The shapes diverge only in how they reach the upstream. fetchExternalImage calls fetch() with an AbortSignal.timeout(7_000). fetchInternalImage dispatches through Next.js's own router by handing a MockedResponse to handleRequest, then reads mocked.res.buffers after the response ends.

On January 6, 2026, PR #88183 landed images.maximumResponseBody with a 50 MB default and changed the external path to enforce it byte by byte inside the chunk loop:

// fetchExternalImage, post-#88183
const chunks: Buffer[] = []
let totalSize = 0

for await (const c of res.body) {
  const chunk = Buffer.from(c)
  totalSize += chunk.byteLength
  if (totalSize > maximumResponseBody) {
    Log.error('upstream image response exceeded maximum size for', href, totalSize)
    throw new ImageError(
      413,
      '"url" parameter is valid but upstream response is invalid'
    )
  }
  chunks.push(chunk)
}

const buffer = Buffer.concat(chunks)

The same PR did not touch fetchInternalImage. Its signature at the time of PR #88183:

export async function fetchInternalImage(
  href: string,
  _req: IncomingMessage,
  _res: ServerResponse,
  handleRequest: (
    newReq: IncomingMessage,
    newRes: ServerResponse,
    newParsedUrl?: NextUrlWithParsedQuery
  ) => Promise<void>
): Promise<ImageUpstream>

The underscore prefix on _req and _res is the TypeScript convention for "this parameter is in the signature so the caller can pass it, but I do not use it." The two parameters are forwarded into createRequestResponseMocks for the socket and method, and never read again. The function had no concept of caller-supplied bytes. There was no slot for maximumResponseBody to live in.

Both branches of the ternary buffered everything into memory

next-server.ts reaches both functions from a single ternary expression. Here is what PR #88183 wrote into that expression on January 6:

        ? await fetchExternalImage(
            href,
            this.nextConfig.images.dangerouslyAllowLocalIP,
+           this.nextConfig.images.maximumResponseBody,
            this.nextConfig.images.maximumRedirects
          )
        : await fetchInternalImage(
            href,
            req.originalRequest,
            res.originalResponse,
            handleInternalReq
          )

The patched line and the unpatched alternative are inside the same await expression. The + line sits directly above : await fetchInternalImage(. The patch author's diff context window showed both branches at once. The branch he edited became safe. The branch he did not edit kept buffering arbitrary bytes through MockedResponse.write, which until then pushed every chunk onto this.buffers with no accumulator and no ceiling:

// MockedResponse.write, pre-CVE-2026-44577
write(chunk: Uint8Array | Buffer | string): boolean {
  if (this.resWriter) {
    return this.resWriter(chunk)
  }
  this.buffers.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
  return true
}

mocked.res.buffers is then read by fetchInternalImage after await mocked.res.hasStreamed resolves:

const buffer = Buffer.concat(mocked.res.buffers)

Buffer.concat is a memory operation. The size is whatever the upstream produced. If the upstream is a multi-gigabyte file matched by images.localPatterns, the process holds it in RAM until the request completes.

"Internal" in fetchInternalImage means "routed through Next.js's own router"

The function name suggests "trusted, in-process, bounded." The behavior is the opposite. fetchInternalImage calls handleInternalReq, which is:

const handleInternalReq = async (
  newReq: IncomingMessage,
  newRes: ServerResponse
) => {
  if (newReq.url === req.url) {
    throw new Error(`Invariant attempted to optimize _next/image itself`)
  }

  if (!this.routerServerHandler) {
    throw new Error(`Invariant missing routerServerHandler`)
  }

  await this.routerServerHandler(newReq, newRes)
  return
}

routerServerHandler is the full Next.js router. Anything the developer's next.config.js can express runs here: rewrites, redirects, middleware, API routes, App Router pages, static files. The only thing the recursion guard blocks is the path /_next/image itself. Every other path the developer's router resolves is reachable.

The path filter is hasLocalMatch(localPatterns, url). The shared library function in match-local-pattern.ts:

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))
}

The advisory says it plainly: "by default, all patterns are allowed." A Next.js self-hoster who has not set images.localPatterns in next.config.js, which is the documented default, exposes every path their router resolves through /_next/image.

The exploit primitive on a default-configured self-hosted Next.js 15.5.15 or 16.2.4:

GET /_next/image?url=%2Flarge.bin&w=1920&q=75 HTTP/1.1
Host: target.example

Where /large.bin is any path the developer's router serves: a static asset, an API route that streams a database export, a rewrite that proxies to an internal backend. The router resolves the path. The handler writes the response into MockedResponse. MockedResponse.write pushes every chunk into this.buffers. Buffer.concat materializes the full size. Repeat the request from N concurrent connections; each connection holds its own copy in heap. Node hits its heap ceiling and the process exits.

The shape applies to rewrites too. A next.config.js rewrite that maps /proxy/:path* to http://internal-bucket/:path* does not become any safer for being matched by localPatterns. The image optimizer treats the rewrite the same way it treats a static file: load the entire upstream body into the in-process buffer. The "internal" in fetchInternalImage describes which router answers the request, not which network the response came from.

The patch is the parameter, threaded through four call sites

CVE-2026-44577's fix lives in commit 4e08dc7 (PR #92920, merged April 16, 2026). The patch is mechanical. It adds maximumResponseBody as a parameter to fetchInternalImage, passes it down to createRequestResponseMocks, stores it on MockedResponse, and adds a four-line check inside MockedResponse.write:

+const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+
+if (this.maximumResponseBody !== undefined) {
+  this.totalSize += buffer.byteLength
+  if (this.totalSize > this.maximumResponseBody) {
+    const error = new Error(
+      `Response body exceeded maximum size of ${this.maximumResponseBody} bytes`
+    ) as NodeJS.ErrnoException
+    error.code = 'ERR_MAX_BODY_SIZE_EXCEEDED'
+    this.destroy(error)
+    return true
+  }
+}
+
+this.buffers.push(buffer)

And the call-site change in next-server.ts:

        : await fetchInternalImage(
            href,
            req.originalRequest,
            res.originalResponse,
+           this.nextConfig.images.maximumResponseBody,
            handleInternalReq
          )

That + line is the line that did not exist on January 6 and existed on April 16. The PR #92920 description names the prior PR explicitly: "In a previous PR https://github.com/vercel/next.js/pull/88183, we added images.maximumResponseBody but in only applied to external images. This PR ensures the same config also applies to internal images." The author of PR #92920 is the same Steven who authored PR #88183.

The value being threaded through, this.nextConfig.images.maximumResponseBody, has been on nextConfig since January with a 50 MB default. The integer was on the config object the whole time. The function call did not ask for it.

The fourth Next.js parallel implementation gap of this release window

This is the parallel-implementation-gap pattern. A capability is implemented by two or more parallel modules; a security check is wired to one and not the others. Three other Next.js CVEs in the same release window are the same shape:

  • CVE-2026-44578: the upgrade-handler in the self-hosted router-server lacked an absolute-URL guard that the Vercel edge runtime had. Two implementations of the same upgrade contract; one was hardened.
  • CVE-2026-44575: the App Router renderer stripped .rsc and .segments suffixes that getMiddlewareMatchers did not learn. Two URL classifiers, one of them on the old Pages-era alphabet.
  • CVE-2026-44573: resolveRoutes prefixed direct-page requests with the default locale and did not prefix data requests. Two locale-resolution sites inside one function, eleven lines re-typed apart.

CVE-2026-44577 is the smallest-distance instance of the four. The two parallel implementations are not two files (Astro), not two runtimes (MLflow), not two branches of a function (Axios), not two suffix sets in a regex (CVE-2026-44575). They are two branches of one ternary expression, in the same await, in the same statement. The patch author had both branches open in the same editor view when the gate was wired to the first. The fix is the same value being passed to the function call on the other branch.

What the timeline says

PR #88183, merged 2026-01-06, named the threat (maximumResponseBody), wrote the enforcement, and chose a default (50 MB). The author understood that buffering arbitrary upstream bytes into memory was a denial-of-service primitive. The PR title was feat(next/image)!: add images.maximumResponseBody config.

PR #92920, merged 2026-04-16, threads the same value into the function call that sits four lines below the call PR #88183 patched. The PR title is fix(next/image): ensure images.maximumResponseBody applies to local images too.

GHSA-h64f-5h5j-jqjh and CVE-2026-44577 were published 2026-05-06, twenty days after the fix. The GHSA's summary is "Denial of Service in the Image Optimization API." It does not mention the parameter-threading shape. It does not mention that the value being threaded was defined three months earlier. It says only that "We now apply response size limits consistently to internal image fetches, not just external ones."

The advisory framing leaves the reader with "Vercel discovered an oversight." The patch framing tells you what the oversight was: a function call in a ternary, four lines below another call in the same ternary, was missing one argument. The argument was the property on nextConfig that the line above already named.

Patched versions: Next.js 15.5.16 and 16.2.5. Versions 10.0.0 through 15.5.15 and 16.0.0 through 16.2.4 buffer any path the router resolves. Self-hosted only; Vercel-hosted deployments do not run this code path.

Advisory: GHSA-h64f-5h5j-jqjh Fix: vercel/next.js@4e08dc7 (PR #92920) Prior PR that introduced the cap: vercel/next.js#88183

The gap was the absence of a parameter in a function signature. The patch is the parameter.