Repository navigation
Expand file tree
/
Copy pathproxy.ts
More file actions
127 lines (121 loc) · 4.1 KB
/
Copy pathproxy.ts
File metadata and controls
127 lines (121 loc) · 4.1 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import http from "node:http"
import type {
IncomingMessage,
OutgoingHttpHeaders,
RequestListener,
ServerResponse,
} from "node:http"
import https from "node:https"
import type { Duplex } from "node:stream"
const HOP_BY_HOP_HEADERS: ReadonlySet<string> = new Set([
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
])
function filterHeaders(headers: IncomingMessage["headers"]): OutgoingHttpHeaders {
const filtered: OutgoingHttpHeaders = {}
for (const [name, value] of Object.entries(headers)) {
if (value === undefined || HOP_BY_HOP_HEADERS.has(name.toLowerCase())) continue
filtered[name] = value
}
return filtered
}
export function createProxyHandler(target: string): RequestListener {
const url = new URL(target)
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error(`Unsupported proxy protocol: ${url.protocol}. Use http or https.`)
}
const transport = url.protocol === "https:" ? https : http
const port = url.port === "" ? (url.protocol === "https:" ? 443 : 80) : Number(url.port)
return function handleProxy(req: IncomingMessage, res: ServerResponse): void {
if (req.method === "OPTIONS") {
res.writeHead(204)
res.end()
return
}
const headers = filterHeaders(req.headers)
headers.host = url.host
if (req.socket.remoteAddress !== undefined) {
const forwardedFor = req.headers["x-forwarded-for"]
headers["x-forwarded-for"] =
forwardedFor === undefined
? req.socket.remoteAddress
: `${forwardedFor}, ${req.socket.remoteAddress}`
}
headers["x-forwarded-proto"] =
(req.socket as { encrypted?: boolean }).encrypted === true ? "https" : "http"
if (req.headers.host !== undefined) headers["x-forwarded-host"] = req.headers.host
const upstream = transport.request(
{
protocol: url.protocol,
hostname: url.hostname,
port,
path: req.url,
method: req.method,
headers,
},
upstreamRes => {
res.writeHead(upstreamRes.statusCode ?? 502, filterHeaders(upstreamRes.headers))
upstreamRes.on("error", () => {
res.destroy()
})
upstreamRes.pipe(res)
},
)
upstream.on("error", () => {
if (res.headersSent) {
res.destroy()
return
}
res.writeHead(502, { "Content-Type": "text/plain; charset=utf-8" })
res.end("Bad gateway.")
})
req.on("aborted", () => {
upstream.destroy()
})
req.pipe(upstream)
}
}
export function createProxyUpgradeHandler(
target: string,
): (req: IncomingMessage, socket: Duplex, head: Buffer) => void {
const url = new URL(target)
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error(`Unsupported proxy protocol: ${url.protocol}. Use http or https.`)
}
const transport = url.protocol === "https:" ? https : http
const port = url.port === "" ? (url.protocol === "https:" ? 443 : 80) : Number(url.port)
return function handleUpgrade(req, clientSocket, head): void {
const headers = filterHeaders(req.headers)
headers.host = url.host
const upstream = transport.request({
protocol: url.protocol,
hostname: url.hostname,
port,
path: req.url,
method: req.method,
headers,
})
upstream.on("upgrade", (upstreamRes, upstreamSocket, upstreamHead) => {
clientSocket.write(
`HTTP/1.1 ${upstreamRes.statusCode ?? 101} ${upstreamRes.statusMessage ?? "Switching Protocols"}\r\n`,
)
for (const [name, value] of Object.entries(upstreamRes.headers)) {
if (value === undefined) continue
const values = Array.isArray(value) ? value : [value]
for (const item of values) clientSocket.write(`${name}: ${item}\r\n`)
}
clientSocket.write("\r\n")
if (upstreamHead.length > 0) clientSocket.write(upstreamHead)
if (head.length > 0) upstreamSocket.write(head)
clientSocket.pipe(upstreamSocket).pipe(clientSocket)
})
upstream.on("error", () => clientSocket.destroy())
upstream.end()
}
}