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.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
|
});
|
|
@@ -12376,9 +12570,29 @@ var require_geoip_updater = __commonJS({
|
|
|
12376
12570
|
var zlib = require("node:zlib");
|
|
12377
12571
|
var { promisify } = require("node:util");
|
|
12378
12572
|
var gunzip = promisify(zlib.gunzip);
|
|
12379
|
-
var DEFAULT_EDITION_ID = "GeoLite2-
|
|
12380
|
-
var DEFAULT_MMDB_NAME =
|
|
12573
|
+
var DEFAULT_EDITION_ID = "GeoLite2-City";
|
|
12574
|
+
var DEFAULT_MMDB_NAME = `${DEFAULT_EDITION_ID}.mmdb`;
|
|
12381
12575
|
var DEFAULT_OUTPUT_PATH = path.resolve(process2.cwd(), "data", DEFAULT_MMDB_NAME);
|
|
12576
|
+
var SUPPORTED_EDITION_IDS = /* @__PURE__ */ new Set([
|
|
12577
|
+
"GeoLite2-City",
|
|
12578
|
+
"GeoLite2-Country",
|
|
12579
|
+
"GeoIP2-City",
|
|
12580
|
+
"GeoIP2-Country"
|
|
12581
|
+
]);
|
|
12582
|
+
function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
|
|
12583
|
+
return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
|
|
12584
|
+
}
|
|
12585
|
+
function inferEditionIdFromPath(filePath) {
|
|
12586
|
+
if (typeof filePath !== "string" || filePath.trim() === "") return "";
|
|
12587
|
+
const basename = path.basename(filePath.trim());
|
|
12588
|
+
if (/GeoIP2-City\.mmdb$/i.test(basename)) return "GeoIP2-City";
|
|
12589
|
+
if (/GeoIP2-Country\.mmdb$/i.test(basename)) return "GeoIP2-Country";
|
|
12590
|
+
if (/GeoLite2-City\.mmdb$/i.test(basename)) return "GeoLite2-City";
|
|
12591
|
+
if (/GeoLite2-Country\.mmdb$/i.test(basename)) return "GeoLite2-Country";
|
|
12592
|
+
if (/city/i.test(basename)) return "GeoLite2-City";
|
|
12593
|
+
if (/country/i.test(basename)) return "GeoLite2-Country";
|
|
12594
|
+
return "";
|
|
12595
|
+
}
|
|
12382
12596
|
function buildDownloadUrl(editionId = DEFAULT_EDITION_ID) {
|
|
12383
12597
|
return `https://download.maxmind.com/geoip/databases/${encodeURIComponent(editionId)}/download?suffix=tar.gz`;
|
|
12384
12598
|
}
|
|
@@ -12387,8 +12601,11 @@ var require_geoip_updater = __commonJS({
|
|
|
12387
12601
|
}
|
|
12388
12602
|
function resolveConfig(env = process2.env, argv = process2.argv.slice(2), overrides = {}) {
|
|
12389
12603
|
const force = argv.includes("--force") || overrides.force === true;
|
|
12390
|
-
const
|
|
12391
|
-
const
|
|
12604
|
+
const configuredOutputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || "";
|
|
12605
|
+
const editionId = normalizeEditionId(
|
|
12606
|
+
overrides.editionId || env.MAXMIND_EDITION_ID || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
|
|
12607
|
+
);
|
|
12608
|
+
const outputPath = configuredOutputPath || path.resolve(process2.cwd(), "data", `${editionId}.mmdb`);
|
|
12392
12609
|
return {
|
|
12393
12610
|
accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || "",
|
|
12394
12611
|
licenseKey: overrides.licenseKey || env.MAXMIND_LICENSE_KEY || "",
|
|
@@ -12546,6 +12763,7 @@ var require_geoip_updater = __commonJS({
|
|
|
12546
12763
|
buildDownloadUrl,
|
|
12547
12764
|
extractMmdbFromTarGz,
|
|
12548
12765
|
fileExists,
|
|
12766
|
+
inferEditionIdFromPath,
|
|
12549
12767
|
needsDownload,
|
|
12550
12768
|
readMetadata,
|
|
12551
12769
|
resolveConfig,
|
|
@@ -12558,6 +12776,7 @@ var require_geoip_updater = __commonJS({
|
|
|
12558
12776
|
var require_geoip = __commonJS({
|
|
12559
12777
|
"server/src/controllers/geoip.js"(exports2, module2) {
|
|
12560
12778
|
"use strict";
|
|
12779
|
+
var fs = require("node:fs");
|
|
12561
12780
|
var path = require("node:path");
|
|
12562
12781
|
var {
|
|
12563
12782
|
fileExists,
|
|
@@ -12571,6 +12790,8 @@ var require_geoip = __commonJS({
|
|
|
12571
12790
|
normalizeGeoIpDatabasePath
|
|
12572
12791
|
} = require_settings_loader();
|
|
12573
12792
|
var CREDENTIALS_KEY = "geoipCredentials";
|
|
12793
|
+
var DEFAULT_CITY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
|
|
12794
|
+
var DEFAULT_COUNTRY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
|
|
12574
12795
|
function getGeoIpStore(strapi2) {
|
|
12575
12796
|
return strapi2.store({
|
|
12576
12797
|
type: "plugin",
|
|
@@ -12606,10 +12827,11 @@ var require_geoip = __commonJS({
|
|
|
12606
12827
|
}
|
|
12607
12828
|
function buildUpdaterConfig(settings, storedCredentials, force = false) {
|
|
12608
12829
|
const outputPath = normalizeGeoIpDatabasePath(settings.geoIpDatabasePath);
|
|
12830
|
+
const existingDefaultPath = !outputPath && fs.existsSync(DEFAULT_CITY_DATABASE_PATH) ? DEFAULT_CITY_DATABASE_PATH : !outputPath && fs.existsSync(DEFAULT_COUNTRY_DATABASE_PATH) ? DEFAULT_COUNTRY_DATABASE_PATH : "";
|
|
12609
12831
|
return resolveConfig(process.env, force ? ["--force"] : [], {
|
|
12610
12832
|
accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
|
|
12611
12833
|
licenseKey: process.env.MAXMIND_LICENSE_KEY || storedCredentials.licenseKey || "",
|
|
12612
|
-
outputPath: outputPath || void 0,
|
|
12834
|
+
outputPath: outputPath || existingDefaultPath || void 0,
|
|
12613
12835
|
force
|
|
12614
12836
|
});
|
|
12615
12837
|
}
|
|
@@ -12633,6 +12855,7 @@ var require_geoip = __commonJS({
|
|
|
12633
12855
|
success: true,
|
|
12634
12856
|
status: {
|
|
12635
12857
|
provider: settings.geoIpProvider || "auto",
|
|
12858
|
+
editionId: config2.editionId,
|
|
12636
12859
|
databasePath: config2.outputPath,
|
|
12637
12860
|
databaseDirectory: path.dirname(config2.outputPath),
|
|
12638
12861
|
exists,
|
|
@@ -12726,7 +12949,7 @@ var require_session2 = __commonJS({
|
|
|
12726
12949
|
var { createLogger } = require_logger();
|
|
12727
12950
|
var { parseUserAgent } = require_user_agent_parser();
|
|
12728
12951
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
12729
|
-
var { enhanceSessions } = require_enhance_session();
|
|
12952
|
+
var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
|
|
12730
12953
|
var { getPluginSettings } = require_settings_loader();
|
|
12731
12954
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
12732
12955
|
var MAX_SESSIONS_QUERY = 1e3;
|
|
@@ -12736,7 +12959,7 @@ var require_session2 = __commonJS({
|
|
|
12736
12959
|
const settings = await getPluginSettings(strapi2);
|
|
12737
12960
|
return {
|
|
12738
12961
|
inactivityTimeout: settings.inactivityTimeout || 15 * 60 * 1e3,
|
|
12739
|
-
geolocationService: strapi2.plugin("magic-sessionmanager").service("geolocation"),
|
|
12962
|
+
geolocationService: shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null,
|
|
12740
12963
|
strapi: strapi2
|
|
12741
12964
|
};
|
|
12742
12965
|
}
|
|
@@ -12791,7 +13014,7 @@ var require_session2 = __commonJS({
|
|
|
12791
13014
|
region: geoData.region,
|
|
12792
13015
|
timezone: geoData.timezone
|
|
12793
13016
|
} : null,
|
|
12794
|
-
securityScore: geoData?.securityScore
|
|
13017
|
+
securityScore: geoData?.securityScore ?? null
|
|
12795
13018
|
}
|
|
12796
13019
|
});
|
|
12797
13020
|
log.info(`[SUCCESS] Session ${session.documentId} (${sessionId}) created for user ${userId}`);
|
|
@@ -12801,19 +13024,72 @@ var require_session2 = __commonJS({
|
|
|
12801
13024
|
throw err;
|
|
12802
13025
|
}
|
|
12803
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
|
+
},
|
|
12804
13079
|
/**
|
|
12805
13080
|
* Terminates a single session, all sessions of a user, or all sessions
|
|
12806
13081
|
* of a user EXCEPT one with a typed reason so the JWT-verify wrapper
|
|
12807
13082
|
* can communicate the cause to the client.
|
|
12808
13083
|
*
|
|
12809
13084
|
* Supported reasons:
|
|
12810
|
-
* - '
|
|
13085
|
+
* - 'logout': user clicked logout
|
|
13086
|
+
* - 'manual': admin terminated a session
|
|
12811
13087
|
* - 'idle': inactivity timeout cleanup
|
|
12812
13088
|
* - 'expired': maxSessionAgeDays exceeded
|
|
12813
13089
|
* - 'blocked': the owning user was marked blocked
|
|
12814
13090
|
*
|
|
12815
13091
|
* For backwards compatibility `terminatedManually` is still set true
|
|
12816
|
-
* only when reason === 'manual'; idle/expired/blocked paths set it
|
|
13092
|
+
* only when reason === 'manual'; logout/idle/expired/blocked paths set it
|
|
12817
13093
|
* false so reporting dashboards that queried that boolean continue
|
|
12818
13094
|
* to work, while new code relies on `terminationReason`.
|
|
12819
13095
|
*
|
|
@@ -12826,13 +13102,13 @@ var require_session2 = __commonJS({
|
|
|
12826
13102
|
* `userId`. Used by
|
|
12827
13103
|
* /logout-other-devices so
|
|
12828
13104
|
* the caller stays logged in.
|
|
12829
|
-
* @param {'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
|
|
13105
|
+
* @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
|
|
12830
13106
|
* @returns {Promise<{terminatedCount: number}>}
|
|
12831
13107
|
*/
|
|
12832
13108
|
async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
|
|
12833
13109
|
try {
|
|
12834
13110
|
const now = /* @__PURE__ */ new Date();
|
|
12835
|
-
const validReasons = ["manual", "idle", "expired", "blocked"];
|
|
13111
|
+
const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
|
|
12836
13112
|
const finalReason = validReasons.includes(reason) ? reason : "manual";
|
|
12837
13113
|
const updateData = {
|
|
12838
13114
|
isActive: false,
|
|
@@ -12863,21 +13139,31 @@ var require_session2 = __commonJS({
|
|
|
12863
13139
|
if (exceptSessionId) {
|
|
12864
13140
|
filters.documentId = { $ne: exceptSessionId };
|
|
12865
13141
|
}
|
|
12866
|
-
const activeSessions = await strapi2.documents(SESSION_UID).findMany({
|
|
12867
|
-
filters,
|
|
12868
|
-
fields: ["documentId"],
|
|
12869
|
-
limit: MAX_SESSIONS_QUERY
|
|
12870
|
-
});
|
|
12871
13142
|
let terminatedCount = 0;
|
|
12872
|
-
|
|
12873
|
-
|
|
12874
|
-
|
|
12875
|
-
|
|
12876
|
-
|
|
12877
|
-
|
|
12878
|
-
|
|
12879
|
-
|
|
12880
|
-
|
|
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;
|
|
12881
13167
|
}
|
|
12882
13168
|
}
|
|
12883
13169
|
const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
|
|
@@ -13263,7 +13549,7 @@ var require_session2 = __commonJS({
|
|
|
13263
13549
|
var require_package = __commonJS({
|
|
13264
13550
|
"package.json"(exports2, module2) {
|
|
13265
13551
|
module2.exports = {
|
|
13266
|
-
version: "4.
|
|
13552
|
+
version: "4.7.1",
|
|
13267
13553
|
keywords: [
|
|
13268
13554
|
"strapi",
|
|
13269
13555
|
"plugin",
|
|
@@ -13321,27 +13607,27 @@ var require_package = __commonJS({
|
|
|
13321
13607
|
},
|
|
13322
13608
|
dependencies: {
|
|
13323
13609
|
"@maxmind/geoip2-node": "^6.3.4",
|
|
13324
|
-
"sanitize-html": "^2.17.
|
|
13610
|
+
"sanitize-html": "^2.17.6"
|
|
13325
13611
|
},
|
|
13326
13612
|
devDependencies: {
|
|
13327
13613
|
"@semantic-release/changelog": "^6.0.3",
|
|
13328
13614
|
"@semantic-release/commit-analyzer": "^13.0.0",
|
|
13329
13615
|
"@semantic-release/git": "^10.0.1",
|
|
13330
|
-
"@semantic-release/github": "^12.0.
|
|
13616
|
+
"@semantic-release/github": "^12.0.9",
|
|
13331
13617
|
"@semantic-release/npm": "^13.1.5",
|
|
13332
13618
|
"@semantic-release/release-notes-generator": "^14.1.1",
|
|
13333
|
-
"@strapi/design-system": "^2.2.
|
|
13334
|
-
"@strapi/icons": "^2.2.
|
|
13619
|
+
"@strapi/design-system": "^2.2.2",
|
|
13620
|
+
"@strapi/icons": "^2.2.2",
|
|
13335
13621
|
"@strapi/sdk-plugin": "^6.1.1",
|
|
13336
|
-
"@strapi/strapi": "^5.
|
|
13622
|
+
"@strapi/strapi": "^5.50.1",
|
|
13337
13623
|
esbuild: "^0.28.1",
|
|
13338
|
-
prettier: "^3.
|
|
13624
|
+
prettier: "^3.9.5",
|
|
13339
13625
|
react: "^18.3.1",
|
|
13340
13626
|
"react-dom": "^18.3.1",
|
|
13341
13627
|
"react-intl": "^7.1.14",
|
|
13342
13628
|
"react-router-dom": "^6.30.4",
|
|
13343
13629
|
"semantic-release": "^25.0.5",
|
|
13344
|
-
"styled-components": "^6.4.
|
|
13630
|
+
"styled-components": "^6.4.3"
|
|
13345
13631
|
},
|
|
13346
13632
|
peerDependencies: {
|
|
13347
13633
|
"@strapi/design-system": "^2.0.0",
|
|
@@ -13612,7 +13898,8 @@ var require_geolocation = __commonJS({
|
|
|
13612
13898
|
var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
|
|
13613
13899
|
var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
|
|
13614
13900
|
var IPAPI_MAX_QUEUE_SIZE = 50;
|
|
13615
|
-
var
|
|
13901
|
+
var DEFAULT_CITY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
|
|
13902
|
+
var DEFAULT_COUNTRY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
|
|
13616
13903
|
var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
|
|
13617
13904
|
var readerCache = /* @__PURE__ */ new Map();
|
|
13618
13905
|
var ipapiCache = /* @__PURE__ */ new Map();
|
|
@@ -13624,12 +13911,32 @@ var require_geolocation = __commonJS({
|
|
|
13624
13911
|
function normalizeProvider(value) {
|
|
13625
13912
|
return VALID_PROVIDERS.has(value) ? value : "auto";
|
|
13626
13913
|
}
|
|
13627
|
-
function
|
|
13628
|
-
|
|
13629
|
-
|
|
13630
|
-
const trimmed = configured.trim();
|
|
13914
|
+
function normalizeDatabasePath(value) {
|
|
13915
|
+
if (typeof value !== "string" || value.trim() === "") return "";
|
|
13916
|
+
const trimmed = value.trim();
|
|
13631
13917
|
return path.isAbsolute(trimmed) ? trimmed : path.resolve(process.cwd(), trimmed);
|
|
13632
13918
|
}
|
|
13919
|
+
function uniqueValues(values) {
|
|
13920
|
+
return [...new Set(values.filter(Boolean))];
|
|
13921
|
+
}
|
|
13922
|
+
function resolveDatabaseCandidates(settings = {}) {
|
|
13923
|
+
const configured = normalizeDatabasePath(
|
|
13924
|
+
settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOIP_DATABASE_PATH
|
|
13925
|
+
);
|
|
13926
|
+
if (configured) return [configured];
|
|
13927
|
+
return uniqueValues([
|
|
13928
|
+
normalizeDatabasePath(process.env.GEOLITE2_CITY_MMDB),
|
|
13929
|
+
normalizeDatabasePath(process.env.GEOIP_CITY_DATABASE_PATH),
|
|
13930
|
+
normalizeDatabasePath(process.env.GEOLITE2_COUNTRY_MMDB),
|
|
13931
|
+
normalizeDatabasePath(process.env.GEOIP_COUNTRY_DATABASE_PATH),
|
|
13932
|
+
DEFAULT_CITY_MMDB_PATH,
|
|
13933
|
+
DEFAULT_COUNTRY_MMDB_PATH
|
|
13934
|
+
]);
|
|
13935
|
+
}
|
|
13936
|
+
function resolveExistingDatabasePath(settings = {}) {
|
|
13937
|
+
const candidates = resolveDatabaseCandidates(settings);
|
|
13938
|
+
return candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0] || "";
|
|
13939
|
+
}
|
|
13633
13940
|
async function openLocalReader(databasePath) {
|
|
13634
13941
|
if (readerCache.has(databasePath)) {
|
|
13635
13942
|
return readerCache.get(databasePath);
|
|
@@ -13714,6 +14021,79 @@ var require_geolocation = __commonJS({
|
|
|
13714
14021
|
next(releaseIpapiSlot);
|
|
13715
14022
|
}
|
|
13716
14023
|
}
|
|
14024
|
+
function getName(names = {}, fallback = "") {
|
|
14025
|
+
return names.en || names.de || names.fr || names.es || names.pt || fallback;
|
|
14026
|
+
}
|
|
14027
|
+
function getReaderDatabaseType(reader, databasePath) {
|
|
14028
|
+
const metadataType = reader?.metadata?.databaseType || reader?.metadata?.database_type || reader?.metadata?.database_type_name;
|
|
14029
|
+
if (typeof metadataType === "string" && metadataType.trim()) {
|
|
14030
|
+
return metadataType;
|
|
14031
|
+
}
|
|
14032
|
+
return path.basename(databasePath || "");
|
|
14033
|
+
}
|
|
14034
|
+
function isCityDatabase(reader, databasePath) {
|
|
14035
|
+
return /(?:^|[-_])City(?:\.|[-_]|$)/i.test(getReaderDatabaseType(reader, databasePath));
|
|
14036
|
+
}
|
|
14037
|
+
function normalizeLocalCountryResult(data, lookupIp, getCountryFlag) {
|
|
14038
|
+
const country = data.country || data.registeredCountry || data.representedCountry || {};
|
|
14039
|
+
const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
|
|
14040
|
+
return {
|
|
14041
|
+
ip: lookupIp,
|
|
14042
|
+
country: getName(country.names, countryCode || "Unknown"),
|
|
14043
|
+
country_code: countryCode,
|
|
14044
|
+
country_flag: getCountryFlag(countryCode),
|
|
14045
|
+
city: "Unknown",
|
|
14046
|
+
region: "Unknown",
|
|
14047
|
+
timezone: "Unknown",
|
|
14048
|
+
latitude: null,
|
|
14049
|
+
longitude: null,
|
|
14050
|
+
postal: null,
|
|
14051
|
+
org: null,
|
|
14052
|
+
asn: null,
|
|
14053
|
+
network: data.traits?.network || null,
|
|
14054
|
+
isVpn: false,
|
|
14055
|
+
isProxy: false,
|
|
14056
|
+
isThreat: false,
|
|
14057
|
+
isAnonymous: false,
|
|
14058
|
+
isTor: false,
|
|
14059
|
+
securityScore: 100,
|
|
14060
|
+
riskLevel: "Low",
|
|
14061
|
+
_status: "ok",
|
|
14062
|
+
_source: "local-mmdb",
|
|
14063
|
+
_databaseType: "country"
|
|
14064
|
+
};
|
|
14065
|
+
}
|
|
14066
|
+
function normalizeLocalCityResult(data, lookupIp, getCountryFlag) {
|
|
14067
|
+
const country = data.country || data.registeredCountry || data.representedCountry || {};
|
|
14068
|
+
const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
|
|
14069
|
+
const region = Array.isArray(data.subdivisions) && data.subdivisions.length > 0 ? data.subdivisions[0] : null;
|
|
14070
|
+
return {
|
|
14071
|
+
ip: lookupIp,
|
|
14072
|
+
country: getName(country.names, countryCode || "Unknown"),
|
|
14073
|
+
country_code: countryCode,
|
|
14074
|
+
country_flag: getCountryFlag(countryCode),
|
|
14075
|
+
city: getName(data.city?.names, "Unknown"),
|
|
14076
|
+
region: getName(region?.names, region?.isoCode || "Unknown"),
|
|
14077
|
+
timezone: data.location?.timeZone || "Unknown",
|
|
14078
|
+
latitude: data.location?.latitude ?? null,
|
|
14079
|
+
longitude: data.location?.longitude ?? null,
|
|
14080
|
+
accuracyRadius: data.location?.accuracyRadius ?? null,
|
|
14081
|
+
postal: data.postal?.code || null,
|
|
14082
|
+
org: null,
|
|
14083
|
+
asn: null,
|
|
14084
|
+
network: data.traits?.network || null,
|
|
14085
|
+
isVpn: false,
|
|
14086
|
+
isProxy: false,
|
|
14087
|
+
isThreat: false,
|
|
14088
|
+
isAnonymous: false,
|
|
14089
|
+
isTor: false,
|
|
14090
|
+
securityScore: 100,
|
|
14091
|
+
riskLevel: "Low",
|
|
14092
|
+
_status: "ok",
|
|
14093
|
+
_source: "local-mmdb",
|
|
14094
|
+
_databaseType: "city"
|
|
14095
|
+
};
|
|
14096
|
+
}
|
|
13717
14097
|
function normalizeLookupIp(ipAddress) {
|
|
13718
14098
|
if (typeof ipAddress !== "string") return "";
|
|
13719
14099
|
let normalized = ipAddress.trim();
|
|
@@ -13809,7 +14189,7 @@ var require_geolocation = __commonJS({
|
|
|
13809
14189
|
return this.getLocalMmdbIpInfo(lookupIp, settings);
|
|
13810
14190
|
}
|
|
13811
14191
|
if (provider === "auto") {
|
|
13812
|
-
const databasePath =
|
|
14192
|
+
const databasePath = resolveExistingDatabasePath(settings);
|
|
13813
14193
|
if (databasePath && fs.existsSync(databasePath)) {
|
|
13814
14194
|
const localResult = await this.getLocalMmdbIpInfo(lookupIp, settings);
|
|
13815
14195
|
if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
|
|
@@ -13832,7 +14212,9 @@ var require_geolocation = __commonJS({
|
|
|
13832
14212
|
}
|
|
13833
14213
|
},
|
|
13834
14214
|
/**
|
|
13835
|
-
* Looks up
|
|
14215
|
+
* Looks up geolocation data from a local MaxMind-compatible MMDB file.
|
|
14216
|
+
* GeoLite2-City is preferred for city-level data; GeoLite2-Country remains
|
|
14217
|
+
* supported for existing installations and country-only firewall decisions.
|
|
13836
14218
|
* @param {string} ipAddress
|
|
13837
14219
|
* @param {object} settings
|
|
13838
14220
|
* @returns {Promise<object>}
|
|
@@ -13842,7 +14224,7 @@ var require_geolocation = __commonJS({
|
|
|
13842
14224
|
if (!lookupIp || net.isIP(lookupIp) === 0) {
|
|
13843
14225
|
return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
|
|
13844
14226
|
}
|
|
13845
|
-
const databasePath =
|
|
14227
|
+
const databasePath = resolveExistingDatabasePath(settings);
|
|
13846
14228
|
if (!databasePath || !fs.existsSync(databasePath)) {
|
|
13847
14229
|
return this.getFallbackData(
|
|
13848
14230
|
ipAddress,
|
|
@@ -13853,35 +14235,12 @@ var require_geolocation = __commonJS({
|
|
|
13853
14235
|
}
|
|
13854
14236
|
try {
|
|
13855
14237
|
const reader = await openLocalReader(databasePath);
|
|
13856
|
-
const
|
|
13857
|
-
const
|
|
13858
|
-
const
|
|
13859
|
-
|
|
13860
|
-
|
|
13861
|
-
|
|
13862
|
-
country: countryNames.en || countryNames.de || countryCode || "Unknown",
|
|
13863
|
-
country_code: countryCode,
|
|
13864
|
-
country_flag: this.getCountryFlag(countryCode),
|
|
13865
|
-
city: "Unknown",
|
|
13866
|
-
region: "Unknown",
|
|
13867
|
-
timezone: "Unknown",
|
|
13868
|
-
latitude: null,
|
|
13869
|
-
longitude: null,
|
|
13870
|
-
postal: null,
|
|
13871
|
-
org: null,
|
|
13872
|
-
asn: null,
|
|
13873
|
-
network: data.traits?.network || null,
|
|
13874
|
-
isVpn: false,
|
|
13875
|
-
isProxy: false,
|
|
13876
|
-
isThreat: false,
|
|
13877
|
-
isAnonymous: false,
|
|
13878
|
-
isTor: false,
|
|
13879
|
-
securityScore: 100,
|
|
13880
|
-
riskLevel: "Low",
|
|
13881
|
-
_status: "ok",
|
|
13882
|
-
_source: "local-mmdb"
|
|
13883
|
-
};
|
|
13884
|
-
strapi2.log.debug(`[magic-sessionmanager/geolocation] Local MMDB IP ${lookupIp}: ${result.country_code}`);
|
|
14238
|
+
const useCityLookup = isCityDatabase(reader, databasePath) && typeof reader.city === "function";
|
|
14239
|
+
const data = useCityLookup ? reader.city(lookupIp) : reader.country(lookupIp);
|
|
14240
|
+
const result = useCityLookup ? normalizeLocalCityResult(data, lookupIp, this.getCountryFlag.bind(this)) : normalizeLocalCountryResult(data, lookupIp, this.getCountryFlag.bind(this));
|
|
14241
|
+
strapi2.log.debug(
|
|
14242
|
+
`[magic-sessionmanager/geolocation] Local MMDB ${result._databaseType} IP ${lookupIp}: ${result.city}, ${result.country_code}`
|
|
14243
|
+
);
|
|
13885
14244
|
return result;
|
|
13886
14245
|
} catch (error) {
|
|
13887
14246
|
strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed for ${lookupIp}:`, error.message);
|