strapi-plugin-magic-sessionmanager 4.11.0 → 4.13.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 (32) hide show
  1. package/CHANGELOG.md +84 -1
  2. package/README.md +75 -24
  3. package/dist/admin/{Analytics-CBHeWeGn.js → Analytics-BikQQx_J.js} +45 -75
  4. package/dist/admin/{Analytics-D56O8Q6e.mjs → Analytics-DIY51RI_.mjs} +45 -75
  5. package/dist/admin/{App-EDIkLJdb.mjs → App-B3vaybSO.mjs} +584 -120
  6. package/dist/admin/{App-D4cBPwB_.js → App-BV1LM9Bp.js} +584 -120
  7. package/dist/admin/{OnlineUsersWidget-MwUutkKQ.mjs → OnlineUsersWidget-T-2upsDd.mjs} +18 -26
  8. package/dist/admin/{OnlineUsersWidget-BF2R2YIy.js → OnlineUsersWidget-fJogM1xl.js} +18 -26
  9. package/dist/admin/{Settings-CMzEF8EH.js → Settings-AyYka8wn.js} +1 -1
  10. package/dist/admin/{Settings-bLMyi0BN.mjs → Settings-BpBlXyMY.mjs} +1 -1
  11. package/dist/admin/{de-CxfuTF6C.mjs → de-BSCDuq1i.mjs} +41 -6
  12. package/dist/admin/{de-DVNTHmSo.js → de-z0aHRwdw.js} +41 -6
  13. package/dist/admin/{en-BcPIlQYL.mjs → en-B4Cuq9JN.mjs} +41 -6
  14. package/dist/admin/{en-BuVXIcHA.js → en-BWPOiiMt.js} +41 -6
  15. package/dist/admin/{es-CEteHmBO.js → es-CMskkUh-.js} +41 -6
  16. package/dist/admin/{es-DxHpaNA1.mjs → es-DBAmysKi.mjs} +41 -6
  17. package/dist/admin/{fr-Dw43lHg7.mjs → fr-BNGdtjEl.mjs} +41 -6
  18. package/dist/admin/{fr-BMd2-wW7.js → fr-ClJ2BkrE.js} +41 -6
  19. package/dist/admin/{index-DvNfekoR.js → index-DyE1rLW0.js} +22 -56
  20. package/dist/admin/{index-qa6Qnfkc.mjs → index-mCVi1j7e.mjs} +48 -82
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +2 -2
  23. package/dist/admin/{pt-BvO63p01.js → pt-CRh_J7JS.js} +41 -6
  24. package/dist/admin/{pt-7jnxDSX-.mjs → pt-Cl7TWsOV.mjs} +41 -6
  25. package/dist/server/index.js +1495 -51
  26. package/dist/server/index.mjs +1495 -51
  27. package/package.json +10 -2
  28. package/pics/untracked-confirm-dialog.webp +0 -0
  29. package/pics/untracked-disclosure-warning-dark.webp +0 -0
  30. package/pics/untracked-disclosure-warning.webp +0 -0
  31. package/pics/untracked-mobile-notice-warning.webp +0 -0
  32. package/pics/untracked-notice-neutral.webp +0 -0
