strapi-plugin-magic-sessionmanager 4.14.2 → 4.15.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 (30) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +151 -79
  3. package/dist/admin/{Analytics-Box2STtg.js → Analytics-Dbs5QXLb.js} +1 -1
  4. package/dist/admin/{Analytics-DfDdcjMe.mjs → Analytics-HK6_TEmk.mjs} +1 -1
  5. package/dist/admin/{App-DzxXcTYs.js → App-7SxOBJP5.js} +63 -29
  6. package/dist/admin/{App-B2JIOiNM.mjs → App-BOFzZ5d8.mjs} +64 -30
  7. package/dist/admin/{OnlineUsersWidget-BOd7p_MF.mjs → OnlineUsersWidget-CoCxnww-.mjs} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-D4M4D6rm.js → OnlineUsersWidget-Dns_74xJ.js} +1 -1
  9. package/dist/admin/{Settings-DNgH9qRy.js → Settings-B6CrR-07.js} +257 -64
  10. package/dist/admin/{Settings-BFdr77zD.mjs → Settings-DYRShQ8W.mjs} +258 -65
  11. package/dist/admin/{de-BlKn1pSD.mjs → de-B3mPtxsW.mjs} +39 -7
  12. package/dist/admin/{de-B0CBR1Dw.js → de-bkkCvSxX.js} +39 -7
  13. package/dist/admin/{en-IT0YTY8f.mjs → en-BnU8BNkN.mjs} +39 -7
  14. package/dist/admin/{en-D0ZGIIjz.js → en-DMICyIow.js} +39 -7
  15. package/dist/admin/{es-BCGzaaCh.mjs → es-BxMgfJ1Y.mjs} +39 -7
  16. package/dist/admin/{es-CWee-XCR.js → es-OSzHGRIu.js} +39 -7
  17. package/dist/admin/{fr-rQS1M7jE.js → fr-Bu_8miJ4.js} +39 -7
  18. package/dist/admin/{fr-xBIH4Byq.mjs → fr-WPrbtx8k.mjs} +39 -7
  19. package/dist/admin/{index-CmW1DJ0c.js → index-CNSJITRX.js} +9 -9
  20. package/dist/admin/{index-C2SrNW6I.mjs → index-lnZBc5n0.mjs} +9 -9
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +1 -1
  23. package/dist/admin/{pt-C-yTLhnS.js → pt-B08xnb0K.js} +39 -7
  24. package/dist/admin/{pt-DWDeIDVa.mjs → pt-C41KyEDN.mjs} +39 -7
  25. package/dist/admin/riskData-BVs9GpgD.js +26 -0
  26. package/dist/admin/riskData-CI1gm2yI.mjs +27 -0
  27. package/dist/server/index.js +565 -178
  28. package/dist/server/index.mjs +565 -178
  29. package/package.json +3 -3
  30. package/scripts/geoip-updater.cjs +58 -15
@@ -1479,10 +1479,75 @@ var require_rejection_cache = __commonJS({
1479
1479
  }
1480
1480
  });
1481
1481
 
1482
+ // server/src/utils/risk-data.js
1483
+ var require_risk_data = __commonJS({
1484
+ "server/src/utils/risk-data.js"(exports, module) {
1485
+ "use strict";
1486
+ var RISK_SOURCES = Object.freeze(["anonymous-ip", "asn-heuristic"]);
1487
+ var SUSPICIOUS_SCORE_BELOW = 70;
1488
+ var REJECT_SCORE_BELOW = 50;
1489
+ function noRiskData() {
1490
+ return {
1491
+ isVpn: false,
1492
+ isProxy: false,
1493
+ isThreat: false,
1494
+ isAnonymous: false,
1495
+ isTor: false,
1496
+ isHosting: false,
1497
+ securityScore: null,
1498
+ riskLevel: "Unknown",
1499
+ riskSource: null
1500
+ };
1501
+ }
1502
+ function hasRiskData(geoData) {
1503
+ return Boolean(geoData) && RISK_SOURCES.includes(geoData.riskSource);
1504
+ }
1505
+ function calculateSecurityScore({ isVpn, isProxy, isThreat, isAnonymous, isTor, isHosting }) {
1506
+ let score = 100;
1507
+ if (isTor) score -= 50;
1508
+ if (isThreat) score -= 40;
1509
+ if (isVpn) score -= 20;
1510
+ if (isHosting) score -= 20;
1511
+ if (isProxy) score -= 15;
1512
+ if (isAnonymous) score -= 10;
1513
+ return Math.max(0, score);
1514
+ }
1515
+ function getRiskLevel({ isVpn, isProxy, isThreat, isTor, isHosting }) {
1516
+ if (isThreat || isTor) return "High";
1517
+ if (isVpn && isProxy) return "Medium-High";
1518
+ if (isVpn || isProxy || isHosting) return "Medium";
1519
+ return "Low";
1520
+ }
1521
+ function evaluateLoginRisk(settings = {}, geoData = null) {
1522
+ if (!hasRiskData(geoData)) {
1523
+ return { hasRiskData: false, isSuspicious: false, isVpnOrProxy: false };
1524
+ }
1525
+ const scoreEvaluationEnabled = settings.enableSecurityScoring !== false;
1526
+ const lowScore = scoreEvaluationEnabled && typeof geoData.securityScore === "number" && geoData.securityScore < SUSPICIOUS_SCORE_BELOW;
1527
+ const isVpnOrProxy = Boolean(geoData.isVpn || geoData.isProxy);
1528
+ const isSuspicious = Boolean(
1529
+ isVpnOrProxy || geoData.isThreat || geoData.isTor || geoData.isHosting || lowScore
1530
+ );
1531
+ return { hasRiskData: true, isSuspicious, isVpnOrProxy };
1532
+ }
1533
+ module.exports = {
1534
+ REJECT_SCORE_BELOW,
1535
+ RISK_SOURCES,
1536
+ SUSPICIOUS_SCORE_BELOW,
1537
+ calculateSecurityScore,
1538
+ evaluateLoginRisk,
1539
+ getRiskLevel,
1540
+ hasRiskData,
1541
+ noRiskData
1542
+ };
1543
+ }
1544
+ });
1545
+
1482
1546
  // server/src/utils/geo-firewall.js
