Skip to content

Commit 7605304

Browse files
authored
fix(connectors): harden website connector sitemap, robots and resume handling (#10556)
* fix(connectors): harden website connector sitemap, robots and resume handling - cap sitemap entries per document and stop parsing once the page cap is met - resume listings from the last URL listed so reconciliation survives resumed runs - skip unreadable or excess sitemaps and mark the listing unsafe instead of failing - keep crawler headers and the configured header across same-site redirects - follow RFC 9309 for robots.txt: 4xx allows, cross-host redirects, product token, 500 KiB prefix - decode pages in their declared charset and honor X-Robots-Tag - give validation an overall deadline * fix(connectors): website page decoding, robots cut and shared listing helpers - a byte order mark decides a page's encoding; meta-declared UTF-16 reads as UTF-8; commented meta tags are ignored - repeated X-Robots-Tag headers never carry another crawler's scope over an unqualified noindex - an oversized robots.txt is cut at its last CR or LF - listing hold and keyset paging are crawler-agnostic helpers * fix(connectors): website robots read stops at its limit; meta charset from attributes only * fix(connectors): website robots.txt keeps the configured header on same-site hops
1 parent 8bfa583 commit 7605304

7 files changed

Lines changed: 700 additions & 150 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { decodePage, robotsHeaderNoindex } from '@/connectors/website/page'
3+
4+
const html = (head: string, text: string) => `<html><head>${head}</head><body>${text}</body></html>`
5+
6+
describe('website page decoding', () => {
7+
it('lets a byte order mark override a declared charset', () => {
8+
const body = Buffer.concat([
9+
Buffer.from([0xff, 0xfe]),
10+
Buffer.from(html('', 'Crème'), 'utf16le'),
11+
])
12+
expect(decodePage(body, 'text/html; charset=iso-8859-1')).toContain('Crème')
13+
})
14+
15+
it('reads a meta-declared UTF-16 page as UTF-8, as the HTML spec does', () => {
16+
const body = Buffer.from(html('<meta charset="utf-16">', 'Crème'), 'utf8')
17+
expect(decodePage(body, 'text/html')).toContain('Crème')
18+
})
19+
20+
it('reads only a charset attribute or Content-Type declaration, not charset text elsewhere', () => {
21+
const body = Buffer.from(
22+
html('<meta name="description" content="Set charset=windows-1252 in your editor">', 'Crème'),
23+
'utf8'
24+
)
25+
expect(decodePage(body, 'text/html')).toContain('Crème')
26+
const declared = Buffer.from(
27+
html(
28+
'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">',
29+
'Cr\u00e8me'
30+
),
31+
'latin1'
32+
)
33+
expect(decodePage(declared, 'text/html')).toContain('Crème')
34+
})
35+
36+
it('ignores a charset declared inside a comment', () => {
37+
const body = Buffer.from(
38+
html('<!-- <meta charset="windows-1252"> --><meta charset="utf-8">', 'Crème'),
39+
'utf8'
40+
)
41+
expect(decodePage(body, 'text/html')).toContain('Crème')
42+
})
43+
})
44+
45+
describe('X-Robots-Tag', () => {
46+
it('honors an unqualified noindex after another crawler’s directive in a repeated header', () => {
47+
expect(robotsHeaderNoindex('otherbot: noindex, noindex')).toBe(true)
48+
expect(robotsHeaderNoindex('otherbot: noindex')).toBe(false)
49+
})
50+
})

‎apps/sim/connectors/website/page.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
assertHtmlStringWithinLimits,
44
loadedHtmlToStructuredText,
55
} from '@/lib/file-parsers/html-parser'
6+
import { decodeTextBuffer, decodeWindows1252 } from '@/lib/file-parsers/utils'
67
import { WEBSITE_CRAWLER_TOKEN } from '@/connectors/website/robots'
78

