Compare commits

...

13 Commits

Author SHA1 Message Date
Peter White ec91048a49 Add Server-Timing, nosniff, null-body handling, and same-origin credentials for direct search proxy 2026-11-25 20:52:16 +00:00
Peter White 402b4b3c9d Harden direct site search middleware proxy and log proxy recovery 2026-11-25 18:50:17 +00:00
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
Steven H 7f08fb14d1 Read site revision previews through the site revision endpoints (#4818)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 21:46:02 +00:00
Nolann B. 867da7b94c Resolve GitBook links in OpenAPI schema descriptions to the site's URLs (#4838) 2026-11-24 19:32:47 +01:00
19 changed files with 1224 additions and 123 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Retry direct site search on the site's own domain after a network error or timeout.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Resolve GitBook links in OpenAPI schema descriptions to the site's published URLs instead of the editor.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Show site revision previews as their site revision pins them, including OpenAPI specs.
+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);
},
},
@@ -14,6 +14,11 @@ export async function hasContentBeenUpdated(props: { revisionId: string }) {
const context = await getServerActionBaseContext();
const siteURLData = await getSiteURLDataFromMiddleware();
// A site revision never changes what it shows.
if (siteURLData.siteRevision) {
return false;
}
if (siteURLData.changeRequest) {
const changeRequest = await getDataOrNull(
context.dataFetcher.getChangeRequest({
@@ -1,13 +1,15 @@
import { afterEach, describe, expect, it, spyOn } from 'bun:test';
import { createSearchPassStore } from './search-pass-store';
import { SEARCH_FALLBACK_HEADER, 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,150 @@ 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: 'same-origin' });
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.get(SEARCH_FALLBACK_HEADER)).toBe('network');
expect(headers.has('authorization')).toBe(false);
expect(new Headers(fetchSpy.mock.calls[3]?.[1]?.headers).has(SEARCH_FALLBACK_HEADER)).toBe(
false
);
});
it('switches to the site proxy after an API timeout', async () => {
const originalSetTimeout = globalThis.setTimeout;
const timeoutSpy = spyOn(globalThis, 'setTimeout').mockImplementation(((
fn: (...args: unknown[]) => void,
ms?: number,
...args: unknown[]
) => {
let delay = ms;
if (ms === 5_000) {
delay = 0;
}
return originalSetTimeout(fn, delay, ...args);
}) as typeof setTimeout);
const fetchSpy = spyOn(globalThis, 'fetch')
.mockResolvedValueOnce(Response.json({ token: 'pass-1', expiresIn: 300_000 }))
.mockImplementationOnce(
(_url, init) =>
new Promise((_, reject) => {
init?.signal?.addEventListener(
'abort',
() => reject(new DOMException('Aborted', 'AbortError')),
{ once: true }
);
})
)
.mockResolvedValueOnce(Response.json({ items: [] }));
restore = () => {
timeoutSpy.mockRestore();
fetchSpy.mockRestore();
};
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
]);
expect(new Headers(fetchSpy.mock.calls[2]?.[1]?.headers).get(SEARCH_FALLBACK_HEADER)).toBe(
'timeout'
);
});
it('refreshes the pass on a 401 from the site proxy', 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: 401 }))
.mockResolvedValueOnce(Response.json({ token: 'pass-2', expiresIn: 300_000 }))
.mockResolvedValueOnce(Response.json({ items: [] }));
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
expect(await search(store)).toEqual({ type: 'route', reason: '401' });
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await search(store)).toEqual({ type: 'results', results: [] });
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
directSearch.passURL,
proxyURL,
]);
expect(new Headers(fetchSpy.mock.calls[4]?.[1]?.headers).get('x-gitbook-search-pass')).toBe(
'pass-2'
);
});
it('honors rate-limit headers on a 429 from the site proxy', async () => {
const resetAtSeconds = Math.ceil((Date.now() + 30_000) / 1000);
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: 429,
headers: {
'x-ratelimit-scope': 'site',
'x-ratelimit-reset': String(resetAtSeconds),
},
})
);
restore = () => fetchSpy.mockRestore();
const store = createSearchPassStore(directSearch);
await store.requestPass();
await expect(search(store)).rejects.toThrow('Search is rate limited');
await expect(search(store)).rejects.toThrow('Search is rate limited');
expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([
directSearch.passURL,
endpoint,
proxyURL,
]);
});
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,144 @@ 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;
let url = `${apiURL}/v1/orgs/${organizationId}/sites/${siteId}/search`;
if (usingProxy) {
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) {
const current = state as SearchPassState;
// TODO: timeout can mean a slow API rather than a blocked host, so consider not sticking to the proxy for the session.
if (current.status === 'ready') {
useProxy = true;
pass = current;
attempt = await sendSearch(
proxyURL,
true,
pass.token,
body,
signal,
attempt.reason
);
} 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,
fallbackReason?: 'network' | 'timeout'
): Promise<SearchAttempt> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
let mode: RequestMode | undefined;
let credentials: RequestCredentials = 'omit';
if (useProxy) {
mode = 'same-origin';
credentials = 'same-origin';
headers['x-gitbook-search-pass'] = token;
if (fallbackReason) {
headers[SEARCH_FALLBACK_HEADER] = fallbackReason;
}
} 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,
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}`
),
};
}
+29 -3
View File
@@ -44,6 +44,7 @@ import {
getLinkerForSiteSpace,
getLocalizedTitle,
getSiteStructureSections,
listAllSiteSpaces,
} from '@/lib/sites';
/**
@@ -57,8 +58,6 @@ export type SiteURLData = Pick<
| 'site'
| 'siteSpace'
| 'space'
| 'revision'
| 'changeRequest'
| 'shareKey'
| 'siteSection'
| 'siteBasePath'
@@ -71,6 +70,14 @@ export type SiteURLData = Pick<
*/
imagesContextId: string;
/**
* Space revision, change request or site revision the URL previews: at most one is set. The
* middleware reads them from the resolved content, which types them as exclusive.
*/
revision?: string;
changeRequest?: string;
siteRevision?: string;
/**
* Whether this request is a fallback rendering.
* We use this when switching variant as we don't know if the page exists in the other variant.
@@ -144,7 +151,7 @@ export type GitBookBaseContext = {
/**
* Target for the browser to query the site search API directly with a search pass.
*/
directSearch?: Omit<DirectSearchProps, 'spaces' | 'passURL'>;
directSearch?: Omit<DirectSearchProps, 'spaces' | 'passURL' | 'proxyURL'>;
};
/**
@@ -217,6 +224,9 @@ export type GitBookSiteContext = GitBookSpaceContext & {
/** Whether search indexation is blocked for this deployment. */
noIndexSearch: boolean;
/** Site revision the URL previews. Content is read as it pins it. */
siteRevision?: string;
/** Whether the request included a visitor token. */
isLoggedInVisitor: boolean;
@@ -250,6 +260,13 @@ export function getBaseContext(input: {
const dataFetcher = createDataFetcher({
apiToken: siteURLData.apiToken ?? null,
siteRevision: siteURLData.siteRevision
? {
organizationId: siteURLData.organization,
siteId: siteURLData.site,
siteRevisionId: siteURLData.siteRevision,
}
: undefined,
});
const linkerInput: SiteLinkerInput = {
@@ -305,6 +322,7 @@ export async function fetchSiteContextByURLLookup(
contextId: data.contextId,
isFallback: data.isFallback ?? false,
noIndexSearch: data.noIndexSearch ?? false,
siteRevision: data.siteRevision,
isLoggedInVisitor: data.isLoggedInVisitor ?? false,
preview: data.preview ?? false,
displayAgentInstructions: data.displayAgentInstructions,
@@ -329,6 +347,7 @@ export async function fetchSiteContextByIds(
contextId?: string;
isFallback: boolean;
noIndexSearch: boolean;
siteRevision?: string;
isLoggedInVisitor: boolean;
preview: boolean;
displayAgentInstructions?: boolean;
@@ -462,6 +481,12 @@ export async function fetchSiteContextByIds(
return {
...spaceContext,
// Only the site's own spaces are read at the site revision it previews.
dataFetcher: ids.siteRevision
? spaceContext.dataFetcher.withSiteRevisionSpaces(
listAllSiteSpaces(siteStructure).map((entry) => entry.space.id)
)
: spaceContext.dataFetcher,
locale: siteSpace.space.language ?? spaceContext.locale,
linker: getLinkerForSiteSpace(siteLinker, siteSpace, spaceContext.revision.pages),
organizationId: ids.organization,
@@ -477,6 +502,7 @@ export async function fetchSiteContextByIds(
contextId: ids.contextId,
isFallback: ids.isFallback,
noIndexSearch: ids.noIndexSearch,
siteRevision: ids.siteRevision,
isLoggedInVisitor: ids.isLoggedInVisitor,
preview: ids.preview,
displayAgentInstructions: ids.displayAgentInstructions,
+351 -47
View File
@@ -11,7 +11,7 @@ import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-t
import { cache } from '../cache';
import { DataFetcherError, wrapDataFetcherError } from './errors';
import type { GitBookDataFetcher } from './types';
import type { DataFetcherResponse, GitBookDataFetcher } from './types';
import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@/lib/env';
import { toSearchSiteContentBody } from '@/lib/search-results';
import { trace } from '@/lib/tracing';
@@ -21,6 +21,25 @@ interface DataFetcherInput {
* API token.
*/
apiToken: string | null;
/**
* Site revision being previewed. The site's spaces and OpenAPI specs are read at it.
*/
siteRevision?: DataFetcherSiteRevision;
}
/**
* A site revision, as a preview URL resolves it.
*/
export interface DataFetcherSiteRevision {
organizationId: string;
siteId: string;
siteRevisionId: string;
/**
* Spaces of the site, read at the site revision. Other spaces are read live. Until the site
* structure is known, every space is read at the site revision.
*/
spaceIds?: string[];
}
/**
@@ -46,10 +65,18 @@ export function createDataFetcher(
withToken({ apiToken }) {
return createDataFetcher({
...input,
apiToken,
});
},
withSiteRevisionSpaces(spaceIds) {
return createDataFetcher({
...input,
siteRevision: input.siteRevision ? { ...input.siteRevision, spaceIds } : undefined,
});
},
//
// API that are tied to the token
//
@@ -77,61 +104,120 @@ export function createDataFetcher(
});
},
getRevision(params) {
return getRevision(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
metadata: params.metadata ?? false,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
getRevisionAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
metadata: params.metadata ?? false,
}),
() =>
getRevision(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
metadata: params.metadata ?? false,
})
);
},
getRevisionPageByPath(params) {
return getRevisionPageByPath(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
path: params.path,
metadata: params.metadata,
cachedMetadata: params.cachedMetadata,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
getPageByPathAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
path: params.path,
metadata: params.metadata ?? false,
cachedMetadata: params.cachedMetadata ?? false,
}),
() =>
getRevisionPageByPath(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
path: params.path,
metadata: params.metadata,
cachedMetadata: params.cachedMetadata,
})
);
},
getRevisionPageMarkdown(params) {
return getRevisionPageMarkdown(
return readAtSiteRevision(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageMarkdown'
params.spaceId,
(siteRevisionInput) =>
getPageMarkdownAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
pageId: params.pageId,
}),
() =>
getRevisionPageMarkdown(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageMarkdown'
)
);
},
getRevisionPageDocument(params) {
return getRevisionPageDocument(
return readAtSiteRevision(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageDocument'
params.spaceId,
(siteRevisionInput) =>
getPageDocumentAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
pageId: params.pageId,
}),
() =>
getRevisionPageDocument(
input,
{
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
},
// We pass the name of the function to distinguish between cache entries
// By default Next only uses the arguments, the filename and the position of the function inside the file
// By adding a dummy argument with the function name, we can change the order without breaking anything
'getRevisionPageDocument'
)
);
},
getRevisionReusableContentDocument(params) {
return getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
getReusableContentDocumentAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
reusableContentId: params.reusableContentId,
}),
() =>
getRevisionReusableContentDocument(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
reusableContentId: params.reusableContentId,
})
);
},
getLatestOpenAPISpecVersionContent(params) {
return getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
});
return readAtSiteRevision(
input,
null,
(siteRevisionInput) =>
getOpenAPISpecContentAtSiteRevision(siteRevisionInput, { slug: params.slug }),
() =>
getLatestOpenAPISpecVersionContent(input, {
organizationId: params.organizationId,
slug: params.slug,
})
);
},
getSpace(params) {
return getSpace(input, {
@@ -195,15 +281,233 @@ export function createDataFetcher(
},
listRevisionPageMetaLinks(params) {
return listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
});
return readAtSiteRevision(
input,
params.spaceId,
(siteRevisionInput) =>
listPageMetaLinksAtSiteRevision(siteRevisionInput, {
spaceId: params.spaceId,
pageId: params.pageId,
}),
() =>
listRevisionPageMetaLinks(input, {
spaceId: params.spaceId,
revisionId: params.revisionId,
pageId: params.pageId,
})
);
},
};
}
/**
* Data fetcher input to read at a site revision. It leaves out the site's space IDs, which only
* choose what to read at the site revision, so they stay out of cache keys.
*/
type SiteRevisionDataFetcherInput = DataFetcherInput & {
siteRevision: Omit<DataFetcherSiteRevision, 'spaceIds'>;
};
/**
* Read content at the site revision of the input, or `live` when there is no site revision or
* for a space outside the site. An OpenAPI spec (no space) is always read at the site revision.
*/
async function readAtSiteRevision<T>(
input: DataFetcherInput,
spaceId: string | null,
atSiteRevision: (input: SiteRevisionDataFetcherInput) => Promise<DataFetcherResponse<T>>,
live: () => Promise<DataFetcherResponse<T>>
): Promise<DataFetcherResponse<T>> {
const { siteRevision } = input;
if (!siteRevision || (spaceId && siteRevision.spaceIds?.includes(spaceId) === false)) {
return live();
}
const { spaceIds: _spaceIds, ...cacheableSiteRevision } = siteRevision;
return atSiteRevision({ ...input, siteRevision: cacheableSiteRevision });
}
// Each read at a site revision sends the same query as its live counterpart.
const getRevisionAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; metadata: boolean }) => {
'use cache';
return fetchAtSiteRevision(
input,
`getRevisionAtSiteRevision(${params.spaceId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getRevisionInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
{ metadata: params.metadata },
{ ...noCacheFetchOptions }
)
);
}
);
const getPageByPathAtSiteRevision = cache(
async (
input: SiteRevisionDataFetcherInput,
params: { spaceId: string; path: string; metadata: boolean; cachedMetadata: boolean }
) => {
'use cache';
return fetchAtSiteRevision(
input,
`getPageByPathAtSiteRevision(${params.spaceId}, ${params.path})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getPageByPathInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
encodeURIComponent(params.path),
{ metadata: params.metadata, cachedMetadata: params.cachedMetadata },
{ ...noCacheFetchOptions }
)
);
}
);
const getPageMarkdownAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
'use cache';
return wrapDataFetcherError(async () => {
return trace(
`getPageMarkdownAtSiteRevision(${params.spaceId}, ${params.pageId})`,
async () => {
const { organizationId, siteId, siteRevisionId } = input.siteRevision;
const res = await apiClient(input).orgs.getPageInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.pageId,
{
format: 'markdown',
'format.markdown.refs': 'stable',
evaluated: 'deterministic-only',
metadata: false,
},
{ ...noCacheFetchOptions }
);
cacheTag(...getCacheTagsFromResponse(res));
cacheLife('max');
if (!('markdown' in res.data)) {
throw new DataFetcherError('Page is not a document', 404);
}
return res.data.markdown;
}
);
});
}
);
const getPageDocumentAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
'use cache';
return fetchAtSiteRevision(
input,
`getPageDocumentAtSiteRevision(${params.spaceId}, ${params.pageId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getPageDocumentInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.pageId,
{ evaluated: 'deterministic-only', dereferenced: 'reusable-contents' },
{ ...noCacheFetchOptions }
)
);
}
);
const getReusableContentDocumentAtSiteRevision = cache(
async (
input: SiteRevisionDataFetcherInput,
params: { spaceId: string; reusableContentId: string }
) => {
'use cache';
return fetchAtSiteRevision(
input,
`getReusableContentDocumentAtSiteRevision(${params.spaceId}, ${params.reusableContentId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getReusableContentDocumentInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.reusableContentId,
{ evaluated: 'deterministic-only' },
{ ...noCacheFetchOptions }
)
);
}
);
const listPageMetaLinksAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { spaceId: string; pageId: string }) => {
'use cache';
return fetchAtSiteRevision(
input,
`listPageMetaLinksAtSiteRevision(${params.spaceId}, ${params.pageId})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.listPageMetaLinksInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.spaceId,
params.pageId,
{ ...noCacheFetchOptions }
)
);
}
);
const getOpenAPISpecContentAtSiteRevision = cache(
async (input: SiteRevisionDataFetcherInput, params: { slug: string }) => {
'use cache';
return fetchAtSiteRevision(
input,
`getOpenAPISpecContentAtSiteRevision(${params.slug})`,
(api, { organizationId, siteId, siteRevisionId }) =>
api.orgs.getOpenApiSpecContentInSiteRevision(
organizationId,
siteId,
siteRevisionId,
params.slug,
{ ...noCacheFetchOptions }
)
);
}
);
/**
* Fetch from an endpoint at a site revision. What a site revision pins never changes, so the
* response is cached forever.
*/
function fetchAtSiteRevision<T>(
input: SiteRevisionDataFetcherInput,
name: string,
request: (
api: ReturnType<typeof apiClient>,
siteRevision: SiteRevisionDataFetcherInput['siteRevision']
) => Promise<HttpResponse<T, unknown>>
): Promise<DataFetcherResponse<T>> {
return wrapDataFetcherError(async () => {
return trace(name, async () => {
const res = await request(apiClient(input), input.siteRevision);
cacheTag(...getCacheTagsFromResponse(res));
cacheLife('max');
return res.data;
});
});
}
/**
* Infer the cache life from the api response headers.
* @param response The response from the API call.
+6
View File
@@ -51,6 +51,12 @@ export interface GitBookDataFetcher {
*/
withToken(input: { apiToken: string }): GitBookDataFetcher;
/**
* Create a data fetcher that reads only these spaces at the site revision it previews, and
* other spaces live.
*/
withSiteRevisionSpaces(spaceIds: string[]): GitBookDataFetcher;
/**
* Get a user by its ID.
*/
+4 -1
View File
@@ -10,6 +10,7 @@ import {
} from '@gitbook/openapi-parser';
import { enrichFilesystem } from './enrich';
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
import type {
AnyOpenAPIOperationsBlock,
OpenAPISchemasBlock,
@@ -41,7 +42,9 @@ export async function fetchOpenAPIFilesystem(
// If the reference is a new OpenAPI reference, we return it.
if (ref.kind === 'openapi') {
assert(resolved.openapi?.filesystem);
return resolved.openapi.filesystem;
return resolveOpenAPIDescriptionLinks(resolved.openapi.filesystem, (contentRef) =>
resolveContentRef(contentRef, context)
);
}
// For legacy blocks ("swagger"), we need to fetch the file system.
return fetchFilesystem(resolved.href, context.space.id);
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'bun:test';
import { parseOpenAPI } from '@gitbook/openapi-parser';
import { resolveOpenAPIDescriptionLinks } from './resolveDescriptionLinks';
const APP_URL = 'https://app.gitbook.com/s/space-1/tables';
describe('resolveOpenAPIDescriptionLinks', () => {
it('points tagged links at their resolved URL without mutating the input', async () => {
const original =
`<p><a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>` +
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
' <a href="https://example.com">Docs</a></p>';
const { filesystem } = await parseOpenAPI({
value: JSON.stringify({
openapi: '3.0.0',
info: { title: 'Test', version: '1.0.0' },
paths: {},
components: {
schemas: {
Condition: { type: 'object', 'x-gitbook-description-html': original },
},
},
}),
rootURL: null,
});
const resolved = await resolveOpenAPIDescriptionLinks(filesystem, async (ref) =>
ref.kind === 'page' && ref.page === 'page-1' ? { href: '/docs/tables' } : null
);
expect(resolved[0]?.specification.components?.schemas?.Condition).toMatchObject({
'x-gitbook-description-html':
'<p><a href="/docs/tables" data-gitbook-ref="/spaces/space-1/pages/page-1">Fields</a>' +
` <a href="${APP_URL}" data-gitbook-ref="/spaces/space-1/pages/missing">Gone</a>` +
' <a href="https://example.com">Docs</a></p>',
});
// The spec content comes from the data cache, shared across sites.
expect(filesystem[0]?.specification.components?.schemas?.Condition).toMatchObject({
'x-gitbook-description-html': original,
});
});
});
@@ -0,0 +1,173 @@
import { type DefaultTreeAdapterMap, parseFragment } from 'parse5';
import * as React from 'react';
import type { ContentRef } from '@gitbook/api';
import type { Filesystem, OpenAPIV3xDocument } from '@gitbook/openapi-parser';
import { escapeHTML } from '@/lib/html';
import { resolveStringContentRef } from '@/lib/references';
const DESCRIPTION_HTML_KEY = 'x-gitbook-description-html';
// Slate JSON, which never holds description HTML: skipped to keep the walk short.
const DESCRIPTION_DOCUMENT_KEY = 'x-gitbook-description-document';
// Set by spec processing on links to GitBook content, e.g. `/spaces/{space}/pages/{page}`.
const CONTENT_REF_ATTRIBUTE = 'data-gitbook-ref';
type OpenAPIFilesystem = Filesystem<OpenAPIV3xDocument>;
type ResolveContentRef = (ref: ContentRef) => Promise<{ href: string } | null>;
// Per request: resolved hrefs depend on the site being rendered.
const getResolvedFilesystems = React.cache(
() => new WeakMap<OpenAPIFilesystem, Promise<OpenAPIFilesystem>>()
);
/**
* Point description links that spec processing tagged with a content ref at their URL in the
* current site. Links whose ref doesn't resolve keep the href written in the spec.
* Returns a copy when something changed: the input may be shared through the data cache.
*/
export function resolveOpenAPIDescriptionLinks(
filesystem: OpenAPIFilesystem,
resolveContentRef: ResolveContentRef
): Promise<OpenAPIFilesystem> {
const resolvedFilesystems = getResolvedFilesystems();
let promise = resolvedFilesystems.get(filesystem);
if (!promise) {
promise = baseResolveOpenAPIDescriptionLinks(filesystem, resolveContentRef);
resolvedFilesystems.set(filesystem, promise);
}
return promise;
}
async function baseResolveOpenAPIDescriptionLinks(
filesystem: OpenAPIFilesystem,
resolveContentRef: ResolveContentRef
): Promise<OpenAPIFilesystem> {
// Tagged HTML → its rewritten version, filled in once the refs resolve.
const rewritten = new Map<string, string>();
mapDescriptionHTML(filesystem, (html) => {
if (html.includes(CONTENT_REF_ATTRIBUTE)) {
rewritten.set(html, html);
}
return html;
});
if (rewritten.size === 0) {
return filesystem;
}
const hrefs = new Map<string, Promise<string | null>>();
const resolveHref = (source: string) => {
let href = hrefs.get(source);
if (!href) {
const ref = resolveStringContentRef(source);
href = ref
? resolveContentRef(ref).then((resolved) => resolved?.href ?? null)
: Promise.resolve(null);
hrefs.set(source, href);
}
return href;
};
await Promise.all(
Array.from(rewritten.keys(), async (html) => {
rewritten.set(html, await rewriteLinks(html, resolveHref));
})
);
return mapDescriptionHTML(filesystem, (html) => rewritten.get(html) ?? html);
}
/**
* Replace the href of each tagged link with its resolved URL.
*/
async function rewriteLinks(
html: string,
resolveHref: (source: string) => Promise<string | null>
): Promise<string> {
const fragment = parseFragment(html, { sourceCodeLocationInfo: true });
const replacements: { start: number; end: number; value: string }[] = [];
await Promise.all(
collectLinks(fragment).map(async (link) => {
const source = link.attrs.find((attr) => attr.name === CONTENT_REF_ATTRIBUTE)?.value;
const location = link.sourceCodeLocation?.attrs?.href;
if (!source || !location) {
return;
}
const href = await resolveHref(source);
if (href) {
replacements.push({
start: location.startOffset,
end: location.endOffset,
value: `href="${escapeHTML(href)}"`,
});
}
})
);
// Apply from the end so earlier offsets stay valid.
replacements.sort((a, b) => b.start - a.start);
let result = html;
for (const { start, end, value } of replacements) {
result = result.slice(0, start) + value + result.slice(end);
}
return result;
}
function collectLinks(
node: DefaultTreeAdapterMap['node'],
links: DefaultTreeAdapterMap['element'][] = []
): DefaultTreeAdapterMap['element'][] {
if ('tagName' in node && node.tagName === 'a') {
links.push(node);
}
if ('childNodes' in node) {
for (const child of node.childNodes) {
collectLinks(child, links);
}
}
return links;
}
/**
* Map every description HTML in a JSON value, copying only the objects on a changed path.
*/
function mapDescriptionHTML<T>(value: T, transform: (html: string) => string): T {
if (typeof value !== 'object' || value === null) {
return value;
}
if (Array.isArray(value)) {
let result: unknown[] | null = null;
for (let index = 0; index < value.length; index++) {
const item = value[index];
const next = mapDescriptionHTML(item, transform);
if (next !== item) {
result ??= [...value];
result[index] = next;
}
}
return (result ?? value) as T;
}
const record = value as Record<string, unknown>;
let result: Record<string, unknown> | null = null;
// `for...in` over plain JSON objects: several times faster than `Object.entries` on large specs.
for (const key in record) {
if (key === DESCRIPTION_DOCUMENT_KEY) {
continue;
}
const child = record[key];
const next =
key === DESCRIPTION_HTML_KEY && typeof child === 'string'
? transform(child)
: mapDescriptionHTML(child, transform);
if (next !== child) {
result ??= { ...record };
result[key] = next;
}
}
return (result ?? record) as T;
}
@@ -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
View File
@@ -32,6 +32,7 @@ export function isSiteIndexable(context: GitBookSiteContext) {
if (
context.changeRequest ||
context.siteRevision ||
context.revisionId !== context.space.revision ||
hasRevisionSelector(context.linker.spaceBasePath)
) {
+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');
+159
View File
@@ -0,0 +1,159 @@
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',
'content-type': 'text/plain',
'user-agent': 'Mozilla/5.0',
[PASS_HEADER]: SEARCH_PASS,
'x-gitbook-search-fallback': 'network',
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',
'user-agent': 'Mozilla/5.0',
'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('x-content-type-options')).toBe('nosniff');
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
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(response.headers.get('x-content-type-options')).toBe('nosniff');
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it('returns an uncached 502 when reading the upstream response body fails', async () => {
const body = new ReadableStream({
start(controller) {
controller.error(new TypeError('Connection reset'));
},
});
fetchSpy.mockResolvedValueOnce(new Response(body, { status: 200 }));
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(response.headers.get('x-content-type-options')).toBe('nosniff');
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it('passes through null-body statuses without throwing', async () => {
fetchSpy.mockResolvedValueOnce(new Response(null, { status: 204 }));
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(204);
expect(response.body).toBeNull();
expect(response.headers.get('cache-control')).toBe('no-store');
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
});
});
+131 -14
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,20 @@ 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}$/;
const DIRECT_SEARCH_TIMEOUT_MS = 5_000;
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 +113,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 +176,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 +194,95 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
return response;
}
async function serveDirectSearch(request: NextRequest, organizationId = '', siteId = '') {
const responseHeaders = new Headers({
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
});
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': 'application/json',
});
const userAgent = request.headers.get('User-Agent');
if (userAgent) headers.set('User-Agent', userAgent);
const ip = request.headers.get('x-gitbook-ip') ?? getXForwardedFor(request.headers);
if (ip) headers.set('X-Forwarded-For', ip);
const controller = new AbortController();
const abort = () => controller.abort();
if (request.signal.aborted) {
abort();
}
request.signal.addEventListener('abort', abort, { once: true });
const timeout = setTimeout(abort, DIRECT_SEARCH_TIMEOUT_MS);
const startedAt = performance.now();
try {
const upstream = await fetch(
`${removeTrailingSlash(GITBOOK_API_URL)}/v1/orgs/${organizationId}/sites/${siteId}/search`,
{
method: 'POST',
headers,
body: request.body,
redirect: 'manual',
signal: controller.signal,
duplex: 'half',
} as RequestInit
);
let responseBody: ArrayBuffer | null = null;
if (upstream.status !== 204 && upstream.status !== 205 && upstream.status !== 304) {
responseBody = await upstream.arrayBuffer();
}
responseHeaders.set(
'Server-Timing',
`api;dur=${Math.round(performance.now() - startedAt)}`
);
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 fallback = request.headers.get('x-gitbook-search-fallback');
if (upstream.ok && (fallback === 'network' || fallback === 'timeout')) {
getLogger().subLogger('directSiteSearch').info('Direct search recovered via proxy', {
reason: fallback,
organizationId,
siteId,
});
}
return new Response(responseBody, { status: upstream.status, headers: responseHeaders });
} catch {
responseHeaders.set(
'Server-Timing',
`api;dur=${Math.round(performance.now() - startedAt)}`
);
getLogger().subLogger('directSiteSearch').warn('Direct search upstream failed', {
status: 502,
organizationId,
siteId,
});
return new Response(null, { status: 502, headers: responseHeaders });
} finally {
clearTimeout(timeout);
request.signal.removeEventListener('abort', abort);
}
}
async function serveSiteRequest(requestURL: URL, request: NextRequest, match: URLWithMode) {
const { url: siteRequestURL, mode } = match;
@@ -449,8 +549,7 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
basePath: siteURLData.basePath,
space: siteURLData.space,
organization: siteURLData.organization,
changeRequest: siteURLData.changeRequest,
revision: siteURLData.revision,
...getPreviewedContent(siteURLData),
shareKey: siteURLData.shareKey,
preview: siteURLData.preview,
apiToken: siteURLData.apiToken,
@@ -965,7 +1064,7 @@ function encodePathInSiteContent(
siteSpace: siteURLData.siteSpace,
siteShareKey: siteURLData.shareKey,
space: siteURLData.space,
revision: siteURLData.revision,
revision: getPreviewedContent(siteURLData).revision,
displayContext: SiteInsightsDisplayContext.Server,
};
@@ -1229,3 +1328,21 @@ function acceptsMarkdown(request: Request): boolean {
const htmlIndex = mediaTypes.findIndex((type) => type === 'text/html' || type === '*/*');
return htmlIndex === -1 || markdownIndex < htmlIndex;
}
/**
* The revision, change request or site revision a URL previews: at most one of them.
*/
function getPreviewedContent(
content: PublishedSiteContent
): Pick<SiteURLData, 'revision' | 'changeRequest' | 'siteRevision'> {
if ('revision' in content) {
return { revision: content.revision };
}
if ('changeRequest' in content) {
return { changeRequest: content.changeRequest };
}
if ('siteRevision' in content) {
return { siteRevision: content.siteRevision };
}
return {};
}