strapi-plugin-magic-sessionmanager 4.6.3 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +20 -12
  3. package/dist/admin/{Analytics-BMkhiuRX.js → Analytics-Cw6R2xZn.js} +5 -1
  4. package/dist/admin/{Analytics-CwNJ3TNI.mjs → Analytics-Dq8PuDhs.mjs} +5 -1
  5. package/dist/admin/{App-Sk0F9UEN.mjs → App-BIFTc3mk.mjs} +36 -6
  6. package/dist/admin/{App-DazHh7Zi.js → App-DLR2M3FT.js} +36 -6
  7. package/dist/admin/{License-BwbmzbP_.js → License-BZtjgFol.js} +1 -1
  8. package/dist/admin/{License-6SIpR7Rk.mjs → License-W_NPUWIn.mjs} +1 -1
  9. package/dist/admin/{OnlineUsersWidget-Qq_uCTi1.mjs → OnlineUsersWidget-BIbmzgLP.mjs} +1 -1
  10. package/dist/admin/{OnlineUsersWidget-BIfnbFcZ.js → OnlineUsersWidget-CAdR0MfU.js} +1 -1
  11. package/dist/admin/{Settings-BA7S_8DF.mjs → Settings-BNu9EAuS.mjs} +10 -10
  12. package/dist/admin/{Settings-CCYScjxv.js → Settings-DWaflQdm.js} +10 -10
  13. package/dist/admin/{de-6rIvkYOp.mjs → de-4pAz-Ihh.mjs} +4 -3
  14. package/dist/admin/{de-DjP2WJ_V.js → de-jU7AaYIc.js} +4 -3
  15. package/dist/admin/{en-8hiv31Dv.mjs → en-BI_aBNXG.mjs} +4 -3
  16. package/dist/admin/{en-0pesBbOT.js → en-Tjp9AEhR.js} +4 -3
  17. package/dist/admin/{es-DdBRpF7F.js → es-BCgwFZPL.js} +4 -3
  18. package/dist/admin/{es-LRQ148f5.mjs → es-Bp4Uzf5h.mjs} +4 -3
  19. package/dist/admin/{fr-CKhx_qil.mjs → fr-B69qIjq2.mjs} +4 -3
  20. package/dist/admin/{fr-DJ6DbeDy.js → fr-Di5zo4wy.js} +4 -3
  21. package/dist/admin/{index-DTskQVDl.js → index-CBS3aqCW.js} +10 -10
  22. package/dist/admin/{index-UTLA1r40.mjs → index-eSND7TDx.mjs} +10 -10
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +1 -1
  25. package/dist/admin/{pt-D0SMoAmo.js → pt-DlGYOi6D.js} +4 -3
  26. package/dist/admin/{pt-DXizUvcj.mjs → pt-Drc-di4D.mjs} +4 -3
  27. package/dist/server/index.js +443 -139
  28. package/dist/server/index.mjs +443 -139
  29. package/package.json +7 -7
  30. package/scripts/geoip-updater.cjs +39 -4
  31. package/scripts/update-geoip-db.mjs +1 -0
