pathProxy.ts 1.5 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 { normalize } from "../../common/util"
A
Asher 已提交
5
import { authenticated, ensureAuthenticated, redirect } from "../http"
A
Asher 已提交
6
import { proxy } from "../proxy"
A
Asher 已提交
7
import { Router as WsRouter } from "../wsRouter"
A
Asher 已提交
8

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

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

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

  // 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 已提交
40 41
export const wsRouter = WsRouter()

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