1483
1547
  var require_geo_firewall = __commonJS({
1484
1548
  "server/src/utils/geo-firewall.js"(exports, module) {
1485
1549
  "use strict";
1550
+ var { REJECT_SCORE_BELOW, hasRiskData } = require_risk_data();
1486
1551
  function normalizeCountryCode(value) {
1487
1552
  if (typeof value !== "string") return null;
1488
1553
  const normalized = value.trim().toUpperCase();
@@ -1502,27 +1567,20 @@ var require_geo_firewall = __commonJS({
1502
1567
  if (status === "private") {
1503
1568
  return { blocked: false, reason: null, status };
1504
1569
  }
1505
- if (status !== "ok") {
1506
- if (getLookupFailureMode(settings) === "block") {
1507
- return {
1508
- blocked: true,
1509
- reason: `geo_lookup_unavailable:${status}`,
1510
- status
1511
- };
1512
- }
1513
- return { blocked: false, reason: null, status };
1514
- }
1515
- if (settings.blockSuspiciousSessions) {
1570
+ if (settings.blockSuspiciousSessions && hasRiskData(geoData)) {
1516
1571
  if (geoData.isThreat) {
1517
1572
  return { blocked: true, reason: "threat_ip", status };
1518
1573
  }
1574
+ if (geoData.isTor) {
1575
+ return { blocked: true, reason: "tor_exit_node", status };
1576
+ }
1519
1577
  if (geoData.isVpn) {
1520
1578
  return { blocked: true, reason: "vpn_detected", status };
1521
1579
  }
1522
1580
  if (geoData.isProxy) {
1523
1581
  return { blocked: true, reason: "proxy_detected", status };
1524
1582
  }
1525
- if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < 50) {
1583
+ if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < REJECT_SCORE_BELOW) {
1526
1584
  return {
1527
1585
  blocked: true,
1528
1586
  reason: `low_security_score:${geoData.securityScore}`,
@@ -1530,6 +1588,16 @@ var require_geo_firewall = __commonJS({
1530
1588
  };
1531
1589
  }
1532
1590
  }
1591
+ if (status !== "ok") {
1592
+ if (getLookupFailureMode(settings) === "block") {
1593
+ return {
1594
+ blocked: true,
1595
+ reason: `geo_lookup_unavailable:${status}`,
1596
+ status
1597
+ };
1598
+ }
1599
+ return { blocked: false, reason: null, status };
1600
+ }
1533
1601
  if (settings.enableGeofencing) {
1534
1602
  const countryCode = normalizeCountryCode(geoData.country_code);
1535
1603
  const blockedCountries = normalizeCountryList(settings.blockedCountries);
@@ -1559,6 +1627,93 @@ var require_geo_firewall = __commonJS({
1559
1627
  }
1560
1628
  });
1561
1629
 
1630
+ // server/src/utils/login-alerts.js
1631
+ var require_login_alerts = __commonJS({
1632
+ "server/src/utils/login-alerts.js"(exports, module) {
1633
+ "use strict";
1634
+ var { evaluateLoginRisk } = require_risk_data();
1635
+ async function dispatchLoginAlerts({
1636
+ settings,
1637
+ notificationService,
1638
+ user,
1639
+ session,
1640
+ geoData,
1641
+ isNewLocation = false
1642
+ }) {
1643
+ const attempted = { webhookEvent: null, emails: [] };
1644
+ if (!geoData) return attempted;
1645
+ const risk = evaluateLoginRisk(settings, geoData);
1646
+ if (settings.enableEmailAlerts) {
1647
+ if (settings.alertOnVpnProxy && risk.isVpnOrProxy) {
1648
+ attempted.emails.push("vpnProxy");
1649
+ await notificationService.sendVpnProxyAlert({
1650
+ user,
1651
+ session,
1652
+ reason: { isVpn: geoData.isVpn, isProxy: geoData.isProxy },
1653
+ geoData
1654
+ });
1655
+ }
1656
+ if (settings.alertOnSuspiciousLogin && risk.isSuspicious) {
1657
+ attempted.emails.push("suspiciousLogin");
1658
+ await notificationService.sendSuspiciousLoginAlert({
1659
+ user,
1660
+ session,
1661
+ reason: {
1662
+ isVpn: geoData.isVpn,
1663
+ isProxy: geoData.isProxy,
1664
+ isThreat: geoData.isThreat,
1665
+ securityScore: geoData.securityScore
1666
+ },
1667
+ geoData
1668
+ });
1669
+ }
1670
+ if (settings.alertOnNewLocation && isNewLocation) {
1671
+ attempted.emails.push("newLocation");
1672
+ await notificationService.sendNewLocationAlert({ user, session, geoData });
1673
+ }
1674
+ }
1675
+ if (settings.enableWebhooks) {
1676
+ const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
1677
+ attempted.webhookEvent = webhookEvent;
1678
+ const targets = [];
1679
+ if (settings.discordWebhookUrl) {
1680
+ targets.push({
1681
+ url: settings.discordWebhookUrl,
1682
+ payload: notificationService.formatDiscordWebhook({
1683
+ event: webhookEvent,
1684
+ session,
1685
+ user,
1686
+ geoData
1687
+ })
1688
+ });
1689
+ }
1690
+ if (settings.slackWebhookUrl) {
1691
+ targets.push({
1692
+ url: settings.slackWebhookUrl,
1693
+ payload: notificationService.formatSlackWebhook({
1694
+ event: webhookEvent,
1695
+ session,
1696
+ user,
1697
+ geoData
1698
+ })
1699
+ });
1700
+ }
1701
+ await Promise.allSettled(
1702
+ targets.map(
1703
+ (target) => notificationService.sendWebhook({
1704
+ event: webhookEvent,
1705
+ data: target.payload,
1706
+ webhookUrl: target.url
1707
+ })
1708
+ )
1709
+ );
1710
+ }
1711
+ return attempted;
1712
+ }
1713
+ module.exports = { dispatchLoginAlerts };
1714
+ }
1715
+ });
1716
+
1562
1717
  // server/src/utils/session-revocation.js
1563
1718
  var require_session_revocation = __commonJS({
1564
1719
  "server/src/utils/session-revocation.js"(exports, module) {
@@ -6386,6 +6541,7 @@ var require_bootstrap = __commonJS({
6386
6541
  var { extractBearerToken } = require_extract_token();
6387
6542
  var { setSessionRejectionReason } = require_rejection_cache();
6388
6543
  var { evaluateGeoFirewall } = require_geo_firewall();
6544
+ var { dispatchLoginAlerts } = require_login_alerts();
6389
6545
  var { REVOCATION_UID } = require_session_revocation();
6390
6546
  var { getNativeSessionManager } = require_native_session_manager();
6391
6547
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
@@ -7128,9 +7284,6 @@ var require_bootstrap = __commonJS({
7128
7284
  return;
7129
7285
  }
7130
7286
  const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
7131
- const scoreEvaluationEnabled = settings.enableSecurityScoring !== false;
7132
- const lowScore = scoreEvaluationEnabled && typeof geoData.securityScore === "number" && geoData.securityScore < 70;
7133
- const isSuspicious = geoData.isVpn || geoData.isProxy || geoData.isThreat || lowScore;
7134
7287
  let isNewLocation = false;
7135
7288
  if (settings.alertOnNewLocation && (geoData.country_code || geoData.country)) {
7136
7289
  try {
@@ -7173,74 +7326,14 @@ var require_bootstrap = __commonJS({
7173
7326
  log.debug("New-location check failed (non-fatal):", locErr?.name || "Error");
7174
7327
  }
7175
7328
  }
7176
- if (settings.enableEmailAlerts) {
7177
- if (settings.alertOnVpnProxy && (geoData.isVpn || geoData.isProxy)) {
7178
- await notificationService.sendVpnProxyAlert({
7179
- user,
7180
- session: newSession,
7181
- reason: {
7182
- isVpn: geoData.isVpn,
7183
- isProxy: geoData.isProxy
7184
- },
7185
- geoData
7186
- });
7187
- }
7188
- if (settings.alertOnSuspiciousLogin && isSuspicious) {
7189
- await notificationService.sendSuspiciousLoginAlert({
7190
- user,
7191
- session: newSession,
7192
- reason: {
7193
- isVpn: geoData.isVpn,
7194
- isProxy: geoData.isProxy,
7195
- isThreat: geoData.isThreat,
7196
- securityScore: geoData.securityScore
7197
- },
7198
- geoData
7199
- });
7200
- }
7201
- if (settings.alertOnNewLocation && isNewLocation) {
7202
- await notificationService.sendNewLocationAlert({
7203
- user,
7204
- session: newSession,
7205
- geoData
7206
- });
7207
- }
7208
- }
7209
- if (settings.enableWebhooks) {
7210
- const webhookEvent = isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
7211
- const targets = [];
7212
- if (settings.discordWebhookUrl) {
7213
- targets.push({
7214
- url: settings.discordWebhookUrl,
7215
- payload: notificationService.formatDiscordWebhook({
7216
- event: webhookEvent,
7217
- session: newSession,
7218
- user,
7219
- geoData
7220
- })
7221
- });
7222
- }
7223
- if (settings.slackWebhookUrl) {
7224
- targets.push({
7225
- url: settings.slackWebhookUrl,
7226
- payload: notificationService.formatSlackWebhook({
7227
- event: webhookEvent,
7228
- session: newSession,
7229
- user,
7230
- geoData
7231
- })
7232
- });
7233
- }
7234
- await Promise.allSettled(
7235
- targets.map(
7236
- (t) => notificationService.sendWebhook({
7237
- event: webhookEvent,
7238
- data: t.payload,
7239
- webhookUrl: t.url
7240
- })
7241
- )
7242
- );
7243
- }
7329
+ await dispatchLoginAlerts({
7330
+ settings,
7331
+ notificationService,
7332
+ user,
7333
+ session: newSession,
7334
+ geoData,
7335
+ isNewLocation
7336
+ });
7244
7337
  } catch (notifErr) {
7245
7338
  log.warn("Notification failed:", notifErr?.name || "Error");
7246
7339
  }
@@ -8920,14 +9013,15 @@ var require_enhance_session = __commonJS({
8920
9013
  country_flag: geoData.country_flag,
8921
9014
  city: geoData.city,
8922
9015
  region: geoData.region,
8923
- timezone: geoData.timezone
9016
+ timezone: geoData.timezone,
9017
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
8924
9018
  };
8925
9019
  if (strapi2) {
8926
9020
  strapi2.documents(SESSION_UID).update({
8927
9021
  documentId: session.documentId,
8928
9022
  data: {
8929
9023
  geoLocation,
8930
- securityScore: geoData.securityScore ?? null
9024
+ securityScore: geoData.riskSource ? geoData.securityScore ?? null : null
8931
9025
  }
8932
9026
  }).catch(() => {
8933
9027
  });
@@ -9636,6 +9730,7 @@ var require_session = __commonJS({
9636
9730
  var { sendServerError } = require_http_errors();
9637
9731
  var { getCoordinator } = require_coordination();
9638
9732
  var { clearSessionStatsCache } = require_session_list();
9733
+ var { noRiskData } = require_risk_data();
9639
9734
  var {
9640
9735
  getNativeOnlySummary,
9641
9736
  endNativeOnlySessions,
@@ -9669,11 +9764,7 @@ var require_session = __commonJS({
9669
9764
  timezone: "Unknown",
9670
9765
  latitude: null,
9671
9766
  longitude: null,
9672
- isVpn: false,
9673
- isProxy: false,
9674
- isThreat: false,
9675
- securityScore: 50,
9676
- riskLevel: "Unknown",
9767
+ ...noRiskData(),
9677
9768
  _status: "disabled",
9678
9769
  _source: "disabled"
9679
9770
  };
@@ -10796,7 +10887,10 @@ var require_geoip_updater = __commonJS({
10796
10887
  var SUPPORTED_MMDB_NAMES = new Set(
10797
10888
  [...SUPPORTED_EDITION_IDS].map((editionId) => `${editionId}.mmdb`)
10798
10889
  );
10799
- function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
10890
+ var RISK_EDITION_IDS = /* @__PURE__ */ new Set(["GeoIP2-Anonymous-IP", "GeoLite2-ASN"]);
10891
+ var ALL_EDITION_IDS = /* @__PURE__ */ new Set([...SUPPORTED_EDITION_IDS, ...RISK_EDITION_IDS]);
10892
+ var ALL_MMDB_NAMES = new Set([...ALL_EDITION_IDS].map((editionId) => `${editionId}.mmdb`));
10893
+ function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY, allowedNames = SUPPORTED_MMDB_NAMES) {
10800
10894
  const root = path.resolve(directory);
10801
10895
  if (value !== void 0 && typeof value !== "string") {
10802
10896
  throw new Error("GeoIP database path must be a string");
@@ -10815,14 +10909,14 @@ var require_geoip_updater = __commonJS({
10815
10909
  }
10816
10910
  filename = requested;
10817
10911
  }
10818
- if (!SUPPORTED_MMDB_NAMES.has(filename)) {
10912
+ if (!allowedNames.has(filename)) {
10819
10913
  throw new Error("GeoIP database path must use a supported MMDB filename");
10820
10914
  }
10821
10915
  return path.join(root, filename);
10822
10916
  }
10823
- async function canonicalizeDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
10917
+ async function canonicalizeDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY, allowedNames = SUPPORTED_MMDB_NAMES) {
10824
10918
  const root = path.resolve(directory);
10825
- const target = resolveDatabaseTarget(value, root);
10919
+ const target = resolveDatabaseTarget(value, root, allowedNames);
10826
10920
  await fs.mkdir(root, { recursive: true, mode: 448 });
10827
10921
  const rootStat = await fs.lstat(root);
10828
10922
  const canonicalRoot = await fs.realpath(root);
@@ -10848,8 +10942,8 @@ var require_geoip_updater = __commonJS({
10848
10942
  }
10849
10943
  return canonicalTarget;
10850
10944
  }
10851
- function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
10852
- return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
10945
+ function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID, allowed = SUPPORTED_EDITION_IDS) {
10946
+ return allowed.has(value) ? value : fallback;
10853
10947
  }
10854
10948
  function inferEditionIdFromPath(filePath) {
10855
10949
  if (typeof filePath !== "string" || filePath.trim() === "") return "";
@@ -10871,10 +10965,25 @@ var require_geoip_updater = __commonJS({
10871
10965
  function resolveConfig(env = process2.env, argv = process2.argv.slice(2), overrides = {}) {
10872
10966
  const force = argv.includes("--force") || overrides.force === true;
10873
10967
  const configuredOutputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || "";
10968
+ const requestedEdition = overrides.editionId || env.MAXMIND_EDITION_ID;
10969
+ const databaseDirectory = overrides.databaseDirectory || DEFAULT_GEOIP_DIRECTORY;
10970
+ if (RISK_EDITION_IDS.has(requestedEdition)) {
10971
+ return {
10972
+ accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || "",
10973
+ licenseKey: overrides.licenseKey || env.MAXMIND_LICENSE_KEY || "",
10974
+ editionId: requestedEdition,
10975
+ outputPath: resolveDatabaseTarget(
10976
+ `${requestedEdition}.mmdb`,
10977
+ databaseDirectory,
10978
+ ALL_MMDB_NAMES
10979
+ ),
10980
+ mmdbFileName: `${requestedEdition}.mmdb`,
10981
+ force
10982
+ };
10983
+ }
10874
10984
  const editionId = normalizeEditionId(
10875
- overrides.editionId || env.MAXMIND_EDITION_ID || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
10985
+ requestedEdition || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
10876
10986
  );
10877
- const databaseDirectory = overrides.databaseDirectory || DEFAULT_GEOIP_DIRECTORY;
10878
10987
  const outputPath = resolveDatabaseTarget(
10879
10988
  configuredOutputPath || `${editionId}.mmdb`,
10880
10989
  databaseDirectory
@@ -10952,7 +11061,9 @@ var require_geoip_updater = __commonJS({
10952
11061
  redirect: "follow"
10953
11062
  });
10954
11063
  if (!response.ok) {
10955
- throw new Error(`MaxMind HEAD failed with HTTP ${response.status}`);
11064
+ const error = new Error(`MaxMind HEAD failed with HTTP ${response.status}`);
11065
+ error.httpStatus = response.status;
11066
+ throw error;
10956
11067
  }
10957
11068
  return {
10958
11069
  lastModified: response.headers.get("last-modified") || "",
@@ -10969,7 +11080,9 @@ var require_geoip_updater = __commonJS({
10969
11080
  redirect: "follow"
10970
11081
  });
10971
11082
  if (!response.ok) {
10972
- throw new Error(`MaxMind download failed with HTTP ${response.status}`);
11083
+ const error = new Error(`MaxMind download failed with HTTP ${response.status}`);
11084
+ error.httpStatus = response.status;
11085
+ throw error;
10973
11086
  }
10974
11087
  return Buffer.from(await response.arrayBuffer());
10975
11088
  }
@@ -11007,8 +11120,12 @@ var require_geoip_updater = __commonJS({
11007
11120
  if (!config.accountId || !config.licenseKey) {
11008
11121
  throw new Error("MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY are required");
11009
11122
  }
11010
- const editionId = normalizeEditionId(config.editionId);
11011
- const outputPath = await canonicalizeDatabaseTarget(config.outputPath);
11123
+ const editionId = normalizeEditionId(config.editionId, DEFAULT_EDITION_ID, ALL_EDITION_IDS);
11124
+ const outputPath = await canonicalizeDatabaseTarget(
11125
+ config.outputPath,
11126
+ DEFAULT_GEOIP_DIRECTORY,
11127
+ ALL_MMDB_NAMES
11128
+ );
11012
11129
  const mmdbFileName = `${editionId}.mmdb`;
11013
11130
  if (path.basename(outputPath) !== mmdbFileName) {
11014
11131
  throw new Error("GeoIP database filename must match the selected edition");
@@ -11060,6 +11177,8 @@ var require_geoip_updater = __commonJS({
11060
11177
  };
11061
11178
  }
11062
11179
  module.exports = {
11180
+ ALL_MMDB_NAMES,
11181
+ RISK_EDITION_IDS,
11063
11182
  DEFAULT_EDITION_ID,
11064
11183
  DEFAULT_GEOIP_DIRECTORY,
11065
11184
  DEFAULT_MMDB_NAME,
@@ -11609,6 +11728,218 @@ var require_settings = __commonJS({
11609
11728
  }
11610
11729
  });
11611
11730
 
11731
+ // server/src/utils/risk-databases.js
11732
+ var require_risk_databases = __commonJS({
11733
+ "server/src/utils/risk-databases.js"(exports, module) {
11734
+ "use strict";
11735
+ var fs = __require("node:fs");
11736
+ var path = __require("node:path");
11737
+ var {
11738
+ DEFAULT_GEOIP_DIRECTORY,
11739
+ RISK_EDITION_IDS,
11740
+ readMetadata
11741
+ } = require_geoip_updater();
11742
+ var { calculateSecurityScore, getRiskLevel, noRiskData } = require_risk_data();
11743
+ var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
11744
+ var RISK_DATABASES = Object.freeze({
11745
+ "anonymous-ip": Object.freeze({
11746
+ editionId: "GeoIP2-Anonymous-IP",
11747
+ envVar: "MAGIC_SESSIONMANAGER_ANONYMOUS_IP_DATABASE",
11748
+ method: "anonymousIP"
11749
+ }),
11750
+ asn: Object.freeze({
11751
+ editionId: "GeoLite2-ASN",
11752
+ envVar: "MAGIC_SESSIONMANAGER_ASN_DATABASE",
11753
+ method: "asn"
11754
+ })
11755
+ });
11756
+ var HOSTING_ASNS = Object.freeze(
11757
+ /* @__PURE__ */ new Set([
11758
+ 16509,
11759
+ // Amazon AWS
11760
+ 14618,
11761
+ // Amazon AWS
11762
+ 396982,
11763
+ // Google Cloud
11764
+ 8075,
11765
+ // Microsoft (Azure; also Microsoft's own offices)
11766
+ 14061,
11767
+ // DigitalOcean
11768
+ 24940,
11769
+ // Hetzner Online
11770
+ 213230,
11771
+ // Hetzner Cloud
11772
+ 16276,
11773
+ // OVHcloud
11774
+ 63949,
11775
+ // Akamai Connected Cloud (Linode)
11776
+ 20473,
11777
+ // Vultr (The Constant Company)
11778
+ 51167,
11779
+ // Contabo
11780
+ 31898,
11781
+ // Oracle Cloud
11782
+ 45102,
11783
+ // Alibaba Cloud
11784
+ 12876,
11785
+ // Scaleway
11786
+ 60781,
11787
+ // Leaseweb Netherlands
11788
+ 28753,
11789
+ // Leaseweb Germany
11790
+ 8560,
11791
+ // IONOS
11792
+ 47583,
11793
+ // Hostinger
11794
+ 9009
11795
+ // M247
11796
+ ])
11797
+ );
11798
+ var readerCache = /* @__PURE__ */ new Map();
11799
+ function resolveRiskDatabasePath(kind, env = process.env) {
11800
+ const definition = RISK_DATABASES[kind];
11801
+ const configured = typeof env[definition.envVar] === "string" ? env[definition.envVar].trim() : "";
11802
+ if (configured) {
11803
+ return {
11804
+ path: path.isAbsolute(configured) ? configured : path.resolve(process.cwd(), configured),
11805
+ fromEnvironment: true
11806
+ };
11807
+ }
11808
+ return {
11809
+ path: path.join(DEFAULT_GEOIP_DIRECTORY, `${definition.editionId}.mmdb`),
11810
+ fromEnvironment: false
11811
+ };
11812
+ }
11813
+ async function openRiskReader(databasePath) {
11814
+ if (readerCache.has(databasePath)) return readerCache.get(databasePath);
11815
+ const { Reader } = __require("@maxmind/geoip2-node");
11816
+ const readerPromise = Reader.open(databasePath, {
11817
+ watchForUpdates: true,
11818
+ watchForUpdatesNonPersistent: true
11819
+ });
11820
+ readerCache.set(databasePath, readerPromise);
11821
+ try {
11822
+ return await readerPromise;
11823
+ } catch (error) {
11824
+ readerCache.delete(databasePath);
11825
+ throw error;
11826
+ }
11827
+ }
11828
+ function resetRiskReaders() {
11829
+ for (const databasePath of readerCache.keys()) fs.unwatchFile(databasePath);
11830
+ readerCache.clear();
11831
+ }
11832
+ async function readRiskRecord(kind, ip, env = process.env) {
11833
+ const { path: databasePath } = resolveRiskDatabasePath(kind, env);
11834
+ if (!fs.existsSync(databasePath)) return { status: "missing" };
11835
+ try {
11836
+ const reader = await openRiskReader(databasePath);
11837
+ return { status: "ok", record: reader[RISK_DATABASES[kind].method](ip) };
11838
+ } catch (error) {
11839
+ if (error?.name === "AddressNotFoundError") return { status: "absent" };
11840
+ return { status: "error", name: error?.name || "Error" };
11841
+ }
11842
+ }
11843
+ function buildRiskData({ anonymous, asn }) {
11844
+ const asnRecord = asn?.status === "ok" ? asn.record : null;
11845
+ const asnNumber = Number.isInteger(asnRecord?.autonomousSystemNumber) ? asnRecord.autonomousSystemNumber : null;
11846
+ const asnFields = asnRecord ? {
11847
+ asn: asnNumber === null ? null : `AS${asnNumber}`,
11848
+ org: asnRecord.autonomousSystemOrganization || null
11849
+ } : {};
11850
+ let flags;
11851
+ let riskSource;
11852
+ if (anonymous?.status === "ok" || anonymous?.status === "absent") {
11853
+ const record = anonymous.record || {};
11854
+ riskSource = "anonymous-ip";
11855
+ flags = {
11856
+ isAnonymous: record.isAnonymous === true,
11857
+ isVpn: record.isAnonymousVpn === true,
11858
+ isPublicProxy: record.isPublicProxy === true,
11859
+ isResidentialProxy: record.isResidentialProxy === true,
11860
+ isProxy: record.isPublicProxy === true || record.isResidentialProxy === true,
11861
+ isTor: record.isTorExitNode === true,
11862
+ isHosting: record.isHostingProvider === true,
11863
+ // MaxMind's Anonymous IP data has no "threat" category.
11864
+ isThreat: false
11865
+ };
11866
+ } else if (asn?.status === "ok" || asn?.status === "absent") {
11867
+ riskSource = "asn-heuristic";
11868
+ flags = {
11869
+ isAnonymous: false,
11870
+ isVpn: false,
11871
+ isPublicProxy: false,
11872
+ isResidentialProxy: false,
11873
+ isProxy: false,
11874
+ isTor: false,
11875
+ isHosting: asnNumber !== null && HOSTING_ASNS.has(asnNumber),
11876
+ isThreat: false
11877
+ };
11878
+ } else {
11879
+ const failed = anonymous?.status === "error" || asn?.status === "error";
11880
+ return { ...noRiskData(), ...asnFields, _riskStatus: failed ? "error" : "missing" };
11881
+ }
11882
+ return {
11883
+ ...flags,
11884
+ ...asnFields,
11885
+ securityScore: calculateSecurityScore(flags),
11886
+ riskLevel: getRiskLevel(flags),
11887
+ riskSource,
11888
+ _riskStatus: "ok"
11889
+ };
11890
+ }
11891
+ async function lookupRiskData(ip, env = process.env) {
11892
+ const [anonymous, asn] = await Promise.all([
11893
+ readRiskRecord("anonymous-ip", ip, env),
11894
+ readRiskRecord("asn", ip, env)
11895
+ ]);
11896
+ return buildRiskData({ anonymous, asn });
11897
+ }
11898
+ async function isUsableRiskDatabase(kind, databasePath) {
11899
+ try {
11900
+ const reader = await openRiskReader(databasePath);
11901
+ reader[RISK_DATABASES[kind].method]("127.0.0.1");
11902
+ return true;
11903
+ } catch (error) {
11904
+ return error?.name === "AddressNotFoundError";
11905
+ }
11906
+ }
11907
+ async function describeRiskDatabase(kind, env = process.env) {
11908
+ const { editionId } = RISK_DATABASES[kind];
11909
+ const { path: databasePath, fromEnvironment } = resolveRiskDatabasePath(kind, env);
11910
+ const exists = fs.existsSync(databasePath);
11911
+ const usable = exists ? await isUsableRiskDatabase(kind, databasePath) : false;
11912
+ return {
11913
+ editionId,
11914
+ exists,
11915
+ usable,
11916
+ fromEnvironment,
11917
+ // Only the dedicated folder is named; an environment path stays private.
11918
+ file: fromEnvironment ? null : `${SAFE_GEOIP_DIRECTORY_LABEL}/${editionId}.mmdb`,
11919
+ metadata: !fromEnvironment && exists ? await readMetadata(`${databasePath}.metadata.json`) : null
11920
+ };
11921
+ }
11922
+ async function getRiskDataStatus(env = process.env) {
11923
+ const [anonymousIp, asn] = await Promise.all([
11924
+ describeRiskDatabase("anonymous-ip", env),
11925
+ describeRiskDatabase("asn", env)
11926
+ ]);
11927
+ const source = anonymousIp.usable ? "anonymous-ip" : asn.usable ? "asn-heuristic" : null;
11928
+ return { available: source !== null, source, anonymousIp, asn };
11929
+ }
11930
+ module.exports = {
11931
+ HOSTING_ASNS,
11932
+ RISK_DATABASES,
11933
+ RISK_EDITION_IDS,
11934
+ buildRiskData,
11935
+ getRiskDataStatus,
11936
+ lookupRiskData,
11937
+ resetRiskReaders,
11938
+ resolveRiskDatabasePath
11939
+ };
11940
+ }
11941
+ });
11942
+
11612
11943
  // server/src/controllers/geoip.js
11613
11944
  var require_geoip = __commonJS({
11614
11945
  "server/src/controllers/geoip.js"(exports, module) {
@@ -11631,6 +11962,7 @@ var require_geoip = __commonJS({
11631
11962
  var { sendServerError } = require_http_errors();
11632
11963
  var { setPluginStoreValue } = require_plugin_store();
11633
11964
  var { getHostFingerprint } = require_coordination();
11965
+ var { getRiskDataStatus, RISK_DATABASES } = require_risk_databases();
11634
11966
  var CREDENTIALS_KEY = "geoipCredentials";
11635
11967
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
11636
11968
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -11687,6 +12019,16 @@ var require_geoip = __commonJS({
11687
12019
  force
11688
12020
  });
11689
12021
  }
12022
+ var UPDATABLE_DATABASES = /* @__PURE__ */ new Set(["location", ...Object.keys(RISK_DATABASES)]);
12023
+ function buildRiskUpdaterConfig(database, storedCredentials, force = false) {
12024
+ return resolveConfig(process.env, force ? ["--force"] : [], {
12025
+ accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
12026
+ licenseKey: process.env.MAXMIND_LICENSE_KEY || storedCredentials.licenseKey || "",
12027
+ editionId: RISK_DATABASES[database].editionId,
12028
+ databaseDirectory: DEFAULT_GEOIP_DIRECTORY,
12029
+ force
12030
+ });
12031
+ }
11690
12032
  function sanitizeCredentialInput(value, maxLength = 256) {
11691
12033
  if (typeof value !== "string") return "";
11692
12034
  return value.replace(/\0/g, "").trim().slice(0, maxLength);
@@ -11725,7 +12067,11 @@ var require_geoip = __commonJS({
11725
12067
  // answered. In multi-instance deployments each instance reports
11726
12068
  // its own file; `instance` is a non-reversible host fingerprint.
11727
12069
  scope: "instance",
11728
- instance: getHostFingerprint()
12070
+ instance: getHostFingerprint(),
12071
+ // VPN, proxy and Tor detection needs a dedicated risk data source.
12072
+ // The location providers (ipapi.co, GeoLite2 City/Country) have
12073
+ // none; the local Anonymous IP or ASN database is reported here.
12074
+ risk: await getRiskDataStatus()
11729
12075
  }
11730
12076
  });
11731
12077
  } catch (error) {
@@ -11780,9 +12126,15 @@ var require_geoip = __commonJS({
11780
12126
  try {
11781
12127
  const body = ctx.request.body || {};
11782
12128
  const force = body.force === true;
12129
+ const database = body.database === void 0 ? "location" : body.database;
12130
+ if (!UPDATABLE_DATABASES.has(database)) {
12131
+ return ctx.badRequest("Unknown GeoIP database", {
12132
+ database: ["Use location, anonymous-ip or asn."]
12133
+ });
12134
+ }
11783
12135
  const settings = await getPluginSettings(strapi2);
11784
12136
  const storedCredentials = await getStoredCredentials(strapi2);
11785
- const config = buildUpdaterConfig(settings, storedCredentials, force);
12137
+ const config = database === "location" ? buildUpdaterConfig(settings, storedCredentials, force) : buildRiskUpdaterConfig(database, storedCredentials, force);
11786
12138
  if (!config.accountId || !config.licenseKey) {
11787
12139
  return ctx.badRequest("MaxMind credentials are required before downloading GeoIP data");
11788
12140
  }
@@ -11794,6 +12146,13 @@ var require_geoip = __commonJS({
11794
12146
  "[magic-sessionmanager/geoip] GeoIP download failed:",
11795
12147
  error?.name || "Error"
11796
12148
  );
12149
+ if (error?.httpStatus === 401 || error?.httpStatus === 403) {
12150
+ return sendServerError(
12151
+ ctx,
12152
+ 502,
12153
+ "MaxMind refused the download. Check the credentials and that your account includes this database."
12154
+ );
12155
+ }
11797
12156
  return sendServerError(ctx, 502, "Error updating GeoIP database");
11798
12157
  }
11799
12158
  invalidateSettingsCache();
@@ -11810,6 +12169,7 @@ var require_geoip = __commonJS({
11810
12169
  }
11811
12170
  },
11812
12171
  __private: {
12172
+ buildRiskUpdaterConfig,
11813
12173
  buildUpdaterConfig,
11814
12174
  getCredentialSource,
11815
12175
  getStoredCredentials,
@@ -12816,9 +13176,12 @@ var require_session2 = __commonJS({
12816
13176
  country_flag: geoData.country_flag,
12817
13177
  city: geoData.city,
12818
13178
  region: geoData.region,
12819
- timezone: geoData.timezone
13179
+ timezone: geoData.timezone,
13180
+ // Marks the stored score as real risk data; without a
13181
+ // risk source the score is null (not a fake 100).
13182
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
12820
13183
  } : null,
12821
- securityScore: geoData?.securityScore ?? null
13184
+ securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
12822
13185
  }
12823
13186
  });
12824
13187
  log.info("[SUCCESS] End-user session metadata created");
@@ -13688,7 +14051,12 @@ var require_geolocation = __commonJS({
13688
14051
  var path = __require("node:path");
13689
14052
  var { getPluginSettings } = require_settings_loader();
13690
14053
  var { getCoordinator, hashedKey } = require_coordination();
13691
- var { resolveDatabaseTarget } = require_geoip_updater();
14054
+ var {
14055
+ DEFAULT_GEOIP_DIRECTORY,
14056
+ resolveDatabaseTarget
14057
+ } = require_geoip_updater();
14058
+ var { calculateSecurityScore, getRiskLevel, noRiskData } = require_risk_data();
14059
+ var { lookupRiskData } = require_risk_databases();
13692
14060
  var GEO_API_TIMEOUT_MS = 4e3;
13693
14061
  var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
13694
14062
  var IPAPI_FAILURE_CACHE_TTL_MS = 5 * 60 * 1e3;
@@ -13718,11 +14086,24 @@ var require_geolocation = __commonJS({
13718
14086
  function uniqueValues(values) {
13719
14087
  return [...new Set(values.filter(Boolean))];
13720
14088
  }
14089
+ function resolveConfiguredCandidates(value) {
14090
+ if (typeof value !== "string" || value.trim() === "") return [];
14091
+ const trimmed = value.trim();
14092
+ if (path.isAbsolute(trimmed)) return [trimmed];
14093
+ const isBareName = trimmed !== "." && trimmed !== ".." && !/[\\/]/.test(trimmed) && !trimmed.includes("\0");
14094
+ if (isBareName) {
14095
+ return uniqueValues([
14096
+ path.join(DEFAULT_GEOIP_DIRECTORY, trimmed),
14097
+ path.resolve(process.cwd(), trimmed)
14098
+ ]);
14099
+ }
14100
+ return [path.resolve(process.cwd(), trimmed)];
14101
+ }
13721
14102
  function resolveDatabaseCandidates(settings = {}) {
13722
- const configured = normalizeDatabasePath(
14103
+ const configured = resolveConfiguredCandidates(
13723
14104
  settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOIP_DATABASE_PATH
13724
14105
  );
13725
- if (configured) return [configured];
14106
+ if (configured.length > 0) return configured;
13726
14107
  return uniqueValues([
13727
14108
  normalizeDatabasePath(process.env.GEOLITE2_CITY_MMDB),
13728
14109
  normalizeDatabasePath(process.env.GEOIP_CITY_DATABASE_PATH),
@@ -13741,7 +14122,11 @@ var require_geolocation = __commonJS({
13741
14122
  return readerCache.get(databasePath);
13742
14123
  }
13743
14124
  const { Reader } = __require("@maxmind/geoip2-node");
13744
- const readerPromise = Reader.open(databasePath, { watchForUpdates: true });
14125
+ const readerPromise = Reader.open(databasePath, {
14126
+ watchForUpdates: true,
14127
+ // Reloads a replaced file without keeping the process alive on its own.
14128
+ watchForUpdatesNonPersistent: true
14129
+ });
13745
14130
  readerCache.set(databasePath, readerPromise);
13746
14131
  try {
13747
14132
  return await readerPromise;
@@ -13894,13 +14279,8 @@ var require_geolocation = __commonJS({
13894
14279
  org: null,
13895
14280
  asn: null,
13896
14281
  network: data.traits?.network || null,
13897
- isVpn: false,
13898
- isProxy: false,
13899
- isThreat: false,
13900
- isAnonymous: false,
13901
- isTor: false,
13902
- securityScore: 100,
13903
- riskLevel: "Low",
14282
+ // A location database has no VPN, proxy or Tor data: no risk data here.
14283
+ ...noRiskData(),
13904
14284
  _status: "ok",
13905
14285
  _source: "local-mmdb",
13906
14286
  _databaseType: "country"
@@ -13925,13 +14305,8 @@ var require_geolocation = __commonJS({
13925
14305
  org: null,
13926
14306
  asn: null,
13927
14307
  network: data.traits?.network || null,
13928
- isVpn: false,
13929
- isProxy: false,
13930
- isThreat: false,
13931
- isAnonymous: false,
13932
- isTor: false,
13933
- securityScore: 100,
13934
- riskLevel: "Low",
14308
+ // A location database has no VPN, proxy or Tor data: no risk data here.
14309
+ ...noRiskData(),
13935
14310
  _status: "ok",
13936
14311
  _source: "local-mmdb",
13937
14312
  _databaseType: "city"
@@ -14027,10 +14402,7 @@ var require_geolocation = __commonJS({
14027
14402
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
14028
14403
  latitude: null,
14029
14404
  longitude: null,
14030
- isVpn: false,
14031
- isProxy: false,
14032
- isThreat: false,
14033
- securityScore: 100,
14405
+ ...noRiskData(),
14034
14406
  riskLevel: "None",
14035
14407
  _status: "private",
14036
14408
  _source: "local"
@@ -14045,21 +14417,53 @@ var require_geolocation = __commonJS({
14045
14417
  return this.getFallbackData(lookupIp, "disabled", "disabled");
14046
14418
  }
14047
14419
  if (provider === "local-mmdb") {
14048
- return this.getLocalMmdbIpInfo(lookupIp, settings);
14420
+ return this.withRiskData(await this.getLocalMmdbIpInfo(lookupIp, settings), lookupIp);
14049
14421
  }
14050
14422
  if (provider === "auto") {
14051
14423
  const databasePath = resolveExistingDatabasePath(settings);
14052
14424
  if (databasePath && fs.existsSync(databasePath)) {
14053
14425
  const localResult = await this.getLocalMmdbIpInfo(lookupIp, settings);
14054
14426
  if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
14055
- return localResult;
14427
+ return this.withRiskData(localResult, lookupIp);
14056
14428
  }
14057
14429
  strapi2.log.warn(
14058
14430
  "[magic-sessionmanager/geolocation] Local MMDB lookup failed, falling back to ipapi.co"
14059
14431
  );
14060
14432
  }
14061
14433
  }
14062
- return this.getIpapiIpInfo(lookupIp);
14434
+ return this.withRiskData(await this.getIpapiIpInfo(lookupIp), lookupIp);
14435
+ },
14436
+ /**
14437
+ * Adds risk data (VPN, proxy, Tor, hosting) from the local risk databases
14438
+ * to a location result. Location providers have none; without a risk
14439
+ * database the result keeps noRiskData(). The lookup is local, so no
14440
+ * address leaves the server. The ASN database also fills `asn` and `org`
14441
+ * when the location provider gave none.
14442
+ *
14443
+ * @param {object} result Location lookup result.
14444
+ * @param {string} lookupIp Normalized, validated IP address.
14445
+ * @returns {Promise<object>} Result with risk fields.
14446
+ */
14447
+ async withRiskData(result, lookupIp) {
14448
+ if (!result || typeof result !== "object") return result;
14449
+ try {
14450
+ const { asn, org, ...risk } = await lookupRiskData(lookupIp);
14451
+ if (risk._riskStatus === "error") {
14452
+ strapi2.log.warn("[magic-sessionmanager/geolocation] Risk database lookup failed");
14453
+ }
14454
+ return {
14455
+ ...result,
14456
+ ...risk,
14457
+ ...asn && !result.asn ? { asn } : {},
14458
+ ...org && !result.org ? { org } : {}
14459
+ };
14460
+ } catch (error) {
14461
+ strapi2.log.warn(
14462
+ "[magic-sessionmanager/geolocation] Risk database lookup failed:",
14463
+ error?.name || "Error"
14464
+ );
14465
+ return { ...result, ...noRiskData(), _riskStatus: "error" };
14466
+ }
14063
14467
  },
14064
14468
  /**
14065
14469
  * Reads effective GEOIP provider settings.
@@ -14231,23 +14635,9 @@ var require_geolocation = __commonJS({
14231
14635
  postal: data.postal,
14232
14636
  org: data.org,
14233
14637
  asn: data.asn,
14234
- isVpn: data.threat?.is_vpn || false,
14235
- isProxy: data.threat?.is_proxy || false,
14236
- isThreat: data.threat?.is_threat || false,
14237
- isAnonymous: data.threat?.is_anonymous || false,
14238
- isTor: data.threat?.is_tor || false,
14239
- securityScore: this.calculateSecurityScore({
14240
- isVpn: data.threat?.is_vpn,
14241
- isProxy: data.threat?.is_proxy,
14242
- isThreat: data.threat?.is_threat,
14243
- isAnonymous: data.threat?.is_anonymous,
14244
- isTor: data.threat?.is_tor
14245
- }),
14246
- riskLevel: this.getRiskLevel({
14247
- isVpn: data.threat?.is_vpn,
14248
- isProxy: data.threat?.is_proxy,
14249
- isThreat: data.threat?.is_threat
14250
- }),
14638
+ // ipapi.co documents no VPN, proxy or threat fields
14639
+ // (https://ipapi.co/api/), so its answer carries no risk data.
14640
+ ...noRiskData(),
14251
14641
  _status: "ok",
14252
14642
  _source: "ipapi"
14253
14643
  };
@@ -14280,25 +14670,16 @@ var require_geolocation = __commonJS({
14280
14670
  * @param {object} flags
14281
14671
  * @returns {number}
14282
14672
  */
14283
- calculateSecurityScore({ isVpn, isProxy, isThreat, isAnonymous, isTor }) {
14284
- let score = 100;
14285
- if (isTor) score -= 50;
14286
- if (isThreat) score -= 40;
14287
- if (isVpn) score -= 20;
14288
- if (isProxy) score -= 15;
14289
- if (isAnonymous) score -= 10;
14290
- return Math.max(0, score);
14673
+ calculateSecurityScore(flags) {
14674
+ return calculateSecurityScore(flags || {});
14291
14675
  },
14292
14676
  /**
14293
- * Maps threat indicators to a human-readable risk level.
14677
+ * Maps risk indicators to a human-readable risk level.
14294
14678
  * @param {object} flags
14295
14679
  * @returns {string}
14296
14680
  */
14297
- getRiskLevel({ isVpn, isProxy, isThreat }) {
14298
- if (isThreat) return "High";
14299
- if (isVpn && isProxy) return "Medium-High";
14300
- if (isVpn || isProxy) return "Medium";
14301
- return "Low";
14681
+ getRiskLevel(flags) {
14682
+ return getRiskLevel(flags || {});
14302
14683
  },
14303
14684
  /**
14304
14685
  * Converts a 2-letter ISO country code into a flag emoji.
@@ -14349,11 +14730,7 @@ var require_geolocation = __commonJS({
14349
14730
  timezone: "Unknown",
14350
14731
  latitude: null,
14351
14732
  longitude: null,
14352
- isVpn: false,
14353
- isProxy: false,
14354
- isThreat: false,
14355
- securityScore: 50,
14356
- riskLevel: "Unknown",
14733
+ ...noRiskData(),
14357
14734
  _status: reason,
14358
14735
  _source: source,
14359
14736
  _reason: detail
@@ -14376,6 +14753,21 @@ var require_geolocation = __commonJS({
14376
14753
  var require_notifications = __commonJS({
14377
14754
  "server/src/services/notifications.js"(exports, module) {
14378
14755
  "use strict";
14756
+ var { hasRiskData } = require_risk_data();
14757
+ function getRiskWarnings(geoData) {
14758
+ if (!hasRiskData(geoData)) return [];
14759
+ const warnings = [];
14760
+ if (geoData.isVpn) warnings.push("VPN");
14761
+ if (geoData.isProxy) warnings.push("Proxy");
14762
+ if (geoData.isTor) warnings.push("Tor");
14763
+ if (geoData.isHosting) {
14764
+ warnings.push(
14765
+ geoData.riskSource === "asn-heuristic" ? "Hosting (ASN heuristic)" : "Hosting provider"
14766
+ );
14767
+ }
14768
+ if (geoData.isThreat) warnings.push("Threat");
14769
+ return warnings;
14770
+ }
14379
14771
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
14380
14772
  var WEBHOOK_TIMEOUT_MS = 5e3;
14381
14773
  module.exports = ({ strapi: strapi2 }) => ({
@@ -14521,9 +14913,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
14521
14913
  result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
14522
14914
  result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
14523
14915
  result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
14916
+ const score = data.reason?.securityScore;
14524
14917
  result = result.replace(
14525
14918
  /\{\{reason\.securityScore\}\}/g,
14526
- esc(String(data.reason?.securityScore || "0"))
14919
+ esc(typeof score === "number" && Number.isFinite(score) ? String(score) : "N/A")
14527
14920
  );
14528
14921
  return result;
14529
14922
  },
@@ -14704,11 +15097,8 @@ ${session.loginTime ? new Date(session.loginTime).toLocaleString() : "-"}`
14704
15097
  text: `*Location*
14705
15098
  ${locationFlag}${geoData.city || "?"}, ${geoData.country || "?"}`
14706
15099
  });
14707
- if (geoData.isVpn || geoData.isProxy || geoData.isThreat) {
14708
- const warnings = [];
14709
- if (geoData.isVpn) warnings.push("VPN");
14710
- if (geoData.isProxy) warnings.push("Proxy");
14711
- if (geoData.isThreat) warnings.push("Threat");
15100
+ const warnings = getRiskWarnings(geoData);
15101
+ if (warnings.length > 0) {
14712
15102
  fields.push({
14713
15103
  type: "mrkdwn",
14714
15104
  text: `*Security*
@@ -14777,11 +15167,8 @@ ${user.username || "N/A"}`, inline: true },
14777
15167
  value: `${geoData.country_flag || ""} ${geoData.city}, ${geoData.country}`,
14778
15168
  inline: true
14779
15169
  });
14780
- if (geoData.isVpn || geoData.isProxy || geoData.isThreat) {
14781
- const warnings = [];
14782
- if (geoData.isVpn) warnings.push("VPN");
14783
- if (geoData.isProxy) warnings.push("Proxy");
14784
- if (geoData.isThreat) warnings.push("Threat");
15170
+ const warnings = getRiskWarnings(geoData);
15171
+ if (warnings.length > 0) {
14785
15172
  embed.fields.push({
14786
15173
  name: "[WARNING] Security",
14787
15174
  value: `${warnings.join(", ")} detected