89
/** 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 {
4041
const text = regionText || region === 'body' ? regionText : loadedHtmlToStructuredText($)
4142
return { title, text, noindex: /\b(noindex|none)\b/i.test(directives) }
4243
}
44+
45+
const META_TAG = /<meta\s[^>]*>/gi
46+
const TAG_ATTRIBUTE = /([^\s"'=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g
47+
48+
/**
49+
* The charset a page's `<meta>` tags declare in its first 1024 bytes, as the HTML spec's prescan
50+
* reads them: a `charset` attribute, or the `content` of an `http-equiv="Content-Type"` tag.
51+
* Comments are skipped, and so is `charset=` text inside any other attribute.
52+
*/
53+
function metaCharset(body: Buffer): string | undefined {
54+
const head = body
55+
.subarray(0, 1024)
56+
.toString('latin1')
57+
.replace(/<!--[\s\S]*?(-->|$)/g, '')
58+
for (const [tag] of head.matchAll(META_TAG)) {
59+
const attributes = new Map(
60+
[...tag.slice(5).matchAll(TAG_ATTRIBUTE)].map(([, name, ...values]) => [
61+
name.toLowerCase(),
62+
values.find((value) => value !== undefined) ?? '',
63+
])
64+
)
65+
const label =
66+
attributes.get('charset')?.trim() ||
67+
(attributes.get('http-equiv')?.toLowerCase() === 'content-type'
68+
? /charset\s*=\s*["']?([\w.:-]+)/i.exec(attributes.get('content') ?? '')?.[1]
69+
: undefined)
70+
// Bytes a parser can read a <meta> tag from are not UTF-16, so the spec reads that as UTF-8.
71+
if (label) return /^utf-?16/i.test(label) ? 'utf-8' : label
72+
}
73+
return undefined
74+
}
75+
76+
/**
77+
* A page's bytes as text. A byte order mark decides first, then the charset its Content-Type or
78+
* `<meta>` tag declares. Without either the shared text decoder applies: UTF-8 when the bytes are
79+
* valid UTF-8, else Windows-1252, so a page is never read with replacement characters for every
80+
* non-ASCII byte.
81+
*/
82+
export function decodePage(body: Buffer, contentType: string): string {
83+
const bom =
84+
(body[0] === 0xef && body[1] === 0xbb && body[2] === 0xbf) ||
85+
(body[0] === 0xff && body[1] === 0xfe) ||
86+
(body[0] === 0xfe && body[1] === 0xff)
87+
const label = bom
88+
? undefined
89+
: (/;\s*charset\s*=\s*"?([^";\s]+)/i.exec(contentType)?.[1] ?? metaCharset(body))
90+
let encoding: string | undefined
91+
try {
92+
encoding = label ? new TextDecoder(label).encoding : undefined
93+
} catch {}
94+
if (encoding === 'windows-1252') return decodeWindows1252(body)
95+
if (!encoding || encoding === 'utf-8' || encoding === 'replacement')
96+
return decodeTextBuffer(body).text
97+
return new TextDecoder(encoding).decode(body)
98+
}
99+
100+
/** X-Robots-Tag directives that take a value, which are not a crawler name before a colon. */
101+
const VALUED_DIRECTIVES = new Set([
102+
'unavailable_after',
103+
'max-snippet',
104+
'max-image-preview',
105+
'max-video-preview',
106+
])
107+
108+
/**
109+
* Whether an `X-Robots-Tag` header asks this crawler not to index the page: `noindex` or `none`,
110+
* either unqualified or after this crawler's name (`SimBot: noindex`). Only a directive right
111+
* after another crawler's name is left to that crawler. Repeated headers arrive joined by commas,
112+
* which hides where one ends, so a crawler name never carries over to the directives after it:
113+
* an unqualified `noindex` is never mistaken for another crawler's.
114+
*/
115+
export function robotsHeaderNoindex(value: string | null): boolean {
116+
if (!value) return false
117+
const token = WEBSITE_CRAWLER_TOKEN.toLowerCase()
118+
return value.split(',').some((part) => {
119+
let directive = part.trim().toLowerCase()
120+
const named = /^([\w-]+)\s*:\s*(.*)$/.exec(directive)
121+
if (named && !VALUED_DIRECTIVES.has(named[1])) {
122+
if (named[1] !== token) return false
123+
directive = named[2]
124+
}
125+
return directive === 'noindex' || directive === 'none'
126+
})
127+
}

‎apps/sim/connectors/website/robots.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,8 @@ export function parseRobots(body: string): RobotsPolicy {
8989
current = { agents: [], rules: [] }
9090
groups.push(current)
9191
}
92-
current.agents.push(value.toLowerCase())
92+
// A group names a crawler by its product token; `SimBot/1.0` names SimBot.
93+
current.agents.push(value.split('/')[0].trim().toLowerCase())
9394
readingAgents = true
9495
continue
9596
}

‎apps/sim/connectors/website/site.ts‎

