strapi-plugin-magic-sessionmanager 4.12.0 → 4.13.1
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 +54 -2
- package/README.md +63 -34
- package/dist/admin/{Analytics-lP0-RsVd.js → Analytics-BikQQx_J.js} +1 -1
- package/dist/admin/{Analytics-C_c24Uzq.mjs → Analytics-DIY51RI_.mjs} +1 -1
- package/dist/admin/{App-DCyNPn1k.mjs → App-B3vaybSO.mjs} +433 -13
- package/dist/admin/{App-miWDdmdX.js → App-BV1LM9Bp.js} +433 -13
- package/dist/admin/{OnlineUsersWidget-C6wlwENC.mjs → OnlineUsersWidget-T-2upsDd.mjs} +1 -1
- package/dist/admin/{OnlineUsersWidget-C6b7e4jb.js → OnlineUsersWidget-fJogM1xl.js} +1 -1
- package/dist/admin/{Settings-D9zyn5xn.js → Settings-AyYka8wn.js} +1 -1
- package/dist/admin/{Settings-DssYw2W4.mjs → Settings-BpBlXyMY.mjs} +1 -1
- package/dist/admin/{de--yNl7MPl.mjs → de-BSCDuq1i.mjs} +38 -1
- package/dist/admin/{de-DjPEATFf.js → de-z0aHRwdw.js} +38 -1
- package/dist/admin/{en-5U7g51cH.mjs → en-B4Cuq9JN.mjs} +38 -1
- package/dist/admin/{en-BoO12UQw.js → en-BWPOiiMt.js} +38 -1
- package/dist/admin/{es-BLpEuycJ.js → es-CMskkUh-.js} +38 -1
- package/dist/admin/{es-BJR-zCXL.mjs → es-DBAmysKi.mjs} +38 -1
- package/dist/admin/{fr-CeeCYQCs.mjs → fr-BNGdtjEl.mjs} +38 -1
- package/dist/admin/{fr-BE828R9Q.js → fr-ClJ2BkrE.js} +38 -1
- package/dist/admin/{index-CfQOMZVX.js → index-DyE1rLW0.js} +22 -19
- package/dist/admin/{index-rbxJZcLv.mjs → index-mCVi1j7e.mjs} +22 -19
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/{pt-BWEFiuvo.js → pt-CRh_J7JS.js} +38 -1
- package/dist/admin/{pt-CorrU3yG.mjs → pt-Cl7TWsOV.mjs} +38 -1
- package/dist/server/index.js +721 -30
- package/dist/server/index.mjs +721 -30
- package/package.json +14 -7
- package/pics/analytics.png +0 -0
- package/pics/dashboard-dark.png +0 -0
- package/pics/dashboard.png +0 -0
- package/pics/dashboardsessionmodal.png +0 -0
- package/pics/mobile-dashboard.png +0 -0
- package/pics/mobile-session.png +0 -0
- package/pics/sessioninfopanel.png +0 -0
- package/pics/settings1.png +0 -0
- package/pics/settings2.png +0 -0
- package/pics/widget.png +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,11 +2315,12 @@ 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) {
|
|
@@ -5916,6 +6335,8 @@ var require_bootstrap = __commonJS({
|
|
|
5916
6335
|
} = require_coordination();
|
|
5917
6336
|
var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
|
|
5918
6337
|
var {
|
|
6338
|
+
normalizeApiPrefix,
|
|
6339
|
+
toCanonicalApiPath,
|
|
5919
6340
|
classifyJwtIssuingRequest,
|
|
5920
6341
|
isFailedLoginTrackedPath,
|
|
5921
6342
|
isPasswordResetRequest,
|
|
@@ -5927,6 +6348,14 @@ var require_bootstrap = __commonJS({
|
|
|
5927
6348
|
getOutgoingRefreshToken,
|
|
5928
6349
|
stripAuthTokensFromResponse
|
|
5929
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();
|
|
5930
6359
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
5931
6360
|
var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
|
|
5932
6361
|
var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -5973,6 +6402,17 @@ var require_bootstrap = __commonJS({
|
|
|
5973
6402
|
await ensureSessionLookupIndexes(strapi2, log);
|
|
5974
6403
|
await registerSessionAwareAuthStrategy(strapi2);
|
|
5975
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
|
+
}
|
|
5976
6416
|
const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
|
|
5977
6417
|
if (!strapi2.sessionManagerIntervals) {
|
|
5978
6418
|
strapi2.sessionManagerIntervals = {};
|
|
@@ -6104,7 +6544,7 @@ var require_bootstrap = __commonJS({
|
|
|
6104
6544
|
}
|
|
6105
6545
|
function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
|
|
6106
6546
|
strapi2.server.use(async (ctx, next) => {
|
|
6107
|
-
if (!shouldRunPreAuthGeoGuard(ctx
|
|
6547
|
+
if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
|
|
6108
6548
|
return next();
|
|
6109
6549
|
}
|
|
6110
6550
|
const settings = await getRequestSettings(strapi2, ctx);
|
|
@@ -6157,7 +6597,8 @@ var require_bootstrap = __commonJS({
|
|
|
6157
6597
|
log.info("[SUCCESS] Pre-login geo guard mounted");
|
|
6158
6598
|
}
|
|
6159
6599
|
function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
|
|
6160
|
-
|
|
6600
|
+
const logoutPath = `${normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"))}/auth/logout`;
|
|
6601
|
+
if (hasRegisteredRoute(strapi2, "POST", logoutPath)) {
|
|
6161
6602
|
log.debug("[LOGOUT] Using the users-permissions logout route");
|
|
6162
6603
|
return;
|
|
6163
6604
|
}
|
|
@@ -6170,7 +6611,7 @@ var require_bootstrap = __commonJS({
|
|
|
6170
6611
|
strapi2.server.routes([
|
|
6171
6612
|
{
|
|
6172
6613
|
method: "POST",
|
|
6173
|
-
path:
|
|
6614
|
+
path: logoutPath,
|
|
6174
6615
|
handler: async (ctx) => {
|
|
6175
6616
|
try {
|
|
6176
6617
|
const token = extractBearerToken(ctx);
|
|
@@ -6246,6 +6687,9 @@ var require_bootstrap = __commonJS({
|
|
|
6246
6687
|
]);
|
|
6247
6688
|
log.info("[SUCCESS] /api/auth/logout route registered (auth-verified)");
|
|
6248
6689
|
}
|
|
6690
|
+
function apiPathOf(strapi2, ctx) {
|
|
6691
|
+
return toCanonicalApiPath(ctx.path, strapi2.config.get("api.rest.prefix", "/api"));
|
|
6692
|
+
}
|
|
6249
6693
|
function hasRegisteredRoute(strapi2, method, path) {
|
|
6250
6694
|
try {
|
|
6251
6695
|
const apiPrefix = strapi2.config.get("api.rest.prefix", "/api");
|
|
@@ -6279,11 +6723,35 @@ var require_bootstrap = __commonJS({
|
|
|
6279
6723
|
function usesNativeRefreshSessions(strapi2) {
|
|
6280
6724
|
return strapi2.config.get("plugin::users-permissions.jwtManagement", "legacy-support") === "refresh";
|
|
6281
6725
|
}
|
|
6282
|
-
async function
|
|
6283
|
-
|
|
6284
|
-
const
|
|
6285
|
-
if (!
|
|
6286
|
-
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");
|
|
6287
6755
|
}
|
|
6288
6756
|
const userId = String(validation.userId);
|
|
6289
6757
|
if (user?.id != null && String(user.id) !== userId) {
|
|
@@ -6315,7 +6783,7 @@ var require_bootstrap = __commonJS({
|
|
|
6315
6783
|
const coordinator = getCoordinator(strapi2);
|
|
6316
6784
|
const keyFor = (ip) => hashedKey("lf", ip);
|
|
6317
6785
|
strapi2.server.use(async (ctx, next) => {
|
|
6318
|
-
if (!isFailedLoginTrackedPath(ctx
|
|
6786
|
+
if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
|
|
6319
6787
|
const settings = await getRequestSettings(strapi2, ctx);
|
|
6320
6788
|
const maxFailed = Number(settings.maxFailedLogins) || 0;
|
|
6321
6789
|
if (maxFailed <= 0) return next();
|
|
@@ -6417,13 +6885,34 @@ var require_bootstrap = __commonJS({
|
|
|
6417
6885
|
}
|
|
6418
6886
|
function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
6419
6887
|
strapi2.server.use(async (ctx, next) => {
|
|
6420
|
-
const
|
|
6888
|
+
const apiPath = apiPathOf(strapi2, ctx);
|
|
6889
|
+
const requestType = classifyJwtIssuingRequest(apiPath, ctx.method);
|
|
6421
6890
|
const previousAccessToken = requestType === "rotate-current" ? extractBearerToken(ctx) : null;
|
|
6422
6891
|
const nativeMode = usesNativeRefreshSessions(strapi2);
|
|
6423
6892
|
await next();
|
|
6893
|
+
if (nativeMode && requestType === null) {
|
|
6894
|
+
await linkCreatedNativeSessions({ strapi: strapi2, ctx, log, sessionService });
|
|
6895
|
+
return;
|
|
6896
|
+
}
|
|
6424
6897
|
if (requestType !== "new-session" && requestType !== "rotate-current") return;
|
|
6425
6898
|
if (ctx.status < 200 || ctx.status >= 300) return;
|
|
6426
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
|
+
}
|
|
6427
6916
|
const refreshCookieName = getRefreshCookieName(strapi2);
|
|
6428
6917
|
if (requestType === "rotate-current") {
|
|
6429
6918
|
if (nativeMode) {
|
|
@@ -6437,6 +6926,7 @@ var require_bootstrap = __commonJS({
|
|
|
6437
6926
|
strapi: strapi2,
|
|
6438
6927
|
nativeSessionManager: nativeSessionManager2,
|
|
6439
6928
|
refreshToken: newRefreshToken,
|
|
6929
|
+
accessToken: ctx.body.jwt,
|
|
6440
6930
|
user: ctx.body.user || ctx.state?.user
|
|
6441
6931
|
});
|
|
6442
6932
|
const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
|
|
@@ -6473,6 +6963,12 @@ var require_bootstrap = __commonJS({
|
|
|
6473
6963
|
if (nativeSessionManager2 && nativeSession2) {
|
|
6474
6964
|
await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
|
|
6475
6965
|
}
|
|
6966
|
+
await compensateCreatedNativeSessions({
|
|
6967
|
+
strapi: strapi2,
|
|
6968
|
+
ctx,
|
|
6969
|
+
log,
|
|
6970
|
+
except: nativeSession2?.sessionId
|
|
6971
|
+
});
|
|
6476
6972
|
failClosedAuthResponse({
|
|
6477
6973
|
ctx,
|
|
6478
6974
|
strapi: strapi2,
|
|
@@ -6529,6 +7025,7 @@ var require_bootstrap = __commonJS({
|
|
|
6529
7025
|
strapi: strapi2,
|
|
6530
7026
|
nativeSessionManager,
|
|
6531
7027
|
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
|
|
7028
|
+
accessToken: ctx.body.jwt,
|
|
6532
7029
|
user
|
|
6533
7030
|
});
|
|
6534
7031
|
userDocId = nativeSession.userDocumentId;
|
|
@@ -6554,7 +7051,7 @@ var require_bootstrap = __commonJS({
|
|
|
6554
7051
|
if (!newSession?.documentId) {
|
|
6555
7052
|
throw new Error(`session creation returned no documentId for user ${userDocId}`);
|
|
6556
7053
|
}
|
|
6557
|
-
if (isPasswordResetRequest(
|
|
7054
|
+
if (isPasswordResetRequest(apiPath, ctx.method)) {
|
|
6558
7055
|
await sessionService.terminateSession({
|
|
6559
7056
|
userId: userDocId,
|
|
6560
7057
|
exceptSessionId: newSession.documentId,
|
|
@@ -6689,6 +7186,14 @@ var require_bootstrap = __commonJS({
|
|
|
6689
7186
|
if (nativeSessionManager && nativeSession) {
|
|
6690
7187
|
await compensateNativeSession({ nativeSessionManager, nativeSession, log });
|
|
6691
7188
|
}
|
|
7189
|
+
if (nativeMode) {
|
|
7190
|
+
await compensateCreatedNativeSessions({
|
|
7191
|
+
strapi: strapi2,
|
|
7192
|
+
ctx,
|
|
7193
|
+
log,
|
|
7194
|
+
except: nativeSession?.sessionId
|
|
7195
|
+
});
|
|
7196
|
+
}
|
|
6692
7197
|
failClosedAuthResponse({
|
|
6693
7198
|
ctx,
|
|
6694
7199
|
strapi: strapi2,
|
|
@@ -6700,9 +7205,76 @@ var require_bootstrap = __commonJS({
|
|
|
6700
7205
|
});
|
|
6701
7206
|
log.info("[SUCCESS] Login interceptor middleware mounted");
|
|
6702
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
|
+
}
|
|
6703
7275
|
function mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
6704
7276
|
strapi2.server.use(async (ctx, next) => {
|
|
6705
|
-
const isRefreshToken = ctx
|
|
7277
|
+
const isRefreshToken = apiPathOf(strapi2, ctx) === "/api/auth/refresh" && ctx.method === "POST";
|
|
6706
7278
|
if (!isRefreshToken) return next();
|
|
6707
7279
|
const cookieName = getRefreshCookieName(strapi2);
|
|
6708
7280
|
const oldRefreshToken = getIncomingRefreshToken(ctx, cookieName);
|
|
@@ -6801,6 +7373,12 @@ var require_bootstrap = __commonJS({
|
|
|
6801
7373
|
if (nativeSession) {
|
|
6802
7374
|
await compensateNativeSession({ nativeSessionManager, nativeSession, log });
|
|
6803
7375
|
}
|
|
7376
|
+
await compensateCreatedNativeSessions({
|
|
7377
|
+
strapi: strapi2,
|
|
7378
|
+
ctx,
|
|
7379
|
+
log,
|
|
7380
|
+
except: nativeSession?.sessionId
|
|
7381
|
+
});
|
|
6804
7382
|
failClosedAuthResponse({
|
|
6805
7383
|
ctx,
|
|
6806
7384
|
strapi: strapi2,
|
|
@@ -6838,7 +7416,7 @@ var require_bootstrap = __commonJS({
|
|
|
6838
7416
|
}
|
|
6839
7417
|
function mountLogoutInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
6840
7418
|
strapi2.server.use(async (ctx, next) => {
|
|
6841
|
-
if (ctx
|
|
7419
|
+
if (apiPathOf(strapi2, ctx) !== "/api/auth/logout" || ctx.method !== "POST") return next();
|
|
6842
7420
|
const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
|
|
6843
7421
|
const accessToken = extractBearerToken(ctx);
|
|
6844
7422
|
const nativeMode = usesNativeRefreshSessions(strapi2);
|
|
@@ -7437,6 +8015,16 @@ var require_destroy = __commonJS({
|
|
|
7437
8015
|
}
|
|
7438
8016
|
strapi2.sessionManagerIntervals = {};
|
|
7439
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
|
+
}
|
|
7440
8028
|
log.info("[SUCCESS] Plugin cleanup completed");
|
|
7441
8029
|
};
|
|
7442
8030
|
}
|
|
@@ -7866,6 +8454,31 @@ var require_admin = __commonJS({
|
|
|
7866
8454
|
description: "Get count-only session statistics (admin)"
|
|
7867
8455
|
}
|
|
7868
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
|
+
},
|
|
7869
8482
|
{
|
|
7870
8483
|
method: "GET",
|
|
7871
8484
|
path: "/sessions/analytics",
|
|
@@ -8551,6 +9164,11 @@ var require_session_list = __commonJS({
|
|
|
8551
9164
|
"use strict";
|
|
8552
9165
|
var { enhanceSessions } = require_enhance_session();
|
|
8553
9166
|
var { getNativeSessionManager } = require_native_session_manager();
|
|
9167
|
+
var {
|
|
9168
|
+
canInspectNativeSessions,
|
|
9169
|
+
countNativeOnly,
|
|
9170
|
+
getNativeTrackingSince
|
|
9171
|
+
} = require_native_only_insight();
|
|
8554
9172
|
var {
|
|
8555
9173
|
LIST_FIELDS,
|
|
8556
9174
|
LIST_USER_FIELDS,
|
|
@@ -8622,19 +9240,13 @@ var require_session_list = __commonJS({
|
|
|
8622
9240
|
);
|
|
8623
9241
|
}
|
|
8624
9242
|
async function countNativeOnlySessions(strapi2) {
|
|
8625
|
-
|
|
8626
|
-
|
|
8627
|
-
|
|
8628
|
-
|
|
8629
|
-
|
|
8630
|
-
const
|
|
8631
|
-
|
|
8632
|
-
const nativeIdColumn = column(nativeMeta, "sessionId");
|
|
8633
|
-
const linkedColumn = column(sessionMeta, "nativeSessionId");
|
|
8634
|
-
const result = await knex(nativeTable).where(column(nativeMeta, "origin"), NATIVE_ORIGIN).andWhere(column(nativeMeta, "status"), "active").andWhere(column(nativeMeta, "expiresAt"), ">", /* @__PURE__ */ new Date()).whereNotExists(function linked() {
|
|
8635
|
-
this.select(knex.raw("1")).from(sessionTable).whereRaw("??.?? = ??.??", [sessionTable, linkedColumn, nativeTable, nativeIdColumn]);
|
|
8636
|
-
}).count({ count: "*" }).first();
|
|
8637
|
-
return Number(result?.count ?? 0);
|
|
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 });
|
|
8638
9250
|
}
|
|
8639
9251
|
async function countUsersOnline(strapi2, cutoff) {
|
|
8640
9252
|
const meta = strapi2.db.metadata.get(SESSION_UID);
|
|
@@ -8722,7 +9334,7 @@ var require_session_list = __commonJS({
|
|
|
8722
9334
|
count({ status: "ended", reason: "logout" }),
|
|
8723
9335
|
count({ status: "ended", reason: "idle" }),
|
|
8724
9336
|
countUsersOnline(strapi2, cutoff),
|
|
8725
|
-
|
|
9337
|
+
countNativeOnlySplit(strapi2)
|
|
8726
9338
|
]);
|
|
8727
9339
|
const ended = Math.max(0, Number(total) - Number(open));
|
|
8728
9340
|
const value = {
|
|
@@ -8735,7 +9347,8 @@ var require_session_list = __commonJS({
|
|
|
8735
9347
|
timedOut: Number(timedOut),
|
|
8736
9348
|
otherReasons: Math.max(0, ended - Number(loggedOut) - Number(timedOut)),
|
|
8737
9349
|
usersOnline: Number(usersOnline),
|
|
8738
|
-
nativeOnly:
|
|
9350
|
+
nativeOnly: nativeOnly.total,
|
|
9351
|
+
nativeOnlyAfterTracking: nativeOnly.afterTracking
|
|
8739
9352
|
};
|
|
8740
9353
|
cache.set(key, { value, expiresAt: Date.now() + STATS_CACHE_MS });
|
|
8741
9354
|
if (cache.size > 20) cache.delete(cache.keys().next().value);
|
|
@@ -8905,6 +9518,12 @@ var require_session = __commonJS({
|
|
|
8905
9518
|
var { sendServerError } = require_http_errors();
|
|
8906
9519
|
var { getCoordinator } = require_coordination();
|
|
8907
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();
|
|
8908
9527
|
var {
|
|
8909
9528
|
decodeExportCursor,
|
|
8910
9529
|
exportQuerySchema,
|
|
@@ -9139,6 +9758,78 @@ var require_session = __commonJS({
|
|
|
9139
9758
|
return ctx.internalServerError("Unable to load session statistics");
|
|
9140
9759
|
}
|
|
9141
9760
|
},
|
|
9761
|
+
/**
|
|
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.
|
|
9774
|
+
*/
|
|
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
|
+
},
|
|
9142
9833
|
/**
|
|
9143
9834
|
* Aggregates for the Analytics page over every session: counts, grouped
|
|
9144
9835
|
* counts per device type and browser, distinct users, average length. No
|