strapi-plugin-magic-sessionmanager 4.20.0 → 4.22.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 (33) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +104 -50
  3. package/dist/admin/{Analytics-B5GnwMtH.js → Analytics-DeDLGiCe.js} +1 -1
  4. package/dist/admin/{Analytics-B-MVQ6dQ.mjs → Analytics-WbCUmkQQ.mjs} +1 -1
  5. package/dist/admin/{App-xBOmg4g9.js → App-Bkv-W0Sv.js} +1640 -2561
  6. package/dist/admin/{App-DzbP5VPQ.mjs → App-C4bihk2K.mjs} +1610 -2531
  7. package/dist/admin/{OnlineUsersWidget-FuPPPCCV.js → OnlineUsersWidget-CSvNe2rC.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Bf3BICmx.mjs → OnlineUsersWidget-q0Z6nbbO.mjs} +1 -1
  9. package/dist/admin/{Settings-hpkloyO6.mjs → Settings-avD0DbXP.mjs} +17 -9
  10. package/dist/admin/{Settings-WRIXHLDa.js → Settings-xokFI5LO.js} +59 -51
  11. package/dist/admin/dashboardModel-BBNRgcEr.mjs +170 -0
  12. package/dist/admin/dashboardModel-D4389iIV.js +169 -0
  13. package/dist/admin/{de-Bzd14FzX.mjs → de-BQlEdBMr.mjs} +104 -4
  14. package/dist/admin/{de-Uqb30N5n.js → de-HcJ19LKI.js} +104 -4
  15. package/dist/admin/{en-CDBcocLk.js → en-DI-98CPM.js} +105 -5
  16. package/dist/admin/{en-DovyVwa5.mjs → en-DzuXWL1W.mjs} +105 -5
  17. package/dist/admin/{es-BygJxl1J.mjs → es-BfyED9YI.mjs} +104 -4
  18. package/dist/admin/{es-DA1X0RPv.js → es-Cm0Eklav.js} +104 -4
  19. package/dist/admin/{fr-CPPA27jW.js → fr-C3nzszsI.js} +104 -4
  20. package/dist/admin/{fr-DONxL73-.mjs → fr-CzFNGWq0.mjs} +104 -4
  21. package/dist/admin/index-6zc5D8eb.mjs +4729 -0
  22. package/dist/admin/index-Dk5Jqe5U.js +4730 -0
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +2 -2
  25. package/dist/admin/{pt-BMuwyaan.js → pt-BPZ6chPT.js} +104 -4
  26. package/dist/admin/{pt-D2yGNz2N.mjs → pt-DmyQnGI_.mjs} +104 -4
  27. package/dist/server/index.js +1048 -67
  28. package/dist/server/index.mjs +1048 -67
  29. package/package.json +1 -1
  30. package/dist/admin/index-DsaGGK7x.mjs +0 -2297
  31. package/dist/admin/index-Q_D-5LlE.js +0 -2298
  32. package/dist/admin/settingsTabs--7IsqMdn.mjs +0 -437
  33. package/dist/admin/settingsTabs-Dxlevody.js +0 -436
