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
@@ -785,10 +785,21 @@ var require_plugin_store = __commonJS({
785
785
  async function setPluginStoreValue(strapi2, key, value) {
786
786
  await withPluginStoreKey(strapi2, key, (store) => store.set({ key, value }));
787
787
  }
788
+ var LEGACY_LICENSE_STORE_KEYS = Object.freeze(["licenseKey", "lastValidated", "deviceId"]);
789
+ async function removeLegacyLicenseData(strapi2) {
790
+ const query = strapi2?.db?.query?.(CORE_STORE_UID);
791
+ if (!query || typeof query.deleteMany !== "function") return 0;
792
+ const result = await query.deleteMany({
793
+ where: { key: { $in: LEGACY_LICENSE_STORE_KEYS.map(coreStoreKey) } }
794
+ });
795
+ return Number(result?.count) || 0;
796
+ }
788
797
  module.exports = {
798
+ LEGACY_LICENSE_STORE_KEYS,
789
799
  PLUGIN_ID,
790
800
  collapseDuplicateStoreRows,
791
801
  coreStoreKey,
802
+ removeLegacyLicenseData,
792
803
  setPluginStoreValue,
793
804
  withPluginStoreKey
794
805
  };
@@ -1902,6 +1913,10 @@ var require_last_seen = __commonJS({
1902
1913
  if (!ctx.state.user) {
1903
1914
  return;
1904
1915
  }
1916
+ const strategyName = ctx.state.auth?.strategy?.name;
1917
+ if (strategyName === "admin" || strategyName === "admin-token") {
1918
+ return;
1919
+ }
1905
1920
  let userDocId = ctx.state.user.documentId;
1906
1921
  if (!userDocId && ctx.state.user.id) {
1907
1922
  try {
@@ -5905,7 +5920,7 @@ var require_bootstrap = __commonJS({
5905
5920
  initCoordination,
5906
5921
  LockTimeoutError
5907
5922
  } = require_coordination();
5908
- var { withPluginStoreKey } = require_plugin_store();
5923
+ var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
5909
5924
  var {
5910
5925
  classifyJwtIssuingRequest,
5911
5926
  isFailedLoginTrackedPath,
@@ -5939,6 +5954,16 @@ var require_bootstrap = __commonJS({
5939
5954
  }
5940
5955
  return settings;
5941
5956
  }
5957
+ async function removeLegacyLicenseRows(strapi2, log) {
5958
+ try {
5959
+ const removed = await removeLegacyLicenseData(strapi2);
5960
+ if (removed > 0) {
5961
+ log.info(`[CLEANUP] Removed ${removed} stored value(s) of the former license feature`);
5962
+ }
5963
+ } catch (err) {
5964
+ log.warn("[CLEANUP] Could not remove former license data:", err?.name || "Error");
5965
+ }
5966
+ }
5942
5967
  module.exports = async ({ strapi: strapi2 }) => {
5943
5968
  const log = createLogger(strapi2);
5944
5969
  log.info("[START] Bootstrap starting...");
@@ -5953,9 +5978,7 @@ var require_bootstrap = __commonJS({
5953
5978
  await checkEncryptionKeyConsistency(strapi2, log);
5954
5979
  await ensureSessionLookupIndexes(strapi2, log);
5955
5980
  await registerSessionAwareAuthStrategy(strapi2);
5956
- const licenseGuardService = strapi2.plugin("magic-sessionmanager").service("license-guard");
5957
- await licenseGuardService.initialize();
5958
- log.info("[SUCCESS] Session Manager active - all features are available without a license key");
5981
+ await removeLegacyLicenseRows(strapi2, log);
5959
5982
  const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
5960
5983
  if (!strapi2.sessionManagerIntervals) {
5961
5984
  strapi2.sessionManagerIntervals = {};
@@ -6915,7 +6938,9 @@ var require_bootstrap = __commonJS({
6915
6938
  });
6916
6939
  const authenticatedRole = roles?.[0];
6917
6940
  if (!authenticatedRole) {
6918
- log.warn("Authenticated role not found - skipping permission setup");
6941
+ log.info(
6942
+ "Authenticated role does not exist yet; permission setup runs again on the first Session Manager API request"
6943
+ );
6919
6944
  return false;
6920
6945
  }
6921
6946
  const requiredActions = [
@@ -7037,8 +7062,14 @@ var require_bootstrap = __commonJS({
7037
7062
  const knex = strapi2.db.connection;
7038
7063
  const tableName = "magic_sessions";
7039
7064
  const definitions = [
7040
- { column: "token_hash", name: "idx_magic_sessions_token_hash" },
7041
- { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
7065
+ { columns: ["token_hash", "is_active"], name: "idx_magic_sessions_token_hash" },
7066
+ { columns: ["refresh_token_hash", "is_active"], name: "idx_magic_sessions_refresh_hash" },
7067
+ { columns: ["login_time", "id"], name: "idx_magic_sessions_login_time" },
7068
+ { columns: ["last_active", "id"], name: "idx_magic_sessions_last_active" },
7069
+ { columns: ["is_active", "last_active"], name: "idx_magic_sessions_active_last" },
7070
+ { columns: ["is_active", "login_time"], name: "idx_magic_sessions_active_login" },
7071
+ { columns: ["is_active", "termination_reason"], name: "idx_magic_sessions_active_reason" },
7072
+ { columns: ["native_session_id"], name: "idx_magic_sessions_native_id" }
7042
7073
  ];
7043
7074
  if (!await knex.schema.hasTable(tableName)) return;
7044
7075
  const dialect = strapi2.db.dialect.client;
@@ -7054,11 +7085,11 @@ var require_bootstrap = __commonJS({
7054
7085
  log.debug(`[INDEX] ${definition.name} already exists`);
7055
7086
  continue;
7056
7087
  }
7057
- await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??, ??)", [
7088
+ const placeholders = definition.columns.map(() => "??").join(", ");
7089
+ await knex.raw(`CREATE INDEX IF NOT EXISTS ?? ON ?? (${placeholders})`, [
7058
7090
  definition.name,
7059
7091
  tableName,
7060
- definition.column,
7061
- "is_active"
7092
+ ...definition.columns
7062
7093
  ]);
7063
7094
  log.info(`[INDEX] Created ${definition.name}`);
7064
7095
  continue;
@@ -7076,7 +7107,7 @@ var require_bootstrap = __commonJS({
7076
7107
  continue;
7077
7108
  }
7078
7109
  await knex.schema.alterTable(tableName, (table) => {
7079
- table.index([definition.column, "is_active"], definition.name);
7110
+ table.index(definition.columns, definition.name);
7080
7111
  });
7081
7112
  log.info(`[INDEX] Created ${definition.name}`);
7082
7113
  }
@@ -7799,6 +7830,12 @@ var require_admin = __commonJS({
7799
7830
  config: { actions: [PLUGIN_ACCESS_ACTION] }
7800
7831
  }
7801
7832
  ];
7833
+ var adminReadRateLimit = () => [
7834
+ {
7835
+ name: "plugin::magic-sessionmanager.rate-limit",
7836
+ config: { profile: "read", max: 120, window: 6e4 }
7837
+ }
7838
+ ];
7802
7839
  var isDevEnvironment = (() => {
7803
7840
  const env = (process.env.NODE_ENV || "development").toLowerCase();
7804
7841
  return env !== "production" && env !== "staging";
@@ -7811,7 +7848,8 @@ var require_admin = __commonJS({
7811
7848
  handler: "session.getAllSessionsAdmin",
7812
7849
  config: {
7813
7850
  policies: adminPolicy(),
7814
- description: "Get all sessions - active and inactive (admin)"
7851
+ middlewares: adminReadRateLimit(),
7852
+ description: "List sessions (admin); paginated with page/pageSize, filters and sort"
7815
7853
  }
7816
7854
  },
7817
7855
  {
@@ -7820,7 +7858,38 @@ var require_admin = __commonJS({
7820
7858
  handler: "session.getActiveSessions",
7821
7859
  config: {
7822
7860
  policies: adminPolicy(),
7823
- description: "Get only active sessions (admin)"
7861
+ middlewares: adminReadRateLimit(),
7862
+ description: "Get only active sessions (admin); paginated with page/pageSize"
7863
+ }
7864
+ },
7865
+ {
7866
+ method: "GET",
7867
+ path: "/sessions/stats",
7868
+ handler: "session.getSessionStatsAdmin",
7869
+ config: {
7870
+ policies: adminPolicy(),
7871
+ middlewares: adminReadRateLimit(),
7872
+ description: "Get count-only session statistics (admin)"
7873
+ }
7874
+ },
7875
+ {
7876
+ method: "GET",
7877
+ path: "/sessions/analytics",
7878
+ handler: "session.getSessionAnalyticsAdmin",
7879
+ config: {
7880
+ policies: adminPolicy(),
7881
+ middlewares: adminReadRateLimit(),
7882
+ description: "Get count-only analytics over all sessions (admin)"
7883
+ }
7884
+ },
7885
+ {
7886
+ method: "GET",
7887
+ path: "/sessions/export",
7888
+ handler: "session.exportSessionsAdmin",
7889
+ config: {
7890
+ policies: adminPolicy(),
7891
+ middlewares: adminReadRateLimit(),
7892
+ description: "Get one export batch of sessions with a keyset cursor (admin)"
7824
7893
  }
7825
7894
  },
7826
7895
  {
@@ -7883,55 +7952,10 @@ var require_admin = __commonJS({
7883
7952
  handler: "session.getUserStatsAdmin",
7884
7953
  config: {
7885
7954
  policies: adminPolicy(),
7955
+ middlewares: adminReadRateLimit(),
7886
7956
  description: "Get aggregate end-user counts only (admin)"
7887
7957
  }
7888
7958
  },
7889
- // ============================ LICENSE ============================
7890
- {
7891
- method: "GET",
7892
- path: "/license/status",
7893
- handler: "license.getStatus",
7894
- config: {
7895
- policies: adminPolicy(),
7896
- description: "Get license status (admin)"
7897
- }
7898
- },
7899
- {
7900
- method: "POST",
7901
- path: "/license/auto-create",
7902
- handler: "license.autoCreate",
7903
- config: {
7904
- policies: adminPolicy(),
7905
- description: "Auto-create license for current admin (admin)"
7906
- }
7907
- },
7908
- {
7909
- method: "POST",
7910
- path: "/license/create",
7911
- handler: "license.createAndActivate",
7912
- config: {
7913
- policies: adminPolicy(),
7914
- description: "Create and activate a new license (admin)"
7915
- }
7916
- },
7917
- {
7918
- method: "POST",
7919
- path: "/license/ping",
7920
- handler: "license.ping",
7921
- config: {
7922
- policies: adminPolicy(),
7923
- description: "Ping the license server (admin)"
7924
- }
7925
- },
7926
- {
7927
- method: "POST",
7928
- path: "/license/store-key",
7929
- handler: "license.storeKey",
7930
- config: {
7931
- policies: adminPolicy(),
7932
- description: "Store a license key (admin)"
7933
- }
7934
- },
7935
7959
  // ============================ GEOLOCATION ============================
7936
7960
  {
7937
7961
  method: "GET",
@@ -8346,6 +8370,529 @@ var require_http_errors = __commonJS({
8346
8370
  }
8347
8371
  });
8348
8372
 
8373
+ // server/src/utils/session-list-query.js
8374
+ var require_session_list_query = __commonJS({
8375
+ "server/src/utils/session-list-query.js"(exports, module) {
8376
+ "use strict";
8377
+ var { z } = __require("@strapi/utils");
8378
+ var SESSION_STATUS_FILTERS = Object.freeze(["all", "open", "active", "idle", "ended"]);
8379
+ var RECORDED_END_REASONS = Object.freeze(["logout", "idle", "expired", "manual", "blocked"]);
8380
+ var END_REASON_FILTERS = Object.freeze(["all", ...RECORDED_END_REASONS, "unrecorded"]);
8381
+ var SORT_ORDERS = Object.freeze({
8382
+ "loginTime:desc": [{ loginTime: "desc" }, { id: "desc" }],
8383
+ "loginTime:asc": [{ loginTime: "asc" }, { id: "asc" }],
8384
+ "lastActive:desc": [{ lastActive: "desc" }, { id: "desc" }],
8385
+ "lastActive:asc": [{ lastActive: "asc" }, { id: "asc" }]
8386
+ });
8387
+ var SORT_KEYS = Object.freeze(Object.keys(SORT_ORDERS));
8388
+ var MAX_PAGE_SIZE = 100;
8389
+ var MAX_SEARCH_LENGTH = 100;
8390
+ var MAX_LIST_OFFSET = 5e4;
8391
+ var MAX_EXPORT_BATCH = 1e3;
8392
+ var MAX_EXPORT_ROWS = 5e4;
8393
+ var LIST_FIELDS = Object.freeze([
8394
+ "id",
8395
+ "documentId",
8396
+ "sessionId",
8397
+ "nativeSessionId",
8398
+ "ipAddress",
8399
+ "userAgent",
8400
+ "loginTime",
8401
+ "logoutTime",
8402
+ "lastActive",
8403
+ "isActive",
8404
+ "terminatedManually",
8405
+ "terminationReason",
8406
+ "geoLocation",
8407
+ "securityScore",
8408
+ "deviceType",
8409
+ "browserName",
8410
+ "osName",
8411
+ "createdAt",
8412
+ "updatedAt"
8413
+ ]);
8414
+ var LIST_USER_FIELDS = Object.freeze(["documentId", "email", "username"]);
8415
+ var searchText = z.string().trim().max(MAX_SEARCH_LENGTH, `search must be at most ${MAX_SEARCH_LENGTH} characters`);
8416
+ var filterShape = {
8417
+ status: z.enum(SESSION_STATUS_FILTERS).default("all"),
8418
+ reason: z.enum(END_REASON_FILTERS).default("all"),
8419
+ search: searchText.default("")
8420
+ };
8421
+ var listQuerySchema = z.strictObject({
8422
+ page: z.coerce.number().int().min(1).max(1e6).default(1),
8423
+ pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(25),
8424
+ sort: z.enum(SORT_KEYS).default("loginTime:desc"),
8425
+ ...filterShape
8426
+ }).refine((query) => (query.page - 1) * query.pageSize < MAX_LIST_OFFSET, {
8427
+ message: `Pages past the first ${MAX_LIST_OFFSET} sessions are not available. Narrow the filter or use the export.`,
8428
+ path: ["page"]
8429
+ });
8430
+ var exportQuerySchema = z.strictObject({
8431
+ limit: z.coerce.number().int().min(1).max(MAX_EXPORT_BATCH).default(MAX_EXPORT_BATCH),
8432
+ cursor: z.string().max(200).optional(),
8433
+ ...filterShape
8434
+ });
8435
+ var statsQuerySchema = z.strictObject({});
8436
+ function isPaginatedListQuery(query) {
8437
+ return Boolean(
8438
+ query && (Object.prototype.hasOwnProperty.call(query, "page") || Object.prototype.hasOwnProperty.call(query, "pageSize"))
8439
+ );
8440
+ }
8441
+ function parseQuery(schema, input) {
8442
+ const result = schema.safeParse(input ?? {});
8443
+ if (result.success) return { ok: true, value: result.data };
8444
+ return {
8445
+ ok: false,
8446
+ errors: result.error.issues.map((issue) => ({
8447
+ path: issue.path.join("."),
8448
+ message: issue.message
8449
+ }))
8450
+ };
8451
+ }
8452
+ function usedSince(cutoff) {
8453
+ return {
8454
+ $or: [
8455
+ { lastActive: { $gt: cutoff } },
8456
+ { $and: [{ lastActive: { $null: true } }, { loginTime: { $gt: cutoff } }] }
8457
+ ]
8458
+ };
8459
+ }
8460
+ function notUsedSince(cutoff) {
8461
+ return {
8462
+ $or: [
8463
+ { lastActive: { $lte: cutoff } },
8464
+ { $and: [{ lastActive: { $null: true } }, { loginTime: { $lte: cutoff } }] }
8465
+ ]
8466
+ };
8467
+ }
8468
+ function buildSessionWhere({ status = "all", reason = "all", search = "" } = {}, { cutoff }) {
8469
+ const conditions = [];
8470
+ if (status === "open") conditions.push({ isActive: true });
8471
+ if (status === "active") conditions.push({ isActive: true }, usedSince(cutoff));
8472
+ if (status === "idle") conditions.push({ isActive: true }, notUsedSince(cutoff));
8473
+ if (status === "ended") {
8474
+ conditions.push({ isActive: false });
8475
+ if (reason === "unrecorded") {
8476
+ conditions.push({
8477
+ $or: [
8478
+ { terminationReason: { $null: true } },
8479
+ { terminationReason: { $notIn: [...RECORDED_END_REASONS] } }
8480
+ ]
8481
+ });
8482
+ } else if (RECORDED_END_REASONS.includes(reason)) {
8483
+ conditions.push({ terminationReason: reason });
8484
+ }
8485
+ }
8486
+ if (search) {
8487
+ conditions.push({
8488
+ $or: [
8489
+ { user: { email: { $containsi: search } } },
8490
+ { user: { username: { $containsi: search } } },
8491
+ { ipAddress: { $containsi: search } },
8492
+ { browserName: { $containsi: search } },
8493
+ { osName: { $containsi: search } },
8494
+ { deviceType: { $containsi: search } }
8495
+ ]
8496
+ });
8497
+ }
8498
+ return conditions.length ? { $and: conditions } : {};
8499
+ }
8500
+ function encodeExportCursor(row) {
8501
+ const time = row.loginTime ? new Date(row.loginTime).toISOString() : null;
8502
+ return Buffer.from(JSON.stringify([time, Number(row.id)])).toString("base64url");
8503
+ }
8504
+ function decodeExportCursor(cursor) {
8505
+ if (cursor === void 0 || cursor === "") return null;
8506
+ if (!/^[A-Za-z0-9_-]+$/.test(cursor)) return false;
8507
+ try {
8508
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
8509
+ if (!Array.isArray(value) || value.length !== 2) return false;
8510
+ const [time, id] = value;
8511
+ if (!Number.isSafeInteger(id) || id < 1) return false;
8512
+ if (time === null) return { loginTime: null, id };
8513
+ if (typeof time !== "string" || Number.isNaN(Date.parse(time))) return false;
8514
+ return { loginTime: new Date(time), id };
8515
+ } catch {
8516
+ return false;
8517
+ }
8518
+ }
8519
+ function afterExportCursor(cursor) {
8520
+ if (cursor.loginTime === null) return { id: { $lt: cursor.id } };
8521
+ return {
8522
+ $or: [
8523
+ { loginTime: { $lt: cursor.loginTime } },
8524
+ { $and: [{ loginTime: cursor.loginTime }, { id: { $lt: cursor.id } }] }
8525
+ ]
8526
+ };
8527
+ }
8528
+ module.exports = {
8529
+ SESSION_STATUS_FILTERS,
8530
+ RECORDED_END_REASONS,
8531
+ END_REASON_FILTERS,
8532
+ SORT_ORDERS,
8533
+ SORT_KEYS,
8534
+ MAX_PAGE_SIZE,
8535
+ MAX_SEARCH_LENGTH,
8536
+ MAX_LIST_OFFSET,
8537
+ MAX_EXPORT_BATCH,
8538
+ MAX_EXPORT_ROWS,
8539
+ LIST_FIELDS,
8540
+ LIST_USER_FIELDS,
8541
+ listQuerySchema,
8542
+ exportQuerySchema,
8543
+ statsQuerySchema,
8544
+ isPaginatedListQuery,
8545
+ parseQuery,
8546
+ buildSessionWhere,
8547
+ encodeExportCursor,
8548
+ decodeExportCursor,
8549
+ afterExportCursor
8550
+ };
8551
+ }
8552
+ });
8553
+
8554
+ // server/src/utils/session-list.js
8555
+ var require_session_list = __commonJS({
8556
+ "server/src/utils/session-list.js"(exports, module) {
8557
+ "use strict";
8558
+ var { enhanceSessions } = require_enhance_session();
8559
+ var { getNativeSessionManager } = require_native_session_manager();
8560
+ var {
8561
+ LIST_FIELDS,
8562
+ LIST_USER_FIELDS,
8563
+ MAX_EXPORT_BATCH,
8564
+ SORT_ORDERS,
8565
+ buildSessionWhere,
8566
+ afterExportCursor,
8567
+ encodeExportCursor
8568
+ } = require_session_list_query();
8569
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
8570
+ var NATIVE_SESSION_UID = "admin::session";
8571
+ var NATIVE_ORIGIN = "users-permissions";
8572
+ var NATIVE_CHECK_CONCURRENCY = 8;
8573
+ var STATS_CACHE_MS = 5e3;
8574
+ var statsCache = /* @__PURE__ */ new WeakMap();
8575
+ function clearSessionStatsCache() {
8576
+ statsCache = /* @__PURE__ */ new WeakMap();
8577
+ }
8578
+ function cacheFor(strapi2) {
8579
+ let map = statsCache.get(strapi2);
8580
+ if (!map) {
8581
+ map = /* @__PURE__ */ new Map();
8582
+ statsCache.set(strapi2, map);
8583
+ }
8584
+ return map;
8585
+ }
8586
+ function inactivityCutoff(inactivityTimeout, now = Date.now()) {
8587
+ return new Date(now - inactivityTimeout);
8588
+ }
8589
+ function hasNativeSessionTable(strapi2) {
8590
+ return Boolean(strapi2?.contentTypes?.[NATIVE_SESSION_UID]);
8591
+ }
8592
+ async function findActiveNativeIds(strapi2, nativeManager, ids) {
8593
+ const unique = [...new Set(ids.filter((id) => typeof id === "string" && id))];
8594
+ if (unique.length === 0) return /* @__PURE__ */ new Set();
8595
+ if (hasNativeSessionTable(strapi2)) {
8596
+ const rows = await strapi2.db.query(NATIVE_SESSION_UID).findMany({
8597
+ select: ["sessionId"],
8598
+ where: {
8599
+ sessionId: { $in: unique },
8600
+ origin: NATIVE_ORIGIN,
8601
+ status: "active",
8602
+ expiresAt: { $gt: /* @__PURE__ */ new Date() }
8603
+ }
8604
+ });
8605
+ return new Set((Array.isArray(rows) ? rows : []).map((row) => String(row.sessionId)));
8606
+ }
8607
+ const active = /* @__PURE__ */ new Set();
8608
+ let next = 0;
8609
+ const worker = async () => {
8610
+ while (next < unique.length) {
8611
+ const id = unique[next++];
8612
+ if (await nativeManager.isSessionActive(id)) active.add(id);
8613
+ }
8614
+ };
8615
+ await Promise.all(
8616
+ Array.from({ length: Math.min(NATIVE_CHECK_CONCURRENCY, unique.length) }, worker)
8617
+ );
8618
+ return active;
8619
+ }
8620
+ async function reconcileNativeRows(strapi2, rows) {
8621
+ const nativeManager = getNativeSessionManager(strapi2);
8622
+ if (!nativeManager) return rows;
8623
+ const ids = rows.filter((row) => row.isActive && row.nativeSessionId).map((row) => String(row.nativeSessionId));
8624
+ if (ids.length === 0) return rows;
8625
+ const active = await findActiveNativeIds(strapi2, nativeManager, ids);
8626
+ return rows.map(
8627
+ (row) => row.isActive && row.nativeSessionId && !active.has(String(row.nativeSessionId)) ? { ...row, isActive: false } : row
8628
+ );
8629
+ }
8630
+ async function countNativeOnlySessions(strapi2) {
8631
+ if (!getNativeSessionManager(strapi2) || !hasNativeSessionTable(strapi2)) return 0;
8632
+ const knex = strapi2.db.connection;
8633
+ const nativeMeta = strapi2.db.metadata.get(NATIVE_SESSION_UID);
8634
+ const sessionMeta = strapi2.db.metadata.get(SESSION_UID);
8635
+ const column = (meta, attribute) => meta.attributes[attribute]?.columnName || attribute;
8636
+ const nativeTable = nativeMeta.tableName;
8637
+ const sessionTable = sessionMeta.tableName;
8638
+ const nativeIdColumn = column(nativeMeta, "sessionId");
8639
+ const linkedColumn = column(sessionMeta, "nativeSessionId");
8640
+ const result = await knex(nativeTable).where(column(nativeMeta, "origin"), NATIVE_ORIGIN).andWhere(column(nativeMeta, "status"), "active").andWhere(column(nativeMeta, "expiresAt"), ">", /* @__PURE__ */ new Date()).whereNotExists(function linked() {
8641
+ this.select(knex.raw("1")).from(sessionTable).whereRaw("??.?? = ??.??", [sessionTable, linkedColumn, nativeTable, nativeIdColumn]);
8642
+ }).count({ count: "*" }).first();
8643
+ return Number(result?.count ?? 0);
8644
+ }
8645
+ async function countUsersOnline(strapi2, cutoff) {
8646
+ const meta = strapi2.db.metadata.get(SESSION_UID);
8647
+ const userAttribute = meta.attributes.user;
8648
+ const joinTable = userAttribute?.joinTable;
8649
+ const column = (attribute) => meta.attributes[attribute]?.columnName || attribute;
8650
+ const knex = strapi2.db.connection;
8651
+ const table = meta.tableName;
8652
+ if (joinTable?.name && joinTable.joinColumn?.name && joinTable.inverseJoinColumn?.name) {
8653
+ const link = joinTable.name;
8654
+ const lastActive = `${table}.${column("lastActive")}`;
8655
+ const loginTime = `${table}.${column("loginTime")}`;
8656
+ const result = await knex(table).join(link, `${link}.${joinTable.joinColumn.name}`, `${table}.id`).where(`${table}.${column("isActive")}`, true).andWhere((qb) => {
8657
+ qb.where(lastActive, ">", cutoff).orWhere((inner) => {
8658
+ inner.whereNull(lastActive).andWhere(loginTime, ">", cutoff);
8659
+ });
8660
+ }).countDistinct({ count: `${link}.${joinTable.inverseJoinColumn.name}` }).first();
8661
+ return Number(result?.count ?? 0);
8662
+ }
8663
+ const seen = /* @__PURE__ */ new Set();
8664
+ const where = buildSessionWhere({ status: "active" }, { cutoff });
8665
+ for (let offset = 0; ; offset += MAX_EXPORT_BATCH) {
8666
+ const rows = await strapi2.db.query(SESSION_UID).findMany({
8667
+ where,
8668
+ select: ["id"],
8669
+ populate: { user: { select: ["id"] } },
8670
+ orderBy: [{ id: "asc" }],
8671
+ offset,
8672
+ limit: MAX_EXPORT_BATCH
8673
+ });
8674
+ for (const row of rows) if (row.user?.id) seen.add(row.user.id);
8675
+ if (rows.length < MAX_EXPORT_BATCH) break;
8676
+ }
8677
+ return seen.size;
8678
+ }
8679
+ async function listSessionPage(strapi2, query, options) {
8680
+ const cutoff = inactivityCutoff(options.inactivityTimeout);
8681
+ const where = buildSessionWhere(query, { cutoff });
8682
+ const sessions = strapi2.db.query(SESSION_UID);
8683
+ const offset = (query.page - 1) * query.pageSize;
8684
+ const [total, rows] = await Promise.all([
8685
+ sessions.count({ where }),
8686
+ sessions.findMany({
8687
+ where,
8688
+ select: [...LIST_FIELDS],
8689
+ populate: { user: { select: [...LIST_USER_FIELDS] } },
8690
+ orderBy: SORT_ORDERS[query.sort] || SORT_ORDERS["loginTime:desc"],
8691
+ offset,
8692
+ limit: query.pageSize
8693
+ })
8694
+ ]);
8695
+ const reconciled = await reconcileNativeRows(strapi2, Array.isArray(rows) ? rows : []);
8696
+ const enhanced = await enhanceSessions(
8697
+ reconciled,
8698
+ {
8699
+ inactivityTimeout: options.inactivityTimeout,
8700
+ geolocationService: options.geolocationService || null,
8701
+ strapi: strapi2
8702
+ },
8703
+ Math.min(20, query.pageSize)
8704
+ );
8705
+ const count = Number(total) || 0;
8706
+ return {
8707
+ rows: enhanced,
8708
+ pagination: {
8709
+ page: query.page,
8710
+ pageSize: query.pageSize,
8711
+ total: count,
8712
+ pageCount: Math.max(1, Math.ceil(count / query.pageSize))
8713
+ }
8714
+ };
8715
+ }
8716
+ async function getSessionStats(strapi2, { inactivityTimeout }) {
8717
+ const key = String(inactivityTimeout);
8718
+ const cache = cacheFor(strapi2);
8719
+ const cached = cache.get(key);
8720
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
8721
+ const cutoff = inactivityCutoff(inactivityTimeout);
8722
+ const sessions = strapi2.db.query(SESSION_UID);
8723
+ const count = (filters) => sessions.count({ where: buildSessionWhere(filters, { cutoff }) });
8724
+ const [total, open, active, loggedOut, timedOut, usersOnline, nativeOnly] = await Promise.all([
8725
+ count({}),
8726
+ count({ status: "open" }),
8727
+ count({ status: "active" }),
8728
+ count({ status: "ended", reason: "logout" }),
8729
+ count({ status: "ended", reason: "idle" }),
8730
+ countUsersOnline(strapi2, cutoff),
8731
+ countNativeOnlySessions(strapi2)
8732
+ ]);
8733
+ const ended = Math.max(0, Number(total) - Number(open));
8734
+ const value = {
8735
+ total: Number(total),
8736
+ open: Number(open),
8737
+ active: Number(active),
8738
+ idle: Math.max(0, Number(open) - Number(active)),
8739
+ ended,
8740
+ loggedOut: Number(loggedOut),
8741
+ timedOut: Number(timedOut),
8742
+ otherReasons: Math.max(0, ended - Number(loggedOut) - Number(timedOut)),
8743
+ usersOnline: Number(usersOnline),
8744
+ nativeOnly: Number(nativeOnly)
8745
+ };
8746
+ cache.set(key, { value, expiresAt: Date.now() + STATS_CACHE_MS });
8747
+ if (cache.size > 20) cache.delete(cache.keys().next().value);
8748
+ return value;
8749
+ }
8750
+ var ANALYTICS_CACHE_MS = 3e4;
8751
+ var MAX_GROUPS = 200;
8752
+ async function countByColumn(strapi2, attribute) {
8753
+ const meta = strapi2.db.metadata.get(SESSION_UID);
8754
+ const column = meta.attributes[attribute]?.columnName || attribute;
8755
+ const rows = await strapi2.db.connection(meta.tableName).select({ value: column }).count({ count: "*" }).groupBy(column).orderBy("count", "desc").limit(MAX_GROUPS);
8756
+ return rows.map((row) => ({ value: row.value ?? null, count: Number(row.count) || 0 }));
8757
+ }
8758
+ async function averageSessionMinutes(strapi2, now) {
8759
+ const meta = strapi2.db.metadata.get(SESSION_UID);
8760
+ const col = (attribute) => meta.attributes[attribute]?.columnName || attribute;
8761
+ const knex = strapi2.db.connection;
8762
+ const client = strapi2.db.dialect?.client || "";
8763
+ const end = `CASE WHEN ?? THEN COALESCE(??, ?) ELSE COALESCE(??, ??) END`;
8764
+ const endBindings = [
8765
+ col("isActive"),
8766
+ col("lastActive"),
8767
+ now,
8768
+ col("logoutTime"),
8769
+ col("lastActive")
8770
+ ];
8771
+ if (client === "postgres") {
8772
+ const row = await knex(meta.tableName).select(
8773
+ knex.raw(`AVG(GREATEST(0, FLOOR(EXTRACT(EPOCH FROM ((${end}) - ??)) / 60))) AS avg`, [
8774
+ ...endBindings,
8775
+ col("loginTime")
8776
+ ])
8777
+ ).first();
8778
+ return Math.floor(Number(row?.avg) || 0);
8779
+ }
8780
+ if (client === "mysql" || client === "mysql2") {
8781
+ const row = await knex(meta.tableName).select(
8782
+ knex.raw(`AVG(GREATEST(0, FLOOR(TIMESTAMPDIFF(SECOND, ??, (${end})) / 60))) AS avg`, [
8783
+ col("loginTime"),
8784
+ ...endBindings
8785
+ ])
8786
+ ).first();
8787
+ return Math.floor(Number(row?.avg) || 0);
8788
+ }
8789
+ let sum = 0;
8790
+ let count = 0;
8791
+ let lastId = 0;
8792
+ const nowMs = now.getTime();
8793
+ for (; ; ) {
8794
+ const rows = await strapi2.db.query(SESSION_UID).findMany({
8795
+ select: ["id", "loginTime", "lastActive", "logoutTime", "isActive"],
8796
+ where: { id: { $gt: lastId } },
8797
+ orderBy: [{ id: "asc" }],
8798
+ limit: 5e3
8799
+ });
8800
+ for (const row of rows) {
8801
+ const start = Date.parse(row.loginTime);
8802
+ if (!Number.isFinite(start)) continue;
8803
+ const lastActive = row.lastActive ? Date.parse(row.lastActive) : Number.NaN;
8804
+ const logout = row.logoutTime ? Date.parse(row.logoutTime) : Number.NaN;
8805
+ let stop;
8806
+ if (row.isActive) stop = Number.isFinite(lastActive) ? lastActive : nowMs;
8807
+ else stop = Number.isFinite(logout) ? logout : lastActive;
8808
+ if (!Number.isFinite(stop)) continue;
8809
+ sum += Math.max(0, Math.floor((stop - start) / 6e4));
8810
+ count += 1;
8811
+ }
8812
+ if (rows.length < 5e3) break;
8813
+ lastId = rows[rows.length - 1].id;
8814
+ }
8815
+ return count > 0 ? Math.floor(sum / count) : 0;
8816
+ }
8817
+ async function countUsersWithSessions(strapi2) {
8818
+ const meta = strapi2.db.metadata.get(SESSION_UID);
8819
+ const joinTable = meta.attributes.user?.joinTable;
8820
+ if (!joinTable?.name || !joinTable.inverseJoinColumn?.name) return 0;
8821
+ const row = await strapi2.db.connection(joinTable.name).countDistinct({ count: joinTable.inverseJoinColumn.name }).first();
8822
+ return Number(row?.count ?? 0);
8823
+ }
8824
+ async function getSessionAnalytics(strapi2, { inactivityTimeout }) {
8825
+ const key = `analytics:${inactivityTimeout}`;
8826
+ const cache = cacheFor(strapi2);
8827
+ const cached = cache.get(key);
8828
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
8829
+ const now = /* @__PURE__ */ new Date();
8830
+ const sessions = strapi2.db.query(SESSION_UID);
8831
+ const since = (ms) => sessions.count({ where: { loginTime: { $gt: new Date(now - ms) } } });
8832
+ const [stats, signIns24h, signIns7d, devices, browsers, uniqueUsers, avgSessionDuration] = await Promise.all([
8833
+ getSessionStats(strapi2, { inactivityTimeout }),
8834
+ since(24 * 60 * 60 * 1e3),
8835
+ since(7 * 24 * 60 * 60 * 1e3),
8836
+ countByColumn(strapi2, "deviceType"),
8837
+ countByColumn(strapi2, "browserName"),
8838
+ countUsersWithSessions(strapi2),
8839
+ averageSessionMinutes(strapi2, now)
8840
+ ]);
8841
+ const value = {
8842
+ totalSessions: stats.total,
8843
+ activeSessions: stats.active,
8844
+ idleSessions: stats.idle,
8845
+ endedSessions: stats.ended,
8846
+ signInsLast24Hours: Number(signIns24h),
8847
+ signInsLast7Days: Number(signIns7d),
8848
+ devices,
8849
+ browsers,
8850
+ uniqueUsers,
8851
+ avgSessionDuration
8852
+ };
8853
+ cache.set(key, { value, expiresAt: Date.now() + ANALYTICS_CACHE_MS });
8854
+ return value;
8855
+ }
8856
+ async function exportSessionBatch(strapi2, query, cursor, { inactivityTimeout }) {
8857
+ const cutoff = inactivityCutoff(inactivityTimeout);
8858
+ const base = buildSessionWhere(query, { cutoff });
8859
+ const where = cursor ? { $and: [...base.$and ? base.$and : [], afterExportCursor(cursor)] } : base;
8860
+ const rows = await strapi2.db.query(SESSION_UID).findMany({
8861
+ where,
8862
+ select: [...LIST_FIELDS],
8863
+ populate: { user: { select: [...LIST_USER_FIELDS] } },
8864
+ orderBy: SORT_ORDERS["loginTime:desc"],
8865
+ limit: query.limit
8866
+ });
8867
+ const list = Array.isArray(rows) ? rows : [];
8868
+ const reconciled = await reconcileNativeRows(strapi2, list);
8869
+ const enhanced = await enhanceSessions(
8870
+ reconciled,
8871
+ { inactivityTimeout, geolocationService: null, strapi: strapi2 },
8872
+ 0
8873
+ );
8874
+ const last = list[list.length - 1];
8875
+ return {
8876
+ rows: enhanced,
8877
+ nextCursor: list.length === query.limit && last ? encodeExportCursor(last) : null
8878
+ };
8879
+ }
8880
+ module.exports = {
8881
+ STATS_CACHE_MS,
8882
+ ANALYTICS_CACHE_MS,
8883
+ listSessionPage,
8884
+ getSessionStats,
8885
+ getSessionAnalytics,
8886
+ exportSessionBatch,
8887
+ countUsersOnline,
8888
+ countNativeOnlySessions,
8889
+ reconcileNativeRows,
8890
+ clearSessionStatsCache,
8891
+ inactivityCutoff
8892
+ };
8893
+ }
8894
+ });
8895
+
8349
8896
  // server/src/controllers/session.js
8350
8897
  var require_session = __commonJS({
8351
8898
  "server/src/controllers/session.js"(exports, module) {
@@ -8363,12 +8910,23 @@ var require_session = __commonJS({
8363
8910
  var { runWithCallerRevocation } = require_block_revocation_scope();
8364
8911
  var { sendServerError } = require_http_errors();
8365
8912
  var { getCoordinator } = require_coordination();
8913
+ var { clearSessionStatsCache } = require_session_list();
8914
+ var {
8915
+ decodeExportCursor,
8916
+ exportQuerySchema,
8917
+ isPaginatedListQuery,
8918
+ listQuerySchema,
8919
+ parseQuery,
8920
+ statsQuerySchema
8921
+ } = require_session_list_query();
8366
8922
  var SESSION_UID = "plugin::magic-sessionmanager.session";
8367
8923
  var USER_UID = "plugin::users-permissions.user";
8368
8924
  var OWN_SESSIONS_LIMIT = 200;
8369
8925
  var NATIVE_SESSION_KEY_PREFIX = "native_";
8370
8926
  var JWT_MANAGEMENT_CONFIG = "plugin::users-permissions.jwtManagement";
8371
8927
  var LEGACY_JWT_MANAGEMENT = "legacy-support";
8928
+ var USER_STATS_CACHE_MS = 5e3;
8929
+ var userStatsCache = { owner: null, value: null, expiresAt: 0 };
8372
8930
  function createDisabledGeolocationResult(ipAddress) {
8373
8931
  return {
8374
8932
  ip: ipAddress,
@@ -8443,6 +9001,55 @@ var require_session = __commonJS({
8443
9001
  function getTruncationMeta(sessions) {
8444
9002
  return sessions?.truncated === true ? { truncated: true } : {};
8445
9003
  }
9004
+ async function listSessionsAdmin(ctx, { activeOnly }) {
9005
+ if (isPaginatedListQuery(ctx.query)) {
9006
+ const parsed = parseQuery(listQuerySchema, ctx.query);
9007
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
9008
+ const query = activeOnly ? { ...parsed.value, status: "active", reason: "all" } : parsed.value;
9009
+ try {
9010
+ const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9011
+ const page = await sessionService.listSessionPage(query);
9012
+ ctx.body = {
9013
+ data: toPublicSessions(page.rows, { admin: true }),
9014
+ meta: { pagination: page.pagination }
9015
+ };
9016
+ return void 0;
9017
+ } catch (err) {
9018
+ strapi.log.error("[magic-sessionmanager] listSessionPage failed:", err?.name || "Error");
9019
+ return ctx.internalServerError("Error fetching sessions");
9020
+ }
9021
+ }
9022
+ try {
9023
+ const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9024
+ if (activeOnly) {
9025
+ const sessions2 = await sessionService.getActiveSessions();
9026
+ ctx.body = {
9027
+ data: toPublicSessions(sessions2, { admin: true }),
9028
+ meta: { count: sessions2.length, ...getTruncationMeta(sessions2) }
9029
+ };
9030
+ return void 0;
9031
+ }
9032
+ const sessions = await sessionService.getAllSessions();
9033
+ ctx.body = {
9034
+ data: toPublicSessions(sessions, { admin: true }),
9035
+ meta: {
9036
+ count: sessions.length,
9037
+ active: sessions.filter((s) => s.isTrulyActive).length,
9038
+ inactive: sessions.filter((s) => !s.isTrulyActive).length,
9039
+ ...getTruncationMeta(sessions)
9040
+ }
9041
+ };
9042
+ return void 0;
9043
+ } catch (err) {
9044
+ strapi.log.error(
9045
+ `[magic-sessionmanager] ${activeOnly ? "getActiveSessions" : "getAllSessionsAdmin"} failed:`,
9046
+ err?.name || "Error"
9047
+ );
9048
+ return ctx.internalServerError(
9049
+ activeOnly ? "Error fetching active sessions" : "Error fetching sessions"
9050
+ );
9051
+ }
9052
+ }
8446
9053
  async function respondIfSessionCreationPending(ctx) {
8447
9054
  const settings = await getPluginSettings(strapi);
8448
9055
  const gracePeriodMs = getSessionCreationGraceMs(settings);
@@ -8473,13 +9080,19 @@ var require_session = __commonJS({
8473
9080
  */
8474
9081
  async getUserStatsAdmin(ctx) {
8475
9082
  try {
8476
- const [totalUsers, blockedUsers] = await Promise.all([
8477
- strapi.db.query(USER_UID).count(),
8478
- strapi.db.query(USER_UID).count({ where: { blocked: true } })
8479
- ]);
9083
+ if (userStatsCache.owner !== strapi || !userStatsCache.value || userStatsCache.expiresAt <= Date.now()) {
9084
+ userStatsCache.owner = null;
9085
+ const [totalUsers, blockedUsers] = await Promise.all([
9086
+ strapi.db.query(USER_UID).count(),
9087
+ strapi.db.query(USER_UID).count({ where: { blocked: true } })
9088
+ ]);
9089
+ userStatsCache.owner = strapi;
9090
+ userStatsCache.value = { totalUsers, blockedUsers };
9091
+ userStatsCache.expiresAt = Date.now() + USER_STATS_CACHE_MS;
9092
+ }
8480
9093
  return ctx.send({
8481
9094
  success: true,
8482
- data: { totalUsers, blockedUsers }
9095
+ data: { ...userStatsCache.value }
8483
9096
  });
8484
9097
  } catch (error) {
8485
9098
  strapi.log.error("[magic-sessionmanager] getUserStatsAdmin failed:", error?.name || "Error");
@@ -8487,42 +9100,102 @@ var require_session = __commonJS({
8487
9100
  }
8488
9101
  },
8489
9102
  /**
8490
- * Lists all sessions (active + inactive) for admin overviews.
9103
+ * Lists sessions for admin overviews.
9104
+ *
9105
+ * With `page` or `pageSize` the list is paginated in SQL and filtered by
9106
+ * `status`, `reason`, `search` and `sort` (whitelisted values only), with
9107
+ * exact totals. Without them the 4.x response (latest 1000 rows) is kept
9108
+ * for existing callers.
9109
+ *
8491
9110
  * @route GET /magic-sessionmanager/sessions
9111
+ * @param {object} ctx Koa context
9112
+ * @returns {Promise<void>}
8492
9113
  */
8493
9114
  async getAllSessionsAdmin(ctx) {
9115
+ return listSessionsAdmin(ctx, { activeOnly: false });
9116
+ },
9117
+ /**
9118
+ * Lists currently-active sessions only (paginated with `page`/`pageSize`,
9119
+ * see getAllSessionsAdmin).
9120
+ *
9121
+ * @route GET /magic-sessionmanager/sessions/active
9122
+ * @param {object} ctx Koa context
9123
+ * @returns {Promise<void>}
9124
+ */
9125
+ async getActiveSessions(ctx) {
9126
+ return listSessionsAdmin(ctx, { activeOnly: true });
9127
+ },
9128
+ /**
9129
+ * Count-only session statistics for the dashboard cards and the homepage
9130
+ * widget. No rows, no personal data.
9131
+ *
9132
+ * @route GET /magic-sessionmanager/sessions/stats
9133
+ * @param {object} ctx Koa context
9134
+ * @returns {Promise<void>}
9135
+ */
9136
+ async getSessionStatsAdmin(ctx) {
9137
+ const parsed = parseQuery(statsQuerySchema, ctx.query);
9138
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
8494
9139
  try {
8495
9140
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8496
- const sessions = await sessionService.getAllSessions();
8497
- ctx.body = {
8498
- data: toPublicSessions(sessions, { admin: true }),
8499
- meta: {
8500
- count: sessions.length,
8501
- active: sessions.filter((s) => s.isTrulyActive).length,
8502
- inactive: sessions.filter((s) => !s.isTrulyActive).length,
8503
- ...getTruncationMeta(sessions)
8504
- }
8505
- };
9141
+ const stats = await sessionService.getSessionStats();
9142
+ return ctx.send({ data: stats });
8506
9143
  } catch (err) {
8507
- strapi.log.error("[magic-sessionmanager] getAllSessionsAdmin failed:", err?.name || "Error");
8508
- return ctx.internalServerError("Error fetching sessions");
9144
+ strapi.log.error("[magic-sessionmanager] getSessionStatsAdmin failed:", err?.name || "Error");
9145
+ return ctx.internalServerError("Unable to load session statistics");
8509
9146
  }
8510
9147
  },
8511
9148
  /**
8512
- * Lists currently-active sessions only.
8513
- * @route GET /magic-sessionmanager/sessions/active
9149
+ * Aggregates for the Analytics page over every session: counts, grouped
9150
+ * counts per device type and browser, distinct users, average length. No
9151
+ * rows and no personal data.
9152
+ *
9153
+ * @route GET /magic-sessionmanager/sessions/analytics
9154
+ * @param {object} ctx Koa context
9155
+ * @returns {Promise<void>}
8514
9156
  */
8515
- async getActiveSessions(ctx) {
9157
+ async getSessionAnalyticsAdmin(ctx) {
9158
+ const parsed = parseQuery(statsQuerySchema, ctx.query);
9159
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
8516
9160
  try {
8517
9161
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8518
- const sessions = await sessionService.getActiveSessions();
8519
- ctx.body = {
8520
- data: toPublicSessions(sessions, { admin: true }),
8521
- meta: { count: sessions.length, ...getTruncationMeta(sessions) }
8522
- };
9162
+ return ctx.send({ data: await sessionService.getSessionAnalytics() });
8523
9163
  } catch (err) {
8524
- strapi.log.error("[magic-sessionmanager] getActiveSessions failed:", err?.name || "Error");
8525
- return ctx.internalServerError("Error fetching active sessions");
9164
+ strapi.log.error(
9165
+ "[magic-sessionmanager] getSessionAnalyticsAdmin failed:",
9166
+ err?.name || "Error"
9167
+ );
9168
+ return ctx.internalServerError("Unable to load session analytics");
9169
+ }
9170
+ },
9171
+ /**
9172
+ * One batch of the session export (newest first, keyset cursor). The admin
9173
+ * client follows `meta.nextCursor` until it is null or its row limit is
9174
+ * reached.
9175
+ *
9176
+ * @route GET /magic-sessionmanager/sessions/export
9177
+ * @param {object} ctx Koa context
9178
+ * @returns {Promise<void>}
9179
+ */
9180
+ async exportSessionsAdmin(ctx) {
9181
+ const parsed = parseQuery(exportQuerySchema, ctx.query);
9182
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
9183
+ const cursor = decodeExportCursor(parsed.value.cursor);
9184
+ if (cursor === false) {
9185
+ return ctx.badRequest("Invalid query", {
9186
+ errors: [{ path: "cursor", message: "Invalid cursor" }]
9187
+ });
9188
+ }
9189
+ try {
9190
+ const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9191
+ const batch = await sessionService.exportSessionBatch(parsed.value, cursor);
9192
+ return ctx.send({
9193
+ data: toPublicSessions(batch.rows, { admin: true }),
9194
+ meta: { count: batch.rows.length, nextCursor: batch.nextCursor }
9195
+ });
9196
+ } catch (err) {
9197
+ strapi.log.error("[magic-sessionmanager] exportSessionsAdmin failed:", err?.name || "Error");
9198
+ return ctx.internalServerError("Unable to export sessions");
8526
9199
  }
8527
9200
  },
8528
9201
  /**
@@ -9045,6 +9718,7 @@ var require_session = __commonJS({
9045
9718
  * A missing target returns 404; existing native-only rows remain supported.
9046
9719
  */
9047
9720
  async terminateSingleSession(ctx) {
9721
+ clearSessionStatsCache();
9048
9722
  try {
9049
9723
  const { sessionId } = ctx.params;
9050
9724
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
@@ -9073,6 +9747,7 @@ var require_session = __commonJS({
9073
9747
  * Unknown numeric IDs and document IDs return 404 before revocation.
9074
9748
  */
9075
9749
  async terminateAllUserSessions(ctx) {
9750
+ clearSessionStatsCache();
9076
9751
  try {
9077
9752
  const { userId } = ctx.params;
9078
9753
  const numericId = /^\d+$/.test(userId) ? Number(userId) : null;
@@ -9155,6 +9830,7 @@ var require_session = __commonJS({
9155
9830
  * any unexpired JWT expires
9156
9831
  */
9157
9832
  async deleteSession(ctx) {
9833
+ clearSessionStatsCache();
9158
9834
  try {
9159
9835
  const { sessionId } = ctx.params;
9160
9836
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
@@ -9180,6 +9856,7 @@ var require_session = __commonJS({
9180
9856
  * could not be removed
9181
9857
  */
9182
9858
  async cleanInactiveSessions(ctx) {
9859
+ clearSessionStatsCache();
9183
9860
  try {
9184
9861
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9185
9862
  const deletedCount = await sessionService.deleteInactiveSessions();
@@ -9226,6 +9903,8 @@ var require_session = __commonJS({
9226
9903
  * can leave the user blocked with partially active sessions.
9227
9904
  */
9228
9905
  async toggleUserBlock(ctx) {
9906
+ clearSessionStatsCache();
9907
+ userStatsCache.expiresAt = 0;
9229
9908
  try {
9230
9909
  const { userId } = ctx.params;
9231
9910
  const body = ctx.request?.body;
@@ -9285,182 +9964,6 @@ var require_session = __commonJS({
9285
9964
  }
9286
9965
  });
9287
9966
 
9288
- // server/src/controllers/license.js
9289
- var require_license = __commonJS({
9290
- "server/src/controllers/license.js"(exports, module) {
9291
- "use strict";
9292
- var { sendServerError } = require_http_errors();
9293
- var PROVIDER_UNREACHABLE_MESSAGE = "License server unreachable. The plugin keeps working without a key.";
9294
- var EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9295
- module.exports = ({ strapi: strapi2 }) => ({
9296
- async getStatus(ctx) {
9297
- try {
9298
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9299
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
9300
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
9301
- if (!licenseKey) {
9302
- return ctx.send({
9303
- success: true,
9304
- valid: true,
9305
- demo: false,
9306
- hasKey: false,
9307
- data: {
9308
- features: {
9309
- premium: true,
9310
- advanced: true,
9311
- enterprise: true,
9312
- custom: true
9313
- }
9314
- },
9315
- message: "Plugin is active. License key activation is optional."
9316
- });
9317
- }
9318
- const license = await licenseGuard.getLicenseByKey(licenseKey);
9319
- return ctx.send({
9320
- success: true,
9321
- valid: true,
9322
- demo: false,
9323
- hasKey: true,
9324
- data: {
9325
- licenseKey,
9326
- email: license?.email || null,
9327
- firstName: license?.firstName || null,
9328
- lastName: license?.lastName || null,
9329
- isActive: license?.isActive ?? true,
9330
- isExpired: license?.isExpired ?? false,
9331
- isOnline: license?.isOnline ?? false,
9332
- expiresAt: license?.expiresAt || null,
9333
- lastPingAt: license?.lastPingAt || null,
9334
- deviceName: license?.deviceName || null,
9335
- deviceId: license?.deviceId || null,
9336
- ipAddress: license?.ipAddress || null,
9337
- features: {
9338
- premium: true,
9339
- advanced: true,
9340
- enterprise: true,
9341
- custom: true
9342
- },
9343
- maxDevices: license?.maxDevices || 1,
9344
- currentDevices: license?.currentDevices || 0
9345
- }
9346
- });
9347
- } catch (error) {
9348
- strapi2.log.error(
9349
- "[magic-sessionmanager] Error getting license status:",
9350
- error?.name || "Error"
9351
- );
9352
- return sendServerError(ctx, 500, "Error getting license status");
9353
- }
9354
- },
9355
- async autoCreate(ctx) {
9356
- try {
9357
- const adminUser = ctx.state.user;
9358
- if (!adminUser) {
9359
- return ctx.unauthorized("No admin user logged in");
9360
- }
9361
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9362
- const license = await licenseGuard.createLicense({
9363
- email: adminUser.email,
9364
- firstName: adminUser.firstname || "Admin",
9365
- lastName: adminUser.lastname || "User"
9366
- });
9367
- if (!license) {
9368
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
9369
- }
9370
- await licenseGuard.storeLicenseKey(license.licenseKey);
9371
- return ctx.send({
9372
- success: true,
9373
- message: "License automatically created and stored",
9374
- data: license
9375
- });
9376
- } catch (error) {
9377
- strapi2.log.error(
9378
- "[magic-sessionmanager] Error auto-creating license:",
9379
- error?.name || "Error"
9380
- );
9381
- return sendServerError(ctx, 500, "Error creating license");
9382
- }
9383
- },
9384
- async createAndActivate(ctx) {
9385
- try {
9386
- const { email, firstName, lastName } = ctx.request.body || {};
9387
- if (![email, firstName, lastName].every((value) => typeof value === "string" && value.trim())) {
9388
- return ctx.badRequest("Email, firstName, and lastName are required");
9389
- }
9390
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9391
- const license = await licenseGuard.createLicense({ email, firstName, lastName });
9392
- if (!license) {
9393
- return sendServerError(ctx, 503, PROVIDER_UNREACHABLE_MESSAGE);
9394
- }
9395
- await licenseGuard.storeLicenseKey(license.licenseKey);
9396
- return ctx.send({
9397
- success: true,
9398
- message: "License created and stored successfully",
9399
- data: license
9400
- });
9401
- } catch (error) {
9402
- strapi2.log.error("[magic-sessionmanager] Error creating license:", error?.name || "Error");
9403
- return sendServerError(ctx, 500, "Error creating license");
9404
- }
9405
- },
9406
- async ping(ctx) {
9407
- try {
9408
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
9409
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
9410
- if (!licenseKey) {
9411
- return ctx.badRequest("No license key found");
9412
- }
9413
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9414
- const verification = await licenseGuard.verifyLicense(licenseKey);
9415
- return ctx.send({
9416
- success: true,
9417
- message: verification.valid ? "License refreshed successfully" : "License key could not be verified, but the plugin keeps working.",
9418
- data: verification.data
9419
- });
9420
- } catch (error) {
9421
- strapi2.log.error("[magic-sessionmanager] Error refreshing license:", error?.name || "Error");
9422
- return sendServerError(ctx, 500, "Error refreshing license");
9423
- }
9424
- },
9425
- async storeKey(ctx) {
9426
- try {
9427
- const { licenseKey, email } = ctx.request.body || {};
9428
- if (typeof licenseKey !== "string" || !licenseKey.trim()) {
9429
- return ctx.badRequest("License key is required");
9430
- }
9431
- if (email !== void 0 && email !== null && email !== "") {
9432
- if (typeof email !== "string" || !EMAIL_PATTERN.test(email.trim())) {
9433
- return ctx.badRequest("Email must be a valid email address");
9434
- }
9435
- }
9436
- const trimmedKey = licenseKey.trim();
9437
- const trimmedEmail = typeof email === "string" && email.trim() ? email.trim().toLowerCase() : null;
9438
- const licenseGuard = strapi2.plugin("magic-sessionmanager").service("license-guard");
9439
- const verification = await licenseGuard.verifyLicense(trimmedKey);
9440
- if (!verification.valid && !verification.networkError) {
9441
- strapi2.log.warn("[magic-sessionmanager] Rejected an invalid license key");
9442
- return ctx.badRequest("Invalid or expired license key");
9443
- }
9444
- const license = verification.valid ? await licenseGuard.getLicenseByKey(trimmedKey) : null;
9445
- if (license?.email && trimmedEmail && license.email.toLowerCase() !== trimmedEmail) {
9446
- strapi2.log.warn("[magic-sessionmanager] Rejected a license holder email mismatch");
9447
- return ctx.badRequest("Email address does not match this license key");
9448
- }
9449
- await licenseGuard.storeLicenseKey(trimmedKey);
9450
- return ctx.send({
9451
- success: true,
9452
- message: verification.networkError ? "License key stored. The license server was unreachable, but the plugin keeps working." : "License key stored successfully",
9453
- data: verification.data || { licenseKey: trimmedKey, email: trimmedEmail }
9454
- });
9455
- } catch (error) {
9456
- strapi2.log.error("[magic-sessionmanager] Error storing license key:", error?.name || "Error");
9457
- return sendServerError(ctx, 500, "Error validating license key");
9458
- }
9459
- }
9460
- });
9461
- }
9462
- });
9463
-
9464
9967
  // scripts/geoip-updater.cjs
9465
9968
  var require_geoip_updater = __commonJS({
9466
9969
  "scripts/geoip-updater.cjs"(exports, module) {
@@ -10518,12 +11021,10 @@ var require_controllers = __commonJS({
10518
11021
  "server/src/controllers/index.js"(exports, module) {
10519
11022
  "use strict";
10520
11023
  var session = require_session();
10521
- var license = require_license();
10522
11024
  var settings = require_settings();
10523
11025
  var geoip = require_geoip();
10524
11026
  module.exports = {
10525
11027
  session,
10526
- license,
10527
11028
  settings,
10528
11029
  geoip
10529
11030
  };
@@ -10545,6 +11046,12 @@ var require_session2 = __commonJS({
10545
11046
  persistAccessTokenRevocation
10546
11047
  } = require_session_revocation();
10547
11048
  var { getNativeSessionManager } = require_native_session_manager();
11049
+ var {
11050
+ exportSessionBatch,
11051
+ getSessionAnalytics: getSessionAnalyticsFromDb,
11052
+ getSessionStats: getSessionStatsFromDb,
11053
+ listSessionPage
11054
+ } = require_session_list();
10548
11055
  var {
10549
11056
  NATIVE_SESSION_PREFIX,
10550
11057
  mapNativeSessionToView,
@@ -11240,8 +11747,51 @@ var require_session2 = __commonJS({
11240
11747
  throw err;
11241
11748
  }
11242
11749
  },
11750
+ /**
11751
+ * One page of sessions with exact totals for the admin dashboard. Only
11752
+ * the rows on the page are enriched; filters and sort run in SQL.
11753
+ *
11754
+ * @param {{page: number, pageSize: number, status: string, reason: string, search: string, sort: string}} query Validated list query
11755
+ * @returns {Promise<{rows: object[], pagination: object}>}
11756
+ */
11757
+ async listSessionPage(query) {
11758
+ return listSessionPage(strapi2, query, await getEnhanceOpts());
11759
+ },
11760
+ /**
11761
+ * Count-only session statistics (cached a few seconds per process).
11762
+ *
11763
+ * @returns {Promise<object>}
11764
+ */
11765
+ async getSessionStats() {
11766
+ const { inactivityTimeout } = await getEnhanceOpts();
11767
+ return getSessionStatsFromDb(strapi2, { inactivityTimeout });
11768
+ },
11769
+ /**
11770
+ * Aggregates for the Analytics page over every session (cached 30 s
11771
+ * per process).
11772
+ *
11773
+ * @returns {Promise<object>}
11774
+ */
11775
+ async getSessionAnalytics() {
11776
+ const { inactivityTimeout } = await getEnhanceOpts();
11777
+ return getSessionAnalyticsFromDb(strapi2, { inactivityTimeout });
11778
+ },
11779
+ /**
11780
+ * One export batch (keyset cursor, newest first).
11781
+ *
11782
+ * @param {{limit: number, status: string, reason: string, search: string}} query Validated export query
11783
+ * @param {{loginTime: Date|null, id: number}|null} cursor Decoded cursor
11784
+ * @returns {Promise<{rows: object[], nextCursor: string|null}>}
11785
+ */
11786
+ async exportSessionBatch(query, cursor) {
11787
+ const { inactivityTimeout } = await getEnhanceOpts();
11788
+ return exportSessionBatch(strapi2, query, cursor, { inactivityTimeout });
11789
+ },
11243
11790
  /**
11244
11791
  * Get ALL sessions (active + inactive) with enhanced display fields.
11792
+ * Kept for callers of `GET /sessions` without paging parameters; capped
11793
+ * at the latest 1000 rows. The admin dashboard uses `listSessionPage`.
11794
+ *
11245
11795
  * @returns {Promise<Array>}
11246
11796
  */
11247
11797
  async getAllSessions() {
@@ -11734,367 +12284,6 @@ var require_session2 = __commonJS({
11734
12284
  }
11735
12285
  });
11736
12286
 
11737
- // package.json
11738
- var require_package = __commonJS({
11739
- "package.json"(exports, module) {
11740
- module.exports = {
11741
- version: "4.10.0",
11742
- keywords: [
11743
- "strapi",
11744
- "plugin",
11745
- "strapi-plugin",
11746
- "strapi-v5",
11747
- "sessions",
11748
- "user-tracking",
11749
- "login-logout",
11750
- "activity-monitoring"
11751
- ],
11752
- type: "commonjs",
11753
- bin: {
11754
- "strapi-magic-sessionmanager-geoip": "./scripts/update-geoip-db.mjs"
11755
- },
11756
- exports: {
11757
- "./package.json": "./package.json",
11758
- "./strapi-admin": {
11759
- source: "./admin/src/index.js",
11760
- import: "./dist/admin/index.mjs",
11761
- require: "./dist/admin/index.js",
11762
- default: "./dist/admin/index.js"
11763
- },
11764
- "./strapi-server": {
11765
- source: "./server/src/index.js",
11766
- import: "./dist/server/index.mjs",
11767
- require: "./dist/server/index.js",
11768
- default: "./dist/server/index.js"
11769
- }
11770
- },
11771
- files: [
11772
- "dist",
11773
- "strapi-admin.js",
11774
- "strapi-server.js",
11775
- "scripts/geoip-updater.cjs",
11776
- "scripts/update-geoip-db.mjs",
11777
- "README.md",
11778
- "LICENSE",
11779
- "CHANGELOG.md",
11780
- "pics"
11781
- ],
11782
- engines: {
11783
- node: "^22.22.2 || >=24.15.0",
11784
- npm: ">=6.0.0"
11785
- },
11786
- scripts: {
11787
- clean: `node -e "require('fs').rmSync('dist', { recursive: true, force: true })"`,
11788
- test: "node --test tests/*.test.js tests/*.test.mjs",
11789
- "test:concurrency": "node scripts/concurrency/run.mjs",
11790
- "test:ts:front": "tsc --noEmit --allowJs --jsx react-jsx --moduleResolution bundler --module esnext -p admin/jsconfig.json",
11791
- "test:ts:back": "tsc --noEmit --allowJs --moduleResolution node --module commonjs -p server/jsconfig.json",
11792
- lint: "eslint .",
11793
- "lint:fix": "eslint . --fix",
11794
- format: "prettier --write .",
11795
- "format:check": "prettier --check .",
11796
- build: "npm run clean && strapi-plugin build && node scripts/build-server-bundle.mjs",
11797
- watch: "strapi-plugin watch",
11798
- "watch:link": "strapi-plugin watch:link",
11799
- "geoip:update": "node scripts/update-geoip-db.mjs",
11800
- verify: "strapi-plugin verify",
11801
- "verify:runtime": "node scripts/verify-server-bundle.mjs",
11802
- prepublishOnly: "npm test && npm run build && npm run verify && npm run verify:runtime"
11803
- },
11804
- dependencies: {
11805
- "@maxmind/geoip2-node": "^7.1.0",
11806
- "sanitize-html": "^2.18.0"
11807
- },
11808
- devDependencies: {
11809
- "@eslint/js": "^10.0.1",
11810
- "@semantic-release/changelog": "^7.0.0",
11811
- "@semantic-release/commit-analyzer": "^13.0.1",
11812
- "@semantic-release/git": "^11.0.1",
11813
- "@semantic-release/github": "^12.0.10",
11814
- "@semantic-release/npm": "^13.2.0",
11815
- "@semantic-release/release-notes-generator": "^14.1.1",
11816
- "@strapi/design-system": "^2.2.4",
11817
- "@strapi/icons": "^2.2.4",
11818
- "@strapi/sdk-plugin": "^6.1.1",
11819
- "@strapi/strapi": "5.61.0",
11820
- "better-sqlite3": "^13.0.3",
11821
- esbuild: "^0.28.2",
11822
- eslint: "^10.14.0",
11823
- "eslint-config-prettier": "^10.1.8",
11824
- "eslint-plugin-react-hooks": "^7.1.1",
11825
- globals: "^17.14.0",
11826
- pg: "^8.23.1",
11827
- prettier: "^3.9.10",
11828
- react: "^18.3.1",
11829
- "react-dom": "^18.3.1",
11830
- "react-intl": "^6.8.9",
11831
- "react-router-dom": "^6.30.6",
11832
- "semantic-release": "^25.0.9",
11833
- "styled-components": "^6.6.0"
11834
- },
11835
- peerDependencies: {
11836
- "@strapi/design-system": "^2.0.0",
11837
- "@strapi/icons": "^2.0.0",
11838
- "@strapi/strapi": "^5.0.0",
11839
- "@strapi/utils": "^5.0.0",
11840
- react: "^18.3.1",
11841
- "react-dom": "^18.3.1",
11842
- "react-intl": "^6.0.0",
11843
- "react-router-dom": "^6.0.0",
11844
- "styled-components": "^6.0.0"
11845
- },
11846
- publishConfig: {
11847
- access: "public"
11848
- },
11849
- strapi: {
11850
- kind: "plugin",
11851
- name: "magic-sessionmanager",
11852
- displayName: "Magic Sessionmanager",
11853
- description: "Advanced session management for Strapi v5 - Track user login/logout, session history, and online status"
11854
- },
11855
- name: "strapi-plugin-magic-sessionmanager",
11856
- description: "Advanced Session Management for Strapi v5 - Track user sessions with IP geolocation, security scoring, and real-time monitoring",
11857
- license: "MIT",
11858
- author: "Schero D.",
11859
- repository: {
11860
- type: "git",
11861
- url: "https://github.com/Schero94/Magic-Sessionmanager.git"
11862
- },
11863
- bugs: {
11864
- url: "https://github.com/Schero94/Magic-Sessionmanager/issues"
11865
- },
11866
- homepage: "https://github.com/Schero94/Magic-Sessionmanager#readme",
11867
- private: false
11868
- };
11869
- }
11870
- });
11871
-
11872
- // server/src/services/license-guard.js
11873
- var require_license_guard = __commonJS({
11874
- "server/src/services/license-guard.js"(exports, module) {
11875
- "use strict";
11876
- var crypto = __require("crypto");
11877
- var os = __require("os");
11878
- var pluginPkg = require_package();
11879
- var { createLogger } = require_logger();
11880
- var { setPluginStoreValue, withPluginStoreKey } = require_plugin_store();
11881
- var DEFAULT_LICENSE_SERVER_URL = "https://magicapi.fitlex.me";
11882
- var envTimeout = Number(process.env.MAGIC_LICENSE_TIMEOUT_MS);
11883
- var DEFAULT_FETCH_TIMEOUT_MS = Number.isFinite(envTimeout) && envTimeout > 0 ? envTimeout : 12e3;
11884
- var FETCH_RETRIES = 1;
11885
- var FETCH_RETRY_BACKOFF_MS = 750;
11886
- async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
11887
- let lastError;
11888
- for (let attempt = 0; attempt <= FETCH_RETRIES; attempt += 1) {
11889
- const controller = new AbortController();
11890
- const timer = setTimeout(() => controller.abort(), timeoutMs);
11891
- try {
11892
- return await fetch(url, { ...options, signal: controller.signal });
11893
- } catch (err) {
11894
- lastError = err;
11895
- if (attempt < FETCH_RETRIES) {
11896
- await new Promise((r) => setTimeout(r, FETCH_RETRY_BACKOFF_MS));
11897
- continue;
11898
- }
11899
- throw err;
11900
- } finally {
11901
- clearTimeout(timer);
11902
- }
11903
- }
11904
- throw lastError;
11905
- }
11906
- module.exports = ({ strapi: strapi2 }) => {
11907
- const log = createLogger(strapi2);
11908
- return {
11909
- getLicenseServerUrl() {
11910
- return process.env.MAGIC_LICENSE_SERVER_URL || DEFAULT_LICENSE_SERVER_URL;
11911
- },
11912
- async generateDeviceId() {
11913
- try {
11914
- return await withPluginStoreKey(strapi2, "deviceId", async (pluginStore) => {
11915
- const stored = await pluginStore.get({ key: "deviceId" });
11916
- if (stored && typeof stored === "string" && stored.length >= 16) {
11917
- return stored;
11918
- }
11919
- let identifier;
11920
- try {
11921
- const networkInterfaces = os.networkInterfaces();
11922
- const macAddresses = [];
11923
- Object.values(networkInterfaces).forEach((interfaces) => {
11924
- interfaces?.forEach((iface) => {
11925
- if (iface.mac && iface.mac !== "00:00:00:00:00:00") {
11926
- macAddresses.push(iface.mac);
11927
- }
11928
- });
11929
- });
11930
- identifier = `${macAddresses.join("-")}-${os.hostname()}`;
11931
- } catch {
11932
- identifier = `${Date.now()}-${crypto.randomBytes(16).toString("hex")}`;
11933
- }
11934
- const deviceId = crypto.createHash("sha256").update(identifier).digest("hex").substring(0, 32);
11935
- await pluginStore.set({ key: "deviceId", value: deviceId });
11936
- return deviceId;
11937
- });
11938
- } catch {
11939
- return crypto.randomBytes(16).toString("hex");
11940
- }
11941
- },
11942
- getDeviceName() {
11943
- try {
11944
- return os.hostname() || "Unknown Device";
11945
- } catch {
11946
- return "Unknown Device";
11947
- }
11948
- },
11949
- getIpAddress() {
11950
- try {
11951
- const networkInterfaces = os.networkInterfaces();
11952
- for (const name of Object.keys(networkInterfaces)) {
11953
- const interfaces = networkInterfaces[name];
11954
- if (!interfaces) continue;
11955
- for (const iface of interfaces) {
11956
- if (iface.family === "IPv4" && !iface.internal) {
11957
- return iface.address;
11958
- }
11959
- }
11960
- }
11961
- return "127.0.0.1";
11962
- } catch {
11963
- return "127.0.0.1";
11964
- }
11965
- },
11966
- getUserAgent() {
11967
- const pluginVersion = pluginPkg.version || "1.0.0";
11968
- const strapiVersion = strapi2.config.get("info.strapi") || "5.0.0";
11969
- return `MagicSessionManager/${pluginVersion} Strapi/${strapiVersion} Node/${process.version} ${os.platform()}/${os.release()}`;
11970
- },
11971
- async createLicense({ email, firstName, lastName }) {
11972
- try {
11973
- const response = await fetchWithTimeout(
11974
- `${this.getLicenseServerUrl()}/api/licenses/create`,
11975
- {
11976
- method: "POST",
11977
- headers: { "Content-Type": "application/json" },
11978
- body: JSON.stringify({
11979
- email,
11980
- firstName,
11981
- lastName,
11982
- deviceName: this.getDeviceName(),
11983
- deviceId: await this.generateDeviceId(),
11984
- ipAddress: this.getIpAddress(),
11985
- userAgent: this.getUserAgent(),
11986
- pluginName: "magic-sessionmanager",
11987
- productName: "Magic Session Manager"
11988
- })
11989
- }
11990
- );
11991
- const data = await response.json();
11992
- if (data.success) {
11993
- log.info("[SUCCESS] License created");
11994
- return data.data;
11995
- }
11996
- log.warn("[WARNING] License creation rejected by server");
11997
- return null;
11998
- } catch (error) {
11999
- log.warn("[WARNING] Error creating license:", error?.name || "Error");
12000
- return null;
12001
- }
12002
- },
12003
- async verifyLicense(licenseKey) {
12004
- try {
12005
- const response = await fetchWithTimeout(
12006
- `${this.getLicenseServerUrl()}/api/licenses/verify`,
12007
- {
12008
- method: "POST",
12009
- headers: { "Content-Type": "application/json" },
12010
- body: JSON.stringify({
12011
- licenseKey,
12012
- pluginName: "magic-sessionmanager",
12013
- productName: "Magic Session Manager"
12014
- })
12015
- }
12016
- );
12017
- const data = await response.json();
12018
- if (data.success && data.data) {
12019
- await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
12020
- return { valid: true, data: data.data };
12021
- }
12022
- return { valid: false, data: null };
12023
- } catch (error) {
12024
- log.warn(
12025
- `[WARNING] License server unreachable during optional activation (${error?.name || "Error"}). This does not block the plugin.`
12026
- );
12027
- return { valid: false, data: null, networkError: true };
12028
- }
12029
- },
12030
- async getLicenseByKey(licenseKey) {
12031
- try {
12032
- const encodedKey = encodeURIComponent(licenseKey);
12033
- const response = await fetchWithTimeout(
12034
- `${this.getLicenseServerUrl()}/api/licenses/key/${encodedKey}`,
12035
- {
12036
- method: "GET",
12037
- headers: { "Content-Type": "application/json" }
12038
- }
12039
- );
12040
- const data = await response.json();
12041
- if (data.success && data.data) return data.data;
12042
- return null;
12043
- } catch (error) {
12044
- log.warn("[WARNING] Could not fetch license by key:", error?.name || "Error");
12045
- return null;
12046
- }
12047
- },
12048
- async pingLicense() {
12049
- return null;
12050
- },
12051
- async storeLicenseKey(licenseKey) {
12052
- await setPluginStoreValue(strapi2, "licenseKey", licenseKey);
12053
- await setPluginStoreValue(strapi2, "lastValidated", (/* @__PURE__ */ new Date()).toISOString());
12054
- log.info("[SUCCESS] License key stored");
12055
- return true;
12056
- },
12057
- startPinging() {
12058
- return null;
12059
- },
12060
- async initialize() {
12061
- return { valid: true, demo: false, data: null };
12062
- },
12063
- cleanup() {
12064
- },
12065
- async hasFeature() {
12066
- return true;
12067
- },
12068
- async getMaxSessions() {
12069
- return -1;
12070
- },
12071
- async getLicenseTierInfo() {
12072
- try {
12073
- const pluginStore = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
12074
- const licenseKey = await pluginStore.get({ key: "licenseKey" });
12075
- const hasKey = !!licenseKey;
12076
- return {
12077
- tier: hasKey ? "pro" : "free",
12078
- hasKey,
12079
- features: {
12080
- premium: true,
12081
- advanced: true,
12082
- enterprise: true
12083
- }
12084
- };
12085
- } catch {
12086
- return {
12087
- tier: "free",
12088
- hasKey: false,
12089
- features: { premium: true, advanced: true, enterprise: true }
12090
- };
12091
- }
12092
- }
12093
- };
12094
- };
12095
- }
12096
- });
12097
-
12098
12287
  // server/src/services/geolocation.js
12099
12288
  var require_geolocation = __commonJS({
12100
12289
  "server/src/services/geolocation.js"(exports, module) {
@@ -13247,12 +13436,10 @@ var require_services = __commonJS({
13247
13436
  "server/src/services/index.js"(exports, module) {
13248
13437
  "use strict";
13249
13438
  var session = require_session2();
13250
- var licenseGuard = require_license_guard();
13251
13439
  var geolocation = require_geolocation();
13252
13440
  var notifications = require_notifications();
13253
13441
  module.exports = {
13254
13442
  session,
13255
- "license-guard": licenseGuard,
13256
13443
  geolocation,
13257
13444
  notifications
13258
13445
  };