Lines changed: 143 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import type { HttpRedirectPolicy } from '@/lib/core/security/http-redirect-policy'
12
import { validateExternalUrl } from '@/lib/core/security/input-validation'
3+
import type { SecureFetchResponse } from '@/lib/core/security/input-validation.server'
24
import {
35
type SecureFetchRetryOptions,
46
secureFetchWithRetry,
@@ -139,34 +141,50 @@ const ATTEMPT_TIMEOUT_MS = 30_000
139141
const REQUEST_DEADLINE_MS = 120_000
140142

141143
/**
142-
* Fetches a resource on the configured site, or `null` when it does not exist (404 or 410). A
143-
* redirect is refused before it is followed unless it stays on the site's host and, for a page,
144-
* within the configured scope (`allowsTarget`), so configured headers never reach another host
145-
* and a page never indexes content from outside the scope.
144+
* robots.txt bytes parsed, the 500 KiB minimum RFC 9309 sets; a longer file is read only that far
145+
* rather than failing the sync.
146146
*/
147-
export async function fetchSiteResource(
148-
url: string,
149-
site: WebsiteSite,
150-
headers: Record<string, string>,
151-
accept: string,
147+
const ROBOTS_PARSE_BYTES = 500 * 1024
148+
149+
interface SiteRequest {
150+
url: string
151+
headers: Record<string, string>
152+
accept: string
153+
retryOptions?: SecureFetchRetryOptions
154+
}
155+
156+
/**
157+
* Redirects confined to the site keep the configured header: `www` and apex, or an HTTP-to-HTTPS
158+
* upgrade, count as one host, and a gateway in front of it needs the header on whichever of them
159+
* it redirects to.
160+
*/
161+
const SAME_SITE_REDIRECTS: HttpRedirectPolicy = {
162+
mode: 'standard',
163+
sendCredentialsOnCrossOriginRedirect: true,
164+
}
165+
166+
/**
167+
* One GET on behalf of the site. `retryOptions.signal`, when given, bounds it alongside the
168+
* request's own deadline. The crawler's User-Agent and Accept survive every redirect hop; what
169+
* happens to the configured header is the redirect policy's call.
170+
*/
171+
function siteGet(
172+
{ url, headers, accept, retryOptions }: SiteRequest,
152173
maxBytes: number,
153-
retryOptions?: SecureFetchRetryOptions,
154-
allowsTarget?: (target: URL) => boolean
155-
): Promise<{ body: Buffer; contentType: string } | null> {
156-
const deadline = AbortSignal.timeout(REQUEST_DEADLINE_MS)
157-
const response = await secureFetchWithRetry(
174+
redirect: { policy: HttpRedirectPolicy; assertTarget?: (target: URL) => void }
175+
): Promise<SecureFetchResponse> {
176+
const signals = [AbortSignal.timeout(REQUEST_DEADLINE_MS)]
177+
if (retryOptions?.signal) signals.push(retryOptions.signal)
178+
const deadline = AbortSignal.any(signals)
179+
return secureFetchWithRetry(
158180
url,
159181
{
160182
profile: 'configuredEndpoint',
161183
method: 'GET',
162184
signal: deadline,
163185
headers: { ...headers, Accept: accept, 'User-Agent': `${WEBSITE_CRAWLER_TOKEN}/1.0` },
164-
assertRedirectTarget: (target) => {
165-
const next = new URL(target)
166-
if (!onSiteHost(next, site)) throw new Error(`The site redirected ${url} off its host`)
167-
if (allowsTarget && !allowsTarget(next))
168-
throw new Error(`The site redirected ${url} outside the configured scope`)
169-
},
186+
redirectPolicy: redirect.policy,
187+
assertRedirectTarget: (target) => redirect.assertTarget?.(new URL(target)),
170188
},
171189
{
172190
timeout: ATTEMPT_TIMEOUT_MS,
@@ -176,10 +194,113 @@ export async function fetchSiteResource(
176194
maxResponseBytes: maxBytes,
177195
}
178196
)
197+
}
198+
199+
/**
200+
* Fetches a resource on the configured site, or `null` when it does not exist (404 or 410). A
201+
* redirect is refused before it is followed unless it stays on the site's host and, for a page,
202+
* within the configured scope (`allowsTarget`), so a page never indexes content from outside the
203+
* scope. The configured header follows the allowed hops ({@link SAME_SITE_REDIRECTS}).
204+
*/
205+
export async function fetchSiteResource(
206+
request: SiteRequest & { site: WebsiteSite },
207+
maxBytes: number,
208+
allowsTarget?: (target: URL) => boolean
209+
): Promise<{ body: Buffer; headers: SecureFetchResponse['headers'] } | null> {
210+
const response = await siteGet(request, maxBytes, {
211+
policy: SAME_SITE_REDIRECTS,
212+
assertTarget: (target) => {
213+
if (!onSiteHost(target, request.site))
214+
throw new Error(`The site redirected ${request.url} off its host`)
215+
if (allowsTarget && !allowsTarget(target))
216+
throw new Error(`The site redirected ${request.url} outside the configured scope`)
217+
},
218+
})
179219
if (response.status === 404 || response.status === 410) return null
180-
if (!response.ok) throw new Error(`The site returned status ${response.status} for ${url}`)
220+
if (!response.ok)
221+
throw new Error(`The site returned status ${response.status} for ${request.url}`)
181222
return {
182223
body: Buffer.from(await response.arrayBuffer()),
183-
contentType: response.headers.get('content-type') ?? '',
224+
headers: response.headers,
225+
}
226+
}
227+
228+
/**
229+
* The text of at most `maxBytes` of a body, cancelling the rest of the transfer as soon as the
230+
* limit is read. A body that reaches the limit loses its unterminated last line, which read whole
231+
* could mean something else.
232+
*/
233+
async function readTextPrefix(
234+
body: ReadableStream<Uint8Array> | null,
235+
maxBytes: number
236+
): Promise<string> {
237+
if (!body) return ''
238+
const reader = body.getReader()
239+
const chunks: Uint8Array[] = []
240+
let length = 0
241+
try {
242+
while (length < maxBytes) {
243+
const { done, value } = await reader.read()
244+
if (done) break
245+
chunks.push(value)
246+
length += value.byteLength
247+
}
248+
} finally {
249+
await reader.cancel().catch(() => {})
250+
}
251+
const text = Buffer.concat(chunks).subarray(0, maxBytes).toString('utf8')
252+
// A body that filled the limit may continue past it.
253+
if (length < maxBytes) return text
254+
return text.slice(0, Math.max(text.lastIndexOf('\n'), text.lastIndexOf('\r')) + 1)
255+
}
256+
257+
/** A robots.txt redirect that leaves the site, to be followed without the configured header. */
258+
class OffSiteRedirect extends Error {
259+
constructor(readonly target: URL) {
260+
super(`robots.txt redirected off the site to ${target.origin}`)
261+
}
262+
}
263+
264+
/**
265+
* The site's robots.txt as text, or `null` when it is unavailable, per RFC 9309: any 4xx but 429
266+
* means there are no rules. Redirects are followed to any host, still through the SSRF guard;
267+
* the file is only read, and the pages it governs stay on the site. Hops within the site keep the
268+
* configured header, as pages and sitemaps do; from the first hop off the site the request starts
269+
* over without it, so it never reaches a host the site did not name. A file over
270+
* {@link ROBOTS_PARSE_BYTES} is parsed up to that point.
271+
*/
272+
export async function fetchRobotsText({
273+
site,
274+
headers,
275+
retryOptions,
276+
}: {
277+
site: WebsiteSite
278+
headers: Record<string, string>
279+
retryOptions?: SecureFetchRetryOptions
280+
}): Promise<string | null> {
281+
const get = (url: string, requestHeaders: Record<string, string>, onSite: boolean) =>
282+
siteGet(
283+
{ url, headers: requestHeaders, accept: 'text/plain', retryOptions },
284+
// Uncapped in transport, which would fail the fetch: the read stops at ROBOTS_PARSE_BYTES.
285+
Number.MAX_SAFE_INTEGER,
286+
{
287+
policy: SAME_SITE_REDIRECTS,
288+
assertTarget: (target) => {
289+
if (onSite && !onSiteHost(target, site)) throw new OffSiteRedirect(target)
290+
},
291+
}
292+
)
293+
let response: SecureFetchResponse
294+
try {
295+
response = await get(`${site.origin}/robots.txt`, headers, true)
296+
} catch (error) {
297+
if (!(error instanceof OffSiteRedirect)) throw error
298+
response = await get(error.target.toString(), {}, false)
299+
}
300+
if (!response.ok) {
301+
await response.body?.cancel().catch(() => {})
302+
if (response.status >= 400 && response.status < 500 && response.status !== 429) return null
303+
throw new Error(`The site returned status ${response.status} for its robots.txt`)
184304
}
305+
return readTextPrefix(response.body, ROBOTS_PARSE_BYTES)
185306
}

0 commit comments

Comments
 (0)