-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
485 lines (422 loc) · 14 KB
/
index.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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
module.exports = function (settings) {
if(typeof settings === 'string' && settings === 'require-watcher') {
return require('./require-watcher');
}
// OS
const os = require('os');
// Child Process
const { exec } = require("child_process");
// Cookie
const cookieParser = require("cookie-parser");
// Importing express module
const express = require("express");
// Importing express-session module
const session = require("express-session");
const { MemoryStore } = session;
// Watcher
const chokidar = require('chokidar');
// Importing file-store module
const filestore = require("session-file-store")(session);
// Router
const router = express.Router();
const path = require('path');
// Kill process
const { kill, killer } = require('cross-port-killer');
// Variables
let { username, password, application, pwcache, production, serverfile, neruservar, storage, removeterminal, watcher, depth, port } = settings;
let watcherlive = null;
// Validate
serverfile || (serverfile = 'index.js');
pwcache || (pwcache = 1); // 1h
neruservar || (neruservar = 'ner_user_auth');
storage || (storage = 'cookie'); // cookie | session | memory
username || (username = 'admin');
application || (application = router);
watcher || (watcher = null);
// production || (process.env.NODE_ENV)
// Storage
// - cookie
// - session
// - momey
if(storage === 'cookie') {
// Use Cookie
application.use(
cookieParser()
);
} else {
// Use Session
application.use(
session({
path: '/ner',
name: "session-nerw-name",
secret: "session-ner-key", // Secret key,
saveUninitialized: false,
resave: false,
unset: 'destroy',
maxAge: 1000 * 60 * pwcache, // 1 min
store: storage === 'memory' ? new MemoryStore({ checkPeriod: 1000 * 60 * pwcache, path: '/ner' }) : new filestore({}),
})
);
}
// Base HTML <pre>
const HTML_PRE = '<html><pre>';
// ----------------------------------------------------------------
// Authentication
// ----------------------------------------------------------------
// Check pw strong
const checkPassWord = (p) => p.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{6,}$/);
// Asking for the authorization
function auth(req, res, next) {
// No password
if(!password) {
const err = 'Set password on node-express-load package. \nhttps://www.npmjs.com/package/node-express-reload';
res.send(`${HTML_PRE}Error: ${err}`)
// throw new Error(err);
return;
}
// Bad password
if(!checkPassWord(password)) {
const err = `Change your password. \n- uppercase\n- lowercase\n- number\n- special character\n- 6 length`;
res.send(`${HTML_PRE}Error: ${err}`)
// throw new Error(err);
return;
}
// console.log(
// req.cookies,
// req.signedCookies,
// req.headers.authorization,
// req.headers
// )
// Get values authorization
const getData = () => {
const {authorization} = req.headers;
return authorization ? new Buffer.from(authorization.split(' ')[1], 'base64').toString().split(':') : ['', ''];
}
// Open dialog
const noAuthenticate = () => {
console.log('Unauthorized');
res.setHeader("WWW-Authenticate", "Basic")
res.sendStatus(401);
}
// Get user from storage
let userSTORAGE;
if(storage === 'cookie') {
userSTORAGE = req.cookies[neruservar];
} else {
userSTORAGE = req.session[neruservar];
}
// Checking authorization
if (userSTORAGE === username) {
// Allowed :))
next();
} else if (!userSTORAGE) {
// Get headers authorization
const [usernameAUTH, passwordAUTH] = getData();
// Check user and pass
if (usernameAUTH === username && passwordAUTH === password) {
// Storage
if(storage === 'cookie') {
// Cookie
res.cookie(`${neruservar}`, username, {
path: '/ner',
maxAge: 1000 * 60 * pwcache, // 1 min
});
} else {
// Session
req.session[neruservar] = username;
}
// Allowed :))
next();
} else {
// Ops :(
return noAuthenticate();
}
} else {
// Ops :(
return noAuthenticate();
}
}
// Run script
function execScript(script) {
return new Promise((resolve, reject) => {
try {
exec(script, (error, stdout, stderr) => {
if (error instanceof Error) {
console.error(error);
//throw new Error(error);
reject(error);
} else {
// console.log("stdout:\n", stdout);
// console.log("stderr:\n", stderr);
let out = stdout + stderr;
if(script.match(/kill/gi) && String(out).toLowerCase().match(/incomplete response received from application/gi)) {
resolve('Goodbye 👋 (maybe reload)');
} else {
resolve(out);
}
}
});
} catch (error) {
reject(error);
}
});
}
// Routers
// ----------------------------------------------------------------
// refresh
// res.redirect(req.get('referer'));
// https://www.npmjs.com/package/chokidar
// Terminal
router.get("/", auth, (req, res) => {
// req.baseUrl;
if(removeterminal === true) {
res.send("👋 HI, Welcome node-express-reload.");
} else {
res.sendFile( __dirname + '/src/terminal.html');
}
});
// List sessions and cookies
router.get("/sessions", auth, function(req, res){
console.log(req.session);
res.send({ session: req.session || {}, cookie: req.cookies || {} });
});
// Post
router.get("/port", (req, res) => {
res.send(`${req.socket.localPort}`);
});
// PID
router.get("/pid", (req, res) => {
res.send(`${process.pid}`);
});
// __dirname
router.get("/dirname", auth, (req, res) => {
res.send(`${__dirname}`);
});
// Logout
router.get("/logout", (req, res) => {
res.setHeader("WWW-Authenticate", "Basic"); // realm="Access to the staging site", charset="UTF-8"
res.status(401);
if(storage === 'cookie') {
// Clear cookie
res.cookie(neruservar, '', { path: '/ner', maxAge: 1, expires: Date.now(0), overwrite: true, httpOnly: true });
res.clearCookie(neruservar);
} else {
// Clear session
req.session[neruservar] = null;
delete req.session[neruservar];
}
res.send("Logout. 👋 Clear all cookies and session.");
});
// Destroy all
router.get("/destroy", auth, (req, res) => {
try {
// Destroy cookies
if(req.cookies){
for(const name in req.cookies) {
res.clearCookie(name);
}
}
// Destroy sessions
if(req.session){
req.session.cookie.expires = Date.now();
req.session.cookie.maxAge = 0;
req.session.destroy();
}
// Remove autehntication
res.setHeader("WWW-Authenticate", "Basic"); // realm="Access to the staging site", charset="UTF-8"
res.status(401);
// Message
res.send("Destroy all cookies and session.");
} catch (error) {
res.send("Ops. :(");
}
});
// Kill port
router.get("/kill-port/:port?", auth, function (req, res) {
// import exec method from child_process module
const port = req.params.port || req.socket.localPort;
console.log(`Killing port ${port}`);
// Unix
exec(`npx kill-port ${port}`);
return res.send(`Port ${port}`);
});
// 1
// https://www.npmjs.com/package/cross-port-killer
// 2
// https://www.npmjs.com/package/tree-kill
// Kill PID
router.get("/kill/:pid?", auth, function (req, res) {
// import exec method from child_process module
const pid = req.params.pid || process.pid;
let script = '';
console.log(`Killing pid ${pid}`);
killer.killByPids([pid]).then(() => console.log('done')).catch(err => {
// 'aix', 'darwin', 'freebsd','linux', 'openbsd', 'sunos', and 'win32'
switch(os.platform()) {
case 'win32':
script = `Taskkill /F /PID ${pid}`; break;
default:
script = `kill -9 ${pid}`; break;
}
execScript(script);
});
req.params.pid || process.exit();
return res.send(`Kill pid ${pid}`);
});
// path.basename('/foo/bar/baz/asdf/file.html'); // out: file.html
// Message:
// Incomplete response received from application
// Solution:
// usar spawn
// Reload PID
router.get("/reload/:pid?", auth, async function (req, res) {
// import exec method from child_process module
const pid = req.params.pid || process.pid;
let script = '';
console.log(`Reload pid ${pid}`);
// 'aix', 'darwin', 'freebsd','linux', 'openbsd', 'sunos', and 'win32'
switch(os.platform()) {
case 'win32': script = `Taskkill /F /PID ${pid} 1>2 & node ${serverfile}`; break;
default: script = `kill -9 ${pid} && node ${serverfile}`;
}
execScript(script);
return res.send( script ? `Reload pid ${pid}` : `Ops!` );
});
// List process
router.get("/list", auth, async function (req, res) {
let output = "";
let script = '';
// 'aix', 'darwin', 'freebsd','linux', 'openbsd', 'sunos', and 'win32'
switch(os.platform()) {
case 'win32': script = `tasklist /NH | findstr /I node`; break;
default: script = `ps -aef | grep 'node'`;
}
output += await execScript(script);
res.send(HTML_PRE + output)
});
// List all processes
router.get("/list-all", auth, async function (req, res) {
let output = "";
// 'aix', 'darwin', 'freebsd','linux', 'openbsd', 'sunos', and 'win32'
switch(os.platform()) {
case 'win32': output += await execScript("tasklist /NH"); break;
default: output += await execScript("ps -aef");
output += await execScript("lsof -i");
}
res.send(HTML_PRE + output)
});
// NPM install and uninstall
router.get("/npm/:type/:list", auth, async function (req, res) {
const list = String(req.params.list)
.replace(/[\n\r\t]/g, '') // scape
.replace(/[\'\"\`]/g, '') // scape
.replace(/\&/g, '') // scape
.replace(/\:/g, '') // scape
.replace(/\-\-/g,'') // scape
.replace(/\|/g, '/')
.split(",")
.join(" ");
let type =
req.params.type === "u"
? "uninstall"
: req.params.type === "i"
? "install"
: false;
if (!type || list.length < 4) {
res.send("Error");
return;
}
const script = `npm ${type} ${list}`;
const output = await execScript(script);
res.send(HTML_PRE + output)
});
// NPM fix
router.get("/npm/fix", auth, async function (req, res) {
const script = `npm audit fix`;
const output = await execScript(script);
res.send(HTML_PRE + output)
});
// NPM install package.json
router.get("/npm/install", auth, async function (req, res) {
const script = `npm install`;
const output = await execScript(script);
res.send(HTML_PRE + output)
});
// NPM ls
router.get("/npm/ls", auth, async function (req, res) {
const script = `npm ls`;
const output = await execScript(script);
res.send(HTML_PRE + output)
});
// NPM audit
router.get("/npm/audit", auth, async function (req, res) {
const script = `npm audit`;
const output = await execScript(script);
res.send(HTML_PRE + output)
});
// ----------------------------------------------------------------
// Watcher
// ----------------------------------------------------------------
// Watcher - Close
function watchClose() {
// Stop watching.
// The method is async!
watcherlive && watcherlive.close().then(() => console.log('closed'));
}
// Watcher - Start
(function(wtch) {
if(!wtch) return;
let dir = Array.isArray(wtch) ? wtch : [ String(wtch) ];
watcherlive = chokidar.watch(dir, {
ignored: /(^|[\/\\])\../, // ignore dotfiles
// ignored: '*.txt',
persistent: true,
depth: depth || 10,
}).on('all', (event, path) => {
console.log(event, path);
});
// watcherlive
// .on('add', path => console.log(`File ${path} has been added`))
// .on('change', path => {
// exec(`kill -9 ${process.pid} && node ${serverfile}`);
// console.log(`File ${path} has been changed @@@@`)
// })
// .on('unlink', path => console.log(`File ${path} has been removed`));
// More possible events.
// watcherlive
// .on('addDir', path => console.log(`Directory ${path} has been added`))
// .on('unlinkDir', path => console.log(`Directory ${path} has been removed`))
// .on('error', error => console.log(`Watcher error: ${error}`))
// .on('ready', () => console.log('Initial scan complete. Ready for changes'))
// .on('raw', (event, path, details) => { // internal
// console.log('Raw event info:', event, path, details);
// });
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
watcherlive.on('change', (path, stats) => {
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
switch(os.platform()) {
case 'win32': script = `Taskkill /F /PID ${process.pid}`; break;
default: script = `kill -9 ${process.pid} && node ${serverfile}`;
}
execScript(script);
process.exit();
});
})(watcher);
// Routers
// ----------------------------------------------------------------
router.get("/watcher/:close?", auth, (req, res) => {
const {close} = req.params || {};
if(close === 'close' || close === 'exit') {
watchClose();
res.send(`Close watcher list.`);
} else {
if(watcher) {
res.send(`Start watcher files and folders... ${Array.isArray(watcher) ? watcher.join(', ') : watcher }`);
} else {
res.send(`No have watcher list.`);
}
}
});
return router;
};