strapi-plugin-magic-sessionmanager 4.7.0 → 4.7.1

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 +7 -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 +558 -301
  29. package/dist/server/index.mjs +558 -301
  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();
@@ -10018,7 +10125,10 @@ var require_bootstrap = __commonJS({
10018
10125
  fields: ["documentId", "isActive"]
10019
10126
  });
10020
10127
  if (matchingSession && matchingSession.isActive) {
10021
- await sessionService.terminateSession({ sessionId: matchingSession.documentId });
10128
+ await sessionService.terminateSession({
10129
+ sessionId: matchingSession.documentId,
10130
+ reason: "logout"
10131
+ });
10022
10132
  log.info(`[LOGOUT] Session ${matchingSession.documentId} terminated (expiredButValid=${expiredButValid})`);
10023
10133
  }
10024
10134
  ctx.status = 200;
@@ -10035,6 +10145,36 @@ var require_bootstrap = __commonJS({
10035
10145
  }]);
10036
10146
  log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
10037
10147
  }
10148
+ function hasRegisteredRoute(strapi2, method, path) {
10149
+ try {
10150
+ const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
10151
+ const directRoutes = strapi2.server.listRoutes?.() || [];
10152
+ const contentRoutes = strapi2.server.api?.("content-api")?.listRoutes?.() || [];
10153
+ return [...directRoutes, ...contentRoutes].some((route) => {
10154
+ const methods = route.methods || (Array.isArray(route.method) ? route.method : [route.method]);
10155
+ const routePaths = /* @__PURE__ */ new Set([
10156
+ route.path,
10157
+ route.path?.startsWith(apiPrefix) ? route.path : `${apiPrefix}${route.path}`
10158
+ ]);
10159
+ return routePaths.has(path) && methods.some((value) => String(value).toUpperCase() === method);
10160
+ });
10161
+ } catch {
10162
+ return false;
10163
+ }
10164
+ }
10165
+ function failClosedAuthResponse({ ctx, strapi: strapi2, log, operation, error }) {
10166
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
10167
+ ctx.status = 503;
10168
+ if (typeof ctx.set === "function") ctx.set("Retry-After", "1");
10169
+ ctx.body = {
10170
+ error: {
10171
+ status: 503,
10172
+ name: "ServiceUnavailableError",
10173
+ message: "Authentication temporarily unavailable. Please try again."
10174
+ }
10175
+ };
10176
+ log.error(`[AUTH-FAIL-CLOSED] ${operation}:`, error?.message || error || "session persistence failed");
10177
+ }
10038
10178
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
10039
10179
  const WINDOW_MS = 15 * 60 * 1e3;
10040
10180
  const failed = /* @__PURE__ */ new Map();
