Compare commits

...

3 Commits

Author SHA1 Message Date
Peter White c466ee39ea Use 500ms timeout for trailing-slash site redirect check 2026-11-30 11:53:45 +00:00
Peter White 8444cf2496 changeset 2026-11-30 11:38:43 +00:00
Peter White 543a5997ea Avoid extra trailing-slash redirect before site redirects 2026-11-30 11:38:43 +00:00
11 changed files with 999 additions and 91 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Resolve trailing-slash URLs matching a site redirect in a single hop.
@@ -6,8 +6,12 @@ import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
await import('./fetch');
const {
fetchPageData,
getLowercasePathnameRedirect,
resolveMissingPagePath,
resolveSitePageFromURL,
} = await import('./fetch');
const { normalizeURL } = await import('@/lib/data/urls');
const { createLinker } = await import('@/lib/links');
@@ -348,6 +352,81 @@ describe('resolveMissingPagePath', () => {
expect(await resolveMissingPagePath(context, 'old')).toBeUndefined();
});
it('redirects a trailing-slash request directly to the site redirect destination', async () => {
const context = {
...createRedirectContext({
siteRedirect: { target: 'https://docs.example.com/new', permanent: true },
}),
trailingSlash: true,
} as unknown as GitBookSiteContext;
let caught: unknown;
try {
await fetchPageData(context, { pathname: 'old' });
} catch (error) {
caught = error;
}
expect((caught as { digest?: string })?.digest).toContain('NEXT_REDIRECT;replace;/new;308');
});
it('keeps page precedence over a stale site redirect on a trailing-slash request', async () => {
const context = {
...createRedirectContext({
siteRedirect: {
source: '/readme',
target: 'https://docs.example.com/elsewhere',
permanent: true,
},
}),
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/',
}),
trailingSlash: true,
} as unknown as GitBookSiteContext;
let caught: unknown;
try {
await fetchPageData(context, { pathname: 'readme' });
} catch (error) {
caught = error;
}
expect((caught as { digest?: string })?.digest).toContain('NEXT_REDIRECT;replace;/;307');
});
it('redirects to the slashless URL when the renderer rejects a trailing-slash site redirect', async () => {
const context = {
...createRedirectContext({
contextId: 'adaptive-ctx',
siteRedirect: {
source: '/old',
target: 'https://docs.example.com/hidden',
permanent: true,
destination: {
kind: 'site-page',
siteSpaceId: 'site-space-hidden',
pageId: 'hidden-page',
},
},
}),
linker: createLinker({
host: 'docs.example.com',
siteBasePath: '/',
spaceBasePath: '/',
}),
trailingSlash: true,
} as unknown as GitBookSiteContext;
let caught: unknown;
try {
await fetchPageData(context, { pathname: 'old' });
} catch (error) {
caught = error;
}
expect((caught as { digest?: string })?.digest).toContain('NEXT_REDIRECT;replace;/old;307');
});
});
describe('resolveSitePageFromURL', () => {
@@ -4,20 +4,24 @@ import {
type RevisionPageDocument,
type SiteRedirect,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
} from '@gitbook/api';
import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/context';
import { getDataOrNull } from '@/lib/data';
import { type ResolvedPagePath, resolvePageId } from '@/lib/pages';
import { type ResolvedPagePath, getPagePath, resolvePageId } from '@/lib/pages';
import { withLeadingSlash } from '@/lib/paths';
import { getSiteRedirectSourceCandidates, isSameRedirectPath } from '@/lib/site-redirects';
import {
findSiteSpaceBy,
findSiteSpaceByUrl,
getSiteSpacePagePaths,
getSiteStructureSections,
resolveSiteSpaceCustomHomePage,
resolveSiteSpacePagePath,
} from '@/lib/sites';
export { isSameRedirectPath };
const MAX_PAGE_URL_REDIRECTS = 5;
export interface PagePathParams {
@@ -63,6 +67,9 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
// When resolving a page, we use the lowercased pathname
const page = resolveSiteSpacePagePath(context.siteSpace, revision.pages, pathname);
if (page) {
if (context.trailingSlash) {
redirect(getCanonicalPagePath(context, rawPathname, page.page));
}
return page;
}
@@ -73,6 +80,10 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
: redirect(fallback.destination);
}
if (!fallback && context.trailingSlash) {
redirect(context.linker.toPathForPagePath({ path: rawPathname }));
}
return fallback?.page;
}
@@ -103,21 +114,16 @@ export async function resolveMissingPagePath(
return undefined;
}
const SITE_REDIRECT_SOURCE_PATH_REGEX = new RegExp(SITE_REDIRECT_SOURCE_PATH_PATTERN);
const redirectPathname = withLeadingSlash(rawPathname);
// If a page can't be found, we try with the API, in case we have a redirect at site level.
const redirectSources = new Set(
[
// Test the pathname relative to the root
// For example hello/world -> section/variant/hello/world
linker.toRelativePathInSite(linker.toPathInSpace(redirectPathname)),
// Test the pathname relative to the content/space
// For example hello/world -> /hello/world
redirectPathname,
]
.map(toSiteRedirectSourceCandidate)
.filter((source) => SITE_REDIRECT_SOURCE_PATH_REGEX.test(source))
);
const redirectSources = getSiteRedirectSourceCandidates([
// Test the pathname relative to the root
// For example hello/world -> section/variant/hello/world
linker.toRelativePathInSite(linker.toPathInSpace(redirectPathname)),
// Test the pathname relative to the content/space
// For example hello/world -> /hello/world
redirectPathname,
]);
const currentPath = linker.toPathInSpace(redirectPathname);
let currentPathWithDefaultVariant: string | null = null;
@@ -228,39 +234,26 @@ export async function resolveSitePageFromURL(
return null;
}
export function isSameRedirectPath(currentPath: string, destination: string): boolean {
if (!destination.startsWith('/') || destination.startsWith('//')) {
return false;
}
const destinationPathname = new URL(destination, 'https://gitbook.invalid').pathname;
return (
normalizeRedirectPathname(currentPath) === normalizeRedirectPathname(destinationPathname)
function getCanonicalPagePath(
context: GitBookSiteContext,
rawPathname: string,
page: RevisionPageDocument
): string {
const customHomePage = resolveSiteSpaceCustomHomePage(
context.siteSpace,
context.revision.pages
);
}
/**
* Transform a pathname into a candidate source for site redirect matching.
* The pathname is already percent-encoded, so each segment is decoded before being encoded
* again: redirect sources store special characters percent-encoded exactly once.
*/
function toSiteRedirectSourceCandidate(pathname: string): string {
const normalized = withLeadingSlash(pathname);
return withLeadingSlash(
normalized
.slice(1)
.split('/')
.map((segment) => encodeURIComponent(safeDecodeURIComponent(segment)))
.join('/')
);
}
function safeDecodeURIComponent(segment: string): string {
try {
return decodeURIComponent(segment);
} catch {
return segment;
let expectedPagePaths = [getPagePath(context.revision.pages, page)];
if (customHomePage) {
expectedPagePaths = getSiteSpacePagePaths(context.siteSpace, context.revision.pages, page);
}
if (expectedPagePaths.includes(rawPathname)) {
return context.linker.toPathForPagePath({ path: rawPathname });
}
return context.linker.toPathForPage({
pages: context.revision.pages,
page,
});
}
async function isRedirectDestinationAccessible(
@@ -308,15 +301,6 @@ async function isRedirectDestinationAccessible(
}
}
function normalizeRedirectPathname(pathname: string): string {
const normalized = pathname
.split('/')
.filter(Boolean)
.map((segment) => safeDecodeURIComponent(segment).toLowerCase())
.join('/');
return `/${normalized}`;
}
/**
* Get the page path from the params.
*/
+11
View File
@@ -123,6 +123,11 @@ export type SiteURLData = Pick<
* Only set for the ask route, which is static and can't read the request headers.
*/
askVisitorAgent?: AskVisitorAgent;
/**
* Whether the incoming request had a trailing slash deferred for single-hop site redirects.
*/
trailingSlash?: boolean;
};
/**
@@ -242,6 +247,9 @@ export type GitBookSiteContext = GitBookSpaceContext & {
/** Whether the request comes from a detected AI agent. Only set for markdown routes. */
isAiAgent?: boolean;
/** Whether the incoming request had a trailing slash deferred for single-hop site redirects. */
trailingSlash?: boolean;
};
/**
@@ -331,6 +339,7 @@ export async function fetchSiteContextByURLLookup(
preview: data.preview ?? false,
displayAgentInstructions: data.displayAgentInstructions,
isAiAgent: data.isAiAgent,
trailingSlash: data.trailingSlash,
});
}
@@ -356,6 +365,7 @@ export async function fetchSiteContextByIds(
preview: boolean;
displayAgentInstructions?: boolean;
isAiAgent?: boolean;
trailingSlash?: boolean;
}
): Promise<GitBookSiteContext> {
const { dataFetcher } = baseContext;
@@ -512,6 +522,7 @@ export async function fetchSiteContextByIds(
preview: ids.preview,
displayAgentInstructions: ids.displayAgentInstructions,
isAiAgent: ids.isAiAgent,
trailingSlash: ids.trailingSlash,
};
}
+28 -2
View File
@@ -41,7 +41,7 @@ describe('getURLLookup', () => {
describe('normalizeRequestURL', () => {
it('does not redirect a normalized URL', () => {
const url = new URL('https://docs.mycompany.com/hello');
expect(normalizeRequestURL(url, 'url-host')).toEqual({ isNormalized: true });
expect(normalizeRequestURL(url, 'url-host')).toEqual({ status: 'normalized' });
});
it('redirects a non-normalized URL to the normalized one', () => {
@@ -59,7 +59,7 @@ describe('normalizeRequestURL', () => {
const url = new URL(
'https://proxy.gitbook.site/sites/site_abc/getting-started/quickstar%74'
);
expect(normalizeRequestURL(url, 'url-host')).toEqual({ isNormalized: false });
expect(normalizeRequestURL(url, 'url-host')).toEqual({ status: 'deferred-proxy' });
});
it('redirects a non-normalized proxied URL in url mode', () => {
@@ -73,6 +73,32 @@ describe('normalizeRequestURL', () => {
);
});
it('defers trailing-slash-only URLs when requested', () => {
const result = normalizeRequestURL(
new URL('https://docs.mycompany.com/hello/world/?foo=bar'),
'url-host',
{ deferTrailingSlash: true }
);
expect(result).toEqual({
status: 'trailing-slash',
normalizedURL: new URL('https://docs.mycompany.com/hello/world?foo=bar'),
});
});
it.each([
'https://docs.mycompany.com/hello//',
'https://docs.mycompany.com/hello/tes%74/',
'https://docs.mycompany.com/~gitbook/image/',
'https://docs.mycompany.com/docs/~gitbook/mcp/',
'https://docs.mycompany.com/robots.txt/',
'https://docs.mycompany.com/docs/robots.txt/',
'https://docs.mycompany.com/.well-known/oauth-protected-resource/~gitbook/mcp/auth/',
])('does not defer trailing slash for %s', (url) => {
const result = normalizeRequestURL(new URL(url), 'url-host', { deferTrailingSlash: true });
expect(result).toBeInstanceOf(Response);
expect((result as Response).status).toBe(302);
});
it.each([
'https://docs.mycompany.com/hello/%ZZ',
'https://proxy.gitbook.site/sites/site_abc/%ZZ',
+37 -7
View File
@@ -1,6 +1,13 @@
import { isGitBookInternalPath } from '../paths';
import { isProxyRequest, isProxyRootRequest } from '../proxy';
import { isRobotsTxtRequest } from '../robots';
import { DataFetcherError, getExposableError } from './errors';
export type RequestURLNormalization =
| { status: 'normalized' }
| { status: 'deferred-proxy' }
| { status: 'trailing-slash'; normalizedURL: URL };
/**
* For a given GitBook URL, return the URL to resolve with the API.
* Returns `null` for the root proxy URLs, which can never resolve to a site.
@@ -16,8 +23,12 @@ export function getURLLookup(input: URL): string | null {
*/
export function normalizeRequestURL(
url: URL,
mode: 'url' | 'url-host'
): Response | { isNormalized: boolean } {
mode: 'url' | 'url-host',
options?: {
/** Defer trailing-slash-only redirects so site redirects can match in one hop. */
deferTrailingSlash?: boolean;
}
): Response | RequestURLNormalization {
let normalizedURL: URL;
try {
normalizedURL = normalizeURL(url);
@@ -26,13 +37,32 @@ export function normalizeRequestURL(
return new Response(sanitized.message, { status: sanitized.code });
}
const isNormalized = normalizedURL.toString() === url.toString();
// A proxied site's public URL is only known after the lookup, which redirects to the canonical URL.
if (!isNormalized && !(mode !== 'url' && isProxyRequest(url))) {
return Response.redirect(normalizedURL.toString(), 302);
if (normalizedURL.toString() === url.toString()) {
return { status: 'normalized' };
}
return { isNormalized };
if (options?.deferTrailingSlash && isTrailingSlashOnly(url, normalizedURL)) {
if (!isGitBookInternalPath(normalizedURL.pathname) && !isRobotsTxtRequest(normalizedURL)) {
return { status: 'trailing-slash', normalizedURL };
}
}
// A proxied site's public URL is only known after the lookup, which redirects to the canonical URL.
if (mode !== 'url' && isProxyRequest(url)) {
return { status: 'deferred-proxy' };
}
return Response.redirect(normalizedURL.toString(), 302);
}
function isTrailingSlashOnly(url: URL, normalizedURL: URL): boolean {
if (url.pathname.length <= 1 || !url.pathname.endsWith('/')) {
return false;
}
const withoutTrailingSlash = new URL(url);
withoutTrailingSlash.pathname = url.pathname.slice(0, -1);
return withoutTrailingSlash.toString() === normalizedURL.toString();
}
/**
+125
View File
@@ -0,0 +1,125 @@
import {
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
} from '@gitbook/api';
import { joinPath, removeTrailingSlash, withLeadingSlash, withTrailingSlash } from './paths';
const SITE_REDIRECT_SOURCE_PATH_REGEX = new RegExp(SITE_REDIRECT_SOURCE_PATH_PATTERN);
/**
* Filter and canonically encode candidate source paths for `getSiteRedirectBySource`.
*/
export function getSiteRedirectSourceCandidates(paths: string[]): string[] {
const candidates = new Set<string>();
for (const pathname of paths) {
const encoded = toSiteRedirectSourceCandidate(pathname);
if (
encoded.length < SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH &&
SITE_REDIRECT_SOURCE_PATH_REGEX.test(encoded)
) {
candidates.add(encoded);
}
}
return Array.from(candidates);
}
/**
* Compute the site-relative path for a page pathname within a site space.
*/
export function getSiteRelativeRedirectPath(input: {
siteBasePath: string;
spaceBasePath: string;
pathname: string;
}): string {
const siteBasePath = withTrailingSlash(withLeadingSlash(input.siteBasePath));
const spaceBasePath = withTrailingSlash(withLeadingSlash(input.spaceBasePath));
const pathInSpace =
removeTrailingSlash(joinPath(spaceBasePath, withLeadingSlash(input.pathname))) || '/';
if (pathInSpace === removeTrailingSlash(siteBasePath)) {
return '/';
}
if (pathInSpace.startsWith(siteBasePath)) {
return pathInSpace.slice(siteBasePath.length);
}
return pathInSpace;
}
export function isSameRedirectPath(currentPath: string, destination: string): boolean {
if (!destination.startsWith('/') || destination.startsWith('//')) {
return false;
}
const destinationPathname = new URL(destination, 'https://gitbook.invalid').pathname;
return (
normalizeRedirectPathname(currentPath) === normalizeRedirectPathname(destinationPathname)
);
}
/**
* Check whether a resolved redirect target points back to the requested canonical URL.
*/
export function isSameSiteRedirectTarget(
canonicalURL: URL,
target: string,
options?: { markdown?: boolean }
): boolean {
let targetPathname: string;
if (target.startsWith('/') && !target.startsWith('//')) {
targetPathname = new URL(target, 'https://gitbook.invalid').pathname;
} else {
try {
const targetURL = new URL(target);
if (targetURL.hostname !== canonicalURL.hostname) {
return false;
}
targetPathname = targetURL.pathname;
} catch {
return false;
}
}
if (isSameRedirectPath(canonicalURL.pathname, targetPathname)) {
return true;
}
if (options?.markdown) {
const markdownPathname = `${removeTrailingSlash(canonicalURL.pathname) || '/'}.md`;
return isSameRedirectPath(markdownPathname, targetPathname);
}
return false;
}
/**
* Transform a pathname into a candidate source for site redirect matching.
* Redirect sources store special characters percent-encoded once.
*/
function toSiteRedirectSourceCandidate(pathname: string): string {
const normalized = withLeadingSlash(pathname);
return withLeadingSlash(
normalized
.slice(1)
.split('/')
.map((segment) => encodeURIComponent(safeDecodeURIComponent(segment)))
.join('/')
);
}
function normalizeRedirectPathname(pathname: string): string {
const normalized = pathname
.split('/')
.filter(Boolean)
.map((segment) => safeDecodeURIComponent(segment).toLowerCase())
.join('/');
return `/${normalized}`;
}
function safeDecodeURIComponent(segment: string): string {
try {
return decodeURIComponent(segment);
} catch {
return segment;
}
}
+408
View File
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
import { RequestCookiesAdapter } from 'next/dist/server/web/spec-extension/adapters/request-cookies';
import * as nextHeaders from 'next/headers';
import { NextRequest } from 'next/server';
import rison from 'rison';
import { middleware } from './middleware';
import { getVisitorAuthBasePath } from '@/lib/data/visitor';
@@ -280,3 +281,410 @@ describe('Site OAuth consent middleware', () => {
).toMatchObject({ source: 'visitor-auth-cookie', token: 'visitor-jwt' });
});
});
describe('Trailing-slash site redirect middleware', () => {
async function runMiddleware(request: NextRequest) {
const cookiesSpy = spyOn(nextHeaders, 'cookies').mockResolvedValue(
RequestCookiesAdapter.seal(request.cookies)
);
try {
return await middleware(request);
} finally {
cookiesSpy.mockRestore();
}
}
function decodeRewriteSiteData(response: Response): Record<string, unknown> {
const rewrite = response.headers.get('x-middleware-rewrite');
expect(rewrite).not.toBeNull();
const segments = new URL(rewrite!).pathname.split('/').filter(Boolean);
return rison.decode(decodeURIComponent(segments[4]!)) as Record<string, unknown>;
}
it.each(['GET', 'HEAD'] as const)(
'rewrites %s trailing-slash request when a site redirect matches',
async (method) => {
const path = '/documentation/web/guides/customizing-ui';
const url = new URL(`https://docs.example.com${path}/`);
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: path,
basePath: '/',
siteBasePath: '/',
canonicalUrl: `https://docs.example.com${path}`,
complete: true,
})
)
.mockResolvedValueOnce(
Response.json({
target: 'https://docs.example.com/web/ui-customization/ui-customization',
redirect: { permanent: true },
})
);
const request = new NextRequest(
`https://origin.example.com/url/docs.example.com${path}`,
{
method,
headers: { 'x-gitbook-url': url.toString() },
}
);
const response = await runMiddleware(request);
expect(response.headers.get('location')).toBeNull();
const rewrite = response.headers.get('x-middleware-rewrite');
expect(rewrite).not.toBeNull();
expect(new URL(rewrite!).pathname).toEndWith(
encodeURIComponent('documentation/web/guides/customizing-ui')
);
expect(decodeRewriteSiteData(response).trailingSlash).toBe(true);
expect(fetchSpy).toHaveBeenCalledTimes(2);
const redirectLookupURL = new URL(String(fetchSpy.mock.calls[1]?.[0]));
expect(redirectLookupURL.pathname).toBe('/v1/orgs/org_1/sites/site_1/redirect');
expect(redirectLookupURL.searchParams.get('source')).toBe(path);
}
);
it('falls back to a 302 redirect preserving query params when no site redirect matches', async () => {
const path = '/getting-started';
const url = new URL(`https://docs.example.com${path}/?utm_source=docs`);
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: path,
basePath: '/',
siteBasePath: '/',
canonicalUrl: `https://docs.example.com${path}`,
complete: true,
})
)
.mockResolvedValueOnce(
Response.json({ error: { message: 'Site redirect not found' } }, { status: 404 })
);
const request = new NextRequest(
`https://origin.example.com/url/docs.example.com${path}?utm_source=docs`,
{
headers: { 'x-gitbook-url': url.toString() },
}
);
const response = await runMiddleware(request);
expect(response.status).toBe(302);
expect(response.headers.get('location')).toBe(
`https://docs.example.com${path}?utm_source=docs`
);
});
it('falls back to the public canonical URL on a proxied site when no site redirect matches', async () => {
const proxyURL = new URL('https://proxy.gitbook.site/sites/site_1/getting-started/?a=1');
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: '/getting-started',
basePath: '/docs/',
siteBasePath: '/docs/',
canonicalUrl: 'https://customer.example.com/docs/getting-started',
complete: true,
})
)
.mockResolvedValueOnce(
Response.json({ error: { message: 'Site redirect not found' } }, { status: 404 })
);
const request = new NextRequest('https://origin.example.com/ignored?a=1', {
headers: { 'x-gitbook-url': proxyURL.toString() },
});
const response = await runMiddleware(request);
expect(response.status).toBe(307);
expect(response.headers.get('location')).toBe(
'https://customer.example.com/docs/getting-started?a=1'
);
});
it('fails open to a 302 redirect when the site redirect lookup errors', async () => {
const path = '/getting-started';
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: path,
basePath: '/',
siteBasePath: '/',
canonicalUrl: `https://docs.example.com${path}`,
complete: true,
})
)
.mockRejectedValueOnce(new TypeError('Upstream unreachable'));
const request = new NextRequest(`https://origin.example.com/url/docs.example.com${path}`, {
headers: { 'x-gitbook-url': `https://docs.example.com${path}/` },
});
const response = await runMiddleware(request);
expect(response.status).toBe(302);
expect(response.headers.get('location')).toBe(`https://docs.example.com${path}`);
});
it('checks both site-relative and space-relative sources for a section trailing-slash URL', async () => {
const url = new URL('https://docs.example.com/docs/v2/old-page/');
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: '/old-page',
basePath: '/docs/v2/',
siteBasePath: '/docs/',
canonicalUrl: 'https://docs.example.com/docs/v2/old-page',
complete: true,
})
)
.mockImplementation(async (input) => {
const lookupURL = new URL(String(input));
if (lookupURL.searchParams.get('source') === '/v2/old-page') {
return Response.json({
target: 'https://docs.example.com/docs/v2/new-page',
redirect: { permanent: true },
});
}
return Response.json({ error: { message: 'Not found' } }, { status: 404 });
});
const request = new NextRequest(
'https://origin.example.com/url/docs.example.com/docs/v2/old-page',
{
headers: { 'x-gitbook-url': url.toString() },
}
);
const response = await runMiddleware(request);
expect(response.headers.get('location')).toBeNull();
expect(decodeRewriteSiteData(response).trailingSlash).toBe(true);
const queriedSources = fetchSpy.mock.calls
.slice(1)
.map(([callURL]) => new URL(String(callURL)).searchParams.get('source'));
expect(queriedSources).toEqual(['/v2/old-page', '/old-page']);
});
it('does not defer trailing-slash normalization for POST requests', async () => {
const request = new NextRequest('https://origin.example.com/url/docs.example.com/old', {
method: 'POST',
headers: { 'x-gitbook-url': 'https://docs.example.com/old/' },
});
const response = await runMiddleware(request);
expect(response.status).toBe(302);
expect(response.headers.get('location')).toBe('https://docs.example.com/old');
expect(fetchSpy).not.toHaveBeenCalled();
});
it('rewrites trailing-slash markdown requests when a site redirect matches', async () => {
const path = '/old-page';
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: path,
basePath: '/',
siteBasePath: '/',
canonicalUrl: `https://docs.example.com${path}`,
complete: true,
})
)
.mockResolvedValueOnce(
Response.json({
target: 'https://docs.example.com/new-page',
redirect: { permanent: true },
})
);
const request = new NextRequest(`https://origin.example.com/url/docs.example.com${path}`, {
headers: {
'x-gitbook-url': `https://docs.example.com${path}/`,
accept: 'text/markdown',
},
});
const response = await runMiddleware(request);
const rewrite = response.headers.get('x-middleware-rewrite');
expect(rewrite).not.toBeNull();
expect(new URL(rewrite!).pathname).toEndWith('/~gitbook/markdown/old-page');
expect(decodeRewriteSiteData(response).trailingSlash).toBe(true);
});
it('falls back to 302 when the initial published content lookup fails', async () => {
const path = '/page';
fetchSpy.mockResolvedValueOnce(
Response.json({ error: { message: 'Service unavailable' } }, { status: 503 })
);
const request = new NextRequest(`https://origin.example.com/url/docs.example.com${path}`, {
headers: { 'x-gitbook-url': `https://docs.example.com${path}/` },
});
const response = await runMiddleware(request);
expect(response.status).toBe(302);
expect(response.headers.get('location')).toBe(`https://docs.example.com${path}`);
});
it('falls back to 302 preserving query params when the matched site redirect is a self-redirect', async () => {
const path = '/old';
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: path,
basePath: '/',
siteBasePath: '/',
canonicalUrl: `https://docs.example.com${path}`,
complete: true,
})
)
.mockResolvedValueOnce(
Response.json({
target: `https://docs.example.com${path}`,
redirect: { permanent: true },
})
);
const request = new NextRequest(
`https://origin.example.com/url/docs.example.com${path}?utm_source=docs`,
{
headers: {
'x-gitbook-url': `https://docs.example.com${path}/?utm_source=docs`,
accept: 'text/markdown',
},
}
);
const response = await runMiddleware(request);
expect(response.status).toBe(302);
expect(response.headers.get('location')).toBe(
`https://docs.example.com${path}?utm_source=docs`
);
});
it('keeps trailing-slash site redirects with query params on the static route so HTTP 308 headers are returned', async () => {
const path = '/old-page';
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: path,
basePath: '/',
siteBasePath: '/',
canonicalUrl: `https://docs.example.com${path}`,
complete: true,
})
)
.mockResolvedValueOnce(
Response.json({
target: 'https://docs.example.com/new-page',
redirect: { permanent: true },
})
);
const request = new NextRequest(
`https://origin.example.com/url/docs.example.com${path}?utm_source=docs`,
{
headers: {
'x-gitbook-url': `https://docs.example.com${path}/?utm_source=docs`,
},
}
);
const response = await runMiddleware(request);
expect(response.headers.get('x-gitbook-route-type')).toBe('static');
expect(decodeRewriteSiteData(response).trailingSlash).toBe(true);
});
it('resolves as soon as one candidate matches without waiting on a stalled sibling lookup', async () => {
let siblingAborted = false;
fetchSpy
.mockResolvedValueOnce(
Response.json({
site: 'site_1',
siteSpace: 'variant',
space: 'space_1',
organization: 'org_1',
apiToken: 'content-token',
pathname: '/old-page',
basePath: '/docs/v2/',
siteBasePath: '/docs/',
canonicalUrl: 'https://docs.example.com/docs/v2/old-page',
complete: true,
})
)
.mockImplementation((input, init) => {
const lookupURL = new URL(String(input));
if (lookupURL.searchParams.get('source') === '/v2/old-page') {
return Promise.resolve(
Response.json({
target: 'https://docs.example.com/docs/v2/new-page',
redirect: { permanent: true },
})
);
}
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
siblingAborted = true;
reject(new DOMException('Aborted', 'AbortError'));
},
{ once: true }
);
});
});
const startedAt = performance.now();
const request = new NextRequest(
'https://origin.example.com/url/docs.example.com/docs/v2/old-page',
{
headers: { 'x-gitbook-url': 'https://docs.example.com/docs/v2/old-page/' },
}
);
const response = await runMiddleware(request);
expect(performance.now() - startedAt).toBeLessThan(500);
expect(siblingAborted).toBe(true);
expect(decodeRewriteSiteData(response).trailingSlash).toBe(true);
});
});
+211 -25
View File
@@ -10,6 +10,8 @@ import {
ContentType,
CustomizationDefaultThemeMode,
CustomizationThemeMode,
GitBookAPIError,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SiteInsightsDisplayContext,
type SiteInsightsEventLocation,
SiteInsightsLLMSVariant,
@@ -36,6 +38,7 @@ import {
getVisitorAuthBasePath,
lookupPublishedContentByUrl,
normalizeRequestURL,
normalizeURL,
throwIfDataError,
} from '@/lib/data';
import {
@@ -57,7 +60,12 @@ import {
isOAuthProtectedResourceMetadataRequestForAuthEndpoint,
isOAuthProtectedResourceRequest,
} from '@/lib/oauth-protected';
import { hasRevisionSelector, removeLeadingSlash, removeTrailingSlash } from '@/lib/paths';
import {
hasRevisionSelector,
removeLeadingSlash,
removeTrailingSlash,
withLeadingSlash,
} from '@/lib/paths';
import {
getPreviewCookieResponse,
getPreviewRequestIdentifier,
@@ -65,11 +73,17 @@ import {
parsePreviewCustomizationCookie,
serializePreviewCustomizationCookie,
} from '@/lib/preview';
import { isProxyRequest } from '@/lib/proxy';
import {
DISALLOW_ALL_ROBOTS_TXT_LINES,
createRobotsTxtResponse,
isRobotsTxtRequest,
} from '@/lib/robots';
import {
getSiteRedirectSourceCandidates,
getSiteRelativeRedirectPath,
isSameSiteRedirectTarget,
} from '@/lib/site-redirects';
import {
UPDATES_FILTER_SEARCH_PARAM,
UPDATES_PAGE_SEARCH_PARAM,
@@ -105,6 +119,7 @@ const DIRECT_SEARCH_ID = /^[a-zA-Z0-9_-]+$/;
const DIRECT_SEARCH_PASS =
/^[a-zA-Z0-9_-]+\.\.[a-zA-Z0-9_-]{16}\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]{22}$/;
const DIRECT_SEARCH_TIMEOUT_MS = 5_000;
const SITE_REDIRECT_CHECK_TIMEOUT_MS = 500;
export async function middleware(request: NextRequest) {
try {
@@ -302,18 +317,13 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
}
// Normalize URL after extracting the URL from the request to make sure the client is redirected to the proper one
const normalization = normalizeRequestURL(siteRequestURL, mode);
const canDeferTrailingSlash = request.method === 'GET' || request.method === 'HEAD';
const normalization = normalizeRequestURL(siteRequestURL, mode, {
deferTrailingSlash: canDeferTrailingSlash,
});
if (normalization instanceof Response) {
const location = normalization.headers.get('location');
if (location && hasRevisionSelector(new URL(location).pathname)) {
return NextResponse.redirect(location, {
status: normalization.status,
headers: { 'x-robots-tag': REVISION_ROBOTS_TAG },
});
}
return normalization;
return withRevisionRobotsHeader(normalization);
}
const isNormalizedURL = normalization.isNormalized;
const imagesContextId = getImageResizingContextId(siteRequestURL);
/**
@@ -339,7 +349,11 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
}
// We want to filter hostnames that contains a port here as this is likely a malicious request.
if (shouldFilterMaliciousRequests(siteRequestURL)) {
let urlToFilter = siteRequestURL;
if (normalization.status === 'trailing-slash') {
urlToFilter = normalization.normalizedURL;
}
if (shouldFilterMaliciousRequests(urlToFilter)) {
return new Response('Invalid request', {
status: 400,
headers: { 'content-type': 'text/plain' },
@@ -406,6 +420,14 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
return createOAuthProtectedResourceUnauthResponse({ siteRequestURL, urlMode: mode });
}
if (
lookup.error &&
normalization.status === 'trailing-slash' &&
!(mode !== 'url' && isProxyRequest(siteRequestURL))
) {
return createTrailingSlashRedirect(normalization.normalizedURL);
}
const siteURLData = throwIfDataError(lookup);
const cookies: ResponseCookies = visitorParamsCookie
@@ -531,8 +553,9 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
// on the redirect response.
//
const normalizedVisitorURL = normalizeVisitorURL(incomingURL);
const hasVisitorParamsToClean = normalizedVisitorURL.toString() !== incomingURL.toString();
if (
(!isNormalizedURL || normalizedVisitorURL.toString() !== incomingURL.toString()) &&
(hasVisitorParamsToClean || normalization.status === 'deferred-proxy') &&
!isRevalidationRequest(request.headers)
) {
if (visitorToken?.source === 'url') {
@@ -546,10 +569,11 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
);
}
return writeResponseCookies(
NextResponse.redirect(normalizedVisitorURL.toString()),
cookies
);
let redirectURL = normalizedVisitorURL;
if (normalization.status === 'trailing-slash' && mode === 'url') {
redirectURL = normalizeURL(normalizedVisitorURL);
}
return writeResponseCookies(NextResponse.redirect(redirectURL.toString()), cookies);
}
if (isSearchPrewarmRequest(siteURLData)) {
@@ -560,6 +584,38 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
return await serveSearchPass(request, siteURLData, visitorToken?.token);
}
const {
pathname,
routeType: routeTypeFromPathname,
events,
isAiAgent,
askVisitorAgent,
siteRedirectPathname,
} = encodePathInSiteContent(siteURLData, request);
let trailingSlash: true | undefined;
if (normalization.status === 'trailing-slash' && !isRevalidationRequest(request.headers)) {
let matchedSiteRedirect = false;
if (siteRedirectPathname !== undefined) {
matchedSiteRedirect = await hasMatchingSiteRedirect(
siteURLData,
siteRedirectPathname,
siteCanonicalURL,
pathname.startsWith('~gitbook/markdown/')
);
}
if (!matchedSiteRedirect) {
if (mode !== 'url' && isProxyRequest(siteRequestURL)) {
return writeResponseCookies(
NextResponse.redirect(normalizedVisitorURL.toString()),
cookies
);
}
return createTrailingSlashRedirect(normalization.normalizedURL);
}
trailingSlash = true;
}
//
// Render and serve the content
//
@@ -595,6 +651,7 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
requestURL.searchParams.get('displayAgentInstructions') === 'false'
? false
: undefined,
trailingSlash,
};
const requestHeaders = new Headers(request.headers);
@@ -668,13 +725,6 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
requestHeaders.set('origin', request.nextUrl.origin);
const siteURLWithoutProtocol = `${siteCanonicalURL.host}${siteURLData.basePath}`;
const {
pathname,
routeType: routeTypeFromPathname,
events,
isAiAgent,
askVisitorAgent,
} = encodePathInSiteContent(siteURLData, request);
routeType = routeTypeFromPathname ?? routeType;
// Only set for markdown routes, so it becomes part of their static cache key.
stableSiteURLData.isAiAgent = isAiAgent;
@@ -1076,6 +1126,132 @@ async function serveSearchPass(
);
}
function withRevisionRobotsHeader(response: Response): Response {
const location = response.headers.get('location');
if (location && hasRevisionSelector(new URL(location).pathname)) {
return NextResponse.redirect(location, {
status: response.status,
headers: { 'x-robots-tag': REVISION_ROBOTS_TAG },
});
}
return response;
}
function createTrailingSlashRedirect(normalizedURL: URL): NextResponse {
const headers: Record<string, string> = {};
if (hasRevisionSelector(normalizedURL.pathname)) {
headers['x-robots-tag'] = REVISION_ROBOTS_TAG;
}
return NextResponse.redirect(normalizedURL.toString(), {
status: 302,
headers,
});
}
async function hasMatchingSiteRedirect(
siteURLData: PublishedSiteContent,
pathname: string,
siteCanonicalURL: URL,
isMarkdownRoute: boolean
): Promise<boolean> {
if (pathname.length >= SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH) {
return false;
}
const candidates = getSiteRedirectSourceCandidates([
getSiteRelativeRedirectPath({
siteBasePath: siteURLData.siteBasePath,
spaceBasePath: siteURLData.basePath,
pathname,
}),
withLeadingSlash(pathname),
]);
if (candidates.length === 0) {
return false;
}
const api = apiClient({ apiToken: siteURLData.apiToken ?? null });
const controller = new AbortController();
let timedOut = false;
let settledMatch = false;
const timeout = setTimeout(() => {
timedOut = true;
controller.abort();
}, SITE_REDIRECT_CHECK_TIMEOUT_MS);
try {
return await new Promise<boolean>((resolve) => {
let remaining = candidates.length;
const finish = (matched: boolean) => {
if (settledMatch) {
return;
}
if (matched) {
settledMatch = true;
controller.abort();
resolve(true);
return;
}
remaining -= 1;
if (remaining === 0) {
resolve(false);
}
};
for (const source of candidates) {
void api.orgs
.getSiteRedirectBySource(
siteURLData.organization,
siteURLData.site,
{
shareKey: siteURLData.shareKey,
source,
},
{
signal: controller.signal,
}
)
.then((res) => {
const isUsableRedirect =
Boolean(res.data?.target) &&
!isSameSiteRedirectTarget(siteCanonicalURL, res.data.target, {
markdown: isMarkdownRoute,
});
finish(isUsableRedirect);
})
.catch((error) => {
if (settledMatch) {
return;
}
if (error instanceof GitBookAPIError && error.code === 404) {
finish(false);
return;
}
let reason = 'error';
if (timedOut) {
reason = 'timeout';
}
let status: number | undefined;
if (error instanceof GitBookAPIError) {
status = error.code;
}
getLogger()
.subLogger('trailingSlashRedirect')
.warn('Site redirect lookup failed', {
reason,
status,
organizationId: siteURLData.organization,
siteId: siteURLData.site,
});
finish(false);
});
}
});
} finally {
clearTimeout(timeout);
}
}
/**
* Encode path in a site content.
* Special paths are not encoded and passed to be handled by the route handlers.
@@ -1091,6 +1267,8 @@ function encodePathInSiteContent(
isAiAgent?: boolean;
/** Only set for the ask route, where the API classifies the asker from these headers. */
askVisitorAgent?: AskVisitorAgent;
/** Page pathname when the route resolves site redirects (page and markdown page routes). */
siteRedirectPathname?: string;
} {
let pathname = removeLeadingSlash(removeTrailingSlash(siteURLData.pathname));
@@ -1220,6 +1398,10 @@ function encodePathInSiteContent(
const markdownSource = Object.values(SiteInsightsMarkdownSource).find(
(source) => source === searchParams.get('markdownSource')
);
let siteRedirectPathname: string | undefined;
if (typeof ask !== 'string') {
siteRedirectPathname = pagePathWithoutMD;
}
return {
pathname:
typeof ask === 'string'
@@ -1232,6 +1414,7 @@ function encodePathInSiteContent(
isAiAgent: isAiAgent || undefined,
askVisitorAgent:
typeof ask === 'string' ? getAskVisitorAgent(request.headers) : undefined,
siteRedirectPathname,
// TODO: track pageId / spaceId when possible
// We don't do it at the moment as we can't easily extract it from the URL.
events: ask
@@ -1256,7 +1439,10 @@ function encodePathInSiteContent(
],
};
}
return { pathname: encodeUpdatesPagePath(pathname, request) };
return {
pathname: encodeUpdatesPagePath(pathname, request),
siteRedirectPathname: pathname,
};
}
}
}
@@ -113,6 +113,40 @@ describe('servePageMarkdown', () => {
expect(response.status).toBe(307);
expect(response.headers.get('Location')).toBe('/docs/new-page.md');
});
it('redirects an existing page on a trailing-slash request instead of serving 200', async () => {
const context = {
...createContext({
siteRedirect: {
target: 'https://docs.example.com/docs/elsewhere',
permanent: true,
},
}),
trailingSlash: true,
} as unknown as GitBookSiteContext;
const response = await servePageMarkdown(context, 'new-page');
expect(response.status).toBe(307);
expect(response.headers.get('Location')).toBe('/docs/new-page.md');
});
it('falls back to a 302 slashless redirect when a trailing-slash site redirect is rejected', async () => {
const context = {
...createContext({
siteRedirect: {
target: 'https://docs.example.com/docs/old-page.md',
permanent: false,
},
}),
trailingSlash: true,
} as unknown as GitBookSiteContext;
const response = await servePageMarkdown(context, 'old-page');
expect(response.status).toBe(302);
expect(response.headers.get('Location')).toBe('/docs/old-page');
});
});
describe('toMarkdownDestination', () => {
@@ -58,6 +58,16 @@ export async function servePageMarkdown(baseContext: GitBookSiteContext, pagePat
);
}
if (baseContext.trailingSlash) {
return new Response(null, {
status: 302,
headers: {
Location: baseContext.linker.toPathForPagePath({ path: pagePath }),
Vary: 'Accept',
},
});
}
// Generates a markdown body for missing pages. Return this with a 200 status (not 404) because agents discard 404 response bodies.=
return {
markdown: renderNotFoundMarkdown(context, pagePath),
@@ -65,6 +75,16 @@ export async function servePageMarkdown(baseContext: GitBookSiteContext, pagePat
};
}
if (baseContext.trailingSlash) {
return markdownRedirect(
context.linker.toPathForPage({
pages: context.revision.pages,
page: pageLookup.page,
}),
false
);
}
const robots = getMarkdownRobots(context, pageLookup);
const markdownPage = await getMarkdownForPage(context, pageLookup);