strapi-plugin-magic-sessionmanager 4.10.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +92 -6
  2. package/README.md +263 -72
  3. package/dist/admin/{Analytics-PRqsLMEx.mjs → Analytics-C_c24Uzq.mjs} +45 -75
  4. package/dist/admin/{Analytics-CdmRsigN.js → Analytics-lP0-RsVd.js} +45 -75
  5. package/dist/admin/{App-BSeYF7KA.mjs → App-DCyNPn1k.mjs} +162 -119
  6. package/dist/admin/{App-DUMCbuCr.js → App-miWDdmdX.js} +162 -119
  7. package/dist/admin/{OnlineUsersWidget-CDZ19_PT.js → OnlineUsersWidget-C6b7e4jb.js} +18 -26
  8. package/dist/admin/{OnlineUsersWidget-B5pXzqM9.mjs → OnlineUsersWidget-C6wlwENC.mjs} +18 -26
  9. package/dist/admin/{Settings-CrLzRXrA.js → Settings-D9zyn5xn.js} +9 -3
  10. package/dist/admin/{Settings-B-GRuWjT.mjs → Settings-DssYw2W4.mjs} +8 -2
  11. package/dist/admin/{de-DwUCBY1b.mjs → de--yNl7MPl.mjs} +4 -48
  12. package/dist/admin/{de-Dzo1tVoJ.js → de-DjPEATFf.js} +4 -48
  13. package/dist/admin/{en-Dd0wXfgR.mjs → en-5U7g51cH.mjs} +4 -48
  14. package/dist/admin/{en-CL5llI55.js → en-BoO12UQw.js} +4 -48
  15. package/dist/admin/{es-Cl5IwDA4.mjs → es-BJR-zCXL.mjs} +4 -48
  16. package/dist/admin/{es-CiNDwv_f.js → es-BLpEuycJ.js} +4 -48
  17. package/dist/admin/{fr-DBOQ-UDm.js → fr-BE828R9Q.js} +4 -48
  18. package/dist/admin/{fr-DhADj8Zs.mjs → fr-CeeCYQCs.mjs} +4 -48
  19. package/dist/admin/{index-CaLVyCio.js → index-CfQOMZVX.js} +9 -56
  20. package/dist/admin/{index-CHACmZsg.mjs → index-rbxJZcLv.mjs} +35 -82
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +2 -2
  23. package/dist/admin/{pt-m73K1nJ0.js → pt-BWEFiuvo.js} +4 -48
  24. package/dist/admin/{pt-CT6VpDMM.mjs → pt-CorrU3yG.mjs} +4 -48
  25. package/dist/server/index.js +815 -628
  26. package/dist/server/index.mjs +815 -628
  27. package/package.json +29 -13
  28. package/dist/admin/License-BeD7Du6r.js +0 -443
  29. package/dist/admin/License-D5W_l35e.mjs +0 -443
  30. package/dist/admin/maskSensitiveValue-BWcSjow7.js +0 -9
  31. package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +0 -10
