Fix logic to fetch visitor auth token from cookies and cleanup URL params (#175)

* Remove va token from query params before using it for response

* sanitize
This commit is contained in:
Taran Vohra
2024-02-20 17:11:23 +05:30
committed by GitHub
parent cf1f281119
commit 258ef413b1
2 changed files with 16 additions and 3 deletions
+11 -1
View File
@@ -38,13 +38,23 @@ export function getVisitorAuthCookieValue(basePath: string, token: string): stri
return JSON.stringify(value);
}
/**
* Sanitize the URL by removing the visitor authentication token from the query parameters (if present).
*/
export function sanitizeVisitorAuthURL(url: URL): URL {
const withoutVAParam = new URL(url);
withoutVAParam.searchParams.delete(VISITOR_AUTH_PARAM);
return withoutVAParam;
}
/**
* Find the visitor authentication token from the request cookies. This is done by
* checking all cookies for a matching "visitor authentication cookie" and returning the
* best possible match for the current URL.
*/
function getVisitorAuthTokenFromCookies(request: NextRequest, url: URL): string | undefined {
const urlBasePath = url.pathname.split('/').filter(Boolean)[0] ?? '';
const urlPathParts = url.pathname.split('/').filter(Boolean);
const urlBasePath = urlPathParts.length === 0 ? `/` : `/${urlPathParts[0]}/`;
return Array.from(request.cookies).reduce<string | undefined>((acc, [name, cookie]) => {
if (name === getVisitorAuthCookieName(urlBasePath)) {
+5 -2
View File
@@ -20,6 +20,7 @@ import {
getVisitorAuthCookieName,
getVisitorAuthCookieValue,
getVisitorAuthToken,
sanitizeVisitorAuthURL,
} from '@/lib/visitor-auth';
export const config = {
@@ -166,8 +167,10 @@ export async function middleware(request: NextRequest) {
headers.set('x-gitbook-api', apiEndpoint);
}
const target = new URL(rewritePathname, request.nextUrl.toString());
target.search = url.search;
const rewrite = new URL(rewritePathname, request.nextUrl.toString());
rewrite.search = url.search;
// Make sure the target URL is clean of any va token before we use it for response
const target = sanitizeVisitorAuthURL(rewrite);
const response = writeCookies(
NextResponse.rewrite(target, {