melperjs 1.0.0

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.
package/LISENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Mahmuthan Elbir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,109 @@
1
+ # MELPERJS
2
+
3
+ Nodejs module to use predefined common functions and utilities
4
+
5
+ ## Installation
6
+
7
+ To install use npm:
8
+
9
+ ```bash
10
+ npm i melperjs
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```javascript
16
+ const helper = require("melperjs");
17
+
18
+
19
+ (async () => {
20
+ console.log("ENDSWITH TH", helper._.endsWith("ENDSWITH", "TH"));
21
+ console.log(helper.exception("something went wrong"));
22
+ console.log(helper.time());
23
+ await helper.sleepMs(1000);
24
+ console.log(helper.time());
25
+ await helper.sleep(1);
26
+ console.log(helper.time());
27
+ try {
28
+ await helper.promiseTimeout(1000, helper.sleepMs(2000));
29
+ } catch (e) {
30
+ console.error(e.message);
31
+ }
32
+ console.log(helper.findKeyNode("c", {
33
+ a: {
34
+ b: {
35
+ x: 1,
36
+ y: 2,
37
+ c: {
38
+ d: true
39
+ }
40
+ }
41
+ }
42
+ }));
43
+ console.log("1 empty", helper.isEmpty(1));
44
+ console.log("[] empty", helper.isEmpty([]));
45
+ console.log(helper.limitString("LONG TEXT", 7));
46
+ console.log(helper.safeString("<strong>SAFE TEXT</strong>"));
47
+ console.log(helper.randomWeighted({strongProbability: 1000, lowProbability: 1}));
48
+ console.log(helper.tokenHex(8));
49
+ console.log(helper.md5("data"));
50
+ const password = helper.hashBcrypt("plain");
51
+ console.log(password)
52
+ console.log("passwordHash", helper.verifyBcrypt("plain", password));
53
+ const cookies = helper.cookieDict(await axios.get("https://google.com"));
54
+ console.log(cookies);
55
+ console.log(helper.cookieHeader(cookies));
56
+ const proxy = helper.formatProxy("127.0.0.1:8080:id:pw-{SESSION}");
57
+ console.log(proxy);
58
+ console.log(helper.proxyObject(proxy));
59
+ console.log(await helper.proxify({mode: 4, proxy}));
60
+ console.log(helper.serverIP());
61
+ console.log("HTTP CODE: 401 FOREIGN", helper.foreignError(401));
62
+ console.log("HTTP CODE: 0 FOREIGN", helper.foreignError(0));
63
+ helper.createNumDir("test");
64
+ helper.createDir("test");
65
+ console.log("VERSIONED BY .GIT", "v" + helper.getVersion());
66
+ })();
67
+
68
+ /*
69
+ ENDSWITH TH true
70
+ { message: 'something went wrong', response: { status: 400 } }
71
+ 1697381865
72
+ 1697381866
73
+ 1697381867
74
+ Promise timed out after 1000ms
75
+ { x: 1, y: 2, c: { d: true } }
76
+ 1 empty false
77
+ [] empty true
78
+ LONG...
79
+ SAFE TEXT
80
+ strongProbability
81
+ 16638f79
82
+ 8d777f385d3dfec8815d20f7496026dc
83
+ $2b$10$TYGF7Pe8YkdZY.w8f4cUneUYDYvzKCEaXohUzCfz.JStoatMKa0Im
84
+ passwordHash true
85
+ {
86
+ '1P_JAR': '2023-10-15-14',
87
+ AEC: 'Ackid1QW89FoW9j6RUUZDe9RpJGJN9Flq0Qs0nnbt7AUHJBuDcf3FKulcg',
88
+ NID: '511=RtEjqdKHa6MQ3Qaxr1Jh-8ktRCWPmSkV7iuo0P1MsLdhyuOyN7u1gXTAL8ojUO85rmcjUpfoul5Ucx7cBUzoLZzs5HpAnF5exxGiPvSUQeQHWADHgio7hmIl62kjHMKWJmmYtRcRFsKI9sgMUPr1MhX4Me181cqtNUgi8OLtCzY'
89
+ }
90
+ 1P_JAR=2023-10-15-14;AEC=Ackid1QW89FoW9j6RUUZDe9RpJGJN9Flq0Qs0nnbt7AUHJBuDcf3FKulcg;NID=511=RtEjqdKHa6MQ3Qaxr1Jh-8ktRCWPmSkV7iuo0P1MsLdhyuOyN7u1gXTAL8ojUO85rmcjUpfoul5Ucx7cBUzoLZzs5HpAnF5exxGiPvSUQeQHWADHgio7hmIl62kjHMKWJmmYtRcRFsKI9sgMUPr1MhX4Me181cqtNUgi8OLtCzY
91
+ http://id:pw-{SESSION}@127.0.0.1:8080
92
+ {
93
+ protocol: 'http',
94
+ host: '127.0.0.1',
95
+ port: 8080,
96
+ auth: { username: 'id', password: 'pw-{SESSION}' }
97
+ }
98
+ http://id:pw-1708fa06@127.0.0.1:8080
99
+ 192.168.1.2
100
+ HTTP CODE: 401 FOREIGN false
101
+ HTTP CODE: 0 FOREIGN true
102
+ fatal: not a git repository (or any of the parent directories): .git
103
+ VERSIONED BY .GIT v2310.151313
104
+ */
105
+ ```
106
+
107
+ ## License
108
+
109
+ The MIT License (MIT). Please see [License File](LISENCE) for more information.
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "melperjs",
3
+ "version": "1.0.0",
4
+ "description": "Nodejs module to use predefined common functions and utilities",
5
+ "main": "src/index.js",
6
+ "scripts": {
7
+ "test": "node test/script.js"
8
+ },
9
+ "keywords": [
10
+ "helper",
11
+ "mixins",
12
+ "lodash",
13
+ "common functions",
14
+ "javascript helper"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/mahelbir/melperjs.git"
19
+ },
20
+ "author": "Mahmuthan Elbir",
21
+ "license": "MIT",
22
+ "dependencies": {
23
+ "axios": "^1.5.1",
24
+ "bcrypt": "^5.1.1",
25
+ "hpagent": "^1.2.0",
26
+ "lodash": "^4.17.21",
27
+ "set-cookie-parser": "^2.6.0",
28
+ "xss": "^1.0.14"
29
+ }
30
+ }
package/src/index.js ADDED
@@ -0,0 +1,323 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const {networkInterfaces} = require('os');
5
+ const {execSync} = require('child_process');
6
+
7
+ const _ = require('lodash');
8
+ const xss = require('xss');
9
+ const axios = require('axios');
10
+ const bcrypt = require('bcrypt');
11
+ const setCookieParser = require('set-cookie-parser');
12
+ const {HttpsProxyAgent} = require('hpagent');
13
+
14
+
15
+ function exception(message, response = {}) {
16
+ response.status = response.status || 400;
17
+ return {
18
+ message: message,
19
+ response: response
20
+ }
21
+ }
22
+
23
+ function time() {
24
+ return Math.floor(Date.now() / 1000);
25
+ }
26
+
27
+ async function sleepMs(milliseconds) {
28
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
29
+ }
30
+
31
+ async function sleep(seconds) {
32
+ return await sleepMs(seconds * 1000);
33
+ }
34
+
35
+ function promiseTimeout(milliseconds, promise) {
36
+ return new Promise((resolve, reject) => {
37
+ const timer = setTimeout(() => {
38
+ reject(new Error('Promise timed out after ' + milliseconds + 'ms'));
39
+ }, milliseconds);
40
+
41
+ promise
42
+ .then(value => {
43
+ clearTimeout(timer);
44
+ resolve(value);
45
+ })
46
+ .catch(reason => {
47
+ clearTimeout(timer);
48
+ reject(reason);
49
+ });
50
+ });
51
+ }
52
+
53
+ function findKeyNode(key, node, pair = null) {
54
+ if (node && node.hasOwnProperty(key) && (pair ? node[key] === pair : true)) {
55
+ return node;
56
+ } else if (typeof node === 'object') {
57
+ for (let index in node) {
58
+ const result = findKeyNode(key, node[index], pair);
59
+ if (result) {
60
+ return result;
61
+ }
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+
67
+ function isEmpty(value) {
68
+ if (typeof value === "number") {
69
+ return value === 0;
70
+ } else {
71
+ return _.isEmpty(value);
72
+ }
73
+ }
74
+
75
+ function limitString(str, limit = 35) {
76
+ str = str || "";
77
+ if (str.length <= limit) {
78
+ return str;
79
+ } else {
80
+ return str.substring(0, limit - 3) + "...";
81
+ }
82
+ }
83
+
84
+ function safeString(source) {
85
+ return xss(source, {
86
+ whiteList: {},
87
+ stripIgnoreTag: true,
88
+ stripIgnoreTagBody: ["script"]
89
+ });
90
+ }
91
+
92
+ function randomWeighted(dict) {
93
+ let elements = Object.keys(dict);
94
+ let weights = Object.values(dict);
95
+
96
+ let totalWeight = 0;
97
+ for (let weight of weights) {
98
+ totalWeight += weight;
99
+ }
100
+
101
+ let randomNum = Math.random() * totalWeight;
102
+ let weightSum = 0;
103
+
104
+ for (let i = 0; i < elements.length; i++) {
105
+ weightSum += weights[i];
106
+ if (randomNum <= weightSum) {
107
+ return elements[i];
108
+ }
109
+ }
110
+ }
111
+
112
+ function tokenHex(length) {
113
+ return crypto.randomBytes(Math.ceil(length / 2))
114
+ .toString('hex')
115
+ .slice(0, length);
116
+ }
117
+
118
+ function md5(data) {
119
+ return crypto.createHash('md5').update(data).digest("hex");
120
+ }
121
+
122
+ function hashBcrypt(plainText) {
123
+ return bcrypt.hashSync(plainText, bcrypt.genSaltSync(10));
124
+ }
125
+
126
+ function verifyBcrypt(plainText, hash) {
127
+ return bcrypt.compareSync(plainText, hash);
128
+ }
129
+
130
+ function cookieDict(res, decodeValues = false) {
131
+ let dict = {};
132
+ const cookies = setCookieParser.parse(res, {decodeValues: decodeValues});
133
+ for (let cookie of cookies) {
134
+ dict[cookie.name] = cookie.value;
135
+ }
136
+ return dict;
137
+ }
138
+
139
+ function cookieHeader(cookieDict) {
140
+ return Object.entries(cookieDict)
141
+ .map(([key, value]) => `${key}=${value}`)
142
+ .join(';')
143
+ }
144
+
145
+ function formatProxy(proxy, protocol = "http") {
146
+ proxy = proxy.trim();
147
+ const splitByProtocol = proxy.split("://");
148
+ if (1 < splitByProtocol.length)
149
+ protocol = splitByProtocol[0];
150
+ proxy = splitByProtocol[splitByProtocol.length - 1];
151
+ if (!proxy.includes("@")) {
152
+ const proxyParts = proxy.split(":");
153
+ if (4 <= proxyParts.length) {
154
+ proxy = `${proxyParts[proxyParts.length - 2]}:${proxyParts[proxyParts.length - 1]}@`;
155
+ proxyParts.pop();
156
+ proxyParts.pop();
157
+ proxy += proxyParts.join(":");
158
+ }
159
+ }
160
+ const proxyParts = proxy.split(':');
161
+ const proxyEnd = parseInt(proxyParts[proxyParts.length - 1]);
162
+ const proxyStart = proxyParts[proxyParts.length - 2];
163
+ if (!proxyStart.includes(".")) {
164
+ proxyParts.pop();
165
+ proxyParts[proxyParts.length - 1] = crypto.randomInt(parseInt(proxyStart), proxyEnd + 1).toString();
166
+ }
167
+ return protocol + "://" + proxyParts.join(':');
168
+ }
169
+
170
+ function proxyObject(...args) {
171
+ let proxy = formatProxy(...args);
172
+ const splitByProtocol = proxy.split('://');
173
+ const splitById = splitByProtocol[splitByProtocol.length - 1].split('@');
174
+ const splitByConn = splitById[splitById.length - 1].split(':');
175
+ proxy = {
176
+ protocol: splitByProtocol[0],
177
+ host: splitByConn[0],
178
+ port: parseInt(splitByConn[1]),
179
+ };
180
+ if (1 < splitById.length) {
181
+ const splitByAuth = splitById[0].split(':');
182
+ proxy.auth = {
183
+ username: splitByAuth[0],
184
+ password: splitByAuth[1]
185
+ };
186
+ }
187
+ return proxy;
188
+ }
189
+
190
+ async function proxify(proxyConfig, callback = formatProxy) {
191
+ proxyConfig = proxyConfig || {};
192
+ const timeout = 7000;
193
+ if (proxyConfig.mode === 1) {
194
+ return callback(proxyConfig.proxy);
195
+ } else if (proxyConfig.mode === 2) {
196
+ const proxy = callback(proxyConfig.proxy);
197
+ try {
198
+ await axios.get(proxyConfig.resetApi, {timeout});
199
+ } catch {
200
+ return false;
201
+ }
202
+ await sleep(5);
203
+ for (let i = 0; i < 5; i++) {
204
+ try {
205
+ const res = await axios.get("https://api64.ipify.org", {
206
+ timeout,
207
+ httpsAgent: new HttpsProxyAgent({proxy, timeout: 7000})
208
+ });
209
+ if (res.status === 200)
210
+ return proxy;
211
+ } catch {
212
+ await sleep(3);
213
+ }
214
+ }
215
+ } else if (proxyConfig.mode === 3) {
216
+ try {
217
+ const res = await axios.get(proxyConfig.resetApi, {timeout});
218
+ if (res.status === 200)
219
+ return callback(proxyConfig.proxy);
220
+ } catch {
221
+ return false;
222
+ }
223
+ } else if (proxyConfig.mode === 4) {
224
+ return callback(proxyConfig.proxy).replace("{SESSION}", tokenHex(8));
225
+ } else if (proxyConfig.mode === 5) {
226
+ try {
227
+ const lines = proxyConfig.proxy.split("\n");
228
+ const line = lines[crypto.randomInt(0, lines.length)];
229
+ return callback(line);
230
+ } catch {
231
+ return false;
232
+ }
233
+ }
234
+
235
+ return null;
236
+ }
237
+
238
+ function serverIP() {
239
+ const interfaces = networkInterfaces();
240
+ for (const devName in interfaces) {
241
+ const interfaceValue = interfaces[devName];
242
+ for (let i = 0; i < interfaceValue.length; i++) {
243
+ const alias = interfaceValue[i];
244
+ if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
245
+ return alias.address;
246
+ }
247
+ }
248
+ return '127.0.0.1';
249
+ }
250
+
251
+ function foreignError(httpCode) {
252
+ return (
253
+ httpCode === undefined ||
254
+ httpCode === null ||
255
+ httpCode === 0 ||
256
+ httpCode === 402 ||
257
+ httpCode === 407 ||
258
+ httpCode === 466 ||
259
+ 500 <= httpCode
260
+ );
261
+ }
262
+
263
+ function createDir(directory) {
264
+ if (!fs.existsSync(directory)) {
265
+ fs.mkdirSync(directory, {recursive: true});
266
+ return true;
267
+ }
268
+ return null;
269
+ }
270
+
271
+ function createNumDir(mainDirectory) {
272
+ if (createDir(mainDirectory)) {
273
+ for (let i = 0; i <= 9; i++) {
274
+ fs.mkdir(path.join(mainDirectory, i.toString()), (err) => {
275
+ if (err)
276
+ console.error(err);
277
+ });
278
+ }
279
+ }
280
+ }
281
+
282
+ function getVersion() {
283
+ try {
284
+ const date = new Date(execSync('git show -s --format=%ci HEAD').toString().trim());
285
+ const formatDatePart = (value) => value.toString().padStart(2, '0');
286
+ const year = date.getFullYear().toString().slice(-2);
287
+ const month = formatDatePart(date.getMonth() + 1);
288
+ const day = formatDatePart(date.getDate());
289
+ const hour = formatDatePart(date.getHours());
290
+ const minute = formatDatePart(date.getMinutes());
291
+ return parseFloat(`${year}${month}.${day}${hour}${minute}`);
292
+ } catch {
293
+ return 1.0;
294
+ }
295
+ }
296
+
297
+ module.exports = {
298
+ _,
299
+ exception,
300
+ time,
301
+ sleepMs,
302
+ sleep,
303
+ promiseTimeout,
304
+ findKeyNode,
305
+ isEmpty,
306
+ limitString,
307
+ safeString,
308
+ randomWeighted,
309
+ tokenHex,
310
+ md5,
311
+ hashBcrypt,
312
+ verifyBcrypt,
313
+ cookieDict,
314
+ cookieHeader,
315
+ formatProxy,
316
+ proxyObject,
317
+ proxify,
318
+ serverIP,
319
+ foreignError,
320
+ createDir,
321
+ createNumDir,
322
+ getVersion
323
+ };
package/test/script.js ADDED
@@ -0,0 +1,52 @@
1
+ const helper = require("../src/index");
2
+ const axios = require("axios");
3
+
4
+
5
+ (async () => {
6
+ console.log("ENDSWITH TH", helper._.endsWith("ENDSWITH", "TH"));
7
+ console.log(helper.exception("something went wrong"));
8
+ console.log(helper.time());
9
+ await helper.sleepMs(1000);
10
+ console.log(helper.time());
11
+ await helper.sleep(1);
12
+ console.log(helper.time());
13
+ try {
14
+ await helper.promiseTimeout(1000, helper.sleepMs(2000));
15
+ } catch (e) {
16
+ console.error(e.message);
17
+ }
18
+ console.log(helper.findKeyNode("c", {
19
+ a: {
20
+ b: {
21
+ x: 1,
22
+ y: 2,
23
+ c: {
24
+ d: true
25
+ }
26
+ }
27
+ }
28
+ }));
29
+ console.log("1 empty", helper.isEmpty(1));
30
+ console.log("[] empty", helper.isEmpty([]));
31
+ console.log(helper.limitString("LONG TEXT", 7));
32
+ console.log(helper.safeString("<strong>SAFE TEXT</strong>"));
33
+ console.log(helper.randomWeighted({strongProbability: 1000, lowProbability: 1}));
34
+ console.log(helper.tokenHex(8));
35
+ console.log(helper.md5("data"));
36
+ const password = helper.hashBcrypt("plain");
37
+ console.log(password)
38
+ console.log("passwordHash", helper.verifyBcrypt("plain", password));
39
+ const cookies = helper.cookieDict(await axios.get("https://google.com"));
40
+ console.log(cookies);
41
+ console.log(helper.cookieHeader(cookies));
42
+ const proxy = helper.formatProxy("127.0.0.1:8080:id:pw-{SESSION}");
43
+ console.log(proxy);
44
+ console.log(helper.proxyObject(proxy));
45
+ console.log(await helper.proxify({mode: 4, proxy}));
46
+ console.log(helper.serverIP());
47
+ console.log("HTTP CODE: 401 FOREIGN", helper.foreignError(401));
48
+ console.log("HTTP CODE: 0 FOREIGN", helper.foreignError(0));
49
+ helper.createNumDir("test");
50
+ helper.createDir("test");
51
+ console.log("VERSIONED BY .GIT", "v" + helper.getVersion());
52
+ })();