@@ -1728,7 +1728,26 @@ var require_auth_routes = __commonJS({
1728
1728
  function isFailedLoginTrackedPath(path, method) {
1729
1729
  return FAILED_LOGIN_ROUTES.has(requestKey(path, method)) || isMagicLinkLogin(path, method);
1730
1730
  }
1731
+ var DEFAULT_API_PREFIX = "/api";
1732
+ function normalizeApiPrefix(prefix) {
1733
+ if (typeof prefix !== "string") return DEFAULT_API_PREFIX;
1734
+ const trimmed = prefix.trim().replace(/\/+$/, "");
1735
+ if (!trimmed) return DEFAULT_API_PREFIX;
1736
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
1737
+ }
1738
+ function toCanonicalApiPath(path, prefix) {
1739
+ if (typeof path !== "string") return null;
1740
+ const normalized = normalizeApiPrefix(prefix);
1741
+ if (normalized === DEFAULT_API_PREFIX) return path;
1742
+ if (path === normalized) return DEFAULT_API_PREFIX;
1743
+ if (path.startsWith(`${normalized}/`)) {
1744
+ return `${DEFAULT_API_PREFIX}${path.slice(normalized.length)}`;
1745
+ }
1746
+ return null;
1747
+ }
1731
1748
  module.exports = {
1749
+ normalizeApiPrefix,
1750
+ toCanonicalApiPath,
1732
1751
  classifyJwtIssuingRequest,
1733
1752
  isFailedLoginTrackedPath,
1734
1753
  isPasswordResetRequest,
@@ -1823,6 +1842,404 @@ var require_refresh_token = __commonJS({
1823
1842
  }
1824
1843
  });
1825
1844
 
1845
+ // server/src/utils/native-session-capture.js
1846
+ var require_native_session_capture = __commonJS({
1847
+ "server/src/utils/native-session-capture.js"(exports, module) {
1848
+ "use strict";
1849
+ var NATIVE_SESSION_UID = "admin::session";
1850
+ var NATIVE_ORIGIN = "users-permissions";
1851
+ var CREATED_STATE_KEY = "__magicSessionNativeCreated";
1852
+ var MAX_RECORDED_PER_REQUEST = 20;
1853
+ var MAX_PARSED_BODY_BYTES = 256 * 1024;
1854
+ var MAX_TOKEN_CANDIDATES = 10;
1855
+ function recordCreatedNativeSession(strapi2, row) {
1856
+ if (!row || row.origin !== NATIVE_ORIGIN || row.status !== "active") return false;
1857
+ if (typeof row.sessionId !== "string" || !row.sessionId) return false;
1858
+ if (row.userId == null || row.userId === "") return false;
1859
+ let ctx;
1860
+ try {
1861
+ ctx = strapi2?.requestContext?.get?.();
1862
+ } catch {
1863
+ return false;
1864
+ }
1865
+ if (!ctx || typeof ctx !== "object" || !ctx.state || typeof ctx.state !== "object") {
1866
+ return false;
1867
+ }
1868
+ const list = Array.isArray(ctx.state[CREATED_STATE_KEY]) ? ctx.state[CREATED_STATE_KEY] : [];
1869
+ if (list.length >= MAX_RECORDED_PER_REQUEST) return false;
1870
+ list.push({ sessionId: row.sessionId, userId: String(row.userId) });
1871
+ ctx.state[CREATED_STATE_KEY] = list;
1872
+ return true;
1873
+ }
1874
+ function subscribeNativeSessionCreation(strapi2) {
1875
+ const lifecycles = strapi2?.db?.lifecycles;
1876
+ if (!lifecycles || typeof lifecycles.subscribe !== "function") return () => {
1877
+ };
1878
+ if (!strapi2?.contentTypes?.[NATIVE_SESSION_UID]) return () => {
1879
+ };
1880
+ const unsubscribe = lifecycles.subscribe({
1881
+ models: [NATIVE_SESSION_UID],
1882
+ afterCreate(event) {
1883
+ try {
1884
+ recordCreatedNativeSession(strapi2, event?.result);
1885
+ } catch {
1886
+ }
1887
+ }
1888
+ });
1889
+ return typeof unsubscribe === "function" ? unsubscribe : () => {
1890
+ };
1891
+ }
1892
+ function getCreatedNativeSessions(ctx) {
1893
+ const list = ctx?.state?.[CREATED_STATE_KEY];
1894
+ return Array.isArray(list) ? list.slice() : [];
1895
+ }
1896
+ function isThenable(value) {
1897
+ return Boolean(value) && typeof value === "object" && typeof value.then === "function";
1898
+ }
1899
+ function readJsonBody(body) {
1900
+ if (body && typeof body === "object" && !Buffer.isBuffer(body) && !isStream(body)) return body;
1901
+ if (typeof body !== "string" || body.length === 0) return null;
1902
+ if (Buffer.byteLength(body, "utf8") > MAX_PARSED_BODY_BYTES) return null;
1903
+ const first = body.trimStart()[0];
1904
+ if (first !== "{") return null;
1905
+ try {
1906
+ const parsed = JSON.parse(body);
1907
+ return parsed && typeof parsed === "object" ? parsed : null;
1908
+ } catch {
1909
+ return null;
1910
+ }
1911
+ }
1912
+ function isStream(value) {
1913
+ return typeof value.pipe === "function";
1914
+ }
1915
+ function findAccessTokenCandidates(body) {
1916
+ const json = readJsonBody(body);
1917
+ if (!json) return [];
1918
+ const candidates = [];
1919
+ const add = (value) => {
1920
+ if (typeof value === "string" && value.length > 0 && value.length <= 8192) {
1921
+ if (!candidates.includes(value)) candidates.push(value);
1922
+ }
1923
+ };
1924
+ add(json.jwt);
1925
+ const data = json.data;
1926
+ if (data && typeof data === "object" && !Array.isArray(data)) {
1927
+ for (const value of Object.values(data)) {
1928
+ if (candidates.length >= MAX_TOKEN_CANDIDATES) break;
1929
+ if (value && typeof value === "object" && !Array.isArray(value)) add(value.jwt);
1930
+ }
1931
+ }
1932
+ return candidates.slice(0, MAX_TOKEN_CANDIDATES);
1933
+ }
1934
+ async function revokeCreatedNativeSessions({ ctx, nativeSessionManager, log, except = null }) {
1935
+ let revoked = 0;
1936
+ for (const created of getCreatedNativeSessions(ctx)) {
1937
+ if (except && created.sessionId === except) continue;
1938
+ try {
1939
+ if (await nativeSessionManager.revokeSessionById(created.userId, created.sessionId)) {
1940
+ revoked += 1;
1941
+ }
1942
+ } catch (err) {
1943
+ log?.error?.("[AUTH-COMPENSATION] Native session revocation failed:", err?.name || "Error");
1944
+ }
1945
+ }
1946
+ return revoked;
1947
+ }
1948
+ module.exports = {
1949
+ CREATED_STATE_KEY,
1950
+ MAX_RECORDED_PER_REQUEST,
1951
+ MAX_PARSED_BODY_BYTES,
1952
+ recordCreatedNativeSession,
1953
+ subscribeNativeSessionCreation,
1954
+ getCreatedNativeSessions,
1955
+ findAccessTokenCandidates,
1956
+ revokeCreatedNativeSessions,
1957
+ isThenable
1958
+ };
1959
+ }
1960
+ });
1961
+
1962
+ // server/src/utils/native-only-insight.js
1963
+ var require_native_only_insight = __commonJS({
1964
+ "server/src/utils/native-only-insight.js"(exports, module) {
1965
+ "use strict";
1966
+ var { getNativeSessionManager } = require_native_session_manager();
1967
+ var { withPluginStoreKey, PLUGIN_ID } = require_plugin_store();
1968
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
1969
+ var NATIVE_SESSION_UID = "admin::session";
1970
+ var NATIVE_ORIGIN = "users-permissions";
1971
+ var TRACKING_STORE_KEY = "nativeTracking";
1972
+ var MONTH_BUCKETS = 12;
1973
+ var DEVICE_SAMPLE_LIMIT = 2e3;
1974
+ var DEVICE_SAMPLE_BATCH = 500;
1975
+ var END_BATCH_SIZE = 200;
1976
+ var END_MAX_ROWS = 5e3;
1977
+ var END_MIN_AGE_MS = 2 * 60 * 1e3;
1978
+ var DAY_MS = 24 * 60 * 60 * 1e3;
1979
+ function canInspectNativeSessions(strapi2) {
1980
+ return Boolean(
1981
+ getNativeSessionManager(strapi2) && strapi2?.contentTypes?.[NATIVE_SESSION_UID] && strapi2?.db?.metadata?.get?.(NATIVE_SESSION_UID)
1982
+ );
1983
+ }
1984
+ function tables(strapi2) {
1985
+ const nativeMeta = strapi2.db.metadata.get(NATIVE_SESSION_UID);
1986
+ const sessionMeta = strapi2.db.metadata.get(SESSION_UID);
1987
+ const column = (meta, attribute) => meta.attributes[attribute]?.columnName || attribute;
1988
+ return {
1989
+ knex: strapi2.db.connection,
1990
+ native: nativeMeta.tableName,
1991
+ sidecar: sessionMeta.tableName,
1992
+ linked: column(sessionMeta, "nativeSessionId"),
1993
+ col: {
1994
+ id: column(nativeMeta, "id"),
1995
+ sessionId: column(nativeMeta, "sessionId"),
1996
+ origin: column(nativeMeta, "origin"),
1997
+ status: column(nativeMeta, "status"),
1998
+ expiresAt: column(nativeMeta, "expiresAt"),
1999
+ absoluteExpiresAt: column(nativeMeta, "absoluteExpiresAt"),
2000
+ createdAt: column(nativeMeta, "createdAt"),
2001
+ metadata: column(nativeMeta, "metadata"),
2002
+ deviceId: column(nativeMeta, "deviceId")
2003
+ }
2004
+ };
2005
+ }
2006
+ function untrackedQuery(t, now) {
2007
+ const { knex, native, sidecar, linked, col } = t;
2008
+ return knex(native).where(`${native}.${col.origin}`, NATIVE_ORIGIN).andWhere(`${native}.${col.status}`, "active").andWhere(`${native}.${col.expiresAt}`, ">", now).andWhere((qb) => {
2009
+ qb.whereNull(`${native}.${col.absoluteExpiresAt}`).orWhere(
2010
+ `${native}.${col.absoluteExpiresAt}`,
2011
+ ">",
2012
+ now
2013
+ );
2014
+ }).whereNotExists(function linkedSidecar() {
2015
+ this.select(knex.raw("1")).from(sidecar).whereRaw("??.?? = ??.??", [sidecar, linked, native, col.sessionId]);
2016
+ });
2017
+ }
2018
+ function sumWhen(knex, condition, bindings, alias) {
2019
+ return knex.raw(`SUM(CASE WHEN ${condition} THEN 1 ELSE 0 END) AS ??`, [...bindings, alias]);
2020
+ }
2021
+ function toCount(value) {
2022
+ const number = Number(value);
2023
+ return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
2024
+ }
2025
+ async function getNativeTrackingSince(strapi2) {
2026
+ const value = await strapi2.store({ type: "plugin", name: PLUGIN_ID }).get({ key: TRACKING_STORE_KEY });
2027
+ const since = value && typeof value === "object" ? new Date(value.since) : null;
2028
+ return since && Number.isFinite(since.getTime()) ? since : null;
2029
+ }
2030
+ async function ensureNativeTrackingSince(strapi2, now = /* @__PURE__ */ new Date()) {
2031
+ const existing = await getNativeTrackingSince(strapi2);
2032
+ if (existing) return existing;
2033
+ return withPluginStoreKey(strapi2, TRACKING_STORE_KEY, async (store) => {
2034
+ const again = await store.get({ key: TRACKING_STORE_KEY });
2035
+ const stored = again && typeof again === "object" ? new Date(again.since) : null;
2036
+ if (stored && Number.isFinite(stored.getTime())) return stored;
2037
+ const oldest = await strapi2.db.query(SESSION_UID).findMany({
2038
+ where: { nativeSessionId: { $notNull: true } },
2039
+ select: ["loginTime"],
2040
+ orderBy: [{ loginTime: "asc" }],
2041
+ limit: 1
2042
+ });
2043
+ const first = oldest?.[0]?.loginTime ? new Date(oldest[0].loginTime) : null;
2044
+ const since = first && Number.isFinite(first.getTime()) && first.getTime() < now.getTime() ? first : now;
2045
+ await store.set({
2046
+ key: TRACKING_STORE_KEY,
2047
+ value: { since: since.toISOString(), source: first ? "first-linked-session" : "install" }
2048
+ });
2049
+ return since;
2050
+ });
2051
+ }
2052
+ async function countNativeOnly(strapi2, { now = /* @__PURE__ */ new Date(), trackingSince = null } = {}) {
2053
+ if (!canInspectNativeSessions(strapi2)) return { total: 0, afterTracking: null };
2054
+ const t = tables(strapi2);
2055
+ const selects = [t.knex.raw("COUNT(*) AS ??", ["total"])];
2056
+ if (trackingSince) {
2057
+ selects.push(
2058
+ sumWhen(t.knex, "??.?? >= ?", [t.native, t.col.createdAt, trackingSince], "afterTracking")
2059
+ );
2060
+ }
2061
+ const row = await untrackedQuery(t, now).select(...selects).first();
2062
+ return {
2063
+ total: toCount(row?.total),
2064
+ afterTracking: trackingSince ? toCount(row?.afterTracking) : null
2065
+ };
2066
+ }
2067
+ function monthStart(date, offset) {
2068
+ return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + offset, 1));
2069
+ }
2070
+ function monthLabel(date) {
2071
+ return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
2072
+ }
2073
+ function deviceClassOf(metadata) {
2074
+ let value = metadata;
2075
+ if (typeof value === "string") {
2076
+ if (value.length > 4096) return "unknown";
2077
+ try {
2078
+ value = JSON.parse(value);
2079
+ } catch {
2080
+ return "unknown";
2081
+ }
2082
+ }
2083
+ const name = value && typeof value === "object" ? value.deviceName : null;
2084
+ if (typeof name !== "string" || !name) return "unknown";
2085
+ const label = name.slice(0, 200);
2086
+ if (/\b(?:iOS|Android)\b/.test(label)) return "mobile";
2087
+ if (/\b(?:Windows|macOS|Linux|ChromeOS)\b/.test(label)) return "desktop";
2088
+ return "unknown";
2089
+ }
2090
+ async function sampleDevices(t, now) {
2091
+ const counts = { desktop: 0, mobile: 0, unknown: 0 };
2092
+ let scanned = 0;
2093
+ let lastId = null;
2094
+ let complete = false;
2095
+ while (scanned < DEVICE_SAMPLE_LIMIT) {
2096
+ const limit = Math.min(DEVICE_SAMPLE_BATCH, DEVICE_SAMPLE_LIMIT - scanned);
2097
+ const query = untrackedQuery(t, now).select({ id: `${t.native}.${t.col.id}`, metadata: `${t.native}.${t.col.metadata}` }).orderBy(`${t.native}.${t.col.id}`, "asc").limit(limit);
2098
+ if (lastId !== null) query.andWhere(`${t.native}.${t.col.id}`, ">", lastId);
2099
+ const rows = await query;
2100
+ for (const row of rows) counts[deviceClassOf(row.metadata)] += 1;
2101
+ scanned += rows.length;
2102
+ if (rows.length < limit) {
2103
+ complete = true;
2104
+ break;
2105
+ }
2106
+ lastId = rows[rows.length - 1].id;
2107
+ }
2108
+ return { ...counts, scanned, complete };
2109
+ }
2110
+ async function getNativeOnlySummary(strapi2, { now = /* @__PURE__ */ new Date() } = {}) {
2111
+ const trackingSince = canInspectNativeSessions(strapi2) ? await getNativeTrackingSince(strapi2) : null;
2112
+ const empty = {
2113
+ available: false,
2114
+ total: 0,
2115
+ trackingSince: trackingSince ? trackingSince.toISOString() : null,
2116
+ beforeTracking: 0,
2117
+ afterTracking: 0,
2118
+ byMonth: [],
2119
+ earlier: 0,
2120
+ bySource: { signIn: 0, passwordChange: 0, tokenOnly: 0 },
2121
+ byDevice: { desktop: 0, mobile: 0, unknown: 0 },
2122
+ deviceSample: { scanned: 0, limit: DEVICE_SAMPLE_LIMIT, complete: true },
2123
+ expiring: { within7Days: 0, within30Days: 0 },
2124
+ generatedAt: now.toISOString()
2125
+ };
2126
+ if (!canInspectNativeSessions(strapi2)) return empty;
2127
+ const t = tables(strapi2);
2128
+ const { knex, native, col } = t;
2129
+ const created = [native, col.createdAt];
2130
+ const in7 = new Date(now.getTime() + 7 * DAY_MS);
2131
+ const in30 = new Date(now.getTime() + 30 * DAY_MS);
2132
+ const expiringWithin = (until) => [
2133
+ "??.?? <= ? OR (??.?? IS NOT NULL AND ??.?? <= ?)",
2134
+ [
2135
+ native,
2136
+ col.expiresAt,
2137
+ until,
2138
+ native,
2139
+ col.absoluteExpiresAt,
2140
+ native,
2141
+ col.absoluteExpiresAt,
2142
+ until
2143
+ ]
2144
+ ];
2145
+ const months = Array.from({ length: MONTH_BUCKETS }, (_, index) => {
2146
+ const start = monthStart(now, index - (MONTH_BUCKETS - 1));
2147
+ return { start, end: monthStart(start, 1), label: monthLabel(start) };
2148
+ });
2149
+ const selects = [
2150
+ knex.raw("COUNT(*) AS ??", ["total"]),
2151
+ sumWhen(knex, "??.?? IS NOT NULL", [native, col.metadata], "signIn"),
2152
+ sumWhen(
2153
+ knex,
2154
+ "??.?? IS NULL AND ??.?? IS NOT NULL",
2155
+ [native, col.metadata, native, col.deviceId],
2156
+ "passwordChange"
2157
+ ),
2158
+ sumWhen(
2159
+ knex,
2160
+ "??.?? IS NULL AND ??.?? IS NULL",
2161
+ [native, col.metadata, native, col.deviceId],
2162
+ "tokenOnly"
2163
+ ),
2164
+ sumWhen(knex, ...expiringWithin(in7), "within7Days"),
2165
+ sumWhen(knex, ...expiringWithin(in30), "within30Days"),
2166
+ sumWhen(knex, "??.?? < ?", [...created, months[0].start], "earlier"),
2167
+ ...months.map(
2168
+ (month, index) => sumWhen(
2169
+ knex,
2170
+ "??.?? >= ? AND ??.?? < ?",
2171
+ [...created, month.start, ...created, month.end],
2172
+ `m${index}`
2173
+ )
2174
+ )
2175
+ ];
2176
+ if (trackingSince) {
2177
+ selects.push(sumWhen(knex, "??.?? >= ?", [...created, trackingSince], "afterTracking"));
2178
+ }
2179
+ const row = await untrackedQuery(t, now).select(...selects).first() || {};
2180
+ const total = toCount(row.total);
2181
+ const afterTracking = trackingSince ? toCount(row.afterTracking) : 0;
2182
+ const devices = total > 0 ? await sampleDevices(t, now) : null;
2183
+ return {
2184
+ ...empty,
2185
+ available: true,
2186
+ total,
2187
+ beforeTracking: trackingSince ? Math.max(0, total - afterTracking) : total,
2188
+ afterTracking,
2189
+ byMonth: months.map((month, index) => ({ month: month.label, count: toCount(row[`m${index}`]) })).filter((entry) => entry.count > 0),
2190
+ earlier: toCount(row.earlier),
2191
+ bySource: {
2192
+ signIn: toCount(row.signIn),
2193
+ passwordChange: toCount(row.passwordChange),
2194
+ tokenOnly: toCount(row.tokenOnly)
2195
+ },
2196
+ byDevice: devices ? { desktop: devices.desktop, mobile: devices.mobile, unknown: devices.unknown } : empty.byDevice,
2197
+ deviceSample: devices ? { scanned: devices.scanned, limit: DEVICE_SAMPLE_LIMIT, complete: devices.complete } : empty.deviceSample,
2198
+ expiring: { within7Days: toCount(row.within7Days), within30Days: toCount(row.within30Days) }
2199
+ };
2200
+ }
2201
+ async function endNativeOnlySessions(strapi2, { now = /* @__PURE__ */ new Date(), maxRows = END_MAX_ROWS } = {}) {
2202
+ if (!canInspectNativeSessions(strapi2)) return { ended: 0, remaining: 0 };
2203
+ const t = tables(strapi2);
2204
+ const limit = Math.max(0, Math.min(END_MAX_ROWS, Math.floor(Number(maxRows) || 0)));
2205
+ const createdBefore = new Date(now.getTime() - END_MIN_AGE_MS);
2206
+ const idColumn = `${t.native}.${t.col.id}`;
2207
+ const oldEnough = (query) => query.andWhere(`${t.native}.${t.col.createdAt}`, "<", createdBefore);
2208
+ let ended = 0;
2209
+ let lastId = null;
2210
+ while (ended < limit) {
2211
+ const size = Math.min(END_BATCH_SIZE, limit - ended);
2212
+ const select = oldEnough(untrackedQuery(t, now)).select({ id: idColumn }).orderBy(idColumn, "asc").limit(size);
2213
+ if (lastId !== null) select.andWhere(idColumn, ">", lastId);
2214
+ const rows = await select;
2215
+ if (rows.length === 0) break;
2216
+ const ids = rows.map((row) => row.id);
2217
+ lastId = ids[ids.length - 1];
2218
+ const deleted = await oldEnough(untrackedQuery(t, now)).whereIn(idColumn, ids).del();
2219
+ ended += toCount(deleted);
2220
+ if (rows.length < size) break;
2221
+ }
2222
+ const { total } = await countNativeOnly(strapi2, { now });
2223
+ return { ended, remaining: total };
2224
+ }
2225
+ module.exports = {
2226
+ TRACKING_STORE_KEY,
2227
+ MONTH_BUCKETS,
2228
+ DEVICE_SAMPLE_LIMIT,
2229
+ END_BATCH_SIZE,
2230
+ END_MAX_ROWS,
2231
+ END_MIN_AGE_MS,
2232
+ canInspectNativeSessions,
2233
+ getNativeTrackingSince,
2234
+ ensureNativeTrackingSince,
2235
+ countNativeOnly,
2236
+ deviceClassOf,
2237
+ getNativeOnlySummary,
2238
+ endNativeOnlySessions
2239
+ };
2240
+ }
2241
+ });
2242
+
1826
2243
  // server/src/middlewares/session-rejection-headers.js
