-
Notifications
You must be signed in to change notification settings - Fork 3
/
express.js
300 lines (247 loc) · 8.58 KB
/
express.js
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/* eslint-env node */
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const fs = require('fs');
const uuid = require('uuid');
const { exec } = require('child_process');
const app = express();
const sourceDir = 'dist';
const { get: getConfig } = require('./config');
const { WebhookClient } = require('discord.js');
const proxy = require('express-http-proxy');
const path = require('path');
const { FirebaseTokenManager } = require('./firebaseAuth');
const formData = require('form-data');
const Mailgun = require('mailgun.js');
const createParentalConsentRouter = require('./parentalConsent');
let config;
try {
config = getConfig();
} catch (e) {
process.exitCode = 1;
throw e;
}
// set up rate limiter: maximum of 100 requests per 15 minute
var RateLimit = require('express-rate-limit');
var limiter = RateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 1000, // max 100 requests per windowMs
});
// apply rate limiter to all requests
app.use(limiter);
const mailgun = new Mailgun(formData);
const mailgunClient = mailgun.client({
username: 'api',
key: config.mailgun.apiKey,
});
const firebaseTokenManager = new FirebaseTokenManager(config.firebase.serviceAccountKey, config.firebase.apiKey);
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.use(morgan('combined'));
app.use('/api/parental-consent', createParentalConsentRouter(firebaseTokenManager, mailgunClient, config));
app.use('/api', proxy(config.dbUrl));
// If we have libkipr (C) artifacts and emsdk, we can compile.
if (config.server.dependencies.libkipr_c && config.server.dependencies.emsdk_env) {
app.post('/compile', (req, res) => {
if (!('code' in req.body)) {
return res.status(400).json({
error: "Expected code key in body"
});
}
if (typeof req.body.code !== 'string') {
return res.status(400).json({
error: "Expected code key in body to be a string"
});
}
// Wrap user's main() in our own "main()" that exits properly
// Required because Asyncify keeps emscripten runtime alive, which would prevent cleanup code from running
const augmentedCode = `${req.body.code}
#include <emscripten.h>
EM_JS(void, on_stop, (), {
if (Module.context.onStop) Module.context.onStop();
})
void simMainWrapper()
{
main();
on_stop();
emscripten_force_exit(0);
}
`;
const id = uuid.v4();
const path = `/tmp/${id}.c`;
fs.writeFile(path, augmentedCode, err => {
if (err) {
return res.status(500).json({
error: "Failed to write ${}"
});
}
// ...process.env causes a linter error for some reason.
// We work around this by doing it manually.
const env = {};
for (const key of Object.keys(process.env)) {
env[key] = process.env[key];
}
env['PATH'] = `${config.server.dependencies.emsdk_env.PATH}:${process.env.PATH}`;
env['EMSDK'] = config.server.dependencies.emsdk_env.EMSDK;
env['EM_CONFIG'] = config.server.dependencies.emsdk_env.EM_CONFIG;
exec(`emcc -s WASM=0 -s INVOKE_RUN=0 -s ASYNCIFY -s EXIT_RUNTIME=1 -s "EXPORTED_FUNCTIONS=['_main', '_simMainWrapper']" -I${config.server.dependencies.libkipr_c}/include -L${config.server.dependencies.libkipr_c}/lib -lkipr -o ${path}.js ${path}`, {
env
}, (err, stdout, stderr) => {
if (err) {
console.log(stderr);
return res.status(200).json({
stdout,
stderr
});
}
fs.readFile(`${path}.js`, (err, data) => {
if (err) {
return res.status(400).json({
error: `Failed to open ${path}.js for reading`
});
}
fs.unlink(`${path}.js`, err => {
if (err) {
return res.status(500).json({
error: `Failed to delete ${path}.js`
});
}
fs.unlink(`${path}`, err => {
if (err) {
return res.status(500).json({
error: `Failed to delete ${path}`
});
}
res.status(200).json({
result: data.toString(),
stdout,
stderr,
});
});
});
});
});
});
});
}
app.post('/feedback', (req, res) => {
const hookURL = config.server.feedbackWebhookURL;
if (!hookURL) {
res.status(500).json({
message: 'The feedback URL is not set on the server. If this is a developoment environment, make sure the feedback URL environment variable is set.'
});
return;
}
const body = req.body;
let content = `User Feedback Recieved:\n\`\`\`${body.feedback} \`\`\``;
content += `Sentiment: `;
switch (body.sentiment) {
case 0: content += 'No sentiment! This is probably a bug'; break;
case 1: content += ':frowning2:'; break;
case 2: content += ':expressionless:'; break;
case 3: content += ':smile:'; break;
}
content += '\n';
if (body.email !== null && body.email !== '') {
content += `User Email: ${body.email}\n`;
}
let files = null;
if (body.includeAnonData) {
content += `Browser User-Agent: ${body.userAgent}\n`;
files = [{
attachment: Buffer.from(JSON.stringify(body.state, undefined, 2)),
name: 'userdata.json'
}];
}
let webhook;
try {
webhook = new WebhookClient({ url: hookURL });
} catch (error) {
console.log(error);
res.status(500).json({
message: 'An error occured on the server. If you are a developer, your webhook url is likely wrong.'
});
// TODO: write the feedback to a file if an error occurs?
return;
}
webhook.send({
content: content,
username: 'KIPR Simulator Feedback',
avatarURL: 'https://www.kipr.org/wp-content/uploads/2018/08/botguy-copy.jpg',
files: files
})
.then(() => {
res.status(200).json({
message: 'Feedback submitted! Thank you!'
});
})
.catch(() => {
res.status(500).json({
message: 'An error occured on the server while sending feedback.'
});
// TODO: write the feedback to a file if an error occurs?
});
});
app.use('/static', express.static(`${__dirname}/static`, {
maxAge: config.caching.staticMaxAge,
}));
if (config.server.dependencies.scratch_rt) {
console.log('Scratch Runtime is enabled.');
app.use('/scratch/rt.js', express.static(`${config.server.dependencies.scratch_rt}`, {
maxAge: config.caching.staticMaxAge,
}));
}
app.use('/scratch', express.static(path.resolve(__dirname, 'node_modules', 'kipr-scratch'), {
maxAge: config.caching.staticMaxAge,
}));
app.use('/media', express.static(path.resolve(__dirname, 'node_modules', 'kipr-scratch', 'media'), {
maxAge: config.caching.staticMaxAge,
}));
// Expose cpython artifacts
if (config.server.dependencies.cpython) {
console.log('CPython artifacts are enabled.');
app.use('/cpython', express.static(`${config.server.dependencies.cpython}`, {
maxAge: config.caching.staticMaxAge,
}));
}
// Expose libkipr (Python) artifacts
if (config.server.dependencies.libkipr_python) {
console.log('libkipr (Python) artifacts are enabled.');
app.use('/libkipr/python', express.static(`${config.server.dependencies.libkipr_python}`, {
maxAge: config.caching.staticMaxAge,
}));
}
app.use('/dist', express.static(`${__dirname}/dist`, {
setHeaders: setCrossOriginIsolationHeaders,
}));
app.use(express.static(sourceDir, {
maxAge: config.caching.staticMaxAge,
setHeaders: setCrossOriginIsolationHeaders,
}));
app.get('/login', (req, res) => {
res.sendFile(`${__dirname}/${sourceDir}/login.html`);
});
app.get('/lms/plugin', (req, res) => {
res.sendFile(`${__dirname}/${sourceDir}/plugin.html`);
});
app.get('/parental-consent/*', (req, res) => {
res.sendFile(`${__dirname}/${sourceDir}/parental-consent.html`);
});
app.use('*', (req, res) => {
setCrossOriginIsolationHeaders(res);
res.sendFile(`${__dirname}/${sourceDir}/index.html`);
});
app.listen(config.server.port, () => {
console.log(`Express web server started: http://localhost:${config.server.port}`);
console.log(`Serving content from /${sourceDir}/`);
});
// Cross-origin isolation required for using features like SharedArrayBuffer
function setCrossOriginIsolationHeaders(res) {
res.header("Cross-Origin-Opener-Policy", "same-origin");
res.header("Cross-Origin-Embedder-Policy", "require-corp");
}