Skip to content

Commit f7a9441

Browse files
committed
fix(testing): #582 dispatch() json route enforces the forgotten-await guard production uses
dispatch()'s json response-route path serialized with a bare JSON.stringify, while production (handleResponseRoute) ran a replacer that throws RESPONSE_NOT_SERIALIZABLE on a nested unresolved Promise. A consumer who forgot an await -- `path.json("/x", () => ({ data: fetchData() }))` -- saw a dispatch() unit test go green with `{"data":{}}` and a 200, while the same route 500s with application/problem+json in production. The testing primitive lied about production. Extract the production replacer into a shared stringifyJsonResponseBody() (rsc/helpers.ts, already imported by both handleResponseRoute and dispatch) and route both serialization sites through it. dispatch's existing callHandler catch turns the thrown RESPONSE_NOT_SERIALIZABLE into the same problem+json 500 production produces (RouterError -> status 500 -> createProblemDetails), so the rejection is now byte-identical across the two paths -- no behavior change in production, only in the test harness's fidelity. Userland coverage (dispatch.test.ts): a forgotten-await Promise on a json route yields a 500 application/problem+json with code RESPONSE_NOT_SERIALIZABLE, plus a non-vacuity case proving a properly-awaited value still serializes 200. This is also the first test pinning the guard at all -- the production path had no unit coverage.
1 parent c61a36f commit f7a9441

4 files changed

Lines changed: 106 additions & 21 deletions

File tree

