strapi-plugin-magic-sessionmanager 4.6.4 → 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 +19 -0
- package/README.md +15 -8
- package/dist/admin/{Analytics-B5IR0Awr.mjs → Analytics-CsrpxJwQ.mjs} +90 -69
- package/dist/admin/{Analytics-BJlc-yE3.js → Analytics-D03ZNNMR.js} +90 -69
- package/dist/admin/{App-DisCm99X.js → App-B2VCS3cz.js} +22 -27
- package/dist/admin/{App-BEniJePD.mjs → App-qxKnK7G2.mjs} +9 -14
- package/dist/admin/{License-BjP7GvCt.mjs → License-ClW7sZLR.mjs} +1 -1
- package/dist/admin/{License-DqDBPjZH.js → License-fixnQ7wF.js} +1 -1
- package/dist/admin/{OnlineUsersWidget-Cm9O0Fjb.mjs → OnlineUsersWidget-mR_OMiwi.mjs} +1 -2
- package/dist/admin/{OnlineUsersWidget-DXdeGmfV.js → OnlineUsersWidget-qb9utPBy.js} +1 -2
- package/dist/admin/{Settings-CnO501iu.mjs → Settings-U3V4eGMo.mjs} +10 -5
- package/dist/admin/{Settings-DoLec2MD.js → Settings-gv2BF54w.js} +10 -5
- package/dist/admin/{de-DjP2WJ_V.js → de-BnqGCokx.js} +6 -5
- package/dist/admin/{de-6rIvkYOp.mjs → de-JBE-iylO.mjs} +6 -5
- package/dist/admin/{en-0pesBbOT.js → en-BRmVwd8-.js} +6 -5
- package/dist/admin/{en-8hiv31Dv.mjs → en-kQWtdEai.mjs} +6 -5
- package/dist/admin/{es-DdBRpF7F.js → es-CH691xcL.js} +6 -5
- package/dist/admin/{es-LRQ148f5.mjs → es-DOQvBxih.mjs} +6 -5
- package/dist/admin/{fr-DJ6DbeDy.js → fr-CLExO0w_.js} +6 -5
- package/dist/admin/{fr-CKhx_qil.mjs → fr-CmfCpepX.mjs} +6 -5
- package/dist/admin/{index-CpMDG2XI.mjs → index-B_lFjUAg.mjs} +15 -15
- package/dist/admin/{index-DJHhzin_.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-D0SMoAmo.js → pt-BJ_F0yNi.js} +6 -5
- package/dist/admin/{pt-DXizUvcj.mjs → pt-BSzZdyAH.mjs} +6 -5
- package/dist/admin/sessionStatus-D_fWEzgj.js +11 -0
- package/dist/admin/sessionStatus-kwggjEMw.mjs +12 -0
- package/dist/server/index.js +708 -349
- package/dist/server/index.mjs +708 -349
- package/package.json +8 -8
- package/scripts/geoip-updater.cjs +39 -4
- package/scripts/update-geoip-db.mjs +1 -0
package/dist/server/index.mjs
CHANGED
|
@@ -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
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
|
621
|
+
if (geoData.isVpn) {
|
|
646
622
|
return { blocked: true, reason: "vpn_detected", status };
|
|
647
623
|
}
|
|
648
|
-
if (geoData.isProxy
|
|
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
|
|
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
|
|
902
|
+
return;
|
|
784
903
|
}
|
|
785
904
|
}
|
|
786
905
|
if (!userDocId) {
|
|
787
|
-
return
|
|
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
|
-
|
|
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
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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 (!
|
|
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
|
-
|
|
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({
|
|
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 (!
|
|
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 (
|
|
10122
|
-
if (ctx.status
|
|
10123
|
-
if (!ctx.body || !ctx.body.jwt
|
|
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
|
-
|
|
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
|
|
10296
|
+
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
|
|
10146
10297
|
geoData
|
|
10147
10298
|
});
|
|
10148
10299
|
if (!newSession?.documentId) {
|
|
10149
|
-
|
|
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
|
-
|
|
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
|
-
|
|
10273
|
-
|
|
10274
|
-
|
|
10275
|
-
|
|
10276
|
-
|
|
10277
|
-
|
|
10278
|
-
|
|
10279
|
-
|
|
10280
|
-
|
|
10281
|
-
|
|
10282
|
-
|
|
10283
|
-
|
|
10284
|
-
|
|
10285
|
-
|
|
10286
|
-
|
|
10287
|
-
|
|
10288
|
-
|
|
10289
|
-
|
|
10290
|
-
|
|
10291
|
-
|
|
10292
|
-
|
|
10293
|
-
|
|
10294
|
-
|
|
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 (
|
|
10463
|
+
if (ctx.status >= 200 && ctx.status < 300 && ctx.body && ctx.body.jwt) {
|
|
10304
10464
|
try {
|
|
10305
|
-
|
|
10306
|
-
|
|
10307
|
-
|
|
10308
|
-
const
|
|
10309
|
-
|
|
10310
|
-
|
|
10311
|
-
|
|
10312
|
-
|
|
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
|
-
|
|
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
|
|
10564
|
+
async function ensureSessionLookupIndexes(strapi2, log) {
|
|
10407
10565
|
try {
|
|
10408
10566
|
const knex = strapi2.db.connection;
|
|
10409
10567
|
const tableName = "magic_sessions";
|
|
10410
|
-
const
|
|
10411
|
-
|
|
10412
|
-
|
|
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,
|
|
10579
|
+
[tableName, definition.name]
|
|
10418
10580
|
);
|
|
10419
|
-
|
|
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,
|
|
10422
|
-
|
|
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
|
-
[
|
|
10588
|
+
[definition.name]
|
|
10427
10589
|
);
|
|
10428
|
-
|
|
10590
|
+
hasIndex = result.length > 0;
|
|
10429
10591
|
}
|
|
10430
|
-
|
|
10431
|
-
|
|
10432
|
-
|
|
10433
|
-
|
|
10434
|
-
|
|
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
|
|
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
|
|
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 {
|
|
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: "
|
|
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=
|
|
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: "
|
|
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: "
|
|
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: "
|
|
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
|
-
|
|
12249
|
-
|
|
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
|
});
|
|
@@ -12382,9 +12576,29 @@ var require_geoip_updater = __commonJS({
|
|
|
12382
12576
|
var zlib = __require("node:zlib");
|
|
12383
12577
|
var { promisify } = __require("node:util");
|
|
12384
12578
|
var gunzip = promisify(zlib.gunzip);
|
|
12385
|
-
var DEFAULT_EDITION_ID = "GeoLite2-
|
|
12386
|
-
var DEFAULT_MMDB_NAME =
|
|
12579
|
+
var DEFAULT_EDITION_ID = "GeoLite2-City";
|
|
12580
|
+
var DEFAULT_MMDB_NAME = `${DEFAULT_EDITION_ID}.mmdb`;
|
|
12387
12581
|
var DEFAULT_OUTPUT_PATH = path.resolve(process2.cwd(), "data", DEFAULT_MMDB_NAME);
|
|
12582
|
+
var SUPPORTED_EDITION_IDS = /* @__PURE__ */ new Set([
|
|
12583
|
+
"GeoLite2-City",
|
|
12584
|
+
"GeoLite2-Country",
|
|
12585
|
+
"GeoIP2-City",
|
|
12586
|
+
"GeoIP2-Country"
|
|
12587
|
+
]);
|
|
12588
|
+
function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
|
|
12589
|
+
return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
|
|
12590
|
+
}
|
|
12591
|
+
function inferEditionIdFromPath(filePath) {
|
|
12592
|
+
if (typeof filePath !== "string" || filePath.trim() === "") return "";
|
|
12593
|
+
const basename = path.basename(filePath.trim());
|
|
12594
|
+
if (/GeoIP2-City\.mmdb$/i.test(basename)) return "GeoIP2-City";
|
|
12595
|
+
if (/GeoIP2-Country\.mmdb$/i.test(basename)) return "GeoIP2-Country";
|
|
12596
|
+
if (/GeoLite2-City\.mmdb$/i.test(basename)) return "GeoLite2-City";
|
|
12597
|
+
if (/GeoLite2-Country\.mmdb$/i.test(basename)) return "GeoLite2-Country";
|
|
12598
|
+
if (/city/i.test(basename)) return "GeoLite2-City";
|
|
12599
|
+
if (/country/i.test(basename)) return "GeoLite2-Country";
|
|
12600
|
+
return "";
|
|
12601
|
+
}
|
|
12388
12602
|
function buildDownloadUrl(editionId = DEFAULT_EDITION_ID) {
|
|
12389
12603
|
return `https://download.maxmind.com/geoip/databases/${encodeURIComponent(editionId)}/download?suffix=tar.gz`;
|
|
12390
12604
|
}
|
|
@@ -12393,8 +12607,11 @@ var require_geoip_updater = __commonJS({
|
|
|
12393
12607
|
}
|
|
12394
12608
|
function resolveConfig(env = process2.env, argv = process2.argv.slice(2), overrides = {}) {
|
|
12395
12609
|
const force = argv.includes("--force") || overrides.force === true;
|
|
12396
|
-
const
|
|
12397
|
-
const
|
|
12610
|
+
const configuredOutputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || "";
|
|
12611
|
+
const editionId = normalizeEditionId(
|
|
12612
|
+
overrides.editionId || env.MAXMIND_EDITION_ID || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
|
|
12613
|
+
);
|
|
12614
|
+
const outputPath = configuredOutputPath || path.resolve(process2.cwd(), "data", `${editionId}.mmdb`);
|
|
12398
12615
|
return {
|
|
12399
12616
|
accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || "",
|
|
12400
12617
|
licenseKey: overrides.licenseKey || env.MAXMIND_LICENSE_KEY || "",
|
|
@@ -12552,6 +12769,7 @@ var require_geoip_updater = __commonJS({
|
|
|
12552
12769
|
buildDownloadUrl,
|
|
12553
12770
|
extractMmdbFromTarGz,
|
|
12554
12771
|
fileExists,
|
|
12772
|
+
inferEditionIdFromPath,
|
|
12555
12773
|
needsDownload,
|
|
12556
12774
|
readMetadata,
|
|
12557
12775
|
resolveConfig,
|
|
@@ -12564,6 +12782,7 @@ var require_geoip_updater = __commonJS({
|
|
|
12564
12782
|
var require_geoip = __commonJS({
|
|
12565
12783
|
"server/src/controllers/geoip.js"(exports, module) {
|
|
12566
12784
|
"use strict";
|
|
12785
|
+
var fs = __require("node:fs");
|
|
12567
12786
|
var path = __require("node:path");
|
|
12568
12787
|
var {
|
|
12569
12788
|
fileExists,
|
|
@@ -12577,6 +12796,8 @@ var require_geoip = __commonJS({
|
|
|
12577
12796
|
normalizeGeoIpDatabasePath
|
|
12578
12797
|
} = require_settings_loader();
|
|
12579
12798
|
var CREDENTIALS_KEY = "geoipCredentials";
|
|
12799
|
+
var DEFAULT_CITY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
|
|
12800
|
+
var DEFAULT_COUNTRY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
|
|
12580
12801
|
function getGeoIpStore(strapi2) {
|
|
12581
12802
|
return strapi2.store({
|
|
12582
12803
|
type: "plugin",
|
|
@@ -12612,10 +12833,11 @@ var require_geoip = __commonJS({
|
|
|
12612
12833
|
}
|
|
12613
12834
|
function buildUpdaterConfig(settings, storedCredentials, force = false) {
|
|
12614
12835
|
const outputPath = normalizeGeoIpDatabasePath(settings.geoIpDatabasePath);
|
|
12836
|
+
const existingDefaultPath = !outputPath && fs.existsSync(DEFAULT_CITY_DATABASE_PATH) ? DEFAULT_CITY_DATABASE_PATH : !outputPath && fs.existsSync(DEFAULT_COUNTRY_DATABASE_PATH) ? DEFAULT_COUNTRY_DATABASE_PATH : "";
|
|
12615
12837
|
return resolveConfig(process.env, force ? ["--force"] : [], {
|
|
12616
12838
|
accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
|
|
12617
12839
|
licenseKey: process.env.MAXMIND_LICENSE_KEY || storedCredentials.licenseKey || "",
|
|
12618
|
-
outputPath: outputPath || void 0,
|
|
12840
|
+
outputPath: outputPath || existingDefaultPath || void 0,
|
|
12619
12841
|
force
|
|
12620
12842
|
});
|
|
12621
12843
|
}
|
|
@@ -12639,6 +12861,7 @@ var require_geoip = __commonJS({
|
|
|
12639
12861
|
success: true,
|
|
12640
12862
|
status: {
|
|
12641
12863
|
provider: settings.geoIpProvider || "auto",
|
|
12864
|
+
editionId: config.editionId,
|
|
12642
12865
|
databasePath: config.outputPath,
|
|
12643
12866
|
databaseDirectory: path.dirname(config.outputPath),
|
|
12644
12867
|
exists,
|
|
@@ -12732,7 +12955,7 @@ var require_session2 = __commonJS({
|
|
|
12732
12955
|
var { createLogger } = require_logger();
|
|
12733
12956
|
var { parseUserAgent } = require_user_agent_parser();
|
|
12734
12957
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
12735
|
-
var { enhanceSessions } = require_enhance_session();
|
|
12958
|
+
var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
|
|
12736
12959
|
var { getPluginSettings } = require_settings_loader();
|
|
12737
12960
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
12738
12961
|
var MAX_SESSIONS_QUERY = 1e3;
|
|
@@ -12742,7 +12965,7 @@ var require_session2 = __commonJS({
|
|
|
12742
12965
|
const settings = await getPluginSettings(strapi2);
|
|
12743
12966
|
return {
|
|
12744
12967
|
inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
|
|
12745
|
-
geolocationService: strapi2.plugin("magic-sessionmanager").service("geolocation"),
|
|
12968
|
+
geolocationService: shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null,
|
|
12746
12969
|
strapi: strapi2
|
|
12747
12970
|
};
|
|
12748
12971
|
}
|
|
@@ -12797,7 +13020,7 @@ var require_session2 = __commonJS({
|
|
|
12797
13020
|
region: geoData.region,
|
|
12798
13021
|
timezone: geoData.timezone
|
|
12799
13022
|
} : null,
|
|
12800
|
-
securityScore: geoData?.securityScore
|
|
13023
|
+
securityScore: geoData?.securityScore ?? null
|
|
12801
13024
|
}
|
|
12802
13025
|
});
|
|
12803
13026
|
log.info(`[SUCCESS] Session ${session.documentId} (${sessionId}) created for user ${userId}`);
|
|
@@ -12807,19 +13030,72 @@ var require_session2 = __commonJS({
|
|
|
12807
13030
|
throw err;
|
|
12808
13031
|
}
|
|
12809
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
|
+
},
|
|
12810
13085
|
/**
|
|
12811
13086
|
* Terminates a single session, all sessions of a user, or all sessions
|
|
12812
13087
|
* of a user EXCEPT one with a typed reason so the JWT-verify wrapper
|
|
12813
13088
|
* can communicate the cause to the client.
|
|
12814
13089
|
*
|
|
12815
13090
|
* Supported reasons:
|
|
12816
|
-
* - '
|
|
13091
|
+
* - 'logout': user clicked logout
|
|
13092
|
+
* - 'manual': admin terminated a session
|
|
12817
13093
|
* - 'idle': inactivity timeout cleanup
|
|
12818
13094
|
* - 'expired': maxSessionAgeDays exceeded
|
|
12819
13095
|
* - 'blocked': the owning user was marked blocked
|
|
12820
13096
|
*
|
|
12821
13097
|
* For backwards compatibility `terminatedManually` is still set true
|
|
12822
|
-
* only when reason === 'manual'; idle/expired/blocked paths set it
|
|
13098
|
+
* only when reason === 'manual'; logout/idle/expired/blocked paths set it
|
|
12823
13099
|
* false so reporting dashboards that queried that boolean continue
|
|
12824
13100
|
* to work, while new code relies on `terminationReason`.
|
|
12825
13101
|
*
|
|
@@ -12832,13 +13108,13 @@ var require_session2 = __commonJS({
|
|
|
12832
13108
|
* `userId`. Used by
|
|
12833
13109
|
* /logout-other-devices so
|
|
12834
13110
|
* the caller stays logged in.
|
|
12835
|
-
* @param {'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
|
|
13111
|
+
* @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
|
|
12836
13112
|
* @returns {Promise<{terminatedCount: number}>}
|
|
12837
13113
|
*/
|
|
12838
13114
|
async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
|
|
12839
13115
|
try {
|
|
12840
13116
|
const now = /* @__PURE__ */ new Date();
|
|
12841
|
-
const validReasons = ["manual", "idle", "expired", "blocked"];
|
|
13117
|
+
const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
|
|
12842
13118
|
const finalReason = validReasons.includes(reason) ? reason : "manual";
|
|
12843
13119
|
const updateData = {
|
|
12844
13120
|
isActive: false,
|
|
@@ -12869,21 +13145,31 @@ var require_session2 = __commonJS({
|
|
|
12869
13145
|
if (exceptSessionId) {
|
|
12870
13146
|
filters.documentId = { $ne: exceptSessionId };
|
|
12871
13147
|
}
|
|
12872
|
-
const activeSessions = await strapi2.documents(SESSION_UID).findMany({
|
|
12873
|
-
filters,
|
|
12874
|
-
fields: ["documentId"],
|
|
12875
|
-
limit: MAX_SESSIONS_QUERY
|
|
12876
|
-
});
|
|
12877
13148
|
let terminatedCount = 0;
|
|
12878
|
-
|
|
12879
|
-
|
|
12880
|
-
|
|
12881
|
-
|
|
12882
|
-
|
|
12883
|
-
|
|
12884
|
-
|
|
12885
|
-
|
|
12886
|
-
|
|
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;
|
|
12887
13173
|
}
|
|
12888
13174
|
}
|
|
12889
13175
|
const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
|
|
@@ -13269,7 +13555,7 @@ var require_session2 = __commonJS({
|
|
|
13269
13555
|
var require_package = __commonJS({
|
|
13270
13556
|
"package.json"(exports, module) {
|
|
13271
13557
|
module.exports = {
|
|
13272
|
-
version: "4.
|
|
13558
|
+
version: "4.7.1",
|
|
13273
13559
|
keywords: [
|
|
13274
13560
|
"strapi",
|
|
13275
13561
|
"plugin",
|
|
@@ -13327,27 +13613,27 @@ var require_package = __commonJS({
|
|
|
13327
13613
|
},
|
|
13328
13614
|
dependencies: {
|
|
13329
13615
|
"@maxmind/geoip2-node": "^6.3.4",
|
|
13330
|
-
"sanitize-html": "^2.17.
|
|
13616
|
+
"sanitize-html": "^2.17.6"
|
|
13331
13617
|
},
|
|
13332
13618
|
devDependencies: {
|
|
13333
13619
|
"@semantic-release/changelog": "^6.0.3",
|
|
13334
13620
|
"@semantic-release/commit-analyzer": "^13.0.0",
|
|
13335
13621
|
"@semantic-release/git": "^10.0.1",
|
|
13336
|
-
"@semantic-release/github": "^12.0.
|
|
13622
|
+
"@semantic-release/github": "^12.0.9",
|
|
13337
13623
|
"@semantic-release/npm": "^13.1.5",
|
|
13338
13624
|
"@semantic-release/release-notes-generator": "^14.1.1",
|
|
13339
|
-
"@strapi/design-system": "^2.2.
|
|
13340
|
-
"@strapi/icons": "^2.2.
|
|
13625
|
+
"@strapi/design-system": "^2.2.2",
|
|
13626
|
+
"@strapi/icons": "^2.2.2",
|
|
13341
13627
|
"@strapi/sdk-plugin": "^6.1.1",
|
|
13342
|
-
"@strapi/strapi": "^5.
|
|
13628
|
+
"@strapi/strapi": "^5.50.1",
|
|
13343
13629
|
esbuild: "^0.28.1",
|
|
13344
|
-
prettier: "^3.
|
|
13630
|
+
prettier: "^3.9.5",
|
|
13345
13631
|
react: "^18.3.1",
|
|
13346
13632
|
"react-dom": "^18.3.1",
|
|
13347
13633
|
"react-intl": "^7.1.14",
|
|
13348
13634
|
"react-router-dom": "^6.30.4",
|
|
13349
13635
|
"semantic-release": "^25.0.5",
|
|
13350
|
-
"styled-components": "^6.4.
|
|
13636
|
+
"styled-components": "^6.4.3"
|
|
13351
13637
|
},
|
|
13352
13638
|
peerDependencies: {
|
|
13353
13639
|
"@strapi/design-system": "^2.0.0",
|
|
@@ -13618,7 +13904,8 @@ var require_geolocation = __commonJS({
|
|
|
13618
13904
|
var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
|
|
13619
13905
|
var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
|
|
13620
13906
|
var IPAPI_MAX_QUEUE_SIZE = 50;
|
|
13621
|
-
var
|
|
13907
|
+
var DEFAULT_CITY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
|
|
13908
|
+
var DEFAULT_COUNTRY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
|
|
13622
13909
|
var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
|
|
13623
13910
|
var readerCache = /* @__PURE__ */ new Map();
|
|
13624
13911
|
var ipapiCache = /* @__PURE__ */ new Map();
|
|
@@ -13630,12 +13917,32 @@ var require_geolocation = __commonJS({
|
|
|
13630
13917
|
function normalizeProvider(value) {
|
|
13631
13918
|
return VALID_PROVIDERS.has(value) ? value : "auto";
|
|
13632
13919
|
}
|
|
13633
|
-
function
|
|
13634
|
-
|
|
13635
|
-
|
|
13636
|
-
const trimmed = configured.trim();
|
|
13920
|
+
function normalizeDatabasePath(value) {
|
|
13921
|
+
if (typeof value !== "string" || value.trim() === "") return "";
|
|
13922
|
+
const trimmed = value.trim();
|
|
13637
13923
|
return path.isAbsolute(trimmed) ? trimmed : path.resolve(process.cwd(), trimmed);
|
|
13638
13924
|
}
|
|
13925
|
+
function uniqueValues(values) {
|
|
13926
|
+
return [...new Set(values.filter(Boolean))];
|
|
13927
|
+
}
|
|
13928
|
+
function resolveDatabaseCandidates(settings = {}) {
|
|
13929
|
+
const configured = normalizeDatabasePath(
|
|
13930
|
+
settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOIP_DATABASE_PATH
|
|
13931
|
+
);
|
|
13932
|
+
if (configured) return [configured];
|
|
13933
|
+
return uniqueValues([
|
|
13934
|
+
normalizeDatabasePath(process.env.GEOLITE2_CITY_MMDB),
|
|
13935
|
+
normalizeDatabasePath(process.env.GEOIP_CITY_DATABASE_PATH),
|
|
13936
|
+
normalizeDatabasePath(process.env.GEOLITE2_COUNTRY_MMDB),
|
|
13937
|
+
normalizeDatabasePath(process.env.GEOIP_COUNTRY_DATABASE_PATH),
|
|
13938
|
+
DEFAULT_CITY_MMDB_PATH,
|
|
13939
|
+
DEFAULT_COUNTRY_MMDB_PATH
|
|
13940
|
+
]);
|
|
13941
|
+
}
|
|
13942
|
+
function resolveExistingDatabasePath(settings = {}) {
|
|
13943
|
+
const candidates = resolveDatabaseCandidates(settings);
|
|
13944
|
+
return candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0] || "";
|
|
13945
|
+
}
|
|
13639
13946
|
async function openLocalReader(databasePath) {
|
|
13640
13947
|
if (readerCache.has(databasePath)) {
|
|
13641
13948
|
return readerCache.get(databasePath);
|
|
@@ -13720,6 +14027,79 @@ var require_geolocation = __commonJS({
|
|
|
13720
14027
|
next(releaseIpapiSlot);
|
|
13721
14028
|
}
|
|
13722
14029
|
}
|
|
14030
|
+
function getName(names = {}, fallback = "") {
|
|
14031
|
+
return names.en || names.de || names.fr || names.es || names.pt || fallback;
|
|
14032
|
+
}
|
|
14033
|
+
function getReaderDatabaseType(reader, databasePath) {
|
|
14034
|
+
const metadataType = reader?.metadata?.databaseType || reader?.metadata?.database_type || reader?.metadata?.database_type_name;
|
|
14035
|
+
if (typeof metadataType === "string" && metadataType.trim()) {
|
|
14036
|
+
return metadataType;
|
|
14037
|
+
}
|
|
14038
|
+
return path.basename(databasePath || "");
|
|
14039
|
+
}
|
|
14040
|
+
function isCityDatabase(reader, databasePath) {
|
|
14041
|
+
return /(?:^|[-_])City(?:\.|[-_]|$)/i.test(getReaderDatabaseType(reader, databasePath));
|
|
14042
|
+
}
|
|
14043
|
+
function normalizeLocalCountryResult(data, lookupIp, getCountryFlag) {
|
|
14044
|
+
const country = data.country || data.registeredCountry || data.representedCountry || {};
|
|
14045
|
+
const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
|
|
14046
|
+
return {
|
|
14047
|
+
ip: lookupIp,
|
|
14048
|
+
country: getName(country.names, countryCode || "Unknown"),
|
|
14049
|
+
country_code: countryCode,
|
|
14050
|
+
country_flag: getCountryFlag(countryCode),
|
|
14051
|
+
city: "Unknown",
|
|
14052
|
+
region: "Unknown",
|
|
14053
|
+
timezone: "Unknown",
|
|
14054
|
+
latitude: null,
|
|
14055
|
+
longitude: null,
|
|
14056
|
+
postal: null,
|
|
14057
|
+
org: null,
|
|
14058
|
+
asn: null,
|
|
14059
|
+
network: data.traits?.network || null,
|
|
14060
|
+
isVpn: false,
|
|
14061
|
+
isProxy: false,
|
|
14062
|
+
isThreat: false,
|
|
14063
|
+
isAnonymous: false,
|
|
14064
|
+
isTor: false,
|
|
14065
|
+
securityScore: 100,
|
|
14066
|
+
riskLevel: "Low",
|
|
14067
|
+
_status: "ok",
|
|
14068
|
+
_source: "local-mmdb",
|
|
14069
|
+
_databaseType: "country"
|
|
14070
|
+
};
|
|
14071
|
+
}
|
|
14072
|
+
function normalizeLocalCityResult(data, lookupIp, getCountryFlag) {
|
|
14073
|
+
const country = data.country || data.registeredCountry || data.representedCountry || {};
|
|
14074
|
+
const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
|
|
14075
|
+
const region = Array.isArray(data.subdivisions) && data.subdivisions.length > 0 ? data.subdivisions[0] : null;
|
|
14076
|
+
return {
|
|
14077
|
+
ip: lookupIp,
|
|
14078
|
+
country: getName(country.names, countryCode || "Unknown"),
|
|
14079
|
+
country_code: countryCode,
|
|
14080
|
+
country_flag: getCountryFlag(countryCode),
|
|
14081
|
+
city: getName(data.city?.names, "Unknown"),
|
|
14082
|
+
region: getName(region?.names, region?.isoCode || "Unknown"),
|
|
14083
|
+
timezone: data.location?.timeZone || "Unknown",
|
|
14084
|
+
latitude: data.location?.latitude ?? null,
|
|
14085
|
+
longitude: data.location?.longitude ?? null,
|
|
14086
|
+
accuracyRadius: data.location?.accuracyRadius ?? null,
|
|
14087
|
+
postal: data.postal?.code || null,
|
|
14088
|
+
org: null,
|
|
14089
|
+
asn: null,
|
|
14090
|
+
network: data.traits?.network || null,
|
|
14091
|
+
isVpn: false,
|
|
14092
|
+
isProxy: false,
|
|
14093
|
+
isThreat: false,
|
|
14094
|
+
isAnonymous: false,
|
|
14095
|
+
isTor: false,
|
|
14096
|
+
securityScore: 100,
|
|
14097
|
+
riskLevel: "Low",
|
|
14098
|
+
_status: "ok",
|
|
14099
|
+
_source: "local-mmdb",
|
|
14100
|
+
_databaseType: "city"
|
|
14101
|
+
};
|
|
14102
|
+
}
|
|
13723
14103
|
function normalizeLookupIp(ipAddress) {
|
|
13724
14104
|
if (typeof ipAddress !== "string") return "";
|
|
13725
14105
|
let normalized = ipAddress.trim();
|
|
@@ -13815,7 +14195,7 @@ var require_geolocation = __commonJS({
|
|
|
13815
14195
|
return this.getLocalMmdbIpInfo(lookupIp, settings);
|
|
13816
14196
|
}
|
|
13817
14197
|
if (provider === "auto") {
|
|
13818
|
-
const databasePath =
|
|
14198
|
+
const databasePath = resolveExistingDatabasePath(settings);
|
|
13819
14199
|
if (databasePath && fs.existsSync(databasePath)) {
|
|
13820
14200
|
const localResult = await this.getLocalMmdbIpInfo(lookupIp, settings);
|
|
13821
14201
|
if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
|
|
@@ -13838,7 +14218,9 @@ var require_geolocation = __commonJS({
|
|
|
13838
14218
|
}
|
|
13839
14219
|
},
|
|
13840
14220
|
/**
|
|
13841
|
-
* Looks up
|
|
14221
|
+
* Looks up geolocation data from a local MaxMind-compatible MMDB file.
|
|
14222
|
+
* GeoLite2-City is preferred for city-level data; GeoLite2-Country remains
|
|
14223
|
+
* supported for existing installations and country-only firewall decisions.
|
|
13842
14224
|
* @param {string} ipAddress
|
|
13843
14225
|
* @param {object} settings
|
|
13844
14226
|
* @returns {Promise<object>}
|
|
@@ -13848,7 +14230,7 @@ var require_geolocation = __commonJS({
|
|
|
13848
14230
|
if (!lookupIp || net.isIP(lookupIp) === 0) {
|
|
13849
14231
|
return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
|
|
13850
14232
|
}
|
|
13851
|
-
const databasePath =
|
|
14233
|
+
const databasePath = resolveExistingDatabasePath(settings);
|
|
13852
14234
|
if (!databasePath || !fs.existsSync(databasePath)) {
|
|
13853
14235
|
return this.getFallbackData(
|
|
13854
14236
|
ipAddress,
|
|
@@ -13859,35 +14241,12 @@ var require_geolocation = __commonJS({
|
|
|
13859
14241
|
}
|
|
13860
14242
|
try {
|
|
13861
14243
|
const reader = await openLocalReader(databasePath);
|
|
13862
|
-
const
|
|
13863
|
-
const
|
|
13864
|
-
const
|
|
13865
|
-
|
|
13866
|
-
|
|
13867
|
-
|
|
13868
|
-
country: countryNames.en || countryNames.de || countryCode || "Unknown",
|
|
13869
|
-
country_code: countryCode,
|
|
13870
|
-
country_flag: this.getCountryFlag(countryCode),
|
|
13871
|
-
city: "Unknown",
|
|
13872
|
-
region: "Unknown",
|
|
13873
|
-
timezone: "Unknown",
|
|
13874
|
-
latitude: null,
|
|
13875
|
-
longitude: null,
|
|
13876
|
-
postal: null,
|
|
13877
|
-
org: null,
|
|
13878
|
-
asn: null,
|
|
13879
|
-
network: data.traits?.network || null,
|
|
13880
|
-
isVpn: false,
|
|
13881
|
-
isProxy: false,
|
|
13882
|
-
isThreat: false,
|
|
13883
|
-
isAnonymous: false,
|
|
13884
|
-
isTor: false,
|
|
13885
|
-
securityScore: 100,
|
|
13886
|
-
riskLevel: "Low",
|
|
13887
|
-
_status: "ok",
|
|
13888
|
-
_source: "local-mmdb"
|
|
13889
|
-
};
|
|
13890
|
-
strapi2.log.debug(`[magic-sessionmanager/geolocation] Local MMDB IP ${lookupIp}: ${result.country_code}`);
|
|
14244
|
+
const useCityLookup = isCityDatabase(reader, databasePath) && typeof reader.city === "function";
|
|
14245
|
+
const data = useCityLookup ? reader.city(lookupIp) : reader.country(lookupIp);
|
|
14246
|
+
const result = useCityLookup ? normalizeLocalCityResult(data, lookupIp, this.getCountryFlag.bind(this)) : normalizeLocalCountryResult(data, lookupIp, this.getCountryFlag.bind(this));
|
|
14247
|
+
strapi2.log.debug(
|
|
14248
|
+
`[magic-sessionmanager/geolocation] Local MMDB ${result._databaseType} IP ${lookupIp}: ${result.city}, ${result.country_code}`
|
|
14249
|
+
);
|
|
13891
14250
|
return result;
|
|
13892
14251
|
} catch (error) {
|
|
13893
14252
|
strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed for ${lookupIp}:`, error.message);
|