@@ -9816,6 +9816,18 @@ var require_bootstrap = __commonJS({
9816
9816
  if (path.startsWith("/api/magic-link/login") && (method === "GET" || method === "POST")) return true;
9817
9817
  return false;
9818
9818
  }
9819
+ async function getRequestSettings(strapi2, ctx) {
9820
+ let settings = {};
9821
+ try {
9822
+ settings = await getPluginSettings(strapi2);
9823
+ } catch {
9824
+ settings = {};
9825
+ }
9826
+ if (ctx && ctx.state) {
9827
+ ctx.state.__magicSessionSettings = settings;
9828
+ }
9829
+ return settings;
9830
+ }
9819
9831
  module.exports = async ({ strapi: strapi2 }) => {
9820
9832
  const log = createLogger(strapi2);
9821
9833
  log.info("[START] Bootstrap starting...");
@@ -9913,12 +9925,7 @@ var require_bootstrap = __commonJS({
9913
9925
  if (!isLoginPath(ctx.path, ctx.method)) {
9914
9926
  return next();
9915
9927
  }
9916
- let settings = {};
9917
- try {
9918
- settings = await getPluginSettings(strapi2);
9919
- } catch {
9920
- settings = {};
9921
- }
9928
+ const settings = await getRequestSettings(strapi2, ctx);
9922
9929
  const needsGeoCheck = settings.blockSuspiciousSessions || settings.enableGeofencing || settings.enableGeolocation;
9923
9930
  if (!needsGeoCheck) {
9924
9931
  return next();
@@ -10056,13 +10063,8 @@ var require_bootstrap = __commonJS({
10056
10063
  const clearFailures = (ip) => failed.delete(ip);
10057
10064
  strapi2.server.use(async (ctx, next) => {
10058
10065
  if (!isLoginPath(ctx.path, ctx.method)) return next();
10059
- let maxFailed = 0;
10060
- try {
10061
- const settings = await getPluginSettings(strapi2);
10062
- maxFailed = Number(settings.maxFailedLogins) || 0;
10063
- } catch {
10064
- maxFailed = 0;
10065
- }
10066
+ const settings = await getRequestSettings(strapi2, ctx);
10067
+ const maxFailed = Number(settings.maxFailedLogins) || 0;
10066
10068
  if (maxFailed <= 0) return next();
10067
10069
  const ip = getClientIp(ctx);
10068
10070
  if (!ip || ip === "unknown") return next();
@@ -10121,6 +10123,7 @@ var require_bootstrap = __commonJS({
10121
10123
  if (!ctx.body || !ctx.body.jwt || !ctx.body.user) return;
10122
10124
  try {
10123
10125
  const user = ctx.body.user;
10126
+ await getRequestSettings(strapi2, ctx);
10124
10127
  const ip = getClientIp(ctx);
10125
10128
  const headers = ctx.request.headers || ctx.request.header || {};
10126
10129
  const userAgent = headers["user-agent"] || "unknown";
@@ -12379,9 +12382,29 @@ var require_geoip_updater = __commonJS({
12379
12382
  var zlib = __require("node:zlib");
12380
12383
  var { promisify } = __require("node:util");
12381
12384
  var gunzip = promisify(zlib.gunzip);
12382
- var DEFAULT_EDITION_ID = "GeoLite2-Country";
12383
- var DEFAULT_MMDB_NAME = "GeoLite2-Country.mmdb";
12385
+ var DEFAULT_EDITION_ID = "GeoLite2-City";
12386
+ var DEFAULT_MMDB_NAME = `${DEFAULT_EDITION_ID}.mmdb`;
12384
12387
  var DEFAULT_OUTPUT_PATH = path.resolve(process2.cwd(), "data", DEFAULT_MMDB_NAME);
12388
+ var SUPPORTED_EDITION_IDS = /* @__PURE__ */ new Set([
12389
+ "GeoLite2-City",
12390
+ "GeoLite2-Country",
12391
+ "GeoIP2-City",
12392
+ "GeoIP2-Country"
12393
+ ]);
12394
+ function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
12395
+ return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
12396
+ }
12397
+ function inferEditionIdFromPath(filePath) {
12398
+ if (typeof filePath !== "string" || filePath.trim() === "") return "";
12399
+ const basename = path.basename(filePath.trim());
12400
+ if (/GeoIP2-City\.mmdb$/i.test(basename)) return "GeoIP2-City";
12401
+ if (/GeoIP2-Country\.mmdb$/i.test(basename)) return "GeoIP2-Country";
12402
+ if (/GeoLite2-City\.mmdb$/i.test(basename)) return "GeoLite2-City";
12403
+ if (/GeoLite2-Country\.mmdb$/i.test(basename)) return "GeoLite2-Country";
12404
+ if (/city/i.test(basename)) return "GeoLite2-City";
12405
+ if (/country/i.test(basename)) return "GeoLite2-Country";
12406
+ return "";
12407
+ }
12385
12408
  function buildDownloadUrl(editionId = DEFAULT_EDITION_ID) {
12386
12409
  return `https://download.maxmind.com/geoip/databases/${encodeURIComponent(editionId)}/download?suffix=tar.gz`;
12387
12410
  }
@@ -12390,8 +12413,11 @@ var require_geoip_updater = __commonJS({
12390
12413
  }
12391
12414
  function resolveConfig(env = process2.env, argv = process2.argv.slice(2), overrides = {}) {
12392
12415
  const force = argv.includes("--force") || overrides.force === true;
12393
- const editionId = overrides.editionId || env.MAXMIND_EDITION_ID || DEFAULT_EDITION_ID;
12394
- const outputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || DEFAULT_OUTPUT_PATH;
12416
+ const configuredOutputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || "";
12417
+ const editionId = normalizeEditionId(
12418
+ overrides.editionId || env.MAXMIND_EDITION_ID || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
12419
+ );
12420
+ const outputPath = configuredOutputPath || path.resolve(process2.cwd(), "data", `${editionId}.mmdb`);
12395
12421
  return {
12396
12422
  accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || "",
12397
12423
  licenseKey: overrides.licenseKey || env.MAXMIND_LICENSE_KEY || "",
@@ -12549,6 +12575,7 @@ var require_geoip_updater = __commonJS({
12549
12575
  buildDownloadUrl,
12550
12576
  extractMmdbFromTarGz,
12551
12577
  fileExists,
12578
+ inferEditionIdFromPath,
12552
12579
  needsDownload,
12553
12580
  readMetadata,
12554
12581
  resolveConfig,
@@ -12561,6 +12588,7 @@ var require_geoip_updater = __commonJS({
12561
12588
  var require_geoip = __commonJS({
12562
12589
  "server/src/controllers/geoip.js"(exports, module) {
12563
12590
  "use strict";
12591
+ var fs = __require("node:fs");
12564
12592
  var path = __require("node:path");
12565
12593
  var {
12566
12594
  fileExists,
@@ -12574,6 +12602,8 @@ var require_geoip = __commonJS({
12574
12602
  normalizeGeoIpDatabasePath
12575
12603
  } = require_settings_loader();
12576
12604
  var CREDENTIALS_KEY = "geoipCredentials";
12605
+ var DEFAULT_CITY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
12606
+ var DEFAULT_COUNTRY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
12577
12607
  function getGeoIpStore(strapi2) {
12578
12608
  return strapi2.store({
12579
12609
  type: "plugin",
@@ -12609,10 +12639,11 @@ var require_geoip = __commonJS({
12609
12639
  }
12610
12640
  function buildUpdaterConfig(settings, storedCredentials, force = false) {
12611
12641
  const outputPath = normalizeGeoIpDatabasePath(settings.geoIpDatabasePath);
12642
+ const existingDefaultPath = !outputPath && fs.existsSync(DEFAULT_CITY_DATABASE_PATH) ? DEFAULT_CITY_DATABASE_PATH : !outputPath && fs.existsSync(DEFAULT_COUNTRY_DATABASE_PATH) ? DEFAULT_COUNTRY_DATABASE_PATH : "";
12612
12643
  return resolveConfig(process.env, force ? ["--force"] : [], {
12613
12644
  accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
12614
12645
  licenseKey: process.env.MAXMIND_LICENSE_KEY || storedCredentials.licenseKey || "",
12615
- outputPath: outputPath || void 0,
12646
+ outputPath: outputPath || existingDefaultPath || void 0,
12616
12647
  force
12617
12648
  });
12618
12649
  }
@@ -12636,6 +12667,7 @@ var require_geoip = __commonJS({
12636
12667
  success: true,
12637
12668
  status: {
12638
12669
  provider: settings.geoIpProvider || "auto",
12670
+ editionId: config.editionId,
12639
12671
  databasePath: config.outputPath,
12640
12672
  databaseDirectory: path.dirname(config.outputPath),
12641
12673
  exists,
@@ -13266,7 +13298,7 @@ var require_session2 = __commonJS({
13266
13298
  var require_package = __commonJS({
13267
13299
  "package.json"(exports, module) {
13268
13300
  module.exports = {
13269
- version: "4.6.3",
13301
+ version: "4.7.0",
13270
13302
  keywords: [
13271
13303
  "strapi",
13272
13304
  "plugin",
@@ -13330,21 +13362,21 @@ var require_package = __commonJS({
13330
13362
  "@semantic-release/changelog": "^6.0.3",
13331
13363
  "@semantic-release/commit-analyzer": "^13.0.0",
13332
13364
  "@semantic-release/git": "^10.0.1",
13333
- "@semantic-release/github": "^12.0.8",
13365
+ "@semantic-release/github": "^12.0.9",
13334
13366
  "@semantic-release/npm": "^13.1.5",
13335
13367
  "@semantic-release/release-notes-generator": "^14.1.1",
13336
- "@strapi/design-system": "^2.2.0",
13337
- "@strapi/icons": "^2.2.0",
13368
+ "@strapi/design-system": "^2.2.2",
13369
+ "@strapi/icons": "^2.2.2",
13338
13370
  "@strapi/sdk-plugin": "^6.1.1",
13339
- "@strapi/strapi": "^5.48.1",
13371
+ "@strapi/strapi": "^5.50.1",
13340
13372
  esbuild: "^0.28.1",
13341
- prettier: "^3.8.4",
13373
+ prettier: "^3.9.5",
13342
13374
  react: "^18.3.1",
13343
13375
  "react-dom": "^18.3.1",
13344
13376
  "react-intl": "^7.1.14",
13345
13377
  "react-router-dom": "^6.30.4",
13346
13378
  "semantic-release": "^25.0.5",
13347
- "styled-components": "^6.4.2"
13379
+ "styled-components": "^6.4.3"
13348
13380
  },
13349
13381
  peerDependencies: {
13350
13382
  "@strapi/design-system": "^2.0.0",
@@ -13605,21 +13637,55 @@ var require_geolocation = __commonJS({
13605
13637
  "server/src/services/geolocation.js"(exports, module) {
13606
13638
  "use strict";
13607
13639
  var fs = __require("node:fs");
13640
+ var net = __require("node:net");
13608
13641
  var path = __require("node:path");
13609
13642
  var { getPluginSettings } = require_settings_loader();
13610
13643
  var GEO_API_TIMEOUT_MS = 4e3;
13611
- var DEFAULT_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
13644
+ var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
13645
+ var IPAPI_FAILURE_CACHE_TTL_MS = 5 * 60 * 1e3;
13646
+ var IPAPI_RATE_LIMIT_BACKOFF_MS = 15 * 60 * 1e3;
13647
+ var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
13648
+ var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
13649
+ var IPAPI_MAX_QUEUE_SIZE = 50;
13650
+ var DEFAULT_CITY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
13651
+ var DEFAULT_COUNTRY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
13612
13652
  var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
13613
13653
  var readerCache = /* @__PURE__ */ new Map();
13654
+ var ipapiCache = /* @__PURE__ */ new Map();
13655
+ var ipapiInFlight = /* @__PURE__ */ new Map();
13656
+ var ipapiQueue = [];
13657
+ var ipapiActiveRequests = 0;
13658
+ var ipapiRateLimitedUntil = 0;
13659
+ var ipapiLastRateLimitLogAt = 0;
13614
13660
  function normalizeProvider(value) {
13615
13661
  return VALID_PROVIDERS.has(value) ? value : "auto";
13616
13662
  }
13617
- function resolveDatabasePath(settings = {}) {
13618
- const configured = settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOLITE2_COUNTRY_MMDB || DEFAULT_MMDB_PATH;
13619
- if (typeof configured !== "string" || configured.trim() === "") return "";
13620
- const trimmed = configured.trim();
13663
+ function normalizeDatabasePath(value) {
13664
+ if (typeof value !== "string" || value.trim() === "") return "";
13665
+ const trimmed = value.trim();
13621
13666
  return path.isAbsolute(trimmed) ? trimmed : path.resolve(process.cwd(), trimmed);
13622
13667
  }
13668
+ function uniqueValues(values) {
13669
+ return [...new Set(values.filter(Boolean))];
13670
+ }
13671
+ function resolveDatabaseCandidates(settings = {}) {
13672
+ const configured = normalizeDatabasePath(
13673
+ settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOIP_DATABASE_PATH
13674
+ );
13675
+ if (configured) return [configured];
13676
+ return uniqueValues([
13677
+ normalizeDatabasePath(process.env.GEOLITE2_CITY_MMDB),
13678
+ normalizeDatabasePath(process.env.GEOIP_CITY_DATABASE_PATH),
13679
+ normalizeDatabasePath(process.env.GEOLITE2_COUNTRY_MMDB),
13680
+ normalizeDatabasePath(process.env.GEOIP_COUNTRY_DATABASE_PATH),
13681
+ DEFAULT_CITY_MMDB_PATH,
13682
+ DEFAULT_COUNTRY_MMDB_PATH
13683
+ ]);
13684
+ }
13685
+ function resolveExistingDatabasePath(settings = {}) {
13686
+ const candidates = resolveDatabaseCandidates(settings);
13687
+ return candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0] || "";
13688
+ }
13623
13689
  async function openLocalReader(databasePath) {
13624
13690
  if (readerCache.has(databasePath)) {
13625
13691
  return readerCache.get(databasePath);
@@ -13634,6 +13700,192 @@ var require_geolocation = __commonJS({
13634
13700
  throw err;
13635
13701
  }
13636
13702
  }
13703
+ function cloneGeoData(data) {
13704
+ return data ? { ...data } : data;
13705
+ }
13706
+ function getCachedIpapiResult(lookupIp) {
13707
+ const cached = ipapiCache.get(lookupIp);
13708
+ if (!cached) return null;
13709
+ if (cached.expiresAt <= Date.now()) {
13710
+ ipapiCache.delete(lookupIp);
13711
+ return null;
13712
+ }
13713
+ return cloneGeoData(cached.data);
13714
+ }
13715
+ function cacheIpapiResult(lookupIp, data, ttlMs) {
13716
+ if (!lookupIp || !data || ttlMs <= 0) return;
13717
+ if (ipapiCache.size > 1e3) {
13718
+ const oldestKey = ipapiCache.keys().next().value;
13719
+ if (oldestKey) ipapiCache.delete(oldestKey);
13720
+ }
13721
+ ipapiCache.set(lookupIp, {
13722
+ data: cloneGeoData(data),
13723
+ expiresAt: Date.now() + ttlMs
13724
+ });
13725
+ }
13726
+ function getRetryAfterMs(response) {
13727
+ const retryAfter = response?.headers?.get?.("retry-after");
13728
+ if (!retryAfter) return null;
13729
+ const seconds = Number.parseInt(retryAfter, 10);
13730
+ if (Number.isFinite(seconds)) {
13731
+ return Math.max(1e3, Math.min(seconds * 1e3, 60 * 60 * 1e3));
13732
+ }
13733
+ const retryDate = Date.parse(retryAfter);
13734
+ if (Number.isFinite(retryDate)) {
13735
+ return Math.max(1e3, Math.min(retryDate - Date.now(), 60 * 60 * 1e3));
13736
+ }
13737
+ return null;
13738
+ }
13739
+ function markIpapiRateLimited(response) {
13740
+ const backoffMs = getRetryAfterMs(response) || IPAPI_RATE_LIMIT_BACKOFF_MS;
13741
+ ipapiRateLimitedUntil = Math.max(ipapiRateLimitedUntil, Date.now() + backoffMs);
13742
+ return backoffMs;
13743
+ }
13744
+ function getIpapiRateLimitRemainingMs() {
13745
+ return Math.max(0, ipapiRateLimitedUntil - Date.now());
13746
+ }
13747
+ function logIpapiRateLimit(strapi2, message) {
13748
+ const now = Date.now();
13749
+ if (now - ipapiLastRateLimitLogAt < IPAPI_RATE_LIMIT_LOG_INTERVAL_MS) return;
13750
+ ipapiLastRateLimitLogAt = now;
13751
+ strapi2.log.warn(message);
13752
+ }
13753
+ async function acquireIpapiSlot() {
13754
+ if (ipapiActiveRequests < IPAPI_MAX_CONCURRENT_REQUESTS) {
13755
+ ipapiActiveRequests++;
13756
+ return releaseIpapiSlot;
13757
+ }
13758
+ if (ipapiQueue.length >= IPAPI_MAX_QUEUE_SIZE) {
13759
+ return null;
13760
+ }
13761
+ return new Promise((resolve) => {
13762
+ ipapiQueue.push(resolve);
13763
+ });
13764
+ }
13765
+ function releaseIpapiSlot() {
13766
+ ipapiActiveRequests = Math.max(0, ipapiActiveRequests - 1);
13767
+ const next = ipapiQueue.shift();
13768
+ if (next) {
13769
+ ipapiActiveRequests++;
13770
+ next(releaseIpapiSlot);
13771
+ }
13772
+ }
13773
+ function getName(names = {}, fallback = "") {
13774
+ return names.en || names.de || names.fr || names.es || names.pt || fallback;
13775
+ }
13776
+ function getReaderDatabaseType(reader, databasePath) {
13777
+ const metadataType = reader?.metadata?.databaseType || reader?.metadata?.database_type || reader?.metadata?.database_type_name;
13778
+ if (typeof metadataType === "string" && metadataType.trim()) {
13779
+ return metadataType;
13780
+ }
13781
+ return path.basename(databasePath || "");
13782
+ }
13783
+ function isCityDatabase(reader, databasePath) {
13784
+ return /(?:^|[-_])City(?:\.|[-_]|$)/i.test(getReaderDatabaseType(reader, databasePath));
13785
+ }
13786
+ function normalizeLocalCountryResult(data, lookupIp, getCountryFlag) {
13787
+ const country = data.country || data.registeredCountry || data.representedCountry || {};
13788
+ const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
13789
+ return {
13790
+ ip: lookupIp,
13791
+ country: getName(country.names, countryCode || "Unknown"),
13792
+ country_code: countryCode,
13793
+ country_flag: getCountryFlag(countryCode),
13794
+ city: "Unknown",
13795
+ region: "Unknown",
13796
+ timezone: "Unknown",
13797
+ latitude: null,
13798
+ longitude: null,
13799
+ postal: null,
13800
+ org: null,
13801
+ asn: null,
13802
+ network: data.traits?.network || null,
13803
+ isVpn: false,
13804
+ isProxy: false,
13805
+ isThreat: false,
13806
+ isAnonymous: false,
13807
+ isTor: false,
13808
+ securityScore: 100,
13809
+ riskLevel: "Low",
13810
+ _status: "ok",
13811
+ _source: "local-mmdb",
13812
+ _databaseType: "country"
13813
+ };
13814
+ }
13815
+ function normalizeLocalCityResult(data, lookupIp, getCountryFlag) {
13816
+ const country = data.country || data.registeredCountry || data.representedCountry || {};
13817
+ const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
13818
+ const region = Array.isArray(data.subdivisions) && data.subdivisions.length > 0 ? data.subdivisions[0] : null;
13819
+ return {
13820
+ ip: lookupIp,
13821
+ country: getName(country.names, countryCode || "Unknown"),
13822
+ country_code: countryCode,
13823
+ country_flag: getCountryFlag(countryCode),
13824
+ city: getName(data.city?.names, "Unknown"),
13825
+ region: getName(region?.names, region?.isoCode || "Unknown"),
13826
+ timezone: data.location?.timeZone || "Unknown",
13827
+ latitude: data.location?.latitude ?? null,
13828
+ longitude: data.location?.longitude ?? null,
13829
+ accuracyRadius: data.location?.accuracyRadius ?? null,
13830
+ postal: data.postal?.code || null,
13831
+ org: null,
13832
+ asn: null,
13833
+ network: data.traits?.network || null,
13834
+ isVpn: false,
13835
+ isProxy: false,
13836
+ isThreat: false,
13837
+ isAnonymous: false,
13838
+ isTor: false,
13839
+ securityScore: 100,
13840
+ riskLevel: "Low",
13841
+ _status: "ok",
13842
+ _source: "local-mmdb",
13843
+ _databaseType: "city"
13844
+ };
13845
+ }
13846
+ function normalizeLookupIp(ipAddress) {
13847
+ if (typeof ipAddress !== "string") return "";
13848
+ let normalized = ipAddress.trim();
13849
+ if (!normalized) return "";
13850
+ if (normalized.startsWith("[") && normalized.endsWith("]")) {
13851
+ normalized = normalized.slice(1, -1).trim();
13852
+ }
13853
+ const ipv4Mapped = normalized.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
13854
+ if (ipv4Mapped && net.isIP(ipv4Mapped[1]) === 4) {
13855
+ return ipv4Mapped[1];
13856
+ }
13857
+ return normalized;
13858
+ }
13859
+ function parseIpv4(ip) {
13860
+ if (net.isIP(ip) !== 4) return null;
13861
+ const parts = ip.split(".").map((part) => Number(part));
13862
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
13863
+ return null;
13864
+ }
13865
+ return parts;
13866
+ }
13867
+ function isPrivateIpv4(ip) {
13868
+ const parts = parseIpv4(ip);
13869
+ if (!parts) return false;
13870
+ const [a, b, c] = parts;
13871
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
13872
+ }
13873
+ function getFirstHextet(ip) {
13874
+ const first = ip.split(":")[0];
13875
+ if (!first) return 0;
13876
+ const parsed = Number.parseInt(first, 16);
13877
+ return Number.isNaN(parsed) ? 0 : parsed;
13878
+ }
13879
+ function isPrivateIpv6(ip) {
13880
+ const lower = ip.toLowerCase();
13881
+ if (lower === "::" || lower === "::1") return true;
13882
+ if (/^(?:0:){7}0$/.test(lower) || /^(?:0:){7}1$/.test(lower)) return true;
13883
+ if (lower.startsWith("::ffff:")) {
13884
+ return isPrivateIpv4(normalizeLookupIp(lower));
13885
+ }
13886
+ const firstHextet = getFirstHextet(lower);
13887
+ return (firstHextet & 65024) === 64512 || (firstHextet & 65472) === 65152;
13888
+ }
13637
13889
  module.exports = ({ strapi: strapi2 }) => ({
13638
13890
  /**
13639
13891
  * Looks up geolocation data for an IP address.
@@ -13653,9 +13905,10 @@ var require_geolocation = __commonJS({
13653
13905
  * @returns {Promise<object>}
13654
13906
  */
13655
13907
  async getIpInfo(ipAddress) {
13656
- if (!ipAddress || this.isPrivateIp(ipAddress)) {
13908
+ const lookupIp = normalizeLookupIp(ipAddress);
13909
+ if (!lookupIp || this.isPrivateIp(lookupIp)) {
13657
13910
  return {
13658
- ip: ipAddress,
13911
+ ip: lookupIp || ipAddress,
13659
13912
  country: "Local Network",
13660
13913
  country_code: "XX",
13661
13914
  country_flag: "",
@@ -13673,25 +13926,28 @@ var require_geolocation = __commonJS({
13673
13926
  _source: "local"
13674
13927
  };
13675
13928
  }
13929
+ if (net.isIP(lookupIp) === 0) {
13930
+ return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
13931
+ }
13676
13932
  const settings = await this.getGeoSettings();
13677
13933
  const provider = normalizeProvider(settings.geoIpProvider);
13678
13934
  if (provider === "disabled") {
13679
- return this.getFallbackData(ipAddress, "disabled", "disabled");
13935
+ return this.getFallbackData(lookupIp, "disabled", "disabled");
13680
13936
  }
13681
13937
  if (provider === "local-mmdb") {
13682
- return this.getLocalMmdbIpInfo(ipAddress, settings);
13938
+ return this.getLocalMmdbIpInfo(lookupIp, settings);
13683
13939
  }
13684
13940
  if (provider === "auto") {
13685
- const databasePath = resolveDatabasePath(settings);
13941
+ const databasePath = resolveExistingDatabasePath(settings);
13686
13942
  if (databasePath && fs.existsSync(databasePath)) {
13687
- const localResult = await this.getLocalMmdbIpInfo(ipAddress, settings);
13688
- if (localResult?._status === "ok") {
13943
+ const localResult = await this.getLocalMmdbIpInfo(lookupIp, settings);
13944
+ if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
13689
13945
  return localResult;
13690
13946
  }
13691
13947
  strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed (${localResult?._reason || localResult?._status}), falling back to ipapi.co`);
13692
13948
  }
13693
13949
  }
13694
- return this.getIpapiIpInfo(ipAddress);
13950
+ return this.getIpapiIpInfo(lookupIp);
13695
13951
  },
13696
13952
  /**
13697
13953
  * Reads effective GEOIP provider settings.
@@ -13705,13 +13961,19 @@ var require_geolocation = __commonJS({
13705
13961
  }
13706
13962
  },
13707
13963
  /**
13708
- * Looks up country data from a local MaxMind-compatible MMDB file.
13964
+ * Looks up geolocation data from a local MaxMind-compatible MMDB file.
13965
+ * GeoLite2-City is preferred for city-level data; GeoLite2-Country remains
13966
+ * supported for existing installations and country-only firewall decisions.
13709
13967
  * @param {string} ipAddress
13710
13968
  * @param {object} settings
13711
13969
  * @returns {Promise<object>}
13712
13970
  */
13713
13971
  async getLocalMmdbIpInfo(ipAddress, settings = {}) {
13714
- const databasePath = resolveDatabasePath(settings);
13972
+ const lookupIp = normalizeLookupIp(ipAddress);
13973
+ if (!lookupIp || net.isIP(lookupIp) === 0) {
13974
+ return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
13975
+ }
13976
+ const databasePath = resolveExistingDatabasePath(settings);
13715
13977
  if (!databasePath || !fs.existsSync(databasePath)) {
13716
13978
  return this.getFallbackData(
13717
13979
  ipAddress,
@@ -13722,39 +13984,16 @@ var require_geolocation = __commonJS({
13722
13984
  }
13723
13985
  try {
13724
13986
  const reader = await openLocalReader(databasePath);
13725
- const data = reader.country(ipAddress);
13726
- const country = data.country || data.registeredCountry || data.representedCountry || {};
13727
- const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
13728
- const countryNames = country.names || {};
13729
- const result = {
13730
- ip: ipAddress,
13731
- country: countryNames.en || countryNames.de || countryCode || "Unknown",
13732
- country_code: countryCode,
13733
- country_flag: this.getCountryFlag(countryCode),
13734
- city: "Unknown",
13735
- region: "Unknown",
13736
- timezone: "Unknown",
13737
- latitude: null,
13738
- longitude: null,
13739
- postal: null,
13740
- org: null,
13741
- asn: null,
13742
- network: data.traits?.network || null,
13743
- isVpn: false,
13744
- isProxy: false,
13745
- isThreat: false,
13746
- isAnonymous: false,
13747
- isTor: false,
13748
- securityScore: 100,
13749
- riskLevel: "Low",
13750
- _status: "ok",
13751
- _source: "local-mmdb"
13752
- };
13753
- strapi2.log.debug(`[magic-sessionmanager/geolocation] Local MMDB IP ${ipAddress}: ${result.country_code}`);
13987
+ const useCityLookup = isCityDatabase(reader, databasePath) && typeof reader.city === "function";
13988
+ const data = useCityLookup ? reader.city(lookupIp) : reader.country(lookupIp);
13989
+ const result = useCityLookup ? normalizeLocalCityResult(data, lookupIp, this.getCountryFlag.bind(this)) : normalizeLocalCountryResult(data, lookupIp, this.getCountryFlag.bind(this));
13990
+ strapi2.log.debug(
13991
+ `[magic-sessionmanager/geolocation] Local MMDB ${result._databaseType} IP ${lookupIp}: ${result.city}, ${result.country_code}`
13992
+ );
13754
13993
  return result;
13755
13994
  } catch (error) {
13756
- strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed for ${ipAddress}:`, error.message);
13757
- return this.getFallbackData(ipAddress, "error", "local-mmdb", error.message);
13995
+ strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed for ${lookupIp}:`, error.message);
13996
+ return this.getFallbackData(lookupIp, "error", "local-mmdb", error.message);
13758
13997
  }
13759
13998
  },
13760
13999
  /**
@@ -13763,65 +14002,135 @@ var require_geolocation = __commonJS({
13763
14002
  * @returns {Promise<object>}
13764
14003
  */
13765
14004
  async getIpapiIpInfo(ipAddress) {
13766
- const controller = new AbortController();
13767
- const timer = setTimeout(() => controller.abort(), GEO_API_TIMEOUT_MS);
14005
+ const lookupIp = normalizeLookupIp(ipAddress);
14006
+ if (!lookupIp || net.isIP(lookupIp) === 0) {
14007
+ return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
14008
+ }
14009
+ const cached = getCachedIpapiResult(lookupIp);
14010
+ if (cached) return cached;
14011
+ const rateLimitRemainingMs = getIpapiRateLimitRemainingMs();
14012
+ if (rateLimitRemainingMs > 0) {
14013
+ logIpapiRateLimit(
14014
+ strapi2,
14015
+ `[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(rateLimitRemainingMs / 1e3)}s`
14016
+ );
14017
+ return this.getFallbackData(lookupIp, "rate_limited", "ipapi", "Remote GeoIP provider is backing off after HTTP 429");
14018
+ }
14019
+ if (ipapiInFlight.has(lookupIp)) {
14020
+ return cloneGeoData(await ipapiInFlight.get(lookupIp));
14021
+ }
14022
+ const lookupPromise = (async () => {
14023
+ const releaseSlot = await acquireIpapiSlot();
14024
+ if (!releaseSlot) {
14025
+ const fallback = this.getFallbackData(
14026
+ lookupIp,
14027
+ "rate_limited",
14028
+ "ipapi",
14029
+ "Remote GeoIP provider concurrency limit reached"
14030
+ );
14031
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14032
+ return fallback;
14033
+ }
14034
+ const queuedRateLimitRemainingMs = getIpapiRateLimitRemainingMs();
14035
+ if (queuedRateLimitRemainingMs > 0) {
14036
+ releaseSlot();
14037
+ logIpapiRateLimit(
14038
+ strapi2,
14039
+ `[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(queuedRateLimitRemainingMs / 1e3)}s`
14040
+ );
14041
+ return this.getFallbackData(lookupIp, "rate_limited", "ipapi", "Remote GeoIP provider is backing off after HTTP 429");
14042
+ }
14043
+ const controller = new AbortController();
14044
+ const timer = setTimeout(() => controller.abort(), GEO_API_TIMEOUT_MS);
14045
+ try {
14046
+ const response = await fetch(`https://ipapi.co/${encodeURIComponent(lookupIp)}/json/`, {
14047
+ method: "GET",
14048
+ headers: { "User-Agent": "Strapi-Magic-SessionManager/1.0" },
14049
+ signal: controller.signal
14050
+ });
14051
+ if (!response.ok) {
14052
+ const reason = response.status === 429 ? "rate_limited" : "error";
14053
+ if (response.status === 429) {
14054
+ const backoffMs = markIpapiRateLimited(response);
14055
+ logIpapiRateLimit(
14056
+ strapi2,
14057
+ `[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
14058
+ );
14059
+ } else {
14060
+ strapi2.log.warn(`[magic-sessionmanager/geolocation] API returned HTTP ${response.status}`);
14061
+ }
14062
+ const fallback = this.getFallbackData(lookupIp, reason, "ipapi", `HTTP ${response.status}`);
14063
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14064
+ return fallback;
14065
+ }
14066
+ const data = await response.json();
14067
+ if (data.error) {
14068
+ const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
14069
+ if (reason === "rate_limited") {
14070
+ const backoffMs = markIpapiRateLimited();
14071
+ logIpapiRateLimit(
14072
+ strapi2,
14073
+ `[magic-sessionmanager/geolocation] API reported rate limit; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
14074
+ );
14075
+ } else {
14076
+ strapi2.log.warn(`[magic-sessionmanager/geolocation] API Error: ${data.reason}`);
14077
+ }
14078
+ const fallback = this.getFallbackData(lookupIp, reason, "ipapi", data.reason);
14079
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14080
+ return fallback;
14081
+ }
14082
+ const result = {
14083
+ ip: data.ip,
14084
+ country: data.country_name,
14085
+ country_code: data.country_code,
14086
+ country_flag: this.getCountryFlag(data.country_code),
14087
+ city: data.city,
14088
+ region: data.region,
14089
+ timezone: data.timezone,
14090
+ latitude: data.latitude,
14091
+ longitude: data.longitude,
14092
+ postal: data.postal,
14093
+ org: data.org,
14094
+ asn: data.asn,
14095
+ isVpn: data.threat?.is_vpn || false,
14096
+ isProxy: data.threat?.is_proxy || false,
14097
+ isThreat: data.threat?.is_threat || false,
14098
+ isAnonymous: data.threat?.is_anonymous || false,
14099
+ isTor: data.threat?.is_tor || false,
14100
+ securityScore: this.calculateSecurityScore({
14101
+ isVpn: data.threat?.is_vpn,
14102
+ isProxy: data.threat?.is_proxy,
14103
+ isThreat: data.threat?.is_threat,
14104
+ isAnonymous: data.threat?.is_anonymous,
14105
+ isTor: data.threat?.is_tor
14106
+ }),
14107
+ riskLevel: this.getRiskLevel({
14108
+ isVpn: data.threat?.is_vpn,
14109
+ isProxy: data.threat?.is_proxy,
14110
+ isThreat: data.threat?.is_threat
14111
+ }),
14112
+ _status: "ok",
14113
+ _source: "ipapi"
14114
+ };
14115
+ strapi2.log.debug(`[magic-sessionmanager/geolocation] IP ${ipAddress}: ${result.city}, ${result.country} (Score: ${result.securityScore})`);
14116
+ cacheIpapiResult(lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
14117
+ return result;
14118
+ } catch (error) {
14119
+ const status = error?.name === "AbortError" ? "error" : "error";
14120
+ strapi2.log.error(`[magic-sessionmanager/geolocation] Error fetching IP info for ${lookupIp}:`, error.message);
14121
+ const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
14122
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14123
+ return fallback;
14124
+ } finally {
14125
+ clearTimeout(timer);
14126
+ releaseSlot();
14127
+ }
14128
+ })();
14129
+ ipapiInFlight.set(lookupIp, lookupPromise);
13768
14130
  try {
13769
- const response = await fetch(`https://ipapi.co/${encodeURIComponent(ipAddress)}/json/`, {
13770
- method: "GET",
13771
- headers: { "User-Agent": "Strapi-Magic-SessionManager/1.0" },
13772
- signal: controller.signal
13773
- });
13774
- if (!response.ok) {
13775
- strapi2.log.warn(`[magic-sessionmanager/geolocation] API returned HTTP ${response.status}`);
13776
- return this.getFallbackData(ipAddress, response.status === 429 ? "rate_limited" : "error", "ipapi");
13777
- }
13778
- const data = await response.json();
13779
- if (data.error) {
13780
- strapi2.log.warn(`[magic-sessionmanager/geolocation] API Error: ${data.reason}`);
13781
- const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
13782
- return this.getFallbackData(ipAddress, reason, "ipapi", data.reason);
13783
- }
13784
- const result = {
13785
- ip: data.ip,
13786
- country: data.country_name,
13787
- country_code: data.country_code,
13788
- country_flag: this.getCountryFlag(data.country_code),
13789
- city: data.city,
13790
- region: data.region,
13791
- timezone: data.timezone,
13792
- latitude: data.latitude,
13793
- longitude: data.longitude,
13794
- postal: data.postal,
13795
- org: data.org,
13796
- asn: data.asn,
13797
- isVpn: data.threat?.is_vpn || false,
13798
- isProxy: data.threat?.is_proxy || false,
13799
- isThreat: data.threat?.is_threat || false,
13800
- isAnonymous: data.threat?.is_anonymous || false,
13801
- isTor: data.threat?.is_tor || false,
13802
- securityScore: this.calculateSecurityScore({
13803
- isVpn: data.threat?.is_vpn,
13804
- isProxy: data.threat?.is_proxy,
13805
- isThreat: data.threat?.is_threat,
13806
- isAnonymous: data.threat?.is_anonymous,
13807
- isTor: data.threat?.is_tor
13808
- }),
13809
- riskLevel: this.getRiskLevel({
13810
- isVpn: data.threat?.is_vpn,
13811
- isProxy: data.threat?.is_proxy,
13812
- isThreat: data.threat?.is_threat
13813
- }),
13814
- _status: "ok",
13815
- _source: "ipapi"
13816
- };
13817
- strapi2.log.debug(`[magic-sessionmanager/geolocation] IP ${ipAddress}: ${result.city}, ${result.country} (Score: ${result.securityScore})`);
13818
- return result;
13819
- } catch (error) {
13820
- const status = error?.name === "AbortError" ? "error" : "error";
13821
- strapi2.log.error(`[magic-sessionmanager/geolocation] Error fetching IP info for ${ipAddress}:`, error.message);
13822
- return this.getFallbackData(ipAddress, status, "ipapi", error.message);
14131
+ return cloneGeoData(await lookupPromise);
13823
14132
  } finally {
13824
- clearTimeout(timer);
14133
+ ipapiInFlight.delete(lookupIp);
13825
14134
  }
13826
14135
  },
13827
14136
  /**
@@ -13868,17 +14177,12 @@ var require_geolocation = __commonJS({
13868
14177
  * @returns {boolean}
13869
14178
  */
13870
14179
  isPrivateIp(ip) {
13871
- if (!ip || ip === "unknown") return true;
13872
- if (ip === "127.0.0.1" || ip === "localhost" || ip === "::1") return true;
13873
- if (ip.startsWith("192.168.")) return true;
13874
- if (ip.startsWith("10.")) return true;
13875
- if (ip.startsWith("172.")) {
13876
- const second = parseInt(ip.split(".")[1], 10);
13877
- if (second >= 16 && second <= 31) return true;
13878
- }
13879
- if (ip.startsWith("169.254.")) return true;
13880
- if (ip.startsWith("fc00:") || ip.startsWith("fd00:")) return true;
13881
- if (ip.startsWith("fe80:")) return true;
14180
+ const normalized = normalizeLookupIp(ip);
14181
+ const lower = normalized.toLowerCase();
14182
+ if (!normalized || lower === "unknown" || lower === "localhost") return true;
14183
+ const version = net.isIP(normalized);
14184
+ if (version === 4) return isPrivateIpv4(normalized);
14185
+ if (version === 6) return isPrivateIpv6(normalized);
13882
14186
  return false;
13883
14187
  },
13884
14188
  /**