UNPKG

@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

884 lines (883 loc) 52.4 kB
"use strict"; 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 _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 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 _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 _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 _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.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.enableSuspiciousCheck = options.enableSuspiciousCheck !== false; this.tagSession = options.tagSession || null; this.enableGeo = options.enableGeo || false; 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 _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); } if (options.expiredSessionCleanupInterval) { setInterval(/*#__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); } } return _createClass(StarAuth, [{ key: "matchEmailFormat", value: function matchEmailFormat(email) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); } }, { key: "matchPasswordStrength", value: function matchPasswordStrength(password) { return typeof password === "string" && password.length >= 8 && /[a-zA-Z]/.test(password) && /[0-9]/.test(password); } }, { 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 _callee3(ip) { var _data$connection, _data$connection2, _data$timezone, _data$flag, res, data; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.prev = 0; _context3.next = 3; return fetch("https://ipwho.is/".concat(ip)); case 3: res = _context3.sent; _context3.next = 6; return res.json(); case 6: data = _context3.sent; if (!(!res.ok || !data.success)) { _context3.next = 9; break; } return _context3.abrupt("return", null); case 9: return _context3.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: _context3.prev = 12; _context3.t0 = _context3["catch"](0); return _context3.abrupt("return", null); case 15: case "end": return _context3.stop(); } }, _callee3, null, [[0, 12]]); })); function lookupGeo(_x) { return _lookupGeo.apply(this, arguments); } return lookupGeo; }() }, { key: "register", value: function () { var _register = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(email, password) { var actionInfo, clientAuth, normalized, existing, hash, _args4 = arguments; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: actionInfo = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : {}; clientAuth = _args4.length > 3 && _args4[3] !== undefined ? _args4[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.")); } _context4.next = 9; return this.locker.hashPassword(password); case 9: hash = _context4.sent; return _context4.abrupt("return", this.vault.create(this.userCollection, { email: normalized, password: hash, createdAt: Date.now() }, actionInfo, clientAuth)); case 11: case "end": return _context4.stop(); } }, _callee4, this); })); function register(_x2, _x3) { return _register.apply(this, arguments); } return register; }() }, { key: "login", value: function () { var _login = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(email, password) { var req, actionInfo, clientAuth, user, now, match, failed, lockUntil, _args5 = arguments; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: req = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : {}; actionInfo = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : {}; clientAuth = _args5.length > 4 && _args5[4] !== undefined ? _args5[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."); } now = Date.now(); if (user.data.lockUntil && now < user.data.lockUntil) { this.throwError("ACCOUNT_LOCKED", "Account locked. Try again later."); } _context5.next = 9; return this.locker.verifyPassword(password, user.data.password); case 9: match = _context5.sent; if (match) { _context5.next = 16; break; } failed = (user.data.failedAttempts || 0) + 1; lockUntil = failed >= this.maxLoginAttempts ? now + this.lockoutDuration : null; _context5.next = 15; return this.vault.update(this.userCollection, user.id, _objectSpread({ failedAttempts: failed }, lockUntil ? { lockUntil: lockUntil } : {}), actionInfo, clientAuth); case 15: this.throwError(failed >= this.maxLoginAttempts ? "ACCOUNT_LOCKED" : "WRONG_PASSWORD", failed >= this.maxLoginAttempts ? "Account locked due to repeated failures." : "Incorrect password."); case 16: if (!(user.data.failedAttempts || user.data.lockUntil)) { _context5.next = 19; break; } _context5.next = 19; return this.vault.update(this.userCollection, user.id, { failedAttempts: 0, lockUntil: null }, actionInfo, clientAuth); case 19: _context5.next = 21; return this.cleanupExpiredSessions(actionInfo, clientAuth); case 21: _context5.next = 23; return _assertClassBrand(_StarAuth_brand, this, _createSession).call(this, user, req, actionInfo, clientAuth); case 23: return _context5.abrupt("return", _context5.sent); case 24: case "end": return _context5.stop(); } }, _callee5, this); })); function login(_x4, _x5) { return _login.apply(this, arguments); } return login; }() }, { key: "validateSession", value: function validateSession(token) { var req = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var actionInfo = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var clientAuth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var sessionRecord = this.vault.query(this.sessionCollection).where({ id: token }).limit(1).execute()[0]; if (!sessionRecord || !sessionRecord.data || !sessionRecord.data.active) { return null; } var session = sessionRecord.data; if (session.expiresAt < Date.now()) { return null; } if (this.strictSessionValidation && req) { var current = this.extractSessionMetadata(req); var _iterator = _createForOfIteratorHelper(this.sessionValidationFields), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var field = _step.value; var expected = session[field]; var actual = current[field]; if (expected && actual && expected !== actual) { if (typeof this.handleHijack === "function") { this.handleHijack(session, field, expected, actual); } this.vault.update(this.sessionCollection, sessionRecord.id, _objectSpread(_objectSpread({}, session), {}, { active: false, hijacked: true, hijackDetectedAt: Date.now() }), actionInfo, clientAuth); return null; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return session.userID; } }, { key: "sessionHijacked", value: function sessionHijacked(token) { var req = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var sessionRecord = this.vault.query(this.sessionCollection).where({ id: token }).limit(1).execute()[0]; if (!sessionRecord || !sessionRecord.data) { return false; } var session = sessionRecord.data; var current = this.extractSessionMetadata(req); var _iterator2 = _createForOfIteratorHelper(this.sessionValidationFields), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var field = _step2.value; var expected = session[field]; var actual = current[field]; if (expected && actual && expected !== actual) { return true; } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return false; } }, { key: "logout", value: function logout(token) { var actionInfo = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var clientAuth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var session = this.vault.query(this.sessionCollection).where({ id: token }).limit(1).execute()[0]; if (!session) { return false; } this.vault.update(this.sessionCollection, session.id, _objectSpread(_objectSpread({}, session.data), {}, { active: false, signedOutAt: Date.now(), reason: "logout" }), actionInfo, clientAuth); return true; } }, { key: "deactivateOtherSessions", value: function () { var _deactivateOtherSessions = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(userID, currentSessionID) { var actionInfo, clientAuth, sessions, _iterator3, _step3, session, _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; sessions = this.vault.query(this.sessionCollection).where({ userID: userID }).filterBy(function (r) { return r.active === true && r.id !== currentSessionID; }).execute(true); _iterator3 = _createForOfIteratorHelper(sessions); _context6.prev = 4; _iterator3.s(); case 6: if ((_step3 = _iterator3.n()).done) { _context6.next = 12; break; } session = _step3.value; _context6.next = 10; return this.vault.update(this.sessionCollection, session.id, _objectSpread(_objectSpread({}, session), {}, { signedOutAt: Date.now(), reason: "replaced", active: false }), actionInfo, clientAuth); case 10: _context6.next = 6; break; case 12: _context6.next = 17; break; case 14: _context6.prev = 14; _context6.t0 = _context6["catch"](4); _iterator3.e(_context6.t0); case 17: _context6.prev = 17; _iterator3.f(); return _context6.finish(17); case 20: return _context6.abrupt("return", sessions.map(function (s) { return s.id; })); case 21: case "end": return _context6.stop(); } }, _callee6, this, [[4, 14, 17, 20]]); })); function deactivateOtherSessions(_x6, _x7) { return _deactivateOtherSessions.apply(this, arguments); } return deactivateOtherSessions; }() }, { key: "extendSession", value: function extendSession(token, ms) { var actionInfo = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var clientAuth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var session = this.vault.query(this.sessionCollection).where({ id: token }).limit(1).execute()[0]; if (!session || !session.data.active || session.data.expiresAt < Date.now()) { return null; } var updated = _objectSpread(_objectSpread({}, session.data), {}, { expiresAt: session.data.expiresAt + ms }); this.vault.update(this.sessionCollection, token, updated, actionInfo, clientAuth); return { id: token, newExpiresAt: updated.expiresAt }; } }, { key: "requestPasswordReset", value: function () { var _requestPasswordReset = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(email) { var actionInfo, clientAuth, user, token, record, _args7 = arguments; return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: actionInfo = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : {}; clientAuth = _args7.length > 2 && _args7[2] !== undefined ? _args7[2] : null; user = this.vault.query(this.userCollection).where({ email: email }).limit(1).execute()[0]; if (!user) { this.throwError("USER_NOT_FOUND", "User not found."); } token = crypto.randomUUID(); record = { id: token, userID: user.id, email: email, createdAt: Date.now(), expiresAt: Date.now() + 1000 * 60 * 15 }; this.vault.create(this.resetCollection, record, actionInfo, clientAuth); return _context7.abrupt("return", { token: token, expires: record.expiresAt }); case 8: case "end": return _context7.stop(); } }, _callee7, this); })); function requestPasswordReset(_x8) { return _requestPasswordReset.apply(this, arguments); } return requestPasswordReset; }() }, { key: "resetPassword", value: function () { var _resetPassword = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(token, newPassword) { var actionInfo, clientAuth, record, hash, _args8 = arguments; return _regeneratorRuntime().wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { case 0: actionInfo = _args8.length > 2 && _args8[2] !== undefined ? _args8[2] : {}; clientAuth = _args8.length > 3 && _args8[3] !== undefined ? _args8[3] : null; record = this.vault.query(this.resetCollection).where({ id: token }).limit(1).execute()[0]; if (!record || record.expiresAt < Date.now()) { this.throwError("INVALID_OR_EXPIRED_TOKEN", "Password renewal invalid or expired."); } _context8.next = 6; return this.locker.hashPassword(newPassword); case 6: hash = _context8.sent; this.vault.update(this.userCollection, record.userID, { password: hash }, actionInfo, clientAuth); this.vault.update(this.resetCollection, token, _objectSpread(_objectSpread({}, record), {}, { used: true }), actionInfo, clientAuth); return _context8.abrupt("return", { userID: record.userID }); case 10: case "end": return _context8.stop(); } }, _callee8, this); })); function resetPassword(_x9, _x10) { return _resetPassword.apply(this, arguments); } return resetPassword; }() }, { key: "requestStellarLink", value: function () { var _requestStellarLink = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(email) { var type, actionInfo, clientAuth, user, existing, token, record, _args9 = arguments; return _regeneratorRuntime().wrap(function _callee9$(_context9) { while (1) switch (_context9.prev = _context9.next) { case 0: type = _args9.length > 1 && _args9[1] !== undefined ? _args9[1] : "link"; actionInfo = _args9.length > 2 && _args9[2] !== undefined ? _args9[2] : {}; clientAuth = _args9.length > 3 && _args9[3] !== undefined ? _args9[3] : null; user = this.vault.query(this.userCollection).where({ email: email }).limit(1).execute()[0]; if (!user) { this.throwError("USER_NOT_FOUND", "User not found."); } existing = this.vault.query(this.stellarCollection).where({ userID: user.id, type: type }).sort({ createdAt: -1 }).limit(1).execute()[0]; if (existing && Date.now() - existing.createdAt < this.stellarRequestCooldown) { this.throwError("TOO_SOON", "Please wait before requesting again."); } token = type === "link" ? crypto.randomUUID() : this.generateStellarCode(); record = { id: token, userID: user.id, email: email, type: type, createdAt: Date.now(), expiresAt: Date.now() + 1000 * 60 * 10 }; this.vault.create(this.stellarCollection, record, actionInfo, clientAuth); return _context9.abrupt("return", { token: token, expires: record.expiresAt }); case 11: case "end": return _context9.stop(); } }, _callee9, this); })); function requestStellarLink(_x11) { return _requestStellarLink.apply(this, arguments); } return requestStellarLink; }() }, { key: "consumeStellarToken", value: function () { var _consumeStellarToken = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(token) { var type, req, actionInfo, clientAuth, record, user, _args10 = arguments; return _regeneratorRuntime().wrap(function _callee10$(_context10) { while (1) switch (_context10.prev = _context10.next) { case 0: type = _args10.length > 1 && _args10[1] !== undefined ? _args10[1] : "link"; req = _args10.length > 2 && _args10[2] !== undefined ? _args10[2] : {}; actionInfo = _args10.length > 3 && _args10[3] !== undefined ? _args10[3] : {}; clientAuth = _args10.length > 4 && _args10[4] !== undefined ? _args10[4] : null; record = this.vault.query(this.stellarCollection).where({ id: token, type: type }).limit(1).execute()[0]; if (!record || record.expiresAt < Date.now()) { this.throwError("INVALID_OR_EXPIRED_TOKEN", "Token invalid or expired."); } user = this.vault.getByID(this.userCollection, record.userID); if (!user) { this.throwError("USER_NOT_FOUND", "User not found."); } this.vault.update(this.stellarCollection, token, _objectSpread(_objectSpread({}, record), {}, { used: true }), actionInfo, clientAuth); _context10.next = 11; return _assertClassBrand(_StarAuth_brand, this, _createSession).call(this, user, req, actionInfo, clientAuth); case 11: return _context10.abrupt("return", _context10.sent); case 12: case "end": return _context10.stop(); } }, _callee10, this); })); function consumeStellarToken(_x12) { return _consumeStellarToken.apply(this, arguments); } return consumeStellarToken; }() }, { key: "cleanupExpiredSessions", value: function () { var _cleanupExpiredSessions = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11() { var actionInfo, clientAuth, now, expired, updated, _iterator4, _step4, session, _args11 = arguments; return _regeneratorRuntime().wrap(function _callee11$(_context11) { while (1) switch (_context11.prev = _context11.next) { case 0: actionInfo = _args11.length > 0 && _args11[0] !== undefined ? _args11[0] : {}; clientAuth = _args11.length > 1 && _args11[1] !== undefined ? _args11[1] : null; now = Date.now(); expired = this.vault.query(this.sessionCollection).filterBy(function (r) { return r.expiresAt < now && r.active === true; }).execute(true); updated = []; _iterator4 = _createForOfIteratorHelper(expired); try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { session = _step4.value; this.vault.update(this.sessionCollection, session.id, _objectSpread(_objectSpread({}, session), {}, { reason: "expired", expiredAt: now, active: false }), actionInfo, clientAuth); updated.push({ id: session.id }); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } return _context11.abrupt("return", updated); case 8: case "end": return _context11.stop(); } }, _callee11, this); })); function cleanupExpiredSessions() { return _cleanupExpiredSessions.apply(this, arguments); } return cleanupExpiredSessions; }() }, { key: "cleanupExpiredTokens", value: function () { var _cleanupExpiredTokens = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12() { var actionInfo, clientAuth, now, collections, deleted, _i, _collections, collection, expired, _iterator5, _step5, r, _args12 = arguments; return _regeneratorRuntime().wrap(function _callee12$(_context12) { while (1) switch (_context12.prev = _context12.next) { case 0: actionInfo = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {}; clientAuth = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : null; now = Date.now(); collections = [this.resetCollection, this.stellarCollection]; deleted = []; for (_i = 0, _collections = collections; _i < _collections.length; _i++) { collection = _collections[_i]; expired = this.vault.query(collection).filterBy(function (r) { return r.expiresAt < now; }).execute(); _iterator5 = _createForOfIteratorHelper(expired); try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { r = _step5.value; this.vault.deleteRecord(collection, r.id, actionInfo, clientAuth); deleted.push({ collection: collection, id: r.id }); } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } } return _context12.abrupt("return", deleted); case 7: case "end": return _context12.stop(); } }, _callee12, this); })); function cleanupExpiredTokens() { return _cleanupExpiredTokens.apply(this, arguments); } return cleanupExpiredTokens; }() }, { key: "checkSuspiciousSession", value: function checkSuspiciousSession(session) { if (!session.geo || !session.ip || !session.userID) { return; } var pastSessions = this.vault.query(this.sessionCollection).where({ userID: session.userID }).sort({ createdAt: -1 }).limit(10).execute(); var _iterator6 = _createForOfIteratorHelper(pastSessions), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var past = _step6.value; if (!past.geo || past.id === session.id) { continue; } if (past.geo.country !== session.geo.country || past.geo.ip !== session.geo.ip) { if (typeof this.onSuspiciousSession === "function") { this.onSuspiciousSession(session, past); } break; } } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } } }]); }(); function _createSession(_x13, _x14) { return _createSession2.apply(this, arguments); } function _createSession2() { _createSession2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(user, req) { var actionInfo, clientAuth, now, token, expires, originInfo, geo, session, tags, existing, _args13 = arguments; return _regeneratorRuntime().wrap(function _callee13$(_context13) { while (1) switch (_context13.prev = _context13.next) { case 0: actionInfo = _args13.length > 2 && _args13[2] !== undefined ? _args13[2] : {}; clientAuth = _args13.length > 3 && _args13[3] !== undefined ? _args13[3] : null; now = Date.now(); token = crypto.randomUUID(); expires = now + this.tokenExpiry * 1000; originInfo = this.extractSessionMetadata(req); if (!(this.enableGeo && originInfo.ip)) { _context13.next = 12; break; } _context13.next = 9; retur