strapi-plugin-magic-sessionmanager 4.16.1 → 4.17.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 +41 -0
  2. package/README.md +49 -15
  3. package/dist/admin/{Analytics-FcRt0X62.mjs → Analytics-B-p2Q7th.mjs} +1 -1
  4. package/dist/admin/{Analytics-CMR62DiD.js → Analytics-BTIByTUY.js} +1 -1
  5. package/dist/admin/{App-CmytGbze.js → App-CH6635JB.js} +33 -170
  6. package/dist/admin/{App-DBieSWB0.mjs → App-DmesuM2g.mjs} +3 -140
  7. package/dist/admin/{OnlineUsersWidget-zP9Hl_it.mjs → OnlineUsersWidget-CuqeQ0tb.mjs} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Lzx9XB74.js → OnlineUsersWidget-TlOp8nie.js} +1 -1
  9. package/dist/admin/{Settings-CZOPusQK.mjs → Settings-C4IgGBjQ.mjs} +1163 -56
  10. package/dist/admin/{Settings-1v--SXC0.js → Settings-DtP_H4JS.js} +1167 -60
  11. package/dist/admin/dashboardModel-0ROcWcB1.mjs +189 -0
  12. package/dist/admin/dashboardModel-BSJhZdXI.js +188 -0
  13. package/dist/admin/{de-D3TSA066.mjs → de-BoahnYIP.mjs} +110 -9
  14. package/dist/admin/{de-y_9mdVT7.js → de-C_ooq6EF.js} +110 -9
  15. package/dist/admin/{en-CIQB8nfI.js → en-CuUVE2K0.js} +110 -9
  16. package/dist/admin/{en-B60I97bK.mjs → en-DHme92L-.mjs} +110 -9
  17. package/dist/admin/{es-CJEL_iGC.mjs → es-CjcTgS9Z.mjs} +110 -9
  18. package/dist/admin/{es-DHhHzlRY.js → es-lbDNXcQi.js} +110 -9
  19. package/dist/admin/{fr-BfBK_iuV.mjs → fr-BPwnrSaC.mjs} +110 -9
  20. package/dist/admin/{fr-D86FTt1w.js → fr-RtypjgGp.js} +110 -9
  21. package/dist/admin/{index-tt61o2VH.mjs → index-B102RF2H.mjs} +40 -38
  22. package/dist/admin/{index-CSJJn4qy.js → index-w0OuPYFm.js} +12 -10
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +1 -1
  25. package/dist/admin/{pt-BE-FT-L8.js → pt-BMCAKRQ4.js} +110 -9
  26. package/dist/admin/{pt-C3PSvC7z.mjs → pt-D5FHSP2y.mjs} +110 -9
  27. package/dist/server/index.js +1519 -78
  28. package/dist/server/index.mjs +1519 -78
  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,28 @@ 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
+ },
237
261
  async prune(now = Date.now()) {
238
262
  let removed = 0;
263
+ for (const [k, v] of registry) {
264
+ if (v.expiresAt <= now) registry.delete(k);
265
+ }
239
266
  for (const [k, v] of counters) {
240
267
  if (v.expiresAt <= now && v.blockedUntil <= now) {
241
268
  counters.delete(k);
@@ -249,6 +276,7 @@ var require_coordination = __commonJS({
249
276
  leases.clear();
250
277
  revisions.clear();
251
278
  lockTails.clear();
279
+ registry.clear();
252
280
  }
253
281
  };
254
282
  }
@@ -390,14 +418,18 @@ var require_coordination = __commonJS({
390
418
  await knex(TABLES.counters).where({ k: key }).andWhere("hits", ">", 0).update({ hits: knex.raw("hits - 1") });
391
419
  },
392
420
  peek: readCounter,
393
- async block(key, untilMs) {
421
+ async block(key, untilMs, { windowStart } = {}) {
394
422
  await ensureCounterRow(key, untilMs);
395
423
  await knex(TABLES.counters).where({ k: key }).andWhere("blocked_until", "<", untilMs).update({
396
424
  blocked_until: untilMs,
397
425
  expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
398
426
  untilMs,
399
427
  untilMs
400
- ])
428
+ ]),
429
+ // Moves the counting window so it ends when the lock ends: the
430
+ // hits stay (requests already in flight are still turned away),
431
+ // and the first attempt after the lock starts a new window.
432
+ ...Number.isFinite(windowStart) ? { window_start: Math.trunc(windowStart) } : {}
401
433
  });
402
434
  },
