strapi-plugin-magic-sessionmanager 4.14.3 → 4.16.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 +87 -0
  2. package/README.md +216 -85
  3. package/dist/admin/{Analytics-CFEgpg-G.mjs → Analytics-D4gsVwL0.mjs} +1 -1
  4. package/dist/admin/{Analytics-DSpn7W5A.js → Analytics-me4qzS0I.js} +1 -1
  5. package/dist/admin/{App-BBne8xI6.mjs → App-BJwtFWxl.mjs} +921 -106
  6. package/dist/admin/{App-UlRrLKcx.js → App-BTG-2Q26.js} +920 -105
  7. package/dist/admin/{OnlineUsersWidget-GFcYyZ9L.js → OnlineUsersWidget-DYS3Vy1Q.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-C3YMTEGD.mjs → OnlineUsersWidget-Yd283YDy.mjs} +1 -1
  9. package/dist/admin/{Settings-BbUNvjno.mjs → Settings-DIlvfdjZ.mjs} +427 -83
  10. package/dist/admin/{Settings-DVhW9XHB.js → Settings-TPZ9_75s.js} +425 -81
  11. package/dist/admin/{de-B0CBR1Dw.js → de-BuMw1gBJ.js} +130 -8
  12. package/dist/admin/{de-BlKn1pSD.mjs → de-DB9ldYwN.mjs} +130 -8
  13. package/dist/admin/{en-IT0YTY8f.mjs → en-BbLMPQB3.mjs} +130 -8
  14. package/dist/admin/{en-D0ZGIIjz.js → en-BqGhOJDy.js} +130 -8
  15. package/dist/admin/{es-CWee-XCR.js → es-BaIeckl9.js} +130 -8
  16. package/dist/admin/{es-BCGzaaCh.mjs → es-C5iaiE9G.mjs} +130 -8
  17. package/dist/admin/{fr-xBIH4Byq.mjs → fr-BEvBUCwI.mjs} +130 -8
  18. package/dist/admin/{fr-rQS1M7jE.js → fr-D1YKyTex.js} +130 -8
  19. package/dist/admin/{index-1KmiZSfy.js → index-CgZiLcJ1.js} +13 -10
  20. package/dist/admin/{index-MOJkFXcZ.mjs → index-DUESEUaO.mjs} +13 -10
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +1 -1
  23. package/dist/admin/{pt-DWDeIDVa.mjs → pt-DeDih9cR.mjs} +130 -8
  24. package/dist/admin/{pt-C-yTLhnS.js → pt-DtnW-s0V.js} +130 -8
  25. package/dist/admin/riskData-BVs9GpgD.js +26 -0
  26. package/dist/admin/riskData-CI1gm2yI.mjs +27 -0
  27. package/dist/server/index.js +2500 -299
  28. package/dist/server/index.mjs +2500 -299
  29. package/package.json +1 -1
  30. package/scripts/geoip-updater.cjs +58 -15
@@ -936,6 +936,16 @@ var require_register = __commonJS({
936
936
  uid: "admin-sessions.revoke",
937
937
  subCategory: "Admin panel",
938
938
  pluginName: "magic-sessionmanager"
939
+ },
940
+ // Admin sign-in history and Content Manager activity (4.15): who signed
941
+ // in from where and what each admin did. Separate from reading the
942
+ // sessions, because it shows IP addresses and work activity.
943
+ {
944
+ section: "plugins",
945
+ displayName: "View admin activity",
946
+ uid: "admin-activity.read",
947
+ subCategory: "Admin panel",
948
+ pluginName: "magic-sessionmanager"
939
949
  }
940
950
  ]);
