From 6e98a57ffdc021ce39653228c23ebb1a025049e5 Mon Sep 17 00:00:00 2001 From: Wyatt Johnson Date: Thu, 28 Mar 2024 16:54:33 -0600 Subject: [PATCH] fix: ensure that the urlPathname is always a pathname --- packages/next/src/server/app-render/app-render.tsx | 3 +-- .../next/src/server/app-render/validate-url.test.ts | 13 +++++++++++++ .../{validate-url.tsx => validate-url.ts} | 4 ++-- 3 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 packages/next/src/server/app-render/validate-url.test.ts rename packages/next/src/server/app-render/{validate-url.tsx => validate-url.ts} (83%) diff --git a/packages/next/src/server/app-render/app-render.tsx b/packages/next/src/server/app-render/app-render.tsx index dcc4564c9c58c0..98582c3f5b62ba 100644 --- a/packages/next/src/server/app-render/app-render.tsx +++ b/packages/next/src/server/app-render/app-render.tsx @@ -1426,8 +1426,7 @@ export const renderToHTMLOrFlight: AppPageRender = ( query, renderOpts ) => { - // TODO: this includes query string, should it? - const pathname = validateURL(req.url) + const { pathname } = validateURL(req.url) return RequestAsyncStorageWrapper.wrap( renderOpts.ComponentMod.requestAsyncStorage, diff --git a/packages/next/src/server/app-render/validate-url.test.ts b/packages/next/src/server/app-render/validate-url.test.ts new file mode 100644 index 00000000000000..4415965c8fb740 --- /dev/null +++ b/packages/next/src/server/app-render/validate-url.test.ts @@ -0,0 +1,13 @@ +import { validateURL } from './validate-url' + +describe('validateUrl', () => { + it('should return valid pathname', () => { + expect(validateURL('/').pathname).toBe('/') + expect(validateURL('/abc').pathname).toBe('/abc') + }) + + it('should throw for invalid pathname', () => { + expect(() => validateURL('//**y/\\')).toThrow() + expect(() => validateURL('//google.com')).toThrow() + }) +}) diff --git a/packages/next/src/server/app-render/validate-url.tsx b/packages/next/src/server/app-render/validate-url.ts similarity index 83% rename from packages/next/src/server/app-render/validate-url.tsx rename to packages/next/src/server/app-render/validate-url.ts index f43b1061b4398c..723442ec4f9fb2 100644 --- a/packages/next/src/server/app-render/validate-url.tsx +++ b/packages/next/src/server/app-render/validate-url.ts @@ -1,7 +1,7 @@ const DUMMY_ORIGIN = 'http://n' const INVALID_URL_MESSAGE = 'Invalid request URL' -export function validateURL(url: string | undefined): string { +export function validateURL(url: string | undefined): URL { if (!url) { throw new Error(INVALID_URL_MESSAGE) } @@ -11,7 +11,7 @@ export function validateURL(url: string | undefined): string { if (parsed.origin !== DUMMY_ORIGIN) { throw new Error(INVALID_URL_MESSAGE) } - return url + return parsed } catch { throw new Error(INVALID_URL_MESSAGE) }