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.
- package/CHANGELOG.md +7 -0
- package/dist/admin/{Analytics-Dq8PuDhs.mjs → Analytics-CsrpxJwQ.mjs} +86 -69
- package/dist/admin/{Analytics-Cw6R2xZn.js → Analytics-D03ZNNMR.js} +86 -69
- package/dist/admin/{App-DLR2M3FT.js → App-B2VCS3cz.js} +22 -27
- package/dist/admin/{App-BIFTc3mk.mjs → App-qxKnK7G2.mjs} +9 -14
- package/dist/admin/{License-W_NPUWIn.mjs → License-ClW7sZLR.mjs} +1 -1
- package/dist/admin/{License-BZtjgFol.js → License-fixnQ7wF.js} +1 -1
- package/dist/admin/{OnlineUsersWidget-BIbmzgLP.mjs → OnlineUsersWidget-mR_OMiwi.mjs} +1 -2
- package/dist/admin/{OnlineUsersWidget-CAdR0MfU.js → OnlineUsersWidget-qb9utPBy.js} +1 -2
- package/dist/admin/{Settings-BNu9EAuS.mjs → Settings-U3V4eGMo.mjs} +1 -1
- package/dist/admin/{Settings-DWaflQdm.js → Settings-gv2BF54w.js} +1 -1
- package/dist/admin/{de-jU7AaYIc.js → de-BnqGCokx.js} +2 -2
- package/dist/admin/{de-4pAz-Ihh.mjs → de-JBE-iylO.mjs} +2 -2
- package/dist/admin/{en-Tjp9AEhR.js → en-BRmVwd8-.js} +2 -2
- package/dist/admin/{en-BI_aBNXG.mjs → en-kQWtdEai.mjs} +2 -2
- package/dist/admin/{es-BCgwFZPL.js → es-CH691xcL.js} +2 -2
- package/dist/admin/{es-Bp4Uzf5h.mjs → es-DOQvBxih.mjs} +2 -2
- package/dist/admin/{fr-Di5zo4wy.js → fr-CLExO0w_.js} +2 -2
- package/dist/admin/{fr-B69qIjq2.mjs → fr-CmfCpepX.mjs} +2 -2
- package/dist/admin/{index-eSND7TDx.mjs → index-B_lFjUAg.mjs} +15 -15
- package/dist/admin/{index-CBS3aqCW.js → index-Duc7cR_d.js} +15 -15
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/{pt-DlGYOi6D.js → pt-BJ_F0yNi.js} +2 -2
- package/dist/admin/{pt-Drc-di4D.mjs → pt-BSzZdyAH.mjs} +2 -2
- package/dist/admin/sessionStatus-D_fWEzgj.js +11 -0
- package/dist/admin/sessionStatus-kwggjEMw.mjs +12 -0
- package/dist/server/index.js +558 -301
- package/dist/server/index.mjs +558 -301
- package/package.json +2 -2
package/dist/server/index.js
CHANGED
|
@@ -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
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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
|
|
615
|
+
if (geoData.isVpn) {
|
|
640
616
|
return { blocked: true, reason: "vpn_detected", status };
|
|
641
617
|
}
|
|
642
|
-
if (geoData.isProxy
|
|
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
|
|
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
|
|
896
|
+
return;
|
|
778
897
|
}
|
|
779
898
|
}
|
|
780
899
|
if (!userDocId) {
|
|
781
|
-
return
|
|
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
|
-
|
|
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
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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 (!
|
|
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
|
-
|
|
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();
|
|
@@ -10012,7 +10119,10 @@ var require_bootstrap = __commonJS({
|
|
|
10012
10119
|
fields: ["documentId", "isActive"]
|
|
10013
10120
|
});
|
|
10014
10121
|
if (matchingSession && matchingSession.isActive) {
|
|
10015
|
-
await sessionService.terminateSession({
|
|
10122
|
+
await sessionService.terminateSession({
|
|
10123
|
+
sessionId: matchingSession.documentId,
|
|
10124
|
+
reason: "logout"
|
|
10125
|
+
});
|
|
10016
10126
|
log.info(`[LOGOUT] Session ${matchingSession.documentId} terminated (expiredButValid=${expiredButValid})`);
|
|
10017
10127
|
}
|
|
10018
10128
|
ctx.status = 200;
|
|
@@ -10029,6 +10139,36 @@ var require_bootstrap = __commonJS({
|
|
|
10029
10139
|
}]);
|
|
10030
10140
|
log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
|
|
10031
10141
|
}
|
|
10142
|
+
function hasRegisteredRoute(strapi2, method, path) {
|
|
10143
|
+
try {
|
|
10144
|
+
const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
|
|
10145
|
+
const directRoutes = strapi2.server.listRoutes?.() || [];
|
|
10146
|
+
const contentRoutes = strapi2.server.api?.("content-api")?.listRoutes?.() || [];
|
|
10147
|
+
return [...directRoutes, ...contentRoutes].some((route) => {
|
|
10148
|
+
const methods = route.methods || (Array.isArray(route.method) ? route.method : [route.method]);
|
|
10149
|
+
const routePaths = /* @__PURE__ */ new Set([
|
|
10150
|
+
route.path,
|
|
10151
|
+
route.path?.startsWith(apiPrefix) ? route.path : `${apiPrefix}${route.path}`
|
|
10152
|
+
]);
|
|
10153
|
+
return routePaths.has(path) && methods.some((value) => String(value).toUpperCase() === method);
|
|
10154
|
+
});
|
|
10155
|
+
} catch {
|
|
10156
|
+
return false;
|
|
10157
|
+
}
|
|
10158
|
+
}
|
|
10159
|
+
function failClosedAuthResponse({ ctx, strapi: strapi2, log, operation, error }) {
|
|
10160
|
+
stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
|
|
10161
|
+
ctx.status = 503;
|
|
10162
|
+
if (typeof ctx.set === "function") ctx.set("Retry-After", "1");
|
|
10163
|
+
ctx.body = {
|
|
10164
|
+
error: {
|
|
10165
|
+
status: 503,
|
|
10166
|
+
name: "ServiceUnavailableError",
|
|
10167
|
+
message: "Authentication temporarily unavailable. Please try again."
|
|
10168
|
+
}
|
|
10169
|
+
};
|
|
10170
|
+
log.error(`[AUTH-FAIL-CLOSED] ${operation}:`, error?.message || error || "session persistence failed");
|
|
10171
|
+
}
|
|
10032
10172
|
function mountFailedLoginLockout({ strapi: strapi2, log }) {
|
|
10033
10173
|
const WINDOW_MS = 15 * 60 * 1e3;
|
|
10034
10174
|
const failed = /* @__PURE__ */ new Map();
|
|
@@ -10056,7 +10196,7 @@ var require_bootstrap = __commonJS({
|
|
|
10056
10196
|
};
|
|
10057
10197
|
const clearFailures = (ip) => failed.delete(ip);
|
|
10058
10198
|
strapi2.server.use(async (ctx, next) => {
|
|
10059
|
-
if (!
|
|
10199
|
+
if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
|
|
10060
10200
|
const settings = await getRequestSettings(strapi2, ctx);
|
|
10061
10201
|
const maxFailed = Number(settings.maxFailedLogins) || 0;
|
|
10062
10202
|
if (maxFailed <= 0) return next();
|
|
@@ -10093,30 +10233,42 @@ var require_bootstrap = __commonJS({
|
|
|
10093
10233
|
});
|
|
10094
10234
|
log.info("[SUCCESS] Failed-login lockout middleware mounted");
|
|
10095
10235
|
}
|
|
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
10236
|
function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
10113
10237
|
strapi2.server.use(async (ctx, next) => {
|
|
10238
|
+
const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
|
|
10239
|
+
const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
|
|
10114
10240
|
await next();
|
|
10115
|
-
if (
|
|
10116
|
-
if (ctx.status
|
|
10117
|
-
if (!ctx.body || !ctx.body.jwt
|
|
10241
|
+
if (requestType !== "new-session" && requestType !== "rotate-current") return;
|
|
10242
|
+
if (ctx.status < 200 || ctx.status >= 300) return;
|
|
10243
|
+
if (!ctx.body || !ctx.body.jwt) return;
|
|
10244
|
+
const refreshCookieName = getRefreshCookieName(strapi2);
|
|
10245
|
+
if (requestType === "rotate-current") {
|
|
10246
|
+
try {
|
|
10247
|
+
if (!previousAccessToken) throw new Error("current access token is missing");
|
|
10248
|
+
const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
|
|
10249
|
+
filters: {
|
|
10250
|
+
tokenHash: hashToken(previousAccessToken),
|
|
10251
|
+
isActive: true
|
|
10252
|
+
},
|
|
10253
|
+
fields: ["documentId"]
|
|
10254
|
+
});
|
|
10255
|
+
if (!matchingSession) throw new Error("current session was not found");
|
|
10256
|
+
const rotated = await sessionService.rotateSessionTokens({
|
|
10257
|
+
sessionId: matchingSession.documentId,
|
|
10258
|
+
expectedAccessToken: previousAccessToken,
|
|
10259
|
+
accessToken: ctx.body.jwt,
|
|
10260
|
+
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName)
|
|
10261
|
+
});
|
|
10262
|
+
if (!rotated) throw new Error("current session changed before token rotation");
|
|
10263
|
+
log.info(`[PASSWORD] Tokens rotated for session ${matchingSession.documentId}`);
|
|
10264
|
+
} catch (err) {
|
|
10265
|
+
failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "change-password rotation failed", error: err });
|
|
10266
|
+
}
|
|
10267
|
+
return;
|
|
10268
|
+
}
|
|
10118
10269
|
try {
|
|
10119
10270
|
const user = ctx.body.user;
|
|
10271
|
+
if (!user) throw new Error("authentication response contains no user");
|
|
10120
10272
|
await getRequestSettings(strapi2, ctx);
|
|
10121
10273
|
const ip = getClientIp(ctx);
|
|
10122
10274
|
const headers = ctx.request.headers || ctx.request.header || {};
|
|
@@ -10127,8 +10279,7 @@ var require_bootstrap = __commonJS({
|
|
|
10127
10279
|
userDocId = await resolveUserDocumentId(strapi2, user.id);
|
|
10128
10280
|
}
|
|
10129
10281
|
if (!userDocId) {
|
|
10130
|
-
|
|
10131
|
-
return;
|
|
10282
|
+
throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
|
|
10132
10283
|
}
|
|
10133
10284
|
const geoData = ctx.state?.__magicSessionGeoData || null;
|
|
10134
10285
|
const newSession = await sessionService.createSession({
|
|
@@ -10136,12 +10287,11 @@ var require_bootstrap = __commonJS({
|
|
|
10136
10287
|
ip,
|
|
10137
10288
|
userAgent,
|
|
10138
10289
|
token: ctx.body.jwt,
|
|
10139
|
-
refreshToken: ctx
|
|
10290
|
+
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
|
|
10140
10291
|
geoData
|
|
10141
10292
|
});
|
|
10142
10293
|
if (!newSession?.documentId) {
|
|
10143
|
-
|
|
10144
|
-
return;
|
|
10294
|
+
throw new Error(`session creation returned no documentId for user ${userDocId}`);
|
|
10145
10295
|
}
|
|
10146
10296
|
log.info(`[SUCCESS] Session ${newSession.documentId} created for user ${userDocId} (IP: ${ip})`);
|
|
10147
10297
|
try {
|
|
@@ -10194,6 +10344,17 @@ var require_bootstrap = __commonJS({
|
|
|
10194
10344
|
}
|
|
10195
10345
|
}
|
|
10196
10346
|
if (settings.enableEmailAlerts) {
|
|
10347
|
+
if (settings.alertOnVpnProxy && (geoData.isVpn || geoData.isProxy)) {
|
|
10348
|
+
await notificationService.sendVpnProxyAlert({
|
|
10349
|
+
user,
|
|
10350
|
+
session: newSession,
|
|
10351
|
+
reason: {
|
|
10352
|
+
isVpn: geoData.isVpn,
|
|
10353
|
+
isProxy: geoData.isProxy
|
|
10354
|
+
},
|
|
10355
|
+
geoData
|
|
10356
|
+
});
|
|
10357
|
+
}
|
|
10197
10358
|
if (settings.alertOnSuspiciousLogin && isSuspicious) {
|
|
10198
10359
|
await notificationService.sendSuspiciousLoginAlert({
|
|
10199
10360
|
user,
|
|
@@ -10254,84 +10415,81 @@ var require_bootstrap = __commonJS({
|
|
|
10254
10415
|
log.warn("Notification failed:", notifErr.message);
|
|
10255
10416
|
}
|
|
10256
10417
|
} catch (err) {
|
|
10257
|
-
|
|
10418
|
+
failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "session creation failed", error: err });
|
|
10258
10419
|
}
|
|
10259
10420
|
});
|
|
10260
10421
|
log.info("[SUCCESS] Login interceptor middleware mounted");
|
|
10261
10422
|
}
|
|
10262
|
-
function mountRefreshTokenInterceptor({ strapi: strapi2, log }) {
|
|
10423
|
+
function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
10263
10424
|
strapi2.server.use(async (ctx, next) => {
|
|
10264
10425
|
const isRefreshToken = ctx.path === "/api/auth/refresh" && ctx.method === "POST";
|
|
10265
|
-
if (isRefreshToken)
|
|
10266
|
-
|
|
10267
|
-
|
|
10268
|
-
|
|
10269
|
-
|
|
10270
|
-
|
|
10271
|
-
|
|
10272
|
-
|
|
10273
|
-
|
|
10274
|
-
|
|
10275
|
-
|
|
10276
|
-
|
|
10277
|
-
|
|
10278
|
-
|
|
10279
|
-
|
|
10280
|
-
|
|
10281
|
-
|
|
10282
|
-
|
|
10283
|
-
|
|
10284
|
-
|
|
10285
|
-
|
|
10286
|
-
|
|
10287
|
-
|
|
10288
|
-
|
|
10289
|
-
}
|
|
10290
|
-
log.info(`[SUCCESS] Refresh token allowed for session ${matchingSession.documentId}`);
|
|
10426
|
+
if (!isRefreshToken) return next();
|
|
10427
|
+
const cookieName = getRefreshCookieName(strapi2);
|
|
10428
|
+
const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
|
|
10429
|
+
let matchingSession = null;
|
|
10430
|
+
try {
|
|
10431
|
+
if (oldRefreshToken) {
|
|
10432
|
+
matchingSession = await strapi2.documents(SESSION_UID).findFirst({
|
|
10433
|
+
filters: {
|
|
10434
|
+
refreshTokenHash: hashToken(oldRefreshToken),
|
|
10435
|
+
isActive: true
|
|
10436
|
+
},
|
|
10437
|
+
fields: ["documentId"]
|
|
10438
|
+
});
|
|
10439
|
+
if (!matchingSession) {
|
|
10440
|
+
log.warn("[BLOCKED] Blocked refresh token request - no active session");
|
|
10441
|
+
ctx.status = 401;
|
|
10442
|
+
ctx.body = {
|
|
10443
|
+
error: {
|
|
10444
|
+
status: 401,
|
|
10445
|
+
name: "UnauthorizedError",
|
|
10446
|
+
message: "Session terminated. Please login again."
|
|
10447
|
+
}
|
|
10448
|
+
};
|
|
10449
|
+
return;
|
|
10291
10450
|
}
|
|
10292
|
-
} catch (err) {
|
|
10293
|
-
log.error("Error checking refresh token:", err);
|
|
10294
10451
|
}
|
|
10452
|
+
} catch (err) {
|
|
10453
|
+
failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh validation failed", error: err });
|
|
10454
|
+
return;
|
|
10295
10455
|
}
|
|
10296
10456
|
await next();
|
|
10297
|
-
if (
|
|
10457
|
+
if (ctx.status >= 200 && ctx.status < 300 && ctx.body && ctx.body.jwt) {
|
|
10298
10458
|
try {
|
|
10299
|
-
|
|
10300
|
-
|
|
10301
|
-
|
|
10302
|
-
const
|
|
10303
|
-
|
|
10304
|
-
|
|
10305
|
-
|
|
10306
|
-
|
|
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
|
-
}
|
|
10459
|
+
if (!oldRefreshToken || !matchingSession) {
|
|
10460
|
+
throw new Error("refresh response issued without a tracked input token");
|
|
10461
|
+
}
|
|
10462
|
+
const rotated = await sessionService.rotateSessionTokens({
|
|
10463
|
+
sessionId: matchingSession.documentId,
|
|
10464
|
+
expectedRefreshToken: oldRefreshToken,
|
|
10465
|
+
accessToken: ctx.body.jwt,
|
|
10466
|
+
refreshToken: getOutgoingRefreshToken(ctx, cookieName)
|
|
10326
10467
|
});
|
|
10468
|
+
if (!rotated) throw new Error("refresh token was already consumed");
|
|
10327
10469
|
log.info(`[REFRESH] Tokens refreshed for session ${matchingSession.documentId}`);
|
|
10328
10470
|
} catch (err) {
|
|
10329
|
-
|
|
10471
|
+
failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh rotation failed", error: err });
|
|
10330
10472
|
}
|
|
10331
10473
|
}
|
|
10332
10474
|
});
|
|
10333
10475
|
log.info("[SUCCESS] Refresh token interceptor middleware mounted");
|
|
10334
10476
|
}
|
|
10477
|
+
function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
10478
|
+
strapi2.server.use(async (ctx, next) => {
|
|
10479
|
+
if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
|
|
10480
|
+
const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
|
|
10481
|
+
if (refreshToken) {
|
|
10482
|
+
try {
|
|
10483
|
+
await sessionService.terminateSessionByRefreshToken(refreshToken);
|
|
10484
|
+
} catch (err) {
|
|
10485
|
+
failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
|
|
10486
|
+
return;
|
|
10487
|
+
}
|
|
10488
|
+
}
|
|
10489
|
+
await next();
|
|
10490
|
+
});
|
|
10491
|
+
log.info("[SUCCESS] Logout interceptor middleware mounted");
|
|
10492
|
+
}
|
|
10335
10493
|
async function ensureContentApiPermissions(strapi2, log) {
|
|
10336
10494
|
const PERMISSIONS_VERSION = 2;
|
|
10337
10495
|
try {
|
|
@@ -10397,42 +10555,45 @@ var require_bootstrap = __commonJS({
|
|
|
10397
10555
|
log.warn("Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated");
|
|
10398
10556
|
}
|
|
10399
10557
|
}
|
|
10400
|
-
async function
|
|
10558
|
+
async function ensureSessionLookupIndexes(strapi2, log) {
|
|
10401
10559
|
try {
|
|
10402
10560
|
const knex = strapi2.db.connection;
|
|
10403
10561
|
const tableName = "magic_sessions";
|
|
10404
|
-
const
|
|
10405
|
-
|
|
10406
|
-
|
|
10562
|
+
const definitions = [
|
|
10563
|
+
{ column: "token_hash", name: "idx_magic_sessions_token_hash" },
|
|
10564
|
+
{ column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
|
|
10565
|
+
];
|
|
10566
|
+
if (!await knex.schema.hasTable(tableName)) return;
|
|
10567
|
+
for (const definition of definitions) {
|
|
10407
10568
|
const dialect = strapi2.db.dialect.client;
|
|
10569
|
+
let hasIndex = false;
|
|
10408
10570
|
if (dialect === "postgres") {
|
|
10409
10571
|
const result = await knex.raw(
|
|
10410
10572
|
"SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?",
|
|
10411
|
-
[tableName,
|
|
10573
|
+
[tableName, definition.name]
|
|
10412
10574
|
);
|
|
10413
|
-
|
|
10575
|
+
hasIndex = result.rows.length > 0;
|
|
10414
10576
|
} else if (dialect === "mysql" || dialect === "mysql2") {
|
|
10415
|
-
const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName,
|
|
10416
|
-
|
|
10577
|
+
const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName, definition.name]);
|
|
10578
|
+
hasIndex = result[0].length > 0;
|
|
10417
10579
|
} else if (dialect === "sqlite" || dialect === "better-sqlite3") {
|
|
10418
10580
|
const result = await knex.raw(
|
|
10419
10581
|
"SELECT name FROM sqlite_master WHERE type='index' AND name = ?",
|
|
10420
|
-
[
|
|
10582
|
+
[definition.name]
|
|
10421
10583
|
);
|
|
10422
|
-
|
|
10584
|
+
hasIndex = result.length > 0;
|
|
10423
10585
|
}
|
|
10424
|
-
|
|
10425
|
-
|
|
10426
|
-
|
|
10427
|
-
|
|
10428
|
-
|
|
10586
|
+
if (hasIndex) {
|
|
10587
|
+
log.debug(`[INDEX] ${definition.name} already exists`);
|
|
10588
|
+
continue;
|
|
10589
|
+
}
|
|
10590
|
+
await knex.schema.alterTable(tableName, (table) => {
|
|
10591
|
+
table.index([definition.column, "is_active"], definition.name);
|
|
10592
|
+
});
|
|
10593
|
+
log.info(`[INDEX] Created ${definition.name}`);
|
|
10429
10594
|
}
|
|
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
10595
|
} catch (err) {
|
|
10435
|
-
log.debug("[INDEX] Could not create
|
|
10596
|
+
log.debug("[INDEX] Could not create session lookup indexes (will retry on next startup):", err.message);
|
|
10436
10597
|
}
|
|
10437
10598
|
}
|
|
10438
10599
|
var sessionCheckErrors = { count: 0, lastReset: Date.now() };
|
|
@@ -10524,6 +10685,16 @@ var require_bootstrap = __commonJS({
|
|
|
10524
10685
|
fields: ["documentId", "isActive", "terminatedManually", "terminationReason", "lastActive", "loginTime"]
|
|
10525
10686
|
});
|
|
10526
10687
|
if (thisSession) {
|
|
10688
|
+
if (thisSession.isActive === false) {
|
|
10689
|
+
const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : null);
|
|
10690
|
+
if (reason) {
|
|
10691
|
+
strapi2.log.info(
|
|
10692
|
+
`[magic-sessionmanager] [JWT-REJECTED] Session inactive (reason: ${reason}) for user ${userDocId.substring(0, 8)}...`
|
|
10693
|
+
);
|
|
10694
|
+
setSessionRejectionReason(tokenHashValue, reason);
|
|
10695
|
+
return null;
|
|
10696
|
+
}
|
|
10697
|
+
}
|
|
10527
10698
|
if (isSessionExpired(thisSession, maxSessionAgeDays)) {
|
|
10528
10699
|
strapi2.log.info(
|
|
10529
10700
|
`[magic-sessionmanager] [JWT-EXPIRED] Session exceeded max age of ${maxSessionAgeDays} days (user: ${userDocId.substring(0, 8)}...)`
|
|
@@ -10540,20 +10711,6 @@ var require_bootstrap = __commonJS({
|
|
|
10540
10711
|
setSessionRejectionReason(tokenHashValue, "expired");
|
|
10541
10712
|
return null;
|
|
10542
10713
|
}
|
|
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
10714
|
const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
|
|
10558
10715
|
const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
|
|
10559
10716
|
const idleFor = Date.now() - lastActiveMs;
|
|
@@ -10564,6 +10721,7 @@ var require_bootstrap = __commonJS({
|
|
|
10564
10721
|
await strapi2.documents(SESSION_UID).update({
|
|
10565
10722
|
documentId: thisSession.documentId,
|
|
10566
10723
|
data: {
|
|
10724
|
+
isActive: false,
|
|
10567
10725
|
terminatedManually: false,
|
|
10568
10726
|
terminationReason: "idle",
|
|
10569
10727
|
logoutTime: /* @__PURE__ */ new Date()
|
|
@@ -10572,6 +10730,10 @@ var require_bootstrap = __commonJS({
|
|
|
10572
10730
|
setSessionRejectionReason(tokenHashValue, "idle");
|
|
10573
10731
|
return null;
|
|
10574
10732
|
}
|
|
10733
|
+
if (thisSession.isActive) {
|
|
10734
|
+
resetErrorCounter();
|
|
10735
|
+
return decoded;
|
|
10736
|
+
}
|
|
10575
10737
|
await strapi2.documents(SESSION_UID).update({
|
|
10576
10738
|
documentId: thisSession.documentId,
|
|
10577
10739
|
data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
|
|
@@ -10621,6 +10783,14 @@ var require_bootstrap = __commonJS({
|
|
|
10621
10783
|
strapi2.log.warn("[magic-sessionmanager] [AUTH] Session validation will only work via middleware (plugin endpoints)");
|
|
10622
10784
|
}
|
|
10623
10785
|
}
|
|
10786
|
+
module2.exports.__private = {
|
|
10787
|
+
registerSessionAwareAuthStrategy,
|
|
10788
|
+
mountPreLoginGeoGuard,
|
|
10789
|
+
mountLoginInterceptor,
|
|
10790
|
+
mountRefreshTokenInterceptor,
|
|
10791
|
+
mountLogoutInterceptor,
|
|
10792
|
+
mountLogoutRoute
|
|
10793
|
+
};
|
|
10624
10794
|
}
|
|
10625
10795
|
});
|
|
10626
10796
|
|
|
@@ -10661,6 +10831,12 @@ var require_config = __commonJS({
|
|
|
10661
10831
|
cleanupInterval: 30 * 60 * 1e3,
|
|
10662
10832
|
retentionDays: 90,
|
|
10663
10833
|
maxSessionAgeDays: 30,
|
|
10834
|
+
maxFailedLogins: 5,
|
|
10835
|
+
sessionCreationGraceMs: 5e3,
|
|
10836
|
+
cleanupUseDbDirect: false,
|
|
10837
|
+
rateLimitWriteMax: 10,
|
|
10838
|
+
rateLimitReadMax: 120,
|
|
10839
|
+
rateLimitWindowSeconds: 60,
|
|
10664
10840
|
strictSessionEnforcement: false,
|
|
10665
10841
|
enableGeolocation: true,
|
|
10666
10842
|
enableSecurityScoring: true,
|
|
@@ -10798,7 +10974,7 @@ var require_schema = __commonJS({
|
|
|
10798
10974
|
},
|
|
10799
10975
|
terminationReason: {
|
|
10800
10976
|
type: "enumeration",
|
|
10801
|
-
enum: ["manual", "idle", "expired", "blocked"],
|
|
10977
|
+
enum: ["logout", "manual", "idle", "expired", "blocked"],
|
|
10802
10978
|
required: false
|
|
10803
10979
|
},
|
|
10804
10980
|
geoLocation: {
|
|
@@ -11259,6 +11435,9 @@ var require_enhance_session = __commonJS({
|
|
|
11259
11435
|
"use strict";
|
|
11260
11436
|
var { parseUserAgent } = require_user_agent_parser();
|
|
11261
11437
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
11438
|
+
function shouldResolveGeoData(settings = {}) {
|
|
11439
|
+
return settings.enableGeolocation === true || settings.enableGeofencing === true || settings.blockSuspiciousSessions === true;
|
|
11440
|
+
}
|
|
11262
11441
|
async function enhanceSession(session, opts = {}) {
|
|
11263
11442
|
const {
|
|
11264
11443
|
inactivityTimeout = 15 * 60 * 1e3,
|
|
@@ -11310,7 +11489,7 @@ var require_enhance_session = __commonJS({
|
|
|
11310
11489
|
documentId: session.documentId,
|
|
11311
11490
|
data: {
|
|
11312
11491
|
geoLocation,
|
|
11313
|
-
securityScore: geoData.securityScore
|
|
11492
|
+
securityScore: geoData.securityScore ?? null
|
|
11314
11493
|
}
|
|
11315
11494
|
}).catch(() => {
|
|
11316
11495
|
});
|
|
@@ -11347,7 +11526,7 @@ var require_enhance_session = __commonJS({
|
|
|
11347
11526
|
sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now }))
|
|
11348
11527
|
);
|
|
11349
11528
|
}
|
|
11350
|
-
module2.exports = { enhanceSession, enhanceSessions };
|
|
11529
|
+
module2.exports = { enhanceSession, enhanceSessions, shouldResolveGeoData };
|
|
11351
11530
|
}
|
|
11352
11531
|
});
|
|
11353
11532
|
|
|
@@ -11356,7 +11535,11 @@ var require_session = __commonJS({
|
|
|
11356
11535
|
"server/src/controllers/session.js"(exports2, module2) {
|
|
11357
11536
|
"use strict";
|
|
11358
11537
|
var { hashToken } = require_encryption();
|
|
11359
|
-
var {
|
|
11538
|
+
var {
|
|
11539
|
+
enhanceSessions,
|
|
11540
|
+
enhanceSession,
|
|
11541
|
+
shouldResolveGeoData
|
|
11542
|
+
} = require_enhance_session();
|
|
11360
11543
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
11361
11544
|
var {
|
|
11362
11545
|
getPluginSettings,
|
|
@@ -11434,7 +11617,7 @@ var require_session = __commonJS({
|
|
|
11434
11617
|
const settings = await getPluginSettings(strapi);
|
|
11435
11618
|
const enhanceOpts = {
|
|
11436
11619
|
inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
|
|
11437
|
-
geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
|
|
11620
|
+
geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
|
|
11438
11621
|
strapi
|
|
11439
11622
|
};
|
|
11440
11623
|
const sessionsWithCurrent = await enhanceSessions(paged, enhanceOpts, 20);
|
|
@@ -11518,7 +11701,7 @@ var require_session = __commonJS({
|
|
|
11518
11701
|
if (matchingSession) {
|
|
11519
11702
|
await sessionService.terminateSession({
|
|
11520
11703
|
sessionId: matchingSession.documentId,
|
|
11521
|
-
reason: "
|
|
11704
|
+
reason: "logout"
|
|
11522
11705
|
});
|
|
11523
11706
|
terminated = true;
|
|
11524
11707
|
strapi.log.info(`[magic-sessionmanager] User ${userDocId} logged out (session ${matchingSession.documentId})`);
|
|
@@ -11536,7 +11719,7 @@ var require_session = __commonJS({
|
|
|
11536
11719
|
* Terminates EVERY session of the authenticated user — including the
|
|
11537
11720
|
* current one. After this call the caller will also be logged out on
|
|
11538
11721
|
* the next request (their own JWT is rejected by the JWT-verify wrapper
|
|
11539
|
-
* with reason=
|
|
11722
|
+
* with reason=logout).
|
|
11540
11723
|
*
|
|
11541
11724
|
* For the "log me out everywhere ELSE but keep me here" flow, use
|
|
11542
11725
|
* `/logout-others` below.
|
|
@@ -11552,7 +11735,7 @@ var require_session = __commonJS({
|
|
|
11552
11735
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
11553
11736
|
const { terminatedCount } = await sessionService.terminateSession({
|
|
11554
11737
|
userId: userDocId,
|
|
11555
|
-
reason: "
|
|
11738
|
+
reason: "logout"
|
|
11556
11739
|
});
|
|
11557
11740
|
strapi.log.info(
|
|
11558
11741
|
`[magic-sessionmanager] User ${userDocId} logged out from all devices (${terminatedCount})`
|
|
@@ -11596,7 +11779,7 @@ var require_session = __commonJS({
|
|
|
11596
11779
|
if (!currentSession) {
|
|
11597
11780
|
const { terminatedCount: terminatedCount2 } = await sessionService.terminateSession({
|
|
11598
11781
|
userId: userDocId,
|
|
11599
|
-
reason: "
|
|
11782
|
+
reason: "logout"
|
|
11600
11783
|
});
|
|
11601
11784
|
strapi.log.warn(
|
|
11602
11785
|
`[magic-sessionmanager] logoutOthers fell back to logoutAll for user ${userDocId} (no current session match)`
|
|
@@ -11611,7 +11794,7 @@ var require_session = __commonJS({
|
|
|
11611
11794
|
const { terminatedCount } = await sessionService.terminateSession({
|
|
11612
11795
|
userId: userDocId,
|
|
11613
11796
|
exceptSessionId: currentSession.documentId,
|
|
11614
|
-
reason: "
|
|
11797
|
+
reason: "logout"
|
|
11615
11798
|
});
|
|
11616
11799
|
strapi.log.info(
|
|
11617
11800
|
`[magic-sessionmanager] User ${userDocId} logged out ${terminatedCount} other device(s)`
|
|
@@ -11672,7 +11855,7 @@ var require_session = __commonJS({
|
|
|
11672
11855
|
const settings = await getPluginSettings(strapi);
|
|
11673
11856
|
const enhanced = await enhanceSession(currentSession, {
|
|
11674
11857
|
inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
|
|
11675
|
-
geolocationService: strapi.plugin("magic-sessionmanager").service("geolocation"),
|
|
11858
|
+
geolocationService: shouldResolveGeoData(settings) ? strapi.plugin("magic-sessionmanager").service("geolocation") : null,
|
|
11676
11859
|
geoCounter: { remaining: 1 },
|
|
11677
11860
|
strapi
|
|
11678
11861
|
});
|
|
@@ -12228,6 +12411,55 @@ var require_settings = __commonJS({
|
|
|
12228
12411
|
}
|
|
12229
12412
|
return result;
|
|
12230
12413
|
}
|
|
12414
|
+
var DEFAULT_EMAIL_TEMPLATES = {
|
|
12415
|
+
suspiciousLogin: { subject: "", html: "", text: "" },
|
|
12416
|
+
newLocation: { subject: "", html: "", text: "" },
|
|
12417
|
+
vpnProxy: { subject: "", html: "", text: "" }
|
|
12418
|
+
};
|
|
12419
|
+
var DEFAULT_SETTINGS = {
|
|
12420
|
+
inactivityTimeout: 15,
|
|
12421
|
+
cleanupInterval: 30,
|
|
12422
|
+
lastSeenRateLimit: 30,
|
|
12423
|
+
retentionDays: 90,
|
|
12424
|
+
maxSessionAgeDays: 30,
|
|
12425
|
+
sessionCreationGraceMs: 5e3,
|
|
12426
|
+
cleanupUseDbDirect: false,
|
|
12427
|
+
rateLimitWriteMax: 10,
|
|
12428
|
+
rateLimitReadMax: 120,
|
|
12429
|
+
rateLimitWindowSeconds: 60,
|
|
12430
|
+
enableGeolocation: true,
|
|
12431
|
+
enableSecurityScoring: true,
|
|
12432
|
+
blockSuspiciousSessions: false,
|
|
12433
|
+
maxFailedLogins: 5,
|
|
12434
|
+
enableGeofencing: false,
|
|
12435
|
+
allowedCountries: [],
|
|
12436
|
+
blockedCountries: [],
|
|
12437
|
+
geoIpProvider: "auto",
|
|
12438
|
+
geoIpDatabasePath: "",
|
|
12439
|
+
geoLookupFailureMode: "auto",
|
|
12440
|
+
enableEmailAlerts: false,
|
|
12441
|
+
alertOnSuspiciousLogin: true,
|
|
12442
|
+
alertOnNewLocation: true,
|
|
12443
|
+
alertOnVpnProxy: true,
|
|
12444
|
+
enableWebhooks: false,
|
|
12445
|
+
discordWebhookUrl: "",
|
|
12446
|
+
slackWebhookUrl: "",
|
|
12447
|
+
strictSessionEnforcement: false,
|
|
12448
|
+
trustedProxies: false,
|
|
12449
|
+
emailTemplates: DEFAULT_EMAIL_TEMPLATES
|
|
12450
|
+
};
|
|
12451
|
+
function mergeSettingsWithDefaults(stored) {
|
|
12452
|
+
const safeStored = stored && typeof stored === "object" ? stored : {};
|
|
12453
|
+
const storedTemplates = safeStored.emailTemplates && typeof safeStored.emailTemplates === "object" ? safeStored.emailTemplates : {};
|
|
12454
|
+
return {
|
|
12455
|
+
...DEFAULT_SETTINGS,
|
|
12456
|
+
...safeStored,
|
|
12457
|
+
emailTemplates: {
|
|
12458
|
+
...DEFAULT_EMAIL_TEMPLATES,
|
|
12459
|
+
...storedTemplates
|
|
12460
|
+
}
|
|
12461
|
+
};
|
|
12462
|
+
}
|
|
12231
12463
|
module2.exports = {
|
|
12232
12464
|
/**
|
|
12233
12465
|
* Returns the current plugin settings (user-facing units: minutes/seconds/days).
|
|
@@ -12239,51 +12471,8 @@ var require_settings = __commonJS({
|
|
|
12239
12471
|
type: "plugin",
|
|
12240
12472
|
name: "magic-sessionmanager"
|
|
12241
12473
|
});
|
|
12242
|
-
|
|
12243
|
-
|
|
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
|
-
}
|
|
12474
|
+
const storedSettings = await pluginStore.get({ key: "settings" });
|
|
12475
|
+
const settings = mergeSettingsWithDefaults(storedSettings);
|
|
12287
12476
|
ctx.send({
|
|
12288
12477
|
settings,
|
|
12289
12478
|
success: true
|
|
@@ -12321,6 +12510,9 @@ var require_settings = __commonJS({
|
|
|
12321
12510
|
maxSessionAgeDays: Math.max(1, Math.min(parseInt(body.maxSessionAgeDays) || 30, 365)),
|
|
12322
12511
|
sessionCreationGraceMs: grace,
|
|
12323
12512
|
cleanupUseDbDirect: !!body.cleanupUseDbDirect,
|
|
12513
|
+
rateLimitWriteMax: Math.max(1, Math.min(parseInt(body.rateLimitWriteMax) || 10, 1e3)),
|
|
12514
|
+
rateLimitReadMax: Math.max(1, Math.min(parseInt(body.rateLimitReadMax) || 120, 1e4)),
|
|
12515
|
+
rateLimitWindowSeconds: Math.max(10, Math.min(parseInt(body.rateLimitWindowSeconds) || 60, 3600)),
|
|
12324
12516
|
// Geo / security
|
|
12325
12517
|
enableGeolocation: !!body.enableGeolocation,
|
|
12326
12518
|
enableSecurityScoring: !!body.enableSecurityScoring,
|
|
@@ -12361,7 +12553,9 @@ var require_settings = __commonJS({
|
|
|
12361
12553
|
strapi.log.error("[magic-sessionmanager/settings] Error updating settings:", error);
|
|
12362
12554
|
ctx.badRequest("Error saving settings");
|
|
12363
12555
|
}
|
|
12364
|
-
}
|
|
12556
|
+
},
|
|
12557
|
+
DEFAULT_SETTINGS,
|
|
12558
|
+
mergeSettingsWithDefaults
|
|
12365
12559
|
};
|
|
12366
12560
|
}
|
|
12367
12561
|
});
|
|
@@ -12755,7 +12949,7 @@ var require_session2 = __commonJS({
|
|
|
12755
12949
|
var { createLogger } = require_logger();
|
|
12756
12950
|
var { parseUserAgent } = require_user_agent_parser();
|
|
12757
12951
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
12758
|
-
var { enhanceSessions } = require_enhance_session();
|
|
12952
|
+
var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
|
|
12759
12953
|
var { getPluginSettings } = require_settings_loader();
|
|
12760
12954
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
12761
12955
|
var MAX_SESSIONS_QUERY = 1e3;
|
|
@@ -12765,7 +12959,7 @@ var require_session2 = __commonJS({
|
|
|
12765
12959
|
const settings = await getPluginSettings(strapi2);
|
|
12766
12960
|
return {
|
|
12767
12961
|
inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
|
|
12768
|
-
geolocationService: strapi2.plugin("magic-sessionmanager").service("geolocation"),
|
|
12962
|
+
geolocationService: shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null,
|
|
12769
12963
|
strapi: strapi2
|
|
12770
12964
|
};
|
|
12771
12965
|
}
|
|
@@ -12820,7 +13014,7 @@ var require_session2 = __commonJS({
|
|
|
12820
13014
|
region: geoData.region,
|
|
12821
13015
|
timezone: geoData.timezone
|
|
12822
13016
|
} : null,
|
|
12823
|
-
securityScore: geoData?.securityScore
|
|
13017
|
+
securityScore: geoData?.securityScore ?? null
|
|
12824
13018
|
}
|
|
12825
13019
|
});
|
|
12826
13020
|
log.info(`[SUCCESS] Session ${session.documentId} (${sessionId}) created for user ${userId}`);
|
|
@@ -12830,19 +13024,72 @@ var require_session2 = __commonJS({
|
|
|
12830
13024
|
throw err;
|
|
12831
13025
|
}
|
|
12832
13026
|
},
|
|
13027
|
+
/**
|
|
13028
|
+
* Atomically replaces the stored tokens only while the caller still owns
|
|
13029
|
+
* the expected active token. This prevents two concurrent refresh
|
|
13030
|
+
* requests from both committing a rotation.
|
|
13031
|
+
*
|
|
13032
|
+
* @returns {Promise<boolean>} Whether exactly one session was rotated
|
|
13033
|
+
*/
|
|
13034
|
+
async rotateSessionTokens({
|
|
13035
|
+
sessionId,
|
|
13036
|
+
expectedAccessToken,
|
|
13037
|
+
expectedRefreshToken,
|
|
13038
|
+
accessToken,
|
|
13039
|
+
refreshToken
|
|
13040
|
+
}) {
|
|
13041
|
+
if (!sessionId || !accessToken || !expectedAccessToken && !expectedRefreshToken) {
|
|
13042
|
+
return false;
|
|
13043
|
+
}
|
|
13044
|
+
const where = { documentId: sessionId, isActive: true };
|
|
13045
|
+
if (expectedAccessToken) where.tokenHash = hashToken(expectedAccessToken);
|
|
13046
|
+
if (expectedRefreshToken) where.refreshTokenHash = hashToken(expectedRefreshToken);
|
|
13047
|
+
const data = {
|
|
13048
|
+
token: encryptToken(accessToken),
|
|
13049
|
+
tokenHash: hashToken(accessToken),
|
|
13050
|
+
lastActive: /* @__PURE__ */ new Date()
|
|
13051
|
+
};
|
|
13052
|
+
if (refreshToken) {
|
|
13053
|
+
data.refreshToken = encryptToken(refreshToken);
|
|
13054
|
+
data.refreshTokenHash = hashToken(refreshToken);
|
|
13055
|
+
}
|
|
13056
|
+
const result = await strapi2.db.query(SESSION_UID).updateMany({ where, data });
|
|
13057
|
+
return result?.count === 1;
|
|
13058
|
+
},
|
|
13059
|
+
/**
|
|
13060
|
+
* Terminates the active session identified by a raw refresh token.
|
|
13061
|
+
* Used by Strapi's built-in cookie/body logout endpoint.
|
|
13062
|
+
*/
|
|
13063
|
+
async terminateSessionByRefreshToken(refreshToken) {
|
|
13064
|
+
if (!refreshToken) return false;
|
|
13065
|
+
const result = await strapi2.db.query(SESSION_UID).updateMany({
|
|
13066
|
+
where: {
|
|
13067
|
+
refreshTokenHash: hashToken(refreshToken),
|
|
13068
|
+
isActive: true
|
|
13069
|
+
},
|
|
13070
|
+
data: {
|
|
13071
|
+
isActive: false,
|
|
13072
|
+
terminatedManually: false,
|
|
13073
|
+
terminationReason: "logout",
|
|
13074
|
+
logoutTime: /* @__PURE__ */ new Date()
|
|
13075
|
+
}
|
|
13076
|
+
});
|
|
13077
|
+
return result?.count === 1;
|
|
13078
|
+
},
|
|
12833
13079
|
/**
|
|
12834
13080
|
* Terminates a single session, all sessions of a user, or all sessions
|
|
12835
13081
|
* of a user EXCEPT one with a typed reason so the JWT-verify wrapper
|
|
12836
13082
|
* can communicate the cause to the client.
|
|
12837
13083
|
*
|
|
12838
13084
|
* Supported reasons:
|
|
12839
|
-
* - '
|
|
13085
|
+
* - 'logout': user clicked logout
|
|
13086
|
+
* - 'manual': admin terminated a session
|
|
12840
13087
|
* - 'idle': inactivity timeout cleanup
|
|
12841
13088
|
* - 'expired': maxSessionAgeDays exceeded
|
|
12842
13089
|
* - 'blocked': the owning user was marked blocked
|
|
12843
13090
|
*
|
|
12844
13091
|
* For backwards compatibility `terminatedManually` is still set true
|
|
12845
|
-
* only when reason === 'manual'; idle/expired/blocked paths set it
|
|
13092
|
+
* only when reason === 'manual'; logout/idle/expired/blocked paths set it
|
|
12846
13093
|
* false so reporting dashboards that queried that boolean continue
|
|
12847
13094
|
* to work, while new code relies on `terminationReason`.
|
|
12848
13095
|
*
|
|
@@ -12855,13 +13102,13 @@ var require_session2 = __commonJS({
|
|
|
12855
13102
|
* `userId`. Used by
|
|
12856
13103
|
* /logout-other-devices so
|
|
12857
13104
|
* the caller stays logged in.
|
|
12858
|
-
* @param {'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
|
|
13105
|
+
* @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
|
|
12859
13106
|
* @returns {Promise<{terminatedCount: number}>}
|
|
12860
13107
|
*/
|
|
12861
13108
|
async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
|
|
12862
13109
|
try {
|
|
12863
13110
|
const now = /* @__PURE__ */ new Date();
|
|
12864
|
-
const validReasons = ["manual", "idle", "expired", "blocked"];
|
|
13111
|
+
const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
|
|
12865
13112
|
const finalReason = validReasons.includes(reason) ? reason : "manual";
|
|
12866
13113
|
const updateData = {
|
|
12867
13114
|
isActive: false,
|
|
@@ -12892,21 +13139,31 @@ var require_session2 = __commonJS({
|
|
|
12892
13139
|
if (exceptSessionId) {
|
|
12893
13140
|
filters.documentId = { $ne: exceptSessionId };
|
|
12894
13141
|
}
|
|
12895
|
-
const activeSessions = await strapi2.documents(SESSION_UID).findMany({
|
|
12896
|
-
filters,
|
|
12897
|
-
fields: ["documentId"],
|
|
12898
|
-
limit: MAX_SESSIONS_QUERY
|
|
12899
|
-
});
|
|
12900
13142
|
let terminatedCount = 0;
|
|
12901
|
-
|
|
12902
|
-
|
|
12903
|
-
|
|
12904
|
-
|
|
12905
|
-
|
|
12906
|
-
|
|
12907
|
-
|
|
12908
|
-
|
|
12909
|
-
|
|
13143
|
+
const batchSize = 500;
|
|
13144
|
+
while (true) {
|
|
13145
|
+
const activeSessions = await strapi2.documents(SESSION_UID).findMany({
|
|
13146
|
+
filters,
|
|
13147
|
+
fields: ["documentId"],
|
|
13148
|
+
limit: batchSize
|
|
13149
|
+
});
|
|
13150
|
+
if (!activeSessions || activeSessions.length === 0) break;
|
|
13151
|
+
let batchTerminated = 0;
|
|
13152
|
+
for (const session of activeSessions) {
|
|
13153
|
+
try {
|
|
13154
|
+
await strapi2.documents(SESSION_UID).update({
|
|
13155
|
+
documentId: session.documentId,
|
|
13156
|
+
data: updateData
|
|
13157
|
+
});
|
|
13158
|
+
terminatedCount++;
|
|
13159
|
+
batchTerminated++;
|
|
13160
|
+
} catch (err) {
|
|
13161
|
+
log.debug(`Failed to terminate session ${session.documentId}:`, err.message);
|
|
13162
|
+
}
|
|
13163
|
+
}
|
|
13164
|
+
if (batchTerminated === 0) {
|
|
13165
|
+
log.warn(`Could not terminate remaining active sessions for user ${userDocumentId}`);
|
|
13166
|
+
break;
|
|
12910
13167
|
}
|
|
12911
13168
|
}
|
|
12912
13169
|
const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
|
|
@@ -13292,7 +13549,7 @@ var require_session2 = __commonJS({
|
|
|
13292
13549
|
var require_package = __commonJS({
|
|
13293
13550
|
"package.json"(exports2, module2) {
|
|
13294
13551
|
module2.exports = {
|
|
13295
|
-
version: "4.7.
|
|
13552
|
+
version: "4.7.1",
|
|
13296
13553
|
keywords: [
|
|
13297
13554
|
"strapi",
|
|
13298
13555
|
"plugin",
|
|
@@ -13350,7 +13607,7 @@ var require_package = __commonJS({
|
|
|
13350
13607
|
},
|
|
13351
13608
|
dependencies: {
|
|
13352
13609
|
"@maxmind/geoip2-node": "^6.3.4",
|
|
13353
|
-
"sanitize-html": "^2.17.
|
|
13610
|
+
"sanitize-html": "^2.17.6"
|
|
13354
13611
|
},
|
|
13355
13612
|
devDependencies: {
|
|
13356
13613
|
"@semantic-release/changelog": "^6.0.3",
|