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
@@ -88,7 +88,6 @@ var require_register = __commonJS({
88
88
  "use strict";
89
89
  var { createLogger } = require_logger();
90
90
  var USER_UID = "plugin::users-permissions.user";
91
- var SESSION_UID = "plugin::magic-sessionmanager.session";
92
91
  module2.exports = async ({ strapi: strapi2 }) => {
93
92
  const log = createLogger(strapi2);
94
93
  log.info("[START] Plugin registration starting...");
@@ -135,34 +134,11 @@ var require_register = __commonJS({
135
134
  if (!data || data.blocked !== true) return;
136
135
  const userDocId = result.documentId;
137
136
  if (!userDocId) return;
138
- const activeSessions = await strapi2.documents(SESSION_UID).findMany({
139
- filters: { user: { documentId: userDocId }, isActive: true },
140
- fields: ["documentId"],
141
- limit: 1e3
137
+ const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
138
+ const { terminatedCount: terminated } = await sessionService.terminateSession({
139
+ userId: userDocId,
140
+ reason: "blocked"
142
141
  });
143
- if (!activeSessions || activeSessions.length === 0) return;
144
- const now = /* @__PURE__ */ new Date();
145
- let terminated = 0;
146
- for (const session of activeSessions) {
147
- try {
148
- await strapi2.documents(SESSION_UID).update({
149
- documentId: session.documentId,
150
- data: {
151
- isActive: false,
152
- // Blocked users are NOT a "manual" self-logout — mark
153
- // this distinctly so the client receives a different
154
- // error message ("account blocked") rather than
155
- // "session terminated".
156
- terminatedManually: false,
157
- terminationReason: "blocked",
158
- logoutTime: now
159
- }
160
- });
161
- terminated++;
162
- } catch (updateErr) {
163
- log.warn(`[lifecycle] failed to terminate session ${session.documentId}:`, updateErr.message);
164
- }
165
- }
166
142
  if (terminated > 0) {
167
143
  log.info(`[lifecycle] Terminated ${terminated} session(s) for blocked user ${userDocId.substring(0, 8)}...`);
168
144
  }
@@ -636,10 +612,10 @@ var require_geo_firewall = __commonJS({
636
612
  if (geoData.isThreat) {
637
613
  return { blocked: true, reason: "threat_ip", status };
638
614
  }
639
- if (geoData.isVpn && settings.alertOnVpnProxy !== false) {
615
+ if (geoData.isVpn) {
640
616
  return { blocked: true, reason: "vpn_detected", status };
641
617
  }
642
- if (geoData.isProxy && settings.alertOnVpnProxy !== false) {
618
+ if (geoData.isProxy) {
643
619
  return { blocked: true, reason: "proxy_detected", status };
644
620
  }
645
621
  if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < 50) {
@@ -679,6 +655,148 @@ var require_geo_firewall = __commonJS({
679
655
  }
680
656
  });
681
657
 
658
+ // server/src/utils/auth-routes.js
659
+ var require_auth_routes = __commonJS({
660
+ "server/src/utils/auth-routes.js"(exports2, module2) {
661
+ "use strict";
662
+ var NEW_SESSION_ROUTES = /* @__PURE__ */ new Set([
663
+ "POST /api/auth/local",
664
+ "POST /api/auth/local/register",
665
+ "POST /api/auth/reset-password",
666
+ "GET /api/auth/email-confirmation",
667
+ "POST /api/auth/email-confirmation",
668
+ "POST /api/magic-link/verify-mfa-totp",
669
+ "POST /api/magic-link/otp/verify",
670
+ "POST /api/magic-link/login-totp"
671
+ ]);
672
+ var FAILED_LOGIN_ROUTES = /* @__PURE__ */ new Set([
673
+ "POST /api/auth/local",
674
+ "POST /api/magic-link/login-totp",
675
+ "POST /api/magic-link/otp/verify",
676
+ "POST /api/magic-link/verify-mfa-totp"
677
+ ]);
678
+ function requestKey(path, method) {
679
+ return `${String(method || "").toUpperCase()} ${path || ""}`;
680
+ }
681
+ function isMagicLinkLogin(path, method) {
682
+ const normalizedMethod = String(method || "").toUpperCase();
683
+ return typeof path === "string" && path.startsWith("/api/magic-link/login") && (normalizedMethod === "GET" || normalizedMethod === "POST");
684
+ }
685
+ function classifyJwtIssuingRequest(path, method) {
686
+ const normalizedMethod = String(method || "").toUpperCase();
687
+ const key = requestKey(path, normalizedMethod);
688
+ if (key === "POST /api/auth/refresh") return "refresh";
689
+ if (key === "POST /api/auth/change-password") return "rotate-current";
690
+ if (NEW_SESSION_ROUTES.has(key)) return "new-session";
691
+ if (normalizedMethod === "GET" && /^\/api\/auth\/[a-z0-9-]+\/callback$/i.test(path || "")) {
692
+ return "new-session";
693
+ }
694
+ if (isMagicLinkLogin(path, normalizedMethod)) return "new-session";
695
+ if (typeof path === "string" && path.startsWith("/api/passwordless/") && (normalizedMethod === "GET" || normalizedMethod === "POST")) {
696
+ return "new-session";
697
+ }
698
+ return null;
699
+ }
700
+ function shouldRunPreAuthGeoGuard(path, method) {
701
+ return classifyJwtIssuingRequest(path, method) === "new-session";
702
+ }
703
+ function isFailedLoginTrackedPath(path, method) {
704
+ return FAILED_LOGIN_ROUTES.has(requestKey(path, method)) || isMagicLinkLogin(path, method);
705
+ }
706
+ module2.exports = {
707
+ classifyJwtIssuingRequest,
708
+ isFailedLoginTrackedPath,
709
+ shouldRunPreAuthGeoGuard
710
+ };
711
+ }
712
+ });
713
+
714
+ // server/src/utils/refresh-token.js
715
+ var require_refresh_token = __commonJS({
716
+ "server/src/utils/refresh-token.js"(exports2, module2) {
717
+ "use strict";
718
+ var DEFAULT_REFRESH_COOKIE_NAME = "strapi_up_refresh";
719
+ function getRefreshCookieName(strapi2) {
720
+ try {
721
+ return strapi2.config.get(
722
+ "plugin::users-permissions.sessions.cookie.name",
723
+ DEFAULT_REFRESH_COOKIE_NAME
724
+ ) || DEFAULT_REFRESH_COOKIE_NAME;
725
+ } catch {
726
+ return DEFAULT_REFRESH_COOKIE_NAME;
727
+ }
728
+ }
729
+ function getIncomingRefreshToken(ctx, cookieName = DEFAULT_REFRESH_COOKIE_NAME) {
730
+ const bodyToken = ctx?.request?.body?.refreshToken;
731
+ if (typeof bodyToken === "string" && bodyToken.length > 0) return bodyToken;
732
+ try {
733
+ const cookieToken = ctx?.cookies?.get(cookieName);
734
+ return typeof cookieToken === "string" && cookieToken.length > 0 ? cookieToken : null;
735
+ } catch {
736
+ return null;
737
+ }
738
+ }
739
+ function getSetCookieHeaders(ctx) {
740
+ const headers = ctx?.response?.headers || ctx?.response?.header || {};
741
+ const raw = headers["set-cookie"] || headers["Set-Cookie"];
742
+ if (!raw) return [];
743
+ return Array.isArray(raw) ? raw : [raw];
744
+ }
745
+ function parseCookieValue(header, cookieName) {
746
+ if (typeof header !== "string") return null;
747
+ const firstPart = header.split(";", 1)[0].trim();
748
+ const separator = firstPart.indexOf("=");
749
+ if (separator < 1 || firstPart.slice(0, separator) !== cookieName) return null;
750
+ const rawValue = firstPart.slice(separator + 1);
751
+ try {
752
+ return decodeURIComponent(rawValue);
753
+ } catch {
754
+ return rawValue;
755
+ }
756
+ }
757
+ function getOutgoingRefreshToken(ctx, cookieName = DEFAULT_REFRESH_COOKIE_NAME) {
758
+ const bodyToken = ctx?.body?.refreshToken;
759
+ if (typeof bodyToken === "string" && bodyToken.length > 0) return bodyToken;
760
+ for (const header of getSetCookieHeaders(ctx)) {
761
+ const value = parseCookieValue(header, cookieName);
762
+ if (value) return value;
763
+ }
764
+ return null;
765
+ }
766
+ function stripAuthTokensFromResponse(ctx, cookieName = DEFAULT_REFRESH_COOKIE_NAME) {
767
+ if (ctx?.body && typeof ctx.body === "object" && !Buffer.isBuffer(ctx.body)) {
768
+ delete ctx.body.jwt;
769
+ delete ctx.body.refreshToken;
770
+ }
771
+ const remainingCookies = getSetCookieHeaders(ctx).filter(
772
+ (header) => parseCookieValue(header, cookieName) === null
773
+ );
774
+ if (typeof ctx?.remove === "function") {
775
+ ctx.remove("Set-Cookie");
776
+ for (const header of remainingCookies) {
777
+ if (typeof ctx.append === "function") ctx.append("Set-Cookie", header);
778
+ }
779
+ return;
780
+ }
781
+ const headers = ctx?.response?.headers || ctx?.response?.header;
782
+ if (!headers) return;
783
+ delete headers["Set-Cookie"];
784
+ if (remainingCookies.length > 0) {
785
+ headers["set-cookie"] = remainingCookies;
786
+ } else {
787
+ delete headers["set-cookie"];
788
+ }
789
+ }
790
+ module2.exports = {
791
+ DEFAULT_REFRESH_COOKIE_NAME,
792
+ getRefreshCookieName,
793
+ getIncomingRefreshToken,
794
+ getOutgoingRefreshToken,
795
+ stripAuthTokensFromResponse
796
+ };
797
+ }
798
+ });
799
+
682
800
  // server/src/middlewares/session-rejection-headers.js
683
801
  var require_session_rejection_headers = __commonJS({
684
802
  "server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
@@ -688,6 +806,7 @@ var require_session_rejection_headers = __commonJS({
688
806
  var { consumeSessionRejectionReason } = require_rejection_cache();
689
807
  var HEADER = "X-Session-Terminated-Reason";
690
808
  var REASON_MESSAGES = {
809
+ logout: "You have logged out. Please log in again.",
691
810
  manual: "Your session was terminated. Please log in again.",
692
811
  idle: "Your session expired due to inactivity. Please log in again.",
693
812
  expired: "Your session has reached its maximum age. Please log in again.",
@@ -732,10 +851,6 @@ var require_last_seen = __commonJS({
732
851
  "server/src/middlewares/last-seen.js"(exports2, module2) {
733
852
  "use strict";
734
853
  var { resolveUserDocumentId } = require_resolve_user();
735
- var {
736
- getPluginSettings,
737
- getSessionCreationGraceMs
738
- } = require_settings_loader();
739
854
  var { extractBearerToken } = require_extract_token();
740
855
  var { hashToken } = require_encryption();
741
856
  var SESSION_UID = "plugin::magic-sessionmanager.session";
@@ -765,8 +880,12 @@ var require_last_seen = __commonJS({
765
880
  if (isAuthEndpoint(ctx.path)) {
766
881
  return next();
767
882
  }
883
+ await next();
884
+ if (isSelfTerminatingEndpoint(ctx.path) || (ctx.status || 200) >= 400) {
885
+ return;
886
+ }
768
887
  if (!ctx.state.user) {
769
- return next();
888
+ return;
770
889
  }
771
890
  let userDocId = ctx.state.user.documentId;
772
891
  if (!userDocId && ctx.state.user.id) {
@@ -774,67 +893,38 @@ var require_last_seen = __commonJS({
774
893
  userDocId = await resolveUserDocumentId(strapi2, ctx.state.user.id);
775
894
  } catch (err) {
776
895
  strapi2.log.debug("[magic-sessionmanager] user doc-id lookup failed:", err.message);
777
- return next();
896
+ return;
778
897
  }
779
898
  }
780
899
  if (!userDocId) {
781
- return next();
900
+ return;
782
901
  }
783
- const settings = await getPluginSettings(strapi2).catch(() => ({}));
784
- const strictMode = settings.strictSessionEnforcement === true;
785
- const gracePeriodMs = getSessionCreationGraceMs(settings);
786
902
  const token = extractBearerToken(ctx);
787
903
  const tokenHashValue = token ? hashToken(token) : null;
788
- let thisSession = null;
789
- if (tokenHashValue) {
790
- try {
791
- thisSession = await strapi2.documents(SESSION_UID).findFirst({
792
- filters: { user: { documentId: userDocId }, tokenHash: tokenHashValue },
793
- fields: ["documentId", "isActive", "terminatedManually", "terminationReason"]
794
- });
795
- } catch (err) {
796
- strapi2.log.debug("[magic-sessionmanager] session lookup failed:", err.message);
797
- }
798
- }
799
- if (thisSession) {
800
- if (thisSession.isActive === false) {
801
- return ctx.unauthorized("Session terminated. Please login again.");
802
- }
803
- ctx.state.userDocumentId = userDocId;
804
- ctx.state.__magicSessionId = thisSession.documentId;
805
- await next();
806
- if (isSelfTerminatingEndpoint(ctx.path)) {
807
- return;
808
- }
809
- try {
810
- await sessionService.touch({
811
- userId: userDocId,
812
- sessionId: thisSession.documentId
813
- });
814
- } catch (err) {
815
- strapi2.log.debug("[magic-sessionmanager] Error updating lastSeen:", err.message);
816
- }
904
+ if (!tokenHashValue) {
817
905
  return;
818
906
  }
819
- if (strictMode) {
820
- const iat = ctx.state.user?.iat;
821
- if (gracePeriodMs > 0 && typeof iat === "number") {
822
- const ageMs = Date.now() - iat * 1e3;
823
- if (ageMs >= 0 && ageMs < gracePeriodMs) {
824
- ctx.state.userDocumentId = userDocId;
825
- return next();
826
- }
827
- }
828
- strapi2.log.info(
829
- `[magic-sessionmanager] [BLOCKED] No session matches this token (user: ${userDocId.substring(0, 8)}..., strictMode)`
830
- );
831
- return ctx.unauthorized("No valid session. Please login again.");
907
+ let thisSession = null;
908
+ try {
909
+ thisSession = await strapi2.documents(SESSION_UID).findFirst({
910
+ filters: { user: { documentId: userDocId }, tokenHash: tokenHashValue },
911
+ fields: ["documentId", "isActive"]
912
+ });
913
+ } catch (err) {
914
+ strapi2.log.debug("[magic-sessionmanager] session lookup failed:", err.message);
915
+ return;
832
916
  }
833
- strapi2.log.debug(
834
- `[magic-sessionmanager] [WARN] No session for token (user: ${userDocId.substring(0, 8)}...) - allowing in non-strict mode`
835
- );
917
+ if (!thisSession || thisSession.isActive !== true) return;
836
918
  ctx.state.userDocumentId = userDocId;
837
- return next();
919
+ ctx.state.__magicSessionId = thisSession.documentId;
920
+ try {
921
+ await sessionService.touch({
922
+ userId: userDocId,
923
+ sessionId: thisSession.documentId
924
+ });
925
+ } catch (err) {
926
+ strapi2.log.debug("[magic-sessionmanager] Error updating lastSeen:", err.message);
927
+ }
838
928
  };
839
929
  };
840
930
  }
@@ -9796,20 +9886,19 @@ var require_bootstrap = __commonJS({
9796
9886
  consumeSessionRejectionReason
9797
9887
  } = require_rejection_cache();
9798
9888
  var { evaluateGeoFirewall } = require_geo_firewall();
9889
+ var {
9890
+ classifyJwtIssuingRequest,
9891
+ isFailedLoginTrackedPath,
9892
+ shouldRunPreAuthGeoGuard
9893
+ } = require_auth_routes();
9894
+ var {
9895
+ getRefreshCookieName,
9896
+ getIncomingRefreshToken,
9897
+ getOutgoingRefreshToken,
9898
+ stripAuthTokensFromResponse
9899
+ } = require_refresh_token();
9799
9900
  var SESSION_UID = "plugin::magic-sessionmanager.session";
9800
9901
  var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
9801
- var LOGIN_PATHS = /* @__PURE__ */ new Set([
9802
- "/api/auth/local",
9803
- "/api/magic-link/login-totp",
9804
- "/api/magic-link/otp/verify",
9805
- "/api/magic-link/verify-mfa-totp"
9806
- ]);
9807
- function isLoginPath(path, method) {
9808
- if (!path) return false;
9809
- if (LOGIN_PATHS.has(path)) return true;
9810
- if (path.startsWith("/api/magic-link/login") && (method === "GET" || method === "POST")) return true;
9811
- return false;
9812
- }
9813
9902
  async function getRequestSettings(strapi2, ctx) {
9814
9903
  let settings = {};
9815
9904
  try {
@@ -9832,7 +9921,7 @@ var require_bootstrap = __commonJS({
9832
9921
  throw e;
9833
9922
  }
9834
9923
  try {
9835
- await ensureTokenHashIndex(strapi2, log);
9924
+ await ensureSessionLookupIndexes(strapi2, log);
9836
9925
  await registerSessionAwareAuthStrategy(strapi2, log);
9837
9926
  const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
9838
9927
  await licenseGuardService.initialize();
@@ -9898,7 +9987,8 @@ var require_bootstrap = __commonJS({
9898
9987
  mountFailedLoginLockout({ strapi: strapi2, log });
9899
9988
  mountLogoutRoute({ strapi: strapi2, log, sessionService });
9900
9989
  mountLoginInterceptor({ strapi: strapi2, log, sessionService });
9901
- mountRefreshTokenInterceptor({ strapi: strapi2, log });
9990
+ mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
9991
+ mountLogoutInterceptor({ strapi: strapi2, log, sessionService });
9902
9992
  strapi2.server.use(
9903
9993
  require_session_rejection_headers()({}, { strapi: strapi2 })
9904
9994
  );
@@ -9916,7 +10006,7 @@ var require_bootstrap = __commonJS({
9916
10006
  };
9917
10007
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
9918
10008
  strapi2.server.use(async (ctx, next) => {
9919
- if (!isLoginPath(ctx.path, ctx.method)) {
10009
+ if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
9920
10010
  return next();
9921
10011
  }
9922
10012
  const settings = await getRequestSettings(strapi2, ctx);
@@ -9949,13 +10039,30 @@ var require_bootstrap = __commonJS({
9949
10039
  ctx.state.__magicSessionGeoData = geoData;
9950
10040
  }
9951
10041
  } catch (err) {
9952
- log.debug("Pre-login geo guard error (allowing):", err.message);
10042
+ const failureDecision = evaluateGeoFirewall(settings, { _status: "error" });
10043
+ if (failureDecision.blocked) {
10044
+ log.warn(`[PRE-BLOCKED] Login rejected because GeoIP lookup failed for ${ip}`);
10045
+ ctx.status = 403;
10046
+ ctx.body = {
10047
+ error: {
10048
+ status: 403,
10049
+ name: "ForbiddenError",
10050
+ message: "Login temporarily unavailable. Please contact support."
10051
+ }
10052
+ };
10053
+ return;
10054
+ }
10055
+ log.debug("Pre-login geo guard error (allowing by configured policy):", err.message);
9953
10056
  }
9954
10057
  await next();
9955
10058
  });
9956
10059
  log.info("[SUCCESS] Pre-login geo guard mounted");
9957
10060
  }
9958
10061
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
10062
+ if (hasRegisteredRoute(strapi2, "POST", "/api/auth/logout")) {
10063
+ log.debug("[LOGOUT] Using the users-permissions logout route");
10064
+ return;
10065
+ }
9959
10066
  let jwt = null;
9960
10067
  try {
9961
10068
  jwt = require_jsonwebtoken();
@@ -9975,7 +10082,6 @@ var require_bootstrap = __commonJS({
9975
10082
  }
9976
10083
  const jwtService = strapi2.plugin("users-permissions").service("jwt");
9977
10084
  let decoded = null;
9978
- let expiredButValid = false;
9979
10085
  try {
9980
10086
  decoded = await jwtService.verify(token);
9981
10087
  } catch (verifyErr) {
@@ -9985,7 +10091,6 @@ var require_bootstrap = __commonJS({
9985
10091
  const jwtSecret = strapi2.config.get("plugin::users-permissions.jwtSecret");
9986
10092
  if (jwtSecret) {
9987
10093
  decoded = jwt.verify(token, jwtSecret, { ignoreExpiration: true });
9988
- expiredButValid = !!decoded;
9989
10094
  }
9990
10095
  } catch {
9991
10096
  decoded = null;
@@ -10002,23 +10107,21 @@ var require_bootstrap = __commonJS({
10002
10107
  ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10003
10108
  return;
10004
10109
  }
10005
- const userDocId = await resolveUserDocumentId(strapi2, decoded.id);
10006
- const tokenHashValue = hashToken(token);
10007
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10008
- filters: {
10009
- tokenHash: tokenHashValue,
10010
- ...userDocId ? { user: { documentId: userDocId } } : {}
10011
- },
10012
- fields: ["documentId", "isActive"]
10013
- });
10014
- if (matchingSession && matchingSession.isActive) {
10015
- await sessionService.terminateSession({ sessionId: matchingSession.documentId });
10016
- log.info(`[LOGOUT] Session ${matchingSession.documentId} terminated (expiredButValid=${expiredButValid})`);
10110
+ const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
10111
+ if (!userDocumentId) {
10112
+ ctx.status = 401;
10113
+ ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10114
+ return;
10017
10115
  }
10116
+ await sessionService.terminateAuthenticatedSession({
10117
+ userDocumentId,
10118
+ accessToken: token,
10119
+ refreshToken: null
10120
+ });
10018
10121
  ctx.status = 200;
10019
- ctx.body = { message: "Logged out successfully" };
10122
+ ctx.body = { ok: true, message: "Logged out successfully" };
10020
10123
  } catch (err) {
10021
- log.error("Logout error:", err);
10124
+ log.error("Logout error:", err?.name || "Error");
10022
10125
  ctx.status = 500;
10023
10126
  ctx.body = { error: { status: 500, name: "InternalServerError", message: "Logout failed" } };
10024
10127
  }
@@ -10029,6 +10132,36 @@ var require_bootstrap = __commonJS({
10029
10132
  }]);
10030
10133
  log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
10031
10134
  }
10135
+ function hasRegisteredRoute(strapi2, method, path) {
10136
+ try {
10137
+ const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
10138
+ const directRoutes = strapi2.server.listRoutes?.() || [];
10139
+ const contentRoutes = strapi2.server.api?.("content-api")?.listRoutes?.() || [];
10140
+ return [...directRoutes, ...contentRoutes].some((route) => {
10141
+ const methods = route.methods || (Array.isArray(route.method) ? route.method : [route.method]);
10142
+ const routePaths = /* @__PURE__ */ new Set([
10143
+ route.path,
10144
+ route.path?.startsWith(apiPrefix) ? route.path : `${apiPrefix}${route.path}`
10145
+ ]);
10146
+ return routePaths.has(path) && methods.some((value) => String(value).toUpperCase() === method);
10147
+ });
10148
+ } catch {
10149
+ return false;
10150
+ }
10151
+ }
10152
+ function failClosedAuthResponse({ ctx, strapi: strapi2, log, operation, error }) {
10153
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
10154
+ ctx.status = 503;
10155
+ if (typeof ctx.set === "function") ctx.set("Retry-After", "1");
10156
+ ctx.body = {
10157
+ error: {
10158
+ status: 503,
10159
+ name: "ServiceUnavailableError",
10160
+ message: "Authentication temporarily unavailable. Please try again."
10161
+ }
10162
+ };
10163
+ log.error(`[AUTH-FAIL-CLOSED] ${operation}:`, error?.message || error || "session persistence failed");
10164
+ }
10032
10165
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
10033
10166
  const WINDOW_MS = 15 * 60 * 1e3;
10034
10167
  const failed = /* @__PURE__ */ new Map();
@@ -10056,7 +10189,7 @@ var require_bootstrap = __commonJS({
10056
10189
  };
10057
10190
  const clearFailures = (ip) => failed.delete(ip);
10058
10191
  strapi2.server.use(async (ctx, next) => {
10059
- if (!isLoginPath(ctx.path, ctx.method)) return next();
10192
+ if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
10060
10193
  const settings = await getRequestSettings(strapi2, ctx);
10061
10194
  const maxFailed = Number(settings.maxFailedLogins) || 0;
10062
10195
  if (maxFailed <= 0) return next();
@@ -10093,30 +10226,42 @@ var require_bootstrap = __commonJS({
10093
10226
  });
10094
10227
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
10095
10228
  }
10096
- function isJwtIssuingPath(path, method) {
10097
- if (!path) return false;
10098
- const get = method === "GET";
10099
- const post = method === "POST";
10100
- if (post && path === "/api/auth/local") return true;
10101
- if (post && path === "/api/auth/local/register") return true;
10102
- if (post && path === "/api/auth/reset-password") return true;
10103
- if ((get || post) && path === "/api/auth/email-confirmation") return true;
10104
- if (get && /^\/api\/auth\/[a-z0-9-]+\/callback$/i.test(path)) return true;
10105
- if ((get || post) && path.startsWith("/api/magic-link/login")) return true;
10106
- if (post && path === "/api/magic-link/verify-mfa-totp") return true;
10107
- if (post && path === "/api/magic-link/otp/verify") return true;
10108
- if (post && path === "/api/magic-link/login-totp") return true;
10109
- if ((get || post) && path.startsWith("/api/passwordless/")) return true;
10110
- return false;
10111
- }
10112
10229
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
10113
10230
  strapi2.server.use(async (ctx, next) => {
10231
+ const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
10232
+ const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
10114
10233
  await next();
10115
- if (!isJwtIssuingPath(ctx.path, ctx.method)) return;
10116
- if (ctx.status !== 200) return;
10117
- if (!ctx.body || !ctx.body.jwt || !ctx.body.user) return;
10234
+ if (requestType !== "new-session" && requestType !== "rotate-current") return;
10235
+ if (ctx.status < 200 || ctx.status >= 300) return;
10236
+ if (!ctx.body || !ctx.body.jwt) return;
10237
+ const refreshCookieName = getRefreshCookieName(strapi2);
10238
+ if (requestType === "rotate-current") {
10239
+ try {
10240
+ if (!previousAccessToken) throw new Error("current access token is missing");
10241
+ const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10242
+ filters: {
10243
+ tokenHash: hashToken(previousAccessToken),
10244
+ isActive: true
10245
+ },
10246
+ fields: ["documentId"]
10247
+ });
10248
+ if (!matchingSession) throw new Error("current session was not found");
10249
+ const rotated = await sessionService.rotateSessionTokens({
10250
+ sessionId: matchingSession.documentId,
10251
+ expectedAccessToken: previousAccessToken,
10252
+ accessToken: ctx.body.jwt,
10253
+ refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName)
10254
+ });
10255
+ if (!rotated) throw new Error("current session changed before token rotation");
10256
+ log.info(`[PASSWORD] Tokens rotated for session ${matchingSession.documentId}`);
10257
+ } catch (err) {
10258
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "change-password rotation failed", error: err });
10259
+ }
10260
+ return;
10261
+ }
10118
10262
  try {
10119
10263
  const user = ctx.body.user;
10264
+ if (!user) throw new Error("authentication response contains no user");
10120
10265
  await getRequestSettings(strapi2, ctx);
10121
10266
  const ip = getClientIp(ctx);
10122
10267
  const headers = ctx.request.headers || ctx.request.header || {};
@@ -10127,8 +10272,7 @@ var require_bootstrap = __commonJS({
10127
10272
  userDocId = await resolveUserDocumentId(strapi2, user.id);
10128
10273
  }
10129
10274
  if (!userDocId) {
10130
- log.error(`[ERROR] Could not resolve documentId for user ${user.id || "unknown"} - session NOT created!`);
10131
- return;
10275
+ throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
10132
10276
  }
10133
10277
  const geoData = ctx.state?.__magicSessionGeoData || null;
10134
10278
  const newSession = await sessionService.createSession({
@@ -10136,12 +10280,11 @@ var require_bootstrap = __commonJS({
10136
10280
  ip,
10137
10281
  userAgent,
10138
10282
  token: ctx.body.jwt,
10139
- refreshToken: ctx.body.refreshToken,
10283
+ refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
10140
10284
  geoData
10141
10285
  });
10142
10286
  if (!newSession?.documentId) {
10143
- log.error(`[ERROR] Session creation returned no documentId for user ${userDocId}`);
10144
- return;
10287
+ throw new Error(`session creation returned no documentId for user ${userDocId}`);
10145
10288
  }
10146
10289
  log.info(`[SUCCESS] Session ${newSession.documentId} created for user ${userDocId} (IP: ${ip})`);
10147
10290
  try {
@@ -10194,6 +10337,17 @@ var require_bootstrap = __commonJS({
10194
10337
  }
10195
10338
  }
10196
10339
  if (settings.enableEmailAlerts) {
10340
+ if (settings.alertOnVpnProxy && (geoData.isVpn || geoData.isProxy)) {
10341
+ await notificationService.sendVpnProxyAlert({
10342
+ user,
10343
+ session: newSession,
10344
+ reason: {
10345
+ isVpn: geoData.isVpn,
10346
+ isProxy: geoData.isProxy
10347
+ },
10348
+ geoData
10349
+ });
10350
+ }
10197
10351
  if (settings.alertOnSuspiciousLogin && isSuspicious) {
10198
10352
  await notificationService.sendSuspiciousLoginAlert({
10199
10353
  user,
@@ -10254,84 +10408,101 @@ var require_bootstrap = __commonJS({
10254
10408
  log.warn("Notification failed:", notifErr.message);
10255
10409
  }
10256
10410
  } catch (err) {
10257
- log.error("[ERROR] Error creating session:", err);
10411
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "session creation failed", error: err });
10258
10412
  }
10259
10413
  });
10260
10414
  log.info("[SUCCESS] Login interceptor middleware mounted");
10261
10415
  }
10262
- function mountRefreshTokenInterceptor({ strapi: strapi2, log }) {
10416
+ function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
10263
10417
  strapi2.server.use(async (ctx, next) => {
10264
10418
  const isRefreshToken = ctx.path === "/api/auth/refresh" && ctx.method === "POST";
10265
- if (isRefreshToken) {
10266
- try {
10267
- const body = ctx.request.body;
10268
- const refreshToken = typeof body?.refreshToken === "string" ? body.refreshToken : null;
10269
- if (refreshToken) {
10270
- const refreshTokenHashValue = hashToken(refreshToken);
10271
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10272
- filters: {
10273
- refreshTokenHash: refreshTokenHashValue,
10274
- isActive: true
10275
- },
10276
- fields: ["documentId"]
10277
- });
10278
- if (!matchingSession) {
10279
- log.warn("[BLOCKED] Blocked refresh token request - no active session");
10280
- ctx.status = 401;
10281
- ctx.body = {
10282
- error: {
10283
- status: 401,
10284
- name: "UnauthorizedError",
10285
- message: "Session terminated. Please login again."
10286
- }
10287
- };
10288
- return;
10289
- }
10290
- log.info(`[SUCCESS] Refresh token allowed for session ${matchingSession.documentId}`);
10419
+ if (!isRefreshToken) return next();
10420
+ const cookieName = getRefreshCookieName(strapi2);
10421
+ const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
10422
+ let matchingSession = null;
10423
+ try {
10424
+ if (oldRefreshToken) {
10425
+ matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10426
+ filters: {
10427
+ refreshTokenHash: hashToken(oldRefreshToken),
10428
+ isActive: true
10429
+ },
10430
+ fields: ["documentId"]
10431
+ });
10432
+ if (!matchingSession) {
10433
+ log.warn("[BLOCKED] Blocked refresh token request - no active session");
10434
+ ctx.status = 401;
10435
+ ctx.body = {
10436
+ error: {
10437
+ status: 401,
10438
+ name: "UnauthorizedError",
10439
+ message: "Session terminated. Please login again."
10440
+ }
10441
+ };
10442
+ return;
10291
10443
  }
10292
- } catch (err) {
10293
- log.error("Error checking refresh token:", err);
10294
10444
  }
10445
+ } catch (err) {
10446
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh validation failed", error: err });
10447
+ return;
10295
10448
  }
10296
10449
  await next();
10297
- if (isRefreshToken && ctx.status === 200 && ctx.body && ctx.body.jwt) {
10450
+ if (ctx.status >= 200 && ctx.status < 300 && ctx.body && ctx.body.jwt) {
10298
10451
  try {
10299
- const body = ctx.request.body;
10300
- const oldRefreshToken = typeof body?.refreshToken === "string" ? body.refreshToken : null;
10301
- const newAccessToken = ctx.body.jwt;
10302
- const newRefreshToken = ctx.body.refreshToken;
10303
- if (!oldRefreshToken) return;
10304
- const oldRefreshTokenHash = hashToken(oldRefreshToken);
10305
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10306
- filters: {
10307
- refreshTokenHash: oldRefreshTokenHash,
10308
- isActive: true
10309
- },
10310
- fields: ["documentId", "token", "tokenHash", "refreshToken", "refreshTokenHash"]
10311
- });
10312
- if (!matchingSession) return;
10313
- const encryptedToken = newAccessToken ? encryptToken(newAccessToken) : matchingSession.token;
10314
- const encryptedRefreshToken = newRefreshToken ? encryptToken(newRefreshToken) : matchingSession.refreshToken;
10315
- const newTokenHash = newAccessToken ? hashToken(newAccessToken) : matchingSession.tokenHash;
10316
- const newRefreshTokenHash = newRefreshToken ? hashToken(newRefreshToken) : matchingSession.refreshTokenHash;
10317
- await strapi2.documents(SESSION_UID).update({
10318
- documentId: matchingSession.documentId,
10319
- data: {
10320
- token: encryptedToken,
10321
- tokenHash: newTokenHash,
10322
- refreshToken: encryptedRefreshToken,
10323
- refreshTokenHash: newRefreshTokenHash,
10324
- lastActive: /* @__PURE__ */ new Date()
10325
- }
10452
+ if (!oldRefreshToken || !matchingSession) {
10453
+ throw new Error("refresh response issued without a tracked input token");
10454
+ }
10455
+ const rotated = await sessionService.rotateSessionTokens({
10456
+ sessionId: matchingSession.documentId,
10457
+ expectedRefreshToken: oldRefreshToken,
10458
+ accessToken: ctx.body.jwt,
10459
+ refreshToken: getOutgoingRefreshToken(ctx, cookieName)
10326
10460
  });
10461
+ if (!rotated) throw new Error("refresh token was already consumed");
10327
10462
  log.info(`[REFRESH] Tokens refreshed for session ${matchingSession.documentId}`);
10328
10463
  } catch (err) {
10329
- log.error("Error updating refreshed tokens:", err);
10464
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh rotation failed", error: err });
10330
10465
  }
10331
10466
  }
10332
10467
  });
10333
10468
  log.info("[SUCCESS] Refresh token interceptor middleware mounted");
10334
10469
  }
10470
+ function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
10471
+ strapi2.server.use(async (ctx, next) => {
10472
+ if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
10473
+ const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
10474
+ const accessToken = extractBearerToken(ctx);
10475
+ const jwtManagement = strapi2.config.get(
10476
+ "plugin::users-permissions.jwtManagement",
10477
+ "legacy-support"
10478
+ );
10479
+ await next();
10480
+ const isUsersPermissionsLogoutRoute = ctx.state?.route?.handler === "auth.logout" && ctx.state?.route?.info?.pluginName === "users-permissions";
10481
+ const isSuccessful = isUsersPermissionsLogoutRoute && ctx.status >= 200 && ctx.status < 300;
10482
+ const isLegacyMissingRoute = jwtManagement === "legacy-support" && ctx.status === 404 && isUsersPermissionsLogoutRoute;
10483
+ const authenticatedUser = ctx.state?.user;
10484
+ if (!authenticatedUser || !isSuccessful && !isLegacyMissingRoute) return;
10485
+ try {
10486
+ const userDocumentId = authenticatedUser.documentId || await resolveUserDocumentId(strapi2, authenticatedUser.id);
10487
+ if (!userDocumentId) {
10488
+ throw new Error("authenticated logout user has no resolvable documentId");
10489
+ }
10490
+ await sessionService.terminateAuthenticatedSession({
10491
+ userDocumentId,
10492
+ refreshToken,
10493
+ accessToken
10494
+ });
10495
+ ctx.status = 200;
10496
+ ctx.body = {
10497
+ ok: true,
10498
+ message: "Logged out successfully"
10499
+ };
10500
+ } catch (err) {
10501
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
10502
+ }
10503
+ });
10504
+ log.info("[SUCCESS] Logout interceptor middleware mounted");
10505
+ }
10335
10506
  async function ensureContentApiPermissions(strapi2, log) {
10336
10507
  const PERMISSIONS_VERSION = 2;
10337
10508
  try {
@@ -10397,42 +10568,45 @@ var require_bootstrap = __commonJS({
10397
10568
  log.warn("Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated");
10398
10569
  }
10399
10570
  }
10400
- async function ensureTokenHashIndex(strapi2, log) {
10571
+ async function ensureSessionLookupIndexes(strapi2, log) {
10401
10572
  try {
10402
10573
  const knex = strapi2.db.connection;
10403
10574
  const tableName = "magic_sessions";
10404
- const indexName = "idx_magic_sessions_token_hash";
10405
- const hasIndex = await knex.schema.hasTable(tableName).then(async (exists) => {
10406
- if (!exists) return false;
10575
+ const definitions = [
10576
+ { column: "token_hash", name: "idx_magic_sessions_token_hash" },
10577
+ { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
10578
+ ];
10579
+ if (!await knex.schema.hasTable(tableName)) return;
10580
+ for (const definition of definitions) {
10407
10581
  const dialect = strapi2.db.dialect.client;
10582
+ let hasIndex = false;
10408
10583
  if (dialect === "postgres") {
10409
10584
  const result = await knex.raw(
10410
10585
  "SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?",
10411
- [tableName, indexName]
10586
+ [tableName, definition.name]
10412
10587
  );
10413
- return result.rows.length > 0;
10588
+ hasIndex = result.rows.length > 0;
10414
10589
  } else if (dialect === "mysql" || dialect === "mysql2") {
10415
- const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName, indexName]);
10416
- return result[0].length > 0;
10590
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName, definition.name]);
10591
+ hasIndex = result[0].length > 0;
10417
10592
  } else if (dialect === "sqlite" || dialect === "better-sqlite3") {
10418
10593
  const result = await knex.raw(
10419
10594
  "SELECT name FROM sqlite_master WHERE type='index' AND name = ?",
10420
- [indexName]
10595
+ [definition.name]
10421
10596
  );
10422
- return result.length > 0;
10597
+ hasIndex = result.length > 0;
10423
10598
  }
10424
- return false;
10425
- });
10426
- if (hasIndex) {
10427
- log.debug("[INDEX] tokenHash index already exists");
10428
- return;
10599
+ if (hasIndex) {
10600
+ log.debug(`[INDEX] ${definition.name} already exists`);
10601
+ continue;
10602
+ }
10603
+ await knex.schema.alterTable(tableName, (table) => {
10604
+ table.index([definition.column, "is_active"], definition.name);
10605
+ });
10606
+ log.info(`[INDEX] Created ${definition.name}`);
10429
10607
  }
10430
- await knex.schema.alterTable(tableName, (table) => {
10431
- table.index(["token_hash", "is_active"], indexName);
10432
- });
10433
- log.info("[INDEX] Created tokenHash index for O(1) session lookup");
10434
10608
  } catch (err) {
10435
- log.debug("[INDEX] Could not create tokenHash index (will retry on next startup):", err.message);
10609
+ log.debug("[INDEX] Could not create session lookup indexes (will retry on next startup):", err.message);
10436
10610
  }
10437
10611
  }
10438
10612
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
@@ -10524,6 +10698,16 @@ var require_bootstrap = __commonJS({
10524
10698
  fields: ["documentId", "isActive", "terminatedManually", "terminationReason", "lastActive", "loginTime"]
10525
10699
  });
10526
10700
  if (thisSession) {
10701
+ if (thisSession.isActive === false) {
10702
+ const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : null);
10703
+ if (reason) {
10704
+ strapi2.log.info(
10705
+ `[magic-sessionmanager] [JWT-REJECTED] Session inactive (reason: ${reason}) for user ${userDocId.substring(0, 8)}...`
10706
+ );
10707
+ setSessionRejectionReason(tokenHashValue, reason);
10708
+ return null;
10709
+ }
10710
+ }
10527
10711
  if (isSessionExpired(thisSession, maxSessionAgeDays)) {
10528
10712
  strapi2.log.info(
10529
10713
  `[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days (user: ${userDocId.substring(0, 8)}...)`
@@ -10540,20 +10724,6 @@ var require_bootstrap = __commonJS({
10540
10724
  setSessionRejectionReason(tokenHashValue, "expired");
10541
10725
  return null;
10542
10726
  }
10543
- if (thisSession.isActive === false) {
10544
- const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : null);
10545
- if (reason) {
10546
- strapi2.log.info(
10547
- `[magic-sessionmanager] [JWT-REJECTED] Session inactive (reason: ${reason}) for user ${userDocId.substring(0, 8)}...`
10548
- );
10549
- setSessionRejectionReason(tokenHashValue, reason);
10550
- return null;
10551
- }
10552
- }
10553
- if (thisSession.isActive) {
10554
- resetErrorCounter();
10555
- return decoded;
10556
- }
10557
10727
  const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
10558
10728
  const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
10559
10729
  const idleFor = Date.now() - lastActiveMs;
@@ -10564,6 +10734,7 @@ var require_bootstrap = __commonJS({
10564
10734
  await strapi2.documents(SESSION_UID).update({
10565
10735
  documentId: thisSession.documentId,
10566
10736
  data: {
10737
+ isActive: false,
10567
10738
  terminatedManually: false,
10568
10739
  terminationReason: "idle",
10569
10740
  logoutTime: /* @__PURE__ */ new Date()
@@ -10572,6 +10743,10 @@ var require_bootstrap = __commonJS({
10572
10743
  setSessionRejectionReason(tokenHashValue, "idle");
10573
10744
  return null;
10574
10745
  }
10746
+ if (thisSession.isActive) {
10747
+ resetErrorCounter();
10748
+ return decoded;
10749
+ }
10575
10750
  await strapi2.documents(SESSION_UID).update({
10576
10751
  documentId: thisSession.documentId,
10577
10752
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
@@ -10621,6 +10796,14 @@ var require_bootstrap = __commonJS({
10621
10796
  strapi2.log.warn("[magic-sessionmanager] [AUTH] Session validation will only work via middleware (plugin endpoints)");
10622
10797
  }
10623
10798
  }
10799
+ module2.exports.__private = {
10800
+ registerSessionAwareAuthStrategy,
10801
+ mountPreLoginGeoGuard,
10802
+ mountLoginInterceptor,
10803
+ mountRefreshTokenInterceptor,
10804
+ mountLogoutInterceptor,
10805
+ mountLogoutRoute
10806
+ };
10624
10807
  }
10625
10808
  });
10626
10809
 
@@ -10661,6 +10844,12 @@ var require_config = __commonJS({
10661
10844
  cleanupInterval: 30 * 60 * 1e3,
10662
10845
  retentionDays: 90,
10663
10846
  maxSessionAgeDays: 30,
10847
+ maxFailedLogins: 5,
10848
+ sessionCreationGraceMs: 5e3,
10849
+ cleanupUseDbDirect: false,
10850
+ rateLimitWriteMax: 10,
10851
+ rateLimitReadMax: 120,
10852
+ rateLimitWindowSeconds: 60,
10664
10853
  strictSessionEnforcement: false,
10665
10854
  enableGeolocation: true,
10666
10855
  enableSecurityScoring: true,
@@ -10798,7 +10987,7 @@ var require_schema = __commonJS({
10798
10987
  },
10799
10988
  terminationReason: {
10800
10989
  type: "enumeration",
10801
- enum: ["manual", "idle", "expired", "blocked"],
10990
+ enum: ["logout", "manual", "idle", "expired", "blocked"],
10802
10991
  required: false
10803
10992
  },
10804
10993
  geoLocation: {
@@ -11259,6 +11448,9 @@ var require_enhance_session = __commonJS({
11259
11448
  "use strict";
11260
11449
  var { parseUserAgent } = require_user_agent_parser();
11261
11450
  var SESSION_UID = "plugin::magic-sessionmanager.session";
11451
+ function shouldResolveGeoData(settings = {}) {
11452
+ return settings.enableGeolocation === true || settings.enableGeofencing === true || settings.blockSuspiciousSessions === true;
11453
+ }
11262
11454
  async function enhanceSession(session, opts = {}) {
11263
11455
  const {
11264
11456
  inactivityTimeout = 15 * 60 * 1e3,
@@ -11310,7 +11502,7 @@ var require_enhance_session = __commonJS({
11310
11502
  documentId: session.documentId,
11311
11503
  data: {
11312
11504
  geoLocation,
11313
- securityScore: geoData.securityScore || null
11505
+ securityScore: geoData.securityScore ?? null
11314
11506
  }
11315
11507
  }).catch(() => {
11316
11508
  });
@@ -11347,7 +11539,7 @@ var require_enhance_session = __commonJS({
11347
11539
  sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now }))
11348
11540
  );
11349
11541
  }
11350
- module2.exports = { enhanceSession, enhanceSessions };
11542
+ module2.exports = { enhanceSession, enhanceSessions, shouldResolveGeoData };
11351
11543
  }
11352
11544
  });
11353
11545
 
@@ -11356,7 +11548,11 @@ var require_session = __commonJS({
11356
11548
  "server/src/controllers/session.js"(exports2, module2) {
11357
11549
  "use strict";
11358
11550
  var { hashToken } = require_encryption();
11359
- var { enhanceSessions, enhanceSession } = require_enhance_session();
11551
+ var {
11552
+ enhanceSessions,
11553
+ enhanceSession,
11554
+ shouldResolveGeoData
11555
+ } = require_enhance_session();
11360
11556
  var { resolveUserDocumentId } = require_resolve_user();
11361
11557
  var {
11362
11558
  getPluginSettings,
@@ -11434,7 +11630,7 @@ var require_session = __commonJS({
11434
11630
  const settings = await getPluginSettings(strapi);
11435
11631
  const enhanceOpts = {
11436
11632
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
11437
- geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
11633
+ geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
11438
11634
  strapi
11439
11635
  };
11440
11636
  const sessionsWithCurrent = await enhanceSessions(paged, enhanceOpts, 20);
@@ -11518,7 +11714,7 @@ var require_session = __commonJS({
11518
11714
  if (matchingSession) {
11519
11715
  await sessionService.terminateSession({
11520
11716
  sessionId: matchingSession.documentId,
11521
- reason: "manual"
11717
+ reason: "logout"
11522
11718
  });
11523
11719
  terminated = true;
11524
11720
  strapi.log.info(`[magic-sessionmanager] User ${userDocId} logged out (session ${matchingSession.documentId})`);
@@ -11536,7 +11732,7 @@ var require_session = __commonJS({
11536
11732
  * Terminates EVERY session of the authenticated user — including the
11537
11733
  * current one. After this call the caller will also be logged out on
11538
11734
  * the next request (their own JWT is rejected by the JWT-verify wrapper
11539
- * with reason=manual).
11735
+ * with reason=logout).
11540
11736
  *
11541
11737
  * For the "log me out everywhere ELSE but keep me here" flow, use
11542
11738
  * `/logout-others` below.
@@ -11552,7 +11748,7 @@ var require_session = __commonJS({
11552
11748
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
11553
11749
  const { terminatedCount } = await sessionService.terminateSession({
11554
11750
  userId: userDocId,
11555
- reason: "manual"
11751
+ reason: "logout"
11556
11752
  });
11557
11753
  strapi.log.info(
11558
11754
  `[magic-sessionmanager] User ${userDocId} logged out from all devices (${terminatedCount})`
@@ -11596,7 +11792,7 @@ var require_session = __commonJS({
11596
11792
  if (!currentSession) {
11597
11793
  const { terminatedCount: terminatedCount2 } = await sessionService.terminateSession({
11598
11794
  userId: userDocId,
11599
- reason: "manual"
11795
+ reason: "logout"
11600
11796
  });
11601
11797
  strapi.log.warn(
11602
11798
  `[magic-sessionmanager] logoutOthers fell back to logoutAll for user ${userDocId} (no current session match)`
@@ -11611,7 +11807,7 @@ var require_session = __commonJS({
11611
11807
  const { terminatedCount } = await sessionService.terminateSession({
11612
11808
  userId: userDocId,
11613
11809
  exceptSessionId: currentSession.documentId,
11614
- reason: "manual"
11810
+ reason: "logout"
11615
11811
  });
11616
11812
  strapi.log.info(
11617
11813
  `[magic-sessionmanager] User ${userDocId} logged out ${terminatedCount} other device(s)`
@@ -11672,7 +11868,7 @@ var require_session = __commonJS({
11672
11868
  const settings = await getPluginSettings(strapi);
11673
11869
  const enhanced = await enhanceSession(currentSession, {
11674
11870
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
11675
- geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
11871
+ geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
11676
11872
  geoCounter: { remaining: 1 },
11677
11873
  strapi
11678
11874
  });
@@ -12228,6 +12424,55 @@ var require_settings = __commonJS({
12228
12424
  }
12229
12425
  return result;
12230
12426
  }
12427
+ var DEFAULT_EMAIL_TEMPLATES = {
12428
+ suspiciousLogin: { subject: "", html: "", text: "" },
12429
+ newLocation: { subject: "", html: "", text: "" },
12430
+ vpnProxy: { subject: "", html: "", text: "" }
12431
+ };
12432
+ var DEFAULT_SETTINGS = {
12433
+ inactivityTimeout: 15,
12434
+ cleanupInterval: 30,
12435
+ lastSeenRateLimit: 30,
12436
+ retentionDays: 90,
12437
+ maxSessionAgeDays: 30,
12438
+ sessionCreationGraceMs: 5e3,
12439
+ cleanupUseDbDirect: false,
12440
+ rateLimitWriteMax: 10,
12441
+ rateLimitReadMax: 120,
12442
+ rateLimitWindowSeconds: 60,
12443
+ enableGeolocation: true,
12444
+ enableSecurityScoring: true,
12445
+ blockSuspiciousSessions: false,
12446
+ maxFailedLogins: 5,
12447
+ enableGeofencing: false,
12448
+ allowedCountries: [],
12449
+ blockedCountries: [],
12450
+ geoIpProvider: "auto",
12451
+ geoIpDatabasePath: "",
12452
+ geoLookupFailureMode: "auto",
12453
+ enableEmailAlerts: false,
12454
+ alertOnSuspiciousLogin: true,
12455
+ alertOnNewLocation: true,
12456
+ alertOnVpnProxy: true,
12457
+ enableWebhooks: false,
12458
+ discordWebhookUrl: "",
12459
+ slackWebhookUrl: "",
12460
+ strictSessionEnforcement: false,
12461
+ trustedProxies: false,
12462
+ emailTemplates: DEFAULT_EMAIL_TEMPLATES
12463
+ };
12464
+ function mergeSettingsWithDefaults(stored) {
12465
+ const safeStored = stored && typeof stored === "object" ? stored : {};
12466
+ const storedTemplates = safeStored.emailTemplates && typeof safeStored.emailTemplates === "object" ? safeStored.emailTemplates : {};
12467
+ return {
12468
+ ...DEFAULT_SETTINGS,
12469
+ ...safeStored,
12470
+ emailTemplates: {
12471
+ ...DEFAULT_EMAIL_TEMPLATES,
12472
+ ...storedTemplates
12473
+ }
12474
+ };
12475
+ }
12231
12476
  module2.exports = {
12232
12477
  /**
12233
12478
  * Returns the current plugin settings (user-facing units: minutes/seconds/days).
@@ -12239,51 +12484,8 @@ var require_settings = __commonJS({
12239
12484
  type: "plugin",
12240
12485
  name: "magic-sessionmanager"
12241
12486
  });
12242
- let settings = await pluginStore.get({ key: "settings" });
12243
- if (!settings) {
12244
- settings = {
12245
- // Timing & cleanup
12246
- inactivityTimeout: 15,
12247
- cleanupInterval: 30,
12248
- lastSeenRateLimit: 30,
12249
- retentionDays: 90,
12250
- maxSessionAgeDays: 30,
12251
- // Grace window (ms) during which a freshly-issued JWT is accepted
12252
- // without a matching session row — see JWT-verify wrapper in bootstrap.
12253
- sessionCreationGraceMs: 5e3,
12254
- // Opt-in: use a single SQL UPDATE for idle-session cleanup
12255
- // (bypasses Document Service lifecycle, required for very large installs).
12256
- cleanupUseDbDirect: false,
12257
- // Geo / security
12258
- enableGeolocation: true,
12259
- enableSecurityScoring: true,
12260
- blockSuspiciousSessions: false,
12261
- maxFailedLogins: 5,
12262
- enableGeofencing: false,
12263
- allowedCountries: [],
12264
- blockedCountries: [],
12265
- geoIpProvider: "auto",
12266
- geoIpDatabasePath: "",
12267
- geoLookupFailureMode: "auto",
12268
- // Notifications
12269
- enableEmailAlerts: false,
12270
- alertOnSuspiciousLogin: true,
12271
- alertOnNewLocation: true,
12272
- alertOnVpnProxy: true,
12273
- enableWebhooks: false,
12274
- discordWebhookUrl: "",
12275
- slackWebhookUrl: "",
12276
- // Session policy
12277
- strictSessionEnforcement: false,
12278
- trustedProxies: false,
12279
- // Email templates
12280
- emailTemplates: {
12281
- suspiciousLogin: { subject: "", html: "", text: "" },
12282
- newLocation: { subject: "", html: "", text: "" },
12283
- vpnProxy: { subject: "", html: "", text: "" }
12284
- }
12285
- };
12286
- }
12487
+ const storedSettings = await pluginStore.get({ key: "settings" });
12488
+ const settings = mergeSettingsWithDefaults(storedSettings);
12287
12489
  ctx.send({
12288
12490
  settings,
12289
12491
  success: true
@@ -12321,6 +12523,9 @@ var require_settings = __commonJS({
12321
12523
  maxSessionAgeDays: Math.max(1, Math.min(parseInt(body.maxSessionAgeDays) || 30, 365)),
12322
12524
  sessionCreationGraceMs: grace,
12323
12525
  cleanupUseDbDirect: !!body.cleanupUseDbDirect,
12526
+ rateLimitWriteMax: Math.max(1, Math.min(parseInt(body.rateLimitWriteMax) || 10, 1e3)),
12527
+ rateLimitReadMax: Math.max(1, Math.min(parseInt(body.rateLimitReadMax) || 120, 1e4)),
12528
+ rateLimitWindowSeconds: Math.max(10, Math.min(parseInt(body.rateLimitWindowSeconds) || 60, 3600)),
12324
12529
  // Geo / security
12325
12530
  enableGeolocation: !!body.enableGeolocation,
12326
12531
  enableSecurityScoring: !!body.enableSecurityScoring,
@@ -12361,7 +12566,9 @@ var require_settings = __commonJS({
12361
12566
  strapi.log.error("[magic-sessionmanager/settings] Error updating settings:", error);
12362
12567
  ctx.badRequest("Error saving settings");
12363
12568
  }
12364
- }
12569
+ },
12570
+ DEFAULT_SETTINGS,
12571
+ mergeSettingsWithDefaults
12365
12572
  };
12366
12573
  }
12367
12574
  });
@@ -12755,17 +12962,20 @@ var require_session2 = __commonJS({
12755
12962
  var { createLogger } = require_logger();
12756
12963
  var { parseUserAgent } = require_user_agent_parser();
12757
12964
  var { resolveUserDocumentId } = require_resolve_user();
12758
- var { enhanceSessions } = require_enhance_session();
12965
+ var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
12759
12966
  var { getPluginSettings } = require_settings_loader();
12760
12967
  var SESSION_UID = "plugin::magic-sessionmanager.session";
12761
12968
  var MAX_SESSIONS_QUERY = 1e3;
12969
+ async function lockSessionRow(trx, documentId) {
12970
+ await trx("magic_sessions").where({ document_id: documentId }).forUpdate().first("document_id");
12971
+ }
12762
12972
  module2.exports = ({ strapi: strapi2 }) => {
12763
12973
  const log = createLogger(strapi2);
12764
12974
  async function getEnhanceOpts() {
12765
12975
  const settings = await getPluginSettings(strapi2);
12766
12976
  return {
12767
12977
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
12768
- geolocationService: strapi2.plugin("magic-sessionmanager").service("geolocation"),
12978
+ geolocationService: shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null,
12769
12979
  strapi: strapi2
12770
12980
  };
12771
12981
  }
@@ -12820,7 +13030,7 @@ var require_session2 = __commonJS({
12820
13030
  region: geoData.region,
12821
13031
  timezone: geoData.timezone
12822
13032
  } : null,
12823
- securityScore: geoData?.securityScore || null
13033
+ securityScore: geoData?.securityScore ?? null
12824
13034
  }
12825
13035
  });
12826
13036
  log.info(`[SUCCESS] Session ${session.documentId} (${sessionId}) created for user ${userId}`);
@@ -12830,19 +13040,118 @@ var require_session2 = __commonJS({
12830
13040
  throw err;
12831
13041
  }
12832
13042
  },
13043
+ /**
13044
+ * Atomically replaces the stored tokens only while the caller still owns
13045
+ * the expected active token. This prevents two concurrent refresh
13046
+ * requests from both committing a rotation.
13047
+ *
13048
+ * @returns {Promise<boolean>} Whether exactly one session was rotated
13049
+ */
13050
+ async rotateSessionTokens({
13051
+ sessionId,
13052
+ expectedAccessToken,
13053
+ expectedRefreshToken,
13054
+ accessToken,
13055
+ refreshToken
13056
+ }) {
13057
+ if (!sessionId || !accessToken || !expectedAccessToken && !expectedRefreshToken) {
13058
+ return false;
13059
+ }
13060
+ const where = { documentId: sessionId, isActive: true };
13061
+ if (expectedAccessToken) where.tokenHash = hashToken(expectedAccessToken);
13062
+ if (expectedRefreshToken) where.refreshTokenHash = hashToken(expectedRefreshToken);
13063
+ const data = {
13064
+ token: encryptToken(accessToken),
13065
+ tokenHash: hashToken(accessToken),
13066
+ lastActive: /* @__PURE__ */ new Date()
13067
+ };
13068
+ if (refreshToken) {
13069
+ data.refreshToken = encryptToken(refreshToken);
13070
+ data.refreshTokenHash = hashToken(refreshToken);
13071
+ }
13072
+ const result = await strapi2.db.query(SESSION_UID).updateMany({ where, data });
13073
+ return result?.count === 1;
13074
+ },
13075
+ /**
13076
+ * Terminates the active session identified by a raw refresh token.
13077
+ * Used by Strapi's built-in cookie/body logout endpoint.
13078
+ */
13079
+ async terminateSessionByRefreshToken(refreshToken) {
13080
+ if (!refreshToken) return false;
13081
+ const result = await strapi2.db.query(SESSION_UID).updateMany({
13082
+ where: {
13083
+ refreshTokenHash: hashToken(refreshToken),
13084
+ isActive: true
13085
+ },
13086
+ data: {
13087
+ isActive: false,
13088
+ terminatedManually: false,
13089
+ terminationReason: "logout",
13090
+ logoutTime: /* @__PURE__ */ new Date()
13091
+ }
13092
+ });
13093
+ return result?.count === 1;
13094
+ },
13095
+ /**
13096
+ * Terminates the authenticated user's active session. A raw access token
13097
+ * is authoritative when present, and a supplied refresh token must match
13098
+ * the same row. Refresh-token-only lookup is used when access is absent.
13099
+ *
13100
+ * @param {Object} params
13101
+ * @param {string} params.userDocumentId - Authenticated user's documentId
13102
+ * @param {string|null} [params.refreshToken=null] - Raw refresh token
13103
+ * @param {string|null} [params.accessToken=null] - Raw access token
13104
+ * @returns {Promise<boolean>} Whether one owned active session was terminated
13105
+ * @throws {Error} When the Document Service lookup or termination fails
13106
+ * @sideeffect Marks the matching session inactive with logout metadata
13107
+ */
13108
+ async terminateAuthenticatedSession({
13109
+ userDocumentId,
13110
+ refreshToken = null,
13111
+ accessToken = null
13112
+ }) {
13113
+ if (!userDocumentId || !refreshToken && !accessToken) return false;
13114
+ const selectedTokenFilters = {
13115
+ user: { documentId: userDocumentId },
13116
+ isActive: true
13117
+ };
13118
+ if (accessToken) {
13119
+ selectedTokenFilters.tokenHash = hashToken(accessToken);
13120
+ if (refreshToken) {
13121
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13122
+ }
13123
+ } else {
13124
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13125
+ }
13126
+ const session = await strapi2.documents(SESSION_UID).findFirst({
13127
+ filters: selectedTokenFilters,
13128
+ fields: ["documentId"]
13129
+ });
13130
+ if (!session) return false;
13131
+ return strapi2.db.transaction(async ({ trx }) => {
13132
+ await lockSessionRow(trx, session.documentId);
13133
+ const result = await this.terminateSession({
13134
+ sessionId: session.documentId,
13135
+ reason: "logout",
13136
+ expectedFilters: selectedTokenFilters
13137
+ });
13138
+ return result?.terminatedCount === 1;
13139
+ });
13140
+ },
12833
13141
  /**
12834
13142
  * Terminates a single session, all sessions of a user, or all sessions
12835
13143
  * of a user EXCEPT one with a typed reason so the JWT-verify wrapper
12836
13144
  * can communicate the cause to the client.
12837
13145
  *
12838
13146
  * Supported reasons:
12839
- * - 'manual': user clicked logout, or admin terminated a session
13147
+ * - 'logout': user clicked logout
13148
+ * - 'manual': admin terminated a session
12840
13149
  * - 'idle': inactivity timeout cleanup
12841
13150
  * - 'expired': maxSessionAgeDays exceeded
12842
13151
  * - 'blocked': the owning user was marked blocked
12843
13152
  *
12844
13153
  * For backwards compatibility `terminatedManually` is still set true
12845
- * only when reason === 'manual'; idle/expired/blocked paths set it
13154
+ * only when reason === 'manual'; logout/idle/expired/blocked paths set it
12846
13155
  * false so reporting dashboards that queried that boolean continue
12847
13156
  * to work, while new code relies on `terminationReason`.
12848
13157
  *
@@ -12855,13 +13164,22 @@ var require_session2 = __commonJS({
12855
13164
  * `userId`. Used by
12856
13165
  * /logout-other-devices so
12857
13166
  * the caller stays logged in.
12858
- * @param {'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
13167
+ * @param {object} [params.expectedFilters] Internal predicates that must
13168
+ * still match before a
13169
+ * single-session update.
13170
+ * @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
12859
13171
  * @returns {Promise<{terminatedCount: number}>}
12860
13172
  */
12861
- async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
13173
+ async terminateSession({
13174
+ sessionId,
13175
+ userId,
13176
+ exceptSessionId = null,
13177
+ reason = "manual",
13178
+ expectedFilters = null
13179
+ }) {
12862
13180
  try {
12863
13181
  const now = /* @__PURE__ */ new Date();
12864
- const validReasons = ["manual", "idle", "expired", "blocked"];
13182
+ const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
12865
13183
  const finalReason = validReasons.includes(reason) ? reason : "manual";
12866
13184
  const updateData = {
12867
13185
  isActive: false,
@@ -12870,7 +13188,13 @@ var require_session2 = __commonJS({
12870
13188
  logoutTime: now
12871
13189
  };
12872
13190
  if (sessionId) {
12873
- const existing = await strapi2.documents(SESSION_UID).findOne({
13191
+ const existing = expectedFilters ? await strapi2.documents(SESSION_UID).findFirst({
13192
+ filters: {
13193
+ ...expectedFilters,
13194
+ documentId: sessionId
13195
+ },
13196
+ fields: ["documentId"]
13197
+ }) : await strapi2.documents(SESSION_UID).findOne({
12874
13198
  documentId: sessionId,
12875
13199
  fields: ["documentId"]
12876
13200
  });
@@ -12892,21 +13216,31 @@ var require_session2 = __commonJS({
12892
13216
  if (exceptSessionId) {
12893
13217
  filters.documentId = { $ne: exceptSessionId };
12894
13218
  }
12895
- const activeSessions = await strapi2.documents(SESSION_UID).findMany({
12896
- filters,
12897
- fields: ["documentId"],
12898
- limit: MAX_SESSIONS_QUERY
12899
- });
12900
13219
  let terminatedCount = 0;
12901
- for (const session of activeSessions) {
12902
- try {
12903
- await strapi2.documents(SESSION_UID).update({
12904
- documentId: session.documentId,
12905
- data: updateData
12906
- });
12907
- terminatedCount++;
12908
- } catch (err) {
12909
- log.debug(`Failed to terminate session ${session.documentId}:`, err.message);
13220
+ const batchSize = 500;
13221
+ while (true) {
13222
+ const activeSessions = await strapi2.documents(SESSION_UID).findMany({
13223
+ filters,
13224
+ fields: ["documentId"],
13225
+ limit: batchSize
13226
+ });
13227
+ if (!activeSessions || activeSessions.length === 0) break;
13228
+ let batchTerminated = 0;
13229
+ for (const session of activeSessions) {
13230
+ try {
13231
+ await strapi2.documents(SESSION_UID).update({
13232
+ documentId: session.documentId,
13233
+ data: updateData
13234
+ });
13235
+ terminatedCount++;
13236
+ batchTerminated++;
13237
+ } catch (err) {
13238
+ log.debug(`Failed to terminate session ${session.documentId}:`, err.message);
13239
+ }
13240
+ }
13241
+ if (batchTerminated === 0) {
13242
+ log.warn(`Could not terminate remaining active sessions for user ${userDocumentId}`);
13243
+ break;
12910
13244
  }
12911
13245
  }
12912
13246
  const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
@@ -13292,7 +13626,7 @@ var require_session2 = __commonJS({
13292
13626
  var require_package = __commonJS({
13293
13627
  "package.json"(exports2, module2) {
13294
13628
  module2.exports = {
13295
- version: "4.7.0",
13629
+ version: "4.7.2",
13296
13630
  keywords: [
13297
13631
  "strapi",
13298
13632
  "plugin",
@@ -13350,7 +13684,7 @@ var require_package = __commonJS({
13350
13684
  },
13351
13685
  dependencies: {
13352
13686
  "@maxmind/geoip2-node": "^6.3.4",
13353
- "sanitize-html": "^2.17.5"
13687
+ "sanitize-html": "^2.17.6"
13354
13688
  },
13355
13689
  devDependencies: {
13356
13690
  "@semantic-release/changelog": "^6.0.3",