Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions apps/sim/connectors/website/page.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest'
import { decodePage, robotsHeaderNoindex } from '@/connectors/website/page'

const html = (head: string, text: string) => `<html><head>${head}</head><body>${text}</body></html>`

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('<meta charset="utf-16">', '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('<meta name="description" content="Set charset=windows-1252 in your editor">', 'Crème'),
'utf8'
)
expect(decodePage(body, 'text/html')).toContain('Crème')
const declared = Buffer.from(
html(
'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">',
'Cr\u00e8me'
),
'latin1'
)
expect(decodePage(declared, 'text/html')).toContain('Crème')
})

it('ignores a charset declared inside a comment', () => {
const body = Buffer.from(
html('<!-- <meta charset="windows-1252"> --><meta charset="utf-8">', '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)
})
})
85 changes: 85 additions & 0 deletions apps/sim/connectors/website/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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 = /<meta\s[^>]*>/gi
const TAG_ATTRIBUTE = /([^\s"'=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g

/**
* The charset a page's `<meta>` 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(/<!--[\s\S]*?(-->|$)/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 <meta> 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
* `<meta>` 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) => {
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
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'
})
}
3 changes: 2 additions & 1 deletion apps/sim/connectors/website/robots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
165 changes: 143 additions & 22 deletions apps/sim/connectors/website/site.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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<string, string>,
accept: string,
const ROBOTS_PARSE_BYTES = 500 * 1024

interface SiteRequest {
url: string
headers: Record<string, string>
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<SecureFetchResponse> {
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,
Expand All @@ -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<Uint8Array> | null,
maxBytes: number
): Promise<string> {
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<string, string>
retryOptions?: SecureFetchRetryOptions
}): Promise<string | null> {
const get = (url: string, requestHeaders: Record<string, string>, 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)
}
Loading
Loading