strapi-plugin-magic-sessionmanager 4.12.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 +37 -2
  2. package/README.md +53 -11
  3. package/dist/admin/{Analytics-lP0-RsVd.js → Analytics-BikQQx_J.js} +1 -1
  4. package/dist/admin/{Analytics-C_c24Uzq.mjs → Analytics-DIY51RI_.mjs} +1 -1
  5. package/dist/admin/{App-DCyNPn1k.mjs → App-B3vaybSO.mjs} +433 -13
  6. package/dist/admin/{App-miWDdmdX.js → App-BV1LM9Bp.js} +433 -13
  7. package/dist/admin/{OnlineUsersWidget-C6wlwENC.mjs → OnlineUsersWidget-T-2upsDd.mjs} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-C6b7e4jb.js → OnlineUsersWidget-fJogM1xl.js} +1 -1
  9. package/dist/admin/{Settings-D9zyn5xn.js → Settings-AyYka8wn.js} +1 -1
  10. package/dist/admin/{Settings-DssYw2W4.mjs → Settings-BpBlXyMY.mjs} +1 -1
  11. package/dist/admin/{de--yNl7MPl.mjs → de-BSCDuq1i.mjs} +38 -1
  12. package/dist/admin/{de-DjPEATFf.js → de-z0aHRwdw.js} +38 -1
  13. package/dist/admin/{en-5U7g51cH.mjs → en-B4Cuq9JN.mjs} +38 -1
  14. package/dist/admin/{en-BoO12UQw.js → en-BWPOiiMt.js} +38 -1
  15. package/dist/admin/{es-BLpEuycJ.js → es-CMskkUh-.js} +38 -1
  16. package/dist/admin/{es-BJR-zCXL.mjs → es-DBAmysKi.mjs} +38 -1
  17. package/dist/admin/{fr-CeeCYQCs.mjs → fr-BNGdtjEl.mjs} +38 -1
  18. package/dist/admin/{fr-BE828R9Q.js → fr-ClJ2BkrE.js} +38 -1
  19. package/dist/admin/{index-CfQOMZVX.js → index-DyE1rLW0.js} +22 -19
  20. package/dist/admin/{index-rbxJZcLv.mjs → index-mCVi1j7e.mjs} +22 -19
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +1 -1
  23. package/dist/admin/{pt-BWEFiuvo.js → pt-CRh_J7JS.js} +38 -1
  24. package/dist/admin/{pt-CorrU3yG.mjs → pt-Cl7TWsOV.mjs} +38 -1
  25. package/dist/server/index.js +721 -30
  26. package/dist/server/index.mjs +721 -30
  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,11 +2321,12 @@ 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) {
@@ -5922,6 +6341,8 @@ var require_bootstrap = __commonJS({
5922
6341
  } = require_coordination();
5923
6342
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
5924
6343
  var {
6344
+ normalizeApiPrefix,
6345
+ toCanonicalApiPath,
5925
6346
  classifyJwtIssuingRequest,
5926
6347
  isFailedLoginTrackedPath,
5927
6348
  isPasswordResetRequest,
@@ -5933,6 +6354,14 @@ var require_bootstrap = __commonJS({
5933
6354
  getOutgoingRefreshToken,
5934
6355
  stripAuthTokensFromResponse
5935
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();
5936
6365
  var SESSION_UID = "plugin::magic-sessionmanager.session";
5937
6366
  var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
5938
6367
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -5979,6 +6408,17 @@ var require_bootstrap = __commonJS({
5979
6408
  await ensureSessionLookupIndexes(strapi2, log);
5980
6409
  await registerSessionAwareAuthStrategy(strapi2);
5981
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
+ }
5982
6422
  const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
5983
6423
  if (!strapi2.sessionManagerIntervals) {
5984
6424
  strapi2.sessionManagerIntervals = {};
@@ -6110,7 +6550,7 @@ var require_bootstrap = __commonJS({
6110
6550
  }
6111
6551
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
6112
6552
  strapi2.server.use(async (ctx, next) => {
6113
- if (!shouldRunPreAuthGeoGuard(ctx.path, ctx.method)) {
6553
+ if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
6114
6554
  return next();
6115
6555
  }
6116
6556
  const settings = await getRequestSettings(strapi2, ctx);
@@ -6163,7 +6603,8 @@ var require_bootstrap = __commonJS({
6163
6603
  log.info("[SUCCESS] Pre-login geo guard mounted");
6164
6604
  }
6165
6605
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
6166
- 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)) {
6167
6608
  log.debug("[LOGOUT] Using the users-permissions logout route");
6168
6609
  return;
6169
6610
  }
@@ -6176,7 +6617,7 @@ var require_bootstrap = __commonJS({
6176
6617
  strapi2.server.routes([
6177
6618
  {
6178
6619
  method: "POST",
6179
- path: "/api/auth/logout",
6620
+ path: logoutPath,
6180
6621
  handler: async (ctx) => {
6181
6622
  try {
6182
6623
  const token = extractBearerToken(ctx);
@@ -6252,6 +6693,9 @@ var require_bootstrap = __commonJS({
6252
6693
  ]);
6253
6694
  log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
6254
6695
  }
6696
+ function apiPathOf(strapi2, ctx) {
6697
+ return toCanonicalApiPath(ctx.path, strapi2.config.get("api.rest.prefix", "/api"));
6698
+ }
6255
6699
  function hasRegisteredRoute(strapi2, method, path) {
6256
6700
  try {
6257
6701
  const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
@@ -6285,11 +6729,35 @@ var require_bootstrap = __commonJS({
6285
6729
  function usesNativeRefreshSessions(strapi2) {
6286
6730
  return strapi2.config.get("plugin::users-permissions.jwtManagement", "legacy-support") === "refresh";
6287
6731
  }
6288
- async function resolveNativeRefreshSession({ strapi: strapi2, nativeSessionManager, refreshToken, user }) {
6289
- if (!refreshToken) throw new Error("native auth response contains no refresh token");
6290
- const validation = await nativeSessionManager.validateRefreshToken(refreshToken);
6291
- if (!validation?.isValid || !validation.userId || !validation.sessionId) {
6292
- 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");
6293
6761
  }
6294
6762
  const userId = String(validation.userId);
6295
6763
  if (user?.id != null && String(user.id) !== userId) {
@@ -6321,7 +6789,7 @@ var require_bootstrap = __commonJS({
6321
6789
  const coordinator = getCoordinator(strapi2);
6322
6790
  const keyFor = (ip) => hashedKey("lf", ip);
6323
6791
  strapi2.server.use(async (ctx, next) => {
6324
- if (!isFailedLoginTrackedPath(ctx.path, ctx.method)) return next();
6792
+ if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
6325
6793
  const settings = await getRequestSettings(strapi2, ctx);
6326
6794
  const maxFailed = Number(settings.maxFailedLogins) || 0;
6327
6795
  if (maxFailed <= 0) return next();
@@ -6423,13 +6891,34 @@ var require_bootstrap = __commonJS({
6423
6891
  }
6424
6892
  function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
6425
6893
  strapi2.server.use(async (ctx, next) => {
6426
- const requestType = classifyJwtIssuingRequest(ctx.path, ctx.method);
6894
+ const apiPath = apiPathOf(strapi2, ctx);
6895
+ const requestType = classifyJwtIssuingRequest(apiPath, ctx.method);
6427
6896
  const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
6428
6897
  const nativeMode = usesNativeRefreshSessions(strapi2);
6429
6898
  await next();
6899
+ if (nativeMode && requestType === null) {
6900
+ await linkCreatedNativeSessions({ strapi: strapi2, ctx, log, sessionService });
6901
+ return;
6902
+ }
6430
6903
  if (requestType !== "new-session" && requestType !== "rotate-current") return;
6431
6904
  if (ctx.status < 200 || ctx.status >= 300) return;
6432
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
+ }
6433
6922
  const refreshCookieName = getRefreshCookieName(strapi2);
6434
6923
  if (requestType === "rotate-current") {
6435
6924
  if (nativeMode) {
@@ -6443,6 +6932,7 @@ var require_bootstrap = __commonJS({
6443
6932
  strapi: strapi2,
6444
6933
  nativeSessionManager: nativeSessionManager2,
6445
6934
  refreshToken: newRefreshToken,
6935
+ accessToken: ctx.body.jwt,
6446
6936
  user: ctx.body.user || ctx.state?.user
6447
6937
  });
6448
6938
  const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
@@ -6479,6 +6969,12 @@ var require_bootstrap = __commonJS({
6479
6969
  if (nativeSessionManager2 && nativeSession2) {
6480
6970
  await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
6481
6971
  }
6972
+ await compensateCreatedNativeSessions({
6973
+ strapi: strapi2,
6974
+ ctx,
6975
+ log,
6976
+ except: nativeSession2?.sessionId
6977
+ });
6482
6978
  failClosedAuthResponse({
6483
6979
  ctx,
6484
6980
  strapi: strapi2,
@@ -6535,6 +7031,7 @@ var require_bootstrap = __commonJS({
6535
7031
  strapi: strapi2,
6536
7032
  nativeSessionManager,
6537
7033
  refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
7034
+ accessToken: ctx.body.jwt,
6538
7035
  user
6539
7036
  });
6540
7037
  userDocId = nativeSession.userDocumentId;
@@ -6560,7 +7057,7 @@ var require_bootstrap = __commonJS({
6560
7057
  if (!newSession?.documentId) {
6561
7058
  throw new Error(`session creation returned no documentId for user ${userDocId}`);
6562
7059
  }
6563
- if (isPasswordResetRequest(ctx.path, ctx.method)) {
7060
+ if (isPasswordResetRequest(apiPath, ctx.method)) {
6564
7061
  await sessionService.terminateSession({
6565
7062
  userId: userDocId,
6566
7063
  exceptSessionId: newSession.documentId,
@@ -6695,6 +7192,14 @@ var require_bootstrap = __commonJS({
6695
7192
  if (nativeSessionManager && nativeSession) {
6696
7193
  await compensateNativeSession({ nativeSessionManager, nativeSession, log });
6697
7194
  }
7195
+ if (nativeMode) {
7196
+ await compensateCreatedNativeSessions({
7197
+ strapi: strapi2,
7198
+ ctx,
7199
+ log,
7200
+ except: nativeSession?.sessionId
7201
+ });
7202
+ }
6698
7203
  failClosedAuthResponse({
6699
7204
  ctx,
6700
7205
  strapi: strapi2,
@@ -6706,9 +7211,76 @@ var require_bootstrap = __commonJS({
6706
7211
  });
6707
7212
  log.info("[SUCCESS] Login interceptor middleware mounted");
6708
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
+ }
6709
7281
  function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
6710
7282
  strapi2.server.use(async (ctx, next) => {
6711
- const isRefreshToken = ctx.path === "/api/auth/refresh" && ctx.method === "POST";
7283
+ const isRefreshToken = apiPathOf(strapi2, ctx) === "/api/auth/refresh" && ctx.method === "POST";
6712
7284
  if (!isRefreshToken) return next();
6713
7285
  const cookieName = getRefreshCookieName(strapi2);
6714
7286
  const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
@@ -6807,6 +7379,12 @@ var require_bootstrap = __commonJS({
6807
7379
  if (nativeSession) {
6808
7380
  await compensateNativeSession({ nativeSessionManager, nativeSession, log });
6809
7381
  }
7382
+ await compensateCreatedNativeSessions({
7383
+ strapi: strapi2,
7384
+ ctx,
7385
+ log,
7386
+ except: nativeSession?.sessionId
7387
+ });
6810
7388
  failClosedAuthResponse({
6811
7389
  ctx,
6812
7390
  strapi: strapi2,
@@ -6844,7 +7422,7 @@ var require_bootstrap = __commonJS({
6844
7422
  }
6845
7423
  function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
6846
7424
  strapi2.server.use(async (ctx, next) => {
6847
- if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
7425
+ if (apiPathOf(strapi2, ctx) !== "/api/auth/logout" || ctx.method !== "POST") return next();
6848
7426
  const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
6849
7427
  const accessToken = extractBearerToken(ctx);
6850
7428
  const nativeMode = usesNativeRefreshSessions(strapi2);
@@ -7443,6 +8021,16 @@ var require_destroy = __commonJS({
7443
8021
  }
7444
8022
  strapi2.sessionManagerIntervals = {};
7445
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
+ }
7446
8034
  log.info("[SUCCESS] Plugin cleanup completed");
7447
8035
  };
7448
8036
  }
@@ -7872,6 +8460,31 @@ var require_admin = __commonJS({
7872
8460
  description: "Get count-only session statistics (admin)"
7873
8461
  }
7874
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
+ },
7875
8488
  {
7876
8489
  method: "GET",
7877
8490
  path: "/sessions/analytics",
@@ -8557,6 +9170,11 @@ var require_session_list = __commonJS({
8557
9170
  "use strict";
8558
9171
  var { enhanceSessions } = require_enhance_session();
8559
9172
  var { getNativeSessionManager } = require_native_session_manager();
9173
+ var {
9174
+ canInspectNativeSessions,
9175
+ countNativeOnly,
9176
+ getNativeTrackingSince
9177
+ } = require_native_only_insight();
8560
9178
  var {
8561
9179
  LIST_FIELDS,
8562
9180
  LIST_USER_FIELDS,
@@ -8628,19 +9246,13 @@ var require_session_list = __commonJS({
8628
9246
  );
8629
9247
  }
8630
9248
  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);
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 });
8644
9256
  }
8645
9257
  async function countUsersOnline(strapi2, cutoff) {
8646
9258
  const meta = strapi2.db.metadata.get(SESSION_UID);
@@ -8728,7 +9340,7 @@ var require_session_list = __commonJS({
8728
9340
  count({ status: "ended", reason: "logout" }),
8729
9341
  count({ status: "ended", reason: "idle" }),
8730
9342
  countUsersOnline(strapi2, cutoff),
8731
- countNativeOnlySessions(strapi2)
9343
+ countNativeOnlySplit(strapi2)
8732
9344
  ]);
8733
9345
  const ended = Math.max(0, Number(total) - Number(open));
8734
9346
  const value = {
@@ -8741,7 +9353,8 @@ var require_session_list = __commonJS({
8741
9353
  timedOut: Number(timedOut),
8742
9354
  otherReasons: Math.max(0, ended - Number(loggedOut) - Number(timedOut)),
8743
9355
  usersOnline: Number(usersOnline),
8744
- nativeOnly: Number(nativeOnly)
9356
+ nativeOnly: nativeOnly.total,
9357
+ nativeOnlyAfterTracking: nativeOnly.afterTracking
8745
9358
  };
8746
9359
  cache.set(key, { value, expiresAt: Date.now() + STATS_CACHE_MS });
8747
9360
  if (cache.size > 20) cache.delete(cache.keys().next().value);
@@ -8911,6 +9524,12 @@ var require_session = __commonJS({
8911
9524
  var { sendServerError } = require_http_errors();
8912
9525
  var { getCoordinator } = require_coordination();
8913
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();
8914
9533
  var {
8915
9534
  decodeExportCursor,
8916
9535
  exportQuerySchema,
@@ -9145,6 +9764,78 @@ var require_session = __commonJS({
9145
9764
  return ctx.internalServerError("Unable to load session statistics");
9146
9765
  }
9147
9766
  },
9767
+ /**
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.
9780
+ */
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
+ },
9148
9839
  /**
9149
9840
  * Aggregates for the Analytics page over every session: counts, grouped
9150
9841
  * counts per device type and browser, distinct users, average length. No