strapi-plugin-magic-sessionmanager 4.8.0 → 4.9.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 (72) hide show
  1. package/CHANGELOG.md +83 -5
  2. package/README.md +379 -641
  3. package/dist/admin/Analytics-B6d-39Qh.js +420 -0
  4. package/dist/admin/Analytics-DxOWXHn8.mjs +418 -0
  5. package/dist/admin/App-ZsSGj7n8.mjs +1894 -0
  6. package/dist/admin/App-mRFV50K6.js +1896 -0
  7. package/dist/admin/License-BE6UQ_V3.mjs +443 -0
  8. package/dist/admin/License-DXt2oi6u.js +443 -0
  9. package/dist/admin/OnlineUsersWidget-CFvM3Vbp.js +273 -0
  10. package/dist/admin/OnlineUsersWidget-_tJ6aeWl.mjs +254 -0
  11. package/dist/admin/SectionCard-BlWv8CRt.js +54 -0
  12. package/dist/admin/SectionCard-D51bv4Hi.mjs +55 -0
  13. package/dist/admin/Settings-BUc12TP5.js +3570 -0
  14. package/dist/admin/Settings-dtW7cjTX.mjs +3568 -0
  15. package/dist/admin/de-BFKoGEVT.js +544 -0
  16. package/dist/admin/de-j0oZH9Pz.mjs +544 -0
  17. package/dist/admin/en-UY4Tb5tE.mjs +544 -0
  18. package/dist/admin/en-s7Ksdkcg.js +544 -0
  19. package/dist/admin/es-07OGMe_5.js +544 -0
  20. package/dist/admin/es-DGBcZwQy.mjs +544 -0
  21. package/dist/admin/fr-B6-DWhGO.mjs +544 -0
  22. package/dist/admin/fr-ETj_2UBY.js +544 -0
  23. package/dist/admin/index-C_SyRULc.mjs +1750 -0
  24. package/dist/admin/index-D4kEnXSp.js +1751 -0
  25. package/dist/admin/index.js +1 -1
  26. package/dist/admin/index.mjs +2 -2
  27. package/dist/admin/maskSensitiveValue-BWcSjow7.js +9 -0
  28. package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +10 -0
  29. package/dist/admin/pt-C7PwrQtV.js +544 -0
  30. package/dist/admin/pt-YMRLm9gx.mjs +544 -0
  31. package/dist/server/index.js +1092 -463
  32. package/dist/server/index.mjs +1092 -463
  33. package/package.json +10 -1
  34. package/pics/analytics.png +0 -0
  35. package/pics/dashboard-dark.png +0 -0
  36. package/pics/dashboard.png +0 -0
  37. package/pics/dashboardsessionmodal.png +0 -0
  38. package/pics/mobile-dashboard.png +0 -0
  39. package/pics/mobile-session.png +0 -0
  40. package/pics/sessioninfopanel.png +0 -0
  41. package/pics/settings1.png +0 -0
  42. package/pics/settings2.png +0 -0
  43. package/pics/widget.png +0 -0
  44. package/scripts/geoip-updater.cjs +35 -24
  45. package/dist/admin/Analytics-CaRlu5ad.js +0 -332
  46. package/dist/admin/Analytics-THqDbNX0.mjs +0 -330
  47. package/dist/admin/App-AbZwLHtF.js +0 -1263
  48. package/dist/admin/App-hSh7guii.mjs +0 -1261
  49. package/dist/admin/FormField-C8kIT2NE.mjs +0 -59
  50. package/dist/admin/FormField-b5KBvkrj.js +0 -60
  51. package/dist/admin/License-BXBVwUVu.mjs +0 -299
  52. package/dist/admin/License-CABdPwnd.js +0 -301
  53. package/dist/admin/OnlineUsersWidget-BnWFj9IM.mjs +0 -230
  54. package/dist/admin/OnlineUsersWidget-CPFAACSb.js +0 -230
  55. package/dist/admin/PluginPageLayout-BPFMcgrx.mjs +0 -42
  56. package/dist/admin/PluginPageLayout-DmNzMdqu.js +0 -43
  57. package/dist/admin/Settings-B4DNdeKx.js +0 -2152
  58. package/dist/admin/Settings-C4RsJosh.mjs +0 -2150
  59. package/dist/admin/de-AwIFTd9i.mjs +0 -450
  60. package/dist/admin/de-D23nmqnl.js +0 -450
  61. package/dist/admin/en-C5iYQ0mC.js +0 -450
  62. package/dist/admin/en-D6QEGeRh.mjs +0 -450
  63. package/dist/admin/es-CIXnsG-p.js +0 -435
  64. package/dist/admin/es-CnFfVdKw.mjs +0 -435
  65. package/dist/admin/fr-BglXE-W4.js +0 -435
  66. package/dist/admin/fr-DefoR7uH.mjs +0 -435
  67. package/dist/admin/index-BFVITQ-o.mjs +0 -624
  68. package/dist/admin/index-DlMm-NyK.js +0 -625
  69. package/dist/admin/maskSensitiveValue-1uGWmrfG.mjs +0 -20
  70. package/dist/admin/maskSensitiveValue-B9vhxPad.js +0 -19
  71. package/dist/admin/pt-J5sf7jiY.js +0 -435
  72. package/dist/admin/pt-TODwvNQA.mjs +0 -435
@@ -119,12 +119,30 @@ var require_content_api_permissions = __commonJS({
119
119
  }
120
120
  });
121
121
 
122
+ // server/src/utils/block-revocation-scope.js
123
+ var require_block_revocation_scope = __commonJS({
124
+ "server/src/utils/block-revocation-scope.js"(exports2, module2) {
125
+ "use strict";
126
+ var { AsyncLocalStorage } = require("node:async_hooks");
127
+ var storage = new AsyncLocalStorage();
128
+ function runWithCallerRevocation(userDocumentId, fn) {
129
+ return storage.run({ userDocumentId: String(userDocumentId) }, fn);
130
+ }
131
+ function isCallerRevocationScope(userDocumentId) {
132
+ const scope = storage.getStore();
133
+ return Boolean(scope && userDocumentId && scope.userDocumentId === String(userDocumentId));
134
+ }
135
+ module2.exports = { runWithCallerRevocation, isCallerRevocationScope };
136
+ }
137
+ });
138
+
122
139
  // server/src/register.js
