From 08bb7d9e3bbb1c777a5ba18d69789fb0521005c9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:09:27 -0800 Subject: [PATCH 1/9] feat(connectors): add a website connector that syncs pages from a site's sitemaps --- apps/docs/components/icons.tsx | 21 ++ apps/sim/components/icons.tsx | 21 ++ apps/sim/connectors/registry.server.ts | 2 + apps/sim/connectors/registry.ts | 2 + apps/sim/connectors/website/index.ts | 1 + apps/sim/connectors/website/meta.ts | 79 ++++++ apps/sim/connectors/website/page.ts | 41 +++ apps/sim/connectors/website/robots.test.ts | 54 ++++ apps/sim/connectors/website/robots.ts | 92 +++++++ apps/sim/connectors/website/site.test.ts | 45 +++ apps/sim/connectors/website/site.ts | 170 ++++++++++++ apps/sim/connectors/website/sitemap.ts | 190 +++++++++++++ .../connectors/website/website.integration.ts | 251 +++++++++++++++++ apps/sim/connectors/website/website.ts | 258 ++++++++++++++++++ apps/sim/lib/file-parsers/html-parser.ts | 20 +- 15 files changed, 1240 insertions(+), 7 deletions(-) create mode 100644 apps/sim/connectors/website/index.ts create mode 100644 apps/sim/connectors/website/meta.ts create mode 100644 apps/sim/connectors/website/page.ts create mode 100644 apps/sim/connectors/website/robots.test.ts create mode 100644 apps/sim/connectors/website/robots.ts create mode 100644 apps/sim/connectors/website/site.test.ts create mode 100644 apps/sim/connectors/website/site.ts create mode 100644 apps/sim/connectors/website/sitemap.ts create mode 100644 apps/sim/connectors/website/website.integration.ts create mode 100644 apps/sim/connectors/website/website.ts diff --git a/apps/docs/components/icons.tsx b/apps/docs/components/icons.tsx index 05b17279bbd..0651d2c3408 100644 --- a/apps/docs/components/icons.tsx +++ b/apps/docs/components/icons.tsx @@ -4874,6 +4874,27 @@ export function WealthboxIcon(props: SVGProps) { ) } +export function WebsiteIcon(props: SVGProps) { + return ( + + + + + + ) +} + export function WebhookIcon(props: SVGProps) { return ( ) { ) } +export function WebsiteIcon(props: SVGProps) { + return ( + + + + + + ) +} + export function WebhookIcon(props: SVGProps) { return ( header, body > footer, nav, [role="navigation"], [role="banner"], [role="contentinfo"]' + +export interface WebsitePageText { + title: string + text: string + /** The page asks not to be indexed (`noindex` or `none` in its robots meta tag). */ + noindex: boolean +} + +/** + * Reads a rendered HTML page as structured text: headings, lists and tables survive, scripts and + * styles do not, and the `
` or `
` region is preferred over the whole body. The + * shared HTML size and markup limits apply before the page is parsed. + */ +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 title = + $('meta[property="og:title"]').attr('content')?.trim() || + $('title').first().text().trim() || + $('h1').first().text().trim() + $(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) } +} diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts new file mode 100644 index 00000000000..64692fcbaea --- /dev/null +++ b/apps/sim/connectors/website/robots.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from 'vitest' +import { parseRobots } from '@/connectors/website/robots' + +describe('robots.txt rules for the website connector', () => { + it('lets the longest matching rule decide, with Allow winning a tie', () => { + const robots = parseRobots( + [ + 'User-agent: *', + 'Disallow: /private', + 'Allow: /private/handbook', + 'Disallow: /tie', + 'Allow: /tie', + ].join('\n') + ) + expect(robots.allows('/private/salaries')).toBe(false) + expect(robots.allows('/private/handbook/leave')).toBe(true) + expect(robots.allows('/tie')).toBe(true) + expect(robots.allows('/public')).toBe(true) + }) + + it('applies only the group naming this crawler when one exists', () => { + const robots = parseRobots( + [ + 'User-agent: *', + 'Disallow: /', + '', + 'User-agent: OtherBot', + 'User-agent: SimBot', + 'Disallow: /drafts', + ].join('\n') + ) + expect(robots.allows('/benefits')).toBe(true) + expect(robots.allows('/drafts/plan')).toBe(false) + }) + + it('matches wildcards and end anchors against the path and query', () => { + const robots = parseRobots( + ['User-agent: *', 'Disallow: /*?print=', 'Disallow: /*.pdf$'].join('\n') + ) + expect(robots.allows('/plans?print=1')).toBe(false) + expect(robots.allows('/guide.pdf')).toBe(false) + expect(robots.allows('/guide.pdf.html')).toBe(true) + }) + + it('treats an empty Disallow as allowing everything and collects declared sitemaps', () => { + const robots = parseRobots( + ['Sitemap: https://example.com/a.xml', 'User-agent: *', 'Disallow:', '# Disallow: /x'].join( + '\n' + ) + ) + expect(robots.allows('/x')).toBe(true) + expect(robots.sitemaps).toEqual(['https://example.com/a.xml']) + }) +}) diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts new file mode 100644 index 00000000000..694a3105017 --- /dev/null +++ b/apps/sim/connectors/website/robots.ts @@ -0,0 +1,92 @@ +import { escapeRegExp } from '@sim/utils/string' + +/** The product token the connector sends and honors robots.txt groups for. */ +export const WEBSITE_CRAWLER_TOKEN = 'SimBot' + +interface RobotsRule { + allow: boolean + pattern: string + matcher: RegExp +} + +/** A site's robots.txt as it applies to this crawler, plus the sitemaps it declares. */ +export interface RobotsPolicy { + allows(path: string): boolean + sitemaps: string[] +} + +/** A path pattern as regular expression source, where `*` matches any run of characters. */ +export function wildcardSource(pattern: string): string { + return pattern.split('*').map(escapeRegExp).join('.*') +} + +/** A robots.txt path pattern as a regular expression: `*` matches anything, a final `$` anchors. */ +function patternMatcher(pattern: string): RegExp { + const anchored = pattern.endsWith('$') + return new RegExp( + `^${wildcardSource(anchored ? pattern.slice(0, -1) : pattern)}${anchored ? '$' : ''}` + ) +} + +/** + * Parses robots.txt per RFC 9309: the rules of the groups naming this crawler, or of the `*` + * 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 sitemaps: string[] = [] + let current: { agents: string[]; rules: RobotsRule[] } | undefined + let readingAgents = false + for (const raw of body.split(/\r?\n/)) { + const line = raw.replace(/#.*$/, '').trim() + const separator = line.indexOf(':') + if (separator < 1) continue + const field = line.slice(0, separator).trim().toLowerCase() + const value = line.slice(separator + 1).trim() + if (field === 'sitemap') { + if (value) sitemaps.push(value) + continue + } + if (field === 'user-agent') { + if (!readingAgents || !current) { + current = { agents: [], rules: [] } + groups.push(current) + } + current.agents.push(value.toLowerCase()) + readingAgents = true + continue + } + readingAgents = false + if (!current || (field !== 'allow' && field !== 'disallow')) continue + if (!value) continue + current.rules.push({ + allow: field === 'allow', + pattern: value, + matcher: patternMatcher(value), + }) + } + 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) + return { + sitemaps, + allows(path) { + let decision: RobotsRule | undefined + for (const rule of rules) { + if (!rule.matcher.test(path)) continue + if ( + !decision || + rule.pattern.length > decision.pattern.length || + (rule.pattern.length === decision.pattern.length && rule.allow) + ) + decision = rule + } + return decision?.allow ?? true + }, + } +} + +/** A site without robots.txt allows everything and declares no sitemaps. */ +export const ALLOW_ALL_ROBOTS: RobotsPolicy = { sitemaps: [], allows: () => true } diff --git a/apps/sim/connectors/website/site.test.ts b/apps/sim/connectors/website/site.test.ts new file mode 100644 index 00000000000..46d48ed6e15 --- /dev/null +++ b/apps/sim/connectors/website/site.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest' +import { parseRequestHeaders, pathPatterns, resolveSite } from '@/connectors/website/site' + +describe('website request headers', () => { + it('accepts up to two service headers', () => { + expect( + parseRequestHeaders('CF-Access-Client-Id: abc.access\nCF-Access-Client-Secret: s3cret') + ).toEqual({ 'cf-access-client-id': 'abc.access', 'cf-access-client-secret': 's3cret' }) + expect(parseRequestHeaders('')).toEqual({}) + }) + + it.each([ + ['a cookie, which is a person’s session', 'Cookie: session=abc', 'cannot be configured'], + ['a header that rewrites the connection', 'Host: internal.example.com', 'cannot be configured'], + ['a proxy credential', 'Proxy-Authorization: Basic abc', 'cannot be configured'], + ['a value carrying control characters', 'X-Api-Key: abc\u0000def', 'Name: value'], + ['a line without a name', ': value', 'Name: value'], + ['more than two headers', 'A: 1\nB: 2\nC: 3', 'at most 2'], + ['a repeated header', 'X-Key: 1\nx-key: 2', 'configured twice'], + ])('refuses %s', (_case, credential, reason) => { + expect(() => parseRequestHeaders(credential)).toThrow(reason) + }) +}) + +describe('website scope', () => { + it('matches a path pattern and what sits beneath it, never a sibling sharing its prefix', () => { + const [matches] = pathPatterns('/benefits') + expect(matches?.('/benefits')).toBe(true) + expect(matches?.('/benefits/medical')).toBe(true) + expect(matches?.('/benefits-archive')).toBe(false) + const [wildcard] = pathPatterns('/help/*/faq') + expect(wildcard?.('/help/hr/faq/leave')).toBe(true) + expect(wildcard?.('/help/faq')).toBe(false) + }) + + it('refuses a site URL carrying credentials or a non-web scheme', () => { + expect(() => resolveSite('https://user:pass@example.com')).toThrow() + expect(() => resolveSite('ftp://example.com')).toThrow('http or https') + expect(resolveSite('www.Example.com/help/')).toMatchObject({ + baseUrl: 'https://www.example.com/help', + basePath: '/help', + hostKey: 'example.com', + }) + }) +}) diff --git a/apps/sim/connectors/website/site.ts b/apps/sim/connectors/website/site.ts new file mode 100644 index 00000000000..7381dd3fac7 --- /dev/null +++ b/apps/sim/connectors/website/site.ts @@ -0,0 +1,170 @@ +import { validateExternalUrl } from '@/lib/core/security/input-validation' +import { + type SecureFetchRetryOptions, + secureFetchWithRetry, +} from '@/lib/knowledge/documents/secure-fetch.server' +import { WEBSITE_CRAWLER_TOKEN, wildcardSource } from '@/connectors/website/robots' + +/** The configured site: its origin, the path pages must sit under, and the host it may reach. */ +export interface WebsiteSite { + origin: string + /** Configured URL without a trailing slash, e.g. `https://example.com/help`. */ + baseUrl: string + /** Path pages must sit under, without a trailing slash; `''` at the host root. */ + basePath: string + /** Hostname without a leading `www.`; the apex and `www` host count as one site. */ + hostKey: string +} + +/** + * Normalizes the configured URL and runs the structural SSRF check. Every request still goes + * through {@link secureFetchWithRetry}, which resolves DNS, re-checks the resolved address and pins + * the connection to it. + */ +export function resolveSite(rawUrl: unknown): WebsiteSite { + let url = (typeof rawUrl === 'string' ? rawUrl : '').trim().replace(/\/+$/, '') + if (!url) throw new Error('Website URL is required') + if (/^[a-z][a-z\d+.-]*:\/\//i.test(url) && !/^https?:\/\//i.test(url)) + throw new Error('Website URL must use http or https') + if (!/^https?:\/\//i.test(url)) url = `https://${url}` + const validation = validateExternalUrl(url, 'siteUrl', 'configuredEndpoint') + if (!validation.isValid) throw new Error(validation.error || 'Invalid website URL') + const parsed = new URL(url) + if (parsed.username || parsed.password) + throw new Error('Website URL must not contain credentials') + return { + origin: parsed.origin, + baseUrl: `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`, + basePath: parsed.pathname.replace(/\/+$/, ''), + hostKey: parsed.hostname.replace(/^www\./, '').toLowerCase(), + } +} + +/** Whether a URL is an http(s) URL on the configured site's host. */ +export function onSiteHost(url: URL, site: WebsiteSite): boolean { + return ( + (url.protocol === 'https:' || url.protocol === 'http:') && + !url.username && + !url.password && + url.hostname.replace(/^www\./, '').toLowerCase() === site.hostKey + ) +} + +/** `location`, resolved against `base`, when it is an http(s) URL on the configured site's host. */ +export function siteUrl(location: string, base: string, site: WebsiteSite): URL | null { + try { + const url = new URL(location, base) + return onSiteHost(url, site) ? url : null + } catch { + return null + } +} + +/** Whether `path` is `prefix` itself or sits beneath it; `/guides` never captures `/guides-old`. */ +export function isUnderPath(path: string, prefix: string): boolean { + return !prefix || path === prefix || path.startsWith(`${prefix}/`) +} + +/** + * Comma-separated path patterns as matchers. A pattern matches the path it names and everything + * beneath it; `*` matches any run of characters, including `/`. + */ +export function pathPatterns(value: unknown): ((path: string) => boolean)[] { + if (typeof value !== 'string') return [] + return value + .split(',') + .map((part) => part.trim().replace(/\/+$/, '')) + .filter(Boolean) + .map((pattern) => { + const prefix = pattern.startsWith('/') ? pattern : `/${pattern}` + if (!prefix.includes('*')) return (path: string) => isUnderPath(path, prefix) + const matcher = new RegExp(`^${wildcardSource(prefix)}(?:/.*)?$`) + return (path: string) => matcher.test(path) + }) +} + +/** Header names a configured credential may never set: they belong to the connection or a person. */ +const RESERVED_HEADERS = new Set([ + 'connection', + 'content-length', + 'cookie', + 'host', + 'keep-alive', + 'proxy-authorization', + 'proxy-connection', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'user-agent', +]) + +const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ +/** Visible ASCII and spaces; anything else could smuggle a second header or a request line. */ +const HEADER_VALUE = /^[\x20-\x7e]*$/ +const MAX_CONFIGURED_HEADERS = 2 + +/** + * The request headers a configured credential names, one `Name: value` per line. Throws on a + * malformed line, a reserved header, or more than two headers. + */ +export function parseRequestHeaders(credential: string): Record { + const headers: Record = {} + const lines = credential + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + if (lines.length > MAX_CONFIGURED_HEADERS) + throw new Error(`Configure at most ${MAX_CONFIGURED_HEADERS} request headers`) + for (const line of lines) { + const separator = line.indexOf(':') + const name = separator > 0 ? line.slice(0, separator).trim() : '' + const value = separator > 0 ? line.slice(separator + 1).trim() : '' + if (!HEADER_NAME.test(name) || !value || !HEADER_VALUE.test(value)) + throw new Error('Request headers must be "Name: value" lines') + const key = name.toLowerCase() + if (RESERVED_HEADERS.has(key) || key.startsWith('proxy-') || key.startsWith('sec-')) + throw new Error(`The ${name} header cannot be configured`) + if (Object.hasOwn(headers, key)) throw new Error(`The ${name} header is configured twice`) + headers[key] = value + } + return headers +} + +/** + * Fetches a resource on the configured site, or `null` when it does not exist (404 or 410). A + * redirect is refused before it is followed unless it stays on the site's host and, for a page, + * within the configured scope (`allowsTarget`), so configured headers never reach another host + * and a page never indexes content from outside the scope. + */ +export async function fetchSiteResource( + url: string, + site: WebsiteSite, + headers: Record, + accept: string, + maxBytes: number, + retryOptions?: SecureFetchRetryOptions, + allowsTarget?: (target: URL) => boolean +): Promise<{ body: Buffer; contentType: string } | null> { + const response = await secureFetchWithRetry( + url, + { + profile: 'configuredEndpoint', + method: 'GET', + headers: { ...headers, Accept: accept, 'User-Agent': `${WEBSITE_CRAWLER_TOKEN}/1.0` }, + assertRedirectTarget: (target) => { + const next = new URL(target) + if (!onSiteHost(next, site)) throw new Error(`The site redirected ${url} off its host`) + if (allowsTarget && !allowsTarget(next)) + throw new Error(`The site redirected ${url} outside the configured scope`) + }, + }, + { ...retryOptions, maxResponseBytes: maxBytes } + ) + if (response.status === 404 || response.status === 410) return null + if (!response.ok) throw new Error(`The site returned status ${response.status} for ${url}`) + return { + body: Buffer.from(await response.arrayBuffer()), + contentType: response.headers.get('content-type') ?? '', + } +} diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts new file mode 100644 index 00000000000..4c76a53101d --- /dev/null +++ b/apps/sim/connectors/website/sitemap.ts @@ -0,0 +1,190 @@ +import { gunzipSync } from 'node:zlib' +import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' +import { decodeHtmlEntities } from '@/connectors/utils' +import type { RobotsPolicy } from '@/connectors/website/robots' +import { + fetchSiteResource, + isUnderPath, + siteUrl, + type WebsiteSite, +} from '@/connectors/website/site' + +/** Bytes read from one sitemap, compressed or not. */ +const SITEMAP_MAX_BYTES = 5 * 1024 * 1024 +/** Decompressed ceiling of a gzipped sitemap. */ +const SITEMAP_MAX_DECOMPRESSED_BYTES = 50 * 1024 * 1024 + +/** Sitemap documents read in one discovery, bounding a hostile or huge sitemap index. */ +const MAX_SITEMAP_DOCUMENTS = 20 + +/** + * Pages accumulated across every sitemap read. Reaching it truncates the listing, which the + * caller must report so deletion reconciliation never treats unlisted pages as removed. + */ +const MAX_SITEMAP_PAGES = 50_000 + +/** Paths that are files rather than pages; only HTML pages are indexed from a sitemap. */ +const NON_PAGE_PATH = + /\.(xml|gz|json|ya?ml|txt|csv|png|jpe?g|gif|svg|webp|ico|pdf|docx?|xlsx?|pptx?|zip|css|js|mp4|mp3)$/i + +/** A page a sitemap lists, by the URL its document is identified by. */ +export interface WebsitePage { + /** Canonical page URL without its fragment; the document's external ID and source URL. */ + url: string + path: string + /** The sitemap's ``, as an ISO timestamp, when it gives a valid one. */ + lastModified?: string +} + +export interface WebsiteDiscovery { + pages: WebsitePage[] + /** The sitemaps listed more pages than one discovery reads. */ + truncated: boolean +} + +interface SitemapDiscoveryOptions { + /** A sitemap on the site's host to read instead of the discovered ones. */ + configuredSitemap?: string + /** Pages to discover before stopping. */ + limit?: number + retryOptions?: SecureFetchRetryOptions +} + +export interface WebsiteScope { + site: WebsiteSite + robots: RobotsPolicy + include: ((path: string) => boolean)[] + exclude: ((path: string) => boolean)[] +} + +const ENTRY_PATTERN = /<(url|sitemap)\b[^>]*>([\s\S]*?)<\/\1\s*>/gi +const LOC_PATTERN = /\s*([^<]+?)\s*<\/loc>/i +const LASTMOD_PATTERN = /\s*([^<]+?)\s*<\/lastmod>/i + +interface SitemapEntry { + kind: 'url' | 'sitemap' + loc: string + lastmod?: string +} + +function sitemapEntries(xml: string): SitemapEntry[] { + const entries: SitemapEntry[] = [] + for (const match of xml.matchAll(ENTRY_PATTERN)) { + const loc = LOC_PATTERN.exec(match[2])?.[1] + if (!loc) continue + entries.push({ + kind: match[1].toLowerCase() === 'sitemap' ? 'sitemap' : 'url', + loc: decodeHtmlEntities(loc), + lastmod: LASTMOD_PATTERN.exec(match[2])?.[1], + }) + } + return entries +} + +/** 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) + if (!url) return null + url.hash = '' + const path = url.pathname.replace(/\/+$/, '') || '/' + if (NON_PAGE_PATH.test(path) || !isUnderPath(path, scope.site.basePath)) return null + if (scope.include.length && !scope.include.some((matches) => matches(path))) return null + if (scope.exclude.some((matches) => matches(path))) return null + if (!scope.robots.allows(`${url.pathname}${url.search}`)) return null + return { url: url.toString(), path } +} + +async function readSitemap( + url: string, + site: WebsiteSite, + headers: Record, + retryOptions?: SecureFetchRetryOptions +): Promise { + const resource = await fetchSiteResource( + url, + site, + headers, + 'application/xml, text/xml;q=0.9, */*;q=0.1', + SITEMAP_MAX_BYTES, + retryOptions + ) + if (!resource) return null + const gzipped = resource.body[0] === 0x1f && resource.body[1] === 0x8b + return ( + gzipped + ? gunzipSync(resource.body, { maxOutputLength: SITEMAP_MAX_DECOMPRESSED_BYTES }) + : resource.body + ).toString('utf8') +} + +/** + * The sitemaps discovery starts from: a configured one, else those robots.txt declares on this + * host, else the conventional `sitemap.xml` under the configured path and at the host root. + */ +function rootSitemaps(scope: WebsiteScope, configured?: string): string[] { + const { site } = scope + if (configured) return [configured] + const declared = scope.robots.sitemaps.flatMap((location) => { + const url = siteUrl(location, `${site.origin}/`, site) + return url ? [url.toString()] : [] + }) + if (declared.length) return [...new Set(declared)] + return [...new Set([`${site.baseUrl}/sitemap.xml`, `${site.origin}/sitemap.xml`])] +} + +/** + * Discovers up to `limit` of the site's pages from its sitemaps, following sitemap indexes into + * their children; reaching the limit with more pages listed reports the discovery as truncated. + * A configured sitemap or a child an index lists must exist: skipping one would hand the sync a + * listing short of that sitemap's pages, which it cannot tell from deletions. + */ +export async function discoverSitemapPages( + scope: WebsiteScope, + headers: Record, + { configuredSitemap, limit = MAX_SITEMAP_PAGES, retryOptions }: SitemapDiscoveryOptions = {} +): Promise { + const { site } = scope + const pages = new Map() + const queue = rootSitemaps(scope, configuredSitemap).map((url) => ({ + url, + required: Boolean(configuredSitemap), + })) + const visited = new Set() + let truncated = false + let documents = 0 + while (queue.length && !truncated) { + const next = queue.shift() + if (!next || visited.has(next.url)) continue + visited.add(next.url) + if (++documents > MAX_SITEMAP_DOCUMENTS) + throw new Error( + `The site's sitemaps span more than ${MAX_SITEMAP_DOCUMENTS} documents. Configure a sitemap URL that lists the pages to sync.` + ) + const xml = await readSitemap(next.url, site, headers, retryOptions) + if (xml === null) { + if (next.required) throw new Error(`Sitemap ${next.url} is unavailable`) + continue + } + for (const entry of sitemapEntries(xml)) { + if (entry.kind === 'sitemap') { + const child = siteUrl(entry.loc, next.url, site) + if (child) queue.push({ url: child.toString(), required: true }) + continue + } + const page = scopedPage(entry.loc, scope) + if (!page || pages.has(page.url)) continue + if (pages.size >= Math.min(limit, MAX_SITEMAP_PAGES)) { + truncated = true + break + } + const lastModified = Date.parse(entry.lastmod ?? '') + pages.set(page.url, { + ...page, + ...(Number.isFinite(lastModified) + ? { lastModified: new Date(lastModified).toISOString() } + : {}), + }) + } + } + return { pages: [...pages.values()], truncated } +} diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts new file mode 100644 index 00000000000..1265a7a216e --- /dev/null +++ b/apps/sim/connectors/website/website.integration.ts @@ -0,0 +1,251 @@ +/** + * The website connector against real HTTP servers through the SSRF-guarded fetch: sitemap index + * discovery (including a gzipped child), robots.txt, scope rules, configured headers, redirects that + * leave the site, the listing cap, and page extraction. + */ +import { createServer, type IncomingMessage, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { gzipSync } from 'node:zlib' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { websiteConnector } from '@/connectors/website/website' + +const KEY = 'synthetic-site-key' +let site = '' +let foreign = '' +let foreignRequests: IncomingMessage[] = [] +let robotsStatus = 200 +let missingChild = false +let faqBody = '

Original answer.

' + +function listen(server: Server, host: string): Promise { + return new Promise((resolve) => + server.listen(0, '127.0.0.1', () => + resolve(`http://${host}:${(server.address() as AddressInfo).port}`) + ) + ) +} + +const page = (title: string, main: string, head = '') => + `${title}${head}
${main}
Copyright
` + +const siteServer = createServer((request, response) => { + if (request.headers['x-api-key'] !== KEY) { + response.writeHead(401).end() + return + } + const send = (status: number, type: string, body: string | Buffer) => + response.writeHead(status, { 'Content-Type': type }).end(body) + const path = new URL(request.url ?? '/', site).pathname + switch (path) { + case '/robots.txt': + if (robotsStatus !== 200) return send(robotsStatus, 'text/plain', 'error') + return send( + 200, + 'text/plain', + `User-agent: *\nDisallow: /private\nSitemap: ${site}/sitemap-index.xml\n` + ) + case '/sitemap-index.xml': + return send( + 200, + 'application/xml', + `${site}/pages.xml${site}/more.xml.gz${foreign}/elsewhere.xml` + ) + case '/pages.xml': + return send( + 200, + 'application/xml', + `${[ + `${site}/benefits2026-11-01`, + `${site}/private/salaries`, + `${foreign}/off-site`, + `${site}/benefits.pdf`, + `${site}/moved`, + `${site}/gone`, + `${site}/hidden`, + `${site}/huge`, + `${site}/renamed`, + ].join('')}` + ) + case '/more.xml.gz': + if (missingChild) return send(404, 'text/plain', '') + return send( + 200, + 'application/gzip', + gzipSync(`${site}/faq`) + ) + case '/benefits': + return send( + 200, + 'text/html; charset=utf-8', + page('Benefits', '

Medical plans

  • Plan A
  • Plan B
') + ) + case '/faq': + return send( + 200, + 'text/html', + `FAQ
${faqBody}
Copyright
` + ) + case '/hidden': + return send( + 200, + 'text/html', + page('Hidden', '

Draft

', '') + ) + case '/huge': + return send(200, 'text/html', page('Huge', `

${'x'.repeat(3 * 1024 * 1024)}

`)) + case '/renamed': + response.writeHead(301, { Location: `${site}/private/salaries` }).end() + return + case '/moved': + response.writeHead(302, { Location: `${foreign}/landing` }).end() + return + default: + return send(404, 'text/plain', '') + } +}) + +const foreignServer = createServer((request, response) => { + foreignRequests.push(request) + response.writeHead(200, { 'Content-Type': 'text/html' }).end(page('Elsewhere', '

Other

')) +}) + +const config = () => ({ siteUrl: site }) + +beforeAll(async () => { + site = await listen(siteServer, '127.0.0.1') + foreign = await listen(foreignServer, 'localhost') +}) + +afterAll(async () => { + await Promise.all( + [siteServer, foreignServer].map( + (server) => new Promise((resolve) => server.close(() => resolve(undefined))) + ) + ) +}) + +beforeEach(() => { + foreignRequests = [] + robotsStatus = 200 + missingChild = false + faqBody = '

Original answer.

' +}) + +async function listAll(sourceConfig: Record, syncContext = {}) { + const urls: string[] = [] + let cursor: string | undefined + do { + const page = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + sourceConfig, + cursor, + syncContext + ) + urls.push(...page.documents.map((document) => document.externalId)) + cursor = page.nextCursor + } while (cursor) + return urls +} + +describe('website connector over real HTTP', () => { + it('lists the pages of a sitemap index and its gzipped child, within scope and robots.txt', async () => { + const urls = await listAll(config()) + expect(urls.sort()).toEqual( + [ + `${site}/benefits`, + `${site}/faq`, + `${site}/gone`, + `${site}/hidden`, + `${site}/huge`, + `${site}/moved`, + `${site}/renamed`, + ].sort() + ) + expect(foreignRequests).toHaveLength(0) + }) + + it('reads a page as its main region, under the same hash its sitemap date gave the listing', async () => { + const context = {} + const listed = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + config(), + undefined, + context + ) + const stub = listed.documents.find((document) => document.externalId === `${site}/benefits`) + const document = await websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + config(), + `${site}/benefits`, + context + ) + expect(document?.title).toBe('Benefits') + expect(document?.content).toContain('Medical plans') + expect(document?.content).toContain('Plan B') + expect(document?.content).not.toContain('Copyright') + expect(document?.contentHash).toBe(stub?.contentHash) + }) + + it('changes an undated page’s hash only when its text changes', async () => { + const read = () => + websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}/faq`, {}) + const first = await read() + expect(first?.content).toContain('Original answer.') + expect(first?.content).not.toContain('Copyright') + expect((await read())?.contentHash).toBe(first?.contentHash) + faqBody = '

Updated answer.

' + expect((await read())?.contentHash).not.toBe(first?.contentHash) + }) + + it('drops pages that are gone, ask not to be indexed, or robots.txt forbids', async () => { + for (const path of ['/gone', '/hidden', '/private/salaries']) + expect( + await websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}${path}`, {}) + ).toBeNull() + }) + + it('refuses a redirect off the site or out of scope before it is followed', async () => { + await expect( + websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}/moved`, {}) + ).rejects.toThrow('off its host') + expect(foreignRequests).toHaveLength(0) + await expect( + websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}/renamed`, {}) + ).rejects.toThrow('outside the configured scope') + }) + + it('records a page over the size limit as skipped instead of failing the sync', async () => { + const document = await websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + config(), + `${site}/huge`, + {} + ) + expect(document?.skippedReason).toContain('size limit') + expect(document?.content).toBe('') + }) + + it('marks a listing cut by the page cap so absent pages are not reconciled away', async () => { + const context: Record = {} + expect(await listAll({ ...config(), maxPages: '2' }, context)).toHaveLength(2) + expect(context.listingCapped).toBe(true) + const complete: Record = {} + await listAll({ ...config(), maxPages: '7' }, complete) + expect(complete.listingCapped).toBeUndefined() + }) + + it('fails the sync rather than guess when robots.txt or a listed sitemap cannot be read', async () => { + robotsStatus = 403 + await expect(listAll(config())).rejects.toThrow('status 403') + robotsStatus = 200 + missingChild = true + await expect(listAll(config())).rejects.toThrow('unavailable') + }) + + it('refuses the site without its configured header, and reports why on validation', async () => { + await expect(websiteConnector.listDocuments('', config(), undefined, {})).rejects.toThrow('401') + expect(await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, config())).toEqual({ + valid: true, + }) + }) +}) diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts new file mode 100644 index 00000000000..e77b9ceab64 --- /dev/null +++ b/apps/sim/connectors/website/website.ts @@ -0,0 +1,258 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' +import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' +import { VALIDATE_RETRY_OPTIONS } from '@/lib/knowledge/documents/utils' +import type { ConnectorConfig, ExternalDocument, ExternalDocumentList } from '@/connectors/types' +import { + computeContentHash, + markSkipped, + parseTagDate, + sizeLimitSkipReason, +} from '@/connectors/utils' +import { + WEBSITE_DEFAULT_MAX_PAGES, + WEBSITE_MAX_PAGES_LIMIT, + websiteConnectorMeta, +} from '@/connectors/website/meta' +import { extractPageText } from '@/connectors/website/page' +import { ALLOW_ALL_ROBOTS, parseRobots } from '@/connectors/website/robots' +import { + fetchSiteResource, + parseRequestHeaders, + pathPatterns, + resolveSite, + siteUrl, +} from '@/connectors/website/site' +import { + discoverSitemapPages, + scopedPage, + type WebsitePage, + type WebsiteScope, +} from '@/connectors/website/sitemap' + +const logger = createLogger('WebsiteConnector') + +/** Documents returned per `listDocuments` call. */ +const DOCS_PER_PAGE = 50 + +/** Bytes read from one page; a larger page is recorded as skipped rather than truncated. */ +const PAGE_MAX_BYTES = 2 * 1024 * 1024 +const ROBOTS_MAX_BYTES = 512 * 1024 + +/** What one sync reads once and every page read reuses: the scope and its request headers. */ +interface WebsiteSession { + scope: WebsiteScope + headers: Record +} + +interface WebsiteListing { + pages: WebsitePage[] + byUrl: Map +} + +const SESSION_KEY = 'websiteSession' +const LISTING_KEY = 'websiteListing' + +function resolveMaxPages(value: unknown): number { + const parsed = Number(value) + if (!Number.isFinite(parsed) || parsed <= 0) return WEBSITE_DEFAULT_MAX_PAGES + return Math.min(Math.floor(parsed), WEBSITE_MAX_PAGES_LIMIT) +} + +/** + * The sync's scope, built once per sync: the site, its path rules and its robots.txt. A missing + * robots.txt allows everything; any other failure fails the sync, since guessing would either + * crawl what the site forbids or drop every page. + */ +async function openSession( + accessToken: string, + sourceConfig: Record, + syncContext?: Record, + retryOptions?: SecureFetchRetryOptions +): Promise { + const cached = syncContext?.[SESSION_KEY] as WebsiteSession | undefined + if (cached) return cached + const site = resolveSite(sourceConfig.siteUrl) + const headers = parseRequestHeaders(accessToken ?? '') + const robots = await fetchSiteResource( + `${site.origin}/robots.txt`, + site, + headers, + 'text/plain', + ROBOTS_MAX_BYTES, + retryOptions + ) + const session: WebsiteSession = { + headers, + scope: { + site, + robots: robots ? parseRobots(robots.body.toString('utf8')) : ALLOW_ALL_ROBOTS, + include: pathPatterns(sourceConfig.includePaths), + exclude: pathPatterns(sourceConfig.excludePaths), + }, + } + if (syncContext) syncContext[SESSION_KEY] = session + return session +} + +/** The configured sitemap URL, which must sit on the site's own host. */ +function configuredSitemap(value: unknown, scope: WebsiteScope): string | undefined { + const raw = typeof value === 'string' ? value.trim() : '' + if (!raw) return undefined + const url = siteUrl(raw, `${scope.site.origin}/`, scope.site) + if (!url) throw new Error('Sitemap URL must be a URL on the website’s host') + return url.toString() +} + +/** + * The listing stub for a page. A sitemap `` is the change indicator, so an unchanged + * page is never fetched. Without one the hash names only the URL, which never equals a stored + * content hash: the page is fetched each sync and `getDocument`'s content hash decides whether + * anything is rewritten. + */ +function pageToStub(page: WebsitePage): ExternalDocument { + return { + externalId: page.url, + title: page.path === '/' ? page.url : page.path, + content: '', + contentDeferred: true, + mimeType: 'text/plain', + sourceUrl: page.url, + contentHash: page.lastModified + ? `website:${page.url}:${page.lastModified}` + : `website:${page.url}`, + metadata: { + section: page.path.split('/').filter(Boolean)[0], + lastModified: page.lastModified, + }, + } +} + +export const websiteConnector: ConnectorConfig = { + ...websiteConnectorMeta, + + listDocuments: async ( + accessToken: string, + sourceConfig: Record, + cursor?: string, + syncContext?: Record + ): Promise => { + let listing = syncContext?.[LISTING_KEY] as WebsiteListing | undefined + if (!listing) { + const { scope, headers } = await openSession(accessToken, sourceConfig, syncContext) + const maxPages = resolveMaxPages(sourceConfig.maxPages) + const { pages, truncated } = await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: maxPages, + }) + // An empty listing would reconcile every stored page away, so fail instead. + if (pages.length === 0) + throw new Error('No pages found in the site’s sitemaps within the configured scope') + if (truncated && syncContext) { + syncContext.listingCapped = true + logger.info('Website page listing capped', { listed: pages.length, maxPages }) + } + listing = { pages, byUrl: new Map(pages.map((page) => [page.url, page])) } + if (syncContext) syncContext[LISTING_KEY] = listing + } + const offset = cursor ? Number(cursor) : 0 + const slice = listing.pages.slice(offset, offset + DOCS_PER_PAGE) + const next = offset + slice.length + return { + documents: slice.map(pageToStub), + nextCursor: next < listing.pages.length ? String(next) : undefined, + hasMore: next < listing.pages.length, + } + }, + + getDocument: async ( + accessToken: string, + sourceConfig: Record, + externalId: string, + syncContext?: Record + ): Promise => { + const { scope, headers } = 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) + if (!page) return null + let resource: Awaited> + try { + resource = await fetchSiteResource( + page.url, + scope.site, + headers, + 'text/html, application/xhtml+xml;q=0.9', + PAGE_MAX_BYTES, + undefined, + (target) => scopedPage(target.toString(), scope) !== null + ) + } catch (error) { + if (!isPayloadSizeLimitError(error)) throw error + return markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES)) + } + if (!resource) return null + if (!/html/i.test(resource.contentType)) { + logger.info('Skipping a website resource that is not an HTML page', { + contentType: resource.contentType.slice(0, 100), + }) + return null + } + const { title, text, noindex } = extractPageText(resource.body.toString('utf8')) + if (noindex || !text.trim()) return null + 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)}`, + } + }, + + validateConfig: async ( + accessToken: string, + sourceConfig: Record + ): Promise<{ valid: boolean; error?: string }> => { + const rawMaxPages = sourceConfig.maxPages + if (rawMaxPages !== undefined && rawMaxPages !== null && rawMaxPages !== '') { + const parsed = Number(rawMaxPages) + if (!Number.isFinite(parsed) || parsed <= 0) + return { valid: false, error: 'Max Pages must be a positive number' } + } + try { + const { scope, headers } = await openSession( + accessToken, + sourceConfig, + undefined, + VALIDATE_RETRY_OPTIONS + ) + const { pages } = await discoverSitemapPages(scope, headers, { + configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope), + limit: 1, + retryOptions: VALIDATE_RETRY_OPTIONS, + }) + if (pages.length === 0) + return { + valid: false, + error: scope.robots.allows(scope.site.basePath || '/') + ? `No pages found in the sitemaps of ${scope.site.baseUrl} within the configured paths. The site must publish a sitemap.xml or declare one in robots.txt.` + : `robots.txt does not allow crawling ${scope.site.baseUrl}`, + } + return { valid: true } + } catch (error) { + return { valid: false, error: getErrorMessage(error, 'Failed to reach the website') } + } + }, + + mapTags: (metadata: Record): Record => { + const result: Record = {} + if (typeof metadata.section === 'string' && metadata.section) result.section = metadata.section + const lastModified = parseTagDate(metadata.lastModified) + if (lastModified) result.lastModified = lastModified + return result + }, +} diff --git a/apps/sim/lib/file-parsers/html-parser.ts b/apps/sim/lib/file-parsers/html-parser.ts index fc2793b4657..8bb44863dc6 100644 --- a/apps/sim/lib/file-parsers/html-parser.ts +++ b/apps/sim/lib/file-parsers/html-parser.ts @@ -136,15 +136,23 @@ function stripNonContent($: cheerio.CheerioAPI): void { * both formats produce the same shape. */ export function htmlToStructuredText(html: string): string { - const $ = cheerio.load(html) + return loadedHtmlToStructuredText(cheerio.load(html)) +} + +/** + * {@link htmlToStructuredText} for a document the caller already loaded, read from the first + * element `rootSelector` matches (the body by default), so a caller that inspects the page itself + * does not parse it twice. + */ +export function loadedHtmlToStructuredText($: cheerio.CheerioAPI, rootSelector = 'body'): string { stripNonContent($) - return extractStructuredText($) + return extractStructuredText($, rootSelector) } -function extractStructuredText($: cheerio.CheerioAPI): string { +function extractStructuredText($: cheerio.CheerioAPI, rootSelector: string): string { const contentParts: string[] = [] - const rootElement = $('body').length > 0 ? $('body') : $.root() + const rootElement = $(rootSelector).length > 0 ? $(rootSelector).first() : $.root() processElement($, rootElement, contentParts, 0) @@ -462,9 +470,7 @@ export class HtmlParser implements FileParser { const title = $('title').text().trim() const metaDescription = $('meta[name="description"]').attr('content') || '' - stripNonContent($) - - const content = extractStructuredText($) + const content = loadedHtmlToStructuredText($) const sanitizedContent = sanitizeTextForUTF8(content) From 84bce9298787dcdf4510f301e67d6bfdae0ebce4 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:21:21 -0800 Subject: [PATCH 2/9] fix(connectors): parse sitemaps with a streaming XML parser, pin the scheme, withdraw excluded pages, one request header --- apps/sim/connectors/website/meta.ts | 10 +-- apps/sim/connectors/website/robots.test.ts | 9 ++ apps/sim/connectors/website/robots.ts | 19 +++- apps/sim/connectors/website/site.test.ts | 31 ++++--- apps/sim/connectors/website/site.ts | 69 ++++++++------- apps/sim/connectors/website/sitemap.ts | 88 +++++++++++++------ .../connectors/website/website.integration.ts | 28 ++++-- apps/sim/connectors/website/website.ts | 44 ++++++---- 8 files changed, 197 insertions(+), 101 deletions(-) diff --git a/apps/sim/connectors/website/meta.ts b/apps/sim/connectors/website/meta.ts index 903e1c2eca2..70cc340f0db 100644 --- a/apps/sim/connectors/website/meta.ts +++ b/apps/sim/connectors/website/meta.ts @@ -15,14 +15,14 @@ export const websiteConnectorMeta: ConnectorMeta = { icon: WebsiteIcon, /** - * Public sites need nothing. A site behind a gateway that accepts a service credential, such as - * an API key header or a Cloudflare Access service token, takes up to two `Name: value` lines. - * Cookies are refused: a session cookie is a person's identity, and everything it unlocks would - * become readable to everyone with access to the knowledge base. + * Public sites need nothing. A site behind a gateway that accepts a service credential in one + * header, such as an API key, takes one `Name: value` line. Cookies are refused: a session cookie + * is a person's identity, and everything it unlocks would become readable to everyone with + * access to the knowledge base. */ auth: { mode: 'apiKey', - label: 'Request Headers', + label: 'Request Header', placeholder: 'Only for sites that require a service header, e.g. X-Api-Key: value', optional: true, }, diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts index 64692fcbaea..69b629dd343 100644 --- a/apps/sim/connectors/website/robots.test.ts +++ b/apps/sim/connectors/website/robots.test.ts @@ -51,4 +51,13 @@ describe('robots.txt rules for the website connector', () => { expect(robots.allows('/x')).toBe(true) expect(robots.sitemaps).toEqual(['https://example.com/a.xml']) }) + + it('matches rules and paths in one canonical encoding, so an escape cannot slip past a rule', () => { + const robots = parseRobots( + ['User-agent: *', 'Disallow: /private', 'Disallow: /café'].join('\n') + ) + expect(robots.allows('/%70rivate/salaries')).toBe(false) + expect(robots.allows('/caf%C3%A9/menu')).toBe(false) + expect(robots.allows('/a%2Fprivate')).toBe(true) + }) }) diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts index 694a3105017..43bf18c1838 100644 --- a/apps/sim/connectors/website/robots.ts +++ b/apps/sim/connectors/website/robots.ts @@ -15,6 +15,20 @@ export interface RobotsPolicy { sitemaps: string[] } +/** + * 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 + * non-ASCII characters percent-encoded. Reserved escapes such as `%2F` keep their meaning. + */ +export function normalizePath(value: string): string { + return value + .replace(/%([\da-f]{2})/gi, (encoded, hex: string) => { + const character = String.fromCharCode(Number.parseInt(hex, 16)) + return /[A-Za-z\d\-._~]/.test(character) ? character : encoded.toUpperCase() + }) + .replace(/[^\x00-\x7f]+/g, (characters) => encodeURIComponent(characters)) +} + /** A path pattern as regular expression source, where `*` matches any run of characters. */ export function wildcardSource(pattern: string): string { return pattern.split('*').map(escapeRegExp).join('.*') @@ -24,7 +38,7 @@ export function wildcardSource(pattern: string): string { function patternMatcher(pattern: string): RegExp { const anchored = pattern.endsWith('$') return new RegExp( - `^${wildcardSource(anchored ? pattern.slice(0, -1) : pattern)}${anchored ? '$' : ''}` + `^${wildcardSource(normalizePath(anchored ? pattern.slice(0, -1) : pattern))}${anchored ? '$' : ''}` ) } @@ -72,7 +86,8 @@ export function parseRobots(body: string): RobotsPolicy { ).flatMap((group) => group.rules) return { sitemaps, - allows(path) { + allows(rawPath) { + const path = normalizePath(rawPath) let decision: RobotsRule | undefined for (const rule of rules) { if (!rule.matcher.test(path)) continue diff --git a/apps/sim/connectors/website/site.test.ts b/apps/sim/connectors/website/site.test.ts index 46d48ed6e15..60bc67e43bf 100644 --- a/apps/sim/connectors/website/site.test.ts +++ b/apps/sim/connectors/website/site.test.ts @@ -1,12 +1,10 @@ import { describe, expect, it } from 'vitest' -import { parseRequestHeaders, pathPatterns, resolveSite } from '@/connectors/website/site' +import { parseRequestHeader, pathPatterns, resolveSite, siteUrl } from '@/connectors/website/site' -describe('website request headers', () => { - it('accepts up to two service headers', () => { - expect( - parseRequestHeaders('CF-Access-Client-Id: abc.access\nCF-Access-Client-Secret: s3cret') - ).toEqual({ 'cf-access-client-id': 'abc.access', 'cf-access-client-secret': 's3cret' }) - expect(parseRequestHeaders('')).toEqual({}) +describe('website request header', () => { + it('accepts one service header, or none', () => { + expect(parseRequestHeader(' X-Api-Key: s3cret ')).toEqual({ 'x-api-key': 's3cret' }) + expect(parseRequestHeader('')).toEqual({}) }) it.each([ @@ -15,10 +13,9 @@ describe('website request headers', () => { ['a proxy credential', 'Proxy-Authorization: Basic abc', 'cannot be configured'], ['a value carrying control characters', 'X-Api-Key: abc\u0000def', 'Name: value'], ['a line without a name', ': value', 'Name: value'], - ['more than two headers', 'A: 1\nB: 2\nC: 3', 'at most 2'], - ['a repeated header', 'X-Key: 1\nx-key: 2', 'configured twice'], + ['a second header line', 'A: 1\nB: 2', 'Name: value'], ])('refuses %s', (_case, credential, reason) => { - expect(() => parseRequestHeaders(credential)).toThrow(reason) + expect(() => parseRequestHeader(credential)).toThrow(reason) }) }) @@ -28,6 +25,10 @@ describe('website scope', () => { expect(matches?.('/benefits')).toBe(true) expect(matches?.('/benefits/medical')).toBe(true) expect(matches?.('/benefits-archive')).toBe(false) + const [root] = pathPatterns('/') + expect(root?.('/anything')).toBe(true) + const [encoded] = pathPatterns('/café') + expect(encoded?.('/caf%C3%A9/menu')).toBe(true) const [wildcard] = pathPatterns('/help/*/faq') expect(wildcard?.('/help/hr/faq/leave')).toBe(true) expect(wildcard?.('/help/faq')).toBe(false) @@ -42,4 +43,14 @@ describe('website scope', () => { hostKey: 'example.com', }) }) + + it('never takes an HTTPS site’s requests to plain HTTP, but follows HTTP sites up to HTTPS', () => { + const secure = resolveSite('https://example.com') + expect(siteUrl('http://example.com/sitemap.xml', 'https://example.com/', secure)).toBeNull() + expect(siteUrl('/sitemap.xml', 'https://www.example.com/', secure)?.href).toBe( + 'https://www.example.com/sitemap.xml' + ) + const plain = { ...secure, origin: 'http://example.com', protocol: 'http:' } + expect(siteUrl('https://example.com/a', 'http://example.com/', plain)).not.toBeNull() + }) }) diff --git a/apps/sim/connectors/website/site.ts b/apps/sim/connectors/website/site.ts index 7381dd3fac7..626ca4eebb0 100644 --- a/apps/sim/connectors/website/site.ts +++ b/apps/sim/connectors/website/site.ts @@ -3,11 +3,13 @@ import { type SecureFetchRetryOptions, secureFetchWithRetry, } from '@/lib/knowledge/documents/secure-fetch.server' -import { WEBSITE_CRAWLER_TOKEN, wildcardSource } from '@/connectors/website/robots' +import { normalizePath, WEBSITE_CRAWLER_TOKEN, wildcardSource } from '@/connectors/website/robots' /** The configured site: its origin, the path pages must sit under, and the host it may reach. */ export interface WebsiteSite { origin: string + /** `https:` or `http:`; an HTTPS site never sends its headers over plain HTTP. */ + protocol: string /** Configured URL without a trailing slash, e.g. `https://example.com/help`. */ baseUrl: string /** Path pages must sit under, without a trailing slash; `''` at the host root. */ @@ -34,16 +36,17 @@ export function resolveSite(rawUrl: unknown): WebsiteSite { throw new Error('Website URL must not contain credentials') return { origin: parsed.origin, + protocol: parsed.protocol, baseUrl: `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`, basePath: parsed.pathname.replace(/\/+$/, ''), hostKey: parsed.hostname.replace(/^www\./, '').toLowerCase(), } } -/** Whether a URL is an http(s) URL on the configured site's host. */ -export function onSiteHost(url: URL, site: WebsiteSite): boolean { +/** Whether a URL is on the configured site's host, over its scheme or an upgrade to HTTPS. */ +function onSiteHost(url: URL, site: WebsiteSite): boolean { return ( - (url.protocol === 'https:' || url.protocol === 'http:') && + (url.protocol === site.protocol || (site.protocol === 'http:' && url.protocol === 'https:')) && !url.username && !url.password && url.hostname.replace(/^www\./, '').toLowerCase() === site.hostKey @@ -73,10 +76,12 @@ export function pathPatterns(value: unknown): ((path: string) => boolean)[] { if (typeof value !== 'string') return [] return value .split(',') - .map((part) => part.trim().replace(/\/+$/, '')) + .map((part) => part.trim()) .filter(Boolean) .map((pattern) => { - const prefix = pattern.startsWith('/') ? pattern : `/${pattern}` + const prefix = normalizePath( + (pattern.startsWith('/') ? pattern : `/${pattern}`).replace(/\/+$/, '') + ) if (!prefix.includes('*')) return (path: string) => isUnderPath(path, prefix) const matcher = new RegExp(`^${wildcardSource(prefix)}(?:/.*)?$`) return (path: string) => matcher.test(path) @@ -102,35 +107,29 @@ const RESERVED_HEADERS = new Set([ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ /** Visible ASCII and spaces; anything else could smuggle a second header or a request line. */ const HEADER_VALUE = /^[\x20-\x7e]*$/ -const MAX_CONFIGURED_HEADERS = 2 /** - * The request headers a configured credential names, one `Name: value` per line. Throws on a - * malformed line, a reserved header, or more than two headers. + * The request header a configured credential names, as one `Name: value` line; an empty + * credential names none. Throws on a malformed or reserved header, or on more than one line. */ -export function parseRequestHeaders(credential: string): Record { - const headers: Record = {} - const lines = credential - .split(/\r?\n/) - .map((line) => line.trim()) - .filter(Boolean) - if (lines.length > MAX_CONFIGURED_HEADERS) - throw new Error(`Configure at most ${MAX_CONFIGURED_HEADERS} request headers`) - for (const line of lines) { - const separator = line.indexOf(':') - const name = separator > 0 ? line.slice(0, separator).trim() : '' - const value = separator > 0 ? line.slice(separator + 1).trim() : '' - if (!HEADER_NAME.test(name) || !value || !HEADER_VALUE.test(value)) - throw new Error('Request headers must be "Name: value" lines') - const key = name.toLowerCase() - if (RESERVED_HEADERS.has(key) || key.startsWith('proxy-') || key.startsWith('sec-')) - throw new Error(`The ${name} header cannot be configured`) - if (Object.hasOwn(headers, key)) throw new Error(`The ${name} header is configured twice`) - headers[key] = value - } - return headers +export function parseRequestHeader(credential: string): Record { + const line = credential.trim() + if (!line) return {} + const separator = line.indexOf(':') + const name = separator > 0 ? line.slice(0, separator).trim() : '' + const value = separator > 0 ? line.slice(separator + 1).trim() : '' + if (!HEADER_NAME.test(name) || !value || !HEADER_VALUE.test(value)) + throw new Error('The request header must be one "Name: value" line') + const key = name.toLowerCase() + if (RESERVED_HEADERS.has(key) || key.startsWith('proxy-') || key.startsWith('sec-')) + throw new Error(`The ${name} header cannot be configured`) + return { [key]: value } } +/** Per-attempt and whole-request deadlines, so a stalled host cannot hold a sync. */ +const ATTEMPT_TIMEOUT_MS = 30_000 +const REQUEST_DEADLINE_MS = 120_000 + /** * Fetches a resource on the configured site, or `null` when it does not exist (404 or 410). A * redirect is refused before it is followed unless it stays on the site's host and, for a page, @@ -146,11 +145,13 @@ export async function fetchSiteResource( retryOptions?: SecureFetchRetryOptions, allowsTarget?: (target: URL) => boolean ): Promise<{ body: Buffer; contentType: string } | null> { + const deadline = AbortSignal.timeout(REQUEST_DEADLINE_MS) const response = await secureFetchWithRetry( url, { profile: 'configuredEndpoint', method: 'GET', + signal: deadline, headers: { ...headers, Accept: accept, 'User-Agent': `${WEBSITE_CRAWLER_TOKEN}/1.0` }, assertRedirectTarget: (target) => { const next = new URL(target) @@ -159,7 +160,13 @@ export async function fetchSiteResource( throw new Error(`The site redirected ${url} outside the configured scope`) }, }, - { ...retryOptions, maxResponseBytes: maxBytes } + { + timeout: ATTEMPT_TIMEOUT_MS, + retryBudgetMs: REQUEST_DEADLINE_MS, + ...retryOptions, + signal: deadline, + maxResponseBytes: maxBytes, + } ) if (response.status === 404 || response.status === 410) return null if (!response.ok) throw new Error(`The site returned status ${response.status} for ${url}`) diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts index 4c76a53101d..91accb29d12 100644 --- a/apps/sim/connectors/website/sitemap.ts +++ b/apps/sim/connectors/website/sitemap.ts @@ -1,6 +1,6 @@ import { gunzipSync } from 'node:zlib' +import { Parser } from 'htmlparser2' import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' -import { decodeHtmlEntities } from '@/connectors/utils' import type { RobotsPolicy } from '@/connectors/website/robots' import { fetchSiteResource, @@ -57,28 +57,56 @@ export interface WebsiteScope { exclude: ((path: string) => boolean)[] } -const ENTRY_PATTERN = /<(url|sitemap)\b[^>]*>([\s\S]*?)<\/\1\s*>/gi -const LOC_PATTERN = /\s*([^<]+?)\s*<\/loc>/i -const LASTMOD_PATTERN = /\s*([^<]+?)\s*<\/lastmod>/i - interface SitemapEntry { kind: 'url' | 'sitemap' loc: string lastmod?: string } -function sitemapEntries(xml: string): SitemapEntry[] { +/** An element's name without its namespace prefix, e.g. `sm:loc` → `loc`. */ +const localName = (name: string) => name.slice(name.indexOf(':') + 1).toLowerCase() + +/** + * The entries of a sitemap or sitemap index, read in one linear pass with a streaming XML parser, + * so CDATA, entities and namespace prefixes are handled and a malformed document cannot cost more + * than its length. `null` when the document is not a sitemap at all (an HTML error page, say). + */ +function sitemapEntries(xml: string): SitemapEntry[] | null { const entries: SitemapEntry[] = [] - for (const match of xml.matchAll(ENTRY_PATTERN)) { - const loc = LOC_PATTERN.exec(match[2])?.[1] - if (!loc) continue - entries.push({ - kind: match[1].toLowerCase() === 'sitemap' ? 'sitemap' : 'url', - loc: decodeHtmlEntities(loc), - lastmod: LASTMOD_PATTERN.exec(match[2])?.[1], - }) - } - return entries + let root: string | undefined + let entry: SitemapEntry | undefined + let field: 'loc' | 'lastmod' | undefined + let text = '' + const parser = new Parser( + { + onopentag(name) { + const element = localName(name) + root ??= element + if (element === 'url' || element === 'sitemap') entry = { kind: element, loc: '' } + else if (entry && (element === 'loc' || element === 'lastmod')) { + field = element + text = '' + } + }, + ontext(data) { + if (field) text += data + }, + onclosetag(name) { + const element = localName(name) + if (entry && field && element === field) { + entry[field] = text.trim() + field = undefined + } else if (entry && element === entry.kind) { + if (entry.loc) entries.push(entry) + entry = undefined + } + }, + }, + { xmlMode: true, decodeEntities: true, recognizeCDATA: true } + ) + parser.write(xml) + parser.end() + return root === 'urlset' || root === 'sitemapindex' ? entries : null } /** The page a sitemap location names, when it is a page within the configured scope. */ @@ -119,17 +147,23 @@ async function readSitemap( /** * The sitemaps discovery starts from: a configured one, else those robots.txt declares on this - * host, else the conventional `sitemap.xml` under the configured path and at the host root. + * host, else the conventional `sitemap.xml` under the configured path and at the host root. A + * configured or declared sitemap must exist; only a guessed location may be missing. */ -function rootSitemaps(scope: WebsiteScope, configured?: string): string[] { +function rootSitemaps( + scope: WebsiteScope, + configured?: string +): { url: string; required: boolean }[] { const { site } = scope - if (configured) return [configured] + if (configured) return [{ url: configured, required: true }] const declared = scope.robots.sitemaps.flatMap((location) => { const url = siteUrl(location, `${site.origin}/`, site) return url ? [url.toString()] : [] }) - if (declared.length) return [...new Set(declared)] - return [...new Set([`${site.baseUrl}/sitemap.xml`, `${site.origin}/sitemap.xml`])] + const guessed = !declared.length + return [ + ...new Set(guessed ? [`${site.baseUrl}/sitemap.xml`, `${site.origin}/sitemap.xml`] : declared), + ].map((url) => ({ url, required: !guessed })) } /** @@ -145,10 +179,7 @@ export async function discoverSitemapPages( ): Promise { const { site } = scope const pages = new Map() - const queue = rootSitemaps(scope, configuredSitemap).map((url) => ({ - url, - required: Boolean(configuredSitemap), - })) + const queue = rootSitemaps(scope, configuredSitemap) const visited = new Set() let truncated = false let documents = 0 @@ -161,11 +192,12 @@ export async function discoverSitemapPages( `The site's sitemaps span more than ${MAX_SITEMAP_DOCUMENTS} documents. Configure a sitemap URL that lists the pages to sync.` ) const xml = await readSitemap(next.url, site, headers, retryOptions) - if (xml === null) { - if (next.required) throw new Error(`Sitemap ${next.url} is unavailable`) + const entries = xml === null ? null : sitemapEntries(xml) + if (entries === null) { + if (next.required) throw new Error(`Sitemap ${next.url} is unavailable or not a sitemap`) continue } - for (const entry of sitemapEntries(xml)) { + for (const entry of entries) { if (entry.kind === 'sitemap') { const child = siteUrl(entry.loc, next.url, site) if (child) queue.push({ url: child.toString(), required: true }) diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index 1265a7a216e..4a77a6995a0 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -15,6 +15,7 @@ let foreign = '' let foreignRequests: IncomingMessage[] = [] let robotsStatus = 200 let missingChild = false +let missingIndex = false let faqBody = '

Original answer.

' function listen(server: Server, host: string): Promise { @@ -45,6 +46,7 @@ const siteServer = createServer((request, response) => { `User-agent: *\nDisallow: /private\nSitemap: ${site}/sitemap-index.xml\n` ) case '/sitemap-index.xml': + if (missingIndex) return send(404, 'text/plain', '') return send( 200, 'application/xml', @@ -71,7 +73,9 @@ const siteServer = createServer((request, response) => { return send( 200, 'application/gzip', - gzipSync(`${site}/faq`) + gzipSync( + `` + ) ) case '/benefits': return send( @@ -128,6 +132,7 @@ beforeEach(() => { foreignRequests = [] robotsStatus = 200 missingChild = false + missingIndex = false faqBody = '

Original answer.

' }) @@ -197,11 +202,16 @@ describe('website connector over real HTTP', () => { expect((await read())?.contentHash).not.toBe(first?.contentHash) }) - it('drops pages that are gone, ask not to be indexed, or robots.txt forbids', async () => { - for (const path of ['/gone', '/hidden', '/private/salaries']) - expect( - await websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}${path}`, {}) - ).toBeNull() + it('withdraws pages that are gone or ask not to be indexed, and never reads disallowed ones', async () => { + const read = (path: string) => + websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}${path}`, {}) + for (const path of ['/gone', '/hidden']) + expect(await read(path)).toMatchObject({ + content: '', + skippedReason: expect.any(String), + skippedExistingDisposition: 'replace', + }) + expect(await read('/private/salaries')).toBeNull() }) it('refuses a redirect off the site or out of scope before it is followed', async () => { @@ -240,6 +250,9 @@ describe('website connector over real HTTP', () => { robotsStatus = 200 missingChild = true await expect(listAll(config())).rejects.toThrow('unavailable') + missingChild = false + missingIndex = true + await expect(listAll(config())).rejects.toThrow('unavailable') }) it('refuses the site without its configured header, and reports why on validation', async () => { @@ -247,5 +260,8 @@ describe('website connector over real HTTP', () => { expect(await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, config())).toEqual({ valid: true, }) + expect( + await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, { ...config(), maxPages: '0.5' }) + ).toMatchObject({ valid: false }) }) }) diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index e77b9ceab64..b92ea6b4f40 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -19,7 +19,7 @@ import { extractPageText } from '@/connectors/website/page' import { ALLOW_ALL_ROBOTS, parseRobots } from '@/connectors/website/robots' import { fetchSiteResource, - parseRequestHeaders, + parseRequestHeader, pathPatterns, resolveSite, siteUrl, @@ -54,10 +54,23 @@ interface WebsiteListing { const SESSION_KEY = 'websiteSession' const LISTING_KEY = 'websiteListing' -function resolveMaxPages(value: unknown): number { +/** The configured page cap: a positive whole number, `undefined` when unset, `null` when invalid. */ +function parseMaxPages(value: unknown): number | null | undefined { + if (value === undefined || value === null || value === '') return undefined const parsed = Number(value) - if (!Number.isFinite(parsed) || parsed <= 0) return WEBSITE_DEFAULT_MAX_PAGES - return Math.min(Math.floor(parsed), WEBSITE_MAX_PAGES_LIMIT) + return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null +} + +function resolveMaxPages(value: unknown): number { + return Math.min(parseMaxPages(value) ?? WEBSITE_DEFAULT_MAX_PAGES, WEBSITE_MAX_PAGES_LIMIT) +} + +/** + * 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. + */ +function withdrawn(page: WebsitePage, reason: string): ExternalDocument { + return { ...markSkipped(pageToStub(page), reason), skippedExistingDisposition: 'replace' } } /** @@ -74,7 +87,7 @@ async function openSession( const cached = syncContext?.[SESSION_KEY] as WebsiteSession | undefined if (cached) return cached const site = resolveSite(sourceConfig.siteUrl) - const headers = parseRequestHeaders(accessToken ?? '') + const headers = parseRequestHeader(accessToken ?? '') const robots = await fetchSiteResource( `${site.origin}/robots.txt`, site, @@ -192,15 +205,12 @@ export const websiteConnector: ConnectorConfig = { if (!isPayloadSizeLimitError(error)) throw error return markSkipped(pageToStub(page), sizeLimitSkipReason(PAGE_MAX_BYTES)) } - if (!resource) return null - if (!/html/i.test(resource.contentType)) { - logger.info('Skipping a website resource that is not an HTML page', { - contentType: resource.contentType.slice(0, 100), - }) - return null - } + if (!resource) return withdrawn(page, 'The page no longer exists on the site') + if (!/html/i.test(resource.contentType)) + return withdrawn(page, 'The URL serves a file, not an HTML page') const { title, text, noindex } = extractPageText(resource.body.toString('utf8')) - if (noindex || !text.trim()) return null + 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, @@ -217,12 +227,8 @@ export const websiteConnector: ConnectorConfig = { accessToken: string, sourceConfig: Record ): Promise<{ valid: boolean; error?: string }> => { - const rawMaxPages = sourceConfig.maxPages - if (rawMaxPages !== undefined && rawMaxPages !== null && rawMaxPages !== '') { - const parsed = Number(rawMaxPages) - if (!Number.isFinite(parsed) || parsed <= 0) - return { valid: false, error: 'Max Pages must be a positive number' } - } + if (parseMaxPages(sourceConfig.maxPages) === null) + return { valid: false, error: 'Max Pages must be a positive whole number' } try { const { scope, headers } = await openSession( accessToken, From 8b81e2f379c3bb5336d02823470a8d9e472d44ab Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:33:28 -0800 Subject: [PATCH 3/9] fix(connectors): read only an entry's own sitemap location, reject malformed sitemaps, match robots in linear time, pin the port --- apps/sim/connectors/website/robots.test.ts | 7 ++ apps/sim/connectors/website/robots.ts | 43 ++++++--- apps/sim/connectors/website/site.test.ts | 1 + apps/sim/connectors/website/site.ts | 20 +++-- apps/sim/connectors/website/sitemap.test.ts | 20 +++++ apps/sim/connectors/website/sitemap.ts | 89 ++++++++++++------- .../connectors/website/website.integration.ts | 65 ++++++++++---- 7 files changed, 178 insertions(+), 67 deletions(-) create mode 100644 apps/sim/connectors/website/sitemap.test.ts diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts index 69b629dd343..673b75b741f 100644 --- a/apps/sim/connectors/website/robots.test.ts +++ b/apps/sim/connectors/website/robots.test.ts @@ -60,4 +60,11 @@ describe('robots.txt rules for the website connector', () => { expect(robots.allows('/caf%C3%A9/menu')).toBe(false) expect(robots.allows('/a%2Fprivate')).toBe(true) }) + + it('matches a pathological wildcard rule against a long path in linear time', () => { + const robots = parseRobots(`User-agent: *\nDisallow: /${'*a'.repeat(40)}b\n`) + const started = performance.now() + expect(robots.allows(`/${'a'.repeat(20_000)}`)).toBe(true) + expect(performance.now() - started).toBeLessThan(1000) + }) }) diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts index 43bf18c1838..701b40f8ede 100644 --- a/apps/sim/connectors/website/robots.ts +++ b/apps/sim/connectors/website/robots.ts @@ -1,12 +1,10 @@ -import { escapeRegExp } from '@sim/utils/string' - /** The product token the connector sends and honors robots.txt groups for. */ export const WEBSITE_CRAWLER_TOKEN = 'SimBot' interface RobotsRule { allow: boolean pattern: string - matcher: RegExp + matches: (path: string) => boolean } /** A site's robots.txt as it applies to this crawler, plus the sitemaps it declares. */ @@ -29,17 +27,36 @@ export function normalizePath(value: string): string { .replace(/[^\x00-\x7f]+/g, (characters) => encodeURIComponent(characters)) } -/** A path pattern as regular expression source, where `*` matches any run of characters. */ -export function wildcardSource(pattern: string): string { - return pattern.split('*').map(escapeRegExp).join('.*') +/** + * Where a match of `pattern` against the start of `path` ends, or -1: `*` matches any run of + * characters, and `anchored` requires the match to end where the path does. Each segment between + * wildcards is found by one forward search from where the last ended, so the cost is linear in + * the path however a site writes its patterns; a backtracking regular expression is not. + */ +export function matchWildcard(pattern: string, path: string, anchored: boolean): number { + const segments = pattern.split('*') + const first = segments[0] ?? '' + if (!path.startsWith(first)) return -1 + if (segments.length === 1) return !anchored || path.length === first.length ? first.length : -1 + let position = first.length + for (const segment of segments.slice(1, -1)) { + const found = path.indexOf(segment, position) + if (found === -1) return -1 + position = found + segment.length + } + const last = segments[segments.length - 1] ?? '' + if (!anchored) { + const found = path.indexOf(last, position) + return found === -1 ? -1 : found + last.length + } + return path.length - last.length >= position && path.endsWith(last) ? path.length : -1 } -/** A robots.txt path pattern as a regular expression: `*` matches anything, a final `$` anchors. */ -function patternMatcher(pattern: string): RegExp { +/** A robots.txt path pattern as a test: `*` matches anything, a final `$` anchors the end. */ +function patternMatcher(pattern: string): (path: string) => boolean { const anchored = pattern.endsWith('$') - return new RegExp( - `^${wildcardSource(normalizePath(anchored ? pattern.slice(0, -1) : pattern))}${anchored ? '$' : ''}` - ) + const body = normalizePath(anchored ? pattern.slice(0, -1) : pattern) + return (path) => matchWildcard(body, path, anchored) !== -1 } /** @@ -76,7 +93,7 @@ export function parseRobots(body: string): RobotsPolicy { current.rules.push({ allow: field === 'allow', pattern: value, - matcher: patternMatcher(value), + matches: patternMatcher(value), }) } const token = WEBSITE_CRAWLER_TOKEN.toLowerCase() @@ -90,7 +107,7 @@ export function parseRobots(body: string): RobotsPolicy { const path = normalizePath(rawPath) let decision: RobotsRule | undefined for (const rule of rules) { - if (!rule.matcher.test(path)) continue + if (!rule.matches(path)) continue if ( !decision || rule.pattern.length > decision.pattern.length || diff --git a/apps/sim/connectors/website/site.test.ts b/apps/sim/connectors/website/site.test.ts index 60bc67e43bf..02cfe7c562d 100644 --- a/apps/sim/connectors/website/site.test.ts +++ b/apps/sim/connectors/website/site.test.ts @@ -50,6 +50,7 @@ describe('website scope', () => { expect(siteUrl('/sitemap.xml', 'https://www.example.com/', secure)?.href).toBe( 'https://www.example.com/sitemap.xml' ) + expect(siteUrl('https://example.com:8443/admin', 'https://example.com/', secure)).toBeNull() const plain = { ...secure, origin: 'http://example.com', protocol: 'http:' } expect(siteUrl('https://example.com/a', 'http://example.com/', plain)).not.toBeNull() }) diff --git a/apps/sim/connectors/website/site.ts b/apps/sim/connectors/website/site.ts index 626ca4eebb0..c02faa4b263 100644 --- a/apps/sim/connectors/website/site.ts +++ b/apps/sim/connectors/website/site.ts @@ -3,13 +3,15 @@ import { type SecureFetchRetryOptions, secureFetchWithRetry, } from '@/lib/knowledge/documents/secure-fetch.server' -import { normalizePath, WEBSITE_CRAWLER_TOKEN, wildcardSource } from '@/connectors/website/robots' +import { matchWildcard, normalizePath, WEBSITE_CRAWLER_TOKEN } from '@/connectors/website/robots' /** The configured site: its origin, the path pages must sit under, and the host it may reach. */ export interface WebsiteSite { origin: string /** `https:` or `http:`; an HTTPS site never sends its headers over plain HTTP. */ protocol: string + /** The explicit port, `''` for the scheme's default; requests never move to another port. */ + port: string /** Configured URL without a trailing slash, e.g. `https://example.com/help`. */ baseUrl: string /** Path pages must sit under, without a trailing slash; `''` at the host root. */ @@ -37,16 +39,22 @@ export function resolveSite(rawUrl: unknown): WebsiteSite { return { origin: parsed.origin, protocol: parsed.protocol, + port: parsed.port, baseUrl: `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`, - basePath: parsed.pathname.replace(/\/+$/, ''), + basePath: normalizePath(parsed.pathname).replace(/\/+$/, ''), hostKey: parsed.hostname.replace(/^www\./, '').toLowerCase(), } } -/** Whether a URL is on the configured site's host, over its scheme or an upgrade to HTTPS. */ +/** + * Whether a URL is on the configured site: its host and port over its scheme, or the same host + * upgraded from HTTP on the default port to HTTPS on the default port. + */ function onSiteHost(url: URL, site: WebsiteSite): boolean { + const sameService = url.protocol === site.protocol && url.port === site.port + const upgraded = site.protocol === 'http:' && !site.port && url.protocol === 'https:' && !url.port return ( - (url.protocol === site.protocol || (site.protocol === 'http:' && url.protocol === 'https:')) && + (sameService || upgraded) && !url.username && !url.password && url.hostname.replace(/^www\./, '').toLowerCase() === site.hostKey @@ -83,8 +91,8 @@ export function pathPatterns(value: unknown): ((path: string) => boolean)[] { (pattern.startsWith('/') ? pattern : `/${pattern}`).replace(/\/+$/, '') ) if (!prefix.includes('*')) return (path: string) => isUnderPath(path, prefix) - const matcher = new RegExp(`^${wildcardSource(prefix)}(?:/.*)?$`) - return (path: string) => matcher.test(path) + return (path: string) => + matchWildcard(prefix, path, true) !== -1 || matchWildcard(`${prefix}/`, path, false) !== -1 }) } diff --git a/apps/sim/connectors/website/sitemap.test.ts b/apps/sim/connectors/website/sitemap.test.ts new file mode 100644 index 00000000000..90181f09c68 --- /dev/null +++ b/apps/sim/connectors/website/sitemap.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { ALLOW_ALL_ROBOTS } from '@/connectors/website/robots' +import { pathPatterns, resolveSite } from '@/connectors/website/site' +import { scopedPage } from '@/connectors/website/sitemap' + +describe('website page scope', () => { + it('applies path rules to one canonical spelling of the path, however either is escaped', () => { + const scope = (exclude: string) => ({ + site: resolveSite('https://example.com'), + robots: ALLOW_ALL_ROBOTS, + include: [], + exclude: pathPatterns(exclude), + }) + expect(scopedPage('https://example.com/private/x', scope('/%70rivate'))).toBeNull() + expect(scopedPage('https://example.com/%70rivate/x', scope('/private'))).toBeNull() + expect(scopedPage('https://example.com/%70ublic/x', scope('/private'))).toMatchObject({ + path: '/public/x', + }) + }) +}) diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts index 91accb29d12..7b95e331e02 100644 --- a/apps/sim/connectors/website/sitemap.ts +++ b/apps/sim/connectors/website/sitemap.ts @@ -1,7 +1,7 @@ import { gunzipSync } from 'node:zlib' import { Parser } from 'htmlparser2' import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' -import type { RobotsPolicy } from '@/connectors/website/robots' +import { normalizePath, type RobotsPolicy } from '@/connectors/website/robots' import { fetchSiteResource, isUnderPath, @@ -66,47 +66,76 @@ interface SitemapEntry { /** An element's name without its namespace prefix, e.g. `sm:loc` → `loc`. */ const localName = (name: string) => name.slice(name.indexOf(':') + 1).toLowerCase() +/** A W3C datetime as sitemaps write ``: a date, optionally with a time and zone. */ +const W3C_DATETIME = + /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2}))?$/ + +/** A `` as an ISO timestamp, when it is a valid W3C datetime naming a real date. */ +function lastModified(value: string | undefined): string | undefined { + if (!value || !W3C_DATETIME.test(value)) return undefined + // `Date` rolls 2026-02-30 over to March; a calendar date that does not round-trip is invalid. + const day = new Date(`${value.slice(0, 10)}T00:00:00Z`) + if (Number.isNaN(day.getTime()) || day.toISOString().slice(0, 10) !== value.slice(0, 10)) + return undefined + const parsed = new Date(value) + return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString() +} + /** * The entries of a sitemap or sitemap index, read in one linear pass with a streaming XML parser, * so CDATA, entities and namespace prefixes are handled and a malformed document cannot cost more - * than its length. `null` when the document is not a sitemap at all (an HTML error page, say). + * than its length. Only an entry's own `` and `` count, never those of extensions + * nested inside it such as ``. `null` when the document is not a complete sitemap: an + * HTML page, another document, or one cut off or left unbalanced. */ function sitemapEntries(xml: string): SitemapEntry[] | null { const entries: SitemapEntry[] = [] let root: string | undefined - let entry: SitemapEntry | undefined - let field: 'loc' | 'lastmod' | undefined + let depth = 0 + let closed = false + let implied = false + let entry: { value: SitemapEntry; depth: number } | undefined + let field: { name: 'loc' | 'lastmod'; depth: number } | undefined let text = '' const parser = new Parser( { onopentag(name) { const element = localName(name) - root ??= element - if (element === 'url' || element === 'sitemap') entry = { kind: element, loc: '' } - else if (entry && (element === 'loc' || element === 'lastmod')) { - field = element + depth++ + if (depth === 1) root = element + if (depth === 2 && (element === 'url' || element === 'sitemap')) + entry = { value: { kind: element, loc: '' }, depth } + else if ( + entry && + depth === entry.depth + 1 && + (element === 'loc' || element === 'lastmod') + ) { + field = { name: element, depth } text = '' } }, ontext(data) { if (field) text += data }, - onclosetag(name) { - const element = localName(name) - if (entry && field && element === field) { - entry[field] = text.trim() + onclosetag(_name, isImplied) { + // The parser closes what a cut-off or unbalanced document left open; that is not a sitemap. + implied ||= isImplied + if (field && depth === field.depth) { + if (entry) entry.value[field.name] = text.trim() field = undefined - } else if (entry && element === entry.kind) { - if (entry.loc) entries.push(entry) + } else if (entry && depth === entry.depth) { + if (entry.value.loc) entries.push(entry.value) entry = undefined } + depth-- + if (depth === 0) closed = true }, }, { xmlMode: true, decodeEntities: true, recognizeCDATA: true } ) parser.write(xml) parser.end() - return root === 'urlset' || root === 'sitemapindex' ? entries : null + return closed && !implied && (root === 'urlset' || root === 'sitemapindex') ? entries : null } /** The page a sitemap location names, when it is a page within the configured scope. */ @@ -114,7 +143,7 @@ export function scopedPage(location: string, scope: WebsiteScope): WebsitePage | const url = siteUrl(location, `${scope.site.origin}/`, scope.site) if (!url) return null url.hash = '' - const path = url.pathname.replace(/\/+$/, '') || '/' + const path = normalizePath(url.pathname).replace(/\/+$/, '') || '/' if (NON_PAGE_PATH.test(path) || !isUnderPath(path, scope.site.basePath)) return null if (scope.include.length && !scope.include.some((matches) => matches(path))) return null if (scope.exclude.some((matches) => matches(path))) return null @@ -127,7 +156,7 @@ async function readSitemap( site: WebsiteSite, headers: Record, retryOptions?: SecureFetchRetryOptions -): Promise { +): Promise<{ xml: string; html: boolean } | null> { const resource = await fetchSiteResource( url, site, @@ -138,11 +167,13 @@ async function readSitemap( ) if (!resource) return null const gzipped = resource.body[0] === 0x1f && resource.body[1] === 0x8b - return ( - gzipped + return { + xml: (gzipped ? gunzipSync(resource.body, { maxOutputLength: SITEMAP_MAX_DECOMPRESSED_BYTES }) : resource.body - ).toString('utf8') + ).toString('utf8'), + html: /html/i.test(resource.contentType), + } } /** @@ -191,11 +222,12 @@ export async function discoverSitemapPages( throw new Error( `The site's sitemaps span more than ${MAX_SITEMAP_DOCUMENTS} documents. Configure a sitemap URL that lists the pages to sync.` ) - const xml = await readSitemap(next.url, site, headers, retryOptions) - const entries = xml === null ? null : sitemapEntries(xml) + const sitemap = await readSitemap(next.url, site, headers, retryOptions) + const entries = sitemap === null ? null : sitemapEntries(sitemap.xml) if (entries === null) { - if (next.required) throw new Error(`Sitemap ${next.url} is unavailable or not a sitemap`) - continue + /** A guessed location may be absent, or a page the site serves for any unknown path. */ + if (!next.required && (sitemap === null || sitemap.html)) continue + throw new Error(`Sitemap ${next.url} is unavailable or not a valid sitemap`) } for (const entry of entries) { if (entry.kind === 'sitemap') { @@ -209,13 +241,8 @@ export async function discoverSitemapPages( truncated = true break } - const lastModified = Date.parse(entry.lastmod ?? '') - pages.set(page.url, { - ...page, - ...(Number.isFinite(lastModified) - ? { lastModified: new Date(lastModified).toISOString() } - : {}), - }) + const modified = lastModified(entry.lastmod) + pages.set(page.url, { ...page, ...(modified ? { lastModified: modified } : {}) }) } } return { pages: [...pages.values()], truncated } diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index 4a77a6995a0..61121052c8e 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -16,6 +16,8 @@ let foreignRequests: IncomingMessage[] = [] let robotsStatus = 200 let missingChild = false let missingIndex = false +let truncatedPages = false +let undeclared: 'html' | 'text' | undefined let faqBody = '

Original answer.

' function listen(server: Server, host: string): Promise { @@ -43,8 +45,12 @@ const siteServer = createServer((request, response) => { return send( 200, 'text/plain', - `User-agent: *\nDisallow: /private\nSitemap: ${site}/sitemap-index.xml\n` + `User-agent: *\nDisallow: /private\n${undeclared ? '' : `Sitemap: ${site}/sitemap-index.xml\n`}` ) + case '/sitemap.xml': + if (undeclared === 'html') return send(200, 'text/html', page('Not found', '

Nothing

')) + if (undeclared === 'text') return send(200, 'text/plain', 'maintenance') + return send(404, 'text/plain', '') case '/sitemap-index.xml': if (missingIndex) return send(404, 'text/plain', '') return send( @@ -52,22 +58,20 @@ const siteServer = createServer((request, response) => { 'application/xml', `${site}/pages.xml${site}/more.xml.gz${foreign}/elsewhere.xml` ) - case '/pages.xml': - return send( - 200, - 'application/xml', - `${[ - `${site}/benefits2026-11-01`, - `${site}/private/salaries`, - `${foreign}/off-site`, - `${site}/benefits.pdf`, - `${site}/moved`, - `${site}/gone`, - `${site}/hidden`, - `${site}/huge`, - `${site}/renamed`, - ].join('')}` - ) + case '/pages.xml': { + const body = `${[ + `${site}/benefits${site}/plans.png2026-11-01`, + `${site}/private/salaries`, + `${foreign}/off-site`, + `${site}/benefits.pdf`, + `${site}/moved`, + `${site}/gone`, + `${site}/hidden2026-02-30`, + `${site}/huge`, + `${site}/renamed`, + ].join('')}` + return send(200, 'application/xml', truncatedPages ? body.slice(0, body.length / 2) : body) + } case '/more.xml.gz': if (missingChild) return send(404, 'text/plain', '') return send( @@ -133,6 +137,8 @@ beforeEach(() => { robotsStatus = 200 missingChild = false missingIndex = false + truncatedPages = false + undeclared = undefined faqBody = '

Original answer.

' }) @@ -169,6 +175,21 @@ describe('website connector over real HTTP', () => { expect(foreignRequests).toHaveLength(0) }) + it('reads only an entry’s own location and a real calendar date from the sitemap', async () => { + const listed = await websiteConnector.listDocuments( + `X-Api-Key: ${KEY}`, + config(), + undefined, + {} + ) + const hashes = new Map( + listed.documents.map((document) => [document.externalId, document.contentHash]) + ) + expect(hashes.get(`${site}/benefits`)).toBe(`website:${site}/benefits:2026-11-01T00:00:00.000Z`) + expect(hashes.get(`${site}/hidden`)).toBe(`website:${site}/hidden`) + expect(hashes.has(`${site}/plans.png`)).toBe(false) + }) + it('reads a page as its main region, under the same hash its sitemap date gave the listing', async () => { const context = {} const listed = await websiteConnector.listDocuments( @@ -253,6 +274,16 @@ describe('website connector over real HTTP', () => { missingChild = false missingIndex = true await expect(listAll(config())).rejects.toThrow('unavailable') + missingIndex = false + truncatedPages = true + await expect(listAll(config())).rejects.toThrow('not a valid sitemap') + }) + + 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') + undeclared = 'text' + await expect(listAll(config())).rejects.toThrow('not a valid sitemap') }) it('refuses the site without its configured header, and reports why on validation', async () => { From ff7288ffc992f871b870f1e3324e0cfc62fc639a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:40:49 -0800 Subject: [PATCH 4/9] fix(connectors): rank robots rules by the path they name, without the end anchor --- apps/sim/connectors/website/robots.test.ts | 1 + apps/sim/connectors/website/robots.ts | 9 +++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts index 673b75b741f..f9eac28eecc 100644 --- a/apps/sim/connectors/website/robots.test.ts +++ b/apps/sim/connectors/website/robots.test.ts @@ -15,6 +15,7 @@ describe('robots.txt rules for the website connector', () => { expect(robots.allows('/private/salaries')).toBe(false) expect(robots.allows('/private/handbook/leave')).toBe(true) expect(robots.allows('/tie')).toBe(true) + expect(parseRobots('User-agent: *\nAllow: /foo\nDisallow: /foo$').allows('/foo')).toBe(true) expect(robots.allows('/public')).toBe(true) }) diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts index 701b40f8ede..24f37a38a29 100644 --- a/apps/sim/connectors/website/robots.ts +++ b/apps/sim/connectors/website/robots.ts @@ -3,7 +3,7 @@ export const WEBSITE_CRAWLER_TOKEN = 'SimBot' interface RobotsRule { allow: boolean - pattern: string + length: number matches: (path: string) => boolean } @@ -92,7 +92,8 @@ export function parseRobots(body: string): RobotsPolicy { if (!value) continue current.rules.push({ allow: field === 'allow', - pattern: value, + /** Precedence counts the path a rule names, not its end anchor. */ + length: normalizePath(value.replace(/\$$/, '')).length, matches: patternMatcher(value), }) } @@ -110,8 +111,8 @@ export function parseRobots(body: string): RobotsPolicy { if (!rule.matches(path)) continue if ( !decision || - rule.pattern.length > decision.pattern.length || - (rule.pattern.length === decision.pattern.length && rule.allow) + rule.length > decision.length || + (rule.length === decision.length && rule.allow) ) decision = rule } From ff011992fd8c3593ab918a07826926e7e92d062e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 21:52:51 -0800 Subject: [PATCH 5/9] fix(connectors): split robots.txt on lone carriage returns and bound the rules it evaluates --- apps/sim/connectors/website/robots.test.ts | 9 +++++++++ apps/sim/connectors/website/robots.ts | 12 +++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/apps/sim/connectors/website/robots.test.ts b/apps/sim/connectors/website/robots.test.ts index f9eac28eecc..7614e81af46 100644 --- a/apps/sim/connectors/website/robots.test.ts +++ b/apps/sim/connectors/website/robots.test.ts @@ -68,4 +68,13 @@ describe('robots.txt rules for the website connector', () => { expect(robots.allows(`/${'a'.repeat(20_000)}`)).toBe(true) expect(performance.now() - started).toBeLessThan(1000) }) + + it('reads records separated by carriage returns alone', () => { + expect(parseRobots('User-agent: *\rDisallow: /\r').allows('/anything')).toBe(false) + }) + + it('refuses a policy with more rules than it evaluates rather than dropping some', () => { + const rules = Array.from({ length: 1001 }, (_, index) => `Disallow: /p${index}`) + expect(() => parseRobots(['User-agent: *', ...rules].join('\n'))).toThrow('more than') + }) }) diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts index 24f37a38a29..3f6c1c631ed 100644 --- a/apps/sim/connectors/website/robots.ts +++ b/apps/sim/connectors/website/robots.ts @@ -59,6 +59,12 @@ function patternMatcher(pattern: string): (path: string) => boolean { return (path) => matchWildcard(body, path, anchored) !== -1 } +/** + * Rules evaluated for every listed page. A larger policy fails the sync rather than being cut + * short, which could crawl what a dropped rule forbids. + */ +const MAX_ROBOTS_RULES = 1000 + /** * Parses robots.txt per RFC 9309: the rules of the groups naming this crawler, or of the `*` * groups when none does. The longest matching rule decides, and Allow wins a tie. @@ -68,7 +74,7 @@ export function parseRobots(body: string): RobotsPolicy { const sitemaps: string[] = [] let current: { agents: string[]; rules: RobotsRule[] } | undefined let readingAgents = false - for (const raw of body.split(/\r?\n/)) { + for (const raw of body.split(/\r\n|\r|\n/)) { const line = raw.replace(/#.*$/, '').trim() const separator = line.indexOf(':') if (separator < 1) continue @@ -102,6 +108,10 @@ export function parseRobots(body: string): RobotsPolicy { const rules = ( named.length ? named : groups.filter((group) => group.agents.includes('*')) ).flatMap((group) => group.rules) + 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, allows(rawPath) { From b1fb431562f28436091c56826d2bef398b165fbc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:03:26 -0800 Subject: [PATCH 6/9] docs(connectors): document the website connector's exported types --- apps/sim/connectors/website/page.ts | 1 + apps/sim/connectors/website/sitemap.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts index aa3ddf12ede..ade43dc464f 100644 --- a/apps/sim/connectors/website/page.ts +++ b/apps/sim/connectors/website/page.ts @@ -9,6 +9,7 @@ import { WEBSITE_CRAWLER_TOKEN } from '@/connectors/website/robots' const CHROME_SELECTOR = 'body > header, body > footer, nav, [role="navigation"], [role="banner"], [role="contentinfo"]' +/** What a rendered page contributes to the index: its title, its text, and whether it opts out. */ export interface WebsitePageText { title: string text: string diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts index 7b95e331e02..ce0f2bf3e86 100644 --- a/apps/sim/connectors/website/sitemap.ts +++ b/apps/sim/connectors/website/sitemap.ts @@ -36,6 +36,7 @@ export interface WebsitePage { lastModified?: string } +/** The pages one sitemap discovery found, and whether it stopped before the sitemaps ran out. */ export interface WebsiteDiscovery { pages: WebsitePage[] /** The sitemaps listed more pages than one discovery reads. */ @@ -50,6 +51,7 @@ interface SitemapDiscoveryOptions { retryOptions?: SecureFetchRetryOptions } +/** What a page must satisfy to be synced: the site, its robots.txt, and the configured paths. */ export interface WebsiteScope { site: WebsiteSite robots: RobotsPolicy From 81ad793b2af7e2dfea1e2925ed7646ad43fb6b33 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:16:19 -0800 Subject: [PATCH 7/9] fix(connectors): withdraw a website page the HTML parser cannot read instead of failing it --- apps/sim/connectors/website/website.integration.ts | 12 ++++++++++++ apps/sim/connectors/website/website.ts | 11 ++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index 61121052c8e..5d57e538972 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -99,6 +99,8 @@ const siteServer = createServer((request, response) => { 'text/html', page('Hidden', '

Draft

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

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

`)) case '/huge': return send(200, 'text/html', page('Huge', `

${'x'.repeat(3 * 1024 * 1024)}

`)) case '/renamed': @@ -245,6 +247,16 @@ describe('website connector over real HTTP', () => { ).rejects.toThrow('outside the configured scope') }) + it('withdraws a page with more markup than the parser accepts instead of failing its read', async () => { + const document = await websiteConnector.getDocument( + `X-Api-Key: ${KEY}`, + config(), + `${site}/dense`, + {} + ) + expect(document).toMatchObject({ skippedReason: expect.stringContaining('too complex') }) + }) + it('records a page over the size limit as skipped instead of failing the sync', async () => { const document = await websiteConnector.getDocument( `X-Api-Key: ${KEY}`, diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index b92ea6b4f40..2fa9a40bb8b 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' +import { isHtmlComplexityError } from '@/lib/file-parsers/html-parser' import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' import { VALIDATE_RETRY_OPTIONS } from '@/lib/knowledge/documents/utils' import type { ConnectorConfig, ExternalDocument, ExternalDocumentList } from '@/connectors/types' @@ -208,7 +209,15 @@ export const websiteConnector: ConnectorConfig = { if (!resource) return withdrawn(page, 'The page no longer exists on the site') if (!/html/i.test(resource.contentType)) return withdrawn(page, 'The URL serves a file, not an HTML page') - const { title, text, noindex } = extractPageText(resource.body.toString('utf8')) + let extracted: ReturnType + try { + extracted = extractPageText(resource.body.toString('utf8')) + } 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) From 29b4e7b74fcf5bc04665e965b048a6296f7f3683 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:26:45 -0800 Subject: [PATCH 8/9] docs(connectors): document the website connector exports --- apps/sim/connectors/website/meta.ts | 1 + apps/sim/connectors/website/website.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/apps/sim/connectors/website/meta.ts b/apps/sim/connectors/website/meta.ts index 70cc340f0db..614013f14f1 100644 --- a/apps/sim/connectors/website/meta.ts +++ b/apps/sim/connectors/website/meta.ts @@ -7,6 +7,7 @@ export const WEBSITE_DEFAULT_MAX_PAGES = 500 /** Hard ceiling on the configurable `maxPages` value. */ export const WEBSITE_MAX_PAGES_LIMIT = 5000 +/** Client-safe metadata for the website connector: its setup fields, auth and tags. */ export const websiteConnectorMeta: ConnectorMeta = { id: 'website', name: 'Website', diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index 2fa9a40bb8b..d8fb7c3d268 100644 --- a/apps/sim/connectors/website/website.ts +++ b/apps/sim/connectors/website/website.ts @@ -143,6 +143,7 @@ function pageToStub(page: WebsitePage): ExternalDocument { } } +/** Discovers website pages from sitemaps and reads their text within the configured scope. */ export const websiteConnector: ConnectorConfig = { ...websiteConnectorMeta, From 994c7d23f58bf16b3eb621dad0a2a35bb28528a6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:38:53 -0800 Subject: [PATCH 9/9] fix(connectors): order website listings by URL and never reconcile a listing rebuilt mid-sync --- .../sim/connectors/website/website.integration.ts | 7 +++++++ apps/sim/connectors/website/website.ts | 15 ++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts index 5d57e538972..f5f193de09c 100644 --- a/apps/sim/connectors/website/website.integration.ts +++ b/apps/sim/connectors/website/website.integration.ts @@ -277,6 +277,13 @@ describe('website connector over real HTTP', () => { expect(complete.listingCapped).toBeUndefined() }) + it('never lets a listing rebuilt for a resumed sync prove a page was removed', async () => { + const fresh = await websiteConnector.listDocuments(`X-Api-Key: ${KEY}`, config(), undefined, {}) + expect(fresh.reconciliationSafe).toBeUndefined() + const resumed = await websiteConnector.listDocuments(`X-Api-Key: ${KEY}`, config(), '2', {}) + expect(resumed.reconciliationSafe).toBe(false) + }) + it('fails the sync rather than guess when robots.txt or a listed sitemap cannot be read', async () => { robotsStatus = 403 await expect(listAll(config())).rejects.toThrow('status 403') diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts index d8fb7c3d268..6dd389c2c1b 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 { compareStrings } from '@sim/utils/string' import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' import { isHtmlComplexityError } from '@/lib/file-parsers/html-parser' import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' @@ -50,6 +51,11 @@ interface WebsiteSession { interface WebsiteListing { pages: WebsitePage[] byUrl: Map + /** + * Rebuilt for a sync resuming from a cursor. Its offsets may not line up with the listing the + * cursor came from, so this sync's listing cannot prove a page was removed. + */ + resumed: boolean } const SESSION_KEY = 'websiteSession' @@ -168,7 +174,13 @@ export const websiteConnector: ConnectorConfig = { syncContext.listingCapped = true logger.info('Website page listing capped', { listed: pages.length, maxPages }) } - listing = { pages, byUrl: new Map(pages.map((page) => [page.url, page])) } + /** URL order keeps offsets stable across listings of an unchanged site. */ + pages.sort((left, right) => compareStrings(left.url, right.url)) + listing = { + pages, + byUrl: new Map(pages.map((page) => [page.url, page])), + resumed: Boolean(cursor), + } if (syncContext) syncContext[LISTING_KEY] = listing } const offset = cursor ? Number(cursor) : 0 @@ -178,6 +190,7 @@ export const websiteConnector: ConnectorConfig = { documents: slice.map(pageToStub), nextCursor: next < listing.pages.length ? String(next) : undefined, hasMore: next < listing.pages.length, + ...(listing.resumed ? { reconciliationSafe: false } : {}), } },