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
@@ -2716,6 +2716,17 @@ var require_register = __commonJS({
2716
2716
  subCategory: "Admin panel",
2717
2717
  pluginName: "magic-sessionmanager"
2718
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
+ },
2719
2730
  // Protected settings (4.17): IP location lookup (whether and where IP
2720
2731
  // addresses are sent), team notification webhooks (the URLs are
2721
2732
  // secrets) and the security log. The other settings stay on `access`.
@@ -12125,6 +12136,7 @@ var require_admin = __commonJS({
12125
12136
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
12126
12137
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
12127
12138
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12139
+ var USER_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.user-activity.read";
12128
12140
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12129
12141
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12130
12142
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
@@ -12386,6 +12398,27 @@ var require_admin = __commonJS({
12386
12398
  description: "Get one export batch of Content Manager activity of admins (admin)"
12387
12399
  }
12388
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
+ },
12389
12422
  // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
12390
12423
  {
12391
12424
  method: "GET",
@@ -16740,25 +16773,66 @@ var require_admin_sessions2 = __commonJS({
16740
16773
  }
16741
16774
  });
16742
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
+
16743
16823
  // server/src/controllers/admin-activity.js
16744
16824
  var require_admin_activity = __commonJS({
16745
16825
  "server/src/controllers/admin-activity.js"(exports, module) {
16746
16826
  "use strict";
16747
16827
  var { z } = __require("@strapi/utils");
16748
16828
  var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
16749
- var { parseInput } = require_admin_sessions();
16750
- var { sendServerError, sendValidationError } = require_http_errors();
16829
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
16751
16830
  var { createLogger } = require_logger();
16752
16831
  var { callerCan } = require_settings_access();
16753
- var MAX_PAGE_SIZE = 100;
16754
16832
  var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
16755
- 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();
16756
16833
  var common = {
16757
16834
  adminId: adminIdField,
16758
- from: dateField("from"),
16759
- to: dateField("to"),
16760
- page: z.coerce.number().int().min(1).max(1e6).default(1),
16761
- pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16835
+ ...periodAndPaging()
16762
16836
  };
16763
16837
  var signInQuerySchema = z.strictObject({
16764
16838
  ...common,
@@ -16778,7 +16852,6 @@ var require_admin_activity = __commonJS({
16778
16852
  "contentType must be a content type uid"
16779
16853
  ).optional()
16780
16854
  });
16781
- var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16782
16855
  var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
16783
16856
  cursor: cursorField
16784
16857
  });
@@ -16811,27 +16884,12 @@ var require_admin_activity = __commonJS({
16811
16884
  } catch {
16812
16885
  }
16813
16886
  };
16814
- const handle = async (ctx, schema, run, operation) => {
16815
- const parsed = parseInput(schema, ctx.query);
16816
- if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16817
- const query = parsed.value;
16818
- if (query.from && query.to && query.from > query.to) {
16819
- return sendValidationError(ctx, "Invalid query", [
16820
- { path: ["from"], message: "from must not be after to" }
16821
- ]);
16822
- }
16823
- try {
16824
- ctx.body = await run(query);
16825
- return ctx.body;
16826
- } catch (error) {
16827
- log.error(
16828
- `Admin activity: ${operation} failed`,
16829
- /** @type {any} */
16830
- error?.name || "Error"
16831
- );
16832
- return sendServerError(ctx, 500, "Admin activity could not be loaded.");
16833
- }
16834
- };
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
+ });
16835
16893
  return {
16836
16894
  /**
16837
16895
  * One page of the admin sign-in history: sign-ins, failed attempts,
@@ -18341,18 +18399,20 @@ var require_impersonation = __commonJS({
18341
18399
  * Loads one impersonation for the request guard (5-second cache).
18342
18400
  *
18343
18401
  * @param {string} documentId Impersonation id.
18344
- * @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>}
18345
18404
  */
18346
18405
  async loadForGuard(documentId) {
18347
18406
  const cached = recordCache.get(documentId);
18348
18407
  if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
18349
18408
  const row = await query().findOne({
18350
18409
  where: { documentId, targetType: "user" },
18351
- select: ["documentId", "actorId", "state", "expiresAt"]
18410
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt"]
18352
18411
  });
18353
18412
  const value = row ? {
18354
18413
  id: row.documentId,
18355
18414
  actorId: row.actorId,
18415
+ targetId: typeof row.targetId === "string" ? row.targetId : null,
18356
18416
  state: row.state,
18357
18417
  expiresAt: new Date(row.expiresAt).getTime()
18358
18418
  } : null;
@@ -18399,7 +18459,10 @@ var require_impersonation = __commonJS({
18399
18459
  * Records a refused Content API call made while impersonating (one event
18400
18460
  * per impersonation and reason per minute).
18401
18461
  *
18402
- * @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.
18403
18466
  * @param {string} reason Refusal reason.
18404
18467
  * @returns {void}
18405
18468
  */
@@ -18414,7 +18477,7 @@ var require_impersonation = __commonJS({
18414
18477
  actorType: "admin",
18415
18478
  actorId: impersonation.actorId,
18416
18479
  targetType: "user",
18417
- targetId: null,
18480
+ targetId: impersonation.targetId || null,
18418
18481
  meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
18419
18482
  });
18420
18483
  },
@@ -18672,6 +18735,265 @@ var require_impersonation2 = __commonJS({
18672
18735
  }
18673
18736
  });
18674
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
+ };
18994
+ }
18995
+ });
18996
+
18675
18997
  // server/src/controllers/index.js
18676
18998
  var require_controllers = __commonJS({
18677
18999
  "server/src/controllers/index.js"(exports, module) {
@@ -18685,6 +19007,7 @@ var require_controllers = __commonJS({
18685
19007
  var selfService = require_self_service();
18686
19008
  var webhooks = require_webhooks();
18687
19009
  var impersonation = require_impersonation2();
19010
+ var userActivity = require_user_activity();
18688
19011
  module.exports = {
18689
19012
  session,
18690
19013
  settings,
@@ -18694,7 +19017,8 @@ var require_controllers = __commonJS({
18694
19017
  lockouts,
18695
19018
  "self-service": selfService,
18696
19019
  webhooks,
18697
- impersonation
19020
+ impersonation,
19021
+ "user-activity": userActivity
18698
19022
  };
18699
19023
  }
18700
19024
  });
@@ -21470,6 +21794,12 @@ var require_security_log = __commonJS({
21470
21794
  normalizeIp
21471
21795
  } = require_admin_request_info();
21472
21796
  var { resolveSecurityLogSettings } = require_security_log_settings();
21797
+ var {
21798
+ USER_ACTIVITY_EVENTS,
21799
+ userActivityWhere,
21800
+ userEventAddress,
21801
+ userEventFacts
21802
+ } = require_user_activity_model();
21473
21803
  var { getPluginSettings } = require_settings_loader();
21474
21804
  var { shouldResolveGeoData } = require_enhance_session();
21475
21805
  var { createLogger } = require_logger();
@@ -21477,6 +21807,7 @@ var require_security_log = __commonJS({
21477
21807
  var ADMIN_USER_UID = "admin::user";
21478
21808
  var ADMIN_SESSION_UID = "admin::session";
21479
21809
  var PERMISSION_UID = "admin::permission";
21810
+ var USER_UID = "plugin::users-permissions.user";
21480
21811
  var SUPER_ADMIN_CODE = "strapi-super-admin";
21481
21812
  var FLUSH_DELAY_MS = 1e3;
21482
21813
  var FLUSH_BATCH = 200;
@@ -21493,6 +21824,7 @@ var require_security_log = __commonJS({
21493
21824
  var EXPORT_BATCH = 500;
21494
21825
  var DELETE_BATCH = 1e3;
21495
21826
  var MAX_DELETE_STEPS = 200;
21827
+ var AUDITED_LISTS = Object.freeze(["sign-ins", "content", "user-activity"]);
21496
21828
  function toId(value) {
21497
21829
  if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
21498
21830
  if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
@@ -21868,13 +22200,35 @@ var require_security_log = __commonJS({
21868
22200
  * @sideeffect Queues one always-on security event.
21869
22201
  */
21870
22202
  recordTokenRead(input) {
21871
- const now = Date.now();
21872
- const tokenId = toId(input?.tokenId);
21873
- const key = `${tokenId || "-"}|${input?.list}|${input?.exported ? "export" : "list"}`;
21874
- const last = readAudits.get(key);
21875
- if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
21876
- readAudits.set(key, now);
21877
- 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
+ }
21878
22232
  return service.record({
21879
22233
  event: SECURITY_EVENTS.LOG_READ,
21880
22234
  actorType: "admin",
@@ -21885,9 +22239,9 @@ var require_security_log = __commonJS({
21885
22239
  targetType: "security-log",
21886
22240
  targetId: null,
21887
22241
  meta: {
21888
- list: input?.list === "content" ? "content" : "sign-ins",
22242
+ list,
21889
22243
  exported: input?.exported === true,
21890
- via: "admin-token",
22244
+ via,
21891
22245
  ...tokenId ? { tokenId } : {}
21892
22246
  }
21893
22247
  });
@@ -22024,16 +22378,63 @@ var require_security_log = __commonJS({
22024
22378
  };
22025
22379
  },
22026
22380
  /**
22027
- * 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.
22028
22387
  *
22029
- * @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.
22030
22430
  * @param {any} query Parsed filters (as for the list).
22031
22431
  * @param {number|null} cursor Id below which to continue.
22032
22432
  * @param {Viewer} [viewer] Reader; the same title and name rules as the lists.
22033
22433
  * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
22034
22434
  */
22035
22435
  async exportBatch(kind, query, cursor, viewer = {}) {
22036
- 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);
22037
22438
  const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
22038
22439
  const rows = await events().findMany({
22039
22440
  where,
@@ -22041,7 +22442,11 @@ var require_security_log = __commonJS({
22041
22442
  limit: EXPORT_BATCH
22042
22443
  });
22043
22444
  const list = Array.isArray(rows) ? rows : [];
22044
- 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);
22045
22450
  const last = list[list.length - 1];
22046
22451
  return {
22047
22452
  data,
@@ -22217,14 +22622,15 @@ var require_security_log = __commonJS({
22217
22622
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
22218
22623
  return { $and: conditions };
22219
22624
  }
22220
- async function recordingFlags() {
22221
- let settings;
22625
+ async function readSettingsOrDefaults() {
22222
22626
  try {
22223
- settings = await getPluginSettings(strapi2);
22627
+ return await getPluginSettings(strapi2) || {};
22224
22628
  } catch {
22225
- settings = {};
22629
+ return {};
22226
22630
  }
22227
- const options = resolveSecurityLogSettings(settings);
22631
+ }
22632
+ async function recordingFlags() {
22633
+ const options = resolveSecurityLogSettings(await readSettingsOrDefaults());
22228
22634
  return {
22229
22635
  signIns: options.signIns,
22230
22636
  contentActivity: options.content,
@@ -22289,8 +22695,9 @@ var require_security_log = __commonJS({
22289
22695
  sessionsEnded: revoked && Number.isInteger(meta.ended) && meta.ended >= 0 ? meta.ended : null,
22290
22696
  change: row.event === SECURITY_EVENTS.SETTINGS_UPDATED ? { keys: settingKeysOf(meta.keys), viaToken: meta.via === "admin-token" } : null,
22291
22697
  read: row.event === SECURITY_EVENTS.LOG_READ ? {
22292
- list: meta.list === "content" ? "content" : "sign-ins",
22293
- 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"
22294
22701
  } : null,
22295
22702
  purge: row.event === SECURITY_EVENTS.LOG_RETENTION_PURGED ? {
22296
22703
  count: Number.isInteger(meta.count) ? meta.count : null,
@@ -22449,6 +22856,96 @@ var require_security_log = __commonJS({
22449
22856
  };
22450
22857
  });
22451
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
+ }
22452
22949
  return service;
22453
22950
  };
22454
22951
  module.exports.EVENT_UID = EVENT_UID;