forked from alseambusher/crontab-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·399 lines (342 loc) · 11.5 KB
/
Copy pathapp.js
File metadata and controls
executable file
·399 lines (342 loc) · 11.5 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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
'use strict';
const express = require('express');
const path = require('path');
const fs = require('fs');
const http = require('http');
const https = require('https');
const mime = require('mime-types');
const dayjs = require('dayjs');
const relativeTime = require('dayjs/plugin/relativeTime');
const busboy = require('connect-busboy');
const cookieParser = require('cookie-parser');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const crontab = require('./crontab');
const restore = require('./restore');
const packageJson = require('./package.json');
const { base_url: baseUrl, routes, relative: routesRelative } = require('./routes');
const { getAuthMode, applyProtection } = require('./middleware/auth');
const { loginHandler, logoutHandler, loginPageHandler } = require('./middleware/jwt');
const errorHandler = require('./middleware/error');
const { validateDbParam, validateIdParam } = require('./middleware/validate');
dayjs.extend(relativeTime);
const app = express();
app.locals.baseURL = baseUrl;
// security headers (relaxed for local/HTTP usage and CDN assets)
app.use(helmet({
contentSecurityPolicy: false,
crossOriginResourcePolicy: { policy: 'cross-origin' },
crossOriginEmbedderPolicy: false,
crossOriginOpenerPolicy: false,
originAgentCluster: false,
strictTransportSecurity: false,
}));
// rate limiting
app.use(rateLimit({
windowMs: 10 * 60 * 1000,
max: 1000,
standardHeaders: true,
legacyHeaders: false,
}));
// ssl credentials
const credentials = {
key: process.env.SSL_KEY ? fs.readFileSync(process.env.SSL_KEY) : '',
cert: process.env.SSL_CERT ? fs.readFileSync(process.env.SSL_CERT) : '',
};
if ((credentials.key && !credentials.cert) || (credentials.cert && !credentials.key)) {
console.error('Please provide both SSL_KEY and SSL_CERT');
process.exit(1);
}
const startHttpsServer = credentials.key && credentials.cert;
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(cookieParser());
app.use(express.json({ limit: '2mb' }));
app.use(express.urlencoded({ extended: true, limit: '2mb' }));
app.use(busboy());
app.use(baseUrl, express.static(path.join(__dirname, 'public')));
app.use(baseUrl, express.static(path.join(__dirname, 'public', 'css')));
app.use(baseUrl, express.static(path.join(__dirname, 'public', 'js')));
app.use(baseUrl, express.static(path.join(__dirname, 'config')));
app.set('host', process.env.HOST || '127.0.0.1');
app.set('port', process.env.PORT || 8000);
// auth: resolve mode, register public login routes (jwt mode), then gate everything below
const authMode = getAuthMode();
app.locals.authEnabled = authMode === 'jwt';
if (authMode === 'jwt') {
app.get(routes.login, loginPageHandler);
app.post(routes.login, loginHandler);
app.post(routes.logout, logoutHandler);
}
applyProtection(app);
// --- Routes ---
app.get(routes.root, (req, res) => {
crontab.reload_db();
crontab.import_crontab(() => {
crontab.public_crontabs((docs) => {
res.render('index', {
routes: JSON.stringify(routesRelative),
crontabs: JSON.stringify(docs),
backups: crontab.get_backup_names(),
dayjs,
});
});
});
});
app.get(routes.code_content, (req, res, next) => {
crontab.get_current_code(req.query._id, (err, currentCode) => {
if (err && err.status && err.status < 500) {
return res.status(err.status).json({ message: err.message || 'Request failed' });
}
if (err) {
const wrapped = new Error(err.message || 'Unable to read managed code file');
wrapped.statusCode = err.status || 500;
wrapped.cause = err.err;
return next(wrapped);
}
res.set('Cache-Control', 'no-store').json(currentCode);
});
});
app.post(routes.save, (req, res, next) => {
const afterDb = (err) => {
if (err && err.status === 409) {
return res.status(409).json({ message: 'Job was modified elsewhere', doc: err.doc });
}
if (err && err.status && err.status < 500) {
return res.status(err.status).json({ message: err.message || 'Request failed' });
}
if (err) return next(err.err || err);
crontab.deploy((deployErr) => {
if (deployErr) return next(deployErr);
res.end();
});
};
if (req.body._id == -1) { // eslint-disable-line eqeqeq
crontab.create_new(req.body, afterDb);
} else {
crontab.update(req.body, afterDb);
}
});
app.post(routes.stop, (req, res, next) => {
crontab.status(req.body._id, true, (err) => {
if (err) return next(err);
crontab.deploy((deployErr) => {
if (deployErr) return next(deployErr);
res.end();
});
});
});
app.post(routes.start, (req, res, next) => {
crontab.status(req.body._id, false, (err) => {
if (err) return next(err);
crontab.deploy((deployErr) => {
if (deployErr) return next(deployErr);
res.end();
});
});
});
app.post(routes.remove, (req, res, next) => {
crontab.remove(req.body._id, (err) => {
if (err) return next(err);
crontab.deploy((deployErr) => {
if (deployErr) return next(deployErr);
res.end();
});
});
});
app.post(routes.run, (req, res, next) => {
crontab.runjob(req.body._id, (err, result) => {
if (err) return handleTestRunError(err, res, next);
return res.set('Cache-Control', 'no-store').status(202).json(result);
});
});
function handleTestRunError(err, res, next) {
if (err && err.status >= 400 && err.status < 600) {
return res.status(err.status).json({
message: err.message || 'Request failed',
...(err.activeRun ? { activeRun: err.activeRun } : {}),
});
}
return next((err && err.err) || err);
}
app.get(`${routes.test_run}/active`, (_req, res) => {
const activeRun = crontab.get_active_test_run();
res.set('Cache-Control', 'no-store');
if (!activeRun) return res.status(204).end();
return res.json(activeRun);
});
app.get(`${routes.test_run}/job/:jobId/latest`, (req, res, next) => {
crontab.get_latest_test_run(req.params.jobId, (err, result) => {
if (err) return handleTestRunError(err, res, next);
return res.set('Cache-Control', 'no-store').json(result);
});
});
app.get(`${routes.test_run}/:id`, (req, res, next) => {
crontab.get_test_run(req.params.id, req.query, (err, result) => {
if (err) return handleTestRunError(err, res, next);
res.set('Cache-Control', 'no-store').json(result);
});
});
app.delete(`${routes.test_run}/:id`, (req, res, next) => {
crontab.stop_test_run(req.params.id, (err, result) => {
if (err) return handleTestRunError(err, res, next);
res.set('Cache-Control', 'no-store').status(202).json(result);
});
});
app.post(routes.test_run, (req, res, next) => {
crontab.test_run(req.body, (err, result) => {
if (err) return handleTestRunError(err, res, next);
res.set('Cache-Control', 'no-store').status(202).json(result);
});
});
app.get(routes.backup, (req, res, next) => {
crontab.backup(req.query.name, (err) => {
if (err) next(err);
else res.end();
});
});
app.get(routes.restore, validateDbParam, (req, res) => {
restore.crontabs(req.query.db, (docs) => {
const back = req.query.from === 'backups'
? (routesRelative.backups || '/')
: (routesRelative.root || '/');
res.render('restore', {
routes: JSON.stringify(routesRelative),
crontabs: JSON.stringify(docs),
backups: crontab.get_backup_names(),
db: req.query.db,
back,
});
});
});
app.get(routes.delete_backup, validateDbParam, (req, res) => {
restore.delete(req.query.db);
res.end();
});
app.get(routes.backups, (_req, res) => {
res.render('backups', {
routes: JSON.stringify(routesRelative),
backups: crontab.get_backup_names(),
details: crontab.get_backup_details(),
dayjs,
});
});
app.get(routes.delete_all_backups, (_req, res, next) => {
restore.deleteAll((err) => {
if (err) return next(err);
res.end();
});
});
app.get(routes.restore_backup, validateDbParam, (req, res) => {
crontab.restore(req.query.db);
res.end();
});
app.get(routes.export, (req, res) => {
const file = crontab.crontab_db_file;
const filename = path.basename(file);
const mimetype = mime.lookup(file);
res.setHeader('Content-disposition', `attachment; filename=${filename}`);
res.setHeader('Content-type', mimetype);
fs.createReadStream(file).pipe(res);
});
app.post(routes.import, (req, res, next) => {
crontab.backup((err) => {
if (err) return next(err);
req.pipe(req.busboy);
req.busboy.on('file', (_fieldname, file) => {
const fstream = fs.createWriteStream(crontab.crontab_db_file);
file.pipe(fstream);
fstream.on('close', () => {
crontab.reload_db();
res.redirect(routes.root);
});
});
});
});
app.get(routes.import_crontab, (_req, res, next) => {
crontab.backup((err) => {
if (err) return next(err);
crontab.import_crontab(() => res.end());
});
});
app.get(routes.preview_crontab, (req, res) => {
crontab.preview_crontab((result) => {
res.type('text/plain').send(result);
});
});
// PATCH: globals editor -- read/write the file of env-var lines prepended
// to the deployed crontab. Saving triggers a redeploy so changes apply
// immediately to /var/spool/cron/crontabs/root.
app.get(routes.globals, (req, res) => {
res.type('text/plain').send(crontab.get_globals());
});
app.post(routes.globals, (req, res, next) => {
crontab.set_globals(req.body.content || '', (err) => {
if (err) return next(err);
crontab.deploy((deployErr) => {
if (deployErr) return next(deployErr);
res.end();
});
});
});
function sendLog(filePath, req, res) {
if (fs.existsSync(filePath)) {
res.type('text/plain');
res.set('Cache-Control', 'no-store');
res.sendFile(filePath);
} else {
res.type('text/plain').send('No errors logged yet');
}
}
app.get(routes.logger, validateIdParam, (req, res) => {
sendLog(path.join(crontab.log_folder, `${req.query.id}.log`), req, res);
});
app.get(routes.stdout, validateIdParam, (req, res) => {
sendLog(path.join(crontab.log_folder, `${req.query.id}.stdout.log`), req, res);
});
// error handler
app.use(errorHandler);
let shutdownStarted = false;
function shutdown() {
if (shutdownStarted) return;
shutdownStarted = true;
console.log('Exiting crontab-ui');
crontab.shutdown_test_runs(() => process.exit());
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
const server = startHttpsServer
? https.createServer(credentials, app)
: http.createServer(app);
server.listen(app.get('port'), app.get('host'), () => {
console.log('Node version:', process.versions.node);
fs.access(crontab.db_folder, fs.constants.W_OK, (err) => {
if (err) {
console.error('Write access to', crontab.db_folder, 'DENIED.');
process.exit(1);
}
});
if (process.argv.includes('--autosave') || process.env.ENABLE_AUTOSAVE) {
crontab.autosave_crontab(() => {});
fs.watchFile(crontab.crontab_db_file, () => {
crontab.autosave_crontab(() => {
console.log('Attempted to autosave crontab');
});
});
}
if (process.argv.includes('--reset')) {
console.log('Resetting crontab-ui');
for (const file of [crontab.crontab_db_file, crontab.env_file]) {
console.log(`Deleting ${file}`);
try {
fs.unlinkSync(file);
} catch (_e) {
console.log(`Unable to delete ${file}`);
}
}
crontab.reload_db();
}
const protocol = startHttpsServer ? 'https' : 'http';
console.log(`Crontab UI (${packageJson.version}) is running at ${protocol}://${app.get('host')}:${app.get('port')}${baseUrl}`);
});
module.exports = app;