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
@@ -126,6 +126,11 @@ var require_coordination = __commonJS({
126
126
  throw new TypeError("coordination key must be a non-empty string of at most 191 characters");
127
127
  }
128
128
  }
129
+ function assertRegistryKey(key) {
130
+ if (typeof key !== "string" || !/^[a-z0-9:-]{1,180}$/.test(key)) {
131
+ throw new TypeError('registry key must be 1-180 lowercase letters, digits, ":" or "-"');
132
+ }
133
+ }
129
134
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
130
135
  var LockTimeoutError = class extends Error {
131
136
  constructor(name) {
@@ -138,6 +143,7 @@ var require_coordination = __commonJS({
138
143
  const leases = /* @__PURE__ */ new Map();
139
144
  const revisions = /* @__PURE__ */ new Map();
140
145
  const lockTails = /* @__PURE__ */ new Map();
146
+ const registry = /* @__PURE__ */ new Map();
141
147
  const pruneCounters = (now) => {
142
148
  if (counters.size < 5e3) return;
143
149
  for (const [k, v] of counters) {
@@ -167,13 +173,14 @@ var require_coordination = __commonJS({
167
173
  if (!entry) return null;
168
174
  return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
169
175
  },
170
- async block(key, untilMs) {
176
+ async block(key, untilMs, { windowStart } = {}) {
171
177
  const entry = counters.get(key) || {
172
178
  hits: 0,
173
179
  windowStart: 0,
174
180
  blockedUntil: 0,
175
181
  expiresAt: 0
176
182
  };
183
+ if (Number.isFinite(windowStart)) entry.windowStart = windowStart;
177
184
  if (entry.blockedUntil < untilMs) entry.blockedUntil = untilMs;
178
185
  entry.expiresAt = Math.max(entry.expiresAt, untilMs);
179
186
  counters.set(key, entry);
@@ -228,8 +235,28 @@ var require_coordination = __commonJS({
228
235
  },
229
236
  async cacheSet() {
230
237
  },
238
+ async registryPut(key, value, ttlMs, now = Date.now()) {
239
+ registry.set(key, { value, expiresAt: now + ttlMs });
240
+ },
241
+ async registryList(prefix, limit = 200, now = Date.now()) {
242
+ const out = [];
243
+ for (const [key, entry] of registry) {
244
+ if (entry.expiresAt <= now) {
245
+ registry.delete(key);
246
+ continue;
247
+ }
248
+ if (key.startsWith(prefix) && out.length < limit) out.push({ key, value: entry.value });
249
+ }
250
+ return out;
251
+ },
252
+ async registryDelete(key) {
253
+ registry.delete(key);
254
+ },
231
255
  async prune(now = Date.now()) {
232
256
  let removed = 0;
257
+ for (const [k, v] of registry) {
258
+ if (v.expiresAt <= now) registry.delete(k);
259
+ }
233
260
  for (const [k, v] of counters) {
234
261
  if (v.expiresAt <= now && v.blockedUntil <= now) {
235
262
  counters.delete(k);
@@ -243,6 +270,7 @@ var require_coordination = __commonJS({
243
270
  leases.clear();
244
271
  revisions.clear();
245
272
  lockTails.clear();
273
+ registry.clear();
246
274
  }
247
275
  };
248
276
  }
@@ -384,14 +412,18 @@ var require_coordination = __commonJS({
384
412
  await knex(TABLES.counters).where({ k: key }).andWhere("hits", ">", 0).update({ hits: knex.raw("hits - 1") });
385
413
  },
386
414
  peek: readCounter,
387
- async block(key, untilMs) {
415
+ async block(key, untilMs, { windowStart } = {}) {
388
416
  await ensureCounterRow(key, untilMs);
389
417
  await knex(TABLES.counters).where({ k: key }).andWhere("blocked_until", "<", untilMs).update({
390
418
  blocked_until: untilMs,
391
419
  expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
392
420
  untilMs,
393
421
  untilMs
394
- ])
422
+ ]),
423
+ // Moves the counting window so it ends when the lock ends: the
424
+ // hits stay (requests already in flight are still turned away),
425
+ // and the first attempt after the lock starts a new window.
426
+ ...Number.isFinite(windowStart) ? { window_start: Math.trunc(windowStart) } : {}
395
427
  });
396
428
  },
397
429
  async clear(key) {
@@ -469,6 +501,27 @@ var require_coordination = __commonJS({
469
501
  const expiresAt = ttlMs === Infinity ? NEVER_EXPIRES : now + ttlMs;
470
502
  await knex(TABLES.cache).insert({ k: key, v: JSON.stringify(value), expires_at: expiresAt }).onConflict("k").merge(["v", "expires_at"]);
471
503
  },
504
+ /**
505
+ * Listable entries live in the cache table under their own key prefix
506
+ * (`reg:`), so they share its expiry index and pruning.
507
+ */
508
+ async registryPut(key, value, ttlMs, now = Date.now()) {
509
+ await knex(TABLES.cache).insert({ k: `reg:${key}`, v: JSON.stringify(value), expires_at: now + ttlMs }).onConflict("k").merge(["v", "expires_at"]);
510
+ },
511
+ async registryList(prefix, limit = 200, now = Date.now()) {
512
+ const rows = await knex(TABLES.cache).select("k", "v").where("k", "like", `reg:${prefix}%`).andWhere("expires_at", ">", now).orderBy("k", "asc").limit(limit);
513
+ const out = [];
514
+ for (const row of rows) {
515
+ try {
516
+ out.push({ key: String(row.k).slice(4), value: JSON.parse(row.v) });
517
+ } catch {
518
+ }
519
+ }
520
+ return out;
521
+ },
522
+ async registryDelete(key) {
523
+ await knex(TABLES.cache).where({ k: `reg:${key}` }).del();
524
+ },
472
525
  async prune(now = Date.now()) {
473
526
  const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
474
527
  const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
@@ -549,10 +602,17 @@ var require_coordination = __commonJS({
549
602
  assertKey(key);
550
603
  return counterCall("counter read", "peek", [key]);
551
604
  },
552
- /** Raises the block deadline of `key` to `untilMs` (never lowers it). */
553
- block(key, untilMs) {
605
+ /**
606
+ * Raises the block deadline of `key` to `untilMs` (never lowers it).
607
+ * With `windowStart` the counting window is moved (see the lockout).
608
+ */
609
+ block(key, untilMs, options) {
554
610
  assertKey(key);
555
- return counterCall("counter block", "block", [key, untilMs]);
611
+ return counterCall(
612
+ "counter block",
613
+ "block",
614
+ options ? [key, untilMs, options] : [key, untilMs]
615
+ );
556
616
  },
557
617
  /** Removes counter `key`. */
558
618
  clear(key) {
@@ -652,6 +712,51 @@ var require_coordination = __commonJS({
652
712
  () => sharedMemory.cacheSet(key, value, ttlMs)
653
713
  );
654
714
  },
715
+ /**
716
+ * Stores a listable entry (for example an active sign-in lock) until
717
+ * `ttlMs` from now. Unlike the cache it also works in memory mode, and
718
+ * entries can be listed by key prefix. Keys use lowercase letters,
719
+ * digits, `:` and `-` only, so they are free of LIKE wildcards.
720
+ *
721
+ * @param {string} key Entry key (at most 180 characters).
722
+ * @param {unknown} value JSON-serialisable value.
723
+ * @param {number} ttlMs Lifetime in milliseconds.
724
+ * @returns {Promise<void>}
725
+ */
726
+ registryPut(key, value, ttlMs) {
727
+ assertRegistryKey(key);
728
+ return run(
729
+ "registry write",
730
+ (backend) => backend.registryPut(key, value, ttlMs),
731
+ () => sharedMemory.registryPut(key, value, ttlMs)
732
+ );
733
+ },
734
+ /**
735
+ * Unexpired entries whose key starts with `prefix`, ordered by key.
736
+ *
737
+ * @param {string} prefix Key prefix (letters, digits, `:` and `-` only).
738
+ * @param {number} [limit] Most entries returned.
739
+ * @returns {Promise<Array<{key: string, value: any}>>}
740
+ */
741
+ registryList(prefix, limit = 200) {
742
+ if (typeof prefix !== "string" || !/^[a-z0-9:-]{1,180}$/.test(prefix)) {
743
+ throw new TypeError('registry prefix must be letters, digits, ":" or "-"');
744
+ }
745
+ return run(
746
+ "registry read",
747
+ (backend) => backend.registryList(prefix, limit),
748
+ () => sharedMemory.registryList(prefix, limit)
749
+ );
750
+ },
751
+ /** Removes a listable entry. */
752
+ registryDelete(key) {
753
+ assertRegistryKey(key);
754
+ return run(
755
+ "registry delete",
756
+ (backend) => backend.registryDelete(key),
757
+ () => sharedMemory.registryDelete(key)
758
+ );
759
+ },
655
760
  prune() {
656
761
  return run(
657
762
  "prune",
@@ -984,11 +1089,359 @@ var require_security_log_settings = __commonJS({
984
1089
  }
985
1090
  });
986
1091
 
1092
+ // server/src/utils/policy-settings.js
1093
+ var require_policy_settings = __commonJS({
1094
+ "server/src/utils/policy-settings.js"(exports2, module2) {
1095
+ "use strict";
1096
+ var net = require("node:net");
1097
+ var POLICY_DEFAULTS = Object.freeze({
1098
+ maxFailedLoginsPerAccount: 0,
1099
+ lockoutWindowMinutes: 15,
1100
+ lockoutDurationMinutes: 15,
1101
+ lockoutTrustedAddresses: Object.freeze([]),
1102
+ lockoutNotifyUser: false,
1103
+ recordUserSignInEvents: true,
1104
+ maxSessionsPerUser: 0,
1105
+ sessionLimitPolicy: "end-oldest",
1106
+ endOtherSessionsOnPasswordChange: true,
1107
+ roleRules: Object.freeze([])
1108
+ });
1109
+ var POLICY_KEYS = Object.freeze(Object.keys(POLICY_DEFAULTS));
1110
+ var POLICY_RANGES = Object.freeze({
1111
+ maxFailedLoginsPerAccount: Object.freeze([0, 100]),
1112
+ lockoutWindowMinutes: Object.freeze([1, 1440]),
1113
+ lockoutDurationMinutes: Object.freeze([1, 10080]),
1114
+ maxSessionsPerUser: Object.freeze([0, 100])
1115
+ });
1116
+ var ROLE_RULE_RANGES = Object.freeze({
1117
+ maxSessionsPerUser: Object.freeze([0, 100]),
1118
+ inactivityTimeout: Object.freeze([1, 1440]),
1119
+ maxFailedLoginsPerAccount: Object.freeze([0, 100])
1120
+ });
1121
+ var ROLE_RULE_FIELDS = Object.freeze(Object.keys(ROLE_RULE_RANGES));
1122
+ var SESSION_LIMIT_POLICIES = Object.freeze(["end-oldest", "refuse"]);
1123
+ var BOOLEAN_KEYS = Object.freeze([
1124
+ "lockoutNotifyUser",
1125
+ "recordUserSignInEvents",
1126
+ "endOtherSessionsOnPasswordChange"
1127
+ ]);
1128
+ var MAX_TRUSTED_ADDRESSES = 100;
1129
+ var MAX_ROLE_RULES = 50;
1130
+ var ROLE_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1131
+ function parseInteger(value) {
1132
+ if (typeof value === "number") return Number.isInteger(value) ? value : null;
1133
+ if (typeof value === "string" && /^\s*-?\d{1,9}\s*$/.test(value)) {
1134
+ return Number.parseInt(value, 10);
1135
+ }
1136
+ return null;
1137
+ }
1138
+ function parseTrustedAddress(value) {
1139
+ if (typeof value !== "string") return null;
1140
+ const text = value.trim();
1141
+ if (!text || text.length > 64) return null;
1142
+ const [rawAddress, rawPrefix, extra] = text.split("/");
1143
+ if (extra !== void 0) return null;
1144
+ let address = rawAddress;
1145
+ if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
1146
+ address = address.slice(7);
1147
+ }
1148
+ const version = net.isIP(address);
1149
+ if (version === 0) return null;
1150
+ const family = version === 4 ? "ipv4" : "ipv6";
1151
+ if (rawPrefix === void 0) {
1152
+ return { text: address.toLowerCase(), address, prefix: null, family };
1153
+ }
1154
+ if (!/^\d{1,3}$/.test(rawPrefix)) return null;
1155
+ const prefix = Number(rawPrefix);
1156
+ if (prefix > (family === "ipv4" ? 32 : 128)) return null;
1157
+ return { text: `${address.toLowerCase()}/${prefix}`, address, prefix, family };
1158
+ }
1159
+ var blockListCache = /* @__PURE__ */ new Map();
1160
+ function trustedAddressList(entries) {
1161
+ const key = entries.join("\n");
1162
+ const cached = blockListCache.get(key);
1163
+ if (cached) return cached;
1164
+ const list = new net.BlockList();
1165
+ for (const entry of entries) {
1166
+ const parsed = parseTrustedAddress(entry);
1167
+ if (!parsed) continue;
1168
+ if (parsed.prefix === null) list.addAddress(parsed.address, parsed.family);
1169
+ else list.addSubnet(parsed.address, parsed.prefix, parsed.family);
1170
+ }
1171
+ if (blockListCache.size > 20) blockListCache.clear();
1172
+ blockListCache.set(key, list);
1173
+ return list;
1174
+ }
1175
+ function isTrustedAddress(entries, ip) {
1176
+ if (!entries.length || typeof ip !== "string") return false;
1177
+ let address = ip.trim();
1178
+ if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
1179
+ address = address.slice(7);
1180
+ }
1181
+ const version = net.isIP(address);
1182
+ if (version === 0) return false;
1183
+ try {
1184
+ return trustedAddressList(entries).check(address, version === 4 ? "ipv4" : "ipv6");
1185
+ } catch {
1186
+ return false;
1187
+ }
1188
+ }
1189
+ function normalizeRoleRules(value) {
1190
+ if (!Array.isArray(value)) return [];
1191
+ const seen = /* @__PURE__ */ new Set();
1192
+ const out = [];
1193
+ for (const raw of value.slice(0, MAX_ROLE_RULES)) {
1194
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
1195
+ const role = typeof raw.role === "string" ? raw.role : "";
1196
+ if (!ROLE_ID_PATTERN.test(role) || seen.has(role)) continue;
1197
+ const rule = { role };
1198
+ for (const field of ROLE_RULE_FIELDS) {
1199
+ const [min, max] = (
1200
+ /** @type {any} */
1201
+ ROLE_RULE_RANGES[field]
1202
+ );
1203
+ const number = raw[field] === null || raw[field] === void 0 ? null : parseInteger(raw[field]);
1204
+ rule[field] = number !== null && number >= min && number <= max ? number : null;
1205
+ }
1206
+ seen.add(role);
1207
+ out.push(rule);
1208
+ }
1209
+ return out;
1210
+ }
1211
+ function normalizePolicySettings(stored) {
1212
+ const out = {};
1213
+ if (!stored || typeof stored !== "object") return out;
1214
+ for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
1215
+ if (stored[key] === void 0) continue;
1216
+ const number = parseInteger(stored[key]);
1217
+ out[key] = number !== null && number >= min && number <= max ? number : (
1218
+ /** @type {any} */
1219
+ POLICY_DEFAULTS[key]
1220
+ );
1221
+ }
1222
+ for (const key of BOOLEAN_KEYS) {
1223
+ if (stored[key] !== void 0) out[key] = stored[key] === true;
1224
+ }
1225
+ if (stored.sessionLimitPolicy !== void 0) {
1226
+ out.sessionLimitPolicy = SESSION_LIMIT_POLICIES.includes(
1227
+ /** @type {string} */
1228
+ stored.sessionLimitPolicy
1229
+ ) ? stored.sessionLimitPolicy : POLICY_DEFAULTS.sessionLimitPolicy;
1230
+ }
1231
+ if (stored.lockoutTrustedAddresses !== void 0) {
1232
+ out.lockoutTrustedAddresses = Array.isArray(stored.lockoutTrustedAddresses) ? stored.lockoutTrustedAddresses.slice(0, MAX_TRUSTED_ADDRESSES).map(parseTrustedAddress).filter(Boolean).map((entry) => (
1233
+ /** @type {any} */
1234
+ entry.text
1235
+ )) : [];
1236
+ }
1237
+ if (stored.roleRules !== void 0) out.roleRules = normalizeRoleRules(stored.roleRules);
1238
+ return out;
1239
+ }
1240
+ function validatePolicySettings(body) {
1241
+ const values = {};
1242
+ const errors = [];
1243
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
1244
+ for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
1245
+ if (!has(key)) continue;
1246
+ const number = parseInteger(body[key]);
1247
+ if (number === null || number < min || number > max) {
1248
+ errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
1249
+ } else {
1250
+ values[key] = number;
1251
+ }
1252
+ }
1253
+ for (const key of BOOLEAN_KEYS) {
1254
+ if (!has(key)) continue;
1255
+ if (typeof body[key] !== "boolean") {
1256
+ errors.push({ path: [key], message: `${key} must be a boolean` });
1257
+ } else {
1258
+ values[key] = body[key];
1259
+ }
1260
+ }
1261
+ if (has("sessionLimitPolicy")) {
1262
+ if (!SESSION_LIMIT_POLICIES.includes(
1263
+ /** @type {string} */
1264
+ body.sessionLimitPolicy
1265
+ )) {
1266
+ errors.push({
1267
+ path: ["sessionLimitPolicy"],
1268
+ message: `sessionLimitPolicy must be one of: ${SESSION_LIMIT_POLICIES.join(", ")}`
1269
+ });
1270
+ } else {
1271
+ values.sessionLimitPolicy = body.sessionLimitPolicy;
1272
+ }
1273
+ }
1274
+ if (has("lockoutTrustedAddresses")) {
1275
+ const list = body.lockoutTrustedAddresses;
1276
+ if (!Array.isArray(list) || list.length > MAX_TRUSTED_ADDRESSES) {
1277
+ errors.push({
1278
+ path: ["lockoutTrustedAddresses"],
1279
+ message: `lockoutTrustedAddresses must be a list of at most ${MAX_TRUSTED_ADDRESSES} IP addresses or CIDR ranges`
1280
+ });
1281
+ } else {
1282
+ const parsed = list.map(parseTrustedAddress);
1283
+ const invalid = parsed.findIndex((entry) => entry === null);
1284
+ if (invalid !== -1) {
1285
+ errors.push({
1286
+ path: ["lockoutTrustedAddresses", invalid],
1287
+ message: "Each trusted address must be an IP address or a CIDR range such as 192.0.2.0/24"
1288
+ });
1289
+ } else {
1290
+ values.lockoutTrustedAddresses = [
1291
+ ...new Set(parsed.map((entry) => (
1292
+ /** @type {any} */
1293
+ entry.text
1294
+ )))
1295
+ ];
1296
+ }
1297
+ }
1298
+ }
1299
+ if (has("roleRules")) {
1300
+ const rules = body.roleRules;
1301
+ if (!Array.isArray(rules) || rules.length > MAX_ROLE_RULES) {
1302
+ errors.push({
1303
+ path: ["roleRules"],
1304
+ message: `roleRules must be a list of at most ${MAX_ROLE_RULES} rules`
1305
+ });
1306
+ } else {
1307
+ const seen = /* @__PURE__ */ new Set();
1308
+ const clean = [];
1309
+ rules.forEach((raw, index) => {
1310
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1311
+ errors.push({ path: ["roleRules", index], message: "A role rule must be an object" });
1312
+ return;
1313
+ }
1314
+ const role = raw.role;
1315
+ if (typeof role !== "string" || !ROLE_ID_PATTERN.test(role)) {
1316
+ errors.push({ path: ["roleRules", index, "role"], message: "Choose a role" });
1317
+ return;
1318
+ }
1319
+ if (seen.has(role)) {
1320
+ errors.push({
1321
+ path: ["roleRules", index, "role"],
1322
+ message: "This role already has a rule"
1323
+ });
1324
+ return;
1325
+ }
1326
+ seen.add(role);
1327
+ const rule = { role };
1328
+ let overrides = 0;
1329
+ for (const field of ROLE_RULE_FIELDS) {
1330
+ const [min, max] = (
1331
+ /** @type {any} */
1332
+ ROLE_RULE_RANGES[field]
1333
+ );
1334
+ const rawValue = raw[field];
1335
+ if (rawValue === null || rawValue === void 0 || rawValue === "") {
1336
+ rule[field] = null;
1337
+ continue;
1338
+ }
1339
+ const number = parseInteger(rawValue);
1340
+ if (number === null || number < min || number > max) {
1341
+ errors.push({
1342
+ path: ["roleRules", index, field],
1343
+ message: `${field} must be empty or an integer between ${min} and ${max}`
1344
+ });
1345
+ continue;
1346
+ }
1347
+ rule[field] = number;
1348
+ overrides += 1;
1349
+ }
1350
+ if (overrides === 0 && !errors.some((e) => e.path[1] === index)) {
1351
+ errors.push({
1352
+ path: ["roleRules", index],
1353
+ message: "A role rule needs at least one value"
1354
+ });
1355
+ return;
1356
+ }
1357
+ clean.push(rule);
1358
+ });
1359
+ if (!errors.some((e) => e.path[0] === "roleRules")) values.roleRules = clean;
1360
+ }
1361
+ }
1362
+ return { values, errors };
1363
+ }
1364
+ function policyValue(settings, key) {
1365
+ const source = settings && typeof settings === "object" ? settings : {};
1366
+ const clean = normalizePolicySettings({ [key]: source[key] });
1367
+ return clean[key] !== void 0 ? clean[key] : POLICY_DEFAULTS[key];
1368
+ }
1369
+ function roleRuleFor(settings, roleDocumentId) {
1370
+ if (!roleDocumentId) return null;
1371
+ const rules = (
1372
+ /** @type {any[]} */
1373
+ policyValue(settings, "roleRules")
1374
+ );
1375
+ return rules.find((rule) => rule.role === roleDocumentId) || null;
1376
+ }
1377
+ function hasRoleOverride(settings, field) {
1378
+ const rules = (
1379
+ /** @type {any[]} */
1380
+ policyValue(settings, "roleRules")
1381
+ );
1382
+ return rules.some((rule) => rule[field] !== null && rule[field] !== void 0);
1383
+ }
1384
+ function resolveLockoutPolicy(settings) {
1385
+ const source = settings && typeof settings === "object" ? settings : {};
1386
+ const ipRaw = parseInteger(source.maxFailedLogins);
1387
+ return {
1388
+ ipMax: ipRaw !== null && ipRaw >= 0 && ipRaw <= 100 ? ipRaw : 0,
1389
+ accountMax: policyValue(source, "maxFailedLoginsPerAccount"),
1390
+ accountMaxByRole: hasRoleOverride(source, "maxFailedLoginsPerAccount"),
1391
+ windowMs: policyValue(source, "lockoutWindowMinutes") * 60 * 1e3,
1392
+ durationMs: policyValue(source, "lockoutDurationMinutes") * 60 * 1e3,
1393
+ trusted: policyValue(source, "lockoutTrustedAddresses"),
1394
+ notifyUser: policyValue(source, "lockoutNotifyUser"),
1395
+ record: policyValue(source, "recordUserSignInEvents")
1396
+ };
1397
+ }
1398
+ function accountThresholdFor(settings, roleDocumentId) {
1399
+ const rule = roleRuleFor(settings, roleDocumentId);
1400
+ if (rule && rule.maxFailedLoginsPerAccount !== null) return rule.maxFailedLoginsPerAccount;
1401
+ return policyValue(settings, "maxFailedLoginsPerAccount");
1402
+ }
1403
+ function sessionLimitFor(settings, roleDocumentId) {
1404
+ const rule = roleRuleFor(settings, roleDocumentId);
1405
+ const limit = rule && rule.maxSessionsPerUser !== null ? rule.maxSessionsPerUser : policyValue(settings, "maxSessionsPerUser");
1406
+ return { limit, policy: policyValue(settings, "sessionLimitPolicy") };
1407
+ }
1408
+ function inactivityTimeoutFor(settings, roleDocumentId) {
1409
+ const rule = roleRuleFor(settings, roleDocumentId);
1410
+ if (rule && rule.inactivityTimeout !== null) return rule.inactivityTimeout * 60 * 1e3;
1411
+ const general = Number(settings?.inactivityTimeout);
1412
+ return Number.isFinite(general) && general > 0 ? general : 15 * 60 * 1e3;
1413
+ }
1414
+ module2.exports = {
1415
+ POLICY_DEFAULTS,
1416
+ POLICY_KEYS,
1417
+ POLICY_RANGES,
1418
+ ROLE_RULE_FIELDS,
1419
+ ROLE_RULE_RANGES,
1420
+ SESSION_LIMIT_POLICIES,
1421
+ MAX_ROLE_RULES,
1422
+ MAX_TRUSTED_ADDRESSES,
1423
+ accountThresholdFor,
1424
+ hasRoleOverride,
1425
+ inactivityTimeoutFor,
1426
+ isTrustedAddress,
1427
+ normalizePolicySettings,
1428
+ normalizeRoleRules,
1429
+ parseTrustedAddress,
1430
+ policyValue,
1431
+ resolveLockoutPolicy,
1432
+ roleRuleFor,
1433
+ sessionLimitFor,
1434
+ validatePolicySettings
1435
+ };
1436
+ }
1437
+ });
1438
+
987
1439
  // server/src/utils/settings-loader.js
988
1440
  var require_settings_loader = __commonJS({
989
1441
  "server/src/utils/settings-loader.js"(exports2, module2) {
990
1442
  "use strict";
991
1443
  var { getCoordinator } = require_coordination();
1444
+ var { normalizePolicySettings } = require_policy_settings();
992
1445
  var PLUGIN_ID = "magic-sessionmanager";
993
1446
  var SETTINGS_KEY = "settings";
994
1447
  var CACHE_TTL_MS = 30 * 1e3;
@@ -1120,6 +1573,7 @@ var require_settings_loader = __commonJS({
1120
1573
  if (stored.trustedProxies !== void 0) {
1121
1574
  out.trustedProxies = stored.trustedProxies;
1122
1575
  }
1576
+ Object.assign(out, normalizePolicySettings(stored));
1123
1577
  return out;
1124
1578
  }
1125
1579
  async function getPluginSettings(strapi2) {
@@ -1230,7 +1684,14 @@ var require_security_log_model = __commonJS({
1230
1684
  // 4.17: always recorded (no switch), never values.
1231
1685
  SETTINGS_UPDATED: "settings.updated",
1232
1686
  LOG_RETENTION_PURGED: "security-log.retention.purged",
1233
- LOG_READ: "security-log.read"
1687
+ LOG_READ: "security-log.read",
1688
+ // App users (Users & Permissions), 4.17.
1689
+ USER_SIGN_IN_FAILED: "user.sign-in.failed",
1690
+ USER_SIGN_IN_REFUSED: "user.sign-in.refused",
1691
+ USER_LOCKOUT: "user.lockout",
1692
+ USER_LOCKOUT_LIFTED: "user.lockout.lifted",
1693
+ USER_SESSION_LIMIT: "user.session.limit",
1694
+ USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others"
1234
1695
  });
1235
1696
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
1236
1697
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
@@ -1238,7 +1699,7 @@ var require_security_log_model = __commonJS({
1238
1699
  SECURITY_EVENTS.LOG_READ
1239
1700
  ]);
1240
1701
  function dropRankOf(event) {
1241
- if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
1702
+ if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
1242
1703
  return { rank: 0, family: "failed" };
1243
1704
  }
1244
1705
  if (event === SECURITY_EVENTS.ADMIN_CONTENT_VIEW) return { rank: 1, family: "content-view" };
@@ -1247,6 +1708,19 @@ var require_security_log_model = __commonJS({
1247
1708
  }
1248
1709
  return { rank: 3, family: "account" };
1249
1710
  }
1711
+ var USER_SIGN_IN_EVENTS = Object.freeze([
1712
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
1713
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
1714
+ SECURITY_EVENTS.USER_LOCKOUT
1715
+ ]);
1716
+ var REFUSAL_REASONS = Object.freeze([
1717
+ "lockout",
1718
+ "too-many-attempts",
1719
+ "session-limit",
1720
+ "country",
1721
+ "risk",
1722
+ "location-unavailable"
1723
+ ]);
1250
1724
  var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
1251
1725
  var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
1252
1726
  var ADMIN_SIGN_IN_EVENTS = Object.freeze([
@@ -1277,6 +1751,7 @@ var require_security_log_model = __commonJS({
1277
1751
  function recordingSwitchOf(event) {
1278
1752
  if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
1279
1753
  if (event.startsWith("admin.content.")) return "content";
1754
+ if (USER_SIGN_IN_EVENTS.includes(event)) return "userSignIns";
1280
1755
  return "always";
1281
1756
  }
1282
1757
  var CONTENT_MANAGER_HANDLERS = Object.freeze({
@@ -1457,6 +1932,8 @@ var require_security_log_model = __commonJS({
1457
1932
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
1458
1933
  }
1459
1934
  module2.exports = {
1935
+ REFUSAL_REASONS,
1936
+ USER_SIGN_IN_EVENTS,
1460
1937
  ACTOR_TYPES,
1461
1938
  ADMIN_CONTENT_EVENTS,
1462
1939
  ADMIN_SIGN_IN_EVENTS,
@@ -1715,10 +2192,19 @@ var require_register = __commonJS({
1715
2192
  // secrets) and the security log. The other settings stay on `access`.
1716
2193
  {
1717
2194
  section: "plugins",
1718
- displayName: "Change protected settings (location lookup, webhooks, security log)",
2195
+ displayName: "Change protected settings (location lookup, webhooks, security log, sign-in policies)",
1719
2196
  uid: "settings.update",
1720
2197
  subCategory: "Settings",
1721
2198
  pluginName: "magic-sessionmanager"
2199
+ },
2200
+ // Lifting a sign-in lock of an app user or IP address (4.17). Seeing the
2201
+ // locks only needs plugin access.
2202
+ {
2203
+ section: "plugins",
2204
+ displayName: "Unlock locked sign-ins",
2205
+ uid: "lockouts.unlock",
2206
+ subCategory: "General",
2207
+ pluginName: "magic-sessionmanager"
1722
2208
  }
1723
2209
  ]);
1724
2210
  disableGraphqlShadowCrud(strapi2, log);
@@ -1769,6 +2255,20 @@ var require_register = __commonJS({
1769
2255
  } catch (err) {
1770
2256
  log.warn("[lifecycle] afterUpdate hook failed:", err?.name || "Error");
1771
2257
  }
2258
+ },
2259
+ /**
2260
+ * Deleting an app user deletes what the security log holds about them.
2261
+ *
2262
+ * @param {object} event
2263
+ */
2264
+ async afterDelete(event) {
2265
+ try {
2266
+ const documentId = event?.result?.documentId;
2267
+ if (!documentId) return;
2268
+ await strapi2.plugin("magic-sessionmanager").service("security-log").deleteUserData(documentId);
2269
+ } catch (err) {
2270
+ log.warn("[lifecycle] Security events of a deleted user stay:", err?.name || "Error");
2271
+ }
1772
2272
  }
1773
2273
  });
1774
2274
  log.info("[SUCCESS] Plugin registered successfully");
@@ -3508,6 +4008,425 @@ var require_admin_activity_capture = __commonJS({
3508
4008
  }
3509
4009
  });
3510
4010
 
4011
+ // server/src/utils/login-lockout.js
4012
+ var require_login_lockout = __commonJS({
4013
+ "server/src/utils/login-lockout.js"(exports2, module2) {
4014
+ "use strict";
4015
+ var { hashedKey } = require_coordination();
4016
+ var { isTrustedAddress } = require_policy_settings();
4017
+ var LOCK_PREFIX = "lock:";
4018
+ var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
4019
+ var MAX_LISTED_LOCKS = 200;
4020
+ function normalizeIdentifier(identifier) {
4021
+ if (typeof identifier !== "string") return null;
4022
+ const value = identifier.trim().toLowerCase();
4023
+ if (!value || value.length > 254) return null;
4024
+ return value;
4025
+ }
4026
+ var ipKey = (ip) => hashedKey("lf", ip);
4027
+ var accountKey = (identifier) => hashedKey("la", identifier);
4028
+ function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
4029
+ const remainingSeconds = async (key) => {
4030
+ if (!key) return 0;
4031
+ const entry = await coordinator.peek(key);
4032
+ const until = Number(entry?.blockedUntil) || 0;
4033
+ const left = until - now();
4034
+ return left > 0 ? Math.ceil(left / 1e3) : 0;
4035
+ };
4036
+ const release = async (reservation) => {
4037
+ if (reservation.ipKey) await coordinator.release(reservation.ipKey);
4038
+ if (reservation.accountKey) await coordinator.release(reservation.accountKey);
4039
+ };
4040
+ return {
4041
+ normalizeIdentifier,
4042
+ /**
4043
+ * Checks the locks and counts the attempt before the password check.
4044
+ *
4045
+ * @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
4046
+ * accountMax: number}} input Client IP, normalised identifier, policy and the
4047
+ * account threshold for this account's role.
4048
+ * @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
4049
+ * lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
4050
+ * @sideeffect Increments the shared counters.
4051
+ */
4052
+ async reserve({ ip, identifier, policy, accountMax }) {
4053
+ const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
4054
+ const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
4055
+ const reservation = {
4056
+ ipKey: countIp ? ipKey(
4057
+ /** @type {string} */
4058
+ ip
4059
+ ) : null,
4060
+ ipHits: 0,
4061
+ accountKey: countAccount ? accountKey(
4062
+ /** @type {string} */
4063
+ identifier
4064
+ ) : null,
4065
+ accountHits: 0
4066
+ };
4067
+ if (!reservation.ipKey && !reservation.accountKey) {
4068
+ return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
4069
+ }
4070
+ const [ipLeft, accountLeft] = await Promise.all([
4071
+ remainingSeconds(reservation.ipKey),
4072
+ remainingSeconds(reservation.accountKey)
4073
+ ]);
4074
+ if (ipLeft > 0 || accountLeft > 0) {
4075
+ return {
4076
+ outcome: "locked",
4077
+ retryAfter: Math.max(ipLeft, accountLeft),
4078
+ lockedKind: accountLeft >= ipLeft && accountLeft > 0 ? "account" : "ip",
4079
+ reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
4080
+ };
4081
+ }
4082
+ if (reservation.ipKey) {
4083
+ reservation.ipHits = (await coordinator.hit(reservation.ipKey, policy.windowMs)).hits;
4084
+ }
4085
+ if (reservation.accountKey) {
4086
+ reservation.accountHits = (await coordinator.hit(reservation.accountKey, policy.windowMs)).hits;
4087
+ }
4088
+ if (reservation.ipKey && reservation.ipHits > policy.ipMax || reservation.accountKey && reservation.accountHits > accountMax) {
4089
+ await release(reservation);
4090
+ return { outcome: "busy", retryAfter: 1, lockedKind: null, reservation };
4091
+ }
4092
+ return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
4093
+ },
4094
+ /**
4095
+ * Records the result of the sign-in.
4096
+ *
4097
+ * @param {Reservation} reservation From `reserve`.
4098
+ * @param {'success'|'failure'|'neutral'} result Outcome of the handler.
4099
+ * @param {{policy: LockoutPolicy, accountMax: number, display?: LockDisplay}} options
4100
+ * Policy, account threshold and what the lock list shows.
4101
+ * @returns {Promise<Array<{kind: 'ip'|'account', id: string, failures: number, until: number}>>}
4102
+ * Locks this request created.
4103
+ * @sideeffect Clears, releases or blocks shared counters; writes lock entries.
4104
+ */
4105
+ async settle(reservation, result, { policy, accountMax, display = {} }) {
4106
+ if (result === "success") {
4107
+ for (const key of [reservation.ipKey, reservation.accountKey]) {
4108
+ if (!key) continue;
4109
+ await coordinator.clear(key);
4110
+ }
4111
+ return [];
4112
+ }
4113
+ if (result !== "failure") {
4114
+ await release(reservation);
4115
+ return [];
4116
+ }
4117
+ const locks = [];
4118
+ const until = now() + policy.durationMs;
4119
+ const candidates = [
4120
+ reservation.ipKey && reservation.ipHits >= policy.ipMax ? {
4121
+ kind: (
4122
+ /** @type {const} */
4123
+ "ip"
4124
+ ),
4125
+ id: reservation.ipKey,
4126
+ failures: reservation.ipHits
4127
+ } : null,
4128
+ reservation.accountKey && reservation.accountHits >= accountMax ? {
4129
+ kind: (
4130
+ /** @type {const} */
4131
+ "account"
4132
+ ),
4133
+ id: reservation.accountKey,
4134
+ failures: reservation.accountHits
4135
+ } : null
4136
+ ];
4137
+ for (const lock of candidates) {
4138
+ if (!lock) continue;
4139
+ await coordinator.block(lock.id, until, { windowStart: until - policy.windowMs });
4140
+ await coordinator.registryPut(
4141
+ `${LOCK_PREFIX}${lock.id}`,
4142
+ {
4143
+ kind: lock.kind,
4144
+ ip: lock.kind === "ip" ? display.ip || null : null,
4145
+ user: lock.kind === "account" ? display.userDocumentId || null : null,
4146
+ failures: lock.failures,
4147
+ lockedAt: now(),
4148
+ until
4149
+ },
4150
+ policy.durationMs
4151
+ );
4152
+ locks.push({ ...lock, until });
4153
+ }
4154
+ return locks;
4155
+ },
4156
+ /**
4157
+ * Active locks, soonest end last.
4158
+ *
4159
+ * @returns {Promise<Array<{id: string, kind: 'ip'|'account', ip: string|null,
4160
+ * user: string|null, failures: number, lockedAt: number, until: number}>>} Locks.
4161
+ */
4162
+ async listLocks() {
4163
+ const entries = await coordinator.registryList(LOCK_PREFIX, MAX_LISTED_LOCKS);
4164
+ const current = now();
4165
+ return entries.map(({ key, value }) => ({
4166
+ id: key.slice(LOCK_PREFIX.length),
4167
+ kind: value?.kind === "account" ? "account" : "ip",
4168
+ ip: typeof value?.ip === "string" ? value.ip : null,
4169
+ user: typeof value?.user === "string" ? value.user : null,
4170
+ failures: Number(value?.failures) || 0,
4171
+ lockedAt: Number(value?.lockedAt) || 0,
4172
+ until: Number(value?.until) || 0
4173
+ })).filter((lock) => KEY_PATTERN.test(lock.id) && lock.until > current).sort((a, b) => b.lockedAt - a.lockedAt);
4174
+ },
4175
+ /**
4176
+ * Lifts a lock: deletes the counter and the list entry.
4177
+ *
4178
+ * @param {string} id Lock id from `listLocks` (`lf:…` or `la:…`).
4179
+ * @returns {Promise<{kind: 'ip'|'account', ip: string|null, user: string|null}|null>}
4180
+ * The lifted lock, or null when the id is invalid or nothing was locked.
4181
+ * @sideeffect Deletes the shared counter and the lock entry.
4182
+ */
4183
+ async unlock(id) {
4184
+ if (typeof id !== "string" || !KEY_PATTERN.test(id)) return null;
4185
+ const entries = await coordinator.registryList(`${LOCK_PREFIX}${id}`, 1);
4186
+ const entry = entries.find((candidate) => candidate.key === `${LOCK_PREFIX}${id}`);
4187
+ const counter = await coordinator.peek(id);
4188
+ const blocked = Number(counter?.blockedUntil) > now();
4189
+ await coordinator.clear(id);
4190
+ await coordinator.registryDelete(`${LOCK_PREFIX}${id}`);
4191
+ if (!entry && !blocked) return null;
4192
+ return {
4193
+ kind: id.startsWith("la:") ? "account" : "ip",
4194
+ ip: typeof entry?.value?.ip === "string" ? entry.value.ip : null,
4195
+ user: typeof entry?.value?.user === "string" ? entry.value.user : null
4196
+ };
4197
+ }
4198
+ };
4199
+ }
4200
+ module2.exports = {
4201
+ LOCK_ID_PATTERN: KEY_PATTERN,
4202
+ accountKey,
4203
+ createLoginLockout,
4204
+ ipKey,
4205
+ normalizeIdentifier
4206
+ };
4207
+ }
4208
+ });
4209
+
4210
+ // server/src/utils/sign-in-policies.js
4211
+ var require_sign_in_policies = __commonJS({
4212
+ "server/src/utils/sign-in-policies.js"(exports2, module2) {
4213
+ "use strict";
4214
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
4215
+ var { getCoordinator, hashedKey } = require_coordination();
4216
+ var { resolveSecurityLogSettings } = require_security_log_settings();
4217
+ var { hasRoleOverride, inactivityTimeoutFor, sessionLimitFor } = require_policy_settings();
4218
+ var { normalizeIdentifier } = require_login_lockout();
4219
+ var USER_UID = "plugin::users-permissions.user";
4220
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
4221
+ var MAX_SESSIONS_CHECKED = 500;
4222
+ function readSignInIdentifier(ctx) {
4223
+ const body = ctx?.request?.body;
4224
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
4225
+ return normalizeIdentifier(body.identifier) || normalizeIdentifier(body.email);
4226
+ }
4227
+ async function findAccountByIdentifier(strapi2, identifier) {
4228
+ if (!identifier) return null;
4229
+ const rows = await strapi2.db.query(USER_UID).findMany({
4230
+ where: { $or: [{ email: identifier }, { username: identifier }] },
4231
+ select: ["documentId", "email", "username"],
4232
+ populate: { role: { select: ["documentId"] } },
4233
+ limit: 2
4234
+ });
4235
+ const list = Array.isArray(rows) ? rows : [];
4236
+ const account = list.find((row) => String(row.email || "").toLowerCase() === identifier) || list[0];
4237
+ if (!account?.documentId) return null;
4238
+ return {
4239
+ documentId: account.documentId,
4240
+ email: typeof account.email === "string" ? account.email : null,
4241
+ username: typeof account.username === "string" ? account.username : null,
4242
+ role: account.role?.documentId || null
4243
+ };
4244
+ }
4245
+ async function findUserRole(strapi2, userDocumentId) {
4246
+ if (!userDocumentId) return null;
4247
+ const user = await strapi2.db.query(USER_UID).findOne({
4248
+ where: { documentId: userDocumentId },
4249
+ select: ["id"],
4250
+ populate: { role: { select: ["documentId"] } }
4251
+ });
4252
+ return user?.role?.documentId || null;
4253
+ }
4254
+ function displayIp(settings, ip) {
4255
+ const options = resolveSecurityLogSettings(settings);
4256
+ if (!options.storeIp) return null;
4257
+ const normalized = normalizeIp(ip || "");
4258
+ if (!normalized) return null;
4259
+ return options.anonymizeIp ? anonymizeIp(normalized) : normalized;
4260
+ }
4261
+ function recordUserEvent(strapi2, input) {
4262
+ try {
4263
+ return strapi2.plugin("magic-sessionmanager").service("security-log").record(input) === true;
4264
+ } catch {
4265
+ return false;
4266
+ }
4267
+ }
4268
+ function isOpenSession(session, idleMs, maxAgeDays, now) {
4269
+ if (session.isActive !== true) return false;
4270
+ const login = session.loginTime ? new Date(session.loginTime).getTime() : NaN;
4271
+ const last = session.lastActive ? new Date(session.lastActive).getTime() : login;
4272
+ if (Number.isFinite(last) && now - last > idleMs) return false;
4273
+ if (Number.isFinite(login) && now - login > maxAgeDays * 24 * 60 * 60 * 1e3) return false;
4274
+ return true;
4275
+ }
4276
+ async function createSessionWithinLimit({
4277
+ strapi: strapi2,
4278
+ settings,
4279
+ userDocumentId,
4280
+ create,
4281
+ sessionService
4282
+ }) {
4283
+ const possible = sessionLimitFor(settings, null).limit > 0 || hasRoleOverride(settings, "maxSessionsPerUser");
4284
+ if (!possible) return { session: await create(), refused: false, ended: 0, limit: 0 };
4285
+ const role = await findUserRole(strapi2, userDocumentId);
4286
+ const { limit, policy } = sessionLimitFor(settings, role);
4287
+ if (limit <= 0) return { session: await create(), refused: false, ended: 0, limit: 0 };
4288
+ return getCoordinator(strapi2).withLock(hashedKey("session-limit", userDocumentId), async () => {
4289
+ const session = await create();
4290
+ if (!session?.documentId) return { session, refused: false, ended: 0, limit };
4291
+ const now = Date.now();
4292
+ const idleMs = inactivityTimeoutFor(settings, role);
4293
+ const maxAgeDays = Number(settings.maxSessionAgeDays) || 30;
4294
+ const rows = await strapi2.documents(SESSION_UID).findMany({
4295
+ filters: { user: { documentId: userDocumentId }, isActive: true },
4296
+ fields: ["documentId", "isActive", "loginTime", "lastActive"],
4297
+ sort: [{ loginTime: "asc" }, { id: "asc" }],
4298
+ limit: MAX_SESSIONS_CHECKED
4299
+ });
4300
+ const open = (Array.isArray(rows) ? rows : []).filter(
4301
+ (row) => isOpenSession(row, idleMs, maxAgeDays, now)
4302
+ );
4303
+ if (open.length <= limit) return { session, refused: false, ended: 0, limit };
4304
+ if (policy === "refuse") {
4305
+ await sessionService.terminateSession({ sessionId: session.documentId, reason: "manual" });
4306
+ return { session, refused: true, ended: 0, limit };
4307
+ }
4308
+ const others = open.filter((row) => row.documentId !== session.documentId);
4309
+ const excess = open.length - limit;
4310
+ let ended = 0;
4311
+ for (const row of others.slice(0, excess)) {
4312
+ const result = await sessionService.terminateSession({
4313
+ sessionId: row.documentId,
4314
+ reason: "manual"
4315
+ });
4316
+ ended += Number(result?.terminatedCount) || 0;
4317
+ }
4318
+ return { session, refused: false, ended, limit };
4319
+ });
4320
+ }
4321
+ function createRefusalDedup({ windowMs = 60 * 1e3, maxKeys = 5e3 } = {}) {
4322
+ const seen = /* @__PURE__ */ new Map();
4323
+ return (key, now = Date.now()) => {
4324
+ const last = seen.get(key);
4325
+ if (last !== void 0 && now - last < windowMs) return false;
4326
+ seen.delete(key);
4327
+ seen.set(key, now);
4328
+ if (seen.size > maxKeys) seen.delete(
4329
+ /** @type {string} */
4330
+ seen.keys().next().value
4331
+ );
4332
+ return true;
4333
+ };
4334
+ }
4335
+ function createAddressCap({ max = 30, windowMs = 60 * 60 * 1e3, maxKeys = 5e3 } = {}) {
4336
+ const counts = /* @__PURE__ */ new Map();
4337
+ return (ip, now = Date.now()) => {
4338
+ const key = anonymizeIp(normalizeIp(ip || "")) || "-";
4339
+ const windowStart = Math.floor(now / windowMs) * windowMs;
4340
+ const entry = counts.get(key);
4341
+ if (!entry || entry.windowStart !== windowStart) {
4342
+ counts.delete(key);
4343
+ counts.set(key, { count: 1, windowStart });
4344
+ if (counts.size > maxKeys) counts.delete(
4345
+ /** @type {string} */
4346
+ counts.keys().next().value
4347
+ );
4348
+ return true;
4349
+ }
4350
+ entry.count += 1;
4351
+ return entry.count <= max;
4352
+ };
4353
+ }
4354
+ function refusalReasonOfGeoDecision(reason) {
4355
+ const value = String(reason || "");
4356
+ if (value.startsWith("country_")) return "country";
4357
+ if (value.startsWith("geo_lookup_unavailable")) return "location-unavailable";
4358
+ return "risk";
4359
+ }
4360
+ module2.exports = {
4361
+ createAddressCap,
4362
+ createRefusalDedup,
4363
+ refusalReasonOfGeoDecision,
4364
+ createSessionWithinLimit,
4365
+ displayIp,
4366
+ findAccountByIdentifier,
4367
+ findUserRole,
4368
+ isOpenSession,
4369
+ readSignInIdentifier,
4370
+ recordUserEvent
4371
+ };
4372
+ }
4373
+ });
4374
+
4375
+ // server/src/utils/upgrade-defaults.js
4376
+ var require_upgrade_defaults = __commonJS({
4377
+ "server/src/utils/upgrade-defaults.js"(exports2, module2) {
4378
+ "use strict";
4379
+ var { withPluginStoreKey } = require_plugin_store();
4380
+ var { notifySettingsChanged } = require_settings_loader();
4381
+ var PROFILE_KEY = "defaultsProfile";
4382
+ var UPGRADE_STEPS = Object.freeze([
4383
+ Object.freeze({
4384
+ version: 1,
4385
+ release: "4.17.0",
4386
+ // Before 4.17 a password change kept the user's other sessions.
4387
+ legacy: Object.freeze({ endOtherSessionsOnPasswordChange: false })
4388
+ })
4389
+ ]);
4390
+ async function applyUpgradeDefaults(strapi2, log, steps = UPGRADE_STEPS) {
4391
+ const latest = steps.length ? steps[steps.length - 1].version : 0;
4392
+ const outcome = await withPluginStoreKey(strapi2, "settings", async (store) => {
4393
+ const profile = Number(await store.get({ key: PROFILE_KEY })) || 0;
4394
+ if (profile >= latest) return { existing: profile > 0, applied: [], changed: false };
4395
+ const stored = await store.get({ key: "settings" });
4396
+ let existing = profile > 0;
4397
+ if (!existing) {
4398
+ const permissionsVersion = await store.get({ key: "contentApiPermissionsVersion" });
4399
+ const legacyFlag = await store.get({ key: "contentApiPermissionsInitialized" });
4400
+ existing = stored !== null && stored !== void 0 || permissionsVersion !== null && permissionsVersion !== void 0 || legacyFlag === true;
4401
+ }
4402
+ const applied = [];
4403
+ if (existing) {
4404
+ const settings = stored && typeof stored === "object" ? { ...stored } : {};
4405
+ for (const step of steps) {
4406
+ if (step.version <= profile) continue;
4407
+ for (const [key, value] of Object.entries(step.legacy)) {
4408
+ if (settings[key] !== void 0) continue;
4409
+ settings[key] = value;
4410
+ applied.push(key);
4411
+ }
4412
+ }
4413
+ if (applied.length) await store.set({ key: "settings", value: settings });
4414
+ }
4415
+ await store.set({ key: PROFILE_KEY, value: latest });
4416
+ return { existing, applied, changed: applied.length > 0 };
4417
+ });
4418
+ if (outcome.changed) {
4419
+ await notifySettingsChanged(strapi2);
4420
+ log.info(
4421
+ `[UPGRADE] Kept the previous behaviour of ${outcome.applied.length} setting(s) on this existing installation`
4422
+ );
4423
+ }
4424
+ return { existing: outcome.existing, applied: outcome.applied };
4425
+ }
4426
+ module2.exports = { PROFILE_KEY, UPGRADE_STEPS, applyUpgradeDefaults };
4427
+ }
4428
+ });
4429
+
3511
4430
  // server/src/middlewares/session-rejection-headers.js
3512
4431
  var require_session_rejection_headers = __commonJS({
3513
4432
  "server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
@@ -7602,12 +8521,7 @@ var require_bootstrap = __commonJS({
7602
8521
  var { REVOCATION_UID } = require_session_revocation();
7603
8522
  var { getNativeSessionManager } = require_native_session_manager();
7604
8523
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
7605
- var {
7606
- getCoordinator,
7607
- hashedKey,
7608
- initCoordination,
7609
- LockTimeoutError
7610
- } = require_coordination();
8524
+ var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
7611
8525
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
7612
8526
  var {
7613
8527
  normalizeApiPrefix,
@@ -7637,8 +8551,27 @@ var require_bootstrap = __commonJS({
7637
8551
  migrateSecurityLog,
7638
8552
  warnUnboundedProxyTrust
7639
8553
  } = require_security_log_hardening();
8554
+ var { createLoginLockout } = require_login_lockout();
8555
+ var {
8556
+ accountThresholdFor,
8557
+ inactivityTimeoutFor,
8558
+ hasRoleOverride,
8559
+ resolveLockoutPolicy
8560
+ } = require_policy_settings();
8561
+ var {
8562
+ createAddressCap,
8563
+ createRefusalDedup,
8564
+ createSessionWithinLimit,
8565
+ displayIp,
8566
+ findAccountByIdentifier,
8567
+ readSignInIdentifier,
8568
+ recordUserEvent,
8569
+ refusalReasonOfGeoDecision
8570
+ } = require_sign_in_policies();
8571
+ var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
8572
+ var { applyUpgradeDefaults } = require_upgrade_defaults();
8573
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
7640
8574
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7641
- var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
7642
8575
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
7643
8576
  var JOB_LEASES = Object.freeze({
7644
8577
  idleCleanup: "job:idle-cleanup",
@@ -7680,6 +8613,11 @@ var require_bootstrap = __commonJS({
7680
8613
  try {
7681
8614
  const coordinator = await initCoordination(strapi2, log);
7682
8615
  await checkEncryptionKeyConsistency(strapi2, log);
8616
+ try {
8617
+ await applyUpgradeDefaults(strapi2, log);
8618
+ } catch (err) {
8619
+ log.warn("[UPGRADE] Previous defaults could not be kept:", err?.name || "Error");
8620
+ }
7683
8621
  await ensureSessionLookupIndexes(strapi2, log);
7684
8622
  await registerSessionAwareAuthStrategy(strapi2);
7685
8623
  await removeLegacyLicenseRows(strapi2, log);
@@ -7841,6 +8779,27 @@ var require_bootstrap = __commonJS({
7841
8779
  }
7842
8780
  }
7843
8781
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
8782
+ const shouldRecordRefusal = createRefusalDedup();
8783
+ const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
8784
+ const recordRefusal = async (ctx, settings, ip, decisionReason) => {
8785
+ if (!resolveLockoutPolicy(settings).record) return;
8786
+ const reason = refusalReasonOfGeoDecision(decisionReason);
8787
+ const identifier = readSignInIdentifier(ctx);
8788
+ if (!shouldRecordRefusal(`${reason}|${ip}|${identifier || ""}`)) return;
8789
+ const account = await findAccountByIdentifier(strapi2, identifier).catch(() => null);
8790
+ if (!account && !shouldRecordUnknownAccount(`refused|${anonymizeIp(normalizeIp(ip || "")) || "none"}`)) {
8791
+ return;
8792
+ }
8793
+ recordUserEvent(strapi2, {
8794
+ event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
8795
+ actorType: "user",
8796
+ targetType: "user",
8797
+ targetId: account?.documentId || null,
8798
+ ip,
8799
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
8800
+ meta: { reason }
8801
+ });
8802
+ };
7844
8803
  strapi2.server.use(async (ctx, next) => {
7845
8804
  if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
7846
8805
  return next();
@@ -7860,6 +8819,7 @@ var require_bootstrap = __commonJS({
7860
8819
  const decision = evaluateGeoFirewall(settings, geoData);
7861
8820
  if (decision.blocked) {
7862
8821
  log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
8822
+ await recordRefusal(ctx, settings, ip, decision.reason);
7863
8823
  ctx.status = 403;
7864
8824
  ctx.body = {
7865
8825
  error: {
@@ -7878,6 +8838,7 @@ var require_bootstrap = __commonJS({
7878
8838
  const failureDecision = evaluateGeoFirewall(settings, { _status: "error" });
7879
8839
  if (failureDecision.blocked) {
7880
8840
  log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
8841
+ await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
7881
8842
  ctx.status = 403;
7882
8843
  ctx.body = {
7883
8844
  error: {
@@ -8077,53 +9038,95 @@ var require_bootstrap = __commonJS({
8077
9038
  }
8078
9039
  }
8079
9040
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
8080
- const WINDOW_MS = FAILED_LOGIN_WINDOW_MS;
8081
- const coordinator = getCoordinator(strapi2);
8082
- const keyFor = (ip) => hashedKey("lf", ip);
9041
+ const lockout = createLoginLockout(getCoordinator(strapi2));
9042
+ const shouldRecordRefusal = createRefusalDedup();
9043
+ const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
9044
+ const underAddressCap = createAddressCap();
9045
+ const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
8083
9046
  strapi2.server.use(async (ctx, next) => {
8084
9047
  if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
8085
9048
  const settings = await getRequestSettings(strapi2, ctx);
8086
- const maxFailed = Number(settings.maxFailedLogins) || 0;
8087
- if (maxFailed <= 0) return next();
8088
- const ip = getClientIp(ctx);
8089
- if (!ip || ip === "unknown") return next();
8090
- const key = keyFor(ip);
8091
- const now = Date.now();
8092
- let existing = null;
9049
+ const policy = resolveLockoutPolicy(settings);
9050
+ const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
9051
+ if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
9052
+ const rawIp = getClientIp(ctx);
9053
+ const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
9054
+ const identifier = readSignInIdentifier(ctx);
9055
+ const userAgent = ctx.request?.headers?.["user-agent"] || null;
9056
+ let account;
9057
+ const loadAccount = async () => {
9058
+ if (account !== void 0) return account;
9059
+ let found = null;
9060
+ if (identifier) {
9061
+ try {
9062
+ found = await findAccountByIdentifier(strapi2, identifier);
9063
+ } catch (err) {
9064
+ log.debug("[LOCKOUT] Account lookup failed:", err?.name || "Error");
9065
+ }
9066
+ }
9067
+ account = found;
9068
+ return account;
9069
+ };
9070
+ if (policy.accountMaxByRole) await loadAccount();
9071
+ const accountMax = accountThresholdFor(settings, account?.role || null);
9072
+ const event = (name, meta) => {
9073
+ const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
9074
+ if (signInFamily && !policy.record) return false;
9075
+ if (signInFamily && !underAddressCap(ip)) return false;
9076
+ return recordUserEvent(strapi2, {
9077
+ event: name,
9078
+ actorType: "user",
9079
+ actorId: null,
9080
+ targetType: "user",
9081
+ targetId: account?.documentId || null,
9082
+ ip,
9083
+ userAgent,
9084
+ meta
9085
+ });
9086
+ };
9087
+ const refusedOnce = (reason, meta) => {
9088
+ if (!policy.record) return;
9089
+ if (!account) {
9090
+ if (!shouldRecordUnknownAccount(`refused|${unknownAccountKey(ip)}`)) return;
9091
+ event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, unknownAccount: true, ...meta });
9092
+ return;
9093
+ }
9094
+ if (!shouldRecordRefusal(`${reason}|${ip || ""}|${identifier || ""}`)) return;
9095
+ event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, ...meta });
9096
+ };
9097
+ let decision;
8093
9098
  try {
8094
- existing = await coordinator.peek(key);
9099
+ decision = await lockout.reserve({ ip, identifier, policy, accountMax });
8095
9100
  } catch (err) {
8096
- log.debug("[LOCKOUT] Counter read failed:", err?.name || "Error");
9101
+ log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
9102
+ decision = {
9103
+ outcome: "allow",
9104
+ retryAfter: 0,
9105
+ lockedKind: null,
9106
+ reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
9107
+ };
8097
9108
  }
8098
- const rejectLocked = (retrySec) => {
8099
- ctx.set("Retry-After", String(retrySec));
8100
- log.warn(`[LOCKOUT] Rejected login from locked client (${retrySec}s remaining)`);
9109
+ if (decision.outcome === "locked") {
9110
+ ctx.set("Retry-After", String(decision.retryAfter));
9111
+ log.warn(
9112
+ `[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
9113
+ );
9114
+ if (policy.record) await loadAccount();
9115
+ refusedOnce("lockout", { lock: decision.lockedKind });
8101
9116
  ctx.status = 429;
8102
9117
  ctx.body = {
8103
9118
  error: {
8104
9119
  status: 429,
8105
9120
  name: "TooManyRequestsError",
8106
9121
  message: "Too many failed login attempts. Please try again later.",
8107
- details: { retryAfter: retrySec }
9122
+ details: { retryAfter: decision.retryAfter }
8108
9123
  }
8109
9124
  };
8110
- };
8111
- if (existing && existing.blockedUntil > now) {
8112
- rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
8113
9125
  return;
8114
9126
  }
8115
- let reserved = null;
8116
- try {
8117
- reserved = await coordinator.hit(key, WINDOW_MS);
8118
- } catch (err) {
8119
- log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
8120
- }
8121
- if (reserved && reserved.hits > maxFailed) {
8122
- try {
8123
- await coordinator.release(key);
8124
- } catch (err) {
8125
- log.debug("[LOCKOUT] Counter release failed:", err?.name || "Error");
8126
- }
9127
+ if (decision.outcome === "busy") {
9128
+ if (policy.record) await loadAccount();
9129
+ refusedOnce("too-many-attempts", {});
8127
9130
  ctx.set("Retry-After", "1");
8128
9131
  ctx.status = 429;
8129
9132
  ctx.body = {
@@ -8143,18 +9146,43 @@ var require_bootstrap = __commonJS({
8143
9146
  thrown = err;
8144
9147
  }
8145
9148
  const status = thrown ? statusOfThrownError(thrown) : ctx.status;
9149
+ const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
9150
+ if (result === "failure") {
9151
+ if (policy.record || decision.reservation.accountKey) await loadAccount();
9152
+ if (account) {
9153
+ event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
9154
+ } else if (shouldRecordUnknownAccount(`failed|${unknownAccountKey(ip)}`)) {
9155
+ event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status, unknownAccount: true });
9156
+ }
9157
+ }
8146
9158
  try {
8147
- if (!thrown && status === 200 && ctx.body && ctx.body.jwt) {
8148
- await coordinator.clear(key);
8149
- } else if (status >= 400 && status < 500 && status !== 429) {
8150
- if (reserved && reserved.hits >= maxFailed) {
8151
- await coordinator.block(key, Date.now() + WINDOW_MS);
8152
- log.warn(
8153
- `[LOCKOUT] Client locked for 15min after ${reserved.hits} failed login attempts`
8154
- );
9159
+ const locks = await lockout.settle(decision.reservation, result, {
9160
+ policy,
9161
+ accountMax,
9162
+ display: {
9163
+ ip: displayIp(settings, ip),
9164
+ userDocumentId: account?.documentId || null
9165
+ }
9166
+ });
9167
+ for (const lock of locks) {
9168
+ const minutes = Math.round(policy.durationMs / 6e4);
9169
+ log.warn(
9170
+ `[LOCKOUT] ${lock.kind === "ip" ? "Client" : "Account"} locked for ${minutes}min after ${lock.failures} failed sign-ins`
9171
+ );
9172
+ event(SECURITY_EVENTS.USER_LOCKOUT, {
9173
+ kind: lock.kind,
9174
+ failures: lock.failures,
9175
+ minutes
9176
+ });
9177
+ if (lock.kind === "account" && policy.notifyUser && account?.email) {
9178
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
9179
+ notifications.sendAccountLockedEmail({
9180
+ user: account,
9181
+ minutes,
9182
+ until: lock.until
9183
+ }).catch(() => {
9184
+ });
8155
9185
  }
8156
- } else if (reserved) {
8157
- await coordinator.release(key);
8158
9186
  }
8159
9187
  } catch (err) {
8160
9188
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
@@ -8181,6 +9209,47 @@ var require_bootstrap = __commonJS({
8181
9209
  };
8182
9210
  return byName[err?.name] || 500;
8183
9211
  }
9212
+ function refuseSessionLimit({ ctx, strapi: strapi2, limit }) {
9213
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
9214
+ ctx.status = 403;
9215
+ ctx.body = {
9216
+ data: null,
9217
+ error: {
9218
+ status: 403,
9219
+ name: "ForbiddenError",
9220
+ message: "Too many active sessions. Sign out on another device and try again.",
9221
+ details: { code: "SESSION_LIMIT_REACHED", limit }
9222
+ }
9223
+ };
9224
+ }
9225
+ async function endOtherSessionsAfterPasswordChange({
9226
+ strapi: strapi2,
9227
+ ctx,
9228
+ log,
9229
+ sessionService,
9230
+ userDocumentId,
9231
+ currentSessionId
9232
+ }) {
9233
+ const settings = await getPluginSettings(strapi2);
9234
+ if (settings.endOtherSessionsOnPasswordChange !== true) return;
9235
+ if (!userDocumentId) throw new Error("password change owner could not be resolved");
9236
+ const { terminatedCount } = await sessionService.terminateSession({
9237
+ userId: userDocumentId,
9238
+ exceptSessionId: currentSessionId,
9239
+ reason: "logout"
9240
+ });
9241
+ recordUserEvent(strapi2, {
9242
+ event: SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
9243
+ actorType: "user",
9244
+ actorId: userDocumentId,
9245
+ targetType: "user",
9246
+ targetId: userDocumentId,
9247
+ ip: getClientIp(ctx),
9248
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
9249
+ meta: { ended: Number(terminatedCount) || 0 }
9250
+ });
9251
+ log.info("[PASSWORD] Ended the other sessions after a password change");
9252
+ }
8184
9253
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
8185
9254
  strapi2.server.use(async (ctx, next) => {
8186
9255
  const apiPath = apiPathOf(strapi2, ctx);
@@ -8231,6 +9300,7 @@ var require_bootstrap = __commonJS({
8231
9300
  filters: { tokenHash: hashToken(previousAccessToken), isActive: true },
8232
9301
  fields: ["documentId"]
8233
9302
  });
9303
+ let currentSidecarId;
8234
9304
  if (matchingSession) {
8235
9305
  const rotated = await sessionService.rotateSessionTokens({
8236
9306
  sessionId: matchingSession.documentId,
@@ -8241,6 +9311,7 @@ var require_bootstrap = __commonJS({
8241
9311
  });
8242
9312
  if (!rotated)
8243
9313
  throw new Error("current sidecar changed before native password rotation was linked");
9314
+ currentSidecarId = matchingSession.documentId;
8244
9315
  log.info("[PASSWORD] Native session link updated");
8245
9316
  } else {
8246
9317
  const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
@@ -8256,7 +9327,16 @@ var require_bootstrap = __commonJS({
8256
9327
  if (!createdSidecar?.documentId) {
8257
9328
  throw new Error("native password-change sidecar creation returned no documentId");
8258
9329
  }
9330
+ currentSidecarId = createdSidecar.documentId;
8259
9331
  }
9332
+ await endOtherSessionsAfterPasswordChange({
9333
+ strapi: strapi2,
9334
+ ctx,
9335
+ log,
9336
+ sessionService,
9337
+ userDocumentId: nativeSession2.userDocumentId,
9338
+ currentSessionId: currentSidecarId
9339
+ });
8260
9340
  } catch (err) {
8261
9341
  if (nativeSessionManager2 && nativeSession2) {
8262
9342
  await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
@@ -8295,6 +9375,19 @@ var require_bootstrap = __commonJS({
8295
9375
  });
8296
9376
  if (!rotated) throw new Error("current session changed before token rotation");
8297
9377
  log.info("[PASSWORD] Legacy session tokens rotated");
9378
+ const owner = await strapi2.documents(SESSION_UID).findOne({
9379
+ documentId: matchingSession.documentId,
9380
+ fields: ["documentId"],
9381
+ populate: { user: { fields: ["documentId"] } }
9382
+ });
9383
+ await endOtherSessionsAfterPasswordChange({
9384
+ strapi: strapi2,
9385
+ ctx,
9386
+ log,
9387
+ sessionService,
9388
+ userDocumentId: owner?.user?.documentId || null,
9389
+ currentSessionId: matchingSession.documentId
9390
+ });
8298
9391
  } catch (err) {
8299
9392
  failClosedAuthResponse({
8300
9393
  ctx,
@@ -8337,7 +9430,9 @@ var require_bootstrap = __commonJS({
8337
9430
  throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
8338
9431
  }
8339
9432
  const geoData = ctx.state?.__magicSessionGeoData || null;
8340
- const newSession = await sessionService.createSession({
9433
+ const requestSettings = await getPluginSettings(strapi2);
9434
+ const isReset = isPasswordResetRequest(apiPath, ctx.method);
9435
+ const create = () => sessionService.createSession({
8341
9436
  userId: userDocId,
8342
9437
  ip,
8343
9438
  userAgent,
@@ -8346,10 +9441,45 @@ var require_bootstrap = __commonJS({
8346
9441
  geoData,
8347
9442
  ...nativeSession ? { nativeSessionId: nativeSession.sessionId } : {}
8348
9443
  });
9444
+ const limited = isReset ? { session: await create(), refused: false, ended: 0, limit: 0 } : await createSessionWithinLimit({
9445
+ strapi: strapi2,
9446
+ settings: requestSettings,
9447
+ userDocumentId: userDocId,
9448
+ create,
9449
+ sessionService
9450
+ });
9451
+ const newSession = limited.session;
8349
9452
  if (!newSession?.documentId) {
8350
9453
  throw new Error(`session creation returned no documentId for user ${userDocId}`);
8351
9454
  }
8352
- if (isPasswordResetRequest(apiPath, ctx.method)) {
9455
+ if (limited.refused) {
9456
+ recordUserEvent(strapi2, {
9457
+ event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
9458
+ actorType: "user",
9459
+ actorId: userDocId,
9460
+ targetType: "user",
9461
+ targetId: userDocId,
9462
+ ip,
9463
+ userAgent,
9464
+ meta: { reason: "session-limit", limit: limited.limit }
9465
+ });
9466
+ refuseSessionLimit({ ctx, strapi: strapi2, limit: limited.limit });
9467
+ log.info("[LIMIT] Sign-in refused: the user reached the session limit");
9468
+ return;
9469
+ }
9470
+ if (limited.ended > 0) {
9471
+ recordUserEvent(strapi2, {
9472
+ event: SECURITY_EVENTS.USER_SESSION_LIMIT,
9473
+ actorType: "system",
9474
+ targetType: "user",
9475
+ targetId: userDocId,
9476
+ ip,
9477
+ userAgent,
9478
+ meta: { ended: limited.ended, limit: limited.limit }
9479
+ });
9480
+ log.info(`[LIMIT] Ended ${limited.ended} older session(s) to stay within the limit`);
9481
+ }
9482
+ if (isReset) {
8353
9483
  await sessionService.terminateSession({
8354
9484
  userId: userDocId,
8355
9485
  exceptSessionId: newSession.documentId,
@@ -9040,11 +10170,13 @@ var require_bootstrap = __commonJS({
9040
10170
  strapi2.log.debug("[magic-sessionmanager] [JWT] No documentId found in relaxed mode");
9041
10171
  return decoded;
9042
10172
  }
10173
+ const needsRole = hasRoleOverride(settings, "inactivityTimeout");
9043
10174
  let userRecord;
9044
10175
  try {
9045
10176
  userRecord = await strapi2.documents("plugin::users-permissions.user").findOne({
9046
10177
  documentId: userDocId,
9047
- fields: ["documentId", "blocked"]
10178
+ fields: ["documentId", "blocked"],
10179
+ ...needsRole ? { populate: { role: { fields: ["documentId"] } } } : {}
9048
10180
  });
9049
10181
  } catch (err) {
9050
10182
  if (strictMode) {
@@ -9113,7 +10245,10 @@ var require_bootstrap = __commonJS({
9113
10245
  setSessionRejectionReason(tokenHashValue, "expired");
9114
10246
  return null;
9115
10247
  }
9116
- const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
10248
+ const inactivityTimeout = inactivityTimeoutFor(
10249
+ settings,
10250
+ userRecord?.role?.documentId || null
10251
+ );
9117
10252
  const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
9118
10253
  const idleFor = Date.now() - lastActiveMs;
9119
10254
  if (idleFor > inactivityTimeout) {
@@ -9309,6 +10444,9 @@ var require_config = __commonJS({
9309
10444
  discordWebhookUrl: "",
9310
10445
  slackWebhookUrl: "",
9311
10446
  trustedProxies: null,
10447
+ // Sign-in and session policies (4.17). Existing installations keep
10448
+ // `endOtherSessionsOnPasswordChange: false` (utils/upgrade-defaults.js).
10449
+ endOtherSessionsOnPasswordChange: true,
9312
10450
  // Cross-process state for pm2 cluster / several replicas. `enabled:
9313
10451
  // false` keeps every counter, lease and cache per process (the pre-4.10
9314
10452
  // behaviour). `counterStore` may supply an object with async
@@ -9743,6 +10881,7 @@ var require_admin = __commonJS({
9743
10881
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
9744
10882
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
9745
10883
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
10884
+ var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
9746
10885
  var adminPolicy = () => [
9747
10886
  "admin::isAuthenticatedAdmin",
9748
10887
  {
@@ -9996,6 +11135,37 @@ var require_admin = __commonJS({
9996
11135
  description: "Get one export batch of Content Manager activity of admins (admin)"
9997
11136
  }
9998
11137
  },
11138
+ // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
11139
+ {
11140
+ method: "GET",
11141
+ path: "/lockouts",
11142
+ handler: "lockouts.list",
11143
+ config: {
11144
+ policies: adminPolicy(),
11145
+ middlewares: adminReadRateLimit(),
11146
+ description: "List the active sign-in locks (admin)"
11147
+ }
11148
+ },
11149
+ {
11150
+ method: "POST",
11151
+ path: "/lockouts/unlock",
11152
+ handler: "lockouts.unlock",
11153
+ config: {
11154
+ policies: adminSessionsPolicy([LOCKOUTS_UNLOCK_ACTION]),
11155
+ middlewares: adminSignOutRateLimit(),
11156
+ description: "Lift one sign-in lock (admin)"
11157
+ }
11158
+ },
11159
+ {
11160
+ method: "GET",
11161
+ path: "/roles",
11162
+ handler: "lockouts.roles",
11163
+ config: {
11164
+ policies: adminPolicy(),
11165
+ middlewares: adminReadRateLimit(),
11166
+ description: "List Users & Permissions roles for per-role rules (admin)"
11167
+ }
11168
+ },
9999
11169
  // ============================ GEOLOCATION ============================
10000
11170
  {
10001
11171
  method: "GET",
@@ -12328,6 +13498,7 @@ var require_settings_access = __commonJS({
12328
13498
  "server/src/utils/settings-access.js"(exports2, module2) {
12329
13499
  "use strict";
12330
13500
  var { SECURITY_LOG_KEYS } = require_security_log_settings();
13501
+ var { POLICY_KEYS } = require_policy_settings();
12331
13502
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12332
13503
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12333
13504
  var GEO_SETTINGS_KEYS = Object.freeze([
@@ -12344,7 +13515,10 @@ var require_settings_access = __commonJS({
12344
13515
  var PROTECTED_SETTINGS_KEYS = Object.freeze([
12345
13516
  ...GEO_SETTINGS_KEYS,
12346
13517
  ...WEBHOOK_SETTINGS_KEYS,
12347
- ...SECURITY_LOG_KEYS
13518
+ ...SECURITY_LOG_KEYS,
13519
+ // Sign-in and session policies (lockout, trusted addresses, session
13520
+ // limit, password-change sign-out, recording switch, per-role rules).
13521
+ ...POLICY_KEYS
12348
13522
  ]);
12349
13523
  var WEBHOOK_SECRETS = Object.freeze([
12350
13524
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
@@ -12437,6 +13611,7 @@ var require_settings = __commonJS({
12437
13611
  missingSettingsPermission,
12438
13612
  toPublicSettings
12439
13613
  } = require_settings_access();
13614
+ var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
12440
13615
  var path = require("node:path");
12441
13616
  var ALLOWED_WEBHOOK_DOMAINS = {
12442
13617
  discord: ["discord.com", "discordapp.com"],
@@ -12468,11 +13643,9 @@ var require_settings = __commonJS({
12468
13643
  }
12469
13644
  }
12470
13645
  function sanitizeEmailTemplates(templates) {
12471
- const defaults = {
12472
- suspiciousLogin: { subject: "", html: "", text: "" },
12473
- newLocation: { subject: "", html: "", text: "" },
12474
- vpnProxy: { subject: "", html: "", text: "" }
12475
- };
13646
+ const defaults = Object.fromEntries(
13647
+ Object.keys(DEFAULT_EMAIL_TEMPLATES).map((key) => [key, { subject: "", html: "", text: "" }])
13648
+ );
12476
13649
  if (!templates || typeof templates !== "object") return defaults;
12477
13650
  let sanitizeHtml;
12478
13651
  try {
@@ -12578,7 +13751,9 @@ var require_settings = __commonJS({
12578
13751
  var DEFAULT_EMAIL_TEMPLATES = {
12579
13752
  suspiciousLogin: { subject: "", html: "", text: "" },
12580
13753
  newLocation: { subject: "", html: "", text: "" },
12581
- vpnProxy: { subject: "", html: "", text: "" }
13754
+ vpnProxy: { subject: "", html: "", text: "" },
13755
+ // 4.17: sent to a user whose account was locked after failed sign-ins.
13756
+ accountLocked: { subject: "", html: "", text: "" }
12582
13757
  };
12583
13758
  var DEFAULT_SETTINGS = {
12584
13759
  inactivityTimeout: 15,
@@ -12611,7 +13786,10 @@ var require_settings = __commonJS({
12611
13786
  strictSessionEnforcement: false,
12612
13787
  trustedProxies: false,
12613
13788
  emailTemplates: DEFAULT_EMAIL_TEMPLATES,
12614
- ...SECURITY_LOG_DEFAULTS
13789
+ ...SECURITY_LOG_DEFAULTS,
13790
+ ...POLICY_DEFAULTS,
13791
+ lockoutTrustedAddresses: [],
13792
+ roleRules: []
12615
13793
  };
12616
13794
  function mergeSettingsWithDefaults(stored) {
12617
13795
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -12819,6 +13997,9 @@ var require_settings = __commonJS({
12819
13997
  const securityLog = validateSecurityLogSettings(body);
12820
13998
  errors.push(...securityLog.errors);
12821
13999
  Object.assign(next, securityLog.values);
14000
+ const policies2 = validatePolicySettings(body);
14001
+ errors.push(...policies2.errors);
14002
+ Object.assign(next, policies2.values);
12822
14003
  if (errors.length > 0) return { errors };
12823
14004
  const settings = {};
12824
14005
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -12868,6 +14049,16 @@ var require_settings = __commonJS({
12868
14049
  } catch {
12869
14050
  }
12870
14051
  }
14052
+ async function findUnknownRoles(rules) {
14053
+ if (!Array.isArray(rules) || rules.length === 0) return [];
14054
+ const ids = rules.map((rule) => rule.role);
14055
+ const rows = await strapi.db.query("plugin::users-permissions.role").findMany({ where: { documentId: { $in: ids } }, select: ["documentId"] });
14056
+ const known = new Set((Array.isArray(rows) ? rows : []).map((row) => row.documentId));
14057
+ return rules.map((rule, index) => known.has(rule.role) ? null : index).filter((index) => index !== null).map((index) => ({
14058
+ path: ["roleRules", index, "role"],
14059
+ message: "This role does not exist any more"
14060
+ }));
14061
+ }
12871
14062
  module2.exports = {
12872
14063
  /**
12873
14064
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -12952,6 +14143,8 @@ var require_settings = __commonJS({
12952
14143
  };
12953
14144
  const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
12954
14145
  if (errors.length > 0) return { errors };
14146
+ const roleErrors = await findUnknownRoles(sanitizedSettings.roleRules);
14147
+ if (roleErrors.length > 0) return { errors: roleErrors };
12955
14148
  const changed = changedKeys(
12956
14149
  {
12957
14150
  ...sanitizedSettings,
@@ -14347,6 +15540,137 @@ var require_admin_activity = __commonJS({
14347
15540
  }
14348
15541
  });
14349
15542
 
15543
+ // server/src/controllers/lockouts.js
15544
+ var require_lockouts = __commonJS({
15545
+ "server/src/controllers/lockouts.js"(exports2, module2) {
15546
+ "use strict";
15547
+ var { getCoordinator } = require_coordination();
15548
+ var { LOCK_ID_PATTERN, createLoginLockout } = require_login_lockout();
15549
+ var { getRequestIp, getRequestUserAgent } = require_admin_request_info();
15550
+ var { SECURITY_EVENTS } = require_security_log_model();
15551
+ var { sendServerError, sendValidationError } = require_http_errors();
15552
+ var { createLogger } = require_logger();
15553
+ var USER_UID = "plugin::users-permissions.user";
15554
+ var ROLE_UID = "plugin::users-permissions.role";
15555
+ module2.exports = ({ strapi: strapi2 }) => {
15556
+ const log = createLogger(strapi2);
15557
+ const lockout = () => createLoginLockout(getCoordinator(strapi2));
15558
+ return {
15559
+ /**
15560
+ * Lists the active sign-in locks: locked IP addresses (shown as the
15561
+ * security log stores IPs) and locked accounts with their user.
15562
+ *
15563
+ * @route GET /magic-sessionmanager/lockouts
15564
+ * @auth admin session or admin API token
15565
+ * @access plugin::magic-sessionmanager.access
15566
+ * @param {any} ctx Koa context.
15567
+ * @returns {Promise<void>} `{ data: Lock[], meta: { total } }`; 500 on store failure.
15568
+ */
15569
+ async list(ctx) {
15570
+ try {
15571
+ const locks = await lockout().listLocks();
15572
+ const ids = [...new Set(locks.map((lock) => lock.user).filter(Boolean))];
15573
+ const users = ids.length ? await strapi2.db.query(USER_UID).findMany({
15574
+ where: { documentId: { $in: ids } },
15575
+ select: ["documentId", "username", "email"]
15576
+ }) : [];
15577
+ const byId = new Map(
15578
+ (Array.isArray(users) ? users : []).map((user) => [user.documentId, user])
15579
+ );
15580
+ const data = locks.map((lock) => {
15581
+ const user = lock.user ? byId.get(lock.user) : null;
15582
+ return {
15583
+ id: lock.id,
15584
+ kind: lock.kind,
15585
+ ip: lock.kind === "ip" ? lock.ip : null,
15586
+ user: user ? { documentId: user.documentId, username: user.username, email: user.email } : null,
15587
+ failures: lock.failures,
15588
+ lockedAt: new Date(lock.lockedAt).toISOString(),
15589
+ until: new Date(lock.until).toISOString()
15590
+ };
15591
+ });
15592
+ ctx.body = { data, meta: { total: data.length } };
15593
+ } catch (err) {
15594
+ log.error("[lockouts] List failed:", err?.name || "Error");
15595
+ return sendServerError(ctx, 500, "Locks could not be loaded");
15596
+ }
15597
+ },
15598
+ /**
15599
+ * Lifts one lock. The admin who lifted it is recorded in the security log.
15600
+ *
15601
+ * @route POST /magic-sessionmanager/lockouts/unlock
15602
+ * @auth admin session or admin API token
15603
+ * @access plugin::magic-sessionmanager.access + plugin::magic-sessionmanager.lockouts.unlock
15604
+ * @param {any} ctx Koa context; body `{ id }` from the list.
15605
+ * @returns {Promise<void>} `{ data: { unlocked: true, kind } }`; 400 invalid id; 404 not locked.
15606
+ * @sideeffect Deletes the shared lock counter and list entry; writes `user.lockout.lifted`.
15607
+ */
15608
+ async unlock(ctx) {
15609
+ const body = ctx.request?.body;
15610
+ const id = body && typeof body === "object" && !Array.isArray(body) ? body.id : void 0;
15611
+ const extra = body && typeof body === "object" ? Object.keys(body).filter((key) => key !== "id") : [];
15612
+ if (typeof id !== "string" || !LOCK_ID_PATTERN.test(id) || extra.length > 0) {
15613
+ return sendValidationError(ctx, "Invalid lock", [
15614
+ { path: ["id"], message: "id must be a lock id from the list" }
15615
+ ]);
15616
+ }
15617
+ try {
15618
+ const lifted = await lockout().unlock(id);
15619
+ if (!lifted) return ctx.notFound("This lock has already ended");
15620
+ try {
15621
+ strapi2.plugin("magic-sessionmanager").service("security-log").record({
15622
+ event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
15623
+ actorType: "admin",
15624
+ actorId: ctx.state?.user?.id ?? null,
15625
+ targetType: lifted.kind === "account" ? "user" : "ip",
15626
+ targetId: lifted.kind === "account" ? lifted.user : null,
15627
+ ip: getRequestIp(ctx),
15628
+ userAgent: getRequestUserAgent(ctx),
15629
+ meta: { kind: lifted.kind }
15630
+ });
15631
+ } catch {
15632
+ }
15633
+ ctx.body = { data: { unlocked: true, kind: lifted.kind } };
15634
+ } catch (err) {
15635
+ log.error("[lockouts] Unlock failed:", err?.name || "Error");
15636
+ return sendServerError(ctx, 500, "The lock could not be lifted");
15637
+ }
15638
+ },
15639
+ /**
15640
+ * Users & Permissions roles for the per-role rules (the Public role has
15641
+ * no signed-in users and is left out).
15642
+ *
15643
+ * @route GET /magic-sessionmanager/roles
15644
+ * @auth admin session or admin API token
15645
+ * @access plugin::magic-sessionmanager.access
15646
+ * @param {any} ctx Koa context.
15647
+ * @returns {Promise<void>} `{ data: [{ documentId, name, type }] }`.
15648
+ */
15649
+ async roles(ctx) {
15650
+ try {
15651
+ const rows = await strapi2.db.query(ROLE_UID).findMany({
15652
+ select: ["documentId", "name", "type"],
15653
+ where: { type: { $ne: "public" } },
15654
+ orderBy: { name: "asc" },
15655
+ limit: 200
15656
+ });
15657
+ ctx.body = {
15658
+ data: (Array.isArray(rows) ? rows : []).map((role) => ({
15659
+ documentId: role.documentId,
15660
+ name: role.name,
15661
+ type: role.type
15662
+ }))
15663
+ };
15664
+ } catch (err) {
15665
+ log.error("[lockouts] Roles could not be listed:", err?.name || "Error");
15666
+ return sendServerError(ctx, 500, "Roles could not be loaded");
15667
+ }
15668
+ }
15669
+ };
15670
+ };
15671
+ }
15672
+ });
15673
+
14350
15674
  // server/src/controllers/index.js
14351
15675
  var require_controllers = __commonJS({
14352
15676
  "server/src/controllers/index.js"(exports2, module2) {
@@ -14356,12 +15680,14 @@ var require_controllers = __commonJS({
14356
15680
  var geoip = require_geoip();
14357
15681
  var adminSessions = require_admin_sessions2();
14358
15682
  var adminActivity = require_admin_activity();
15683
+ var lockouts = require_lockouts();
14359
15684
  module2.exports = {
14360
15685
  session,
14361
15686
  settings,
14362
15687
  geoip,
14363
15688
  "admin-sessions": adminSessions,
14364
- "admin-activity": adminActivity
15689
+ "admin-activity": adminActivity,
15690
+ lockouts
14365
15691
  };
14366
15692
  }
14367
15693
  });
@@ -14376,6 +15702,7 @@ var require_session2 = __commonJS({
14376
15702
  var { resolveUserDocumentId } = require_resolve_user();
14377
15703
  var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
14378
15704
  var { getPluginSettings } = require_settings_loader();
15705
+ var { hasRoleOverride, inactivityTimeoutFor } = require_policy_settings();
14379
15706
  var {
14380
15707
  cleanupExpiredAccessTokenRevocations,
14381
15708
  persistAccessTokenRevocation
@@ -15352,12 +16679,13 @@ var require_session2 = __commonJS({
15352
16679
  const settings = await getPluginSettings(strapi2);
15353
16680
  const nativeManager = getNativeSessionManager(strapi2);
15354
16681
  const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
16682
+ const perRole = hasRoleOverride(settings, "inactivityTimeout");
15355
16683
  const now = /* @__PURE__ */ new Date();
15356
16684
  const cutoffTime = new Date(now.getTime() - inactivityTimeout);
15357
16685
  log.info(
15358
16686
  `[CLEANUP] Cleaning up sessions inactive since before ${cutoffTime.toISOString()}`
15359
16687
  );
15360
- if (useDbDirect && !nativeManager) {
16688
+ if (useDbDirect && !nativeManager && !perRole) {
15361
16689
  try {
15362
16690
  const deactivated = await strapi2.db.connection("magic_sessions").where("is_active", true).andWhere(function whereIdle() {
15363
16691
  this.where("last_active", "<", cutoffTime).orWhere(function whereNullLastActive() {
@@ -15386,7 +16714,9 @@ var require_session2 = __commonJS({
15386
16714
  const batch = await strapi2.documents(SESSION_UID).findMany({
15387
16715
  filters: { isActive: true },
15388
16716
  fields: ["documentId", "lastActive", "loginTime", "nativeSessionId"],
15389
- populate: { user: { fields: ["id", "documentId"] } },
16717
+ populate: {
16718
+ user: perRole ? { fields: ["id", "documentId"], populate: { role: { fields: ["documentId"] } } } : { fields: ["id", "documentId"] }
16719
+ },
15390
16720
  limit: BATCH,
15391
16721
  start,
15392
16722
  sort: { loginTime: "asc" }
@@ -15394,8 +16724,11 @@ var require_session2 = __commonJS({
15394
16724
  if (!batch || batch.length === 0) break;
15395
16725
  for (const session of batch) {
15396
16726
  const lastActiveTime = session.lastActive ? new Date(session.lastActive) : session.loginTime ? new Date(session.loginTime) : null;
15397
- if (lastActiveTime && lastActiveTime < cutoffTime) {
15398
- sessionsToDeactivate.push(session);
16727
+ const sessionCutoff = perRole ? new Date(
16728
+ now.getTime() - inactivityTimeoutFor(settings, session.user?.role?.documentId || null)
16729
+ ) : cutoffTime;
16730
+ if (lastActiveTime && lastActiveTime < sessionCutoff) {
16731
+ sessionsToDeactivate.push({ ...session, cutoff: sessionCutoff });
15399
16732
  }
15400
16733
  }
15401
16734
  if (batch.length < BATCH) break;
@@ -15414,8 +16747,8 @@ var require_session2 = __commonJS({
15414
16747
  documentId: session.documentId,
15415
16748
  isActive: true,
15416
16749
  $or: [
15417
- { lastActive: { $lt: cutoffTime } },
15418
- { lastActive: { $null: true }, loginTime: { $lt: cutoffTime } }
16750
+ { lastActive: { $lt: session.cutoff } },
16751
+ { lastActive: { $null: true }, loginTime: { $lt: session.cutoff } }
15419
16752
  ]
15420
16753
  };
15421
16754
  if (nativeManager) {
@@ -16450,6 +17783,29 @@ var require_notifications = __commonJS({
16450
17783
  if (geoData.isThreat) warnings.push("Threat");
16451
17784
  return warnings;
16452
17785
  }
17786
+ var POLICY_TEMPLATES = Object.freeze({
17787
+ accountLocked: Object.freeze({
17788
+ subject: "Your account was locked after failed sign-ins",
17789
+ html: `<html>
17790
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
17791
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
17792
+ <h2>Your account was temporarily locked</h2>
17793
+ <p>Hello {{user.username}},</p>
17794
+ <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>
17795
+ <p>If these attempts were not yours, change your password after the lock ends.</p>
17796
+ <p style="color: #666; font-size: 12px;">This is an automated security notification.</p>
17797
+ </div>
17798
+ </body>
17799
+ </html>`,
17800
+ text: `Your account was temporarily locked
17801
+
17802
+ Hello {{user.username}},
17803
+
17804
+ There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
17805
+
17806
+ If these attempts were not yours, change your password after the lock ends.`
17807
+ })
17808
+ });
16453
17809
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
16454
17810
  var WEBHOOK_TIMEOUT_MS = 5e3;
16455
17811
  module2.exports = ({ strapi: strapi2 }) => ({
@@ -16555,9 +17911,60 @@ Account: {{user.email}}
16555
17911
  Time: {{session.loginTime}}
16556
17912
  IP: {{session.ipAddress}}
16557
17913
  VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
16558
- }
17914
+ },
17915
+ ...POLICY_TEMPLATES
16559
17916
  };
16560
17917
  },
17918
+ /**
17919
+ * One template by key. A stored template without html and text falls back
17920
+ * to the default of that key.
17921
+ *
17922
+ * @param {string} key Template key.
17923
+ * @returns {Promise<{subject: string, html: string, text: string}>} Template.
17924
+ */
17925
+ async getTemplate(key) {
17926
+ const templates = await this.getEmailTemplates();
17927
+ const template = templates?.[key];
17928
+ if (template && (template.html || template.text)) {
17929
+ return {
17930
+ subject: template.subject || POLICY_TEMPLATES[key]?.subject || "",
17931
+ html: template.html || "",
17932
+ text: template.text || ""
17933
+ };
17934
+ }
17935
+ return { ...POLICY_TEMPLATES[key] };
17936
+ },
17937
+ /**
17938
+ * Emails a user that their account was locked after failed sign-ins.
17939
+ * Sent through Strapi's email plugin, so a provider plugin such as Magic
17940
+ * Mail delivers it when installed.
17941
+ *
17942
+ * @param {{user: {email?: string, username?: string}, minutes: number, until: number}} params
17943
+ * Account, lock duration in minutes and lock end (epoch ms).
17944
+ * @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
17945
+ * @sideeffect Sends one email.
17946
+ */
17947
+ async sendAccountLockedEmail({ user, minutes, until }) {
17948
+ try {
17949
+ if (!user?.email) return false;
17950
+ const template = await this.getTemplate("accountLocked");
17951
+ const data = { user, lock: { minutes, until } };
17952
+ await strapi2.plugin("email").service("email").send({
17953
+ to: user.email,
17954
+ subject: this.replaceVariables(template.subject, data),
17955
+ html: this.replaceVariables(template.html, data),
17956
+ text: this.replaceVariables(template.text, data)
17957
+ });
17958
+ strapi2.log.info("[magic-sessionmanager/notifications] Account lock email sent");
17959
+ return true;
17960
+ } catch (err) {
17961
+ strapi2.log.error(
17962
+ "[magic-sessionmanager/notifications] Account lock email failed:",
17963
+ err?.name || "Error"
17964
+ );
17965
+ return false;
17966
+ }
17967
+ },
16561
17968
  /**
16562
17969
  * HTML-escapes a string to prevent XSS when it is interpolated into an
16563
17970
  * HTML email template. Non-string inputs are coerced to strings first.
@@ -16595,6 +18002,14 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
16595
18002
  result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
16596
18003
  result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
16597
18004
  result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
18005
+ result = result.replace(
18006
+ /\{\{lock\.minutes\}\}/g,
18007
+ esc(Number.isFinite(data.lock?.minutes) ? String(data.lock.minutes) : "N/A")
18008
+ );
18009
+ result = result.replace(
18010
+ /\{\{lock\.until\}\}/g,
18011
+ esc(Number.isFinite(data.lock?.until) ? new Date(data.lock.until).toUTCString() : "N/A")
18012
+ );
16598
18013
  const score = data.reason?.securityScore;
16599
18014
  result = result.replace(
16600
18015
  /\{\{reason\.securityScore\}\}/g,
@@ -17102,9 +18517,12 @@ var require_security_log = __commonJS({
17102
18517
  };
17103
18518
  const buildRows = async (batch, options, settings) => {
17104
18519
  const groups = /* @__PURE__ */ new Map();
18520
+ const recordUserSignIns = settings.recordUserSignInEvents !== false;
17105
18521
  const wanted = batch.filter((entry) => {
17106
18522
  const gate = recordingSwitchOf(entry.event);
17107
- return gate === "always" || (gate === "signIns" ? options.signIns : options.content);
18523
+ if (gate === "always") return true;
18524
+ if (gate === "userSignIns") return recordUserSignIns;
18525
+ return gate === "signIns" ? options.signIns : options.content;
17108
18526
  });
17109
18527
  if (!wanted.length) return { rows: [], groups };
17110
18528
  const emails = [
@@ -17590,6 +19008,29 @@ var require_security_log = __commonJS({
17590
19008
  * @returns {Promise<void>}
17591
19009
  * @sideeffect Deletes and updates rows of the security event table.
17592
19010
  */
19011
+ /**
19012
+ * Deletes what the log holds about an app user whose account was
19013
+ * deleted: events about the account and events the user caused.
19014
+ *
19015
+ * @param {string} userDocumentId Deleted user's documentId.
19016
+ * @returns {Promise<void>}
19017
+ * @sideeffect Deletes rows of the security event table.
19018
+ */
19019
+ async deleteUserData(userDocumentId) {
19020
+ const key = toId(userDocumentId);
19021
+ if (!key) return;
19022
+ queue = queue.filter(
19023
+ (entry) => !(entry.targetType === "user" && String(entry.targetId) === key) && !(entry.actorType === "user" && String(entry.actorId) === key)
19024
+ );
19025
+ await events().deleteMany({
19026
+ where: {
19027
+ $or: [
19028
+ { targetType: "user", targetId: key },
19029
+ { actorType: "user", actorId: key }
19030
+ ]
19031
+ }
19032
+ });
19033
+ },
17593
19034
  async deleteAdminData(adminId) {
17594
19035
  const id = toAdminId(adminId);
17595
19036
  if (!id) return;