From 978ea55af4b2b02340448e329aef8b4c4641a2da Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:54:52 -0800 Subject: [PATCH 1/4] feat(connectors): crawl a website by its links when it has no sitemap, keeping robots.txt Crawl-delay --- apps/sim/connectors/website/crawl.ts | 82 ++++++ apps/sim/connectors/website/meta.ts | 32 ++- apps/sim/connectors/website/page.ts | 15 +- apps/sim/connectors/website/robots.test.ts | 9 + apps/sim/connectors/website/robots.ts | 30 ++- apps/sim/connectors/website/sitemap.ts | 12 +- .../connectors/website/website.integration.ts | 112 +++++++- apps/sim/connectors/website/website.ts | 239 +++++++++++++----- 8 files changed, 450 insertions(+), 81 deletions(-) create mode 100644 apps/sim/connectors/website/crawl.ts diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts new file mode 100644 index 00000000000..3a0922ee6b0 --- /dev/null +++ b/apps/sim/connectors/website/crawl.ts @@ -0,0 +1,82 @@ +import { mapSettledWithConcurrency } from '@sim/utils/concurrency' +import { + scopedPage, + type WebsiteDiscovery, + type WebsitePage, + type WebsiteScope, +} from '@/connectors/website/sitemap' + +/** Pages read at once while crawling, bounding the load a sync puts on one site. */ +const CRAWL_CONCURRENCY = 4 + +/** + * What reading one page told the crawl: whether the page belongs in the listing (with the hash of + * its text, the listing's change indicator), and the links it offers. A page the site no longer + * serves, or that is not an HTML page, is not listed. + */ +export interface CrawledPage { + listed: boolean + contentHash?: string + links: string[] +} + +interface CrawlLimits { + maxPages: number + maxDepth: number + /** The instant a crawl stops queueing reads; what it found by then is a truncated listing. */ + deadline: number +} + +/** + * Discovers a site's pages by following links breadth-first from the configured URL: each + * in-scope page is read once, never deeper than `maxDepth` links from the start, and no more pages + * are queued than `maxPages`. A crawl cut by the page cap or its deadline is truncated, and one + * where a page could not be read is incomplete, so neither lets an unlisted page read as removed. + */ +export async function crawlSitePages( + scope: WebsiteScope, + read: (page: WebsitePage) => Promise, + limits: CrawlLimits +): Promise { + const start = scopedPage(scope.site.baseUrl, scope) ?? scopedPage(`${scope.site.baseUrl}/`, scope) + if (!start) + throw new Error('The website URL is outside the configured paths or disallowed by robots.txt') + const pages: WebsitePage[] = [] + const seen = new Set([start.url]) + let level = [start] + let truncated = false + let incomplete = false + for (let depth = 0; level.length; depth++) { + const next: WebsitePage[] = [] + for (let offset = 0; offset < level.length; offset += CRAWL_CONCURRENCY) { + if (Date.now() >= limits.deadline) { + truncated = true + return { pages, truncated, incomplete } + } + const batch = level.slice(offset, offset + CRAWL_CONCURRENCY) + const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, read) + for (const [index, result] of results.entries()) { + const page = batch[index] + if (!page) continue + if (result.status === 'rejected') { + incomplete = true + continue + } + if (result.value.listed) pages.push({ ...page, contentHash: result.value.contentHash }) + if (depth >= limits.maxDepth) continue + for (const link of result.value.links) { + const found = scopedPage(link, scope, page.url) + if (!found || seen.has(found.url)) continue + if (seen.size >= limits.maxPages) { + truncated = true + break + } + seen.add(found.url) + next.push(found) + } + } + } + level = next + } + return { pages, truncated, incomplete } +} diff --git a/apps/sim/connectors/website/meta.ts b/apps/sim/connectors/website/meta.ts index 614013f14f1..4749eb71afb 100644 --- a/apps/sim/connectors/website/meta.ts +++ b/apps/sim/connectors/website/meta.ts @@ -7,11 +7,17 @@ export const WEBSITE_DEFAULT_MAX_PAGES = 500 /** Hard ceiling on the configurable `maxPages` value. */ export const WEBSITE_MAX_PAGES_LIMIT = 5000 +/** Links followed from the website URL when crawling, unless `maxDepth` says otherwise. */ +export const WEBSITE_DEFAULT_MAX_DEPTH = 3 + +/** Hard ceiling on the configurable `maxDepth` value. */ +export const WEBSITE_MAX_DEPTH_LIMIT = 10 + /** Client-safe metadata for the website connector: its setup fields, auth and tags. */ export const websiteConnectorMeta: ConnectorMeta = { id: 'website', name: 'Website', - description: 'Sync the pages of a website from its sitemap', + description: 'Sync the pages of a website from its sitemap or by following its links', version: '1.0.0', icon: WebsiteIcon, @@ -36,7 +42,21 @@ export const websiteConnectorMeta: ConnectorMeta = { placeholder: 'https://www.example.com', required: true, description: - 'Pages are discovered from the sitemaps the site lists in robots.txt, or its sitemap.xml. Only pages on this host and under this path are synced, and robots.txt rules are honored.', + 'Only pages on this host and under this path are synced, and robots.txt rules (including Crawl-delay) are honored.', + }, + { + id: 'discovery', + title: 'Page Discovery', + type: 'dropdown', + required: false, + options: [ + { label: 'Sitemap, or follow links when there is none', id: 'auto' }, + { label: 'Sitemap only', id: 'sitemap' }, + { label: 'Follow links from the website URL', id: 'links' }, + ], + placeholder: 'Sitemap, or follow links when there is none', + description: + 'Sitemaps come from robots.txt or sitemap.xml. Following links starts at the website URL and reads each page once, up to the link depth.', }, { id: 'sitemapUrl', @@ -63,6 +83,14 @@ export const websiteConnectorMeta: ConnectorMeta = { required: false, description: 'Comma-separated path prefixes never to sync; * matches any characters.', }, + { + id: 'maxDepth', + title: 'Max Link Depth', + type: 'short-input', + placeholder: `e.g. 2 (default: ${WEBSITE_DEFAULT_MAX_DEPTH}, max: ${WEBSITE_MAX_DEPTH_LIMIT})`, + required: false, + description: 'How many links away from the website URL a crawl reads pages', + }, { id: 'maxPages', title: 'Max Pages', diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts index 60a4624fa99..67b43c42ee6 100644 --- a/apps/sim/connectors/website/page.ts +++ b/apps/sim/connectors/website/page.ts @@ -15,6 +15,11 @@ export interface WebsitePageText { title: string text: string /** The page asks not to be indexed (`noindex` or `none` in its robots meta tag). */ + /** + * The links a crawl may follow from the page, as written (relative or absolute): none when the + * page asks not to be followed, and never a link marked `rel="nofollow"`. + */ + links: string[] noindex: boolean } @@ -34,12 +39,20 @@ export function extractPageText(html: string): WebsitePageText { $('meta[property="og:title"]').attr('content')?.trim() || $('title').first().text().trim() || $('h1').first().text().trim() + // Read before page chrome is dropped: navigation is where most of a site's links live. + const links = /\b(nofollow|none)\b/i.test(directives) + ? [] + : $('a[href], area[href]') + .filter((_, element) => !/\bnofollow\b/i.test($(element).attr('rel') ?? '')) + .map((_, element) => $(element).attr('href') ?? '') + .get() + .filter(Boolean) $(CHROME_SELECTOR).remove() const region = ['main', 'article'].find((selector) => $(selector).length > 0) ?? 'body' const regionText = loadedHtmlToStructuredText($, region) // A client-rendered page leaves
/
empty; fall back to the body. const text = regionText || region === 'body' ? regionText : loadedHtmlToStructuredText($) - return { title, text, noindex: /\b(noindex|none)\b/i.test(directives) } + return { title, text, noindex: /\b(noindex|none)\b/i.test(directives), links } } const META_TAG = /]*>/gi diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts index 7614e81af46..1d599bebb40 100644 --- a/apps/sim/connectors/website/robots.test.ts +++ b/apps/sim/connectors/website/robots.test.ts @@ -77,4 +77,13 @@ describe('robots.txt rules for the website connector', () => { const rules = Array.from({ length: 1001 }, (_, index) => `Disallow: /p${index}`) expect(() => parseRobots(['User-agent: *', ...rules].join('\n'))).toThrow('more than') }) + + it('takes the Crawl-delay of the applied group, capped so a site cannot stall a sync', () => { + expect(parseRobots('User-agent: *\nCrawl-delay: 1.5\nDisallow: /x').crawlDelayMs).toBe(1500) + expect(parseRobots('User-agent: *\nCrawl-delay: 3600').crawlDelayMs).toBe(10_000) + expect( + parseRobots('User-agent: *\nCrawl-delay: 5\n\nUser-agent: SimBot\nDisallow: /x').crawlDelayMs + ).toBe(0) + expect(parseRobots('User-agent: *\nCrawl-delay: soon').crawlDelayMs).toBe(0) + }) }) diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts index ef1ac461f7c..eb691c50f30 100644 --- a/apps/sim/connectors/website/robots.ts +++ b/apps/sim/connectors/website/robots.ts @@ -11,8 +11,20 @@ interface RobotsRule { export interface RobotsPolicy { allows(path: string): boolean sitemaps: string[] + /** The pause the site asks for between requests, in milliseconds, capped; 0 when none. */ + crawlDelayMs: number } +/** One `User-agent` group: the crawlers it names, its rules, and its Crawl-delay in seconds. */ +interface RobotsGroup { + agents: string[] + rules: RobotsRule[] + delaySeconds?: number +} + +/** The longest pause between requests a site's Crawl-delay may impose. */ +const MAX_CRAWL_DELAY_MS = 10_000 + /** * A URL path in one canonical form, so `/%70rivate` and `/private`, or `/café` and `/caf%C3%A9`, * compare equal: escapes of unreserved characters are decoded, other escapes uppercased, and @@ -70,9 +82,9 @@ const MAX_ROBOTS_RULES = 1000 * groups when none does. The longest matching rule decides, and Allow wins a tie. */ export function parseRobots(body: string): RobotsPolicy { - const groups: { agents: string[]; rules: RobotsRule[] }[] = [] + const groups: RobotsGroup[] = [] const sitemaps: string[] = [] - let current: { agents: string[]; rules: RobotsRule[] } | undefined + let current: RobotsGroup | undefined let readingAgents = false for (const raw of body.split(/\r\n|\r|\n/)) { const line = raw.replace(/#.*$/, '').trim() @@ -95,6 +107,11 @@ export function parseRobots(body: string): RobotsPolicy { continue } readingAgents = false + if (current && field === 'crawl-delay') { + const seconds = Number(value) + if (Number.isFinite(seconds) && seconds > 0) current.delaySeconds = seconds + continue + } if (!current || (field !== 'allow' && field !== 'disallow')) continue if (!value) continue current.rules.push({ @@ -106,15 +123,16 @@ export function parseRobots(body: string): RobotsPolicy { } const token = WEBSITE_CRAWLER_TOKEN.toLowerCase() const named = groups.filter((group) => group.agents.includes(token)) - const rules = ( - named.length ? named : groups.filter((group) => group.agents.includes('*')) - ).flatMap((group) => group.rules) + const applied = named.length ? named : groups.filter((group) => group.agents.includes('*')) + const rules = applied.flatMap((group) => group.rules) + const delaySeconds = Math.max(0, ...applied.map((group) => group.delaySeconds ?? 0)) if (rules.length > MAX_ROBOTS_RULES) throw new Error( `robots.txt applies ${rules.length} rules to this crawler, more than the ${MAX_ROBOTS_RULES} it evaluates` ) return { sitemaps, + crawlDelayMs: Math.min(Math.round(delaySeconds * 1000), MAX_CRAWL_DELAY_MS), allows(rawPath) { const path = normalizePath(rawPath) let decision: RobotsRule | undefined @@ -133,4 +151,4 @@ export function parseRobots(body: string): RobotsPolicy { } /** A site without robots.txt allows everything and declares no sitemaps. */ -export const ALLOW_ALL_ROBOTS: RobotsPolicy = { sitemaps: [], allows: () => true } +export const ALLOW_ALL_ROBOTS: RobotsPolicy = { sitemaps: [], crawlDelayMs: 0, allows: () => true } diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts index 7580b4bc8dc..f8fc715c2ff 100644 --- a/apps/sim/connectors/website/sitemap.ts +++ b/apps/sim/connectors/website/sitemap.ts @@ -47,6 +47,8 @@ export interface WebsitePage { path: string /** The sitemap's ``, as an ISO timestamp, when it gives a valid one. */ lastModified?: string + /** The hash of the text a crawl read from the page, its change indicator when it has no date. */ + contentHash?: string } /** The pages one discovery found, and why they may not be all the site has. */ @@ -166,9 +168,13 @@ function readSitemapEntries( return closed && !implied && isSitemap() ? 'complete' : 'invalid' } -/** The page a sitemap location names, when it is a page within the configured scope. */ -export function scopedPage(location: string, scope: WebsiteScope): WebsitePage | null { - const url = siteUrl(location, `${scope.site.origin}/`, scope.site) +/** The page a location names, resolved against `base`, when it is a page within the scope. */ +export function scopedPage( + location: string, + scope: WebsiteScope, + base = `${scope.site.origin}/` +): WebsitePage | null { + const url = siteUrl(location, base, scope.site) if (!url) return null url.hash = '' const path = normalizePath(url.pathname).replace(/\/+$/, '') || '/' diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index f798c255207..e5539b0bc77 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -29,6 +29,9 @@ let robotsToWww = false let hung: ServerResponse[] = [] let wwwRequests: IncomingMessage[] = [] let undeclared: 'html' | 'text' | undefined +let crawlDelay = '' +let lockedLink = false +const pageRequests: { path: string; at: number }[] = [] let faqBody = '

Original answer.

' /** More `` entries than one sitemap may list, all disallowed, between two listed pages. */ @@ -55,7 +58,22 @@ const siteServer = createServer((request, response) => { if (request.headers.host?.startsWith('www.')) wwwRequests.push(request) const path = new URL(request.url ?? '/', site).pathname if (/^\/child-\d+\.xml$/.test(path)) return send(200, 'application/xml', '') + if (!/\.(xml|gz|txt)$/.test(path)) pageRequests.push({ path, at: Date.now() }) switch (path) { + case '/': + return send( + 200, + 'text/html', + `Home

Welcome.

HiddenPlans${lockedLink ? 'Locked' : ''}
` + ) + case '/locked': + return send(403, 'text/plain', 'forbidden') + case '/secret': + return send(200, 'text/html', page('Secret', '

Not followed

')) + case '/deep': + return send(200, 'text/html', page('Deep', '

Two links away

More')) + case '/deeper': + return send(200, 'text/html', page('Deeper', '

Too far

')) case '/robots.txt': if (robotsHang) { hung.push(response) @@ -86,7 +104,7 @@ const siteServer = createServer((request, response) => { robotsOversized ? // Lines end in a bare CR, which robots.txt allows, so the cut must find one. `User-agent: *\rDisallow: /private\rSitemap: ${site}/sitemap-index.xml\r${'#'.repeat(600 * 1024)}\rDisallow: /benefits\r` - : `User-agent: *\nDisallow: /private\n${undeclared ? '' : `Sitemap: ${site}/sitemap-index.xml\n`}${staleDeclared ? `Sitemap: ${site}/stale.xml\n` : ''}` + : `User-agent: *\nDisallow: /private\n${crawlDelay ? `Crawl-delay: ${crawlDelay}\n` : ''}${undeclared ? '' : `Sitemap: ${site}/sitemap-index.xml\n`}${staleDeclared ? `Sitemap: ${site}/stale.xml\n` : ''}` ) case '/sitemap.xml': if (undeclared === 'html') return send(200, 'text/html', page('Not found', '

Nothing

')) @@ -174,7 +192,11 @@ const siteServer = createServer((request, response) => { return send( 200, 'text/html', - page('Hidden', '

Draft

', '') + page( + 'Hidden', + '

Draft

Deep', + '' + ) ) case '/dense': return send(200, 'text/html', page('Dense', `

${'<'.repeat(1_000_001)}

`)) @@ -233,6 +255,9 @@ beforeEach(() => { hung = [] undeclared = undefined faqBody = '

Original answer.

' + crawlDelay = '' + lockedLink = false + pageRequests.length = 0 }) /** `www.localhost` stands in for a site's www host; it resolves where `localhost` does. */ @@ -535,7 +560,7 @@ describe('website connector over real HTTP', () => { it('skips a guessed sitemap location the site answers with a page, but not one that is invalid', async () => { undeclared = 'html' - await expect(listAll(config())).rejects.toThrow('No pages found') + await expect(listAll({ ...config(), discovery: 'sitemap' })).rejects.toThrow('No pages found') undeclared = 'text' await expect(listAll(config())).rejects.toThrow('not a valid sitemap') }) @@ -549,4 +574,85 @@ describe('website connector over real HTTP', () => { await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { ...config(), maxPages: '0.5' }) ).toMatchObject({ valid: false }) }) + + it('crawls links breadth-first within scope, robots.txt, nofollow and depth, reading each page once', async () => { + const context: Record = {} + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2' }, context) + expect([...urls].sort()).toEqual([ + `${site}/`, + `${site}/benefits`, + `${site}/deep`, + `${site}/faq`, + ]) + expect(foreignRequests).toHaveLength(0) + const paths = pageRequests.map((request) => request.path) + expect(paths).not.toContain('/secret') + expect(paths).not.toContain('/deeper') + expect(paths.filter((path) => path === '/benefits')).toHaveLength(1) + expect(paths).toContain('/hidden') + expect(context.listingCapped).toBeUndefined() + expect(context.reconciliationUnsafe).toBeUndefined() + }) + + it('lists crawled pages under the hash of their text, so unchanged pages are not read again', async () => { + const context: Record = {} + const listed = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links', maxDepth: '1' }, + undefined, + context + ) + const stub = listed.documents.find((document) => document.externalId === `${site}/faq`) + const document = await websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + { ...config(), discovery: 'links' }, + `${site}/faq`, + context + ) + expect(stub?.contentHash).toBe(document?.contentHash) + }) + + it('falls back to following links when the site has no sitemap', async () => { + undeclared = 'html' + const urls = await listAll({ ...config(), maxDepth: '1' }) + expect(urls).toContain(`${site}/benefits`) + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { + ...config(), + discovery: 'links', + }) + ).toEqual({ valid: true }) + }) + + it('marks a crawl cut by the page cap so absent pages are not reconciled away', async () => { + const context: Record = {} + expect(await listAll({ ...config(), discovery: 'links', maxPages: '2' }, context)).toHaveLength( + 2 + ) + expect(context.listingCapped).toBe(true) + }) + + it('keeps the pace robots.txt asks for between page requests', async () => { + crawlDelay = '0.2' + await listAll({ ...config(), discovery: 'links', maxDepth: '1' }) + const times = pageRequests.map((request) => request.at) + expect(times.length).toBeGreaterThanOrEqual(4) + for (let index = 1; index < times.length; index++) + expect((times[index] ?? 0) - (times[index - 1] ?? 0)).toBeGreaterThanOrEqual(150) + }) + + it('fails a crawl whose starting page cannot be read rather than listing an empty site', async () => { + await expect(listAll({ siteUrl: `${site}/gone`, discovery: 'links' })).rejects.toThrow( + 'No pages found' + ) + }) + + it('never lets a crawl that could not read a page reconcile pages away', async () => { + lockedLink = true + const context: Record = {} + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '1' }, context) + expect(urls).toContain(`${site}/benefits`) + expect(urls).not.toContain(`${site}/locked`) + expect(context.reconciliationUnsafe).toBe(true) + }) }) diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index de9c8d5ed3e..07e22ea3f1d 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' +import { sleep } from '@sim/utils/helpers' import { compareStrings } from '@sim/utils/string' import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' import { isHtmlComplexityError } from '@/lib/file-parsers/html-parser' @@ -12,8 +13,11 @@ import { parseTagDate, sizeLimitSkipReason, } from '@/connectors/utils' +import { type CrawledPage, crawlSitePages } from '@/connectors/website/crawl' import { + WEBSITE_DEFAULT_MAX_DEPTH, WEBSITE_DEFAULT_MAX_PAGES, + WEBSITE_MAX_DEPTH_LIMIT, WEBSITE_MAX_PAGES_LIMIT, websiteConnectorMeta, } from '@/connectors/website/meta' @@ -46,10 +50,38 @@ const PAGE_MAX_BYTES = 2 * 1024 * 1024 /** Whole-validation deadline: validation runs inside a request, which a slow site must not hold. */ const VALIDATE_DEADLINE_MS = 20_000 -/** What one sync reads once and every page read reuses: the scope and its request headers. */ +/** Wall-clock one crawl may spend discovering pages; what it found by then still syncs. */ +const CRAWL_DEADLINE_MS = 120_000 + +/** + * What one sync reads once and every page read reuses: the scope, its request headers, and the + * pace robots.txt asks page requests to keep. + */ interface WebsiteSession { scope: WebsiteScope headers: Record + pace: () => Promise +} + +/** + * Spaces calls at least `delayMs` apart, in the order they ask, however many run at once: the + * Crawl-delay a site requests, applied to every page request of the sync. + */ +function pacer(delayMs: number): () => Promise { + let nextSlot = 0 + return async () => { + if (!delayMs) return + const now = Date.now() + const slot = Math.max(now, nextSlot) + nextSlot = slot + delayMs + if (slot > now) await sleep(slot - now) + } +} + +type DiscoveryMode = 'auto' | 'sitemap' | 'links' + +function discoveryMode(value: unknown): DiscoveryMode { + return value === 'sitemap' || value === 'links' ? value : 'auto' } interface WebsiteListing { @@ -72,6 +104,15 @@ function resolveMaxPages(value: unknown): number { return Math.min(parseMaxPages(value) ?? WEBSITE_DEFAULT_MAX_PAGES, WEBSITE_MAX_PAGES_LIMIT) } +/** How many links from the website URL a crawl reads; `null` when the setting is invalid. */ +function parseMaxDepth(value: unknown): number | null { + if (value === undefined || value === null || value === '') return WEBSITE_DEFAULT_MAX_DEPTH + const parsed = Number(value) + return Number.isSafeInteger(parsed) && parsed > 0 + ? Math.min(parsed, WEBSITE_MAX_DEPTH_LIMIT) + : null +} + /** * A listed page this read deliberately leaves out: recorded as skipped and replacing whatever was * indexed before, so a page that disappears or opts out of indexing stops being searchable. @@ -96,11 +137,13 @@ async function openSession( const site = resolveSite(sourceConfig.siteUrl) const headers = parseRequestHeader(accessToken ?? '') const robots = await fetchRobotsText({ site, headers, retryOptions }) + const policy = robots === null ? ALLOW_ALL_ROBOTS : parseRobots(robots) const session: WebsiteSession = { headers, + pace: pacer(policy.crawlDelayMs), scope: { site, - robots: robots === null ? ALLOW_ALL_ROBOTS : parseRobots(robots), + robots: policy, include: pathPatterns(sourceConfig.includePaths), exclude: pathPatterns(sourceConfig.excludePaths), }, @@ -134,7 +177,9 @@ function pageToStub(page: WebsitePage): ExternalDocument { sourceUrl: page.url, contentHash: page.lastModified ? `website:${page.url}:${page.lastModified}` - : `website:${page.url}`, + : page.contentHash + ? `website:${page.url}:${page.contentHash}` + : `website:${page.url}`, metadata: { section: page.path.split('/').filter(Boolean)[0], lastModified: page.lastModified, @@ -182,7 +227,84 @@ function listingPage(listing: WebsiteListing, cursor?: string): ExternalDocument } } -/** Discovers website pages from sitemaps and reads their text within the configured scope. */ +interface PageRead extends CrawledPage { + document: ExternalDocument +} + +/** + * Reads one page: its document (with text, or recorded as withdrawn or skipped), whether it + * belongs in a crawl's listing, and the links a crawl may follow from it. A redirect may not leave + * the scope, and requests keep the pace the site's robots.txt asks for. + */ +async function readPage(session: WebsiteSession, page: WebsitePage): Promise { + const { scope, headers } = session + const unlisted = (document: ExternalDocument): PageRead => ({ + document, + listed: false, + links: [], + }) + let resource: Awaited> + await session.pace() + try { + resource = await fetchSiteResource( + { + url: page.url, + site: scope.site, + headers, + accept: 'text/html, application/xhtml+xml;q=0.9', + }, + PAGE_MAX_BYTES, + (target) => scopedPage(target.toString(), scope) !== null + ) + } catch (error) { + if (!isPayloadSizeLimitError(error)) throw error + return unlisted(markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES))) + } + if (!resource) return unlisted(withdrawn(page, 'The page no longer exists on the site')) + const contentType = resource.headers.get('content-type') ?? '' + if (!/html/i.test(contentType)) + return unlisted(withdrawn(page, 'The URL serves a file, not an HTML page')) + const headerNoindex = robotsHeaderNoindex(resource.headers.get('x-robots-tag')) + let extracted: ReturnType + try { + extracted = extractPageText(decodePage(resource.body, contentType)) + } catch (error) { + // Markup past the parser's limits, or nesting deep enough to exhaust the walk's stack. + if (!isHtmlComplexityError(error) && !(error instanceof RangeError)) throw error + return unlisted(withdrawn(page, 'The page is too complex to read')) + } + const { title, text, noindex, links } = extracted + // A page that opts out of indexing is not listed, but a crawl may still follow its links. + if (noindex || headerNoindex) + return { document: withdrawn(page, 'The page asks not to be indexed'), listed: false, links } + if (!text.trim()) + return { document: withdrawn(page, 'The page has no text content'), listed: false, links } + const contentHash = await computeContentHash(text) + const stub = pageToStub(page) + return { + listed: true, + contentHash, + links, + document: { + ...stub, + title: title || stub.title, + content: text, + contentDeferred: false, + contentHash: page.lastModified ? stub.contentHash : `website:${page.url}:${contentHash}`, + }, + } +} + +/** Discovers a site's pages by following its links, each page read once and in scope. */ +function crawlDiscovery(session: WebsiteSession, sourceConfig: Record) { + return crawlSitePages(session.scope, (page) => readPage(session, page), { + maxPages: resolveMaxPages(sourceConfig.maxPages), + maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, + deadline: Date.now() + CRAWL_DEADLINE_MS, + }) +} + +/** Discovers website pages and reads their text within the configured scope. */ export const websiteConnector: ConnectorConfig = { ...websiteConnectorMeta, @@ -194,14 +316,25 @@ export const websiteConnector: ConnectorConfig = { ): Promise => { let listing = syncContext?.[LISTING_KEY] as WebsiteListing | undefined if (!listing) { - const { scope, headers } = await openSession(accessToken, sourceConfig, syncContext) - const discovery = await discoverSitemapPages(scope, headers, { - configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), - limit: resolveMaxPages(sourceConfig.maxPages), - }) + const session = await openSession(accessToken, sourceConfig, syncContext) + const { scope, headers } = session + const mode = discoveryMode(sourceConfig.discovery) + let discovery = + mode === 'links' + ? await crawlDiscovery(session, sourceConfig) + : await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: resolveMaxPages(sourceConfig.maxPages), + }) + if (mode === 'auto' && discovery.pages.length === 0 && !discovery.incomplete) + discovery = await crawlDiscovery(session, sourceConfig) // An empty listing would reconcile every stored page away, so fail instead. if (discovery.pages.length === 0) - throw new Error('No pages found in the site’s sitemaps within the configured scope') + throw new Error( + mode === 'sitemap' + ? 'No pages found in the site’s sitemaps within the configured scope' + : 'No pages found in the site’s sitemaps or by following its links within the configured scope' + ) listing = holdListing(discovery, syncContext) } return listingPage(listing, cursor) @@ -213,54 +346,12 @@ export const websiteConnector: ConnectorConfig = { externalId: string, syncContext?: Record ): Promise => { - const { scope, headers } = await openSession(accessToken, sourceConfig, syncContext) + const session = await openSession(accessToken, sourceConfig, syncContext) const listed = (syncContext?.[LISTING_KEY] as WebsiteListing | undefined)?.byUrl.get(externalId) // A page this sync did not list must still pass the current scope before it is read. - const page = listed ?? scopedPage(externalId, scope) + const page = listed ?? scopedPage(externalId, session.scope) if (!page) return null - let resource: Awaited> - try { - resource = await fetchSiteResource( - { - url: page.url, - site: scope.site, - headers, - accept: 'text/html, application/xhtml+xml;q=0.9', - }, - PAGE_MAX_BYTES, - (target) => scopedPage(target.toString(), scope) !== null - ) - } catch (error) { - if (!isPayloadSizeLimitError(error)) throw error - return markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES)) - } - if (!resource) return withdrawn(page, 'The page no longer exists on the site') - const contentType = resource.headers.get('content-type') ?? '' - if (!/html/i.test(contentType)) - return withdrawn(page, 'The URL serves a file, not an HTML page') - if (robotsHeaderNoindex(resource.headers.get('x-robots-tag'))) - return withdrawn(page, 'The page asks not to be indexed') - let extracted: ReturnType - try { - extracted = extractPageText(decodePage(resource.body, contentType)) - } catch (error) { - // Markup past the parser's limits, or nesting deep enough to exhaust the walk's stack. - if (!isHtmlComplexityError(error) && !(error instanceof RangeError)) throw error - return withdrawn(page, 'The page is too complex to read') - } - const { title, text, noindex } = extracted - if (noindex) return withdrawn(page, 'The page asks not to be indexed') - if (!text.trim()) return withdrawn(page, 'The page has no text content') - const stub = pageToStub(page) - return { - ...stub, - title: title || stub.title, - content: text, - contentDeferred: false, - contentHash: page.lastModified - ? stub.contentHash - : `website:${page.url}:${await computeContentHash(text)}`, - } + return (await readPage(session, page)).document }, validateConfig: async ( @@ -269,22 +360,38 @@ export const websiteConnector: ConnectorConfig = { ): Promise<{ valid: boolean; error?: string }> => { if (parseMaxPages(sourceConfig.maxPages) === null) return { valid: false, error: 'Max Pages must be a positive whole number' } + if (parseMaxDepth(sourceConfig.maxDepth) === null) + return { valid: false, error: 'Max Link Depth must be a positive whole number' } const retryOptions = { ...VALIDATE_RETRY_OPTIONS, signal: AbortSignal.timeout(VALIDATE_DEADLINE_MS), } try { - const { scope, headers } = await openSession( - accessToken, - sourceConfig, - undefined, - retryOptions - ) - const { pages } = await discoverSitemapPages(scope, headers, { - configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), - limit: 1, - retryOptions, - }) + const session = await openSession(accessToken, sourceConfig, undefined, retryOptions) + const { scope, headers } = session + const mode = discoveryMode(sourceConfig.discovery) + const { pages } = + mode === 'links' + ? { pages: [] } + : await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: 1, + retryOptions, + }) + if (pages.length === 0 && mode !== 'sitemap') { + // The crawl reads its first page the way a sync does, and needs text or links to go on. + const crawl = await crawlSitePages(scope, (page) => readPage(session, page), { + maxPages: 2, + maxDepth: 1, + deadline: Date.now() + VALIDATE_DEADLINE_MS, + }) + return crawl.pages.length + ? { valid: true } + : { + valid: false, + error: `${scope.site.baseUrl} has no sitemap, and its page offers no text or links to follow within the configured paths`, + } + } if (pages.length === 0) return { valid: false, From 07ee6f71038e91e42988395f2decdb9fd9adae8c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:57:53 -0800 Subject: [PATCH 2/4] fix(connectors): resolve crawled links where the page was served, and never reconcile through an unread page --- apps/sim/connectors/website/crawl.ts | 13 +++++- apps/sim/connectors/website/page.ts | 13 +++++- .../connectors/website/website.integration.ts | 45 ++++++++++++++++++- apps/sim/connectors/website/website.ts | 31 ++++++++++--- 4 files changed, 91 insertions(+), 11 deletions(-) diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts index 3a0922ee6b0..f57caa3b1fa 100644 --- a/apps/sim/connectors/website/crawl.ts +++ b/apps/sim/connectors/website/crawl.ts @@ -18,6 +18,10 @@ export interface CrawledPage { listed: boolean contentHash?: string links: string[] + /** Where the page's relative links resolve: its final URL after redirects, or its ``. */ + base?: string + /** The page exists but could not be read, so the links it holds are unknown. */ + unreadable?: boolean } interface CrawlLimits { @@ -38,6 +42,7 @@ export async function crawlSitePages( read: (page: WebsitePage) => Promise, limits: CrawlLimits ): Promise { + // Relative links resolve against the URL a page is finally served at, as a browser's would. const start = scopedPage(scope.site.baseUrl, scope) ?? scopedPage(`${scope.site.baseUrl}/`, scope) if (!start) throw new Error('The website URL is outside the configured paths or disallowed by robots.txt') @@ -58,14 +63,15 @@ export async function crawlSitePages( for (const [index, result] of results.entries()) { const page = batch[index] if (!page) continue - if (result.status === 'rejected') { + if (result.status === 'rejected' || result.value.unreadable) { incomplete = true continue } if (result.value.listed) pages.push({ ...page, contentHash: result.value.contentHash }) if (depth >= limits.maxDepth) continue + const before = seen.size for (const link of result.value.links) { - const found = scopedPage(link, scope, page.url) + const found = scopedPage(link, scope, result.value.base ?? page.url) if (!found || seen.has(found.url)) continue if (seen.size >= limits.maxPages) { truncated = true @@ -74,6 +80,9 @@ export async function crawlSitePages( seen.add(found.url) next.push(found) } + // A start page that leads nowhere is more likely unread (a client-rendered site) than a + // site of one page, so it does not prove the site's other pages are gone. + if (depth === 0 && seen.size === before && !truncated) incomplete = true } } level = next diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts index 67b43c42ee6..0bf395515b2 100644 --- a/apps/sim/connectors/website/page.ts +++ b/apps/sim/connectors/website/page.ts @@ -15,12 +15,14 @@ export interface WebsitePageText { title: string text: string /** The page asks not to be indexed (`noindex` or `none` in its robots meta tag). */ + noindex: boolean /** * The links a crawl may follow from the page, as written (relative or absolute): none when the * page asks not to be followed, and never a link marked `rel="nofollow"`. */ links: string[] - noindex: boolean + /** The page's first ``, as written, which relative links resolve against. */ + baseHref?: string } /** @@ -52,7 +54,14 @@ export function extractPageText(html: string): WebsitePageText { const regionText = loadedHtmlToStructuredText($, region) // A client-rendered page leaves
/
empty; fall back to the body. const text = regionText || region === 'body' ? regionText : loadedHtmlToStructuredText($) - return { title, text, noindex: /\b(noindex|none)\b/i.test(directives), links } + const baseHref = $('base[href]').first().attr('href')?.trim() + return { + title, + text, + noindex: /\b(noindex|none)\b/i.test(directives), + links, + ...(baseHref ? { baseHref } : {}), + } } const META_TAG = /]*>/gi diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index e5539b0bc77..bfc7abb658b 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -31,6 +31,7 @@ let wwwRequests: IncomingMessage[] = [] let undeclared: 'html' | 'text' | undefined let crawlDelay = '' let lockedLink = false +let extraLinks = '' const pageRequests: { path: string; at: number }[] = [] let faqBody = '

Original answer.

' @@ -64,8 +65,23 @@ const siteServer = createServer((request, response) => { return send( 200, 'text/html', - `Home

Welcome.

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

Welcome.

HiddenPlans${lockedLink ? 'Locked' : ''}${extraLinks}
` ) + case '/guide': + response.writeHead(301, { Location: '/guide/' }).end() + return + case '/guide/': + return send(200, 'text/html', page('Guide', '

Guide home

Intro')) + case '/guide/intro': + return send(200, 'text/html', page('Intro', '

Start here

')) + case '/based': + return send( + 200, + 'text/html', + page('Based', '

Docs index

Setup', '') + ) + case '/docs/setup': + return send(200, 'text/html', page('Setup', '

Install steps

')) case '/locked': return send(403, 'text/plain', 'forbidden') case '/secret': @@ -257,6 +273,7 @@ beforeEach(() => { faqBody = '

Original answer.

' crawlDelay = '' lockedLink = false + extraLinks = '' pageRequests.length = 0 }) @@ -655,4 +672,30 @@ describe('website connector over real HTTP', () => { expect(urls).not.toContain(`${site}/locked`) expect(context.reconciliationUnsafe).toBe(true) }) + + it('resolves a page’s relative links against its ', async () => { + extraLinks = 'Docs' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2' }) + expect(urls).toContain(`${site}/docs/setup`) + }) + + it('never lets a page it could not parse hide the pages it links to', async () => { + extraLinks = 'Dense' + const context: Record = {} + await listAll({ ...config(), discovery: 'links', maxDepth: '1' }, context) + expect(context.reconciliationUnsafe).toBe(true) + }) + + it('does not take a start page that links nowhere as proof the rest of the site is gone', async () => { + const context: Record = {} + expect(await listAll({ siteUrl: `${site}/secret`, discovery: 'links' }, context)).toEqual([ + `${site}/secret`, + ]) + expect(context.reconciliationUnsafe).toBe(true) + }) + + it('resolves relative links against the URL a redirect served the page from', async () => { + const urls = await listAll({ siteUrl: `${site}/guide`, discovery: 'links' }) + expect(urls).toContain(`${site}/guide/intro`) + }) }) diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index 07e22ea3f1d..52c4d4e67a8 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -243,7 +243,12 @@ async function readPage(session: WebsiteSession, page: WebsitePage): Promise ({ + ...unlisted(document), + unreadable: true, + }) let resource: Awaited> + let finalUrl = page.url await session.pace() try { resource = await fetchSiteResource( @@ -254,11 +259,15 @@ async function readPage(session: WebsiteSession, page: WebsitePage): Promise scopedPage(target.toString(), scope) !== null + (target) => { + if (scopedPage(target.toString(), scope) === null) return false + finalUrl = target.toString() + return true + } ) } catch (error) { if (!isPayloadSizeLimitError(error)) throw error - return unlisted(markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES))) + return unreadable(markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES))) } if (!resource) return unlisted(withdrawn(page, 'The page no longer exists on the site')) const contentType = resource.headers.get('content-type') ?? '' @@ -271,20 +280,30 @@ async function readPage(session: WebsiteSession, page: WebsitePage): Promise Date: Tue, 1 Dec 2026 01:13:59 -0800 Subject: [PATCH 3/4] fix(connectors): bound link crawls by their deadline and honor nofollow in X-Robots-Tag Page reads and Crawl-delay waits take the crawl's signal, so a stalled page cannot hold a sync or validation past its deadline. X-Robots-Tag nofollow/none stops link following, robots directives are parsed as tokens so valued directives such as max-image-preview:none are not read as none, and a start URL outside the include paths is read for its links without being listed. --- apps/sim/connectors/website/crawl.ts | 33 +++++++----- apps/sim/connectors/website/page.test.ts | 24 +++++++-- apps/sim/connectors/website/page.ts | 54 ++++++++++++------- .../connectors/website/website.integration.ts | 52 ++++++++++++++++++ apps/sim/connectors/website/website.ts | 52 ++++++++++++------ 5 files changed, 164 insertions(+), 51 deletions(-) diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts index f57caa3b1fa..22ed117203f 100644 --- a/apps/sim/connectors/website/crawl.ts +++ b/apps/sim/connectors/website/crawl.ts @@ -27,25 +27,34 @@ export interface CrawledPage { interface CrawlLimits { maxPages: number maxDepth: number - /** The instant a crawl stops queueing reads; what it found by then is a truncated listing. */ - deadline: number + /** + * Ends the crawl: reads in flight are cancelled and none start after it, and what the crawl found + * by then is a truncated listing. + */ + signal: AbortSignal } /** * Discovers a site's pages by following links breadth-first from the configured URL: each * in-scope page is read once, never deeper than `maxDepth` links from the start, and no more pages - * are queued than `maxPages`. A crawl cut by the page cap or its deadline is truncated, and one + * are queued than `maxPages`. A crawl cut by the page cap or its signal is truncated, and one * where a page could not be read is incomplete, so neither lets an unlisted page read as removed. + * A configured URL outside the include paths is still read for its links, but not listed. */ export async function crawlSitePages( scope: WebsiteScope, - read: (page: WebsitePage) => Promise, + read: (page: WebsitePage, signal: AbortSignal) => Promise, limits: CrawlLimits ): Promise { // Relative links resolve against the URL a page is finally served at, as a browser's would. - const start = scopedPage(scope.site.baseUrl, scope) ?? scopedPage(`${scope.site.baseUrl}/`, scope) + const seed = (within: WebsiteScope) => + scopedPage(scope.site.baseUrl, within) ?? scopedPage(`${scope.site.baseUrl}/`, within) + const listedStart = seed(scope) + const start = listedStart ?? seed({ ...scope, include: [] }) if (!start) - throw new Error('The website URL is outside the configured paths or disallowed by robots.txt') + throw new Error( + 'The website URL is excluded by the configured paths or disallowed by robots.txt' + ) const pages: WebsitePage[] = [] const seen = new Set([start.url]) let level = [start] @@ -54,12 +63,11 @@ export async function crawlSitePages( for (let depth = 0; level.length; depth++) { const next: WebsitePage[] = [] for (let offset = 0; offset < level.length; offset += CRAWL_CONCURRENCY) { - if (Date.now() >= limits.deadline) { - truncated = true - return { pages, truncated, incomplete } - } + if (limits.signal.aborted) return { pages, truncated: true, incomplete } const batch = level.slice(offset, offset + CRAWL_CONCURRENCY) - const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, read) + const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, (page) => + read(page, limits.signal) + ) for (const [index, result] of results.entries()) { const page = batch[index] if (!page) continue @@ -67,7 +75,8 @@ export async function crawlSitePages( incomplete = true continue } - if (result.value.listed) pages.push({ ...page, contentHash: result.value.contentHash }) + if (result.value.listed && (depth > 0 || listedStart)) + pages.push({ ...page, contentHash: result.value.contentHash }) if (depth >= limits.maxDepth) continue const before = seen.size for (const link of result.value.links) { diff --git a/apps/sim/connectors/website/page.test.ts b/apps/sim/connectors/website/page.test.ts index c8d216c8abf..a51ea3af3cc 100644 --- a/apps/sim/connectors/website/page.test.ts +++ b/apps/sim/connectors/website/page.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { decodePage, robotsHeaderNoindex } from '@/connectors/website/page' +import { decodePage, extractPageText, robotsDirectives } from '@/connectors/website/page' const html = (head: string, text: string) => `${head}${text}` @@ -44,7 +44,25 @@ describe('website page decoding', () => { describe('X-Robots-Tag', () => { it('honors an unqualified noindex after another crawler’s directive in a repeated header', () => { - expect(robotsHeaderNoindex('otherbot: noindex, noindex')).toBe(true) - expect(robotsHeaderNoindex('otherbot: noindex')).toBe(false) + expect(robotsDirectives('otherbot: noindex, noindex').noindex).toBe(true) + expect(robotsDirectives('otherbot: noindex').noindex).toBe(false) + }) + + it('reads nofollow and none as forbidding links, for this crawler only', () => { + expect(robotsDirectives('simbot: nofollow')).toEqual({ noindex: false, nofollow: true }) + expect(robotsDirectives('none')).toEqual({ noindex: true, nofollow: true }) + expect(robotsDirectives('otherbot: none').nofollow).toBe(false) + }) +}) + +describe('robots meta tag', () => { + const links = (content: string) => + extractPageText(html(``, 'Next')) + it('never reads a valued directive’s value as a directive', () => { + expect(links('max-image-preview:none')).toMatchObject({ noindex: false, links: ['/next'] }) + }) + + it('reads directives separated by spaces as well as commas', () => { + expect(links('noindex nofollow')).toMatchObject({ noindex: true, links: [] }) }) }) diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts index 0bf395515b2..0bbfed6a045 100644 --- a/apps/sim/connectors/website/page.ts +++ b/apps/sim/connectors/website/page.ts @@ -33,16 +33,18 @@ export interface WebsitePageText { export function extractPageText(html: string): WebsitePageText { assertHtmlStringWithinLimits(html) const $ = cheerio.load(html) - const directives = $(`meta[name="robots" i], meta[name="${WEBSITE_CRAWLER_TOKEN}" i]`) - .map((_, element) => $(element).attr('content') ?? '') - .get() - .join(',') + const directives = robotsDirectives( + $(`meta[name="robots" i], meta[name="${WEBSITE_CRAWLER_TOKEN}" i]`) + .map((_, element) => $(element).attr('content') ?? '') + .get() + .join(',') + ) const title = $('meta[property="og:title"]').attr('content')?.trim() || $('title').first().text().trim() || $('h1').first().text().trim() // Read before page chrome is dropped: navigation is where most of a site's links live. - const links = /\b(nofollow|none)\b/i.test(directives) + const links = directives.nofollow ? [] : $('a[href], area[href]') .filter((_, element) => !/\bnofollow\b/i.test($(element).attr('rel') ?? '')) @@ -58,7 +60,7 @@ export function extractPageText(html: string): WebsitePageText { return { title, text, - noindex: /\b(noindex|none)\b/i.test(directives), + noindex: directives.noindex, links, ...(baseHref ? { baseHref } : {}), } @@ -127,23 +129,35 @@ const VALUED_DIRECTIVES = new Set([ 'max-video-preview', ]) +/** What a page's robots directives ask of this crawler. */ +export interface RobotsDirectives { + /** `noindex` or `none`: leave the page out of the index. */ + noindex: boolean + /** `nofollow` or `none`: do not follow the page's links. */ + nofollow: boolean +} + /** - * Whether an `X-Robots-Tag` header asks this crawler not to index the page: `noindex` or `none`, - * either unqualified or after this crawler's name (`SimBot: noindex`). Only a directive right - * after another crawler's name is left to that crawler. Repeated headers arrive joined by commas, - * which hides where one ends, so a crawler name never carries over to the directives after it: - * an unqualified `noindex` is never mistaken for another crawler's. + * The directives a robots `` tag's content or an `X-Robots-Tag` header gives this crawler: + * each directive, either unqualified or after this crawler's name + * (`SimBot: noindex`). Only a directive right after another crawler's name is left to that + * crawler, and a valued directive (`max-image-preview: none`) is never read as its value. + * Repeated headers arrive joined by commas, which hides where one ends, so a crawler name never + * carries over to the directives after it: an unqualified `noindex` is never mistaken for another + * crawler's. */ -export function robotsHeaderNoindex(value: string | null): boolean { - if (!value) return false +export function robotsDirectives(value: string | null | undefined): RobotsDirectives { const token = WEBSITE_CRAWLER_TOKEN.toLowerCase() - return value.split(',').some((part) => { - let directive = part.trim().toLowerCase() + const directives = (value ?? '').split(',').flatMap((part) => { + const directive = part.trim().toLowerCase() const named = /^([\w-]+)\s*:\s*(.*)$/.exec(directive) - if (named && !VALUED_DIRECTIVES.has(named[1])) { - if (named[1] !== token) return false - directive = named[2] - } - return directive === 'noindex' || directive === 'none' + // Some pages separate directives with spaces (`noindex nofollow`) rather than commas. + if (!named) return directive.split(/\s+/) + if (VALUED_DIRECTIVES.has(named[1])) return [] + return named[1] === token ? [named[2]] : [] }) + return { + noindex: directives.some((directive) => directive === 'noindex' || directive === 'none'), + nofollow: directives.some((directive) => directive === 'nofollow' || directive === 'none'), + } } diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index bfc7abb658b..9441ffa5f89 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -188,6 +188,24 @@ const siteServer = createServer((request, response) => { }) .end(page('Tagged', '

Internal

')) return + case '/header-nofollow': + response + .writeHead(200, { 'Content-Type': 'text/html', 'X-Robots-Tag': 'simbot: nofollow' }) + .end(page('Header nofollow', '

Listed

Unfollowed')) + return + case '/image-policy': + return send( + 200, + 'text/html', + page( + 'Image policy', + '

Followed

Followed', + '' + ) + ) + case '/stall': + hung.push(response) + return case '/other-bot': response .writeHead(200, { 'Content-Type': 'text/html', 'X-Robots-Tag': 'otherbot: noindex' }) @@ -698,4 +716,38 @@ describe('website connector over real HTTP', () => { const urls = await listAll({ siteUrl: `${site}/guide`, discovery: 'links' }) expect(urls).toContain(`${site}/guide/intro`) }) + + it('follows no links from a page whose X-Robots-Tag forbids it, but still lists the page', async () => { + extraLinks = 'TaggedImages' + const urls = await listAll({ ...config(), discovery: 'links', maxDepth: '2' }) + expect(urls).toContain(`${site}/header-nofollow`) + const paths = pageRequests.map((request) => request.path) + expect(paths).not.toContain('/unfollowed') + expect(paths).toContain('/followed') + }) + + it('reads a start page outside the include paths for its links without listing it', async () => { + const urls = await listAll({ ...config(), discovery: 'links', includePaths: '/benefits' }) + expect(urls).toEqual([`${site}/benefits`]) + }) + + it('holds link validation to its deadline when a page stalls', async () => { + 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 ? 300 : ms)) + const started = Date.now() + try { + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { + siteUrl: `${site}/stall`, + discovery: 'links', + }) + ).toEqual({ valid: false, error: expect.stringContaining('did not answer') }) + } finally { + spy.mockRestore() + } + expect(Date.now() - started).toBeLessThan(5_000) + }) }) diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index 52c4d4e67a8..410b3dcfd51 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -1,6 +1,5 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' -import { sleep } from '@sim/utils/helpers' import { compareStrings } from '@sim/utils/string' import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' import { isHtmlComplexityError } from '@/lib/file-parsers/html-parser' @@ -21,7 +20,7 @@ import { WEBSITE_MAX_PAGES_LIMIT, websiteConnectorMeta, } from '@/connectors/website/meta' -import { decodePage, extractPageText, robotsHeaderNoindex } from '@/connectors/website/page' +import { decodePage, extractPageText, robotsDirectives } from '@/connectors/website/page' import { ALLOW_ALL_ROBOTS, parseRobots } from '@/connectors/website/robots' import { fetchRobotsText, @@ -60,21 +59,33 @@ const CRAWL_DEADLINE_MS = 120_000 interface WebsiteSession { scope: WebsiteScope headers: Record - pace: () => Promise + pace: (signal?: AbortSignal) => Promise } /** * Spaces calls at least `delayMs` apart, in the order they ask, however many run at once: the * Crawl-delay a site requests, applied to every page request of the sync. */ -function pacer(delayMs: number): () => Promise { +function pacer(delayMs: number): (signal?: AbortSignal) => Promise { let nextSlot = 0 - return async () => { + return async (signal) => { + signal?.throwIfAborted() if (!delayMs) return const now = Date.now() const slot = Math.max(now, nextSlot) nextSlot = slot + delayMs - if (slot > now) await sleep(slot - now) + if (slot <= now) return + await new Promise((resolve, reject) => { + const abort = () => { + clearTimeout(timer) + reject(signal?.reason) + } + const timer = setTimeout(() => { + signal?.removeEventListener('abort', abort) + resolve() + }, slot - now) + signal?.addEventListener('abort', abort, { once: true }) + }) } } @@ -234,9 +245,14 @@ interface PageRead extends CrawledPage { /** * Reads one page: its document (with text, or recorded as withdrawn or skipped), whether it * belongs in a crawl's listing, and the links a crawl may follow from it. A redirect may not leave - * the scope, and requests keep the pace the site's robots.txt asks for. + * the scope, and requests keep the pace the site's robots.txt asks for. `retryOptions.signal`, + * when given, bounds the wait for that pace as well as the request. */ -async function readPage(session: WebsiteSession, page: WebsitePage): Promise { +async function readPage( + session: WebsiteSession, + page: WebsitePage, + retryOptions?: SecureFetchRetryOptions +): Promise { const { scope, headers } = session const unlisted = (document: ExternalDocument): PageRead => ({ document, @@ -249,7 +265,7 @@ async function readPage(session: WebsiteSession, page: WebsitePage): Promise> let finalUrl = page.url - await session.pace() + await session.pace(retryOptions?.signal) try { resource = await fetchSiteResource( { @@ -257,6 +273,7 @@ async function readPage(session: WebsiteSession, page: WebsitePage): Promise { @@ -273,7 +290,7 @@ async function readPage(session: WebsiteSession, page: WebsitePage): Promise try { extracted = extractPageText(decodePage(resource.body, contentType)) @@ -282,13 +299,14 @@ async function readPage(session: WebsiteSession, page: WebsitePage): Promise) { - return crawlSitePages(session.scope, (page) => readPage(session, page), { + return crawlSitePages(session.scope, (page, signal) => readPage(session, page, { signal }), { maxPages: resolveMaxPages(sourceConfig.maxPages), maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, - deadline: Date.now() + CRAWL_DEADLINE_MS, + signal: AbortSignal.timeout(CRAWL_DEADLINE_MS), }) } @@ -399,11 +417,13 @@ export const websiteConnector: ConnectorConfig = { }) if (pages.length === 0 && mode !== 'sitemap') { // The crawl reads its first page the way a sync does, and needs text or links to go on. - const crawl = await crawlSitePages(scope, (page) => readPage(session, page), { + const crawl = await crawlSitePages(scope, (page) => readPage(session, page, retryOptions), { maxPages: 2, maxDepth: 1, - deadline: Date.now() + VALIDATE_DEADLINE_MS, + signal: retryOptions.signal, }) + // A crawl the deadline stopped before it found a page says nothing about the site. + if (!crawl.pages.length) retryOptions.signal.throwIfAborted() return crawl.pages.length ? { valid: true } : { From fc1ae500939bf30ab082a7f3b79343f20d7024de Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 01:27:34 -0800 Subject: [PATCH 4/4] fix(connectors): let a start page outside the include paths redirect, and validate links mode within the configured limits A traverse-only start page's redirects keep its include exception, validation crawls with the configured depth and page cap and stops at the first page it would list, crawler-named robots directives split on spaces, and rel=nofollow matches only the exact token. --- apps/sim/connectors/website/crawl.ts | 14 +++++-- apps/sim/connectors/website/page.test.ts | 11 ++++++ apps/sim/connectors/website/page.ts | 7 +++- .../connectors/website/website.integration.ts | 32 +++++++++++++++ apps/sim/connectors/website/website.ts | 39 ++++++++++++------- 5 files changed, 83 insertions(+), 20 deletions(-) diff --git a/apps/sim/connectors/website/crawl.ts b/apps/sim/connectors/website/crawl.ts index 22ed117203f..9175f95baa4 100644 --- a/apps/sim/connectors/website/crawl.ts +++ b/apps/sim/connectors/website/crawl.ts @@ -32,6 +32,8 @@ interface CrawlLimits { * by then is a truncated listing. */ signal: AbortSignal + /** Stops the crawl once this many pages are listed, when only some are needed. */ + maxListed?: number } /** @@ -39,18 +41,20 @@ interface CrawlLimits { * in-scope page is read once, never deeper than `maxDepth` links from the start, and no more pages * are queued than `maxPages`. A crawl cut by the page cap or its signal is truncated, and one * where a page could not be read is incomplete, so neither lets an unlisted page read as removed. - * A configured URL outside the include paths is still read for its links, but not listed. + * A configured URL outside the include paths is still read for its links, but not listed: `read` + * receives the scope a page and its redirects must stay within. */ export async function crawlSitePages( scope: WebsiteScope, - read: (page: WebsitePage, signal: AbortSignal) => Promise, + read: (page: WebsitePage, signal: AbortSignal, within: WebsiteScope) => Promise, limits: CrawlLimits ): Promise { // Relative links resolve against the URL a page is finally served at, as a browser's would. const seed = (within: WebsiteScope) => scopedPage(scope.site.baseUrl, within) ?? scopedPage(`${scope.site.baseUrl}/`, within) const listedStart = seed(scope) - const start = listedStart ?? seed({ ...scope, include: [] }) + const startScope = listedStart ? scope : { ...scope, include: [] } + const start = listedStart ?? seed(startScope) if (!start) throw new Error( 'The website URL is excluded by the configured paths or disallowed by robots.txt' @@ -66,7 +70,7 @@ export async function crawlSitePages( if (limits.signal.aborted) return { pages, truncated: true, incomplete } const batch = level.slice(offset, offset + CRAWL_CONCURRENCY) const results = await mapSettledWithConcurrency(batch, CRAWL_CONCURRENCY, (page) => - read(page, limits.signal) + read(page, limits.signal, depth === 0 ? startScope : scope) ) for (const [index, result] of results.entries()) { const page = batch[index] @@ -77,6 +81,8 @@ export async function crawlSitePages( } if (result.value.listed && (depth > 0 || listedStart)) pages.push({ ...page, contentHash: result.value.contentHash }) + if (limits.maxListed && pages.length >= limits.maxListed) + return { pages, truncated: true, incomplete } if (depth >= limits.maxDepth) continue const before = seen.size for (const link of result.value.links) { diff --git a/apps/sim/connectors/website/page.test.ts b/apps/sim/connectors/website/page.test.ts index a51ea3af3cc..b119135b496 100644 --- a/apps/sim/connectors/website/page.test.ts +++ b/apps/sim/connectors/website/page.test.ts @@ -52,6 +52,7 @@ describe('X-Robots-Tag', () => { expect(robotsDirectives('simbot: nofollow')).toEqual({ noindex: false, nofollow: true }) expect(robotsDirectives('none')).toEqual({ noindex: true, nofollow: true }) expect(robotsDirectives('otherbot: none').nofollow).toBe(false) + expect(robotsDirectives('simbot: noindex nofollow')).toEqual({ noindex: true, nofollow: true }) }) }) @@ -62,6 +63,16 @@ describe('robots meta tag', () => { expect(links('max-image-preview:none')).toMatchObject({ noindex: false, links: ['/next'] }) }) + it('skips only links whose rel holds the nofollow token', () => { + const page = extractPageText( + html( + '', + 'KeptDropped' + ) + ) + expect(page.links).toEqual(['/kept']) + }) + it('reads directives separated by spaces as well as commas', () => { expect(links('noindex nofollow')).toMatchObject({ noindex: true, links: [] }) }) diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts index 0bbfed6a045..725baa3b959 100644 --- a/apps/sim/connectors/website/page.ts +++ b/apps/sim/connectors/website/page.ts @@ -47,7 +47,10 @@ export function extractPageText(html: string): WebsitePageText { const links = directives.nofollow ? [] : $('a[href], area[href]') - .filter((_, element) => !/\bnofollow\b/i.test($(element).attr('rel') ?? '')) + .filter( + (_, element) => + !($(element).attr('rel') ?? '').toLowerCase().split(/\s+/).includes('nofollow') + ) .map((_, element) => $(element).attr('href') ?? '') .get() .filter(Boolean) @@ -154,7 +157,7 @@ export function robotsDirectives(value: string | null | undefined): RobotsDirect // Some pages separate directives with spaces (`noindex nofollow`) rather than commas. if (!named) return directive.split(/\s+/) if (VALUED_DIRECTIVES.has(named[1])) return [] - return named[1] === token ? [named[2]] : [] + return named[1] === token ? named[2].split(/\s+/) : [] }) return { noindex: directives.some((directive) => directive === 'noindex' || directive === 'none'), diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index 9441ffa5f89..705ba73d561 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -203,6 +203,19 @@ const siteServer = createServer((request, response) => { '' ) ) + case '/chain': + case '/chain/next': + return send( + 200, + 'text/html', + page( + 'Chain', + `

Draft

Next`, + '' + ) + ) + case '/chain/next/next': + return send(200, 'text/html', page('End', '

Published

')) case '/stall': hung.push(response) return @@ -644,6 +657,7 @@ describe('website connector over real HTTP', () => { `${site}/faq`, context ) + expect(stub?.contentHash).toEqual(expect.any(String)) expect(stub?.contentHash).toBe(document?.contentHash) }) @@ -731,6 +745,24 @@ describe('website connector over real HTTP', () => { expect(urls).toEqual([`${site}/benefits`]) }) + it('lets a start page outside the include paths redirect before its links are read', async () => { + const urls = await listAll({ + siteUrl: `${site}/guide`, + discovery: 'links', + includePaths: '/guide/intro', + }) + expect(urls).toEqual([`${site}/guide/intro`]) + }) + + it('validates a site whose first page with text is several links from the start', async () => { + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { + siteUrl: `${site}/chain`, + discovery: 'links', + }) + ).toEqual({ valid: true }) + }) + it('holds link validation to its deadline when a page stalls', async () => { const timeout = AbortSignal.timeout.bind(AbortSignal) const spy = vi diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index 410b3dcfd51..8ef1db00606 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -251,9 +251,10 @@ interface PageRead extends CrawledPage { async function readPage( session: WebsiteSession, page: WebsitePage, - retryOptions?: SecureFetchRetryOptions + retryOptions?: SecureFetchRetryOptions, + scope = session.scope ): Promise { - const { scope, headers } = session + const { headers } = session const unlisted = (document: ExternalDocument): PageRead => ({ document, listed: false, @@ -334,11 +335,15 @@ async function readPage( /** Discovers a site's pages by following its links, each page read once and in scope. */ function crawlDiscovery(session: WebsiteSession, sourceConfig: Record) { - return crawlSitePages(session.scope, (page, signal) => readPage(session, page, { signal }), { - maxPages: resolveMaxPages(sourceConfig.maxPages), - maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, - signal: AbortSignal.timeout(CRAWL_DEADLINE_MS), - }) + return crawlSitePages( + session.scope, + (page, signal, within) => readPage(session, page, { signal }, within), + { + maxPages: resolveMaxPages(sourceConfig.maxPages), + maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, + signal: AbortSignal.timeout(CRAWL_DEADLINE_MS), + } + ) } /** Discovers website pages and reads their text within the configured scope. */ @@ -416,19 +421,25 @@ export const websiteConnector: ConnectorConfig = { retryOptions, }) if (pages.length === 0 && mode !== 'sitemap') { - // The crawl reads its first page the way a sync does, and needs text or links to go on. - const crawl = await crawlSitePages(scope, (page) => readPage(session, page, retryOptions), { - maxPages: 2, - maxDepth: 1, - signal: retryOptions.signal, - }) + // The crawl reads pages the way a sync does, within the configured limits, and stops at + // the first page it would list. + const crawl = await crawlSitePages( + scope, + (page, _signal, within) => readPage(session, page, retryOptions, within), + { + maxPages: resolveMaxPages(sourceConfig.maxPages), + maxDepth: parseMaxDepth(sourceConfig.maxDepth) ?? WEBSITE_DEFAULT_MAX_DEPTH, + signal: retryOptions.signal, + maxListed: 1, + } + ) // A crawl the deadline stopped before it found a page says nothing about the site. if (!crawl.pages.length) retryOptions.signal.throwIfAborted() return crawl.pages.length ? { valid: true } : { valid: false, - error: `${scope.site.baseUrl} has no sitemap, and its page offers no text or links to follow within the configured paths`, + error: `${scope.site.baseUrl} has no sitemap, and following its links found no page with text within the configured paths`, } } if (pages.length === 0)