forked from coder/code-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
188 lines (168 loc) · 5.87 KB
/
Copy pathproxy.ts
File metadata and controls
188 lines (168 loc) · 5.87 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { logger } from "@coder/logger"
import * as http from "http"
import proxy from "http-proxy"
import * as net from "net"
import * as querystring from "querystring"
import { HttpCode, HttpError } from "../../common/http"
import { HttpProvider, HttpProviderOptions, HttpProxyProvider, HttpResponse, Route } from "../http"
interface Request extends http.IncomingMessage {
base?: string
}
/**
* Proxy HTTP provider.
*/
export class ProxyHttpProvider extends HttpProvider implements HttpProxyProvider {
/**
* Proxy domains are stored here without the leading `*.`
*/
public readonly proxyDomains: string[]
private readonly proxy = proxy.createProxyServer({})
/**
* Domains can be provided in the form `coder.com` or `*.coder.com`. Either
* way, `<number>.coder.com` will be proxied to `number`.
*/
public constructor(options: HttpProviderOptions, proxyDomains: string[] = []) {
super(options)
this.proxyDomains = proxyDomains.map((d) => d.replace(/^\*\./, "")).filter((d, i, arr) => arr.indexOf(d) === i)
this.proxy.on("error", (error) => logger.warn(error.message))
// Intercept the response to rewrite absolute redirects against the base path.
this.proxy.on("proxyRes", (response, request: Request) => {
if (response.headers.location && response.headers.location.startsWith("/") && request.base) {
response.headers.location = request.base + response.headers.location
}
})
}
public async handleRequest(
route: Route,
request: http.IncomingMessage,
response: http.ServerResponse,
): Promise<HttpResponse> {
if (!this.authenticated(request)) {
if (this.isRoot(route)) {
return { redirect: "/login", query: { to: route.fullPath } }
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// Ensure there is a trailing slash so relative paths work correctly.
if (this.isRoot(route) && !route.fullPath.endsWith("/")) {
return {
redirect: `${route.fullPath}/`,
}
}
const port = route.base.replace(/^\//, "")
const base = `${this.options.base}/${port}`
const payload = this.doProxy(route, request, response, port, base)
if (payload) {
return payload
}
throw new HttpError("Not found", HttpCode.NotFound)
}
public async handleWebSocket(
route: Route,
request: http.IncomingMessage,
socket: net.Socket,
head: Buffer,
): Promise<void> {
this.ensureAuthenticated(request)
const port = route.base.replace(/^\//, "")
const base = `${this.options.base}/${port}`
this.doProxy(route, request, { socket, head }, port, base)
}
public getCookieDomain(host: string): string {
let current: string | undefined
this.proxyDomains.forEach((domain) => {
if (host.endsWith(domain) && (!current || domain.length < current.length)) {
current = domain
}
})
// Setting the domain to localhost doesn't seem to work for subdomains (for
// example dev.localhost).
return current && current !== "localhost" ? current : host
}
public maybeProxyRequest(
route: Route,
request: http.IncomingMessage,
response: http.ServerResponse,
): HttpResponse | undefined {
const port = this.getPort(request)
return port ? this.doProxy(route, request, response, port) : undefined
}
public maybeProxyWebSocket(
route: Route,
request: http.IncomingMessage,
socket: net.Socket,
head: Buffer,
): HttpResponse | undefined {
const port = this.getPort(request)
return port ? this.doProxy(route, request, { socket, head }, port) : undefined
}
private getPort(request: http.IncomingMessage): string | undefined {
// No proxy until we're authenticated. This will cause the login page to
// show as well as let our assets keep loading normally.
if (!this.authenticated(request)) {
return undefined
}
// Split into parts.
const host = request.headers.host || ""
const idx = host.indexOf(":")
const domain = idx !== -1 ? host.substring(0, idx) : host
const parts = domain.split(".")
// There must be an exact match.
const port = parts.shift()
const proxyDomain = parts.join(".")
if (!port || !this.proxyDomains.includes(proxyDomain)) {
return undefined
}
return port
}
private doProxy(
route: Route,
request: http.IncomingMessage,
response: http.ServerResponse,
portStr: string,
base?: string,
): HttpResponse
private doProxy(
route: Route,
request: http.IncomingMessage,
response: { socket: net.Socket; head: Buffer },
portStr: string,
base?: string,
): HttpResponse
private doProxy(
route: Route,
request: http.IncomingMessage,
response: http.ServerResponse | { socket: net.Socket; head: Buffer },
portStr: string,
base?: string,
): HttpResponse {
const port = parseInt(portStr, 10)
if (isNaN(port)) {
return {
code: HttpCode.BadRequest,
content: `"${portStr}" is not a valid number`,
}
}
// REVIEW: Absolute redirects need to be based on the subpath but I'm not
// sure how best to get this information to the `proxyRes` event handler.
// For now I'm sticking it on the request object which is passed through to
// the event.
;(request as Request).base = base
const isHttp = response instanceof http.ServerResponse
const path = base ? route.fullPath.replace(base, "") : route.fullPath
const options: proxy.ServerOptions = {
changeOrigin: true,
ignorePath: true,
target: `${isHttp ? "http" : "ws"}://127.0.0.1:${port}${path}${
Object.keys(route.query).length > 0 ? `?${querystring.stringify(route.query)}` : ""
}`,
ws: !isHttp,
}
if (response instanceof http.ServerResponse) {
this.proxy.web(request, response, options)
} else {
this.proxy.ws(request, response.socket, response.head, options)
}
return { handled: true }
}
}