1827
2244
  var require_session_rejection_headers = __commonJS({
1828
2245
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -1879,6 +2296,7 @@ var require_last_seen = __commonJS({
1879
2296
  var { resolveUserDocumentId } = require_resolve_user();
1880
2297
  var { extractBearerToken } = require_extract_token();
1881
2298
  var { hashToken } = require_encryption();
2299
+ var { toCanonicalApiPath } = require_auth_routes();
1882
2300
  var SESSION_UID = "plugin::magic-sessionmanager.session";
1883
2301
  var AUTH_PATH_PREFIXES = [
1884
2302
  "/api/auth/",
@@ -1903,16 +2321,21 @@ var require_last_seen = __commonJS({
1903
2321
  }
1904
2322
  module.exports = ({ strapi: strapi2, sessionService }) => {
1905
2323
  return async (ctx, next) => {
1906
- if (isAuthEndpoint(ctx.path)) {
2324
+ const apiPath = toCanonicalApiPath(ctx.path, strapi2.config?.get?.("api.rest.prefix", "/api")) ?? ctx.path;
2325
+ if (isAuthEndpoint(apiPath)) {
1907
2326
  return next();
1908
2327
  }
1909
2328
  await next();
1910
- if (isSelfTerminatingEndpoint(ctx.path) || (ctx.status || 200) >= 400) {
2329
+ if (isSelfTerminatingEndpoint(apiPath) || (ctx.status || 200) >= 400) {
1911
2330
  return;
1912
2331
  }
1913
2332
  if (!ctx.state.user) {
1914
2333
  return;
1915
2334
  }
2335
+ const strategyName = ctx.state.auth?.strategy?.name;
2336
+ if (strategyName === "admin" || strategyName === "admin-token") {
2337
+ return;
2338
+ }
1916
2339
  let userDocId = ctx.state.user.documentId;
1917
2340
  if (!userDocId && ctx.state.user.id) {
1918
2341
  try {
@@ -5918,6 +6341,8 @@ var require_bootstrap = __commonJS({
5918
6341
  } = require_coordination();
5919
6342
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
5920
6343
  var {
6344
+ normalizeApiPrefix,
6345
+ toCanonicalApiPath,
5921
6346
  classifyJwtIssuingRequest,
5922
6347
  isFailedLoginTrackedPath,
5923
6348
  isPasswordResetRequest,
@@ -5929,6 +6354,14 @@ var require_bootstrap = __commonJS({
5929
6354
  getOutgoingRefreshToken,
5930
6355
  stripAuthTokensFromResponse
5931
6356
  } = require_refresh_token();
6357
+ var {
6358
+ subscribeNativeSessionCreation,
6359
+ getCreatedNativeSessions,
6360
+ findAccessTokenCandidates,
6361
+ revokeCreatedNativeSessions,
6362
+ isThenable
6363
+ } = require_native_session_capture();
6364
+ var { ensureNativeTrackingSince } = require_native_only_insight();
5932
6365
  var SESSION_UID = "plugin::magic-sessionmanager.session";
5933
6366
  var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
5934
6367
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -5975,6 +6408,17 @@ var require_bootstrap = __commonJS({
5975
6408
  await ensureSessionLookupIndexes(strapi2, log);
5976
6409
  await registerSessionAwareAuthStrategy(strapi2);
5977
6410
  await removeLegacyLicenseRows(strapi2, log);
6411
+ strapi2.sessionManagerUnsubscribers = [
6412
+ ...strapi2.sessionManagerUnsubscribers || [],
6413
+ subscribeNativeSessionCreation(strapi2)
6414
+ ];
6415
+ if (usesNativeRefreshSessions(strapi2)) {
6416
+ try {
6417
+ await ensureNativeTrackingSince(strapi2);
6418
+ } catch (err) {
6419
+ log.warn("[NATIVE] Tracking start date could not be stored:", err?.name || "Error");
6420
+ }
6421
+ }
5978
6422
  const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
5979
6423
  if (!strapi2.sessionManagerIntervals) {
5980
6424
  strapi2.sessionManagerIntervals = {};
@@ -6106,7 +6550,7 @@ var require_bootstrap = __commonJS({
6106
6550
  }
6107
6551
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
6108
6552
  strapi2.server.use(async (ctx, next) => {
6109
- if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
6553
+ if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
6110
6554
  return next();
6111
6555
  }
6112
6556
  const settings = await getRequestSettings(strapi2, ctx);
@@ -6159,7 +6603,8 @@ var require_bootstrap = __commonJS({
6159
6603
  log.info("[SUCCESS] Pre-login geo guard mounted");
6160
6604
  }
6161
6605
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
6162
- if (hasRegisteredRoute(strapi2, "POST", "/api/auth/logout")) {
6606
+ const logoutPath = `${normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"))}/auth/logout`;
6607
+ if (hasRegisteredRoute(strapi2, "POST", logoutPath)) {
6163
6608
  log.debug("[LOGOUT] Using the users-permissions logout route");
6164
6609
  return;
6165
6610
  }
@@ -6172,7 +6617,7 @@ var require_bootstrap = __commonJS({
6172
6617
  strapi2.server.routes([
6173
6618
  {
6174
6619
  method: "POST",
6175
- path: "/api/auth/logout",
6620
+ path: logoutPath,
6176
6621
  handler: async (ctx) => {
6177
6622
  try {
6178
6623
  const token = extractBearerToken(ctx);
@@ -6248,6 +6693,9 @@ var require_bootstrap = __commonJS({
6248
6693
  ]);
6249
6694
  log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
6250
6695
  }
6696
+ function apiPathOf(strapi2, ctx) {
6697
+ return toCanonicalApiPath(ctx.path, strapi2.config.get("api.rest.prefix", "/api"));
6698
+ }
6251
6699
  function hasRegisteredRoute(strapi2, method, path) {
6252
6700
  try {
6253
6701
  const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
@@ -6281,11 +6729,35 @@ var require_bootstrap = __commonJS({
6281
6729
  function usesNativeRefreshSessions(strapi2) {
6282
6730
  return strapi2.config.get("plugin::users-permissions.jwtManagement", "legacy-support") === "refresh";
6283
6731
  }
6284
- async function resolveNativeRefreshSession({ strapi: strapi2, nativeSessionManager, refreshToken, user }) {
6285
- if (!refreshToken) throw new Error("native auth response contains no refresh token");
6286
- const validation = await nativeSessionManager.validateRefreshToken(refreshToken);
6287
- if (!validation?.isValid || !validation.userId || !validation.sessionId) {
6288
- throw new Error("new native refresh token could not be validated");
6732
+ async function resolveNativeAccessSession(nativeSessionManager, accessToken) {
6733
+ const validation = await nativeSessionManager.validateAccessToken(accessToken);
6734
+ const payload = validation?.isValid ? validation.payload : null;
6735
+ if (!payload?.userId || !payload?.sessionId) {
6736
+ throw new Error("native access token could not be validated");
6737
+ }
6738
+ const sessionId = String(payload.sessionId);
6739
+ if (!await nativeSessionManager.isSessionActive(sessionId)) {
6740
+ throw new Error("native access token belongs to no active session");
6741
+ }
6742
+ return { userId: String(payload.userId), sessionId };
6743
+ }
6744
+ async function resolveNativeRefreshSession({
6745
+ strapi: strapi2,
6746
+ nativeSessionManager,
6747
+ refreshToken,
6748
+ accessToken = null,
6749
+ user
6750
+ }) {
6751
+ let validation;
6752
+ if (refreshToken) {
6753
+ validation = await nativeSessionManager.validateRefreshToken(refreshToken);
6754
+ if (!validation?.isValid || !validation.userId || !validation.sessionId) {
6755
+ throw new Error("new native refresh token could not be validated");
6756
+ }
6757
+ } else if (typeof accessToken === "string" && accessToken) {
6758
+ validation = await resolveNativeAccessSession(nativeSessionManager, accessToken);
6759
+ } else {
6760
+ throw new Error("native auth response contains no refresh token");
6289
6761
  }
6290
6762
  const userId = String(validation.userId);
6291
6763
  if (user?.id != null && String(user.id) !== userId) {
@@ -6317,7 +6789,7 @@ var require_bootstrap = __commonJS({
6317
6789
  const coordinator = getCoordinator(strapi2);
6318
6790
  const keyFor = (ip) => hashedKey("lf", ip);
6319
6791
  strapi2.server.use(async (ctx, next) => {
6320
- if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
6792
+ if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
6321
6793
  const settings = await getRequestSettings(strapi2, ctx);
6322
6794
  const maxFailed = Number(settings.maxFailedLogins) || 0;
6323
6795
  if (maxFailed <= 0) return next();
@@ -6419,13 +6891,34 @@ var require_bootstrap = __commonJS({
6419
6891
  }
6420
6892
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
6421
6893
  strapi2.server.use(async (ctx, next) => {
6422
- const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
6894
+ const apiPath = apiPathOf(strapi2, ctx);
6895
+ const requestType = classifyJwtIssuingRequest(apiPath, ctx.method);
6423
6896
  const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
6424
6897
  const nativeMode = usesNativeRefreshSessions(strapi2);
6425
6898
  await next();
6899
+ if (nativeMode && requestType === null) {
6900
+ await linkCreatedNativeSessions({ strapi: strapi2, ctx, log, sessionService });
6901
+ return;
6902
+ }
6426
6903
  if (requestType !== "new-session" && requestType !== "rotate-current") return;
6427
6904
  if (ctx.status < 200 || ctx.status >= 300) return;
6428
6905
  if (!ctx.body || !ctx.body.jwt) return;
6906
+ if (nativeMode && isThenable(ctx.body.jwt)) {
6907
+ try {
6908
+ ctx.body.jwt = await ctx.body.jwt;
6909
+ } catch (err) {
6910
+ await compensateCreatedNativeSessions({ strapi: strapi2, ctx, log });
6911
+ failClosedAuthResponse({
6912
+ ctx,
6913
+ strapi: strapi2,
6914
+ log,
6915
+ operation: "access token could not be issued",
6916
+ error: err
6917
+ });
6918
+ return;
6919
+ }
6920
+ if (typeof ctx.body.jwt !== "string" || !ctx.body.jwt) return;
6921
+ }
6429
6922
  const refreshCookieName = getRefreshCookieName(strapi2);
6430
6923
  if (requestType === "rotate-current") {
6431
6924
  if (nativeMode) {
@@ -6439,6 +6932,7 @@ var require_bootstrap = __commonJS({
6439
6932
  strapi: strapi2,
6440
6933
  nativeSessionManager: nativeSessionManager2,
6441
6934
  refreshToken: newRefreshToken,
6935
+ accessToken: ctx.body.jwt,
6442
6936
  user: ctx.body.user || ctx.state?.user
6443
6937
  });
6444
6938
  const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
@@ -6475,6 +6969,12 @@ var require_bootstrap = __commonJS({
6475
6969
  if (nativeSessionManager2 && nativeSession2) {
6476
6970
  await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
6477
6971
  }
6972
+ await compensateCreatedNativeSessions({
6973
+ strapi: strapi2,
6974
+ ctx,
6975
+ log,
6976
+ except: nativeSession2?.sessionId
6977
+ });
6478
6978
  failClosedAuthResponse({
6479
6979
  ctx,
6480
6980
  strapi: strapi2,
@@ -6531,6 +7031,7 @@ var require_bootstrap = __commonJS({
6531
7031
  strapi: strapi2,
6532
7032
  nativeSessionManager,
6533
7033
  refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
7034
+ accessToken: ctx.body.jwt,
6534
7035
  user
6535
7036
  });
6536
7037
  userDocId = nativeSession.userDocumentId;
@@ -6556,7 +7057,7 @@ var require_bootstrap = __commonJS({
6556
7057
  if (!newSession?.documentId) {
6557
7058
  throw new Error(`session creation returned no documentId for user ${userDocId}`);
6558
7059
  }
6559
- if (isPasswordResetRequest(ctx.path, ctx.method)) {
7060
+ if (isPasswordResetRequest(apiPath, ctx.method)) {
6560
7061
  await sessionService.terminateSession({
6561
7062
  userId: userDocId,
6562
7063
  exceptSessionId: newSession.documentId,
@@ -6691,6 +7192,14 @@ var require_bootstrap = __commonJS({
6691
7192
  if (nativeSessionManager && nativeSession) {
6692
7193
  await compensateNativeSession({ nativeSessionManager, nativeSession, log });
6693
7194
  }
7195
+ if (nativeMode) {
7196
+ await compensateCreatedNativeSessions({
7197
+ strapi: strapi2,
7198
+ ctx,
7199
+ log,
7200
+ except: nativeSession?.sessionId
7201
+ });
7202
+ }
6694
7203
  failClosedAuthResponse({
6695
7204
  ctx,
6696
7205
  strapi: strapi2,
@@ -6702,9 +7211,76 @@ var require_bootstrap = __commonJS({
6702
7211
  });
6703
7212
  log.info("[SUCCESS] Login interceptor middleware mounted");
6704
7213
  }
7214
+ async function compensateCreatedNativeSessions({ strapi: strapi2, ctx, log, except = null }) {
7215
+ if (getCreatedNativeSessions(ctx).length === 0) return;
7216
+ try {
7217
+ const nativeSessionManager = getNativeSessionManager(strapi2);
7218
+ if (!nativeSessionManager) return;
7219
+ await revokeCreatedNativeSessions({ ctx, nativeSessionManager, log, except });
7220
+ } catch (err) {
7221
+ log.error("[AUTH-COMPENSATION] Native session revocation failed:", err?.name || "Error");
7222
+ }
7223
+ }
7224
+ async function linkCreatedNativeSessions({ strapi: strapi2, ctx, log, sessionService }) {
7225
+ const created = getCreatedNativeSessions(ctx);
7226
+ if (created.length === 0) return 0;
7227
+ if (ctx.status < 200 || ctx.status >= 300) return 0;
7228
+ let linked = 0;
7229
+ try {
7230
+ const nativeSessionManager = getNativeSessionManager(strapi2);
7231
+ if (!nativeSessionManager) return 0;
7232
+ const ids = [...new Set(created.map((entry) => entry.sessionId))];
7233
+ const existing = await strapi2.db.query(SESSION_UID).findMany({
7234
+ where: { nativeSessionId: { $in: ids } },
7235
+ select: ["nativeSessionId"]
7236
+ });
7237
+ const alreadyLinked = new Set((existing || []).map((row) => String(row.nativeSessionId)));
7238
+ const pending = new Map(
7239
+ created.filter((entry) => !alreadyLinked.has(entry.sessionId)).map((entry) => [entry.sessionId, entry])
7240
+ );
7241
+ if (pending.size === 0) return 0;
7242
+ for (const candidate of findAccessTokenCandidates(ctx.body)) {
7243
+ if (pending.size === 0) break;
7244
+ let session;
7245
+ try {
7246
+ session = await resolveNativeAccessSession(nativeSessionManager, candidate);
7247
+ } catch {
7248
+ continue;
7249
+ }
7250
+ const entry = pending.get(session.sessionId);
7251
+ if (!entry || entry.userId !== session.userId) continue;
7252
+ const userDocumentId = await resolveUserDocumentId(strapi2, session.userId);
7253
+ if (!userDocumentId) continue;
7254
+ const headers = ctx.request?.headers || ctx.request?.header || {};
7255
+ const createdSidecar = await sessionService.createSession({
7256
+ userId: userDocumentId,
7257
+ ip: getClientIp(ctx),
7258
+ userAgent: headers["user-agent"] || "unknown",
7259
+ token: candidate,
7260
+ geoData: ctx.state?.__magicSessionGeoData || null,
7261
+ nativeSessionId: session.sessionId
7262
+ });
7263
+ if (createdSidecar?.documentId) {
7264
+ pending.delete(session.sessionId);
7265
+ linked += 1;
7266
+ }
7267
+ }
7268
+ if (linked > 0) {
7269
+ log.info(`[CAPTURE] Linked ${linked} session(s) created outside the intercepted auth routes`);
7270
+ }
7271
+ if (pending.size > 0) {
7272
+ log.debug(
7273
+ `[CAPTURE] ${pending.size} session(s) created without their token in the response; not tracked`
7274
+ );
7275
+ }
7276
+ } catch (err) {
7277
+ log.warn("[CAPTURE] Linking a session created elsewhere failed:", err?.name || "Error");
7278
+ }
7279
+ return linked;
7280
+ }
6705
7281
  function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
6706
7282
  strapi2.server.use(async (ctx, next) => {
6707
- const isRefreshToken = ctx.path === "/api/auth/refresh" && ctx.method === "POST";
7283
+ const isRefreshToken = apiPathOf(strapi2, ctx) === "/api/auth/refresh" && ctx.method === "POST";
6708
7284
  if (!isRefreshToken) return next();
6709
7285
  const cookieName = getRefreshCookieName(strapi2);
6710
7286
  const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
@@ -6803,6 +7379,12 @@ var require_bootstrap = __commonJS({
6803
7379
  if (nativeSession) {
6804
7380
  await compensateNativeSession({ nativeSessionManager, nativeSession, log });
6805
7381
  }
7382
+ await compensateCreatedNativeSessions({
7383
+ strapi: strapi2,
7384
+ ctx,
7385
+ log,
7386
+ except: nativeSession?.sessionId
7387
+ });
6806
7388
  failClosedAuthResponse({
6807
7389
  ctx,
6808
7390
  strapi: strapi2,
@@ -6840,7 +7422,7 @@ var require_bootstrap = __commonJS({
6840
7422
  }
6841
7423
  function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
6842
7424
  strapi2.server.use(async (ctx, next) => {
6843
- if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
7425
+ if (apiPathOf(strapi2, ctx) !== "/api/auth/logout" || ctx.method !== "POST") return next();
6844
7426
  const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
6845
7427
  const accessToken = extractBearerToken(ctx);
6846
7428
  const nativeMode = usesNativeRefreshSessions(strapi2);
@@ -7058,8 +7640,14 @@ var require_bootstrap = __commonJS({
7058
7640
  const knex = strapi2.db.connection;
7059
7641
  const tableName = "magic_sessions";
7060
7642
  const definitions = [
7061
- { column: "token_hash", name: "idx_magic_sessions_token_hash" },
7062
- { column: "refresh_token_hash", name: "idx_magic_sessions_refresh_hash" }
7643
+ { columns: ["token_hash", "is_active"], name: "idx_magic_sessions_token_hash" },
7644
+ { columns: ["refresh_token_hash", "is_active"], name: "idx_magic_sessions_refresh_hash" },
7645
+ { columns: ["login_time", "id"], name: "idx_magic_sessions_login_time" },
7646
+ { columns: ["last_active", "id"], name: "idx_magic_sessions_last_active" },
7647
+ { columns: ["is_active", "last_active"], name: "idx_magic_sessions_active_last" },
7648
+ { columns: ["is_active", "login_time"], name: "idx_magic_sessions_active_login" },
7649
+ { columns: ["is_active", "termination_reason"], name: "idx_magic_sessions_active_reason" },
7650
+ { columns: ["native_session_id"], name: "idx_magic_sessions_native_id" }
7063
7651
  ];
7064
7652
  if (!await knex.schema.hasTable(tableName)) return;
7065
7653
  const dialect = strapi2.db.dialect.client;
@@ -7075,11 +7663,11 @@ var require_bootstrap = __commonJS({
7075
7663
  log.debug(`[INDEX] ${definition.name} already exists`);
7076
7664
  continue;
7077
7665
  }
7078
- await knex.raw("CREATE INDEX IF NOT EXISTS ?? ON ?? (??, ??)", [
7666
+ const placeholders = definition.columns.map(() => "??").join(", ");
7667
+ await knex.raw(`CREATE INDEX IF NOT EXISTS ?? ON ?? (${placeholders})`, [
7079
7668
  definition.name,
7080
7669
  tableName,
7081
- definition.column,
7082
- "is_active"
7670
+ ...definition.columns
7083
7671
  ]);
7084
7672
  log.info(`[INDEX] Created ${definition.name}`);
7085
7673
  continue;
@@ -7097,7 +7685,7 @@ var require_bootstrap = __commonJS({
7097
7685
  continue;
7098
7686
  }
7099
7687
  await knex.schema.alterTable(tableName, (table) => {
7100
- table.index([definition.column, "is_active"], definition.name);
7688
+ table.index(definition.columns, definition.name);
7101
7689
  });
7102
7690
  log.info(`[INDEX] Created ${definition.name}`);
7103
7691
  }
@@ -7433,6 +8021,16 @@ var require_destroy = __commonJS({
7433
8021
  }
7434
8022
  strapi2.sessionManagerIntervals = {};
7435
8023
  }
8024
+ if (Array.isArray(strapi2.sessionManagerUnsubscribers)) {
8025
+ for (const unsubscribe of strapi2.sessionManagerUnsubscribers) {
8026
+ try {
8027
+ if (typeof unsubscribe === "function") unsubscribe();
8028
+ } catch (err) {
8029
+ log.warn("Failed to remove a database subscriber:", err?.name || "Error");
8030
+ }
8031
+ }
8032
+ strapi2.sessionManagerUnsubscribers = [];
8033
+ }
7436
8034
  log.info("[SUCCESS] Plugin cleanup completed");
7437
8035
  };
7438
8036
  }
@@ -7820,6 +8418,12 @@ var require_admin = __commonJS({
7820
8418
  config: { actions: [PLUGIN_ACCESS_ACTION] }
7821
8419
  }
7822
8420
  ];
8421
+ var adminReadRateLimit = () => [
8422
+ {
8423
+ name: "plugin::magic-sessionmanager.rate-limit",
8424
+ config: { profile: "read", max: 120, window: 6e4 }
8425
+ }
8426
+ ];
7823
8427
  var isDevEnvironment = (() => {
7824
8428
  const env = (process.env.NODE_ENV || "development").toLowerCase();
7825
8429
  return env !== "production" && env !== "staging";
@@ -7832,7 +8436,8 @@ var require_admin = __commonJS({
7832
8436
  handler: "session.getAllSessionsAdmin",
7833
8437
  config: {
7834
8438
  policies: adminPolicy(),
7835
- description: "Get all sessions - active and inactive (admin)"
8439
+ middlewares: adminReadRateLimit(),
8440
+ description: "List sessions (admin); paginated with page/pageSize, filters and sort"
7836
8441
  }
7837
8442
  },
7838
8443
  {
@@ -7841,7 +8446,63 @@ var require_admin = __commonJS({
7841
8446
  handler: "session.getActiveSessions",
7842
8447
  config: {
7843
8448
  policies: adminPolicy(),
7844
- description: "Get only active sessions (admin)"
8449
+ middlewares: adminReadRateLimit(),
8450
+ description: "Get only active sessions (admin); paginated with page/pageSize"
8451
+ }
8452
+ },
8453
+ {
8454
+ method: "GET",
8455
+ path: "/sessions/stats",
8456
+ handler: "session.getSessionStatsAdmin",
8457
+ config: {
8458
+ policies: adminPolicy(),
8459
+ middlewares: adminReadRateLimit(),
8460
+ description: "Get count-only session statistics (admin)"
8461
+ }
8462
+ },
8463
+ {
8464
+ method: "GET",
8465
+ path: "/sessions/native-only/summary",
8466
+ handler: "session.getNativeOnlySummaryAdmin",
8467
+ config: {
8468
+ policies: adminPolicy(),
8469
+ middlewares: adminReadRateLimit(),
8470
+ description: "Get count-only diagnostics of untracked Strapi sessions (admin)"
8471
+ }
8472
+ },
8473
+ {
8474
+ method: "POST",
8475
+ path: "/sessions/native-only/end",
8476
+ handler: "session.endNativeOnlySessionsAdmin",
8477
+ config: {
8478
+ policies: adminPolicy(),
8479
+ middlewares: [
8480
+ {
8481
+ name: "plugin::magic-sessionmanager.rate-limit",
8482
+ config: { profile: "write", max: 5, window: 6e4 }
8483
+ }
8484
+ ],
8485
+ description: "End untracked Users & Permissions sessions, bounded per request (admin)"
8486
+ }
8487
+ },
8488
+ {
8489
+ method: "GET",
8490
+ path: "/sessions/analytics",
8491
+ handler: "session.getSessionAnalyticsAdmin",
8492
+ config: {
8493
+ policies: adminPolicy(),
8494
+ middlewares: adminReadRateLimit(),
8495
+ description: "Get count-only analytics over all sessions (admin)"
8496
+ }
8497
+ },
8498
+ {
8499
+ method: "GET",
8500
+ path: "/sessions/export",
8501
+ handler: "session.exportSessionsAdmin",
8502
+ config: {
8503
+ policies: adminPolicy(),
8504
+ middlewares: adminReadRateLimit(),
8505
+ description: "Get one export batch of sessions with a keyset cursor (admin)"
7845
8506
  }
7846
8507
  },
7847
8508
  {
@@ -7904,6 +8565,7 @@ var require_admin = __commonJS({
7904
8565
  handler: "session.getUserStatsAdmin",
7905
8566
  config: {
7906
8567
  policies: adminPolicy(),
8568
+ middlewares: adminReadRateLimit(),
7907
8569
  description: "Get aggregate end-user counts only (admin)"
7908
8570
  }
7909
8571
  },
@@ -8321,6 +8983,529 @@ var require_http_errors = __commonJS({
8321
8983
  }
8322
8984
  });
8323
8985
 
8986
+ // server/src/utils/session-list-query.js
8987
+ var require_session_list_query = __commonJS({
8988
+ "server/src/utils/session-list-query.js"(exports, module) {
8989
+ "use strict";
8990
+ var { z } = __require("@strapi/utils");
8991
+ var SESSION_STATUS_FILTERS = Object.freeze(["all", "open", "active", "idle", "ended"]);
8992
+ var RECORDED_END_REASONS = Object.freeze(["logout", "idle", "expired", "manual", "blocked"]);
8993
+ var END_REASON_FILTERS = Object.freeze(["all", ...RECORDED_END_REASONS, "unrecorded"]);
8994
+ var SORT_ORDERS = Object.freeze({
8995
+ "loginTime:desc": [{ loginTime: "desc" }, { id: "desc" }],
8996
+ "loginTime:asc": [{ loginTime: "asc" }, { id: "asc" }],
8997
+ "lastActive:desc": [{ lastActive: "desc" }, { id: "desc" }],
8998
+ "lastActive:asc": [{ lastActive: "asc" }, { id: "asc" }]
8999
+ });
9000
+ var SORT_KEYS = Object.freeze(Object.keys(SORT_ORDERS));
9001
+ var MAX_PAGE_SIZE = 100;
9002
+ var MAX_SEARCH_LENGTH = 100;
9003
+ var MAX_LIST_OFFSET = 5e4;
9004
+ var MAX_EXPORT_BATCH = 1e3;
9005
+ var MAX_EXPORT_ROWS = 5e4;
9006
+ var LIST_FIELDS = Object.freeze([
9007
+ "id",
9008
+ "documentId",
9009
+ "sessionId",
9010
+ "nativeSessionId",
9011
+ "ipAddress",
9012
+ "userAgent",
9013
+ "loginTime",
9014
+ "logoutTime",
9015
+ "lastActive",
9016
+ "isActive",
9017
+ "terminatedManually",
9018
+ "terminationReason",
9019
+ "geoLocation",
9020
+ "securityScore",
9021
+ "deviceType",
9022
+ "browserName",
9023
+ "osName",
9024
+ "createdAt",
9025
+ "updatedAt"
9026
+ ]);
9027
+ var LIST_USER_FIELDS = Object.freeze(["documentId", "email", "username"]);
9028
+ var searchText = z.string().trim().max(MAX_SEARCH_LENGTH, `search must be at most ${MAX_SEARCH_LENGTH} characters`);
9029
+ var filterShape = {
9030
+ status: z.enum(SESSION_STATUS_FILTERS).default("all"),
9031
+ reason: z.enum(END_REASON_FILTERS).default("all"),
9032
+ search: searchText.default("")
9033
+ };
9034
+ var listQuerySchema = z.strictObject({
9035
+ page: z.coerce.number().int().min(1).max(1e6).default(1),
9036
+ pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(25),
9037
+ sort: z.enum(SORT_KEYS).default("loginTime:desc"),
9038
+ ...filterShape
9039
+ }).refine((query) => (query.page - 1) * query.pageSize < MAX_LIST_OFFSET, {
9040
+ message: `Pages past the first ${MAX_LIST_OFFSET} sessions are not available. Narrow the filter or use the export.`,
9041
+ path: ["page"]
9042
+ });
9043
+ var exportQuerySchema = z.strictObject({
9044
+ limit: z.coerce.number().int().min(1).max(MAX_EXPORT_BATCH).default(MAX_EXPORT_BATCH),
9045
+ cursor: z.string().max(200).optional(),
9046
+ ...filterShape
9047
+ });
9048
+ var statsQuerySchema = z.strictObject({});
9049
+ function isPaginatedListQuery(query) {
9050
+ return Boolean(
9051
+ query && (Object.prototype.hasOwnProperty.call(query, "page") || Object.prototype.hasOwnProperty.call(query, "pageSize"))
9052
+ );
9053
+ }
9054
+ function parseQuery(schema, input) {
9055
+ const result = schema.safeParse(input ?? {});
9056
+ if (result.success) return { ok: true, value: result.data };
9057
+ return {
9058
+ ok: false,
9059
+ errors: result.error.issues.map((issue) => ({
9060
+ path: issue.path.join("."),
9061
+ message: issue.message
9062
+ }))
9063
+ };
9064
+ }
9065
+ function usedSince(cutoff) {
9066
+ return {
9067
+ $or: [
9068
+ { lastActive: { $gt: cutoff } },
9069
+ { $and: [{ lastActive: { $null: true } }, { loginTime: { $gt: cutoff } }] }
9070
+ ]
9071
+ };
9072
+ }
9073
+ function notUsedSince(cutoff) {
9074
+ return {
9075
+ $or: [
9076
+ { lastActive: { $lte: cutoff } },
9077
+ { $and: [{ lastActive: { $null: true } }, { loginTime: { $lte: cutoff } }] }
9078
+ ]
9079
+ };
9080
+ }
9081
+ function buildSessionWhere({ status = "all", reason = "all", search = "" } = {}, { cutoff }) {
9082
+ const conditions = [];
9083
+ if (status === "open") conditions.push({ isActive: true });
9084
+ if (status === "active") conditions.push({ isActive: true }, usedSince(cutoff));
9085
+ if (status === "idle") conditions.push({ isActive: true }, notUsedSince(cutoff));
9086
+ if (status === "ended") {
9087
+ conditions.push({ isActive: false });
9088
+ if (reason === "unrecorded") {
9089
+ conditions.push({
9090
+ $or: [
9091
+ { terminationReason: { $null: true } },
9092
+ { terminationReason: { $notIn: [...RECORDED_END_REASONS] } }
9093
+ ]
9094
+ });
9095
+ } else if (RECORDED_END_REASONS.includes(reason)) {
9096
+ conditions.push({ terminationReason: reason });
9097
+ }
9098
+ }
9099
+ if (search) {
9100
+ conditions.push({
9101
+ $or: [
9102
+ { user: { email: { $containsi: search } } },
9103
+ { user: { username: { $containsi: search } } },
9104
+ { ipAddress: { $containsi: search } },
9105
+ { browserName: { $containsi: search } },
9106
+ { osName: { $containsi: search } },
9107
+ { deviceType: { $containsi: search } }
9108
+ ]
9109
+ });
9110
+ }
9111
+ return conditions.length ? { $and: conditions } : {};
9112
+ }
9113
+ function encodeExportCursor(row) {
9114
+ const time = row.loginTime ? new Date(row.loginTime).toISOString() : null;
9115
+ return Buffer.from(JSON.stringify([time, Number(row.id)])).toString("base64url");
9116
+ }
9117
+ function decodeExportCursor(cursor) {
9118
+ if (cursor === void 0 || cursor === "") return null;
9119
+ if (!/^[A-Za-z0-9_-]+$/.test(cursor)) return false;
9120
+ try {
9121
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
9122
+ if (!Array.isArray(value) || value.length !== 2) return false;
9123
+ const [time, id] = value;
9124
+ if (!Number.isSafeInteger(id) || id < 1) return false;
9125
+ if (time === null) return { loginTime: null, id };
9126
+ if (typeof time !== "string" || Number.isNaN(Date.parse(time))) return false;
9127
+ return { loginTime: new Date(time), id };
9128
+ } catch {
9129
+ return false;
9130
+ }
9131
+ }
9132
+ function afterExportCursor(cursor) {
9133
+ if (cursor.loginTime === null) return { id: { $lt: cursor.id } };
9134
+ return {
9135
+ $or: [
9136
+ { loginTime: { $lt: cursor.loginTime } },
9137
+ { $and: [{ loginTime: cursor.loginTime }, { id: { $lt: cursor.id } }] }
9138
+ ]
9139
+ };
9140
+ }
9141
+ module.exports = {
9142
+ SESSION_STATUS_FILTERS,
9143
+ RECORDED_END_REASONS,
9144
+ END_REASON_FILTERS,
9145
+ SORT_ORDERS,
9146
+ SORT_KEYS,
9147
+ MAX_PAGE_SIZE,
9148
+ MAX_SEARCH_LENGTH,
9149
+ MAX_LIST_OFFSET,
9150
+ MAX_EXPORT_BATCH,
9151
+ MAX_EXPORT_ROWS,
9152
+ LIST_FIELDS,
9153
+ LIST_USER_FIELDS,
9154
+ listQuerySchema,
9155
+ exportQuerySchema,
9156
+ statsQuerySchema,
9157
+ isPaginatedListQuery,
9158
+ parseQuery,
9159
+ buildSessionWhere,
9160
+ encodeExportCursor,
9161
+ decodeExportCursor,
9162
+ afterExportCursor
9163
+ };
9164
+ }
9165
+ });
9166
+
9167
+ // server/src/utils/session-list.js
9168
+ var require_session_list = __commonJS({
9169
+ "server/src/utils/session-list.js"(exports, module) {
9170
+ "use strict";
9171
+ var { enhanceSessions } = require_enhance_session();
9172
+ var { getNativeSessionManager } = require_native_session_manager();
9173
+ var {
9174
+ canInspectNativeSessions,
9175
+ countNativeOnly,
9176
+ getNativeTrackingSince
9177
+ } = require_native_only_insight();
9178
+ var {
9179
+ LIST_FIELDS,
9180
+ LIST_USER_FIELDS,
9181
+ MAX_EXPORT_BATCH,
9182
+ SORT_ORDERS,
9183
+ buildSessionWhere,
9184
+ afterExportCursor,
9185
+ encodeExportCursor
9186
+ } = require_session_list_query();
9187
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
9188
+ var NATIVE_SESSION_UID = "admin::session";
9189
+ var NATIVE_ORIGIN = "users-permissions";
9190
+ var NATIVE_CHECK_CONCURRENCY = 8;
9191
+ var STATS_CACHE_MS = 5e3;
9192
+ var statsCache = /* @__PURE__ */ new WeakMap();
9193
+ function clearSessionStatsCache() {
9194
+ statsCache = /* @__PURE__ */ new WeakMap();
9195
+ }
9196
+ function cacheFor(strapi2) {
9197
+ let map = statsCache.get(strapi2);
9198
+ if (!map) {
9199
+ map = /* @__PURE__ */ new Map();
9200
+ statsCache.set(strapi2, map);
9201
+ }
9202
+ return map;
9203
+ }
9204
+ function inactivityCutoff(inactivityTimeout, now = Date.now()) {
9205
+ return new Date(now - inactivityTimeout);
9206
+ }
9207
+ function hasNativeSessionTable(strapi2) {
9208
+ return Boolean(strapi2?.contentTypes?.[NATIVE_SESSION_UID]);
9209
+ }
9210
+ async function findActiveNativeIds(strapi2, nativeManager, ids) {
9211
+ const unique = [...new Set(ids.filter((id) => typeof id === "string" && id))];
9212
+ if (unique.length === 0) return /* @__PURE__ */ new Set();
9213
+ if (hasNativeSessionTable(strapi2)) {
9214
+ const rows = await strapi2.db.query(NATIVE_SESSION_UID).findMany({
9215
+ select: ["sessionId"],
9216
+ where: {
9217
+ sessionId: { $in: unique },
9218
+ origin: NATIVE_ORIGIN,
9219
+ status: "active",
9220
+ expiresAt: { $gt: /* @__PURE__ */ new Date() }
9221
+ }
9222
+ });
9223
+ return new Set((Array.isArray(rows) ? rows : []).map((row) => String(row.sessionId)));
9224
+ }
9225
+ const active = /* @__PURE__ */ new Set();
9226
+ let next = 0;
9227
+ const worker = async () => {
9228
+ while (next < unique.length) {
9229
+ const id = unique[next++];
9230
+ if (await nativeManager.isSessionActive(id)) active.add(id);
9231
+ }
9232
+ };
9233
+ await Promise.all(
9234
+ Array.from({ length: Math.min(NATIVE_CHECK_CONCURRENCY, unique.length) }, worker)
9235
+ );
9236
+ return active;
9237
+ }
9238
+ async function reconcileNativeRows(strapi2, rows) {
9239
+ const nativeManager = getNativeSessionManager(strapi2);
9240
+ if (!nativeManager) return rows;
9241
+ const ids = rows.filter((row) => row.isActive && row.nativeSessionId).map((row) => String(row.nativeSessionId));
9242
+ if (ids.length === 0) return rows;
9243
+ const active = await findActiveNativeIds(strapi2, nativeManager, ids);
9244
+ return rows.map(
9245
+ (row) => row.isActive && row.nativeSessionId && !active.has(String(row.nativeSessionId)) ? { ...row, isActive: false } : row
9246
+ );
9247
+ }
9248
+ async function countNativeOnlySessions(strapi2) {
9249
+ const { total } = await countNativeOnly(strapi2);
9250
+ return total;
9251
+ }
9252
+ async function countNativeOnlySplit(strapi2) {
9253
+ if (!canInspectNativeSessions(strapi2)) return { total: 0, afterTracking: null };
9254
+ const trackingSince = await getNativeTrackingSince(strapi2);
9255
+ return countNativeOnly(strapi2, { trackingSince });
9256
+ }
9257
+ async function countUsersOnline(strapi2, cutoff) {
9258
+ const meta = strapi2.db.metadata.get(SESSION_UID);
9259
+ const userAttribute = meta.attributes.user;
9260
+ const joinTable = userAttribute?.joinTable;
9261
+ const column = (attribute) => meta.attributes[attribute]?.columnName || attribute;
9262
+ const knex = strapi2.db.connection;
9263
+ const table = meta.tableName;
9264
+ if (joinTable?.name && joinTable.joinColumn?.name && joinTable.inverseJoinColumn?.name) {
9265
+ const link = joinTable.name;
9266
+ const lastActive = `${table}.${column("lastActive")}`;
9267
+ const loginTime = `${table}.${column("loginTime")}`;
9268
+ const result = await knex(table).join(link, `${link}.${joinTable.joinColumn.name}`, `${table}.id`).where(`${table}.${column("isActive")}`, true).andWhere((qb) => {
9269
+ qb.where(lastActive, ">", cutoff).orWhere((inner) => {
9270
+ inner.whereNull(lastActive).andWhere(loginTime, ">", cutoff);
9271
+ });
9272
+ }).countDistinct({ count: `${link}.${joinTable.inverseJoinColumn.name}` }).first();
9273
+ return Number(result?.count ?? 0);
9274
+ }
9275
+ const seen = /* @__PURE__ */ new Set();
9276
+ const where = buildSessionWhere({ status: "active" }, { cutoff });
9277
+ for (let offset = 0; ; offset += MAX_EXPORT_BATCH) {
9278
+ const rows = await strapi2.db.query(SESSION_UID).findMany({
9279
+ where,
9280
+ select: ["id"],
9281
+ populate: { user: { select: ["id"] } },
9282
+ orderBy: [{ id: "asc" }],
9283
+ offset,
9284
+ limit: MAX_EXPORT_BATCH
9285
+ });
9286
+ for (const row of rows) if (row.user?.id) seen.add(row.user.id);
9287
+ if (rows.length < MAX_EXPORT_BATCH) break;
9288
+ }
9289
+ return seen.size;
9290
+ }
9291
+ async function listSessionPage(strapi2, query, options) {
9292
+ const cutoff = inactivityCutoff(options.inactivityTimeout);
9293
+ const where = buildSessionWhere(query, { cutoff });
9294
+ const sessions = strapi2.db.query(SESSION_UID);
9295
+ const offset = (query.page - 1) * query.pageSize;
9296
+ const [total, rows] = await Promise.all([
9297
+ sessions.count({ where }),
9298
+ sessions.findMany({
9299
+ where,
9300
+ select: [...LIST_FIELDS],
9301
+ populate: { user: { select: [...LIST_USER_FIELDS] } },
9302
+ orderBy: SORT_ORDERS[query.sort] || SORT_ORDERS["loginTime:desc"],
9303
+ offset,
9304
+ limit: query.pageSize
9305
+ })
9306
+ ]);
9307
+ const reconciled = await reconcileNativeRows(strapi2, Array.isArray(rows) ? rows : []);
9308
+ const enhanced = await enhanceSessions(
9309
+ reconciled,
9310
+ {
9311
+ inactivityTimeout: options.inactivityTimeout,
9312
+ geolocationService: options.geolocationService || null,
9313
+ strapi: strapi2
9314
+ },
9315
+ Math.min(20, query.pageSize)
9316
+ );
9317
+ const count = Number(total) || 0;
9318
+ return {
9319
+ rows: enhanced,
9320
+ pagination: {
9321
+ page: query.page,
9322
+ pageSize: query.pageSize,
9323
+ total: count,
9324
+ pageCount: Math.max(1, Math.ceil(count / query.pageSize))
9325
+ }
9326
+ };
9327
+ }
9328
+ async function getSessionStats(strapi2, { inactivityTimeout }) {
9329
+ const key = String(inactivityTimeout);
9330
+ const cache = cacheFor(strapi2);
9331
+ const cached = cache.get(key);
9332
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
9333
+ const cutoff = inactivityCutoff(inactivityTimeout);
9334
+ const sessions = strapi2.db.query(SESSION_UID);
9335
+ const count = (filters) => sessions.count({ where: buildSessionWhere(filters, { cutoff }) });
9336
+ const [total, open, active, loggedOut, timedOut, usersOnline, nativeOnly] = await Promise.all([
9337
+ count({}),
9338
+ count({ status: "open" }),
9339
+ count({ status: "active" }),
9340
+ count({ status: "ended", reason: "logout" }),
9341
+ count({ status: "ended", reason: "idle" }),
9342
+ countUsersOnline(strapi2, cutoff),
9343
+ countNativeOnlySplit(strapi2)
9344
+ ]);
9345
+ const ended = Math.max(0, Number(total) - Number(open));
9346
+ const value = {
9347
+ total: Number(total),
9348
+ open: Number(open),
9349
+ active: Number(active),
9350
+ idle: Math.max(0, Number(open) - Number(active)),
9351
+ ended,
9352
+ loggedOut: Number(loggedOut),
9353
+ timedOut: Number(timedOut),
9354
+ otherReasons: Math.max(0, ended - Number(loggedOut) - Number(timedOut)),
9355
+ usersOnline: Number(usersOnline),
9356
+ nativeOnly: nativeOnly.total,
9357
+ nativeOnlyAfterTracking: nativeOnly.afterTracking
9358
+ };
9359
+ cache.set(key, { value, expiresAt: Date.now() + STATS_CACHE_MS });
9360
+ if (cache.size > 20) cache.delete(cache.keys().next().value);
9361
+ return value;
9362
+ }
9363
+ var ANALYTICS_CACHE_MS = 3e4;
9364
+ var MAX_GROUPS = 200;
9365
+ async function countByColumn(strapi2, attribute) {
9366
+ const meta = strapi2.db.metadata.get(SESSION_UID);
9367
+ const column = meta.attributes[attribute]?.columnName || attribute;
9368
+ const rows = await strapi2.db.connection(meta.tableName).select({ value: column }).count({ count: "*" }).groupBy(column).orderBy("count", "desc").limit(MAX_GROUPS);
9369
+ return rows.map((row) => ({ value: row.value ?? null, count: Number(row.count) || 0 }));
9370
+ }
9371
+ async function averageSessionMinutes(strapi2, now) {
9372
+ const meta = strapi2.db.metadata.get(SESSION_UID);
9373
+ const col = (attribute) => meta.attributes[attribute]?.columnName || attribute;
9374
+ const knex = strapi2.db.connection;
9375
+ const client = strapi2.db.dialect?.client || "";
9376
+ const end = `CASE WHEN ?? THEN COALESCE(??, ?) ELSE COALESCE(??, ??) END`;
9377
+ const endBindings = [
9378
+ col("isActive"),
9379
+ col("lastActive"),
9380
+ now,
9381
+ col("logoutTime"),
9382
+ col("lastActive")
9383
+ ];
9384
+ if (client === "postgres") {
9385
+ const row = await knex(meta.tableName).select(
9386
+ knex.raw(`AVG(GREATEST(0, FLOOR(EXTRACT(EPOCH FROM ((${end}) - ??)) / 60))) AS avg`, [
9387
+ ...endBindings,
9388
+ col("loginTime")
9389
+ ])
9390
+ ).first();
9391
+ return Math.floor(Number(row?.avg) || 0);
9392
+ }
9393
+ if (client === "mysql" || client === "mysql2") {
9394
+ const row = await knex(meta.tableName).select(
9395
+ knex.raw(`AVG(GREATEST(0, FLOOR(TIMESTAMPDIFF(SECOND, ??, (${end})) / 60))) AS avg`, [
9396
+ col("loginTime"),
9397
+ ...endBindings
9398
+ ])
9399
+ ).first();
9400
+ return Math.floor(Number(row?.avg) || 0);
9401
+ }
9402
+ let sum = 0;
9403
+ let count = 0;
9404
+ let lastId = 0;
9405
+ const nowMs = now.getTime();
9406
+ for (; ; ) {
9407
+ const rows = await strapi2.db.query(SESSION_UID).findMany({
9408
+ select: ["id", "loginTime", "lastActive", "logoutTime", "isActive"],
9409
+ where: { id: { $gt: lastId } },
9410
+ orderBy: [{ id: "asc" }],
9411
+ limit: 5e3
9412
+ });
9413
+ for (const row of rows) {
9414
+ const start = Date.parse(row.loginTime);
9415
+ if (!Number.isFinite(start)) continue;
9416
+ const lastActive = row.lastActive ? Date.parse(row.lastActive) : Number.NaN;
9417
+ const logout = row.logoutTime ? Date.parse(row.logoutTime) : Number.NaN;
9418
+ let stop;
9419
+ if (row.isActive) stop = Number.isFinite(lastActive) ? lastActive : nowMs;
9420
+ else stop = Number.isFinite(logout) ? logout : lastActive;
9421
+ if (!Number.isFinite(stop)) continue;
9422
+ sum += Math.max(0, Math.floor((stop - start) / 6e4));
9423
+ count += 1;
9424
+ }
9425
+ if (rows.length < 5e3) break;
9426
+ lastId = rows[rows.length - 1].id;
9427
+ }
9428
+ return count > 0 ? Math.floor(sum / count) : 0;
9429
+ }
9430
+ async function countUsersWithSessions(strapi2) {
9431
+ const meta = strapi2.db.metadata.get(SESSION_UID);
9432
+ const joinTable = meta.attributes.user?.joinTable;
9433
+ if (!joinTable?.name || !joinTable.inverseJoinColumn?.name) return 0;
9434
+ const row = await strapi2.db.connection(joinTable.name).countDistinct({ count: joinTable.inverseJoinColumn.name }).first();
9435
+ return Number(row?.count ?? 0);
9436
+ }
9437
+ async function getSessionAnalytics(strapi2, { inactivityTimeout }) {
9438
+ const key = `analytics:${inactivityTimeout}`;
9439
+ const cache = cacheFor(strapi2);
9440
+ const cached = cache.get(key);
9441
+ if (cached && cached.expiresAt > Date.now()) return cached.value;
9442
+ const now = /* @__PURE__ */ new Date();
9443
+ const sessions = strapi2.db.query(SESSION_UID);
9444
+ const since = (ms) => sessions.count({ where: { loginTime: { $gt: new Date(now - ms) } } });
9445
+ const [stats, signIns24h, signIns7d, devices, browsers, uniqueUsers, avgSessionDuration] = await Promise.all([
9446
+ getSessionStats(strapi2, { inactivityTimeout }),
9447
+ since(24 * 60 * 60 * 1e3),
9448
+ since(7 * 24 * 60 * 60 * 1e3),
9449
+ countByColumn(strapi2, "deviceType"),
9450
+ countByColumn(strapi2, "browserName"),
9451
+ countUsersWithSessions(strapi2),
9452
+ averageSessionMinutes(strapi2, now)
9453
+ ]);
9454
+ const value = {
9455
+ totalSessions: stats.total,
9456
+ activeSessions: stats.active,
9457
+ idleSessions: stats.idle,
9458
+ endedSessions: stats.ended,
9459
+ signInsLast24Hours: Number(signIns24h),
9460
+ signInsLast7Days: Number(signIns7d),
9461
+ devices,
9462
+ browsers,
9463
+ uniqueUsers,
9464
+ avgSessionDuration
9465
+ };
9466
+ cache.set(key, { value, expiresAt: Date.now() + ANALYTICS_CACHE_MS });
9467
+ return value;
9468
+ }
9469
+ async function exportSessionBatch(strapi2, query, cursor, { inactivityTimeout }) {
9470
+ const cutoff = inactivityCutoff(inactivityTimeout);
9471
+ const base = buildSessionWhere(query, { cutoff });
9472
+ const where = cursor ? { $and: [...base.$and ? base.$and : [], afterExportCursor(cursor)] } : base;
9473
+ const rows = await strapi2.db.query(SESSION_UID).findMany({
9474
+ where,
9475
+ select: [...LIST_FIELDS],
9476
+ populate: { user: { select: [...LIST_USER_FIELDS] } },
9477
+ orderBy: SORT_ORDERS["loginTime:desc"],
9478
+ limit: query.limit
9479
+ });
9480
+ const list = Array.isArray(rows) ? rows : [];
9481
+ const reconciled = await reconcileNativeRows(strapi2, list);
9482
+ const enhanced = await enhanceSessions(
9483
+ reconciled,
9484
+ { inactivityTimeout, geolocationService: null, strapi: strapi2 },
9485
+ 0
9486
+ );
9487
+ const last = list[list.length - 1];
9488
+ return {
9489
+ rows: enhanced,
9490
+ nextCursor: list.length === query.limit && last ? encodeExportCursor(last) : null
9491
+ };
9492
+ }
9493
+ module.exports = {
9494
+ STATS_CACHE_MS,
9495
+ ANALYTICS_CACHE_MS,
9496
+ listSessionPage,
9497
+ getSessionStats,
9498
+ getSessionAnalytics,
9499
+ exportSessionBatch,
9500
+ countUsersOnline,
9501
+ countNativeOnlySessions,
9502
+ reconcileNativeRows,
9503
+ clearSessionStatsCache,
9504
+ inactivityCutoff
9505
+ };
9506
+ }
9507
+ });
9508
+
8324
9509
  // server/src/controllers/session.js
8325
9510
  var require_session = __commonJS({
8326
9511
  "server/src/controllers/session.js"(exports, module) {
@@ -8338,12 +9523,29 @@ var require_session = __commonJS({
8338
9523
  var { runWithCallerRevocation } = require_block_revocation_scope();
8339
9524
  var { sendServerError } = require_http_errors();
8340
9525
  var { getCoordinator } = require_coordination();
9526
+ var { clearSessionStatsCache } = require_session_list();
9527
+ var {
9528
+ getNativeOnlySummary,
9529
+ endNativeOnlySessions,
9530
+ END_MAX_ROWS
9531
+ } = require_native_only_insight();
9532
+ var { LockTimeoutError } = require_coordination();
9533
+ var {
9534
+ decodeExportCursor,
9535
+ exportQuerySchema,
9536
+ isPaginatedListQuery,
9537
+ listQuerySchema,
9538
+ parseQuery,
9539
+ statsQuerySchema
9540
+ } = require_session_list_query();
8341
9541
  var SESSION_UID = "plugin::magic-sessionmanager.session";
8342
9542
  var USER_UID = "plugin::users-permissions.user";
8343
9543
  var OWN_SESSIONS_LIMIT = 200;
8344
9544
  var NATIVE_SESSION_KEY_PREFIX = "native_";
8345
9545
  var JWT_MANAGEMENT_CONFIG = "plugin::users-permissions.jwtManagement";
8346
9546
  var LEGACY_JWT_MANAGEMENT = "legacy-support";
9547
+ var USER_STATS_CACHE_MS = 5e3;
9548
+ var userStatsCache = { owner: null, value: null, expiresAt: 0 };
8347
9549
  function createDisabledGeolocationResult(ipAddress) {
8348
9550
  return {
8349
9551
  ip: ipAddress,
@@ -8418,6 +9620,55 @@ var require_session = __commonJS({
8418
9620
  function getTruncationMeta(sessions) {
8419
9621
  return sessions?.truncated === true ? { truncated: true } : {};
8420
9622
  }
9623
+ async function listSessionsAdmin(ctx, { activeOnly }) {
9624
+ if (isPaginatedListQuery(ctx.query)) {
9625
+ const parsed = parseQuery(listQuerySchema, ctx.query);
9626
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
9627
+ const query = activeOnly ? { ...parsed.value, status: "active", reason: "all" } : parsed.value;
9628
+ try {
9629
+ const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9630
+ const page = await sessionService.listSessionPage(query);
9631
+ ctx.body = {
9632
+ data: toPublicSessions(page.rows, { admin: true }),
9633
+ meta: { pagination: page.pagination }
9634
+ };
9635
+ return void 0;
9636
+ } catch (err) {
9637
+ strapi.log.error("[magic-sessionmanager] listSessionPage failed:", err?.name || "Error");
9638
+ return ctx.internalServerError("Error fetching sessions");
9639
+ }
9640
+ }
9641
+ try {
9642
+ const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9643
+ if (activeOnly) {
9644
+ const sessions2 = await sessionService.getActiveSessions();
9645
+ ctx.body = {
9646
+ data: toPublicSessions(sessions2, { admin: true }),
9647
+ meta: { count: sessions2.length, ...getTruncationMeta(sessions2) }
9648
+ };
9649
+ return void 0;
9650
+ }
9651
+ const sessions = await sessionService.getAllSessions();
9652
+ ctx.body = {
9653
+ data: toPublicSessions(sessions, { admin: true }),
9654
+ meta: {
9655
+ count: sessions.length,
9656
+ active: sessions.filter((s) => s.isTrulyActive).length,
9657
+ inactive: sessions.filter((s) => !s.isTrulyActive).length,
9658
+ ...getTruncationMeta(sessions)
9659
+ }
9660
+ };
9661
+ return void 0;
9662
+ } catch (err) {
9663
+ strapi.log.error(
9664
+ `[magic-sessionmanager] ${activeOnly ? "getActiveSessions" : "getAllSessionsAdmin"} failed:`,
9665
+ err?.name || "Error"
9666
+ );
9667
+ return ctx.internalServerError(
9668
+ activeOnly ? "Error fetching active sessions" : "Error fetching sessions"
9669
+ );
9670
+ }
9671
+ }
8421
9672
  async function respondIfSessionCreationPending(ctx) {
8422
9673
  const settings = await getPluginSettings(strapi);
8423
9674
  const gracePeriodMs = getSessionCreationGraceMs(settings);
@@ -8448,13 +9699,19 @@ var require_session = __commonJS({
8448
9699
  */
8449
9700
  async getUserStatsAdmin(ctx) {
8450
9701
  try {
8451
- const [totalUsers, blockedUsers] = await Promise.all([
8452
- strapi.db.query(USER_UID).count(),
8453
- strapi.db.query(USER_UID).count({ where: { blocked: true } })
8454
- ]);
9702
+ if (userStatsCache.owner !== strapi || !userStatsCache.value || userStatsCache.expiresAt <= Date.now()) {
9703
+ userStatsCache.owner = null;
9704
+ const [totalUsers, blockedUsers] = await Promise.all([
9705
+ strapi.db.query(USER_UID).count(),
9706
+ strapi.db.query(USER_UID).count({ where: { blocked: true } })
9707
+ ]);
9708
+ userStatsCache.owner = strapi;
9709
+ userStatsCache.value = { totalUsers, blockedUsers };
9710
+ userStatsCache.expiresAt = Date.now() + USER_STATS_CACHE_MS;
9711
+ }
8455
9712
  return ctx.send({
8456
9713
  success: true,
8457
- data: { totalUsers, blockedUsers }
9714
+ data: { ...userStatsCache.value }
8458
9715
  });
8459
9716
  } catch (error) {
8460
9717
  strapi.log.error("[magic-sessionmanager] getUserStatsAdmin failed:", error?.name || "Error");
@@ -8462,42 +9719,174 @@ var require_session = __commonJS({
8462
9719
  }
8463
9720
  },
8464
9721
  /**
8465
- * Lists all sessions (active + inactive) for admin overviews.
9722
+ * Lists sessions for admin overviews.
9723
+ *
9724
+ * With `page` or `pageSize` the list is paginated in SQL and filtered by
9725
+ * `status`, `reason`, `search` and `sort` (whitelisted values only), with
9726
+ * exact totals. Without them the 4.x response (latest 1000 rows) is kept
9727
+ * for existing callers.
9728
+ *
8466
9729
  * @route GET /magic-sessionmanager/sessions
9730
+ * @param {object} ctx Koa context
9731
+ * @returns {Promise<void>}
8467
9732
  */
8468
9733
  async getAllSessionsAdmin(ctx) {
9734
+ return listSessionsAdmin(ctx, { activeOnly: false });
9735
+ },
9736
+ /**
9737
+ * Lists currently-active sessions only (paginated with `page`/`pageSize`,
9738
+ * see getAllSessionsAdmin).
9739
+ *
9740
+ * @route GET /magic-sessionmanager/sessions/active
9741
+ * @param {object} ctx Koa context
9742
+ * @returns {Promise<void>}
9743
+ */
9744
+ async getActiveSessions(ctx) {
9745
+ return listSessionsAdmin(ctx, { activeOnly: true });
9746
+ },
9747
+ /**
9748
+ * Count-only session statistics for the dashboard cards and the homepage
9749
+ * widget. No rows, no personal data.
9750
+ *
9751
+ * @route GET /magic-sessionmanager/sessions/stats
9752
+ * @param {object} ctx Koa context
9753
+ * @returns {Promise<void>}
9754
+ */
9755
+ async getSessionStatsAdmin(ctx) {
9756
+ const parsed = parseQuery(statsQuerySchema, ctx.query);
9757
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
8469
9758
  try {
8470
9759
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8471
- const sessions = await sessionService.getAllSessions();
8472
- ctx.body = {
8473
- data: toPublicSessions(sessions, { admin: true }),
8474
- meta: {
8475
- count: sessions.length,
8476
- active: sessions.filter((s) => s.isTrulyActive).length,
8477
- inactive: sessions.filter((s) => !s.isTrulyActive).length,
8478
- ...getTruncationMeta(sessions)
8479
- }
8480
- };
9760
+ const stats = await sessionService.getSessionStats();
9761
+ return ctx.send({ data: stats });
8481
9762
  } catch (err) {
8482
- strapi.log.error("[magic-sessionmanager] getAllSessionsAdmin failed:", err?.name || "Error");
8483
- return ctx.internalServerError("Error fetching sessions");
9763
+ strapi.log.error("[magic-sessionmanager] getSessionStatsAdmin failed:", err?.name || "Error");
9764
+ return ctx.internalServerError("Unable to load session statistics");
8484
9765
  }
8485
9766
  },
8486
9767
  /**
8487
- * Lists currently-active sessions only.
8488
- * @route GET /magic-sessionmanager/sessions/active
9768
+ * Count-only diagnostics of untracked Strapi sessions: Users & Permissions
9769
+ * sessions that Strapi still accepts (unexpired refresh tokens) but that
9770
+ * have no Magic session row. Splits them by creation before or after the
9771
+ * plugin started linking sessions, creation month, how Strapi created
9772
+ * them, device class and upcoming expiry. Read-only; no session IDs, user
9773
+ * data or IP addresses.
9774
+ *
9775
+ * @route GET /magic-sessionmanager/sessions/native-only/summary
9776
+ * @auth admin JWT or admin API token
9777
+ * @access plugin::magic-sessionmanager.access
9778
+ * @param {object} ctx Koa context; no query parameters are accepted.
9779
+ * @returns {Promise<void>} `{ data: summary }`, 400 on query parameters, 500 on a database error.
8489
9780
  */
8490
- async getActiveSessions(ctx) {
9781
+ async getNativeOnlySummaryAdmin(ctx) {
9782
+ const parsed = parseQuery(statsQuerySchema, ctx.query);
9783
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
9784
+ try {
9785
+ return ctx.send({ data: await getNativeOnlySummary(strapi) });
9786
+ } catch (err) {
9787
+ strapi.log.error(
9788
+ "[magic-sessionmanager] getNativeOnlySummaryAdmin failed:",
9789
+ err?.name || "Error"
9790
+ );
9791
+ return ctx.internalServerError("Unable to load the untracked session summary");
9792
+ }
9793
+ },
9794
+ /**
9795
+ * Ends untracked Users & Permissions sessions: deletes the Strapi session
9796
+ * rows that have no Magic session row, so their refresh tokens stop
9797
+ * working. Admin-panel sessions (origin `admin`) and linked sessions are
9798
+ * never touched. Bounded to `END_MAX_ROWS` rows per request; the response
9799
+ * says how many remain. Runs one at a time across instances.
9800
+ *
9801
+ * Requires a signed-in administrator (admin session strategy): an admin API
9802
+ * token cannot run this bulk sign-out.
9803
+ *
9804
+ * @route POST /magic-sessionmanager/sessions/native-only/end
9805
+ * @auth admin JWT (admin API tokens are refused)
9806
+ * @access plugin::magic-sessionmanager.access
9807
+ * @param {object} ctx Koa context; the body must be empty or `{}`.
9808
+ * @returns {Promise<void>} `{ data: { ended, remaining, limit } }`; 400, 403, 409 or 500.
9809
+ * @sideeffect Deletes rows from Strapi's `admin::session` table and writes an audit log line with counts only.
9810
+ */
9811
+ async endNativeOnlySessionsAdmin(ctx) {
9812
+ if (ctx.state?.auth?.strategy?.name !== "admin") {
9813
+ return ctx.forbidden("Only a signed-in administrator can end these sessions");
9814
+ }
9815
+ const body = ctx.request?.body;
9816
+ const emptyBody = body === void 0 || body === null || typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 0;
9817
+ if (!emptyBody) return ctx.badRequest("This endpoint takes no request body");
9818
+ try {
9819
+ const result = await getCoordinator(strapi).withLock(
9820
+ "native-only-end",
9821
+ () => endNativeOnlySessions(strapi)
9822
+ );
9823
+ clearSessionStatsCache();
9824
+ strapi.log.info(
9825
+ `[magic-sessionmanager] [AUDIT] Untracked Users & Permissions sessions ended by an administrator: ended=${result.ended} remaining=${result.remaining}`
9826
+ );
9827
+ return ctx.send({ data: { ...result, limit: END_MAX_ROWS } });
9828
+ } catch (err) {
9829
+ if (err instanceof LockTimeoutError || err?.name === "LockTimeoutError") {
9830
+ return ctx.conflict("Another clean-up is running. Try again in a moment.");
9831
+ }
9832
+ strapi.log.error(
9833
+ "[magic-sessionmanager] endNativeOnlySessionsAdmin failed:",
9834
+ err?.name || "Error"
9835
+ );
9836
+ return ctx.internalServerError("Unable to end the untracked sessions");
9837
+ }
9838
+ },
9839
+ /**
9840
+ * Aggregates for the Analytics page over every session: counts, grouped
9841
+ * counts per device type and browser, distinct users, average length. No
9842
+ * rows and no personal data.
9843
+ *
9844
+ * @route GET /magic-sessionmanager/sessions/analytics
9845
+ * @param {object} ctx Koa context
9846
+ * @returns {Promise<void>}
9847
+ */
9848
+ async getSessionAnalyticsAdmin(ctx) {
9849
+ const parsed = parseQuery(statsQuerySchema, ctx.query);
9850
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
8491
9851
  try {
8492
9852
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
8493
- const sessions = await sessionService.getActiveSessions();
8494
- ctx.body = {
8495
- data: toPublicSessions(sessions, { admin: true }),
8496
- meta: { count: sessions.length, ...getTruncationMeta(sessions) }
8497
- };
9853
+ return ctx.send({ data: await sessionService.getSessionAnalytics() });
9854
+ } catch (err) {
9855
+ strapi.log.error(
9856
+ "[magic-sessionmanager] getSessionAnalyticsAdmin failed:",
9857
+ err?.name || "Error"
9858
+ );
9859
+ return ctx.internalServerError("Unable to load session analytics");
9860
+ }
9861
+ },
9862
+ /**
9863
+ * One batch of the session export (newest first, keyset cursor). The admin
9864
+ * client follows `meta.nextCursor` until it is null or its row limit is
9865
+ * reached.
9866
+ *
9867
+ * @route GET /magic-sessionmanager/sessions/export
9868
+ * @param {object} ctx Koa context
9869
+ * @returns {Promise<void>}
9870
+ */
9871
+ async exportSessionsAdmin(ctx) {
9872
+ const parsed = parseQuery(exportQuerySchema, ctx.query);
9873
+ if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
9874
+ const cursor = decodeExportCursor(parsed.value.cursor);
9875
+ if (cursor === false) {
9876
+ return ctx.badRequest("Invalid query", {
9877
+ errors: [{ path: "cursor", message: "Invalid cursor" }]
9878
+ });
9879
+ }
9880
+ try {
9881
+ const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9882
+ const batch = await sessionService.exportSessionBatch(parsed.value, cursor);
9883
+ return ctx.send({
9884
+ data: toPublicSessions(batch.rows, { admin: true }),
9885
+ meta: { count: batch.rows.length, nextCursor: batch.nextCursor }
9886
+ });
8498
9887
  } catch (err) {
8499
- strapi.log.error("[magic-sessionmanager] getActiveSessions failed:", err?.name || "Error");
8500
- return ctx.internalServerError("Error fetching active sessions");
9888
+ strapi.log.error("[magic-sessionmanager] exportSessionsAdmin failed:", err?.name || "Error");
9889
+ return ctx.internalServerError("Unable to export sessions");
8501
9890
  }
8502
9891
  },
8503
9892
  /**
@@ -9020,6 +10409,7 @@ var require_session = __commonJS({
9020
10409
  * A missing target returns 404; existing native-only rows remain supported.
9021
10410
  */
9022
10411
  async terminateSingleSession(ctx) {
10412
+ clearSessionStatsCache();
9023
10413
  try {
9024
10414
  const { sessionId } = ctx.params;
9025
10415
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
@@ -9048,6 +10438,7 @@ var require_session = __commonJS({
9048
10438
  * Unknown numeric IDs and document IDs return 404 before revocation.
9049
10439
  */
9050
10440
  async terminateAllUserSessions(ctx) {
10441
+ clearSessionStatsCache();
9051
10442
  try {
9052
10443
  const { userId } = ctx.params;
9053
10444
  const numericId = /^\d+$/.test(userId) ? Number(userId) : null;
@@ -9130,6 +10521,7 @@ var require_session = __commonJS({
9130
10521
  * any unexpired JWT expires
9131
10522
  */
9132
10523
  async deleteSession(ctx) {
10524
+ clearSessionStatsCache();
9133
10525
  try {
9134
10526
  const { sessionId } = ctx.params;
9135
10527
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
@@ -9155,6 +10547,7 @@ var require_session = __commonJS({
9155
10547
  * could not be removed
9156
10548
  */
9157
10549
  async cleanInactiveSessions(ctx) {
10550
+ clearSessionStatsCache();
9158
10551
  try {
9159
10552
  const sessionService = strapi.plugin("magic-sessionmanager").service("session");
9160
10553
  const deletedCount = await sessionService.deleteInactiveSessions();
@@ -9201,6 +10594,8 @@ var require_session = __commonJS({
9201
10594
  * can leave the user blocked with partially active sessions.
9202
10595
  */
9203
10596
  async toggleUserBlock(ctx) {
10597
+ clearSessionStatsCache();
10598
+ userStatsCache.expiresAt = 0;
9204
10599
  try {
9205
10600
  const { userId } = ctx.params;
9206
10601
  const body = ctx.request?.body;
@@ -10342,6 +11737,12 @@ var require_session2 = __commonJS({
10342
11737
  persistAccessTokenRevocation
10343
11738
  } = require_session_revocation();
10344
11739
  var { getNativeSessionManager } = require_native_session_manager();
11740
+ var {
11741
+ exportSessionBatch,
11742
+ getSessionAnalytics: getSessionAnalyticsFromDb,
11743
+ getSessionStats: getSessionStatsFromDb,
11744
+ listSessionPage
11745
+ } = require_session_list();
10345
11746
  var {
10346
11747
  NATIVE_SESSION_PREFIX,
10347
11748
  mapNativeSessionToView,
@@ -11037,8 +12438,51 @@ var require_session2 = __commonJS({
11037
12438
  throw err;
11038
12439
  }
11039
12440
  },
12441
+ /**
12442
+ * One page of sessions with exact totals for the admin dashboard. Only
12443
+ * the rows on the page are enriched; filters and sort run in SQL.
12444
+ *
12445
+ * @param {{page: number, pageSize: number, status: string, reason: string, search: string, sort: string}} query Validated list query
12446
+ * @returns {Promise<{rows: object[], pagination: object}>}
12447
+ */
12448
+ async listSessionPage(query) {
12449
+ return listSessionPage(strapi2, query, await getEnhanceOpts());
12450
+ },
12451
+ /**
12452
+ * Count-only session statistics (cached a few seconds per process).
12453
+ *
12454
+ * @returns {Promise<object>}
12455
+ */
12456
+ async getSessionStats() {
12457
+ const { inactivityTimeout } = await getEnhanceOpts();
12458
+ return getSessionStatsFromDb(strapi2, { inactivityTimeout });
12459
+ },
12460
+ /**
12461
+ * Aggregates for the Analytics page over every session (cached 30 s
12462
+ * per process).
12463
+ *
12464
+ * @returns {Promise<object>}
12465
+ */
12466
+ async getSessionAnalytics() {
12467
+ const { inactivityTimeout } = await getEnhanceOpts();
12468
+ return getSessionAnalyticsFromDb(strapi2, { inactivityTimeout });
12469
+ },
12470
+ /**
12471
+ * One export batch (keyset cursor, newest first).
12472
+ *
12473
+ * @param {{limit: number, status: string, reason: string, search: string}} query Validated export query
12474
+ * @param {{loginTime: Date|null, id: number}|null} cursor Decoded cursor
12475
+ * @returns {Promise<{rows: object[], nextCursor: string|null}>}
12476
+ */
12477
+ async exportSessionBatch(query, cursor) {
12478
+ const { inactivityTimeout } = await getEnhanceOpts();
12479
+ return exportSessionBatch(strapi2, query, cursor, { inactivityTimeout });
12480
+ },
11040
12481
  /**
11041
12482
  * Get ALL sessions (active + inactive) with enhanced display fields.
12483
+ * Kept for callers of `GET /sessions` without paging parameters; capped
12484
+ * at the latest 1000 rows. The admin dashboard uses `listSessionPage`.
12485
+ *
11042
12486
  * @returns {Promise<Array>}
11043
12487
  */
11044
12488
  async getAllSessions() {