strapi-plugin-magic-sessionmanager 4.11.0 → 4.12.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 +49 -1
- package/README.md +24 -15
- package/dist/admin/{Analytics-D56O8Q6e.mjs → Analytics-C_c24Uzq.mjs} +45 -75
- package/dist/admin/{Analytics-CBHeWeGn.js → Analytics-lP0-RsVd.js} +45 -75
- package/dist/admin/{App-EDIkLJdb.mjs → App-DCyNPn1k.mjs} +161 -117
- package/dist/admin/{App-D4cBPwB_.js → App-miWDdmdX.js} +161 -117
- package/dist/admin/{OnlineUsersWidget-BF2R2YIy.js → OnlineUsersWidget-C6b7e4jb.js} +18 -26
- package/dist/admin/{OnlineUsersWidget-MwUutkKQ.mjs → OnlineUsersWidget-C6wlwENC.mjs} +18 -26
- package/dist/admin/{Settings-CMzEF8EH.js → Settings-D9zyn5xn.js} +1 -1
- package/dist/admin/{Settings-bLMyi0BN.mjs → Settings-DssYw2W4.mjs} +1 -1
- package/dist/admin/{de-CxfuTF6C.mjs → de--yNl7MPl.mjs} +4 -6
- package/dist/admin/{de-DVNTHmSo.js → de-DjPEATFf.js} +4 -6
- package/dist/admin/{en-BcPIlQYL.mjs → en-5U7g51cH.mjs} +4 -6
- package/dist/admin/{en-BuVXIcHA.js → en-BoO12UQw.js} +4 -6
- package/dist/admin/{es-DxHpaNA1.mjs → es-BJR-zCXL.mjs} +4 -6
- package/dist/admin/{es-CEteHmBO.js → es-BLpEuycJ.js} +4 -6
- package/dist/admin/{fr-BMd2-wW7.js → fr-BE828R9Q.js} +4 -6
- package/dist/admin/{fr-Dw43lHg7.mjs → fr-CeeCYQCs.mjs} +4 -6
- package/dist/admin/{index-DvNfekoR.js → index-CfQOMZVX.js} +9 -46
- package/dist/admin/{index-qa6Qnfkc.mjs → index-rbxJZcLv.mjs} +35 -72
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +2 -2
- package/dist/admin/{pt-BvO63p01.js → pt-BWEFiuvo.js} +4 -6
- package/dist/admin/{pt-7jnxDSX-.mjs → pt-CorrU3yG.mjs} +4 -6
- package/dist/server/index.js +789 -36
- package/dist/server/index.mjs +789 -36
- package/package.json +1 -1
package/dist/server/index.mjs
CHANGED
|
@@ -1913,6 +1913,10 @@ var require_last_seen = __commonJS({
|
|
|
1913
1913
|
if (!ctx.state.user) {
|
|
1914
1914
|
return;
|
|
1915
1915
|
}
|
|
1916
|
+
const strategyName = ctx.state.auth?.strategy?.name;
|
|
1917
|
+
if (strategyName === "admin" || strategyName === "admin-token") {
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1916
1920
|
let userDocId = ctx.state.user.documentId;
|
|
1917
1921
|
if (!userDocId && ctx.state.user.id) {
|
|
1918
1922
|
try {
|
|
@@ -7058,8 +7062,14 @@ var require_bootstrap = __commonJS({
|
|
|
7058
7062
|
const knex = strapi2.db.connection;
|
|
7059
7063
|
const tableName = "magic_sessions";
|
|
7060
7064
|
const definitions = [
|
|
7061
|
-
{
|
|
7062
|
-
{
|
|
7065
|
+
{ columns: ["token_hash", "is_active"], name: "idx_magic_sessions_token_hash" },
|
|
7066
|
+
{ columns: ["refresh_token_hash", "is_active"], name: "idx_magic_sessions_refresh_hash" },
|
|
7067
|
+
{ columns: ["login_time", "id"], name: "idx_magic_sessions_login_time" },
|
|
7068
|
+
{ columns: ["last_active", "id"], name: "idx_magic_sessions_last_active" },
|
|
7069
|
+
{ columns: ["is_active", "last_active"], name: "idx_magic_sessions_active_last" },
|
|
7070
|
+
{ columns: ["is_active", "login_time"], name: "idx_magic_sessions_active_login" },
|
|
7071
|
+
{ columns: ["is_active", "termination_reason"], name: "idx_magic_sessions_active_reason" },
|
|
7072
|
+
{ columns: ["native_session_id"], name: "idx_magic_sessions_native_id" }
|
|
7063
7073
|
];
|
|
7064
7074
|
if (!await knex.schema.hasTable(tableName)) return;
|
|
7065
7075
|
const dialect = strapi2.db.dialect.client;
|
|
@@ -7075,11 +7085,11 @@ var require_bootstrap = __commonJS({
|
|
|
7075
7085
|
log.debug(`[INDEX] ${definition.name} already exists`);
|
|
7076
7086
|
continue;
|
|
7077
7087
|
}
|
|
7078
|
-
|
|
7088
|
+
const placeholders = definition.columns.map(() => "??").join(", ");
|
|
7089
|
+
await knex.raw(`CREATE INDEX IF NOT EXISTS ?? ON ?? (${placeholders})`, [
|
|
7079
7090
|
definition.name,
|
|
7080
7091
|
tableName,
|
|
7081
|
-
definition.
|
|
7082
|
-
"is_active"
|
|
7092
|
+
...definition.columns
|
|
7083
7093
|
]);
|
|
7084
7094
|
log.info(`[INDEX] Created ${definition.name}`);
|
|
7085
7095
|
continue;
|
|
@@ -7097,7 +7107,7 @@ var require_bootstrap = __commonJS({
|
|
|
7097
7107
|
continue;
|
|
7098
7108
|
}
|
|
7099
7109
|
await knex.schema.alterTable(tableName, (table) => {
|
|
7100
|
-
table.index(
|
|
7110
|
+
table.index(definition.columns, definition.name);
|
|
7101
7111
|
});
|
|
7102
7112
|
log.info(`[INDEX] Created ${definition.name}`);
|
|
7103
7113
|
}
|
|
@@ -7820,6 +7830,12 @@ var require_admin = __commonJS({
|
|
|
7820
7830
|
config: { actions: [PLUGIN_ACCESS_ACTION] }
|
|
7821
7831
|
}
|
|
7822
7832
|
];
|
|
7833
|
+
var adminReadRateLimit = () => [
|
|
7834
|
+
{
|
|
7835
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
7836
|
+
config: { profile: "read", max: 120, window: 6e4 }
|
|
7837
|
+
}
|
|
7838
|
+
];
|
|
7823
7839
|
var isDevEnvironment = (() => {
|
|
7824
7840
|
const env = (process.env.NODE_ENV || "development").toLowerCase();
|
|
7825
7841
|
return env !== "production" && env !== "staging";
|
|
@@ -7832,7 +7848,8 @@ var require_admin = __commonJS({
|
|
|
7832
7848
|
handler: "session.getAllSessionsAdmin",
|
|
7833
7849
|
config: {
|
|
7834
7850
|
policies: adminPolicy(),
|
|
7835
|
-
|
|
7851
|
+
middlewares: adminReadRateLimit(),
|
|
7852
|
+
description: "List sessions (admin); paginated with page/pageSize, filters and sort"
|
|
7836
7853
|
}
|
|
7837
7854
|
},
|
|
7838
7855
|
{
|
|
@@ -7841,7 +7858,38 @@ var require_admin = __commonJS({
|
|
|
7841
7858
|
handler: "session.getActiveSessions",
|
|
7842
7859
|
config: {
|
|
7843
7860
|
policies: adminPolicy(),
|
|
7844
|
-
|
|
7861
|
+
middlewares: adminReadRateLimit(),
|
|
7862
|
+
description: "Get only active sessions (admin); paginated with page/pageSize"
|
|
7863
|
+
}
|
|
7864
|
+
},
|
|
7865
|
+
{
|
|
7866
|
+
method: "GET",
|
|
7867
|
+
path: "/sessions/stats",
|
|
7868
|
+
handler: "session.getSessionStatsAdmin",
|
|
7869
|
+
config: {
|
|
7870
|
+
policies: adminPolicy(),
|
|
7871
|
+
middlewares: adminReadRateLimit(),
|
|
7872
|
+
description: "Get count-only session statistics (admin)"
|
|
7873
|
+
}
|
|
7874
|
+
},
|
|
7875
|
+
{
|
|
7876
|
+
method: "GET",
|
|
7877
|
+
path: "/sessions/analytics",
|
|
7878
|
+
handler: "session.getSessionAnalyticsAdmin",
|
|
7879
|
+
config: {
|
|
7880
|
+
policies: adminPolicy(),
|
|
7881
|
+
middlewares: adminReadRateLimit(),
|
|
7882
|
+
description: "Get count-only analytics over all sessions (admin)"
|
|
7883
|
+
}
|
|
7884
|
+
},
|
|
7885
|
+
{
|
|
7886
|
+
method: "GET",
|
|
7887
|
+
path: "/sessions/export",
|
|
7888
|
+
handler: "session.exportSessionsAdmin",
|
|
7889
|
+
config: {
|
|
7890
|
+
policies: adminPolicy(),
|
|
7891
|
+
middlewares: adminReadRateLimit(),
|
|
7892
|
+
description: "Get one export batch of sessions with a keyset cursor (admin)"
|
|
7845
7893
|
}
|
|
7846
7894
|
},
|
|
7847
7895
|
{
|
|
@@ -7904,6 +7952,7 @@ var require_admin = __commonJS({
|
|
|
7904
7952
|
handler: "session.getUserStatsAdmin",
|
|
7905
7953
|
config: {
|
|
7906
7954
|
policies: adminPolicy(),
|
|
7955
|
+
middlewares: adminReadRateLimit(),
|
|
7907
7956
|
description: "Get aggregate end-user counts only (admin)"
|
|
7908
7957
|
}
|
|
7909
7958
|
},
|
|
@@ -8321,6 +8370,529 @@ var require_http_errors = __commonJS({
|
|
|
8321
8370
|
}
|
|
8322
8371
|
});
|
|
8323
8372
|
|
|
8373
|
+
// server/src/utils/session-list-query.js
|
|
8374
|
+
var require_session_list_query = __commonJS({
|
|
8375
|
+
"server/src/utils/session-list-query.js"(exports, module) {
|
|
8376
|
+
"use strict";
|
|
8377
|
+
var { z } = __require("@strapi/utils");
|
|
8378
|
+
var SESSION_STATUS_FILTERS = Object.freeze(["all", "open", "active", "idle", "ended"]);
|
|
8379
|
+
var RECORDED_END_REASONS = Object.freeze(["logout", "idle", "expired", "manual", "blocked"]);
|
|
8380
|
+
var END_REASON_FILTERS = Object.freeze(["all", ...RECORDED_END_REASONS, "unrecorded"]);
|
|
8381
|
+
var SORT_ORDERS = Object.freeze({
|
|
8382
|
+
"loginTime:desc": [{ loginTime: "desc" }, { id: "desc" }],
|
|
8383
|
+
"loginTime:asc": [{ loginTime: "asc" }, { id: "asc" }],
|
|
8384
|
+
"lastActive:desc": [{ lastActive: "desc" }, { id: "desc" }],
|
|
8385
|
+
"lastActive:asc": [{ lastActive: "asc" }, { id: "asc" }]
|
|
8386
|
+
});
|
|
8387
|
+
var SORT_KEYS = Object.freeze(Object.keys(SORT_ORDERS));
|
|
8388
|
+
var MAX_PAGE_SIZE = 100;
|
|
8389
|
+
var MAX_SEARCH_LENGTH = 100;
|
|
8390
|
+
var MAX_LIST_OFFSET = 5e4;
|
|
8391
|
+
var MAX_EXPORT_BATCH = 1e3;
|
|
8392
|
+
var MAX_EXPORT_ROWS = 5e4;
|
|
8393
|
+
var LIST_FIELDS = Object.freeze([
|
|
8394
|
+
"id",
|
|
8395
|
+
"documentId",
|
|
8396
|
+
"sessionId",
|
|
8397
|
+
"nativeSessionId",
|
|
8398
|
+
"ipAddress",
|
|
8399
|
+
"userAgent",
|
|
8400
|
+
"loginTime",
|
|
8401
|
+
"logoutTime",
|
|
8402
|
+
"lastActive",
|
|
8403
|
+
"isActive",
|
|
8404
|
+
"terminatedManually",
|
|
8405
|
+
"terminationReason",
|
|
8406
|
+
"geoLocation",
|
|
8407
|
+
"securityScore",
|
|
8408
|
+
"deviceType",
|
|
8409
|
+
"browserName",
|
|
8410
|
+
"osName",
|
|
8411
|
+
"createdAt",
|
|
8412
|
+
"updatedAt"
|
|
8413
|
+
]);
|
|
8414
|
+
var LIST_USER_FIELDS = Object.freeze(["documentId", "email", "username"]);
|
|
8415
|
+
var searchText = z.string().trim().max(MAX_SEARCH_LENGTH, `search must be at most ${MAX_SEARCH_LENGTH} characters`);
|
|
8416
|
+
var filterShape = {
|
|
8417
|
+
status: z.enum(SESSION_STATUS_FILTERS).default("all"),
|
|
8418
|
+
reason: z.enum(END_REASON_FILTERS).default("all"),
|
|
8419
|
+
search: searchText.default("")
|
|
8420
|
+
};
|
|
8421
|
+
var listQuerySchema = z.strictObject({
|
|
8422
|
+
page: z.coerce.number().int().min(1).max(1e6).default(1),
|
|
8423
|
+
pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(25),
|
|
8424
|
+
sort: z.enum(SORT_KEYS).default("loginTime:desc"),
|
|
8425
|
+
...filterShape
|
|
8426
|
+
}).refine((query) => (query.page - 1) * query.pageSize < MAX_LIST_OFFSET, {
|
|
8427
|
+
message: `Pages past the first ${MAX_LIST_OFFSET} sessions are not available. Narrow the filter or use the export.`,
|
|
8428
|
+
path: ["page"]
|
|
8429
|
+
});
|
|
8430
|
+
var exportQuerySchema = z.strictObject({
|
|
8431
|
+
limit: z.coerce.number().int().min(1).max(MAX_EXPORT_BATCH).default(MAX_EXPORT_BATCH),
|
|
8432
|
+
cursor: z.string().max(200).optional(),
|
|
8433
|
+
...filterShape
|
|
8434
|
+
});
|
|
8435
|
+
var statsQuerySchema = z.strictObject({});
|
|
8436
|
+
function isPaginatedListQuery(query) {
|
|
8437
|
+
return Boolean(
|
|
8438
|
+
query && (Object.prototype.hasOwnProperty.call(query, "page") || Object.prototype.hasOwnProperty.call(query, "pageSize"))
|
|
8439
|
+
);
|
|
8440
|
+
}
|
|
8441
|
+
function parseQuery(schema, input) {
|
|
8442
|
+
const result = schema.safeParse(input ?? {});
|
|
8443
|
+
if (result.success) return { ok: true, value: result.data };
|
|
8444
|
+
return {
|
|
8445
|
+
ok: false,
|
|
8446
|
+
errors: result.error.issues.map((issue) => ({
|
|
8447
|
+
path: issue.path.join("."),
|
|
8448
|
+
message: issue.message
|
|
8449
|
+
}))
|
|
8450
|
+
};
|
|
8451
|
+
}
|
|
8452
|
+
function usedSince(cutoff) {
|
|
8453
|
+
return {
|
|
8454
|
+
$or: [
|
|
8455
|
+
{ lastActive: { $gt: cutoff } },
|
|
8456
|
+
{ $and: [{ lastActive: { $null: true } }, { loginTime: { $gt: cutoff } }] }
|
|
8457
|
+
]
|
|
8458
|
+
};
|
|
8459
|
+
}
|
|
8460
|
+
function notUsedSince(cutoff) {
|
|
8461
|
+
return {
|
|
8462
|
+
$or: [
|
|
8463
|
+
{ lastActive: { $lte: cutoff } },
|
|
8464
|
+
{ $and: [{ lastActive: { $null: true } }, { loginTime: { $lte: cutoff } }] }
|
|
8465
|
+
]
|
|
8466
|
+
};
|
|
8467
|
+
}
|
|
8468
|
+
function buildSessionWhere({ status = "all", reason = "all", search = "" } = {}, { cutoff }) {
|
|
8469
|
+
const conditions = [];
|
|
8470
|
+
if (status === "open") conditions.push({ isActive: true });
|
|
8471
|
+
if (status === "active") conditions.push({ isActive: true }, usedSince(cutoff));
|
|
8472
|
+
if (status === "idle") conditions.push({ isActive: true }, notUsedSince(cutoff));
|
|
8473
|
+
if (status === "ended") {
|
|
8474
|
+
conditions.push({ isActive: false });
|
|
8475
|
+
if (reason === "unrecorded") {
|
|
8476
|
+
conditions.push({
|
|
8477
|
+
$or: [
|
|
8478
|
+
{ terminationReason: { $null: true } },
|
|
8479
|
+
{ terminationReason: { $notIn: [...RECORDED_END_REASONS] } }
|
|
8480
|
+
]
|
|
8481
|
+
});
|
|
8482
|
+
} else if (RECORDED_END_REASONS.includes(reason)) {
|
|
8483
|
+
conditions.push({ terminationReason: reason });
|
|
8484
|
+
}
|
|
8485
|
+
}
|
|
8486
|
+
if (search) {
|
|
8487
|
+
conditions.push({
|
|
8488
|
+
$or: [
|
|
8489
|
+
{ user: { email: { $containsi: search } } },
|
|
8490
|
+
{ user: { username: { $containsi: search } } },
|
|
8491
|
+
{ ipAddress: { $containsi: search } },
|
|
8492
|
+
{ browserName: { $containsi: search } },
|
|
8493
|
+
{ osName: { $containsi: search } },
|
|
8494
|
+
{ deviceType: { $containsi: search } }
|
|
8495
|
+
]
|
|
8496
|
+
});
|
|
8497
|
+
}
|
|
8498
|
+
return conditions.length ? { $and: conditions } : {};
|
|
8499
|
+
}
|
|
8500
|
+
function encodeExportCursor(row) {
|
|
8501
|
+
const time = row.loginTime ? new Date(row.loginTime).toISOString() : null;
|
|
8502
|
+
return Buffer.from(JSON.stringify([time, Number(row.id)])).toString("base64url");
|
|
8503
|
+
}
|
|
8504
|
+
function decodeExportCursor(cursor) {
|
|
8505
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
8506
|
+
if (!/^[A-Za-z0-9_-]+$/.test(cursor)) return false;
|
|
8507
|
+
try {
|
|
8508
|
+
const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
8509
|
+
if (!Array.isArray(value) || value.length !== 2) return false;
|
|
8510
|
+
const [time, id] = value;
|
|
8511
|
+
if (!Number.isSafeInteger(id) || id < 1) return false;
|
|
8512
|
+
if (time === null) return { loginTime: null, id };
|
|
8513
|
+
if (typeof time !== "string" || Number.isNaN(Date.parse(time))) return false;
|
|
8514
|
+
return { loginTime: new Date(time), id };
|
|
8515
|
+
} catch {
|
|
8516
|
+
return false;
|
|
8517
|
+
}
|
|
8518
|
+
}
|
|
8519
|
+
function afterExportCursor(cursor) {
|
|
8520
|
+
if (cursor.loginTime === null) return { id: { $lt: cursor.id } };
|
|
8521
|
+
return {
|
|
8522
|
+
$or: [
|
|
8523
|
+
{ loginTime: { $lt: cursor.loginTime } },
|
|
8524
|
+
{ $and: [{ loginTime: cursor.loginTime }, { id: { $lt: cursor.id } }] }
|
|
8525
|
+
]
|
|
8526
|
+
};
|
|
8527
|
+
}
|
|
8528
|
+
module.exports = {
|
|
8529
|
+
SESSION_STATUS_FILTERS,
|
|
8530
|
+
RECORDED_END_REASONS,
|
|
8531
|
+
END_REASON_FILTERS,
|
|
8532
|
+
SORT_ORDERS,
|
|
8533
|
+
SORT_KEYS,
|
|
8534
|
+
MAX_PAGE_SIZE,
|
|
8535
|
+
MAX_SEARCH_LENGTH,
|
|
8536
|
+
MAX_LIST_OFFSET,
|
|
8537
|
+
MAX_EXPORT_BATCH,
|
|
8538
|
+
MAX_EXPORT_ROWS,
|
|
8539
|
+
LIST_FIELDS,
|
|
8540
|
+
LIST_USER_FIELDS,
|
|
8541
|
+
listQuerySchema,
|
|
8542
|
+
exportQuerySchema,
|
|
8543
|
+
statsQuerySchema,
|
|
8544
|
+
isPaginatedListQuery,
|
|
8545
|
+
parseQuery,
|
|
8546
|
+
buildSessionWhere,
|
|
8547
|
+
encodeExportCursor,
|
|
8548
|
+
decodeExportCursor,
|
|
8549
|
+
afterExportCursor
|
|
8550
|
+
};
|
|
8551
|
+
}
|
|
8552
|
+
});
|
|
8553
|
+
|
|
8554
|
+
// server/src/utils/session-list.js
|
|
8555
|
+
var require_session_list = __commonJS({
|
|
8556
|
+
"server/src/utils/session-list.js"(exports, module) {
|
|
8557
|
+
"use strict";
|
|
8558
|
+
var { enhanceSessions } = require_enhance_session();
|
|
8559
|
+
var { getNativeSessionManager } = require_native_session_manager();
|
|
8560
|
+
var {
|
|
8561
|
+
LIST_FIELDS,
|
|
8562
|
+
LIST_USER_FIELDS,
|
|
8563
|
+
MAX_EXPORT_BATCH,
|
|
8564
|
+
SORT_ORDERS,
|
|
8565
|
+
buildSessionWhere,
|
|
8566
|
+
afterExportCursor,
|
|
8567
|
+
encodeExportCursor
|
|
8568
|
+
} = require_session_list_query();
|
|
8569
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
8570
|
+
var NATIVE_SESSION_UID = "admin::session";
|
|
8571
|
+
var NATIVE_ORIGIN = "users-permissions";
|
|
8572
|
+
var NATIVE_CHECK_CONCURRENCY = 8;
|
|
8573
|
+
var STATS_CACHE_MS = 5e3;
|
|
8574
|
+
var statsCache = /* @__PURE__ */ new WeakMap();
|
|
8575
|
+
function clearSessionStatsCache() {
|
|
8576
|
+
statsCache = /* @__PURE__ */ new WeakMap();
|
|
8577
|
+
}
|
|
8578
|
+
function cacheFor(strapi2) {
|
|
8579
|
+
let map = statsCache.get(strapi2);
|
|
8580
|
+
if (!map) {
|
|
8581
|
+
map = /* @__PURE__ */ new Map();
|
|
8582
|
+
statsCache.set(strapi2, map);
|
|
8583
|
+
}
|
|
8584
|
+
return map;
|
|
8585
|
+
}
|
|
8586
|
+
function inactivityCutoff(inactivityTimeout, now = Date.now()) {
|
|
8587
|
+
return new Date(now - inactivityTimeout);
|
|
8588
|
+
}
|
|
8589
|
+
function hasNativeSessionTable(strapi2) {
|
|
8590
|
+
return Boolean(strapi2?.contentTypes?.[NATIVE_SESSION_UID]);
|
|
8591
|
+
}
|
|
8592
|
+
async function findActiveNativeIds(strapi2, nativeManager, ids) {
|
|
8593
|
+
const unique = [...new Set(ids.filter((id) => typeof id === "string" && id))];
|
|
8594
|
+
if (unique.length === 0) return /* @__PURE__ */ new Set();
|
|
8595
|
+
if (hasNativeSessionTable(strapi2)) {
|
|
8596
|
+
const rows = await strapi2.db.query(NATIVE_SESSION_UID).findMany({
|
|
8597
|
+
select: ["sessionId"],
|
|
8598
|
+
where: {
|
|
8599
|
+
sessionId: { $in: unique },
|
|
8600
|
+
origin: NATIVE_ORIGIN,
|
|
8601
|
+
status: "active",
|
|
8602
|
+
expiresAt: { $gt: /* @__PURE__ */ new Date() }
|
|
8603
|
+
}
|
|
8604
|
+
});
|
|
8605
|
+
return new Set((Array.isArray(rows) ? rows : []).map((row) => String(row.sessionId)));
|
|
8606
|
+
}
|
|
8607
|
+
const active = /* @__PURE__ */ new Set();
|
|
8608
|
+
let next = 0;
|
|
8609
|
+
const worker = async () => {
|
|
8610
|
+
while (next < unique.length) {
|
|
8611
|
+
const id = unique[next++];
|
|
8612
|
+
if (await nativeManager.isSessionActive(id)) active.add(id);
|
|
8613
|
+
}
|
|
8614
|
+
};
|
|
8615
|
+
await Promise.all(
|
|
8616
|
+
Array.from({ length: Math.min(NATIVE_CHECK_CONCURRENCY, unique.length) }, worker)
|
|
8617
|
+
);
|
|
8618
|
+
return active;
|
|
8619
|
+
}
|
|
8620
|
+
async function reconcileNativeRows(strapi2, rows) {
|
|
8621
|
+
const nativeManager = getNativeSessionManager(strapi2);
|
|
8622
|
+
if (!nativeManager) return rows;
|
|
8623
|
+
const ids = rows.filter((row) => row.isActive && row.nativeSessionId).map((row) => String(row.nativeSessionId));
|
|
8624
|
+
if (ids.length === 0) return rows;
|
|
8625
|
+
const active = await findActiveNativeIds(strapi2, nativeManager, ids);
|
|
8626
|
+
return rows.map(
|
|
8627
|
+
(row) => row.isActive && row.nativeSessionId && !active.has(String(row.nativeSessionId)) ? { ...row, isActive: false } : row
|
|
8628
|
+
);
|
|
8629
|
+
}
|
|
8630
|
+
async function countNativeOnlySessions(strapi2) {
|
|
8631
|
+
if (!getNativeSessionManager(strapi2) || !hasNativeSessionTable(strapi2)) return 0;
|
|
8632
|
+
const knex = strapi2.db.connection;
|
|
8633
|
+
const nativeMeta = strapi2.db.metadata.get(NATIVE_SESSION_UID);
|
|
8634
|
+
const sessionMeta = strapi2.db.metadata.get(SESSION_UID);
|
|
8635
|
+
const column = (meta, attribute) => meta.attributes[attribute]?.columnName || attribute;
|
|
8636
|
+
const nativeTable = nativeMeta.tableName;
|
|
8637
|
+
const sessionTable = sessionMeta.tableName;
|
|
8638
|
+
const nativeIdColumn = column(nativeMeta, "sessionId");
|
|
8639
|
+
const linkedColumn = column(sessionMeta, "nativeSessionId");
|
|
8640
|
+
const result = await knex(nativeTable).where(column(nativeMeta, "origin"), NATIVE_ORIGIN).andWhere(column(nativeMeta, "status"), "active").andWhere(column(nativeMeta, "expiresAt"), ">", /* @__PURE__ */ new Date()).whereNotExists(function linked() {
|
|
8641
|
+
this.select(knex.raw("1")).from(sessionTable).whereRaw("??.?? = ??.??", [sessionTable, linkedColumn, nativeTable, nativeIdColumn]);
|
|
8642
|
+
}).count({ count: "*" }).first();
|
|
8643
|
+
return Number(result?.count ?? 0);
|
|
8644
|
+
}
|
|
8645
|
+
async function countUsersOnline(strapi2, cutoff) {
|
|
8646
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
8647
|
+
const userAttribute = meta.attributes.user;
|
|
8648
|
+
const joinTable = userAttribute?.joinTable;
|
|
8649
|
+
const column = (attribute) => meta.attributes[attribute]?.columnName || attribute;
|
|
8650
|
+
const knex = strapi2.db.connection;
|
|
8651
|
+
const table = meta.tableName;
|
|
8652
|
+
if (joinTable?.name && joinTable.joinColumn?.name && joinTable.inverseJoinColumn?.name) {
|
|
8653
|
+
const link = joinTable.name;
|
|
8654
|
+
const lastActive = `${table}.${column("lastActive")}`;
|
|
8655
|
+
const loginTime = `${table}.${column("loginTime")}`;
|
|
8656
|
+
const result = await knex(table).join(link, `${link}.${joinTable.joinColumn.name}`, `${table}.id`).where(`${table}.${column("isActive")}`, true).andWhere((qb) => {
|
|
8657
|
+
qb.where(lastActive, ">", cutoff).orWhere((inner) => {
|
|
8658
|
+
inner.whereNull(lastActive).andWhere(loginTime, ">", cutoff);
|
|
8659
|
+
});
|
|
8660
|
+
}).countDistinct({ count: `${link}.${joinTable.inverseJoinColumn.name}` }).first();
|
|
8661
|
+
return Number(result?.count ?? 0);
|
|
8662
|
+
}
|
|
8663
|
+
const seen = /* @__PURE__ */ new Set();
|
|
8664
|
+
const where = buildSessionWhere({ status: "active" }, { cutoff });
|
|
8665
|
+
for (let offset = 0; ; offset += MAX_EXPORT_BATCH) {
|
|
8666
|
+
const rows = await strapi2.db.query(SESSION_UID).findMany({
|
|
8667
|
+
where,
|
|
8668
|
+
select: ["id"],
|
|
8669
|
+
populate: { user: { select: ["id"] } },
|
|
8670
|
+
orderBy: [{ id: "asc" }],
|
|
8671
|
+
offset,
|
|
8672
|
+
limit: MAX_EXPORT_BATCH
|
|
8673
|
+
});
|
|
8674
|
+
for (const row of rows) if (row.user?.id) seen.add(row.user.id);
|
|
8675
|
+
if (rows.length < MAX_EXPORT_BATCH) break;
|
|
8676
|
+
}
|
|
8677
|
+
return seen.size;
|
|
8678
|
+
}
|
|
8679
|
+
async function listSessionPage(strapi2, query, options) {
|
|
8680
|
+
const cutoff = inactivityCutoff(options.inactivityTimeout);
|
|
8681
|
+
const where = buildSessionWhere(query, { cutoff });
|
|
8682
|
+
const sessions = strapi2.db.query(SESSION_UID);
|
|
8683
|
+
const offset = (query.page - 1) * query.pageSize;
|
|
8684
|
+
const [total, rows] = await Promise.all([
|
|
8685
|
+
sessions.count({ where }),
|
|
8686
|
+
sessions.findMany({
|
|
8687
|
+
where,
|
|
8688
|
+
select: [...LIST_FIELDS],
|
|
8689
|
+
populate: { user: { select: [...LIST_USER_FIELDS] } },
|
|
8690
|
+
orderBy: SORT_ORDERS[query.sort] || SORT_ORDERS["loginTime:desc"],
|
|
8691
|
+
offset,
|
|
8692
|
+
limit: query.pageSize
|
|
8693
|
+
})
|
|
8694
|
+
]);
|
|
8695
|
+
const reconciled = await reconcileNativeRows(strapi2, Array.isArray(rows) ? rows : []);
|
|
8696
|
+
const enhanced = await enhanceSessions(
|
|
8697
|
+
reconciled,
|
|
8698
|
+
{
|
|
8699
|
+
inactivityTimeout: options.inactivityTimeout,
|
|
8700
|
+
geolocationService: options.geolocationService || null,
|
|
8701
|
+
strapi: strapi2
|
|
8702
|
+
},
|
|
8703
|
+
Math.min(20, query.pageSize)
|
|
8704
|
+
);
|
|
8705
|
+
const count = Number(total) || 0;
|
|
8706
|
+
return {
|
|
8707
|
+
rows: enhanced,
|
|
8708
|
+
pagination: {
|
|
8709
|
+
page: query.page,
|
|
8710
|
+
pageSize: query.pageSize,
|
|
8711
|
+
total: count,
|
|
8712
|
+
pageCount: Math.max(1, Math.ceil(count / query.pageSize))
|
|
8713
|
+
}
|
|
8714
|
+
};
|
|
8715
|
+
}
|
|
8716
|
+
async function getSessionStats(strapi2, { inactivityTimeout }) {
|
|
8717
|
+
const key = String(inactivityTimeout);
|
|
8718
|
+
const cache = cacheFor(strapi2);
|
|
8719
|
+
const cached = cache.get(key);
|
|
8720
|
+
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
8721
|
+
const cutoff = inactivityCutoff(inactivityTimeout);
|
|
8722
|
+
const sessions = strapi2.db.query(SESSION_UID);
|
|
8723
|
+
const count = (filters) => sessions.count({ where: buildSessionWhere(filters, { cutoff }) });
|
|
8724
|
+
const [total, open, active, loggedOut, timedOut, usersOnline, nativeOnly] = await Promise.all([
|
|
8725
|
+
count({}),
|
|
8726
|
+
count({ status: "open" }),
|
|
8727
|
+
count({ status: "active" }),
|
|
8728
|
+
count({ status: "ended", reason: "logout" }),
|
|
8729
|
+
count({ status: "ended", reason: "idle" }),
|
|
8730
|
+
countUsersOnline(strapi2, cutoff),
|
|
8731
|
+
countNativeOnlySessions(strapi2)
|
|
8732
|
+
]);
|
|
8733
|
+
const ended = Math.max(0, Number(total) - Number(open));
|
|
8734
|
+
const value = {
|
|
8735
|
+
total: Number(total),
|
|
8736
|
+
open: Number(open),
|
|
8737
|
+
active: Number(active),
|
|
8738
|
+
idle: Math.max(0, Number(open) - Number(active)),
|
|
8739
|
+
ended,
|
|
8740
|
+
loggedOut: Number(loggedOut),
|
|
8741
|
+
timedOut: Number(timedOut),
|
|
8742
|
+
otherReasons: Math.max(0, ended - Number(loggedOut) - Number(timedOut)),
|
|
8743
|
+
usersOnline: Number(usersOnline),
|
|
8744
|
+
nativeOnly: Number(nativeOnly)
|
|
8745
|
+
};
|
|
8746
|
+
cache.set(key, { value, expiresAt: Date.now() + STATS_CACHE_MS });
|
|
8747
|
+
if (cache.size > 20) cache.delete(cache.keys().next().value);
|
|
8748
|
+
return value;
|
|
8749
|
+
}
|
|
8750
|
+
var ANALYTICS_CACHE_MS = 3e4;
|
|
8751
|
+
var MAX_GROUPS = 200;
|
|
8752
|
+
async function countByColumn(strapi2, attribute) {
|
|
8753
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
8754
|
+
const column = meta.attributes[attribute]?.columnName || attribute;
|
|
8755
|
+
const rows = await strapi2.db.connection(meta.tableName).select({ value: column }).count({ count: "*" }).groupBy(column).orderBy("count", "desc").limit(MAX_GROUPS);
|
|
8756
|
+
return rows.map((row) => ({ value: row.value ?? null, count: Number(row.count) || 0 }));
|
|
8757
|
+
}
|
|
8758
|
+
async function averageSessionMinutes(strapi2, now) {
|
|
8759
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
8760
|
+
const col = (attribute) => meta.attributes[attribute]?.columnName || attribute;
|
|
8761
|
+
const knex = strapi2.db.connection;
|
|
8762
|
+
const client = strapi2.db.dialect?.client || "";
|
|
8763
|
+
const end = `CASE WHEN ?? THEN COALESCE(??, ?) ELSE COALESCE(??, ??) END`;
|
|
8764
|
+
const endBindings = [
|
|
8765
|
+
col("isActive"),
|
|
8766
|
+
col("lastActive"),
|
|
8767
|
+
now,
|
|
8768
|
+
col("logoutTime"),
|
|
8769
|
+
col("lastActive")
|
|
8770
|
+
];
|
|
8771
|
+
if (client === "postgres") {
|
|
8772
|
+
const row = await knex(meta.tableName).select(
|
|
8773
|
+
knex.raw(`AVG(GREATEST(0, FLOOR(EXTRACT(EPOCH FROM ((${end}) - ??)) / 60))) AS avg`, [
|
|
8774
|
+
...endBindings,
|
|
8775
|
+
col("loginTime")
|
|
8776
|
+
])
|
|
8777
|
+
).first();
|
|
8778
|
+
return Math.floor(Number(row?.avg) || 0);
|
|
8779
|
+
}
|
|
8780
|
+
if (client === "mysql" || client === "mysql2") {
|
|
8781
|
+
const row = await knex(meta.tableName).select(
|
|
8782
|
+
knex.raw(`AVG(GREATEST(0, FLOOR(TIMESTAMPDIFF(SECOND, ??, (${end})) / 60))) AS avg`, [
|
|
8783
|
+
col("loginTime"),
|
|
8784
|
+
...endBindings
|
|
8785
|
+
])
|
|
8786
|
+
).first();
|
|
8787
|
+
return Math.floor(Number(row?.avg) || 0);
|
|
8788
|
+
}
|
|
8789
|
+
let sum = 0;
|
|
8790
|
+
let count = 0;
|
|
8791
|
+
let lastId = 0;
|
|
8792
|
+
const nowMs = now.getTime();
|
|
8793
|
+
for (; ; ) {
|
|
8794
|
+
const rows = await strapi2.db.query(SESSION_UID).findMany({
|
|
8795
|
+
select: ["id", "loginTime", "lastActive", "logoutTime", "isActive"],
|
|
8796
|
+
where: { id: { $gt: lastId } },
|
|
8797
|
+
orderBy: [{ id: "asc" }],
|
|
8798
|
+
limit: 5e3
|
|
8799
|
+
});
|
|
8800
|
+
for (const row of rows) {
|
|
8801
|
+
const start = Date.parse(row.loginTime);
|
|
8802
|
+
if (!Number.isFinite(start)) continue;
|
|
8803
|
+
const lastActive = row.lastActive ? Date.parse(row.lastActive) : Number.NaN;
|
|
8804
|
+
const logout = row.logoutTime ? Date.parse(row.logoutTime) : Number.NaN;
|
|
8805
|
+
let stop;
|
|
8806
|
+
if (row.isActive) stop = Number.isFinite(lastActive) ? lastActive : nowMs;
|
|
8807
|
+
else stop = Number.isFinite(logout) ? logout : lastActive;
|
|
8808
|
+
if (!Number.isFinite(stop)) continue;
|
|
8809
|
+
sum += Math.max(0, Math.floor((stop - start) / 6e4));
|
|
8810
|
+
count += 1;
|
|
8811
|
+
}
|
|
8812
|
+
if (rows.length < 5e3) break;
|
|
8813
|
+
lastId = rows[rows.length - 1].id;
|
|
8814
|
+
}
|
|
8815
|
+
return count > 0 ? Math.floor(sum / count) : 0;
|
|
8816
|
+
}
|
|
8817
|
+
async function countUsersWithSessions(strapi2) {
|
|
8818
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
8819
|
+
const joinTable = meta.attributes.user?.joinTable;
|
|
8820
|
+
if (!joinTable?.name || !joinTable.inverseJoinColumn?.name) return 0;
|
|
8821
|
+
const row = await strapi2.db.connection(joinTable.name).countDistinct({ count: joinTable.inverseJoinColumn.name }).first();
|
|
8822
|
+
return Number(row?.count ?? 0);
|
|
8823
|
+
}
|
|
8824
|
+
async function getSessionAnalytics(strapi2, { inactivityTimeout }) {
|
|
8825
|
+
const key = `analytics:${inactivityTimeout}`;
|
|
8826
|
+
const cache = cacheFor(strapi2);
|
|
8827
|
+
const cached = cache.get(key);
|
|
8828
|
+
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
8829
|
+
const now = /* @__PURE__ */ new Date();
|
|
8830
|
+
const sessions = strapi2.db.query(SESSION_UID);
|
|
8831
|
+
const since = (ms) => sessions.count({ where: { loginTime: { $gt: new Date(now - ms) } } });
|
|
8832
|
+
const [stats, signIns24h, signIns7d, devices, browsers, uniqueUsers, avgSessionDuration] = await Promise.all([
|
|
8833
|
+
getSessionStats(strapi2, { inactivityTimeout }),
|
|
8834
|
+
since(24 * 60 * 60 * 1e3),
|
|
8835
|
+
since(7 * 24 * 60 * 60 * 1e3),
|
|
8836
|
+
countByColumn(strapi2, "deviceType"),
|
|
8837
|
+
countByColumn(strapi2, "browserName"),
|
|
8838
|
+
countUsersWithSessions(strapi2),
|
|
8839
|
+
averageSessionMinutes(strapi2, now)
|
|
8840
|
+
]);
|
|
8841
|
+
const value = {
|
|
8842
|
+
totalSessions: stats.total,
|
|
8843
|
+
activeSessions: stats.active,
|
|
8844
|
+
idleSessions: stats.idle,
|
|
8845
|
+
endedSessions: stats.ended,
|
|
8846
|
+
signInsLast24Hours: Number(signIns24h),
|
|
8847
|
+
signInsLast7Days: Number(signIns7d),
|
|
8848
|
+
devices,
|
|
8849
|
+
browsers,
|
|
8850
|
+
uniqueUsers,
|
|
8851
|
+
avgSessionDuration
|
|
8852
|
+
};
|
|
8853
|
+
cache.set(key, { value, expiresAt: Date.now() + ANALYTICS_CACHE_MS });
|
|
8854
|
+
return value;
|
|
8855
|
+
}
|
|
8856
|
+
async function exportSessionBatch(strapi2, query, cursor, { inactivityTimeout }) {
|
|
8857
|
+
const cutoff = inactivityCutoff(inactivityTimeout);
|
|
8858
|
+
const base = buildSessionWhere(query, { cutoff });
|
|
8859
|
+
const where = cursor ? { $and: [...base.$and ? base.$and : [], afterExportCursor(cursor)] } : base;
|
|
8860
|
+
const rows = await strapi2.db.query(SESSION_UID).findMany({
|
|
8861
|
+
where,
|
|
8862
|
+
select: [...LIST_FIELDS],
|
|
8863
|
+
populate: { user: { select: [...LIST_USER_FIELDS] } },
|
|
8864
|
+
orderBy: SORT_ORDERS["loginTime:desc"],
|
|
8865
|
+
limit: query.limit
|
|
8866
|
+
});
|
|
8867
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
8868
|
+
const reconciled = await reconcileNativeRows(strapi2, list);
|
|
8869
|
+
const enhanced = await enhanceSessions(
|
|
8870
|
+
reconciled,
|
|
8871
|
+
{ inactivityTimeout, geolocationService: null, strapi: strapi2 },
|
|
8872
|
+
0
|
|
8873
|
+
);
|
|
8874
|
+
const last = list[list.length - 1];
|
|
8875
|
+
return {
|
|
8876
|
+
rows: enhanced,
|
|
8877
|
+
nextCursor: list.length === query.limit && last ? encodeExportCursor(last) : null
|
|
8878
|
+
};
|
|
8879
|
+
}
|
|
8880
|
+
module.exports = {
|
|
8881
|
+
STATS_CACHE_MS,
|
|
8882
|
+
ANALYTICS_CACHE_MS,
|
|
8883
|
+
listSessionPage,
|
|
8884
|
+
getSessionStats,
|
|
8885
|
+
getSessionAnalytics,
|
|
8886
|
+
exportSessionBatch,
|
|
8887
|
+
countUsersOnline,
|
|
8888
|
+
countNativeOnlySessions,
|
|
8889
|
+
reconcileNativeRows,
|
|
8890
|
+
clearSessionStatsCache,
|
|
8891
|
+
inactivityCutoff
|
|
8892
|
+
};
|
|
8893
|
+
}
|
|
8894
|
+
});
|
|
8895
|
+
|
|
8324
8896
|
// server/src/controllers/session.js
|
|
8325
8897
|
var require_session = __commonJS({
|
|
8326
8898
|
"server/src/controllers/session.js"(exports, module) {
|
|
@@ -8338,12 +8910,23 @@ var require_session = __commonJS({
|
|
|
8338
8910
|
var { runWithCallerRevocation } = require_block_revocation_scope();
|
|
8339
8911
|
var { sendServerError } = require_http_errors();
|
|
8340
8912
|
var { getCoordinator } = require_coordination();
|
|
8913
|
+
var { clearSessionStatsCache } = require_session_list();
|
|
8914
|
+
var {
|
|
8915
|
+
decodeExportCursor,
|
|
8916
|
+
exportQuerySchema,
|
|
8917
|
+
isPaginatedListQuery,
|
|
8918
|
+
listQuerySchema,
|
|
8919
|
+
parseQuery,
|
|
8920
|
+
statsQuerySchema
|
|
8921
|
+
} = require_session_list_query();
|
|
8341
8922
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
8342
8923
|
var USER_UID = "plugin::users-permissions.user";
|
|
8343
8924
|
var OWN_SESSIONS_LIMIT = 200;
|
|
8344
8925
|
var NATIVE_SESSION_KEY_PREFIX = "native_";
|
|
8345
8926
|
var JWT_MANAGEMENT_CONFIG = "plugin::users-permissions.jwtManagement";
|
|
8346
8927
|
var LEGACY_JWT_MANAGEMENT = "legacy-support";
|
|
8928
|
+
var USER_STATS_CACHE_MS = 5e3;
|
|
8929
|
+
var userStatsCache = { owner: null, value: null, expiresAt: 0 };
|
|
8347
8930
|
function createDisabledGeolocationResult(ipAddress) {
|
|
8348
8931
|
return {
|
|
8349
8932
|
ip: ipAddress,
|
|
@@ -8418,6 +9001,55 @@ var require_session = __commonJS({
|
|
|
8418
9001
|
function getTruncationMeta(sessions) {
|
|
8419
9002
|
return sessions?.truncated === true ? { truncated: true } : {};
|
|
8420
9003
|
}
|
|
9004
|
+
async function listSessionsAdmin(ctx, { activeOnly }) {
|
|
9005
|
+
if (isPaginatedListQuery(ctx.query)) {
|
|
9006
|
+
const parsed = parseQuery(listQuerySchema, ctx.query);
|
|
9007
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
9008
|
+
const query = activeOnly ? { ...parsed.value, status: "active", reason: "all" } : parsed.value;
|
|
9009
|
+
try {
|
|
9010
|
+
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9011
|
+
const page = await sessionService.listSessionPage(query);
|
|
9012
|
+
ctx.body = {
|
|
9013
|
+
data: toPublicSessions(page.rows, { admin: true }),
|
|
9014
|
+
meta: { pagination: page.pagination }
|
|
9015
|
+
};
|
|
9016
|
+
return void 0;
|
|
9017
|
+
} catch (err) {
|
|
9018
|
+
strapi.log.error("[magic-sessionmanager] listSessionPage failed:", err?.name || "Error");
|
|
9019
|
+
return ctx.internalServerError("Error fetching sessions");
|
|
9020
|
+
}
|
|
9021
|
+
}
|
|
9022
|
+
try {
|
|
9023
|
+
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9024
|
+
if (activeOnly) {
|
|
9025
|
+
const sessions2 = await sessionService.getActiveSessions();
|
|
9026
|
+
ctx.body = {
|
|
9027
|
+
data: toPublicSessions(sessions2, { admin: true }),
|
|
9028
|
+
meta: { count: sessions2.length, ...getTruncationMeta(sessions2) }
|
|
9029
|
+
};
|
|
9030
|
+
return void 0;
|
|
9031
|
+
}
|
|
9032
|
+
const sessions = await sessionService.getAllSessions();
|
|
9033
|
+
ctx.body = {
|
|
9034
|
+
data: toPublicSessions(sessions, { admin: true }),
|
|
9035
|
+
meta: {
|
|
9036
|
+
count: sessions.length,
|
|
9037
|
+
active: sessions.filter((s) => s.isTrulyActive).length,
|
|
9038
|
+
inactive: sessions.filter((s) => !s.isTrulyActive).length,
|
|
9039
|
+
...getTruncationMeta(sessions)
|
|
9040
|
+
}
|
|
9041
|
+
};
|
|
9042
|
+
return void 0;
|
|
9043
|
+
} catch (err) {
|
|
9044
|
+
strapi.log.error(
|
|
9045
|
+
`[magic-sessionmanager] ${activeOnly ? "getActiveSessions" : "getAllSessionsAdmin"} failed:`,
|
|
9046
|
+
err?.name || "Error"
|
|
9047
|
+
);
|
|
9048
|
+
return ctx.internalServerError(
|
|
9049
|
+
activeOnly ? "Error fetching active sessions" : "Error fetching sessions"
|
|
9050
|
+
);
|
|
9051
|
+
}
|
|
9052
|
+
}
|
|
8421
9053
|
async function respondIfSessionCreationPending(ctx) {
|
|
8422
9054
|
const settings = await getPluginSettings(strapi);
|
|
8423
9055
|
const gracePeriodMs = getSessionCreationGraceMs(settings);
|
|
@@ -8448,13 +9080,19 @@ var require_session = __commonJS({
|
|
|
8448
9080
|
*/
|
|
8449
9081
|
async getUserStatsAdmin(ctx) {
|
|
8450
9082
|
try {
|
|
8451
|
-
|
|
8452
|
-
|
|
8453
|
-
|
|
8454
|
-
|
|
9083
|
+
if (userStatsCache.owner !== strapi || !userStatsCache.value || userStatsCache.expiresAt <= Date.now()) {
|
|
9084
|
+
userStatsCache.owner = null;
|
|
9085
|
+
const [totalUsers, blockedUsers] = await Promise.all([
|
|
9086
|
+
strapi.db.query(USER_UID).count(),
|
|
9087
|
+
strapi.db.query(USER_UID).count({ where: { blocked: true } })
|
|
9088
|
+
]);
|
|
9089
|
+
userStatsCache.owner = strapi;
|
|
9090
|
+
userStatsCache.value = { totalUsers, blockedUsers };
|
|
9091
|
+
userStatsCache.expiresAt = Date.now() + USER_STATS_CACHE_MS;
|
|
9092
|
+
}
|
|
8455
9093
|
return ctx.send({
|
|
8456
9094
|
success: true,
|
|
8457
|
-
data: {
|
|
9095
|
+
data: { ...userStatsCache.value }
|
|
8458
9096
|
});
|
|
8459
9097
|
} catch (error) {
|
|
8460
9098
|
strapi.log.error("[magic-sessionmanager] getUserStatsAdmin failed:", error?.name || "Error");
|
|
@@ -8462,42 +9100,102 @@ var require_session = __commonJS({
|
|
|
8462
9100
|
}
|
|
8463
9101
|
},
|
|
8464
9102
|
/**
|
|
8465
|
-
* Lists
|
|
9103
|
+
* Lists sessions for admin overviews.
|
|
9104
|
+
*
|
|
9105
|
+
* With `page` or `pageSize` the list is paginated in SQL and filtered by
|
|
9106
|
+
* `status`, `reason`, `search` and `sort` (whitelisted values only), with
|
|
9107
|
+
* exact totals. Without them the 4.x response (latest 1000 rows) is kept
|
|
9108
|
+
* for existing callers.
|
|
9109
|
+
*
|
|
8466
9110
|
* @route GET /magic-sessionmanager/sessions
|
|
9111
|
+
* @param {object} ctx Koa context
|
|
9112
|
+
* @returns {Promise<void>}
|
|
8467
9113
|
*/
|
|
8468
9114
|
async getAllSessionsAdmin(ctx) {
|
|
9115
|
+
return listSessionsAdmin(ctx, { activeOnly: false });
|
|
9116
|
+
},
|
|
9117
|
+
/**
|
|
9118
|
+
* Lists currently-active sessions only (paginated with `page`/`pageSize`,
|
|
9119
|
+
* see getAllSessionsAdmin).
|
|
9120
|
+
*
|
|
9121
|
+
* @route GET /magic-sessionmanager/sessions/active
|
|
9122
|
+
* @param {object} ctx Koa context
|
|
9123
|
+
* @returns {Promise<void>}
|
|
9124
|
+
*/
|
|
9125
|
+
async getActiveSessions(ctx) {
|
|
9126
|
+
return listSessionsAdmin(ctx, { activeOnly: true });
|
|
9127
|
+
},
|
|
9128
|
+
/**
|
|
9129
|
+
* Count-only session statistics for the dashboard cards and the homepage
|
|
9130
|
+
* widget. No rows, no personal data.
|
|
9131
|
+
*
|
|
9132
|
+
* @route GET /magic-sessionmanager/sessions/stats
|
|
9133
|
+
* @param {object} ctx Koa context
|
|
9134
|
+
* @returns {Promise<void>}
|
|
9135
|
+
*/
|
|
9136
|
+
async getSessionStatsAdmin(ctx) {
|
|
9137
|
+
const parsed = parseQuery(statsQuerySchema, ctx.query);
|
|
9138
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
8469
9139
|
try {
|
|
8470
9140
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
8471
|
-
const
|
|
8472
|
-
ctx.
|
|
8473
|
-
data: toPublicSessions(sessions, { admin: true }),
|
|
8474
|
-
meta: {
|
|
8475
|
-
count: sessions.length,
|
|
8476
|
-
active: sessions.filter((s) => s.isTrulyActive).length,
|
|
8477
|
-
inactive: sessions.filter((s) => !s.isTrulyActive).length,
|
|
8478
|
-
...getTruncationMeta(sessions)
|
|
8479
|
-
}
|
|
8480
|
-
};
|
|
9141
|
+
const stats = await sessionService.getSessionStats();
|
|
9142
|
+
return ctx.send({ data: stats });
|
|
8481
9143
|
} catch (err) {
|
|
8482
|
-
strapi.log.error("[magic-sessionmanager]
|
|
8483
|
-
return ctx.internalServerError("
|
|
9144
|
+
strapi.log.error("[magic-sessionmanager] getSessionStatsAdmin failed:", err?.name || "Error");
|
|
9145
|
+
return ctx.internalServerError("Unable to load session statistics");
|
|
8484
9146
|
}
|
|
8485
9147
|
},
|
|
8486
9148
|
/**
|
|
8487
|
-
*
|
|
8488
|
-
*
|
|
9149
|
+
* Aggregates for the Analytics page over every session: counts, grouped
|
|
9150
|
+
* counts per device type and browser, distinct users, average length. No
|
|
9151
|
+
* rows and no personal data.
|
|
9152
|
+
*
|
|
9153
|
+
* @route GET /magic-sessionmanager/sessions/analytics
|
|
9154
|
+
* @param {object} ctx Koa context
|
|
9155
|
+
* @returns {Promise<void>}
|
|
8489
9156
|
*/
|
|
8490
|
-
async
|
|
9157
|
+
async getSessionAnalyticsAdmin(ctx) {
|
|
9158
|
+
const parsed = parseQuery(statsQuerySchema, ctx.query);
|
|
9159
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
8491
9160
|
try {
|
|
8492
9161
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
8493
|
-
|
|
8494
|
-
|
|
8495
|
-
|
|
8496
|
-
|
|
8497
|
-
|
|
9162
|
+
return ctx.send({ data: await sessionService.getSessionAnalytics() });
|
|
9163
|
+
} catch (err) {
|
|
9164
|
+
strapi.log.error(
|
|
9165
|
+
"[magic-sessionmanager] getSessionAnalyticsAdmin failed:",
|
|
9166
|
+
err?.name || "Error"
|
|
9167
|
+
);
|
|
9168
|
+
return ctx.internalServerError("Unable to load session analytics");
|
|
9169
|
+
}
|
|
9170
|
+
},
|
|
9171
|
+
/**
|
|
9172
|
+
* One batch of the session export (newest first, keyset cursor). The admin
|
|
9173
|
+
* client follows `meta.nextCursor` until it is null or its row limit is
|
|
9174
|
+
* reached.
|
|
9175
|
+
*
|
|
9176
|
+
* @route GET /magic-sessionmanager/sessions/export
|
|
9177
|
+
* @param {object} ctx Koa context
|
|
9178
|
+
* @returns {Promise<void>}
|
|
9179
|
+
*/
|
|
9180
|
+
async exportSessionsAdmin(ctx) {
|
|
9181
|
+
const parsed = parseQuery(exportQuerySchema, ctx.query);
|
|
9182
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
9183
|
+
const cursor = decodeExportCursor(parsed.value.cursor);
|
|
9184
|
+
if (cursor === false) {
|
|
9185
|
+
return ctx.badRequest("Invalid query", {
|
|
9186
|
+
errors: [{ path: "cursor", message: "Invalid cursor" }]
|
|
9187
|
+
});
|
|
9188
|
+
}
|
|
9189
|
+
try {
|
|
9190
|
+
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9191
|
+
const batch = await sessionService.exportSessionBatch(parsed.value, cursor);
|
|
9192
|
+
return ctx.send({
|
|
9193
|
+
data: toPublicSessions(batch.rows, { admin: true }),
|
|
9194
|
+
meta: { count: batch.rows.length, nextCursor: batch.nextCursor }
|
|
9195
|
+
});
|
|
8498
9196
|
} catch (err) {
|
|
8499
|
-
strapi.log.error("[magic-sessionmanager]
|
|
8500
|
-
return ctx.internalServerError("
|
|
9197
|
+
strapi.log.error("[magic-sessionmanager] exportSessionsAdmin failed:", err?.name || "Error");
|
|
9198
|
+
return ctx.internalServerError("Unable to export sessions");
|
|
8501
9199
|
}
|
|
8502
9200
|
},
|
|
8503
9201
|
/**
|
|
@@ -9020,6 +9718,7 @@ var require_session = __commonJS({
|
|
|
9020
9718
|
* A missing target returns 404; existing native-only rows remain supported.
|
|
9021
9719
|
*/
|
|
9022
9720
|
async terminateSingleSession(ctx) {
|
|
9721
|
+
clearSessionStatsCache();
|
|
9023
9722
|
try {
|
|
9024
9723
|
const { sessionId } = ctx.params;
|
|
9025
9724
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
@@ -9048,6 +9747,7 @@ var require_session = __commonJS({
|
|
|
9048
9747
|
* Unknown numeric IDs and document IDs return 404 before revocation.
|
|
9049
9748
|
*/
|
|
9050
9749
|
async terminateAllUserSessions(ctx) {
|
|
9750
|
+
clearSessionStatsCache();
|
|
9051
9751
|
try {
|
|
9052
9752
|
const { userId } = ctx.params;
|
|
9053
9753
|
const numericId = /^\d+$/.test(userId) ? Number(userId) : null;
|
|
@@ -9130,6 +9830,7 @@ var require_session = __commonJS({
|
|
|
9130
9830
|
* any unexpired JWT expires
|
|
9131
9831
|
*/
|
|
9132
9832
|
async deleteSession(ctx) {
|
|
9833
|
+
clearSessionStatsCache();
|
|
9133
9834
|
try {
|
|
9134
9835
|
const { sessionId } = ctx.params;
|
|
9135
9836
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
@@ -9155,6 +9856,7 @@ var require_session = __commonJS({
|
|
|
9155
9856
|
* could not be removed
|
|
9156
9857
|
*/
|
|
9157
9858
|
async cleanInactiveSessions(ctx) {
|
|
9859
|
+
clearSessionStatsCache();
|
|
9158
9860
|
try {
|
|
9159
9861
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9160
9862
|
const deletedCount = await sessionService.deleteInactiveSessions();
|
|
@@ -9201,6 +9903,8 @@ var require_session = __commonJS({
|
|
|
9201
9903
|
* can leave the user blocked with partially active sessions.
|
|
9202
9904
|
*/
|
|
9203
9905
|
async toggleUserBlock(ctx) {
|
|
9906
|
+
clearSessionStatsCache();
|
|
9907
|
+
userStatsCache.expiresAt = 0;
|
|
9204
9908
|
try {
|
|
9205
9909
|
const { userId } = ctx.params;
|
|
9206
9910
|
const body = ctx.request?.body;
|
|
@@ -10342,6 +11046,12 @@ var require_session2 = __commonJS({
|
|
|
10342
11046
|
persistAccessTokenRevocation
|
|
10343
11047
|
} = require_session_revocation();
|
|
10344
11048
|
var { getNativeSessionManager } = require_native_session_manager();
|
|
11049
|
+
var {
|
|
11050
|
+
exportSessionBatch,
|
|
11051
|
+
getSessionAnalytics: getSessionAnalyticsFromDb,
|
|
11052
|
+
getSessionStats: getSessionStatsFromDb,
|
|
11053
|
+
listSessionPage
|
|
11054
|
+
} = require_session_list();
|
|
10345
11055
|
var {
|
|
10346
11056
|
NATIVE_SESSION_PREFIX,
|
|
10347
11057
|
mapNativeSessionToView,
|
|
@@ -11037,8 +11747,51 @@ var require_session2 = __commonJS({
|
|
|
11037
11747
|
throw err;
|
|
11038
11748
|
}
|
|
11039
11749
|
},
|
|
11750
|
+
/**
|
|
11751
|
+
* One page of sessions with exact totals for the admin dashboard. Only
|
|
11752
|
+
* the rows on the page are enriched; filters and sort run in SQL.
|
|
11753
|
+
*
|
|
11754
|
+
* @param {{page: number, pageSize: number, status: string, reason: string, search: string, sort: string}} query Validated list query
|
|
11755
|
+
* @returns {Promise<{rows: object[], pagination: object}>}
|
|
11756
|
+
*/
|
|
11757
|
+
async listSessionPage(query) {
|
|
11758
|
+
return listSessionPage(strapi2, query, await getEnhanceOpts());
|
|
11759
|
+
},
|
|
11760
|
+
/**
|
|
11761
|
+
* Count-only session statistics (cached a few seconds per process).
|
|
11762
|
+
*
|
|
11763
|
+
* @returns {Promise<object>}
|
|
11764
|
+
*/
|
|
11765
|
+
async getSessionStats() {
|
|
11766
|
+
const { inactivityTimeout } = await getEnhanceOpts();
|
|
11767
|
+
return getSessionStatsFromDb(strapi2, { inactivityTimeout });
|
|
11768
|
+
},
|
|
11769
|
+
/**
|
|
11770
|
+
* Aggregates for the Analytics page over every session (cached 30 s
|
|
11771
|
+
* per process).
|
|
11772
|
+
*
|
|
11773
|
+
* @returns {Promise<object>}
|
|
11774
|
+
*/
|
|
11775
|
+
async getSessionAnalytics() {
|
|
11776
|
+
const { inactivityTimeout } = await getEnhanceOpts();
|
|
11777
|
+
return getSessionAnalyticsFromDb(strapi2, { inactivityTimeout });
|
|
11778
|
+
},
|
|
11779
|
+
/**
|
|
11780
|
+
* One export batch (keyset cursor, newest first).
|
|
11781
|
+
*
|
|
11782
|
+
* @param {{limit: number, status: string, reason: string, search: string}} query Validated export query
|
|
11783
|
+
* @param {{loginTime: Date|null, id: number}|null} cursor Decoded cursor
|
|
11784
|
+
* @returns {Promise<{rows: object[], nextCursor: string|null}>}
|
|
11785
|
+
*/
|
|
11786
|
+
async exportSessionBatch(query, cursor) {
|
|
11787
|
+
const { inactivityTimeout } = await getEnhanceOpts();
|
|
11788
|
+
return exportSessionBatch(strapi2, query, cursor, { inactivityTimeout });
|
|
11789
|
+
},
|
|
11040
11790
|
/**
|
|
11041
11791
|
* Get ALL sessions (active + inactive) with enhanced display fields.
|
|
11792
|
+
* Kept for callers of `GET /sessions` without paging parameters; capped
|
|
11793
|
+
* at the latest 1000 rows. The admin dashboard uses `listSessionPage`.
|
|
11794
|
+
*
|
|
11042
11795
|
* @returns {Promise<Array>}
|
|
11043
11796
|
*/
|
|
11044
11797
|
async getAllSessions() {
|