diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts index b8b0be63329..38b3d76449b 100644 --- a/apps/sim/connectors/website/crawl.ts +++ b/apps/sim/connectors/website/crawl.ts @@ -12,8 +12,8 @@ const CRAWL_CONCURRENCY = 4 /** * What reading one page told the crawl: the page as it belongs in the listing, if it does, and the - * links it offers. A listed page is identified by the URL it was finally served at or names as - * canonical, which may differ from the URL the crawl requested. + * links it offers. A listed page is identified by the URL it was finally served at, which may + * differ from the URL the crawl requested. */ export interface CrawledPage { value: T @@ -24,6 +24,12 @@ export interface CrawledPage { * reaches the sync, so a copy indexed before is replaced even when the crawl is incomplete. */ withdrawn?: boolean + /** + * Another page the page names as canonical: it is read and listed in this page's place, under + * its own URL and text, so its listing and its later reads agree. The page is listed itself + * only when that cannot happen: the cap is full, or the canonical page named it back. + */ + canonical?: WebsitePage links: string[] /** Where the page's relative links resolve: its final URL after redirects, or its ``. */ base?: string @@ -39,6 +45,13 @@ export interface CrawlFrontier { level: string[] next: string[] seen: string[] + /** + * Each page that handed its place to a canonical page, to that page: a chain of canonicals + * resolves to its last page, and a cycle lists one of its pages. + */ + handedOff: Record + /** Pages already listed, so a later read under another URL of one of them is not listed again. */ + listedIds: string[] admitted: number listed: number capped: boolean @@ -109,8 +122,29 @@ export async function crawlSitePages( let level = resume ? rescope(resume.level, within()) : [start] let next = resume ? rescope(resume.next, scope) : [] const seen = new Set(resume?.seen ?? [identityHash(start.url)]) + const handedOff = new Map(Object.entries(resume?.handedOff ?? {})) let admitted = resume?.admitted ?? 1 const listed: CrawlSlice['listed'] = [] + const listedIds = new Set(resume?.listedIds ?? []) + /** Admits a page the crawl has not met while `maxPages` allows; a full crawl is truncated. */ + const admit = (found: WebsitePage): 'admitted' | 'seen' | 'full' => { + const identity = identityHash(found.url) + if (seen.has(identity)) return 'seen' + if (admitted >= limits.maxPages) { + truncated = true + return 'full' + } + seen.add(identity) + admitted++ + return 'admitted' + } + // A frontier names pages on the site's own origin by path, which resolves back against it, so + // thousands of long URLs fit in one cursor. + // A path starting `//` would read back as another host, so such a URL stays whole. + const shortUrl = ({ url }: WebsitePage) => + url.startsWith(`${scope.site.origin}/`) && !url.startsWith(`${scope.site.origin}//`) + ? url.slice(scope.site.origin.length) + : url const withdrawn: T[] = [] const listedTotal = () => (resume?.listed ?? 0) + listed.length let truncated = resume?.capped ?? false @@ -131,7 +165,8 @@ export async function crawlSitePages( depth++ continue } - for (let offset = 0; offset < level.length; offset += CRAWL_CONCURRENCY) { + // Advances by the pages actually read, so canonical pages appended to the level are read too. + for (let offset = 0; offset < level.length; ) { if ( limits.signal?.aborted || (limits.endsAt !== undefined && Date.now() >= limits.endsAt) || @@ -141,14 +176,17 @@ export async function crawlSitePages( ) return slice({ depth, - level: level.slice(offset).map((page) => page.url), - next: next.map((page) => page.url), + level: level.slice(offset).map(shortUrl), + next: next.map(shortUrl), seen: [...seen], + handedOff: Object.fromEntries(handedOff), + listedIds: [...listedIds], admitted, listed: listedTotal(), capped: truncated, }) const batch = level.slice(offset, offset + CRAWL_CONCURRENCY) + offset += batch.length const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, (page) => read(page, within(), limits.signal) ) @@ -162,27 +200,47 @@ export async function crawlSitePages( const { value, listedAs, links, base } = result.value const inScope = depth > 0 || listedStart if (inScope && result.value.withdrawn) withdrawn.push(value) - if (listedAs && inScope) { - // A page served from, or canonical to, a URL the crawl has already met is that page. - const identity = identityHash(listedAs.url) - if (identity === identityHash(page.url) || !seen.has(identity)) { - seen.add(identity) - listed.push({ page: listedAs, value }) + const { canonical } = result.value + const requested = identityHash(page.url) + const self = listedAs ? identityHash(listedAs.url) : requested + // A redirect makes the requested URL another name for the page it served. + if (self !== requested) handedOff.set(requested, self) + let handOff = false + if (canonical && inScope) { + const canonicalId = identityHash(canonical.url) + const admission = admit(canonical) + if (admission === 'admitted') { + level.push(canonical) + handOff = true + } else if (admission === 'seen') { + // A canonical page queued for the next depth is read at this one, as if linked here. + const queued = next.findIndex((found) => identityHash(found.url) === canonicalId) + if (queued !== -1) level.push(...next.splice(queued, 1)) + // Follow the chain of hand-offs from the canonical page; one leading back here is a cycle. + const visited = new Set([self]) + let target = canonicalId + for (let after = handedOff.get(target); after && !visited.has(target); ) { + visited.add(target) + target = after + after = handedOff.get(target) + } + handOff = target !== self } + if (handOff) handedOff.set(self, canonicalId) + } + // A page another read already listed, under any of its URLs, is that page. + if (listedAs && inScope && !handOff && !listedIds.has(self)) { + seen.add(self) + listedIds.add(self) + listed.push({ page: listedAs, value }) } if (depth >= limits.maxDepth) continue let queued = 0 for (const link of links) { const found = scopedPage(link, scope, base ?? page.url) - if (!found) continue - const identity = identityHash(found.url) - if (seen.has(identity)) continue - if (admitted >= limits.maxPages) { - truncated = true - break - } - seen.add(identity) - admitted++ + const admission = found ? admit(found) : 'seen' + if (admission === 'full') break + if (admission === 'seen' || !found) continue next.push(found) queued++ } diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index 7f6de82a11d..69fcca8e389 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -32,7 +32,11 @@ let undeclared: 'html' | 'text' | undefined let crawlDelay = '' let lockedLink = false let extraLinks = '' -let homeCanonical = false +let bareHome = false +let signInWall: 'off-host' | 'on-host' | false = false +let homeVisits = 0 +let homeStallsAfterFirst = false +let homeForbiddenOnce = false let flakyFailures = 0 const pageRequests: { path: string; at: number }[] = [] const sitemapRequests: number[] = [] @@ -60,10 +64,72 @@ const siteServer = createServer((request, response) => { const send = (status: number, type: string, body: string | Buffer) => response.writeHead(status, { 'Content-Type': type }).end(body) if (request.headers.host?.startsWith('www.')) wwwRequests.push(request) + if (request.url === '//double') + return send(200, 'text/html', page('Double', '

Double slash

')) const path = new URL(request.url ?? '/', site).pathname if (/^\/child-\d+\.xml$/.test(path)) return send(200, 'application/xml', '') if (/\.(xml|gz)$/.test(path)) sitemapRequests.push(Date.now()) else if (!path.endsWith('.txt')) pageRequests.push({ path, at: Date.now() }) + if (signInWall && path !== '/login' && !/\.(xml|gz|txt)$/.test(path)) { + response + .writeHead(302, { Location: signInWall === 'on-host' ? `${site}/login` : `${foreign}/login` }) + .end() + return + } + if (path === '/' && homeForbiddenOnce) { + homeForbiddenOnce = false + return send(403, 'text/plain', 'forbidden') + } + if (path === '/old-new') { + response.writeHead(301, { Location: '/new-old' }).end() + return + } + if (path === '/new-old') + return send( + 200, + 'text/html', + page('New', '

New home of the page

', ``) + ) + if (path === '/q-page') + return send(200, 'text/html', page('Q', '

Q

C')) + if (path === '/print2') + return send( + 200, + 'text/html', + page('Print2', '

Print

', ``) + ) + if (path === '/canon2') + return send(200, 'text/html', page('Canon2', '

Canon

Leaf')) + if (path === '/deep-leaf') return send(200, 'text/html', page('Leaf', '

Leaf

')) + if (/^\/link-[abc]$/.test(path)) + return send( + 200, + 'text/html', + page( + 'Link', + `

Link ${path}

`, + path === '/link-c' + ? '' + : `` + ) + ) + if (path === '/' && homeStallsAfterFirst && homeVisits++ > 0) { + hung.push(response) + return + } + if (/^\/cycle-[ab]$/.test(path)) + return send( + 200, + 'text/html', + page( + 'Cycle', + `

Cycle ${path}

`, + `` + ) + ) + if (/^\/long-\d+-x+$/.test(path)) return send(200, 'text/html', page('Long', '

Long path

')) + if (/^\/big-\d+$/.test(path)) + return send(200, 'text/html', page('Big', `

${'word '.repeat(80_000)}${path}

`)) if (/^\/many-\d+$/.test(path)) return send(200, 'text/html', page('Many', `

Page ${path}

`)) if (/^\/quiet-\d+$/.test(path)) return send( @@ -76,10 +142,20 @@ const siteServer = createServer((request, response) => { return send( 200, 'text/html', - `Home${homeCanonical ? `` : ''}

Welcome.

HiddenPlans${lockedLink ? 'Locked' : ''}${extraLinks}
` + bareHome + ? `Home${homeStallsAfterFirst ? '' : ''}

Welcome.

${extraLinks}
` + : `Home

Welcome.

HiddenPlans${lockedLink ? 'Locked' : ''}${extraLinks}
` ) case '/corrupt.xml.gz': return send(200, 'application/gzip', Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0x01, 0x02])) + case '/print-only': + return send( + 200, + 'text/html', + page('Print', '

Printable copy

', ``) + ) + case '/canon-target': + return send(200, 'text/html', page('Canonical', '

Canonical text

')) case '/print-faq': return send( 200, @@ -89,6 +165,9 @@ const siteServer = createServer((request, response) => { case '/old-faq': response.writeHead(301, { Location: '/faq' }).end() return + case '/old-guide': + response.writeHead(301, { Location: '/guide/' }).end() + return case '/guide': response.writeHead(301, { Location: '/guide/' }).end() return @@ -331,7 +410,11 @@ beforeEach(() => { crawlDelay = '' lockedLink = false extraLinks = '' - homeCanonical = false + bareHome = false + signInWall = false + homeVisits = 0 + homeStallsAfterFirst = false + homeForbiddenOnce = false flakyFailures = 0 pageRequests.length = 0 sitemapRequests.length = 0 @@ -848,6 +931,190 @@ describe('website connector over real HTTP', () => { expect(first.documents.length).toBeLessThanOrEqual(53) }) + it('keeps stored pages when the whole site redirects to a sign-in wall', async () => { + signInWall = 'off-host' + await expect( + websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}/benefits`, {}) + ).rejects.toThrow('off its host') + expect(foreignRequests).toHaveLength(0) + }) + + it('keeps stored pages when the wall is an excluded sign-in page on the same host', async () => { + signInWall = 'on-host' + await expect( + websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + { ...config(), excludePaths: '/login' }, + `${site}/benefits`, + {} + ) + ).rejects.toThrow('outside the configured scope') + }) + + it('holds the site-wide redirect check to validation’s deadline', async () => { + bareHome = true + homeStallsAfterFirst = true + extraLinks = 'Moved' + const timeout = AbortSignal.timeout.bind(AbortSignal) + const spy = vi + .spyOn(AbortSignal, 'timeout') + // 20_000 is VALIDATE_DEADLINE_MS; every other deadline stays real. + .mockImplementation((ms) => timeout(ms === 20_000 ? 500 : ms)) + const started = Date.now() + try { + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { + ...config(), + discovery: 'links', + }) + ).toEqual({ valid: false, error: expect.stringContaining('did not answer') }) + } finally { + spy.mockRestore() + } + expect(Date.now() - started).toBeLessThan(5_000) + }) + + it('reads a canonical page named at the end of a short batch', async () => { + bareHome = true + extraLinks = ['/many-0', '/many-1', '/many-2', '/many-3', '/print-only'] + .map((href) => `Link`) + .join('') + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + expect(urls).toContain(`${site}/canon-target`) + }) + + it('resolves a chain of canonical pages to its last page, whatever order it is read in', async () => { + bareHome = true + extraLinks = 'BA' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + expect(urls.filter((url) => /link-/.test(url))).toEqual([`${site}/link-c`]) + }) + + it('never lists a page again in a later slice under a URL that redirects to it', async () => { + bareHome = true + extraLinks = [ + '/guide/', + ...Array.from({ length: 60 }, (_, index) => `/many-${index}`), + '/old-guide', + ] + .map((href) => `Link`) + .join('') + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + expect(urls.filter((url) => url.includes('/guide'))).toEqual([`${site}/guide/`]) + }) + + it('lists a page whose canonical URL redirects back to it', async () => { + bareHome = true + extraLinks = 'OldNew' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + expect(urls.filter((url) => /old|new/.test(url))).toEqual([`${site}/new-old`]) + }) + + it('reads a canonical page already queued deeper at the depth of the page naming it', async () => { + bareHome = true + extraLinks = 'QPrint' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2' }) + expect(urls).toContain(`${site}/deep-leaf`) + }) + + it('lists a page under its own URL when the cap leaves no room for its canonical page', async () => { + bareHome = true + extraLinks = 'Print' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1', maxPages: '2' }) + expect(urls).toEqual([`${site}/`, `${site}/print-only`]) + }) + + it('asks again whether the site redirects away after that check failed', async () => { + const context: Record = {} + const read = () => + websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}/moved`, context) + homeForbiddenOnce = true + await expect(read()).rejects.toThrow('status 403') + expect(await read()).toMatchObject({ skippedReason: 'The page redirects outside this source' }) + }) + + it('lists one page of a pair that name each other as canonical', async () => { + bareHome = true + extraLinks = 'Cycle' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + expect(urls.filter((url) => /cycle-/.test(url))).toHaveLength(1) + }) + + it('resumes a page whose path starts with two slashes on the site’s own host', async () => { + bareHome = true + extraLinks = [...Array.from({ length: 60 }, (_, index) => `/many-${index}`), `${site}//double`] + .map((href) => `Link`) + .join('') + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + expect(urls).toContain(`${site}//double`) + }) + + it('reads a page named as canonical on its own, so its listing and later reads agree', async () => { + extraLinks = 'Print' + const context: Record = {} + const listed = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links', maxDepth: '1' }, + undefined, + context + ) + const ids = listed.documents.filter((document) => !document.skippedReason) + expect(ids.map((document) => document.externalId)).not.toContain(`${site}/print-only`) + const canonical = ids.find((document) => document.externalId === `${site}/canon-target`) + expect(canonical?.content).toContain('Canonical text') + const read = await websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links' }, + `${site}/canon-target`, + {} + ) + expect(canonical?.contentHash).toBe(read?.contentHash) + }) + + it('lists pages past a slice’s text budget for the sync to read, under the same hash', async () => { + extraLinks = Array.from({ length: 50 }, (_, index) => `Big`).join( + '' + ) + const listed = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links', maxDepth: '1' }, + undefined, + {} + ) + const deferred = listed.documents.find((document) => document.contentDeferred) + expect(deferred).toMatchObject({ content: '' }) + const read = await websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links' }, + deferred?.externalId ?? '', + {} + ) + expect(read?.contentHash).toBe(deferred?.contentHash) + }) + + it('ends a crawl whose frontier outgrows its cursor as capped', async () => { + extraLinks = Array.from( + { length: 2900 }, + (_, index) => `Long` + ).join('') + const context: Record = {} + const first = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links', maxDepth: '1', maxPages: '5000' }, + undefined, + context + ) + expect(first.hasMore).toBe(false) + expect(context.listingCapped).toBe(true) + }) + + it('restarts the listing from an unreadable crawl cursor', async () => { + const error = await websiteConnector + .listDocuments(`X-Api-Key: ${KEY}`, { ...config(), discovery: 'links' }, 'crawl:{', {}) + .catch((caught: unknown) => caught) + expect(websiteConnector.isListingCursorInvalidError?.(error)).toBe(true) + }) + it('hands the sync a crawled page that opts out, so a copy indexed before is withdrawn', async () => { const listed = await websiteConnector.listDocuments( `X-Api-Key: ${KEY}`, @@ -863,11 +1130,12 @@ describe('website connector over real HTTP', () => { }) }) - it('counts a page listed under its canonical URL once against the page cap', async () => { - homeCanonical = true - const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1', maxPages: '2' }) - expect(urls).toContain(`${site}/home`) - expect(urls.filter((url) => url !== `${site}/home`)).toHaveLength(1) + it('counts a page listed under the URL it redirects to once against the page cap', async () => { + bareHome = true + extraLinks = 'Guide' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2', maxPages: '3' }) + expect(urls).toContain(`${site}/guide/`) + expect(urls).toContain(`${site}/guide/intro`) }) it('keeps reading the pages a capped crawl admitted, across slices', async () => { diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index eac16812764..347199c6c4b 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -36,6 +36,7 @@ import { } from '@/connectors/website/site' import { discoverSitemapPages, + pageKey, SitemapUnavailableError, scopedPage, type WebsiteDiscovery, @@ -48,6 +49,8 @@ const logger = createLogger('WebsiteConnector') /** Documents returned per `listDocuments` call. */ const DOCS_PER_PAGE = 50 +const PAGE_ACCEPT = 'text/html, application/xhtml+xml;q=0.9' + /** Bytes read from one page; a larger page is recorded as skipped rather than truncated. */ const PAGE_MAX_BYTES = 2 * 1024 * 1024 @@ -66,8 +69,11 @@ const CRAWL_SLICE_MS = 120_000 */ const CRAWL_SLICE_TEXT_BYTES = 16 * 1024 * 1024 -/** Longest crawl cursor; a longer frontier ends the crawl as capped. */ -const CRAWL_CURSOR_MAX_CHARS = 400 * 1024 +/** + * Longest crawl cursor, inside the 512 KiB a listing checkpoint keeps. A longer frontier ends the + * crawl as capped, like `maxPages`. + */ +const CRAWL_CURSOR_MAX_CHARS = 480 * 1024 const CRAWL_CURSOR_PREFIX = 'crawl:' @@ -77,6 +83,44 @@ interface WebsiteSession { headers: Record /** The pace robots.txt's Crawl-delay asks every request after robots.txt to keep. */ pace: SitePace + /** Cached probe; see {@link siteRedirectsAway}. */ + siteRedirectsAway?: Promise +} + +/** + * Whether the configured site URL itself now redirects out of the scope: a sign-in, maintenance + * or consent wall in front of the whole site rather than one moved page. Read at most once a sync, + * the first time a page redirects out of the scope. + */ +function siteRedirectsAway( + session: WebsiteSession, + retryOptions?: SecureFetchRetryOptions +): Promise { + const { scope } = session + session.siteRedirectsAway ??= fetchSiteResource( + { + url: scope.site.baseUrl, + site: scope.site, + headers: session.headers, + accept: PAGE_ACCEPT, + retryOptions, + pace: session.pace, + }, + PAGE_MAX_BYTES, + // Any path the site serves from counts, except one the configuration excludes, such as a + // sign-in page: a wall redirecting there still leaves every page out of scope. + (target) => scopedPage(target.toString(), { ...scope, include: [] }) !== null + ).then( + () => false, + (error) => { + if (error instanceof RedirectOutOfScopeError) return true + if (isPayloadSizeLimitError(error)) return false + // A probe that failed says nothing yet; the next redirect asks again. + session.siteRedirectsAway = undefined + throw error + } + ) + return session.siteRedirectsAway } type DiscoveryMode = 'auto' | 'sitemap' | 'links' @@ -252,10 +296,12 @@ type PageRead = CrawledPage * What a page itself says is permanent until the page changes, so it withdraws the page rather * than leaving the listing incomplete: a redirect out of the scope, a size or markup past what is * read, no text, or a request not to be indexed. A crawl does not reach pages linked only from - * such a page, as it does not reach pages past its depth. Only a page that could not be fetched - * (a network failure, a 5xx, a deadline) throws, which leaves a crawl incomplete. With `identify`, - * a crawl's page is listed under the URL a redirect finally served it from, or the in-scope - * `rel="canonical"` URL it names; a read by external ID keeps that ID. + * such a page, as it does not reach pages past its depth. A redirect out of the scope throws instead + * when the site URL redirects away too ({@link siteRedirectsAway}); otherwise only a fetch failure + * (network, 5xx, deadline) throws, leaving a crawl incomplete. With `identify`, a crawl's page is + * listed under the URL a redirect finally served it from, and a page naming another in-scope page + * as `rel="canonical"` hands the crawl that page instead of being listed; a read by external ID + * keeps that ID. */ async function readPage( session: WebsiteSession, @@ -281,7 +327,7 @@ async function readPage( url: page.url, site: scope.site, headers: session.headers, - accept: 'text/html, application/xhtml+xml;q=0.9', + accept: PAGE_ACCEPT, retryOptions, pace: session.pace, }, @@ -293,8 +339,10 @@ async function readPage( } ) } catch (error) { - if (error instanceof RedirectOutOfScopeError) + if (error instanceof RedirectOutOfScopeError) { + if (await siteRedirectsAway(session, retryOptions)) throw error return excluded('The page redirects outside this source') + } if (!isPayloadSizeLimitError(error)) throw error return excluded(sizeLimitSkipReason(PAGE_MAX_BYTES)) } @@ -319,11 +367,9 @@ async function readPage( // A page that opts out of indexing is not listed, but a crawl may still follow its links. if (noindex || header.noindex) return excluded('The page asks not to be indexed', { links, base }) if (!text.trim()) return excluded('The page has no text content', { links, base }) - const identity = identify - ? ((canonicalHref ? scopedPage(canonicalHref, scope, base) : null) ?? - scopedPage(finalUrl, scope) ?? - page) - : page + const identity = identify ? (scopedPage(finalUrl, scope) ?? page) : page + const canonical = identify && canonicalHref ? scopedPage(canonicalHref, scope, base) : null + const handOff = canonical && pageKey(canonical.url) !== pageKey(identity.url) const stub = pageToStub(identity) const document: ExternalDocument = { ...stub, @@ -334,7 +380,13 @@ async function readPage( ? stub.contentHash : `website:${identity.url}:${await computeContentHash(text)}`, } - return { value: document, listedAs: identity, links, base } + return { + value: document, + listedAs: identity, + links, + base, + ...(canonical && handOff ? { canonical } : {}), + } } class CrawlCursorError extends Error { @@ -348,6 +400,8 @@ const crawlCursorSchema = z.object({ level: z.array(z.string()), next: z.array(z.string()), seen: z.array(z.string()), + handedOff: z.record(z.string(), z.string()).default({}), + listedIds: z.array(z.string()).default([]), admitted: z.number().int().min(0), listed: z.number().int().min(0), capped: z.boolean(), diff --git a/apps/sim/lib/core/security/input-validation.server.ts b/apps/sim/lib/core/security/input-validation.server.ts index 691affd96da..28a1f8e9fd5 100644 --- a/apps/sim/lib/core/security/input-validation.server.ts +++ b/apps/sim/lib/core/security/input-validation.server.ts @@ -1276,7 +1276,9 @@ export async function secureFetchWithPinnedIP( settledReject(error) return } - Promise.resolve(options.beforeRedirect?.(redirectUrl)) + // Called inside the chain, so a hook that throws synchronously rejects the request. + Promise.resolve() + .then(() => options.beforeRedirect?.(redirectUrl)) .then(() => validateUrlWithDNS(redirectUrl, 'redirectUrl', options.profile, { logDetails: options.logUrlValidationDetails, diff --git a/apps/sim/lib/core/security/pinned-redirect-replay.server.test.ts b/apps/sim/lib/core/security/pinned-redirect-replay.server.test.ts index 2a2ae7697cb..89bfd0ba330 100644 --- a/apps/sim/lib/core/security/pinned-redirect-replay.server.test.ts +++ b/apps/sim/lib/core/security/pinned-redirect-replay.server.test.ts @@ -76,6 +76,22 @@ describe('secureFetchWithPinnedIP redirect replay', () => { expect(hops).toEqual([]) }) + it('rejects the request when a before-redirect hook throws synchronously', async () => { + const hops: RecordedHop[] = [] + const target = await startRecordingServer(hops) + const origin = await startRedirectServer(302, `${target}/after`) + + await expect( + secureFetchWithPinnedIP(origin, '127.0.0.1', { + profile: 'configuredEndpoint', + beforeRedirect: () => { + throw new Error('hop refused') + }, + }) + ).rejects.toThrow('hop refused') + expect(hops).toEqual([]) + }) + it('returns a 305 Use Proxy rather than following it', async () => { const hops: RecordedHop[] = [] const target = await startRecordingServer(hops)