strapi-plugin-magic-sessionmanager 4.7.0 → 4.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/admin/{Analytics-Dq8PuDhs.mjs → Analytics-CsrpxJwQ.mjs} +86 -69
  3. package/dist/admin/{Analytics-Cw6R2xZn.js → Analytics-D03ZNNMR.js} +86 -69
  4. package/dist/admin/{App-DLR2M3FT.js → App-B2VCS3cz.js} +22 -27
  5. package/dist/admin/{App-BIFTc3mk.mjs → App-qxKnK7G2.mjs} +9 -14
  6. package/dist/admin/{License-W_NPUWIn.mjs → License-ClW7sZLR.mjs} +1 -1
  7. package/dist/admin/{License-BZtjgFol.js → License-fixnQ7wF.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-BIbmzgLP.mjs → OnlineUsersWidget-mR_OMiwi.mjs} +1 -2
  9. package/dist/admin/{OnlineUsersWidget-CAdR0MfU.js → OnlineUsersWidget-qb9utPBy.js} +1 -2
  10. package/dist/admin/{Settings-BNu9EAuS.mjs → Settings-U3V4eGMo.mjs} +1 -1
  11. package/dist/admin/{Settings-DWaflQdm.js → Settings-gv2BF54w.js} +1 -1
  12. package/dist/admin/{de-jU7AaYIc.js → de-BnqGCokx.js} +2 -2
  13. package/dist/admin/{de-4pAz-Ihh.mjs → de-JBE-iylO.mjs} +2 -2
  14. package/dist/admin/{en-Tjp9AEhR.js → en-BRmVwd8-.js} +2 -2
  15. package/dist/admin/{en-BI_aBNXG.mjs → en-kQWtdEai.mjs} +2 -2
  16. package/dist/admin/{es-BCgwFZPL.js → es-CH691xcL.js} +2 -2
  17. package/dist/admin/{es-Bp4Uzf5h.mjs → es-DOQvBxih.mjs} +2 -2
  18. package/dist/admin/{fr-Di5zo4wy.js → fr-CLExO0w_.js} +2 -2
  19. package/dist/admin/{fr-B69qIjq2.mjs → fr-CmfCpepX.mjs} +2 -2
  20. package/dist/admin/{index-eSND7TDx.mjs → index-B_lFjUAg.mjs} +15 -15
  21. package/dist/admin/{index-CBS3aqCW.js → index-Duc7cR_d.js} +15 -15
  22. package/dist/admin/index.js +1 -1
  23. package/dist/admin/index.mjs +1 -1
  24. package/dist/admin/{pt-DlGYOi6D.js → pt-BJ_F0yNi.js} +2 -2
  25. package/dist/admin/{pt-Drc-di4D.mjs → pt-BSzZdyAH.mjs} +2 -2
  26. package/dist/admin/sessionStatus-D_fWEzgj.js +11 -0
  27. package/dist/admin/sessionStatus-kwggjEMw.mjs +12 -0
  28. package/dist/server/index.js +652 -318
  29. package/dist/server/index.mjs +652 -318
  30. package/package.json +2 -2
