File size: 2,979 Bytes
4b8da13
 
 
 
 
 
 
 
 
 
 
 
 
 
837c968
4b8da13
 
 
 
 
 
 
 
 
837c968
4b8da13
 
 
 
 
 
 
 
 
837c968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b8da13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837c968
4b8da13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const HOP_BY_HOP_HEADERS = new Set([
  'connection',
  'content-encoding',
  'content-length',
  'host',
  'keep-alive',
  'proxy-authenticate',
  'proxy-authorization',
  'te',
  'trailer',
  'transfer-encoding',
  'upgrade',
])


function readRequestBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = []
    req.on('data', chunk => chunks.push(chunk))
    req.on('end', () => resolve(Buffer.concat(chunks)))
    req.on('error', reject)
  })
}

export function buildTargetUrl(req) {
  const base = process.env.API_PROXY_TARGET || process.env.BACKEND_URL
  if (!base) {
    throw new Error('API_PROXY_TARGET is not configured')
  }

  const incoming = new URL(req.url, 'http://localhost')
  const path = incoming.searchParams.get('path') || ''
  incoming.searchParams.delete('path')

  // Reject paths that contain a protocol scheme — these cause
  // `new URL(path, base)` to ignore the base entirely per the WHATWG
  // URL spec, enabling SSRF to arbitrary hosts.
  if (/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(path) || path.includes('://')) {
    throw new Error('Invalid proxy path')
  }

  const normalizedBase = `${base.replace(/\/+$/, '')}/`
  const target = new URL(path.replace(/^\/+/, ''), normalizedBase)

  // Defence-in-depth: verify the resolved URL still points at our backend.
  const expectedOrigin = new URL(normalizedBase).origin
  if (target.origin !== expectedOrigin) {
    throw new Error('Invalid proxy path')
  }

  incoming.searchParams.forEach((value, key) => {
    target.searchParams.append(key, value)
  })

  return target
}

function copyResponseHeaders(response, res) {
  response.headers.forEach((value, key) => {
    const lowerKey = key.toLowerCase()
    if (lowerKey !== 'set-cookie' && !HOP_BY_HOP_HEADERS.has(lowerKey)) {
      res.setHeader(key, value)
    }
  })

  const cookies = response.headers.getSetCookie?.()
  if (cookies?.length) {
    res.setHeader('set-cookie', cookies)
    return
  }

  const cookie = response.headers.get('set-cookie')
  if (cookie) {
    res.setHeader('set-cookie', cookie)
  }
}

export default async function handler(req, res) {
  let target
  try {
    target = buildTargetUrl(req)
  } catch (error) {
    res.statusCode = 400
    res.setHeader('content-type', 'application/json')
    res.end(JSON.stringify({ detail: error.message }))
    return
  }

  const headers = new Headers()
  for (const [key, value] of Object.entries(req.headers)) {
    const lowerKey = key.toLowerCase()
    if (!HOP_BY_HOP_HEADERS.has(lowerKey) && value !== undefined) {
      headers.set(key, Array.isArray(value) ? value.join(', ') : value)
    }
  }

  const hasBody = !['GET', 'HEAD'].includes(req.method)
  const response = await fetch(target, {
    method: req.method,
    headers,
    body: hasBody ? await readRequestBody(req) : undefined,
    redirect: 'manual',
  })

  res.statusCode = response.status
  copyResponseHeaders(response, res)
  res.end(Buffer.from(await response.arrayBuffer()))
}