2020-02-20 00:00:58 +01:00
|
|
|
import { field, logger } from "@coder/logger"
|
2020-10-21 01:05:58 +02:00
|
|
|
import * as express from "express"
|
|
|
|
import * as expressCore from "express-serve-static-core"
|
2021-10-28 22:27:17 +02:00
|
|
|
import * as http from "http"
|
|
|
|
import * as net from "net"
|
2021-12-07 22:39:01 +01:00
|
|
|
import * as qs from "qs"
|
2021-10-28 22:27:17 +02:00
|
|
|
import { Disposable } from "../common/emitter"
|
2021-12-02 01:21:52 +01:00
|
|
|
import { CookieKeys, HttpCode, HttpError } from "../common/http"
|
2021-09-30 05:14:56 +02:00
|
|
|
import { normalize } from "../common/util"
|
2021-01-30 01:03:21 +01:00
|
|
|
import { AuthType, DefaultedArgs } from "./cli"
|
2021-09-30 05:14:56 +02:00
|
|
|
import { version as codeServerVersion } from "./constants"
|
2021-01-30 01:03:21 +01:00
|
|
|
import { Heart } from "./heart"
|
2021-12-17 20:06:52 +01:00
|
|
|
import { CoderSettings, SettingsProvider } from "./settings"
|
|
|
|
import { UpdateProvider } from "./update"
|
2021-09-30 05:14:56 +02:00
|
|
|
import { getPasswordMethod, IsCookieValidArgs, isCookieValid, sanitizeString, escapeHtml, escapeJSON } from "./util"
|
2020-02-04 20:27:46 +01:00
|
|
|
|
2021-10-28 22:27:17 +02:00
|
|
|
/**
|
|
|
|
* Base options included on every page.
|
|
|
|
*/
|
|
|
|
export interface ClientConfiguration {
|
|
|
|
codeServerVersion: string
|
2021-12-08 22:52:15 +01:00
|
|
|
/** Relative path from this page to the root. No trailing slash. */
|
2021-10-28 22:27:17 +02:00
|
|
|
base: string
|
2021-12-08 22:52:15 +01:00
|
|
|
/** Relative path from this page to the static root. No trailing slash. */
|
2021-10-28 22:27:17 +02:00
|
|
|
csStaticBase: string
|
|
|
|
}
|
|
|
|
|
2021-01-30 01:03:21 +01:00
|
|
|
declare global {
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
|
|
|
namespace Express {
|
|
|
|
export interface Request {
|
|
|
|
args: DefaultedArgs
|
|
|
|
heart: Heart
|
2021-12-17 20:06:52 +01:00
|
|
|
settings: SettingsProvider<CoderSettings>
|
|
|
|
updater: UpdateProvider
|
2021-01-30 01:03:21 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-28 22:27:17 +02:00
|
|
|
export const createClientConfiguration = (req: express.Request): ClientConfiguration => {
|
2021-12-08 22:52:15 +01:00
|
|
|
const base = relativeRoot(req.originalUrl)
|
2021-09-30 05:14:56 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
base,
|
2021-12-08 22:52:15 +01:00
|
|
|
csStaticBase: base + "/_static",
|
2021-09-30 05:14:56 +02:00
|
|
|
codeServerVersion,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-04 20:27:46 +01:00
|
|
|
/**
|
2020-10-21 01:05:58 +02:00
|
|
|
* Replace common variable strings in HTML templates.
|
2020-02-04 20:27:46 +01:00
|
|
|
*/
|
2020-10-21 01:05:58 +02:00
|
|
|
export const replaceTemplates = <T extends object>(
|
|
|
|
req: express.Request,
|
|
|
|
content: string,
|
|
|
|
extraOpts?: Omit<T, "base" | "csStaticBase" | "logLevel">,
|
|
|
|
): string => {
|
2021-10-28 22:27:17 +02:00
|
|
|
const serverOptions: ClientConfiguration = {
|
2021-09-30 05:14:56 +02:00
|
|
|
...createClientConfiguration(req),
|
2020-10-21 01:05:58 +02:00
|
|
|
...extraOpts,
|
|
|
|
}
|
2021-09-30 05:14:56 +02:00
|
|
|
|
2020-10-21 01:05:58 +02:00
|
|
|
return content
|
2021-06-30 19:39:48 +02:00
|
|
|
.replace(/{{TO}}/g, (typeof req.query.to === "string" && escapeHtml(req.query.to)) || "/")
|
2021-09-30 05:14:56 +02:00
|
|
|
.replace(/{{BASE}}/g, serverOptions.base)
|
|
|
|
.replace(/{{CS_STATIC_BASE}}/g, serverOptions.csStaticBase)
|
|
|
|
.replace("{{OPTIONS}}", () => escapeJSON(serverOptions))
|
2020-02-04 20:27:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-11-03 23:45:03 +01:00
|
|
|
* Throw an error if not authorized. Call `next` if provided.
|
2020-02-04 20:27:46 +01:00
|
|
|
*/
|
2021-06-02 22:21:59 +02:00
|
|
|
export const ensureAuthenticated = async (
|
|
|
|
req: express.Request,
|
|
|
|
_?: express.Response,
|
|
|
|
next?: express.NextFunction,
|
|
|
|
): Promise<void> => {
|
|
|
|
const isAuthenticated = await authenticated(req)
|
|
|
|
if (!isAuthenticated) {
|
2020-10-21 01:05:58 +02:00
|
|
|
throw new HttpError("Unauthorized", HttpCode.Unauthorized)
|
2020-04-01 18:28:09 +02:00
|
|
|
}
|
2020-11-03 23:45:03 +01:00
|
|
|
if (next) {
|
|
|
|
next()
|
|
|
|
}
|
2020-02-04 20:27:46 +01:00
|
|
|
}
|
|
|
|
|
2020-10-21 01:05:58 +02:00
|
|
|
/**
|
|
|
|
* Return true if authenticated via cookies.
|
|
|
|
*/
|
2021-06-02 22:21:59 +02:00
|
|
|
export const authenticated = async (req: express.Request): Promise<boolean> => {
|
2020-10-21 01:05:58 +02:00
|
|
|
switch (req.args.auth) {
|
2021-06-04 01:37:46 +02:00
|
|
|
case AuthType.None: {
|
2020-10-21 01:05:58 +02:00
|
|
|
return true
|
2021-06-04 01:37:46 +02:00
|
|
|
}
|
|
|
|
case AuthType.Password: {
|
2020-10-21 01:05:58 +02:00
|
|
|
// The password is stored in the cookie after being hashed.
|
2021-06-03 02:24:37 +02:00
|
|
|
const hashedPasswordFromArgs = req.args["hashed-password"]
|
|
|
|
const passwordMethod = getPasswordMethod(hashedPasswordFromArgs)
|
|
|
|
const isCookieValidArgs: IsCookieValidArgs = {
|
|
|
|
passwordMethod,
|
2021-12-02 01:21:52 +01:00
|
|
|
cookieKey: sanitizeString(req.cookies[CookieKeys.Session]),
|
2021-06-03 02:24:37 +02:00
|
|
|
passwordFromArgs: req.args.password || "",
|
|
|
|
hashedPasswordFromArgs: req.args["hashed-password"],
|
|
|
|
}
|
|
|
|
|
|
|
|
return await isCookieValid(isCookieValidArgs)
|
2021-06-04 01:37:46 +02:00
|
|
|
}
|
|
|
|
default: {
|
2020-10-21 01:05:58 +02:00
|
|
|
throw new Error(`Unsupported auth type ${req.args.auth}`)
|
2021-06-04 01:37:46 +02:00
|
|
|
}
|
2020-10-21 01:05:58 +02:00
|
|
|
}
|
2020-02-04 23:55:27 +01:00
|
|
|
}
|
|
|
|
|
2020-10-21 01:05:58 +02:00
|
|
|
/**
|
|
|
|
* Get the relative path that will get us to the root of the page. For each
|
2021-12-08 22:52:15 +01:00
|
|
|
* slash we need to go up a directory. Will not have a trailing slash.
|
|
|
|
*
|
|
|
|
* For example:
|
|
|
|
*
|
2020-10-21 01:05:58 +02:00
|
|
|
* / => .
|
|
|
|
* /foo => .
|
|
|
|
* /foo/ => ./..
|
|
|
|
* /foo/bar => ./..
|
|
|
|
* /foo/bar/ => ./../..
|
2021-12-08 22:52:15 +01:00
|
|
|
*
|
|
|
|
* All paths must be relative in order to work behind a reverse proxy since we
|
|
|
|
* we do not know the base path. Anything that needs to be absolute (for
|
|
|
|
* example cookies) must get the base path from the frontend.
|
|
|
|
*
|
|
|
|
* All relative paths must be prefixed with the relative root to ensure they
|
|
|
|
* work no matter the depth at which they happen to appear.
|
|
|
|
*
|
|
|
|
* For Express `req.originalUrl` should be used as they remove the base from the
|
|
|
|
* standard `url` property making it impossible to get the true depth.
|
2020-10-21 01:05:58 +02:00
|
|
|
*/
|
2021-12-08 22:52:15 +01:00
|
|
|
export const relativeRoot = (originalUrl: string): string => {
|
|
|
|
const depth = (originalUrl.split("?", 1)[0].match(/\//g) || []).length
|
2020-10-21 01:05:58 +02:00
|
|
|
return normalize("./" + (depth > 1 ? "../".repeat(depth - 1) : ""))
|
2020-02-14 22:57:51 +01:00
|
|
|
}
|
|
|
|
|
2022-03-01 20:11:56 +01:00
|
|
|
/**
|
|
|
|
* A helper function to construct a redirect path based on
|
|
|
|
* an Express Request, query and a path to redirect to.
|
|
|
|
*
|
|
|
|
* Redirect path is relative to `/${to}`.
|
|
|
|
*/
|
|
|
|
export const constructRedirectPath = (req: express.Request, query: qs.ParsedQs, to: string): string => {
|
|
|
|
const relativePath = normalize(`${relativeRoot(req.originalUrl)}/${to}`, true)
|
|
|
|
// %2f or %2F are both equalivent to an encoded slash /
|
|
|
|
const queryString = qs.stringify(query).replace(/%2[fF]/g, "/")
|
|
|
|
const redirectPath = `${relativePath}${queryString ? `?${queryString}` : ""}`
|
|
|
|
|
|
|
|
return redirectPath
|
|
|
|
}
|
|
|
|
|
2020-10-21 01:05:58 +02:00
|
|
|
/**
|
2021-12-17 20:06:52 +01:00
|
|
|
* Redirect relatively to `/${to}`. Query variables on the current URI will be
|
|
|
|
* preserved. `to` should be a simple path without any query parameters
|
2020-10-21 01:05:58 +02:00
|
|
|
* `override` will merge with the existing query (use `undefined` to unset).
|
|
|
|
*/
|
|
|
|
export const redirect = (
|
|
|
|
req: express.Request,
|
|
|
|
res: express.Response,
|
|
|
|
to: string,
|
|
|
|
override: expressCore.Query = {},
|
|
|
|
): void => {
|
|
|
|
const query = Object.assign({}, req.query, override)
|
|
|
|
Object.keys(override).forEach((key) => {
|
|
|
|
if (typeof override[key] === "undefined") {
|
|
|
|
delete query[key]
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2022-03-01 20:11:56 +01:00
|
|
|
const redirectPath = constructRedirectPath(req, query, to)
|
2020-10-21 01:05:58 +02:00
|
|
|
logger.debug(`redirecting from ${req.originalUrl} to ${redirectPath}`)
|
|
|
|
res.redirect(redirectPath)
|
2020-02-27 19:04:23 +01:00
|
|
|
}
|
|
|
|
|
2020-02-04 20:27:46 +01:00
|
|
|
/**
|
2020-10-21 01:05:58 +02:00
|
|
|
* Get the value that should be used for setting a cookie domain. This will
|
2020-11-11 01:33:16 +01:00
|
|
|
* allow the user to authenticate once no matter what sub-domain they use to log
|
|
|
|
* in. This will use the highest level proxy domain (e.g. `coder.com` over
|
|
|
|
* `test.coder.com` if both are specified).
|
2020-02-04 20:27:46 +01:00
|
|
|
*/
|
2020-10-21 01:05:58 +02:00
|
|
|
export const getCookieDomain = (host: string, proxyDomains: string[]): string | undefined => {
|
|
|
|
const idx = host.lastIndexOf(":")
|
|
|
|
host = idx !== -1 ? host.substring(0, idx) : host
|
2020-11-11 01:33:16 +01:00
|
|
|
// If any of these are true we will still set cookies but without an explicit
|
|
|
|
// `Domain` attribute on the cookie.
|
2020-10-21 01:05:58 +02:00
|
|
|
if (
|
2020-11-11 01:33:16 +01:00
|
|
|
// The host can be be blank or missing so there's nothing we can set.
|
2020-10-21 01:05:58 +02:00
|
|
|
!host ||
|
|
|
|
// IP addresses can't have subdomains so there's no value in setting the
|
2020-11-11 01:33:16 +01:00
|
|
|
// domain for them. Assume that anything with a : is ipv6 (valid domain name
|
|
|
|
// characters are alphanumeric or dashes)...
|
2020-10-21 01:05:58 +02:00
|
|
|
host.includes(":") ||
|
2020-11-11 01:33:16 +01:00
|
|
|
// ...and that anything entirely numbers and dots is ipv4 (currently tlds
|
2020-10-21 01:05:58 +02:00
|
|
|
// cannot be entirely numbers).
|
|
|
|
!/[^0-9.]/.test(host) ||
|
2020-11-11 01:33:16 +01:00
|
|
|
// localhost subdomains don't seem to work at all (browser bug?). A cookie
|
|
|
|
// set at dev.localhost cannot be read by 8080.dev.localhost.
|
2020-10-21 01:05:58 +02:00
|
|
|
host.endsWith(".localhost") ||
|
2020-11-11 01:33:16 +01:00
|
|
|
// Domains without at least one dot (technically two since domain.tld will
|
|
|
|
// become .domain.tld) are considered invalid according to the spec so don't
|
|
|
|
// set the domain for them. In my testing though localhost is the only
|
|
|
|
// problem (the browser just doesn't store the cookie at all). localhost has
|
|
|
|
// an additional problem which is that a reverse proxy might give
|
|
|
|
// code-server localhost even though the domain is really domain.tld (by
|
|
|
|
// default NGINX does this).
|
|
|
|
!host.includes(".")
|
2020-10-21 01:05:58 +02:00
|
|
|
) {
|
2022-03-01 16:43:41 +01:00
|
|
|
logger.debug("no valid cookie domain", field("host", host))
|
2020-10-21 01:05:58 +02:00
|
|
|
return undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
proxyDomains.forEach((domain) => {
|
|
|
|
if (host.endsWith(domain) && domain.length < host.length) {
|
|
|
|
host = domain
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2022-03-01 16:43:41 +01:00
|
|
|
logger.debug("got cookie domain", field("host", host))
|
2020-11-03 23:44:08 +01:00
|
|
|
return host || undefined
|
2020-10-21 01:05:58 +02:00
|
|
|
}
|
2021-10-28 22:27:17 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Return a function capable of fully disposing an HTTP server.
|
|
|
|
*/
|
|
|
|
export function disposer(server: http.Server): Disposable["dispose"] {
|
|
|
|
const sockets = new Set<net.Socket>()
|
|
|
|
let cleanupTimeout: undefined | NodeJS.Timeout
|
|
|
|
|
|
|
|
server.on("connection", (socket) => {
|
|
|
|
sockets.add(socket)
|
|
|
|
|
|
|
|
socket.on("close", () => {
|
|
|
|
sockets.delete(socket)
|
|
|
|
|
|
|
|
if (cleanupTimeout && sockets.size === 0) {
|
|
|
|
clearTimeout(cleanupTimeout)
|
|
|
|
cleanupTimeout = undefined
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
return new Promise<void>((resolve, reject) => {
|
|
|
|
// The whole reason we need this disposer is because close will not
|
|
|
|
// actually close anything; it only prevents future connections then waits
|
|
|
|
// until everything is closed.
|
|
|
|
server.close((err) => {
|
|
|
|
if (err) {
|
|
|
|
return reject(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
|
|
|
|
// If there are sockets remaining we might need to force close them or
|
|
|
|
// this promise might never resolve.
|
|
|
|
if (sockets.size > 0) {
|
|
|
|
// Give sockets a chance to close up shop.
|
|
|
|
cleanupTimeout = setTimeout(() => {
|
|
|
|
cleanupTimeout = undefined
|
|
|
|
|
|
|
|
for (const socket of sockets.values()) {
|
|
|
|
console.warn("a socket was left hanging")
|
|
|
|
socket.destroy()
|
|
|
|
}
|
|
|
|
}, 1000)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2021-12-08 22:52:15 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the options for setting a cookie. The options must be identical for
|
|
|
|
* setting and unsetting cookies otherwise they are considered separate.
|
|
|
|
*/
|
|
|
|
export const getCookieOptions = (req: express.Request): express.CookieOptions => {
|
|
|
|
// Normally we set paths relatively. However browsers do not appear to allow
|
|
|
|
// cookies to be set relatively which means we need an absolute path. We
|
|
|
|
// cannot be guaranteed we know the path since a reverse proxy might have
|
|
|
|
// rewritten it. That means we need to get the path from the frontend.
|
|
|
|
|
|
|
|
// The reason we need to set the path (as opposed to defaulting to /) is to
|
|
|
|
// avoid code-server instances on different sub-paths clobbering each other or
|
|
|
|
// from accessing each other's tokens (and to prevent other services from
|
|
|
|
// accessing code-server's tokens).
|
|
|
|
|
|
|
|
// When logging in or out the request must include the href (the full current
|
|
|
|
// URL of that page) and the relative path to the root as given to it by the
|
|
|
|
// backend. Using these two we can determine the true absolute root.
|
|
|
|
const url = new URL(
|
|
|
|
req.query.base || req.body.base || "/",
|
|
|
|
req.query.href || req.body.href || "http://" + (req.headers.host || "localhost"),
|
|
|
|
)
|
|
|
|
return {
|
|
|
|
domain: getCookieDomain(url.host, req.args["proxy-domain"]),
|
|
|
|
path: normalize(url.pathname) || "/",
|
|
|
|
sameSite: "lax",
|
|
|
|
}
|
|
|
|
}
|
2021-12-17 20:06:52 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the full path to the current page, preserving any trailing slash.
|
|
|
|
*/
|
|
|
|
export const self = (req: express.Request): string => {
|
|
|
|
return normalize(`${req.baseUrl}${req.originalUrl.endsWith("/") ? "/" : ""}`, true)
|
|
|
|
}
|