strapi-plugin-magic-sessionmanager 4.15.0 → 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 (27) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +91 -7
  3. package/dist/admin/{Analytics-HK6_TEmk.mjs → Analytics-D4gsVwL0.mjs} +1 -1
  4. package/dist/admin/{Analytics-Dbs5QXLb.js → Analytics-me4qzS0I.js} +1 -1
  5. package/dist/admin/{App-BOFzZ5d8.mjs → App-BJwtFWxl.mjs} +863 -81
  6. package/dist/admin/{App-7SxOBJP5.js → App-BTG-2Q26.js} +862 -80
  7. package/dist/admin/{OnlineUsersWidget-Dns_74xJ.js → OnlineUsersWidget-DYS3Vy1Q.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-CoCxnww-.mjs → OnlineUsersWidget-Yd283YDy.mjs} +1 -1
  9. package/dist/admin/{Settings-DYRShQ8W.mjs → Settings-DIlvfdjZ.mjs} +170 -19
  10. package/dist/admin/{Settings-B6CrR-07.js → Settings-TPZ9_75s.js} +169 -18
  11. package/dist/admin/{de-bkkCvSxX.js → de-BuMw1gBJ.js} +92 -2
  12. package/dist/admin/{de-B3mPtxsW.mjs → de-DB9ldYwN.mjs} +92 -2
  13. package/dist/admin/{en-BnU8BNkN.mjs → en-BbLMPQB3.mjs} +92 -2
  14. package/dist/admin/{en-DMICyIow.js → en-BqGhOJDy.js} +92 -2
  15. package/dist/admin/{es-OSzHGRIu.js → es-BaIeckl9.js} +92 -2
  16. package/dist/admin/{es-BxMgfJ1Y.mjs → es-C5iaiE9G.mjs} +92 -2
  17. package/dist/admin/{fr-WPrbtx8k.mjs → fr-BEvBUCwI.mjs} +92 -2
  18. package/dist/admin/{fr-Bu_8miJ4.js → fr-D1YKyTex.js} +92 -2
  19. package/dist/admin/{index-CNSJITRX.js → index-CgZiLcJ1.js} +13 -10
  20. package/dist/admin/{index-lnZBc5n0.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-C41KyEDN.mjs → pt-DeDih9cR.mjs} +92 -2
  24. package/dist/admin/{pt-B08xnb0K.js → pt-DtnW-s0V.js} +92 -2
  25. package/dist/server/index.js +1917 -103
  26. package/dist/server/index.mjs +1917 -103
  27. package/package.json +1 -1
@@ -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,
@@ -2451,6 +2477,800 @@ var require_native_only_insight = __commonJS({
2451
2477
  }
2452
2478
  });
2453
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
+
2454
3274
  // server/src/middlewares/session-rejection-headers.js
