2019-02-22 00:55:42 +07:00
|
|
|
import { logger, field } from "@coder/logger";
|
2019-01-16 01:36:09 +07:00
|
|
|
import { ReadWriteConnection } from "@coder/protocol";
|
|
|
|
import { Server, ServerOptions } from "@coder/protocol/src/node/server";
|
|
|
|
import * as express from "express";
|
2019-02-06 00:15:20 +07:00
|
|
|
//@ts-ignore
|
|
|
|
import * as expressStaticGzip from "express-static-gzip";
|
2019-01-27 02:16:06 +07:00
|
|
|
import * as fs from "fs";
|
2019-01-16 01:36:09 +07:00
|
|
|
import * as http from "http";
|
2019-02-22 00:55:42 +07:00
|
|
|
//@ts-ignore
|
|
|
|
import * as httpolyglot from "httpolyglot";
|
|
|
|
import * as https from "https";
|
2019-01-27 02:16:06 +07:00
|
|
|
import * as mime from "mime-types";
|
2019-02-22 00:55:42 +07:00
|
|
|
import * as net from "net";
|
2019-02-28 04:12:26 +07:00
|
|
|
import * as os from "os";
|
2019-01-26 07:18:21 +07:00
|
|
|
import * as path from "path";
|
2019-02-22 00:55:42 +07:00
|
|
|
import * as pem from "pem";
|
2019-01-27 02:16:06 +07:00
|
|
|
import * as util from "util";
|
2019-01-16 01:36:09 +07:00
|
|
|
import * as ws from "ws";
|
2019-02-22 00:55:42 +07: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-16 01:36:09 +07:00
|
|
|
|
2019-02-27 05:03:42 +07: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-16 01:36:09 +07:00
|
|
|
readonly express: express.Application;
|
|
|
|
readonly server: http.Server;
|
|
|
|
readonly wss: ws.Server;
|
2019-02-22 00:55:42 +07: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 05:03:42 +07: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 00:55:42 +07:00
|
|
|
const isAuthed = (req: http.IncomingMessage): boolean => {
|
|
|
|
try {
|
2019-02-27 05:03:42 +07:00
|
|
|
if (!options.password || options.bypassAuth) {
|
2019-02-22 00:55:42 +07:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try/catch placed here just in case
|
|
|
|
const cookies = parseCookies(req);
|
2019-02-27 05:03:42 +07:00
|
|
|
if (cookies.password && cookies.password === options.password) {
|
2019-02-22 00:55:42 +07:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
} catch (ex) {
|
|
|
|
logger.error("Failed to parse cookies", field("error", ex));
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
|
|
|
const isEncrypted = (socket: net.Socket): boolean => {
|
|
|
|
// tslint:disable-next-line:no-any
|
|
|
|
return (socket as any).encrypted;
|
|
|
|
};
|
|
|
|
|
2019-01-16 01:36:09 +07:00
|
|
|
const app = express();
|
2019-02-27 05:03:42 +07:00
|
|
|
if (options.registerMiddleware) {
|
|
|
|
options.registerMiddleware(app);
|
2019-01-16 01:36:09 +07:00
|
|
|
}
|
2019-02-22 00:55:42 +07:00
|
|
|
|
|
|
|
const certs = await new Promise<pem.CertificateCreationResult>((res, rej): void => {
|
|
|
|
pem.createCertificate({
|
|
|
|
selfSigned: true,
|
|
|
|
}, (err, result) => {
|
|
|
|
if (err) {
|
|
|
|
rej(err);
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
res(result);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
const server = httpolyglot.createServer({
|
|
|
|
key: certs.serviceKey,
|
|
|
|
cert: certs.certificate,
|
|
|
|
}, app) as http.Server;
|
2019-01-16 01:36:09 +07:00
|
|
|
const wss = new ws.Server({ server });
|
2019-01-19 04:46:40 +07:00
|
|
|
|
|
|
|
wss.shouldHandle = (req): boolean => {
|
2019-02-22 00:55:42 +07:00
|
|
|
return isAuthed(req);
|
2019-01-19 04:46:40 +07:00
|
|
|
};
|
|
|
|
|
2019-02-22 00:55:42 +07: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 01:36:09 +07:00
|
|
|
const connection: ReadWriteConnection = {
|
2019-01-19 04:46:40 +07:00
|
|
|
onMessage: (cb): void => {
|
2019-01-16 01:36:09 +07:00
|
|
|
ws.addEventListener("message", (event) => cb(event.data));
|
|
|
|
},
|
2019-01-19 04:46:40 +07:00
|
|
|
close: (): void => ws.close(),
|
2019-01-23 00:48:01 +07:00
|
|
|
send: (data): void => {
|
2019-01-29 00:14:06 +07:00
|
|
|
if (ws.readyState !== ws.OPEN) {
|
|
|
|
return;
|
|
|
|
}
|
2019-01-23 00:48:01 +07:00
|
|
|
try {
|
|
|
|
ws.send(data);
|
|
|
|
} catch (error) {
|
2019-01-23 02:48:43 +07:00
|
|
|
logger.error(error.message);
|
2019-01-23 00:48:01 +07:00
|
|
|
}
|
|
|
|
},
|
2019-01-19 04:46:40 +07:00
|
|
|
onClose: (cb): void => ws.addEventListener("close", () => cb()),
|
2019-01-16 01:36:09 +07:00
|
|
|
};
|
2019-01-19 04:46:40 +07:00
|
|
|
|
2019-02-27 05:03:42 +07:00
|
|
|
const server = new Server(connection, options.serverOptions);
|
2019-01-16 01:36:09 +07:00
|
|
|
});
|
|
|
|
|
2019-02-08 00:47:00 +07:00
|
|
|
const baseDir = buildDir || path.join(__dirname, "..");
|
2019-02-22 00:55:42 +07:00
|
|
|
const authStaticFunc = expressStaticGzip(path.join(baseDir, "build/web/auth"));
|
|
|
|
const unauthStaticFunc = expressStaticGzip(path.join(baseDir, "build/web/unauth"));
|
|
|
|
app.use((req, res, next) => {
|
|
|
|
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-28 04:12:26 +07:00
|
|
|
app.get("/ping", (req, res) => {
|
|
|
|
res.json({
|
|
|
|
hostname: os.hostname(),
|
|
|
|
});
|
|
|
|
});
|
2019-01-27 02:16:06 +07:00
|
|
|
app.get("/resource/:url(*)", async (req, res) => {
|
2019-02-27 05:03:42 +07:00
|
|
|
if (!ensureAuthed(req, res)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-01-27 02:16:06 +07:00
|
|
|
try {
|
|
|
|
const fullPath = `/${req.params.url}`;
|
2019-01-29 00:14:06 +07:00
|
|
|
// const relative = path.relative(options!.dataDirectory, fullPath);
|
|
|
|
// if (relative.startsWith("..")) {
|
|
|
|
// return res.status(403).end();
|
|
|
|
// }
|
2019-02-06 00:15:20 +07:00
|
|
|
const exists = fs.existsSync(fullPath);
|
2019-01-27 02:16:06 +07:00
|
|
|
if (!exists) {
|
2019-02-08 00:47:00 +07:00
|
|
|
return res.status(404).end();
|
2019-01-27 02:16:06 +07: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 00:47:00 +07:00
|
|
|
return res.end();
|
2019-01-27 02:16:06 +07: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-22 00:55:42 +07:00
|
|
|
app.post("/resource/:url(*)", async (req, res) => {
|
2019-02-27 05:03:42 +07:00
|
|
|
if (!ensureAuthed(req, res)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-02-22 00:55:42 +07: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-27 02:16:06 +07:00
|
|
|
|
2019-01-16 01:36:09 +07:00
|
|
|
return {
|
|
|
|
express: app,
|
|
|
|
server,
|
|
|
|
wss,
|
|
|
|
};
|
|
|
|
};
|