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
@@ -1699,12 +1699,14 @@ var require_impersonation_rules = __commonJS({
1699
1699
  var IMPERSONATION_DEFAULTS = Object.freeze({ impersonationEnabled: false });
1700
1700
  var IMPERSONATION_KEYS = Object.freeze(Object.keys(IMPERSONATION_DEFAULTS));
1701
1701
  var USER_DURATIONS = Object.freeze([15, 30, 60]);
1702
+ var ADMIN_DURATIONS = Object.freeze([15, 30]);
1702
1703
  var REASON_MIN = 3;
1703
1704
  var REASON_MAX = 255;
1704
1705
  var CODE_TTL_MS = 60 * 1e3;
1705
1706
  var IMPERSONATION_HEADER = "X-Magic-Impersonation";
1706
1707
  var CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
1707
1708
  var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1709
+ var ADMIN_ID_PATTERN = /^[1-9][0-9]{0,15}$/;
1708
1710
  var LOOPBACK_HOSTS = Object.freeze(["localhost", "127.0.0.1", "[::1]"]);
1709
1711
  function normalizeImpersonationSettings(stored) {
1710
1712
  return { impersonationEnabled: stored?.impersonationEnabled === true };
@@ -1907,6 +1909,8 @@ var require_impersonation_rules = __commonJS({
1907
1909
  }
1908
1910
  }
1909
1911
  module.exports = {
1912
+ ADMIN_DURATIONS,
1913
+ ADMIN_ID_PATTERN,
1910
1914
  CODE_PATTERN,
1911
1915
  CODE_TTL_MS,
1912
1916
  DOCUMENT_ID_PATTERN,
@@ -2712,6 +2716,17 @@ var require_register = __commonJS({
2712
2716
  subCategory: "Admin panel",
2713
2717
  pluginName: "magic-sessionmanager"
2714
2718
  },
2719
+ // App-user security activity (4.22): failed and refused sign-ins,
2720
+ // lockouts, new devices, impossible travel, "This wasn't me", data
2721
+ // exports and impersonations of Users & Permissions accounts, with IP
2722
+ // addresses. Separate from plugin access because it shows personal data.
2723
+ {
2724
+ section: "plugins",
2725
+ displayName: "View app-user security activity",
2726
+ uid: "user-activity.read",
2727
+ subCategory: "General",
2728
+ pluginName: "magic-sessionmanager"
2729
+ },
2715
2730
  // Protected settings (4.17): IP location lookup (whether and where IP
2716
2731
  // addresses are sent), team notification webhooks (the URLs are
2717
2732
  // secrets) and the security log. The other settings stay on `access`.
@@ -2741,6 +2756,17 @@ var require_register = __commonJS({
2741
2756
  uid: "impersonate.users",
2742
2757
  subCategory: "Impersonation",
2743
2758
  pluginName: "magic-sessionmanager"
2759
+ },
2760
+ // "View as admin" (4.20): a read-only preview of which content types and
2761
+ // actions another admin can use. Never a Super Admin, never oneself, and
2762
+ // for non-Super-Admins only admins whose permissions are a subset of
2763
+ // their own.
2764
+ {
2765
+ section: "plugins",
2766
+ displayName: "View as admin (read-only permission preview)",
2767
+ uid: "impersonate.admins",
2768
+ subCategory: "Impersonation",
2769
+ pluginName: "magic-sessionmanager"
2744
2770
  }
2745
2771
  ]);
2746
2772
  disableGraphqlShadowCrud(strapi2, log);
@@ -12110,9 +12136,15 @@ var require_admin = __commonJS({
12110
12136
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
12111
12137
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
12112
12138
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12139
+ var USER_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.user-activity.read";
12113
12140
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12114
12141
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12115
12142
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
12143
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
12144
+ var impersonationListPolicy = () => [
12145
+ ...adminPolicy(),
12146
+ "plugin::magic-sessionmanager.can-impersonate"
12147
+ ];
12116
12148
  var adminPolicy = () => [
12117
12149
  "admin::isAuthenticatedAdmin",
12118
12150
  {
@@ -12366,6 +12398,27 @@ var require_admin = __commonJS({
12366
12398
  description: "Get one export batch of Content Manager activity of admins (admin)"
12367
12399
  }
12368
12400
  },
12401
+ // ===================== APP-USER SECURITY ACTIVITY (4.22) =====================
12402
+ {
12403
+ method: "GET",
12404
+ path: "/user-activity",
12405
+ handler: "user-activity.list",
12406
+ config: {
12407
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
12408
+ middlewares: adminReadRateLimit(),
12409
+ description: "List the security activity of app users (admin)"
12410
+ }
12411
+ },
12412
+ {
12413
+ method: "GET",
12414
+ path: "/user-activity/export",
12415
+ handler: "user-activity.export",
12416
+ config: {
12417
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
12418
+ middlewares: adminReadRateLimit(),
12419
+ description: "Get one export batch of the security activity of app users (admin)"
12420
+ }
12421
+ },
12369
12422
  // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
12370
12423
  {
12371
12424
  method: "GET",
@@ -12477,12 +12530,36 @@ var require_admin = __commonJS({
12477
12530
  ]
12478
12531
  }
12479
12532
  },
12533
+ {
12534
+ method: "POST",
12535
+ path: "/impersonation/admins/:adminId/preview",
12536
+ handler: "impersonation.previewAdmin",
12537
+ config: {
12538
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12539
+ // Ten previews per ten minutes per admin.
12540
+ middlewares: [
12541
+ {
12542
+ name: "plugin::magic-sessionmanager.rate-limit",
12543
+ config: { max: 10, window: 10 * 60 * 1e3 }
12544
+ }
12545
+ ]
12546
+ }
12547
+ },
12548
+ {
12549
+ method: "GET",
12550
+ path: "/impersonation/previews/:id",
12551
+ handler: "impersonation.getPreview",
12552
+ config: {
12553
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12554
+ middlewares: adminReadRateLimit()
12555
+ }
12556
+ },
12480
12557
  {
12481
12558
  method: "GET",
12482
12559
  path: "/impersonation/active",
12483
12560
  handler: "impersonation.listActive",
12484
12561
  config: {
12485
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12562
+ policies: impersonationListPolicy(),
12486
12563
  middlewares: adminReadRateLimit()
12487
12564
  }
12488
12565
  },
@@ -12491,7 +12568,7 @@ var require_admin = __commonJS({
12491
12568
  path: "/impersonation/:id/end",
12492
12569
  handler: "impersonation.end",
12493
12570
  config: {
12494
- policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12571
+ policies: impersonationListPolicy(),
12495
12572
  middlewares: adminSignOutRateLimit()
12496
12573
  }
12497
12574
  },
@@ -16696,25 +16773,66 @@ var require_admin_sessions2 = __commonJS({
16696
16773
  }
16697
16774
  });
16698
16775
 
16776
+ // server/src/utils/event-query.js
16777
+ var require_event_query = __commonJS({
16778
+ "server/src/utils/event-query.js"(exports, module) {
16779
+ "use strict";
16780
+ var { z } = __require("@strapi/utils");
16781
+ var { parseInput } = require_admin_sessions();
16782
+ var { sendServerError, sendValidationError } = require_http_errors();
16783
+ var MAX_PAGE_SIZE = 100;
16784
+ 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();
16785
+ var periodAndPaging = () => ({
16786
+ from: dateField("from"),
16787
+ to: dateField("to"),
16788
+ page: z.coerce.number().int().min(1).max(1e6).default(1),
16789
+ pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16790
+ });
16791
+ var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16792
+ async function handleEventQuery(ctx, schema, run, { log, logPrefix, operation, failureMessage }) {
16793
+ const parsed = parseInput(schema, ctx.query);
16794
+ if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16795
+ const query = parsed.value;
16796
+ if (query.from && query.to && query.from > query.to) {
16797
+ return sendValidationError(ctx, "Invalid query", [
16798
+ { path: ["from"], message: "from must not be after to" }
16799
+ ]);
16800
+ }
16801
+ try {
16802
+ ctx.body = await run(query);
16803
+ return ctx.body;
16804
+ } catch (error) {
16805
+ log.error(
16806
+ `${logPrefix}: ${operation} failed`,
16807
+ /** @type {any} */
16808
+ error?.name || "Error"
16809
+ );
16810
+ return sendServerError(ctx, 500, failureMessage);
16811
+ }
16812
+ }
16813
+ module.exports = {
16814
+ MAX_PAGE_SIZE,
16815
+ cursorField,
16816
+ dateField,
16817
+ handleEventQuery,
16818
+ periodAndPaging
16819
+ };
16820
+ }
16821
+ });
16822
+
16699
16823
  // server/src/controllers/admin-activity.js
16700
16824
  var require_admin_activity = __commonJS({
16701
16825
  "server/src/controllers/admin-activity.js"(exports, module) {
16702
16826
  "use strict";
16703
16827
  var { z } = __require("@strapi/utils");
16704
16828
  var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
16705
- var { parseInput } = require_admin_sessions();
16706
- var { sendServerError, sendValidationError } = require_http_errors();
16829
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
16707
16830
  var { createLogger } = require_logger();
16708
16831
  var { callerCan } = require_settings_access();
16709
- var MAX_PAGE_SIZE = 100;
16710
16832
  var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
16711
- 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();
16712
16833
  var common = {
16713
16834
  adminId: adminIdField,
16714
- from: dateField("from"),
16715
- to: dateField("to"),
16716
- page: z.coerce.number().int().min(1).max(1e6).default(1),
16717
- pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16835
+ ...periodAndPaging()
16718
16836
  };
16719
16837
  var signInQuerySchema = z.strictObject({
16720
16838
  ...common,
@@ -16734,7 +16852,6 @@ var require_admin_activity = __commonJS({
16734
16852
  "contentType must be a content type uid"
16735
16853
  ).optional()
16736
16854
  });
16737
- var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16738
16855
  var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
16739
16856
  cursor: cursorField
16740
16857
  });
@@ -16767,27 +16884,12 @@ var require_admin_activity = __commonJS({
16767
16884
  } catch {
16768
16885
  }
16769
16886
  };
16770
- const handle = async (ctx, schema, run, operation) => {
16771
- const parsed = parseInput(schema, ctx.query);
16772
- if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16773
- const query = parsed.value;
16774
- if (query.from && query.to && query.from > query.to) {
16775
- return sendValidationError(ctx, "Invalid query", [
16776
- { path: ["from"], message: "from must not be after to" }
16777
- ]);
16778
- }
16779
- try {
16780
- ctx.body = await run(query);
16781
- return ctx.body;
16782
- } catch (error) {
16783
- log.error(
16784
- `Admin activity: ${operation} failed`,
16785
- /** @type {any} */
16786
- error?.name || "Error"
16787
- );
16788
- return sendServerError(ctx, 500, "Admin activity could not be loaded.");
16789
- }
16790
- };
16887
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
16888
+ log,
16889
+ logPrefix: "Admin activity",
16890
+ operation,
16891
+ failureMessage: "Admin activity could not be loaded."
16892
+ });
16791
16893
  return {
16792
16894
  /**
16793
16895
  * One page of the admin sign-in history: sign-ins, failed attempts,
@@ -17353,6 +17455,228 @@ var require_webhooks = __commonJS({
17353
17455
  }
17354
17456
  });
17355
17457
 
17458
+ // server/src/utils/permission-subset.js
17459
+ var require_permission_subset = __commonJS({
17460
+ "server/src/utils/permission-subset.js"(exports, module) {
17461
+ "use strict";
17462
+ function grantsNothing(permission) {
17463
+ const fields = permission?.properties?.fields;
17464
+ return Array.isArray(fields) && fields.length === 0;
17465
+ }
17466
+ function parametersKey(value) {
17467
+ const normalize = (input) => {
17468
+ if (Array.isArray(input)) {
17469
+ return input.every((item) => typeof item === "string") ? [...new Set(input)].sort() : input.map(normalize);
17470
+ }
17471
+ if (input && typeof input === "object") {
17472
+ return Object.fromEntries(
17473
+ Object.keys(input).filter((key) => input[key] !== void 0).sort().map((key) => [key, normalize(input[key])])
17474
+ );
17475
+ }
17476
+ return input;
17477
+ };
17478
+ return JSON.stringify(normalize(value ?? {}));
17479
+ }
17480
+ function coversValue(held, property, value) {
17481
+ const allowed = held.properties?.[property];
17482
+ if (allowed === void 0 || allowed === null) return true;
17483
+ if (value === null || !Array.isArray(allowed)) return false;
17484
+ return allowed.some(
17485
+ (entry) => entry === value || property === "fields" && value.startsWith(`${entry}.`)
17486
+ );
17487
+ }
17488
+ function coversCondition(held, condition) {
17489
+ const conditions = held.conditions ?? [];
17490
+ if (conditions.length === 0) return true;
17491
+ return condition !== null && conditions.includes(condition);
17492
+ }
17493
+ function isPermissionCovered(requested, held) {
17494
+ if (grantsNothing(requested)) return true;
17495
+ const subject = requested.subject ?? null;
17496
+ const parameters = parametersKey(requested.actionParameters);
17497
+ const matching = held.filter(
17498
+ (permission) => permission.action === requested.action && (permission.subject ?? null) === subject && parametersKey(permission.actionParameters) === parameters && !grantsNothing(permission)
17499
+ );
17500
+ if (matching.length === 0) return false;
17501
+ const properties = [
17502
+ .../* @__PURE__ */ new Set([
17503
+ ...Object.keys(requested.properties ?? {}),
17504
+ ...matching.flatMap((permission) => Object.keys(permission.properties ?? {}))
17505
+ ])
17506
+ ];
17507
+ const dimensions = [];
17508
+ for (const property of properties) {
17509
+ const values = requested.properties?.[property];
17510
+ if (!Array.isArray(values)) dimensions.push({ property, values: [null] });
17511
+ else if (values.length > 0) {
17512
+ dimensions.push({ property, values: [...new Set(values.map(String))] });
17513
+ }
17514
+ }
17515
+ const conditions = (requested.conditions ?? []).length === 0 ? [null] : [...new Set(requested.conditions)];
17516
+ const walk = (index, picked, condition) => {
17517
+ if (index === dimensions.length) {
17518
+ return matching.some(
17519
+ (permission) => Object.entries(picked).every(
17520
+ ([property2, value]) => coversValue(permission, property2, value)
17521
+ ) && coversCondition(permission, condition)
17522
+ );
17523
+ }
17524
+ const { property, values } = dimensions[index];
17525
+ return values.every((value) => walk(index + 1, { ...picked, [property]: value }, condition));
17526
+ };
17527
+ return conditions.every((condition) => walk(0, {}, condition));
17528
+ }
17529
+ function uncoveredPermissions(target, actor) {
17530
+ return target.filter((permission) => !isPermissionCovered(permission, actor));
17531
+ }
17532
+ function toEnforced(permissions, context) {
17533
+ const out = [];
17534
+ for (const permission of permissions) {
17535
+ const conditions = permission.conditions ?? [];
17536
+ const registered = conditions.filter((id) => context.isConditionRegistered(id));
17537
+ if (conditions.length > 0 && registered.length === 0) continue;
17538
+ const properties = { ...permission.properties ?? {} };
17539
+ if (context.appliesLocales(permission)) {
17540
+ if (properties.locales === void 0) properties.locales = [];
17541
+ } else {
17542
+ delete properties.locales;
17543
+ }
17544
+ out.push({ ...permission, conditions: registered, properties });
17545
+ }
17546
+ return out;
17547
+ }
17548
+ module.exports = { isPermissionCovered, toEnforced, uncoveredPermissions };
17549
+ }
17550
+ });
17551
+
17552
+ // server/src/utils/admin-preview.js
17553
+ var require_admin_preview = __commonJS({
17554
+ "server/src/utils/admin-preview.js"(exports, module) {
17555
+ "use strict";
17556
+ var { toEnforced, uncoveredPermissions } = require_permission_subset();
17557
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
17558
+ function isSuperAdmin(user) {
17559
+ return (user?.roles || []).some((role) => role?.code === SUPER_ADMIN_CODE);
17560
+ }
17561
+ async function loadAdmin(strapi2, id) {
17562
+ return strapi2.db.query("admin::user").findOne({
17563
+ where: { id },
17564
+ select: ["id", "firstname", "lastname", "username", "email", "isActive"],
17565
+ populate: { roles: { select: ["id", "name", "code"] } }
17566
+ });
17567
+ }
17568
+ async function effectivePermissions(strapi2, user) {
17569
+ const service = strapi2.admin.services.permission;
17570
+ const raw = await service.findUserPermissions(user);
17571
+ const appliesCache = /* @__PURE__ */ new Map();
17572
+ for (const permission of raw) {
17573
+ const key = `${permission.action}::${permission.subject}`;
17574
+ if (appliesCache.has(key)) continue;
17575
+ let applies;
17576
+ try {
17577
+ applies = Boolean(permission.subject) && service.actionProvider.has(permission.action) && await service.actionProvider.appliesToProperty(
17578
+ "locales",
17579
+ permission.action,
17580
+ permission.subject
17581
+ ) === true;
17582
+ } catch {
17583
+ applies = false;
17584
+ }
17585
+ appliesCache.set(key, applies);
17586
+ }
17587
+ return toEnforced(raw, {
17588
+ isConditionRegistered: (id) => {
17589
+ try {
17590
+ return service.conditionProvider.has(id) === true;
17591
+ } catch {
17592
+ return false;
17593
+ }
17594
+ },
17595
+ appliesLocales: (permission) => appliesCache.get(`${permission.action}::${permission.subject}`) === true
17596
+ });
17597
+ }
17598
+ async function previewRefusal(strapi2, actor, target) {
17599
+ if (String(actor.id) === String(target.id)) return { reason: "self" };
17600
+ if (isSuperAdmin(target)) return { reason: "super-admin" };
17601
+ if (isSuperAdmin(actor)) return null;
17602
+ const [held, wanted] = await Promise.all([
17603
+ effectivePermissions(strapi2, actor),
17604
+ effectivePermissions(strapi2, target)
17605
+ ]);
17606
+ const uncovered = uncoveredPermissions(wanted, held);
17607
+ return uncovered.length > 0 ? { reason: "not-subset", uncovered: uncovered.length } : null;
17608
+ }
17609
+ function contentAction(action) {
17610
+ const match = /^plugin::content-manager\.explorer\.([a-z-]+)$/.exec(action);
17611
+ return match ? match[1] : action;
17612
+ }
17613
+ async function buildPreview(strapi2, target) {
17614
+ const permissions = await effectivePermissions(strapi2, target);
17615
+ const provider = strapi2.admin.services.permission.actionProvider;
17616
+ const types = /* @__PURE__ */ new Map();
17617
+ const other = [];
17618
+ for (const permission of permissions) {
17619
+ const contentType = permission.subject ? strapi2.contentTypes?.[permission.subject] : null;
17620
+ if (contentType && permission.action.startsWith("plugin::content-manager.explorer.")) {
17621
+ const entry = types.get(permission.subject) || {
17622
+ uid: permission.subject,
17623
+ name: String(contentType.info?.displayName || permission.subject).slice(0, 120),
17624
+ kind: contentType.kind === "singleType" ? "single" : "collection",
17625
+ actions: []
17626
+ };
17627
+ const fields = permission.properties?.fields;
17628
+ const locales = permission.properties?.locales;
17629
+ entry.actions.push({
17630
+ action: contentAction(permission.action),
17631
+ fields: Array.isArray(fields) ? fields.length : null,
17632
+ locales: Array.isArray(locales) ? locales.slice(0, 20) : null,
17633
+ conditions: (permission.conditions || []).slice(0, 10)
17634
+ });
17635
+ types.set(permission.subject, entry);
17636
+ continue;
17637
+ }
17638
+ let definition;
17639
+ try {
17640
+ definition = provider.get(permission.action);
17641
+ } catch {
17642
+ definition = null;
17643
+ }
17644
+ other.push({
17645
+ action: permission.action,
17646
+ name: String(definition?.displayName || permission.action).slice(0, 160),
17647
+ section: String(definition?.section || "other"),
17648
+ scope: definition?.pluginName ? String(definition.pluginName) : null
17649
+ });
17650
+ }
17651
+ const order = ["create", "read", "update", "delete", "publish"];
17652
+ const contentTypes = [...types.values()].map((entry) => ({
17653
+ ...entry,
17654
+ actions: entry.actions.sort(
17655
+ (a, b) => (order.indexOf(a.action) + 1 || 99) - (order.indexOf(b.action) + 1 || 99) || a.action.localeCompare(b.action)
17656
+ )
17657
+ })).sort((a, b) => a.name.localeCompare(b.name));
17658
+ other.sort((a, b) => a.section.localeCompare(b.section) || a.name.localeCompare(b.name));
17659
+ return {
17660
+ admin: {
17661
+ id: target.id,
17662
+ name: [target.firstname, target.lastname].filter(Boolean).join(" ").trim() || target.username || "",
17663
+ active: target.isActive === true,
17664
+ roles: (target.roles || []).map((role) => ({ name: role.name }))
17665
+ },
17666
+ contentTypes,
17667
+ otherPermissions: other.slice(0, 500)
17668
+ };
17669
+ }
17670
+ module.exports = {
17671
+ buildPreview,
17672
+ effectivePermissions,
17673
+ isSuperAdmin,
17674
+ loadAdmin,
17675
+ previewRefusal
17676
+ };
17677
+ }
17678
+ });
17679
+
17356
17680
  // server/src/services/impersonation.js
17357
17681
  var require_impersonation = __commonJS({
17358
17682
  "server/src/services/impersonation.js"(exports, module) {
@@ -17364,7 +17688,10 @@ var require_impersonation = __commonJS({
17364
17688
  var { getPluginSettings } = require_settings_loader();
17365
17689
  var { getNativeSessionManager } = require_native_session_manager();
17366
17690
  var { REVOCATION_UID } = require_session_revocation();
17691
+ var { buildPreview, loadAdmin, previewRefusal } = require_admin_preview();
17367
17692
  var {
17693
+ ADMIN_DURATIONS,
17694
+ ADMIN_ID_PATTERN,
17368
17695
  CODE_PATTERN,
17369
17696
  CODE_TTL_MS,
17370
17697
  DOCUMENT_ID_PATTERN,
@@ -17495,6 +17822,7 @@ var require_impersonation = __commonJS({
17495
17822
  handoff: frontend ? "frontend" : "token",
17496
17823
  frontendOrigin: frontend ? frontend.origin : null,
17497
17824
  durations: [...USER_DURATIONS],
17825
+ adminDurations: [...ADMIN_DURATIONS],
17498
17826
  mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
17499
17827
  };
17500
17828
  },
@@ -17620,6 +17948,137 @@ var require_impersonation = __commonJS({
17620
17948
  handoff
17621
17949
  };
17622
17950
  },
17951
+ /**
17952
+ * Starts a read-only permission preview of another admin ("View as
17953
+ * admin"). No session or token is created; the preview can be read by
17954
+ * the admin who started it until it ends.
17955
+ *
17956
+ * @param {{actor: any, adminId: unknown, body: unknown, canReadAdmins: boolean}} input
17957
+ * Caller (with roles), target id and request body.
17958
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17959
+ * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17960
+ * or not a subset of the caller's permissions; 404 unknown admin.
17961
+ * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17962
+ */
17963
+ async previewAdmin({ actor, adminId, body, canReadAdmins }) {
17964
+ const actorId = String(actor.id);
17965
+ const refuse = (reason, status, message, extra = {}) => {
17966
+ service.recordRefused({ actorId, targetType: "admin", targetId: adminId, reason });
17967
+ return new ImpersonationError(status, message, { reason, ...extra });
17968
+ };
17969
+ if (!await service.isEnabled()) {
17970
+ throw refuse("disabled", 403, "Impersonation is turned off");
17971
+ }
17972
+ if (typeof adminId !== "string" || !ADMIN_ID_PATTERN.test(adminId)) {
17973
+ throw new ImpersonationError(404, "Admin not found");
17974
+ }
17975
+ const { value, errors: fieldErrors } = validateStartBody(body, {
17976
+ durations: ADMIN_DURATIONS,
17977
+ notify: false
17978
+ });
17979
+ if (!value) {
17980
+ throw new ImpersonationError(400, "Invalid preview request", {
17981
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
17982
+ });
17983
+ }
17984
+ const [caller, target] = await Promise.all([
17985
+ loadAdmin(strapi2, actor.id),
17986
+ loadAdmin(strapi2, Number(adminId))
17987
+ ]);
17988
+ if (!target) throw new ImpersonationError(404, "Admin not found");
17989
+ const refusal = await previewRefusal(strapi2, caller || actor, target);
17990
+ if (refusal) {
17991
+ const messages = {
17992
+ self: "You cannot view yourself as another admin",
17993
+ "super-admin": "Super Admins cannot be viewed as another admin",
17994
+ "not-subset": "This admin has permissions that you do not have"
17995
+ };
17996
+ throw refuse(
17997
+ refusal.reason,
17998
+ 403,
17999
+ messages[refusal.reason],
18000
+ refusal.uncovered ? { uncovered: refusal.uncovered } : {}
18001
+ );
18002
+ }
18003
+ await service.sweep();
18004
+ const now = /* @__PURE__ */ new Date();
18005
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
18006
+ const row = await query().create({
18007
+ data: {
18008
+ targetType: "admin",
18009
+ targetId: String(target.id),
18010
+ actorId,
18011
+ state: "active",
18012
+ reason: value.reason,
18013
+ durationMinutes: value.durationMinutes,
18014
+ handoff: "preview",
18015
+ notifyUser: false,
18016
+ startedAt: now,
18017
+ expiresAt
18018
+ }
18019
+ });
18020
+ record({
18021
+ event: EVENTS.STARTED,
18022
+ actorType: "admin",
18023
+ actorId,
18024
+ targetType: "admin",
18025
+ targetId: String(target.id),
18026
+ meta: {
18027
+ reason: value.reason,
18028
+ durationMinutes: value.durationMinutes,
18029
+ handoff: "preview"
18030
+ }
18031
+ });
18032
+ const preview = await buildPreview(strapi2, target);
18033
+ if (!canReadAdmins) preview.admin.name = "";
18034
+ return {
18035
+ impersonation: service.toDto(row, {
18036
+ admins: /* @__PURE__ */ new Map([
18037
+ [String(target.id), canReadAdmins ? target : null],
18038
+ [actorId, caller || actor]
18039
+ ]),
18040
+ viewer: actor
18041
+ }),
18042
+ preview
18043
+ };
18044
+ },
18045
+ /**
18046
+ * The preview of a running admin preview, for the admin who started it.
18047
+ * An expired one is ended and answers 404 like an unknown one.
18048
+ *
18049
+ * @param {{id: unknown, viewer: any, canReadAdmins: boolean}} input Preview id and caller.
18050
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
18051
+ * @throws {ImpersonationError} 404 unknown, ended, expired or started by someone else.
18052
+ */
18053
+ async getPreview({ id, viewer, canReadAdmins }) {
18054
+ if (typeof id !== "string" || !DOCUMENT_ID_PATTERN.test(id)) {
18055
+ throw new ImpersonationError(404, "Preview not found");
18056
+ }
18057
+ const row = await query().findOne({
18058
+ where: { documentId: id, targetType: "admin", state: "active" }
18059
+ });
18060
+ if (!row || String(row.actorId) !== String(viewer.id)) {
18061
+ throw new ImpersonationError(404, "Preview not found");
18062
+ }
18063
+ if (new Date(row.expiresAt).getTime() <= Date.now()) {
18064
+ await service.end(row.documentId, { reason: "expired" });
18065
+ throw new ImpersonationError(404, "Preview not found");
18066
+ }
18067
+ const target = await loadAdmin(strapi2, Number(row.targetId));
18068
+ if (!target) {
18069
+ await service.end(row.documentId, { reason: "failed", silent: true });
18070
+ throw new ImpersonationError(404, "Preview not found");
18071
+ }
18072
+ const preview = await buildPreview(strapi2, target);
18073
+ if (!canReadAdmins) preview.admin.name = "";
18074
+ return {
18075
+ impersonation: service.toDto(row, {
18076
+ admins: /* @__PURE__ */ new Map([[String(target.id), canReadAdmins ? target : null]]),
18077
+ viewer
18078
+ }),
18079
+ preview
18080
+ };
18081
+ },
17623
18082
  /**
17624
18083
  * Mints the short-lived credential of an impersonation and links its
17625
18084
  * Magic session row.
@@ -17864,12 +18323,15 @@ var require_impersonation = __commonJS({
17864
18323
  return ended;
17865
18324
  },
17866
18325
  /**
17867
- * Active impersonations of the given target types, newest first.
18326
+ * Active impersonations of the given target types, newest first. Admin
18327
+ * names are shown only to callers who may read admin users (as in the
18328
+ * Admin panel view); the caller's own name always.
17868
18329
  *
17869
- * @param {{targetTypes: Array<'user'|'admin'>, viewer: any}} input Kinds the caller may see.
18330
+ * @param {{targetTypes: Array<'user'|'admin'>, viewer: any, canReadAdmins?: boolean}} input
18331
+ * Kinds the caller may see.
17870
18332
  * @returns {Promise<object[]>} DTOs.
17871
18333
  */
17872
- async listActive({ targetTypes, viewer }) {
18334
+ async listActive({ targetTypes, viewer, canReadAdmins = true }) {
17873
18335
  if (!targetTypes.length) return [];
17874
18336
  await service.sweep();
17875
18337
  const rows = await query().findMany({
@@ -17888,7 +18350,11 @@ var require_impersonation = __commonJS({
17888
18350
  select: ["documentId", "username", "email"]
17889
18351
  }) : [];
17890
18352
  const admins = adminIds.length ? await strapi2.db.query("admin::user").findMany({
17891
- where: { id: { $in: adminIds } },
18353
+ where: {
18354
+ id: {
18355
+ $in: canReadAdmins ? adminIds : adminIds.filter((id) => String(id) === String(viewer?.id))
18356
+ }
18357
+ },
17892
18358
  select: ["id", "firstname", "lastname", "username", "email"]
17893
18359
  }) : [];
17894
18360
  const context = {
@@ -17933,18 +18399,20 @@ var require_impersonation = __commonJS({
17933
18399
  * Loads one impersonation for the request guard (5-second cache).
17934
18400
  *
17935
18401
  * @param {string} documentId Impersonation id.
17936
- * @returns {Promise<{id: string, actorId: string, state: string, expiresAt: number}|null>}
18402
+ * @returns {Promise<{id: string, actorId: string, targetId: string|null, state: string,
18403
+ * expiresAt: number}|null>}
17937
18404
  */
17938
18405
  async loadForGuard(documentId) {
17939
18406
  const cached = recordCache.get(documentId);
17940
18407
  if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
17941
18408
  const row = await query().findOne({
17942
18409
  where: { documentId, targetType: "user" },
17943
- select: ["documentId", "actorId", "state", "expiresAt"]
18410
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt"]
17944
18411
  });
17945
18412
  const value = row ? {
17946
18413
  id: row.documentId,
17947
18414
  actorId: row.actorId,
18415
+ targetId: typeof row.targetId === "string" ? row.targetId : null,
17948
18416
  state: row.state,
17949
18417
  expiresAt: new Date(row.expiresAt).getTime()
17950
18418
  } : null;
@@ -17991,7 +18459,10 @@ var require_impersonation = __commonJS({
17991
18459
  * Records a refused Content API call made while impersonating (one event
17992
18460
  * per impersonation and reason per minute).
17993
18461
  *
17994
- * @param {{id: string, actorId: string}} impersonation Impersonation.
18462
+ * The impersonated user is the target (since 4.22), so the refusal shows
18463
+ * in that user's security activity and is deleted with the account.
18464
+ *
18465
+ * @param {{id: string, actorId: string, targetId?: string|null}} impersonation Impersonation.
17995
18466
  * @param {string} reason Refusal reason.
17996
18467
  * @returns {void}
17997
18468
  */
@@ -18006,7 +18477,7 @@ var require_impersonation = __commonJS({
18006
18477
  actorType: "admin",
18007
18478
  actorId: impersonation.actorId,
18008
18479
  targetType: "user",
18009
- targetId: null,
18480
+ targetId: impersonation.targetId || null,
18010
18481
  meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
18011
18482
  });
18012
18483
  },
@@ -18060,6 +18531,7 @@ var require_impersonation2 = __commonJS({
18060
18531
  var { ImpersonationError } = require_impersonation();
18061
18532
  var { sendServerError } = require_http_errors();
18062
18533
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18534
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
18063
18535
  function callerCan(ctx, action) {
18064
18536
  try {
18065
18537
  return ctx?.state?.userAbility?.can?.(action) === true;
@@ -18068,7 +18540,10 @@ var require_impersonation2 = __commonJS({
18068
18540
  }
18069
18541
  }
18070
18542
  function visibleTargetTypes(ctx) {
18071
- return callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [];
18543
+ return [
18544
+ ...callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [],
18545
+ ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) ? ["admin"] : []
18546
+ ];
18072
18547
  }
18073
18548
  var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
18074
18549
  async function respond(ctx, operation, handler) {
@@ -18141,17 +18616,19 @@ var require_impersonation2 = __commonJS({
18141
18616
  },
18142
18617
  /**
18143
18618
  * Active impersonations the caller may see: app users with
18144
- * `impersonate.users`.
18619
+ * `impersonate.users`, admin previews with `impersonate.admins`. Admin
18620
+ * names need `admin::users.read`, as in the Admin panel view.
18145
18621
  *
18146
18622
  * @route GET /magic-sessionmanager/impersonation/active
18147
- * @auth Admin JWT or admin API token; `access` + `impersonate.users`.
18623
+ * @auth Admin JWT or admin API token; `access` + one of the impersonate actions.
18148
18624
  * @returns {Promise<void>} `{ data: Impersonation[] }` (at most 100).
18149
18625
  */
18150
18626
  async listActive(ctx) {
18151
18627
  return respond(ctx, "list", async () => {
18152
18628
  const data = await service().listActive({
18153
18629
  targetTypes: visibleTargetTypes(ctx),
18154
- viewer: ctx.state.user
18630
+ viewer: ctx.state.user,
18631
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18155
18632
  });
18156
18633
  ctx.body = { data };
18157
18634
  });
@@ -18160,7 +18637,8 @@ var require_impersonation2 = __commonJS({
18160
18637
  * Ends an active impersonation now.
18161
18638
  *
18162
18639
  * @route POST /magic-sessionmanager/impersonation/:id/end
18163
- * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind.
18640
+ * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind
18641
+ * (`impersonate.users` for app users, `impersonate.admins` for admin previews).
18164
18642
  * @returns {Promise<void>} `{ data: { ended: boolean } }`.
18165
18643
  * Answers 404 for an unknown id or a kind the caller may not see.
18166
18644
  * @sideeffect Revokes the credential; logs `impersonation.ended`.
@@ -18179,6 +18657,54 @@ var require_impersonation2 = __commonJS({
18179
18657
  ctx.body = { data: { ended } };
18180
18658
  });
18181
18659
  },
18660
+ /**
18661
+ * Starts a read-only permission preview of another admin ("View as
18662
+ * admin"): which content types and actions they can use. No session or
18663
+ * token is created.
18664
+ *
18665
+ * @route POST /magic-sessionmanager/impersonation/admins/:adminId/preview
18666
+ * @auth Admin JWT only (admin API tokens are refused); `access` + `impersonate.admins`.
18667
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30 }`.
18668
+ * @returns {Promise<void>} 201 `{ data: { impersonation, preview } }`. Answers 403 with
18669
+ * `details.reason` `disabled`, `api-token`, `self`, `super-admin` or `not-subset`,
18670
+ * 400 for an invalid body and 404 for an unknown admin.
18671
+ * @sideeffect Creates a preview row; logs `impersonation.started` or `.refused`.
18672
+ */
18673
+ async previewAdmin(ctx) {
18674
+ ctx.set("Cache-Control", "no-store");
18675
+ return respond(ctx, "preview", async () => {
18676
+ const { adminId } = ctx.params;
18677
+ requirePerson(ctx, "admin", adminId);
18678
+ const result = await service().previewAdmin({
18679
+ actor: ctx.state.user,
18680
+ adminId,
18681
+ body: ctx.request.body,
18682
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18683
+ });
18684
+ ctx.status = 201;
18685
+ ctx.body = { data: result };
18686
+ });
18687
+ },
18688
+ /**
18689
+ * Reads a running admin preview; only the admin who started it.
18690
+ *
18691
+ * @route GET /magic-sessionmanager/impersonation/previews/:id
18692
+ * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
18693
+ * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
18694
+ * expired or started by someone else.
18695
+ */
18696
+ async getPreview(ctx) {
18697
+ ctx.set("Cache-Control", "no-store");
18698
+ return respond(ctx, "preview", async () => {
18699
+ ctx.body = {
18700
+ data: await service().getPreview({
18701
+ id: ctx.params.id,
18702
+ viewer: ctx.state.user,
18703
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18704
+ })
18705
+ };
18706
+ });
18707
+ },
18182
18708
  /**
18183
18709
  * Exchanges a one-time hand-off code for the impersonation credential.
18184
18710
  * Public on purpose: the code is the credential (32 random bytes, stored
@@ -18205,6 +18731,266 @@ var require_impersonation2 = __commonJS({
18205
18731
  };
18206
18732
  };
18207
18733
  module.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
18734
+ module.exports.IMPERSONATE_ADMINS_ACTION = IMPERSONATE_ADMINS_ACTION;
18735
+ }
18736
+ });
18737
+
18738
+ // server/src/utils/user-activity-model.js
18739
+ var require_user_activity_model = __commonJS({
18740
+ "server/src/utils/user-activity-model.js"(exports, module) {
18741
+ "use strict";
18742
+ var { REFUSAL_REASONS, SECURITY_EVENTS, toObject } = require_security_log_model();
18743
+ var USER_ACCOUNT_EVENTS = Object.freeze([
18744
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
18745
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
18746
+ SECURITY_EVENTS.USER_LOCKOUT,
18747
+ SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
18748
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
18749
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
18750
+ SECURITY_EVENTS.USER_NEW_DEVICE,
18751
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
18752
+ SECURITY_EVENTS.USER_NOT_ME,
18753
+ SECURITY_EVENTS.USER_DATA_EXPORTED
18754
+ ]);
18755
+ var USER_IMPERSONATION_EVENTS = Object.freeze([
18756
+ SECURITY_EVENTS.IMPERSONATION_STARTED,
18757
+ SECURITY_EVENTS.IMPERSONATION_ENDED,
18758
+ SECURITY_EVENTS.IMPERSONATION_EXPIRED,
18759
+ SECURITY_EVENTS.IMPERSONATION_REFUSED
18760
+ ]);
18761
+ var USER_ACTIVITY_EVENTS = Object.freeze([...USER_ACCOUNT_EVENTS, ...USER_IMPERSONATION_EVENTS]);
18762
+ var USER_ACTIVITY_FILTERS = Object.freeze({
18763
+ all: USER_ACTIVITY_EVENTS,
18764
+ failed: Object.freeze([
18765
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
18766
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED
18767
+ ]),
18768
+ lockouts: Object.freeze([SECURITY_EVENTS.USER_LOCKOUT, SECURITY_EVENTS.USER_LOCKOUT_LIFTED]),
18769
+ suspicious: Object.freeze([
18770
+ SECURITY_EVENTS.USER_NEW_DEVICE,
18771
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
18772
+ SECURITY_EVENTS.USER_NOT_ME
18773
+ ]),
18774
+ sessions: Object.freeze([
18775
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
18776
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED
18777
+ ]),
18778
+ privacy: Object.freeze([SECURITY_EVENTS.USER_DATA_EXPORTED]),
18779
+ impersonation: USER_IMPERSONATION_EVENTS
18780
+ });
18781
+ var USER_DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
18782
+ function userActivityWhere(query, { retentionDays, now = /* @__PURE__ */ new Date() }) {
18783
+ const group = (
18784
+ /** @type {Record<string, readonly string[]>} */
18785
+ USER_ACTIVITY_FILTERS[query.event || "all"] || USER_ACTIVITY_FILTERS.all
18786
+ );
18787
+ const account = group.filter((event) => USER_ACCOUNT_EVENTS.includes(event));
18788
+ const impersonation = group.filter((event) => USER_IMPERSONATION_EVENTS.includes(event));
18789
+ const kinds = [];
18790
+ if (account.length) kinds.push({ event: { $in: account } });
18791
+ if (impersonation.length) kinds.push({ event: { $in: impersonation }, targetType: "user" });
18792
+ const conditions = [kinds.length === 1 ? kinds[0] : { $or: kinds }];
18793
+ if (query.userId) conditions.push({ targetType: "user", targetId: String(query.userId) });
18794
+ const days = Number.isInteger(retentionDays) && retentionDays > 0 ? retentionDays : 90;
18795
+ const cutoff = new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
18796
+ const from = query.from && query.from > cutoff ? query.from : cutoff;
18797
+ conditions.push({ createdAt: { $gte: from } });
18798
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
18799
+ return { $and: conditions };
18800
+ }
18801
+ var count = (value, max = 1e6) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max ? value : null;
18802
+ var oneOf = (value, allowed) => typeof value === "string" && allowed.includes(value) ? value : null;
18803
+ var countryCode = (value) => typeof value === "string" && /^[A-Z]{2}$/.test(value) ? value : null;
18804
+ var code = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value) ? value : null;
18805
+ function userEventFacts(event, storedMeta, viewer = {}) {
18806
+ const meta = toObject(storedMeta);
18807
+ switch (event) {
18808
+ case SECURITY_EVENTS.USER_SIGN_IN_FAILED:
18809
+ return { status: count(meta.status, 599), unknownAccount: meta.unknownAccount === true };
18810
+ case SECURITY_EVENTS.USER_SIGN_IN_REFUSED:
18811
+ return {
18812
+ reason: oneOf(meta.reason, REFUSAL_REASONS),
18813
+ limit: count(meta.limit, 1e4),
18814
+ lock: oneOf(meta.lock, ["ip", "account"]),
18815
+ unknownAccount: meta.unknownAccount === true
18816
+ };
18817
+ case SECURITY_EVENTS.USER_LOCKOUT:
18818
+ return {
18819
+ kind: oneOf(meta.kind, ["ip", "account"]),
18820
+ failures: count(meta.failures, 1e5),
18821
+ minutes: count(meta.minutes, 1e6)
18822
+ };
18823
+ case SECURITY_EVENTS.USER_LOCKOUT_LIFTED:
18824
+ return { kind: oneOf(meta.kind, ["ip", "account"]) };
18825
+ case SECURITY_EVENTS.USER_SESSION_LIMIT:
18826
+ return { ended: count(meta.ended, 1e5), limit: count(meta.limit, 1e4) };
18827
+ case SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED:
18828
+ return { ended: count(meta.ended, 1e5) };
18829
+ case SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL:
18830
+ return {
18831
+ distanceKm: count(meta.distanceKm, 5e4),
18832
+ speedKmh: count(meta.speedKmh, 1e7),
18833
+ from: countryCode(meta.from),
18834
+ to: countryCode(meta.to),
18835
+ action: oneOf(meta.action, ["alert", "reauthenticate"])
18836
+ };
18837
+ case SECURITY_EVENTS.USER_NOT_ME:
18838
+ return { scope: oneOf(meta.scope, ["session", "all"]), ended: count(meta.ended, 1e5) };
18839
+ case SECURITY_EVENTS.USER_DATA_EXPORTED:
18840
+ return { sessions: count(meta.sessions, 1e6), events: count(meta.events, 1e6) };
18841
+ case SECURITY_EVENTS.IMPERSONATION_STARTED:
18842
+ case SECURITY_EVENTS.IMPERSONATION_ENDED:
18843
+ case SECURITY_EVENTS.IMPERSONATION_EXPIRED:
18844
+ case SECURITY_EVENTS.IMPERSONATION_REFUSED: {
18845
+ const reason = viewer.canSeeImpersonationReason === true && typeof meta.reason === "string" && meta.reason.trim() ? meta.reason.trim().slice(0, 255) : null;
18846
+ return {
18847
+ durationMinutes: count(meta.durationMinutes, 1440),
18848
+ handoff: oneOf(meta.handoff, ["frontend", "token"]),
18849
+ endReason: oneOf(meta.endReason, ["ended", "disabled", "failed"]),
18850
+ refusal: code(meta.refusal),
18851
+ reason
18852
+ };
18853
+ }
18854
+ default:
18855
+ return {};
18856
+ }
18857
+ }
18858
+ function userEventAddress(row, options, anonymize) {
18859
+ if (!options.storeIp) return { ipAddress: null, ipAnonymized: false, keepLocation: false };
18860
+ const stored = typeof row.ip === "string" && row.ip ? row.ip : null;
18861
+ const alreadyShortened = toObject(row.meta).ipAnonymized === true;
18862
+ if (!stored) return { ipAddress: null, ipAnonymized: false, keepLocation: true };
18863
+ if (options.anonymizeIp && !alreadyShortened) {
18864
+ const shortened = anonymize(stored);
18865
+ return { ipAddress: shortened || null, ipAnonymized: Boolean(shortened), keepLocation: true };
18866
+ }
18867
+ return { ipAddress: stored, ipAnonymized: alreadyShortened, keepLocation: true };
18868
+ }
18869
+ module.exports = {
18870
+ USER_ACCOUNT_EVENTS,
18871
+ USER_ACTIVITY_EVENTS,
18872
+ USER_ACTIVITY_FILTERS,
18873
+ USER_DOCUMENT_ID_PATTERN,
18874
+ USER_IMPERSONATION_EVENTS,
18875
+ userActivityWhere,
18876
+ userEventAddress,
18877
+ userEventFacts
18878
+ };
18879
+ }
18880
+ });
18881
+
18882
+ // server/src/controllers/user-activity.js
18883
+ var require_user_activity = __commonJS({
18884
+ "server/src/controllers/user-activity.js"(exports, module) {
18885
+ "use strict";
18886
+ var { z } = __require("@strapi/utils");
18887
+ var { USER_ACTIVITY_FILTERS } = require_user_activity_model();
18888
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
18889
+ var { createLogger } = require_logger();
18890
+ var { callerCan } = require_settings_access();
18891
+ var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18892
+ var listQuerySchema = z.strictObject({
18893
+ event: z.enum(
18894
+ /** @type {[string, ...string[]]} */
18895
+ Object.keys(USER_ACTIVITY_FILTERS)
18896
+ ).default("all"),
18897
+ userId: z.string().regex(/^[A-Za-z0-9]{1,64}$/, "userId must be the documentId of a user").optional(),
18898
+ ...periodAndPaging()
18899
+ });
18900
+ var exportQuerySchema = listQuerySchema.omit({ page: true, pageSize: true }).extend({
18901
+ cursor: cursorField
18902
+ });
18903
+ module.exports = ({ strapi: strapi2 }) => {
18904
+ const log = createLogger(strapi2);
18905
+ const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
18906
+ const viewerOf = (ctx) => ({
18907
+ ability: (
18908
+ /** @type {any} */
18909
+ ctx.state?.userAbility || null
18910
+ ),
18911
+ canReadAdmins: callerCan(ctx, "admin::users.read"),
18912
+ canSeeImpersonationReason: callerCan(ctx, IMPERSONATE_USERS_ACTION)
18913
+ });
18914
+ const audit = (ctx, exported) => {
18915
+ const state = (
18916
+ /** @type {any} */
18917
+ ctx.state
18918
+ );
18919
+ const viaToken = state?.auth?.strategy?.name === "admin-token";
18920
+ if (!viaToken && !exported) return;
18921
+ try {
18922
+ service().recordLogRead({
18923
+ adminId: state?.user?.id,
18924
+ tokenId: viaToken ? state?.auth?.credentials?.id : null,
18925
+ list: "user-activity",
18926
+ exported,
18927
+ via: viaToken ? "admin-token" : "admin-panel"
18928
+ });
18929
+ } catch {
18930
+ }
18931
+ };
18932
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
18933
+ log,
18934
+ logPrefix: "User activity",
18935
+ operation,
18936
+ failureMessage: "Security activity could not be loaded."
18937
+ });
18938
+ return {
18939
+ /**
18940
+ * One page of the app-user security activity, newest first.
18941
+ *
18942
+ * @route GET /magic-sessionmanager/user-activity
18943
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + user-activity.read;
18944
+ * read rate limit.
18945
+ * @param {Context} ctx Reads `ctx.query.event` (`all`|`failed`|`lockouts`|`suspicious`|
18946
+ * `sessions`|`privacy`|`impersonation`), `userId` (documentId of a Users & Permissions
18947
+ * user), `from`/`to` (ISO dates), `page`, `pageSize` (1..100, default 20). Unknown keys
18948
+ * are a 400.
18949
+ * @returns {Promise<unknown>} 200 `{ data: UserEventRow[], meta: { pagination, recording,
18950
+ * identity } }`; 400 ValidationError with field errors; 500 fixed message. Rows hold the
18951
+ * event, time, the user (`{ id, documentId, email, username }`, email and username empty
18952
+ * unless the caller may read that user in the Content Manager), the admin who acted
18953
+ * (name empty without `admin::users.read`), the event's facts (numbers and codes; the
18954
+ * impersonation reason only with `impersonate.users`), IP address as the current
18955
+ * switches allow it, location, browser, OS and the stored user agent. Rows older than
18956
+ * the retention period are left out.
18957
+ * @sideeffect A read with an admin API token queues a `security-log.read` event.
18958
+ */
18959
+ async list(ctx) {
18960
+ return handle(
18961
+ ctx,
18962
+ listQuerySchema,
18963
+ (query) => {
18964
+ audit(ctx, false);
18965
+ return service().listUserActivity(query, viewerOf(ctx));
18966
+ },
18967
+ "list"
18968
+ );
18969
+ },
18970
+ /**
18971
+ * One export batch (500 rows, keyset cursor) of the app-user security activity.
18972
+ *
18973
+ * @route GET /magic-sessionmanager/user-activity/export
18974
+ * @auth As list.
18975
+ * @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
18976
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
18977
+ * @sideeffect The first batch of an export (no `cursor`) queues a `security-log.read` event
18978
+ * with `list: 'user-activity'`, `exported: true` and `via` (`admin-panel` or
18979
+ * `admin-token`).
18980
+ */
18981
+ async export(ctx) {
18982
+ return handle(
18983
+ ctx,
18984
+ exportQuerySchema,
18985
+ (query) => {
18986
+ if (!query.cursor) audit(ctx, true);
18987
+ return service().exportBatch("user-activity", query, query.cursor || null, viewerOf(ctx));
18988
+ },
18989
+ "export"
18990
+ );
18991
+ }
18992
+ };
18993
+ };
18208
18994
  }
18209
18995
  });
18210
18996
 
@@ -18221,6 +19007,7 @@ var require_controllers = __commonJS({
18221
19007
  var selfService = require_self_service();
18222
19008
  var webhooks = require_webhooks();
18223
19009
  var impersonation = require_impersonation2();
19010
+ var userActivity = require_user_activity();
18224
19011
  module.exports = {
18225
19012
  session,
18226
19013
  settings,
@@ -18230,7 +19017,8 @@ var require_controllers = __commonJS({
18230
19017
  lockouts,
18231
19018
  "self-service": selfService,
18232
19019
  webhooks,
18233
- impersonation
19020
+ impersonation,
19021
+ "user-activity": userActivity
18234
19022
  };
18235
19023
  }
18236
19024
  });
@@ -21006,6 +21794,12 @@ var require_security_log = __commonJS({
21006
21794
  normalizeIp
21007
21795
  } = require_admin_request_info();
21008
21796
  var { resolveSecurityLogSettings } = require_security_log_settings();
21797
+ var {
21798
+ USER_ACTIVITY_EVENTS,
21799
+ userActivityWhere,
21800
+ userEventAddress,
21801
+ userEventFacts
21802
+ } = require_user_activity_model();
21009
21803
  var { getPluginSettings } = require_settings_loader();
21010
21804
  var { shouldResolveGeoData } = require_enhance_session();
21011
21805
  var { createLogger } = require_logger();
@@ -21013,6 +21807,7 @@ var require_security_log = __commonJS({
21013
21807
  var ADMIN_USER_UID = "admin::user";
21014
21808
  var ADMIN_SESSION_UID = "admin::session";
21015
21809
  var PERMISSION_UID = "admin::permission";
21810
+ var USER_UID = "plugin::users-permissions.user";
21016
21811
  var SUPER_ADMIN_CODE = "strapi-super-admin";
21017
21812
  var FLUSH_DELAY_MS = 1e3;
21018
21813
  var FLUSH_BATCH = 200;
@@ -21029,6 +21824,7 @@ var require_security_log = __commonJS({
21029
21824
  var EXPORT_BATCH = 500;
21030
21825
  var DELETE_BATCH = 1e3;
21031
21826
  var MAX_DELETE_STEPS = 200;
21827
+ var AUDITED_LISTS = Object.freeze(["sign-ins", "content", "user-activity"]);
21032
21828
  function toId(value) {
21033
21829
  if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
21034
21830
  if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
@@ -21404,13 +22200,35 @@ var require_security_log = __commonJS({
21404
22200
  * @sideeffect Queues one always-on security event.
21405
22201
  */
21406
22202
  recordTokenRead(input) {
21407
- const now = Date.now();
21408
- const tokenId = toId(input?.tokenId);
21409
- const key = `${tokenId || "-"}|${input?.list}|${input?.exported ? "export" : "list"}`;
21410
- const last = readAudits.get(key);
21411
- if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
21412
- readAudits.set(key, now);
21413
- pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
22203
+ return service.recordLogRead({ ...input, via: "admin-token" });
22204
+ },
22205
+ /**
22206
+ * Records a read of the security log (`security-log.read`, always on).
22207
+ * Reads with an admin API token (4.17) are recorded once per token, list
22208
+ * and kind within 5 minutes. An export of the app-user activity from the
22209
+ * admin panel (4.22) is recorded each time it starts: it takes personal
22210
+ * data of app users out of Strapi.
22211
+ *
22212
+ * @param {{adminId: unknown, tokenId?: unknown, list: 'sign-ins'|'content'|'user-activity',
22213
+ * exported: boolean, via: 'admin-token'|'admin-panel'}} input Who read what, and how.
22214
+ * @returns {boolean} Whether an event was queued.
22215
+ * @sideeffect Queues one always-on security event.
22216
+ */
22217
+ recordLogRead(input) {
22218
+ const via = input?.via === "admin-panel" ? "admin-panel" : "admin-token";
22219
+ const list = AUDITED_LISTS.includes(
22220
+ /** @type {string} */
22221
+ input?.list
22222
+ ) ? input.list : "sign-ins";
22223
+ const tokenId = via === "admin-token" ? toId(input?.tokenId) : null;
22224
+ if (via === "admin-token") {
22225
+ const now = Date.now();
22226
+ const key = `${tokenId || "-"}|${list}|${input?.exported ? "export" : "list"}`;
22227
+ const last = readAudits.get(key);
22228
+ if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
22229
+ readAudits.set(key, now);
22230
+ pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
22231
+ }
21414
22232
  return service.record({
21415
22233
  event: SECURITY_EVENTS.LOG_READ,
21416
22234
  actorType: "admin",
@@ -21421,9 +22239,9 @@ var require_security_log = __commonJS({
21421
22239
  targetType: "security-log",
21422
22240
  targetId: null,
21423
22241
  meta: {
21424
- list: input?.list === "content" ? "content" : "sign-ins",
22242
+ list,
21425
22243
  exported: input?.exported === true,
21426
- via: "admin-token",
22244
+ via,
21427
22245
  ...tokenId ? { tokenId } : {}
21428
22246
  }
21429
22247
  });
@@ -21560,16 +22378,63 @@ var require_security_log = __commonJS({
21560
22378
  };
21561
22379
  },
21562
22380
  /**
21563
- * One export batch (newest first, keyset on id) of either list.
22381
+ * One page of the app-user security activity (4.22), newest first:
22382
+ * failed and refused sign-ins, lockouts, session limits, sign-outs after
22383
+ * a password change, new devices, impossible travel, "This wasn't me",
22384
+ * data exports and impersonations of app users. Rows older than the
22385
+ * retention period are not returned; IP addresses follow the current
22386
+ * "Store" and "Anonymise" switches.
21564
22387
  *
21565
- * @param {'sign-ins'|'content'} kind List.
22388
+ * @param {{event?: string, userId?: string, from?: Date|null, to?: Date|null,
22389
+ * page: number, pageSize: number}} query Parsed filters.
22390
+ * @param {Viewer} [viewer] Reader (user emails need Content Manager read access to the
22391
+ * user; admin names `admin::users.read`; impersonation reasons `impersonate.users`).
22392
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
22393
+ */
22394
+ async listUserActivity(query, viewer = {}) {
22395
+ const settings = await readSettingsOrDefaults();
22396
+ const options = resolveSecurityLogSettings(settings);
22397
+ const where = userActivityWhere(query, options);
22398
+ const [total, rows] = await Promise.all([
22399
+ events().count({ where }),
22400
+ events().findMany({
22401
+ where,
22402
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
22403
+ offset: (query.page - 1) * query.pageSize,
22404
+ limit: query.pageSize
22405
+ })
22406
+ ]);
22407
+ const shaped = await shapeUserEvents(Array.isArray(rows) ? rows : [], viewer, options);
22408
+ return {
22409
+ data: shaped.data,
22410
+ meta: {
22411
+ pagination: paginationOf(query, total),
22412
+ recording: {
22413
+ ipAddresses: options.storeIp,
22414
+ anonymizeIp: options.anonymizeIp,
22415
+ retentionDays: options.retentionDays,
22416
+ userSignIns: settings.recordUserSignInEvents !== false
22417
+ },
22418
+ identity: {
22419
+ users: shaped.usersVisible,
22420
+ names: viewer.canReadAdmins === true,
22421
+ impersonationReasons: viewer.canSeeImpersonationReason === true
22422
+ }
22423
+ }
22424
+ };
22425
+ },
22426
+ /**
22427
+ * One export batch (newest first, keyset on id) of a list.
22428
+ *
22429
+ * @param {'sign-ins'|'content'|'user-activity'} kind List.
21566
22430
  * @param {any} query Parsed filters (as for the list).
21567
22431
  * @param {number|null} cursor Id below which to continue.
21568
22432
  * @param {Viewer} [viewer] Reader; the same title and name rules as the lists.
21569
22433
  * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
21570
22434
  */
21571
22435
  async exportBatch(kind, query, cursor, viewer = {}) {
21572
- const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
22436
+ const options = kind === "user-activity" ? resolveSecurityLogSettings(await readSettingsOrDefaults()) : null;
22437
+ const base = kind === "sign-ins" ? signInWhere(query) : kind === "user-activity" && options ? userActivityWhere(query, options) : activityWhere(query);
21573
22438
  const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
21574
22439
  const rows = await events().findMany({
21575
22440
  where,
@@ -21577,7 +22442,11 @@ var require_security_log = __commonJS({
21577
22442
  limit: EXPORT_BATCH
21578
22443
  });
21579
22444
  const list = Array.isArray(rows) ? rows : [];
21580
- const data = kind === "sign-ins" ? await shapeSignIns(list, viewer) : await shapeActivity(list, viewer);
22445
+ let data;
22446
+ if (kind === "sign-ins") data = await shapeSignIns(list, viewer);
22447
+ else if (kind === "user-activity" && options) {
22448
+ data = (await shapeUserEvents(list, viewer, options)).data;
22449
+ } else data = await shapeActivity(list, viewer);
21581
22450
  const last = list[list.length - 1];
21582
22451
  return {
21583
22452
  data,
@@ -21753,14 +22622,15 @@ var require_security_log = __commonJS({
21753
22622
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
21754
22623
  return { $and: conditions };
21755
22624
  }
21756
- async function recordingFlags() {
21757
- let settings;
22625
+ async function readSettingsOrDefaults() {
21758
22626
  try {
21759
- settings = await getPluginSettings(strapi2);
22627
+ return await getPluginSettings(strapi2) || {};
21760
22628
  } catch {
21761
- settings = {};
22629
+ return {};
21762
22630
  }
21763
- const options = resolveSecurityLogSettings(settings);
22631
+ }
22632
+ async function recordingFlags() {
22633
+ const options = resolveSecurityLogSettings(await readSettingsOrDefaults());
21764
22634
  return {
21765
22635
  signIns: options.signIns,
21766
22636
  contentActivity: options.content,
@@ -21825,8 +22695,9 @@ var require_security_log = __commonJS({
21825
22695
  sessionsEnded: revoked && Number.isInteger(meta.ended) && meta.ended >= 0 ? meta.ended : null,
21826
22696
  change: row.event === SECURITY_EVENTS.SETTINGS_UPDATED ? { keys: settingKeysOf(meta.keys), viaToken: meta.via === "admin-token" } : null,
21827
22697
  read: row.event === SECURITY_EVENTS.LOG_READ ? {
21828
- list: meta.list === "content" ? "content" : "sign-ins",
21829
- exported: meta.exported === true
22698
+ list: AUDITED_LISTS.includes(meta.list) ? meta.list : "sign-ins",
22699
+ exported: meta.exported === true,
22700
+ via: meta.via === "admin-panel" ? "admin-panel" : "admin-token"
21830
22701
  } : null,
21831
22702
  purge: row.event === SECURITY_EVENTS.LOG_RETENTION_PURGED ? {
21832
22703
  count: Number.isInteger(meta.count) ? meta.count : null,
@@ -21985,6 +22856,96 @@ var require_security_log = __commonJS({
21985
22856
  };
21986
22857
  });
21987
22858
  }
22859
+ async function loadAppUsers(documentIds, ability) {
22860
+ const users = /* @__PURE__ */ new Map();
22861
+ if (!strapi2.contentTypes?.[USER_UID]) return { users, visible: false };
22862
+ let checker = null;
22863
+ if (ability) {
22864
+ try {
22865
+ const checkers = strapi2.plugin("content-manager")?.service("permission-checker");
22866
+ const candidate = checkers?.create({ userAbility: ability, model: USER_UID }) || null;
22867
+ checker = candidate && !candidate.cannot.read() ? candidate : null;
22868
+ } catch {
22869
+ checker = null;
22870
+ }
22871
+ }
22872
+ const ids = [
22873
+ ...new Set(
22874
+ documentIds.filter((id) => typeof id === "string" && /^[A-Za-z0-9]{1,64}$/.test(id))
22875
+ )
22876
+ ];
22877
+ if (!ids.length) return { users, visible: Boolean(checker) };
22878
+ const attributes = strapi2.contentTypes[USER_UID].attributes || {};
22879
+ const found = await strapi2.db.query(USER_UID).findMany({
22880
+ select: ["id", "documentId", "email", "username"],
22881
+ where: { documentId: { $in: ids } },
22882
+ ...attributes.createdBy ? { populate: { createdBy: { select: ["id"] } } } : {},
22883
+ limit: ids.length * 2
22884
+ });
22885
+ for (const user of Array.isArray(found) ? found : []) {
22886
+ const may = (field) => {
22887
+ if (!checker) return false;
22888
+ try {
22889
+ return checker.can.read(user, field) === true;
22890
+ } catch {
22891
+ return false;
22892
+ }
22893
+ };
22894
+ const email = may("email") && typeof user.email === "string" ? user.email : "";
22895
+ const username = may("username") && typeof user.username === "string" ? user.username : "";
22896
+ users.set(String(user.documentId), {
22897
+ id: Number(user.id),
22898
+ documentId: String(user.documentId),
22899
+ email: email.slice(0, 254),
22900
+ username: username.slice(0, 200)
22901
+ });
22902
+ }
22903
+ return { users, visible: Boolean(checker) };
22904
+ }
22905
+ async function shapeUserEvents(rows, viewer, options) {
22906
+ const list = rows.filter((row) => USER_ACTIVITY_EVENTS.includes(row.event));
22907
+ const { users, visible } = await loadAppUsers(
22908
+ list.filter((row) => row.targetType === "user").map((row) => row.targetId),
22909
+ viewer.ability || null
22910
+ );
22911
+ const admins = await loadAdmins(
22912
+ list.filter((row) => row.actorType === "admin").map((row) => row.actorId)
22913
+ );
22914
+ const data = list.map((row) => {
22915
+ const byAdmin = row.actorType === "admin";
22916
+ const userAgent = !byAdmin && typeof row.userAgent === "string" && row.userAgent ? row.userAgent : null;
22917
+ const described = describeUserAgent(userAgent);
22918
+ const address = byAdmin ? { ipAddress: null, ipAnonymized: false, keepLocation: false } : userEventAddress(row, options, (ip) => anonymizeIp(normalizeIp(ip)));
22919
+ const user = row.targetType === "user" && typeof row.targetId === "string" ? users.get(row.targetId) || null : null;
22920
+ const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
22921
+ let actor = null;
22922
+ if (row.actorType === "system") actor = { type: "system", id: null, name: "" };
22923
+ else if (row.actorType === "admin" && toAdminId(row.actorId)) {
22924
+ actor = {
22925
+ type: "admin",
22926
+ id: Number(row.actorId),
22927
+ name: admin && viewer.canReadAdmins === true ? adminName(admin) : ""
22928
+ };
22929
+ }
22930
+ return {
22931
+ id: Number(row.id),
22932
+ event: row.event,
22933
+ at: toIso(row.createdAt),
22934
+ target: row.targetType === "ip" ? "ip" : "user",
22935
+ user,
22936
+ actor,
22937
+ details: userEventFacts(row.event, row.meta, viewer),
22938
+ ipAddress: address.ipAddress,
22939
+ ipAnonymized: address.ipAnonymized,
22940
+ location: address.keepLocation ? toLocation(row.geo) : null,
22941
+ browser: described.browserName,
22942
+ os: described.osName,
22943
+ deviceType: described.deviceType,
22944
+ userAgent: userAgent ? userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null
22945
+ };
22946
+ });
22947
+ return { data, usersVisible: visible };
22948
+ }
21988
22949
  return service;
21989
22950
  };
21990
22951
  module.exports.EVENT_UID = EVENT_UID;
@@ -22688,13 +23649,33 @@ var require_session_required = __commonJS({
22688
23649
  }
22689
23650
  });
22690
23651
 
23652
+ // server/src/policies/can-impersonate.js
23653
+ var require_can_impersonate = __commonJS({
23654
+ "server/src/policies/can-impersonate.js"(exports, module) {
23655
+ "use strict";
23656
+ module.exports = (policyContext) => {
23657
+ const ability = policyContext?.state?.userAbility;
23658
+ const can = (action) => {
23659
+ try {
23660
+ return ability?.can?.(action) === true;
23661
+ } catch {
23662
+ return false;
23663
+ }
23664
+ };
23665
+ return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins");
23666
+ };
23667
+ }
23668
+ });
23669
+
22691
23670
  // server/src/policies/index.js
22692
23671
  var require_policies = __commonJS({
22693
23672
  "server/src/policies/index.js"(exports, module) {
22694
23673
  "use strict";
22695
23674
  var sessionRequired = require_session_required();
23675
+ var canImpersonate = require_can_impersonate();
22696
23676
  module.exports = {
22697
- "session-required": sessionRequired
23677
+ "session-required": sessionRequired,
23678
+ "can-impersonate": canImpersonate
22698
23679
  };
22699
23680
  }
22700
23681
  });