pathProxy.ts 1.4 KB
Newer Older
A
Asher 已提交
1 2
import { Request, Router } from "express"
import qs from "qs"
A
Asher 已提交
3
import { HttpCode, HttpError } from "../../common/http"
A
Asher 已提交
4
import { authenticated, ensureAuthenticated, redirect } from "../http"
A
Asher 已提交
5
import { proxy } from "../proxy"
A
Asher 已提交
6
import { Router as WsRouter } from "../wsRouter"
A
Asher 已提交
7

A
Asher 已提交
8
export const router = Router()
A
Asher 已提交
9

A
Asher 已提交
10 11 12
const getProxyTarget = (req: Request, rewrite: boolean): string => {
  if (rewrite) {
    const query = qs.stringify(req.query)
A
Asher 已提交
13
    return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
A
Asher 已提交
14
  }
A
Asher 已提交
15
  return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
A
Asher 已提交
16
}
A
Asher 已提交
17

A
Asher 已提交
18 19 20 21 22 23 24 25
router.all("/(:port)(/*)?", (req, res) => {
  if (!authenticated(req)) {
    // If visiting the root (/proxy/:port and nothing else) redirect to the
    // login page.
    if (!req.params[0] || req.params[0] === "/") {
      return redirect(req, res, "login", {
        to: `${req.baseUrl}${req.path}` || "/",
      })
A
Asher 已提交
26
    }
A
Asher 已提交
27
    throw new HttpError("Unauthorized", HttpCode.Unauthorized)
A
Asher 已提交
28
  }
A
Asher 已提交
29 30 31 32 33 34 35 36 37 38

  // 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, true),
  })
})

A
Asher 已提交
39 40
export const wsRouter = WsRouter()

A
Asher 已提交
41
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
A
Asher 已提交
42
  proxy.ws(req, req.ws, req.head, {
A
Asher 已提交
43 44 45 46
    ignorePath: true,
    target: getProxyTarget(req, true),
  })
})