1
0
mirror of https://git.tuxpa.in/a/code-server.git synced 2025-02-26 20:56:47 +00:00
code-server-2/src/node/routes/pathProxy.ts

60 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Request, Response } from "express"
import * as path from "path"
2020-10-20 23:05:58 +00:00
import qs from "qs"
2021-01-20 20:11:08 +00:00
import * as pluginapi from "../../../typings/pluginapi"
import { HttpCode, HttpError } from "../../common/http"
import { normalize } from "../../common/util"
import { authenticated, ensureAuthenticated, redirect } from "../http"
import { proxy as _proxy } from "../proxy"
2020-03-31 19:56:01 +00:00
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}` : ""}`
2020-10-20 23:05:58 +00:00
}
export function proxy(
req: Request,
res: Response,
opts?: {
passthroughPath?: boolean
},
): void {
2020-10-20 23:05:58 +00:00
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
if (!opts?.passthroughPath) {
// Absolute redirects need to be based on the subpath when rewriting.
// See proxy.ts.
;(req as any).base = req.path.split(path.sep).slice(0, 3).join(path.sep)
}
2020-10-20 23:05:58 +00:00
_proxy.web(req, res, {
2020-10-20 23:05:58 +00:00
ignorePath: true,
target: getProxyTarget(req, opts?.passthroughPath),
2020-10-20 23:05:58 +00:00
})
}
export async function wsProxy(
2021-01-20 20:11:08 +00:00
req: pluginapi.WebsocketRequest,
opts?: {
passthroughPath?: boolean
},
): Promise<void> {
await ensureAuthenticated(req)
_proxy.ws(req, req.ws, req.head, {
2020-10-20 23:05:58 +00:00
ignorePath: true,
target: getProxyTarget(req, opts?.passthroughPath),
2020-10-20 23:05:58 +00:00
})
}