refactored data transfer, moved Functions to file

This commit is contained in:
Mathew committed 2019-04-27 14:53:18 +02:00
1 parent 2ebd410baf
commit c9b5dd20c1
4 files changed
+879 -833

No files matched your search

+169
View File
@@ -0,0 +1,169 @@
const chalk = require('chalk')
module.exports = class Functions{
static ID(n) {
/**
* thiserate random base64 string identificator.
* @param n number of charaters in string.
*
* @returns {string} generatred string
*/
var out = ""
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
for (var i = 0; i < n; i++)
out += chars.charAt(Math.floor(Math.random() * chars.length))
return out;
}
static date(format) {
/**
* thiserates current date in specified format
* long - DD/MM/YYYY HH:MM:SS
* log - DD/MMM HH:MM:SS
* @param {string} format date format
*
* @returns {string} date in specified format
*/
var d = new Date,
out = new String
switch (format) {
default:
case 'long':
let m = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()
let s = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds()
out = d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear() + " " + d.getHours() + ":" + m + ":" + s
break;
case 'log':
let p = new Date().toString().replace(/[A-Z]{3}\+/, '+').split(/ /)
out = p[2] + '/' + p[1] + ' ' + p[4]
break;
}
return out
}
static escape() {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
static multiLine(...arr) {
var out = "";
for (let key of arr) {
out += key.join("\n");
}
return out;
}
static hrtimeToMs(hrtime) {
return hrtime[0] * 1e3 + hrtime[1] / 1e6
}
static email(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
static isDefined(...d) {
for (let key in d) {
if (typeof d[key] != "undefined")
return d[key]
}
return undefined
}
static isNotNull(v, d) {
if (v == null)
return d
else
return v
}
static find(key, value, array) {
for (let index in array) {
if (typeof array[index] == 'object') return Che.find(key, value, array[index])
if (array[index][key] == value) return array[index]
}
return undefined
}
static log(data, lvl) { // log user information //user, session, action, data, ip
var lvl = lvl || 1,
verbose = typeof db != 'undefined' ? (typeof db.config != 'undefined' ? db.config.verbose : Infinity) : Infinity
if (lvl > verbose) return
var date = chalk.underline(this.date('log')) + ` ${"#".repeat(lvl)}`,
actions = {
'connect': () => console.log(`${date} CONNECTED ${chalk.gray(`${data.handle.ip} ${data.handle.shortid}`)}`),
'disconnect': () => console.log(`${date} DISCONNECTED ${chalk.gray(`${data.handle.ip} ${data.handle.shortid} ${data.handle.login}`)}`),
'auth': () => console.log(`${date} AUTH ${
data.handle.authStat === 0 ? 'OK ' : (
data.handle.authStat === 1 ? 'ERR ' : (
data.handle.authStat === 2 ? 'FAILED ' : '[]'
))
} ${chalk.gray(`${data.handle.ip} ${data.handle.shortid} ${data.handle.login}`)}`),
'command': () => console.log(`${date} ${data.com.req.com} ${
data.stat === 0 ? ' ' : (
data.stat === 1 ? 'ERR ' : (
data.stat === 2 ? 'FAILED ' : '[]'
))
} ${chalk.gray(`${data.handle.ip} ${data.handle.shortid} ${data.handle.login}`)}`)
,
// 'denied': () => console.log(`${date} ${chalk.magenta(data.udata.login + " " + data.udata.shortid + " !>! " + data.data.c + " " + data.data.arg)}`),
'login': () => console.log(`${date} ${data.udata.login} ${data.udata.shortid} <-< [${data.data.arg[0]}]`),
'logout': () => console.log(`${date} ${data.udata.login} ${data.udata.shortid} >-> [guest]`),
// 'unknown': () => console.log(`${date} ${chalk.yellow(`${data.udata.login} ${data.udata.shortid} ?>? ${data.data.c} ${data.data.arg}`)}`),
'err': () => console.log(`${date} err -!- ${data.data}`),
'info': () => console.log(`${date} ${chalk.cyan(data.data)}`),
'req': () => {
let status = data.handle.status
switch (parseInt(status.toString()[0])) {
case 1: status = chalk.cyan(status); break;
case 2: status = chalk.green(status); break;
case 3: status = chalk.yellow(status); break;
case 4: status = chalk.magenta(status); break;
case 5: status = chalk.red(status); break;
}
console.log(`${date} ${data.handle.method} ${status} ${data.handle.path} ${data.handle.ip}`);
}
};
if (actions[data.action]) {
actions[data.action]()
} else {
console.log(data)
}
}
static blink() { // blink the status led
// cmd.run('python /home/mathias/python/blink.py');
}
static getUptime() {
var uptime = cmd.get("uptime -p", function (err, data, stderr) {
if (err) {
throw err
} else if (stderr) {
throw stderr
} else if (data) {
db.stats.uptime = data
}
})
}
}
+269 -491
View File
@@ -1,20 +1,59 @@
// dependencies
const
conf = require('./conf.json'),
data = require('./db.json'),
express = require('express'),
bodyParser = require('body-parser'),
path = require('path'),
fs = require("fs"),
cmd = require('node-cmd'),
cookieParser = require('cookie-parser'),
// bcrypt = require('bcrypt'),
http = require('http'),
https = require('https'),
socket = require('socket.io'),
chalk = require('chalk'),
nodemailer = require('nodemailer'),
{ gzip, ungzip } = require('node-gzip')
// // dependencies
// const conf = require('./conf.json')
// console.log('loading')
// const data = require('./db.json')
// console.log('loading')
// const express = require('express')
// console.log('loading')
// const bodyParser = require('body-parser')
// console.log('loading')
// const path = require('path')
// console.log('loading')
// const fs = require("fs")
// console.log('loading')
// const cmd = require('node-cmd')
// console.log('loading')
// const cookieParser = require('cookie-parser')
// console.log('loading')
// // const bcrypt = require('bcrypt')
// console.log('loading')
// const http = require('http')
// console.log('loading')
// const https = require('https')
// console.log('loading')
// const socket = require('socket.io')
// console.log('loading')
// const chalk = require('chalk')
// console.log('loading')
// const nodemailer = require('nodemailer')
// console.log('loading')
// const { gzip, ungzip } = require('node-gzip')
// console.log('loading')
const dependencies = [
['Functions', './Functions.js'],
['conf', './conf.json'],
['data', './db.json'],
'express',
['bodyParser', 'body-parser'],
'path',
'fs',
'node-cmd',
['cookieParser', 'cookie-parser'],
'http', 'https',
['socket', 'socket.io'],
'chalk',
'nodemailer',
'node-gzip'
]
for(let dep of dependencies){
if(typeof dep == 'string') var name = value = dep
else if(dep instanceof Array) var name = dep[0], value = dep[1]
global[name] = require(value)
Functions.log({ action: 'info', data: `Loading '${name}' module` })
}
// other
const
@@ -28,13 +67,13 @@ const
}
})
// ssl credentials
if (conf.cert.key && conf.cert.crt && conf.cert.ca && conf.cert.enable)
credentials = {
key: fs.readFileSync(conf.cert.key, 'utf8'),
cert: fs.readFileSync(conf.cert.crt, 'utf8'),
ca: fs.readFileSync(conf.cert.ca, 'utf8')
}
// // ssl credentials
// if (conf.cert.key && conf.cert.crt && conf.cert.ca && conf.cert.enable)
// credentials = {
// key: fs.readFileSync(conf.cert.key, 'utf8'),
// cert: fs.readFileSync(conf.cert.crt, 'utf8'),
// ca: fs.readFileSync(conf.cert.ca, 'utf8')
// }
class DataBase {
@@ -119,6 +158,7 @@ class DataBase {
this._macNames = {
"70:85:c2:70:88:37": "DESKTOP",
'40:65:a3:90:2a:04': "dekoder",
'dc:0e:a1:18:a9:2e': "SERVER",
'68:a3:c4:c7:27:90': "TOSHIBA",
'90:72:82:0d:77:ec': "funbox",
'0c:8f:ff:64:de:58': "Huawei P10 Lite",
@@ -159,7 +199,7 @@ class DataBase {
this.f(this.params)
this.exit(true)
} catch (error) {
Exe.log({ action: "info", data: "Event Error" }, 1)
Functions.log({ action: "info", data: "Event Error" }, 1)
this.exit(error)
}
}
@@ -169,7 +209,7 @@ class DataBase {
_check() {
Exe.log({ action: "info", data: "Checking Events" }, 3)
Functions.log({ action: "info", data: "Checking Events" }, 3)
var now = new Date()
var next = new Date()
@@ -177,7 +217,7 @@ class DataBase {
for (let e of this._list) {
if (!e.stats.done) {
if (e.time.getTime() <= now.getTime()) {
Exe.log({ action: "info", data: "Event Found" }, 2)
Functions.log({ action: "info", data: "Event Found" }, 2)
e.exec()
} else {
if ((e.time.getTime() < next.getTime()) || (next.getTime() == now.getTime())) {
@@ -190,7 +230,7 @@ class DataBase {
// for(let e of this._regular){
// if(!e.stats.done){
// if(e.time[e.time.when[0]]() - now[e.time.when[0]]()){
// Exe.log({action: "info", data: "Event Found"}, 2)
// Functions.log({action: "info", data: "Event Found"}, 2)
// e.exec()
// }else{
// console.log((e.time[e.time.when[0]]() - now[e.time.when[0]]()) *e.time.when[1])
@@ -203,7 +243,7 @@ class DataBase {
let n = next.getTime() - now.getTime()
if (n != 0) {
Exe.log({ action: "info", data: `Next event check in: ${n} ms` }, 3)
Functions.log({ action: "info", data: `Next event check in: ${n} ms` }, 3)
// clearTimeout(this.timeout)
this.timeout = setTimeout(function (s) { s._check() }, n, this)
return
@@ -240,7 +280,7 @@ class DataBase {
getDevices() {
Exe.log({
Functions.log({
action: "info",
data: "Updating device list"
}, 2)
@@ -255,7 +295,7 @@ class DataBase {
let m
var len = 0
Exe.log({
Functions.log({
action: "info",
data: "arp-scan done"
}, 3)
@@ -284,7 +324,7 @@ class DataBase {
mac: m[2],
desc: m[3],
name: name,
connected: Gen.date('long')
connected: Functions.date('long')
}
}
@@ -308,7 +348,7 @@ class DataBase {
if (!list[key]) { // goes offline
db.stats.offline[key] = db.stats.network[key];
db.stats.offline[key].disconnected = Gen.date('long')
db.stats.offline[key].disconnected = Functions.date('long')
delete db.stats.network[key]
@@ -325,7 +365,7 @@ class DataBase {
// for(let key in db.stats.network){
// if(!db.stats.offline[key]){
// db.stats.offline[key] = db.stats.network[key];
// db.stats.offline[key].date = Gen.date()
// db.stats.offline[key].date = Functions.date()
// }
//
// }
@@ -336,7 +376,7 @@ class DataBase {
// }
// }
Exe.log({
Functions.log({
action: "info",
data: `arp-scan -> ${len} devices online`
}, 3)
@@ -348,15 +388,15 @@ class DataBase {
addAccount(data) {
Exe.log({
Functions.log({
action: "info",
data: "Creating user account"
}, 2);
var id = (function (len, users) {
var id = Gen.ID(len);
var id = Functions.ID(len);
while (users[id]) {
id = Gen.ID(len);
id = Functions.ID(len);
}
return id
})(6, this.data.users)
@@ -372,7 +412,7 @@ class DataBase {
saveData() {
Exe.log({
Functions.log({
action: "info",
data: "Saving database file"
}, 1);
@@ -382,7 +422,7 @@ class DataBase {
console.log(err);
return err;
} else {
Exe.log({
Functions.log({
action: "info",
data: "Database saved"
}, 2);
@@ -391,27 +431,6 @@ class DataBase {
});
}
verify(credentials) {
if (credentials) {
if (credentials.token) {
var token = credentials.token.split(":");
if (token.length == 2) {
if (typeof this.data.tokens[token[0]] != "undefined") {
if (this.data.tokens[token[0]] == token[1]) {
return new Connection(credentials, this.data.users[token[0]]);
} else {
console.log("identity theft attempt")
}
}
}
}
return new Connection(credentials);
}
throw Error("verify credentials undefined")
}
checkPermissions(request, udata) { // check permissions
if (typeof this.commands[request.com] != "undefined") {
@@ -484,9 +503,9 @@ class DataBase {
emitToGroup(e, data, group, direction) {
var direction = Che.isDefined(direction, "only")
var direction = Functions.isDefined(direction, "only")
Exe.log({
Functions.log({
action: "info",
data: `Emit to group ${group} ${direction}`
}, 3);
@@ -510,33 +529,46 @@ class DataBase {
}
class Connection {
constructor(credentials, user) {
var user = Che.isDefined(user, {
login: "guest",
group: 9,
ll: "n/a"
})
class Connection{
constructor(obj){
var {req, res, socket, cred} = obj
if(obj.req){
switch (user.group) {
case 0: this.badge = "txred"; break;
case 1: this.badge = "txblu"; break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9: this.badge = "txcya"; break;
}
if(req.headers['x-forwarded-for'])
this.ip = req.headers['x-forwarded-for']
else
this.ip = req.ip
this.shortid = Functions.ID(6)
this.method = req.method
this.status = res.statusCode
this.path = req.path
this.hostname = req.hostname
this.secure = req.secure
this.login = user.login;
this.group = user.group;
this.ll = user.ll;
this.ip = credentials.ip.slice(7);
this.socketid = credentials.socketid;
this.shortid = Gen.ID(6);
this.req = obj.req
}else if(obj.socket){
if (socket.handshake.headers['x-forwarded-for'])
this.ip = socket.handshake.headers['x-forwarded-for']
else
this.ip = socket.handshake.address
this.shortid = Functions.ID(6)
this.secure = socket.handshake.secure
this.hostname = socket.handshake.headers.host
this.socket = socket
this.login = 'guest'
this.group = 9
this.ll = 'n/a'
this.badge = 'txcya'
this.coms = []
this.authStat = 1
}else throw new Error("Unknown connection type")
}
get userInfo() {
@@ -549,373 +581,109 @@ class Connection {
}
}
auth(cred){
if(cred){
if(cred.token && cred.user){
if (db.data.tokens[cred.user]){
var n = db.data.tokens[cred.user].indexOf(cred.token)
if (n != -1) {
var user = db.data.users[cred.user]
this.login = user.login
this.group = user.group
this.ll = user.ll
this.badge = (grp => {
switch (grp) {
case 0: return "txred"
case 1: return "txblu"
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9: return "txcya"
}
})(user.group)
this.authStat = 0
return 0
} else {
this.authStat = 2
return 2
}
}else{
this.authStat = 3
return 3
}
}
}
}
}
class Response {
constructor(obj, socket) {
this.socket = socket;
this.ready = false;
this.error = undefined;
this.sent = false;
this.lui = undefined;
class Com {
constructor(req, handle) {
this.handle = handle
this.req = req
this.req = obj;
// this.req.com = obj.com;
// this.req.arg = obj.arg;
// this.req.dir = obj.dir;
// this.req.id = Che.isDefined(obj.id, null);
// this.req.con = Che.isDefined(obj.con, 0);
// this.req.udata = Che.isDefined(obj.udata, null);
this.data = {
blocks: []
}
this.res = {};
this.res.data = null;
this.res.flag = 0;
this.res.arg = null;
this.res.frm = "root";
this.res.dir = null;
this.res.lui = null;
this.res.udata = this.socket.udata.userInfo;
this.res.con = this.req.con;
this.res.id = this.req.id;
this.res.time = [];
this.start = process.hrtime();
this.lastTime = this.start;
this.res = {
udata: handle.userInfo,
con: req.con,
id: req.id,
}
}
addTime(desc, hrt) {
addTime(){}
let t = Che.isDefined(hrt, process.hrtime(this.lastTime));
this.lastTime = process.hrtime();
this.res.time.push(
[
Tra.hrtimeToMs(t),
desc
]
);
Block(data, meta) {
var data = Functions.isDefined(data, {}),
meta = Functions.isDefined(meta, {})
return {
id: Functions.ID(6),
sent: false,
data: data,
meta: meta,
}
}
insert(data, meta) {
this.data.blocks.push(this.Block(data, meta))
var newN = this.data.blocks.length - 1
this.data.blocks[newN].meta.n = newN
this.update()
return this
}
insert(data) {
for (let key in data) {
if (key in this.res) {
this.res[key] = data[key];
} else {
this.error = 0x00; // invalid input data
update() {
for (let block of this.data.blocks) {
if (!block.sent) {
block.sent = true
this._send(block)
}
}
this.ready = true;
this.lui = Che.isNotNull(this.res.lui, "command");
this.addTime("Response.insert");
return this
}
denied() {
this.insert({
data: this.req.com + ": Permission denied",
flag: 6,
arg: "error"
end() {
this.update()
this.handle.socket.emit('com', {
res: this.res,
data: null,
meta: null
});
this.lui = "denied";
this.addTime("Response.denied");
this.send();
}
unknown() {
this.insert({
data: this.req.com + ": Command not found",
flag: 6,
arg: "error"
_send(block) {
this.handle.socket.emit('com', {
res: this.res,
data: block.data,
meta: block.meta
});
this.lui = "unknown";
this.addTime("Response.unknown");
this.send();
}
send() {
this.addTime("Response.send");
this.addTime("Total", process.hrtime(this.start));
if (this.ready) {
if (!this.sent) {
if (!this.error) {
this.socket.emit("com", this.res);
Exe.log({
action: this.lui,
udata: this.socket.udata,
id: this.socket.id,
data: {
c: this.req.com,
arg: this.req.arg
}
});
this.sent = true;
this.error = false;
return true
} else {
this.error = 0x01 // error occured, stop
Exe.log({
data: "Command send error: " + this.error
});
return false
}
} else {
this.error = 0x02 // res already sent
Exe.log({
data: "Command send error: " + this.error
});
return false
}
} else {
this.error = 0x03 // data not ready
Exe.log({
data: "Command send error: " + this.error
});
return false
}
}
}
class Gen {
/**
* Helper Class
* Generate data
*
*/
static ID(n) {
/**
* Generate random base64 string identificator.
* @param n number of charaters in string.
*
* @returns {string} generatred string
*/
var out = ""
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
for (var i = 0; i < n; i++)
out += chars.charAt(Math.floor(Math.random() * chars.length))
return out;
}
static date(format) {
/**
* Generates current date in specified format
* long - DD/MM/YYYY HH:MM:SS
* log - DD/MMM HH:MM:SS
* @param {string} format date format
*
* @returns {string} date in specified format
*/
var d = new Date,
out = new String
switch (format) {
default:
case 'long':
let m = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()
let s = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds()
out = d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear() + " " + d.getHours() + ":" + m + ":" + s
break;
case 'log':
let p = new Date().toString().replace(/[A-Z]{3}\+/, '+').split(/ /)
out = p[2] + '/' + p[1] + ' ' + p[4]
break;
}
return out
}
}
class Tra {
/**
* Helper Class
* Transform data
*
*/
static escape() {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
static multiLine(...arr) {
var out = "";
for (let key of arr) {
out += key.join("\n");
}
return out;
}
static hrtimeToMs(hrtime) {
return hrtime[0] * 1e3 + hrtime[1] / 1e6
}
}
class Che {
/**
* Helper Class
* Check data
*
*/
static email(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
static isDefined(...d) {
for (let key in d) {
if (typeof d[key] != "undefined")
return d[key]
}
return undefined
}
static isNotNull(v, d) {
if (v == null)
return d
else
return v
}
}
class Exe {
/**
* Helper Class
* Execute actions
*
*/
static log(obj, lvl) { // log user information //user, session, action, data, ip
var lvl = Che.isDefined(lvl, 1)
if (lvl > db.config.verbose) return
var d = chalk.underline(Gen.date('log')) + ` ${"#".repeat(lvl)} `;
if (typeof obj.ip != "undefined") {
if (obj.ip == "::1") return
obj.ip = obj.ip.slice(7);
}
switch (obj.action) {
default:
console.log(" --- ");
break;
case "disconnect":
console.log(`${d}${chalk.gray(`${obj.udata.login} ${obj.udata.shortid} --> disconnected`)}`);
break;
case "connect":
console.log(`${d}${chalk.gray(`[${obj.udata.ip}] --connected--`)}`);
break;
case "auth":
console.log(`${d}${chalk.gray(`[${obj.udata.ip}] --auth--> \'${obj.udata.login}\' \'${obj.udata.shortid}\'`)}`)
break;
case "command":
console.log(`${d}\'${obj.udata.login}\' \'${obj.udata.shortid}\' --comm--> \"${obj.data.c} ${obj.data.arg}\"`);
break;
case "denied":
console.log(d + chalk.magenta(obj.udata.login + " " + obj.udata.shortid + " !>! " + obj.data.c + " " + obj.data.arg));
break;
case "login":
console.log(d + obj.udata.login + " " + obj.udata.shortid + " <-< [" + obj.data.arg[0] + "]");
break;
case "logout":
console.log(d + obj.udata.login + " " + obj.udata.shortid + " >-> [guest]");
break;
case "data":
if (db.config.dlog)
console.log(d + "data -+- " + obj.data);
break;
case "err":
console.log(d + "err -!- " + obj.data);
break;
case "info":
console.log(d + chalk.red(obj.data));
break;
case "req":
switch (parseInt(obj.response.toString()[0])) {
case 1: obj.response = chalk.cyan(obj.response); break;
case 2: obj.response = chalk.green(obj.response); break;
case 3: obj.response = chalk.yellow(obj.response); break;
case 4: obj.response = chalk.magenta(obj.response); break;
case 5: obj.response = chalk.red(obj.response); break;
}
console.log(d + obj.type + " " + obj.response + " " + obj.path + " " + obj.ip);
break;
case "unknown":
console.log(d + chalk.yellow(obj.udata.login + " " + obj.udata.shortid + " ?>? " + obj.data.c + " " + obj.data.arg));
break;
}
Exe.blink();
}
static blink() { // blink the status led
cmd.run('python /home/mathias/python/blink.py');
}
static runCommand(req, socket) { // execute sent command
var response = new Response(req, socket);
response.addTime("command-execute");
if (db.commands[response.req.com]) {
response.addTime("permchek");
if (db.checkPermissions(response.req, response.socket.udata)) {
db.commands[response.req.com].f(response, db)
} else response.denied();
} else response.unknown();
}
static getUptime() {
var uptime = cmd.get("uptime -p", function (err, data, stderr) {
if (err) {
throw err
} else if (stderr) {
throw stderr
} else if (data) {
db.stats.uptime = data
}
})
}
}
function save(file, data) { // save data to file
@@ -938,12 +706,12 @@ function dataparse(data) { // parse data coming from /data
if (key != "type") db.stats[key] = obj[key]
}
Exe.log({
Functions.log({
action: "data",
data: "Data recieved succesfully. " + "[Length: " + l + "]"
});
} catch (e) {
Exe.log({
Functions.log({
action: "err",
data: "Invalid JSON string recieved. " + "[Length: " + l + "]"
});
@@ -959,14 +727,14 @@ function dataparse(data) { // parse data coming from /data
}
// emto(obj, to)
Exe.blink();
Functions.blink();
}
function gpath(dir, arg) { // get path
var path = [];
Che.isDefined(arg, ""); // if no user argument replace with empty
Functions.isDefined(arg, ""); // if no user argument replace with empty
if (arg.startsWith("\/")) { // if arg is absolute, dont merge
path = arg.slice(1).split("\/");
@@ -1080,6 +848,11 @@ function fsearch(dir, name) {
return is
}
function exit(sig) {
console.log(`\n${sig}`)
process.exit(0)
}
// express setup
app
.set('view engine', 'ejs')
@@ -1087,22 +860,20 @@ app
.use(bodyParser.json())
.use(cookieParser())
.use(express.static(path.join(__dirname, 'public')))
.use(function (req, res, next) {
var handle = new Connection({req: req, res: res})
res.on("finish", function () {
Exe.log({
Functions.log({
action: "req",
type: req.method,
response: res.statusCode,
path: req.path,
ip: req.ip
req: req,
res: res,
handle: handle
});
});
next()
});
app.use(function (err, req, res, next) {
return res.status(404).send("404");
});
})
// .use((err, req, res, next) => res.status(404).render('pages/404.ejs'))
// server setup
@@ -1115,6 +886,8 @@ if (conf.cert.enable) {
io.attach(httpsServer)
}
process.on('SIGINT', exit)
// stdin input listener
stdin.addListener("data", function (d) {
c = d.toString().trim();
@@ -1130,7 +903,7 @@ global.db = new DataBase(data);
db.onReady = function () {
Exe.log({
Functions.log({
action: "info",
data: "DataBase ready"
}, 1);
@@ -1145,7 +918,7 @@ db.onReady = function () {
// http standard server
httpServer.listen(conf.ports.main, function () {
Exe.log({
Functions.log({
action: "info",
data: `Server listening on port ${conf.ports.main}`
}, 1);
@@ -1153,59 +926,64 @@ httpServer.listen(conf.ports.main, function () {
// https secure server
if (conf.cert.enable) httpsServer.listen(conf.ports.ssl, function () {
Exe.log({
Functions.log({
action: "info",
data: `Server listening on port ${conf.ports.ssl}`
}, 1);
});
// socketio events
io.on('connection', function (socket) { // connection established event
io.on('connection', function (socket) {
// verify user information
socket.udata = db.verify({
// token: socket.request._query.token,
ip: socket.handshake.address,
socketid: socket.id
var handle = new Connection({socket: socket})
db.addConnection(handle)
Functions.log({ action: "connect", handle: handle });
socket.on('disconnect', function () {
db.removeConnection(handle)
Functions.log({ action: "disconnect", handle: handle });
});
db.addConnection(socket.udata) // add current connection data to online users list
Exe.log({
action: "connect",
udata: socket.udata
});
socket.on('disconnect', function () { // connection disconnect event
Exe.log({
action: "disconnect",
udata: socket.udata
});
db.removeConnection(socket.udata); // remove current connection data from online users list
});
socket.on('auth', function (data) { // user command request
socket.udata = db.updateConnection(socket.udata, db.verify({
token: data ? data.token : undefined,
ip: socket.handshake.address,
socketid: socket.id
}))
Exe.log({
action: "auth",
udata: socket.udata
});
socket.emit("auth", socket.udata.userInfo)
socket.on('auth', function (data) { // user authorization request
handle.auth(data)
socket.emit("auth", handle.userInfo)
Functions.log({ action: "auth", handle: handle });
});
socket.on('com', function (data) { // user command request
if (data.dir == "~") data.dir = "\/home\/" + socket.udata.login; // home path translation
// if (data.dir == "~") data.dir = "\/home\/" + socket.udata.login; // home path translation
Exe.runCommand(data, socket); // command execution
var com = handle.coms.find(el => el.res.id == data.id)
if (!com) {
com = new Com(data, handle)
handle.coms.push(com)
}
if (db.commands[com.req.com]) {
if (db.checkPermissions(com.req, handle)) {
Functions.log({ action: "command", handle: handle, com: com, stat: 0 })
db.commands[com.req.com].f(com, db)
} else {
Functions.log({ action: "command", handle: handle, com: com, stat: 2 })
com.insert(com.req.com + ": Permission denied", {
flag: 6,
arg: "error"
}).end()
}
} else {
Functions.log({ action: "command", handle: handle, com: com, stat: 1 })
com.insert({
data: com.req.com + ": Command not found"
}, {
flag: 6,
arg: "error"
}).end()
}
});
+157 -167
View File
@@ -2,30 +2,46 @@ const PERM_FULL = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
const PERM_ROOT = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
const PERM_NULL = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
const STAGE_F = "functional"
const STAGE_D = "development"
const STAGE_F = 1 // functional
const STAGE_D = 2 // development
const STAGE_B = 3 // bugs / not working
module.exports = {
motd: {
f: com => {
com.insert('hey', {
flag: 0
});
com.end();
},
desc: "Welcome message",
args: [],
man: "user manual",
permissions: PERM_FULL,
stage: STAGE_F
},
help: {
f: (response, db) => {
if(response.req.arg[0]){ // command manual
var c = response.req.arg[0];
var cc = db.commands[response.req.arg[0]]
f: (com, db) => {
if(com.req.arg[0]){ // command manual
var c = com.req.arg[0];
var cc = db.commands[com.req.arg[0]]
if(cc){
response.insert({data: cc.man}).send()
com.insert(cc.man).end()
}else{
response.insert({data: `User manual for ${c} not found`, flag: 6, arg: "error"}).send()
com.insert(`User manual for ${c} not found`, {flag: 6, arg: "error"}).end()
}
}else{ // commands list
response.insert({data:
(function(commands, response){
com.insert(
(function(commands, com){
var out = []
for(let com in commands){
if (commands[com].permissions[response.socket.udata.group] !== 1){
for(let command in commands){
if (commands[command].permissions[com.handle.group] !== 1){
continue
}
out.push([`<txred>${com}</txred> ${(function(args){
out.push([`<txred>${command}</txred> ${(function(args){
let out = ""
for(let arg of args){
if(arg.startsWith("[") && arg.endsWith("]")){ // necessary
@@ -39,11 +55,11 @@ module.exports = {
out += arg+" "
}
return out
})(commands[com].args)}`, commands[com].desc])
})(commands[command].args)}`, commands[command].desc])
}
return out
})(db.commands, response)
, flag: 10}).send()
})(db.commands, com)
, {flag: 10}).end()
}
@@ -57,23 +73,20 @@ module.exports = {
},
evals: {
f: response => {
f: com => {
try{
var e = eval(response.req.arg.join(" "));
response.insert({
data: e,
var e = eval(com.req.arg.join(" "));
com.insert(e, {
flag: 9
});
}catch(error){
console.log(error);
response.insert({
data: error.message,
com.insert(error.message, {
flag: 6,
arg: "error"
});
}
response.send();
com.end();
},
desc: "Eval-server. Executes js code on server",
args: ["[javascript]"],
@@ -84,17 +97,17 @@ module.exports = {
},
about: {
f: response => {
response.insert({
data: [
["<txblu>Facebook</txblu>", "<a target='_blank' href='http://facebook.com/pstrucha.mateusz'>/pstrucha.mateusz</a>"],
["<txorn>Reddit</txorn>", "<a target='_blank' href='http://reddit.com/u/mathias_-'>/u/mathias_-</a>"],
["<txdbl>GitHub</txdbl>", "<a target='_blank' href='https://github.com/Maathias'>/Maathias</a>"],
["<txblu>Discord</txblu>", "<a target='_blank' href='https://discord.gg/z8kW2eY'>WKR</a>"],
["<txorn>StackOverflow</txorn>", "<a target='_blank' href='https://stackoverflow.com/users/7358565/mathias'>mathias</a>"]
],
flag: 10
}); response.send();
f: com => {
com.insert([
["<txblu>Facebook</txblu>", "<a target='_blank' href='http://facebook.com/pstrucha.mateusz'>/pstrucha.mateusz</a>"],
["<txorn>Reddit</txorn>", "<a target='_blank' href='http://reddit.com/u/mathias_-'>/u/mathias_-</a>"],
["<txdbl>GitHub</txdbl>", "<a target='_blank' href='https://github.com/Maathias'>/Maathias</a>"],
["<txblu>Discord</txblu>", "<a target='_blank' href='https://discord.gg/z8kW2eY'>WKR</a>"],
["<txorn>StackOverflow</txorn>", "<a target='_blank' href='https://stackoverflow.com/users/7358565/mathias'>mathias</a>"]
], {
flag: 10
});
com.end();
},
desc: "Displays contact info",
args: [],
@@ -104,53 +117,34 @@ module.exports = {
},
do: {
f: response => {
response.addTime("do.begin");
var out = cmd.get(response.req.arg.join(" "), function(err, data, stderr){
response.addTime("do.end");
if(stderr){
response.insert({
data: stderr,
flag: 6,
arg: "error"
});
}else if(err){
response.insert({
data: err,
flag: 6,
arg: "error"
});
}else{
response.insert({
data: data,
flag: response.req.arg[0]=="cat"?11:0
});
}
bash: {
f: com => {
cmd = require('node-cmd')
if (!com.cmd) {
com.cmd = cmd.run('bash')
com.cmd.stdin.setEncoding('utf-8')
com.cmd.stdout.on('data', data => { com.insert(data) })
}
com.cmd.stdin.write(`${com.req.arg[0]}\n`)
response.send();
});
setTimeout(function(out){
response.addTime("do.kill");
cmd.run(`kill ${out.pid}`)
}, 15000, out)
},
desc: "Executes linus commands (on root)",
args: ["[linux syntax]"],
man: "user manual",
permissions: PERM_ROOT,
stage: STAGE_F
permissions: PERM_FULL,
stage: STAGE_B
},
ping: {
f: response => {
response.insert({
data: "pong",
flag: 12
}).send();
f: com => {
com.insert("pong", {
flag: 0
}).end();
},
desc: "tests internet connection",
desc: "tests requeest latency",
args: [],
man: "user manual",
permissions: PERM_FULL,
@@ -159,16 +153,15 @@ module.exports = {
},
uptime: {
f: response => {
response.insert({
data: [
f: com => {
com.insert([
[`<txred>Uptime:</txred>`, `<span class="info0">${db.stats['uptime']}</span>`],
[`<txred>Load average:</txred>`, `<span class="info1">${db.stats['load1']}</span>% <span class="info2">${db.stats['load2']}</span>% <span class="info3">${db.stats['load3']}</span>%`],
[`<txred>Memory:</txred>`, `<span class="info4">${db.stats['memory']}</span>%`],
[`<txred>In terminal:</txred>`, `<span class="info5">${db.stats['users']}</span>`]
],
], {
flag: 10 // toTable
}); response.send();
}); com.end();
},
desc: "Displays current OS stats",
args: [],
@@ -179,17 +172,15 @@ module.exports = {
},
stats: {
f: response => {
response.insert({
//'[TIME] <txblu>'+new Date()+'</txblu>'+
data: [
f: com => {
com.insert([
["[TEMP]", `<txyel>OUTSIDE: </txyel><span class="info6">${db.stats['tempout']}</span>C`, `<txcya>INSIDE: </txcya><span class="info7">${db.stats['tempin']}</span>C`],
["[HUM]", `<txyel>OUTSIDE: </txyel><span class="info8">${db.stats['humout']}</span>%`, `<txcya>INSIDE: </txcya><span class="info9">${db.stats['humin']}</span>%`]
],
], {
flag: 10 // toTable
// data: <br></span> <br></span> <br></span>[BED] '+(info['bed']?"occupied":"empty")
});
response.send();
com.end();
},
desc: "Displys current physical stats",
args: [],
@@ -200,11 +191,10 @@ module.exports = {
},
devices: {
f: response => {
response.insert({
data: {Network: db.stats.network, Offline: db.stats.offline},
f: com => {
com.insert({Network: db.stats.network, Offline: db.stats.offline}, {
flag: 9 // toTree
}); response.send();
}); com.end();
},
desc: "Display network devices connection history",
args: [],
@@ -215,18 +205,18 @@ module.exports = {
},
connection: {
f: response => {
response.insert({
data: [
["<txcya>socket</txcya>.<txred>shortid</txred>", response.socket.udata.shortid],
["<txcya>socket</txcya>.<txred>ip</txred>", response.socket.udata.ip],
["<txcya>socket</txcya>.<txred>hostname</txred>", response.socket.handshake.headers.host],
["<txcya>socket</txcya>.<txred>ssl</txred>", response.socket.handshake.secure],
["<txcya>Last Login</txcya>", response.socket.udata.ll],
["<txcya>Permission Group</txcya>", response.socket.udata.group]
],
f: com => {
com.insert([
["<txcya>handle</txcya>.<txred>shortid</txred>", com.handle.shortid],
["<txcya>handle</txcya>.<txred>ip</txred>", com.handle.ip],
["<txcya>handle</txcya>.<txred>hostname</txred>", com.handle.hostname],
["<txcya>handle</txcya>.<txred>ssl</txred>", com.handle.secure],
["<txcya>Last Login</txcya>", com.handle.ll],
["<txcya>Permission Group</txcya>", com.handle.group]
], {
flag: 10 // toTable
}); response.send();
});
com.end()
},
desc: "Displays current socket connection data",
args: [],
@@ -237,41 +227,41 @@ module.exports = {
},
login: {
f: response => {
f: com => {
if( // data validation
(typeof response.req.arg != "object")||
(typeof response.req.arg.remember != 'boolean')||
(typeof response.req.arg.login != 'string')||
(typeof response.req.arg.pass != 'string')
(typeof com.req.arg != "object")||
(typeof com.req.arg.remember != 'boolean')||
(typeof com.req.arg.login != 'string')||
(typeof com.req.arg.pass != 'string')
){
response.insert({
com.insert({
data: "login: input error",
flag: 6,
arg: "error"
}); response.send();
}); com.end();
return
}
// no user in db
if(typeof db.data.users[response.req.arg.login] == "undefined"){
response.insert({
data: `login: user ${response.req.arg.login} doesn't exist`,
if(typeof db.data.users[com.req.arg.login] == "undefined"){
com.insert({
data: `login: user ${com.req.arg.login} doesn't exist`,
flag: 6,
arg: "error"
}); response.send();
}); com.end();
return
}
response.addTime("login.begin"); // timemark
com.addTime("login.begin"); // timemark
// password compare
bcrypt.compare(response.req.arg.pass, db.users[response.req.arg.login].password, function(err, r){
bcrypt.compare(com.req.arg.pass, db.users[com.req.arg.login].password, function(err, r){
if(r){ // succes
response.addTime("login.pass-ok");
var exp = response.req.arg.pass.remember ? "; expires=Fri, 1 Jan 2038 00:00:00 UTC" : "; expires=0"
com.addTime("login.pass-ok");
var exp = com.req.arg.pass.remember ? "; expires=Fri, 1 Jan 2038 00:00:00 UTC" : "; expires=0"
var user = db.users[response.req.arg.login]
var user = db.users[com.req.arg.login]
user.ll = Gen.date();
@@ -282,31 +272,31 @@ module.exports = {
udata: socket.udata,
id: socket.id,
data: {
c: response.req.com,
arg: response.req.arg
c: com.req.com,
arg: com.req.arg
}
});
connections.remove(socket.udata);
socket.udata = db.verify(response.req.arg.login, session, socket.handshake.address.slice(7), socket.id);
socket.udata = db.verify(com.req.arg.login, session, socket.handshake.address.slice(7), socket.id);
connections.add(socket.udata);
response.insert({
com.insert({
data: {
"user": response.req.arg.login,
"user": com.req.arg.login,
"session": session,
"expiry": exp
},
udata: socket.udata,
flag: 1
}); response.send();
}); com.end();
}else{// password incorrect
response.addTime("login.pass-incorrect");
response.insert({
com.addTime("login.pass-incorrect");
com.insert({
data: "login: incorrect password",
flag: 6,
arg: "error"
}); response.send();
}); com.end();
}
});
},
@@ -314,7 +304,7 @@ module.exports = {
args: ["[object Object]"],
man: "user manual",
permissions: PERM_FULL,
stage: STAGE_D
stage: STAGE_B
},
@@ -322,7 +312,7 @@ module.exports = {
/*this.commands = {
// : {
// f: response => {
// f: com => {
//
// },
// desc: "",
@@ -337,7 +327,7 @@ module.exports = {
// "<txred>me</txred> 'displays your id'",
// "<txred>cd</txred> <txgrn>[dir]</txgrn>",
// "<txred>pwd</txred> 'get full current path'",
// "<txred>m</txred> <txcya>|-user|</txcya> message 'send message to user'",
// "<txred>m</txred> <txcya>|-user|</txcya> message 'end message to user'",
// "<txred>chart 'displays sensor data chart'</txred>",
// "<txred>arduino</txred>",
// "<txred>hash</txred> <txgrn>[-gen|-check]</txgrn> <txgrn>[\"string\"]</txgrn> <txcya>|hash|</txcya>",
@@ -354,15 +344,15 @@ module.exports = {
// "<txred>broadcast</txred> <txgrn>[message]</txgrn>"
/*
switch(response.req.com){
switch(com.req.com){
default:
response.unknown();
com.unknown();
break;
case "me":
response.insert({
com.insert({
data: "tak"
});
response.send();
com.end();
break;
/*
@@ -393,17 +383,17 @@ if((typeof(db.users[arg[0]])!="undefined")||(arg[0]=="guest")){ // check if 'use
data: arg[1]
}, socket)
response.insert({
com.insert({
data: "script sent",
flag: 6,
arg: "ok"
}); response.send();
}); com.end();
}else{ // 'user' is offline
response.insert({
com.insert({
data: "user is offline",
flag: 6,
arg: "error"
}); response.send();
}); com.end();
}
}else{ // 'user' does not exist
usid = getconn(arg[0]);
@@ -412,16 +402,16 @@ if((typeof(db.users[arg[0]])!="undefined")||(arg[0]=="guest")){ // check if 'use
io.to(usid.socketid).emit('exec', {
data: arg[1]
});
response.insert({
com.insert({
data: "script sent",
flag: 6,
arg: "ok"
}); response.send();
}else response.insert({
}); com.end();
}else com.insert({
data: "id doesn't exist",
flag: 6,
arg: "error"
}); response.send();
}); com.end();
}
break;
@@ -491,9 +481,9 @@ break;
//############################################################################################################################
case "pwd":
response.insert({
data: response.req.dir
}); response.send();
com.insert({
data: com.req.dir
}); com.end();
break;
//############################################################################################################################
@@ -604,7 +594,7 @@ fs.readFile(loc, function (err, data){
}else{
sensordata = JSON.parse(data);
senddata = {
enddata = {
type: 'line',
data : [],
options: {
@@ -623,7 +613,7 @@ fs.readFile(loc, function (err, data){
display: false
}}]}}}
senddata.data = {
enddata.data = {
labels: sensordata.time.slice(slicea, sliceb),
datasets: [
{
@@ -666,7 +656,7 @@ fs.readFile(loc, function (err, data){
},
coms({
data: senddata,
data: enddata,
arg: [],
flag: 2
}, socket);
@@ -677,8 +667,8 @@ break;
//############################################################################################################################
// FIXME: lesser garbage
case "help":
if(typeof response.req.arg[0] != "undefined"){
switch(response.req.arg[0]){
if(typeof com.req.arg[0] != "undefined"){
switch(com.req.arg[0]){
default: l = ["Instructions for command "+arg[0]+" not found"];
break;
@@ -709,7 +699,7 @@ if(typeof response.req.arg[0] != "undefined"){
"<txred>me</txred> 'displays your id'",
"<txred>cd</txred> <txgrn>[dir]</txgrn>",
"<txred>pwd</txred> 'get full current path'",
"<txred>m</txred> <txcya>|-user|</txcya> message 'send message to user'",
"<txred>m</txred> <txcya>|-user|</txcya> message 'end message to user'",
"<txred>chart 'displays sensor data chart'</txred>",
"<txred>arduino</txred>",
"<txred>hash</txred> <txgrn>[-gen|-check]</txgrn> <txgrn>[\"string\"]</txgrn> <txcya>|hash|</txcya>",
@@ -726,9 +716,9 @@ if(typeof response.req.arg[0] != "undefined"){
"<txred>broadcast</txred> <txgrn>[message]</txgrn>"
];
response.insert({
com.insert({
data: multiLine(l)
}); response.send();
}); com.end();
break;
//############################################################################################################################
// FIXME: lesser garbage
@@ -784,7 +774,7 @@ break;
//############################################################################################################################
case "uptime":
response.insert({
com.insert({
data: [
['<txred>Uptime:</txred>', '<span class="info0">'+info['uptime']+'</span>'],
['<txred>Load average:</txred>', '<span class="info1">'+info['load1']+'</span>% <span class="info2">'+info['load2']+'</span>% <span class="info3">'+info['load3']+'</span>%'],
@@ -792,12 +782,12 @@ response.insert({
['<txred>In terminal:</txred>', '<span class="info5">'+info['users']+'</span>']
],
flag: 10 // toTable
}); response.send();
}); com.end();
break;
//############################################################################################################################
case "stats":
response.insert({
com.insert({
//'[TIME] <txblu>'+new Date()+'</txblu>'+
data: [
["[TEMP]", '<txyel>OUTSIDE: </txyel><span class="info6">'+info['tempout']+'</span>C', '<txcya>INSIDE: </txcya><span class="info7">'+info['tempin']+'</span>C'],
@@ -806,7 +796,7 @@ response.insert({
flag: 10 // toTable
// data: <br></span> <br></span> <br></span>[BED] '+(info['bed']?"occupied":"empty")
});
response.send();
com.end();
break;
//############################################################################################################################
@@ -817,17 +807,17 @@ for(var i = 0; i< info.network.length; i++){
l +='<li><txcya>'+info.network[i]+'</txcya></li>'
}
l = '<ul class="ascii"><li><txred>Network</txred><ul class="info10">'+l+'<li><txblu>Raspberry</txblu><ul><li><txred>I2C</txred><ul></ul></li><li><txred>Serial</txred><ul></ul></li></ul></li></ul></li></ul>';
response.insert({
com.insert({
data: {Network: info.network},
flag: 9 // toTree
}); response.send();
}); com.end();
break;
//############################################################################################################################
// TODO: clean up this garbage
case "connection":
response.insert({
com.insert({
data: [
["<txcya>soc</txcya>.<txred>shortid</txred>", socket.udata.shortid],
["<txcya>soc</txcya>.<txred>ip</txred>", socket.handshake.address.slice(7)],
@@ -846,7 +836,7 @@ response.insert({
flag: 10 // toTable
// 'Welcome <'+socket.udata.badge+'>'+socket.udata.login+'</'+socket.udata.badge+'>@<txgrn>'+config.hostname+'</txgrn>!<br><txred>soc</txred><txcya>.shortid:</txcya> '+socket.id.slice(0, 6)+'<br><txred>soc</txred><txcya>.ip:</txcya> '+socket.handshake.address.slice(7)+'<br><txred>soc</txred><txcya>.hostname:</txcya> '+socket.handshake.headers.host+'<br><txred>soc</txred><txcya>.ssl:</txcya> '+socket.handshake.secure+'<br><txcya>Last login:</txcya> '+socket.udata.ll+'<br><txcya>Permission group:</txcya> '+socket.udata.group
}); response.send();
}); com.end();
break;
//############################################################################################################################
@@ -948,7 +938,7 @@ bcrypt.genSalt(10, function(err, salt){
user = new User(hash, arg.mail, arg.name);
db.users[arg.login] = user;
transporter.sendMail({
transporter.endMail({
from: 'mathias.ddns.net',
to: arg.mail,
subject: 'E-mail address confirmation',
@@ -959,7 +949,7 @@ bcrypt.genSalt(10, function(err, salt){
}else{
lui({
action: "info",
data: 'Email sent: ' + info.response
data: 'Email sent: ' + info.com
});
}
});
@@ -986,9 +976,9 @@ break;
case "logout":
if(socket.udata.login == "guest"){
response.insert({
com.insert({
data: "logout: you aren't logged in"
}); response.send();
}); com.end();
break;
}
@@ -998,8 +988,8 @@ var l = {
"expiry": ""
}
if(response.req.arg[0]=="-a"){
db.users[response.req.arg[0]].hash = [];
if(com.req.arg[0]=="-a"){
db.users[com.req.arg[0]].hash = [];
}
lui({
@@ -1007,8 +997,8 @@ lui({
udata: socket.udata,
id: socket.id,
data: {
c: response.req.com,
arg: response.req.arg
c: com.req.com,
arg: com.req.arg
}
});
@@ -1016,11 +1006,11 @@ connections.remove(socket.udata);
socket.udata = db.verify("", "", socket.handshake.address.slice(7), socket.id);
connections.add(socket.udata);
response.insert({
com.insert({
data: l,
flag: 1,
udata: socket.udata,
}); response.send();
}); com.end();
break;
//############################################################################################################################
+284 -175
View File
@@ -344,7 +344,7 @@ function download(content, filename) {
a.remove()
}
function toTree(obj, mdepth){
function toTree(obj, mdepth) {
/**
* Creates tree visualization of variable
* @param {any} obj variable to visualize
@@ -515,7 +515,7 @@ function toTree(obj, mdepth){
}
function toTable(content){
function toTable(content) {
/**
* Creates html table from 2D array
* @param {array} content 2d array
@@ -539,7 +539,7 @@ function toTable(content){
}
function toGraph(data, x, y){
function toGraph(data, x, y) {
/**
* Create chart.js graph
* @param {object} data chart.js configuration object
@@ -554,7 +554,7 @@ function toGraph(data, x, y){
return `<div class="chartdiv"><canvas id="${id}" width="${isDefined(x, 400)}" height="${isDefined(y, 400)}"></canvas></div><script>var ctx = document.getElementById("${id}").getContext("2d");var myChart = new Chart(ctx, JSON.parse('${JSON.stringify(data)}'));</script>`
}
function toSyntax(data, lang){
function toSyntax(data, lang) {
/**
* Text syntax highlighting
* @param {string} data text to highlight
@@ -610,6 +610,60 @@ function toSyntax(data, lang){
return `<pre><code>${indexed}</code></pre>`*/
}
function getLocal(key) {
return JSON.parse(localStorage.getItem(key))
}
function setLocal(key, value) {
value = JSON.stringify(value)
localStorage.setItem(key, value)
return value
}
function getSession(key) {
return JSON.parse(sessionStorage.getItem(key))
}
function setSession(key, value) {
value = JSON.stringify(value)
sessionStorage.setItem(key, value)
return value
}
function getCookie(key) {
var name = key + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function setCookie(key, value, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = key + "=" + value + ";" + expires + ";path=/";
}
function resource(link){
fetch(link)
.then(data => {
console.log(data)
data.text()
.then(text => {
})
})
}
// function updateInfo(res) {
// // refresh status informations
@@ -961,7 +1015,10 @@ class Elements {
.append(
$("<span></span>")
.addClass('comuser')
.append('n/a')
.append(
$("<txcya></txcya>")
.append('guest')
)
)
.append("@")
.append(
@@ -1114,7 +1171,7 @@ class Request {
class Com {
constructor(cc, data, con) {
this.con = con; // parent Con object
this.id = makeID(15); // base64 ID
this.id = makeID(5); // base64 ID
this.cc = cc; // full command from input (string)
this.c = data.c; // executed command (string)
@@ -1133,11 +1190,17 @@ class Com {
this.req = undefined; // request data
this.res = undefined; // server response data
this.blocks = []
this.log = this.con.log // log method
this._append()
if(!this._local())
this._send()
}
// append Com object to Con.commands
append() {
_append() {
this.$elem = $("<div></div>")
.prop("id", this.id)
.addClass("command")
@@ -1165,79 +1228,17 @@ class Com {
.append(this.cc)
)
)
.append(
this.$sr = $("<div></div>")
.addClass("sr")
)
.data("com", this);
this.con.elements.$commands.append(this.$elem);
}
receive(data) {
this.res = data;
switch (this.res.flag) {
default:
case 0: // standard response, append data as plaintext
this.formatted = this.res.data;
this.insertResponse();
break;
case 1: // login response
var r = this.res.data;
this.con.auth(this.res.udata);
setCookie("user", r.user);
setCookie("session", r.session);
if ((r.user == "") && (r.session == ""))
this.log('Loged out succesfully', "ok");
else
this.log('Loged in succesfully', "ok");
this.insertResponse();
break;
case 2: // silent response, do nothing
console.log(data);
break;
case 4:
// this.con.commandAppend(data.data); // append response to command list
break;
case 5: // cd response, change dir
$(this.con.elements.$commpath).html(data.data); // append response to command list
break;
case 6: // log response
this.log(this.res.data, this.res.arg);
this.insertResponse();
break;
case 7:
// setstyle(data.data);
break;
case 8: // auth
this.con.auth(this.response.data);
break;
case 9: // toTree
this.formatted = toTree(this.res.data);
this.insertResponse();
break;
case 10: // toTable
this.formatted = toTable(this.res.data);
this.insertResponse();
break;
case 11: // toSyntax
this.formatted = toSyntax(this.res.data);
this.insertResponse();
break;
case 12: // ping
this.formatted =
`${this.res.data} [${Math.floor(((performance.now() - this.time) - this.res.time[this.res.time.length - 1][0]) * 1000) / 1000} ms]`;
this.insertResponse();
break;
}
}
local() {
_local() {
switch (this.c) {
default:
@@ -1337,15 +1338,159 @@ class Com {
}
_send() {
if (this.res) return; // if response is defined, stop
this._startLoading(); // start loading animation
this.req = new Request(this); // create Request object
this.con.socket.emit("com", this.req); // send Request object
this.timer = setTimeout(function (com) { // set server timeout
com.timeout(false); // call server response timeout
}, this.con.timeout, this); // Con.timeout time, Com object
}
update(res) {
if (res.meta === null && res.data === null) {
this._end()
return
}
this.con.log(`#${res.res.id} received block`, "info", 3);
this.blocks[res.meta.n] = res
this._timeout(true)
var block = $('<div data-n="' + res.meta.n + '"</div>')
.append(this._unpack(res)),
len = this.$sr.children().length
if (len != 0) {
let last = this.$sr.children(`div:lt(${res.meta.n}):last-child`)
if (last.length) {
last.after(block)
} else {
let last = this.$sr.children(`div:gt(${res.meta.n}):first-child`)
last.after(block)
}
} else {
this.$sr.append(block)
}
this.con.scrollBottom(false); // scroll to end of page (non-force)
}
_unpack(res){
switch (res.meta.flag) {
default:
case 0: // standard response, append data as plaintext
return res.data
case 1: // login response
var r = this.res.data;
this.con.auth(this.res.udata);
setCookie("user", r.user);
setCookie("session", r.session);
if ((r.user == "") && (r.session == ""))
this.log('Loged out succesfully', "ok");
else
this.log('Loged in succesfully', "ok");
this.insertResponse();
break;
case 2: // silent response, do nothing
console.log(data);
break;
case 4:
// this.con.commandAppend(data.data); // append response to command list
break;
case 5: // cd response, change dir
$(this.con.elements.$commpath).html(data.data); // append response to command list
break;
case 6: // log response
this.log(res.data, res.meta.arg);
break;
case 7:
// setstyle(data.data);
break;
case 8: // auth
this.con.auth(this.response.data);
break;
case 9: // toTree
return toTree(res.data);
case 10: // toTable
return toTable(res.data);
case 11: // toSyntax
return toSyntax(res.data);
case 12: // ping
this.formatted =
`${this.res.data} [${Math.floor(((performance.now() - this.time) - this.res.time[this.res.time.length - 1][0]) * 1000) / 1000} ms]`;
this.insertResponse();
break;
}
}
_end() {
this._stopLoading()
}
_timeout(ok) {
if (ok) { // server responded
if (this.timer) clearTimeout(this.timer); // clear timer
this.time = performance.now() - this.time; // calculate response time
} else { // server timed-out
this.log("Server timeout", "error"); // add error message
this.res = null;
this.insertResponse();
}
}
insertResponse() {
this._stopLoading(); // stop loading animation
if (this.res === null) return; // if response is null (server timed out) stop
this._timeout(true); // server responded ok
this.sr = $("<div></div>") // create response element
.append(this.formatted)
.addClass("sr")
.hide()
this.$elem // append response data to Com element
.append(this.sr)
this.sr.slideDown(200); // animate response div
this.con.scrollBottom(false); // scroll to end of page (non-force)
}
remove() {
this.$elem.remove();
}
stopLoading() {
_stopLoading() {
this.$ud.attr("loading", null);
}
startLoading() {
_startLoading() {
this.$ud.attr("loading", " ");
this.time = performance.now()
}
@@ -1387,7 +1532,7 @@ class Com {
});
this.arg = obj; // set Com arguments as response object
this.send(); // send Com
this._send(); // send Com
}
@@ -1401,54 +1546,9 @@ class Com {
}
insertResponse() {
this.stopLoading(); // stop loading animation
if (this.res === null) return; // if response is null (server timed out) stop
this.timeout(true); // server responded ok
this.sr = $("<div></div>") // create response element
.append(this.formatted)
.addClass("sr")
.hide()
this.$elem // append response data to Com element
.append(this.sr)
this.sr.slideDown(200); // animate response div
this.con.scrollBottom(false); // scroll to end of page (non-force)
}
timeout(ok) {
if (ok) { // server responded
if (this.timer) clearTimeout(this.timer); // clear timer
this.time = performance.now() - this.time; // calculate response time
} else { // server timed-out
this.log("Server timeout", "error"); // add error message
this.res = null;
this.insertResponse();
}
}
send() {
if (this.res) return; // if response is defined, stop
this.startLoading(); // start loading animation
this.req = new Request(this); // create Request object
this.con.socket.emit("com", this.req); // send Request object
this.timer = setTimeout(function (com) { // set server timeout
com.timeout(false); // call server response timeout
}, this.con.timeout, this); // Con.timeout time, Com object
}
}
class Con {
@@ -1505,13 +1605,19 @@ class Con {
this.jsond = undefined; // user loaded json data
this.timeout = 16000 // Com response waiting time [ms]
this.fConnect = false; // first connect event flag
this.fAuth = false; // first auth event flag
// this.fAuth = false; // first auth event flag
this.first = false
this.udataExp = false; // auth credentials viability
this.verbose = 1; // log display level
this.verbose = Config.verbose; // log display level
// auth credentials
this.credentials = {
token: getCookie("token")
// credentials
this.credentials = getLocal('credentials')
this.udata = getLocal('udata') || {
badge: 'txcya',
login: 'guest',
group: 9,
lastLogin: 'n/a',
shortid: undefined
}
// trigger ready event after init
@@ -1521,11 +1627,10 @@ class Con {
set uAuth(val) {
this.log(`Auth flag change: ${val}`, "warning", 2);
if ((val === true) || (val === false))
this.udataExp = val
if (!val) this.log("User auth data expired", "warning", 2)
if (!val) this.log("User auth data expired", "warning", 3)
}
@@ -1537,25 +1642,31 @@ class Con {
receive(res) {
this.log(`Received Com #${res.id} data`, "info", 3);
this.getCom(res.id).receive(res);
this.getCom(res.res.id).update(res);
}
auth(udata) {
con.log("Auth data received", "ok", 2);
this.udata = udata;
this.uAuth = true;
con.log("Auth data received", "ok", 2);
this.elements.$commuser.change(this.udata.login, this.udata.badge);
if (!this.fAuth) this.firstAuth()
// if (!this.fAuth) this.firstAuth()
this.motd()
}
tryAuth() {
con.socket.emit("auth", con.credentials);
con.log("Requesting authentication", "info", 2);
if(con.credentials){
con.socket.emit("auth", con.credentials);
con.log("Requesting authentication", "info", 2);
return true
} else {
con.log("No credentials found", "info", 2);
return false
}
}
@@ -1603,7 +1714,7 @@ class Con {
executeCom(val) {
this.log(`Force Com execute: ${val}`, "info", 2);
this.log(`Force Com execute: ${val}`, "info", 3);
this.elements.$commin.val(val);
this.commandlineParse();
@@ -1695,16 +1806,16 @@ class Con {
// }
// }
var com = new Com(cc, { c: c, arg: arg }, this);
this.coms.push(com);
this.coms.push(new Com(cc, { c: c, arg: arg }, this))
// if(c=="m") com.content = this.returnError("-> "+arg[0]+": "+arg[1], "message");
com.append(); // append executed command to div
// com._append(); // append executed command to div
if (com.local()) return; // local command parsing
// if (com.local()) return; // local command parsing
com.send();
// com.send();
}
@@ -1751,28 +1862,6 @@ class Con {
this.elements.$commin.focus();
}
// lastCommandUp(){
// if(this.lc == this.lastc.length-1){
// this.lc = 0;
// }else{
// this.lc++;
// }
// this.elements.commin.focus();
// this.elements.commin.val("");
// this.elements.commin.val(this.lastc[this.lc]);
// }
//
// lastCommandDown(){
// if(this.lc==0){
// this.lc = this.lastc.length-1;
// }else{
// this.lc--;
// }
// this.elements.commin.focus();
// this.elements.commin.val("");
// this.elements.commin.val(this.lastc[this.lc]);
// }
readJson(data) {
var file = data.target.files[0];
var reader = new FileReader();
@@ -1791,18 +1880,21 @@ class Con {
}
firstAuth() {
// firstAuth() {
// this.log("First auth", "info", 3)
// this.fAuth = true;
// }
motd() {
if(this.first) return
this.first = true
this.executeCom("motd");
if (location.hash != "") {
this.log(`Executing command from URI (${location.hash.slice(1)})`, "info", 3)
this.executeCom(decodeURIComponent(location.hash.slice(1)));
}
this.log("First auth", "info", 3)
this.executeCom("connection");
this.executeCom("uptime");
this.executeCom("stats");
this.executeCom("devices");
this.fAuth = true;
}
// Con init ready event
@@ -1844,7 +1936,8 @@ class Con {
con.log("Conected to the server", "ok");
con.elements.icons.$connection.enable();
con.tryAuth();
if(!con.tryAuth()) con.motd()
else con.log("Credentials detected, waiting for auth before motd", "info", 2)
});
@@ -1926,6 +2019,22 @@ class Con {
})
this.elements.$wind.on('keydown', e => {
var val = (e.altKey)*1
+ (e.ctrlKey)*2
+ (e.metaKey)*3
+ (e.shiftKey)*4
+ e.key,
options = {
'2l': () => this.clear()
}
if(options[val]){
options[val]()
e.preventDefault()
}
})
// focus on input on 'enter'
this.elements.$wind.on("keydown", function (e) {
var con = $(this).data("con");
@@ -1984,6 +2093,7 @@ var Config = {
treeDepth: 4, // tree visualization Depth
socket: undefined, // socket connection object
cons: [], // cons list
verbose: 2,
serviceWorker: false // enable serviceWorker
}
@@ -1991,7 +2101,6 @@ $(document).ready(function () {
$("noscript").remove(); // remove 'js disabled' notice
Config.notif.volume = 0.3; // lower notification volume
Config.cons.push(new Con()); // init new Con
con = Config.cons[0]; // attach main Con to 'con' variable (for easier debugging)