@synotech/utils
Version:
a collection of utilities for internal use
1,071 lines (1,064 loc) • 155 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var node_dns = require('node:dns');
var crypto = require('crypto');
var jwt = _interopDefault(require('jsonwebtoken'));
var node_console = require('node:console');
var _ = require('lodash');
var ___default = _interopDefault(_);
var libphonenumberJs = require('libphonenumber-js');
var currency = _interopDefault(require('currency.js'));
var BigNumber = _interopDefault(require('bignumber.js'));
var dateFns = require('date-fns');
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
function _extends() {
return _extends = Object.assign ? Object.assign.bind() : function (n) {
for (var e = 1; e < arguments.length; e++) {
var t = arguments[e];
for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
}
return n;
}, _extends.apply(null, arguments);
}
function _regeneratorRuntime() {
_regeneratorRuntime = function () {
return e;
};
var t,
e = {},
r = Object.prototype,
n = r.hasOwnProperty,
o = Object.defineProperty || function (t, e, r) {
t[e] = r.value;
},
i = "function" == typeof Symbol ? Symbol : {},
a = i.iterator || "@@iterator",
c = i.asyncIterator || "@@asyncIterator",
u = i.toStringTag || "@@toStringTag";
function define(t, e, r) {
return Object.defineProperty(t, e, {
value: r,
enumerable: !0,
configurable: !0,
writable: !0
}), t[e];
}
try {
define({}, "");
} catch (t) {
define = function (t, e, r) {
return t[e] = r;
};
}
function wrap(t, e, r, n) {
var i = e && e.prototype instanceof Generator ? e : Generator,
a = Object.create(i.prototype),
c = new Context(n || []);
return o(a, "_invoke", {
value: makeInvokeMethod(t, r, c)
}), a;
}
function tryCatch(t, e, r) {
try {
return {
type: "normal",
arg: t.call(e, r)
};
} catch (t) {
return {
type: "throw",
arg: t
};
}
}
e.wrap = wrap;
var h = "suspendedStart",
l = "suspendedYield",
f = "executing",
s = "completed",
y = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var p = {};
define(p, a, function () {
return this;
});
var d = Object.getPrototypeOf,
v = d && d(d(values([])));
v && v !== r && n.call(v, a) && (p = v);
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
function defineIteratorMethods(t) {
["next", "throw", "return"].forEach(function (e) {
define(t, e, function (t) {
return this._invoke(e, t);
});
});
}
function AsyncIterator(t, e) {
function invoke(r, o, i, a) {
var c = tryCatch(t[r], t, o);
if ("throw" !== c.type) {
var u = c.arg,
h = u.value;
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
invoke("next", t, i, a);
}, function (t) {
invoke("throw", t, i, a);
}) : e.resolve(h).then(function (t) {
u.value = t, i(u);
}, function (t) {
return invoke("throw", t, i, a);
});
}
a(c.arg);
}
var r;
o(this, "_invoke", {
value: function (t, n) {
function callInvokeWithMethodAndArg() {
return new e(function (e, r) {
invoke(t, n, e, r);
});
}
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
}
});
}
function makeInvokeMethod(e, r, n) {
var o = h;
return function (i, a) {
if (o === f) throw Error("Generator is already running");
if (o === s) {
if ("throw" === i) throw a;
return {
value: t,
done: !0
};
}
for (n.method = i, n.arg = a;;) {
var c = n.delegate;
if (c) {
var u = maybeInvokeDelegate(c, n);
if (u) {
if (u === y) continue;
return u;
}
}
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
if (o === h) throw o = s, n.arg;
n.dispatchException(n.arg);
} else "return" === n.method && n.abrupt("return", n.arg);
o = f;
var p = tryCatch(e, r, n);
if ("normal" === p.type) {
if (o = n.done ? s : l, p.arg === y) continue;
return {
value: p.arg,
done: n.done
};
}
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
}
};
}
function maybeInvokeDelegate(e, r) {
var n = r.method,
o = e.iterator[n];
if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
var i = tryCatch(o, e.iterator, r.arg);
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
var a = i.arg;
return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
}
function pushTryEntry(t) {
var e = {
tryLoc: t[0]
};
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
}
function resetTryEntry(t) {
var e = t.completion || {};
e.type = "normal", delete e.arg, t.completion = e;
}
function Context(t) {
this.tryEntries = [{
tryLoc: "root"
}], t.forEach(pushTryEntry, this), this.reset(!0);
}
function values(e) {
if (e || "" === e) {
var r = e[a];
if (r) return r.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) {
var o = -1,
i = function next() {
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
return next.value = t, next.done = !0, next;
};
return i.next = i;
}
}
throw new TypeError(typeof e + " is not iterable");
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
value: GeneratorFunctionPrototype,
configurable: !0
}), o(GeneratorFunctionPrototype, "constructor", {
value: GeneratorFunction,
configurable: !0
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
var e = "function" == typeof t && t.constructor;
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
}, e.mark = function (t) {
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
}, e.awrap = function (t) {
return {
__await: t
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
return this;
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
void 0 === i && (i = Promise);
var a = new AsyncIterator(wrap(t, r, n, o), i);
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
return t.done ? t.value : a.next();
});
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
return this;
}), define(g, "toString", function () {
return "[object Generator]";
}), e.keys = function (t) {
var e = Object(t),
r = [];
for (var n in e) r.push(n);
return r.reverse(), function next() {
for (; r.length;) {
var t = r.pop();
if (t in e) return next.value = t, next.done = !1, next;
}
return next.done = !0, next;
};
}, e.values = values, Context.prototype = {
constructor: Context,
reset: function (e) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
},
stop: function () {
this.done = !0;
var t = this.tryEntries[0].completion;
if ("throw" === t.type) throw t.arg;
return this.rval;
},
dispatchException: function (e) {
if (this.done) throw e;
var r = this;
function handle(n, o) {
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
}
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
var i = this.tryEntries[o],
a = i.completion;
if ("root" === i.tryLoc) return handle("end");
if (i.tryLoc <= this.prev) {
var c = n.call(i, "catchLoc"),
u = n.call(i, "finallyLoc");
if (c && u) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
} else if (c) {
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
} else {
if (!u) throw Error("try statement without catch or finally");
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
}
}
}
},
abrupt: function (t, e) {
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
var o = this.tryEntries[r];
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
var i = o;
break;
}
}
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
var a = i ? i.completion : {};
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
},
complete: function (t, e) {
if ("throw" === t.type) throw t.arg;
return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
},
finish: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
}
},
catch: function (t) {
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
var r = this.tryEntries[e];
if (r.tryLoc === t) {
var n = r.completion;
if ("throw" === n.type) {
var o = n.arg;
resetTryEntry(r);
}
return o;
}
}
throw Error("illegal catch attempt");
},
delegateYield: function (e, r, n) {
return this.delegate = {
iterator: values(e),
resultName: r,
nextLoc: n
}, "next" === this.method && (this.arg = t), y;
}
}, e;
}
var tlds = ['# version 2023033100, last updated fri mar 31 07:07:01 2023 utc', 'aaa', 'aarp', 'abarth', 'abb', 'abbott', 'abbvie', 'abc', 'able', 'abogado', 'abudhabi', 'ac', 'academy', 'accenture', 'accountant', 'accountants', 'aco', 'actor', 'ad', 'ads', 'adult', 'ae', 'aeg', 'aero', 'aetna', 'af', 'afl', 'africa', 'ag', 'agakhan', 'agency', 'ai', 'aig', 'airbus', 'airforce', 'airtel', 'akdn', 'al', 'alfaromeo', 'alibaba', 'alipay', 'allfinanz', 'allstate', 'ally', 'alsace', 'alstom', 'am', 'amazon', 'americanexpress', 'americanfamily', 'amex', 'amfam', 'amica', 'amsterdam', 'analytics', 'android', 'anquan', 'anz', 'ao', 'aol', 'apartments', 'app', 'apple', 'aq', 'aquarelle', 'ar', 'arab', 'aramco', 'archi', 'army', 'arpa', 'art', 'arte', 'as', 'asda', 'asia', 'associates', 'at', 'athleta', 'attorney', 'au', 'auction', 'audi', 'audible', 'audio', 'auspost', 'author', 'auto', 'autos', 'avianca', 'aw', 'aws', 'ax', 'axa', 'az', 'azure', 'ba', 'baby', 'baidu', 'banamex', 'bananarepublic', 'band', 'bank', 'bar', 'barcelona', 'barclaycard', 'barclays', 'barefoot', 'bargains', 'baseball', 'basketball', 'bauhaus', 'bayern', 'bb', 'bbc', 'bbt', 'bbva', 'bcg', 'bcn', 'bd', 'be', 'beats', 'beauty', 'beer', 'bentley', 'berlin', 'best', 'bestbuy', 'bet', 'bf', 'bg', 'bh', 'bharti', 'bi', 'bible', 'bid', 'bike', 'bing', 'bingo', 'bio', 'biz', 'bj', 'black', 'blackfriday', 'blockbuster', 'blog', 'bloomberg', 'blue', 'bm', 'bms', 'bmw', 'bn', 'bnpparibas', 'bo', 'boats', 'boehringer', 'bofa', 'bom', 'bond', 'boo', 'book', 'booking', 'bosch', 'bostik', 'boston', 'bot', 'boutique', 'box', 'br', 'bradesco', 'bridgestone', 'broadway', 'broker', 'brother', 'brussels', 'bs', 'bt', 'build', 'builders', 'business', 'buy', 'buzz', 'bv', 'bw', 'by', 'bz', 'bzh', 'ca', 'cab', 'cafe', 'cal', 'call', 'calvinklein', 'cam', 'camera', 'camp', 'canon', 'capetown', 'capital', 'capitalone', 'car', 'caravan', 'cards', 'care', 'career', 'careers', 'cars', 'casa', 'case', 'cash', 'casino', 'cat', 'catering', 'catholic', 'cba', 'cbn', 'cbre', 'cbs', 'cc', 'cd', 'center', 'ceo', 'cern', 'cf', 'cfa', 'cfd', 'cg', 'ch', 'chanel', 'channel', 'charity', 'chase', 'chat', 'cheap', 'chintai', 'christmas', 'chrome', 'church', 'ci', 'cipriani', 'circle', 'cisco', 'citadel', 'citi', 'citic', 'city', 'cityeats', 'ck', 'cl', 'claims', 'cleaning', 'click', 'clinic', 'clinique', 'clothing', 'cloud', 'club', 'clubmed', 'cm', 'cn', 'co', 'coach', 'codes', 'coffee', 'college', 'cologne', 'com', 'comcast', 'commbank', 'community', 'company', 'compare', 'computer', 'comsec', 'condos', 'construction', 'consulting', 'contact', 'contractors', 'cooking', 'cookingchannel', 'cool', 'coop', 'corsica', 'country', 'coupon', 'coupons', 'courses', 'cpa', 'cr', 'credit', 'creditcard', 'creditunion', 'cricket', 'crown', 'crs', 'cruise', 'cruises', 'cu', 'cuisinella', 'cv', 'cw', 'cx', 'cy', 'cymru', 'cyou', 'cz', 'dabur', 'dad', 'dance', 'data', 'date', 'dating', 'datsun', 'day', 'dclk', 'dds', 'de', 'deal', 'dealer', 'deals', 'degree', 'delivery', 'dell', 'deloitte', 'delta', 'democrat', 'dental', 'dentist', 'desi', 'design', 'dev', 'dhl', 'diamonds', 'diet', 'digital', 'direct', 'directory', 'discount', 'discover', 'dish', 'diy', 'dj', 'dk', 'dm', 'dnp', 'do', 'docs', 'doctor', 'dog', 'domains', 'dot', 'download', 'drive', 'dtv', 'dubai', 'dunlop', 'dupont', 'durban', 'dvag', 'dvr', 'dz', 'earth', 'eat', 'ec', 'eco', 'edeka', 'edu', 'education', 'ee', 'eg', 'email', 'emerck', 'energy', 'engineer', 'engineering', 'enterprises', 'epson', 'equipment', 'er', 'ericsson', 'erni', 'es', 'esq', 'estate', 'et', 'etisalat', 'eu', 'eurovision', 'eus', 'events', 'exchange', 'expert', 'exposed', 'express', 'extraspace', 'fage', 'fail', 'fairwinds', 'faith', 'family', 'fan', 'fans', 'farm', 'farmers', 'fashion', 'fast', 'fedex', 'feedback', 'ferrari', 'ferrero', 'fi', 'fiat', 'fidelity', 'fido', 'film', 'final', 'finance', 'financial', 'fire', 'firestone', 'firmdale', 'fish', 'fishing', 'fit', 'fitness', 'fj', 'fk', 'flickr', 'flights', 'flir', 'florist', 'flowers', 'fly', 'fm', 'fo', 'foo', 'food', 'foodnetwork', 'football', 'ford', 'forex', 'forsale', 'forum', 'foundation', 'fox', 'fr', 'free', 'fresenius', 'frl', 'frogans', 'frontdoor', 'frontier', 'ftr', 'fujitsu', 'fun', 'fund', 'furniture', 'futbol', 'fyi', 'ga', 'gal', 'gallery', 'gallo', 'gallup', 'game', 'games', 'gap', 'garden', 'gay', 'gb', 'gbiz', 'gd', 'gdn', 'ge', 'gea', 'gent', 'genting', 'george', 'gf', 'gg', 'ggee', 'gh', 'gi', 'gift', 'gifts', 'gives', 'giving', 'gl', 'glass', 'gle', 'global', 'globo', 'gm', 'gmail', 'gmbh', 'gmo', 'gmx', 'gn', 'godaddy', 'gold', 'goldpoint', 'golf', 'goo', 'goodyear', 'goog', 'google', 'gop', 'got', 'gov', 'gp', 'gq', 'gr', 'grainger', 'graphics', 'gratis', 'green', 'gripe', 'grocery', 'group', 'gs', 'gt', 'gu', 'guardian', 'gucci', 'guge', 'guide', 'guitars', 'guru', 'gw', 'gy', 'hair', 'hamburg', 'hangout', 'haus', 'hbo', 'hdfc', 'hdfcbank', 'health', 'healthcare', 'help', 'helsinki', 'here', 'hermes', 'hgtv', 'hiphop', 'hisamitsu', 'hitachi', 'hiv', 'hk', 'hkt', 'hm', 'hn', 'hockey', 'holdings', 'holiday', 'homedepot', 'homegoods', 'homes', 'homesense', 'honda', 'horse', 'hospital', 'host', 'hosting', 'hot', 'hoteles', 'hotels', 'hotmail', 'house', 'how', 'hr', 'hsbc', 'ht', 'hu', 'hughes', 'hyatt', 'hyundai', 'ibm', 'icbc', 'ice', 'icu', 'id', 'ie', 'ieee', 'ifm', 'ikano', 'il', 'im', 'imamat', 'imdb', 'immo', 'immobilien', 'in', 'inc', 'industries', 'infiniti', 'info', 'ing', 'ink', 'institute', 'insurance', 'insure', 'int', 'international', 'intuit', 'investments', 'io', 'ipiranga', 'iq', 'ir', 'irish', 'is', 'ismaili', 'ist', 'istanbul', 'it', 'itau', 'itv', 'jaguar', 'java', 'jcb', 'je', 'jeep', 'jetzt', 'jewelry', 'jio', 'jll', 'jm', 'jmp', 'jnj', 'jo', 'jobs', 'joburg', 'jot', 'joy', 'jp', 'jpmorgan', 'jprs', 'juegos', 'juniper', 'kaufen', 'kddi', 'ke', 'kerryhotels', 'kerrylogistics', 'kerryproperties', 'kfh', 'kg', 'kh', 'ki', 'kia', 'kids', 'kim', 'kinder', 'kindle', 'kitchen', 'kiwi', 'km', 'kn', 'koeln', 'komatsu', 'kosher', 'kp', 'kpmg', 'kpn', 'kr', 'krd', 'kred', 'kuokgroup', 'kw', 'ky', 'kyoto', 'kz', 'la', 'lacaixa', 'lamborghini', 'lamer', 'lancaster', 'lancia', 'land', 'landrover', 'lanxess', 'lasalle', 'lat', 'latino', 'latrobe', 'law', 'lawyer', 'lb', 'lc', 'lds', 'lease', 'leclerc', 'lefrak', 'legal', 'lego', 'lexus', 'lgbt', 'li', 'lidl', 'life', 'lifeinsurance', 'lifestyle', 'lighting', 'like', 'lilly', 'limited', 'limo', 'lincoln', 'link', 'lipsy', 'live', 'living', 'lk', 'llc', 'llp', 'loan', 'loans', 'locker', 'locus', 'lol', 'london', 'lotte', 'lotto', 'love', 'lpl', 'lplfinancial', 'lr', 'ls', 'lt', 'ltd', 'ltda', 'lu', 'lundbeck', 'luxe', 'luxury', 'lv', 'ly', 'ma', 'madrid', 'maif', 'maison', 'makeup', 'man', 'management', 'mango', 'map', 'market', 'marketing', 'markets', 'marriott', 'marshalls', 'maserati', 'mattel', 'mba', 'mc', 'mckinsey', 'md', 'me', 'med', 'media', 'meet', 'melbourne', 'meme', 'memorial', 'men', 'menu', 'merckmsd', 'mg', 'mh', 'miami', 'microsoft', 'mil', 'mini', 'mint', 'mit', 'mitsubishi', 'mk', 'ml', 'mlb', 'mls', 'mm', 'mma', 'mn', 'mo', 'mobi', 'mobile', 'moda', 'moe', 'moi', 'mom', 'monash', 'money', 'monster', 'mormon', 'mortgage', 'moscow', 'moto', 'motorcycles', 'mov', 'movie', 'mp', 'mq', 'mr', 'ms', 'msd', 'mt', 'mtn', 'mtr', 'mu', 'museum', 'music', 'mutual', 'mv', 'mw', 'mx', 'my', 'mz', 'na', 'nab', 'nagoya', 'name', 'natura', 'navy', 'nba', 'nc', 'ne', 'nec', 'net', 'netbank', 'netflix', 'network', 'neustar', 'new', 'news', 'next', 'nextdirect', 'nexus', 'nf', 'nfl', 'ng', 'ngo', 'nhk', 'ni', 'nico', 'nike', 'nikon', 'ninja', 'nissan', 'nissay', 'nl', 'no', 'nokia', 'northwesternmutual', 'norton', 'now', 'nowruz', 'nowtv', 'np', 'nr', 'nra', 'nrw', 'ntt', 'nu', 'nyc', 'nz', 'obi', 'observer', 'office', 'okinawa', 'olayan', 'olayangroup', 'oldnavy', 'ollo', 'om', 'omega', 'one', 'ong', 'onl', 'online', 'ooo', 'open', 'oracle', 'orange', 'org', 'organic', 'origins', 'osaka', 'otsuka', 'ott', 'ovh', 'pa', 'page', 'panasonic', 'paris', 'pars', 'partners', 'parts', 'party', 'passagens', 'pay', 'pccw', 'pe', 'pet', 'pf', 'pfizer', 'pg', 'ph', 'pharmacy', 'phd', 'philips', 'phone', 'photo', 'photography', 'photos', 'physio', 'pics', 'pictet', 'pictures', 'pid', 'pin', 'ping', 'pink', 'pioneer', 'pizza', 'pk', 'pl', 'place', 'play', 'playstation', 'plumbing', 'plus', 'pm', 'pn', 'pnc', 'pohl', 'poker', 'politie', 'porn', 'post', 'pr', 'pramerica', 'praxi', 'press', 'prime', 'pro', 'prod', 'productions', 'prof', 'progressive', 'promo', 'properties', 'property', 'protection', 'pru', 'prudential', 'ps', 'pt', 'pub', 'pw', 'pwc', 'py', 'qa', 'qpon', 'quebec', 'quest', 'racing', 'radio', 're', 'read', 'realestate', 'realtor', 'realty', 'recipes', 'red', 'redstone', 'redumbrella', 'rehab', 'reise', 'reisen', 'reit', 'reliance', 'ren', 'rent', 'rentals', 'repair', 'report', 'republican', 'rest', 'restaurant', 'review', 'reviews', 'rexroth', 'rich', 'richardli', 'ricoh', 'ril', 'rio', 'rip', 'ro', 'rocher', 'rocks', 'rodeo', 'rogers', 'room', 'rs', 'rsvp', 'ru', 'rugby', 'ruhr', 'run', 'rw', 'rwe', 'ryukyu', 'sa', 'saarland', 'safe', 'safety', 'sakura', 'sale', 'salon', 'samsclub', 'samsung', 'sandvik', 'sandvikcoromant', 'sanofi', 'sap', 'sarl', 'sas', 'save', 'saxo', 'sb', 'sbi', 'sbs', 'sc', 'sca', 'scb', 'schaeffler', 'schmidt', 'scholarships', 'school', 'schule', 'schwarz', 'science', 'scot', 'sd', 'se', 'search', 'seat', 'secure', 'security', 'seek', 'select', 'sener', 'services', 'seven', 'sew', 'sex', 'sexy', 'sfr', 'sg', 'sh', 'shangrila', 'sharp', 'shaw', 'shell', 'shia', 'shiksha', 'shoes', 'shop', 'shopping', 'shouji', 'show', 'showtime', 'si', 'silk', 'sina', 'singles', 'site', 'sj', 'sk', 'ski', 'skin', 'sky', 'skype', 'sl', 'sling', 'sm', 'smart', 'smile', 'sn', 'sncf', 'so', 'soccer', 'social', 'softbank', 'software', 'sohu', 'solar', 'solutions', 'song', 'sony', 'soy', 'spa', 'space', 'sport', 'spot', 'sr', 'srl', 'ss', 'st', 'stada', 'staples', 'star', 'statebank', 'statefarm', 'stc', 'stcgroup', 'stockholm', 'storage', 'store', 'stream', 'studio', 'study', 'style', 'su', 'sucks', 'supplies', 'supply', 'support', 'surf', 'surgery', 'suzuki', 'sv', 'swatch', 'swiss', 'sx', 'sy', 'sydney', 'systems', 'sz', 'tab', 'taipei', 'talk', 'taobao', 'target', 'tatamotors', 'tatar', 'tattoo', 'tax', 'taxi', 'tc', 'tci', 'td', 'tdk', 'team', 'tech', 'technology', 'tel', 'temasek', 'tennis', 'teva', 'tf', 'tg', 'th', 'thd', 'theater', 'theatre', 'tiaa', 'tickets', 'tienda', 'tiffany', 'tips', 'tires', 'tirol', 'tj', 'tjmaxx', 'tjx', 'tk', 'tkmaxx', 'tl', 'tm', 'tmall', 'tn', 'to', 'today', 'tokyo', 'tools', 'top', 'toray', 'toshiba', 'total', 'tours', 'town', 'toyota', 'toys', 'tr', 'trade', 'trading', 'training', 'travel', 'travelchannel', 'travelers', 'travelersinsurance', 'trust', 'trv', 'tt', 'tube', 'tui', 'tunes', 'tushu', 'tv', 'tvs', 'tw', 'tz', 'ua', 'ubank', 'ubs', 'ug', 'uk', 'unicom', 'university', 'uno', 'uol', 'ups', 'us', 'uy', 'uz', 'va', 'vacations', 'vana', 'vanguard', 'vc', 've', 'vegas', 'ventures', 'verisign', 'versicherung', 'vet', 'vg', 'vi', 'viajes', 'video', 'vig', 'viking', 'villas', 'vin', 'vip', 'virgin', 'visa', 'vision', 'viva', 'vivo', 'vlaanderen', 'vn', 'vodka', 'volkswagen', 'volvo', 'vote', 'voting', 'voto', 'voyage', 'vu', 'vuelos', 'wales', 'walmart', 'walter', 'wang', 'wanggou', 'watch', 'watches', 'weather', 'weatherchannel', 'webcam', 'weber', 'website', 'wed', 'wedding', 'weibo', 'weir', 'wf', 'whoswho', 'wien', 'wiki', 'williamhill', 'win', 'windows', 'wine', 'winners', 'wme', 'wolterskluwer', 'woodside', 'work', 'works', 'world', 'wow', 'ws', 'wtc', 'wtf', 'xbox', 'xerox', 'xfinity', 'xihuan', 'xin', 'xn--11b4c3d', 'xn--1ck2e1b', 'xn--1qqw23a', 'xn--2scrj9c', 'xn--30rr7y', 'xn--3bst00m', 'xn--3ds443g', 'xn--3e0b707e', 'xn--3hcrj9c', 'xn--3pxu8k', 'xn--42c2d9a', 'xn--45br5cyl', 'xn--45brj9c', 'xn--45q11c', 'xn--4dbrk0ce', 'xn--4gbrim', 'xn--54b7fta0cc', 'xn--55qw42g', 'xn--55qx5d', 'xn--5su34j936bgsg', 'xn--5tzm5g', 'xn--6frz82g', 'xn--6qq986b3xl', 'xn--80adxhks', 'xn--80ao21a', 'xn--80aqecdr1a', 'xn--80asehdb', 'xn--80aswg', 'xn--8y0a063a', 'xn--90a3ac', 'xn--90ae', 'xn--90ais', 'xn--9dbq2a', 'xn--9et52u', 'xn--9krt00a', 'xn--b4w605ferd', 'xn--bck1b9a5dre4c', 'xn--c1avg', 'xn--c2br7g', 'xn--cck2b3b', 'xn--cckwcxetd', 'xn--cg4bki', 'xn--clchc0ea0b2g2a9gcd', 'xn--czr694b', 'xn--czrs0t', 'xn--czru2d', 'xn--d1acj3b', 'xn--d1alf', 'xn--e1a4c', 'xn--eckvdtc9d', 'xn--efvy88h', 'xn--fct429k', 'xn--fhbei', 'xn--fiq228c5hs', 'xn--fiq64b', 'xn--fiqs8s', 'xn--fiqz9s', 'xn--fjq720a', 'xn--flw351e', 'xn--fpcrj9c3d', 'xn--fzc2c9e2c', 'xn--fzys8d69uvgm', 'xn--g2xx48c', 'xn--gckr3f0f', 'xn--gecrj9c', 'xn--gk3at1e', 'xn--h2breg3eve', 'xn--h2brj9c', 'xn--h2brj9c8c', 'xn--hxt814e', 'xn--i1b6b1a6a2e', 'xn--imr513n', 'xn--io0a7i', 'xn--j1aef', 'xn--j1amh', 'xn--j6w193g', 'xn--jlq480n2rg', 'xn--jvr189m', 'xn--kcrx77d1x4a', 'xn--kprw13d', 'xn--kpry57d', 'xn--kput3i', 'xn--l1acc', 'xn--lgbbat1ad8j', 'xn--mgb9awbf', 'xn--mgba3a3ejt', 'xn--mgba3a4f16a', 'xn--mgba7c0bbn0a', 'xn--mgbaakc7dvf', 'xn--mgbaam7a8h', 'xn--mgbab2bd', 'xn--mgbah1a3hjkrd', 'xn--mgbai9azgqp6j', 'xn--mgbayh7gpa', 'xn--mgbbh1a', 'xn--mgbbh1a71e', 'xn--mgbc0a9azcg', 'xn--mgbca7dzdo', 'xn--mgbcpq6gpa1a', 'xn--mgberp4a5d4ar', 'xn--mgbgu82a', 'xn--mgbi4ecexp', 'xn--mgbpl2fh', 'xn--mgbt3dhd', 'xn--mgbtx2b', 'xn--mgbx4cd0ab', 'xn--mix891f', 'xn--mk1bu44c', 'xn--mxtq1m', 'xn--ngbc5azd', 'xn--ngbe9e0a', 'xn--ngbrx', 'xn--node', 'xn--nqv7f', 'xn--nqv7fs00ema', 'xn--nyqy26a', 'xn--o3cw4h', 'xn--ogbpf8fl', 'xn--otu796d', 'xn--p1acf', 'xn--p1ai', 'xn--pgbs0dh', 'xn--pssy2u', 'xn--q7ce6a', 'xn--q9jyb4c', 'xn--qcka1pmc', 'xn--qxa6a', 'xn--qxam', 'xn--rhqv96g', 'xn--rovu88b', 'xn--rvc1e0am3e', 'xn--s9brj9c', 'xn--ses554g', 'xn--t60b56a', 'xn--tckwe', 'xn--tiq49xqyj', 'xn--unup4y', 'xn--vermgensberater-ctb', 'xn--vermgensberatung-pwb', 'xn--vhquv', 'xn--vuq861b', 'xn--w4r85el8fhu5dnra', 'xn--w4rs40l', 'xn--wgbh1c', 'xn--wgbl6a', 'xn--xhq521b', 'xn--xkc2al3hye2a', 'xn--xkc2dl3a5ee0h', 'xn--y9a3aq', 'xn--yfro4i67o', 'xn--ygbi2ammx', 'xn--zfr164b', 'xxx', 'xyz', 'yachts', 'yahoo', 'yamaxun', 'yandex', 'ye', 'yodobashi', 'yoga', 'yokohama', 'you', 'youtube', 'yt', 'yun', 'za', 'zappos', 'zara', 'zero', 'zip', 'zm', 'zone', 'zuerich', 'zw', ''];
var resolver = /*#__PURE__*/new node_dns.Resolver();
resolver.setServers(['8.8.8.8']);
var dnsResolver = function dnsResolver(domain) {
return new Promise(function (resolve) {
resolver.resolveMx(domain, function (err, addresses) {
try {
if (err || !addresses || addresses.length === 0) {
console.trace(err);
resolve(false);
} else {
addresses.sort(function (a, b) {
return a.priority - b.priority;
});
var priorityRecord = addresses[0];
if (!priorityRecord.exchange) resolve(false);
resolver.resolve(priorityRecord.exchange, function (err) {
if (err) {
console.trace(err);
resolve(false);
} else {
resolve(true);
}
});
}
} catch (error) {
console.trace(error);
resolve(false);
}
});
});
};
/**
* This method validates email address
* @param {Object} contact
* @param {String} contact.email the email to be validated
* @return {boolean} {Promise<boolean>} a boolean value indicating if the email is valid or not
* @memberof Verymail
* @example
* const isValid = await validateEmail({
* email: 'user@example.com',
* })
*/
function validateEmail(_x) {
return _validateEmail.apply(this, arguments);
}
/**
* This method validates all supplied email addresses.
* @param {Array} mailingList array of email objects to be verified
* @returns {Array} object consisting of valid and invalid email addresses { valid: [], invalid: [] }
* @memberof Verymail
* @example
* const { data } = await validateEmailBulk(
* {
* email: 'user1@example.com',
* },
* {
* email: 'user2@example.com',
* },
* ])
*
*/
function _validateEmail() {
_validateEmail = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
var _email$match$length, _email$match;
var email, emailPattern, tld, atIndex, plusIndex, _email$split, username, domain;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
email = _ref.email;
if (email) {
_context.next = 3;
break;
}
return _context.abrupt("return", false);
case 3:
email = email.toLowerCase();
email = email.replace(/\s/g, '');
emailPattern = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
if (emailPattern.test(email)) {
_context.next = 8;
break;
}
return _context.abrupt("return", false);
case 8:
if (!(email && ((_email$match$length = (_email$match = email.match(/\./g)) == null ? void 0 : _email$match.length) != null ? _email$match$length : 0) > 3)) {
_context.next = 10;
break;
}
return _context.abrupt("return", false);
case 10:
/**
* Validate TLD
*/
tld = function tld(email) {
return email.split('@')[1].split('.').pop();
};
if (tlds.includes(tld(email))) {
_context.next = 13;
break;
}
return _context.abrupt("return", false);
case 13:
/**
* remove email modifier
*/
atIndex = email.indexOf('@');
plusIndex = email.indexOf('+');
if (plusIndex !== -1 && plusIndex < atIndex && "development" === 'production') {
email = email.slice(0, plusIndex) + email.slice(atIndex);
}
_email$split = email.split('@'), username = _email$split[0], domain = _email$split[1];
if (!(username.length < 3)) {
_context.next = 19;
break;
}
return _context.abrupt("return", false);
case 19:
if (!/^\d+$/.test(username)) {
_context.next = 21;
break;
}
return _context.abrupt("return", false);
case 21:
return _context.abrupt("return", dnsResolver(domain));
case 22:
case "end":
return _context.stop();
}
}, _callee);
}));
return _validateEmail.apply(this, arguments);
}
function validateEmailBulk(_x2) {
return _validateEmailBulk.apply(this, arguments);
}
function _validateEmailBulk() {
_validateEmailBulk = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(mailingList) {
var i, ValidEmailList, InValidEmailList;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
ValidEmailList = [];
InValidEmailList = [];
_context2.t0 = _regeneratorRuntime().keys(mailingList);
case 4:
if ((_context2.t1 = _context2.t0()).done) {
_context2.next = 16;
break;
}
i = _context2.t1.value;
if (!mailingList.hasOwnProperty(i)) {
_context2.next = 14;
break;
}
_context2.next = 9;
return validateEmail({
email: mailingList[i].email
});
case 9:
if (!_context2.sent) {
_context2.next = 13;
break;
}
ValidEmailList.push(mailingList[i]);
_context2.next = 14;
break;
case 13:
InValidEmailList.push(mailingList[i]);
case 14:
_context2.next = 4;
break;
case 16:
return _context2.abrupt("return", {
valid: ValidEmailList,
invalid: InValidEmailList
});
case 19:
_context2.prev = 19;
_context2.t2 = _context2["catch"](0);
return _context2.abrupt("return", {
data: []
});
case 22:
case "end":
return _context2.stop();
}
}, _callee2, null, [[0, 19]]);
}));
return _validateEmailBulk.apply(this, arguments);
}
/**
* The Cryptography class provides methods for encryption, decryption, signing, and verification of data using various cryptographic algorithms.
*
* @class Cryptography
*
* @example
* const cryptography = new Cryptography({
* keys: ['key1', 'key2', 'key3'],
* encryptKey: '',
* encryptKeySingle: '',
* })
*
* const encryptedData = cryptography.encrypt('Hello, World!')
* const decryptedData = cryptography.decrypt(encryptedData)
*
* const signature = cryptography.signature()
* const isVerified = cryptography.signatureVerify(signature)
*
* // creates a KrugerGold Token Address
* const address = cryptography.address()
*
* const encodedData = cryptography.base64Encode('Hello, World!')
* const decodedData = cryptography.base64Decode(encodedData)
* const isEncodedOrNot = cryptography.isBase64Encoded(encodedData)
*
* cryptography.get('strong_pw') // returns i=SQ_qa3W[<RxoM
* cryptography.random({ length: 20, useLowerCase: true, useUpperCase: true, useNumbers: true, useSpecial: true, useHex: false }) // returns *ajz:74,*ak0
*
*/
var Cryptography = /*#__PURE__*/function () {
/**
* Initializes a new instance of the Cryptography class.
* @param keys - An array of keys used for encryption and decryption.
*/
function Cryptography(options) {
var _this = this;
this.lowerCase = 'abcdefghijklmnopqrstuvwxyz';
this.upperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
this.numbers = '1234567890';
this.special = '`~!@#$%^&*()-=_+[]{}|;\\\':",./<>?';
this.hex = '123456789ABCDEF';
/**
* @method getKeys
* Generates random keys from the provided key array.
* @param count - The number of keys to generate. Defaults to 12.
* @returns An array of randomly generated keys.
*/
this.getKeys = function (count) {
var _count;
count = (_count = count) != null ? _count : 12;
var random = [];
for (var i = 0; i < count; i++) {
var randomIndex = Math.floor(Math.random() * _this.keys.length);
var randomWord = _this.keys[randomIndex];
// @ts-ignore
random.push(randomWord);
}
return random;
};
var keys = options.keys,
encryptKey = options.encryptKey,
encryptKeySingle = options.encryptKeySingle;
this.keys = keys || ["D5uBt7z18on1Z1I2", "fqIlGkitP9Ik7xmp", "tttiKz8PaaExA6gZ"];
this.KEYS = {
encryptKey: encryptKey != null ? encryptKey : process.env.ENCRYPTION_TWO_WAY_KEY,
encryptKeySingle: encryptKeySingle != null ? encryptKeySingle : process.env.ENCRYPTION_ONE_WAY_KEY
};
this.ALG = {
/**
* GCM is an authenticated encryption mode that
* not only provides confidentiality but also
* provides integrity in a secured way.
*/
NODE_CIPHER: 'aes-256-gcm',
/**
* 128 bit auth tag is recommended for GCM.
*/
AUTH_TAG_BYTE_LEN: 16,
/**
* NIST recommends 96 bits or 12 bytes IV for GCM
* to promote interoperability, efficiency, and
* simplicity of design.
*/
IV_BYTE_LEN: 12,
/**
* Note: 256 (in ALG name) is key size.
* NODE size for AES is always 128.
*/
KEY_BYTE_LEN: 32,
/**
* To prevent rainbow table attacks.
*/
SALT_BYTE_LEN: 16
};
}
var _proto = Cryptography.prototype;
_proto.randomizer = function randomizer() {
return crypto.randomBytes(1).readUInt8(0) / 255;
}
/**
* @method random
* The Random module class provides methods for generating random strings.
*
* @example
* cryptography.random({ length: 20, useLowerCase: true, useUpperCase: true, useNumbers: true, useSpecial: true, useHex: false }) // returns *ajz:74,*ak0
*
* // Decent Passwords - Good for nothing really, public accounts and other non-critical things.
* cryptography.get('decent_pw') // returns rXjdx36oro
*
* // Strong Passwords - Robust enough to keep your web hosting account secure.
* cryptography.get('strong_pw') // returns i=SQ_qa3W[<RxoM
*
* // Fort Knox Passwords - Secure enough for almost anything, like root or administrator passwords.
* cryptography.get('ft_knox_pw') // returns P}U%H\OOYAYb;wc"3hgI,3Lz[gd-z]
*
* // Encryption Keys - Can be used for any other 256-bit key requirement.
* cryptography.get('ci_key') // returns CeXHpM3nDgzdv0o3AkMCs3OuxzepLGW8
*
* // 160-bit WPA Key
* cryptography.get('160_wpa') // returns oHI#gR8z#h7BS>cZ!zH(
*
* // 504-bit WPA Key
* cryptography.get('504_wpa') // returns <os[g`s}u06jqt"Ea]t11,HsI[UipHD)%F";:9RhJ@kTU8GknLpMAXtoCzsJjT`
*
* // 64-bit WEP Keys
* cryptography.get('64_wep') // returns 8911B
*
* // 128-bit WEP Keys
* cryptography.get('128_wep') // returns 9F4E4F933BCCC
*
* // 152-bit WEP Keys
* cryptography.get('152_wep') // returns 695E1EE96E483961
*
* // 256-bit WEP Keys
* cryptography.get('256_wep') // returns AC7E866246BA6B71BF5D88A6861AB
*
*/;
_proto.random = function random(options) {
var _options$length = options.length,
length = _options$length === void 0 ? 32 : _options$length,
_options$useLowerCase = options.useLowerCase,
useLowerCase = _options$useLowerCase === void 0 ? true : _options$useLowerCase,
_options$useUpperCase = options.useUpperCase,
useUpperCase = _options$useUpperCase === void 0 ? true : _options$useUpperCase,
_options$useNumbers = options.useNumbers,
useNumbers = _options$useNumbers === void 0 ? true : _options$useNumbers,
_options$useSpecial = options.useSpecial,
useSpecial = _options$useSpecial === void 0 ? false : _options$useSpecial,
_options$useHex = options.useHex,
useHex = _options$useHex === void 0 ? false : _options$useHex;
var chars = '';
var key = '';
if (useLowerCase) chars += this.lowerCase;
if (useUpperCase) chars += this.upperCase;
if (useNumbers) chars += this.numbers;
if (useSpecial) chars += this.special;
if (useHex) chars += this.hex;
for (var i = 0; i < length; i++) {
key += chars[Math.floor(this.randomizer() * chars.length)];
}
return key;
}
/**
*
* @method get
* @param strength - The strength of the key to generate. decent_pw|strong_pw|ft_knox_pw|ci_key|160_wpa|504_wpa|64_wep|128_wep|152_wep|256_wep
*/;
_proto.get = function get(strength) {
switch (strength) {
case 'decent_pw':
return this.random({
length: 10,
useLowerCase: true,
useUpperCase: true,
useNumbers: true,
useSpecial: false,
useHex: false
});
case 'strong_pw':
return this.random({
length: 15,
useLowerCase: true,
useUpperCase: true,
useNumbers: true,
useSpecial: true,
useHex: false
});
case 'ft_knox_pw':
return this.random({
length: 30,
useLowerCase: true,
useUpperCase: true,
useNumbers: true,
useSpecial: true,
useHex: false
});
case 'ci_key':
return this.random({
length: 32,
useLowerCase: true,
useUpperCase: true,
useNumbers: true,
useSpecial: false,
useHex: false
});
case '160_wpa':
return this.random({
length: 20,
useLowerCase: true,
useUpperCase: true,
useNumbers: true,
useSpecial: true,
useHex: false
});
case '504_wpa':
return this.random({
length: 63,
useLowerCase: true,
useUpperCase: true,
useNumbers: true,
useSpecial: true,
useHex: false
});
case '64_wep':
return this.random({
length: 5,
useLowerCase: false,
useUpperCase: false,
useNumbers: false,
useSpecial: false,
useHex: true
});
case '128_wep':
return this.random({
length: 13,
useLowerCase: false,
useUpperCase: false,
useNumbers: false,
useSpecial: false,
useHex: true
});
case '152_wep':
return this.random({
length: 16,
useLowerCase: false,
useUpperCase: false,
useNumbers: false,
useSpecial: false,
useHex: true
});
case '256_wep':
return this.random({
length: 29,
useLowerCase: false,
useUpperCase: false,
useNumbers: false,
useSpecial: false,
useHex: true
});
default:
throw new Error("No such strength");
}
}
/**
* @method salt
* Generates a random salt value.
* @returns The generated salt value as a hexadecimal string.
*
* @example
* const salt = cryptography.salt()
* console.log(salt)
* // Output:
* // 5eb63bbbe01eeed093cb22bb8f5acdc3
*/;
_proto.salt = function salt() {
return crypto.randomBytes(this.ALG.SALT_BYTE_LEN).toString('hex');
}
/**
* @method iv
* Generates a random initialization vector (IV).
* @returns The generated IV as a Buffer.
*/;
_proto.iv = function iv() {
return crypto.randomBytes(this.ALG.AUTH_TAG_BYTE_LEN);
}
/**
* @method signature
* Generates a signature using the encryption keys.
* @returns The generated signature as a string.
*
* @example
* const signature = cryptography.signature()
* console.log(signature)
* // Output:
* // 6a3a4b5c6d7e8f9a
*/;
_proto.signature = function signature() {
return this.encrypt(this.getKeys(2).join(' '));
}
/**
* @method signatureVerify
* Verifies a signature against the encryption keys.
* @param signature - The signature to verify.
* @returns True if the signature is valid, false otherwise.
* @throws An error if the signature contains unknown identifiers.
*
* @example
* const signature = '6a3a4b5c6d7e8f9a'
* const isValid = cryptography.signatureVerify(signature)
* console.log(isValid)
* // Output:
* // true
*/;
_proto.signatureVerify = function signatureVerify(signature) {
var _this2 = this;
var signatures = this.decrypt(signature).split(' ');
if (signatures.every(function (value) {
return _this2.keys.includes(value);
})) {
return true;
} else {
throw "Unknown identifier";
}
}
/**
* @method address
* Generates a random crypto address.
* @returns The generated address as a string.
* @throws An error if an error occurs during address generation.
*
* @example
* const address = cryptography.address()
* console.log(address)
* // Output:
* // kK5HCVlAmmEnnlKh6wVX9TiJ6YGI7FCl
*/;
_proto.address = function address() {
try {
var _address = this.random({
length: this.ALG.KEY_BYTE_LEN - 1
});
return "k" + _address;
} catch (error) {
node_console.trace(error);
throw error;
}
}
/**
* @method encryptSingle
* Encrypts data one way using an encryption key.
* @param data - The data to encrypt.
* @returns The encrypted data as a base64-encoded string.
*
* @example
* const crypto = new Cryptography(['key1', 'key2', 'key3'], 'encryptKey', 'encryptKeySingle')
* const data = 'Hello, World!'
* const encryptedData = cryptography.encryptSingle(data)
* console.log(encryptedData)
* // Output:
* // 5eb63bbbe01eeed093cb22bb8f5acdc3
*/;
_proto.encryptSingle = function encryptSingle(data) {
try {
var signature = crypto.createHmac("sha256", this.KEYS.encryptKeySingle).update(data).digest("hex");
var b64Buffer = Buffer.from(signature);
return b64Buffer.toString("base64");
} catch (error) {
node_console.trace(error);
return Buffer.alloc(16);
}
}
/**
* @method encrypt
* Encrypts text two way using the encryption keys.
* @param text - The text to encrypt.
* @returns The encrypted text as a string.
* @throws An error if an error occurs during encryption.
*
* @example
* const text = 'Hello, World!'
* const encryptedText = cryptography.encrypt(text)
* console.log(encryptedText)
* // Output:
* // 6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a
*/;
_proto.encrypt = function encrypt(text) {
try {
var iv = crypto.randomBytes(this.ALG.AUTH_TAG_BYTE_LEN);
var cipher = crypto.createCipheriv(this.ALG.NODE_CIPHER, this.KEYS.encryptKey, iv);
var encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher["final"]('hex');
var tag = cipher.getAuthTag();
return iv.toString('hex') + ":" + encrypted + ":" + tag.toString('hex');
} catch (error) {
node_console.trace(error);
throw error;
}
}
/**
* @method decrypt
* Decrypts encrypted text using the encryption keys.
* @param encryptedText - The encrypted text to decrypt.
* @returns The decrypted text as a string.
* @throws An error if an error occurs during decryption.
*
* @example
* const encryptedText = '6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a:6a3a4b5c6d7e8f9a'
* const decryptedText = cryptography.decrypt(encryptedText)
* console.log(decryptedText)
* // Output:
* // Hello, World!
*/;
_proto.decrypt = function decrypt(encryptedText) {
try {
var _encryptedText$split = encryptedText.split(':'),
ivHex = _encryptedText$split[0],
encryptedHex = _encryptedText$split[1],
tagHex = _encryptedText$split[2];
var iv = Buffer.from(ivHex, 'hex');
var encrypted = Buffer.from(encryptedHex, 'hex');
var tag = Buffer.from(tagHex, 'hex');
var decipher = crypto.createDecipheriv(this.ALG.NODE_CIPHER, this.KEYS.encryptKey, iv);
decipher.setAuthTag(tag);
var decrypted = decipher.update(encrypted, undefined, 'utf8');
decrypted += decipher["final"]('utf8');
return decrypted;
} catch (error) {
node_console.trace(error);
throw error;
}
}
/**
* @method password
* Generates a password hash using the provided password and salt.
* @param password - The password to hash.
* @param salt - The salt value to use for hashing.
* @returns The hashed password as a hexadecimal string.
* @throws An error if an error occurs during password hashing.
*
* @example
* const password = 'myPassword'
* const salt = cryptography.salt()
* const hashedPassword = cryptography.password(password, salt)
* console.log(hashedPassword)
* // Output:
* // 5ebe2294ecd0e0f08eab7690d2a6ee69
*/;
_proto.password = function password(_password, salt) {
try {
var pbkdf = crypto.pbkdf2Sync(_password, salt, 10000, 256, "sha256");
return pbkdf.toString('hex');
} catch (error) {
node_console.trace(error);
throw error;
}
}
/**
* @method jwtIssue
* Issues a JSON Web Token (JWT) with the provided payload and expiry.
* @param payload - The payload to include in the JWT.
* @param expiry - The expiry time for the JWT.
* @returns The issued JWT as a string.
* @throws An error if an error occurs during JWT issuance.
*
* @example
* const payload = {
* sub: '1234567890',
* name: 'John Doe',
* iat: 1516239022
* }
*
* const expiry = '1h'
* const token = cryptography.jwtIssue(payload, expiry)
* console.log(token)
* // Output:
* // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
*/;
_proto.jwtIssue = function jwtIssue(payload, expiry) {
if (payload === void 0) {
payload = {};
}
try {
return jwt.sign(_extends({}, payload), this.KEYS.encryptKeySingle, {
expiresIn: expiry
});
} catch (error) {
node_console.trace(error);
throw error;
}
}
/**
* @method jwtVerify
* Verifies a JSON Web Token (JWT) and returns the decoded payload.
* @param token - The JWT to verify.
* @returns The decoded payload if the JWT is valid.
* @throws An error if the JWT is invalid or an error occurs during verification.
*
* @example
* const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
* const payload = cryptography.jwtVerify(token)
* console.log(payload)
* // Output:
* // {
* // sub: '1234567890',
* // name: 'John Doe',
* // iat: 1516239022
* // }
*/;
_proto.jwtVerify = function jwtVerify(token) {
try {
return jwt.verify(token, this.KEYS.encryptKeySingle);
} catch (error) {
node_console.trace(error);
throw error;
}
}
/**
* @method publicKey
* Generates a private key for asymmetric encryption.
* @returns The generated private key as a PEM-encoded string.
* @throws An error if an error occurs during private key generation.
*
* @example
* con