@trap_stevo/star-vault
Version:
Unleash the future of data management with the ultimate platform for secure, scalable, and dynamic data operations. Power the next generation of applications by combining advanced encryption, revolutionary real-time querying, and seamless synchronization
816 lines (814 loc) • 125 kB
JavaScript
"use strict";
var _excluded = ["password"],
_excluded2 = ["password"];
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { 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 define(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 value(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 reset(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 stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(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 abrupt(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 complete(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 finish(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 _catch(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 delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
var _require = require("@trap_stevo/encryped-lock"),
HUDLockManager = _require.HUDLockManager;
var useragent = require("useragent");
var fetch = require("node-fetch");
var crypto = require("crypto");
var _StarAuth_brand = /*#__PURE__*/new WeakSet();
var StarAuth = /*#__PURE__*/function () {
function StarAuth(vault) {
var _options$passwordRequ,
_this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, StarAuth);
_classPrivateMethodInitSpec(this, _StarAuth_brand);
this.vault = vault;
this.stellarCollection = options.stellarCollection || "stellar-auths";
this.sessionCollection = options.sessionCollection || "auth-sessions";
this.resetCollection = options.resetCollection || "auth-resets";
this.userCollection = options.collection || "auth-users";
this.lockoutDuration = options.lockoutDuration || 15 * 60 * 1000;
this.sessionPolicy = options.sessionPolicy || "default";
this.maxLoginAttempts = options.maxLoginAttempts || 5;
this.tokenExpiry = options.tokenExpiry || 3600;
this.allowGuestSessions = options.allowGuestSessions !== false;
this.guestInactivityThreshold = options.guestInactivityThreshold || 7 * 24 * 60 * 60 * 1000;
this.cleanupGuestInterval = options.cleanupGuestInterval || 5 * 60 * 1000;
this.guestActivityTrackers = options.guestActivityTrackers || [];
this.generateGuestID = typeof options.generateGuestID === "function" ? options.generateGuestID : function () {
return "guest-".concat(crypto.randomUUID());
};
this.generateStellarCode = options.generateStellarCode || function () {
return Math.floor(100000 + Math.random() * 900000).toString();
};
this.sessionValidationFields = options.sessionValidationFields || ["ip", "fingerprint"];
this.stellarRequestCooldown = options.stellarRequestCooldown || 60 * 1000;
this.strictSessionValidation = options.strictSessionValidation === true;
this.passwordRequirements = _objectSpread({
minLength: 8,
requireLetter: true,
requireNumber: true,
requireSymbol: false,
customValidator: null
}, (_options$passwordRequ = options.passwordRequirements) !== null && _options$passwordRequ !== void 0 ? _options$passwordRequ : {});
this.enableSuspiciousCheck = options.enableSuspiciousCheck !== false;
this.tagSession = options.tagSession || null;
this.enableGeoDebug = options.enableGeoDebug || false;
this.enableGeo = options.enableGeo || false;
var ipgeolocationKey = options.ipgeolocationKey || null;
var ipinfoToken = options.ipinfoToken || null;
var baseGeoServices = {
ipwhois: function () {
var _ipwhois = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(ip) {
var _data$connection, _data$connection2, _data$timezone, _data$flag, res, data;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return fetch("https://ipwho.is/".concat(ip));
case 3:
res = _context.sent;
_context.next = 6;
return res.json();
case 6:
data = _context.sent;
if (!(!res.ok || !data.success)) {
_context.next = 9;
break;
}
return _context.abrupt("return", null);
case 9:
return _context.abrupt("return", {
ip: data.ip,
city: data.city,
region: data.region,
country: data.country,
org: (_data$connection = data.connection) === null || _data$connection === void 0 ? void 0 : _data$connection.org,
isp: (_data$connection2 = data.connection) === null || _data$connection2 === void 0 ? void 0 : _data$connection2.isp,
loc: data.latitude && data.longitude ? "".concat(data.latitude, ",").concat(data.longitude) : null,
timezone: (_data$timezone = data.timezone) === null || _data$timezone === void 0 ? void 0 : _data$timezone.id,
postal: data.postal,
flag: (_data$flag = data.flag) === null || _data$flag === void 0 ? void 0 : _data$flag.emoji,
continent: data.continent
});
case 12:
_context.prev = 12;
_context.t0 = _context["catch"](0);
return _context.abrupt("return", null);
case 15:
case "end":
return _context.stop();
}
}, _callee, null, [[0, 12]]);
}));
function ipwhois(_x) {
return _ipwhois.apply(this, arguments);
}
return ipwhois;
}(),
ipapi: function () {
var _ipapi = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ip) {
var res, data;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return fetch("https://ipapi.co/".concat(ip, "/json/"));
case 3:
res = _context2.sent;
_context2.next = 6;
return res.json();
case 6:
data = _context2.sent;
if (!(!res.ok || data.error)) {
_context2.next = 9;
break;
}
return _context2.abrupt("return", null);
case 9:
return _context2.abrupt("return", {
ip: data.ip,
city: data.city,
region: data.region,
country: data.country_name,
org: data.org,
isp: data.org,
loc: "".concat(data.latitude, ",").concat(data.longitude),
timezone: data.timezone,
postal: data.postal,
flag: null,
continent: data.continent_code
});
case 12:
_context2.prev = 12;
_context2.t0 = _context2["catch"](0);
return _context2.abrupt("return", null);
case 15:
case "end":
return _context2.stop();
}
}, _callee2, null, [[0, 12]]);
}));
function ipapi(_x2) {
return _ipapi.apply(this, arguments);
}
return ipapi;
}()
};
if (ipinfoToken) {
baseGeoServices.ipinfo = /*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(ip) {
var _data$loc, res, data, _ref2, _ref3, lat, lon;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context3.prev = 0;
_context3.next = 3;
return fetch("https://ipinfo.io/".concat(ip, "?token=").concat(ipinfoToken));
case 3:
res = _context3.sent;
_context3.next = 6;
return res.json();
case 6:
data = _context3.sent;
if (!(!res.ok || data.error)) {
_context3.next = 9;
break;
}
return _context3.abrupt("return", null);
case 9:
_ref2 = ((_data$loc = data.loc) === null || _data$loc === void 0 ? void 0 : _data$loc.split(",")) || [null, null], _ref3 = _slicedToArray(_ref2, 2), lat = _ref3[0], lon = _ref3[1];
return _context3.abrupt("return", {
source: "ipinfo",
ip: data.ip,
city: data.city,
region: data.region,
country: data.country,
org: data.org,
isp: data.org,
loc: lat && lon ? "".concat(lat, ",").concat(lon) : null,
timezone: data.timezone,
postal: data.postal,
flag: null,
continent: null
});
case 13:
_context3.prev = 13;
_context3.t0 = _context3["catch"](0);
return _context3.abrupt("return", null);
case 16:
case "end":
return _context3.stop();
}
}, _callee3, null, [[0, 13]]);
}));
return function (_x3) {
return _ref.apply(this, arguments);
};
}();
}
if (ipgeolocationKey) {
baseGeoServices.ipgeolocation = /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(ip) {
var _data$time_zone, res, data;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
_context4.prev = 0;
_context4.next = 3;
return fetch("https://api.ipgeolocation.io/ipgeo?apiKey=".concat(ipgeolocationKey, "&ip=").concat(ip));
case 3:
res = _context4.sent;
_context4.next = 6;
return res.json();
case 6:
data = _context4.sent;
if (!(!res.ok || data.message)) {
_context4.next = 9;
break;
}
return _context4.abrupt("return", null);
case 9:
return _context4.abrupt("return", {
source: "ipgeolocation",
ip: data.ip,
city: data.city,
region: data.state_prov,
country: data.country_name,
org: data.organization,
isp: data.isp,
loc: "".concat(data.latitude, ",").concat(data.longitude),
timezone: (_data$time_zone = data.time_zone) === null || _data$time_zone === void 0 ? void 0 : _data$time_zone.name,
postal: data.zipcode,
flag: data.country_flag_emoji || null,
continent: data.continent_name
});
case 12:
_context4.prev = 12;
_context4.t0 = _context4["catch"](0);
return _context4.abrupt("return", null);
case 15:
case "end":
return _context4.stop();
}
}, _callee4, null, [[0, 12]]);
}));
return function (_x4) {
return _ref4.apply(this, arguments);
};
}();
}
var userGeoServices = Array.isArray(options.geoServices) ? options.geoServices : [];
this.geoServiceMap = _objectSpread({}, baseGeoServices);
this.geoServices = [].concat(_toConsumableArray(Object.values(this.geoServiceMap)), _toConsumableArray(userGeoServices));
this.onSuspiciousSession = options.onSuspiciousSession || null;
this.handleHijack = options.handleHijack || null;
this.onCleanup = options.onCleanup || null;
this.vaultID = options.vaultID || null;
this.locker = new HUDLockManager(options.lockingCombinations || 10);
if (options.autoCleanupInterval) {
setInterval(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
var result;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_context5.prev = 0;
_context5.next = 3;
return _this.cleanupExpiredTokens(options.cleanupExpiredTokensActionInfo, options.cleanupExpiredTokensClientAuth);
case 3:
result = _context5.sent;
if (typeof _this.onCleanup === "function") {
_this.onCleanup({
cleanupID: "expired-token",
result: result,
timestamp: Date.now(),
vaultID: _this.vaultID
});
}
_context5.next = 10;
break;
case 7:
_context5.prev = 7;
_context5.t0 = _context5["catch"](0);
console.warn("Error during StarAuth cleanup ~", _context5.t0.message);
case 10:
case "end":
return _context5.stop();
}
}, _callee5, null, [[0, 7]]);
})), options.autoCleanupInterval);
}
if (this.allowGuestSessions && this.cleanupGuestInterval) {
setInterval(function () {
_this.cleanupInactiveGuests();
}, this.cleanupGuestInterval);
}
_assertClassBrand(_StarAuth_brand, this, _registerGuestActivityTackers).call(this);
if (options.expiredSessionCleanupInterval) {
setInterval(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
var result;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
_context6.prev = 0;
_context6.next = 3;
return _this.cleanupExpiredSessions(options.cleanupExpiredSessionsActionInfo, options.cleanupExpiredSessionsClientAuth);
case 3:
result = _context6.sent;
if (typeof _this.onCleanup === "function") {
_this.onCleanup({
cleanupID: "expired-session",
result: result,
timestamp: Date.now(),
vaultID: _this.vaultID
});
}
_context6.next = 10;
break;
case 7:
_context6.prev = 7;
_context6.t0 = _context6["catch"](0);
console.warn("Error during StarAuth cleanup ~", _context6.t0.message);
case 10:
case "end":
return _context6.stop();
}
}, _callee6, null, [[0, 7]]);
})), options.expiredSessionCleanupInterval);
}
}
return _createClass(StarAuth, [{
key: "matchEmailFormat",
value: function matchEmailFormat(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
}, {
key: "matchPasswordStrength",
value: function matchPasswordStrength(password) {
if (typeof password !== "string") {
return false;
}
var _this$passwordRequire = this.passwordRequirements,
minLength = _this$passwordRequire.minLength,
requireLetter = _this$passwordRequire.requireLetter,
requireNumber = _this$passwordRequire.requireNumber,
requireSymbol = _this$passwordRequire.requireSymbol,
customValidator = _this$passwordRequire.customValidator;
if (password.length < minLength) {
return false;
}
if (requireLetter && !/[a-zA-Z]/.test(password)) {
return false;
}
if (requireNumber && !/[0-9]/.test(password)) {
return false;
}
if (requireSymbol && !/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
return false;
}
if (typeof customValidator === "function" && !customValidator(password)) {
return false;
}
return true;
}
}, {
key: "extractSessionMetadata",
value: function extractSessionMetadata(req) {
var _req$headers, _req$connection, _req$socket, _req$headers2, _agent$device, _req$headers3, _req$headers4, _req$headers5, _req$connection2, _req$headers6, _req$headers7, _req$headers8, _req$headers9;
var ip = (req === null || req === void 0 || (_req$headers = req.headers) === null || _req$headers === void 0 || (_req$headers = _req$headers["x-forwarded-for"]) === null || _req$headers === void 0 ? void 0 : _req$headers.split(",")[0]) || (req === null || req === void 0 || (_req$connection = req.connection) === null || _req$connection === void 0 ? void 0 : _req$connection.remoteAddress) || (req === null || req === void 0 || (_req$socket = req.socket) === null || _req$socket === void 0 ? void 0 : _req$socket.remoteAddress) || (req === null || req === void 0 ? void 0 : req.ip) || null;
var userAgentString = (req === null || req === void 0 || (_req$headers2 = req.headers) === null || _req$headers2 === void 0 ? void 0 : _req$headers2["user-agent"]) || "";
var agent = useragent.parse(userAgentString);
return {
ip: ip,
userAgent: userAgentString,
platform: agent.os.toString(),
browser: agent.toAgent(),
deviceType: ((_agent$device = agent.device) === null || _agent$device === void 0 ? void 0 : _agent$device.toString()) || null,
origin: (req === null || req === void 0 || (_req$headers3 = req.headers) === null || _req$headers3 === void 0 ? void 0 : _req$headers3["origin"]) || null,
referer: (req === null || req === void 0 || (_req$headers4 = req.headers) === null || _req$headers4 === void 0 ? void 0 : _req$headers4["referer"]) || null,
host: (req === null || req === void 0 || (_req$headers5 = req.headers) === null || _req$headers5 === void 0 ? void 0 : _req$headers5["host"]) || null,
protocol: (req === null || req === void 0 ? void 0 : req.protocol) || (req !== null && req !== void 0 && (_req$connection2 = req.connection) !== null && _req$connection2 !== void 0 && _req$connection2.encrypted ? "https" : "http"),
method: (req === null || req === void 0 ? void 0 : req.method) || null,
path: (req === null || req === void 0 ? void 0 : req.originalUrl) || (req === null || req === void 0 ? void 0 : req.url) || null,
acceptLanguage: (req === null || req === void 0 || (_req$headers6 = req.headers) === null || _req$headers6 === void 0 ? void 0 : _req$headers6["accept-language"]) || null,
encoding: (req === null || req === void 0 || (_req$headers7 = req.headers) === null || _req$headers7 === void 0 ? void 0 : _req$headers7["accept-encoding"]) || null,
fingerprint: (req === null || req === void 0 || (_req$headers8 = req.headers) === null || _req$headers8 === void 0 ? void 0 : _req$headers8["x-client-fingerprint"]) || (req === null || req === void 0 || (_req$headers9 = req.headers) === null || _req$headers9 === void 0 ? void 0 : _req$headers9["x-device-id"]) || null
};
}
}, {
key: "throwError",
value: function throwError(code, message) {
var error = new Error(message);
error.code = code;
throw error;
}
}, {
key: "lookupGeo",
value: function () {
var _lookupGeo = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(ip) {
var _i, _Object$entries, _Object$entries$_i, name, fn, data, _iterator, _step, _fn, _data;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
_i = 0, _Object$entries = Object.entries(this.geoServiceMap);
case 1:
if (!(_i < _Object$entries.length)) {
_context7.next = 18;
break;
}
_Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), name = _Object$entries$_i[0], fn = _Object$entries$_i[1];
_context7.prev = 3;
_context7.next = 6;
return fn(ip);
case 6:
data = _context7.sent;
if (!data) {
_context7.next = 10;
break;
}
if (this.enableGeoDebug) {
console.log("[Star Auth | Geo Success] ".concat(name));
}
return _context7.abrupt("return", data);
case 10:
_context7.next = 15;
break;
case 12:
_context7.prev = 12;
_context7.t0 = _context7["catch"](3);
if (this.enableGeoDebug) {
console.warn("[Star Auth | Geo Error] ".concat(name), _context7.t0.message);
}
case 15:
_i++;
_context7.next = 1;
break;
case 18:
_iterator = _createForOfIteratorHelper(this.geoServices.slice(Object.keys(this.geoServiceMap).length));
_context7.prev = 19;
_iterator.s();
case 21:
if ((_step = _iterator.n()).done) {
_context7.next = 35;
break;
}
_fn = _step.value;
_context7.prev = 23;
_context7.next = 26;
return _fn(ip);
case 26:
_data = _context7.sent;
if (!_data) {
_context7.next = 29;
break;
}
return _context7.abrupt("return", _data);
case 29:
_context7.next = 33;
break;
case 31:
_context7.prev = 31;
_context7.t1 = _context7["catch"](23);
case 33:
_context7.next = 21;
break;
case 35:
_context7.next = 40;
break;
case 37:
_context7.prev = 37;
_context7.t2 = _context7["catch"](19);
_iterator.e(_context7.t2);
case 40:
_context7.prev = 40;
_iterator.f();
return _context7.finish(40);
case 43:
return _context7.abrupt("return", null);
case 44:
case "end":
return _context7.stop();
}
}, _callee7, this, [[3, 12], [19, 37, 40, 43], [23, 31]]);
}));
function lookupGeo(_x5) {
return _lookupGeo.apply(this, arguments);
}
return lookupGeo;
}()
}, {
key: "registerGuest",
value: function () {
var _registerGuest = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
var req,
metadata,
actionInfo,
clientAuth,
now,
accountID,
attempt,
guestID,
existing,
guestUser,
session,
_args8 = arguments;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
req = _args8.length > 0 && _args8[0] !== undefined ? _args8[0] : {};
metadata = _args8.length > 1 && _args8[1] !== undefined ? _args8[1] : {};
actionInfo = _args8.length > 2 && _args8[2] !== undefined ? _args8[2] : {};
clientAuth = _args8.length > 3 && _args8[3] !== undefined ? _args8[3] : null;
if (!this.allowGuestSessions) {
this.throwError("GUEST_SESSIONS_DISABLED", "Guest sessions not permitted.");
}
now = Date.now();
accountID = crypto.randomUUID();
attempt = 0;
case 8:
if (attempt++ > 100) {
this.throwError("GUEST_ID_CONFLICT", "Could not generate a unique guest ID.");
}
guestID = this.generateGuestID();
existing = this.vault.query(this.userCollection).where({
guestID: guestID
}).limit(1).execute()[0];
if (existing) {
_context8.next = 13;
break;
}
return _context8.abrupt("break", 14);
case 13:
if (true) {
_context8.next = 8;
break;
}
case 14:
_context8.next = 16;
return this.vault.create(this.userCollection, {
email: null,
password: null,
type: "guest",
createdAt: now,
metadata: metadata || {},
accountID: accountID,
guestID: guestID
}, actionInfo, clientAuth);
case 16:
guestUser = _context8.sent;
_context8.next = 19;
return _assertClassBrand(_StarAuth_brand, this, _createSession).call(this, guestUser, req, actionInfo, clientAuth);
case 19:
session = _context8.sent;
return _context8.abrupt("return", _objectSpread(_objectSpread({}, session), {}, {
id: guestUser.id,
accountID: accountID,
guestID: guestID
}));
case 21:
case "end":
return _context8.stop();
}
}, _callee8, this);
}));
function registerGuest() {
return _registerGuest.apply(this, arguments);
}
return registerGuest;
}()
}, {
key: "register",
value: function () {
var _register = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(email, password) {
var actionInfo,
clientAuth,
normalized,
existing,
hash,
accountID,
_args9 = arguments;
return _regeneratorRuntime().wrap(function _callee9$(_context9) {
while (1) switch (_context9.prev = _context9.next) {
case 0:
actionInfo = _args9.length > 2 && _args9[2] !== undefined ? _args9[2] : {};
clientAuth = _args9.length > 3 && _args9[3] !== undefined ? _args9[3] : null;
normalized = email.trim().toLowerCase();
if (!this.matchEmailFormat(normalized)) {
this.throwError("INVALID_EMAIL", "Invalid email format.");
}
if (!this.matchPasswordStrength(password)) {
this.throwError("WEAK_PASSWORD", "Password must contain letters and numbers.");
}
existing = this.vault.query(this.userCollection).where({
email: normalized
}).limit(1).execute();
if (existing.length > 0) {
this.throwError("EMAIL_EXISTS", "Email \"".concat(normalized, "\" already exists."));
}
_context9.next = 9;
return this.locker.hashPassword(password);
case 9:
hash = _context9.sent;
accountID = crypto.randomUUID();
return _context9.abrupt("return", this.vault.create(this.userCollection, {
email: normalized,
password: hash,
createdAt: Date.now(),
type: "user",
metadata: {},
accountID: accountID
}, actionInfo, clientAuth));
case 12:
case "end":
return _context9.stop();
}
}, _callee9, this);
}));
function register(_x6, _x7) {
return _register.apply(this, arguments);
}
return register;
}()
}, {
key: "upgradeGuestAccount",
value: function () {
var _upgradeGuestAccount = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(accountID, email, password) {
var _user$data;
var actionInfo,
clientAuth,
user,
now,
hashedPassword,
updatedFields,
_args10 = arguments;
return _regeneratorRuntime().wrap(function _callee10$(_context10) {
while (1) switch (_context10.prev = _context10.next) {
case 0:
actionInfo = _args10.length > 3 && _args10[3] !== undefined ? _args10[3] : {};
clientAuth = _args10.length > 4 && _args10[4] !== undefined ? _args10[4] : null;
user = this.vault.query(this.userCollection).where({
accountID: accountID,
type: "guest"
}).limit(1).execute()[0];
if (!user || (_user$data = user.data) !== null && _user$data !== void 0 && _user$data.accountDeleted) {
this.throwError("GUEST_NOT_FOUND", "Guest account not found.");
}
_assertClassBrand(_StarAuth_brand, this, _assertAccountAvailability).call(this, user);
now = Date.now();
_context10.next = 8;
return this.locker.hashPassword(password);
case 8:
hashedPassword = _context10.sent;
updatedFields = {
email: email,
password: hashedPassword,
upgradedAt: now,
type: "user",
guestID: undefined
};
_context10.next = 12;
return this.vault.update(this.userCollection, user.id, _objectSpread(_objectSpread({}, user.data), updatedFields), actionInfo, clientAuth);
case 12:
if (typeof this.vault.emit === "function") {
this.vault.emit("guest:upgraded", {
userID: user.id,
accountID: user.data.accountID,
email: email,
upgradedAt: now
});
}
return _context10.abrupt("return", {
userID: user.id,
accountID: user.data.accountID,
email: email,
upgradedAt: now
});
case 14:
case "end":
return _context10.stop();
}
}, _callee10, this);
}));
function upgradeGuestAccount(_x8, _x9, _x10) {
return _upgradeGuestAccount.apply(this, arguments);
}
return upgradeGuestAccount;
}()
}, {
key: "loginGuest",
value: function () {
var _loginGuest = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(accountID) {
var _guestUser$data;
var req,
actionInfo,
clientAuth,
guestUser,
now,
activeSession,
_args11 = arguments;
return _regeneratorRuntime().wrap(function _callee11$(_context11) {
while (1) switch (_context11.prev = _context11.next) {
case 0:
req = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : {};
actionInfo = _args11.length > 2 && _args11[2] !== undefined ? _args11[2] : {};
clientAuth = _args11.length > 3 && _args11[3] !== undefined ? _args11[3] : null;
if (!this.allowGuestSessions) {
this.throwError("GUEST_SESSIONS_DISABLED", "Guest sessions not permitted.");
}
guestUser = this.vault.query(this.userCollection).where({
accountID: accountID,
type: "guest"
}).limit(1).execute()[0];
if (!guestUser || (_guestUser$data = guestUser.data) !== null && _guestUser$data !== void 0 && _guestUser$data.accountDeleted) {
this.throwError("GUEST_NOT_FOUND", "Guest account not found or deleted.");
}
_assertClassBrand(_StarAuth_brand, this, _assertAccountAvailability).call(this, guestUser);
now = Date.now();
activeSession = this.vault.query(this.sessionCollection).where({
userID: guestUser.id,
active: true
}).filterBy(function (r) {
return r.expiresAt > now;
}).limit(1).execute(true)[0];
if (this.sessionPolicy === "strict" && activeSession) {
this.throwError("ALREADY_LOGGED_IN", "Guest already in an active session.");
}
if (!(this.sessionPolicy === "replace" && activeSession)) {
_context11.next = 13;
break;
}
_context11.next = 13;
return this.deactivateOtherSessions(guestUser.id, null, actionInfo, clientAuth);
case 13:
_context11.next = 15;
return _assertClassBrand(_StarAuth_brand, this, _createSession).call(this, guestUser, req, actionInfo, clientAuth);
case 15:
return _context11.abrupt("return", _context11.sent);
case 16:
case "end":
return _context11.stop();
}
}, _callee11, this);
}));
function loginGuest(_x11) {
return _loginGuest.apply(this, arguments);
}
return loginGuest;
}()
}, {
key: "login",
value: function () {
var _login = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(email, password) {
var req,
actionInfo,
clientAuth,
user,
now,
match,
failed,
lockUntil,
_args12 = arguments;
return _regeneratorRuntime().wrap(function _callee12$(_context12) {
while (1) switch (_context12.prev = _context12.next) {
case 0:
req = _args12.length > 2 && _args12[2] !== undefined ? _args12[2] : {};
actionInfo = _args12.length > 3 && _args12[3] !== undefined ? _args12[3] : {};
clientAuth = _args12.length > 4 && _args12[4] !== undefined ? _args12[4] : null;
user = this.vault.query(this.userCollection).where({
email: email
}).limit(1).execute()[0];
if (!user) {
this.throwError("USER_NOT_FOUND", "User not found.");
}
_assertClassBrand(_StarAuth_brand, this, _assertAccountAvailability).call(this, user);
now = Date.now();
if (user.data.lockUntil && now < user.data.lockUntil) {
this.throwError("ACCOUNT_LOCKED", "Account locked. Try again later.");
}
_context12.next = 10;
return this.locker.verifyPassword(password, user.data.password);
case 10:
match = _context12.sent;
if (match) {