123
140
  var require_register = __commonJS({
124
141
  "server/src/register.js"(exports2, module2) {
125
142
  "use strict";
126
143
  var { createLogger } = require_logger();
127
144
  var { createContentApiPermissionsLifecycle } = require_content_api_permissions();
145
+ var { isCallerRevocationScope } = require_block_revocation_scope();
128
146
  var USER_UID = "plugin::users-permissions.user";
129
147
  module2.exports = async ({ strapi: strapi2 }) => {
130
148
  const log = createLogger(strapi2);
@@ -177,6 +195,7 @@ var require_register = __commonJS({
177
195
  if (!data || data.blocked !== true) return;
178
196
  const userDocId = result.documentId;
179
197
  if (!userDocId) return;
198
+ if (isCallerRevocationScope(userDocId)) return;
180
199
  const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
181
200
  const { terminatedCount: terminated } = await sessionService.terminateSession({
182
201
  userId: userDocId,
@@ -241,7 +260,10 @@ var require_getClientIp = __commonJS({
241
260
  return "unknown";
242
261
  } catch (error) {
243
262
  if (ctx?.app?.context?.strapi?.log?.debug) {
244
- ctx.app.context.strapi.log.debug("[getClientIp] Error extracting IP:", error?.name || "Error");
263
+ ctx.app.context.strapi.log.debug(
264
+ "[getClientIp] Error extracting IP:",
265
+ error?.name || "Error"
266
+ );
245
267
  }
246
268
  return "unknown";
247
269
  }
@@ -274,6 +296,7 @@ var require_encryption = __commonJS({
274
296
  var crypto = require("crypto");
275
297
  var ALGORITHM = "aes-256-gcm";
276
298
  var IV_LENGTH = 16;
299
+ var AUTH_TAG_LENGTH = 16;
277
300
  var warnedMissingKey = false;
278
301
  var isProduction = () => process.env.NODE_ENV === "production";
279
302
  function getEncryptionKey() {
@@ -307,9 +330,12 @@ var require_encryption = __commonJS({
307
330
  return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
308
331
  } catch (err) {
309
332
  if (typeof strapi !== "undefined" && strapi?.log) {
310
- strapi.log.error("[magic-sessionmanager/encryption] Encryption failed:", err?.name || "Error");
333
+ strapi.log.error(
334
+ "[magic-sessionmanager/encryption] Encryption failed:",
335
+ err?.name || "Error"
336
+ );
311
337
  }
312
- throw new Error("Failed to encrypt token");
338
+ throw new Error("Failed to encrypt token", { cause: err });
313
339
  }
314
340
  }
315
341
  function decryptToken(encryptedToken) {
@@ -323,14 +349,19 @@ var require_encryption = __commonJS({
323
349
  const iv = Buffer.from(parts[0], "hex");
324
350
  const authTag = Buffer.from(parts[1], "hex");
325
351
  const encrypted = parts[2];
326
- const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
352
+ const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, {
353
+ authTagLength: AUTH_TAG_LENGTH
354
+ });
327
355
  decipher.setAuthTag(authTag);
328
356
  let decrypted = decipher.update(encrypted, "hex", "utf8");
329
357
  decrypted += decipher.final("utf8");
330
358
  return decrypted;
331
359
  } catch (err) {
332
360
  if (typeof strapi !== "undefined" && strapi?.log) {
333
- strapi.log.error("[magic-sessionmanager/encryption] Decryption failed:", err?.name || "Error");
361
+ strapi.log.error(
362
+ "[magic-sessionmanager/encryption] Decryption failed:",
363
+ err?.name || "Error"
364
+ );
334
365
  }
335
366
  return null;
336
367
  }
@@ -528,14 +559,16 @@ var require_settings_loader = __commonJS({
528
559
  return cached;
529
560
  }
530
561
  const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
531
- let storedSettings = {};
562
+ let storedSettings;
532
563
  try {
533
564
  const pluginStore = strapi2.store({ type: "plugin", name: PLUGIN_ID });
534
565
  const raw = await pluginStore.get({ key: SETTINGS_KEY });
535
566
  storedSettings = normalizeStoredSettings(raw);
536
567
  } catch {
537
- strapi2.log.error(`[${PLUGIN_ID}] settings-loader: store read failed; strict session enforcement is enabled`);
538
- storedSettings = { strictSessionEnforcement: true };
568
+ strapi2.log.error(
569
+ `[${PLUGIN_ID}] settings-loader: store read failed; strict session enforcement is enabled and geolocation is disabled`
570
+ );
571
+ storedSettings = { strictSessionEnforcement: true, enableGeolocation: false };
539
572
  }
540
573
  const merged = { ...staticConfig, ...storedSettings };
541
574
  cached = merged;
@@ -913,6 +946,9 @@ var require_auth_routes = __commonJS({
913
946
  }
914
947
  return null;
915
948
  }
949
+ function isPasswordResetRequest(path, method) {
950
+ return requestKey(path, String(method || "").toUpperCase()) === "POST /api/auth/reset-password";
951
+ }
916
952
  function shouldRunPreAuthGeoGuard(path, method) {
917
953
  return classifyJwtIssuingRequest(path, method) === "new-session";
918
954
  }
@@ -922,6 +958,7 @@ var require_auth_routes = __commonJS({
922
958
  module2.exports = {
923
959
  classifyJwtIssuingRequest,
924
960
  isFailedLoginTrackedPath,
961
+ isPasswordResetRequest,
925
962
  shouldRunPreAuthGeoGuard
926
963
  };
927
964
  }
@@ -1108,7 +1145,10 @@ var require_last_seen = __commonJS({
1108
1145
  try {
1109
1146
  userDocId = await resolveUserDocumentId(strapi2, ctx.state.user.id);
1110
1147
  } catch (err) {
1111
- strapi2.log.debug("[magic-sessionmanager] user document lookup failed:", err?.name || "Error");
1148
+ strapi2.log.debug(
1149
+ "[magic-sessionmanager] user document lookup failed:",
1150
+ err?.name || "Error"
1151
+ );
1112
1152
  return;
1113
1153
  }
1114
1154
  }
@@ -1121,7 +1161,7 @@ var require_last_seen = __commonJS({
1121
1161
  if (!nativeSessionId && !tokenHashValue) {
1122
1162
  return;
1123
1163
  }
1124
- let thisSession = null;
1164
+ let thisSession;
1125
1165
  try {
1126
1166
  const filters = { user: { documentId: userDocId } };
1127
1167
  if (nativeSessionId) {
@@ -5090,15 +5130,9 @@ var require_bootstrap = __commonJS({
5090
5130
  var { encryptToken, hashToken } = require_encryption();
5091
5131
  var { createLogger } = require_logger();
5092
5132
  var { resolveUserDocumentId } = require_resolve_user();
5093
- var {
5094
- getPluginSettings,
5095
- getSessionCreationGraceMs
5096
- } = require_settings_loader();
5133
+ var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
5097
5134
  var { extractBearerToken } = require_extract_token();
5098
- var {
5099
- setSessionRejectionReason,
5100
- consumeSessionRejectionReason
5101
- } = require_rejection_cache();
5135
+ var { setSessionRejectionReason } = require_rejection_cache();
5102
5136
  var { evaluateGeoFirewall } = require_geo_firewall();
5103
5137
  var { REVOCATION_UID } = require_session_revocation();
5104
5138
  var { getNativeSessionManager } = require_native_session_manager();
@@ -5106,6 +5140,7 @@ var require_bootstrap = __commonJS({
5106
5140
  var {
5107
5141
  classifyJwtIssuingRequest,
5108
5142
  isFailedLoginTrackedPath,
5143
+ isPasswordResetRequest,
5109
5144
  shouldRunPreAuthGeoGuard
5110
5145
  } = require_auth_routes();
5111
5146
  var {
@@ -5118,7 +5153,7 @@ var require_bootstrap = __commonJS({
5118
5153
  var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
5119
5154
  var deferredContentApiPermissionSetup = /* @__PURE__ */ new WeakMap();
5120
5155
  async function getRequestSettings(strapi2, ctx) {
5121
- let settings = {};
5156
+ let settings;
5122
5157
  try {
5123
5158
  settings = await getPluginSettings(strapi2);
5124
5159
  } catch {
@@ -5140,7 +5175,7 @@ var require_bootstrap = __commonJS({
5140
5175
  }
5141
5176
  try {
5142
5177
  await ensureSessionLookupIndexes(strapi2, log);
5143
- await registerSessionAwareAuthStrategy(strapi2, log);
5178
+ await registerSessionAwareAuthStrategy(strapi2);
5144
5179
  const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
5145
5180
  await licenseGuardService.initialize();
5146
5181
  log.info("[SUCCESS] Session Manager active - all features are available without a license key");
@@ -5197,9 +5232,12 @@ var require_bootstrap = __commonJS({
5197
5232
  }, RETENTION_INTERVAL_MS);
5198
5233
  strapi2.sessionManagerIntervals.retentionTimeout = handle;
5199
5234
  };
5200
- strapi2.sessionManagerIntervals.retentionStartup = setTimeout(() => {
5201
- scheduleRetention();
5202
- }, 5 * 60 * 1e3);
5235
+ strapi2.sessionManagerIntervals.retentionStartup = setTimeout(
5236
+ () => {
5237
+ scheduleRetention();
5238
+ },
5239
+ 5 * 60 * 1e3
5240
+ );
5203
5241
  log.info("[TIME] Dynamic cleanup + retention scheduled");
5204
5242
  mountPreLoginGeoGuard({ strapi: strapi2, log });
5205
5243
  mountFailedLoginLockout({ strapi: strapi2, log });
@@ -5207,13 +5245,9 @@ var require_bootstrap = __commonJS({
5207
5245
  mountLoginInterceptor({ strapi: strapi2, log, sessionService });
5208
5246
  mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
5209
5247
  mountLogoutInterceptor({ strapi: strapi2, log, sessionService });
5210
- strapi2.server.use(
5211
- require_session_rejection_headers()({}, { strapi: strapi2 })
5212
- );
5248
+ strapi2.server.use(require_session_rejection_headers()({}, { strapi: strapi2 }));
5213
5249
  log.info("[SUCCESS] Session-rejection-headers middleware mounted");
5214
- strapi2.server.use(
5215
- require_last_seen()({ strapi: strapi2, sessionService })
5216
- );
5250
+ strapi2.server.use(require_last_seen()({ strapi: strapi2, sessionService }));
5217
5251
  log.info("[SUCCESS] LastSeen middleware mounted");
5218
5252
  const contentApiPermissionsReady = await ensureContentApiPermissions(strapi2, log);
5219
5253
  mountDeferredContentApiPermissionRetry({
@@ -5222,7 +5256,9 @@ var require_bootstrap = __commonJS({
5222
5256
  initiallyReady: contentApiPermissionsReady
5223
5257
  });
5224
5258
  log.info("[SUCCESS] Bootstrap complete");
5225
- log.info("[READY] Session Manager ready! Sessions stored in plugin::magic-sessionmanager.session");
5259
+ log.info(
5260
+ "[READY] Session Manager ready! Sessions stored in plugin::magic-sessionmanager.session"
5261
+ );
5226
5262
  } catch (err) {
5227
5263
  log.error("[ERROR] Bootstrap error:", err?.name || "Error");
5228
5264
  }
@@ -5292,67 +5328,83 @@ var require_bootstrap = __commonJS({
5292
5328
  } catch {
5293
5329
  jwt = null;
5294
5330
  }
5295
- strapi2.server.routes([{
5296
- method: "POST",
5297
- path: "/api/auth/logout",
5298
- handler: async (ctx) => {
5299
- try {
5300
- const token = extractBearerToken(ctx);
5301
- if (!token) {
5302
- ctx.status = 401;
5303
- ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Authorization token required" } };
5304
- return;
5305
- }
5306
- const jwtService = strapi2.plugin("users-permissions").service("jwt");
5307
- let decoded = null;
5331
+ strapi2.server.routes([
5332
+ {
5333
+ method: "POST",
5334
+ path: "/api/auth/logout",
5335
+ handler: async (ctx) => {
5308
5336
  try {
5309
- decoded = await jwtService.verify(token);
5310
- } catch (verifyErr) {
5311
- const isExpired = verifyErr?.name === "TokenExpiredError" || /expired/i.test(verifyErr?.message || "");
5312
- if (isExpired && jwt) {
5313
- try {
5314
- const jwtSecret = strapi2.config.get("plugin::users-permissions.jwtSecret");
5315
- if (jwtSecret) {
5316
- decoded = jwt.verify(token, jwtSecret, { ignoreExpiration: true });
5337
+ const token = extractBearerToken(ctx);
5338
+ if (!token) {
5339
+ ctx.status = 401;
5340
+ ctx.body = {
5341
+ error: {
5342
+ status: 401,
5343
+ name: "UnauthorizedError",
5344
+ message: "Authorization token required"
5345
+ }
5346
+ };
5347
+ return;
5348
+ }
5349
+ const jwtService = strapi2.plugin("users-permissions").service("jwt");
5350
+ let decoded = null;
5351
+ try {
5352
+ decoded = await jwtService.verify(token);
5353
+ } catch (verifyErr) {
5354
+ const isExpired = verifyErr?.name === "TokenExpiredError" || /expired/i.test(verifyErr?.message || "");
5355
+ if (isExpired && jwt) {
5356
+ try {
5357
+ const jwtSecret = strapi2.config.get("plugin::users-permissions.jwtSecret");
5358
+ if (jwtSecret) {
5359
+ decoded = jwt.verify(token, jwtSecret, { ignoreExpiration: true });
5360
+ }
5361
+ } catch {
5362
+ decoded = null;
5317
5363
  }
5318
- } catch {
5319
- decoded = null;
5320
5364
  }
5365
+ if (!decoded) {
5366
+ ctx.status = 401;
5367
+ ctx.body = {
5368
+ error: { status: 401, name: "UnauthorizedError", message: "Invalid token" }
5369
+ };
5370
+ return;
5371
+ }
5372
+ }
5373
+ if (!decoded || !decoded.id) {
5374
+ ctx.status = 401;
5375
+ ctx.body = {
5376
+ error: { status: 401, name: "UnauthorizedError", message: "Invalid token" }
5377
+ };
5378
+ return;
5321
5379
  }
5322
- if (!decoded) {
5380
+ const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
5381
+ if (!userDocumentId) {
5323
5382
  ctx.status = 401;
5324
- ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
5383
+ ctx.body = {
5384
+ error: { status: 401, name: "UnauthorizedError", message: "Invalid token" }
5385
+ };
5325
5386
  return;
5326
5387
  }
5388
+ await sessionService.terminateAuthenticatedSession({
5389
+ userDocumentId,
5390
+ accessToken: token,
5391
+ refreshToken: null
5392
+ });
5393
+ ctx.status = 200;
5394
+ ctx.body = { ok: true, message: "Logged out successfully" };
5395
+ } catch (err) {
5396
+ log.error("Logout error:", err?.name || "Error");
5397
+ ctx.status = 500;
5398
+ ctx.body = {
5399
+ error: { status: 500, name: "InternalServerError", message: "Logout failed" }
5400
+ };
5327
5401
  }
5328
- if (!decoded || !decoded.id) {
5329
- ctx.status = 401;
5330
- ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
5331
- return;
5332
- }
5333
- const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
5334
- if (!userDocumentId) {
5335
- ctx.status = 401;
5336
- ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
5337
- return;
5338
- }
5339
- await sessionService.terminateAuthenticatedSession({
5340
- userDocumentId,
5341
- accessToken: token,
5342
- refreshToken: null
5343
- });
5344
- ctx.status = 200;
5345
- ctx.body = { ok: true, message: "Logged out successfully" };
5346
- } catch (err) {
5347
- log.error("Logout error:", err?.name || "Error");
5348
- ctx.status = 500;
5349
- ctx.body = { error: { status: 500, name: "InternalServerError", message: "Logout failed" } };
5402
+ },
5403
+ config: {
5404
+ auth: false
5350
5405
  }
5351
- },
5352
- config: {
5353
- auth: false
5354
5406
  }
5355
- }]);
5407
+ ]);
5356
5408
  log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
5357
5409
  }
5358
5410
  function hasRegisteredRoute(strapi2, method, path) {
@@ -5403,7 +5455,8 @@ var require_bootstrap = __commonJS({
5403
5455
  throw new Error("native refresh token owner does not match the authentication response");
5404
5456
  }
5405
5457
  const userDocumentId = resolvedUserDocumentId || user?.documentId;
5406
- if (!userDocumentId) throw new Error("native refresh token owner has no resolvable user documentId");
5458
+ if (!userDocumentId)
5459
+ throw new Error("native refresh token owner has no resolvable user documentId");
5407
5460
  return { userId, userDocumentId, sessionId: String(validation.sessionId) };
5408
5461
  }
5409
5462
  async function compensateNativeSession({ nativeSessionManager, nativeSession, log }) {
@@ -5474,9 +5527,7 @@ var require_bootstrap = __commonJS({
5474
5527
  } else if (ctx.status >= 400 && ctx.status < 500 && ctx.status !== 429) {
5475
5528
  const entry = recordFailure(ip, maxFailed);
5476
5529
  if (entry.blockedUntil > now) {
5477
- log.warn(
5478
- `[LOCKOUT] Client locked for 15min after ${entry.count} failed login attempts`
5479
- );
5530
+ log.warn(`[LOCKOUT] Client locked for 15min after ${entry.count} failed login attempts`);
5480
5531
  }
5481
5532
  }
5482
5533
  });
@@ -5518,7 +5569,8 @@ var require_bootstrap = __commonJS({
5518
5569
  refreshToken: newRefreshToken,
5519
5570
  nativeSessionId: nativeSession2.sessionId
5520
5571
  });
5521
- if (!rotated) throw new Error("current sidecar changed before native password rotation was linked");
5572
+ if (!rotated)
5573
+ throw new Error("current sidecar changed before native password rotation was linked");
5522
5574
  log.info("[PASSWORD] Native session link updated");
5523
5575
  } else {
5524
5576
  const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
@@ -5568,7 +5620,13 @@ var require_bootstrap = __commonJS({
5568
5620
  if (!rotated) throw new Error("current session changed before token rotation");
5569
5621
  log.info("[PASSWORD] Legacy session tokens rotated");
5570
5622
  } catch (err) {
5571
- failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "change-password rotation failed", error: err });
5623
+ failClosedAuthResponse({
5624
+ ctx,
5625
+ strapi: strapi2,
5626
+ log,
5627
+ operation: "change-password rotation failed",
5628
+ error: err
5629
+ });
5572
5630
  }
5573
5631
  return;
5574
5632
  }
@@ -5614,6 +5672,14 @@ var require_bootstrap = __commonJS({
5614
5672
  if (!newSession?.documentId) {
5615
5673
  throw new Error(`session creation returned no documentId for user ${userDocId}`);
5616
5674
  }
5675
+ if (isPasswordResetRequest(ctx.path, ctx.method)) {
5676
+ await sessionService.terminateSession({
5677
+ userId: userDocId,
5678
+ exceptSessionId: newSession.documentId,
5679
+ reason: "logout"
5680
+ });
5681
+ log.info("[PASSWORD] Ended older sessions after password reset");
5682
+ }
5617
5683
  log.info("[SUCCESS] End-user session metadata created");
5618
5684
  try {
5619
5685
  const settings = await getPluginSettings(strapi2);
@@ -5654,7 +5720,9 @@ var require_bootstrap = __commonJS({
5654
5720
  limit: 50
5655
5721
  });
5656
5722
  const previousCountries = new Set(
5657
- (previousSessions || []).flatMap((session) => countryTokensFromGeo(session.geoLocation))
5723
+ (previousSessions || []).flatMap(
5724
+ (session) => countryTokensFromGeo(session.geoLocation)
5725
+ )
5658
5726
  );
5659
5727
  const currentCountries = countryTokensFromGeo(geoData);
5660
5728
  if (currentCountries.length > 0 && previousCountries.size > 0 && !currentCountries.some((country) => previousCountries.has(country))) {
@@ -5739,7 +5807,13 @@ var require_bootstrap = __commonJS({
5739
5807
  if (nativeSessionManager && nativeSession) {
5740
5808
  await compensateNativeSession({ nativeSessionManager, nativeSession, log });
5741
5809
  }
5742
- failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "session creation failed", error: err });
5810
+ failClosedAuthResponse({
5811
+ ctx,
5812
+ strapi: strapi2,
5813
+ log,
5814
+ operation: "session creation failed",
5815
+ error: err
5816
+ });
5743
5817
  }
5744
5818
  });
5745
5819
  log.info("[SUCCESS] Login interceptor middleware mounted");
@@ -5792,7 +5866,13 @@ var require_bootstrap = __commonJS({
5792
5866
  }
5793
5867
  }
5794
5868
  } catch (err) {
5795
- failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh validation failed", error: err });
5869
+ failClosedAuthResponse({
5870
+ ctx,
5871
+ strapi: strapi2,
5872
+ log,
5873
+ operation: "refresh validation failed",
5874
+ error: err
5875
+ });
5796
5876
  return;
5797
5877
  }
5798
5878
  await next();
@@ -5817,7 +5897,8 @@ var require_bootstrap = __commonJS({
5817
5897
  refreshToken: newRefreshToken,
5818
5898
  nativeSessionId: nativeSession.sessionId
5819
5899
  });
5820
- if (!rotated) throw new Error("current sidecar changed before native refresh was linked");
5900
+ if (!rotated)
5901
+ throw new Error("current sidecar changed before native refresh was linked");
5821
5902
  log.info("[REFRESH] Native session link updated");
5822
5903
  } else {
5823
5904
  const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
@@ -5861,7 +5942,13 @@ var require_bootstrap = __commonJS({
5861
5942
  if (!rotated) throw new Error("refresh token was already consumed");
5862
5943
  log.info("[REFRESH] Legacy session tokens refreshed");
5863
5944
  } catch (err) {
5864
- failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "refresh rotation failed", error: err });
5945
+ failClosedAuthResponse({
5946
+ ctx,
5947
+ strapi: strapi2,
5948
+ log,
5949
+ operation: "refresh rotation failed",
5950
+ error: err
5951
+ });
5865
5952
  }
5866
5953
  }
5867
5954
  });
@@ -5873,7 +5960,10 @@ var require_bootstrap = __commonJS({
5873
5960
  const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
5874
5961
  const accessToken = extractBearerToken(ctx);
5875
5962
  const nativeMode = usesNativeRefreshSessions(strapi2);
5876
- const jwtManagement = strapi2.config.get("plugin::users-permissions.jwtManagement", "legacy-support");
5963
+ const jwtManagement = strapi2.config.get(
5964
+ "plugin::users-permissions.jwtManagement",
5965
+ "legacy-support"
5966
+ );
5877
5967
  await next();
5878
5968
  const isUsersPermissionsLogoutRoute = ctx.state?.route?.handler === "auth.logout" && ctx.state?.route?.info?.pluginName === "users-permissions";
5879
5969
  const isSuccessful = isUsersPermissionsLogoutRoute && ctx.status >= 200 && ctx.status < 300;
@@ -5883,11 +5973,14 @@ var require_bootstrap = __commonJS({
5883
5973
  try {
5884
5974
  if (nativeMode) {
5885
5975
  const nativeSessionId = ctx.state?.session?.id;
5886
- if (!nativeSessionId) throw new Error("authenticated logout has no native session identifier");
5976
+ if (!nativeSessionId)
5977
+ throw new Error("authenticated logout has no native session identifier");
5887
5978
  const nativeSessionManager = getNativeSessionManager(strapi2);
5888
5979
  const nativeSessionStillActive = await nativeSessionManager.isSessionActive(nativeSessionId);
5889
5980
  if (nativeSessionStillActive) {
5890
- throw new Error("Users & Permissions logout returned success while the native session remains active");
5981
+ throw new Error(
5982
+ "Users & Permissions logout returned success while the native session remains active"
5983
+ );
5891
5984
  }
5892
5985
  }
5893
5986
  const userDocumentId = authenticatedUser.documentId || await resolveUserDocumentId(strapi2, authenticatedUser.id);
@@ -5905,7 +5998,13 @@ var require_bootstrap = __commonJS({
5905
5998
  message: "Logged out successfully"
5906
5999
  };
5907
6000
  } catch (err) {
5908
- failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
6001
+ failClosedAuthResponse({
6002
+ ctx,
6003
+ strapi: strapi2,
6004
+ log,
6005
+ operation: "logout termination failed",
6006
+ error: err
6007
+ });
5909
6008
  }
5910
6009
  });
5911
6010
  log.info("[SUCCESS] Logout interceptor middleware mounted");
@@ -5978,7 +6077,9 @@ var require_bootstrap = __commonJS({
5978
6077
  return true;
5979
6078
  } catch (err) {
5980
6079
  log.warn("Could not auto-configure permissions:", err?.name || "Error");
5981
- log.warn("Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated");
6080
+ log.warn(
6081
+ "Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
6082
+ );
5982
6083
  return false;
5983
6084
  }
5984
6085
  }
@@ -6040,7 +6141,10 @@ var require_bootstrap = __commonJS({
6040
6141
  );
6041
6142
  hasIndex = result.rows.length > 0;
6042
6143
  } else if (dialect === "mysql" || dialect === "mysql2") {
6043
- const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [tableName, definition.name]);
6144
+ const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
6145
+ tableName,
6146
+ definition.name
6147
+ ]);
6044
6148
  hasIndex = result[0].length > 0;
6045
6149
  } else if (dialect === "sqlite" || dialect === "better-sqlite3") {
6046
6150
  const result = await knex.raw(
@@ -6059,7 +6163,10 @@ var require_bootstrap = __commonJS({
6059
6163
  log.info(`[INDEX] Created ${definition.name}`);
6060
6164
  }
6061
6165
  } catch (err) {
6062
- log.debug("[INDEX] Could not create session lookup indexes (will retry on next startup):", err?.name || "Error");
6166
+ log.debug(
6167
+ "[INDEX] Could not create session lookup indexes (will retry on next startup):",
6168
+ err?.name || "Error"
6169
+ );
6063
6170
  }
6064
6171
  }
6065
6172
  var sessionCheckErrors = { count: 0, lastReset: Date.now() };
@@ -6086,7 +6193,7 @@ var require_bootstrap = __commonJS({
6086
6193
  const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
6087
6194
  return Date.now() - loginTime > maxAgeMs;
6088
6195
  }
6089
- async function registerSessionAwareAuthStrategy(strapi2, log) {
6196
+ async function registerSessionAwareAuthStrategy(strapi2) {
6090
6197
  try {
6091
6198
  const usersPermissionsPlugin = strapi2.plugin("users-permissions");
6092
6199
  if (!usersPermissionsPlugin) {
@@ -6116,7 +6223,9 @@ var require_bootstrap = __commonJS({
6116
6223
  if (nativeMode) {
6117
6224
  if (typeof decoded.sessionId !== "string" || decoded.sessionId.length === 0) {
6118
6225
  setSessionRejectionReason(tokenHashValue, "manual");
6119
- strapi2.log.info("[magic-sessionmanager] [JWT-REJECTED] Native access token has no session identifier");
6226
+ strapi2.log.info(
6227
+ "[magic-sessionmanager] [JWT-REJECTED] Native access token has no session identifier"
6228
+ );
6120
6229
  return null;
6121
6230
  }
6122
6231
  try {
@@ -6124,7 +6233,9 @@ var require_bootstrap = __commonJS({
6124
6233
  const nativeSessionActive = await nativeSessionManager.isSessionActive(decoded.sessionId);
6125
6234
  if (!nativeSessionActive) {
6126
6235
  setSessionRejectionReason(tokenHashValue, "manual");
6127
- strapi2.log.info("[magic-sessionmanager] [JWT-REJECTED] Native session is missing or revoked");
6236
+ strapi2.log.info(
6237
+ "[magic-sessionmanager] [JWT-REJECTED] Native session is missing or revoked"
6238
+ );
6128
6239
  return null;
6129
6240
  }
6130
6241
  } catch (err) {
@@ -6144,7 +6255,10 @@ var require_bootstrap = __commonJS({
6144
6255
  fields: ["documentId", "expiresAt"]
6145
6256
  });
6146
6257
  } catch (err) {
6147
- strapi2.log.error("[magic-sessionmanager] [JWT] Revocation lookup failed; rejecting token:", err?.name || "Error");
6258
+ strapi2.log.error(
6259
+ "[magic-sessionmanager] [JWT] Revocation lookup failed; rejecting token:",
6260
+ err?.name || "Error"
6261
+ );
6148
6262
  return null;
6149
6263
  }
6150
6264
  if (revocation) {
@@ -6168,7 +6282,9 @@ var require_bootstrap = __commonJS({
6168
6282
  const userDocId = await resolveUserDocumentId(strapi2, decoded.id);
6169
6283
  if (!userDocId) {
6170
6284
  if (strictMode) {
6171
- strapi2.log.warn("[magic-sessionmanager] [JWT] User documentId could not be resolved; rejecting in strict mode");
6285
+ strapi2.log.warn(
6286
+ "[magic-sessionmanager] [JWT] User documentId could not be resolved; rejecting in strict mode"
6287
+ );
6172
6288
  return null;
6173
6289
  }
6174
6290
  strapi2.log.debug("[magic-sessionmanager] [JWT] No documentId found in relaxed mode");
@@ -6182,13 +6298,21 @@ var require_bootstrap = __commonJS({
6182
6298
  });
6183
6299
  } catch (err) {
6184
6300
  if (strictMode) {
6185
- strapi2.log.error("[magic-sessionmanager] [JWT] User lookup failed in strict mode; rejecting token:", err?.name || "Error");
6301
+ strapi2.log.error(
6302
+ "[magic-sessionmanager] [JWT] User lookup failed in strict mode; rejecting token:",
6303
+ err?.name || "Error"
6304
+ );
6186
6305
  return null;
6187
6306
  }
6188
- strapi2.log.debug("[magic-sessionmanager] [JWT] User lookup failed in relaxed mode:", err?.name || "Error");
6307
+ strapi2.log.debug(
6308
+ "[magic-sessionmanager] [JWT] User lookup failed in relaxed mode:",
6309
+ err?.name || "Error"
6310
+ );
6189
6311
  }
6190
6312
  if (!userRecord && strictMode) {
6191
- strapi2.log.warn("[magic-sessionmanager] [JWT] User record could not be resolved; rejecting in strict mode");
6313
+ strapi2.log.warn(
6314
+ "[magic-sessionmanager] [JWT] User record could not be resolved; rejecting in strict mode"
6315
+ );
6192
6316
  return null;
6193
6317
  }
6194
6318
  if (userRecord?.blocked === true) {
@@ -6266,9 +6390,7 @@ var require_bootstrap = __commonJS({
6266
6390
  documentId: thisSession.documentId,
6267
6391
  data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
6268
6392
  });
6269
- strapi2.log.info(
6270
- "[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated"
6271
- );
6393
+ strapi2.log.info("[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated");
6272
6394
  resetErrorCounter();
6273
6395
  return decoded;
6274
6396
  }
@@ -6296,23 +6418,39 @@ var require_bootstrap = __commonJS({
6296
6418
  return decoded;
6297
6419
  } catch (err) {
6298
6420
  if (strictMode) {
6299
- strapi2.log.error("[magic-sessionmanager] [JWT] Session check failed in strict mode; rejecting token:", err?.name || "Error");
6421
+ strapi2.log.error(
6422
+ "[magic-sessionmanager] [JWT] Session check failed in strict mode; rejecting token:",
6423
+ err?.name || "Error"
6424
+ );
6300
6425
  return null;
6301
6426
  }
6302
6427
  if (shouldFailOpen()) {
6303
- strapi2.log.warn("[magic-sessionmanager] [JWT] Session check error (allowing):", err?.name || "Error");
6428
+ strapi2.log.warn(
6429
+ "[magic-sessionmanager] [JWT] Session check error (allowing):",
6430
+ err?.name || "Error"
6431
+ );
6304
6432
  return decoded;
6305
6433
  }
6306
- strapi2.log.error("[magic-sessionmanager] [JWT] Too many consecutive errors, blocking request:", err?.name || "Error");
6434
+ strapi2.log.error(
6435
+ "[magic-sessionmanager] [JWT] Too many consecutive errors, blocking request:",
6436
+ err?.name || "Error"
6437
+ );
6307
6438
  return null;
6308
6439
  }
6309
6440
  };
6310
6441
  jwtService.verify[JWT_WRAPPED_FLAG] = true;
6311
6442
  jwtService[JWT_WRAPPED_FLAG] = true;
6312
- strapi2.log.info("[magic-sessionmanager] [AUTH] [SUCCESS] JWT verify wrapped with session validation");
6443
+ strapi2.log.info(
6444
+ "[magic-sessionmanager] [AUTH] [SUCCESS] JWT verify wrapped with session validation"
6445
+ );
6313
6446
  } catch (err) {
6314
- strapi2.log.warn("[magic-sessionmanager] [AUTH] Could not wrap JWT verify:", err?.name || "Error");
6315
- strapi2.log.warn("[magic-sessionmanager] [AUTH] Session validation will only work via middleware (plugin endpoints)");
6447
+ strapi2.log.warn(
6448
+ "[magic-sessionmanager] [AUTH] Could not wrap JWT verify:",
6449
+ err?.name || "Error"
6450
+ );
6451
+ strapi2.log.warn(
6452
+ "[magic-sessionmanager] [AUTH] Session validation will only work via middleware (plugin endpoints)"
6453
+ );
6316
6454
  }
6317
6455
  }
6318
6456
  module2.exports.__private = {
@@ -6783,7 +6921,7 @@ var require_admin = __commonJS({
6783
6921
  handler: "session.toggleUserBlock",
6784
6922
  config: {
6785
6923
  policies: adminPolicy(),
6786
- description: "Toggle user blocked status (admin)"
6924
+ description: "Set an explicit user blocked status (admin)"
6787
6925
  }
6788
6926
  },
6789
6927
  {
@@ -6943,11 +7081,12 @@ var require_user_agent_parser = __commonJS({
6943
7081
  osVersion: null
6944
7082
  };
6945
7083
  }
6946
- const ua = userAgent.toLowerCase();
6947
7084
  let deviceType = "desktop";
6948
- if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
7085
+ if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
7086
+ deviceType = "tablet";
7087
+ } else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
6949
7088
  deviceType = "mobile";
6950
- } else if (/tablet|ipad|android(?!.*mobile)|kindle|silk/i.test(userAgent)) {
7089
+ } else if (/android(?!.*mobile)/i.test(userAgent)) {
6951
7090
  deviceType = "tablet";
6952
7091
  } else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
6953
7092
  deviceType = "bot";
@@ -6956,46 +7095,46 @@ var require_user_agent_parser = __commonJS({
6956
7095
  let browserVersion = null;
6957
7096
  if (/edg\//i.test(userAgent)) {
6958
7097
  browserName = "Edge";
6959
- browserVersion = extractVersion(userAgent, /edg\/(\d+[\.\d]*)/i);
7098
+ browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
6960
7099
  } else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
6961
7100
  browserName = "Opera";
6962
- browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s\/](\d+[\.\d]*)/i);
7101
+ browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
6963
7102
  } else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
6964
7103
  browserName = "Chrome";
6965
- browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[\.\d]*)/i);
7104
+ browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
6966
7105
  } else if (/firefox|fxios/i.test(userAgent)) {
6967
7106
  browserName = "Firefox";
6968
- browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[\.\d]*)/i);
7107
+ browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
6969
7108
  } else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
6970
7109
  browserName = "Safari";
6971
- browserVersion = extractVersion(userAgent, /version\/(\d+[\.\d]*)/i);
7110
+ browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
6972
7111
  } else if (/msie|trident/i.test(userAgent)) {
6973
7112
  browserName = "Internet Explorer";
6974
- browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[\.\d]*)/i);
7113
+ browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
6975
7114
  }
6976
7115
  let osName = "unknown";
6977
7116
  let osVersion = null;
6978
7117
  if (/windows nt/i.test(userAgent)) {
6979
7118
  osName = "Windows";
6980
- const winVersion = extractVersion(userAgent, /windows nt (\d+[\.\d]*)/i);
7119
+ const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
6981
7120
  const winVersionMap = {
6982
7121
  "10.0": "10/11",
6983
- "6.3": "8.1",
6984
- "6.2": "8",
6985
- "6.1": "7",
7122
+ 6.3: "8.1",
7123
+ 6.2: "8",
7124
+ 6.1: "7",
6986
7125
  "6.0": "Vista",
6987
- "5.1": "XP"
7126
+ 5.1: "XP"
6988
7127
  };
6989
7128
  osVersion = winVersionMap[winVersion] || winVersion;
6990
- } else if (/mac os x/i.test(userAgent)) {
6991
- osName = "macOS";
6992
- osVersion = extractVersion(userAgent, /mac os x (\d+[_\.\d]*)/i)?.replace(/_/g, ".");
6993
7129
  } else if (/iphone|ipad|ipod/i.test(userAgent)) {
6994
7130
  osName = "iOS";
6995
- osVersion = extractVersion(userAgent, /os (\d+[_\.\d]*)/i)?.replace(/_/g, ".");
7131
+ osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
7132
+ } else if (/mac os x/i.test(userAgent)) {
7133
+ osName = "macOS";
7134
+ osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
6996
7135
  } else if (/android/i.test(userAgent)) {
6997
7136
  osName = "Android";
6998
- osVersion = extractVersion(userAgent, /android (\d+[\.\d]*)/i);
7137
+ osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
6999
7138
  } else if (/linux/i.test(userAgent)) {
7000
7139
  osName = "Linux";
7001
7140
  } else if (/cros/i.test(userAgent)) {
@@ -7119,14 +7258,141 @@ var require_enhance_session = __commonJS({
7119
7258
  async function enhanceSessions(sessions, opts = {}, maxGeoLookups = 20) {
7120
7259
  const geoCounter = { remaining: maxGeoLookups };
7121
7260
  const now = /* @__PURE__ */ new Date();
7122
- return Promise.all(
7123
- sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now }))
7124
- );
7261
+ return Promise.all(sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now })));
7125
7262
  }
7126
7263
  module2.exports = { enhanceSession, enhanceSessions, shouldResolveGeoData };
7127
7264
  }
7128
7265
  });
7129
7266
 
7267
+ // server/src/utils/native-session-view.js
7268
+ var require_native_session_view = __commonJS({
7269
+ "server/src/utils/native-session-view.js"(exports2, module2) {
7270
+ "use strict";
7271
+ var NATIVE_SESSION_PREFIX = "native_";
7272
+ function createNativeSessionKey(userDocumentId, nativeSessionId) {
7273
+ if (typeof userDocumentId !== "string" || !userDocumentId || typeof nativeSessionId !== "string" || !nativeSessionId) {
7274
+ throw new TypeError("Native session view keys require an owner documentId and session ID.");
7275
+ }
7276
+ const payload = Buffer.from(JSON.stringify([userDocumentId, nativeSessionId])).toString(
7277
+ "base64url"
7278
+ );
7279
+ if (payload.length > 2048) {
7280
+ throw new RangeError("Native session view key exceeds the supported URL-safe length.");
7281
+ }
7282
+ return `${NATIVE_SESSION_PREFIX}${payload}`;
7283
+ }
7284
+ function parseNativeSessionKey(value) {
7285
+ if (typeof value !== "string" || !value.startsWith(NATIVE_SESSION_PREFIX)) return null;
7286
+ const encoded = value.slice(NATIVE_SESSION_PREFIX.length);
7287
+ if (!encoded || encoded.length > 2048 || !/^[A-Za-z0-9_-]+$/.test(encoded)) return null;
7288
+ try {
7289
+ const decoded = Buffer.from(encoded, "base64url").toString("utf8");
7290
+ if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded) return null;
7291
+ const payload = JSON.parse(decoded);
7292
+ if (!Array.isArray(payload) || payload.length !== 2 || typeof payload[0] !== "string" || !payload[0] || typeof payload[1] !== "string" || !payload[1]) {
7293
+ return null;
7294
+ }
7295
+ return {
7296
+ userDocumentId: payload[0],
7297
+ nativeSessionId: payload[1]
7298
+ };
7299
+ } catch {
7300
+ return null;
7301
+ }
7302
+ }
7303
+ function mapNativeSessionToView(session, user) {
7304
+ const nativeId = String(session.sessionId);
7305
+ const stableId = createNativeSessionKey(String(user.documentId), nativeId);
7306
+ const metadata = session.metadata && typeof session.metadata === "object" ? session.metadata : {};
7307
+ const loginAt = typeof metadata.loginAt === "string" && !Number.isNaN(Date.parse(metadata.loginAt)) ? new Date(metadata.loginAt) : null;
7308
+ const createdAt = session.createdAt && !Number.isNaN(new Date(session.createdAt).getTime()) ? new Date(session.createdAt) : null;
7309
+ const userView = {
7310
+ documentId: user.documentId,
7311
+ email: user.email,
7312
+ username: user.username
7313
+ };
7314
+ return {
7315
+ documentId: stableId,
7316
+ id: stableId,
7317
+ sessionId: stableId,
7318
+ nativeSessionId: nativeId,
7319
+ user: userView,
7320
+ ipAddress: null,
7321
+ userAgent: null,
7322
+ loginTime: loginAt || createdAt,
7323
+ logoutTime: null,
7324
+ lastActive: createdAt || loginAt,
7325
+ isActive: true,
7326
+ terminatedManually: false,
7327
+ geoLocation: null,
7328
+ securityScore: null,
7329
+ deviceType: null,
7330
+ deviceName: typeof metadata.deviceName === "string" ? metadata.deviceName : void 0,
7331
+ browserName: null,
7332
+ osName: null
7333
+ };
7334
+ }
7335
+ function markSessionsTruncated(sessions, truncated) {
7336
+ Object.defineProperty(sessions, "truncated", {
7337
+ value: Boolean(truncated),
7338
+ enumerable: false,
7339
+ configurable: false,
7340
+ writable: false
7341
+ });
7342
+ return sessions;
7343
+ }
7344
+ module2.exports = {
7345
+ NATIVE_SESSION_PREFIX,
7346
+ createNativeSessionKey,
7347
+ parseNativeSessionKey,
7348
+ mapNativeSessionToView,
7349
+ markSessionsTruncated
7350
+ };
7351
+ }
7352
+ });
7353
+
7354
+ // server/src/utils/http-errors.js
7355
+ var require_http_errors = __commonJS({
7356
+ "server/src/utils/http-errors.js"(exports2, module2) {
7357
+ "use strict";
7358
+ var SERVER_ERROR_METHODS = {
7359
+ 500: "internalServerError",
7360
+ 502: "badGateway",
7361
+ 503: "serviceUnavailable"
7362
+ };
7363
+ var SERVER_ERROR_NAMES = {
7364
+ 500: "InternalServerError",
7365
+ 502: "BadGatewayError",
7366
+ 503: "ServiceUnavailableError"
7367
+ };
7368
+ function sendServerError(ctx, status, message, details) {
7369
+ const method = SERVER_ERROR_METHODS[status] || SERVER_ERROR_METHODS[500];
7370
+ if (typeof ctx[method] === "function") return ctx[method](message, details || {});
7371
+ if (status === 500 && typeof ctx.internalServerError === "function") {
7372
+ return ctx.internalServerError(message, details || {});
7373
+ }
7374
+ const finalStatus = SERVER_ERROR_METHODS[status] ? status : 500;
7375
+ ctx.status = finalStatus;
7376
+ ctx.body = {
7377
+ data: null,
7378
+ error: {
7379
+ status: finalStatus,
7380
+ name: SERVER_ERROR_NAMES[finalStatus],
7381
+ message,
7382
+ details: details || {}
7383
+ }
7384
+ };
7385
+ return ctx.body;
7386
+ }
7387
+ function sendValidationError(ctx, message, errors) {
7388
+ return ctx.badRequest(message, {
7389
+ errors: errors.map((error) => ({ ...error, name: "ValidationError" }))
7390
+ });
7391
+ }
7392
+ module2.exports = { sendServerError, sendValidationError };
7393
+ }
7394
+ });
7395
+
7130
7396
  // server/src/controllers/session.js
7131
7397
  var require_session = __commonJS({
7132
7398
  "server/src/controllers/session.js"(exports2, module2) {
@@ -7138,11 +7404,11 @@ var require_session = __commonJS({
7138
7404
  shouldResolveGeoData
7139
7405
  } = require_enhance_session();
7140
7406
  var { resolveUserDocumentId } = require_resolve_user();
7141
- var {
7142
- getPluginSettings,
7143
- getSessionCreationGraceMs
7144
- } = require_settings_loader();
7407
+ var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
7145
7408
  var { extractBearerToken } = require_extract_token();
7409
+ var { parseNativeSessionKey } = require_native_session_view();
7410
+ var { runWithCallerRevocation } = require_block_revocation_scope();
7411
+ var { sendServerError } = require_http_errors();
7146
7412
  var SESSION_UID = "plugin::magic-sessionmanager.session";
7147
7413
  var USER_UID = "plugin::users-permissions.user";
7148
7414
  var OWN_SESSIONS_LIMIT = 200;
@@ -7187,6 +7453,23 @@ var require_session = __commonJS({
7187
7453
  const value = ctx?.state?.session?.id ?? ctx?.state?.auth?.credentials?.sessionId;
7188
7454
  return typeof value === "string" && value.length > 0 ? value : null;
7189
7455
  }
7456
+ var PRIVATE_SESSION_FIELDS = [
7457
+ "token",
7458
+ "tokenHash",
7459
+ "refreshToken",
7460
+ "refreshTokenHash",
7461
+ "nativeSessionId"
7462
+ ];
7463
+ function toPublicSession(session, { admin = false } = {}) {
7464
+ if (!session || typeof session !== "object") return session;
7465
+ const safe = { ...session };
7466
+ for (const field of PRIVATE_SESSION_FIELDS) delete safe[field];
7467
+ if (admin) delete safe.sessionId;
7468
+ return safe;
7469
+ }
7470
+ function toPublicSessions(sessions, options) {
7471
+ return Array.isArray(sessions) ? sessions.map((session) => toPublicSession(session, options)) : sessions;
7472
+ }
7190
7473
  function getSessionViewKey(session) {
7191
7474
  const key = session?.documentId ?? session?.id ?? session?.sessionId;
7192
7475
  return key === void 0 || key === null ? null : String(key);
@@ -7245,10 +7528,7 @@ var require_session = __commonJS({
7245
7528
  data: { totalUsers, blockedUsers }
7246
7529
  });
7247
7530
  } catch (error) {
7248
- strapi.log.error(
7249
- "[magic-sessionmanager] getUserStatsAdmin failed:",
7250
- error?.name || "Error"
7251
- );
7531
+ strapi.log.error("[magic-sessionmanager] getUserStatsAdmin failed:", error?.name || "Error");
7252
7532
  return ctx.internalServerError("Unable to load end-user counts");
7253
7533
  }
7254
7534
  },
@@ -7261,7 +7541,7 @@ var require_session = __commonJS({
7261
7541
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
7262
7542
  const sessions = await sessionService.getAllSessions();
7263
7543
  ctx.body = {
7264
- data: sessions,
7544
+ data: toPublicSessions(sessions, { admin: true }),
7265
7545
  meta: {
7266
7546
  count: sessions.length,
7267
7547
  active: sessions.filter((s) => s.isTrulyActive).length,
@@ -7283,7 +7563,7 @@ var require_session = __commonJS({
7283
7563
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
7284
7564
  const sessions = await sessionService.getActiveSessions();
7285
7565
  ctx.body = {
7286
- data: sessions,
7566
+ data: toPublicSessions(sessions, { admin: true }),
7287
7567
  meta: { count: sessions.length, ...getTruncationMeta(sessions) }
7288
7568
  };
7289
7569
  } catch (err) {
@@ -7323,7 +7603,7 @@ var require_session = __commonJS({
7323
7603
  return new Date(b.loginTime || 0) - new Date(a.loginTime || 0);
7324
7604
  });
7325
7605
  ctx.body = {
7326
- data: sessionsWithCurrent2,
7606
+ data: toPublicSessions(sessionsWithCurrent2),
7327
7607
  meta: {
7328
7608
  count: sessionsWithCurrent2.length,
7329
7609
  active: sessionsWithCurrent2.filter((session) => session.isTrulyActive).length,
@@ -7351,9 +7631,7 @@ var require_session = __commonJS({
7351
7631
  };
7352
7632
  const sessionsWithCurrent = await enhanceSessions(paged, enhanceOpts, 20);
7353
7633
  for (const s of sessionsWithCurrent) {
7354
- s.isCurrentSession = !!(currentTokenHash && paged.find(
7355
- (raw) => raw.documentId === s.documentId && raw.tokenHash === currentTokenHash
7356
- ));
7634
+ s.isCurrentSession = !!(currentTokenHash && paged.find((raw) => raw.documentId === s.documentId && raw.tokenHash === currentTokenHash));
7357
7635
  }
7358
7636
  sessionsWithCurrent.sort((a, b) => {
7359
7637
  if (a.isCurrentSession) return -1;
@@ -7361,7 +7639,7 @@ var require_session = __commonJS({
7361
7639
  return new Date(b.loginTime) - new Date(a.loginTime);
7362
7640
  });
7363
7641
  ctx.body = {
7364
- data: sessionsWithCurrent,
7642
+ data: toPublicSessions(sessionsWithCurrent),
7365
7643
  meta: {
7366
7644
  count: sessionsWithCurrent.length,
7367
7645
  active: sessionsWithCurrent.filter((s) => s.isTrulyActive).length,
@@ -7385,7 +7663,9 @@ var require_session = __commonJS({
7385
7663
  const requestingUserDocId = await resolveAuthUserDocId(ctx);
7386
7664
  if (!isAdminRequest) {
7387
7665
  if (!requestingUserDocId) {
7388
- strapi.log.warn("[magic-sessionmanager] Denied a session lookup without a verifiable user identity");
7666
+ strapi.log.warn(
7667
+ "[magic-sessionmanager] Denied a session lookup without a verifiable user identity"
7668
+ );
7389
7669
  return ctx.forbidden("Cannot verify user identity");
7390
7670
  }
7391
7671
  const requestedDocId = await resolveUserDocumentId(strapi, userId);
@@ -7399,7 +7679,7 @@ var require_session = __commonJS({
7399
7679
  if (!serviceUserId) return ctx.forbidden("Cannot verify user identity");
7400
7680
  const sessions = await sessionService.getUserSessions(serviceUserId);
7401
7681
  ctx.body = {
7402
- data: sessions,
7682
+ data: toPublicSessions(sessions, { admin: isAdminRequest }),
7403
7683
  meta: { count: sessions.length, ...getTruncationMeta(sessions) }
7404
7684
  };
7405
7685
  } catch (err) {
@@ -7676,7 +7956,10 @@ var require_session = __commonJS({
7676
7956
  data: { ...enhanced, isCurrentSession: true }
7677
7957
  };
7678
7958
  } catch (err) {
7679
- strapi.log.error("[magic-sessionmanager] Error getting current session:", err?.name || "Error");
7959
+ strapi.log.error(
7960
+ "[magic-sessionmanager] Error getting current session:",
7961
+ err?.name || "Error"
7962
+ );
7680
7963
  return ctx.internalServerError("Error fetching current session");
7681
7964
  }
7682
7965
  },
@@ -7741,10 +8024,12 @@ var require_session = __commonJS({
7741
8024
  }
7742
8025
  const sessionUserId = sessionToTerminate.user?.documentId;
7743
8026
  if (sessionUserId !== userDocId) {
7744
- strapi.log.warn("[magic-sessionmanager] Denied an attempt to terminate another user session");
7745
- return ctx.forbidden("You can only terminate your own sessions");
8027
+ strapi.log.warn(
8028
+ "[magic-sessionmanager] Denied an attempt to terminate another user session"
8029
+ );
8030
+ return ctx.notFound("Session not found");
7746
8031
  }
7747
- if (currentTokenHash && sessionToTerminate.tokenHash === currentTokenHash) {
8032
+ if (isNativeSessionMode() && isCurrentNativeSession(sessionToTerminate, getCurrentNativeSessionId(ctx)) || currentTokenHash && sessionToTerminate.tokenHash === currentTokenHash) {
7748
8033
  return ctx.badRequest("Cannot terminate the current session. Use /logout instead.");
7749
8034
  }
7750
8035
  const alreadyTerminated = sessionToTerminate.isActive === false;
@@ -7758,7 +8043,10 @@ var require_session = __commonJS({
7758
8043
  alreadyTerminated
7759
8044
  };
7760
8045
  } catch (err) {
7761
- strapi.log.error("[magic-sessionmanager] Error terminating own session:", err?.name || "Error");
8046
+ strapi.log.error(
8047
+ "[magic-sessionmanager] Error terminating own session:",
8048
+ err?.name || "Error"
8049
+ );
7762
8050
  return ctx.internalServerError("Error terminating session");
7763
8051
  }
7764
8052
  },
@@ -7800,12 +8088,23 @@ var require_session = __commonJS({
7800
8088
  },
7801
8089
  /**
7802
8090
  * Terminates a specific session (admin action).
8091
+ * A missing target returns 404; existing native-only rows remain supported.
7803
8092
  */
7804
8093
  async terminateSingleSession(ctx) {
7805
8094
  try {
7806
8095
  const { sessionId } = ctx.params;
7807
8096
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
7808
- await sessionService.terminateSession({ sessionId, reason: "manual" });
8097
+ let nativeTargetExists = false;
8098
+ if (isNativeSessionMode() && sessionId?.startsWith(NATIVE_SESSION_KEY_PREFIX)) {
8099
+ const nativeKey = parseNativeSessionKey(sessionId);
8100
+ if (!nativeKey) return ctx.notFound("Session not found");
8101
+ const sessions = await sessionService.getUserSessions(nativeKey.userDocumentId);
8102
+ nativeTargetExists = !!findOwnedNativeSession(sessions, sessionId);
8103
+ if (!nativeTargetExists) return ctx.notFound("Session not found");
8104
+ }
8105
+ const result = await sessionService.terminateSession({ sessionId, reason: "manual" });
8106
+ if (!nativeTargetExists && result?.terminatedCount === 0)
8107
+ return ctx.notFound("Session not found");
7809
8108
  ctx.body = {
7810
8109
  message: `Session ${sessionId} terminated`,
7811
8110
  success: true
@@ -7817,10 +8116,17 @@ var require_session = __commonJS({
7817
8116
  },
7818
8117
  /**
7819
8118
  * Terminates ALL sessions for a specific user (admin action).
8119
+ * Unknown numeric IDs and document IDs return 404 before revocation.
7820
8120
  */
7821
8121
  async terminateAllUserSessions(ctx) {
7822
8122
  try {
7823
8123
  const { userId } = ctx.params;
8124
+ const numericId = /^\d+$/.test(userId) ? Number(userId) : null;
8125
+ const user = await strapi.db.query(USER_UID).findOne({
8126
+ where: numericId === null ? { documentId: userId } : { id: numericId },
8127
+ select: ["id"]
8128
+ });
8129
+ if (!user) return ctx.notFound("User not found");
7824
8130
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
7825
8131
  await sessionService.terminateSession({ userId, reason: "manual" });
7826
8132
  ctx.body = {
@@ -7828,7 +8134,10 @@ var require_session = __commonJS({
7828
8134
  success: true
7829
8135
  };
7830
8136
  } catch (err) {
7831
- strapi.log.error("[magic-sessionmanager] Error terminating all user sessions:", err?.name || "Error");
8137
+ strapi.log.error(
8138
+ "[magic-sessionmanager] Error terminating all user sessions:",
8139
+ err?.name || "Error"
8140
+ );
7832
8141
  return ctx.internalServerError("Error terminating all user sessions");
7833
8142
  }
7834
8143
  },
@@ -7877,7 +8186,10 @@ var require_session = __commonJS({
7877
8186
  data: ipData
7878
8187
  };
7879
8188
  } catch (err) {
7880
- strapi.log.error("[magic-sessionmanager] Error getting IP geolocation:", err?.name || "Error");
8189
+ strapi.log.error(
8190
+ "[magic-sessionmanager] Error getting IP geolocation:",
8191
+ err?.name || "Error"
8192
+ );
7881
8193
  return ctx.internalServerError("Error fetching IP geolocation data");
7882
8194
  }
7883
8195
  },
@@ -7909,6 +8221,9 @@ var require_session = __commonJS({
7909
8221
  * @route POST /magic-sessionmanager/sessions/clean-inactive
7910
8222
  * @sideeffect Deletes inactive session rows and retains token deny records
7911
8223
  * until expiry
8224
+ * @returns {Promise<void>} 200 with `deletedCount`, or 500 whose
8225
+ * `error.details` carries `deletedCount` and `failedCount` when some rows
8226
+ * could not be removed
7912
8227
  */
7913
8228
  async cleanInactiveSessions(ctx) {
7914
8229
  try {
@@ -7920,16 +8235,51 @@ var require_session = __commonJS({
7920
8235
  deletedCount
7921
8236
  };
7922
8237
  } catch (err) {
7923
- strapi.log.error("[magic-sessionmanager] Error cleaning inactive sessions:", err?.name || "Error");
8238
+ if (err?.name === "PartialCleanupError") {
8239
+ strapi.log.warn("[magic-sessionmanager] Inactive session cleanup finished partially");
8240
+ return sendServerError(ctx, 500, "Some inactive session records could not be removed", {
8241
+ deletedCount: Number(err.deletedCount) || 0,
8242
+ failedCount: Number(err.failedCount) || 0
8243
+ });
8244
+ }
8245
+ strapi.log.error(
8246
+ "[magic-sessionmanager] Error cleaning inactive sessions:",
8247
+ err?.name || "Error"
8248
+ );
7924
8249
  return ctx.internalServerError("Error deleting inactive sessions");
7925
8250
  }
7926
8251
  },
7927
8252
  /**
7928
- * Toggles a user's blocked status and terminates their sessions on block.
8253
+ * Sets or toggles an end user's blocked state.
8254
+ *
8255
+ * - `{ blocked: true | false }` sets that state (retry-safe, used by the
8256
+ * admin UI). A repeated block also retries session revocation, including
8257
+ * after an earlier partial failure.
8258
+ * - A request without `blocked` keeps the pre-4.9 behaviour and toggles the
8259
+ * stored state. It is deprecated because a retried toggle can undo itself.
8260
+ * - A `blocked` value that is present but not a boolean is rejected with 400
8261
+ * before any mutation.
8262
+ *
8263
+ * The response keeps `message`, `blocked` and `success`; `mode`
8264
+ * (`'explicit' | 'toggle'`) is additive.
8265
+ *
8266
+ * Requires an authenticated administrator with the plugin access permission.
8267
+ * @route POST /magic-sessionmanager/user/:userId/toggle-block
8268
+ * @param {object} ctx - Strapi context; optional body.blocked boolean.
8269
+ * @returns {Promise<void>} Writes the resulting state or a 400, 404 or 500 response.
8270
+ * @sideeffect Updates the user and, when blocking, revokes their sessions
8271
+ * exactly once (the user lifecycle skips this update). A failed revocation
8272
+ * can leave the user blocked with partially active sessions.
7929
8273
  */
7930
8274
  async toggleUserBlock(ctx) {
7931
8275
  try {
7932
8276
  const { userId } = ctx.params;
8277
+ const body = ctx.request?.body;
8278
+ const hasRequestedState = body !== null && typeof body === "object" && Object.prototype.hasOwnProperty.call(body, "blocked") && body.blocked !== void 0;
8279
+ const requestedBlocked = hasRequestedState ? body.blocked : void 0;
8280
+ if (hasRequestedState && typeof requestedBlocked !== "boolean") {
8281
+ return ctx.badRequest("A boolean blocked state is required");
8282
+ }
7933
8283
  let userDocumentId = await resolveUserDocumentId(strapi, userId);
7934
8284
  if (!userDocumentId) {
7935
8285
  try {
@@ -7947,11 +8297,15 @@ var require_session = __commonJS({
7947
8297
  if (!user) {
7948
8298
  return ctx.notFound("User not found");
7949
8299
  }
7950
- const newBlockedStatus = !user.blocked;
7951
- await strapi.documents(USER_UID).update({
7952
- documentId: userDocumentId,
7953
- data: { blocked: newBlockedStatus }
7954
- });
8300
+ const mode = hasRequestedState ? "explicit" : "toggle";
8301
+ const newBlockedStatus = hasRequestedState ? requestedBlocked : !user.blocked;
8302
+ await runWithCallerRevocation(
8303
+ userDocumentId,
8304
+ () => strapi.documents(USER_UID).update({
8305
+ documentId: userDocumentId,
8306
+ data: { blocked: newBlockedStatus }
8307
+ })
8308
+ );
7955
8309
  if (newBlockedStatus) {
7956
8310
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
7957
8311
  await sessionService.terminateSession({ userId: userDocumentId, reason: "blocked" });
@@ -7959,7 +8313,8 @@ var require_session = __commonJS({
7959
8313
  ctx.body = {
7960
8314
  message: `User ${newBlockedStatus ? "blocked" : "unblocked"} successfully`,
7961
8315
  blocked: newBlockedStatus,
7962
- success: true
8316
+ success: true,
8317
+ mode
7963
8318
  };
7964
8319
  } catch (err) {
7965
8320
  strapi.log.error("[magic-sessionmanager] Error toggling user block:", err?.name || "Error");
@@ -7974,6 +8329,9 @@ var require_session = __commonJS({
7974
8329
  var require_license = __commonJS({
7975
8330
  "server/src/controllers/license.js"(exports2, module2) {
7976
8331
  "use strict";
8332
+ var { sendServerError } = require_http_errors();
8333
+ var PROVIDER_UNREACHABLE_MESSAGE = "License server unreachable. The plugin keeps working without a key.";
8334
+ var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
7977
8335
  module2.exports = ({ strapi: strapi2 }) => ({
7978
8336
  async getStatus(ctx) {
7979
8337
  try {
@@ -8027,8 +8385,11 @@ var require_license = __commonJS({
8027
8385
  }
8028
8386
  });
8029
8387
  } catch (error) {
8030
- strapi2.log.error("[magic-sessionmanager] Error getting license status:", error?.name || "Error");
8031
- return ctx.badRequest("Error getting license status");
8388
+ strapi2.log.error(
8389
+ "[magic-sessionmanager] Error getting license status:",
8390
+ error?.name || "Error"
8391
+ );
8392
+ return sendServerError(ctx, 500, "Error getting license status");
8032
8393
  }
8033
8394
  },
8034
8395
  async autoCreate(ctx) {
@@ -8044,7 +8405,7 @@ var require_license = __commonJS({
8044
8405
  lastName: adminUser.lastname || "User"
8045
8406
  });
8046
8407
  if (!license) {
8047
- return ctx.badRequest("License server unreachable. The plugin keeps working without a key.");
8408
+ return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
8048
8409
  }
8049
8410
  await licenseGuard.storeLicenseKey(license.licenseKey);
8050
8411
  return ctx.send({
@@ -8053,20 +8414,23 @@ var require_license = __commonJS({
8053
8414
  data: license
8054
8415
  });
8055
8416
  } catch (error) {
8056
- strapi2.log.error("[magic-sessionmanager] Error auto-creating license:", error?.name || "Error");
8057
- return ctx.badRequest("Error creating license");
8417
+ strapi2.log.error(
8418
+ "[magic-sessionmanager] Error auto-creating license:",
8419
+ error?.name || "Error"
8420
+ );
8421
+ return sendServerError(ctx, 500, "Error creating license");
8058
8422
  }
8059
8423
  },
8060
8424
  async createAndActivate(ctx) {
8061
8425
  try {
8062
8426
  const { email, firstName, lastName } = ctx.request.body || {};
8063
- if (!email || !firstName || !lastName) {
8427
+ if (![email, firstName, lastName].every((value) => typeof value === "string" && value.trim())) {
8064
8428
  return ctx.badRequest("Email, firstName, and lastName are required");
8065
8429
  }
8066
8430
  const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8067
8431
  const license = await licenseGuard.createLicense({ email, firstName, lastName });
8068
8432
  if (!license) {
8069
- return ctx.badRequest("License server unreachable. The plugin keeps working without a key.");
8433
+ return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
8070
8434
  }
8071
8435
  await licenseGuard.storeLicenseKey(license.licenseKey);
8072
8436
  return ctx.send({
@@ -8076,7 +8440,7 @@ var require_license = __commonJS({
8076
8440
  });
8077
8441
  } catch (error) {
8078
8442
  strapi2.log.error("[magic-sessionmanager] Error creating license:", error?.name || "Error");
8079
- return ctx.badRequest("Error creating license");
8443
+ return sendServerError(ctx, 500, "Error creating license");
8080
8444
  }
8081
8445
  },
8082
8446
  async ping(ctx) {
@@ -8095,17 +8459,22 @@ var require_license = __commonJS({
8095
8459
  });
8096
8460
  } catch (error) {
8097
8461
  strapi2.log.error("[magic-sessionmanager] Error refreshing license:", error?.name || "Error");
8098
- return ctx.badRequest("Error refreshing license");
8462
+ return sendServerError(ctx, 500, "Error refreshing license");
8099
8463
  }
8100
8464
  },
8101
8465
  async storeKey(ctx) {
8102
8466
  try {
8103
8467
  const { licenseKey, email } = ctx.request.body || {};
8104
- if (!licenseKey || !licenseKey.trim()) {
8468
+ if (typeof licenseKey !== "string" || !licenseKey.trim()) {
8105
8469
  return ctx.badRequest("License key is required");
8106
8470
  }
8471
+ if (email !== void 0 && email !== null && email !== "") {
8472
+ if (typeof email !== "string" || !EMAIL_PATTERN.test(email.trim())) {
8473
+ return ctx.badRequest("Email must be a valid email address");
8474
+ }
8475
+ }
8107
8476
  const trimmedKey = licenseKey.trim();
8108
- const trimmedEmail = email?.trim().toLowerCase() || null;
8477
+ const trimmedEmail = typeof email === "string" && email.trim() ? email.trim().toLowerCase() : null;
8109
8478
  const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
8110
8479
  const verification = await licenseGuard.verifyLicense(trimmedKey);
8111
8480
  if (!verification.valid && !verification.networkError) {
@@ -8125,7 +8494,7 @@ var require_license = __commonJS({
8125
8494
  });
8126
8495
  } catch (error) {
8127
8496
  strapi2.log.error("[magic-sessionmanager] Error storing license key:", error?.name || "Error");
8128
- return ctx.badRequest("Error validating license key");
8497
+ return sendServerError(ctx, 500, "Error validating license key");
8129
8498
  }
8130
8499
  }
8131
8500
  });
@@ -8145,7 +8514,12 @@ var require_geoip_updater = __commonJS({
8145
8514
  var gunzip = promisify(zlib.gunzip);
8146
8515
  var DEFAULT_EDITION_ID = "GeoLite2-City";
8147
8516
  var DEFAULT_MMDB_NAME = `${DEFAULT_EDITION_ID}.mmdb`;
8148
- var DEFAULT_GEOIP_DIRECTORY = path.resolve(process2.cwd(), "data", "magic-sessionmanager", "geoip");
8517
+ var DEFAULT_GEOIP_DIRECTORY = path.resolve(
8518
+ process2.cwd(),
8519
+ "data",
8520
+ "magic-sessionmanager",
8521
+ "geoip"
8522
+ );
8149
8523
  var DEFAULT_OUTPUT_PATH = path.join(DEFAULT_GEOIP_DIRECTORY, DEFAULT_MMDB_NAME);
8150
8524
  var SUPPORTED_EDITION_IDS = /* @__PURE__ */ new Set([
8151
8525
  "GeoLite2-City",
@@ -8153,7 +8527,9 @@ var require_geoip_updater = __commonJS({
8153
8527
  "GeoIP2-City",
8154
8528
  "GeoIP2-Country"
8155
8529
  ]);
8156
- var SUPPORTED_MMDB_NAMES = new Set([...SUPPORTED_EDITION_IDS].map((editionId) => `${editionId}.mmdb`));
8530
+ var SUPPORTED_MMDB_NAMES = new Set(
8531
+ [...SUPPORTED_EDITION_IDS].map((editionId) => `${editionId}.mmdb`)
8532
+ );
8157
8533
  function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
8158
8534
  const root = path.resolve(directory);
8159
8535
  if (value !== void 0 && typeof value !== "string") {
@@ -8246,12 +8622,7 @@ var require_geoip_updater = __commonJS({
8246
8622
  force
8247
8623
  };
8248
8624
  }
8249
- function needsDownload({
8250
- force,
8251
- localExists,
8252
- localMetadata,
8253
- remoteLastModified
8254
- }) {
8625
+ function needsDownload({ force, localExists, localMetadata, remoteLastModified }) {
8255
8626
  if (force) return true;
8256
8627
  if (!localExists) return true;
8257
8628
  if (!remoteLastModified) return true;
@@ -8400,13 +8771,20 @@ var require_geoip_updater = __commonJS({
8400
8771
  const archive = await fetchArchive(url, authHeader);
8401
8772
  const extracted = await extractMmdbFromTarGz(archive, mmdbFileName);
8402
8773
  await writeAtomic(outputPath, extracted.data);
8403
- await writeAtomic(metadataPath, JSON.stringify({
8404
- editionId,
8405
- sourceFile: extracted.name,
8406
- lastModified: head.lastModified,
8407
- downloadedAt: (/* @__PURE__ */ new Date()).toISOString(),
8408
- sourceUrl: url
8409
- }, null, 2));
8774
+ await writeAtomic(
8775
+ metadataPath,
8776
+ JSON.stringify(
8777
+ {
8778
+ editionId,
8779
+ sourceFile: extracted.name,
8780
+ lastModified: head.lastModified,
8781
+ downloadedAt: (/* @__PURE__ */ new Date()).toISOString(),
8782
+ sourceUrl: url
8783
+ },
8784
+ null,
8785
+ 2
8786
+ )
8787
+ );
8410
8788
  return {
8411
8789
  changed: true,
8412
8790
  outputPath,
@@ -8440,13 +8818,12 @@ var require_settings = __commonJS({
8440
8818
  "server/src/controllers/settings.js"(exports2, module2) {
8441
8819
  "use strict";
8442
8820
  var {
8443
- getSessionCreationGraceMs,
8444
8821
  invalidateSettingsCache,
8445
8822
  normalizeGeoIpProvider,
8446
- normalizeGeoLookupFailureMode,
8447
- normalizeRetentionDays
8823
+ normalizeGeoLookupFailureMode
8448
8824
  } = require_settings_loader();
8449
8825
  var { resolveDatabaseTarget } = require_geoip_updater();
8826
+ var { sendServerError, sendValidationError } = require_http_errors();
8450
8827
  var path = require("node:path");
8451
8828
  var ALLOWED_WEBHOOK_DOMAINS = {
8452
8829
  discord: ["discord.com", "discordapp.com"],
@@ -8469,13 +8846,6 @@ var require_settings = __commonJS({
8469
8846
  return "";
8470
8847
  }
8471
8848
  }
8472
- function sanitizeCountryList(list) {
8473
- if (!Array.isArray(list)) return [];
8474
- return list.filter((code) => typeof code === "string" && /^[A-Z]{2}$/.test(code.trim().toUpperCase())).map((code) => code.trim().toUpperCase());
8475
- }
8476
- function sanitizeBoolean(value) {
8477
- return value === true;
8478
- }
8479
8849
  function getSafeGeoIpFilename(value) {
8480
8850
  if (typeof value !== "string" || !value.trim()) return "";
8481
8851
  try {
@@ -8491,7 +8861,7 @@ var require_settings = __commonJS({
8491
8861
  vpnProxy: { subject: "", html: "", text: "" }
8492
8862
  };
8493
8863
  if (!templates || typeof templates !== "object") return defaults;
8494
- let sanitizeHtml = null;
8864
+ let sanitizeHtml;
8495
8865
  try {
8496
8866
  sanitizeHtml = require("sanitize-html");
8497
8867
  } catch {
@@ -8642,6 +9012,203 @@ var require_settings = __commonJS({
8642
9012
  geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath)
8643
9013
  };
8644
9014
  }
9015
+ var INTEGER_SETTING_RANGES = {
9016
+ inactivityTimeout: [1, 1440],
9017
+ cleanupInterval: [5, 1440],
9018
+ lastSeenRateLimit: [5, 300],
9019
+ maxSessionAgeDays: [1, 365],
9020
+ sessionCreationGraceMs: [0, 3e4],
9021
+ rateLimitWriteMax: [1, 1e3],
9022
+ rateLimitReadMax: [1, 1e4],
9023
+ rateLimitWindowSeconds: [10, 3600],
9024
+ maxFailedLogins: [0, 100]
9025
+ };
9026
+ var BOOLEAN_SETTINGS = [
9027
+ "cleanupUseDbDirect",
9028
+ "enableGeolocation",
9029
+ "enableSecurityScoring",
9030
+ "blockSuspiciousSessions",
9031
+ "enableGeofencing",
9032
+ "enableEmailAlerts",
9033
+ "alertOnSuspiciousLogin",
9034
+ "alertOnNewLocation",
9035
+ "alertOnVpnProxy",
9036
+ "enableWebhooks",
9037
+ "strictSessionEnforcement",
9038
+ "trustedProxies"
9039
+ ];
9040
+ var GEO_IP_PROVIDER_VALUES = ["auto", "local-mmdb", "ipapi", "disabled"];
9041
+ var GEO_LOOKUP_FAILURE_MODE_VALUES = ["auto", "allow", "block"];
9042
+ var EMAIL_TEMPLATE_LIMITS = { subject: 200, html: 1e4, text: 5e3 };
9043
+ function parseInteger(value) {
9044
+ if (typeof value === "number") return Number.isInteger(value) ? value : null;
9045
+ if (typeof value === "string" && /^\s*-?\d+\s*$/.test(value)) return Number.parseInt(value, 10);
9046
+ return null;
9047
+ }
9048
+ function mergeEmailTemplate(key, update, current, errors) {
9049
+ if (!update || typeof update !== "object" || Array.isArray(update)) {
9050
+ errors.push({
9051
+ path: ["emailTemplates", key],
9052
+ message: `emailTemplates.${key} must be an object`
9053
+ });
9054
+ return void 0;
9055
+ }
9056
+ const merged = {
9057
+ subject: "",
9058
+ html: "",
9059
+ text: "",
9060
+ ...current && typeof current === "object" ? current : {}
9061
+ };
9062
+ for (const [field, limit] of Object.entries(EMAIL_TEMPLATE_LIMITS)) {
9063
+ if (update[field] === void 0) continue;
9064
+ if (typeof update[field] !== "string") {
9065
+ errors.push({
9066
+ path: ["emailTemplates", key, field],
9067
+ message: `emailTemplates.${key}.${field} must be a string`
9068
+ });
9069
+ } else if (update[field].length > limit) {
9070
+ errors.push({
9071
+ path: ["emailTemplates", key, field],
9072
+ message: `emailTemplates.${key}.${field} must be at most ${limit} characters`
9073
+ });
9074
+ } else {
9075
+ merged[field] = update[field];
9076
+ }
9077
+ }
9078
+ return merged;
9079
+ }
9080
+ function validateSettingsUpdate(body, current) {
9081
+ const errors = [];
9082
+ const next = {};
9083
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
9084
+ for (const [key, [min, max]] of Object.entries(INTEGER_SETTING_RANGES)) {
9085
+ if (!has(key)) continue;
9086
+ const value = parseInteger(body[key]);
9087
+ if (value === null || value < min || value > max) {
9088
+ errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
9089
+ } else {
9090
+ next[key] = value;
9091
+ }
9092
+ }
9093
+ if (has("retentionDays")) {
9094
+ const value = parseInteger(body.retentionDays);
9095
+ if (value === null || value !== -1 && (value < 1 || value > 365)) {
9096
+ errors.push({
9097
+ path: ["retentionDays"],
9098
+ message: "retentionDays must be -1 (forever) or an integer between 1 and 365"
9099
+ });
9100
+ } else {
9101
+ next.retentionDays = value;
9102
+ }
9103
+ }
9104
+ for (const key of BOOLEAN_SETTINGS) {
9105
+ if (!has(key)) continue;
9106
+ if (typeof body[key] !== "boolean") {
9107
+ errors.push({ path: [key], message: `${key} must be a boolean` });
9108
+ } else {
9109
+ next[key] = body[key];
9110
+ }
9111
+ }
9112
+ for (const key of ["allowedCountries", "blockedCountries"]) {
9113
+ if (!has(key)) continue;
9114
+ const list = body[key];
9115
+ if (!Array.isArray(list)) {
9116
+ errors.push({
9117
+ path: [key],
9118
+ message: `${key} must be a list of ISO 3166-1 alpha-2 country codes`
9119
+ });
9120
+ continue;
9121
+ }
9122
+ const normalized = list.map(
9123
+ (code) => typeof code === "string" ? code.trim().toUpperCase() : ""
9124
+ );
9125
+ if (normalized.some((code) => !/^[A-Z]{2}$/.test(code))) {
9126
+ errors.push({
9127
+ path: [key],
9128
+ message: `${key} must contain only ISO 3166-1 alpha-2 country codes`
9129
+ });
9130
+ } else {
9131
+ next[key] = [...new Set(normalized)];
9132
+ }
9133
+ }
9134
+ if (has("geoIpProvider")) {
9135
+ if (!GEO_IP_PROVIDER_VALUES.includes(body.geoIpProvider)) {
9136
+ errors.push({
9137
+ path: ["geoIpProvider"],
9138
+ message: `geoIpProvider must be one of: ${GEO_IP_PROVIDER_VALUES.join(", ")}`
9139
+ });
9140
+ } else {
9141
+ next.geoIpProvider = normalizeGeoIpProvider(body.geoIpProvider);
9142
+ }
9143
+ }
9144
+ if (has("geoLookupFailureMode")) {
9145
+ if (!GEO_LOOKUP_FAILURE_MODE_VALUES.includes(body.geoLookupFailureMode)) {
9146
+ errors.push({
9147
+ path: ["geoLookupFailureMode"],
9148
+ message: `geoLookupFailureMode must be one of: ${GEO_LOOKUP_FAILURE_MODE_VALUES.join(", ")}`
9149
+ });
9150
+ } else {
9151
+ next.geoLookupFailureMode = normalizeGeoLookupFailureMode(body.geoLookupFailureMode);
9152
+ }
9153
+ }
9154
+ if (Object.prototype.hasOwnProperty.call(body, "geoIpDatabasePath")) {
9155
+ if (body.geoIpDatabasePath === "") {
9156
+ next.geoIpDatabasePath = "";
9157
+ } else {
9158
+ try {
9159
+ next.geoIpDatabasePath = path.basename(resolveDatabaseTarget(body.geoIpDatabasePath));
9160
+ } catch {
9161
+ errors.push({
9162
+ path: ["geoIpDatabasePath"],
9163
+ message: "GeoIP database path must be a supported MMDB filename in the dedicated GeoIP directory"
9164
+ });
9165
+ }
9166
+ }
9167
+ }
9168
+ for (const [key, type] of [
9169
+ ["discordWebhookUrl", "discord"],
9170
+ ["slackWebhookUrl", "slack"]
9171
+ ]) {
9172
+ if (!has(key)) continue;
9173
+ const value = body[key];
9174
+ if (typeof value !== "string") {
9175
+ errors.push({ path: [key], message: `${key} must be a string` });
9176
+ } else if (!value.trim()) {
9177
+ next[key] = "";
9178
+ } else {
9179
+ const sanitized = sanitizeWebhookUrl(value, type);
9180
+ if (!sanitized) {
9181
+ errors.push({
9182
+ path: [key],
9183
+ message: `${key} must be an https URL on ${ALLOWED_WEBHOOK_DOMAINS[type].join(" or ")}`
9184
+ });
9185
+ } else {
9186
+ next[key] = sanitized;
9187
+ }
9188
+ }
9189
+ }
9190
+ if (has("emailTemplates")) {
9191
+ const templates = body.emailTemplates;
9192
+ if (!templates || typeof templates !== "object" || Array.isArray(templates)) {
9193
+ errors.push({ path: ["emailTemplates"], message: "emailTemplates must be an object" });
9194
+ } else {
9195
+ const currentTemplates = current.emailTemplates || DEFAULT_EMAIL_TEMPLATES;
9196
+ const mergedTemplates = { ...DEFAULT_EMAIL_TEMPLATES, ...currentTemplates };
9197
+ for (const key of Object.keys(DEFAULT_EMAIL_TEMPLATES)) {
9198
+ if (templates[key] === void 0) continue;
9199
+ const merged = mergeEmailTemplate(key, templates[key], mergedTemplates[key], errors);
9200
+ if (merged) mergedTemplates[key] = merged;
9201
+ }
9202
+ next.emailTemplates = sanitizeEmailTemplates(mergedTemplates);
9203
+ }
9204
+ }
9205
+ if (errors.length > 0) return { errors };
9206
+ const settings = {};
9207
+ for (const key of Object.keys(DEFAULT_SETTINGS)) {
9208
+ settings[key] = Object.prototype.hasOwnProperty.call(next, key) ? next[key] : current[key];
9209
+ }
9210
+ return { settings, errors };
9211
+ }
8645
9212
  module2.exports = {
8646
9213
  /**
8647
9214
  * Returns current plugin settings in user-facing units. Legacy custom MMDB
@@ -8663,75 +9230,47 @@ var require_settings = __commonJS({
8663
9230
  success: true
8664
9231
  });
8665
9232
  } catch (error) {
8666
- strapi.log.error("[magic-sessionmanager/settings] Error getting settings:", error?.name || "Error");
8667
- ctx.badRequest("Error loading settings");
9233
+ strapi.log.error(
9234
+ "[magic-sessionmanager/settings] Error getting settings:",
9235
+ error?.name || "Error"
9236
+ );
9237
+ return sendServerError(ctx, 500, "Error loading settings");
8668
9238
  }
8669
9239
  },
8670
9240
  /**
8671
- * Validates and persists plugin settings, then invalidates the settings cache
8672
- * so runtime code picks up the new values on next read.
9241
+ * Validates a full or partial settings payload, merges it over the stored
9242
+ * settings and persists the result, then invalidates the settings cache so
9243
+ * runtime code picks up the new values on next read.
9244
+ *
9245
+ * Omitted fields keep their stored value. Invalid values are rejected with
9246
+ * a 400 whose `error.details.errors` names each field; nothing is clamped
9247
+ * or written in that case. Store failures return a 500 with a safe message.
9248
+ *
8673
9249
  * @route PUT /magic-sessionmanager/settings
8674
- * @throws {ValidationError} when the body or GeoIP filename is invalid
8675
9250
  * @returns {Promise<void>}
8676
9251
  */
8677
9252
  async updateSettings(ctx) {
9253
+ let pluginStore;
9254
+ let current;
8678
9255
  try {
8679
9256
  const { body } = ctx.request;
8680
9257
  if (!body || typeof body !== "object" || Array.isArray(body)) {
8681
9258
  return ctx.badRequest("Settings data must be an object");
8682
9259
  }
8683
- const pluginStore = strapi.store({
9260
+ pluginStore = strapi.store({
8684
9261
  type: "plugin",
8685
9262
  name: "magic-sessionmanager"
8686
9263
  });
8687
- let geoIpDatabasePath = "";
8688
- if (body.geoIpDatabasePath !== void 0 && body.geoIpDatabasePath !== "") {
8689
- try {
8690
- geoIpDatabasePath = path.basename(resolveDatabaseTarget(body.geoIpDatabasePath));
8691
- } catch {
8692
- return ctx.badRequest("GeoIP database path must be a supported MMDB filename in the dedicated GeoIP directory");
8693
- }
8694
- }
8695
- const grace = getSessionCreationGraceMs(body);
8696
- const maxFailedLoginsRaw = Number.parseInt(body.maxFailedLogins, 10);
8697
- const maxFailedLogins = Number.isFinite(maxFailedLoginsRaw) ? Math.max(0, Math.min(maxFailedLoginsRaw, 100)) : 5;
8698
- const sanitizedSettings = {
8699
- // Timing & cleanup
8700
- inactivityTimeout: Math.max(1, Math.min(parseInt(body.inactivityTimeout) || 15, 1440)),
8701
- cleanupInterval: Math.max(5, Math.min(parseInt(body.cleanupInterval) || 30, 1440)),
8702
- lastSeenRateLimit: Math.max(5, Math.min(parseInt(body.lastSeenRateLimit) || 30, 300)),
8703
- retentionDays: normalizeRetentionDays(body.retentionDays, 90),
8704
- maxSessionAgeDays: Math.max(1, Math.min(parseInt(body.maxSessionAgeDays) || 30, 365)),
8705
- sessionCreationGraceMs: grace,
8706
- cleanupUseDbDirect: sanitizeBoolean(body.cleanupUseDbDirect),
8707
- rateLimitWriteMax: Math.max(1, Math.min(parseInt(body.rateLimitWriteMax) || 10, 1e3)),
8708
- rateLimitReadMax: Math.max(1, Math.min(parseInt(body.rateLimitReadMax) || 120, 1e4)),
8709
- rateLimitWindowSeconds: Math.max(10, Math.min(parseInt(body.rateLimitWindowSeconds) || 60, 3600)),
8710
- // Geo / security
8711
- enableGeolocation: sanitizeBoolean(body.enableGeolocation),
8712
- enableSecurityScoring: sanitizeBoolean(body.enableSecurityScoring),
8713
- blockSuspiciousSessions: sanitizeBoolean(body.blockSuspiciousSessions),
8714
- maxFailedLogins,
8715
- enableGeofencing: sanitizeBoolean(body.enableGeofencing),
8716
- allowedCountries: sanitizeCountryList(body.allowedCountries),
8717
- blockedCountries: sanitizeCountryList(body.blockedCountries),
8718
- geoIpProvider: normalizeGeoIpProvider(body.geoIpProvider),
8719
- geoIpDatabasePath,
8720
- geoLookupFailureMode: normalizeGeoLookupFailureMode(body.geoLookupFailureMode),
8721
- // Notifications
8722
- enableEmailAlerts: sanitizeBoolean(body.enableEmailAlerts),
8723
- alertOnSuspiciousLogin: sanitizeBoolean(body.alertOnSuspiciousLogin),
8724
- alertOnNewLocation: sanitizeBoolean(body.alertOnNewLocation),
8725
- alertOnVpnProxy: sanitizeBoolean(body.alertOnVpnProxy),
8726
- enableWebhooks: sanitizeBoolean(body.enableWebhooks),
8727
- discordWebhookUrl: sanitizeWebhookUrl(body.discordWebhookUrl, "discord"),
8728
- slackWebhookUrl: sanitizeWebhookUrl(body.slackWebhookUrl, "slack"),
8729
- // Session policy
8730
- strictSessionEnforcement: sanitizeBoolean(body.strictSessionEnforcement),
8731
- trustedProxies: sanitizeBoolean(body.trustedProxies),
8732
- // Email templates
8733
- emailTemplates: sanitizeEmailTemplates(body.emailTemplates)
9264
+ const stored = await pluginStore.get({ key: "settings" });
9265
+ const storedObject = stored && typeof stored === "object" ? stored : {};
9266
+ current = {
9267
+ ...mergeSettingsWithDefaults(storedObject),
9268
+ geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
8734
9269
  };
9270
+ const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
9271
+ if (errors.length > 0) {
9272
+ return sendValidationError(ctx, "Invalid settings", errors);
9273
+ }
8735
9274
  await pluginStore.set({
8736
9275
  key: "settings",
8737
9276
  value: sanitizedSettings
@@ -8739,17 +9278,24 @@ var require_settings = __commonJS({
8739
9278
  invalidateSettingsCache();
8740
9279
  strapi.log.info("[magic-sessionmanager/settings] Settings updated successfully");
8741
9280
  ctx.send({
8742
- settings: sanitizedSettings,
9281
+ settings: {
9282
+ ...sanitizedSettings,
9283
+ geoIpDatabasePath: getSafeGeoIpFilename(sanitizedSettings.geoIpDatabasePath)
9284
+ },
8743
9285
  success: true,
8744
9286
  message: "Settings saved successfully!"
8745
9287
  });
8746
9288
  } catch (error) {
8747
- strapi.log.error("[magic-sessionmanager/settings] Error updating settings:", error?.name || "Error");
8748
- ctx.badRequest("Error saving settings");
9289
+ strapi.log.error(
9290
+ "[magic-sessionmanager/settings] Error updating settings:",
9291
+ error?.name || "Error"
9292
+ );
9293
+ return sendServerError(ctx, 500, "Error saving settings");
8749
9294
  }
8750
9295
  },
8751
9296
  DEFAULT_SETTINGS,
8752
- mergeSettingsWithDefaults
9297
+ mergeSettingsWithDefaults,
9298
+ validateSettingsUpdate
8753
9299
  };
8754
9300
  }
8755
9301
  });
@@ -8773,6 +9319,7 @@ var require_geoip = __commonJS({
8773
9319
  invalidateSettingsCache,
8774
9320
  normalizeGeoIpDatabasePath
8775
9321
  } = require_settings_loader();
9322
+ var { sendServerError } = require_http_errors();
8776
9323
  var CREDENTIALS_KEY = "geoipCredentials";
8777
9324
  var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
8778
9325
  var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
@@ -8870,8 +9417,11 @@ var require_geoip = __commonJS({
8870
9417
  }
8871
9418
  });
8872
9419
  } catch (error) {
8873
- strapi2.log.error("[magic-sessionmanager/geoip] Error getting status:", error?.name || "Error");
8874
- return ctx.badRequest("Error getting GeoIP status");
9420
+ strapi2.log.error(
9421
+ "[magic-sessionmanager/geoip] Error getting status:",
9422
+ error?.name || "Error"
9423
+ );
9424
+ return sendServerError(ctx, 500, "Error getting GeoIP status");
8875
9425
  }
8876
9426
  },
8877
9427
  /**
@@ -8900,8 +9450,11 @@ var require_geoip = __commonJS({
8900
9450
  accountId
8901
9451
  });
8902
9452
  } catch (error) {
8903
- strapi2.log.error("[magic-sessionmanager/geoip] Error storing credentials:", error?.name || "Error");
8904
- return ctx.badRequest("Error storing GeoIP credentials");
9453
+ strapi2.log.error(
9454
+ "[magic-sessionmanager/geoip] Error storing credentials:",
9455
+ error?.name || "Error"
9456
+ );
9457
+ return sendServerError(ctx, 500, "Error storing GeoIP credentials");
8905
9458
  }
8906
9459
  },
8907
9460
  /**
@@ -8921,15 +9474,27 @@ var require_geoip = __commonJS({
8921
9474
  if (!config2.accountId || !config2.licenseKey) {
8922
9475
  return ctx.badRequest("MaxMind credentials are required before downloading GeoIP data");
8923
9476
  }
8924
- const result = await updateDatabase(config2);
9477
+ let result;
9478
+ try {
9479
+ result = await updateDatabase(config2);
9480
+ } catch (error) {
9481
+ strapi2.log.error(
9482
+ "[magic-sessionmanager/geoip] GeoIP download failed:",
9483
+ error?.name || "Error"
9484
+ );
9485
+ return sendServerError(ctx, 502, "Error updating GeoIP database");
9486
+ }
8925
9487
  invalidateSettingsCache();
8926
9488
  ctx.send({
8927
9489
  success: true,
8928
9490
  result
8929
9491
  });
8930
9492
  } catch (error) {
8931
- strapi2.log.error("[magic-sessionmanager/geoip] Error updating database:", error?.name || "Error");
8932
- return ctx.badRequest("Error updating GeoIP database");
9493
+ strapi2.log.error(
9494
+ "[magic-sessionmanager/geoip] Error updating database:",
9495
+ error?.name || "Error"
9496
+ );
9497
+ return sendServerError(ctx, 500, "Error updating GeoIP database");
8933
9498
  }
8934
9499
  },
8935
9500
  __private: {
@@ -8959,93 +9524,6 @@ var require_controllers = __commonJS({
8959
9524
  }
8960
9525
  });
8961
9526
 
8962
- // server/src/utils/native-session-view.js
8963
- var require_native_session_view = __commonJS({
8964
- "server/src/utils/native-session-view.js"(exports2, module2) {
8965
- "use strict";
8966
- var NATIVE_SESSION_PREFIX = "native_";
8967
- function createNativeSessionKey(userDocumentId, nativeSessionId) {
8968
- if (typeof userDocumentId !== "string" || !userDocumentId || typeof nativeSessionId !== "string" || !nativeSessionId) {
8969
- throw new TypeError("Native session view keys require an owner documentId and session ID.");
8970
- }
8971
- const payload = Buffer.from(JSON.stringify([userDocumentId, nativeSessionId])).toString(
8972
- "base64url"
8973
- );
8974
- if (payload.length > 2048) {
8975
- throw new RangeError("Native session view key exceeds the supported URL-safe length.");
8976
- }
8977
- return `${NATIVE_SESSION_PREFIX}${payload}`;
8978
- }
8979
- function parseNativeSessionKey(value) {
8980
- if (typeof value !== "string" || !value.startsWith(NATIVE_SESSION_PREFIX)) return null;
8981
- const encoded = value.slice(NATIVE_SESSION_PREFIX.length);
8982
- if (!encoded || encoded.length > 2048 || !/^[A-Za-z0-9_-]+$/.test(encoded)) return null;
8983
- try {
8984
- const decoded = Buffer.from(encoded, "base64url").toString("utf8");
8985
- if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded) return null;
8986
- const payload = JSON.parse(decoded);
8987
- if (!Array.isArray(payload) || payload.length !== 2 || typeof payload[0] !== "string" || !payload[0] || typeof payload[1] !== "string" || !payload[1]) {
8988
- return null;
8989
- }
8990
- return {
8991
- userDocumentId: payload[0],
8992
- nativeSessionId: payload[1]
8993
- };
8994
- } catch {
8995
- return null;
8996
- }
8997
- }
8998
- function mapNativeSessionToView(session, user) {
8999
- const nativeId = String(session.sessionId);
9000
- const stableId = createNativeSessionKey(String(user.documentId), nativeId);
9001
- const metadata = session.metadata && typeof session.metadata === "object" ? session.metadata : {};
9002
- const loginAt = typeof metadata.loginAt === "string" && !Number.isNaN(Date.parse(metadata.loginAt)) ? new Date(metadata.loginAt) : null;
9003
- const createdAt = session.createdAt && !Number.isNaN(new Date(session.createdAt).getTime()) ? new Date(session.createdAt) : null;
9004
- const userView = {
9005
- documentId: user.documentId,
9006
- email: user.email,
9007
- username: user.username
9008
- };
9009
- return {
9010
- documentId: stableId,
9011
- id: stableId,
9012
- sessionId: stableId,
9013
- nativeSessionId: nativeId,
9014
- user: userView,
9015
- ipAddress: null,
9016
- userAgent: null,
9017
- loginTime: loginAt || createdAt,
9018
- logoutTime: null,
9019
- lastActive: createdAt || loginAt,
9020
- isActive: true,
9021
- terminatedManually: false,
9022
- geoLocation: null,
9023
- securityScore: null,
9024
- deviceType: null,
9025
- deviceName: typeof metadata.deviceName === "string" ? metadata.deviceName : void 0,
9026
- browserName: null,
9027
- osName: null
9028
- };
9029
- }
9030
- function markSessionsTruncated(sessions, truncated) {
9031
- Object.defineProperty(sessions, "truncated", {
9032
- value: Boolean(truncated),
9033
- enumerable: false,
9034
- configurable: false,
9035
- writable: false
9036
- });
9037
- return sessions;
9038
- }
9039
- module2.exports = {
9040
- NATIVE_SESSION_PREFIX,
9041
- createNativeSessionKey,
9042
- parseNativeSessionKey,
9043
- mapNativeSessionToView,
9044
- markSessionsTruncated
9045
- };
9046
- }
9047
- });
9048
-
9049
9527
  // server/src/services/session.js
9050
9528
  var require_session2 = __commonJS({
9051
9529
  "server/src/services/session.js"(exports2, module2) {
@@ -9594,7 +10072,8 @@ var require_session2 = __commonJS({
9594
10072
  * still match before a
9595
10073
  * single-session update.
9596
10074
  * @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
9597
- * @returns {Promise<{terminatedCount: number}>}
10075
+ * @returns {Promise<{terminatedCount: number}>} Completed count; rejects if
10076
+ * active rows cannot be updated. Earlier updates may already be committed.
9598
10077
  */
9599
10078
  async terminateSession({
9600
10079
  sessionId,
@@ -9737,13 +10216,11 @@ var require_session2 = __commonJS({
9737
10216
  }
9738
10217
  if (batchTerminated === 0) {
9739
10218
  log.warn("Could not terminate remaining active sessions for one user");
9740
- break;
10219
+ throw new Error("Unable to terminate all requested sessions");
9741
10220
  }
9742
10221
  }
9743
10222
  const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
9744
- log.info(
9745
- `${label} terminated (reason: ${finalReason}, count: ${terminatedCount})`
9746
- );
10223
+ log.info(`${label} terminated (reason: ${finalReason}, count: ${terminatedCount})`);
9747
10224
  return { terminatedCount: nativeManager ? terminatedKeys.size : terminatedCount };
9748
10225
  }
9749
10226
  return { terminatedCount: 0 };
@@ -10161,18 +10638,29 @@ var require_session2 = __commonJS({
10161
10638
  * Removes all inactive session rows, retaining deny hashes for unexpired
10162
10639
  * access tokens. A failed hash write leaves its session row in place.
10163
10640
  *
10164
- * @returns {Promise<number>} Number of session rows removed
10641
+ * A row that cannot be removed is excluded from later batches, so one
10642
+ * persistently failing row cannot block the rest of the cleanup. Expired
10643
+ * revocation records are cleaned up in every case.
10644
+ *
10645
+ * @returns {Promise<number>} Number of rows removed when every row succeeded
10646
+ * @throws {Error} `PartialCleanupError` with `deletedCount` and
10647
+ * `failedCount` when at least one row could not be removed; the other
10648
+ * rows have been removed by then
10165
10649
  * @sideeffect Writes revocation records before deleting session rows
10166
10650
  */
10167
10651
  async deleteInactiveSessions() {
10168
10652
  try {
10169
10653
  log.info("[DELETE] Deleting all inactive sessions...");
10170
10654
  let deletedCount = 0;
10655
+ const failedIds = /* @__PURE__ */ new Set();
10171
10656
  const BATCH_SIZE = 100;
10172
- let consecutiveEmptyLoops = 0;
10173
10657
  while (true) {
10658
+ const filters = { isActive: false };
10659
+ if (failedIds.size > 0) {
10660
+ filters.documentId = { $notIn: [...failedIds] };
10661
+ }
10174
10662
  const batch = await strapi2.documents(SESSION_UID).findMany({
10175
- filters: { isActive: false },
10663
+ filters,
10176
10664
  fields: ["documentId", "token", "tokenHash", "nativeSessionId"],
10177
10665
  populate: { user: { fields: ["id", "documentId"] } },
10178
10666
  limit: BATCH_SIZE
@@ -10181,26 +10669,32 @@ var require_session2 = __commonJS({
10181
10669
  const deleteResults = await Promise.allSettled(
10182
10670
  batch.map((session) => deleteSessionPreservingRevocation(session))
10183
10671
  );
10184
- const successful = deleteResults.filter((r) => r.status === "fulfilled").length;
10185
- deletedCount += successful;
10186
- if (successful === 0) {
10187
- consecutiveEmptyLoops++;
10188
- if (consecutiveEmptyLoops >= 3) {
10189
- log.warn(
10190
- "[DELETE] No progress on 3 consecutive batches, aborting to prevent infinite loop"
10191
- );
10192
- break;
10672
+ deleteResults.forEach((result, index) => {
10673
+ if (result.status === "fulfilled") {
10674
+ deletedCount += 1;
10675
+ } else {
10676
+ failedIds.add(batch[index].documentId);
10193
10677
  }
10194
- } else {
10195
- consecutiveEmptyLoops = 0;
10196
- }
10678
+ });
10197
10679
  if (batch.length < BATCH_SIZE) break;
10198
10680
  }
10199
10681
  await cleanupExpiredRevocations();
10682
+ if (failedIds.size > 0) {
10683
+ log.warn(
10684
+ `[DELETE] Deleted ${deletedCount} inactive sessions; ${failedIds.size} could not be removed`
10685
+ );
10686
+ const error = new Error("Unable to remove all inactive sessions");
10687
+ error.name = "PartialCleanupError";
10688
+ error.deletedCount = deletedCount;
10689
+ error.failedCount = failedIds.size;
10690
+ throw error;
10691
+ }
10200
10692
  log.info(`[SUCCESS] Deleted ${deletedCount} inactive sessions`);
10201
10693
  return deletedCount;
10202
10694
  } catch (err) {
10203
- log.error("Error deleting inactive sessions:", err?.name || "Error");
10695
+ if (err?.name !== "PartialCleanupError") {
10696
+ log.error("Error deleting inactive sessions:", err?.name || "Error");
10697
+ }
10204
10698
  throw err;
10205
10699
  }
10206
10700
  }
@@ -10213,7 +10707,7 @@ var require_session2 = __commonJS({
10213
10707
  var require_package = __commonJS({
10214
10708
  "package.json"(exports2, module2) {
10215
10709
  module2.exports = {
10216
- version: "4.8.0",
10710
+ version: "4.9.0",
10217
10711
  keywords: [
10218
10712
  "strapi",
10219
10713
  "plugin",
@@ -10263,6 +10757,10 @@ var require_package = __commonJS({
10263
10757
  test: "node --test tests/*.test.js tests/*.test.mjs",
10264
10758
  "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
10265
10759
  "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
10760
+ lint: "eslint .",
10761
+ "lint:fix": "eslint . --fix",
10762
+ format: "prettier --write .",
10763
+ "format:check": "prettier --check .",
10266
10764
  build: "npm run clean && strapi-plugin build && node scripts/build-server-bundle.mjs",
10267
10765
  watch: "strapi-plugin watch",
10268
10766
  "watch:link": "strapi-plugin watch:link",
@@ -10276,6 +10774,7 @@ var require_package = __commonJS({
10276
10774
  "sanitize-html": "^2.18.0"
10277
10775
  },
10278
10776
  devDependencies: {
10777
+ "@eslint/js": "^10.0.1",
10279
10778
  "@semantic-release/changelog": "^7.0.0",
10280
10779
  "@semantic-release/commit-analyzer": "^13.0.1",
10281
10780
  "@semantic-release/git": "^11.0.1",
@@ -10287,6 +10786,10 @@ var require_package = __commonJS({
10287
10786
  "@strapi/sdk-plugin": "^6.1.1",
10288
10787
  "@strapi/strapi": "5.61.0",
10289
10788
  esbuild: "^0.28.2",
10789
+ eslint: "^10.14.0",
10790
+ "eslint-config-prettier": "^10.1.8",
10791
+ "eslint-plugin-react-hooks": "^7.1.1",
10792
+ globals: "^17.14.0",
10290
10793
  prettier: "^3.9.10",
10291
10794
  react: "^18.3.1",
10292
10795
  "react-dom": "^18.3.1",
@@ -10431,21 +10934,24 @@ var require_license_guard = __commonJS({
10431
10934
  },
10432
10935
  async createLicense({ email, firstName, lastName }) {
10433
10936
  try {
10434
- const response = await fetchWithTimeout(`${this.getLicenseServerUrl()}/api/licenses/create`, {
10435
- method: "POST",
10436
- headers: { "Content-Type": "application/json" },
10437
- body: JSON.stringify({
10438
- email,
10439
- firstName,
10440
- lastName,
10441
- deviceName: this.getDeviceName(),
10442
- deviceId: await this.generateDeviceId(),
10443
- ipAddress: this.getIpAddress(),
10444
- userAgent: this.getUserAgent(),
10445
- pluginName: "magic-sessionmanager",
10446
- productName: "Magic Session Manager"
10447
- })
10448
- });
10937
+ const response = await fetchWithTimeout(
10938
+ `${this.getLicenseServerUrl()}/api/licenses/create`,
10939
+ {
10940
+ method: "POST",
10941
+ headers: { "Content-Type": "application/json" },
10942
+ body: JSON.stringify({
10943
+ email,
10944
+ firstName,
10945
+ lastName,
10946
+ deviceName: this.getDeviceName(),
10947
+ deviceId: await this.generateDeviceId(),
10948
+ ipAddress: this.getIpAddress(),
10949
+ userAgent: this.getUserAgent(),
10950
+ pluginName: "magic-sessionmanager",
10951
+ productName: "Magic Session Manager"
10952
+ })
10953
+ }
10954
+ );
10449
10955
  const data = await response.json();
10450
10956
  if (data.success) {
10451
10957
  log.info("[SUCCESS] License created");
@@ -10460,15 +10966,18 @@ var require_license_guard = __commonJS({
10460
10966
  },
10461
10967
  async verifyLicense(licenseKey) {
10462
10968
  try {
10463
- const response = await fetchWithTimeout(`${this.getLicenseServerUrl()}/api/licenses/verify`, {
10464
- method: "POST",
10465
- headers: { "Content-Type": "application/json" },
10466
- body: JSON.stringify({
10467
- licenseKey,
10468
- pluginName: "magic-sessionmanager",
10469
- productName: "Magic Session Manager"
10470
- })
10471
- });
10969
+ const response = await fetchWithTimeout(
10970
+ `${this.getLicenseServerUrl()}/api/licenses/verify`,
10971
+ {
10972
+ method: "POST",
10973
+ headers: { "Content-Type": "application/json" },
10974
+ body: JSON.stringify({
10975
+ licenseKey,
10976
+ pluginName: "magic-sessionmanager",
10977
+ productName: "Magic Session Manager"
10978
+ })
10979
+ }
10980
+ );
10472
10981
  const data = await response.json();
10473
10982
  if (data.success && data.data) {
10474
10983
  const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
@@ -10486,10 +10995,13 @@ var require_license_guard = __commonJS({
10486
10995
  async getLicenseByKey(licenseKey) {
10487
10996
  try {
10488
10997
  const encodedKey = encodeURIComponent(licenseKey);
10489
- const response = await fetchWithTimeout(`${this.getLicenseServerUrl()}/api/licenses/key/${encodedKey}`, {
10490
- method: "GET",
10491
- headers: { "Content-Type": "application/json" }
10492
- });
10998
+ const response = await fetchWithTimeout(
10999
+ `${this.getLicenseServerUrl()}/api/licenses/key/${encodedKey}`,
11000
+ {
11001
+ method: "GET",
11002
+ headers: { "Content-Type": "application/json" }
11003
+ }
11004
+ );
10493
11005
  const data = await response.json();
10494
11006
  if (data.success && data.data) return data.data;
10495
11007
  return null;
@@ -10772,6 +11284,18 @@ var require_geolocation = __commonJS({
10772
11284
  if (ipv4Mapped && net.isIP(ipv4Mapped[1]) === 4) {
10773
11285
  return ipv4Mapped[1];
10774
11286
  }
11287
+ if (net.isIP(normalized) === 6) {
11288
+ try {
11289
+ const canonical = new URL(`http://[${normalized}]/`).hostname.slice(1, -1);
11290
+ const mapped = canonical.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
11291
+ if (mapped) {
11292
+ const high = Number.parseInt(mapped[1], 16);
11293
+ const low = Number.parseInt(mapped[2], 16);
11294
+ return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
11295
+ }
11296
+ } catch {
11297
+ }
11298
+ }
10775
11299
  return normalized;
10776
11300
  }
10777
11301
  function parseIpv4(ip) {
@@ -10795,7 +11319,11 @@ var require_geolocation = __commonJS({
10795
11319
  return Number.isNaN(parsed) ? 0 : parsed;
10796
11320
  }
10797
11321
  function isPrivateIpv6(ip) {
10798
- const lower = ip.toLowerCase();
11322
+ let lower = ip.toLowerCase();
11323
+ try {
11324
+ lower = new URL(`http://[${lower}]/`).hostname.slice(1, -1);
11325
+ } catch {
11326
+ }
10799
11327
  if (lower === "::" || lower === "::1") return true;
10800
11328
  if (/^(?:0:){7}0$/.test(lower) || /^(?:0:){7}1$/.test(lower)) return true;
10801
11329
  if (lower.startsWith("::ffff:")) {
@@ -10862,7 +11390,9 @@ var require_geolocation = __commonJS({
10862
11390
  if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
10863
11391
  return localResult;
10864
11392
  }
10865
- strapi2.log.warn(`[magic-sessionmanager/geolocation] Local MMDB lookup failed (${localResult?._reason || localResult?._status}), falling back to ipapi.co`);
11393
+ strapi2.log.warn(
11394
+ "[magic-sessionmanager/geolocation] Local MMDB lookup failed, falling back to ipapi.co"
11395
+ );
10866
11396
  }
10867
11397
  }
10868
11398
  return this.getIpapiIpInfo(lookupIp);
@@ -10905,10 +11435,15 @@ var require_geolocation = __commonJS({
10905
11435
  const useCityLookup = isCityDatabase(reader, databasePath) && typeof reader.city === "function";
10906
11436
  const data = useCityLookup ? reader.city(lookupIp) : reader.country(lookupIp);
10907
11437
  const result = useCityLookup ? normalizeLocalCityResult(data, lookupIp, this.getCountryFlag.bind(this)) : normalizeLocalCountryResult(data, lookupIp, this.getCountryFlag.bind(this));
10908
- strapi2.log.debug(`[magic-sessionmanager/geolocation] Local MMDB lookup completed (${result._databaseType})`);
11438
+ strapi2.log.debug(
11439
+ `[magic-sessionmanager/geolocation] Local MMDB lookup completed (${result._databaseType})`
11440
+ );
10909
11441
  return result;
10910
11442
  } catch (error) {
10911
- strapi2.log.warn("[magic-sessionmanager/geolocation] Local MMDB lookup failed:", error?.name || "Error");
11443
+ strapi2.log.warn(
11444
+ "[magic-sessionmanager/geolocation] Local MMDB lookup failed:",
11445
+ error?.name || "Error"
11446
+ );
10912
11447
  return this.getFallbackData(lookupIp, "error", "local-mmdb", error.message);
10913
11448
  }
10914
11449
  },
@@ -10930,7 +11465,12 @@ var require_geolocation = __commonJS({
10930
11465
  strapi2,
10931
11466
  `[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(rateLimitRemainingMs / 1e3)}s`
10932
11467
  );
10933
- return this.getFallbackData(lookupIp, "rate_limited", "ipapi", "Remote GeoIP provider is backing off after HTTP 429");
11468
+ return this.getFallbackData(
11469
+ lookupIp,
11470
+ "rate_limited",
11471
+ "ipapi",
11472
+ "Remote GeoIP provider is backing off after HTTP 429"
11473
+ );
10934
11474
  }
10935
11475
  if (ipapiInFlight.has(lookupIp)) {
10936
11476
  return cloneGeoData(await ipapiInFlight.get(lookupIp));
@@ -10954,7 +11494,12 @@ var require_geolocation = __commonJS({
10954
11494
  strapi2,
10955
11495
  `[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(queuedRateLimitRemainingMs / 1e3)}s`
10956
11496
  );
10957
- return this.getFallbackData(lookupIp, "rate_limited", "ipapi", "Remote GeoIP provider is backing off after HTTP 429");
11497
+ return this.getFallbackData(
11498
+ lookupIp,
11499
+ "rate_limited",
11500
+ "ipapi",
11501
+ "Remote GeoIP provider is backing off after HTTP 429"
11502
+ );
10958
11503
  }
10959
11504
  const controller = new AbortController();
10960
11505
  const timer = setTimeout(() => controller.abort(), GEO_API_TIMEOUT_MS);
@@ -10973,9 +11518,16 @@ var require_geolocation = __commonJS({
10973
11518
  `[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
10974
11519
  );
10975
11520
  } else {
10976
- strapi2.log.warn(`[magic-sessionmanager/geolocation] API returned HTTP ${response.status}`);
11521
+ strapi2.log.warn(
11522
+ `[magic-sessionmanager/geolocation] API returned HTTP ${response.status}`
11523
+ );
10977
11524
  }
10978
- const fallback = this.getFallbackData(lookupIp, reason, "ipapi", `HTTP ${response.status}`);
11525
+ const fallback = this.getFallbackData(
11526
+ lookupIp,
11527
+ reason,
11528
+ "ipapi",
11529
+ `HTTP ${response.status}`
11530
+ );
10979
11531
  cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
10980
11532
  return fallback;
10981
11533
  }
@@ -11033,7 +11585,10 @@ var require_geolocation = __commonJS({
11033
11585
  return result;
11034
11586
  } catch (error) {
11035
11587
  const status = error?.name === "AbortError" ? "error" : "error";
11036
- strapi2.log.error("[magic-sessionmanager/geolocation] ipapi lookup failed:", error?.name || "Error");
11588
+ strapi2.log.error(
11589
+ "[magic-sessionmanager/geolocation] ipapi lookup failed:",
11590
+ error?.name || "Error"
11591
+ );
11037
11592
  const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
11038
11593
  cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
11039
11594
  return fallback;
@@ -11150,11 +11705,7 @@ var require_geolocation = __commonJS({
11150
11705
  var require_notifications = __commonJS({
11151
11706
  "server/src/services/notifications.js"(exports2, module2) {
11152
11707
  "use strict";
11153
- var ALLOWED_WEBHOOK_HOSTS = [
11154
- "discord.com",
11155
- "discordapp.com",
11156
- "hooks.slack.com"
11157
- ];
11708
+ var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
11158
11709
  var WEBHOOK_TIMEOUT_MS = 5e3;
11159
11710
  module2.exports = ({ strapi: strapi2 }) => ({
11160
11711
  /**
@@ -11178,8 +11729,10 @@ var require_notifications = __commonJS({
11178
11729
  return settings.emailTemplates;
11179
11730
  }
11180
11731
  }
11181
- } catch (err) {
11182
- strapi2.log.warn("[magic-sessionmanager/notifications] Could not load templates from DB; using defaults");
11732
+ } catch {
11733
+ strapi2.log.warn(
11734
+ "[magic-sessionmanager/notifications] Could not load templates from DB; using defaults"
11735
+ );
11183
11736
  }
11184
11737
  strapi2.log.debug("[magic-sessionmanager/notifications] Using default fallback templates");
11185
11738
  return {
@@ -11297,7 +11850,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
11297
11850
  result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
11298
11851
  result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
11299
11852
  result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
11300
- result = result.replace(/\{\{reason\.securityScore\}\}/g, esc(String(data.reason?.securityScore || "0")));
11853
+ result = result.replace(
11854
+ /\{\{reason\.securityScore\}\}/g,
11855
+ esc(String(data.reason?.securityScore || "0"))
11856
+ );
11301
11857
  return result;
11302
11858
  },
11303
11859
  /**
@@ -11321,7 +11877,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
11321
11877
  strapi2.log.info("[magic-sessionmanager/notifications] Suspicious login alert sent");
11322
11878
  return true;
11323
11879
  } catch (err) {
11324
- strapi2.log.error("[magic-sessionmanager/notifications] Email alert failed:", err?.name || "Error");
11880
+ strapi2.log.error(
11881
+ "[magic-sessionmanager/notifications] Email alert failed:",
11882
+ err?.name || "Error"
11883
+ );
11325
11884
  return false;
11326
11885
  }
11327
11886
  },
@@ -11346,7 +11905,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
11346
11905
  strapi2.log.info("[magic-sessionmanager/notifications] New location alert sent");
11347
11906
  return true;
11348
11907
  } catch (err) {
11349
- strapi2.log.error("[magic-sessionmanager/notifications] New-location email failed:", err?.name || "Error");
11908
+ strapi2.log.error(
11909
+ "[magic-sessionmanager/notifications] New-location email failed:",
11910
+ err?.name || "Error"
11911
+ );
11350
11912
  return false;
11351
11913
  }
11352
11914
  },
@@ -11371,7 +11933,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
11371
11933
  strapi2.log.info("[magic-sessionmanager/notifications] VPN/Proxy alert sent");
11372
11934
  return true;
11373
11935
  } catch (err) {
11374
- strapi2.log.error("[magic-sessionmanager/notifications] VPN/Proxy email failed:", err?.name || "Error");
11936
+ strapi2.log.error(
11937
+ "[magic-sessionmanager/notifications] VPN/Proxy email failed:",
11938
+ err?.name || "Error"
11939
+ );
11375
11940
  return false;
11376
11941
  }
11377
11942
  },
@@ -11395,7 +11960,9 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
11395
11960
  try {
11396
11961
  try {
11397
11962
  const parsed = new URL(webhookUrl);
11398
- const isAllowed = parsed.protocol === "https:" && ALLOWED_WEBHOOK_HOSTS.some((h) => parsed.hostname === h || parsed.hostname.endsWith(`.${h}`));
11963
+ const isAllowed = parsed.protocol === "https:" && ALLOWED_WEBHOOK_HOSTS.some(
11964
+ (h) => parsed.hostname === h || parsed.hostname.endsWith(`.${h}`)
11965
+ );
11399
11966
  if (!isAllowed) {
11400
11967
  strapi2.log.warn("[magic-sessionmanager/notifications] Blocked webhook to untrusted host");
11401
11968
  return false;
@@ -11427,7 +11994,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
11427
11994
  clearTimeout(timer);
11428
11995
  }
11429
11996
  } catch (err) {
11430
- strapi2.log.error("[magic-sessionmanager/notifications] Webhook request failed:", err?.name || "Error");
11997
+ strapi2.log.error(
11998
+ "[magic-sessionmanager/notifications] Webhook request failed:",
11999
+ err?.name || "Error"
12000
+ );
11431
12001
  return false;
11432
12002
  }
11433
12003
  },
@@ -11620,38 +12190,56 @@ var require_rate_limit = __commonJS({
11620
12190
  if (tokenId) return `t:${String(tokenId).slice(-16)}`;
11621
12191
  return `ip:${ctx.request.ip || ctx.ip || "unknown"}`;
11622
12192
  };
12193
+ var routeKey = (ctx) => {
12194
+ const route = ctx.state?.route;
12195
+ const method = String(route?.method || ctx.method || "").toUpperCase();
12196
+ if (route && typeof route.path === "string") {
12197
+ const plugin = route.info?.pluginName || route.plugin || "";
12198
+ const handler = typeof route.handler === "string" ? route.handler : "";
12199
+ return `${method} ${plugin}:${handler}:${route.path.toLowerCase()}`;
12200
+ }
12201
+ const rawPath = String(ctx.path || "").toLowerCase();
12202
+ const normalizedPath = rawPath.length > 1 ? rawPath.replace(/\/+$/, "") || "/" : rawPath;
12203
+ return `${method} path:${normalizedPath}`;
12204
+ };
11623
12205
  var RESOLVED_TTL_MS = 3e4;
11624
- var resolvedCache = null;
11625
- var resolvedAt = 0;
12206
+ var resolvedCache = /* @__PURE__ */ new Map();
11626
12207
  async function resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) {
11627
12208
  const now = Date.now();
11628
- if (resolvedCache && now - resolvedAt < RESOLVED_TTL_MS) {
11629
- const p = resolvedCache[profile];
11630
- if (p) {
11631
- return { max: p.max, windowMs: p.windowMs };
11632
- }
12209
+ const cacheKey = `${profile}:${routeMax}:${routeWindowMs}`;
12210
+ const cachedEntry = resolvedCache.get(cacheKey);
12211
+ if (cachedEntry && now - cachedEntry.at < RESOLVED_TTL_MS) {
12212
+ return { max: cachedEntry.max, windowMs: cachedEntry.windowMs };
11633
12213
  }
11634
- let settings = {};
12214
+ let settings;
11635
12215
  try {
11636
12216
  settings = await getPluginSettings(strapi2);
11637
12217
  } catch {
11638
12218
  settings = {};
11639
12219
  }
11640
- const windowSec = Number.isFinite(settings.rateLimitWindowSeconds) ? settings.rateLimitWindowSeconds : Math.round(routeWindowMs / 1e3);
11641
- const windowMs = Math.max(1e4, windowSec * 1e3);
11642
- const resolvedWrite = {
11643
- max: Math.min(routeMax, Number.isFinite(settings.rateLimitWriteMax) ? settings.rateLimitWriteMax : routeMax),
11644
- windowMs
11645
- };
11646
- const resolvedRead = {
11647
- max: Math.max(routeMax, Number.isFinite(settings.rateLimitReadMax) ? settings.rateLimitReadMax : routeMax),
11648
- windowMs
11649
- };
11650
- resolvedCache = { read: resolvedRead, write: resolvedWrite };
11651
- resolvedAt = now;
11652
- if (profile === "read") return resolvedRead;
11653
- if (profile === "write") return resolvedWrite;
11654
- return { max: routeMax, windowMs };
12220
+ const settingsWindowMs = Number.isFinite(settings.rateLimitWindowSeconds) ? Math.max(1e4, settings.rateLimitWindowSeconds * 1e3) : routeWindowMs;
12221
+ let resolved;
12222
+ if (profile === "write") {
12223
+ resolved = {
12224
+ max: Math.min(
12225
+ routeMax,
12226
+ Number.isFinite(settings.rateLimitWriteMax) ? settings.rateLimitWriteMax : routeMax
12227
+ ),
12228
+ windowMs: Math.max(routeWindowMs, settingsWindowMs)
12229
+ };
12230
+ } else if (profile === "read") {
12231
+ resolved = {
12232
+ max: Math.max(
12233
+ routeMax,
12234
+ Number.isFinite(settings.rateLimitReadMax) ? settings.rateLimitReadMax : routeMax
12235
+ ),
12236
+ windowMs: settingsWindowMs
12237
+ };
12238
+ } else {
12239
+ resolved = { max: routeMax, windowMs: routeWindowMs };
12240
+ }
12241
+ resolvedCache.set(cacheKey, { ...resolved, at: now });
12242
+ return resolved;
11655
12243
  }
11656
12244
  var rateLimit = (cfg = {}, { strapi: strapi2 }) => {
11657
12245
  const routeMax = Number.isFinite(cfg.max) ? cfg.max : 30;
@@ -11659,7 +12247,7 @@ var require_rate_limit = __commonJS({
11659
12247
  const profile = cfg.profile === "read" || cfg.profile === "write" ? cfg.profile : null;
11660
12248
  return async (ctx, next) => {
11661
12249
  const { max, windowMs } = profile ? await resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) : { max: routeMax, windowMs: routeWindowMs };
11662
- const key = `${ctx.path}::${callerKey(ctx)}`;
12250
+ const key = `${routeKey(ctx)}::${callerKey(ctx)}`;
11663
12251
  const now = Date.now();
11664
12252
  if (buckets.size > 5e3) prune(now);
11665
12253
  let entry = buckets.get(key);
@@ -11687,6 +12275,14 @@ var require_rate_limit = __commonJS({
11687
12275
  await next();
11688
12276
  };
11689
12277
  };
12278
+ rateLimit.__private = {
12279
+ resolveLimits,
12280
+ routeKey,
12281
+ reset() {
12282
+ buckets.clear();
12283
+ resolvedCache.clear();
12284
+ }
12285
+ };
11690
12286
  module2.exports = rateLimit;
11691
12287
  }
11692
12288
  });
@@ -11713,21 +12309,30 @@ var require_session_required = __commonJS({
11713
12309
  var { getPluginSettings } = require_settings_loader();
11714
12310
  var { extractBearerToken } = require_extract_token();
11715
12311
  var { hashToken } = require_encryption();
12312
+ var JWT_MANAGEMENT_CONFIG = "plugin::users-permissions.jwtManagement";
12313
+ function getVerifiedNativeSessionId(policyContext) {
12314
+ const value = policyContext?.state?.session?.id ?? policyContext?.state?.auth?.credentials?.sessionId;
12315
+ return typeof value === "string" && value.length > 0 ? value : null;
12316
+ }
11716
12317
  module2.exports = async (policyContext, _policyConfig, { strapi: strapi2 }) => {
11717
12318
  if (!policyContext.state.user) {
11718
12319
  return true;
11719
12320
  }
11720
12321
  const user = policyContext.state.user;
12322
+ let strictMode = true;
11721
12323
  try {
12324
+ const settings = await getPluginSettings(strapi2);
12325
+ strictMode = settings.strictSessionEnforcement === true;
11722
12326
  let userDocId = user.documentId;
11723
12327
  if (!userDocId && user.id) {
11724
12328
  userDocId = await resolveUserDocumentId(strapi2, user.id);
11725
12329
  }
11726
12330
  if (!userDocId) {
12331
+ if (strictMode) {
12332
+ throw new errors.UnauthorizedError("No valid session. Please login again.");
12333
+ }
11727
12334
  return true;
11728
12335
  }
11729
- const settings = await getPluginSettings(strapi2);
11730
- const strictMode = settings.strictSessionEnforcement === true;
11731
12336
  const token = extractBearerToken(policyContext);
11732
12337
  const tokenHashValue = token ? hashToken(token) : null;
11733
12338
  if (!tokenHashValue) {
@@ -11737,29 +12342,53 @@ var require_session_required = __commonJS({
11737
12342
  }
11738
12343
  return true;
11739
12344
  }
12345
+ const nativeMode = strapi2.config?.get?.(JWT_MANAGEMENT_CONFIG, "legacy-support") === "refresh";
12346
+ const nativeSessionId = nativeMode ? getVerifiedNativeSessionId(policyContext) : null;
12347
+ if (nativeMode && !nativeSessionId) {
12348
+ if (strictMode) {
12349
+ strapi2.log.info(
12350
+ "[magic-sessionmanager] [POLICY-BLOCKED] No verified native session (strictMode)"
12351
+ );
12352
+ throw new errors.UnauthorizedError("No valid session. Please login again.");
12353
+ }
12354
+ return true;
12355
+ }
11740
12356
  const thisSession = await strapi2.documents(SESSION_UID).findFirst({
11741
- filters: { user: { documentId: userDocId }, tokenHash: tokenHashValue },
12357
+ filters: {
12358
+ user: { documentId: userDocId },
12359
+ tokenHash: tokenHashValue,
12360
+ ...nativeSessionId ? { nativeSessionId } : {}
12361
+ },
11742
12362
  fields: ["documentId", "isActive", "terminatedManually", "terminationReason"]
11743
12363
  });
11744
12364
  if (thisSession) {
11745
12365
  if (thisSession.isActive === false || thisSession.terminatedManually === true) {
11746
12366
  const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : "inactive");
11747
- strapi2.log.info(`[magic-sessionmanager] [POLICY-BLOCKED] Session inactive (reason: ${reason})`);
12367
+ strapi2.log.info(
12368
+ `[magic-sessionmanager] [POLICY-BLOCKED] Session inactive (reason: ${reason})`
12369
+ );
11748
12370
  throw new errors.UnauthorizedError("Session terminated. Please login again.");
11749
12371
  }
11750
12372
  return true;
11751
12373
  }
11752
12374
  if (strictMode) {
11753
- strapi2.log.info("[magic-sessionmanager] [POLICY-BLOCKED] No session matches this token (strictMode)");
12375
+ strapi2.log.info(
12376
+ "[magic-sessionmanager] [POLICY-BLOCKED] No session matches this token (strictMode)"
12377
+ );
11754
12378
  throw new errors.UnauthorizedError("No valid session. Please login again.");
11755
12379
  }
11756
- strapi2.log.warn("[magic-sessionmanager] [POLICY-WARN] No session for token; allowing in non-strict mode");
12380
+ strapi2.log.warn(
12381
+ "[magic-sessionmanager] [POLICY-WARN] No session for token; allowing in non-strict mode"
12382
+ );
11757
12383
  return true;
11758
12384
  } catch (err) {
11759
12385
  if (err instanceof errors.UnauthorizedError) {
11760
12386
  throw err;
11761
12387
  }
11762
12388
  strapi2.log.debug("[magic-sessionmanager] Session policy check error:", err?.name || "Error");
12389
+ if (strictMode) {
12390
+ throw new errors.UnauthorizedError("No valid session. Please login again.");
12391
+ }
11763
12392
  return true;
11764
12393
  }
11765
12394
  };