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
@@ -9810,6 +9810,18 @@ var require_bootstrap = __commonJS({
9810
9810
  if (path.startsWith("/api/magic-link/login") && (method === "GET" || method === "POST")) return true;
9811
9811
  return false;
9812
9812
  }
9813
+ async function getRequestSettings(strapi2, ctx) {
9814
+ let settings = {};
9815
+ try {
9816
+ settings = await getPluginSettings(strapi2);
9817
+ } catch {
9818
+ settings = {};
9819
+ }
9820
+ if (ctx && ctx.state) {
9821
+ ctx.state.__magicSessionSettings = settings;
9822
+ }
9823
+ return settings;
9824
+ }
9813
9825
  module2.exports = async ({ strapi: strapi2 }) => {
9814
9826
  const log = createLogger(strapi2);
9815
9827
  log.info("[START] Bootstrap starting...");
@@ -9907,12 +9919,7 @@ var require_bootstrap = __commonJS({
9907
9919
  if (!isLoginPath(ctx.path, ctx.method)) {
9908
9920
  return next();
9909
9921
  }
9910
- let settings = {};
9911
- try {
9912
- settings = await getPluginSettings(strapi2);
9913
- } catch {
9914
- settings = {};
9915
- }
9922
+ const settings = await getRequestSettings(strapi2, ctx);
9916
9923
  const needsGeoCheck = settings.blockSuspiciousSessions || settings.enableGeofencing || settings.enableGeolocation;
9917
9924
  if (!needsGeoCheck) {
9918
9925
  return next();
@@ -10050,13 +10057,8 @@ var require_bootstrap = __commonJS({
10050
10057
  const clearFailures = (ip) => failed.delete(ip);
10051
10058
  strapi2.server.use(async (ctx, next) => {
10052
10059
  if (!isLoginPath(ctx.path, ctx.method)) return next();
10053
- let maxFailed = 0;
10054
- try {
10055
- const settings = await getPluginSettings(strapi2);
10056
- maxFailed = Number(settings.maxFailedLogins) || 0;
10057
- } catch {
10058
- maxFailed = 0;
10059
- }
10060
+ const settings = await getRequestSettings(strapi2, ctx);
10061
+ const maxFailed = Number(settings.maxFailedLogins) || 0;
10060
10062
  if (maxFailed <= 0) return next();
10061
10063
  const ip = getClientIp(ctx);
10062
10064
  if (!ip || ip === "unknown") return next();
@@ -10115,6 +10117,7 @@ var require_bootstrap = __commonJS({
10115
10117
  if (!ctx.body || !ctx.body.jwt || !ctx.body.user) return;
10116
10118
  try {
10117
10119
  const user = ctx.body.user;
10120
+ await getRequestSettings(strapi2, ctx);
10118
10121
  const ip = getClientIp(ctx);
10119
10122
  const headers = ctx.request.headers || ctx.request.header || {};
10120
10123
  const userAgent = headers["user-agent"] || "unknown";
@@ -12373,9 +12376,29 @@ var require_geoip_updater = __commonJS({
12373
12376
  var zlib = require("node:zlib");
12374
12377
  var { promisify } = require("node:util");
12375
12378
  var gunzip = promisify(zlib.gunzip);
12376
- var DEFAULT_EDITION_ID = "GeoLite2-Country";
12377
- var DEFAULT_MMDB_NAME = "GeoLite2-Country.mmdb";
12379
+ var DEFAULT_EDITION_ID = "GeoLite2-City";
12380
+ var DEFAULT_MMDB_NAME = `${DEFAULT_EDITION_ID}.mmdb`;
12378
12381
  var DEFAULT_OUTPUT_PATH = path.resolve(process2.cwd(), "data", DEFAULT_MMDB_NAME);
12382
+ var SUPPORTED_EDITION_IDS = /* @__PURE__ */ new Set([
12383
+ "GeoLite2-City",
12384
+ "GeoLite2-Country",
12385
+ "GeoIP2-City",
12386
+ "GeoIP2-Country"
12387
+ ]);
12388
+ function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
12389
+ return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
12390
+ }
12391
+ function inferEditionIdFromPath(filePath) {
12392
+ if (typeof filePath !== "string" || filePath.trim() === "") return "";
12393
+ const basename = path.basename(filePath.trim());
12394
+ if (/GeoIP2-City\.mmdb$/i.test(basename)) return "GeoIP2-City";
12395
+ if (/GeoIP2-Country\.mmdb$/i.test(basename)) return "GeoIP2-Country";
12396
+ if (/GeoLite2-City\.mmdb$/i.test(basename)) return "GeoLite2-City";
12397
+ if (/GeoLite2-Country\.mmdb$/i.test(basename)) return "GeoLite2-Country";
12398
+ if (/city/i.test(basename)) return "GeoLite2-City";
12399
+ if (/country/i.test(basename)) return "GeoLite2-Country";
12400
+ return "";
12401
+ }
12379
12402
  function buildDownloadUrl(editionId = DEFAULT_EDITION_ID) {
12380
12403
  return `https://download.maxmind.com/geoip/databases/${encodeURIComponent(editionId)}/download?suffix=tar.gz`;
12381
12404
  }
@@ -12384,8 +12407,11 @@ var require_geoip_updater = __commonJS({
12384
12407
  }
12385
12408
  function resolveConfig(env = process2.env, argv = process2.argv.slice(2), overrides = {}) {
12386
12409
  const force = argv.includes("--force") || overrides.force === true;
12387
- const editionId = overrides.editionId || env.MAXMIND_EDITION_ID || DEFAULT_EDITION_ID;
12388
- const outputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || DEFAULT_OUTPUT_PATH;
12410
+ const configuredOutputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || "";
12411
+ const editionId = normalizeEditionId(
12412
+ overrides.editionId || env.MAXMIND_EDITION_ID || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
12413
+ );
12414
+ const outputPath = configuredOutputPath || path.resolve(process2.cwd(), "data", `${editionId}.mmdb`);
12389
12415
  return {
12390
12416
  accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || "",
12391
12417
  licenseKey: overrides.licenseKey || env.MAXMIND_LICENSE_KEY || "",
@@ -12543,6 +12569,7 @@ var require_geoip_updater = __commonJS({
12543
12569
  buildDownloadUrl,
12544
12570
  extractMmdbFromTarGz,
12545
12571
  fileExists,
12572
+ inferEditionIdFromPath,
12546
12573
  needsDownload,
12547
12574
  readMetadata,
12548
12575
  resolveConfig,
@@ -12555,6 +12582,7 @@ var require_geoip_updater = __commonJS({
12555
12582
  var require_geoip = __commonJS({
12556
12583
  "server/src/controllers/geoip.js"(exports2, module2) {
12557
12584
  "use strict";
12585
+ var fs = require("node:fs");
12558
12586
  var path = require("node:path");
12559
12587
  var {
12560
12588
  fileExists,
@@ -12568,6 +12596,8 @@ var require_geoip = __commonJS({
12568
12596
  normalizeGeoIpDatabasePath
12569
12597
  } = require_settings_loader();
12570
12598
  var CREDENTIALS_KEY = "geoipCredentials";
12599
+ var DEFAULT_CITY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
12600
+ var DEFAULT_COUNTRY_DATABASE_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
12571
12601
  function getGeoIpStore(strapi2) {
12572
12602
  return strapi2.store({
12573
12603
  type: "plugin",
@@ -12603,10 +12633,11 @@ var require_geoip = __commonJS({
12603
12633
  }
12604
12634
  function buildUpdaterConfig(settings, storedCredentials, force = false) {
12605
12635
  const outputPath = normalizeGeoIpDatabasePath(settings.geoIpDatabasePath);
12636
+ const existingDefaultPath = !outputPath && fs.existsSync(DEFAULT_CITY_DATABASE_PATH) ? DEFAULT_CITY_DATABASE_PATH : !outputPath && fs.existsSync(DEFAULT_COUNTRY_DATABASE_PATH) ? DEFAULT_COUNTRY_DATABASE_PATH : "";
12606
12637
  return resolveConfig(process.env, force ? ["--force"] : [], {
12607
12638
  accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
12608
12639
  licenseKey: process.env.MAXMIND_LICENSE_KEY || storedCredentials.licenseKey || "",
12609
- outputPath: outputPath || void 0,
12640
+ outputPath: outputPath || existingDefaultPath || void 0,
12610
12641
  force
12611
12642
  });
12612
12643
  }
@@ -12630,6 +12661,7 @@ var require_geoip = __commonJS({
12630
12661
  success: true,
12631
12662
  status: {
12632
12663
  provider: settings.geoIpProvider || "auto",
12664
+ editionId: config2.editionId,
12633
12665
  databasePath: config2.outputPath,
12634
12666
  databaseDirectory: path.dirname(config2.outputPath),
12635
12667
  exists,
@@ -13260,7 +13292,7 @@ var require_session2 = __commonJS({
13260
13292
  var require_package = __commonJS({
13261
13293
  "package.json"(exports2, module2) {
13262
13294
  module2.exports = {
13263
- version: "4.6.3",
13295
+ version: "4.7.0",
13264
13296
  keywords: [
13265
13297
  "strapi",
13266
13298
  "plugin",
@@ -13324,21 +13356,21 @@ var require_package = __commonJS({
13324
13356
  "@semantic-release/changelog": "^6.0.3",
13325
13357
  "@semantic-release/commit-analyzer": "^13.0.0",
13326
13358
  "@semantic-release/git": "^10.0.1",
13327
- "@semantic-release/github": "^12.0.8",
13359
+ "@semantic-release/github": "^12.0.9",
13328
13360
  "@semantic-release/npm": "^13.1.5",
13329
13361
  "@semantic-release/release-notes-generator": "^14.1.1",
13330
- "@strapi/design-system": "^2.2.0",
13331
- "@strapi/icons": "^2.2.0",
13362
+ "@strapi/design-system": "^2.2.2",
13363
+ "@strapi/icons": "^2.2.2",
13332
13364
  "@strapi/sdk-plugin": "^6.1.1",
13333
- "@strapi/strapi": "^5.48.1",
13365
+ "@strapi/strapi": "^5.50.1",
13334
13366
  esbuild: "^0.28.1",
13335
- prettier: "^3.8.4",
13367
+ prettier: "^3.9.5",
13336
13368
  react: "^18.3.1",
13337
13369
  "react-dom": "^18.3.1",
13338
13370
  "react-intl": "^7.1.14",
13339
13371
  "react-router-dom": "^6.30.4",
13340
13372
  "semantic-release": "^25.0.5",
13341
- "styled-components": "^6.4.2"
13373
+ "styled-components": "^6.4.3"
13342
13374
  },
13343
13375
  peerDependencies: {
13344
13376
  "@strapi/design-system": "^2.0.0",
@@ -13599,21 +13631,55 @@ var require_geolocation = __commonJS({
13599
13631
  "server/src/services/geolocation.js"(exports2, module2) {
13600
13632
  "use strict";
13601
13633
  var fs = require("node:fs");
13634
+ var net = require("node:net");
13602
13635
  var path = require("node:path");
13603
13636
  var { getPluginSettings } = require_settings_loader();
13604
13637
  var GEO_API_TIMEOUT_MS = 4e3;
13605
- var DEFAULT_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
13638
+ var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
13639
+ var IPAPI_FAILURE_CACHE_TTL_MS = 5 * 60 * 1e3;
13640
+ var IPAPI_RATE_LIMIT_BACKOFF_MS = 15 * 60 * 1e3;
13641
+ var IPAPI_RATE_LIMIT_LOG_INTERVAL_MS = 60 * 1e3;
13642
+ var IPAPI_MAX_CONCURRENT_REQUESTS = 4;
13643
+ var IPAPI_MAX_QUEUE_SIZE = 50;
13644
+ var DEFAULT_CITY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-City.mmdb");
13645
+ var DEFAULT_COUNTRY_MMDB_PATH = path.resolve(process.cwd(), "data", "GeoLite2-Country.mmdb");
13606
13646
  var VALID_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
13607
13647
  var readerCache = /* @__PURE__ */ new Map();
13648
+ var ipapiCache = /* @__PURE__ */ new Map();
13649
+ var ipapiInFlight = /* @__PURE__ */ new Map();
13650
+ var ipapiQueue = [];
13651
+ var ipapiActiveRequests = 0;
13652
+ var ipapiRateLimitedUntil = 0;
13653
+ var ipapiLastRateLimitLogAt = 0;
13608
13654
  function normalizeProvider(value) {
13609
13655
  return VALID_PROVIDERS.has(value) ? value : "auto";
13610
13656
  }
13611
- function resolveDatabasePath(settings = {}) {
13612
- const configured = settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOLITE2_COUNTRY_MMDB || DEFAULT_MMDB_PATH;
13613
- if (typeof configured !== "string" || configured.trim() === "") return "";
13614
- const trimmed = configured.trim();
13657
+ function normalizeDatabasePath(value) {
13658
+ if (typeof value !== "string" || value.trim() === "") return "";
13659
+ const trimmed = value.trim();
13615
13660
  return path.isAbsolute(trimmed) ? trimmed : path.resolve(process.cwd(), trimmed);
13616
13661
  }
13662
+ function uniqueValues(values) {
13663
+ return [...new Set(values.filter(Boolean))];
13664
+ }
13665
+ function resolveDatabaseCandidates(settings = {}) {
13666
+ const configured = normalizeDatabasePath(
13667
+ settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOIP_DATABASE_PATH
13668
+ );
13669
+ if (configured) return [configured];
13670
+ return uniqueValues([
13671
+ normalizeDatabasePath(process.env.GEOLITE2_CITY_MMDB),
13672
+ normalizeDatabasePath(process.env.GEOIP_CITY_DATABASE_PATH),
13673
+ normalizeDatabasePath(process.env.GEOLITE2_COUNTRY_MMDB),
13674
+ normalizeDatabasePath(process.env.GEOIP_COUNTRY_DATABASE_PATH),
13675
+ DEFAULT_CITY_MMDB_PATH,
13676
+ DEFAULT_COUNTRY_MMDB_PATH
13677
+ ]);
13678
+ }
13679
+ function resolveExistingDatabasePath(settings = {}) {
13680
+ const candidates = resolveDatabaseCandidates(settings);
13681
+ return candidates.find((candidate) => fs.existsSync(candidate)) || candidates[0] || "";
13682
+ }
13617
13683
  async function openLocalReader(databasePath) {
13618
13684
  if (readerCache.has(databasePath)) {
13619
13685
  return readerCache.get(databasePath);
@@ -13628,6 +13694,192 @@ var require_geolocation = __commonJS({
13628
13694
  throw err;
13629
13695
  }
13630
13696
  }
13697
+ function cloneGeoData(data) {
13698
+ return data ? { ...data } : data;
13699
+ }
13700
+ function getCachedIpapiResult(lookupIp) {
13701
+ const cached = ipapiCache.get(lookupIp);
13702
+ if (!cached) return null;
13703
+ if (cached.expiresAt <= Date.now()) {
13704
+ ipapiCache.delete(lookupIp);
13705
+ return null;
13706
+ }
13707
+ return cloneGeoData(cached.data);
13708
+ }
13709
+ function cacheIpapiResult(lookupIp, data, ttlMs) {
13710
+ if (!lookupIp || !data || ttlMs <= 0) return;
13711
+ if (ipapiCache.size > 1e3) {
13712
+ const oldestKey = ipapiCache.keys().next().value;
13713
+ if (oldestKey) ipapiCache.delete(oldestKey);
13714
+ }
13715
+ ipapiCache.set(lookupIp, {
13716
+ data: cloneGeoData(data),
13717
+ expiresAt: Date.now() + ttlMs
13718
+ });
13719
+ }
13720
+ function getRetryAfterMs(response) {
13721
+ const retryAfter = response?.headers?.get?.("retry-after");
13722
+ if (!retryAfter) return null;
13723
+ const seconds = Number.parseInt(retryAfter, 10);
13724
+ if (Number.isFinite(seconds)) {
13725
+ return Math.max(1e3, Math.min(seconds * 1e3, 60 * 60 * 1e3));
13726
+ }
13727
+ const retryDate = Date.parse(retryAfter);
13728
+ if (Number.isFinite(retryDate)) {
13729
+ return Math.max(1e3, Math.min(retryDate - Date.now(), 60 * 60 * 1e3));
13730
+ }
13731
+ return null;
13732
+ }
13733
+ function markIpapiRateLimited(response) {
13734
+ const backoffMs = getRetryAfterMs(response) || IPAPI_RATE_LIMIT_BACKOFF_MS;
13735
+ ipapiRateLimitedUntil = Math.max(ipapiRateLimitedUntil, Date.now() + backoffMs);
13736
+ return backoffMs;
13737
+ }
13738
+ function getIpapiRateLimitRemainingMs() {
13739
+ return Math.max(0, ipapiRateLimitedUntil - Date.now());
13740
+ }
13741
+ function logIpapiRateLimit(strapi2, message) {
13742
+ const now = Date.now();
13743
+ if (now - ipapiLastRateLimitLogAt < IPAPI_RATE_LIMIT_LOG_INTERVAL_MS) return;
13744
+ ipapiLastRateLimitLogAt = now;
13745
+ strapi2.log.warn(message);
13746
+ }
13747
+ async function acquireIpapiSlot() {
13748
+ if (ipapiActiveRequests < IPAPI_MAX_CONCURRENT_REQUESTS) {
13749
+ ipapiActiveRequests++;
13750
+ return releaseIpapiSlot;
13751
+ }
13752
+ if (ipapiQueue.length >= IPAPI_MAX_QUEUE_SIZE) {
13753
+ return null;
13754
+ }
13755
+ return new Promise((resolve) => {
13756
+ ipapiQueue.push(resolve);
13757
+ });
13758
+ }
13759
+ function releaseIpapiSlot() {
13760
+ ipapiActiveRequests = Math.max(0, ipapiActiveRequests - 1);
13761
+ const next = ipapiQueue.shift();
13762
+ if (next) {
13763
+ ipapiActiveRequests++;
13764
+ next(releaseIpapiSlot);
13765
+ }
13766
+ }
13767
+ function getName(names = {}, fallback = "") {
13768
+ return names.en || names.de || names.fr || names.es || names.pt || fallback;
13769
+ }
13770
+ function getReaderDatabaseType(reader, databasePath) {
13771
+ const metadataType = reader?.metadata?.databaseType || reader?.metadata?.database_type || reader?.metadata?.database_type_name;
13772
+ if (typeof metadataType === "string" && metadataType.trim()) {
13773
+ return metadataType;
13774
+ }
13775
+ return path.basename(databasePath || "");
13776
+ }
13777
+ function isCityDatabase(reader, databasePath) {
13778
+ return /(?:^|[-_])City(?:\.|[-_]|$)/i.test(getReaderDatabaseType(reader, databasePath));
13779
+ }
13780
+ function normalizeLocalCountryResult(data, lookupIp, getCountryFlag) {
13781
+ const country = data.country || data.registeredCountry || data.representedCountry || {};
13782
+ const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
13783
+ return {
13784
+ ip: lookupIp,
13785
+ country: getName(country.names, countryCode || "Unknown"),
13786
+ country_code: countryCode,
13787
+ country_flag: getCountryFlag(countryCode),
13788
+ city: "Unknown",
13789
+ region: "Unknown",
13790
+ timezone: "Unknown",
13791
+ latitude: null,
13792
+ longitude: null,
13793
+ postal: null,
13794
+ org: null,
13795
+ asn: null,
13796
+ network: data.traits?.network || null,
13797
+ isVpn: false,
13798
+ isProxy: false,
13799
+ isThreat: false,
13800
+ isAnonymous: false,
13801
+ isTor: false,
13802
+ securityScore: 100,
13803
+ riskLevel: "Low",
13804
+ _status: "ok",
13805
+ _source: "local-mmdb",
13806
+ _databaseType: "country"
13807
+ };
13808
+ }
13809
+ function normalizeLocalCityResult(data, lookupIp, getCountryFlag) {
13810
+ const country = data.country || data.registeredCountry || data.representedCountry || {};
13811
+ const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
13812
+ const region = Array.isArray(data.subdivisions) && data.subdivisions.length > 0 ? data.subdivisions[0] : null;
13813
+ return {
13814
+ ip: lookupIp,
13815
+ country: getName(country.names, countryCode || "Unknown"),
13816
+ country_code: countryCode,
13817
+ country_flag: getCountryFlag(countryCode),
13818
+ city: getName(data.city?.names, "Unknown"),
13819
+ region: getName(region?.names, region?.isoCode || "Unknown"),
13820
+ timezone: data.location?.timeZone || "Unknown",
13821
+ latitude: data.location?.latitude ?? null,
13822
+ longitude: data.location?.longitude ?? null,
13823
+ accuracyRadius: data.location?.accuracyRadius ?? null,
13824
+ postal: data.postal?.code || null,
13825
+ org: null,
13826
+ asn: null,
13827
+ network: data.traits?.network || null,
13828
+ isVpn: false,
13829
+ isProxy: false,
13830
+ isThreat: false,
13831
+ isAnonymous: false,
13832
+ isTor: false,
13833
+ securityScore: 100,
13834
+ riskLevel: "Low",
13835
+ _status: "ok",
13836
+ _source: "local-mmdb",
13837
+ _databaseType: "city"
13838
+ };
13839
+ }
13840
+ function normalizeLookupIp(ipAddress) {
13841
+ if (typeof ipAddress !== "string") return "";
13842
+ let normalized = ipAddress.trim();
13843
+ if (!normalized) return "";
13844
+ if (normalized.startsWith("[") && normalized.endsWith("]")) {
13845
+ normalized = normalized.slice(1, -1).trim();
13846
+ }
13847
+ const ipv4Mapped = normalized.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
13848
+ if (ipv4Mapped && net.isIP(ipv4Mapped[1]) === 4) {
13849
+ return ipv4Mapped[1];
13850
+ }
13851
+ return normalized;
13852
+ }
13853
+ function parseIpv4(ip) {
13854
+ if (net.isIP(ip) !== 4) return null;
13855
+ const parts = ip.split(".").map((part) => Number(part));
13856
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
13857
+ return null;
13858
+ }
13859
+ return parts;
13860
+ }
13861
+ function isPrivateIpv4(ip) {
13862
+ const parts = parseIpv4(ip);
13863
+ if (!parts) return false;
13864
+ const [a, b, c] = parts;
13865
+ 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;
13866
+ }
13867
+ function getFirstHextet(ip) {
13868
+ const first = ip.split(":")[0];
13869
+ if (!first) return 0;
13870
+ const parsed = Number.parseInt(first, 16);
13871
+ return Number.isNaN(parsed) ? 0 : parsed;
13872
+ }
13873
+ function isPrivateIpv6(ip) {
13874
+ const lower = ip.toLowerCase();
13875
+ if (lower === "::" || lower === "::1") return true;
13876
+ if (/^(?:0:){7}0$/.test(lower) || /^(?:0:){7}1$/.test(lower)) return true;
13877
+ if (lower.startsWith("::ffff:")) {
13878
+ return isPrivateIpv4(normalizeLookupIp(lower));
13879
+ }
13880
+ const firstHextet = getFirstHextet(lower);
13881
+ return (firstHextet & 65024) === 64512 || (firstHextet & 65472) === 65152;
13882
+ }
13631
13883
  module2.exports = ({ strapi: strapi2 }) => ({
13632
13884
  /**
13633
13885
  * Looks up geolocation data for an IP address.
@@ -13647,9 +13899,10 @@ var require_geolocation = __commonJS({
13647
13899
  * @returns {Promise<object>}
13648
13900
  */
13649
13901
  async getIpInfo(ipAddress) {
13650
- if (!ipAddress || this.isPrivateIp(ipAddress)) {
13902
+ const lookupIp = normalizeLookupIp(ipAddress);
13903
+ if (!lookupIp || this.isPrivateIp(lookupIp)) {
13651
13904
  return {
13652
- ip: ipAddress,
13905
+ ip: lookupIp || ipAddress,
13653
13906
  country: "Local Network",
13654
13907
  country_code: "XX",
13655
13908
  country_flag: "",
@@ -13667,25 +13920,28 @@ var require_geolocation = __commonJS({
13667
13920
  _source: "local"
13668
13921
  };
13669
13922
  }
13923
+ if (net.isIP(lookupIp) === 0) {
13924
+ return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
13925
+ }
13670
13926
  const settings = await this.getGeoSettings();
13671
13927
  const provider = normalizeProvider(settings.geoIpProvider);
13672
13928
  if (provider === "disabled") {
13673
- return this.getFallbackData(ipAddress, "disabled", "disabled");
13929
+ return this.getFallbackData(lookupIp, "disabled", "disabled");
13674
13930
  }
13675
13931
  if (provider === "local-mmdb") {
13676
- return this.getLocalMmdbIpInfo(ipAddress, settings);
13932
+ return this.getLocalMmdbIpInfo(lookupIp, settings);
13677
13933
  }
13678
13934
  if (provider === "auto") {
13679
- const databasePath = resolveDatabasePath(settings);
13935
+ const databasePath = resolveExistingDatabasePath(settings);
13680
13936
  if (databasePath && fs.existsSync(databasePath)) {
13681
- const localResult = await this.getLocalMmdbIpInfo(ipAddress, settings);
13682
- if (localResult?._status === "ok") {
13937
+ const localResult = await this.getLocalMmdbIpInfo(lookupIp, settings);
13938
+ if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
13683
13939
  return localResult;
13684
13940
  }
13685
13941
  strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed (${localResult?._reason || localResult?._status}), falling back to ipapi.co`);
13686
13942
  }
13687
13943
  }
13688
- return this.getIpapiIpInfo(ipAddress);
13944
+ return this.getIpapiIpInfo(lookupIp);
13689
13945
  },
13690
13946
  /**
13691
13947
  * Reads effective GEOIP provider settings.
@@ -13699,13 +13955,19 @@ var require_geolocation = __commonJS({
13699
13955
  }
13700
13956
  },
13701
13957
  /**
13702
- * Looks up country data from a local MaxMind-compatible MMDB file.
13958
+ * Looks up geolocation data from a local MaxMind-compatible MMDB file.
13959
+ * GeoLite2-City is preferred for city-level data; GeoLite2-Country remains
13960
+ * supported for existing installations and country-only firewall decisions.
13703
13961
  * @param {string} ipAddress
13704
13962
  * @param {object} settings
13705
13963
  * @returns {Promise<object>}
13706
13964
  */
13707
13965
  async getLocalMmdbIpInfo(ipAddress, settings = {}) {
13708
- const databasePath = resolveDatabasePath(settings);
13966
+ const lookupIp = normalizeLookupIp(ipAddress);
13967
+ if (!lookupIp || net.isIP(lookupIp) === 0) {
13968
+ return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
13969
+ }
13970
+ const databasePath = resolveExistingDatabasePath(settings);
13709
13971
  if (!databasePath || !fs.existsSync(databasePath)) {
13710
13972
  return this.getFallbackData(
13711
13973
  ipAddress,
@@ -13716,39 +13978,16 @@ var require_geolocation = __commonJS({
13716
13978
  }
13717
13979
  try {
13718
13980
  const reader = await openLocalReader(databasePath);
13719
- const data = reader.country(ipAddress);
13720
- const country = data.country || data.registeredCountry || data.representedCountry || {};
13721
- const countryCode = country.isoCode || data.registeredCountry?.isoCode || "XX";
13722
- const countryNames = country.names || {};
13723
- const result = {
13724
- ip: ipAddress,
13725
- country: countryNames.en || countryNames.de || countryCode || "Unknown",
13726
- country_code: countryCode,
13727
- country_flag: this.getCountryFlag(countryCode),
13728
- city: "Unknown",
13729
- region: "Unknown",
13730
- timezone: "Unknown",
13731
- latitude: null,
13732
- longitude: null,
13733
- postal: null,
13734
- org: null,
13735
- asn: null,
13736
- network: data.traits?.network || null,
13737
- isVpn: false,
13738
- isProxy: false,
13739
- isThreat: false,
13740
- isAnonymous: false,
13741
- isTor: false,
13742
- securityScore: 100,
13743
- riskLevel: "Low",
13744
- _status: "ok",
13745
- _source: "local-mmdb"
13746
- };
13747
- strapi2.log.debug(`[magic-sessionmanager/geolocation] Local MMDB IP ${ipAddress}: ${result.country_code}`);
13981
+ const useCityLookup = isCityDatabase(reader, databasePath) && typeof reader.city === "function";
13982
+ const data = useCityLookup ? reader.city(lookupIp) : reader.country(lookupIp);
13983
+ const result = useCityLookup ? normalizeLocalCityResult(data, lookupIp, this.getCountryFlag.bind(this)) : normalizeLocalCountryResult(data, lookupIp, this.getCountryFlag.bind(this));
13984
+ strapi2.log.debug(
13985
+ `[magic-sessionmanager/geolocation] Local MMDB ${result._databaseType} IP ${lookupIp}: ${result.city}, ${result.country_code}`
13986
+ );
13748
13987
  return result;
13749
13988
  } catch (error) {
13750
- strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed for ${ipAddress}:`, error.message);
13751
- return this.getFallbackData(ipAddress, "error", "local-mmdb", error.message);
13989
+ strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed for ${lookupIp}:`, error.message);
13990
+ return this.getFallbackData(lookupIp, "error", "local-mmdb", error.message);
13752
13991
  }
13753
13992
  },
13754
13993
  /**
@@ -13757,65 +13996,135 @@ var require_geolocation = __commonJS({
13757
13996
  * @returns {Promise<object>}
13758
13997
  */
13759
13998
  async getIpapiIpInfo(ipAddress) {
13760
- const controller = new AbortController();
13761
- const timer = setTimeout(() => controller.abort(), GEO_API_TIMEOUT_MS);
13999
+ const lookupIp = normalizeLookupIp(ipAddress);
14000
+ if (!lookupIp || net.isIP(lookupIp) === 0) {
14001
+ return this.getFallbackData(ipAddress, "error", "validation", "Invalid IP address");
14002
+ }
14003
+ const cached = getCachedIpapiResult(lookupIp);
14004
+ if (cached) return cached;
14005
+ const rateLimitRemainingMs = getIpapiRateLimitRemainingMs();
14006
+ if (rateLimitRemainingMs > 0) {
14007
+ logIpapiRateLimit(
14008
+ strapi2,
14009
+ `[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(rateLimitRemainingMs / 1e3)}s`
14010
+ );
14011
+ return this.getFallbackData(lookupIp, "rate_limited", "ipapi", "Remote GeoIP provider is backing off after HTTP 429");
14012
+ }
14013
+ if (ipapiInFlight.has(lookupIp)) {
14014
+ return cloneGeoData(await ipapiInFlight.get(lookupIp));
14015
+ }
14016
+ const lookupPromise = (async () => {
14017
+ const releaseSlot = await acquireIpapiSlot();
14018
+ if (!releaseSlot) {
14019
+ const fallback = this.getFallbackData(
14020
+ lookupIp,
14021
+ "rate_limited",
14022
+ "ipapi",
14023
+ "Remote GeoIP provider concurrency limit reached"
14024
+ );
14025
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14026
+ return fallback;
14027
+ }
14028
+ const queuedRateLimitRemainingMs = getIpapiRateLimitRemainingMs();
14029
+ if (queuedRateLimitRemainingMs > 0) {
14030
+ releaseSlot();
14031
+ logIpapiRateLimit(
14032
+ strapi2,
14033
+ `[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(queuedRateLimitRemainingMs / 1e3)}s`
14034
+ );
14035
+ return this.getFallbackData(lookupIp, "rate_limited", "ipapi", "Remote GeoIP provider is backing off after HTTP 429");
14036
+ }
14037
+ const controller = new AbortController();
14038
+ const timer = setTimeout(() => controller.abort(), GEO_API_TIMEOUT_MS);
14039
+ try {
14040
+ const response = await fetch(`https://ipapi.co/${encodeURIComponent(lookupIp)}/json/`, {
14041
+ method: "GET",
14042
+ headers: { "User-Agent": "Strapi-Magic-SessionManager/1.0" },
14043
+ signal: controller.signal
14044
+ });
14045
+ if (!response.ok) {
14046
+ const reason = response.status === 429 ? "rate_limited" : "error";
14047
+ if (response.status === 429) {
14048
+ const backoffMs = markIpapiRateLimited(response);
14049
+ logIpapiRateLimit(
14050
+ strapi2,
14051
+ `[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
14052
+ );
14053
+ } else {
14054
+ strapi2.log.warn(`[magic-sessionmanager/geolocation] API returned HTTP ${response.status}`);
14055
+ }
14056
+ const fallback = this.getFallbackData(lookupIp, reason, "ipapi", `HTTP ${response.status}`);
14057
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14058
+ return fallback;
14059
+ }
14060
+ const data = await response.json();
14061
+ if (data.error) {
14062
+ const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
14063
+ if (reason === "rate_limited") {
14064
+ const backoffMs = markIpapiRateLimited();
14065
+ logIpapiRateLimit(
14066
+ strapi2,
14067
+ `[magic-sessionmanager/geolocation] API reported rate limit; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
14068
+ );
14069
+ } else {
14070
+ strapi2.log.warn(`[magic-sessionmanager/geolocation] API Error: ${data.reason}`);
14071
+ }
14072
+ const fallback = this.getFallbackData(lookupIp, reason, "ipapi", data.reason);
14073
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14074
+ return fallback;
14075
+ }
14076
+ const result = {
14077
+ ip: data.ip,
14078
+ country: data.country_name,
14079
+ country_code: data.country_code,
14080
+ country_flag: this.getCountryFlag(data.country_code),
14081
+ city: data.city,
14082
+ region: data.region,
14083
+ timezone: data.timezone,
14084
+ latitude: data.latitude,
14085
+ longitude: data.longitude,
14086
+ postal: data.postal,
14087
+ org: data.org,
14088
+ asn: data.asn,
14089
+ isVpn: data.threat?.is_vpn || false,
14090
+ isProxy: data.threat?.is_proxy || false,
14091
+ isThreat: data.threat?.is_threat || false,
14092
+ isAnonymous: data.threat?.is_anonymous || false,
14093
+ isTor: data.threat?.is_tor || false,
14094
+ securityScore: this.calculateSecurityScore({
14095
+ isVpn: data.threat?.is_vpn,
14096
+ isProxy: data.threat?.is_proxy,
14097
+ isThreat: data.threat?.is_threat,
14098
+ isAnonymous: data.threat?.is_anonymous,
14099
+ isTor: data.threat?.is_tor
14100
+ }),
14101
+ riskLevel: this.getRiskLevel({
14102
+ isVpn: data.threat?.is_vpn,
14103
+ isProxy: data.threat?.is_proxy,
14104
+ isThreat: data.threat?.is_threat
14105
+ }),
14106
+ _status: "ok",
14107
+ _source: "ipapi"
14108
+ };
14109
+ strapi2.log.debug(`[magic-sessionmanager/geolocation] IP ${ipAddress}: ${result.city}, ${result.country} (Score: ${result.securityScore})`);
14110
+ cacheIpapiResult(lookupIp, result, IPAPI_SUCCESS_CACHE_TTL_MS);
14111
+ return result;
14112
+ } catch (error) {
14113
+ const status = error?.name === "AbortError" ? "error" : "error";
14114
+ strapi2.log.error(`[magic-sessionmanager/geolocation] Error fetching IP info for ${lookupIp}:`, error.message);
14115
+ const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
14116
+ cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
14117
+ return fallback;
14118
+ } finally {
14119
+ clearTimeout(timer);
14120
+ releaseSlot();
14121
+ }
14122
+ })();
14123
+ ipapiInFlight.set(lookupIp, lookupPromise);
13762
14124
  try {
13763
- const response = await fetch(`https://ipapi.co/${encodeURIComponent(ipAddress)}/json/`, {
13764
- method: "GET",
13765
- headers: { "User-Agent": "Strapi-Magic-SessionManager/1.0" },
13766
- signal: controller.signal
13767
- });
13768
- if (!response.ok) {
13769
- strapi2.log.warn(`[magic-sessionmanager/geolocation] API returned HTTP ${response.status}`);
13770
- return this.getFallbackData(ipAddress, response.status === 429 ? "rate_limited" : "error", "ipapi");
13771
- }
13772
- const data = await response.json();
13773
- if (data.error) {
13774
- strapi2.log.warn(`[magic-sessionmanager/geolocation] API Error: ${data.reason}`);
13775
- const reason = /rate/i.test(data.reason || "") ? "rate_limited" : "error";
13776
- return this.getFallbackData(ipAddress, reason, "ipapi", data.reason);
13777
- }
13778
- const result = {
13779
- ip: data.ip,
13780
- country: data.country_name,
13781
- country_code: data.country_code,
13782
- country_flag: this.getCountryFlag(data.country_code),
13783
- city: data.city,
13784
- region: data.region,
13785
- timezone: data.timezone,
13786
- latitude: data.latitude,
13787
- longitude: data.longitude,
13788
- postal: data.postal,
13789
- org: data.org,
13790
- asn: data.asn,
13791
- isVpn: data.threat?.is_vpn || false,
13792
- isProxy: data.threat?.is_proxy || false,
13793
- isThreat: data.threat?.is_threat || false,
13794
- isAnonymous: data.threat?.is_anonymous || false,
13795
- isTor: data.threat?.is_tor || false,
13796
- securityScore: this.calculateSecurityScore({
13797
- isVpn: data.threat?.is_vpn,
13798
- isProxy: data.threat?.is_proxy,
13799
- isThreat: data.threat?.is_threat,
13800
- isAnonymous: data.threat?.is_anonymous,
13801
- isTor: data.threat?.is_tor
13802
- }),
13803
- riskLevel: this.getRiskLevel({
13804
- isVpn: data.threat?.is_vpn,
13805
- isProxy: data.threat?.is_proxy,
13806
- isThreat: data.threat?.is_threat
13807
- }),
13808
- _status: "ok",
13809
- _source: "ipapi"
13810
- };
13811
- strapi2.log.debug(`[magic-sessionmanager/geolocation] IP ${ipAddress}: ${result.city}, ${result.country} (Score: ${result.securityScore})`);
13812
- return result;
13813
- } catch (error) {
13814
- const status = error?.name === "AbortError" ? "error" : "error";
13815
- strapi2.log.error(`[magic-sessionmanager/geolocation] Error fetching IP info for ${ipAddress}:`, error.message);
13816
- return this.getFallbackData(ipAddress, status, "ipapi", error.message);
14125
+ return cloneGeoData(await lookupPromise);
13817
14126
  } finally {
13818
- clearTimeout(timer);
14127
+ ipapiInFlight.delete(lookupIp);
13819
14128
  }
13820
14129
  },
13821
14130
  /**
@@ -13862,17 +14171,12 @@ var require_geolocation = __commonJS({
13862
14171
  * @returns {boolean}
13863
14172
  */
13864
14173
  isPrivateIp(ip) {
13865
- if (!ip || ip === "unknown") return true;
13866
- if (ip === "127.0.0.1" || ip === "localhost" || ip === "::1") return true;
13867
- if (ip.startsWith("192.168.")) return true;
13868
- if (ip.startsWith("10.")) return true;
13869
- if (ip.startsWith("172.")) {
13870
- const second = parseInt(ip.split(".")[1], 10);
13871
- if (second >= 16 && second <= 31) return true;
13872
- }
13873
- if (ip.startsWith("169.254.")) return true;
13874
- if (ip.startsWith("fc00:") || ip.startsWith("fd00:")) return true;
13875
- if (ip.startsWith("fe80:")) return true;
14174
+ const normalized = normalizeLookupIp(ip);
14175
+ const lower = normalized.toLowerCase();
14176
+ if (!normalized || lower === "unknown" || lower === "localhost") return true;
14177
+ const version = net.isIP(normalized);
14178
+ if (version === 4) return isPrivateIpv4(normalized);
14179
+ if (version === 6) return isPrivateIpv6(normalized);
13876
14180
  return false;
13877
14181
  },
13878
14182
  /**