Compare commits

...

9 Commits

Author SHA1 Message Date
Peter White dc5ec80893 Use same-domain direct site search as fallback only 2026-11-25 17:51:30 +00:00
Peter White 429a63bb59 Simplify direct site search proxy and tests 2026-11-25 16:30:40 +00:00
Peter White b08a4f9acd Start direct site search on the same-domain proxy when search.sameDomain is enabled 2026-11-25 15:51:48 +00:00
Peter White c9e2de32b6 Buffer direct search proxy response body to avoid chunked stall 2026-11-25 15:37:17 +00:00
Peter White fa19dc41aa changeset 2026-11-25 14:58:11 +00:00
Peter White 8fed05f354 Use the site search proxy after API network failures or timeouts 2026-11-25 14:58:11 +00:00
Peter White 9f0531484e Handle direct site search in GBO middleware 2026-11-25 14:28:36 +00:00
Peter White 30ea30421d changeset 2026-11-25 13:37:56 +00:00
Peter White 4c01f40d7e Serve direct site search under the site's own domain 2026-11-25 13:37:56 +00:00
9 changed files with 377 additions and 68 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Retry direct site search on the site's own domain after a network error or timeout.
+28 -4
View File
@@ -781,7 +781,7 @@ const searchPassTestCases: Test[] = [
},
},
{
name: 'Dropped API request: the search falls back to the route after its time limit',
name: 'Dropped API request: search uses the site proxy before falling back to the route',
url: '',
screenshot: false,
run: async (page) => {
@@ -791,6 +791,18 @@ const searchPassTestCases: Test[] = [
await page.route(SEARCH_API_URL, (route) => {
apiCalls.push(route.request());
});
const proxyCalls: Request[] = [];
await page.route(
/\/~gitbook\/search-direct\/orgs\/[^/]+\/sites\/[^/]+$/,
async (route) => {
proxyCalls.push(route.request());
if (proxyCalls.length === 1) {
await route.fulfill({ json: { items: [SEARCH_PASS_RECORD] } });
return;
}
await route.fulfill({ status: 502 });
}
);
const routeSearches = trackRouteSearches(page);
await waitForCookiesDialog(page);
@@ -798,12 +810,24 @@ const searchPassTestCases: Test[] = [
await typeSearch(page, 'gitbook');
await expect.poll(() => apiCalls.length, { timeout: 30_000 }).toBe(1);
await page.clock.fastForward(5_000);
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('timeout');
expect((await routeSearches[0]?.response())?.status()).toBe(200);
await expect(
page
.getByTestId('search-record-result')
.filter({ hasText: SEARCH_PASS_RECORD.title })
).toBeVisible({ timeout: 30_000 });
expect(routeSearches).toHaveLength(0);
expect((await proxyCalls[0]?.allHeaders())?.['x-gitbook-search-pass']).toBe(
'test-search-pass-1'
);
await typeSearch(page, ' editor');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(1);
expect(routeSearches[0]?.headers()['x-gitbook-search-fallback']).toBe('502');
expect((await routeSearches[0]?.response())?.status()).toBe(200);
await typeSearch(page, ' blocks');
await expect.poll(() => routeSearches.length, { timeout: 30_000 }).toBe(2);
expect(proxyCalls).toHaveLength(2);
expect(apiCalls).toHaveLength(1);
},
},
@@ -4,10 +4,12 @@ import { createSearchPassStore } from './search-pass-store';
import type { DirectSearchProps } from '@/lib/search-results';
const endpoint = 'https://api.gitbook.com/v1/orgs/org_1/sites/site_1/search';
const proxyURL = '/~gitbook/search-direct/orgs/org_1/sites/site_1';
const directSearch: DirectSearchProps = {
apiURL: 'https://api.gitbook.com',
organizationId: 'org_1',
siteId: 'site_1',
proxyURL,
linker: {
urlMode: 'url-host',
siteHost: 'docs.example.com',
@@ -60,6 +62,49 @@ describe('createSearchPassStore', () => {
let restore: (() => void) | undefined;
afterEach(() => restore?.());
it('switches to the site proxy after an API network failure', async () => {
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockImplementation(async () => Response.json({ items: [] }));
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
proxyURL,
]);
const init = fetchSpy.mock.calls[2]?.[1];
expect(init).toMatchObject({ mode: 'same-origin', credentials: 'omit' });
expect(init?.body).toBe(JSON.stringify({ query: 'tokens', mode: 'all' }));
const headers = new Headers(init?.headers);
expect(headers.get('x-gitbook-search-pass')).toBe('pass-1');
expect(headers.has('authorization')).toBe(false);
});
it('uses the server route after the site proxy also fails', async () => {
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockRejectedValueOnce(new TypeError('Failed to fetch'))
.mockResolvedValueOnce(new Response(null, { status: 502 }));
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: '502' });
expect(await search(store)).toEqual({ type: 'route', reason: '502' });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
]);
});
it('stays on the route for the rest of the page after a 403', async () => {
const { authorizations, fetchSpy } = mockFetch([403]);
restore = () => fetchSpy.mockRestore();
@@ -32,6 +32,11 @@ type DirectSearchOutcome =
| { type: 'results'; results: OrderedComputedResult[] }
| { type: 'route'; reason?: string };
type SearchAttempt =
| { type: 'success'; body: string }
| { type: 'http'; response: Response }
| { type: 'failure'; reason: 'network' | 'timeout' };
export type SearchPassStore = ReturnType<typeof createSearchPassStore>;
/**
@@ -39,6 +44,7 @@ export type SearchPassStore = ReturnType<typeof createSearchPassStore>;
*/
export function createSearchPassStore(directSearch: DirectSearchProps | undefined) {
let state: SearchPassState = { status: 'none' };
let useProxy = false;
let pendingRequest: Promise<void> | null = null;
const sendPassRequest = async () => {
@@ -77,7 +83,9 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
(current.status === 'none' && current.reason === '401') ||
(current.status === 'ready' && current.replacesRejectedPass),
};
ReactDOM.preconnect(directSearch.apiURL, { crossOrigin: 'anonymous' });
if (!useProxy) {
ReactDOM.preconnect(directSearch.apiURL, { crossOrigin: 'anonymous' });
}
} else if (current.status === 'ready') {
state = { status: 'none' };
}
@@ -146,78 +154,130 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine
return { type: 'results', results: [] };
}
const { token, replacesRejectedPass } = state;
const { apiURL, organizationId, siteId } = directSearch;
// A request dropped on the way to the API never settles, so it gets its own time limit.
// The browser targets predate `AbortSignal.any`.
const request = new AbortController();
if (signal.aborted) {
request.abort();
let pass = state;
const { apiURL, organizationId, siteId, proxyURL } = directSearch;
const usingProxy = useProxy && Boolean(proxyURL);
let url = `${apiURL}/v1/orgs/${organizationId}/sites/${siteId}/search`;
if (usingProxy && proxyURL) {
url = proxyURL;
}
signal.addEventListener('abort', () => request.abort(), { once: true });
const timeout = setTimeout(() => request.abort(), DIRECT_SEARCH_TIMEOUT_MS);
let response: Response;
try {
response = await fetch(`${apiURL}/v1/orgs/${organizationId}/sites/${siteId}/search`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(toSearchSiteContentBody(query, scope, searchId)),
credentials: 'omit',
signal: request.signal,
});
} catch (error) {
if (signal.aborted) {
throw error;
const body = JSON.stringify(toSearchSiteContentBody(query, scope, searchId));
let attempt = await sendSearch(url, usingProxy, pass.token, body, signal);
if (attempt.type === 'failure' && !usingProxy && proxyURL) {
const current = state as SearchPassState;
if (current.status === 'ready') {
useProxy = true;
pass = current;
attempt = await sendSearch(proxyURL, true, pass.token, body, signal);
} else if (current.status === 'none') {
useProxy = true;
return { type: 'route', reason: attempt.reason };
}
return fallBack(request.signal.aborted ? 'timeout' : 'network');
}
if (response.status === 401) {
return replacesRejectedPass ? fallBack('401') : dropPass(token, '401');
if (attempt.type === 'failure') {
const current = state as SearchPassState;
if (current.status === 'route') {
return waitForCooldown(current, signal);
}
return fallBack(attempt.reason);
}
if (response.status === 429) {
state = {
status: 'route',
reason: '429',
cooldownUntil: Date.now() + getRateLimitWaitMs(response),
};
return waitForCooldown(state, signal);
}
if (!response.ok) {
if (attempt.type === 'http') {
const { response } = attempt;
if (response.status === 401) {
if (pass.replacesRejectedPass) {
return fallBack('401');
}
return dropPass(pass.token, '401');
}
if (response.status === 429) {
state = {
status: 'route',
reason: '429',
cooldownUntil: Date.now() + getRateLimitWaitMs(response),
};
return waitForCooldown(state, signal);
}
return fallBack(String(response.status));
}
let results: OrderedComputedResult[] | null;
try {
const { items } = (await response.json()) as {
const { items } = JSON.parse(attempt.body) as {
items: (SearchSpaceResult | SearchRecordResult)[];
};
const linker = createSiteLinker(directSearch.linker);
results = computePublishedSearchResults({
let linker = createSiteLinker(directSearch.linker);
if (asEmbeddable) {
linker = getEmbeddableLinker(linker);
}
const results = computePublishedSearchResults({
asEmbeddable,
linker: asEmbeddable ? getEmbeddableLinker(linker) : linker,
linker,
searchResults: items,
spaces: directSearch.spaces,
});
} catch (error) {
if (signal.aborted) {
throw error;
if (!results) {
return { type: 'route', reason: 'unknown_space' };
}
return fallBack(request.signal.aborted ? 'timeout' : 'invalid');
} finally {
clearTimeout(timeout);
return { type: 'results', results };
} catch {
return fallBack('invalid');
}
// An unmapped space can come from a structure change after page load; fall back for this query only.
return results ? { type: 'results', results } : { type: 'route', reason: 'unknown_space' };
};
return { requestPass, search };
}
async function sendSearch(
url: string,
useProxy: boolean,
token: string,
body: string,
signal: AbortSignal
): Promise<SearchAttempt> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
let mode: RequestMode | undefined;
if (useProxy) {
mode = 'same-origin';
headers['x-gitbook-search-pass'] = token;
} else {
headers.Authorization = `Bearer ${token}`;
}
const request = new AbortController();
const abort = () => request.abort();
if (signal.aborted) {
abort();
}
signal.addEventListener('abort', abort, { once: true });
const timeout = setTimeout(abort, DIRECT_SEARCH_TIMEOUT_MS);
try {
const response = await fetch(url, {
method: 'POST',
headers,
body,
credentials: 'omit',
mode,
signal: request.signal,
});
if (!response.ok) {
return { type: 'http', response };
}
return { type: 'success', body: await response.text() };
} catch (error) {
if (signal.aborted) {
throw error;
}
if (request.signal.aborted) {
return { type: 'failure', reason: 'timeout' };
}
return { type: 'failure', reason: 'network' };
} finally {
clearTimeout(timeout);
signal.removeEventListener('abort', abort);
}
}
/**
* Hold a search until a short rate limit cooldown ends, then send it to the route.
* During a longer cooldown the search fails at once, as the route would.
@@ -132,9 +132,13 @@ export function getDirectSearchProps(context: GitBookSiteContext): DirectSearchP
return undefined;
}
const { organizationId, siteId } = context.directSearch;
return {
...context.directSearch,
spaces: getSearchSpaceLookup(context.structure),
passURL: context.linker.toPathInSite('~gitbook/search-pass'),
proxyURL: context.linker.toPathInSite(
`~gitbook/search-direct/orgs/${organizationId}/sites/${siteId}`
),
};
}
@@ -41,6 +41,7 @@ export type DirectSearchProps = {
apiURL: string;
organizationId: string;
siteId: string;
proxyURL?: string;
linker: SiteLinkerInput;
spaces: SearchSpaceLookup;
/** Site route that hands out a search pass. */
+1 -2
View File
@@ -157,8 +157,7 @@ export async function serveProxyAnalyticsEvent(req: Request) {
/**
* Extract the real IP address of the client from the request headers, accounting for various proxies and CDNs.
*/
function getXForwardedFor(headers: Headers): string | null {
export function getXForwardedFor(headers: Headers): string | null {
// We start first with the cloudflare headers
if (headers.has('cf-connecting-ip')) {
return headers.get('cf-connecting-ip');
+114
View File
@@ -0,0 +1,114 @@
import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
import { NextRequest } from 'next/server';
import { middleware } from './middleware';
import { GITBOOK_API_URL } from '@/lib/env';
import { removeTrailingSlash } from '@/lib/paths';
const PATH = '/~gitbook/search-direct/orgs/org_1/sites/site-1';
const PASS_HEADER = 'x-gitbook-search-pass';
const SEARCH_PASS =
'eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIiwidHlwIjoic2l0ZS1zZWFyY2gtcGFzcytqd3QifQ..AAAAAAAAAAAAAAAA.AAAA.AAAAAAAAAAAAAAAAAAAAAA';
let fetchSpy: ReturnType<typeof spyOn<typeof globalThis, 'fetch'>>;
beforeEach(() => {
fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(null));
});
afterEach(() => fetchSpy.mockRestore());
describe('direct site search middleware', () => {
it.each([
['https://hosted.gitbook.io', '', ''],
['https://proxy.gitbook.site', '/sites/site-1', '/'],
])('forwards a search from %s%s%s directly to GBX', async (host, prefix, suffix) => {
fetchSpy.mockResolvedValueOnce(
Response.json(
{ items: [] },
{
status: 429,
headers: {
'cache-control': 'public, max-age=600',
'set-cookie': 'upstream=1',
'retry-after': '3',
'x-ratelimit-scope': 'site',
'x-ratelimit-reset': '123',
},
}
)
);
const body = '{"query":"tokens"}';
const request = new NextRequest('https://origin.example.com/ignored?ignored=1', {
method: 'POST',
body: new TextEncoder().encode(body),
headers: {
'x-gitbook-url': `${host}${prefix}${PATH}${suffix}?also-ignored=1`,
'x-gitbook-url-signature': 'internal',
'x-gitbook-ip': '192.0.2.1',
'cf-connecting-ip': '192.0.2.2',
'x-forwarded-for': '192.0.2.3',
[PASS_HEADER]: SEARCH_PASS,
cookie: 'session=1',
authorization: 'Bearer incoming-token',
},
});
const response = await middleware(request);
expect(fetchSpy).toHaveBeenCalledTimes(1);
const [url, init] = fetchSpy.mock.calls[0] ?? [];
expect(String(url)).toBe(
`${removeTrailingSlash(GITBOOK_API_URL)}/v1/orgs/org_1/sites/site-1/search`
);
expect(init).toMatchObject({ method: 'POST', redirect: 'manual', duplex: 'half' });
expect(init?.body).toBe(request.body);
expect(await new Response(init?.body).text()).toBe(body);
expect(Object.fromEntries(new Headers(init?.headers))).toEqual({
authorization: `Bearer ${SEARCH_PASS}`,
'content-type': 'application/json',
'x-forwarded-for': '192.0.2.1',
});
expect(response.status).toBe(429);
expect(response.headers.get('cache-control')).toBe('no-store');
expect(response.headers.get('set-cookie')).toBeNull();
expect(response.headers.get('retry-after')).toBe('3');
expect(response.headers.get('x-ratelimit-scope')).toBe('site');
expect(response.headers.get('x-ratelimit-reset')).toBe('123');
expect(await response.text()).toBe('{"items":[]}');
});
it.each([
['wrong method', 'GET', PATH, '', 405],
['missing pass', 'POST', PATH, '', 401],
['personal token', 'POST', PATH, 'personal-api-token', 401],
['signed API token', 'POST', PATH, 'eyJhbGciOiJIUzI1NiJ9.e30.c2ln', 401],
['invalid organization ID', 'POST', PATH.replace('org_1', 'org%20bad'), SEARCH_PASS, 400],
['invalid site ID', 'POST', PATH.replace('site-1', 'site.bad'), SEARCH_PASS, 400],
] as const)('rejects %s', async (_name, method, path, pass, status) => {
const headers = new Headers({ 'x-forwarded-host': 'docs.example.com' });
if (pass) {
headers.set(PASS_HEADER, pass);
}
const response = await middleware(
new NextRequest(`https://origin.example.com${path}`, { method, headers })
);
expect(response.status).toBe(status);
expect(response.headers.get('cache-control')).toBe('no-store');
expect(fetchSpy).not.toHaveBeenCalled();
});
it('returns an uncached 502 when the upstream request fails', async () => {
fetchSpy.mockRejectedValueOnce(new TypeError('Failed to fetch'));
const response = await middleware(
new NextRequest(`https://origin.example.com${PATH}`, {
method: 'POST',
headers: { 'x-forwarded-host': 'docs.example.com', [PASS_HEADER]: SEARCH_PASS },
})
);
expect(response.status).toBe(502);
expect(response.headers.get('cache-control')).toBe('no-store');
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
});
+68 -11
View File
@@ -18,6 +18,7 @@ import {
import {
type ServerInsightsEventInput,
getXForwardedFor,
serveProxyAnalyticsEvent,
trackServerInsightsEvents,
} from './lib/tracking';
@@ -37,7 +38,12 @@ import {
normalizeRequestURL,
throwIfDataError,
} from '@/lib/data';
import { GITBOOK_DISABLE_INSIGHTS, isGitBookAssetsHostURL, isGitBookHostURL } from '@/lib/env';
import {
GITBOOK_API_URL,
GITBOOK_DISABLE_INSIGHTS,
isGitBookAssetsHostURL,
isGitBookHostURL,
} from '@/lib/env';
import { getImageResizingContextId } from '@/lib/images';
import { isAITrainingOrIndexingRequest } from '@/lib/indexing-crawlers';
import { getLogger } from '@/lib/logger';
@@ -86,10 +92,19 @@ export const config = {
type URLWithMode = { url: URL; mode: 'url' | 'url-host' };
const REVISION_ROBOTS_TAG = 'noindex, nofollow';
const DIRECT_SEARCH_PATH = /\/~gitbook\/search-direct\/orgs\/([^/]*)\/sites\/([^/]*)\/?$/;
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}$/;
export async function middleware(request: NextRequest) {
try {
const requestURL = new URL(request.url);
const siteURL = getSiteURLFromRequest(request);
const directSearch = siteURL?.url.pathname.match(DIRECT_SEARCH_PATH);
if (directSearch) {
return await serveDirectSearch(request, directSearch[1], directSearch[2]);
}
// Reject malicious requests
const rejectResponse = await validateServerActionRequest(request);
@@ -97,14 +112,10 @@ export async function middleware(request: NextRequest) {
return rejectResponse;
}
for (const handler of [serveSiteRoutes, serveSpacePDFRoutes]) {
const result = await handler(requestURL, request);
if (result) {
return result;
}
}
return NextResponse.next();
const siteResponse = await serveSiteRoutes(requestURL, request, siteURL);
return (
siteResponse ?? (await serveSpacePDFRoutes(requestURL, request)) ?? NextResponse.next()
);
} catch (error) {
return serveErrorResponse(error as Error);
}
@@ -164,8 +175,7 @@ function shouldFilterMaliciousRequests(requestURL: URL): boolean {
/**
* Handle request that are targetting the site routes group.
*/
async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
const match = getSiteURLFromRequest(request);
async function serveSiteRoutes(requestURL: URL, request: NextRequest, match: URLWithMode | null) {
if (!match) {
return null;
}
@@ -183,6 +193,53 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
return response;
}
async function serveDirectSearch(request: NextRequest, organizationId = '', siteId = '') {
const responseHeaders = new Headers({ 'Cache-Control': 'no-store' });
if (request.method !== 'POST') {
responseHeaders.set('Allow', 'POST');
return new Response(null, { status: 405, headers: responseHeaders });
}
if (!DIRECT_SEARCH_ID.test(organizationId) || !DIRECT_SEARCH_ID.test(siteId)) {
return new Response(null, { status: 400, headers: responseHeaders });
}
const pass = request.headers.get('x-gitbook-search-pass');
if (!pass || !DIRECT_SEARCH_PASS.test(pass)) {
return new Response(null, { status: 401, headers: responseHeaders });
}
const headers = new Headers({
Authorization: `Bearer ${pass}`,
'Content-Type': request.headers.get('Content-Type') ?? 'application/json',
});
const ip = request.headers.get('x-gitbook-ip') ?? getXForwardedFor(request.headers);
if (ip) headers.set('X-Forwarded-For', ip);
const upstream = await fetch(
`${removeTrailingSlash(GITBOOK_API_URL)}/v1/orgs/${organizationId}/sites/${siteId}/search`,
{
method: 'POST',
headers,
body: request.body,
redirect: 'manual',
signal: request.signal,
duplex: 'half',
} as RequestInit
).catch(() => {
getLogger().subLogger('directSiteSearch').warn('Direct search upstream failed', {
status: 502,
organizationId,
siteId,
});
return new Response(null, { status: 502 });
});
for (const name of ['Content-Type', 'Retry-After', 'X-RateLimit-Scope', 'X-RateLimit-Reset']) {
const value = upstream.headers.get(name);
if (value !== null) responseHeaders.set(name, value);
}
const responseBody = await upstream.arrayBuffer();
return new Response(responseBody, { status: upstream.status, headers: responseHeaders });
}
async function serveSiteRequest(requestURL: URL, request: NextRequest, match: URLWithMode) {
const { url: siteRequestURL, mode } = match;