strapi-plugin-magic-sessionmanager 4.16.1 → 4.18.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 (31) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +119 -25
  3. package/dist/admin/{Analytics-CMR62DiD.js → Analytics-C8fV6LDV.js} +1 -1
  4. package/dist/admin/{Analytics-FcRt0X62.mjs → Analytics-CBspdl1I.mjs} +1 -1
  5. package/dist/admin/{App-CmytGbze.js → App-D92MTQmn.js} +33 -170
  6. package/dist/admin/{App-DBieSWB0.mjs → App-PLwqaRSQ.mjs} +3 -140
  7. package/dist/admin/{OnlineUsersWidget-Lzx9XB74.js → OnlineUsersWidget-CiKapC1B.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-zP9Hl_it.mjs → OnlineUsersWidget-CwfBJdIX.mjs} +1 -1
  9. package/dist/admin/{Settings-CZOPusQK.mjs → Settings-CMgL-Aub.mjs} +2013 -78
  10. package/dist/admin/{Settings-1v--SXC0.js → Settings-Duil_4jv.js} +2017 -82
  11. package/dist/admin/dashboardModel-BhUonEqc.mjs +189 -0
  12. package/dist/admin/dashboardModel-sksvIc1c.js +188 -0
  13. package/dist/admin/{de-y_9mdVT7.js → de-CnInuvMY.js} +196 -11
  14. package/dist/admin/{de-D3TSA066.mjs → de-D2BqfY1f.mjs} +196 -11
  15. package/dist/admin/{en-B60I97bK.mjs → en-BPy208we.mjs} +196 -11
  16. package/dist/admin/{en-CIQB8nfI.js → en-KnmmYHTF.js} +196 -11
  17. package/dist/admin/{es-CJEL_iGC.mjs → es-B4VNeT0A.mjs} +196 -11
  18. package/dist/admin/{es-DHhHzlRY.js → es-D1NGCAJK.js} +196 -11
  19. package/dist/admin/{fr-BfBK_iuV.mjs → fr-AwhLN1BC.mjs} +196 -11
  20. package/dist/admin/{fr-D86FTt1w.js → fr-D1KNyogi.js} +196 -11
  21. package/dist/admin/{index-tt61o2VH.mjs → index-BmnC2BPs.mjs} +40 -38
  22. package/dist/admin/{index-CSJJn4qy.js → index-Bnt0Jq6O.js} +12 -10
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +1 -1
  25. package/dist/admin/{pt-C3PSvC7z.mjs → pt-D6m1TijL.mjs} +196 -11
  26. package/dist/admin/{pt-BE-FT-L8.js → pt-EKThRXPY.js} +196 -11
  27. package/dist/server/index.js +3230 -129
  28. package/dist/server/index.mjs +3230 -129
  29. package/package.json +1 -1
  30. package/dist/admin/riskData-BVs9GpgD.js +0 -26
  31. package/dist/admin/riskData-CI1gm2yI.mjs +0 -27
@@ -132,6 +132,11 @@ var require_coordination = __commonJS({
132
132
  throw new TypeError("coordination key must be a non-empty string of at most 191 characters");
133
133
  }
134
134
  }
