mybase 1.1.53 → 1.2.3

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.
Files changed (124) hide show
  1. package/ip6addr.d.ts +10 -1
  2. package/mybase.d.ts +57 -0
  3. package/mybase.js +401 -684
  4. package/mybase.js.map +1 -0
  5. package/package.json +18 -2
  6. package/ts/funcs/Geoip2Paths.js +7 -5
  7. package/ts/funcs/Geoip2Paths.js.map +1 -0
  8. package/ts/funcs/MaxRuntimeHours.js.map +1 -0
  9. package/ts/funcs/asJSON.d.ts +1 -1
  10. package/ts/funcs/asJSON.js +6 -4
  11. package/ts/funcs/asJSON.js.map +1 -0
  12. package/ts/funcs/deepCopy.js.map +1 -0
  13. package/ts/funcs/ensureFolder.js.map +1 -0
  14. package/ts/funcs/fileCacheIsValid.js.map +1 -0
  15. package/ts/funcs/getMysql1.js.map +1 -0
  16. package/ts/funcs/getMysql2.js.map +1 -0
  17. package/ts/funcs/getWeekNumber.js.map +1 -0
  18. package/ts/funcs/hash_sha512.d.ts +1 -1
  19. package/ts/funcs/hash_sha512.js +4 -4
  20. package/ts/funcs/hash_sha512.js.map +1 -0
  21. package/ts/funcs/initMysql2Pool.js.map +1 -0
  22. package/ts/funcs/int2ip.js.map +1 -0
  23. package/ts/funcs/ip2int.js.map +1 -0
  24. package/ts/funcs/isLANIp.d.ts +2 -3
  25. package/ts/funcs/isLANIp.js +14 -15
  26. package/ts/funcs/isLANIp.js.map +1 -0
  27. package/ts/funcs/isLocal.js.map +1 -0
  28. package/ts/funcs/isLoopbackIP.d.ts +2 -3
  29. package/ts/funcs/isLoopbackIP.js +15 -16
  30. package/ts/funcs/isLoopbackIP.js.map +1 -0
  31. package/ts/funcs/knexConnection.js.map +1 -0
  32. package/ts/funcs/promiseTimeout.js.map +1 -0
  33. package/ts/funcs/randomIP.js.map +1 -0
  34. package/ts/funcs/randomIP6.js.map +1 -0
  35. package/ts/funcs/randomString.js.map +1 -0
  36. package/ts/funcs/randomTCPPort.js.map +1 -0
  37. package/ts/funcs/randomUTFString.js.map +1 -0
  38. package/ts/funcs/utcnow.js.map +1 -0
  39. package/ts/funcs/validEmail.d.ts +1 -1
  40. package/ts/funcs/validEmail.js +0 -3
  41. package/ts/funcs/validEmail.js.map +1 -0
  42. package/ts/funcs/validIp.js.map +1 -0
  43. package/ts/funcs/vaultFill.js +1 -1
  44. package/ts/funcs/vaultFill.js.map +1 -0
  45. package/ts/funcs/vaultRead.js +9 -3
  46. package/ts/funcs/vaultRead.js.map +1 -0
  47. package/ts/funcs/wait.js.map +1 -0
  48. package/ts/global.js.map +1 -0
  49. package/ts/index.js.map +1 -0
  50. package/ts/models/DateIterator.js.map +1 -0
  51. package/ts/models/IPAddress.d.ts +13 -13
  52. package/ts/models/IPAddress.js.map +1 -0
  53. package/ts/models/Interfaces.js.map +1 -0
  54. package/ts/models/OTPGenerator.js.map +1 -0
  55. package/ts/models/Timespan.js.map +1 -0
  56. package/ts/models/Unixtime.js.map +1 -0
  57. package/ts/types.d.ts +35 -0
  58. package/ts/types.js +1 -0
  59. package/ts/types.js.map +1 -0
  60. package/jest/isLANIp.test.js +0 -36
  61. package/jest/isLoopbackIP.test.js +0 -31
  62. package/jest.config.js +0 -7
  63. package/ts/funcs/Geoip2Paths.test.ts +0 -11
  64. package/ts/funcs/Geoip2Paths.ts +0 -26
  65. package/ts/funcs/MaxRuntimeHours.ts +0 -7
  66. package/ts/funcs/asJSON.test.js +0 -72
  67. package/ts/funcs/asJSON.ts +0 -6
  68. package/ts/funcs/deepCopy.test.ts +0 -108
  69. package/ts/funcs/deepCopy.ts +0 -34
  70. package/ts/funcs/ensureFolder.test.ts +0 -79
  71. package/ts/funcs/ensureFolder.ts +0 -21
  72. package/ts/funcs/fileCacheIsValid.ts +0 -13
  73. package/ts/funcs/getMysql1.ts +0 -41
  74. package/ts/funcs/getMysql2.ts +0 -42
  75. package/ts/funcs/getWeekNumber.test.ts +0 -9
  76. package/ts/funcs/getWeekNumber.ts +0 -31
  77. package/ts/funcs/hash_sha512.ts +0 -7
  78. package/ts/funcs/initMysql2Pool.ts +0 -11
  79. package/ts/funcs/int2ip.test.js +0 -33
  80. package/ts/funcs/int2ip.ts +0 -9
  81. package/ts/funcs/ip2int.test.js +0 -30
  82. package/ts/funcs/ip2int.ts +0 -10
  83. package/ts/funcs/isLANIp.test.ts +0 -59
  84. package/ts/funcs/isLANIp.ts +0 -37
  85. package/ts/funcs/isLocal.test.ts +0 -16
  86. package/ts/funcs/isLocal.ts +0 -5
  87. package/ts/funcs/isLoopbackIP.test.ts +0 -72
  88. package/ts/funcs/isLoopbackIP.ts +0 -32
  89. package/ts/funcs/knexConnection.ts +0 -42
  90. package/ts/funcs/promiseTimeout.test.js +0 -104
  91. package/ts/funcs/promiseTimeout.ts +0 -19
  92. package/ts/funcs/randomIP.test.ts +0 -16
  93. package/ts/funcs/randomIP.ts +0 -10
  94. package/ts/funcs/randomIP6.test.js +0 -18
  95. package/ts/funcs/randomIP6.ts +0 -12
  96. package/ts/funcs/randomString.test.ts +0 -15
  97. package/ts/funcs/randomString.ts +0 -5
  98. package/ts/funcs/randomTCPPort.test.ts +0 -62
  99. package/ts/funcs/randomTCPPort.ts +0 -58
  100. package/ts/funcs/randomUTFString.test.ts +0 -44
  101. package/ts/funcs/randomUTFString.ts +0 -33
  102. package/ts/funcs/utcnow.ts +0 -5
  103. package/ts/funcs/validEmail.test.js +0 -31
  104. package/ts/funcs/validEmail.ts +0 -13
  105. package/ts/funcs/validIp.test.ts +0 -33
  106. package/ts/funcs/validIp.ts +0 -5
  107. package/ts/funcs/vaultFill.ts +0 -89
  108. package/ts/funcs/vaultRead.ts +0 -45
  109. package/ts/funcs/wait.ts +0 -7
  110. package/ts/global.ts +0 -10
  111. package/ts/index.test.ts +0 -7
  112. package/ts/index.ts +0 -39
  113. package/ts/models/DateIterator.test.ts +0 -149
  114. package/ts/models/DateIterator.ts +0 -80
  115. package/ts/models/IPAddress.test.ts +0 -393
  116. package/ts/models/IPAddress.ts +0 -272
  117. package/ts/models/Interfaces.ts +0 -58
  118. package/ts/models/OTPGenerator.test.ts +0 -42
  119. package/ts/models/OTPGenerator.ts +0 -43
  120. package/ts/models/Timespan.ts +0 -80
  121. package/ts/models/Unixtime.test.ts +0 -168
  122. package/ts/models/Unixtime.ts +0 -208
  123. package/ts/types.ts +0 -1
  124. package/tsconfig.json +0 -36