2455
3275
  var require_session_rejection_headers = __commonJS({
2456
3276
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -6574,6 +7394,7 @@ var require_bootstrap = __commonJS({
6574
7394
  isThenable
6575
7395
  } = require_native_session_capture();
6576
7396
  var { ensureNativeTrackingSince } = require_native_only_insight();
7397
+ var { installAdminActivityCapture } = require_admin_activity_capture();
6577
7398
  var SESSION_UID = "plugin::magic-sessionmanager.session";
6578
7399
  var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
6579
7400
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -6728,6 +7549,13 @@ var require_bootstrap = __commonJS({
6728
7549
  log.info("[SUCCESS] Session-rejection-headers middleware mounted");
6729
7550
  strapi2.server.use(require_last_seen()({ strapi: strapi2, sessionService }));
6730
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");
6731
7559
  const contentApiPermissionsReady = await ensureContentApiPermissions(strapi2, log);
6732
7560
  mountDeferredContentApiPermissionRetry({
6733
7561
  strapi: strapi2,
@@ -8180,6 +9008,14 @@ var require_destroy = __commonJS({
8180
9008
  }
8181
9009
  strapi2.sessionManagerUnsubscribers = [];
8182
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
+ }
8183
9019
  log.info("[SUCCESS] Plugin cleanup completed");
8184
9020
  };
8185
9021
  }
@@ -8441,18 +9277,110 @@ var require_schema2 = __commonJS({
8441
9277
  }
8442
9278
  });
8443
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
+
8444
9364
  // server/src/content-types/index.js
8445
9365
  var require_content_types = __commonJS({
8446
9366
  "server/src/content-types/index.js"(exports, module) {
8447
9367
  "use strict";
8448
9368
  var session = require_schema();
8449
9369
  var revokedToken = require_schema2();
9370
+ var securityEvent = require_schema3();
8450
9371
  module.exports = {
8451
9372
  session: {
8452
9373
  schema: session
8453
9374
  },
8454
9375
  "revoked-token": {
8455
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
8456
9384
  }
8457
9385
  };
8458
9386
  }
@@ -8562,6 +9490,7 @@ var require_admin = __commonJS({
8562
9490
  var PLUGIN_ACCESS_ACTION = "plugin::magic-sessionmanager.access";
8563
9491
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
8564
9492
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
9493
+ var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
8565
9494
  var adminPolicy = () => [
8566
9495
  "admin::isAuthenticatedAdmin",
8567
9496
  {
@@ -8774,6 +9703,47 @@ var require_admin = __commonJS({
8774
9703
  description: "Sign a Strapi admin out of every browser (admin)"
8775
9704
  }
8776
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]),
9713
+ middlewares: adminReadRateLimit(),
9714
+ description: "List the admin sign-in history (admin)"
9715
+ }
9716
+ },
9717
+ {
9718
+ method: "GET",
9719
+ path: "/admin-activity/sign-ins/export",
9720
+ handler: "admin-activity.exportSignIns",
9721
+ config: {
9722
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9723
+ middlewares: adminReadRateLimit(),
9724
+ description: "Get one export batch of the admin sign-in history (admin)"
9725
+ }
9726
+ },
9727
+ {
9728
+ method: "GET",
9729
+ path: "/admin-activity/content",
9730
+ handler: "admin-activity.listContentActivity",
9731
+ config: {
9732
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9733
+ middlewares: adminReadRateLimit(),
9734
+ description: "List Content Manager activity of admins (admin)"
9735
+ }
9736
+ },
9737
+ {
9738
+ method: "GET",
9739
+ path: "/admin-activity/content/export",
9740
+ handler: "admin-activity.exportContentActivity",
9741
+ config: {
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)"
9745
+ }
9746
+ },
8777
9747
  // ============================ GEOLOCATION ============================
8778
9748
  {
8779
9749
  method: "GET",
@@ -8862,103 +9832,6 @@ var require_routes = __commonJS({
8862
9832
  }
8863
9833
  });
8864
9834
 
8865
- // server/src/utils/user-agent-parser.js
8866
- var require_user_agent_parser = __commonJS({
8867
- "server/src/utils/user-agent-parser.js"(exports, module) {
8868
- "use strict";
8869
- function parseUserAgent(userAgent) {
8870
- if (!userAgent) {
8871
- return {
8872
- deviceType: "unknown",
8873
- browserName: "unknown",
8874
- browserVersion: null,
8875
- osName: "unknown",
8876
- osVersion: null
8877
- };
8878
- }
8879
- let deviceType = "desktop";
8880
- if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
8881
- deviceType = "tablet";
8882
- } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
8883
- deviceType = "mobile";
8884
- } else if (/android(?!.*mobile)/i.test(userAgent)) {
8885
- deviceType = "tablet";
8886
- } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
8887
- deviceType = "bot";
8888
- }
8889
- let browserName = "unknown";
8890
- let browserVersion = null;
8891
- if (/edg\//i.test(userAgent)) {
8892
- browserName = "Edge";
8893
- browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
8894
- } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
8895
- browserName = "Opera";
8896
- browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
8897
- } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
8898
- browserName = "Chrome";
8899
- browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
8900
- } else if (/firefox|fxios/i.test(userAgent)) {
8901
- browserName = "Firefox";
8902
- browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
8903
- } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
8904
- browserName = "Safari";
8905
- browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
8906
- } else if (/msie|trident/i.test(userAgent)) {
8907
- browserName = "Internet Explorer";
8908
- browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
8909
- }
8910
- let osName = "unknown";
8911
- let osVersion = null;
8912
- if (/windows nt/i.test(userAgent)) {
8913
- osName = "Windows";
8914
- const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
8915
- const winVersionMap = {
8916
- "10.0": "10/11",
8917
- 6.3: "8.1",
8918
- 6.2: "8",
8919
- 6.1: "7",
8920
- "6.0": "Vista",
8921
- 5.1: "XP"
8922
- };
8923
- osVersion = winVersionMap[winVersion] || winVersion;
8924
- } else if (/iphone|ipad|ipod/i.test(userAgent)) {
8925
- osName = "iOS";
8926
- osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8927
- } else if (/mac os x/i.test(userAgent)) {
8928
- osName = "macOS";
8929
- osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8930
- } else if (/android/i.test(userAgent)) {
8931
- osName = "Android";
8932
- osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
8933
- } else if (/linux/i.test(userAgent)) {
8934
- osName = "Linux";
8935
- } else if (/cros/i.test(userAgent)) {
8936
- osName = "Chrome OS";
8937
- }
8938
- return {
8939
- deviceType,
8940
- browserName,
8941
- browserVersion,
8942
- osName,
8943
- osVersion
8944
- };
8945
- }
8946
- function extractVersion(userAgent, regex) {
8947
- const match = userAgent.match(regex);
8948
- return match ? match[1] : null;
8949
- }
8950
- function getDeviceDescription(parsed) {
8951
- const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
8952
- const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
8953
- return `${browser} on ${os}`;
8954
- }
8955
- module.exports = {
8956
- parseUserAgent,
8957
- getDeviceDescription
8958
- };
8959
- }
8960
- });
8961
-
8962
9835
  // server/src/utils/enhance-session.js
