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
@@ -936,6 +936,16 @@ var require_register = __commonJS({
936
936
  uid: "admin-sessions.revoke",
937
937
  subCategory: "Admin panel",
938
938
  pluginName: "magic-sessionmanager"
939
+ },
940
+ // Admin sign-in history and Content Manager activity (4.15): who signed
941
+ // in from where and what each admin did. Separate from reading the
942
+ // sessions, because it shows IP addresses and work activity.
943
+ {
944
+ section: "plugins",
945
+ displayName: "View admin activity",
946
+ uid: "admin-activity.read",
947
+ subCategory: "Admin panel",
948
+ pluginName: "magic-sessionmanager"
939
949
  }
940
950
  ]);
941
951
  try {
@@ -1229,6 +1239,7 @@ var require_settings_loader = __commonJS({
1229
1239
  var cachedAt = 0;
1230
1240
  var cachedRevision = null;
1231
1241
  var revisionCheckedAt = 0;
1242
+ var generation = 0;
1232
1243
  function toIntInRange(value, fallback, min, max) {
1233
1244
  const n = Number.parseInt(value, 10);
1234
1245
  if (!Number.isFinite(n)) return fallback;
@@ -1294,7 +1305,12 @@ var require_settings_loader = __commonJS({
1294
1305
  // Opt-in: use a single-statement SQL UPDATE in the cleanup job instead
1295
1306
  // of batching via the Document Service. Bypasses lifecycle hooks but
1296
1307
  // drains the backlog in one query on very large installations.
1297
- "cleanupUseDbDirect"
1308
+ "cleanupUseDbDirect",
1309
+ // Security event log (4.15).
1310
+ "adminSignInHistory",
1311
+ "adminContentActivity",
1312
+ "securityLogStoreIp",
1313
+ "securityLogAnonymizeIp"
1298
1314
  ];
1299
1315
  if (stored.sessionCreationGraceMs !== void 0) {
1300
1316
  out.sessionCreationGraceMs = getSessionCreationGraceMs(stored);
@@ -1335,6 +1351,9 @@ var require_settings_loader = __commonJS({
1335
1351
  if (stored.emailTemplates && typeof stored.emailTemplates === "object") {
1336
1352
  out.emailTemplates = stored.emailTemplates;
1337
1353
  }
1354
+ if (stored.securityLogRetentionDays !== void 0) {
1355
+ out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 1, 730);
1356
+ }
1338
1357
  if (stored.trustedProxies !== void 0) {
1339
1358
  out.trustedProxies = stored.trustedProxies;
1340
1359
  }
@@ -1354,6 +1373,7 @@ var require_settings_loader = __commonJS({
1354
1373
  }
1355
1374
  if (revision2 === cachedRevision) return cached;
1356
1375
  }
1376
+ const loadGeneration = generation;
1357
1377
  let revision;
1358
1378
  try {
1359
1379
  revision = await coordinator.getRevision(SETTINGS_REVISION);
@@ -1373,6 +1393,7 @@ var require_settings_loader = __commonJS({
1373
1393
  storedSettings = { strictSessionEnforcement: true, enableGeolocation: false };
1374
1394
  }
1375
1395
  const merged = { ...staticConfig, ...storedSettings };
1396
+ if (loadGeneration !== generation) return merged;
1376
1397
  cached = merged;
1377
1398
  cachedAt = now;
1378
1399
  cachedRevision = revision;
@@ -1383,7 +1404,11 @@ var require_settings_loader = __commonJS({
1383
1404
  if (cached) return cached;
1384
1405
  return strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
1385
1406
  }
1407
+ function peekCachedSettings() {
1408
+ return cached;
1409
+ }
1386
1410
  function invalidateSettingsCache() {
1411
+ generation += 1;
1387
1412
  cached = null;
1388
1413
  cachedAt = 0;
1389
1414
  cachedRevision = null;
@@ -1407,6 +1432,7 @@ var require_settings_loader = __commonJS({
1407
1432
  module2.exports = {
1408
1433
  getPluginSettings,
1409
1434
  getPluginSettingsSync,
1435
+ peekCachedSettings,
1410
1436
  invalidateSettingsCache,
1411
1437
  notifySettingsChanged,
1412
1438
  getSettingsRevision,
@@ -2445,6 +2471,800 @@ var require_native_only_insight = __commonJS({
2445
2471
  }
2446
2472
  });
2447
2473
 
2474
+ // server/src/utils/security-log-model.js
2475
+ var require_security_log_model = __commonJS({
2476
+ "server/src/utils/security-log-model.js"(exports2, module2) {
2477
+ "use strict";
2478
+ var SECURITY_EVENTS = Object.freeze({
2479
+ ADMIN_SIGN_IN: "admin.sign-in",
2480
+ ADMIN_SIGN_IN_FAILED: "admin.sign-in.failed",
2481
+ ADMIN_LOCKOUT: "admin.lockout",
2482
+ ADMIN_SIGN_OUT: "admin.sign-out",
2483
+ ADMIN_SESSION_REVOKED: "admin.session.revoked",
2484
+ ADMIN_CONTENT_VIEW: "admin.content.view",
2485
+ ADMIN_CONTENT_CREATE: "admin.content.create",
2486
+ ADMIN_CONTENT_UPDATE: "admin.content.update",
2487
+ ADMIN_CONTENT_PUBLISH: "admin.content.publish",
2488
+ ADMIN_CONTENT_UNPUBLISH: "admin.content.unpublish",
2489
+ ADMIN_CONTENT_DISCARD: "admin.content.discard",
2490
+ ADMIN_CONTENT_DELETE: "admin.content.delete",
2491
+ ADMIN_CONTENT_CLONE: "admin.content.clone"
2492
+ });
2493
+ var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
2494
+ var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
2495
+ var ADMIN_SIGN_IN_EVENTS = Object.freeze([
2496
+ SECURITY_EVENTS.ADMIN_SIGN_IN,
2497
+ SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
2498
+ SECURITY_EVENTS.ADMIN_LOCKOUT,
2499
+ SECURITY_EVENTS.ADMIN_SIGN_OUT,
2500
+ SECURITY_EVENTS.ADMIN_SESSION_REVOKED
2501
+ ]);
2502
+ var SIGN_IN_FILTERS = Object.freeze({
2503
+ all: ADMIN_SIGN_IN_EVENTS,
2504
+ succeeded: [SECURITY_EVENTS.ADMIN_SIGN_IN],
2505
+ failed: [SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED, SECURITY_EVENTS.ADMIN_LOCKOUT],
2506
+ "signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED]
2507
+ });
2508
+ var CONTENT_ACTIONS = Object.freeze([
2509
+ "view",
2510
+ "create",
2511
+ "update",
2512
+ "publish",
2513
+ "unpublish",
2514
+ "discard",
2515
+ "delete",
2516
+ "clone"
2517
+ ]);
2518
+ var contentEvent = (action) => `admin.content.${action}`;
2519
+ var ADMIN_CONTENT_EVENTS = Object.freeze(CONTENT_ACTIONS.map(contentEvent));
2520
+ function recordingSwitchOf(event) {
2521
+ if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
2522
+ if (event.startsWith("admin.content.")) return "content";
2523
+ return "always";
2524
+ }
2525
+ var CONTENT_MANAGER_HANDLERS = Object.freeze({
2526
+ "collection-types.findOne": { action: "view", kind: "collection" },
2527
+ "collection-types.create": { action: "create", kind: "collection" },
2528
+ "collection-types.update": { action: "update", kind: "collection" },
2529
+ "collection-types.clone": { action: "clone", kind: "collection" },
2530
+ "collection-types.autoClone": { action: "clone", kind: "collection" },
2531
+ "collection-types.publish": { action: "publish", kind: "collection" },
2532
+ "collection-types.unpublish": { action: "unpublish", kind: "collection" },
2533
+ "collection-types.discard": { action: "discard", kind: "collection" },
2534
+ "collection-types.delete": { action: "delete", kind: "collection" },
2535
+ "collection-types.bulkDelete": { action: "delete", kind: "collection", bulk: true },
2536
+ "collection-types.bulkPublish": { action: "publish", kind: "collection", bulk: true },
2537
+ "collection-types.bulkUnpublish": { action: "unpublish", kind: "collection", bulk: true },
2538
+ "single-types.find": { action: "view", kind: "single" },
2539
+ "single-types.createOrUpdate": { action: "update", kind: "single" },
2540
+ "single-types.delete": { action: "delete", kind: "single" },
2541
+ "single-types.publish": { action: "publish", kind: "single" },
2542
+ "single-types.unpublish": { action: "unpublish", kind: "single" },
2543
+ "single-types.discard": { action: "discard", kind: "single" }
2544
+ });
2545
+ var UID_PATTERN = /^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/;
2546
+ var LOCALE_PATTERN = /^[A-Za-z0-9-]{1,20}$/;
2547
+ var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
2548
+ var MAX_META_BYTES = 2048;
2549
+ var MAX_META_KEYS = 16;
2550
+ function boundMeta(meta) {
2551
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
2552
+ const out = {};
2553
+ let keys = 0;
2554
+ for (const [key, value] of Object.entries(meta)) {
2555
+ if (keys >= MAX_META_KEYS) break;
2556
+ if (!/^[a-zA-Z][a-zA-Z0-9]{0,39}$/.test(key)) continue;
2557
+ if (value === null || typeof value === "boolean") out[key] = value;
2558
+ else if (typeof value === "number" && Number.isFinite(value)) out[key] = value;
2559
+ else if (typeof value === "string") out[key] = value.slice(0, 255);
2560
+ else continue;
2561
+ keys += 1;
2562
+ }
2563
+ if (!keys) return null;
2564
+ while (JSON.stringify(out).length > MAX_META_BYTES) {
2565
+ const longest = Object.keys(out).reduce(
2566
+ (a, b) => String(out[a] ?? "").length >= String(out[b] ?? "").length ? a : b
2567
+ );
2568
+ delete out[longest];
2569
+ }
2570
+ return Object.keys(out).length ? out : null;
2571
+ }
2572
+ function handlerName(handler) {
2573
+ if (typeof handler !== "string") return null;
2574
+ const parts = handler.split(".");
2575
+ if (parts.length < 2) return null;
2576
+ const tail = parts.slice(-2).join(".");
2577
+ return tail.includes("::") ? tail.split("::").pop() || null : tail;
2578
+ }
2579
+ function shaped(value, pattern) {
2580
+ return typeof value === "string" && pattern.test(value) ? value : null;
2581
+ }
2582
+ function describeContentManagerRequest({
2583
+ status,
2584
+ route,
2585
+ params,
2586
+ query,
2587
+ requestBody,
2588
+ responseBody
2589
+ }) {
2590
+ if (!(status >= 200 && status < 300)) return null;
2591
+ if (route?.info?.pluginName !== "content-manager") return null;
2592
+ const name = handlerName(route.handler);
2593
+ const mapping = name ? (
2594
+ /** @type {any} */
2595
+ CONTENT_MANAGER_HANDLERS[name]
2596
+ ) : null;
2597
+ if (!mapping) return null;
2598
+ const contentType = shaped(params?.model, UID_PATTERN);
2599
+ if (!contentType) return null;
2600
+ const data = responseBody && typeof responseBody === "object" && !Array.isArray(responseBody) ? responseBody.data : null;
2601
+ const single = data && typeof data === "object" && !Array.isArray(data) ? data : null;
2602
+ let count = null;
2603
+ if (mapping.bulk) {
2604
+ const ids = requestBody?.documentIds;
2605
+ count = Array.isArray(ids) ? Math.min(ids.length, 1e5) : null;
2606
+ if (typeof responseBody?.data?.count === "number") count = responseBody.data.count;
2607
+ }
2608
+ const documentId = mapping.bulk ? null : shaped(params?.id, DOCUMENT_ID_PATTERN) || shaped(single?.documentId, DOCUMENT_ID_PATTERN);
2609
+ const locale = shaped(query?.locale, LOCALE_PATTERN) || shaped(single?.locale, LOCALE_PATTERN);
2610
+ return {
2611
+ action: mapping.action,
2612
+ kind: mapping.kind,
2613
+ contentType,
2614
+ documentId,
2615
+ locale,
2616
+ count,
2617
+ data: mapping.bulk ? null : single
2618
+ };
2619
+ }
2620
+ function pickEntryTitle(data, mainField) {
2621
+ if (!data || typeof data !== "object" || !mainField || mainField === "id") return null;
2622
+ const value = data[mainField];
2623
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
2624
+ if (typeof value !== "string") return null;
2625
+ const text = value.replace(/\s+/g, " ").trim();
2626
+ return text ? text.slice(0, 255) : null;
2627
+ }
2628
+ function safeReason(reason) {
2629
+ return typeof reason === "string" && /^[a-z][a-z0-9_-]{0,39}$/.test(reason) ? reason : null;
2630
+ }
2631
+ function deriveSessionStates(signIns, laterEvents, liveDevices) {
2632
+ const sorted = [...laterEvents].sort((a, b) => String(a.at).localeCompare(String(b.at)));
2633
+ const out = /* @__PURE__ */ new Map();
2634
+ for (const row of signIns) {
2635
+ if (!row.deviceHash) {
2636
+ out.set(row.id, { state: "unknown", endedAt: null, endedBy: null });
2637
+ continue;
2638
+ }
2639
+ let result = null;
2640
+ for (const event of sorted) {
2641
+ if (event.adminId !== row.adminId || String(event.at) <= String(row.at)) continue;
2642
+ const sameDevice = event.deviceHash === row.deviceHash;
2643
+ if (event.event === SECURITY_EVENTS.ADMIN_SIGN_IN && sameDevice) {
2644
+ result = { state: "ended", endedAt: null, endedBy: null };
2645
+ break;
2646
+ }
2647
+ const isEnd = event.event === SECURITY_EVENTS.ADMIN_SIGN_OUT || event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
2648
+ if (isEnd && (sameDevice || !event.deviceHash)) {
2649
+ result = {
2650
+ state: "signed-out",
2651
+ endedAt: event.at,
2652
+ endedBy: event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED ? event.actorId : null
2653
+ };
2654
+ break;
2655
+ }
2656
+ }
2657
+ if (!result) {
2658
+ const live = liveDevices.get(row.adminId);
2659
+ result = live && live.has(row.deviceHash) ? { state: "active", endedAt: null, endedBy: null } : { state: "ended", endedAt: null, endedBy: null };
2660
+ }
2661
+ out.set(row.id, result);
2662
+ }
2663
+ return out;
2664
+ }
2665
+ function toLocation(value) {
2666
+ let geo = value;
2667
+ if (typeof geo === "string") {
2668
+ try {
2669
+ geo = JSON.parse(geo);
2670
+ } catch {
2671
+ return null;
2672
+ }
2673
+ }
2674
+ if (!geo || typeof geo !== "object") return null;
2675
+ const text = (v) => typeof v === "string" && v.trim() ? v.trim().slice(0, 80) : null;
2676
+ const record = (
2677
+ /** @type {Record<string, unknown>} */
2678
+ geo
2679
+ );
2680
+ const location = {
2681
+ country: text(record.country),
2682
+ countryCode: text(record.countryCode ?? record.country_code),
2683
+ city: text(record.city)
2684
+ };
2685
+ return location.country || location.city ? location : null;
2686
+ }
2687
+ function toIso(value) {
2688
+ if (!value) return null;
2689
+ const date = value instanceof Date ? value : new Date(String(value));
2690
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
2691
+ }
2692
+ function toObject(value) {
2693
+ let parsed = value;
2694
+ if (typeof parsed === "string") {
2695
+ try {
2696
+ parsed = JSON.parse(parsed);
2697
+ } catch {
2698
+ return {};
2699
+ }
2700
+ }
2701
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2702
+ }
2703
+ module2.exports = {
2704
+ ACTOR_TYPES,
2705
+ ADMIN_CONTENT_EVENTS,
2706
+ ADMIN_SIGN_IN_EVENTS,
2707
+ CONTENT_ACTIONS,
2708
+ CONTENT_MANAGER_HANDLERS,
2709
+ EVENT_NAME_PATTERN,
2710
+ MAX_META_BYTES,
2711
+ SECURITY_EVENTS,
2712
+ SIGN_IN_FILTERS,
2713
+ boundMeta,
2714
+ contentEvent,
2715
+ deriveSessionStates,
2716
+ describeContentManagerRequest,
2717
+ handlerName,
2718
+ pickEntryTitle,
2719
+ recordingSwitchOf,
2720
+ safeReason,
2721
+ toIso,
2722
+ toLocation,
2723
+ toObject
2724
+ };
2725
+ }
2726
+ });
2727
+
2728
+ // server/src/utils/user-agent-parser.js
2729
+ var require_user_agent_parser = __commonJS({
2730
+ "server/src/utils/user-agent-parser.js"(exports2, module2) {
2731
+ "use strict";
2732
+ function parseUserAgent(userAgent) {
2733
+ if (!userAgent) {
2734
+ return {
2735
+ deviceType: "unknown",
2736
+ browserName: "unknown",
2737
+ browserVersion: null,
2738
+ osName: "unknown",
2739
+ osVersion: null
2740
+ };
2741
+ }
2742
+ let deviceType = "desktop";
2743
+ if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
2744
+ deviceType = "tablet";
2745
+ } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
2746
+ deviceType = "mobile";
2747
+ } else if (/android(?!.*mobile)/i.test(userAgent)) {
2748
+ deviceType = "tablet";
2749
+ } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
2750
+ deviceType = "bot";
2751
+ }
2752
+ let browserName = "unknown";
2753
+ let browserVersion = null;
2754
+ if (/edg\//i.test(userAgent)) {
2755
+ browserName = "Edge";
2756
+ browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
2757
+ } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
2758
+ browserName = "Opera";
2759
+ browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
2760
+ } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
2761
+ browserName = "Chrome";
2762
+ browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
2763
+ } else if (/firefox|fxios/i.test(userAgent)) {
2764
+ browserName = "Firefox";
2765
+ browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
2766
+ } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
2767
+ browserName = "Safari";
2768
+ browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
2769
+ } else if (/msie|trident/i.test(userAgent)) {
2770
+ browserName = "Internet Explorer";
2771
+ browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
2772
+ }
2773
+ let osName = "unknown";
2774
+ let osVersion = null;
2775
+ if (/windows nt/i.test(userAgent)) {
2776
+ osName = "Windows";
2777
+ const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
2778
+ const winVersionMap = {
2779
+ "10.0": "10/11",
2780
+ 6.3: "8.1",
2781
+ 6.2: "8",
2782
+ 6.1: "7",
2783
+ "6.0": "Vista",
2784
+ 5.1: "XP"
2785
+ };
2786
+ osVersion = winVersionMap[winVersion] || winVersion;
2787
+ } else if (/iphone|ipad|ipod/i.test(userAgent)) {
2788
+ osName = "iOS";
2789
+ osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
2790
+ } else if (/mac os x/i.test(userAgent)) {
2791
+ osName = "macOS";
2792
+ osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
2793
+ } else if (/android/i.test(userAgent)) {
2794
+ osName = "Android";
2795
+ osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
2796
+ } else if (/linux/i.test(userAgent)) {
2797
+ osName = "Linux";
2798
+ } else if (/cros/i.test(userAgent)) {
2799
+ osName = "Chrome OS";
2800
+ }
2801
+ return {
2802
+ deviceType,
2803
+ browserName,
2804
+ browserVersion,
2805
+ osName,
2806
+ osVersion
2807
+ };
2808
+ }
2809
+ function extractVersion(userAgent, regex) {
2810
+ const match = userAgent.match(regex);
2811
+ return match ? match[1] : null;
2812
+ }
2813
+ function getDeviceDescription(parsed) {
2814
+ const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
2815
+ const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
2816
+ return `${browser} on ${os}`;
2817
+ }
2818
+ module2.exports = {
2819
+ parseUserAgent,
2820
+ getDeviceDescription
2821
+ };
2822
+ }
2823
+ });
2824
+
2825
+ // server/src/utils/admin-request-info.js
2826
+ var require_admin_request_info = __commonJS({
2827
+ "server/src/utils/admin-request-info.js"(exports2, module2) {
2828
+ "use strict";
2829
+ var crypto = require("node:crypto");
2830
+ var net = require("node:net");
2831
+ var { parseUserAgent } = require_user_agent_parser();
2832
+ var MAX_USER_AGENT_LENGTH = 500;
2833
+ var MAX_DEVICE_ID_LENGTH = 200;
2834
+ function normalizeIp(value) {
2835
+ if (typeof value !== "string") return null;
2836
+ let ip = value.trim();
2837
+ if (!ip || ip.length > 100) return null;
2838
+ if (ip.startsWith("[")) {
2839
+ const end = ip.indexOf("]");
2840
+ ip = end === -1 ? ip.slice(1) : ip.slice(1, end);
2841
+ }
2842
+ if (/^::ffff:/i.test(ip) && net.isIPv4(ip.slice(7))) ip = ip.slice(7);
2843
+ if (ip.includes(".") && ip.split(":").length === 2) ip = ip.split(":")[0];
2844
+ const zone = ip.indexOf("%");
2845
+ if (zone !== -1) ip = ip.slice(0, zone);
2846
+ return net.isIP(ip) === 0 ? null : ip.toLowerCase();
2847
+ }
2848
+ function getRequestIp(ctx) {
2849
+ try {
2850
+ return normalizeIp(ctx?.request?.ip);
2851
+ } catch {
2852
+ return null;
2853
+ }
2854
+ }
2855
+ function ipv6Groups(ip) {
2856
+ let address = ip;
2857
+ let tail = [];
2858
+ const lastColon = address.lastIndexOf(":");
2859
+ const suffix = address.slice(lastColon + 1);
2860
+ if (net.isIPv4(suffix)) {
2861
+ const [a, b, c, d] = suffix.split(".").map(Number);
2862
+ tail = [a << 8 | b, c << 8 | d];
2863
+ address = `${address.slice(0, lastColon + 1)}0`;
2864
+ }
2865
+ const [head, rest] = address.includes("::") ? address.split("::") : [address, null];
2866
+ const left = head ? head.split(":") : [];
2867
+ const right = rest ? rest.split(":") : [];
2868
+ const fill = rest === null ? 0 : 8 - left.length - right.length;
2869
+ const groups = [...left, ...Array(Math.max(0, fill)).fill("0"), ...right].map(
2870
+ (g) => Number.parseInt(g || "0", 16)
2871
+ );
2872
+ if (tail.length) groups.splice(6, 2, ...tail);
2873
+ return groups.slice(0, 8);
2874
+ }
2875
+ function anonymizeIp(ip) {
2876
+ if (!ip) return null;
2877
+ if (net.isIPv4(ip)) {
2878
+ const parts = ip.split(".");
2879
+ return `${parts[0]}.${parts[1]}.${parts[2]}.0`;
2880
+ }
2881
+ if (net.isIPv6(ip)) {
2882
+ const groups = ipv6Groups(ip);
2883
+ return `${groups.slice(0, 3).map((group) => group.toString(16)).join(":")}::`;
2884
+ }
2885
+ return null;
2886
+ }
2887
+ function getRequestUserAgent(ctx) {
2888
+ const value = ctx?.request?.headers?.["user-agent"];
2889
+ if (typeof value !== "string" || !value.trim()) return null;
2890
+ return value.slice(0, MAX_USER_AGENT_LENGTH);
2891
+ }
2892
+ function describeUserAgent(userAgent) {
2893
+ if (!userAgent) return { browserName: null, osName: null, deviceType: null };
2894
+ const parsed = parseUserAgent(userAgent);
2895
+ const known = (value) => value && value !== "unknown" ? String(value) : null;
2896
+ const browser = known(parsed.browserName);
2897
+ const os = known(parsed.osName);
2898
+ return {
2899
+ browserName: browser ? (parsed.browserVersion ? `${browser} ${parsed.browserVersion}` : browser).slice(0, 60) : null,
2900
+ osName: os ? (parsed.osVersion ? `${os} ${parsed.osVersion}` : os).slice(0, 60) : null,
2901
+ deviceType: known(parsed.deviceType)?.slice(0, 20) || null
2902
+ };
2903
+ }
2904
+ function hashDeviceId(deviceId) {
2905
+ if (typeof deviceId !== "string" || !deviceId || deviceId.length > MAX_DEVICE_ID_LENGTH) {
2906
+ return null;
2907
+ }
2908
+ return crypto.createHash("sha256").update(deviceId).digest("hex");
2909
+ }
2910
+ module2.exports = {
2911
+ anonymizeIp,
2912
+ describeUserAgent,
2913
+ getRequestIp,
2914
+ getRequestUserAgent,
2915
+ hashDeviceId,
2916
+ normalizeIp
2917
+ };
2918
+ }
2919
+ });
2920
+
2921
+ // server/src/utils/security-log-settings.js
2922
+ var require_security_log_settings = __commonJS({
2923
+ "server/src/utils/security-log-settings.js"(exports2, module2) {
2924
+ "use strict";
2925
+ var SECURITY_LOG_DEFAULTS = Object.freeze({
2926
+ adminSignInHistory: true,
2927
+ adminContentActivity: false,
2928
+ securityLogStoreIp: true,
2929
+ securityLogAnonymizeIp: false,
2930
+ securityLogRetentionDays: 90
2931
+ });
2932
+ var SECURITY_LOG_BOOLEAN_KEYS = Object.freeze([
2933
+ "adminSignInHistory",
2934
+ "adminContentActivity",
2935
+ "securityLogStoreIp",
2936
+ "securityLogAnonymizeIp"
2937
+ ]);
2938
+ var SECURITY_LOG_RETENTION_RANGE = Object.freeze({ min: 1, max: 730 });
2939
+ var SECURITY_LOG_KEYS = Object.freeze(Object.keys(SECURITY_LOG_DEFAULTS));
2940
+ function resolveSecurityLogSettings(settings) {
2941
+ const source = settings && typeof settings === "object" ? settings : {};
2942
+ const flag = (key) => typeof source[key] === "boolean" ? (
2943
+ /** @type {boolean} */
2944
+ source[key]
2945
+ ) : (
2946
+ /** @type {any} */
2947
+ SECURITY_LOG_DEFAULTS[key]
2948
+ );
2949
+ const days = Number(source.securityLogRetentionDays);
2950
+ const { min, max } = SECURITY_LOG_RETENTION_RANGE;
2951
+ return {
2952
+ signIns: flag("adminSignInHistory"),
2953
+ content: flag("adminContentActivity"),
2954
+ storeIp: flag("securityLogStoreIp"),
2955
+ anonymizeIp: flag("securityLogAnonymizeIp"),
2956
+ retentionDays: Number.isInteger(days) && days >= min && days <= max ? days : SECURITY_LOG_DEFAULTS.securityLogRetentionDays
2957
+ };
2958
+ }
2959
+ function validateSecurityLogSettings(body) {
2960
+ const values = {};
2961
+ const errors = [];
2962
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
2963
+ for (const key of SECURITY_LOG_BOOLEAN_KEYS) {
2964
+ if (!has(key)) continue;
2965
+ if (typeof body[key] !== "boolean") {
2966
+ errors.push({ path: [key], message: `${key} must be a boolean` });
2967
+ } else {
2968
+ values[key] = /** @type {boolean} */
2969
+ body[key];
2970
+ }
2971
+ }
2972
+ if (has("securityLogRetentionDays")) {
2973
+ const raw = body.securityLogRetentionDays;
2974
+ const value = typeof raw === "number" ? raw : typeof raw === "string" && /^\s*\d+\s*$/.test(raw) ? Number.parseInt(raw, 10) : NaN;
2975
+ const { min, max } = SECURITY_LOG_RETENTION_RANGE;
2976
+ if (!Number.isInteger(value) || value < min || value > max) {
2977
+ errors.push({
2978
+ path: ["securityLogRetentionDays"],
2979
+ message: `securityLogRetentionDays must be an integer between ${min} and ${max}`
2980
+ });
2981
+ } else {
2982
+ values.securityLogRetentionDays = value;
2983
+ }
2984
+ }
2985
+ return { values, errors };
2986
+ }
2987
+ module2.exports = {
2988
+ SECURITY_LOG_BOOLEAN_KEYS,
2989
+ SECURITY_LOG_DEFAULTS,
2990
+ SECURITY_LOG_KEYS,
2991
+ SECURITY_LOG_RETENTION_RANGE,
2992
+ resolveSecurityLogSettings,
2993
+ validateSecurityLogSettings
2994
+ };
2995
+ }
2996
+ });
2997
+
2998
+ // server/src/utils/admin-activity-capture.js
2999
+ var require_admin_activity_capture = __commonJS({
3000
+ "server/src/utils/admin-activity-capture.js"(exports2, module2) {
3001
+ "use strict";
3002
+ var {
3003
+ SECURITY_EVENTS,
3004
+ describeContentManagerRequest,
3005
+ handlerName,
3006
+ safeReason
3007
+ } = require_security_log_model();
3008
+ var { getRequestIp, getRequestUserAgent } = require_admin_request_info();
3009
+ var { resolveSecurityLogSettings } = require_security_log_settings();
3010
+ var { getPluginSettings, peekCachedSettings } = require_settings_loader();
3011
+ var SERVICE = "security-log";
3012
+ var AUTH_HANDLERS = Object.freeze({
3013
+ login: "authentication.login",
3014
+ registerAdmin: "authentication.registerAdmin",
3015
+ register: "authentication.register",
3016
+ resetPassword: "authentication.resetPassword"
3017
+ });
3018
+ var SESSION_CREATING = Object.freeze({
3019
+ [AUTH_HANDLERS.registerAdmin]: "registration",
3020
+ [AUTH_HANDLERS.register]: "registration",
3021
+ [AUTH_HANDLERS.resetPassword]: "password_reset"
3022
+ });
3023
+ function peekSwitches(strapi2) {
3024
+ const cached = peekCachedSettings();
3025
+ if (!cached) {
3026
+ getPluginSettings(strapi2).catch(() => {
3027
+ });
3028
+ return null;
3029
+ }
3030
+ return resolveSecurityLogSettings(cached);
3031
+ }
3032
+ function bodyDeviceId(ctx) {
3033
+ const value = ctx?.request?.body?.deviceId;
3034
+ return typeof value === "string" && value.length > 0 && value.length <= 200 ? value : null;
3035
+ }
3036
+ function currentRequestFacts(strapi2) {
3037
+ const ctx = currentContext(strapi2);
3038
+ return {
3039
+ ip: ctx ? getRequestIp(ctx) : null,
3040
+ userAgent: ctx ? getRequestUserAgent(ctx) : null,
3041
+ deviceId: ctx ? bodyDeviceId(ctx) : null
3042
+ };
3043
+ }
3044
+ function currentContext(strapi2) {
3045
+ try {
3046
+ return strapi2.requestContext?.get?.() || null;
3047
+ } catch {
3048
+ return null;
3049
+ }
3050
+ }
3051
+ function attemptedEmailOf(ctx) {
3052
+ const email = ctx?.request?.body?.email;
3053
+ return typeof email === "string" && email.length <= 254 ? email : null;
3054
+ }
3055
+ function createCaptureMiddleware(strapi2, getService) {
3056
+ return async function adminActivityCapture(ctx, next) {
3057
+ let thrown = null;
3058
+ let result;
3059
+ try {
3060
+ result = await next();
3061
+ } catch (error) {
3062
+ thrown = error;
3063
+ }
3064
+ try {
3065
+ const route = ctx.state?.route;
3066
+ const plugin = route?.info?.pluginName;
3067
+ if (plugin === "content-manager") {
3068
+ if (!thrown) observeContentManager(strapi2, getService, ctx, route);
3069
+ } else if (plugin === "admin") {
3070
+ observeAuthentication(strapi2, getService, ctx, route, thrown);
3071
+ }
3072
+ } catch {
3073
+ }
3074
+ if (thrown) throw thrown;
3075
+ return result;
3076
+ };
3077
+ }
3078
+ function observeContentManager(strapi2, getService, ctx, route) {
3079
+ const adminId = ctx.state?.user?.id;
3080
+ const strategy = ctx.state?.auth?.strategy?.name;
3081
+ if (adminId === void 0 || strategy !== "admin" && strategy !== "admin-token") return;
3082
+ const switches = peekSwitches(strapi2);
3083
+ if (switches && !switches.content) return;
3084
+ const entry = describeContentManagerRequest({
3085
+ status: ctx.status,
3086
+ route,
3087
+ params: ctx.params,
3088
+ query: ctx.query,
3089
+ requestBody: ctx.request?.body,
3090
+ responseBody: ctx.body
3091
+ });
3092
+ if (!entry) return;
3093
+ getService()?.recordContentAction({ ...entry, adminUserId: adminId });
3094
+ }
3095
+ function observeAuthentication(strapi2, getService, ctx, route, thrown) {
3096
+ const name = handlerName(route?.handler);
3097
+ if (!name || !(name === AUTH_HANDLERS.login || name in SESSION_CREATING)) return;
3098
+ const switches = peekSwitches(strapi2);
3099
+ if (switches && !switches.signIns) return;
3100
+ const error = (
3101
+ /** @type {any} */
3102
+ thrown
3103
+ );
3104
+ const status = error ? error.name === "RateLimitError" ? 429 : Number(error.status) || 500 : Number(ctx.status);
3105
+ const facts = {
3106
+ ip: getRequestIp(ctx),
3107
+ userAgent: getRequestUserAgent(ctx),
3108
+ deviceId: bodyDeviceId(ctx)
3109
+ };
3110
+ if (name === AUTH_HANDLERS.login) {
3111
+ if (status !== 429) return;
3112
+ getService()?.record({
3113
+ event: SECURITY_EVENTS.ADMIN_LOCKOUT,
3114
+ actorType: "admin",
3115
+ targetType: "admin",
3116
+ // Resolved to an existing admin in the background, then dropped.
3117
+ attemptedEmail: attemptedEmailOf(ctx),
3118
+ meta: { reason: "rate_limited", provider: "local" },
3119
+ ...facts
3120
+ });
3121
+ return;
3122
+ }
3123
+ if (status < 200 || status >= 300) return;
3124
+ const userId = ctx.body?.data?.user?.id;
3125
+ if (userId === void 0) return;
3126
+ getService()?.record({
3127
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN,
3128
+ actorType: "admin",
3129
+ actorId: userId,
3130
+ targetType: "admin",
3131
+ targetId: userId,
3132
+ meta: { reason: (
3133
+ /** @type {any} */
3134
+ SESSION_CREATING[name]
3135
+ ), provider: "local" },
3136
+ ...facts,
3137
+ // A password reset gives the browser a new device id server-side.
3138
+ deviceId: name === AUTH_HANDLERS.resetPassword ? null : facts.deviceId
3139
+ });
3140
+ }
3141
+ function installAdminActivityCapture(strapi2, { log, runExclusive }) {
3142
+ const getService = () => {
3143
+ const service = strapi2.plugin("magic-sessionmanager")?.service(SERVICE);
3144
+ return service && !service.isStopped() ? service : null;
3145
+ };
3146
+ const cleanups = [];
3147
+ const on = (event, listener) => {
3148
+ const off = strapi2.eventHub?.on?.(event, (payload) => {
3149
+ try {
3150
+ listener(payload);
3151
+ } catch {
3152
+ }
3153
+ });
3154
+ if (typeof off === "function") cleanups.push(off);
3155
+ };
3156
+ on("admin.auth.success", (payload) => {
3157
+ const switches = peekSwitches(strapi2);
3158
+ if (switches && !switches.signIns) return;
3159
+ const id = payload?.user?.id;
3160
+ getService()?.record({
3161
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN,
3162
+ actorType: "admin",
3163
+ actorId: id,
3164
+ targetType: "admin",
3165
+ targetId: id,
3166
+ meta: { provider: safeReason(payload?.provider) || "local" },
3167
+ ...currentRequestFacts(strapi2)
3168
+ });
3169
+ });
3170
+ on("admin.auth.error", (payload) => {
3171
+ const switches = peekSwitches(strapi2);
3172
+ if (switches && !switches.signIns) return;
3173
+ const id = payload?.user?.id ?? null;
3174
+ getService()?.record({
3175
+ event: SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
3176
+ actorType: "admin",
3177
+ actorId: id,
3178
+ targetType: "admin",
3179
+ targetId: id,
3180
+ ...id === null ? { attemptedEmail: attemptedEmailOf(currentContext(strapi2)), actorFromEmail: true } : {},
3181
+ meta: {
3182
+ reason: safeReason(payload?.reason) || "invalid_credentials",
3183
+ provider: safeReason(payload?.provider) || "local"
3184
+ },
3185
+ ...currentRequestFacts(strapi2)
3186
+ });
3187
+ });
3188
+ on("admin.logout", (payload) => {
3189
+ const switches = peekSwitches(strapi2);
3190
+ if (switches && !switches.signIns) return;
3191
+ const id = payload?.user?.id;
3192
+ getService()?.record({
3193
+ event: SECURITY_EVENTS.ADMIN_SIGN_OUT,
3194
+ actorType: "admin",
3195
+ actorId: id,
3196
+ targetType: "admin",
3197
+ targetId: id,
3198
+ ...currentRequestFacts(strapi2)
3199
+ });
3200
+ });
3201
+ strapi2.server.use(createCaptureMiddleware(strapi2, getService));
3202
+ try {
3203
+ const unsubscribe = strapi2.db.lifecycles.subscribe({
3204
+ models: ["admin::user"],
3205
+ async afterDelete(event) {
3206
+ const id = event?.result?.id;
3207
+ if (id === void 0) return;
3208
+ try {
3209
+ await strapi2.plugin("magic-sessionmanager").service(SERVICE).deleteAdminData(id);
3210
+ } catch (err) {
3211
+ log.warn(
3212
+ "[security-log] Data of a deleted admin could not be removed:",
3213
+ err?.name || "Error"
3214
+ );
3215
+ }
3216
+ }
3217
+ });
3218
+ if (typeof unsubscribe === "function") cleanups.push(unsubscribe);
3219
+ } catch (err) {
3220
+ log.warn("[security-log] Could not watch admin deletions:", err?.name || "Error");
3221
+ }
3222
+ const jobName = "magic-sessionmanager-security-log-retention";
3223
+ const retention = async () => {
3224
+ const job = async () => {
3225
+ const service = strapi2.plugin("magic-sessionmanager").service(SERVICE);
3226
+ const removed = await service.cleanup();
3227
+ if (removed.expired || removed.orphans) {
3228
+ log.info(
3229
+ `[security-log] Retention removed ${removed.expired} expired events and ${removed.orphans} of deleted admins`
3230
+ );
3231
+ }
3232
+ };
3233
+ try {
3234
+ if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
3235
+ else await job();
3236
+ } catch (err) {
3237
+ log.warn("[security-log] Retention failed:", err?.name || "Error");
3238
+ }
3239
+ };
3240
+ try {
3241
+ strapi2.cron.add({ [jobName]: { task: retention, options: { rule: "17 3 * * *" } } });
3242
+ cleanups.push(() => strapi2.cron.remove(jobName));
3243
+ } catch (err) {
3244
+ log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
3245
+ }
3246
+ return async () => {
3247
+ for (const cleanup of cleanups.splice(0)) {
3248
+ try {
3249
+ cleanup();
3250
+ } catch {
3251
+ }
3252
+ }
3253
+ try {
3254
+ await strapi2.plugin("magic-sessionmanager")?.service(SERVICE)?.stop();
3255
+ } catch {
3256
+ }
3257
+ };
3258
+ }
3259
+ module2.exports = {
3260
+ createCaptureMiddleware,
3261
+ installAdminActivityCapture,
3262
+ observeAuthentication,
3263
+ observeContentManager
3264
+ };
3265
+ }
3266
+ });
3267
+
2448
3268
  // server/src/middlewares/session-rejection-headers.js
2449
3269
  var require_session_rejection_headers = __commonJS({
2450
3270
  "server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
@@ -6568,6 +7388,7 @@ var require_bootstrap = __commonJS({
6568
7388
  isThenable
6569
7389
  } = require_native_session_capture();
6570
7390
  var { ensureNativeTrackingSince } = require_native_only_insight();
7391
+ var { installAdminActivityCapture } = require_admin_activity_capture();
6571
7392
  var SESSION_UID = "plugin::magic-sessionmanager.session";
6572
7393
  var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
6573
7394
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -6722,6 +7543,13 @@ var require_bootstrap = __commonJS({
6722
7543
  log.info("[SUCCESS] Session-rejection-headers middleware mounted");
6723
7544
  strapi2.server.use(require_last_seen()({ strapi: strapi2, sessionService }));
6724
7545
  log.info("[SUCCESS] LastSeen middleware mounted");
7546
+ strapi2.sessionManagerAdminActivityUninstall = installAdminActivityCapture(strapi2, {
7547
+ log,
7548
+ runExclusive: async (name, leaseMs, job) => {
7549
+ if (await coordinator.tryAcquireLease(name, leaseMs)) await job();
7550
+ }
7551
+ });
7552
+ log.info("[SUCCESS] Admin activity capture mounted");
6725
7553
  const contentApiPermissionsReady = await ensureContentApiPermissions(strapi2, log);
6726
7554
  mountDeferredContentApiPermissionRetry({
6727
7555
  strapi: strapi2,
@@ -8174,6 +9002,14 @@ var require_destroy = __commonJS({
8174
9002
  }
8175
9003
  strapi2.sessionManagerUnsubscribers = [];
8176
9004
  }
9005
+ if (typeof strapi2.sessionManagerAdminActivityUninstall === "function") {
9006
+ try {
9007
+ await strapi2.sessionManagerAdminActivityUninstall();
9008
+ } catch (err) {
9009
+ log.warn("Failed to stop the admin activity capture:", err?.name || "Error");
9010
+ }
9011
+ strapi2.sessionManagerAdminActivityUninstall = null;
9012
+ }
8177
9013
  log.info("[SUCCESS] Plugin cleanup completed");
8178
9014
  };
8179
9015
  }
@@ -8435,18 +9271,110 @@ var require_schema2 = __commonJS({
8435
9271
  }
8436
9272
  });
8437
9273
 
9274
+ // server/src/content-types/security-event/schema.json
9275
+ var require_schema3 = __commonJS({
9276
+ "server/src/content-types/security-event/schema.json"(exports2, module2) {
9277
+ module2.exports = {
9278
+ kind: "collectionType",
9279
+ collectionName: "magic_sessions_security_events",
9280
+ info: {
9281
+ singularName: "security-event",
9282
+ pluralName: "security-events",
9283
+ displayName: "Security event",
9284
+ description: "Security event log: admin sign-ins, failed attempts, lockouts, sign-outs, who signed out whom, and Content Manager activity of admins"
9285
+ },
9286
+ options: {
9287
+ draftAndPublish: false,
9288
+ comment: ""
9289
+ },
9290
+ pluginOptions: {
9291
+ "content-manager": {
9292
+ visible: false
9293
+ },
9294
+ "content-type-builder": {
9295
+ visible: false
9296
+ }
9297
+ },
9298
+ indexes: [
9299
+ {
9300
+ name: "msm_security_events_actor",
9301
+ columns: ["actor_type", "actor_id", "created_at"]
9302
+ },
9303
+ {
9304
+ name: "msm_security_events_target",
9305
+ columns: ["target_type", "target_id", "created_at"]
9306
+ },
9307
+ {
9308
+ name: "msm_security_events_event",
9309
+ columns: ["event", "created_at"]
9310
+ },
9311
+ {
9312
+ name: "msm_security_events_created",
9313
+ columns: ["created_at"]
9314
+ }
9315
+ ],
9316
+ attributes: {
9317
+ event: {
9318
+ type: "string",
9319
+ maxLength: 64,
9320
+ required: true
9321
+ },
9322
+ actorType: {
9323
+ type: "enumeration",
9324
+ enum: ["admin", "user", "system"],
9325
+ required: true
9326
+ },
9327
+ actorId: {
9328
+ type: "string",
9329
+ maxLength: 64
9330
+ },
9331
+ targetType: {
9332
+ type: "string",
9333
+ maxLength: 40
9334
+ },
9335
+ targetId: {
9336
+ type: "string",
9337
+ maxLength: 255
9338
+ },
9339
+ ip: {
9340
+ type: "string",
9341
+ maxLength: 45
9342
+ },
9343
+ userAgent: {
9344
+ type: "text",
9345
+ maxLength: 500
9346
+ },
9347
+ geo: {
9348
+ type: "json"
9349
+ },
9350
+ meta: {
9351
+ type: "json"
9352
+ }
9353
+ }
9354
+ };
9355
+ }
9356
+ });
9357
+
8438
9358
  // server/src/content-types/index.js
8439
9359
  var require_content_types = __commonJS({
8440
9360
  "server/src/content-types/index.js"(exports2, module2) {
8441
9361
  "use strict";
8442
9362
  var session = require_schema();
8443
9363
  var revokedToken = require_schema2();
9364
+ var securityEvent = require_schema3();
8444
9365
  module2.exports = {
8445
9366
  session: {
8446
9367
  schema: session
8447
9368
  },
8448
9369
  "revoked-token": {
8449
9370
  schema: revokedToken
9371
+ },
9372
+ // One security event log (4.15): admin sign-ins and sign-outs, failed
9373
+ // attempts, lockouts, who signed out whom, Content Manager activity, and
9374
+ // later app-user security events. Hidden from the Content Manager and the
9375
+ // Content-Type Builder.
9376
+ "security-event": {
9377
+ schema: securityEvent
8450
9378
  }
8451
9379
  };
8452
9380
  }
@@ -8556,6 +9484,7 @@ var require_admin = __commonJS({
8556
9484
  var PLUGIN_ACCESS_ACTION = "plugin::magic-sessionmanager.access";
8557
9485
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
8558
9486
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
9487
+ var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
8559
9488
  var adminPolicy = () => [
8560
9489
  "admin::isAuthenticatedAdmin",
8561
9490
  {
@@ -8768,6 +9697,47 @@ var require_admin = __commonJS({
8768
9697
  description: "Sign a Strapi admin out of every browser (admin)"
8769
9698
  }
8770
9699
  },
9700
+ // ============== ADMIN SIGN-IN HISTORY AND CONTENT MANAGER ACTIVITY ==============
9701
+ {
9702
+ method: "GET",
9703
+ path: "/admin-activity/sign-ins",
9704
+ handler: "admin-activity.listSignIns",
9705
+ config: {
9706
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9707
+ middlewares: adminReadRateLimit(),
9708
+ description: "List the admin sign-in history (admin)"
9709
+ }
9710
+ },
9711
+ {
9712
+ method: "GET",
9713
+ path: "/admin-activity/sign-ins/export",
9714
+ handler: "admin-activity.exportSignIns",
9715
+ config: {
9716
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9717
+ middlewares: adminReadRateLimit(),
9718
+ description: "Get one export batch of the admin sign-in history (admin)"
9719
+ }
9720
+ },
9721
+ {
9722
+ method: "GET",
9723
+ path: "/admin-activity/content",
9724
+ handler: "admin-activity.listContentActivity",
9725
+ config: {
9726
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9727
+ middlewares: adminReadRateLimit(),
9728
+ description: "List Content Manager activity of admins (admin)"
9729
+ }
9730
+ },
9731
+ {
9732
+ method: "GET",
9733
+ path: "/admin-activity/content/export",
9734
+ handler: "admin-activity.exportContentActivity",
9735
+ config: {
9736
+ policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
9737
+ middlewares: adminReadRateLimit(),
9738
+ description: "Get one export batch of Content Manager activity of admins (admin)"
9739
+ }
9740
+ },
8771
9741
  // ============================ GEOLOCATION ============================
8772
9742
  {
8773
9743
  method: "GET",
@@ -8856,103 +9826,6 @@ var require_routes = __commonJS({
8856
9826
  }
8857
9827
  });
8858
9828
 
8859
- // server/src/utils/user-agent-parser.js
8860
- var require_user_agent_parser = __commonJS({
8861
- "server/src/utils/user-agent-parser.js"(exports2, module2) {
8862
- "use strict";
8863
- function parseUserAgent(userAgent) {
8864
- if (!userAgent) {
8865
- return {
8866
- deviceType: "unknown",
8867
- browserName: "unknown",
8868
- browserVersion: null,
8869
- osName: "unknown",
8870
- osVersion: null
8871
- };
8872
- }
8873
- let deviceType = "desktop";
8874
- if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
8875
- deviceType = "tablet";
8876
- } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
8877
- deviceType = "mobile";
8878
- } else if (/android(?!.*mobile)/i.test(userAgent)) {
8879
- deviceType = "tablet";
8880
- } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
8881
- deviceType = "bot";
8882
- }
8883
- let browserName = "unknown";
8884
- let browserVersion = null;
8885
- if (/edg\//i.test(userAgent)) {
8886
- browserName = "Edge";
8887
- browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
8888
- } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
8889
- browserName = "Opera";
8890
- browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
8891
- } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
8892
- browserName = "Chrome";
8893
- browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
8894
- } else if (/firefox|fxios/i.test(userAgent)) {
8895
- browserName = "Firefox";
8896
- browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
8897
- } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
8898
- browserName = "Safari";
8899
- browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
8900
- } else if (/msie|trident/i.test(userAgent)) {
8901
- browserName = "Internet Explorer";
8902
- browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
8903
- }
8904
- let osName = "unknown";
8905
- let osVersion = null;
8906
- if (/windows nt/i.test(userAgent)) {
8907
- osName = "Windows";
8908
- const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
8909
- const winVersionMap = {
8910
- "10.0": "10/11",
8911
- 6.3: "8.1",
8912
- 6.2: "8",
8913
- 6.1: "7",
8914
- "6.0": "Vista",
8915
- 5.1: "XP"
8916
- };
8917
- osVersion = winVersionMap[winVersion] || winVersion;
8918
- } else if (/iphone|ipad|ipod/i.test(userAgent)) {
8919
- osName = "iOS";
8920
- osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8921
- } else if (/mac os x/i.test(userAgent)) {
8922
- osName = "macOS";
8923
- osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
8924
- } else if (/android/i.test(userAgent)) {
8925
- osName = "Android";
8926
- osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
8927
- } else if (/linux/i.test(userAgent)) {
8928
- osName = "Linux";
8929
- } else if (/cros/i.test(userAgent)) {
8930
- osName = "Chrome OS";
8931
- }
8932
- return {
8933
- deviceType,
8934
- browserName,
8935
- browserVersion,
8936
- osName,
8937
- osVersion
8938
- };
8939
- }
8940
- function extractVersion(userAgent, regex) {
8941
- const match = userAgent.match(regex);
8942
- return match ? match[1] : null;
8943
- }
8944
- function getDeviceDescription(parsed) {
8945
- const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
8946
- const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
8947
- return `${browser} on ${os}`;
8948
- }
8949
- module2.exports = {
8950
- parseUserAgent,
8951
- getDeviceDescription
8952
- };
8953
- }
8954
- });
8955
-
8956
9829
  // server/src/utils/enhance-session.js
8957
9830
  var require_enhance_session = __commonJS({
8958
9831
  "server/src/utils/enhance-session.js"(exports2, module2) {
@@ -11206,6 +12079,12 @@ var require_settings = __commonJS({
11206
12079
  var { LockTimeoutError } = require_coordination();
11207
12080
  var { resolveDatabaseTarget } = require_geoip_updater();
11208
12081
  var { sendServerError, sendValidationError } = require_http_errors();
12082
+ var {
12083
+ SECURITY_LOG_DEFAULTS,
12084
+ SECURITY_LOG_KEYS,
12085
+ validateSecurityLogSettings
12086
+ } = require_security_log_settings();
12087
+ var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
11209
12088
  var path = require("node:path");
11210
12089
  var ALLOWED_WEBHOOK_DOMAINS = {
11211
12090
  discord: ["discord.com", "discordapp.com"],
@@ -11379,7 +12258,8 @@ var require_settings = __commonJS({
11379
12258
  slackWebhookUrl: "",
11380
12259
  strictSessionEnforcement: false,
11381
12260
  trustedProxies: false,
11382
- emailTemplates: DEFAULT_EMAIL_TEMPLATES
12261
+ emailTemplates: DEFAULT_EMAIL_TEMPLATES,
12262
+ ...SECURITY_LOG_DEFAULTS
11383
12263
  };
11384
12264
  function mergeSettingsWithDefaults(stored) {
11385
12265
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -11584,6 +12464,9 @@ var require_settings = __commonJS({
11584
12464
  next.emailTemplates = sanitizeEmailTemplates(mergedTemplates);
11585
12465
  }
11586
12466
  }
12467
+ const securityLog = validateSecurityLogSettings(body);
12468
+ errors.push(...securityLog.errors);
12469
+ Object.assign(next, securityLog.values);
11587
12470
  if (errors.length > 0) return { errors };
11588
12471
  const settings = {};
11589
12472
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -11611,6 +12494,13 @@ var require_settings = __commonJS({
11611
12494
  };
11612
12495
  return ctx.body;
11613
12496
  }
12497
+ function canChangeAdminActivity(ctx) {
12498
+ try {
12499
+ return ctx.state?.userAbility?.can?.(ADMIN_ACTIVITY_READ_ACTION) === true;
12500
+ } catch {
12501
+ return false;
12502
+ }
12503
+ }
11614
12504
  module2.exports = {
11615
12505
  /**
11616
12506
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -11649,6 +12539,9 @@ var require_settings = __commonJS({
11649
12539
  * Omitted fields keep their stored value. Invalid values are rejected with
11650
12540
  * a 400 whose `error.details.errors` names each field; nothing is clamped
11651
12541
  * or written in that case. Store failures return a 500 with a safe message.
12542
+ * Changing a security log setting (`adminSignInHistory`,
12543
+ * `adminContentActivity`, `securityLogStoreIp`, `securityLogAnonymizeIp`,
12544
+ * `securityLogRetentionDays`) also needs `admin-activity.read`, else 403.
11652
12545
  *
11653
12546
  * @route PUT /magic-sessionmanager/settings
11654
12547
  * @returns {Promise<void>}
@@ -11680,6 +12573,10 @@ var require_settings = __commonJS({
11680
12573
  };
11681
12574
  const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
11682
12575
  if (errors.length > 0) return { errors };
12576
+ const changesAdminActivity = SECURITY_LOG_KEYS.some(
12577
+ (key) => sanitizedSettings[key] !== current[key]
12578
+ );
12579
+ if (changesAdminActivity && !canChangeAdminActivity(ctx)) return { forbidden: true };
11683
12580
  await pluginStore.set({
11684
12581
  key: "settings",
11685
12582
  value: sanitizedSettings
@@ -11687,6 +12584,11 @@ var require_settings = __commonJS({
11687
12584
  const revision = await notifySettingsChanged(strapi);
11688
12585
  return { settings: sanitizedSettings, revision };
11689
12586
  });
12587
+ if (outcome.forbidden) {
12588
+ return ctx.forbidden('Changing the security log settings needs "View admin activity".', {
12589
+ reason: "admin-activity-permission"
12590
+ });
12591
+ }
11690
12592
  if (outcome.conflict) {
11691
12593
  return sendSettingsConflict(ctx, outcome.currentRevision);
11692
12594
  }
@@ -12178,6 +13080,9 @@ var require_admin_sessions = __commonJS({
12178
13080
  "server/src/utils/admin-sessions.js"(exports2, module2) {
12179
13081
  "use strict";
12180
13082
  var { z } = require("@strapi/utils");
13083
+ var { hashDeviceId } = require_admin_request_info();
13084
+ var { resolveSecurityLogSettings } = require_security_log_settings();
13085
+ var { getPluginSettings } = require_settings_loader();
12181
13086
  var ADMIN_ORIGIN = "admin";
12182
13087
  var SESSION_UID = "admin::session";
12183
13088
  var ADMIN_USER_UID = "admin::user";
@@ -12379,6 +13284,18 @@ var require_admin_sessions = __commonJS({
12379
13284
  }
12380
13285
  return map;
12381
13286
  }
13287
+ async function readSignInRecording(strapi2) {
13288
+ try {
13289
+ const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
13290
+ return {
13291
+ signIns: options.signIns,
13292
+ ipAddresses: options.signIns && options.storeIp,
13293
+ anonymizeIp: options.signIns && options.storeIp && options.anonymizeIp
13294
+ };
13295
+ } catch {
13296
+ return { signIns: false, ipAddresses: false, anonymizeIp: false };
13297
+ }
13298
+ }
12382
13299
  async function listAdmins(strapi2, query, actor) {
12383
13300
  const policy = readSessionPolicy(strapi2);
12384
13301
  if (!getAdminSessionManager(strapi2)) {
@@ -12389,7 +13306,8 @@ var require_admin_sessions = __commonJS({
12389
13306
  pagination: { page: 1, pageSize: query.pageSize, total: 0, pageCount: 1 },
12390
13307
  stats: null,
12391
13308
  policy,
12392
- truncated: false
13309
+ truncated: false,
13310
+ recording: await readSignInRecording(strapi2)
12393
13311
  }
12394
13312
  };
12395
13313
  }
@@ -12470,7 +13388,8 @@ var require_admin_sessions = __commonJS({
12470
13388
  totalAdmins: Number(totalAdmins) || 0
12471
13389
  },
12472
13390
  policy,
12473
- truncated
13391
+ truncated,
13392
+ recording: await readSignInRecording(strapi2)
12474
13393
  }
12475
13394
  };
12476
13395
  }
@@ -12541,6 +13460,7 @@ var require_admin_sessions = __commonJS({
12541
13460
  const currentDeviceId = self ? await findCurrentDeviceId(strapi2, { userId, sessionId: actor.sessionId }) : null;
12542
13461
  let ended;
12543
13462
  let signedOutSelf;
13463
+ let endedDeviceId = null;
12544
13464
  if (sessionId) {
12545
13465
  const row = await strapi2.db.query(SESSION_UID).findOne({
12546
13466
  select: ["userId", "deviceId", "origin"],
@@ -12551,6 +13471,7 @@ var require_admin_sessions = __commonJS({
12551
13471
  }
12552
13472
  if (blockReason === "account-inactive") throw new AdminSignOutError(404, "Session not found");
12553
13473
  await manager.invalidateRefreshToken(userId, String(row.deviceId));
13474
+ endedDeviceId = String(row.deviceId);
12554
13475
  ended = 1;
12555
13476
  signedOutSelf = Boolean(currentDeviceId) && String(row.deviceId) === currentDeviceId;
12556
13477
  } else {
@@ -12563,6 +13484,18 @@ var require_admin_sessions = __commonJS({
12563
13484
  target.id
12564
13485
  )} scope=${scope} ended=${ended}`;
12565
13486
  strapi2.log.info(audit);
13487
+ try {
13488
+ strapi2.plugin("magic-sessionmanager")?.service("security-log")?.record({
13489
+ event: "admin.session.revoked",
13490
+ actorType: "admin",
13491
+ actorId: Number(actor.id),
13492
+ targetType: "admin",
13493
+ targetId: Number(target.id),
13494
+ meta: { scope: scope === "one" ? "one_browser" : "everywhere", ended },
13495
+ deviceHash: endedDeviceId ? hashDeviceId(endedDeviceId) : null
13496
+ });
13497
+ } catch {
13498
+ }
12566
13499
  try {
12567
13500
  strapi2.eventHub?.emit?.("magic-sessionmanager.admin-sessions.signed-out", {
12568
13501
  actorId: Number(actor.id),
@@ -12763,6 +13696,149 @@ var require_admin_sessions2 = __commonJS({
12763
13696
  }
12764
13697
  });
12765
13698
 
13699
+ // server/src/controllers/admin-activity.js
13700
+ var require_admin_activity = __commonJS({
13701
+ "server/src/controllers/admin-activity.js"(exports2, module2) {
13702
+ "use strict";
13703
+ var { z } = require("@strapi/utils");
13704
+ var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
13705
+ var { parseInput } = require_admin_sessions();
13706
+ var { sendServerError, sendValidationError } = require_http_errors();
13707
+ var { createLogger } = require_logger();
13708
+ var MAX_PAGE_SIZE = 100;
13709
+ var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
13710
+ var dateField = (name) => z.string().max(40, `${name} must be an ISO 8601 date`).refine((value) => !Number.isNaN(Date.parse(value)), `${name} must be an ISO 8601 date`).transform((value) => new Date(value)).optional();
13711
+ var common = {
13712
+ adminId: adminIdField,
13713
+ from: dateField("from"),
13714
+ to: dateField("to"),
13715
+ page: z.coerce.number().int().min(1).max(1e6).default(1),
13716
+ pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
13717
+ };
13718
+ var signInQuerySchema = z.strictObject({
13719
+ ...common,
13720
+ event: z.enum(
13721
+ /** @type {[string, ...string[]]} */
13722
+ Object.keys(SIGN_IN_FILTERS)
13723
+ ).default("all")
13724
+ });
13725
+ var activityQuerySchema = z.strictObject({
13726
+ ...common,
13727
+ action: z.enum(
13728
+ /** @type {[string, ...string[]]} */
13729
+ ["all", ...CONTENT_ACTIONS]
13730
+ ).default("all"),
13731
+ contentType: z.string().regex(
13732
+ /^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/,
13733
+ "contentType must be a content type uid"
13734
+ ).optional()
13735
+ });
13736
+ var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
13737
+ var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
13738
+ cursor: cursorField
13739
+ });
13740
+ var activityExportSchema = activityQuerySchema.omit({ page: true, pageSize: true }).extend({
13741
+ cursor: cursorField
13742
+ });
13743
+ module2.exports = ({ strapi: strapi2 }) => {
13744
+ const log = createLogger(strapi2);
13745
+ const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
13746
+ const handle = async (ctx, schema, run, operation) => {
13747
+ const parsed = parseInput(schema, ctx.query);
13748
+ if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
13749
+ const query = parsed.value;
13750
+ if (query.from && query.to && query.from > query.to) {
13751
+ return sendValidationError(ctx, "Invalid query", [
13752
+ { path: ["from"], message: "from must not be after to" }
13753
+ ]);
13754
+ }
13755
+ try {
13756
+ ctx.body = await run(query);
13757
+ return ctx.body;
13758
+ } catch (error) {
13759
+ log.error(
13760
+ `Admin activity: ${operation} failed`,
13761
+ /** @type {any} */
13762
+ error?.name || "Error"
13763
+ );
13764
+ return sendServerError(ctx, 500, "Admin activity could not be loaded.");
13765
+ }
13766
+ };
13767
+ return {
13768
+ /**
13769
+ * One page of the admin sign-in history: sign-ins, failed attempts,
13770
+ * lockouts and sign-outs, newest first.
13771
+ *
13772
+ * @route GET /magic-sessionmanager/admin-activity/sign-ins
13773
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
13774
+ * read rate limit.
13775
+ * @param {Context} ctx Reads `ctx.query.adminId` (optional positive integer), `event`
13776
+ * (`all`|`succeeded`|`failed`|`signed-out`), `from`/`to` (ISO dates), `page`, `pageSize`
13777
+ * (1..100, default 20).
13778
+ * @returns {Promise<unknown>} 200 `{ data: SignInRow[], meta: { pagination, recording } }`;
13779
+ * 400 ValidationError with field errors; 500 fixed message. Rows hold IP address
13780
+ * (possibly anonymised), location, browser, OS and session state; never the device id,
13781
+ * a typed email or a token.
13782
+ */
13783
+ async listSignIns(ctx) {
13784
+ return handle(ctx, signInQuerySchema, (query) => service().listSignIns(query), "sign-ins");
13785
+ },
13786
+ /**
13787
+ * One page of Content Manager activity, newest first.
13788
+ *
13789
+ * @route GET /magic-sessionmanager/admin-activity/content
13790
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
13791
+ * read rate limit.
13792
+ * @param {Context} ctx Reads `ctx.query.adminId`, `action` (`all` or an action),
13793
+ * `contentType` (uid), `from`/`to`, `page`, `pageSize`.
13794
+ * @returns {Promise<unknown>} 200 `{ data: ActivityRow[], meta: { pagination, recording,
13795
+ * contentTypes, contentManagerAccess? } }`; 400; 500 fixed message.
13796
+ */
13797
+ async listContentActivity(ctx) {
13798
+ return handle(
13799
+ ctx,
13800
+ activityQuerySchema,
13801
+ (query) => service().listContentActivity(query),
13802
+ "content"
13803
+ );
13804
+ },
13805
+ /**
13806
+ * One export batch (500 rows, keyset cursor) of the sign-in history.
13807
+ *
13808
+ * @route GET /magic-sessionmanager/admin-activity/sign-ins/export
13809
+ * @auth As listSignIns.
13810
+ * @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
13811
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
13812
+ */
13813
+ async exportSignIns(ctx) {
13814
+ return handle(
13815
+ ctx,
13816
+ signInExportSchema,
13817
+ (query) => service().exportBatch("sign-ins", query, query.cursor || null),
13818
+ "sign-in export"
13819
+ );
13820
+ },
13821
+ /**
13822
+ * One export batch (500 rows, keyset cursor) of Content Manager activity.
13823
+ *
13824
+ * @route GET /magic-sessionmanager/admin-activity/content/export
13825
+ * @auth As listContentActivity.
13826
+ * @param {Context} ctx Same filters as the list, plus `cursor`.
13827
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
13828
+ */
13829
+ async exportContentActivity(ctx) {
13830
+ return handle(
13831
+ ctx,
13832
+ activityExportSchema,
13833
+ (query) => service().exportBatch("content", query, query.cursor || null),
13834
+ "activity export"
13835
+ );
13836
+ }
13837
+ };
13838
+ };
13839
+ }
13840
+ });
13841
+
12766
13842
  // server/src/controllers/index.js
12767
13843
  var require_controllers = __commonJS({
12768
13844
  "server/src/controllers/index.js"(exports2, module2) {
@@ -12771,11 +13847,13 @@ var require_controllers = __commonJS({
12771
13847
  var settings = require_settings();
12772
13848
  var geoip = require_geoip();
12773
13849
  var adminSessions = require_admin_sessions2();
13850
+ var adminActivity = require_admin_activity();
12774
13851
  module2.exports = {
12775
13852
  session,
12776
13853
  settings,
12777
13854
  geoip,
12778
- "admin-sessions": adminSessions
13855
+ "admin-sessions": adminSessions,
13856
+ "admin-activity": adminActivity
12779
13857
  };
12780
13858
  }
12781
13859
  });
@@ -15207,6 +16285,740 @@ Score: ${geoData.securityScore}/100`,
15207
16285
  }
15208
16286
  });
15209
16287
 
16288
+ // server/src/services/security-log.js
16289
+ var require_security_log = __commonJS({
16290
+ "server/src/services/security-log.js"(exports2, module2) {
16291
+ "use strict";
16292
+ var {
16293
+ ACTOR_TYPES,
16294
+ ADMIN_CONTENT_EVENTS,
16295
+ CONTENT_ACTIONS,
16296
+ EVENT_NAME_PATTERN,
16297
+ SECURITY_EVENTS,
16298
+ SIGN_IN_FILTERS,
16299
+ boundMeta,
16300
+ contentEvent,
16301
+ deriveSessionStates,
16302
+ pickEntryTitle,
16303
+ recordingSwitchOf,
16304
+ safeReason,
16305
+ toIso,
16306
+ toLocation,
16307
+ toObject
16308
+ } = require_security_log_model();
16309
+ var {
16310
+ anonymizeIp,
16311
+ describeUserAgent,
16312
+ hashDeviceId,
16313
+ normalizeIp
16314
+ } = require_admin_request_info();
16315
+ var { resolveSecurityLogSettings } = require_security_log_settings();
16316
+ var { getPluginSettings } = require_settings_loader();
16317
+ var { shouldResolveGeoData } = require_enhance_session();
16318
+ var { createLogger } = require_logger();
16319
+ var EVENT_UID = "plugin::magic-sessionmanager.security-event";
16320
+ var ADMIN_USER_UID = "admin::user";
16321
+ var ADMIN_SESSION_UID = "admin::session";
16322
+ var PERMISSION_UID = "admin::permission";
16323
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
16324
+ var FLUSH_DELAY_MS = 1e3;
16325
+ var FLUSH_BATCH = 200;
16326
+ var MAX_QUEUE = 2e3;
16327
+ var VIEW_DEDUP_MS = 10 * 60 * 1e3;
16328
+ var LOCKOUT_DEDUP_MS = 5 * 60 * 1e3;
16329
+ var MAX_DEDUP_KEYS = 2e4;
16330
+ var GEO_LOOKUPS_PER_FLUSH = 20;
16331
+ var MAIN_FIELD_TTL_MS = 5 * 60 * 1e3;
16332
+ var EXPORT_BATCH = 500;
16333
+ var DELETE_BATCH = 1e3;
16334
+ var MAX_DELETE_STEPS = 200;
16335
+ function toId(value) {
16336
+ if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
16337
+ if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
16338
+ return null;
16339
+ }
16340
+ function toAdminId(value) {
16341
+ const id = Number(value);
16342
+ return Number.isInteger(id) && id > 0 && id < 1e12 ? id : null;
16343
+ }
16344
+ function adminName(user) {
16345
+ if (!user) return "";
16346
+ const name = [user.firstname, user.lastname].filter((part) => typeof part === "string" && part.trim()).join(" ").trim();
16347
+ return (name || user.username || user.email || "").slice(0, 200);
16348
+ }
16349
+ function pruneDedup(map, now, windowMs) {
16350
+ if (map.size <= MAX_DEDUP_KEYS) return;
16351
+ for (const [key, at] of map) if (now - at >= windowMs) map.delete(key);
16352
+ while (map.size > MAX_DEDUP_KEYS) {
16353
+ const first = map.keys().next().value;
16354
+ if (first === void 0) break;
16355
+ map.delete(first);
16356
+ }
16357
+ }
16358
+ function deviceHashOf(meta) {
16359
+ const value = toObject(meta).deviceHash;
16360
+ return typeof value === "string" ? value : null;
16361
+ }
16362
+ module2.exports = ({ strapi: strapi2 }) => {
16363
+ const log = createLogger(strapi2);
16364
+ let queue = [];
16365
+ let timer = null;
16366
+ let flushing = null;
16367
+ let stopped = false;
16368
+ let dropped = 0;
16369
+ const viewed = /* @__PURE__ */ new Map();
16370
+ const lockouts = /* @__PURE__ */ new Map();
16371
+ const mainFields = /* @__PURE__ */ new Map();
16372
+ const events = () => strapi2.db.query(EVENT_UID);
16373
+ const schedule = () => {
16374
+ if (timer || stopped) return;
16375
+ timer = setTimeout(() => {
16376
+ timer = null;
16377
+ service.flush().catch(() => {
16378
+ });
16379
+ }, FLUSH_DELAY_MS);
16380
+ if (typeof timer.unref === "function") timer.unref();
16381
+ };
16382
+ const mainFieldOf = async (uid) => {
16383
+ const now = Date.now();
16384
+ const cachedField = mainFields.get(uid);
16385
+ if (cachedField && now - cachedField.at < MAIN_FIELD_TTL_MS) return cachedField.field;
16386
+ let field;
16387
+ try {
16388
+ const contentTypes2 = strapi2.plugin("content-manager")?.service("content-types");
16389
+ const configuration = contentTypes2 ? await contentTypes2.findConfiguration({ uid }) : null;
16390
+ const configured = configuration?.settings?.mainField;
16391
+ field = typeof configured === "string" ? configured : null;
16392
+ } catch {
16393
+ field = null;
16394
+ }
16395
+ mainFields.set(uid, { field, at: now });
16396
+ return field;
16397
+ };
16398
+ const loadAdmins = async (ids) => {
16399
+ const unique = [...new Set(ids.map(toAdminId).filter((id) => id !== null))];
16400
+ if (!unique.length) return /* @__PURE__ */ new Map();
16401
+ const rows = await strapi2.db.query(ADMIN_USER_UID).findMany({
16402
+ where: { id: { $in: unique } },
16403
+ select: ["id", "firstname", "lastname", "username", "email"]
16404
+ });
16405
+ return new Map((Array.isArray(rows) ? rows : []).map((row) => [Number(row.id), row]));
16406
+ };
16407
+ const titleFromLog = async (targetType, targetId) => {
16408
+ const rows = await events().findMany({
16409
+ select: ["meta"],
16410
+ where: { targetType, targetId, event: { $startsWith: "admin.content." } },
16411
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16412
+ limit: 10
16413
+ });
16414
+ for (const row of Array.isArray(rows) ? rows : []) {
16415
+ const title = toObject(row.meta).title;
16416
+ if (typeof title === "string" && title) return title;
16417
+ }
16418
+ return null;
16419
+ };
16420
+ const buildRows = async (batch, options, settings) => {
16421
+ const wanted = batch.filter((entry) => {
16422
+ const gate = recordingSwitchOf(entry.event);
16423
+ return gate === "always" || (gate === "signIns" ? options.signIns : options.content);
16424
+ });
16425
+ if (!wanted.length) return [];
16426
+ const emails = [
16427
+ ...new Set(
16428
+ wanted.map((entry) => typeof entry.attemptedEmail === "string" ? entry.attemptedEmail : "").filter((email) => email && email.length <= 254).map((email) => email.toLowerCase())
16429
+ )
16430
+ ];
16431
+ const byEmail = /* @__PURE__ */ new Map();
16432
+ if (emails.length) {
16433
+ const found = await strapi2.db.query(ADMIN_USER_UID).findMany({
16434
+ where: { email: { $in: emails } },
16435
+ select: ["id", "email"]
16436
+ });
16437
+ for (const row of Array.isArray(found) ? found : []) {
16438
+ byEmail.set(String(row.email).toLowerCase(), Number(row.id));
16439
+ }
16440
+ }
16441
+ const geoService = options.storeIp && shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null;
16442
+ const geoCache = /* @__PURE__ */ new Map();
16443
+ let geoBudget = GEO_LOOKUPS_PER_FLUSH;
16444
+ const knownTitles = /* @__PURE__ */ new Map();
16445
+ for (const entry of wanted) {
16446
+ const title = entry.entryData && entry.targetType && entry.targetId ? pickEntryTitle(entry.entryData, await mainFieldOf(entry.targetType)) : null;
16447
+ if (title) knownTitles.set(`${entry.targetType}|${toId(entry.targetId)}`, title);
16448
+ }
16449
+ const rows = [];
16450
+ for (const entry of wanted) {
16451
+ const ip = options.storeIp ? normalizeIp(entry.ip) : null;
16452
+ const storedIp = ip && options.anonymizeIp ? anonymizeIp(ip) : ip;
16453
+ let geo = null;
16454
+ if (storedIp && geoService) {
16455
+ if (geoCache.has(storedIp)) {
16456
+ geo = geoCache.get(storedIp) || null;
16457
+ } else if (geoBudget > 0) {
16458
+ geoBudget -= 1;
16459
+ try {
16460
+ const info = await geoService.getIpInfo(storedIp);
16461
+ geo = info && info._status === "ok" ? {
16462
+ country: info.country || null,
16463
+ country_code: info.country_code || null,
16464
+ city: info.city || null
16465
+ } : null;
16466
+ } catch {
16467
+ geo = null;
16468
+ }
16469
+ geoCache.set(storedIp, geo);
16470
+ }
16471
+ }
16472
+ let targetId = toId(entry.targetId);
16473
+ let actorId = toId(entry.actorId);
16474
+ if (!targetId && typeof entry.attemptedEmail === "string") {
16475
+ const found = byEmail.get(entry.attemptedEmail.toLowerCase());
16476
+ targetId = found ? String(found) : null;
16477
+ if (entry.actorFromEmail && !actorId) actorId = targetId;
16478
+ }
16479
+ const meta = { ...entry.meta || {} };
16480
+ const deviceHash = entry.deviceHash || hashDeviceId(entry.deviceId);
16481
+ if (deviceHash) meta.deviceHash = deviceHash;
16482
+ if (storedIp && options.anonymizeIp) meta.ipAnonymized = true;
16483
+ if (entry.entryData && entry.targetType) {
16484
+ const title = pickEntryTitle(entry.entryData, await mainFieldOf(entry.targetType));
16485
+ if (title) meta.title = title;
16486
+ }
16487
+ if (!meta.title && entry.event.startsWith("admin.content.") && entry.targetType) {
16488
+ const id = toId(entry.targetId);
16489
+ if (id) {
16490
+ const key = `${entry.targetType}|${id}`;
16491
+ if (!knownTitles.has(key)) knownTitles.set(key, await titleFromLog(entry.targetType, id));
16492
+ const known = knownTitles.get(key);
16493
+ if (known) meta.title = known;
16494
+ }
16495
+ }
16496
+ const occurredAt = entry.occurredAt || /* @__PURE__ */ new Date();
16497
+ rows.push({
16498
+ event: entry.event,
16499
+ actorType: entry.actorType,
16500
+ actorId,
16501
+ targetType: typeof entry.targetType === "string" ? entry.targetType.slice(0, 191) : null,
16502
+ targetId,
16503
+ ip: storedIp,
16504
+ userAgent: typeof entry.userAgent === "string" && entry.userAgent ? entry.userAgent.slice(0, 500) : null,
16505
+ geo,
16506
+ meta: boundMeta(meta),
16507
+ createdAt: occurredAt,
16508
+ updatedAt: occurredAt
16509
+ });
16510
+ }
16511
+ return rows;
16512
+ };
16513
+ const deleteOlderThan = async (cutoff) => {
16514
+ let deleted = 0;
16515
+ for (let step = 0; step < MAX_DELETE_STEPS; step += 1) {
16516
+ const rows = await events().findMany({
16517
+ select: ["id"],
16518
+ where: { createdAt: { $lt: cutoff } },
16519
+ orderBy: { id: "asc" },
16520
+ limit: DELETE_BATCH
16521
+ });
16522
+ const ids = (Array.isArray(rows) ? rows : []).map((row) => row.id);
16523
+ if (!ids.length) break;
16524
+ const result = await events().deleteMany({ where: { id: { $in: ids } } });
16525
+ deleted += Number(result?.count ?? ids.length);
16526
+ if (ids.length < DELETE_BATCH) break;
16527
+ }
16528
+ return deleted;
16529
+ };
16530
+ const writeQueued = async () => {
16531
+ while (queue.length) {
16532
+ const batch = queue;
16533
+ queue = [];
16534
+ let settings;
16535
+ try {
16536
+ settings = await getPluginSettings(strapi2);
16537
+ } catch {
16538
+ return;
16539
+ }
16540
+ try {
16541
+ const rows = await buildRows(batch, resolveSecurityLogSettings(settings), settings);
16542
+ for (let i = 0; i < rows.length; i += FLUSH_BATCH) {
16543
+ await events().createMany({ data: rows.slice(i, i + FLUSH_BATCH) });
16544
+ }
16545
+ } catch (err) {
16546
+ log.warn("[security-log] Events could not be written:", err?.name || "Error");
16547
+ }
16548
+ }
16549
+ if (dropped > 0) {
16550
+ log.warn(`[security-log] ${dropped} queued events were dropped (queue full)`);
16551
+ dropped = 0;
16552
+ }
16553
+ };
16554
+ const service = {
16555
+ /**
16556
+ * Queues one security event. Returns at once; nothing is awaited.
16557
+ * Unknown event names or actor types are ignored.
16558
+ *
16559
+ * @param {SecurityEventInput} input Event.
16560
+ * @returns {boolean} Whether the event was queued.
16561
+ * @sideeffect Adds to the in-memory queue; the flush stores it when its switch is on.
16562
+ */
16563
+ record(input) {
16564
+ if (stopped || !input || typeof input.event !== "string") return false;
16565
+ if (!EVENT_NAME_PATTERN.test(input.event) || !ACTOR_TYPES.includes(input.actorType)) {
16566
+ return false;
16567
+ }
16568
+ const now = Date.now();
16569
+ if (input.event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
16570
+ const who = String(input.attemptedEmail || input.targetId || "").toLowerCase();
16571
+ const key = `${who}|${input.ip || ""}`;
16572
+ const last = lockouts.get(key);
16573
+ if (last !== void 0 && now - last < LOCKOUT_DEDUP_MS) return false;
16574
+ lockouts.set(key, now);
16575
+ pruneDedup(lockouts, now, LOCKOUT_DEDUP_MS);
16576
+ }
16577
+ queue.push({ ...input, occurredAt: input.occurredAt || new Date(now) });
16578
+ if (queue.length > MAX_QUEUE) {
16579
+ dropped += queue.length - MAX_QUEUE;
16580
+ queue = queue.slice(queue.length - MAX_QUEUE);
16581
+ }
16582
+ schedule();
16583
+ return true;
16584
+ },
16585
+ /**
16586
+ * Queues one Content Manager action of an admin as
16587
+ * `admin.content.<action>` with the entry as target (`targetType` = content
16588
+ * type uid, `targetId` = document id). Opening the same entry (same
16589
+ * admin, type, document and locale) again within 10 minutes, or right
16590
+ * after writing it, is not a new "view".
16591
+ *
16592
+ * @param {{adminUserId: number|string, action: string, kind: 'collection'|'single',
16593
+ * contentType: string, documentId: string|null, locale: string|null,
16594
+ * count: number|null, data?: any}} input Action.
16595
+ * @returns {boolean} Whether the action was queued.
16596
+ */
16597
+ recordContentAction(input) {
16598
+ if (stopped || !input || !CONTENT_ACTIONS.includes(input.action)) return false;
16599
+ const now = Date.now();
16600
+ const key = `${input.adminUserId}|${input.contentType}|${input.documentId || ""}|${input.locale || ""}`;
16601
+ if (input.documentId || input.kind === "single") {
16602
+ if (input.action === "view") {
16603
+ const last = viewed.get(key);
16604
+ if (last !== void 0 && now - last < VIEW_DEDUP_MS) return false;
16605
+ }
16606
+ viewed.delete(key);
16607
+ viewed.set(key, now);
16608
+ pruneDedup(viewed, now, VIEW_DEDUP_MS);
16609
+ }
16610
+ return service.record({
16611
+ event: contentEvent(input.action),
16612
+ actorType: "admin",
16613
+ actorId: input.adminUserId,
16614
+ targetType: input.contentType,
16615
+ targetId: input.documentId,
16616
+ meta: {
16617
+ kind: input.kind,
16618
+ locale: input.locale || null,
16619
+ ...typeof input.count === "number" ? { count: input.count } : {}
16620
+ },
16621
+ entryData: input.data || null
16622
+ });
16623
+ },
16624
+ /**
16625
+ * Writes everything queued. Concurrent calls share one run.
16626
+ *
16627
+ * @returns {Promise<void>}
16628
+ * @sideeffect Inserts rows into the security event table; may call the GeoIP provider.
16629
+ */
16630
+ async flush() {
16631
+ if (flushing) return flushing;
16632
+ if (!queue.length) return void 0;
16633
+ flushing = writeQueued().finally(() => {
16634
+ flushing = null;
16635
+ });
16636
+ return flushing;
16637
+ },
16638
+ /**
16639
+ * Stops recording and writes what is queued (plugin destroy).
16640
+ *
16641
+ * @returns {Promise<void>}
16642
+ */
16643
+ async stop() {
16644
+ stopped = true;
16645
+ if (timer) clearTimeout(timer);
16646
+ timer = null;
16647
+ await service.flush().catch(() => {
16648
+ });
16649
+ },
16650
+ /** @returns {boolean} Whether recording was stopped. */
16651
+ isStopped() {
16652
+ return stopped;
16653
+ },
16654
+ /**
16655
+ * One page of the admin sign-in history, newest first, with names of the
16656
+ * admins involved and the session state of each sign-in.
16657
+ *
16658
+ * @param {{adminId?: number, event?: keyof typeof SIGN_IN_FILTERS, from?: Date|null,
16659
+ * to?: Date|null, page: number, pageSize: number}} query Parsed filters.
16660
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
16661
+ */
16662
+ async listSignIns(query) {
16663
+ const where = signInWhere(query);
16664
+ const [total, rows] = await Promise.all([
16665
+ events().count({ where }),
16666
+ events().findMany({
16667
+ where,
16668
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16669
+ offset: (query.page - 1) * query.pageSize,
16670
+ limit: query.pageSize
16671
+ })
16672
+ ]);
16673
+ return {
16674
+ data: await shapeSignIns(Array.isArray(rows) ? rows : []),
16675
+ meta: {
16676
+ pagination: paginationOf(query, total),
16677
+ recording: await recordingFlags()
16678
+ }
16679
+ };
16680
+ },
16681
+ /**
16682
+ * One page of Content Manager activity, newest first.
16683
+ *
16684
+ * @param {{adminId?: number, action?: string, contentType?: string, from?: Date|null,
16685
+ * to?: Date|null, page: number, pageSize: number}} query Parsed filters.
16686
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
16687
+ */
16688
+ async listContentActivity(query) {
16689
+ const where = activityWhere(query);
16690
+ const [total, rows] = await Promise.all([
16691
+ events().count({ where }),
16692
+ events().findMany({
16693
+ where,
16694
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16695
+ offset: (query.page - 1) * query.pageSize,
16696
+ limit: query.pageSize
16697
+ })
16698
+ ]);
16699
+ return {
16700
+ data: await shapeActivity(Array.isArray(rows) ? rows : []),
16701
+ meta: {
16702
+ pagination: paginationOf(query, total),
16703
+ recording: await recordingFlags(),
16704
+ contentTypes: listContentTypes(),
16705
+ ...query.adminId ? { contentManagerAccess: await service.hasContentManagerAccess(query.adminId) } : {}
16706
+ }
16707
+ };
16708
+ },
16709
+ /**
16710
+ * One export batch (newest first, keyset on id) of either list.
16711
+ *
16712
+ * @param {'sign-ins'|'content'} kind List.
16713
+ * @param {any} query Parsed filters (as for the list).
16714
+ * @param {number|null} cursor Id below which to continue.
16715
+ * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
16716
+ */
16717
+ async exportBatch(kind, query, cursor) {
16718
+ const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
16719
+ const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
16720
+ const rows = await events().findMany({
16721
+ where,
16722
+ orderBy: [{ id: "desc" }],
16723
+ limit: EXPORT_BATCH
16724
+ });
16725
+ const list = Array.isArray(rows) ? rows : [];
16726
+ const data = kind === "sign-ins" ? await shapeSignIns(list) : await shapeActivity(list);
16727
+ const last = list[list.length - 1];
16728
+ return {
16729
+ data,
16730
+ meta: { nextCursor: list.length === EXPORT_BATCH && last ? String(last.id) : null }
16731
+ };
16732
+ },
16733
+ /**
16734
+ * Whether an admin can use the Content Manager: Super Admin, or a role
16735
+ * with any `plugin::content-manager.explorer.*` permission.
16736
+ *
16737
+ * @param {number} adminId Admin id.
16738
+ * @returns {Promise<boolean|null>} Null when the admin does not exist.
16739
+ */
16740
+ async hasContentManagerAccess(adminId) {
16741
+ const user = await strapi2.db.query(ADMIN_USER_UID).findOne({
16742
+ where: { id: adminId },
16743
+ select: ["id"],
16744
+ populate: { roles: { select: ["id", "code"] } }
16745
+ });
16746
+ if (!user) return null;
16747
+ const roles = Array.isArray(user.roles) ? user.roles : [];
16748
+ if (roles.some((role) => role?.code === SUPER_ADMIN_CODE)) return true;
16749
+ const roleIds = roles.map((role) => role.id).filter((id) => id !== void 0);
16750
+ if (!roleIds.length) return false;
16751
+ const count = await strapi2.db.query(PERMISSION_UID).count({
16752
+ where: {
16753
+ role: { id: { $in: roleIds } },
16754
+ action: { $startsWith: "plugin::content-manager.explorer." }
16755
+ }
16756
+ });
16757
+ return Number(count) > 0;
16758
+ },
16759
+ /**
16760
+ * Retention for the whole log: deletes events older than the configured
16761
+ * number of days, and the events of admins that no longer exist (where a
16762
+ * deleted admin signed someone else out, only the actor is cleared).
16763
+ *
16764
+ * @param {{now?: Date}} [options] Clock for tests.
16765
+ * @returns {Promise<{expired: number, orphans: number}>} Deleted rows.
16766
+ * @sideeffect Deletes and updates rows of the security event table.
16767
+ */
16768
+ async cleanup({ now = /* @__PURE__ */ new Date() } = {}) {
16769
+ const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
16770
+ const cutoff = new Date(now.getTime() - options.retentionDays * 24 * 60 * 60 * 1e3);
16771
+ const expired = await deleteOlderThan(cutoff);
16772
+ const admins = await strapi2.db.query(ADMIN_USER_UID).findMany({ select: ["id"] });
16773
+ const existing = (Array.isArray(admins) ? admins : []).map((row) => String(row.id));
16774
+ let orphans = 0;
16775
+ if (existing.length) {
16776
+ const removed = await events().deleteMany({
16777
+ where: {
16778
+ $or: [
16779
+ { targetType: "admin", targetId: { $notNull: true, $notIn: existing } },
16780
+ {
16781
+ actorType: "admin",
16782
+ actorId: { $notNull: true, $notIn: existing },
16783
+ event: { $ne: SECURITY_EVENTS.ADMIN_SESSION_REVOKED }
16784
+ }
16785
+ ]
16786
+ }
16787
+ });
16788
+ orphans = Number(removed?.count || 0);
16789
+ await events().updateMany({
16790
+ where: {
16791
+ event: SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
16792
+ actorType: "admin",
16793
+ actorId: { $notNull: true, $notIn: existing }
16794
+ },
16795
+ data: { actorId: null }
16796
+ });
16797
+ }
16798
+ return { expired, orphans };
16799
+ },
16800
+ /**
16801
+ * Deletes what was recorded about an admin whose account was deleted:
16802
+ * events they did and events about their account. Where they signed
16803
+ * someone else out, the actor reference is cleared and the target keeps
16804
+ * the event.
16805
+ *
16806
+ * @param {number} adminId Deleted admin id.
16807
+ * @returns {Promise<void>}
16808
+ * @sideeffect Deletes and updates rows of the security event table.
16809
+ */
16810
+ async deleteAdminData(adminId) {
16811
+ const id = toAdminId(adminId);
16812
+ if (!id) return;
16813
+ const key = String(id);
16814
+ queue = queue.filter(
16815
+ (entry) => !(entry.actorType === "admin" && String(entry.actorId) === key) && !(entry.targetType === "admin" && String(entry.targetId) === key)
16816
+ );
16817
+ await events().deleteMany({
16818
+ where: {
16819
+ $or: [
16820
+ { targetType: "admin", targetId: key },
16821
+ {
16822
+ actorType: "admin",
16823
+ actorId: key,
16824
+ event: { $ne: SECURITY_EVENTS.ADMIN_SESSION_REVOKED }
16825
+ }
16826
+ ]
16827
+ }
16828
+ });
16829
+ await events().updateMany({
16830
+ where: { event: SECURITY_EVENTS.ADMIN_SESSION_REVOKED, actorType: "admin", actorId: key },
16831
+ data: { actorId: null }
16832
+ });
16833
+ }
16834
+ };
16835
+ function paginationOf(query, total) {
16836
+ const count = Number(total) || 0;
16837
+ return {
16838
+ page: query.page,
16839
+ pageSize: query.pageSize,
16840
+ total: count,
16841
+ pageCount: Math.max(1, Math.ceil(count / query.pageSize))
16842
+ };
16843
+ }
16844
+ function signInWhere(query) {
16845
+ const conditions = [{ event: { $in: [...SIGN_IN_FILTERS[query.event || "all"]] } }];
16846
+ if (query.adminId) conditions.push({ targetType: "admin", targetId: String(query.adminId) });
16847
+ if (query.from) conditions.push({ createdAt: { $gte: query.from } });
16848
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
16849
+ return { $and: conditions };
16850
+ }
16851
+ function activityWhere(query) {
16852
+ const conditions = [
16853
+ {
16854
+ event: query.action && query.action !== "all" ? contentEvent(query.action) : { $in: [...ADMIN_CONTENT_EVENTS] }
16855
+ }
16856
+ ];
16857
+ if (query.adminId) conditions.push({ actorType: "admin", actorId: String(query.adminId) });
16858
+ if (query.contentType) conditions.push({ targetType: query.contentType });
16859
+ if (query.from) conditions.push({ createdAt: { $gte: query.from } });
16860
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
16861
+ return { $and: conditions };
16862
+ }
16863
+ async function recordingFlags() {
16864
+ let settings;
16865
+ try {
16866
+ settings = await getPluginSettings(strapi2);
16867
+ } catch {
16868
+ settings = {};
16869
+ }
16870
+ const options = resolveSecurityLogSettings(settings);
16871
+ return {
16872
+ signIns: options.signIns,
16873
+ contentActivity: options.content,
16874
+ ipAddresses: options.storeIp,
16875
+ anonymizeIp: options.anonymizeIp,
16876
+ retentionDays: options.retentionDays
16877
+ };
16878
+ }
16879
+ function listContentTypes() {
16880
+ return Object.entries(strapi2.contentTypes || {}).filter(([uid, type]) => {
16881
+ const visible = (
16882
+ /** @type {any} */
16883
+ type?.pluginOptions?.["content-manager"]?.visible
16884
+ );
16885
+ return uid.startsWith("api::") && visible !== false;
16886
+ }).map(([uid, type]) => ({
16887
+ uid,
16888
+ name: String(
16889
+ /** @type {any} */
16890
+ type?.info?.displayName || uid
16891
+ ).slice(0, 120),
16892
+ kind: (
16893
+ /** @type {any} */
16894
+ type?.kind === "singleType" ? "single" : "collection"
16895
+ )
16896
+ })).sort((a, b) => a.name.localeCompare(b.name));
16897
+ }
16898
+ async function shapeSignIns(rows) {
16899
+ const admins = await loadAdmins(rows.flatMap((row) => [row.targetId, row.actorId]));
16900
+ const states = await sessionStates(rows);
16901
+ return rows.map((row) => {
16902
+ const meta = toObject(row.meta);
16903
+ const admin = row.targetType === "admin" ? admins.get(Number(row.targetId)) : void 0;
16904
+ const revoked = row.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
16905
+ const actor = revoked ? admins.get(Number(row.actorId)) : void 0;
16906
+ const described = describeUserAgent(row.userAgent || null);
16907
+ const state = states.get(Number(row.id));
16908
+ return {
16909
+ id: Number(row.id),
16910
+ event: row.event,
16911
+ reason: safeReason(meta.reason),
16912
+ provider: safeReason(meta.provider),
16913
+ scope: revoked ? safeReason(meta.scope) : null,
16914
+ at: toIso(row.createdAt),
16915
+ ipAddress: row.ip || null,
16916
+ ipAnonymized: meta.ipAnonymized === true,
16917
+ location: toLocation(row.geo),
16918
+ browser: described.browserName,
16919
+ os: described.osName,
16920
+ deviceType: described.deviceType,
16921
+ admin: admin ? { id: Number(admin.id), name: adminName(admin) } : null,
16922
+ actor: actor ? { id: Number(actor.id), name: adminName(actor) } : null,
16923
+ session: row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && state ? { state: state.state, endedAt: toIso(state.endedAt) } : null
16924
+ };
16925
+ });
16926
+ }
16927
+ async function sessionStates(rows) {
16928
+ const list = rows.filter(
16929
+ (row) => row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && toAdminId(row.targetId)
16930
+ );
16931
+ if (!list.length) return /* @__PURE__ */ new Map();
16932
+ const adminIds = [...new Set(list.map((row) => String(row.targetId)))];
16933
+ const oldest = new Date(
16934
+ Math.min(...list.map((row) => new Date(toIso(row.createdAt) || Date.now()).getTime()))
16935
+ );
16936
+ const later = await events().findMany({
16937
+ select: ["id", "event", "targetId", "actorId", "meta", "createdAt"],
16938
+ where: {
16939
+ targetType: "admin",
16940
+ targetId: { $in: adminIds },
16941
+ event: {
16942
+ $in: [
16943
+ SECURITY_EVENTS.ADMIN_SIGN_IN,
16944
+ SECURITY_EVENTS.ADMIN_SIGN_OUT,
16945
+ SECURITY_EVENTS.ADMIN_SESSION_REVOKED
16946
+ ]
16947
+ },
16948
+ createdAt: { $gte: oldest }
16949
+ },
16950
+ orderBy: [{ createdAt: "asc" }],
16951
+ limit: 5e3
16952
+ });
16953
+ const live = /* @__PURE__ */ new Map();
16954
+ if (strapi2.contentTypes?.[ADMIN_SESSION_UID]) {
16955
+ const now = /* @__PURE__ */ new Date();
16956
+ const sessions = await strapi2.db.query(ADMIN_SESSION_UID).findMany({
16957
+ select: ["userId", "deviceId"],
16958
+ where: {
16959
+ origin: "admin",
16960
+ status: "active",
16961
+ userId: { $in: adminIds },
16962
+ expiresAt: { $gt: now },
16963
+ $or: [{ absoluteExpiresAt: { $null: true } }, { absoluteExpiresAt: { $gt: now } }]
16964
+ },
16965
+ limit: 1e4
16966
+ });
16967
+ for (const session of Array.isArray(sessions) ? sessions : []) {
16968
+ const hash = hashDeviceId(session.deviceId);
16969
+ if (!hash) continue;
16970
+ const key = String(session.userId);
16971
+ if (!live.has(key)) live.set(key, /* @__PURE__ */ new Set());
16972
+ live.get(key)?.add(hash);
16973
+ }
16974
+ }
16975
+ const toEvent = (row) => ({
16976
+ id: Number(row.id),
16977
+ adminId: String(row.targetId),
16978
+ event: row.event,
16979
+ actorId: row.actorId ? String(row.actorId) : null,
16980
+ deviceHash: deviceHashOf(row.meta),
16981
+ at: toIso(row.createdAt) || ""
16982
+ });
16983
+ return deriveSessionStates(
16984
+ list.map(toEvent),
16985
+ (Array.isArray(later) ? later : []).map(toEvent),
16986
+ live
16987
+ );
16988
+ }
16989
+ async function shapeActivity(rows) {
16990
+ const admins = await loadAdmins(rows.map((row) => row.actorId));
16991
+ return rows.map((row) => {
16992
+ const meta = toObject(row.meta);
16993
+ const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
16994
+ const type = strapi2.contentTypes?.[row.targetType];
16995
+ return {
16996
+ id: Number(row.id),
16997
+ action: String(row.event).replace(/^admin\.content\./, ""),
16998
+ at: toIso(row.createdAt),
16999
+ contentType: {
17000
+ uid: row.targetType,
17001
+ name: String(type?.info?.displayName || row.targetType).slice(0, 120),
17002
+ kind: meta.kind === "single" ? "single" : "collection",
17003
+ exists: Boolean(type)
17004
+ },
17005
+ entry: {
17006
+ documentId: row.targetId || null,
17007
+ locale: typeof meta.locale === "string" ? meta.locale : null,
17008
+ title: typeof meta.title === "string" ? meta.title : null,
17009
+ count: typeof meta.count === "number" ? meta.count : null
17010
+ },
17011
+ admin: admin ? { id: Number(admin.id), name: adminName(admin) } : null
17012
+ };
17013
+ });
17014
+ }
17015
+ return service;
17016
+ };
17017
+ module2.exports.EVENT_UID = EVENT_UID;
17018
+ module2.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
17019
+ }
17020
+ });
17021
+
15210
17022
  // server/src/services/index.js
15211
17023
  var require_services = __commonJS({
15212
17024
  "server/src/services/index.js"(exports2, module2) {
@@ -15214,10 +17026,12 @@ var require_services = __commonJS({
15214
17026
  var session = require_session2();
15215
17027
  var geolocation = require_geolocation();
15216
17028
  var notifications = require_notifications();
17029
+ var securityLog = require_security_log();
15217
17030
  module2.exports = {
15218
17031
  session,
15219
17032
  geolocation,
15220
- notifications
17033
+ notifications,
17034
+ "security-log": securityLog
15221
17035
  };
15222
17036
  }
15223
17037
  });