@@ -779,10 +779,21 @@ var require_plugin_store = __commonJS({
779
779
  async function setPluginStoreValue(strapi2, key, value) {
780
780
  await withPluginStoreKey(strapi2, key, (store) => store.set({ key, value }));
781
781
  }
782
+ var LEGACY_LICENSE_STORE_KEYS = Object.freeze(["licenseKey", "lastValidated", "deviceId"]);
783
+ async function removeLegacyLicenseData(strapi2) {
784
+ const query = strapi2?.db?.query?.(CORE_STORE_UID);
785
+ if (!query || typeof query.deleteMany !== "function") return 0;
786
+ const result = await query.deleteMany({
787
+ where: { key: { $in: LEGACY_LICENSE_STORE_KEYS.map(coreStoreKey) } }
788
+ });
789
+ return Number(result?.count) || 0;
790
+ }
782
791
  module2.exports = {
792
+ LEGACY_LICENSE_STORE_KEYS,
783
793
  PLUGIN_ID,
784
794
  collapseDuplicateStoreRows,
785
795
  coreStoreKey,
796
+ removeLegacyLicenseData,
786
797
  setPluginStoreValue,
787
798
  withPluginStoreKey
788
799
  };
@@ -1896,6 +1907,10 @@ var require_last_seen = __commonJS({
1896
1907
  if (!ctx.state.user) {
1897
1908
  return;
1898
1909
  }
1910
+ const strategyName = ctx.state.auth?.strategy?.name;
1911
+ if (strategyName === "admin" || strategyName === "admin-token") {
1912
+ return;
1913
+ }
1899
1914
  let userDocId = ctx.state.user.documentId;
1900
1915
  if (!userDocId && ctx.state.user.id) {
1901
1916
  try {
@@ -5899,7 +5914,7 @@ var require_bootstrap = __commonJS({
5899
5914
  initCoordination,
5900
5915
  LockTimeoutError
5901
5916
  } = require_coordination();
5902
- var { withPluginStoreKey } = require_plugin_store();
5917
+ var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
5903
5918
  var {
5904
5919
  classifyJwtIssuingRequest,
5905
5920
  isFailedLoginTrackedPath,
@@ -5933,6 +5948,16 @@ var require_bootstrap = __commonJS({
5933
5948
  }
5934
5949
  return settings;
5935
5950
  }
5951
+ async function removeLegacyLicenseRows(strapi2, log) {
5952
+ try {
5953
+ const removed = await removeLegacyLicenseData(strapi2);
5954
+ if (removed > 0) {
5955
+ log.info(`[CLEANUP] Removed ${removed} stored value(s) of the former license feature`);
5956
+ }
5957
+ } catch (err) {
5958
+ log.warn("[CLEANUP] Could not remove former license data:", err?.name || "Error");
5959
+ }
5960
+ }
5936
5961
  module2.exports = async ({ strapi: strapi2 }) => {
5937
5962
  const log = createLogger(strapi2);
5938
5963
  log.info("[START] Bootstrap starting...");
@@ -5947,9 +5972,7 @@ var require_bootstrap = __commonJS({
5947
5972
  await checkEncryptionKeyConsistency(strapi2, log);
5948
5973
  await ensureSessionLookupIndexes(strapi2, log);
5949
5974
  await registerSessionAwareAuthStrategy(strapi2);
5950
- const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
5951
- await licenseGuardService.initialize();
5952
- log.info("[SUCCESS] Session Manager active - all features are available without a license key");
5975
+ await removeLegacyLicenseRows(strapi2, log);
5953
5976
  const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
5954
5977
  if (!strapi2.sessionManagerIntervals) {
5955
5978
  strapi2.sessionManagerIntervals = {};
@@ -6909,7 +6932,9 @@ var require_bootstrap = __commonJS({
6909
6932
  });
6910
6933
  const authenticatedRole = roles?.[0];
6911
6934
  if (!authenticatedRole) {
6912
- log.warn("Authenticated role not found - skipping permission setup");
6935
+ log.info(
6936
+ "Authenticated role does not exist yet; permission setup runs again on the first Session Manager API request"
6937
+ );
6913
6938
  return false;
6914
6939
  }
6915
6940
  const requiredActions = [
@@ -7031,8 +7056,14 @@ var require_bootstrap = __commonJS({
7031
7056
  const knex = strapi2.db.connection;
7032
7057
  const tableName = "magic_sessions";
7033
7058
  const definitions = [
7034
- { column: "token_hash", name: "idx_magic_sessions_token_hash" },
7035
- { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
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" }
7036
7067
  ];
7037
7068
  if (!await knex.schema.hasTable(tableName)) return;
7038
7069
  const dialect = strapi2.db.dialect.client;
@@ -7048,11 +7079,11 @@ var require_bootstrap = __commonJS({
7048
7079
  log.debug(`[INDEX] ${definition.name} already exists`);
7049
7080
  continue;
7050
7081
  }
7051
- await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??, ??)", [
7082
+ const placeholders = definition.columns.map(() => "??").join(", ");
7083
+ await knex.raw(`CREATE INDEX IF NOT EXISTS ?? ON ?? (${placeholders})`, [
7052
7084
  definition.name,
7053
7085
  tableName,
7054
- definition.column,
7055
- "is_active"
7086
+ ...definition.columns
7056
7087
  ]);
7057
7088
  log.info(`[INDEX] Created ${definition.name}`);
7058
7089
  continue;
@@ -7070,7 +7101,7 @@ var require_bootstrap = __commonJS({
7070
7101
  continue;
7071
7102
  }
7072
7103
  await knex.schema.alterTable(tableName, (table) => {
7073
- table.index([definition.column, "is_active"], definition.name);
7104
+ table.index(definition.columns, definition.name);
7074
7105
  });
7075
7106
  log.info(`[INDEX] Created ${definition.name}`);
7076
7107
  }
@@ -7793,6 +7824,12 @@ var require_admin = __commonJS({
7793
7824
  config: { actions: [PLUGIN_ACCESS_ACTION] }
7794
7825
  }
7795
7826
  ];
7827
+ var adminReadRateLimit = () => [
7828
+ {
7829
+ name: "plugin::magic-sessionmanager.rate-limit",
7830
+ config: { profile: "read", max: 120, window: 6e4 }
7831
+ }
7832
+ ];
7796
7833
  var isDevEnvironment = (() => {
7797
7834
  const env = (process.env.NODE_ENV || "development").toLowerCase();
7798
7835
  return env !== "production" && env !== "staging";
@@ -7805,7 +7842,8 @@ var require_admin = __commonJS({
7805
7842
  handler: "session.getAllSessionsAdmin",
7806
7843
  config: {
7807
7844
  policies: adminPolicy(),
7808
- description: "Get all sessions - active and inactive (admin)"
7845
+ middlewares: adminReadRateLimit(),
7846
+ description: "List sessions (admin); paginated with page/pageSize, filters and sort"
7809
7847
  }
7810
7848
  },
7811
7849
  {
@@ -7814,7 +7852,38 @@ var require_admin = __commonJS({
7814
7852
  handler: "session.getActiveSessions",
7815
7853
  config: {
7816
7854
  policies: adminPolicy(),
7817
- description: "Get only active sessions (admin)"
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)"
7818
7887
  }
7819
7888
  },
7820
7889
  {
@@ -7877,55 +7946,10 @@ var require_admin = __commonJS({
7877
7946
  handler: "session.getUserStatsAdmin",
7878
7947
  config: {
7879
7948
  policies: adminPolicy(),
7949
+ middlewares: adminReadRateLimit(),
7880
7950
  description: "Get aggregate end-user counts only (admin)"
7881
7951
  }
7882
7952
  },
7883
- // ============================ LICENSE ============================
7884
- {
7885
- method: "GET",
7886
- path: "/license/status",
7887
- handler: "license.getStatus",
7888
- config: {
7889
- policies: adminPolicy(),
7890
- description: "Get license status (admin)"
7891
- }
7892
- },
7893
- {
7894
- method: "POST",
7895
- path: "/license/auto-create",
7896
- handler: "license.autoCreate",
7897
- config: {
7898
- policies: adminPolicy(),
7899
- description: "Auto-create license for current admin (admin)"
7900
- }
7901
- },
7902
- {
7903
- method: "POST",
7904
- path: "/license/create",
7905
- handler: "license.createAndActivate",
7906
- config: {
7907
- policies: adminPolicy(),
7908
- description: "Create and activate a new license (admin)"
7909
- }
7910
- },
7911
- {
7912
- method: "POST",
7913
- path: "/license/ping",
7914
- handler: "license.ping",
7915
- config: {
7916
- policies: adminPolicy(),
7917
- description: "Ping the license server (admin)"
7918
- }
7919
- },
7920
- {
7921
- method: "POST",
7922
- path: "/license/store-key",
7923
- handler: "license.storeKey",
7924
- config: {
7925
- policies: adminPolicy(),
7926
- description: "Store a license key (admin)"
7927
- }
7928
- },
7929
7953
  // ============================ GEOLOCATION ============================
7930
7954
  {
7931
7955
  method: "GET",
@@ -8340,6 +8364,529 @@ var require_http_errors = __commonJS({
8340
8364
  }
8341
8365
  });
8342
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
+
8343
8890
  // server/src/controllers/session.js
8344
8891
  var require_session = __commonJS({
8345
8892
  "server/src/controllers/session.js"(exports2, module2) {
@@ -8357,12 +8904,23 @@ var require_session = __commonJS({
8357
8904
  var { runWithCallerRevocation } = require_block_revocation_scope();
8358
8905
  var { sendServerError } = require_http_errors();
8359
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();
8360
8916
  var SESSION_UID = "plugin::magic-sessionmanager.session";
8361
8917
  var USER_UID = "plugin::users-permissions.user";
8362
8918
  var OWN_SESSIONS_LIMIT = 200;
8363
8919
  var NATIVE_SESSION_KEY_PREFIX = "native_";
8364
8920
  var JWT_MANAGEMENT_CONFIG = "plugin::users-permissions.jwtManagement";
8365
8921
  var LEGACY_JWT_MANAGEMENT = "legacy-support";
8922
+ var USER_STATS_CACHE_MS = 5e3;
8923
+ var userStatsCache = { owner: null, value: null, expiresAt: 0 };
8366
8924
  function createDisabledGeolocationResult(ipAddress) {
8367
8925
  return {
8368
8926
  ip: ipAddress,
@@ -8437,6 +8995,55 @@ var require_session = __commonJS({
8437
8995
  function getTruncationMeta(sessions) {
8438
8996
  return sessions?.truncated === true ? { truncated: true } : {};
8439
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
+ }
8440
9047
  async function respondIfSessionCreationPending(ctx) {
8441
9048
  const settings = await getPluginSettings(strapi);
8442
9049
  const gracePeriodMs = getSessionCreationGraceMs(settings);
@@ -8467,13 +9074,19 @@ var require_session = __commonJS({
8467
9074
  */
8468
9075
  async getUserStatsAdmin(ctx) {
8469
9076
  try {
8470
- const [totalUsers, blockedUsers] = await Promise.all([
8471
- strapi.db.query(USER_UID).count(),
8472
- strapi.db.query(USER_UID).count({ where: { blocked: true } })
8473
- ]);
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
+ }
8474
9087
  return ctx.send({
8475
9088
  success: true,
8476
- data: { totalUsers, blockedUsers }
9089
+ data: { ...userStatsCache.value }
8477
9090
  });
8478
9091
  } catch (error) {
8479
9092
  strapi.log.error("[magic-sessionmanager] getUserStatsAdmin failed:", error?.name || "Error");
@@ -8481,42 +9094,102 @@ var require_session = __commonJS({
8481
9094
  }
8482
9095
  },
8483
9096
  /**
8484
- * Lists all sessions (active + inactive) for admin overviews.
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
+ *
8485
9104
  * @route GET /magic-sessionmanager/sessions
9105
+ * @param {object} ctx Koa context
9106
+ * @returns {Promise<void>}
8486
9107
  */
8487
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 });
8488
9133
  try {
8489
9134
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8490
- const sessions = await sessionService.getAllSessions();
8491
- ctx.body = {
8492
- data: toPublicSessions(sessions, { admin: true }),
8493
- meta: {
8494
- count: sessions.length,
8495
- active: sessions.filter((s) => s.isTrulyActive).length,
8496
- inactive: sessions.filter((s) => !s.isTrulyActive).length,
8497
- ...getTruncationMeta(sessions)
8498
- }
8499
- };
9135
+ const stats = await sessionService.getSessionStats();
9136
+ return ctx.send({ data: stats });
8500
9137
  } catch (err) {
8501
- strapi.log.error("[magic-sessionmanager] getAllSessionsAdmin failed:", err?.name || "Error");
8502
- return ctx.internalServerError("Error fetching sessions");
9138
+ strapi.log.error("[magic-sessionmanager] getSessionStatsAdmin failed:", err?.name || "Error");
9139
+ return ctx.internalServerError("Unable to load session statistics");
8503
9140
  }
8504
9141
  },
8505
9142
  /**
8506
- * Lists currently-active sessions only.
8507
- * @route GET /magic-sessionmanager/sessions/active
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>}
8508
9150
  */
8509
- async getActiveSessions(ctx) {
9151
+ async getSessionAnalyticsAdmin(ctx) {
9152
+ const parsed = parseQuery(statsQuerySchema, ctx.query);
9153
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
8510
9154
  try {
8511
9155
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8512
- const sessions = await sessionService.getActiveSessions();
8513
- ctx.body = {
8514
- data: toPublicSessions(sessions, { admin: true }),
8515
- meta: { count: sessions.length, ...getTruncationMeta(sessions) }
8516
- };
9156
+ return ctx.send({ data: await sessionService.getSessionAnalytics() });
8517
9157
  } catch (err) {
8518
- strapi.log.error("[magic-sessionmanager] getActiveSessions failed:", err?.name || "Error");
8519
- return ctx.internalServerError("Error fetching active sessions");
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
+ });
9190
+ } catch (err) {
9191
+ strapi.log.error("[magic-sessionmanager] exportSessionsAdmin failed:", err?.name || "Error");
9192
+ return ctx.internalServerError("Unable to export sessions");
8520
9193
  }
8521
9194
  },
8522
9195
  /**
@@ -9039,6 +9712,7 @@ var require_session = __commonJS({
9039
9712
  * A missing target returns 404; existing native-only rows remain supported.
9040
9713
  */
9041
9714
  async terminateSingleSession(ctx) {
9715
+ clearSessionStatsCache();
9042
9716
  try {
9043
9717
  const { sessionId } = ctx.params;
9044
9718
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
@@ -9067,6 +9741,7 @@ var require_session = __commonJS({
9067
9741
  * Unknown numeric IDs and document IDs return 404 before revocation.
9068
9742
  */
9069
9743
  async terminateAllUserSessions(ctx) {
9744
+ clearSessionStatsCache();
9070
9745
  try {
9071
9746
  const { userId } = ctx.params;
9072
9747
  const numericId = /^\d+$/.test(userId) ? Number(userId) : null;
@@ -9149,6 +9824,7 @@ var require_session = __commonJS({
9149
9824
  * any unexpired JWT expires
9150
9825
  */
9151
9826
  async deleteSession(ctx) {
9827
+ clearSessionStatsCache();
9152
9828
  try {
9153
9829
  const { sessionId } = ctx.params;
9154
9830
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
@@ -9174,6 +9850,7 @@ var require_session = __commonJS({
9174
9850
  * could not be removed
9175
9851
  */
9176
9852
  async cleanInactiveSessions(ctx) {
9853
+ clearSessionStatsCache();
9177
9854
  try {
9178
9855
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9179
9856
  const deletedCount = await sessionService.deleteInactiveSessions();
@@ -9220,6 +9897,8 @@ var require_session = __commonJS({
9220
9897
  * can leave the user blocked with partially active sessions.
9221
9898
  */
9222
9899
  async toggleUserBlock(ctx) {
9900
+ clearSessionStatsCache();
9901
+ userStatsCache.expiresAt = 0;
9223
9902
  try {
9224
9903
  const { userId } = ctx.params;
9225
9904
  const body = ctx.request?.body;
@@ -9279,182 +9958,6 @@ var require_session = __commonJS({
9279
9958
  }
9280
9959
  });
9281
9960
 
9282
- // server/src/controllers/license.js
9283
- var require_license = __commonJS({
9284
- "server/src/controllers/license.js"(exports2, module2) {
9285
- "use strict";
9286
- var { sendServerError } = require_http_errors();
9287
- var PROVIDER_UNREACHABLE_MESSAGE = "License server unreachable. The plugin keeps working without a key.";
9288
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9289
- module2.exports = ({ strapi: strapi2 }) => ({
9290
- async getStatus(ctx) {
9291
- try {
9292
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9293
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
9294
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
9295
- if (!licenseKey) {
9296
- return ctx.send({
9297
- success: true,
9298
- valid: true,
9299
- demo: false,
9300
- hasKey: false,
9301
- data: {
9302
- features: {
9303
- premium: true,
9304
- advanced: true,
9305
- enterprise: true,
9306
- custom: true
9307
- }
9308
- },
9309
- message: "Plugin is active. License key activation is optional."
9310
- });
9311
- }
9312
- const license = await licenseGuard.getLicenseByKey(licenseKey);
9313
- return ctx.send({
9314
- success: true,
9315
- valid: true,
9316
- demo: false,
9317
- hasKey: true,
9318
- data: {
9319
- licenseKey,
9320
- email: license?.email || null,
9321
- firstName: license?.firstName || null,
9322
- lastName: license?.lastName || null,
9323
- isActive: license?.isActive ?? true,
9324
- isExpired: license?.isExpired ?? false,
9325
- isOnline: license?.isOnline ?? false,
9326
- expiresAt: license?.expiresAt || null,
9327
- lastPingAt: license?.lastPingAt || null,
9328
- deviceName: license?.deviceName || null,
9329
- deviceId: license?.deviceId || null,
9330
- ipAddress: license?.ipAddress || null,
9331
- features: {
9332
- premium: true,
9333
- advanced: true,
9334
- enterprise: true,
9335
- custom: true
9336
- },
9337
- maxDevices: license?.maxDevices || 1,
9338
- currentDevices: license?.currentDevices || 0
9339
- }
9340
- });
9341
- } catch (error) {
9342
- strapi2.log.error(
9343
- "[magic-sessionmanager] Error getting license status:",
9344
- error?.name || "Error"
9345
- );
9346
- return sendServerError(ctx, 500, "Error getting license status");
9347
- }
9348
- },
9349
- async autoCreate(ctx) {
9350
- try {
9351
- const adminUser = ctx.state.user;
9352
- if (!adminUser) {
9353
- return ctx.unauthorized("No admin user logged in");
9354
- }
9355
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9356
- const license = await licenseGuard.createLicense({
9357
- email: adminUser.email,
9358
- firstName: adminUser.firstname || "Admin",
9359
- lastName: adminUser.lastname || "User"
9360
- });
9361
- if (!license) {
9362
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
9363
- }
9364
- await licenseGuard.storeLicenseKey(license.licenseKey);
9365
- return ctx.send({
9366
- success: true,
9367
- message: "License automatically created and stored",
9368
- data: license
9369
- });
9370
- } catch (error) {
9371
- strapi2.log.error(
9372
- "[magic-sessionmanager] Error auto-creating license:",
9373
- error?.name || "Error"
9374
- );
9375
- return sendServerError(ctx, 500, "Error creating license");
9376
- }
9377
- },
9378
- async createAndActivate(ctx) {
9379
- try {
9380
- const { email, firstName, lastName } = ctx.request.body || {};
9381
- if (![email, firstName, lastName].every((value) => typeof value === "string" && value.trim())) {
9382
- return ctx.badRequest("Email, firstName, and lastName are required");
9383
- }
9384
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9385
- const license = await licenseGuard.createLicense({ email, firstName, lastName });
9386
- if (!license) {
9387
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
9388
- }
9389
- await licenseGuard.storeLicenseKey(license.licenseKey);
9390
- return ctx.send({
9391
- success: true,
9392
- message: "License created and stored successfully",
9393
- data: license
9394
- });
9395
- } catch (error) {
9396
- strapi2.log.error("[magic-sessionmanager] Error creating license:", error?.name || "Error");
9397
- return sendServerError(ctx, 500, "Error creating license");
9398
- }
9399
- },
9400
- async ping(ctx) {
9401
- try {
9402
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
9403
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
9404
- if (!licenseKey) {
9405
- return ctx.badRequest("No license key found");
9406
- }
9407
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9408
- const verification = await licenseGuard.verifyLicense(licenseKey);
9409
- return ctx.send({
9410
- success: true,
9411
- message: verification.valid ? "License refreshed successfully" : "License key could not be verified, but the plugin keeps working.",
9412
- data: verification.data
9413
- });
9414
- } catch (error) {
9415
- strapi2.log.error("[magic-sessionmanager] Error refreshing license:", error?.name || "Error");
9416
- return sendServerError(ctx, 500, "Error refreshing license");
9417
- }
9418
- },
9419
- async storeKey(ctx) {
9420
- try {
9421
- const { licenseKey, email } = ctx.request.body || {};
9422
- if (typeof licenseKey !== "string" || !licenseKey.trim()) {
9423
- return ctx.badRequest("License key is required");
9424
- }
9425
- if (email !== void 0 && email !== null && email !== "") {
9426
- if (typeof email !== "string" || !EMAIL_PATTERN.test(email.trim())) {
9427
- return ctx.badRequest("Email must be a valid email address");
9428
- }
9429
- }
9430
- const trimmedKey = licenseKey.trim();
9431
- const trimmedEmail = typeof email === "string" && email.trim() ? email.trim().toLowerCase() : null;
9432
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9433
- const verification = await licenseGuard.verifyLicense(trimmedKey);
9434
- if (!verification.valid && !verification.networkError) {
9435
- strapi2.log.warn("[magic-sessionmanager] Rejected an invalid license key");
9436
- return ctx.badRequest("Invalid or expired license key");
9437
- }
9438
- const license = verification.valid ? await licenseGuard.getLicenseByKey(trimmedKey) : null;
9439
- if (license?.email && trimmedEmail && license.email.toLowerCase() !== trimmedEmail) {
9440
- strapi2.log.warn("[magic-sessionmanager] Rejected a license holder email mismatch");
9441
- return ctx.badRequest("Email address does not match this license key");
9442
- }
9443
- await licenseGuard.storeLicenseKey(trimmedKey);
9444
- return ctx.send({
9445
- success: true,
9446
- message: verification.networkError ? "License key stored. The license server was unreachable, but the plugin keeps working." : "License key stored successfully",
9447
- data: verification.data || { licenseKey: trimmedKey, email: trimmedEmail }
9448
- });
9449
- } catch (error) {
9450
- strapi2.log.error("[magic-sessionmanager] Error storing license key:", error?.name || "Error");
9451
- return sendServerError(ctx, 500, "Error validating license key");
9452
- }
9453
- }
9454
- });
9455
- }
9456
- });
9457
-
9458
9961
  // scripts/geoip-updater.cjs
9459
9962
  var require_geoip_updater = __commonJS({
9460
9963
  "scripts/geoip-updater.cjs"(exports2, module2) {
@@ -10512,12 +11015,10 @@ var require_controllers = __commonJS({
10512
11015
  "server/src/controllers/index.js"(exports2, module2) {
10513
11016
  "use strict";
10514
11017
  var session = require_session();
10515
- var license = require_license();
10516
11018
  var settings = require_settings();
10517
11019
  var geoip = require_geoip();
10518
11020
  module2.exports = {
10519
11021
  session,
10520
- license,
10521
11022
  settings,
10522
11023
  geoip
10523
11024
  };
@@ -10539,6 +11040,12 @@ var require_session2 = __commonJS({
10539
11040
  persistAccessTokenRevocation
10540
11041
  } = require_session_revocation();
10541
11042
  var { getNativeSessionManager } = require_native_session_manager();
11043
+ var {
11044
+ exportSessionBatch,
11045
+ getSessionAnalytics: getSessionAnalyticsFromDb,
11046
+ getSessionStats: getSessionStatsFromDb,
11047
+ listSessionPage
11048
+ } = require_session_list();
10542
11049
  var {
10543
11050
  NATIVE_SESSION_PREFIX,
10544
11051
  mapNativeSessionToView,
@@ -11234,8 +11741,51 @@ var require_session2 = __commonJS({
11234
11741
  throw err;
11235
11742
  }
11236
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
+ },
11237
11784
  /**
11238
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
+ *
11239
11789
  * @returns {Promise<Array>}
11240
11790
  */
11241
11791
  async getAllSessions() {
@@ -11728,367 +12278,6 @@ var require_session2 = __commonJS({
11728
12278
  }
11729
12279
  });
11730
12280
 
11731
- // package.json
11732
- var require_package = __commonJS({
11733
- "package.json"(exports2, module2) {
11734
- module2.exports = {
11735
- version: "4.10.0",
11736
- keywords: [
11737
- "strapi",
11738
- "plugin",
11739
- "strapi-plugin",
11740
- "strapi-v5",
11741
- "sessions",
11742
- "user-tracking",
11743
- "login-logout",
11744
- "activity-monitoring"
11745
- ],
11746
- type: "commonjs",
11747
- bin: {
11748
- "strapi-magic-sessionmanager-geoip": "./scripts/update-geoip-db.mjs"
11749
- },
11750
- exports: {
11751
- "./package.json": "./package.json",
11752
- "./strapi-admin": {
11753
- source: "./admin/src/index.js",
11754
- import: "./dist/admin/index.mjs",
11755
- require: "./dist/admin/index.js",
11756
- default: "./dist/admin/index.js"
11757
- },
11758
- "./strapi-server": {
11759
- source: "./server/src/index.js",
11760
- import: "./dist/server/index.mjs",
11761
- require: "./dist/server/index.js",
11762
- default: "./dist/server/index.js"
11763
- }
11764
- },
11765
- files: [
11766
- "dist",
11767
- "strapi-admin.js",
11768
- "strapi-server.js",
11769
- "scripts/geoip-updater.cjs",
11770
- "scripts/update-geoip-db.mjs",
11771
- "README.md",
11772
- "LICENSE",
11773
- "CHANGELOG.md",
11774
- "pics"
11775
- ],
11776
- engines: {
11777
- node: "^22.22.2 || >=24.15.0",
11778
- npm: ">=6.0.0"
11779
- },
11780
- scripts: {
11781
- clean: `node -e "require('fs').rmSync('dist', { recursive: true, force: true })"`,
11782
- test: "node --test tests/*.test.js tests/*.test.mjs",
11783
- "test:concurrency": "node scripts/concurrency/run.mjs",
11784
- "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
11785
- "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
11786
- lint: "eslint .",
11787
- "lint:fix": "eslint . --fix",
11788
- format: "prettier --write .",
11789
- "format:check": "prettier --check .",
11790
- build: "npm run clean && strapi-plugin build && node scripts/build-server-bundle.mjs",
11791
- watch: "strapi-plugin watch",
11792
- "watch:link": "strapi-plugin watch:link",
11793
- "geoip:update": "node scripts/update-geoip-db.mjs",
11794
- verify: "strapi-plugin verify",
11795
- "verify:runtime": "node scripts/verify-server-bundle.mjs",
11796
- prepublishOnly: "npm test && npm run build && npm run verify && npm run verify:runtime"
11797
- },
11798
- dependencies: {
11799
- "@maxmind/geoip2-node": "^7.1.0",
11800
- "sanitize-html": "^2.18.0"
11801
- },
11802
- devDependencies: {
11803
- "@eslint/js": "^10.0.1",
11804
- "@semantic-release/changelog": "^7.0.0",
11805
- "@semantic-release/commit-analyzer": "^13.0.1",
11806
- "@semantic-release/git": "^11.0.1",
11807
- "@semantic-release/github": "^12.0.10",
11808
- "@semantic-release/npm": "^13.2.0",
11809
- "@semantic-release/release-notes-generator": "^14.1.1",
11810
- "@strapi/design-system": "^2.2.4",
11811
- "@strapi/icons": "^2.2.4",
11812
- "@strapi/sdk-plugin": "^6.1.1",
11813
- "@strapi/strapi": "5.61.0",
11814
- "better-sqlite3": "^13.0.3",
11815
- esbuild: "^0.28.2",
11816
- eslint: "^10.14.0",
11817
- "eslint-config-prettier": "^10.1.8",
11818
- "eslint-plugin-react-hooks": "^7.1.1",
11819
- globals: "^17.14.0",
11820
- pg: "^8.23.1",
11821
- prettier: "^3.9.10",
11822
- react: "^18.3.1",
11823
- "react-dom": "^18.3.1",
11824
- "react-intl": "^6.8.9",
11825
- "react-router-dom": "^6.30.6",
11826
- "semantic-release": "^25.0.9",
11827
- "styled-components": "^6.6.0"
11828
- },
11829
- peerDependencies: {
11830
- "@strapi/design-system": "^2.0.0",
11831
- "@strapi/icons": "^2.0.0",
11832
- "@strapi/strapi": "^5.0.0",
11833
- "@strapi/utils": "^5.0.0",
11834
- react: "^18.3.1",
11835
- "react-dom": "^18.3.1",
11836
- "react-intl": "^6.0.0",
11837
- "react-router-dom": "^6.0.0",
11838
- "styled-components": "^6.0.0"
11839
- },
11840
- publishConfig: {
11841
- access: "public"
11842
- },
11843
- strapi: {
11844
- kind: "plugin",
11845
- name: "magic-sessionmanager",
11846
- displayName: "Magic Sessionmanager",
11847
- description: "Advanced session management for Strapi v5 - Track user login/logout, session history, and online status"
11848
- },
11849
- name: "strapi-plugin-magic-sessionmanager",
11850
- description: "Advanced Session Management for Strapi v5 - Track user sessions with IP geolocation, security scoring, and real-time monitoring",
11851
- license: "MIT",
11852
- author: "Schero D.",
11853
- repository: {
11854
- type: "git",
11855
- url: "https://github.com/Schero94/Magic-Sessionmanager.git"
11856
- },
11857
- bugs: {
11858
- url: "https://github.com/Schero94/Magic-Sessionmanager/issues"
11859
- },
11860
- homepage: "https://github.com/Schero94/Magic-Sessionmanager#readme",
11861
- private: false
11862
- };
11863
- }
11864
- });
11865
-
11866
- // server/src/services/license-guard.js
11867
- var require_license_guard = __commonJS({
11868
- "server/src/services/license-guard.js"(exports2, module2) {
11869
- "use strict";
11870
- var crypto = require("crypto");
11871
- var os = require("os");
11872
- var pluginPkg = require_package();
11873
- var { createLogger } = require_logger();
11874
- var { setPluginStoreValue, withPluginStoreKey } = require_plugin_store();
11875
- var DEFAULT_LICENSE_SERVER_URL = "https://magicapi.fitlex.me";
11876
- var envTimeout = Number(process.env.MAGIC_LICENSE_TIMEOUT_MS);
11877
- var DEFAULT_FETCH_TIMEOUT_MS = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 12e3;
11878
- var FETCH_RETRIES = 1;
11879
- var FETCH_RETRY_BACKOFF_MS = 750;
11880
- async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
11881
- let lastError;
11882
- for (let attempt = 0; attempt <= FETCH_RETRIES; attempt += 1) {
11883
- const controller = new AbortController();
11884
- const timer = setTimeout(() => controller.abort(), timeoutMs);
11885
- try {
11886
- return await fetch(url, { ...options, signal: controller.signal });
11887
- } catch (err) {
11888
- lastError = err;
11889
- if (attempt < FETCH_RETRIES) {
11890
- await new Promise((r) => setTimeout(r, FETCH_RETRY_BACKOFF_MS));
11891
- continue;
11892
- }
11893
- throw err;
11894
- } finally {
11895
- clearTimeout(timer);
11896
- }
11897
- }
11898
- throw lastError;
11899
- }
11900
- module2.exports = ({ strapi: strapi2 }) => {
11901
- const log = createLogger(strapi2);
11902
- return {
11903
- getLicenseServerUrl() {
11904
- return process.env.MAGIC_LICENSE_SERVER_URL || DEFAULT_LICENSE_SERVER_URL;
11905
- },
11906
- async generateDeviceId() {
11907
- try {
11908
- return await withPluginStoreKey(strapi2, "deviceId", async (pluginStore) => {
11909
- const stored = await pluginStore.get({ key: "deviceId" });
11910
- if (stored && typeof stored === "string" && stored.length >= 16) {
11911
- return stored;
11912
- }
11913
- let identifier;
11914
- try {
11915
- const networkInterfaces = os.networkInterfaces();
11916
- const macAddresses = [];
11917
- Object.values(networkInterfaces).forEach((interfaces) => {
11918
- interfaces?.forEach((iface) => {
11919
- if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
11920
- macAddresses.push(iface.mac);
11921
- }
11922
- });
11923
- });
11924
- identifier = `${macAddresses.join("-")}-${os.hostname()}`;
11925
- } catch {
11926
- identifier = `${Date.now()}-${crypto.randomBytes(16).toString("hex")}`;
11927
- }
11928
- const deviceId = crypto.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
11929
- await pluginStore.set({ key: "deviceId", value: deviceId });
11930
- return deviceId;
11931
- });
11932
- } catch {
11933
- return crypto.randomBytes(16).toString("hex");
11934
- }
11935
- },
11936
- getDeviceName() {
11937
- try {
11938
- return os.hostname() || "Unknown Device";
11939
- } catch {
11940
- return "Unknown Device";
11941
- }
11942
- },
11943
- getIpAddress() {
11944
- try {
11945
- const networkInterfaces = os.networkInterfaces();
11946
- for (const name of Object.keys(networkInterfaces)) {
11947
- const interfaces = networkInterfaces[name];
11948
- if (!interfaces) continue;
11949
- for (const iface of interfaces) {
11950
- if (iface.family === "IPv4" && !iface.internal) {
11951
- return iface.address;
11952
- }
11953
- }
11954
- }
11955
- return "127.0.0.1";
11956
- } catch {
11957
- return "127.0.0.1";
11958
- }
11959
- },
11960
- getUserAgent() {
11961
- const pluginVersion = pluginPkg.version || "1.0.0";
11962
- const strapiVersion = strapi2.config.get("info.strapi") || "5.0.0";
11963
- return `MagicSessionManager/${pluginVersion} Strapi/${strapiVersion} Node/${process.version} ${os.platform()}/${os.release()}`;
11964
- },
11965
- async createLicense({ email, firstName, lastName }) {
11966
- try {
11967
- const response = await fetchWithTimeout(
11968
- `${this.getLicenseServerUrl()}/api/licenses/create`,
11969
- {
11970
- method: "POST",
11971
- headers: { "Content-Type": "application/json" },
11972
- body: JSON.stringify({
11973
- email,
11974
- firstName,
11975
- lastName,
11976
- deviceName: this.getDeviceName(),
11977
- deviceId: await this.generateDeviceId(),
11978
- ipAddress: this.getIpAddress(),
11979
- userAgent: this.getUserAgent(),
11980
- pluginName: "magic-sessionmanager",
11981
- productName: "Magic Session Manager"
11982
- })
11983
- }
11984
- );
11985
- const data = await response.json();
11986
- if (data.success) {
11987
- log.info("[SUCCESS] License created");
11988
- return data.data;
11989
- }
11990
- log.warn("[WARNING] License creation rejected by server");
11991
- return null;
11992
- } catch (error) {
11993
- log.warn("[WARNING] Error creating license:", error?.name || "Error");
11994
- return null;
11995
- }
11996
- },
11997
- async verifyLicense(licenseKey) {
11998
- try {
11999
- const response = await fetchWithTimeout(
12000
- `${this.getLicenseServerUrl()}/api/licenses/verify`,
12001
- {
12002
- method: "POST",
12003
- headers: { "Content-Type": "application/json" },
12004
- body: JSON.stringify({
12005
- licenseKey,
12006
- pluginName: "magic-sessionmanager",
12007
- productName: "Magic Session Manager"
12008
- })
12009
- }
12010
- );
12011
- const data = await response.json();
12012
- if (data.success && data.data) {
12013
- await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
12014
- return { valid: true, data: data.data };
12015
- }
12016
- return { valid: false, data: null };
12017
- } catch (error) {
12018
- log.warn(
12019
- `[WARNING] License server unreachable during optional activation (${error?.name || "Error"}). This does not block the plugin.`
12020
- );
12021
- return { valid: false, data: null, networkError: true };
12022
- }
12023
- },
12024
- async getLicenseByKey(licenseKey) {
12025
- try {
12026
- const encodedKey = encodeURIComponent(licenseKey);
12027
- const response = await fetchWithTimeout(
12028
- `${this.getLicenseServerUrl()}/api/licenses/key/${encodedKey}`,
12029
- {
12030
- method: "GET",
12031
- headers: { "Content-Type": "application/json" }
12032
- }
12033
- );
12034
- const data = await response.json();
12035
- if (data.success && data.data) return data.data;
12036
- return null;
12037
- } catch (error) {
12038
- log.warn("[WARNING] Could not fetch license by key:", error?.name || "Error");
12039
- return null;
12040
- }
12041
- },
12042
- async pingLicense() {
12043
- return null;
12044
- },
12045
- async storeLicenseKey(licenseKey) {
12046
- await setPluginStoreValue(strapi2, "licenseKey", licenseKey);
12047
- await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
12048
- log.info("[SUCCESS] License key stored");
12049
- return true;
12050
- },
12051
- startPinging() {
12052
- return null;
12053
- },
12054
- async initialize() {
12055
- return { valid: true, demo: false, data: null };
12056
- },
12057
- cleanup() {
12058
- },
12059
- async hasFeature() {
12060
- return true;
12061
- },
12062
- async getMaxSessions() {
12063
- return -1;
12064
- },
12065
- async getLicenseTierInfo() {
12066
- try {
12067
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
12068
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
12069
- const hasKey = !!licenseKey;
12070
- return {
12071
- tier: hasKey ? "pro" : "free",
12072
- hasKey,
12073
- features: {
12074
- premium: true,
12075
- advanced: true,
12076
- enterprise: true
12077
- }
12078
- };
12079
- } catch {
12080
- return {
12081
- tier: "free",
12082
- hasKey: false,
12083
- features: { premium: true, advanced: true, enterprise: true }
12084
- };
12085
- }
12086
- }
12087
- };
12088
- };
12089
- }
12090
- });
12091
-
12092
12281
  // server/src/services/geolocation.js
12093
12282
  var require_geolocation = __commonJS({
12094
12283
  "server/src/services/geolocation.js"(exports2, module2) {
@@ -13241,12 +13430,10 @@ var require_services = __commonJS({
13241
13430
  "server/src/services/index.js"(exports2, module2) {
13242
13431
  "use strict";
13243
13432
  var session = require_session2();
13244
- var licenseGuard = require_license_guard();
13245
13433
  var geolocation = require_geolocation();
13246
13434
  var notifications = require_notifications();
13247
13435
  module2.exports = {
13248
13436
  session,
13249
- "license-guard": licenseGuard,
13250
13437
  geolocation,
13251
13438
  notifications
13252
13439
  };