mirror of
https://github.com/cloudflare/vinext.git
synced 2026-09-14 19:04:59 +08:00
9ba0772a2e
* fix(middleware): clear nextUrl.basePath for absolute paths outside basePath (part of #1830) * fix(middleware): reconcile NextURL basePath tests and App Router regression Address two blocking issues from ask-bonk review on #1872: 1. Update 10 unit tests in tests/shims.test.ts that used basePath-stripped URLs (e.g. http://localhost/dashboard with basePath="/app") — these tests encoded the old incorrect behavior where basePath was always set from config regardless of the URL. Switch them to prefixed input URLs (http://localhost/app/dashboard) to match the new correct semantics. 2. Fix App Router regression: createNextRequest in middleware-runtime.ts was receiving normalizedPathname already stripped of basePath (App Router passes cleanPathname), so the NextRequest URL had no basePath prefix and _stripBasePath incorrectly cleared basePath to "". Fix by applying addBasePathToPathname before constructing the URL, mirroring the un-stripped URL that Next.js's adapter always passes to middleware. Also use addBasePathToPathname helper in prod-server.ts and deploy.ts closures instead of duplicating the root-path edge-case logic. * test(middleware): fix stale test assertions broken by basePath wrapper change Update 9 tests in deploy.test.ts that checked for the old simple runMiddleware passthrough ('runMiddleware: typeof runMiddleware === "function" ? runMiddleware : null') which no longer matches the generated code after the basePath re-add wrapper was introduced in the deploy adapter. Fix 1 test in app-route-handler-runtime.test.ts that incorrectly expected NextURL to re-add the basePath prefix to a URL that was already stripped of it. Per getNextPathnameInfo semantics (the fix this PR implements for #1830), basePath is only set when the pathname actually starts with the configured prefix — a stripped URL stays stripped. * fix(middleware): gate basePath re-add on in-basePath state and restore route handler URL parity - Fix the missed import assertion in tests/deploy.test.ts (the generated entry now imports addBasePathToPathname alongside hasBasePath/stripBasePath). - Gate the basePath re-add in createNextRequest on a new hadBasePath option: the unconditional re-add regressed the Pages out-of-basePath flow by re-prefixing absolute-path requests the adapters deliberately left bare, making middleware see nextUrl.basePath === "/root" instead of "". The flag defaults to URL-derived (correct for prod/deploy Pages adapters) and is asserted true by callers that pass pre-stripped URLs (App Router, dev server). - Re-add basePath in createTrackedAppRouteRequest so App Route handlers see the original prefixed request.url / nextUrl.href and an active nextUrl.basePath, matching Next.js (the routing layer strips basePath before handlers run). - Re-derive the active basePath from the configured value in NextURL._stripBasePath on every parse, so href reassignment toggles basePath like Next.js NextURL.analyze(). - Add unit tests covering the App Router nextUrl.basePath re-add, the Pages in-/out-of-basePath flows, matcher evaluation against stripped paths, and href re-derivation. * refactor(middleware): extract shared wrapMiddlewareWithBasePath helper The runMiddleware basePath re-add closure was duplicated verbatim in prod-server.ts and the generated worker entry in deploy.ts. Extract it to wrapMiddlewareWithBasePath in server/pages-request-pipeline.ts (both adapters already import from that module) to keep the two adapters in sync. * test(middleware): add unit coverage for wrapMiddlewareWithBasePath Covers the helper's gating contract directly: pass-through when hadBasePath is false or basePath is empty, prefix re-add (preserving query, headers, ctx, and opts), and idempotent re-add for an already-prefixed URL.
300 lines
12 KiB
TypeScript
300 lines
12 KiB
TypeScript
import { describe, expect, it } from "vite-plus/test";
|
|
import {
|
|
buildRouteHandlerAllowHeader,
|
|
collectRouteHandlerMethods,
|
|
createTrackedAppRouteRequest,
|
|
isKnownDynamicAppRoute,
|
|
markKnownDynamicAppRoute,
|
|
} from "../packages/vinext/src/server/app-route-handler-runtime.js";
|
|
import { NextRequest, NextURL } from "../packages/vinext/src/shims/server.js";
|
|
|
|
describe("app route handler runtime helpers", () => {
|
|
it("collects exported route handler methods and auto-adds HEAD for GET", () => {
|
|
const methods = collectRouteHandlerMethods({
|
|
GET() {},
|
|
POST() {},
|
|
default() {},
|
|
});
|
|
|
|
expect(methods).toEqual(["GET", "POST", "HEAD"]);
|
|
expect(buildRouteHandlerAllowHeader(methods)).toBe("GET, HEAD, OPTIONS, POST");
|
|
});
|
|
|
|
it("tracks direct request.headers access", () => {
|
|
const accesses: string[] = [];
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://example.com/demo", {
|
|
headers: { "x-test-ping": "pong" },
|
|
}),
|
|
{
|
|
onDynamicAccess(access) {
|
|
accesses.push(access);
|
|
},
|
|
},
|
|
);
|
|
|
|
expect(tracked.request.headers.get("x-test-ping")).toBe("pong");
|
|
expect(tracked.didAccessDynamicRequest()).toBe(true);
|
|
expect(accesses).toEqual(["request.headers"]);
|
|
});
|
|
|
|
it("stubs request-specific fields for force-static route handlers", () => {
|
|
const accesses: string[] = [];
|
|
const options = {
|
|
basePath: "",
|
|
requestMode: "force-static" as const,
|
|
onDynamicAccess(access: string) {
|
|
accesses.push(access);
|
|
},
|
|
};
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://tenant.example.com/demo?secret=from-user", {
|
|
headers: {
|
|
"cf-connecting-ip": "203.0.113.10",
|
|
"cf-ipcountry": "AU",
|
|
cookie: "session=abc",
|
|
"x-test-ping": "pong",
|
|
},
|
|
}),
|
|
options,
|
|
);
|
|
|
|
expect(tracked.request.headers.get("x-test-ping")).toBeNull();
|
|
expect(typeof tracked.request.headers.set).toBe("function");
|
|
expect(() => tracked.request.headers.set("x-test-ping", "mutated")).toThrow(
|
|
"Headers cannot be modified",
|
|
);
|
|
expect(tracked.request.headers.get("x-test-ping")).toBeNull();
|
|
expect(tracked.request.cookies.get("session")).toBeUndefined();
|
|
expect(tracked.request.ip).toBeUndefined();
|
|
expect(tracked.request.geo).toBeUndefined();
|
|
expect(tracked.request.url).toBe("http://localhost:3000/demo");
|
|
expect(tracked.request.nextUrl.href).toBe("http://localhost:3000/demo");
|
|
expect(tracked.request.nextUrl.search).toBe("");
|
|
expect(tracked.request.nextUrl.searchParams.get("secret")).toBeNull();
|
|
expect(tracked.didAccessDynamicRequest()).toBe(false);
|
|
expect(accesses).toEqual([]);
|
|
});
|
|
|
|
it("removes credentials from force-static route handler URLs", () => {
|
|
const request = new NextRequest("https://tenant.example.com/demo");
|
|
Object.defineProperty(request, "nextUrl", {
|
|
configurable: true,
|
|
value: new NextURL("https://user:pass@tenant.example.com/demo?secret=from-user#fragment"),
|
|
});
|
|
const tracked = createTrackedAppRouteRequest(request, {
|
|
requestMode: "force-static",
|
|
});
|
|
|
|
expect(tracked.request.url).toBe("http://localhost:3000/demo");
|
|
expect(tracked.request.nextUrl.href).toBe("http://localhost:3000/demo");
|
|
});
|
|
|
|
it("stubs body-reading APIs for force-static route handlers", async () => {
|
|
const accesses: string[] = [];
|
|
const createTrackedPost = () =>
|
|
createTrackedAppRouteRequest(
|
|
new Request("https://example.com/demo", {
|
|
method: "POST",
|
|
body: JSON.stringify({ secret: "from-user" }),
|
|
headers: { "content-type": "application/json" },
|
|
}),
|
|
{
|
|
requestMode: "force-static",
|
|
onDynamicAccess(access) {
|
|
accesses.push(access);
|
|
},
|
|
},
|
|
);
|
|
|
|
expect(createTrackedPost().request.body).toBeNull();
|
|
await expect(createTrackedPost().request.text()).resolves.toBe("");
|
|
await expect(createTrackedPost().request.arrayBuffer()).resolves.toHaveProperty(
|
|
"byteLength",
|
|
0,
|
|
);
|
|
await expect(createTrackedPost().request.blob()).resolves.toHaveProperty("size", 0);
|
|
await expect(createTrackedPost().request.json()).rejects.toThrow();
|
|
await expect(createTrackedPost().request.formData()).rejects.toThrow();
|
|
expect(accesses).toEqual([]);
|
|
});
|
|
|
|
it("seals force-static route handler request cookies", () => {
|
|
const tracked = createTrackedAppRouteRequest(new Request("https://example.com/demo"), {
|
|
requestMode: "force-static",
|
|
});
|
|
|
|
expect(typeof tracked.request.cookies.set).toBe("function");
|
|
expect(typeof tracked.request.cookies.delete).toBe("function");
|
|
expect(typeof tracked.request.cookies.clear).toBe("function");
|
|
expect(() => tracked.request.cookies.set("session", "abc")).toThrow(
|
|
"Cookies can only be modified",
|
|
);
|
|
expect(() => tracked.request.cookies.delete("session")).toThrow("Cookies can only be modified");
|
|
expect(() => tracked.request.cookies.clear()).toThrow("Cookies can only be modified");
|
|
});
|
|
|
|
it("throws on dynamic request access for dynamic error route handlers", () => {
|
|
const expectedMessage = (expression?: string): string =>
|
|
`Route /private with \`dynamic = "error"\` couldn't be rendered statically because it used ${expression ?? "a dynamic request API"}. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`;
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://example.com/private?token=secret", {
|
|
method: "POST",
|
|
body: "payload",
|
|
}),
|
|
{
|
|
requestMode: "error",
|
|
staticGenerationErrorMessage: expectedMessage,
|
|
},
|
|
);
|
|
|
|
expect(() => tracked.request.headers).toThrow(expectedMessage("request.headers"));
|
|
expect(() => tracked.request.cookies).toThrow(expectedMessage("request.cookies"));
|
|
expect(() => tracked.request.url).toThrow(expectedMessage("request.url"));
|
|
expect(() => tracked.request.ip).toThrow(expectedMessage("request.ip"));
|
|
expect(() => tracked.request.geo).toThrow(expectedMessage("request.geo"));
|
|
expect(() => Reflect.get(tracked.request, "body")).toThrow(expectedMessage("request.body"));
|
|
expect(() => Reflect.get(tracked.request, "blob")).toThrow(expectedMessage("request.blob"));
|
|
expect(() => Reflect.get(tracked.request, "json")).toThrow(expectedMessage("request.json"));
|
|
expect(() => Reflect.get(tracked.request, "text")).toThrow(expectedMessage("request.text"));
|
|
expect(() => Reflect.get(tracked.request, "arrayBuffer")).toThrow(
|
|
expectedMessage("request.arrayBuffer"),
|
|
);
|
|
expect(() => Reflect.get(tracked.request, "formData")).toThrow(
|
|
expectedMessage("request.formData"),
|
|
);
|
|
|
|
expect(() => tracked.request.nextUrl.search).toThrow(expectedMessage("nextUrl.search"));
|
|
expect(() => tracked.request.nextUrl.searchParams).toThrow(
|
|
expectedMessage("nextUrl.searchParams"),
|
|
);
|
|
expect(() => tracked.request.nextUrl.href).toThrow(expectedMessage("nextUrl.href"));
|
|
expect(() => tracked.request.nextUrl.origin).toThrow(expectedMessage("nextUrl.origin"));
|
|
expect(() => Reflect.get(tracked.request.nextUrl, "toString")).toThrow(
|
|
expectedMessage("nextUrl.toString"),
|
|
);
|
|
|
|
const clonedRequest = tracked.request.clone();
|
|
expect(() => clonedRequest.headers).toThrow(expectedMessage("request.headers"));
|
|
|
|
const clonedNextUrl = tracked.request.nextUrl.clone();
|
|
expect(() => clonedNextUrl.search).toThrow(expectedMessage("nextUrl.search"));
|
|
});
|
|
|
|
it("tracks request.url access for query parsing", () => {
|
|
const accesses: string[] = [];
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://example.com/demo?ping=from-url"),
|
|
{
|
|
onDynamicAccess(access) {
|
|
accesses.push(access);
|
|
},
|
|
},
|
|
);
|
|
|
|
const url = new URL(tracked.request.url);
|
|
|
|
expect(url.searchParams.get("ping")).toBe("from-url");
|
|
expect(tracked.didAccessDynamicRequest()).toBe(true);
|
|
expect(accesses).toEqual(["request.url"]);
|
|
});
|
|
|
|
it("normalizes request.url through nextUrl for stripped internal app route requests", () => {
|
|
// The App Router routing layer strips basePath before route handlers run,
|
|
// so createTrackedAppRouteRequest re-adds the configured prefix. Route
|
|
// handlers then observe the original URL Next.js would hand them:
|
|
// request.url / nextUrl.href carry the basePath prefix, while
|
|
// nextUrl.pathname stays basePath- and locale-free and nextUrl.basePath
|
|
// reports the configured value (getNextPathnameInfo semantics).
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://example.com/fr/demo?ping=from-url"),
|
|
{
|
|
basePath: "/base",
|
|
i18n: { locales: ["en", "fr"], defaultLocale: "en" },
|
|
},
|
|
);
|
|
|
|
expect(tracked.request.nextUrl.basePath).toBe("/base");
|
|
expect(tracked.request.nextUrl.pathname).toBe("/demo");
|
|
expect(tracked.request.nextUrl.href).toBe("https://example.com/base/fr/demo?ping=from-url");
|
|
expect(tracked.request.url).toBe("https://example.com/base/fr/demo?ping=from-url");
|
|
});
|
|
|
|
it("tracks request.ip and request.geo access", () => {
|
|
const accesses: string[] = [];
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://example.com/demo", {
|
|
headers: {
|
|
"cf-connecting-ip": "203.0.113.10",
|
|
"cf-ipcountry": "AU",
|
|
},
|
|
}),
|
|
{
|
|
onDynamicAccess(access) {
|
|
accesses.push(access);
|
|
},
|
|
},
|
|
);
|
|
|
|
expect(tracked.request.ip).toBe("203.0.113.10");
|
|
expect(tracked.request.geo).toEqual({ country: "AU" });
|
|
expect(tracked.didAccessDynamicRequest()).toBe(true);
|
|
expect(accesses).toEqual(["request.ip", "request.geo"]);
|
|
});
|
|
|
|
it("tracks dynamic nextUrl fields but not pathname", () => {
|
|
const accesses: string[] = [];
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://example.com/base/fr/demo?ping=from-next-url"),
|
|
{
|
|
basePath: "/base",
|
|
i18n: { locales: ["en", "fr"], defaultLocale: "en" },
|
|
onDynamicAccess(access) {
|
|
accesses.push(access);
|
|
},
|
|
},
|
|
);
|
|
|
|
expect(tracked.request.nextUrl.pathname).toBe("/demo");
|
|
expect(tracked.request.nextUrl.locale).toBe("fr");
|
|
expect(tracked.didAccessDynamicRequest()).toBe(false);
|
|
|
|
expect(tracked.request.nextUrl.searchParams.get("ping")).toBe("from-next-url");
|
|
expect(tracked.request.nextUrl.href).toBe(
|
|
"https://example.com/base/fr/demo?ping=from-next-url",
|
|
);
|
|
expect(accesses).toEqual(["nextUrl.searchParams", "nextUrl.href"]);
|
|
expect(tracked.didAccessDynamicRequest()).toBe(true);
|
|
});
|
|
|
|
it("tracks body-reading request methods without breaking Request internals", async () => {
|
|
const accesses: string[] = [];
|
|
const tracked = createTrackedAppRouteRequest(
|
|
new Request("https://example.com/demo", {
|
|
method: "POST",
|
|
body: JSON.stringify({ ok: true }),
|
|
headers: { "content-type": "application/json" },
|
|
}),
|
|
{
|
|
onDynamicAccess(access) {
|
|
accesses.push(access);
|
|
},
|
|
},
|
|
);
|
|
|
|
expect(tracked.request instanceof Request).toBe(true);
|
|
expect(tracked.request.method).toBe("POST");
|
|
expect(tracked.request.clone().headers.get("content-type")).toBe("application/json");
|
|
await expect(tracked.request.json()).resolves.toEqual({ ok: true });
|
|
expect(accesses).toEqual(["request.headers", "request.json"]);
|
|
});
|
|
|
|
it("remembers known dynamic app routes for the process lifetime", () => {
|
|
const pattern = "/tests/app-route-handler-runtime/" + Date.now();
|
|
|
|
expect(isKnownDynamicAppRoute(pattern)).toBe(false);
|
|
markKnownDynamicAppRoute(pattern);
|
|
expect(isKnownDynamicAppRoute(pattern)).toBe(true);
|
|
});
|
|
});
|