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