strapi-plugin-magic-sessionmanager 4.21.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 +48 -0
  2. package/README.md +46 -11
  3. package/dist/admin/{Analytics-BqdZIBV4.js → Analytics-DeDLGiCe.js} +1 -1
  4. package/dist/admin/{Analytics-C-OLLzoB.mjs → Analytics-WbCUmkQQ.mjs} +1 -1
  5. package/dist/admin/{App-Cx9v6n_7.js → App-Bkv-W0Sv.js} +1336 -2591
  6. package/dist/admin/{App-BswHmNQT.mjs → App-C4bihk2K.mjs} +1309 -2564
  7. package/dist/admin/{OnlineUsersWidget-BRmQPPp9.js → OnlineUsersWidget-CSvNe2rC.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Dusgjc1d.mjs → OnlineUsersWidget-q0Z6nbbO.mjs} +1 -1
  9. package/dist/admin/{Settings-DZyQheUS.mjs → Settings-avD0DbXP.mjs} +2 -2
  10. package/dist/admin/{Settings-DWGuf_Z3.js → Settings-xokFI5LO.js} +44 -44
  11. package/dist/admin/dashboardModel-BBNRgcEr.mjs +170 -0
  12. package/dist/admin/dashboardModel-D4389iIV.js +169 -0
  13. package/dist/admin/{de-DUnrmFWk.mjs → de-BQlEdBMr.mjs} +73 -4
  14. package/dist/admin/{de-24TPqzG6.js → de-HcJ19LKI.js} +73 -4
  15. package/dist/admin/{en-8mBSkWOF.js → en-DI-98CPM.js} +74 -5
  16. package/dist/admin/{en-D8J__tyF.mjs → en-DzuXWL1W.mjs} +74 -5
  17. package/dist/admin/{es-BgpgWdk0.mjs → es-BfyED9YI.mjs} +73 -4
  18. package/dist/admin/{es-ChUKey-Q.js → es-Cm0Eklav.js} +73 -4
  19. package/dist/admin/{fr-DE_CWmgq.js → fr-C3nzszsI.js} +73 -4
  20. package/dist/admin/{fr-k1MHYKJo.mjs → fr-CzFNGWq0.mjs} +73 -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-BjqU5ioB.js → pt-BPZ6chPT.js} +73 -4
  26. package/dist/admin/{pt-DPO4DmDc.mjs → pt-DmyQnGI_.mjs} +73 -4
  27. package/dist/server/index.js +552 -55
  28. package/dist/server/index.mjs +552 -55
  29. package/package.json +1 -1
  30. package/dist/admin/index-Ceh3Q1Ki.js +0 -2308
  31. package/dist/admin/index-meLDPPwt.mjs +0 -2307
  32. package/dist/admin/settingsTabs-C1q5iMMw.mjs +0 -437
  33. package/dist/admin/settingsTabs-CfquZuKH.js +0 -436
