-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathpathProxy.ts
47 lines (40 loc) · 1.55 KB
/
pathProxy.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
import { Request, Router } from "express"
import qs from "qs"
import { HttpCode, HttpError } from "../../common/http"
import { normalize } from "../../common/util"
import { authenticated, ensureAuthenticated, redirect } from "../http"
import { proxy } from "../proxy"
import { Router as WsRouter } from "../wsRouter"
export const router = Router()
const getProxyTarget = (req: Request, passthroughPath: boolean): string => {
if (passthroughPath) {
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
}
const query = qs.stringify(req.query)
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
}
router.all("/(:port)(/*)?", (req, res) => {
if (!authenticated(req)) {
// If visiting the root (/:port only) redirect to the login page.
if (!req.params[0] || req.params[0] === "/") {
const to = normalize(`${req.baseUrl}${req.path}`)
return redirect(req, res, "login", {
to: to !== "/" ? to : undefined,
})
}
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
// Absolute redirects need to be based on the subpath when rewriting.
;(req as any).base = `${req.baseUrl}/${req.params.port}`
proxy.web(req, res, {
ignorePath: true,
target: getProxyTarget(req, req.args["proxy-path-passthrough"] || false),
})
})
export const wsRouter = WsRouter()
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
proxy.ws(req, req.ws, req.head, {
ignorePath: true,
target: getProxyTarget(req, req.args["proxy-path-passthrough"] || false),
})
})