1
0
mirror of https://git.tuxpa.in/a/code-server.git synced 2025-01-07 09:08:45 +00:00
code-server-2/src/node/routes/pathProxy.ts

48 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-10-20 23:05:58 +00:00
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"
2020-10-20 23:05:58 +00:00
import { proxy } from "../proxy"
import { Router as WsRouter } from "../wsRouter"
2020-03-31 19:56:01 +00:00
2020-10-20 23:05:58 +00:00
export const router = Router()
2020-10-20 23:05:58 +00:00
const getProxyTarget = (req: Request, rewrite: boolean): string => {
if (rewrite) {
const query = qs.stringify(req.query)
2020-10-28 16:29:43 +00:00
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
}
2020-10-28 16:29:43 +00:00
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
2020-10-20 23:05:58 +00:00
}
2020-10-20 23:05:58 +00:00
router.all("/(:port)(/*)?", (req, res) => {
if (!authenticated(req)) {
// If visiting the root (/:port only) redirect to the login page.
2020-10-20 23:05:58 +00:00
if (!req.params[0] || req.params[0] === "/") {
const to = normalize(`${req.baseUrl}${req.path}`)
2020-10-20 23:05:58 +00:00
return redirect(req, res, "login", {
to: to !== "/" ? to : undefined,
2020-10-20 23:05:58 +00:00
})
2020-03-23 23:02:31 +00:00
}
2020-10-20 23:05:58 +00:00
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
}
2020-10-20 23:05:58 +00:00
// 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),
})
})
export const wsRouter = WsRouter()
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
2020-11-03 22:45:03 +00:00
proxy.ws(req, req.ws, req.head, {
2020-10-20 23:05:58 +00:00
ignorePath: true,
target: getProxyTarget(req, true),
})
})