mirror of
https://github.com/coder/code-server.git
synced 2025-07-31 22:13:52 +08:00
Move domain proxy to routes
This matches better with the other routes. Also add a missing authentication check to the path proxy web socket.
This commit is contained in:
46
src/node/routes/pathProxy.ts
Normal file
46
src/node/routes/pathProxy.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import { Request, Router } from "express"
|
||||
import qs from "qs"
|
||||
import { HttpCode, HttpError } from "../../common/http"
|
||||
import { authenticated, ensureAuthenticated, redirect } from "../http"
|
||||
import { proxy } from "../proxy"
|
||||
import { Router as WsRouter } from "../wsRouter"
|
||||
|
||||
export const router = Router()
|
||||
|
||||
const getProxyTarget = (req: Request, rewrite: boolean): string => {
|
||||
if (rewrite) {
|
||||
const query = qs.stringify(req.query)
|
||||
return `http://0.0.0.0:${req.params.port}/${req.params[0] || ""}${query ? `?${query}` : ""}`
|
||||
}
|
||||
return `http://0.0.0.0:${req.params.port}/${req.originalUrl}`
|
||||
}
|
||||
|
||||
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}` || "/",
|
||||
})
|
||||
}
|
||||
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, true),
|
||||
})
|
||||
})
|
||||
|
||||
export const wsRouter = WsRouter()
|
||||
|
||||
wsRouter.ws("/(:port)(/*)?", ensureAuthenticated, (req) => {
|
||||
proxy.ws(req, req.ws, req.head, {
|
||||
ignorePath: true,
|
||||
target: getProxyTarget(req, true),
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user