@@ -1693,12 +1693,14 @@ var require_impersonation_rules = __commonJS({
1693
1693
  var IMPERSONATION_DEFAULTS = Object.freeze({ impersonationEnabled: false });
1694
1694
  var IMPERSONATION_KEYS = Object.freeze(Object.keys(IMPERSONATION_DEFAULTS));
1695
1695
  var USER_DURATIONS = Object.freeze([15, 30, 60]);
1696
+ var ADMIN_DURATIONS = Object.freeze([15, 30]);
1696
1697
  var REASON_MIN = 3;
1697
1698
  var REASON_MAX = 255;
1698
1699
  var CODE_TTL_MS = 60 * 1e3;
1699
1700
  var IMPERSONATION_HEADER = "X-Magic-Impersonation";
1700
1701
  var CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
1701
1702
  var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1703
+ var ADMIN_ID_PATTERN = /^[1-9][0-9]{0,15}$/;
1702
1704
  var LOOPBACK_HOSTS = Object.freeze(["localhost", "127.0.0.1", "[::1]"]);
1703
1705
  function normalizeImpersonationSettings(stored) {
1704
1706
  return { impersonationEnabled: stored?.impersonationEnabled === true };
@@ -1901,6 +1903,8 @@ var require_impersonation_rules = __commonJS({
1901
1903
  }
1902
1904
  }
1903
1905
  module2.exports = {
1906
+ ADMIN_DURATIONS,
1907
+ ADMIN_ID_PATTERN,
1904
1908
  CODE_PATTERN,
1905
1909
  CODE_TTL_MS,
1906
1910
  DOCUMENT_ID_PATTERN,
@@ -2706,6 +2710,17 @@ var require_register = __commonJS({
2706
2710
  subCategory: "Admin panel",
2707
2711
  pluginName: "magic-sessionmanager"
2708
2712
  },
2713
+ // App-user security activity (4.22): failed and refused sign-ins,
2714
+ // lockouts, new devices, impossible travel, "This wasn't me", data
2715
+ // exports and impersonations of Users & Permissions accounts, with IP
2716
+ // addresses. Separate from plugin access because it shows personal data.
2717
+ {
2718
+ section: "plugins",
2719
+ displayName: "View app-user security activity",
2720
+ uid: "user-activity.read",
2721
+ subCategory: "General",
2722
+ pluginName: "magic-sessionmanager"
2723
+ },
2709
2724
  // Protected settings (4.17): IP location lookup (whether and where IP
2710
2725
  // addresses are sent), team notification webhooks (the URLs are
2711
2726
  // secrets) and the security log. The other settings stay on `access`.
@@ -2735,6 +2750,17 @@ var require_register = __commonJS({
2735
2750
  uid: "impersonate.users",
2736
2751
  subCategory: "Impersonation",
2737
2752
  pluginName: "magic-sessionmanager"
2753
+ },
2754
+ // "View as admin" (4.20): a read-only preview of which content types and
2755
+ // actions another admin can use. Never a Super Admin, never oneself, and
2756
+ // for non-Super-Admins only admins whose permissions are a subset of
2757
+ // their own.
2758
+ {
2759
+ section: "plugins",
2760
+ displayName: "View as admin (read-only permission preview)",
2761
+ uid: "impersonate.admins",
2762
+ subCategory: "Impersonation",
2763
+ pluginName: "magic-sessionmanager"
2738
2764
  }
2739
2765
  ]);
2740
2766
  disableGraphqlShadowCrud(strapi2, log);
@@ -12104,9 +12130,15 @@ var require_admin = __commonJS({
12104
12130
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
12105
12131
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
12106
12132
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12133
+ var USER_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.user-activity.read";
12107
12134
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12108
12135
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12109
12136
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
12137
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
12138
+ var impersonationListPolicy = () => [
12139
+ ...adminPolicy(),
12140
+ "plugin::magic-sessionmanager.can-impersonate"
12141
+ ];
12110
12142
  var adminPolicy = () => [
12111
12143
  "admin::isAuthenticatedAdmin",
12112
12144
  {
@@ -12360,6 +12392,27 @@ var require_admin = __commonJS({
12360
12392
  description: "Get one export batch of Content Manager activity of admins (admin)"
12361
12393
  }
12362
12394
  },
12395
+ // ===================== APP-USER SECURITY ACTIVITY (4.22) =====================
12396
+ {
12397
+ method: "GET",
12398
+ path: "/user-activity",
12399
+ handler: "user-activity.list",
12400
+ config: {
12401
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
12402
+ middlewares: adminReadRateLimit(),
12403
+ description: "List the security activity of app users (admin)"
12404
+ }
12405
+ },
12406
+ {
12407
+ method: "GET",
12408
+ path: "/user-activity/export",
12409
+ handler: "user-activity.export",
12410
+ config: {
12411
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
12412
+ middlewares: adminReadRateLimit(),
12413
+ description: "Get one export batch of the security activity of app users (admin)"
12414
+ }
12415
+ },
12363
12416
  // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
12364
12417
  {
12365
12418
  method: "GET",
@@ -12471,12 +12524,36 @@ var require_admin = __commonJS({
12471
12524
  ]
12472
12525
  }
12473
12526
  },
12527
+ {
12528
+ method: "POST",
12529
+ path: "/impersonation/admins/:adminId/preview",
12530
+ handler: "impersonation.previewAdmin",
12531
+ config: {
12532
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12533
+ // Ten previews per ten minutes per admin.
12534
+ middlewares: [
12535
+ {
12536
+ name: "plugin::magic-sessionmanager.rate-limit",
12537
+ config: { max: 10, window: 10 * 60 * 1e3 }
12538
+ }
12539
+ ]
12540
+ }
12541
+ },
12542
+ {
12543
+ method: "GET",
12544
+ path: "/impersonation/previews/:id",
12545
+ handler: "impersonation.getPreview",
12546
+ config: {
12547
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12548
+ middlewares: adminReadRateLimit()
12549
+ }
12550
+ },
12474
12551
  {
12475
12552
  method: "GET",
12476
12553
  path: "/impersonation/active",
12477
12554
  handler: "impersonation.listActive",
12478
12555
  config: {
12479
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12556
+ policies: impersonationListPolicy(),
12480
12557
  middlewares: adminReadRateLimit()
12481
12558
  }
12482
12559
  },
@@ -12485,7 +12562,7 @@ var require_admin = __commonJS({
12485
12562
  path: "/impersonation/:id/end",
12486
12563
  handler: "impersonation.end",
12487
12564
  config: {
12488
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12565
+ policies: impersonationListPolicy(),
12489
12566
  middlewares: adminSignOutRateLimit()
12490
12567
  }
12491
12568
  },
@@ -16690,25 +16767,66 @@ var require_admin_sessions2 = __commonJS({
16690
16767
  }
16691
16768
  });
16692
16769
 
16770
+ // server/src/utils/event-query.js
16771
+ var require_event_query = __commonJS({
16772
+ "server/src/utils/event-query.js"(exports2, module2) {
16773
+ "use strict";
16774
+ var { z } = require("@strapi/utils");
16775
+ var { parseInput } = require_admin_sessions();
16776
+ var { sendServerError, sendValidationError } = require_http_errors();
16777
+ var MAX_PAGE_SIZE = 100;
16778
+ 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();
16779
+ var periodAndPaging = () => ({
16780
+ from: dateField("from"),
16781
+ to: dateField("to"),
16782
+ page: z.coerce.number().int().min(1).max(1e6).default(1),
16783
+ pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16784
+ });
16785
+ var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16786
+ async function handleEventQuery(ctx, schema, run, { log, logPrefix, operation, failureMessage }) {
16787
+ const parsed = parseInput(schema, ctx.query);
16788
+ if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16789
+ const query = parsed.value;
16790
+ if (query.from && query.to && query.from > query.to) {
16791
+ return sendValidationError(ctx, "Invalid query", [
16792
+ { path: ["from"], message: "from must not be after to" }
16793
+ ]);
16794
+ }
16795
+ try {
16796
+ ctx.body = await run(query);
16797
+ return ctx.body;
16798
+ } catch (error) {
16799
+ log.error(
16800
+ `${logPrefix}: ${operation} failed`,
16801
+ /** @type {any} */
16802
+ error?.name || "Error"
16803
+ );
16804
+ return sendServerError(ctx, 500, failureMessage);
16805
+ }
16806
+ }
16807
+ module2.exports = {
16808
+ MAX_PAGE_SIZE,
16809
+ cursorField,
16810
+ dateField,
16811
+ handleEventQuery,
16812
+ periodAndPaging
16813
+ };
16814
+ }
16815
+ });
16816
+
16693
16817
  // server/src/controllers/admin-activity.js
16694
16818
  var require_admin_activity = __commonJS({
16695
16819
  "server/src/controllers/admin-activity.js"(exports2, module2) {
16696
16820
  "use strict";
16697
16821
  var { z } = require("@strapi/utils");
16698
16822
  var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
16699
- var { parseInput } = require_admin_sessions();
16700
- var { sendServerError, sendValidationError } = require_http_errors();
16823
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
16701
16824
  var { createLogger } = require_logger();
16702
16825
  var { callerCan } = require_settings_access();
16703
- var MAX_PAGE_SIZE = 100;
16704
16826
  var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
16705
- 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();
16706
16827
  var common = {
16707
16828
  adminId: adminIdField,
16708
- from: dateField("from"),
16709
- to: dateField("to"),
16710
- page: z.coerce.number().int().min(1).max(1e6).default(1),
16711
- pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16829
+ ...periodAndPaging()
16712
16830
  };
16713
16831
  var signInQuerySchema = z.strictObject({
16714
16832
  ...common,
@@ -16728,7 +16846,6 @@ var require_admin_activity = __commonJS({
16728
16846
  "contentType must be a content type uid"
16729
16847
  ).optional()
16730
16848
  });
16731
- var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16732
16849
  var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
16733
16850
  cursor: cursorField
16734
16851
  });
@@ -16761,27 +16878,12 @@ var require_admin_activity = __commonJS({
16761
16878
  } catch {
16762
16879
  }
16763
16880
  };
16764
- const handle = async (ctx, schema, run, operation) => {
16765
- const parsed = parseInput(schema, ctx.query);
16766
- if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16767
- const query = parsed.value;
16768
- if (query.from && query.to && query.from > query.to) {
16769
- return sendValidationError(ctx, "Invalid query", [
16770
- { path: ["from"], message: "from must not be after to" }
16771
- ]);
16772
- }
16773
- try {
16774
- ctx.body = await run(query);
16775
- return ctx.body;
16776
- } catch (error) {
16777
- log.error(
16778
- `Admin activity: ${operation} failed`,
16779
- /** @type {any} */
16780
- error?.name || "Error"
16781
- );
16782
- return sendServerError(ctx, 500, "Admin activity could not be loaded.");
16783
- }
16784
- };
16881
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
16882
+ log,
16883
+ logPrefix: "Admin activity",
16884
+ operation,
16885
+ failureMessage: "Admin activity could not be loaded."
16886
+ });
16785
16887
  return {
16786
16888
  /**
16787
16889
  * One page of the admin sign-in history: sign-ins, failed attempts,
@@ -17347,6 +17449,228 @@ var require_webhooks = __commonJS({
17347
17449
  }
17348
17450
  });
17349
17451
 
17452
+ // server/src/utils/permission-subset.js
17453
+ var require_permission_subset = __commonJS({
17454
+ "server/src/utils/permission-subset.js"(exports2, module2) {
17455
+ "use strict";
17456
+ function grantsNothing(permission) {
17457
+ const fields = permission?.properties?.fields;
17458
+ return Array.isArray(fields) && fields.length === 0;
17459
+ }
17460
+ function parametersKey(value) {
17461
+ const normalize = (input) => {
17462
+ if (Array.isArray(input)) {
17463
+ return input.every((item) => typeof item === "string") ? [...new Set(input)].sort() : input.map(normalize);
17464
+ }
17465
+ if (input && typeof input === "object") {
17466
+ return Object.fromEntries(
17467
+ Object.keys(input).filter((key) => input[key] !== void 0).sort().map((key) => [key, normalize(input[key])])
17468
+ );
17469
+ }
17470
+ return input;
17471
+ };
17472
+ return JSON.stringify(normalize(value ?? {}));
17473
+ }
17474
+ function coversValue(held, property, value) {
17475
+ const allowed = held.properties?.[property];
17476
+ if (allowed === void 0 || allowed === null) return true;
17477
+ if (value === null || !Array.isArray(allowed)) return false;
17478
+ return allowed.some(
17479
+ (entry) => entry === value || property === "fields" && value.startsWith(`${entry}.`)
17480
+ );
17481
+ }
17482
+ function coversCondition(held, condition) {
17483
+ const conditions = held.conditions ?? [];
17484
+ if (conditions.length === 0) return true;
17485
+ return condition !== null && conditions.includes(condition);
17486
+ }
17487
+ function isPermissionCovered(requested, held) {
17488
+ if (grantsNothing(requested)) return true;
17489
+ const subject = requested.subject ?? null;
17490
+ const parameters = parametersKey(requested.actionParameters);
17491
+ const matching = held.filter(
17492
+ (permission) => permission.action === requested.action && (permission.subject ?? null) === subject && parametersKey(permission.actionParameters) === parameters && !grantsNothing(permission)
17493
+ );
17494
+ if (matching.length === 0) return false;
17495
+ const properties = [
17496
+ .../* @__PURE__ */ new Set([
17497
+ ...Object.keys(requested.properties ?? {}),
17498
+ ...matching.flatMap((permission) => Object.keys(permission.properties ?? {}))
17499
+ ])
17500
+ ];
17501
+ const dimensions = [];
17502
+ for (const property of properties) {
17503
+ const values = requested.properties?.[property];
17504
+ if (!Array.isArray(values)) dimensions.push({ property, values: [null] });
17505
+ else if (values.length > 0) {
17506
+ dimensions.push({ property, values: [...new Set(values.map(String))] });
17507
+ }
17508
+ }
17509
+ const conditions = (requested.conditions ?? []).length === 0 ? [null] : [...new Set(requested.conditions)];
17510
+ const walk = (index, picked, condition) => {
17511
+ if (index === dimensions.length) {
17512
+ return matching.some(
17513
+ (permission) => Object.entries(picked).every(
17514
+ ([property2, value]) => coversValue(permission, property2, value)
17515
+ ) && coversCondition(permission, condition)
17516
+ );
17517
+ }
17518
+ const { property, values } = dimensions[index];
17519
+ return values.every((value) => walk(index + 1, { ...picked, [property]: value }, condition));
17520
+ };
17521
+ return conditions.every((condition) => walk(0, {}, condition));
17522
+ }
17523
+ function uncoveredPermissions(target, actor) {
17524
+ return target.filter((permission) => !isPermissionCovered(permission, actor));
17525
+ }
17526
+ function toEnforced(permissions, context) {
17527
+ const out = [];
17528
+ for (const permission of permissions) {
17529
+ const conditions = permission.conditions ?? [];
17530
+ const registered = conditions.filter((id) => context.isConditionRegistered(id));
17531
+ if (conditions.length > 0 && registered.length === 0) continue;
17532
+ const properties = { ...permission.properties ?? {} };
17533
+ if (context.appliesLocales(permission)) {
17534
+ if (properties.locales === void 0) properties.locales = [];
17535
+ } else {
17536
+ delete properties.locales;
17537
+ }
17538
+ out.push({ ...permission, conditions: registered, properties });
17539
+ }
17540
+ return out;
17541
+ }
17542
+ module2.exports = { isPermissionCovered, toEnforced, uncoveredPermissions };
17543
+ }
17544
+ });
17545
+
17546
+ // server/src/utils/admin-preview.js
17547
+ var require_admin_preview = __commonJS({
17548
+ "server/src/utils/admin-preview.js"(exports2, module2) {
17549
+ "use strict";
17550
+ var { toEnforced, uncoveredPermissions } = require_permission_subset();
17551
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
17552
+ function isSuperAdmin(user) {
17553
+ return (user?.roles || []).some((role) => role?.code === SUPER_ADMIN_CODE);
17554
+ }
17555
+ async function loadAdmin(strapi2, id) {
17556
+ return strapi2.db.query("admin::user").findOne({
17557
+ where: { id },
17558
+ select: ["id", "firstname", "lastname", "username", "email", "isActive"],
17559
+ populate: { roles: { select: ["id", "name", "code"] } }
17560
+ });
17561
+ }
17562
+ async function effectivePermissions(strapi2, user) {
17563
+ const service = strapi2.admin.services.permission;
17564
+ const raw = await service.findUserPermissions(user);
17565
+ const appliesCache = /* @__PURE__ */ new Map();
17566
+ for (const permission of raw) {
17567
+ const key = `${permission.action}::${permission.subject}`;
17568
+ if (appliesCache.has(key)) continue;
17569
+ let applies;
17570
+ try {
17571
+ applies = Boolean(permission.subject) && service.actionProvider.has(permission.action) && await service.actionProvider.appliesToProperty(
17572
+ "locales",
17573
+ permission.action,
17574
+ permission.subject
17575
+ ) === true;
17576
+ } catch {
17577
+ applies = false;
17578
+ }
17579
+ appliesCache.set(key, applies);
17580
+ }
17581
+ return toEnforced(raw, {
17582
+ isConditionRegistered: (id) => {
17583
+ try {
17584
+ return service.conditionProvider.has(id) === true;
17585
+ } catch {
17586
+ return false;
17587
+ }
17588
+ },
17589
+ appliesLocales: (permission) => appliesCache.get(`${permission.action}::${permission.subject}`) === true
17590
+ });
17591
+ }
17592
+ async function previewRefusal(strapi2, actor, target) {
17593
+ if (String(actor.id) === String(target.id)) return { reason: "self" };
17594
+ if (isSuperAdmin(target)) return { reason: "super-admin" };
17595
+ if (isSuperAdmin(actor)) return null;
17596
+ const [held, wanted] = await Promise.all([
17597
+ effectivePermissions(strapi2, actor),
17598
+ effectivePermissions(strapi2, target)
17599
+ ]);
17600
+ const uncovered = uncoveredPermissions(wanted, held);
17601
+ return uncovered.length > 0 ? { reason: "not-subset", uncovered: uncovered.length } : null;
17602
+ }
17603
+ function contentAction(action) {
17604
+ const match = /^plugin::content-manager\.explorer\.([a-z-]+)$/.exec(action);
17605
+ return match ? match[1] : action;
17606
+ }
17607
+ async function buildPreview(strapi2, target) {
17608
+ const permissions = await effectivePermissions(strapi2, target);
17609
+ const provider = strapi2.admin.services.permission.actionProvider;
17610
+ const types = /* @__PURE__ */ new Map();
17611
+ const other = [];
17612
+ for (const permission of permissions) {
17613
+ const contentType = permission.subject ? strapi2.contentTypes?.[permission.subject] : null;
17614
+ if (contentType && permission.action.startsWith("plugin::content-manager.explorer.")) {
17615
+ const entry = types.get(permission.subject) || {
17616
+ uid: permission.subject,
17617
+ name: String(contentType.info?.displayName || permission.subject).slice(0, 120),
17618
+ kind: contentType.kind === "singleType" ? "single" : "collection",
17619
+ actions: []
17620
+ };
17621
+ const fields = permission.properties?.fields;
17622
+ const locales = permission.properties?.locales;
17623
+ entry.actions.push({
17624
+ action: contentAction(permission.action),
17625
+ fields: Array.isArray(fields) ? fields.length : null,
17626
+ locales: Array.isArray(locales) ? locales.slice(0, 20) : null,
17627
+ conditions: (permission.conditions || []).slice(0, 10)
17628
+ });
17629
+ types.set(permission.subject, entry);
17630
+ continue;
17631
+ }
17632
+ let definition;
17633
+ try {
17634
+ definition = provider.get(permission.action);
17635
+ } catch {
17636
+ definition = null;
17637
+ }
17638
+ other.push({
17639
+ action: permission.action,
17640
+ name: String(definition?.displayName || permission.action).slice(0, 160),
17641
+ section: String(definition?.section || "other"),
17642
+ scope: definition?.pluginName ? String(definition.pluginName) : null
17643
+ });
17644
+ }
17645
+ const order = ["create", "read", "update", "delete", "publish"];
17646
+ const contentTypes2 = [...types.values()].map((entry) => ({
17647
+ ...entry,
17648
+ actions: entry.actions.sort(
17649
+ (a, b) => (order.indexOf(a.action) + 1 || 99) - (order.indexOf(b.action) + 1 || 99) || a.action.localeCompare(b.action)
17650
+ )
17651
+ })).sort((a, b) => a.name.localeCompare(b.name));
17652
+ other.sort((a, b) => a.section.localeCompare(b.section) || a.name.localeCompare(b.name));
17653
+ return {
17654
+ admin: {
17655
+ id: target.id,
17656
+ name: [target.firstname, target.lastname].filter(Boolean).join(" ").trim() || target.username || "",
17657
+ active: target.isActive === true,
17658
+ roles: (target.roles || []).map((role) => ({ name: role.name }))
17659
+ },
17660
+ contentTypes: contentTypes2,
17661
+ otherPermissions: other.slice(0, 500)
17662
+ };
17663
+ }
17664
+ module2.exports = {
17665
+ buildPreview,
17666
+ effectivePermissions,
17667
+ isSuperAdmin,
17668
+ loadAdmin,
17669
+ previewRefusal
17670
+ };
17671
+ }
17672
+ });
17673
+
17350
17674
  // server/src/services/impersonation.js
17351
17675
  var require_impersonation = __commonJS({
17352
17676
  "server/src/services/impersonation.js"(exports2, module2) {
@@ -17358,7 +17682,10 @@ var require_impersonation = __commonJS({
17358
17682
  var { getPluginSettings } = require_settings_loader();
17359
17683
  var { getNativeSessionManager } = require_native_session_manager();
17360
17684
  var { REVOCATION_UID } = require_session_revocation();
17685
+ var { buildPreview, loadAdmin, previewRefusal } = require_admin_preview();
17361
17686
  var {
17687
+ ADMIN_DURATIONS,
17688
+ ADMIN_ID_PATTERN,
17362
17689
  CODE_PATTERN,
17363
17690
  CODE_TTL_MS,
17364
17691
  DOCUMENT_ID_PATTERN,
@@ -17489,6 +17816,7 @@ var require_impersonation = __commonJS({
17489
17816
  handoff: frontend ? "frontend" : "token",
17490
17817
  frontendOrigin: frontend ? frontend.origin : null,
17491
17818
  durations: [...USER_DURATIONS],
17819
+ adminDurations: [...ADMIN_DURATIONS],
17492
17820
  mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
17493
17821
  };
17494
17822
  },
@@ -17614,6 +17942,137 @@ var require_impersonation = __commonJS({
17614
17942
  handoff
17615
17943
  };
17616
17944
  },
17945
+ /**
17946
+ * Starts a read-only permission preview of another admin ("View as
17947
+ * admin"). No session or token is created; the preview can be read by
17948
+ * the admin who started it until it ends.
17949
+ *
17950
+ * @param {{actor: any, adminId: unknown, body: unknown, canReadAdmins: boolean}} input
17951
+ * Caller (with roles), target id and request body.
17952
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17953
+ * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17954
+ * or not a subset of the caller's permissions; 404 unknown admin.
17955
+ * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17956
+ */
17957
+ async previewAdmin({ actor, adminId, body, canReadAdmins }) {
17958
+ const actorId = String(actor.id);
17959
+ const refuse = (reason, status, message, extra = {}) => {
17960
+ service.recordRefused({ actorId, targetType: "admin", targetId: adminId, reason });
17961
+ return new ImpersonationError(status, message, { reason, ...extra });
17962
+ };
17963
+ if (!await service.isEnabled()) {
17964
+ throw refuse("disabled", 403, "Impersonation is turned off");
17965
+ }
17966
+ if (typeof adminId !== "string" || !ADMIN_ID_PATTERN.test(adminId)) {
17967
+ throw new ImpersonationError(404, "Admin not found");
17968
+ }
17969
+ const { value, errors: fieldErrors } = validateStartBody(body, {
17970
+ durations: ADMIN_DURATIONS,
17971
+ notify: false
17972
+ });
17973
+ if (!value) {
17974
+ throw new ImpersonationError(400, "Invalid preview request", {
17975
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
17976
+ });
17977
+ }
17978
+ const [caller, target] = await Promise.all([
17979
+ loadAdmin(strapi2, actor.id),
17980
+ loadAdmin(strapi2, Number(adminId))
17981
+ ]);
17982
+ if (!target) throw new ImpersonationError(404, "Admin not found");
17983
+ const refusal = await previewRefusal(strapi2, caller || actor, target);
17984
+ if (refusal) {
17985
+ const messages = {
17986
+ self: "You cannot view yourself as another admin",
17987
+ "super-admin": "Super Admins cannot be viewed as another admin",
17988
+ "not-subset": "This admin has permissions that you do not have"
17989
+ };
17990
+ throw refuse(
17991
+ refusal.reason,
17992
+ 403,
17993
+ messages[refusal.reason],
17994
+ refusal.uncovered ? { uncovered: refusal.uncovered } : {}
17995
+ );
17996
+ }
17997
+ await service.sweep();
17998
+ const now = /* @__PURE__ */ new Date();
17999
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
18000
+ const row = await query().create({
18001
+ data: {
18002
+ targetType: "admin",
18003
+ targetId: String(target.id),
18004
+ actorId,
18005
+ state: "active",
18006
+ reason: value.reason,
18007
+ durationMinutes: value.durationMinutes,
18008
+ handoff: "preview",
18009
+ notifyUser: false,
18010
+ startedAt: now,
18011
+ expiresAt
18012
+ }
18013
+ });
18014
+ record({
18015
+ event: EVENTS.STARTED,
18016
+ actorType: "admin",
18017
+ actorId,
18018
+ targetType: "admin",
18019
+ targetId: String(target.id),
18020
+ meta: {
18021
+ reason: value.reason,
18022
+ durationMinutes: value.durationMinutes,
18023
+ handoff: "preview"
18024
+ }
18025
+ });
18026
+ const preview = await buildPreview(strapi2, target);
18027
+ if (!canReadAdmins) preview.admin.name = "";
18028
+ return {
18029
+ impersonation: service.toDto(row, {
18030
+ admins: /* @__PURE__ */ new Map([
18031
+ [String(target.id), canReadAdmins ? target : null],
18032
+ [actorId, caller || actor]
18033
+ ]),
18034
+ viewer: actor
18035
+ }),
18036
+ preview
18037
+ };
18038
+ },
18039
+ /**
18040
+ * The preview of a running admin preview, for the admin who started it.
18041
+ * An expired one is ended and answers 404 like an unknown one.
18042
+ *
18043
+ * @param {{id: unknown, viewer: any, canReadAdmins: boolean}} input Preview id and caller.
18044
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
18045
+ * @throws {ImpersonationError} 404 unknown, ended, expired or started by someone else.
18046
+ */
18047
+ async getPreview({ id, viewer, canReadAdmins }) {
18048
+ if (typeof id !== "string" || !DOCUMENT_ID_PATTERN.test(id)) {
18049
+ throw new ImpersonationError(404, "Preview not found");
18050
+ }
18051
+ const row = await query().findOne({
18052
+ where: { documentId: id, targetType: "admin", state: "active" }
18053
+ });
18054
+ if (!row || String(row.actorId) !== String(viewer.id)) {
18055
+ throw new ImpersonationError(404, "Preview not found");
18056
+ }
18057
+ if (new Date(row.expiresAt).getTime() <= Date.now()) {
18058
+ await service.end(row.documentId, { reason: "expired" });
18059
+ throw new ImpersonationError(404, "Preview not found");
18060
+ }
18061
+ const target = await loadAdmin(strapi2, Number(row.targetId));
18062
+ if (!target) {
18063
+ await service.end(row.documentId, { reason: "failed", silent: true });
18064
+ throw new ImpersonationError(404, "Preview not found");
18065
+ }
18066
+ const preview = await buildPreview(strapi2, target);
18067
+ if (!canReadAdmins) preview.admin.name = "";
18068
+ return {
18069
+ impersonation: service.toDto(row, {
18070
+ admins: /* @__PURE__ */ new Map([[String(target.id), canReadAdmins ? target : null]]),
18071
+ viewer
18072
+ }),
18073
+ preview
18074
+ };
18075
+ },
17617
18076
  /**
17618
18077
  * Mints the short-lived credential of an impersonation and links its
17619
18078
  * Magic session row.
@@ -17858,12 +18317,15 @@ var require_impersonation = __commonJS({
17858
18317
  return ended;
17859
18318
  },
17860
18319
  /**
17861
- * Active impersonations of the given target types, newest first.
18320
+ * Active impersonations of the given target types, newest first. Admin
18321
+ * names are shown only to callers who may read admin users (as in the
18322
+ * Admin panel view); the caller's own name always.
17862
18323
  *
17863
- * @param {{targetTypes: Array<'user'|'admin'>, viewer: any}} input Kinds the caller may see.
18324
+ * @param {{targetTypes: Array<'user'|'admin'>, viewer: any, canReadAdmins?: boolean}} input
18325
+ * Kinds the caller may see.
17864
18326
  * @returns {Promise<object[]>} DTOs.
17865
18327
  */
17866
- async listActive({ targetTypes, viewer }) {
18328
+ async listActive({ targetTypes, viewer, canReadAdmins = true }) {
17867
18329
  if (!targetTypes.length) return [];
17868
18330
  await service.sweep();
17869
18331
  const rows = await query().findMany({
@@ -17882,7 +18344,11 @@ var require_impersonation = __commonJS({
17882
18344
  select: ["documentId", "username", "email"]
17883
18345
  }) : [];
17884
18346
  const admins = adminIds.length ? await strapi2.db.query("admin::user").findMany({
17885
- where: { id: { $in: adminIds } },
18347
+ where: {
18348
+ id: {
18349
+ $in: canReadAdmins ? adminIds : adminIds.filter((id) => String(id) === String(viewer?.id))
18350
+ }
18351
+ },
17886
18352
  select: ["id", "firstname", "lastname", "username", "email"]
17887
18353
  }) : [];
17888
18354
  const context = {
@@ -17927,18 +18393,20 @@ var require_impersonation = __commonJS({
17927
18393
  * Loads one impersonation for the request guard (5-second cache).
17928
18394
  *
17929
18395
  * @param {string} documentId Impersonation id.
17930
- * @returns {Promise<{id: string, actorId: string, state: string, expiresAt: number}|null>}
18396
+ * @returns {Promise<{id: string, actorId: string, targetId: string|null, state: string,
18397
+ * expiresAt: number}|null>}
17931
18398
  */
17932
18399
  async loadForGuard(documentId) {
17933
18400
  const cached = recordCache.get(documentId);
17934
18401
  if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
17935
18402
  const row = await query().findOne({
17936
18403
  where: { documentId, targetType: "user" },
17937
- select: ["documentId", "actorId", "state", "expiresAt"]
18404
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt"]
17938
18405
  });
17939
18406
  const value = row ? {
17940
18407
  id: row.documentId,
17941
18408
  actorId: row.actorId,
18409
+ targetId: typeof row.targetId === "string" ? row.targetId : null,
17942
18410
  state: row.state,
17943
18411
  expiresAt: new Date(row.expiresAt).getTime()
17944
18412
  } : null;
@@ -17985,7 +18453,10 @@ var require_impersonation = __commonJS({
17985
18453
  * Records a refused Content API call made while impersonating (one event
17986
18454
  * per impersonation and reason per minute).
17987
18455
  *
17988
- * @param {{id: string, actorId: string}} impersonation Impersonation.
18456
+ * The impersonated user is the target (since 4.22), so the refusal shows
18457
+ * in that user's security activity and is deleted with the account.
18458
+ *
18459
+ * @param {{id: string, actorId: string, targetId?: string|null}} impersonation Impersonation.
17989
18460
  * @param {string} reason Refusal reason.
17990
18461
  * @returns {void}
17991
18462
  */
@@ -18000,7 +18471,7 @@ var require_impersonation = __commonJS({
18000
18471
  actorType: "admin",
18001
18472
  actorId: impersonation.actorId,
18002
18473
  targetType: "user",
18003
- targetId: null,
18474
+ targetId: impersonation.targetId || null,
18004
18475
  meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
18005
18476
  });
18006
18477
  },
@@ -18054,6 +18525,7 @@ var require_impersonation2 = __commonJS({
18054
18525
  var { ImpersonationError } = require_impersonation();
18055
18526
  var { sendServerError } = require_http_errors();
18056
18527
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18528
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
18057
18529
  function callerCan(ctx, action) {
18058
18530
  try {
18059
18531
  return ctx?.state?.userAbility?.can?.(action) === true;
@@ -18062,7 +18534,10 @@ var require_impersonation2 = __commonJS({
18062
18534
  }
18063
18535
  }
18064
18536
  function visibleTargetTypes(ctx) {
18065
- return callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [];
18537
+ return [
18538
+ ...callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [],
18539
+ ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) ? ["admin"] : []
18540
+ ];
18066
18541
  }
18067
18542
  var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
18068
18543
  async function respond(ctx, operation, handler) {
@@ -18135,17 +18610,19 @@ var require_impersonation2 = __commonJS({
18135
18610
  },
18136
18611
  /**
18137
18612
  * Active impersonations the caller may see: app users with
18138
- * `impersonate.users`.
18613
+ * `impersonate.users`, admin previews with `impersonate.admins`. Admin
18614
+ * names need `admin::users.read`, as in the Admin panel view.
18139
18615
  *
18140
18616
  * @route GET /magic-sessionmanager/impersonation/active
18141
- * @auth Admin JWT or admin API token; `access` + `impersonate.users`.
18617
+ * @auth Admin JWT or admin API token; `access` + one of the impersonate actions.
18142
18618
  * @returns {Promise<void>} `{ data: Impersonation[] }` (at most 100).
18143
18619
  */
18144
18620
  async listActive(ctx) {
18145
18621
  return respond(ctx, "list", async () => {
18146
18622
  const data = await service().listActive({
18147
18623
  targetTypes: visibleTargetTypes(ctx),
18148
- viewer: ctx.state.user
18624
+ viewer: ctx.state.user,
18625
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18149
18626
  });
18150
18627
  ctx.body = { data };
18151
18628
  });
@@ -18154,7 +18631,8 @@ var require_impersonation2 = __commonJS({
18154
18631
  * Ends an active impersonation now.
18155
18632
  *
18156
18633
  * @route POST /magic-sessionmanager/impersonation/:id/end
18157
- * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind.
18634
+ * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind
18635
+ * (`impersonate.users` for app users, `impersonate.admins` for admin previews).
18158
18636
  * @returns {Promise<void>} `{ data: { ended: boolean } }`.
18159
18637
  * Answers 404 for an unknown id or a kind the caller may not see.
18160
18638
  * @sideeffect Revokes the credential; logs `impersonation.ended`.
@@ -18173,6 +18651,54 @@ var require_impersonation2 = __commonJS({
18173
18651
  ctx.body = { data: { ended } };
18174
18652
  });
18175
18653
  },
18654
+ /**
18655
+ * Starts a read-only permission preview of another admin ("View as
18656
+ * admin"): which content types and actions they can use. No session or
18657
+ * token is created.
18658
+ *
18659
+ * @route POST /magic-sessionmanager/impersonation/admins/:adminId/preview
18660
+ * @auth Admin JWT only (admin API tokens are refused); `access` + `impersonate.admins`.
18661
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30 }`.
18662
+ * @returns {Promise<void>} 201 `{ data: { impersonation, preview } }`. Answers 403 with
18663
+ * `details.reason` `disabled`, `api-token`, `self`, `super-admin` or `not-subset`,
18664
+ * 400 for an invalid body and 404 for an unknown admin.
18665
+ * @sideeffect Creates a preview row; logs `impersonation.started` or `.refused`.
18666
+ */
18667
+ async previewAdmin(ctx) {
18668
+ ctx.set("Cache-Control", "no-store");
18669
+ return respond(ctx, "preview", async () => {
18670
+ const { adminId } = ctx.params;
18671
+ requirePerson(ctx, "admin", adminId);
18672
+ const result = await service().previewAdmin({
18673
+ actor: ctx.state.user,
18674
+ adminId,
18675
+ body: ctx.request.body,
18676
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18677
+ });
18678
+ ctx.status = 201;
18679
+ ctx.body = { data: result };
18680
+ });
18681
+ },
18682
+ /**
18683
+ * Reads a running admin preview; only the admin who started it.
18684
+ *
18685
+ * @route GET /magic-sessionmanager/impersonation/previews/:id
18686
+ * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
18687
+ * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
18688
+ * expired or started by someone else.
18689
+ */
18690
+ async getPreview(ctx) {
18691
+ ctx.set("Cache-Control", "no-store");
18692
+ return respond(ctx, "preview", async () => {
18693
+ ctx.body = {
18694
+ data: await service().getPreview({
18695
+ id: ctx.params.id,
18696
+ viewer: ctx.state.user,
18697
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18698
+ })
18699
+ };
18700
+ });
18701
+ },
18176
18702
  /**
18177
18703
  * Exchanges a one-time hand-off code for the impersonation credential.
18178
18704
  * Public on purpose: the code is the credential (32 random bytes, stored
@@ -18199,6 +18725,266 @@ var require_impersonation2 = __commonJS({
18199
18725
  };
18200
18726
  };
18201
18727
  module2.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
18728
+ module2.exports.IMPERSONATE_ADMINS_ACTION = IMPERSONATE_ADMINS_ACTION;
18729
+ }
18730
+ });
18731
+
18732
+ // server/src/utils/user-activity-model.js
18733
+ var require_user_activity_model = __commonJS({
18734
+ "server/src/utils/user-activity-model.js"(exports2, module2) {
18735
+ "use strict";
18736
+ var { REFUSAL_REASONS, SECURITY_EVENTS, toObject } = require_security_log_model();
18737
+ var USER_ACCOUNT_EVENTS = Object.freeze([
18738
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
18739
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
18740
+ SECURITY_EVENTS.USER_LOCKOUT,
18741
+ SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
18742
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
18743
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
18744
+ SECURITY_EVENTS.USER_NEW_DEVICE,
18745
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
18746
+ SECURITY_EVENTS.USER_NOT_ME,
18747
+ SECURITY_EVENTS.USER_DATA_EXPORTED
18748
+ ]);
18749
+ var USER_IMPERSONATION_EVENTS = Object.freeze([
18750
+ SECURITY_EVENTS.IMPERSONATION_STARTED,
18751
+ SECURITY_EVENTS.IMPERSONATION_ENDED,
18752
+ SECURITY_EVENTS.IMPERSONATION_EXPIRED,
18753
+ SECURITY_EVENTS.IMPERSONATION_REFUSED
18754
+ ]);
18755
+ var USER_ACTIVITY_EVENTS = Object.freeze([...USER_ACCOUNT_EVENTS, ...USER_IMPERSONATION_EVENTS]);
18756
+ var USER_ACTIVITY_FILTERS = Object.freeze({
18757
+ all: USER_ACTIVITY_EVENTS,
18758
+ failed: Object.freeze([
18759
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
18760
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED
18761
+ ]),
18762
+ lockouts: Object.freeze([SECURITY_EVENTS.USER_LOCKOUT, SECURITY_EVENTS.USER_LOCKOUT_LIFTED]),
18763
+ suspicious: Object.freeze([
18764
+ SECURITY_EVENTS.USER_NEW_DEVICE,
18765
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
18766
+ SECURITY_EVENTS.USER_NOT_ME
18767
+ ]),
18768
+ sessions: Object.freeze([
18769
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
18770
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED
18771
+ ]),
18772
+ privacy: Object.freeze([SECURITY_EVENTS.USER_DATA_EXPORTED]),
18773
+ impersonation: USER_IMPERSONATION_EVENTS
18774
+ });
18775
+ var USER_DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
18776
+ function userActivityWhere(query, { retentionDays, now = /* @__PURE__ */ new Date() }) {
18777
+ const group = (
18778
+ /** @type {Record<string, readonly string[]>} */
18779
+ USER_ACTIVITY_FILTERS[query.event || "all"] || USER_ACTIVITY_FILTERS.all
18780
+ );
18781
+ const account = group.filter((event) => USER_ACCOUNT_EVENTS.includes(event));
18782
+ const impersonation = group.filter((event) => USER_IMPERSONATION_EVENTS.includes(event));
18783
+ const kinds = [];
18784
+ if (account.length) kinds.push({ event: { $in: account } });
18785
+ if (impersonation.length) kinds.push({ event: { $in: impersonation }, targetType: "user" });
18786
+ const conditions = [kinds.length === 1 ? kinds[0] : { $or: kinds }];
18787
+ if (query.userId) conditions.push({ targetType: "user", targetId: String(query.userId) });
18788
+ const days = Number.isInteger(retentionDays) && retentionDays > 0 ? retentionDays : 90;
18789
+ const cutoff = new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
18790
+ const from = query.from && query.from > cutoff ? query.from : cutoff;
18791
+ conditions.push({ createdAt: { $gte: from } });
18792
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
18793
+ return { $and: conditions };
18794
+ }
18795
+ var count = (value, max = 1e6) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max ? value : null;
18796
+ var oneOf = (value, allowed) => typeof value === "string" && allowed.includes(value) ? value : null;
18797
+ var countryCode = (value) => typeof value === "string" && /^[A-Z]{2}$/.test(value) ? value : null;
18798
+ var code = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value) ? value : null;
18799
+ function userEventFacts(event, storedMeta, viewer = {}) {
18800
+ const meta = toObject(storedMeta);
18801
+ switch (event) {
18802
+ case SECURITY_EVENTS.USER_SIGN_IN_FAILED:
18803
+ return { status: count(meta.status, 599), unknownAccount: meta.unknownAccount === true };
18804
+ case SECURITY_EVENTS.USER_SIGN_IN_REFUSED:
18805
+ return {
18806
+ reason: oneOf(meta.reason, REFUSAL_REASONS),
18807
+ limit: count(meta.limit, 1e4),
18808
+ lock: oneOf(meta.lock, ["ip", "account"]),
18809
+ unknownAccount: meta.unknownAccount === true
18810
+ };
18811
+ case SECURITY_EVENTS.USER_LOCKOUT:
18812
+ return {
18813
+ kind: oneOf(meta.kind, ["ip", "account"]),
18814
+ failures: count(meta.failures, 1e5),
18815
+ minutes: count(meta.minutes, 1e6)
18816
+ };
18817
+ case SECURITY_EVENTS.USER_LOCKOUT_LIFTED:
18818
+ return { kind: oneOf(meta.kind, ["ip", "account"]) };
18819
+ case SECURITY_EVENTS.USER_SESSION_LIMIT:
18820
+ return { ended: count(meta.ended, 1e5), limit: count(meta.limit, 1e4) };
18821
+ case SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED:
18822
+ return { ended: count(meta.ended, 1e5) };
18823
+ case SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL:
18824
+ return {
18825
+ distanceKm: count(meta.distanceKm, 5e4),
18826
+ speedKmh: count(meta.speedKmh, 1e7),
18827
+ from: countryCode(meta.from),
18828
+ to: countryCode(meta.to),
18829
+ action: oneOf(meta.action, ["alert", "reauthenticate"])
18830
+ };
18831
+ case SECURITY_EVENTS.USER_NOT_ME:
18832
+ return { scope: oneOf(meta.scope, ["session", "all"]), ended: count(meta.ended, 1e5) };
18833
+ case SECURITY_EVENTS.USER_DATA_EXPORTED:
18834
+ return { sessions: count(meta.sessions, 1e6), events: count(meta.events, 1e6) };
18835
+ case SECURITY_EVENTS.IMPERSONATION_STARTED:
18836
+ case SECURITY_EVENTS.IMPERSONATION_ENDED:
18837
+ case SECURITY_EVENTS.IMPERSONATION_EXPIRED:
18838
+ case SECURITY_EVENTS.IMPERSONATION_REFUSED: {
18839
+ const reason = viewer.canSeeImpersonationReason === true && typeof meta.reason === "string" && meta.reason.trim() ? meta.reason.trim().slice(0, 255) : null;
18840
+ return {
18841
+ durationMinutes: count(meta.durationMinutes, 1440),
18842
+ handoff: oneOf(meta.handoff, ["frontend", "token"]),
18843
+ endReason: oneOf(meta.endReason, ["ended", "disabled", "failed"]),
18844
+ refusal: code(meta.refusal),
18845
+ reason
18846
+ };
18847
+ }
18848
+ default:
18849
+ return {};
18850
+ }
18851
+ }
18852
+ function userEventAddress(row, options, anonymize) {
18853
+ if (!options.storeIp) return { ipAddress: null, ipAnonymized: false, keepLocation: false };
18854
+ const stored = typeof row.ip === "string" && row.ip ? row.ip : null;
18855
+ const alreadyShortened = toObject(row.meta).ipAnonymized === true;
18856
+ if (!stored) return { ipAddress: null, ipAnonymized: false, keepLocation: true };
18857
+ if (options.anonymizeIp && !alreadyShortened) {
18858
+ const shortened = anonymize(stored);
18859
+ return { ipAddress: shortened || null, ipAnonymized: Boolean(shortened), keepLocation: true };
18860
+ }
18861
+ return { ipAddress: stored, ipAnonymized: alreadyShortened, keepLocation: true };
18862
+ }
18863
+ module2.exports = {
18864
+ USER_ACCOUNT_EVENTS,
18865
+ USER_ACTIVITY_EVENTS,
18866
+ USER_ACTIVITY_FILTERS,
18867
+ USER_DOCUMENT_ID_PATTERN,
18868
+ USER_IMPERSONATION_EVENTS,
18869
+ userActivityWhere,
18870
+ userEventAddress,
18871
+ userEventFacts
18872
+ };
18873
+ }
18874
+ });
18875
+
18876
+ // server/src/controllers/user-activity.js
18877
+ var require_user_activity = __commonJS({
18878
+ "server/src/controllers/user-activity.js"(exports2, module2) {
18879
+ "use strict";
18880
+ var { z } = require("@strapi/utils");
18881
+ var { USER_ACTIVITY_FILTERS } = require_user_activity_model();
18882
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
18883
+ var { createLogger } = require_logger();
18884
+ var { callerCan } = require_settings_access();
18885
+ var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18886
+ var listQuerySchema = z.strictObject({
18887
+ event: z.enum(
18888
+ /** @type {[string, ...string[]]} */
18889
+ Object.keys(USER_ACTIVITY_FILTERS)
18890
+ ).default("all"),
18891
+ userId: z.string().regex(/^[A-Za-z0-9]{1,64}$/, "userId must be the documentId of a user").optional(),
18892
+ ...periodAndPaging()
18893
+ });
18894
+ var exportQuerySchema = listQuerySchema.omit({ page: true, pageSize: true }).extend({
18895
+ cursor: cursorField
18896
+ });
18897
+ module2.exports = ({ strapi: strapi2 }) => {
18898
+ const log = createLogger(strapi2);
18899
+ const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
18900
+ const viewerOf = (ctx) => ({
18901
+ ability: (
18902
+ /** @type {any} */
18903
+ ctx.state?.userAbility || null
18904
+ ),
18905
+ canReadAdmins: callerCan(ctx, "admin::users.read"),
18906
+ canSeeImpersonationReason: callerCan(ctx, IMPERSONATE_USERS_ACTION)
18907
+ });
18908
+ const audit = (ctx, exported) => {
18909
+ const state = (
18910
+ /** @type {any} */
18911
+ ctx.state
18912
+ );
18913
+ const viaToken = state?.auth?.strategy?.name === "admin-token";
18914
+ if (!viaToken && !exported) return;
18915
+ try {
18916
+ service().recordLogRead({
18917
+ adminId: state?.user?.id,
18918
+ tokenId: viaToken ? state?.auth?.credentials?.id : null,
18919
+ list: "user-activity",
18920
+ exported,
18921
+ via: viaToken ? "admin-token" : "admin-panel"
18922
+ });
18923
+ } catch {
18924
+ }
18925
+ };
18926
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
18927
+ log,
18928
+ logPrefix: "User activity",
18929
+ operation,
18930
+ failureMessage: "Security activity could not be loaded."
18931
+ });
18932
+ return {
18933
+ /**
18934
+ * One page of the app-user security activity, newest first.
18935
+ *
18936
+ * @route GET /magic-sessionmanager/user-activity
18937
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + user-activity.read;
18938
+ * read rate limit.
18939
+ * @param {Context} ctx Reads `ctx.query.event` (`all`|`failed`|`lockouts`|`suspicious`|
18940
+ * `sessions`|`privacy`|`impersonation`), `userId` (documentId of a Users & Permissions
18941
+ * user), `from`/`to` (ISO dates), `page`, `pageSize` (1..100, default 20). Unknown keys
18942
+ * are a 400.
18943
+ * @returns {Promise<unknown>} 200 `{ data: UserEventRow[], meta: { pagination, recording,
18944
+ * identity } }`; 400 ValidationError with field errors; 500 fixed message. Rows hold the
18945
+ * event, time, the user (`{ id, documentId, email, username }`, email and username empty
18946
+ * unless the caller may read that user in the Content Manager), the admin who acted
18947
+ * (name empty without `admin::users.read`), the event's facts (numbers and codes; the
18948
+ * impersonation reason only with `impersonate.users`), IP address as the current
18949
+ * switches allow it, location, browser, OS and the stored user agent. Rows older than
18950
+ * the retention period are left out.
18951
+ * @sideeffect A read with an admin API token queues a `security-log.read` event.
18952
+ */
18953
+ async list(ctx) {
18954
+ return handle(
18955
+ ctx,
18956
+ listQuerySchema,
18957
+ (query) => {
18958
+ audit(ctx, false);
18959
+ return service().listUserActivity(query, viewerOf(ctx));
18960
+ },
18961
+ "list"
18962
+ );
18963
+ },
18964
+ /**
18965
+ * One export batch (500 rows, keyset cursor) of the app-user security activity.
18966
+ *
18967
+ * @route GET /magic-sessionmanager/user-activity/export
18968
+ * @auth As list.
18969
+ * @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
18970
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
18971
+ * @sideeffect The first batch of an export (no `cursor`) queues a `security-log.read` event
18972
+ * with `list: 'user-activity'`, `exported: true` and `via` (`admin-panel` or
18973
+ * `admin-token`).
18974
+ */
18975
+ async export(ctx) {
18976
+ return handle(
18977
+ ctx,
18978
+ exportQuerySchema,
18979
+ (query) => {
18980
+ if (!query.cursor) audit(ctx, true);
18981
+ return service().exportBatch("user-activity", query, query.cursor || null, viewerOf(ctx));
18982
+ },
18983
+ "export"
18984
+ );
18985
+ }
18986
+ };
18987
+ };
18202
18988
  }
18203
18989
  });
18204
18990
 
@@ -18215,6 +19001,7 @@ var require_controllers = __commonJS({
18215
19001
  var selfService = require_self_service();
18216
19002
  var webhooks = require_webhooks();
18217
19003
  var impersonation = require_impersonation2();
19004
+ var userActivity = require_user_activity();
18218
19005
  module2.exports = {
18219
19006
  session,
18220
19007
  settings,
@@ -18224,7 +19011,8 @@ var require_controllers = __commonJS({
18224
19011
  lockouts,
18225
19012
  "self-service": selfService,
18226
19013
  webhooks,
18227
- impersonation
19014
+ impersonation,
19015
+ "user-activity": userActivity
18228
19016
  };
18229
19017
  }
18230
19018
  });
@@ -21000,6 +21788,12 @@ var require_security_log = __commonJS({
21000
21788
  normalizeIp
21001
21789
  } = require_admin_request_info();
21002
21790
  var { resolveSecurityLogSettings } = require_security_log_settings();
21791
+ var {
21792
+ USER_ACTIVITY_EVENTS,
21793
+ userActivityWhere,
21794
+ userEventAddress,
21795
+ userEventFacts
21796
+ } = require_user_activity_model();
21003
21797
  var { getPluginSettings } = require_settings_loader();
21004
21798
  var { shouldResolveGeoData } = require_enhance_session();
21005
21799
  var { createLogger } = require_logger();
@@ -21007,6 +21801,7 @@ var require_security_log = __commonJS({
21007
21801
  var ADMIN_USER_UID = "admin::user";
21008
21802
  var ADMIN_SESSION_UID = "admin::session";
21009
21803
  var PERMISSION_UID = "admin::permission";
21804
+ var USER_UID = "plugin::users-permissions.user";
21010
21805
  var SUPER_ADMIN_CODE = "strapi-super-admin";
21011
21806
  var FLUSH_DELAY_MS = 1e3;
21012
21807
  var FLUSH_BATCH = 200;
@@ -21023,6 +21818,7 @@ var require_security_log = __commonJS({
21023
21818
  var EXPORT_BATCH = 500;
21024
21819
  var DELETE_BATCH = 1e3;
21025
21820
  var MAX_DELETE_STEPS = 200;
21821
+ var AUDITED_LISTS = Object.freeze(["sign-ins", "content", "user-activity"]);
21026
21822
  function toId(value) {
21027
21823
  if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
21028
21824
  if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
@@ -21398,13 +22194,35 @@ var require_security_log = __commonJS({
21398
22194
  * @sideeffect Queues one always-on security event.
21399
22195
  */
21400
22196
  recordTokenRead(input) {
21401
- const now = Date.now();
21402
- const tokenId = toId(input?.tokenId);
21403
- const key = `${tokenId || "-"}|${input?.list}|${input?.exported ? "export" : "list"}`;
21404
- const last = readAudits.get(key);
21405
- if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
21406
- readAudits.set(key, now);
21407
- pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
22197
+ return service.recordLogRead({ ...input, via: "admin-token" });
22198
+ },
22199
+ /**
22200
+ * Records a read of the security log (`security-log.read`, always on).
22201
+ * Reads with an admin API token (4.17) are recorded once per token, list
22202
+ * and kind within 5 minutes. An export of the app-user activity from the
22203
+ * admin panel (4.22) is recorded each time it starts: it takes personal
22204
+ * data of app users out of Strapi.
22205
+ *
22206
+ * @param {{adminId: unknown, tokenId?: unknown, list: 'sign-ins'|'content'|'user-activity',
22207
+ * exported: boolean, via: 'admin-token'|'admin-panel'}} input Who read what, and how.
22208
+ * @returns {boolean} Whether an event was queued.
22209
+ * @sideeffect Queues one always-on security event.
22210
+ */
22211
+ recordLogRead(input) {
22212
+ const via = input?.via === "admin-panel" ? "admin-panel" : "admin-token";
22213
+ const list = AUDITED_LISTS.includes(
22214
+ /** @type {string} */
22215
+ input?.list
22216
+ ) ? input.list : "sign-ins";
22217
+ const tokenId = via === "admin-token" ? toId(input?.tokenId) : null;
22218
+ if (via === "admin-token") {
22219
+ const now = Date.now();
22220
+ const key = `${tokenId || "-"}|${list}|${input?.exported ? "export" : "list"}`;
22221
+ const last = readAudits.get(key);
22222
+ if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
22223
+ readAudits.set(key, now);
22224
+ pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
22225
+ }
21408
22226
  return service.record({
21409
22227
  event: SECURITY_EVENTS.LOG_READ,
21410
22228
  actorType: "admin",
@@ -21415,9 +22233,9 @@ var require_security_log = __commonJS({
21415
22233
  targetType: "security-log",
21416
22234
  targetId: null,
21417
22235
  meta: {
21418
- list: input?.list === "content" ? "content" : "sign-ins",
22236
+ list,
21419
22237
  exported: input?.exported === true,
21420
- via: "admin-token",
22238
+ via,
21421
22239
  ...tokenId ? { tokenId } : {}
21422
22240
  }
21423
22241
  });
@@ -21554,16 +22372,63 @@ var require_security_log = __commonJS({
21554
22372
  };
21555
22373
  },
21556
22374
  /**
21557
- * One export batch (newest first, keyset on id) of either list.
22375
+ * One page of the app-user security activity (4.22), newest first:
22376
+ * failed and refused sign-ins, lockouts, session limits, sign-outs after
22377
+ * a password change, new devices, impossible travel, "This wasn't me",
22378
+ * data exports and impersonations of app users. Rows older than the
22379
+ * retention period are not returned; IP addresses follow the current
22380
+ * "Store" and "Anonymise" switches.
21558
22381
  *
21559
- * @param {'sign-ins'|'content'} kind List.
22382
+ * @param {{event?: string, userId?: string, from?: Date|null, to?: Date|null,
22383
+ * page: number, pageSize: number}} query Parsed filters.
22384
+ * @param {Viewer} [viewer] Reader (user emails need Content Manager read access to the
22385
+ * user; admin names `admin::users.read`; impersonation reasons `impersonate.users`).
22386
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
22387
+ */
22388
+ async listUserActivity(query, viewer = {}) {
22389
+ const settings = await readSettingsOrDefaults();
22390
+ const options = resolveSecurityLogSettings(settings);
22391
+ const where = userActivityWhere(query, options);
22392
+ const [total, rows] = await Promise.all([
22393
+ events().count({ where }),
22394
+ events().findMany({
22395
+ where,
22396
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
22397
+ offset: (query.page - 1) * query.pageSize,
22398
+ limit: query.pageSize
22399
+ })
22400
+ ]);
22401
+ const shaped = await shapeUserEvents(Array.isArray(rows) ? rows : [], viewer, options);
22402
+ return {
22403
+ data: shaped.data,
22404
+ meta: {
22405
+ pagination: paginationOf(query, total),
22406
+ recording: {
22407
+ ipAddresses: options.storeIp,
22408
+ anonymizeIp: options.anonymizeIp,
22409
+ retentionDays: options.retentionDays,
22410
+ userSignIns: settings.recordUserSignInEvents !== false
22411
+ },
22412
+ identity: {
22413
+ users: shaped.usersVisible,
22414
+ names: viewer.canReadAdmins === true,
22415
+ impersonationReasons: viewer.canSeeImpersonationReason === true
22416
+ }
22417
+ }
22418
+ };
22419
+ },
22420
+ /**
22421
+ * One export batch (newest first, keyset on id) of a list.
22422
+ *
22423
+ * @param {'sign-ins'|'content'|'user-activity'} kind List.
21560
22424
  * @param {any} query Parsed filters (as for the list).
21561
22425
  * @param {number|null} cursor Id below which to continue.
21562
22426
  * @param {Viewer} [viewer] Reader; the same title and name rules as the lists.
21563
22427
  * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
21564
22428
  */
21565
22429
  async exportBatch(kind, query, cursor, viewer = {}) {
21566
- const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
22430
+ const options = kind === "user-activity" ? resolveSecurityLogSettings(await readSettingsOrDefaults()) : null;
22431
+ const base = kind === "sign-ins" ? signInWhere(query) : kind === "user-activity" && options ? userActivityWhere(query, options) : activityWhere(query);
21567
22432
  const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
21568
22433
  const rows = await events().findMany({
21569
22434
  where,
@@ -21571,7 +22436,11 @@ var require_security_log = __commonJS({
21571
22436
  limit: EXPORT_BATCH
21572
22437
  });
21573
22438
  const list = Array.isArray(rows) ? rows : [];
21574
- const data = kind === "sign-ins" ? await shapeSignIns(list, viewer) : await shapeActivity(list, viewer);
22439
+ let data;
22440
+ if (kind === "sign-ins") data = await shapeSignIns(list, viewer);
22441
+ else if (kind === "user-activity" && options) {
22442
+ data = (await shapeUserEvents(list, viewer, options)).data;
22443
+ } else data = await shapeActivity(list, viewer);
21575
22444
  const last = list[list.length - 1];
21576
22445
  return {
21577
22446
  data,
@@ -21747,14 +22616,15 @@ var require_security_log = __commonJS({
21747
22616
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
21748
22617
  return { $and: conditions };
21749
22618
  }
21750
- async function recordingFlags() {
21751
- let settings;
22619
+ async function readSettingsOrDefaults() {
21752
22620
  try {
21753
- settings = await getPluginSettings(strapi2);
22621
+ return await getPluginSettings(strapi2) || {};
21754
22622
  } catch {
21755
- settings = {};
22623
+ return {};
21756
22624
  }
21757
- const options = resolveSecurityLogSettings(settings);
22625
+ }
22626
+ async function recordingFlags() {
22627
+ const options = resolveSecurityLogSettings(await readSettingsOrDefaults());
21758
22628
  return {
21759
22629
  signIns: options.signIns,
21760
22630
  contentActivity: options.content,
@@ -21819,8 +22689,9 @@ var require_security_log = __commonJS({
21819
22689
  sessionsEnded: revoked && Number.isInteger(meta.ended) && meta.ended >= 0 ? meta.ended : null,
21820
22690
  change: row.event === SECURITY_EVENTS.SETTINGS_UPDATED ? { keys: settingKeysOf(meta.keys), viaToken: meta.via === "admin-token" } : null,
21821
22691
  read: row.event === SECURITY_EVENTS.LOG_READ ? {
21822
- list: meta.list === "content" ? "content" : "sign-ins",
21823
- exported: meta.exported === true
22692
+ list: AUDITED_LISTS.includes(meta.list) ? meta.list : "sign-ins",
22693
+ exported: meta.exported === true,
22694
+ via: meta.via === "admin-panel" ? "admin-panel" : "admin-token"
21824
22695
  } : null,
21825
22696
  purge: row.event === SECURITY_EVENTS.LOG_RETENTION_PURGED ? {
21826
22697
  count: Number.isInteger(meta.count) ? meta.count : null,
@@ -21979,6 +22850,96 @@ var require_security_log = __commonJS({
21979
22850
  };
21980
22851
  });
21981
22852
  }
22853
+ async function loadAppUsers(documentIds, ability) {
22854
+ const users = /* @__PURE__ */ new Map();
22855
+ if (!strapi2.contentTypes?.[USER_UID]) return { users, visible: false };
22856
+ let checker = null;
22857
+ if (ability) {
22858
+ try {
22859
+ const checkers = strapi2.plugin("content-manager")?.service("permission-checker");
22860
+ const candidate = checkers?.create({ userAbility: ability, model: USER_UID }) || null;
22861
+ checker = candidate && !candidate.cannot.read() ? candidate : null;
22862
+ } catch {
22863
+ checker = null;
22864
+ }
22865
+ }
22866
+ const ids = [
22867
+ ...new Set(
22868
+ documentIds.filter((id) => typeof id === "string" && /^[A-Za-z0-9]{1,64}$/.test(id))
22869
+ )
22870
+ ];
22871
+ if (!ids.length) return { users, visible: Boolean(checker) };
22872
+ const attributes = strapi2.contentTypes[USER_UID].attributes || {};
22873
+ const found = await strapi2.db.query(USER_UID).findMany({
22874
+ select: ["id", "documentId", "email", "username"],
22875
+ where: { documentId: { $in: ids } },
22876
+ ...attributes.createdBy ? { populate: { createdBy: { select: ["id"] } } } : {},
22877
+ limit: ids.length * 2
22878
+ });
22879
+ for (const user of Array.isArray(found) ? found : []) {
22880
+ const may = (field) => {
22881
+ if (!checker) return false;
22882
+ try {
22883
+ return checker.can.read(user, field) === true;
22884
+ } catch {
22885
+ return false;
22886
+ }
22887
+ };
22888
+ const email = may("email") && typeof user.email === "string" ? user.email : "";
22889
+ const username = may("username") && typeof user.username === "string" ? user.username : "";
22890
+ users.set(String(user.documentId), {
22891
+ id: Number(user.id),
22892
+ documentId: String(user.documentId),
22893
+ email: email.slice(0, 254),
22894
+ username: username.slice(0, 200)
22895
+ });
22896
+ }
22897
+ return { users, visible: Boolean(checker) };
22898
+ }
22899
+ async function shapeUserEvents(rows, viewer, options) {
22900
+ const list = rows.filter((row) => USER_ACTIVITY_EVENTS.includes(row.event));
22901
+ const { users, visible } = await loadAppUsers(
22902
+ list.filter((row) => row.targetType === "user").map((row) => row.targetId),
22903
+ viewer.ability || null
22904
+ );
22905
+ const admins = await loadAdmins(
22906
+ list.filter((row) => row.actorType === "admin").map((row) => row.actorId)
22907
+ );
22908
+ const data = list.map((row) => {
22909
+ const byAdmin = row.actorType === "admin";
22910
+ const userAgent = !byAdmin && typeof row.userAgent === "string" && row.userAgent ? row.userAgent : null;
22911
+ const described = describeUserAgent(userAgent);
22912
+ const address = byAdmin ? { ipAddress: null, ipAnonymized: false, keepLocation: false } : userEventAddress(row, options, (ip) => anonymizeIp(normalizeIp(ip)));
22913
+ const user = row.targetType === "user" && typeof row.targetId === "string" ? users.get(row.targetId) || null : null;
22914
+ const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
22915
+ let actor = null;
22916
+ if (row.actorType === "system") actor = { type: "system", id: null, name: "" };
22917
+ else if (row.actorType === "admin" && toAdminId(row.actorId)) {
22918
+ actor = {
22919
+ type: "admin",
22920
+ id: Number(row.actorId),
22921
+ name: admin && viewer.canReadAdmins === true ? adminName(admin) : ""
22922
+ };
22923
+ }
22924
+ return {
22925
+ id: Number(row.id),
22926
+ event: row.event,
22927
+ at: toIso(row.createdAt),
22928
+ target: row.targetType === "ip" ? "ip" : "user",
22929
+ user,
22930
+ actor,
22931
+ details: userEventFacts(row.event, row.meta, viewer),
22932
+ ipAddress: address.ipAddress,
22933
+ ipAnonymized: address.ipAnonymized,
22934
+ location: address.keepLocation ? toLocation(row.geo) : null,
22935
+ browser: described.browserName,
22936
+ os: described.osName,
22937
+ deviceType: described.deviceType,
22938
+ userAgent: userAgent ? userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null
22939
+ };
22940
+ });
22941
+ return { data, usersVisible: visible };
22942
+ }
21982
22943
  return service;
21983
22944
  };
21984
22945
  module2.exports.EVENT_UID = EVENT_UID;
@@ -22682,13 +23643,33 @@ var require_session_required = __commonJS({
22682
23643
  }
22683
23644
  });
22684
23645
 
23646
+ // server/src/policies/can-impersonate.js
23647
+ var require_can_impersonate = __commonJS({
23648
+ "server/src/policies/can-impersonate.js"(exports2, module2) {
23649
+ "use strict";
23650
+ module2.exports = (policyContext) => {
23651
+ const ability = policyContext?.state?.userAbility;
23652
+ const can = (action) => {
23653
+ try {
23654
+ return ability?.can?.(action) === true;
23655
+ } catch {
23656
+ return false;
23657
+ }
23658
+ };
23659
+ return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins");
23660
+ };
23661
+ }
23662
+ });
23663
+
22685
23664
  // server/src/policies/index.js
22686
23665
  var require_policies = __commonJS({
22687
23666
  "server/src/policies/index.js"(exports2, module2) {
22688
23667
  "use strict";
22689
23668
  var sessionRequired = require_session_required();
23669
+ var canImpersonate = require_can_impersonate();
22690
23670
  module2.exports = {
22691
- "session-required": sessionRequired
23671
+ "session-required": sessionRequired,
23672
+ "can-impersonate": canImpersonate
22692
23673
  };
22693
23674
  }
22694
23675
  });