@@ -2710,6 +2710,17 @@ var require_register = __commonJS({
2710
2710
  subCategory: "Admin panel",
2711
2711
  pluginName: "magic-sessionmanager"
2712
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
+ },
2713
2724
  // Protected settings (4.17): IP location lookup (whether and where IP
2714
2725
  // addresses are sent), team notification webhooks (the URLs are
2715
2726
  // secrets) and the security log. The other settings stay on `access`.
@@ -12119,6 +12130,7 @@ var require_admin = __commonJS({
12119
12130
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
12120
12131
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
12121
12132
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12133
+ var USER_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.user-activity.read";
12122
12134
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12123
12135
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12124
12136
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
@@ -12380,6 +12392,27 @@ var require_admin = __commonJS({
12380
12392
  description: "Get one export batch of Content Manager activity of admins (admin)"
12381
12393
  }
12382
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
+ },
12383
12416
  // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
12384
12417
  {
12385
12418
  method: "GET",
@@ -16734,25 +16767,66 @@ var require_admin_sessions2 = __commonJS({
16734
16767
  }
16735
16768
  });
16736
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
+
16737
16817
  // server/src/controllers/admin-activity.js
16738
16818
  var require_admin_activity = __commonJS({
16739
16819
  "server/src/controllers/admin-activity.js"(exports2, module2) {
16740
16820
  "use strict";
16741
16821
  var { z } = require("@strapi/utils");
16742
16822
  var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
16743
- var { parseInput } = require_admin_sessions();
16744
- var { sendServerError, sendValidationError } = require_http_errors();
16823
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
16745
16824
  var { createLogger } = require_logger();
16746
16825
  var { callerCan } = require_settings_access();
16747
- var MAX_PAGE_SIZE = 100;
16748
16826
  var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
16749
- 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();
16750
16827
  var common = {
16751
16828
  adminId: adminIdField,
16752
- from: dateField("from"),
16753
- to: dateField("to"),
16754
- page: z.coerce.number().int().min(1).max(1e6).default(1),
16755
- pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16829
+ ...periodAndPaging()
16756
16830
  };
16757
16831
  var signInQuerySchema = z.strictObject({
16758
16832
  ...common,
@@ -16772,7 +16846,6 @@ var require_admin_activity = __commonJS({
16772
16846
  "contentType must be a content type uid"
16773
16847
  ).optional()
16774
16848
  });
16775
- var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16776
16849
  var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
16777
16850
  cursor: cursorField
16778
16851
  });
@@ -16805,27 +16878,12 @@ var require_admin_activity = __commonJS({
16805
16878
  } catch {
16806
16879
  }
16807
16880
  };
16808
- const handle = async (ctx, schema, run, operation) => {
16809
- const parsed = parseInput(schema, ctx.query);
16810
- if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16811
- const query = parsed.value;
16812
- if (query.from && query.to && query.from > query.to) {
16813
- return sendValidationError(ctx, "Invalid query", [
16814
- { path: ["from"], message: "from must not be after to" }
16815
- ]);
16816
- }
16817
- try {
16818
- ctx.body = await run(query);
16819
- return ctx.body;
16820
- } catch (error) {
16821
- log.error(
16822
- `Admin activity: ${operation} failed`,
16823
- /** @type {any} */
16824
- error?.name || "Error"
16825
- );
16826
- return sendServerError(ctx, 500, "Admin activity could not be loaded.");
16827
- }
16828
- };
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
+ });
16829
16887
  return {
16830
16888
  /**
16831
16889
  * One page of the admin sign-in history: sign-ins, failed attempts,
@@ -18335,18 +18393,20 @@ var require_impersonation = __commonJS({
18335
18393
  * Loads one impersonation for the request guard (5-second cache).
18336
18394
  *
18337
18395
  * @param {string} documentId Impersonation id.
18338
- * @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>}
18339
18398
  */
18340
18399
  async loadForGuard(documentId) {
18341
18400
  const cached = recordCache.get(documentId);
18342
18401
  if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
18343
18402
  const row = await query().findOne({
18344
18403
  where: { documentId, targetType: "user" },
18345
- select: ["documentId", "actorId", "state", "expiresAt"]
18404
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt"]
18346
18405
  });
18347
18406
  const value = row ? {
18348
18407
  id: row.documentId,
18349
18408
  actorId: row.actorId,
18409
+ targetId: typeof row.targetId === "string" ? row.targetId : null,
18350
18410
  state: row.state,
18351
18411
  expiresAt: new Date(row.expiresAt).getTime()
18352
18412
  } : null;
@@ -18393,7 +18453,10 @@ var require_impersonation = __commonJS({
18393
18453
  * Records a refused Content API call made while impersonating (one event
18394
18454
  * per impersonation and reason per minute).
18395
18455
  *
18396
- * @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.
18397
18460
  * @param {string} reason Refusal reason.
18398
18461
  * @returns {void}
18399
18462
  */
@@ -18408,7 +18471,7 @@ var require_impersonation = __commonJS({
18408
18471
  actorType: "admin",
18409
18472
  actorId: impersonation.actorId,
18410
18473
  targetType: "user",
18411
- targetId: null,
18474
+ targetId: impersonation.targetId || null,
18412
18475
  meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
18413
18476
  });
18414
18477
  },
@@ -18666,6 +18729,265 @@ var require_impersonation2 = __commonJS({
18666
18729
  }
18667
18730
  });
18668
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
+ };
18988
+ }
18989
+ });
18990
+
18669
18991
  // server/src/controllers/index.js
18670
18992
  var require_controllers = __commonJS({
18671
18993
  "server/src/controllers/index.js"(exports2, module2) {
@@ -18679,6 +19001,7 @@ var require_controllers = __commonJS({
18679
19001
  var selfService = require_self_service();
18680
19002
  var webhooks = require_webhooks();
18681
19003
  var impersonation = require_impersonation2();
19004
+ var userActivity = require_user_activity();
18682
19005
  module2.exports = {
18683
19006
  session,
18684
19007
  settings,
@@ -18688,7 +19011,8 @@ var require_controllers = __commonJS({
18688
19011
  lockouts,
18689
19012
  "self-service": selfService,
18690
19013
  webhooks,
18691
- impersonation
19014
+ impersonation,
19015
+ "user-activity": userActivity
18692
19016
  };
18693
19017
  }
18694
19018
  });
@@ -21464,6 +21788,12 @@ var require_security_log = __commonJS({
21464
21788
  normalizeIp
21465
21789
  } = require_admin_request_info();
21466
21790
  var { resolveSecurityLogSettings } = require_security_log_settings();
21791
+ var {
21792
+ USER_ACTIVITY_EVENTS,
21793
+ userActivityWhere,
21794
+ userEventAddress,
21795
+ userEventFacts
21796
+ } = require_user_activity_model();
21467
21797
  var { getPluginSettings } = require_settings_loader();
21468
21798
  var { shouldResolveGeoData } = require_enhance_session();
21469
21799
  var { createLogger } = require_logger();
@@ -21471,6 +21801,7 @@ var require_security_log = __commonJS({
21471
21801
  var ADMIN_USER_UID = "admin::user";
21472
21802
  var ADMIN_SESSION_UID = "admin::session";
21473
21803
  var PERMISSION_UID = "admin::permission";
21804
+ var USER_UID = "plugin::users-permissions.user";
21474
21805
  var SUPER_ADMIN_CODE = "strapi-super-admin";
21475
21806
  var FLUSH_DELAY_MS = 1e3;
21476
21807
  var FLUSH_BATCH = 200;
@@ -21487,6 +21818,7 @@ var require_security_log = __commonJS({
21487
21818
  var EXPORT_BATCH = 500;
21488
21819
  var DELETE_BATCH = 1e3;
21489
21820
  var MAX_DELETE_STEPS = 200;
21821
+ var AUDITED_LISTS = Object.freeze(["sign-ins", "content", "user-activity"]);
21490
21822
  function toId(value) {
21491
21823
  if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
21492
21824
  if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
@@ -21862,13 +22194,35 @@ var require_security_log = __commonJS({
21862
22194
  * @sideeffect Queues one always-on security event.
21863
22195
  */
21864
22196
  recordTokenRead(input) {
21865
- const now = Date.now();
21866
- const tokenId = toId(input?.tokenId);
21867
- const key = `${tokenId || "-"}|${input?.list}|${input?.exported ? "export" : "list"}`;
21868
- const last = readAudits.get(key);
21869
- if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
21870
- readAudits.set(key, now);
21871
- 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
+ }
21872
22226
  return service.record({
21873
22227
  event: SECURITY_EVENTS.LOG_READ,
21874
22228
  actorType: "admin",
@@ -21879,9 +22233,9 @@ var require_security_log = __commonJS({
21879
22233
  targetType: "security-log",
21880
22234
  targetId: null,
21881
22235
  meta: {
21882
- list: input?.list === "content" ? "content" : "sign-ins",
22236
+ list,
21883
22237
  exported: input?.exported === true,
21884
- via: "admin-token",
22238
+ via,
21885
22239
  ...tokenId ? { tokenId } : {}
21886
22240
  }
21887
22241
  });
@@ -22018,16 +22372,63 @@ var require_security_log = __commonJS({
22018
22372
  };
22019
22373
  },
22020
22374
  /**
22021
- * 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.
22022
22381
  *
22023
- * @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.
22024
22424
  * @param {any} query Parsed filters (as for the list).
22025
22425
  * @param {number|null} cursor Id below which to continue.
22026
22426
  * @param {Viewer} [viewer] Reader; the same title and name rules as the lists.
22027
22427
  * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
22028
22428
  */
22029
22429
  async exportBatch(kind, query, cursor, viewer = {}) {
22030
- 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);
22031
22432
  const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
22032
22433
  const rows = await events().findMany({
22033
22434
  where,
@@ -22035,7 +22436,11 @@ var require_security_log = __commonJS({
22035
22436
  limit: EXPORT_BATCH
22036
22437
  });
22037
22438
  const list = Array.isArray(rows) ? rows : [];
22038
- 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);
22039
22444
  const last = list[list.length - 1];
22040
22445
  return {
22041
22446
  data,
@@ -22211,14 +22616,15 @@ var require_security_log = __commonJS({
22211
22616
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
22212
22617
  return { $and: conditions };
22213
22618
  }
22214
- async function recordingFlags() {
22215
- let settings;
22619
+ async function readSettingsOrDefaults() {
22216
22620
  try {
22217
- settings = await getPluginSettings(strapi2);
22621
+ return await getPluginSettings(strapi2) || {};
22218
22622
  } catch {
22219
- settings = {};
22623
+ return {};
22220
22624
  }
22221
- const options = resolveSecurityLogSettings(settings);
22625
+ }
22626
+ async function recordingFlags() {
22627
+ const options = resolveSecurityLogSettings(await readSettingsOrDefaults());
22222
22628
  return {
22223
22629
  signIns: options.signIns,
22224
22630
  contentActivity: options.content,
@@ -22283,8 +22689,9 @@ var require_security_log = __commonJS({
22283
22689
  sessionsEnded: revoked && Number.isInteger(meta.ended) && meta.ended >= 0 ? meta.ended : null,
22284
22690
  change: row.event === SECURITY_EVENTS.SETTINGS_UPDATED ? { keys: settingKeysOf(meta.keys), viaToken: meta.via === "admin-token" } : null,
22285
22691
  read: row.event === SECURITY_EVENTS.LOG_READ ? {
22286
- list: meta.list === "content" ? "content" : "sign-ins",
22287
- 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"
22288
22695
  } : null,
22289
22696
  purge: row.event === SECURITY_EVENTS.LOG_RETENTION_PURGED ? {
22290
22697
  count: Number.isInteger(meta.count) ? meta.count : null,
@@ -22443,6 +22850,96 @@ var require_security_log = __commonJS({
22443
22850
  };
22444
22851
  });
22445
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
+ }
22446
22943
  return service;
22447
22944
  };
22448
22945
  module2.exports.EVENT_UID = EVENT_UID;