diff --git a/apps/sim/connectors/website/page.test.ts b/apps/sim/connectors/website/page.test.ts
new file mode 100644
index 00000000000..c8d216c8abf
--- /dev/null
+++ b/apps/sim/connectors/website/page.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest'
+import { decodePage, robotsHeaderNoindex } from '@/connectors/website/page'
+
+const html = (head: string, text: string) => `
${head}${text}`
+
+describe('website page decoding', () => {
+ it('lets a byte order mark override a declared charset', () => {
+ const body = Buffer.concat([
+ Buffer.from([0xff, 0xfe]),
+ Buffer.from(html('', 'Crème'), 'utf16le'),
+ ])
+ expect(decodePage(body, 'text/html; charset=iso-8859-1')).toContain('Crème')
+ })
+
+ it('reads a meta-declared UTF-16 page as UTF-8, as the HTML spec does', () => {
+ const body = Buffer.from(html('', 'Crème'), 'utf8')
+ expect(decodePage(body, 'text/html')).toContain('Crème')
+ })
+
+ it('reads only a charset attribute or Content-Type declaration, not charset text elsewhere', () => {
+ const body = Buffer.from(
+ html('', 'Crème'),
+ 'utf8'
+ )
+ expect(decodePage(body, 'text/html')).toContain('Crème')
+ const declared = Buffer.from(
+ html(
+ '',
+ 'Cr\u00e8me'
+ ),
+ 'latin1'
+ )
+ expect(decodePage(declared, 'text/html')).toContain('Crème')
+ })
+
+ it('ignores a charset declared inside a comment', () => {
+ const body = Buffer.from(
+ html('', 'Crème'),
+ 'utf8'
+ )
+ expect(decodePage(body, 'text/html')).toContain('Crème')
+ })
+})
+
+describe('X-Robots-Tag', () => {
+ it('honors an unqualified noindex after another crawler’s directive in a repeated header', () => {
+ expect(robotsHeaderNoindex('otherbot: noindex, noindex')).toBe(true)
+ expect(robotsHeaderNoindex('otherbot: noindex')).toBe(false)
+ })
+})
diff --git a/apps/sim/connectors/website/page.ts b/apps/sim/connectors/website/page.ts
index ade43dc464f..60a4624fa99 100644
--- a/apps/sim/connectors/website/page.ts
+++ b/apps/sim/connectors/website/page.ts
@@ -3,6 +3,7 @@ import {
assertHtmlStringWithinLimits,
loadedHtmlToStructuredText,
} from '@/lib/file-parsers/html-parser'
+import { decodeTextBuffer, decodeWindows1252 } from '@/lib/file-parsers/utils'
import { WEBSITE_CRAWLER_TOKEN } from '@/connectors/website/robots'
/** Page-level chrome repeated on every page, which would make every page's text look alike. */
@@ -40,3 +41,87 @@ export function extractPageText(html: string): WebsitePageText {
const text = regionText || region === 'body' ? regionText : loadedHtmlToStructuredText($)
return { title, text, noindex: /\b(noindex|none)\b/i.test(directives) }
}
+
+const META_TAG = /]*>/gi
+const TAG_ATTRIBUTE = /([^\s"'=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g
+
+/**
+ * The charset a page's `` tags declare in its first 1024 bytes, as the HTML spec's prescan
+ * reads them: a `charset` attribute, or the `content` of an `http-equiv="Content-Type"` tag.
+ * Comments are skipped, and so is `charset=` text inside any other attribute.
+ */
+function metaCharset(body: Buffer): string | undefined {
+ const head = body
+ .subarray(0, 1024)
+ .toString('latin1')
+ .replace(/|$)/g, '')
+ for (const [tag] of head.matchAll(META_TAG)) {
+ const attributes = new Map(
+ [...tag.slice(5).matchAll(TAG_ATTRIBUTE)].map(([, name, ...values]) => [
+ name.toLowerCase(),
+ values.find((value) => value !== undefined) ?? '',
+ ])
+ )
+ const label =
+ attributes.get('charset')?.trim() ||
+ (attributes.get('http-equiv')?.toLowerCase() === 'content-type'
+ ? /charset\s*=\s*["']?([\w.:-]+)/i.exec(attributes.get('content') ?? '')?.[1]
+ : undefined)
+ // Bytes a parser can read a tag from are not UTF-16, so the spec reads that as UTF-8.
+ if (label) return /^utf-?16/i.test(label) ? 'utf-8' : label
+ }
+ return undefined
+}
+
+/**
+ * A page's bytes as text. A byte order mark decides first, then the charset its Content-Type or
+ * `` tag declares. Without either the shared text decoder applies: UTF-8 when the bytes are
+ * valid UTF-8, else Windows-1252, so a page is never read with replacement characters for every
+ * non-ASCII byte.
+ */
+export function decodePage(body: Buffer, contentType: string): string {
+ const bom =
+ (body[0] === 0xef && body[1] === 0xbb && body[2] === 0xbf) ||
+ (body[0] === 0xff && body[1] === 0xfe) ||
+ (body[0] === 0xfe && body[1] === 0xff)
+ const label = bom
+ ? undefined
+ : (/;\s*charset\s*=\s*"?([^";\s]+)/i.exec(contentType)?.[1] ?? metaCharset(body))
+ let encoding: string | undefined
+ try {
+ encoding = label ? new TextDecoder(label).encoding : undefined
+ } catch {}
+ if (encoding === 'windows-1252') return decodeWindows1252(body)
+ if (!encoding || encoding === 'utf-8' || encoding === 'replacement')
+ return decodeTextBuffer(body).text
+ return new TextDecoder(encoding).decode(body)
+}
+
+/** X-Robots-Tag directives that take a value, which are not a crawler name before a colon. */
+const VALUED_DIRECTIVES = new Set([
+ 'unavailable_after',
+ 'max-snippet',
+ 'max-image-preview',
+ 'max-video-preview',
+])
+
+/**
+ * Whether an `X-Robots-Tag` header asks this crawler not to index the page: `noindex` or `none`,
+ * either unqualified or after this crawler's name (`SimBot: noindex`). Only a directive right
+ * after another crawler's name is left to that crawler. Repeated headers arrive joined by commas,
+ * which hides where one ends, so a crawler name never carries over to the directives after it:
+ * an unqualified `noindex` is never mistaken for another crawler's.
+ */
+export function robotsHeaderNoindex(value: string | null): boolean {
+ if (!value) return false
+ const token = WEBSITE_CRAWLER_TOKEN.toLowerCase()
+ return value.split(',').some((part) => {
+ let directive = part.trim().toLowerCase()
+ const named = /^([\w-]+)\s*:\s*(.*)$/.exec(directive)
+ if (named && !VALUED_DIRECTIVES.has(named[1])) {
+ if (named[1] !== token) return false
+ directive = named[2]
+ }
+ return directive === 'noindex' || directive === 'none'
+ })
+}
diff --git a/apps/sim/connectors/website/robots.ts b/apps/sim/connectors/website/robots.ts
index 3f6c1c631ed..ef1ac461f7c 100644
--- a/apps/sim/connectors/website/robots.ts
+++ b/apps/sim/connectors/website/robots.ts
@@ -89,7 +89,8 @@ export function parseRobots(body: string): RobotsPolicy {
current = { agents: [], rules: [] }
groups.push(current)
}
- current.agents.push(value.toLowerCase())
+ // A group names a crawler by its product token; `SimBot/1.0` names SimBot.
+ current.agents.push(value.split('/')[0].trim().toLowerCase())
readingAgents = true
continue
}
diff --git a/apps/sim/connectors/website/site.ts b/apps/sim/connectors/website/site.ts
index c02faa4b263..4f531ae695b 100644
--- a/apps/sim/connectors/website/site.ts
+++ b/apps/sim/connectors/website/site.ts
@@ -1,4 +1,6 @@
+import type { HttpRedirectPolicy } from '@/lib/core/security/http-redirect-policy'
import { validateExternalUrl } from '@/lib/core/security/input-validation'
+import type { SecureFetchResponse } from '@/lib/core/security/input-validation.server'
import {
type SecureFetchRetryOptions,
secureFetchWithRetry,
@@ -139,34 +141,50 @@ 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.
+ * robots.txt bytes parsed, the 500 KiB minimum RFC 9309 sets; a longer file is read only that far
+ * rather than failing the sync.
*/
-export async function fetchSiteResource(
- url: string,
- site: WebsiteSite,
- headers: Record,
- accept: string,
+const ROBOTS_PARSE_BYTES = 500 * 1024
+
+interface SiteRequest {
+ url: string
+ headers: Record
+ accept: string
+ retryOptions?: SecureFetchRetryOptions
+}
+
+/**
+ * Redirects confined to the site keep the configured header: `www` and apex, or an HTTP-to-HTTPS
+ * upgrade, count as one host, and a gateway in front of it needs the header on whichever of them
+ * it redirects to.
+ */
+const SAME_SITE_REDIRECTS: HttpRedirectPolicy = {
+ mode: 'standard',
+ sendCredentialsOnCrossOriginRedirect: true,
+}
+
+/**
+ * One GET on behalf of the site. `retryOptions.signal`, when given, bounds it alongside the
+ * request's own deadline. The crawler's User-Agent and Accept survive every redirect hop; what
+ * happens to the configured header is the redirect policy's call.
+ */
+function siteGet(
+ { url, headers, accept, retryOptions }: SiteRequest,
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(
+ redirect: { policy: HttpRedirectPolicy; assertTarget?: (target: URL) => void }
+): Promise {
+ const signals = [AbortSignal.timeout(REQUEST_DEADLINE_MS)]
+ if (retryOptions?.signal) signals.push(retryOptions.signal)
+ const deadline = AbortSignal.any(signals)
+ return 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`)
- },
+ redirectPolicy: redirect.policy,
+ assertRedirectTarget: (target) => redirect.assertTarget?.(new URL(target)),
},
{
timeout: ATTEMPT_TIMEOUT_MS,
@@ -176,10 +194,113 @@ export async function fetchSiteResource(
maxResponseBytes: maxBytes,
}
)
+}
+
+/**
+ * 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 a page never indexes content from outside the
+ * scope. The configured header follows the allowed hops ({@link SAME_SITE_REDIRECTS}).
+ */
+export async function fetchSiteResource(
+ request: SiteRequest & { site: WebsiteSite },
+ maxBytes: number,
+ allowsTarget?: (target: URL) => boolean
+): Promise<{ body: Buffer; headers: SecureFetchResponse['headers'] } | null> {
+ const response = await siteGet(request, maxBytes, {
+ policy: SAME_SITE_REDIRECTS,
+ assertTarget: (target) => {
+ if (!onSiteHost(target, request.site))
+ throw new Error(`The site redirected ${request.url} off its host`)
+ if (allowsTarget && !allowsTarget(target))
+ throw new Error(`The site redirected ${request.url} outside the configured scope`)
+ },
+ })
if (response.status === 404 || response.status === 410) return null
- if (!response.ok) throw new Error(`The site returned status ${response.status} for ${url}`)
+ if (!response.ok)
+ throw new Error(`The site returned status ${response.status} for ${request.url}`)
return {
body: Buffer.from(await response.arrayBuffer()),
- contentType: response.headers.get('content-type') ?? '',
+ headers: response.headers,
+ }
+}
+
+/**
+ * The text of at most `maxBytes` of a body, cancelling the rest of the transfer as soon as the
+ * limit is read. A body that reaches the limit loses its unterminated last line, which read whole
+ * could mean something else.
+ */
+async function readTextPrefix(
+ body: ReadableStream | null,
+ maxBytes: number
+): Promise {
+ if (!body) return ''
+ const reader = body.getReader()
+ const chunks: Uint8Array[] = []
+ let length = 0
+ try {
+ while (length < maxBytes) {
+ const { done, value } = await reader.read()
+ if (done) break
+ chunks.push(value)
+ length += value.byteLength
+ }
+ } finally {
+ await reader.cancel().catch(() => {})
+ }
+ const text = Buffer.concat(chunks).subarray(0, maxBytes).toString('utf8')
+ // A body that filled the limit may continue past it.
+ if (length < maxBytes) return text
+ return text.slice(0, Math.max(text.lastIndexOf('\n'), text.lastIndexOf('\r')) + 1)
+}
+
+/** A robots.txt redirect that leaves the site, to be followed without the configured header. */
+class OffSiteRedirect extends Error {
+ constructor(readonly target: URL) {
+ super(`robots.txt redirected off the site to ${target.origin}`)
+ }
+}
+
+/**
+ * The site's robots.txt as text, or `null` when it is unavailable, per RFC 9309: any 4xx but 429
+ * means there are no rules. Redirects are followed to any host, still through the SSRF guard;
+ * the file is only read, and the pages it governs stay on the site. Hops within the site keep the
+ * configured header, as pages and sitemaps do; from the first hop off the site the request starts
+ * over without it, so it never reaches a host the site did not name. A file over
+ * {@link ROBOTS_PARSE_BYTES} is parsed up to that point.
+ */
+export async function fetchRobotsText({
+ site,
+ headers,
+ retryOptions,
+}: {
+ site: WebsiteSite
+ headers: Record
+ retryOptions?: SecureFetchRetryOptions
+}): Promise {
+ const get = (url: string, requestHeaders: Record, onSite: boolean) =>
+ siteGet(
+ { url, headers: requestHeaders, accept: 'text/plain', retryOptions },
+ // Uncapped in transport, which would fail the fetch: the read stops at ROBOTS_PARSE_BYTES.
+ Number.MAX_SAFE_INTEGER,
+ {
+ policy: SAME_SITE_REDIRECTS,
+ assertTarget: (target) => {
+ if (onSite && !onSiteHost(target, site)) throw new OffSiteRedirect(target)
+ },
+ }
+ )
+ let response: SecureFetchResponse
+ try {
+ response = await get(`${site.origin}/robots.txt`, headers, true)
+ } catch (error) {
+ if (!(error instanceof OffSiteRedirect)) throw error
+ response = await get(error.target.toString(), {}, false)
+ }
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {})
+ if (response.status >= 400 && response.status < 500 && response.status !== 429) return null
+ throw new Error(`The site returned status ${response.status} for its robots.txt`)
}
+ return readTextPrefix(response.body, ROBOTS_PARSE_BYTES)
}
diff --git a/apps/sim/connectors/website/sitemap.ts b/apps/sim/connectors/website/sitemap.ts
index ce0f2bf3e86..7580b4bc8dc 100644
--- a/apps/sim/connectors/website/sitemap.ts
+++ b/apps/sim/connectors/website/sitemap.ts
@@ -14,15 +14,28 @@ 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. */
+/**
+ * Sitemap documents read in one discovery, bounding a hostile or huge sitemap index. Children an
+ * index lists past it are skipped and the listing reported as truncated.
+ */
const MAX_SITEMAP_DOCUMENTS = 20
+/**
+ * Entries read from one sitemap document, the sitemaps.org limit. A document listing more is read
+ * only that far, and the listing reported as truncated, so its size bounds work and memory
+ * however small its entries are.
+ */
+const MAX_SITEMAP_ENTRIES = 50_000
+
/**
* 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
+/** Characters handed to the XML parser at a time, so a read that has what it needs stops early. */
+const PARSE_CHUNK_CHARS = 64 * 1024
+
/** 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
@@ -36,11 +49,13 @@ export interface WebsitePage {
lastModified?: string
}
-/** The pages one sitemap discovery found, and whether it stopped before the sitemaps ran out. */
+/** The pages one discovery found, and why they may not be all the site has. */
export interface WebsiteDiscovery {
pages: WebsitePage[]
- /** The sitemaps listed more pages than one discovery reads. */
+ /** The site offered more than one discovery reads (pages, sitemap entries or documents). */
truncated: boolean
+ /** A source the site points to could not be read, so pages it lists may be missing. */
+ incomplete: boolean
}
interface SitemapDiscoveryOptions {
@@ -48,6 +63,7 @@ interface SitemapDiscoveryOptions {
configuredSitemap?: string
/** Pages to discover before stopping. */
limit?: number
+ /** Retry policy for every sitemap request; its `signal` bounds the whole discovery. */
retryOptions?: SecureFetchRetryOptions
}
@@ -84,28 +100,35 @@ function lastModified(value: string | undefined): string | undefined {
}
/**
- * The entries of a sitemap or sitemap index, read in one linear pass with a streaming XML parser,
+ * Reads the entries of a sitemap or sitemap index 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.
+ * nested inside it such as ``. Each entry goes to `visit` as it is read, and reading
+ * stops early (`stopped`) when `visit` returns false or the document lists more entries than
+ * {@link MAX_SITEMAP_ENTRIES}. `invalid` when the document is not a complete sitemap: an HTML page,
+ * another document, or one cut off or left unbalanced; entries it gave before that still count.
*/
-function sitemapEntries(xml: string): SitemapEntry[] | null {
- const entries: SitemapEntry[] = []
+function readSitemapEntries(
+ xml: string,
+ visit: (entry: SitemapEntry) => boolean
+): 'complete' | 'stopped' | 'invalid' {
let root: string | undefined
let depth = 0
let closed = false
let implied = false
+ let stopped = false
+ let count = 0
let entry: { value: SitemapEntry; depth: number } | undefined
let field: { name: 'loc' | 'lastmod'; depth: number } | undefined
let text = ''
+ const isSitemap = () => root === 'urlset' || root === 'sitemapindex'
const parser = new Parser(
{
onopentag(name) {
const element = localName(name)
depth++
if (depth === 1) root = element
- if (depth === 2 && (element === 'url' || element === 'sitemap'))
+ if (depth === 2 && isSitemap() && (element === 'url' || element === 'sitemap'))
entry = { value: { kind: element, loc: '' }, depth }
else if (
entry &&
@@ -126,7 +149,8 @@ function sitemapEntries(xml: string): SitemapEntry[] | null {
if (entry) entry.value[field.name] = text.trim()
field = undefined
} else if (entry && depth === entry.depth) {
- if (entry.value.loc) entries.push(entry.value)
+ if (entry.value.loc && !stopped)
+ stopped = ++count > MAX_SITEMAP_ENTRIES || !visit(entry.value)
entry = undefined
}
depth--
@@ -135,9 +159,11 @@ function sitemapEntries(xml: string): SitemapEntry[] | null {
},
{ xmlMode: true, decodeEntities: true, recognizeCDATA: true }
)
- parser.write(xml)
+ for (let offset = 0; offset < xml.length && !stopped; offset += PARSE_CHUNK_CHARS)
+ parser.write(xml.slice(offset, offset + PARSE_CHUNK_CHARS))
+ if (stopped) return 'stopped'
parser.end()
- return closed && !implied && (root === 'urlset' || root === 'sitemapindex') ? entries : null
+ return closed && !implied && isSitemap() ? 'complete' : 'invalid'
}
/** The page a sitemap location names, when it is a page within the configured scope. */
@@ -160,12 +186,8 @@ async function readSitemap(
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
+ { url, site, headers, accept: 'application/xml, text/xml;q=0.9, */*;q=0.1', retryOptions },
+ SITEMAP_MAX_BYTES
)
if (!resource) return null
const gzipped = resource.body[0] === 0x1f && resource.body[1] === 0x8b
@@ -174,14 +196,14 @@ async function readSitemap(
? gunzipSync(resource.body, { maxOutputLength: SITEMAP_MAX_DECOMPRESSED_BYTES })
: resource.body
).toString('utf8'),
- html: /html/i.test(resource.contentType),
+ html: /html/i.test(resource.headers.get('content-type') ?? ''),
}
}
/**
* 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.
+ * configured or declared sitemap is expected to exist; only a guessed location may be missing.
*/
function rootSitemaps(
scope: WebsiteScope,
@@ -202,8 +224,9 @@ function rootSitemaps(
/**
* 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.
+ * A sitemap the site lists that cannot be read (a stale robots.txt entry, a child an index lists
+ * that is gone) is skipped and the discovery reported as incomplete, since the sync cannot tell
+ * its pages from deletions. Discovery fails only when it found no pages and some sitemap failed.
*/
export async function discoverSitemapPages(
scope: WebsiteScope,
@@ -211,41 +234,50 @@ export async function discoverSitemapPages(
{ configuredSitemap, limit = MAX_SITEMAP_PAGES, retryOptions }: SitemapDiscoveryOptions = {}
): Promise {
const { site } = scope
+ const pageLimit = Math.min(limit, MAX_SITEMAP_PAGES)
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 roots = rootSitemaps(scope, configuredSitemap)
+ const queue = roots.slice(0, MAX_SITEMAP_DOCUMENTS)
+ const enqueued = new Set(queue.map((sitemap) => sitemap.url))
+ let truncated = roots.length > queue.length
+ let full = false
+ let failure: unknown
+ const visit = (entry: SitemapEntry, base: string): boolean => {
+ if (entry.kind === 'sitemap') {
+ const child = siteUrl(entry.loc, base, site)?.toString()
+ if (!child || enqueued.has(child)) return true
+ if (enqueued.size >= MAX_SITEMAP_DOCUMENTS) truncated = true
+ else {
+ enqueued.add(child)
+ queue.push({ url: child, required: true })
}
- const modified = lastModified(entry.lastmod)
- pages.set(page.url, { ...page, ...(modified ? { lastModified: modified } : {}) })
+ return true
+ }
+ const page = scopedPage(entry.loc, scope)
+ if (!page || pages.has(page.url)) return true
+ if (pages.size >= pageLimit) {
+ full = truncated = true
+ return false
+ }
+ const modified = lastModified(entry.lastmod)
+ pages.set(page.url, { ...page, ...(modified ? { lastModified: modified } : {}) })
+ return true
+ }
+ for (let next = queue.shift(); next && !full; next = queue.shift()) {
+ const { url, required } = next
+ try {
+ const sitemap = await readSitemap(url, site, headers, retryOptions)
+ const outcome = sitemap && readSitemapEntries(sitemap.xml, (entry) => visit(entry, url))
+ if (outcome === 'stopped') truncated = true
+ if (outcome === 'complete' || outcome === 'stopped') continue
+ // A guessed location may be absent, or a page the site serves for any unknown path.
+ if (!required && (!sitemap || sitemap.html)) continue
+ failure ??= new Error(`Sitemap ${url} is unavailable or not a valid sitemap`)
+ } catch (error) {
+ if (retryOptions?.signal?.aborted) throw error
+ failure ??= error
}
}
- return { pages: [...pages.values()], truncated }
+ if (pages.size === 0 && failure) throw failure
+ return { pages: [...pages.values()], truncated, incomplete: Boolean(failure) }
}
diff --git a/apps/sim/connectors/website/website.integration.ts b/apps/sim/connectors/website/website.integration.ts
index f5f193de09c..f798c255207 100644
--- a/apps/sim/connectors/website/website.integration.ts
+++ b/apps/sim/connectors/website/website.integration.ts
@@ -3,10 +3,12 @@
* 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 { LookupAddress, LookupAllOptions } from 'node:dns'
+import dns from 'node:dns/promises'
+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'
import { gzipSync } from 'node:zlib'
-import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { websiteConnector } from '@/connectors/website/website'
const KEY = 'synthetic-site-key'
@@ -17,9 +19,21 @@ let robotsStatus = 200
let missingChild = false
let missingIndex = false
let truncatedPages = false
+let staleDeclared = false
+let manyChildren = false
+let robotsElsewhere = false
+let robotsOversized = false
+let robotsHang = false
+let robotsHeldOpen = false
+let robotsToWww = false
+let hung: ServerResponse[] = []
+let wwwRequests: IncomingMessage[] = []
let undeclared: 'html' | 'text' | undefined
let faqBody = 'Original answer.
'
+/** More `` entries than one sitemap may list, all disallowed, between two listed pages. */
+const OVERFULL_ENTRIES = 50_000
+
function listen(server: Server, host: string): Promise {
return new Promise((resolve) =>
server.listen(0, '127.0.0.1', () =>
@@ -38,14 +52,41 @@ const siteServer = createServer((request, response) => {
}
const send = (status: number, type: string, body: string | Buffer) =>
response.writeHead(status, { 'Content-Type': type }).end(body)
+ if (request.headers.host?.startsWith('www.')) wwwRequests.push(request)
const path = new URL(request.url ?? '/', site).pathname
+ if (/^\/child-\d+\.xml$/.test(path)) return send(200, 'application/xml', '')
switch (path) {
case '/robots.txt':
+ if (robotsHang) {
+ hung.push(response)
+ return
+ }
+ if (robotsToWww && !request.headers.host?.startsWith('www.')) {
+ response
+ .writeHead(301, { Location: `http://www.localhost:${new URL(site).port}/robots.txt` })
+ .end()
+ return
+ }
+ if (robotsHeldOpen) {
+ // Exactly the 500 KiB robots.txt limit, then the connection stays open.
+ const rules = `User-agent: *\nDisallow: /private\nSitemap: ${site}/sitemap-index.xml\n`
+ response.writeHead(200, { 'Content-Type': 'text/plain' })
+ response.write(`${rules}${'#'.repeat(500 * 1024 - rules.length - 1)}\n`)
+ hung.push(response)
+ return
+ }
+ if (robotsElsewhere) {
+ response.writeHead(301, { Location: `${foreign}/robots.txt` }).end()
+ return
+ }
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`}`
+ robotsOversized
+ ? // Lines end in a bare CR, which robots.txt allows, so the cut must find one.
+ `User-agent: *\rDisallow: /private\rSitemap: ${site}/sitemap-index.xml\r${'#'.repeat(600 * 1024)}\rDisallow: /benefits\r`
+ : `User-agent: *\nDisallow: /private\n${undeclared ? '' : `Sitemap: ${site}/sitemap-index.xml\n`}${staleDeclared ? `Sitemap: ${site}/stale.xml\n` : ''}`
)
case '/sitemap.xml':
if (undeclared === 'html') return send(200, 'text/html', page('Not found', 'Nothing
'))
@@ -56,7 +97,19 @@ const siteServer = createServer((request, response) => {
return send(
200,
'application/xml',
- `${site}/pages.xml${site}/more.xml.gz${foreign}/elsewhere.xml`
+ `${site}/pages.xml${site}/more.xml.gz${foreign}/elsewhere.xml${manyChildren ? Array.from({ length: 25 }, (_, index) => `${site}/child-${index}.xml`).join('') : ''}`
+ )
+ case '/overfull.xml':
+ return send(
+ 200,
+ 'application/xml',
+ `${site}/benefits${`${site}/private/x`.repeat(OVERFULL_ENTRIES)}${site}/faq`
+ )
+ case '/cut-off.xml':
+ return send(
+ 200,
+ 'application/xml',
+ `${site}/benefits${site}/faq${site}/gone${site}/hid`
)
case '/pages.xml': {
const body = `${[
@@ -87,6 +140,30 @@ const siteServer = createServer((request, response) => {
'text/html; charset=utf-8',
page('Benefits', 'Medical plans
')
)
+ case '/latin':
+ return send(
+ 200,
+ 'text/html; charset=iso-8859-1',
+ Buffer.from(page('Café', 'Crème brûlée
'), 'latin1')
+ )
+ case '/tagged':
+ response
+ .writeHead(200, {
+ 'Content-Type': 'text/html',
+ 'X-Robots-Tag': 'otherbot: none, simbot: noindex',
+ })
+ .end(page('Tagged', 'Internal
'))
+ return
+ case '/other-bot':
+ response
+ .writeHead(200, { 'Content-Type': 'text/html', 'X-Robots-Tag': 'otherbot: noindex' })
+ .end(page('Other bot', 'Public
'))
+ return
+ case '/apex-hop':
+ response
+ .writeHead(301, { Location: `http://www.localhost:${new URL(site).port}/benefits` })
+ .end()
+ return
case '/faq':
return send(
200,
@@ -116,6 +193,10 @@ const siteServer = createServer((request, response) => {
const foreignServer = createServer((request, response) => {
foreignRequests.push(request)
+ if (request.url === '/robots.txt')
+ return response
+ .writeHead(200, { 'Content-Type': 'text/plain' })
+ .end(`User-agent: SimBot/1.0\nDisallow: /benefits\nSitemap: ${site}/sitemap-index.xml\n`)
response.writeHead(200, { 'Content-Type': 'text/html' }).end(page('Elsewhere', 'Other
'))
})
@@ -136,14 +217,33 @@ afterAll(async () => {
beforeEach(() => {
foreignRequests = []
+ wwwRequests = []
robotsStatus = 200
missingChild = false
missingIndex = false
truncatedPages = false
+ staleDeclared = false
+ manyChildren = false
+ robotsElsewhere = false
+ robotsOversized = false
+ robotsHang = false
+ robotsHeldOpen = false
+ robotsToWww = false
+ for (const response of hung) response.destroy()
+ hung = []
undeclared = undefined
faqBody = 'Original answer.
'
})
+/** `www.localhost` stands in for a site's www host; it resolves where `localhost` does. */
+function resolveWwwLocalhost() {
+ const resolve: (hostname: string, options: LookupAllOptions) => Promise =
+ dns.lookup.bind(dns)
+ const stub = (hostname: string, options: LookupAllOptions) =>
+ resolve(hostname === 'www.localhost' ? 'localhost' : hostname, options)
+ return vi.spyOn(dns, 'lookup').mockImplementation(stub as typeof dns.lookup)
+}
+
async function listAll(sourceConfig: Record, syncContext = {}) {
const urls: string[] = []
let cursor: string | undefined
@@ -277,25 +377,160 @@ 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('resumes a rebuilt listing after the last URL listed, without giving up reconciliation', async () => {
+ const resumed = await websiteConnector.listDocuments(
+ `X-Api-Key: ${KEY}`,
+ config(),
+ `${site}/faq`,
+ {}
+ )
+ expect(resumed.documents.map((document) => document.externalId)).toEqual(
+ ['/gone', '/hidden', '/huge', '/moved', '/renamed'].map((path) => `${site}${path}`)
+ )
+ expect(resumed.reconciliationSafe).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')
- missingChild = false
+ it('reads an oversized sitemap only to its entry limit, and stops once the cap is met', async () => {
+ const overfull: Record = {}
+ expect(await listAll({ ...config(), sitemapUrl: `${site}/overfull.xml` }, overfull)).toEqual([
+ `${site}/benefits`,
+ ])
+ expect(overfull.listingCapped).toBe(true)
+ const capped: Record = {}
+ expect(
+ await listAll({ ...config(), sitemapUrl: `${site}/cut-off.xml`, maxPages: '2' }, capped)
+ ).toHaveLength(2)
+ expect(capped).toMatchObject({ listingCapped: true })
+ expect(capped.reconciliationUnsafe).toBeUndefined()
+ })
+
+ it('skips a sitemap it cannot read and keeps the rest, without reconciling absent pages', async () => {
+ const cases: [() => void, string[]][] = [
+ [() => (missingChild = true), ['/faq']],
+ [() => (truncatedPages = true), []],
+ [() => (staleDeclared = true), []],
+ ]
+ for (const [arrange, absent] of cases) {
+ missingChild = truncatedPages = staleDeclared = false
+ arrange()
+ const context: Record = {}
+ const urls = await listAll(config(), context)
+ expect(urls).toContain(`${site}/benefits`)
+ for (const path of absent) expect(urls).not.toContain(`${site}${path}`)
+ expect(context.reconciliationUnsafe).toBe(true)
+ }
+ })
+
+ it('caps how many child sitemaps an index fans out to', async () => {
+ manyChildren = true
+ const capped: Record = {}
+ expect(await listAll(config(), capped)).toContain(`${site}/faq`)
+ expect(capped.listingCapped).toBe(true)
+ })
+
+ it('fails the sync when the only sitemap it could start from is unavailable', async () => {
missingIndex = true
await expect(listAll(config())).rejects.toThrow('unavailable')
- missingIndex = false
- truncatedPages = true
- await expect(listAll(config())).rejects.toThrow('not a valid sitemap')
+ })
+
+ it('treats an unavailable robots.txt as allowing everything, per RFC 9309', async () => {
+ robotsStatus = 403
+ expect(await listAll({ ...config(), sitemapUrl: `${site}/sitemap-index.xml` })).toContain(
+ `${site}/private/salaries`
+ )
+ })
+
+ it('follows robots.txt to another host without the configured header, matching its product token', async () => {
+ robotsElsewhere = true
+ const urls = await listAll(config())
+ expect(urls).toContain(`${site}/faq`)
+ expect(urls).not.toContain(`${site}/benefits`)
+ expect(foreignRequests).toHaveLength(1)
+ expect(foreignRequests[0]?.headers['x-api-key']).toBeUndefined()
+ expect(foreignRequests[0]?.headers['user-agent']).toBe('SimBot/1.0')
+ })
+
+ it('parses an oversized robots.txt up to 500 KiB instead of failing', async () => {
+ robotsOversized = true
+ const urls = await listAll(config())
+ expect(urls).toContain(`${site}/benefits`)
+ expect(urls).not.toContain(`${site}/private/salaries`)
+ })
+
+ it('stops reading robots.txt at its limit without waiting for the rest', async () => {
+ robotsHeldOpen = true
+ const urls = await listAll(config())
+ expect(urls).toContain(`${site}/benefits`)
+ expect(urls).not.toContain(`${site}/private/salaries`)
+ })
+
+ it('keeps the crawler headers and configured header across a www hop on the same site', async () => {
+ const spy = resolveWwwLocalhost()
+ try {
+ const apex = `http://localhost:${new URL(site).port}`
+ const document = await websiteConnector.getDocument(
+ `X-Api-Key: ${KEY}`,
+ { siteUrl: apex },
+ `${apex}/apex-hop`,
+ {}
+ )
+ expect(document?.content).toContain('Medical plans')
+ expect(wwwRequests[0]?.headers['user-agent']).toBe('SimBot/1.0')
+ expect(wwwRequests[0]?.headers['x-api-key']).toBe(KEY)
+ } finally {
+ spy.mockRestore()
+ }
+ })
+
+ it('keeps the configured header when robots.txt redirects within the site', async () => {
+ robotsToWww = true
+ const spy = resolveWwwLocalhost()
+ try {
+ const apex = `http://localhost:${new URL(site).port}`
+ expect(
+ await websiteConnector.getDocument(
+ `X-Api-Key: ${KEY}`,
+ { siteUrl: apex },
+ `${apex}/private/salaries`,
+ {}
+ )
+ ).toBeNull()
+ expect(wwwRequests.map((request) => request.headers['x-api-key'])).toEqual([KEY])
+ } finally {
+ spy.mockRestore()
+ }
+ })
+
+ it('decodes a page in the charset it declares', async () => {
+ const read = (path: string) =>
+ websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}${path}`, {})
+ expect((await read('/latin'))?.content).toContain('Crème brûlée')
+ })
+
+ it('withdraws a page whose X-Robots-Tag tells this crawler not to index it', async () => {
+ const read = (path: string) =>
+ websiteConnector.getDocument(`X-Api-Key: ${KEY}`, config(), `${site}${path}`, {})
+ expect(await read('/tagged')).toMatchObject({
+ skippedReason: expect.stringContaining('not to be indexed'),
+ })
+ expect((await read('/other-bot'))?.content).toContain('Public')
+ })
+
+ it('gives validation an overall deadline a stalled site cannot hold past', async () => {
+ robotsHang = true
+ const timeout = AbortSignal.timeout.bind(AbortSignal)
+ const spy = vi
+ .spyOn(AbortSignal, 'timeout')
+ // 20_000 is VALIDATE_DEADLINE_MS; every other deadline stays real.
+ .mockImplementation((ms) => timeout(ms === 20_000 ? 200 : ms))
+ try {
+ expect(await websiteConnector.validateConfig(`X-Api-Key: ${KEY}`, config())).toEqual({
+ valid: false,
+ error: expect.stringContaining('did not answer'),
+ })
+ } finally {
+ spy.mockRestore()
+ }
})
it('skips a guessed sitemap location the site answers with a page, but not one that is invalid', async () => {
diff --git a/apps/sim/connectors/website/website.ts b/apps/sim/connectors/website/website.ts
index 6dd389c2c1b..de9c8d5ed3e 100644
--- a/apps/sim/connectors/website/website.ts
+++ b/apps/sim/connectors/website/website.ts
@@ -17,9 +17,10 @@ import {
WEBSITE_MAX_PAGES_LIMIT,
websiteConnectorMeta,
} from '@/connectors/website/meta'
-import { extractPageText } from '@/connectors/website/page'
+import { decodePage, extractPageText, robotsHeaderNoindex } from '@/connectors/website/page'
import { ALLOW_ALL_ROBOTS, parseRobots } from '@/connectors/website/robots'
import {
+ fetchRobotsText,
fetchSiteResource,
parseRequestHeader,
pathPatterns,
@@ -29,6 +30,7 @@ import {
import {
discoverSitemapPages,
scopedPage,
+ type WebsiteDiscovery,
type WebsitePage,
type WebsiteScope,
} from '@/connectors/website/sitemap'
@@ -40,7 +42,9 @@ 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
+
+/** Whole-validation deadline: validation runs inside a request, which a slow site must not hold. */
+const VALIDATE_DEADLINE_MS = 20_000
/** What one sync reads once and every page read reuses: the scope and its request headers. */
interface WebsiteSession {
@@ -49,13 +53,9 @@ interface WebsiteSession {
}
interface WebsiteListing {
+ /** Sorted by URL: a cursor is the last URL listed, so a listing rebuilt to resume picks up there. */
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'
@@ -81,9 +81,9 @@ function withdrawn(page: WebsitePage, reason: string): ExternalDocument {
}
/**
- * 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.
+ * The sync's scope, built once per sync: the site, its path rules and its robots.txt. An
+ * unavailable 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,
@@ -95,19 +95,12 @@ async function openSession(
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 robots = await fetchRobotsText({ site, headers, retryOptions })
const session: WebsiteSession = {
headers,
scope: {
site,
- robots: robots ? parseRobots(robots.body.toString('utf8')) : ALLOW_ALL_ROBOTS,
+ robots: robots === null ? ALLOW_ALL_ROBOTS : parseRobots(robots),
include: pathPatterns(sourceConfig.includePaths),
exclude: pathPatterns(sourceConfig.excludePaths),
},
@@ -149,6 +142,46 @@ function pageToStub(page: WebsitePage): ExternalDocument {
}
}
+/**
+ * Holds a discovery as this sync's listing, sorted by URL, and reports what it could not prove
+ * to the engine: a truncated discovery caps the listing, an incomplete one makes absence from it
+ * no evidence of deletion. Either way the pages it did find still sync.
+ */
+function holdListing(
+ { pages, truncated, incomplete }: WebsiteDiscovery,
+ syncContext?: Record
+): WebsiteListing {
+ if (truncated && syncContext) {
+ syncContext.listingCapped = true
+ logger.info('Website page listing capped', { listed: pages.length })
+ }
+ if (incomplete && syncContext) {
+ syncContext.reconciliationUnsafe = true
+ logger.warn('Website listing is incomplete', { listed: pages.length })
+ }
+ pages.sort((left, right) => compareStrings(left.url, right.url))
+ const listing = { pages, byUrl: new Map(pages.map((page) => [page.url, page])) }
+ if (syncContext) syncContext[LISTING_KEY] = listing
+ return listing
+}
+
+/**
+ * The listing's next page after `cursor`, the last URL a previous page ended on. Keyed by URL
+ * rather than offset, a listing rebuilt to resume a sync picks up where the last one stopped even
+ * if pages were added or removed before it, so the resumed listing stays fit for reconciliation.
+ */
+function listingPage(listing: WebsiteListing, cursor?: string): ExternalDocumentList {
+ const start = cursor ? listing.pages.findIndex((page) => compareStrings(page.url, cursor) > 0) : 0
+ const offset = start === -1 ? listing.pages.length : start
+ const slice = listing.pages.slice(offset, offset + DOCS_PER_PAGE)
+ const hasMore = offset + slice.length < listing.pages.length
+ return {
+ documents: slice.map(pageToStub),
+ nextCursor: hasMore ? slice[slice.length - 1]?.url : undefined,
+ hasMore,
+ }
+}
+
/** Discovers website pages from sitemaps and reads their text within the configured scope. */
export const websiteConnector: ConnectorConfig = {
...websiteConnectorMeta,
@@ -162,36 +195,16 @@ export const websiteConnector: ConnectorConfig = {
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, {
+ const discovery = await discoverSitemapPages(scope, headers, {
configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope),
- limit: maxPages,
+ limit: resolveMaxPages(sourceConfig.maxPages),
})
// An empty listing would reconcile every stored page away, so fail instead.
- if (pages.length === 0)
+ if (discovery.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 } : {}),
+ listing = holdListing(discovery, syncContext)
}
+ return listingPage(listing, cursor)
},
getDocument: async (
@@ -208,12 +221,13 @@ export const websiteConnector: ConnectorConfig = {
let resource: Awaited>
try {
resource = await fetchSiteResource(
- page.url,
- scope.site,
- headers,
- 'text/html, application/xhtml+xml;q=0.9',
+ {
+ url: page.url,
+ site: scope.site,
+ headers,
+ accept: 'text/html, application/xhtml+xml;q=0.9',
+ },
PAGE_MAX_BYTES,
- undefined,
(target) => scopedPage(target.toString(), scope) !== null
)
} catch (error) {
@@ -221,11 +235,14 @@ export const websiteConnector: ConnectorConfig = {
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))
+ const contentType = resource.headers.get('content-type') ?? ''
+ if (!/html/i.test(contentType))
return withdrawn(page, 'The URL serves a file, not an HTML page')
+ if (robotsHeaderNoindex(resource.headers.get('x-robots-tag')))
+ return withdrawn(page, 'The page asks not to be indexed')
let extracted: ReturnType
try {
- extracted = extractPageText(resource.body.toString('utf8'))
+ extracted = extractPageText(decodePage(resource.body, contentType))
} catch (error) {
// Markup past the parser's limits, or nesting deep enough to exhaust the walk's stack.
if (!isHtmlComplexityError(error) && !(error instanceof RangeError)) throw error
@@ -252,17 +269,21 @@ export const websiteConnector: ConnectorConfig = {
): Promise<{ valid: boolean; error?: string }> => {
if (parseMaxPages(sourceConfig.maxPages) === null)
return { valid: false, error: 'Max Pages must be a positive whole number' }
+ const retryOptions = {
+ ...VALIDATE_RETRY_OPTIONS,
+ signal: AbortSignal.timeout(VALIDATE_DEADLINE_MS),
+ }
try {
const { scope, headers } = await openSession(
accessToken,
sourceConfig,
undefined,
- VALIDATE_RETRY_OPTIONS
+ retryOptions
)
const { pages } = await discoverSitemapPages(scope, headers, {
configuredSitemap: configuredSitemap(sourceConfig.sitemapUrl, scope),
limit: 1,
- retryOptions: VALIDATE_RETRY_OPTIONS,
+ retryOptions,
})
if (pages.length === 0)
return {
@@ -273,6 +294,11 @@ export const websiteConnector: ConnectorConfig = {
}
return { valid: true }
} catch (error) {
+ if (retryOptions.signal.aborted)
+ return {
+ valid: false,
+ error: `The website did not answer within ${VALIDATE_DEADLINE_MS / 1000} seconds`,
+ }
return { valid: false, error: getErrorMessage(error, 'Failed to reach the website') }
}
},