2019-02-21 17:55:42 +00:00
|
|
|
import { logger, field } from "@coder/logger";
|
2019-01-15 18:36:09 +00:00
|
|
|
import { ReadWriteConnection } from "@coder/protocol";
|
|
|
|
import { Server, ServerOptions } from "@coder/protocol/src/node/server";
|
|
|
|
import * as express from "express";
|
2019-02-05 17:15:20 +00:00
|
|
|
//@ts-ignore
|
|
|
|
import * as expressStaticGzip from "express-static-gzip";
|
2019-01-26 19:16:06 +00:00
|
|
|
import * as fs from "fs";
|
2019-01-15 18:36:09 +00:00
|
|
|
import * as http from "http";
|
2019-02-21 17:55:42 +00:00
|
|
|
//@ts-ignore
|
|
|
|
import * as httpolyglot from "httpolyglot";
|
|
|
|
import * as https from "https";
|
2019-01-26 19:16:06 +00:00
|
|
|
import * as mime from "mime-types";
|
2019-02-21 17:55:42 +00:00
|
|
|
import * as net from "net";
|
2019-02-27 21:12:26 +00:00
|
|
|
import * as os from "os";
|
2019-01-26 00:18:21 +00:00
|
|
|
import * as path from "path";
|
2019-02-21 17:55:42 +00:00
|
|
|
import * as pem from "pem";
|
2019-01-26 19:16:06 +00:00
|
|
|
import * as util from "util";
|
2019-01-15 18:36:09 +00:00
|
|
|
import * as ws from "ws";
|
2019-02-21 17:55:42 +00:00
|
|
|
import { TunnelCloseCode } from "@coder/tunnel/src/common";
|
|
|
|
import { handle as handleTunnel } from "@coder/tunnel/src/server";
|
|
|
|
import { createPortScanner } from "./portScanner";
|
|
|
|
import { buildDir, isCli } from "./constants";
|
2019-01-15 18:36:09 +00:00
|
|
|
|
2019-02-26 22:03:42 +00:00
|
|
|
interface CreateAppOptions {
|
|
|
|
registerMiddleware?: (app: express.Application) => void;
|
|
|
|
serverOptions?: ServerOptions;
|
|
|
|
password?: string;
|
|
|
|
httpsOptions?: https.ServerOptions;
|
|
|
|
bypassAuth?: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const createApp = async (options: CreateAppOptions): Promise<{
|
2019-01-15 18:36:09 +00:00
|
|
|
readonly express: express.Application;
|
|
|
|
readonly server: http.Server;
|
|
|
|
readonly wss: ws.Server;
|
2019-02-21 17:55:42 +00:00
|
|
|
}> => {
|
|
|
|
const parseCookies = (req: http.IncomingMessage): { [key: string]: string } => {
|
|
|
|
const cookies: { [key: string]: string } = {};
|
|
|
|
const rc = req.headers.cookie;
|
|
|
|
if (rc) {
|
|
|
|
rc.split(";").forEach((cook) => {
|
|
|
|
const parts = cook.split("=");
|
|
|
|
cookies[parts.shift()!.trim()] = decodeURI(parts.join("="));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return cookies;
|
|
|
|
};
|
|
|
|
|
2019-02-26 22:03:42 +00:00
|
|
|
const ensureAuthed = (req: http.IncomingMessage, res: express.Response): boolean => {
|
|
|
|
if (!isAuthed(req)) {
|
|
|
|
res.status(401);
|
|
|
|
res.end();
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
2019-02-21 17:55:42 +00:00
|
|
|
const isAuthed = (req: http.IncomingMessage): boolean => {
|
|
|
|
try {
|
2019-02-26 22:03:42 +00:00
|
|
|
if (!options.password || options.bypassAuth) {
|
2019-02-21 17:55:42 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try/catch placed here just in case
|
|
|
|
const cookies = parseCookies(req);
|
2019-02-26 22:03:42 +00:00
|
|
|
if (cookies.password && cookies.password === options.password) {
|
2019-02-21 17:55:42 +00:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
} catch (ex) {
|
|
|
|
logger.error("Failed to parse cookies", field("error", ex));
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
const isEncrypted = (socket: net.Socket): boolean => {
|
2019-02-28 22:06:17 +00:00
|
|
|
if (options.bypassAuth) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-02-21 17:55:42 +00:00
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
return (socket as any).encrypted;
|
|
|
|
};
|
|
|
|
|
2019-01-15 18:36:09 +00:00
|
|
|
const app = express();
|
2019-02-26 22:03:42 +00:00
|
|
|
if (options.registerMiddleware) {
|
|
|
|
options.registerMiddleware(app);
|
2019-01-15 18:36:09 +00:00
|
|
|
}
|
2019-02-21 17:55:42 +00:00
|
|
|
|
2019-02-28 20:34:54 +00:00
|
|
|
interface CertificateInfo {
|
|
|
|
readonly key: string;
|
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
readonly cert: any;
|
|
|
|
}
|
|
|
|
|
|
|
|
const certs = await new Promise<CertificateInfo>(async (resolve, reject): Promise<void> => {
|
|
|
|
const selfSignedKeyPath = path.join(options.serverOptions!.dataDirectory, "self-signed.key");
|
|
|
|
const selfSignedCertPath = path.join(options.serverOptions!.dataDirectory, "self-signed.cert");
|
|
|
|
|
|
|
|
if (!fs.existsSync(selfSignedKeyPath) || !fs.existsSync(selfSignedCertPath)) {
|
|
|
|
try {
|
|
|
|
const certs = await new Promise<pem.CertificateCreationResult>((res, rej): void => {
|
|
|
|
pem.createCertificate({
|
|
|
|
selfSigned: true,
|
|
|
|
}, (err, result) => {
|
|
|
|
if (err) {
|
|
|
|
rej(err);
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
res(result);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
fs.writeFileSync(selfSignedKeyPath, certs.serviceKey);
|
|
|
|
fs.writeFileSync(selfSignedCertPath, certs.certificate);
|
|
|
|
} catch (ex) {
|
|
|
|
return reject(ex);
|
2019-02-21 17:55:42 +00:00
|
|
|
}
|
2019-02-28 20:34:54 +00:00
|
|
|
}
|
2019-02-21 17:55:42 +00:00
|
|
|
|
2019-02-28 20:34:54 +00:00
|
|
|
resolve({
|
|
|
|
cert: fs.readFileSync(selfSignedCertPath).toString(),
|
|
|
|
key: fs.readFileSync(selfSignedKeyPath).toString(),
|
2019-02-21 17:55:42 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2019-02-28 22:06:17 +00:00
|
|
|
const server = httpolyglot.createServer(options.bypassAuth ? {} : options.httpsOptions || certs, app) as http.Server;
|
2019-01-15 18:36:09 +00:00
|
|
|
const wss = new ws.Server({ server });
|
2019-01-18 21:46:40 +00:00
|
|
|
|
|
|
|
wss.shouldHandle = (req): boolean => {
|
2019-02-21 17:55:42 +00:00
|
|
|
return isAuthed(req);
|
2019-01-18 21:46:40 +00:00
|
|
|
};
|
|
|
|
|
2019-02-21 17:55:42 +00:00
|
|
|
const portScanner = createPortScanner();
|
|
|
|
wss.on("connection", (ws, req) => {
|
|
|
|
if (req.url && req.url.startsWith("/tunnel")) {
|
|
|
|
try {
|
|
|
|
const rawPort = req.url.split("/").pop();
|
|
|
|
const port = Number.parseInt(rawPort!, 10);
|
|
|
|
|
|
|
|
handleTunnel(ws, port);
|
|
|
|
} catch (ex) {
|
|
|
|
ws.close(TunnelCloseCode.Error, ex.toString());
|
|
|
|
}
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.url && req.url.startsWith("/ports")) {
|
|
|
|
const onAdded = portScanner.onAdded((added) => ws.send(JSON.stringify({ added })));
|
|
|
|
const onRemoved = portScanner.onRemoved((removed) => ws.send(JSON.stringify({ removed })));
|
|
|
|
ws.on("close", () => {
|
|
|
|
onAdded.dispose();
|
|
|
|
onRemoved.dispose();
|
|
|
|
});
|
|
|
|
|
|
|
|
return ws.send(JSON.stringify({ ports: portScanner.ports }));
|
|
|
|
}
|
|
|
|
|
2019-01-15 18:36:09 +00:00
|
|
|
const connection: ReadWriteConnection = {
|
2019-01-18 21:46:40 +00:00
|
|
|
onMessage: (cb): void => {
|
2019-01-15 18:36:09 +00:00
|
|
|
ws.addEventListener("message", (event) => cb(event.data));
|
|
|
|
},
|
2019-01-18 21:46:40 +00:00
|
|
|
close: (): void => ws.close(),
|
2019-01-22 17:48:01 +00:00
|
|
|
send: (data): void => {
|
2019-01-28 17:14:06 +00:00
|
|
|
if (ws.readyState !== ws.OPEN) {
|
|
|
|
return;
|
|
|
|
}
|
2019-01-22 17:48:01 +00:00
|
|
|
try {
|
|
|
|
ws.send(data);
|
|
|
|
} catch (error) {
|
2019-01-22 19:48:43 +00:00
|
|
|
logger.error(error.message);
|
2019-01-22 17:48:01 +00:00
|
|
|
}
|
|
|
|
},
|
2019-01-18 21:46:40 +00:00
|
|
|
onClose: (cb): void => ws.addEventListener("close", () => cb()),
|
2019-01-15 18:36:09 +00:00
|
|
|
};
|
2019-01-18 21:46:40 +00:00
|
|
|
|
2019-02-26 22:03:42 +00:00
|
|
|
const server = new Server(connection, options.serverOptions);
|
2019-01-15 18:36:09 +00:00
|
|
|
});
|
|
|
|
|
2019-02-07 17:47:00 +00:00
|
|
|
const baseDir = buildDir || path.join(__dirname, "..");
|
2019-02-21 17:55:42 +00:00
|
|
|
const authStaticFunc = expressStaticGzip(path.join(baseDir, "build/web/auth"));
|
|
|
|
const unauthStaticFunc = expressStaticGzip(path.join(baseDir, "build/web/unauth"));
|
|
|
|
app.use((req, res, next) => {
|
2019-02-28 20:34:54 +00:00
|
|
|
if (!isEncrypted(req.socket)) {
|
|
|
|
return res.redirect(301, `https://${req.headers.host!}${req.path}`);
|
|
|
|
}
|
|
|
|
|
2019-02-21 17:55:42 +00:00
|
|
|
if (isAuthed(req)) {
|
|
|
|
// We can serve the actual VSCode bin
|
|
|
|
authStaticFunc(req, res, next);
|
|
|
|
} else {
|
|
|
|
// Serve only the unauthed version
|
|
|
|
unauthStaticFunc(req, res, next);
|
|
|
|
}
|
|
|
|
});
|
2019-02-27 21:12:26 +00:00
|
|
|
app.get("/ping", (req, res) => {
|
|
|
|
res.json({
|
|
|
|
hostname: os.hostname(),
|
|
|
|
});
|
|
|
|
});
|
2019-01-26 19:16:06 +00:00
|
|
|
app.get("/resource/:url(*)", async (req, res) => {
|
2019-02-26 22:03:42 +00:00
|
|
|
if (!ensureAuthed(req, res)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-01-26 19:16:06 +00:00
|
|
|
try {
|
|
|
|
const fullPath = `/${req.params.url}`;
|
2019-01-28 17:14:06 +00:00
|
|
|
// const relative = path.relative(options!.dataDirectory, fullPath);
|
|
|
|
// if (relative.startsWith("..")) {
|
|
|
|
// return res.status(403).end();
|
|
|
|
// }
|
2019-02-05 17:15:20 +00:00
|
|
|
const exists = fs.existsSync(fullPath);
|
2019-01-26 19:16:06 +00:00
|
|
|
if (!exists) {
|
2019-02-07 17:47:00 +00:00
|
|
|
return res.status(404).end();
|
2019-01-26 19:16:06 +00:00
|
|
|
}
|
|
|
|
const stat = await util.promisify(fs.stat)(fullPath);
|
|
|
|
if (!stat.isFile()) {
|
|
|
|
res.write("Resource must be a file.");
|
|
|
|
res.status(422);
|
|
|
|
|
2019-02-07 17:47:00 +00:00
|
|
|
return res.end();
|
2019-01-26 19:16:06 +00:00
|
|
|
}
|
|
|
|
let mimeType = mime.lookup(fullPath);
|
|
|
|
if (mimeType === false) {
|
|
|
|
mimeType = "application/octet-stream";
|
|
|
|
}
|
|
|
|
const content = await util.promisify(fs.readFile)(fullPath);
|
|
|
|
|
|
|
|
res.header("Content-Type", mimeType as string);
|
|
|
|
res.write(content);
|
|
|
|
res.status(200);
|
|
|
|
res.end();
|
|
|
|
} catch (ex) {
|
|
|
|
res.write(ex.toString());
|
|
|
|
res.status(500);
|
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
});
|
2019-02-21 17:55:42 +00:00
|
|
|
app.post("/resource/:url(*)", async (req, res) => {
|
2019-02-26 22:03:42 +00:00
|
|
|
if (!ensureAuthed(req, res)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-02-21 17:55:42 +00:00
|
|
|
try {
|
|
|
|
const fullPath = `/${req.params.url}`;
|
|
|
|
|
|
|
|
const data: string[] = [];
|
|
|
|
req.setEncoding("utf8");
|
|
|
|
req.on("data", (chunk) => {
|
|
|
|
data.push(chunk);
|
|
|
|
});
|
|
|
|
req.on("end", () => {
|
|
|
|
const body = data.join("");
|
|
|
|
fs.writeFileSync(fullPath, body);
|
|
|
|
logger.debug("Wrote resource", field("path", fullPath), field("content-length", body.length));
|
|
|
|
res.status(200);
|
|
|
|
res.end();
|
|
|
|
});
|
|
|
|
} catch (ex) {
|
|
|
|
res.write(ex.toString());
|
|
|
|
res.status(500);
|
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
});
|
2019-01-26 19:16:06 +00:00
|
|
|
|
2019-01-15 18:36:09 +00:00
|
|
|
return {
|
|
|
|
express: app,
|
|
|
|
server,
|
|
|
|
wss,
|
|
|
|
};
|
|
|
|
};
|