8963
9836
  var require_enhance_session = __commonJS({
8964
9837
  "server/src/utils/enhance-session.js"(exports, module) {
@@ -11212,6 +12085,12 @@ var require_settings = __commonJS({
11212
12085
  var { LockTimeoutError } = require_coordination();
11213
12086
  var { resolveDatabaseTarget } = require_geoip_updater();
11214
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";
11215
12094
  var path = __require("node:path");
11216
12095
  var ALLOWED_WEBHOOK_DOMAINS = {
11217
12096
  discord: ["discord.com", "discordapp.com"],
@@ -11385,7 +12264,8 @@ var require_settings = __commonJS({
11385
12264
  slackWebhookUrl: "",
11386
12265
  strictSessionEnforcement: false,
11387
12266
  trustedProxies: false,
11388
- emailTemplates: DEFAULT_EMAIL_TEMPLATES
12267
+ emailTemplates: DEFAULT_EMAIL_TEMPLATES,
12268
+ ...SECURITY_LOG_DEFAULTS
11389
12269
  };
11390
12270
  function mergeSettingsWithDefaults(stored) {
11391
12271
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -11590,6 +12470,9 @@ var require_settings = __commonJS({
11590
12470
  next.emailTemplates = sanitizeEmailTemplates(mergedTemplates);
11591
12471
  }
11592
12472
  }
12473
+ const securityLog = validateSecurityLogSettings(body);
12474
+ errors.push(...securityLog.errors);
12475
+ Object.assign(next, securityLog.values);
11593
12476
  if (errors.length > 0) return { errors };
11594
12477
  const settings = {};
11595
12478
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -11617,6 +12500,13 @@ var require_settings = __commonJS({
11617
12500
  };
11618
12501
  return ctx.body;
11619
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
+ }
11620
12510
  module.exports = {
11621
12511
  /**
11622
12512
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -11655,6 +12545,9 @@ var require_settings = __commonJS({
11655
12545
  * Omitted fields keep their stored value. Invalid values are rejected with
11656
12546
  * a 400 whose `error.details.errors` names each field; nothing is clamped
11657
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.
11658
12551
  *
11659
12552
  * @route PUT /magic-sessionmanager/settings
11660
12553
  * @returns {Promise<void>}
@@ -11686,6 +12579,10 @@ var require_settings = __commonJS({
11686
12579
  };
11687
12580
  const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
11688
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 };
11689
12586
  await pluginStore.set({
11690
12587
  key: "settings",
11691
12588
  value: sanitizedSettings
@@ -11693,6 +12590,11 @@ var require_settings = __commonJS({
11693
12590
  const revision = await notifySettingsChanged(strapi);
11694
12591
  return { settings: sanitizedSettings, revision };
11695
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
+ }
11696
12598
  if (outcome.conflict) {
11697
12599
  return sendSettingsConflict(ctx, outcome.currentRevision);
11698
12600
  }
@@ -12184,6 +13086,9 @@ var require_admin_sessions = __commonJS({
12184
13086
  "server/src/utils/admin-sessions.js"(exports, module) {
12185
13087
  "use strict";
12186
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();
12187
13092
  var ADMIN_ORIGIN = "admin";
12188
13093
  var SESSION_UID = "admin::session";
12189
13094
  var ADMIN_USER_UID = "admin::user";
@@ -12385,6 +13290,18 @@ var require_admin_sessions = __commonJS({
12385
13290
  }
12386
13291
  return map;
12387
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
+ }
12388
13305
  async function listAdmins(strapi2, query, actor) {
12389
13306
  const policy = readSessionPolicy(strapi2);
12390
13307
  if (!getAdminSessionManager(strapi2)) {
@@ -12395,7 +13312,8 @@ var require_admin_sessions = __commonJS({
12395
13312
  pagination: { page: 1, pageSize: query.pageSize, total: 0, pageCount: 1 },
12396
13313
  stats: null,
12397
13314
  policy,
12398
- truncated: false
13315
+ truncated: false,
13316
+ recording: await readSignInRecording(strapi2)
12399
13317
  }
12400
13318
  };
12401
13319
  }
@@ -12476,7 +13394,8 @@ var require_admin_sessions = __commonJS({
12476
13394
  totalAdmins: Number(totalAdmins) || 0
12477
13395
  },
12478
13396
  policy,
12479
- truncated
13397
+ truncated,
13398
+ recording: await readSignInRecording(strapi2)
12480
13399
  }
12481
13400
  };
12482
13401
  }
@@ -12547,6 +13466,7 @@ var require_admin_sessions = __commonJS({
12547
13466
  const currentDeviceId = self ? await findCurrentDeviceId(strapi2, { userId, sessionId: actor.sessionId }) : null;
12548
13467
  let ended;
12549
13468
  let signedOutSelf;
13469
+ let endedDeviceId = null;
12550
13470
  if (sessionId) {
12551
13471
  const row = await strapi2.db.query(SESSION_UID).findOne({
12552
13472
  select: ["userId", "deviceId", "origin"],
@@ -12557,6 +13477,7 @@ var require_admin_sessions = __commonJS({
12557
13477
  }
12558
13478
  if (blockReason === "account-inactive") throw new AdminSignOutError(404, "Session not found");
12559
13479
  await manager.invalidateRefreshToken(userId, String(row.deviceId));
13480
+ endedDeviceId = String(row.deviceId);
12560
13481
  ended = 1;
12561
13482
  signedOutSelf = Boolean(currentDeviceId) && String(row.deviceId) === currentDeviceId;
12562
13483
  } else {
@@ -12569,6 +13490,18 @@ var require_admin_sessions = __commonJS({
12569
13490
  target.id
12570
13491
  )} scope=${scope} ended=${ended}`;
12571
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
+ }
12572
13505
  try {
12573
13506
  strapi2.eventHub?.emit?.("magic-sessionmanager.admin-sessions.signed-out", {
12574
13507
  actorId: Number(actor.id),
@@ -12769,6 +13702,149 @@ var require_admin_sessions2 = __commonJS({
12769
13702
  }
12770
13703
  });
12771
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
+
12772
13848
  // server/src/controllers/index.js
12773
13849
  var require_controllers = __commonJS({
12774
13850
  "server/src/controllers/index.js"(exports, module) {
@@ -12777,11 +13853,13 @@ var require_controllers = __commonJS({
12777
13853
  var settings = require_settings();
12778
13854
  var geoip = require_geoip();
12779
13855
  var adminSessions = require_admin_sessions2();
13856
+ var adminActivity = require_admin_activity();
12780
13857
  module.exports = {
12781
13858
  session,
12782
13859
  settings,
12783
13860
  geoip,
12784
- "admin-sessions": adminSessions
13861
+ "admin-sessions": adminSessions,
13862
+ "admin-activity": adminActivity
12785
13863
  };
12786
13864
  }
12787
13865
  });
@@ -15213,6 +16291,740 @@ Score: ${geoData.securityScore}/100`,
15213
16291
  }
15214
16292
  });
15215
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
+
15216
17028
  // server/src/services/index.js
15217
17029
  var require_services = __commonJS({
15218
17030
  "server/src/services/index.js"(exports, module) {
@@ -15220,10 +17032,12 @@ var require_services = __commonJS({
15220
17032
  var session = require_session2();
15221
17033
  var geolocation = require_geolocation();
15222
17034
  var notifications = require_notifications();
17035
+ var securityLog = require_security_log();
15223
17036
  module.exports = {
15224
17037
  session,
15225
17038
  geolocation,
15226
- notifications
17039
+ notifications,
17040
+ "security-log": securityLog
15227
17041
  };
15228
17042
  }
15229
17043
  });