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.
- package/CHANGELOG.md +84 -1
- package/README.md +75 -24
- package/dist/admin/{Analytics-CBHeWeGn.js → Analytics-BikQQx_J.js} +45 -75
- package/dist/admin/{Analytics-D56O8Q6e.mjs → Analytics-DIY51RI_.mjs} +45 -75
- package/dist/admin/{App-EDIkLJdb.mjs → App-B3vaybSO.mjs} +584 -120
- package/dist/admin/{App-D4cBPwB_.js → App-BV1LM9Bp.js} +584 -120
- package/dist/admin/{OnlineUsersWidget-MwUutkKQ.mjs → OnlineUsersWidget-T-2upsDd.mjs} +18 -26
- package/dist/admin/{OnlineUsersWidget-BF2R2YIy.js → OnlineUsersWidget-fJogM1xl.js} +18 -26
- package/dist/admin/{Settings-CMzEF8EH.js → Settings-AyYka8wn.js} +1 -1
- package/dist/admin/{Settings-bLMyi0BN.mjs → Settings-BpBlXyMY.mjs} +1 -1
- package/dist/admin/{de-CxfuTF6C.mjs → de-BSCDuq1i.mjs} +41 -6
- package/dist/admin/{de-DVNTHmSo.js → de-z0aHRwdw.js} +41 -6
- package/dist/admin/{en-BcPIlQYL.mjs → en-B4Cuq9JN.mjs} +41 -6
- package/dist/admin/{en-BuVXIcHA.js → en-BWPOiiMt.js} +41 -6
- package/dist/admin/{es-CEteHmBO.js → es-CMskkUh-.js} +41 -6
- package/dist/admin/{es-DxHpaNA1.mjs → es-DBAmysKi.mjs} +41 -6
- package/dist/admin/{fr-Dw43lHg7.mjs → fr-BNGdtjEl.mjs} +41 -6
- package/dist/admin/{fr-BMd2-wW7.js → fr-ClJ2BkrE.js} +41 -6
- package/dist/admin/{index-DvNfekoR.js → index-DyE1rLW0.js} +22 -56
- package/dist/admin/{index-qa6Qnfkc.mjs → index-mCVi1j7e.mjs} +48 -82
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +2 -2
- package/dist/admin/{pt-BvO63p01.js → pt-CRh_J7JS.js} +41 -6
- package/dist/admin/{pt-7jnxDSX-.mjs → pt-Cl7TWsOV.mjs} +41 -6
- package/dist/server/index.js +1495 -51
- package/dist/server/index.mjs +1495 -51
- package/package.json +10 -2
- package/pics/untracked-confirm-dialog.webp +0 -0
- package/pics/untracked-disclosure-warning-dark.webp +0 -0
- package/pics/untracked-disclosure-warning.webp +0 -0
- package/pics/untracked-mobile-notice-warning.webp +0 -0
- package/pics/untracked-notice-neutral.webp +0 -0
package/dist/server/index.js
CHANGED
|
@@ -1722,7 +1722,26 @@ var require_auth_routes = __commonJS({
|
|
|
1722
1722
|
function isFailedLoginTrackedPath(path, method) {
|
|
1723
1723
|
return FAILED_LOGIN_ROUTES.has(requestKey(path, method)) || isMagicLinkLogin(path, method);
|
|
1724
1724
|
}
|
|
1725
|
+
var DEFAULT_API_PREFIX = "/api";
|
|
1726
|
+
function normalizeApiPrefix(prefix) {
|
|
1727
|
+
if (typeof prefix !== "string") return DEFAULT_API_PREFIX;
|
|
1728
|
+
const trimmed = prefix.trim().replace(/\/+$/, "");
|
|
1729
|
+
if (!trimmed) return DEFAULT_API_PREFIX;
|
|
1730
|
+
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
1731
|
+
}
|
|
1732
|
+
function toCanonicalApiPath(path, prefix) {
|
|
1733
|
+
if (typeof path !== "string") return null;
|
|
1734
|
+
const normalized = normalizeApiPrefix(prefix);
|
|
1735
|
+
if (normalized === DEFAULT_API_PREFIX) return path;
|
|
1736
|
+
if (path === normalized) return DEFAULT_API_PREFIX;
|
|
1737
|
+
if (path.startsWith(`${normalized}/`)) {
|
|
1738
|
+
return `${DEFAULT_API_PREFIX}${path.slice(normalized.length)}`;
|
|
1739
|
+
}
|
|
1740
|
+
return null;
|
|
1741
|
+
}
|
|
1725
1742
|
module2.exports = {
|
|
1743
|
+
normalizeApiPrefix,
|
|
1744
|
+
toCanonicalApiPath,
|
|
1726
1745
|
classifyJwtIssuingRequest,
|
|
1727
1746
|
isFailedLoginTrackedPath,
|
|
1728
1747
|
isPasswordResetRequest,
|
|
@@ -1817,6 +1836,404 @@ var require_refresh_token = __commonJS({
|
|
|
1817
1836
|
}
|
|
1818
1837
|
});
|
|
1819
1838
|
|
|
1839
|
+
// server/src/utils/native-session-capture.js
|
|
1840
|
+
var require_native_session_capture = __commonJS({
|
|
1841
|
+
"server/src/utils/native-session-capture.js"(exports2, module2) {
|
|
1842
|
+
"use strict";
|
|
1843
|
+
var NATIVE_SESSION_UID = "admin::session";
|
|
1844
|
+
var NATIVE_ORIGIN = "users-permissions";
|
|
1845
|
+
var CREATED_STATE_KEY = "__magicSessionNativeCreated";
|
|
1846
|
+
var MAX_RECORDED_PER_REQUEST = 20;
|
|
1847
|
+
var MAX_PARSED_BODY_BYTES = 256 * 1024;
|
|
1848
|
+
var MAX_TOKEN_CANDIDATES = 10;
|
|
1849
|
+
function recordCreatedNativeSession(strapi2, row) {
|
|
1850
|
+
if (!row || row.origin !== NATIVE_ORIGIN || row.status !== "active") return false;
|
|
1851
|
+
if (typeof row.sessionId !== "string" || !row.sessionId) return false;
|
|
1852
|
+
if (row.userId == null || row.userId === "") return false;
|
|
1853
|
+
let ctx;
|
|
1854
|
+
try {
|
|
1855
|
+
ctx = strapi2?.requestContext?.get?.();
|
|
1856
|
+
} catch {
|
|
1857
|
+
return false;
|
|
1858
|
+
}
|
|
1859
|
+
if (!ctx || typeof ctx !== "object" || !ctx.state || typeof ctx.state !== "object") {
|
|
1860
|
+
return false;
|
|
1861
|
+
}
|
|
1862
|
+
const list = Array.isArray(ctx.state[CREATED_STATE_KEY]) ? ctx.state[CREATED_STATE_KEY] : [];
|
|
1863
|
+
if (list.length >= MAX_RECORDED_PER_REQUEST) return false;
|
|
1864
|
+
list.push({ sessionId: row.sessionId, userId: String(row.userId) });
|
|
1865
|
+
ctx.state[CREATED_STATE_KEY] = list;
|
|
1866
|
+
return true;
|
|
1867
|
+
}
|
|
1868
|
+
function subscribeNativeSessionCreation(strapi2) {
|
|
1869
|
+
const lifecycles = strapi2?.db?.lifecycles;
|
|
1870
|
+
if (!lifecycles || typeof lifecycles.subscribe !== "function") return () => {
|
|
1871
|
+
};
|
|
1872
|
+
if (!strapi2?.contentTypes?.[NATIVE_SESSION_UID]) return () => {
|
|
1873
|
+
};
|
|
1874
|
+
const unsubscribe = lifecycles.subscribe({
|
|
1875
|
+
models: [NATIVE_SESSION_UID],
|
|
1876
|
+
afterCreate(event) {
|
|
1877
|
+
try {
|
|
1878
|
+
recordCreatedNativeSession(strapi2, event?.result);
|
|
1879
|
+
} catch {
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
});
|
|
1883
|
+
return typeof unsubscribe === "function" ? unsubscribe : () => {
|
|
1884
|
+
};
|
|
1885
|
+
}
|
|
1886
|
+
function getCreatedNativeSessions(ctx) {
|
|
1887
|
+
const list = ctx?.state?.[CREATED_STATE_KEY];
|
|
1888
|
+
return Array.isArray(list) ? list.slice() : [];
|
|
1889
|
+
}
|
|
1890
|
+
function isThenable(value) {
|
|
1891
|
+
return Boolean(value) && typeof value === "object" && typeof value.then === "function";
|
|
1892
|
+
}
|
|
1893
|
+
function readJsonBody(body) {
|
|
1894
|
+
if (body && typeof body === "object" && !Buffer.isBuffer(body) && !isStream(body)) return body;
|
|
1895
|
+
if (typeof body !== "string" || body.length === 0) return null;
|
|
1896
|
+
if (Buffer.byteLength(body, "utf8") > MAX_PARSED_BODY_BYTES) return null;
|
|
1897
|
+
const first = body.trimStart()[0];
|
|
1898
|
+
if (first !== "{") return null;
|
|
1899
|
+
try {
|
|
1900
|
+
const parsed = JSON.parse(body);
|
|
1901
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
1902
|
+
} catch {
|
|
1903
|
+
return null;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
function isStream(value) {
|
|
1907
|
+
return typeof value.pipe === "function";
|
|
1908
|
+
}
|
|
1909
|
+
function findAccessTokenCandidates(body) {
|
|
1910
|
+
const json = readJsonBody(body);
|
|
1911
|
+
if (!json) return [];
|
|
1912
|
+
const candidates = [];
|
|
1913
|
+
const add = (value) => {
|
|
1914
|
+
if (typeof value === "string" && value.length > 0 && value.length <= 8192) {
|
|
1915
|
+
if (!candidates.includes(value)) candidates.push(value);
|
|
1916
|
+
}
|
|
1917
|
+
};
|
|
1918
|
+
add(json.jwt);
|
|
1919
|
+
const data = json.data;
|
|
1920
|
+
if (data && typeof data === "object" && !Array.isArray(data)) {
|
|
1921
|
+
for (const value of Object.values(data)) {
|
|
1922
|
+
if (candidates.length >= MAX_TOKEN_CANDIDATES) break;
|
|
1923
|
+
if (value && typeof value === "object" && !Array.isArray(value)) add(value.jwt);
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
return candidates.slice(0, MAX_TOKEN_CANDIDATES);
|
|
1927
|
+
}
|
|
1928
|
+
async function revokeCreatedNativeSessions({ ctx, nativeSessionManager, log, except = null }) {
|
|
1929
|
+
let revoked = 0;
|
|
1930
|
+
for (const created of getCreatedNativeSessions(ctx)) {
|
|
1931
|
+
if (except && created.sessionId === except) continue;
|
|
1932
|
+
try {
|
|
1933
|
+
if (await nativeSessionManager.revokeSessionById(created.userId, created.sessionId)) {
|
|
1934
|
+
revoked += 1;
|
|
1935
|
+
}
|
|
1936
|
+
} catch (err) {
|
|
1937
|
+
log?.error?.("[AUTH-COMPENSATION] Native session revocation failed:", err?.name || "Error");
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
return revoked;
|
|
1941
|
+
}
|
|
1942
|
+
module2.exports = {
|
|
1943
|
+
CREATED_STATE_KEY,
|
|
1944
|
+
MAX_RECORDED_PER_REQUEST,
|
|
1945
|
+
MAX_PARSED_BODY_BYTES,
|
|
1946
|
+
recordCreatedNativeSession,
|
|
1947
|
+
subscribeNativeSessionCreation,
|
|
1948
|
+
getCreatedNativeSessions,
|
|
1949
|
+
findAccessTokenCandidates,
|
|
1950
|
+
revokeCreatedNativeSessions,
|
|
1951
|
+
isThenable
|
|
1952
|
+
};
|
|
1953
|
+
}
|
|
1954
|
+
});
|
|
1955
|
+
|
|
1956
|
+
// server/src/utils/native-only-insight.js
|
|
1957
|
+
var require_native_only_insight = __commonJS({
|
|
1958
|
+
"server/src/utils/native-only-insight.js"(exports2, module2) {
|
|
1959
|
+
"use strict";
|
|
1960
|
+
var { getNativeSessionManager } = require_native_session_manager();
|
|
1961
|
+
var { withPluginStoreKey, PLUGIN_ID } = require_plugin_store();
|
|
1962
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
1963
|
+
var NATIVE_SESSION_UID = "admin::session";
|
|
1964
|
+
var NATIVE_ORIGIN = "users-permissions";
|
|
1965
|
+
var TRACKING_STORE_KEY = "nativeTracking";
|
|
1966
|
+
var MONTH_BUCKETS = 12;
|
|
1967
|
+
var DEVICE_SAMPLE_LIMIT = 2e3;
|
|
1968
|
+
var DEVICE_SAMPLE_BATCH = 500;
|
|
1969
|
+
var END_BATCH_SIZE = 200;
|
|
1970
|
+
var END_MAX_ROWS = 5e3;
|
|
1971
|
+
var END_MIN_AGE_MS = 2 * 60 * 1e3;
|
|
1972
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
1973
|
+
function canInspectNativeSessions(strapi2) {
|
|
1974
|
+
return Boolean(
|
|
1975
|
+
getNativeSessionManager(strapi2) && strapi2?.contentTypes?.[NATIVE_SESSION_UID] && strapi2?.db?.metadata?.get?.(NATIVE_SESSION_UID)
|
|
1976
|
+
);
|
|
1977
|
+
}
|
|
1978
|
+
function tables(strapi2) {
|
|
1979
|
+
const nativeMeta = strapi2.db.metadata.get(NATIVE_SESSION_UID);
|
|
1980
|
+
const sessionMeta = strapi2.db.metadata.get(SESSION_UID);
|
|
1981
|
+
const column = (meta, attribute) => meta.attributes[attribute]?.columnName || attribute;
|
|
1982
|
+
return {
|
|
1983
|
+
knex: strapi2.db.connection,
|
|
1984
|
+
native: nativeMeta.tableName,
|
|
1985
|
+
sidecar: sessionMeta.tableName,
|
|
1986
|
+
linked: column(sessionMeta, "nativeSessionId"),
|
|
1987
|
+
col: {
|
|
1988
|
+
id: column(nativeMeta, "id"),
|
|
1989
|
+
sessionId: column(nativeMeta, "sessionId"),
|
|
1990
|
+
origin: column(nativeMeta, "origin"),
|
|
1991
|
+
status: column(nativeMeta, "status"),
|
|
1992
|
+
expiresAt: column(nativeMeta, "expiresAt"),
|
|
1993
|
+
absoluteExpiresAt: column(nativeMeta, "absoluteExpiresAt"),
|
|
1994
|
+
createdAt: column(nativeMeta, "createdAt"),
|
|
1995
|
+
metadata: column(nativeMeta, "metadata"),
|
|
1996
|
+
deviceId: column(nativeMeta, "deviceId")
|
|
1997
|
+
}
|
|
1998
|
+
};
|
|
1999
|
+
}
|
|
2000
|
+
function untrackedQuery(t, now) {
|
|
2001
|
+
const { knex, native, sidecar, linked, col } = t;
|
|
2002
|
+
return knex(native).where(`${native}.${col.origin}`, NATIVE_ORIGIN).andWhere(`${native}.${col.status}`, "active").andWhere(`${native}.${col.expiresAt}`, ">", now).andWhere((qb) => {
|
|
2003
|
+
qb.whereNull(`${native}.${col.absoluteExpiresAt}`).orWhere(
|
|
2004
|
+
`${native}.${col.absoluteExpiresAt}`,
|
|
2005
|
+
">",
|
|
2006
|
+
now
|
|
2007
|
+
);
|
|
2008
|
+
}).whereNotExists(function linkedSidecar() {
|
|
2009
|
+
this.select(knex.raw("1")).from(sidecar).whereRaw("??.?? = ??.??", [sidecar, linked, native, col.sessionId]);
|
|
2010
|
+
});
|
|
2011
|
+
}
|
|
2012
|
+
function sumWhen(knex, condition, bindings, alias) {
|
|
2013
|
+
return knex.raw(`SUM(CASE WHEN ${condition} THEN 1 ELSE 0 END) AS ??`, [...bindings, alias]);
|
|
2014
|
+
}
|
|
2015
|
+
function toCount(value) {
|
|
2016
|
+
const number = Number(value);
|
|
2017
|
+
return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
|
|
2018
|
+
}
|
|
2019
|
+
async function getNativeTrackingSince(strapi2) {
|
|
2020
|
+
const value = await strapi2.store({ type: "plugin", name: PLUGIN_ID }).get({ key: TRACKING_STORE_KEY });
|
|
2021
|
+
const since = value && typeof value === "object" ? new Date(value.since) : null;
|
|
2022
|
+
return since && Number.isFinite(since.getTime()) ? since : null;
|
|
2023
|
+
}
|
|
2024
|
+
async function ensureNativeTrackingSince(strapi2, now = /* @__PURE__ */ new Date()) {
|
|
2025
|
+
const existing = await getNativeTrackingSince(strapi2);
|
|
2026
|
+
if (existing) return existing;
|
|
2027
|
+
return withPluginStoreKey(strapi2, TRACKING_STORE_KEY, async (store) => {
|
|
2028
|
+
const again = await store.get({ key: TRACKING_STORE_KEY });
|
|
2029
|
+
const stored = again && typeof again === "object" ? new Date(again.since) : null;
|
|
2030
|
+
if (stored && Number.isFinite(stored.getTime())) return stored;
|
|
2031
|
+
const oldest = await strapi2.db.query(SESSION_UID).findMany({
|
|
2032
|
+
where: { nativeSessionId: { $notNull: true } },
|
|
2033
|
+
select: ["loginTime"],
|
|
2034
|
+
orderBy: [{ loginTime: "asc" }],
|
|
2035
|
+
limit: 1
|
|
2036
|
+
});
|
|
2037
|
+
const first = oldest?.[0]?.loginTime ? new Date(oldest[0].loginTime) : null;
|
|
2038
|
+
const since = first && Number.isFinite(first.getTime()) && first.getTime() < now.getTime() ? first : now;
|
|
2039
|
+
await store.set({
|
|
2040
|
+
key: TRACKING_STORE_KEY,
|
|
2041
|
+
value: { since: since.toISOString(), source: first ? "first-linked-session" : "install" }
|
|
2042
|
+
});
|
|
2043
|
+
return since;
|
|
2044
|
+
});
|
|
2045
|
+
}
|
|
2046
|
+
async function countNativeOnly(strapi2, { now = /* @__PURE__ */ new Date(), trackingSince = null } = {}) {
|
|
2047
|
+
if (!canInspectNativeSessions(strapi2)) return { total: 0, afterTracking: null };
|
|
2048
|
+
const t = tables(strapi2);
|
|
2049
|
+
const selects = [t.knex.raw("COUNT(*) AS ??", ["total"])];
|
|
2050
|
+
if (trackingSince) {
|
|
2051
|
+
selects.push(
|
|
2052
|
+
sumWhen(t.knex, "??.?? >= ?", [t.native, t.col.createdAt, trackingSince], "afterTracking")
|
|
2053
|
+
);
|
|
2054
|
+
}
|
|
2055
|
+
const row = await untrackedQuery(t, now).select(...selects).first();
|
|
2056
|
+
return {
|
|
2057
|
+
total: toCount(row?.total),
|
|
2058
|
+
afterTracking: trackingSince ? toCount(row?.afterTracking) : null
|
|
2059
|
+
};
|
|
2060
|
+
}
|
|
2061
|
+
function monthStart(date, offset) {
|
|
2062
|
+
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + offset, 1));
|
|
2063
|
+
}
|
|
2064
|
+
function monthLabel(date) {
|
|
2065
|
+
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
|
|
2066
|
+
}
|
|
2067
|
+
function deviceClassOf(metadata) {
|
|
2068
|
+
let value = metadata;
|
|
2069
|
+
if (typeof value === "string") {
|
|
2070
|
+
if (value.length > 4096) return "unknown";
|
|
2071
|
+
try {
|
|
2072
|
+
value = JSON.parse(value);
|
|
2073
|
+
} catch {
|
|
2074
|
+
return "unknown";
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
const name = value && typeof value === "object" ? value.deviceName : null;
|
|
2078
|
+
if (typeof name !== "string" || !name) return "unknown";
|
|
2079
|
+
const label = name.slice(0, 200);
|
|
2080
|
+
if (/\b(?:iOS|Android)\b/.test(label)) return "mobile";
|
|
2081
|
+
if (/\b(?:Windows|macOS|Linux|ChromeOS)\b/.test(label)) return "desktop";
|
|
2082
|
+
return "unknown";
|
|
2083
|
+
}
|
|
2084
|
+
async function sampleDevices(t, now) {
|
|
2085
|
+
const counts = { desktop: 0, mobile: 0, unknown: 0 };
|
|
2086
|
+
let scanned = 0;
|
|
2087
|
+
let lastId = null;
|
|
2088
|
+
let complete = false;
|
|
2089
|
+
while (scanned < DEVICE_SAMPLE_LIMIT) {
|
|
2090
|
+
const limit = Math.min(DEVICE_SAMPLE_BATCH, DEVICE_SAMPLE_LIMIT - scanned);
|
|
2091
|
+
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);
|
|
2092
|
+
if (lastId !== null) query.andWhere(`${t.native}.${t.col.id}`, ">", lastId);
|
|
2093
|
+
const rows = await query;
|
|
2094
|
+
for (const row of rows) counts[deviceClassOf(row.metadata)] += 1;
|
|
2095
|
+
scanned += rows.length;
|
|
2096
|
+
if (rows.length < limit) {
|
|
2097
|
+
complete = true;
|
|
2098
|
+
break;
|
|
2099
|
+
}
|
|
2100
|
+
lastId = rows[rows.length - 1].id;
|
|
2101
|
+
}
|
|
2102
|
+
return { ...counts, scanned, complete };
|
|
2103
|
+
}
|
|
2104
|
+
async function getNativeOnlySummary(strapi2, { now = /* @__PURE__ */ new Date() } = {}) {
|
|
2105
|
+
const trackingSince = canInspectNativeSessions(strapi2) ? await getNativeTrackingSince(strapi2) : null;
|
|
2106
|
+
const empty = {
|
|
2107
|
+
available: false,
|
|
2108
|
+
total: 0,
|
|
2109
|
+
trackingSince: trackingSince ? trackingSince.toISOString() : null,
|
|
2110
|
+
beforeTracking: 0,
|
|
2111
|
+
afterTracking: 0,
|
|
2112
|
+
byMonth: [],
|
|
2113
|
+
earlier: 0,
|
|
2114
|
+
bySource: { signIn: 0, passwordChange: 0, tokenOnly: 0 },
|
|
2115
|
+
byDevice: { desktop: 0, mobile: 0, unknown: 0 },
|
|
2116
|
+
deviceSample: { scanned: 0, limit: DEVICE_SAMPLE_LIMIT, complete: true },
|
|
2117
|
+
expiring: { within7Days: 0, within30Days: 0 },
|
|
2118
|
+
generatedAt: now.toISOString()
|
|
2119
|
+
};
|
|
2120
|
+
if (!canInspectNativeSessions(strapi2)) return empty;
|
|
2121
|
+
const t = tables(strapi2);
|
|
2122
|
+
const { knex, native, col } = t;
|
|
2123
|
+
const created = [native, col.createdAt];
|
|
2124
|
+
const in7 = new Date(now.getTime() + 7 * DAY_MS);
|
|
2125
|
+
const in30 = new Date(now.getTime() + 30 * DAY_MS);
|
|
2126
|
+
const expiringWithin = (until) => [
|
|
2127
|
+
"??.?? <= ? OR (??.?? IS NOT NULL AND ??.?? <= ?)",
|
|
2128
|
+
[
|
|
2129
|
+
native,
|
|
2130
|
+
col.expiresAt,
|
|
2131
|
+
until,
|
|
2132
|
+
native,
|
|
2133
|
+
col.absoluteExpiresAt,
|
|
2134
|
+
native,
|
|
2135
|
+
col.absoluteExpiresAt,
|
|
2136
|
+
until
|
|
2137
|
+
]
|
|
2138
|
+
];
|
|
2139
|
+
const months = Array.from({ length: MONTH_BUCKETS }, (_, index) => {
|
|
2140
|
+
const start = monthStart(now, index - (MONTH_BUCKETS - 1));
|
|
2141
|
+
return { start, end: monthStart(start, 1), label: monthLabel(start) };
|
|
2142
|
+
});
|
|
2143
|
+
const selects = [
|
|
2144
|
+
knex.raw("COUNT(*) AS ??", ["total"]),
|
|
2145
|
+
sumWhen(knex, "??.?? IS NOT NULL", [native, col.metadata], "signIn"),
|
|
2146
|
+
sumWhen(
|
|
2147
|
+
knex,
|
|
2148
|
+
"??.?? IS NULL AND ??.?? IS NOT NULL",
|
|
2149
|
+
[native, col.metadata, native, col.deviceId],
|
|
2150
|
+
"passwordChange"
|
|
2151
|
+
),
|
|
2152
|
+
sumWhen(
|
|
2153
|
+
knex,
|
|
2154
|
+
"??.?? IS NULL AND ??.?? IS NULL",
|
|
2155
|
+
[native, col.metadata, native, col.deviceId],
|
|
2156
|
+
"tokenOnly"
|
|
2157
|
+
),
|
|
2158
|
+
sumWhen(knex, ...expiringWithin(in7), "within7Days"),
|
|
2159
|
+
sumWhen(knex, ...expiringWithin(in30), "within30Days"),
|
|
2160
|
+
sumWhen(knex, "??.?? < ?", [...created, months[0].start], "earlier"),
|
|
2161
|
+
...months.map(
|
|
2162
|
+
(month, index) => sumWhen(
|
|
2163
|
+
knex,
|
|
2164
|
+
"??.?? >= ? AND ??.?? < ?",
|
|
2165
|
+
[...created, month.start, ...created, month.end],
|
|
2166
|
+
`m${index}`
|
|
2167
|
+
)
|
|
2168
|
+
)
|
|
2169
|
+
];
|
|
2170
|
+
if (trackingSince) {
|
|
2171
|
+
selects.push(sumWhen(knex, "??.?? >= ?", [...created, trackingSince], "afterTracking"));
|
|
2172
|
+
}
|
|
2173
|
+
const row = await untrackedQuery(t, now).select(...selects).first() || {};
|
|
2174
|
+
const total = toCount(row.total);
|
|
2175
|
+
const afterTracking = trackingSince ? toCount(row.afterTracking) : 0;
|
|
2176
|
+
const devices = total > 0 ? await sampleDevices(t, now) : null;
|
|
2177
|
+
return {
|
|
2178
|
+
...empty,
|
|
2179
|
+
available: true,
|
|
2180
|
+
total,
|
|
2181
|
+
beforeTracking: trackingSince ? Math.max(0, total - afterTracking) : total,
|
|
2182
|
+
afterTracking,
|
|
2183
|
+
byMonth: months.map((month, index) => ({ month: month.label, count: toCount(row[`m${index}`]) })).filter((entry) => entry.count > 0),
|
|
2184
|
+
earlier: toCount(row.earlier),
|
|
2185
|
+
bySource: {
|
|
2186
|
+
signIn: toCount(row.signIn),
|
|
2187
|
+
passwordChange: toCount(row.passwordChange),
|
|
2188
|
+
tokenOnly: toCount(row.tokenOnly)
|
|
2189
|
+
},
|
|
2190
|
+
byDevice: devices ? { desktop: devices.desktop, mobile: devices.mobile, unknown: devices.unknown } : empty.byDevice,
|
|
2191
|
+
deviceSample: devices ? { scanned: devices.scanned, limit: DEVICE_SAMPLE_LIMIT, complete: devices.complete } : empty.deviceSample,
|
|
2192
|
+
expiring: { within7Days: toCount(row.within7Days), within30Days: toCount(row.within30Days) }
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
async function endNativeOnlySessions(strapi2, { now = /* @__PURE__ */ new Date(), maxRows = END_MAX_ROWS } = {}) {
|
|
2196
|
+
if (!canInspectNativeSessions(strapi2)) return { ended: 0, remaining: 0 };
|
|
2197
|
+
const t = tables(strapi2);
|
|
2198
|
+
const limit = Math.max(0, Math.min(END_MAX_ROWS, Math.floor(Number(maxRows) || 0)));
|
|
2199
|
+
const createdBefore = new Date(now.getTime() - END_MIN_AGE_MS);
|
|
2200
|
+
const idColumn = `${t.native}.${t.col.id}`;
|
|
2201
|
+
const oldEnough = (query) => query.andWhere(`${t.native}.${t.col.createdAt}`, "<", createdBefore);
|
|
2202
|
+
let ended = 0;
|
|
2203
|
+
let lastId = null;
|
|
2204
|
+
while (ended < limit) {
|
|
2205
|
+
const size = Math.min(END_BATCH_SIZE, limit - ended);
|
|
2206
|
+
const select = oldEnough(untrackedQuery(t, now)).select({ id: idColumn }).orderBy(idColumn, "asc").limit(size);
|
|
2207
|
+
if (lastId !== null) select.andWhere(idColumn, ">", lastId);
|
|
2208
|
+
const rows = await select;
|
|
2209
|
+
if (rows.length === 0) break;
|
|
2210
|
+
const ids = rows.map((row) => row.id);
|
|
2211
|
+
lastId = ids[ids.length - 1];
|
|
2212
|
+
const deleted = await oldEnough(untrackedQuery(t, now)).whereIn(idColumn, ids).del();
|
|
2213
|
+
ended += toCount(deleted);
|
|
2214
|
+
if (rows.length < size) break;
|
|
2215
|
+
}
|
|
2216
|
+
const { total } = await countNativeOnly(strapi2, { now });
|
|
2217
|
+
return { ended, remaining: total };
|
|
2218
|
+
}
|
|
2219
|
+
module2.exports = {
|
|
2220
|
+
TRACKING_STORE_KEY,
|
|
2221
|
+
MONTH_BUCKETS,
|
|
2222
|
+
DEVICE_SAMPLE_LIMIT,
|
|
2223
|
+
END_BATCH_SIZE,
|
|
2224
|
+
END_MAX_ROWS,
|
|
2225
|
+
END_MIN_AGE_MS,
|
|
2226
|
+
canInspectNativeSessions,
|
|
2227
|
+
getNativeTrackingSince,
|
|
2228
|
+
ensureNativeTrackingSince,
|
|
2229
|
+
countNativeOnly,
|
|
2230
|
+
deviceClassOf,
|
|
2231
|
+
getNativeOnlySummary,
|
|
2232
|
+
endNativeOnlySessions
|
|
2233
|
+
};
|
|
2234
|
+
}
|
|
2235
|
+
});
|
|
2236
|
+
|
|
1820
2237
|
// server/src/middlewares/session-rejection-headers.js
|
|
1821
2238
|
var require_session_rejection_headers = __commonJS({
|
|
1822
2239
|
"server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
|
|
@@ -1873,6 +2290,7 @@ var require_last_seen = __commonJS({
|
|
|
1873
2290
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
1874
2291
|
var { extractBearerToken } = require_extract_token();
|
|
1875
2292
|
var { hashToken } = require_encryption();
|
|
2293
|
+
var { toCanonicalApiPath } = require_auth_routes();
|
|
1876
2294
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
1877
2295
|
var AUTH_PATH_PREFIXES = [
|
|
1878
2296
|
"/api/auth/",
|
|
@@ -1897,16 +2315,21 @@ var require_last_seen = __commonJS({
|
|
|
1897
2315
|
}
|
|
1898
2316
|
module2.exports = ({ strapi: strapi2, sessionService }) => {
|
|
1899
2317
|
return async (ctx, next) => {
|
|
1900
|
-
|
|
2318
|
+
const apiPath = toCanonicalApiPath(ctx.path, strapi2.config?.get?.("api.rest.prefix", "/api")) ?? ctx.path;
|
|
2319
|
+
if (isAuthEndpoint(apiPath)) {
|
|
1901
2320
|
return next();
|
|
1902
2321
|
}
|
|
1903
2322
|
await next();
|
|
1904
|
-
if (isSelfTerminatingEndpoint(
|
|
2323
|
+
if (isSelfTerminatingEndpoint(apiPath) || (ctx.status || 200) >= 400) {
|
|
1905
2324
|
return;
|
|
1906
2325
|
}
|
|
1907
2326
|
if (!ctx.state.user) {
|
|
1908
2327
|
return;
|
|
1909
2328
|
}
|
|
2329
|
+
const strategyName = ctx.state.auth?.strategy?.name;
|
|
2330
|
+
if (strategyName === "admin" || strategyName === "admin-token") {
|
|
2331
|
+
return;
|
|
2332
|
+
}
|
|
1910
2333
|
let userDocId = ctx.state.user.documentId;
|
|
1911
2334
|
if (!userDocId && ctx.state.user.id) {
|
|
1912
2335
|
try {
|
|
@@ -5912,6 +6335,8 @@ var require_bootstrap = __commonJS({
|
|
|
5912
6335
|
} = require_coordination();
|
|
5913
6336
|
var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
|
|
5914
6337
|
var {
|
|
6338
|
+
normalizeApiPrefix,
|
|
6339
|
+
toCanonicalApiPath,
|
|
5915
6340
|
classifyJwtIssuingRequest,
|
|
5916
6341
|
isFailedLoginTrackedPath,
|
|
5917
6342
|
isPasswordResetRequest,
|
|
@@ -5923,6 +6348,14 @@ var require_bootstrap = __commonJS({
|
|
|
5923
6348
|
getOutgoingRefreshToken,
|
|
5924
6349
|
stripAuthTokensFromResponse
|
|
5925
6350
|
} = require_refresh_token();
|
|
6351
|
+
var {
|
|
6352
|
+
subscribeNativeSessionCreation,
|
|
6353
|
+
getCreatedNativeSessions,
|
|
6354
|
+
findAccessTokenCandidates,
|
|
6355
|
+
revokeCreatedNativeSessions,
|
|
6356
|
+
isThenable
|
|
6357
|
+
} = require_native_session_capture();
|
|
6358
|
+
var { ensureNativeTrackingSince } = require_native_only_insight();
|
|
5926
6359
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
5927
6360
|
var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
|
|
5928
6361
|
var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -5969,6 +6402,17 @@ var require_bootstrap = __commonJS({
|
|
|
5969
6402
|
await ensureSessionLookupIndexes(strapi2, log);
|
|
5970
6403
|
await registerSessionAwareAuthStrategy(strapi2);
|
|
5971
6404
|
await removeLegacyLicenseRows(strapi2, log);
|
|
6405
|
+
strapi2.sessionManagerUnsubscribers = [
|
|
6406
|
+
...strapi2.sessionManagerUnsubscribers || [],
|
|
6407
|
+
subscribeNativeSessionCreation(strapi2)
|
|
6408
|
+
];
|
|
6409
|
+
if (usesNativeRefreshSessions(strapi2)) {
|
|
6410
|
+
try {
|
|
6411
|
+
await ensureNativeTrackingSince(strapi2);
|
|
6412
|
+
} catch (err) {
|
|
6413
|
+
log.warn("[NATIVE] Tracking start date could not be stored:", err?.name || "Error");
|
|
6414
|
+
}
|
|
6415
|
+
}
|
|
5972
6416
|
const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
|
|
5973
6417
|
if (!strapi2.sessionManagerIntervals) {
|
|
5974
6418
|
strapi2.sessionManagerIntervals = {};
|
|
@@ -6100,7 +6544,7 @@ var require_bootstrap = __commonJS({
|
|
|
6100
6544
|
}
|
|
6101
6545
|
function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
|
|
6102
6546
|
strapi2.server.use(async (ctx, next) => {
|
|
6103
|
-
if (!shouldRunPreAuthGeoGuard(ctx
|
|
6547
|
+
if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
|
|
6104
6548
|
return next();
|
|
6105
6549
|
}
|
|
6106
6550
|
const settings = await getRequestSettings(strapi2, ctx);
|
|
@@ -6153,7 +6597,8 @@ var require_bootstrap = __commonJS({
|
|
|
6153
6597
|
log.info("[SUCCESS] Pre-login geo guard mounted");
|
|
6154
6598
|
}
|
|
6155
6599
|
function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
|
|
6156
|
-
|
|
6600
|
+
const logoutPath = `${normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"))}/auth/logout`;
|
|
6601
|
+
if (hasRegisteredRoute(strapi2, "POST", logoutPath)) {
|
|
6157
6602
|
log.debug("[LOGOUT] Using the users-permissions logout route");
|
|
6158
6603
|
return;
|
|
6159
6604
|
}
|
|
@@ -6166,7 +6611,7 @@ var require_bootstrap = __commonJS({
|
|
|
6166
6611
|
strapi2.server.routes([
|
|
6167
6612
|
{
|
|
6168
6613
|
method: "POST",
|
|
6169
|
-
path:
|
|
6614
|
+
path: logoutPath,
|
|
6170
6615
|
handler: async (ctx) => {
|
|
6171
6616
|
try {
|
|
6172
6617
|
const token = extractBearerToken(ctx);
|
|
@@ -6242,6 +6687,9 @@ var require_bootstrap = __commonJS({
|
|
|
6242
6687
|
]);
|
|
6243
6688
|
log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
|
|
6244
6689
|
}
|
|
6690
|
+
function apiPathOf(strapi2, ctx) {
|
|
6691
|
+
return toCanonicalApiPath(ctx.path, strapi2.config.get("api.rest.prefix", "/api"));
|
|
6692
|
+
}
|
|
6245
6693
|
function hasRegisteredRoute(strapi2, method, path) {
|
|
6246
6694
|
try {
|
|
6247
6695
|
const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
|
|
@@ -6275,11 +6723,35 @@ var require_bootstrap = __commonJS({
|
|
|
6275
6723
|
function usesNativeRefreshSessions(strapi2) {
|
|
6276
6724
|
return strapi2.config.get("plugin::users-permissions.jwtManagement", "legacy-support") === "refresh";
|
|
6277
6725
|
}
|
|
6278
|
-
async function
|
|
6279
|
-
|
|
6280
|
-
const
|
|
6281
|
-
if (!
|
|
6282
|
-
throw new Error("
|
|
6726
|
+
async function resolveNativeAccessSession(nativeSessionManager, accessToken) {
|
|
6727
|
+
const validation = await nativeSessionManager.validateAccessToken(accessToken);
|
|
6728
|
+
const payload = validation?.isValid ? validation.payload : null;
|
|
6729
|
+
if (!payload?.userId || !payload?.sessionId) {
|
|
6730
|
+
throw new Error("native access token could not be validated");
|
|
6731
|
+
}
|
|
6732
|
+
const sessionId = String(payload.sessionId);
|
|
6733
|
+
if (!await nativeSessionManager.isSessionActive(sessionId)) {
|
|
6734
|
+
throw new Error("native access token belongs to no active session");
|
|
6735
|
+
}
|
|
6736
|
+
return { userId: String(payload.userId), sessionId };
|
|
6737
|
+
}
|
|
6738
|
+
async function resolveNativeRefreshSession({
|
|
6739
|
+
strapi: strapi2,
|
|
6740
|
+
nativeSessionManager,
|
|
6741
|
+
refreshToken,
|
|
6742
|
+
accessToken = null,
|
|
6743
|
+
user
|
|
6744
|
+
}) {
|
|
6745
|
+
let validation;
|
|
6746
|
+
if (refreshToken) {
|
|
6747
|
+
validation = await nativeSessionManager.validateRefreshToken(refreshToken);
|
|
6748
|
+
if (!validation?.isValid || !validation.userId || !validation.sessionId) {
|
|
6749
|
+
throw new Error("new native refresh token could not be validated");
|
|
6750
|
+
}
|
|
6751
|
+
} else if (typeof accessToken === "string" && accessToken) {
|
|
6752
|
+
validation = await resolveNativeAccessSession(nativeSessionManager, accessToken);
|
|
6753
|
+
} else {
|
|
6754
|
+
throw new Error("native auth response contains no refresh token");
|
|
6283
6755
|
}
|
|
6284
6756
|
const userId = String(validation.userId);
|
|
6285
6757
|
if (user?.id != null && String(user.id) !== userId) {
|
|
@@ -6311,7 +6783,7 @@ var require_bootstrap = __commonJS({
|
|
|
6311
6783
|
const coordinator = getCoordinator(strapi2);
|
|
6312
6784
|
const keyFor = (ip) => hashedKey("lf", ip);
|
|
6313
6785
|
strapi2.server.use(async (ctx, next) => {
|
|
6314
|
-
if (!isFailedLoginTrackedPath(ctx
|
|
6786
|
+
if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
|
|
6315
6787
|
const settings = await getRequestSettings(strapi2, ctx);
|
|
6316
6788
|
const maxFailed = Number(settings.maxFailedLogins) || 0;
|
|
6317
6789
|
if (maxFailed <= 0) return next();
|
|
@@ -6413,13 +6885,34 @@ var require_bootstrap = __commonJS({
|
|
|
6413
6885
|
}
|
|
6414
6886
|
function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
6415
6887
|
strapi2.server.use(async (ctx, next) => {
|
|
6416
|
-
const
|
|
6888
|
+
const apiPath = apiPathOf(strapi2, ctx);
|
|
6889
|
+
const requestType = classifyJwtIssuingRequest(apiPath, ctx.method);
|
|
6417
6890
|
const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
|
|
6418
6891
|
const nativeMode = usesNativeRefreshSessions(strapi2);
|
|
6419
6892
|
await next();
|
|
6893
|
+
if (nativeMode && requestType === null) {
|
|
6894
|
+
await linkCreatedNativeSessions({ strapi: strapi2, ctx, log, sessionService });
|
|
6895
|
+
return;
|
|
6896
|
+
}
|
|
6420
6897
|
if (requestType !== "new-session" && requestType !== "rotate-current") return;
|
|
6421
6898
|
if (ctx.status < 200 || ctx.status >= 300) return;
|
|
6422
6899
|
if (!ctx.body || !ctx.body.jwt) return;
|
|
6900
|
+
if (nativeMode && isThenable(ctx.body.jwt)) {
|
|
6901
|
+
try {
|
|
6902
|
+
ctx.body.jwt = await ctx.body.jwt;
|
|
6903
|
+
} catch (err) {
|
|
6904
|
+
await compensateCreatedNativeSessions({ strapi: strapi2, ctx, log });
|
|
6905
|
+
failClosedAuthResponse({
|
|
6906
|
+
ctx,
|
|
6907
|
+
strapi: strapi2,
|
|
6908
|
+
log,
|
|
6909
|
+
operation: "access token could not be issued",
|
|
6910
|
+
error: err
|
|
6911
|
+
});
|
|
6912
|
+
return;
|
|
6913
|
+
}
|
|
6914
|
+
if (typeof ctx.body.jwt !== "string" || !ctx.body.jwt) return;
|
|
6915
|
+
}
|
|
6423
6916
|
const refreshCookieName = getRefreshCookieName(strapi2);
|
|
6424
6917
|
if (requestType === "rotate-current") {
|
|
6425
6918
|
if (nativeMode) {
|
|
@@ -6433,6 +6926,7 @@ var require_bootstrap = __commonJS({
|
|
|
6433
6926
|
strapi: strapi2,
|
|
6434
6927
|
nativeSessionManager: nativeSessionManager2,
|
|
6435
6928
|
refreshToken: newRefreshToken,
|
|
6929
|
+
accessToken: ctx.body.jwt,
|
|
6436
6930
|
user: ctx.body.user || ctx.state?.user
|
|
6437
6931
|
});
|
|
6438
6932
|
const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
|
|
@@ -6469,6 +6963,12 @@ var require_bootstrap = __commonJS({
|
|
|
6469
6963
|
if (nativeSessionManager2 && nativeSession2) {
|
|
6470
6964
|
await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
|
|
6471
6965
|
}
|
|
6966
|
+
await compensateCreatedNativeSessions({
|
|
6967
|
+
strapi: strapi2,
|
|
6968
|
+
ctx,
|
|
6969
|
+
log,
|
|
6970
|
+
except: nativeSession2?.sessionId
|
|
6971
|
+
});
|
|
6472
6972
|
failClosedAuthResponse({
|
|
6473
6973
|
ctx,
|
|
6474
6974
|
strapi: strapi2,
|
|
@@ -6525,6 +7025,7 @@ var require_bootstrap = __commonJS({
|
|
|
6525
7025
|
strapi: strapi2,
|
|
6526
7026
|
nativeSessionManager,
|
|
6527
7027
|
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
|
|
7028
|
+
accessToken: ctx.body.jwt,
|
|
6528
7029
|
user
|
|
6529
7030
|
});
|
|
6530
7031
|
userDocId = nativeSession.userDocumentId;
|
|
@@ -6550,7 +7051,7 @@ var require_bootstrap = __commonJS({
|
|
|
6550
7051
|
if (!newSession?.documentId) {
|
|
6551
7052
|
throw new Error(`session creation returned no documentId for user ${userDocId}`);
|
|
6552
7053
|
}
|
|
6553
|
-
if (isPasswordResetRequest(
|
|
7054
|
+
if (isPasswordResetRequest(apiPath, ctx.method)) {
|
|
6554
7055
|
await sessionService.terminateSession({
|
|
6555
7056
|
userId: userDocId,
|
|
6556
7057
|
exceptSessionId: newSession.documentId,
|
|
@@ -6685,6 +7186,14 @@ var require_bootstrap = __commonJS({
|
|
|
6685
7186
|
if (nativeSessionManager && nativeSession) {
|
|
6686
7187
|
await compensateNativeSession({ nativeSessionManager, nativeSession, log });
|
|
6687
7188
|
}
|
|
7189
|
+
if (nativeMode) {
|
|
7190
|
+
await compensateCreatedNativeSessions({
|
|
7191
|
+
strapi: strapi2,
|
|
7192
|
+
ctx,
|
|
7193
|
+
log,
|
|
7194
|
+
except: nativeSession?.sessionId
|
|
7195
|
+
});
|
|
7196
|
+
}
|
|
6688
7197
|
failClosedAuthResponse({
|
|
6689
7198
|
ctx,
|
|
6690
7199
|
strapi: strapi2,
|
|
@@ -6696,9 +7205,76 @@ var require_bootstrap = __commonJS({
|
|
|
6696
7205
|
});
|
|
6697
7206
|
log.info("[SUCCESS] Login interceptor middleware mounted");
|
|
6698
7207
|
}
|
|
7208
|
+
async function compensateCreatedNativeSessions({ strapi: strapi2, ctx, log, except = null }) {
|
|
7209
|
+
if (getCreatedNativeSessions(ctx).length === 0) return;
|
|
7210
|
+
try {
|
|
7211
|
+
const nativeSessionManager = getNativeSessionManager(strapi2);
|
|
7212
|
+
if (!nativeSessionManager) return;
|
|
7213
|
+
await revokeCreatedNativeSessions({ ctx, nativeSessionManager, log, except });
|
|
7214
|
+
} catch (err) {
|
|
7215
|
+
log.error("[AUTH-COMPENSATION] Native session revocation failed:", err?.name || "Error");
|
|
7216
|
+
}
|
|
7217
|
+
}
|
|
7218
|
+
async function linkCreatedNativeSessions({ strapi: strapi2, ctx, log, sessionService }) {
|
|
7219
|
+
const created = getCreatedNativeSessions(ctx);
|
|
7220
|
+
if (created.length === 0) return 0;
|
|
7221
|
+
if (ctx.status < 200 || ctx.status >= 300) return 0;
|
|
7222
|
+
let linked = 0;
|
|
7223
|
+
try {
|
|
7224
|
+
const nativeSessionManager = getNativeSessionManager(strapi2);
|
|
7225
|
+
if (!nativeSessionManager) return 0;
|
|
7226
|
+
const ids = [...new Set(created.map((entry) => entry.sessionId))];
|
|
7227
|
+
const existing = await strapi2.db.query(SESSION_UID).findMany({
|
|
7228
|
+
where: { nativeSessionId: { $in: ids } },
|
|
7229
|
+
select: ["nativeSessionId"]
|
|
7230
|
+
});
|
|
7231
|
+
const alreadyLinked = new Set((existing || []).map((row) => String(row.nativeSessionId)));
|
|
7232
|
+
const pending = new Map(
|
|
7233
|
+
created.filter((entry) => !alreadyLinked.has(entry.sessionId)).map((entry) => [entry.sessionId, entry])
|
|
7234
|
+
);
|
|
7235
|
+
if (pending.size === 0) return 0;
|
|
7236
|
+
for (const candidate of findAccessTokenCandidates(ctx.body)) {
|
|
7237
|
+
if (pending.size === 0) break;
|
|
7238
|
+
let session;
|
|
7239
|
+
try {
|
|
7240
|
+
session = await resolveNativeAccessSession(nativeSessionManager, candidate);
|
|
7241
|
+
} catch {
|
|
7242
|
+
continue;
|
|
7243
|
+
}
|
|
7244
|
+
const entry = pending.get(session.sessionId);
|
|
7245
|
+
if (!entry || entry.userId !== session.userId) continue;
|
|
7246
|
+
const userDocumentId = await resolveUserDocumentId(strapi2, session.userId);
|
|
7247
|
+
if (!userDocumentId) continue;
|
|
7248
|
+
const headers = ctx.request?.headers || ctx.request?.header || {};
|
|
7249
|
+
const createdSidecar = await sessionService.createSession({
|
|
7250
|
+
userId: userDocumentId,
|
|
7251
|
+
ip: getClientIp(ctx),
|
|
7252
|
+
userAgent: headers["user-agent"] || "unknown",
|
|
7253
|
+
token: candidate,
|
|
7254
|
+
geoData: ctx.state?.__magicSessionGeoData || null,
|
|
7255
|
+
nativeSessionId: session.sessionId
|
|
7256
|
+
});
|
|
7257
|
+
if (createdSidecar?.documentId) {
|
|
7258
|
+
pending.delete(session.sessionId);
|
|
7259
|
+
linked += 1;
|
|
7260
|
+
}
|
|
7261
|
+
}
|
|
7262
|
+
if (linked > 0) {
|
|
7263
|
+
log.info(`[CAPTURE] Linked ${linked} session(s) created outside the intercepted auth routes`);
|
|
7264
|
+
}
|
|
7265
|
+
if (pending.size > 0) {
|
|
7266
|
+
log.debug(
|
|
7267
|
+
`[CAPTURE] ${pending.size} session(s) created without their token in the response; not tracked`
|
|
7268
|
+
);
|
|
7269
|
+
}
|
|
7270
|
+
} catch (err) {
|
|
7271
|
+
log.warn("[CAPTURE] Linking a session created elsewhere failed:", err?.name || "Error");
|
|
7272
|
+
}
|
|
7273
|
+
return linked;
|
|
7274
|
+
}
|
|
6699
7275
|
function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
6700
7276
|
strapi2.server.use(async (ctx, next) => {
|
|
6701
|
-
const isRefreshToken = ctx
|
|
7277
|
+
const isRefreshToken = apiPathOf(strapi2, ctx) === "/api/auth/refresh" && ctx.method === "POST";
|
|
6702
7278
|
if (!isRefreshToken) return next();
|
|
6703
7279
|
const cookieName = getRefreshCookieName(strapi2);
|
|
6704
7280
|
const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
|
|
@@ -6797,6 +7373,12 @@ var require_bootstrap = __commonJS({
|
|
|
6797
7373
|
if (nativeSession) {
|
|
6798
7374
|
await compensateNativeSession({ nativeSessionManager, nativeSession, log });
|
|
6799
7375
|
}
|
|
7376
|
+
await compensateCreatedNativeSessions({
|
|
7377
|
+
strapi: strapi2,
|
|
7378
|
+
ctx,
|
|
7379
|
+
log,
|
|
7380
|
+
except: nativeSession?.sessionId
|
|
7381
|
+
});
|
|
6800
7382
|
failClosedAuthResponse({
|
|
6801
7383
|
ctx,
|
|
6802
7384
|
strapi: strapi2,
|
|
@@ -6834,7 +7416,7 @@ var require_bootstrap = __commonJS({
|
|
|
6834
7416
|
}
|
|
6835
7417
|
function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
6836
7418
|
strapi2.server.use(async (ctx, next) => {
|
|
6837
|
-
if (ctx
|
|
7419
|
+
if (apiPathOf(strapi2, ctx) !== "/api/auth/logout" || ctx.method !== "POST") return next();
|
|
6838
7420
|
const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
|
|
6839
7421
|
const accessToken = extractBearerToken(ctx);
|
|
6840
7422
|
const nativeMode = usesNativeRefreshSessions(strapi2);
|
|
@@ -7052,8 +7634,14 @@ var require_bootstrap = __commonJS({
|
|
|
7052
7634
|
const knex = strapi2.db.connection;
|
|
7053
7635
|
const tableName = "magic_sessions";
|
|
7054
7636
|
const definitions = [
|
|
7055
|
-
{
|
|
7056
|
-
{
|
|
7637
|
+
{ columns: ["token_hash", "is_active"], name: "idx_magic_sessions_token_hash" },
|
|
7638
|
+
{ columns: ["refresh_token_hash", "is_active"], name: "idx_magic_sessions_refresh_hash" },
|
|
7639
|
+
{ columns: ["login_time", "id"], name: "idx_magic_sessions_login_time" },
|
|
7640
|
+
{ columns: ["last_active", "id"], name: "idx_magic_sessions_last_active" },
|
|
7641
|
+
{ columns: ["is_active", "last_active"], name: "idx_magic_sessions_active_last" },
|
|
7642
|
+
{ columns: ["is_active", "login_time"], name: "idx_magic_sessions_active_login" },
|
|
7643
|
+
{ columns: ["is_active", "termination_reason"], name: "idx_magic_sessions_active_reason" },
|
|
7644
|
+
{ columns: ["native_session_id"], name: "idx_magic_sessions_native_id" }
|
|
7057
7645
|
];
|
|
7058
7646
|
if (!await knex.schema.hasTable(tableName)) return;
|
|
7059
7647
|
const dialect = strapi2.db.dialect.client;
|
|
@@ -7069,11 +7657,11 @@ var require_bootstrap = __commonJS({
|
|
|
7069
7657
|
log.debug(`[INDEX] ${definition.name} already exists`);
|
|
7070
7658
|
continue;
|
|
7071
7659
|
}
|
|
7072
|
-
|
|
7660
|
+
const placeholders = definition.columns.map(() => "??").join(", ");
|
|
7661
|
+
await knex.raw(`CREATE INDEX IF NOT EXISTS ?? ON ?? (${placeholders})`, [
|
|
7073
7662
|
definition.name,
|
|
7074
7663
|
tableName,
|
|
7075
|
-
definition.
|
|
7076
|
-
"is_active"
|
|
7664
|
+
...definition.columns
|
|
7077
7665
|
]);
|
|
7078
7666
|
log.info(`[INDEX] Created ${definition.name}`);
|
|
7079
7667
|
continue;
|
|
@@ -7091,7 +7679,7 @@ var require_bootstrap = __commonJS({
|
|
|
7091
7679
|
continue;
|
|
7092
7680
|
}
|
|
7093
7681
|
await knex.schema.alterTable(tableName, (table) => {
|
|
7094
|
-
table.index(
|
|
7682
|
+
table.index(definition.columns, definition.name);
|
|
7095
7683
|
});
|
|
7096
7684
|
log.info(`[INDEX] Created ${definition.name}`);
|
|
7097
7685
|
}
|
|
@@ -7427,6 +8015,16 @@ var require_destroy = __commonJS({
|
|
|
7427
8015
|
}
|
|
7428
8016
|
strapi2.sessionManagerIntervals = {};
|
|
7429
8017
|
}
|
|
8018
|
+
if (Array.isArray(strapi2.sessionManagerUnsubscribers)) {
|
|
8019
|
+
for (const unsubscribe of strapi2.sessionManagerUnsubscribers) {
|
|
8020
|
+
try {
|
|
8021
|
+
if (typeof unsubscribe === "function") unsubscribe();
|
|
8022
|
+
} catch (err) {
|
|
8023
|
+
log.warn("Failed to remove a database subscriber:", err?.name || "Error");
|
|
8024
|
+
}
|
|
8025
|
+
}
|
|
8026
|
+
strapi2.sessionManagerUnsubscribers = [];
|
|
8027
|
+
}
|
|
7430
8028
|
log.info("[SUCCESS] Plugin cleanup completed");
|
|
7431
8029
|
};
|
|
7432
8030
|
}
|
|
@@ -7814,6 +8412,12 @@ var require_admin = __commonJS({
|
|
|
7814
8412
|
config: { actions: [PLUGIN_ACCESS_ACTION] }
|
|
7815
8413
|
}
|
|
7816
8414
|
];
|
|
8415
|
+
var adminReadRateLimit = () => [
|
|
8416
|
+
{
|
|
8417
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
8418
|
+
config: { profile: "read", max: 120, window: 6e4 }
|
|
8419
|
+
}
|
|
8420
|
+
];
|
|
7817
8421
|
var isDevEnvironment = (() => {
|
|
7818
8422
|
const env = (process.env.NODE_ENV || "development").toLowerCase();
|
|
7819
8423
|
return env !== "production" && env !== "staging";
|
|
@@ -7826,7 +8430,8 @@ var require_admin = __commonJS({
|
|
|
7826
8430
|
handler: "session.getAllSessionsAdmin",
|
|
7827
8431
|
config: {
|
|
7828
8432
|
policies: adminPolicy(),
|
|
7829
|
-
|
|
8433
|
+
middlewares: adminReadRateLimit(),
|
|
8434
|
+
description: "List sessions (admin); paginated with page/pageSize, filters and sort"
|
|
7830
8435
|
}
|
|
7831
8436
|
},
|
|
7832
8437
|
{
|
|
@@ -7835,7 +8440,63 @@ var require_admin = __commonJS({
|
|
|
7835
8440
|
handler: "session.getActiveSessions",
|
|
7836
8441
|
config: {
|
|
7837
8442
|
policies: adminPolicy(),
|
|
7838
|
-
|
|
8443
|
+
middlewares: adminReadRateLimit(),
|
|
8444
|
+
description: "Get only active sessions (admin); paginated with page/pageSize"
|
|
8445
|
+
}
|
|
8446
|
+
},
|
|
8447
|
+
{
|
|
8448
|
+
method: "GET",
|
|
8449
|
+
path: "/sessions/stats",
|
|
8450
|
+
handler: "session.getSessionStatsAdmin",
|
|
8451
|
+
config: {
|
|
8452
|
+
policies: adminPolicy(),
|
|
8453
|
+
middlewares: adminReadRateLimit(),
|
|
8454
|
+
description: "Get count-only session statistics (admin)"
|
|
8455
|
+
}
|
|
8456
|
+
},
|
|
8457
|
+
{
|
|
8458
|
+
method: "GET",
|
|
8459
|
+
path: "/sessions/native-only/summary",
|
|
8460
|
+
handler: "session.getNativeOnlySummaryAdmin",
|
|
8461
|
+
config: {
|
|
8462
|
+
policies: adminPolicy(),
|
|
8463
|
+
middlewares: adminReadRateLimit(),
|
|
8464
|
+
description: "Get count-only diagnostics of untracked Strapi sessions (admin)"
|
|
8465
|
+
}
|
|
8466
|
+
},
|
|
8467
|
+
{
|
|
8468
|
+
method: "POST",
|
|
8469
|
+
path: "/sessions/native-only/end",
|
|
8470
|
+
handler: "session.endNativeOnlySessionsAdmin",
|
|
8471
|
+
config: {
|
|
8472
|
+
policies: adminPolicy(),
|
|
8473
|
+
middlewares: [
|
|
8474
|
+
{
|
|
8475
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
8476
|
+
config: { profile: "write", max: 5, window: 6e4 }
|
|
8477
|
+
}
|
|
8478
|
+
],
|
|
8479
|
+
description: "End untracked Users & Permissions sessions, bounded per request (admin)"
|
|
8480
|
+
}
|
|
8481
|
+
},
|
|
8482
|
+
{
|
|
8483
|
+
method: "GET",
|
|
8484
|
+
path: "/sessions/analytics",
|
|
8485
|
+
handler: "session.getSessionAnalyticsAdmin",
|
|
8486
|
+
config: {
|
|
8487
|
+
policies: adminPolicy(),
|
|
8488
|
+
middlewares: adminReadRateLimit(),
|
|
8489
|
+
description: "Get count-only analytics over all sessions (admin)"
|
|
8490
|
+
}
|
|
8491
|
+
},
|
|
8492
|
+
{
|
|
8493
|
+
method: "GET",
|
|
8494
|
+
path: "/sessions/export",
|
|
8495
|
+
handler: "session.exportSessionsAdmin",
|
|
8496
|
+
config: {
|
|
8497
|
+
policies: adminPolicy(),
|
|
8498
|
+
middlewares: adminReadRateLimit(),
|
|
8499
|
+
description: "Get one export batch of sessions with a keyset cursor (admin)"
|
|
7839
8500
|
}
|
|
7840
8501
|
},
|
|
7841
8502
|
{
|
|
@@ -7898,6 +8559,7 @@ var require_admin = __commonJS({
|
|
|
7898
8559
|
handler: "session.getUserStatsAdmin",
|
|
7899
8560
|
config: {
|
|
7900
8561
|
policies: adminPolicy(),
|
|
8562
|
+
middlewares: adminReadRateLimit(),
|
|
7901
8563
|
description: "Get aggregate end-user counts only (admin)"
|
|
7902
8564
|
}
|
|
7903
8565
|
},
|
|
@@ -8315,6 +8977,529 @@ var require_http_errors = __commonJS({
|
|
|
8315
8977
|
}
|
|
8316
8978
|
});
|
|
8317
8979
|
|
|
8980
|
+
// server/src/utils/session-list-query.js
|
|
8981
|
+
var require_session_list_query = __commonJS({
|
|
8982
|
+
"server/src/utils/session-list-query.js"(exports2, module2) {
|
|
8983
|
+
"use strict";
|
|
8984
|
+
var { z } = require("@strapi/utils");
|
|
8985
|
+
var SESSION_STATUS_FILTERS = Object.freeze(["all", "open", "active", "idle", "ended"]);
|
|
8986
|
+
var RECORDED_END_REASONS = Object.freeze(["logout", "idle", "expired", "manual", "blocked"]);
|
|
8987
|
+
var END_REASON_FILTERS = Object.freeze(["all", ...RECORDED_END_REASONS, "unrecorded"]);
|
|
8988
|
+
var SORT_ORDERS = Object.freeze({
|
|
8989
|
+
"loginTime:desc": [{ loginTime: "desc" }, { id: "desc" }],
|
|
8990
|
+
"loginTime:asc": [{ loginTime: "asc" }, { id: "asc" }],
|
|
8991
|
+
"lastActive:desc": [{ lastActive: "desc" }, { id: "desc" }],
|
|
8992
|
+
"lastActive:asc": [{ lastActive: "asc" }, { id: "asc" }]
|
|
8993
|
+
});
|
|
8994
|
+
var SORT_KEYS = Object.freeze(Object.keys(SORT_ORDERS));
|
|
8995
|
+
var MAX_PAGE_SIZE = 100;
|
|
8996
|
+
var MAX_SEARCH_LENGTH = 100;
|
|
8997
|
+
var MAX_LIST_OFFSET = 5e4;
|
|
8998
|
+
var MAX_EXPORT_BATCH = 1e3;
|
|
8999
|
+
var MAX_EXPORT_ROWS = 5e4;
|
|
9000
|
+
var LIST_FIELDS = Object.freeze([
|
|
9001
|
+
"id",
|
|
9002
|
+
"documentId",
|
|
9003
|
+
"sessionId",
|
|
9004
|
+
"nativeSessionId",
|
|
9005
|
+
"ipAddress",
|
|
9006
|
+
"userAgent",
|
|
9007
|
+
"loginTime",
|
|
9008
|
+
"logoutTime",
|
|
9009
|
+
"lastActive",
|
|
9010
|
+
"isActive",
|
|
9011
|
+
"terminatedManually",
|
|
9012
|
+
"terminationReason",
|
|
9013
|
+
"geoLocation",
|
|
9014
|
+
"securityScore",
|
|
9015
|
+
"deviceType",
|
|
9016
|
+
"browserName",
|
|
9017
|
+
"osName",
|
|
9018
|
+
"createdAt",
|
|
9019
|
+
"updatedAt"
|
|
9020
|
+
]);
|
|
9021
|
+
var LIST_USER_FIELDS = Object.freeze(["documentId", "email", "username"]);
|
|
9022
|
+
var searchText = z.string().trim().max(MAX_SEARCH_LENGTH, `search must be at most ${MAX_SEARCH_LENGTH} characters`);
|
|
9023
|
+
var filterShape = {
|
|
9024
|
+
status: z.enum(SESSION_STATUS_FILTERS).default("all"),
|
|
9025
|
+
reason: z.enum(END_REASON_FILTERS).default("all"),
|
|
9026
|
+
search: searchText.default("")
|
|
9027
|
+
};
|
|
9028
|
+
var listQuerySchema = z.strictObject({
|
|
9029
|
+
page: z.coerce.number().int().min(1).max(1e6).default(1),
|
|
9030
|
+
pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(25),
|
|
9031
|
+
sort: z.enum(SORT_KEYS).default("loginTime:desc"),
|
|
9032
|
+
...filterShape
|
|
9033
|
+
}).refine((query) => (query.page - 1) * query.pageSize < MAX_LIST_OFFSET, {
|
|
9034
|
+
message: `Pages past the first ${MAX_LIST_OFFSET} sessions are not available. Narrow the filter or use the export.`,
|
|
9035
|
+
path: ["page"]
|
|
9036
|
+
});
|
|
9037
|
+
var exportQuerySchema = z.strictObject({
|
|
9038
|
+
limit: z.coerce.number().int().min(1).max(MAX_EXPORT_BATCH).default(MAX_EXPORT_BATCH),
|
|
9039
|
+
cursor: z.string().max(200).optional(),
|
|
9040
|
+
...filterShape
|
|
9041
|
+
});
|
|
9042
|
+
var statsQuerySchema = z.strictObject({});
|
|
9043
|
+
function isPaginatedListQuery(query) {
|
|
9044
|
+
return Boolean(
|
|
9045
|
+
query && (Object.prototype.hasOwnProperty.call(query, "page") || Object.prototype.hasOwnProperty.call(query, "pageSize"))
|
|
9046
|
+
);
|
|
9047
|
+
}
|
|
9048
|
+
function parseQuery(schema, input) {
|
|
9049
|
+
const result = schema.safeParse(input ?? {});
|
|
9050
|
+
if (result.success) return { ok: true, value: result.data };
|
|
9051
|
+
return {
|
|
9052
|
+
ok: false,
|
|
9053
|
+
errors: result.error.issues.map((issue) => ({
|
|
9054
|
+
path: issue.path.join("."),
|
|
9055
|
+
message: issue.message
|
|
9056
|
+
}))
|
|
9057
|
+
};
|
|
9058
|
+
}
|
|
9059
|
+
function usedSince(cutoff) {
|
|
9060
|
+
return {
|
|
9061
|
+
$or: [
|
|
9062
|
+
{ lastActive: { $gt: cutoff } },
|
|
9063
|
+
{ $and: [{ lastActive: { $null: true } }, { loginTime: { $gt: cutoff } }] }
|
|
9064
|
+
]
|
|
9065
|
+
};
|
|
9066
|
+
}
|
|
9067
|
+
function notUsedSince(cutoff) {
|
|
9068
|
+
return {
|
|
9069
|
+
$or: [
|
|
9070
|
+
{ lastActive: { $lte: cutoff } },
|
|
9071
|
+
{ $and: [{ lastActive: { $null: true } }, { loginTime: { $lte: cutoff } }] }
|
|
9072
|
+
]
|
|
9073
|
+
};
|
|
9074
|
+
}
|
|
9075
|
+
function buildSessionWhere({ status = "all", reason = "all", search = "" } = {}, { cutoff }) {
|
|
9076
|
+
const conditions = [];
|
|
9077
|
+
if (status === "open") conditions.push({ isActive: true });
|
|
9078
|
+
if (status === "active") conditions.push({ isActive: true }, usedSince(cutoff));
|
|
9079
|
+
if (status === "idle") conditions.push({ isActive: true }, notUsedSince(cutoff));
|
|
9080
|
+
if (status === "ended") {
|
|
9081
|
+
conditions.push({ isActive: false });
|
|
9082
|
+
if (reason === "unrecorded") {
|
|
9083
|
+
conditions.push({
|
|
9084
|
+
$or: [
|
|
9085
|
+
{ terminationReason: { $null: true } },
|
|
9086
|
+
{ terminationReason: { $notIn: [...RECORDED_END_REASONS] } }
|
|
9087
|
+
]
|
|
9088
|
+
});
|
|
9089
|
+
} else if (RECORDED_END_REASONS.includes(reason)) {
|
|
9090
|
+
conditions.push({ terminationReason: reason });
|
|
9091
|
+
}
|
|
9092
|
+
}
|
|
9093
|
+
if (search) {
|
|
9094
|
+
conditions.push({
|
|
9095
|
+
$or: [
|
|
9096
|
+
{ user: { email: { $containsi: search } } },
|
|
9097
|
+
{ user: { username: { $containsi: search } } },
|
|
9098
|
+
{ ipAddress: { $containsi: search } },
|
|
9099
|
+
{ browserName: { $containsi: search } },
|
|
9100
|
+
{ osName: { $containsi: search } },
|
|
9101
|
+
{ deviceType: { $containsi: search } }
|
|
9102
|
+
]
|
|
9103
|
+
});
|
|
9104
|
+
}
|
|
9105
|
+
return conditions.length ? { $and: conditions } : {};
|
|
9106
|
+
}
|
|
9107
|
+
function encodeExportCursor(row) {
|
|
9108
|
+
const time = row.loginTime ? new Date(row.loginTime).toISOString() : null;
|
|
9109
|
+
return Buffer.from(JSON.stringify([time, Number(row.id)])).toString("base64url");
|
|
9110
|
+
}
|
|
9111
|
+
function decodeExportCursor(cursor) {
|
|
9112
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
9113
|
+
if (!/^[A-Za-z0-9_-]+$/.test(cursor)) return false;
|
|
9114
|
+
try {
|
|
9115
|
+
const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
9116
|
+
if (!Array.isArray(value) || value.length !== 2) return false;
|
|
9117
|
+
const [time, id] = value;
|
|
9118
|
+
if (!Number.isSafeInteger(id) || id < 1) return false;
|
|
9119
|
+
if (time === null) return { loginTime: null, id };
|
|
9120
|
+
if (typeof time !== "string" || Number.isNaN(Date.parse(time))) return false;
|
|
9121
|
+
return { loginTime: new Date(time), id };
|
|
9122
|
+
} catch {
|
|
9123
|
+
return false;
|
|
9124
|
+
}
|
|
9125
|
+
}
|
|
9126
|
+
function afterExportCursor(cursor) {
|
|
9127
|
+
if (cursor.loginTime === null) return { id: { $lt: cursor.id } };
|
|
9128
|
+
return {
|
|
9129
|
+
$or: [
|
|
9130
|
+
{ loginTime: { $lt: cursor.loginTime } },
|
|
9131
|
+
{ $and: [{ loginTime: cursor.loginTime }, { id: { $lt: cursor.id } }] }
|
|
9132
|
+
]
|
|
9133
|
+
};
|
|
9134
|
+
}
|
|
9135
|
+
module2.exports = {
|
|
9136
|
+
SESSION_STATUS_FILTERS,
|
|
9137
|
+
RECORDED_END_REASONS,
|
|
9138
|
+
END_REASON_FILTERS,
|
|
9139
|
+
SORT_ORDERS,
|
|
9140
|
+
SORT_KEYS,
|
|
9141
|
+
MAX_PAGE_SIZE,
|
|
9142
|
+
MAX_SEARCH_LENGTH,
|
|
9143
|
+
MAX_LIST_OFFSET,
|
|
9144
|
+
MAX_EXPORT_BATCH,
|
|
9145
|
+
MAX_EXPORT_ROWS,
|
|
9146
|
+
LIST_FIELDS,
|
|
9147
|
+
LIST_USER_FIELDS,
|
|
9148
|
+
listQuerySchema,
|
|
9149
|
+
exportQuerySchema,
|
|
9150
|
+
statsQuerySchema,
|
|
9151
|
+
isPaginatedListQuery,
|
|
9152
|
+
parseQuery,
|
|
9153
|
+
buildSessionWhere,
|
|
9154
|
+
encodeExportCursor,
|
|
9155
|
+
decodeExportCursor,
|
|
9156
|
+
afterExportCursor
|
|
9157
|
+
};
|
|
9158
|
+
}
|
|
9159
|
+
});
|
|
9160
|
+
|
|
9161
|
+
// server/src/utils/session-list.js
|
|
9162
|
+
var require_session_list = __commonJS({
|
|
9163
|
+
"server/src/utils/session-list.js"(exports2, module2) {
|
|
9164
|
+
"use strict";
|
|
9165
|
+
var { enhanceSessions } = require_enhance_session();
|
|
9166
|
+
var { getNativeSessionManager } = require_native_session_manager();
|
|
9167
|
+
var {
|
|
9168
|
+
canInspectNativeSessions,
|
|
9169
|
+
countNativeOnly,
|
|
9170
|
+
getNativeTrackingSince
|
|
9171
|
+
} = require_native_only_insight();
|
|
9172
|
+
var {
|
|
9173
|
+
LIST_FIELDS,
|
|
9174
|
+
LIST_USER_FIELDS,
|
|
9175
|
+
MAX_EXPORT_BATCH,
|
|
9176
|
+
SORT_ORDERS,
|
|
9177
|
+
buildSessionWhere,
|
|
9178
|
+
afterExportCursor,
|
|
9179
|
+
encodeExportCursor
|
|
9180
|
+
} = require_session_list_query();
|
|
9181
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
9182
|
+
var NATIVE_SESSION_UID = "admin::session";
|
|
9183
|
+
var NATIVE_ORIGIN = "users-permissions";
|
|
9184
|
+
var NATIVE_CHECK_CONCURRENCY = 8;
|
|
9185
|
+
var STATS_CACHE_MS = 5e3;
|
|
9186
|
+
var statsCache = /* @__PURE__ */ new WeakMap();
|
|
9187
|
+
function clearSessionStatsCache() {
|
|
9188
|
+
statsCache = /* @__PURE__ */ new WeakMap();
|
|
9189
|
+
}
|
|
9190
|
+
function cacheFor(strapi2) {
|
|
9191
|
+
let map = statsCache.get(strapi2);
|
|
9192
|
+
if (!map) {
|
|
9193
|
+
map = /* @__PURE__ */ new Map();
|
|
9194
|
+
statsCache.set(strapi2, map);
|
|
9195
|
+
}
|
|
9196
|
+
return map;
|
|
9197
|
+
}
|
|
9198
|
+
function inactivityCutoff(inactivityTimeout, now = Date.now()) {
|
|
9199
|
+
return new Date(now - inactivityTimeout);
|
|
9200
|
+
}
|
|
9201
|
+
function hasNativeSessionTable(strapi2) {
|
|
9202
|
+
return Boolean(strapi2?.contentTypes?.[NATIVE_SESSION_UID]);
|
|
9203
|
+
}
|
|
9204
|
+
async function findActiveNativeIds(strapi2, nativeManager, ids) {
|
|
9205
|
+
const unique = [...new Set(ids.filter((id) => typeof id === "string" && id))];
|
|
9206
|
+
if (unique.length === 0) return /* @__PURE__ */ new Set();
|
|
9207
|
+
if (hasNativeSessionTable(strapi2)) {
|
|
9208
|
+
const rows = await strapi2.db.query(NATIVE_SESSION_UID).findMany({
|
|
9209
|
+
select: ["sessionId"],
|
|
9210
|
+
where: {
|
|
9211
|
+
sessionId: { $in: unique },
|
|
9212
|
+
origin: NATIVE_ORIGIN,
|
|
9213
|
+
status: "active",
|
|
9214
|
+
expiresAt: { $gt: /* @__PURE__ */ new Date() }
|
|
9215
|
+
}
|
|
9216
|
+
});
|
|
9217
|
+
return new Set((Array.isArray(rows) ? rows : []).map((row) => String(row.sessionId)));
|
|
9218
|
+
}
|
|
9219
|
+
const active = /* @__PURE__ */ new Set();
|
|
9220
|
+
let next = 0;
|
|
9221
|
+
const worker = async () => {
|
|
9222
|
+
while (next < unique.length) {
|
|
9223
|
+
const id = unique[next++];
|
|
9224
|
+
if (await nativeManager.isSessionActive(id)) active.add(id);
|
|
9225
|
+
}
|
|
9226
|
+
};
|
|
9227
|
+
await Promise.all(
|
|
9228
|
+
Array.from({ length: Math.min(NATIVE_CHECK_CONCURRENCY, unique.length) }, worker)
|
|
9229
|
+
);
|
|
9230
|
+
return active;
|
|
9231
|
+
}
|
|
9232
|
+
async function reconcileNativeRows(strapi2, rows) {
|
|
9233
|
+
const nativeManager = getNativeSessionManager(strapi2);
|
|
9234
|
+
if (!nativeManager) return rows;
|
|
9235
|
+
const ids = rows.filter((row) => row.isActive && row.nativeSessionId).map((row) => String(row.nativeSessionId));
|
|
9236
|
+
if (ids.length === 0) return rows;
|
|
9237
|
+
const active = await findActiveNativeIds(strapi2, nativeManager, ids);
|
|
9238
|
+
return rows.map(
|
|
9239
|
+
(row) => row.isActive && row.nativeSessionId && !active.has(String(row.nativeSessionId)) ? { ...row, isActive: false } : row
|
|
9240
|
+
);
|
|
9241
|
+
}
|
|
9242
|
+
async function countNativeOnlySessions(strapi2) {
|
|
9243
|
+
const { total } = await countNativeOnly(strapi2);
|
|
9244
|
+
return total;
|
|
9245
|
+
}
|
|
9246
|
+
async function countNativeOnlySplit(strapi2) {
|
|
9247
|
+
if (!canInspectNativeSessions(strapi2)) return { total: 0, afterTracking: null };
|
|
9248
|
+
const trackingSince = await getNativeTrackingSince(strapi2);
|
|
9249
|
+
return countNativeOnly(strapi2, { trackingSince });
|
|
9250
|
+
}
|
|
9251
|
+
async function countUsersOnline(strapi2, cutoff) {
|
|
9252
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
9253
|
+
const userAttribute = meta.attributes.user;
|
|
9254
|
+
const joinTable = userAttribute?.joinTable;
|
|
9255
|
+
const column = (attribute) => meta.attributes[attribute]?.columnName || attribute;
|
|
9256
|
+
const knex = strapi2.db.connection;
|
|
9257
|
+
const table = meta.tableName;
|
|
9258
|
+
if (joinTable?.name && joinTable.joinColumn?.name && joinTable.inverseJoinColumn?.name) {
|
|
9259
|
+
const link = joinTable.name;
|
|
9260
|
+
const lastActive = `${table}.${column("lastActive")}`;
|
|
9261
|
+
const loginTime = `${table}.${column("loginTime")}`;
|
|
9262
|
+
const result = await knex(table).join(link, `${link}.${joinTable.joinColumn.name}`, `${table}.id`).where(`${table}.${column("isActive")}`, true).andWhere((qb) => {
|
|
9263
|
+
qb.where(lastActive, ">", cutoff).orWhere((inner) => {
|
|
9264
|
+
inner.whereNull(lastActive).andWhere(loginTime, ">", cutoff);
|
|
9265
|
+
});
|
|
9266
|
+
}).countDistinct({ count: `${link}.${joinTable.inverseJoinColumn.name}` }).first();
|
|
9267
|
+
return Number(result?.count ?? 0);
|
|
9268
|
+
}
|
|
9269
|
+
const seen = /* @__PURE__ */ new Set();
|
|
9270
|
+
const where = buildSessionWhere({ status: "active" }, { cutoff });
|
|
9271
|
+
for (let offset = 0; ; offset += MAX_EXPORT_BATCH) {
|
|
9272
|
+
const rows = await strapi2.db.query(SESSION_UID).findMany({
|
|
9273
|
+
where,
|
|
9274
|
+
select: ["id"],
|
|
9275
|
+
populate: { user: { select: ["id"] } },
|
|
9276
|
+
orderBy: [{ id: "asc" }],
|
|
9277
|
+
offset,
|
|
9278
|
+
limit: MAX_EXPORT_BATCH
|
|
9279
|
+
});
|
|
9280
|
+
for (const row of rows) if (row.user?.id) seen.add(row.user.id);
|
|
9281
|
+
if (rows.length < MAX_EXPORT_BATCH) break;
|
|
9282
|
+
}
|
|
9283
|
+
return seen.size;
|
|
9284
|
+
}
|
|
9285
|
+
async function listSessionPage(strapi2, query, options) {
|
|
9286
|
+
const cutoff = inactivityCutoff(options.inactivityTimeout);
|
|
9287
|
+
const where = buildSessionWhere(query, { cutoff });
|
|
9288
|
+
const sessions = strapi2.db.query(SESSION_UID);
|
|
9289
|
+
const offset = (query.page - 1) * query.pageSize;
|
|
9290
|
+
const [total, rows] = await Promise.all([
|
|
9291
|
+
sessions.count({ where }),
|
|
9292
|
+
sessions.findMany({
|
|
9293
|
+
where,
|
|
9294
|
+
select: [...LIST_FIELDS],
|
|
9295
|
+
populate: { user: { select: [...LIST_USER_FIELDS] } },
|
|
9296
|
+
orderBy: SORT_ORDERS[query.sort] || SORT_ORDERS["loginTime:desc"],
|
|
9297
|
+
offset,
|
|
9298
|
+
limit: query.pageSize
|
|
9299
|
+
})
|
|
9300
|
+
]);
|
|
9301
|
+
const reconciled = await reconcileNativeRows(strapi2, Array.isArray(rows) ? rows : []);
|
|
9302
|
+
const enhanced = await enhanceSessions(
|
|
9303
|
+
reconciled,
|
|
9304
|
+
{
|
|
9305
|
+
inactivityTimeout: options.inactivityTimeout,
|
|
9306
|
+
geolocationService: options.geolocationService || null,
|
|
9307
|
+
strapi: strapi2
|
|
9308
|
+
},
|
|
9309
|
+
Math.min(20, query.pageSize)
|
|
9310
|
+
);
|
|
9311
|
+
const count = Number(total) || 0;
|
|
9312
|
+
return {
|
|
9313
|
+
rows: enhanced,
|
|
9314
|
+
pagination: {
|
|
9315
|
+
page: query.page,
|
|
9316
|
+
pageSize: query.pageSize,
|
|
9317
|
+
total: count,
|
|
9318
|
+
pageCount: Math.max(1, Math.ceil(count / query.pageSize))
|
|
9319
|
+
}
|
|
9320
|
+
};
|
|
9321
|
+
}
|
|
9322
|
+
async function getSessionStats(strapi2, { inactivityTimeout }) {
|
|
9323
|
+
const key = String(inactivityTimeout);
|
|
9324
|
+
const cache = cacheFor(strapi2);
|
|
9325
|
+
const cached = cache.get(key);
|
|
9326
|
+
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
9327
|
+
const cutoff = inactivityCutoff(inactivityTimeout);
|
|
9328
|
+
const sessions = strapi2.db.query(SESSION_UID);
|
|
9329
|
+
const count = (filters) => sessions.count({ where: buildSessionWhere(filters, { cutoff }) });
|
|
9330
|
+
const [total, open, active, loggedOut, timedOut, usersOnline, nativeOnly] = await Promise.all([
|
|
9331
|
+
count({}),
|
|
9332
|
+
count({ status: "open" }),
|
|
9333
|
+
count({ status: "active" }),
|
|
9334
|
+
count({ status: "ended", reason: "logout" }),
|
|
9335
|
+
count({ status: "ended", reason: "idle" }),
|
|
9336
|
+
countUsersOnline(strapi2, cutoff),
|
|
9337
|
+
countNativeOnlySplit(strapi2)
|
|
9338
|
+
]);
|
|
9339
|
+
const ended = Math.max(0, Number(total) - Number(open));
|
|
9340
|
+
const value = {
|
|
9341
|
+
total: Number(total),
|
|
9342
|
+
open: Number(open),
|
|
9343
|
+
active: Number(active),
|
|
9344
|
+
idle: Math.max(0, Number(open) - Number(active)),
|
|
9345
|
+
ended,
|
|
9346
|
+
loggedOut: Number(loggedOut),
|
|
9347
|
+
timedOut: Number(timedOut),
|
|
9348
|
+
otherReasons: Math.max(0, ended - Number(loggedOut) - Number(timedOut)),
|
|
9349
|
+
usersOnline: Number(usersOnline),
|
|
9350
|
+
nativeOnly: nativeOnly.total,
|
|
9351
|
+
nativeOnlyAfterTracking: nativeOnly.afterTracking
|
|
9352
|
+
};
|
|
9353
|
+
cache.set(key, { value, expiresAt: Date.now() + STATS_CACHE_MS });
|
|
9354
|
+
if (cache.size > 20) cache.delete(cache.keys().next().value);
|
|
9355
|
+
return value;
|
|
9356
|
+
}
|
|
9357
|
+
var ANALYTICS_CACHE_MS = 3e4;
|
|
9358
|
+
var MAX_GROUPS = 200;
|
|
9359
|
+
async function countByColumn(strapi2, attribute) {
|
|
9360
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
9361
|
+
const column = meta.attributes[attribute]?.columnName || attribute;
|
|
9362
|
+
const rows = await strapi2.db.connection(meta.tableName).select({ value: column }).count({ count: "*" }).groupBy(column).orderBy("count", "desc").limit(MAX_GROUPS);
|
|
9363
|
+
return rows.map((row) => ({ value: row.value ?? null, count: Number(row.count) || 0 }));
|
|
9364
|
+
}
|
|
9365
|
+
async function averageSessionMinutes(strapi2, now) {
|
|
9366
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
9367
|
+
const col = (attribute) => meta.attributes[attribute]?.columnName || attribute;
|
|
9368
|
+
const knex = strapi2.db.connection;
|
|
9369
|
+
const client = strapi2.db.dialect?.client || "";
|
|
9370
|
+
const end = `CASE WHEN ?? THEN COALESCE(??, ?) ELSE COALESCE(??, ??) END`;
|
|
9371
|
+
const endBindings = [
|
|
9372
|
+
col("isActive"),
|
|
9373
|
+
col("lastActive"),
|
|
9374
|
+
now,
|
|
9375
|
+
col("logoutTime"),
|
|
9376
|
+
col("lastActive")
|
|
9377
|
+
];
|
|
9378
|
+
if (client === "postgres") {
|
|
9379
|
+
const row = await knex(meta.tableName).select(
|
|
9380
|
+
knex.raw(`AVG(GREATEST(0, FLOOR(EXTRACT(EPOCH FROM ((${end}) - ??)) / 60))) AS avg`, [
|
|
9381
|
+
...endBindings,
|
|
9382
|
+
col("loginTime")
|
|
9383
|
+
])
|
|
9384
|
+
).first();
|
|
9385
|
+
return Math.floor(Number(row?.avg) || 0);
|
|
9386
|
+
}
|
|
9387
|
+
if (client === "mysql" || client === "mysql2") {
|
|
9388
|
+
const row = await knex(meta.tableName).select(
|
|
9389
|
+
knex.raw(`AVG(GREATEST(0, FLOOR(TIMESTAMPDIFF(SECOND, ??, (${end})) / 60))) AS avg`, [
|
|
9390
|
+
col("loginTime"),
|
|
9391
|
+
...endBindings
|
|
9392
|
+
])
|
|
9393
|
+
).first();
|
|
9394
|
+
return Math.floor(Number(row?.avg) || 0);
|
|
9395
|
+
}
|
|
9396
|
+
let sum = 0;
|
|
9397
|
+
let count = 0;
|
|
9398
|
+
let lastId = 0;
|
|
9399
|
+
const nowMs = now.getTime();
|
|
9400
|
+
for (; ; ) {
|
|
9401
|
+
const rows = await strapi2.db.query(SESSION_UID).findMany({
|
|
9402
|
+
select: ["id", "loginTime", "lastActive", "logoutTime", "isActive"],
|
|
9403
|
+
where: { id: { $gt: lastId } },
|
|
9404
|
+
orderBy: [{ id: "asc" }],
|
|
9405
|
+
limit: 5e3
|
|
9406
|
+
});
|
|
9407
|
+
for (const row of rows) {
|
|
9408
|
+
const start = Date.parse(row.loginTime);
|
|
9409
|
+
if (!Number.isFinite(start)) continue;
|
|
9410
|
+
const lastActive = row.lastActive ? Date.parse(row.lastActive) : Number.NaN;
|
|
9411
|
+
const logout = row.logoutTime ? Date.parse(row.logoutTime) : Number.NaN;
|
|
9412
|
+
let stop;
|
|
9413
|
+
if (row.isActive) stop = Number.isFinite(lastActive) ? lastActive : nowMs;
|
|
9414
|
+
else stop = Number.isFinite(logout) ? logout : lastActive;
|
|
9415
|
+
if (!Number.isFinite(stop)) continue;
|
|
9416
|
+
sum += Math.max(0, Math.floor((stop - start) / 6e4));
|
|
9417
|
+
count += 1;
|
|
9418
|
+
}
|
|
9419
|
+
if (rows.length < 5e3) break;
|
|
9420
|
+
lastId = rows[rows.length - 1].id;
|
|
9421
|
+
}
|
|
9422
|
+
return count > 0 ? Math.floor(sum / count) : 0;
|
|
9423
|
+
}
|
|
9424
|
+
async function countUsersWithSessions(strapi2) {
|
|
9425
|
+
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
9426
|
+
const joinTable = meta.attributes.user?.joinTable;
|
|
9427
|
+
if (!joinTable?.name || !joinTable.inverseJoinColumn?.name) return 0;
|
|
9428
|
+
const row = await strapi2.db.connection(joinTable.name).countDistinct({ count: joinTable.inverseJoinColumn.name }).first();
|
|
9429
|
+
return Number(row?.count ?? 0);
|
|
9430
|
+
}
|
|
9431
|
+
async function getSessionAnalytics(strapi2, { inactivityTimeout }) {
|
|
9432
|
+
const key = `analytics:${inactivityTimeout}`;
|
|
9433
|
+
const cache = cacheFor(strapi2);
|
|
9434
|
+
const cached = cache.get(key);
|
|
9435
|
+
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
9436
|
+
const now = /* @__PURE__ */ new Date();
|
|
9437
|
+
const sessions = strapi2.db.query(SESSION_UID);
|
|
9438
|
+
const since = (ms) => sessions.count({ where: { loginTime: { $gt: new Date(now - ms) } } });
|
|
9439
|
+
const [stats, signIns24h, signIns7d, devices, browsers, uniqueUsers, avgSessionDuration] = await Promise.all([
|
|
9440
|
+
getSessionStats(strapi2, { inactivityTimeout }),
|
|
9441
|
+
since(24 * 60 * 60 * 1e3),
|
|
9442
|
+
since(7 * 24 * 60 * 60 * 1e3),
|
|
9443
|
+
countByColumn(strapi2, "deviceType"),
|
|
9444
|
+
countByColumn(strapi2, "browserName"),
|
|
9445
|
+
countUsersWithSessions(strapi2),
|
|
9446
|
+
averageSessionMinutes(strapi2, now)
|
|
9447
|
+
]);
|
|
9448
|
+
const value = {
|
|
9449
|
+
totalSessions: stats.total,
|
|
9450
|
+
activeSessions: stats.active,
|
|
9451
|
+
idleSessions: stats.idle,
|
|
9452
|
+
endedSessions: stats.ended,
|
|
9453
|
+
signInsLast24Hours: Number(signIns24h),
|
|
9454
|
+
signInsLast7Days: Number(signIns7d),
|
|
9455
|
+
devices,
|
|
9456
|
+
browsers,
|
|
9457
|
+
uniqueUsers,
|
|
9458
|
+
avgSessionDuration
|
|
9459
|
+
};
|
|
9460
|
+
cache.set(key, { value, expiresAt: Date.now() + ANALYTICS_CACHE_MS });
|
|
9461
|
+
return value;
|
|
9462
|
+
}
|
|
9463
|
+
async function exportSessionBatch(strapi2, query, cursor, { inactivityTimeout }) {
|
|
9464
|
+
const cutoff = inactivityCutoff(inactivityTimeout);
|
|
9465
|
+
const base = buildSessionWhere(query, { cutoff });
|
|
9466
|
+
const where = cursor ? { $and: [...base.$and ? base.$and : [], afterExportCursor(cursor)] } : base;
|
|
9467
|
+
const rows = await strapi2.db.query(SESSION_UID).findMany({
|
|
9468
|
+
where,
|
|
9469
|
+
select: [...LIST_FIELDS],
|
|
9470
|
+
populate: { user: { select: [...LIST_USER_FIELDS] } },
|
|
9471
|
+
orderBy: SORT_ORDERS["loginTime:desc"],
|
|
9472
|
+
limit: query.limit
|
|
9473
|
+
});
|
|
9474
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
9475
|
+
const reconciled = await reconcileNativeRows(strapi2, list);
|
|
9476
|
+
const enhanced = await enhanceSessions(
|
|
9477
|
+
reconciled,
|
|
9478
|
+
{ inactivityTimeout, geolocationService: null, strapi: strapi2 },
|
|
9479
|
+
0
|
|
9480
|
+
);
|
|
9481
|
+
const last = list[list.length - 1];
|
|
9482
|
+
return {
|
|
9483
|
+
rows: enhanced,
|
|
9484
|
+
nextCursor: list.length === query.limit && last ? encodeExportCursor(last) : null
|
|
9485
|
+
};
|
|
9486
|
+
}
|
|
9487
|
+
module2.exports = {
|
|
9488
|
+
STATS_CACHE_MS,
|
|
9489
|
+
ANALYTICS_CACHE_MS,
|
|
9490
|
+
listSessionPage,
|
|
9491
|
+
getSessionStats,
|
|
9492
|
+
getSessionAnalytics,
|
|
9493
|
+
exportSessionBatch,
|
|
9494
|
+
countUsersOnline,
|
|
9495
|
+
countNativeOnlySessions,
|
|
9496
|
+
reconcileNativeRows,
|
|
9497
|
+
clearSessionStatsCache,
|
|
9498
|
+
inactivityCutoff
|
|
9499
|
+
};
|
|
9500
|
+
}
|
|
9501
|
+
});
|
|
9502
|
+
|
|
8318
9503
|
// server/src/controllers/session.js
|
|
8319
9504
|
var require_session = __commonJS({
|
|
8320
9505
|
"server/src/controllers/session.js"(exports2, module2) {
|
|
@@ -8332,12 +9517,29 @@ var require_session = __commonJS({
|
|
|
8332
9517
|
var { runWithCallerRevocation } = require_block_revocation_scope();
|
|
8333
9518
|
var { sendServerError } = require_http_errors();
|
|
8334
9519
|
var { getCoordinator } = require_coordination();
|
|
9520
|
+
var { clearSessionStatsCache } = require_session_list();
|
|
9521
|
+
var {
|
|
9522
|
+
getNativeOnlySummary,
|
|
9523
|
+
endNativeOnlySessions,
|
|
9524
|
+
END_MAX_ROWS
|
|
9525
|
+
} = require_native_only_insight();
|
|
9526
|
+
var { LockTimeoutError } = require_coordination();
|
|
9527
|
+
var {
|
|
9528
|
+
decodeExportCursor,
|
|
9529
|
+
exportQuerySchema,
|
|
9530
|
+
isPaginatedListQuery,
|
|
9531
|
+
listQuerySchema,
|
|
9532
|
+
parseQuery,
|
|
9533
|
+
statsQuerySchema
|
|
9534
|
+
} = require_session_list_query();
|
|
8335
9535
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
8336
9536
|
var USER_UID = "plugin::users-permissions.user";
|
|
8337
9537
|
var OWN_SESSIONS_LIMIT = 200;
|
|
8338
9538
|
var NATIVE_SESSION_KEY_PREFIX = "native_";
|
|
8339
9539
|
var JWT_MANAGEMENT_CONFIG = "plugin::users-permissions.jwtManagement";
|
|
8340
9540
|
var LEGACY_JWT_MANAGEMENT = "legacy-support";
|
|
9541
|
+
var USER_STATS_CACHE_MS = 5e3;
|
|
9542
|
+
var userStatsCache = { owner: null, value: null, expiresAt: 0 };
|
|
8341
9543
|
function createDisabledGeolocationResult(ipAddress) {
|
|
8342
9544
|
return {
|
|
8343
9545
|
ip: ipAddress,
|
|
@@ -8412,6 +9614,55 @@ var require_session = __commonJS({
|
|
|
8412
9614
|
function getTruncationMeta(sessions) {
|
|
8413
9615
|
return sessions?.truncated === true ? { truncated: true } : {};
|
|
8414
9616
|
}
|
|
9617
|
+
async function listSessionsAdmin(ctx, { activeOnly }) {
|
|
9618
|
+
if (isPaginatedListQuery(ctx.query)) {
|
|
9619
|
+
const parsed = parseQuery(listQuerySchema, ctx.query);
|
|
9620
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
9621
|
+
const query = activeOnly ? { ...parsed.value, status: "active", reason: "all" } : parsed.value;
|
|
9622
|
+
try {
|
|
9623
|
+
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9624
|
+
const page = await sessionService.listSessionPage(query);
|
|
9625
|
+
ctx.body = {
|
|
9626
|
+
data: toPublicSessions(page.rows, { admin: true }),
|
|
9627
|
+
meta: { pagination: page.pagination }
|
|
9628
|
+
};
|
|
9629
|
+
return void 0;
|
|
9630
|
+
} catch (err) {
|
|
9631
|
+
strapi.log.error("[magic-sessionmanager] listSessionPage failed:", err?.name || "Error");
|
|
9632
|
+
return ctx.internalServerError("Error fetching sessions");
|
|
9633
|
+
}
|
|
9634
|
+
}
|
|
9635
|
+
try {
|
|
9636
|
+
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9637
|
+
if (activeOnly) {
|
|
9638
|
+
const sessions2 = await sessionService.getActiveSessions();
|
|
9639
|
+
ctx.body = {
|
|
9640
|
+
data: toPublicSessions(sessions2, { admin: true }),
|
|
9641
|
+
meta: { count: sessions2.length, ...getTruncationMeta(sessions2) }
|
|
9642
|
+
};
|
|
9643
|
+
return void 0;
|
|
9644
|
+
}
|
|
9645
|
+
const sessions = await sessionService.getAllSessions();
|
|
9646
|
+
ctx.body = {
|
|
9647
|
+
data: toPublicSessions(sessions, { admin: true }),
|
|
9648
|
+
meta: {
|
|
9649
|
+
count: sessions.length,
|
|
9650
|
+
active: sessions.filter((s) => s.isTrulyActive).length,
|
|
9651
|
+
inactive: sessions.filter((s) => !s.isTrulyActive).length,
|
|
9652
|
+
...getTruncationMeta(sessions)
|
|
9653
|
+
}
|
|
9654
|
+
};
|
|
9655
|
+
return void 0;
|
|
9656
|
+
} catch (err) {
|
|
9657
|
+
strapi.log.error(
|
|
9658
|
+
`[magic-sessionmanager] ${activeOnly ? "getActiveSessions" : "getAllSessionsAdmin"} failed:`,
|
|
9659
|
+
err?.name || "Error"
|
|
9660
|
+
);
|
|
9661
|
+
return ctx.internalServerError(
|
|
9662
|
+
activeOnly ? "Error fetching active sessions" : "Error fetching sessions"
|
|
9663
|
+
);
|
|
9664
|
+
}
|
|
9665
|
+
}
|
|
8415
9666
|
async function respondIfSessionCreationPending(ctx) {
|
|
8416
9667
|
const settings = await getPluginSettings(strapi);
|
|
8417
9668
|
const gracePeriodMs = getSessionCreationGraceMs(settings);
|
|
@@ -8442,13 +9693,19 @@ var require_session = __commonJS({
|
|
|
8442
9693
|
*/
|
|
8443
9694
|
async getUserStatsAdmin(ctx) {
|
|
8444
9695
|
try {
|
|
8445
|
-
|
|
8446
|
-
|
|
8447
|
-
|
|
8448
|
-
|
|
9696
|
+
if (userStatsCache.owner !== strapi || !userStatsCache.value || userStatsCache.expiresAt <= Date.now()) {
|
|
9697
|
+
userStatsCache.owner = null;
|
|
9698
|
+
const [totalUsers, blockedUsers] = await Promise.all([
|
|
9699
|
+
strapi.db.query(USER_UID).count(),
|
|
9700
|
+
strapi.db.query(USER_UID).count({ where: { blocked: true } })
|
|
9701
|
+
]);
|
|
9702
|
+
userStatsCache.owner = strapi;
|
|
9703
|
+
userStatsCache.value = { totalUsers, blockedUsers };
|
|
9704
|
+
userStatsCache.expiresAt = Date.now() + USER_STATS_CACHE_MS;
|
|
9705
|
+
}
|
|
8449
9706
|
return ctx.send({
|
|
8450
9707
|
success: true,
|
|
8451
|
-
data: {
|
|
9708
|
+
data: { ...userStatsCache.value }
|
|
8452
9709
|
});
|
|
8453
9710
|
} catch (error) {
|
|
8454
9711
|
strapi.log.error("[magic-sessionmanager] getUserStatsAdmin failed:", error?.name || "Error");
|
|
@@ -8456,42 +9713,174 @@ var require_session = __commonJS({
|
|
|
8456
9713
|
}
|
|
8457
9714
|
},
|
|
8458
9715
|
/**
|
|
8459
|
-
* Lists
|
|
9716
|
+
* Lists sessions for admin overviews.
|
|
9717
|
+
*
|
|
9718
|
+
* With `page` or `pageSize` the list is paginated in SQL and filtered by
|
|
9719
|
+
* `status`, `reason`, `search` and `sort` (whitelisted values only), with
|
|
9720
|
+
* exact totals. Without them the 4.x response (latest 1000 rows) is kept
|
|
9721
|
+
* for existing callers.
|
|
9722
|
+
*
|
|
8460
9723
|
* @route GET /magic-sessionmanager/sessions
|
|
9724
|
+
* @param {object} ctx Koa context
|
|
9725
|
+
* @returns {Promise<void>}
|
|
8461
9726
|
*/
|
|
8462
9727
|
async getAllSessionsAdmin(ctx) {
|
|
9728
|
+
return listSessionsAdmin(ctx, { activeOnly: false });
|
|
9729
|
+
},
|
|
9730
|
+
/**
|
|
9731
|
+
* Lists currently-active sessions only (paginated with `page`/`pageSize`,
|
|
9732
|
+
* see getAllSessionsAdmin).
|
|
9733
|
+
*
|
|
9734
|
+
* @route GET /magic-sessionmanager/sessions/active
|
|
9735
|
+
* @param {object} ctx Koa context
|
|
9736
|
+
* @returns {Promise<void>}
|
|
9737
|
+
*/
|
|
9738
|
+
async getActiveSessions(ctx) {
|
|
9739
|
+
return listSessionsAdmin(ctx, { activeOnly: true });
|
|
9740
|
+
},
|
|
9741
|
+
/**
|
|
9742
|
+
* Count-only session statistics for the dashboard cards and the homepage
|
|
9743
|
+
* widget. No rows, no personal data.
|
|
9744
|
+
*
|
|
9745
|
+
* @route GET /magic-sessionmanager/sessions/stats
|
|
9746
|
+
* @param {object} ctx Koa context
|
|
9747
|
+
* @returns {Promise<void>}
|
|
9748
|
+
*/
|
|
9749
|
+
async getSessionStatsAdmin(ctx) {
|
|
9750
|
+
const parsed = parseQuery(statsQuerySchema, ctx.query);
|
|
9751
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
8463
9752
|
try {
|
|
8464
9753
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
8465
|
-
const
|
|
8466
|
-
ctx.
|
|
8467
|
-
data: toPublicSessions(sessions, { admin: true }),
|
|
8468
|
-
meta: {
|
|
8469
|
-
count: sessions.length,
|
|
8470
|
-
active: sessions.filter((s) => s.isTrulyActive).length,
|
|
8471
|
-
inactive: sessions.filter((s) => !s.isTrulyActive).length,
|
|
8472
|
-
...getTruncationMeta(sessions)
|
|
8473
|
-
}
|
|
8474
|
-
};
|
|
9754
|
+
const stats = await sessionService.getSessionStats();
|
|
9755
|
+
return ctx.send({ data: stats });
|
|
8475
9756
|
} catch (err) {
|
|
8476
|
-
strapi.log.error("[magic-sessionmanager]
|
|
8477
|
-
return ctx.internalServerError("
|
|
9757
|
+
strapi.log.error("[magic-sessionmanager] getSessionStatsAdmin failed:", err?.name || "Error");
|
|
9758
|
+
return ctx.internalServerError("Unable to load session statistics");
|
|
8478
9759
|
}
|
|
8479
9760
|
},
|
|
8480
9761
|
/**
|
|
8481
|
-
*
|
|
8482
|
-
*
|
|
9762
|
+
* Count-only diagnostics of untracked Strapi sessions: Users & Permissions
|
|
9763
|
+
* sessions that Strapi still accepts (unexpired refresh tokens) but that
|
|
9764
|
+
* have no Magic session row. Splits them by creation before or after the
|
|
9765
|
+
* plugin started linking sessions, creation month, how Strapi created
|
|
9766
|
+
* them, device class and upcoming expiry. Read-only; no session IDs, user
|
|
9767
|
+
* data or IP addresses.
|
|
9768
|
+
*
|
|
9769
|
+
* @route GET /magic-sessionmanager/sessions/native-only/summary
|
|
9770
|
+
* @auth admin JWT or admin API token
|
|
9771
|
+
* @access plugin::magic-sessionmanager.access
|
|
9772
|
+
* @param {object} ctx Koa context; no query parameters are accepted.
|
|
9773
|
+
* @returns {Promise<void>} `{ data: summary }`, 400 on query parameters, 500 on a database error.
|
|
8483
9774
|
*/
|
|
8484
|
-
async
|
|
9775
|
+
async getNativeOnlySummaryAdmin(ctx) {
|
|
9776
|
+
const parsed = parseQuery(statsQuerySchema, ctx.query);
|
|
9777
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
9778
|
+
try {
|
|
9779
|
+
return ctx.send({ data: await getNativeOnlySummary(strapi) });
|
|
9780
|
+
} catch (err) {
|
|
9781
|
+
strapi.log.error(
|
|
9782
|
+
"[magic-sessionmanager] getNativeOnlySummaryAdmin failed:",
|
|
9783
|
+
err?.name || "Error"
|
|
9784
|
+
);
|
|
9785
|
+
return ctx.internalServerError("Unable to load the untracked session summary");
|
|
9786
|
+
}
|
|
9787
|
+
},
|
|
9788
|
+
/**
|
|
9789
|
+
* Ends untracked Users & Permissions sessions: deletes the Strapi session
|
|
9790
|
+
* rows that have no Magic session row, so their refresh tokens stop
|
|
9791
|
+
* working. Admin-panel sessions (origin `admin`) and linked sessions are
|
|
9792
|
+
* never touched. Bounded to `END_MAX_ROWS` rows per request; the response
|
|
9793
|
+
* says how many remain. Runs one at a time across instances.
|
|
9794
|
+
*
|
|
9795
|
+
* Requires a signed-in administrator (admin session strategy): an admin API
|
|
9796
|
+
* token cannot run this bulk sign-out.
|
|
9797
|
+
*
|
|
9798
|
+
* @route POST /magic-sessionmanager/sessions/native-only/end
|
|
9799
|
+
* @auth admin JWT (admin API tokens are refused)
|
|
9800
|
+
* @access plugin::magic-sessionmanager.access
|
|
9801
|
+
* @param {object} ctx Koa context; the body must be empty or `{}`.
|
|
9802
|
+
* @returns {Promise<void>} `{ data: { ended, remaining, limit } }`; 400, 403, 409 or 500.
|
|
9803
|
+
* @sideeffect Deletes rows from Strapi's `admin::session` table and writes an audit log line with counts only.
|
|
9804
|
+
*/
|
|
9805
|
+
async endNativeOnlySessionsAdmin(ctx) {
|
|
9806
|
+
if (ctx.state?.auth?.strategy?.name !== "admin") {
|
|
9807
|
+
return ctx.forbidden("Only a signed-in administrator can end these sessions");
|
|
9808
|
+
}
|
|
9809
|
+
const body = ctx.request?.body;
|
|
9810
|
+
const emptyBody = body === void 0 || body === null || typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 0;
|
|
9811
|
+
if (!emptyBody) return ctx.badRequest("This endpoint takes no request body");
|
|
9812
|
+
try {
|
|
9813
|
+
const result = await getCoordinator(strapi).withLock(
|
|
9814
|
+
"native-only-end",
|
|
9815
|
+
() => endNativeOnlySessions(strapi)
|
|
9816
|
+
);
|
|
9817
|
+
clearSessionStatsCache();
|
|
9818
|
+
strapi.log.info(
|
|
9819
|
+
`[magic-sessionmanager] [AUDIT] Untracked Users & Permissions sessions ended by an administrator: ended=${result.ended} remaining=${result.remaining}`
|
|
9820
|
+
);
|
|
9821
|
+
return ctx.send({ data: { ...result, limit: END_MAX_ROWS } });
|
|
9822
|
+
} catch (err) {
|
|
9823
|
+
if (err instanceof LockTimeoutError || err?.name === "LockTimeoutError") {
|
|
9824
|
+
return ctx.conflict("Another clean-up is running. Try again in a moment.");
|
|
9825
|
+
}
|
|
9826
|
+
strapi.log.error(
|
|
9827
|
+
"[magic-sessionmanager] endNativeOnlySessionsAdmin failed:",
|
|
9828
|
+
err?.name || "Error"
|
|
9829
|
+
);
|
|
9830
|
+
return ctx.internalServerError("Unable to end the untracked sessions");
|
|
9831
|
+
}
|
|
9832
|
+
},
|
|
9833
|
+
/**
|
|
9834
|
+
* Aggregates for the Analytics page over every session: counts, grouped
|
|
9835
|
+
* counts per device type and browser, distinct users, average length. No
|
|
9836
|
+
* rows and no personal data.
|
|
9837
|
+
*
|
|
9838
|
+
* @route GET /magic-sessionmanager/sessions/analytics
|
|
9839
|
+
* @param {object} ctx Koa context
|
|
9840
|
+
* @returns {Promise<void>}
|
|
9841
|
+
*/
|
|
9842
|
+
async getSessionAnalyticsAdmin(ctx) {
|
|
9843
|
+
const parsed = parseQuery(statsQuerySchema, ctx.query);
|
|
9844
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
8485
9845
|
try {
|
|
8486
9846
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
8487
|
-
|
|
8488
|
-
|
|
8489
|
-
|
|
8490
|
-
|
|
8491
|
-
|
|
9847
|
+
return ctx.send({ data: await sessionService.getSessionAnalytics() });
|
|
9848
|
+
} catch (err) {
|
|
9849
|
+
strapi.log.error(
|
|
9850
|
+
"[magic-sessionmanager] getSessionAnalyticsAdmin failed:",
|
|
9851
|
+
err?.name || "Error"
|
|
9852
|
+
);
|
|
9853
|
+
return ctx.internalServerError("Unable to load session analytics");
|
|
9854
|
+
}
|
|
9855
|
+
},
|
|
9856
|
+
/**
|
|
9857
|
+
* One batch of the session export (newest first, keyset cursor). The admin
|
|
9858
|
+
* client follows `meta.nextCursor` until it is null or its row limit is
|
|
9859
|
+
* reached.
|
|
9860
|
+
*
|
|
9861
|
+
* @route GET /magic-sessionmanager/sessions/export
|
|
9862
|
+
* @param {object} ctx Koa context
|
|
9863
|
+
* @returns {Promise<void>}
|
|
9864
|
+
*/
|
|
9865
|
+
async exportSessionsAdmin(ctx) {
|
|
9866
|
+
const parsed = parseQuery(exportQuerySchema, ctx.query);
|
|
9867
|
+
if (!parsed.ok) return ctx.badRequest("Invalid query", { errors: parsed.errors });
|
|
9868
|
+
const cursor = decodeExportCursor(parsed.value.cursor);
|
|
9869
|
+
if (cursor === false) {
|
|
9870
|
+
return ctx.badRequest("Invalid query", {
|
|
9871
|
+
errors: [{ path: "cursor", message: "Invalid cursor" }]
|
|
9872
|
+
});
|
|
9873
|
+
}
|
|
9874
|
+
try {
|
|
9875
|
+
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9876
|
+
const batch = await sessionService.exportSessionBatch(parsed.value, cursor);
|
|
9877
|
+
return ctx.send({
|
|
9878
|
+
data: toPublicSessions(batch.rows, { admin: true }),
|
|
9879
|
+
meta: { count: batch.rows.length, nextCursor: batch.nextCursor }
|
|
9880
|
+
});
|
|
8492
9881
|
} catch (err) {
|
|
8493
|
-
strapi.log.error("[magic-sessionmanager]
|
|
8494
|
-
return ctx.internalServerError("
|
|
9882
|
+
strapi.log.error("[magic-sessionmanager] exportSessionsAdmin failed:", err?.name || "Error");
|
|
9883
|
+
return ctx.internalServerError("Unable to export sessions");
|
|
8495
9884
|
}
|
|
8496
9885
|
},
|
|
8497
9886
|
/**
|
|
@@ -9014,6 +10403,7 @@ var require_session = __commonJS({
|
|
|
9014
10403
|
* A missing target returns 404; existing native-only rows remain supported.
|
|
9015
10404
|
*/
|
|
9016
10405
|
async terminateSingleSession(ctx) {
|
|
10406
|
+
clearSessionStatsCache();
|
|
9017
10407
|
try {
|
|
9018
10408
|
const { sessionId } = ctx.params;
|
|
9019
10409
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
@@ -9042,6 +10432,7 @@ var require_session = __commonJS({
|
|
|
9042
10432
|
* Unknown numeric IDs and document IDs return 404 before revocation.
|
|
9043
10433
|
*/
|
|
9044
10434
|
async terminateAllUserSessions(ctx) {
|
|
10435
|
+
clearSessionStatsCache();
|
|
9045
10436
|
try {
|
|
9046
10437
|
const { userId } = ctx.params;
|
|
9047
10438
|
const numericId = /^\d+$/.test(userId) ? Number(userId) : null;
|
|
@@ -9124,6 +10515,7 @@ var require_session = __commonJS({
|
|
|
9124
10515
|
* any unexpired JWT expires
|
|
9125
10516
|
*/
|
|
9126
10517
|
async deleteSession(ctx) {
|
|
10518
|
+
clearSessionStatsCache();
|
|
9127
10519
|
try {
|
|
9128
10520
|
const { sessionId } = ctx.params;
|
|
9129
10521
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
@@ -9149,6 +10541,7 @@ var require_session = __commonJS({
|
|
|
9149
10541
|
* could not be removed
|
|
9150
10542
|
*/
|
|
9151
10543
|
async cleanInactiveSessions(ctx) {
|
|
10544
|
+
clearSessionStatsCache();
|
|
9152
10545
|
try {
|
|
9153
10546
|
const sessionService = strapi.plugin("magic-sessionmanager").service("session");
|
|
9154
10547
|
const deletedCount = await sessionService.deleteInactiveSessions();
|
|
@@ -9195,6 +10588,8 @@ var require_session = __commonJS({
|
|
|
9195
10588
|
* can leave the user blocked with partially active sessions.
|
|
9196
10589
|
*/
|
|
9197
10590
|
async toggleUserBlock(ctx) {
|
|
10591
|
+
clearSessionStatsCache();
|
|
10592
|
+
userStatsCache.expiresAt = 0;
|
|
9198
10593
|
try {
|
|
9199
10594
|
const { userId } = ctx.params;
|
|
9200
10595
|
const body = ctx.request?.body;
|
|
@@ -10336,6 +11731,12 @@ var require_session2 = __commonJS({
|
|
|
10336
11731
|
persistAccessTokenRevocation
|
|
10337
11732
|
} = require_session_revocation();
|
|
10338
11733
|
var { getNativeSessionManager } = require_native_session_manager();
|
|
11734
|
+
var {
|
|
11735
|
+
exportSessionBatch,
|
|
11736
|
+
getSessionAnalytics: getSessionAnalyticsFromDb,
|
|
11737
|
+
getSessionStats: getSessionStatsFromDb,
|
|
11738
|
+
listSessionPage
|
|
11739
|
+
} = require_session_list();
|
|
10339
11740
|
var {
|
|
10340
11741
|
NATIVE_SESSION_PREFIX,
|
|
10341
11742
|
mapNativeSessionToView,
|
|
@@ -11031,8 +12432,51 @@ var require_session2 = __commonJS({
|
|
|
11031
12432
|
throw err;
|
|
11032
12433
|
}
|
|
11033
12434
|
},
|
|
12435
|
+
/**
|
|
12436
|
+
* One page of sessions with exact totals for the admin dashboard. Only
|
|
12437
|
+
* the rows on the page are enriched; filters and sort run in SQL.
|
|
12438
|
+
*
|
|
12439
|
+
* @param {{page: number, pageSize: number, status: string, reason: string, search: string, sort: string}} query Validated list query
|
|
12440
|
+
* @returns {Promise<{rows: object[], pagination: object}>}
|
|
12441
|
+
*/
|
|
12442
|
+
async listSessionPage(query) {
|
|
12443
|
+
return listSessionPage(strapi2, query, await getEnhanceOpts());
|
|
12444
|
+
},
|
|
12445
|
+
/**
|
|
12446
|
+
* Count-only session statistics (cached a few seconds per process).
|
|
12447
|
+
*
|
|
12448
|
+
* @returns {Promise<object>}
|
|
12449
|
+
*/
|
|
12450
|
+
async getSessionStats() {
|
|
12451
|
+
const { inactivityTimeout } = await getEnhanceOpts();
|
|
12452
|
+
return getSessionStatsFromDb(strapi2, { inactivityTimeout });
|
|
12453
|
+
},
|
|
12454
|
+
/**
|
|
12455
|
+
* Aggregates for the Analytics page over every session (cached 30 s
|
|
12456
|
+
* per process).
|
|
12457
|
+
*
|
|
12458
|
+
* @returns {Promise<object>}
|
|
12459
|
+
*/
|
|
12460
|
+
async getSessionAnalytics() {
|
|
12461
|
+
const { inactivityTimeout } = await getEnhanceOpts();
|
|
12462
|
+
return getSessionAnalyticsFromDb(strapi2, { inactivityTimeout });
|
|
12463
|
+
},
|
|
12464
|
+
/**
|
|
12465
|
+
* One export batch (keyset cursor, newest first).
|
|
12466
|
+
*
|
|
12467
|
+
* @param {{limit: number, status: string, reason: string, search: string}} query Validated export query
|
|
12468
|
+
* @param {{loginTime: Date|null, id: number}|null} cursor Decoded cursor
|
|
12469
|
+
* @returns {Promise<{rows: object[], nextCursor: string|null}>}
|
|
12470
|
+
*/
|
|
12471
|
+
async exportSessionBatch(query, cursor) {
|
|
12472
|
+
const { inactivityTimeout } = await getEnhanceOpts();
|
|
12473
|
+
return exportSessionBatch(strapi2, query, cursor, { inactivityTimeout });
|
|
12474
|
+
},
|
|
11034
12475
|
/**
|
|
11035
12476
|
* Get ALL sessions (active + inactive) with enhanced display fields.
|
|
12477
|
+
* Kept for callers of `GET /sessions` without paging parameters; capped
|
|
12478
|
+
* at the latest 1000 rows. The admin dashboard uses `listSessionPage`.
|
|
12479
|
+
*
|
|
11036
12480
|
* @returns {Promise<Array>}
|
|
11037
12481
|
*/
|
|
11038
12482
|
async getAllSessions() {
|