From ce030fdf766270b93c77ebd00f463cdea9a160be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samy=20Pess=C3=A9?= Date: Fri, 21 Mar 2025 00:46:39 +0100 Subject: [PATCH] v2: Fix redirect to strip jwt_token in url-host mode (#3014) --- packages/gitbook-v2/src/middleware.ts | 10 ++++++---- packages/gitbook/src/lib/visitor-token.ts | 10 +++++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/packages/gitbook-v2/src/middleware.ts b/packages/gitbook-v2/src/middleware.ts index 79d5929bb..b7904a578 100644 --- a/packages/gitbook-v2/src/middleware.ts +++ b/packages/gitbook-v2/src/middleware.ts @@ -141,10 +141,12 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) { // Make sure the URL is clean of any va token after a successful lookup // The token is stored in a cookie that is set on the redirect response // - const requestURLWithoutToken = normalizeVisitorAuthURL( - mode === 'url' ? requestURL : siteURL - ); - if (requestURLWithoutToken.toString() !== requestURL.toString()) { + const incomingURL = mode === 'url' ? requestURL : siteURL; + const requestURLWithoutToken = normalizeVisitorAuthURL(incomingURL); + if ( + requestURLWithoutToken !== incomingURL && + requestURLWithoutToken.toString() !== incomingURL.toString() + ) { return writeResponseCookies( NextResponse.redirect(requestURLWithoutToken.toString()), cookies diff --git a/packages/gitbook/src/lib/visitor-token.ts b/packages/gitbook/src/lib/visitor-token.ts index 3350da828..64f0c9793 100644 --- a/packages/gitbook/src/lib/visitor-token.ts +++ b/packages/gitbook/src/lib/visitor-token.ts @@ -151,9 +151,13 @@ export function getVisitorAuthCookieValue(basePath: string, token: string): stri * Normalize the URL by removing the visitor authentication token from the query parameters (if present). */ export function normalizeVisitorAuthURL(url: URL): URL { - const withoutVAParam = new URL(url); - withoutVAParam.searchParams.delete(VISITOR_AUTH_PARAM); - return withoutVAParam; + if (url.searchParams.has(VISITOR_AUTH_PARAM)) { + const withoutVAParam = new URL(url); + withoutVAParam.searchParams.delete(VISITOR_AUTH_PARAM); + return withoutVAParam; + } + + return url; } /**