mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-25 17:54:27 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dc5ec80893 | |||
| 429a63bb59 | |||
| b08a4f9acd | |||
| c9e2de32b6 | |||
| fa19dc41aa | |||
| 8fed05f354 | |||
| 9f0531484e | |||
| 30ea30421d | |||
| 4c01f40d7e |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Retry direct site search on the site's own domain after a network error or timeout.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Prevent self-redirect loops and skip redirects targeting hidden adaptive content.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Drop description HTML supplied by OpenAPI specs and sanitize example descriptions that could render HTML.
|
||||
@@ -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}`
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
|
||||
import type { RevisionPageDocument, SiteRedirectDestination } from '@gitbook/api';
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
|
||||
@@ -23,28 +23,15 @@ const page = {
|
||||
|
||||
describe('resolveMissingPagePath', () => {
|
||||
function createRedirectContext(options: {
|
||||
siteRedirect?: {
|
||||
source?: string;
|
||||
target: string;
|
||||
permanent?: boolean;
|
||||
destination?: SiteRedirectDestination;
|
||||
};
|
||||
siteRedirect?: { source?: string; target: string; permanent?: boolean };
|
||||
spaceRedirectPageId?: string;
|
||||
contextId?: string;
|
||||
structure?: GitBookSiteContext['structure'];
|
||||
revisionsBySpace?: Record<string, RevisionPageDocument[]>;
|
||||
}) {
|
||||
const getSiteRedirectBySource = mock(async ({ source }: { source: string }) =>
|
||||
options.siteRedirect && source === (options.siteRedirect.source ?? '/old')
|
||||
? {
|
||||
data: {
|
||||
target: options.siteRedirect.target,
|
||||
redirect: {
|
||||
permanent: options.siteRedirect.permanent ?? false,
|
||||
...(options.siteRedirect.destination
|
||||
? { destination: options.siteRedirect.destination }
|
||||
: {}),
|
||||
},
|
||||
redirect: { permanent: options.siteRedirect.permanent ?? false },
|
||||
},
|
||||
}
|
||||
: { error: { code: 404, message: 'Not found' } }
|
||||
@@ -54,35 +41,19 @@ describe('resolveMissingPagePath', () => {
|
||||
? { data: { id: options.spaceRedirectPageId } }
|
||||
: { error: { code: 404, message: 'Not found' } }
|
||||
);
|
||||
const getRevision = mock(async ({ spaceId }: { spaceId: string }) =>
|
||||
options.revisionsBySpace?.[spaceId]
|
||||
? { data: { pages: options.revisionsBySpace[spaceId] } }
|
||||
: { error: { code: 404, message: 'Not found' } }
|
||||
);
|
||||
|
||||
const defaultSiteSpace = {
|
||||
id: 'site-space-1',
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
};
|
||||
|
||||
return {
|
||||
organizationId: 'org-1',
|
||||
site: { id: 'site-1' },
|
||||
siteSpace: defaultSiteSpace,
|
||||
structure: options.structure ?? {
|
||||
type: 'siteSpaces',
|
||||
structure: [defaultSiteSpace],
|
||||
},
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
revisionId: 'revision-1',
|
||||
revision: { pages: [page] },
|
||||
contextId: options.contextId,
|
||||
linker: {
|
||||
toPathInSpace: (path: string) => path,
|
||||
toRelativePathInSite: (path: string) => path,
|
||||
toLinkForContent: (url: string) => new URL(url).pathname,
|
||||
},
|
||||
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath, getRevision },
|
||||
dataFetcher: { getSiteRedirectBySource, getRevisionPageByPath },
|
||||
} as unknown as GitBookSiteContext;
|
||||
}
|
||||
|
||||
@@ -116,224 +87,6 @@ describe('resolveMissingPagePath', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a site redirect that targets the current path', async () => {
|
||||
const context = createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/release-notes/restricted',
|
||||
target: 'https://docs.example.com/release-notes/restricted',
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect that targets the current path with trailing slash, case, or query differences', async () => {
|
||||
const context = createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/release-notes/restricted',
|
||||
target: 'https://docs.example.com/Release-Notes/Restricted/?tab=1#top',
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'release-notes/restricted')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a space-relative redirect that resolves back to the current section path', async () => {
|
||||
const context = {
|
||||
...createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/v3/getting-started',
|
||||
target: 'https://docs.example.com/docs/v3/getting-started',
|
||||
},
|
||||
}),
|
||||
linker: createLinker({
|
||||
host: 'docs.example.com',
|
||||
siteBasePath: '/',
|
||||
spaceBasePath: '/docs/',
|
||||
}),
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'v3/getting-started')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting a hidden site space on an adaptive site', async () => {
|
||||
const context = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
siteRedirect: {
|
||||
source: '/getting-started',
|
||||
target: 'https://docs.example.com/docs/v3/getting-started',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-hidden',
|
||||
pageId: 'page-v3',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'getting-started')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting a hidden section on an adaptive site', async () => {
|
||||
const context = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
structure: {
|
||||
type: 'sections',
|
||||
structure: [
|
||||
{
|
||||
object: 'site-section',
|
||||
id: 'section-visible',
|
||||
siteSpaces: [
|
||||
{
|
||||
id: 'site-space-1',
|
||||
space: { id: 'space-1', revision: 'revision-1' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as GitBookSiteContext['structure'],
|
||||
siteRedirect: {
|
||||
source: '/old-section',
|
||||
target: 'https://docs.example.com/hidden-section',
|
||||
destination: {
|
||||
kind: 'site-section',
|
||||
siteSectionId: 'section-hidden',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'old-section')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting a hidden page in the current space on an adaptive site', async () => {
|
||||
const context = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
siteRedirect: {
|
||||
source: '/release-notes/restricted.html',
|
||||
target: 'https://docs.example.com/release-notes/restricted',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-1',
|
||||
pageId: 'hidden-page',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await resolveMissingPagePath(context, 'release-notes/restricted.html')
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('checks target page visibility in another accessible space on an adaptive site', async () => {
|
||||
const otherSpace = {
|
||||
id: 'site-space-2',
|
||||
space: { id: 'space-2', revision: 'revision-2' },
|
||||
};
|
||||
const structure = {
|
||||
type: 'siteSpaces',
|
||||
structure: [
|
||||
{ id: 'site-space-1', space: { id: 'space-1', revision: 'revision-1' } },
|
||||
otherSpace,
|
||||
],
|
||||
} as unknown as GitBookSiteContext['structure'];
|
||||
|
||||
const hiddenContext = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
structure,
|
||||
revisionsBySpace: { 'space-2': [] },
|
||||
siteRedirect: {
|
||||
source: '/old',
|
||||
target: 'https://docs.example.com/other/secret',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-2',
|
||||
pageId: 'page-secret',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(await resolveMissingPagePath(hiddenContext, 'old')).toBeUndefined();
|
||||
|
||||
const visibleContext = createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
structure,
|
||||
revisionsBySpace: { 'space-2': [{ ...page, id: 'page-secret', path: 'secret' }] },
|
||||
siteRedirect: {
|
||||
source: '/old',
|
||||
target: 'https://docs.example.com/other/secret',
|
||||
destination: {
|
||||
kind: 'site-page',
|
||||
siteSpaceId: 'site-space-2',
|
||||
pageId: 'page-secret',
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(await resolveMissingPagePath(visibleContext, 'old')).toEqual({
|
||||
type: 'redirect',
|
||||
destination: '/other/secret',
|
||||
permanent: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a site redirect targeting the reassigned default variant path of the current space', async () => {
|
||||
const context = {
|
||||
...createRedirectContext({
|
||||
contextId: 'adaptive-ctx',
|
||||
siteRedirect: {
|
||||
source: '/guide/missing',
|
||||
target: 'https://docs.example.com/guide/v3/missing',
|
||||
destination: {
|
||||
kind: 'site-space',
|
||||
siteSpaceId: 'site-space-v3',
|
||||
},
|
||||
},
|
||||
structure: {
|
||||
type: 'sections',
|
||||
structure: [
|
||||
{
|
||||
object: 'site-section',
|
||||
id: 'section-guide',
|
||||
siteSpaces: [
|
||||
{
|
||||
id: 'site-space-v3',
|
||||
path: 'v3',
|
||||
default: true,
|
||||
space: { id: 'space-v3', revision: 'revision-1' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as GitBookSiteContext['structure'],
|
||||
}),
|
||||
siteSpace: {
|
||||
id: 'site-space-v3',
|
||||
path: 'v3',
|
||||
default: true,
|
||||
space: { id: 'space-v3', revision: 'revision-1' },
|
||||
},
|
||||
linker: createLinker({
|
||||
host: 'docs.example.com',
|
||||
siteBasePath: '/',
|
||||
spaceBasePath: '/guide/',
|
||||
}),
|
||||
} as unknown as GitBookSiteContext;
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'missing')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('keeps a redirect whose current path contains a literal question mark', async () => {
|
||||
const context = createRedirectContext({
|
||||
siteRedirect: {
|
||||
source: '/foo/bar%3Fbaz',
|
||||
target: 'https://docs.example.com/foo/bar',
|
||||
},
|
||||
});
|
||||
|
||||
expect(await resolveMissingPagePath(context, 'foo/bar?baz')).toEqual({
|
||||
type: 'redirect',
|
||||
destination: '/foo/bar',
|
||||
permanent: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves a space redirect to a page', async () => {
|
||||
const context = createRedirectContext({ spaceRedirectPageId: page.id });
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import { permanentRedirect, redirect } from 'next/navigation';
|
||||
|
||||
import {
|
||||
type RevisionPageDocument,
|
||||
type SiteRedirect,
|
||||
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
|
||||
SITE_REDIRECT_SOURCE_PATH_PATTERN,
|
||||
} from '@gitbook/api';
|
||||
@@ -11,12 +10,7 @@ import { type GitBookSiteContext, fetchSiteContextForSiteSpace } from '@/lib/con
|
||||
import { getDataOrNull } from '@/lib/data';
|
||||
import { type ResolvedPagePath, resolvePageId } from '@/lib/pages';
|
||||
import { withLeadingSlash } from '@/lib/paths';
|
||||
import {
|
||||
findSiteSpaceBy,
|
||||
findSiteSpaceByUrl,
|
||||
getSiteStructureSections,
|
||||
resolveSiteSpacePagePath,
|
||||
} from '@/lib/sites';
|
||||
import { findSiteSpaceByUrl, resolveSiteSpacePagePath } from '@/lib/sites';
|
||||
|
||||
const MAX_PAGE_URL_REDIRECTS = 5;
|
||||
|
||||
@@ -119,14 +113,6 @@ export async function resolveMissingPagePath(
|
||||
.filter((source) => SITE_REDIRECT_SOURCE_PATH_REGEX.test(source))
|
||||
);
|
||||
|
||||
const currentPath = linker.toPathInSpace(redirectPathname);
|
||||
let currentPathWithDefaultVariant: string | null = null;
|
||||
if (context.siteSpace.default && context.siteSpace.path) {
|
||||
currentPathWithDefaultVariant = linker.toPathInSpace(
|
||||
`/${context.siteSpace.path}${redirectPathname}`
|
||||
);
|
||||
}
|
||||
|
||||
for (const source of redirectSources) {
|
||||
// We try to resolve the site redirect
|
||||
const resolvedSiteRedirect =
|
||||
@@ -140,18 +126,6 @@ export async function resolveMissingPagePath(
|
||||
})
|
||||
));
|
||||
if (resolvedSiteRedirect) {
|
||||
const destination = linker.toLinkForContent(resolvedSiteRedirect.target);
|
||||
// Skip self-redirects (including default-variant canonical aliases) and hidden adaptive targets.
|
||||
const targetsCurrentPath =
|
||||
isSameRedirectPath(currentPath, destination) ||
|
||||
(currentPathWithDefaultVariant !== null &&
|
||||
isSameRedirectPath(currentPathWithDefaultVariant, destination));
|
||||
if (
|
||||
targetsCurrentPath ||
|
||||
!(await isRedirectDestinationAccessible(context, resolvedSiteRedirect.redirect))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
const isPublicLiveContext =
|
||||
!shareKey &&
|
||||
!context.changeRequest &&
|
||||
@@ -160,7 +134,7 @@ export async function resolveMissingPagePath(
|
||||
!context.isLoggedInVisitor;
|
||||
return {
|
||||
type: 'redirect',
|
||||
destination,
|
||||
destination: linker.toLinkForContent(resolvedSiteRedirect.target),
|
||||
permanent: Boolean(
|
||||
resolvedSiteRedirect.redirect?.permanent &&
|
||||
!resolvedSiteRedirect.redirect.draft &&
|
||||
@@ -228,17 +202,6 @@ 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)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -263,60 +226,6 @@ function safeDecodeURIComponent(segment: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
async function isRedirectDestinationAccessible(
|
||||
context: GitBookSiteContext,
|
||||
siteRedirect: SiteRedirect | null
|
||||
): Promise<boolean> {
|
||||
if (!context.contextId || !siteRedirect?.destination) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const { destination } = siteRedirect;
|
||||
switch (destination.kind) {
|
||||
case 'external':
|
||||
return true;
|
||||
case 'site-section':
|
||||
return getSiteStructureSections(context.structure, { ignoreGroups: true }).some(
|
||||
(section) => section.id === destination.siteSectionId
|
||||
);
|
||||
case 'site-space':
|
||||
return Boolean(
|
||||
findSiteSpaceBy(context.structure, (entry) => entry.id === destination.siteSpaceId)
|
||||
);
|
||||
case 'site-page': {
|
||||
const target = findSiteSpaceBy(
|
||||
context.structure,
|
||||
(entry) => entry.id === destination.siteSpaceId
|
||||
);
|
||||
if (!target) {
|
||||
return false;
|
||||
}
|
||||
if (destination.siteSpaceId === context.siteSpace.id) {
|
||||
return Boolean(resolvePageId(context.revision.pages, destination.pageId));
|
||||
}
|
||||
const targetRevision = await getDataOrNull(
|
||||
context.dataFetcher.getRevision({
|
||||
spaceId: target.siteSpace.space.id,
|
||||
revisionId: target.siteSpace.space.revision,
|
||||
})
|
||||
);
|
||||
if (!targetRevision) {
|
||||
return false;
|
||||
}
|
||||
return Boolean(resolvePageId(targetRevision.pages, destination.pageId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
@@ -35,61 +35,4 @@ describe('#enrichFilesystem', () => {
|
||||
expect(paths['/a'].get['x-gitbook-description-html']).toBe('<p>constructor</p>');
|
||||
expect(paths['/b'].get['x-gitbook-description-html']).toBe('<p>constructor</p>');
|
||||
});
|
||||
|
||||
async function enrichSchemas(schemas: Record<string, unknown>) {
|
||||
const { filesystem } = await parseOpenAPI({
|
||||
value: JSON.stringify({
|
||||
openapi: '3.0.0',
|
||||
info: { title: 'Test', version: '1.0.0' },
|
||||
paths: {},
|
||||
components: { schemas },
|
||||
}),
|
||||
rootURL: null,
|
||||
});
|
||||
const enriched = await enrichFilesystem(filesystem);
|
||||
return enriched[0]?.specification.components.schemas;
|
||||
}
|
||||
|
||||
it('drops description fields supplied by the specification', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
Pet: {
|
||||
type: 'object',
|
||||
'x-gitbook-description-html': '<b>spec</b>',
|
||||
'x-gitbook-description-document': { nodes: [] },
|
||||
},
|
||||
});
|
||||
expect(schemas.Pet['x-gitbook-description-html']).toBeUndefined();
|
||||
expect(schemas.Pet['x-gitbook-description-document']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sanitizes descriptions of schemas named example', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
example: { type: 'string', description: '<img src=x onerror=alert(1)>' },
|
||||
});
|
||||
const html = schemas.example['x-gitbook-description-html'];
|
||||
expect(html).toContain('<img');
|
||||
expect(html).not.toContain('onerror');
|
||||
});
|
||||
|
||||
it('sanitizes descriptions in example values that could render HTML', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
Pet: {
|
||||
type: 'object',
|
||||
example: {
|
||||
description: '<img src=x onerror=alert(1)>',
|
||||
'x-gitbook-description-html': '<img src=x onerror=alert(2)>',
|
||||
},
|
||||
},
|
||||
});
|
||||
const html = schemas.Pet.example['x-gitbook-description-html'];
|
||||
expect(html).toBeDefined();
|
||||
expect(html).not.toContain('onerror');
|
||||
});
|
||||
|
||||
it('keeps example values without HTML as written', async () => {
|
||||
const schemas = await enrichSchemas({
|
||||
Pet: { type: 'object', example: { description: 'A **good** dog' } },
|
||||
});
|
||||
expect(schemas.Pet.example).toEqual({ description: 'A **good** dog' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,21 +8,19 @@ import { parseMarkdown } from '../markdown';
|
||||
export async function enrichFilesystem(filesystem: Filesystem) {
|
||||
const parseMarkdownWithCache = createMarkdownParser();
|
||||
return traverse(filesystem, async (node, path) => {
|
||||
// Examples included: a `$ref` can render an example value as a schema.
|
||||
delete node['x-gitbook-description-html'];
|
||||
delete node['x-gitbook-description-document'];
|
||||
|
||||
if (
|
||||
path !== undefined &&
|
||||
'description' in node &&
|
||||
typeof node.description === 'string' &&
|
||||
node.description
|
||||
) {
|
||||
const description = node.description.trim();
|
||||
// Examples stay as written, except where their raw description could render a tag.
|
||||
const isExample = path[path.length - 1] === 'example';
|
||||
if (description && (!isExample || description.includes('<'))) {
|
||||
node['x-gitbook-description-html'] = await parseMarkdownWithCache(description);
|
||||
const key = path[path.length - 1];
|
||||
// Avoid parsing descriptions in examples.
|
||||
if (key !== 'example') {
|
||||
const description = node.description.trim();
|
||||
if (description) {
|
||||
node['x-gitbook-description-html'] = await parseMarkdownWithCache(description);
|
||||
}
|
||||
}
|
||||
}
|
||||
return node;
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -94,17 +94,6 @@ describe('servePageMarkdown', () => {
|
||||
expect(response.headers.get('Location')).toBe('/docs/new-page.md');
|
||||
});
|
||||
|
||||
it('returns not-found markdown instead of looping when a site redirect targets the same markdown path', async () => {
|
||||
const context = createContext({
|
||||
siteRedirect: { target: 'https://docs.example.com/docs/old-page.md', permanent: false },
|
||||
});
|
||||
|
||||
const response = await servePageMarkdown(context, 'old-page');
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.text()).toContain('# Page Not Found');
|
||||
});
|
||||
|
||||
it('redirects to the markdown version of a space redirect target', async () => {
|
||||
const context = createContext({ spaceRedirectPageId: page.id });
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
|
||||
|
||||
import { isSameRedirectPath, resolveMissingPagePath } from '@/components/SitePage/fetch';
|
||||
import { resolveMissingPagePath } from '@/components/SitePage/fetch';
|
||||
import { isAIEnabled } from '@/components/utils/isAIChatEnabled';
|
||||
import { renderPageAgentInstructions, renderQueryingDocumentation } from '@/lib/ask-prompt';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
@@ -38,15 +38,10 @@ export async function servePageMarkdown(baseContext: GitBookSiteContext, pagePat
|
||||
if (!pageLookup) {
|
||||
const fallback = await resolveMissingPagePath(baseContext, pagePath);
|
||||
if (fallback?.type === 'redirect') {
|
||||
const destination = toMarkdownDestination(fallback.destination);
|
||||
if (
|
||||
!isSameRedirectPath(
|
||||
context.linker.toPathForPagePath({ path: pagePath }),
|
||||
destination
|
||||
)
|
||||
) {
|
||||
return markdownRedirect(destination, fallback.permanent);
|
||||
}
|
||||
return markdownRedirect(
|
||||
toMarkdownDestination(fallback.destination),
|
||||
fallback.permanent
|
||||
);
|
||||
}
|
||||
if (fallback?.type === 'page') {
|
||||
return markdownRedirect(
|
||||
|
||||
Reference in New Issue
Block a user