api/src/lib/fetch.ts
62 lines · 1796 bytes
3 symbols in this file
1/**
2 * JSON http fetch for outbound calls (used for /enrich/* routes)
3 * Default timeout is 5 sec, any non-2xx responses return ApiError
4 * Note that it only allows HTTPS fetches from allowed hosts list
5 */
6
7import { ApiError } from '@/lib/errors'
8import { log } from '@/lib/log'
9
10const ALLOWED_HOSTS = new Set([
11 'api.tosdr.org',
12 'api.github.com',
13 'itunes.apple.com',
14 'reports.exodus-privacy.eu.org',
15 'discord.com',
16 'www.reddit.com',
17 'endpoint.apivoid.com',
18 'raw.githubusercontent.com',
19 'api.deps.dev',
20 'plexus.techlore.tech',
21 'hub.docker.com',
22 'staticcdn.duckduckgo.com',
23])
24
25export interface FetchOpts {
26 timeoutMs?: number
27 headers?: Record<string, string>
28}
29
30export const fetchJson = async <T = unknown>(
31 url: string,
32 opts: FetchOpts = {},
33): Promise<T> => {
34 // Validate scheme + host against the allowlist before any network IO
35 const parsed = new URL(url)
36 if (parsed.protocol !== 'https:') {
37 throw new ApiError('BAD_REQUEST', 'Invalid URL scheme', 400)
38 }
39 if (!ALLOWED_HOSTS.has(parsed.hostname)) {
40 throw new ApiError('BAD_REQUEST', `Host not allowed: ${parsed.hostname}`, 400)
41 }
42 const signal = AbortSignal.timeout(opts.timeoutMs ?? 5000)
43 let response: Response
44 try {
45 response = await fetch(url, { headers: opts.headers, signal })
46 } catch (caught) {
47 log.warn('fetch_failed', {
48 host: parsed.hostname,
49 err: (caught as Error).message,
50 })
51 throw new ApiError('UPSTREAM_ERROR', `Upstream fetch failed: ${parsed.hostname}`, 502)
52 }
53 if (!response.ok) {
54 log.warn('upstream_status', { host: parsed.hostname, status: response.status })
55 throw new ApiError(
56 'UPSTREAM_ERROR',
57 `Upstream ${parsed.hostname} returned ${response.status}`,
58 502,
59 )
60 }
61 return (await response.json()) as T
62}