‎packages/rangojs-router/src/rsc/helpers.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
import type { RequestContext } from "../server/request-context.js";
1212
import { resolveLocationStateEntries } from "../browser/react/location-state-shared.js";
1313
import { isRedirectResponse } from "../response-utils.js";
14+
import { RouterError } from "../errors.js";
1415
import {
1516
EXTERNAL_REDIRECT_MARKER,
1617
isExternalRedirect,
@@ -263,6 +264,37 @@ export function isCacheableStatus(status: number): boolean {
263264
return status === 200;
264265
}
265266

267+
/**
268+
* Serialize a json() response-route handler result to a JSON body string,
269+
* guarding against the forgotten-await footgun. The json() return type rejects
270+
* nested Promises at compile time, but an `as`-cast or an untyped (JS) handler
271+
* can still slip one through. A bare JSON.stringify would silently emit `{}` for
272+
* a Promise (the RSC pipeline awaits nested promises; this path does not), so
273+
* the handler would 200 with empty data instead of failing. Throw a typed
274+
* RouterError ("RESPONSE_NOT_SERIALIZABLE", status 500) so the caller's catch
275+
* turns it into the same problem+json 500 a real serialization failure produces.
276+
*
277+
* Shared by the production response-route handler (response-route-handler.ts)
278+
* and the dispatch() testing primitive (testing/dispatch.ts) so a forgotten
279+
* await is rejected identically in tests and in production.
280+
*/
281+
export function stringifyJsonResponseBody(result: unknown): string {
282+
return JSON.stringify(result, (_key, value) => {
283+
if (
284+
value != null &&
285+
typeof (value as { then?: unknown }).then === "function"
286+
) {
287+
throw new RouterError(
288+
"RESPONSE_NOT_SERIALIZABLE",
289+
"A json() response route returned a Promise (likely a forgotten " +
290+
"await). Await async values before returning so they serialize, " +
291+
"instead of emitting an empty {}.",
292+
);
293+
}
294+
return value;
295+
});
296+
}
297+
266298
/**
267299
* Convert route-level middleware entries to the format expected by
268300
* executeMiddleware. Route middleware from previewMatch carries just

‎packages/rangojs-router/src/rsc/response-route-handler.ts‎

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
isCacheableStatus,
2929
buildRouteMiddlewareEntries,
3030
mergeStubHeadersAndFinalize,
31+
stringifyJsonResponseBody,
3132
} from "./helpers.js";
3233
import { isWebSocketUpgradeResponse } from "../response-utils.js";
3334
import {
@@ -149,25 +150,11 @@ export async function handleResponseRoute<TEnv>(
149150

150151
// Handled before the MIME lookup (json is also a RESPONSE_TYPE_MIME key).
151152
if (preview.responseType === "json") {
152-
// Runtime guard: the json() return type rejects nested Promises at
153-
// compile time, but an `as`-cast or untyped (JS) handler can still slip
154-
// one through. JSON.stringify would silently emit {} for it (the
155-
// forgotten-await footgun — the RSC pipeline awaits nested promises, this
156-
// path does not). Throw a clear error instead of shipping empty data.
157-
const body = JSON.stringify(result, (_key, value) => {
158-
if (
159-
value != null &&
160-
typeof (value as { then?: unknown }).then === "function"
161-
) {
162-
throw new RouterError(
163-
"RESPONSE_NOT_SERIALIZABLE",
164-
"A json() response route returned a Promise (likely a forgotten " +
165-
"await). Await async values before returning so they serialize, " +
166-
"instead of emitting an empty {}.",
167-
);
168-
}
169-
return value;
170-
});
153+
// stringifyJsonResponseBody guards the forgotten-await footgun: a nested
154+
// Promise throws RESPONSE_NOT_SERIALIZABLE (caught below -> problem+json
155+
// 500) rather than serializing to an empty {}. Shared with dispatch() so
156+
// the rejection is identical in tests and production.
157+
const body = stringifyJsonResponseBody(result);
171158
return createResponseWithMergedHeaders(body, {
172159
status: 200,
173160
headers: { "content-type": "application/json;charset=utf-8" },

‎packages/rangojs-router/src/testing/__tests__/dispatch.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -879,6 +879,62 @@ describe("dispatch", () => {
879879
process.env.NODE_ENV = prev;
880880
}
881881
});
882+
883+
// The forgotten-await footgun: json()'s return type rejects nested Promises
884+
// at compile time, but an `as`-cast or an untyped (JS) handler slips one
885+
// through. Production (handleResponseRoute) and dispatch share
886+
// stringifyJsonResponseBody, which throws RESPONSE_NOT_SERIALIZABLE rather
887+
// than letting JSON.stringify emit an empty {}. Without the shared guard a
888+
// dispatch test would 200 with {"user":{}} while production 500s — the
889+
// exact false-green this pins shut.
890+
it("maps a forgotten-await Promise on a json route to a problem+json 500 (production parity)", async () => {
891+
const router = createRouter<{}>({}).routes(
892+
urls(({ path }) => [
893+
path.json(
894+
"/api/leak",
895+
// Cast past the compile-time guard the way a JS handler (or an
896+
// `as`-cast) would: return the Promise itself, unawaited.
897+
(() => ({ user: Promise.resolve({ id: 1 }) })) as () => object,
898+
{ name: "api.leak" },
899+
),
900+
]),
901+
) as any;
902+
903+
const res = await dispatch(router, { request: "/api/leak" });
904+
expect(res.status).toBe(500);
905+
expect(res.headers.get("content-type")).toBe(
906+
"application/problem+json;charset=utf-8",
907+
);
908+
const body = await res.json();
909+
expect(body.status).toBe(500);
910+
expect(body.code).toBe("RESPONSE_NOT_SERIALIZABLE");
911+
expect(body.title).toBe("Internal Server Error");
912+
// NODE_ENV is "test" under vitest, so the dev branch exposes the message.
913+
expect(body.detail).toMatch(/forgotten/i);
914+
});
915+
916+
// Non-vacuity: a properly awaited value (the common case) must still
917+
// serialize to a 200, so the guard isn't rejecting legitimate payloads.
918+
it("still serializes a json route whose async value is awaited (non-vacuity)", async () => {
919+
const router = createRouter<{}>({}).routes(
920+
urls(({ path }) => [
921+
path.json(
922+
"/api/ok",
923+
async () => ({ user: await Promise.resolve(1) }),
924+
{
925+
name: "api.ok",
926+
},
927+
),
928+
]),
929+
) as any;
930+
931+
const res = await dispatch(router, { request: "/api/ok" });
932+
expect(res.status).toBe(200);
933+
expect(res.headers.get("content-type")).toBe(
934+
"application/json;charset=utf-8",
935+
);
936+
expect(await res.json()).toEqual({ user: 1 });
937+
});
882938
});
883939

884940
// Content negotiation: when the router's previewMatch reports negotiated:true

‎packages/rangojs-router/src/testing/dispatch.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
* cookies/headers merge onto the 308/404 the way createResponseWithMergedHeaders
1919
* merges them in production.
2020
* - Response routes (non-RSC) -> serialized Response
21-
* - json: JSON.stringify(result) (bare value) with application/json
21+
* - json: bare value via the shared stringifyJsonResponseBody guard
22+
* (a forgotten-await nested Promise throws
23+
* RESPONSE_NOT_SERIALIZABLE -> problem+json 500, exactly as
24+
* production) with application/json
2225
* - text/html/xml/md: String(result) with the mapped MIME type
2326
* - handler returning a Response: re-wrapped like
2427
* handleResponseRoute (stub headers/cookies merged, Set-Cookie preserved,
@@ -94,6 +97,7 @@ import {
9497
finalizeResponse,
9598
interceptRedirectForPartial,
9699
mergeStubHeadersAndFinalize,
100+
stringifyJsonResponseBody,
97101
} from "../rsc/helpers.js";
98102
import { guardOutgoingRedirect } from "../rsc/redirect-guard.js";
99103
import {
@@ -177,7 +181,13 @@ function serializeResponseRouteResult(
177181
responseType: string,
178182
): Response {
179183
if (responseType === "json") {
180-
return new Response(JSON.stringify(result), {
184+
// stringifyJsonResponseBody (rsc/helpers.ts) is the SAME guard production's
185+
// handleResponseRoute uses: a nested unresolved Promise (forgotten await)
186+
// throws RESPONSE_NOT_SERIALIZABLE here, propagates to callHandler's catch,
187+
// and becomes the identical problem+json 500. A bare JSON.stringify would
188+
// serialize the Promise to {} and 200 — green in a dispatch test, 500 in
189+
// production. Reusing the production helper closes that fidelity gap.
190+
return new Response(stringifyJsonResponseBody(result), {
181191
status: 200,
182192
headers: { "content-type": "application/json;charset=utf-8" },
183193
});

0 commit comments

Comments
 (0)