serverpreconfigured 2.2.14 → 2.2.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ import { Request } from 'express';
2
+ export declare const BASE_LOG_PATH = "./logs";
3
+ export declare enum LogSeverity {
4
+ danger = "danger",
5
+ servere = "severe",
6
+ moderate = "moderate",
7
+ info = "info"
8
+ }
9
+ export interface SaveLogOptions {
10
+ userId?: number;
11
+ data: string;
12
+ severity: LogSeverity;
13
+ addPath?: string;
14
+ filePrefix?: string;
15
+ penTestSuspcion?: boolean;
16
+ req?: Request;
17
+ ip?: string;
18
+ url?: string;
19
+ }
20
+ export declare function stringfyError(err: any): string;
21
+ export declare function getIpFromRequest(req: Request): string;
22
+ export declare function saveInternalErrorLog(req: Request, error: any, options?: {
23
+ penTestSuspcion?: boolean;
24
+ severity?: LogSeverity;
25
+ }): Promise<void>;
26
+ export declare function saveLog(options: SaveLogOptions): {
27
+ fileName: string;
28
+ basePath: string;
29
+ };
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.saveLog = exports.saveInternalErrorLog = exports.getIpFromRequest = exports.stringfyError = exports.LogSeverity = exports.BASE_LOG_PATH = void 0;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const path_1 = __importDefault(require("path"));
18
+ exports.BASE_LOG_PATH = './logs';
19
+ var LogSeverity;
20
+ (function (LogSeverity) {
21
+ LogSeverity["danger"] = "danger";
22
+ LogSeverity["servere"] = "severe";
23
+ LogSeverity["moderate"] = "moderate";
24
+ LogSeverity["info"] = "info";
25
+ })(LogSeverity = exports.LogSeverity || (exports.LogSeverity = {}));
26
+ function stringfyError(err) {
27
+ const type = typeof (err);
28
+ if (type !== 'object')
29
+ return err.toString();
30
+ let ret = stringfyObject(err, 0);
31
+ return ret || "";
32
+ function stringfyObject(obj, level = 0) {
33
+ if (!obj)
34
+ return "";
35
+ if (typeof (obj) !== 'object')
36
+ return obj.toString();
37
+ if (level == 5)
38
+ return "Is Object level max 8";
39
+ let ret = {};
40
+ for (let key of Object.keys(obj)) {
41
+ let value = obj[key];
42
+ //@ts-ignore
43
+ ret[key] = typeof (value) == 'object' ? stringfyObject(value, level + 1).replaceAll('\\', '') : value === null || value === void 0 ? void 0 : value.toString();
44
+ }
45
+ return JSON.stringify(ret);
46
+ }
47
+ }
48
+ exports.stringfyError = stringfyError;
49
+ function getIpFromRequest(req) {
50
+ //@
51
+ let ips = (req.headers['cf-connecting-ip'] ||
52
+ req.headers['x-real-ip'] ||
53
+ req.headers['x-forwarded-for'] ||
54
+ req.ip || '');
55
+ if (typeof (ips) == 'string') {
56
+ ips = ips.split(',');
57
+ }
58
+ return ips[0].trim();
59
+ }
60
+ exports.getIpFromRequest = getIpFromRequest;
61
+ function saveInternalErrorLog(req, error, options) {
62
+ var _a;
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ try {
65
+ const ip = getIpFromRequest(req);
66
+ const url = req.originalUrl;
67
+ //@ts-ignore
68
+ const userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a.id;
69
+ let errorString = stringfyError(error);
70
+ saveLog({
71
+ ip: ip,
72
+ url: url,
73
+ userId: userId,
74
+ data: errorString,
75
+ severity: (options === null || options === void 0 ? void 0 : options.severity) || LogSeverity.info,
76
+ penTestSuspcion: options === null || options === void 0 ? void 0 : options.penTestSuspcion,
77
+ });
78
+ }
79
+ catch (e) {
80
+ console.log("Error ON Save Log", e);
81
+ }
82
+ });
83
+ }
84
+ exports.saveInternalErrorLog = saveInternalErrorLog;
85
+ function saveLog(options) {
86
+ if (!fs_1.default.existsSync(exports.BASE_LOG_PATH)) {
87
+ fs_1.default.mkdirSync(exports.BASE_LOG_PATH);
88
+ }
89
+ let basePath = exports.BASE_LOG_PATH;
90
+ if (options.addPath) {
91
+ basePath = path_1.default.join(basePath, options.addPath);
92
+ if (!fs_1.default.existsSync(basePath)) {
93
+ fs_1.default.mkdirSync(basePath);
94
+ }
95
+ }
96
+ if (options.userId) {
97
+ basePath = path_1.default.join(basePath, options.userId.toString());
98
+ }
99
+ else {
100
+ basePath = path_1.default.join(basePath, "unlogged");
101
+ }
102
+ if (!fs_1.default.existsSync(basePath)) {
103
+ fs_1.default.mkdirSync(basePath);
104
+ }
105
+ let fileName = path_1.default.join(basePath, `${options.filePrefix ? options.filePrefix + '_' : ""}${getDateString(new Date())}.csv`);
106
+ let data = "";
107
+ if (fs_1.default.existsSync(fileName)) {
108
+ data = fs_1.default.readFileSync(fileName).toString() + "\n";
109
+ }
110
+ if (!data) {
111
+ data = 'Data;Severidade;Usuário;Dados;IP;URL;Supeita de Ataque\n';
112
+ }
113
+ data += `${new Date()};${options.severity};${options.userId || "Deslogado"};${options.data};${options.ip || "Não Informado"};${options.url || "Não Informado"};${options.penTestSuspcion ? "SIM" : "NÃO"}`;
114
+ fs_1.default.writeFileSync(fileName, data);
115
+ return {
116
+ fileName,
117
+ basePath,
118
+ };
119
+ }
120
+ exports.saveLog = saveLog;
121
+ function getDateString(d) {
122
+ const year = d.getFullYear();
123
+ const month = zerof(d.getMonth() + 1);
124
+ const day = zerof(d.getDate());
125
+ const hour = zerof(d.getHours());
126
+ return `${year}_${month}_${day}_${hour}`;
127
+ function zerof(n) {
128
+ if (n > 9)
129
+ return n.toString();
130
+ return `0${n}`;
131
+ }
132
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serverpreconfigured",
3
- "version": "2.2.14",
3
+ "version": "2.2.16",
4
4
  "description": "\"Pre-configured server with authentication system and database integration\"",
5
5
  "main": "dist/server.js",
6
6
  "keywords": [
@@ -0,0 +1,127 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { Request } from 'express';
4
+ import axios from 'axios';
5
+ export const BASE_LOG_PATH='./logs';
6
+ export enum LogSeverity{
7
+ danger='danger',
8
+ servere='severe',
9
+ moderate='moderate',
10
+ info='info',
11
+ }
12
+ export interface SaveLogOptions{
13
+ userId?:number;
14
+ data:string;
15
+ severity:LogSeverity;
16
+ addPath?:string;
17
+ filePrefix?:string;
18
+ penTestSuspcion?:boolean;
19
+ req?:Request;
20
+ ip?:string;
21
+ url?:string;
22
+ }
23
+
24
+
25
+ export function stringfyError(err:any):string{
26
+ const type=typeof(err);
27
+ if(type!=='object')
28
+ return err.toString();
29
+ let ret=stringfyObject(err,0);
30
+ return ret||"";
31
+ function stringfyObject(obj:any,level:number=0){
32
+ if(!obj)
33
+ return "";
34
+ if(typeof(obj)!=='object')
35
+ return obj.toString();
36
+ if(level==5)
37
+ return "Is Object level max 8";
38
+ let ret:any={};
39
+ for(let key of Object.keys(obj)){
40
+ let value=obj[key];
41
+ //@ts-ignore
42
+ ret[key]=typeof(value)=='object'?stringfyObject(value,level+1).replaceAll('\\',''):value?.toString();
43
+ }
44
+ return JSON.stringify(ret);
45
+ }
46
+
47
+ }
48
+
49
+
50
+ export function getIpFromRequest(req:Request){
51
+ //@
52
+ let ips = (
53
+ req.headers['cf-connecting-ip'] ||
54
+ req.headers['x-real-ip'] ||
55
+ req.headers['x-forwarded-for'] ||
56
+ req.ip || ''
57
+ );
58
+ if(typeof(ips)=='string'){
59
+ ips=ips.split(',');
60
+ }
61
+ return ips[0].trim();
62
+ }
63
+ export async function saveInternalErrorLog(req:Request,error:any,options?:{penTestSuspcion?:boolean,severity?:LogSeverity}){
64
+ try{
65
+ const ip=getIpFromRequest(req);
66
+ const url=req.originalUrl;
67
+ //@ts-ignore
68
+ const userId=req.user?.id;
69
+ let errorString=stringfyError(error);
70
+ saveLog({
71
+ ip:ip,
72
+ url:url,
73
+ userId:userId,
74
+ data:errorString,
75
+ severity:options?.severity||LogSeverity.info,
76
+ penTestSuspcion:options?.penTestSuspcion,
77
+ });
78
+ }catch(e){
79
+ console.log("Error ON Save Log",e);
80
+ }
81
+ }
82
+ export function saveLog(options:SaveLogOptions){
83
+ if(!fs.existsSync(BASE_LOG_PATH)){
84
+ fs.mkdirSync(BASE_LOG_PATH);
85
+ }
86
+ let basePath=BASE_LOG_PATH;
87
+ if(options.addPath){
88
+ basePath=path.join(basePath,options.addPath);
89
+ if(!fs.existsSync(basePath)){
90
+ fs.mkdirSync(basePath);
91
+ }
92
+ }
93
+ if(options.userId){
94
+ basePath=path.join(basePath,options.userId.toString());
95
+ }else{
96
+ basePath=path.join(basePath,"unlogged");
97
+ }
98
+ if(!fs.existsSync(basePath)){
99
+ fs.mkdirSync(basePath);
100
+ }
101
+ let fileName=path.join(basePath,`${options.filePrefix?options.filePrefix+'_':""}${getDateString(new Date())}.csv`);
102
+ let data="";
103
+ if(fs.existsSync(fileName)){
104
+ data=fs.readFileSync(fileName).toString()+"\n";
105
+ }
106
+ if(!data){
107
+ data='Data;Severidade;Usuário;Dados;IP;URL;Supeita de Ataque\n';
108
+ }
109
+ data+=`${new Date()};${options.severity};${options.userId||"Deslogado"};${options.data};${options.ip||"Não Informado"};${options.url||"Não Informado"};${options.penTestSuspcion?"SIM":"NÃO"}`;
110
+ fs.writeFileSync(fileName,data);
111
+ return {
112
+ fileName,
113
+ basePath,
114
+ };
115
+ }
116
+ function getDateString(d:Date){
117
+ const year=d.getFullYear();
118
+ const month=zerof(d.getMonth()+1);
119
+ const day=zerof(d.getDate());
120
+ const hour=zerof(d.getHours());
121
+ return `${year}_${month}_${day}_${hour}`;
122
+ function zerof(n:number){
123
+ if(n>9)
124
+ return n.toString();
125
+ return `0${n}`;
126
+ }
127
+ }
@@ -1,2 +0,0 @@
1
- declare const router: import("express-serve-static-core").Router;
2
- export default router;
@@ -1,56 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const express_1 = __importDefault(require("express"));
16
- const secureset_1 = require("../sessions/secureset");
17
- const config_1 = require("../auth/config");
18
- const response_1 = require("../utils/response");
19
- const auth_1 = require("../auth/auth");
20
- const meta_sanitizer_1 = __importDefault(require("meta-sanitizer"));
21
- const users_1 = require("../users/users");
22
- var LoginErrorCode;
23
- (function (LoginErrorCode) {
24
- LoginErrorCode[LoginErrorCode["NoError"] = 0] = "NoError";
25
- LoginErrorCode[LoginErrorCode["InvalidParams"] = 1] = "InvalidParams";
26
- LoginErrorCode[LoginErrorCode["InvalidPassword"] = 2] = "InvalidPassword";
27
- })(LoginErrorCode || (LoginErrorCode = {}));
28
- const router = express_1.default.Router();
29
- router.post('/logout', (req, res) => {
30
- let is_ok = false;
31
- if (auth_1.userIsLogged(req)) {
32
- secureset_1.deleteSessionValue(req, config_1.SESSION_LOGGED_DATA);
33
- is_ok = true;
34
- }
35
- res.send(response_1.JSONResponse(is_ok, 0, is_ok ? "" : "User Must be logged", {}));
36
- });
37
- router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
38
- let email = "";
39
- let password = "";
40
- try {
41
- email = meta_sanitizer_1.default.sanitizeEmail(req.body.email);
42
- password = meta_sanitizer_1.default.queryProtector(req.body.password);
43
- }
44
- catch (e) {
45
- return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
46
- }
47
- if (password == "" || email == "")
48
- return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidParams, "Must have 'email' and 'password' params"));
49
- const checkPass = yield users_1.checkUserPassword(email, password);
50
- if (checkPass) {
51
- secureset_1.setSessionValue(req, config_1.SESSION_LOGGED_DATA, email);
52
- return res.send(response_1.JSONResponse(true, LoginErrorCode.NoError, "Login Ok"));
53
- }
54
- return res.send(response_1.JSONResponse(false, LoginErrorCode.InvalidPassword, "Invalid Password"));
55
- }));
56
- exports.default = router;
@@ -1,2 +0,0 @@
1
- declare const router: import("express-serve-static-core").Router;
2
- export default router;
@@ -1,90 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const express_1 = __importDefault(require("express"));
16
- const response_1 = require("../utils/response");
17
- const auth_1 = require("../auth/auth");
18
- const meta_sanitizer_1 = __importDefault(require("meta-sanitizer"));
19
- const users_1 = require("../users/users");
20
- const users_2 = require("../users/users");
21
- const auth_2 = require("../middlewares/auth");
22
- const auth_3 = require("../auth/auth");
23
- const auth_4 = require("../auth/auth");
24
- const server_1 = require("../server");
25
- const email_1 = require("../utils/validators/email");
26
- const router = express_1.default.Router();
27
- router.post('/logout', (req, res) => {
28
- let is_ok = false;
29
- if ((0, auth_1.userIsLogged)(req)) {
30
- (0, auth_4.logoutUser)(req);
31
- is_ok = true;
32
- }
33
- res.send((0, response_1.JSONResponse)("OK"));
34
- });
35
- router.post('/login', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
36
- let email = "";
37
- let password = "";
38
- try {
39
- email = meta_sanitizer_1.default.sanitizeEmail(req.body.email);
40
- password = meta_sanitizer_1.default.queryProtector(req.body.password);
41
- }
42
- catch (e) {
43
- return res.status(403).send((0, response_1.JSONResponse)({}, "Must have 'email' and 'password' params"));
44
- }
45
- if (password == "" || email == "")
46
- return res.status(403).send((0, response_1.JSONResponse)({}, "Must have 'email' and 'password' params"));
47
- email = email.toLocaleLowerCase();
48
- try {
49
- const checkPass = yield (0, users_1.checkUserPassword)(email, password);
50
- if (checkPass) {
51
- const user = yield server_1.User.findOne({ where: { email: email } });
52
- if (!user)
53
- throw "Dont find User";
54
- if (!user.is_active) {
55
- return res.status(403).send((0, response_1.JSONResponse)({}, "User deleted"));
56
- }
57
- (0, auth_3.setUserLogged)(req, email);
58
- yield (0, users_1.updateUserLastAction)(user);
59
- return res.status(200).send((0, response_1.JSONResponse)("Login Ok"));
60
- }
61
- return res.status(403).send((0, response_1.JSONResponse)({}, "Invalid Password"));
62
- }
63
- catch (e) {
64
- return (0, response_1.sendIError)(req, res, e);
65
- }
66
- }));
67
- router.post('/register', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
68
- try {
69
- let email = meta_sanitizer_1.default.sanitizeEmail(req.body.email || '');
70
- let password = meta_sanitizer_1.default.queryProtector(req.body.password || '');
71
- let name = meta_sanitizer_1.default.SanitizerEngine(req.body.name || '', true, false, [' ']).sanitizedData;
72
- if (email == "" || password == "" || name == "")
73
- return res.send((0, response_1.JSONResponse)({}, "Invalid params"));
74
- email = email.toLocaleLowerCase();
75
- if (!(0, email_1.checkEmail)(email)) {
76
- return res.status(403).send((0, response_1.JSONResponse)({}, "Invalid Email"));
77
- }
78
- yield (0, users_2.createUser)({ first_name: name, email: email, password_string: password });
79
- return res.send((0, response_1.JSONResponse)("REGISTER OK"));
80
- }
81
- catch (e) {
82
- if (e === "User exist")
83
- return res.send((0, response_1.JSONResponse)({}, "User Exist"));
84
- return (0, response_1.sendIError)(req, res, e);
85
- }
86
- }));
87
- router.post('/getuser', auth_2.setUserDataMiddleware, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
88
- res.send((0, response_1.JSONResponse)({}, { email: req.user.email, id: req.user.id }));
89
- }));
90
- exports.default = router;