2019-03-27 02:01:25 +08:00
|
|
|
import { field, logger } from "@coder/logger";
|
2019-03-13 04:45:44 +08:00
|
|
|
import { ReadWriteConnection } from "@coder/protocol";
|
2019-01-16 02:36:09 +08:00
|
|
|
import { Server, ServerOptions } from "@coder/protocol/src/node/server";
|
2019-03-27 02:01:25 +08:00
|
|
|
import { TunnelCloseCode } from "@coder/tunnel/src/common";
|
|
|
|
import { handle as handleTunnel } from "@coder/tunnel/src/server";
|
2019-01-16 02:36:09 +08:00
|
|
|
import * as express from "express";
|
2019-02-06 01:15:20 +08:00
|
|
|
//@ts-ignore
|
|
|
|
import * as expressStaticGzip from "express-static-gzip";
|
2019-01-27 03:16:06 +08:00
|
|
|
import * as fs from "fs";
|
2019-03-27 02:01:25 +08:00
|
|
|
import { mkdirp } from "fs-extra";
|
2019-01-16 02:36:09 +08:00
|
|
|
import * as http from "http";
|
2019-02-22 01:55:42 +08:00
|
|
|
//@ts-ignore
|
|
|
|
import * as httpolyglot from "httpolyglot";
|
|
|
|
import * as https from "https";
|
2019-01-27 03:16:06 +08:00
|
|
|
import * as mime from "mime-types";
|
2019-02-22 01:55:42 +08:00
|
|
|
import * as net from "net";
|
2019-02-28 05:12:26 +08:00
|
|
|
import * as os from "os";
|
2019-01-26 08:18:21 +08:00
|
|
|
import * as path from "path";
|
2019-02-22 01:55:42 +08:00
|
|
|
import * as pem from "pem";
|
2019-01-27 03:16:06 +08:00
|
|
|
import * as util from "util";
|
2019-01-16 02:36:09 +08:00
|
|
|
import * as ws from "ws";
|
2019-03-13 00:12:50 +08:00
|
|
|
import { buildDir } from "./constants";
|
2019-03-27 02:01:25 +08:00
|
|
|
import { createPortScanner } from "./portScanner";
|
|
|
|
import safeCompare = require("safe-compare");
|
2019-01-16 02:36:09 +08:00
|
|
|
|
2019-02-27 06:03:42 +08:00
|
|
|
interface CreateAppOptions {
|
|
|
|
registerMiddleware?: (app: express.Application) => void;
|
|
|
|
serverOptions?: ServerOptions;
|
|
|
|
password?: string;
|
|
|
|
httpsOptions?: https.ServerOptions;
|
2019-03-04 15:45:35 +08:00
|
|
|
allowHttp?: boolean;
|
2019-02-27 06:03:42 +08:00
|
|
|
bypassAuth?: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const createApp = async (options: CreateAppOptions): Promise<{
|
2019-01-16 02:36:09 +08:00
|
|
|
readonly express: express.Application;
|
|
|
|
readonly server: http.Server;
|
|
|
|
readonly wss: ws.Server;
|
2019-02-22 01:55:42 +08: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-27 06:03:42 +08:00
|
|
|
const ensureAuthed = (req: http.IncomingMessage, res: express.Response): boolean => {
|
|
|
|
if (!isAuthed(req)) {
|
|
|
|
res.status(401);
|
|
|
|
res.end();
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
2019-02-22 01:55:42 +08:00
|
|
|
const isAuthed = (req: http.IncomingMessage): boolean => {
|
|
|
|
try {
|
2019-02-27 06:03:42 +08:00
|
|
|
if (!options.password || options.bypassAuth) {
|
2019-02-22 01:55:42 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try/catch placed here just in case
|
|
|
|
const cookies = parseCookies(req);
|
2019-03-10 01:24:36 +08:00
|
|
|
if (cookies.password && safeCompare(cookies.password, options.password)) {
|
2019-02-22 01:55:42 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
} catch (ex) {
|
|
|
|
logger.error("Failed to parse cookies", field("error", ex));
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
const isEncrypted = (socket: net.Socket): boolean => {
|
2019-03-01 06:06:17 +08:00
|
|
|
if (options.bypassAuth) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-02-22 01:55:42 +08:00
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
return (socket as any).encrypted;
|
|
|
|
};
|
|
|
|
|
2019-01-16 02:36:09 +08:00
|
|
|
const app = express();
|
2019-02-27 06:03:42 +08:00
|
|
|
if (options.registerMiddleware) {
|
|
|
|
options.registerMiddleware(app);
|
2019-01-16 02:36:09 +08:00
|
|
|
}
|
2019-02-22 01:55:42 +08:00
|
|
|
|
2019-03-01 04:34:54 +08: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-22 01:55:42 +08:00
|
|
|
}
|
2019-03-01 04:34:54 +08:00
|
|
|
}
|
2019-02-22 01:55:42 +08:00
|
|
|
|
2019-03-01 04:34:54 +08:00
|
|
|
resolve({
|
|
|
|
cert: fs.readFileSync(selfSignedCertPath).toString(),
|
|
|
|
key: fs.readFileSync(selfSignedKeyPath).toString(),
|
2019-02-22 01:55:42 +08:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2019-03-01 06:06:17 +08:00
|
|
|
const server = httpolyglot.createServer(options.bypassAuth ? {} : options.httpsOptions || certs, app) as http.Server;
|
2019-01-16 02:36:09 +08:00
|
|
|
const wss = new ws.Server({ server });
|
2019-01-19 05:46:40 +08:00
|
|
|
|
|
|
|
wss.shouldHandle = (req): boolean => {
|
2019-02-22 01:55:42 +08:00
|
|
|
return isAuthed(req);
|
2019-01-19 05:46:40 +08:00
|
|
|
};
|
|
|
|
|
2019-02-22 01:55:42 +08: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-16 02:36:09 +08:00
|
|
|
const connection: ReadWriteConnection = {
|
2019-01-19 05:46:40 +08:00
|
|
|
onMessage: (cb): void => {
|
2019-01-16 02:36:09 +08:00
|
|
|
ws.addEventListener("message", (event) => cb(event.data));
|
|
|
|
},
|
2019-01-19 05:46:40 +08:00
|
|
|
close: (): void => ws.close(),
|
2019-01-23 01:48:01 +08:00
|
|
|
send: (data): void => {
|
2019-01-29 01:14:06 +08:00
|
|
|
if (ws.readyState !== ws.OPEN) {
|
|
|
|
return;
|
|
|
|
}
|
2019-01-23 01:48:01 +08:00
|
|
|
try {
|
|
|
|
ws.send(data);
|
|
|
|
} catch (error) {
|
2019-01-23 03:48:43 +08:00
|
|
|
logger.error(error.message);
|
2019-01-23 01:48:01 +08:00
|
|
|
}
|
|
|
|
},
|
2019-03-27 02:01:25 +08:00
|
|
|
onUp: (): void => undefined, // This can't come back up.
|
|
|
|
onDown: (cb): void => ws.addEventListener("close", () => cb()),
|
2019-01-19 05:46:40 +08:00
|
|
|
onClose: (cb): void => ws.addEventListener("close", () => cb()),
|
2019-01-16 02:36:09 +08:00
|
|
|
};
|
2019-01-19 05:46:40 +08:00
|
|
|
|
2019-03-27 02:01:25 +08:00
|
|
|
// tslint:disable-next-line no-unused-expression
|
|
|
|
new Server(connection, options.serverOptions);
|
2019-01-16 02:36:09 +08:00
|
|
|
});
|
|
|
|
|
2019-02-08 01:47:00 +08:00
|
|
|
const baseDir = buildDir || path.join(__dirname, "..");
|
2019-02-22 01:55:42 +08: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-03-04 15:45:35 +08:00
|
|
|
if (!isEncrypted(req.socket) && !options.allowHttp) {
|
2019-03-01 04:34:54 +08:00
|
|
|
return res.redirect(301, `https://${req.headers.host!}${req.path}`);
|
|
|
|
}
|
|
|
|
|
2019-02-22 01:55:42 +08: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-03-27 02:01:25 +08:00
|
|
|
// @ts-ignore
|
|
|
|
app.use((err, req, res, next) => {
|
|
|
|
next();
|
|
|
|
});
|
2019-02-28 05:12:26 +08:00
|
|
|
app.get("/ping", (req, res) => {
|
|
|
|
res.json({
|
|
|
|
hostname: os.hostname(),
|
|
|
|
});
|
|
|
|
});
|
2019-01-27 03:16:06 +08:00
|
|
|
app.get("/resource/:url(*)", async (req, res) => {
|
2019-02-27 06:03:42 +08:00
|
|
|
if (!ensureAuthed(req, res)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-01-27 03:16:06 +08:00
|
|
|
try {
|
|
|
|
const fullPath = `/${req.params.url}`;
|
2019-01-29 01:14:06 +08:00
|
|
|
// const relative = path.relative(options!.dataDirectory, fullPath);
|
|
|
|
// if (relative.startsWith("..")) {
|
|
|
|
// return res.status(403).end();
|
|
|
|
// }
|
2019-02-06 01:15:20 +08:00
|
|
|
const exists = fs.existsSync(fullPath);
|
2019-01-27 03:16:06 +08:00
|
|
|
if (!exists) {
|
2019-02-08 01:47:00 +08:00
|
|
|
return res.status(404).end();
|
2019-01-27 03:16:06 +08:00
|
|
|
}
|
|
|
|
const stat = await util.promisify(fs.stat)(fullPath);
|
|
|
|
if (!stat.isFile()) {
|
|
|
|
res.write("Resource must be a file.");
|
|
|
|
res.status(422);
|
|
|
|
|
2019-02-08 01:47:00 +08:00
|
|
|
return res.end();
|
2019-01-27 03:16:06 +08:00
|
|
|
}
|
|
|
|
let mimeType = mime.lookup(fullPath);
|
|
|
|
if (mimeType === false) {
|
|
|
|
mimeType = "application/octet-stream";
|
|
|
|
}
|
|
|
|
const content = await util.promisify(fs.readFile)(fullPath);
|
|
|
|
|
2019-03-27 02:01:25 +08:00
|
|
|
res.writeHead(200, {
|
|
|
|
"Content-Type": mimeType,
|
|
|
|
"Content-Length": content.byteLength,
|
|
|
|
});
|
2019-01-27 03:16:06 +08:00
|
|
|
res.write(content);
|
|
|
|
res.end();
|
|
|
|
} catch (ex) {
|
|
|
|
res.write(ex.toString());
|
|
|
|
res.status(500);
|
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
});
|
2019-02-22 01:55:42 +08:00
|
|
|
app.post("/resource/:url(*)", async (req, res) => {
|
2019-02-27 06:03:42 +08:00
|
|
|
if (!ensureAuthed(req, res)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-02-22 01:55:42 +08:00
|
|
|
try {
|
|
|
|
const fullPath = `/${req.params.url}`;
|
|
|
|
|
|
|
|
const data: string[] = [];
|
|
|
|
req.setEncoding("utf8");
|
|
|
|
req.on("data", (chunk) => {
|
|
|
|
data.push(chunk);
|
|
|
|
});
|
2019-03-13 00:12:50 +08:00
|
|
|
req.on("end", async () => {
|
2019-02-22 01:55:42 +08:00
|
|
|
const body = data.join("");
|
2019-03-13 04:45:44 +08:00
|
|
|
await mkdirp(path.dirname(fullPath));
|
2019-02-22 01:55:42 +08:00
|
|
|
fs.writeFileSync(fullPath, body);
|
2019-04-10 00:24:53 +08:00
|
|
|
logger.info("Wrote resource", field("path", fullPath), field("content-length", body.length));
|
2019-02-22 01:55:42 +08:00
|
|
|
res.status(200);
|
|
|
|
res.end();
|
|
|
|
});
|
|
|
|
} catch (ex) {
|
|
|
|
res.write(ex.toString());
|
|
|
|
res.status(500);
|
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
});
|
2019-01-27 03:16:06 +08:00
|
|
|
|
2019-01-16 02:36:09 +08:00
|
|
|
return {
|
|
|
|
express: app,
|
|
|
|
server,
|
|
|
|
wss,
|
|
|
|
};
|
|
|
|
};
|