Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(og): pin preview requests to validated IPs (#127)

OKNOTOKfedeac21a475
diff --git a/server/src/__tests__/og-redirects.test.ts b/server/src/__tests__/og-redirects.test.ts
index eac5105..b3c216f 100644
--- a/server/src/__tests__/og-redirects.test.ts
+++ b/server/src/__tests__/og-redirects.test.ts
@@ -1,36 +1,41 @@
/**
- * Open Graph redirect SSRF regression tests.
+ * Open Graph SSRF and redirect regression tests.
*
* Run: node --import tsx --test server/src/__tests__/og-redirects.test.ts
*/
-import { after, afterEach, beforeEach, test } from 'node:test'
import assert from 'node:assert/strict'
+import { after, afterEach, beforeEach, test } from 'node:test'
// Keep Redis lazy during this focused unit test. ogPreview's cache methods are
// stubbed below, so no external service is required.
process.env.CUMORA_RUNTIME_CLIENT = 'http'
+process.env.OPENAI_API_KEY ??= 'test-key'
-const { OgError, ogPreview } = await import('../og.js')
+const { OgError, ogPreview, __setOgFetchDependenciesForTesting } = await import('../og.js')
const { redis, sub } = await import('../redis.js')
-const savedFetch = globalThis.fetch
+type Dependencies = Exclude<Parameters<typeof __setOgFetchDependenciesForTesting>[0], null>
+type RequestTarget = Parameters<Dependencies['request']>[0]
+type OgResponse = Awaited<ReturnType<Dependencies['request']>>
+
const savedWarn = console.warn
const savedRedisGet = redis.get.bind(redis)
const savedRedisSet = redis.set.bind(redis)
-type FetchCall = { url: string; redirect: RequestInit['redirect'] }
-
-function href(input: string | URL | Request): string {
- return typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
-}
-
-function htmlResponse(url: string, html: string): Response {
- const response = new Response(html, {
- status: 200,
- headers: { 'content-type': 'text/html; charset=utf-8' },
- })
- Object.defineProperty(response, 'url', { value: url })
- return response
+function response(
+ status: number,
+ headers: Record<string, string> = {},
+ chunks: Array<string | Buffer> = [],
+ onCancel?: () => void,
+): OgResponse {
+ return {
+ status,
+ headers,
+ body: (async function* () {
+ for (const chunk of chunks) yield Buffer.from(chunk)
+ })(),
+ cancel: () => onCancel?.(),
+ }
}
beforeEach(() => {
@@ -41,7 +46,7 @@ beforeEach(() => {
})
afterEach(() => {
- globalThis.fetch = savedFetch
+ __setOgFetchDependenciesForTesting(null)
console.warn = savedWarn
;(redis as unknown as { get: typeof savedRedisGet }).get = savedRedisGet
;(redis as unknown as { set: typeof savedRedisSet }).set = savedRedisSet
@@ -52,119 +57,165 @@ after(() => {
sub.disconnect()
})
-test('ogPreview follows a validated public redirect manually', async () => {
- const calls: FetchCall[] = []
- globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
- const url = href(input)
- calls.push({ url, redirect: init?.redirect })
- if (url === 'https://8.8.8.8/start') {
- return new Response(null, {
- status: 302,
- headers: { location: '/article' },
- })
- }
- if (url === 'https://8.8.8.8/article') {
- return htmlResponse(url, '<html><head><title>Public article</title></head></html>')
- }
- throw new Error(`unexpected fetch: ${url}`)
- }) as typeof fetch
-
- const result = await ogPreview('https://8.8.8.8/start')
+test('ogPreview pins the connection to the exact public DNS answer it validated', async () => {
+ let lookupCalls = 0
+ const connected: Array<Pick<RequestTarget, 'hostname' | 'address' | 'family'>> = []
+ __setOgFetchDependenciesForTesting({
+ lookup: async hostname => {
+ assert.equal(hostname, 'rebind.example')
+ lookupCalls += 1
+ // A second resolution would simulate a rebound private answer. The
+ // request layer must receive the first address directly instead.
+ return lookupCalls === 1
+ ? [{ address: '93.184.216.34', family: 4 }]
+ : [{ address: '127.0.0.1', family: 4 }]
+ },
+ request: async target => {
+ connected.push({ hostname: target.hostname, address: target.address, family: target.family })
+ return response(200, { 'content-type': 'text/html' }, [
+ '<html><head><title>Pinned article</title></head></html>',
+ ])
+ },
+ })
- assert.equal(result?.title, 'Public article')
- assert.equal(result?.finalUrl, 'https://8.8.8.8/article')
- assert.deepEqual(calls, [
- { url: 'https://8.8.8.8/start', redirect: 'manual' },
- { url: 'https://8.8.8.8/article', redirect: 'manual' },
+ const result = await ogPreview('https://rebind.example/article')
+
+ assert.equal(result?.title, 'Pinned article')
+ assert.equal(lookupCalls, 1)
+ assert.deepEqual(connected, [
+ { hostname: 'rebind.example', address: '93.184.216.34', family: 4 },
])
})
-test('ogPreview rejects a redirect to cloud metadata before the second request', async () => {
- const calls: FetchCall[] = []
- globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
- const url = href(input)
- calls.push({ url, redirect: init?.redirect })
- if (url === 'https://8.8.8.8/redirect-private') {
- return new Response(null, {
- status: 302,
- headers: { location: 'http://169.254.169.254/latest/meta-data/' },
- })
- }
- throw new Error(`private redirect target was fetched: ${url}`)
- }) as typeof fetch
+test('ogPreview rejects a hostname when any DNS answer is private', async () => {
+ let requests = 0
+ __setOgFetchDependenciesForTesting({
+ lookup: async () => [
+ { address: '93.184.216.34', family: 4 },
+ { address: '10.0.0.8', family: 4 },
+ ],
+ request: async () => {
+ requests += 1
+ return response(500)
+ },
+ })
await assert.rejects(
- () => ogPreview('https://8.8.8.8/redirect-private'),
+ () => ogPreview('https://mixed.example/article'),
(error: unknown) => error instanceof OgError && error.status === 403,
)
+ assert.equal(requests, 0)
+})
+
+test('ogPreview revalidates and pins every public redirect hop', async () => {
+ const lookedUp: string[] = []
+ const connected: Array<Pick<RequestTarget, 'hostname' | 'address'>> = []
+ let cancelled = 0
+ __setOgFetchDependenciesForTesting({
+ lookup: async hostname => {
+ lookedUp.push(hostname)
+ return hostname === 'start.example'
+ ? [{ address: '93.184.216.34', family: 4 }]
+ : [{ address: '1.1.1.1', family: 4 }]
+ },
+ request: async target => {
+ connected.push({ hostname: target.hostname, address: target.address })
+ if (target.hostname === 'start.example') {
+ return response(302, { location: 'https://cdn.example/article' }, [], () => { cancelled += 1 })
+ }
+ return response(200, { 'content-type': 'text/html' }, [
+ '<html><head><title>Public article</title></head></html>',
+ ])
+ },
+ })
+
+ const result = await ogPreview('https://start.example/short')
- assert.deepEqual(calls, [
- { url: 'https://8.8.8.8/redirect-private', redirect: 'manual' },
+ assert.equal(result?.title, 'Public article')
+ assert.equal(result?.finalUrl, 'https://cdn.example/article')
+ assert.deepEqual(lookedUp, ['start.example', 'cdn.example'])
+ assert.deepEqual(connected, [
+ { hostname: 'start.example', address: '93.184.216.34' },
+ { hostname: 'cdn.example', address: '1.1.1.1' },
])
+ assert.equal(cancelled, 1)
})
-test('ogPreview rejects a redirect to an RFC1918 host before the second request', async () => {
- const calls: FetchCall[] = []
- globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
- const url = href(input)
- calls.push({ url, redirect: init?.redirect })
- if (url === 'https://8.8.8.8/redirect-rfc1918') {
- return new Response(null, {
- status: 307,
- headers: { location: 'http://10.0.0.1/internal' },
- })
- }
- throw new Error(`private redirect target was fetched: ${url}`)
- }) as typeof fetch
+test('ogPreview rejects a redirect to cloud metadata before the second request', async () => {
+ const connected: string[] = []
+ __setOgFetchDependenciesForTesting({
+ lookup: async hostname => hostname === 'start.example'
+ ? [{ address: '93.184.216.34', family: 4 }]
+ : [{ address: '169.254.169.254', family: 4 }],
+ request: async target => {
+ connected.push(target.address)
+ return response(302, { location: 'http://metadata.internal/latest' })
+ },
+ })
await assert.rejects(
- () => ogPreview('https://8.8.8.8/redirect-rfc1918'),
+ () => ogPreview('https://start.example/redirect-private'),
(error: unknown) => error instanceof OgError && error.status === 403,
)
+ assert.deepEqual(connected, ['93.184.216.34'])
+})
- assert.deepEqual(calls, [
- { url: 'https://8.8.8.8/redirect-rfc1918', redirect: 'manual' },
- ])
+test('ogPreview blocks alternate private IP literals before DNS or connect', async () => {
+ for (const url of [
+ 'http://127.0.0.1/article',
+ 'http://2130706433/article',
+ 'http://[::1]/article',
+ 'http://[::ffff:7f00:1]/article',
+ 'http://[64:ff9b::7f00:1]/article',
+ ]) {
+ let lookups = 0
+ let requests = 0
+ __setOgFetchDependenciesForTesting({
+ lookup: async () => { lookups += 1; return [] },
+ request: async () => { requests += 1; return response(500) },
+ })
+
+ await assert.rejects(
+ () => ogPreview(url),
+ (error: unknown) => error instanceof OgError && error.status === 403,
+ url,
+ )
+ assert.equal(lookups, 0, url)
+ assert.equal(requests, 0, url)
+ }
})
test('ogPreview rejects a redirect to a non-http protocol', async () => {
- const calls: FetchCall[] = []
- globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
- const url = href(input)
- calls.push({ url, redirect: init?.redirect })
- if (url === 'https://8.8.8.8/redirect-file') {
- return new Response(null, {
- status: 302,
- headers: { location: 'file:///etc/passwd' },
- })
- }
- throw new Error(`non-http redirect target was fetched: ${url}`)
- }) as typeof fetch
+ let requests = 0
+ __setOgFetchDependenciesForTesting({
+ lookup: async () => [{ address: '93.184.216.34', family: 4 }],
+ request: async () => {
+ requests += 1
+ return response(302, { location: 'file:///etc/passwd' })
+ },
+ })
await assert.rejects(
- () => ogPreview('https://8.8.8.8/redirect-file'),
+ () => ogPreview('https://start.example/redirect-file'),
(error: unknown) => error instanceof OgError && error.status === 400,
)
-
- assert.deepEqual(calls, [
- { url: 'https://8.8.8.8/redirect-file', redirect: 'manual' },
- ])
+ assert.equal(requests, 1)
})
test('ogPreview stops after the bounded redirect limit', async () => {
- const calls: FetchCall[] = []
- globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
- const url = href(input)
- calls.push({ url, redirect: init?.redirect })
- return new Response(null, {
- status: 302,
- headers: { location: `/loop/${calls.length}` },
- })
- }) as typeof fetch
+ let requests = 0
+ let cancelled = 0
+ __setOgFetchDependenciesForTesting({
+ lookup: async () => [{ address: '93.184.216.34', family: 4 }],
+ request: async () => {
+ requests += 1
+ return response(302, { location: `/loop/${requests}` }, [], () => { cancelled += 1 })
+ },
+ })
- const result = await ogPreview('https://8.8.8.8/loop/0')
+ const result = await ogPreview('https://loop.example/loop/0')
assert.equal(result, null)
- assert.equal(calls.length, 6)
- assert.ok(calls.every(({ redirect }) => redirect === 'manual'))
+ assert.equal(requests, 6)
+ assert.equal(cancelled, 6)
})
diff --git a/server/src/og.ts b/server/src/og.ts
index e0b9eff..8f9e98a 100644
--- a/server/src/og.ts
+++ b/server/src/og.ts
@@ -18,7 +18,9 @@
*/
import { Buffer } from 'node:buffer'
import { lookup as dnsLookup } from 'node:dns/promises'
-import { isIP } from 'node:net'
+import { request as httpRequest, type IncomingHttpHeaders } from 'node:http'
+import { type RequestOptions as HttpsRequestOptions, request as httpsRequest } from 'node:https'
+import { BlockList, isIP } from 'node:net'
import { redis } from './redis.js'
const CACHE_PREFIX = 'cumora:og:'
@@ -43,6 +45,69 @@ const MAX_REDIRECTS = 5
* this threshold is crossed. */
const MAX_BYTES = 1024 * 1024
+interface ResolvedAddress {
+ address: string
+ family: 4 | 6
+}
+
+interface ResolvedOgTarget {
+ url: URL
+ hostname: string
+ address: string
+ family: 4 | 6
+}
+
+interface OgHttpResponse {
+ status: number
+ headers: IncomingHttpHeaders
+ body: AsyncIterable<Uint8Array>
+ cancel(): void
+}
+
+interface OgFetchDependencies {
+ lookup(hostname: string): Promise<readonly ResolvedAddress[]>
+ request(target: ResolvedOgTarget, signal: AbortSignal): Promise<OgHttpResponse>
+}
+
+const blockedIpv4 = new BlockList()
+for (const [network, prefix] of [
+ ['0.0.0.0', 8],
+ ['10.0.0.0', 8],
+ ['100.64.0.0', 10],
+ ['127.0.0.0', 8],
+ ['169.254.0.0', 16],
+ ['172.16.0.0', 12],
+ ['192.0.0.0', 24],
+ ['192.0.2.0', 24],
+ ['192.88.99.0', 24],
+ ['192.168.0.0', 16],
+ ['198.18.0.0', 15],
+ ['198.51.100.0', 24],
+ ['203.0.113.0', 24],
+ ['224.0.0.0', 4],
+ ['240.0.0.0', 4],
+] as const) {
+ blockedIpv4.addSubnet(network, prefix, 'ipv4')
+}
+
+const blockedIpv6 = new BlockList()
+for (const [network, prefix] of [
+ ['::', 96],
+ ['::ffff:0:0', 96],
+ ['64:ff9b::', 96],
+ ['64:ff9b:1::', 48],
+ ['100::', 64],
+ ['2001::', 23],
+ ['2001:db8::', 32],
+ ['2002::', 16],
+ ['fc00::', 7],
+ ['fe80::', 10],
+ ['fec0::', 10],
+ ['ff00::', 8],
+] as const) {
+ blockedIpv6.addSubnet(network, prefix, 'ipv6')
+}
+
export interface OgResult {
url: string
title?: string
@@ -86,14 +151,9 @@ export async function ogPreview(rawUrl: string): Promise<OgResult | null> {
try { return JSON.parse(cached) as OgResult } catch { /* corrupt entry, refetch */ }
}
- // DNS check happens AFTER URL validation but BEFORE fetch — protects
- // against rebinding / private IP ranges that didn't show in the literal
- // hostname (e.g. someone resolves to 10.0.0.1).
- await assertPublicHost(new URL(url).hostname)
-
let result: OgResult | null = null
try {
- result = await fetchAndParse(url)
+ result = await fetchAndParse(url, ogFetchDependenciesOverride ?? productionDependencies)
} catch (e) {
if (e instanceof OgUrlError) throw e
// Network or parse failure — cache the miss briefly so we don't hammer
@@ -126,80 +186,190 @@ function validateUrlString(raw: string): string {
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
throw new OgUrlError('only http(s) urls are supported')
}
+ if (u.username || u.password) throw new OgUrlError('url credentials are not supported')
// Drop fragment for cache hit-rate (#section doesn't change OG metadata).
u.hash = ''
return u.toString()
}
-/** Block private / loopback / link-local IP ranges. Resolves the hostname
- * first; if any answer is a private address, refuse. Hostname literals
- * that ARE IPs are checked directly. */
-async function assertPublicHost(host: string): Promise<void> {
- // Hostname literal is itself an IP — check directly, no DNS.
- if (isIP(host)) {
- if (isBlockedIp(host)) throw new OgUrlError('blocked private host', 403)
- return
- }
- if (!host || host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local')) {
+function normalizedHostname(url: URL): string {
+ const hostname = url.hostname.startsWith('[') && url.hostname.endsWith(']')
+ ? url.hostname.slice(1, -1)
+ : url.hostname
+ return hostname.toLowerCase().replace(/\.$/, '')
+}
+
+function isBlockedIp(ip: string): boolean {
+ const family = isIP(ip)
+ if (family === 4) return blockedIpv4.check(ip, 'ipv4')
+ if (family === 6) return blockedIpv6.check(ip, 'ipv6')
+ return true
+}
+
+function isReservedHostname(hostname: string): boolean {
+ return hostname === 'localhost' || hostname.endsWith('.localhost') ||
+ hostname.endsWith('.local') || hostname === 'home.arpa' || hostname.endsWith('.home.arpa')
+}
+
+async function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) throw signal.reason ?? new Error('aborted')
+ return await new Promise<T>((resolve, reject) => {
+ const cleanup = () => signal.removeEventListener('abort', onAbort)
+ const onAbort = () => {
+ cleanup()
+ reject(signal.reason ?? new Error('aborted'))
+ }
+ signal.addEventListener('abort', onAbort, { once: true })
+ promise.then(
+ value => { cleanup(); resolve(value) },
+ error => { cleanup(); reject(error) },
+ )
+ })
+}
+
+async function resolvePublicTarget(
+ url: URL,
+ signal: AbortSignal,
+ lookup: OgFetchDependencies['lookup'],
+): Promise<ResolvedOgTarget> {
+ const hostname = normalizedHostname(url)
+ if (!hostname || isReservedHostname(hostname)) {
throw new OgUrlError('blocked private host', 403)
}
+
+ const literalFamily = isIP(hostname)
+ let addresses: readonly ResolvedAddress[]
try {
- const addresses = await dnsLookup(host, { all: true })
- if (addresses.length === 0 || addresses.some(({ address }) => isBlockedIp(address))) {
+ addresses = literalFamily
+ ? [{ address: hostname, family: literalFamily as 4 | 6 }]
+ : await abortable(lookup(hostname), signal)
+ } catch (error) {
+ if (signal.aborted) throw signal.reason ?? error
+ if (error instanceof OgUrlError) throw error
+ throw new OgUrlError('dns lookup failed', 400)
+ }
+
+ if (addresses.length === 0) throw new OgUrlError('dns lookup failed', 400)
+ for (const answer of addresses) {
+ if ((answer.family !== 4 && answer.family !== 6) ||
+ isIP(answer.address) !== answer.family || isBlockedIp(answer.address)) {
throw new OgUrlError('blocked private host', 403)
}
- } catch (e) {
- if (e instanceof OgUrlError) throw e
- throw new OgUrlError('dns lookup failed', 400)
}
+
+ const selected = addresses[0]
+ return { url, hostname, address: selected.address, family: selected.family }
}
-function isBlockedIp(ip: string): boolean {
- // IPv4
- if (ip.startsWith('10.') || ip.startsWith('127.') || ip.startsWith('169.254.') ||
- ip.startsWith('192.168.') || ip === '0.0.0.0' ||
- /^172\.(1[6-9]|2\d|3[01])\./.test(ip) ||
- // GCP / AWS / Azure metadata endpoints
- ip === '169.254.169.254') {
- return true
- }
- // IPv6
- if (ip === '::1' || ip === '::' ||
- ip.toLowerCase().startsWith('fe80:') ||
- ip.toLowerCase().startsWith('fc') || ip.toLowerCase().startsWith('fd')) {
- return true
+function requestPinnedOg(target: ResolvedOgTarget, signal: AbortSignal): Promise<OgHttpResponse> {
+ return new Promise((resolve, reject) => {
+ const options: HttpsRequestOptions = {
+ protocol: target.url.protocol,
+ hostname: target.address,
+ family: target.family,
+ port: target.url.port ? Number(target.url.port) : undefined,
+ path: `${target.url.pathname}${target.url.search}`,
+ method: 'GET',
+ agent: false,
+ signal,
+ headers: {
+ host: target.url.host,
+ 'user-agent': 'Mozilla/5.0 (compatible; CumoraBot/1.0; +https://cumora.ai)',
+ accept: 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.5',
+ 'accept-language': 'en-US,en;q=0.9',
+ },
+ }
+ if (target.url.protocol === 'https:' && !isIP(target.hostname)) {
+ options.servername = target.hostname
+ }
+
+ const onResponse = (response: import('node:http').IncomingMessage) => {
+ resolve({
+ status: response.statusCode ?? 0,
+ headers: response.headers,
+ body: response,
+ cancel: () => response.destroy(),
+ })
+ }
+ const request = target.url.protocol === 'https:'
+ ? httpsRequest(options, onResponse)
+ : httpRequest(options, onResponse)
+ request.once('error', reject)
+ request.end()
+ })
+}
+
+const productionDependencies: OgFetchDependencies = {
+ lookup: async hostname => {
+ const answers = await dnsLookup(hostname, { all: true, verbatim: true })
+ return answers.map(({ address, family }) => ({ address, family: family as 4 | 6 }))
+ },
+ request: requestPinnedOg,
+}
+
+let ogFetchDependenciesOverride: OgFetchDependencies | null = null
+
+function headerValue(headers: IncomingHttpHeaders, name: string): string | undefined {
+ const value = headers[name]
+ return Array.isArray(value) ? value[0] : value
+}
+
+async function readBodyWithCap(
+ response: OgHttpResponse,
+ signal: AbortSignal,
+): Promise<Buffer | null> {
+ const chunks: Buffer[] = []
+ let total = 0
+ const iterator = response.body[Symbol.asyncIterator]()
+ for (;;) {
+ const { done, value } = await abortable(iterator.next(), signal)
+ if (done) break
+ if (!value) continue
+ const chunk = Buffer.from(value)
+ total += chunk.byteLength
+ if (total > MAX_BYTES) {
+ response.cancel()
+ return null
+ }
+ chunks.push(chunk)
}
- return false
+ return Buffer.concat(chunks, total)
}
-async function fetchAndParse(url: string): Promise<OgResult> {
+async function fetchAndParse(url: string, dependencies: OgFetchDependencies): Promise<OgResult> {
const ac = new AbortController()
const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS)
try {
- const { response: res, finalUrl } = await fetchWithValidatedRedirects(url, ac.signal)
- if (!res.ok) throw new OgError(`upstream ${res.status}`, 502)
+ const { response: res, finalUrl } = await fetchWithValidatedRedirects(url, ac.signal, dependencies)
+ if (res.status < 200 || res.status >= 300) {
+ res.cancel()
+ throw new OgError(`upstream ${res.status}`, 502)
+ }
- const ct = (res.headers.get('content-type') ?? '').toLowerCase()
+ const ct = (headerValue(res.headers, 'content-type') ?? '').toLowerCase()
if (!ct.includes('text/html') && !ct.includes('xhtml')) {
+ res.cancel()
throw new OgError(`unsupported content-type: ${ct || 'unknown'}`, 415)
}
- // Size-bounded streamed read. fetch() in Node can run unbounded if the
- // upstream sends a giant body; we cancel as soon as we've collected
- // enough to be sure the `<head>` ended.
- const reader = res.body?.getReader()
- if (!reader) throw new OgError('no response body', 502)
- const chunks: Uint8Array[] = []
- let total = 0
- while (total < MAX_BYTES) {
- const { value, done } = await reader.read()
- if (done) break
- if (!value) continue
- chunks.push(value)
- total += value.length
+ const contentLength = headerValue(res.headers, 'content-length')
+ if (contentLength !== undefined) {
+ const declared = Number(contentLength)
+ if (Number.isFinite(declared) && declared > MAX_BYTES) {
+ res.cancel()
+ throw new OgError('upstream body too large', 413)
+ }
+ }
+
+ let body: Buffer | null
+ try {
+ body = await readBodyWithCap(res, ac.signal)
+ } catch (error) {
+ res.cancel()
+ throw error
}
- await reader.cancel().catch(() => { /* ignore — upstream may already be done */ })
- const html = Buffer.concat(chunks).toString('utf8')
+ if (!body) throw new OgError('upstream body too large', 413)
+ const html = body.toString('utf8')
const og: OgResult = { url, finalUrl }
const title = pickMetaContent(html, 'og:title') ?? pickMetaContent(html, 'twitter:title') ?? pickHtmlTitle(html)
@@ -219,39 +389,32 @@ async function fetchAndParse(url: string): Promise<OgResult> {
async function fetchWithValidatedRedirects(
url: string,
signal: AbortSignal,
-): Promise<{ response: Response; finalUrl: string }> {
+ dependencies: OgFetchDependencies,
+): Promise<{ response: OgHttpResponse; finalUrl: string }> {
let currentUrl = url
for (let redirectCount = 0; ; redirectCount += 1) {
- const response = await fetch(currentUrl, {
- signal,
- // Automatic following would bypass assertPublicHost for every target
- // after the first. Resolve and validate each Location ourselves.
- redirect: 'manual',
- headers: {
- // A descriptive UA + Accept header improves the OG hit rate (some
- // sites serve a stripped page to bots that look like cURL).
- 'user-agent': 'Mozilla/5.0 (compatible; CumoraBot/1.0; +https://cumora.ai)',
- 'accept': 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.5',
- 'accept-language': 'en-US,en;q=0.9',
- },
- })
+ const parsedUrl = new URL(currentUrl)
+ const target = await resolvePublicTarget(parsedUrl, signal, dependencies.lookup)
+ const response = await abortable(dependencies.request(target, signal), signal)
if (!isRedirectStatus(response.status)) return { response, finalUrl: currentUrl }
- const location = response.headers.get('location')
- if (response.body) {
- await response.body.cancel().catch(() => { /* ignore cleanup failures */ })
- }
+ const location = headerValue(response.headers, 'location')
+ response.cancel()
if (!location) throw new OgError('redirect missing location', 502)
if (redirectCount >= MAX_REDIRECTS) throw new OgError('too many redirects', 502)
const nextUrl = resolveRedirectUrl(location, currentUrl)
- await assertPublicHost(new URL(nextUrl).hostname)
currentUrl = nextUrl
}
}
+/** Test hook for deterministic DNS answers and socket targets. */
+export function __setOgFetchDependenciesForTesting(dependencies: OgFetchDependencies | null): void {
+ ogFetchDependenciesOverride = dependencies
+}
+
function isRedirectStatus(status: number): boolean {
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
}