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.
- package/CHANGELOG.md +83 -5
- package/README.md +379 -641
- package/dist/admin/Analytics-B6d-39Qh.js +420 -0
- package/dist/admin/Analytics-DxOWXHn8.mjs +418 -0
- package/dist/admin/App-ZsSGj7n8.mjs +1894 -0
- package/dist/admin/App-mRFV50K6.js +1896 -0
- package/dist/admin/License-BE6UQ_V3.mjs +443 -0
- package/dist/admin/License-DXt2oi6u.js +443 -0
- package/dist/admin/OnlineUsersWidget-CFvM3Vbp.js +273 -0
- package/dist/admin/OnlineUsersWidget-_tJ6aeWl.mjs +254 -0
- package/dist/admin/SectionCard-BlWv8CRt.js +54 -0
- package/dist/admin/SectionCard-D51bv4Hi.mjs +55 -0
- package/dist/admin/Settings-BUc12TP5.js +3570 -0
- package/dist/admin/Settings-dtW7cjTX.mjs +3568 -0
- package/dist/admin/de-BFKoGEVT.js +544 -0
- package/dist/admin/de-j0oZH9Pz.mjs +544 -0
- package/dist/admin/en-UY4Tb5tE.mjs +544 -0
- package/dist/admin/en-s7Ksdkcg.js +544 -0
- package/dist/admin/es-07OGMe_5.js +544 -0
- package/dist/admin/es-DGBcZwQy.mjs +544 -0
- package/dist/admin/fr-B6-DWhGO.mjs +544 -0
- package/dist/admin/fr-ETj_2UBY.js +544 -0
- package/dist/admin/index-C_SyRULc.mjs +1750 -0
- package/dist/admin/index-D4kEnXSp.js +1751 -0
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +2 -2
- package/dist/admin/maskSensitiveValue-BWcSjow7.js +9 -0
- package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +10 -0
- package/dist/admin/pt-C7PwrQtV.js +544 -0
- package/dist/admin/pt-YMRLm9gx.mjs +544 -0
- package/dist/server/index.js +1092 -463
- package/dist/server/index.mjs +1092 -463
- package/package.json +10 -1
- package/pics/analytics.png +0 -0
- package/pics/dashboard-dark.png +0 -0
- package/pics/dashboard.png +0 -0
- package/pics/dashboardsessionmodal.png +0 -0
- package/pics/mobile-dashboard.png +0 -0
- package/pics/mobile-session.png +0 -0
- package/pics/sessioninfopanel.png +0 -0
- package/pics/settings1.png +0 -0
- package/pics/settings2.png +0 -0
- package/pics/widget.png +0 -0
- package/scripts/geoip-updater.cjs +35 -24
- package/dist/admin/Analytics-CaRlu5ad.js +0 -332
- package/dist/admin/Analytics-THqDbNX0.mjs +0 -330
- package/dist/admin/App-AbZwLHtF.js +0 -1263
- package/dist/admin/App-hSh7guii.mjs +0 -1261
- package/dist/admin/FormField-C8kIT2NE.mjs +0 -59
- package/dist/admin/FormField-b5KBvkrj.js +0 -60
- package/dist/admin/License-BXBVwUVu.mjs +0 -299
- package/dist/admin/License-CABdPwnd.js +0 -301
- package/dist/admin/OnlineUsersWidget-BnWFj9IM.mjs +0 -230
- package/dist/admin/OnlineUsersWidget-CPFAACSb.js +0 -230
- package/dist/admin/PluginPageLayout-BPFMcgrx.mjs +0 -42
- package/dist/admin/PluginPageLayout-DmNzMdqu.js +0 -43
- package/dist/admin/Settings-B4DNdeKx.js +0 -2152
- package/dist/admin/Settings-C4RsJosh.mjs +0 -2150
- package/dist/admin/de-AwIFTd9i.mjs +0 -450
- package/dist/admin/de-D23nmqnl.js +0 -450
- package/dist/admin/en-C5iYQ0mC.js +0 -450
- package/dist/admin/en-D6QEGeRh.mjs +0 -450
- package/dist/admin/es-CIXnsG-p.js +0 -435
- package/dist/admin/es-CnFfVdKw.mjs +0 -435
- package/dist/admin/fr-BglXE-W4.js +0 -435
- package/dist/admin/fr-DefoR7uH.mjs +0 -435
- package/dist/admin/index-BFVITQ-o.mjs +0 -624
- package/dist/admin/index-DlMm-NyK.js +0 -625
- package/dist/admin/maskSensitiveValue-1uGWmrfG.mjs +0 -20
- package/dist/admin/maskSensitiveValue-B9vhxPad.js +0 -19
- package/dist/admin/pt-J5sf7jiY.js +0 -435
- package/dist/admin/pt-TODwvNQA.mjs +0 -435
package/dist/server/index.mjs
CHANGED
|
@@ -125,12 +125,30 @@ var require_content_api_permissions = __commonJS({
|
|
|
125
125
|
}
|
|
126
126
|
});
|
|
127
127
|
|
|
128
|
+
// server/src/utils/block-revocation-scope.js
|
|
129
|
+
var require_block_revocation_scope = __commonJS({
|
|
130
|
+
"server/src/utils/block-revocation-scope.js"(exports, module) {
|
|
131
|
+
"use strict";
|
|
132
|
+
var { AsyncLocalStorage } = __require("node:async_hooks");
|
|
133
|
+
var storage = new AsyncLocalStorage();
|
|
134
|
+
function runWithCallerRevocation(userDocumentId, fn) {
|
|
135
|
+
return storage.run({ userDocumentId: String(userDocumentId) }, fn);
|
|
136
|
+
}
|
|
137
|
+
function isCallerRevocationScope(userDocumentId) {
|
|
138
|
+
const scope = storage.getStore();
|
|
139
|
+
return Boolean(scope && userDocumentId && scope.userDocumentId === String(userDocumentId));
|
|
140
|
+
}
|
|
141
|
+
module.exports = { runWithCallerRevocation, isCallerRevocationScope };
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
|
|
128
145
|
// server/src/register.js
|
|
129
146
|
var require_register = __commonJS({
|
|
130
147
|
"server/src/register.js"(exports, module) {
|
|
131
148
|
"use strict";
|
|
132
149
|
var { createLogger } = require_logger();
|
|
133
150
|
var { createContentApiPermissionsLifecycle } = require_content_api_permissions();
|
|
151
|
+
var { isCallerRevocationScope } = require_block_revocation_scope();
|
|
134
152
|
var USER_UID = "plugin::users-permissions.user";
|
|
135
153
|
module.exports = async ({ strapi: strapi2 }) => {
|
|
136
154
|
const log = createLogger(strapi2);
|
|
@@ -183,6 +201,7 @@ var require_register = __commonJS({
|
|
|
183
201
|
if (!data || data.blocked !== true) return;
|
|
184
202
|
const userDocId = result.documentId;
|
|
185
203
|
if (!userDocId) return;
|
|
204
|
+
if (isCallerRevocationScope(userDocId)) return;
|
|
186
205
|
const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
|
|
187
206
|
const { terminatedCount: terminated } = await sessionService.terminateSession({
|
|
188
207
|
userId: userDocId,
|
|
@@ -247,7 +266,10 @@ var require_getClientIp = __commonJS({
|
|
|
247
266
|
return "unknown";
|
|
248
267
|
} catch (error) {
|
|
249
268
|
if (ctx?.app?.context?.strapi?.log?.debug) {
|
|
250
|
-
ctx.app.context.strapi.log.debug(
|
|
269
|
+
ctx.app.context.strapi.log.debug(
|
|
270
|
+
"[getClientIp] Error extracting IP:",
|
|
271
|
+
error?.name || "Error"
|
|
272
|
+
);
|
|
251
273
|
}
|
|
252
274
|
return "unknown";
|
|
253
275
|
}
|
|
@@ -280,6 +302,7 @@ var require_encryption = __commonJS({
|
|
|
280
302
|
var crypto = __require("crypto");
|
|
281
303
|
var ALGORITHM = "aes-256-gcm";
|
|
282
304
|
var IV_LENGTH = 16;
|
|
305
|
+
var AUTH_TAG_LENGTH = 16;
|
|
283
306
|
var warnedMissingKey = false;
|
|
284
307
|
var isProduction = () => process.env.NODE_ENV === "production";
|
|
285
308
|
function getEncryptionKey() {
|
|
@@ -313,9 +336,12 @@ var require_encryption = __commonJS({
|
|
|
313
336
|
return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
|
|
314
337
|
} catch (err) {
|
|
315
338
|
if (typeof strapi !== "undefined" && strapi?.log) {
|
|
316
|
-
strapi.log.error(
|
|
339
|
+
strapi.log.error(
|
|
340
|
+
"[magic-sessionmanager/encryption] Encryption failed:",
|
|
341
|
+
err?.name || "Error"
|
|
342
|
+
);
|
|
317
343
|
}
|
|
318
|
-
throw new Error("Failed to encrypt token");
|
|
344
|
+
throw new Error("Failed to encrypt token", { cause: err });
|
|
319
345
|
}
|
|
320
346
|
}
|
|
321
347
|
function decryptToken(encryptedToken) {
|
|
@@ -329,14 +355,19 @@ var require_encryption = __commonJS({
|
|
|
329
355
|
const iv = Buffer.from(parts[0], "hex");
|
|
330
356
|
const authTag = Buffer.from(parts[1], "hex");
|
|
331
357
|
const encrypted = parts[2];
|
|
332
|
-
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv
|
|
358
|
+
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv, {
|
|
359
|
+
authTagLength: AUTH_TAG_LENGTH
|
|
360
|
+
});
|
|
333
361
|
decipher.setAuthTag(authTag);
|
|
334
362
|
let decrypted = decipher.update(encrypted, "hex", "utf8");
|
|
335
363
|
decrypted += decipher.final("utf8");
|
|
336
364
|
return decrypted;
|
|
337
365
|
} catch (err) {
|
|
338
366
|
if (typeof strapi !== "undefined" && strapi?.log) {
|
|
339
|
-
strapi.log.error(
|
|
367
|
+
strapi.log.error(
|
|
368
|
+
"[magic-sessionmanager/encryption] Decryption failed:",
|
|
369
|
+
err?.name || "Error"
|
|
370
|
+
);
|
|
340
371
|
}
|
|
341
372
|
return null;
|
|
342
373
|
}
|
|
@@ -534,14 +565,16 @@ var require_settings_loader = __commonJS({
|
|
|
534
565
|
return cached;
|
|
535
566
|
}
|
|
536
567
|
const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
|
|
537
|
-
let storedSettings
|
|
568
|
+
let storedSettings;
|
|
538
569
|
try {
|
|
539
570
|
const pluginStore = strapi2.store({ type: "plugin", name: PLUGIN_ID });
|
|
540
571
|
const raw = await pluginStore.get({ key: SETTINGS_KEY });
|
|
541
572
|
storedSettings = normalizeStoredSettings(raw);
|
|
542
573
|
} catch {
|
|
543
|
-
strapi2.log.error(
|
|
544
|
-
|
|
574
|
+
strapi2.log.error(
|
|
575
|
+
`[${PLUGIN_ID}] settings-loader: store read failed; strict session enforcement is enabled and geolocation is disabled`
|
|
576
|
+
);
|
|
577
|
+
storedSettings = { strictSessionEnforcement: true, enableGeolocation: false };
|
|
545
578
|
}
|
|
546
579
|
const merged = { ...staticConfig, ...storedSettings };
|
|
547
580
|
cached = merged;
|
|
@@ -919,6 +952,9 @@ var require_auth_routes = __commonJS({
|
|
|
919
952
|
}
|
|
920
953
|
return null;
|
|
921
954
|
}
|
|
955
|
+
function isPasswordResetRequest(path, method) {
|
|
956
|
+
return requestKey(path, String(method || "").toUpperCase()) === "POST /api/auth/reset-password";
|
|
957
|
+
}
|
|
922
958
|
function shouldRunPreAuthGeoGuard(path, method) {
|
|
923
959
|
return classifyJwtIssuingRequest(path, method) === "new-session";
|
|
924
960
|
}
|
|
@@ -928,6 +964,7 @@ var require_auth_routes = __commonJS({
|
|
|
928
964
|
module.exports = {
|
|
929
965
|
classifyJwtIssuingRequest,
|
|
930
966
|
isFailedLoginTrackedPath,
|
|
967
|
+
isPasswordResetRequest,
|
|
931
968
|
shouldRunPreAuthGeoGuard
|
|
932
969
|
};
|
|
933
970
|
}
|
|
@@ -1114,7 +1151,10 @@ var require_last_seen = __commonJS({
|
|
|
1114
1151
|
try {
|
|
1115
1152
|
userDocId = await resolveUserDocumentId(strapi2, ctx.state.user.id);
|
|
1116
1153
|
} catch (err) {
|
|
1117
|
-
strapi2.log.debug(
|
|
1154
|
+
strapi2.log.debug(
|
|
1155
|
+
"[magic-sessionmanager] user document lookup failed:",
|
|
1156
|
+
err?.name || "Error"
|
|
1157
|
+
);
|
|
1118
1158
|
return;
|
|
1119
1159
|
}
|
|
1120
1160
|
}
|
|
@@ -1127,7 +1167,7 @@ var require_last_seen = __commonJS({
|
|
|
1127
1167
|
if (!nativeSessionId && !tokenHashValue) {
|
|
1128
1168
|
return;
|
|
1129
1169
|
}
|
|
1130
|
-
let thisSession
|
|
1170
|
+
let thisSession;
|
|
1131
1171
|
try {
|
|
1132
1172
|
const filters = { user: { documentId: userDocId } };
|
|
1133
1173
|
if (nativeSessionId) {
|
|
@@ -5096,15 +5136,9 @@ var require_bootstrap = __commonJS({
|
|
|
5096
5136
|
var { encryptToken, hashToken } = require_encryption();
|
|
5097
5137
|
var { createLogger } = require_logger();
|
|
5098
5138
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
5099
|
-
var {
|
|
5100
|
-
getPluginSettings,
|
|
5101
|
-
getSessionCreationGraceMs
|
|
5102
|
-
} = require_settings_loader();
|
|
5139
|
+
var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
|
|
5103
5140
|
var { extractBearerToken } = require_extract_token();
|
|
5104
|
-
var {
|
|
5105
|
-
setSessionRejectionReason,
|
|
5106
|
-
consumeSessionRejectionReason
|
|
5107
|
-
} = require_rejection_cache();
|
|
5141
|
+
var { setSessionRejectionReason } = require_rejection_cache();
|
|
5108
5142
|
var { evaluateGeoFirewall } = require_geo_firewall();
|
|
5109
5143
|
var { REVOCATION_UID } = require_session_revocation();
|
|
5110
5144
|
var { getNativeSessionManager } = require_native_session_manager();
|
|
@@ -5112,6 +5146,7 @@ var require_bootstrap = __commonJS({
|
|
|
5112
5146
|
var {
|
|
5113
5147
|
classifyJwtIssuingRequest,
|
|
5114
5148
|
isFailedLoginTrackedPath,
|
|
5149
|
+
isPasswordResetRequest,
|
|
5115
5150
|
shouldRunPreAuthGeoGuard
|
|
5116
5151
|
} = require_auth_routes();
|
|
5117
5152
|
var {
|
|
@@ -5124,7 +5159,7 @@ var require_bootstrap = __commonJS({
|
|
|
5124
5159
|
var JWT_WRAPPED_FLAG = /* @__PURE__ */ Symbol.for("magic-sessionmanager.jwt.wrapped");
|
|
5125
5160
|
var deferredContentApiPermissionSetup = /* @__PURE__ */ new WeakMap();
|
|
5126
5161
|
async function getRequestSettings(strapi2, ctx) {
|
|
5127
|
-
let settings
|
|
5162
|
+
let settings;
|
|
5128
5163
|
try {
|
|
5129
5164
|
settings = await getPluginSettings(strapi2);
|
|
5130
5165
|
} catch {
|
|
@@ -5146,7 +5181,7 @@ var require_bootstrap = __commonJS({
|
|
|
5146
5181
|
}
|
|
5147
5182
|
try {
|
|
5148
5183
|
await ensureSessionLookupIndexes(strapi2, log);
|
|
5149
|
-
await registerSessionAwareAuthStrategy(strapi2
|
|
5184
|
+
await registerSessionAwareAuthStrategy(strapi2);
|
|
5150
5185
|
const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
|
|
5151
5186
|
await licenseGuardService.initialize();
|
|
5152
5187
|
log.info("[SUCCESS] Session Manager active - all features are available without a license key");
|
|
@@ -5203,9 +5238,12 @@ var require_bootstrap = __commonJS({
|
|
|
5203
5238
|
}, RETENTION_INTERVAL_MS);
|
|
5204
5239
|
strapi2.sessionManagerIntervals.retentionTimeout = handle;
|
|
5205
5240
|
};
|
|
5206
|
-
strapi2.sessionManagerIntervals.retentionStartup = setTimeout(
|
|
5207
|
-
|
|
5208
|
-
|
|
5241
|
+
strapi2.sessionManagerIntervals.retentionStartup = setTimeout(
|
|
5242
|
+
() => {
|
|
5243
|
+
scheduleRetention();
|
|
5244
|
+
},
|
|
5245
|
+
5 * 60 * 1e3
|
|
5246
|
+
);
|
|
5209
5247
|
log.info("[TIME] Dynamic cleanup + retention scheduled");
|
|
5210
5248
|
mountPreLoginGeoGuard({ strapi: strapi2, log });
|
|
5211
5249
|
mountFailedLoginLockout({ strapi: strapi2, log });
|
|
@@ -5213,13 +5251,9 @@ var require_bootstrap = __commonJS({
|
|
|
5213
5251
|
mountLoginInterceptor({ strapi: strapi2, log, sessionService });
|
|
5214
5252
|
mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
|
|
5215
5253
|
mountLogoutInterceptor({ strapi: strapi2, log, sessionService });
|
|
5216
|
-
strapi2.server.use(
|
|
5217
|
-
require_session_rejection_headers()({}, { strapi: strapi2 })
|
|
5218
|
-
);
|
|
5254
|
+
strapi2.server.use(require_session_rejection_headers()({}, { strapi: strapi2 }));
|
|
5219
5255
|
log.info("[SUCCESS] Session-rejection-headers middleware mounted");
|
|
5220
|
-
strapi2.server.use(
|
|
5221
|
-
require_last_seen()({ strapi: strapi2, sessionService })
|
|
5222
|
-
);
|
|
5256
|
+
strapi2.server.use(require_last_seen()({ strapi: strapi2, sessionService }));
|
|
5223
5257
|
log.info("[SUCCESS] LastSeen middleware mounted");
|
|
5224
5258
|
const contentApiPermissionsReady = await ensureContentApiPermissions(strapi2, log);
|
|
5225
5259
|
mountDeferredContentApiPermissionRetry({
|
|
@@ -5228,7 +5262,9 @@ var require_bootstrap = __commonJS({
|
|
|
5228
5262
|
initiallyReady: contentApiPermissionsReady
|
|
5229
5263
|
});
|
|
5230
5264
|
log.info("[SUCCESS] Bootstrap complete");
|
|
5231
|
-
log.info(
|
|
5265
|
+
log.info(
|
|
5266
|
+
"[READY] Session Manager ready! Sessions stored in plugin::magic-sessionmanager.session"
|
|
5267
|
+
);
|
|
5232
5268
|
} catch (err) {
|
|
5233
5269
|
log.error("[ERROR] Bootstrap error:", err?.name || "Error");
|
|
5234
5270
|
}
|
|
@@ -5298,67 +5334,83 @@ var require_bootstrap = __commonJS({
|
|
|
5298
5334
|
} catch {
|
|
5299
5335
|
jwt = null;
|
|
5300
5336
|
}
|
|
5301
|
-
strapi2.server.routes([
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
|
|
5306
|
-
const token = extractBearerToken(ctx);
|
|
5307
|
-
if (!token) {
|
|
5308
|
-
ctx.status = 401;
|
|
5309
|
-
ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Authorization token required" } };
|
|
5310
|
-
return;
|
|
5311
|
-
}
|
|
5312
|
-
const jwtService = strapi2.plugin("users-permissions").service("jwt");
|
|
5313
|
-
let decoded = null;
|
|
5337
|
+
strapi2.server.routes([
|
|
5338
|
+
{
|
|
5339
|
+
method: "POST",
|
|
5340
|
+
path: "/api/auth/logout",
|
|
5341
|
+
handler: async (ctx) => {
|
|
5314
5342
|
try {
|
|
5315
|
-
|
|
5316
|
-
|
|
5317
|
-
|
|
5318
|
-
|
|
5319
|
-
|
|
5320
|
-
|
|
5321
|
-
|
|
5322
|
-
|
|
5343
|
+
const token = extractBearerToken(ctx);
|
|
5344
|
+
if (!token) {
|
|
5345
|
+
ctx.status = 401;
|
|
5346
|
+
ctx.body = {
|
|
5347
|
+
error: {
|
|
5348
|
+
status: 401,
|
|
5349
|
+
name: "UnauthorizedError",
|
|
5350
|
+
message: "Authorization token required"
|
|
5351
|
+
}
|
|
5352
|
+
};
|
|
5353
|
+
return;
|
|
5354
|
+
}
|
|
5355
|
+
const jwtService = strapi2.plugin("users-permissions").service("jwt");
|
|
5356
|
+
let decoded = null;
|
|
5357
|
+
try {
|
|
5358
|
+
decoded = await jwtService.verify(token);
|
|
5359
|
+
} catch (verifyErr) {
|
|
5360
|
+
const isExpired = verifyErr?.name === "TokenExpiredError" || /expired/i.test(verifyErr?.message || "");
|
|
5361
|
+
if (isExpired && jwt) {
|
|
5362
|
+
try {
|
|
5363
|
+
const jwtSecret = strapi2.config.get("plugin::users-permissions.jwtSecret");
|
|
5364
|
+
if (jwtSecret) {
|
|
5365
|
+
decoded = jwt.verify(token, jwtSecret, { ignoreExpiration: true });
|
|
5366
|
+
}
|
|
5367
|
+
} catch {
|
|
5368
|
+
decoded = null;
|
|
5323
5369
|
}
|
|
5324
|
-
} catch {
|
|
5325
|
-
decoded = null;
|
|
5326
5370
|
}
|
|
5371
|
+
if (!decoded) {
|
|
5372
|
+
ctx.status = 401;
|
|
5373
|
+
ctx.body = {
|
|
5374
|
+
error: { status: 401, name: "UnauthorizedError", message: "Invalid token" }
|
|
5375
|
+
};
|
|
5376
|
+
return;
|
|
5377
|
+
}
|
|
5378
|
+
}
|
|
5379
|
+
if (!decoded || !decoded.id) {
|
|
5380
|
+
ctx.status = 401;
|
|
5381
|
+
ctx.body = {
|
|
5382
|
+
error: { status: 401, name: "UnauthorizedError", message: "Invalid token" }
|
|
5383
|
+
};
|
|
5384
|
+
return;
|
|
5327
5385
|
}
|
|
5328
|
-
|
|
5386
|
+
const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
|
|
5387
|
+
if (!userDocumentId) {
|
|
5329
5388
|
ctx.status = 401;
|
|
5330
|
-
ctx.body = {
|
|
5389
|
+
ctx.body = {
|
|
5390
|
+
error: { status: 401, name: "UnauthorizedError", message: "Invalid token" }
|
|
5391
|
+
};
|
|
5331
5392
|
return;
|
|
5332
5393
|
}
|
|
5394
|
+
await sessionService.terminateAuthenticatedSession({
|
|
5395
|
+
userDocumentId,
|
|
5396
|
+
accessToken: token,
|
|
5397
|
+
refreshToken: null
|
|
5398
|
+
});
|
|
5399
|
+
ctx.status = 200;
|
|
5400
|
+
ctx.body = { ok: true, message: "Logged out successfully" };
|
|
5401
|
+
} catch (err) {
|
|
5402
|
+
log.error("Logout error:", err?.name || "Error");
|
|
5403
|
+
ctx.status = 500;
|
|
5404
|
+
ctx.body = {
|
|
5405
|
+
error: { status: 500, name: "InternalServerError", message: "Logout failed" }
|
|
5406
|
+
};
|
|
5333
5407
|
}
|
|
5334
|
-
|
|
5335
|
-
|
|
5336
|
-
|
|
5337
|
-
return;
|
|
5338
|
-
}
|
|
5339
|
-
const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
|
|
5340
|
-
if (!userDocumentId) {
|
|
5341
|
-
ctx.status = 401;
|
|
5342
|
-
ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
|
|
5343
|
-
return;
|
|
5344
|
-
}
|
|
5345
|
-
await sessionService.terminateAuthenticatedSession({
|
|
5346
|
-
userDocumentId,
|
|
5347
|
-
accessToken: token,
|
|
5348
|
-
refreshToken: null
|
|
5349
|
-
});
|
|
5350
|
-
ctx.status = 200;
|
|
5351
|
-
ctx.body = { ok: true, message: "Logged out successfully" };
|
|
5352
|
-
} catch (err) {
|
|
5353
|
-
log.error("Logout error:", err?.name || "Error");
|
|
5354
|
-
ctx.status = 500;
|
|
5355
|
-
ctx.body = { error: { status: 500, name: "InternalServerError", message: "Logout failed" } };
|
|
5408
|
+
},
|
|
5409
|
+
config: {
|
|
5410
|
+
auth: false
|
|
5356
5411
|
}
|
|
5357
|
-
},
|
|
5358
|
-
config: {
|
|
5359
|
-
auth: false
|
|
5360
5412
|
}
|
|
5361
|
-
|
|
5413
|
+
]);
|
|
5362
5414
|
log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
|
|
5363
5415
|
}
|
|
5364
5416
|
function hasRegisteredRoute(strapi2, method, path) {
|
|
@@ -5409,7 +5461,8 @@ var require_bootstrap = __commonJS({
|
|
|
5409
5461
|
throw new Error("native refresh token owner does not match the authentication response");
|
|
5410
5462
|
}
|
|
5411
5463
|
const userDocumentId = resolvedUserDocumentId || user?.documentId;
|
|
5412
|
-
if (!userDocumentId)
|
|
5464
|
+
if (!userDocumentId)
|
|
5465
|
+
throw new Error("native refresh token owner has no resolvable user documentId");
|
|
5413
5466
|
return { userId, userDocumentId, sessionId: String(validation.sessionId) };
|
|
5414
5467
|
}
|
|
5415
5468
|
async function compensateNativeSession({ nativeSessionManager, nativeSession, log }) {
|
|
@@ -5480,9 +5533,7 @@ var require_bootstrap = __commonJS({
|
|
|
5480
5533
|
} else if (ctx.status >= 400 && ctx.status < 500 && ctx.status !== 429) {
|
|
5481
5534
|
const entry = recordFailure(ip, maxFailed);
|
|
5482
5535
|
if (entry.blockedUntil > now) {
|
|
5483
|
-
log.warn(
|
|
5484
|
-
`[LOCKOUT] Client locked for 15min after ${entry.count} failed login attempts`
|
|
5485
|
-
);
|
|
5536
|
+
log.warn(`[LOCKOUT] Client locked for 15min after ${entry.count} failed login attempts`);
|
|
5486
5537
|
}
|
|
5487
5538
|
}
|
|
5488
5539
|
});
|
|
@@ -5524,7 +5575,8 @@ var require_bootstrap = __commonJS({
|
|
|
5524
5575
|
refreshToken: newRefreshToken,
|
|
5525
5576
|
nativeSessionId: nativeSession2.sessionId
|
|
5526
5577
|
});
|
|
5527
|
-
if (!rotated)
|
|
5578
|
+
if (!rotated)
|
|
5579
|
+
throw new Error("current sidecar changed before native password rotation was linked");
|
|
5528
5580
|
log.info("[PASSWORD] Native session link updated");
|
|
5529
5581
|
} else {
|
|
5530
5582
|
const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
|
|
@@ -5574,7 +5626,13 @@ var require_bootstrap = __commonJS({
|
|
|
5574
5626
|
if (!rotated) throw new Error("current session changed before token rotation");
|
|
5575
5627
|
log.info("[PASSWORD] Legacy session tokens rotated");
|
|
5576
5628
|
} catch (err) {
|
|
5577
|
-
failClosedAuthResponse({
|
|
5629
|
+
failClosedAuthResponse({
|
|
5630
|
+
ctx,
|
|
5631
|
+
strapi: strapi2,
|
|
5632
|
+
log,
|
|
5633
|
+
operation: "change-password rotation failed",
|
|
5634
|
+
error: err
|
|
5635
|
+
});
|
|
5578
5636
|
}
|
|
5579
5637
|
return;
|
|
5580
5638
|
}
|
|
@@ -5620,6 +5678,14 @@ var require_bootstrap = __commonJS({
|
|
|
5620
5678
|
if (!newSession?.documentId) {
|
|
5621
5679
|
throw new Error(`session creation returned no documentId for user ${userDocId}`);
|
|
5622
5680
|
}
|
|
5681
|
+
if (isPasswordResetRequest(ctx.path, ctx.method)) {
|
|
5682
|
+
await sessionService.terminateSession({
|
|
5683
|
+
userId: userDocId,
|
|
5684
|
+
exceptSessionId: newSession.documentId,
|
|
5685
|
+
reason: "logout"
|
|
5686
|
+
});
|
|
5687
|
+
log.info("[PASSWORD] Ended older sessions after password reset");
|
|
5688
|
+
}
|
|
5623
5689
|
log.info("[SUCCESS] End-user session metadata created");
|
|
5624
5690
|
try {
|
|
5625
5691
|
const settings = await getPluginSettings(strapi2);
|
|
@@ -5660,7 +5726,9 @@ var require_bootstrap = __commonJS({
|
|
|
5660
5726
|
limit: 50
|
|
5661
5727
|
});
|
|
5662
5728
|
const previousCountries = new Set(
|
|
5663
|
-
(previousSessions || []).flatMap(
|
|
5729
|
+
(previousSessions || []).flatMap(
|
|
5730
|
+
(session) => countryTokensFromGeo(session.geoLocation)
|
|
5731
|
+
)
|
|
5664
5732
|
);
|
|
5665
5733
|
const currentCountries = countryTokensFromGeo(geoData);
|
|
5666
5734
|
if (currentCountries.length > 0 && previousCountries.size > 0 && !currentCountries.some((country) => previousCountries.has(country))) {
|
|
@@ -5745,7 +5813,13 @@ var require_bootstrap = __commonJS({
|
|
|
5745
5813
|
if (nativeSessionManager && nativeSession) {
|
|
5746
5814
|
await compensateNativeSession({ nativeSessionManager, nativeSession, log });
|
|
5747
5815
|
}
|
|
5748
|
-
failClosedAuthResponse({
|
|
5816
|
+
failClosedAuthResponse({
|
|
5817
|
+
ctx,
|
|
5818
|
+
strapi: strapi2,
|
|
5819
|
+
log,
|
|
5820
|
+
operation: "session creation failed",
|
|
5821
|
+
error: err
|
|
5822
|
+
});
|
|
5749
5823
|
}
|
|
5750
5824
|
});
|
|
5751
5825
|
log.info("[SUCCESS] Login interceptor middleware mounted");
|
|
@@ -5798,7 +5872,13 @@ var require_bootstrap = __commonJS({
|
|
|
5798
5872
|
}
|
|
5799
5873
|
}
|
|
5800
5874
|
} catch (err) {
|
|
5801
|
-
failClosedAuthResponse({
|
|
5875
|
+
failClosedAuthResponse({
|
|
5876
|
+
ctx,
|
|
5877
|
+
strapi: strapi2,
|
|
5878
|
+
log,
|
|
5879
|
+
operation: "refresh validation failed",
|
|
5880
|
+
error: err
|
|
5881
|
+
});
|
|
5802
5882
|
return;
|
|
5803
5883
|
}
|
|
5804
5884
|
await next();
|
|
@@ -5823,7 +5903,8 @@ var require_bootstrap = __commonJS({
|
|
|
5823
5903
|
refreshToken: newRefreshToken,
|
|
5824
5904
|
nativeSessionId: nativeSession.sessionId
|
|
5825
5905
|
});
|
|
5826
|
-
if (!rotated)
|
|
5906
|
+
if (!rotated)
|
|
5907
|
+
throw new Error("current sidecar changed before native refresh was linked");
|
|
5827
5908
|
log.info("[REFRESH] Native session link updated");
|
|
5828
5909
|
} else {
|
|
5829
5910
|
const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
|
|
@@ -5867,7 +5948,13 @@ var require_bootstrap = __commonJS({
|
|
|
5867
5948
|
if (!rotated) throw new Error("refresh token was already consumed");
|
|
5868
5949
|
log.info("[REFRESH] Legacy session tokens refreshed");
|
|
5869
5950
|
} catch (err) {
|
|
5870
|
-
failClosedAuthResponse({
|
|
5951
|
+
failClosedAuthResponse({
|
|
5952
|
+
ctx,
|
|
5953
|
+
strapi: strapi2,
|
|
5954
|
+
log,
|
|
5955
|
+
operation: "refresh rotation failed",
|
|
5956
|
+
error: err
|
|
5957
|
+
});
|
|
5871
5958
|
}
|
|
5872
5959
|
}
|
|
5873
5960
|
});
|
|
@@ -5879,7 +5966,10 @@ var require_bootstrap = __commonJS({
|
|
|
5879
5966
|
const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
|
|
5880
5967
|
const accessToken = extractBearerToken(ctx);
|
|
5881
5968
|
const nativeMode = usesNativeRefreshSessions(strapi2);
|
|
5882
|
-
const jwtManagement = strapi2.config.get(
|
|
5969
|
+
const jwtManagement = strapi2.config.get(
|
|
5970
|
+
"plugin::users-permissions.jwtManagement",
|
|
5971
|
+
"legacy-support"
|
|
5972
|
+
);
|
|
5883
5973
|
await next();
|
|
5884
5974
|
const isUsersPermissionsLogoutRoute = ctx.state?.route?.handler === "auth.logout" && ctx.state?.route?.info?.pluginName === "users-permissions";
|
|
5885
5975
|
const isSuccessful = isUsersPermissionsLogoutRoute && ctx.status >= 200 && ctx.status < 300;
|
|
@@ -5889,11 +5979,14 @@ var require_bootstrap = __commonJS({
|
|
|
5889
5979
|
try {
|
|
5890
5980
|
if (nativeMode) {
|
|
5891
5981
|
const nativeSessionId = ctx.state?.session?.id;
|
|
5892
|
-
if (!nativeSessionId)
|
|
5982
|
+
if (!nativeSessionId)
|
|
5983
|
+
throw new Error("authenticated logout has no native session identifier");
|
|
5893
5984
|
const nativeSessionManager = getNativeSessionManager(strapi2);
|
|
5894
5985
|
const nativeSessionStillActive = await nativeSessionManager.isSessionActive(nativeSessionId);
|
|
5895
5986
|
if (nativeSessionStillActive) {
|
|
5896
|
-
throw new Error(
|
|
5987
|
+
throw new Error(
|
|
5988
|
+
"Users & Permissions logout returned success while the native session remains active"
|
|
5989
|
+
);
|
|
5897
5990
|
}
|
|
5898
5991
|
}
|
|
5899
5992
|
const userDocumentId = authenticatedUser.documentId || await resolveUserDocumentId(strapi2, authenticatedUser.id);
|
|
@@ -5911,7 +6004,13 @@ var require_bootstrap = __commonJS({
|
|
|
5911
6004
|
message: "Logged out successfully"
|
|
5912
6005
|
};
|
|
5913
6006
|
} catch (err) {
|
|
5914
|
-
failClosedAuthResponse({
|
|
6007
|
+
failClosedAuthResponse({
|
|
6008
|
+
ctx,
|
|
6009
|
+
strapi: strapi2,
|
|
6010
|
+
log,
|
|
6011
|
+
operation: "logout termination failed",
|
|
6012
|
+
error: err
|
|
6013
|
+
});
|
|
5915
6014
|
}
|
|
5916
6015
|
});
|
|
5917
6016
|
log.info("[SUCCESS] Logout interceptor middleware mounted");
|
|
@@ -5984,7 +6083,9 @@ var require_bootstrap = __commonJS({
|
|
|
5984
6083
|
return true;
|
|
5985
6084
|
} catch (err) {
|
|
5986
6085
|
log.warn("Could not auto-configure permissions:", err?.name || "Error");
|
|
5987
|
-
log.warn(
|
|
6086
|
+
log.warn(
|
|
6087
|
+
"Please manually enable plugin permissions in Settings > Users & Permissions > Roles > Authenticated"
|
|
6088
|
+
);
|
|
5988
6089
|
return false;
|
|
5989
6090
|
}
|
|
5990
6091
|
}
|
|
@@ -6046,7 +6147,10 @@ var require_bootstrap = __commonJS({
|
|
|
6046
6147
|
);
|
|
6047
6148
|
hasIndex = result.rows.length > 0;
|
|
6048
6149
|
} else if (dialect === "mysql" || dialect === "mysql2") {
|
|
6049
|
-
const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
|
|
6150
|
+
const result = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [
|
|
6151
|
+
tableName,
|
|
6152
|
+
definition.name
|
|
6153
|
+
]);
|
|
6050
6154
|
hasIndex = result[0].length > 0;
|
|
6051
6155
|
} else if (dialect === "sqlite" || dialect === "better-sqlite3") {
|
|
6052
6156
|
const result = await knex.raw(
|
|
@@ -6065,7 +6169,10 @@ var require_bootstrap = __commonJS({
|
|
|
6065
6169
|
log.info(`[INDEX] Created ${definition.name}`);
|
|
6066
6170
|
}
|
|
6067
6171
|
} catch (err) {
|
|
6068
|
-
log.debug(
|
|
6172
|
+
log.debug(
|
|
6173
|
+
"[INDEX] Could not create session lookup indexes (will retry on next startup):",
|
|
6174
|
+
err?.name || "Error"
|
|
6175
|
+
);
|
|
6069
6176
|
}
|
|
6070
6177
|
}
|
|
6071
6178
|
var sessionCheckErrors = { count: 0, lastReset: Date.now() };
|
|
@@ -6092,7 +6199,7 @@ var require_bootstrap = __commonJS({
|
|
|
6092
6199
|
const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
|
|
6093
6200
|
return Date.now() - loginTime > maxAgeMs;
|
|
6094
6201
|
}
|
|
6095
|
-
async function registerSessionAwareAuthStrategy(strapi2
|
|
6202
|
+
async function registerSessionAwareAuthStrategy(strapi2) {
|
|
6096
6203
|
try {
|
|
6097
6204
|
const usersPermissionsPlugin = strapi2.plugin("users-permissions");
|
|
6098
6205
|
if (!usersPermissionsPlugin) {
|
|
@@ -6122,7 +6229,9 @@ var require_bootstrap = __commonJS({
|
|
|
6122
6229
|
if (nativeMode) {
|
|
6123
6230
|
if (typeof decoded.sessionId !== "string" || decoded.sessionId.length === 0) {
|
|
6124
6231
|
setSessionRejectionReason(tokenHashValue, "manual");
|
|
6125
|
-
strapi2.log.info(
|
|
6232
|
+
strapi2.log.info(
|
|
6233
|
+
"[magic-sessionmanager] [JWT-REJECTED] Native access token has no session identifier"
|
|
6234
|
+
);
|
|
6126
6235
|
return null;
|
|
6127
6236
|
}
|
|
6128
6237
|
try {
|
|
@@ -6130,7 +6239,9 @@ var require_bootstrap = __commonJS({
|
|
|
6130
6239
|
const nativeSessionActive = await nativeSessionManager.isSessionActive(decoded.sessionId);
|
|
6131
6240
|
if (!nativeSessionActive) {
|
|
6132
6241
|
setSessionRejectionReason(tokenHashValue, "manual");
|
|
6133
|
-
strapi2.log.info(
|
|
6242
|
+
strapi2.log.info(
|
|
6243
|
+
"[magic-sessionmanager] [JWT-REJECTED] Native session is missing or revoked"
|
|
6244
|
+
);
|
|
6134
6245
|
return null;
|
|
6135
6246
|
}
|
|
6136
6247
|
} catch (err) {
|
|
@@ -6150,7 +6261,10 @@ var require_bootstrap = __commonJS({
|
|
|
6150
6261
|
fields: ["documentId", "expiresAt"]
|
|
6151
6262
|
});
|
|
6152
6263
|
} catch (err) {
|
|
6153
|
-
strapi2.log.error(
|
|
6264
|
+
strapi2.log.error(
|
|
6265
|
+
"[magic-sessionmanager] [JWT] Revocation lookup failed; rejecting token:",
|
|
6266
|
+
err?.name || "Error"
|
|
6267
|
+
);
|
|
6154
6268
|
return null;
|
|
6155
6269
|
}
|
|
6156
6270
|
if (revocation) {
|
|
@@ -6174,7 +6288,9 @@ var require_bootstrap = __commonJS({
|
|
|
6174
6288
|
const userDocId = await resolveUserDocumentId(strapi2, decoded.id);
|
|
6175
6289
|
if (!userDocId) {
|
|
6176
6290
|
if (strictMode) {
|
|
6177
|
-
strapi2.log.warn(
|
|
6291
|
+
strapi2.log.warn(
|
|
6292
|
+
"[magic-sessionmanager] [JWT] User documentId could not be resolved; rejecting in strict mode"
|
|
6293
|
+
);
|
|
6178
6294
|
return null;
|
|
6179
6295
|
}
|
|
6180
6296
|
strapi2.log.debug("[magic-sessionmanager] [JWT] No documentId found in relaxed mode");
|
|
@@ -6188,13 +6304,21 @@ var require_bootstrap = __commonJS({
|
|
|
6188
6304
|
});
|
|
6189
6305
|
} catch (err) {
|
|
6190
6306
|
if (strictMode) {
|
|
6191
|
-
strapi2.log.error(
|
|
6307
|
+
strapi2.log.error(
|
|
6308
|
+
"[magic-sessionmanager] [JWT] User lookup failed in strict mode; rejecting token:",
|
|
6309
|
+
err?.name || "Error"
|
|
6310
|
+
);
|
|
6192
6311
|
return null;
|
|
6193
6312
|
}
|
|
6194
|
-
strapi2.log.debug(
|
|
6313
|
+
strapi2.log.debug(
|
|
6314
|
+
"[magic-sessionmanager] [JWT] User lookup failed in relaxed mode:",
|
|
6315
|
+
err?.name || "Error"
|
|
6316
|
+
);
|
|
6195
6317
|
}
|
|
6196
6318
|
if (!userRecord && strictMode) {
|
|
6197
|
-
strapi2.log.warn(
|
|
6319
|
+
strapi2.log.warn(
|
|
6320
|
+
"[magic-sessionmanager] [JWT] User record could not be resolved; rejecting in strict mode"
|
|
6321
|
+
);
|
|
6198
6322
|
return null;
|
|
6199
6323
|
}
|
|
6200
6324
|
if (userRecord?.blocked === true) {
|
|
@@ -6272,9 +6396,7 @@ var require_bootstrap = __commonJS({
|
|
|
6272
6396
|
documentId: thisSession.documentId,
|
|
6273
6397
|
data: { isActive: true, lastActive: /* @__PURE__ */ new Date() }
|
|
6274
6398
|
});
|
|
6275
|
-
strapi2.log.info(
|
|
6276
|
-
"[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated"
|
|
6277
|
-
);
|
|
6399
|
+
strapi2.log.info("[magic-sessionmanager] [JWT-REACTIVATED] Session reactivated");
|
|
6278
6400
|
resetErrorCounter();
|
|
6279
6401
|
return decoded;
|
|
6280
6402
|
}
|
|
@@ -6302,23 +6424,39 @@ var require_bootstrap = __commonJS({
|
|
|
6302
6424
|
return decoded;
|
|
6303
6425
|
} catch (err) {
|
|
6304
6426
|
if (strictMode) {
|
|
6305
|
-
strapi2.log.error(
|
|
6427
|
+
strapi2.log.error(
|
|
6428
|
+
"[magic-sessionmanager] [JWT] Session check failed in strict mode; rejecting token:",
|
|
6429
|
+
err?.name || "Error"
|
|
6430
|
+
);
|
|
6306
6431
|
return null;
|
|
6307
6432
|
}
|
|
6308
6433
|
if (shouldFailOpen()) {
|
|
6309
|
-
strapi2.log.warn(
|
|
6434
|
+
strapi2.log.warn(
|
|
6435
|
+
"[magic-sessionmanager] [JWT] Session check error (allowing):",
|
|
6436
|
+
err?.name || "Error"
|
|
6437
|
+
);
|
|
6310
6438
|
return decoded;
|
|
6311
6439
|
}
|
|
6312
|
-
strapi2.log.error(
|
|
6440
|
+
strapi2.log.error(
|
|
6441
|
+
"[magic-sessionmanager] [JWT] Too many consecutive errors, blocking request:",
|
|
6442
|
+
err?.name || "Error"
|
|
6443
|
+
);
|
|
6313
6444
|
return null;
|
|
6314
6445
|
}
|
|
6315
6446
|
};
|
|
6316
6447
|
jwtService.verify[JWT_WRAPPED_FLAG] = true;
|
|
6317
6448
|
jwtService[JWT_WRAPPED_FLAG] = true;
|
|
6318
|
-
strapi2.log.info(
|
|
6449
|
+
strapi2.log.info(
|
|
6450
|
+
"[magic-sessionmanager] [AUTH] [SUCCESS] JWT verify wrapped with session validation"
|
|
6451
|
+
);
|
|
6319
6452
|
} catch (err) {
|
|
6320
|
-
strapi2.log.warn(
|
|
6321
|
-
|
|
6453
|
+
strapi2.log.warn(
|
|
6454
|
+
"[magic-sessionmanager] [AUTH] Could not wrap JWT verify:",
|
|
6455
|
+
err?.name || "Error"
|
|
6456
|
+
);
|
|
6457
|
+
strapi2.log.warn(
|
|
6458
|
+
"[magic-sessionmanager] [AUTH] Session validation will only work via middleware (plugin endpoints)"
|
|
6459
|
+
);
|
|
6322
6460
|
}
|
|
6323
6461
|
}
|
|
6324
6462
|
module.exports.__private = {
|
|
@@ -6789,7 +6927,7 @@ var require_admin = __commonJS({
|
|
|
6789
6927
|
handler: "session.toggleUserBlock",
|
|
6790
6928
|
config: {
|
|
6791
6929
|
policies: adminPolicy(),
|
|
6792
|
-
description: "
|
|
6930
|
+
description: "Set an explicit user blocked status (admin)"
|
|
6793
6931
|
}
|
|
6794
6932
|
},
|
|
6795
6933
|
{
|
|
@@ -6949,11 +7087,12 @@ var require_user_agent_parser = __commonJS({
|
|
|
6949
7087
|
osVersion: null
|
|
6950
7088
|
};
|
|
6951
7089
|
}
|
|
6952
|
-
const ua = userAgent.toLowerCase();
|
|
6953
7090
|
let deviceType = "desktop";
|
|
6954
|
-
if (/
|
|
7091
|
+
if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
|
|
7092
|
+
deviceType = "tablet";
|
|
7093
|
+
} else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
|
|
6955
7094
|
deviceType = "mobile";
|
|
6956
|
-
} else if (/
|
|
7095
|
+
} else if (/android(?!.*mobile)/i.test(userAgent)) {
|
|
6957
7096
|
deviceType = "tablet";
|
|
6958
7097
|
} else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
|
|
6959
7098
|
deviceType = "bot";
|
|
@@ -6962,46 +7101,46 @@ var require_user_agent_parser = __commonJS({
|
|
|
6962
7101
|
let browserVersion = null;
|
|
6963
7102
|
if (/edg\//i.test(userAgent)) {
|
|
6964
7103
|
browserName = "Edge";
|
|
6965
|
-
browserVersion = extractVersion(userAgent, /edg\/(\d+[
|
|
7104
|
+
browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
|
|
6966
7105
|
} else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
|
|
6967
7106
|
browserName = "Opera";
|
|
6968
|
-
browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s
|
|
7107
|
+
browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
|
|
6969
7108
|
} else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
|
|
6970
7109
|
browserName = "Chrome";
|
|
6971
|
-
browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[
|
|
7110
|
+
browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
|
|
6972
7111
|
} else if (/firefox|fxios/i.test(userAgent)) {
|
|
6973
7112
|
browserName = "Firefox";
|
|
6974
|
-
browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[
|
|
7113
|
+
browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
|
|
6975
7114
|
} else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
|
|
6976
7115
|
browserName = "Safari";
|
|
6977
|
-
browserVersion = extractVersion(userAgent, /version\/(\d+[
|
|
7116
|
+
browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
|
|
6978
7117
|
} else if (/msie|trident/i.test(userAgent)) {
|
|
6979
7118
|
browserName = "Internet Explorer";
|
|
6980
|
-
browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[
|
|
7119
|
+
browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
|
|
6981
7120
|
}
|
|
6982
7121
|
let osName = "unknown";
|
|
6983
7122
|
let osVersion = null;
|
|
6984
7123
|
if (/windows nt/i.test(userAgent)) {
|
|
6985
7124
|
osName = "Windows";
|
|
6986
|
-
const winVersion = extractVersion(userAgent, /windows nt (\d+[
|
|
7125
|
+
const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
|
|
6987
7126
|
const winVersionMap = {
|
|
6988
7127
|
"10.0": "10/11",
|
|
6989
|
-
|
|
6990
|
-
|
|
6991
|
-
|
|
7128
|
+
6.3: "8.1",
|
|
7129
|
+
6.2: "8",
|
|
7130
|
+
6.1: "7",
|
|
6992
7131
|
"6.0": "Vista",
|
|
6993
|
-
|
|
7132
|
+
5.1: "XP"
|
|
6994
7133
|
};
|
|
6995
7134
|
osVersion = winVersionMap[winVersion] || winVersion;
|
|
6996
|
-
} else if (/mac os x/i.test(userAgent)) {
|
|
6997
|
-
osName = "macOS";
|
|
6998
|
-
osVersion = extractVersion(userAgent, /mac os x (\d+[_\.\d]*)/i)?.replace(/_/g, ".");
|
|
6999
7135
|
} else if (/iphone|ipad|ipod/i.test(userAgent)) {
|
|
7000
7136
|
osName = "iOS";
|
|
7001
|
-
osVersion = extractVersion(userAgent,
|
|
7137
|
+
osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
|
|
7138
|
+
} else if (/mac os x/i.test(userAgent)) {
|
|
7139
|
+
osName = "macOS";
|
|
7140
|
+
osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
|
|
7002
7141
|
} else if (/android/i.test(userAgent)) {
|
|
7003
7142
|
osName = "Android";
|
|
7004
|
-
osVersion = extractVersion(userAgent, /android (\d+[
|
|
7143
|
+
osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
|
|
7005
7144
|
} else if (/linux/i.test(userAgent)) {
|
|
7006
7145
|
osName = "Linux";
|
|
7007
7146
|
} else if (/cros/i.test(userAgent)) {
|
|
@@ -7125,14 +7264,141 @@ var require_enhance_session = __commonJS({
|
|
|
7125
7264
|
async function enhanceSessions(sessions, opts = {}, maxGeoLookups = 20) {
|
|
7126
7265
|
const geoCounter = { remaining: maxGeoLookups };
|
|
7127
7266
|
const now = /* @__PURE__ */ new Date();
|
|
7128
|
-
return Promise.all(
|
|
7129
|
-
sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now }))
|
|
7130
|
-
);
|
|
7267
|
+
return Promise.all(sessions.map((s) => enhanceSession(s, { ...opts, geoCounter, now })));
|
|
7131
7268
|
}
|
|
7132
7269
|
module.exports = { enhanceSession, enhanceSessions, shouldResolveGeoData };
|
|
7133
7270
|
}
|
|
7134
7271
|
});
|
|
7135
7272
|
|
|
7273
|
+
// server/src/utils/native-session-view.js
|
|
7274
|
+
var require_native_session_view = __commonJS({
|
|
7275
|
+
"server/src/utils/native-session-view.js"(exports, module) {
|
|
7276
|
+
"use strict";
|
|
7277
|
+
var NATIVE_SESSION_PREFIX = "native_";
|
|
7278
|
+
function createNativeSessionKey(userDocumentId, nativeSessionId) {
|
|
7279
|
+
if (typeof userDocumentId !== "string" || !userDocumentId || typeof nativeSessionId !== "string" || !nativeSessionId) {
|
|
7280
|
+
throw new TypeError("Native session view keys require an owner documentId and session ID.");
|
|
7281
|
+
}
|
|
7282
|
+
const payload = Buffer.from(JSON.stringify([userDocumentId, nativeSessionId])).toString(
|
|
7283
|
+
"base64url"
|
|
7284
|
+
);
|
|
7285
|
+
if (payload.length > 2048) {
|
|
7286
|
+
throw new RangeError("Native session view key exceeds the supported URL-safe length.");
|
|
7287
|
+
}
|
|
7288
|
+
return `${NATIVE_SESSION_PREFIX}${payload}`;
|
|
7289
|
+
}
|
|
7290
|
+
function parseNativeSessionKey(value) {
|
|
7291
|
+
if (typeof value !== "string" || !value.startsWith(NATIVE_SESSION_PREFIX)) return null;
|
|
7292
|
+
const encoded = value.slice(NATIVE_SESSION_PREFIX.length);
|
|
7293
|
+
if (!encoded || encoded.length > 2048 || !/^[A-Za-z0-9_-]+$/.test(encoded)) return null;
|
|
7294
|
+
try {
|
|
7295
|
+
const decoded = Buffer.from(encoded, "base64url").toString("utf8");
|
|
7296
|
+
if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded) return null;
|
|
7297
|
+
const payload = JSON.parse(decoded);
|
|
7298
|
+
if (!Array.isArray(payload) || payload.length !== 2 || typeof payload[0] !== "string" || !payload[0] || typeof payload[1] !== "string" || !payload[1]) {
|
|
7299
|
+
return null;
|
|
7300
|
+
}
|
|
7301
|
+
return {
|
|
7302
|
+
userDocumentId: payload[0],
|
|
7303
|
+
nativeSessionId: payload[1]
|
|
7304
|
+
};
|
|
7305
|
+
} catch {
|
|
7306
|
+
return null;
|
|
7307
|
+
}
|
|
7308
|
+
}
|
|
7309
|
+
function mapNativeSessionToView(session, user) {
|
|
7310
|
+
const nativeId = String(session.sessionId);
|
|
7311
|
+
const stableId = createNativeSessionKey(String(user.documentId), nativeId);
|
|
7312
|
+
const metadata = session.metadata && typeof session.metadata === "object" ? session.metadata : {};
|
|
7313
|
+
const loginAt = typeof metadata.loginAt === "string" && !Number.isNaN(Date.parse(metadata.loginAt)) ? new Date(metadata.loginAt) : null;
|
|
7314
|
+
const createdAt = session.createdAt && !Number.isNaN(new Date(session.createdAt).getTime()) ? new Date(session.createdAt) : null;
|
|
7315
|
+
const userView = {
|
|
7316
|
+
documentId: user.documentId,
|
|
7317
|
+
email: user.email,
|
|
7318
|
+
username: user.username
|
|
7319
|
+
};
|
|
7320
|
+
return {
|
|
7321
|
+
documentId: stableId,
|
|
7322
|
+
id: stableId,
|
|
7323
|
+
sessionId: stableId,
|
|
7324
|
+
nativeSessionId: nativeId,
|
|
7325
|
+
user: userView,
|
|
7326
|
+
ipAddress: null,
|
|
7327
|
+
userAgent: null,
|
|
7328
|
+
loginTime: loginAt || createdAt,
|
|
7329
|
+
logoutTime: null,
|
|
7330
|
+
lastActive: createdAt || loginAt,
|
|
7331
|
+
isActive: true,
|
|
7332
|
+
terminatedManually: false,
|
|
7333
|
+
geoLocation: null,
|
|
7334
|
+
securityScore: null,
|
|
7335
|
+
deviceType: null,
|
|
7336
|
+
deviceName: typeof metadata.deviceName === "string" ? metadata.deviceName : void 0,
|
|
7337
|
+
browserName: null,
|
|
7338
|
+
osName: null
|
|
7339
|
+
};
|
|
7340
|
+
}
|
|
7341
|
+
function markSessionsTruncated(sessions, truncated) {
|
|
7342
|
+
Object.defineProperty(sessions, "truncated", {
|
|
7343
|
+
value: Boolean(truncated),
|
|
7344
|
+
enumerable: false,
|
|
7345
|
+
configurable: false,
|
|
7346
|
+
writable: false
|
|
7347
|
+
});
|
|
7348
|
+
return sessions;
|
|
7349
|
+
}
|
|
7350
|
+
module.exports = {
|
|
7351
|
+
NATIVE_SESSION_PREFIX,
|
|
7352
|
+
createNativeSessionKey,
|
|
7353
|
+
parseNativeSessionKey,
|
|
7354
|
+
mapNativeSessionToView,
|
|
7355
|
+
markSessionsTruncated
|
|
7356
|
+
};
|
|
7357
|
+
}
|
|
7358
|
+
});
|
|
7359
|
+
|
|
7360
|
+
// server/src/utils/http-errors.js
|
|
7361
|
+
var require_http_errors = __commonJS({
|
|
7362
|
+
"server/src/utils/http-errors.js"(exports, module) {
|
|
7363
|
+
"use strict";
|
|
7364
|
+
var SERVER_ERROR_METHODS = {
|
|
7365
|
+
500: "internalServerError",
|
|
7366
|
+
502: "badGateway",
|
|
7367
|
+
503: "serviceUnavailable"
|
|
7368
|
+
};
|
|
7369
|
+
var SERVER_ERROR_NAMES = {
|
|
7370
|
+
500: "InternalServerError",
|
|
7371
|
+
502: "BadGatewayError",
|
|
7372
|
+
503: "ServiceUnavailableError"
|
|
7373
|
+
};
|
|
7374
|
+
function sendServerError(ctx, status, message, details) {
|
|
7375
|
+
const method = SERVER_ERROR_METHODS[status] || SERVER_ERROR_METHODS[500];
|
|
7376
|
+
if (typeof ctx[method] === "function") return ctx[method](message, details || {});
|
|
7377
|
+
if (status === 500 && typeof ctx.internalServerError === "function") {
|
|
7378
|
+
return ctx.internalServerError(message, details || {});
|
|
7379
|
+
}
|
|
7380
|
+
const finalStatus = SERVER_ERROR_METHODS[status] ? status : 500;
|
|
7381
|
+
ctx.status = finalStatus;
|
|
7382
|
+
ctx.body = {
|
|
7383
|
+
data: null,
|
|
7384
|
+
error: {
|
|
7385
|
+
status: finalStatus,
|
|
7386
|
+
name: SERVER_ERROR_NAMES[finalStatus],
|
|
7387
|
+
message,
|
|
7388
|
+
details: details || {}
|
|
7389
|
+
}
|
|
7390
|
+
};
|
|
7391
|
+
return ctx.body;
|
|
7392
|
+
}
|
|
7393
|
+
function sendValidationError(ctx, message, errors) {
|
|
7394
|
+
return ctx.badRequest(message, {
|
|
7395
|
+
errors: errors.map((error) => ({ ...error, name: "ValidationError" }))
|
|
7396
|
+
});
|
|
7397
|
+
}
|
|
7398
|
+
module.exports = { sendServerError, sendValidationError };
|
|
7399
|
+
}
|
|
7400
|
+
});
|
|
7401
|
+
|
|
7136
7402
|
// server/src/controllers/session.js
|
|
7137
7403
|
var require_session = __commonJS({
|
|
7138
7404
|
"server/src/controllers/session.js"(exports, module) {
|
|
@@ -7144,11 +7410,11 @@ var require_session = __commonJS({
|
|
|
7144
7410
|
shouldResolveGeoData
|
|
7145
7411
|
} = require_enhance_session();
|
|
7146
7412
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
7147
|
-
var {
|
|
7148
|
-
getPluginSettings,
|
|
7149
|
-
getSessionCreationGraceMs
|
|
7150
|
-
} = require_settings_loader();
|
|
7413
|
+
var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
|
|
7151
7414
|
var { extractBearerToken } = require_extract_token();
|
|
7415
|
+
var { parseNativeSessionKey } = require_native_session_view();
|
|
7416
|
+
var { runWithCallerRevocation } = require_block_revocation_scope();
|
|
7417
|
+
var { sendServerError } = require_http_errors();
|
|
7152
7418
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
7153
7419
|
var USER_UID = "plugin::users-permissions.user";
|
|
7154
7420
|
var OWN_SESSIONS_LIMIT = 200;
|
|
@@ -7193,6 +7459,23 @@ var require_session = __commonJS({
|
|
|
7193
7459
|
const value = ctx?.state?.session?.id ?? ctx?.state?.auth?.credentials?.sessionId;
|
|
7194
7460
|
return typeof value === "string" && value.length > 0 ? value : null;
|
|
7195
7461
|
}
|
|
7462
|
+
var PRIVATE_SESSION_FIELDS = [
|
|
7463
|
+
"token",
|
|
7464
|
+
"tokenHash",
|
|
7465
|
+
"refreshToken",
|
|
7466
|
+
"refreshTokenHash",
|
|
7467
|
+
"nativeSessionId"
|
|
7468
|
+
];
|
|
7469
|
+
function toPublicSession(session, { admin = false } = {}) {
|
|
7470
|
+
if (!session || typeof session !== "object") return session;
|
|
7471
|
+
const safe = { ...session };
|
|
7472
|
+
for (const field of PRIVATE_SESSION_FIELDS) delete safe[field];
|
|
7473
|
+
if (admin) delete safe.sessionId;
|
|
7474
|
+
return safe;
|
|
7475
|
+
}
|
|
7476
|
+
function toPublicSessions(sessions, options) {
|
|
7477
|
+
return Array.isArray(sessions) ? sessions.map((session) => toPublicSession(session, options)) : sessions;
|
|
7478
|
+
}
|
|
7196
7479
|
function getSessionViewKey(session) {
|
|
7197
7480
|
const key = session?.documentId ?? session?.id ?? session?.sessionId;
|
|
7198
7481
|
return key === void 0 || key === null ? null : String(key);
|
|
@@ -7251,10 +7534,7 @@ var require_session = __commonJS({
|
|
|
7251
7534
|
data: { totalUsers, blockedUsers }
|
|
7252
7535
|
});
|
|
7253
7536
|
} catch (error) {
|
|
7254
|
-
strapi.log.error(
|
|
7255
|
-
"[magic-sessionmanager] getUserStatsAdmin failed:",
|
|
7256
|
-
error?.name || "Error"
|
|
7257
|
-
);
|
|
7537
|
+
strapi.log.error("[magic-sessionmanager] getUserStatsAdmin failed:", error?.name || "Error");
|
|
7258
7538
|
return ctx.internalServerError("Unable to load end-user counts");
|
|
7259
7539
|
}
|
|
7260
7540
|
},
|
|
@@ -7267,7 +7547,7 @@ var require_session = __commonJS({
|
|
|
7267
7547
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
7268
7548
|
const sessions = await sessionService.getAllSessions();
|
|
7269
7549
|
ctx.body = {
|
|
7270
|
-
data: sessions,
|
|
7550
|
+
data: toPublicSessions(sessions, { admin: true }),
|
|
7271
7551
|
meta: {
|
|
7272
7552
|
count: sessions.length,
|
|
7273
7553
|
active: sessions.filter((s) => s.isTrulyActive).length,
|
|
@@ -7289,7 +7569,7 @@ var require_session = __commonJS({
|
|
|
7289
7569
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
7290
7570
|
const sessions = await sessionService.getActiveSessions();
|
|
7291
7571
|
ctx.body = {
|
|
7292
|
-
data: sessions,
|
|
7572
|
+
data: toPublicSessions(sessions, { admin: true }),
|
|
7293
7573
|
meta: { count: sessions.length, ...getTruncationMeta(sessions) }
|
|
7294
7574
|
};
|
|
7295
7575
|
} catch (err) {
|
|
@@ -7329,7 +7609,7 @@ var require_session = __commonJS({
|
|
|
7329
7609
|
return new Date(b.loginTime || 0) - new Date(a.loginTime || 0);
|
|
7330
7610
|
});
|
|
7331
7611
|
ctx.body = {
|
|
7332
|
-
data: sessionsWithCurrent2,
|
|
7612
|
+
data: toPublicSessions(sessionsWithCurrent2),
|
|
7333
7613
|
meta: {
|
|
7334
7614
|
count: sessionsWithCurrent2.length,
|
|
7335
7615
|
active: sessionsWithCurrent2.filter((session) => session.isTrulyActive).length,
|
|
@@ -7357,9 +7637,7 @@ var require_session = __commonJS({
|
|
|
7357
7637
|
};
|
|
7358
7638
|
const sessionsWithCurrent = await enhanceSessions(paged, enhanceOpts, 20);
|
|
7359
7639
|
for (const s of sessionsWithCurrent) {
|
|
7360
|
-
s.isCurrentSession = !!(currentTokenHash && paged.find(
|
|
7361
|
-
(raw) => raw.documentId === s.documentId && raw.tokenHash === currentTokenHash
|
|
7362
|
-
));
|
|
7640
|
+
s.isCurrentSession = !!(currentTokenHash && paged.find((raw) => raw.documentId === s.documentId && raw.tokenHash === currentTokenHash));
|
|
7363
7641
|
}
|
|
7364
7642
|
sessionsWithCurrent.sort((a, b) => {
|
|
7365
7643
|
if (a.isCurrentSession) return -1;
|
|
@@ -7367,7 +7645,7 @@ var require_session = __commonJS({
|
|
|
7367
7645
|
return new Date(b.loginTime) - new Date(a.loginTime);
|
|
7368
7646
|
});
|
|
7369
7647
|
ctx.body = {
|
|
7370
|
-
data: sessionsWithCurrent,
|
|
7648
|
+
data: toPublicSessions(sessionsWithCurrent),
|
|
7371
7649
|
meta: {
|
|
7372
7650
|
count: sessionsWithCurrent.length,
|
|
7373
7651
|
active: sessionsWithCurrent.filter((s) => s.isTrulyActive).length,
|
|
@@ -7391,7 +7669,9 @@ var require_session = __commonJS({
|
|
|
7391
7669
|
const requestingUserDocId = await resolveAuthUserDocId(ctx);
|
|
7392
7670
|
if (!isAdminRequest) {
|
|
7393
7671
|
if (!requestingUserDocId) {
|
|
7394
|
-
strapi.log.warn(
|
|
7672
|
+
strapi.log.warn(
|
|
7673
|
+
"[magic-sessionmanager] Denied a session lookup without a verifiable user identity"
|
|
7674
|
+
);
|
|
7395
7675
|
return ctx.forbidden("Cannot verify user identity");
|
|
7396
7676
|
}
|
|
7397
7677
|
const requestedDocId = await resolveUserDocumentId(strapi, userId);
|
|
@@ -7405,7 +7685,7 @@ var require_session = __commonJS({
|
|
|
7405
7685
|
if (!serviceUserId) return ctx.forbidden("Cannot verify user identity");
|
|
7406
7686
|
const sessions = await sessionService.getUserSessions(serviceUserId);
|
|
7407
7687
|
ctx.body = {
|
|
7408
|
-
data: sessions,
|
|
7688
|
+
data: toPublicSessions(sessions, { admin: isAdminRequest }),
|
|
7409
7689
|
meta: { count: sessions.length, ...getTruncationMeta(sessions) }
|
|
7410
7690
|
};
|
|
7411
7691
|
} catch (err) {
|
|
@@ -7682,7 +7962,10 @@ var require_session = __commonJS({
|
|
|
7682
7962
|
data: { ...enhanced, isCurrentSession: true }
|
|
7683
7963
|
};
|
|
7684
7964
|
} catch (err) {
|
|
7685
|
-
strapi.log.error(
|
|
7965
|
+
strapi.log.error(
|
|
7966
|
+
"[magic-sessionmanager] Error getting current session:",
|
|
7967
|
+
err?.name || "Error"
|
|
7968
|
+
);
|
|
7686
7969
|
return ctx.internalServerError("Error fetching current session");
|
|
7687
7970
|
}
|
|
7688
7971
|
},
|
|
@@ -7747,10 +8030,12 @@ var require_session = __commonJS({
|
|
|
7747
8030
|
}
|
|
7748
8031
|
const sessionUserId = sessionToTerminate.user?.documentId;
|
|
7749
8032
|
if (sessionUserId !== userDocId) {
|
|
7750
|
-
strapi.log.warn(
|
|
7751
|
-
|
|
8033
|
+
strapi.log.warn(
|
|
8034
|
+
"[magic-sessionmanager] Denied an attempt to terminate another user session"
|
|
8035
|
+
);
|
|
8036
|
+
return ctx.notFound("Session not found");
|
|
7752
8037
|
}
|
|
7753
|
-
if (currentTokenHash && sessionToTerminate.tokenHash === currentTokenHash) {
|
|
8038
|
+
if (isNativeSessionMode() && isCurrentNativeSession(sessionToTerminate, getCurrentNativeSessionId(ctx)) || currentTokenHash && sessionToTerminate.tokenHash === currentTokenHash) {
|
|
7754
8039
|
return ctx.badRequest("Cannot terminate the current session. Use /logout instead.");
|
|
7755
8040
|
}
|
|
7756
8041
|
const alreadyTerminated = sessionToTerminate.isActive === false;
|
|
@@ -7764,7 +8049,10 @@ var require_session = __commonJS({
|
|
|
7764
8049
|
alreadyTerminated
|
|
7765
8050
|
};
|
|
7766
8051
|
} catch (err) {
|
|
7767
|
-
strapi.log.error(
|
|
8052
|
+
strapi.log.error(
|
|
8053
|
+
"[magic-sessionmanager] Error terminating own session:",
|
|
8054
|
+
err?.name || "Error"
|
|
8055
|
+
);
|
|
7768
8056
|
return ctx.internalServerError("Error terminating session");
|
|
7769
8057
|
}
|
|
7770
8058
|
},
|
|
@@ -7806,12 +8094,23 @@ var require_session = __commonJS({
|
|
|
7806
8094
|
},
|
|
7807
8095
|
/**
|
|
7808
8096
|
* Terminates a specific session (admin action).
|
|
8097
|
+
* A missing target returns 404; existing native-only rows remain supported.
|
|
7809
8098
|
*/
|
|
7810
8099
|
async terminateSingleSession(ctx) {
|
|
7811
8100
|
try {
|
|
7812
8101
|
const { sessionId } = ctx.params;
|
|
7813
8102
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
7814
|
-
|
|
8103
|
+
let nativeTargetExists = false;
|
|
8104
|
+
if (isNativeSessionMode() && sessionId?.startsWith(NATIVE_SESSION_KEY_PREFIX)) {
|
|
8105
|
+
const nativeKey = parseNativeSessionKey(sessionId);
|
|
8106
|
+
if (!nativeKey) return ctx.notFound("Session not found");
|
|
8107
|
+
const sessions = await sessionService.getUserSessions(nativeKey.userDocumentId);
|
|
8108
|
+
nativeTargetExists = !!findOwnedNativeSession(sessions, sessionId);
|
|
8109
|
+
if (!nativeTargetExists) return ctx.notFound("Session not found");
|
|
8110
|
+
}
|
|
8111
|
+
const result = await sessionService.terminateSession({ sessionId, reason: "manual" });
|
|
8112
|
+
if (!nativeTargetExists && result?.terminatedCount === 0)
|
|
8113
|
+
return ctx.notFound("Session not found");
|
|
7815
8114
|
ctx.body = {
|
|
7816
8115
|
message: `Session ${sessionId} terminated`,
|
|
7817
8116
|
success: true
|
|
@@ -7823,10 +8122,17 @@ var require_session = __commonJS({
|
|
|
7823
8122
|
},
|
|
7824
8123
|
/**
|
|
7825
8124
|
* Terminates ALL sessions for a specific user (admin action).
|
|
8125
|
+
* Unknown numeric IDs and document IDs return 404 before revocation.
|
|
7826
8126
|
*/
|
|
7827
8127
|
async terminateAllUserSessions(ctx) {
|
|
7828
8128
|
try {
|
|
7829
8129
|
const { userId } = ctx.params;
|
|
8130
|
+
const numericId = /^\d+$/.test(userId) ? Number(userId) : null;
|
|
8131
|
+
const user = await strapi.db.query(USER_UID).findOne({
|
|
8132
|
+
where: numericId === null ? { documentId: userId } : { id: numericId },
|
|
8133
|
+
select: ["id"]
|
|
8134
|
+
});
|
|
8135
|
+
if (!user) return ctx.notFound("User not found");
|
|
7830
8136
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
7831
8137
|
await sessionService.terminateSession({ userId, reason: "manual" });
|
|
7832
8138
|
ctx.body = {
|
|
@@ -7834,7 +8140,10 @@ var require_session = __commonJS({
|
|
|
7834
8140
|
success: true
|
|
7835
8141
|
};
|
|
7836
8142
|
} catch (err) {
|
|
7837
|
-
strapi.log.error(
|
|
8143
|
+
strapi.log.error(
|
|
8144
|
+
"[magic-sessionmanager] Error terminating all user sessions:",
|
|
8145
|
+
err?.name || "Error"
|
|
8146
|
+
);
|
|
7838
8147
|
return ctx.internalServerError("Error terminating all user sessions");
|
|
7839
8148
|
}
|
|
7840
8149
|
},
|
|
@@ -7883,7 +8192,10 @@ var require_session = __commonJS({
|
|
|
7883
8192
|
data: ipData
|
|
7884
8193
|
};
|
|
7885
8194
|
} catch (err) {
|
|
7886
|
-
strapi.log.error(
|
|
8195
|
+
strapi.log.error(
|
|
8196
|
+
"[magic-sessionmanager] Error getting IP geolocation:",
|
|
8197
|
+
err?.name || "Error"
|
|
8198
|
+
);
|
|
7887
8199
|
return ctx.internalServerError("Error fetching IP geolocation data");
|
|
7888
8200
|
}
|
|
7889
8201
|
},
|
|
@@ -7915,6 +8227,9 @@ var require_session = __commonJS({
|
|
|
7915
8227
|
* @route POST /magic-sessionmanager/sessions/clean-inactive
|
|
7916
8228
|
* @sideeffect Deletes inactive session rows and retains token deny records
|
|
7917
8229
|
* until expiry
|
|
8230
|
+
* @returns {Promise<void>} 200 with `deletedCount`, or 500 whose
|
|
8231
|
+
* `error.details` carries `deletedCount` and `failedCount` when some rows
|
|
8232
|
+
* could not be removed
|
|
7918
8233
|
*/
|
|
7919
8234
|
async cleanInactiveSessions(ctx) {
|
|
7920
8235
|
try {
|
|
@@ -7926,16 +8241,51 @@ var require_session = __commonJS({
|
|
|
7926
8241
|
deletedCount
|
|
7927
8242
|
};
|
|
7928
8243
|
} catch (err) {
|
|
7929
|
-
|
|
8244
|
+
if (err?.name === "PartialCleanupError") {
|
|
8245
|
+
strapi.log.warn("[magic-sessionmanager] Inactive session cleanup finished partially");
|
|
8246
|
+
return sendServerError(ctx, 500, "Some inactive session records could not be removed", {
|
|
8247
|
+
deletedCount: Number(err.deletedCount) || 0,
|
|
8248
|
+
failedCount: Number(err.failedCount) || 0
|
|
8249
|
+
});
|
|
8250
|
+
}
|
|
8251
|
+
strapi.log.error(
|
|
8252
|
+
"[magic-sessionmanager] Error cleaning inactive sessions:",
|
|
8253
|
+
err?.name || "Error"
|
|
8254
|
+
);
|
|
7930
8255
|
return ctx.internalServerError("Error deleting inactive sessions");
|
|
7931
8256
|
}
|
|
7932
8257
|
},
|
|
7933
8258
|
/**
|
|
7934
|
-
*
|
|
8259
|
+
* Sets or toggles an end user's blocked state.
|
|
8260
|
+
*
|
|
8261
|
+
* - `{ blocked: true | false }` sets that state (retry-safe, used by the
|
|
8262
|
+
* admin UI). A repeated block also retries session revocation, including
|
|
8263
|
+
* after an earlier partial failure.
|
|
8264
|
+
* - A request without `blocked` keeps the pre-4.9 behaviour and toggles the
|
|
8265
|
+
* stored state. It is deprecated because a retried toggle can undo itself.
|
|
8266
|
+
* - A `blocked` value that is present but not a boolean is rejected with 400
|
|
8267
|
+
* before any mutation.
|
|
8268
|
+
*
|
|
8269
|
+
* The response keeps `message`, `blocked` and `success`; `mode`
|
|
8270
|
+
* (`'explicit' | 'toggle'`) is additive.
|
|
8271
|
+
*
|
|
8272
|
+
* Requires an authenticated administrator with the plugin access permission.
|
|
8273
|
+
* @route POST /magic-sessionmanager/user/:userId/toggle-block
|
|
8274
|
+
* @param {object} ctx - Strapi context; optional body.blocked boolean.
|
|
8275
|
+
* @returns {Promise<void>} Writes the resulting state or a 400, 404 or 500 response.
|
|
8276
|
+
* @sideeffect Updates the user and, when blocking, revokes their sessions
|
|
8277
|
+
* exactly once (the user lifecycle skips this update). A failed revocation
|
|
8278
|
+
* can leave the user blocked with partially active sessions.
|
|
7935
8279
|
*/
|
|
7936
8280
|
async toggleUserBlock(ctx) {
|
|
7937
8281
|
try {
|
|
7938
8282
|
const { userId } = ctx.params;
|
|
8283
|
+
const body = ctx.request?.body;
|
|
8284
|
+
const hasRequestedState = body !== null && typeof body === "object" && Object.prototype.hasOwnProperty.call(body, "blocked") && body.blocked !== void 0;
|
|
8285
|
+
const requestedBlocked = hasRequestedState ? body.blocked : void 0;
|
|
8286
|
+
if (hasRequestedState && typeof requestedBlocked !== "boolean") {
|
|
8287
|
+
return ctx.badRequest("A boolean blocked state is required");
|
|
8288
|
+
}
|
|
7939
8289
|
let userDocumentId = await resolveUserDocumentId(strapi, userId);
|
|
7940
8290
|
if (!userDocumentId) {
|
|
7941
8291
|
try {
|
|
@@ -7953,11 +8303,15 @@ var require_session = __commonJS({
|
|
|
7953
8303
|
if (!user) {
|
|
7954
8304
|
return ctx.notFound("User not found");
|
|
7955
8305
|
}
|
|
7956
|
-
const
|
|
7957
|
-
|
|
7958
|
-
|
|
7959
|
-
|
|
7960
|
-
|
|
8306
|
+
const mode = hasRequestedState ? "explicit" : "toggle";
|
|
8307
|
+
const newBlockedStatus = hasRequestedState ? requestedBlocked : !user.blocked;
|
|
8308
|
+
await runWithCallerRevocation(
|
|
8309
|
+
userDocumentId,
|
|
8310
|
+
() => strapi.documents(USER_UID).update({
|
|
8311
|
+
documentId: userDocumentId,
|
|
8312
|
+
data: { blocked: newBlockedStatus }
|
|
8313
|
+
})
|
|
8314
|
+
);
|
|
7961
8315
|
if (newBlockedStatus) {
|
|
7962
8316
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
7963
8317
|
await sessionService.terminateSession({ userId: userDocumentId, reason: "blocked" });
|
|
@@ -7965,7 +8319,8 @@ var require_session = __commonJS({
|
|
|
7965
8319
|
ctx.body = {
|
|
7966
8320
|
message: `User ${newBlockedStatus ? "blocked" : "unblocked"} successfully`,
|
|
7967
8321
|
blocked: newBlockedStatus,
|
|
7968
|
-
success: true
|
|
8322
|
+
success: true,
|
|
8323
|
+
mode
|
|
7969
8324
|
};
|
|
7970
8325
|
} catch (err) {
|
|
7971
8326
|
strapi.log.error("[magic-sessionmanager] Error toggling user block:", err?.name || "Error");
|
|
@@ -7980,6 +8335,9 @@ var require_session = __commonJS({
|
|
|
7980
8335
|
var require_license = __commonJS({
|
|
7981
8336
|
"server/src/controllers/license.js"(exports, module) {
|
|
7982
8337
|
"use strict";
|
|
8338
|
+
var { sendServerError } = require_http_errors();
|
|
8339
|
+
var PROVIDER_UNREACHABLE_MESSAGE = "License server unreachable. The plugin keeps working without a key.";
|
|
8340
|
+
var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
7983
8341
|
module.exports = ({ strapi: strapi2 }) => ({
|
|
7984
8342
|
async getStatus(ctx) {
|
|
7985
8343
|
try {
|
|
@@ -8033,8 +8391,11 @@ var require_license = __commonJS({
|
|
|
8033
8391
|
}
|
|
8034
8392
|
});
|
|
8035
8393
|
} catch (error) {
|
|
8036
|
-
strapi2.log.error(
|
|
8037
|
-
|
|
8394
|
+
strapi2.log.error(
|
|
8395
|
+
"[magic-sessionmanager] Error getting license status:",
|
|
8396
|
+
error?.name || "Error"
|
|
8397
|
+
);
|
|
8398
|
+
return sendServerError(ctx, 500, "Error getting license status");
|
|
8038
8399
|
}
|
|
8039
8400
|
},
|
|
8040
8401
|
async autoCreate(ctx) {
|
|
@@ -8050,7 +8411,7 @@ var require_license = __commonJS({
|
|
|
8050
8411
|
lastName: adminUser.lastname || "User"
|
|
8051
8412
|
});
|
|
8052
8413
|
if (!license) {
|
|
8053
|
-
return ctx
|
|
8414
|
+
return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
|
|
8054
8415
|
}
|
|
8055
8416
|
await licenseGuard.storeLicenseKey(license.licenseKey);
|
|
8056
8417
|
return ctx.send({
|
|
@@ -8059,20 +8420,23 @@ var require_license = __commonJS({
|
|
|
8059
8420
|
data: license
|
|
8060
8421
|
});
|
|
8061
8422
|
} catch (error) {
|
|
8062
|
-
strapi2.log.error(
|
|
8063
|
-
|
|
8423
|
+
strapi2.log.error(
|
|
8424
|
+
"[magic-sessionmanager] Error auto-creating license:",
|
|
8425
|
+
error?.name || "Error"
|
|
8426
|
+
);
|
|
8427
|
+
return sendServerError(ctx, 500, "Error creating license");
|
|
8064
8428
|
}
|
|
8065
8429
|
},
|
|
8066
8430
|
async createAndActivate(ctx) {
|
|
8067
8431
|
try {
|
|
8068
8432
|
const { email, firstName, lastName } = ctx.request.body || {};
|
|
8069
|
-
if (!email
|
|
8433
|
+
if (![email, firstName, lastName].every((value) => typeof value === "string" && value.trim())) {
|
|
8070
8434
|
return ctx.badRequest("Email, firstName, and lastName are required");
|
|
8071
8435
|
}
|
|
8072
8436
|
const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
|
|
8073
8437
|
const license = await licenseGuard.createLicense({ email, firstName, lastName });
|
|
8074
8438
|
if (!license) {
|
|
8075
|
-
return ctx
|
|
8439
|
+
return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
|
|
8076
8440
|
}
|
|
8077
8441
|
await licenseGuard.storeLicenseKey(license.licenseKey);
|
|
8078
8442
|
return ctx.send({
|
|
@@ -8082,7 +8446,7 @@ var require_license = __commonJS({
|
|
|
8082
8446
|
});
|
|
8083
8447
|
} catch (error) {
|
|
8084
8448
|
strapi2.log.error("[magic-sessionmanager] Error creating license:", error?.name || "Error");
|
|
8085
|
-
return ctx
|
|
8449
|
+
return sendServerError(ctx, 500, "Error creating license");
|
|
8086
8450
|
}
|
|
8087
8451
|
},
|
|
8088
8452
|
async ping(ctx) {
|
|
@@ -8101,17 +8465,22 @@ var require_license = __commonJS({
|
|
|
8101
8465
|
});
|
|
8102
8466
|
} catch (error) {
|
|
8103
8467
|
strapi2.log.error("[magic-sessionmanager] Error refreshing license:", error?.name || "Error");
|
|
8104
|
-
return ctx
|
|
8468
|
+
return sendServerError(ctx, 500, "Error refreshing license");
|
|
8105
8469
|
}
|
|
8106
8470
|
},
|
|
8107
8471
|
async storeKey(ctx) {
|
|
8108
8472
|
try {
|
|
8109
8473
|
const { licenseKey, email } = ctx.request.body || {};
|
|
8110
|
-
if (
|
|
8474
|
+
if (typeof licenseKey !== "string" || !licenseKey.trim()) {
|
|
8111
8475
|
return ctx.badRequest("License key is required");
|
|
8112
8476
|
}
|
|
8477
|
+
if (email !== void 0 && email !== null && email !== "") {
|
|
8478
|
+
if (typeof email !== "string" || !EMAIL_PATTERN.test(email.trim())) {
|
|
8479
|
+
return ctx.badRequest("Email must be a valid email address");
|
|
8480
|
+
}
|
|
8481
|
+
}
|
|
8113
8482
|
const trimmedKey = licenseKey.trim();
|
|
8114
|
-
const trimmedEmail = email
|
|
8483
|
+
const trimmedEmail = typeof email === "string" && email.trim() ? email.trim().toLowerCase() : null;
|
|
8115
8484
|
const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
|
|
8116
8485
|
const verification = await licenseGuard.verifyLicense(trimmedKey);
|
|
8117
8486
|
if (!verification.valid && !verification.networkError) {
|
|
@@ -8131,7 +8500,7 @@ var require_license = __commonJS({
|
|
|
8131
8500
|
});
|
|
8132
8501
|
} catch (error) {
|
|
8133
8502
|
strapi2.log.error("[magic-sessionmanager] Error storing license key:", error?.name || "Error");
|
|
8134
|
-
return ctx
|
|
8503
|
+
return sendServerError(ctx, 500, "Error validating license key");
|
|
8135
8504
|
}
|
|
8136
8505
|
}
|
|
8137
8506
|
});
|
|
@@ -8151,7 +8520,12 @@ var require_geoip_updater = __commonJS({
|
|
|
8151
8520
|
var gunzip = promisify(zlib.gunzip);
|
|
8152
8521
|
var DEFAULT_EDITION_ID = "GeoLite2-City";
|
|
8153
8522
|
var DEFAULT_MMDB_NAME = `${DEFAULT_EDITION_ID}.mmdb`;
|
|
8154
|
-
var DEFAULT_GEOIP_DIRECTORY = path.resolve(
|
|
8523
|
+
var DEFAULT_GEOIP_DIRECTORY = path.resolve(
|
|
8524
|
+
process2.cwd(),
|
|
8525
|
+
"data",
|
|
8526
|
+
"magic-sessionmanager",
|
|
8527
|
+
"geoip"
|
|
8528
|
+
);
|
|
8155
8529
|
var DEFAULT_OUTPUT_PATH = path.join(DEFAULT_GEOIP_DIRECTORY, DEFAULT_MMDB_NAME);
|
|
8156
8530
|
var SUPPORTED_EDITION_IDS = /* @__PURE__ */ new Set([
|
|
8157
8531
|
"GeoLite2-City",
|
|
@@ -8159,7 +8533,9 @@ var require_geoip_updater = __commonJS({
|
|
|
8159
8533
|
"GeoIP2-City",
|
|
8160
8534
|
"GeoIP2-Country"
|
|
8161
8535
|
]);
|
|
8162
|
-
var SUPPORTED_MMDB_NAMES = new Set(
|
|
8536
|
+
var SUPPORTED_MMDB_NAMES = new Set(
|
|
8537
|
+
[...SUPPORTED_EDITION_IDS].map((editionId) => `${editionId}.mmdb`)
|
|
8538
|
+
);
|
|
8163
8539
|
function resolveDatabaseTarget(value, directory = DEFAULT_GEOIP_DIRECTORY) {
|
|
8164
8540
|
const root = path.resolve(directory);
|
|
8165
8541
|
if (value !== void 0 && typeof value !== "string") {
|
|
@@ -8252,12 +8628,7 @@ var require_geoip_updater = __commonJS({
|
|
|
8252
8628
|
force
|
|
8253
8629
|
};
|
|
8254
8630
|
}
|
|
8255
|
-
function needsDownload({
|
|
8256
|
-
force,
|
|
8257
|
-
localExists,
|
|
8258
|
-
localMetadata,
|
|
8259
|
-
remoteLastModified
|
|
8260
|
-
}) {
|
|
8631
|
+
function needsDownload({ force, localExists, localMetadata, remoteLastModified }) {
|
|
8261
8632
|
if (force) return true;
|
|
8262
8633
|
if (!localExists) return true;
|
|
8263
8634
|
if (!remoteLastModified) return true;
|
|
@@ -8406,13 +8777,20 @@ var require_geoip_updater = __commonJS({
|
|
|
8406
8777
|
const archive = await fetchArchive(url, authHeader);
|
|
8407
8778
|
const extracted = await extractMmdbFromTarGz(archive, mmdbFileName);
|
|
8408
8779
|
await writeAtomic(outputPath, extracted.data);
|
|
8409
|
-
await writeAtomic(
|
|
8410
|
-
|
|
8411
|
-
|
|
8412
|
-
|
|
8413
|
-
|
|
8414
|
-
|
|
8415
|
-
|
|
8780
|
+
await writeAtomic(
|
|
8781
|
+
metadataPath,
|
|
8782
|
+
JSON.stringify(
|
|
8783
|
+
{
|
|
8784
|
+
editionId,
|
|
8785
|
+
sourceFile: extracted.name,
|
|
8786
|
+
lastModified: head.lastModified,
|
|
8787
|
+
downloadedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8788
|
+
sourceUrl: url
|
|
8789
|
+
},
|
|
8790
|
+
null,
|
|
8791
|
+
2
|
|
8792
|
+
)
|
|
8793
|
+
);
|
|
8416
8794
|
return {
|
|
8417
8795
|
changed: true,
|
|
8418
8796
|
outputPath,
|
|
@@ -8446,13 +8824,12 @@ var require_settings = __commonJS({
|
|
|
8446
8824
|
"server/src/controllers/settings.js"(exports, module) {
|
|
8447
8825
|
"use strict";
|
|
8448
8826
|
var {
|
|
8449
|
-
getSessionCreationGraceMs,
|
|
8450
8827
|
invalidateSettingsCache,
|
|
8451
8828
|
normalizeGeoIpProvider,
|
|
8452
|
-
normalizeGeoLookupFailureMode
|
|
8453
|
-
normalizeRetentionDays
|
|
8829
|
+
normalizeGeoLookupFailureMode
|
|
8454
8830
|
} = require_settings_loader();
|
|
8455
8831
|
var { resolveDatabaseTarget } = require_geoip_updater();
|
|
8832
|
+
var { sendServerError, sendValidationError } = require_http_errors();
|
|
8456
8833
|
var path = __require("node:path");
|
|
8457
8834
|
var ALLOWED_WEBHOOK_DOMAINS = {
|
|
8458
8835
|
discord: ["discord.com", "discordapp.com"],
|
|
@@ -8475,13 +8852,6 @@ var require_settings = __commonJS({
|
|
|
8475
8852
|
return "";
|
|
8476
8853
|
}
|
|
8477
8854
|
}
|
|
8478
|
-
function sanitizeCountryList(list) {
|
|
8479
|
-
if (!Array.isArray(list)) return [];
|
|
8480
|
-
return list.filter((code) => typeof code === "string" && /^[A-Z]{2}$/.test(code.trim().toUpperCase())).map((code) => code.trim().toUpperCase());
|
|
8481
|
-
}
|
|
8482
|
-
function sanitizeBoolean(value) {
|
|
8483
|
-
return value === true;
|
|
8484
|
-
}
|
|
8485
8855
|
function getSafeGeoIpFilename(value) {
|
|
8486
8856
|
if (typeof value !== "string" || !value.trim()) return "";
|
|
8487
8857
|
try {
|
|
@@ -8497,7 +8867,7 @@ var require_settings = __commonJS({
|
|
|
8497
8867
|
vpnProxy: { subject: "", html: "", text: "" }
|
|
8498
8868
|
};
|
|
8499
8869
|
if (!templates || typeof templates !== "object") return defaults;
|
|
8500
|
-
let sanitizeHtml
|
|
8870
|
+
let sanitizeHtml;
|
|
8501
8871
|
try {
|
|
8502
8872
|
sanitizeHtml = __require("sanitize-html");
|
|
8503
8873
|
} catch {
|
|
@@ -8648,6 +9018,203 @@ var require_settings = __commonJS({
|
|
|
8648
9018
|
geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath)
|
|
8649
9019
|
};
|
|
8650
9020
|
}
|
|
9021
|
+
var INTEGER_SETTING_RANGES = {
|
|
9022
|
+
inactivityTimeout: [1, 1440],
|
|
9023
|
+
cleanupInterval: [5, 1440],
|
|
9024
|
+
lastSeenRateLimit: [5, 300],
|
|
9025
|
+
maxSessionAgeDays: [1, 365],
|
|
9026
|
+
sessionCreationGraceMs: [0, 3e4],
|
|
9027
|
+
rateLimitWriteMax: [1, 1e3],
|
|
9028
|
+
rateLimitReadMax: [1, 1e4],
|
|
9029
|
+
rateLimitWindowSeconds: [10, 3600],
|
|
9030
|
+
maxFailedLogins: [0, 100]
|
|
9031
|
+
};
|
|
9032
|
+
var BOOLEAN_SETTINGS = [
|
|
9033
|
+
"cleanupUseDbDirect",
|
|
9034
|
+
"enableGeolocation",
|
|
9035
|
+
"enableSecurityScoring",
|
|
9036
|
+
"blockSuspiciousSessions",
|
|
9037
|
+
"enableGeofencing",
|
|
9038
|
+
"enableEmailAlerts",
|
|
9039
|
+
"alertOnSuspiciousLogin",
|
|
9040
|
+
"alertOnNewLocation",
|
|
9041
|
+
"alertOnVpnProxy",
|
|
9042
|
+
"enableWebhooks",
|
|
9043
|
+
"strictSessionEnforcement",
|
|
9044
|
+
"trustedProxies"
|
|
9045
|
+
];
|
|
9046
|
+
var GEO_IP_PROVIDER_VALUES = ["auto", "local-mmdb", "ipapi", "disabled"];
|
|
9047
|
+
var GEO_LOOKUP_FAILURE_MODE_VALUES = ["auto", "allow", "block"];
|
|
9048
|
+
var EMAIL_TEMPLATE_LIMITS = { subject: 200, html: 1e4, text: 5e3 };
|
|
9049
|
+
function parseInteger(value) {
|
|
9050
|
+
if (typeof value === "number") return Number.isInteger(value) ? value : null;
|
|
9051
|
+
if (typeof value === "string" && /^\s*-?\d+\s*$/.test(value)) return Number.parseInt(value, 10);
|
|
9052
|
+
return null;
|
|
9053
|
+
}
|
|
9054
|
+
function mergeEmailTemplate(key, update, current, errors) {
|
|
9055
|
+
if (!update || typeof update !== "object" || Array.isArray(update)) {
|
|
9056
|
+
errors.push({
|
|
9057
|
+
path: ["emailTemplates", key],
|
|
9058
|
+
message: `emailTemplates.${key} must be an object`
|
|
9059
|
+
});
|
|
9060
|
+
return void 0;
|
|
9061
|
+
}
|
|
9062
|
+
const merged = {
|
|
9063
|
+
subject: "",
|
|
9064
|
+
html: "",
|
|
9065
|
+
text: "",
|
|
9066
|
+
...current && typeof current === "object" ? current : {}
|
|
9067
|
+
};
|
|
9068
|
+
for (const [field, limit] of Object.entries(EMAIL_TEMPLATE_LIMITS)) {
|
|
9069
|
+
if (update[field] === void 0) continue;
|
|
9070
|
+
if (typeof update[field] !== "string") {
|
|
9071
|
+
errors.push({
|
|
9072
|
+
path: ["emailTemplates", key, field],
|
|
9073
|
+
message: `emailTemplates.${key}.${field} must be a string`
|
|
9074
|
+
});
|
|
9075
|
+
} else if (update[field].length > limit) {
|
|
9076
|
+
errors.push({
|
|
9077
|
+
path: ["emailTemplates", key, field],
|
|
9078
|
+
message: `emailTemplates.${key}.${field} must be at most ${limit} characters`
|
|
9079
|
+
});
|
|
9080
|
+
} else {
|
|
9081
|
+
merged[field] = update[field];
|
|
9082
|
+
}
|
|
9083
|
+
}
|
|
9084
|
+
return merged;
|
|
9085
|
+
}
|
|
9086
|
+
function validateSettingsUpdate(body, current) {
|
|
9087
|
+
const errors = [];
|
|
9088
|
+
const next = {};
|
|
9089
|
+
const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
|
|
9090
|
+
for (const [key, [min, max]] of Object.entries(INTEGER_SETTING_RANGES)) {
|
|
9091
|
+
if (!has(key)) continue;
|
|
9092
|
+
const value = parseInteger(body[key]);
|
|
9093
|
+
if (value === null || value < min || value > max) {
|
|
9094
|
+
errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
|
|
9095
|
+
} else {
|
|
9096
|
+
next[key] = value;
|
|
9097
|
+
}
|
|
9098
|
+
}
|
|
9099
|
+
if (has("retentionDays")) {
|
|
9100
|
+
const value = parseInteger(body.retentionDays);
|
|
9101
|
+
if (value === null || value !== -1 && (value < 1 || value > 365)) {
|
|
9102
|
+
errors.push({
|
|
9103
|
+
path: ["retentionDays"],
|
|
9104
|
+
message: "retentionDays must be -1 (forever) or an integer between 1 and 365"
|
|
9105
|
+
});
|
|
9106
|
+
} else {
|
|
9107
|
+
next.retentionDays = value;
|
|
9108
|
+
}
|
|
9109
|
+
}
|
|
9110
|
+
for (const key of BOOLEAN_SETTINGS) {
|
|
9111
|
+
if (!has(key)) continue;
|
|
9112
|
+
if (typeof body[key] !== "boolean") {
|
|
9113
|
+
errors.push({ path: [key], message: `${key} must be a boolean` });
|
|
9114
|
+
} else {
|
|
9115
|
+
next[key] = body[key];
|
|
9116
|
+
}
|
|
9117
|
+
}
|
|
9118
|
+
for (const key of ["allowedCountries", "blockedCountries"]) {
|
|
9119
|
+
if (!has(key)) continue;
|
|
9120
|
+
const list = body[key];
|
|
9121
|
+
if (!Array.isArray(list)) {
|
|
9122
|
+
errors.push({
|
|
9123
|
+
path: [key],
|
|
9124
|
+
message: `${key} must be a list of ISO 3166-1 alpha-2 country codes`
|
|
9125
|
+
});
|
|
9126
|
+
continue;
|
|
9127
|
+
}
|
|
9128
|
+
const normalized = list.map(
|
|
9129
|
+
(code) => typeof code === "string" ? code.trim().toUpperCase() : ""
|
|
9130
|
+
);
|
|
9131
|
+
if (normalized.some((code) => !/^[A-Z]{2}$/.test(code))) {
|
|
9132
|
+
errors.push({
|
|
9133
|
+
path: [key],
|
|
9134
|
+
message: `${key} must contain only ISO 3166-1 alpha-2 country codes`
|
|
9135
|
+
});
|
|
9136
|
+
} else {
|
|
9137
|
+
next[key] = [...new Set(normalized)];
|
|
9138
|
+
}
|
|
9139
|
+
}
|
|
9140
|
+
if (has("geoIpProvider")) {
|
|
9141
|
+
if (!GEO_IP_PROVIDER_VALUES.includes(body.geoIpProvider)) {
|
|
9142
|
+
errors.push({
|
|
9143
|
+
path: ["geoIpProvider"],
|
|
9144
|
+
message: `geoIpProvider must be one of: ${GEO_IP_PROVIDER_VALUES.join(", ")}`
|
|
9145
|
+
});
|
|
9146
|
+
} else {
|
|
9147
|
+
next.geoIpProvider = normalizeGeoIpProvider(body.geoIpProvider);
|
|
9148
|
+
}
|
|
9149
|
+
}
|
|
9150
|
+
if (has("geoLookupFailureMode")) {
|
|
9151
|
+
if (!GEO_LOOKUP_FAILURE_MODE_VALUES.includes(body.geoLookupFailureMode)) {
|
|
9152
|
+
errors.push({
|
|
9153
|
+
path: ["geoLookupFailureMode"],
|
|
9154
|
+
message: `geoLookupFailureMode must be one of: ${GEO_LOOKUP_FAILURE_MODE_VALUES.join(", ")}`
|
|
9155
|
+
});
|
|
9156
|
+
} else {
|
|
9157
|
+
next.geoLookupFailureMode = normalizeGeoLookupFailureMode(body.geoLookupFailureMode);
|
|
9158
|
+
}
|
|
9159
|
+
}
|
|
9160
|
+
if (Object.prototype.hasOwnProperty.call(body, "geoIpDatabasePath")) {
|
|
9161
|
+
if (body.geoIpDatabasePath === "") {
|
|
9162
|
+
next.geoIpDatabasePath = "";
|
|
9163
|
+
} else {
|
|
9164
|
+
try {
|
|
9165
|
+
next.geoIpDatabasePath = path.basename(resolveDatabaseTarget(body.geoIpDatabasePath));
|
|
9166
|
+
} catch {
|
|
9167
|
+
errors.push({
|
|
9168
|
+
path: ["geoIpDatabasePath"],
|
|
9169
|
+
message: "GeoIP database path must be a supported MMDB filename in the dedicated GeoIP directory"
|
|
9170
|
+
});
|
|
9171
|
+
}
|
|
9172
|
+
}
|
|
9173
|
+
}
|
|
9174
|
+
for (const [key, type] of [
|
|
9175
|
+
["discordWebhookUrl", "discord"],
|
|
9176
|
+
["slackWebhookUrl", "slack"]
|
|
9177
|
+
]) {
|
|
9178
|
+
if (!has(key)) continue;
|
|
9179
|
+
const value = body[key];
|
|
9180
|
+
if (typeof value !== "string") {
|
|
9181
|
+
errors.push({ path: [key], message: `${key} must be a string` });
|
|
9182
|
+
} else if (!value.trim()) {
|
|
9183
|
+
next[key] = "";
|
|
9184
|
+
} else {
|
|
9185
|
+
const sanitized = sanitizeWebhookUrl(value, type);
|
|
9186
|
+
if (!sanitized) {
|
|
9187
|
+
errors.push({
|
|
9188
|
+
path: [key],
|
|
9189
|
+
message: `${key} must be an https URL on ${ALLOWED_WEBHOOK_DOMAINS[type].join(" or ")}`
|
|
9190
|
+
});
|
|
9191
|
+
} else {
|
|
9192
|
+
next[key] = sanitized;
|
|
9193
|
+
}
|
|
9194
|
+
}
|
|
9195
|
+
}
|
|
9196
|
+
if (has("emailTemplates")) {
|
|
9197
|
+
const templates = body.emailTemplates;
|
|
9198
|
+
if (!templates || typeof templates !== "object" || Array.isArray(templates)) {
|
|
9199
|
+
errors.push({ path: ["emailTemplates"], message: "emailTemplates must be an object" });
|
|
9200
|
+
} else {
|
|
9201
|
+
const currentTemplates = current.emailTemplates || DEFAULT_EMAIL_TEMPLATES;
|
|
9202
|
+
const mergedTemplates = { ...DEFAULT_EMAIL_TEMPLATES, ...currentTemplates };
|
|
9203
|
+
for (const key of Object.keys(DEFAULT_EMAIL_TEMPLATES)) {
|
|
9204
|
+
if (templates[key] === void 0) continue;
|
|
9205
|
+
const merged = mergeEmailTemplate(key, templates[key], mergedTemplates[key], errors);
|
|
9206
|
+
if (merged) mergedTemplates[key] = merged;
|
|
9207
|
+
}
|
|
9208
|
+
next.emailTemplates = sanitizeEmailTemplates(mergedTemplates);
|
|
9209
|
+
}
|
|
9210
|
+
}
|
|
9211
|
+
if (errors.length > 0) return { errors };
|
|
9212
|
+
const settings = {};
|
|
9213
|
+
for (const key of Object.keys(DEFAULT_SETTINGS)) {
|
|
9214
|
+
settings[key] = Object.prototype.hasOwnProperty.call(next, key) ? next[key] : current[key];
|
|
9215
|
+
}
|
|
9216
|
+
return { settings, errors };
|
|
9217
|
+
}
|
|
8651
9218
|
module.exports = {
|
|
8652
9219
|
/**
|
|
8653
9220
|
* Returns current plugin settings in user-facing units. Legacy custom MMDB
|
|
@@ -8669,75 +9236,47 @@ var require_settings = __commonJS({
|
|
|
8669
9236
|
success: true
|
|
8670
9237
|
});
|
|
8671
9238
|
} catch (error) {
|
|
8672
|
-
strapi.log.error(
|
|
8673
|
-
|
|
9239
|
+
strapi.log.error(
|
|
9240
|
+
"[magic-sessionmanager/settings] Error getting settings:",
|
|
9241
|
+
error?.name || "Error"
|
|
9242
|
+
);
|
|
9243
|
+
return sendServerError(ctx, 500, "Error loading settings");
|
|
8674
9244
|
}
|
|
8675
9245
|
},
|
|
8676
9246
|
/**
|
|
8677
|
-
* Validates
|
|
8678
|
-
*
|
|
9247
|
+
* Validates a full or partial settings payload, merges it over the stored
|
|
9248
|
+
* settings and persists the result, then invalidates the settings cache so
|
|
9249
|
+
* runtime code picks up the new values on next read.
|
|
9250
|
+
*
|
|
9251
|
+
* Omitted fields keep their stored value. Invalid values are rejected with
|
|
9252
|
+
* a 400 whose `error.details.errors` names each field; nothing is clamped
|
|
9253
|
+
* or written in that case. Store failures return a 500 with a safe message.
|
|
9254
|
+
*
|
|
8679
9255
|
* @route PUT /magic-sessionmanager/settings
|
|
8680
|
-
* @throws {ValidationError} when the body or GeoIP filename is invalid
|
|
8681
9256
|
* @returns {Promise<void>}
|
|
8682
9257
|
*/
|
|
8683
9258
|
async updateSettings(ctx) {
|
|
9259
|
+
let pluginStore;
|
|
9260
|
+
let current;
|
|
8684
9261
|
try {
|
|
8685
9262
|
const { body } = ctx.request;
|
|
8686
9263
|
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
8687
9264
|
return ctx.badRequest("Settings data must be an object");
|
|
8688
9265
|
}
|
|
8689
|
-
|
|
9266
|
+
pluginStore = strapi.store({
|
|
8690
9267
|
type: "plugin",
|
|
8691
9268
|
name: "magic-sessionmanager"
|
|
8692
9269
|
});
|
|
8693
|
-
|
|
8694
|
-
|
|
8695
|
-
|
|
8696
|
-
|
|
8697
|
-
|
|
8698
|
-
return ctx.badRequest("GeoIP database path must be a supported MMDB filename in the dedicated GeoIP directory");
|
|
8699
|
-
}
|
|
8700
|
-
}
|
|
8701
|
-
const grace = getSessionCreationGraceMs(body);
|
|
8702
|
-
const maxFailedLoginsRaw = Number.parseInt(body.maxFailedLogins, 10);
|
|
8703
|
-
const maxFailedLogins = Number.isFinite(maxFailedLoginsRaw) ? Math.max(0, Math.min(maxFailedLoginsRaw, 100)) : 5;
|
|
8704
|
-
const sanitizedSettings = {
|
|
8705
|
-
// Timing & cleanup
|
|
8706
|
-
inactivityTimeout: Math.max(1, Math.min(parseInt(body.inactivityTimeout) || 15, 1440)),
|
|
8707
|
-
cleanupInterval: Math.max(5, Math.min(parseInt(body.cleanupInterval) || 30, 1440)),
|
|
8708
|
-
lastSeenRateLimit: Math.max(5, Math.min(parseInt(body.lastSeenRateLimit) || 30, 300)),
|
|
8709
|
-
retentionDays: normalizeRetentionDays(body.retentionDays, 90),
|
|
8710
|
-
maxSessionAgeDays: Math.max(1, Math.min(parseInt(body.maxSessionAgeDays) || 30, 365)),
|
|
8711
|
-
sessionCreationGraceMs: grace,
|
|
8712
|
-
cleanupUseDbDirect: sanitizeBoolean(body.cleanupUseDbDirect),
|
|
8713
|
-
rateLimitWriteMax: Math.max(1, Math.min(parseInt(body.rateLimitWriteMax) || 10, 1e3)),
|
|
8714
|
-
rateLimitReadMax: Math.max(1, Math.min(parseInt(body.rateLimitReadMax) || 120, 1e4)),
|
|
8715
|
-
rateLimitWindowSeconds: Math.max(10, Math.min(parseInt(body.rateLimitWindowSeconds) || 60, 3600)),
|
|
8716
|
-
// Geo / security
|
|
8717
|
-
enableGeolocation: sanitizeBoolean(body.enableGeolocation),
|
|
8718
|
-
enableSecurityScoring: sanitizeBoolean(body.enableSecurityScoring),
|
|
8719
|
-
blockSuspiciousSessions: sanitizeBoolean(body.blockSuspiciousSessions),
|
|
8720
|
-
maxFailedLogins,
|
|
8721
|
-
enableGeofencing: sanitizeBoolean(body.enableGeofencing),
|
|
8722
|
-
allowedCountries: sanitizeCountryList(body.allowedCountries),
|
|
8723
|
-
blockedCountries: sanitizeCountryList(body.blockedCountries),
|
|
8724
|
-
geoIpProvider: normalizeGeoIpProvider(body.geoIpProvider),
|
|
8725
|
-
geoIpDatabasePath,
|
|
8726
|
-
geoLookupFailureMode: normalizeGeoLookupFailureMode(body.geoLookupFailureMode),
|
|
8727
|
-
// Notifications
|
|
8728
|
-
enableEmailAlerts: sanitizeBoolean(body.enableEmailAlerts),
|
|
8729
|
-
alertOnSuspiciousLogin: sanitizeBoolean(body.alertOnSuspiciousLogin),
|
|
8730
|
-
alertOnNewLocation: sanitizeBoolean(body.alertOnNewLocation),
|
|
8731
|
-
alertOnVpnProxy: sanitizeBoolean(body.alertOnVpnProxy),
|
|
8732
|
-
enableWebhooks: sanitizeBoolean(body.enableWebhooks),
|
|
8733
|
-
discordWebhookUrl: sanitizeWebhookUrl(body.discordWebhookUrl, "discord"),
|
|
8734
|
-
slackWebhookUrl: sanitizeWebhookUrl(body.slackWebhookUrl, "slack"),
|
|
8735
|
-
// Session policy
|
|
8736
|
-
strictSessionEnforcement: sanitizeBoolean(body.strictSessionEnforcement),
|
|
8737
|
-
trustedProxies: sanitizeBoolean(body.trustedProxies),
|
|
8738
|
-
// Email templates
|
|
8739
|
-
emailTemplates: sanitizeEmailTemplates(body.emailTemplates)
|
|
9270
|
+
const stored = await pluginStore.get({ key: "settings" });
|
|
9271
|
+
const storedObject = stored && typeof stored === "object" ? stored : {};
|
|
9272
|
+
current = {
|
|
9273
|
+
...mergeSettingsWithDefaults(storedObject),
|
|
9274
|
+
geoIpDatabasePath: typeof storedObject.geoIpDatabasePath === "string" ? storedObject.geoIpDatabasePath : ""
|
|
8740
9275
|
};
|
|
9276
|
+
const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
|
|
9277
|
+
if (errors.length > 0) {
|
|
9278
|
+
return sendValidationError(ctx, "Invalid settings", errors);
|
|
9279
|
+
}
|
|
8741
9280
|
await pluginStore.set({
|
|
8742
9281
|
key: "settings",
|
|
8743
9282
|
value: sanitizedSettings
|
|
@@ -8745,17 +9284,24 @@ var require_settings = __commonJS({
|
|
|
8745
9284
|
invalidateSettingsCache();
|
|
8746
9285
|
strapi.log.info("[magic-sessionmanager/settings] Settings updated successfully");
|
|
8747
9286
|
ctx.send({
|
|
8748
|
-
settings:
|
|
9287
|
+
settings: {
|
|
9288
|
+
...sanitizedSettings,
|
|
9289
|
+
geoIpDatabasePath: getSafeGeoIpFilename(sanitizedSettings.geoIpDatabasePath)
|
|
9290
|
+
},
|
|
8749
9291
|
success: true,
|
|
8750
9292
|
message: "Settings saved successfully!"
|
|
8751
9293
|
});
|
|
8752
9294
|
} catch (error) {
|
|
8753
|
-
strapi.log.error(
|
|
8754
|
-
|
|
9295
|
+
strapi.log.error(
|
|
9296
|
+
"[magic-sessionmanager/settings] Error updating settings:",
|
|
9297
|
+
error?.name || "Error"
|
|
9298
|
+
);
|
|
9299
|
+
return sendServerError(ctx, 500, "Error saving settings");
|
|
8755
9300
|
}
|
|
8756
9301
|
},
|
|
8757
9302
|
DEFAULT_SETTINGS,
|
|
8758
|
-
mergeSettingsWithDefaults
|
|
9303
|
+
mergeSettingsWithDefaults,
|
|
9304
|
+
validateSettingsUpdate
|
|
8759
9305
|
};
|
|
8760
9306
|
}
|
|
8761
9307
|
});
|
|
@@ -8779,6 +9325,7 @@ var require_geoip = __commonJS({
|
|
|
8779
9325
|
invalidateSettingsCache,
|
|
8780
9326
|
normalizeGeoIpDatabasePath
|
|
8781
9327
|
} = require_settings_loader();
|
|
9328
|
+
var { sendServerError } = require_http_errors();
|
|
8782
9329
|
var CREDENTIALS_KEY = "geoipCredentials";
|
|
8783
9330
|
var SAFE_GEOIP_DIRECTORY_LABEL = "data/magic-sessionmanager/geoip";
|
|
8784
9331
|
var DEFAULT_CITY_DATABASE_PATH = resolveDatabaseTarget("GeoLite2-City.mmdb");
|
|
@@ -8876,8 +9423,11 @@ var require_geoip = __commonJS({
|
|
|
8876
9423
|
}
|
|
8877
9424
|
});
|
|
8878
9425
|
} catch (error) {
|
|
8879
|
-
strapi2.log.error(
|
|
8880
|
-
|
|
9426
|
+
strapi2.log.error(
|
|
9427
|
+
"[magic-sessionmanager/geoip] Error getting status:",
|
|
9428
|
+
error?.name || "Error"
|
|
9429
|
+
);
|
|
9430
|
+
return sendServerError(ctx, 500, "Error getting GeoIP status");
|
|
8881
9431
|
}
|
|
8882
9432
|
},
|
|
8883
9433
|
/**
|
|
@@ -8906,8 +9456,11 @@ var require_geoip = __commonJS({
|
|
|
8906
9456
|
accountId
|
|
8907
9457
|
});
|
|
8908
9458
|
} catch (error) {
|
|
8909
|
-
strapi2.log.error(
|
|
8910
|
-
|
|
9459
|
+
strapi2.log.error(
|
|
9460
|
+
"[magic-sessionmanager/geoip] Error storing credentials:",
|
|
9461
|
+
error?.name || "Error"
|
|
9462
|
+
);
|
|
9463
|
+
return sendServerError(ctx, 500, "Error storing GeoIP credentials");
|
|
8911
9464
|
}
|
|
8912
9465
|
},
|
|
8913
9466
|
/**
|
|
@@ -8927,15 +9480,27 @@ var require_geoip = __commonJS({
|
|
|
8927
9480
|
if (!config.accountId || !config.licenseKey) {
|
|
8928
9481
|
return ctx.badRequest("MaxMind credentials are required before downloading GeoIP data");
|
|
8929
9482
|
}
|
|
8930
|
-
|
|
9483
|
+
let result;
|
|
9484
|
+
try {
|
|
9485
|
+
result = await updateDatabase(config);
|
|
9486
|
+
} catch (error) {
|
|
9487
|
+
strapi2.log.error(
|
|
9488
|
+
"[magic-sessionmanager/geoip] GeoIP download failed:",
|
|
9489
|
+
error?.name || "Error"
|
|
9490
|
+
);
|
|
9491
|
+
return sendServerError(ctx, 502, "Error updating GeoIP database");
|
|
9492
|
+
}
|
|
8931
9493
|
invalidateSettingsCache();
|
|
8932
9494
|
ctx.send({
|
|
8933
9495
|
success: true,
|
|
8934
9496
|
result
|
|
8935
9497
|
});
|
|
8936
9498
|
} catch (error) {
|
|
8937
|
-
strapi2.log.error(
|
|
8938
|
-
|
|
9499
|
+
strapi2.log.error(
|
|
9500
|
+
"[magic-sessionmanager/geoip] Error updating database:",
|
|
9501
|
+
error?.name || "Error"
|
|
9502
|
+
);
|
|
9503
|
+
return sendServerError(ctx, 500, "Error updating GeoIP database");
|
|
8939
9504
|
}
|
|
8940
9505
|
},
|
|
8941
9506
|
__private: {
|
|
@@ -8965,93 +9530,6 @@ var require_controllers = __commonJS({
|
|
|
8965
9530
|
}
|
|
8966
9531
|
});
|
|
8967
9532
|
|
|
8968
|
-
// server/src/utils/native-session-view.js
|
|
8969
|
-
var require_native_session_view = __commonJS({
|
|
8970
|
-
"server/src/utils/native-session-view.js"(exports, module) {
|
|
8971
|
-
"use strict";
|
|
8972
|
-
var NATIVE_SESSION_PREFIX = "native_";
|
|
8973
|
-
function createNativeSessionKey(userDocumentId, nativeSessionId) {
|
|
8974
|
-
if (typeof userDocumentId !== "string" || !userDocumentId || typeof nativeSessionId !== "string" || !nativeSessionId) {
|
|
8975
|
-
throw new TypeError("Native session view keys require an owner documentId and session ID.");
|
|
8976
|
-
}
|
|
8977
|
-
const payload = Buffer.from(JSON.stringify([userDocumentId, nativeSessionId])).toString(
|
|
8978
|
-
"base64url"
|
|
8979
|
-
);
|
|
8980
|
-
if (payload.length > 2048) {
|
|
8981
|
-
throw new RangeError("Native session view key exceeds the supported URL-safe length.");
|
|
8982
|
-
}
|
|
8983
|
-
return `${NATIVE_SESSION_PREFIX}${payload}`;
|
|
8984
|
-
}
|
|
8985
|
-
function parseNativeSessionKey(value) {
|
|
8986
|
-
if (typeof value !== "string" || !value.startsWith(NATIVE_SESSION_PREFIX)) return null;
|
|
8987
|
-
const encoded = value.slice(NATIVE_SESSION_PREFIX.length);
|
|
8988
|
-
if (!encoded || encoded.length > 2048 || !/^[A-Za-z0-9_-]+$/.test(encoded)) return null;
|
|
8989
|
-
try {
|
|
8990
|
-
const decoded = Buffer.from(encoded, "base64url").toString("utf8");
|
|
8991
|
-
if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded) return null;
|
|
8992
|
-
const payload = JSON.parse(decoded);
|
|
8993
|
-
if (!Array.isArray(payload) || payload.length !== 2 || typeof payload[0] !== "string" || !payload[0] || typeof payload[1] !== "string" || !payload[1]) {
|
|
8994
|
-
return null;
|
|
8995
|
-
}
|
|
8996
|
-
return {
|
|
8997
|
-
userDocumentId: payload[0],
|
|
8998
|
-
nativeSessionId: payload[1]
|
|
8999
|
-
};
|
|
9000
|
-
} catch {
|
|
9001
|
-
return null;
|
|
9002
|
-
}
|
|
9003
|
-
}
|
|
9004
|
-
function mapNativeSessionToView(session, user) {
|
|
9005
|
-
const nativeId = String(session.sessionId);
|
|
9006
|
-
const stableId = createNativeSessionKey(String(user.documentId), nativeId);
|
|
9007
|
-
const metadata = session.metadata && typeof session.metadata === "object" ? session.metadata : {};
|
|
9008
|
-
const loginAt = typeof metadata.loginAt === "string" && !Number.isNaN(Date.parse(metadata.loginAt)) ? new Date(metadata.loginAt) : null;
|
|
9009
|
-
const createdAt = session.createdAt && !Number.isNaN(new Date(session.createdAt).getTime()) ? new Date(session.createdAt) : null;
|
|
9010
|
-
const userView = {
|
|
9011
|
-
documentId: user.documentId,
|
|
9012
|
-
email: user.email,
|
|
9013
|
-
username: user.username
|
|
9014
|
-
};
|
|
9015
|
-
return {
|
|
9016
|
-
documentId: stableId,
|
|
9017
|
-
id: stableId,
|
|
9018
|
-
sessionId: stableId,
|
|
9019
|
-
nativeSessionId: nativeId,
|
|
9020
|
-
user: userView,
|
|
9021
|
-
ipAddress: null,
|
|
9022
|
-
userAgent: null,
|
|
9023
|
-
loginTime: loginAt || createdAt,
|
|
9024
|
-
logoutTime: null,
|
|
9025
|
-
lastActive: createdAt || loginAt,
|
|
9026
|
-
isActive: true,
|
|
9027
|
-
terminatedManually: false,
|
|
9028
|
-
geoLocation: null,
|
|
9029
|
-
securityScore: null,
|
|
9030
|
-
deviceType: null,
|
|
9031
|
-
deviceName: typeof metadata.deviceName === "string" ? metadata.deviceName : void 0,
|
|
9032
|
-
browserName: null,
|
|
9033
|
-
osName: null
|
|
9034
|
-
};
|
|
9035
|
-
}
|
|
9036
|
-
function markSessionsTruncated(sessions, truncated) {
|
|
9037
|
-
Object.defineProperty(sessions, "truncated", {
|
|
9038
|
-
value: Boolean(truncated),
|
|
9039
|
-
enumerable: false,
|
|
9040
|
-
configurable: false,
|
|
9041
|
-
writable: false
|
|
9042
|
-
});
|
|
9043
|
-
return sessions;
|
|
9044
|
-
}
|
|
9045
|
-
module.exports = {
|
|
9046
|
-
NATIVE_SESSION_PREFIX,
|
|
9047
|
-
createNativeSessionKey,
|
|
9048
|
-
parseNativeSessionKey,
|
|
9049
|
-
mapNativeSessionToView,
|
|
9050
|
-
markSessionsTruncated
|
|
9051
|
-
};
|
|
9052
|
-
}
|
|
9053
|
-
});
|
|
9054
|
-
|
|
9055
9533
|
// server/src/services/session.js
|
|
9056
9534
|
var require_session2 = __commonJS({
|
|
9057
9535
|
"server/src/services/session.js"(exports, module) {
|
|
@@ -9600,7 +10078,8 @@ var require_session2 = __commonJS({
|
|
|
9600
10078
|
* still match before a
|
|
9601
10079
|
* single-session update.
|
|
9602
10080
|
* @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
|
|
9603
|
-
* @returns {Promise<{terminatedCount: number}>}
|
|
10081
|
+
* @returns {Promise<{terminatedCount: number}>} Completed count; rejects if
|
|
10082
|
+
* active rows cannot be updated. Earlier updates may already be committed.
|
|
9604
10083
|
*/
|
|
9605
10084
|
async terminateSession({
|
|
9606
10085
|
sessionId,
|
|
@@ -9743,13 +10222,11 @@ var require_session2 = __commonJS({
|
|
|
9743
10222
|
}
|
|
9744
10223
|
if (batchTerminated === 0) {
|
|
9745
10224
|
log.warn("Could not terminate remaining active sessions for one user");
|
|
9746
|
-
|
|
10225
|
+
throw new Error("Unable to terminate all requested sessions");
|
|
9747
10226
|
}
|
|
9748
10227
|
}
|
|
9749
10228
|
const label = exceptSessionId ? "OTHER sessions" : "ALL sessions";
|
|
9750
|
-
log.info(
|
|
9751
|
-
`${label} terminated (reason: ${finalReason}, count: ${terminatedCount})`
|
|
9752
|
-
);
|
|
10229
|
+
log.info(`${label} terminated (reason: ${finalReason}, count: ${terminatedCount})`);
|
|
9753
10230
|
return { terminatedCount: nativeManager ? terminatedKeys.size : terminatedCount };
|
|
9754
10231
|
}
|
|
9755
10232
|
return { terminatedCount: 0 };
|
|
@@ -10167,18 +10644,29 @@ var require_session2 = __commonJS({
|
|
|
10167
10644
|
* Removes all inactive session rows, retaining deny hashes for unexpired
|
|
10168
10645
|
* access tokens. A failed hash write leaves its session row in place.
|
|
10169
10646
|
*
|
|
10170
|
-
*
|
|
10647
|
+
* A row that cannot be removed is excluded from later batches, so one
|
|
10648
|
+
* persistently failing row cannot block the rest of the cleanup. Expired
|
|
10649
|
+
* revocation records are cleaned up in every case.
|
|
10650
|
+
*
|
|
10651
|
+
* @returns {Promise<number>} Number of rows removed when every row succeeded
|
|
10652
|
+
* @throws {Error} `PartialCleanupError` with `deletedCount` and
|
|
10653
|
+
* `failedCount` when at least one row could not be removed; the other
|
|
10654
|
+
* rows have been removed by then
|
|
10171
10655
|
* @sideeffect Writes revocation records before deleting session rows
|
|
10172
10656
|
*/
|
|
10173
10657
|
async deleteInactiveSessions() {
|
|
10174
10658
|
try {
|
|
10175
10659
|
log.info("[DELETE] Deleting all inactive sessions...");
|
|
10176
10660
|
let deletedCount = 0;
|
|
10661
|
+
const failedIds = /* @__PURE__ */ new Set();
|
|
10177
10662
|
const BATCH_SIZE = 100;
|
|
10178
|
-
let consecutiveEmptyLoops = 0;
|
|
10179
10663
|
while (true) {
|
|
10664
|
+
const filters = { isActive: false };
|
|
10665
|
+
if (failedIds.size > 0) {
|
|
10666
|
+
filters.documentId = { $notIn: [...failedIds] };
|
|
10667
|
+
}
|
|
10180
10668
|
const batch = await strapi2.documents(SESSION_UID).findMany({
|
|
10181
|
-
filters
|
|
10669
|
+
filters,
|
|
10182
10670
|
fields: ["documentId", "token", "tokenHash", "nativeSessionId"],
|
|
10183
10671
|
populate: { user: { fields: ["id", "documentId"] } },
|
|
10184
10672
|
limit: BATCH_SIZE
|
|
@@ -10187,26 +10675,32 @@ var require_session2 = __commonJS({
|
|
|
10187
10675
|
const deleteResults = await Promise.allSettled(
|
|
10188
10676
|
batch.map((session) => deleteSessionPreservingRevocation(session))
|
|
10189
10677
|
);
|
|
10190
|
-
|
|
10191
|
-
|
|
10192
|
-
|
|
10193
|
-
|
|
10194
|
-
|
|
10195
|
-
log.warn(
|
|
10196
|
-
"[DELETE] No progress on 3 consecutive batches, aborting to prevent infinite loop"
|
|
10197
|
-
);
|
|
10198
|
-
break;
|
|
10678
|
+
deleteResults.forEach((result, index) => {
|
|
10679
|
+
if (result.status === "fulfilled") {
|
|
10680
|
+
deletedCount += 1;
|
|
10681
|
+
} else {
|
|
10682
|
+
failedIds.add(batch[index].documentId);
|
|
10199
10683
|
}
|
|
10200
|
-
}
|
|
10201
|
-
consecutiveEmptyLoops = 0;
|
|
10202
|
-
}
|
|
10684
|
+
});
|
|
10203
10685
|
if (batch.length < BATCH_SIZE) break;
|
|
10204
10686
|
}
|
|
10205
10687
|
await cleanupExpiredRevocations();
|
|
10688
|
+
if (failedIds.size > 0) {
|
|
10689
|
+
log.warn(
|
|
10690
|
+
`[DELETE] Deleted ${deletedCount} inactive sessions; ${failedIds.size} could not be removed`
|
|
10691
|
+
);
|
|
10692
|
+
const error = new Error("Unable to remove all inactive sessions");
|
|
10693
|
+
error.name = "PartialCleanupError";
|
|
10694
|
+
error.deletedCount = deletedCount;
|
|
10695
|
+
error.failedCount = failedIds.size;
|
|
10696
|
+
throw error;
|
|
10697
|
+
}
|
|
10206
10698
|
log.info(`[SUCCESS] Deleted ${deletedCount} inactive sessions`);
|
|
10207
10699
|
return deletedCount;
|
|
10208
10700
|
} catch (err) {
|
|
10209
|
-
|
|
10701
|
+
if (err?.name !== "PartialCleanupError") {
|
|
10702
|
+
log.error("Error deleting inactive sessions:", err?.name || "Error");
|
|
10703
|
+
}
|
|
10210
10704
|
throw err;
|
|
10211
10705
|
}
|
|
10212
10706
|
}
|
|
@@ -10219,7 +10713,7 @@ var require_session2 = __commonJS({
|
|
|
10219
10713
|
var require_package = __commonJS({
|
|
10220
10714
|
"package.json"(exports, module) {
|
|
10221
10715
|
module.exports = {
|
|
10222
|
-
version: "4.
|
|
10716
|
+
version: "4.9.0",
|
|
10223
10717
|
keywords: [
|
|
10224
10718
|
"strapi",
|
|
10225
10719
|
"plugin",
|
|
@@ -10269,6 +10763,10 @@ var require_package = __commonJS({
|
|
|
10269
10763
|
test: "node --test tests/*.test.js tests/*.test.mjs",
|
|
10270
10764
|
"test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
|
|
10271
10765
|
"test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
|
|
10766
|
+
lint: "eslint .",
|
|
10767
|
+
"lint:fix": "eslint . --fix",
|
|
10768
|
+
format: "prettier --write .",
|
|
10769
|
+
"format:check": "prettier --check .",
|
|
10272
10770
|
build: "npm run clean && strapi-plugin build && node scripts/build-server-bundle.mjs",
|
|
10273
10771
|
watch: "strapi-plugin watch",
|
|
10274
10772
|
"watch:link": "strapi-plugin watch:link",
|
|
@@ -10282,6 +10780,7 @@ var require_package = __commonJS({
|
|
|
10282
10780
|
"sanitize-html": "^2.18.0"
|
|
10283
10781
|
},
|
|
10284
10782
|
devDependencies: {
|
|
10783
|
+
"@eslint/js": "^10.0.1",
|
|
10285
10784
|
"@semantic-release/changelog": "^7.0.0",
|
|
10286
10785
|
"@semantic-release/commit-analyzer": "^13.0.1",
|
|
10287
10786
|
"@semantic-release/git": "^11.0.1",
|
|
@@ -10293,6 +10792,10 @@ var require_package = __commonJS({
|
|
|
10293
10792
|
"@strapi/sdk-plugin": "^6.1.1",
|
|
10294
10793
|
"@strapi/strapi": "5.61.0",
|
|
10295
10794
|
esbuild: "^0.28.2",
|
|
10795
|
+
eslint: "^10.14.0",
|
|
10796
|
+
"eslint-config-prettier": "^10.1.8",
|
|
10797
|
+
"eslint-plugin-react-hooks": "^7.1.1",
|
|
10798
|
+
globals: "^17.14.0",
|
|
10296
10799
|
prettier: "^3.9.10",
|
|
10297
10800
|
react: "^18.3.1",
|
|
10298
10801
|
"react-dom": "^18.3.1",
|
|
@@ -10437,21 +10940,24 @@ var require_license_guard = __commonJS({
|
|
|
10437
10940
|
},
|
|
10438
10941
|
async createLicense({ email, firstName, lastName }) {
|
|
10439
10942
|
try {
|
|
10440
|
-
const response = await fetchWithTimeout(
|
|
10441
|
-
|
|
10442
|
-
|
|
10443
|
-
|
|
10444
|
-
|
|
10445
|
-
|
|
10446
|
-
|
|
10447
|
-
|
|
10448
|
-
|
|
10449
|
-
|
|
10450
|
-
|
|
10451
|
-
|
|
10452
|
-
|
|
10453
|
-
|
|
10454
|
-
|
|
10943
|
+
const response = await fetchWithTimeout(
|
|
10944
|
+
`${this.getLicenseServerUrl()}/api/licenses/create`,
|
|
10945
|
+
{
|
|
10946
|
+
method: "POST",
|
|
10947
|
+
headers: { "Content-Type": "application/json" },
|
|
10948
|
+
body: JSON.stringify({
|
|
10949
|
+
email,
|
|
10950
|
+
firstName,
|
|
10951
|
+
lastName,
|
|
10952
|
+
deviceName: this.getDeviceName(),
|
|
10953
|
+
deviceId: await this.generateDeviceId(),
|
|
10954
|
+
ipAddress: this.getIpAddress(),
|
|
10955
|
+
userAgent: this.getUserAgent(),
|
|
10956
|
+
pluginName: "magic-sessionmanager",
|
|
10957
|
+
productName: "Magic Session Manager"
|
|
10958
|
+
})
|
|
10959
|
+
}
|
|
10960
|
+
);
|
|
10455
10961
|
const data = await response.json();
|
|
10456
10962
|
if (data.success) {
|
|
10457
10963
|
log.info("[SUCCESS] License created");
|
|
@@ -10466,15 +10972,18 @@ var require_license_guard = __commonJS({
|
|
|
10466
10972
|
},
|
|
10467
10973
|
async verifyLicense(licenseKey) {
|
|
10468
10974
|
try {
|
|
10469
|
-
const response = await fetchWithTimeout(
|
|
10470
|
-
|
|
10471
|
-
|
|
10472
|
-
|
|
10473
|
-
|
|
10474
|
-
|
|
10475
|
-
|
|
10476
|
-
|
|
10477
|
-
|
|
10975
|
+
const response = await fetchWithTimeout(
|
|
10976
|
+
`${this.getLicenseServerUrl()}/api/licenses/verify`,
|
|
10977
|
+
{
|
|
10978
|
+
method: "POST",
|
|
10979
|
+
headers: { "Content-Type": "application/json" },
|
|
10980
|
+
body: JSON.stringify({
|
|
10981
|
+
licenseKey,
|
|
10982
|
+
pluginName: "magic-sessionmanager",
|
|
10983
|
+
productName: "Magic Session Manager"
|
|
10984
|
+
})
|
|
10985
|
+
}
|
|
10986
|
+
);
|
|
10478
10987
|
const data = await response.json();
|
|
10479
10988
|
if (data.success && data.data) {
|
|
10480
10989
|
const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
|
|
@@ -10492,10 +11001,13 @@ var require_license_guard = __commonJS({
|
|
|
10492
11001
|
async getLicenseByKey(licenseKey) {
|
|
10493
11002
|
try {
|
|
10494
11003
|
const encodedKey = encodeURIComponent(licenseKey);
|
|
10495
|
-
const response = await fetchWithTimeout(
|
|
10496
|
-
|
|
10497
|
-
|
|
10498
|
-
|
|
11004
|
+
const response = await fetchWithTimeout(
|
|
11005
|
+
`${this.getLicenseServerUrl()}/api/licenses/key/${encodedKey}`,
|
|
11006
|
+
{
|
|
11007
|
+
method: "GET",
|
|
11008
|
+
headers: { "Content-Type": "application/json" }
|
|
11009
|
+
}
|
|
11010
|
+
);
|
|
10499
11011
|
const data = await response.json();
|
|
10500
11012
|
if (data.success && data.data) return data.data;
|
|
10501
11013
|
return null;
|
|
@@ -10778,6 +11290,18 @@ var require_geolocation = __commonJS({
|
|
|
10778
11290
|
if (ipv4Mapped && net.isIP(ipv4Mapped[1]) === 4) {
|
|
10779
11291
|
return ipv4Mapped[1];
|
|
10780
11292
|
}
|
|
11293
|
+
if (net.isIP(normalized) === 6) {
|
|
11294
|
+
try {
|
|
11295
|
+
const canonical = new URL(`http://[${normalized}]/`).hostname.slice(1, -1);
|
|
11296
|
+
const mapped = canonical.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
|
|
11297
|
+
if (mapped) {
|
|
11298
|
+
const high = Number.parseInt(mapped[1], 16);
|
|
11299
|
+
const low = Number.parseInt(mapped[2], 16);
|
|
11300
|
+
return `${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`;
|
|
11301
|
+
}
|
|
11302
|
+
} catch {
|
|
11303
|
+
}
|
|
11304
|
+
}
|
|
10781
11305
|
return normalized;
|
|
10782
11306
|
}
|
|
10783
11307
|
function parseIpv4(ip) {
|
|
@@ -10801,7 +11325,11 @@ var require_geolocation = __commonJS({
|
|
|
10801
11325
|
return Number.isNaN(parsed) ? 0 : parsed;
|
|
10802
11326
|
}
|
|
10803
11327
|
function isPrivateIpv6(ip) {
|
|
10804
|
-
|
|
11328
|
+
let lower = ip.toLowerCase();
|
|
11329
|
+
try {
|
|
11330
|
+
lower = new URL(`http://[${lower}]/`).hostname.slice(1, -1);
|
|
11331
|
+
} catch {
|
|
11332
|
+
}
|
|
10805
11333
|
if (lower === "::" || lower === "::1") return true;
|
|
10806
11334
|
if (/^(?:0:){7}0$/.test(lower) || /^(?:0:){7}1$/.test(lower)) return true;
|
|
10807
11335
|
if (lower.startsWith("::ffff:")) {
|
|
@@ -10868,7 +11396,9 @@ var require_geolocation = __commonJS({
|
|
|
10868
11396
|
if (localResult?._status === "ok" || settings.geoLookupFailureMode === "block") {
|
|
10869
11397
|
return localResult;
|
|
10870
11398
|
}
|
|
10871
|
-
strapi2.log.warn(
|
|
11399
|
+
strapi2.log.warn(
|
|
11400
|
+
"[magic-sessionmanager/geolocation] Local MMDB lookup failed, falling back to ipapi.co"
|
|
11401
|
+
);
|
|
10872
11402
|
}
|
|
10873
11403
|
}
|
|
10874
11404
|
return this.getIpapiIpInfo(lookupIp);
|
|
@@ -10911,10 +11441,15 @@ var require_geolocation = __commonJS({
|
|
|
10911
11441
|
const useCityLookup = isCityDatabase(reader, databasePath) && typeof reader.city === "function";
|
|
10912
11442
|
const data = useCityLookup ? reader.city(lookupIp) : reader.country(lookupIp);
|
|
10913
11443
|
const result = useCityLookup ? normalizeLocalCityResult(data, lookupIp, this.getCountryFlag.bind(this)) : normalizeLocalCountryResult(data, lookupIp, this.getCountryFlag.bind(this));
|
|
10914
|
-
strapi2.log.debug(
|
|
11444
|
+
strapi2.log.debug(
|
|
11445
|
+
`[magic-sessionmanager/geolocation] Local MMDB lookup completed (${result._databaseType})`
|
|
11446
|
+
);
|
|
10915
11447
|
return result;
|
|
10916
11448
|
} catch (error) {
|
|
10917
|
-
strapi2.log.warn(
|
|
11449
|
+
strapi2.log.warn(
|
|
11450
|
+
"[magic-sessionmanager/geolocation] Local MMDB lookup failed:",
|
|
11451
|
+
error?.name || "Error"
|
|
11452
|
+
);
|
|
10918
11453
|
return this.getFallbackData(lookupIp, "error", "local-mmdb", error.message);
|
|
10919
11454
|
}
|
|
10920
11455
|
},
|
|
@@ -10936,7 +11471,12 @@ var require_geolocation = __commonJS({
|
|
|
10936
11471
|
strapi2,
|
|
10937
11472
|
`[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(rateLimitRemainingMs / 1e3)}s`
|
|
10938
11473
|
);
|
|
10939
|
-
return this.getFallbackData(
|
|
11474
|
+
return this.getFallbackData(
|
|
11475
|
+
lookupIp,
|
|
11476
|
+
"rate_limited",
|
|
11477
|
+
"ipapi",
|
|
11478
|
+
"Remote GeoIP provider is backing off after HTTP 429"
|
|
11479
|
+
);
|
|
10940
11480
|
}
|
|
10941
11481
|
if (ipapiInFlight.has(lookupIp)) {
|
|
10942
11482
|
return cloneGeoData(await ipapiInFlight.get(lookupIp));
|
|
@@ -10960,7 +11500,12 @@ var require_geolocation = __commonJS({
|
|
|
10960
11500
|
strapi2,
|
|
10961
11501
|
`[magic-sessionmanager/geolocation] ipapi.co is rate-limited; skipping remote lookups for ${Math.ceil(queuedRateLimitRemainingMs / 1e3)}s`
|
|
10962
11502
|
);
|
|
10963
|
-
return this.getFallbackData(
|
|
11503
|
+
return this.getFallbackData(
|
|
11504
|
+
lookupIp,
|
|
11505
|
+
"rate_limited",
|
|
11506
|
+
"ipapi",
|
|
11507
|
+
"Remote GeoIP provider is backing off after HTTP 429"
|
|
11508
|
+
);
|
|
10964
11509
|
}
|
|
10965
11510
|
const controller = new AbortController();
|
|
10966
11511
|
const timer = setTimeout(() => controller.abort(), GEO_API_TIMEOUT_MS);
|
|
@@ -10979,9 +11524,16 @@ var require_geolocation = __commonJS({
|
|
|
10979
11524
|
`[magic-sessionmanager/geolocation] API returned HTTP 429; backing off ipapi.co lookups for ${Math.ceil(backoffMs / 1e3)}s`
|
|
10980
11525
|
);
|
|
10981
11526
|
} else {
|
|
10982
|
-
strapi2.log.warn(
|
|
11527
|
+
strapi2.log.warn(
|
|
11528
|
+
`[magic-sessionmanager/geolocation] API returned HTTP ${response.status}`
|
|
11529
|
+
);
|
|
10983
11530
|
}
|
|
10984
|
-
const fallback = this.getFallbackData(
|
|
11531
|
+
const fallback = this.getFallbackData(
|
|
11532
|
+
lookupIp,
|
|
11533
|
+
reason,
|
|
11534
|
+
"ipapi",
|
|
11535
|
+
`HTTP ${response.status}`
|
|
11536
|
+
);
|
|
10985
11537
|
cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
|
|
10986
11538
|
return fallback;
|
|
10987
11539
|
}
|
|
@@ -11039,7 +11591,10 @@ var require_geolocation = __commonJS({
|
|
|
11039
11591
|
return result;
|
|
11040
11592
|
} catch (error) {
|
|
11041
11593
|
const status = error?.name === "AbortError" ? "error" : "error";
|
|
11042
|
-
strapi2.log.error(
|
|
11594
|
+
strapi2.log.error(
|
|
11595
|
+
"[magic-sessionmanager/geolocation] ipapi lookup failed:",
|
|
11596
|
+
error?.name || "Error"
|
|
11597
|
+
);
|
|
11043
11598
|
const fallback = this.getFallbackData(lookupIp, status, "ipapi", error.message);
|
|
11044
11599
|
cacheIpapiResult(lookupIp, fallback, IPAPI_FAILURE_CACHE_TTL_MS);
|
|
11045
11600
|
return fallback;
|
|
@@ -11156,11 +11711,7 @@ var require_geolocation = __commonJS({
|
|
|
11156
11711
|
var require_notifications = __commonJS({
|
|
11157
11712
|
"server/src/services/notifications.js"(exports, module) {
|
|
11158
11713
|
"use strict";
|
|
11159
|
-
var ALLOWED_WEBHOOK_HOSTS = [
|
|
11160
|
-
"discord.com",
|
|
11161
|
-
"discordapp.com",
|
|
11162
|
-
"hooks.slack.com"
|
|
11163
|
-
];
|
|
11714
|
+
var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
|
|
11164
11715
|
var WEBHOOK_TIMEOUT_MS = 5e3;
|
|
11165
11716
|
module.exports = ({ strapi: strapi2 }) => ({
|
|
11166
11717
|
/**
|
|
@@ -11184,8 +11735,10 @@ var require_notifications = __commonJS({
|
|
|
11184
11735
|
return settings.emailTemplates;
|
|
11185
11736
|
}
|
|
11186
11737
|
}
|
|
11187
|
-
} catch
|
|
11188
|
-
strapi2.log.warn(
|
|
11738
|
+
} catch {
|
|
11739
|
+
strapi2.log.warn(
|
|
11740
|
+
"[magic-sessionmanager/notifications] Could not load templates from DB; using defaults"
|
|
11741
|
+
);
|
|
11189
11742
|
}
|
|
11190
11743
|
strapi2.log.debug("[magic-sessionmanager/notifications] Using default fallback templates");
|
|
11191
11744
|
return {
|
|
@@ -11303,7 +11856,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
11303
11856
|
result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
|
|
11304
11857
|
result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
|
|
11305
11858
|
result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
|
|
11306
|
-
result = result.replace(
|
|
11859
|
+
result = result.replace(
|
|
11860
|
+
/\{\{reason\.securityScore\}\}/g,
|
|
11861
|
+
esc(String(data.reason?.securityScore || "0"))
|
|
11862
|
+
);
|
|
11307
11863
|
return result;
|
|
11308
11864
|
},
|
|
11309
11865
|
/**
|
|
@@ -11327,7 +11883,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
11327
11883
|
strapi2.log.info("[magic-sessionmanager/notifications] Suspicious login alert sent");
|
|
11328
11884
|
return true;
|
|
11329
11885
|
} catch (err) {
|
|
11330
|
-
strapi2.log.error(
|
|
11886
|
+
strapi2.log.error(
|
|
11887
|
+
"[magic-sessionmanager/notifications] Email alert failed:",
|
|
11888
|
+
err?.name || "Error"
|
|
11889
|
+
);
|
|
11331
11890
|
return false;
|
|
11332
11891
|
}
|
|
11333
11892
|
},
|
|
@@ -11352,7 +11911,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
11352
11911
|
strapi2.log.info("[magic-sessionmanager/notifications] New location alert sent");
|
|
11353
11912
|
return true;
|
|
11354
11913
|
} catch (err) {
|
|
11355
|
-
strapi2.log.error(
|
|
11914
|
+
strapi2.log.error(
|
|
11915
|
+
"[magic-sessionmanager/notifications] New-location email failed:",
|
|
11916
|
+
err?.name || "Error"
|
|
11917
|
+
);
|
|
11356
11918
|
return false;
|
|
11357
11919
|
}
|
|
11358
11920
|
},
|
|
@@ -11377,7 +11939,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
11377
11939
|
strapi2.log.info("[magic-sessionmanager/notifications] VPN/Proxy alert sent");
|
|
11378
11940
|
return true;
|
|
11379
11941
|
} catch (err) {
|
|
11380
|
-
strapi2.log.error(
|
|
11942
|
+
strapi2.log.error(
|
|
11943
|
+
"[magic-sessionmanager/notifications] VPN/Proxy email failed:",
|
|
11944
|
+
err?.name || "Error"
|
|
11945
|
+
);
|
|
11381
11946
|
return false;
|
|
11382
11947
|
}
|
|
11383
11948
|
},
|
|
@@ -11401,7 +11966,9 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
11401
11966
|
try {
|
|
11402
11967
|
try {
|
|
11403
11968
|
const parsed = new URL(webhookUrl);
|
|
11404
|
-
const isAllowed = parsed.protocol === "https:" && ALLOWED_WEBHOOK_HOSTS.some(
|
|
11969
|
+
const isAllowed = parsed.protocol === "https:" && ALLOWED_WEBHOOK_HOSTS.some(
|
|
11970
|
+
(h) => parsed.hostname === h || parsed.hostname.endsWith(`.${h}`)
|
|
11971
|
+
);
|
|
11405
11972
|
if (!isAllowed) {
|
|
11406
11973
|
strapi2.log.warn("[magic-sessionmanager/notifications] Blocked webhook to untrusted host");
|
|
11407
11974
|
return false;
|
|
@@ -11433,7 +12000,10 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
11433
12000
|
clearTimeout(timer);
|
|
11434
12001
|
}
|
|
11435
12002
|
} catch (err) {
|
|
11436
|
-
strapi2.log.error(
|
|
12003
|
+
strapi2.log.error(
|
|
12004
|
+
"[magic-sessionmanager/notifications] Webhook request failed:",
|
|
12005
|
+
err?.name || "Error"
|
|
12006
|
+
);
|
|
11437
12007
|
return false;
|
|
11438
12008
|
}
|
|
11439
12009
|
},
|
|
@@ -11626,38 +12196,56 @@ var require_rate_limit = __commonJS({
|
|
|
11626
12196
|
if (tokenId) return `t:${String(tokenId).slice(-16)}`;
|
|
11627
12197
|
return `ip:${ctx.request.ip || ctx.ip || "unknown"}`;
|
|
11628
12198
|
};
|
|
12199
|
+
var routeKey = (ctx) => {
|
|
12200
|
+
const route = ctx.state?.route;
|
|
12201
|
+
const method = String(route?.method || ctx.method || "").toUpperCase();
|
|
12202
|
+
if (route && typeof route.path === "string") {
|
|
12203
|
+
const plugin = route.info?.pluginName || route.plugin || "";
|
|
12204
|
+
const handler = typeof route.handler === "string" ? route.handler : "";
|
|
12205
|
+
return `${method} ${plugin}:${handler}:${route.path.toLowerCase()}`;
|
|
12206
|
+
}
|
|
12207
|
+
const rawPath = String(ctx.path || "").toLowerCase();
|
|
12208
|
+
const normalizedPath = rawPath.length > 1 ? rawPath.replace(/\/+$/, "") || "/" : rawPath;
|
|
12209
|
+
return `${method} path:${normalizedPath}`;
|
|
12210
|
+
};
|
|
11629
12211
|
var RESOLVED_TTL_MS = 3e4;
|
|
11630
|
-
var resolvedCache =
|
|
11631
|
-
var resolvedAt = 0;
|
|
12212
|
+
var resolvedCache = /* @__PURE__ */ new Map();
|
|
11632
12213
|
async function resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) {
|
|
11633
12214
|
const now = Date.now();
|
|
11634
|
-
|
|
11635
|
-
|
|
11636
|
-
|
|
11637
|
-
|
|
11638
|
-
}
|
|
12215
|
+
const cacheKey = `${profile}:${routeMax}:${routeWindowMs}`;
|
|
12216
|
+
const cachedEntry = resolvedCache.get(cacheKey);
|
|
12217
|
+
if (cachedEntry && now - cachedEntry.at < RESOLVED_TTL_MS) {
|
|
12218
|
+
return { max: cachedEntry.max, windowMs: cachedEntry.windowMs };
|
|
11639
12219
|
}
|
|
11640
|
-
let settings
|
|
12220
|
+
let settings;
|
|
11641
12221
|
try {
|
|
11642
12222
|
settings = await getPluginSettings(strapi2);
|
|
11643
12223
|
} catch {
|
|
11644
12224
|
settings = {};
|
|
11645
12225
|
}
|
|
11646
|
-
const
|
|
11647
|
-
|
|
11648
|
-
|
|
11649
|
-
|
|
11650
|
-
|
|
11651
|
-
|
|
11652
|
-
|
|
11653
|
-
|
|
11654
|
-
|
|
11655
|
-
|
|
11656
|
-
|
|
11657
|
-
|
|
11658
|
-
|
|
11659
|
-
|
|
11660
|
-
|
|
12226
|
+
const settingsWindowMs = Number.isFinite(settings.rateLimitWindowSeconds) ? Math.max(1e4, settings.rateLimitWindowSeconds * 1e3) : routeWindowMs;
|
|
12227
|
+
let resolved;
|
|
12228
|
+
if (profile === "write") {
|
|
12229
|
+
resolved = {
|
|
12230
|
+
max: Math.min(
|
|
12231
|
+
routeMax,
|
|
12232
|
+
Number.isFinite(settings.rateLimitWriteMax) ? settings.rateLimitWriteMax : routeMax
|
|
12233
|
+
),
|
|
12234
|
+
windowMs: Math.max(routeWindowMs, settingsWindowMs)
|
|
12235
|
+
};
|
|
12236
|
+
} else if (profile === "read") {
|
|
12237
|
+
resolved = {
|
|
12238
|
+
max: Math.max(
|
|
12239
|
+
routeMax,
|
|
12240
|
+
Number.isFinite(settings.rateLimitReadMax) ? settings.rateLimitReadMax : routeMax
|
|
12241
|
+
),
|
|
12242
|
+
windowMs: settingsWindowMs
|
|
12243
|
+
};
|
|
12244
|
+
} else {
|
|
12245
|
+
resolved = { max: routeMax, windowMs: routeWindowMs };
|
|
12246
|
+
}
|
|
12247
|
+
resolvedCache.set(cacheKey, { ...resolved, at: now });
|
|
12248
|
+
return resolved;
|
|
11661
12249
|
}
|
|
11662
12250
|
var rateLimit = (cfg = {}, { strapi: strapi2 }) => {
|
|
11663
12251
|
const routeMax = Number.isFinite(cfg.max) ? cfg.max : 30;
|
|
@@ -11665,7 +12253,7 @@ var require_rate_limit = __commonJS({
|
|
|
11665
12253
|
const profile = cfg.profile === "read" || cfg.profile === "write" ? cfg.profile : null;
|
|
11666
12254
|
return async (ctx, next) => {
|
|
11667
12255
|
const { max, windowMs } = profile ? await resolveLimits({ profile, routeMax, routeWindowMs, strapi: strapi2 }) : { max: routeMax, windowMs: routeWindowMs };
|
|
11668
|
-
const key = `${ctx
|
|
12256
|
+
const key = `${routeKey(ctx)}::${callerKey(ctx)}`;
|
|
11669
12257
|
const now = Date.now();
|
|
11670
12258
|
if (buckets.size > 5e3) prune(now);
|
|
11671
12259
|
let entry = buckets.get(key);
|
|
@@ -11693,6 +12281,14 @@ var require_rate_limit = __commonJS({
|
|
|
11693
12281
|
await next();
|
|
11694
12282
|
};
|
|
11695
12283
|
};
|
|
12284
|
+
rateLimit.__private = {
|
|
12285
|
+
resolveLimits,
|
|
12286
|
+
routeKey,
|
|
12287
|
+
reset() {
|
|
12288
|
+
buckets.clear();
|
|
12289
|
+
resolvedCache.clear();
|
|
12290
|
+
}
|
|
12291
|
+
};
|
|
11696
12292
|
module.exports = rateLimit;
|
|
11697
12293
|
}
|
|
11698
12294
|
});
|
|
@@ -11719,21 +12315,30 @@ var require_session_required = __commonJS({
|
|
|
11719
12315
|
var { getPluginSettings } = require_settings_loader();
|
|
11720
12316
|
var { extractBearerToken } = require_extract_token();
|
|
11721
12317
|
var { hashToken } = require_encryption();
|
|
12318
|
+
var JWT_MANAGEMENT_CONFIG = "plugin::users-permissions.jwtManagement";
|
|
12319
|
+
function getVerifiedNativeSessionId(policyContext) {
|
|
12320
|
+
const value = policyContext?.state?.session?.id ?? policyContext?.state?.auth?.credentials?.sessionId;
|
|
12321
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
12322
|
+
}
|
|
11722
12323
|
module.exports = async (policyContext, _policyConfig, { strapi: strapi2 }) => {
|
|
11723
12324
|
if (!policyContext.state.user) {
|
|
11724
12325
|
return true;
|
|
11725
12326
|
}
|
|
11726
12327
|
const user = policyContext.state.user;
|
|
12328
|
+
let strictMode = true;
|
|
11727
12329
|
try {
|
|
12330
|
+
const settings = await getPluginSettings(strapi2);
|
|
12331
|
+
strictMode = settings.strictSessionEnforcement === true;
|
|
11728
12332
|
let userDocId = user.documentId;
|
|
11729
12333
|
if (!userDocId && user.id) {
|
|
11730
12334
|
userDocId = await resolveUserDocumentId(strapi2, user.id);
|
|
11731
12335
|
}
|
|
11732
12336
|
if (!userDocId) {
|
|
12337
|
+
if (strictMode) {
|
|
12338
|
+
throw new errors.UnauthorizedError("No valid session. Please login again.");
|
|
12339
|
+
}
|
|
11733
12340
|
return true;
|
|
11734
12341
|
}
|
|
11735
|
-
const settings = await getPluginSettings(strapi2);
|
|
11736
|
-
const strictMode = settings.strictSessionEnforcement === true;
|
|
11737
12342
|
const token = extractBearerToken(policyContext);
|
|
11738
12343
|
const tokenHashValue = token ? hashToken(token) : null;
|
|
11739
12344
|
if (!tokenHashValue) {
|
|
@@ -11743,29 +12348,53 @@ var require_session_required = __commonJS({
|
|
|
11743
12348
|
}
|
|
11744
12349
|
return true;
|
|
11745
12350
|
}
|
|
12351
|
+
const nativeMode = strapi2.config?.get?.(JWT_MANAGEMENT_CONFIG, "legacy-support") === "refresh";
|
|
12352
|
+
const nativeSessionId = nativeMode ? getVerifiedNativeSessionId(policyContext) : null;
|
|
12353
|
+
if (nativeMode && !nativeSessionId) {
|
|
12354
|
+
if (strictMode) {
|
|
12355
|
+
strapi2.log.info(
|
|
12356
|
+
"[magic-sessionmanager] [POLICY-BLOCKED] No verified native session (strictMode)"
|
|
12357
|
+
);
|
|
12358
|
+
throw new errors.UnauthorizedError("No valid session. Please login again.");
|
|
12359
|
+
}
|
|
12360
|
+
return true;
|
|
12361
|
+
}
|
|
11746
12362
|
const thisSession = await strapi2.documents(SESSION_UID).findFirst({
|
|
11747
|
-
filters: {
|
|
12363
|
+
filters: {
|
|
12364
|
+
user: { documentId: userDocId },
|
|
12365
|
+
tokenHash: tokenHashValue,
|
|
12366
|
+
...nativeSessionId ? { nativeSessionId } : {}
|
|
12367
|
+
},
|
|
11748
12368
|
fields: ["documentId", "isActive", "terminatedManually", "terminationReason"]
|
|
11749
12369
|
});
|
|
11750
12370
|
if (thisSession) {
|
|
11751
12371
|
if (thisSession.isActive === false || thisSession.terminatedManually === true) {
|
|
11752
12372
|
const reason = thisSession.terminationReason || (thisSession.terminatedManually === true ? "manual" : "inactive");
|
|
11753
|
-
strapi2.log.info(
|
|
12373
|
+
strapi2.log.info(
|
|
12374
|
+
`[magic-sessionmanager] [POLICY-BLOCKED] Session inactive (reason: ${reason})`
|
|
12375
|
+
);
|
|
11754
12376
|
throw new errors.UnauthorizedError("Session terminated. Please login again.");
|
|
11755
12377
|
}
|
|
11756
12378
|
return true;
|
|
11757
12379
|
}
|
|
11758
12380
|
if (strictMode) {
|
|
11759
|
-
strapi2.log.info(
|
|
12381
|
+
strapi2.log.info(
|
|
12382
|
+
"[magic-sessionmanager] [POLICY-BLOCKED] No session matches this token (strictMode)"
|
|
12383
|
+
);
|
|
11760
12384
|
throw new errors.UnauthorizedError("No valid session. Please login again.");
|
|
11761
12385
|
}
|
|
11762
|
-
strapi2.log.warn(
|
|
12386
|
+
strapi2.log.warn(
|
|
12387
|
+
"[magic-sessionmanager] [POLICY-WARN] No session for token; allowing in non-strict mode"
|
|
12388
|
+
);
|
|
11763
12389
|
return true;
|
|
11764
12390
|
} catch (err) {
|
|
11765
12391
|
if (err instanceof errors.UnauthorizedError) {
|
|
11766
12392
|
throw err;
|
|
11767
12393
|
}
|
|
11768
12394
|
strapi2.log.debug("[magic-sessionmanager] Session policy check error:", err?.name || "Error");
|
|
12395
|
+
if (strictMode) {
|
|
12396
|
+
throw new errors.UnauthorizedError("No valid session. Please login again.");
|
|
12397
|
+
}
|
|
11769
12398
|
return true;
|
|
11770
12399
|
}
|
|
11771
12400
|
};
|