403
435
  async clear(key) {
@@ -475,6 +507,27 @@ var require_coordination = __commonJS({
475
507
  const expiresAt = ttlMs === Infinity ? NEVER_EXPIRES : now + ttlMs;
476
508
  await knex(TABLES.cache).insert({ k: key, v: JSON.stringify(value), expires_at: expiresAt }).onConflict("k").merge(["v", "expires_at"]);
477
509
  },
510
+ /**
511
+ * Listable entries live in the cache table under their own key prefix
512
+ * (`reg:`), so they share its expiry index and pruning.
513
+ */
514
+ async registryPut(key, value, ttlMs, now = Date.now()) {
515
+ await knex(TABLES.cache).insert({ k: `reg:${key}`, v: JSON.stringify(value), expires_at: now + ttlMs }).onConflict("k").merge(["v", "expires_at"]);
516
+ },
517
+ async registryList(prefix, limit = 200, now = Date.now()) {
518
+ const rows = await knex(TABLES.cache).select("k", "v").where("k", "like", `reg:${prefix}%`).andWhere("expires_at", ">", now).orderBy("k", "asc").limit(limit);
519
+ const out = [];
520
+ for (const row of rows) {
521
+ try {
522
+ out.push({ key: String(row.k).slice(4), value: JSON.parse(row.v) });
523
+ } catch {
524
+ }
525
+ }
526
+ return out;
527
+ },
528
+ async registryDelete(key) {
529
+ await knex(TABLES.cache).where({ k: `reg:${key}` }).del();
530
+ },
478
531
  async prune(now = Date.now()) {
479
532
  const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
480
533
  const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
@@ -555,10 +608,17 @@ var require_coordination = __commonJS({
555
608
  assertKey(key);
556
609
  return counterCall("counter read", "peek", [key]);
557
610
  },
558
- /** Raises the block deadline of `key` to `untilMs` (never lowers it). */
559
- block(key, untilMs) {
611
+ /**
612
+ * Raises the block deadline of `key` to `untilMs` (never lowers it).
613
+ * With `windowStart` the counting window is moved (see the lockout).
614
+ */
615
+ block(key, untilMs, options) {
560
616
  assertKey(key);
561
- return counterCall("counter block", "block", [key, untilMs]);
617
+ return counterCall(
618
+ "counter block",
619
+ "block",
620
+ options ? [key, untilMs, options] : [key, untilMs]
621
+ );
562
622
  },
563
623
  /** Removes counter `key`. */
564
624
  clear(key) {
@@ -658,6 +718,51 @@ var require_coordination = __commonJS({
658
718
  () => sharedMemory.cacheSet(key, value, ttlMs)
659
719
  );
660
720
  },
721
+ /**
722
+ * Stores a listable entry (for example an active sign-in lock) until
723
+ * `ttlMs` from now. Unlike the cache it also works in memory mode, and
724
+ * entries can be listed by key prefix. Keys use lowercase letters,
725
+ * digits, `:` and `-` only, so they are free of LIKE wildcards.
726
+ *
727
+ * @param {string} key Entry key (at most 180 characters).
728
+ * @param {unknown} value JSON-serialisable value.
729
+ * @param {number} ttlMs Lifetime in milliseconds.
730
+ * @returns {Promise<void>}
731
+ */
732
+ registryPut(key, value, ttlMs) {
733
+ assertRegistryKey(key);
734
+ return run(
735
+ "registry write",
736
+ (backend) => backend.registryPut(key, value, ttlMs),
737
+ () => sharedMemory.registryPut(key, value, ttlMs)
738
+ );
739
+ },
740
+ /**
741
+ * Unexpired entries whose key starts with `prefix`, ordered by key.
742
+ *
743
+ * @param {string} prefix Key prefix (letters, digits, `:` and `-` only).
744
+ * @param {number} [limit] Most entries returned.
745
+ * @returns {Promise<Array<{key: string, value: any}>>}
746
+ */
747
+ registryList(prefix, limit = 200) {
748
+ if (typeof prefix !== "string" || !/^[a-z0-9:-]{1,180}$/.test(prefix)) {
749
+ throw new TypeError('registry prefix must be letters, digits, ":" or "-"');
750
+ }
751
+ return run(
752
+ "registry read",
753
+ (backend) => backend.registryList(prefix, limit),
754
+ () => sharedMemory.registryList(prefix, limit)
755
+ );
756
+ },
757
+ /** Removes a listable entry. */
758
+ registryDelete(key) {
759
+ assertRegistryKey(key);
760
+ return run(
761
+ "registry delete",
762
+ (backend) => backend.registryDelete(key),
763
+ () => sharedMemory.registryDelete(key)
764
+ );
765
+ },
661
766
  prune() {
662
767
  return run(
663
768
  "prune",
@@ -990,11 +1095,359 @@ var require_security_log_settings = __commonJS({
990
1095
  }
991
1096
  });
992
1097
 
1098
+ // server/src/utils/policy-settings.js
1099
+ var require_policy_settings = __commonJS({
1100
+ "server/src/utils/policy-settings.js"(exports, module) {
1101
+ "use strict";
1102
+ var net = __require("node:net");
1103
+ var POLICY_DEFAULTS = Object.freeze({
1104
+ maxFailedLoginsPerAccount: 0,
1105
+ lockoutWindowMinutes: 15,
1106
+ lockoutDurationMinutes: 15,
1107
+ lockoutTrustedAddresses: Object.freeze([]),
1108
+ lockoutNotifyUser: false,
1109
+ recordUserSignInEvents: true,
1110
+ maxSessionsPerUser: 0,
1111
+ sessionLimitPolicy: "end-oldest",
1112
+ endOtherSessionsOnPasswordChange: true,
1113
+ roleRules: Object.freeze([])
1114
+ });
1115
+ var POLICY_KEYS = Object.freeze(Object.keys(POLICY_DEFAULTS));
1116
+ var POLICY_RANGES = Object.freeze({
1117
+ maxFailedLoginsPerAccount: Object.freeze([0, 100]),
1118
+ lockoutWindowMinutes: Object.freeze([1, 1440]),
1119
+ lockoutDurationMinutes: Object.freeze([1, 10080]),
1120
+ maxSessionsPerUser: Object.freeze([0, 100])
1121
+ });
1122
+ var ROLE_RULE_RANGES = Object.freeze({
1123
+ maxSessionsPerUser: Object.freeze([0, 100]),
1124
+ inactivityTimeout: Object.freeze([1, 1440]),
1125
+ maxFailedLoginsPerAccount: Object.freeze([0, 100])
1126
+ });
1127
+ var ROLE_RULE_FIELDS = Object.freeze(Object.keys(ROLE_RULE_RANGES));
1128
+ var SESSION_LIMIT_POLICIES = Object.freeze(["end-oldest", "refuse"]);
1129
+ var BOOLEAN_KEYS = Object.freeze([
1130
+ "lockoutNotifyUser",
1131
+ "recordUserSignInEvents",
1132
+ "endOtherSessionsOnPasswordChange"
1133
+ ]);
1134
+ var MAX_TRUSTED_ADDRESSES = 100;
1135
+ var MAX_ROLE_RULES = 50;
1136
+ var ROLE_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1137
+ function parseInteger(value) {
1138
+ if (typeof value === "number") return Number.isInteger(value) ? value : null;
1139
+ if (typeof value === "string" && /^\s*-?\d{1,9}\s*$/.test(value)) {
1140
+ return Number.parseInt(value, 10);
1141
+ }
1142
+ return null;
1143
+ }
1144
+ function parseTrustedAddress(value) {
1145
+ if (typeof value !== "string") return null;
1146
+ const text = value.trim();
1147
+ if (!text || text.length > 64) return null;
1148
+ const [rawAddress, rawPrefix, extra] = text.split("/");
1149
+ if (extra !== void 0) return null;
1150
+ let address = rawAddress;
1151
+ if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
1152
+ address = address.slice(7);
1153
+ }
1154
+ const version = net.isIP(address);
1155
+ if (version === 0) return null;
1156
+ const family = version === 4 ? "ipv4" : "ipv6";
1157
+ if (rawPrefix === void 0) {
1158
+ return { text: address.toLowerCase(), address, prefix: null, family };
1159
+ }
1160
+ if (!/^\d{1,3}$/.test(rawPrefix)) return null;
1161
+ const prefix = Number(rawPrefix);
1162
+ if (prefix > (family === "ipv4" ? 32 : 128)) return null;
1163
+ return { text: `${address.toLowerCase()}/${prefix}`, address, prefix, family };
1164
+ }
1165
+ var blockListCache = /* @__PURE__ */ new Map();
1166
+ function trustedAddressList(entries) {
1167
+ const key = entries.join("\n");
1168
+ const cached = blockListCache.get(key);
1169
+ if (cached) return cached;
1170
+ const list = new net.BlockList();
1171
+ for (const entry of entries) {
1172
+ const parsed = parseTrustedAddress(entry);
1173
+ if (!parsed) continue;
1174
+ if (parsed.prefix === null) list.addAddress(parsed.address, parsed.family);
1175
+ else list.addSubnet(parsed.address, parsed.prefix, parsed.family);
1176
+ }
1177
+ if (blockListCache.size > 20) blockListCache.clear();
1178
+ blockListCache.set(key, list);
1179
+ return list;
1180
+ }
1181
+ function isTrustedAddress(entries, ip) {
1182
+ if (!entries.length || typeof ip !== "string") return false;
1183
+ let address = ip.trim();
1184
+ if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
1185
+ address = address.slice(7);
1186
+ }
1187
+ const version = net.isIP(address);
1188
+ if (version === 0) return false;
1189
+ try {
1190
+ return trustedAddressList(entries).check(address, version === 4 ? "ipv4" : "ipv6");
1191
+ } catch {
1192
+ return false;
1193
+ }
1194
+ }
1195
+ function normalizeRoleRules(value) {
1196
+ if (!Array.isArray(value)) return [];
1197
+ const seen = /* @__PURE__ */ new Set();
1198
+ const out = [];
1199
+ for (const raw of value.slice(0, MAX_ROLE_RULES)) {
1200
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
1201
+ const role = typeof raw.role === "string" ? raw.role : "";
1202
+ if (!ROLE_ID_PATTERN.test(role) || seen.has(role)) continue;
1203
+ const rule = { role };
1204
+ for (const field of ROLE_RULE_FIELDS) {
1205
+ const [min, max] = (
1206
+ /** @type {any} */
1207
+ ROLE_RULE_RANGES[field]
1208
+ );
1209
+ const number = raw[field] === null || raw[field] === void 0 ? null : parseInteger(raw[field]);
1210
+ rule[field] = number !== null && number >= min && number <= max ? number : null;
1211
+ }
1212
+ seen.add(role);
1213
+ out.push(rule);
1214
+ }
1215
+ return out;
1216
+ }
1217
+ function normalizePolicySettings(stored) {
1218
+ const out = {};
1219
+ if (!stored || typeof stored !== "object") return out;
1220
+ for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
1221
+ if (stored[key] === void 0) continue;
1222
+ const number = parseInteger(stored[key]);
1223
+ out[key] = number !== null && number >= min && number <= max ? number : (
1224
+ /** @type {any} */
1225
+ POLICY_DEFAULTS[key]
1226
+ );
1227
+ }
1228
+ for (const key of BOOLEAN_KEYS) {
1229
+ if (stored[key] !== void 0) out[key] = stored[key] === true;
1230
+ }
1231
+ if (stored.sessionLimitPolicy !== void 0) {
1232
+ out.sessionLimitPolicy = SESSION_LIMIT_POLICIES.includes(
1233
+ /** @type {string} */
1234
+ stored.sessionLimitPolicy
1235
+ ) ? stored.sessionLimitPolicy : POLICY_DEFAULTS.sessionLimitPolicy;
1236
+ }
1237
+ if (stored.lockoutTrustedAddresses !== void 0) {
1238
+ out.lockoutTrustedAddresses = Array.isArray(stored.lockoutTrustedAddresses) ? stored.lockoutTrustedAddresses.slice(0, MAX_TRUSTED_ADDRESSES).map(parseTrustedAddress).filter(Boolean).map((entry) => (
1239
+ /** @type {any} */
1240
+ entry.text
1241
+ )) : [];
1242
+ }
1243
+ if (stored.roleRules !== void 0) out.roleRules = normalizeRoleRules(stored.roleRules);
1244
+ return out;
1245
+ }
1246
+ function validatePolicySettings(body) {
1247
+ const values = {};
1248
+ const errors = [];
1249
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
1250
+ for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
1251
+ if (!has(key)) continue;
1252
+ const number = parseInteger(body[key]);
1253
+ if (number === null || number < min || number > max) {
1254
+ errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
1255
+ } else {
1256
+ values[key] = number;
1257
+ }
1258
+ }
1259
+ for (const key of BOOLEAN_KEYS) {
1260
+ if (!has(key)) continue;
1261
+ if (typeof body[key] !== "boolean") {
1262
+ errors.push({ path: [key], message: `${key} must be a boolean` });
1263
+ } else {
1264
+ values[key] = body[key];
1265
+ }
1266
+ }
1267
+ if (has("sessionLimitPolicy")) {
1268
+ if (!SESSION_LIMIT_POLICIES.includes(
1269
+ /** @type {string} */
1270
+ body.sessionLimitPolicy
1271
+ )) {
1272
+ errors.push({
1273
+ path: ["sessionLimitPolicy"],
1274
+ message: `sessionLimitPolicy must be one of: ${SESSION_LIMIT_POLICIES.join(", ")}`
1275
+ });
1276
+ } else {
1277
+ values.sessionLimitPolicy = body.sessionLimitPolicy;
1278
+ }
1279
+ }
1280
+ if (has("lockoutTrustedAddresses")) {
1281
+ const list = body.lockoutTrustedAddresses;
1282
+ if (!Array.isArray(list) || list.length > MAX_TRUSTED_ADDRESSES) {
1283
+ errors.push({
1284
+ path: ["lockoutTrustedAddresses"],
1285
+ message: `lockoutTrustedAddresses must be a list of at most ${MAX_TRUSTED_ADDRESSES} IP addresses or CIDR ranges`
1286
+ });
1287
+ } else {
1288
+ const parsed = list.map(parseTrustedAddress);
1289
+ const invalid = parsed.findIndex((entry) => entry === null);
1290
+ if (invalid !== -1) {
1291
+ errors.push({
1292
+ path: ["lockoutTrustedAddresses", invalid],
1293
+ message: "Each trusted address must be an IP address or a CIDR range such as 192.0.2.0/24"
1294
+ });
1295
+ } else {
1296
+ values.lockoutTrustedAddresses = [
1297
+ ...new Set(parsed.map((entry) => (
1298
+ /** @type {any} */
1299
+ entry.text
1300
+ )))
1301
+ ];
1302
+ }
1303
+ }
1304
+ }
1305
+ if (has("roleRules")) {
1306
+ const rules = body.roleRules;
1307
+ if (!Array.isArray(rules) || rules.length > MAX_ROLE_RULES) {
1308
+ errors.push({
1309
+ path: ["roleRules"],
1310
+ message: `roleRules must be a list of at most ${MAX_ROLE_RULES} rules`
1311
+ });
1312
+ } else {
1313
+ const seen = /* @__PURE__ */ new Set();
1314
+ const clean = [];
1315
+ rules.forEach((raw, index) => {
1316
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1317
+ errors.push({ path: ["roleRules", index], message: "A role rule must be an object" });
1318
+ return;
1319
+ }
1320
+ const role = raw.role;
1321
+ if (typeof role !== "string" || !ROLE_ID_PATTERN.test(role)) {
1322
+ errors.push({ path: ["roleRules", index, "role"], message: "Choose a role" });
1323
+ return;
1324
+ }
1325
+ if (seen.has(role)) {
1326
+ errors.push({
1327
+ path: ["roleRules", index, "role"],
1328
+ message: "This role already has a rule"
1329
+ });
1330
+ return;
1331
+ }
1332
+ seen.add(role);
1333
+ const rule = { role };
1334
+ let overrides = 0;
1335
+ for (const field of ROLE_RULE_FIELDS) {
1336
+ const [min, max] = (
1337
+ /** @type {any} */
1338
+ ROLE_RULE_RANGES[field]
1339
+ );
1340
+ const rawValue = raw[field];
1341
+ if (rawValue === null || rawValue === void 0 || rawValue === "") {
1342
+ rule[field] = null;
1343
+ continue;
1344
+ }
1345
+ const number = parseInteger(rawValue);
1346
+ if (number === null || number < min || number > max) {
1347
+ errors.push({
1348
+ path: ["roleRules", index, field],
1349
+ message: `${field} must be empty or an integer between ${min} and ${max}`
1350
+ });
1351
+ continue;
1352
+ }
1353
+ rule[field] = number;
1354
+ overrides += 1;
1355
+ }
1356
+ if (overrides === 0 && !errors.some((e) => e.path[1] === index)) {
1357
+ errors.push({
1358
+ path: ["roleRules", index],
1359
+ message: "A role rule needs at least one value"
1360
+ });
1361
+ return;
1362
+ }
1363
+ clean.push(rule);
1364
+ });
1365
+ if (!errors.some((e) => e.path[0] === "roleRules")) values.roleRules = clean;
1366
+ }
1367
+ }
1368
+ return { values, errors };
1369
+ }
1370
+ function policyValue(settings, key) {
1371
+ const source = settings && typeof settings === "object" ? settings : {};
1372
+ const clean = normalizePolicySettings({ [key]: source[key] });
1373
+ return clean[key] !== void 0 ? clean[key] : POLICY_DEFAULTS[key];
1374
+ }
1375
+ function roleRuleFor(settings, roleDocumentId) {
1376
+ if (!roleDocumentId) return null;
1377
+ const rules = (
1378
+ /** @type {any[]} */
1379
+ policyValue(settings, "roleRules")
1380
+ );
1381
+ return rules.find((rule) => rule.role === roleDocumentId) || null;
1382
+ }
1383
+ function hasRoleOverride(settings, field) {
1384
+ const rules = (
1385
+ /** @type {any[]} */
1386
+ policyValue(settings, "roleRules")
1387
+ );
1388
+ return rules.some((rule) => rule[field] !== null && rule[field] !== void 0);
1389
+ }
1390
+ function resolveLockoutPolicy(settings) {
1391
+ const source = settings && typeof settings === "object" ? settings : {};
1392
+ const ipRaw = parseInteger(source.maxFailedLogins);
1393
+ return {
1394
+ ipMax: ipRaw !== null && ipRaw >= 0 && ipRaw <= 100 ? ipRaw : 0,
1395
+ accountMax: policyValue(source, "maxFailedLoginsPerAccount"),
1396
+ accountMaxByRole: hasRoleOverride(source, "maxFailedLoginsPerAccount"),
1397
+ windowMs: policyValue(source, "lockoutWindowMinutes") * 60 * 1e3,
1398
+ durationMs: policyValue(source, "lockoutDurationMinutes") * 60 * 1e3,
1399
+ trusted: policyValue(source, "lockoutTrustedAddresses"),
1400
+ notifyUser: policyValue(source, "lockoutNotifyUser"),
1401
+ record: policyValue(source, "recordUserSignInEvents")
1402
+ };
1403
+ }
1404
+ function accountThresholdFor(settings, roleDocumentId) {
1405
+ const rule = roleRuleFor(settings, roleDocumentId);
1406
+ if (rule && rule.maxFailedLoginsPerAccount !== null) return rule.maxFailedLoginsPerAccount;
1407
+ return policyValue(settings, "maxFailedLoginsPerAccount");
1408
+ }
1409
+ function sessionLimitFor(settings, roleDocumentId) {
1410
+ const rule = roleRuleFor(settings, roleDocumentId);
1411
+ const limit = rule && rule.maxSessionsPerUser !== null ? rule.maxSessionsPerUser : policyValue(settings, "maxSessionsPerUser");
1412
+ return { limit, policy: policyValue(settings, "sessionLimitPolicy") };
1413
+ }
1414
+ function inactivityTimeoutFor(settings, roleDocumentId) {
1415
+ const rule = roleRuleFor(settings, roleDocumentId);
1416
+ if (rule && rule.inactivityTimeout !== null) return rule.inactivityTimeout * 60 * 1e3;
1417
+ const general = Number(settings?.inactivityTimeout);
1418
+ return Number.isFinite(general) && general > 0 ? general : 15 * 60 * 1e3;
1419
+ }
1420
+ module.exports = {
1421
+ POLICY_DEFAULTS,
1422
+ POLICY_KEYS,
1423
+ POLICY_RANGES,
1424
+ ROLE_RULE_FIELDS,
1425
+ ROLE_RULE_RANGES,
1426
+ SESSION_LIMIT_POLICIES,
1427
+ MAX_ROLE_RULES,
1428
+ MAX_TRUSTED_ADDRESSES,
1429
+ accountThresholdFor,
1430
+ hasRoleOverride,
1431
+ inactivityTimeoutFor,
1432
+ isTrustedAddress,
1433
+ normalizePolicySettings,
1434
+ normalizeRoleRules,
1435
+ parseTrustedAddress,
1436
+ policyValue,
1437
+ resolveLockoutPolicy,
1438
+ roleRuleFor,
1439
+ sessionLimitFor,
1440
+ validatePolicySettings
1441
+ };
1442
+ }
1443
+ });
1444
+
993
1445
  // server/src/utils/settings-loader.js
994
1446
  var require_settings_loader = __commonJS({
995
1447
  "server/src/utils/settings-loader.js"(exports, module) {
996
1448
  "use strict";
997
1449
  var { getCoordinator } = require_coordination();
1450
+ var { normalizePolicySettings } = require_policy_settings();
998
1451
  var PLUGIN_ID = "magic-sessionmanager";
999
1452
  var SETTINGS_KEY = "settings";
1000
1453
  var CACHE_TTL_MS = 30 * 1e3;
@@ -1126,6 +1579,7 @@ var require_settings_loader = __commonJS({
1126
1579
  if (stored.trustedProxies !== void 0) {
1127
1580
  out.trustedProxies = stored.trustedProxies;
1128
1581
  }
1582
+ Object.assign(out, normalizePolicySettings(stored));
1129
1583
  return out;
1130
1584
  }
1131
1585
  async function getPluginSettings(strapi2) {
@@ -1236,7 +1690,14 @@ var require_security_log_model = __commonJS({
1236
1690
  // 4.17: always recorded (no switch), never values.
1237
1691
  SETTINGS_UPDATED: "settings.updated",
1238
1692
  LOG_RETENTION_PURGED: "security-log.retention.purged",
1239
- LOG_READ: "security-log.read"
1693
+ LOG_READ: "security-log.read",
1694
+ // App users (Users & Permissions), 4.17.
1695
+ USER_SIGN_IN_FAILED: "user.sign-in.failed",
1696
+ USER_SIGN_IN_REFUSED: "user.sign-in.refused",
1697
+ USER_LOCKOUT: "user.lockout",
1698
+ USER_LOCKOUT_LIFTED: "user.lockout.lifted",
1699
+ USER_SESSION_LIMIT: "user.session.limit",
1700
+ USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others"
1240
1701
  });
1241
1702
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
1242
1703
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
@@ -1244,7 +1705,7 @@ var require_security_log_model = __commonJS({
1244
1705
  SECURITY_EVENTS.LOG_READ
1245
1706
  ]);
1246
1707
  function dropRankOf(event) {
1247
- if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
1708
+ if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
1248
1709
  return { rank: 0, family: "failed" };
1249
1710
  }
1250
1711
  if (event === SECURITY_EVENTS.ADMIN_CONTENT_VIEW) return { rank: 1, family: "content-view" };
@@ -1253,6 +1714,19 @@ var require_security_log_model = __commonJS({
1253
1714
  }
1254
1715
  return { rank: 3, family: "account" };
1255
1716
  }
1717
+ var USER_SIGN_IN_EVENTS = Object.freeze([
1718
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
1719
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
1720
+ SECURITY_EVENTS.USER_LOCKOUT
1721
+ ]);
1722
+ var REFUSAL_REASONS = Object.freeze([
1723
+ "lockout",
1724
+ "too-many-attempts",
1725
+ "session-limit",
1726
+ "country",
1727
+ "risk",
1728
+ "location-unavailable"
1729
+ ]);
1256
1730
  var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
1257
1731
  var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
1258
1732
  var ADMIN_SIGN_IN_EVENTS = Object.freeze([
@@ -1283,6 +1757,7 @@ var require_security_log_model = __commonJS({
1283
1757
  function recordingSwitchOf(event) {
1284
1758
  if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
1285
1759
  if (event.startsWith("admin.content.")) return "content";
1760
+ if (USER_SIGN_IN_EVENTS.includes(event)) return "userSignIns";
1286
1761
  return "always";
1287
1762
  }
1288
1763
  var CONTENT_MANAGER_HANDLERS = Object.freeze({
@@ -1463,6 +1938,8 @@ var require_security_log_model = __commonJS({
1463
1938
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1464
1939
  }
1465
1940
  module.exports = {
1941
+ REFUSAL_REASONS,
1942
+ USER_SIGN_IN_EVENTS,
1466
1943
  ACTOR_TYPES,
1467
1944
  ADMIN_CONTENT_EVENTS,
1468
1945
  ADMIN_SIGN_IN_EVENTS,
@@ -1721,10 +2198,19 @@ var require_register = __commonJS({
1721
2198
  // secrets) and the security log. The other settings stay on `access`.
1722
2199
  {
1723
2200
  section: "plugins",
1724
- displayName: "Change protected settings (location lookup, webhooks, security log)",
2201
+ displayName: "Change protected settings (location lookup, webhooks, security log, sign-in policies)",
1725
2202
  uid: "settings.update",
1726
2203
  subCategory: "Settings",
1727
2204
  pluginName: "magic-sessionmanager"
2205
+ },
2206
+ // Lifting a sign-in lock of an app user or IP address (4.17). Seeing the
2207
+ // locks only needs plugin access.
2208
+ {
2209
+ section: "plugins",
2210
+ displayName: "Unlock locked sign-ins",
2211
+ uid: "lockouts.unlock",
2212
+ subCategory: "General",
2213
+ pluginName: "magic-sessionmanager"
1728
2214
  }
1729
2215
  ]);
1730
2216
  disableGraphqlShadowCrud(strapi2, log);
@@ -1775,6 +2261,20 @@ var require_register = __commonJS({
1775
2261
  } catch (err) {
1776
2262
  log.warn("[lifecycle] afterUpdate hook failed:", err?.name || "Error");
1777
2263
  }
2264
+ },
2265
+ /**
2266
+ * Deleting an app user deletes what the security log holds about them.
2267
+ *
2268
+ * @param {object} event
2269
+ */
2270
+ async afterDelete(event) {
2271
+ try {
2272
+ const documentId = event?.result?.documentId;
2273
+ if (!documentId) return;
2274
+ await strapi2.plugin("magic-sessionmanager").service("security-log").deleteUserData(documentId);
2275
+ } catch (err) {
2276
+ log.warn("[lifecycle] Security events of a deleted user stay:", err?.name || "Error");
2277
+ }
1778
2278
  }
1779
2279
  });
1780
2280
  log.info("[SUCCESS] Plugin registered successfully");
@@ -3514,6 +4014,425 @@ var require_admin_activity_capture = __commonJS({
3514
4014
  }
3515
4015
  });
3516
4016
 
4017
+ // server/src/utils/login-lockout.js
4018
+ var require_login_lockout = __commonJS({
4019
+ "server/src/utils/login-lockout.js"(exports, module) {
4020
+ "use strict";
4021
+ var { hashedKey } = require_coordination();
4022
+ var { isTrustedAddress } = require_policy_settings();
4023
+ var LOCK_PREFIX = "lock:";
4024
+ var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
4025
+ var MAX_LISTED_LOCKS = 200;
4026
+ function normalizeIdentifier(identifier) {
4027
+ if (typeof identifier !== "string") return null;
4028
+ const value = identifier.trim().toLowerCase();
4029
+ if (!value || value.length > 254) return null;
4030
+ return value;
4031
+ }
4032
+ var ipKey = (ip) => hashedKey("lf", ip);
4033
+ var accountKey = (identifier) => hashedKey("la", identifier);
4034
+ function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
4035
+ const remainingSeconds = async (key) => {
4036
+ if (!key) return 0;
4037
+ const entry = await coordinator.peek(key);
4038
+ const until = Number(entry?.blockedUntil) || 0;
4039
+ const left = until - now();
4040
+ return left > 0 ? Math.ceil(left / 1e3) : 0;
4041
+ };
4042
+ const release = async (reservation) => {
4043
+ if (reservation.ipKey) await coordinator.release(reservation.ipKey);
4044
+ if (reservation.accountKey) await coordinator.release(reservation.accountKey);
4045
+ };
4046
+ return {
4047
+ normalizeIdentifier,
4048
+ /**
4049
+ * Checks the locks and counts the attempt before the password check.
4050
+ *
4051
+ * @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
4052
+ * accountMax: number}} input Client IP, normalised identifier, policy and the
4053
+ * account threshold for this account's role.
4054
+ * @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
4055
+ * lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
4056
+ * @sideeffect Increments the shared counters.
4057
+ */
4058
+ async reserve({ ip, identifier, policy, accountMax }) {
4059
+ const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
4060
+ const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
4061
+ const reservation = {
4062
+ ipKey: countIp ? ipKey(
4063
+ /** @type {string} */
4064
+ ip
4065
+ ) : null,
4066
+ ipHits: 0,
4067
+ accountKey: countAccount ? accountKey(
4068
+ /** @type {string} */
4069
+ identifier
4070
+ ) : null,
4071
+ accountHits: 0
4072
+ };
4073
+ if (!reservation.ipKey && !reservation.accountKey) {
4074
+ return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
4075
+ }
4076
+ const [ipLeft, accountLeft] = await Promise.all([
4077
+ remainingSeconds(reservation.ipKey),
4078
+ remainingSeconds(reservation.accountKey)
4079
+ ]);
4080
+ if (ipLeft > 0 || accountLeft > 0) {
4081
+ return {
4082
+ outcome: "locked",
4083
+ retryAfter: Math.max(ipLeft, accountLeft),
4084
+ lockedKind: accountLeft >= ipLeft && accountLeft > 0 ? "account" : "ip",
4085
+ reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
4086
+ };
4087
+ }
4088
+ if (reservation.ipKey) {
4089
+ reservation.ipHits = (await coordinator.hit(reservation.ipKey, policy.windowMs)).hits;
4090
+ }
4091
+ if (reservation.accountKey) {
4092
+ reservation.accountHits = (await coordinator.hit(reservation.accountKey, policy.windowMs)).hits;
4093
+ }
4094
+ if (reservation.ipKey && reservation.ipHits > policy.ipMax || reservation.accountKey && reservation.accountHits > accountMax) {
4095
+ await release(reservation);
4096
+ return { outcome: "busy", retryAfter: 1, lockedKind: null, reservation };
4097
+ }
4098
+ return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
4099
+ },
4100
+ /**
4101
+ * Records the result of the sign-in.
4102
+ *
4103
+ * @param {Reservation} reservation From `reserve`.
4104
+ * @param {'success'|'failure'|'neutral'} result Outcome of the handler.
4105
+ * @param {{policy: LockoutPolicy, accountMax: number, display?: LockDisplay}} options
4106
+ * Policy, account threshold and what the lock list shows.
4107
+ * @returns {Promise<Array<{kind: 'ip'|'account', id: string, failures: number, until: number}>>}
4108
+ * Locks this request created.
4109
+ * @sideeffect Clears, releases or blocks shared counters; writes lock entries.
4110
+ */
4111
+ async settle(reservation, result, { policy, accountMax, display = {} }) {
4112
+ if (result === "success") {
4113
+ for (const key of [reservation.ipKey, reservation.accountKey]) {
4114
+ if (!key) continue;
4115
+ await coordinator.clear(key);
4116
+ }
4117
+ return [];
4118
+ }
4119
+ if (result !== "failure") {
4120
+ await release(reservation);
4121
+ return [];
4122
+ }
4123
+ const locks = [];
4124
+ const until = now() + policy.durationMs;
4125
+ const candidates = [
4126
+ reservation.ipKey && reservation.ipHits >= policy.ipMax ? {
4127
+ kind: (
4128
+ /** @type {const} */
4129
+ "ip"
4130
+ ),
4131
+ id: reservation.ipKey,
4132
+ failures: reservation.ipHits
4133
+ } : null,
4134
+ reservation.accountKey && reservation.accountHits >= accountMax ? {
4135
+ kind: (
4136
+ /** @type {const} */
4137
+ "account"
4138
+ ),
4139
+ id: reservation.accountKey,
4140
+ failures: reservation.accountHits
4141
+ } : null
4142
+ ];
4143
+ for (const lock of candidates) {
4144
+ if (!lock) continue;
4145
+ await coordinator.block(lock.id, until, { windowStart: until - policy.windowMs });
4146
+ await coordinator.registryPut(
4147
+ `${LOCK_PREFIX}${lock.id}`,
4148
+ {
4149
+ kind: lock.kind,
4150
+ ip: lock.kind === "ip" ? display.ip || null : null,
4151
+ user: lock.kind === "account" ? display.userDocumentId || null : null,
4152
+ failures: lock.failures,
4153
+ lockedAt: now(),
4154
+ until
4155
+ },
4156
+ policy.durationMs
4157
+ );
4158
+ locks.push({ ...lock, until });
4159
+ }
4160
+ return locks;
4161
+ },
4162
+ /**
4163
+ * Active locks, soonest end last.
4164
+ *
4165
+ * @returns {Promise<Array<{id: string, kind: 'ip'|'account', ip: string|null,
4166
+ * user: string|null, failures: number, lockedAt: number, until: number}>>} Locks.
4167
+ */
4168
+ async listLocks() {
4169
+ const entries = await coordinator.registryList(LOCK_PREFIX, MAX_LISTED_LOCKS);
4170
+ const current = now();
4171
+ return entries.map(({ key, value }) => ({
4172
+ id: key.slice(LOCK_PREFIX.length),
4173
+ kind: value?.kind === "account" ? "account" : "ip",
4174
+ ip: typeof value?.ip === "string" ? value.ip : null,
4175
+ user: typeof value?.user === "string" ? value.user : null,
4176
+ failures: Number(value?.failures) || 0,
4177
+ lockedAt: Number(value?.lockedAt) || 0,
4178
+ until: Number(value?.until) || 0
4179
+ })).filter((lock) => KEY_PATTERN.test(lock.id) && lock.until > current).sort((a, b) => b.lockedAt - a.lockedAt);
4180
+ },
4181
+ /**
4182
+ * Lifts a lock: deletes the counter and the list entry.
4183
+ *
4184
+ * @param {string} id Lock id from `listLocks` (`lf:…` or `la:…`).
4185
+ * @returns {Promise<{kind: 'ip'|'account', ip: string|null, user: string|null}|null>}
4186
+ * The lifted lock, or null when the id is invalid or nothing was locked.
4187
+ * @sideeffect Deletes the shared counter and the lock entry.
4188
+ */
4189
+ async unlock(id) {
4190
+ if (typeof id !== "string" || !KEY_PATTERN.test(id)) return null;
4191
+ const entries = await coordinator.registryList(`${LOCK_PREFIX}${id}`, 1);
4192
+ const entry = entries.find((candidate) => candidate.key === `${LOCK_PREFIX}${id}`);
4193
+ const counter = await coordinator.peek(id);
4194
+ const blocked = Number(counter?.blockedUntil) > now();
4195
+ await coordinator.clear(id);
4196
+ await coordinator.registryDelete(`${LOCK_PREFIX}${id}`);
4197
+ if (!entry && !blocked) return null;
4198
+ return {
4199
+ kind: id.startsWith("la:") ? "account" : "ip",
4200
+ ip: typeof entry?.value?.ip === "string" ? entry.value.ip : null,
4201
+ user: typeof entry?.value?.user === "string" ? entry.value.user : null
4202
+ };
4203
+ }
4204
+ };
4205
+ }
4206
+ module.exports = {
4207
+ LOCK_ID_PATTERN: KEY_PATTERN,
4208
+ accountKey,
4209
+ createLoginLockout,
4210
+ ipKey,
4211
+ normalizeIdentifier
4212
+ };
4213
+ }
4214
+ });
4215
+
4216
+ // server/src/utils/sign-in-policies.js
4217
+ var require_sign_in_policies = __commonJS({
4218
+ "server/src/utils/sign-in-policies.js"(exports, module) {
4219
+ "use strict";
4220
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
4221
+ var { getCoordinator, hashedKey } = require_coordination();
4222
+ var { resolveSecurityLogSettings } = require_security_log_settings();
4223
+ var { hasRoleOverride, inactivityTimeoutFor, sessionLimitFor } = require_policy_settings();
4224
+ var { normalizeIdentifier } = require_login_lockout();
4225
+ var USER_UID = "plugin::users-permissions.user";
4226
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
4227
+ var MAX_SESSIONS_CHECKED = 500;
4228
+ function readSignInIdentifier(ctx) {
4229
+ const body = ctx?.request?.body;
4230
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
4231
+ return normalizeIdentifier(body.identifier) || normalizeIdentifier(body.email);
4232
+ }
4233
+ async function findAccountByIdentifier(strapi2, identifier) {
4234
+ if (!identifier) return null;
4235
+ const rows = await strapi2.db.query(USER_UID).findMany({
4236
+ where: { $or: [{ email: identifier }, { username: identifier }] },
4237
+ select: ["documentId", "email", "username"],
4238
+ populate: { role: { select: ["documentId"] } },
4239
+ limit: 2
4240
+ });
4241
+ const list = Array.isArray(rows) ? rows : [];
4242
+ const account = list.find((row) => String(row.email || "").toLowerCase() === identifier) || list[0];
4243
+ if (!account?.documentId) return null;
4244
+ return {
4245
+ documentId: account.documentId,
4246
+ email: typeof account.email === "string" ? account.email : null,
4247
+ username: typeof account.username === "string" ? account.username : null,
4248
+ role: account.role?.documentId || null
4249
+ };
4250
+ }
4251
+ async function findUserRole(strapi2, userDocumentId) {
4252
+ if (!userDocumentId) return null;
4253
+ const user = await strapi2.db.query(USER_UID).findOne({
4254
+ where: { documentId: userDocumentId },
4255
+ select: ["id"],
4256
+ populate: { role: { select: ["documentId"] } }
4257
+ });
4258
+ return user?.role?.documentId || null;
4259
+ }
4260
+ function displayIp(settings, ip) {
4261
+ const options = resolveSecurityLogSettings(settings);
4262
+ if (!options.storeIp) return null;
4263
+ const normalized = normalizeIp(ip || "");
4264
+ if (!normalized) return null;
4265
+ return options.anonymizeIp ? anonymizeIp(normalized) : normalized;
4266
+ }
4267
+ function recordUserEvent(strapi2, input) {
4268
+ try {
4269
+ return strapi2.plugin("magic-sessionmanager").service("security-log").record(input) === true;
4270
+ } catch {
4271
+ return false;
4272
+ }
4273
+ }
4274
+ function isOpenSession(session, idleMs, maxAgeDays, now) {
4275
+ if (session.isActive !== true) return false;
4276
+ const login = session.loginTime ? new Date(session.loginTime).getTime() : NaN;
4277
+ const last = session.lastActive ? new Date(session.lastActive).getTime() : login;
4278
+ if (Number.isFinite(last) && now - last > idleMs) return false;
4279
+ if (Number.isFinite(login) && now - login > maxAgeDays * 24 * 60 * 60 * 1e3) return false;
4280
+ return true;
4281
+ }
4282
+ async function createSessionWithinLimit({
4283
+ strapi: strapi2,
4284
+ settings,
4285
+ userDocumentId,
4286
+ create,
4287
+ sessionService
4288
+ }) {
4289
+ const possible = sessionLimitFor(settings, null).limit > 0 || hasRoleOverride(settings, "maxSessionsPerUser");
4290
+ if (!possible) return { session: await create(), refused: false, ended: 0, limit: 0 };
4291
+ const role = await findUserRole(strapi2, userDocumentId);
4292
+ const { limit, policy } = sessionLimitFor(settings, role);
4293
+ if (limit <= 0) return { session: await create(), refused: false, ended: 0, limit: 0 };
4294
+ return getCoordinator(strapi2).withLock(hashedKey("session-limit", userDocumentId), async () => {
4295
+ const session = await create();
4296
+ if (!session?.documentId) return { session, refused: false, ended: 0, limit };
4297
+ const now = Date.now();
4298
+ const idleMs = inactivityTimeoutFor(settings, role);
4299
+ const maxAgeDays = Number(settings.maxSessionAgeDays) || 30;
4300
+ const rows = await strapi2.documents(SESSION_UID).findMany({
4301
+ filters: { user: { documentId: userDocumentId }, isActive: true },
4302
+ fields: ["documentId", "isActive", "loginTime", "lastActive"],
4303
+ sort: [{ loginTime: "asc" }, { id: "asc" }],
4304
+ limit: MAX_SESSIONS_CHECKED
4305
+ });
4306
+ const open = (Array.isArray(rows) ? rows : []).filter(
4307
+ (row) => isOpenSession(row, idleMs, maxAgeDays, now)
4308
+ );
4309
+ if (open.length <= limit) return { session, refused: false, ended: 0, limit };
4310
+ if (policy === "refuse") {
4311
+ await sessionService.terminateSession({ sessionId: session.documentId, reason: "manual" });
4312
+ return { session, refused: true, ended: 0, limit };
4313
+ }
4314
+ const others = open.filter((row) => row.documentId !== session.documentId);
4315
+ const excess = open.length - limit;
4316
+ let ended = 0;
4317
+ for (const row of others.slice(0, excess)) {
4318
+ const result = await sessionService.terminateSession({
4319
+ sessionId: row.documentId,
4320
+ reason: "manual"
4321
+ });
4322
+ ended += Number(result?.terminatedCount) || 0;
4323
+ }
4324
+ return { session, refused: false, ended, limit };
4325
+ });
4326
+ }
4327
+ function createRefusalDedup({ windowMs = 60 * 1e3, maxKeys = 5e3 } = {}) {
4328
+ const seen = /* @__PURE__ */ new Map();
4329
+ return (key, now = Date.now()) => {
4330
+ const last = seen.get(key);
4331
+ if (last !== void 0 && now - last < windowMs) return false;
4332
+ seen.delete(key);
4333
+ seen.set(key, now);
4334
+ if (seen.size > maxKeys) seen.delete(
4335
+ /** @type {string} */
4336
+ seen.keys().next().value
4337
+ );
4338
+ return true;
4339
+ };
4340
+ }
4341
+ function createAddressCap({ max = 30, windowMs = 60 * 60 * 1e3, maxKeys = 5e3 } = {}) {
4342
+ const counts = /* @__PURE__ */ new Map();
4343
+ return (ip, now = Date.now()) => {
4344
+ const key = anonymizeIp(normalizeIp(ip || "")) || "-";
4345
+ const windowStart = Math.floor(now / windowMs) * windowMs;
4346
+ const entry = counts.get(key);
4347
+ if (!entry || entry.windowStart !== windowStart) {
4348
+ counts.delete(key);
4349
+ counts.set(key, { count: 1, windowStart });
4350
+ if (counts.size > maxKeys) counts.delete(
4351
+ /** @type {string} */
4352
+ counts.keys().next().value
4353
+ );
4354
+ return true;
4355
+ }
4356
+ entry.count += 1;
4357
+ return entry.count <= max;
4358
+ };
4359
+ }
4360
+ function refusalReasonOfGeoDecision(reason) {
4361
+ const value = String(reason || "");
4362
+ if (value.startsWith("country_")) return "country";
4363
+ if (value.startsWith("geo_lookup_unavailable")) return "location-unavailable";
4364
+ return "risk";
4365
+ }
4366
+ module.exports = {
4367
+ createAddressCap,
4368
+ createRefusalDedup,
4369
+ refusalReasonOfGeoDecision,
4370
+ createSessionWithinLimit,
4371
+ displayIp,
4372
+ findAccountByIdentifier,
4373
+ findUserRole,
4374
+ isOpenSession,
4375
+ readSignInIdentifier,
4376
+ recordUserEvent
4377
+ };
4378
+ }
4379
+ });
4380
+
4381
+ // server/src/utils/upgrade-defaults.js
4382
+ var require_upgrade_defaults = __commonJS({
4383
+ "server/src/utils/upgrade-defaults.js"(exports, module) {
4384
+ "use strict";
4385
+ var { withPluginStoreKey } = require_plugin_store();
4386
+ var { notifySettingsChanged } = require_settings_loader();
4387
+ var PROFILE_KEY = "defaultsProfile";
4388
+ var UPGRADE_STEPS = Object.freeze([
4389
+ Object.freeze({
4390
+ version: 1,
4391
+ release: "4.17.0",
4392
+ // Before 4.17 a password change kept the user's other sessions.
4393
+ legacy: Object.freeze({ endOtherSessionsOnPasswordChange: false })
4394
+ })
4395
+ ]);
4396
+ async function applyUpgradeDefaults(strapi2, log, steps = UPGRADE_STEPS) {
4397
+ const latest = steps.length ? steps[steps.length - 1].version : 0;
4398
+ const outcome = await withPluginStoreKey(strapi2, "settings", async (store) => {
4399
+ const profile = Number(await store.get({ key: PROFILE_KEY })) || 0;
4400
+ if (profile >= latest) return { existing: profile > 0, applied: [], changed: false };
4401
+ const stored = await store.get({ key: "settings" });
4402
+ let existing = profile > 0;
4403
+ if (!existing) {
4404
+ const permissionsVersion = await store.get({ key: "contentApiPermissionsVersion" });
4405
+ const legacyFlag = await store.get({ key: "contentApiPermissionsInitialized" });
4406
+ existing = stored !== null && stored !== void 0 || permissionsVersion !== null && permissionsVersion !== void 0 || legacyFlag === true;
4407
+ }
4408
+ const applied = [];
4409
+ if (existing) {
4410
+ const settings = stored && typeof stored === "object" ? { ...stored } : {};
4411
+ for (const step of steps) {
4412
+ if (step.version <= profile) continue;
4413
+ for (const [key, value] of Object.entries(step.legacy)) {
4414
+ if (settings[key] !== void 0) continue;
4415
+ settings[key] = value;
4416
+ applied.push(key);
4417
+ }
4418
+ }
4419
+ if (applied.length) await store.set({ key: "settings", value: settings });
4420
+ }
4421
+ await store.set({ key: PROFILE_KEY, value: latest });
4422
+ return { existing, applied, changed: applied.length > 0 };
4423
+ });
4424
+ if (outcome.changed) {
4425
+ await notifySettingsChanged(strapi2);
4426
+ log.info(
4427
+ `[UPGRADE] Kept the previous behaviour of ${outcome.applied.length} setting(s) on this existing installation`
4428
+ );
4429
+ }
4430
+ return { existing: outcome.existing, applied: outcome.applied };
4431
+ }
4432
+ module.exports = { PROFILE_KEY, UPGRADE_STEPS, applyUpgradeDefaults };
4433
+ }
4434
+ });
4435
+
3517
4436
  // server/src/middlewares/session-rejection-headers.js
3518
4437
  var require_session_rejection_headers = __commonJS({
3519
4438
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -7608,12 +8527,7 @@ var require_bootstrap = __commonJS({
7608
8527
  var { REVOCATION_UID } = require_session_revocation();
7609
8528
  var { getNativeSessionManager } = require_native_session_manager();
7610
8529
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
7611
- var {
7612
- getCoordinator,
7613
- hashedKey,
7614
- initCoordination,
7615
- LockTimeoutError
7616
- } = require_coordination();
8530
+ var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
7617
8531
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
7618
8532
  var {
7619
8533
  normalizeApiPrefix,
@@ -7643,8 +8557,27 @@ var require_bootstrap = __commonJS({
7643
8557
  migrateSecurityLog,
7644
8558
  warnUnboundedProxyTrust
7645
8559
  } = require_security_log_hardening();
8560
+ var { createLoginLockout } = require_login_lockout();
8561
+ var {
8562
+ accountThresholdFor,
8563
+ inactivityTimeoutFor,
8564
+ hasRoleOverride,
8565
+ resolveLockoutPolicy
8566
+ } = require_policy_settings();
8567
+ var {
8568
+ createAddressCap,
8569
+ createRefusalDedup,
8570
+ createSessionWithinLimit,
8571
+ displayIp,
8572
+ findAccountByIdentifier,
8573
+ readSignInIdentifier,
8574
+ recordUserEvent,
8575
+ refusalReasonOfGeoDecision
8576
+ } = require_sign_in_policies();
8577
+ var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
8578
+ var { applyUpgradeDefaults } = require_upgrade_defaults();
8579
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
7646
8580
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7647
- var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
7648
8581
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
7649
8582
  var JOB_LEASES = Object.freeze({
7650
8583
  idleCleanup: "job:idle-cleanup",
@@ -7686,6 +8619,11 @@ var require_bootstrap = __commonJS({
7686
8619
  try {
7687
8620
  const coordinator = await initCoordination(strapi2, log);
7688
8621
  await checkEncryptionKeyConsistency(strapi2, log);
8622
+ try {
8623
+ await applyUpgradeDefaults(strapi2, log);
8624
+ } catch (err) {
8625
+ log.warn("[UPGRADE] Previous defaults could not be kept:", err?.name || "Error");
8626
+ }
7689
8627
  await ensureSessionLookupIndexes(strapi2, log);
7690
8628
  await registerSessionAwareAuthStrategy(strapi2);
7691
8629
  await removeLegacyLicenseRows(strapi2, log);
@@ -7847,6 +8785,27 @@ var require_bootstrap = __commonJS({
7847
8785
  }
7848
8786
  }
7849
8787
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
8788
+ const shouldRecordRefusal = createRefusalDedup();
8789
+ const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
8790
+ const recordRefusal = async (ctx, settings, ip, decisionReason) => {
8791
+ if (!resolveLockoutPolicy(settings).record) return;
8792
+ const reason = refusalReasonOfGeoDecision(decisionReason);
8793
+ const identifier = readSignInIdentifier(ctx);
8794
+ if (!shouldRecordRefusal(`${reason}|${ip}|${identifier || ""}`)) return;
8795
+ const account = await findAccountByIdentifier(strapi2, identifier).catch(() => null);
8796
+ if (!account && !shouldRecordUnknownAccount(`refused|${anonymizeIp(normalizeIp(ip || "")) || "none"}`)) {
8797
+ return;
8798
+ }
8799
+ recordUserEvent(strapi2, {
8800
+ event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
8801
+ actorType: "user",
8802
+ targetType: "user",
8803
+ targetId: account?.documentId || null,
8804
+ ip,
8805
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
8806
+ meta: { reason }
8807
+ });
8808
+ };
7850
8809
  strapi2.server.use(async (ctx, next) => {
7851
8810
  if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
7852
8811
  return next();
@@ -7866,6 +8825,7 @@ var require_bootstrap = __commonJS({
7866
8825
  const decision = evaluateGeoFirewall(settings, geoData);
7867
8826
  if (decision.blocked) {
7868
8827
  log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
8828
+ await recordRefusal(ctx, settings, ip, decision.reason);
7869
8829
  ctx.status = 403;
7870
8830
  ctx.body = {
7871
8831
  error: {
@@ -7884,6 +8844,7 @@ var require_bootstrap = __commonJS({
7884
8844
  const failureDecision = evaluateGeoFirewall(settings, { _status: "error" });
7885
8845
  if (failureDecision.blocked) {
7886
8846
  log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
8847
+ await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
7887
8848
  ctx.status = 403;
7888
8849
  ctx.body = {
7889
8850
  error: {
@@ -8083,53 +9044,95 @@ var require_bootstrap = __commonJS({
8083
9044
  }
8084
9045
  }
8085
9046
  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);
9047
+ const lockout = createLoginLockout(getCoordinator(strapi2));
9048
+ const shouldRecordRefusal = createRefusalDedup();
9049
+ const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
9050
+ const underAddressCap = createAddressCap();
9051
+ const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
8089
9052
  strapi2.server.use(async (ctx, next) => {
8090
9053
  if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
8091
9054
  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;
9055
+ const policy = resolveLockoutPolicy(settings);
9056
+ const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
9057
+ if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
9058
+ const rawIp = getClientIp(ctx);
9059
+ const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
9060
+ const identifier = readSignInIdentifier(ctx);
9061
+ const userAgent = ctx.request?.headers?.["user-agent"] || null;
9062
+ let account;
9063
+ const loadAccount = async () => {
9064
+ if (account !== void 0) return account;
9065
+ let found = null;
9066
+ if (identifier) {
9067
+ try {
9068
+ found = await findAccountByIdentifier(strapi2, identifier);
9069
+ } catch (err) {
9070
+ log.debug("[LOCKOUT] Account lookup failed:", err?.name || "Error");
9071
+ }
9072
+ }
9073
+ account = found;
9074
+ return account;
9075
+ };
9076
+ if (policy.accountMaxByRole) await loadAccount();
9077
+ const accountMax = accountThresholdFor(settings, account?.role || null);
9078
+ const event = (name, meta) => {
9079
+ const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
9080
+ if (signInFamily && !policy.record) return false;
9081
+ if (signInFamily && !underAddressCap(ip)) return false;
9082
+ return recordUserEvent(strapi2, {
9083
+ event: name,
9084
+ actorType: "user",
9085
+ actorId: null,
9086
+ targetType: "user",
9087
+ targetId: account?.documentId || null,
9088
+ ip,
9089
+ userAgent,
9090
+ meta
9091
+ });
9092
+ };
9093
+ const refusedOnce = (reason, meta) => {
9094
+ if (!policy.record) return;
9095
+ if (!account) {
9096
+ if (!shouldRecordUnknownAccount(`refused|${unknownAccountKey(ip)}`)) return;
9097
+ event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, unknownAccount: true, ...meta });
9098
+ return;
9099
+ }
9100
+ if (!shouldRecordRefusal(`${reason}|${ip || ""}|${identifier || ""}`)) return;
9101
+ event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, ...meta });
9102
+ };
9103
+ let decision;
8099
9104
  try {
8100
- existing = await coordinator.peek(key);
9105
+ decision = await lockout.reserve({ ip, identifier, policy, accountMax });
8101
9106
  } catch (err) {
8102
- log.debug("[LOCKOUT] Counter read failed:", err?.name || "Error");
9107
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
9108
+ decision = {
9109
+ outcome: "allow",
9110
+ retryAfter: 0,
9111
+ lockedKind: null,
9112
+ reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
9113
+ };
8103
9114
  }
8104
- const rejectLocked = (retrySec) => {
8105
- ctx.set("Retry-After", String(retrySec));
8106
- log.warn(`[LOCKOUT] Rejected login from locked client (${retrySec}s remaining)`);
9115
+ if (decision.outcome === "locked") {
9116
+ ctx.set("Retry-After", String(decision.retryAfter));
9117
+ log.warn(
9118
+ `[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
9119
+ );
9120
+ if (policy.record) await loadAccount();
9121
+ refusedOnce("lockout", { lock: decision.lockedKind });
8107
9122
  ctx.status = 429;
8108
9123
  ctx.body = {
8109
9124
  error: {
8110
9125
  status: 429,
8111
9126
  name: "TooManyRequestsError",
8112
9127
  message: "Too many failed login attempts. Please try again later.",
8113
- details: { retryAfter: retrySec }
9128
+ details: { retryAfter: decision.retryAfter }
8114
9129
  }
8115
9130
  };
8116
- };
8117
- if (existing && existing.blockedUntil > now) {
8118
- rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
8119
9131
  return;
8120
9132
  }
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
- }
9133
+ if (decision.outcome === "busy") {
9134
+ if (policy.record) await loadAccount();
9135
+ refusedOnce("too-many-attempts", {});
8133
9136
  ctx.set("Retry-After", "1");
8134
9137
  ctx.status = 429;
8135
9138
  ctx.body = {
@@ -8149,18 +9152,43 @@ var require_bootstrap = __commonJS({
8149
9152
  thrown = err;
8150
9153
  }
8151
9154
  const status = thrown ? statusOfThrownError(thrown) : ctx.status;
9155
+ const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
9156
+ if (result === "failure") {
9157
+ if (policy.record || decision.reservation.accountKey) await loadAccount();
9158
+ if (account) {
9159
+ event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
9160
+ } else if (shouldRecordUnknownAccount(`failed|${unknownAccountKey(ip)}`)) {
9161
+ event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status, unknownAccount: true });
9162
+ }
9163
+ }
8152
9164
  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
- );
9165
+ const locks = await lockout.settle(decision.reservation, result, {
9166
+ policy,
9167
+ accountMax,
9168
+ display: {
9169
+ ip: displayIp(settings, ip),
9170
+ userDocumentId: account?.documentId || null
9171
+ }
9172
+ });
9173
+ for (const lock of locks) {
9174
+ const minutes = Math.round(policy.durationMs / 6e4);
9175
+ log.warn(
9176
+ `[LOCKOUT] ${lock.kind === "ip" ? "Client" : "Account"} locked for ${minutes}min after ${lock.failures} failed sign-ins`
9177
+ );
9178
+ event(SECURITY_EVENTS.USER_LOCKOUT, {
9179
+ kind: lock.kind,
9180
+ failures: lock.failures,
9181
+ minutes
9182
+ });
9183
+ if (lock.kind === "account" && policy.notifyUser && account?.email) {
9184
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
9185
+ notifications.sendAccountLockedEmail({
9186
+ user: account,
9187
+ minutes,
9188
+ until: lock.until
9189
+ }).catch(() => {
9190
+ });
8161
9191
  }
8162
- } else if (reserved) {
8163
- await coordinator.release(key);
8164
9192
  }
8165
9193
  } catch (err) {
8166
9194
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
@@ -8187,6 +9215,47 @@ var require_bootstrap = __commonJS({
8187
9215
  };
8188
9216
  return byName[err?.name] || 500;
8189
9217
  }
9218
+ function refuseSessionLimit({ ctx, strapi: strapi2, limit }) {
9219
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
9220
+ ctx.status = 403;
9221
+ ctx.body = {
9222
+ data: null,
9223
+ error: {
9224
+ status: 403,
9225
+ name: "ForbiddenError",
9226
+ message: "Too many active sessions. Sign out on another device and try again.",
9227
+ details: { code: "SESSION_LIMIT_REACHED", limit }
9228
+ }
9229
+ };
9230
+ }
9231
+ async function endOtherSessionsAfterPasswordChange({
9232
+ strapi: strapi2,
9233
+ ctx,
9234
+ log,
9235
+ sessionService,
9236
+ userDocumentId,
9237
+ currentSessionId
9238
+ }) {
9239
+ const settings = await getPluginSettings(strapi2);
9240
+ if (settings.endOtherSessionsOnPasswordChange !== true) return;
9241
+ if (!userDocumentId) throw new Error("password change owner could not be resolved");
9242
+ const { terminatedCount } = await sessionService.terminateSession({
9243
+ userId: userDocumentId,
9244
+ exceptSessionId: currentSessionId,
9245
+ reason: "logout"
9246
+ });
9247
+ recordUserEvent(strapi2, {
9248
+ event: SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
9249
+ actorType: "user",
9250
+ actorId: userDocumentId,
9251
+ targetType: "user",
9252
+ targetId: userDocumentId,
9253
+ ip: getClientIp(ctx),
9254
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
9255
+ meta: { ended: Number(terminatedCount) || 0 }
9256
+ });
9257
+ log.info("[PASSWORD] Ended the other sessions after a password change");
9258
+ }
8190
9259
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
8191
9260
  strapi2.server.use(async (ctx, next) => {
8192
9261
  const apiPath = apiPathOf(strapi2, ctx);
@@ -8237,6 +9306,7 @@ var require_bootstrap = __commonJS({
8237
9306
  filters: { tokenHash: hashToken(previousAccessToken), isActive: true },
8238
9307
  fields: ["documentId"]
8239
9308
  });
9309
+ let currentSidecarId;
8240
9310
  if (matchingSession) {
8241
9311
  const rotated = await sessionService.rotateSessionTokens({
8242
9312
  sessionId: matchingSession.documentId,
@@ -8247,6 +9317,7 @@ var require_bootstrap = __commonJS({
8247
9317
  });
8248
9318
  if (!rotated)
8249
9319
  throw new Error("current sidecar changed before native password rotation was linked");
9320
+ currentSidecarId = matchingSession.documentId;
8250
9321
  log.info("[PASSWORD] Native session link updated");
8251
9322
  } else {
8252
9323
  const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
@@ -8262,7 +9333,16 @@ var require_bootstrap = __commonJS({
8262
9333
  if (!createdSidecar?.documentId) {
8263
9334
  throw new Error("native password-change sidecar creation returned no documentId");
8264
9335
  }
9336
+ currentSidecarId = createdSidecar.documentId;
8265
9337
  }
9338
+ await endOtherSessionsAfterPasswordChange({
9339
+ strapi: strapi2,
9340
+ ctx,
9341
+ log,
9342
+ sessionService,
9343
+ userDocumentId: nativeSession2.userDocumentId,
9344
+ currentSessionId: currentSidecarId
9345
+ });
8266
9346
  } catch (err) {
8267
9347
  if (nativeSessionManager2 && nativeSession2) {
8268
9348
  await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
@@ -8301,6 +9381,19 @@ var require_bootstrap = __commonJS({
8301
9381
  });
8302
9382
  if (!rotated) throw new Error("current session changed before token rotation");
8303
9383
  log.info("[PASSWORD] Legacy session tokens rotated");
9384
+ const owner = await strapi2.documents(SESSION_UID).findOne({
9385
+ documentId: matchingSession.documentId,
9386
+ fields: ["documentId"],
9387
+ populate: { user: { fields: ["documentId"] } }
9388
+ });
9389
+ await endOtherSessionsAfterPasswordChange({
9390
+ strapi: strapi2,
9391
+ ctx,
9392
+ log,
9393
+ sessionService,
9394
+ userDocumentId: owner?.user?.documentId || null,
9395
+ currentSessionId: matchingSession.documentId
9396
+ });
8304
9397
  } catch (err) {
8305
9398
  failClosedAuthResponse({
8306
9399
  ctx,
@@ -8343,7 +9436,9 @@ var require_bootstrap = __commonJS({
8343
9436
  throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
8344
9437
  }
8345
9438
  const geoData = ctx.state?.__magicSessionGeoData || null;
8346
- const newSession = await sessionService.createSession({
9439
+ const requestSettings = await getPluginSettings(strapi2);
9440
+ const isReset = isPasswordResetRequest(apiPath, ctx.method);
9441
+ const create = () => sessionService.createSession({
8347
9442
  userId: userDocId,
8348
9443
  ip,
8349
9444
  userAgent,
@@ -8352,10 +9447,45 @@ var require_bootstrap = __commonJS({
8352
9447
  geoData,
8353
9448
  ...nativeSession ? { nativeSessionId: nativeSession.sessionId } : {}
8354
9449
  });
9450
+ const limited = isReset ? { session: await create(), refused: false, ended: 0, limit: 0 } : await createSessionWithinLimit({
9451
+ strapi: strapi2,
9452
+ settings: requestSettings,
9453
+ userDocumentId: userDocId,
9454
+ create,
9455
+ sessionService
9456
+ });
9457
+ const newSession = limited.session;
8355
9458
  if (!newSession?.documentId) {
8356
9459
  throw new Error(`session creation returned no documentId for user ${userDocId}`);
8357
9460
  }
8358
- if (isPasswordResetRequest(apiPath, ctx.method)) {
9461
+ if (limited.refused) {
9462
+ recordUserEvent(strapi2, {
9463
+ event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
9464
+ actorType: "user",
9465
+ actorId: userDocId,
9466
+ targetType: "user",
9467
+ targetId: userDocId,
9468
+ ip,
9469
+ userAgent,
9470
+ meta: { reason: "session-limit", limit: limited.limit }
9471
+ });
9472
+ refuseSessionLimit({ ctx, strapi: strapi2, limit: limited.limit });
9473
+ log.info("[LIMIT] Sign-in refused: the user reached the session limit");
9474
+ return;
9475
+ }
9476
+ if (limited.ended > 0) {
9477
+ recordUserEvent(strapi2, {
9478
+ event: SECURITY_EVENTS.USER_SESSION_LIMIT,
9479
+ actorType: "system",
9480
+ targetType: "user",
9481
+ targetId: userDocId,
9482
+ ip,
9483
+ userAgent,
9484
+ meta: { ended: limited.ended, limit: limited.limit }
9485
+ });
9486
+ log.info(`[LIMIT] Ended ${limited.ended} older session(s) to stay within the limit`);
9487
+ }
9488
+ if (isReset) {
8359
9489
  await sessionService.terminateSession({
8360
9490
  userId: userDocId,
8361
9491
  exceptSessionId: newSession.documentId,
@@ -9046,11 +10176,13 @@ var require_bootstrap = __commonJS({
9046
10176
  strapi2.log.debug("[magic-sessionmanager] [JWT] No documentId found in relaxed mode");
9047
10177
  return decoded;
9048
10178
  }
10179
+ const needsRole = hasRoleOverride(settings, "inactivityTimeout");
9049
10180
  let userRecord;
9050
10181
  try {
9051
10182
  userRecord = await strapi2.documents("plugin::users-permissions.user").findOne({
9052
10183
  documentId: userDocId,
9053
- fields: ["documentId", "blocked"]
10184
+ fields: ["documentId", "blocked"],
10185
+ ...needsRole ? { populate: { role: { fields: ["documentId"] } } } : {}
9054
10186
  });
9055
10187
  } catch (err) {
9056
10188
  if (strictMode) {
@@ -9119,7 +10251,10 @@ var require_bootstrap = __commonJS({
9119
10251
  setSessionRejectionReason(tokenHashValue, "expired");
9120
10252
  return null;
9121
10253
  }
9122
- const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
10254
+ const inactivityTimeout = inactivityTimeoutFor(
10255
+ settings,
10256
+ userRecord?.role?.documentId || null
10257
+ );
9123
10258
  const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
9124
10259
  const idleFor = Date.now() - lastActiveMs;
9125
10260
  if (idleFor > inactivityTimeout) {
@@ -9315,6 +10450,9 @@ var require_config = __commonJS({
9315
10450
  discordWebhookUrl: "",
9316
10451
  slackWebhookUrl: "",
9317
10452
  trustedProxies: null,
10453
+ // Sign-in and session policies (4.17). Existing installations keep
10454
+ // `endOtherSessionsOnPasswordChange: false` (utils/upgrade-defaults.js).
10455
+ endOtherSessionsOnPasswordChange: true,
9318
10456
  // Cross-process state for pm2 cluster / several replicas. `enabled:
9319
10457
  // false` keeps every counter, lease and cache per process (the pre-4.10
9320
10458
  // behaviour). `counterStore` may supply an object with async
@@ -9749,6 +10887,7 @@ var require_admin = __commonJS({
9749
10887
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
9750
10888
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
9751
10889
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
10890
+ var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
9752
10891
  var adminPolicy = () => [
9753
10892
  "admin::isAuthenticatedAdmin",
9754
10893
  {
@@ -10002,6 +11141,37 @@ var require_admin = __commonJS({
10002
11141
  description: "Get one export batch of Content Manager activity of admins (admin)"
10003
11142
  }
10004
11143
  },
11144
+ // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
11145
+ {
11146
+ method: "GET",
11147
+ path: "/lockouts",
11148
+ handler: "lockouts.list",
11149
+ config: {
11150
+ policies: adminPolicy(),
11151
+ middlewares: adminReadRateLimit(),
11152
+ description: "List the active sign-in locks (admin)"
11153
+ }
11154
+ },
11155
+ {
11156
+ method: "POST",
11157
+ path: "/lockouts/unlock",
11158
+ handler: "lockouts.unlock",
11159
+ config: {
11160
+ policies: adminSessionsPolicy([LOCKOUTS_UNLOCK_ACTION]),
11161
+ middlewares: adminSignOutRateLimit(),
11162
+ description: "Lift one sign-in lock (admin)"
11163
+ }
11164
+ },
11165
+ {
11166
+ method: "GET",
11167
+ path: "/roles",
11168
+ handler: "lockouts.roles",
11169
+ config: {
11170
+ policies: adminPolicy(),
11171
+ middlewares: adminReadRateLimit(),
11172
+ description: "List Users & Permissions roles for per-role rules (admin)"
11173
+ }
11174
+ },
10005
11175
  // ============================ GEOLOCATION ============================
10006
11176
  {
10007
11177
  method: "GET",
@@ -12334,6 +13504,7 @@ var require_settings_access = __commonJS({
12334
13504
  "server/src/utils/settings-access.js"(exports, module) {
12335
13505
  "use strict";
12336
13506
  var { SECURITY_LOG_KEYS } = require_security_log_settings();
13507
+ var { POLICY_KEYS } = require_policy_settings();
12337
13508
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12338
13509
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12339
13510
  var GEO_SETTINGS_KEYS = Object.freeze([
@@ -12350,7 +13521,10 @@ var require_settings_access = __commonJS({
12350
13521
  var PROTECTED_SETTINGS_KEYS = Object.freeze([
12351
13522
  ...GEO_SETTINGS_KEYS,
12352
13523
  ...WEBHOOK_SETTINGS_KEYS,
12353
- ...SECURITY_LOG_KEYS
13524
+ ...SECURITY_LOG_KEYS,
13525
+ // Sign-in and session policies (lockout, trusted addresses, session
13526
+ // limit, password-change sign-out, recording switch, per-role rules).
13527
+ ...POLICY_KEYS
12354
13528
  ]);
12355
13529
  var WEBHOOK_SECRETS = Object.freeze([
12356
13530
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
@@ -12443,6 +13617,7 @@ var require_settings = __commonJS({
12443
13617
  missingSettingsPermission,
12444
13618
  toPublicSettings
12445
13619
  } = require_settings_access();
13620
+ var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
12446
13621
  var path = __require("node:path");
12447
13622
  var ALLOWED_WEBHOOK_DOMAINS = {
12448
13623
  discord: ["discord.com", "discordapp.com"],
@@ -12474,11 +13649,9 @@ var require_settings = __commonJS({
12474
13649
  }
12475
13650
  }
12476
13651
  function sanitizeEmailTemplates(templates) {
12477
- const defaults = {
12478
- suspiciousLogin: { subject: "", html: "", text: "" },
12479
- newLocation: { subject: "", html: "", text: "" },
12480
- vpnProxy: { subject: "", html: "", text: "" }
12481
- };
13652
+ const defaults = Object.fromEntries(
13653
+ Object.keys(DEFAULT_EMAIL_TEMPLATES).map((key) => [key, { subject: "", html: "", text: "" }])
13654
+ );
12482
13655
  if (!templates || typeof templates !== "object") return defaults;
12483
13656
  let sanitizeHtml;
12484
13657
  try {
@@ -12584,7 +13757,9 @@ var require_settings = __commonJS({
12584
13757
  var DEFAULT_EMAIL_TEMPLATES = {
12585
13758
  suspiciousLogin: { subject: "", html: "", text: "" },
12586
13759
  newLocation: { subject: "", html: "", text: "" },
12587
- vpnProxy: { subject: "", html: "", text: "" }
13760
+ vpnProxy: { subject: "", html: "", text: "" },
13761
+ // 4.17: sent to a user whose account was locked after failed sign-ins.
13762
+ accountLocked: { subject: "", html: "", text: "" }
12588
13763
  };
12589
13764
  var DEFAULT_SETTINGS = {
12590
13765
  inactivityTimeout: 15,
@@ -12617,7 +13792,10 @@ var require_settings = __commonJS({
12617
13792
  strictSessionEnforcement: false,
12618
13793
  trustedProxies: false,
12619
13794
  emailTemplates: DEFAULT_EMAIL_TEMPLATES,
12620
- ...SECURITY_LOG_DEFAULTS
13795
+ ...SECURITY_LOG_DEFAULTS,
13796
+ ...POLICY_DEFAULTS,
13797
+ lockoutTrustedAddresses: [],
13798
+ roleRules: []
12621
13799
  };
12622
13800
  function mergeSettingsWithDefaults(stored) {
12623
13801
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -12825,6 +14003,9 @@ var require_settings = __commonJS({
12825
14003
  const securityLog = validateSecurityLogSettings(body);
12826
14004
  errors.push(...securityLog.errors);
12827
14005
  Object.assign(next, securityLog.values);
14006
+ const policies = validatePolicySettings(body);
14007
+ errors.push(...policies.errors);
14008
+ Object.assign(next, policies.values);
12828
14009
  if (errors.length > 0) return { errors };
12829
14010
  const settings = {};
12830
14011
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -12874,6 +14055,16 @@ var require_settings = __commonJS({
12874
14055
  } catch {
12875
14056
  }
12876
14057
  }
14058
+ async function findUnknownRoles(rules) {
14059
+ if (!Array.isArray(rules) || rules.length === 0) return [];
14060
+ const ids = rules.map((rule) => rule.role);
14061
+ const rows = await strapi.db.query("plugin::users-permissions.role").findMany({ where: { documentId: { $in: ids } }, select: ["documentId"] });
14062
+ const known = new Set((Array.isArray(rows) ? rows : []).map((row) => row.documentId));
14063
+ return rules.map((rule, index) => known.has(rule.role) ? null : index).filter((index) => index !== null).map((index) => ({
14064
+ path: ["roleRules", index, "role"],
14065
+ message: "This role does not exist any more"
14066
+ }));
14067
+ }
12877
14068
  module.exports = {
12878
14069
  /**
12879
14070
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -12958,6 +14149,8 @@ var require_settings = __commonJS({
12958
14149
  };
12959
14150
  const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
12960
14151
  if (errors.length > 0) return { errors };
14152
+ const roleErrors = await findUnknownRoles(sanitizedSettings.roleRules);
14153
+ if (roleErrors.length > 0) return { errors: roleErrors };
12961
14154
  const changed = changedKeys(
12962
14155
  {
12963
14156
  ...sanitizedSettings,
@@ -14353,6 +15546,137 @@ var require_admin_activity = __commonJS({
14353
15546
  }
14354
15547
  });
14355
15548
 
15549
+ // server/src/controllers/lockouts.js
15550
+ var require_lockouts = __commonJS({
15551
+ "server/src/controllers/lockouts.js"(exports, module) {
15552
+ "use strict";
15553
+ var { getCoordinator } = require_coordination();
15554
+ var { LOCK_ID_PATTERN, createLoginLockout } = require_login_lockout();
15555
+ var { getRequestIp, getRequestUserAgent } = require_admin_request_info();
15556
+ var { SECURITY_EVENTS } = require_security_log_model();
15557
+ var { sendServerError, sendValidationError } = require_http_errors();
15558
+ var { createLogger } = require_logger();
15559
+ var USER_UID = "plugin::users-permissions.user";
15560
+ var ROLE_UID = "plugin::users-permissions.role";
15561
+ module.exports = ({ strapi: strapi2 }) => {
15562
+ const log = createLogger(strapi2);
15563
+ const lockout = () => createLoginLockout(getCoordinator(strapi2));
15564
+ return {
15565
+ /**
15566
+ * Lists the active sign-in locks: locked IP addresses (shown as the
15567
+ * security log stores IPs) and locked accounts with their user.
15568
+ *
15569
+ * @route GET /magic-sessionmanager/lockouts
15570
+ * @auth admin session or admin API token
15571
+ * @access plugin::magic-sessionmanager.access
15572
+ * @param {any} ctx Koa context.
15573
+ * @returns {Promise<void>} `{ data: Lock[], meta: { total } }`; 500 on store failure.
15574
+ */
15575
+ async list(ctx) {
15576
+ try {
15577
+ const locks = await lockout().listLocks();
15578
+ const ids = [...new Set(locks.map((lock) => lock.user).filter(Boolean))];
15579
+ const users = ids.length ? await strapi2.db.query(USER_UID).findMany({
15580
+ where: { documentId: { $in: ids } },
15581
+ select: ["documentId", "username", "email"]
15582
+ }) : [];
15583
+ const byId = new Map(
15584
+ (Array.isArray(users) ? users : []).map((user) => [user.documentId, user])
15585
+ );
15586
+ const data = locks.map((lock) => {
15587
+ const user = lock.user ? byId.get(lock.user) : null;
15588
+ return {
15589
+ id: lock.id,
15590
+ kind: lock.kind,
15591
+ ip: lock.kind === "ip" ? lock.ip : null,
15592
+ user: user ? { documentId: user.documentId, username: user.username, email: user.email } : null,
15593
+ failures: lock.failures,
15594
+ lockedAt: new Date(lock.lockedAt).toISOString(),
15595
+ until: new Date(lock.until).toISOString()
15596
+ };
15597
+ });
15598
+ ctx.body = { data, meta: { total: data.length } };
15599
+ } catch (err) {
15600
+ log.error("[lockouts] List failed:", err?.name || "Error");
15601
+ return sendServerError(ctx, 500, "Locks could not be loaded");
15602
+ }
15603
+ },
15604
+ /**
15605
+ * Lifts one lock. The admin who lifted it is recorded in the security log.
15606
+ *
15607
+ * @route POST /magic-sessionmanager/lockouts/unlock
15608
+ * @auth admin session or admin API token
15609
+ * @access plugin::magic-sessionmanager.access + plugin::magic-sessionmanager.lockouts.unlock
15610
+ * @param {any} ctx Koa context; body `{ id }` from the list.
15611
+ * @returns {Promise<void>} `{ data: { unlocked: true, kind } }`; 400 invalid id; 404 not locked.
15612
+ * @sideeffect Deletes the shared lock counter and list entry; writes `user.lockout.lifted`.
15613
+ */
15614
+ async unlock(ctx) {
15615
+ const body = ctx.request?.body;
15616
+ const id = body && typeof body === "object" && !Array.isArray(body) ? body.id : void 0;
15617
+ const extra = body && typeof body === "object" ? Object.keys(body).filter((key) => key !== "id") : [];
15618
+ if (typeof id !== "string" || !LOCK_ID_PATTERN.test(id) || extra.length > 0) {
15619
+ return sendValidationError(ctx, "Invalid lock", [
15620
+ { path: ["id"], message: "id must be a lock id from the list" }
15621
+ ]);
15622
+ }
15623
+ try {
15624
+ const lifted = await lockout().unlock(id);
15625
+ if (!lifted) return ctx.notFound("This lock has already ended");
15626
+ try {
15627
+ strapi2.plugin("magic-sessionmanager").service("security-log").record({
15628
+ event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
15629
+ actorType: "admin",
15630
+ actorId: ctx.state?.user?.id ?? null,
15631
+ targetType: lifted.kind === "account" ? "user" : "ip",
15632
+ targetId: lifted.kind === "account" ? lifted.user : null,
15633
+ ip: getRequestIp(ctx),
15634
+ userAgent: getRequestUserAgent(ctx),
15635
+ meta: { kind: lifted.kind }
15636
+ });
15637
+ } catch {
15638
+ }
15639
+ ctx.body = { data: { unlocked: true, kind: lifted.kind } };
15640
+ } catch (err) {
15641
+ log.error("[lockouts] Unlock failed:", err?.name || "Error");
15642
+ return sendServerError(ctx, 500, "The lock could not be lifted");
15643
+ }
15644
+ },
15645
+ /**
15646
+ * Users & Permissions roles for the per-role rules (the Public role has
15647
+ * no signed-in users and is left out).
15648
+ *
15649
+ * @route GET /magic-sessionmanager/roles
15650
+ * @auth admin session or admin API token
15651
+ * @access plugin::magic-sessionmanager.access
15652
+ * @param {any} ctx Koa context.
15653
+ * @returns {Promise<void>} `{ data: [{ documentId, name, type }] }`.
15654
+ */
15655
+ async roles(ctx) {
15656
+ try {
15657
+ const rows = await strapi2.db.query(ROLE_UID).findMany({
15658
+ select: ["documentId", "name", "type"],
15659
+ where: { type: { $ne: "public" } },
15660
+ orderBy: { name: "asc" },
15661
+ limit: 200
15662
+ });
15663
+ ctx.body = {
15664
+ data: (Array.isArray(rows) ? rows : []).map((role) => ({
15665
+ documentId: role.documentId,
15666
+ name: role.name,
15667
+ type: role.type
15668
+ }))
15669
+ };
15670
+ } catch (err) {
15671
+ log.error("[lockouts] Roles could not be listed:", err?.name || "Error");
15672
+ return sendServerError(ctx, 500, "Roles could not be loaded");
15673
+ }
15674
+ }
15675
+ };
15676
+ };
15677
+ }
15678
+ });
15679
+
14356
15680
  // server/src/controllers/index.js
14357
15681
  var require_controllers = __commonJS({
14358
15682
  "server/src/controllers/index.js"(exports, module) {
@@ -14362,12 +15686,14 @@ var require_controllers = __commonJS({
14362
15686
  var geoip = require_geoip();
14363
15687
  var adminSessions = require_admin_sessions2();
14364
15688
  var adminActivity = require_admin_activity();
15689
+ var lockouts = require_lockouts();
14365
15690
  module.exports = {
14366
15691
  session,
14367
15692
  settings,
14368
15693
  geoip,
14369
15694
  "admin-sessions": adminSessions,
14370
- "admin-activity": adminActivity
15695
+ "admin-activity": adminActivity,
15696
+ lockouts
14371
15697
  };
14372
15698
  }
14373
15699
  });
@@ -14382,6 +15708,7 @@ var require_session2 = __commonJS({
14382
15708
  var { resolveUserDocumentId } = require_resolve_user();
14383
15709
  var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
14384
15710
  var { getPluginSettings } = require_settings_loader();
15711
+ var { hasRoleOverride, inactivityTimeoutFor } = require_policy_settings();
14385
15712
  var {
14386
15713
  cleanupExpiredAccessTokenRevocations,
14387
15714
  persistAccessTokenRevocation
@@ -15358,12 +16685,13 @@ var require_session2 = __commonJS({
15358
16685
  const settings = await getPluginSettings(strapi2);
15359
16686
  const nativeManager = getNativeSessionManager(strapi2);
15360
16687
  const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
16688
+ const perRole = hasRoleOverride(settings, "inactivityTimeout");
15361
16689
  const now = /* @__PURE__ */ new Date();
15362
16690
  const cutoffTime = new Date(now.getTime() - inactivityTimeout);
15363
16691
  log.info(
15364
16692
  `[CLEANUP] Cleaning up sessions inactive since before ${cutoffTime.toISOString()}`
15365
16693
  );
15366
- if (useDbDirect && !nativeManager) {
16694
+ if (useDbDirect && !nativeManager && !perRole) {
15367
16695
  try {
15368
16696
  const deactivated = await strapi2.db.connection("magic_sessions").where("is_active", true).andWhere(function whereIdle() {
15369
16697
  this.where("last_active", "<", cutoffTime).orWhere(function whereNullLastActive() {
@@ -15392,7 +16720,9 @@ var require_session2 = __commonJS({
15392
16720
  const batch = await strapi2.documents(SESSION_UID).findMany({
15393
16721
  filters: { isActive: true },
15394
16722
  fields: ["documentId", "lastActive", "loginTime", "nativeSessionId"],
15395
- populate: { user: { fields: ["id", "documentId"] } },
16723
+ populate: {
16724
+ user: perRole ? { fields: ["id", "documentId"], populate: { role: { fields: ["documentId"] } } } : { fields: ["id", "documentId"] }
16725
+ },
15396
16726
  limit: BATCH,
15397
16727
  start,
15398
16728
  sort: { loginTime: "asc" }
@@ -15400,8 +16730,11 @@ var require_session2 = __commonJS({
15400
16730
  if (!batch || batch.length === 0) break;
15401
16731
  for (const session of batch) {
15402
16732
  const lastActiveTime = session.lastActive ? new Date(session.lastActive) : session.loginTime ? new Date(session.loginTime) : null;
15403
- if (lastActiveTime && lastActiveTime < cutoffTime) {
15404
- sessionsToDeactivate.push(session);
16733
+ const sessionCutoff = perRole ? new Date(
16734
+ now.getTime() - inactivityTimeoutFor(settings, session.user?.role?.documentId || null)
16735
+ ) : cutoffTime;
16736
+ if (lastActiveTime && lastActiveTime < sessionCutoff) {
16737
+ sessionsToDeactivate.push({ ...session, cutoff: sessionCutoff });
15405
16738
  }
15406
16739
  }
15407
16740
  if (batch.length < BATCH) break;
@@ -15420,8 +16753,8 @@ var require_session2 = __commonJS({
15420
16753
  documentId: session.documentId,
15421
16754
  isActive: true,
15422
16755
  $or: [
15423
- { lastActive: { $lt: cutoffTime } },
15424
- { lastActive: { $null: true }, loginTime: { $lt: cutoffTime } }
16756
+ { lastActive: { $lt: session.cutoff } },
16757
+ { lastActive: { $null: true }, loginTime: { $lt: session.cutoff } }
15425
16758
  ]
15426
16759
  };
15427
16760
  if (nativeManager) {
@@ -16456,6 +17789,29 @@ var require_notifications = __commonJS({
16456
17789
  if (geoData.isThreat) warnings.push("Threat");
16457
17790
  return warnings;
16458
17791
  }
17792
+ var POLICY_TEMPLATES = Object.freeze({
17793
+ accountLocked: Object.freeze({
17794
+ subject: "Your account was locked after failed sign-ins",
17795
+ html: `<html>
17796
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
17797
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
17798
+ <h2>Your account was temporarily locked</h2>
17799
+ <p>Hello {{user.username}},</p>
17800
+ <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>
17801
+ <p>If these attempts were not yours, change your password after the lock ends.</p>
17802
+ <p style="color: #666; font-size: 12px;">This is an automated security notification.</p>
17803
+ </div>
17804
+ </body>
17805
+ </html>`,
17806
+ text: `Your account was temporarily locked
17807
+
17808
+ Hello {{user.username}},
17809
+
17810
+ There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
17811
+
17812
+ If these attempts were not yours, change your password after the lock ends.`
17813
+ })
17814
+ });
16459
17815
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
16460
17816
  var WEBHOOK_TIMEOUT_MS = 5e3;
16461
17817
  module.exports = ({ strapi: strapi2 }) => ({
@@ -16561,9 +17917,60 @@ Account: {{user.email}}
16561
17917
  Time: {{session.loginTime}}
16562
17918
  IP: {{session.ipAddress}}
16563
17919
  VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
16564
- }
17920
+ },
17921
+ ...POLICY_TEMPLATES
16565
17922
  };
16566
17923
  },
17924
+ /**
17925
+ * One template by key. A stored template without html and text falls back
17926
+ * to the default of that key.
17927
+ *
17928
+ * @param {string} key Template key.
17929
+ * @returns {Promise<{subject: string, html: string, text: string}>} Template.
17930
+ */
17931
+ async getTemplate(key) {
17932
+ const templates = await this.getEmailTemplates();
17933
+ const template = templates?.[key];
17934
+ if (template && (template.html || template.text)) {
17935
+ return {
17936
+ subject: template.subject || POLICY_TEMPLATES[key]?.subject || "",
17937
+ html: template.html || "",
17938
+ text: template.text || ""
17939
+ };
17940
+ }
17941
+ return { ...POLICY_TEMPLATES[key] };
17942
+ },
17943
+ /**
17944
+ * Emails a user that their account was locked after failed sign-ins.
17945
+ * Sent through Strapi's email plugin, so a provider plugin such as Magic
17946
+ * Mail delivers it when installed.
17947
+ *
17948
+ * @param {{user: {email?: string, username?: string}, minutes: number, until: number}} params
17949
+ * Account, lock duration in minutes and lock end (epoch ms).
17950
+ * @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
17951
+ * @sideeffect Sends one email.
17952
+ */
17953
+ async sendAccountLockedEmail({ user, minutes, until }) {
17954
+ try {
17955
+ if (!user?.email) return false;
17956
+ const template = await this.getTemplate("accountLocked");
17957
+ const data = { user, lock: { minutes, until } };
17958
+ await strapi2.plugin("email").service("email").send({
17959
+ to: user.email,
17960
+ subject: this.replaceVariables(template.subject, data),
17961
+ html: this.replaceVariables(template.html, data),
17962
+ text: this.replaceVariables(template.text, data)
17963
+ });
17964
+ strapi2.log.info("[magic-sessionmanager/notifications] Account lock email sent");
17965
+ return true;
17966
+ } catch (err) {
17967
+ strapi2.log.error(
17968
+ "[magic-sessionmanager/notifications] Account lock email failed:",
17969
+ err?.name || "Error"
17970
+ );
17971
+ return false;
17972
+ }
17973
+ },
16567
17974
  /**
16568
17975
  * HTML-escapes a string to prevent XSS when it is interpolated into an
16569
17976
  * HTML email template. Non-string inputs are coerced to strings first.
@@ -16601,6 +18008,14 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
16601
18008
  result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
16602
18009
  result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
16603
18010
  result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
18011
+ result = result.replace(
18012
+ /\{\{lock\.minutes\}\}/g,
18013
+ esc(Number.isFinite(data.lock?.minutes) ? String(data.lock.minutes) : "N/A")
18014
+ );
18015
+ result = result.replace(
18016
+ /\{\{lock\.until\}\}/g,
18017
+ esc(Number.isFinite(data.lock?.until) ? new Date(data.lock.until).toUTCString() : "N/A")
18018
+ );
16604
18019
  const score = data.reason?.securityScore;
16605
18020
  result = result.replace(
16606
18021
  /\{\{reason\.securityScore\}\}/g,
@@ -17108,9 +18523,12 @@ var require_security_log = __commonJS({
17108
18523
  };
17109
18524
  const buildRows = async (batch, options, settings) => {
17110
18525
  const groups = /* @__PURE__ */ new Map();
18526
+ const recordUserSignIns = settings.recordUserSignInEvents !== false;
17111
18527
  const wanted = batch.filter((entry) => {
17112
18528
  const gate = recordingSwitchOf(entry.event);
17113
- return gate === "always" || (gate === "signIns" ? options.signIns : options.content);
18529
+ if (gate === "always") return true;
18530
+ if (gate === "userSignIns") return recordUserSignIns;
18531
+ return gate === "signIns" ? options.signIns : options.content;
17114
18532
  });
17115
18533
  if (!wanted.length) return { rows: [], groups };
17116
18534
  const emails = [
@@ -17596,6 +19014,29 @@ var require_security_log = __commonJS({
17596
19014
  * @returns {Promise<void>}
17597
19015
  * @sideeffect Deletes and updates rows of the security event table.
17598
19016
  */
19017
+ /**
19018
+ * Deletes what the log holds about an app user whose account was
19019
+ * deleted: events about the account and events the user caused.
19020
+ *
19021
+ * @param {string} userDocumentId Deleted user's documentId.
19022
+ * @returns {Promise<void>}
19023
+ * @sideeffect Deletes rows of the security event table.
19024
+ */
19025
+ async deleteUserData(userDocumentId) {
19026
+ const key = toId(userDocumentId);
19027
+ if (!key) return;
19028
+ queue = queue.filter(
19029
+ (entry) => !(entry.targetType === "user" && String(entry.targetId) === key) && !(entry.actorType === "user" && String(entry.actorId) === key)
19030
+ );
19031
+ await events().deleteMany({
19032
+ where: {
19033
+ $or: [
19034
+ { targetType: "user", targetId: key },
19035
+ { actorType: "user", actorId: key }
19036
+ ]
19037
+ }
19038
+ });
19039
+ },
17599
19040
  async deleteAdminData(adminId) {
17600
19041
  const id = toAdminId(adminId);
17601
19042
  if (!id) return;