@@ -94,7 +94,6 @@ var require_register = __commonJS({
94
94
  "use strict";
95
95
  var { createLogger } = require_logger();
96
96
  var USER_UID = "plugin::users-permissions.user";
97
- var SESSION_UID = "plugin::magic-sessionmanager.session";
98
97
  module.exports = async ({ strapi: strapi2 }) => {
99
98
  const log = createLogger(strapi2);
100
99
  log.info("[START] Plugin registration starting...");
@@ -141,34 +140,11 @@ var require_register = __commonJS({
141
140
  if (!data || data.blocked !== true) return;
142
141
  const userDocId = result.documentId;
143
142
  if (!userDocId) return;
144
- const activeSessions = await strapi2.documents(SESSION_UID).findMany({
145
- filters: { user: { documentId: userDocId }, isActive: true },
146
- fields: ["documentId"],
147
- limit: 1e3
143
+ const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
144
+ const { terminatedCount: terminated } = await sessionService.terminateSession({
145
+ userId: userDocId,
146
+ reason: "blocked"
148
147
  });
149
- if (!activeSessions || activeSessions.length === 0) return;
150
- const now = /* @__PURE__ */ new Date();
151
- let terminated = 0;
152
- for (const session of activeSessions) {
153
- try {
154
- await strapi2.documents(SESSION_UID).update({
155
- documentId: session.documentId,
156
- data: {
157
- isActive: false,
158
- // Blocked users are NOT a "manual" self-logout — mark
159
- // this distinctly so the client receives a different
160
- // error message ("account blocked") rather than
161
- // "session terminated".
162
- terminatedManually: false,
163
- terminationReason: "blocked",
164
- logoutTime: now
165
- }
166
- });
167
- terminated++;
168
- } catch (updateErr) {
169
- log.warn(`[lifecycle] failed to terminate session ${session.documentId}:`, updateErr.message);
170
- }
171
- }
172
148
  if (terminated > 0) {
173
149
  log.info(`[lifecycle] Terminated ${terminated} session(s) for blocked user ${userDocId.substring(0, 8)}...`);
174
150
  }
@@ -642,10 +618,10 @@ var require_geo_firewall = __commonJS({
642
618
  if (geoData.isThreat) {
643
619
  return { blocked: true, reason: "threat_ip", status };
644
620
  }
645
- if (geoData.isVpn && settings.alertOnVpnProxy !== false) {
621
+ if (geoData.isVpn) {
646
622
  return { blocked: true, reason: "vpn_detected", status };
647
623
  }
648
- if (geoData.isProxy && settings.alertOnVpnProxy !== false) {
624
+ if (geoData.isProxy) {
649
625
  return { blocked: true, reason: "proxy_detected", status };
650
626
  }
651
627
  if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < 50) {
@@ -685,6 +661,148 @@ var require_geo_firewall = __commonJS({
685
661
  }
686
662
  });
687
663
 
664
+ // server/src/utils/auth-routes.js
665
+ var require_auth_routes = __commonJS({
666
+ "server/src/utils/auth-routes.js"(exports, module) {
667
+ "use strict";
668
+ var NEW_SESSION_ROUTES = /* @__PURE__ */ new Set([
669
+ "POST /api/auth/local",
670
+ "POST /api/auth/local/register",
671
+ "POST /api/auth/reset-password",
672
+ "GET /api/auth/email-confirmation",
673
+ "POST /api/auth/email-confirmation",
674
+ "POST /api/magic-link/verify-mfa-totp",
675
+ "POST /api/magic-link/otp/verify",
676
+ "POST /api/magic-link/login-totp"
677
+ ]);
678
+ var FAILED_LOGIN_ROUTES = /* @__PURE__ */ new Set([
679
+ "POST /api/auth/local",
680
+ "POST /api/magic-link/login-totp",
681
+ "POST /api/magic-link/otp/verify",
682
+ "POST /api/magic-link/verify-mfa-totp"
683
+ ]);
684
+ function requestKey(path, method) {
685
+ return `${String(method || "").toUpperCase()} ${path || ""}`;
686
+ }
687
+ function isMagicLinkLogin(path, method) {
688
+ const normalizedMethod = String(method || "").toUpperCase();
689
+ return typeof path === "string" && path.startsWith("/api/magic-link/login") && (normalizedMethod === "GET" || normalizedMethod === "POST");
690
+ }
691
+ function classifyJwtIssuingRequest(path, method) {
692
+ const normalizedMethod = String(method || "").toUpperCase();
693
+ const key = requestKey(path, normalizedMethod);
694
+ if (key === "POST /api/auth/refresh") return "refresh";
695
+ if (key === "POST /api/auth/change-password") return "rotate-current";
696
+ if (NEW_SESSION_ROUTES.has(key)) return "new-session";
697
+ if (normalizedMethod === "GET" && /^\/api\/auth\/[a-z0-9-]+\/callback$/i.test(path || "")) {
698
+ return "new-session";
699
+ }
700
+ if (isMagicLinkLogin(path, normalizedMethod)) return "new-session";
701
+ if (typeof path === "string" && path.startsWith("/api/passwordless/") && (normalizedMethod === "GET" || normalizedMethod === "POST")) {
702
+ return "new-session";
703
+ }
704
+ return null;
705
+ }
706
+ function shouldRunPreAuthGeoGuard(path, method) {
707
+ return classifyJwtIssuingRequest(path, method) === "new-session";
708
+ }
709
+ function isFailedLoginTrackedPath(path, method) {
710
+ return FAILED_LOGIN_ROUTES.has(requestKey(path, method)) || isMagicLinkLogin(path, method);
711
+ }
712
+ module.exports = {
713
+ classifyJwtIssuingRequest,
714
+ isFailedLoginTrackedPath,
715
+ shouldRunPreAuthGeoGuard
716
+ };
717
+ }
718
+ });
719
+
720
+ // server/src/utils/refresh-token.js
721
+ var require_refresh_token = __commonJS({
722
+ "server/src/utils/refresh-token.js"(exports, module) {
723
+ "use strict";
724
+ var DEFAULT_REFRESH_COOKIE_NAME = "strapi_up_refresh";
725
+ function getRefreshCookieName(strapi2) {
726
+ try {
727
+ return strapi2.config.get(
728
+ "plugin::users-permissions.sessions.cookie.name",
729
+ DEFAULT_REFRESH_COOKIE_NAME
730
+ ) || DEFAULT_REFRESH_COOKIE_NAME;
731
+ } catch {
732
+ return DEFAULT_REFRESH_COOKIE_NAME;
733
+ }
734
+ }
735
+ function getIncomingRefreshToken(ctx, cookieName = DEFAULT_REFRESH_COOKIE_NAME) {
736
+ const bodyToken = ctx?.request?.body?.refreshToken;
737
+ if (typeof bodyToken === "string" && bodyToken.length > 0) return bodyToken;
738
+ try {
739
+ const cookieToken = ctx?.cookies?.get(cookieName);
740
+ return typeof cookieToken === "string" && cookieToken.length > 0 ? cookieToken : null;
741
+ } catch {
742
+ return null;
743
+ }
744
+ }
745
+ function getSetCookieHeaders(ctx) {
746
+ const headers = ctx?.response?.headers || ctx?.response?.header || {};
747
+ const raw = headers["set-cookie"] || headers["Set-Cookie"];
748
+ if (!raw) return [];
749
+ return Array.isArray(raw) ? raw : [raw];
750
+ }
751
+ function parseCookieValue(header, cookieName) {
752
+ if (typeof header !== "string") return null;
753
+ const firstPart = header.split(";", 1)[0].trim();
754
+ const separator = firstPart.indexOf("=");
755
+ if (separator < 1 || firstPart.slice(0, separator) !== cookieName) return null;
756
+ const rawValue = firstPart.slice(separator + 1);
757
+ try {
758
+ return decodeURIComponent(rawValue);
759
+ } catch {
760
+ return rawValue;
761
+ }
762
+ }
763
+ function getOutgoingRefreshToken(ctx, cookieName = DEFAULT_REFRESH_COOKIE_NAME) {
764
+ const bodyToken = ctx?.body?.refreshToken;
765
+ if (typeof bodyToken === "string" && bodyToken.length > 0) return bodyToken;
766
+ for (const header of getSetCookieHeaders(ctx)) {
767
+ const value = parseCookieValue(header, cookieName);
768
+ if (value) return value;
769
+ }
770
+ return null;
771
+ }
772
+ function stripAuthTokensFromResponse(ctx, cookieName = DEFAULT_REFRESH_COOKIE_NAME) {
773
+ if (ctx?.body && typeof ctx.body === "object" && !Buffer.isBuffer(ctx.body)) {
774
+ delete ctx.body.jwt;
775
+ delete ctx.body.refreshToken;
776
+ }
777
+ const remainingCookies = getSetCookieHeaders(ctx).filter(
778
+ (header) => parseCookieValue(header, cookieName) === null
779
+ );
780
+ if (typeof ctx?.remove === "function") {
781
+ ctx.remove("Set-Cookie");
782
+ for (const header of remainingCookies) {
783
+ if (typeof ctx.append === "function") ctx.append("Set-Cookie", header);
784
+ }
785
+ return;
786
+ }
787
+ const headers = ctx?.response?.headers || ctx?.response?.header;
788
+ if (!headers) return;
789
+ delete headers["Set-Cookie"];
790
+ if (remainingCookies.length > 0) {
791
+ headers["set-cookie"] = remainingCookies;
792
+ } else {
793
+ delete headers["set-cookie"];
794
+ }
795
+ }
796
+ module.exports = {
797
+ DEFAULT_REFRESH_COOKIE_NAME,
798
+ getRefreshCookieName,
799
+ getIncomingRefreshToken,
800
+ getOutgoingRefreshToken,
801
+ stripAuthTokensFromResponse
802
+ };
803
+ }
804
+ });
805
+
688
806
  // server/src/middlewares/session-rejection-headers.js
689
807
  var require_session_rejection_headers = __commonJS({
690
808
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -694,6 +812,7 @@ var require_session_rejection_headers = __commonJS({
694
812
  var { consumeSessionRejectionReason } = require_rejection_cache();
695
813
  var HEADER = "X-Session-Terminated-Reason";
696
814
  var REASON_MESSAGES = {
815
+ logout: "You have logged out. Please log in again.",
697
816
  manual: "Your session was terminated. Please log in again.",
698
817
  idle: "Your session expired due to inactivity. Please log in again.",
699
818
  expired: "Your session has reached its maximum age. Please log in again.",
@@ -738,10 +857,6 @@ var require_last_seen = __commonJS({
738
857
  "server/src/middlewares/last-seen.js"(exports, module) {
739
858
  "use strict";
740
859
  var { resolveUserDocumentId } = require_resolve_user();
741
- var {
742
- getPluginSettings,
743
- getSessionCreationGraceMs
744
- } = require_settings_loader();
745
860
  var { extractBearerToken } = require_extract_token();
746
861
  var { hashToken } = require_encryption();
747
862
  var SESSION_UID = "plugin::magic-sessionmanager.session";
@@ -771,8 +886,12 @@ var require_last_seen = __commonJS({
771
886
  if (isAuthEndpoint(ctx.path)) {
772
887
  return next();
773
888
  }
889
+ await next();
890
+ if (isSelfTerminatingEndpoint(ctx.path) || (ctx.status || 200) >= 400) {
891
+ return;
892
+ }
774
893
  if (!ctx.state.user) {
775
- return next();
894
+ return;
776
895
  }
777
896
  let userDocId = ctx.state.user.documentId;
778
897
  if (!userDocId && ctx.state.user.id) {
@@ -780,67 +899,38 @@ var require_last_seen = __commonJS({
780
899
  userDocId = await resolveUserDocumentId(strapi2, ctx.state.user.id);
781
900
  } catch (err) {
782
901
  strapi2.log.debug("[magic-sessionmanager] user doc-id lookup failed:", err.message);
783
- return next();
902
+ return;
784
903
  }
785
904
  }
786
905
  if (!userDocId) {
787
- return next();
906
+ return;
788
907
  }
789
- const settings = await getPluginSettings(strapi2).catch(() => ({}));
790
- const strictMode = settings.strictSessionEnforcement === true;
791
- const gracePeriodMs = getSessionCreationGraceMs(settings);
792
908
  const token = extractBearerToken(ctx);
793
909
  const tokenHashValue = token ? hashToken(token) : null;
794
- let thisSession = null;
795
- if (tokenHashValue) {
796
- try {
797
- thisSession = await strapi2.documents(SESSION_UID).findFirst({
798
- filters: { user: { documentId: userDocId }, tokenHash: tokenHashValue },
799
- fields: ["documentId", "isActive", "terminatedManually", "terminationReason"]
800
- });
801
- } catch (err) {
802
- strapi2.log.debug("[magic-sessionmanager] session lookup failed:", err.message);
803
- }
804
- }
805
- if (thisSession) {
806
- if (thisSession.isActive === false) {
807
- return ctx.unauthorized("Session terminated. Please login again.");
808
- }
809
- ctx.state.userDocumentId = userDocId;
810
- ctx.state.__magicSessionId = thisSession.documentId;
811
- await next();
812
- if (isSelfTerminatingEndpoint(ctx.path)) {
813
- return;
814
- }
815
- try {
816
- await sessionService.touch({
817
- userId: userDocId,
818
- sessionId: thisSession.documentId
819
- });
820
- } catch (err) {
821
- strapi2.log.debug("[magic-sessionmanager] Error updating lastSeen:", err.message);
822
- }
910
+ if (!tokenHashValue) {
823
911
  return;
824
912
  }
825
- if (strictMode) {
826
- const iat = ctx.state.user?.iat;
827
- if (gracePeriodMs > 0 && typeof iat === "number") {
828
- const ageMs = Date.now() - iat * 1e3;
829
- if (ageMs >= 0 && ageMs < gracePeriodMs) {
830
- ctx.state.userDocumentId = userDocId;
831
- return next();
832
- }
833
- }
834
- strapi2.log.info(
835
- `[magic-sessionmanager] [BLOCKED] No session matches this token (user: ${userDocId.substring(0, 8)}..., strictMode)`
836
- );
837
- return ctx.unauthorized("No valid session. Please login again.");
913
+ let thisSession = null;
914
+ try {
915
+ thisSession = await strapi2.documents(SESSION_UID).findFirst({
916
+ filters: { user: { documentId: userDocId }, tokenHash: tokenHashValue },
917
+ fields: ["documentId", "isActive"]
918
+ });
919
+ } catch (err) {
920
+ strapi2.log.debug("[magic-sessionmanager] session lookup failed:", err.message);
921
+ return;
838
922
  }
839
- strapi2.log.debug(
840
- `[magic-sessionmanager] [WARN] No session for token (user: ${userDocId.substring(0, 8)}...) - allowing in non-strict mode`
841
- );
923
+ if (!thisSession || thisSession.isActive !== true) return;
842
924
  ctx.state.userDocumentId = userDocId;
843
- return next();
925
+ ctx.state.__magicSessionId = thisSession.documentId;
926
+ try {
927
+ await sessionService.touch({
928
+ userId: userDocId,
929
+ sessionId: thisSession.documentId
930
+ });
931
+ } catch (err) {
932
+ strapi2.log.debug("[magic-sessionmanager] Error updating lastSeen:", err.message);
933
+ }
844
934
  };
845
935
  };
846
936
  }
@@ -9802,20 +9892,19 @@ var require_bootstrap = __commonJS({
9802
9892
  consumeSessionRejectionReason
9803
9893
  } = require_rejection_cache();
9804
9894
  var { evaluateGeoFirewall } = require_geo_firewall();
9895
+ var {
9896
+ classifyJwtIssuingRequest,
9897
+ isFailedLoginTrackedPath,
9898
+ shouldRunPreAuthGeoGuard
9899
+ } = require_auth_routes();
9900
+ var {
9901
+ getRefreshCookieName,
9902
+ getIncomingRefreshToken,
9903
+ getOutgoingRefreshToken,
9904
+ stripAuthTokensFromResponse
9905
+ } = require_refresh_token();
9805
9906
  var SESSION_UID = "plugin::magic-sessionmanager.session";
9806
9907
  var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
9807
- var LOGIN_PATHS = /* @__PURE__ */ new Set([
9808
- "/api/auth/local",
9809
- "/api/magic-link/login-totp",
9810
- "/api/magic-link/otp/verify",
9811
- "/api/magic-link/verify-mfa-totp"
9812
- ]);
9813
- function isLoginPath(path, method) {
9814
- if (!path) return false;
9815
- if (LOGIN_PATHS.has(path)) return true;
9816
- if (path.startsWith("/api/magic-link/login") && (method === "GET" || method === "POST")) return true;
9817
- return false;
9818
- }
9819
9908
  async function getRequestSettings(strapi2, ctx) {
9820
9909
  let settings = {};
9821
9910
  try {
@@ -9838,7 +9927,7 @@ var require_bootstrap = __commonJS({
9838
9927
  throw e;
9839
9928
  }
9840
9929
  try {
9841
- await ensureTokenHashIndex(strapi2, log);
9930
+ await ensureSessionLookupIndexes(strapi2, log);
9842
9931
  await registerSessionAwareAuthStrategy(strapi2, log);
9843
9932
  const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
9844
9933
  await licenseGuardService.initialize();
@@ -9904,7 +9993,8 @@ var require_bootstrap = __commonJS({
9904
9993
  mountFailedLoginLockout({ strapi: strapi2, log });
9905
9994
  mountLogoutRoute({ strapi: strapi2, log, sessionService });
9906
9995
  mountLoginInterceptor({ strapi: strapi2, log, sessionService });
9907
- mountRefreshTokenInterceptor({ strapi: strapi2, log });
9996
+ mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
9997
+ mountLogoutInterceptor({ strapi: strapi2, log, sessionService });
9908
9998
  strapi2.server.use(
9909
9999
  require_session_rejection_headers()({}, { strapi: strapi2 })
9910
10000
  );
@@ -9922,7 +10012,7 @@ var require_bootstrap = __commonJS({
9922
10012
  };
9923
10013
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
9924
10014
  strapi2.server.use(async (ctx, next) => {
9925
- if (!isLoginPath(ctx.path, ctx.method)) {
10015
+ if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
9926
10016
  return next();
9927
10017
  }
9928
10018
  const settings = await getRequestSettings(strapi2, ctx);
@@ -9955,13 +10045,30 @@ var require_bootstrap = __commonJS({
9955
10045
  ctx.state.__magicSessionGeoData = geoData;
9956
10046
  }
9957
10047
  } catch (err) {
9958
- log.debug("Pre-login geo guard error (allowing):", err.message);
10048
+ const failureDecision = evaluateGeoFirewall(settings, { _status: "error" });
10049
+ if (failureDecision.blocked) {
10050
+ log.warn(`[PRE-BLOCKED] Login rejected because GeoIP lookup failed for ${ip}`);
10051
+ ctx.status = 403;
10052
+ ctx.body = {
10053
+ error: {
10054
+ status: 403,
10055
+ name: "ForbiddenError",
10056
+ message: "Login temporarily unavailable. Please contact support."
10057
+ }
10058
+ };
10059
+ return;
10060
+ }
10061
+ log.debug("Pre-login geo guard error (allowing by configured policy):", err.message);
9959
10062
  }
9960
10063
  await next();
9961
10064
  });
9962
10065
  log.info("[SUCCESS] Pre-login geo guard mounted");
9963
10066
  }
9964
10067
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
10068
+ if (hasRegisteredRoute(strapi2, "POST", "/api/auth/logout")) {
10069
+ log.debug("[LOGOUT] Using the users-permissions logout route");
10070
+ return;
10071
+ }
9965
10072
  let jwt = null;
9966
10073
  try {
9967
10074
  jwt = require_jsonwebtoken();
@@ -9981,7 +10088,6 @@ var require_bootstrap = __commonJS({
9981
10088
  }
9982
10089
  const jwtService = strapi2.plugin("users-permissions").service("jwt");
9983
10090
  let decoded = null;
9984
- let expiredButValid = false;
9985
10091
  try {
9986
10092
  decoded = await jwtService.verify(token);
9987
10093
  } catch (verifyErr) {
@@ -9991,7 +10097,6 @@ var require_bootstrap = __commonJS({
9991
10097
  const jwtSecret = strapi2.config.get("plugin::users-permissions.jwtSecret");
9992
10098
  if (jwtSecret) {
9993
10099
  decoded = jwt.verify(token, jwtSecret, { ignoreExpiration: true });
9994
- expiredButValid = !!decoded;
9995
10100
  }
9996
10101
  } catch {
9997
10102
  decoded = null;
@@ -10008,23 +10113,21 @@ var require_bootstrap = __commonJS({
10008
10113
  ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10009
10114
  return;
10010
10115
  }
10011
- const userDocId = await resolveUserDocumentId(strapi2, decoded.id);
10012
- const tokenHashValue = hashToken(token);
10013
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10014
- filters: {
10015
- tokenHash: tokenHashValue,
10016
- ...userDocId ? { user: { documentId: userDocId } } : {}
10017
- },
10018
- fields: ["documentId", "isActive"]
10019
- });
10020
- if (matchingSession && matchingSession.isActive) {
10021
- await sessionService.terminateSession({ sessionId: matchingSession.documentId });
10022
- log.info(`[LOGOUT] Session ${matchingSession.documentId} terminated (expiredButValid=${expiredButValid})`);
10116
+ const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
10117
+ if (!userDocumentId) {
10118
+ ctx.status = 401;
10119
+ ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10120
+ return;
10023
10121
  }
10122
+ await sessionService.terminateAuthenticatedSession({
10123
+ userDocumentId,
10124
+ accessToken: token,
10125
+ refreshToken: null
10126
+ });
10024
10127
  ctx.status = 200;
10025
- ctx.body = { message: "Logged out successfully" };
10128
+ ctx.body = { ok: true, message: "Logged out successfully" };
10026
10129
  } catch (err) {
10027
- log.error("Logout error:", err);
10130
+ log.error("Logout error:", err?.name || "Error");
10028
10131
  ctx.status = 500;
10029
10132
  ctx.body = { error: { status: 500, name: "InternalServerError", message: "Logout failed" } };
10030
10133
  }
@@ -10035,6 +10138,36 @@ var require_bootstrap = __commonJS({
10035
10138
  }]);
10036
10139
  log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
10037
10140
  }
10141
+ function hasRegisteredRoute(strapi2, method, path) {
10142
+ try {
10143
+ const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
10144
+ const directRoutes = strapi2.server.listRoutes?.() || [];
10145
+ const contentRoutes = strapi2.server.api?.("content-api")?.listRoutes?.() || [];
10146
+ return [...directRoutes, ...contentRoutes].some((route) => {
10147
+ const methods = route.methods || (Array.isArray(route.method) ? route.method : [route.method]);
10148
+ const routePaths = /* @__PURE__ */ new Set([
10149
+ route.path,
10150
+ route.path?.startsWith(apiPrefix) ? route.path : `${apiPrefix}${route.path}`
10151
+ ]);
10152
+ return routePaths.has(path) && methods.some((value) => String(value).toUpperCase() === method);
10153
+ });
10154
+ } catch {
10155
+ return false;
10156
+ }
10157
+ }
10158
+ function failClosedAuthResponse({ ctx, strapi: strapi2, log, operation, error }) {
10159
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
10160
+ ctx.status = 503;
10161
+ if (typeof ctx.set === "function") ctx.set("Retry-After", "1");
10162
+ ctx.body = {
10163
+ error: {
10164
+ status: 503,
10165
+ name: "ServiceUnavailableError",
10166
+ message: "Authentication temporarily unavailable. Please try again."
10167
+ }
10168
+ };
10169
+ log.error(`[AUTH-FAIL-CLOSED] ${operation}:`, error?.message || error || "session persistence failed");
10170
+ }
10038
10171
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
10039
10172
  const WINDOW_MS = 15 * 60 * 1e3;
10040
10173
  const failed = /* @__PURE__ */ new Map();
@@ -10062,7 +10195,7 @@ var require_bootstrap = __commonJS({
10062
10195
  };
10063
10196
  const clearFailures = (ip) => failed.delete(ip);
10064
10197
  strapi2.server.use(async (ctx, next) => {
10065
- if (!isLoginPath(ctx.path, ctx.method)) return next();
10198
+ if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
10066
10199
  const settings = await getRequestSettings(strapi2, ctx);
10067
10200
  const maxFailed = Number(settings.maxFailedLogins) || 0;
10068
10201
  if (maxFailed <= 0) return next();
@@ -10099,30 +10232,42 @@ var require_bootstrap = __commonJS({
10099
10232
  });
10100
10233
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
10101
10234
  }
10102
- function isJwtIssuingPath(path, method) {
10103
- if (!path) return false;
10104
- const get = method === "GET";
10105
- const post = method === "POST";
10106
- if (post && path === "/api/auth/local") return true;
10107
- if (post && path === "/api/auth/local/register") return true;
10108
- if (post && path === "/api/auth/reset-password") return true;
10109
- if ((get || post) && path === "/api/auth/email-confirmation") return true;
10110
- if (get && /^\/api\/auth\/[a-z0-9-]+\/callback$/i.test(path)) return true;
10111
- if ((get || post) && path.startsWith("/api/magic-link/login")) return true;
10112
- if (post && path === "/api/magic-link/verify-mfa-totp") return true;
10113
- if (post && path === "/api/magic-link/otp/verify") return true;
10114
- if (post && path === "/api/magic-link/login-totp") return true;
10115
- if ((get || post) && path.startsWith("/api/passwordless/")) return true;
10116
- return false;
10117
- }
10118
10235
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
10119
10236
  strapi2.server.use(async (ctx, next) => {
10237
+ const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
10238
+ const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
10120
10239
  await next();
10121
- if (!isJwtIssuingPath(ctx.path, ctx.method)) return;
10122
- if (ctx.status !== 200) return;
10123
- if (!ctx.body || !ctx.body.jwt || !ctx.body.user) return;
10240
+ if (requestType !== "new-session" && requestType !== "rotate-current") return;
10241
+ if (ctx.status < 200 || ctx.status >= 300) return;
10242
+ if (!ctx.body || !ctx.body.jwt) return;
10243
+ const refreshCookieName = getRefreshCookieName(strapi2);
10244
+ if (requestType === "rotate-current") {
10245
+ try {
10246
+ if (!previousAccessToken) throw new Error("current access token is missing");
10247
+ const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10248
+ filters: {
10249
+ tokenHash: hashToken(previousAccessToken),
10250
+ isActive: true
10251
+ },
10252
+ fields: ["documentId"]
10253
+ });
10254
+ if (!matchingSession) throw new Error("current session was not found");
10255
+ const rotated = await sessionService.rotateSessionTokens({
10256
+ sessionId: matchingSession.documentId,
10257
+ expectedAccessToken: previousAccessToken,
10258
+ accessToken: ctx.body.jwt,
10259
+ refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName)
10260
+ });
10261
+ if (!rotated) throw new Error("current session changed before token rotation");
10262
+ log.info(`[PASSWORD] Tokens rotated for session ${matchingSession.documentId}`);
10263
+ } catch (err) {
10264
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "change-password rotation failed", error: err });
10265
+ }
10266
+ return;
10267
+ }
10124
10268
  try {
10125
10269
  const user = ctx.body.user;
10270
+ if (!user) throw new Error("authentication response contains no user");
10126
10271
  await getRequestSettings(strapi2, ctx);
10127
10272
  const ip = getClientIp(ctx);
10128
10273
  const headers = ctx.request.headers || ctx.request.header || {};
@@ -10133,8 +10278,7 @@ var require_bootstrap = __commonJS({
10133
10278
  userDocId = await resolveUserDocumentId(strapi2, user.id);
10134
10279
  }
10135
10280
  if (!userDocId) {
10136
- log.error(`[ERROR] Could not resolve documentId for user ${user.id || "unknown"} - session NOT created!`);
10137
- return;
10281
+ throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
10138
10282
  }
10139
10283
  const geoData = ctx.state?.__magicSessionGeoData || null;
10140
10284
  const newSession = await sessionService.createSession({
@@ -10142,12 +10286,11 @@ var require_bootstrap = __commonJS({
10142
10286
  ip,
10143
10287
  userAgent,
10144
10288
  token: ctx.body.jwt,
10145
- refreshToken: ctx.body.refreshToken,
10289
+ refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
10146
10290
  geoData
10147
10291
  });
10148
10292
  if (!newSession?.documentId) {
10149
- log.error(`[ERROR] Session creation returned no documentId for user ${userDocId}`);
10150
- return;
10293
+ throw new Error(`session creation returned no documentId for user ${userDocId}`);
10151
10294
  }
10152
10295
  log.info(`[SUCCESS] Session ${newSession.documentId} created for user ${userDocId} (IP: ${ip})`);
10153
10296
  try {
@@ -10200,6 +10343,17 @@ var require_bootstrap = __commonJS({
10200
10343
  }
10201
10344
  }
10202
10345
  if (settings.enableEmailAlerts) {
10346
+ if (settings.alertOnVpnProxy && (geoData.isVpn || geoData.isProxy)) {
10347
+ await notificationService.sendVpnProxyAlert({
10348
+ user,
10349
+ session: newSession,
10350
+ reason: {
10351
+ isVpn: geoData.isVpn,
10352
+ isProxy: geoData.isProxy
10353
+ },
10354
+ geoData
10355
+ });
10356
+ }
10203
10357
  if (settings.alertOnSuspiciousLogin && isSuspicious) {
10204
10358
  await notificationService.sendSuspiciousLoginAlert({
10205
10359
  user,
@@ -10260,84 +10414,101 @@ var require_bootstrap = __commonJS({
10260
10414
  log.warn("Notification failed:", notifErr.message);
10261
10415
  }
10262
10416
  } catch (err) {
10263
- log.error("[ERROR] Error creating session:", err);
10417
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "session creation failed", error: err });
10264
10418
  }
10265
10419
  });
10266
10420
  log.info("[SUCCESS] Login interceptor middleware mounted");
10267
10421
  }
10268
- function mountRefreshTokenInterceptor({ strapi: strapi2, log }) {
10422
+ function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
10269
10423
  strapi2.server.use(async (ctx, next) => {
10270
10424
  const isRefreshToken = ctx.path === "/api/auth/refresh" && ctx.method === "POST";
10271
- if (isRefreshToken) {
10272
- try {
10273
- const body = ctx.request.body;
10274
- const refreshToken = typeof body?.refreshToken === "string" ? body.refreshToken : null;
10275
- if (refreshToken) {
10276
- const refreshTokenHashValue = hashToken(refreshToken);
10277
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10278
- filters: {
10279
- refreshTokenHash: refreshTokenHashValue,
10280
- isActive: true
10281
- },
10282
- fields: ["documentId"]
10283
- });
10284
- if (!matchingSession) {
10285
- log.warn("[BLOCKED] Blocked refresh token request - no active session");
10286
- ctx.status = 401;
10287
- ctx.body = {
10288
- error: {
10289
- status: 401,
10290
- name: "UnauthorizedError",
10291
- message: "Session terminated. Please login again."
10292
- }
10293
- };
10294
- return;
10295
- }
10296
- log.info(`[SUCCESS] Refresh token allowed for session ${matchingSession.documentId}`);
10425
+ if (!isRefreshToken) return next();
10426
+ const cookieName = getRefreshCookieName(strapi2);
10427
+ const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
10428
+ let matchingSession = null;
10429
+ try {
10430
+ if (oldRefreshToken) {
10431
+ matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10432
+ filters: {
10433
+ refreshTokenHash: hashToken(oldRefreshToken),
10434
+ isActive: true
10435
+ },
10436
+ fields: ["documentId"]
10437
+ });
10438
+ if (!matchingSession) {
10439
+ log.warn("[BLOCKED] Blocked refresh token request - no active session");
10440
+ ctx.status = 401;
10441
+ ctx.body = {
10442
+ error: {
10443
+ status: 401,
10444
+ name: "UnauthorizedError",
10445
+ message: "Session terminated. Please login again."
10446
+ }
10447
+ };
10448
+ return;
10297
10449
  }
10298
- } catch (err) {
10299
- log.error("Error checking refresh token:", err);
10300
10450
  }
10451
+ } catch (err) {
10452
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh validation failed", error: err });
10453
+ return;
10301
10454
  }
10302
10455
  await next();
10303
- if (isRefreshToken && ctx.status === 200 && ctx.body && ctx.body.jwt) {
10456
+ if (ctx.status >= 200 && ctx.status < 300 && ctx.body && ctx.body.jwt) {
10304
10457
  try {
10305
- const body = ctx.request.body;
10306
- const oldRefreshToken = typeof body?.refreshToken === "string" ? body.refreshToken : null;
10307
- const newAccessToken = ctx.body.jwt;
10308
- const newRefreshToken = ctx.body.refreshToken;
10309
- if (!oldRefreshToken) return;
10310
- const oldRefreshTokenHash = hashToken(oldRefreshToken);
10311
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10312
- filters: {
10313
- refreshTokenHash: oldRefreshTokenHash,
10314
- isActive: true
10315
- },
10316
- fields: ["documentId", "token", "tokenHash", "refreshToken", "refreshTokenHash"]
10317
- });
10318
- if (!matchingSession) return;
10319
- const encryptedToken = newAccessToken ? encryptToken(newAccessToken) : matchingSession.token;
10320
- const encryptedRefreshToken = newRefreshToken ? encryptToken(newRefreshToken) : matchingSession.refreshToken;
10321
- const newTokenHash = newAccessToken ? hashToken(newAccessToken) : matchingSession.tokenHash;
10322
- const newRefreshTokenHash = newRefreshToken ? hashToken(newRefreshToken) : matchingSession.refreshTokenHash;
10323
- await strapi2.documents(SESSION_UID).update({
10324
- documentId: matchingSession.documentId,
10325
- data: {
10326
- token: encryptedToken,
10327
- tokenHash: newTokenHash,
10328
- refreshToken: encryptedRefreshToken,
10329
- refreshTokenHash: newRefreshTokenHash,
10330
- lastActive: /* @__PURE__ */ new Date()
10331
- }
10458
+ if (!oldRefreshToken || !matchingSession) {
10459
+ throw new Error("refresh response issued without a tracked input token");
10460
+ }
10461
+ const rotated = await sessionService.rotateSessionTokens({
10462
+ sessionId: matchingSession.documentId,
10463
+ expectedRefreshToken: oldRefreshToken,
10464
+ accessToken: ctx.body.jwt,
10465
+ refreshToken: getOutgoingRefreshToken(ctx, cookieName)
10332
10466
  });
10467
+ if (!rotated) throw new Error("refresh token was already consumed");
10333
10468
  log.info(`[REFRESH] Tokens refreshed for session ${matchingSession.documentId}`);
10334
10469
  } catch (err) {
10335
- log.error("Error updating refreshed tokens:", err);
10470
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh rotation failed", error: err });
10336
10471
  }
10337
10472
  }
10338
10473
  });
10339
10474
  log.info("[SUCCESS] Refresh token interceptor middleware mounted");
10340
10475
  }
10476
+ function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
10477
+ strapi2.server.use(async (ctx, next) => {
10478
+ if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
10479
+ const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
10480
+ const accessToken = extractBearerToken(ctx);
10481
+ const jwtManagement = strapi2.config.get(
10482
+ "plugin::users-permissions.jwtManagement",
10483
+ "legacy-support"
10484
+ );
10485
+ await next();
10486
+ const isUsersPermissionsLogoutRoute = ctx.state?.route?.handler === "auth.logout" && ctx.state?.route?.info?.pluginName === "users-permissions";
10487
+ const isSuccessful = isUsersPermissionsLogoutRoute && ctx.status >= 200 && ctx.status < 300;
10488
+ const isLegacyMissingRoute = jwtManagement === "legacy-support" && ctx.status === 404 && isUsersPermissionsLogoutRoute;
10489
+ const authenticatedUser = ctx.state?.user;
10490
+ if (!authenticatedUser || !isSuccessful && !isLegacyMissingRoute) return;
10491
+ try {
10492
+ const userDocumentId = authenticatedUser.documentId || await resolveUserDocumentId(strapi2, authenticatedUser.id);
10493
+ if (!userDocumentId) {
10494
+ throw new Error("authenticated logout user has no resolvable documentId");
10495
+ }
10496
+ await sessionService.terminateAuthenticatedSession({
10497
+ userDocumentId,
10498
+ refreshToken,
10499
+ accessToken
10500
+ });
10501
+ ctx.status = 200;
10502
+ ctx.body = {
10503
+ ok: true,
10504
+ message: "Logged out successfully"
10505
+ };
10506
+ } catch (err) {
10507
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
10508
+ }
10509
+ });
10510
+ log.info("[SUCCESS] Logout interceptor middleware mounted");
10511
+ }
10341
10512
  async function ensureContentApiPermissions(strapi2, log) {
10342
10513
  const PERMISSIONS_VERSION = 2;
10343
10514
  try {
@@ -10403,42 +10574,45 @@ var require_bootstrap = __commonJS({
10403
10574
  log.warn("Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated");
10404
10575
  }
10405
10576
  }
10406
- async function ensureTokenHashIndex(strapi2, log) {
10577
+ async function ensureSessionLookupIndexes(strapi2, log) {
10407
10578
  try {
10408
10579
  const knex = strapi2.db.connection;
10409
10580
  const tableName = "magic_sessions";
10410
- const indexName = "idx_magic_sessions_token_hash";
10411
- const hasIndex = await knex.schema.hasTable(tableName).then(async (exists) => {
10412
- if (!exists) return false;
10581
+ const definitions = [
10582
+ { column: "token_hash", name: "idx_magic_sessions_token_hash" },
10583
+ { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
10584
+ ];
10585
+ if (!await knex.schema.hasTable(tableName)) return;
10586
+ for (const definition of definitions) {
10413
10587
  const dialect = strapi2.db.dialect.client;
10588
+ let hasIndex = false;
10414
10589
  if (dialect === "postgres") {
10415
10590
  const result = await knex.raw(
10416
10591
  "SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?",
10417
- [tableName, indexName]
10592
+ [tableName, definition.name]
10418
10593
  );
10419
- return result.rows.length > 0;
10594
+ hasIndex = result.rows.length > 0;
10420
10595
  } else if (dialect === "mysql" || dialect === "mysql2") {
10421
- const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName, indexName]);
10422
- return result[0].length > 0;
10596
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName, definition.name]);
10597
+ hasIndex = result[0].length > 0;
10423
10598
  } else if (dialect === "sqlite" || dialect === "better-sqlite3") {
10424
10599
  const result = await knex.raw(
10425
10600
  "SELECT name FROM sqlite_master WHERE type='index' AND name = ?",
10426
- [indexName]
10601
+ [definition.name]
10427
10602
  );
10428
- return result.length > 0;
10603
+ hasIndex = result.length > 0;
10429
10604
  }
10430
- return false;
10431
- });
10432
- if (hasIndex) {
10433
- log.debug("[INDEX] tokenHash index already exists");
10434
- return;
10605
+ if (hasIndex) {
10606
+ log.debug(`[INDEX] ${definition.name} already exists`);
10607
+ continue;
10608
+ }
10609
+ await knex.schema.alterTable(tableName, (table) => {
10610
+ table.index([definition.column, "is_active"], definition.name);
10611
+ });
10612
+ log.info(`[INDEX] Created ${definition.name}`);
10435
10613
  }
10436
- await knex.schema.alterTable(tableName, (table) => {
10437
- table.index(["token_hash", "is_active"], indexName);
10438
- });
10439
- log.info("[INDEX] Created tokenHash index for O(1) session lookup");
10440
10614
  } catch (err) {
10441
- log.debug("[INDEX] Could not create tokenHash index (will retry on next startup):", err.message);
10615
+ log.debug("[INDEX] Could not create session lookup indexes (will retry on next startup):", err.message);
10442
10616
  }
10443
10617
  }
10444
10618
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
@@ -10530,6 +10704,16 @@ var require_bootstrap = __commonJS({
10530
10704
  fields: ["documentId", "isActive", "terminatedManually", "terminationReason", "lastActive", "loginTime"]
10531
10705
  });
10532
10706
  if (thisSession) {
10707
+ if (thisSession.isActive === false) {
10708
+ const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : null);
10709
+ if (reason) {
10710
+ strapi2.log.info(
10711
+ `[magic-sessionmanager] [JWT-REJECTED] Session inactive (reason: ${reason}) for user ${userDocId.substring(0, 8)}...`
10712
+ );
10713
+ setSessionRejectionReason(tokenHashValue, reason);
10714
+ return null;
10715
+ }
10716
+ }
10533
10717
  if (isSessionExpired(thisSession, maxSessionAgeDays)) {
10534
10718
  strapi2.log.info(
10535
10719
  `[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days (user: ${userDocId.substring(0, 8)}...)`
@@ -10546,20 +10730,6 @@ var require_bootstrap = __commonJS({
10546
10730
  setSessionRejectionReason(tokenHashValue, "expired");
10547
10731
  return null;
10548
10732
  }
10549
- if (thisSession.isActive === false) {
10550
- const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : null);
10551
- if (reason) {
10552
- strapi2.log.info(
10553
- `[magic-sessionmanager] [JWT-REJECTED] Session inactive (reason: ${reason}) for user ${userDocId.substring(0, 8)}...`
10554
- );
10555
- setSessionRejectionReason(tokenHashValue, reason);
10556
- return null;
10557
- }
10558
- }
10559
- if (thisSession.isActive) {
10560
- resetErrorCounter();
10561
- return decoded;
10562
- }
10563
10733
  const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
10564
10734
  const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
10565
10735
  const idleFor = Date.now() - lastActiveMs;
@@ -10570,6 +10740,7 @@ var require_bootstrap = __commonJS({
10570
10740
  await strapi2.documents(SESSION_UID).update({
10571
10741
  documentId: thisSession.documentId,
10572
10742
  data: {
10743
+ isActive: false,
10573
10744
  terminatedManually: false,
10574
10745
  terminationReason: "idle",
10575
10746
  logoutTime: /* @__PURE__ */ new Date()
@@ -10578,6 +10749,10 @@ var require_bootstrap = __commonJS({
10578
10749
  setSessionRejectionReason(tokenHashValue, "idle");
10579
10750
  return null;
10580
10751
  }
10752
+ if (thisSession.isActive) {
10753
+ resetErrorCounter();
10754
+ return decoded;
10755
+ }
10581
10756
  await strapi2.documents(SESSION_UID).update({
10582
10757
  documentId: thisSession.documentId,
10583
10758
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
@@ -10627,6 +10802,14 @@ var require_bootstrap = __commonJS({
10627
10802
  strapi2.log.warn("[magic-sessionmanager] [AUTH] Session validation will only work via middleware (plugin endpoints)");
10628
10803
  }
10629
10804
  }
10805
+ module.exports.__private = {
10806
+ registerSessionAwareAuthStrategy,
10807
+ mountPreLoginGeoGuard,
10808
+ mountLoginInterceptor,
10809
+ mountRefreshTokenInterceptor,
10810
+ mountLogoutInterceptor,
10811
+ mountLogoutRoute
10812
+ };
10630
10813
  }
10631
10814
  });
10632
10815
 
@@ -10667,6 +10850,12 @@ var require_config = __commonJS({
10667
10850
  cleanupInterval: 30 * 60 * 1e3,
10668
10851
  retentionDays: 90,
10669
10852
  maxSessionAgeDays: 30,
10853
+ maxFailedLogins: 5,
10854
+ sessionCreationGraceMs: 5e3,
10855
+ cleanupUseDbDirect: false,
10856
+ rateLimitWriteMax: 10,
10857
+ rateLimitReadMax: 120,
10858
+ rateLimitWindowSeconds: 60,
10670
10859
  strictSessionEnforcement: false,
10671
10860
  enableGeolocation: true,
10672
10861
  enableSecurityScoring: true,
@@ -10804,7 +10993,7 @@ var require_schema = __commonJS({
10804
10993
  },
10805
10994
  terminationReason: {
10806
10995
  type: "enumeration",
10807
- enum: ["manual", "idle", "expired", "blocked"],
10996
+ enum: ["logout", "manual", "idle", "expired", "blocked"],
10808
10997
  required: false
10809
10998
  },
10810
10999
  geoLocation: {
@@ -11265,6 +11454,9 @@ var require_enhance_session = __commonJS({
11265
11454
  "use strict";
11266
11455
  var { parseUserAgent } = require_user_agent_parser();
11267
11456
  var SESSION_UID = "plugin::magic-sessionmanager.session";
11457
+ function shouldResolveGeoData(settings = {}) {
11458
+ return settings.enableGeolocation === true || settings.enableGeofencing === true || settings.blockSuspiciousSessions === true;
11459
+ }
11268
11460
  async function enhanceSession(session, opts = {}) {
11269
11461
  const {
11270
11462
  inactivityTimeout = 15 * 60 * 1e3,
@@ -11316,7 +11508,7 @@ var require_enhance_session = __commonJS({
11316
11508
  documentId: session.documentId,
11317
11509
  data: {
11318
11510
  geoLocation,
11319
- securityScore: geoData.securityScore || null
11511
+ securityScore: geoData.securityScore ?? null
11320
11512
  }
11321
11513
  }).catch(() => {
11322
11514
  });
@@ -11353,7 +11545,7 @@ var require_enhance_session = __commonJS({
11353
11545
  sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now }))
11354
11546
  );
11355
11547
  }
11356
- module.exports = { enhanceSession, enhanceSessions };
11548
+ module.exports = { enhanceSession, enhanceSessions, shouldResolveGeoData };
11357
11549
  }
11358
11550
  });
11359
11551
 
@@ -11362,7 +11554,11 @@ var require_session = __commonJS({
11362
11554
  "server/src/controllers/session.js"(exports, module) {
11363
11555
  "use strict";
11364
11556
  var { hashToken } = require_encryption();
11365
- var { enhanceSessions, enhanceSession } = require_enhance_session();
11557
+ var {
11558
+ enhanceSessions,
11559
+ enhanceSession,
11560
+ shouldResolveGeoData
11561
+ } = require_enhance_session();
11366
11562
  var { resolveUserDocumentId } = require_resolve_user();
11367
11563
  var {
11368
11564
  getPluginSettings,
@@ -11440,7 +11636,7 @@ var require_session = __commonJS({
11440
11636
  const settings = await getPluginSettings(strapi);
11441
11637
  const enhanceOpts = {
11442
11638
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
11443
- geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
11639
+ geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
11444
11640
  strapi
11445
11641
  };
11446
11642
  const sessionsWithCurrent = await enhanceSessions(paged, enhanceOpts, 20);
@@ -11524,7 +11720,7 @@ var require_session = __commonJS({
11524
11720
  if (matchingSession) {
11525
11721
  await sessionService.terminateSession({
11526
11722
  sessionId: matchingSession.documentId,
11527
- reason: "manual"
11723
+ reason: "logout"
11528
11724
  });
11529
11725
  terminated = true;
11530
11726
  strapi.log.info(`[magic-sessionmanager] User ${userDocId} logged out (session ${matchingSession.documentId})`);
@@ -11542,7 +11738,7 @@ var require_session = __commonJS({
11542
11738
  * Terminates EVERY session of the authenticated user — including the
11543
11739
  * current one. After this call the caller will also be logged out on
11544
11740
  * the next request (their own JWT is rejected by the JWT-verify wrapper
11545
- * with reason=manual).
11741
+ * with reason=logout).
11546
11742
  *
11547
11743
  * For the "log me out everywhere ELSE but keep me here" flow, use
11548
11744
  * `/logout-others` below.
@@ -11558,7 +11754,7 @@ var require_session = __commonJS({
11558
11754
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
11559
11755
  const { terminatedCount } = await sessionService.terminateSession({
11560
11756
  userId: userDocId,
11561
- reason: "manual"
11757
+ reason: "logout"
11562
11758
  });
11563
11759
  strapi.log.info(
11564
11760
  `[magic-sessionmanager] User ${userDocId} logged out from all devices (${terminatedCount})`
@@ -11602,7 +11798,7 @@ var require_session = __commonJS({
11602
11798
  if (!currentSession) {
11603
11799
  const { terminatedCount: terminatedCount2 } = await sessionService.terminateSession({
11604
11800
  userId: userDocId,
11605
- reason: "manual"
11801
+ reason: "logout"
11606
11802
  });
11607
11803
  strapi.log.warn(
11608
11804
  `[magic-sessionmanager] logoutOthers fell back to logoutAll for user ${userDocId} (no current session match)`
@@ -11617,7 +11813,7 @@ var require_session = __commonJS({
11617
11813
  const { terminatedCount } = await sessionService.terminateSession({
11618
11814
  userId: userDocId,
11619
11815
  exceptSessionId: currentSession.documentId,
11620
- reason: "manual"
11816
+ reason: "logout"
11621
11817
  });
11622
11818
  strapi.log.info(
11623
11819
  `[magic-sessionmanager] User ${userDocId} logged out ${terminatedCount} other device(s)`
@@ -11678,7 +11874,7 @@ var require_session = __commonJS({
11678
11874
  const settings = await getPluginSettings(strapi);
11679
11875
  const enhanced = await enhanceSession(currentSession, {
11680
11876
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
11681
- geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
11877
+ geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
11682
11878
  geoCounter: { remaining: 1 },
11683
11879
  strapi
11684
11880
  });
@@ -12234,6 +12430,55 @@ var require_settings = __commonJS({
12234
12430
  }
12235
12431
  return result;
12236
12432
  }
12433
+ var DEFAULT_EMAIL_TEMPLATES = {
12434
+ suspiciousLogin: { subject: "", html: "", text: "" },
12435
+ newLocation: { subject: "", html: "", text: "" },
12436
+ vpnProxy: { subject: "", html: "", text: "" }
12437
+ };
12438
+ var DEFAULT_SETTINGS = {
12439
+ inactivityTimeout: 15,
12440
+ cleanupInterval: 30,
12441
+ lastSeenRateLimit: 30,
12442
+ retentionDays: 90,
12443
+ maxSessionAgeDays: 30,
12444
+ sessionCreationGraceMs: 5e3,
12445
+ cleanupUseDbDirect: false,
12446
+ rateLimitWriteMax: 10,
12447
+ rateLimitReadMax: 120,
12448
+ rateLimitWindowSeconds: 60,
12449
+ enableGeolocation: true,
12450
+ enableSecurityScoring: true,
12451
+ blockSuspiciousSessions: false,
12452
+ maxFailedLogins: 5,
12453
+ enableGeofencing: false,
12454
+ allowedCountries: [],
12455
+ blockedCountries: [],
12456
+ geoIpProvider: "auto",
12457
+ geoIpDatabasePath: "",
12458
+ geoLookupFailureMode: "auto",
12459
+ enableEmailAlerts: false,
12460
+ alertOnSuspiciousLogin: true,
12461
+ alertOnNewLocation: true,
12462
+ alertOnVpnProxy: true,
12463
+ enableWebhooks: false,
12464
+ discordWebhookUrl: "",
12465
+ slackWebhookUrl: "",
12466
+ strictSessionEnforcement: false,
12467
+ trustedProxies: false,
12468
+ emailTemplates: DEFAULT_EMAIL_TEMPLATES
12469
+ };
12470
+ function mergeSettingsWithDefaults(stored) {
12471
+ const safeStored = stored && typeof stored === "object" ? stored : {};
12472
+ const storedTemplates = safeStored.emailTemplates && typeof safeStored.emailTemplates === "object" ? safeStored.emailTemplates : {};
12473
+ return {
12474
+ ...DEFAULT_SETTINGS,
12475
+ ...safeStored,
12476
+ emailTemplates: {
12477
+ ...DEFAULT_EMAIL_TEMPLATES,
12478
+ ...storedTemplates
12479
+ }
12480
+ };
12481
+ }
12237
12482
  module.exports = {
12238
12483
  /**
12239
12484
  * Returns the current plugin settings (user-facing units: minutes/seconds/days).
@@ -12245,51 +12490,8 @@ var require_settings = __commonJS({
12245
12490
  type: "plugin",
12246
12491
  name: "magic-sessionmanager"
12247
12492
  });
12248
- let settings = await pluginStore.get({ key: "settings" });
12249
- if (!settings) {
12250
- settings = {
12251
- // Timing & cleanup
12252
- inactivityTimeout: 15,
12253
- cleanupInterval: 30,
12254
- lastSeenRateLimit: 30,
12255
- retentionDays: 90,
12256
- maxSessionAgeDays: 30,
12257
- // Grace window (ms) during which a freshly-issued JWT is accepted
12258
- // without a matching session row — see JWT-verify wrapper in bootstrap.
12259
- sessionCreationGraceMs: 5e3,
12260
- // Opt-in: use a single SQL UPDATE for idle-session cleanup
12261
- // (bypasses Document Service lifecycle, required for very large installs).
12262
- cleanupUseDbDirect: false,
12263
- // Geo / security
12264
- enableGeolocation: true,
12265
- enableSecurityScoring: true,
12266
- blockSuspiciousSessions: false,
12267
- maxFailedLogins: 5,
12268
- enableGeofencing: false,
12269
- allowedCountries: [],
12270
- blockedCountries: [],
12271
- geoIpProvider: "auto",
12272
- geoIpDatabasePath: "",
12273
- geoLookupFailureMode: "auto",
12274
- // Notifications
12275
- enableEmailAlerts: false,
12276
- alertOnSuspiciousLogin: true,
12277
- alertOnNewLocation: true,
12278
- alertOnVpnProxy: true,
12279
- enableWebhooks: false,
12280
- discordWebhookUrl: "",
12281
- slackWebhookUrl: "",
12282
- // Session policy
12283
- strictSessionEnforcement: false,
12284
- trustedProxies: false,
12285
- // Email templates
12286
- emailTemplates: {
12287
- suspiciousLogin: { subject: "", html: "", text: "" },
12288
- newLocation: { subject: "", html: "", text: "" },
12289
- vpnProxy: { subject: "", html: "", text: "" }
12290
- }
12291
- };
12292
- }
12493
+ const storedSettings = await pluginStore.get({ key: "settings" });
12494
+ const settings = mergeSettingsWithDefaults(storedSettings);
12293
12495
  ctx.send({
12294
12496
  settings,
12295
12497
  success: true
@@ -12327,6 +12529,9 @@ var require_settings = __commonJS({
12327
12529
  maxSessionAgeDays: Math.max(1, Math.min(parseInt(body.maxSessionAgeDays) || 30, 365)),
12328
12530
  sessionCreationGraceMs: grace,
12329
12531
  cleanupUseDbDirect: !!body.cleanupUseDbDirect,
12532
+ rateLimitWriteMax: Math.max(1, Math.min(parseInt(body.rateLimitWriteMax) || 10, 1e3)),
12533
+ rateLimitReadMax: Math.max(1, Math.min(parseInt(body.rateLimitReadMax) || 120, 1e4)),
12534
+ rateLimitWindowSeconds: Math.max(10, Math.min(parseInt(body.rateLimitWindowSeconds) || 60, 3600)),
12330
12535
  // Geo / security
12331
12536
  enableGeolocation: !!body.enableGeolocation,
12332
12537
  enableSecurityScoring: !!body.enableSecurityScoring,
@@ -12367,7 +12572,9 @@ var require_settings = __commonJS({
12367
12572
  strapi.log.error("[magic-sessionmanager/settings] Error updating settings:", error);
12368
12573
  ctx.badRequest("Error saving settings");
12369
12574
  }
12370
- }
12575
+ },
12576
+ DEFAULT_SETTINGS,
12577
+ mergeSettingsWithDefaults
12371
12578
  };
12372
12579
  }
12373
12580
  });
@@ -12761,17 +12968,20 @@ var require_session2 = __commonJS({
12761
12968
  var { createLogger } = require_logger();
12762
12969
  var { parseUserAgent } = require_user_agent_parser();
12763
12970
  var { resolveUserDocumentId } = require_resolve_user();
12764
- var { enhanceSessions } = require_enhance_session();
12971
+ var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
12765
12972
  var { getPluginSettings } = require_settings_loader();
12766
12973
  var SESSION_UID = "plugin::magic-sessionmanager.session";
12767
12974
  var MAX_SESSIONS_QUERY = 1e3;
12975
+ async function lockSessionRow(trx, documentId) {
12976
+ await trx("magic_sessions").where({ document_id: documentId }).forUpdate().first("document_id");
12977
+ }
12768
12978
  module.exports = ({ strapi: strapi2 }) => {
12769
12979
  const log = createLogger(strapi2);
12770
12980
  async function getEnhanceOpts() {
12771
12981
  const settings = await getPluginSettings(strapi2);
12772
12982
  return {
12773
12983
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
12774
- geolocationService: strapi2.plugin("magic-sessionmanager").service("geolocation"),
12984
+ geolocationService: shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null,
12775
12985
  strapi: strapi2
12776
12986
  };
12777
12987
  }
@@ -12826,7 +13036,7 @@ var require_session2 = __commonJS({
12826
13036
  region: geoData.region,
12827
13037
  timezone: geoData.timezone
12828
13038
  } : null,
12829
- securityScore: geoData?.securityScore || null
13039
+ securityScore: geoData?.securityScore ?? null
12830
13040
  }
12831
13041
  });
12832
13042
  log.info(`[SUCCESS] Session ${session.documentId} (${sessionId}) created for user ${userId}`);
@@ -12836,19 +13046,118 @@ var require_session2 = __commonJS({
12836
13046
  throw err;
12837
13047
  }
12838
13048
  },
13049
+ /**
13050
+ * Atomically replaces the stored tokens only while the caller still owns
13051
+ * the expected active token. This prevents two concurrent refresh
13052
+ * requests from both committing a rotation.
13053
+ *
13054
+ * @returns {Promise<boolean>} Whether exactly one session was rotated
13055
+ */
13056
+ async rotateSessionTokens({
13057
+ sessionId,
13058
+ expectedAccessToken,
13059
+ expectedRefreshToken,
13060
+ accessToken,
13061
+ refreshToken
13062
+ }) {
13063
+ if (!sessionId || !accessToken || !expectedAccessToken && !expectedRefreshToken) {
13064
+ return false;
13065
+ }
13066
+ const where = { documentId: sessionId, isActive: true };
13067
+ if (expectedAccessToken) where.tokenHash = hashToken(expectedAccessToken);
13068
+ if (expectedRefreshToken) where.refreshTokenHash = hashToken(expectedRefreshToken);
13069
+ const data = {
13070
+ token: encryptToken(accessToken),
13071
+ tokenHash: hashToken(accessToken),
13072
+ lastActive: /* @__PURE__ */ new Date()
13073
+ };
13074
+ if (refreshToken) {
13075
+ data.refreshToken = encryptToken(refreshToken);
13076
+ data.refreshTokenHash = hashToken(refreshToken);
13077
+ }
13078
+ const result = await strapi2.db.query(SESSION_UID).updateMany({ where, data });
13079
+ return result?.count === 1;
13080
+ },
13081
+ /**
13082
+ * Terminates the active session identified by a raw refresh token.
13083
+ * Used by Strapi's built-in cookie/body logout endpoint.
13084
+ */
13085
+ async terminateSessionByRefreshToken(refreshToken) {
13086
+ if (!refreshToken) return false;
13087
+ const result = await strapi2.db.query(SESSION_UID).updateMany({
13088
+ where: {
13089
+ refreshTokenHash: hashToken(refreshToken),
13090
+ isActive: true
13091
+ },
13092
+ data: {
13093
+ isActive: false,
13094
+ terminatedManually: false,
13095
+ terminationReason: "logout",
13096
+ logoutTime: /* @__PURE__ */ new Date()
13097
+ }
13098
+ });
13099
+ return result?.count === 1;
13100
+ },
13101
+ /**
13102
+ * Terminates the authenticated user's active session. A raw access token
13103
+ * is authoritative when present, and a supplied refresh token must match
13104
+ * the same row. Refresh-token-only lookup is used when access is absent.
13105
+ *
13106
+ * @param {Object} params
13107
+ * @param {string} params.userDocumentId - Authenticated user's documentId
13108
+ * @param {string|null} [params.refreshToken=null] - Raw refresh token
13109
+ * @param {string|null} [params.accessToken=null] - Raw access token
13110
+ * @returns {Promise<boolean>} Whether one owned active session was terminated
13111
+ * @throws {Error} When the Document Service lookup or termination fails
13112
+ * @sideeffect Marks the matching session inactive with logout metadata
13113
+ */
13114
+ async terminateAuthenticatedSession({
13115
+ userDocumentId,
13116
+ refreshToken = null,
13117
+ accessToken = null
13118
+ }) {
13119
+ if (!userDocumentId || !refreshToken && !accessToken) return false;
13120
+ const selectedTokenFilters = {
13121
+ user: { documentId: userDocumentId },
13122
+ isActive: true
13123
+ };
13124
+ if (accessToken) {
13125
+ selectedTokenFilters.tokenHash = hashToken(accessToken);
13126
+ if (refreshToken) {
13127
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13128
+ }
13129
+ } else {
13130
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13131
+ }
13132
+ const session = await strapi2.documents(SESSION_UID).findFirst({
13133
+ filters: selectedTokenFilters,
13134
+ fields: ["documentId"]
13135
+ });
13136
+ if (!session) return false;
13137
+ return strapi2.db.transaction(async ({ trx }) => {
13138
+ await lockSessionRow(trx, session.documentId);
13139
+ const result = await this.terminateSession({
13140
+ sessionId: session.documentId,
13141
+ reason: "logout",
13142
+ expectedFilters: selectedTokenFilters
13143
+ });
13144
+ return result?.terminatedCount === 1;
13145
+ });
13146
+ },
12839
13147
  /**
12840
13148
  * Terminates a single session, all sessions of a user, or all sessions
12841
13149
  * of a user EXCEPT one with a typed reason so the JWT-verify wrapper
12842
13150
  * can communicate the cause to the client.
12843
13151
  *
12844
13152
  * Supported reasons:
12845
- * - 'manual': user clicked logout, or admin terminated a session
13153
+ * - 'logout': user clicked logout
13154
+ * - 'manual': admin terminated a session
12846
13155
  * - 'idle': inactivity timeout cleanup
12847
13156
  * - 'expired': maxSessionAgeDays exceeded
12848
13157
  * - 'blocked': the owning user was marked blocked
12849
13158
  *
12850
13159
  * For backwards compatibility `terminatedManually` is still set true
12851
- * only when reason === 'manual'; idle/expired/blocked paths set it
13160
+ * only when reason === 'manual'; logout/idle/expired/blocked paths set it
12852
13161
  * false so reporting dashboards that queried that boolean continue
12853
13162
  * to work, while new code relies on `terminationReason`.
12854
13163
  *
@@ -12861,13 +13170,22 @@ var require_session2 = __commonJS({
12861
13170
  * `userId`. Used by
12862
13171
  * /logout-other-devices so
12863
13172
  * the caller stays logged in.
12864
- * @param {'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
13173
+ * @param {object} [params.expectedFilters] Internal predicates that must
13174
+ * still match before a
13175
+ * single-session update.
13176
+ * @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
12865
13177
  * @returns {Promise<{terminatedCount: number}>}
12866
13178
  */
12867
- async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
13179
+ async terminateSession({
13180
+ sessionId,
13181
+ userId,
13182
+ exceptSessionId = null,
13183
+ reason = "manual",
13184
+ expectedFilters = null
13185
+ }) {
12868
13186
  try {
12869
13187
  const now = /* @__PURE__ */ new Date();
12870
- const validReasons = ["manual", "idle", "expired", "blocked"];
13188
+ const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
12871
13189
  const finalReason = validReasons.includes(reason) ? reason : "manual";
12872
13190
  const updateData = {
12873
13191
  isActive: false,
@@ -12876,7 +13194,13 @@ var require_session2 = __commonJS({
12876
13194
  logoutTime: now
12877
13195
  };
12878
13196
  if (sessionId) {
12879
- const existing = await strapi2.documents(SESSION_UID).findOne({
13197
+ const existing = expectedFilters ? await strapi2.documents(SESSION_UID).findFirst({
13198
+ filters: {
13199
+ ...expectedFilters,
13200
+ documentId: sessionId
13201
+ },
13202
+ fields: ["documentId"]
13203
+ }) : await strapi2.documents(SESSION_UID).findOne({
12880
13204
  documentId: sessionId,
12881
13205
  fields: ["documentId"]
12882
13206
  });
@@ -12898,21 +13222,31 @@ var require_session2 = __commonJS({
12898
13222
  if (exceptSessionId) {
12899
13223
  filters.documentId = { $ne: exceptSessionId };
12900
13224
  }
12901
- const activeSessions = await strapi2.documents(SESSION_UID).findMany({
12902
- filters,
12903
- fields: ["documentId"],
12904
- limit: MAX_SESSIONS_QUERY
12905
- });
12906
13225
  let terminatedCount = 0;
12907
- for (const session of activeSessions) {
12908
- try {
12909
- await strapi2.documents(SESSION_UID).update({
12910
- documentId: session.documentId,
12911
- data: updateData
12912
- });
12913
- terminatedCount++;
12914
- } catch (err) {
12915
- log.debug(`Failed to terminate session ${session.documentId}:`, err.message);
13226
+ const batchSize = 500;
13227
+ while (true) {
13228
+ const activeSessions = await strapi2.documents(SESSION_UID).findMany({
13229
+ filters,
13230
+ fields: ["documentId"],
13231
+ limit: batchSize
13232
+ });
13233
+ if (!activeSessions || activeSessions.length === 0) break;
13234
+ let batchTerminated = 0;
13235
+ for (const session of activeSessions) {
13236
+ try {
13237
+ await strapi2.documents(SESSION_UID).update({
13238
+ documentId: session.documentId,
13239
+ data: updateData
13240
+ });
13241
+ terminatedCount++;
13242
+ batchTerminated++;
13243
+ } catch (err) {
13244
+ log.debug(`Failed to terminate session ${session.documentId}:`, err.message);
13245
+ }
13246
+ }
13247
+ if (batchTerminated === 0) {
13248
+ log.warn(`Could not terminate remaining active sessions for user ${userDocumentId}`);
13249
+ break;
12916
13250
  }
12917
13251
  }
12918
13252
  const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
@@ -13298,7 +13632,7 @@ var require_session2 = __commonJS({
13298
13632
  var require_package = __commonJS({
13299
13633
  "package.json"(exports, module) {
13300
13634
  module.exports = {
13301
- version: "4.7.0",
13635
+ version: "4.7.2",
13302
13636
  keywords: [
13303
13637
  "strapi",
13304
13638
  "plugin",
@@ -13356,7 +13690,7 @@ var require_package = __commonJS({
13356
13690
  },
13357
13691
  dependencies: {
13358
13692
  "@maxmind/geoip2-node": "^6.3.4",
13359
- "sanitize-html": "^2.17.5"
13693
+ "sanitize-html": "^2.17.6"
13360
13694
  },
13361
13695
  devDependencies: {
13362
13696
  "@semantic-release/changelog": "^6.0.3",