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
@@ -942,6 +942,16 @@ var require_register = __commonJS({
942
942
  uid: "admin-sessions.revoke",
943
943
  subCategory: "Admin panel",
944
944
  pluginName: "magic-sessionmanager"
945
+ },
946
+ // Admin sign-in history and Content Manager activity (4.15): who signed
947
+ // in from where and what each admin did. Separate from reading the
948
+ // sessions, because it shows IP addresses and work activity.
949
+ {
950
+ section: "plugins",
951
+ displayName: "View admin activity",
952
+ uid: "admin-activity.read",
953
+ subCategory: "Admin panel",
954
+ pluginName: "magic-sessionmanager"
945
955
  }
946
956
  ]);
947
957
  try {
@@ -1235,6 +1245,7 @@ var require_settings_loader = __commonJS({
1235
1245
  var cachedAt = 0;
1236
1246
  var cachedRevision = null;
1237
1247
  var revisionCheckedAt = 0;
1248
+ var generation = 0;
1238
1249
  function toIntInRange(value, fallback, min, max) {
1239
1250
  const n = Number.parseInt(value, 10);
1240
1251
  if (!Number.isFinite(n)) return fallback;
@@ -1300,7 +1311,12 @@ var require_settings_loader = __commonJS({
1300
1311
  // Opt-in: use a single-statement SQL UPDATE in the cleanup job instead
1301
1312
  // of batching via the Document Service. Bypasses lifecycle hooks but
1302
1313
  // drains the backlog in one query on very large installations.
1303
- "cleanupUseDbDirect"
1314
+ "cleanupUseDbDirect",
1315
+ // Security event log (4.15).
1316
+ "adminSignInHistory",
1317
+ "adminContentActivity",
1318
+ "securityLogStoreIp",
1319
+ "securityLogAnonymizeIp"
1304
1320
  ];
1305
1321
  if (stored.sessionCreationGraceMs !== void 0) {
1306
1322
  out.sessionCreationGraceMs = getSessionCreationGraceMs(stored);
@@ -1341,6 +1357,9 @@ var require_settings_loader = __commonJS({
1341
1357
  if (stored.emailTemplates && typeof stored.emailTemplates === "object") {
1342
1358
  out.emailTemplates = stored.emailTemplates;
1343
1359
  }
1360
+ if (stored.securityLogRetentionDays !== void 0) {
1361
+ out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 1, 730);
1362
+ }
1344
1363
  if (stored.trustedProxies !== void 0) {
1345
1364
  out.trustedProxies = stored.trustedProxies;
1346
1365
  }
@@ -1360,6 +1379,7 @@ var require_settings_loader = __commonJS({
1360
1379
  }
1361
1380
  if (revision2 === cachedRevision) return cached;
1362
1381
  }
1382
+ const loadGeneration = generation;
1363
1383
  let revision;
1364
1384
  try {
1365
1385
  revision = await coordinator.getRevision(SETTINGS_REVISION);
@@ -1379,6 +1399,7 @@ var require_settings_loader = __commonJS({
1379
1399
  storedSettings = { strictSessionEnforcement: true, enableGeolocation: false };
1380
1400
  }
1381
1401
  const merged = { ...staticConfig, ...storedSettings };
1402
+ if (loadGeneration !== generation) return merged;
1382
1403
  cached = merged;
1383
1404
  cachedAt = now;
1384
1405
  cachedRevision = revision;
@@ -1389,7 +1410,11 @@ var require_settings_loader = __commonJS({
1389
1410
  if (cached) return cached;
1390
1411
  return strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
1391
1412
  }
1413
+ function peekCachedSettings() {
1414
+ return cached;
1415
+ }
1392
1416
  function invalidateSettingsCache() {
1417
+ generation += 1;
1393
1418
  cached = null;
1394
1419
  cachedAt = 0;
1395
1420
  cachedRevision = null;
@@ -1413,6 +1438,7 @@ var require_settings_loader = __commonJS({
1413
1438
  module.exports = {
1414
1439
  getPluginSettings,
1415
1440
  getPluginSettingsSync,
1441
+ peekCachedSettings,
1416
1442
  invalidateSettingsCache,
1417
1443
  notifySettingsChanged,
1418
1444
  getSettingsRevision,
@@ -1479,10 +1505,75 @@ var require_rejection_cache = __commonJS({
1479
1505
  }
1480
1506
  });
1481
1507
 
1508
+ // server/src/utils/risk-data.js
1509
+ var require_risk_data = __commonJS({
1510
+ "server/src/utils/risk-data.js"(exports, module) {
1511
+ "use strict";
1512
+ var RISK_SOURCES = Object.freeze(["anonymous-ip", "asn-heuristic"]);
1513
+ var SUSPICIOUS_SCORE_BELOW = 70;
1514
+ var REJECT_SCORE_BELOW = 50;
1515
+ function noRiskData() {
1516
+ return {
1517
+ isVpn: false,
1518
+ isProxy: false,
1519
+ isThreat: false,
1520
+ isAnonymous: false,
1521
+ isTor: false,
1522
+ isHosting: false,
1523
+ securityScore: null,
1524
+ riskLevel: "Unknown",
1525
+ riskSource: null
1526
+ };
1527
+ }
1528
+ function hasRiskData(geoData) {
1529
+ return Boolean(geoData) && RISK_SOURCES.includes(geoData.riskSource);
1530
+ }
1531
+ function calculateSecurityScore({ isVpn, isProxy, isThreat, isAnonymous, isTor, isHosting }) {
1532
+ let score = 100;
1533
+ if (isTor) score -= 50;
1534
+ if (isThreat) score -= 40;
1535
+ if (isVpn) score -= 20;
1536
+ if (isHosting) score -= 20;
1537
+ if (isProxy) score -= 15;
1538
+ if (isAnonymous) score -= 10;
1539
+ return Math.max(0, score);
1540
+ }
1541
+ function getRiskLevel({ isVpn, isProxy, isThreat, isTor, isHosting }) {
1542
+ if (isThreat || isTor) return "High";
1543
+ if (isVpn && isProxy) return "Medium-High";
1544
+ if (isVpn || isProxy || isHosting) return "Medium";
1545
+ return "Low";
1546
+ }
1547
+ function evaluateLoginRisk(settings = {}, geoData = null) {
1548
+ if (!hasRiskData(geoData)) {
1549
+ return { hasRiskData: false, isSuspicious: false, isVpnOrProxy: false };
1550
+ }
1551
+ const scoreEvaluationEnabled = settings.enableSecurityScoring !== false;
1552
+ const lowScore = scoreEvaluationEnabled && typeof geoData.securityScore === "number" && geoData.securityScore < SUSPICIOUS_SCORE_BELOW;
1553
+ const isVpnOrProxy = Boolean(geoData.isVpn || geoData.isProxy);
1554
+ const isSuspicious = Boolean(
1555
+ isVpnOrProxy || geoData.isThreat || geoData.isTor || geoData.isHosting || lowScore
1556
+ );
1557
+ return { hasRiskData: true, isSuspicious, isVpnOrProxy };
1558
+ }
1559
+ module.exports = {
1560
+ REJECT_SCORE_BELOW,
1561
+ RISK_SOURCES,
1562
+ SUSPICIOUS_SCORE_BELOW,
1563
+ calculateSecurityScore,
1564
+ evaluateLoginRisk,
1565
+ getRiskLevel,
1566
+ hasRiskData,
1567
+ noRiskData
1568
+ };
1569
+ }
1570
+ });
1571
+
1482
1572
  // server/src/utils/geo-firewall.js
1483
1573
  var require_geo_firewall = __commonJS({
1484
1574
  "server/src/utils/geo-firewall.js"(exports, module) {
1485
1575
  "use strict";
1576
+ var { REJECT_SCORE_BELOW, hasRiskData } = require_risk_data();
1486
1577
  function normalizeCountryCode(value) {
1487
1578
  if (typeof value !== "string") return null;
1488
1579
  const normalized = value.trim().toUpperCase();
@@ -1502,27 +1593,20 @@ var require_geo_firewall = __commonJS({
1502
1593
  if (status === "private") {
1503
1594
  return { blocked: false, reason: null, status };
1504
1595
  }
1505
- if (status !== "ok") {
1506
- if (getLookupFailureMode(settings) === "block") {
1507
- return {
1508
- blocked: true,
1509
- reason: `geo_lookup_unavailable:${status}`,
1510
- status
1511
- };
1512
- }
1513
- return { blocked: false, reason: null, status };
1514
- }
1515
- if (settings.blockSuspiciousSessions) {
1596
+ if (settings.blockSuspiciousSessions && hasRiskData(geoData)) {
1516
1597
  if (geoData.isThreat) {
1517
1598
  return { blocked: true, reason: "threat_ip", status };
1518
1599
  }
1600
+ if (geoData.isTor) {
1601
+ return { blocked: true, reason: "tor_exit_node", status };
1602
+ }
1519
1603
  if (geoData.isVpn) {
1520
1604
  return { blocked: true, reason: "vpn_detected", status };
1521
1605
  }
1522
1606
  if (geoData.isProxy) {
1523
1607
  return { blocked: true, reason: "proxy_detected", status };
1524
1608
  }
1525
- if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < 50) {
1609
+ if (settings.enableSecurityScoring !== false && typeof geoData.securityScore === "number" && geoData.securityScore < REJECT_SCORE_BELOW) {
1526
1610
  return {
1527
1611
  blocked: true,
1528
1612
  reason: `low_security_score:${geoData.securityScore}`,
@@ -1530,6 +1614,16 @@ var require_geo_firewall = __commonJS({
1530
1614
  };
1531
1615
  }
1532
1616
  }
1617
+ if (status !== "ok") {
1618
+ if (getLookupFailureMode(settings) === "block") {
1619
+ return {
1620
+ blocked: true,
1621
+ reason: `geo_lookup_unavailable:${status}`,
1622
+ status
1623
+ };
1624
+ }
1625
+ return { blocked: false, reason: null, status };
1626
+ }
1533
1627
  if (settings.enableGeofencing) {
1534
1628
  const countryCode = normalizeCountryCode(geoData.country_code);
1535
1629
  const blockedCountries = normalizeCountryList(settings.blockedCountries);
@@ -1559,6 +1653,93 @@ var require_geo_firewall = __commonJS({
1559
1653
  }
1560
1654
  });
1561
1655
 
1656
+ // server/src/utils/login-alerts.js
1657
+ var require_login_alerts = __commonJS({
1658
+ "server/src/utils/login-alerts.js"(exports, module) {
1659
+ "use strict";
1660
+ var { evaluateLoginRisk } = require_risk_data();
1661
+ async function dispatchLoginAlerts({
1662
+ settings,
1663
+ notificationService,
1664
+ user,
1665
+ session,
1666
+ geoData,
1667
+ isNewLocation = false
1668
+ }) {
1669
+ const attempted = { webhookEvent: null, emails: [] };
1670
+ if (!geoData) return attempted;
1671
+ const risk = evaluateLoginRisk(settings, geoData);
1672
+ if (settings.enableEmailAlerts) {
1673
+ if (settings.alertOnVpnProxy && risk.isVpnOrProxy) {
1674
+ attempted.emails.push("vpnProxy");
1675
+ await notificationService.sendVpnProxyAlert({
1676
+ user,
1677
+ session,
1678
+ reason: { isVpn: geoData.isVpn, isProxy: geoData.isProxy },
1679
+ geoData
1680
+ });
1681
+ }
1682
+ if (settings.alertOnSuspiciousLogin && risk.isSuspicious) {
1683
+ attempted.emails.push("suspiciousLogin");
1684
+ await notificationService.sendSuspiciousLoginAlert({
1685
+ user,
1686
+ session,
1687
+ reason: {
1688
+ isVpn: geoData.isVpn,
1689
+ isProxy: geoData.isProxy,
1690
+ isThreat: geoData.isThreat,
1691
+ securityScore: geoData.securityScore
1692
+ },
1693
+ geoData
1694
+ });
1695
+ }
1696
+ if (settings.alertOnNewLocation && isNewLocation) {
1697
+ attempted.emails.push("newLocation");
1698
+ await notificationService.sendNewLocationAlert({ user, session, geoData });
1699
+ }
1700
+ }
1701
+ if (settings.enableWebhooks) {
1702
+ const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
1703
+ attempted.webhookEvent = webhookEvent;
1704
+ const targets = [];
1705
+ if (settings.discordWebhookUrl) {
1706
+ targets.push({
1707
+ url: settings.discordWebhookUrl,
1708
+ payload: notificationService.formatDiscordWebhook({
1709
+ event: webhookEvent,
1710
+ session,
1711
+ user,
1712
+ geoData
1713
+ })
1714
+ });
1715
+ }
1716
+ if (settings.slackWebhookUrl) {
1717
+ targets.push({
1718
+ url: settings.slackWebhookUrl,
1719
+ payload: notificationService.formatSlackWebhook({
1720
+ event: webhookEvent,
1721
+ session,
1722
+ user,
1723
+ geoData
1724
+ })
1725
+ });
1726
+ }
1727
+ await Promise.allSettled(
1728
+ targets.map(
1729
+ (target) => notificationService.sendWebhook({
1730
+ event: webhookEvent,
1731
+ data: target.payload,
1732
+ webhookUrl: target.url
1733
+ })
1734
+ )
1735
+ );
1736
+ }
1737
+ return attempted;
1738
+ }
1739
+ module.exports = { dispatchLoginAlerts };
1740
+ }
1741
+ });
1742
+
1562
1743
  // server/src/utils/session-revocation.js
1563
1744
  var require_session_revocation = __commonJS({
1564
1745
  "server/src/utils/session-revocation.js"(exports, module) {
@@ -2296,6 +2477,800 @@ var require_native_only_insight = __commonJS({
2296
2477
  }
2297
2478
  });
2298
2479
 
2480
+ // server/src/utils/security-log-model.js
2481
+ var require_security_log_model = __commonJS({
2482
+ "server/src/utils/security-log-model.js"(exports, module) {
2483
+ "use strict";
2484
+ var SECURITY_EVENTS = Object.freeze({
2485
+ ADMIN_SIGN_IN: "admin.sign-in",
2486
+ ADMIN_SIGN_IN_FAILED: "admin.sign-in.failed",
2487
+ ADMIN_LOCKOUT: "admin.lockout",
2488
+ ADMIN_SIGN_OUT: "admin.sign-out",
2489
+ ADMIN_SESSION_REVOKED: "admin.session.revoked",
2490
+ ADMIN_CONTENT_VIEW: "admin.content.view",
2491
+ ADMIN_CONTENT_CREATE: "admin.content.create",
2492
+ ADMIN_CONTENT_UPDATE: "admin.content.update",
2493
+ ADMIN_CONTENT_PUBLISH: "admin.content.publish",
2494
+ ADMIN_CONTENT_UNPUBLISH: "admin.content.unpublish",
2495
+ ADMIN_CONTENT_DISCARD: "admin.content.discard",
2496
+ ADMIN_CONTENT_DELETE: "admin.content.delete",
2497
+ ADMIN_CONTENT_CLONE: "admin.content.clone"
2498
+ });
2499
+ var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
2500
+ var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
2501
+ var ADMIN_SIGN_IN_EVENTS = Object.freeze([
2502
+ SECURITY_EVENTS.ADMIN_SIGN_IN,
2503
+ SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
2504
+ SECURITY_EVENTS.ADMIN_LOCKOUT,
2505
+ SECURITY_EVENTS.ADMIN_SIGN_OUT,
2506
+ SECURITY_EVENTS.ADMIN_SESSION_REVOKED
2507
+ ]);
2508
+ var SIGN_IN_FILTERS = Object.freeze({
2509
+ all: ADMIN_SIGN_IN_EVENTS,
2510
+ succeeded: [SECURITY_EVENTS.ADMIN_SIGN_IN],
2511
+ failed: [SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED, SECURITY_EVENTS.ADMIN_LOCKOUT],
2512
+ "signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED]
2513
+ });
2514
+ var CONTENT_ACTIONS = Object.freeze([
2515
+ "view",
2516
+ "create",
2517
+ "update",
2518
+ "publish",
2519
+ "unpublish",
2520
+ "discard",
2521
+ "delete",
2522
+ "clone"
2523
+ ]);
2524
+ var contentEvent = (action) => `admin.content.${action}`;
2525
+ var ADMIN_CONTENT_EVENTS = Object.freeze(CONTENT_ACTIONS.map(contentEvent));
2526
+ function recordingSwitchOf(event) {
2527
+ if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
2528
+ if (event.startsWith("admin.content.")) return "content";
2529
+ return "always";
2530
+ }
2531
+ var CONTENT_MANAGER_HANDLERS = Object.freeze({
2532
+ "collection-types.findOne": { action: "view", kind: "collection" },
2533
+ "collection-types.create": { action: "create", kind: "collection" },
2534
+ "collection-types.update": { action: "update", kind: "collection" },
2535
+ "collection-types.clone": { action: "clone", kind: "collection" },
2536
+ "collection-types.autoClone": { action: "clone", kind: "collection" },
2537
+ "collection-types.publish": { action: "publish", kind: "collection" },
2538
+ "collection-types.unpublish": { action: "unpublish", kind: "collection" },
2539
+ "collection-types.discard": { action: "discard", kind: "collection" },
2540
+ "collection-types.delete": { action: "delete", kind: "collection" },
2541
+ "collection-types.bulkDelete": { action: "delete", kind: "collection", bulk: true },
2542
+ "collection-types.bulkPublish": { action: "publish", kind: "collection", bulk: true },
2543
+ "collection-types.bulkUnpublish": { action: "unpublish", kind: "collection", bulk: true },
2544
+ "single-types.find": { action: "view", kind: "single" },
2545
+ "single-types.createOrUpdate": { action: "update", kind: "single" },
2546
+ "single-types.delete": { action: "delete", kind: "single" },
2547
+ "single-types.publish": { action: "publish", kind: "single" },
2548
+ "single-types.unpublish": { action: "unpublish", kind: "single" },
2549
+ "single-types.discard": { action: "discard", kind: "single" }
2550
+ });
2551
+ var UID_PATTERN = /^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/;
2552
+ var LOCALE_PATTERN = /^[A-Za-z0-9-]{1,20}$/;
2553
+ var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
2554
+ var MAX_META_BYTES = 2048;
2555
+ var MAX_META_KEYS = 16;
2556
+ function boundMeta(meta) {
2557
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
2558
+ const out = {};
2559
+ let keys = 0;
2560
+ for (const [key, value] of Object.entries(meta)) {
2561
+ if (keys >= MAX_META_KEYS) break;
2562
+ if (!/^[a-zA-Z][a-zA-Z0-9]{0,39}$/.test(key)) continue;
2563
+ if (value === null || typeof value === "boolean") out[key] = value;
2564
+ else if (typeof value === "number" && Number.isFinite(value)) out[key] = value;
2565
+ else if (typeof value === "string") out[key] = value.slice(0, 255);
2566
+ else continue;
2567
+ keys += 1;
2568
+ }
2569
+ if (!keys) return null;
2570
+ while (JSON.stringify(out).length > MAX_META_BYTES) {
2571
+ const longest = Object.keys(out).reduce(
2572
+ (a, b) => String(out[a] ?? "").length >= String(out[b] ?? "").length ? a : b
2573
+ );
2574
+ delete out[longest];
2575
+ }
2576
+ return Object.keys(out).length ? out : null;
2577
+ }
2578
+ function handlerName(handler) {
2579
+ if (typeof handler !== "string") return null;
2580
+ const parts = handler.split(".");
2581
+ if (parts.length < 2) return null;
2582
+ const tail = parts.slice(-2).join(".");
2583
+ return tail.includes("::") ? tail.split("::").pop() || null : tail;
2584
+ }
2585
+ function shaped(value, pattern) {
2586
+ return typeof value === "string" && pattern.test(value) ? value : null;
2587
+ }
2588
+ function describeContentManagerRequest({
2589
+ status,
2590
+ route,
2591
+ params,
2592
+ query,
2593
+ requestBody,
2594
+ responseBody
2595
+ }) {
2596
+ if (!(status >= 200 && status < 300)) return null;
2597
+ if (route?.info?.pluginName !== "content-manager") return null;
2598
+ const name = handlerName(route.handler);
2599
+ const mapping = name ? (
2600
+ /** @type {any} */
2601
+ CONTENT_MANAGER_HANDLERS[name]
2602
+ ) : null;
2603
+ if (!mapping) return null;
2604
+ const contentType = shaped(params?.model, UID_PATTERN);
2605
+ if (!contentType) return null;
2606
+ const data = responseBody && typeof responseBody === "object" && !Array.isArray(responseBody) ? responseBody.data : null;
2607
+ const single = data && typeof data === "object" && !Array.isArray(data) ? data : null;
2608
+ let count = null;
2609
+ if (mapping.bulk) {
2610
+ const ids = requestBody?.documentIds;
2611
+ count = Array.isArray(ids) ? Math.min(ids.length, 1e5) : null;
2612
+ if (typeof responseBody?.data?.count === "number") count = responseBody.data.count;
2613
+ }
2614
+ const documentId = mapping.bulk ? null : shaped(params?.id, DOCUMENT_ID_PATTERN) || shaped(single?.documentId, DOCUMENT_ID_PATTERN);
2615
+ const locale = shaped(query?.locale, LOCALE_PATTERN) || shaped(single?.locale, LOCALE_PATTERN);
2616
+ return {
2617
+ action: mapping.action,
2618
+ kind: mapping.kind,
2619
+ contentType,
2620
+ documentId,
2621
+ locale,
2622
+ count,
2623
+ data: mapping.bulk ? null : single
2624
+ };
2625
+ }
2626
+ function pickEntryTitle(data, mainField) {
2627
+ if (!data || typeof data !== "object" || !mainField || mainField === "id") return null;
2628
+ const value = data[mainField];
2629
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
2630
+ if (typeof value !== "string") return null;
2631
+ const text = value.replace(/\s+/g, " ").trim();
2632
+ return text ? text.slice(0, 255) : null;
2633
+ }
2634
+ function safeReason(reason) {
2635
+ return typeof reason === "string" && /^[a-z][a-z0-9_-]{0,39}$/.test(reason) ? reason : null;
2636
+ }
2637
+ function deriveSessionStates(signIns, laterEvents, liveDevices) {
2638
+ const sorted = [...laterEvents].sort((a, b) => String(a.at).localeCompare(String(b.at)));
2639
+ const out = /* @__PURE__ */ new Map();
2640
+ for (const row of signIns) {
2641
+ if (!row.deviceHash) {
2642
+ out.set(row.id, { state: "unknown", endedAt: null, endedBy: null });
2643
+ continue;
2644
+ }
2645
+ let result = null;
2646
+ for (const event of sorted) {
2647
+ if (event.adminId !== row.adminId || String(event.at) <= String(row.at)) continue;
2648
+ const sameDevice = event.deviceHash === row.deviceHash;
2649
+ if (event.event === SECURITY_EVENTS.ADMIN_SIGN_IN && sameDevice) {
2650
+ result = { state: "ended", endedAt: null, endedBy: null };
2651
+ break;
2652
+ }
2653
+ const isEnd = event.event === SECURITY_EVENTS.ADMIN_SIGN_OUT || event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
2654
+ if (isEnd && (sameDevice || !event.deviceHash)) {
2655
+ result = {
2656
+ state: "signed-out",
2657
+ endedAt: event.at,
2658
+ endedBy: event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED ? event.actorId : null
2659
+ };
2660
+ break;
2661
+ }
2662
+ }
2663
+ if (!result) {
2664
+ const live = liveDevices.get(row.adminId);
2665
+ result = live && live.has(row.deviceHash) ? { state: "active", endedAt: null, endedBy: null } : { state: "ended", endedAt: null, endedBy: null };
2666
+ }
2667
+ out.set(row.id, result);
2668
+ }
2669
+ return out;
2670
+ }
2671
+ function toLocation(value) {
2672
+ let geo = value;
2673
+ if (typeof geo === "string") {
2674
+ try {
2675
+ geo = JSON.parse(geo);
2676
+ } catch {
2677
+ return null;
2678
+ }
2679
+ }
2680
+ if (!geo || typeof geo !== "object") return null;
2681
+ const text = (v) => typeof v === "string" && v.trim() ? v.trim().slice(0, 80) : null;
2682
+ const record = (
2683
+ /** @type {Record<string, unknown>} */
2684
+ geo
2685
+ );
2686
+ const location = {
2687
+ country: text(record.country),
2688
+ countryCode: text(record.countryCode ?? record.country_code),
2689
+ city: text(record.city)
2690
+ };
2691
+ return location.country || location.city ? location : null;
2692
+ }
2693
+ function toIso(value) {
2694
+ if (!value) return null;
2695
+ const date = value instanceof Date ? value : new Date(String(value));
2696
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
2697
+ }
2698
+ function toObject(value) {
2699
+ let parsed = value;
2700
+ if (typeof parsed === "string") {
2701
+ try {
2702
+ parsed = JSON.parse(parsed);
2703
+ } catch {
2704
+ return {};
2705
+ }
2706
+ }
2707
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2708
+ }
2709
+ module.exports = {
2710
+ ACTOR_TYPES,
2711
+ ADMIN_CONTENT_EVENTS,
2712
+ ADMIN_SIGN_IN_EVENTS,
2713
+ CONTENT_ACTIONS,
2714
+ CONTENT_MANAGER_HANDLERS,
2715
+ EVENT_NAME_PATTERN,
2716
+ MAX_META_BYTES,
2717
+ SECURITY_EVENTS,
2718
+ SIGN_IN_FILTERS,
2719
+ boundMeta,
2720
+ contentEvent,
2721
+ deriveSessionStates,
2722
+ describeContentManagerRequest,
2723
+ handlerName,
2724
+ pickEntryTitle,
2725
+ recordingSwitchOf,
2726
+ safeReason,
2727
+ toIso,
2728
+ toLocation,
2729
+ toObject
2730
+ };
2731
+ }
2732
+ });
2733
+
2734
+ // server/src/utils/user-agent-parser.js
2735
+ var require_user_agent_parser = __commonJS({
2736
+ "server/src/utils/user-agent-parser.js"(exports, module) {
2737
+ "use strict";
2738
+ function parseUserAgent(userAgent) {
2739
+ if (!userAgent) {
2740
+ return {
2741
+ deviceType: "unknown",
2742
+ browserName: "unknown",
2743
+ browserVersion: null,
2744
+ osName: "unknown",
2745
+ osVersion: null
2746
+ };
2747
+ }
2748
+ let deviceType = "desktop";
2749
+ if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
2750
+ deviceType = "tablet";
2751
+ } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
2752
+ deviceType = "mobile";
2753
+ } else if (/android(?!.*mobile)/i.test(userAgent)) {
2754
+ deviceType = "tablet";
2755
+ } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
2756
+ deviceType = "bot";
2757
+ }
2758
+ let browserName = "unknown";
2759
+ let browserVersion = null;
2760
+ if (/edg\//i.test(userAgent)) {
2761
+ browserName = "Edge";
2762
+ browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
2763
+ } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
2764
+ browserName = "Opera";
2765
+ browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
2766
+ } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
2767
+ browserName = "Chrome";
2768
+ browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
2769
+ } else if (/firefox|fxios/i.test(userAgent)) {
2770
+ browserName = "Firefox";
2771
+ browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
2772
+ } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
2773
+ browserName = "Safari";
2774
+ browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
2775
+ } else if (/msie|trident/i.test(userAgent)) {
2776
+ browserName = "Internet Explorer";
2777
+ browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
2778
+ }
2779
+ let osName = "unknown";
2780
+ let osVersion = null;
2781
+ if (/windows nt/i.test(userAgent)) {
2782
+ osName = "Windows";
2783
+ const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
2784
+ const winVersionMap = {
2785
+ "10.0": "10/11",
2786
+ 6.3: "8.1",
2787
+ 6.2: "8",
2788
+ 6.1: "7",
2789
+ "6.0": "Vista",
2790
+ 5.1: "XP"
2791
+ };
2792
+ osVersion = winVersionMap[winVersion] || winVersion;
2793
+ } else if (/iphone|ipad|ipod/i.test(userAgent)) {
2794
+ osName = "iOS";
2795
+ osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
2796
+ } else if (/mac os x/i.test(userAgent)) {
2797
+ osName = "macOS";
2798
+ osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
2799
+ } else if (/android/i.test(userAgent)) {
2800
+ osName = "Android";
2801
+ osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
2802
+ } else if (/linux/i.test(userAgent)) {
2803
+ osName = "Linux";
2804
+ } else if (/cros/i.test(userAgent)) {
2805
+ osName = "Chrome OS";
2806
+ }
2807
+ return {
2808
+ deviceType,
2809
+ browserName,
2810
+ browserVersion,
2811
+ osName,
2812
+ osVersion
2813
+ };
2814
+ }
2815
+ function extractVersion(userAgent, regex) {
2816
+ const match = userAgent.match(regex);
2817
+ return match ? match[1] : null;
2818
+ }
2819
+ function getDeviceDescription(parsed) {
2820
+ const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
2821
+ const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
2822
+ return `${browser} on ${os}`;
2823
+ }
2824
+ module.exports = {
2825
+ parseUserAgent,
2826
+ getDeviceDescription
2827
+ };
2828
+ }
2829
+ });
2830
+
2831
+ // server/src/utils/admin-request-info.js
2832
+ var require_admin_request_info = __commonJS({
2833
+ "server/src/utils/admin-request-info.js"(exports, module) {
2834
+ "use strict";
2835
+ var crypto = __require("node:crypto");
2836
+ var net = __require("node:net");
2837
+ var { parseUserAgent } = require_user_agent_parser();
2838
+ var MAX_USER_AGENT_LENGTH = 500;
2839
+ var MAX_DEVICE_ID_LENGTH = 200;
2840
+ function normalizeIp(value) {
2841
+ if (typeof value !== "string") return null;
2842
+ let ip = value.trim();
2843
+ if (!ip || ip.length > 100) return null;
2844
+ if (ip.startsWith("[")) {
2845
+ const end = ip.indexOf("]");
2846
+ ip = end === -1 ? ip.slice(1) : ip.slice(1, end);
2847
+ }
2848
+ if (/^::ffff:/i.test(ip) && net.isIPv4(ip.slice(7))) ip = ip.slice(7);
2849
+ if (ip.includes(".") && ip.split(":").length === 2) ip = ip.split(":")[0];
2850
+ const zone = ip.indexOf("%");
2851
+ if (zone !== -1) ip = ip.slice(0, zone);
2852
+ return net.isIP(ip) === 0 ? null : ip.toLowerCase();
2853
+ }
2854
+ function getRequestIp(ctx) {
2855
+ try {
2856
+ return normalizeIp(ctx?.request?.ip);
2857
+ } catch {
2858
+ return null;
2859
+ }
2860
+ }
2861
+ function ipv6Groups(ip) {
2862
+ let address = ip;
2863
+ let tail = [];
2864
+ const lastColon = address.lastIndexOf(":");
2865
+ const suffix = address.slice(lastColon + 1);
2866
+ if (net.isIPv4(suffix)) {
2867
+ const [a, b, c, d] = suffix.split(".").map(Number);
2868
+ tail = [a << 8 | b, c << 8 | d];
2869
+ address = `${address.slice(0, lastColon + 1)}0`;
2870
+ }
2871
+ const [head, rest] = address.includes("::") ? address.split("::") : [address, null];
2872
+ const left = head ? head.split(":") : [];
2873
+ const right = rest ? rest.split(":") : [];
2874
+ const fill = rest === null ? 0 : 8 - left.length - right.length;
2875
+ const groups = [...left, ...Array(Math.max(0, fill)).fill("0"), ...right].map(
2876
+ (g) => Number.parseInt(g || "0", 16)
2877
+ );
2878
+ if (tail.length) groups.splice(6, 2, ...tail);
2879
+ return groups.slice(0, 8);
2880
+ }
2881
+ function anonymizeIp(ip) {
2882
+ if (!ip) return null;
2883
+ if (net.isIPv4(ip)) {
2884
+ const parts = ip.split(".");
2885
+ return `${parts[0]}.${parts[1]}.${parts[2]}.0`;
2886
+ }
2887
+ if (net.isIPv6(ip)) {
2888
+ const groups = ipv6Groups(ip);
2889
+ return `${groups.slice(0, 3).map((group) => group.toString(16)).join(":")}::`;
2890
+ }
2891
+ return null;
2892
+ }
2893
+ function getRequestUserAgent(ctx) {
2894
+ const value = ctx?.request?.headers?.["user-agent"];
2895
+ if (typeof value !== "string" || !value.trim()) return null;
2896
+ return value.slice(0, MAX_USER_AGENT_LENGTH);
2897
+ }
2898
+ function describeUserAgent(userAgent) {
2899
+ if (!userAgent) return { browserName: null, osName: null, deviceType: null };
2900
+ const parsed = parseUserAgent(userAgent);
2901
+ const known = (value) => value && value !== "unknown" ? String(value) : null;
2902
+ const browser = known(parsed.browserName);
2903
+ const os = known(parsed.osName);
2904
+ return {
2905
+ browserName: browser ? (parsed.browserVersion ? `${browser} ${parsed.browserVersion}` : browser).slice(0, 60) : null,
2906
+ osName: os ? (parsed.osVersion ? `${os} ${parsed.osVersion}` : os).slice(0, 60) : null,
2907
+ deviceType: known(parsed.deviceType)?.slice(0, 20) || null
2908
+ };
2909
+ }
2910
+ function hashDeviceId(deviceId) {
2911
+ if (typeof deviceId !== "string" || !deviceId || deviceId.length > MAX_DEVICE_ID_LENGTH) {
2912
+ return null;
2913
+ }
2914
+ return crypto.createHash("sha256").update(deviceId).digest("hex");
2915
+ }
2916
+ module.exports = {
2917
+ anonymizeIp,
2918
+ describeUserAgent,
2919
+ getRequestIp,
2920
+ getRequestUserAgent,
2921
+ hashDeviceId,
2922
+ normalizeIp
2923
+ };
2924
+ }
2925
+ });
2926
+
2927
+ // server/src/utils/security-log-settings.js
2928
+ var require_security_log_settings = __commonJS({
2929
+ "server/src/utils/security-log-settings.js"(exports, module) {
2930
+ "use strict";
2931
+ var SECURITY_LOG_DEFAULTS = Object.freeze({
2932
+ adminSignInHistory: true,
2933
+ adminContentActivity: false,
2934
+ securityLogStoreIp: true,
2935
+ securityLogAnonymizeIp: false,
2936
+ securityLogRetentionDays: 90
2937
+ });
2938
+ var SECURITY_LOG_BOOLEAN_KEYS = Object.freeze([
2939
+ "adminSignInHistory",
2940
+ "adminContentActivity",
2941
+ "securityLogStoreIp",
2942
+ "securityLogAnonymizeIp"
2943
+ ]);
2944
+ var SECURITY_LOG_RETENTION_RANGE = Object.freeze({ min: 1, max: 730 });
2945
+ var SECURITY_LOG_KEYS = Object.freeze(Object.keys(SECURITY_LOG_DEFAULTS));
2946
+ function resolveSecurityLogSettings(settings) {
2947
+ const source = settings && typeof settings === "object" ? settings : {};
2948
+ const flag = (key) => typeof source[key] === "boolean" ? (
2949
+ /** @type {boolean} */
2950
+ source[key]
2951
+ ) : (
2952
+ /** @type {any} */
2953
+ SECURITY_LOG_DEFAULTS[key]
2954
+ );
2955
+ const days = Number(source.securityLogRetentionDays);
2956
+ const { min, max } = SECURITY_LOG_RETENTION_RANGE;
2957
+ return {
2958
+ signIns: flag("adminSignInHistory"),
2959
+ content: flag("adminContentActivity"),
2960
+ storeIp: flag("securityLogStoreIp"),
2961
+ anonymizeIp: flag("securityLogAnonymizeIp"),
2962
+ retentionDays: Number.isInteger(days) && days >= min && days <= max ? days : SECURITY_LOG_DEFAULTS.securityLogRetentionDays
2963
+ };
2964
+ }
2965
+ function validateSecurityLogSettings(body) {
2966
+ const values = {};
2967
+ const errors = [];
2968
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
2969
+ for (const key of SECURITY_LOG_BOOLEAN_KEYS) {
2970
+ if (!has(key)) continue;
2971
+ if (typeof body[key] !== "boolean") {
2972
+ errors.push({ path: [key], message: `${key} must be a boolean` });
2973
+ } else {
2974
+ values[key] = /** @type {boolean} */
2975
+ body[key];
2976
+ }
2977
+ }
2978
+ if (has("securityLogRetentionDays")) {
2979
+ const raw = body.securityLogRetentionDays;
2980
+ const value = typeof raw === "number" ? raw : typeof raw === "string" && /^\s*\d+\s*$/.test(raw) ? Number.parseInt(raw, 10) : NaN;
2981
+ const { min, max } = SECURITY_LOG_RETENTION_RANGE;
2982
+ if (!Number.isInteger(value) || value < min || value > max) {
2983
+ errors.push({
2984
+ path: ["securityLogRetentionDays"],
2985
+ message: `securityLogRetentionDays must be an integer between ${min} and ${max}`
2986
+ });
2987
+ } else {
2988
+ values.securityLogRetentionDays = value;
2989
+ }
2990
+ }
2991
+ return { values, errors };
2992
+ }
2993
+ module.exports = {
2994
+ SECURITY_LOG_BOOLEAN_KEYS,
2995
+ SECURITY_LOG_DEFAULTS,
2996
+ SECURITY_LOG_KEYS,
2997
+ SECURITY_LOG_RETENTION_RANGE,
2998
+ resolveSecurityLogSettings,
2999
+ validateSecurityLogSettings
3000
+ };
3001
+ }
3002
+ });
3003
+
3004
+ // server/src/utils/admin-activity-capture.js
3005
+ var require_admin_activity_capture = __commonJS({
3006
+ "server/src/utils/admin-activity-capture.js"(exports, module) {
3007
+ "use strict";
3008
+ var {
3009
+ SECURITY_EVENTS,
3010
+ describeContentManagerRequest,
3011
+ handlerName,
3012
+ safeReason
3013
+ } = require_security_log_model();
3014
+ var { getRequestIp, getRequestUserAgent } = require_admin_request_info();
3015
+ var { resolveSecurityLogSettings } = require_security_log_settings();
3016
+ var { getPluginSettings, peekCachedSettings } = require_settings_loader();
3017
+ var SERVICE = "security-log";
3018
+ var AUTH_HANDLERS = Object.freeze({
3019
+ login: "authentication.login",
3020
+ registerAdmin: "authentication.registerAdmin",
3021
+ register: "authentication.register",
3022
+ resetPassword: "authentication.resetPassword"
3023
+ });
3024
+ var SESSION_CREATING = Object.freeze({
3025
+ [AUTH_HANDLERS.registerAdmin]: "registration",
3026
+ [AUTH_HANDLERS.register]: "registration",
3027
+ [AUTH_HANDLERS.resetPassword]: "password_reset"
3028
+ });
3029
+ function peekSwitches(strapi2) {
3030
+ const cached = peekCachedSettings();
3031
+ if (!cached) {
3032
+ getPluginSettings(strapi2).catch(() => {
3033
+ });
3034
+ return null;
3035
+ }
3036
+ return resolveSecurityLogSettings(cached);
3037
+ }
3038
+ function bodyDeviceId(ctx) {
3039
+ const value = ctx?.request?.body?.deviceId;
3040
+ return typeof value === "string" && value.length > 0 && value.length <= 200 ? value : null;
3041
+ }
3042
+ function currentRequestFacts(strapi2) {
3043
+ const ctx = currentContext(strapi2);
3044
+ return {
3045
+ ip: ctx ? getRequestIp(ctx) : null,
3046
+ userAgent: ctx ? getRequestUserAgent(ctx) : null,
3047
+ deviceId: ctx ? bodyDeviceId(ctx) : null
3048
+ };
3049
+ }
3050
+ function currentContext(strapi2) {
3051
+ try {
3052
+ return strapi2.requestContext?.get?.() || null;
3053
+ } catch {
3054
+ return null;
3055
+ }
3056
+ }
3057
+ function attemptedEmailOf(ctx) {
3058
+ const email = ctx?.request?.body?.email;
3059
+ return typeof email === "string" && email.length <= 254 ? email : null;
3060
+ }
3061
+ function createCaptureMiddleware(strapi2, getService) {
3062
+ return async function adminActivityCapture(ctx, next) {
3063
+ let thrown = null;
3064
+ let result;
3065
+ try {
3066
+ result = await next();
3067
+ } catch (error) {
3068
+ thrown = error;
3069
+ }
3070
+ try {
3071
+ const route = ctx.state?.route;
3072
+ const plugin = route?.info?.pluginName;
3073
+ if (plugin === "content-manager") {
3074
+ if (!thrown) observeContentManager(strapi2, getService, ctx, route);
3075
+ } else if (plugin === "admin") {
3076
+ observeAuthentication(strapi2, getService, ctx, route, thrown);
3077
+ }
3078
+ } catch {
3079
+ }
3080
+ if (thrown) throw thrown;
3081
+ return result;
3082
+ };
3083
+ }
3084
+ function observeContentManager(strapi2, getService, ctx, route) {
3085
+ const adminId = ctx.state?.user?.id;
3086
+ const strategy = ctx.state?.auth?.strategy?.name;
3087
+ if (adminId === void 0 || strategy !== "admin" && strategy !== "admin-token") return;
3088
+ const switches = peekSwitches(strapi2);
3089
+ if (switches && !switches.content) return;
3090
+ const entry = describeContentManagerRequest({
3091
+ status: ctx.status,
3092
+ route,
3093
+ params: ctx.params,
3094
+ query: ctx.query,
3095
+ requestBody: ctx.request?.body,
3096
+ responseBody: ctx.body
3097
+ });
3098
+ if (!entry) return;
3099
+ getService()?.recordContentAction({ ...entry, adminUserId: adminId });
3100
+ }
3101
+ function observeAuthentication(strapi2, getService, ctx, route, thrown) {
3102
+ const name = handlerName(route?.handler);
3103
+ if (!name || !(name === AUTH_HANDLERS.login || name in SESSION_CREATING)) return;
3104
+ const switches = peekSwitches(strapi2);
3105
+ if (switches && !switches.signIns) return;
3106
+ const error = (
3107
+ /** @type {any} */
3108
+ thrown
3109
+ );
3110
+ const status = error ? error.name === "RateLimitError" ? 429 : Number(error.status) || 500 : Number(ctx.status);
3111
+ const facts = {
3112
+ ip: getRequestIp(ctx),
3113
+ userAgent: getRequestUserAgent(ctx),
3114
+ deviceId: bodyDeviceId(ctx)
3115
+ };
3116
+ if (name === AUTH_HANDLERS.login) {
3117
+ if (status !== 429) return;
3118
+ getService()?.record({
3119
+ event: SECURITY_EVENTS.ADMIN_LOCKOUT,
3120
+ actorType: "admin",
3121
+ targetType: "admin",
3122
+ // Resolved to an existing admin in the background, then dropped.
3123
+ attemptedEmail: attemptedEmailOf(ctx),
3124
+ meta: { reason: "rate_limited", provider: "local" },
3125
+ ...facts
3126
+ });
3127
+ return;
3128
+ }
3129
+ if (status < 200 || status >= 300) return;
3130
+ const userId = ctx.body?.data?.user?.id;
3131
+ if (userId === void 0) return;
3132
+ getService()?.record({
3133
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN,
3134
+ actorType: "admin",
3135
+ actorId: userId,
3136
+ targetType: "admin",
3137
+ targetId: userId,
3138
+ meta: { reason: (
3139
+ /** @type {any} */
3140
+ SESSION_CREATING[name]
3141
+ ), provider: "local" },
3142
+ ...facts,
3143
+ // A password reset gives the browser a new device id server-side.
3144
+ deviceId: name === AUTH_HANDLERS.resetPassword ? null : facts.deviceId
3145
+ });
3146
+ }
3147
+ function installAdminActivityCapture(strapi2, { log, runExclusive }) {
3148
+ const getService = () => {
3149
+ const service = strapi2.plugin("magic-sessionmanager")?.service(SERVICE);
3150
+ return service && !service.isStopped() ? service : null;
3151
+ };
3152
+ const cleanups = [];
3153
+ const on = (event, listener) => {
3154
+ const off = strapi2.eventHub?.on?.(event, (payload) => {
3155
+ try {
3156
+ listener(payload);
3157
+ } catch {
3158
+ }
3159
+ });
3160
+ if (typeof off === "function") cleanups.push(off);
3161
+ };
3162
+ on("admin.auth.success", (payload) => {
3163
+ const switches = peekSwitches(strapi2);
3164
+ if (switches && !switches.signIns) return;
3165
+ const id = payload?.user?.id;
3166
+ getService()?.record({
3167
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN,
3168
+ actorType: "admin",
3169
+ actorId: id,
3170
+ targetType: "admin",
3171
+ targetId: id,
3172
+ meta: { provider: safeReason(payload?.provider) || "local" },
3173
+ ...currentRequestFacts(strapi2)
3174
+ });
3175
+ });
3176
+ on("admin.auth.error", (payload) => {
3177
+ const switches = peekSwitches(strapi2);
3178
+ if (switches && !switches.signIns) return;
3179
+ const id = payload?.user?.id ?? null;
3180
+ getService()?.record({
3181
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
3182
+ actorType: "admin",
3183
+ actorId: id,
3184
+ targetType: "admin",
3185
+ targetId: id,
3186
+ ...id === null ? { attemptedEmail: attemptedEmailOf(currentContext(strapi2)), actorFromEmail: true } : {},
3187
+ meta: {
3188
+ reason: safeReason(payload?.reason) || "invalid_credentials",
3189
+ provider: safeReason(payload?.provider) || "local"
3190
+ },
3191
+ ...currentRequestFacts(strapi2)
3192
+ });
3193
+ });
3194
+ on("admin.logout", (payload) => {
3195
+ const switches = peekSwitches(strapi2);
3196
+ if (switches && !switches.signIns) return;
3197
+ const id = payload?.user?.id;
3198
+ getService()?.record({
3199
+ event: SECURITY_EVENTS.ADMIN_SIGN_OUT,
3200
+ actorType: "admin",
3201
+ actorId: id,
3202
+ targetType: "admin",
3203
+ targetId: id,
3204
+ ...currentRequestFacts(strapi2)
3205
+ });
3206
+ });
3207
+ strapi2.server.use(createCaptureMiddleware(strapi2, getService));
3208
+ try {
3209
+ const unsubscribe = strapi2.db.lifecycles.subscribe({
3210
+ models: ["admin::user"],
3211
+ async afterDelete(event) {
3212
+ const id = event?.result?.id;
3213
+ if (id === void 0) return;
3214
+ try {
3215
+ await strapi2.plugin("magic-sessionmanager").service(SERVICE).deleteAdminData(id);
3216
+ } catch (err) {
3217
+ log.warn(
3218
+ "[security-log] Data of a deleted admin could not be removed:",
3219
+ err?.name || "Error"
3220
+ );
3221
+ }
3222
+ }
3223
+ });
3224
+ if (typeof unsubscribe === "function") cleanups.push(unsubscribe);
3225
+ } catch (err) {
3226
+ log.warn("[security-log] Could not watch admin deletions:", err?.name || "Error");
3227
+ }
3228
+ const jobName = "magic-sessionmanager-security-log-retention";
3229
+ const retention = async () => {
3230
+ const job = async () => {
3231
+ const service = strapi2.plugin("magic-sessionmanager").service(SERVICE);
3232
+ const removed = await service.cleanup();
3233
+ if (removed.expired || removed.orphans) {
3234
+ log.info(
3235
+ `[security-log] Retention removed ${removed.expired} expired events and ${removed.orphans} of deleted admins`
3236
+ );
3237
+ }
3238
+ };
3239
+ try {
3240
+ if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
3241
+ else await job();
3242
+ } catch (err) {
3243
+ log.warn("[security-log] Retention failed:", err?.name || "Error");
3244
+ }
3245
+ };
3246
+ try {
3247
+ strapi2.cron.add({ [jobName]: { task: retention, options: { rule: "17 3 * * *" } } });
3248
+ cleanups.push(() => strapi2.cron.remove(jobName));
3249
+ } catch (err) {
3250
+ log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
3251
+ }
3252
+ return async () => {
3253
+ for (const cleanup of cleanups.splice(0)) {
3254
+ try {
3255
+ cleanup();
3256
+ } catch {
3257
+ }
3258
+ }
3259
+ try {
3260
+ await strapi2.plugin("magic-sessionmanager")?.service(SERVICE)?.stop();
3261
+ } catch {
3262
+ }
3263
+ };
3264
+ }
3265
+ module.exports = {
3266
+ createCaptureMiddleware,
3267
+ installAdminActivityCapture,
3268
+ observeAuthentication,
3269
+ observeContentManager
3270
+ };
3271
+ }
3272
+ });
3273
+
2299
3274
  // server/src/middlewares/session-rejection-headers.js
2300
3275
  var require_session_rejection_headers = __commonJS({
2301
3276
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -6386,6 +7361,7 @@ var require_bootstrap = __commonJS({
6386
7361
  var { extractBearerToken } = require_extract_token();
6387
7362
  var { setSessionRejectionReason } = require_rejection_cache();
6388
7363
  var { evaluateGeoFirewall } = require_geo_firewall();
7364
+ var { dispatchLoginAlerts } = require_login_alerts();
6389
7365
  var { REVOCATION_UID } = require_session_revocation();
6390
7366
  var { getNativeSessionManager } = require_native_session_manager();
6391
7367
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
@@ -6418,6 +7394,7 @@ var require_bootstrap = __commonJS({
6418
7394
  isThenable
6419
7395
  } = require_native_session_capture();
6420
7396
  var { ensureNativeTrackingSince } = require_native_only_insight();
7397
+ var { installAdminActivityCapture } = require_admin_activity_capture();
6421
7398
  var SESSION_UID = "plugin::magic-sessionmanager.session";
6422
7399
  var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
6423
7400
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -6572,6 +7549,13 @@ var require_bootstrap = __commonJS({
6572
7549
  log.info("[SUCCESS] Session-rejection-headers middleware mounted");
6573
7550
  strapi2.server.use(require_last_seen()({ strapi: strapi2, sessionService }));
6574
7551
  log.info("[SUCCESS] LastSeen middleware mounted");
7552
+ strapi2.sessionManagerAdminActivityUninstall = installAdminActivityCapture(strapi2, {
7553
+ log,
7554
+ runExclusive: async (name, leaseMs, job) => {
7555
+ if (await coordinator.tryAcquireLease(name, leaseMs)) await job();
7556
+ }
7557
+ });
7558
+ log.info("[SUCCESS] Admin activity capture mounted");
6575
7559
  const contentApiPermissionsReady = await ensureContentApiPermissions(strapi2, log);
6576
7560
  mountDeferredContentApiPermissionRetry({
6577
7561
  strapi: strapi2,
@@ -7128,9 +8112,6 @@ var require_bootstrap = __commonJS({
7128
8112
  return;
7129
8113
  }
7130
8114
  const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
7131
- const scoreEvaluationEnabled = settings.enableSecurityScoring !== false;
7132
- const lowScore = scoreEvaluationEnabled && typeof geoData.securityScore === "number" && geoData.securityScore < 70;
7133
- const isSuspicious = geoData.isVpn || geoData.isProxy || geoData.isThreat || lowScore;
7134
8115
  let isNewLocation = false;
7135
8116
  if (settings.alertOnNewLocation && (geoData.country_code || geoData.country)) {
7136
8117
  try {
@@ -7173,74 +8154,14 @@ var require_bootstrap = __commonJS({
7173
8154
  log.debug("New-location check failed (non-fatal):", locErr?.name || "Error");
7174
8155
  }
7175
8156
  }
7176
- if (settings.enableEmailAlerts) {
7177
- if (settings.alertOnVpnProxy && (geoData.isVpn || geoData.isProxy)) {
7178
- await notificationService.sendVpnProxyAlert({
7179
- user,
7180
- session: newSession,
7181
- reason: {
7182
- isVpn: geoData.isVpn,
7183
- isProxy: geoData.isProxy
7184
- },
7185
- geoData
7186
- });
7187
- }
7188
- if (settings.alertOnSuspiciousLogin && isSuspicious) {
7189
- await notificationService.sendSuspiciousLoginAlert({
7190
- user,
7191
- session: newSession,
7192
- reason: {
7193
- isVpn: geoData.isVpn,
7194
- isProxy: geoData.isProxy,
7195
- isThreat: geoData.isThreat,
7196
- securityScore: geoData.securityScore
7197
- },
7198
- geoData
7199
- });
7200
- }
7201
- if (settings.alertOnNewLocation && isNewLocation) {
7202
- await notificationService.sendNewLocationAlert({
7203
- user,
7204
- session: newSession,
7205
- geoData
7206
- });
7207
- }
7208
- }
7209
- if (settings.enableWebhooks) {
7210
- const webhookEvent = isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
7211
- const targets = [];
7212
- if (settings.discordWebhookUrl) {
7213
- targets.push({
7214
- url: settings.discordWebhookUrl,
7215
- payload: notificationService.formatDiscordWebhook({
7216
- event: webhookEvent,
7217
- session: newSession,
7218
- user,
7219
- geoData
7220
- })
7221
- });
7222
- }
7223
- if (settings.slackWebhookUrl) {
7224
- targets.push({
7225
- url: settings.slackWebhookUrl,
7226
- payload: notificationService.formatSlackWebhook({
7227
- event: webhookEvent,
7228
- session: newSession,
7229
- user,
7230
- geoData
7231
- })
7232
- });
7233
- }
7234
- await Promise.allSettled(
7235
- targets.map(
7236
- (t) => notificationService.sendWebhook({
7237
- event: webhookEvent,
7238
- data: t.payload,
7239
- webhookUrl: t.url
7240
- })
7241
- )
7242
- );
7243
- }
8157
+ await dispatchLoginAlerts({
8158
+ settings,
8159
+ notificationService,
8160
+ user,
8161
+ session: newSession,
8162
+ geoData,
8163
+ isNewLocation
8164
+ });
7244
8165
  } catch (notifErr) {
7245
8166
  log.warn("Notification failed:", notifErr?.name || "Error");
7246
8167
  }
@@ -8087,6 +9008,14 @@ var require_destroy = __commonJS({
8087
9008
  }
8088
9009
  strapi2.sessionManagerUnsubscribers = [];
8089
9010
  }
9011
+ if (typeof strapi2.sessionManagerAdminActivityUninstall === "function") {
9012
+ try {
9013
+ await strapi2.sessionManagerAdminActivityUninstall();
9014
+ } catch (err) {
9015
+ log.warn("Failed to stop the admin activity capture:", err?.name || "Error");
9016
+ }
9017
+ strapi2.sessionManagerAdminActivityUninstall = null;
9018
+ }
8090
9019
  log.info("[SUCCESS] Plugin cleanup completed");
8091
9020
  };
8092
9021
  }
@@ -8348,18 +9277,110 @@ var require_schema2 = __commonJS({
8348
9277
  }
8349
9278
  });
8350
9279
 
9280
+ // server/src/content-types/security-event/schema.json
9281
+ var require_schema3 = __commonJS({
9282
+ "server/src/content-types/security-event/schema.json"(exports, module) {
9283
+ module.exports = {
9284
+ kind: "collectionType",
9285
+ collectionName: "magic_sessions_security_events",
9286
+ info: {
9287
+ singularName: "security-event",
9288
+ pluralName: "security-events",
9289
+ displayName: "Security event",
9290
+ description: "Security event log: admin sign-ins, failed attempts, lockouts, sign-outs, who signed out whom, and Content Manager activity of admins"
9291
+ },
9292
+ options: {
9293
+ draftAndPublish: false,
9294
+ comment: ""
9295
+ },
9296
+ pluginOptions: {
9297
+ "content-manager": {
9298
+ visible: false
9299
+ },
9300
+ "content-type-builder": {
9301
+ visible: false
9302
+ }
9303
+ },
9304
+ indexes: [
9305
+ {
9306
+ name: "msm_security_events_actor",
9307
+ columns: ["actor_type", "actor_id", "created_at"]
9308
+ },
9309
+ {
9310
+ name: "msm_security_events_target",
9311
+ columns: ["target_type", "target_id", "created_at"]
9312
+ },
9313
+ {
9314
+ name: "msm_security_events_event",
9315
+ columns: ["event", "created_at"]
9316
+ },
9317
+ {
9318
+ name: "msm_security_events_created",
9319
+ columns: ["created_at"]
9320
+ }
9321
+ ],
9322
+ attributes: {
9323
+ event: {
9324
+ type: "string",
9325
+ maxLength: 64,
9326
+ required: true
9327
+ },
9328
+ actorType: {
9329
+ type: "enumeration",
9330
+ enum: ["admin", "user", "system"],
9331
+ required: true
9332
+ },
9333
+ actorId: {
9334
+ type: "string",
9335
+ maxLength: 64
9336
+ },
9337
+ targetType: {
9338
+ type: "string",
9339
+ maxLength: 40
9340
+ },
9341
+ targetId: {
9342
+ type: "string",
9343
+ maxLength: 255
9344
+ },
9345
+ ip: {
9346
+ type: "string",
9347
+ maxLength: 45
9348
+ },
9349
+ userAgent: {
9350
+ type: "text",
9351
+ maxLength: 500
9352
+ },
9353
+ geo: {
9354
+ type: "json"
9355
+ },
9356
+ meta: {
9357
+ type: "json"
9358
+ }
9359
+ }
9360
+ };
9361
+ }
9362
+ });
9363
+
8351
9364
  // server/src/content-types/index.js
8352
9365
  var require_content_types = __commonJS({
8353
9366
  "server/src/content-types/index.js"(exports, module) {
8354
9367
  "use strict";
8355
9368
  var session = require_schema();
8356
9369
  var revokedToken = require_schema2();
9370
+ var securityEvent = require_schema3();
8357
9371
  module.exports = {
8358
9372
  session: {
8359
9373
  schema: session
8360
9374
  },
8361
9375
  "revoked-token": {
8362
9376
  schema: revokedToken
9377
+ },
9378
+ // One security event log (4.15): admin sign-ins and sign-outs, failed
9379
+ // attempts, lockouts, who signed out whom, Content Manager activity, and
9380
+ // later app-user security events. Hidden from the Content Manager and the
9381
+ // Content-Type Builder.
9382
+ "security-event": {
9383
+ schema: securityEvent
8363
9384
  }
8364
9385
  };
8365
9386
  }
@@ -8469,6 +9490,7 @@ var require_admin = __commonJS({
8469
9490
  var PLUGIN_ACCESS_ACTION = "plugin::magic-sessionmanager.access";
8470
9491
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
8471
9492
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
9493
+ var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
8472
9494
  var adminPolicy = () => [
8473
9495
  "admin::isAuthenticatedAdmin",
8474
9496
  {
@@ -8646,39 +9668,80 @@ var require_admin = __commonJS({
8646
9668
  path: "/admin-sessions/admins",
8647
9669
  handler: "admin-sessions.listAdmins",
8648
9670
  config: {
8649
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9671
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9672
+ middlewares: adminReadRateLimit(),
9673
+ description: "List Strapi admins with their admin panel sessions (admin)"
9674
+ }
9675
+ },
9676
+ {
9677
+ method: "GET",
9678
+ path: "/admin-sessions/admins/:adminId/sessions",
9679
+ handler: "admin-sessions.listAdminSessions",
9680
+ config: {
9681
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9682
+ middlewares: adminReadRateLimit(),
9683
+ description: "List the admin panel sessions of one Strapi admin (admin)"
9684
+ }
9685
+ },
9686
+ {
9687
+ method: "POST",
9688
+ path: "/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out",
9689
+ handler: "admin-sessions.signOutSession",
9690
+ config: {
9691
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
9692
+ middlewares: adminSignOutRateLimit(),
9693
+ description: "Sign a Strapi admin out of one browser (admin)"
9694
+ }
9695
+ },
9696
+ {
9697
+ method: "POST",
9698
+ path: "/admin-sessions/admins/:adminId/sign-out-everywhere",
9699
+ handler: "admin-sessions.signOutEverywhere",
9700
+ config: {
9701
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
9702
+ middlewares: adminSignOutRateLimit(),
9703
+ description: "Sign a Strapi admin out of every browser (admin)"
9704
+ }
9705
+ },
9706
+ // ============== ADMIN SIGN-IN HISTORY AND CONTENT MANAGER ACTIVITY ==============
9707
+ {
9708
+ method: "GET",
9709
+ path: "/admin-activity/sign-ins",
9710
+ handler: "admin-activity.listSignIns",
9711
+ config: {
9712
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
8650
9713
  middlewares: adminReadRateLimit(),
8651
- description: "List Strapi admins with their admin panel sessions (admin)"
9714
+ description: "List the admin sign-in history (admin)"
8652
9715
  }
8653
9716
  },
8654
9717
  {
8655
9718
  method: "GET",
8656
- path: "/admin-sessions/admins/:adminId/sessions",
8657
- handler: "admin-sessions.listAdminSessions",
9719
+ path: "/admin-activity/sign-ins/export",
9720
+ handler: "admin-activity.exportSignIns",
8658
9721
  config: {
8659
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]),
9722
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
8660
9723
  middlewares: adminReadRateLimit(),
8661
- description: "List the admin panel sessions of one Strapi admin (admin)"
9724
+ description: "Get one export batch of the admin sign-in history (admin)"
8662
9725
  }
8663
9726
  },
8664
9727
  {
8665
- method: "POST",
8666
- path: "/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out",
8667
- handler: "admin-sessions.signOutSession",
9728
+ method: "GET",
9729
+ path: "/admin-activity/content",
9730
+ handler: "admin-activity.listContentActivity",
8668
9731
  config: {
8669
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
8670
- middlewares: adminSignOutRateLimit(),
8671
- description: "Sign a Strapi admin out of one browser (admin)"
9732
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9733
+ middlewares: adminReadRateLimit(),
9734
+ description: "List Content Manager activity of admins (admin)"
8672
9735
  }
8673
9736
  },
8674
9737
  {
8675
- method: "POST",
8676
- path: "/admin-sessions/admins/:adminId/sign-out-everywhere",
8677
- handler: "admin-sessions.signOutEverywhere",
9738
+ method: "GET",
9739
+ path: "/admin-activity/content/export",
9740
+ handler: "admin-activity.exportContentActivity",
8678
9741
  config: {
8679
- policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]),
8680
- middlewares: adminSignOutRateLimit(),
8681
- description: "Sign a Strapi admin out of every browser (admin)"
9742
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9743
+ middlewares: adminReadRateLimit(),
9744
+ description: "Get one export batch of Content Manager activity of admins (admin)"
8682
9745
  }
8683
9746
  },
8684
9747
  // ============================ GEOLOCATION ============================
@@ -8769,103 +9832,6 @@ var require_routes = __commonJS({
8769
9832
  }
8770
9833
  });
8771
9834
 
8772
- // server/src/utils/user-agent-parser.js
8773
- var require_user_agent_parser = __commonJS({
8774
- "server/src/utils/user-agent-parser.js"(exports, module) {
8775
- "use strict";
8776
- function parseUserAgent(userAgent) {
8777
- if (!userAgent) {
8778
- return {
8779
- deviceType: "unknown",
8780
- browserName: "unknown",
8781
- browserVersion: null,
8782
- osName: "unknown",
8783
- osVersion: null
8784
- };
8785
- }
8786
- let deviceType = "desktop";
8787
- if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
8788
- deviceType = "tablet";
8789
- } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
8790
- deviceType = "mobile";
8791
- } else if (/android(?!.*mobile)/i.test(userAgent)) {
8792
- deviceType = "tablet";
8793
- } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
8794
- deviceType = "bot";
8795
- }
8796
- let browserName = "unknown";
8797
- let browserVersion = null;
8798
- if (/edg\//i.test(userAgent)) {
8799
- browserName = "Edge";
8800
- browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
8801
- } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
8802
- browserName = "Opera";
8803
- browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
8804
- } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
8805
- browserName = "Chrome";
8806
- browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
8807
- } else if (/firefox|fxios/i.test(userAgent)) {
8808
- browserName = "Firefox";
8809
- browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
8810
- } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
8811
- browserName = "Safari";
8812
- browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
8813
- } else if (/msie|trident/i.test(userAgent)) {
8814
- browserName = "Internet Explorer";
8815
- browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
8816
- }
8817
- let osName = "unknown";
8818
- let osVersion = null;
8819
- if (/windows nt/i.test(userAgent)) {
8820
- osName = "Windows";
8821
- const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
8822
- const winVersionMap = {
8823
- "10.0": "10/11",
8824
- 6.3: "8.1",
8825
- 6.2: "8",
8826
- 6.1: "7",
8827
- "6.0": "Vista",
8828
- 5.1: "XP"
8829
- };
8830
- osVersion = winVersionMap[winVersion] || winVersion;
8831
- } else if (/iphone|ipad|ipod/i.test(userAgent)) {
8832
- osName = "iOS";
8833
- osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8834
- } else if (/mac os x/i.test(userAgent)) {
8835
- osName = "macOS";
8836
- osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8837
- } else if (/android/i.test(userAgent)) {
8838
- osName = "Android";
8839
- osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
8840
- } else if (/linux/i.test(userAgent)) {
8841
- osName = "Linux";
8842
- } else if (/cros/i.test(userAgent)) {
8843
- osName = "Chrome OS";
8844
- }
8845
- return {
8846
- deviceType,
8847
- browserName,
8848
- browserVersion,
8849
- osName,
8850
- osVersion
8851
- };
8852
- }
8853
- function extractVersion(userAgent, regex) {
8854
- const match = userAgent.match(regex);
8855
- return match ? match[1] : null;
8856
- }
8857
- function getDeviceDescription(parsed) {
8858
- const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
8859
- const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
8860
- return `${browser} on ${os}`;
8861
- }
8862
- module.exports = {
8863
- parseUserAgent,
8864
- getDeviceDescription
8865
- };
8866
- }
8867
- });
8868
-
8869
9835
  // server/src/utils/enhance-session.js
8870
9836
  var require_enhance_session = __commonJS({
8871
9837
  "server/src/utils/enhance-session.js"(exports, module) {
@@ -8920,14 +9886,15 @@ var require_enhance_session = __commonJS({
8920
9886
  country_flag: geoData.country_flag,
8921
9887
  city: geoData.city,
8922
9888
  region: geoData.region,
8923
- timezone: geoData.timezone
9889
+ timezone: geoData.timezone,
9890
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
8924
9891
  };
8925
9892
  if (strapi2) {
8926
9893
  strapi2.documents(SESSION_UID).update({
8927
9894
  documentId: session.documentId,
8928
9895
  data: {
8929
9896
  geoLocation,
8930
- securityScore: geoData.securityScore ?? null
9897
+ securityScore: geoData.riskSource ? geoData.securityScore ?? null : null
8931
9898
  }
8932
9899
  }).catch(() => {
8933
9900
  });
@@ -9636,6 +10603,7 @@ var require_session = __commonJS({
9636
10603
  var { sendServerError } = require_http_errors();
9637
10604
  var { getCoordinator } = require_coordination();
9638
10605
  var { clearSessionStatsCache } = require_session_list();
10606
+ var { noRiskData } = require_risk_data();
9639
10607
  var {
9640
10608
  getNativeOnlySummary,
9641
10609
  endNativeOnlySessions,
@@ -9669,11 +10637,7 @@ var require_session = __commonJS({
9669
10637
  timezone: "Unknown",
9670
10638
  latitude: null,
9671
10639
  longitude: null,
9672
- isVpn: false,
9673
- isProxy: false,
9674
- isThreat: false,
9675
- securityScore: 50,
9676
- riskLevel: "Unknown",
10640
+ ...noRiskData(),
9677
10641
  _status: "disabled",
9678
10642
  _source: "disabled"
9679
10643
  };
@@ -10796,7 +11760,10 @@ var require_geoip_updater = __commonJS({
10796
11760
  var SUPPORTED_MMDB_NAMES = new Set(
10797
11761
  [...SUPPORTED_EDITION_IDS].map((editionId) => `${editionId}.mmdb`)
10798
11762
  );
10799
- function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
11763
+ var RISK_EDITION_IDS = /* @__PURE__ */ new Set(["GeoIP2-Anonymous-IP", "GeoLite2-ASN"]);
11764
+ var ALL_EDITION_IDS = /* @__PURE__ */ new Set([...SUPPORTED_EDITION_IDS, ...RISK_EDITION_IDS]);
11765
+ var ALL_MMDB_NAMES = new Set([...ALL_EDITION_IDS].map((editionId) => `${editionId}.mmdb`));
11766
+ function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY, allowedNames = SUPPORTED_MMDB_NAMES) {
10800
11767
  const root = path.resolve(directory);
10801
11768
  if (value !== void 0 && typeof value !== "string") {
10802
11769
  throw new Error("GeoIP database path must be a string");
@@ -10815,14 +11782,14 @@ var require_geoip_updater = __commonJS({
10815
11782
  }
10816
11783
  filename = requested;
10817
11784
  }
10818
- if (!SUPPORTED_MMDB_NAMES.has(filename)) {
11785
+ if (!allowedNames.has(filename)) {
10819
11786
  throw new Error("GeoIP database path must use a supported MMDB filename");
10820
11787
  }
10821
11788
  return path.join(root, filename);
10822
11789
  }
10823
- async function canonicalizeDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
11790
+ async function canonicalizeDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY, allowedNames = SUPPORTED_MMDB_NAMES) {
10824
11791
  const root = path.resolve(directory);
10825
- const target = resolveDatabaseTarget(value, root);
11792
+ const target = resolveDatabaseTarget(value, root, allowedNames);
10826
11793
  await fs.mkdir(root, { recursive: true, mode: 448 });
10827
11794
  const rootStat = await fs.lstat(root);
10828
11795
  const canonicalRoot = await fs.realpath(root);
@@ -10848,8 +11815,8 @@ var require_geoip_updater = __commonJS({
10848
11815
  }
10849
11816
  return canonicalTarget;
10850
11817
  }
10851
- function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID) {
10852
- return SUPPORTED_EDITION_IDS.has(value) ? value : fallback;
11818
+ function normalizeEditionId(value, fallback = DEFAULT_EDITION_ID, allowed = SUPPORTED_EDITION_IDS) {
11819
+ return allowed.has(value) ? value : fallback;
10853
11820
  }
10854
11821
  function inferEditionIdFromPath(filePath) {
10855
11822
  if (typeof filePath !== "string" || filePath.trim() === "") return "";
@@ -10871,10 +11838,25 @@ var require_geoip_updater = __commonJS({
10871
11838
  function resolveConfig(env = process2.env, argv = process2.argv.slice(2), overrides = {}) {
10872
11839
  const force = argv.includes("--force") || overrides.force === true;
10873
11840
  const configuredOutputPath = overrides.outputPath || env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || env.GEOIP_DATABASE_PATH || "";
11841
+ const requestedEdition = overrides.editionId || env.MAXMIND_EDITION_ID;
11842
+ const databaseDirectory = overrides.databaseDirectory || DEFAULT_GEOIP_DIRECTORY;
11843
+ if (RISK_EDITION_IDS.has(requestedEdition)) {
11844
+ return {
11845
+ accountId: overrides.accountId || env.MAXMIND_ACCOUNT_ID || env.MAXMIND_USER_ID || "",
11846
+ licenseKey: overrides.licenseKey || env.MAXMIND_LICENSE_KEY || "",
11847
+ editionId: requestedEdition,
11848
+ outputPath: resolveDatabaseTarget(
11849
+ `${requestedEdition}.mmdb`,
11850
+ databaseDirectory,
11851
+ ALL_MMDB_NAMES
11852
+ ),
11853
+ mmdbFileName: `${requestedEdition}.mmdb`,
11854
+ force
11855
+ };
11856
+ }
10874
11857
  const editionId = normalizeEditionId(
10875
- overrides.editionId || env.MAXMIND_EDITION_ID || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
11858
+ requestedEdition || inferEditionIdFromPath(configuredOutputPath) || DEFAULT_EDITION_ID
10876
11859
  );
10877
- const databaseDirectory = overrides.databaseDirectory || DEFAULT_GEOIP_DIRECTORY;
10878
11860
  const outputPath = resolveDatabaseTarget(
10879
11861
  configuredOutputPath || `${editionId}.mmdb`,
10880
11862
  databaseDirectory
@@ -10952,7 +11934,9 @@ var require_geoip_updater = __commonJS({
10952
11934
  redirect: "follow"
10953
11935
  });
10954
11936
  if (!response.ok) {
10955
- throw new Error(`MaxMind HEAD failed with HTTP ${response.status}`);
11937
+ const error = new Error(`MaxMind HEAD failed with HTTP ${response.status}`);
11938
+ error.httpStatus = response.status;
11939
+ throw error;
10956
11940
  }
10957
11941
  return {
10958
11942
  lastModified: response.headers.get("last-modified") || "",
@@ -10969,7 +11953,9 @@ var require_geoip_updater = __commonJS({
10969
11953
  redirect: "follow"
10970
11954
  });
10971
11955
  if (!response.ok) {
10972
- throw new Error(`MaxMind download failed with HTTP ${response.status}`);
11956
+ const error = new Error(`MaxMind download failed with HTTP ${response.status}`);
11957
+ error.httpStatus = response.status;
11958
+ throw error;
10973
11959
  }
10974
11960
  return Buffer.from(await response.arrayBuffer());
10975
11961
  }
@@ -11007,8 +11993,12 @@ var require_geoip_updater = __commonJS({
11007
11993
  if (!config.accountId || !config.licenseKey) {
11008
11994
  throw new Error("MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY are required");
11009
11995
  }
11010
- const editionId = normalizeEditionId(config.editionId);
11011
- const outputPath = await canonicalizeDatabaseTarget(config.outputPath);
11996
+ const editionId = normalizeEditionId(config.editionId, DEFAULT_EDITION_ID, ALL_EDITION_IDS);
11997
+ const outputPath = await canonicalizeDatabaseTarget(
11998
+ config.outputPath,
11999
+ DEFAULT_GEOIP_DIRECTORY,
12000
+ ALL_MMDB_NAMES
12001
+ );
11012
12002
  const mmdbFileName = `${editionId}.mmdb`;
11013
12003
  if (path.basename(outputPath) !== mmdbFileName) {
11014
12004
  throw new Error("GeoIP database filename must match the selected edition");
@@ -11060,6 +12050,8 @@ var require_geoip_updater = __commonJS({
11060
12050
  };
11061
12051
  }
11062
12052
  module.exports = {
12053
+ ALL_MMDB_NAMES,
12054
+ RISK_EDITION_IDS,
11063
12055
  DEFAULT_EDITION_ID,
11064
12056
  DEFAULT_GEOIP_DIRECTORY,
11065
12057
  DEFAULT_MMDB_NAME,
@@ -11093,6 +12085,12 @@ var require_settings = __commonJS({
11093
12085
  var { LockTimeoutError } = require_coordination();
11094
12086
  var { resolveDatabaseTarget } = require_geoip_updater();
11095
12087
  var { sendServerError, sendValidationError } = require_http_errors();
12088
+ var {
12089
+ SECURITY_LOG_DEFAULTS,
12090
+ SECURITY_LOG_KEYS,
12091
+ validateSecurityLogSettings
12092
+ } = require_security_log_settings();
12093
+ var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
11096
12094
  var path = __require("node:path");
11097
12095
  var ALLOWED_WEBHOOK_DOMAINS = {
11098
12096
  discord: ["discord.com", "discordapp.com"],
@@ -11266,7 +12264,8 @@ var require_settings = __commonJS({
11266
12264
  slackWebhookUrl: "",
11267
12265
  strictSessionEnforcement: false,
11268
12266
  trustedProxies: false,
11269
- emailTemplates: DEFAULT_EMAIL_TEMPLATES
12267
+ emailTemplates: DEFAULT_EMAIL_TEMPLATES,
12268
+ ...SECURITY_LOG_DEFAULTS
11270
12269
  };
11271
12270
  function mergeSettingsWithDefaults(stored) {
11272
12271
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -11471,6 +12470,9 @@ var require_settings = __commonJS({
11471
12470
  next.emailTemplates = sanitizeEmailTemplates(mergedTemplates);
11472
12471
  }
11473
12472
  }
12473
+ const securityLog = validateSecurityLogSettings(body);
12474
+ errors.push(...securityLog.errors);
12475
+ Object.assign(next, securityLog.values);
11474
12476
  if (errors.length > 0) return { errors };
11475
12477
  const settings = {};
11476
12478
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -11498,6 +12500,13 @@ var require_settings = __commonJS({
11498
12500
  };
11499
12501
  return ctx.body;
11500
12502
  }
12503
+ function canChangeAdminActivity(ctx) {
12504
+ try {
12505
+ return ctx.state?.userAbility?.can?.(ADMIN_ACTIVITY_READ_ACTION) === true;
12506
+ } catch {
12507
+ return false;
12508
+ }
12509
+ }
11501
12510
  module.exports = {
11502
12511
  /**
11503
12512
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -11536,6 +12545,9 @@ var require_settings = __commonJS({
11536
12545
  * Omitted fields keep their stored value. Invalid values are rejected with
11537
12546
  * a 400 whose `error.details.errors` names each field; nothing is clamped
11538
12547
  * or written in that case. Store failures return a 500 with a safe message.
12548
+ * Changing a security log setting (`adminSignInHistory`,
12549
+ * `adminContentActivity`, `securityLogStoreIp`, `securityLogAnonymizeIp`,
12550
+ * `securityLogRetentionDays`) also needs `admin-activity.read`, else 403.
11539
12551
  *
11540
12552
  * @route PUT /magic-sessionmanager/settings
11541
12553
  * @returns {Promise<void>}
@@ -11567,6 +12579,10 @@ var require_settings = __commonJS({
11567
12579
  };
11568
12580
  const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
11569
12581
  if (errors.length > 0) return { errors };
12582
+ const changesAdminActivity = SECURITY_LOG_KEYS.some(
12583
+ (key) => sanitizedSettings[key] !== current[key]
12584
+ );
12585
+ if (changesAdminActivity && !canChangeAdminActivity(ctx)) return { forbidden: true };
11570
12586
  await pluginStore.set({
11571
12587
  key: "settings",
11572
12588
  value: sanitizedSettings
@@ -11574,6 +12590,11 @@ var require_settings = __commonJS({
11574
12590
  const revision = await notifySettingsChanged(strapi);
11575
12591
  return { settings: sanitizedSettings, revision };
11576
12592
  });
12593
+ if (outcome.forbidden) {
12594
+ return ctx.forbidden('Changing the security log settings needs "View admin activity".', {
12595
+ reason: "admin-activity-permission"
12596
+ });
12597
+ }
11577
12598
  if (outcome.conflict) {
11578
12599
  return sendSettingsConflict(ctx, outcome.currentRevision);
11579
12600
  }
@@ -11609,6 +12630,218 @@ var require_settings = __commonJS({
11609
12630
  }
11610
12631
  });
11611
12632
 
12633
+ // server/src/utils/risk-databases.js
12634
+ var require_risk_databases = __commonJS({
12635
+ "server/src/utils/risk-databases.js"(exports, module) {
12636
+ "use strict";
12637
+ var fs = __require("node:fs");
12638
+ var path = __require("node:path");
12639
+ var {
12640
+ DEFAULT_GEOIP_DIRECTORY,
12641
+ RISK_EDITION_IDS,
12642
+ readMetadata
12643
+ } = require_geoip_updater();
12644
+ var { calculateSecurityScore, getRiskLevel, noRiskData } = require_risk_data();
12645
+ var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
12646
+ var RISK_DATABASES = Object.freeze({
12647
+ "anonymous-ip": Object.freeze({
12648
+ editionId: "GeoIP2-Anonymous-IP",
12649
+ envVar: "MAGIC_SESSIONMANAGER_ANONYMOUS_IP_DATABASE",
12650
+ method: "anonymousIP"
12651
+ }),
12652
+ asn: Object.freeze({
12653
+ editionId: "GeoLite2-ASN",
12654
+ envVar: "MAGIC_SESSIONMANAGER_ASN_DATABASE",
12655
+ method: "asn"
12656
+ })
12657
+ });
12658
+ var HOSTING_ASNS = Object.freeze(
12659
+ /* @__PURE__ */ new Set([
12660
+ 16509,
12661
+ // Amazon AWS
12662
+ 14618,
12663
+ // Amazon AWS
12664
+ 396982,
12665
+ // Google Cloud
12666
+ 8075,
12667
+ // Microsoft (Azure; also Microsoft's own offices)
12668
+ 14061,
12669
+ // DigitalOcean
12670
+ 24940,
12671
+ // Hetzner Online
12672
+ 213230,
12673
+ // Hetzner Cloud
12674
+ 16276,
12675
+ // OVHcloud
12676
+ 63949,
12677
+ // Akamai Connected Cloud (Linode)
12678
+ 20473,
12679
+ // Vultr (The Constant Company)
12680
+ 51167,
12681
+ // Contabo
12682
+ 31898,
12683
+ // Oracle Cloud
12684
+ 45102,
12685
+ // Alibaba Cloud
12686
+ 12876,
12687
+ // Scaleway
12688
+ 60781,
12689
+ // Leaseweb Netherlands
12690
+ 28753,
12691
+ // Leaseweb Germany
12692
+ 8560,
12693
+ // IONOS
12694
+ 47583,
12695
+ // Hostinger
12696
+ 9009
12697
+ // M247
12698
+ ])
12699
+ );
12700
+ var readerCache = /* @__PURE__ */ new Map();
12701
+ function resolveRiskDatabasePath(kind, env = process.env) {
12702
+ const definition = RISK_DATABASES[kind];
12703
+ const configured = typeof env[definition.envVar] === "string" ? env[definition.envVar].trim() : "";
12704
+ if (configured) {
12705
+ return {
12706
+ path: path.isAbsolute(configured) ? configured : path.resolve(process.cwd(), configured),
12707
+ fromEnvironment: true
12708
+ };
12709
+ }
12710
+ return {
12711
+ path: path.join(DEFAULT_GEOIP_DIRECTORY, `${definition.editionId}.mmdb`),
12712
+ fromEnvironment: false
12713
+ };
12714
+ }
12715
+ async function openRiskReader(databasePath) {
12716
+ if (readerCache.has(databasePath)) return readerCache.get(databasePath);
12717
+ const { Reader } = __require("@maxmind/geoip2-node");
12718
+ const readerPromise = Reader.open(databasePath, {
12719
+ watchForUpdates: true,
12720
+ watchForUpdatesNonPersistent: true
12721
+ });
12722
+ readerCache.set(databasePath, readerPromise);
12723
+ try {
12724
+ return await readerPromise;
12725
+ } catch (error) {
12726
+ readerCache.delete(databasePath);
12727
+ throw error;
12728
+ }
12729
+ }
12730
+ function resetRiskReaders() {
12731
+ for (const databasePath of readerCache.keys()) fs.unwatchFile(databasePath);
12732
+ readerCache.clear();
12733
+ }
12734
+ async function readRiskRecord(kind, ip, env = process.env) {
12735
+ const { path: databasePath } = resolveRiskDatabasePath(kind, env);
12736
+ if (!fs.existsSync(databasePath)) return { status: "missing" };
12737
+ try {
12738
+ const reader = await openRiskReader(databasePath);
12739
+ return { status: "ok", record: reader[RISK_DATABASES[kind].method](ip) };
12740
+ } catch (error) {
12741
+ if (error?.name === "AddressNotFoundError") return { status: "absent" };
12742
+ return { status: "error", name: error?.name || "Error" };
12743
+ }
12744
+ }
12745
+ function buildRiskData({ anonymous, asn }) {
12746
+ const asnRecord = asn?.status === "ok" ? asn.record : null;
12747
+ const asnNumber = Number.isInteger(asnRecord?.autonomousSystemNumber) ? asnRecord.autonomousSystemNumber : null;
12748
+ const asnFields = asnRecord ? {
12749
+ asn: asnNumber === null ? null : `AS${asnNumber}`,
12750
+ org: asnRecord.autonomousSystemOrganization || null
12751
+ } : {};
12752
+ let flags;
12753
+ let riskSource;
12754
+ if (anonymous?.status === "ok" || anonymous?.status === "absent") {
12755
+ const record = anonymous.record || {};
12756
+ riskSource = "anonymous-ip";
12757
+ flags = {
12758
+ isAnonymous: record.isAnonymous === true,
12759
+ isVpn: record.isAnonymousVpn === true,
12760
+ isPublicProxy: record.isPublicProxy === true,
12761
+ isResidentialProxy: record.isResidentialProxy === true,
12762
+ isProxy: record.isPublicProxy === true || record.isResidentialProxy === true,
12763
+ isTor: record.isTorExitNode === true,
12764
+ isHosting: record.isHostingProvider === true,
12765
+ // MaxMind's Anonymous IP data has no "threat" category.
12766
+ isThreat: false
12767
+ };
12768
+ } else if (asn?.status === "ok" || asn?.status === "absent") {
12769
+ riskSource = "asn-heuristic";
12770
+ flags = {
12771
+ isAnonymous: false,
12772
+ isVpn: false,
12773
+ isPublicProxy: false,
12774
+ isResidentialProxy: false,
12775
+ isProxy: false,
12776
+ isTor: false,
12777
+ isHosting: asnNumber !== null && HOSTING_ASNS.has(asnNumber),
12778
+ isThreat: false
12779
+ };
12780
+ } else {
12781
+ const failed = anonymous?.status === "error" || asn?.status === "error";
12782
+ return { ...noRiskData(), ...asnFields, _riskStatus: failed ? "error" : "missing" };
12783
+ }
12784
+ return {
12785
+ ...flags,
12786
+ ...asnFields,
12787
+ securityScore: calculateSecurityScore(flags),
12788
+ riskLevel: getRiskLevel(flags),
12789
+ riskSource,
12790
+ _riskStatus: "ok"
12791
+ };
12792
+ }
12793
+ async function lookupRiskData(ip, env = process.env) {
12794
+ const [anonymous, asn] = await Promise.all([
12795
+ readRiskRecord("anonymous-ip", ip, env),
12796
+ readRiskRecord("asn", ip, env)
12797
+ ]);
12798
+ return buildRiskData({ anonymous, asn });
12799
+ }
12800
+ async function isUsableRiskDatabase(kind, databasePath) {
12801
+ try {
12802
+ const reader = await openRiskReader(databasePath);
12803
+ reader[RISK_DATABASES[kind].method]("127.0.0.1");
12804
+ return true;
12805
+ } catch (error) {
12806
+ return error?.name === "AddressNotFoundError";
12807
+ }
12808
+ }
12809
+ async function describeRiskDatabase(kind, env = process.env) {
12810
+ const { editionId } = RISK_DATABASES[kind];
12811
+ const { path: databasePath, fromEnvironment } = resolveRiskDatabasePath(kind, env);
12812
+ const exists = fs.existsSync(databasePath);
12813
+ const usable = exists ? await isUsableRiskDatabase(kind, databasePath) : false;
12814
+ return {
12815
+ editionId,
12816
+ exists,
12817
+ usable,
12818
+ fromEnvironment,
12819
+ // Only the dedicated folder is named; an environment path stays private.
12820
+ file: fromEnvironment ? null : `${SAFE_GEOIP_DIRECTORY_LABEL}/${editionId}.mmdb`,
12821
+ metadata: !fromEnvironment && exists ? await readMetadata(`${databasePath}.metadata.json`) : null
12822
+ };
12823
+ }
12824
+ async function getRiskDataStatus(env = process.env) {
12825
+ const [anonymousIp, asn] = await Promise.all([
12826
+ describeRiskDatabase("anonymous-ip", env),
12827
+ describeRiskDatabase("asn", env)
12828
+ ]);
12829
+ const source = anonymousIp.usable ? "anonymous-ip" : asn.usable ? "asn-heuristic" : null;
12830
+ return { available: source !== null, source, anonymousIp, asn };
12831
+ }
12832
+ module.exports = {
12833
+ HOSTING_ASNS,
12834
+ RISK_DATABASES,
12835
+ RISK_EDITION_IDS,
12836
+ buildRiskData,
12837
+ getRiskDataStatus,
12838
+ lookupRiskData,
12839
+ resetRiskReaders,
12840
+ resolveRiskDatabasePath
12841
+ };
12842
+ }
12843
+ });
12844
+
11612
12845
  // server/src/controllers/geoip.js
11613
12846
  var require_geoip = __commonJS({
11614
12847
  "server/src/controllers/geoip.js"(exports, module) {
@@ -11631,6 +12864,7 @@ var require_geoip = __commonJS({
11631
12864
  var { sendServerError } = require_http_errors();
11632
12865
  var { setPluginStoreValue } = require_plugin_store();
11633
12866
  var { getHostFingerprint } = require_coordination();
12867
+ var { getRiskDataStatus, RISK_DATABASES } = require_risk_databases();
11634
12868
  var CREDENTIALS_KEY = "geoipCredentials";
11635
12869
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
11636
12870
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -11687,6 +12921,16 @@ var require_geoip = __commonJS({
11687
12921
  force
11688
12922
  });
11689
12923
  }
12924
+ var UPDATABLE_DATABASES = /* @__PURE__ */ new Set(["location", ...Object.keys(RISK_DATABASES)]);
12925
+ function buildRiskUpdaterConfig(database, storedCredentials, force = false) {
12926
+ return resolveConfig(process.env, force ? ["--force"] : [], {
12927
+ accountId: process.env.MAXMIND_ACCOUNT_ID || storedCredentials.accountId || "",
12928
+ licenseKey: process.env.MAXMIND_LICENSE_KEY || storedCredentials.licenseKey || "",
12929
+ editionId: RISK_DATABASES[database].editionId,
12930
+ databaseDirectory: DEFAULT_GEOIP_DIRECTORY,
12931
+ force
12932
+ });
12933
+ }
11690
12934
  function sanitizeCredentialInput(value, maxLength = 256) {
11691
12935
  if (typeof value !== "string") return "";
11692
12936
  return value.replace(/\0/g, "").trim().slice(0, maxLength);
@@ -11725,7 +12969,11 @@ var require_geoip = __commonJS({
11725
12969
  // answered. In multi-instance deployments each instance reports
11726
12970
  // its own file; `instance` is a non-reversible host fingerprint.
11727
12971
  scope: "instance",
11728
- instance: getHostFingerprint()
12972
+ instance: getHostFingerprint(),
12973
+ // VPN, proxy and Tor detection needs a dedicated risk data source.
12974
+ // The location providers (ipapi.co, GeoLite2 City/Country) have
12975
+ // none; the local Anonymous IP or ASN database is reported here.
12976
+ risk: await getRiskDataStatus()
11729
12977
  }
11730
12978
  });
11731
12979
  } catch (error) {
@@ -11780,9 +13028,15 @@ var require_geoip = __commonJS({
11780
13028
  try {
11781
13029
  const body = ctx.request.body || {};
11782
13030
  const force = body.force === true;
13031
+ const database = body.database === void 0 ? "location" : body.database;
13032
+ if (!UPDATABLE_DATABASES.has(database)) {
13033
+ return ctx.badRequest("Unknown GeoIP database", {
13034
+ database: ["Use location, anonymous-ip or asn."]
13035
+ });
13036
+ }
11783
13037
  const settings = await getPluginSettings(strapi2);
11784
13038
  const storedCredentials = await getStoredCredentials(strapi2);
11785
- const config = buildUpdaterConfig(settings, storedCredentials, force);
13039
+ const config = database === "location" ? buildUpdaterConfig(settings, storedCredentials, force) : buildRiskUpdaterConfig(database, storedCredentials, force);
11786
13040
  if (!config.accountId || !config.licenseKey) {
11787
13041
  return ctx.badRequest("MaxMind credentials are required before downloading GeoIP data");
11788
13042
  }
@@ -11794,6 +13048,13 @@ var require_geoip = __commonJS({
11794
13048
  "[magic-sessionmanager/geoip] GeoIP download failed:",
11795
13049
  error?.name || "Error"
11796
13050
  );
13051
+ if (error?.httpStatus === 401 || error?.httpStatus === 403) {
13052
+ return sendServerError(
13053
+ ctx,
13054
+ 502,
13055
+ "MaxMind refused the download. Check the credentials and that your account includes this database."
13056
+ );
13057
+ }
11797
13058
  return sendServerError(ctx, 502, "Error updating GeoIP database");
11798
13059
  }
11799
13060
  invalidateSettingsCache();
@@ -11810,6 +13071,7 @@ var require_geoip = __commonJS({
11810
13071
  }
11811
13072
  },
11812
13073
  __private: {
13074
+ buildRiskUpdaterConfig,
11813
13075
  buildUpdaterConfig,
11814
13076
  getCredentialSource,
11815
13077
  getStoredCredentials,
@@ -11824,6 +13086,9 @@ var require_admin_sessions = __commonJS({
11824
13086
  "server/src/utils/admin-sessions.js"(exports, module) {
11825
13087
  "use strict";
11826
13088
  var { z } = __require("@strapi/utils");
13089
+ var { hashDeviceId } = require_admin_request_info();
13090
+ var { resolveSecurityLogSettings } = require_security_log_settings();
13091
+ var { getPluginSettings } = require_settings_loader();
11827
13092
  var ADMIN_ORIGIN = "admin";
11828
13093
  var SESSION_UID = "admin::session";
11829
13094
  var ADMIN_USER_UID = "admin::user";
@@ -12025,6 +13290,18 @@ var require_admin_sessions = __commonJS({
12025
13290
  }
12026
13291
  return map;
12027
13292
  }
13293
+ async function readSignInRecording(strapi2) {
13294
+ try {
13295
+ const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
13296
+ return {
13297
+ signIns: options.signIns,
13298
+ ipAddresses: options.signIns && options.storeIp,
13299
+ anonymizeIp: options.signIns && options.storeIp && options.anonymizeIp
13300
+ };
13301
+ } catch {
13302
+ return { signIns: false, ipAddresses: false, anonymizeIp: false };
13303
+ }
13304
+ }
12028
13305
  async function listAdmins(strapi2, query, actor) {
12029
13306
  const policy = readSessionPolicy(strapi2);
12030
13307
  if (!getAdminSessionManager(strapi2)) {
@@ -12035,7 +13312,8 @@ var require_admin_sessions = __commonJS({
12035
13312
  pagination: { page: 1, pageSize: query.pageSize, total: 0, pageCount: 1 },
12036
13313
  stats: null,
12037
13314
  policy,
12038
- truncated: false
13315
+ truncated: false,
13316
+ recording: await readSignInRecording(strapi2)
12039
13317
  }
12040
13318
  };
12041
13319
  }
@@ -12116,7 +13394,8 @@ var require_admin_sessions = __commonJS({
12116
13394
  totalAdmins: Number(totalAdmins) || 0
12117
13395
  },
12118
13396
  policy,
12119
- truncated
13397
+ truncated,
13398
+ recording: await readSignInRecording(strapi2)
12120
13399
  }
12121
13400
  };
12122
13401
  }
@@ -12187,6 +13466,7 @@ var require_admin_sessions = __commonJS({
12187
13466
  const currentDeviceId = self ? await findCurrentDeviceId(strapi2, { userId, sessionId: actor.sessionId }) : null;
12188
13467
  let ended;
12189
13468
  let signedOutSelf;
13469
+ let endedDeviceId = null;
12190
13470
  if (sessionId) {
12191
13471
  const row = await strapi2.db.query(SESSION_UID).findOne({
12192
13472
  select: ["userId", "deviceId", "origin"],
@@ -12197,6 +13477,7 @@ var require_admin_sessions = __commonJS({
12197
13477
  }
12198
13478
  if (blockReason === "account-inactive") throw new AdminSignOutError(404, "Session not found");
12199
13479
  await manager.invalidateRefreshToken(userId, String(row.deviceId));
13480
+ endedDeviceId = String(row.deviceId);
12200
13481
  ended = 1;
12201
13482
  signedOutSelf = Boolean(currentDeviceId) && String(row.deviceId) === currentDeviceId;
12202
13483
  } else {
@@ -12209,6 +13490,18 @@ var require_admin_sessions = __commonJS({
12209
13490
  target.id
12210
13491
  )} scope=${scope} ended=${ended}`;
12211
13492
  strapi2.log.info(audit);
13493
+ try {
13494
+ strapi2.plugin("magic-sessionmanager")?.service("security-log")?.record({
13495
+ event: "admin.session.revoked",
13496
+ actorType: "admin",
13497
+ actorId: Number(actor.id),
13498
+ targetType: "admin",
13499
+ targetId: Number(target.id),
13500
+ meta: { scope: scope === "one" ? "one_browser" : "everywhere", ended },
13501
+ deviceHash: endedDeviceId ? hashDeviceId(endedDeviceId) : null
13502
+ });
13503
+ } catch {
13504
+ }
12212
13505
  try {
12213
13506
  strapi2.eventHub?.emit?.("magic-sessionmanager.admin-sessions.signed-out", {
12214
13507
  actorId: Number(actor.id),
@@ -12409,6 +13702,149 @@ var require_admin_sessions2 = __commonJS({
12409
13702
  }
12410
13703
  });
12411
13704
 
13705
+ // server/src/controllers/admin-activity.js
13706
+ var require_admin_activity = __commonJS({
13707
+ "server/src/controllers/admin-activity.js"(exports, module) {
13708
+ "use strict";
13709
+ var { z } = __require("@strapi/utils");
13710
+ var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
13711
+ var { parseInput } = require_admin_sessions();
13712
+ var { sendServerError, sendValidationError } = require_http_errors();
13713
+ var { createLogger } = require_logger();
13714
+ var MAX_PAGE_SIZE = 100;
13715
+ var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
13716
+ 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();
13717
+ var common = {
13718
+ adminId: adminIdField,
13719
+ from: dateField("from"),
13720
+ to: dateField("to"),
13721
+ page: z.coerce.number().int().min(1).max(1e6).default(1),
13722
+ pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
13723
+ };
13724
+ var signInQuerySchema = z.strictObject({
13725
+ ...common,
13726
+ event: z.enum(
13727
+ /** @type {[string, ...string[]]} */
13728
+ Object.keys(SIGN_IN_FILTERS)
13729
+ ).default("all")
13730
+ });
13731
+ var activityQuerySchema = z.strictObject({
13732
+ ...common,
13733
+ action: z.enum(
13734
+ /** @type {[string, ...string[]]} */
13735
+ ["all", ...CONTENT_ACTIONS]
13736
+ ).default("all"),
13737
+ contentType: z.string().regex(
13738
+ /^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/,
13739
+ "contentType must be a content type uid"
13740
+ ).optional()
13741
+ });
13742
+ var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
13743
+ var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
13744
+ cursor: cursorField
13745
+ });
13746
+ var activityExportSchema = activityQuerySchema.omit({ page: true, pageSize: true }).extend({
13747
+ cursor: cursorField
13748
+ });
13749
+ module.exports = ({ strapi: strapi2 }) => {
13750
+ const log = createLogger(strapi2);
13751
+ const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
13752
+ const handle = async (ctx, schema, run, operation) => {
13753
+ const parsed = parseInput(schema, ctx.query);
13754
+ if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
13755
+ const query = parsed.value;
13756
+ if (query.from && query.to && query.from > query.to) {
13757
+ return sendValidationError(ctx, "Invalid query", [
13758
+ { path: ["from"], message: "from must not be after to" }
13759
+ ]);
13760
+ }
13761
+ try {
13762
+ ctx.body = await run(query);
13763
+ return ctx.body;
13764
+ } catch (error) {
13765
+ log.error(
13766
+ `Admin activity: ${operation} failed`,
13767
+ /** @type {any} */
13768
+ error?.name || "Error"
13769
+ );
13770
+ return sendServerError(ctx, 500, "Admin activity could not be loaded.");
13771
+ }
13772
+ };
13773
+ return {
13774
+ /**
13775
+ * One page of the admin sign-in history: sign-ins, failed attempts,
13776
+ * lockouts and sign-outs, newest first.
13777
+ *
13778
+ * @route GET /magic-sessionmanager/admin-activity/sign-ins
13779
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
13780
+ * read rate limit.
13781
+ * @param {Context} ctx Reads `ctx.query.adminId` (optional positive integer), `event`
13782
+ * (`all`|`succeeded`|`failed`|`signed-out`), `from`/`to` (ISO dates), `page`, `pageSize`
13783
+ * (1..100, default 20).
13784
+ * @returns {Promise<unknown>} 200 `{ data: SignInRow[], meta: { pagination, recording } }`;
13785
+ * 400 ValidationError with field errors; 500 fixed message. Rows hold IP address
13786
+ * (possibly anonymised), location, browser, OS and session state; never the device id,
13787
+ * a typed email or a token.
13788
+ */
13789
+ async listSignIns(ctx) {
13790
+ return handle(ctx, signInQuerySchema, (query) => service().listSignIns(query), "sign-ins");
13791
+ },
13792
+ /**
13793
+ * One page of Content Manager activity, newest first.
13794
+ *
13795
+ * @route GET /magic-sessionmanager/admin-activity/content
13796
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
13797
+ * read rate limit.
13798
+ * @param {Context} ctx Reads `ctx.query.adminId`, `action` (`all` or an action),
13799
+ * `contentType` (uid), `from`/`to`, `page`, `pageSize`.
13800
+ * @returns {Promise<unknown>} 200 `{ data: ActivityRow[], meta: { pagination, recording,
13801
+ * contentTypes, contentManagerAccess? } }`; 400; 500 fixed message.
13802
+ */
13803
+ async listContentActivity(ctx) {
13804
+ return handle(
13805
+ ctx,
13806
+ activityQuerySchema,
13807
+ (query) => service().listContentActivity(query),
13808
+ "content"
13809
+ );
13810
+ },
13811
+ /**
13812
+ * One export batch (500 rows, keyset cursor) of the sign-in history.
13813
+ *
13814
+ * @route GET /magic-sessionmanager/admin-activity/sign-ins/export
13815
+ * @auth As listSignIns.
13816
+ * @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
13817
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
13818
+ */
13819
+ async exportSignIns(ctx) {
13820
+ return handle(
13821
+ ctx,
13822
+ signInExportSchema,
13823
+ (query) => service().exportBatch("sign-ins", query, query.cursor || null),
13824
+ "sign-in export"
13825
+ );
13826
+ },
13827
+ /**
13828
+ * One export batch (500 rows, keyset cursor) of Content Manager activity.
13829
+ *
13830
+ * @route GET /magic-sessionmanager/admin-activity/content/export
13831
+ * @auth As listContentActivity.
13832
+ * @param {Context} ctx Same filters as the list, plus `cursor`.
13833
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
13834
+ */
13835
+ async exportContentActivity(ctx) {
13836
+ return handle(
13837
+ ctx,
13838
+ activityExportSchema,
13839
+ (query) => service().exportBatch("content", query, query.cursor || null),
13840
+ "activity export"
13841
+ );
13842
+ }
13843
+ };
13844
+ };
13845
+ }
13846
+ });
13847
+
12412
13848
  // server/src/controllers/index.js
12413
13849
  var require_controllers = __commonJS({
12414
13850
  "server/src/controllers/index.js"(exports, module) {
@@ -12417,11 +13853,13 @@ var require_controllers = __commonJS({
12417
13853
  var settings = require_settings();
12418
13854
  var geoip = require_geoip();
12419
13855
  var adminSessions = require_admin_sessions2();
13856
+ var adminActivity = require_admin_activity();
12420
13857
  module.exports = {
12421
13858
  session,
12422
13859
  settings,
12423
13860
  geoip,
12424
- "admin-sessions": adminSessions
13861
+ "admin-sessions": adminSessions,
13862
+ "admin-activity": adminActivity
12425
13863
  };
12426
13864
  }
12427
13865
  });
@@ -12816,9 +14254,12 @@ var require_session2 = __commonJS({
12816
14254
  country_flag: geoData.country_flag,
12817
14255
  city: geoData.city,
12818
14256
  region: geoData.region,
12819
- timezone: geoData.timezone
14257
+ timezone: geoData.timezone,
14258
+ // Marks the stored score as real risk data; without a
14259
+ // risk source the score is null (not a fake 100).
14260
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
12820
14261
  } : null,
12821
- securityScore: geoData?.securityScore ?? null
14262
+ securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
12822
14263
  }
12823
14264
  });
12824
14265
  log.info("[SUCCESS] End-user session metadata created");
@@ -13688,7 +15129,12 @@ var require_geolocation = __commonJS({
13688
15129
  var path = __require("node:path");
13689
15130
  var { getPluginSettings } = require_settings_loader();
13690
15131
  var { getCoordinator, hashedKey } = require_coordination();
13691
- var { resolveDatabaseTarget } = require_geoip_updater();
15132
+ var {
15133
+ DEFAULT_GEOIP_DIRECTORY,
15134
+ resolveDatabaseTarget
15135
+ } = require_geoip_updater();
15136
+ var { calculateSecurityScore, getRiskLevel, noRiskData } = require_risk_data();
15137
+ var { lookupRiskData } = require_risk_databases();
13692
15138
  var GEO_API_TIMEOUT_MS = 4e3;
13693
15139
  var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
13694
15140
  var IPAPI_FAILURE_CACHE_TTL_MS = 5 * 60 * 1e3;
@@ -13718,11 +15164,24 @@ var require_geolocation = __commonJS({
13718
15164
  function uniqueValues(values) {
13719
15165
  return [...new Set(values.filter(Boolean))];
13720
15166
  }
15167
+ function resolveConfiguredCandidates(value) {
15168
+ if (typeof value !== "string" || value.trim() === "") return [];
15169
+ const trimmed = value.trim();
15170
+ if (path.isAbsolute(trimmed)) return [trimmed];
15171
+ const isBareName = trimmed !== "." && trimmed !== ".." && !/[\\/]/.test(trimmed) && !trimmed.includes("\0");
15172
+ if (isBareName) {
15173
+ return uniqueValues([
15174
+ path.join(DEFAULT_GEOIP_DIRECTORY, trimmed),
15175
+ path.resolve(process.cwd(), trimmed)
15176
+ ]);
15177
+ }
15178
+ return [path.resolve(process.cwd(), trimmed)];
15179
+ }
13721
15180
  function resolveDatabaseCandidates(settings = {}) {
13722
- const configured = normalizeDatabasePath(
15181
+ const configured = resolveConfiguredCandidates(
13723
15182
  settings.geoIpDatabasePath || process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE || process.env.GEOIP_DATABASE_PATH
13724
15183
  );
13725
- if (configured) return [configured];
15184
+ if (configured.length > 0) return configured;
13726
15185
  return uniqueValues([
13727
15186
  normalizeDatabasePath(process.env.GEOLITE2_CITY_MMDB),
13728
15187
  normalizeDatabasePath(process.env.GEOIP_CITY_DATABASE_PATH),
@@ -13741,7 +15200,11 @@ var require_geolocation = __commonJS({
13741
15200
  return readerCache.get(databasePath);
13742
15201
  }
13743
15202
  const { Reader } = __require("@maxmind/geoip2-node");
13744
- const readerPromise = Reader.open(databasePath, { watchForUpdates: true });
15203
+ const readerPromise = Reader.open(databasePath, {
15204
+ watchForUpdates: true,
15205
+ // Reloads a replaced file without keeping the process alive on its own.
15206
+ watchForUpdatesNonPersistent: true
15207
+ });
13745
15208
  readerCache.set(databasePath, readerPromise);
13746
15209
  try {
13747
15210
  return await readerPromise;
@@ -13894,13 +15357,8 @@ var require_geolocation = __commonJS({
13894
15357
  org: null,
13895
15358
  asn: null,
13896
15359
  network: data.traits?.network || null,
13897
- isVpn: false,
13898
- isProxy: false,
13899
- isThreat: false,
13900
- isAnonymous: false,
13901
- isTor: false,
13902
- securityScore: 100,
13903
- riskLevel: "Low",
15360
+ // A location database has no VPN, proxy or Tor data: no risk data here.
15361
+ ...noRiskData(),
13904
15362
  _status: "ok",
13905
15363
  _source: "local-mmdb",
13906
15364
  _databaseType: "country"
@@ -13925,13 +15383,8 @@ var require_geolocation = __commonJS({
13925
15383
  org: null,
13926
15384
  asn: null,
13927
15385
  network: data.traits?.network || null,
13928
- isVpn: false,
13929
- isProxy: false,
13930
- isThreat: false,
13931
- isAnonymous: false,
13932
- isTor: false,
13933
- securityScore: 100,
13934
- riskLevel: "Low",
15386
+ // A location database has no VPN, proxy or Tor data: no risk data here.
15387
+ ...noRiskData(),
13935
15388
  _status: "ok",
13936
15389
  _source: "local-mmdb",
13937
15390
  _databaseType: "city"
@@ -14027,10 +15480,7 @@ var require_geolocation = __commonJS({
14027
15480
  timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
14028
15481
  latitude: null,
14029
15482
  longitude: null,
14030
- isVpn: false,
14031
- isProxy: false,
14032
- isThreat: false,
14033
- securityScore: 100,
15483
+ ...noRiskData(),
14034
15484
  riskLevel: "None",
14035
15485
  _status: "private",
14036
15486
  _source: "local"
@@ -14045,21 +15495,53 @@ var require_geolocation = __commonJS({
14045
15495
  return this.getFallbackData(lookupIp, "disabled", "disabled");
14046
15496
  }
14047
15497
  if (provider === "local-mmdb") {
14048
- return this.getLocalMmdbIpInfo(lookupIp, settings);
15498
+ return this.withRiskData(await this.getLocalMmdbIpInfo(lookupIp, settings), lookupIp);
14049
15499
  }
14050
15500
  if (provider === "auto") {
14051
15501
  const databasePath = resolveExistingDatabasePath(settings);
14052
15502
  if (databasePath && fs.existsSync(databasePath)) {
14053
15503
  const localResult = await this.getLocalMmdbIpInfo(lookupIp, settings);
14054
15504
  if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
14055
- return localResult;
15505
+ return this.withRiskData(localResult, lookupIp);
14056
15506
  }
14057
15507
  strapi2.log.warn(
14058
15508
  "[magic-sessionmanager/geolocation] Local MMDB lookup failed, falling back to ipapi.co"
14059
15509
  );
14060
15510
  }
14061
15511
  }
14062
- return this.getIpapiIpInfo(lookupIp);
15512
+ return this.withRiskData(await this.getIpapiIpInfo(lookupIp), lookupIp);
15513
+ },
15514
+ /**
15515
+ * Adds risk data (VPN, proxy, Tor, hosting) from the local risk databases
15516
+ * to a location result. Location providers have none; without a risk
15517
+ * database the result keeps noRiskData(). The lookup is local, so no
15518
+ * address leaves the server. The ASN database also fills `asn` and `org`
15519
+ * when the location provider gave none.
15520
+ *
15521
+ * @param {object} result Location lookup result.
15522
+ * @param {string} lookupIp Normalized, validated IP address.
15523
+ * @returns {Promise<object>} Result with risk fields.
15524
+ */
15525
+ async withRiskData(result, lookupIp) {
15526
+ if (!result || typeof result !== "object") return result;
15527
+ try {
15528
+ const { asn, org, ...risk } = await lookupRiskData(lookupIp);
15529
+ if (risk._riskStatus === "error") {
15530
+ strapi2.log.warn("[magic-sessionmanager/geolocation] Risk database lookup failed");
15531
+ }
15532
+ return {
15533
+ ...result,
15534
+ ...risk,
15535
+ ...asn && !result.asn ? { asn } : {},
15536
+ ...org && !result.org ? { org } : {}
15537
+ };
15538
+ } catch (error) {
15539
+ strapi2.log.warn(
15540
+ "[magic-sessionmanager/geolocation] Risk database lookup failed:",
15541
+ error?.name || "Error"
15542
+ );
15543
+ return { ...result, ...noRiskData(), _riskStatus: "error" };
15544
+ }
14063
15545
  },
14064
15546
  /**
14065
15547
  * Reads effective GEOIP provider settings.
@@ -14231,23 +15713,9 @@ var require_geolocation = __commonJS({
14231
15713
  postal: data.postal,
14232
15714
  org: data.org,
14233
15715
  asn: data.asn,
14234
- isVpn: data.threat?.is_vpn || false,
14235
- isProxy: data.threat?.is_proxy || false,
14236
- isThreat: data.threat?.is_threat || false,
14237
- isAnonymous: data.threat?.is_anonymous || false,
14238
- isTor: data.threat?.is_tor || false,
14239
- securityScore: this.calculateSecurityScore({
14240
- isVpn: data.threat?.is_vpn,
14241
- isProxy: data.threat?.is_proxy,
14242
- isThreat: data.threat?.is_threat,
14243
- isAnonymous: data.threat?.is_anonymous,
14244
- isTor: data.threat?.is_tor
14245
- }),
14246
- riskLevel: this.getRiskLevel({
14247
- isVpn: data.threat?.is_vpn,
14248
- isProxy: data.threat?.is_proxy,
14249
- isThreat: data.threat?.is_threat
14250
- }),
15716
+ // ipapi.co documents no VPN, proxy or threat fields
15717
+ // (https://ipapi.co/api/), so its answer carries no risk data.
15718
+ ...noRiskData(),
14251
15719
  _status: "ok",
14252
15720
  _source: "ipapi"
14253
15721
  };
@@ -14280,25 +15748,16 @@ var require_geolocation = __commonJS({
14280
15748
  * @param {object} flags
14281
15749
  * @returns {number}
14282
15750
  */
14283
- calculateSecurityScore({ isVpn, isProxy, isThreat, isAnonymous, isTor }) {
14284
- let score = 100;
14285
- if (isTor) score -= 50;
14286
- if (isThreat) score -= 40;
14287
- if (isVpn) score -= 20;
14288
- if (isProxy) score -= 15;
14289
- if (isAnonymous) score -= 10;
14290
- return Math.max(0, score);
15751
+ calculateSecurityScore(flags) {
15752
+ return calculateSecurityScore(flags || {});
14291
15753
  },
14292
15754
  /**
14293
- * Maps threat indicators to a human-readable risk level.
15755
+ * Maps risk indicators to a human-readable risk level.
14294
15756
  * @param {object} flags
14295
15757
  * @returns {string}
14296
15758
  */
14297
- getRiskLevel({ isVpn, isProxy, isThreat }) {
14298
- if (isThreat) return "High";
14299
- if (isVpn && isProxy) return "Medium-High";
14300
- if (isVpn || isProxy) return "Medium";
14301
- return "Low";
15759
+ getRiskLevel(flags) {
15760
+ return getRiskLevel(flags || {});
14302
15761
  },
14303
15762
  /**
14304
15763
  * Converts a 2-letter ISO country code into a flag emoji.
@@ -14349,11 +15808,7 @@ var require_geolocation = __commonJS({
14349
15808
  timezone: "Unknown",
14350
15809
  latitude: null,
14351
15810
  longitude: null,
14352
- isVpn: false,
14353
- isProxy: false,
14354
- isThreat: false,
14355
- securityScore: 50,
14356
- riskLevel: "Unknown",
15811
+ ...noRiskData(),
14357
15812
  _status: reason,
14358
15813
  _source: source,
14359
15814
  _reason: detail
@@ -14376,6 +15831,21 @@ var require_geolocation = __commonJS({
14376
15831
  var require_notifications = __commonJS({
14377
15832
  "server/src/services/notifications.js"(exports, module) {
14378
15833
  "use strict";
15834
+ var { hasRiskData } = require_risk_data();
15835
+ function getRiskWarnings(geoData) {
15836
+ if (!hasRiskData(geoData)) return [];
15837
+ const warnings = [];
15838
+ if (geoData.isVpn) warnings.push("VPN");
15839
+ if (geoData.isProxy) warnings.push("Proxy");
15840
+ if (geoData.isTor) warnings.push("Tor");
15841
+ if (geoData.isHosting) {
15842
+ warnings.push(
15843
+ geoData.riskSource === "asn-heuristic" ? "Hosting (ASN heuristic)" : "Hosting provider"
15844
+ );
15845
+ }
15846
+ if (geoData.isThreat) warnings.push("Threat");
15847
+ return warnings;
15848
+ }
14379
15849
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
14380
15850
  var WEBHOOK_TIMEOUT_MS = 5e3;
14381
15851
  module.exports = ({ strapi: strapi2 }) => ({
@@ -14521,9 +15991,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
14521
15991
  result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
14522
15992
  result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
14523
15993
  result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
15994
+ const score = data.reason?.securityScore;
14524
15995
  result = result.replace(
14525
15996
  /\{\{reason\.securityScore\}\}/g,
14526
- esc(String(data.reason?.securityScore || "0"))
15997
+ esc(typeof score === "number" && Number.isFinite(score) ? String(score) : "N/A")
14527
15998
  );
14528
15999
  return result;
14529
16000
  },
@@ -14704,11 +16175,8 @@ ${session.loginTime ? new Date(session.loginTime).toLocaleString() : "-"}`
14704
16175
  text: `*Location*
14705
16176
  ${locationFlag}${geoData.city || "?"}, ${geoData.country || "?"}`
14706
16177
  });
14707
- if (geoData.isVpn || geoData.isProxy || geoData.isThreat) {
14708
- const warnings = [];
14709
- if (geoData.isVpn) warnings.push("VPN");
14710
- if (geoData.isProxy) warnings.push("Proxy");
14711
- if (geoData.isThreat) warnings.push("Threat");
16178
+ const warnings = getRiskWarnings(geoData);
16179
+ if (warnings.length > 0) {
14712
16180
  fields.push({
14713
16181
  type: "mrkdwn",
14714
16182
  text: `*Security*
@@ -14777,11 +16245,8 @@ ${user.username || "N/A"}`, inline: true },
14777
16245
  value: `${geoData.country_flag || ""} ${geoData.city}, ${geoData.country}`,
14778
16246
  inline: true
14779
16247
  });
14780
- if (geoData.isVpn || geoData.isProxy || geoData.isThreat) {
14781
- const warnings = [];
14782
- if (geoData.isVpn) warnings.push("VPN");
14783
- if (geoData.isProxy) warnings.push("Proxy");
14784
- if (geoData.isThreat) warnings.push("Threat");
16248
+ const warnings = getRiskWarnings(geoData);
16249
+ if (warnings.length > 0) {
14785
16250
  embed.fields.push({
14786
16251
  name: "[WARNING] Security",
14787
16252
  value: `${warnings.join(", ")} detected
@@ -14826,6 +16291,740 @@ Score: ${geoData.securityScore}/100`,
14826
16291
  }
14827
16292
  });
14828
16293
 
16294
+ // server/src/services/security-log.js
16295
+ var require_security_log = __commonJS({
16296
+ "server/src/services/security-log.js"(exports, module) {
16297
+ "use strict";
16298
+ var {
16299
+ ACTOR_TYPES,
16300
+ ADMIN_CONTENT_EVENTS,
16301
+ CONTENT_ACTIONS,
16302
+ EVENT_NAME_PATTERN,
16303
+ SECURITY_EVENTS,
16304
+ SIGN_IN_FILTERS,
16305
+ boundMeta,
16306
+ contentEvent,
16307
+ deriveSessionStates,
16308
+ pickEntryTitle,
16309
+ recordingSwitchOf,
16310
+ safeReason,
16311
+ toIso,
16312
+ toLocation,
16313
+ toObject
16314
+ } = require_security_log_model();
16315
+ var {
16316
+ anonymizeIp,
16317
+ describeUserAgent,
16318
+ hashDeviceId,
16319
+ normalizeIp
16320
+ } = require_admin_request_info();
16321
+ var { resolveSecurityLogSettings } = require_security_log_settings();
16322
+ var { getPluginSettings } = require_settings_loader();
16323
+ var { shouldResolveGeoData } = require_enhance_session();
16324
+ var { createLogger } = require_logger();
16325
+ var EVENT_UID = "plugin::magic-sessionmanager.security-event";
16326
+ var ADMIN_USER_UID = "admin::user";
16327
+ var ADMIN_SESSION_UID = "admin::session";
16328
+ var PERMISSION_UID = "admin::permission";
16329
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
16330
+ var FLUSH_DELAY_MS = 1e3;
16331
+ var FLUSH_BATCH = 200;
16332
+ var MAX_QUEUE = 2e3;
16333
+ var VIEW_DEDUP_MS = 10 * 60 * 1e3;
16334
+ var LOCKOUT_DEDUP_MS = 5 * 60 * 1e3;
16335
+ var MAX_DEDUP_KEYS = 2e4;
16336
+ var GEO_LOOKUPS_PER_FLUSH = 20;
16337
+ var MAIN_FIELD_TTL_MS = 5 * 60 * 1e3;
16338
+ var EXPORT_BATCH = 500;
16339
+ var DELETE_BATCH = 1e3;
16340
+ var MAX_DELETE_STEPS = 200;
16341
+ function toId(value) {
16342
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
16343
+ if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
16344
+ return null;
16345
+ }
16346
+ function toAdminId(value) {
16347
+ const id = Number(value);
16348
+ return Number.isInteger(id) && id > 0 && id < 1e12 ? id : null;
16349
+ }
16350
+ function adminName(user) {
16351
+ if (!user) return "";
16352
+ const name = [user.firstname, user.lastname].filter((part) => typeof part === "string" && part.trim()).join(" ").trim();
16353
+ return (name || user.username || user.email || "").slice(0, 200);
16354
+ }
16355
+ function pruneDedup(map, now, windowMs) {
16356
+ if (map.size <= MAX_DEDUP_KEYS) return;
16357
+ for (const [key, at] of map) if (now - at >= windowMs) map.delete(key);
16358
+ while (map.size > MAX_DEDUP_KEYS) {
16359
+ const first = map.keys().next().value;
16360
+ if (first === void 0) break;
16361
+ map.delete(first);
16362
+ }
16363
+ }
16364
+ function deviceHashOf(meta) {
16365
+ const value = toObject(meta).deviceHash;
16366
+ return typeof value === "string" ? value : null;
16367
+ }
16368
+ module.exports = ({ strapi: strapi2 }) => {
16369
+ const log = createLogger(strapi2);
16370
+ let queue = [];
16371
+ let timer = null;
16372
+ let flushing = null;
16373
+ let stopped = false;
16374
+ let dropped = 0;
16375
+ const viewed = /* @__PURE__ */ new Map();
16376
+ const lockouts = /* @__PURE__ */ new Map();
16377
+ const mainFields = /* @__PURE__ */ new Map();
16378
+ const events = () => strapi2.db.query(EVENT_UID);
16379
+ const schedule = () => {
16380
+ if (timer || stopped) return;
16381
+ timer = setTimeout(() => {
16382
+ timer = null;
16383
+ service.flush().catch(() => {
16384
+ });
16385
+ }, FLUSH_DELAY_MS);
16386
+ if (typeof timer.unref === "function") timer.unref();
16387
+ };
16388
+ const mainFieldOf = async (uid) => {
16389
+ const now = Date.now();
16390
+ const cachedField = mainFields.get(uid);
16391
+ if (cachedField && now - cachedField.at < MAIN_FIELD_TTL_MS) return cachedField.field;
16392
+ let field;
16393
+ try {
16394
+ const contentTypes = strapi2.plugin("content-manager")?.service("content-types");
16395
+ const configuration = contentTypes ? await contentTypes.findConfiguration({ uid }) : null;
16396
+ const configured = configuration?.settings?.mainField;
16397
+ field = typeof configured === "string" ? configured : null;
16398
+ } catch {
16399
+ field = null;
16400
+ }
16401
+ mainFields.set(uid, { field, at: now });
16402
+ return field;
16403
+ };
16404
+ const loadAdmins = async (ids) => {
16405
+ const unique = [...new Set(ids.map(toAdminId).filter((id) => id !== null))];
16406
+ if (!unique.length) return /* @__PURE__ */ new Map();
16407
+ const rows = await strapi2.db.query(ADMIN_USER_UID).findMany({
16408
+ where: { id: { $in: unique } },
16409
+ select: ["id", "firstname", "lastname", "username", "email"]
16410
+ });
16411
+ return new Map((Array.isArray(rows) ? rows : []).map((row) => [Number(row.id), row]));
16412
+ };
16413
+ const titleFromLog = async (targetType, targetId) => {
16414
+ const rows = await events().findMany({
16415
+ select: ["meta"],
16416
+ where: { targetType, targetId, event: { $startsWith: "admin.content." } },
16417
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16418
+ limit: 10
16419
+ });
16420
+ for (const row of Array.isArray(rows) ? rows : []) {
16421
+ const title = toObject(row.meta).title;
16422
+ if (typeof title === "string" && title) return title;
16423
+ }
16424
+ return null;
16425
+ };
16426
+ const buildRows = async (batch, options, settings) => {
16427
+ const wanted = batch.filter((entry) => {
16428
+ const gate = recordingSwitchOf(entry.event);
16429
+ return gate === "always" || (gate === "signIns" ? options.signIns : options.content);
16430
+ });
16431
+ if (!wanted.length) return [];
16432
+ const emails = [
16433
+ ...new Set(
16434
+ wanted.map((entry) => typeof entry.attemptedEmail === "string" ? entry.attemptedEmail : "").filter((email) => email && email.length <= 254).map((email) => email.toLowerCase())
16435
+ )
16436
+ ];
16437
+ const byEmail = /* @__PURE__ */ new Map();
16438
+ if (emails.length) {
16439
+ const found = await strapi2.db.query(ADMIN_USER_UID).findMany({
16440
+ where: { email: { $in: emails } },
16441
+ select: ["id", "email"]
16442
+ });
16443
+ for (const row of Array.isArray(found) ? found : []) {
16444
+ byEmail.set(String(row.email).toLowerCase(), Number(row.id));
16445
+ }
16446
+ }
16447
+ const geoService = options.storeIp && shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null;
16448
+ const geoCache = /* @__PURE__ */ new Map();
16449
+ let geoBudget = GEO_LOOKUPS_PER_FLUSH;
16450
+ const knownTitles = /* @__PURE__ */ new Map();
16451
+ for (const entry of wanted) {
16452
+ const title = entry.entryData && entry.targetType && entry.targetId ? pickEntryTitle(entry.entryData, await mainFieldOf(entry.targetType)) : null;
16453
+ if (title) knownTitles.set(`${entry.targetType}|${toId(entry.targetId)}`, title);
16454
+ }
16455
+ const rows = [];
16456
+ for (const entry of wanted) {
16457
+ const ip = options.storeIp ? normalizeIp(entry.ip) : null;
16458
+ const storedIp = ip && options.anonymizeIp ? anonymizeIp(ip) : ip;
16459
+ let geo = null;
16460
+ if (storedIp && geoService) {
16461
+ if (geoCache.has(storedIp)) {
16462
+ geo = geoCache.get(storedIp) || null;
16463
+ } else if (geoBudget > 0) {
16464
+ geoBudget -= 1;
16465
+ try {
16466
+ const info = await geoService.getIpInfo(storedIp);
16467
+ geo = info && info._status === "ok" ? {
16468
+ country: info.country || null,
16469
+ country_code: info.country_code || null,
16470
+ city: info.city || null
16471
+ } : null;
16472
+ } catch {
16473
+ geo = null;
16474
+ }
16475
+ geoCache.set(storedIp, geo);
16476
+ }
16477
+ }
16478
+ let targetId = toId(entry.targetId);
16479
+ let actorId = toId(entry.actorId);
16480
+ if (!targetId && typeof entry.attemptedEmail === "string") {
16481
+ const found = byEmail.get(entry.attemptedEmail.toLowerCase());
16482
+ targetId = found ? String(found) : null;
16483
+ if (entry.actorFromEmail && !actorId) actorId = targetId;
16484
+ }
16485
+ const meta = { ...entry.meta || {} };
16486
+ const deviceHash = entry.deviceHash || hashDeviceId(entry.deviceId);
16487
+ if (deviceHash) meta.deviceHash = deviceHash;
16488
+ if (storedIp && options.anonymizeIp) meta.ipAnonymized = true;
16489
+ if (entry.entryData && entry.targetType) {
16490
+ const title = pickEntryTitle(entry.entryData, await mainFieldOf(entry.targetType));
16491
+ if (title) meta.title = title;
16492
+ }
16493
+ if (!meta.title && entry.event.startsWith("admin.content.") && entry.targetType) {
16494
+ const id = toId(entry.targetId);
16495
+ if (id) {
16496
+ const key = `${entry.targetType}|${id}`;
16497
+ if (!knownTitles.has(key)) knownTitles.set(key, await titleFromLog(entry.targetType, id));
16498
+ const known = knownTitles.get(key);
16499
+ if (known) meta.title = known;
16500
+ }
16501
+ }
16502
+ const occurredAt = entry.occurredAt || /* @__PURE__ */ new Date();
16503
+ rows.push({
16504
+ event: entry.event,
16505
+ actorType: entry.actorType,
16506
+ actorId,
16507
+ targetType: typeof entry.targetType === "string" ? entry.targetType.slice(0, 191) : null,
16508
+ targetId,
16509
+ ip: storedIp,
16510
+ userAgent: typeof entry.userAgent === "string" && entry.userAgent ? entry.userAgent.slice(0, 500) : null,
16511
+ geo,
16512
+ meta: boundMeta(meta),
16513
+ createdAt: occurredAt,
16514
+ updatedAt: occurredAt
16515
+ });
16516
+ }
16517
+ return rows;
16518
+ };
16519
+ const deleteOlderThan = async (cutoff) => {
16520
+ let deleted = 0;
16521
+ for (let step = 0; step < MAX_DELETE_STEPS; step += 1) {
16522
+ const rows = await events().findMany({
16523
+ select: ["id"],
16524
+ where: { createdAt: { $lt: cutoff } },
16525
+ orderBy: { id: "asc" },
16526
+ limit: DELETE_BATCH
16527
+ });
16528
+ const ids = (Array.isArray(rows) ? rows : []).map((row) => row.id);
16529
+ if (!ids.length) break;
16530
+ const result = await events().deleteMany({ where: { id: { $in: ids } } });
16531
+ deleted += Number(result?.count ?? ids.length);
16532
+ if (ids.length < DELETE_BATCH) break;
16533
+ }
16534
+ return deleted;
16535
+ };
16536
+ const writeQueued = async () => {
16537
+ while (queue.length) {
16538
+ const batch = queue;
16539
+ queue = [];
16540
+ let settings;
16541
+ try {
16542
+ settings = await getPluginSettings(strapi2);
16543
+ } catch {
16544
+ return;
16545
+ }
16546
+ try {
16547
+ const rows = await buildRows(batch, resolveSecurityLogSettings(settings), settings);
16548
+ for (let i = 0; i < rows.length; i += FLUSH_BATCH) {
16549
+ await events().createMany({ data: rows.slice(i, i + FLUSH_BATCH) });
16550
+ }
16551
+ } catch (err) {
16552
+ log.warn("[security-log] Events could not be written:", err?.name || "Error");
16553
+ }
16554
+ }
16555
+ if (dropped > 0) {
16556
+ log.warn(`[security-log] ${dropped} queued events were dropped (queue full)`);
16557
+ dropped = 0;
16558
+ }
16559
+ };
16560
+ const service = {
16561
+ /**
16562
+ * Queues one security event. Returns at once; nothing is awaited.
16563
+ * Unknown event names or actor types are ignored.
16564
+ *
16565
+ * @param {SecurityEventInput} input Event.
16566
+ * @returns {boolean} Whether the event was queued.
16567
+ * @sideeffect Adds to the in-memory queue; the flush stores it when its switch is on.
16568
+ */
16569
+ record(input) {
16570
+ if (stopped || !input || typeof input.event !== "string") return false;
16571
+ if (!EVENT_NAME_PATTERN.test(input.event) || !ACTOR_TYPES.includes(input.actorType)) {
16572
+ return false;
16573
+ }
16574
+ const now = Date.now();
16575
+ if (input.event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
16576
+ const who = String(input.attemptedEmail || input.targetId || "").toLowerCase();
16577
+ const key = `${who}|${input.ip || ""}`;
16578
+ const last = lockouts.get(key);
16579
+ if (last !== void 0 && now - last < LOCKOUT_DEDUP_MS) return false;
16580
+ lockouts.set(key, now);
16581
+ pruneDedup(lockouts, now, LOCKOUT_DEDUP_MS);
16582
+ }
16583
+ queue.push({ ...input, occurredAt: input.occurredAt || new Date(now) });
16584
+ if (queue.length > MAX_QUEUE) {
16585
+ dropped += queue.length - MAX_QUEUE;
16586
+ queue = queue.slice(queue.length - MAX_QUEUE);
16587
+ }
16588
+ schedule();
16589
+ return true;
16590
+ },
16591
+ /**
16592
+ * Queues one Content Manager action of an admin as
16593
+ * `admin.content.<action>` with the entry as target (`targetType` = content
16594
+ * type uid, `targetId` = document id). Opening the same entry (same
16595
+ * admin, type, document and locale) again within 10 minutes, or right
16596
+ * after writing it, is not a new "view".
16597
+ *
16598
+ * @param {{adminUserId: number|string, action: string, kind: 'collection'|'single',
16599
+ * contentType: string, documentId: string|null, locale: string|null,
16600
+ * count: number|null, data?: any}} input Action.
16601
+ * @returns {boolean} Whether the action was queued.
16602
+ */
16603
+ recordContentAction(input) {
16604
+ if (stopped || !input || !CONTENT_ACTIONS.includes(input.action)) return false;
16605
+ const now = Date.now();
16606
+ const key = `${input.adminUserId}|${input.contentType}|${input.documentId || ""}|${input.locale || ""}`;
16607
+ if (input.documentId || input.kind === "single") {
16608
+ if (input.action === "view") {
16609
+ const last = viewed.get(key);
16610
+ if (last !== void 0 && now - last < VIEW_DEDUP_MS) return false;
16611
+ }
16612
+ viewed.delete(key);
16613
+ viewed.set(key, now);
16614
+ pruneDedup(viewed, now, VIEW_DEDUP_MS);
16615
+ }
16616
+ return service.record({
16617
+ event: contentEvent(input.action),
16618
+ actorType: "admin",
16619
+ actorId: input.adminUserId,
16620
+ targetType: input.contentType,
16621
+ targetId: input.documentId,
16622
+ meta: {
16623
+ kind: input.kind,
16624
+ locale: input.locale || null,
16625
+ ...typeof input.count === "number" ? { count: input.count } : {}
16626
+ },
16627
+ entryData: input.data || null
16628
+ });
16629
+ },
16630
+ /**
16631
+ * Writes everything queued. Concurrent calls share one run.
16632
+ *
16633
+ * @returns {Promise<void>}
16634
+ * @sideeffect Inserts rows into the security event table; may call the GeoIP provider.
16635
+ */
16636
+ async flush() {
16637
+ if (flushing) return flushing;
16638
+ if (!queue.length) return void 0;
16639
+ flushing = writeQueued().finally(() => {
16640
+ flushing = null;
16641
+ });
16642
+ return flushing;
16643
+ },
16644
+ /**
16645
+ * Stops recording and writes what is queued (plugin destroy).
16646
+ *
16647
+ * @returns {Promise<void>}
16648
+ */
16649
+ async stop() {
16650
+ stopped = true;
16651
+ if (timer) clearTimeout(timer);
16652
+ timer = null;
16653
+ await service.flush().catch(() => {
16654
+ });
16655
+ },
16656
+ /** @returns {boolean} Whether recording was stopped. */
16657
+ isStopped() {
16658
+ return stopped;
16659
+ },
16660
+ /**
16661
+ * One page of the admin sign-in history, newest first, with names of the
16662
+ * admins involved and the session state of each sign-in.
16663
+ *
16664
+ * @param {{adminId?: number, event?: keyof typeof SIGN_IN_FILTERS, from?: Date|null,
16665
+ * to?: Date|null, page: number, pageSize: number}} query Parsed filters.
16666
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
16667
+ */
16668
+ async listSignIns(query) {
16669
+ const where = signInWhere(query);
16670
+ const [total, rows] = await Promise.all([
16671
+ events().count({ where }),
16672
+ events().findMany({
16673
+ where,
16674
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16675
+ offset: (query.page - 1) * query.pageSize,
16676
+ limit: query.pageSize
16677
+ })
16678
+ ]);
16679
+ return {
16680
+ data: await shapeSignIns(Array.isArray(rows) ? rows : []),
16681
+ meta: {
16682
+ pagination: paginationOf(query, total),
16683
+ recording: await recordingFlags()
16684
+ }
16685
+ };
16686
+ },
16687
+ /**
16688
+ * One page of Content Manager activity, newest first.
16689
+ *
16690
+ * @param {{adminId?: number, action?: string, contentType?: string, from?: Date|null,
16691
+ * to?: Date|null, page: number, pageSize: number}} query Parsed filters.
16692
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
16693
+ */
16694
+ async listContentActivity(query) {
16695
+ const where = activityWhere(query);
16696
+ const [total, rows] = await Promise.all([
16697
+ events().count({ where }),
16698
+ events().findMany({
16699
+ where,
16700
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16701
+ offset: (query.page - 1) * query.pageSize,
16702
+ limit: query.pageSize
16703
+ })
16704
+ ]);
16705
+ return {
16706
+ data: await shapeActivity(Array.isArray(rows) ? rows : []),
16707
+ meta: {
16708
+ pagination: paginationOf(query, total),
16709
+ recording: await recordingFlags(),
16710
+ contentTypes: listContentTypes(),
16711
+ ...query.adminId ? { contentManagerAccess: await service.hasContentManagerAccess(query.adminId) } : {}
16712
+ }
16713
+ };
16714
+ },
16715
+ /**
16716
+ * One export batch (newest first, keyset on id) of either list.
16717
+ *
16718
+ * @param {'sign-ins'|'content'} kind List.
16719
+ * @param {any} query Parsed filters (as for the list).
16720
+ * @param {number|null} cursor Id below which to continue.
16721
+ * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
16722
+ */
16723
+ async exportBatch(kind, query, cursor) {
16724
+ const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
16725
+ const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
16726
+ const rows = await events().findMany({
16727
+ where,
16728
+ orderBy: [{ id: "desc" }],
16729
+ limit: EXPORT_BATCH
16730
+ });
16731
+ const list = Array.isArray(rows) ? rows : [];
16732
+ const data = kind === "sign-ins" ? await shapeSignIns(list) : await shapeActivity(list);
16733
+ const last = list[list.length - 1];
16734
+ return {
16735
+ data,
16736
+ meta: { nextCursor: list.length === EXPORT_BATCH && last ? String(last.id) : null }
16737
+ };
16738
+ },
16739
+ /**
16740
+ * Whether an admin can use the Content Manager: Super Admin, or a role
16741
+ * with any `plugin::content-manager.explorer.*` permission.
16742
+ *
16743
+ * @param {number} adminId Admin id.
16744
+ * @returns {Promise<boolean|null>} Null when the admin does not exist.
16745
+ */
16746
+ async hasContentManagerAccess(adminId) {
16747
+ const user = await strapi2.db.query(ADMIN_USER_UID).findOne({
16748
+ where: { id: adminId },
16749
+ select: ["id"],
16750
+ populate: { roles: { select: ["id", "code"] } }
16751
+ });
16752
+ if (!user) return null;
16753
+ const roles = Array.isArray(user.roles) ? user.roles : [];
16754
+ if (roles.some((role) => role?.code === SUPER_ADMIN_CODE)) return true;
16755
+ const roleIds = roles.map((role) => role.id).filter((id) => id !== void 0);
16756
+ if (!roleIds.length) return false;
16757
+ const count = await strapi2.db.query(PERMISSION_UID).count({
16758
+ where: {
16759
+ role: { id: { $in: roleIds } },
16760
+ action: { $startsWith: "plugin::content-manager.explorer." }
16761
+ }
16762
+ });
16763
+ return Number(count) > 0;
16764
+ },
16765
+ /**
16766
+ * Retention for the whole log: deletes events older than the configured
16767
+ * number of days, and the events of admins that no longer exist (where a
16768
+ * deleted admin signed someone else out, only the actor is cleared).
16769
+ *
16770
+ * @param {{now?: Date}} [options] Clock for tests.
16771
+ * @returns {Promise<{expired: number, orphans: number}>} Deleted rows.
16772
+ * @sideeffect Deletes and updates rows of the security event table.
16773
+ */
16774
+ async cleanup({ now = /* @__PURE__ */ new Date() } = {}) {
16775
+ const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
16776
+ const cutoff = new Date(now.getTime() - options.retentionDays * 24 * 60 * 60 * 1e3);
16777
+ const expired = await deleteOlderThan(cutoff);
16778
+ const admins = await strapi2.db.query(ADMIN_USER_UID).findMany({ select: ["id"] });
16779
+ const existing = (Array.isArray(admins) ? admins : []).map((row) => String(row.id));
16780
+ let orphans = 0;
16781
+ if (existing.length) {
16782
+ const removed = await events().deleteMany({
16783
+ where: {
16784
+ $or: [
16785
+ { targetType: "admin", targetId: { $notNull: true, $notIn: existing } },
16786
+ {
16787
+ actorType: "admin",
16788
+ actorId: { $notNull: true, $notIn: existing },
16789
+ event: { $ne: SECURITY_EVENTS.ADMIN_SESSION_REVOKED }
16790
+ }
16791
+ ]
16792
+ }
16793
+ });
16794
+ orphans = Number(removed?.count || 0);
16795
+ await events().updateMany({
16796
+ where: {
16797
+ event: SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
16798
+ actorType: "admin",
16799
+ actorId: { $notNull: true, $notIn: existing }
16800
+ },
16801
+ data: { actorId: null }
16802
+ });
16803
+ }
16804
+ return { expired, orphans };
16805
+ },
16806
+ /**
16807
+ * Deletes what was recorded about an admin whose account was deleted:
16808
+ * events they did and events about their account. Where they signed
16809
+ * someone else out, the actor reference is cleared and the target keeps
16810
+ * the event.
16811
+ *
16812
+ * @param {number} adminId Deleted admin id.
16813
+ * @returns {Promise<void>}
16814
+ * @sideeffect Deletes and updates rows of the security event table.
16815
+ */
16816
+ async deleteAdminData(adminId) {
16817
+ const id = toAdminId(adminId);
16818
+ if (!id) return;
16819
+ const key = String(id);
16820
+ queue = queue.filter(
16821
+ (entry) => !(entry.actorType === "admin" && String(entry.actorId) === key) && !(entry.targetType === "admin" && String(entry.targetId) === key)
16822
+ );
16823
+ await events().deleteMany({
16824
+ where: {
16825
+ $or: [
16826
+ { targetType: "admin", targetId: key },
16827
+ {
16828
+ actorType: "admin",
16829
+ actorId: key,
16830
+ event: { $ne: SECURITY_EVENTS.ADMIN_SESSION_REVOKED }
16831
+ }
16832
+ ]
16833
+ }
16834
+ });
16835
+ await events().updateMany({
16836
+ where: { event: SECURITY_EVENTS.ADMIN_SESSION_REVOKED, actorType: "admin", actorId: key },
16837
+ data: { actorId: null }
16838
+ });
16839
+ }
16840
+ };
16841
+ function paginationOf(query, total) {
16842
+ const count = Number(total) || 0;
16843
+ return {
16844
+ page: query.page,
16845
+ pageSize: query.pageSize,
16846
+ total: count,
16847
+ pageCount: Math.max(1, Math.ceil(count / query.pageSize))
16848
+ };
16849
+ }
16850
+ function signInWhere(query) {
16851
+ const conditions = [{ event: { $in: [...SIGN_IN_FILTERS[query.event || "all"]] } }];
16852
+ if (query.adminId) conditions.push({ targetType: "admin", targetId: String(query.adminId) });
16853
+ if (query.from) conditions.push({ createdAt: { $gte: query.from } });
16854
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
16855
+ return { $and: conditions };
16856
+ }
16857
+ function activityWhere(query) {
16858
+ const conditions = [
16859
+ {
16860
+ event: query.action && query.action !== "all" ? contentEvent(query.action) : { $in: [...ADMIN_CONTENT_EVENTS] }
16861
+ }
16862
+ ];
16863
+ if (query.adminId) conditions.push({ actorType: "admin", actorId: String(query.adminId) });
16864
+ if (query.contentType) conditions.push({ targetType: query.contentType });
16865
+ if (query.from) conditions.push({ createdAt: { $gte: query.from } });
16866
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
16867
+ return { $and: conditions };
16868
+ }
16869
+ async function recordingFlags() {
16870
+ let settings;
16871
+ try {
16872
+ settings = await getPluginSettings(strapi2);
16873
+ } catch {
16874
+ settings = {};
16875
+ }
16876
+ const options = resolveSecurityLogSettings(settings);
16877
+ return {
16878
+ signIns: options.signIns,
16879
+ contentActivity: options.content,
16880
+ ipAddresses: options.storeIp,
16881
+ anonymizeIp: options.anonymizeIp,
16882
+ retentionDays: options.retentionDays
16883
+ };
16884
+ }
16885
+ function listContentTypes() {
16886
+ return Object.entries(strapi2.contentTypes || {}).filter(([uid, type]) => {
16887
+ const visible = (
16888
+ /** @type {any} */
16889
+ type?.pluginOptions?.["content-manager"]?.visible
16890
+ );
16891
+ return uid.startsWith("api::") && visible !== false;
16892
+ }).map(([uid, type]) => ({
16893
+ uid,
16894
+ name: String(
16895
+ /** @type {any} */
16896
+ type?.info?.displayName || uid
16897
+ ).slice(0, 120),
16898
+ kind: (
16899
+ /** @type {any} */
16900
+ type?.kind === "singleType" ? "single" : "collection"
16901
+ )
16902
+ })).sort((a, b) => a.name.localeCompare(b.name));
16903
+ }
16904
+ async function shapeSignIns(rows) {
16905
+ const admins = await loadAdmins(rows.flatMap((row) => [row.targetId, row.actorId]));
16906
+ const states = await sessionStates(rows);
16907
+ return rows.map((row) => {
16908
+ const meta = toObject(row.meta);
16909
+ const admin = row.targetType === "admin" ? admins.get(Number(row.targetId)) : void 0;
16910
+ const revoked = row.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
16911
+ const actor = revoked ? admins.get(Number(row.actorId)) : void 0;
16912
+ const described = describeUserAgent(row.userAgent || null);
16913
+ const state = states.get(Number(row.id));
16914
+ return {
16915
+ id: Number(row.id),
16916
+ event: row.event,
16917
+ reason: safeReason(meta.reason),
16918
+ provider: safeReason(meta.provider),
16919
+ scope: revoked ? safeReason(meta.scope) : null,
16920
+ at: toIso(row.createdAt),
16921
+ ipAddress: row.ip || null,
16922
+ ipAnonymized: meta.ipAnonymized === true,
16923
+ location: toLocation(row.geo),
16924
+ browser: described.browserName,
16925
+ os: described.osName,
16926
+ deviceType: described.deviceType,
16927
+ admin: admin ? { id: Number(admin.id), name: adminName(admin) } : null,
16928
+ actor: actor ? { id: Number(actor.id), name: adminName(actor) } : null,
16929
+ session: row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && state ? { state: state.state, endedAt: toIso(state.endedAt) } : null
16930
+ };
16931
+ });
16932
+ }
16933
+ async function sessionStates(rows) {
16934
+ const list = rows.filter(
16935
+ (row) => row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && toAdminId(row.targetId)
16936
+ );
16937
+ if (!list.length) return /* @__PURE__ */ new Map();
16938
+ const adminIds = [...new Set(list.map((row) => String(row.targetId)))];
16939
+ const oldest = new Date(
16940
+ Math.min(...list.map((row) => new Date(toIso(row.createdAt) || Date.now()).getTime()))
16941
+ );
16942
+ const later = await events().findMany({
16943
+ select: ["id", "event", "targetId", "actorId", "meta", "createdAt"],
16944
+ where: {
16945
+ targetType: "admin",
16946
+ targetId: { $in: adminIds },
16947
+ event: {
16948
+ $in: [
16949
+ SECURITY_EVENTS.ADMIN_SIGN_IN,
16950
+ SECURITY_EVENTS.ADMIN_SIGN_OUT,
16951
+ SECURITY_EVENTS.ADMIN_SESSION_REVOKED
16952
+ ]
16953
+ },
16954
+ createdAt: { $gte: oldest }
16955
+ },
16956
+ orderBy: [{ createdAt: "asc" }],
16957
+ limit: 5e3
16958
+ });
16959
+ const live = /* @__PURE__ */ new Map();
16960
+ if (strapi2.contentTypes?.[ADMIN_SESSION_UID]) {
16961
+ const now = /* @__PURE__ */ new Date();
16962
+ const sessions = await strapi2.db.query(ADMIN_SESSION_UID).findMany({
16963
+ select: ["userId", "deviceId"],
16964
+ where: {
16965
+ origin: "admin",
16966
+ status: "active",
16967
+ userId: { $in: adminIds },
16968
+ expiresAt: { $gt: now },
16969
+ $or: [{ absoluteExpiresAt: { $null: true } }, { absoluteExpiresAt: { $gt: now } }]
16970
+ },
16971
+ limit: 1e4
16972
+ });
16973
+ for (const session of Array.isArray(sessions) ? sessions : []) {
16974
+ const hash = hashDeviceId(session.deviceId);
16975
+ if (!hash) continue;
16976
+ const key = String(session.userId);
16977
+ if (!live.has(key)) live.set(key, /* @__PURE__ */ new Set());
16978
+ live.get(key)?.add(hash);
16979
+ }
16980
+ }
16981
+ const toEvent = (row) => ({
16982
+ id: Number(row.id),
16983
+ adminId: String(row.targetId),
16984
+ event: row.event,
16985
+ actorId: row.actorId ? String(row.actorId) : null,
16986
+ deviceHash: deviceHashOf(row.meta),
16987
+ at: toIso(row.createdAt) || ""
16988
+ });
16989
+ return deriveSessionStates(
16990
+ list.map(toEvent),
16991
+ (Array.isArray(later) ? later : []).map(toEvent),
16992
+ live
16993
+ );
16994
+ }
16995
+ async function shapeActivity(rows) {
16996
+ const admins = await loadAdmins(rows.map((row) => row.actorId));
16997
+ return rows.map((row) => {
16998
+ const meta = toObject(row.meta);
16999
+ const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
17000
+ const type = strapi2.contentTypes?.[row.targetType];
17001
+ return {
17002
+ id: Number(row.id),
17003
+ action: String(row.event).replace(/^admin\.content\./, ""),
17004
+ at: toIso(row.createdAt),
17005
+ contentType: {
17006
+ uid: row.targetType,
17007
+ name: String(type?.info?.displayName || row.targetType).slice(0, 120),
17008
+ kind: meta.kind === "single" ? "single" : "collection",
17009
+ exists: Boolean(type)
17010
+ },
17011
+ entry: {
17012
+ documentId: row.targetId || null,
17013
+ locale: typeof meta.locale === "string" ? meta.locale : null,
17014
+ title: typeof meta.title === "string" ? meta.title : null,
17015
+ count: typeof meta.count === "number" ? meta.count : null
17016
+ },
17017
+ admin: admin ? { id: Number(admin.id), name: adminName(admin) } : null
17018
+ };
17019
+ });
17020
+ }
17021
+ return service;
17022
+ };
17023
+ module.exports.EVENT_UID = EVENT_UID;
17024
+ module.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
17025
+ }
17026
+ });
17027
+
14829
17028
  // server/src/services/index.js
14830
17029
  var require_services = __commonJS({
14831
17030
  "server/src/services/index.js"(exports, module) {
@@ -14833,10 +17032,12 @@ var require_services = __commonJS({
14833
17032
  var session = require_session2();
14834
17033
  var geolocation = require_geolocation();
14835
17034
  var notifications = require_notifications();
17035
+ var securityLog = require_security_log();
14836
17036
  module.exports = {
14837
17037
  session,
14838
17038
  geolocation,
14839
- notifications
17039
+ notifications,
17040
+ "security-log": securityLog
14840
17041
  };
14841
17042
  }
14842
17043
  });