diff --git a/packages/next/src/server/app-render/action-handler.ts b/packages/next/src/server/app-render/action-handler.ts index 76b065a1fc..cdaf8464f6 100644 --- a/packages/next/src/server/app-render/action-handler.ts +++ b/packages/next/src/server/app-render/action-handler.ts @@ -56,10 +56,15 @@ import { type ServerModuleMap, getServerActionsManifest, getServerModuleMap, + getActionNotFoundError, + getInvalidServerReferenceIdError, } from './manifests-singleton' import { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers' import { normalizeFilePath } from './segment-explorer-path' -import { extractInfoFromServerReferenceId } from '../../shared/lib/server-reference-info' +import { + extractInfoFromServerReferenceId, + mightBeServerReferenceId, +} from '../../shared/lib/server-reference-info' import type { ServerActionLogInfo } from '../dev/server-action-logger' import { RedirectStatusCode } from '../../client/components/redirect-status-code' import { synchronizeMutableCookies } from '../async-storage/request-store' @@ -608,7 +613,11 @@ export async function handleAction({ // If the app has no server actions at all, we can 404 early. if (!hasServerActions()) { - return handleUnrecognizedFetchAction(getActionNotFoundError(actionId)) + const error = + actionId !== null && !mightBeServerReferenceId(actionId) + ? getInvalidServerReferenceIdError(actionId) + : getActionNotFoundError(actionId) + return handleUnrecognizedFetchAction(error) } if (workStore.isStaticGeneration) { @@ -1369,25 +1378,27 @@ function getActionModIdOrError( throw new InvariantError("Missing 'next-action' header.") } - const actionModId = serverModuleMap[actionId]?.id + const entry = serverModuleMap[actionId] - if (!actionModId) { - throw getActionNotFoundError(actionId) + if (entry == null) { + // The proxy throws for malformed IDs and IDs that are missing from the + // manifest. It only returns undefined when the ID collides with a + // well-known property name (e.g. `toString`) that the proxy excludes from + // server reference validation so that framework reflection probes don't + // throw. Next.js never produces such an ID, so this is almost certainly a + // probe with a known-bad ID. Repeat the manifest's throw logic here so the + // caller gets a diagnosable error instead of a `TypeError`. + throw mightBeServerReferenceId(actionId) + ? getActionNotFoundError(actionId) + : getInvalidServerReferenceIdError(actionId) } - return actionModId -} - -function getActionNotFoundError(actionId: string | null): Error { - return new Error( - `Failed to find Server Action${actionId ? ` "${actionId}"` : ''}. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action` - ) + return entry.id } const $ACTION_ = '$ACTION_' const $ACTION_REF_ = '$ACTION_REF_' const $ACTION_ID_ = '$ACTION_ID_' -const ACTION_ID_EXPECTED_LENGTH = 42 /** * This function mirrors logic inside React's decodeAction and should be kept in sync with that. @@ -1446,14 +1457,14 @@ function isInvalidStringActionDescriptor( } const from = ACTION_DESCRIPTOR_ID_PREFIX.length - const to = from + ACTION_ID_EXPECTED_LENGTH + const to = actionDescriptor.indexOf('"', from) + if (to === -1) { + return true + } // We expect actionDescriptor to be '{"id":"",...}' const actionId = actionDescriptor.slice(from, to) - if ( - actionId.length !== ACTION_ID_EXPECTED_LENGTH || - actionDescriptor[to] !== '"' - ) { + if (!mightBeServerReferenceId(actionId)) { return true } @@ -1473,15 +1484,13 @@ function isInvalidActionIdFieldName( // The field name must always start with $ACTION_ID_ but since it is // the id is extracted from the key of the field we have already validated // this before entering this function - if ( - actionIdFieldName.length !== - $ACTION_ID_.length + ACTION_ID_EXPECTED_LENGTH - ) { + const actionId = actionIdFieldName.slice($ACTION_ID_.length) + if (!mightBeServerReferenceId(actionId)) { // this field name has too few or too many characters + // or it is otherwise in the wrong format return true } - const actionId = actionIdFieldName.slice($ACTION_ID_.length) const entry = serverModuleMap[actionId] if (entry == null) { diff --git a/packages/next/src/server/app-render/manifests-singleton.ts b/packages/next/src/server/app-render/manifests-singleton.ts index 5df89c9881..e58e85aa70 100644 --- a/packages/next/src/server/app-render/manifests-singleton.ts +++ b/packages/next/src/server/app-render/manifests-singleton.ts @@ -5,6 +5,8 @@ import { InvariantError } from '../../shared/lib/invariant-error' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' +import { mightBeServerReferenceId } from '../../shared/lib/server-reference-info' +import { wellKnownProperties } from '../../shared/lib/utils/reflect-utils' import { workAsyncStorage } from './work-async-storage.external' export interface ServerModuleMap { @@ -16,6 +18,37 @@ export interface ServerModuleMap { } } +export function getActionNotFoundError(actionId: string | null): Error { + return new Error( + `Failed to find Server Action${actionId ? ` "${actionId}"` : ''}. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action` + ) +} + +export function getInvalidServerReferenceIdError(id: string): Error { + // `id` is arbitrary client-provided input. Unlike the not-found case, it has + // not passed the length gate and can reach this error via a malformed server + // reference in an action payload, so it may be of any length and contain + // control characters. `JSON.stringify` escapes newlines and quotes so it + // can't forge log lines, and truncating overly long ids prevents log + // flooding. Ids at or below the cap are logged in full so that we only add an + // ellipsis to ids that are meaningfully longer than the truncated length. + const encoded = JSON.stringify( + id.length > MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH + ? id.slice(0, TRUNCATED_SERVER_REFERENCE_ID_LENGTH) + '…' + : id + ) + + return new Error( + `The Server Reference ID did not match the expected format. Received ${encoded}.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action` + ) +} + +// Ids at or below the cap are logged in full. Longer ids are truncated to the +// shorter length and marked with an ellipsis, so the cap leaves headroom over +// the truncated length rather than ellipsizing ids that are barely too long. +const MAX_LOGGED_SERVER_REFERENCE_ID_LENGTH = 100 +const TRUNCATED_SERVER_REFERENCE_ID_LENGTH = 90 + // This is a global singleton that is, among other things, also used to // encode/decode bound args of server function closures. This can't be using a // AsyncLocalStorage as it might happen at the module level. @@ -179,48 +212,57 @@ function createProxiedClientReferenceManifest( * runtime, workers, etc. that React doesn't need to know. */ function createServerModuleMap(): ServerModuleMap { - return new Proxy( - {}, - { - get: (_, id: string) => { - const workers = - getServerActionsManifest()[ - process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node' - ]?.[id]?.workers + return new Proxy(Object.create(null) as ServerModuleMap, { + get: (target, id: string | symbol, receiver) => { + // React's debug serialization can probe the module map like a plain object. + // These probes are not server reference lookups. + if (typeof id !== 'string') { + return Reflect.get(target, id, receiver) + } - if (!workers) { - return undefined - } + if (wellKnownProperties.has(id)) { + return Reflect.get(target, id, receiver) + } - const workStore = workAsyncStorage.getStore() + if (!mightBeServerReferenceId(id)) { + throw getInvalidServerReferenceIdError(id) + } - let workerEntry: - | { moduleId: string | number; async: boolean } - | undefined - - if (workStore) { - workerEntry = workers[normalizeWorkerPageName(workStore.page)] - } else { - // If there's no work store defined, we can assume that a server - // module map is needed during module evaluation, e.g. to create a - // server action using a higher-order function. Therefore it should be - // safe to return any entry from the manifest that matches the action - // ID. They all refer to the same module ID, which must also exist in - // the current page bundle. TODO: This is currently not guaranteed in - // Turbopack, and needs to be fixed. - workerEntry = Object.values(workers).at(0) - } + const workers = + getServerActionsManifest()[ + process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node' + ]?.[id]?.workers - if (!workerEntry) { - return undefined - } + if (!workers) { + throw getActionNotFoundError(id) + } - const { moduleId, async } = workerEntry + const workStore = workAsyncStorage.getStore() + + let workerEntry: { moduleId: string | number; async: boolean } | undefined + + if (workStore) { + workerEntry = workers[normalizeWorkerPageName(workStore.page)] + } else { + // If there's no work store defined, we can assume that a server + // module map is needed during module evaluation, e.g. to create a + // server action using a higher-order function. Therefore it should be + // safe to return any entry from the manifest that matches the action + // ID. They all refer to the same module ID, which must also exist in + // the current page bundle. TODO: This is currently not guaranteed in + // Turbopack, and needs to be fixed. + workerEntry = Object.values(workers).at(0) + } - return { id: moduleId, name: id, chunks: [], async } - }, - } - ) + if (!workerEntry) { + throw getActionNotFoundError(id) + } + + const { moduleId, async } = workerEntry + + return { id: moduleId, name: id, chunks: [], async } + }, + }) } /** diff --git a/packages/next/src/shared/lib/server-reference-info.ts b/packages/next/src/shared/lib/server-reference-info.ts index b8d27b08f7..6dd8687957 100644 --- a/packages/next/src/shared/lib/server-reference-info.ts +++ b/packages/next/src/shared/lib/server-reference-info.ts @@ -4,6 +4,12 @@ export interface ServerReferenceInfo { hasRestArgs: boolean } +export const SERVER_REFERENCE_ID_LENGTH = 42 + +export function mightBeServerReferenceId(id: string): boolean { + return id.length === SERVER_REFERENCE_ID_LENGTH +} + /** * Extracts info about the server reference for the given server reference ID by * parsing the first byte of the hex-encoded ID.