941
951
  try {
@@ -1229,6 +1239,7 @@ var require_settings_loader = __commonJS({
1229
1239
  var cachedAt = 0;
1230
1240
  var cachedRevision = null;
1231
1241
  var revisionCheckedAt = 0;
1242
+ var generation = 0;
1232
1243
  function toIntInRange(value, fallback, min, max) {
1233
1244
  const n = Number.parseInt(value, 10);
1234
1245
  if (!Number.isFinite(n)) return fallback;
@@ -1294,7 +1305,12 @@ var require_settings_loader = __commonJS({
1294
1305
  // Opt-in: use a single-statement SQL UPDATE in the cleanup job instead
1295
1306
  // of batching via the Document Service. Bypasses lifecycle hooks but
1296
1307
  // drains the backlog in one query on very large installations.
1297
- "cleanupUseDbDirect"
1308
+ "cleanupUseDbDirect",
1309
+ // Security event log (4.15).
1310
+ "adminSignInHistory",
1311
+ "adminContentActivity",
1312
+ "securityLogStoreIp",
1313
+ "securityLogAnonymizeIp"
1298
1314
  ];
1299
1315
  if (stored.sessionCreationGraceMs !== void 0) {
1300
1316
  out.sessionCreationGraceMs = getSessionCreationGraceMs(stored);
@@ -1335,6 +1351,9 @@ var require_settings_loader = __commonJS({
1335
1351
  if (stored.emailTemplates && typeof stored.emailTemplates === "object") {
1336
1352
  out.emailTemplates = stored.emailTemplates;
1337
1353
  }
1354
+ if (stored.securityLogRetentionDays !== void 0) {
1355
+ out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 1, 730);
1356
+ }
1338
1357
  if (stored.trustedProxies !== void 0) {
1339
1358
  out.trustedProxies = stored.trustedProxies;
1340
1359
  }
@@ -1354,6 +1373,7 @@ var require_settings_loader = __commonJS({
1354
1373
  }
1355
1374
  if (revision2 === cachedRevision) return cached;
1356
1375
  }
1376
+ const loadGeneration = generation;
1357
1377
  let revision;
1358
1378
  try {
1359
1379
  revision = await coordinator.getRevision(SETTINGS_REVISION);
@@ -1373,6 +1393,7 @@ var require_settings_loader = __commonJS({
1373
1393
  storedSettings = { strictSessionEnforcement: true, enableGeolocation: false };
1374
1394
  }
1375
1395
  const merged = { ...staticConfig, ...storedSettings };
1396
+ if (loadGeneration !== generation) return merged;
1376
1397
  cached = merged;
1377
1398
  cachedAt = now;
1378
1399
  cachedRevision = revision;
@@ -1383,7 +1404,11 @@ var require_settings_loader = __commonJS({
1383
1404
  if (cached) return cached;
1384
1405
  return strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
1385
1406
  }
1407
+ function peekCachedSettings() {
1408
+ return cached;
1409
+ }
1386
1410
  function invalidateSettingsCache() {
1411
+ generation += 1;
1387
1412
  cached = null;
1388
1413
  cachedAt = 0;
1389
1414
  cachedRevision = null;
@@ -1407,6 +1432,7 @@ var require_settings_loader = __commonJS({
1407
1432
  module2.exports = {
1408
1433
  getPluginSettings,
1409
1434
  getPluginSettingsSync,
1435
+ peekCachedSettings,
1410
1436
  invalidateSettingsCache,
1411
1437
  notifySettingsChanged,
1412
1438
  getSettingsRevision,
@@ -1473,10 +1499,75 @@ var require_rejection_cache = __commonJS({
1473
1499
  }
1474
1500
  });
1475
1501
 
1502
+ // server/src/utils/risk-data.js
1503
+ var require_risk_data = __commonJS({
1504
+ "server/src/utils/risk-data.js"(exports2, module2) {
1505
+ "use strict";
1506
+ var RISK_SOURCES = Object.freeze(["anonymous-ip", "asn-heuristic"]);
1507
+ var SUSPICIOUS_SCORE_BELOW = 70;
1508
+ var REJECT_SCORE_BELOW = 50;
1509
+ function noRiskData() {
1510
+ return {
1511
+ isVpn: false,
1512
+ isProxy: false,
1513
+ isThreat: false,
1514
+ isAnonymous: false,
1515
+ isTor: false,
1516
+ isHosting: false,
1517
+ securityScore: null,
1518
+ riskLevel: "Unknown",
1519
+ riskSource: null
1520
+ };
1521
+ }
1522
+ function hasRiskData(geoData) {
1523
+ return Boolean(geoData) && RISK_SOURCES.includes(geoData.riskSource);
1524
+ }
1525
+ function calculateSecurityScore({ isVpn, isProxy, isThreat, isAnonymous, isTor, isHosting }) {
1526
+ let score = 100;
1527
+ if (isTor) score -= 50;
1528
+ if (isThreat) score -= 40;
1529
+ if (isVpn) score -= 20;
1530
+ if (isHosting) score -= 20;
1531
+ if (isProxy) score -= 15;
1532
+ if (isAnonymous) score -= 10;
1533
+ return Math.max(0, score);
1534
+ }
1535
+ function getRiskLevel({ isVpn, isProxy, isThreat, isTor, isHosting }) {
1536
+ if (isThreat || isTor) return "High";
1537
+ if (isVpn && isProxy) return "Medium-High";
1538
+ if (isVpn || isProxy || isHosting) return "Medium";
1539
+ return "Low";
1540
+ }
1541
+ function evaluateLoginRisk(settings = {}, geoData = null) {
1542
+ if (!hasRiskData(geoData)) {
1543
+ return { hasRiskData: false, isSuspicious: false, isVpnOrProxy: false };
1544
+ }
1545
+ const scoreEvaluationEnabled = settings.enableSecurityScoring !== false;
1546
+ const lowScore = scoreEvaluationEnabled && typeof geoData.securityScore === "number" && geoData.securityScore < SUSPICIOUS_SCORE_BELOW;
1547
+ const isVpnOrProxy = Boolean(geoData.isVpn || geoData.isProxy);
1548
+ const isSuspicious = Boolean(
1549
+ isVpnOrProxy || geoData.isThreat || geoData.isTor || geoData.isHosting || lowScore
1550
+ );
1551
+ return { hasRiskData: true, isSuspicious, isVpnOrProxy };
1552
+ }
1553
+ module2.exports = {
1554
+ REJECT_SCORE_BELOW,
1555
+ RISK_SOURCES,
1556
+ SUSPICIOUS_SCORE_BELOW,
1557
+ calculateSecurityScore,
1558
+ evaluateLoginRisk,
1559
+ getRiskLevel,
1560
+ hasRiskData,
1561
+ noRiskData
1562
+ };
1563
+ }
1564
+ });
1565
+
1476
1566
  // server/src/utils/geo-firewall.js
1477
1567
  var require_geo_firewall = __commonJS({
1478
1568
  "server/src/utils/geo-firewall.js"(exports2, module2) {
1479
1569
  "use strict";
1570
+ var { REJECT_SCORE_BELOW, hasRiskData } = require_risk_data();
1480
1571
  function normalizeCountryCode(value) {
1481
1572
  if (typeof value !== "string") return null;
1482
1573
  const normalized = value.trim().toUpperCase();
@@ -1496,27 +1587,20 @@ var require_geo_firewall = __commonJS({
1496
1587
  if (status === "private") {
1497
1588
  return { blocked: false, reason: null, status };
1498
1589
  }
1499
- if (status !== "ok") {
1500
- if (getLookupFailureMode(settings) === "block") {
1501
- return {
1502
- blocked: true,
1503
- reason: `geo_lookup_unavailable:${status}`,
1504
- status
1505
- };
1506
- }
1507
- return { blocked: false, reason: null, status };
1508
- }
1509
- if (settings.blockSuspiciousSessions) {
1590
+ if (settings.blockSuspiciousSessions && hasRiskData(geoData)) {
1510
1591
  if (geoData.isThreat) {
1511
1592
  return { blocked: true, reason: "threat_ip", status };
1512
1593
  }
1594
+ if (geoData.isTor) {
1595
+ return { blocked: true, reason: "tor_exit_node", status };
1596
+ }
1513
1597
  if (geoData.isVpn) {
1514
1598
  return { blocked: true, reason: "vpn_detected", status };
1515
1599
  }
1516
1600
  if (geoData.isProxy) {
1517
1601
  return { blocked: true, reason: "proxy_detected", status };
1518
1602
  }
1519
- if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < 50) {
1603
+ if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < REJECT_SCORE_BELOW) {
1520
1604
  return {
1521
1605
  blocked: true,
1522
1606
  reason: `low_security_score:${geoData.securityScore}`,
@@ -1524,6 +1608,16 @@ var require_geo_firewall = __commonJS({
1524
1608
  };
1525
1609
  }
1526
1610
  }
1611
+ if (status !== "ok") {
1612
+ if (getLookupFailureMode(settings) === "block") {
1613
+ return {
1614
+ blocked: true,
1615
+ reason: `geo_lookup_unavailable:${status}`,
1616
+ status
1617
+ };
1618
+ }
1619
+ return { blocked: false, reason: null, status };
1620
+ }
1527
1621
  if (settings.enableGeofencing) {
1528
1622
  const countryCode = normalizeCountryCode(geoData.country_code);
1529
1623
  const blockedCountries = normalizeCountryList(settings.blockedCountries);
@@ -1553,6 +1647,93 @@ var require_geo_firewall = __commonJS({
1553
1647
  }
1554
1648
  });
1555
1649
 
1650
+ // server/src/utils/login-alerts.js
1651
+ var require_login_alerts = __commonJS({
1652
+ "server/src/utils/login-alerts.js"(exports2, module2) {
1653
+ "use strict";
1654
+ var { evaluateLoginRisk } = require_risk_data();
1655
+ async function dispatchLoginAlerts({
1656
+ settings,
1657
+ notificationService,
1658
+ user,
1659
+ session,
1660
+ geoData,
1661
+ isNewLocation = false
1662
+ }) {
1663
+ const attempted = { webhookEvent: null, emails: [] };
1664
+ if (!geoData) return attempted;
1665
+ const risk = evaluateLoginRisk(settings, geoData);
1666
+ if (settings.enableEmailAlerts) {
1667
+ if (settings.alertOnVpnProxy && risk.isVpnOrProxy) {
1668
+ attempted.emails.push("vpnProxy");
1669
+ await notificationService.sendVpnProxyAlert({
1670
+ user,
1671
+ session,
1672
+ reason: { isVpn: geoData.isVpn, isProxy: geoData.isProxy },
1673
+ geoData
1674
+ });
1675
+ }
1676
+ if (settings.alertOnSuspiciousLogin && risk.isSuspicious) {
1677
+ attempted.emails.push("suspiciousLogin");
1678
+ await notificationService.sendSuspiciousLoginAlert({
1679
+ user,
1680
+ session,
1681
+ reason: {
1682
+ isVpn: geoData.isVpn,
1683
+ isProxy: geoData.isProxy,
1684
+ isThreat: geoData.isThreat,
1685
+ securityScore: geoData.securityScore
1686
+ },
1687
+ geoData
1688
+ });
1689
+ }
1690
+ if (settings.alertOnNewLocation && isNewLocation) {
1691
+ attempted.emails.push("newLocation");
1692
+ await notificationService.sendNewLocationAlert({ user, session, geoData });
1693
+ }
1694
+ }
1695
+ if (settings.enableWebhooks) {
1696
+ const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
1697
+ attempted.webhookEvent = webhookEvent;
1698
+ const targets = [];
1699
+ if (settings.discordWebhookUrl) {
1700
+ targets.push({
1701
+ url: settings.discordWebhookUrl,
1702
+ payload: notificationService.formatDiscordWebhook({
1703
+ event: webhookEvent,
1704
+ session,
1705
+ user,
1706
+ geoData
1707
+ })
1708
+ });
1709
+ }
1710
+ if (settings.slackWebhookUrl) {
1711
+ targets.push({
1712
+ url: settings.slackWebhookUrl,
1713
+ payload: notificationService.formatSlackWebhook({
1714
+ event: webhookEvent,
1715
+ session,
1716
+ user,
1717
+ geoData
1718
+ })
1719
+ });
1720
+ }
1721
+ await Promise.allSettled(
1722
+ targets.map(
1723
+ (target) => notificationService.sendWebhook({
1724
+ event: webhookEvent,
1725
+ data: target.payload,
1726
+ webhookUrl: target.url
1727
+ })
1728
+ )
1729
+ );
1730
+ }
1731
+ return attempted;
1732
+ }
1733
+ module2.exports = { dispatchLoginAlerts };
1734
+ }
1735
+ });
1736
+
1556
1737
  // server/src/utils/session-revocation.js
1557
1738
  var require_session_revocation = __commonJS({
1558
1739
  "server/src/utils/session-revocation.js"(exports2, module2) {
@@ -2290,6 +2471,800 @@ var require_native_only_insight = __commonJS({
2290
2471
  }
2291
2472
  });
2292
2473
 
2474
+ // server/src/utils/security-log-model.js
2475
+ var require_security_log_model = __commonJS({
2476
+ "server/src/utils/security-log-model.js"(exports2, module2) {
2477
+ "use strict";
2478
+ var SECURITY_EVENTS = Object.freeze({
2479
+ ADMIN_SIGN_IN: "admin.sign-in",
2480
+ ADMIN_SIGN_IN_FAILED: "admin.sign-in.failed",
2481
+ ADMIN_LOCKOUT: "admin.lockout",
2482
+ ADMIN_SIGN_OUT: "admin.sign-out",
2483
+ ADMIN_SESSION_REVOKED: "admin.session.revoked",
2484
+ ADMIN_CONTENT_VIEW: "admin.content.view",
2485
+ ADMIN_CONTENT_CREATE: "admin.content.create",
2486
+ ADMIN_CONTENT_UPDATE: "admin.content.update",
2487
+ ADMIN_CONTENT_PUBLISH: "admin.content.publish",
2488
+ ADMIN_CONTENT_UNPUBLISH: "admin.content.unpublish",
2489
+ ADMIN_CONTENT_DISCARD: "admin.content.discard",
2490
+ ADMIN_CONTENT_DELETE: "admin.content.delete",
2491
+ ADMIN_CONTENT_CLONE: "admin.content.clone"
2492
+ });
2493
+ var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
2494
+ var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
2495
+ var ADMIN_SIGN_IN_EVENTS = Object.freeze([
2496
+ SECURITY_EVENTS.ADMIN_SIGN_IN,
2497
+ SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
2498
+ SECURITY_EVENTS.ADMIN_LOCKOUT,
2499
+ SECURITY_EVENTS.ADMIN_SIGN_OUT,
2500
+ SECURITY_EVENTS.ADMIN_SESSION_REVOKED
2501
+ ]);
2502
+ var SIGN_IN_FILTERS = Object.freeze({
2503
+ all: ADMIN_SIGN_IN_EVENTS,
2504
+ succeeded: [SECURITY_EVENTS.ADMIN_SIGN_IN],
2505
+ failed: [SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED, SECURITY_EVENTS.ADMIN_LOCKOUT],
2506
+ "signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED]
2507
+ });
2508
+ var CONTENT_ACTIONS = Object.freeze([
2509
+ "view",
2510
+ "create",
2511
+ "update",
2512
+ "publish",
2513
+ "unpublish",
2514
+ "discard",
2515
+ "delete",
2516
+ "clone"
2517
+ ]);
2518
+ var contentEvent = (action) => `admin.content.${action}`;
2519
+ var ADMIN_CONTENT_EVENTS = Object.freeze(CONTENT_ACTIONS.map(contentEvent));
2520
+ function recordingSwitchOf(event) {
2521
+ if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
2522
+ if (event.startsWith("admin.content.")) return "content";
2523
+ return "always";
2524
+ }
2525
+ var CONTENT_MANAGER_HANDLERS = Object.freeze({
2526
+ "collection-types.findOne": { action: "view", kind: "collection" },
2527
+ "collection-types.create": { action: "create", kind: "collection" },
2528
+ "collection-types.update": { action: "update", kind: "collection" },
2529
+ "collection-types.clone": { action: "clone", kind: "collection" },
2530
+ "collection-types.autoClone": { action: "clone", kind: "collection" },
2531
+ "collection-types.publish": { action: "publish", kind: "collection" },
2532
+ "collection-types.unpublish": { action: "unpublish", kind: "collection" },
2533
+ "collection-types.discard": { action: "discard", kind: "collection" },
2534
+ "collection-types.delete": { action: "delete", kind: "collection" },
2535
+ "collection-types.bulkDelete": { action: "delete", kind: "collection", bulk: true },
2536
+ "collection-types.bulkPublish": { action: "publish", kind: "collection", bulk: true },
2537
+ "collection-types.bulkUnpublish": { action: "unpublish", kind: "collection", bulk: true },
2538
+ "single-types.find": { action: "view", kind: "single" },
2539
+ "single-types.createOrUpdate": { action: "update", kind: "single" },
2540
+ "single-types.delete": { action: "delete", kind: "single" },
2541
+ "single-types.publish": { action: "publish", kind: "single" },
2542
+ "single-types.unpublish": { action: "unpublish", kind: "single" },
2543
+ "single-types.discard": { action: "discard", kind: "single" }
2544
+ });
2545
+ var UID_PATTERN = /^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/;
2546
+ var LOCALE_PATTERN = /^[A-Za-z0-9-]{1,20}$/;
2547
+ var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
2548
+ var MAX_META_BYTES = 2048;
2549
+ var MAX_META_KEYS = 16;
2550
+ function boundMeta(meta) {
2551
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
2552
+ const out = {};
2553
+ let keys = 0;
2554
+ for (const [key, value] of Object.entries(meta)) {
2555
+ if (keys >= MAX_META_KEYS) break;
2556
+ if (!/^[a-zA-Z][a-zA-Z0-9]{0,39}$/.test(key)) continue;
2557
+ if (value === null || typeof value === "boolean") out[key] = value;
2558
+ else if (typeof value === "number" && Number.isFinite(value)) out[key] = value;
2559
+ else if (typeof value === "string") out[key] = value.slice(0, 255);
2560
+ else continue;
2561
+ keys += 1;
2562
+ }
2563
+ if (!keys) return null;
2564
+ while (JSON.stringify(out).length > MAX_META_BYTES) {
2565
+ const longest = Object.keys(out).reduce(
2566
+ (a, b) => String(out[a] ?? "").length >= String(out[b] ?? "").length ? a : b
2567
+ );
2568
+ delete out[longest];
2569
+ }
2570
+ return Object.keys(out).length ? out : null;
2571
+ }
2572
+ function handlerName(handler) {
2573
+ if (typeof handler !== "string") return null;
2574
+ const parts = handler.split(".");
2575
+ if (parts.length < 2) return null;
2576
+ const tail = parts.slice(-2).join(".");
2577
+ return tail.includes("::") ? tail.split("::").pop() || null : tail;
2578
+ }
2579
+ function shaped(value, pattern) {
2580
+ return typeof value === "string" && pattern.test(value) ? value : null;
2581
+ }
2582
+ function describeContentManagerRequest({
2583
+ status,
2584
+ route,
2585
+ params,
2586
+ query,
2587
+ requestBody,
2588
+ responseBody
2589
+ }) {
2590
+ if (!(status >= 200 && status < 300)) return null;
2591
+ if (route?.info?.pluginName !== "content-manager") return null;
2592
+ const name = handlerName(route.handler);
2593
+ const mapping = name ? (
2594
+ /** @type {any} */
2595
+ CONTENT_MANAGER_HANDLERS[name]
2596
+ ) : null;
2597
+ if (!mapping) return null;
2598
+ const contentType = shaped(params?.model, UID_PATTERN);
2599
+ if (!contentType) return null;
2600
+ const data = responseBody && typeof responseBody === "object" && !Array.isArray(responseBody) ? responseBody.data : null;
2601
+ const single = data && typeof data === "object" && !Array.isArray(data) ? data : null;
2602
+ let count = null;
2603
+ if (mapping.bulk) {
2604
+ const ids = requestBody?.documentIds;
2605
+ count = Array.isArray(ids) ? Math.min(ids.length, 1e5) : null;
2606
+ if (typeof responseBody?.data?.count === "number") count = responseBody.data.count;
2607
+ }
2608
+ const documentId = mapping.bulk ? null : shaped(params?.id, DOCUMENT_ID_PATTERN) || shaped(single?.documentId, DOCUMENT_ID_PATTERN);
2609
+ const locale = shaped(query?.locale, LOCALE_PATTERN) || shaped(single?.locale, LOCALE_PATTERN);
2610
+ return {
2611
+ action: mapping.action,
2612
+ kind: mapping.kind,
2613
+ contentType,
2614
+ documentId,
2615
+ locale,
2616
+ count,
2617
+ data: mapping.bulk ? null : single
2618
+ };
2619
+ }
2620
+ function pickEntryTitle(data, mainField) {
2621
+ if (!data || typeof data !== "object" || !mainField || mainField === "id") return null;
2622
+ const value = data[mainField];
2623
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
2624
+ if (typeof value !== "string") return null;
2625
+ const text = value.replace(/\s+/g, " ").trim();
2626
+ return text ? text.slice(0, 255) : null;
2627
+ }
2628
+ function safeReason(reason) {
2629
+ return typeof reason === "string" && /^[a-z][a-z0-9_-]{0,39}$/.test(reason) ? reason : null;
2630
+ }
2631
+ function deriveSessionStates(signIns, laterEvents, liveDevices) {
2632
+ const sorted = [...laterEvents].sort((a, b) => String(a.at).localeCompare(String(b.at)));
2633
+ const out = /* @__PURE__ */ new Map();
2634
+ for (const row of signIns) {
2635
+ if (!row.deviceHash) {
2636
+ out.set(row.id, { state: "unknown", endedAt: null, endedBy: null });
2637
+ continue;
2638
+ }
2639
+ let result = null;
2640
+ for (const event of sorted) {
2641
+ if (event.adminId !== row.adminId || String(event.at) <= String(row.at)) continue;
2642
+ const sameDevice = event.deviceHash === row.deviceHash;
2643
+ if (event.event === SECURITY_EVENTS.ADMIN_SIGN_IN && sameDevice) {
2644
+ result = { state: "ended", endedAt: null, endedBy: null };
2645
+ break;
2646
+ }
2647
+ const isEnd = event.event === SECURITY_EVENTS.ADMIN_SIGN_OUT || event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
2648
+ if (isEnd && (sameDevice || !event.deviceHash)) {
2649
+ result = {
2650
+ state: "signed-out",
2651
+ endedAt: event.at,
2652
+ endedBy: event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED ? event.actorId : null
2653
+ };
2654
+ break;
2655
+ }
2656
+ }
2657
+ if (!result) {
2658
+ const live = liveDevices.get(row.adminId);
2659
+ result = live && live.has(row.deviceHash) ? { state: "active", endedAt: null, endedBy: null } : { state: "ended", endedAt: null, endedBy: null };
2660
+ }
2661
+ out.set(row.id, result);
2662
+ }
2663
+ return out;
2664
+ }
2665
+ function toLocation(value) {
2666
+ let geo = value;
2667
+ if (typeof geo === "string") {
2668
+ try {
2669
+ geo = JSON.parse(geo);
2670
+ } catch {
2671
+ return null;
2672
+ }
2673
+ }
2674
+ if (!geo || typeof geo !== "object") return null;
2675
+ const text = (v) => typeof v === "string" && v.trim() ? v.trim().slice(0, 80) : null;
2676
+ const record = (
2677
+ /** @type {Record<string, unknown>} */
2678
+ geo
2679
+ );
2680
+ const location = {
2681
+ country: text(record.country),
2682
+ countryCode: text(record.countryCode ?? record.country_code),
2683
+ city: text(record.city)
2684
+ };
2685
+ return location.country || location.city ? location : null;
2686
+ }
2687
+ function toIso(value) {
2688
+ if (!value) return null;
2689
+ const date = value instanceof Date ? value : new Date(String(value));
2690
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
2691
+ }
2692
+ function toObject(value) {
2693
+ let parsed = value;
2694
+ if (typeof parsed === "string") {
2695
+ try {
2696
+ parsed = JSON.parse(parsed);
2697
+ } catch {
2698
+ return {};
2699
+ }
2700
+ }
2701
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2702
+ }
2703
+ module2.exports = {
2704
+ ACTOR_TYPES,
2705
+ ADMIN_CONTENT_EVENTS,
2706
+ ADMIN_SIGN_IN_EVENTS,
2707
+ CONTENT_ACTIONS,
2708
+ CONTENT_MANAGER_HANDLERS,
2709
+ EVENT_NAME_PATTERN,
2710
+ MAX_META_BYTES,
2711
+ SECURITY_EVENTS,
2712
+ SIGN_IN_FILTERS,
2713
+ boundMeta,
2714
+ contentEvent,
2715
+ deriveSessionStates,
2716
+ describeContentManagerRequest,
2717
+ handlerName,
2718
+ pickEntryTitle,
2719
+ recordingSwitchOf,
2720
+ safeReason,
2721
+ toIso,
2722
+ toLocation,
2723
+ toObject
2724
+ };
2725
+ }
2726
+ });
2727
+
2728
+ // server/src/utils/user-agent-parser.js
2729
+ var require_user_agent_parser = __commonJS({
2730
+ "server/src/utils/user-agent-parser.js"(exports2, module2) {
2731
+ "use strict";
2732
+ function parseUserAgent(userAgent) {
2733
+ if (!userAgent) {
2734
+ return {
2735
+ deviceType: "unknown",
2736
+ browserName: "unknown",
2737
+ browserVersion: null,
2738
+ osName: "unknown",
2739
+ osVersion: null
2740
+ };
2741
+ }
2742
+ let deviceType = "desktop";
2743
+ if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
2744
+ deviceType = "tablet";
2745
+ } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
2746
+ deviceType = "mobile";
2747
+ } else if (/android(?!.*mobile)/i.test(userAgent)) {
2748
+ deviceType = "tablet";
2749
+ } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
2750
+ deviceType = "bot";
2751
+ }
2752
+ let browserName = "unknown";
2753
+ let browserVersion = null;
2754
+ if (/edg\//i.test(userAgent)) {
2755
+ browserName = "Edge";
2756
+ browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
2757
+ } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
2758
+ browserName = "Opera";
2759
+ browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
2760
+ } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
2761
+ browserName = "Chrome";
2762
+ browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
2763
+ } else if (/firefox|fxios/i.test(userAgent)) {
2764
+ browserName = "Firefox";
2765
+ browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
2766
+ } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
2767
+ browserName = "Safari";
2768
+ browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
2769
+ } else if (/msie|trident/i.test(userAgent)) {
2770
+ browserName = "Internet Explorer";
2771
+ browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
2772
+ }
2773
+ let osName = "unknown";
2774
+ let osVersion = null;
2775
+ if (/windows nt/i.test(userAgent)) {
2776
+ osName = "Windows";
2777
+ const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
2778
+ const winVersionMap = {
2779
+ "10.0": "10/11",
2780
+ 6.3: "8.1",
2781
+ 6.2: "8",
2782
+ 6.1: "7",
2783
+ "6.0": "Vista",
2784
+ 5.1: "XP"
2785
+ };
2786
+ osVersion = winVersionMap[winVersion] || winVersion;
2787
+ } else if (/iphone|ipad|ipod/i.test(userAgent)) {
2788
+ osName = "iOS";
2789
+ osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
2790
+ } else if (/mac os x/i.test(userAgent)) {
2791
+ osName = "macOS";
2792
+ osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
2793
+ } else if (/android/i.test(userAgent)) {
2794
+ osName = "Android";
2795
+ osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
2796
+ } else if (/linux/i.test(userAgent)) {
2797
+ osName = "Linux";
2798
+ } else if (/cros/i.test(userAgent)) {
2799
+ osName = "Chrome OS";
2800
+ }
2801
+ return {
2802
+ deviceType,
2803
+ browserName,
2804
+ browserVersion,
2805
+ osName,
2806
+ osVersion
2807
+ };
2808
+ }
2809
+ function extractVersion(userAgent, regex) {
2810
+ const match = userAgent.match(regex);
2811
+ return match ? match[1] : null;
2812
+ }
2813
+ function getDeviceDescription(parsed) {
2814
+ const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
2815
+ const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
2816
+ return `${browser} on ${os}`;
2817
+ }
2818
+ module2.exports = {
2819
+ parseUserAgent,
2820
+ getDeviceDescription
2821
+ };
2822
+ }
2823
+ });
2824
+
2825
+ // server/src/utils/admin-request-info.js
2826
+ var require_admin_request_info = __commonJS({
2827
+ "server/src/utils/admin-request-info.js"(exports2, module2) {
2828
+ "use strict";
2829
+ var crypto = require("node:crypto");
2830
+ var net = require("node:net");
2831
+ var { parseUserAgent } = require_user_agent_parser();
2832
+ var MAX_USER_AGENT_LENGTH = 500;
2833
+ var MAX_DEVICE_ID_LENGTH = 200;
2834
+ function normalizeIp(value) {
2835
+ if (typeof value !== "string") return null;
2836
+ let ip = value.trim();
2837
+ if (!ip || ip.length > 100) return null;
2838
+ if (ip.startsWith("[")) {
2839
+ const end = ip.indexOf("]");
2840
+ ip = end === -1 ? ip.slice(1) : ip.slice(1, end);
2841
+ }
2842
+ if (/^::ffff:/i.test(ip) && net.isIPv4(ip.slice(7))) ip = ip.slice(7);
2843
+ if (ip.includes(".") && ip.split(":").length === 2) ip = ip.split(":")[0];
2844
+ const zone = ip.indexOf("%");
2845
+ if (zone !== -1) ip = ip.slice(0, zone);
2846
+ return net.isIP(ip) === 0 ? null : ip.toLowerCase();
2847
+ }
2848
+ function getRequestIp(ctx) {
2849
+ try {
2850
+ return normalizeIp(ctx?.request?.ip);
2851
+ } catch {
2852
+ return null;
2853
+ }
2854
+ }
2855
+ function ipv6Groups(ip) {
2856
+ let address = ip;
2857
+ let tail = [];
2858
+ const lastColon = address.lastIndexOf(":");
2859
+ const suffix = address.slice(lastColon + 1);
2860
+ if (net.isIPv4(suffix)) {
2861
+ const [a, b, c, d] = suffix.split(".").map(Number);
2862
+ tail = [a << 8 | b, c << 8 | d];
2863
+ address = `${address.slice(0, lastColon + 1)}0`;
2864
+ }
2865
+ const [head, rest] = address.includes("::") ? address.split("::") : [address, null];
2866
+ const left = head ? head.split(":") : [];
2867
+ const right = rest ? rest.split(":") : [];
2868
+ const fill = rest === null ? 0 : 8 - left.length - right.length;
2869
+ const groups = [...left, ...Array(Math.max(0, fill)).fill("0"), ...right].map(
2870
+ (g) => Number.parseInt(g || "0", 16)
2871
+ );
2872
+ if (tail.length) groups.splice(6, 2, ...tail);
2873
+ return groups.slice(0, 8);
2874
+ }
2875
+ function anonymizeIp(ip) {
2876
+ if (!ip) return null;
2877
+ if (net.isIPv4(ip)) {
2878
+ const parts = ip.split(".");
2879
+ return `${parts[0]}.${parts[1]}.${parts[2]}.0`;
2880
+ }
2881
+ if (net.isIPv6(ip)) {
2882
+ const groups = ipv6Groups(ip);
2883
+ return `${groups.slice(0, 3).map((group) => group.toString(16)).join(":")}::`;
2884
+ }
2885
+ return null;
2886
+ }
2887
+ function getRequestUserAgent(ctx) {
2888
+ const value = ctx?.request?.headers?.["user-agent"];
2889
+ if (typeof value !== "string" || !value.trim()) return null;
2890
+ return value.slice(0, MAX_USER_AGENT_LENGTH);
2891
+ }
2892
+ function describeUserAgent(userAgent) {
2893
+ if (!userAgent) return { browserName: null, osName: null, deviceType: null };
2894
+ const parsed = parseUserAgent(userAgent);
2895
+ const known = (value) => value && value !== "unknown" ? String(value) : null;
2896
+ const browser = known(parsed.browserName);
2897
+ const os = known(parsed.osName);
2898
+ return {
2899
+ browserName: browser ? (parsed.browserVersion ? `${browser} ${parsed.browserVersion}` : browser).slice(0, 60) : null,
2900
+ osName: os ? (parsed.osVersion ? `${os} ${parsed.osVersion}` : os).slice(0, 60) : null,
2901
+ deviceType: known(parsed.deviceType)?.slice(0, 20) || null
2902
+ };
2903
+ }
2904
+ function hashDeviceId(deviceId) {
2905
+ if (typeof deviceId !== "string" || !deviceId || deviceId.length > MAX_DEVICE_ID_LENGTH) {
2906
+ return null;
2907
+ }
2908
+ return crypto.createHash("sha256").update(deviceId).digest("hex");
2909
+ }
2910
+ module2.exports = {
2911
+ anonymizeIp,
2912
+ describeUserAgent,
2913
+ getRequestIp,
2914
+ getRequestUserAgent,
2915
+ hashDeviceId,
2916
+ normalizeIp
2917
+ };
2918
+ }
2919
+ });
2920
+
2921
+ // server/src/utils/security-log-settings.js
2922
+ var require_security_log_settings = __commonJS({
2923
+ "server/src/utils/security-log-settings.js"(exports2, module2) {
2924
+ "use strict";
2925
+ var SECURITY_LOG_DEFAULTS = Object.freeze({
2926
+ adminSignInHistory: true,
2927
+ adminContentActivity: false,
2928
+ securityLogStoreIp: true,
2929
+ securityLogAnonymizeIp: false,
2930
+ securityLogRetentionDays: 90
2931
+ });
2932
+ var SECURITY_LOG_BOOLEAN_KEYS = Object.freeze([
2933
+ "adminSignInHistory",
2934
+ "adminContentActivity",
2935
+ "securityLogStoreIp",
2936
+ "securityLogAnonymizeIp"
2937
+ ]);
2938
+ var SECURITY_LOG_RETENTION_RANGE = Object.freeze({ min: 1, max: 730 });
2939
+ var SECURITY_LOG_KEYS = Object.freeze(Object.keys(SECURITY_LOG_DEFAULTS));
2940
+ function resolveSecurityLogSettings(settings) {
2941
+ const source = settings && typeof settings === "object" ? settings : {};
2942
+ const flag = (key) => typeof source[key] === "boolean" ? (
2943
+ /** @type {boolean} */
2944
+ source[key]
2945
+ ) : (
2946
+ /** @type {any} */
2947
+ SECURITY_LOG_DEFAULTS[key]
2948
+ );
2949
+ const days = Number(source.securityLogRetentionDays);
2950
+ const { min, max } = SECURITY_LOG_RETENTION_RANGE;
2951
+ return {
2952
+ signIns: flag("adminSignInHistory"),
2953
+ content: flag("adminContentActivity"),
2954
+ storeIp: flag("securityLogStoreIp"),
2955
+ anonymizeIp: flag("securityLogAnonymizeIp"),
2956
+ retentionDays: Number.isInteger(days) && days >= min && days <= max ? days : SECURITY_LOG_DEFAULTS.securityLogRetentionDays
2957
+ };
2958
+ }
2959
+ function validateSecurityLogSettings(body) {
2960
+ const values = {};
2961
+ const errors = [];
2962
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
2963
+ for (const key of SECURITY_LOG_BOOLEAN_KEYS) {
2964
+ if (!has(key)) continue;
2965
+ if (typeof body[key] !== "boolean") {
2966
+ errors.push({ path: [key], message: `${key} must be a boolean` });
2967
+ } else {
2968
+ values[key] = /** @type {boolean} */
2969
+ body[key];
2970
+ }
2971
+ }
2972
+ if (has("securityLogRetentionDays")) {
2973
+ const raw = body.securityLogRetentionDays;
2974
+ const value = typeof raw === "number" ? raw : typeof raw === "string" && /^\s*\d+\s*$/.test(raw) ? Number.parseInt(raw, 10) : NaN;
2975
+ const { min, max } = SECURITY_LOG_RETENTION_RANGE;
2976
+ if (!Number.isInteger(value) || value < min || value > max) {
2977
+ errors.push({
2978
+ path: ["securityLogRetentionDays"],
2979
+ message: `securityLogRetentionDays must be an integer between ${min} and ${max}`
2980
+ });
2981
+ } else {
2982
+ values.securityLogRetentionDays = value;
2983
+ }
2984
+ }
2985
+ return { values, errors };
2986
+ }
2987
+ module2.exports = {
2988
+ SECURITY_LOG_BOOLEAN_KEYS,
2989
+ SECURITY_LOG_DEFAULTS,
2990
+ SECURITY_LOG_KEYS,
2991
+ SECURITY_LOG_RETENTION_RANGE,
2992
+ resolveSecurityLogSettings,
2993
+ validateSecurityLogSettings
2994
+ };
2995
+ }
2996
+ });
2997
+
2998
+ // server/src/utils/admin-activity-capture.js
2999
+ var require_admin_activity_capture = __commonJS({
3000
+ "server/src/utils/admin-activity-capture.js"(exports2, module2) {
3001
+ "use strict";
3002
+ var {
3003
+ SECURITY_EVENTS,
3004
+ describeContentManagerRequest,
3005
+ handlerName,
3006
+ safeReason
3007
+ } = require_security_log_model();
3008
+ var { getRequestIp, getRequestUserAgent } = require_admin_request_info();
3009
+ var { resolveSecurityLogSettings } = require_security_log_settings();
3010
+ var { getPluginSettings, peekCachedSettings } = require_settings_loader();
3011
+ var SERVICE = "security-log";
3012
+ var AUTH_HANDLERS = Object.freeze({
3013
+ login: "authentication.login",
3014
+ registerAdmin: "authentication.registerAdmin",
3015
+ register: "authentication.register",
3016
+ resetPassword: "authentication.resetPassword"
3017
+ });
3018
+ var SESSION_CREATING = Object.freeze({
3019
+ [AUTH_HANDLERS.registerAdmin]: "registration",
3020
+ [AUTH_HANDLERS.register]: "registration",
3021
+ [AUTH_HANDLERS.resetPassword]: "password_reset"
3022
+ });
3023
+ function peekSwitches(strapi2) {
3024
+ const cached = peekCachedSettings();
3025
+ if (!cached) {
3026
+ getPluginSettings(strapi2).catch(() => {
3027
+ });
3028
+ return null;
3029
+ }
3030
+ return resolveSecurityLogSettings(cached);
3031
+ }
3032
+ function bodyDeviceId(ctx) {
3033
+ const value = ctx?.request?.body?.deviceId;
3034
+ return typeof value === "string" && value.length > 0 && value.length <= 200 ? value : null;
3035
+ }
3036
+ function currentRequestFacts(strapi2) {
3037
+ const ctx = currentContext(strapi2);
3038
+ return {
3039
+ ip: ctx ? getRequestIp(ctx) : null,
3040
+ userAgent: ctx ? getRequestUserAgent(ctx) : null,
3041
+ deviceId: ctx ? bodyDeviceId(ctx) : null
3042
+ };
3043
+ }
3044
+ function currentContext(strapi2) {
3045
+ try {
3046
+ return strapi2.requestContext?.get?.() || null;
3047
+ } catch {
3048
+ return null;
3049
+ }
3050
+ }
3051
+ function attemptedEmailOf(ctx) {
3052
+ const email = ctx?.request?.body?.email;
3053
+ return typeof email === "string" && email.length <= 254 ? email : null;
3054
+ }
3055
+ function createCaptureMiddleware(strapi2, getService) {
3056
+ return async function adminActivityCapture(ctx, next) {
3057
+ let thrown = null;
3058
+ let result;
3059
+ try {
3060
+ result = await next();
3061
+ } catch (error) {
3062
+ thrown = error;
3063
+ }
3064
+ try {
3065
+ const route = ctx.state?.route;
3066
+ const plugin = route?.info?.pluginName;
3067
+ if (plugin === "content-manager") {
3068
+ if (!thrown) observeContentManager(strapi2, getService, ctx, route);
3069
+ } else if (plugin === "admin") {
3070
+ observeAuthentication(strapi2, getService, ctx, route, thrown);
3071
+ }
3072
+ } catch {
3073
+ }
3074
+ if (thrown) throw thrown;
3075
+ return result;
3076
+ };
3077
+ }
3078
+ function observeContentManager(strapi2, getService, ctx, route) {
3079
+ const adminId = ctx.state?.user?.id;
3080
+ const strategy = ctx.state?.auth?.strategy?.name;
3081
+ if (adminId === void 0 || strategy !== "admin" && strategy !== "admin-token") return;
3082
+ const switches = peekSwitches(strapi2);
3083
+ if (switches && !switches.content) return;
3084
+ const entry = describeContentManagerRequest({
3085
+ status: ctx.status,
3086
+ route,
3087
+ params: ctx.params,
3088
+ query: ctx.query,
3089
+ requestBody: ctx.request?.body,
3090
+ responseBody: ctx.body
3091
+ });
3092
+ if (!entry) return;
3093
+ getService()?.recordContentAction({ ...entry, adminUserId: adminId });
3094
+ }
3095
+ function observeAuthentication(strapi2, getService, ctx, route, thrown) {
3096
+ const name = handlerName(route?.handler);
3097
+ if (!name || !(name === AUTH_HANDLERS.login || name in SESSION_CREATING)) return;
3098
+ const switches = peekSwitches(strapi2);
3099
+ if (switches && !switches.signIns) return;
3100
+ const error = (
3101
+ /** @type {any} */
3102
+ thrown
3103
+ );
3104
+ const status = error ? error.name === "RateLimitError" ? 429 : Number(error.status) || 500 : Number(ctx.status);
3105
+ const facts = {
3106
+ ip: getRequestIp(ctx),
3107
+ userAgent: getRequestUserAgent(ctx),
3108
+ deviceId: bodyDeviceId(ctx)
3109
+ };
3110
+ if (name === AUTH_HANDLERS.login) {
3111
+ if (status !== 429) return;
3112
+ getService()?.record({
3113
+ event: SECURITY_EVENTS.ADMIN_LOCKOUT,
3114
+ actorType: "admin",
3115
+ targetType: "admin",
3116
+ // Resolved to an existing admin in the background, then dropped.
3117
+ attemptedEmail: attemptedEmailOf(ctx),
3118
+ meta: { reason: "rate_limited", provider: "local" },
3119
+ ...facts
3120
+ });
3121
+ return;
3122
+ }
3123
+ if (status < 200 || status >= 300) return;
3124
+ const userId = ctx.body?.data?.user?.id;
3125
+ if (userId === void 0) return;
3126
+ getService()?.record({
3127
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN,
3128
+ actorType: "admin",
3129
+ actorId: userId,
3130
+ targetType: "admin",
3131
+ targetId: userId,
3132
+ meta: { reason: (
3133
+ /** @type {any} */
3134
+ SESSION_CREATING[name]
3135
+ ), provider: "local" },
3136
+ ...facts,
3137
+ // A password reset gives the browser a new device id server-side.
3138
+ deviceId: name === AUTH_HANDLERS.resetPassword ? null : facts.deviceId
3139
+ });
3140
+ }
3141
+ function installAdminActivityCapture(strapi2, { log, runExclusive }) {
3142
+ const getService = () => {
3143
+ const service = strapi2.plugin("magic-sessionmanager")?.service(SERVICE);
3144
+ return service && !service.isStopped() ? service : null;
3145
+ };
3146
+ const cleanups = [];
3147
+ const on = (event, listener) => {
3148
+ const off = strapi2.eventHub?.on?.(event, (payload) => {
3149
+ try {
3150
+ listener(payload);
3151
+ } catch {
3152
+ }
3153
+ });
3154
+ if (typeof off === "function") cleanups.push(off);
3155
+ };
3156
+ on("admin.auth.success", (payload) => {
3157
+ const switches = peekSwitches(strapi2);
3158
+ if (switches && !switches.signIns) return;
3159
+ const id = payload?.user?.id;
3160
+ getService()?.record({
3161
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN,
3162
+ actorType: "admin",
3163
+ actorId: id,
3164
+ targetType: "admin",
3165
+ targetId: id,
3166
+ meta: { provider: safeReason(payload?.provider) || "local" },
3167
+ ...currentRequestFacts(strapi2)
3168
+ });
3169
+ });
3170
+ on("admin.auth.error", (payload) => {
3171
+ const switches = peekSwitches(strapi2);
3172
+ if (switches && !switches.signIns) return;
3173
+ const id = payload?.user?.id ?? null;
3174
+ getService()?.record({
3175
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
3176
+ actorType: "admin",
3177
+ actorId: id,
3178
+ targetType: "admin",
3179
+ targetId: id,
3180
+ ...id === null ? { attemptedEmail: attemptedEmailOf(currentContext(strapi2)), actorFromEmail: true } : {},
3181
+ meta: {
3182
+ reason: safeReason(payload?.reason) || "invalid_credentials",
3183
+ provider: safeReason(payload?.provider) || "local"
3184
+ },
3185
+ ...currentRequestFacts(strapi2)
3186
+ });
3187
+ });
3188
+ on("admin.logout", (payload) => {
3189
+ const switches = peekSwitches(strapi2);
3190
+ if (switches && !switches.signIns) return;
3191
+ const id = payload?.user?.id;
3192
+ getService()?.record({
3193
+ event: SECURITY_EVENTS.ADMIN_SIGN_OUT,
3194
+ actorType: "admin",
3195
+ actorId: id,
3196
+ targetType: "admin",
3197
+ targetId: id,
3198
+ ...currentRequestFacts(strapi2)
3199
+ });
3200
+ });
3201
+ strapi2.server.use(createCaptureMiddleware(strapi2, getService));
3202
+ try {
3203
+ const unsubscribe = strapi2.db.lifecycles.subscribe({
3204
+ models: ["admin::user"],
3205
+ async afterDelete(event) {
3206
+ const id = event?.result?.id;
3207
+ if (id === void 0) return;
3208
+ try {
3209
+ await strapi2.plugin("magic-sessionmanager").service(SERVICE).deleteAdminData(id);
3210
+ } catch (err) {
3211
+ log.warn(
3212
+ "[security-log] Data of a deleted admin could not be removed:",
3213
+ err?.name || "Error"
3214
+ );
3215
+ }
3216
+ }
3217
+ });
3218
+ if (typeof unsubscribe === "function") cleanups.push(unsubscribe);
3219
+ } catch (err) {
3220
+ log.warn("[security-log] Could not watch admin deletions:", err?.name || "Error");
3221
+ }
3222
+ const jobName = "magic-sessionmanager-security-log-retention";
3223
+ const retention = async () => {
3224
+ const job = async () => {
3225
+ const service = strapi2.plugin("magic-sessionmanager").service(SERVICE);
3226
+ const removed = await service.cleanup();
3227
+ if (removed.expired || removed.orphans) {
3228
+ log.info(
3229
+ `[security-log] Retention removed ${removed.expired} expired events and ${removed.orphans} of deleted admins`
3230
+ );
3231
+ }
3232
+ };
3233
+ try {
3234
+ if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
3235
+ else await job();
3236
+ } catch (err) {
3237
+ log.warn("[security-log] Retention failed:", err?.name || "Error");
3238
+ }
3239
+ };
3240
+ try {
3241
+ strapi2.cron.add({ [jobName]: { task: retention, options: { rule: "17 3 * * *" } } });
3242
+ cleanups.push(() => strapi2.cron.remove(jobName));
3243
+ } catch (err) {
3244
+ log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
3245
+ }
3246
+ return async () => {
3247
+ for (const cleanup of cleanups.splice(0)) {
3248
+ try {
3249
+ cleanup();
3250
+ } catch {
3251
+ }
3252
+ }
3253
+ try {
3254
+ await strapi2.plugin("magic-sessionmanager")?.service(SERVICE)?.stop();
3255
+ } catch {
3256
+ }
3257
+ };
3258
+ }
3259
+ module2.exports = {
3260
+ createCaptureMiddleware,
3261
+ installAdminActivityCapture,
3262
+ observeAuthentication,
3263
+ observeContentManager
3264
+ };
3265
+ }
3266
+ });
3267
+
2293
3268
  // server/src/middlewares/session-rejection-headers.js
2294
3269
  var require_session_rejection_headers = __commonJS({
2295
3270
  "server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
@@ -6380,6 +7355,7 @@ var require_bootstrap = __commonJS({
6380
7355
  var { extractBearerToken } = require_extract_token();
6381
7356
  var { setSessionRejectionReason } = require_rejection_cache();
6382
7357
  var { evaluateGeoFirewall } = require_geo_firewall();
7358
+ var { dispatchLoginAlerts } = require_login_alerts();
6383
7359
  var { REVOCATION_UID } = require_session_revocation();
6384
7360
  var { getNativeSessionManager } = require_native_session_manager();
6385
7361
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
@@ -6412,6 +7388,7 @@ var require_bootstrap = __commonJS({
6412
7388
  isThenable
6413
7389
  } = require_native_session_capture();
6414
7390
  var { ensureNativeTrackingSince } = require_native_only_insight();
7391
+ var { installAdminActivityCapture } = require_admin_activity_capture();
6415
7392
  var SESSION_UID = "plugin::magic-sessionmanager.session";
6416
7393
  var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
6417
7394
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -6566,6 +7543,13 @@ var require_bootstrap = __commonJS({
6566
7543
  log.info("[SUCCESS] Session-rejection-headers middleware mounted");
6567
7544
  strapi2.server.use(require_last_seen()({ strapi: strapi2, sessionService }));
6568
7545
  log.info("[SUCCESS] LastSeen middleware mounted");
7546
+ strapi2.sessionManagerAdminActivityUninstall = installAdminActivityCapture(strapi2, {
7547
+ log,
7548
+ runExclusive: async (name, leaseMs, job) => {
7549
+ if (await coordinator.tryAcquireLease(name, leaseMs)) await job();
7550
+ }
7551
+ });
7552
+ log.info("[SUCCESS] Admin activity capture mounted");
6569
7553
  const contentApiPermissionsReady = await ensureContentApiPermissions(strapi2, log);
6570
7554
  mountDeferredContentApiPermissionRetry({
6571
7555
  strapi: strapi2,
@@ -7122,9 +8106,6 @@ var require_bootstrap = __commonJS({
7122
8106
  return;
7123
8107
  }
7124
8108
  const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
7125
- const scoreEvaluationEnabled = settings.enableSecurityScoring !== false;
7126
- const lowScore = scoreEvaluationEnabled && typeof geoData.securityScore === "number" && geoData.securityScore < 70;
7127
- const isSuspicious = geoData.isVpn || geoData.isProxy || geoData.isThreat || lowScore;
7128
8109
  let isNewLocation = false;
7129
8110
  if (settings.alertOnNewLocation && (geoData.country_code || geoData.country)) {
7130
8111
  try {
@@ -7167,74 +8148,14 @@ var require_bootstrap = __commonJS({
7167
8148
  log.debug("New-location check failed (non-fatal):", locErr?.name || "Error");
7168
8149
  }
7169
8150
  }
7170
- if (settings.enableEmailAlerts) {
7171
- if (settings.alertOnVpnProxy && (geoData.isVpn || geoData.isProxy)) {
7172
- await notificationService.sendVpnProxyAlert({
7173
- user,
7174
- session: newSession,
7175
- reason: {
7176
- isVpn: geoData.isVpn,
7177
- isProxy: geoData.isProxy
7178
- },
7179
- geoData
7180
- });
7181
- }
7182
- if (settings.alertOnSuspiciousLogin && isSuspicious) {
7183
- await notificationService.sendSuspiciousLoginAlert({
7184
- user,
7185
- session: newSession,
7186
- reason: {
7187
- isVpn: geoData.isVpn,
7188
- isProxy: geoData.isProxy,
7189
- isThreat: geoData.isThreat,
7190
- securityScore: geoData.securityScore
7191
- },
7192
- geoData
7193
- });
7194
- }
7195
- if (settings.alertOnNewLocation && isNewLocation) {
7196
- await notificationService.sendNewLocationAlert({
7197
- user,
7198
- session: newSession,
7199
- geoData
7200
- });
7201
- }
7202
- }
7203
- if (settings.enableWebhooks) {
7204
- const webhookEvent = isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
7205
- const targets = [];
7206
- if (settings.discordWebhookUrl) {
7207
- targets.push({
7208
- url: settings.discordWebhookUrl,
7209
- payload: notificationService.formatDiscordWebhook({
7210
- event: webhookEvent,
7211
- session: newSession,
7212
- user,
7213
- geoData
7214
- })
7215
- });
7216
- }
7217
- if (settings.slackWebhookUrl) {
7218
- targets.push({
7219
- url: settings.slackWebhookUrl,
7220
- payload: notificationService.formatSlackWebhook({
7221
- event: webhookEvent,
7222
- session: newSession,
7223
- user,
7224
- geoData
7225
- })
7226
- });
7227
- }
7228
- await Promise.allSettled(
7229
- targets.map(
7230
- (t) => notificationService.sendWebhook({
7231
- event: webhookEvent,
7232
- data: t.payload,
7233
- webhookUrl: t.url
7234
- })
7235
- )
7236
- );
7237
- }
8151
+ await dispatchLoginAlerts({
8152
+ settings,
8153
+ notificationService,
8154
+ user,
8155
+ session: newSession,
8156
+ geoData,
8157
+ isNewLocation
8158
+ });
7238
8159
  } catch (notifErr) {
7239
8160
  log.warn("Notification failed:", notifErr?.name || "Error");
7240
8161
  }
@@ -8081,6 +9002,14 @@ var require_destroy = __commonJS({
8081
9002
  }
8082
9003
  strapi2.sessionManagerUnsubscribers = [];
8083
9004
  }
9005
+ if (typeof strapi2.sessionManagerAdminActivityUninstall === "function") {
9006
+ try {
9007
+ await strapi2.sessionManagerAdminActivityUninstall();
9008
+ } catch (err) {
9009
+ log.warn("Failed to stop the admin activity capture:", err?.name || "Error");
9010
+ }
9011
+ strapi2.sessionManagerAdminActivityUninstall = null;
9012
+ }
8084
9013
  log.info("[SUCCESS] Plugin cleanup completed");
8085
9014
  };
8086
9015
  }
@@ -8342,18 +9271,110 @@ var require_schema2 = __commonJS({
8342
9271
  }
8343
9272
  });
8344
9273
 
9274
+ // server/src/content-types/security-event/schema.json
9275
+ var require_schema3 = __commonJS({
9276
+ "server/src/content-types/security-event/schema.json"(exports2, module2) {
9277
+ module2.exports = {
9278
+ kind: "collectionType",
9279
+ collectionName: "magic_sessions_security_events",
9280
+ info: {
9281
+ singularName: "security-event",
9282
+ pluralName: "security-events",
9283
+ displayName: "Security event",
9284
+ description: "Security event log: admin sign-ins, failed attempts, lockouts, sign-outs, who signed out whom, and Content Manager activity of admins"
9285
+ },
9286
+ options: {
9287
+ draftAndPublish: false,
9288
+ comment: ""
9289
+ },
9290
+ pluginOptions: {
9291
+ "content-manager": {
9292
+ visible: false
9293
+ },
9294
+ "content-type-builder": {
9295
+ visible: false
9296
+ }
9297
+ },
9298
+ indexes: [
9299
+ {
9300
+ name: "msm_security_events_actor",
9301
+ columns: ["actor_type", "actor_id", "created_at"]
9302
+ },
9303
+ {
9304
+ name: "msm_security_events_target",
9305
+ columns: ["target_type", "target_id", "created_at"]
9306
+ },
9307
+ {
9308
+ name: "msm_security_events_event",
9309
+ columns: ["event", "created_at"]
9310
+ },
9311
+ {
9312
+ name: "msm_security_events_created",
9313
+ columns: ["created_at"]
9314
+ }
9315
+ ],
9316
+ attributes: {
9317
+ event: {
9318
+ type: "string",
9319
+ maxLength: 64,
9320
+ required: true
9321
+ },
9322
+ actorType: {
9323
+ type: "enumeration",
9324
+ enum: ["admin", "user", "system"],
9325
+ required: true
9326
+ },
9327
+ actorId: {
9328
+ type: "string",
9329
+ maxLength: 64
9330
+ },
9331
+ targetType: {
9332
+ type: "string",
9333
+ maxLength: 40
9334
+ },
9335
+ targetId: {
9336
+ type: "string",
9337
+ maxLength: 255
9338
+ },
9339
+ ip: {
9340
+ type: "string",
9341
+ maxLength: 45
9342
+ },
9343
+ userAgent: {
9344
+ type: "text",
9345
+ maxLength: 500
9346
+ },
9347
+ geo: {
9348
+ type: "json"
9349
+ },
9350
+ meta: {
9351
+ type: "json"
9352
+ }
9353
+ }
9354
+ };
9355
+ }
9356
+ });
9357
+
8345
9358
  // server/src/content-types/index.js
8346
9359
  var require_content_types = __commonJS({
8347
9360
  "server/src/content-types/index.js"(exports2, module2) {
8348
9361
  "use strict";
8349
9362
  var session = require_schema();
8350
9363
  var revokedToken = require_schema2();
9364
+ var securityEvent = require_schema3();
8351
9365
  module2.exports = {
8352
9366
  session: {
8353
9367
  schema: session
8354
9368
  },
8355
9369
  "revoked-token": {
8356
9370
  schema: revokedToken
9371
+ },
9372
+ // One security event log (4.15): admin sign-ins and sign-outs, failed
9373
+ // attempts, lockouts, who signed out whom, Content Manager activity, and
9374
+ // later app-user security events. Hidden from the Content Manager and the
9375
+ // Content-Type Builder.
9376
+ "security-event": {
9377
+ schema: securityEvent
8357
9378
  }
8358
9379
  };
8359
9380
  }
@@ -8463,6 +9484,7 @@ var require_admin = __commonJS({
8463
9484
  var PLUGIN_ACCESS_ACTION = "plugin::magic-sessionmanager.access";
8464
9485
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
8465
9486
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
9487
+ var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
8466
9488
  var adminPolicy = () => [
8467
9489
  "admin::isAuthenticatedAdmin",
8468
9490
  {
@@ -8640,39 +9662,80 @@ var require_admin = __commonJS({
8640
9662
  path: "/admin-sessions/admins",
8641
9663
  handler: "admin-sessions.listAdmins",
8642
9664
  config: {
8643
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9665
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9666
+ middlewares: adminReadRateLimit(),
9667
+ description: "List Strapi admins with their admin panel sessions (admin)"
9668
+ }
9669
+ },
9670
+ {
9671
+ method: "GET",
9672
+ path: "/admin-sessions/admins/:adminId/sessions",
9673
+ handler: "admin-sessions.listAdminSessions",
9674
+ config: {
9675
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9676
+ middlewares: adminReadRateLimit(),
9677
+ description: "List the admin panel sessions of one Strapi admin (admin)"
9678
+ }
9679
+ },
9680
+ {
9681
+ method: "POST",
9682
+ path: "/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out",
9683
+ handler: "admin-sessions.signOutSession",
9684
+ config: {
9685
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
9686
+ middlewares: adminSignOutRateLimit(),
9687
+ description: "Sign a Strapi admin out of one browser (admin)"
9688
+ }
9689
+ },
9690
+ {
9691
+ method: "POST",
9692
+ path: "/admin-sessions/admins/:adminId/sign-out-everywhere",
9693
+ handler: "admin-sessions.signOutEverywhere",
9694
+ config: {
9695
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
9696
+ middlewares: adminSignOutRateLimit(),
9697
+ description: "Sign a Strapi admin out of every browser (admin)"
9698
+ }
9699
+ },
9700
+ // ============== ADMIN SIGN-IN HISTORY AND CONTENT MANAGER ACTIVITY ==============
9701
+ {
9702
+ method: "GET",
9703
+ path: "/admin-activity/sign-ins",
9704
+ handler: "admin-activity.listSignIns",
9705
+ config: {
9706
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
8644
9707
  middlewares: adminReadRateLimit(),
8645
- description: "List Strapi admins with their admin panel sessions (admin)"
9708
+ description: "List the admin sign-in history (admin)"
8646
9709
  }
8647
9710
  },
8648
9711
  {
8649
9712
  method: "GET",
8650
- path: "/admin-sessions/admins/:adminId/sessions",
8651
- handler: "admin-sessions.listAdminSessions",
9713
+ path: "/admin-activity/sign-ins/export",
9714
+ handler: "admin-activity.exportSignIns",
8652
9715
  config: {
8653
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9716
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
8654
9717
  middlewares: adminReadRateLimit(),
8655
- description: "List the admin panel sessions of one Strapi admin (admin)"
9718
+ description: "Get one export batch of the admin sign-in history (admin)"
8656
9719
  }
8657
9720
  },
8658
9721
  {
8659
- method: "POST",
8660
- path: "/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out",
8661
- handler: "admin-sessions.signOutSession",
9722
+ method: "GET",
9723
+ path: "/admin-activity/content",
9724
+ handler: "admin-activity.listContentActivity",
8662
9725
  config: {
8663
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
8664
- middlewares: adminSignOutRateLimit(),
8665
- description: "Sign a Strapi admin out of one browser (admin)"
9726
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9727
+ middlewares: adminReadRateLimit(),
9728
+ description: "List Content Manager activity of admins (admin)"
8666
9729
  }
8667
9730
  },
8668
9731
  {
8669
- method: "POST",
8670
- path: "/admin-sessions/admins/:adminId/sign-out-everywhere",
8671
- handler: "admin-sessions.signOutEverywhere",
9732
+ method: "GET",
9733
+ path: "/admin-activity/content/export",
9734
+ handler: "admin-activity.exportContentActivity",
8672
9735
  config: {
8673
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
8674
- middlewares: adminSignOutRateLimit(),
8675
- description: "Sign a Strapi admin out of every browser (admin)"
9736
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9737
+ middlewares: adminReadRateLimit(),
9738
+ description: "Get one export batch of Content Manager activity of admins (admin)"
8676
9739
  }
8677
9740
  },
8678
9741
  // ============================ GEOLOCATION ============================
@@ -8763,103 +9826,6 @@ var require_routes = __commonJS({
8763
9826
  }
8764
9827
  });
8765
9828
 
8766
- // server/src/utils/user-agent-parser.js
8767
- var require_user_agent_parser = __commonJS({
8768
- "server/src/utils/user-agent-parser.js"(exports2, module2) {
8769
- "use strict";
8770
- function parseUserAgent(userAgent) {
8771
- if (!userAgent) {
8772
- return {
8773
- deviceType: "unknown",
8774
- browserName: "unknown",
8775
- browserVersion: null,
8776
- osName: "unknown",
8777
- osVersion: null
8778
- };
8779
- }
8780
- let deviceType = "desktop";
8781
- if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
8782
- deviceType = "tablet";
8783
- } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
8784
- deviceType = "mobile";
8785
- } else if (/android(?!.*mobile)/i.test(userAgent)) {
8786
- deviceType = "tablet";
8787
- } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
8788
- deviceType = "bot";
8789
- }
8790
- let browserName = "unknown";
8791
- let browserVersion = null;
8792
- if (/edg\//i.test(userAgent)) {
8793
- browserName = "Edge";
8794
- browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
8795
- } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
8796
- browserName = "Opera";
8797
- browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
8798
- } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
8799
- browserName = "Chrome";
8800
- browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
8801
- } else if (/firefox|fxios/i.test(userAgent)) {
8802
- browserName = "Firefox";
8803
- browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
8804
- } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
8805
- browserName = "Safari";
8806
- browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
8807
- } else if (/msie|trident/i.test(userAgent)) {
8808
- browserName = "Internet Explorer";
8809
- browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
8810
- }
8811
- let osName = "unknown";
8812
- let osVersion = null;
8813
- if (/windows nt/i.test(userAgent)) {
8814
- osName = "Windows";
8815
- const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
8816
- const winVersionMap = {
8817
- "10.0": "10/11",
8818
- 6.3: "8.1",
8819
- 6.2: "8",
8820
- 6.1: "7",
8821
- "6.0": "Vista",
8822
- 5.1: "XP"
8823
- };
8824
- osVersion = winVersionMap[winVersion] || winVersion;
8825
- } else if (/iphone|ipad|ipod/i.test(userAgent)) {
8826
- osName = "iOS";
8827
- osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8828
- } else if (/mac os x/i.test(userAgent)) {
8829
- osName = "macOS";
8830
- osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8831
- } else if (/android/i.test(userAgent)) {
8832
- osName = "Android";
8833
- osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
8834
- } else if (/linux/i.test(userAgent)) {
8835
- osName = "Linux";
8836
- } else if (/cros/i.test(userAgent)) {
8837
- osName = "Chrome OS";
8838
- }
8839
- return {
8840
- deviceType,
8841
- browserName,
8842
- browserVersion,
8843
- osName,
8844
- osVersion
8845
- };
8846
- }
8847
- function extractVersion(userAgent, regex) {
8848
- const match = userAgent.match(regex);
8849
- return match ? match[1] : null;
8850
- }
8851
- function getDeviceDescription(parsed) {
8852
- const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
8853
- const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
8854
- return `${browser} on ${os}`;
8855
- }
8856
- module2.exports = {
8857
- parseUserAgent,
8858
- getDeviceDescription
8859
- };
8860
- }
8861
- });
8862
-
8863
9829
  // server/src/utils/enhance-session.js
8864
9830
  var require_enhance_session = __commonJS({
8865
9831
  "server/src/utils/enhance-session.js"(exports2, module2) {
@@ -8914,14 +9880,15 @@ var require_enhance_session = __commonJS({
8914
9880
  country_flag: geoData.country_flag,
8915
9881
  city: geoData.city,
8916
9882
  region: geoData.region,
8917
- timezone: geoData.timezone
9883
+ timezone: geoData.timezone,
9884
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
8918
9885
  };
8919
9886
  if (strapi2) {
8920
9887
  strapi2.documents(SESSION_UID).update({
8921
9888
  documentId: session.documentId,
8922
9889
  data: {
8923
9890
  geoLocation,
8924
- securityScore: geoData.securityScore ?? null
9891
+ securityScore: geoData.riskSource ? geoData.securityScore ?? null : null
8925
9892
  }
8926
9893
  }).catch(() => {
8927
9894
  });
@@ -9630,6 +10597,7 @@ var require_session = __commonJS({
9630
10597
  var { sendServerError } = require_http_errors();
9631
10598
  var { getCoordinator } = require_coordination();
9632
10599
  var { clearSessionStatsCache } = require_session_list();
10600
+ var { noRiskData } = require_risk_data();
9633
10601
  var {
9634
10602
  getNativeOnlySummary,
9635
10603
  endNativeOnlySessions,
@@ -9663,11 +10631,7 @@ var require_session = __commonJS({
9663
10631
  timezone: "Unknown",
9664
10632
  latitude: null,
9665
10633
  longitude: null,
9666
- isVpn: false,
9667
- isProxy: false,
9668
- isThreat: false,
9669
- securityScore: 50,
9670
- riskLevel: "Unknown",
10634
+ ...noRiskData(),
9671
10635
  _status: "disabled",
9672
10636
  _source: "disabled"
9673
10637
  };
@@ -10790,7 +11754,10 @@ var require_geoip_updater = __commonJS({
10790
11754
  var SUPPORTED_MMDB_NAMES = new Set(
10791
11755
  [...SUPPORTED_EDITION_IDS].map((editionId) => `${editionId}.mmdb`)
10792
11756
  );
10793
- function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
11757
+ var RISK_EDITION_IDS = /* @__PURE__ */ new Set(["GeoIP2-Anonymous-IP", "GeoLite2-ASN"]);
11758
+ var ALL_EDITION_IDS = /* @__PURE__ */ new Set([...SUPPORTED_EDITION_IDS, ...RISK_EDITION_IDS]);
11759
+ var ALL_MMDB_NAMES = new Set([...ALL_EDITION_IDS].map((editionId) => `${editionId}.mmdb`));
11760
+ function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY, allowedNames = SUPPORTED_MMDB_NAMES) {
10794
11761
  const root = path.resolve(directory);
10795
11762
  if (value !== void 0 && typeof value !== "string") {
10796
11763
  throw new Error("GeoIP database path must be a string");
@@ -10809,14 +11776,14 @@ var require_geoip_updater = __commonJS({
10809
11776
  }
10810
11777
  filename = requested;
10811
11778
  }
10812
- if (!SUPPORTED_MMDB_NAMES.has(filename)) {
11779
+ if (!allowedNames.has(filename)) {
10813
11780
  throw new Error("GeoIP database path must use a supported MMDB filename");
10814
11781
  }
10815
11782
  return path.join(root, filename);
10816
11783
  }
10817
- async function canonicalizeDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
11784
+ async function canonicalizeDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY, allowedNames = SUPPORTED_MMDB_NAMES) {
10818
11785
  const root = path.resolve(directory);
10819
- const target = resolveDatabaseTarget(value, root);
11786
+ const target = resolveDatabaseTarget(value, root, allowedNames);
10820
11787
  await fs.mkdir(root, { recursive: true, mode: 448 });
10821
11788
  const rootStat = await fs.lstat(root);
10822
11789
  const canonicalRoot = await fs.realpath(root);
@@ -10842,8 +11809,8 @@ var require_geoip_updater = __commonJS({
10842
11809
  }
10843
11810
  return canonicalTarget;
10844
11811
  }
10845
- function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
10846
- return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
11812
+ function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID, allowed = SUPPORTED_EDITION_IDS) {
11813
+ return allowed.has(value) ? value : fallback;
10847
11814
  }
10848
11815
  function inferEditionIdFromPath(filePath) {
10849
11816
  if (typeof filePath !== "string" || filePath.trim() === "") return "";
@@ -10865,10 +11832,25 @@ var require_geoip_updater = __commonJS({
10865
11832
  function resolveConfig(env = process2.env, argv = process2.argv.slice(2), overrides = {}) {
10866
11833
  const force = argv.includes("--force") || overrides.force === true;
10867
11834
  const configuredOutputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || "";
11835
+ const requestedEdition = overrides.editionId || env.MAXMIND_EDITION_ID;
11836
+ const databaseDirectory = overrides.databaseDirectory || DEFAULT_GEOIP_DIRECTORY;
11837
+ if (RISK_EDITION_IDS.has(requestedEdition)) {
11838
+ return {
11839
+ accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || "",
11840
+ licenseKey: overrides.licenseKey || env.MAXMIND_LICENSE_KEY || "",
11841
+ editionId: requestedEdition,
11842
+ outputPath: resolveDatabaseTarget(
11843
+ `${requestedEdition}.mmdb`,
11844
+ databaseDirectory,
11845
+ ALL_MMDB_NAMES
11846
+ ),
11847
+ mmdbFileName: `${requestedEdition}.mmdb`,
11848
+ force
11849
+ };
11850
+ }
10868
11851
  const editionId = normalizeEditionId(
10869
- overrides.editionId || env.MAXMIND_EDITION_ID || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
11852
+ requestedEdition || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
10870
11853
  );
10871
- const databaseDirectory = overrides.databaseDirectory || DEFAULT_GEOIP_DIRECTORY;
10872
11854
  const outputPath = resolveDatabaseTarget(
10873
11855
  configuredOutputPath || `${editionId}.mmdb`,
10874
11856
  databaseDirectory
@@ -10946,7 +11928,9 @@ var require_geoip_updater = __commonJS({
10946
11928
  redirect: "follow"
10947
11929
  });
10948
11930
  if (!response.ok) {
10949
- throw new Error(`MaxMind HEAD failed with HTTP ${response.status}`);
11931
+ const error = new Error(`MaxMind HEAD failed with HTTP ${response.status}`);
11932
+ error.httpStatus = response.status;
11933
+ throw error;
10950
11934
  }
10951
11935
  return {
10952
11936
  lastModified: response.headers.get("last-modified") || "",
@@ -10963,7 +11947,9 @@ var require_geoip_updater = __commonJS({
10963
11947
  redirect: "follow"
10964
11948
  });
10965
11949
  if (!response.ok) {
10966
- throw new Error(`MaxMind download failed with HTTP ${response.status}`);
11950
+ const error = new Error(`MaxMind download failed with HTTP ${response.status}`);
11951
+ error.httpStatus = response.status;
11952
+ throw error;
10967
11953
  }
10968
11954
  return Buffer.from(await response.arrayBuffer());
10969
11955
  }
@@ -11001,8 +11987,12 @@ var require_geoip_updater = __commonJS({
11001
11987
  if (!config2.accountId || !config2.licenseKey) {
11002
11988
  throw new Error("MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY are required");
11003
11989
  }
11004
- const editionId = normalizeEditionId(config2.editionId);
11005
- const outputPath = await canonicalizeDatabaseTarget(config2.outputPath);
11990
+ const editionId = normalizeEditionId(config2.editionId, DEFAULT_EDITION_ID, ALL_EDITION_IDS);
11991
+ const outputPath = await canonicalizeDatabaseTarget(
11992
+ config2.outputPath,
11993
+ DEFAULT_GEOIP_DIRECTORY,
11994
+ ALL_MMDB_NAMES
11995
+ );
11006
11996
  const mmdbFileName = `${editionId}.mmdb`;
11007
11997
  if (path.basename(outputPath) !== mmdbFileName) {
11008
11998
  throw new Error("GeoIP database filename must match the selected edition");
@@ -11054,6 +12044,8 @@ var require_geoip_updater = __commonJS({
11054
12044
  };
11055
12045
  }
11056
12046
  module2.exports = {
12047
+ ALL_MMDB_NAMES,
12048
+ RISK_EDITION_IDS,
11057
12049
  DEFAULT_EDITION_ID,
11058
12050
  DEFAULT_GEOIP_DIRECTORY,
11059
12051
  DEFAULT_MMDB_NAME,
@@ -11087,6 +12079,12 @@ var require_settings = __commonJS({
11087
12079
  var { LockTimeoutError } = require_coordination();
11088
12080
  var { resolveDatabaseTarget } = require_geoip_updater();
11089
12081
  var { sendServerError, sendValidationError } = require_http_errors();
12082
+ var {
12083
+ SECURITY_LOG_DEFAULTS,
12084
+ SECURITY_LOG_KEYS,
12085
+ validateSecurityLogSettings
12086
+ } = require_security_log_settings();
12087
+ var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
11090
12088
  var path = require("node:path");
11091
12089
  var ALLOWED_WEBHOOK_DOMAINS = {
11092
12090
  discord: ["discord.com", "discordapp.com"],
@@ -11260,7 +12258,8 @@ var require_settings = __commonJS({
11260
12258
  slackWebhookUrl: "",
11261
12259
  strictSessionEnforcement: false,
11262
12260
  trustedProxies: false,
11263
- emailTemplates: DEFAULT_EMAIL_TEMPLATES
12261
+ emailTemplates: DEFAULT_EMAIL_TEMPLATES,
12262
+ ...SECURITY_LOG_DEFAULTS
11264
12263
  };
11265
12264
  function mergeSettingsWithDefaults(stored) {
11266
12265
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -11465,6 +12464,9 @@ var require_settings = __commonJS({
11465
12464
  next.emailTemplates = sanitizeEmailTemplates(mergedTemplates);
11466
12465
  }
11467
12466
  }
12467
+ const securityLog = validateSecurityLogSettings(body);
12468
+ errors.push(...securityLog.errors);
12469
+ Object.assign(next, securityLog.values);
11468
12470
  if (errors.length > 0) return { errors };
11469
12471
  const settings = {};
11470
12472
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -11492,6 +12494,13 @@ var require_settings = __commonJS({
11492
12494
  };
11493
12495
  return ctx.body;
11494
12496
  }
12497
+ function canChangeAdminActivity(ctx) {
12498
+ try {
12499
+ return ctx.state?.userAbility?.can?.(ADMIN_ACTIVITY_READ_ACTION) === true;
12500
+ } catch {
12501
+ return false;
12502
+ }
12503
+ }
11495
12504
  module2.exports = {
11496
12505
  /**
11497
12506
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -11530,6 +12539,9 @@ var require_settings = __commonJS({
11530
12539
  * Omitted fields keep their stored value. Invalid values are rejected with
11531
12540
  * a 400 whose `error.details.errors` names each field; nothing is clamped
11532
12541
  * or written in that case. Store failures return a 500 with a safe message.
12542
+ * Changing a security log setting (`adminSignInHistory`,
12543
+ * `adminContentActivity`, `securityLogStoreIp`, `securityLogAnonymizeIp`,
12544
+ * `securityLogRetentionDays`) also needs `admin-activity.read`, else 403.
11533
12545
  *
11534
12546
  * @route PUT /magic-sessionmanager/settings
11535
12547
  * @returns {Promise<void>}
@@ -11561,6 +12573,10 @@ var require_settings = __commonJS({
11561
12573
  };
11562
12574
  const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
11563
12575
  if (errors.length > 0) return { errors };
12576
+ const changesAdminActivity = SECURITY_LOG_KEYS.some(
12577
+ (key) => sanitizedSettings[key] !== current[key]
12578
+ );
12579
+ if (changesAdminActivity && !canChangeAdminActivity(ctx)) return { forbidden: true };
11564
12580
  await pluginStore.set({
11565
12581
  key: "settings",
11566
12582
  value: sanitizedSettings
@@ -11568,6 +12584,11 @@ var require_settings = __commonJS({
11568
12584
  const revision = await notifySettingsChanged(strapi);
11569
12585
  return { settings: sanitizedSettings, revision };
11570
12586
  });
12587
+ if (outcome.forbidden) {
12588
+ return ctx.forbidden('Changing the security log settings needs "View admin activity".', {
12589
+ reason: "admin-activity-permission"
12590
+ });
12591
+ }
11571
12592
  if (outcome.conflict) {
11572
12593
  return sendSettingsConflict(ctx, outcome.currentRevision);
11573
12594
  }
@@ -11603,6 +12624,218 @@ var require_settings = __commonJS({
11603
12624
  }
11604
12625
  });
11605
12626
 
12627
+ // server/src/utils/risk-databases.js
12628
+ var require_risk_databases = __commonJS({
12629
+ "server/src/utils/risk-databases.js"(exports2, module2) {
12630
+ "use strict";
12631
+ var fs = require("node:fs");
12632
+ var path = require("node:path");
12633
+ var {
12634
+ DEFAULT_GEOIP_DIRECTORY,
12635
+ RISK_EDITION_IDS,
12636
+ readMetadata
12637
+ } = require_geoip_updater();
12638
+ var { calculateSecurityScore, getRiskLevel, noRiskData } = require_risk_data();
12639
+ var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
12640
+ var RISK_DATABASES = Object.freeze({
12641
+ "anonymous-ip": Object.freeze({
12642
+ editionId: "GeoIP2-Anonymous-IP",
12643
+ envVar: "MAGIC_SESSIONMANAGER_ANONYMOUS_IP_DATABASE",
12644
+ method: "anonymousIP"
12645
+ }),
12646
+ asn: Object.freeze({
12647
+ editionId: "GeoLite2-ASN",
12648
+ envVar: "MAGIC_SESSIONMANAGER_ASN_DATABASE",
12649
+ method: "asn"
12650
+ })
12651
+ });
12652
+ var HOSTING_ASNS = Object.freeze(
12653
+ /* @__PURE__ */ new Set([
12654
+ 16509,
12655
+ // Amazon AWS
12656
+ 14618,
12657
+ // Amazon AWS
12658
+ 396982,
12659
+ // Google Cloud
12660
+ 8075,
12661
+ // Microsoft (Azure; also Microsoft's own offices)
12662
+ 14061,
12663
+ // DigitalOcean
12664
+ 24940,
12665
+ // Hetzner Online
12666
+ 213230,
12667
+ // Hetzner Cloud
12668
+ 16276,
12669
+ // OVHcloud
12670
+ 63949,
12671
+ // Akamai Connected Cloud (Linode)
12672
+ 20473,
12673
+ // Vultr (The Constant Company)
12674
+ 51167,
12675
+ // Contabo
12676
+ 31898,
12677
+ // Oracle Cloud
12678
+ 45102,
12679
+ // Alibaba Cloud
12680
+ 12876,
12681
+ // Scaleway
12682
+ 60781,
12683
+ // Leaseweb Netherlands
12684
+ 28753,
12685
+ // Leaseweb Germany
12686
+ 8560,
12687
+ // IONOS
12688
+ 47583,
12689
+ // Hostinger
12690
+ 9009
12691
+ // M247
12692
+ ])
12693
+ );
12694
+ var readerCache = /* @__PURE__ */ new Map();
12695
+ function resolveRiskDatabasePath(kind, env = process.env) {
12696
+ const definition = RISK_DATABASES[kind];
12697
+ const configured = typeof env[definition.envVar] === "string" ? env[definition.envVar].trim() : "";
12698
+ if (configured) {
12699
+ return {
12700
+ path: path.isAbsolute(configured) ? configured : path.resolve(process.cwd(), configured),
12701
+ fromEnvironment: true
12702
+ };
12703
+ }
12704
+ return {
12705
+ path: path.join(DEFAULT_GEOIP_DIRECTORY, `${definition.editionId}.mmdb`),
12706
+ fromEnvironment: false
12707
+ };
12708
+ }
12709
+ async function openRiskReader(databasePath) {
12710
+ if (readerCache.has(databasePath)) return readerCache.get(databasePath);
12711
+ const { Reader } = require("@maxmind/geoip2-node");
12712
+ const readerPromise = Reader.open(databasePath, {
12713
+ watchForUpdates: true,
12714
+ watchForUpdatesNonPersistent: true
12715
+ });
12716
+ readerCache.set(databasePath, readerPromise);
12717
+ try {
12718
+ return await readerPromise;
12719
+ } catch (error) {
12720
+ readerCache.delete(databasePath);
12721
+ throw error;
12722
+ }
12723
+ }
12724
+ function resetRiskReaders() {
12725
+ for (const databasePath of readerCache.keys()) fs.unwatchFile(databasePath);
12726
+ readerCache.clear();
12727
+ }
12728
+ async function readRiskRecord(kind, ip, env = process.env) {
12729
+ const { path: databasePath } = resolveRiskDatabasePath(kind, env);
12730
+ if (!fs.existsSync(databasePath)) return { status: "missing" };
12731
+ try {
12732
+ const reader = await openRiskReader(databasePath);
12733
+ return { status: "ok", record: reader[RISK_DATABASES[kind].method](ip) };
12734
+ } catch (error) {
12735
+ if (error?.name === "AddressNotFoundError") return { status: "absent" };
12736
+ return { status: "error", name: error?.name || "Error" };
12737
+ }
12738
+ }
12739
+ function buildRiskData({ anonymous, asn }) {
12740
+ const asnRecord = asn?.status === "ok" ? asn.record : null;
12741
+ const asnNumber = Number.isInteger(asnRecord?.autonomousSystemNumber) ? asnRecord.autonomousSystemNumber : null;
12742
+ const asnFields = asnRecord ? {
12743
+ asn: asnNumber === null ? null : `AS${asnNumber}`,
12744
+ org: asnRecord.autonomousSystemOrganization || null
12745
+ } : {};
12746
+ let flags;
12747
+ let riskSource;
12748
+ if (anonymous?.status === "ok" || anonymous?.status === "absent") {
12749
+ const record = anonymous.record || {};
12750
+ riskSource = "anonymous-ip";
12751
+ flags = {
12752
+ isAnonymous: record.isAnonymous === true,
12753
+ isVpn: record.isAnonymousVpn === true,
12754
+ isPublicProxy: record.isPublicProxy === true,
12755
+ isResidentialProxy: record.isResidentialProxy === true,
12756
+ isProxy: record.isPublicProxy === true || record.isResidentialProxy === true,
12757
+ isTor: record.isTorExitNode === true,
12758
+ isHosting: record.isHostingProvider === true,
12759
+ // MaxMind's Anonymous IP data has no "threat" category.
12760
+ isThreat: false
12761
+ };
12762
+ } else if (asn?.status === "ok" || asn?.status === "absent") {
12763
+ riskSource = "asn-heuristic";
12764
+ flags = {
12765
+ isAnonymous: false,
12766
+ isVpn: false,
12767
+ isPublicProxy: false,
12768
+ isResidentialProxy: false,
12769
+ isProxy: false,
12770
+ isTor: false,
12771
+ isHosting: asnNumber !== null && HOSTING_ASNS.has(asnNumber),
12772
+ isThreat: false
12773
+ };
12774
+ } else {
12775
+ const failed = anonymous?.status === "error" || asn?.status === "error";
12776
+ return { ...noRiskData(), ...asnFields, _riskStatus: failed ? "error" : "missing" };
12777
+ }
12778
+ return {
12779
+ ...flags,
12780
+ ...asnFields,
12781
+ securityScore: calculateSecurityScore(flags),
12782
+ riskLevel: getRiskLevel(flags),
12783
+ riskSource,
12784
+ _riskStatus: "ok"
12785
+ };
12786
+ }
12787
+ async function lookupRiskData(ip, env = process.env) {
12788
+ const [anonymous, asn] = await Promise.all([
12789
+ readRiskRecord("anonymous-ip", ip, env),
12790
+ readRiskRecord("asn", ip, env)
12791
+ ]);
12792
+ return buildRiskData({ anonymous, asn });
12793
+ }
12794
+ async function isUsableRiskDatabase(kind, databasePath) {
12795
+ try {
12796
+ const reader = await openRiskReader(databasePath);
12797
+ reader[RISK_DATABASES[kind].method]("127.0.0.1");
12798
+ return true;
12799
+ } catch (error) {
12800
+ return error?.name === "AddressNotFoundError";
12801
+ }
12802
+ }
12803
+ async function describeRiskDatabase(kind, env = process.env) {
12804
+ const { editionId } = RISK_DATABASES[kind];
12805
+ const { path: databasePath, fromEnvironment } = resolveRiskDatabasePath(kind, env);
12806
+ const exists = fs.existsSync(databasePath);
12807
+ const usable = exists ? await isUsableRiskDatabase(kind, databasePath) : false;
12808
+ return {
12809
+ editionId,
12810
+ exists,
12811
+ usable,
12812
+ fromEnvironment,
12813
+ // Only the dedicated folder is named; an environment path stays private.
12814
+ file: fromEnvironment ? null : `${SAFE_GEOIP_DIRECTORY_LABEL}/${editionId}.mmdb`,
12815
+ metadata: !fromEnvironment && exists ? await readMetadata(`${databasePath}.metadata.json`) : null
12816
+ };
12817
+ }
12818
+ async function getRiskDataStatus(env = process.env) {
12819
+ const [anonymousIp, asn] = await Promise.all([
12820
+ describeRiskDatabase("anonymous-ip", env),
12821
+ describeRiskDatabase("asn", env)
12822
+ ]);
12823
+ const source = anonymousIp.usable ? "anonymous-ip" : asn.usable ? "asn-heuristic" : null;
12824
+ return { available: source !== null, source, anonymousIp, asn };
12825
+ }
12826
+ module2.exports = {
12827
+ HOSTING_ASNS,
12828
+ RISK_DATABASES,
12829
+ RISK_EDITION_IDS,
12830
+ buildRiskData,
12831
+ getRiskDataStatus,
12832
+ lookupRiskData,
12833
+ resetRiskReaders,
12834
+ resolveRiskDatabasePath
12835
+ };
12836
+ }
12837
+ });
12838
+
11606
12839
  // server/src/controllers/geoip.js
11607
12840
  var require_geoip = __commonJS({
11608
12841
  "server/src/controllers/geoip.js"(exports2, module2) {
@@ -11625,6 +12858,7 @@ var require_geoip = __commonJS({
11625
12858
  var { sendServerError } = require_http_errors();
11626
12859
  var { setPluginStoreValue } = require_plugin_store();
11627
12860
  var { getHostFingerprint } = require_coordination();
12861
+ var { getRiskDataStatus, RISK_DATABASES } = require_risk_databases();
11628
12862
  var CREDENTIALS_KEY = "geoipCredentials";
11629
12863
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
11630
12864
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -11681,6 +12915,16 @@ var require_geoip = __commonJS({
11681
12915
  force
11682
12916
  });
11683
12917
  }
12918
+ var UPDATABLE_DATABASES = /* @__PURE__ */ new Set(["location", ...Object.keys(RISK_DATABASES)]);
12919
+ function buildRiskUpdaterConfig(database, storedCredentials, force = false) {
12920
+ return resolveConfig(process.env, force ? ["--force"] : [], {
12921
+ accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
12922
+ licenseKey: process.env.MAXMIND_LICENSE_KEY || storedCredentials.licenseKey || "",
12923
+ editionId: RISK_DATABASES[database].editionId,
12924
+ databaseDirectory: DEFAULT_GEOIP_DIRECTORY,
12925
+ force
12926
+ });
12927
+ }
11684
12928
  function sanitizeCredentialInput(value, maxLength = 256) {
11685
12929
  if (typeof value !== "string") return "";
11686
12930
  return value.replace(/\0/g, "").trim().slice(0, maxLength);
@@ -11719,7 +12963,11 @@ var require_geoip = __commonJS({
11719
12963
  // answered. In multi-instance deployments each instance reports
11720
12964
  // its own file; `instance` is a non-reversible host fingerprint.
11721
12965
  scope: "instance",
11722
- instance: getHostFingerprint()
12966
+ instance: getHostFingerprint(),
12967
+ // VPN, proxy and Tor detection needs a dedicated risk data source.
12968
+ // The location providers (ipapi.co, GeoLite2 City/Country) have
12969
+ // none; the local Anonymous IP or ASN database is reported here.
12970
+ risk: await getRiskDataStatus()
11723
12971
  }
11724
12972
  });
11725
12973
  } catch (error) {
@@ -11774,9 +13022,15 @@ var require_geoip = __commonJS({
11774
13022
  try {
11775
13023
  const body = ctx.request.body || {};
11776
13024
  const force = body.force === true;
13025
+ const database = body.database === void 0 ? "location" : body.database;
13026
+ if (!UPDATABLE_DATABASES.has(database)) {
13027
+ return ctx.badRequest("Unknown GeoIP database", {
13028
+ database: ["Use location, anonymous-ip or asn."]
13029
+ });
13030
+ }
11777
13031
  const settings = await getPluginSettings(strapi2);
11778
13032
  const storedCredentials = await getStoredCredentials(strapi2);
11779
- const config2 = buildUpdaterConfig(settings, storedCredentials, force);
13033
+ const config2 = database === "location" ? buildUpdaterConfig(settings, storedCredentials, force) : buildRiskUpdaterConfig(database, storedCredentials, force);
11780
13034
  if (!config2.accountId || !config2.licenseKey) {
11781
13035
  return ctx.badRequest("MaxMind credentials are required before downloading GeoIP data");
11782
13036
  }
@@ -11788,6 +13042,13 @@ var require_geoip = __commonJS({
11788
13042
  "[magic-sessionmanager/geoip] GeoIP download failed:",
11789
13043
  error?.name || "Error"
11790
13044
  );
13045
+ if (error?.httpStatus === 401 || error?.httpStatus === 403) {
13046
+ return sendServerError(
13047
+ ctx,
13048
+ 502,
13049
+ "MaxMind refused the download. Check the credentials and that your account includes this database."
13050
+ );
13051
+ }
11791
13052
  return sendServerError(ctx, 502, "Error updating GeoIP database");
11792
13053
  }
11793
13054
  invalidateSettingsCache();
@@ -11804,6 +13065,7 @@ var require_geoip = __commonJS({
11804
13065
  }
11805
13066
  },
11806
13067
  __private: {
13068
+ buildRiskUpdaterConfig,
11807
13069
  buildUpdaterConfig,
11808
13070
  getCredentialSource,
11809
13071
  getStoredCredentials,
@@ -11818,6 +13080,9 @@ var require_admin_sessions = __commonJS({
11818
13080
  "server/src/utils/admin-sessions.js"(exports2, module2) {
11819
13081
  "use strict";
11820
13082
  var { z } = require("@strapi/utils");
13083
+ var { hashDeviceId } = require_admin_request_info();
13084
+ var { resolveSecurityLogSettings } = require_security_log_settings();
13085
+ var { getPluginSettings } = require_settings_loader();
11821
13086
  var ADMIN_ORIGIN = "admin";
11822
13087
  var SESSION_UID = "admin::session";
11823
13088
  var ADMIN_USER_UID = "admin::user";
@@ -12019,6 +13284,18 @@ var require_admin_sessions = __commonJS({
12019
13284
  }
12020
13285
  return map;
12021
13286
  }
13287
+ async function readSignInRecording(strapi2) {
13288
+ try {
13289
+ const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
13290
+ return {
13291
+ signIns: options.signIns,
13292
+ ipAddresses: options.signIns && options.storeIp,
13293
+ anonymizeIp: options.signIns && options.storeIp && options.anonymizeIp
13294
+ };
13295
+ } catch {
13296
+ return { signIns: false, ipAddresses: false, anonymizeIp: false };
13297
+ }
13298
+ }
12022
13299
  async function listAdmins(strapi2, query, actor) {
12023
13300
  const policy = readSessionPolicy(strapi2);
12024
13301
  if (!getAdminSessionManager(strapi2)) {
@@ -12029,7 +13306,8 @@ var require_admin_sessions = __commonJS({
12029
13306
  pagination: { page: 1, pageSize: query.pageSize, total: 0, pageCount: 1 },
12030
13307
  stats: null,
12031
13308
  policy,
12032
- truncated: false
13309
+ truncated: false,
13310
+ recording: await readSignInRecording(strapi2)
12033
13311
  }
12034
13312
  };
12035
13313
  }
@@ -12110,7 +13388,8 @@ var require_admin_sessions = __commonJS({
12110
13388
  totalAdmins: Number(totalAdmins) || 0
12111
13389
  },
12112
13390
  policy,
12113
- truncated
13391
+ truncated,
13392
+ recording: await readSignInRecording(strapi2)
12114
13393
  }
12115
13394
  };
12116
13395
  }
@@ -12181,6 +13460,7 @@ var require_admin_sessions = __commonJS({
12181
13460
  const currentDeviceId = self ? await findCurrentDeviceId(strapi2, { userId, sessionId: actor.sessionId }) : null;
12182
13461
  let ended;
12183
13462
  let signedOutSelf;
13463
+ let endedDeviceId = null;
12184
13464
  if (sessionId) {
12185
13465
  const row = await strapi2.db.query(SESSION_UID).findOne({
12186
13466
  select: ["userId", "deviceId", "origin"],
@@ -12191,6 +13471,7 @@ var require_admin_sessions = __commonJS({
12191
13471
  }
12192
13472
  if (blockReason === "account-inactive") throw new AdminSignOutError(404, "Session not found");
12193
13473
  await manager.invalidateRefreshToken(userId, String(row.deviceId));
13474
+ endedDeviceId = String(row.deviceId);
12194
13475
  ended = 1;
12195
13476
  signedOutSelf = Boolean(currentDeviceId) && String(row.deviceId) === currentDeviceId;
12196
13477
  } else {
@@ -12203,6 +13484,18 @@ var require_admin_sessions = __commonJS({
12203
13484
  target.id
12204
13485
  )} scope=${scope} ended=${ended}`;
12205
13486
  strapi2.log.info(audit);
13487
+ try {
13488
+ strapi2.plugin("magic-sessionmanager")?.service("security-log")?.record({
13489
+ event: "admin.session.revoked",
13490
+ actorType: "admin",
13491
+ actorId: Number(actor.id),
13492
+ targetType: "admin",
13493
+ targetId: Number(target.id),
13494
+ meta: { scope: scope === "one" ? "one_browser" : "everywhere", ended },
13495
+ deviceHash: endedDeviceId ? hashDeviceId(endedDeviceId) : null
13496
+ });
13497
+ } catch {
13498
+ }
12206
13499
  try {
12207
13500
  strapi2.eventHub?.emit?.("magic-sessionmanager.admin-sessions.signed-out", {
12208
13501
  actorId: Number(actor.id),
@@ -12403,6 +13696,149 @@ var require_admin_sessions2 = __commonJS({
12403
13696
  }
12404
13697
  });
12405
13698
 
13699
+ // server/src/controllers/admin-activity.js
13700
+ var require_admin_activity = __commonJS({
13701
+ "server/src/controllers/admin-activity.js"(exports2, module2) {
13702
+ "use strict";
13703
+ var { z } = require("@strapi/utils");
13704
+ var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
13705
+ var { parseInput } = require_admin_sessions();
13706
+ var { sendServerError, sendValidationError } = require_http_errors();
13707
+ var { createLogger } = require_logger();
13708
+ var MAX_PAGE_SIZE = 100;
13709
+ var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
13710
+ var dateField = (name) => z.string().max(40, `${name} must be an ISO 8601 date`).refine((value) => !Number.isNaN(Date.parse(value)), `${name} must be an ISO 8601 date`).transform((value) => new Date(value)).optional();
13711
+ var common = {
13712
+ adminId: adminIdField,
13713
+ from: dateField("from"),
13714
+ to: dateField("to"),
13715
+ page: z.coerce.number().int().min(1).max(1e6).default(1),
13716
+ pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
13717
+ };
13718
+ var signInQuerySchema = z.strictObject({
13719
+ ...common,
13720
+ event: z.enum(
13721
+ /** @type {[string, ...string[]]} */
13722
+ Object.keys(SIGN_IN_FILTERS)
13723
+ ).default("all")
13724
+ });
13725
+ var activityQuerySchema = z.strictObject({
13726
+ ...common,
13727
+ action: z.enum(
13728
+ /** @type {[string, ...string[]]} */
13729
+ ["all", ...CONTENT_ACTIONS]
13730
+ ).default("all"),
13731
+ contentType: z.string().regex(
13732
+ /^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/,
13733
+ "contentType must be a content type uid"
13734
+ ).optional()
13735
+ });
13736
+ var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
13737
+ var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
13738
+ cursor: cursorField
13739
+ });
13740
+ var activityExportSchema = activityQuerySchema.omit({ page: true, pageSize: true }).extend({
13741
+ cursor: cursorField
13742
+ });
13743
+ module2.exports = ({ strapi: strapi2 }) => {
13744
+ const log = createLogger(strapi2);
13745
+ const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
13746
+ const handle = async (ctx, schema, run, operation) => {
13747
+ const parsed = parseInput(schema, ctx.query);
13748
+ if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
13749
+ const query = parsed.value;
13750
+ if (query.from && query.to && query.from > query.to) {
13751
+ return sendValidationError(ctx, "Invalid query", [
13752
+ { path: ["from"], message: "from must not be after to" }
13753
+ ]);
13754
+ }
13755
+ try {
13756
+ ctx.body = await run(query);
13757
+ return ctx.body;
13758
+ } catch (error) {
13759
+ log.error(
13760
+ `Admin activity: ${operation} failed`,
13761
+ /** @type {any} */
13762
+ error?.name || "Error"
13763
+ );
13764
+ return sendServerError(ctx, 500, "Admin activity could not be loaded.");
13765
+ }
13766
+ };
13767
+ return {
13768
+ /**
13769
+ * One page of the admin sign-in history: sign-ins, failed attempts,
13770
+ * lockouts and sign-outs, newest first.
13771
+ *
13772
+ * @route GET /magic-sessionmanager/admin-activity/sign-ins
13773
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
13774
+ * read rate limit.
13775
+ * @param {Context} ctx Reads `ctx.query.adminId` (optional positive integer), `event`
13776
+ * (`all`|`succeeded`|`failed`|`signed-out`), `from`/`to` (ISO dates), `page`, `pageSize`
13777
+ * (1..100, default 20).
13778
+ * @returns {Promise<unknown>} 200 `{ data: SignInRow[], meta: { pagination, recording } }`;
13779
+ * 400 ValidationError with field errors; 500 fixed message. Rows hold IP address
13780
+ * (possibly anonymised), location, browser, OS and session state; never the device id,
13781
+ * a typed email or a token.
13782
+ */
13783
+ async listSignIns(ctx) {
13784
+ return handle(ctx, signInQuerySchema, (query) => service().listSignIns(query), "sign-ins");
13785
+ },
13786
+ /**
13787
+ * One page of Content Manager activity, newest first.
13788
+ *
13789
+ * @route GET /magic-sessionmanager/admin-activity/content
13790
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
13791
+ * read rate limit.
13792
+ * @param {Context} ctx Reads `ctx.query.adminId`, `action` (`all` or an action),
13793
+ * `contentType` (uid), `from`/`to`, `page`, `pageSize`.
13794
+ * @returns {Promise<unknown>} 200 `{ data: ActivityRow[], meta: { pagination, recording,
13795
+ * contentTypes, contentManagerAccess? } }`; 400; 500 fixed message.
13796
+ */
13797
+ async listContentActivity(ctx) {
13798
+ return handle(
13799
+ ctx,
13800
+ activityQuerySchema,
13801
+ (query) => service().listContentActivity(query),
13802
+ "content"
13803
+ );
13804
+ },
13805
+ /**
13806
+ * One export batch (500 rows, keyset cursor) of the sign-in history.
13807
+ *
13808
+ * @route GET /magic-sessionmanager/admin-activity/sign-ins/export
13809
+ * @auth As listSignIns.
13810
+ * @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
13811
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
13812
+ */
13813
+ async exportSignIns(ctx) {
13814
+ return handle(
13815
+ ctx,
13816
+ signInExportSchema,
13817
+ (query) => service().exportBatch("sign-ins", query, query.cursor || null),
13818
+ "sign-in export"
13819
+ );
13820
+ },
13821
+ /**
13822
+ * One export batch (500 rows, keyset cursor) of Content Manager activity.
13823
+ *
13824
+ * @route GET /magic-sessionmanager/admin-activity/content/export
13825
+ * @auth As listContentActivity.
13826
+ * @param {Context} ctx Same filters as the list, plus `cursor`.
13827
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
13828
+ */
13829
+ async exportContentActivity(ctx) {
13830
+ return handle(
13831
+ ctx,
13832
+ activityExportSchema,
13833
+ (query) => service().exportBatch("content", query, query.cursor || null),
13834
+ "activity export"
13835
+ );
13836
+ }
13837
+ };
13838
+ };
13839
+ }
13840
+ });
13841
+
12406
13842
  // server/src/controllers/index.js
12407
13843
  var require_controllers = __commonJS({
12408
13844
  "server/src/controllers/index.js"(exports2, module2) {
@@ -12411,11 +13847,13 @@ var require_controllers = __commonJS({
12411
13847
  var settings = require_settings();
12412
13848
  var geoip = require_geoip();
12413
13849
  var adminSessions = require_admin_sessions2();
13850
+ var adminActivity = require_admin_activity();
12414
13851
  module2.exports = {
12415
13852
  session,
12416
13853
  settings,
12417
13854
  geoip,
12418
- "admin-sessions": adminSessions
13855
+ "admin-sessions": adminSessions,
13856
+ "admin-activity": adminActivity
12419
13857
  };
12420
13858
  }
12421
13859
  });
@@ -12810,9 +14248,12 @@ var require_session2 = __commonJS({
12810
14248
  country_flag: geoData.country_flag,
12811
14249
  city: geoData.city,
12812
14250
  region: geoData.region,
12813
- timezone: geoData.timezone
14251
+ timezone: geoData.timezone,
14252
+ // Marks the stored score as real risk data; without a
14253
+ // risk source the score is null (not a fake 100).
14254
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
12814
14255
  } : null,
12815
- securityScore: geoData?.securityScore ?? null
14256
+ securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
12816
14257
  }
12817
14258
  });
12818
14259
  log.info("[SUCCESS] End-user session metadata created");
@@ -13682,7 +15123,12 @@ var require_geolocation = __commonJS({
13682
15123
  var path = require("node:path");
13683
15124
  var { getPluginSettings } = require_settings_loader();
13684
15125
  var { getCoordinator, hashedKey } = require_coordination();
13685
- var { resolveDatabaseTarget } = require_geoip_updater();
15126
+ var {
15127
+ DEFAULT_GEOIP_DIRECTORY,
15128
+ resolveDatabaseTarget
15129
+ } = require_geoip_updater();
15130
+ var { calculateSecurityScore, getRiskLevel, noRiskData } = require_risk_data();
15131
+ var { lookupRiskData } = require_risk_databases();
13686
15132
  var GEO_API_TIMEOUT_MS = 4e3;
13687
15133
  var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
13688
15134
  var IPAPI_FAILURE_CACHE_TTL_MS = 5 * 60 * 1e3;
@@ -13712,11 +15158,24 @@ var require_geolocation = __commonJS({
13712
15158
  function uniqueValues(values) {
13713
15159
  return [...new Set(values.filter(Boolean))];
13714
15160
  }
15161
+ function resolveConfiguredCandidates(value) {
15162
+ if (typeof value !== "string" || value.trim() === "") return [];
15163
+ const trimmed = value.trim();
15164
+ if (path.isAbsolute(trimmed)) return [trimmed];
15165
+ const isBareName = trimmed !== "." && trimmed !== ".." && !/[\\/]/.test(trimmed) && !trimmed.includes("\0");
15166
+ if (isBareName) {
15167
+ return uniqueValues([
15168
+ path.join(DEFAULT_GEOIP_DIRECTORY, trimmed),
15169
+ path.resolve(process.cwd(), trimmed)
15170
+ ]);
15171
+ }
15172
+ return [path.resolve(process.cwd(), trimmed)];
15173
+ }
13715
15174
  function resolveDatabaseCandidates(settings = {}) {
13716
- const configured = normalizeDatabasePath(
15175
+ const configured = resolveConfiguredCandidates(
13717
15176
  settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOIP_DATABASE_PATH
13718
15177
  );
13719
- if (configured) return [configured];
15178
+ if (configured.length > 0) return configured;
13720
15179
  return uniqueValues([
13721
15180
  normalizeDatabasePath(process.env.GEOLITE2_CITY_MMDB),
13722
15181
  normalizeDatabasePath(process.env.GEOIP_CITY_DATABASE_PATH),
@@ -13735,7 +15194,11 @@ var require_geolocation = __commonJS({
13735
15194
  return readerCache.get(databasePath);
13736
15195
  }
13737
15196
  const { Reader } = require("@maxmind/geoip2-node");
13738
- const readerPromise = Reader.open(databasePath, { watchForUpdates: true });
15197
+ const readerPromise = Reader.open(databasePath, {
15198
+ watchForUpdates: true,
15199
+ // Reloads a replaced file without keeping the process alive on its own.
15200
+ watchForUpdatesNonPersistent: true
15201
+ });
13739
15202
  readerCache.set(databasePath, readerPromise);
13740
15203
  try {
13741
15204
  return await readerPromise;
@@ -13888,13 +15351,8 @@ var require_geolocation = __commonJS({
13888
15351
  org: null,
13889
15352
  asn: null,
13890
15353
  network: data.traits?.network || null,
13891
- isVpn: false,
13892
- isProxy: false,
13893
- isThreat: false,
13894
- isAnonymous: false,
13895
- isTor: false,
13896
- securityScore: 100,
13897
- riskLevel: "Low",
15354
+ // A location database has no VPN, proxy or Tor data: no risk data here.
15355
+ ...noRiskData(),
13898
15356
  _status: "ok",
13899
15357
  _source: "local-mmdb",
13900
15358
  _databaseType: "country"
@@ -13919,13 +15377,8 @@ var require_geolocation = __commonJS({
13919
15377
  org: null,
13920
15378
  asn: null,
13921
15379
  network: data.traits?.network || null,
13922
- isVpn: false,
13923
- isProxy: false,
13924
- isThreat: false,
13925
- isAnonymous: false,
13926
- isTor: false,
13927
- securityScore: 100,
13928
- riskLevel: "Low",
15380
+ // A location database has no VPN, proxy or Tor data: no risk data here.
15381
+ ...noRiskData(),
13929
15382
  _status: "ok",
13930
15383
  _source: "local-mmdb",
13931
15384
  _databaseType: "city"
@@ -14021,10 +15474,7 @@ var require_geolocation = __commonJS({
14021
15474
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
14022
15475
  latitude: null,
14023
15476
  longitude: null,
14024
- isVpn: false,
14025
- isProxy: false,
14026
- isThreat: false,
14027
- securityScore: 100,
15477
+ ...noRiskData(),
14028
15478
  riskLevel: "None",
14029
15479
  _status: "private",
14030
15480
  _source: "local"
@@ -14039,21 +15489,53 @@ var require_geolocation = __commonJS({
14039
15489
  return this.getFallbackData(lookupIp, "disabled", "disabled");
14040
15490
  }
14041
15491
  if (provider === "local-mmdb") {
14042
- return this.getLocalMmdbIpInfo(lookupIp, settings);
15492
+ return this.withRiskData(await this.getLocalMmdbIpInfo(lookupIp, settings), lookupIp);
14043
15493
  }
14044
15494
  if (provider === "auto") {
14045
15495
  const databasePath = resolveExistingDatabasePath(settings);
14046
15496
  if (databasePath && fs.existsSync(databasePath)) {
14047
15497
  const localResult = await this.getLocalMmdbIpInfo(lookupIp, settings);
14048
15498
  if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
14049
- return localResult;
15499
+ return this.withRiskData(localResult, lookupIp);
14050
15500
  }
14051
15501
  strapi2.log.warn(
14052
15502
  "[magic-sessionmanager/geolocation] Local MMDB lookup failed, falling back to ipapi.co"
14053
15503
  );
14054
15504
  }
14055
15505
  }
14056
- return this.getIpapiIpInfo(lookupIp);
15506
+ return this.withRiskData(await this.getIpapiIpInfo(lookupIp), lookupIp);
15507
+ },
15508
+ /**
15509
+ * Adds risk data (VPN, proxy, Tor, hosting) from the local risk databases
15510
+ * to a location result. Location providers have none; without a risk
15511
+ * database the result keeps noRiskData(). The lookup is local, so no
15512
+ * address leaves the server. The ASN database also fills `asn` and `org`
15513
+ * when the location provider gave none.
15514
+ *
15515
+ * @param {object} result Location lookup result.
15516
+ * @param {string} lookupIp Normalized, validated IP address.
15517
+ * @returns {Promise<object>} Result with risk fields.
15518
+ */
15519
+ async withRiskData(result, lookupIp) {
15520
+ if (!result || typeof result !== "object") return result;
15521
+ try {
15522
+ const { asn, org, ...risk } = await lookupRiskData(lookupIp);
15523
+ if (risk._riskStatus === "error") {
15524
+ strapi2.log.warn("[magic-sessionmanager/geolocation] Risk database lookup failed");
15525
+ }
15526
+ return {
15527
+ ...result,
15528
+ ...risk,
15529
+ ...asn && !result.asn ? { asn } : {},
15530
+ ...org && !result.org ? { org } : {}
15531
+ };
15532
+ } catch (error) {
15533
+ strapi2.log.warn(
15534
+ "[magic-sessionmanager/geolocation] Risk database lookup failed:",
15535
+ error?.name || "Error"
15536
+ );
15537
+ return { ...result, ...noRiskData(), _riskStatus: "error" };
15538
+ }
14057
15539
  },
14058
15540
  /**
14059
15541
  * Reads effective GEOIP provider settings.
@@ -14225,23 +15707,9 @@ var require_geolocation = __commonJS({
14225
15707
  postal: data.postal,
14226
15708
  org: data.org,
14227
15709
  asn: data.asn,
14228
- isVpn: data.threat?.is_vpn || false,
14229
- isProxy: data.threat?.is_proxy || false,
14230
- isThreat: data.threat?.is_threat || false,
14231
- isAnonymous: data.threat?.is_anonymous || false,
14232
- isTor: data.threat?.is_tor || false,
14233
- securityScore: this.calculateSecurityScore({
14234
- isVpn: data.threat?.is_vpn,
14235
- isProxy: data.threat?.is_proxy,
14236
- isThreat: data.threat?.is_threat,
14237
- isAnonymous: data.threat?.is_anonymous,
14238
- isTor: data.threat?.is_tor
14239
- }),
14240
- riskLevel: this.getRiskLevel({
14241
- isVpn: data.threat?.is_vpn,
14242
- isProxy: data.threat?.is_proxy,
14243
- isThreat: data.threat?.is_threat
14244
- }),
15710
+ // ipapi.co documents no VPN, proxy or threat fields
15711
+ // (https://ipapi.co/api/), so its answer carries no risk data.
15712
+ ...noRiskData(),
14245
15713
  _status: "ok",
14246
15714
  _source: "ipapi"
14247
15715
  };
@@ -14274,25 +15742,16 @@ var require_geolocation = __commonJS({
14274
15742
  * @param {object} flags
14275
15743
  * @returns {number}
14276
15744
  */
14277
- calculateSecurityScore({ isVpn, isProxy, isThreat, isAnonymous, isTor }) {
14278
- let score = 100;
14279
- if (isTor) score -= 50;
14280
- if (isThreat) score -= 40;
14281
- if (isVpn) score -= 20;
14282
- if (isProxy) score -= 15;
14283
- if (isAnonymous) score -= 10;
14284
- return Math.max(0, score);
15745
+ calculateSecurityScore(flags) {
15746
+ return calculateSecurityScore(flags || {});
14285
15747
  },
14286
15748
  /**
14287
- * Maps threat indicators to a human-readable risk level.
15749
+ * Maps risk indicators to a human-readable risk level.
14288
15750
  * @param {object} flags
14289
15751
  * @returns {string}
14290
15752
  */
14291
- getRiskLevel({ isVpn, isProxy, isThreat }) {
14292
- if (isThreat) return "High";
14293
- if (isVpn && isProxy) return "Medium-High";
14294
- if (isVpn || isProxy) return "Medium";
14295
- return "Low";
15753
+ getRiskLevel(flags) {
15754
+ return getRiskLevel(flags || {});
14296
15755
  },
14297
15756
  /**
14298
15757
  * Converts a 2-letter ISO country code into a flag emoji.
@@ -14343,11 +15802,7 @@ var require_geolocation = __commonJS({
14343
15802
  timezone: "Unknown",
14344
15803
  latitude: null,
14345
15804
  longitude: null,
14346
- isVpn: false,
14347
- isProxy: false,
14348
- isThreat: false,
14349
- securityScore: 50,
14350
- riskLevel: "Unknown",
15805
+ ...noRiskData(),
14351
15806
  _status: reason,
14352
15807
  _source: source,
14353
15808
  _reason: detail
@@ -14370,6 +15825,21 @@ var require_geolocation = __commonJS({
14370
15825
  var require_notifications = __commonJS({
14371
15826
  "server/src/services/notifications.js"(exports2, module2) {
14372
15827
  "use strict";
15828
+ var { hasRiskData } = require_risk_data();
15829
+ function getRiskWarnings(geoData) {
15830
+ if (!hasRiskData(geoData)) return [];
15831
+ const warnings = [];
15832
+ if (geoData.isVpn) warnings.push("VPN");
15833
+ if (geoData.isProxy) warnings.push("Proxy");
15834
+ if (geoData.isTor) warnings.push("Tor");
15835
+ if (geoData.isHosting) {
15836
+ warnings.push(
15837
+ geoData.riskSource === "asn-heuristic" ? "Hosting (ASN heuristic)" : "Hosting provider"
15838
+ );
15839
+ }
15840
+ if (geoData.isThreat) warnings.push("Threat");
15841
+ return warnings;
15842
+ }
14373
15843
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
14374
15844
  var WEBHOOK_TIMEOUT_MS = 5e3;
14375
15845
  module2.exports = ({ strapi: strapi2 }) => ({
@@ -14515,9 +15985,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
14515
15985
  result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
14516
15986
  result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
14517
15987
  result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
15988
+ const score = data.reason?.securityScore;
14518
15989
  result = result.replace(
14519
15990
  /\{\{reason\.securityScore\}\}/g,
14520
- esc(String(data.reason?.securityScore || "0"))
15991
+ esc(typeof score === "number" && Number.isFinite(score) ? String(score) : "N/A")
14521
15992
  );
14522
15993
  return result;
14523
15994
  },
@@ -14698,11 +16169,8 @@ ${session.loginTime ? new Date(session.loginTime).toLocaleString() : "-"}`
14698
16169
  text: `*Location*
14699
16170
  ${locationFlag}${geoData.city || "?"}, ${geoData.country || "?"}`
14700
16171
  });
14701
- if (geoData.isVpn || geoData.isProxy || geoData.isThreat) {
14702
- const warnings = [];
14703
- if (geoData.isVpn) warnings.push("VPN");
14704
- if (geoData.isProxy) warnings.push("Proxy");
14705
- if (geoData.isThreat) warnings.push("Threat");
16172
+ const warnings = getRiskWarnings(geoData);
16173
+ if (warnings.length > 0) {
14706
16174
  fields.push({
14707
16175
  type: "mrkdwn",
14708
16176
  text: `*Security*
@@ -14771,11 +16239,8 @@ ${user.username || "N/A"}`, inline: true },
14771
16239
  value: `${geoData.country_flag || ""} ${geoData.city}, ${geoData.country}`,
14772
16240
  inline: true
14773
16241
  });
14774
- if (geoData.isVpn || geoData.isProxy || geoData.isThreat) {
14775
- const warnings = [];
14776
- if (geoData.isVpn) warnings.push("VPN");
14777
- if (geoData.isProxy) warnings.push("Proxy");
14778
- if (geoData.isThreat) warnings.push("Threat");
16242
+ const warnings = getRiskWarnings(geoData);
16243
+ if (warnings.length > 0) {
14779
16244
  embed.fields.push({
14780
16245
  name: "[WARNING] Security",
14781
16246
  value: `${warnings.join(", ")} detected
@@ -14820,6 +16285,740 @@ Score: ${geoData.securityScore}/100`,
14820
16285
  }
14821
16286
  });
14822
16287
 
16288
+ // server/src/services/security-log.js
16289
+ var require_security_log = __commonJS({
16290
+ "server/src/services/security-log.js"(exports2, module2) {
16291
+ "use strict";
16292
+ var {
16293
+ ACTOR_TYPES,
16294
+ ADMIN_CONTENT_EVENTS,
16295
+ CONTENT_ACTIONS,
16296
+ EVENT_NAME_PATTERN,
16297
+ SECURITY_EVENTS,
16298
+ SIGN_IN_FILTERS,
16299
+ boundMeta,
16300
+ contentEvent,
16301
+ deriveSessionStates,
16302
+ pickEntryTitle,
16303
+ recordingSwitchOf,
16304
+ safeReason,
16305
+ toIso,
16306
+ toLocation,
16307
+ toObject
16308
+ } = require_security_log_model();
16309
+ var {
16310
+ anonymizeIp,
16311
+ describeUserAgent,
16312
+ hashDeviceId,
16313
+ normalizeIp
16314
+ } = require_admin_request_info();
16315
+ var { resolveSecurityLogSettings } = require_security_log_settings();
16316
+ var { getPluginSettings } = require_settings_loader();
16317
+ var { shouldResolveGeoData } = require_enhance_session();
16318
+ var { createLogger } = require_logger();
16319
+ var EVENT_UID = "plugin::magic-sessionmanager.security-event";
16320
+ var ADMIN_USER_UID = "admin::user";
16321
+ var ADMIN_SESSION_UID = "admin::session";
16322
+ var PERMISSION_UID = "admin::permission";
16323
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
16324
+ var FLUSH_DELAY_MS = 1e3;
16325
+ var FLUSH_BATCH = 200;
16326
+ var MAX_QUEUE = 2e3;
16327
+ var VIEW_DEDUP_MS = 10 * 60 * 1e3;
16328
+ var LOCKOUT_DEDUP_MS = 5 * 60 * 1e3;
16329
+ var MAX_DEDUP_KEYS = 2e4;
16330
+ var GEO_LOOKUPS_PER_FLUSH = 20;
16331
+ var MAIN_FIELD_TTL_MS = 5 * 60 * 1e3;
16332
+ var EXPORT_BATCH = 500;
16333
+ var DELETE_BATCH = 1e3;
16334
+ var MAX_DELETE_STEPS = 200;
16335
+ function toId(value) {
16336
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
16337
+ if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
16338
+ return null;
16339
+ }
16340
+ function toAdminId(value) {
16341
+ const id = Number(value);
16342
+ return Number.isInteger(id) && id > 0 && id < 1e12 ? id : null;
16343
+ }
16344
+ function adminName(user) {
16345
+ if (!user) return "";
16346
+ const name = [user.firstname, user.lastname].filter((part) => typeof part === "string" && part.trim()).join(" ").trim();
16347
+ return (name || user.username || user.email || "").slice(0, 200);
16348
+ }
16349
+ function pruneDedup(map, now, windowMs) {
16350
+ if (map.size <= MAX_DEDUP_KEYS) return;
16351
+ for (const [key, at] of map) if (now - at >= windowMs) map.delete(key);
16352
+ while (map.size > MAX_DEDUP_KEYS) {
16353
+ const first = map.keys().next().value;
16354
+ if (first === void 0) break;
16355
+ map.delete(first);
16356
+ }
16357
+ }
16358
+ function deviceHashOf(meta) {
16359
+ const value = toObject(meta).deviceHash;
16360
+ return typeof value === "string" ? value : null;
16361
+ }
16362
+ module2.exports = ({ strapi: strapi2 }) => {
16363
+ const log = createLogger(strapi2);
16364
+ let queue = [];
16365
+ let timer = null;
16366
+ let flushing = null;
16367
+ let stopped = false;
16368
+ let dropped = 0;
16369
+ const viewed = /* @__PURE__ */ new Map();
16370
+ const lockouts = /* @__PURE__ */ new Map();
16371
+ const mainFields = /* @__PURE__ */ new Map();
16372
+ const events = () => strapi2.db.query(EVENT_UID);
16373
+ const schedule = () => {
16374
+ if (timer || stopped) return;
16375
+ timer = setTimeout(() => {
16376
+ timer = null;
16377
+ service.flush().catch(() => {
16378
+ });
16379
+ }, FLUSH_DELAY_MS);
16380
+ if (typeof timer.unref === "function") timer.unref();
16381
+ };
16382
+ const mainFieldOf = async (uid) => {
16383
+ const now = Date.now();
16384
+ const cachedField = mainFields.get(uid);
16385
+ if (cachedField && now - cachedField.at < MAIN_FIELD_TTL_MS) return cachedField.field;
16386
+ let field;
16387
+ try {
16388
+ const contentTypes2 = strapi2.plugin("content-manager")?.service("content-types");
16389
+ const configuration = contentTypes2 ? await contentTypes2.findConfiguration({ uid }) : null;
16390
+ const configured = configuration?.settings?.mainField;
16391
+ field = typeof configured === "string" ? configured : null;
16392
+ } catch {
16393
+ field = null;
16394
+ }
16395
+ mainFields.set(uid, { field, at: now });
16396
+ return field;
16397
+ };
16398
+ const loadAdmins = async (ids) => {
16399
+ const unique = [...new Set(ids.map(toAdminId).filter((id) => id !== null))];
16400
+ if (!unique.length) return /* @__PURE__ */ new Map();
16401
+ const rows = await strapi2.db.query(ADMIN_USER_UID).findMany({
16402
+ where: { id: { $in: unique } },
16403
+ select: ["id", "firstname", "lastname", "username", "email"]
16404
+ });
16405
+ return new Map((Array.isArray(rows) ? rows : []).map((row) => [Number(row.id), row]));
16406
+ };
16407
+ const titleFromLog = async (targetType, targetId) => {
16408
+ const rows = await events().findMany({
16409
+ select: ["meta"],
16410
+ where: { targetType, targetId, event: { $startsWith: "admin.content." } },
16411
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16412
+ limit: 10
16413
+ });
16414
+ for (const row of Array.isArray(rows) ? rows : []) {
16415
+ const title = toObject(row.meta).title;
16416
+ if (typeof title === "string" && title) return title;
16417
+ }
16418
+ return null;
16419
+ };
16420
+ const buildRows = async (batch, options, settings) => {
16421
+ const wanted = batch.filter((entry) => {
16422
+ const gate = recordingSwitchOf(entry.event);
16423
+ return gate === "always" || (gate === "signIns" ? options.signIns : options.content);
16424
+ });
16425
+ if (!wanted.length) return [];
16426
+ const emails = [
16427
+ ...new Set(
16428
+ wanted.map((entry) => typeof entry.attemptedEmail === "string" ? entry.attemptedEmail : "").filter((email) => email && email.length <= 254).map((email) => email.toLowerCase())
16429
+ )
16430
+ ];
16431
+ const byEmail = /* @__PURE__ */ new Map();
16432
+ if (emails.length) {
16433
+ const found = await strapi2.db.query(ADMIN_USER_UID).findMany({
16434
+ where: { email: { $in: emails } },
16435
+ select: ["id", "email"]
16436
+ });
16437
+ for (const row of Array.isArray(found) ? found : []) {
16438
+ byEmail.set(String(row.email).toLowerCase(), Number(row.id));
16439
+ }
16440
+ }
16441
+ const geoService = options.storeIp && shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null;
16442
+ const geoCache = /* @__PURE__ */ new Map();
16443
+ let geoBudget = GEO_LOOKUPS_PER_FLUSH;
16444
+ const knownTitles = /* @__PURE__ */ new Map();
16445
+ for (const entry of wanted) {
16446
+ const title = entry.entryData && entry.targetType && entry.targetId ? pickEntryTitle(entry.entryData, await mainFieldOf(entry.targetType)) : null;
16447
+ if (title) knownTitles.set(`${entry.targetType}|${toId(entry.targetId)}`, title);
16448
+ }
16449
+ const rows = [];
16450
+ for (const entry of wanted) {
16451
+ const ip = options.storeIp ? normalizeIp(entry.ip) : null;
16452
+ const storedIp = ip && options.anonymizeIp ? anonymizeIp(ip) : ip;
16453
+ let geo = null;
16454
+ if (storedIp && geoService) {
16455
+ if (geoCache.has(storedIp)) {
16456
+ geo = geoCache.get(storedIp) || null;
16457
+ } else if (geoBudget > 0) {
16458
+ geoBudget -= 1;
16459
+ try {
16460
+ const info = await geoService.getIpInfo(storedIp);
16461
+ geo = info && info._status === "ok" ? {
16462
+ country: info.country || null,
16463
+ country_code: info.country_code || null,
16464
+ city: info.city || null
16465
+ } : null;
16466
+ } catch {
16467
+ geo = null;
16468
+ }
16469
+ geoCache.set(storedIp, geo);
16470
+ }
16471
+ }
16472
+ let targetId = toId(entry.targetId);
16473
+ let actorId = toId(entry.actorId);
16474
+ if (!targetId && typeof entry.attemptedEmail === "string") {
16475
+ const found = byEmail.get(entry.attemptedEmail.toLowerCase());
16476
+ targetId = found ? String(found) : null;
16477
+ if (entry.actorFromEmail && !actorId) actorId = targetId;
16478
+ }
16479
+ const meta = { ...entry.meta || {} };
16480
+ const deviceHash = entry.deviceHash || hashDeviceId(entry.deviceId);
16481
+ if (deviceHash) meta.deviceHash = deviceHash;
16482
+ if (storedIp && options.anonymizeIp) meta.ipAnonymized = true;
16483
+ if (entry.entryData && entry.targetType) {
16484
+ const title = pickEntryTitle(entry.entryData, await mainFieldOf(entry.targetType));
16485
+ if (title) meta.title = title;
16486
+ }
16487
+ if (!meta.title && entry.event.startsWith("admin.content.") && entry.targetType) {
16488
+ const id = toId(entry.targetId);
16489
+ if (id) {
16490
+ const key = `${entry.targetType}|${id}`;
16491
+ if (!knownTitles.has(key)) knownTitles.set(key, await titleFromLog(entry.targetType, id));
16492
+ const known = knownTitles.get(key);
16493
+ if (known) meta.title = known;
16494
+ }
16495
+ }
16496
+ const occurredAt = entry.occurredAt || /* @__PURE__ */ new Date();
16497
+ rows.push({
16498
+ event: entry.event,
16499
+ actorType: entry.actorType,
16500
+ actorId,
16501
+ targetType: typeof entry.targetType === "string" ? entry.targetType.slice(0, 191) : null,
16502
+ targetId,
16503
+ ip: storedIp,
16504
+ userAgent: typeof entry.userAgent === "string" && entry.userAgent ? entry.userAgent.slice(0, 500) : null,
16505
+ geo,
16506
+ meta: boundMeta(meta),
16507
+ createdAt: occurredAt,
16508
+ updatedAt: occurredAt
16509
+ });
16510
+ }
16511
+ return rows;
16512
+ };
16513
+ const deleteOlderThan = async (cutoff) => {
16514
+ let deleted = 0;
16515
+ for (let step = 0; step < MAX_DELETE_STEPS; step += 1) {
16516
+ const rows = await events().findMany({
16517
+ select: ["id"],
16518
+ where: { createdAt: { $lt: cutoff } },
16519
+ orderBy: { id: "asc" },
16520
+ limit: DELETE_BATCH
16521
+ });
16522
+ const ids = (Array.isArray(rows) ? rows : []).map((row) => row.id);
16523
+ if (!ids.length) break;
16524
+ const result = await events().deleteMany({ where: { id: { $in: ids } } });
16525
+ deleted += Number(result?.count ?? ids.length);
16526
+ if (ids.length < DELETE_BATCH) break;
16527
+ }
16528
+ return deleted;
16529
+ };
16530
+ const writeQueued = async () => {
16531
+ while (queue.length) {
16532
+ const batch = queue;
16533
+ queue = [];
16534
+ let settings;
16535
+ try {
16536
+ settings = await getPluginSettings(strapi2);
16537
+ } catch {
16538
+ return;
16539
+ }
16540
+ try {
16541
+ const rows = await buildRows(batch, resolveSecurityLogSettings(settings), settings);
16542
+ for (let i = 0; i < rows.length; i += FLUSH_BATCH) {
16543
+ await events().createMany({ data: rows.slice(i, i + FLUSH_BATCH) });
16544
+ }
16545
+ } catch (err) {
16546
+ log.warn("[security-log] Events could not be written:", err?.name || "Error");
16547
+ }
16548
+ }
16549
+ if (dropped > 0) {
16550
+ log.warn(`[security-log] ${dropped} queued events were dropped (queue full)`);
16551
+ dropped = 0;
16552
+ }
16553
+ };
16554
+ const service = {
16555
+ /**
16556
+ * Queues one security event. Returns at once; nothing is awaited.
16557
+ * Unknown event names or actor types are ignored.
16558
+ *
16559
+ * @param {SecurityEventInput} input Event.
16560
+ * @returns {boolean} Whether the event was queued.
16561
+ * @sideeffect Adds to the in-memory queue; the flush stores it when its switch is on.
16562
+ */
16563
+ record(input) {
16564
+ if (stopped || !input || typeof input.event !== "string") return false;
16565
+ if (!EVENT_NAME_PATTERN.test(input.event) || !ACTOR_TYPES.includes(input.actorType)) {
16566
+ return false;
16567
+ }
16568
+ const now = Date.now();
16569
+ if (input.event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
16570
+ const who = String(input.attemptedEmail || input.targetId || "").toLowerCase();
16571
+ const key = `${who}|${input.ip || ""}`;
16572
+ const last = lockouts.get(key);
16573
+ if (last !== void 0 && now - last < LOCKOUT_DEDUP_MS) return false;
16574
+ lockouts.set(key, now);
16575
+ pruneDedup(lockouts, now, LOCKOUT_DEDUP_MS);
16576
+ }
16577
+ queue.push({ ...input, occurredAt: input.occurredAt || new Date(now) });
16578
+ if (queue.length > MAX_QUEUE) {
16579
+ dropped += queue.length - MAX_QUEUE;
16580
+ queue = queue.slice(queue.length - MAX_QUEUE);
16581
+ }
16582
+ schedule();
16583
+ return true;
16584
+ },
16585
+ /**
16586
+ * Queues one Content Manager action of an admin as
16587
+ * `admin.content.<action>` with the entry as target (`targetType` = content
16588
+ * type uid, `targetId` = document id). Opening the same entry (same
16589
+ * admin, type, document and locale) again within 10 minutes, or right
16590
+ * after writing it, is not a new "view".
16591
+ *
16592
+ * @param {{adminUserId: number|string, action: string, kind: 'collection'|'single',
16593
+ * contentType: string, documentId: string|null, locale: string|null,
16594
+ * count: number|null, data?: any}} input Action.
16595
+ * @returns {boolean} Whether the action was queued.
16596
+ */
16597
+ recordContentAction(input) {
16598
+ if (stopped || !input || !CONTENT_ACTIONS.includes(input.action)) return false;
16599
+ const now = Date.now();
16600
+ const key = `${input.adminUserId}|${input.contentType}|${input.documentId || ""}|${input.locale || ""}`;
16601
+ if (input.documentId || input.kind === "single") {
16602
+ if (input.action === "view") {
16603
+ const last = viewed.get(key);
16604
+ if (last !== void 0 && now - last < VIEW_DEDUP_MS) return false;
16605
+ }
16606
+ viewed.delete(key);
16607
+ viewed.set(key, now);
16608
+ pruneDedup(viewed, now, VIEW_DEDUP_MS);
16609
+ }
16610
+ return service.record({
16611
+ event: contentEvent(input.action),
16612
+ actorType: "admin",
16613
+ actorId: input.adminUserId,
16614
+ targetType: input.contentType,
16615
+ targetId: input.documentId,
16616
+ meta: {
16617
+ kind: input.kind,
16618
+ locale: input.locale || null,
16619
+ ...typeof input.count === "number" ? { count: input.count } : {}
16620
+ },
16621
+ entryData: input.data || null
16622
+ });
16623
+ },
16624
+ /**
16625
+ * Writes everything queued. Concurrent calls share one run.
16626
+ *
16627
+ * @returns {Promise<void>}
16628
+ * @sideeffect Inserts rows into the security event table; may call the GeoIP provider.
16629
+ */
16630
+ async flush() {
16631
+ if (flushing) return flushing;
16632
+ if (!queue.length) return void 0;
16633
+ flushing = writeQueued().finally(() => {
16634
+ flushing = null;
16635
+ });
16636
+ return flushing;
16637
+ },
16638
+ /**
16639
+ * Stops recording and writes what is queued (plugin destroy).
16640
+ *
16641
+ * @returns {Promise<void>}
16642
+ */
16643
+ async stop() {
16644
+ stopped = true;
16645
+ if (timer) clearTimeout(timer);
16646
+ timer = null;
16647
+ await service.flush().catch(() => {
16648
+ });
16649
+ },
16650
+ /** @returns {boolean} Whether recording was stopped. */
16651
+ isStopped() {
16652
+ return stopped;
16653
+ },
16654
+ /**
16655
+ * One page of the admin sign-in history, newest first, with names of the
16656
+ * admins involved and the session state of each sign-in.
16657
+ *
16658
+ * @param {{adminId?: number, event?: keyof typeof SIGN_IN_FILTERS, from?: Date|null,
16659
+ * to?: Date|null, page: number, pageSize: number}} query Parsed filters.
16660
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
16661
+ */
16662
+ async listSignIns(query) {
16663
+ const where = signInWhere(query);
16664
+ const [total, rows] = await Promise.all([
16665
+ events().count({ where }),
16666
+ events().findMany({
16667
+ where,
16668
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16669
+ offset: (query.page - 1) * query.pageSize,
16670
+ limit: query.pageSize
16671
+ })
16672
+ ]);
16673
+ return {
16674
+ data: await shapeSignIns(Array.isArray(rows) ? rows : []),
16675
+ meta: {
16676
+ pagination: paginationOf(query, total),
16677
+ recording: await recordingFlags()
16678
+ }
16679
+ };
16680
+ },
16681
+ /**
16682
+ * One page of Content Manager activity, newest first.
16683
+ *
16684
+ * @param {{adminId?: number, action?: string, contentType?: string, from?: Date|null,
16685
+ * to?: Date|null, page: number, pageSize: number}} query Parsed filters.
16686
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
16687
+ */
16688
+ async listContentActivity(query) {
16689
+ const where = activityWhere(query);
16690
+ const [total, rows] = await Promise.all([
16691
+ events().count({ where }),
16692
+ events().findMany({
16693
+ where,
16694
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16695
+ offset: (query.page - 1) * query.pageSize,
16696
+ limit: query.pageSize
16697
+ })
16698
+ ]);
16699
+ return {
16700
+ data: await shapeActivity(Array.isArray(rows) ? rows : []),
16701
+ meta: {
16702
+ pagination: paginationOf(query, total),
16703
+ recording: await recordingFlags(),
16704
+ contentTypes: listContentTypes(),
16705
+ ...query.adminId ? { contentManagerAccess: await service.hasContentManagerAccess(query.adminId) } : {}
16706
+ }
16707
+ };
16708
+ },
16709
+ /**
16710
+ * One export batch (newest first, keyset on id) of either list.
16711
+ *
16712
+ * @param {'sign-ins'|'content'} kind List.
16713
+ * @param {any} query Parsed filters (as for the list).
16714
+ * @param {number|null} cursor Id below which to continue.
16715
+ * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
16716
+ */
16717
+ async exportBatch(kind, query, cursor) {
16718
+ const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
16719
+ const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
16720
+ const rows = await events().findMany({
16721
+ where,
16722
+ orderBy: [{ id: "desc" }],
16723
+ limit: EXPORT_BATCH
16724
+ });
16725
+ const list = Array.isArray(rows) ? rows : [];
16726
+ const data = kind === "sign-ins" ? await shapeSignIns(list) : await shapeActivity(list);
16727
+ const last = list[list.length - 1];
16728
+ return {
16729
+ data,
16730
+ meta: { nextCursor: list.length === EXPORT_BATCH && last ? String(last.id) : null }
16731
+ };
16732
+ },
16733
+ /**
16734
+ * Whether an admin can use the Content Manager: Super Admin, or a role
16735
+ * with any `plugin::content-manager.explorer.*` permission.
16736
+ *
16737
+ * @param {number} adminId Admin id.
16738
+ * @returns {Promise<boolean|null>} Null when the admin does not exist.
16739
+ */
16740
+ async hasContentManagerAccess(adminId) {
16741
+ const user = await strapi2.db.query(ADMIN_USER_UID).findOne({
16742
+ where: { id: adminId },
16743
+ select: ["id"],
16744
+ populate: { roles: { select: ["id", "code"] } }
16745
+ });
16746
+ if (!user) return null;
16747
+ const roles = Array.isArray(user.roles) ? user.roles : [];
16748
+ if (roles.some((role) => role?.code === SUPER_ADMIN_CODE)) return true;
16749
+ const roleIds = roles.map((role) => role.id).filter((id) => id !== void 0);
16750
+ if (!roleIds.length) return false;
16751
+ const count = await strapi2.db.query(PERMISSION_UID).count({
16752
+ where: {
16753
+ role: { id: { $in: roleIds } },
16754
+ action: { $startsWith: "plugin::content-manager.explorer." }
16755
+ }
16756
+ });
16757
+ return Number(count) > 0;
16758
+ },
16759
+ /**
16760
+ * Retention for the whole log: deletes events older than the configured
16761
+ * number of days, and the events of admins that no longer exist (where a
16762
+ * deleted admin signed someone else out, only the actor is cleared).
16763
+ *
16764
+ * @param {{now?: Date}} [options] Clock for tests.
16765
+ * @returns {Promise<{expired: number, orphans: number}>} Deleted rows.
16766
+ * @sideeffect Deletes and updates rows of the security event table.
16767
+ */
16768
+ async cleanup({ now = /* @__PURE__ */ new Date() } = {}) {
16769
+ const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
16770
+ const cutoff = new Date(now.getTime() - options.retentionDays * 24 * 60 * 60 * 1e3);
16771
+ const expired = await deleteOlderThan(cutoff);
16772
+ const admins = await strapi2.db.query(ADMIN_USER_UID).findMany({ select: ["id"] });
16773
+ const existing = (Array.isArray(admins) ? admins : []).map((row) => String(row.id));
16774
+ let orphans = 0;
16775
+ if (existing.length) {
16776
+ const removed = await events().deleteMany({
16777
+ where: {
16778
+ $or: [
16779
+ { targetType: "admin", targetId: { $notNull: true, $notIn: existing } },
16780
+ {
16781
+ actorType: "admin",
16782
+ actorId: { $notNull: true, $notIn: existing },
16783
+ event: { $ne: SECURITY_EVENTS.ADMIN_SESSION_REVOKED }
16784
+ }
16785
+ ]
16786
+ }
16787
+ });
16788
+ orphans = Number(removed?.count || 0);
16789
+ await events().updateMany({
16790
+ where: {
16791
+ event: SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
16792
+ actorType: "admin",
16793
+ actorId: { $notNull: true, $notIn: existing }
16794
+ },
16795
+ data: { actorId: null }
16796
+ });
16797
+ }
16798
+ return { expired, orphans };
16799
+ },
16800
+ /**
16801
+ * Deletes what was recorded about an admin whose account was deleted:
16802
+ * events they did and events about their account. Where they signed
16803
+ * someone else out, the actor reference is cleared and the target keeps
16804
+ * the event.
16805
+ *
16806
+ * @param {number} adminId Deleted admin id.
16807
+ * @returns {Promise<void>}
16808
+ * @sideeffect Deletes and updates rows of the security event table.
16809
+ */
16810
+ async deleteAdminData(adminId) {
16811
+ const id = toAdminId(adminId);
16812
+ if (!id) return;
16813
+ const key = String(id);
16814
+ queue = queue.filter(
16815
+ (entry) => !(entry.actorType === "admin" && String(entry.actorId) === key) && !(entry.targetType === "admin" && String(entry.targetId) === key)
16816
+ );
16817
+ await events().deleteMany({
16818
+ where: {
16819
+ $or: [
16820
+ { targetType: "admin", targetId: key },
16821
+ {
16822
+ actorType: "admin",
16823
+ actorId: key,
16824
+ event: { $ne: SECURITY_EVENTS.ADMIN_SESSION_REVOKED }
16825
+ }
16826
+ ]
16827
+ }
16828
+ });
16829
+ await events().updateMany({
16830
+ where: { event: SECURITY_EVENTS.ADMIN_SESSION_REVOKED, actorType: "admin", actorId: key },
16831
+ data: { actorId: null }
16832
+ });
16833
+ }
16834
+ };
16835
+ function paginationOf(query, total) {
16836
+ const count = Number(total) || 0;
16837
+ return {
16838
+ page: query.page,
16839
+ pageSize: query.pageSize,
16840
+ total: count,
16841
+ pageCount: Math.max(1, Math.ceil(count / query.pageSize))
16842
+ };
16843
+ }
16844
+ function signInWhere(query) {
16845
+ const conditions = [{ event: { $in: [...SIGN_IN_FILTERS[query.event || "all"]] } }];
16846
+ if (query.adminId) conditions.push({ targetType: "admin", targetId: String(query.adminId) });
16847
+ if (query.from) conditions.push({ createdAt: { $gte: query.from } });
16848
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
16849
+ return { $and: conditions };
16850
+ }
16851
+ function activityWhere(query) {
16852
+ const conditions = [
16853
+ {
16854
+ event: query.action && query.action !== "all" ? contentEvent(query.action) : { $in: [...ADMIN_CONTENT_EVENTS] }
16855
+ }
16856
+ ];
16857
+ if (query.adminId) conditions.push({ actorType: "admin", actorId: String(query.adminId) });
16858
+ if (query.contentType) conditions.push({ targetType: query.contentType });
16859
+ if (query.from) conditions.push({ createdAt: { $gte: query.from } });
16860
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
16861
+ return { $and: conditions };
16862
+ }
16863
+ async function recordingFlags() {
16864
+ let settings;
16865
+ try {
16866
+ settings = await getPluginSettings(strapi2);
16867
+ } catch {
16868
+ settings = {};
16869
+ }
16870
+ const options = resolveSecurityLogSettings(settings);
16871
+ return {
16872
+ signIns: options.signIns,
16873
+ contentActivity: options.content,
16874
+ ipAddresses: options.storeIp,
16875
+ anonymizeIp: options.anonymizeIp,
16876
+ retentionDays: options.retentionDays
16877
+ };
16878
+ }
16879
+ function listContentTypes() {
16880
+ return Object.entries(strapi2.contentTypes || {}).filter(([uid, type]) => {
16881
+ const visible = (
16882
+ /** @type {any} */
16883
+ type?.pluginOptions?.["content-manager"]?.visible
16884
+ );
16885
+ return uid.startsWith("api::") && visible !== false;
16886
+ }).map(([uid, type]) => ({
16887
+ uid,
16888
+ name: String(
16889
+ /** @type {any} */
16890
+ type?.info?.displayName || uid
16891
+ ).slice(0, 120),
16892
+ kind: (
16893
+ /** @type {any} */
16894
+ type?.kind === "singleType" ? "single" : "collection"
16895
+ )
16896
+ })).sort((a, b) => a.name.localeCompare(b.name));
16897
+ }
16898
+ async function shapeSignIns(rows) {
16899
+ const admins = await loadAdmins(rows.flatMap((row) => [row.targetId, row.actorId]));
16900
+ const states = await sessionStates(rows);
16901
+ return rows.map((row) => {
16902
+ const meta = toObject(row.meta);
16903
+ const admin = row.targetType === "admin" ? admins.get(Number(row.targetId)) : void 0;
16904
+ const revoked = row.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
16905
+ const actor = revoked ? admins.get(Number(row.actorId)) : void 0;
16906
+ const described = describeUserAgent(row.userAgent || null);
16907
+ const state = states.get(Number(row.id));
16908
+ return {
16909
+ id: Number(row.id),
16910
+ event: row.event,
16911
+ reason: safeReason(meta.reason),
16912
+ provider: safeReason(meta.provider),
16913
+ scope: revoked ? safeReason(meta.scope) : null,
16914
+ at: toIso(row.createdAt),
16915
+ ipAddress: row.ip || null,
16916
+ ipAnonymized: meta.ipAnonymized === true,
16917
+ location: toLocation(row.geo),
16918
+ browser: described.browserName,
16919
+ os: described.osName,
16920
+ deviceType: described.deviceType,
16921
+ admin: admin ? { id: Number(admin.id), name: adminName(admin) } : null,
16922
+ actor: actor ? { id: Number(actor.id), name: adminName(actor) } : null,
16923
+ session: row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && state ? { state: state.state, endedAt: toIso(state.endedAt) } : null
16924
+ };
16925
+ });
16926
+ }
16927
+ async function sessionStates(rows) {
16928
+ const list = rows.filter(
16929
+ (row) => row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && toAdminId(row.targetId)
16930
+ );
16931
+ if (!list.length) return /* @__PURE__ */ new Map();
16932
+ const adminIds = [...new Set(list.map((row) => String(row.targetId)))];
16933
+ const oldest = new Date(
16934
+ Math.min(...list.map((row) => new Date(toIso(row.createdAt) || Date.now()).getTime()))
16935
+ );
16936
+ const later = await events().findMany({
16937
+ select: ["id", "event", "targetId", "actorId", "meta", "createdAt"],
16938
+ where: {
16939
+ targetType: "admin",
16940
+ targetId: { $in: adminIds },
16941
+ event: {
16942
+ $in: [
16943
+ SECURITY_EVENTS.ADMIN_SIGN_IN,
16944
+ SECURITY_EVENTS.ADMIN_SIGN_OUT,
16945
+ SECURITY_EVENTS.ADMIN_SESSION_REVOKED
16946
+ ]
16947
+ },
16948
+ createdAt: { $gte: oldest }
16949
+ },
16950
+ orderBy: [{ createdAt: "asc" }],
16951
+ limit: 5e3
16952
+ });
16953
+ const live = /* @__PURE__ */ new Map();
16954
+ if (strapi2.contentTypes?.[ADMIN_SESSION_UID]) {
16955
+ const now = /* @__PURE__ */ new Date();
16956
+ const sessions = await strapi2.db.query(ADMIN_SESSION_UID).findMany({
16957
+ select: ["userId", "deviceId"],
16958
+ where: {
16959
+ origin: "admin",
16960
+ status: "active",
16961
+ userId: { $in: adminIds },
16962
+ expiresAt: { $gt: now },
16963
+ $or: [{ absoluteExpiresAt: { $null: true } }, { absoluteExpiresAt: { $gt: now } }]
16964
+ },
16965
+ limit: 1e4
16966
+ });
16967
+ for (const session of Array.isArray(sessions) ? sessions : []) {
16968
+ const hash = hashDeviceId(session.deviceId);
16969
+ if (!hash) continue;
16970
+ const key = String(session.userId);
16971
+ if (!live.has(key)) live.set(key, /* @__PURE__ */ new Set());
16972
+ live.get(key)?.add(hash);
16973
+ }
16974
+ }
16975
+ const toEvent = (row) => ({
16976
+ id: Number(row.id),
16977
+ adminId: String(row.targetId),
16978
+ event: row.event,
16979
+ actorId: row.actorId ? String(row.actorId) : null,
16980
+ deviceHash: deviceHashOf(row.meta),
16981
+ at: toIso(row.createdAt) || ""
16982
+ });
16983
+ return deriveSessionStates(
16984
+ list.map(toEvent),
16985
+ (Array.isArray(later) ? later : []).map(toEvent),
16986
+ live
16987
+ );
16988
+ }
16989
+ async function shapeActivity(rows) {
16990
+ const admins = await loadAdmins(rows.map((row) => row.actorId));
16991
+ return rows.map((row) => {
16992
+ const meta = toObject(row.meta);
16993
+ const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
16994
+ const type = strapi2.contentTypes?.[row.targetType];
16995
+ return {
16996
+ id: Number(row.id),
16997
+ action: String(row.event).replace(/^admin\.content\./, ""),
16998
+ at: toIso(row.createdAt),
16999
+ contentType: {
17000
+ uid: row.targetType,
17001
+ name: String(type?.info?.displayName || row.targetType).slice(0, 120),
17002
+ kind: meta.kind === "single" ? "single" : "collection",
17003
+ exists: Boolean(type)
17004
+ },
17005
+ entry: {
17006
+ documentId: row.targetId || null,
17007
+ locale: typeof meta.locale === "string" ? meta.locale : null,
17008
+ title: typeof meta.title === "string" ? meta.title : null,
17009
+ count: typeof meta.count === "number" ? meta.count : null
17010
+ },
17011
+ admin: admin ? { id: Number(admin.id), name: adminName(admin) } : null
17012
+ };
17013
+ });
17014
+ }
17015
+ return service;
17016
+ };
17017
+ module2.exports.EVENT_UID = EVENT_UID;
17018
+ module2.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
17019
+ }
17020
+ });
17021
+
14823
17022
  // server/src/services/index.js
14824
17023
  var require_services = __commonJS({
14825
17024
  "server/src/services/index.js"(exports2, module2) {
@@ -14827,10 +17026,12 @@ var require_services = __commonJS({
14827
17026
  var session = require_session2();
14828
17027
  var geolocation = require_geolocation();
14829
17028
  var notifications = require_notifications();
17029
+ var securityLog = require_security_log();
14830
17030
  module2.exports = {
14831
17031
  session,
14832
17032
  geolocation,
14833
- notifications
17033
+ notifications,
17034
+ "security-log": securityLog
14834
17035
  };
14835
17036
  }
14836
17037
  });