@trap_stevo/star-vault
Version:
Deterministic data engine that eliminates query-time joins and enables normalized data execution. Architect secure, scalable, real-time systems with integrated sharding, encryption, and event-driven data flows. Manage hierarchical structures, execute adva
659 lines (658 loc) • 169 kB
JavaScript
"use strict";
var _excluded = ["password"],
_excluded2 = ["password"];
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 _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 _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 _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 _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 _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 _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 _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
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 GeoTide = require("@trap_stevo/geotide");
var useragent = require("useragent");
var crypto = require("crypto");
var _guestTrackerCleanups = /*#__PURE__*/new WeakMap();
var _geoDebugCleanups = /*#__PURE__*/new WeakMap();
var _timers = /*#__PURE__*/new WeakMap();
var _disposed = /*#__PURE__*/new WeakMap();
var _StarAuth_brand = /*#__PURE__*/new WeakSet();
var StarAuth = /*#__PURE__*/function () {
function StarAuth(vault) {
var _options$passwordRequ,
_options$lockout,
_options$lockout2,
_options$lockout$maxA,
_options$lockout3,
_options$lockout$base,
_options$lockout4,
_options$lockout$maxD,
_options$lockout5,
_options$lockout$jitt,
_options$lockout6,
_options$lockout$deca,
_options$lockout7,
_options$lockout$wind,
_options$lockout8,
_options$lockout$wind2,
_options$lockout9,
_options$lockout$capt,
_options$lockout10,
_options$lockout$otpA,
_options$lockout11,
_options$lockout12,
_options$lockout13,
_options$lockout14,
_options$lockout15,
_options$lockout16,
_options$lockout17,
_options$lockout18,
_options$lockout$timi,
_options$lockout19,
_options$lockout$timi2,
_options$lockout20,
_options$lockout$timi3,
_options$lockout21,
_options$lockout$timi4,
_options$lockout22,
_options$lockout$timi5,
_options$lockout23,
_options$lockout$timi6,
_options$lockout24,
_options$lockout$timi7,
_options$lockout25,
_options$lockout$timi8,
_options$lockout26,
_options$lockout$timi9,
_options$lockout27,
_options$lockout$timi10,
_options$lockout28,
_options$lockout$timi11,
_options$lockout29,
_options$lockout$timi12,
_options$lockout30,
_this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, StarAuth);
_classPrivateMethodInitSpec(this, _StarAuth_brand);
_classPrivateFieldInitSpec(this, _guestTrackerCleanups, new Set());
_classPrivateFieldInitSpec(this, _geoDebugCleanups, new Set());
_classPrivateFieldInitSpec(this, _timers, new Set());
_classPrivateFieldInitSpec(this, _disposed, false);
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.enableReverseGeo = options.enableReverseGeo || false;
this.enableGeoDebug = options.enableGeoDebug || false;
this.enableGeo = options.enableGeo || false;
this.starLocator = new GeoTide({
enableDebug: this.enableGeoDebug,
ipinfoToken: options.ipinfoToken || null,
ipgeolocationKey: options.ipgeolocationKey || null,
nominatimUserAgent: options.nominatimUserAgent || "StarAuth/1.0 (star-vault@sclpowerful.com)",
googleMapsKey: options.googleMapsKey || null,
mapboxToken: options.mapboxToken || null,
cacheTtlMs: options.geoCacheTtlMs || 10 * 60 * 1000,
deadlineMs: options.geoDeadlineMs || 3000,
timeoutMs: options.geoTimeoutMs || 2500,
scoreOk: options.geoScoreOk || 5,
maxConcurrency: options.geoMaxConcurrency || 8
});
var extraGeoProviders = options.geoProviders || options.geoServices || [];
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);
this.lockCollection = options.lockCollection || "auth-locks";
this.lockout = {
strategy: ((_options$lockout = options.lockout) === null || _options$lockout === void 0 ? void 0 : _options$lockout.strategy) || "fixed",
scopes: ((_options$lockout2 = options.lockout) === null || _options$lockout2 === void 0 ? void 0 : _options$lockout2.scopes) || ["account", "ipua"],
maxAttempts: (_options$lockout$maxA = (_options$lockout3 = options.lockout) === null || _options$lockout3 === void 0 ? void 0 : _options$lockout3.maxAttempts) !== null && _options$lockout$maxA !== void 0 ? _options$lockout$maxA : 5,
baseDuration: (_options$lockout$base = (_options$lockout4 = options.lockout) === null || _options$lockout4 === void 0 ? void 0 : _options$lockout4.baseDuration) !== null && _options$lockout$base !== void 0 ? _options$lockout$base : 15 * 60 * 1000,
maxDuration: (_options$lockout$maxD = (_options$lockout5 = options.lockout) === null || _options$lockout5 === void 0 ? void 0 : _options$lockout5.maxDuration) !== null && _options$lockout$maxD !== void 0 ? _options$lockout$maxD : 24 * 60 * 60 * 1000,
jitterDuration: (_options$lockout$jitt = (_options$lockout6 = options.lockout) === null || _options$lockout6 === void 0 ? void 0 : _options$lockout6.jitterDuration) !== null && _options$lockout$jitt !== void 0 ? _options$lockout$jitt : 15 * 1000,
decayDuration: (_options$lockout$deca = (_options$lockout7 = options.lockout) === null || _options$lockout7 === void 0 ? void 0 : _options$lockout7.decayDuration) !== null && _options$lockout$deca !== void 0 ? _options$lockout$deca : 30 * 60 * 1000,
windowDuration: (_options$lockout$wind = (_options$lockout8 = options.lockout) === null || _options$lockout8 === void 0 ? void 0 : _options$lockout8.windowDuration) !== null && _options$lockout$wind !== void 0 ? _options$lockout$wind : 10 * 60 * 1000,
windowThreshold: (_options$lockout$wind2 = (_options$lockout9 = options.lockout) === null || _options$lockout9 === void 0 ? void 0 : _options$lockout9.windowThreshold) !== null && _options$lockout$wind2 !== void 0 ? _options$lockout$wind2 : 7,
captchaAfter: (_options$lockout$capt = (_options$lockout10 = options.lockout) === null || _options$lockout10 === void 0 ? void 0 : _options$lockout10.captchaAfter) !== null && _options$lockout$capt !== void 0 ? _options$lockout$capt : null,
otpAfter: (_options$lockout$otpA = (_options$lockout11 = options.lockout) === null || _options$lockout11 === void 0 ? void 0 : _options$lockout11.otpAfter) !== null && _options$lockout$otpA !== void 0 ? _options$lockout$otpA : null,
captchaVerifier: ((_options$lockout12 = options.lockout) === null || _options$lockout12 === void 0 ? void 0 : _options$lockout12.captchaVerifier) || null,
otpVerifier: ((_options$lockout13 = options.lockout) === null || _options$lockout13 === void 0 ? void 0 : _options$lockout13.otpVerifier) || null,
onLock: ((_options$lockout14 = options.lockout) === null || _options$lockout14 === void 0 ? void 0 : _options$lockout14.onLock) || null,
onUnlock: ((_options$lockout15 = options.lockout) === null || _options$lockout15 === void 0 ? void 0 : _options$lockout15.onUnlock) || null,
onChallenge: ((_options$lockout16 = options.lockout) === null || _options$lockout16 === void 0 ? void 0 : _options$lockout16.onChallenge) || null,
notifyLock: ((_options$lockout17 = options.lockout) === null || _options$lockout17 === void 0 ? void 0 : _options$lockout17.notifyLock) || null,
bypassed: ((_options$lockout18 = options.lockout) === null || _options$lockout18 === void 0 ? void 0 : _options$lockout18.bypassed) || null,
timingHeuristics: {
enabled: (_options$lockout$timi = (_options$lockout19 = options.lockout) === null || _options$lockout19 === void 0 || (_options$lockout19 = _options$lockout19.timingHeuristics) === null || _options$lockout19 === void 0 ? void 0 : _options$lockout19.enabled) !== null && _options$lockout$timi !== void 0 ? _options$lockout$timi : true,
burstDetectionDuration: (_options$lockout$timi2 = (_options$lockout20 = options.lockout) === null || _options$lockout20 === void 0 || (_options$lockout20 = _options$lockout20.timingHeuristics) === null || _options$lockout20 === void 0 ? void 0 : _options$lockout20.burstDetectionDuration) !== null && _options$lockout$timi2 !== void 0 ? _options$lockout$timi2 : 3000,
humanDetectionDuration: (_options$lockout$timi3 = (_options$lockout21 = options.lockout) === null || _options$lockout21 === void 0 || (_options$lockout21 = _options$lockout21.timingHeuristics) === null || _options$lockout21 === void 0 ? void 0 : _options$lockout21.humanDetectionDuration) !== null && _options$lockout$timi3 !== void 0 ? _options$lockout$timi3 : 45000,
maxConsiderDuration: (_options$lockout$timi4 = (_options$lockout22 = options.lockout) === null || _options$lockout22 === void 0 || (_options$lockout22 = _options$lockout22.timingHeuristics) === null || _options$lockout22 === void 0 ? void 0 : _options$lockout22.maxConsiderDuration) !== null && _options$lockout$timi4 !== void 0 ? _options$lockout$timi4 : 10 * 60 * 1000,
burstWeight: (_options$lockout$timi5 = (_options$lockout23 = options.lockout) === null || _options$lockout23 === void 0 || (_options$lockout23 = _options$lockout23.timingHeuristics) === null || _options$lockout23 === void 0 ? void 0 : _options$lockout23.burstWeight) !== null && _options$lockout$timi5 !== void 0 ? _options$lockout$timi5 : 2.0,
normalWeight: (_options$lockout$timi6 = (_options$lockout24 = options.lockout) === null || _options$lockout24 === void 0 || (_options$lockout24 = _options$lockout24.timingHeuristics) === null || _options$lockout24 === void 0 ? void 0 : _options$lockout24.normalWeight) !== null && _options$lockout$timi6 !== void 0 ? _options$lockout$timi6 : 1.0,
graceWeight: (_options$lockout$timi7 = (_options$lockout25 = options.lockout) === null || _options$lockout25 === void 0 || (_options$lockout25 = _options$lockout25.timingHeuristics) === null || _options$lockout25 === void 0 ? void 0 : _options$lockout25.graceWeight) !== null && _options$lockout$timi7 !== void 0 ? _options$lockout$timi7 : 0.0,
emaAlpha: (_options$lockout$timi8 = (_options$lockout26 = options.lockout) === null || _options$lockout26 === void 0 || (_options$lockout26 = _options$lockout26.timingHeuristics) === null || _options$lockout26 === void 0 ? void 0 : _options$lockout26.emaAlpha) !== null && _options$lockout$timi8 !== void 0 ? _options$lockout$timi8 : 0.3,
decayOnGrace: (_options$lockout$timi9 = (_options$lockout27 = options.lockout) === null || _options$lockout27 === void 0 || (_options$lockout27 = _options$lockout27.timingHeuristics) === null || _options$lockout27 === void 0 ? void 0 : _options$lockout27.decayOnGrace) !== null && _options$lockout$timi9 !== void 0 ? _options$lockout$timi9 : true,
decayStep: (_options$lockout$timi10 = (_options$lockout28 = options.lockout) === null || _options$lockout28 === void 0 || (_options$lockout28 = _options$lockout28.timingHeuristics) === null || _options$lockout28 === void 0 ? void 0 : _options$lockout28.decayStep) !== null && _options$lockout$timi10 !== void 0 ? _options$lockout$timi10 : 1,
minFailures: (_options$lockout$timi11 = (_options$lockout29 = options.lockout) === null || _options$lockout29 === void 0 || (_options$lockout29 = _options$lockout29.timingHeuristics) === null || _options$lockout29 === void 0 ? void 0 : _options$lockout29.minFailures) !== null && _options$lockout$timi11 !== void 0 ? _options$lockout$timi11 : 0,
maxFailures: (_options$lockout$timi12 = (_options$lockout30 = options.lockout) === null || _options$lockout30 === void 0 || (_options$lockout30 = _options$lockout30.timingHeuristics) === null || _options$lockout30 === void 0 ? void 0 : _options$lockout30.maxFailures) !== null && _options$lockout$timi12 !== void 0 ? _options$lockout$timi12 : 9999
}
};
this.detachedTimers = (options === null || options === void 0 ? void 0 : options.detachedTimers) !== false;
if (options.autoCleanupInterval) {
_assertClassBrand(_StarAuth_brand, this, _setIntervalTracked).call(this, /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var result;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return _this.cleanupExpiredTokens(options.cleanupExpiredTokensActionInfo, options.cleanupExpiredTokensClientAuth);
case 3:
result = _context.sent;
if (typeof _this.onCleanup === "function") {
_this.onCleanup({
cleanupID: "expired-token",
result: result,
timestamp: Date.now(),
vaultID: _this.vaultID
});
}
_context.next = 10;
break;
case 7:
_context.prev = 7;
_context.t0 = _context["catch"](0);
console.warn("Error during StarAuth cleanup ~", _context.t0.message);
case 10:
case "end":
return _context.stop();
}
}, _callee, null, [[0, 7]]);
})), options.autoCleanupInterval, {
unref: this.detachedTimers
});
}
if (this.allowGuestSessions && this.cleanupGuestInterval) {
_assertClassBrand(_StarAuth_brand, this, _setIntervalTracked).call(this, function () {
_this.cleanupInactiveGuests();
}, this.cleanupGuestInterval, {
unref: this.detachedTimers
});
}
_assertClassBrand(_StarAuth_brand, this, _registerGuestActivityTrackers).call(this);
if (options.expiredSessionCleanupInterval) {
_assertClassBrand(_StarAuth_brand, this, _setIntervalTracked).call(this, /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var result;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return _this.cleanupExpiredSessions(options.cleanupExpiredSessionsActionInfo, options.cleanupExpiredSessionsClientAuth);
case 3:
result = _context2.sent;
if (typeof _this.onCleanup === "function") {
_this.onCleanup({
cleanupID: "expired-session",
result: result,
timestamp: Date.now(),
vaultID: _this.vaultID
});
}
_context2.next = 10;
break;
case 7:
_context2.prev = 7;
_context2.t0 = _context2["catch"](0);
console.warn("Error during StarAuth cleanup ~", _context2.t0.message);
case 10:
case "end":
return _context2.stop();
}
}, _callee2, null, [[0, 7]]);
})), options.expiredSessionCleanupInterval, {
unref: this.detachedTimers
});
}
if (Array.isArray(extraGeoProviders)) {
var _loop = function _loop() {
var svc = extraGeoProviders[i];
if (typeof svc === "function") {
var name = svc.name || "custom_".concat(i);
_this.starLocator.register(name, /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(ip, _ref3) {
var signal, r;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
signal = _ref3.signal;
_context3.next = 3;
return svc(ip, {
signal: signal
});
case 3:
r = _context3.sent;
if (r) {
_context3.next = 6;
break;
}
return _context3.abrupt("return", null);
case 6:
return _context3.abrupt("return", {
source: name,
city: r.city,
region: r.region,
country: r.country,
org: r.org,
isp: r.isp,
loc: r.loc || (r.latitude != null && r.longitude != null ? "".concat(r.latitude, ",").concat(r.longitude) : null),
timezone: r.timezone,
postal: r.postal,
flag: r.flag,
continent: r.continent
});
case 7:
case "end":
return _context3.stop();
}
}, _callee3);
}));
return function (_x, _x2) {
return _ref4.apply(this, arguments);
};
}());
} else if (svc && typeof svc.fn === "function") {
var _name = String(svc.name || "custom_".concat(i));
_this.starLocator.register(_name, svc.fn);
}
};
for (var i = 0; i < extraGeoProviders.length; i++) {
_loop();
}
}
if (this.enableGeoDebug && typeof this.starLocator.on === "function") {
var onOk = function onOk(d) {
return console.log("[StarAuth | Star Locator] ~ provider ok", d);
};
var onErr = function onErr(d) {
return console.warn("[StarAuth | Star Locator] ~ provider error", d);
};
var onLookup = function onLookup(d) {
var _d$result, _d$result2;
return console.log("[StarAuth | Star Locator] ~ lookup result", d === null || d === void 0 || (_d$result = d.result) === null || _d$result === void 0 ? void 0 : _d$result.ip, d === null || d === void 0 || (_d$result2 = d.result) === null || _d$result2 === void 0 ? void 0 : _d$result2.country);
};
var onReverse = function onReverse(d) {
return console.log("[StarAuth | Star Locator] ~ reverse result", d === null || d === void 0 ? void 0 : d.provider);
};
this.starLocator.on("provider:success", onOk);
this.starLocator.on("provider:error", onErr);
this.starLocator.on("lookup:result", onLookup);
this.starLocator.on("reverse:result", onReverse);
var off = function off(evt, fn) {
if (typeof _this.starLocator.off === "function") {
_this.starLocator.off(evt, fn);
return;
}
if (typeof _this.starLocator.removeListener === "function") {
_this.starLocator.removeListener(evt, fn);
return;
}
};
_classPrivateFieldGet(_geoDebugCleanups, this).add(function () {
return off("provider:success", onOk);
});
_classPrivateFieldGet(_geoDebugCleanups, this).add(function () {
return off("provider:error", onErr);
});
_classPrivateFieldGet(_geoDebugCleanups, this).add(function () {
return off("lookup:result", onLookup);
});
_classPrivateFieldGet(_geoDebugCleanups, this).add(function () {
return off("reverse:result", onReverse);
});
}
}
return _createClass(StarAuth, [{
key: "getLockDoc",
value: function getLockDoc(key) {
var actionInfo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.vault.query(this.lockCollection, actionInfo).where({
key: key
}).limit(1).execute(true)[0] || null;
}
}, {
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 _callee4(ip) {
var _r$confidence, r;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
if (!(!this.enableGeo || !ip)) {
_context4.next = 2;
break;
}
return _context4.abrupt("return", null);
case 2:
_context4.prev = 2;
_context4.next = 5;
return this.starLocator.lookup(ip);
case 5:
r = _context4.sent;
if (r) {
_context4.next = 8;
break;
}
return _context4.abrupt("return", null);
case 8:
return _context4.abrupt("return", {
requestIP: ip,
ip: r.ip || ip,
timezone: r.timezone || null,
continent: r.continent || null,
country: r.country || null,
region: r.region || null,
postal: r.postal || null,
city: r.city || null,
loc: r.loc || null,
flag: r.flag || null,
org: r.org || null,
isp: r.isp || null,
confidence: (_r$confidence = r.confidence) !== null && _r$confidence !== void 0 ? _r$confidence : null
});
case 11:
_context4.prev = 11;
_context4.t0 = _context4["catch"](2);
if (this.enableGeoDebug) {
console.warn("[StarAuth | Star Locator] ~ Lookup error:", _context4.t0.message);
}
return _context4.abrupt("return", null);
case 15:
case "end":
return _context4.stop();
}
}, _callee4, this, [[2, 11]]);
}));
function lookupGeo(_x3) {
return _lookupGeo.apply(this, arguments);
}
return lookupGeo;
}()
}, {
key: "registerGuest",
value: function () {
var _registerGuest = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
var req,
metadata,
actionInfo,
clientAuth,
now,
accountID,
attempt,
guestID,
existing,
guestUser,
session,
_args5 = arguments;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
req = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : {};
metadata = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {};
actionInfo = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : {};
clientAuth = _args5.length > 3 && _args5[3] !== undefined ? _args5[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) {
_context5.next = 13;
break;
}
return _context5.abrupt("break", 14);
case 13:
if (true) {
_context5.next = 8;
break;
}
case 14:
_context5.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 = _context5.sent;
_context5.next = 19;
return _assertClassBrand(_StarAuth_brand, this, _createSession).call(this, guestUser, req, actionInfo, clientAuth);
case 19:
session = _context5.sent;
return _context5.abrupt("return", _objectSpread(_objectSpread({}, session), {}, {
id: guestUser.id,
accountID: accountID,
guestID: guestID
}));
case 21:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
function registerGuest() {
return _registerGuest.apply(this, arguments);
}
return registerGuest;
}()
}, {
key: "register",
value: function () {
var _register = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(email, password) {
var actionInfo,
clientAuth,
normalized,
existing,
hash,
accountID,
_args6 = arguments;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
actionInfo = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : {};
clientAuth = _args6.length > 3 && _args6[3] !== undefined ? _args6[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(true);
if (existing.length > 0) {
this.throwError("EMAIL_EXISTS", "Email \"".concat(normalized, "\" already exists."));
}
_context6.next = 9;
return this.locker.hashPassword(password);
case 9:
hash = _context6.sent;
accountID = crypto.randomUUID();
return _context6.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 _context6.stop();
}
}, _callee6, this);
}));
function register(_x4, _x5) {
return _register.apply(this, arguments);
}
return register;
}()
}, {
key: "upgradeGuestAccount",
value: function () {
var _upgradeGuestAccount = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(accountID, email, password) {
var _user$data;
var actionInfo,
clientAuth,
user,
now,
hashedPassword,
updatedFields,
_args7 = arguments;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
actionInfo = _args7.length > 3 && _args7[3] !== undefined ? _args7[3] : {};
clientAuth = _args7.length > 4 && _args7[4] !== undefined ? _args7[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, _assertAcco