1+ import type { HttpRedirectPolicy } from '@/lib/core/security/http-redirect-policy'
12import { validateExternalUrl } from '@/lib/core/security/input-validation'
3+ import type { SecureFetchResponse } from '@/lib/core/security/input-validation.server'
24import {
35 type SecureFetchRetryOptions ,
46 secureFetchWithRetry ,
@@ -139,34 +141,50 @@ const ATTEMPT_TIMEOUT_MS = 30_000
139141const 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