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(agents): validate image fetch targets before connecting (#83)

OKNOTOK71de2b5f5018
diff --git a/server/src/__integration__/agent-error-paths.test.ts b/server/src/__integration__/agent-error-paths.test.ts
index 139777c..074ce40 100644
--- a/server/src/__integration__/agent-error-paths.test.ts
+++ b/server/src/__integration__/agent-error-paths.test.ts
@@ -13,8 +13,8 @@
* drives the rest of the turn.
* - image generation via `r.data[0].url` (the upstream returned a URL
* instead of inline b64): `generateAndUploadImage` fetches the URL
- * and uploads the buffer; we mock globalThis.fetch to return a known
- * PNG so the test stays hermetic.
+ * and uploads the buffer; we inject a known PNG at the safe image-fetch
+ * boundary so the test stays hermetic.
*
* Run via:
* INTEGRATION_DATABASE_URL=postgres://$USER@localhost:5432/cumora_test \
@@ -30,24 +30,24 @@ import { __setLlmClientOverrideForTesting } from '../llm.js'
import { __setPodToolOverrideForTesting } from '../agents/runtime/pod-tools.js'
import { runAgentTurn } from '../agents/turn.js'
import { runCli } from '../agents/cli.js'
+import { __setImageFetchOverrideForTesting } from '../agents/image-fetcher.js'
import type { ToolResult } from '../agents/tools-shared.js'
before(async () => {
await ensureSchemaOnce()
})
-const realFetch = globalThis.fetch
beforeEach(async () => {
await resetAllTables()
__setLlmClientOverrideForTesting(null)
__setPodToolOverrideForTesting(null)
- globalThis.fetch = realFetch
+ __setImageFetchOverrideForTesting(null)
})
after(async () => {
__setLlmClientOverrideForTesting(null)
__setPodToolOverrideForTesting(null)
- globalThis.fetch = realFetch
+ __setImageFetchOverrideForTesting(null)
await teardownAll()
})
@@ -396,15 +396,21 @@ test('[integration] image_url fetch fail on attempt 0 → retry with images stri
test('[integration] generateAndUploadImage: r.data[0].url fallback — fetches remote bytes and persists attachment', async () => {
// When the image API returns a URL instead of inline b64, cumora's
// `generateAndUploadImage` fetches the URL and uploads the resulting
- // buffer. We mock globalThis.fetch to return a known PNG byte sequence
- // so the test stays hermetic.
+ // buffer. Inject at the safe-fetch boundary so this call-site test stays
+ // hermetic while image-fetcher.test.ts owns DNS/redirect policy coverage.
const { agentId, conversationId } = await seedDirect()
let fetchedUrl: string | null = null
- globalThis.fetch = (async (input: unknown) => {
- fetchedUrl = typeof input === 'string' ? input : String(input)
- return new Response(TINY_PNG_BYTES, { status: 200, headers: { 'content-type': 'image/png' } })
- }) as typeof globalThis.fetch
+ __setImageFetchOverrideForTesting(async input => {
+ fetchedUrl = input
+ return {
+ ok: true,
+ buffer: TINY_PNG_BYTES,
+ mime: 'image/png',
+ bytes: TINY_PNG_BYTES.length,
+ finalUrl: input,
+ }
+ })
__setLlmClientOverrideForTesting(async () => {
return {
diff --git a/server/src/__tests__/image-fetcher.test.ts b/server/src/__tests__/image-fetcher.test.ts
new file mode 100644
index 0000000..5855f32
--- /dev/null
+++ b/server/src/__tests__/image-fetcher.test.ts
@@ -0,0 +1,187 @@
+/**
+ * Regression tests for agent image egress.
+ *
+ * Run: node --import tsx --test server/src/__tests__/image-fetcher.test.ts
+ */
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { _fetchImageBytesForTest } from '../agents/image-fetcher.js'
+
+type Dependencies = Parameters<typeof _fetchImageBytesForTest>[2]
+type RequestTarget = Parameters<Dependencies['request']>[0]
+type ImageResponse = Awaited<ReturnType<Dependencies['request']>>
+
+function response(
+ status: number,
+ headers: Record<string, string> = {},
+ chunks: Array<string | Buffer> = [],
+ onCancel?: () => void,
+): ImageResponse {
+ return {
+ status,
+ headers,
+ body: (async function* () {
+ for (const chunk of chunks) yield Buffer.from(chunk)
+ })(),
+ cancel: () => onCancel?.(),
+ }
+}
+
+test('blocks private, metadata, alternate IPv4, and IPv6 literals before connecting', async () => {
+ for (const url of [
+ 'http://127.0.0.1/image.png',
+ 'http://100.64.0.1/image.png',
+ 'http://169.254.169.254/latest/meta-data',
+ 'http://198.18.0.1/image.png',
+ 'http://2130706433/image.png',
+ 'http://[::1]/image.png',
+ 'http://[::ffff:7f00:1]/image.png',
+ 'http://[64:ff9b::7f00:1]/image.png',
+ ]) {
+ let lookups = 0
+ let requests = 0
+ const result = await _fetchImageBytesForTest(url, {}, {
+ lookup: async () => { lookups += 1; return [] },
+ request: async () => { requests += 1; return response(500) },
+ })
+ assert.deepEqual(result, { ok: false, reason: 'blocked' }, url)
+ assert.equal(lookups, 0, `literal ${url} must not use DNS`)
+ assert.equal(requests, 0, `literal ${url} must be rejected before connect`)
+ }
+})
+
+test('blocks hostnames when any DNS answer is private', async () => {
+ for (const answers of [
+ [{ address: '10.0.0.8', family: 4 as const }],
+ [
+ { address: '93.184.216.34', family: 4 as const },
+ { address: '192.168.1.20', family: 4 as const },
+ ],
+ [{ address: 'fc00::1234', family: 6 as const }],
+ ]) {
+ let requests = 0
+ const result = await _fetchImageBytesForTest('https://images.example/avatar.png', {}, {
+ lookup: async hostname => {
+ assert.equal(hostname, 'images.example')
+ return answers
+ },
+ request: async () => { requests += 1; return response(500) },
+ })
+ assert.deepEqual(result, { ok: false, reason: 'blocked' })
+ assert.equal(requests, 0, 'a mixed/private answer set must be rejected before connect')
+ }
+})
+
+test('revalidates redirects and never connects to a private redirect target', async () => {
+ const connected: string[] = []
+ let cancelled = 0
+ const result = await _fetchImageBytesForTest('https://images.example/start', {}, {
+ lookup: async hostname => hostname === 'images.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' }, [], () => { cancelled += 1 })
+ },
+ })
+
+ assert.deepEqual(result, { ok: false, reason: 'blocked' })
+ assert.deepEqual(connected, ['93.184.216.34'])
+ assert.equal(cancelled, 1, 'redirect response must be closed before validating the next hop')
+})
+
+test('pins each public redirect hop to the address that was validated', async () => {
+ const connected: Array<Pick<RequestTarget, 'hostname' | 'address' | 'family'>> = []
+ const lookedUp: string[] = []
+ const result = await _fetchImageBytesForTest('https://images.example/start', {}, {
+ lookup: async hostname => {
+ lookedUp.push(hostname)
+ return hostname === 'images.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, family: target.family })
+ if (target.hostname === 'images.example') {
+ return response(302, { location: 'https://cdn.example/final.png' })
+ }
+ return response(200, { 'content-type': 'image/png' }, ['safe-image'])
+ },
+ })
+
+ assert.deepEqual(lookedUp, ['images.example', 'cdn.example'])
+ assert.deepEqual(connected, [
+ { hostname: 'images.example', address: '93.184.216.34', family: 4 },
+ { hostname: 'cdn.example', address: '1.1.1.1', family: 4 },
+ ])
+ assert.equal(result.ok, true)
+ if (result.ok) {
+ assert.equal(result.buffer.toString(), 'safe-image')
+ assert.equal(result.mime, 'image/png')
+ assert.equal(result.finalUrl, 'https://cdn.example/final.png')
+ }
+})
+
+test('blocks redirects to unsupported schemes and redirect loops', async () => {
+ const publicLookup: Dependencies['lookup'] = async () => [
+ { address: '93.184.216.34', family: 4 },
+ ]
+
+ const badScheme = await _fetchImageBytesForTest('https://images.example/start', {}, {
+ lookup: publicLookup,
+ request: async () => response(302, { location: 'file:///etc/passwd' }),
+ })
+ assert.deepEqual(badScheme, { ok: false, reason: 'blocked' })
+
+ let requests = 0
+ const redirectLoop = await _fetchImageBytesForTest('https://images.example/start', {
+ maxRedirects: 1,
+ }, {
+ lookup: publicLookup,
+ request: async () => {
+ requests += 1
+ return response(302, { location: '/again' })
+ },
+ })
+ assert.deepEqual(redirectLoop, { ok: false, reason: 'blocked' })
+ assert.equal(requests, 2)
+})
+
+test('enforces content type, declared size, streamed size, and timeout centrally', async () => {
+ const lookup: Dependencies['lookup'] = async () => [
+ { address: '93.184.216.34', family: 4 },
+ ]
+
+ const badType = await _fetchImageBytesForTest('https://images.example/file', {}, {
+ lookup,
+ request: async () => response(200, { 'content-type': 'text/plain' }, ['not-image']),
+ })
+ assert.deepEqual(badType, { ok: false, reason: 'bad-type' })
+
+ const declaredTooLarge = await _fetchImageBytesForTest('https://images.example/file', {
+ maxBytes: 4,
+ }, {
+ lookup,
+ request: async () => response(200, {
+ 'content-type': 'image/png',
+ 'content-length': '5',
+ }, ['small']),
+ })
+ assert.deepEqual(declaredTooLarge, { ok: false, reason: 'too-large' })
+
+ const streamedTooLarge = await _fetchImageBytesForTest('https://images.example/file', {
+ maxBytes: 4,
+ }, {
+ lookup,
+ request: async () => response(200, { 'content-type': 'image/png' }, ['12', '345']),
+ })
+ assert.deepEqual(streamedTooLarge, { ok: false, reason: 'too-large' })
+
+ const timedOut = await _fetchImageBytesForTest('https://images.example/file', {
+ timeoutMs: 20,
+ }, {
+ lookup: async () => await new Promise<never>(() => {}),
+ request: async () => response(500),
+ })
+ assert.deepEqual(timedOut, { ok: false, reason: 'timeout' })
+})
diff --git a/server/src/agents/cli.ts b/server/src/agents/cli.ts
index f41ef6f..3ebadbd 100644
--- a/server/src/agents/cli.ts
+++ b/server/src/agents/cli.ts
@@ -13,6 +13,7 @@ import { pool } from '../db/pool.js'
import { storage, freshenAttachmentUrl, type StoredAttachment } from '../storage.js'
import { env } from '../env.js'
import type { CliResult, CliSideEffect } from './cli-result.js'
+import { fetchImageBytes } from './image-fetcher.js'
import { stripLoneSurrogates } from './text-safety.js'
import {
asMemorySource,
@@ -2137,8 +2138,12 @@ async function generateAndUploadImage(opts: {
if (b64) {
buf = Buffer.from(b64, 'base64')
} else if (remoteUrl) {
- const fetched = await fetch(remoteUrl)
- buf = Buffer.from(await fetched.arrayBuffer())
+ const fetched = await fetchImageBytes(remoteUrl, {
+ maxBytes: 20 * 1024 * 1024,
+ timeoutMs: 30_000,
+ })
+ if (!fetched.ok) throw new Error(`image API download failed (${fetched.reason})`)
+ buf = fetched.buffer
} else {
throw new Error('image API returned no data')
}
@@ -3405,13 +3410,20 @@ async function setAgentAvatarFromUrl(args: {
throw new Error('avatar source must be an http(s) URL')
}
const MAX_BYTES = 8 * 1024 * 1024 // 8MB ceiling for portraits
- const fetched = await fetch(args.sourceUrl, { signal: AbortSignal.timeout(15_000) })
- if (!fetched.ok) throw new Error(`source URL returned ${fetched.status}`)
- const mime = (fetched.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase()
- if (!mime.startsWith('image/')) throw new Error(`source URL is not an image (content-type: ${mime || 'unknown'})`)
- const buf = Buffer.from(await fetched.arrayBuffer())
+ const fetched = await fetchImageBytes(args.sourceUrl, {
+ maxBytes: MAX_BYTES,
+ timeoutMs: 15_000,
+ })
+ if (!fetched.ok) {
+ if (fetched.reason === 'http') throw new Error(`source URL returned ${fetched.status ?? 'an error'}`)
+ if (fetched.reason === 'bad-type') throw new Error('source URL is not an image')
+ if (fetched.reason === 'too-large') throw new Error(`source image exceeds ${MAX_BYTES} bytes`)
+ if (fetched.reason === 'blocked') throw new Error('source URL is not allowed')
+ if (fetched.reason === 'timeout') throw new Error('source URL timed out')
+ throw new Error('source URL could not be fetched')
+ }
+ const { buffer: buf, mime } = fetched
if (buf.length === 0) throw new Error('source image is empty')
- if (buf.length > MAX_BYTES) throw new Error(`source image too large (${buf.length} > ${MAX_BYTES})`)
// Pick a sensible extension from the mime so the stored object has a
// useful filename and the Worker serves the right content-type.
diff --git a/server/src/agents/image-fetcher.ts b/server/src/agents/image-fetcher.ts
index a07edb9..ab52ea2 100644
--- a/server/src/agents/image-fetcher.ts
+++ b/server/src/agents/image-fetcher.ts
@@ -17,6 +17,13 @@
* fetch failure on our side → we drop the image silently → turn still runs
* (the model loses one face, gains 0% chance of bricking).
*
+ * Security boundary: every image download in the agent runtime should use
+ * `fetchImageBytes`. It resolves every hostname, rejects the entire answer
+ * set when any address is non-public, then connects directly to one of the
+ * validated addresses. Redirects are followed manually and repeat the same
+ * validation. This closes both DNS rebinding/TOCTOU and redirect pivots into
+ * loopback, link-local, metadata, or private-network services.
+ *
* Tradeoff vs. HEAD-probe + raw URL: ~33% larger request body to OpenAI
* (base64 overhead). Image *tokens* are identical (computed from decoded
* pixel dimensions, not wire format), so billing is unchanged; only the
@@ -29,13 +36,71 @@
* memory bounded at ~100 MB via byte-aware eviction.
*/
+import { Buffer } from 'node:buffer'
+import { lookup as dnsLookup } from 'node:dns/promises'
+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'
+
+type ImageFetchFailureReason = 'http' | 'timeout' | 'too-large' | 'bad-type' | 'blocked' | 'error'
+
interface MaterializeOk { ok: true; dataUrl: string; bytes: number }
-interface MaterializeErr {
+interface ImageFetchFailure {
ok: false
- reason: 'http' | 'timeout' | 'too-large' | 'bad-type' | 'blocked' | 'error'
+ reason: ImageFetchFailureReason
status?: number
}
-export type MaterializeResult = MaterializeOk | MaterializeErr
+export type MaterializeResult = MaterializeOk | ImageFetchFailure
+
+export interface ImageBytesOk {
+ ok: true
+ buffer: Buffer
+ mime: string
+ bytes: number
+ finalUrl: string
+}
+export type ImageBytesResult = ImageBytesOk | ImageFetchFailure
+
+export interface ImageFetchOptions {
+ maxBytes?: number
+ timeoutMs?: number
+ maxRedirects?: number
+}
+
+interface ResolvedAddress {
+ address: string
+ family: 4 | 6
+}
+
+interface ResolvedImageTarget {
+ url: URL
+ hostname: string
+ address: string
+ family: 4 | 6
+}
+
+interface ImageHttpResponse {
+ status: number
+ headers: IncomingHttpHeaders
+ body: AsyncIterable<Uint8Array>
+ cancel(): void
+}
+
+interface ImageFetchDependencies {
+ lookup(hostname: string): Promise<readonly ResolvedAddress[]>
+ request(target: ResolvedImageTarget, signal: AbortSignal): Promise<ImageHttpResponse>
+}
+
+interface RequiredImageFetchOptions {
+ maxBytes: number
+ timeoutMs: number
+ maxRedirects: number
+}
+
+type ImageFetchOverride = (
+ url: string,
+ options: ImageFetchOptions,
+) => Promise<ImageBytesResult>
/** 10 MB per image. OpenAI's per-image limits vary by model but are
* typically <=20 MB on the wire; staying well under avoids edge rejection
@@ -47,12 +112,55 @@ const MAX_IMAGE_BYTES = 10 * 1024 * 1024
* push us over. */
const MAX_CACHE_BYTES = 100 * 1024 * 1024
const FETCH_TIMEOUT_MS = 5000
+const MAX_REDIRECTS = 5
const SUCCESS_TTL_MS = 10 * 60_000
const FAILURE_TTL_MS = 60_000
+const blockedIpv4 = new BlockList()
+for (const [network, prefix] of [
+ ['0.0.0.0', 8], // current network / unspecified
+ ['10.0.0.0', 8], // private
+ ['100.64.0.0', 10], // carrier-grade NAT
+ ['127.0.0.0', 8], // loopback
+ ['169.254.0.0', 16], // link-local and cloud metadata
+ ['172.16.0.0', 12], // private
+ ['192.0.0.0', 24], // IETF protocol assignments
+ ['192.0.2.0', 24], // documentation
+ ['192.88.99.0', 24], // deprecated 6to4 relay anycast
+ ['192.168.0.0', 16], // private
+ ['198.18.0.0', 15], // benchmarking
+ ['198.51.100.0', 24], // documentation
+ ['203.0.113.0', 24], // documentation
+ ['224.0.0.0', 4], // multicast
+ ['240.0.0.0', 4], // reserved / broadcast
+] as const) {
+ blockedIpv4.addSubnet(network, prefix, 'ipv4')
+}
+
+const blockedIpv6 = new BlockList()
+for (const [network, prefix] of [
+ ['::', 96], // unspecified, loopback, IPv4-compatible
+ ['::ffff:0:0', 96], // IPv4-mapped
+ ['64:ff9b::', 96], // well-known NAT64
+ ['64:ff9b:1::', 48], // local-use NAT64
+ ['100::', 64], // discard-only
+ ['2001::', 23], // IETF protocol assignments, including Teredo
+ ['2001:db8::', 32], // documentation
+ ['2002::', 16], // 6to4 (embeds an IPv4 target)
+ ['fc00::', 7], // unique-local
+ ['fe80::', 10], // link-local
+ ['fec0::', 10], // deprecated site-local
+ ['ff00::', 8], // multicast
+] as const) {
+ blockedIpv6.addSubnet(network, prefix, 'ipv6')
+}
+
interface CacheEntry { at: number; result: MaterializeResult; bytes: number }
const cache = new Map<string, CacheEntry>()
let cacheBytes = 0
+let imageFetchOverrideForTesting: ImageFetchOverride | null = null
+
+class BlockedImageUrlError extends Error {}
function readCache(url: string): MaterializeResult | null {
const entry = cache.get(url)
@@ -81,96 +189,286 @@ function writeCache(url: string, result: MaterializeResult, bytes: number): void
cacheBytes += bytes
}
-/** Reject loopback / RFC1918 / link-local hostnames so a stray URL can't be
- * used to probe the cluster's internal network from this process. Real
- * avatar/attachment URLs go to public CDN hostnames so this is purely a
- * defense-in-depth net. */
-function isBlockedHost(host: string): boolean {
- const h = host.toLowerCase()
- if (h === 'localhost' || h.endsWith('.localhost')) return true
- if (h.startsWith('127.') || h.startsWith('10.') || h.startsWith('0.')) return true
- if (h.startsWith('169.254.') || h.startsWith('192.168.')) return true
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(h)) return true
- // IPv6 loopback / link-local. Crude but adequate — we don't expect raw v6
- // hostnames in our config; CDN/storage are all named.
- if (h === '::1' || h.startsWith('fe80:') || h.startsWith('fc') || h.startsWith('fd')) return true
- return false
+function normalizedHostname(url: URL): string {
+ // WHATWG URL keeps brackets around IPv6 literals in `hostname`; net.isIP
+ // expects the raw address.
+ const hostname = url.hostname.startsWith('[') && url.hostname.endsWith(']')
+ ? url.hostname.slice(1, -1)
+ : url.hostname
+ return hostname.toLowerCase().replace(/\.$/, '')
}
-/** Fetch `url`, validate it's an image we can ship, and return a base64
- * `data:` URL on success. Never throws — callers iterate over many URLs
- * and shouldn't have to wrap each. */
-export async function materializeImage(url: string): Promise<MaterializeResult> {
- const cached = readCache(url)
- if (cached) return cached
+function isBlockedIp(address: string): boolean {
+ const family = isIP(address)
+ if (family === 4) return blockedIpv4.check(address, 'ipv4')
+ if (family === 6) return blockedIpv6.check(address, '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 resolveImageTarget(
+ url: URL,
+ signal: AbortSignal,
+ lookup: ImageFetchDependencies['lookup'],
+): Promise<ResolvedImageTarget> {
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password) {
+ throw new BlockedImageUrlError('unsupported image URL')
+ }
- let parsed: URL
- try { parsed = new URL(url) }
- catch {
- const r: MaterializeResult = { ok: false, reason: 'blocked' }
- writeCache(url, r, 0); return r
+ const hostname = normalizedHostname(url)
+ if (!hostname || isReservedHostname(hostname)) {
+ throw new BlockedImageUrlError('reserved image hostname')
}
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
- const r: MaterializeResult = { ok: false, reason: 'blocked' }
- writeCache(url, r, 0); return r
+
+ const literalFamily = isIP(hostname)
+ const addresses = literalFamily
+ ? [{ address: hostname, family: literalFamily as 4 | 6 }]
+ : await abortable(lookup(hostname), signal)
+
+ if (addresses.length === 0) throw new Error('image hostname resolved to no addresses')
+
+ // Reject the whole answer set, rather than picking around a private answer.
+ // That prevents an attacker from mixing public and private records and
+ // relying on resolver/connection ordering to reach the private one.
+ for (const answer of addresses) {
+ if ((answer.family !== 4 && answer.family !== 6) ||
+ isIP(answer.address) !== answer.family || isBlockedIp(answer.address)) {
+ throw new BlockedImageUrlError('image hostname resolved to a non-public address')
+ }
+ }
+
+ const selected = addresses[0]
+ return { url, hostname, address: selected.address, family: selected.family }
+}
+
+function requestPinnedImage(target: ResolvedImageTarget, signal: AbortSignal): Promise<ImageHttpResponse> {
+ 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,
+ accept: 'image/*,*/*;q=0.1',
+ 'user-agent': 'CumoraImageFetcher/1.0',
+ },
+ }
+ if (target.url.protocol === 'https:' && !isIP(target.hostname)) {
+ // Keep certificate verification and SNI bound to the original public
+ // hostname even though the TCP socket is pinned to a resolved address.
+ 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: ImageFetchDependencies = {
+ lookup: async hostname => {
+ const answers = await dnsLookup(hostname, { all: true, verbatim: true })
+ return answers.map(({ address, family }) => ({ address, family: family as 4 | 6 }))
+ },
+ request: requestPinnedImage,
+}
+
+function headerValue(headers: IncomingHttpHeaders, name: string): string | undefined {
+ const value = headers[name]
+ return Array.isArray(value) ? value[0] : value
+}
+
+function isRedirect(status: number): boolean {
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
+}
+
+async function readBodyWithCap(
+ response: ImageHttpResponse,
+ maxBytes: number,
+ 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 > maxBytes) {
+ response.cancel()
+ return null
+ }
+ chunks.push(chunk)
}
- if (isBlockedHost(parsed.hostname)) {
- const r: MaterializeResult = { ok: false, reason: 'blocked' }
- writeCache(url, r, 0); return r
+ return Buffer.concat(chunks, total)
+}
+
+async function fetchImageBytesWithDependencies(
+ rawUrl: string,
+ options: RequiredImageFetchOptions,
+ dependencies: ImageFetchDependencies,
+): Promise<ImageBytesResult> {
+ let current: URL
+ try {
+ current = new URL(rawUrl)
+ } catch {
+ return { ok: false, reason: 'blocked' }
}
- const ctrl = new AbortController()
- const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)
- let result: MaterializeResult
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs)
try {
- const res = await fetch(url, { signal: ctrl.signal, redirect: 'follow' })
- if (!res.ok) {
- result = { ok: false, reason: 'http', status: res.status }
- } else {
- const ctype = (res.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase()
- if (!ctype.startsWith('image/')) {
- result = { ok: false, reason: 'bad-type' }
- } else {
- const declared = Number(res.headers.get('content-length') ?? '')
- if (Number.isFinite(declared) && declared > MAX_IMAGE_BYTES) {
- result = { ok: false, reason: 'too-large' }
- } else {
- result = await streamWithCap(res, ctype)
+ for (let redirects = 0; ; redirects += 1) {
+ const target = await resolveImageTarget(current, controller.signal, dependencies.lookup)
+ const response = await abortable(dependencies.request(target, controller.signal), controller.signal)
+ const location = headerValue(response.headers, 'location')
+
+ if (isRedirect(response.status) && location) {
+ response.cancel()
+ if (redirects >= options.maxRedirects) return { ok: false, reason: 'blocked' }
+ try {
+ current = new URL(location, current)
+ } catch {
+ return { ok: false, reason: 'blocked' }
+ }
+ continue
+ }
+
+ if (response.status < 200 || response.status >= 300) {
+ response.cancel()
+ return { ok: false, reason: 'http', status: response.status }
+ }
+
+ const mime = (headerValue(response.headers, 'content-type') ?? '')
+ .split(';')[0].trim().toLowerCase()
+ if (!mime.startsWith('image/')) {
+ response.cancel()
+ return { ok: false, reason: 'bad-type' }
+ }
+
+ const contentLength = headerValue(response.headers, 'content-length')
+ if (contentLength !== undefined) {
+ const declared = Number(contentLength)
+ if (Number.isFinite(declared) && declared > options.maxBytes) {
+ response.cancel()
+ return { ok: false, reason: 'too-large' }
}
}
+
+ let buffer: Buffer | null
+ try {
+ buffer = await readBodyWithCap(response, options.maxBytes, controller.signal)
+ } catch (error) {
+ response.cancel()
+ throw error
+ }
+ if (!buffer) return { ok: false, reason: 'too-large' }
+ return {
+ ok: true,
+ buffer,
+ mime,
+ bytes: buffer.byteLength,
+ finalUrl: current.toString(),
+ }
}
- } catch (err) {
- const name = (err as Error)?.name
- result = { ok: false, reason: name === 'AbortError' ? 'timeout' : 'error' }
+ } catch (error) {
+ if (controller.signal.aborted) return { ok: false, reason: 'timeout' }
+ if (error instanceof BlockedImageUrlError) return { ok: false, reason: 'blocked' }
+ return { ok: false, reason: 'error' }
} finally {
clearTimeout(timer)
}
+}
+
+/** Safely download an image from a public URL. The connection is pinned to
+ * a pre-validated DNS answer and every redirect is independently checked.
+ * Never throws so callers can turn failures into their own user-facing
+ * behavior without duplicating network-policy logic. */
+export async function fetchImageBytes(
+ url: string,
+ options: ImageFetchOptions = {},
+): Promise<ImageBytesResult> {
+ if (imageFetchOverrideForTesting) return await imageFetchOverrideForTesting(url, options)
+ return await fetchImageBytesWithDependencies(url, {
+ maxBytes: options.maxBytes ?? MAX_IMAGE_BYTES,
+ timeoutMs: options.timeoutMs ?? FETCH_TIMEOUT_MS,
+ maxRedirects: options.maxRedirects ?? MAX_REDIRECTS,
+ }, productionDependencies)
+}
+
+/** Integration-test hook for call sites that consume the centralized helper. */
+export function __setImageFetchOverrideForTesting(override: ImageFetchOverride | null): void {
+ imageFetchOverrideForTesting = override
+}
+
+/** Fetch `url`, validate it's an image we can ship, and return a base64
+ * `data:` URL on success. Never throws — callers iterate over many URLs
+ * and shouldn't have to wrap each. */
+export async function materializeImage(url: string): Promise<MaterializeResult> {
+ const cached = readCache(url)
+ if (cached) return cached
+
+ const fetched = await fetchImageBytes(url)
+ const result: MaterializeResult = fetched.ok
+ ? {
+ ok: true,
+ dataUrl: `data:${fetched.mime};base64,${fetched.buffer.toString('base64')}`,
+ bytes: fetched.bytes,
+ }
+ : fetched
const cacheBytesForEntry = result.ok ? result.dataUrl.length : 0
writeCache(url, result, cacheBytesForEntry)
return result
}
-async function streamWithCap(res: Response, mime: string): Promise<MaterializeResult> {
- // Don't trust Content-Length — chunked / missing / lying responses still
- // need a hard cap during the actual read. Bail the instant we cross
- // MAX_IMAGE_BYTES so a malicious / misconfigured origin can't OOM us.
- const reader = res.body?.getReader()
- if (!reader) return { ok: false, reason: 'error' }
- const chunks: Buffer[] = []
- let total = 0
- for (;;) {
- const { done, value } = await reader.read()
- if (done) break
- if (!value) continue
- total += value.byteLength
- if (total > MAX_IMAGE_BYTES) {
- await reader.cancel().catch(() => { /* ignore */ })
- return { ok: false, reason: 'too-large' }
- }
- chunks.push(Buffer.from(value))
- }
- const buf = Buffer.concat(chunks)
- return { ok: true, dataUrl: `data:${mime};base64,${buf.toString('base64')}`, bytes: total }
+/** Test hook for deterministic DNS and network regression cases. */
+export async function _fetchImageBytesForTest(
+ url: string,
+ options: ImageFetchOptions,
+ dependencies: ImageFetchDependencies,
+): Promise<ImageBytesResult> {
+ return await fetchImageBytesWithDependencies(url, {
+ maxBytes: options.maxBytes ?? MAX_IMAGE_BYTES,
+ timeoutMs: options.timeoutMs ?? FETCH_TIMEOUT_MS,
+ maxRedirects: options.maxRedirects ?? MAX_REDIRECTS,
+ }, dependencies)
}
/** Test hook — clear the cache between runs so failure cases don't leak
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index d9ffa19..0f069ec 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -8,6 +8,7 @@ import { CH_MESSAGE_NEW, CH_REACTIONS, CH_CONVO_UPDATED, CH_DOCS, CH_TYPING, CH_
import { createPoll, castVote, closePoll, PollError } from '../polls.js'
import { env } from '../env.js'
import { startConvene, getActiveConvene } from '../agents/convene.js'
+import { fetchImageBytes } from '../agents/image-fetcher.js'
import { getTriageEconomics } from '../agents/observability.js'
import { BUSY_STATUS_LEASE_MS } from '../status.js'
import { notifyMessage, computeMessageRecipients } from '../push.js'
@@ -2636,8 +2637,12 @@ export async function generateAndPersistAvatar(args: {
if (b64) {
imageBuf = Buffer.from(b64, 'base64')
} else if (remoteUrl) {
- const fetched = await fetch(remoteUrl)
- imageBuf = Buffer.from(await fetched.arrayBuffer())
+ const fetched = await fetchImageBytes(remoteUrl, {
+ maxBytes: 20 * 1024 * 1024,
+ timeoutMs: 30_000,
+ })
+ if (!fetched.ok) throw new HttpError(502, `image API download failed (${fetched.reason})`)
+ imageBuf = fetched.buffer
} else {
throw new HttpError(502, 'image API returned no image')
}