File size: 11,302 Bytes
4514571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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":"<actionId>",...}'
   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.