api/src/lib/fetch.ts

61 lines · 1766 bytes

 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])
23
24export interface FetchOpts {
25  timeoutMs?: number
26  headers?: Record<string, string>
27}
28
29export const fetchJson = async <T = unknown>(
30  url: string,
31  opts: FetchOpts = {},
32): Promise<T> => {
33  // Validate scheme + host against the allowlist before any network IO
34  const parsed = new URL(url)
35  if (parsed.protocol !== 'https:') {
36    throw new ApiError('BAD_REQUEST', 'Invalid URL scheme', 400)
37  }
38  if (!ALLOWED_HOSTS.has(parsed.hostname)) {
39    throw new ApiError('BAD_REQUEST', `Host not allowed: ${parsed.hostname}`, 400)
40  }
41  const signal = AbortSignal.timeout(opts.timeoutMs ?? 5000)
42  let response: Response
43  try {
44    response = await fetch(url, { headers: opts.headers, signal })
45  } catch (caught) {
46    log.warn('fetch_failed', {
47      host: parsed.hostname,
48      err: (caught as Error).message,
49    })
50    throw new ApiError('UPSTREAM_ERROR', `Upstream fetch failed: ${parsed.hostname}`, 502)
51  }
52  if (!response.ok) {
53    log.warn('upstream_status', { host: parsed.hostname, status: response.status })
54    throw new ApiError(
55      'UPSTREAM_ERROR',
56      `Upstream ${parsed.hostname} returned ${response.status}`,
57      502,
58    )
59  }
60  return (await response.json()) as T
61}