package/mybase.js CHANGED
@@ -1,427 +1,270 @@
1
- const { ipRangeCheck } = require('ip-range-check')
2
- const aesjs = require("aes-js")
3
- const debug = require('debug')('mybase')
4
- const os = require('os')
5
- const fs = require('fs')
6
- const path = require('path')
7
- const net = require('net')
8
- const chalk = require('chalk')
9
- const _validURL = require('@7c/validurl')
10
- const validator = require('validator')
11
- const sha512 = require('js-sha512')
12
- const ip6addr = require('@7c/node-ip6addr')
13
-
14
- const private_network_cidrs = [ip6addr.createCIDR('10.0.0.0/8')
15
- ,ip6addr.createCIDR('172.16.0.0/12')
16
- ,ip6addr.createCIDR('192.168.0.0/16')
17
- ,ip6addr.createCIDR('fd00::/8'), // Reserved by IETF for future use, but not currently in active use.
18
- ,ip6addr.createCIDR('fc00::/8'), // The range currently in use for local communications within a site or organization.
19
- ]
20
-
21
- const local_network_cidrs = [ip6addr.createCIDR('127.0.0.0/8')
22
- ,ip6addr.createCIDR('::1/128')]
23
-
24
- // create cache folder if not exists
25
- let vault_cache_folder = '/var/tmp/vault-cache'
26
- if (!fs.existsSync(vault_cache_folder)) fs.mkdirSync(vault_cache_folder)
27
-
28
-
29
- Date.prototype.yyyymmdd = function() {
30
- var mm = this.getMonth() + 1; // getMonth() is zero-based
31
- var dd = this.getDate();
32
-
33
- return [this.getFullYear(),
34
- (mm > 9 ? '' : '0') + mm,
35
- (dd > 9 ? '' : '0') + dd
36
- ].join('');
37
- };
38
-
39
- function hash_sha512(plain) {
40
- if (typeof plain==='string') return sha512(plain)
41
- return false
42
- }
43
-
44
- function normalizeIp(ip) {
45
- // also support ipv6
46
- if (net.isIP(ip) === 0) return false;
47
- if (net.isIPv6(ip)) return ip.toLowerCase().replace(/^::ffff:/, '');
48
- return ip;
49
- }
50
-
51
-
52
- function isLoopbackIP(ip) { // ported
53
- ip=normalizeIp(ip)
54
- if (net.isIP(ip) === 0) return false
55
- try {
56
- // speed optimized
57
- let ipVersion = net.isIPv4(ip) ? 'ipv4' : 'ipv6'
58
- for (let cidr of local_network_cidrs) {
59
- let first = cidr.first()
60
- if (first.kind() !== ipVersion) continue
61
- if (cidr.contains(ip))
62
- return true
63
- }
64
- return null
65
- } catch (err) {
66
- console.log(err)
67
- }
68
- return false
69
- }
70
-
71
- function isLANIp(ip) { // ported
72
- ip=normalizeIp(ip)
73
- if (net.isIP(ip) === 0) return false
74
- try {
75
- // speed optimized
76
- let ipVersion = net.isIPv4(ip) ? 'ipv4' : 'ipv6'
77
- for (let cidr of private_network_cidrs) {
78
- if (!cidr) continue
79
- let first = cidr.first()
80
- if (first.kind() !== ipVersion) continue
81
- if (cidr.contains(ip))
82
- return true
83
- }
84
- return null
85
- } catch (err) {
86
- console.log(err)
87
- }
88
- return false
89
- }
90
-
91
- function validHPassword(hpassword) { return (hpassword && hpassword.length === 128 && hpassword.search(/^[a-f0-9]+$/) == 0) }
92
- function randomHPassword(length=10) {
93
- let plain = randomString(length)
94
- return sha512(plain)
95
- }
96
-
97
- function validEmail(email) { //! ported
98
- if (typeof email==='string')
99
- return validator.isEmail(email) // validator needs a string
100
- return false
101
- // giving up old style, was not reliable
102
- // taken from https://www.w3resource.com/javascript/form/email-validation.php
103
- // strange looking emails might be indeed valid
104
- // check https://www.w3resource.com/javascript/form/example-javascript-form-validation-email-REC-2822.html
105
- if (typeof email==='string') email=email.toLowerCase().trim()
106
- return (/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/).test(email)
107
- }
108
-
109
- function arrayRandomItem(arry,defaultValue=false) {
110
- if (Array.isArray(arry)) {
111
- return arry[Math.floor(Math.random()*arry.length)]
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
112
7
  }
113
- return defaultValue
114
- }
115
-
116
- function utcnow() { // ported
117
- return Math.floor(Date.now() / 1000)
118
- }
119
-
120
- function validIp(str) { // ported
121
- console.log(`WARNING: validIp is deprecated, use validIpNative or IPAddress model`)
122
- if (str && typeof str==='string') {
123
- let splitted
124
- if (splitted=str.match(/^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/)) {
125
- for(let octet of splitted) {
126
- if (parseInt(octet)>=0 && parseInt(octet)<=255) continue
127
- return false
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.isLANIp = exports.isLoopbackIP = exports.hash_sha512 = exports.vaultFill = exports.vaultRead = exports.Geoip2Paths = exports.MaxRuntimeHours = exports.randomIP = exports.promiseTimeout = exports.asJSON = exports.validEmail = exports.isLocal = exports.utcnow = exports.wait = exports.randomString = void 0;
40
+ exports.validHPassword = validHPassword;
41
+ exports.randomHPassword = randomHPassword;
42
+ exports.arrayRandomItem = arrayRandomItem;
43
+ exports.validIp = validIp;
44
+ exports.validIpNative = validIpNative;
45
+ exports.isURL = isURL;
46
+ exports.validTime = validTime;
47
+ exports.validURL = validURL;
48
+ exports.isObject = isObject;
49
+ exports.getMysql = getMysql;
50
+ exports.maxmindOpen = maxmindOpen;
51
+ exports.randomBase32 = randomBase32;
52
+ exports.validAuthcode = validAuthcode;
53
+ exports.randomAuthcode = randomAuthcode;
54
+ exports.array_shuffle = array_shuffle;
55
+ exports.object_shuffle = object_shuffle;
56
+ exports.canReadAndWrite = canReadAndWrite;
57
+ exports.softexit = softexit;
58
+ exports.validHostname = validHostname;
59
+ exports.validHostname2 = validHostname2;
60
+ exports.removeDoubleSlashes = removeDoubleSlashes;
61
+ exports.getTemp = getTemp;
62
+ exports.sqlQuery = sqlQuery;
63
+ exports.isMochaRunning = isMochaRunning;
64
+ exports.validUUID4 = validUUID4;
65
+ exports.portCheck_tcp = portCheck_tcp;
66
+ exports.ensureProperty = ensureProperty;
67
+ exports.int2ip = int2ip;
68
+ exports.ip2int = ip2int;
69
+ exports.encryptAES_CBC_NOIV = encryptAES_CBC_NOIV;
70
+ exports.decryptAES_CBC_NOIV = decryptAES_CBC_NOIV;
71
+ exports.isReservedLANIP = isReservedLANIP;
72
+ /// <reference path="./ip6addr.d.ts" />
73
+ //#region imports
74
+ const ip_range_check_1 = __importDefault(require("ip-range-check"));
75
+ const aes_js_1 = __importDefault(require("aes-js"));
76
+ const debug_1 = __importDefault(require("debug"));
77
+ const os_1 = __importDefault(require("os"));
78
+ const fs_1 = __importDefault(require("fs"));
79
+ const path_1 = __importDefault(require("path"));
80
+ const net_1 = __importDefault(require("net"));
81
+ const chalk_1 = __importDefault(require("chalk"));
82
+ const validurl_1 = __importDefault(require("@7c/validurl"));
83
+ const js_sha512_1 = require("js-sha512");
84
+ const ip6 = __importStar(require("ip6"));
85
+ const geoip2_node_1 = require("@maxmind/geoip2-node");
86
+ const randomString_1 = require("./ts/funcs/randomString");
87
+ Object.defineProperty(exports, "randomString", { enumerable: true, get: function () { return randomString_1.randomString; } });
88
+ var wait_1 = require("./ts/funcs/wait");
89
+ Object.defineProperty(exports, "wait", { enumerable: true, get: function () { return wait_1.wait; } });
90
+ var utcnow_1 = require("./ts/funcs/utcnow");
91
+ Object.defineProperty(exports, "utcnow", { enumerable: true, get: function () { return utcnow_1.utcnow; } });
92
+ var isLocal_1 = require("./ts/funcs/isLocal");
93
+ Object.defineProperty(exports, "isLocal", { enumerable: true, get: function () { return isLocal_1.isLocal; } });
94
+ var validEmail_1 = require("./ts/funcs/validEmail");
95
+ Object.defineProperty(exports, "validEmail", { enumerable: true, get: function () { return validEmail_1.validEmail; } });
96
+ var asJSON_1 = require("./ts/funcs/asJSON");
97
+ Object.defineProperty(exports, "asJSON", { enumerable: true, get: function () { return asJSON_1.asJSON; } });
98
+ var promiseTimeout_1 = require("./ts/funcs/promiseTimeout");
99
+ Object.defineProperty(exports, "promiseTimeout", { enumerable: true, get: function () { return promiseTimeout_1.promiseTimeout; } });
100
+ var randomIP_1 = require("./ts/funcs/randomIP");
101
+ Object.defineProperty(exports, "randomIP", { enumerable: true, get: function () { return randomIP_1.randomIP; } });
102
+ var MaxRuntimeHours_1 = require("./ts/funcs/MaxRuntimeHours");
103
+ Object.defineProperty(exports, "MaxRuntimeHours", { enumerable: true, get: function () { return MaxRuntimeHours_1.MaxRuntimeHours; } });
104
+ var Geoip2Paths_1 = require("./ts/funcs/Geoip2Paths");
105
+ Object.defineProperty(exports, "Geoip2Paths", { enumerable: true, get: function () { return Geoip2Paths_1.Geoip2Paths; } });
106
+ var vaultRead_1 = require("./ts/funcs/vaultRead");
107
+ Object.defineProperty(exports, "vaultRead", { enumerable: true, get: function () { return vaultRead_1.vaultRead; } });
108
+ var vaultFill_1 = require("./ts/funcs/vaultFill");
109
+ Object.defineProperty(exports, "vaultFill", { enumerable: true, get: function () { return vaultFill_1.vaultFill; } });
110
+ var hash_sha512_1 = require("./ts/funcs/hash_sha512");
111
+ Object.defineProperty(exports, "hash_sha512", { enumerable: true, get: function () { return hash_sha512_1.hash_sha512; } });
112
+ var isLoopbackIP_1 = require("./ts/funcs/isLoopbackIP");
113
+ Object.defineProperty(exports, "isLoopbackIP", { enumerable: true, get: function () { return isLoopbackIP_1.isLoopbackIP; } });
114
+ var isLANIp_1 = require("./ts/funcs/isLANIp");
115
+ Object.defineProperty(exports, "isLANIp", { enumerable: true, get: function () { return isLANIp_1.isLANIp; } });
116
+ //#endregion
117
+ const debug = (0, debug_1.default)('mybase');
118
+ Date.prototype.yyyymmdd = function yyyymmdd() {
119
+ const mm = this.getMonth() + 1;
120
+ const dd = this.getDate();
121
+ return [this.getFullYear(), (mm > 9 ? '' : '0') + mm, (dd > 9 ? '' : '0') + dd].join('');
122
+ };
123
+ //#endregion
124
+ function validHPassword(hpassword) {
125
+ return !!(hpassword && hpassword.length === 128 && hpassword.search(/^[a-f0-9]+$/) === 0);
126
+ }
127
+ function randomHPassword(length = 10) {
128
+ const plain = (0, randomString_1.randomString)(length);
129
+ return (0, js_sha512_1.sha512)(plain);
130
+ }
131
+ function arrayRandomItem(arry, defaultValue = false) {
132
+ if (Array.isArray(arry))
133
+ return arry[Math.floor(Math.random() * arry.length)];
134
+ return defaultValue;
135
+ }
136
+ function validIp(str) {
137
+ console.log(`WARNING: validIp is deprecated, use validIpNative or IPAddress model`);
138
+ if (str && typeof str === 'string') {
139
+ const splitted = str.match(/^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/);
140
+ if (splitted) {
141
+ for (const octet of splitted) {
142
+ if (parseInt(octet, 10) >= 0 && parseInt(octet, 10) <= 255)
143
+ continue;
144
+ return false;
128
145
  }
129
- return true
146
+ return true;
130
147
  }
131
148
  }
132
- return false
133
- }
134
-
135
- function Geoip2Paths() { // ported
136
- function firstExisting(paths) {
137
- if (Array.isArray(paths))
138
- for(let fpath of paths)
139
- if (fs.existsSync(fpath)) return fpath
140
- return false
141
- }
142
-
143
- return {
144
- country:firstExisting(['/opt/geoip2/GeoIP2-Country.mmdb','/usr/local/var/GeoIP/GeoIP2-Country.mmdb','/var/lib/GeoIP/GeoIP2-Country.mmdb','/usr/share/GeoIP/GeoIP2-Country.mmdb',path.join(__dirname, 'assets/GeoIP2-Country.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-Country.mmdb')]),
145
- city:firstExisting(['/opt/geoip2/GeoIP2-City.mmdb','/usr/local/var/GeoIP/GeoIP2-City.mmdb','/var/lib/GeoIP/GeoIP2-City.mmdb','/usr/share/GeoIP/GeoIP2-City.mmdb',path.join(__dirname, 'assets/GeoIP2-City.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-City.mmdb')]),
146
- isp:firstExisting(['/opt/geoip2/GeoIP2-ISP.mmdb','/usr/local/var/GeoIP/GeoIP2-ISP.mmdb','/var/lib/GeoIP/GeoIP2-ISP.mmdb','/usr/share/GeoIP/GeoIP2-ISP.mmdb',path.join(__dirname, 'assets/GeoIP2-ISP.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-ISP.mmdb')]),
147
- ct:firstExisting(['/opt/geoip2/GeoIP2-Connection-Type.mmdb','/usr/local/var/GeoIP/GeoIP2-Connection-Type.mmdb','/var/lib/GeoIP/GeoIP2-Connection-Type.mmdb','/usr/share/GeoIP/GeoIP2-Connection-Type.mmdb',path.join(__dirname, 'assets/GeoIP2-Connection-Type.mmdb'),path.join(require?.main?.path || __dirname, 'assets/GeoIP2-Connection-Type.mmdb')]),
148
- }
149
+ return false;
149
150
  }
150
-
151
151
  function validIpNative(str) {
152
- return (net.isIP(str)!==0)
153
- // const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';
154
- // const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}$`);
155
- // return regex.test(str);
156
- }
157
-
158
- function randomIP() { // ported
159
- function int2ip (ipInt) {
160
- return ( (ipInt>>>24) +'.' + (ipInt>>16 & 255) +'.' + (ipInt>>8 & 255) +'.' + (ipInt & 255) );
161
- }
162
- return int2ip(Math.random()*Math.pow(2,32))
152
+ return net_1.default.isIP(str) !== 0;
163
153
  }
164
-
165
-
166
154
  function isURL(url) {
167
- if (typeof url === 'string') try { return new URL(url) } catch (e) { }
168
- return false
155
+ if (typeof url === 'string') {
156
+ try {
157
+ return new URL(url);
158
+ }
159
+ catch (_a) {
160
+ /* ignore */
161
+ }
162
+ }
163
+ return false;
169
164
  }
170
-
171
-
172
165
  function validTime(t) {
173
- var valid = (t && parseInt(t)>0 && t.toString().length===10)
174
- if (!valid) return false
175
- return parseInt(t)
166
+ const valid = !!(t && parseInt(String(t), 10) > 0 && String(t).length === 10);
167
+ if (!valid)
168
+ return false;
169
+ return parseInt(String(t), 10);
176
170
  }
177
-
178
171
  function validURL(host) {
179
- // started using @7c/validurl repo
180
- return _validURL(host)
172
+ return (0, validurl_1.default)(host);
181
173
  }
182
-
183
- function asJSON(str) { // ported
184
- if (!str || typeof str!=='string') return false
185
- try { return JSON.parse(str)}catch(_) {}
186
- return false
187
- }
188
-
189
174
  function isObject(a) {
190
- return (!!a) && (a.constructor === Object);
191
- }
192
-
193
- async function getMysql(mysqlClass,config,keep_pinging=true) {
194
- return new Promise((resolve,reject)=>{
195
- var mysql_client = mysqlClass.createConnection({
196
- host : config.host,
197
- port: config.port ? config.port : 3306,
198
- user : config.login,
199
- password : config.password,
200
- database : config.db
201
- });
202
- mysql_client.connect((err,res)=>{
175
+ return !!a && a.constructor === Object;
176
+ }
177
+ async function getMysql(mysqlClass, config, keep_pinging = true) {
178
+ const mysql_client = mysqlClass.createConnection({
179
+ host: config.host,
180
+ port: config.port ? config.port : 3306,
181
+ user: config.login,
182
+ password: config.password,
183
+ database: config.db,
184
+ });
185
+ await new Promise((resolve, reject) => {
186
+ mysql_client.connect((err) => {
203
187
  if (err) {
204
- debug(`mysql connection has failed to ${config.host}@${config.db}`,err)
205
- return reject(err);
188
+ debug(`mysql connection has failed to ${config.host}@${config.db}`, err);
189
+ reject(err);
190
+ return;
191
+ }
192
+ debug(`mysql connection has been established to ${config.host}@${config.db}`);
193
+ if (keep_pinging) {
194
+ setInterval(() => {
195
+ mysql_client.ping((errPing) => {
196
+ if (errPing && 'code' in errPing)
197
+ return console.log(`could not ping mysql ${config.host}@${config.db}`, errPing.code);
198
+ debug(chalk_1.default.bold(`mysql ${config.host}@${config.db} is pinging properly`));
199
+ });
200
+ }, 30000);
206
201
  }
207
- debug(`mysql connection has been established to ${config.host}@${config.db}`)
208
- // install a pinger every 30 seconds to keep the connection alive
209
- if (keep_pinging)
210
- setInterval(()=>{
211
- mysql_client.ping(function (err) {
212
- if (err) return console.log(`could not ping mysql ${config.host}@${config.db}`,err.code)
213
- debug(chalk.bold(`mysql ${config.host}@${config.db} is pinging properly`))
214
- })
215
- },30000)
216
- resolve(mysql_client);
202
+ resolve();
217
203
  });
218
- })
219
- }
220
-
221
- function fileCacheIsValid(cacheFile, cache_in_minutes = 60) {
222
- if (fs.existsSync(cacheFile)) {
223
- const stat = fs.statSync(cacheFile)
224
- const mtime = new Date(stat.mtime).getTime()
225
- if (Date.now() - mtime < cache_in_minutes * 60 * 1000) {
226
- // cache is still valid
227
- return true
228
- }
204
+ });
205
+ return mysql_client;
206
+ }
207
+ async function maxmindOpen(geoipFile) {
208
+ debug(`maxmindOpen ${geoipFile}`);
209
+ try {
210
+ const reader = await geoip2_node_1.Reader.open(geoipFile, { watchForUpdates: true });
211
+ debug(`${geoipFile} is opened successfully`);
212
+ return reader;
229
213
  }
230
- return false
231
- }
232
-
233
- function vaultRead(vault, key, cache_in_minutes = 10) {
234
- // v2 - supports caching
235
- return new Promise((resolve, reject) => {
236
- let cache_file = path.join(vault_cache_folder,hash_sha512(`${vault.endpoint}/${key}`))
237
- if (cache_in_minutes>0 && fileCacheIsValid(cache_file,cache_in_minutes))
238
- return resolve(JSON.parse(fs.readFileSync(cache_file)))
239
-
240
- vault.read(key).then((r) => {
241
- if (r.data) {
242
- debug(`vault ${key} - success`)
243
- if (cache_in_minutes>0)
244
- try { fs.writeFileSync(cache_file, JSON.stringify(r.data)); fs.chmodSync(cache_file,0o600); } catch(_) {}
245
- return resolve(r.data);
246
- }
247
- debug(`vault ${key} - failed`)
248
- reject(r);
249
- }).catch(e => {
250
- console.log(e)
251
- debug(`exception inside vaultRead`, e)
252
- // we will still return latest information from cache
253
- try {
254
- console.log(chalk.bgRed(`returning vault@${key} from cache due to error`))
255
- if (fs.existsSync(cache_file))
256
- return resolve(JSON.parse(fs.readFileSync(cache_file)))
257
- }catch(e2) {
258
- // content of the file is invalid
259
- console.log(e2)
260
- }
261
-
262
- reject(e);
263
- })
264
- })
265
- }
266
-
267
-
268
- function vaultFill(vault, obj, ignoreError = false, keepCache=true) { // ported
269
- // v2.1
270
- // fills all strings with ^vault@/secret/... with proper vault values
271
- // if you call it again, it does reload the configuration
272
- // v2.2
273
- // supports keepCache - if vault fails, we will keep previous values instead of filling with false
274
- return new Promise(async function(resolve, reject) {
275
- function findVaultKeyMappings(config, keys = []) {
276
-
277
- for (var i in config) {
278
- if (config[i] !== null) {
279
- if (typeof config[i] === 'object' && ( config[i].constructor.name==='Array' || config[i].constructor.name==='Object'))
280
- findVaultKeyMappings(config[i], keys)
281
-
282
- // detect previously read vaultKey
283
- if (i === '__vaultkey') {
284
- if (!keys.includes(vaultKey)) keys.push(config[i])
285
- continue
286
- }
287
- // --
288
- if (typeof config[i] === 'string' && config[i].search(/^vault@/) == 0) {
289
- var splitted = config[i].split(/vault@/)
290
- if (splitted.length == 2) {
291
- var vaultKey = splitted[1]
292
- if (!keys.includes(vaultKey)) keys.push(vaultKey)
293
- }
294
- }
295
- }
296
- }
297
- }
298
-
299
- function fillVaultKeyMappings(config, vaultResults) {
300
- for (var i in config) {
301
- if (config[i] !== null) {
302
-
303
- if (config[i] && config[i].constructor.name === 'Object' && config[i].hasOwnProperty('__vaultkey')) {
304
- if (keepCache) {
305
- if (vaultResults[config[i]['__vaultkey']]) config[i] = vaultResults[config[i]['__vaultkey']]
306
- }
307
-
308
- else
309
- config[i] = vaultResults[config[i]['__vaultkey']]
310
- continue
311
- }
312
- if (typeof config[i] === 'object' && ( config[i].constructor.name==='Array' || config[i].constructor.name==='Object'))
313
- fillVaultKeyMappings(config[i], vaultResults)
314
- if (typeof config[i] === 'string' && config[i].search(/^vault@/) == 0) {
315
- var splitted = config[i].split(/vault@/)
316
- if (splitted.length == 2) {
317
- var vaultKey = splitted[1]
318
- config[i] = vaultResults[vaultKey]
319
- }
320
- }
321
- }
322
- }
323
- }
324
-
325
- var vaultKeys = []
326
- var vaultResults = {}
327
- findVaultKeyMappings(obj, vaultKeys)
328
-
329
- // read these keys from vault
330
- for (var i in vaultKeys) {
331
- var val = vaultKeys[i]
332
- if (typeof val === "string")
333
- try {
334
- var got = await vaultRead(vault, vaultKeys[i])
335
- got['__vaultkey'] = val
336
- got['__vaultfilled'] = Date.now()
337
- vaultResults[val] = got
338
- }
339
- catch (err) {
340
- debug(`Could not read vaultKey '${val}'`, err)
341
- if (!ignoreError) vaultResults[val] = false
342
- }
343
- }
344
-
345
- fillVaultKeyMappings(obj, vaultResults)
346
-
347
- resolve(true)
348
- })
349
- }
350
-
351
-
352
- function maxmindOpen(geoipFile) {
353
- return new Promise((resolve, reject) => {
354
- const MaxmindReader = require('@maxmind/geoip2-node').Reader;
355
- debug(`maxmindOpen ${geoipFile}`)
356
- MaxmindReader.open(geoipFile, { watchForUpdates: true })
357
- .then(reader => {
358
- debug(`${geoipFile} is opened successfully`)
359
- resolve(reader)
360
- })
361
- .catch(err => {
362
- debug(`maxmindOpen Error at ${geoipFile}`, err)
363
- return reject(err)
364
- })
365
- })
366
- }
367
-
368
- function isLocal() { // ported
369
- return (os.type() === 'Darwin')
370
- }
371
-
372
- // https://en.wikipedia.org/wiki/Base32
373
- // base32 is case-insensivite
374
- // it uses an alphabet of A–Z, followed by 2–7. 0 and 1 are skipped due to their similarity with the letters O and I
214
+ catch (err) {
215
+ debug(`maxmindOpen Error at ${geoipFile}`, err);
216
+ throw err;
217
+ }
218
+ }
375
219
  function randomBase32(length = 10) {
376
- var charSet = "abcdefghijklmnopqrstuvwxyz234567"
377
- var text = "";
378
- for (var i = 0; i < length; i++)
220
+ const charSet = 'abcdefghijklmnopqrstuvwxyz234567';
221
+ let text = '';
222
+ for (let i = 0; i < length; i++)
379
223
  text += charSet.charAt(Math.floor(Math.random() * charSet.length));
380
224
  return text;
381
225
  }
382
-
383
-
384
226
  function validAuthcode(authcode) {
385
- var alphabetOnly = "abcdefghijklmnopqrstuvwxyz"
386
-
387
- if (!authcode || authcode.length!==12) return false
388
- authcode=authcode.toLowerCase()
389
- if (authcode.charAt(3)!='-') return false
390
- if (authcode.charAt(9)!='-') return false
391
- var checksum = 0
392
- var body = authcode.substring(1)
393
-
394
- for (var i = 0; i < body.length; i++){
395
- var c = body.charAt(i)
396
- if (c=='-') continue
397
- checksum+=c.charCodeAt(0)
227
+ const alphabetOnly = 'abcdefghijklmnopqrstuvwxyz';
228
+ if (!authcode || authcode.length !== 12)
229
+ return false;
230
+ const ac = authcode.toLowerCase();
231
+ if (ac.charAt(3) !== '-')
232
+ return false;
233
+ if (ac.charAt(9) !== '-')
234
+ return false;
235
+ let checksum = 0;
236
+ const body = ac.substring(1);
237
+ for (let i = 0; i < body.length; i++) {
238
+ const c = body.charAt(i);
239
+ if (c === '-')
240
+ continue;
241
+ checksum += c.charCodeAt(0);
398
242
  }
399
- var checksumChar = alphabetOnly.charAt(checksum % (alphabetOnly.length))
400
- if (checksumChar!==authcode.charAt(0)) return false
401
-
402
- return true
243
+ const checksumChar = alphabetOnly.charAt(checksum % alphabetOnly.length);
244
+ if (checksumChar !== ac.charAt(0))
245
+ return false;
246
+ return true;
403
247
  }
404
-
405
248
  function randomAuthcode() {
406
- var length = 9
407
- var charSet = "abcdefghijklmnopqrstuvwxyz234567"
408
- var alphabetOnly = "abcdefghijklmnopqrstuvwxyz"
409
- var checksum = 0
410
- var text = "";
411
- for (var i = 0; i < length; i++){
412
- if (i==2 || i==7) text+='-'
413
- var c = charSet.charAt(Math.floor(Math.random() * charSet.length))
414
- checksum+=c.charCodeAt(0)
415
- text+=c;
249
+ const length = 9;
250
+ const charSet = 'abcdefghijklmnopqrstuvwxyz234567';
251
+ const alphabetOnly = 'abcdefghijklmnopqrstuvwxyz';
252
+ let checksum = 0;
253
+ let text = '';
254
+ for (let i = 0; i < length; i++) {
255
+ if (i === 2 || i === 7)
256
+ text += '-';
257
+ const c = charSet.charAt(Math.floor(Math.random() * charSet.length));
258
+ checksum += c.charCodeAt(0);
259
+ text += c;
416
260
  }
417
- text = alphabetOnly.charAt(checksum % alphabetOnly.length)+text
261
+ text = alphabetOnly.charAt(checksum % alphabetOnly.length) + text;
418
262
  return text;
419
263
  }
420
-
421
-
422
264
  function array_shuffle(a) {
423
- var j, x, i;
424
- for (i = a.length - 1; i > 0; i--) {
265
+ let j;
266
+ let x;
267
+ for (let i = a.length - 1; i > 0; i--) {
425
268
  j = Math.floor(Math.random() * (i + 1));
426
269
  x = a[i];
427
270
  a[i] = a[j];
@@ -429,327 +272,201 @@ function array_shuffle(a) {
429
272
  }
430
273
  return a;
431
274
  }
432
-
433
275
  function object_shuffle(object) {
434
- var keys = array_shuffle(Object.keys(object))
435
- var ret = {}
436
- for(var k of keys) {
437
- ret[k]=object[k]
438
- }
439
- return ret
440
- }
441
-
442
-
443
-
444
-
445
- function randomString(length = 10, charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") { // ported
446
- var text = "";
447
- for (var i = 0; i < length; i++)
448
- text += charSet.charAt(Math.floor(Math.random() * charSet.length));
449
- return text;
450
- }
451
-
452
- function canReadAndWrite(targetPath, create = false) {
453
- return new Promise((resolve, reject) => {
454
- fs.stat(targetPath, (err) => {
276
+ const keys = array_shuffle(Object.keys(object));
277
+ const ret = {};
278
+ for (const k of keys)
279
+ ret[k] = object[k];
280
+ return ret;
281
+ }
282
+ async function canReadAndWrite(targetPath, _create = false) {
283
+ await new Promise((resolve, reject) => {
284
+ fs_1.default.stat(targetPath, (err) => {
455
285
  if (err) {
456
286
  if (err.code === 'ENOENT') {
457
- fs.mkdirSync(targetPath)
458
- } else return reject(err)
287
+ fs_1.default.mkdirSync(targetPath);
288
+ }
289
+ else {
290
+ reject(err);
291
+ return;
292
+ }
459
293
  }
460
- fs.access(targetPath, fs.W_OK | fs.R_OK, (err, b) => {
461
- if (err) return reject(err)
462
- debug(`canReadAndWrite ${targetPath}`)
463
- resolve(true);
464
- })
294
+ fs_1.default.access(targetPath, fs_1.default.constants.W_OK | fs_1.default.constants.R_OK, (errAcc) => {
295
+ if (errAcc)
296
+ return reject(errAcc);
297
+ debug(`canReadAndWrite ${targetPath}`);
298
+ resolve();
299
+ });
465
300
  });
466
- })
301
+ });
302
+ return true;
467
303
  }
468
-
469
-
470
304
  function softexit(message = false, seconds = 60, exitcode = 1) {
471
- if (message) console.log(message)
472
- console.log(`Softexit: will stop in ${seconds} seconds..`)
473
- setTimeout(() => { process.exit(exitcode) }, seconds * 1000)
305
+ if (message)
306
+ console.log(message);
307
+ console.log(`Softexit: will stop in ${seconds} seconds..`);
308
+ setTimeout(() => {
309
+ process.exit(exitcode);
310
+ }, seconds * 1000);
474
311
  }
475
-
476
312
  function validHostname(value) {
477
- // credit: https://github.com/miguelmota/is-valid-hostname/blob/master/index.js
478
- if (typeof value !== 'string') return false
479
-
480
- const validHostnameChars = /^[a-zA-Z0-9-.]{1,253}\.?$/g
481
- if (!validHostnameChars.test(value)) {
482
- return false
483
- }
484
-
485
- if (value.endsWith('.')) {
486
- value = value.slice(0, value.length - 1)
487
- }
488
-
489
- if (value.length > 253) {
490
- return false
491
- }
492
-
493
- const labels = value.split('.')
494
-
495
- const isValid = labels.every(function (label) {
496
- const validLabelChars = /^([a-zA-Z0-9-]+)$/g
497
-
498
- const validLabel = (
499
- validLabelChars.test(label) &&
500
- label.length < 64 &&
501
- !label.startsWith('-') &&
502
- !label.endsWith('-')
503
- )
504
-
505
- return validLabel
506
- })
507
-
508
- return isValid
509
- }
510
-
313
+ if (typeof value !== 'string')
314
+ return false;
315
+ let v = value;
316
+ const validHostnameChars = /^[a-zA-Z0-9-.]{1,253}\.?$/g;
317
+ if (!validHostnameChars.test(v))
318
+ return false;
319
+ if (v.endsWith('.'))
320
+ v = v.slice(0, v.length - 1);
321
+ if (v.length > 253)
322
+ return false;
323
+ const labels = v.split('.');
324
+ return labels.every((label) => {
325
+ const validLabelChars = /^([a-zA-Z0-9-]+)$/g;
326
+ return validLabelChars.test(label) && label.length < 64 && !label.startsWith('-') && !label.endsWith('-');
327
+ });
328
+ }
511
329
  function validHostname2(domainName) {
512
- var domainNameRegex = /^(?:[a-z0-9](?:[a-z0-9_\-]{0,61}[a-z0-9])?\.){0,126}(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9]))\.?$/i
513
- if (!domainName || typeof domainName!=='string') return false
514
- // is an ip host
515
- if (net.isIPv4(domainName) || net.isIPv6(domainName.replace(/[\[\]]/g,''))) return true
516
- // remove last '.'
517
- domainName=domainName.replace(/\.$/,'')
518
- if (domainName.length < 2) return false
519
- if (domainName.length > 255) return false
520
-
521
- if (domainName.search(/\./)<0 && domainName.search(/^[0-9]+$/)==0) {
522
- // using numbers without . in body
523
- return false
524
- }
525
-
526
- return domainNameRegex.test(domainName)
330
+ const domainNameRegex = /^(?:[a-z0-9](?:[a-z0-9_\-]{0,61}[a-z0-9])?\.){0,126}(?:[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9]))\.?$/i;
331
+ if (!domainName || typeof domainName !== 'string')
332
+ return false;
333
+ if (net_1.default.isIPv4(domainName) || net_1.default.isIPv6(domainName.replace(/[\[\]]/g, '')))
334
+ return true;
335
+ let dn = domainName.replace(/\.$/, '');
336
+ if (dn.length < 2)
337
+ return false;
338
+ if (dn.length > 255)
339
+ return false;
340
+ if (dn.search(/\./) < 0 && dn.search(/^[0-9]+$/) === 0)
341
+ return false;
342
+ return domainNameRegex.test(dn);
527
343
  }
528
-
529
344
  function removeDoubleSlashes(url) {
530
- if (typeof url==='string')
531
- return url.replace(/([^:]\/)\/+/g, "$1")
532
- return false
533
- }
534
-
535
-
536
- function getTemp(filename=false) {
537
- const fs = require('fs')
538
- const os = require('os')
539
- const path = require('path')
540
-
345
+ if (typeof url === 'string')
346
+ return url.replace(/([^:]\/)\/+/g, '$1');
347
+ return false;
348
+ }
349
+ function getTemp(filename = false) {
541
350
  const tempDirectorySymbol = Symbol.for('__RESOLVED_TEMP_DIRECTORY__');
542
-
543
- if (!global[tempDirectorySymbol]) {
544
- Object.defineProperty(global, tempDirectorySymbol, {
545
- value: fs.realpathSync(os.tmpdir())
351
+ const g = globalThis;
352
+ if (!g[tempDirectorySymbol]) {
353
+ Object.defineProperty(g, tempDirectorySymbol, {
354
+ value: fs_1.default.realpathSync(os_1.default.tmpdir()),
546
355
  });
547
356
  }
548
- var tmp = global[tempDirectorySymbol]
549
- if (filename) tmp=path.join(tmp,filename)
550
- return tmp
551
- }
552
-
553
- function sqlQuery(sqlHandle,query,values=[]) {
554
- return new Promise((resolve,reject)=>{
555
- sqlHandle.query(query,values,(err,res)=>{
556
- if (err)return reject(err)
557
- resolve(res)
558
- })
559
- })
560
- }
561
-
562
- function wait(seconds=1){ // ported
563
- return new Promise((resolve,reject)=>{
564
- setTimeout(resolve,seconds*1000)
565
- })
566
- }
567
-
357
+ let tmp = g[tempDirectorySymbol];
358
+ if (filename)
359
+ tmp = path_1.default.join(tmp, filename);
360
+ return tmp;
361
+ }
362
+ async function sqlQuery(sqlHandle, query, values = []) {
363
+ return await new Promise((resolve, reject) => {
364
+ sqlHandle.query(query, values, (err, res) => {
365
+ if (err)
366
+ return reject(err);
367
+ resolve(res);
368
+ });
369
+ });
370
+ }
568
371
  function isMochaRunning() {
569
- context = global
570
- return ['afterEach','after','beforeEach','before','describe','it'].every(function(functionName){
571
- return context[functionName] instanceof Function;
572
- })
372
+ const context = globalThis;
373
+ return ['afterEach', 'after', 'beforeEach', 'before', 'describe', 'it'].every((functionName) => {
374
+ return context[functionName] instanceof Function;
375
+ });
573
376
  }
574
-
575
377
  function validUUID4(uuid) {
576
- return new RegExp(/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i).test(uuid)
577
- }
578
-
579
- function promiseTimeout(ms, promise) { // ported
580
- // Create a promise that rejects in <ms> milliseconds
581
- let timeout = new Promise((resolve, reject) => {
582
- let id = setTimeout(() => {
583
- clearTimeout(id);
584
- reject('TIMEDOUT')
585
- }, ms)
586
- })
587
-
588
- // Returns a race between our timeout and the passed in promise
589
- return Promise.race([
590
- promise,
591
- timeout
592
- ])
593
- }
594
-
595
- async function portCheck_tcp (port, {timeout = 1000, host='127.0.0.1'} = {}) {
596
- const promise = new Promise(((resolve, reject) => {
597
- const socket = new net.Socket();
598
-
599
- const onError = (err) => {
600
- debug(`onError`,err)
601
- socket.destroy()
602
- reject()
603
- };
604
-
605
- socket.setTimeout(timeout);
606
- socket.once('error', onError);
607
- socket.once('timeout', onError);
608
-
609
- socket.connect(port, host, () => {
610
- debug(`socket.connect ${host}:${port}`)
611
- socket.end()
612
- resolve()
613
- })
614
- }))
615
-
616
- try {
617
- await promise;
618
- return true;
619
- } catch (_) {
620
- console.log(_)
621
- return false;
622
- }
623
- }
624
-
625
- function ensureProperty(target, propsString, defaultValue = false, debug = false) {
378
+ return /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i.test(uuid);
379
+ }
380
+ async function portCheck_tcp(port, opts = {}) {
381
+ const { timeout = 1000, host = '127.0.0.1' } = opts;
382
+ const promise = new Promise((resolve, reject) => {
383
+ const socket = new net_1.default.Socket();
384
+ const onError = (err) => {
385
+ debug(`onError`, err);
386
+ socket.destroy();
387
+ reject();
388
+ };
389
+ socket.setTimeout(timeout);
390
+ socket.once('error', onError);
391
+ socket.once('timeout', onError);
392
+ socket.connect(port, host, () => {
393
+ debug(`socket.connect ${host}:${port}`);
394
+ socket.end();
395
+ resolve();
396
+ });
397
+ });
398
+ try {
399
+ await promise;
400
+ return true;
401
+ }
402
+ catch (e) {
403
+ console.log(e);
404
+ return false;
405
+ }
406
+ }
407
+ function ensureProperty(target, propsString, defaultValue = false, debugWalk = false) {
626
408
  function iterate(o, parts) {
627
- if (debug) console.log(parts)
628
- let pname = parts.shift()
629
- if (debug) console.log(`iterate`, o, pname)
630
- if (o.hasOwnProperty(pname) && typeof o[pname] === 'object' && parts.length > 0) return iterate(o[pname], parts)
631
- if (debug) console.log(`--`, o, pname, o[pname], parts)
632
- if (o.hasOwnProperty(pname) && parts.length === 0) return o[pname]
633
- if (debug) console.log(`+++`)
634
- return defaultValue
409
+ if (debugWalk)
410
+ console.log(parts);
411
+ const pname = parts.shift();
412
+ if (pname === undefined)
413
+ return defaultValue;
414
+ if (debugWalk)
415
+ console.log(`iterate`, o, pname);
416
+ if (Object.prototype.hasOwnProperty.call(o, pname) && typeof o[pname] === 'object' && o[pname] !== null && parts.length > 0) {
417
+ return iterate(o[pname], parts);
418
+ }
419
+ if (debugWalk)
420
+ console.log(`--`, o, pname, o[pname], parts);
421
+ if (Object.prototype.hasOwnProperty.call(o, pname) && parts.length === 0)
422
+ return o[pname];
423
+ if (debugWalk)
424
+ console.log(`+++`);
425
+ return defaultValue;
635
426
  }
636
- var parts = propsString.split('.')
637
- return iterate(target, parts)
427
+ const parts = propsString.split('.');
428
+ return iterate(target, parts);
638
429
  }
639
-
640
-
641
-
642
- function int2ip (ipInt) { // ported into IPAddress
643
- return ( (ipInt>>>24) +'.' + (ipInt>>16 & 255) +'.' + (ipInt>>8 & 255) +'.' + (ipInt & 255) );
430
+ function int2ip(ipInt) {
431
+ return `${ipInt >>> 24}.${(ipInt >> 16) & 255}.${(ipInt >> 8) & 255}.${ipInt & 255}`;
644
432
  }
645
-
646
- function ip2int(ip) { // ported into IPAddress
647
- return ip.split('.').reduce(function(ipInt, octet) { return (ipInt<<8) + parseInt(octet, 10)}, 0) >>> 0;
433
+ function ip2int(ip) {
434
+ return (ip.split('.').reduce((ipInt, octet) => (ipInt << 8) + parseInt(octet, 10), 0) >>> 0);
648
435
  }
649
-
650
436
  function encryptAES_CBC_NOIV(plainString, encryptionKey) {
651
437
  try {
652
- const key = aesjs.utils.utf8.toBytes(encryptionKey); // 16,32 Bytes = 128,256 bits = AES128,AES256
653
- const textBytes = aesjs.utils.utf8.toBytes(plainString);
654
- const aesCbc = new aesjs.ModeOfOperation.cbc(key);
655
- const encryptedBytes = aesCbc.encrypt(aesjs.padding.pkcs7.pad(textBytes, 16));
656
- return aesjs.utils.hex.fromBytes(encryptedBytes);
657
- } catch (err) {
658
- // console.log(err)
659
- return false
438
+ const key = aes_js_1.default.utils.utf8.toBytes(encryptionKey);
439
+ const textBytes = aes_js_1.default.utils.utf8.toBytes(plainString);
440
+ const aesCbc = new aes_js_1.default.ModeOfOperation.cbc(key);
441
+ const encryptedBytes = aesCbc.encrypt(aes_js_1.default.padding.pkcs7.pad(textBytes, 16));
442
+ return aes_js_1.default.utils.hex.fromBytes(encryptedBytes);
443
+ }
444
+ catch (_a) {
445
+ return false;
660
446
  }
661
447
  }
662
-
663
-
664
-
665
-
666
-
667
448
  function decryptAES_CBC_NOIV(encryptedHex, encryptionKey) {
668
449
  try {
669
- const key = aesjs.utils.utf8.toBytes(encryptionKey); // 16,32 Bytes = 128,256 bits = AES128,AES256
670
- const encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);
671
- const aesCbc = new aesjs.ModeOfOperation.cbc(key);
672
- const decryptedBytes = aesjs.padding.pkcs7.strip(aesCbc.decrypt(encryptedBytes));
673
- return aesjs.utils.utf8.fromBytes(decryptedBytes);
674
-
675
- } catch (err) {
676
- // console.log(err)
677
- return false
450
+ const key = aes_js_1.default.utils.utf8.toBytes(encryptionKey);
451
+ const encryptedBytes = aes_js_1.default.utils.hex.toBytes(encryptedHex);
452
+ const aesCbc = new aes_js_1.default.ModeOfOperation.cbc(key);
453
+ const decryptedBytes = aes_js_1.default.padding.pkcs7.strip(aesCbc.decrypt(encryptedBytes));
454
+ return aes_js_1.default.utils.utf8.fromBytes(decryptedBytes);
455
+ }
456
+ catch (_a) {
457
+ return false;
678
458
  }
679
459
  }
680
-
681
- function MaxRuntimeHours(hours=24) {
682
- setTimeout(() => {
683
- console.log(`Max runtime of ${hours} hours reached, exiting`)
684
- process.exit(0)
685
- }, hours * 60 * 60 * 1000)
686
- }
687
-
688
-
689
460
  function isReservedLANIP(address) {
690
- // Define the reserved LAN IP ranges for IPv4 and IPv6.
691
461
  const reservedLANIPRanges = [
692
- '127.0.0.0/8', // Private IPv4 network
693
- '10.0.0.0/8', // Private IPv4 network
694
- '172.16.0.0/12', // Private IPv4 network
695
- '192.168.0.0/16', // Private IPv4 network
696
- '100.64.0.0/10', // Carrier-Grade NAT (CGN)
697
- 'fd00::/8', // Unique local address for IPv6
462
+ '127.0.0.0/8',
463
+ '10.0.0.0/8',
464
+ '172.16.0.0/12',
465
+ '192.168.0.0/16',
466
+ '100.64.0.0/10',
467
+ 'fd00::/8',
698
468
  ];
699
-
700
- // Normalize the IP address to expand any IPv6 shorthand notation.
701
- if (net.isIPv6(address))
702
- normalizedAddress = ip6.normalize(address);
703
- else normalizedAddress = address;
704
-
705
- // Check if the IP address is in the reserved LAN IP range.
706
- return ipRangeCheck(normalizedAddress, reservedLANIPRanges);
707
- }
708
-
709
- module.exports = {
710
- encryptAES_CBC_NOIV,
711
- decryptAES_CBC_NOIV,
712
- ip2int,int2ip,
713
- canReadAndWrite,
714
- softexit,
715
- randomString,
716
- randomBase32,
717
- randomAuthcode,
718
- validAuthcode,
719
- vaultRead,
720
- vaultFill,
721
- isLocal,
722
- isObject,
723
- maxmindOpen,
724
- validHPassword,
725
- validEmail,
726
- validHostname,
727
- validHostname2,
728
- validIp,validIpNative,
729
- validUUID4,
730
- getTemp,
731
- getMysql,
732
- sqlQuery,
733
- validURL,
734
- randomIP,
735
- wait,
736
- validTime,
737
- removeDoubleSlashes,
738
- array_shuffle,
739
- object_shuffle,
740
- isMochaRunning,
741
- portCheck_tcp,
742
- asJSON,
743
- ensureProperty,
744
- arrayRandomItem,
745
- promiseTimeout,
746
- utcnow,
747
- Geoip2Paths,
748
- randomHPassword,
749
- isURL,
750
- hash_sha512,
751
- isReservedLANIP,
752
- isLANIp,
753
- isLoopbackIP,
754
- MaxRuntimeHours
755
- }
469
+ const normalizedAddress = net_1.default.isIPv6(address) ? ip6.normalize(address) : address;
470
+ return (0, ip_range_check_1.default)(normalizedAddress, reservedLANIPRanges);
471
+ }
472
+ //# sourceMappingURL=mybase.js.map