135
+ function assertRegistryKey(key) {
136
+ if (typeof key !== "string" || !/^[a-z0-9:-]{1,180}$/.test(key)) {
137
+ throw new TypeError('registry key must be 1-180 lowercase letters, digits, ":" or "-"');
138
+ }
139
+ }
135
140
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
136
141
  var LockTimeoutError = class extends Error {
137
142
  constructor(name) {
@@ -144,6 +149,7 @@ var require_coordination = __commonJS({
144
149
  const leases = /* @__PURE__ */ new Map();
145
150
  const revisions = /* @__PURE__ */ new Map();
146
151
  const lockTails = /* @__PURE__ */ new Map();
152
+ const registry = /* @__PURE__ */ new Map();
147
153
  const pruneCounters = (now) => {
148
154
  if (counters.size < 5e3) return;
149
155
  for (const [k, v] of counters) {
@@ -173,13 +179,14 @@ var require_coordination = __commonJS({
173
179
  if (!entry) return null;
174
180
  return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
175
181
  },
176
- async block(key, untilMs) {
182
+ async block(key, untilMs, { windowStart } = {}) {
177
183
  const entry = counters.get(key) || {
178
184
  hits: 0,
179
185
  windowStart: 0,
180
186
  blockedUntil: 0,
181
187
  expiresAt: 0
182
188
  };
189
+ if (Number.isFinite(windowStart)) entry.windowStart = windowStart;
183
190
  if (entry.blockedUntil < untilMs) entry.blockedUntil = untilMs;
184
191
  entry.expiresAt = Math.max(entry.expiresAt, untilMs);
185
192
  counters.set(key, entry);
@@ -234,8 +241,33 @@ var require_coordination = __commonJS({
234
241
  },
235
242
  async cacheSet() {
236
243
  },
244
+ async registryPut(key, value, ttlMs, now = Date.now()) {
245
+ registry.set(key, { value, expiresAt: now + ttlMs });
246
+ },
247
+ async registryList(prefix, limit = 200, now = Date.now()) {
248
+ const out = [];
249
+ for (const [key, entry] of registry) {
250
+ if (entry.expiresAt <= now) {
251
+ registry.delete(key);
252
+ continue;
253
+ }
254
+ if (key.startsWith(prefix) && out.length < limit) out.push({ key, value: entry.value });
255
+ }
256
+ return out;
257
+ },
258
+ async registryDelete(key) {
259
+ registry.delete(key);
260
+ },
261
+ async registryTake(key, now = Date.now()) {
262
+ const entry = registry.get(key);
263
+ registry.delete(key);
264
+ return entry && entry.expiresAt > now ? entry.value : null;
265
+ },
237
266
  async prune(now = Date.now()) {
238
267
  let removed = 0;
268
+ for (const [k, v] of registry) {
269
+ if (v.expiresAt <= now) registry.delete(k);
270
+ }
239
271
  for (const [k, v] of counters) {
240
272
  if (v.expiresAt <= now && v.blockedUntil <= now) {
241
273
  counters.delete(k);
@@ -249,6 +281,7 @@ var require_coordination = __commonJS({
249
281
  leases.clear();
250
282
  revisions.clear();
251
283
  lockTails.clear();
284
+ registry.clear();
252
285
  }
253
286
  };
254
287
  }
@@ -390,14 +423,18 @@ var require_coordination = __commonJS({
390
423
  await knex(TABLES.counters).where({ k: key }).andWhere("hits", ">", 0).update({ hits: knex.raw("hits - 1") });
391
424
  },
392
425
  peek: readCounter,
393
- async block(key, untilMs) {
426
+ async block(key, untilMs, { windowStart } = {}) {
394
427
  await ensureCounterRow(key, untilMs);
395
428
  await knex(TABLES.counters).where({ k: key }).andWhere("blocked_until", "<", untilMs).update({
396
429
  blocked_until: untilMs,
397
430
  expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
398
431
  untilMs,
399
432
  untilMs
400
- ])
433
+ ]),
434
+ // Moves the counting window so it ends when the lock ends: the
435
+ // hits stay (requests already in flight are still turned away),
436
+ // and the first attempt after the lock starts a new window.
437
+ ...Number.isFinite(windowStart) ? { window_start: Math.trunc(windowStart) } : {}
401
438
  });
402
439
  },
403
440
  async clear(key) {
@@ -475,6 +512,42 @@ var require_coordination = __commonJS({
475
512
  const expiresAt = ttlMs === Infinity ? NEVER_EXPIRES : now + ttlMs;
476
513
  await knex(TABLES.cache).insert({ k: key, v: JSON.stringify(value), expires_at: expiresAt }).onConflict("k").merge(["v", "expires_at"]);
477
514
  },
515
+ /**
516
+ * Listable entries live in the cache table under their own key prefix
517
+ * (`reg:`), so they share its expiry index and pruning.
518
+ */
519
+ async registryPut(key, value, ttlMs, now = Date.now()) {
520
+ await knex(TABLES.cache).insert({ k: `reg:${key}`, v: JSON.stringify(value), expires_at: now + ttlMs }).onConflict("k").merge(["v", "expires_at"]);
521
+ },
522
+ async registryList(prefix, limit = 200, now = Date.now()) {
523
+ const rows = await knex(TABLES.cache).select("k", "v").where("k", "like", `reg:${prefix}%`).andWhere("expires_at", ">", now).orderBy("k", "asc").limit(limit);
524
+ const out = [];
525
+ for (const row of rows) {
526
+ try {
527
+ out.push({ key: String(row.k).slice(4), value: JSON.parse(row.v) });
528
+ } catch {
529
+ }
530
+ }
531
+ return out;
532
+ },
533
+ async registryDelete(key) {
534
+ await knex(TABLES.cache).where({ k: `reg:${key}` }).del();
535
+ },
536
+ /**
537
+ * Reads and deletes an entry. Only the caller whose DELETE removed the
538
+ * row gets the value, so parallel takes of one key yield it once.
539
+ */
540
+ async registryTake(key, now = Date.now()) {
541
+ const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: `reg:${key}` }).first();
542
+ if (!row) return null;
543
+ const deleted = await knex(TABLES.cache).where({ k: `reg:${key}`, expires_at: row.expires_at }).del();
544
+ if (toNumber(deleted) !== 1 || toNumber(row.expires_at) <= now) return null;
545
+ try {
546
+ return JSON.parse(row.v);
547
+ } catch {
548
+ return null;
549
+ }
550
+ },
478
551
  async prune(now = Date.now()) {
479
552
  const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
480
553
  const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
@@ -555,10 +628,17 @@ var require_coordination = __commonJS({
555
628
  assertKey(key);
556
629
  return counterCall("counter read", "peek", [key]);
557
630
  },
558
- /** Raises the block deadline of `key` to `untilMs` (never lowers it). */
559
- block(key, untilMs) {
631
+ /**
632
+ * Raises the block deadline of `key` to `untilMs` (never lowers it).
633
+ * With `windowStart` the counting window is moved (see the lockout).
634
+ */
635
+ block(key, untilMs, options) {
560
636
  assertKey(key);
561
- return counterCall("counter block", "block", [key, untilMs]);
637
+ return counterCall(
638
+ "counter block",
639
+ "block",
640
+ options ? [key, untilMs, options] : [key, untilMs]
641
+ );
562
642
  },
563
643
  /** Removes counter `key`. */
564
644
  clear(key) {
@@ -658,6 +738,66 @@ var require_coordination = __commonJS({
658
738
  () => sharedMemory.cacheSet(key, value, ttlMs)
659
739
  );
660
740
  },
741
+ /**
742
+ * Stores a listable entry (for example an active sign-in lock) until
743
+ * `ttlMs` from now. Unlike the cache it also works in memory mode, and
744
+ * entries can be listed by key prefix. Keys use lowercase letters,
745
+ * digits, `:` and `-` only, so they are free of LIKE wildcards.
746
+ *
747
+ * @param {string} key Entry key (at most 180 characters).
748
+ * @param {unknown} value JSON-serialisable value.
749
+ * @param {number} ttlMs Lifetime in milliseconds.
750
+ * @returns {Promise<void>}
751
+ */
752
+ registryPut(key, value, ttlMs) {
753
+ assertRegistryKey(key);
754
+ return run(
755
+ "registry write",
756
+ (backend) => backend.registryPut(key, value, ttlMs),
757
+ () => sharedMemory.registryPut(key, value, ttlMs)
758
+ );
759
+ },
760
+ /**
761
+ * Unexpired entries whose key starts with `prefix`, ordered by key.
762
+ *
763
+ * @param {string} prefix Key prefix (letters, digits, `:` and `-` only).
764
+ * @param {number} [limit] Most entries returned.
765
+ * @returns {Promise<Array<{key: string, value: any}>>}
766
+ */
767
+ registryList(prefix, limit = 200) {
768
+ if (typeof prefix !== "string" || !/^[a-z0-9:-]{1,180}$/.test(prefix)) {
769
+ throw new TypeError('registry prefix must be letters, digits, ":" or "-"');
770
+ }
771
+ return run(
772
+ "registry read",
773
+ (backend) => backend.registryList(prefix, limit),
774
+ () => sharedMemory.registryList(prefix, limit)
775
+ );
776
+ },
777
+ /**
778
+ * Takes a listable entry once: returns its value and removes it. Of
779
+ * several concurrent takes (any process) at most one gets the value.
780
+ *
781
+ * @param {string} key Entry key.
782
+ * @returns {Promise<any|null>} Value, or null when absent, expired or taken.
783
+ */
784
+ registryTake(key) {
785
+ assertRegistryKey(key);
786
+ return run(
787
+ "registry take",
788
+ (backend) => backend.registryTake(key),
789
+ () => sharedMemory.registryTake(key)
790
+ );
791
+ },
792
+ /** Removes a listable entry. */
793
+ registryDelete(key) {
794
+ assertRegistryKey(key);
795
+ return run(
796
+ "registry delete",
797
+ (backend) => backend.registryDelete(key),
798
+ () => sharedMemory.registryDelete(key)
799
+ );
800
+ },
661
801
  prune() {
662
802
  return run(
663
803
  "prune",
@@ -811,7 +951,7 @@ var require_content_api_permissions = __commonJS({
811
951
  "server/src/utils/content-api-permissions.js"(exports, module) {
812
952
  "use strict";
813
953
  var { withPluginStoreKey } = require_plugin_store();
814
- var CONTENT_API_PERMISSIONS_VERSION = 2;
954
+ var CONTENT_API_PERMISSIONS_VERSION = 3;
815
955
  var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
816
956
  var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
817
957
  async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
@@ -990,11 +1130,575 @@ var require_security_log_settings = __commonJS({
990
1130
  }
991
1131
  });
992
1132
 
1133
+ // server/src/utils/policy-settings.js
1134
+ var require_policy_settings = __commonJS({
1135
+ "server/src/utils/policy-settings.js"(exports, module) {
1136
+ "use strict";
1137
+ var net = __require("node:net");
1138
+ var POLICY_DEFAULTS = Object.freeze({
1139
+ maxFailedLoginsPerAccount: 0,
1140
+ lockoutWindowMinutes: 15,
1141
+ lockoutDurationMinutes: 15,
1142
+ lockoutTrustedAddresses: Object.freeze([]),
1143
+ lockoutNotifyUser: false,
1144
+ recordUserSignInEvents: true,
1145
+ maxSessionsPerUser: 0,
1146
+ sessionLimitPolicy: "end-oldest",
1147
+ endOtherSessionsOnPasswordChange: true,
1148
+ roleRules: Object.freeze([])
1149
+ });
1150
+ var POLICY_KEYS = Object.freeze(Object.keys(POLICY_DEFAULTS));
1151
+ var POLICY_RANGES = Object.freeze({
1152
+ maxFailedLoginsPerAccount: Object.freeze([0, 100]),
1153
+ lockoutWindowMinutes: Object.freeze([1, 1440]),
1154
+ lockoutDurationMinutes: Object.freeze([1, 10080]),
1155
+ maxSessionsPerUser: Object.freeze([0, 100])
1156
+ });
1157
+ var ROLE_RULE_RANGES = Object.freeze({
1158
+ maxSessionsPerUser: Object.freeze([0, 100]),
1159
+ inactivityTimeout: Object.freeze([1, 1440]),
1160
+ maxFailedLoginsPerAccount: Object.freeze([0, 100])
1161
+ });
1162
+ var ROLE_RULE_FIELDS = Object.freeze(Object.keys(ROLE_RULE_RANGES));
1163
+ var SESSION_LIMIT_POLICIES = Object.freeze(["end-oldest", "refuse"]);
1164
+ var BOOLEAN_KEYS = Object.freeze([
1165
+ "lockoutNotifyUser",
1166
+ "recordUserSignInEvents",
1167
+ "endOtherSessionsOnPasswordChange"
1168
+ ]);
1169
+ var MAX_TRUSTED_ADDRESSES = 100;
1170
+ var MAX_ROLE_RULES = 50;
1171
+ var ROLE_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1172
+ function parseInteger(value) {
1173
+ if (typeof value === "number") return Number.isInteger(value) ? value : null;
1174
+ if (typeof value === "string" && /^\s*-?\d{1,9}\s*$/.test(value)) {
1175
+ return Number.parseInt(value, 10);
1176
+ }
1177
+ return null;
1178
+ }
1179
+ function parseTrustedAddress(value) {
1180
+ if (typeof value !== "string") return null;
1181
+ const text = value.trim();
1182
+ if (!text || text.length > 64) return null;
1183
+ const [rawAddress, rawPrefix, extra] = text.split("/");
1184
+ if (extra !== void 0) return null;
1185
+ let address = rawAddress;
1186
+ if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
1187
+ address = address.slice(7);
1188
+ }
1189
+ const version = net.isIP(address);
1190
+ if (version === 0) return null;
1191
+ const family = version === 4 ? "ipv4" : "ipv6";
1192
+ if (rawPrefix === void 0) {
1193
+ return { text: address.toLowerCase(), address, prefix: null, family };
1194
+ }
1195
+ if (!/^\d{1,3}$/.test(rawPrefix)) return null;
1196
+ const prefix = Number(rawPrefix);
1197
+ if (prefix > (family === "ipv4" ? 32 : 128)) return null;
1198
+ return { text: `${address.toLowerCase()}/${prefix}`, address, prefix, family };
1199
+ }
1200
+ var blockListCache = /* @__PURE__ */ new Map();
1201
+ function trustedAddressList(entries) {
1202
+ const key = entries.join("\n");
1203
+ const cached = blockListCache.get(key);
1204
+ if (cached) return cached;
1205
+ const list = new net.BlockList();
1206
+ for (const entry of entries) {
1207
+ const parsed = parseTrustedAddress(entry);
1208
+ if (!parsed) continue;
1209
+ if (parsed.prefix === null) list.addAddress(parsed.address, parsed.family);
1210
+ else list.addSubnet(parsed.address, parsed.prefix, parsed.family);
1211
+ }
1212
+ if (blockListCache.size > 20) blockListCache.clear();
1213
+ blockListCache.set(key, list);
1214
+ return list;
1215
+ }
1216
+ function isTrustedAddress(entries, ip) {
1217
+ if (!entries.length || typeof ip !== "string") return false;
1218
+ let address = ip.trim();
1219
+ if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
1220
+ address = address.slice(7);
1221
+ }
1222
+ const version = net.isIP(address);
1223
+ if (version === 0) return false;
1224
+ try {
1225
+ return trustedAddressList(entries).check(address, version === 4 ? "ipv4" : "ipv6");
1226
+ } catch {
1227
+ return false;
1228
+ }
1229
+ }
1230
+ function normalizeRoleRules(value) {
1231
+ if (!Array.isArray(value)) return [];
1232
+ const seen = /* @__PURE__ */ new Set();
1233
+ const out = [];
1234
+ for (const raw of value.slice(0, MAX_ROLE_RULES)) {
1235
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
1236
+ const role = typeof raw.role === "string" ? raw.role : "";
1237
+ if (!ROLE_ID_PATTERN.test(role) || seen.has(role)) continue;
1238
+ const rule = { role };
1239
+ for (const field of ROLE_RULE_FIELDS) {
1240
+ const [min, max] = (
1241
+ /** @type {any} */
1242
+ ROLE_RULE_RANGES[field]
1243
+ );
1244
+ const number = raw[field] === null || raw[field] === void 0 ? null : parseInteger(raw[field]);
1245
+ rule[field] = number !== null && number >= min && number <= max ? number : null;
1246
+ }
1247
+ seen.add(role);
1248
+ out.push(rule);
1249
+ }
1250
+ return out;
1251
+ }
1252
+ function normalizePolicySettings(stored) {
1253
+ const out = {};
1254
+ if (!stored || typeof stored !== "object") return out;
1255
+ for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
1256
+ if (stored[key] === void 0) continue;
1257
+ const number = parseInteger(stored[key]);
1258
+ out[key] = number !== null && number >= min && number <= max ? number : (
1259
+ /** @type {any} */
1260
+ POLICY_DEFAULTS[key]
1261
+ );
1262
+ }
1263
+ for (const key of BOOLEAN_KEYS) {
1264
+ if (stored[key] !== void 0) out[key] = stored[key] === true;
1265
+ }
1266
+ if (stored.sessionLimitPolicy !== void 0) {
1267
+ out.sessionLimitPolicy = SESSION_LIMIT_POLICIES.includes(
1268
+ /** @type {string} */
1269
+ stored.sessionLimitPolicy
1270
+ ) ? stored.sessionLimitPolicy : POLICY_DEFAULTS.sessionLimitPolicy;
1271
+ }
1272
+ if (stored.lockoutTrustedAddresses !== void 0) {
1273
+ out.lockoutTrustedAddresses = Array.isArray(stored.lockoutTrustedAddresses) ? stored.lockoutTrustedAddresses.slice(0, MAX_TRUSTED_ADDRESSES).map(parseTrustedAddress).filter(Boolean).map((entry) => (
1274
+ /** @type {any} */
1275
+ entry.text
1276
+ )) : [];
1277
+ }
1278
+ if (stored.roleRules !== void 0) out.roleRules = normalizeRoleRules(stored.roleRules);
1279
+ return out;
1280
+ }
1281
+ function validatePolicySettings(body) {
1282
+ const values = {};
1283
+ const errors = [];
1284
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
1285
+ for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
1286
+ if (!has(key)) continue;
1287
+ const number = parseInteger(body[key]);
1288
+ if (number === null || number < min || number > max) {
1289
+ errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
1290
+ } else {
1291
+ values[key] = number;
1292
+ }
1293
+ }
1294
+ for (const key of BOOLEAN_KEYS) {
1295
+ if (!has(key)) continue;
1296
+ if (typeof body[key] !== "boolean") {
1297
+ errors.push({ path: [key], message: `${key} must be a boolean` });
1298
+ } else {
1299
+ values[key] = body[key];
1300
+ }
1301
+ }
1302
+ if (has("sessionLimitPolicy")) {
1303
+ if (!SESSION_LIMIT_POLICIES.includes(
1304
+ /** @type {string} */
1305
+ body.sessionLimitPolicy
1306
+ )) {
1307
+ errors.push({
1308
+ path: ["sessionLimitPolicy"],
1309
+ message: `sessionLimitPolicy must be one of: ${SESSION_LIMIT_POLICIES.join(", ")}`
1310
+ });
1311
+ } else {
1312
+ values.sessionLimitPolicy = body.sessionLimitPolicy;
1313
+ }
1314
+ }
1315
+ if (has("lockoutTrustedAddresses")) {
1316
+ const list = body.lockoutTrustedAddresses;
1317
+ if (!Array.isArray(list) || list.length > MAX_TRUSTED_ADDRESSES) {
1318
+ errors.push({
1319
+ path: ["lockoutTrustedAddresses"],
1320
+ message: `lockoutTrustedAddresses must be a list of at most ${MAX_TRUSTED_ADDRESSES} IP addresses or CIDR ranges`
1321
+ });
1322
+ } else {
1323
+ const parsed = list.map(parseTrustedAddress);
1324
+ const invalid = parsed.findIndex((entry) => entry === null);
1325
+ if (invalid !== -1) {
1326
+ errors.push({
1327
+ path: ["lockoutTrustedAddresses", invalid],
1328
+ message: "Each trusted address must be an IP address or a CIDR range such as 192.0.2.0/24"
1329
+ });
1330
+ } else {
1331
+ values.lockoutTrustedAddresses = [
1332
+ ...new Set(parsed.map((entry) => (
1333
+ /** @type {any} */
1334
+ entry.text
1335
+ )))
1336
+ ];
1337
+ }
1338
+ }
1339
+ }
1340
+ if (has("roleRules")) {
1341
+ const rules = body.roleRules;
1342
+ if (!Array.isArray(rules) || rules.length > MAX_ROLE_RULES) {
1343
+ errors.push({
1344
+ path: ["roleRules"],
1345
+ message: `roleRules must be a list of at most ${MAX_ROLE_RULES} rules`
1346
+ });
1347
+ } else {
1348
+ const seen = /* @__PURE__ */ new Set();
1349
+ const clean = [];
1350
+ rules.forEach((raw, index) => {
1351
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1352
+ errors.push({ path: ["roleRules", index], message: "A role rule must be an object" });
1353
+ return;
1354
+ }
1355
+ const role = raw.role;
1356
+ if (typeof role !== "string" || !ROLE_ID_PATTERN.test(role)) {
1357
+ errors.push({ path: ["roleRules", index, "role"], message: "Choose a role" });
1358
+ return;
1359
+ }
1360
+ if (seen.has(role)) {
1361
+ errors.push({
1362
+ path: ["roleRules", index, "role"],
1363
+ message: "This role already has a rule"
1364
+ });
1365
+ return;
1366
+ }
1367
+ seen.add(role);
1368
+ const rule = { role };
1369
+ let overrides = 0;
1370
+ for (const field of ROLE_RULE_FIELDS) {
1371
+ const [min, max] = (
1372
+ /** @type {any} */
1373
+ ROLE_RULE_RANGES[field]
1374
+ );
1375
+ const rawValue = raw[field];
1376
+ if (rawValue === null || rawValue === void 0 || rawValue === "") {
1377
+ rule[field] = null;
1378
+ continue;
1379
+ }
1380
+ const number = parseInteger(rawValue);
1381
+ if (number === null || number < min || number > max) {
1382
+ errors.push({
1383
+ path: ["roleRules", index, field],
1384
+ message: `${field} must be empty or an integer between ${min} and ${max}`
1385
+ });
1386
+ continue;
1387
+ }
1388
+ rule[field] = number;
1389
+ overrides += 1;
1390
+ }
1391
+ if (overrides === 0 && !errors.some((e) => e.path[1] === index)) {
1392
+ errors.push({
1393
+ path: ["roleRules", index],
1394
+ message: "A role rule needs at least one value"
1395
+ });
1396
+ return;
1397
+ }
1398
+ clean.push(rule);
1399
+ });
1400
+ if (!errors.some((e) => e.path[0] === "roleRules")) values.roleRules = clean;
1401
+ }
1402
+ }
1403
+ return { values, errors };
1404
+ }
1405
+ function policyValue(settings, key) {
1406
+ const source = settings && typeof settings === "object" ? settings : {};
1407
+ const clean = normalizePolicySettings({ [key]: source[key] });
1408
+ return clean[key] !== void 0 ? clean[key] : POLICY_DEFAULTS[key];
1409
+ }
1410
+ function roleRuleFor(settings, roleDocumentId) {
1411
+ if (!roleDocumentId) return null;
1412
+ const rules = (
1413
+ /** @type {any[]} */
1414
+ policyValue(settings, "roleRules")
1415
+ );
1416
+ return rules.find((rule) => rule.role === roleDocumentId) || null;
1417
+ }
1418
+ function hasRoleOverride(settings, field) {
1419
+ const rules = (
1420
+ /** @type {any[]} */
1421
+ policyValue(settings, "roleRules")
1422
+ );
1423
+ return rules.some((rule) => rule[field] !== null && rule[field] !== void 0);
1424
+ }
1425
+ function resolveLockoutPolicy(settings) {
1426
+ const source = settings && typeof settings === "object" ? settings : {};
1427
+ const ipRaw = parseInteger(source.maxFailedLogins);
1428
+ return {
1429
+ ipMax: ipRaw !== null && ipRaw >= 0 && ipRaw <= 100 ? ipRaw : 0,
1430
+ accountMax: policyValue(source, "maxFailedLoginsPerAccount"),
1431
+ accountMaxByRole: hasRoleOverride(source, "maxFailedLoginsPerAccount"),
1432
+ windowMs: policyValue(source, "lockoutWindowMinutes") * 60 * 1e3,
1433
+ durationMs: policyValue(source, "lockoutDurationMinutes") * 60 * 1e3,
1434
+ trusted: policyValue(source, "lockoutTrustedAddresses"),
1435
+ notifyUser: policyValue(source, "lockoutNotifyUser"),
1436
+ record: policyValue(source, "recordUserSignInEvents")
1437
+ };
1438
+ }
1439
+ function accountThresholdFor(settings, roleDocumentId) {
1440
+ const rule = roleRuleFor(settings, roleDocumentId);
1441
+ if (rule && rule.maxFailedLoginsPerAccount !== null) return rule.maxFailedLoginsPerAccount;
1442
+ return policyValue(settings, "maxFailedLoginsPerAccount");
1443
+ }
1444
+ function sessionLimitFor(settings, roleDocumentId) {
1445
+ const rule = roleRuleFor(settings, roleDocumentId);
1446
+ const limit = rule && rule.maxSessionsPerUser !== null ? rule.maxSessionsPerUser : policyValue(settings, "maxSessionsPerUser");
1447
+ return { limit, policy: policyValue(settings, "sessionLimitPolicy") };
1448
+ }
1449
+ function inactivityTimeoutFor(settings, roleDocumentId) {
1450
+ const rule = roleRuleFor(settings, roleDocumentId);
1451
+ if (rule && rule.inactivityTimeout !== null) return rule.inactivityTimeout * 60 * 1e3;
1452
+ const general = Number(settings?.inactivityTimeout);
1453
+ return Number.isFinite(general) && general > 0 ? general : 15 * 60 * 1e3;
1454
+ }
1455
+ module.exports = {
1456
+ POLICY_DEFAULTS,
1457
+ POLICY_KEYS,
1458
+ POLICY_RANGES,
1459
+ ROLE_RULE_FIELDS,
1460
+ ROLE_RULE_RANGES,
1461
+ SESSION_LIMIT_POLICIES,
1462
+ MAX_ROLE_RULES,
1463
+ MAX_TRUSTED_ADDRESSES,
1464
+ accountThresholdFor,
1465
+ hasRoleOverride,
1466
+ inactivityTimeoutFor,
1467
+ isTrustedAddress,
1468
+ normalizePolicySettings,
1469
+ normalizeRoleRules,
1470
+ parseTrustedAddress,
1471
+ policyValue,
1472
+ resolveLockoutPolicy,
1473
+ roleRuleFor,
1474
+ sessionLimitFor,
1475
+ validatePolicySettings
1476
+ };
1477
+ }
1478
+ });
1479
+
1480
+ // server/src/utils/detection-settings.js
1481
+ var require_detection_settings = __commonJS({
1482
+ "server/src/utils/detection-settings.js"(exports, module) {
1483
+ "use strict";
1484
+ var WEBHOOK_EVENTS = Object.freeze([
1485
+ "login.success",
1486
+ "login.suspicious",
1487
+ "login.new_location",
1488
+ "login.new_device",
1489
+ "login.impossible_travel",
1490
+ "login.failed",
1491
+ "login.refused",
1492
+ "lockout",
1493
+ "lockout.lifted",
1494
+ "session.limit",
1495
+ "password.changed",
1496
+ "user.not_me"
1497
+ ]);
1498
+ var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
1499
+ "login.suspicious",
1500
+ "login.new_location",
1501
+ "login.new_device",
1502
+ "login.impossible_travel",
1503
+ "lockout",
1504
+ "user.not_me"
1505
+ ]);
1506
+ var LEGACY_WEBHOOK_EVENTS = Object.freeze([
1507
+ "login.success",
1508
+ "login.suspicious",
1509
+ "login.new_location"
1510
+ ]);
1511
+ var IMPOSSIBLE_TRAVEL_ACTIONS = Object.freeze(["alert", "reauthenticate"]);
1512
+ var DETECTION_DEFAULTS = Object.freeze({
1513
+ alertOnNewDevice: false,
1514
+ alertOnImpossibleTravel: false,
1515
+ impossibleTravelEnabled: false,
1516
+ impossibleTravelSpeedKmh: 1e3,
1517
+ impossibleTravelMinDistanceKm: 500,
1518
+ impossibleTravelAction: "alert",
1519
+ webhookEvents: DEFAULT_WEBHOOK_EVENTS,
1520
+ genericWebhookEnabled: false,
1521
+ genericWebhookUrl: "",
1522
+ sessionIpAnonymize: false
1523
+ });
1524
+ var DETECTION_KEYS = Object.freeze(Object.keys(DETECTION_DEFAULTS));
1525
+ var PROTECTED_DETECTION_KEYS = Object.freeze([
1526
+ "impossibleTravelEnabled",
1527
+ "impossibleTravelSpeedKmh",
1528
+ "impossibleTravelMinDistanceKm",
1529
+ "impossibleTravelAction",
1530
+ "webhookEvents",
1531
+ "genericWebhookEnabled",
1532
+ "genericWebhookUrl",
1533
+ "genericWebhookSecret",
1534
+ "sessionIpAnonymize"
1535
+ ]);
1536
+ var RANGES = Object.freeze({
1537
+ impossibleTravelSpeedKmh: Object.freeze([100, 5e3]),
1538
+ impossibleTravelMinDistanceKm: Object.freeze([50, 2e4])
1539
+ });
1540
+ var BOOLEAN_KEYS = Object.freeze([
1541
+ "alertOnNewDevice",
1542
+ "alertOnImpossibleTravel",
1543
+ "impossibleTravelEnabled",
1544
+ "genericWebhookEnabled",
1545
+ "sessionIpAnonymize"
1546
+ ]);
1547
+ var MAX_URL_LENGTH = 2048;
1548
+ function parseInteger(value) {
1549
+ if (typeof value === "number") return Number.isInteger(value) ? value : null;
1550
+ if (typeof value === "string" && /^\s*\d{1,9}\s*$/.test(value)) return Number.parseInt(value, 10);
1551
+ return null;
1552
+ }
1553
+ function normalizeWebhookUrl(value) {
1554
+ if (typeof value !== "string") return null;
1555
+ const trimmed = value.trim();
1556
+ if (!trimmed || trimmed.length > MAX_URL_LENGTH) return null;
1557
+ let parsed;
1558
+ try {
1559
+ parsed = new URL(trimmed);
1560
+ } catch {
1561
+ return null;
1562
+ }
1563
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) return null;
1564
+ const host = parsed.hostname.toLowerCase();
1565
+ if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
1566
+ return null;
1567
+ }
1568
+ return parsed.toString();
1569
+ }
1570
+ function normalizeEventList(value) {
1571
+ if (!Array.isArray(value)) return null;
1572
+ return [...new Set(value.filter((event) => WEBHOOK_EVENTS.includes(event)))];
1573
+ }
1574
+ function normalizeDetectionSettings(stored) {
1575
+ const out = {};
1576
+ if (!stored || typeof stored !== "object") return out;
1577
+ for (const key of BOOLEAN_KEYS) if (stored[key] !== void 0) out[key] = stored[key] === true;
1578
+ for (const [key, [min, max]] of Object.entries(RANGES)) {
1579
+ if (stored[key] === void 0) continue;
1580
+ const number = parseInteger(stored[key]);
1581
+ out[key] = number !== null && number >= min && number <= max ? number : (
1582
+ /** @type {any} */
1583
+ DETECTION_DEFAULTS[key]
1584
+ );
1585
+ }
1586
+ if (stored.impossibleTravelAction !== void 0) {
1587
+ out.impossibleTravelAction = IMPOSSIBLE_TRAVEL_ACTIONS.includes(
1588
+ /** @type {string} */
1589
+ stored.impossibleTravelAction
1590
+ ) ? stored.impossibleTravelAction : "alert";
1591
+ }
1592
+ if (stored.webhookEvents !== void 0) {
1593
+ out.webhookEvents = normalizeEventList(stored.webhookEvents) || [...DEFAULT_WEBHOOK_EVENTS];
1594
+ }
1595
+ if (stored.genericWebhookUrl !== void 0) {
1596
+ out.genericWebhookUrl = normalizeWebhookUrl(stored.genericWebhookUrl) || "";
1597
+ }
1598
+ return out;
1599
+ }
1600
+ function validateDetectionSettings(body) {
1601
+ const values = {};
1602
+ const errors = [];
1603
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
1604
+ for (const key of BOOLEAN_KEYS) {
1605
+ if (!has(key)) continue;
1606
+ if (typeof body[key] !== "boolean")
1607
+ errors.push({ path: [key], message: `${key} must be a boolean` });
1608
+ else values[key] = body[key];
1609
+ }
1610
+ for (const [key, [min, max]] of Object.entries(RANGES)) {
1611
+ if (!has(key)) continue;
1612
+ const number = parseInteger(body[key]);
1613
+ if (number === null || number < min || number > max) {
1614
+ errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
1615
+ } else {
1616
+ values[key] = number;
1617
+ }
1618
+ }
1619
+ if (has("impossibleTravelAction")) {
1620
+ if (!IMPOSSIBLE_TRAVEL_ACTIONS.includes(
1621
+ /** @type {string} */
1622
+ body.impossibleTravelAction
1623
+ )) {
1624
+ errors.push({
1625
+ path: ["impossibleTravelAction"],
1626
+ message: `impossibleTravelAction must be one of: ${IMPOSSIBLE_TRAVEL_ACTIONS.join(", ")}`
1627
+ });
1628
+ } else {
1629
+ values.impossibleTravelAction = body.impossibleTravelAction;
1630
+ }
1631
+ }
1632
+ if (has("webhookEvents")) {
1633
+ const list = body.webhookEvents;
1634
+ if (!Array.isArray(list) || list.length > WEBHOOK_EVENTS.length || list.some((event) => !WEBHOOK_EVENTS.includes(event))) {
1635
+ errors.push({
1636
+ path: ["webhookEvents"],
1637
+ message: `webhookEvents must be a list of: ${WEBHOOK_EVENTS.join(", ")}`
1638
+ });
1639
+ } else {
1640
+ values.webhookEvents = [...new Set(list)];
1641
+ }
1642
+ }
1643
+ if (has("genericWebhookUrl")) {
1644
+ const raw = body.genericWebhookUrl;
1645
+ if (typeof raw !== "string") {
1646
+ errors.push({ path: ["genericWebhookUrl"], message: "genericWebhookUrl must be a string" });
1647
+ } else if (!raw.trim()) {
1648
+ values.genericWebhookUrl = "";
1649
+ } else {
1650
+ const url = normalizeWebhookUrl(raw);
1651
+ if (!url) {
1652
+ errors.push({
1653
+ path: ["genericWebhookUrl"],
1654
+ message: "genericWebhookUrl must be an https URL without credentials on a public host name"
1655
+ });
1656
+ } else {
1657
+ values.genericWebhookUrl = url;
1658
+ }
1659
+ }
1660
+ }
1661
+ return { values, errors };
1662
+ }
1663
+ function resolveDetectionSettings(settings) {
1664
+ const source = settings && typeof settings === "object" ? settings : {};
1665
+ const clean = normalizeDetectionSettings(
1666
+ Object.fromEntries(
1667
+ DETECTION_KEYS.map((key) => [key, source[key]]).filter(([, v]) => v !== void 0)
1668
+ )
1669
+ );
1670
+ return (
1671
+ /** @type {any} */
1672
+ {
1673
+ ...DETECTION_DEFAULTS,
1674
+ webhookEvents: [...DEFAULT_WEBHOOK_EVENTS],
1675
+ ...clean
1676
+ }
1677
+ );
1678
+ }
1679
+ module.exports = {
1680
+ DEFAULT_WEBHOOK_EVENTS,
1681
+ DETECTION_DEFAULTS,
1682
+ DETECTION_KEYS,
1683
+ PROTECTED_DETECTION_KEYS,
1684
+ IMPOSSIBLE_TRAVEL_ACTIONS,
1685
+ LEGACY_WEBHOOK_EVENTS,
1686
+ WEBHOOK_EVENTS,
1687
+ normalizeDetectionSettings,
1688
+ normalizeWebhookUrl,
1689
+ resolveDetectionSettings,
1690
+ validateDetectionSettings
1691
+ };
1692
+ }
1693
+ });
1694
+
993
1695
  // server/src/utils/settings-loader.js
994
1696
  var require_settings_loader = __commonJS({
995
1697
  "server/src/utils/settings-loader.js"(exports, module) {
996
1698
  "use strict";
997
1699
  var { getCoordinator } = require_coordination();
1700
+ var { normalizePolicySettings } = require_policy_settings();
1701
+ var { normalizeDetectionSettings } = require_detection_settings();
998
1702
  var PLUGIN_ID = "magic-sessionmanager";
999
1703
  var SETTINGS_KEY = "settings";
1000
1704
  var CACHE_TTL_MS = 30 * 1e3;
@@ -1126,6 +1830,11 @@ var require_settings_loader = __commonJS({
1126
1830
  if (stored.trustedProxies !== void 0) {
1127
1831
  out.trustedProxies = stored.trustedProxies;
1128
1832
  }
1833
+ Object.assign(out, normalizePolicySettings(stored));
1834
+ Object.assign(out, normalizeDetectionSettings(stored));
1835
+ if (typeof stored.genericWebhookSecret === "string") {
1836
+ out.genericWebhookSecret = stored.genericWebhookSecret;
1837
+ }
1129
1838
  return out;
1130
1839
  }
1131
1840
  async function getPluginSettings(strapi2) {
@@ -1236,7 +1945,18 @@ var require_security_log_model = __commonJS({
1236
1945
  // 4.17: always recorded (no switch), never values.
1237
1946
  SETTINGS_UPDATED: "settings.updated",
1238
1947
  LOG_RETENTION_PURGED: "security-log.retention.purged",
1239
- LOG_READ: "security-log.read"
1948
+ LOG_READ: "security-log.read",
1949
+ // App users (Users & Permissions), 4.17.
1950
+ USER_SIGN_IN_FAILED: "user.sign-in.failed",
1951
+ USER_SIGN_IN_REFUSED: "user.sign-in.refused",
1952
+ USER_LOCKOUT: "user.lockout",
1953
+ USER_LOCKOUT_LIFTED: "user.lockout.lifted",
1954
+ USER_SESSION_LIMIT: "user.session.limit",
1955
+ USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others",
1956
+ USER_NEW_DEVICE: "user.sign-in.new-device",
1957
+ USER_IMPOSSIBLE_TRAVEL: "user.sign-in.impossible-travel",
1958
+ USER_NOT_ME: "user.not-me",
1959
+ USER_DATA_EXPORTED: "user.data.exported"
1240
1960
  });
1241
1961
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
1242
1962
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
@@ -1244,7 +1964,7 @@ var require_security_log_model = __commonJS({
1244
1964
  SECURITY_EVENTS.LOG_READ
1245
1965
  ]);
1246
1966
  function dropRankOf(event) {
1247
- if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
1967
+ if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
1248
1968
  return { rank: 0, family: "failed" };
1249
1969
  }
1250
1970
  if (event === SECURITY_EVENTS.ADMIN_CONTENT_VIEW) return { rank: 1, family: "content-view" };
@@ -1253,6 +1973,19 @@ var require_security_log_model = __commonJS({
1253
1973
  }
1254
1974
  return { rank: 3, family: "account" };
1255
1975
  }
1976
+ var USER_SIGN_IN_EVENTS = Object.freeze([
1977
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
1978
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
1979
+ SECURITY_EVENTS.USER_LOCKOUT
1980
+ ]);
1981
+ var REFUSAL_REASONS = Object.freeze([
1982
+ "lockout",
1983
+ "too-many-attempts",
1984
+ "session-limit",
1985
+ "country",
1986
+ "risk",
1987
+ "location-unavailable"
1988
+ ]);
1256
1989
  var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
1257
1990
  var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
1258
1991
  var ADMIN_SIGN_IN_EVENTS = Object.freeze([
@@ -1283,6 +2016,7 @@ var require_security_log_model = __commonJS({
1283
2016
  function recordingSwitchOf(event) {
1284
2017
  if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
1285
2018
  if (event.startsWith("admin.content.")) return "content";
2019
+ if (USER_SIGN_IN_EVENTS.includes(event)) return "userSignIns";
1286
2020
  return "always";
1287
2021
  }
1288
2022
  var CONTENT_MANAGER_HANDLERS = Object.freeze({
@@ -1463,6 +2197,8 @@ var require_security_log_model = __commonJS({
1463
2197
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1464
2198
  }
1465
2199
  module.exports = {
2200
+ REFUSAL_REASONS,
2201
+ USER_SIGN_IN_EVENTS,
1466
2202
  ACTOR_TYPES,
1467
2203
  ADMIN_CONTENT_EVENTS,
1468
2204
  ADMIN_SIGN_IN_EVENTS,
@@ -1721,10 +2457,19 @@ var require_register = __commonJS({
1721
2457
  // secrets) and the security log. The other settings stay on `access`.
1722
2458
  {
1723
2459
  section: "plugins",
1724
- displayName: "Change protected settings (location lookup, webhooks, security log)",
2460
+ displayName: "Change protected settings (location lookup, webhooks, security log, sign-in policies)",
1725
2461
  uid: "settings.update",
1726
2462
  subCategory: "Settings",
1727
2463
  pluginName: "magic-sessionmanager"
2464
+ },
2465
+ // Lifting a sign-in lock of an app user or IP address (4.17). Seeing the
2466
+ // locks only needs plugin access.
2467
+ {
2468
+ section: "plugins",
2469
+ displayName: "Unlock locked sign-ins",
2470
+ uid: "lockouts.unlock",
2471
+ subCategory: "General",
2472
+ pluginName: "magic-sessionmanager"
1728
2473
  }
1729
2474
  ]);
1730
2475
  disableGraphqlShadowCrud(strapi2, log);
@@ -1775,6 +2520,20 @@ var require_register = __commonJS({
1775
2520
  } catch (err) {
1776
2521
  log.warn("[lifecycle] afterUpdate hook failed:", err?.name || "Error");
1777
2522
  }
2523
+ },
2524
+ /**
2525
+ * Deleting an app user deletes what the security log holds about them.
2526
+ *
2527
+ * @param {object} event
2528
+ */
2529
+ async afterDelete(event) {
2530
+ try {
2531
+ const documentId = event?.result?.documentId;
2532
+ if (!documentId) return;
2533
+ await strapi2.plugin("magic-sessionmanager").service("security-log").deleteUserData(documentId);
2534
+ } catch (err) {
2535
+ log.warn("[lifecycle] Security events of a deleted user stay:", err?.name || "Error");
2536
+ }
1778
2537
  }
1779
2538
  });
1780
2539
  log.info("[SUCCESS] Plugin registered successfully");
@@ -1947,7 +2706,13 @@ var require_encryption = __commonJS({
1947
2706
  function getEncryptionKeyCheck() {
1948
2707
  return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
1949
2708
  }
2709
+ function derivePurposeKey(purpose) {
2710
+ return Buffer.from(
2711
+ crypto.hkdfSync("sha256", getEncryptionKey(), "magic-sessionmanager", `msm:${purpose}`, 32)
2712
+ );
2713
+ }
1950
2714
  module.exports = {
2715
+ derivePurposeKey,
1951
2716
  getEncryptionKeyCheck,
1952
2717
  encryptToken,
1953
2718
  decryptToken,
@@ -2209,13 +2974,15 @@ var require_login_alerts = __commonJS({
2209
2974
  "server/src/utils/login-alerts.js"(exports, module) {
2210
2975
  "use strict";
2211
2976
  var { evaluateLoginRisk } = require_risk_data();
2977
+ var { resolveDetectionSettings } = require_detection_settings();
2212
2978
  async function dispatchLoginAlerts({
2213
2979
  settings,
2214
2980
  notificationService,
2215
2981
  user,
2216
2982
  session,
2217
2983
  geoData,
2218
- isNewLocation = false
2984
+ isNewLocation = false,
2985
+ webhooks = null
2219
2986
  }) {
2220
2987
  const attempted = { webhookEvent: null, emails: [] };
2221
2988
  if (!geoData) return attempted;
@@ -2249,8 +3016,22 @@ var require_login_alerts = __commonJS({
2249
3016
  await notificationService.sendNewLocationAlert({ user, session, geoData });
2250
3017
  }
2251
3018
  }
2252
- if (settings.enableWebhooks) {
2253
- const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
3019
+ const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
3020
+ const selected = resolveDetectionSettings(settings).webhookEvents.includes(webhookEvent);
3021
+ if (selected && webhooks) {
3022
+ webhooks.emit(
3023
+ webhookEvent,
3024
+ {
3025
+ userId: user?.documentId || null,
3026
+ ip: session?.ipAddress || null,
3027
+ userAgent: session?.userAgent || null,
3028
+ geo: geoData,
3029
+ details: null
3030
+ },
3031
+ { chat: false }
3032
+ );
3033
+ }
3034
+ if (settings.enableWebhooks && selected) {
2254
3035
  attempted.webhookEvent = webhookEvent;
2255
3036
  const targets = [];
2256
3037
  if (settings.discordWebhookUrl) {
@@ -3477,39 +4258,734 @@ var require_admin_activity_capture = __commonJS({
3477
4258
  `[security-log] Retention removed ${removed.expired} expired events and ${removed.orphans} of deleted admins`
3478
4259
  );
3479
4260
  }
3480
- };
3481
- try {
3482
- if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
3483
- else await job();
3484
- } catch (err) {
3485
- log.warn("[security-log] Retention failed:", err?.name || "Error");
4261
+ };
4262
+ try {
4263
+ if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
4264
+ else await job();
4265
+ } catch (err) {
4266
+ log.warn("[security-log] Retention failed:", err?.name || "Error");
4267
+ }
4268
+ };
4269
+ try {
4270
+ strapi2.cron.add({ [jobName]: { task: retention, options: { rule: "17 3 * * *" } } });
4271
+ cleanups.push(() => strapi2.cron.remove(jobName));
4272
+ } catch (err) {
4273
+ log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
4274
+ }
4275
+ return async () => {
4276
+ for (const cleanup of cleanups.splice(0)) {
4277
+ try {
4278
+ cleanup();
4279
+ } catch {
4280
+ }
4281
+ }
4282
+ try {
4283
+ await strapi2.plugin("magic-sessionmanager")?.service(SERVICE)?.stop();
4284
+ } catch {
4285
+ }
4286
+ };
4287
+ }
4288
+ module.exports = {
4289
+ authErrorNamesKnownAdmins,
4290
+ createCaptureMiddleware,
4291
+ installAdminActivityCapture,
4292
+ observeAuthentication,
4293
+ observeContentManager
4294
+ };
4295
+ }
4296
+ });
4297
+
4298
+ // server/src/utils/login-lockout.js
4299
+ var require_login_lockout = __commonJS({
4300
+ "server/src/utils/login-lockout.js"(exports, module) {
4301
+ "use strict";
4302
+ var { hashedKey } = require_coordination();
4303
+ var { isTrustedAddress } = require_policy_settings();
4304
+ var LOCK_PREFIX = "lock:";
4305
+ var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
4306
+ var MAX_LISTED_LOCKS = 200;
4307
+ function normalizeIdentifier(identifier) {
4308
+ if (typeof identifier !== "string") return null;
4309
+ const value = identifier.trim().toLowerCase();
4310
+ if (!value || value.length > 254) return null;
4311
+ return value;
4312
+ }
4313
+ var ipKey = (ip) => hashedKey("lf", ip);
4314
+ var accountKey = (identifier) => hashedKey("la", identifier);
4315
+ function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
4316
+ const remainingSeconds = async (key) => {
4317
+ if (!key) return 0;
4318
+ const entry = await coordinator.peek(key);
4319
+ const until = Number(entry?.blockedUntil) || 0;
4320
+ const left = until - now();
4321
+ return left > 0 ? Math.ceil(left / 1e3) : 0;
4322
+ };
4323
+ const release = async (reservation) => {
4324
+ if (reservation.ipKey) await coordinator.release(reservation.ipKey);
4325
+ if (reservation.accountKey) await coordinator.release(reservation.accountKey);
4326
+ };
4327
+ return {
4328
+ normalizeIdentifier,
4329
+ /**
4330
+ * Checks the locks and counts the attempt before the password check.
4331
+ *
4332
+ * @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
4333
+ * accountMax: number}} input Client IP, normalised identifier, policy and the
4334
+ * account threshold for this account's role.
4335
+ * @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
4336
+ * lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
4337
+ * @sideeffect Increments the shared counters.
4338
+ */
4339
+ async reserve({ ip, identifier, policy, accountMax }) {
4340
+ const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
4341
+ const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
4342
+ const reservation = {
4343
+ ipKey: countIp ? ipKey(
4344
+ /** @type {string} */
4345
+ ip
4346
+ ) : null,
4347
+ ipHits: 0,
4348
+ accountKey: countAccount ? accountKey(
4349
+ /** @type {string} */
4350
+ identifier
4351
+ ) : null,
4352
+ accountHits: 0
4353
+ };
4354
+ if (!reservation.ipKey && !reservation.accountKey) {
4355
+ return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
4356
+ }
4357
+ const [ipLeft, accountLeft] = await Promise.all([
4358
+ remainingSeconds(reservation.ipKey),
4359
+ remainingSeconds(reservation.accountKey)
4360
+ ]);
4361
+ if (ipLeft > 0 || accountLeft > 0) {
4362
+ return {
4363
+ outcome: "locked",
4364
+ retryAfter: Math.max(ipLeft, accountLeft),
4365
+ lockedKind: accountLeft >= ipLeft && accountLeft > 0 ? "account" : "ip",
4366
+ reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
4367
+ };
4368
+ }
4369
+ if (reservation.ipKey) {
4370
+ reservation.ipHits = (await coordinator.hit(reservation.ipKey, policy.windowMs)).hits;
4371
+ }
4372
+ if (reservation.accountKey) {
4373
+ reservation.accountHits = (await coordinator.hit(reservation.accountKey, policy.windowMs)).hits;
4374
+ }
4375
+ if (reservation.ipKey && reservation.ipHits > policy.ipMax || reservation.accountKey && reservation.accountHits > accountMax) {
4376
+ await release(reservation);
4377
+ return { outcome: "busy", retryAfter: 1, lockedKind: null, reservation };
4378
+ }
4379
+ return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
4380
+ },
4381
+ /**
4382
+ * Records the result of the sign-in.
4383
+ *
4384
+ * @param {Reservation} reservation From `reserve`.
4385
+ * @param {'success'|'failure'|'neutral'} result Outcome of the handler.
4386
+ * @param {{policy: LockoutPolicy, accountMax: number, display?: LockDisplay}} options
4387
+ * Policy, account threshold and what the lock list shows.
4388
+ * @returns {Promise<Array<{kind: 'ip'|'account', id: string, failures: number, until: number}>>}
4389
+ * Locks this request created.
4390
+ * @sideeffect Clears, releases or blocks shared counters; writes lock entries.
4391
+ */
4392
+ async settle(reservation, result, { policy, accountMax, display = {} }) {
4393
+ if (result === "success") {
4394
+ for (const key of [reservation.ipKey, reservation.accountKey]) {
4395
+ if (!key) continue;
4396
+ await coordinator.clear(key);
4397
+ }
4398
+ return [];
4399
+ }
4400
+ if (result !== "failure") {
4401
+ await release(reservation);
4402
+ return [];
4403
+ }
4404
+ const locks = [];
4405
+ const until = now() + policy.durationMs;
4406
+ const candidates = [
4407
+ reservation.ipKey && reservation.ipHits >= policy.ipMax ? {
4408
+ kind: (
4409
+ /** @type {const} */
4410
+ "ip"
4411
+ ),
4412
+ id: reservation.ipKey,
4413
+ failures: reservation.ipHits
4414
+ } : null,
4415
+ reservation.accountKey && reservation.accountHits >= accountMax ? {
4416
+ kind: (
4417
+ /** @type {const} */
4418
+ "account"
4419
+ ),
4420
+ id: reservation.accountKey,
4421
+ failures: reservation.accountHits
4422
+ } : null
4423
+ ];
4424
+ for (const lock of candidates) {
4425
+ if (!lock) continue;
4426
+ await coordinator.block(lock.id, until, { windowStart: until - policy.windowMs });
4427
+ await coordinator.registryPut(
4428
+ `${LOCK_PREFIX}${lock.id}`,
4429
+ {
4430
+ kind: lock.kind,
4431
+ ip: lock.kind === "ip" ? display.ip || null : null,
4432
+ user: lock.kind === "account" ? display.userDocumentId || null : null,
4433
+ failures: lock.failures,
4434
+ lockedAt: now(),
4435
+ until
4436
+ },
4437
+ policy.durationMs
4438
+ );
4439
+ locks.push({ ...lock, until });
4440
+ }
4441
+ return locks;
4442
+ },
4443
+ /**
4444
+ * Active locks, soonest end last.
4445
+ *
4446
+ * @returns {Promise<Array<{id: string, kind: 'ip'|'account', ip: string|null,
4447
+ * user: string|null, failures: number, lockedAt: number, until: number}>>} Locks.
4448
+ */
4449
+ async listLocks() {
4450
+ const entries = await coordinator.registryList(LOCK_PREFIX, MAX_LISTED_LOCKS);
4451
+ const current = now();
4452
+ return entries.map(({ key, value }) => ({
4453
+ id: key.slice(LOCK_PREFIX.length),
4454
+ kind: value?.kind === "account" ? "account" : "ip",
4455
+ ip: typeof value?.ip === "string" ? value.ip : null,
4456
+ user: typeof value?.user === "string" ? value.user : null,
4457
+ failures: Number(value?.failures) || 0,
4458
+ lockedAt: Number(value?.lockedAt) || 0,
4459
+ until: Number(value?.until) || 0
4460
+ })).filter((lock) => KEY_PATTERN.test(lock.id) && lock.until > current).sort((a, b) => b.lockedAt - a.lockedAt);
4461
+ },
4462
+ /**
4463
+ * Lifts a lock: deletes the counter and the list entry.
4464
+ *
4465
+ * @param {string} id Lock id from `listLocks` (`lf:…` or `la:…`).
4466
+ * @returns {Promise<{kind: 'ip'|'account', ip: string|null, user: string|null}|null>}
4467
+ * The lifted lock, or null when the id is invalid or nothing was locked.
4468
+ * @sideeffect Deletes the shared counter and the lock entry.
4469
+ */
4470
+ async unlock(id) {
4471
+ if (typeof id !== "string" || !KEY_PATTERN.test(id)) return null;
4472
+ const entries = await coordinator.registryList(`${LOCK_PREFIX}${id}`, 1);
4473
+ const entry = entries.find((candidate) => candidate.key === `${LOCK_PREFIX}${id}`);
4474
+ const counter = await coordinator.peek(id);
4475
+ const blocked = Number(counter?.blockedUntil) > now();
4476
+ await coordinator.clear(id);
4477
+ await coordinator.registryDelete(`${LOCK_PREFIX}${id}`);
4478
+ if (!entry && !blocked) return null;
4479
+ return {
4480
+ kind: id.startsWith("la:") ? "account" : "ip",
4481
+ ip: typeof entry?.value?.ip === "string" ? entry.value.ip : null,
4482
+ user: typeof entry?.value?.user === "string" ? entry.value.user : null
4483
+ };
3486
4484
  }
3487
4485
  };
4486
+ }
4487
+ module.exports = {
4488
+ LOCK_ID_PATTERN: KEY_PATTERN,
4489
+ accountKey,
4490
+ createLoginLockout,
4491
+ ipKey,
4492
+ normalizeIdentifier
4493
+ };
4494
+ }
4495
+ });
4496
+
4497
+ // server/src/utils/sign-in-policies.js
4498
+ var require_sign_in_policies = __commonJS({
4499
+ "server/src/utils/sign-in-policies.js"(exports, module) {
4500
+ "use strict";
4501
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
4502
+ var { getCoordinator, hashedKey } = require_coordination();
4503
+ var { resolveSecurityLogSettings } = require_security_log_settings();
4504
+ var { hasRoleOverride, inactivityTimeoutFor, sessionLimitFor } = require_policy_settings();
4505
+ var { normalizeIdentifier } = require_login_lockout();
4506
+ var USER_UID = "plugin::users-permissions.user";
4507
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
4508
+ var MAX_SESSIONS_CHECKED = 500;
4509
+ function readSignInIdentifier(ctx) {
4510
+ const body = ctx?.request?.body;
4511
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
4512
+ return normalizeIdentifier(body.identifier) || normalizeIdentifier(body.email);
4513
+ }
4514
+ async function findAccountByIdentifier(strapi2, identifier) {
4515
+ if (!identifier) return null;
4516
+ const rows = await strapi2.db.query(USER_UID).findMany({
4517
+ where: { $or: [{ email: identifier }, { username: identifier }] },
4518
+ select: ["documentId", "email", "username"],
4519
+ populate: { role: { select: ["documentId"] } },
4520
+ limit: 2
4521
+ });
4522
+ const list = Array.isArray(rows) ? rows : [];
4523
+ const account = list.find((row) => String(row.email || "").toLowerCase() === identifier) || list[0];
4524
+ if (!account?.documentId) return null;
4525
+ return {
4526
+ documentId: account.documentId,
4527
+ email: typeof account.email === "string" ? account.email : null,
4528
+ username: typeof account.username === "string" ? account.username : null,
4529
+ role: account.role?.documentId || null
4530
+ };
4531
+ }
4532
+ async function findUserRole(strapi2, userDocumentId) {
4533
+ if (!userDocumentId) return null;
4534
+ const user = await strapi2.db.query(USER_UID).findOne({
4535
+ where: { documentId: userDocumentId },
4536
+ select: ["id"],
4537
+ populate: { role: { select: ["documentId"] } }
4538
+ });
4539
+ return user?.role?.documentId || null;
4540
+ }
4541
+ function displayIp(settings, ip) {
4542
+ const options = resolveSecurityLogSettings(settings);
4543
+ if (!options.storeIp) return null;
4544
+ const normalized = normalizeIp(ip || "");
4545
+ if (!normalized) return null;
4546
+ return options.anonymizeIp ? anonymizeIp(normalized) : normalized;
4547
+ }
4548
+ function recordUserEvent(strapi2, input) {
3488
4549
  try {
3489
- strapi2.cron.add({ [jobName]: { task: retention, options: { rule: "17 3 * * *" } } });
3490
- cleanups.push(() => strapi2.cron.remove(jobName));
3491
- } catch (err) {
3492
- log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
4550
+ strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(input);
4551
+ } catch {
3493
4552
  }
3494
- return async () => {
3495
- for (const cleanup of cleanups.splice(0)) {
3496
- try {
3497
- cleanup();
3498
- } catch {
4553
+ try {
4554
+ return strapi2.plugin("magic-sessionmanager").service("security-log").record(input) === true;
4555
+ } catch {
4556
+ return false;
4557
+ }
4558
+ }
4559
+ function isOpenSession(session, idleMs, maxAgeDays, now) {
4560
+ if (session.isActive !== true) return false;
4561
+ const login = session.loginTime ? new Date(session.loginTime).getTime() : NaN;
4562
+ const last = session.lastActive ? new Date(session.lastActive).getTime() : login;
4563
+ if (Number.isFinite(last) && now - last > idleMs) return false;
4564
+ if (Number.isFinite(login) && now - login > maxAgeDays * 24 * 60 * 60 * 1e3) return false;
4565
+ return true;
4566
+ }
4567
+ async function createSessionWithinLimit({
4568
+ strapi: strapi2,
4569
+ settings,
4570
+ userDocumentId,
4571
+ create,
4572
+ sessionService
4573
+ }) {
4574
+ const possible = sessionLimitFor(settings, null).limit > 0 || hasRoleOverride(settings, "maxSessionsPerUser");
4575
+ if (!possible) return { session: await create(), refused: false, ended: 0, limit: 0 };
4576
+ const role = await findUserRole(strapi2, userDocumentId);
4577
+ const { limit, policy } = sessionLimitFor(settings, role);
4578
+ if (limit <= 0) return { session: await create(), refused: false, ended: 0, limit: 0 };
4579
+ return getCoordinator(strapi2).withLock(hashedKey("session-limit", userDocumentId), async () => {
4580
+ const session = await create();
4581
+ if (!session?.documentId) return { session, refused: false, ended: 0, limit };
4582
+ const now = Date.now();
4583
+ const idleMs = inactivityTimeoutFor(settings, role);
4584
+ const maxAgeDays = Number(settings.maxSessionAgeDays) || 30;
4585
+ const rows = await strapi2.documents(SESSION_UID).findMany({
4586
+ filters: { user: { documentId: userDocumentId }, isActive: true },
4587
+ fields: ["documentId", "isActive", "loginTime", "lastActive"],
4588
+ sort: [{ loginTime: "asc" }, { id: "asc" }],
4589
+ limit: MAX_SESSIONS_CHECKED
4590
+ });
4591
+ const open = (Array.isArray(rows) ? rows : []).filter(
4592
+ (row) => isOpenSession(row, idleMs, maxAgeDays, now)
4593
+ );
4594
+ if (open.length <= limit) return { session, refused: false, ended: 0, limit };
4595
+ if (policy === "refuse") {
4596
+ await sessionService.terminateSession({ sessionId: session.documentId, reason: "manual" });
4597
+ return { session, refused: true, ended: 0, limit };
4598
+ }
4599
+ const others = open.filter((row) => row.documentId !== session.documentId);
4600
+ const excess = open.length - limit;
4601
+ let ended = 0;
4602
+ for (const row of others.slice(0, excess)) {
4603
+ const result = await sessionService.terminateSession({
4604
+ sessionId: row.documentId,
4605
+ reason: "manual"
4606
+ });
4607
+ ended += Number(result?.terminatedCount) || 0;
4608
+ }
4609
+ return { session, refused: false, ended, limit };
4610
+ });
4611
+ }
4612
+ function createRefusalDedup({ windowMs = 60 * 1e3, maxKeys = 5e3 } = {}) {
4613
+ const seen = /* @__PURE__ */ new Map();
4614
+ return (key, now = Date.now()) => {
4615
+ const last = seen.get(key);
4616
+ if (last !== void 0 && now - last < windowMs) return false;
4617
+ seen.delete(key);
4618
+ seen.set(key, now);
4619
+ if (seen.size > maxKeys) seen.delete(
4620
+ /** @type {string} */
4621
+ seen.keys().next().value
4622
+ );
4623
+ return true;
4624
+ };
4625
+ }
4626
+ function createAddressCap({ max = 30, windowMs = 60 * 60 * 1e3, maxKeys = 5e3 } = {}) {
4627
+ const counts = /* @__PURE__ */ new Map();
4628
+ return (ip, now = Date.now()) => {
4629
+ const key = anonymizeIp(normalizeIp(ip || "")) || "-";
4630
+ const windowStart = Math.floor(now / windowMs) * windowMs;
4631
+ const entry = counts.get(key);
4632
+ if (!entry || entry.windowStart !== windowStart) {
4633
+ counts.delete(key);
4634
+ counts.set(key, { count: 1, windowStart });
4635
+ if (counts.size > maxKeys) counts.delete(
4636
+ /** @type {string} */
4637
+ counts.keys().next().value
4638
+ );
4639
+ return true;
4640
+ }
4641
+ entry.count += 1;
4642
+ return entry.count <= max;
4643
+ };
4644
+ }
4645
+ function refusalReasonOfGeoDecision(reason) {
4646
+ const value = String(reason || "");
4647
+ if (value.startsWith("country_")) return "country";
4648
+ if (value.startsWith("geo_lookup_unavailable")) return "location-unavailable";
4649
+ return "risk";
4650
+ }
4651
+ module.exports = {
4652
+ createAddressCap,
4653
+ createRefusalDedup,
4654
+ refusalReasonOfGeoDecision,
4655
+ createSessionWithinLimit,
4656
+ displayIp,
4657
+ findAccountByIdentifier,
4658
+ findUserRole,
4659
+ isOpenSession,
4660
+ readSignInIdentifier,
4661
+ recordUserEvent
4662
+ };
4663
+ }
4664
+ });
4665
+
4666
+ // server/src/utils/upgrade-defaults.js
4667
+ var require_upgrade_defaults = __commonJS({
4668
+ "server/src/utils/upgrade-defaults.js"(exports, module) {
4669
+ "use strict";
4670
+ var { withPluginStoreKey } = require_plugin_store();
4671
+ var { notifySettingsChanged } = require_settings_loader();
4672
+ var { LEGACY_WEBHOOK_EVENTS } = require_detection_settings();
4673
+ var PROFILE_KEY = "defaultsProfile";
4674
+ var UPGRADE_STEPS = Object.freeze([
4675
+ Object.freeze({
4676
+ version: 1,
4677
+ release: "4.17.0",
4678
+ // Before 4.17 a password change kept the user's other sessions.
4679
+ legacy: Object.freeze({ endOtherSessionsOnPasswordChange: false })
4680
+ }),
4681
+ Object.freeze({
4682
+ version: 2,
4683
+ release: "sign-in signals and signed webhook",
4684
+ // Before, Discord and Slack received every sign-in (success, new
4685
+ // country, suspicious). New installations leave out every sign-in.
4686
+ legacy: Object.freeze({ webhookEvents: LEGACY_WEBHOOK_EVENTS })
4687
+ })
4688
+ ]);
4689
+ async function applyUpgradeDefaults(strapi2, log, steps = UPGRADE_STEPS) {
4690
+ const latest = steps.length ? steps[steps.length - 1].version : 0;
4691
+ const outcome = await withPluginStoreKey(strapi2, "settings", async (store) => {
4692
+ const profile = Number(await store.get({ key: PROFILE_KEY })) || 0;
4693
+ if (profile >= latest) return { existing: profile > 0, applied: [], changed: false };
4694
+ const stored = await store.get({ key: "settings" });
4695
+ let existing = profile > 0;
4696
+ if (!existing) {
4697
+ const permissionsVersion = await store.get({ key: "contentApiPermissionsVersion" });
4698
+ const legacyFlag = await store.get({ key: "contentApiPermissionsInitialized" });
4699
+ existing = stored !== null && stored !== void 0 || permissionsVersion !== null && permissionsVersion !== void 0 || legacyFlag === true;
4700
+ }
4701
+ const applied = [];
4702
+ if (existing) {
4703
+ const settings = stored && typeof stored === "object" ? { ...stored } : {};
4704
+ for (const step of steps) {
4705
+ if (step.version <= profile) continue;
4706
+ for (const [key, value] of Object.entries(step.legacy)) {
4707
+ if (settings[key] !== void 0) continue;
4708
+ settings[key] = Array.isArray(value) ? [...value] : value;
4709
+ applied.push(key);
4710
+ }
3499
4711
  }
4712
+ if (applied.length) await store.set({ key: "settings", value: settings });
3500
4713
  }
4714
+ await store.set({ key: PROFILE_KEY, value: latest });
4715
+ return { existing, applied, changed: applied.length > 0 };
4716
+ });
4717
+ if (outcome.changed) {
4718
+ await notifySettingsChanged(strapi2);
4719
+ log.info(
4720
+ `[UPGRADE] Kept the previous behaviour of ${outcome.applied.length} setting(s) on this existing installation`
4721
+ );
4722
+ }
4723
+ return { existing: outcome.existing, applied: outcome.applied };
4724
+ }
4725
+ module.exports = { PROFILE_KEY, UPGRADE_STEPS, applyUpgradeDefaults };
4726
+ }
4727
+ });
4728
+
4729
+ // server/src/utils/not-me-link.js
4730
+ var require_not_me_link = __commonJS({
4731
+ "server/src/utils/not-me-link.js"(exports, module) {
4732
+ "use strict";
4733
+ var crypto = __require("node:crypto");
4734
+ var { derivePurposeKey } = require_encryption();
4735
+ var LIFETIME_MS = 72 * 60 * 60 * 1e3;
4736
+ var NONCE_PREFIX = "notme:";
4737
+ var DOCUMENT_ID = /^[A-Za-z0-9]{1,64}$/;
4738
+ var TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,400}\.[A-Za-z0-9_-]{43}$/;
4739
+ var signingKey = () => derivePurposeKey("not-me-link");
4740
+ var sign = (payload) => crypto.createHmac("sha256", signingKey()).update(payload).digest("base64url");
4741
+ async function issueNotMeToken(coordinator, { sessionId, userId, now = Date.now() }) {
4742
+ if (!DOCUMENT_ID.test(String(sessionId)) || !DOCUMENT_ID.test(String(userId))) return null;
4743
+ const nonce = crypto.randomBytes(18).toString("hex");
4744
+ const payload = Buffer.from(
4745
+ JSON.stringify({ s: sessionId, u: userId, e: now + LIFETIME_MS, n: nonce })
4746
+ ).toString("base64url");
4747
+ await coordinator.registryPut(
4748
+ `${NONCE_PREFIX}${nonce}`,
4749
+ { s: sessionId, u: userId },
4750
+ LIFETIME_MS
4751
+ );
4752
+ return `${payload}.${sign(payload)}`;
4753
+ }
4754
+ function readNotMeToken(token, { now = Date.now() } = {}) {
4755
+ if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) return null;
4756
+ const [payload, signature] = token.split(".");
4757
+ const expected = Buffer.from(sign(payload));
4758
+ const given = Buffer.from(signature);
4759
+ if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null;
4760
+ let claims;
4761
+ try {
4762
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
4763
+ } catch {
4764
+ return null;
4765
+ }
4766
+ if (!claims || !DOCUMENT_ID.test(String(claims.s)) || !DOCUMENT_ID.test(String(claims.u)) || !/^[a-f0-9]{36}$/.test(String(claims.n)) || !Number.isFinite(claims.e) || claims.e <= now) {
4767
+ return null;
4768
+ }
4769
+ return { sessionId: claims.s, userId: claims.u, nonce: claims.n, expiresAt: claims.e };
4770
+ }
4771
+ async function consumeNotMeToken(coordinator, token) {
4772
+ const claims = readNotMeToken(token);
4773
+ if (!claims) return null;
4774
+ const stored = await coordinator.registryTake(`${NONCE_PREFIX}${claims.nonce}`);
4775
+ if (!stored || stored.s !== claims.sessionId || stored.u !== claims.userId) return null;
4776
+ return { sessionId: claims.sessionId, userId: claims.userId };
4777
+ }
4778
+ module.exports = { LIFETIME_MS, consumeNotMeToken, issueNotMeToken, readNotMeToken };
4779
+ }
4780
+ });
4781
+
4782
+ // server/src/utils/sign-in-signals.js
4783
+ var require_sign_in_signals = __commonJS({
4784
+ "server/src/utils/sign-in-signals.js"(exports, module) {
4785
+ "use strict";
4786
+ var crypto = __require("node:crypto");
4787
+ var { derivePurposeKey } = require_encryption();
4788
+ var { parseUserAgent } = require_user_agent_parser();
4789
+ var { getCoordinator } = require_coordination();
4790
+ var { normalizeApiPrefix } = require_auth_routes();
4791
+ var { resolveDetectionSettings } = require_detection_settings();
4792
+ var { issueNotMeToken } = require_not_me_link();
4793
+ var { SECURITY_EVENTS } = require_security_log_model();
4794
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
4795
+ var HISTORY = 50;
4796
+ var EARTH_RADIUS_KM = 6371.0088;
4797
+ function deviceFamilies(userAgent) {
4798
+ const parsed = parseUserAgent(typeof userAgent === "string" ? userAgent.slice(0, 500) : "");
4799
+ return {
4800
+ browser: String(parsed.browserName || "unknown"),
4801
+ os: String(parsed.osName || "unknown"),
4802
+ deviceType: String(parsed.deviceType || "unknown")
4803
+ };
4804
+ }
4805
+ function family(value) {
4806
+ return String(value || "unknown").replace(/\s+[\d.]+$/, "").trim();
4807
+ }
4808
+ function deviceKeyOf(userAgent, deviceId) {
4809
+ const { browser, os, deviceType } = deviceFamilies(userAgent);
4810
+ const id = typeof deviceId === "string" && deviceId.length <= 128 ? deviceId : "";
4811
+ return crypto.createHmac("sha256", derivePurposeKey("device")).update(`${browser}|${os}|${deviceType}|${id}`).digest("hex").slice(0, 32);
4812
+ }
4813
+ function requestDeviceId(ctx) {
4814
+ const value = ctx?.request?.body?.deviceId;
4815
+ return typeof value === "string" && value && value.length <= 128 ? value : null;
4816
+ }
4817
+ function distanceKm(a, b) {
4818
+ const rad = (deg) => deg * Math.PI / 180;
4819
+ const dLat = rad(b.lat - a.lat);
4820
+ const dLon = rad(b.lon - a.lon);
4821
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
4822
+ return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)));
4823
+ }
4824
+ function pointOf(geo) {
4825
+ const lat = Number(geo?.latitude);
4826
+ const lon = Number(geo?.longitude);
4827
+ if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
4828
+ return null;
4829
+ }
4830
+ if (geo?.latitude === null || geo?.longitude === null) return null;
4831
+ return { lat: Math.round(lat * 10) / 10, lon: Math.round(lon * 10) / 10 };
4832
+ }
4833
+ function evaluateTravel(previous, current, { speedKmh, minDistanceKm }) {
4834
+ if (!previous?.point || !current?.point) return null;
4835
+ const km = distanceKm(previous.point, current.point);
4836
+ const hours = Math.max(current.at - previous.at, 60 * 1e3) / (60 * 60 * 1e3);
4837
+ const speed = km / hours;
4838
+ return {
4839
+ flagged: km >= minDistanceKm && speed > speedKmh,
4840
+ distanceKm: Math.round(km),
4841
+ speedKmh: Math.round(speed)
4842
+ };
4843
+ }
4844
+ async function previousSessions(strapi2, userDocumentId, exceptSessionId) {
4845
+ const rows = await strapi2.documents(SESSION_UID).findMany({
4846
+ filters: { user: { documentId: userDocumentId }, documentId: { $ne: exceptSessionId } },
4847
+ fields: [
4848
+ "documentId",
4849
+ "loginTime",
4850
+ "deviceKey",
4851
+ "browserName",
4852
+ "osName",
4853
+ "deviceType",
4854
+ "geoLocation"
4855
+ ],
4856
+ sort: [{ loginTime: "desc" }, { id: "desc" }],
4857
+ limit: HISTORY
4858
+ });
4859
+ return Array.isArray(rows) ? rows : [];
4860
+ }
4861
+ function isNewDevice(previous, { deviceKey, userAgent }) {
4862
+ if (previous.length === 0) return false;
4863
+ if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
4864
+ const families = deviceFamilies(userAgent);
4865
+ return !previous.some(
4866
+ (row) => !row.deviceKey && family(row.browserName) === families.browser && family(row.osName) === families.os
4867
+ );
4868
+ }
4869
+ function storedLocation(row) {
4870
+ let geo = row?.geoLocation;
4871
+ if (typeof geo === "string") {
3501
4872
  try {
3502
- await strapi2.plugin("magic-sessionmanager")?.service(SERVICE)?.stop();
4873
+ geo = JSON.parse(geo);
3503
4874
  } catch {
4875
+ geo = null;
3504
4876
  }
4877
+ }
4878
+ return {
4879
+ point: pointOf(geo),
4880
+ country: typeof geo?.country_code === "string" ? geo.country_code : null
4881
+ };
4882
+ }
4883
+ async function notMeUrl(strapi2, sessionId, userId) {
4884
+ const base = String(strapi2.config.get("server.absoluteUrl") || "").replace(/\/+$/, "");
4885
+ if (!/^https?:\/\/[^/]+/.test(base)) return null;
4886
+ const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
4887
+ if (!token) return null;
4888
+ const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
4889
+ return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
4890
+ }
4891
+ async function runSignInSignals({
4892
+ strapi: strapi2,
4893
+ settings,
4894
+ user,
4895
+ userDocumentId,
4896
+ session,
4897
+ geoData,
4898
+ deviceKey,
4899
+ userAgent,
4900
+ ip,
4901
+ record,
4902
+ now = Date.now()
4903
+ }) {
4904
+ const outcome = { newDevice: false, travel: null, reauthenticate: false };
4905
+ const detection = resolveDetectionSettings(settings);
4906
+ const plugin = strapi2.plugin("magic-sessionmanager");
4907
+ const emails = settings.enableEmailAlerts === true;
4908
+ const hasWebhookTarget = detection.genericWebhookEnabled && !!detection.genericWebhookUrl || settings.enableWebhooks === true && !!(settings.discordWebhookUrl || settings.slackWebhookUrl);
4909
+ const wantNewDevice = emails && detection.alertOnNewDevice || hasWebhookTarget && detection.webhookEvents.includes("login.new_device");
4910
+ const wantTravel = detection.impossibleTravelEnabled;
4911
+ if (!wantNewDevice && !wantTravel || !session?.documentId) return outcome;
4912
+ const previous = await previousSessions(strapi2, userDocumentId, session.documentId);
4913
+ const families = deviceFamilies(userAgent);
4914
+ let link;
4915
+ const linkOnce = async () => {
4916
+ if (link === void 0) link = await notMeUrl(strapi2, session.documentId, userDocumentId);
4917
+ return link;
3505
4918
  };
4919
+ const notifications = plugin.service("notifications");
4920
+ const facts = { user, session, geoData, device: { browser: families.browser, os: families.os } };
4921
+ if (wantNewDevice && isNewDevice(previous, { deviceKey, userAgent })) {
4922
+ outcome.newDevice = true;
4923
+ record({
4924
+ event: SECURITY_EVENTS.USER_NEW_DEVICE,
4925
+ actorType: "user",
4926
+ actorId: userDocumentId,
4927
+ targetType: "user",
4928
+ targetId: userDocumentId,
4929
+ ip,
4930
+ userAgent,
4931
+ meta: { browser: families.browser, os: families.os, deviceType: families.deviceType }
4932
+ });
4933
+ if (emails && detection.alertOnNewDevice) {
4934
+ const url = await linkOnce();
4935
+ notifications.sendSignInSignalEmail("newDevice", { ...facts, link: url }).catch(() => {
4936
+ });
4937
+ }
4938
+ }
4939
+ if (wantTravel) {
4940
+ const before = previous.find((row) => storedLocation(row).point);
4941
+ const result = before ? evaluateTravel(
4942
+ { point: storedLocation(before).point, at: new Date(before.loginTime).getTime() },
4943
+ { point: pointOf(geoData), at: now },
4944
+ {
4945
+ speedKmh: detection.impossibleTravelSpeedKmh,
4946
+ minDistanceKm: detection.impossibleTravelMinDistanceKm
4947
+ }
4948
+ ) : null;
4949
+ if (result?.flagged) {
4950
+ outcome.travel = result;
4951
+ record({
4952
+ event: SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
4953
+ actorType: "user",
4954
+ actorId: userDocumentId,
4955
+ targetType: "user",
4956
+ targetId: userDocumentId,
4957
+ ip,
4958
+ userAgent,
4959
+ meta: {
4960
+ distanceKm: result.distanceKm,
4961
+ speedKmh: result.speedKmh,
4962
+ from: storedLocation(before).country,
4963
+ to: typeof geoData?.country_code === "string" ? geoData.country_code : null,
4964
+ action: detection.impossibleTravelAction
4965
+ }
4966
+ });
4967
+ if (emails && detection.alertOnImpossibleTravel) {
4968
+ const url = await linkOnce();
4969
+ notifications.sendSignInSignalEmail("impossibleTravel", { ...facts, travel: result, link: url }).catch(() => {
4970
+ });
4971
+ }
4972
+ outcome.reauthenticate = detection.impossibleTravelAction === "reauthenticate";
4973
+ }
4974
+ }
4975
+ return outcome;
3506
4976
  }
3507
4977
  module.exports = {
3508
- authErrorNamesKnownAdmins,
3509
- createCaptureMiddleware,
3510
- installAdminActivityCapture,
3511
- observeAuthentication,
3512
- observeContentManager
4978
+ notMeUrl,
4979
+ runSignInSignals,
4980
+ deviceFamilies,
4981
+ deviceKeyOf,
4982
+ distanceKm,
4983
+ evaluateTravel,
4984
+ isNewDevice,
4985
+ pointOf,
4986
+ previousSessions,
4987
+ requestDeviceId,
4988
+ storedLocation
3513
4989
  };
3514
4990
  }
3515
4991
  });
@@ -7608,12 +9084,7 @@ var require_bootstrap = __commonJS({
7608
9084
  var { REVOCATION_UID } = require_session_revocation();
7609
9085
  var { getNativeSessionManager } = require_native_session_manager();
7610
9086
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
7611
- var {
7612
- getCoordinator,
7613
- hashedKey,
7614
- initCoordination,
7615
- LockTimeoutError
7616
- } = require_coordination();
9087
+ var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
7617
9088
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
7618
9089
  var {
7619
9090
  normalizeApiPrefix,
@@ -7643,8 +9114,28 @@ var require_bootstrap = __commonJS({
7643
9114
  migrateSecurityLog,
7644
9115
  warnUnboundedProxyTrust
7645
9116
  } = require_security_log_hardening();
9117
+ var { createLoginLockout } = require_login_lockout();
9118
+ var {
9119
+ accountThresholdFor,
9120
+ inactivityTimeoutFor,
9121
+ hasRoleOverride,
9122
+ resolveLockoutPolicy
9123
+ } = require_policy_settings();
9124
+ var {
9125
+ createAddressCap,
9126
+ createRefusalDedup,
9127
+ createSessionWithinLimit,
9128
+ displayIp,
9129
+ findAccountByIdentifier,
9130
+ readSignInIdentifier,
9131
+ recordUserEvent,
9132
+ refusalReasonOfGeoDecision
9133
+ } = require_sign_in_policies();
9134
+ var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
9135
+ var { applyUpgradeDefaults } = require_upgrade_defaults();
9136
+ var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
9137
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
7646
9138
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7647
- var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
7648
9139
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
7649
9140
  var JOB_LEASES = Object.freeze({
7650
9141
  idleCleanup: "job:idle-cleanup",
@@ -7686,6 +9177,11 @@ var require_bootstrap = __commonJS({
7686
9177
  try {
7687
9178
  const coordinator = await initCoordination(strapi2, log);
7688
9179
  await checkEncryptionKeyConsistency(strapi2, log);
9180
+ try {
9181
+ await applyUpgradeDefaults(strapi2, log);
9182
+ } catch (err) {
9183
+ log.warn("[UPGRADE] Previous defaults could not be kept:", err?.name || "Error");
9184
+ }
7689
9185
  await ensureSessionLookupIndexes(strapi2, log);
7690
9186
  await registerSessionAwareAuthStrategy(strapi2);
7691
9187
  await removeLegacyLicenseRows(strapi2, log);
@@ -7847,6 +9343,27 @@ var require_bootstrap = __commonJS({
7847
9343
  }
7848
9344
  }
7849
9345
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
9346
+ const shouldRecordRefusal = createRefusalDedup();
9347
+ const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
9348
+ const recordRefusal = async (ctx, settings, ip, decisionReason) => {
9349
+ if (!resolveLockoutPolicy(settings).record) return;
9350
+ const reason = refusalReasonOfGeoDecision(decisionReason);
9351
+ const identifier = readSignInIdentifier(ctx);
9352
+ if (!shouldRecordRefusal(`${reason}|${ip}|${identifier || ""}`)) return;
9353
+ const account = await findAccountByIdentifier(strapi2, identifier).catch(() => null);
9354
+ if (!account && !shouldRecordUnknownAccount(`refused|${anonymizeIp(normalizeIp(ip || "")) || "none"}`)) {
9355
+ return;
9356
+ }
9357
+ recordUserEvent(strapi2, {
9358
+ event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
9359
+ actorType: "user",
9360
+ targetType: "user",
9361
+ targetId: account?.documentId || null,
9362
+ ip,
9363
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
9364
+ meta: { reason }
9365
+ });
9366
+ };
7850
9367
  strapi2.server.use(async (ctx, next) => {
7851
9368
  if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
7852
9369
  return next();
@@ -7866,6 +9383,7 @@ var require_bootstrap = __commonJS({
7866
9383
  const decision = evaluateGeoFirewall(settings, geoData);
7867
9384
  if (decision.blocked) {
7868
9385
  log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
9386
+ await recordRefusal(ctx, settings, ip, decision.reason);
7869
9387
  ctx.status = 403;
7870
9388
  ctx.body = {
7871
9389
  error: {
@@ -7884,6 +9402,7 @@ var require_bootstrap = __commonJS({
7884
9402
  const failureDecision = evaluateGeoFirewall(settings, { _status: "error" });
7885
9403
  if (failureDecision.blocked) {
7886
9404
  log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
9405
+ await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
7887
9406
  ctx.status = 403;
7888
9407
  ctx.body = {
7889
9408
  error: {
@@ -8083,53 +9602,95 @@ var require_bootstrap = __commonJS({
8083
9602
  }
8084
9603
  }
8085
9604
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
8086
- const WINDOW_MS = FAILED_LOGIN_WINDOW_MS;
8087
- const coordinator = getCoordinator(strapi2);
8088
- const keyFor = (ip) => hashedKey("lf", ip);
9605
+ const lockout = createLoginLockout(getCoordinator(strapi2));
9606
+ const shouldRecordRefusal = createRefusalDedup();
9607
+ const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
9608
+ const underAddressCap = createAddressCap();
9609
+ const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
8089
9610
  strapi2.server.use(async (ctx, next) => {
8090
9611
  if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
8091
9612
  const settings = await getRequestSettings(strapi2, ctx);
8092
- const maxFailed = Number(settings.maxFailedLogins) || 0;
8093
- if (maxFailed <= 0) return next();
8094
- const ip = getClientIp(ctx);
8095
- if (!ip || ip === "unknown") return next();
8096
- const key = keyFor(ip);
8097
- const now = Date.now();
8098
- let existing = null;
9613
+ const policy = resolveLockoutPolicy(settings);
9614
+ const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
9615
+ if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
9616
+ const rawIp = getClientIp(ctx);
9617
+ const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
9618
+ const identifier = readSignInIdentifier(ctx);
9619
+ const userAgent = ctx.request?.headers?.["user-agent"] || null;
9620
+ let account;
9621
+ const loadAccount = async () => {
9622
+ if (account !== void 0) return account;
9623
+ let found = null;
9624
+ if (identifier) {
9625
+ try {
9626
+ found = await findAccountByIdentifier(strapi2, identifier);
9627
+ } catch (err) {
9628
+ log.debug("[LOCKOUT] Account lookup failed:", err?.name || "Error");
9629
+ }
9630
+ }
9631
+ account = found;
9632
+ return account;
9633
+ };
9634
+ if (policy.accountMaxByRole) await loadAccount();
9635
+ const accountMax = accountThresholdFor(settings, account?.role || null);
9636
+ const event = (name, meta) => {
9637
+ const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
9638
+ if (signInFamily && !policy.record) return false;
9639
+ if (signInFamily && !underAddressCap(ip)) return false;
9640
+ return recordUserEvent(strapi2, {
9641
+ event: name,
9642
+ actorType: "user",
9643
+ actorId: null,
9644
+ targetType: "user",
9645
+ targetId: account?.documentId || null,
9646
+ ip,
9647
+ userAgent,
9648
+ meta
9649
+ });
9650
+ };
9651
+ const refusedOnce = (reason, meta) => {
9652
+ if (!policy.record) return;
9653
+ if (!account) {
9654
+ if (!shouldRecordUnknownAccount(`refused|${unknownAccountKey(ip)}`)) return;
9655
+ event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, unknownAccount: true, ...meta });
9656
+ return;
9657
+ }
9658
+ if (!shouldRecordRefusal(`${reason}|${ip || ""}|${identifier || ""}`)) return;
9659
+ event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, ...meta });
9660
+ };
9661
+ let decision;
8099
9662
  try {
8100
- existing = await coordinator.peek(key);
9663
+ decision = await lockout.reserve({ ip, identifier, policy, accountMax });
8101
9664
  } catch (err) {
8102
- log.debug("[LOCKOUT] Counter read failed:", err?.name || "Error");
9665
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
9666
+ decision = {
9667
+ outcome: "allow",
9668
+ retryAfter: 0,
9669
+ lockedKind: null,
9670
+ reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
9671
+ };
8103
9672
  }
8104
- const rejectLocked = (retrySec) => {
8105
- ctx.set("Retry-After", String(retrySec));
8106
- log.warn(`[LOCKOUT] Rejected login from locked client (${retrySec}s remaining)`);
9673
+ if (decision.outcome === "locked") {
9674
+ ctx.set("Retry-After", String(decision.retryAfter));
9675
+ log.warn(
9676
+ `[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
9677
+ );
9678
+ if (policy.record) await loadAccount();
9679
+ refusedOnce("lockout", { lock: decision.lockedKind });
8107
9680
  ctx.status = 429;
8108
9681
  ctx.body = {
8109
9682
  error: {
8110
9683
  status: 429,
8111
9684
  name: "TooManyRequestsError",
8112
9685
  message: "Too many failed login attempts. Please try again later.",
8113
- details: { retryAfter: retrySec }
9686
+ details: { retryAfter: decision.retryAfter }
8114
9687
  }
8115
9688
  };
8116
- };
8117
- if (existing && existing.blockedUntil > now) {
8118
- rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
8119
9689
  return;
8120
9690
  }
8121
- let reserved = null;
8122
- try {
8123
- reserved = await coordinator.hit(key, WINDOW_MS);
8124
- } catch (err) {
8125
- log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
8126
- }
8127
- if (reserved && reserved.hits > maxFailed) {
8128
- try {
8129
- await coordinator.release(key);
8130
- } catch (err) {
8131
- log.debug("[LOCKOUT] Counter release failed:", err?.name || "Error");
8132
- }
9691
+ if (decision.outcome === "busy") {
9692
+ if (policy.record) await loadAccount();
9693
+ refusedOnce("too-many-attempts", {});
8133
9694
  ctx.set("Retry-After", "1");
8134
9695
  ctx.status = 429;
8135
9696
  ctx.body = {
@@ -8149,18 +9710,43 @@ var require_bootstrap = __commonJS({
8149
9710
  thrown = err;
8150
9711
  }
8151
9712
  const status = thrown ? statusOfThrownError(thrown) : ctx.status;
9713
+ const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
9714
+ if (result === "failure") {
9715
+ if (policy.record || decision.reservation.accountKey) await loadAccount();
9716
+ if (account) {
9717
+ event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
9718
+ } else if (shouldRecordUnknownAccount(`failed|${unknownAccountKey(ip)}`)) {
9719
+ event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status, unknownAccount: true });
9720
+ }
9721
+ }
8152
9722
  try {
8153
- if (!thrown && status === 200 && ctx.body && ctx.body.jwt) {
8154
- await coordinator.clear(key);
8155
- } else if (status >= 400 && status < 500 && status !== 429) {
8156
- if (reserved && reserved.hits >= maxFailed) {
8157
- await coordinator.block(key, Date.now() + WINDOW_MS);
8158
- log.warn(
8159
- `[LOCKOUT] Client locked for 15min after ${reserved.hits} failed login attempts`
8160
- );
9723
+ const locks = await lockout.settle(decision.reservation, result, {
9724
+ policy,
9725
+ accountMax,
9726
+ display: {
9727
+ ip: displayIp(settings, ip),
9728
+ userDocumentId: account?.documentId || null
9729
+ }
9730
+ });
9731
+ for (const lock of locks) {
9732
+ const minutes = Math.round(policy.durationMs / 6e4);
9733
+ log.warn(
9734
+ `[LOCKOUT] ${lock.kind === "ip" ? "Client" : "Account"} locked for ${minutes}min after ${lock.failures} failed sign-ins`
9735
+ );
9736
+ event(SECURITY_EVENTS.USER_LOCKOUT, {
9737
+ kind: lock.kind,
9738
+ failures: lock.failures,
9739
+ minutes
9740
+ });
9741
+ if (lock.kind === "account" && policy.notifyUser && account?.email) {
9742
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
9743
+ notifications.sendAccountLockedEmail({
9744
+ user: account,
9745
+ minutes,
9746
+ until: lock.until
9747
+ }).catch(() => {
9748
+ });
8161
9749
  }
8162
- } else if (reserved) {
8163
- await coordinator.release(key);
8164
9750
  }
8165
9751
  } catch (err) {
8166
9752
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
@@ -8187,6 +9773,54 @@ var require_bootstrap = __commonJS({
8187
9773
  };
8188
9774
  return byName[err?.name] || 500;
8189
9775
  }
9776
+ function optionalService(strapi2, name) {
9777
+ try {
9778
+ return strapi2.plugin("magic-sessionmanager").service(name) || null;
9779
+ } catch {
9780
+ return null;
9781
+ }
9782
+ }
9783
+ function refuseSessionLimit({ ctx, strapi: strapi2, limit }) {
9784
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
9785
+ ctx.status = 403;
9786
+ ctx.body = {
9787
+ data: null,
9788
+ error: {
9789
+ status: 403,
9790
+ name: "ForbiddenError",
9791
+ message: "Too many active sessions. Sign out on another device and try again.",
9792
+ details: { code: "SESSION_LIMIT_REACHED", limit }
9793
+ }
9794
+ };
9795
+ }
9796
+ async function endOtherSessionsAfterPasswordChange({
9797
+ strapi: strapi2,
9798
+ ctx,
9799
+ log,
9800
+ sessionService,
9801
+ userDocumentId,
9802
+ currentSessionId
9803
+ }) {
9804
+ const settings = await getPluginSettings(strapi2);
9805
+ if (settings.endOtherSessionsOnPasswordChange !== true) return;
9806
+ if (!userDocumentId) throw new Error("password change owner could not be resolved");
9807
+ const { terminatedCount } = await sessionService.terminateSession({
9808
+ userId: userDocumentId,
9809
+ exceptSessionId: currentSessionId,
9810
+ reason: "logout"
9811
+ });
9812
+ recordUserEvent(strapi2, {
9813
+ event: SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
9814
+ actorType: "user",
9815
+ actorId: userDocumentId,
9816
+ targetType: "user",
9817
+ targetId: userDocumentId,
9818
+ ip: getClientIp(ctx),
9819
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
9820
+ meta: { ended: Number(terminatedCount) || 0 }
9821
+ });
9822
+ log.info("[PASSWORD] Ended the other sessions after a password change");
9823
+ }
8190
9824
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
8191
9825
  strapi2.server.use(async (ctx, next) => {
8192
9826
  const apiPath = apiPathOf(strapi2, ctx);
@@ -8237,6 +9871,7 @@ var require_bootstrap = __commonJS({
8237
9871
  filters: { tokenHash: hashToken(previousAccessToken), isActive: true },
8238
9872
  fields: ["documentId"]
8239
9873
  });
9874
+ let currentSidecarId;
8240
9875
  if (matchingSession) {
8241
9876
  const rotated = await sessionService.rotateSessionTokens({
8242
9877
  sessionId: matchingSession.documentId,
@@ -8247,6 +9882,7 @@ var require_bootstrap = __commonJS({
8247
9882
  });
8248
9883
  if (!rotated)
8249
9884
  throw new Error("current sidecar changed before native password rotation was linked");
9885
+ currentSidecarId = matchingSession.documentId;
8250
9886
  log.info("[PASSWORD] Native session link updated");
8251
9887
  } else {
8252
9888
  const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
@@ -8262,7 +9898,16 @@ var require_bootstrap = __commonJS({
8262
9898
  if (!createdSidecar?.documentId) {
8263
9899
  throw new Error("native password-change sidecar creation returned no documentId");
8264
9900
  }
9901
+ currentSidecarId = createdSidecar.documentId;
8265
9902
  }
9903
+ await endOtherSessionsAfterPasswordChange({
9904
+ strapi: strapi2,
9905
+ ctx,
9906
+ log,
9907
+ sessionService,
9908
+ userDocumentId: nativeSession2.userDocumentId,
9909
+ currentSessionId: currentSidecarId
9910
+ });
8266
9911
  } catch (err) {
8267
9912
  if (nativeSessionManager2 && nativeSession2) {
8268
9913
  await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
@@ -8299,8 +9944,21 @@ var require_bootstrap = __commonJS({
8299
9944
  accessToken: ctx.body.jwt,
8300
9945
  refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName)
8301
9946
  });
8302
- if (!rotated) throw new Error("current session changed before token rotation");
8303
- log.info("[PASSWORD] Legacy session tokens rotated");
9947
+ if (!rotated) throw new Error("current session changed before token rotation");
9948
+ log.info("[PASSWORD] Legacy session tokens rotated");
9949
+ const owner = await strapi2.documents(SESSION_UID).findOne({
9950
+ documentId: matchingSession.documentId,
9951
+ fields: ["documentId"],
9952
+ populate: { user: { fields: ["documentId"] } }
9953
+ });
9954
+ await endOtherSessionsAfterPasswordChange({
9955
+ strapi: strapi2,
9956
+ ctx,
9957
+ log,
9958
+ sessionService,
9959
+ userDocumentId: owner?.user?.documentId || null,
9960
+ currentSessionId: matchingSession.documentId
9961
+ });
8304
9962
  } catch (err) {
8305
9963
  failClosedAuthResponse({
8306
9964
  ctx,
@@ -8343,19 +10001,58 @@ var require_bootstrap = __commonJS({
8343
10001
  throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
8344
10002
  }
8345
10003
  const geoData = ctx.state?.__magicSessionGeoData || null;
8346
- const newSession = await sessionService.createSession({
10004
+ const requestSettings = await getPluginSettings(strapi2);
10005
+ const isReset = isPasswordResetRequest(apiPath, ctx.method);
10006
+ const deviceKey = deviceKeyOf(userAgent, requestDeviceId(ctx));
10007
+ const create = () => sessionService.createSession({
8347
10008
  userId: userDocId,
8348
10009
  ip,
8349
10010
  userAgent,
8350
10011
  token: ctx.body.jwt,
8351
10012
  refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
8352
10013
  geoData,
10014
+ deviceKey,
8353
10015
  ...nativeSession ? { nativeSessionId: nativeSession.sessionId } : {}
8354
10016
  });
10017
+ const limited = isReset ? { session: await create(), refused: false, ended: 0, limit: 0 } : await createSessionWithinLimit({
10018
+ strapi: strapi2,
10019
+ settings: requestSettings,
10020
+ userDocumentId: userDocId,
10021
+ create,
10022
+ sessionService
10023
+ });
10024
+ const newSession = limited.session;
8355
10025
  if (!newSession?.documentId) {
8356
10026
  throw new Error(`session creation returned no documentId for user ${userDocId}`);
8357
10027
  }
8358
- if (isPasswordResetRequest(apiPath, ctx.method)) {
10028
+ if (limited.refused) {
10029
+ recordUserEvent(strapi2, {
10030
+ event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
10031
+ actorType: "user",
10032
+ actorId: userDocId,
10033
+ targetType: "user",
10034
+ targetId: userDocId,
10035
+ ip,
10036
+ userAgent,
10037
+ meta: { reason: "session-limit", limit: limited.limit }
10038
+ });
10039
+ refuseSessionLimit({ ctx, strapi: strapi2, limit: limited.limit });
10040
+ log.info("[LIMIT] Sign-in refused: the user reached the session limit");
10041
+ return;
10042
+ }
10043
+ if (limited.ended > 0) {
10044
+ recordUserEvent(strapi2, {
10045
+ event: SECURITY_EVENTS.USER_SESSION_LIMIT,
10046
+ actorType: "system",
10047
+ targetType: "user",
10048
+ targetId: userDocId,
10049
+ ip,
10050
+ userAgent,
10051
+ meta: { ended: limited.ended, limit: limited.limit }
10052
+ });
10053
+ log.info(`[LIMIT] Ended ${limited.ended} older session(s) to stay within the limit`);
10054
+ }
10055
+ if (isReset) {
8359
10056
  await sessionService.terminateSession({
8360
10057
  userId: userDocId,
8361
10058
  exceptSessionId: newSession.documentId,
@@ -8364,9 +10061,45 @@ var require_bootstrap = __commonJS({
8364
10061
  log.info("[PASSWORD] Ended older sessions after password reset");
8365
10062
  }
8366
10063
  log.info("[SUCCESS] End-user session metadata created");
10064
+ let signals = { reauthenticate: false };
10065
+ if (!isReset) {
10066
+ try {
10067
+ signals = await runSignInSignals({
10068
+ strapi: strapi2,
10069
+ settings: requestSettings,
10070
+ user,
10071
+ userDocumentId: userDocId,
10072
+ session: newSession,
10073
+ geoData,
10074
+ deviceKey,
10075
+ userAgent: userAgent === "unknown" ? null : userAgent,
10076
+ ip,
10077
+ record: (input) => recordUserEvent(strapi2, input)
10078
+ });
10079
+ } catch (signalErr) {
10080
+ log.warn("[SIGNALS] Sign-in signals failed (non-fatal):", signalErr?.name || "Error");
10081
+ }
10082
+ }
10083
+ if (signals.reauthenticate) {
10084
+ await sessionService.terminateSession({ userId: userDocId, reason: "manual" });
10085
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
10086
+ ctx.status = 401;
10087
+ ctx.body = {
10088
+ data: null,
10089
+ error: {
10090
+ status: 401,
10091
+ name: "UnauthorizedError",
10092
+ message: "Please sign in again.",
10093
+ details: { code: "REAUTHENTICATION_REQUIRED" }
10094
+ }
10095
+ };
10096
+ log.info("[SIGNALS] Impossible travel: every session ended, a new sign-in is required");
10097
+ return;
10098
+ }
8367
10099
  try {
8368
10100
  const settings = await getPluginSettings(strapi2);
8369
- if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks)) {
10101
+ const genericWebhook = settings.genericWebhookEnabled === true;
10102
+ if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks || genericWebhook)) {
8370
10103
  return;
8371
10104
  }
8372
10105
  const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
@@ -8418,7 +10151,8 @@ var require_bootstrap = __commonJS({
8418
10151
  user,
8419
10152
  session: newSession,
8420
10153
  geoData,
8421
- isNewLocation
10154
+ isNewLocation,
10155
+ webhooks: optionalService(strapi2, "webhooks")
8422
10156
  });
8423
10157
  } catch (notifErr) {
8424
10158
  log.warn("Notification failed:", notifErr?.name || "Error");
@@ -8756,7 +10490,7 @@ var require_bootstrap = __commonJS({
8756
10490
  );
8757
10491
  return false;
8758
10492
  }
8759
- const requiredActions = [
10493
+ const baseActions = [
8760
10494
  "plugin::magic-sessionmanager.session.logout",
8761
10495
  "plugin::magic-sessionmanager.session.logoutAll",
8762
10496
  "plugin::magic-sessionmanager.session.logoutOthers",
@@ -8765,6 +10499,8 @@ var require_bootstrap = __commonJS({
8765
10499
  "plugin::magic-sessionmanager.session.getCurrentSession",
8766
10500
  "plugin::magic-sessionmanager.session.terminateOwnSession"
8767
10501
  ];
10502
+ const version3Actions = ["plugin::magic-sessionmanager.self-service.exportOwnData"];
10503
+ const requiredActions = Number(effectiveVersion) === 2 ? version3Actions : [...baseActions, ...version3Actions];
8768
10504
  const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
8769
10505
  filters: {
8770
10506
  role: authenticatedRole.id,
@@ -9046,11 +10782,13 @@ var require_bootstrap = __commonJS({
9046
10782
  strapi2.log.debug("[magic-sessionmanager] [JWT] No documentId found in relaxed mode");
9047
10783
  return decoded;
9048
10784
  }
10785
+ const needsRole = hasRoleOverride(settings, "inactivityTimeout");
9049
10786
  let userRecord;
9050
10787
  try {
9051
10788
  userRecord = await strapi2.documents("plugin::users-permissions.user").findOne({
9052
10789
  documentId: userDocId,
9053
- fields: ["documentId", "blocked"]
10790
+ fields: ["documentId", "blocked"],
10791
+ ...needsRole ? { populate: { role: { fields: ["documentId"] } } } : {}
9054
10792
  });
9055
10793
  } catch (err) {
9056
10794
  if (strictMode) {
@@ -9119,7 +10857,10 @@ var require_bootstrap = __commonJS({
9119
10857
  setSessionRejectionReason(tokenHashValue, "expired");
9120
10858
  return null;
9121
10859
  }
9122
- const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
10860
+ const inactivityTimeout = inactivityTimeoutFor(
10861
+ settings,
10862
+ userRecord?.role?.documentId || null
10863
+ );
9123
10864
  const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
9124
10865
  const idleFor = Date.now() - lastActiveMs;
9125
10866
  if (idleFor > inactivityTimeout) {
@@ -9274,6 +11015,11 @@ var require_destroy = __commonJS({
9274
11015
  }
9275
11016
  strapi2.sessionManagerAdminActivityUninstall = null;
9276
11017
  }
11018
+ try {
11019
+ strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
11020
+ } catch (err) {
11021
+ log.warn("Failed to stop webhook deliveries:", err?.name || "Error");
11022
+ }
9277
11023
  log.info("[SUCCESS] Plugin cleanup completed");
9278
11024
  };
9279
11025
  }
@@ -9315,6 +11061,9 @@ var require_config = __commonJS({
9315
11061
  discordWebhookUrl: "",
9316
11062
  slackWebhookUrl: "",
9317
11063
  trustedProxies: null,
11064
+ // Sign-in and session policies (4.17). Existing installations keep
11065
+ // `endOtherSessionsOnPasswordChange: false` (utils/upgrade-defaults.js).
11066
+ endOtherSessionsOnPasswordChange: true,
9318
11067
  // Cross-process state for pm2 cluster / several replicas. `enabled:
9319
11068
  // false` keeps every counter, lease and cache per process (the pre-4.10
9320
11069
  // behaviour). `counterStore` may supply an object with async
@@ -9485,6 +11234,12 @@ var require_schema = __commonJS({
9485
11234
  },
9486
11235
  osName: {
9487
11236
  type: "string"
11237
+ },
11238
+ deviceKey: {
11239
+ type: "string",
11240
+ maxLength: 64,
11241
+ configurable: false,
11242
+ private: true
9488
11243
  }
9489
11244
  }
9490
11245
  };
@@ -9725,6 +11480,57 @@ var require_content_api = __commonJS({
9725
11480
  description: "Get sessions by userId (user can only see own sessions)"
9726
11481
  }
9727
11482
  },
11483
+ // ================== SELF-SERVICE (4.17) ==================
11484
+ {
11485
+ method: "GET",
11486
+ path: "/my-data",
11487
+ handler: "self-service.exportOwnData",
11488
+ config: {
11489
+ auth: { strategies: ["users-permissions"] },
11490
+ // An export reads every own session and event: 3 per hour per user.
11491
+ middlewares: [
11492
+ {
11493
+ name: "plugin::magic-sessionmanager.rate-limit",
11494
+ config: { max: 3, window: 60 * 60 * 1e3 }
11495
+ }
11496
+ ],
11497
+ description: "Download own sessions and security events as JSON (GDPR Art. 15)"
11498
+ }
11499
+ },
11500
+ {
11501
+ method: "GET",
11502
+ path: "/not-me",
11503
+ handler: "self-service.notMePage",
11504
+ config: {
11505
+ // Public on purpose: opened from the "This wasn't me" email. Only
11506
+ // shows a confirmation; the signed token is checked, nothing changes.
11507
+ auth: false,
11508
+ middlewares: [
11509
+ {
11510
+ name: "plugin::magic-sessionmanager.rate-limit",
11511
+ config: { max: 30, window: 6e4 }
11512
+ }
11513
+ ],
11514
+ description: `Confirmation page of the "This wasn't me" email link (public)`
11515
+ }
11516
+ },
11517
+ {
11518
+ method: "POST",
11519
+ path: "/not-me",
11520
+ handler: "self-service.notMeConfirm",
11521
+ config: {
11522
+ // Public on purpose: the signed, expiring, single-use token from the
11523
+ // email is the authorisation.
11524
+ auth: false,
11525
+ middlewares: [
11526
+ {
11527
+ name: "plugin::magic-sessionmanager.rate-limit",
11528
+ config: { max: 10, window: 6e4 }
11529
+ }
11530
+ ],
11531
+ description: `End the session of a "This wasn't me" link (public, single-use token)`
11532
+ }
11533
+ },
9728
11534
  // ================== OWN SESSION MANAGEMENT ==================
9729
11535
  {
9730
11536
  method: "DELETE",
@@ -9749,6 +11555,8 @@ var require_admin = __commonJS({
9749
11555
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
9750
11556
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
9751
11557
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
11558
+ var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
11559
+ var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
9752
11560
  var adminPolicy = () => [
9753
11561
  "admin::isAuthenticatedAdmin",
9754
11562
  {
@@ -10002,6 +11810,54 @@ var require_admin = __commonJS({
10002
11810
  description: "Get one export batch of Content Manager activity of admins (admin)"
10003
11811
  }
10004
11812
  },
11813
+ // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
11814
+ {
11815
+ method: "GET",
11816
+ path: "/lockouts",
11817
+ handler: "lockouts.list",
11818
+ config: {
11819
+ policies: adminPolicy(),
11820
+ middlewares: adminReadRateLimit(),
11821
+ description: "List the active sign-in locks (admin)"
11822
+ }
11823
+ },
11824
+ {
11825
+ method: "POST",
11826
+ path: "/lockouts/unlock",
11827
+ handler: "lockouts.unlock",
11828
+ config: {
11829
+ policies: adminSessionsPolicy([LOCKOUTS_UNLOCK_ACTION]),
11830
+ middlewares: adminSignOutRateLimit(),
11831
+ description: "Lift one sign-in lock (admin)"
11832
+ }
11833
+ },
11834
+ {
11835
+ method: "GET",
11836
+ path: "/roles",
11837
+ handler: "lockouts.roles",
11838
+ config: {
11839
+ policies: adminPolicy(),
11840
+ middlewares: adminReadRateLimit(),
11841
+ description: "List Users & Permissions roles for per-role rules (admin)"
11842
+ }
11843
+ },
11844
+ // ============================ SIGNED WEBHOOK ============================
11845
+ {
11846
+ method: "POST",
11847
+ path: "/webhook/test",
11848
+ handler: "webhooks.sendTest",
11849
+ config: {
11850
+ // Sends to the stored URL: same permission as changing it.
11851
+ policies: adminSessionsPolicy([SETTINGS_UPDATE_ACTION]),
11852
+ middlewares: [
11853
+ {
11854
+ name: "plugin::magic-sessionmanager.rate-limit",
11855
+ config: { profile: "write", max: 5, window: 6e4 }
11856
+ }
11857
+ ],
11858
+ description: "Send a signed test event to the stored webhook URL (admin)"
11859
+ }
11860
+ },
10005
11861
  // ============================ GEOLOCATION ============================
10006
11862
  {
10007
11863
  method: "GET",
@@ -12334,6 +14190,8 @@ var require_settings_access = __commonJS({
12334
14190
  "server/src/utils/settings-access.js"(exports, module) {
12335
14191
  "use strict";
12336
14192
  var { SECURITY_LOG_KEYS } = require_security_log_settings();
14193
+ var { POLICY_KEYS } = require_policy_settings();
14194
+ var { PROTECTED_DETECTION_KEYS } = require_detection_settings();
12337
14195
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12338
14196
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12339
14197
  var GEO_SETTINGS_KEYS = Object.freeze([
@@ -12350,11 +14208,20 @@ var require_settings_access = __commonJS({
12350
14208
  var PROTECTED_SETTINGS_KEYS = Object.freeze([
12351
14209
  ...GEO_SETTINGS_KEYS,
12352
14210
  ...WEBHOOK_SETTINGS_KEYS,
12353
- ...SECURITY_LOG_KEYS
14211
+ ...SECURITY_LOG_KEYS,
14212
+ // Sign-in and session policies (lockout, trusted addresses, session
14213
+ // limit, password-change sign-out, recording switch, per-role rules).
14214
+ ...POLICY_KEYS,
14215
+ // Signed webhook, event selection, impossible travel and shortened IPs.
14216
+ ...PROTECTED_DETECTION_KEYS
12354
14217
  ]);
12355
14218
  var WEBHOOK_SECRETS = Object.freeze([
12356
14219
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
12357
- { key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" }
14220
+ { key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" },
14221
+ { key: "genericWebhookUrl", has: "hasGenericWebhook", hint: "genericWebhookHint" }
14222
+ ]);
14223
+ var WRITE_ONLY_SECRETS = Object.freeze([
14224
+ { key: "genericWebhookSecret", has: "hasGenericWebhookSecret" }
12358
14225
  ]);
12359
14226
  function sameValue(a, b) {
12360
14227
  if (a === b) return true;
@@ -12402,6 +14269,11 @@ var require_settings_access = __commonJS({
12402
14269
  out[has] = typeof value === "string" && value.trim().length > 0;
12403
14270
  out[hint] = webhookHint(value);
12404
14271
  }
14272
+ for (const { key, has } of WRITE_ONLY_SECRETS) {
14273
+ const value = out[key];
14274
+ delete out[key];
14275
+ out[has] = typeof value === "string" && value.length > 0;
14276
+ }
12405
14277
  return out;
12406
14278
  }
12407
14279
  module.exports = {
@@ -12411,6 +14283,7 @@ var require_settings_access = __commonJS({
12411
14283
  SETTINGS_UPDATE_ACTION,
12412
14284
  WEBHOOK_SECRETS,
12413
14285
  WEBHOOK_SETTINGS_KEYS,
14286
+ WRITE_ONLY_SECRETS,
12414
14287
  callerCan,
12415
14288
  changedKeys,
12416
14289
  missingSettingsPermission,
@@ -12443,6 +14316,10 @@ var require_settings = __commonJS({
12443
14316
  missingSettingsPermission,
12444
14317
  toPublicSettings
12445
14318
  } = require_settings_access();
14319
+ var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
14320
+ var { DETECTION_DEFAULTS, validateDetectionSettings } = require_detection_settings();
14321
+ var { encryptToken } = require_encryption();
14322
+ var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
12446
14323
  var path = __require("node:path");
12447
14324
  var ALLOWED_WEBHOOK_DOMAINS = {
12448
14325
  discord: ["discord.com", "discordapp.com"],
@@ -12474,11 +14351,9 @@ var require_settings = __commonJS({
12474
14351
  }
12475
14352
  }
12476
14353
  function sanitizeEmailTemplates(templates) {
12477
- const defaults = {
12478
- suspiciousLogin: { subject: "", html: "", text: "" },
12479
- newLocation: { subject: "", html: "", text: "" },
12480
- vpnProxy: { subject: "", html: "", text: "" }
12481
- };
14354
+ const defaults = Object.fromEntries(
14355
+ Object.keys(DEFAULT_EMAIL_TEMPLATES).map((key) => [key, { subject: "", html: "", text: "" }])
14356
+ );
12482
14357
  if (!templates || typeof templates !== "object") return defaults;
12483
14358
  let sanitizeHtml;
12484
14359
  try {
@@ -12584,7 +14459,11 @@ var require_settings = __commonJS({
12584
14459
  var DEFAULT_EMAIL_TEMPLATES = {
12585
14460
  suspiciousLogin: { subject: "", html: "", text: "" },
12586
14461
  newLocation: { subject: "", html: "", text: "" },
12587
- vpnProxy: { subject: "", html: "", text: "" }
14462
+ vpnProxy: { subject: "", html: "", text: "" },
14463
+ // 4.17: sent to a user whose account was locked after failed sign-ins.
14464
+ accountLocked: { subject: "", html: "", text: "" },
14465
+ newDevice: { subject: "", html: "", text: "" },
14466
+ impossibleTravel: { subject: "", html: "", text: "" }
12588
14467
  };
12589
14468
  var DEFAULT_SETTINGS = {
12590
14469
  inactivityTimeout: 15,
@@ -12617,7 +14496,13 @@ var require_settings = __commonJS({
12617
14496
  strictSessionEnforcement: false,
12618
14497
  trustedProxies: false,
12619
14498
  emailTemplates: DEFAULT_EMAIL_TEMPLATES,
12620
- ...SECURITY_LOG_DEFAULTS
14499
+ ...SECURITY_LOG_DEFAULTS,
14500
+ ...POLICY_DEFAULTS,
14501
+ lockoutTrustedAddresses: [],
14502
+ roleRules: [],
14503
+ ...DETECTION_DEFAULTS,
14504
+ webhookEvents: [...DETECTION_DEFAULTS.webhookEvents],
14505
+ genericWebhookSecret: ""
12621
14506
  };
12622
14507
  function mergeSettingsWithDefaults(stored) {
12623
14508
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -12825,6 +14710,25 @@ var require_settings = __commonJS({
12825
14710
  const securityLog = validateSecurityLogSettings(body);
12826
14711
  errors.push(...securityLog.errors);
12827
14712
  Object.assign(next, securityLog.values);
14713
+ const policies = validatePolicySettings(body);
14714
+ errors.push(...policies.errors);
14715
+ Object.assign(next, policies.values);
14716
+ const detection = validateDetectionSettings(body);
14717
+ errors.push(...detection.errors);
14718
+ Object.assign(next, detection.values);
14719
+ if (has("genericWebhookSecret")) {
14720
+ const secret = body.genericWebhookSecret;
14721
+ if (secret === "") {
14722
+ next.genericWebhookSecret = "";
14723
+ } else if (typeof secret !== "string" || !WEBHOOK_SECRET_PATTERN.test(secret)) {
14724
+ errors.push({
14725
+ path: ["genericWebhookSecret"],
14726
+ message: "genericWebhookSecret must be 32 to 256 printable characters without spaces"
14727
+ });
14728
+ } else {
14729
+ next.genericWebhookSecret = encryptToken(secret);
14730
+ }
14731
+ }
12828
14732
  if (errors.length > 0) return { errors };
12829
14733
  const settings = {};
12830
14734
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -12854,7 +14758,7 @@ var require_settings = __commonJS({
12854
14758
  }
12855
14759
  var FORBIDDEN_MESSAGES = Object.freeze({
12856
14760
  "admin-activity-permission": 'Changing the security log settings needs "View admin activity".',
12857
- "settings-update-permission": 'Changing location lookup, webhook or security log settings needs "Change protected settings".'
14761
+ "settings-update-permission": 'Changing location lookup, webhook, security log, sign-in policy or detection settings needs "Change protected settings".'
12858
14762
  });
12859
14763
  function recordSettingsChange(ctx, keys) {
12860
14764
  if (!keys.length) return;
@@ -12874,6 +14778,16 @@ var require_settings = __commonJS({
12874
14778
  } catch {
12875
14779
  }
12876
14780
  }
14781
+ async function findUnknownRoles(rules) {
14782
+ if (!Array.isArray(rules) || rules.length === 0) return [];
14783
+ const ids = rules.map((rule) => rule.role);
14784
+ const rows = await strapi.db.query("plugin::users-permissions.role").findMany({ where: { documentId: { $in: ids } }, select: ["documentId"] });
14785
+ const known = new Set((Array.isArray(rows) ? rows : []).map((row) => row.documentId));
14786
+ return rules.map((rule, index) => known.has(rule.role) ? null : index).filter((index) => index !== null).map((index) => ({
14787
+ path: ["roleRules", index, "role"],
14788
+ message: "This role does not exist any more"
14789
+ }));
14790
+ }
12877
14791
  module.exports = {
12878
14792
  /**
12879
14793
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -12958,6 +14872,8 @@ var require_settings = __commonJS({
12958
14872
  };
12959
14873
  const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
12960
14874
  if (errors.length > 0) return { errors };
14875
+ const roleErrors = await findUnknownRoles(sanitizedSettings.roleRules);
14876
+ if (roleErrors.length > 0) return { errors: roleErrors };
12961
14877
  const changed = changedKeys(
12962
14878
  {
12963
14879
  ...sanitizedSettings,
@@ -13013,6 +14929,7 @@ var require_settings = __commonJS({
13013
14929
  },
13014
14930
  DEFAULT_SETTINGS,
13015
14931
  mergeSettingsWithDefaults,
14932
+ toPublicSettings,
13016
14933
  validateSettingsUpdate
13017
14934
  };
13018
14935
  }
@@ -14330,23 +16247,490 @@ var require_admin_activity = __commonJS({
14330
16247
  );
14331
16248
  },
14332
16249
  /**
14333
- * One export batch (500 rows, keyset cursor) of Content Manager activity.
16250
+ * One export batch (500 rows, keyset cursor) of Content Manager activity.
16251
+ *
16252
+ * @route GET /magic-sessionmanager/admin-activity/content/export
16253
+ * @auth As listContentActivity.
16254
+ * @param {Context} ctx Same filters as the list, plus `cursor`.
16255
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
16256
+ */
16257
+ async exportContentActivity(ctx) {
16258
+ return handle(
16259
+ ctx,
16260
+ activityExportSchema,
16261
+ (query) => {
16262
+ auditTokenRead(ctx, "content", true);
16263
+ return service().exportBatch("content", query, query.cursor || null, viewerOf(ctx));
16264
+ },
16265
+ "activity export"
16266
+ );
16267
+ }
16268
+ };
16269
+ };
16270
+ }
16271
+ });
16272
+
16273
+ // server/src/controllers/lockouts.js
16274
+ var require_lockouts = __commonJS({
16275
+ "server/src/controllers/lockouts.js"(exports, module) {
16276
+ "use strict";
16277
+ var { getCoordinator } = require_coordination();
16278
+ var { LOCK_ID_PATTERN, createLoginLockout } = require_login_lockout();
16279
+ var { getRequestIp, getRequestUserAgent } = require_admin_request_info();
16280
+ var { SECURITY_EVENTS } = require_security_log_model();
16281
+ var { sendServerError, sendValidationError } = require_http_errors();
16282
+ var { createLogger } = require_logger();
16283
+ var USER_UID = "plugin::users-permissions.user";
16284
+ var ROLE_UID = "plugin::users-permissions.role";
16285
+ module.exports = ({ strapi: strapi2 }) => {
16286
+ const log = createLogger(strapi2);
16287
+ const lockout = () => createLoginLockout(getCoordinator(strapi2));
16288
+ return {
16289
+ /**
16290
+ * Lists the active sign-in locks: locked IP addresses (shown as the
16291
+ * security log stores IPs) and locked accounts with their user.
16292
+ *
16293
+ * @route GET /magic-sessionmanager/lockouts
16294
+ * @auth admin session or admin API token
16295
+ * @access plugin::magic-sessionmanager.access
16296
+ * @param {any} ctx Koa context.
16297
+ * @returns {Promise<void>} `{ data: Lock[], meta: { total } }`; 500 on store failure.
16298
+ */
16299
+ async list(ctx) {
16300
+ try {
16301
+ const locks = await lockout().listLocks();
16302
+ const ids = [...new Set(locks.map((lock) => lock.user).filter(Boolean))];
16303
+ const users = ids.length ? await strapi2.db.query(USER_UID).findMany({
16304
+ where: { documentId: { $in: ids } },
16305
+ select: ["documentId", "username", "email"]
16306
+ }) : [];
16307
+ const byId = new Map(
16308
+ (Array.isArray(users) ? users : []).map((user) => [user.documentId, user])
16309
+ );
16310
+ const data = locks.map((lock) => {
16311
+ const user = lock.user ? byId.get(lock.user) : null;
16312
+ return {
16313
+ id: lock.id,
16314
+ kind: lock.kind,
16315
+ ip: lock.kind === "ip" ? lock.ip : null,
16316
+ user: user ? { documentId: user.documentId, username: user.username, email: user.email } : null,
16317
+ failures: lock.failures,
16318
+ lockedAt: new Date(lock.lockedAt).toISOString(),
16319
+ until: new Date(lock.until).toISOString()
16320
+ };
16321
+ });
16322
+ ctx.body = { data, meta: { total: data.length } };
16323
+ } catch (err) {
16324
+ log.error("[lockouts] List failed:", err?.name || "Error");
16325
+ return sendServerError(ctx, 500, "Locks could not be loaded");
16326
+ }
16327
+ },
16328
+ /**
16329
+ * Lifts one lock. The admin who lifted it is recorded in the security log.
16330
+ *
16331
+ * @route POST /magic-sessionmanager/lockouts/unlock
16332
+ * @auth admin session or admin API token
16333
+ * @access plugin::magic-sessionmanager.access + plugin::magic-sessionmanager.lockouts.unlock
16334
+ * @param {any} ctx Koa context; body `{ id }` from the list.
16335
+ * @returns {Promise<void>} `{ data: { unlocked: true, kind } }`; 400 invalid id; 404 not locked.
16336
+ * @sideeffect Deletes the shared lock counter and list entry; writes `user.lockout.lifted`.
16337
+ */
16338
+ async unlock(ctx) {
16339
+ const body = ctx.request?.body;
16340
+ const id = body && typeof body === "object" && !Array.isArray(body) ? body.id : void 0;
16341
+ const extra = body && typeof body === "object" ? Object.keys(body).filter((key) => key !== "id") : [];
16342
+ if (typeof id !== "string" || !LOCK_ID_PATTERN.test(id) || extra.length > 0) {
16343
+ return sendValidationError(ctx, "Invalid lock", [
16344
+ { path: ["id"], message: "id must be a lock id from the list" }
16345
+ ]);
16346
+ }
16347
+ try {
16348
+ const lifted = await lockout().unlock(id);
16349
+ if (!lifted) return ctx.notFound("This lock has already ended");
16350
+ try {
16351
+ const liftEvent = {
16352
+ event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
16353
+ actorType: "admin",
16354
+ actorId: ctx.state?.user?.id ?? null,
16355
+ targetType: lifted.kind === "account" ? "user" : "ip",
16356
+ targetId: lifted.kind === "account" ? lifted.user : null,
16357
+ meta: { kind: lifted.kind }
16358
+ };
16359
+ strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(liftEvent);
16360
+ strapi2.plugin("magic-sessionmanager").service("security-log").record({
16361
+ event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
16362
+ actorType: "admin",
16363
+ actorId: ctx.state?.user?.id ?? null,
16364
+ targetType: lifted.kind === "account" ? "user" : "ip",
16365
+ targetId: lifted.kind === "account" ? lifted.user : null,
16366
+ ip: getRequestIp(ctx),
16367
+ userAgent: getRequestUserAgent(ctx),
16368
+ meta: { kind: lifted.kind }
16369
+ });
16370
+ } catch {
16371
+ }
16372
+ ctx.body = { data: { unlocked: true, kind: lifted.kind } };
16373
+ } catch (err) {
16374
+ log.error("[lockouts] Unlock failed:", err?.name || "Error");
16375
+ return sendServerError(ctx, 500, "The lock could not be lifted");
16376
+ }
16377
+ },
16378
+ /**
16379
+ * Users & Permissions roles for the per-role rules (the Public role has
16380
+ * no signed-in users and is left out).
16381
+ *
16382
+ * @route GET /magic-sessionmanager/roles
16383
+ * @auth admin session or admin API token
16384
+ * @access plugin::magic-sessionmanager.access
16385
+ * @param {any} ctx Koa context.
16386
+ * @returns {Promise<void>} `{ data: [{ documentId, name, type }] }`.
16387
+ */
16388
+ async roles(ctx) {
16389
+ try {
16390
+ const rows = await strapi2.db.query(ROLE_UID).findMany({
16391
+ select: ["documentId", "name", "type"],
16392
+ where: { type: { $ne: "public" } },
16393
+ orderBy: { name: "asc" },
16394
+ limit: 200
16395
+ });
16396
+ ctx.body = {
16397
+ data: (Array.isArray(rows) ? rows : []).map((role) => ({
16398
+ documentId: role.documentId,
16399
+ name: role.name,
16400
+ type: role.type
16401
+ }))
16402
+ };
16403
+ } catch (err) {
16404
+ log.error("[lockouts] Roles could not be listed:", err?.name || "Error");
16405
+ return sendServerError(ctx, 500, "Roles could not be loaded");
16406
+ }
16407
+ }
16408
+ };
16409
+ };
16410
+ }
16411
+ });
16412
+
16413
+ // server/src/controllers/self-service.js
16414
+ var require_self_service = __commonJS({
16415
+ "server/src/controllers/self-service.js"(exports, module) {
16416
+ "use strict";
16417
+ var { getCoordinator } = require_coordination();
16418
+ var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
16419
+ var { recordUserEvent } = require_sign_in_policies();
16420
+ var { resolveUserDocumentId } = require_resolve_user();
16421
+ var { SECURITY_EVENTS } = require_security_log_model();
16422
+ var { sendServerError } = require_http_errors();
16423
+ var { createLogger } = require_logger();
16424
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
16425
+ var EVENT_UID = "plugin::magic-sessionmanager.security-event";
16426
+ var USER_UID = "plugin::users-permissions.user";
16427
+ var EXPORT_LIMIT = 5e3;
16428
+ var EXPORT_BATCH = 500;
16429
+ var PAGE_TEXT = Object.freeze({
16430
+ en: {
16431
+ title: "Was this sign-in not you?",
16432
+ body: "Sign the device of that sign-in out now. Then change your password.",
16433
+ one: "Sign out that device",
16434
+ all: "Sign out everywhere",
16435
+ done: "Done. The session was ended. Change your password now.",
16436
+ doneAll: "Done. Every session of your account was ended. Change your password now.",
16437
+ invalid: "This link is no longer valid. It works once and expires after 72 hours."
16438
+ },
16439
+ de: {
16440
+ title: "Waren Sie das nicht?",
16441
+ body: "Melden Sie das Ger\xE4t dieser Anmeldung jetzt ab. \xC4ndern Sie danach Ihr Passwort.",
16442
+ one: "Dieses Ger\xE4t abmelden",
16443
+ all: "\xDCberall abmelden",
16444
+ done: "Erledigt. Die Sitzung wurde beendet. \xC4ndern Sie jetzt Ihr Passwort.",
16445
+ doneAll: "Erledigt. Alle Sitzungen Ihres Kontos wurden beendet. \xC4ndern Sie jetzt Ihr Passwort.",
16446
+ invalid: "Dieser Link ist nicht mehr g\xFCltig. Er funktioniert einmal und l\xE4uft nach 72 Stunden ab."
16447
+ },
16448
+ fr: {
16449
+ title: "Cette connexion n\u2019\xE9tait pas vous ?",
16450
+ body: "D\xE9connectez maintenant l\u2019appareil de cette connexion, puis changez votre mot de passe.",
16451
+ one: "D\xE9connecter cet appareil",
16452
+ all: "Se d\xE9connecter partout",
16453
+ done: "C\u2019est fait. La session a \xE9t\xE9 termin\xE9e. Changez maintenant votre mot de passe.",
16454
+ doneAll: "C\u2019est fait. Toutes les sessions de votre compte ont \xE9t\xE9 termin\xE9es. Changez maintenant votre mot de passe.",
16455
+ invalid: "Ce lien n\u2019est plus valide. Il fonctionne une fois et expire apr\xE8s 72 heures."
16456
+ },
16457
+ es: {
16458
+ title: "\xBFEste inicio de sesi\xF3n no fue usted?",
16459
+ body: "Cierre ahora la sesi\xF3n del dispositivo de ese inicio de sesi\xF3n y despu\xE9s cambie su contrase\xF1a.",
16460
+ one: "Cerrar la sesi\xF3n de ese dispositivo",
16461
+ all: "Cerrar sesi\xF3n en todas partes",
16462
+ done: "Hecho. La sesi\xF3n ha terminado. Cambie ahora su contrase\xF1a.",
16463
+ doneAll: "Hecho. Todas las sesiones de su cuenta han terminado. Cambie ahora su contrase\xF1a.",
16464
+ invalid: "Este enlace ya no es v\xE1lido. Funciona una vez y caduca a las 72 horas."
16465
+ },
16466
+ pt: {
16467
+ title: "Este in\xEDcio de sess\xE3o n\xE3o foi seu?",
16468
+ body: "Termine agora a sess\xE3o do dispositivo desse in\xEDcio de sess\xE3o e depois altere a sua palavra-passe.",
16469
+ one: "Terminar a sess\xE3o desse dispositivo",
16470
+ all: "Terminar sess\xE3o em todo o lado",
16471
+ done: "Feito. A sess\xE3o foi terminada. Altere agora a sua palavra-passe.",
16472
+ doneAll: "Feito. Todas as sess\xF5es da sua conta foram terminadas. Altere agora a sua palavra-passe.",
16473
+ invalid: "Esta liga\xE7\xE3o j\xE1 n\xE3o \xE9 v\xE1lida. Funciona uma vez e expira ap\xF3s 72 horas."
16474
+ }
16475
+ });
16476
+ function pageLanguage(ctx) {
16477
+ const header = String(ctx.request?.headers?.["accept-language"] || "").slice(0, 200);
16478
+ for (const part of header.split(",")) {
16479
+ const code = part.trim().slice(0, 2).toLowerCase();
16480
+ if (Object.prototype.hasOwnProperty.call(PAGE_TEXT, code)) {
16481
+ return (
16482
+ /** @type {keyof typeof PAGE_TEXT} */
16483
+ code
16484
+ );
16485
+ }
16486
+ }
16487
+ return "en";
16488
+ }
16489
+ var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
16490
+ function sendPage(ctx, status, lang, title, body) {
16491
+ ctx.status = status;
16492
+ ctx.set("Content-Type", "text/html; charset=utf-8");
16493
+ ctx.set(
16494
+ "Content-Security-Policy",
16495
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
16496
+ );
16497
+ ctx.set("Referrer-Policy", "no-referrer");
16498
+ ctx.set("Cache-Control", "no-store");
16499
+ ctx.set("X-Robots-Tag", "noindex");
16500
+ ctx.body = `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>
16501
+ <style>body{font-family:system-ui,sans-serif;max-width:36rem;margin:3rem auto;padding:0 1rem;line-height:1.5;color:#212134;background:#fff}button{font:inherit;padding:.6rem 1rem;margin:.25rem .5rem .25rem 0;border-radius:4px;border:1px solid #4945ff;background:#4945ff;color:#fff;cursor:pointer}button.secondary{background:#fff;color:#4945ff}@media (prefers-color-scheme:dark){body{background:#181826;color:#eaeaef}button.secondary{background:#181826}}</style></head>
16502
+ <body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
16503
+ }
16504
+ module.exports = ({ strapi: strapi2 }) => {
16505
+ const log = createLogger(strapi2);
16506
+ return {
16507
+ /**
16508
+ * Confirmation page of the "This wasn't me" link. Uses nothing.
16509
+ *
16510
+ * @route GET /api/magic-sessionmanager/not-me?token=
16511
+ * @auth none (public on purpose: the link is opened from an email; the
16512
+ * signed token is checked, and nothing changes until the POST)
16513
+ * @param {any} ctx Koa context.
16514
+ * @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
16515
+ */
16516
+ async notMePage(ctx) {
16517
+ const lang = pageLanguage(ctx);
16518
+ const text = PAGE_TEXT[lang];
16519
+ const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
16520
+ if (!readNotMeToken(token)) {
16521
+ return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
16522
+ }
16523
+ const form = (scope, label, className) => `<form method="post" style="display:inline"><input type="hidden" name="token" value="${escapeHtml(token)}"><input type="hidden" name="scope" value="${scope}"><button type="submit"${className ? ` class="${className}"` : ""}>${escapeHtml(label)}</button></form>`;
16524
+ return sendPage(
16525
+ ctx,
16526
+ 200,
16527
+ lang,
16528
+ text.title,
16529
+ `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
16530
+ );
16531
+ },
16532
+ /**
16533
+ * Uses a "This wasn't me" token: ends that session, or every session of
16534
+ * the user with `scope=all`, and records `user.not-me`.
16535
+ *
16536
+ * @route POST /api/magic-sessionmanager/not-me
16537
+ * @auth none (public on purpose; the signed single-use token authorises)
16538
+ * @param {any} ctx Koa context; body `{ token, scope?: 'session'|'all' }` (form or JSON).
16539
+ * @returns {Promise<void>} 200 page (or JSON `{ ended }` with Accept: application/json);
16540
+ * 410 when the token is invalid, expired or used.
16541
+ * @sideeffect Ends sessions (and native sessions); writes a security event.
16542
+ */
16543
+ async notMeConfirm(ctx) {
16544
+ const lang = pageLanguage(ctx);
16545
+ const text = PAGE_TEXT[lang];
16546
+ const wantsJson = String(ctx.request?.headers?.accept || "").includes("application/json");
16547
+ const body = ctx.request?.body && typeof ctx.request.body === "object" ? ctx.request.body : {};
16548
+ const scope = body.scope === "all" ? "all" : "session";
16549
+ const claims = await consumeNotMeToken(getCoordinator(strapi2), body.token);
16550
+ if (!claims) {
16551
+ if (wantsJson) {
16552
+ ctx.status = 410;
16553
+ ctx.body = {
16554
+ data: null,
16555
+ error: { status: 410, name: "GoneError", message: "This link is no longer valid" }
16556
+ };
16557
+ return;
16558
+ }
16559
+ return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
16560
+ }
16561
+ try {
16562
+ const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
16563
+ let ended = 0;
16564
+ if (scope === "all") {
16565
+ ended = Number(
16566
+ (await sessionService.terminateSession({ userId: claims.userId, reason: "manual" }))?.terminatedCount
16567
+ ) || 0;
16568
+ } else {
16569
+ const session = await strapi2.documents(SESSION_UID).findFirst({
16570
+ filters: { documentId: claims.sessionId, user: { documentId: claims.userId } },
16571
+ fields: ["documentId", "isActive"]
16572
+ });
16573
+ if (session?.isActive) {
16574
+ ended = Number(
16575
+ (await sessionService.terminateSession({
16576
+ sessionId: session.documentId,
16577
+ reason: "manual"
16578
+ }))?.terminatedCount
16579
+ ) || 0;
16580
+ }
16581
+ }
16582
+ recordUserEvent(strapi2, {
16583
+ event: SECURITY_EVENTS.USER_NOT_ME,
16584
+ actorType: "user",
16585
+ actorId: claims.userId,
16586
+ targetType: "user",
16587
+ targetId: claims.userId,
16588
+ ip: ctx.request?.ip || null,
16589
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
16590
+ meta: { scope, ended }
16591
+ });
16592
+ if (wantsJson) {
16593
+ ctx.body = { data: { ended, scope } };
16594
+ return;
16595
+ }
16596
+ return sendPage(
16597
+ ctx,
16598
+ 200,
16599
+ lang,
16600
+ text.title,
16601
+ `<p>${escapeHtml(scope === "all" ? text.doneAll : text.done)}</p>`
16602
+ );
16603
+ } catch (err) {
16604
+ log.error("[not-me] Ending the session failed:", err?.name || "Error");
16605
+ return sendServerError(ctx, 500, "The session could not be ended");
16606
+ }
16607
+ },
16608
+ /**
16609
+ * The signed-in user's own sessions and security events as JSON (GDPR
16610
+ * Art. 15). Tokens, token hashes, device keys and native ids are never
16611
+ * included. At most 5,000 rows of each kind, newest first.
16612
+ *
16613
+ * @route GET /api/magic-sessionmanager/my-data
16614
+ * @auth users-permissions JWT (own data only; the user comes from the token)
16615
+ * @access plugin::magic-sessionmanager.self-service.exportOwnData (Authenticated role)
16616
+ * @param {any} ctx Koa context.
16617
+ * @returns {Promise<void>} 200 JSON attachment; 401 without a user.
16618
+ * @sideeffect Writes a `user.data.exported` security event.
16619
+ */
16620
+ async exportOwnData(ctx) {
16621
+ const authUser = ctx.state?.user;
16622
+ const userDocumentId = authUser?.documentId || (authUser?.id ? await resolveUserDocumentId(strapi2, authUser.id) : null);
16623
+ if (!userDocumentId) return ctx.unauthorized("Authentication required");
16624
+ try {
16625
+ const user = await strapi2.db.query(USER_UID).findOne({
16626
+ where: { documentId: userDocumentId },
16627
+ select: ["documentId", "username", "email", "createdAt"]
16628
+ });
16629
+ const sessions = [];
16630
+ for (let start = 0; start < EXPORT_LIMIT; start += EXPORT_BATCH) {
16631
+ const rows = await strapi2.documents(SESSION_UID).findMany({
16632
+ filters: { user: { documentId: userDocumentId } },
16633
+ fields: [
16634
+ "documentId",
16635
+ "loginTime",
16636
+ "lastActive",
16637
+ "logoutTime",
16638
+ "isActive",
16639
+ "terminationReason",
16640
+ "ipAddress",
16641
+ "userAgent",
16642
+ "deviceType",
16643
+ "browserName",
16644
+ "osName",
16645
+ "geoLocation"
16646
+ ],
16647
+ sort: [{ loginTime: "desc" }, { id: "desc" }],
16648
+ start,
16649
+ limit: EXPORT_BATCH
16650
+ });
16651
+ const list = Array.isArray(rows) ? rows : [];
16652
+ sessions.push(...list.map(({ id: _id, ...row }) => row));
16653
+ if (list.length < EXPORT_BATCH) break;
16654
+ }
16655
+ const events = await strapi2.db.query(EVENT_UID).findMany({
16656
+ where: {
16657
+ $or: [
16658
+ { targetType: "user", targetId: userDocumentId },
16659
+ { actorType: "user", actorId: userDocumentId }
16660
+ ]
16661
+ },
16662
+ select: ["event", "createdAt", "ip", "userAgent", "geo", "meta"],
16663
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16664
+ limit: EXPORT_LIMIT
16665
+ });
16666
+ recordUserEvent(strapi2, {
16667
+ event: SECURITY_EVENTS.USER_DATA_EXPORTED,
16668
+ actorType: "user",
16669
+ actorId: userDocumentId,
16670
+ targetType: "user",
16671
+ targetId: userDocumentId,
16672
+ ip: ctx.request?.ip || null,
16673
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
16674
+ meta: { sessions: sessions.length, events: Array.isArray(events) ? events.length : 0 }
16675
+ });
16676
+ ctx.set("Content-Disposition", 'attachment; filename="my-session-data.json"');
16677
+ ctx.set("Cache-Control", "no-store");
16678
+ ctx.body = {
16679
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
16680
+ user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
16681
+ sessions,
16682
+ securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
16683
+ };
16684
+ } catch (err) {
16685
+ log.error("[my-data] Export failed:", err?.name || "Error");
16686
+ return sendServerError(ctx, 500, "Your data could not be exported");
16687
+ }
16688
+ }
16689
+ };
16690
+ };
16691
+ }
16692
+ });
16693
+
16694
+ // server/src/controllers/webhooks.js
16695
+ var require_webhooks = __commonJS({
16696
+ "server/src/controllers/webhooks.js"(exports, module) {
16697
+ "use strict";
16698
+ var { sendServerError } = require_http_errors();
16699
+ var { createLogger } = require_logger();
16700
+ var RESULT_CODES = /* @__PURE__ */ new Set([
16701
+ "no_url",
16702
+ "no_secret",
16703
+ "invalid_url",
16704
+ "dns_failed",
16705
+ "address_not_allowed",
16706
+ "timeout",
16707
+ "network_error",
16708
+ "redirect_not_followed"
16709
+ ]);
16710
+ module.exports = ({ strapi: strapi2 }) => {
16711
+ const log = createLogger(strapi2);
16712
+ return {
16713
+ /**
16714
+ * Sends one signed `test` event to the stored URL, without retries.
14334
16715
  *
14335
- * @route GET /magic-sessionmanager/admin-activity/content/export
14336
- * @auth As listContentActivity.
14337
- * @param {Context} ctx Same filters as the list, plus `cursor`.
14338
- * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
16716
+ * @route POST /magic-sessionmanager/webhook/test
16717
+ * @auth admin session or admin API token
16718
+ * @access plugin::magic-sessionmanager.access
16719
+ * @param {any} ctx Koa context.
16720
+ * @returns {Promise<void>} `{ data: { ok, status, code } }` (status of the receiver's answer;
16721
+ * code: no_url, no_secret, invalid_url, dns_failed, address_not_allowed, timeout,
16722
+ * network_error, redirect_not_followed or http_<status>).
16723
+ * @sideeffect One HTTPS request to the stored webhook URL.
14339
16724
  */
14340
- async exportContentActivity(ctx) {
14341
- return handle(
14342
- ctx,
14343
- activityExportSchema,
14344
- (query) => {
14345
- auditTokenRead(ctx, "content", true);
14346
- return service().exportBatch("content", query, query.cursor || null, viewerOf(ctx));
14347
- },
14348
- "activity export"
14349
- );
16725
+ async sendTest(ctx) {
16726
+ try {
16727
+ const result = await strapi2.plugin("magic-sessionmanager").service("webhooks").sendTest();
16728
+ const code = result.code === null || RESULT_CODES.has(result.code) || /^http_\d{3}$/.test(result.code) ? result.code : "network_error";
16729
+ ctx.body = { data: { ok: result.ok === true, status: result.status ?? null, code } };
16730
+ } catch (err) {
16731
+ log.error("[webhooks] Test send failed:", err?.name || "Error");
16732
+ return sendServerError(ctx, 500, "The test event could not be sent");
16733
+ }
14350
16734
  }
14351
16735
  };
14352
16736
  };
@@ -14362,12 +16746,18 @@ var require_controllers = __commonJS({
14362
16746
  var geoip = require_geoip();
14363
16747
  var adminSessions = require_admin_sessions2();
14364
16748
  var adminActivity = require_admin_activity();
16749
+ var lockouts = require_lockouts();
16750
+ var selfService = require_self_service();
16751
+ var webhooks = require_webhooks();
14365
16752
  module.exports = {
14366
16753
  session,
14367
16754
  settings,
14368
16755
  geoip,
14369
16756
  "admin-sessions": adminSessions,
14370
- "admin-activity": adminActivity
16757
+ "admin-activity": adminActivity,
16758
+ lockouts,
16759
+ "self-service": selfService,
16760
+ webhooks
14371
16761
  };
14372
16762
  }
14373
16763
  });
@@ -14382,6 +16772,10 @@ var require_session2 = __commonJS({
14382
16772
  var { resolveUserDocumentId } = require_resolve_user();
14383
16773
  var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
14384
16774
  var { getPluginSettings } = require_settings_loader();
16775
+ var { hasRoleOverride, inactivityTimeoutFor } = require_policy_settings();
16776
+ var { resolveDetectionSettings } = require_detection_settings();
16777
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
16778
+ var { pointOf } = require_sign_in_signals();
14385
16779
  var {
14386
16780
  cleanupExpiredAccessTokenRevocations,
14387
16781
  persistAccessTokenRevocation
@@ -14713,6 +17107,7 @@ var require_session2 = __commonJS({
14713
17107
  * @param {string} [params.refreshToken] - Refresh token (will be encrypted)
14714
17108
  * @param {string} [params.nativeSessionId] - Native Users & Permissions session ID.
14715
17109
  * @param {object} [params.geoData]
17110
+ * @param {string} [params.deviceKey] Device key from utils/sign-in-signals.js.
14716
17111
  * @returns {Promise<object>} Created session
14717
17112
  * @throws {Error} When userId is missing
14718
17113
  */
@@ -14723,11 +17118,13 @@ var require_session2 = __commonJS({
14723
17118
  token,
14724
17119
  refreshToken,
14725
17120
  nativeSessionId,
14726
- geoData
17121
+ geoData,
17122
+ deviceKey
14727
17123
  }) {
14728
17124
  if (!userId) {
14729
17125
  throw new Error("createSession: userId is required");
14730
17126
  }
17127
+ const privacy = await getPluginSettings(strapi2).then(resolveDetectionSettings).catch(() => ({}));
14731
17128
  try {
14732
17129
  const now = /* @__PURE__ */ new Date();
14733
17130
  const sessionId = generateSessionId(userId);
@@ -14737,7 +17134,9 @@ var require_session2 = __commonJS({
14737
17134
  const tokenHashValue = token ? hashToken(token) : null;
14738
17135
  const refreshTokenHashValue = refreshToken ? hashToken(refreshToken) : null;
14739
17136
  const parsedUA = parseUserAgent(userAgent);
14740
- const safeIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
17137
+ const rawIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
17138
+ const safeIp = privacy.sessionIpAnonymize && normalizeIp(rawIp) ? anonymizeIp(normalizeIp(rawIp)) || rawIp : rawIp;
17139
+ const point = privacy.impossibleTravelEnabled ? pointOf(geoData) : null;
14741
17140
  const safeUa = (typeof userAgent === "string" ? userAgent : "unknown").substring(0, 500);
14742
17141
  const session = await strapi2.documents(SESSION_UID).create({
14743
17142
  data: {
@@ -14765,8 +17164,10 @@ var require_session2 = __commonJS({
14765
17164
  timezone: geoData.timezone,
14766
17165
  // Marks the stored score as real risk data; without a
14767
17166
  // risk source the score is null (not a fake 100).
14768
- ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
17167
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {},
17168
+ ...point ? { latitude: point.lat, longitude: point.lon } : {}
14769
17169
  } : null,
17170
+ ...typeof deviceKey === "string" && /^[a-f0-9]{32}$/.test(deviceKey) ? { deviceKey } : {},
14770
17171
  securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
14771
17172
  }
14772
17173
  });
@@ -15358,12 +17759,13 @@ var require_session2 = __commonJS({
15358
17759
  const settings = await getPluginSettings(strapi2);
15359
17760
  const nativeManager = getNativeSessionManager(strapi2);
15360
17761
  const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
17762
+ const perRole = hasRoleOverride(settings, "inactivityTimeout");
15361
17763
  const now = /* @__PURE__ */ new Date();
15362
17764
  const cutoffTime = new Date(now.getTime() - inactivityTimeout);
15363
17765
  log.info(
15364
17766
  `[CLEANUP] Cleaning up sessions inactive since before ${cutoffTime.toISOString()}`
15365
17767
  );
15366
- if (useDbDirect && !nativeManager) {
17768
+ if (useDbDirect && !nativeManager && !perRole) {
15367
17769
  try {
15368
17770
  const deactivated = await strapi2.db.connection("magic_sessions").where("is_active", true).andWhere(function whereIdle() {
15369
17771
  this.where("last_active", "<", cutoffTime).orWhere(function whereNullLastActive() {
@@ -15392,7 +17794,9 @@ var require_session2 = __commonJS({
15392
17794
  const batch = await strapi2.documents(SESSION_UID).findMany({
15393
17795
  filters: { isActive: true },
15394
17796
  fields: ["documentId", "lastActive", "loginTime", "nativeSessionId"],
15395
- populate: { user: { fields: ["id", "documentId"] } },
17797
+ populate: {
17798
+ user: perRole ? { fields: ["id", "documentId"], populate: { role: { fields: ["documentId"] } } } : { fields: ["id", "documentId"] }
17799
+ },
15396
17800
  limit: BATCH,
15397
17801
  start,
15398
17802
  sort: { loginTime: "asc" }
@@ -15400,8 +17804,11 @@ var require_session2 = __commonJS({
15400
17804
  if (!batch || batch.length === 0) break;
15401
17805
  for (const session of batch) {
15402
17806
  const lastActiveTime = session.lastActive ? new Date(session.lastActive) : session.loginTime ? new Date(session.loginTime) : null;
15403
- if (lastActiveTime && lastActiveTime < cutoffTime) {
15404
- sessionsToDeactivate.push(session);
17807
+ const sessionCutoff = perRole ? new Date(
17808
+ now.getTime() - inactivityTimeoutFor(settings, session.user?.role?.documentId || null)
17809
+ ) : cutoffTime;
17810
+ if (lastActiveTime && lastActiveTime < sessionCutoff) {
17811
+ sessionsToDeactivate.push({ ...session, cutoff: sessionCutoff });
15405
17812
  }
15406
17813
  }
15407
17814
  if (batch.length < BATCH) break;
@@ -15420,8 +17827,8 @@ var require_session2 = __commonJS({
15420
17827
  documentId: session.documentId,
15421
17828
  isActive: true,
15422
17829
  $or: [
15423
- { lastActive: { $lt: cutoffTime } },
15424
- { lastActive: { $null: true }, loginTime: { $lt: cutoffTime } }
17830
+ { lastActive: { $lt: session.cutoff } },
17831
+ { lastActive: { $null: true }, loginTime: { $lt: session.cutoff } }
15425
17832
  ]
15426
17833
  };
15427
17834
  if (nativeManager) {
@@ -16456,6 +18863,98 @@ var require_notifications = __commonJS({
16456
18863
  if (geoData.isThreat) warnings.push("Threat");
16457
18864
  return warnings;
16458
18865
  }
18866
+ var POLICY_TEMPLATES = Object.freeze({
18867
+ accountLocked: Object.freeze({
18868
+ subject: "Your account was locked after failed sign-ins",
18869
+ html: `<html>
18870
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
18871
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
18872
+ <h2>Your account was temporarily locked</h2>
18873
+ <p>Hello {{user.username}},</p>
18874
+ <p>There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.</p>
18875
+ <p>If these attempts were not yours, change your password after the lock ends.</p>
18876
+ <p style="color: #666; font-size: 12px;">This is an automated security notification.</p>
18877
+ </div>
18878
+ </body>
18879
+ </html>`,
18880
+ text: `Your account was temporarily locked
18881
+
18882
+ Hello {{user.username}},
18883
+
18884
+ There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
18885
+
18886
+ If these attempts were not yours, change your password after the lock ends.`
18887
+ }),
18888
+ newDevice: Object.freeze({
18889
+ subject: "New sign-in to your account",
18890
+ html: `<html>
18891
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
18892
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
18893
+ <h2>New sign-in to your account</h2>
18894
+ <p>Hello {{user.username}},</p>
18895
+ <p>Your account was just used on a device we have not seen before.</p>
18896
+ <ul>
18897
+ <li>Time: {{session.loginTime}}</li>
18898
+ <li>Device: {{device.browser}} on {{device.os}}</li>
18899
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
18900
+ <li>IP address: {{session.ipAddress}}</li>
18901
+ </ul>
18902
+ <p>If this was you, you can ignore this email.</p>
18903
+ <p>If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
18904
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
18905
+ </div>
18906
+ </body>
18907
+ </html>`,
18908
+ text: `New sign-in to your account
18909
+
18910
+ Hello {{user.username}},
18911
+
18912
+ Your account was just used on a device we have not seen before.
18913
+
18914
+ Time: {{session.loginTime}}
18915
+ Device: {{device.browser}} on {{device.os}}
18916
+ Location: {{geo.city}}, {{geo.country}}
18917
+ IP address: {{session.ipAddress}}
18918
+
18919
+ If this was not you, sign this device out and change your password:
18920
+ {{link.notMe}}
18921
+
18922
+ The link works once and expires after 72 hours.`
18923
+ }),
18924
+ impossibleTravel: Object.freeze({
18925
+ subject: "Unusual sign-in to your account",
18926
+ html: `<html>
18927
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
18928
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
18929
+ <h2>Unusual sign-in to your account</h2>
18930
+ <p>Hello {{user.username}},</p>
18931
+ <p>Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.</p>
18932
+ <ul>
18933
+ <li>Time: {{session.loginTime}}</li>
18934
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
18935
+ <li>Device: {{device.browser}} on {{device.os}}</li>
18936
+ </ul>
18937
+ <p>A VPN or a mobile network can cause this. If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
18938
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
18939
+ </div>
18940
+ </body>
18941
+ </html>`,
18942
+ text: `Unusual sign-in to your account
18943
+
18944
+ Hello {{user.username}},
18945
+
18946
+ Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.
18947
+
18948
+ Time: {{session.loginTime}}
18949
+ Location: {{geo.city}}, {{geo.country}}
18950
+ Device: {{device.browser}} on {{device.os}}
18951
+
18952
+ A VPN or a mobile network can cause this. If this was not you, sign this device out and change your password:
18953
+ {{link.notMe}}
18954
+
18955
+ The link works once and expires after 72 hours.`
18956
+ })
18957
+ });
16459
18958
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
16460
18959
  var WEBHOOK_TIMEOUT_MS = 5e3;
16461
18960
  module.exports = ({ strapi: strapi2 }) => ({
@@ -16561,9 +19060,91 @@ Account: {{user.email}}
16561
19060
  Time: {{session.loginTime}}
16562
19061
  IP: {{session.ipAddress}}
16563
19062
  VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
16564
- }
19063
+ },
19064
+ ...POLICY_TEMPLATES
16565
19065
  };
16566
19066
  },
19067
+ /**
19068
+ * One template by key. A stored template without html and text falls back
19069
+ * to the default of that key.
19070
+ *
19071
+ * @param {string} key Template key.
19072
+ * @returns {Promise<{subject: string, html: string, text: string}>} Template.
19073
+ */
19074
+ async getTemplate(key) {
19075
+ const templates = await this.getEmailTemplates();
19076
+ const template = templates?.[key];
19077
+ if (template && (template.html || template.text)) {
19078
+ return {
19079
+ subject: template.subject || POLICY_TEMPLATES[key]?.subject || "",
19080
+ html: template.html || "",
19081
+ text: template.text || ""
19082
+ };
19083
+ }
19084
+ return { ...POLICY_TEMPLATES[key] };
19085
+ },
19086
+ /**
19087
+ * Emails a user about a sign-in from a new device or an impossible
19088
+ * travel, with the "This wasn't me" link.
19089
+ *
19090
+ * @param {'newDevice'|'impossibleTravel'} key Template.
19091
+ * @param {{user: object, session: object, geoData?: object|null, device: object,
19092
+ * travel?: object|null, link: string|null}} data Values.
19093
+ * @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
19094
+ * @sideeffect Sends one email.
19095
+ */
19096
+ async sendSignInSignalEmail(key, data) {
19097
+ try {
19098
+ if (!data?.user?.email) return false;
19099
+ const template = await this.getTemplate(key);
19100
+ const values = { ...data, geoData: data.geoData || {}, link: { notMe: data.link } };
19101
+ await strapi2.plugin("email").service("email").send({
19102
+ to: data.user.email,
19103
+ subject: this.replaceVariables(template.subject, values),
19104
+ html: this.replaceVariables(template.html, values),
19105
+ text: this.replaceVariables(template.text, values)
19106
+ });
19107
+ strapi2.log.info(`[magic-sessionmanager/notifications] ${key} email sent`);
19108
+ return true;
19109
+ } catch (err) {
19110
+ strapi2.log.error(
19111
+ `[magic-sessionmanager/notifications] ${key} email failed:`,
19112
+ err?.name || "Error"
19113
+ );
19114
+ return false;
19115
+ }
19116
+ },
19117
+ /**
19118
+ * Emails a user that their account was locked after failed sign-ins.
19119
+ * Sent through Strapi's email plugin, so a provider plugin such as Magic
19120
+ * Mail delivers it when installed.
19121
+ *
19122
+ * @param {{user: {email?: string, username?: string}, minutes: number, until: number}} params
19123
+ * Account, lock duration in minutes and lock end (epoch ms).
19124
+ * @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
19125
+ * @sideeffect Sends one email.
19126
+ */
19127
+ async sendAccountLockedEmail({ user, minutes, until }) {
19128
+ try {
19129
+ if (!user?.email) return false;
19130
+ const template = await this.getTemplate("accountLocked");
19131
+ const data = { user, lock: { minutes, until } };
19132
+ await strapi2.plugin("email").service("email").send({
19133
+ to: user.email,
19134
+ subject: this.replaceVariables(template.subject, data),
19135
+ html: this.replaceVariables(template.html, data),
19136
+ text: this.replaceVariables(template.text, data)
19137
+ });
19138
+ strapi2.log.info("[magic-sessionmanager/notifications] Account lock email sent");
19139
+ return true;
19140
+ } catch (err) {
19141
+ strapi2.log.error(
19142
+ "[magic-sessionmanager/notifications] Account lock email failed:",
19143
+ err?.name || "Error"
19144
+ );
19145
+ return false;
19146
+ }
19147
+ },
16567
19148
  /**
16568
19149
  * HTML-escapes a string to prevent XSS when it is interpolated into an
16569
19150
  * HTML email template. Non-string inputs are coerced to strings first.
@@ -16601,6 +19182,26 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
16601
19182
  result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
16602
19183
  result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
16603
19184
  result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
19185
+ result = result.replace(
19186
+ /\{\{lock\.minutes\}\}/g,
19187
+ esc(Number.isFinite(data.lock?.minutes) ? String(data.lock.minutes) : "N/A")
19188
+ );
19189
+ result = result.replace(
19190
+ /\{\{lock\.until\}\}/g,
19191
+ esc(Number.isFinite(data.lock?.until) ? new Date(data.lock.until).toUTCString() : "N/A")
19192
+ );
19193
+ result = result.replace(/\{\{device\.browser\}\}/g, esc(data.device?.browser || "Unknown"));
19194
+ result = result.replace(/\{\{device\.os\}\}/g, esc(data.device?.os || "Unknown"));
19195
+ result = result.replace(
19196
+ /\{\{travel\.distanceKm\}\}/g,
19197
+ esc(Number.isFinite(data.travel?.distanceKm) ? String(data.travel.distanceKm) : "N/A")
19198
+ );
19199
+ result = result.replace(
19200
+ /\{\{travel\.speedKmh\}\}/g,
19201
+ esc(Number.isFinite(data.travel?.speedKmh) ? String(data.travel.speedKmh) : "N/A")
19202
+ );
19203
+ const link = typeof data.link?.notMe === "string" && /^https?:\/\//.test(data.link.notMe) ? data.link.notMe : "";
19204
+ result = result.replace(/\{\{link\.notMe\}\}/g, esc(link));
16604
19205
  const score = data.reason?.securityScore;
16605
19206
  result = result.replace(
16606
19207
  /\{\{reason\.securityScore\}\}/g,
@@ -17108,9 +19709,12 @@ var require_security_log = __commonJS({
17108
19709
  };
17109
19710
  const buildRows = async (batch, options, settings) => {
17110
19711
  const groups = /* @__PURE__ */ new Map();
19712
+ const recordUserSignIns = settings.recordUserSignInEvents !== false;
17111
19713
  const wanted = batch.filter((entry) => {
17112
19714
  const gate = recordingSwitchOf(entry.event);
17113
- return gate === "always" || (gate === "signIns" ? options.signIns : options.content);
19715
+ if (gate === "always") return true;
19716
+ if (gate === "userSignIns") return recordUserSignIns;
19717
+ return gate === "signIns" ? options.signIns : options.content;
17114
19718
  });
17115
19719
  if (!wanted.length) return { rows: [], groups };
17116
19720
  const emails = [
@@ -17596,6 +20200,29 @@ var require_security_log = __commonJS({
17596
20200
  * @returns {Promise<void>}
17597
20201
  * @sideeffect Deletes and updates rows of the security event table.
17598
20202
  */
20203
+ /**
20204
+ * Deletes what the log holds about an app user whose account was
20205
+ * deleted: events about the account and events the user caused.
20206
+ *
20207
+ * @param {string} userDocumentId Deleted user's documentId.
20208
+ * @returns {Promise<void>}
20209
+ * @sideeffect Deletes rows of the security event table.
20210
+ */
20211
+ async deleteUserData(userDocumentId) {
20212
+ const key = toId(userDocumentId);
20213
+ if (!key) return;
20214
+ queue = queue.filter(
20215
+ (entry) => !(entry.targetType === "user" && String(entry.targetId) === key) && !(entry.actorType === "user" && String(entry.actorId) === key)
20216
+ );
20217
+ await events().deleteMany({
20218
+ where: {
20219
+ $or: [
20220
+ { targetType: "user", targetId: key },
20221
+ { actorType: "user", actorId: key }
20222
+ ]
20223
+ }
20224
+ });
20225
+ },
17599
20226
  async deleteAdminData(adminId) {
17600
20227
  const id = toAdminId(adminId);
17601
20228
  if (!id) return;
@@ -17868,6 +20495,478 @@ var require_security_log = __commonJS({
17868
20495
  }
17869
20496
  });
17870
20497
 
20498
+ // server/src/utils/webhook-delivery.js
20499
+ var require_webhook_delivery = __commonJS({
20500
+ "server/src/utils/webhook-delivery.js"(exports, module) {
20501
+ "use strict";
20502
+ var crypto = __require("node:crypto");
20503
+ var dns = __require("node:dns");
20504
+ var https = __require("node:https");
20505
+ var net = __require("node:net");
20506
+ var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
20507
+ var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
20508
+ var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
20509
+ var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
20510
+ var TIMEOUT_MS = 5e3;
20511
+ var MAX_RESPONSE_BYTES = 64 * 1024;
20512
+ var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
20513
+ var BLOCKED = (() => {
20514
+ const list = new net.BlockList();
20515
+ for (const [address, prefix] of [
20516
+ ["0.0.0.0", 8],
20517
+ ["10.0.0.0", 8],
20518
+ ["100.64.0.0", 10],
20519
+ ["127.0.0.0", 8],
20520
+ ["169.254.0.0", 16],
20521
+ ["172.16.0.0", 12],
20522
+ ["192.0.0.0", 24],
20523
+ ["192.0.2.0", 24],
20524
+ ["192.88.99.0", 24],
20525
+ ["192.168.0.0", 16],
20526
+ ["198.18.0.0", 15],
20527
+ ["198.51.100.0", 24],
20528
+ ["203.0.113.0", 24],
20529
+ ["224.0.0.0", 4],
20530
+ ["240.0.0.0", 4]
20531
+ ]) {
20532
+ list.addSubnet(address, prefix, "ipv4");
20533
+ }
20534
+ for (const [address, prefix] of [
20535
+ ["::", 128],
20536
+ ["::1", 128],
20537
+ // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
20538
+ // checks them against the IPv4 rules above, and a listed /96 would
20539
+ // match every IPv4 address.
20540
+ ["64:ff9b::", 96],
20541
+ ["64:ff9b:1::", 48],
20542
+ ["100::", 64],
20543
+ ["2001::", 23],
20544
+ ["2001:db8::", 32],
20545
+ ["2002::", 16],
20546
+ ["fc00::", 7],
20547
+ ["fe80::", 10],
20548
+ ["fec0::", 10],
20549
+ ["ff00::", 8]
20550
+ ]) {
20551
+ list.addSubnet(address, prefix, "ipv6");
20552
+ }
20553
+ return list;
20554
+ })();
20555
+ function isBlockedAddress(address) {
20556
+ let value = String(address || "").trim();
20557
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
20558
+ value = value.slice(7);
20559
+ }
20560
+ const version = net.isIP(value);
20561
+ if (version === 0) return true;
20562
+ return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
20563
+ }
20564
+ function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
20565
+ const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
20566
+ return `t=${timestamp},v1=${digest}`;
20567
+ }
20568
+ function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
20569
+ const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
20570
+ if (!match) return false;
20571
+ const timestamp = Number(match[1]);
20572
+ if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
20573
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
20574
+ const given = Buffer.from(match[2], "hex");
20575
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
20576
+ }
20577
+ var DeliveryError = class extends Error {
20578
+ /**
20579
+ * @param {string} code Stable code.
20580
+ * @param {boolean} retryable Whether another attempt may succeed.
20581
+ * @param {number|null} [status] HTTP status, when there was one.
20582
+ */
20583
+ constructor(code, retryable, status = null) {
20584
+ super(code);
20585
+ this.name = "DeliveryError";
20586
+ this.code = code;
20587
+ this.retryable = retryable;
20588
+ this.status = status;
20589
+ }
20590
+ };
20591
+ var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
20592
+ function httpsPost({ url, address, headers, body, timeoutMs }) {
20593
+ return new Promise((resolve, reject) => {
20594
+ const request = https.request(
20595
+ {
20596
+ protocol: "https:",
20597
+ hostname: url.hostname,
20598
+ port: url.port || 443,
20599
+ path: `${url.pathname}${url.search}`,
20600
+ method: "POST",
20601
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
20602
+ servername: net.isIP(url.hostname) ? void 0 : url.hostname,
20603
+ timeout: timeoutMs,
20604
+ // Pinned to the address that passed the check: no second lookup.
20605
+ lookup: (_hostname, options, callback) => {
20606
+ if (options && options.all) callback(null, [address]);
20607
+ else callback(null, address.address, address.family);
20608
+ }
20609
+ },
20610
+ (response) => {
20611
+ let received = 0;
20612
+ response.on("data", (chunk) => {
20613
+ received += chunk.length;
20614
+ if (received > MAX_RESPONSE_BYTES) response.destroy();
20615
+ });
20616
+ response.on("end", () => resolve(response.statusCode || 0));
20617
+ response.on("close", () => resolve(response.statusCode || 0));
20618
+ response.on("error", () => resolve(response.statusCode || 0));
20619
+ }
20620
+ );
20621
+ request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
20622
+ request.on(
20623
+ "error",
20624
+ (err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
20625
+ );
20626
+ request.end(body);
20627
+ });
20628
+ }
20629
+ async function deliverOnce({
20630
+ url,
20631
+ body,
20632
+ headers,
20633
+ resolve = resolveAll,
20634
+ post = httpsPost,
20635
+ timeoutMs = TIMEOUT_MS
20636
+ }) {
20637
+ let parsed;
20638
+ try {
20639
+ parsed = new URL(url);
20640
+ } catch {
20641
+ throw new DeliveryError("invalid_url", false);
20642
+ }
20643
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
20644
+ throw new DeliveryError("invalid_url", false);
20645
+ }
20646
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
20647
+ let addresses;
20648
+ if (net.isIP(host)) {
20649
+ addresses = [{ address: host, family: net.isIP(host) }];
20650
+ } else {
20651
+ try {
20652
+ addresses = await resolve(host);
20653
+ } catch {
20654
+ throw new DeliveryError("dns_failed", true);
20655
+ }
20656
+ }
20657
+ if (!Array.isArray(addresses) || addresses.length === 0)
20658
+ throw new DeliveryError("dns_failed", true);
20659
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
20660
+ throw new DeliveryError("address_not_allowed", false);
20661
+ }
20662
+ const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
20663
+ if (status >= 200 && status < 300) return { status };
20664
+ if (status >= 300 && status < 400)
20665
+ throw new DeliveryError("redirect_not_followed", false, status);
20666
+ throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
20667
+ }
20668
+ function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
20669
+ const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
20670
+ return {
20671
+ id,
20672
+ body,
20673
+ headers: {
20674
+ "Content-Type": "application/json",
20675
+ "User-Agent": USER_AGENT,
20676
+ [EVENT_HEADER]: event,
20677
+ [DELIVERY_HEADER]: id,
20678
+ [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
20679
+ }
20680
+ };
20681
+ }
20682
+ async function deliverWithRetries({
20683
+ delays = RETRY_DELAYS_MS,
20684
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
20685
+ ...request
20686
+ }) {
20687
+ let attempts = 0;
20688
+ let last = { ok: false, status: null, code: "not_sent" };
20689
+ for (const delay of delays) {
20690
+ if (delay > 0) await sleep(delay);
20691
+ attempts += 1;
20692
+ try {
20693
+ const { status } = await deliverOnce(request);
20694
+ return { ok: true, status, code: null, attempts };
20695
+ } catch (err) {
20696
+ const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
20697
+ last = { ok: false, status: error.status, code: error.code };
20698
+ if (!error.retryable) break;
20699
+ }
20700
+ }
20701
+ return { ...last, attempts };
20702
+ }
20703
+ module.exports = {
20704
+ DELIVERY_HEADER,
20705
+ DeliveryError,
20706
+ EVENT_HEADER,
20707
+ RETRY_DELAYS_MS,
20708
+ SIGNATURE_HEADER,
20709
+ buildSignedRequest,
20710
+ deliverOnce,
20711
+ deliverWithRetries,
20712
+ isBlockedAddress,
20713
+ signPayload,
20714
+ verifySignature
20715
+ };
20716
+ }
20717
+ });
20718
+
20719
+ // server/src/services/webhooks.js
20720
+ var require_webhooks2 = __commonJS({
20721
+ "server/src/services/webhooks.js"(exports, module) {
20722
+ "use strict";
20723
+ var { decryptToken } = require_encryption();
20724
+ var { getPluginSettings } = require_settings_loader();
20725
+ var { resolveDetectionSettings } = require_detection_settings();
20726
+ var { resolveSecurityLogSettings } = require_security_log_settings();
20727
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
20728
+ var { SECURITY_EVENTS } = require_security_log_model();
20729
+ var {
20730
+ buildSignedRequest,
20731
+ deliverOnce,
20732
+ deliverWithRetries
20733
+ } = require_webhook_delivery();
20734
+ var { createLogger } = require_logger();
20735
+ var EVENT_OF_SECURITY_EVENT = Object.freeze({
20736
+ [SECURITY_EVENTS.USER_SIGN_IN_FAILED]: "login.failed",
20737
+ [SECURITY_EVENTS.USER_SIGN_IN_REFUSED]: "login.refused",
20738
+ [SECURITY_EVENTS.USER_LOCKOUT]: "lockout",
20739
+ [SECURITY_EVENTS.USER_LOCKOUT_LIFTED]: "lockout.lifted",
20740
+ [SECURITY_EVENTS.USER_SESSION_LIMIT]: "session.limit",
20741
+ [SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED]: "password.changed",
20742
+ "user.sign-in.new-device": "login.new_device",
20743
+ "user.sign-in.impossible-travel": "login.impossible_travel",
20744
+ "user.not-me": "user.not_me"
20745
+ });
20746
+ var CHAT_TITLES = Object.freeze({
20747
+ "login.failed": "Failed sign-in",
20748
+ "login.refused": "Refused sign-in",
20749
+ "login.new_device": "Sign-in from a new device",
20750
+ "login.impossible_travel": "Impossible travel",
20751
+ lockout: "Sign-in locked",
20752
+ "lockout.lifted": "Sign-in lock lifted",
20753
+ "session.limit": "Session limit reached",
20754
+ "password.changed": "Other sessions ended after a password change",
20755
+ "user.not_me": "User reported a sign-in as not theirs",
20756
+ test: "Test message"
20757
+ });
20758
+ var MAX_PARALLEL = 4;
20759
+ var MAX_QUEUE = 500;
20760
+ module.exports = ({ strapi: strapi2 }) => {
20761
+ const log = createLogger(strapi2);
20762
+ const queue = [];
20763
+ let running = 0;
20764
+ let stopped = false;
20765
+ const pump = () => {
20766
+ while (!stopped && running < MAX_PARALLEL && queue.length) {
20767
+ const job = (
20768
+ /** @type {() => Promise<void>} */
20769
+ queue.shift()
20770
+ );
20771
+ running += 1;
20772
+ job().catch(() => {
20773
+ }).finally(() => {
20774
+ running -= 1;
20775
+ pump();
20776
+ });
20777
+ }
20778
+ };
20779
+ const enqueue = (job) => {
20780
+ if (stopped) return;
20781
+ if (queue.length >= MAX_QUEUE) {
20782
+ queue.shift();
20783
+ log.warn("[webhooks] Queue full; the oldest delivery was dropped");
20784
+ }
20785
+ queue.push(job);
20786
+ pump();
20787
+ };
20788
+ const secretOf = (settings) => {
20789
+ const stored = settings?.genericWebhookSecret;
20790
+ if (typeof stored !== "string" || !stored) return null;
20791
+ try {
20792
+ return decryptToken(stored) || null;
20793
+ } catch {
20794
+ return null;
20795
+ }
20796
+ };
20797
+ const dataOf = (settings, input) => {
20798
+ const options = resolveSecurityLogSettings(settings);
20799
+ const ip = options.storeIp ? normalizeIp(input.ip || "") : null;
20800
+ return {
20801
+ user: input.userId ? { documentId: String(input.userId) } : null,
20802
+ ip: ip && options.anonymizeIp ? anonymizeIp(ip) : ip,
20803
+ userAgent: typeof input.userAgent === "string" ? input.userAgent.slice(0, 256) : null,
20804
+ location: input.geo && (input.geo.country_code || input.geo.city) ? { country: input.geo.country_code || null, city: input.geo.city || null } : null,
20805
+ details: input.details || null
20806
+ };
20807
+ };
20808
+ const chatBody = (kind, event, data) => {
20809
+ const title = CHAT_TITLES[event] || event;
20810
+ const fields = [
20811
+ ["User", data.user?.documentId || "-"],
20812
+ ["IP", data.ip || "-"],
20813
+ ...Object.entries(data.details || {}).slice(0, 6).map(([key, value]) => [key, String(value)])
20814
+ ];
20815
+ if (kind === "discord") {
20816
+ return {
20817
+ embeds: [
20818
+ {
20819
+ title,
20820
+ color: 5793266,
20821
+ fields: fields.map(([name, value]) => ({
20822
+ name,
20823
+ value: value.slice(0, 200),
20824
+ inline: true
20825
+ })),
20826
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
20827
+ footer: { text: "Magic Session Manager" }
20828
+ }
20829
+ ]
20830
+ };
20831
+ }
20832
+ return {
20833
+ text: title,
20834
+ attachments: [
20835
+ {
20836
+ color: "#2563eb",
20837
+ blocks: [
20838
+ { type: "header", text: { type: "plain_text", text: title } },
20839
+ {
20840
+ type: "section",
20841
+ fields: fields.map(([name, value]) => ({
20842
+ type: "mrkdwn",
20843
+ text: `*${name}*
20844
+ ${value.slice(0, 200)}`
20845
+ }))
20846
+ }
20847
+ ]
20848
+ }
20849
+ ]
20850
+ };
20851
+ };
20852
+ const service = {
20853
+ EVENT_OF_SECURITY_EVENT,
20854
+ /**
20855
+ * Whether an event is selected.
20856
+ *
20857
+ * @param {Record<string, any>} settings Merged settings.
20858
+ * @param {string} event Webhook event.
20859
+ * @returns {boolean} True when selected.
20860
+ */
20861
+ isSelected(settings, event) {
20862
+ return resolveDetectionSettings(settings).webhookEvents.includes(event);
20863
+ },
20864
+ /**
20865
+ * Queues an event for the signed webhook and, for non-sign-in events,
20866
+ * Discord and Slack. Sign-in events (`login.success`, `login.suspicious`,
20867
+ * `login.new_location`) reach Discord and Slack through the login alerts
20868
+ * with their richer message. Returns at once.
20869
+ *
20870
+ * @param {string} event Webhook event.
20871
+ * @param {{userId?: string|null, ip?: string|null, userAgent?: string|null, geo?: any,
20872
+ * details?: Record<string, unknown>|null}} input Event facts.
20873
+ * @param {{chat?: boolean}} [options] Whether Discord/Slack get it here.
20874
+ * @returns {void}
20875
+ */
20876
+ emit(event, input, { chat = true } = {}) {
20877
+ enqueue(async () => {
20878
+ const settings = await getPluginSettings(strapi2);
20879
+ if (!service.isSelected(settings, event)) return;
20880
+ const data = dataOf(settings, input);
20881
+ const detection = resolveDetectionSettings(settings);
20882
+ const secret = secretOf(settings);
20883
+ if (detection.genericWebhookEnabled && detection.genericWebhookUrl && secret) {
20884
+ const request = buildSignedRequest({ event, data, secret });
20885
+ const result = await deliverWithRetries({ url: detection.genericWebhookUrl, ...request });
20886
+ if (!result.ok) {
20887
+ log.warn(
20888
+ `[webhooks] Signed webhook delivery failed (${result.code}, ${result.attempts} attempts)`
20889
+ );
20890
+ }
20891
+ }
20892
+ if (chat && settings.enableWebhooks) {
20893
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
20894
+ const targets = [
20895
+ ["discord", settings.discordWebhookUrl],
20896
+ ["slack", settings.slackWebhookUrl]
20897
+ ].filter(([, url]) => typeof url === "string" && url);
20898
+ await Promise.allSettled(
20899
+ targets.map(
20900
+ ([kind, url]) => notifications.sendWebhook({
20901
+ event,
20902
+ data: chatBody(kind, event, data),
20903
+ webhookUrl: url
20904
+ })
20905
+ )
20906
+ );
20907
+ }
20908
+ });
20909
+ },
20910
+ /**
20911
+ * Emits the webhook event that belongs to a security log event, if any.
20912
+ *
20913
+ * @param {{event: string, actorType?: string, actorId?: any, targetId?: any, ip?: any,
20914
+ * userAgent?: any, meta?: any}} input Security event input.
20915
+ * @returns {void}
20916
+ */
20917
+ emitSecurityEvent(input) {
20918
+ const event = EVENT_OF_SECURITY_EVENT[input?.event];
20919
+ if (!event) return;
20920
+ service.emit(event, {
20921
+ userId: input.targetId || (input.actorType === "user" ? input.actorId : null) || null,
20922
+ // An admin's own address is not sent for admin actions.
20923
+ ip: input.actorType === "admin" ? null : input.ip,
20924
+ userAgent: input.actorType === "admin" ? null : input.userAgent,
20925
+ details: input.meta || null
20926
+ });
20927
+ },
20928
+ /**
20929
+ * Sends one `test` event to the signed webhook now, without retries.
20930
+ *
20931
+ * @returns {Promise<{ok: boolean, status: number|null, code: string|null}>} Result.
20932
+ */
20933
+ async sendTest() {
20934
+ const settings = await getPluginSettings(strapi2);
20935
+ const detection = resolveDetectionSettings(settings);
20936
+ const secret = secretOf(settings);
20937
+ if (!detection.genericWebhookUrl) return { ok: false, status: null, code: "no_url" };
20938
+ if (!secret) return { ok: false, status: null, code: "no_secret" };
20939
+ const request = buildSignedRequest({
20940
+ event: "test",
20941
+ data: { user: null, ip: null, userAgent: null, location: null, details: { test: true } },
20942
+ secret
20943
+ });
20944
+ try {
20945
+ const { status } = await deliverOnce({ url: detection.genericWebhookUrl, ...request });
20946
+ return { ok: true, status, code: null };
20947
+ } catch (err) {
20948
+ return {
20949
+ ok: false,
20950
+ status: Number.isInteger(err?.status) ? err.status : null,
20951
+ code: typeof err?.code === "string" ? err.code : "network_error"
20952
+ };
20953
+ }
20954
+ },
20955
+ /**
20956
+ * Stops new deliveries (plugin destroy).
20957
+ *
20958
+ * @returns {void}
20959
+ */
20960
+ stop() {
20961
+ stopped = true;
20962
+ queue.length = 0;
20963
+ }
20964
+ };
20965
+ return service;
20966
+ };
20967
+ }
20968
+ });
20969
+
17871
20970
  // server/src/services/index.js
17872
20971
  var require_services = __commonJS({
17873
20972
  "server/src/services/index.js"(exports, module) {
@@ -17876,11 +20975,13 @@ var require_services = __commonJS({
17876
20975
  var geolocation = require_geolocation();
17877
20976
  var notifications = require_notifications();
17878
20977
  var securityLog = require_security_log();
20978
+ var webhooks = require_webhooks2();
17879
20979
  module.exports = {
17880
20980
  session,
17881
20981
  geolocation,
17882
20982
  notifications,
17883
- "security-log": securityLog
20983
+ "security-log": securityLog,
20984
+ webhooks
17884
20985
  };
17885
20986
  }
17886
20987
  });