forked from coder/code-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
214 lines (190 loc) · 5.58 KB
/
Copy pathserver.ts
File metadata and controls
214 lines (190 loc) · 5.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { logger, field } from "@coder/logger";
import { ReadWriteConnection } from "@coder/protocol";
import { Server, ServerOptions } from "@coder/protocol/src/node/server";
import * as express from "express";
//@ts-ignore
import * as expressStaticGzip from "express-static-gzip";
import * as fs from "fs";
import * as http from "http";
//@ts-ignore
import * as httpolyglot from "httpolyglot";
import * as https from "https";
import * as mime from "mime-types";
import * as net from "net";
import * as path from "path";
import * as pem from "pem";
import * as util from "util";
import * as ws from "ws";
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";
export const createApp = async (registerMiddleware?: (app: express.Application) => void, options?: ServerOptions, password?: string, httpsOptions?: https.ServerOptions): Promise<{
readonly express: express.Application;
readonly server: http.Server;
readonly wss: ws.Server;
}> => {
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;
};
const isAuthed = (req: http.IncomingMessage): boolean => {
try {
if (!password || !isCli) {
return true;
}
// Try/catch placed here just in case
const cookies = parseCookies(req);
if (cookies.password && cookies.password === password) {
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;
};
const app = express();
if (registerMiddleware) {
registerMiddleware(app);
}
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;
const wss = new ws.Server({ server });
wss.shouldHandle = (req): boolean => {
return isAuthed(req);
};
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 }));
}
const connection: ReadWriteConnection = {
onMessage: (cb): void => {
ws.addEventListener("message", (event) => cb(event.data));
},
close: (): void => ws.close(),
send: (data): void => {
if (ws.readyState !== ws.OPEN) {
return;
}
try {
ws.send(data);
} catch (error) {
logger.error(error.message);
}
},
onClose: (cb): void => ws.addEventListener("close", () => cb()),
};
const server = new Server(connection, options);
});
const baseDir = buildDir || path.join(__dirname, "..");
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);
}
});
app.get("/resource/:url(*)", async (req, res) => {
try {
const fullPath = `/${req.params.url}`;
// const relative = path.relative(options!.dataDirectory, fullPath);
// if (relative.startsWith("..")) {
// return res.status(403).end();
// }
const exists = fs.existsSync(fullPath);
if (!exists) {
return res.status(404).end();
}
const stat = await util.promisify(fs.stat)(fullPath);
if (!stat.isFile()) {
res.write("Resource must be a file.");
res.status(422);
return res.end();
}
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();
}
});
app.post("/resource/:url(*)", async (req, res) => {
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();
}
});
return {
express: app,
server,
wss,
};
};