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"]' + +/** What a rendered page contributes to the index: its title, its text, and whether it opts out. */ +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..7614e81af46 --- /dev/null +++ b/apps/sim/connectors/website/robots.test.ts @@ -0,0 +1,80 @@ +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(parseRobots('User-agent: *\nAllow: /foo\nDisallow: /foo$').allows('/foo')).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']) + }) + + 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) + }) + + 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) + }) + + 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 new file mode 100644 index 00000000000..3f6c1c631ed --- /dev/null +++ b/apps/sim/connectors/website/robots.ts @@ -0,0 +1,135 @@ +/** The product token the connector sends and honors robots.txt groups for. */ +export const WEBSITE_CRAWLER_TOKEN = 'SimBot' + +interface RobotsRule { + allow: boolean + length: number + matches: (path: string) => boolean +} + +/** 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 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)) +} + +/** + * 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 test: `*` matches anything, a final `$` anchors the end. */ +function patternMatcher(pattern: string): (path: string) => boolean { + const anchored = pattern.endsWith('$') + const body = normalizePath(anchored ? pattern.slice(0, -1) : pattern) + 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. + */ +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|\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', + /** Precedence counts the path a rule names, not its end anchor. */ + length: normalizePath(value.replace(/\$$/, '')).length, + matches: 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) + 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) { + const path = normalizePath(rawPath) + let decision: RobotsRule | undefined + for (const rule of rules) { + if (!rule.matches(path)) continue + if ( + !decision || + rule.length > decision.length || + (rule.length === decision.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..02cfe7c562d --- /dev/null +++ b/apps/sim/connectors/website/site.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { parseRequestHeader, pathPatterns, resolveSite, siteUrl } from '@/connectors/website/site' + +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([ + ['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'], + ['a second header line', 'A: 1\nB: 2', 'Name: value'], + ])('refuses %s', (_case, credential, reason) => { + expect(() => parseRequestHeader(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 [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) + }) + + 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', + }) + }) + + 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' + ) + 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 new file mode 100644 index 00000000000..c02faa4b263 --- /dev/null +++ b/apps/sim/connectors/website/site.ts @@ -0,0 +1,185 @@ +import { validateExternalUrl } from '@/lib/core/security/input-validation' +import { + type SecureFetchRetryOptions, + secureFetchWithRetry, +} from '@/lib/knowledge/documents/secure-fetch.server' +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. */ + 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, + protocol: parsed.protocol, + port: parsed.port, + baseUrl: `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`, + basePath: normalizePath(parsed.pathname).replace(/\/+$/, ''), + hostKey: parsed.hostname.replace(/^www\./, '').toLowerCase(), + } +} + +/** + * 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 ( + (sameService || upgraded) && + !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()) + .filter(Boolean) + .map((pattern) => { + const prefix = normalizePath( + (pattern.startsWith('/') ? pattern : `/${pattern}`).replace(/\/+$/, '') + ) + if (!prefix.includes('*')) return (path: string) => isUnderPath(path, prefix) + return (path: string) => + matchWildcard(prefix, path, true) !== -1 || matchWildcard(`${prefix}/`, path, false) !== -1 + }) +} + +/** 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]*$/ + +/** + * 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 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, + * 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 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) + 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`) + }, + }, + { + 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}`) + return { + body: Buffer.from(await response.arrayBuffer()), + contentType: response.headers.get('content-type') ?? '', + } +} 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 new file mode 100644 index 00000000000..ce0f2bf3e86 --- /dev/null +++ b/apps/sim/connectors/website/sitemap.ts @@ -0,0 +1,251 @@ +import { gunzipSync } from 'node:zlib' +import { Parser } from 'htmlparser2' +import type { SecureFetchRetryOptions } from '@/lib/knowledge/documents/secure-fetch.server' +import { normalizePath, 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 +} + +/** 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. */ + 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 +} + +/** What a page must satisfy to be synced: the site, its robots.txt, and the configured paths. */ +export interface WebsiteScope { + site: WebsiteSite + robots: RobotsPolicy + include: ((path: string) => boolean)[] + exclude: ((path: string) => boolean)[] +} + +interface SitemapEntry { + kind: 'url' | 'sitemap' + loc: string + lastmod?: string +} + +/** 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. 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 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) + 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, 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 && 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 closed && !implied && (root === 'urlset' || root === 'sitemapindex') ? entries : null +} + +/** 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 = 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 + 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<{ xml: string; html: boolean } | null> { + 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 { + xml: (gzipped + ? gunzipSync(resource.body, { maxOutputLength: SITEMAP_MAX_DECOMPRESSED_BYTES }) + : resource.body + ).toString('utf8'), + html: /html/i.test(resource.contentType), + } +} + +/** + * 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. A + * configured or declared sitemap must exist; only a guessed location may be missing. + */ +function rootSitemaps( + scope: WebsiteScope, + configured?: string +): { url: string; required: boolean }[] { + const { site } = scope + 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()] : [] + }) + const guessed = !declared.length + return [ + ...new Set(guessed ? [`${site.baseUrl}/sitemap.xml`, `${site.origin}/sitemap.xml`] : declared), + ].map((url) => ({ url, required: !guessed })) +} + +/** + * 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) + 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 sitemap = await readSitemap(next.url, site, headers, retryOptions) + const entries = sitemap === null ? null : sitemapEntries(sitemap.xml) + if (entries === null) { + /** 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') { + 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 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 new file mode 100644 index 00000000000..f5f193de09c --- /dev/null +++ b/apps/sim/connectors/website/website.integration.ts @@ -0,0 +1,317 @@ +/** + * 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 missingIndex = false +let truncatedPages = false +let undeclared: 'html' | 'text' | undefined +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\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( + 200, + 'application/xml', + `${site}/pages.xml${site}/more.xml.gz${foreign}/elsewhere.xml` + ) + 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( + 200, + 'application/gzip', + gzipSync( + `` + ) + ) + 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 '/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': + 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 + missingIndex = false + truncatedPages = false + undeclared = undefined + 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 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( + `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('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 () => { + 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('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}`, + 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('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') + robotsStatus = 200 + missingChild = true + await expect(listAll(config())).rejects.toThrow('unavailable') + 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 () => { + await expect(websiteConnector.listDocuments('', config(), undefined, {})).rejects.toThrow('401') + 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 new file mode 100644 index 00000000000..6dd389c2c1b --- /dev/null +++ b/apps/sim/connectors/website/website.ts @@ -0,0 +1,287 @@ +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' +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, + parseRequestHeader, + 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 + /** + * 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' +const LISTING_KEY = 'websiteListing' + +/** 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) + 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' } +} + +/** + * 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 = parseRequestHeader(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, + }, + } +} + +/** Discovers website pages from sitemaps and reads their text within the configured scope. */ +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 }) + } + /** 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 + 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, + ...(listing.resumed ? { reconciliationSafe: false } : {}), + } + }, + + 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 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') + 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) + 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 }> => { + if (parseMaxPages(sourceConfig.maxPages) === null) + return { valid: false, error: 'Max Pages must be a positive whole 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)