mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-21 01:53:26 +00:00
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:
+11
-1
@@ -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
@@ -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, {
|
||||
|
||||
Reference in New Issue
Block a user