Unverified Commit 409edf93 authored by Josh Story's avatar Josh Story Committed by GitHub

Stop compressing resume data cache

## Summary

Serialize the Resume Data Cache in postponed state as raw JSON instead of a zlib-compressed base64 string. This lets cache persistence implementations decide whether and how to compress postponed state, and removes the decompression path and zip-bomb exposure from Next.js.

Remove the temporary experimental.disableResumeDataCacheCompression rollout flag together with the deflate and inflate branches, making raw JSON the only persisted representation.

Retain serializePostponedState as the single construction path for the postponed-state wire format so HTML and data serialization cannot drift.

The existing postponed-state request-body size limit remains in place. Parsing diagnostics and tests cover truncated or malformed JSON cache tails.

## Verification

- pnpm build-all
- pnpm exec jest packages/next/src/server/resume-data-cache/resume-data-cache.test.ts packages/next/src/server/app-render/postponed-state.test.ts --runInBand
- pnpm --filter=next types

<!-- NEXT_JS_LLM -->
parent fef4c28b
......@@ -953,9 +953,6 @@ export function createAppPageEntrypoint({
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
nextConfig.experimental.maxPostponedStateSize
),
disableResumeDataCacheCompression:
nextConfig.experimental.disableResumeDataCacheCompression ??
false,
exposeTestingApi,
},
......
......@@ -184,8 +184,6 @@ async function requestHandler(
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
nextConfig.experimental.maxPostponedStateSize
),
disableResumeDataCacheCompression:
nextConfig.experimental.disableResumeDataCacheCompression ?? false,
exposeTestingApi:
nextConfig.cacheComponents === true &&
(pageRouteModule.isDev === true ||
......
......@@ -521,8 +521,6 @@ async function exportAppImpl(
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
nextConfig.experimental.maxPostponedStateSize
),
disableResumeDataCacheCompression:
nextConfig.experimental.disableResumeDataCacheCompression ?? false,
exposeTestingApi:
nextConfig.experimental.exposeTestingApiInProductionBuild === true,
},
......
......@@ -28,10 +28,7 @@ import { AfterRunner } from '../../server/after/run-with-after'
import type { RequestLifecycleOpts } from '../../server/base-server'
import type { AppSharedContext } from '../../server/app-render/app-render'
import type { MultiFileWriter } from '../../lib/multi-file-writer'
import {
deflateResumeDataCache,
stringifyResumeDataCache,
} from '../../server/resume-data-cache/resume-data-cache'
import { stringifyResumeDataCache } from '../../server/resume-data-cache/resume-data-cache'
import {
UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
......@@ -231,19 +228,6 @@ export async function exportAppPage(
JSON.stringify(meta, null, 2)
)
let serializedRenderResumeDataCache: string | undefined
if (renderResumeDataCache) {
serializedRenderResumeDataCache = await stringifyResumeDataCache(
renderResumeDataCache,
renderOpts.cacheComponents
)
if (!renderOpts.experimental.disableResumeDataCacheCompression) {
serializedRenderResumeDataCache = deflateResumeDataCache(
serializedRenderResumeDataCache
)
}
}
return {
// Filter the metadata if the environment does not have next support.
metadata: hasNextSupport
......@@ -259,7 +243,12 @@ export async function exportAppPage(
hasStaticRsc,
cacheControl,
fetchMetrics,
renderResumeDataCache: serializedRenderResumeDataCache,
renderResumeDataCache: renderResumeDataCache
? await stringifyResumeDataCache(
renderResumeDataCache,
renderOpts.cacheComponents
)
: undefined,
}
} catch (err) {
if (!isDynamicUsageError(err)) {
......
......@@ -413,11 +413,7 @@ export async function exportPages(
process.env.NODE_OPTIONS?.includes('--inspect')
const renderResumeDataCache = renderResumeDataCachesByPage[pageKey]
? createRenderResumeDataCache(
renderResumeDataCachesByPage[pageKey],
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
)
? createRenderResumeDataCache(renderResumeDataCachesByPage[pageKey])
: undefined
while (attempt < maxAttempts) {
......
......@@ -3310,17 +3310,13 @@ function prepareAppPage(
postponedState = {
type: DynamicState.DATA,
renderResumeDataCache: parseResumeDataCacheFromPostponedState(
renderOpts.postponed,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
renderOpts.postponed
),
}
} else {
postponedState = parsePostponedState(
renderOpts.postponed,
interpolatedParams,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
interpolatedParams
)
}
}
......@@ -9425,16 +9421,12 @@ async function prerenderToStream(
: DynamicHTMLPreludeState.Full,
fallbackRouteParams,
resumeDataCache,
cacheComponents,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
cacheComponents
)
} else {
metadata.postponed = await getDynamicDataPostponedState(
resumeDataCache,
cacheComponents,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
cacheComponents
)
}
reactServerResult.consume()
......@@ -9958,9 +9950,7 @@ async function prerenderToStream(
if (originalFlightPrerenderResultIsDynamic) {
metadata.postponed = await getDynamicDataPostponedState(
originalResumeDataCache,
cacheComponents,
renderOpts.experimental.maxPostponedStateSizeBytes,
renderOpts.experimental.disableResumeDataCacheCompression
cacheComponents
)
originalFlightPrerenderResult.consume()
errorServerResult.consume()
......
import {
createPrerenderResumeDataCache,
stringifyResumeDataCache,
} from '../resume-data-cache/resume-data-cache'
import { createPrerenderResumeDataCache } from '../resume-data-cache/resume-data-cache'
import {
streamFromString,
streamToString,
......@@ -18,7 +15,6 @@ import type {
OpaqueFallbackRouteParams,
OpaqueFallbackRouteParamValue,
} from '../request/fallback-params'
import { CachedRouteKind } from '../response-cache/types'
export function createMockOpaqueFallbackRouteParams(
params: Record<string, OpaqueFallbackRouteParamValue>
......@@ -62,7 +58,7 @@ describe('getDynamicHTMLPostponedState', () => {
isCacheComponentsEnabled
)
const parsed = parsePostponedState(state, { slug: '123' }, undefined)
const parsed = parsePostponedState(state, { slug: '123' })
expect(parsed).toMatchInlineSnapshot(`
{
......@@ -122,7 +118,7 @@ describe('getDynamicHTMLPostponedState', () => {
const value = 'hello'
const params = { slug: value }
const parsed = parsePostponedState(state, params, undefined)
const parsed = parsePostponedState(state, params)
expect(parsed).toEqual({
type: DynamicState.HTML,
data: [1, { [value]: value }],
......@@ -149,79 +145,6 @@ describe('getDynamicDataPostponedState', () => {
)
expect(state).toMatchInlineSnapshot(`"4:nullnull"`)
})
it('serializes and parses an uncompressed cache when compression is disabled', async () => {
const resumeDataCache = createPrerenderResumeDataCache()
resumeDataCache.fetch.set('cache-key', {
kind: CachedRouteKind.FETCH,
data: {
headers: {},
body: 'cached body',
url: 'https://example.com',
},
revalidate: 60,
})
const serializedResumeDataCache = await stringifyResumeDataCache(
resumeDataCache,
isCacheComponentsEnabled
)
const state = await getDynamicDataPostponedState(
resumeDataCache,
isCacheComponentsEnabled,
undefined,
true
)
expect(state).toBe(`4:null${serializedResumeDataCache}`)
const parsed = parsePostponedState(state, {}, undefined, true)
expect(parsed.renderResumeDataCache.fetch.get('cache-key')).toEqual(
resumeDataCache.fetch.get('cache-key')
)
})
it('warns when the uncompressed state would exceed the size limit', async () => {
const resumeDataCache = createPrerenderResumeDataCache()
resumeDataCache.fetch.set('cache-key', {
kind: CachedRouteKind.FETCH,
data: {
headers: {},
body: '💥'.repeat(2048),
url: 'https://example.com',
},
revalidate: 60,
})
const serializedResumeDataCache = await stringifyResumeDataCache(
resumeDataCache,
isCacheComponentsEnabled
)
const uncompressedStateByteLength = Buffer.byteLength(
`4:null${serializedResumeDataCache}`
)
const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})
await getDynamicDataPostponedState(
resumeDataCache,
isCacheComponentsEnabled,
uncompressedStateByteLength
)
expect(warn).not.toHaveBeenCalled()
await getDynamicDataPostponedState(
resumeDataCache,
isCacheComponentsEnabled,
uncompressedStateByteLength - 1
)
expect(warn).toHaveBeenCalledWith(
expect.stringContaining(
`The uncompressed postponed state is ${uncompressedStateByteLength} bytes`
)
)
warn.mockRestore()
})
})
describe('parseResumeDataCacheFromPostponedState', () => {
......@@ -258,10 +181,7 @@ describe('parseResumeDataCacheFromPostponedState', () => {
isCacheComponentsEnabled
)
const resumeDataCache = parseResumeDataCacheFromPostponedState(
state,
undefined
)
const resumeDataCache = parseResumeDataCacheFromPostponedState(state)
const value = await resumeDataCache.cache.get('cache-key')
expect(value).toBeDefined()
......@@ -277,7 +197,7 @@ describe('parsePostponedState', () => {
const params = {
slug: Math.random().toString(16).slice(3),
}
const parsed = parsePostponedState(state, params, undefined)
const parsed = parsePostponedState(state, params)
// Ensure that it parsed it correctly.
expect(parsed).toEqual({
......@@ -300,7 +220,7 @@ describe('parsePostponedState', () => {
it('parses a HTML postponed state without fallback params', () => {
const state = `2:{}null`
const params = {}
const parsed = parsePostponedState(state, params, undefined)
const parsed = parsePostponedState(state, params)
// Ensure that it parsed it correctly.
expect(parsed).toEqual({
......@@ -319,7 +239,7 @@ describe('parsePostponedState', () => {
it('parses a data postponed state', () => {
const state = '4:nullnull'
const parsed = parsePostponedState(state, {}, undefined)
const parsed = parsePostponedState(state, {})
// Ensure that it parsed it correctly.
expect(parsed).toEqual({
......
......@@ -7,7 +7,6 @@ import type { Params } from '../request/params'
import {
createPrerenderResumeDataCache,
createRenderResumeDataCache,
deflateResumeDataCache,
stringifyResumeDataCache,
type PrerenderResumeDataCache,
type RenderResumeDataCache,
......@@ -79,34 +78,14 @@ export type PostponedState =
async function serializePostponedState(
postponedString: string,
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache,
isCacheComponentsEnabled: boolean,
maxPostponedStateSizeBytes: number | undefined,
disableResumeDataCacheCompression: boolean
isCacheComponentsEnabled: boolean
): Promise<string> {
const prefix = `${postponedString.length}:${postponedString}`
let serializedResumeDataCache = await stringifyResumeDataCache(
const serializedResumeDataCache = await stringifyResumeDataCache(
resumeDataCache,
isCacheComponentsEnabled
)
if (!disableResumeDataCacheCompression) {
if (maxPostponedStateSizeBytes !== undefined) {
const uncompressedPostponedStateByteLength =
Buffer.byteLength(prefix) + Buffer.byteLength(serializedResumeDataCache)
if (uncompressedPostponedStateByteLength > maxPostponedStateSizeBytes) {
console.warn(
`The uncompressed postponed state is ${uncompressedPostponedStateByteLength} bytes, which exceeds the configured experimental.maxPostponedStateSize limit of ${maxPostponedStateSizeBytes} bytes. Next.js currently compresses the Resume Data Cache before persisting the postponed state, but this compression will be removed in a future release. Increase experimental.maxPostponedStateSize to ensure this route can still be resumed after that change.`
)
}
}
serializedResumeDataCache = deflateResumeDataCache(
serializedResumeDataCache
)
}
return prefix + serializedResumeDataCache
return `${postponedString.length}:${postponedString}${serializedResumeDataCache}`
}
export async function getDynamicHTMLPostponedState(
......@@ -114,9 +93,7 @@ export async function getDynamicHTMLPostponedState(
preludeState: DynamicHTMLPreludeState,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache,
isCacheComponentsEnabled: boolean,
maxPostponedStateSizeBytes?: number,
disableResumeDataCacheCompression = false
isCacheComponentsEnabled: boolean
): Promise<string> {
const data: DynamicHTMLPostponedState['data'] = [preludeState, postponed]
const dataString = JSON.stringify(data)
......@@ -128,9 +105,7 @@ export async function getDynamicHTMLPostponedState(
return serializePostponedState(
dataString,
resumeDataCache,
isCacheComponentsEnabled,
maxPostponedStateSizeBytes,
disableResumeDataCacheCompression
isCacheComponentsEnabled
)
}
......@@ -146,32 +121,22 @@ export async function getDynamicHTMLPostponedState(
return serializePostponedState(
postponedString,
resumeDataCache,
isCacheComponentsEnabled,
maxPostponedStateSizeBytes,
disableResumeDataCacheCompression
isCacheComponentsEnabled
)
}
export async function getDynamicDataPostponedState(
resumeDataCache: PrerenderResumeDataCache | RenderResumeDataCache,
isCacheComponentsEnabled: boolean,
maxPostponedStateSizeBytes?: number,
disableResumeDataCacheCompression = false
isCacheComponentsEnabled: boolean
): Promise<string> {
return serializePostponedState(
'null',
resumeDataCache,
isCacheComponentsEnabled,
maxPostponedStateSizeBytes,
disableResumeDataCacheCompression
isCacheComponentsEnabled
)
}
function parsePostponedStateParts(
state: string,
maxPostponedStateSizeBytes: number | undefined,
disableResumeDataCacheCompression: boolean
): {
function parsePostponedStateParts(state: string): {
postponedString: string
renderResumeDataCache: RenderResumeDataCache
} {
......@@ -191,25 +156,15 @@ function parsePostponedStateParts(
postponedStringLengthMatch.length + 1,
tailStart
),
renderResumeDataCache: createRenderResumeDataCache(
state.slice(tailStart),
maxPostponedStateSizeBytes,
disableResumeDataCacheCompression
),
renderResumeDataCache: createRenderResumeDataCache(state.slice(tailStart)),
}
}
export function parseResumeDataCacheFromPostponedState(
state: string,
maxPostponedStateSizeBytes: number | undefined,
disableResumeDataCacheCompression = false
state: string
): RenderResumeDataCache {
try {
return parsePostponedStateParts(
state,
maxPostponedStateSizeBytes,
disableResumeDataCacheCompression
).renderResumeDataCache
return parsePostponedStateParts(state).renderResumeDataCache
} catch (err) {
console.error(
'Failed to parse postponed state',
......@@ -221,16 +176,11 @@ export function parseResumeDataCacheFromPostponedState(
export function parsePostponedState(
state: string,
interpolatedParams: Params,
maxPostponedStateSizeBytes: number | undefined,
disableResumeDataCacheCompression = false
interpolatedParams: Params
): PostponedState {
try {
const { postponedString, renderResumeDataCache } = parsePostponedStateParts(
state,
maxPostponedStateSizeBytes,
disableResumeDataCacheCompression
)
const { postponedString, renderResumeDataCache } =
parsePostponedStateParts(state)
try {
if (postponedString === 'null') {
......@@ -318,14 +268,12 @@ export function parsePostponedState(
* sensitive) serialized contents. Every field is a size, a structural flag, or
* an error code, never the state bytes themselves.
*
* The serialized layout is `<N>:<postponedString><cache>`. The cache is a
* base64-deflate string by default and raw JSON when RDC compression is
* disabled, so these fields distinguish the failure shapes:
* The serialized layout is `<N>:<postponedString><JSON cache>`, so
* these fields distinguish the failure shapes:
* - `postponedStringComplete: false`: the declared length `N` exceeds what
* actually arrived, i.e. the postponed string itself was truncated.
* - `errorCode: 'Z_BUF_ERROR'` with an empty or short tail: the
* resume-data-cache tail was truncated (ran out of input while inflating).
* - `errorCode: 'Z_DATA_ERROR'`: the tail bytes are corrupt, not merely short.
* - `errorName: 'SyntaxError'` with an empty or short tail: the
* resume-data-cache tail was truncated or malformed.
* - `hasLengthPrefix: false`: the body had no `<N>:` prefix at all (e.g. empty
* or otherwise malformed input).
*/
......
......@@ -172,15 +172,10 @@ export interface RenderOptsPartial {
/**
* The maximum size (in bytes) of the postponed state body for PPR resume
* requests. Used to calculate decompression limits (5x this value).
* requests.
*/
maxPostponedStateSizeBytes: number | undefined
/**
* Whether the Resume Data Cache should be persisted without compression.
*/
disableResumeDataCacheCompression: boolean
/**
* Whether the Instant Navigation Testing API is exposed (dev mode or the
* `exposeTestingApiInProductionBuild` flag). When true, the prerendered
......
......@@ -611,9 +611,6 @@ export default abstract class Server<
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
this.nextConfig.experimental.maxPostponedStateSize
),
disableResumeDataCacheCompression:
this.nextConfig.experimental.disableResumeDataCacheCompression ??
false,
exposeTestingApi:
this.nextConfig.cacheComponents === true &&
(this.dev === true ||
......
......@@ -251,7 +251,6 @@ export const experimentalSchema = {
})
.optional(),
maxPostponedStateSize: zSizeLimit.optional(),
disableResumeDataCacheCompression: z.boolean().optional(),
// The original type was Record<string, any>
extensionAlias: z.record(z.string(), z.any()).optional(),
externalDir: z.boolean().optional(),
......
......@@ -1182,13 +1182,6 @@ export interface ExperimentalConfig {
*/
maxPostponedStateSize?: SizeLimit
/**
* Disables compression of the Resume Data Cache (RDC) when persisting
* postponed state.
* @default false
*/
disableResumeDataCacheCompression?: boolean
/**
* enables the minification of server code.
*
......@@ -2306,7 +2299,6 @@ export const defaultConfig = Object.freeze({
globalNotFound: false,
browserDebugInfoInTerminal: 'warn',
lockDistDir: true,
disableResumeDataCacheCompression: false,
proxyClientMaxBodySize: 10_485_760, // 10MB
hideLogsAfterAbort: false,
mcpServer: true,
......@@ -2418,7 +2410,6 @@ export interface NextConfigRuntime {
| 'testProxy'
| 'runtimeServerDeploymentId'
| 'maxPostponedStateSize'
| 'disableResumeDataCacheCompression'
| 'cachedNavigations'
| 'exposeTestingApiInProductionBuild'
| 'instantInsights'
......@@ -2486,7 +2477,6 @@ export function getNextConfigRuntime(
testProxy: ex.testProxy,
runtimeServerDeploymentId: ex.runtimeServerDeploymentId,
maxPostponedStateSize: ex.maxPostponedStateSize,
disableResumeDataCacheCompression: ex.disableResumeDataCacheCompression,
cachedNavigations: ex.cachedNavigations,
exposeTestingApiInProductionBuild: ex.exposeTestingApiInProductionBuild,
instantInsights: ex.instantInsights,
......
import {
deflateResumeDataCache,
stringifyResumeDataCache,
createRenderResumeDataCache,
} from './resume-data-cache'
......@@ -150,14 +149,12 @@ describe('stringifyResumeDataCache', () => {
})
describe('parseResumeDataCache', () => {
it('throws in the edge runtime before handling an uncompressed cache', () => {
it('throws in the edge runtime before parsing an empty cache', () => {
const nextRuntime = process.env.NEXT_RUNTIME
process.env.NEXT_RUNTIME = 'edge'
try {
expect(() =>
createRenderResumeDataCache('null', undefined, true)
).toThrow(
expect(() => createRenderResumeDataCache('null')).toThrow(
'`createRenderResumeDataCache` should not be called in edge runtime.'
)
} finally {
......@@ -170,7 +167,7 @@ describe('parseResumeDataCache', () => {
})
it('parses an empty cache', () => {
const parsed = createRenderResumeDataCache('null', undefined)
const parsed = createRenderResumeDataCache('null')
expect(parsed.cache).toEqual(new Map())
expect(parsed.fetch).toEqual(new Map())
expect(parsed.encryptedBoundArgs).toEqual(new Map())
......@@ -178,26 +175,16 @@ describe('parseResumeDataCache', () => {
expect(parsed.dynamicCacheKeys).toBeUndefined()
})
it.each([false, true])(
'parses a filled cache with compression disabled: %s',
async (disableResumeDataCacheCompression) => {
const cache = createMockedCache()
const serialized = await stringifyResumeDataCache(
cache,
isCacheComponentsEnabled
)
it('parses a filled cache', async () => {
const cache = createMockedCache()
const serialized = await stringifyResumeDataCache(
cache,
isCacheComponentsEnabled
)
const persisted = disableResumeDataCacheCompression
? serialized
: deflateResumeDataCache(serialized)
const parsed = createRenderResumeDataCache(
persisted,
undefined,
disableResumeDataCacheCompression
)
const parsed = createRenderResumeDataCache(serialized)
expect(parsed.cache.size).toBe(isCacheComponentsEnabled ? 1 : 3)
expect(parsed.fetch.size).toBe(0)
}
)
expect(parsed.cache.size).toBe(isCacheComponentsEnabled ? 1 : 3)
expect(parsed.fetch.size).toBe(0)
})
})
......@@ -199,25 +199,6 @@ export async function stringifyResumeDataCache(
return JSON.stringify(json)
}
export function deflateResumeDataCache(
serializedResumeDataCache: string
): string {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'`deflateResumeDataCache` should not be called in edge runtime.'
)
} else {
if (serializedResumeDataCache === 'null') {
return serializedResumeDataCache
}
// Compress the JSON string using zlib. As the data is already in memory,
// we use the synchronous deflateSync function.
const { deflateSync } = require('node:zlib') as typeof import('node:zlib')
return deflateSync(serializedResumeDataCache).toString('base64')
}
}
/**
* Creates a new empty mutable resume data cache for pre-rendering.
* Initializes fresh Map instances for both the 'use cache' and fetch caches.
......@@ -261,96 +242,55 @@ export function createPrerenderResumeDataCache(
* @param renderResumeDataCache - A RenderResumeDataCache instance to be used directly
* @param prerenderResumeDataCache - A PrerenderResumeDataCache instance to convert to immutable
* @param persistedCache - A serialized cache string to parse
* @param maxPostponedStateSizeBytes - The max compressed size limit in bytes (used to calculate 5x decompression limit)
* @param disableResumeDataCacheCompression - Whether the persisted cache is raw JSON instead of compressed
* @returns An immutable RenderResumeDataCache instance
*/
export function createRenderResumeDataCache(
resumeDataCache: ResumeDataCache
): RenderResumeDataCache
export function createRenderResumeDataCache(
persistedCache: string,
maxPostponedStateSizeBytes: number | undefined,
disableResumeDataCacheCompression?: boolean
persistedCache: string
): RenderResumeDataCache
export function createRenderResumeDataCache(
resumeDataCacheOrPersistedCache: ResumeDataCache | string,
maxPostponedStateSizeBytes?: number | undefined,
disableResumeDataCacheCompression = false
resumeDataCacheOrPersistedCache: ResumeDataCache | string
): RenderResumeDataCache {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'`createRenderResumeDataCache` should not be called in edge runtime.'
)
} else {
if (typeof resumeDataCacheOrPersistedCache !== 'string') {
// If the cache is already read-only, return it directly. Otherwise we
// perform a type change by overriding the discriminator — the underlying
// Map references are still shared, but callers should treat the result
// as immutable.
if (!resumeDataCacheOrPersistedCache.mutable) {
return resumeDataCacheOrPersistedCache
}
return { ...resumeDataCacheOrPersistedCache, mutable: false }
}
if (resumeDataCacheOrPersistedCache === 'null') {
return {
mutable: false,
cache: new Map(),
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
}
}
let serializedResumeDataCache = resumeDataCacheOrPersistedCache
if (!disableResumeDataCacheCompression) {
// This should be a compressed string. Let's decompress it using zlib.
// As the data we already want to decompress is in memory, we use the
// synchronous inflateSync function.
const { inflateSync } = require('node:zlib') as typeof import('node:zlib')
// Limit decompressed size to prevent zipbomb attacks. This is 5x the
// configured maxPostponedStateSize, allowing reasonable compression
// ratios while preventing extreme decompression bombs.
// Default is 500MB (5x the default 100MB compressed limit).
const maxDecompressedSize = maxPostponedStateSizeBytes
? maxPostponedStateSizeBytes * 5
: 500 * 1024 * 1024
}
try {
serializedResumeDataCache = inflateSync(
Buffer.from(serializedResumeDataCache, 'base64'),
{
maxOutputLength: maxDecompressedSize,
}
).toString('utf-8')
} catch (err: unknown) {
if (
err instanceof RangeError &&
(err as NodeJS.ErrnoException).code === 'ERR_BUFFER_TOO_LARGE'
) {
throw new Error(
`Decompressed resume data cache exceeded ${maxDecompressedSize} byte limit`
)
}
throw err
}
if (typeof resumeDataCacheOrPersistedCache !== 'string') {
// If the cache is already read-only, return it directly. Otherwise we
// perform a type change by overriding the discriminator — the underlying
// Map references are still shared, but callers should treat the result
// as immutable.
if (!resumeDataCacheOrPersistedCache.mutable) {
return resumeDataCacheOrPersistedCache
}
return { ...resumeDataCacheOrPersistedCache, mutable: false }
}
const json = JSON.parse(serializedResumeDataCache) as ResumeStoreSerialized
if (resumeDataCacheOrPersistedCache === 'null') {
return {
mutable: false,
cache: parseUseCacheCacheStore(Object.entries(json.store.cache)),
fetch: new Map(Object.entries(json.store.fetch)),
encryptedBoundArgs: new Map(
Object.entries(json.store.encryptedBoundArgs)
),
cache: new Map(),
fetch: new Map(),
encryptedBoundArgs: new Map(),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
}
}
const json = JSON.parse(
resumeDataCacheOrPersistedCache
) as ResumeStoreSerialized
return {
mutable: false,
cache: parseUseCacheCacheStore(Object.entries(json.store.cache)),
fetch: new Map(Object.entries(json.store.fetch)),
encryptedBoundArgs: new Map(Object.entries(json.store.encryptedBoundArgs)),
decryptedBoundArgs: new Map(),
imageResponses: new Map(),
}
}
......@@ -1828,7 +1828,6 @@ function extractResumeDataCacheFromPostponedState(
const postponedStringLength = parseInt(postponedStringLengthMatch)
return createRenderResumeDataCache(
state.slice(postponedStringLengthMatch.length + postponedStringLength + 1),
undefined
state.slice(postponedStringLengthMatch.length + postponedStringLength + 1)
)
}
import { nextTestSetup } from 'e2e-utils'
import { createNowRouteMatches, retry } from 'next-test-utils'
import zlib from 'node:zlib'
const MATCHED_PATH = '/dynamic/[slug]'
const PARSE_ERROR = 'Failed to parse postponed state'
// A real deflate stream (base64) of a representative resume-data-cache payload.
// Slicing this produces the truncated/corrupt tails used by the cases below.
// A representative serialized resume-data-cache payload. Slicing this produces
// the truncated/malformed tails used by the cases below.
function validResumeDataCacheTail(): string {
return zlib
.deflateSync(
JSON.stringify({
store: { cache: {}, fetch: { a: 1 }, encryptedBoundArgs: {} },
})
)
.toString('base64')
return JSON.stringify({
store: { cache: {}, fetch: { a: 1 }, encryptedBoundArgs: {} },
})
}
// These tests exercise the real minimal-mode resume path: the body of a
......@@ -51,7 +46,7 @@ describe('postponed resume - parse failure diagnostics', () => {
return { response, outputIndex }
}
it('reports a truncated postponed string (incomplete delivery) as Z_BUF', async () => {
it('reports a truncated postponed string (incomplete delivery)', async () => {
// Declares a 100-char postponed string but delivers far fewer bytes, so the
// postponed string itself is short and the resume-data-cache tail is empty.
const { response, outputIndex } = await postResume('a', '100:short')
......@@ -63,11 +58,11 @@ describe('postponed resume - parse failure diagnostics', () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toContain(PARSE_ERROR)
expect(cliOutput).toContain('postponedStringComplete: false')
expect(cliOutput).toContain('Z_BUF_ERROR')
expect(cliOutput).toContain("errorName: 'SyntaxError'")
})
})
it('reports a truncated resume-data-cache tail (complete string) as Z_BUF', async () => {
it('reports a truncated resume-data-cache tail (complete string)', async () => {
const tail = validResumeDataCacheTail()
const truncatedTail = tail.slice(0, tail.length - 12)
const { response, outputIndex } = await postResume(
......@@ -81,14 +76,13 @@ describe('postponed resume - parse failure diagnostics', () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toContain(PARSE_ERROR)
expect(cliOutput).toContain('postponedStringComplete: true')
expect(cliOutput).toContain('Z_BUF_ERROR')
expect(cliOutput).toContain("errorName: 'SyntaxError'")
})
})
it('reports a corrupt resume-data-cache tail as Z_DATA (a real bug to surface)', async () => {
it('reports a malformed resume-data-cache tail', async () => {
const tail = validResumeDataCacheTail()
// Dropping the leading bytes corrupts the deflate header, which is a
// content corruption rather than a short read.
// Dropping the leading bytes makes the JSON malformed rather than short.
const corruptTail = tail.slice(6)
const { response, outputIndex } = await postResume('c', `1:x${corruptTail}`)
......@@ -97,7 +91,7 @@ describe('postponed resume - parse failure diagnostics', () => {
await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toContain(PARSE_ERROR)
expect(cliOutput).toContain('Z_DATA_ERROR')
expect(cliOutput).toContain("errorName: 'SyntaxError'")
})
})
......
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