@@ -10062,7 +10202,7 @@ var require_bootstrap = __commonJS({
10062
10202
  };
10063
10203
  const clearFailures = (ip) => failed.delete(ip);
10064
10204
  strapi2.server.use(async (ctx, next) => {
10065
- if (!isLoginPath(ctx.path, ctx.method)) return next();
10205
+ if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
10066
10206
  const settings = await getRequestSettings(strapi2, ctx);
10067
10207
  const maxFailed = Number(settings.maxFailedLogins) || 0;
10068
10208
  if (maxFailed <= 0) return next();
@@ -10099,30 +10239,42 @@ var require_bootstrap = __commonJS({
10099
10239
  });
10100
10240
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
10101
10241
  }
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
10242
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
10119
10243
  strapi2.server.use(async (ctx, next) => {
10244
+ const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
10245
+ const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
10120
10246
  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;
10247
+ if (requestType !== "new-session" && requestType !== "rotate-current") return;
10248
+ if (ctx.status < 200 || ctx.status >= 300) return;
10249
+ if (!ctx.body || !ctx.body.jwt) return;
10250
+ const refreshCookieName = getRefreshCookieName(strapi2);
10251
+ if (requestType === "rotate-current") {
10252
+ try {
10253
+ if (!previousAccessToken) throw new Error("current access token is missing");
10254
+ const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10255
+ filters: {
10256
+ tokenHash: hashToken(previousAccessToken),
10257
+ isActive: true
10258
+ },
10259
+ fields: ["documentId"]
10260
+ });
10261
+ if (!matchingSession) throw new Error("current session was not found");
10262
+ const rotated = await sessionService.rotateSessionTokens({
10263
+ sessionId: matchingSession.documentId,
10264
+ expectedAccessToken: previousAccessToken,
10265
+ accessToken: ctx.body.jwt,
10266
+ refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName)
10267
+ });
10268
+ if (!rotated) throw new Error("current session changed before token rotation");
10269
+ log.info(`[PASSWORD] Tokens rotated for session ${matchingSession.documentId}`);
10270
+ } catch (err) {
10271
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "change-password rotation failed", error: err });
10272
+ }
10273
+ return;
10274
+ }
10124
10275
  try {
10125
10276
  const user = ctx.body.user;
10277
+ if (!user) throw new Error("authentication response contains no user");
10126
10278
  await getRequestSettings(strapi2, ctx);
10127
10279
  const ip = getClientIp(ctx);
10128
10280
  const headers = ctx.request.headers || ctx.request.header || {};
@@ -10133,8 +10285,7 @@ var require_bootstrap = __commonJS({
10133
10285
  userDocId = await resolveUserDocumentId(strapi2, user.id);
10134
10286
  }
10135
10287
  if (!userDocId) {
10136
- log.error(`[ERROR] Could not resolve documentId for user ${user.id || "unknown"} - session NOT created!`);
10137
- return;
10288
+ throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
10138
10289
  }
10139
10290
  const geoData = ctx.state?.__magicSessionGeoData || null;
10140
10291
  const newSession = await sessionService.createSession({
@@ -10142,12 +10293,11 @@ var require_bootstrap = __commonJS({
10142
10293
  ip,
10143
10294
  userAgent,
10144
10295
  token: ctx.body.jwt,
10145
- refreshToken: ctx.body.refreshToken,
10296
+ refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
10146
10297
  geoData
10147
10298
  });
10148
10299
  if (!newSession?.documentId) {
10149
- log.error(`[ERROR] Session creation returned no documentId for user ${userDocId}`);
10150
- return;
10300
+ throw new Error(`session creation returned no documentId for user ${userDocId}`);
10151
10301
  }
10152
10302
  log.info(`[SUCCESS] Session ${newSession.documentId} created for user ${userDocId} (IP: ${ip})`);
10153
10303
  try {
@@ -10200,6 +10350,17 @@ var require_bootstrap = __commonJS({
10200
10350
  }
10201
10351
  }
10202
10352
  if (settings.enableEmailAlerts) {
10353
+ if (settings.alertOnVpnProxy && (geoData.isVpn || geoData.isProxy)) {
10354
+ await notificationService.sendVpnProxyAlert({
10355
+ user,
10356
+ session: newSession,
10357
+ reason: {
10358
+ isVpn: geoData.isVpn,
10359
+ isProxy: geoData.isProxy
10360
+ },
10361
+ geoData
10362
+ });
10363
+ }
10203
10364
  if (settings.alertOnSuspiciousLogin && isSuspicious) {
10204
10365
  await notificationService.sendSuspiciousLoginAlert({
10205
10366
  user,
@@ -10260,84 +10421,81 @@ var require_bootstrap = __commonJS({
10260
10421
  log.warn("Notification failed:", notifErr.message);
10261
10422
  }
10262
10423
  } catch (err) {
10263
- log.error("[ERROR] Error creating session:", err);
10424
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "session creation failed", error: err });
10264
10425
  }
10265
10426
  });
10266
10427
  log.info("[SUCCESS] Login interceptor middleware mounted");
10267
10428
  }
10268
- function mountRefreshTokenInterceptor({ strapi: strapi2, log }) {
10429
+ function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
10269
10430
  strapi2.server.use(async (ctx, next) => {
10270
10431
  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}`);
10432
+ if (!isRefreshToken) return next();
10433
+ const cookieName = getRefreshCookieName(strapi2);
10434
+ const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
10435
+ let matchingSession = null;
10436
+ try {
10437
+ if (oldRefreshToken) {
10438
+ matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10439
+ filters: {
10440
+ refreshTokenHash: hashToken(oldRefreshToken),
10441
+ isActive: true
10442
+ },
10443
+ fields: ["documentId"]
10444
+ });
10445
+ if (!matchingSession) {
10446
+ log.warn("[BLOCKED] Blocked refresh token request - no active session");
10447
+ ctx.status = 401;
10448
+ ctx.body = {
10449
+ error: {
10450
+ status: 401,
10451
+ name: "UnauthorizedError",
10452
+ message: "Session terminated. Please login again."
10453
+ }
10454
+ };
10455
+ return;
10297
10456
  }
10298
- } catch (err) {
10299
- log.error("Error checking refresh token:", err);
10300
10457
  }
10458
+ } catch (err) {
10459
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh validation failed", error: err });
10460
+ return;
10301
10461
  }
10302
10462
  await next();
10303
- if (isRefreshToken && ctx.status === 200 && ctx.body && ctx.body.jwt) {
10463
+ if (ctx.status >= 200 && ctx.status < 300 && ctx.body && ctx.body.jwt) {
10304
10464
  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
- }
10465
+ if (!oldRefreshToken || !matchingSession) {
10466
+ throw new Error("refresh response issued without a tracked input token");
10467
+ }
10468
+ const rotated = await sessionService.rotateSessionTokens({
10469
+ sessionId: matchingSession.documentId,
10470
+ expectedRefreshToken: oldRefreshToken,
10471
+ accessToken: ctx.body.jwt,
10472
+ refreshToken: getOutgoingRefreshToken(ctx, cookieName)
10332
10473
  });
10474
+ if (!rotated) throw new Error("refresh token was already consumed");
10333
10475
  log.info(`[REFRESH] Tokens refreshed for session ${matchingSession.documentId}`);
10334
10476
  } catch (err) {
10335
- log.error("Error updating refreshed tokens:", err);
10477
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh rotation failed", error: err });
10336
10478
  }
10337
10479
  }
10338
10480
  });
10339
10481
  log.info("[SUCCESS] Refresh token interceptor middleware mounted");
10340
10482
  }
10483
+ function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
10484
+ strapi2.server.use(async (ctx, next) => {
10485
+ if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
10486
+ const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
10487
+ if (refreshToken) {
10488
+ try {
10489
+ await sessionService.terminateSessionByRefreshToken(refreshToken);
10490
+ } catch (err) {
10491
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
10492
+ return;
10493
+ }
10494
+ }
10495
+ await next();
10496
+ });
10497
+ log.info("[SUCCESS] Logout interceptor middleware mounted");
10498
+ }
10341
10499
  async function ensureContentApiPermissions(strapi2, log) {
10342
10500
  const PERMISSIONS_VERSION = 2;
10343
10501
  try {
@@ -10403,42 +10561,45 @@ var require_bootstrap = __commonJS({
10403
10561
  log.warn("Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated");
10404
10562
  }
10405
10563
  }
10406
- async function ensureTokenHashIndex(strapi2, log) {
10564
+ async function ensureSessionLookupIndexes(strapi2, log) {
10407
10565
  try {
10408
10566
  const knex = strapi2.db.connection;
10409
10567
  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;
10568
+ const definitions = [
10569
+ { column: "token_hash", name: "idx_magic_sessions_token_hash" },
10570
+ { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
10571
+ ];
10572
+ if (!await knex.schema.hasTable(tableName)) return;
10573
+ for (const definition of definitions) {
10413
10574
  const dialect = strapi2.db.dialect.client;
10575
+ let hasIndex = false;
10414
10576
  if (dialect === "postgres") {
10415
10577
  const result = await knex.raw(
10416
10578
  "SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?",
10417
- [tableName, indexName]
10579
+ [tableName, definition.name]
10418
10580
  );
10419
- return result.rows.length > 0;
10581
+ hasIndex = result.rows.length > 0;
10420
10582
  } 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;
10583
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName, definition.name]);
10584
+ hasIndex = result[0].length > 0;
10423
10585
  } else if (dialect === "sqlite" || dialect === "better-sqlite3") {
10424
10586
  const result = await knex.raw(
10425
10587
  "SELECT name FROM sqlite_master WHERE type='index' AND name = ?",
10426
- [indexName]
10588
+ [definition.name]
10427
10589
  );
10428
- return result.length > 0;
10590
+ hasIndex = result.length > 0;
10429
10591
  }
10430
- return false;
10431
- });
10432
- if (hasIndex) {
10433
- log.debug("[INDEX] tokenHash index already exists");
10434
- return;
10592
+ if (hasIndex) {
10593
+ log.debug(`[INDEX] ${definition.name} already exists`);
10594
+ continue;
10595
+ }
10596
+ await knex.schema.alterTable(tableName, (table) => {
10597
+ table.index([definition.column, "is_active"], definition.name);
10598
+ });
10599
+ log.info(`[INDEX] Created ${definition.name}`);
10435
10600
  }
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
10601
  } catch (err) {
10441
- log.debug("[INDEX] Could not create tokenHash index (will retry on next startup):", err.message);
10602
+ log.debug("[INDEX] Could not create session lookup indexes (will retry on next startup):", err.message);
10442
10603
  }
10443
10604
  }
10444
10605
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
@@ -10530,6 +10691,16 @@ var require_bootstrap = __commonJS({
10530
10691
  fields: ["documentId", "isActive", "terminatedManually", "terminationReason", "lastActive", "loginTime"]
10531
10692
  });
10532
10693
  if (thisSession) {
10694
+ if (thisSession.isActive === false) {
10695
+ const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : null);
10696
+ if (reason) {
10697
+ strapi2.log.info(
10698
+ `[magic-sessionmanager] [JWT-REJECTED] Session inactive (reason: ${reason}) for user ${userDocId.substring(0, 8)}...`
10699
+ );
10700
+ setSessionRejectionReason(tokenHashValue, reason);
10701
+ return null;
10702
+ }
10703
+ }
10533
10704
  if (isSessionExpired(thisSession, maxSessionAgeDays)) {
10534
10705
  strapi2.log.info(
10535
10706
  `[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days (user: ${userDocId.substring(0, 8)}...)`
@@ -10546,20 +10717,6 @@ var require_bootstrap = __commonJS({
10546
10717
  setSessionRejectionReason(tokenHashValue, "expired");
10547
10718
  return null;
10548
10719
  }
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
10720
  const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
10564
10721
  const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
10565
10722
  const idleFor = Date.now() - lastActiveMs;
@@ -10570,6 +10727,7 @@ var require_bootstrap = __commonJS({
10570
10727
  await strapi2.documents(SESSION_UID).update({
10571
10728
  documentId: thisSession.documentId,
10572
10729
  data: {
10730
+ isActive: false,
10573
10731
  terminatedManually: false,
10574
10732
  terminationReason: "idle",
10575
10733
  logoutTime: /* @__PURE__ */ new Date()
@@ -10578,6 +10736,10 @@ var require_bootstrap = __commonJS({
10578
10736
  setSessionRejectionReason(tokenHashValue, "idle");
10579
10737
  return null;
10580
10738
  }
10739
+ if (thisSession.isActive) {
10740
+ resetErrorCounter();
10741
+ return decoded;
10742
+ }
10581
10743
  await strapi2.documents(SESSION_UID).update({
10582
10744
  documentId: thisSession.documentId,
10583
10745
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
@@ -10627,6 +10789,14 @@ var require_bootstrap = __commonJS({
10627
10789
  strapi2.log.warn("[magic-sessionmanager] [AUTH] Session validation will only work via middleware (plugin endpoints)");
10628
10790
  }
10629
10791
  }
10792
+ module.exports.__private = {
10793
+ registerSessionAwareAuthStrategy,
10794
+ mountPreLoginGeoGuard,
10795
+ mountLoginInterceptor,
10796
+ mountRefreshTokenInterceptor,
10797
+ mountLogoutInterceptor,
10798
+ mountLogoutRoute
10799
+ };
10630
10800
  }
10631
10801
  });
10632
10802
 
@@ -10667,6 +10837,12 @@ var require_config = __commonJS({
10667
10837
  cleanupInterval: 30 * 60 * 1e3,
10668
10838
  retentionDays: 90,
10669
10839
  maxSessionAgeDays: 30,
10840
+ maxFailedLogins: 5,
10841
+ sessionCreationGraceMs: 5e3,
10842
+ cleanupUseDbDirect: false,
10843
+ rateLimitWriteMax: 10,
10844
+ rateLimitReadMax: 120,
10845
+ rateLimitWindowSeconds: 60,
10670
10846
  strictSessionEnforcement: false,
10671
10847
  enableGeolocation: true,
10672
10848
  enableSecurityScoring: true,
@@ -10804,7 +10980,7 @@ var require_schema = __commonJS({
10804
10980
  },
10805
10981
  terminationReason: {
10806
10982
  type: "enumeration",
10807
- enum: ["manual", "idle", "expired", "blocked"],
10983
+ enum: ["logout", "manual", "idle", "expired", "blocked"],
10808
10984
  required: false
10809
10985
  },
10810
10986
  geoLocation: {
@@ -11265,6 +11441,9 @@ var require_enhance_session = __commonJS({
11265
11441
  "use strict";
11266
11442
  var { parseUserAgent } = require_user_agent_parser();
11267
11443
  var SESSION_UID = "plugin::magic-sessionmanager.session";
11444
+ function shouldResolveGeoData(settings = {}) {
11445
+ return settings.enableGeolocation === true || settings.enableGeofencing === true || settings.blockSuspiciousSessions === true;
11446
+ }
11268
11447
  async function enhanceSession(session, opts = {}) {
11269
11448
  const {
11270
11449
  inactivityTimeout = 15 * 60 * 1e3,
@@ -11316,7 +11495,7 @@ var require_enhance_session = __commonJS({
11316
11495
  documentId: session.documentId,
11317
11496
  data: {
11318
11497
  geoLocation,
11319
- securityScore: geoData.securityScore || null
11498
+ securityScore: geoData.securityScore ?? null
11320
11499
  }
11321
11500
  }).catch(() => {
11322
11501
  });
@@ -11353,7 +11532,7 @@ var require_enhance_session = __commonJS({
11353
11532
  sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now }))
11354
11533
  );
11355
11534
  }
11356
- module.exports = { enhanceSession, enhanceSessions };
11535
+ module.exports = { enhanceSession, enhanceSessions, shouldResolveGeoData };
11357
11536
  }
11358
11537
  });
11359
11538
 
@@ -11362,7 +11541,11 @@ var require_session = __commonJS({
11362
11541
  "server/src/controllers/session.js"(exports, module) {
11363
11542
  "use strict";
11364
11543
  var { hashToken } = require_encryption();
11365
- var { enhanceSessions, enhanceSession } = require_enhance_session();
11544
+ var {
11545
+ enhanceSessions,
11546
+ enhanceSession,
11547
+ shouldResolveGeoData
11548
+ } = require_enhance_session();
11366
11549
  var { resolveUserDocumentId } = require_resolve_user();
11367
11550
  var {
11368
11551
  getPluginSettings,
@@ -11440,7 +11623,7 @@ var require_session = __commonJS({
11440
11623
  const settings = await getPluginSettings(strapi);
11441
11624
  const enhanceOpts = {
11442
11625
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
11443
- geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
11626
+ geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
11444
11627
  strapi
11445
11628
  };
11446
11629
  const sessionsWithCurrent = await enhanceSessions(paged, enhanceOpts, 20);
@@ -11524,7 +11707,7 @@ var require_session = __commonJS({
11524
11707
  if (matchingSession) {
11525
11708
  await sessionService.terminateSession({
11526
11709
  sessionId: matchingSession.documentId,
11527
- reason: "manual"
11710
+ reason: "logout"
11528
11711
  });
11529
11712
  terminated = true;
11530
11713
  strapi.log.info(`[magic-sessionmanager] User ${userDocId} logged out (session ${matchingSession.documentId})`);
@@ -11542,7 +11725,7 @@ var require_session = __commonJS({
11542
11725
  * Terminates EVERY session of the authenticated user — including the
11543
11726
  * current one. After this call the caller will also be logged out on
11544
11727
  * the next request (their own JWT is rejected by the JWT-verify wrapper
11545
- * with reason=manual).
11728
+ * with reason=logout).
11546
11729
  *
11547
11730
  * For the "log me out everywhere ELSE but keep me here" flow, use
11548
11731
  * `/logout-others` below.
@@ -11558,7 +11741,7 @@ var require_session = __commonJS({
11558
11741
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
11559
11742
  const { terminatedCount } = await sessionService.terminateSession({
11560
11743
  userId: userDocId,
11561
- reason: "manual"
11744
+ reason: "logout"
11562
11745
  });
11563
11746
  strapi.log.info(
11564
11747
  `[magic-sessionmanager] User ${userDocId} logged out from all devices (${terminatedCount})`
@@ -11602,7 +11785,7 @@ var require_session = __commonJS({
11602
11785
  if (!currentSession) {
11603
11786
  const { terminatedCount: terminatedCount2 } = await sessionService.terminateSession({
11604
11787
  userId: userDocId,
11605
- reason: "manual"
11788
+ reason: "logout"
11606
11789
  });
11607
11790
  strapi.log.warn(
11608
11791
  `[magic-sessionmanager] logoutOthers fell back to logoutAll for user ${userDocId} (no current session match)`
@@ -11617,7 +11800,7 @@ var require_session = __commonJS({
11617
11800
  const { terminatedCount } = await sessionService.terminateSession({
11618
11801
  userId: userDocId,
11619
11802
  exceptSessionId: currentSession.documentId,
11620
- reason: "manual"
11803
+ reason: "logout"
11621
11804
  });
11622
11805
  strapi.log.info(
11623
11806
  `[magic-sessionmanager] User ${userDocId} logged out ${terminatedCount} other device(s)`
@@ -11678,7 +11861,7 @@ var require_session = __commonJS({
11678
11861
  const settings = await getPluginSettings(strapi);
11679
11862
  const enhanced = await enhanceSession(currentSession, {
11680
11863
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
11681
- geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
11864
+ geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
11682
11865
  geoCounter: { remaining: 1 },
11683
11866
  strapi
11684
11867
  });
@@ -12234,6 +12417,55 @@ var require_settings = __commonJS({
12234
12417
  }
12235
12418
  return result;
12236
12419
  }
12420
+ var DEFAULT_EMAIL_TEMPLATES = {
12421
+ suspiciousLogin: { subject: "", html: "", text: "" },
12422
+ newLocation: { subject: "", html: "", text: "" },
12423
+ vpnProxy: { subject: "", html: "", text: "" }
12424
+ };
12425
+ var DEFAULT_SETTINGS = {
12426
+ inactivityTimeout: 15,
12427
+ cleanupInterval: 30,
12428
+ lastSeenRateLimit: 30,
12429
+ retentionDays: 90,
12430
+ maxSessionAgeDays: 30,
12431
+ sessionCreationGraceMs: 5e3,
12432
+ cleanupUseDbDirect: false,
12433
+ rateLimitWriteMax: 10,
12434
+ rateLimitReadMax: 120,
12435
+ rateLimitWindowSeconds: 60,
12436
+ enableGeolocation: true,
12437
+ enableSecurityScoring: true,
12438
+ blockSuspiciousSessions: false,
12439
+ maxFailedLogins: 5,
12440
+ enableGeofencing: false,
12441
+ allowedCountries: [],
12442
+ blockedCountries: [],
12443
+ geoIpProvider: "auto",
12444
+ geoIpDatabasePath: "",
12445
+ geoLookupFailureMode: "auto",
12446
+ enableEmailAlerts: false,
12447
+ alertOnSuspiciousLogin: true,
12448
+ alertOnNewLocation: true,
12449
+ alertOnVpnProxy: true,
12450
+ enableWebhooks: false,
12451
+ discordWebhookUrl: "",
12452
+ slackWebhookUrl: "",
12453
+ strictSessionEnforcement: false,
12454
+ trustedProxies: false,
12455
+ emailTemplates: DEFAULT_EMAIL_TEMPLATES
12456
+ };
12457
+ function mergeSettingsWithDefaults(stored) {
12458
+ const safeStored = stored && typeof stored === "object" ? stored : {};
12459
+ const storedTemplates = safeStored.emailTemplates && typeof safeStored.emailTemplates === "object" ? safeStored.emailTemplates : {};
12460
+ return {
12461
+ ...DEFAULT_SETTINGS,
12462
+ ...safeStored,
12463
+ emailTemplates: {
12464
+ ...DEFAULT_EMAIL_TEMPLATES,
12465
+ ...storedTemplates
12466
+ }
12467
+ };
12468
+ }
12237
12469
  module.exports = {
12238
12470
  /**
12239
12471
  * Returns the current plugin settings (user-facing units: minutes/seconds/days).
@@ -12245,51 +12477,8 @@ var require_settings = __commonJS({
12245
12477
  type: "plugin",
12246
12478
  name: "magic-sessionmanager"
12247
12479
  });
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
- }
12480
+ const storedSettings = await pluginStore.get({ key: "settings" });
12481
+ const settings = mergeSettingsWithDefaults(storedSettings);
12293
12482
  ctx.send({
12294
12483
  settings,
12295
12484
  success: true
@@ -12327,6 +12516,9 @@ var require_settings = __commonJS({
12327
12516
  maxSessionAgeDays: Math.max(1, Math.min(parseInt(body.maxSessionAgeDays) || 30, 365)),
12328
12517
  sessionCreationGraceMs: grace,
12329
12518
  cleanupUseDbDirect: !!body.cleanupUseDbDirect,
12519
+ rateLimitWriteMax: Math.max(1, Math.min(parseInt(body.rateLimitWriteMax) || 10, 1e3)),
12520
+ rateLimitReadMax: Math.max(1, Math.min(parseInt(body.rateLimitReadMax) || 120, 1e4)),
12521
+ rateLimitWindowSeconds: Math.max(10, Math.min(parseInt(body.rateLimitWindowSeconds) || 60, 3600)),
12330
12522
  // Geo / security
12331
12523
  enableGeolocation: !!body.enableGeolocation,
12332
12524
  enableSecurityScoring: !!body.enableSecurityScoring,
@@ -12367,7 +12559,9 @@ var require_settings = __commonJS({
12367
12559
  strapi.log.error("[magic-sessionmanager/settings] Error updating settings:", error);
12368
12560
  ctx.badRequest("Error saving settings");
12369
12561
  }
12370
- }
12562
+ },
12563
+ DEFAULT_SETTINGS,
12564
+ mergeSettingsWithDefaults
12371
12565
  };
12372
12566
  }
12373
12567
  });
@@ -12761,7 +12955,7 @@ var require_session2 = __commonJS({
12761
12955
  var { createLogger } = require_logger();
12762
12956
  var { parseUserAgent } = require_user_agent_parser();
12763
12957
  var { resolveUserDocumentId } = require_resolve_user();
12764
- var { enhanceSessions } = require_enhance_session();
12958
+ var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
12765
12959
  var { getPluginSettings } = require_settings_loader();
12766
12960
  var SESSION_UID = "plugin::magic-sessionmanager.session";
12767
12961
  var MAX_SESSIONS_QUERY = 1e3;
@@ -12771,7 +12965,7 @@ var require_session2 = __commonJS({
12771
12965
  const settings = await getPluginSettings(strapi2);
12772
12966
  return {
12773
12967
  inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
12774
- geolocationService: strapi2.plugin("magic-sessionmanager").service("geolocation"),
12968
+ geolocationService: shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null,
12775
12969
  strapi: strapi2
12776
12970
  };
12777
12971
  }
@@ -12826,7 +13020,7 @@ var require_session2 = __commonJS({
12826
13020
  region: geoData.region,
12827
13021
  timezone: geoData.timezone
12828
13022
  } : null,
12829
- securityScore: geoData?.securityScore || null
13023
+ securityScore: geoData?.securityScore ?? null
12830
13024
  }
12831
13025
  });
12832
13026
  log.info(`[SUCCESS] Session ${session.documentId} (${sessionId}) created for user ${userId}`);
@@ -12836,19 +13030,72 @@ var require_session2 = __commonJS({
12836
13030
  throw err;
12837
13031
  }
12838
13032
  },
13033
+ /**
13034
+ * Atomically replaces the stored tokens only while the caller still owns
13035
+ * the expected active token. This prevents two concurrent refresh
13036
+ * requests from both committing a rotation.
13037
+ *
13038
+ * @returns {Promise<boolean>} Whether exactly one session was rotated
13039
+ */
13040
+ async rotateSessionTokens({
13041
+ sessionId,
13042
+ expectedAccessToken,
13043
+ expectedRefreshToken,
13044
+ accessToken,
13045
+ refreshToken
13046
+ }) {
13047
+ if (!sessionId || !accessToken || !expectedAccessToken && !expectedRefreshToken) {
13048
+ return false;
13049
+ }
13050
+ const where = { documentId: sessionId, isActive: true };
13051
+ if (expectedAccessToken) where.tokenHash = hashToken(expectedAccessToken);
13052
+ if (expectedRefreshToken) where.refreshTokenHash = hashToken(expectedRefreshToken);
13053
+ const data = {
13054
+ token: encryptToken(accessToken),
13055
+ tokenHash: hashToken(accessToken),
13056
+ lastActive: /* @__PURE__ */ new Date()
13057
+ };
13058
+ if (refreshToken) {
13059
+ data.refreshToken = encryptToken(refreshToken);
13060
+ data.refreshTokenHash = hashToken(refreshToken);
13061
+ }
13062
+ const result = await strapi2.db.query(SESSION_UID).updateMany({ where, data });
13063
+ return result?.count === 1;
13064
+ },
13065
+ /**
13066
+ * Terminates the active session identified by a raw refresh token.
13067
+ * Used by Strapi's built-in cookie/body logout endpoint.
13068
+ */
13069
+ async terminateSessionByRefreshToken(refreshToken) {
13070
+ if (!refreshToken) return false;
13071
+ const result = await strapi2.db.query(SESSION_UID).updateMany({
13072
+ where: {
13073
+ refreshTokenHash: hashToken(refreshToken),
13074
+ isActive: true
13075
+ },
13076
+ data: {
13077
+ isActive: false,
13078
+ terminatedManually: false,
13079
+ terminationReason: "logout",
13080
+ logoutTime: /* @__PURE__ */ new Date()
13081
+ }
13082
+ });
13083
+ return result?.count === 1;
13084
+ },
12839
13085
  /**
12840
13086
  * Terminates a single session, all sessions of a user, or all sessions
12841
13087
  * of a user EXCEPT one with a typed reason so the JWT-verify wrapper
12842
13088
  * can communicate the cause to the client.
12843
13089
  *
12844
13090
  * Supported reasons:
12845
- * - 'manual': user clicked logout, or admin terminated a session
13091
+ * - 'logout': user clicked logout
13092
+ * - 'manual': admin terminated a session
12846
13093
  * - 'idle': inactivity timeout cleanup
12847
13094
  * - 'expired': maxSessionAgeDays exceeded
12848
13095
  * - 'blocked': the owning user was marked blocked
12849
13096
  *
12850
13097
  * For backwards compatibility `terminatedManually` is still set true
12851
- * only when reason === 'manual'; idle/expired/blocked paths set it
13098
+ * only when reason === 'manual'; logout/idle/expired/blocked paths set it
12852
13099
  * false so reporting dashboards that queried that boolean continue
12853
13100
  * to work, while new code relies on `terminationReason`.
12854
13101
  *
@@ -12861,13 +13108,13 @@ var require_session2 = __commonJS({
12861
13108
  * `userId`. Used by
12862
13109
  * /logout-other-devices so
12863
13110
  * the caller stays logged in.
12864
- * @param {'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
13111
+ * @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
12865
13112
  * @returns {Promise<{terminatedCount: number}>}
12866
13113
  */
12867
13114
  async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
12868
13115
  try {
12869
13116
  const now = /* @__PURE__ */ new Date();
12870
- const validReasons = ["manual", "idle", "expired", "blocked"];
13117
+ const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
12871
13118
  const finalReason = validReasons.includes(reason) ? reason : "manual";
12872
13119
  const updateData = {
12873
13120
  isActive: false,
@@ -12898,21 +13145,31 @@ var require_session2 = __commonJS({
12898
13145
  if (exceptSessionId) {
12899
13146
  filters.documentId = { $ne: exceptSessionId };
12900
13147
  }
12901
- const activeSessions = await strapi2.documents(SESSION_UID).findMany({
12902
- filters,
12903
- fields: ["documentId"],
12904
- limit: MAX_SESSIONS_QUERY
12905
- });
12906
13148
  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);
13149
+ const batchSize = 500;
13150
+ while (true) {
13151
+ const activeSessions = await strapi2.documents(SESSION_UID).findMany({
13152
+ filters,
13153
+ fields: ["documentId"],
13154
+ limit: batchSize
13155
+ });
13156
+ if (!activeSessions || activeSessions.length === 0) break;
13157
+ let batchTerminated = 0;
13158
+ for (const session of activeSessions) {
13159
+ try {
13160
+ await strapi2.documents(SESSION_UID).update({
13161
+ documentId: session.documentId,
13162
+ data: updateData
13163
+ });
13164
+ terminatedCount++;
13165
+ batchTerminated++;
13166
+ } catch (err) {
13167
+ log.debug(`Failed to terminate session ${session.documentId}:`, err.message);
13168
+ }
13169
+ }
13170
+ if (batchTerminated === 0) {
13171
+ log.warn(`Could not terminate remaining active sessions for user ${userDocumentId}`);
13172
+ break;
12916
13173
  }
12917
13174
  }
12918
13175
  const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
@@ -13298,7 +13555,7 @@ var require_session2 = __commonJS({
13298
13555
  var require_package = __commonJS({
13299
13556
  "package.json"(exports, module) {
13300
13557
  module.exports = {
13301
- version: "4.7.0",
13558
+ version: "4.7.1",
13302
13559
  keywords: [
13303
13560
  "strapi",
13304
13561
  "plugin",
@@ -13356,7 +13613,7 @@ var require_package = __commonJS({
13356
13613
  },
13357
13614
  dependencies: {
13358
13615
  "@maxmind/geoip2-node": "^6.3.4",
13359
- "sanitize-html": "^2.17.5"
13616
+ "sanitize-html": "^2.17.6"
13360
13617
  },
13361
13618
  devDependencies: {
13362
13619
  "@semantic-release/changelog": "^6.0.3",