-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
53 lines (42 loc) · 1.2 KB
/
mod.ts
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
import type { ConnInfo } from 'https://deno.land/[email protected]/http/server.ts'
export type RequestWithConnection = Request & { conn: ConnInfo }
/**
* Get all addresses in the request, using the `X-Forwarded-For` header.
*
* @param req Request object
*/
export function forwarded(req: RequestWithConnection) {
// simple header parsing
const proxyAddrs = parse(req.headers.get('x-forwarded-for') ?? '')
const { hostname: socketAddr } = req.conn.remoteAddr as Deno.NetAddr
// return all addresses
return [socketAddr].concat(proxyAddrs)
}
/**
* Parse the `X-Forwarded-For` header.
*
* @param header Header value
*/
export function parse(header: string) {
const list = []
let start = header.length
let end = header.length
// gather addresses, backwards
for (let i = header.length - 1; i >= 0; i--) {
switch (header.charCodeAt(i)) {
case 0x20 /* */:
if (start === end) start = end = i
break
case 0x2c /* , */:
if (start !== end) list.push(header.substring(start, end))
start = end = i
break
default:
start = i
break
}
}
// final address
if (start !== end) list.push(header.substring(start, end))
return list
}