strapi-plugin-magic-sessionmanager 4.19.1 → 4.20.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 +24 -0
- package/README.md +136 -1
- package/dist/admin/{Analytics-BqFlgLnN.mjs → Analytics-B-MVQ6dQ.mjs} +1 -1
- package/dist/admin/{Analytics-BElmzyNJ.js → Analytics-B5GnwMtH.js} +1 -1
- package/dist/admin/{App-0thsC_P9.mjs → App-DzbP5VPQ.mjs} +2 -2
- package/dist/admin/{App-D_J2eeEG.js → App-xBOmg4g9.js} +2 -2
- package/dist/admin/{OnlineUsersWidget-BgJ1ws-5.mjs → OnlineUsersWidget-Bf3BICmx.mjs} +1 -1
- package/dist/admin/{OnlineUsersWidget-DMZBwqdY.js → OnlineUsersWidget-FuPPPCCV.js} +1 -1
- package/dist/admin/{Settings-FOkui_ke.js → Settings-WRIXHLDa.js} +280 -65
- package/dist/admin/{Settings-QN3Mu4AQ.mjs → Settings-hpkloyO6.mjs} +250 -35
- package/dist/admin/{de-uGKSKVYD.mjs → de-Bzd14FzX.mjs} +63 -1
- package/dist/admin/{de-CEyi4lpp.js → de-Uqb30N5n.js} +63 -1
- package/dist/admin/{en-CSXeJYKy.js → en-CDBcocLk.js} +63 -1
- package/dist/admin/{en-Yu7tfwqx.mjs → en-DovyVwa5.mjs} +63 -1
- package/dist/admin/{es-iNG9Amf9.mjs → es-BygJxl1J.mjs} +63 -1
- package/dist/admin/{es-BrKqXhAU.js → es-DA1X0RPv.js} +63 -1
- package/dist/admin/{fr-DKZNfdlH.js → fr-CPPA27jW.js} +63 -1
- package/dist/admin/{fr-CaFICHlf.mjs → fr-DONxL73-.mjs} +63 -1
- package/dist/admin/{index-h-ksmM8A.mjs → index-DsaGGK7x.mjs} +627 -61
- package/dist/admin/{index-DEYtqPc3.js → index-Q_D-5LlE.js} +612 -46
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +2 -2
- package/dist/admin/{pt-IEagyVDL.js → pt-BMuwyaan.js} +63 -1
- package/dist/admin/{pt-Bz2hWVrq.mjs → pt-D2yGNz2N.mjs} +63 -1
- package/dist/admin/{settingsTabs-D02CuEvs.mjs → settingsTabs--7IsqMdn.mjs} +5 -1
- package/dist/admin/{settingsTabs-N4TFn-mw.js → settingsTabs-Dxlevody.js} +5 -1
- package/dist/server/index.js +1485 -19
- package/dist/server/index.mjs +1485 -19
- package/package.json +1 -1
package/dist/server/index.js
CHANGED
|
@@ -1686,6 +1686,245 @@ var require_detection_settings = __commonJS({
|
|
|
1686
1686
|
}
|
|
1687
1687
|
});
|
|
1688
1688
|
|
|
1689
|
+
// server/src/utils/impersonation-rules.js
|
|
1690
|
+
var require_impersonation_rules = __commonJS({
|
|
1691
|
+
"server/src/utils/impersonation-rules.js"(exports2, module2) {
|
|
1692
|
+
"use strict";
|
|
1693
|
+
var IMPERSONATION_DEFAULTS = Object.freeze({ impersonationEnabled: false });
|
|
1694
|
+
var IMPERSONATION_KEYS = Object.freeze(Object.keys(IMPERSONATION_DEFAULTS));
|
|
1695
|
+
var USER_DURATIONS = Object.freeze([15, 30, 60]);
|
|
1696
|
+
var REASON_MIN = 3;
|
|
1697
|
+
var REASON_MAX = 255;
|
|
1698
|
+
var CODE_TTL_MS = 60 * 1e3;
|
|
1699
|
+
var IMPERSONATION_HEADER = "X-Magic-Impersonation";
|
|
1700
|
+
var CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
1701
|
+
var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
|
|
1702
|
+
var LOOPBACK_HOSTS = Object.freeze(["localhost", "127.0.0.1", "[::1]"]);
|
|
1703
|
+
function normalizeImpersonationSettings(stored) {
|
|
1704
|
+
return { impersonationEnabled: stored?.impersonationEnabled === true };
|
|
1705
|
+
}
|
|
1706
|
+
function validateImpersonationSettings(body) {
|
|
1707
|
+
const values = {};
|
|
1708
|
+
const errors = [];
|
|
1709
|
+
if (Object.prototype.hasOwnProperty.call(body, "impersonationEnabled")) {
|
|
1710
|
+
if (typeof body.impersonationEnabled !== "boolean") {
|
|
1711
|
+
errors.push({
|
|
1712
|
+
path: ["impersonationEnabled"],
|
|
1713
|
+
message: "impersonationEnabled must be a boolean"
|
|
1714
|
+
});
|
|
1715
|
+
} else {
|
|
1716
|
+
values.impersonationEnabled = body.impersonationEnabled;
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
return { values, errors };
|
|
1720
|
+
}
|
|
1721
|
+
function parseHandoffUrl(value, env) {
|
|
1722
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 2048) return null;
|
|
1723
|
+
let url;
|
|
1724
|
+
try {
|
|
1725
|
+
url = new URL(value);
|
|
1726
|
+
} catch {
|
|
1727
|
+
return null;
|
|
1728
|
+
}
|
|
1729
|
+
if (url.username || url.password || url.hash) return null;
|
|
1730
|
+
if (url.protocol === "https:") return url;
|
|
1731
|
+
if (url.protocol === "http:" && !env.production && LOOPBACK_HOSTS.includes(url.hostname)) {
|
|
1732
|
+
return url;
|
|
1733
|
+
}
|
|
1734
|
+
return null;
|
|
1735
|
+
}
|
|
1736
|
+
function validateImpersonationConfig(config2, env) {
|
|
1737
|
+
if (config2 === void 0 || config2 === null) return;
|
|
1738
|
+
if (typeof config2 !== "object" || Array.isArray(config2)) {
|
|
1739
|
+
throw new Error("impersonation must be an object");
|
|
1740
|
+
}
|
|
1741
|
+
const { frontendUrl, allowedFrontendOrigins } = (
|
|
1742
|
+
/** @type {any} */
|
|
1743
|
+
config2
|
|
1744
|
+
);
|
|
1745
|
+
const unknown = Object.keys(config2).filter(
|
|
1746
|
+
(key) => !["frontendUrl", "allowedFrontendOrigins"].includes(key)
|
|
1747
|
+
);
|
|
1748
|
+
if (unknown.length > 0) throw new Error("impersonation has unknown keys");
|
|
1749
|
+
if (allowedFrontendOrigins !== void 0 && allowedFrontendOrigins !== null) {
|
|
1750
|
+
if (!Array.isArray(allowedFrontendOrigins) || allowedFrontendOrigins.length > 20) {
|
|
1751
|
+
throw new Error("impersonation.allowedFrontendOrigins must be a list of at most 20 origins");
|
|
1752
|
+
}
|
|
1753
|
+
for (const origin of allowedFrontendOrigins) {
|
|
1754
|
+
const url2 = parseHandoffUrl(origin, env);
|
|
1755
|
+
if (!url2 || url2.origin !== origin) {
|
|
1756
|
+
throw new Error(
|
|
1757
|
+
"impersonation.allowedFrontendOrigins entries must be https origins without a path"
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
if (frontendUrl === void 0 || frontendUrl === null || frontendUrl === "") return;
|
|
1763
|
+
const url = parseHandoffUrl(frontendUrl, env);
|
|
1764
|
+
if (!url || url.search) {
|
|
1765
|
+
throw new Error(
|
|
1766
|
+
"impersonation.frontendUrl must be an https URL without user info, query or fragment"
|
|
1767
|
+
);
|
|
1768
|
+
}
|
|
1769
|
+
if (Array.isArray(allowedFrontendOrigins) && !allowedFrontendOrigins.includes(url.origin)) {
|
|
1770
|
+
throw new Error("impersonation.frontendUrl must use an origin of allowedFrontendOrigins");
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
function resolveFrontendHandoff(config2, env) {
|
|
1774
|
+
try {
|
|
1775
|
+
validateImpersonationConfig(config2, env);
|
|
1776
|
+
} catch {
|
|
1777
|
+
return null;
|
|
1778
|
+
}
|
|
1779
|
+
const url = parseHandoffUrl(
|
|
1780
|
+
/** @type {any} */
|
|
1781
|
+
config2?.frontendUrl,
|
|
1782
|
+
env
|
|
1783
|
+
);
|
|
1784
|
+
return url ? { url: url.toString(), origin: url.origin } : null;
|
|
1785
|
+
}
|
|
1786
|
+
function cleanReason(value) {
|
|
1787
|
+
if (typeof value !== "string" || value.length > REASON_MAX * 4) return null;
|
|
1788
|
+
const clean = value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
|
|
1789
|
+
if (clean.length < REASON_MIN || clean.length > REASON_MAX) return null;
|
|
1790
|
+
return clean;
|
|
1791
|
+
}
|
|
1792
|
+
function validateStartBody(body, { durations, notify }) {
|
|
1793
|
+
const errors = [];
|
|
1794
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1795
|
+
return { value: null, errors: [{ path: [], message: "Body must be an object" }] };
|
|
1796
|
+
}
|
|
1797
|
+
const allowed = ["reason", "durationMinutes", ...notify ? ["notifyUser"] : []];
|
|
1798
|
+
for (const key of Object.keys(body)) {
|
|
1799
|
+
if (!allowed.includes(key)) errors.push({ path: [key], message: "Unknown field" });
|
|
1800
|
+
}
|
|
1801
|
+
const source = (
|
|
1802
|
+
/** @type {Record<string, unknown>} */
|
|
1803
|
+
body
|
|
1804
|
+
);
|
|
1805
|
+
const reason = cleanReason(source.reason);
|
|
1806
|
+
if (reason === null) {
|
|
1807
|
+
errors.push({
|
|
1808
|
+
path: ["reason"],
|
|
1809
|
+
message: `reason must be ${REASON_MIN} to ${REASON_MAX} characters`
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
const duration = source.durationMinutes;
|
|
1813
|
+
if (typeof duration !== "number" || !durations.includes(duration)) {
|
|
1814
|
+
errors.push({
|
|
1815
|
+
path: ["durationMinutes"],
|
|
1816
|
+
message: `durationMinutes must be one of: ${durations.join(", ")}`
|
|
1817
|
+
});
|
|
1818
|
+
}
|
|
1819
|
+
if (notify && source.notifyUser !== void 0 && typeof source.notifyUser !== "boolean") {
|
|
1820
|
+
errors.push({ path: ["notifyUser"], message: "notifyUser must be a boolean" });
|
|
1821
|
+
}
|
|
1822
|
+
if (errors.length > 0) return { value: null, errors };
|
|
1823
|
+
return {
|
|
1824
|
+
value: {
|
|
1825
|
+
reason: (
|
|
1826
|
+
/** @type {string} */
|
|
1827
|
+
reason
|
|
1828
|
+
),
|
|
1829
|
+
durationMinutes: (
|
|
1830
|
+
/** @type {number} */
|
|
1831
|
+
duration
|
|
1832
|
+
),
|
|
1833
|
+
notifyUser: source.notifyUser === true
|
|
1834
|
+
},
|
|
1835
|
+
errors
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
function normalizePath(path) {
|
|
1839
|
+
const value = String(path || "").toLowerCase().replace(/\/{2,}/g, "/");
|
|
1840
|
+
return value.length > 1 ? value.replace(/\/+$/, "") || "/" : value;
|
|
1841
|
+
}
|
|
1842
|
+
var PLUGIN_READ_ROUTES = Object.freeze([
|
|
1843
|
+
/^\/magic-sessionmanager\/my-sessions$/,
|
|
1844
|
+
/^\/magic-sessionmanager\/current-session$/,
|
|
1845
|
+
/^\/magic-sessionmanager\/user\/[^/]{1,64}\/sessions$/
|
|
1846
|
+
]);
|
|
1847
|
+
function classifyRestrictedRequest(method, path, apiPrefix = "/api") {
|
|
1848
|
+
const verb = String(method || "").toUpperCase();
|
|
1849
|
+
const normalized = normalizePath(path);
|
|
1850
|
+
const prefix = normalizePath(apiPrefix || "/api");
|
|
1851
|
+
const base = prefix === "/" ? "" : prefix;
|
|
1852
|
+
if (!(normalized === base || normalized.startsWith(`${base}/`))) return null;
|
|
1853
|
+
const rest = normalized.slice(base.length) || "/";
|
|
1854
|
+
const isRead = verb === "GET" || verb === "HEAD";
|
|
1855
|
+
if (rest === "/auth" || rest.startsWith("/auth/")) {
|
|
1856
|
+
if (verb === "POST" && rest === "/auth/refresh") return null;
|
|
1857
|
+
if (isRead && rest === "/auth/sessions") return null;
|
|
1858
|
+
if (rest === "/auth/logout" || rest.startsWith("/auth/sessions")) return "sessions";
|
|
1859
|
+
return "credentials";
|
|
1860
|
+
}
|
|
1861
|
+
if (rest === "/connect" || rest.startsWith("/connect/")) return "credentials";
|
|
1862
|
+
if (rest === "/users" || rest.startsWith("/users/")) return isRead ? null : "account";
|
|
1863
|
+
if (rest.startsWith("/magic-sessionmanager/") || rest === "/magic-sessionmanager") {
|
|
1864
|
+
const sub = rest.slice("/magic-sessionmanager".length);
|
|
1865
|
+
if (isRead && PLUGIN_READ_ROUTES.some((pattern) => pattern.test(`/magic-sessionmanager${sub}`)))
|
|
1866
|
+
return null;
|
|
1867
|
+
if (sub === "/my-data" || sub === "/not-me") return "account";
|
|
1868
|
+
return "sessions";
|
|
1869
|
+
}
|
|
1870
|
+
if (rest.startsWith("/magic-link/") || rest.startsWith("/passwordless/")) {
|
|
1871
|
+
return "credentials";
|
|
1872
|
+
}
|
|
1873
|
+
return null;
|
|
1874
|
+
}
|
|
1875
|
+
var GRAPHQL_RESTRICTED = /\b(login|register|forgotPassword|resetPassword|changePassword|emailConfirmation|createUsersPermissionsUser|updateUsersPermissionsUser|deleteUsersPermissionsUser)\b/;
|
|
1876
|
+
var MAX_GRAPHQL_LENGTH = 100 * 1024;
|
|
1877
|
+
function isRestrictedGraphqlRequest(body, queryString) {
|
|
1878
|
+
const documents = [];
|
|
1879
|
+
const collect = (value) => {
|
|
1880
|
+
if (value && typeof value === "object" && typeof value.query === "string") {
|
|
1881
|
+
documents.push(value.query);
|
|
1882
|
+
}
|
|
1883
|
+
};
|
|
1884
|
+
if (Array.isArray(body)) body.slice(0, 50).forEach(collect);
|
|
1885
|
+
else collect(body);
|
|
1886
|
+
if (typeof queryString === "string") documents.push(queryString);
|
|
1887
|
+
return documents.some((text) => {
|
|
1888
|
+
if (text.length > MAX_GRAPHQL_LENGTH) return true;
|
|
1889
|
+
return /\bmutation\b/.test(text) && GRAPHQL_RESTRICTED.test(text);
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
function decodeJwtPayload(token) {
|
|
1893
|
+
if (typeof token !== "string" || token.length > 8192) return null;
|
|
1894
|
+
const parts = token.split(".");
|
|
1895
|
+
if (parts.length !== 3 || !parts[1]) return null;
|
|
1896
|
+
try {
|
|
1897
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
1898
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : null;
|
|
1899
|
+
} catch {
|
|
1900
|
+
return null;
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
module2.exports = {
|
|
1904
|
+
CODE_PATTERN,
|
|
1905
|
+
CODE_TTL_MS,
|
|
1906
|
+
DOCUMENT_ID_PATTERN,
|
|
1907
|
+
IMPERSONATION_DEFAULTS,
|
|
1908
|
+
IMPERSONATION_HEADER,
|
|
1909
|
+
IMPERSONATION_KEYS,
|
|
1910
|
+
REASON_MAX,
|
|
1911
|
+
REASON_MIN,
|
|
1912
|
+
USER_DURATIONS,
|
|
1913
|
+
classifyRestrictedRequest,
|
|
1914
|
+
cleanReason,
|
|
1915
|
+
decodeJwtPayload,
|
|
1916
|
+
isRestrictedGraphqlRequest,
|
|
1917
|
+
normalizeImpersonationSettings,
|
|
1918
|
+
normalizePath,
|
|
1919
|
+
parseHandoffUrl,
|
|
1920
|
+
resolveFrontendHandoff,
|
|
1921
|
+
validateImpersonationConfig,
|
|
1922
|
+
validateImpersonationSettings,
|
|
1923
|
+
validateStartBody
|
|
1924
|
+
};
|
|
1925
|
+
}
|
|
1926
|
+
});
|
|
1927
|
+
|
|
1689
1928
|
// server/src/utils/settings-loader.js
|
|
1690
1929
|
var require_settings_loader = __commonJS({
|
|
1691
1930
|
"server/src/utils/settings-loader.js"(exports2, module2) {
|
|
@@ -1693,6 +1932,7 @@ var require_settings_loader = __commonJS({
|
|
|
1693
1932
|
var { getCoordinator } = require_coordination();
|
|
1694
1933
|
var { normalizePolicySettings } = require_policy_settings();
|
|
1695
1934
|
var { normalizeDetectionSettings } = require_detection_settings();
|
|
1935
|
+
var { normalizeImpersonationSettings } = require_impersonation_rules();
|
|
1696
1936
|
var PLUGIN_ID = "magic-sessionmanager";
|
|
1697
1937
|
var SETTINGS_KEY = "settings";
|
|
1698
1938
|
var CACHE_TTL_MS = 30 * 1e3;
|
|
@@ -1829,6 +2069,7 @@ var require_settings_loader = __commonJS({
|
|
|
1829
2069
|
if (typeof stored.genericWebhookSecret === "string") {
|
|
1830
2070
|
out.genericWebhookSecret = stored.genericWebhookSecret;
|
|
1831
2071
|
}
|
|
2072
|
+
Object.assign(out, normalizeImpersonationSettings(stored));
|
|
1832
2073
|
return out;
|
|
1833
2074
|
}
|
|
1834
2075
|
async function getPluginSettings(strapi2) {
|
|
@@ -1950,12 +2191,23 @@ var require_security_log_model = __commonJS({
|
|
|
1950
2191
|
USER_NEW_DEVICE: "user.sign-in.new-device",
|
|
1951
2192
|
USER_IMPOSSIBLE_TRAVEL: "user.sign-in.impossible-travel",
|
|
1952
2193
|
USER_NOT_ME: "user.not-me",
|
|
1953
|
-
USER_DATA_EXPORTED: "user.data.exported"
|
|
2194
|
+
USER_DATA_EXPORTED: "user.data.exported",
|
|
2195
|
+
// Impersonation (4.20): always recorded while the feature is on; the actor
|
|
2196
|
+
// is the real admin, the target the app user. `meta` holds the reason and
|
|
2197
|
+
// the duration, never a code or token.
|
|
2198
|
+
IMPERSONATION_STARTED: "impersonation.started",
|
|
2199
|
+
IMPERSONATION_ENDED: "impersonation.ended",
|
|
2200
|
+
IMPERSONATION_EXPIRED: "impersonation.expired",
|
|
2201
|
+
IMPERSONATION_REFUSED: "impersonation.refused"
|
|
1954
2202
|
});
|
|
1955
2203
|
var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
|
|
1956
2204
|
SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
|
|
1957
2205
|
SECURITY_EVENTS.SETTINGS_UPDATED,
|
|
1958
|
-
SECURITY_EVENTS.LOG_READ
|
|
2206
|
+
SECURITY_EVENTS.LOG_READ,
|
|
2207
|
+
SECURITY_EVENTS.IMPERSONATION_STARTED,
|
|
2208
|
+
SECURITY_EVENTS.IMPERSONATION_ENDED,
|
|
2209
|
+
SECURITY_EVENTS.IMPERSONATION_EXPIRED,
|
|
2210
|
+
SECURITY_EVENTS.IMPERSONATION_REFUSED
|
|
1959
2211
|
]);
|
|
1960
2212
|
function dropRankOf(event) {
|
|
1961
2213
|
if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
|
|
@@ -2243,7 +2495,8 @@ var require_security_log_hardening = __commonJS({
|
|
|
2243
2495
|
var INTERNAL_TYPES = Object.freeze([
|
|
2244
2496
|
`plugin::${PLUGIN_ID}.session`,
|
|
2245
2497
|
`plugin::${PLUGIN_ID}.revoked-token`,
|
|
2246
|
-
EVENT_UID
|
|
2498
|
+
EVENT_UID,
|
|
2499
|
+
`plugin::${PLUGIN_ID}.impersonation`
|
|
2247
2500
|
]);
|
|
2248
2501
|
var MIGRATIONS_KEY = "migrations";
|
|
2249
2502
|
var MIGRATION_BATCH = 500;
|
|
@@ -2471,6 +2724,17 @@ var require_register = __commonJS({
|
|
|
2471
2724
|
uid: "lockouts.unlock",
|
|
2472
2725
|
subCategory: "General",
|
|
2473
2726
|
pluginName: "magic-sessionmanager"
|
|
2727
|
+
},
|
|
2728
|
+
// Impersonation of app users (4.20): a short-lived credential for one
|
|
2729
|
+
// Users & Permissions user, with a reason, logged. Super Admin holds it
|
|
2730
|
+
// automatically; other roles only when granted. Works only while the
|
|
2731
|
+
// Impersonation switch in the settings is on.
|
|
2732
|
+
{
|
|
2733
|
+
section: "plugins",
|
|
2734
|
+
displayName: "Impersonate app users",
|
|
2735
|
+
uid: "impersonate.users",
|
|
2736
|
+
subCategory: "Impersonation",
|
|
2737
|
+
pluginName: "magic-sessionmanager"
|
|
2474
2738
|
}
|
|
2475
2739
|
]);
|
|
2476
2740
|
disableGraphqlShadowCrud(strapi2, log);
|
|
@@ -4991,6 +5255,106 @@ var require_sign_in_signals = __commonJS({
|
|
|
4991
5255
|
}
|
|
4992
5256
|
});
|
|
4993
5257
|
|
|
5258
|
+
// server/src/middlewares/impersonation-guard.js
|
|
5259
|
+
var require_impersonation_guard = __commonJS({
|
|
5260
|
+
"server/src/middlewares/impersonation-guard.js"(exports2, module2) {
|
|
5261
|
+
"use strict";
|
|
5262
|
+
var { extractBearerToken } = require_extract_token();
|
|
5263
|
+
var { getIncomingRefreshToken, getRefreshCookieName } = require_refresh_token();
|
|
5264
|
+
var {
|
|
5265
|
+
IMPERSONATION_HEADER,
|
|
5266
|
+
classifyRestrictedRequest,
|
|
5267
|
+
isRestrictedGraphqlRequest,
|
|
5268
|
+
normalizePath
|
|
5269
|
+
} = require_impersonation_rules();
|
|
5270
|
+
function reply(ctx, status, name, message, reason) {
|
|
5271
|
+
ctx.status = status;
|
|
5272
|
+
ctx.body = { data: null, error: { status, name, message, details: { reason } } };
|
|
5273
|
+
}
|
|
5274
|
+
function markResponse(ctx) {
|
|
5275
|
+
ctx.set(IMPERSONATION_HEADER, "true");
|
|
5276
|
+
if (!ctx.response.get("Access-Control-Allow-Origin")) return;
|
|
5277
|
+
const exposed = ctx.response.get("Access-Control-Expose-Headers");
|
|
5278
|
+
const list = exposed ? exposed.split(",").map((item) => item.trim()) : [];
|
|
5279
|
+
if (!list.some((item) => item.toLowerCase() === IMPERSONATION_HEADER.toLowerCase())) {
|
|
5280
|
+
ctx.set("Access-Control-Expose-Headers", [...list, IMPERSONATION_HEADER].join(", "));
|
|
5281
|
+
}
|
|
5282
|
+
}
|
|
5283
|
+
module2.exports = (_config, { strapi: strapi2 }) => {
|
|
5284
|
+
const service = () => strapi2.plugin("magic-sessionmanager").service("impersonation");
|
|
5285
|
+
return async function impersonationGuard(ctx, next) {
|
|
5286
|
+
const prefix = normalizePath(strapi2.config.get("api.rest.prefix", "/api") || "/api");
|
|
5287
|
+
const path = normalizePath(ctx.path);
|
|
5288
|
+
const graphqlEndpoint = normalizePath(
|
|
5289
|
+
strapi2.plugin("graphql")?.config?.("endpoint") || "/graphql"
|
|
5290
|
+
);
|
|
5291
|
+
const isGraphql = path === graphqlEndpoint;
|
|
5292
|
+
const base = prefix === "/" ? "" : prefix;
|
|
5293
|
+
const isContentApi = path === base || path.startsWith(`${base}/`);
|
|
5294
|
+
if (!isGraphql && !isContentApi) return next();
|
|
5295
|
+
let impersonationId = null;
|
|
5296
|
+
try {
|
|
5297
|
+
const bearer = extractBearerToken(ctx);
|
|
5298
|
+
if (bearer) impersonationId = await service().impersonationOfToken(bearer);
|
|
5299
|
+
if (!impersonationId && ctx.method === "POST" && path === `${base}/auth/refresh`) {
|
|
5300
|
+
const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
|
|
5301
|
+
if (refreshToken) impersonationId = await service().impersonationOfToken(refreshToken);
|
|
5302
|
+
}
|
|
5303
|
+
} catch {
|
|
5304
|
+
return reply(
|
|
5305
|
+
ctx,
|
|
5306
|
+
503,
|
|
5307
|
+
"ServiceUnavailableError",
|
|
5308
|
+
"Session check unavailable",
|
|
5309
|
+
"impersonation-check"
|
|
5310
|
+
);
|
|
5311
|
+
}
|
|
5312
|
+
if (!impersonationId) return next();
|
|
5313
|
+
markResponse(ctx);
|
|
5314
|
+
let impersonation;
|
|
5315
|
+
try {
|
|
5316
|
+
impersonation = await service().loadForGuard(impersonationId);
|
|
5317
|
+
} catch {
|
|
5318
|
+
return reply(
|
|
5319
|
+
ctx,
|
|
5320
|
+
503,
|
|
5321
|
+
"ServiceUnavailableError",
|
|
5322
|
+
"Session check unavailable",
|
|
5323
|
+
"impersonation-check"
|
|
5324
|
+
);
|
|
5325
|
+
}
|
|
5326
|
+
if (!impersonation || impersonation.state !== "active") {
|
|
5327
|
+
return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-ended");
|
|
5328
|
+
}
|
|
5329
|
+
if (Date.now() >= impersonation.expiresAt) {
|
|
5330
|
+
try {
|
|
5331
|
+
await service().end(impersonation.id, { reason: "expired" });
|
|
5332
|
+
} catch {
|
|
5333
|
+
}
|
|
5334
|
+
return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-expired");
|
|
5335
|
+
}
|
|
5336
|
+
const restricted = isGraphql ? isRestrictedGraphqlRequest(ctx.request?.body, ctx.query?.query) ? "credentials" : null : classifyRestrictedRequest(ctx.method, path, prefix);
|
|
5337
|
+
if (restricted) {
|
|
5338
|
+
service().recordRefusedCall(impersonation, restricted);
|
|
5339
|
+
return reply(
|
|
5340
|
+
ctx,
|
|
5341
|
+
403,
|
|
5342
|
+
"ForbiddenError",
|
|
5343
|
+
"Not allowed while impersonating",
|
|
5344
|
+
`impersonation-${restricted}`
|
|
5345
|
+
);
|
|
5346
|
+
}
|
|
5347
|
+
ctx.state.magicImpersonation = { id: impersonation.id, actorId: impersonation.actorId };
|
|
5348
|
+
try {
|
|
5349
|
+
await next();
|
|
5350
|
+
} finally {
|
|
5351
|
+
markResponse(ctx);
|
|
5352
|
+
}
|
|
5353
|
+
};
|
|
5354
|
+
};
|
|
5355
|
+
}
|
|
5356
|
+
});
|
|
5357
|
+
|
|
4994
5358
|
// server/src/middlewares/session-rejection-headers.js
|
|
4995
5359
|
var require_session_rejection_headers = __commonJS({
|
|
4996
5360
|
"server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
|
|
@@ -9284,6 +9648,13 @@ var require_bootstrap = __commonJS({
|
|
|
9284
9648
|
5 * 60 * 1e3
|
|
9285
9649
|
);
|
|
9286
9650
|
log.info("[TIME] Dynamic cleanup + retention scheduled");
|
|
9651
|
+
strapi2.server.use(require_impersonation_guard()({}, { strapi: strapi2 }));
|
|
9652
|
+
const impersonationSweep = setInterval(() => {
|
|
9653
|
+
strapi2.plugin("magic-sessionmanager").service("impersonation").sweep().catch((err) => log.warn("[IMPERSONATION] Sweep failed:", err?.name || "Error"));
|
|
9654
|
+
}, 30 * 1e3);
|
|
9655
|
+
impersonationSweep.unref?.();
|
|
9656
|
+
strapi2.sessionManagerIntervals.impersonationSweep = impersonationSweep;
|
|
9657
|
+
strapi2.plugin("magic-sessionmanager").service("impersonation").checkHandoffSetup();
|
|
9287
9658
|
mountPreLoginGeoGuard({ strapi: strapi2, log });
|
|
9288
9659
|
mountFailedLoginLockout({ strapi: strapi2, log });
|
|
9289
9660
|
mountLogoutRoute({ strapi: strapi2, log, sessionService });
|
|
@@ -11030,6 +11401,7 @@ var require_destroy = __commonJS({
|
|
|
11030
11401
|
var require_config = __commonJS({
|
|
11031
11402
|
"server/src/config/index.js"(exports2, module2) {
|
|
11032
11403
|
"use strict";
|
|
11404
|
+
var { validateImpersonationConfig } = require_impersonation_rules();
|
|
11033
11405
|
module2.exports = {
|
|
11034
11406
|
default: {
|
|
11035
11407
|
debug: false,
|
|
@@ -11103,6 +11475,9 @@ var require_config = __commonJS({
|
|
|
11103
11475
|
if (config2.geoLookupFailureMode !== void 0 && !["auto", "allow", "block"].includes(config2.geoLookupFailureMode)) {
|
|
11104
11476
|
throw new Error("geoLookupFailureMode must be one of: auto, allow, block");
|
|
11105
11477
|
}
|
|
11478
|
+
validateImpersonationConfig(config2.impersonation, {
|
|
11479
|
+
production: process.env.NODE_ENV === "production"
|
|
11480
|
+
});
|
|
11106
11481
|
if (config2.coordination !== void 0 && config2.coordination !== null) {
|
|
11107
11482
|
const coordination = config2.coordination;
|
|
11108
11483
|
if (typeof coordination !== "object" || Array.isArray(coordination)) {
|
|
@@ -11375,6 +11750,153 @@ var require_schema3 = __commonJS({
|
|
|
11375
11750
|
}
|
|
11376
11751
|
});
|
|
11377
11752
|
|
|
11753
|
+
// server/src/content-types/impersonation/schema.json
|
|
11754
|
+
var require_schema4 = __commonJS({
|
|
11755
|
+
"server/src/content-types/impersonation/schema.json"(exports2, module2) {
|
|
11756
|
+
module2.exports = {
|
|
11757
|
+
kind: "collectionType",
|
|
11758
|
+
collectionName: "magic_sessions_impersonations",
|
|
11759
|
+
info: {
|
|
11760
|
+
singularName: "impersonation",
|
|
11761
|
+
pluralName: "impersonations",
|
|
11762
|
+
displayName: "Impersonation",
|
|
11763
|
+
description: "Time-limited impersonations of app users and permission previews of admins, started by an admin with a reason"
|
|
11764
|
+
},
|
|
11765
|
+
options: {
|
|
11766
|
+
draftAndPublish: false,
|
|
11767
|
+
comment: ""
|
|
11768
|
+
},
|
|
11769
|
+
pluginOptions: {
|
|
11770
|
+
"content-manager": {
|
|
11771
|
+
visible: false
|
|
11772
|
+
},
|
|
11773
|
+
"content-type-builder": {
|
|
11774
|
+
visible: false
|
|
11775
|
+
}
|
|
11776
|
+
},
|
|
11777
|
+
indexes: [
|
|
11778
|
+
{
|
|
11779
|
+
name: "msm_impersonations_state",
|
|
11780
|
+
columns: ["state", "expires_at"]
|
|
11781
|
+
},
|
|
11782
|
+
{
|
|
11783
|
+
name: "msm_impersonations_code",
|
|
11784
|
+
columns: ["code_hash"]
|
|
11785
|
+
},
|
|
11786
|
+
{
|
|
11787
|
+
name: "msm_impersonations_target",
|
|
11788
|
+
columns: ["target_type", "target_id", "state"]
|
|
11789
|
+
}
|
|
11790
|
+
],
|
|
11791
|
+
attributes: {
|
|
11792
|
+
targetType: {
|
|
11793
|
+
type: "enumeration",
|
|
11794
|
+
enum: ["user", "admin"],
|
|
11795
|
+
required: true
|
|
11796
|
+
},
|
|
11797
|
+
targetId: {
|
|
11798
|
+
type: "string",
|
|
11799
|
+
maxLength: 64,
|
|
11800
|
+
required: true
|
|
11801
|
+
},
|
|
11802
|
+
actorId: {
|
|
11803
|
+
type: "string",
|
|
11804
|
+
maxLength: 64,
|
|
11805
|
+
required: true
|
|
11806
|
+
},
|
|
11807
|
+
state: {
|
|
11808
|
+
type: "enumeration",
|
|
11809
|
+
enum: ["active", "ended", "expired"],
|
|
11810
|
+
required: true,
|
|
11811
|
+
default: "active"
|
|
11812
|
+
},
|
|
11813
|
+
reason: {
|
|
11814
|
+
type: "string",
|
|
11815
|
+
maxLength: 255,
|
|
11816
|
+
required: true
|
|
11817
|
+
},
|
|
11818
|
+
durationMinutes: {
|
|
11819
|
+
type: "integer",
|
|
11820
|
+
min: 1,
|
|
11821
|
+
max: 60,
|
|
11822
|
+
required: true
|
|
11823
|
+
},
|
|
11824
|
+
handoff: {
|
|
11825
|
+
type: "enumeration",
|
|
11826
|
+
enum: ["frontend", "token", "preview"],
|
|
11827
|
+
required: true
|
|
11828
|
+
},
|
|
11829
|
+
notifyUser: {
|
|
11830
|
+
type: "boolean",
|
|
11831
|
+
default: false
|
|
11832
|
+
},
|
|
11833
|
+
startedAt: {
|
|
11834
|
+
type: "datetime",
|
|
11835
|
+
required: true
|
|
11836
|
+
},
|
|
11837
|
+
expiresAt: {
|
|
11838
|
+
type: "datetime",
|
|
11839
|
+
required: true
|
|
11840
|
+
},
|
|
11841
|
+
endedAt: {
|
|
11842
|
+
type: "datetime"
|
|
11843
|
+
},
|
|
11844
|
+
endReason: {
|
|
11845
|
+
type: "string",
|
|
11846
|
+
maxLength: 32
|
|
11847
|
+
},
|
|
11848
|
+
endedBy: {
|
|
11849
|
+
type: "string",
|
|
11850
|
+
maxLength: 64
|
|
11851
|
+
},
|
|
11852
|
+
codeHash: {
|
|
11853
|
+
type: "string",
|
|
11854
|
+
maxLength: 64,
|
|
11855
|
+
private: true,
|
|
11856
|
+
configurable: false
|
|
11857
|
+
},
|
|
11858
|
+
codeExpiresAt: {
|
|
11859
|
+
type: "datetime",
|
|
11860
|
+
private: true,
|
|
11861
|
+
configurable: false
|
|
11862
|
+
},
|
|
11863
|
+
credentialIssuedAt: {
|
|
11864
|
+
type: "datetime"
|
|
11865
|
+
},
|
|
11866
|
+
sessionDocumentId: {
|
|
11867
|
+
type: "string",
|
|
11868
|
+
maxLength: 64,
|
|
11869
|
+
private: true,
|
|
11870
|
+
configurable: false
|
|
11871
|
+
},
|
|
11872
|
+
nativeUserId: {
|
|
11873
|
+
type: "string",
|
|
11874
|
+
maxLength: 64,
|
|
11875
|
+
private: true,
|
|
11876
|
+
configurable: false
|
|
11877
|
+
},
|
|
11878
|
+
nativeDeviceId: {
|
|
11879
|
+
type: "string",
|
|
11880
|
+
maxLength: 80,
|
|
11881
|
+
private: true,
|
|
11882
|
+
configurable: false
|
|
11883
|
+
},
|
|
11884
|
+
tokenHash: {
|
|
11885
|
+
type: "string",
|
|
11886
|
+
maxLength: 64,
|
|
11887
|
+
private: true,
|
|
11888
|
+
configurable: false
|
|
11889
|
+
},
|
|
11890
|
+
tokenExpiresAt: {
|
|
11891
|
+
type: "datetime",
|
|
11892
|
+
private: true,
|
|
11893
|
+
configurable: false
|
|
11894
|
+
}
|
|
11895
|
+
}
|
|
11896
|
+
};
|
|
11897
|
+
}
|
|
11898
|
+
});
|
|
11899
|
+
|
|
11378
11900
|
// server/src/content-types/index.js
|
|
11379
11901
|
var require_content_types = __commonJS({
|
|
11380
11902
|
"server/src/content-types/index.js"(exports2, module2) {
|
|
@@ -11382,6 +11904,7 @@ var require_content_types = __commonJS({
|
|
|
11382
11904
|
var session = require_schema();
|
|
11383
11905
|
var revokedToken = require_schema2();
|
|
11384
11906
|
var securityEvent = require_schema3();
|
|
11907
|
+
var impersonation = require_schema4();
|
|
11385
11908
|
module2.exports = {
|
|
11386
11909
|
session: {
|
|
11387
11910
|
schema: session
|
|
@@ -11395,6 +11918,12 @@ var require_content_types = __commonJS({
|
|
|
11395
11918
|
// Content-Type Builder.
|
|
11396
11919
|
"security-event": {
|
|
11397
11920
|
schema: securityEvent
|
|
11921
|
+
},
|
|
11922
|
+
// Time-limited impersonations (4.20): who opened which account, why and
|
|
11923
|
+
// until when. Ended rows are deleted after 7 days; the security log keeps
|
|
11924
|
+
// the record. Hidden from the Content Manager and the Content-Type Builder.
|
|
11925
|
+
impersonation: {
|
|
11926
|
+
schema: impersonation
|
|
11398
11927
|
}
|
|
11399
11928
|
};
|
|
11400
11929
|
}
|
|
@@ -11532,6 +12061,25 @@ var require_content_api = __commonJS({
|
|
|
11532
12061
|
description: `End the session of a "This wasn't me" link (public, single-use token)`
|
|
11533
12062
|
}
|
|
11534
12063
|
},
|
|
12064
|
+
// ================== IMPERSONATION HAND-OFF (4.20) ==================
|
|
12065
|
+
{
|
|
12066
|
+
method: "POST",
|
|
12067
|
+
path: "/impersonation/exchange",
|
|
12068
|
+
handler: "impersonation.exchange",
|
|
12069
|
+
config: {
|
|
12070
|
+
// Public on purpose: the one-time code is the credential (32 random
|
|
12071
|
+
// bytes, stored hashed, 60 seconds, single use). Every invalid code
|
|
12072
|
+
// gets the same 400.
|
|
12073
|
+
auth: false,
|
|
12074
|
+
middlewares: [
|
|
12075
|
+
{
|
|
12076
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
12077
|
+
config: { max: 10, window: 6e4 }
|
|
12078
|
+
}
|
|
12079
|
+
],
|
|
12080
|
+
description: "Exchange a one-time impersonation code for a short-lived credential"
|
|
12081
|
+
}
|
|
12082
|
+
},
|
|
11535
12083
|
// ================== OWN SESSION MANAGEMENT ==================
|
|
11536
12084
|
{
|
|
11537
12085
|
method: "DELETE",
|
|
@@ -11558,6 +12106,7 @@ var require_admin = __commonJS({
|
|
|
11558
12106
|
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
11559
12107
|
var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
|
|
11560
12108
|
var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
|
|
12109
|
+
var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
|
|
11561
12110
|
var adminPolicy = () => [
|
|
11562
12111
|
"admin::isAuthenticatedAdmin",
|
|
11563
12112
|
{
|
|
@@ -11897,26 +12446,69 @@ var require_admin = __commonJS({
|
|
|
11897
12446
|
}
|
|
11898
12447
|
},
|
|
11899
12448
|
// ============================ SETTINGS ============================
|
|
12449
|
+
// ================== IMPERSONATION (4.20) ==================
|
|
11900
12450
|
{
|
|
11901
12451
|
method: "GET",
|
|
11902
|
-
path: "/
|
|
11903
|
-
handler: "
|
|
12452
|
+
path: "/impersonation/status",
|
|
12453
|
+
handler: "impersonation.status",
|
|
11904
12454
|
config: {
|
|
11905
12455
|
policies: adminPolicy(),
|
|
11906
|
-
|
|
12456
|
+
middlewares: adminReadRateLimit()
|
|
11907
12457
|
}
|
|
11908
12458
|
},
|
|
11909
12459
|
{
|
|
11910
|
-
method: "
|
|
11911
|
-
path: "/
|
|
11912
|
-
handler: "
|
|
12460
|
+
method: "POST",
|
|
12461
|
+
path: "/impersonation/users/:userId",
|
|
12462
|
+
handler: "impersonation.startUser",
|
|
11913
12463
|
config: {
|
|
11914
|
-
policies:
|
|
11915
|
-
|
|
11916
|
-
|
|
11917
|
-
|
|
11918
|
-
|
|
11919
|
-
|
|
12464
|
+
policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
|
|
12465
|
+
// Ten starts per ten minutes per admin.
|
|
12466
|
+
middlewares: [
|
|
12467
|
+
{
|
|
12468
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
12469
|
+
config: { max: 10, window: 10 * 60 * 1e3 }
|
|
12470
|
+
}
|
|
12471
|
+
]
|
|
12472
|
+
}
|
|
12473
|
+
},
|
|
12474
|
+
{
|
|
12475
|
+
method: "GET",
|
|
12476
|
+
path: "/impersonation/active",
|
|
12477
|
+
handler: "impersonation.listActive",
|
|
12478
|
+
config: {
|
|
12479
|
+
policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
|
|
12480
|
+
middlewares: adminReadRateLimit()
|
|
12481
|
+
}
|
|
12482
|
+
},
|
|
12483
|
+
{
|
|
12484
|
+
method: "POST",
|
|
12485
|
+
path: "/impersonation/:id/end",
|
|
12486
|
+
handler: "impersonation.end",
|
|
12487
|
+
config: {
|
|
12488
|
+
policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
|
|
12489
|
+
middlewares: adminSignOutRateLimit()
|
|
12490
|
+
}
|
|
12491
|
+
},
|
|
12492
|
+
{
|
|
12493
|
+
method: "GET",
|
|
12494
|
+
path: "/settings",
|
|
12495
|
+
handler: "settings.getSettings",
|
|
12496
|
+
config: {
|
|
12497
|
+
policies: adminPolicy(),
|
|
12498
|
+
description: "Get plugin settings (admin)"
|
|
12499
|
+
}
|
|
12500
|
+
},
|
|
12501
|
+
{
|
|
12502
|
+
method: "PUT",
|
|
12503
|
+
path: "/settings",
|
|
12504
|
+
handler: "settings.updateSettings",
|
|
12505
|
+
config: {
|
|
12506
|
+
policies: adminPolicy(),
|
|
12507
|
+
description: "Update plugin settings (admin)"
|
|
12508
|
+
}
|
|
12509
|
+
}
|
|
12510
|
+
];
|
|
12511
|
+
var devOnlyRoutes = [
|
|
11920
12512
|
{
|
|
11921
12513
|
method: "POST",
|
|
11922
12514
|
path: "/sessions/:sessionId/simulate-timeout",
|
|
@@ -14193,6 +14785,7 @@ var require_settings_access = __commonJS({
|
|
|
14193
14785
|
var { SECURITY_LOG_KEYS } = require_security_log_settings();
|
|
14194
14786
|
var { POLICY_KEYS } = require_policy_settings();
|
|
14195
14787
|
var { PROTECTED_DETECTION_KEYS } = require_detection_settings();
|
|
14788
|
+
var { IMPERSONATION_KEYS } = require_impersonation_rules();
|
|
14196
14789
|
var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
|
|
14197
14790
|
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
14198
14791
|
var GEO_SETTINGS_KEYS = Object.freeze([
|
|
@@ -14214,7 +14807,9 @@ var require_settings_access = __commonJS({
|
|
|
14214
14807
|
// limit, password-change sign-out, recording switch, per-role rules).
|
|
14215
14808
|
...POLICY_KEYS,
|
|
14216
14809
|
// Signed webhook, event selection, impossible travel and shortened IPs.
|
|
14217
|
-
...PROTECTED_DETECTION_KEYS
|
|
14810
|
+
...PROTECTED_DETECTION_KEYS,
|
|
14811
|
+
// Impersonation switch (4.20): whether admins can act as app users.
|
|
14812
|
+
...IMPERSONATION_KEYS
|
|
14218
14813
|
]);
|
|
14219
14814
|
var WEBHOOK_SECRETS = Object.freeze([
|
|
14220
14815
|
{ key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
|
|
@@ -14319,6 +14914,10 @@ var require_settings = __commonJS({
|
|
|
14319
14914
|
} = require_settings_access();
|
|
14320
14915
|
var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
|
|
14321
14916
|
var { DETECTION_DEFAULTS, validateDetectionSettings } = require_detection_settings();
|
|
14917
|
+
var {
|
|
14918
|
+
IMPERSONATION_DEFAULTS,
|
|
14919
|
+
validateImpersonationSettings
|
|
14920
|
+
} = require_impersonation_rules();
|
|
14322
14921
|
var { encryptToken } = require_encryption();
|
|
14323
14922
|
var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
|
|
14324
14923
|
var path = require("node:path");
|
|
@@ -14503,7 +15102,8 @@ var require_settings = __commonJS({
|
|
|
14503
15102
|
roleRules: [],
|
|
14504
15103
|
...DETECTION_DEFAULTS,
|
|
14505
15104
|
webhookEvents: [...DETECTION_DEFAULTS.webhookEvents],
|
|
14506
|
-
genericWebhookSecret: ""
|
|
15105
|
+
genericWebhookSecret: "",
|
|
15106
|
+
...IMPERSONATION_DEFAULTS
|
|
14507
15107
|
};
|
|
14508
15108
|
function mergeSettingsWithDefaults(stored) {
|
|
14509
15109
|
const safeStored = stored && typeof stored === "object" ? stored : {};
|
|
@@ -14717,6 +15317,9 @@ var require_settings = __commonJS({
|
|
|
14717
15317
|
const detection = validateDetectionSettings(body);
|
|
14718
15318
|
errors.push(...detection.errors);
|
|
14719
15319
|
Object.assign(next, detection.values);
|
|
15320
|
+
const impersonation = validateImpersonationSettings(body);
|
|
15321
|
+
errors.push(...impersonation.errors);
|
|
15322
|
+
Object.assign(next, impersonation.values);
|
|
14720
15323
|
if (has("genericWebhookSecret")) {
|
|
14721
15324
|
const secret = body.genericWebhookSecret;
|
|
14722
15325
|
if (secret === "") {
|
|
@@ -14904,6 +15507,10 @@ var require_settings = __commonJS({
|
|
|
14904
15507
|
return sendValidationError(ctx, "Invalid settings", outcome.errors);
|
|
14905
15508
|
}
|
|
14906
15509
|
recordSettingsChange(ctx, outcome.changed);
|
|
15510
|
+
if (outcome.changed.includes("impersonationEnabled") && !outcome.settings.impersonationEnabled) {
|
|
15511
|
+
strapi.plugin("magic-sessionmanager").service("impersonation").sweep().catch(() => {
|
|
15512
|
+
});
|
|
15513
|
+
}
|
|
14907
15514
|
strapi.log.info(
|
|
14908
15515
|
`[magic-sessionmanager/settings] Settings updated (${outcome.changed.length} keys changed)`
|
|
14909
15516
|
);
|
|
@@ -16740,6 +17347,861 @@ var require_webhooks = __commonJS({
|
|
|
16740
17347
|
}
|
|
16741
17348
|
});
|
|
16742
17349
|
|
|
17350
|
+
// server/src/services/impersonation.js
|
|
17351
|
+
var require_impersonation = __commonJS({
|
|
17352
|
+
"server/src/services/impersonation.js"(exports2, module2) {
|
|
17353
|
+
"use strict";
|
|
17354
|
+
var crypto = require("node:crypto");
|
|
17355
|
+
var { createLogger } = require_logger();
|
|
17356
|
+
var { hashToken } = require_encryption();
|
|
17357
|
+
var getClientIp = require_getClientIp();
|
|
17358
|
+
var { getPluginSettings } = require_settings_loader();
|
|
17359
|
+
var { getNativeSessionManager } = require_native_session_manager();
|
|
17360
|
+
var { REVOCATION_UID } = require_session_revocation();
|
|
17361
|
+
var {
|
|
17362
|
+
CODE_PATTERN,
|
|
17363
|
+
CODE_TTL_MS,
|
|
17364
|
+
DOCUMENT_ID_PATTERN,
|
|
17365
|
+
USER_DURATIONS,
|
|
17366
|
+
decodeJwtPayload,
|
|
17367
|
+
resolveFrontendHandoff,
|
|
17368
|
+
validateStartBody
|
|
17369
|
+
} = require_impersonation_rules();
|
|
17370
|
+
var UID = "plugin::magic-sessionmanager.impersonation";
|
|
17371
|
+
var USER_UID = "plugin::users-permissions.user";
|
|
17372
|
+
var NATIVE_SESSION_UID = "admin::session";
|
|
17373
|
+
var NATIVE_ORIGIN = "users-permissions";
|
|
17374
|
+
var DEVICE_PREFIX = "msm-impersonation-";
|
|
17375
|
+
var MAX_CACHE = 1e4;
|
|
17376
|
+
var RECORD_CACHE_MS = 5e3;
|
|
17377
|
+
var REFUSAL_DEDUP_MS = 60 * 1e3;
|
|
17378
|
+
var ENDED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
17379
|
+
var SWEEP_BATCH = 100;
|
|
17380
|
+
var ImpersonationError = class extends Error {
|
|
17381
|
+
/**
|
|
17382
|
+
* @param {400|403|404} status HTTP status.
|
|
17383
|
+
* @param {string} message Fixed message.
|
|
17384
|
+
* @param {Record<string, unknown>} [details] Safe details.
|
|
17385
|
+
*/
|
|
17386
|
+
constructor(status, message, details = {}) {
|
|
17387
|
+
super(message);
|
|
17388
|
+
this.name = "ImpersonationError";
|
|
17389
|
+
this.status = status;
|
|
17390
|
+
this.details = details;
|
|
17391
|
+
}
|
|
17392
|
+
};
|
|
17393
|
+
var EVENTS = Object.freeze({
|
|
17394
|
+
STARTED: "impersonation.started",
|
|
17395
|
+
ENDED: "impersonation.ended",
|
|
17396
|
+
EXPIRED: "impersonation.expired",
|
|
17397
|
+
REFUSED: "impersonation.refused"
|
|
17398
|
+
});
|
|
17399
|
+
function remember(map, key, value) {
|
|
17400
|
+
map.delete(key);
|
|
17401
|
+
map.set(key, value);
|
|
17402
|
+
if (map.size > MAX_CACHE) map.delete(map.keys().next().value);
|
|
17403
|
+
}
|
|
17404
|
+
function adminLabel(admin) {
|
|
17405
|
+
if (!admin) return "";
|
|
17406
|
+
const name = [admin.firstname, admin.lastname].filter(Boolean).join(" ").trim();
|
|
17407
|
+
return (name || admin.username || admin.email || "").slice(0, 120);
|
|
17408
|
+
}
|
|
17409
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
17410
|
+
const log = createLogger(strapi2);
|
|
17411
|
+
const nativeSessionCache = /* @__PURE__ */ new Map();
|
|
17412
|
+
const recordCache = /* @__PURE__ */ new Map();
|
|
17413
|
+
const refusals = /* @__PURE__ */ new Map();
|
|
17414
|
+
const query = () => strapi2.db.query(UID);
|
|
17415
|
+
const securityLog = () => strapi2.plugin("magic-sessionmanager").service("security-log");
|
|
17416
|
+
const record = (input) => {
|
|
17417
|
+
try {
|
|
17418
|
+
securityLog()?.record(input);
|
|
17419
|
+
} catch {
|
|
17420
|
+
}
|
|
17421
|
+
};
|
|
17422
|
+
const isProduction = () => process.env.NODE_ENV === "production";
|
|
17423
|
+
const service = {
|
|
17424
|
+
EVENTS,
|
|
17425
|
+
/**
|
|
17426
|
+
* Whether the feature switch is on.
|
|
17427
|
+
*
|
|
17428
|
+
* @returns {Promise<boolean>}
|
|
17429
|
+
*/
|
|
17430
|
+
async isEnabled() {
|
|
17431
|
+
try {
|
|
17432
|
+
const settings = await getPluginSettings(strapi2);
|
|
17433
|
+
return settings?.impersonationEnabled === true;
|
|
17434
|
+
} catch {
|
|
17435
|
+
return false;
|
|
17436
|
+
}
|
|
17437
|
+
},
|
|
17438
|
+
/**
|
|
17439
|
+
* The configured frontend hand-off, or null for the token fallback.
|
|
17440
|
+
*
|
|
17441
|
+
* @returns {{url: string, origin: string}|null}
|
|
17442
|
+
*/
|
|
17443
|
+
frontendHandoff() {
|
|
17444
|
+
return resolveFrontendHandoff(
|
|
17445
|
+
strapi2.config.get("plugin::magic-sessionmanager.impersonation"),
|
|
17446
|
+
{
|
|
17447
|
+
production: isProduction()
|
|
17448
|
+
}
|
|
17449
|
+
);
|
|
17450
|
+
},
|
|
17451
|
+
/**
|
|
17452
|
+
* Warns once at start-up when the frontend hand-off cannot work: the
|
|
17453
|
+
* admin panel posts the one-time code to `impersonation.frontendUrl`, and
|
|
17454
|
+
* Strapi's default Content-Security-Policy (`form-action 'self'`, from
|
|
17455
|
+
* `strapi::security`) blocks that unless the frontend origin is listed.
|
|
17456
|
+
*
|
|
17457
|
+
* @returns {boolean} Whether the setup looks complete (true without a frontend URL).
|
|
17458
|
+
*/
|
|
17459
|
+
checkHandoffSetup() {
|
|
17460
|
+
const frontend = service.frontendHandoff();
|
|
17461
|
+
if (!frontend) return true;
|
|
17462
|
+
let directives;
|
|
17463
|
+
try {
|
|
17464
|
+
const entry = (strapi2.config.get("middlewares") || []).find(
|
|
17465
|
+
(item) => item === "strapi::security" || item?.name === "strapi::security"
|
|
17466
|
+
);
|
|
17467
|
+
directives = typeof entry === "object" ? entry?.config?.contentSecurityPolicy?.directives : null;
|
|
17468
|
+
} catch {
|
|
17469
|
+
directives = null;
|
|
17470
|
+
}
|
|
17471
|
+
const formAction = directives?.["form-action"] ?? directives?.formAction;
|
|
17472
|
+
const list = Array.isArray(formAction) ? formAction.map(String) : [];
|
|
17473
|
+
if (list.includes(frontend.origin)) return true;
|
|
17474
|
+
log.warn(
|
|
17475
|
+
"[IMPERSONATION] impersonation.frontendUrl is set, but the Content-Security-Policy form-action of strapi::security does not list its origin; the admin panel cannot send the sign-in until it does (see README > Impersonation)"
|
|
17476
|
+
);
|
|
17477
|
+
return false;
|
|
17478
|
+
},
|
|
17479
|
+
/**
|
|
17480
|
+
* What the admin UI needs to know before it offers impersonation.
|
|
17481
|
+
*
|
|
17482
|
+
* @returns {Promise<{enabled: boolean, handoff: 'frontend'|'token', frontendOrigin: string|null,
|
|
17483
|
+
* durations: number[], mode: 'refresh'|'legacy'}>}
|
|
17484
|
+
*/
|
|
17485
|
+
async status() {
|
|
17486
|
+
const frontend = service.frontendHandoff();
|
|
17487
|
+
return {
|
|
17488
|
+
enabled: await service.isEnabled(),
|
|
17489
|
+
handoff: frontend ? "frontend" : "token",
|
|
17490
|
+
frontendOrigin: frontend ? frontend.origin : null,
|
|
17491
|
+
durations: [...USER_DURATIONS],
|
|
17492
|
+
mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
|
|
17493
|
+
};
|
|
17494
|
+
},
|
|
17495
|
+
/**
|
|
17496
|
+
* Records a refused start.
|
|
17497
|
+
*
|
|
17498
|
+
* @param {{actorId: unknown, targetType: 'user'|'admin', targetId: unknown, reason: string,
|
|
17499
|
+
* via?: string}} input Who tried what and why it was refused.
|
|
17500
|
+
* @returns {void}
|
|
17501
|
+
*/
|
|
17502
|
+
recordRefused({ actorId, targetType, targetId, reason, via }) {
|
|
17503
|
+
record({
|
|
17504
|
+
event: EVENTS.REFUSED,
|
|
17505
|
+
actorType: "admin",
|
|
17506
|
+
actorId: actorId == null ? null : String(actorId),
|
|
17507
|
+
targetType,
|
|
17508
|
+
targetId: targetId == null ? null : String(targetId).slice(0, 64),
|
|
17509
|
+
meta: { refusal: reason, ...via ? { via } : {} }
|
|
17510
|
+
});
|
|
17511
|
+
},
|
|
17512
|
+
/**
|
|
17513
|
+
* Starts an impersonation of an app user.
|
|
17514
|
+
*
|
|
17515
|
+
* @param {{actor: any, userDocumentId: unknown, body: unknown, ctx: any}} input Caller,
|
|
17516
|
+
* target and request body.
|
|
17517
|
+
* @returns {Promise<object>} Impersonation DTO plus the hand-off.
|
|
17518
|
+
* @throws {ImpersonationError} 400 invalid body, id or blocked user; 403 feature off or
|
|
17519
|
+
* already active; 404 unknown user.
|
|
17520
|
+
* @sideeffect Creates an impersonation row; with the token hand-off also a session; queues
|
|
17521
|
+
* `impersonation.started`; may send an email to the user.
|
|
17522
|
+
*/
|
|
17523
|
+
async startForUser({ actor, userDocumentId, body, ctx }) {
|
|
17524
|
+
const actorId = String(actor.id);
|
|
17525
|
+
const refuse = (reason, status, message) => {
|
|
17526
|
+
service.recordRefused({ actorId, targetType: "user", targetId: userDocumentId, reason });
|
|
17527
|
+
return new ImpersonationError(status, message, { reason });
|
|
17528
|
+
};
|
|
17529
|
+
if (!await service.isEnabled()) {
|
|
17530
|
+
throw refuse("disabled", 403, "Impersonation is turned off");
|
|
17531
|
+
}
|
|
17532
|
+
if (typeof userDocumentId !== "string" || !DOCUMENT_ID_PATTERN.test(userDocumentId)) {
|
|
17533
|
+
throw new ImpersonationError(400, "Invalid user id");
|
|
17534
|
+
}
|
|
17535
|
+
const { value, errors: fieldErrors } = validateStartBody(body, {
|
|
17536
|
+
durations: USER_DURATIONS,
|
|
17537
|
+
notify: true
|
|
17538
|
+
});
|
|
17539
|
+
if (!value) {
|
|
17540
|
+
throw new ImpersonationError(400, "Invalid impersonation request", {
|
|
17541
|
+
errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
|
|
17542
|
+
});
|
|
17543
|
+
}
|
|
17544
|
+
const user = await strapi2.db.query(USER_UID).findOne({
|
|
17545
|
+
where: { documentId: userDocumentId },
|
|
17546
|
+
select: ["id", "documentId", "username", "email", "blocked"]
|
|
17547
|
+
});
|
|
17548
|
+
if (!user) throw new ImpersonationError(404, "User not found");
|
|
17549
|
+
if (user.blocked === true) {
|
|
17550
|
+
throw refuse("blocked", 400, "Blocked accounts cannot be impersonated");
|
|
17551
|
+
}
|
|
17552
|
+
await service.sweep();
|
|
17553
|
+
const running = await query().findOne({
|
|
17554
|
+
where: { targetType: "user", targetId: user.documentId, state: "active" },
|
|
17555
|
+
select: ["id"]
|
|
17556
|
+
});
|
|
17557
|
+
if (running) {
|
|
17558
|
+
throw refuse("already-active", 403, "An impersonation of this user is active");
|
|
17559
|
+
}
|
|
17560
|
+
const now = /* @__PURE__ */ new Date();
|
|
17561
|
+
const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
|
|
17562
|
+
const frontend = service.frontendHandoff();
|
|
17563
|
+
const code = frontend ? crypto.randomBytes(32).toString("base64url") : null;
|
|
17564
|
+
const row = await query().create({
|
|
17565
|
+
data: {
|
|
17566
|
+
targetType: "user",
|
|
17567
|
+
targetId: user.documentId,
|
|
17568
|
+
actorId,
|
|
17569
|
+
state: "active",
|
|
17570
|
+
reason: value.reason,
|
|
17571
|
+
durationMinutes: value.durationMinutes,
|
|
17572
|
+
handoff: frontend ? "frontend" : "token",
|
|
17573
|
+
notifyUser: value.notifyUser,
|
|
17574
|
+
startedAt: now,
|
|
17575
|
+
expiresAt,
|
|
17576
|
+
...code ? { codeHash: hashToken(code), codeExpiresAt: new Date(now.getTime() + CODE_TTL_MS) } : {}
|
|
17577
|
+
}
|
|
17578
|
+
});
|
|
17579
|
+
let handoff;
|
|
17580
|
+
try {
|
|
17581
|
+
if (frontend) {
|
|
17582
|
+
handoff = {
|
|
17583
|
+
type: "frontend",
|
|
17584
|
+
url: frontend.url,
|
|
17585
|
+
field: "code",
|
|
17586
|
+
code,
|
|
17587
|
+
codeExpiresAt: new Date(now.getTime() + CODE_TTL_MS).toISOString()
|
|
17588
|
+
};
|
|
17589
|
+
} else {
|
|
17590
|
+
const credential = await service.issueCredential(row, user, ctx);
|
|
17591
|
+
handoff = { type: "token", ...credential };
|
|
17592
|
+
}
|
|
17593
|
+
} catch (err) {
|
|
17594
|
+
await service.end(row.documentId, { reason: "failed", endedBy: actorId, silent: true });
|
|
17595
|
+
throw err;
|
|
17596
|
+
}
|
|
17597
|
+
record({
|
|
17598
|
+
event: EVENTS.STARTED,
|
|
17599
|
+
actorType: "admin",
|
|
17600
|
+
actorId,
|
|
17601
|
+
targetType: "user",
|
|
17602
|
+
targetId: user.documentId,
|
|
17603
|
+
meta: {
|
|
17604
|
+
reason: value.reason,
|
|
17605
|
+
durationMinutes: value.durationMinutes,
|
|
17606
|
+
handoff: frontend ? "frontend" : "token",
|
|
17607
|
+
notifyUser: value.notifyUser
|
|
17608
|
+
}
|
|
17609
|
+
});
|
|
17610
|
+
log.info(`[IMPERSONATION] Started (${value.durationMinutes} min, ${handoff.type})`);
|
|
17611
|
+
if (value.notifyUser) service.notifyUser(user, value, expiresAt);
|
|
17612
|
+
return {
|
|
17613
|
+
impersonation: service.toDto(row, { users: /* @__PURE__ */ new Map([[user.documentId, user]]), actor }),
|
|
17614
|
+
handoff
|
|
17615
|
+
};
|
|
17616
|
+
},
|
|
17617
|
+
/**
|
|
17618
|
+
* Mints the short-lived credential of an impersonation and links its
|
|
17619
|
+
* Magic session row.
|
|
17620
|
+
*
|
|
17621
|
+
* @param {any} row Impersonation row.
|
|
17622
|
+
* @param {{id: number, documentId: string}} user Target user.
|
|
17623
|
+
* @param {any} ctx Request context (IP and user agent of the session row).
|
|
17624
|
+
* @returns {Promise<{jwt: string, refreshToken?: string, expiresAt: string}>}
|
|
17625
|
+
* @throws {Error} When the credential cannot be minted.
|
|
17626
|
+
* @sideeffect Creates a Strapi session (refresh mode) and a Magic session row.
|
|
17627
|
+
*/
|
|
17628
|
+
async issueCredential(row, user, ctx) {
|
|
17629
|
+
const now = Date.now();
|
|
17630
|
+
const expiresAt = new Date(row.expiresAt);
|
|
17631
|
+
const remainingSeconds = Math.floor((expiresAt.getTime() - now) / 1e3);
|
|
17632
|
+
if (remainingSeconds < 5) throw new ImpersonationError(403, "Impersonation ended");
|
|
17633
|
+
const native = getNativeSessionManager(strapi2);
|
|
17634
|
+
const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
|
|
17635
|
+
const headers = ctx?.request?.headers || {};
|
|
17636
|
+
const refs = { credentialIssuedAt: new Date(now) };
|
|
17637
|
+
let jwt;
|
|
17638
|
+
let refreshToken;
|
|
17639
|
+
let nativeSessionId;
|
|
17640
|
+
if (native) {
|
|
17641
|
+
const deviceId = `${DEVICE_PREFIX}${crypto.randomBytes(12).toString("hex")}`;
|
|
17642
|
+
const manager = strapi2.sessionManager(NATIVE_ORIGIN);
|
|
17643
|
+
await query().update({
|
|
17644
|
+
where: { id: row.id },
|
|
17645
|
+
data: { nativeUserId: String(user.id), nativeDeviceId: deviceId }
|
|
17646
|
+
});
|
|
17647
|
+
const refresh = await manager.generateRefreshToken(String(user.id), deviceId, {
|
|
17648
|
+
type: "session",
|
|
17649
|
+
metadata: {
|
|
17650
|
+
loginAt: new Date(now).toISOString(),
|
|
17651
|
+
deviceName: "Impersonation",
|
|
17652
|
+
msmImpersonation: row.documentId
|
|
17653
|
+
}
|
|
17654
|
+
});
|
|
17655
|
+
const access = await manager.generateAccessToken(refresh.token);
|
|
17656
|
+
if (!access || "error" in access) throw new Error("Access token could not be minted");
|
|
17657
|
+
jwt = access.token;
|
|
17658
|
+
refreshToken = refresh.token;
|
|
17659
|
+
nativeSessionId = refresh.sessionId;
|
|
17660
|
+
remember(nativeSessionCache, refresh.sessionId, row.documentId);
|
|
17661
|
+
} else {
|
|
17662
|
+
jwt = strapi2.plugin("users-permissions").service("jwt").issue({ id: user.id, msmImp: row.documentId }, { expiresIn: remainingSeconds });
|
|
17663
|
+
refs.tokenHash = hashToken(jwt);
|
|
17664
|
+
refs.tokenExpiresAt = expiresAt;
|
|
17665
|
+
}
|
|
17666
|
+
const session = await sessionService.createSession({
|
|
17667
|
+
userId: user.documentId,
|
|
17668
|
+
ip: getClientIp(ctx),
|
|
17669
|
+
userAgent: headers["user-agent"] || "unknown",
|
|
17670
|
+
token: jwt,
|
|
17671
|
+
...nativeSessionId ? { nativeSessionId } : {}
|
|
17672
|
+
});
|
|
17673
|
+
if (session?.documentId) refs.sessionDocumentId = session.documentId;
|
|
17674
|
+
await query().update({ where: { id: row.id }, data: refs });
|
|
17675
|
+
recordCache.delete(row.documentId);
|
|
17676
|
+
return {
|
|
17677
|
+
jwt,
|
|
17678
|
+
...refreshToken ? { refreshToken } : {},
|
|
17679
|
+
expiresAt: expiresAt.toISOString()
|
|
17680
|
+
};
|
|
17681
|
+
},
|
|
17682
|
+
/**
|
|
17683
|
+
* Exchanges a one-time hand-off code for the credential. The code is
|
|
17684
|
+
* single use (atomic update) and valid for 60 seconds; every failure
|
|
17685
|
+
* answers the same.
|
|
17686
|
+
*
|
|
17687
|
+
* @param {unknown} code Code from the request body.
|
|
17688
|
+
* @param {any} ctx Request context.
|
|
17689
|
+
* @returns {Promise<object|null>} Credential response, or null for any invalid code.
|
|
17690
|
+
* @sideeffect Consumes the code; creates the credential and its session.
|
|
17691
|
+
*/
|
|
17692
|
+
async exchange(code, ctx) {
|
|
17693
|
+
if (typeof code !== "string" || !CODE_PATTERN.test(code)) return null;
|
|
17694
|
+
if (!await service.isEnabled()) return null;
|
|
17695
|
+
const codeHash = hashToken(code);
|
|
17696
|
+
const now = /* @__PURE__ */ new Date();
|
|
17697
|
+
const row = await query().findOne({
|
|
17698
|
+
where: { codeHash, state: "active" }
|
|
17699
|
+
});
|
|
17700
|
+
if (!row) return null;
|
|
17701
|
+
const claimed = await query().updateMany({
|
|
17702
|
+
where: {
|
|
17703
|
+
id: row.id,
|
|
17704
|
+
codeHash,
|
|
17705
|
+
state: "active",
|
|
17706
|
+
credentialIssuedAt: { $null: true },
|
|
17707
|
+
codeExpiresAt: { $gt: now },
|
|
17708
|
+
expiresAt: { $gt: now }
|
|
17709
|
+
},
|
|
17710
|
+
data: { codeHash: null, codeExpiresAt: null, credentialIssuedAt: now }
|
|
17711
|
+
});
|
|
17712
|
+
if (Number(claimed?.count) !== 1) return null;
|
|
17713
|
+
const user = await strapi2.db.query(USER_UID).findOne({
|
|
17714
|
+
where: { documentId: row.targetId },
|
|
17715
|
+
select: ["id", "documentId", "username", "email", "blocked"]
|
|
17716
|
+
});
|
|
17717
|
+
if (!user || user.blocked === true) {
|
|
17718
|
+
await service.end(row.documentId, { reason: "failed", silent: true });
|
|
17719
|
+
return null;
|
|
17720
|
+
}
|
|
17721
|
+
try {
|
|
17722
|
+
const credential = await service.issueCredential(row, user, ctx);
|
|
17723
|
+
return {
|
|
17724
|
+
...credential,
|
|
17725
|
+
user: { id: user.id, documentId: user.documentId, username: user.username },
|
|
17726
|
+
impersonation: { id: row.documentId, expiresAt: new Date(row.expiresAt).toISOString() }
|
|
17727
|
+
};
|
|
17728
|
+
} catch (err) {
|
|
17729
|
+
await service.end(row.documentId, { reason: "failed", silent: true });
|
|
17730
|
+
throw err;
|
|
17731
|
+
}
|
|
17732
|
+
},
|
|
17733
|
+
/**
|
|
17734
|
+
* Ends an impersonation: revokes its credential first (idempotent), then
|
|
17735
|
+
* marks the row ended once (atomic), so one event is recorded.
|
|
17736
|
+
*
|
|
17737
|
+
* @param {string} documentId Impersonation id.
|
|
17738
|
+
* @param {{reason?: 'ended'|'expired'|'disabled'|'failed', endedBy?: string|null,
|
|
17739
|
+
* silent?: boolean}} [options] Why and by whom.
|
|
17740
|
+
* @returns {Promise<boolean>} Whether this call ended it.
|
|
17741
|
+
* @sideeffect Revokes sessions and tokens; updates the row; queues an event.
|
|
17742
|
+
*/
|
|
17743
|
+
async end(documentId, { reason = "ended", endedBy = null, silent = false } = {}) {
|
|
17744
|
+
const row = await query().findOne({ where: { documentId } });
|
|
17745
|
+
if (!row) return false;
|
|
17746
|
+
await service.revoke(row, reason === "expired" ? "expired" : "manual");
|
|
17747
|
+
const claimed = await query().updateMany({
|
|
17748
|
+
where: { id: row.id, state: "active" },
|
|
17749
|
+
data: {
|
|
17750
|
+
state: reason === "expired" ? "expired" : "ended",
|
|
17751
|
+
endedAt: /* @__PURE__ */ new Date(),
|
|
17752
|
+
endReason: reason,
|
|
17753
|
+
endedBy: endedBy == null ? null : String(endedBy),
|
|
17754
|
+
codeHash: null,
|
|
17755
|
+
codeExpiresAt: null
|
|
17756
|
+
}
|
|
17757
|
+
});
|
|
17758
|
+
recordCache.delete(documentId);
|
|
17759
|
+
if (Number(claimed?.count) !== 1) return false;
|
|
17760
|
+
if (!silent) {
|
|
17761
|
+
record({
|
|
17762
|
+
event: reason === "expired" ? EVENTS.EXPIRED : EVENTS.ENDED,
|
|
17763
|
+
actorType: endedBy ? "admin" : "system",
|
|
17764
|
+
actorId: endedBy ? String(endedBy) : null,
|
|
17765
|
+
targetType: row.targetType,
|
|
17766
|
+
targetId: row.targetId,
|
|
17767
|
+
meta: {
|
|
17768
|
+
startedBy: row.actorId,
|
|
17769
|
+
durationMinutes: row.durationMinutes,
|
|
17770
|
+
...reason === "expired" ? {} : { endReason: reason }
|
|
17771
|
+
}
|
|
17772
|
+
});
|
|
17773
|
+
}
|
|
17774
|
+
log.info(`[IMPERSONATION] Ended (${reason})`);
|
|
17775
|
+
return true;
|
|
17776
|
+
},
|
|
17777
|
+
/**
|
|
17778
|
+
* Revokes everything minted for an impersonation. Safe to repeat.
|
|
17779
|
+
*
|
|
17780
|
+
* @param {any} row Impersonation row.
|
|
17781
|
+
* @param {'manual'|'expired'} sessionReason Termination reason of the Magic session row.
|
|
17782
|
+
* @returns {Promise<void>}
|
|
17783
|
+
* @sideeffect Deletes Strapi session rows, writes a revocation record, ends the Magic session.
|
|
17784
|
+
*/
|
|
17785
|
+
async revoke(row, sessionReason) {
|
|
17786
|
+
if (row.nativeUserId && row.nativeDeviceId) {
|
|
17787
|
+
try {
|
|
17788
|
+
await strapi2.sessionManager(NATIVE_ORIGIN).invalidateRefreshToken(String(row.nativeUserId), String(row.nativeDeviceId));
|
|
17789
|
+
} catch (err) {
|
|
17790
|
+
log.error("[IMPERSONATION] Session revocation failed:", err?.name || "Error");
|
|
17791
|
+
}
|
|
17792
|
+
}
|
|
17793
|
+
if (row.tokenHash) {
|
|
17794
|
+
try {
|
|
17795
|
+
const documents = strapi2.documents(REVOCATION_UID);
|
|
17796
|
+
const existing = await documents.findFirst({
|
|
17797
|
+
filters: { tokenHash: row.tokenHash },
|
|
17798
|
+
fields: ["documentId"]
|
|
17799
|
+
});
|
|
17800
|
+
if (!existing) {
|
|
17801
|
+
await documents.create({
|
|
17802
|
+
data: {
|
|
17803
|
+
tokenHash: row.tokenHash,
|
|
17804
|
+
expiresAt: row.tokenExpiresAt || row.expiresAt,
|
|
17805
|
+
revokedAt: /* @__PURE__ */ new Date()
|
|
17806
|
+
}
|
|
17807
|
+
});
|
|
17808
|
+
}
|
|
17809
|
+
} catch (err) {
|
|
17810
|
+
log.error("[IMPERSONATION] Token revocation failed:", err?.name || "Error");
|
|
17811
|
+
}
|
|
17812
|
+
}
|
|
17813
|
+
if (row.sessionDocumentId) {
|
|
17814
|
+
try {
|
|
17815
|
+
await strapi2.plugin("magic-sessionmanager").service("session").terminateSession({ sessionId: row.sessionDocumentId, reason: sessionReason });
|
|
17816
|
+
} catch (err) {
|
|
17817
|
+
log.warn("[IMPERSONATION] Session row could not be ended:", err?.name || "Error");
|
|
17818
|
+
}
|
|
17819
|
+
}
|
|
17820
|
+
},
|
|
17821
|
+
/**
|
|
17822
|
+
* Ends expired impersonations, and all of them while the feature is off;
|
|
17823
|
+
* deletes rows that ended more than 7 days ago (the security log keeps
|
|
17824
|
+
* the record). Bounded per run; safe on several processes.
|
|
17825
|
+
*
|
|
17826
|
+
* @returns {Promise<number>} Number ended by this run.
|
|
17827
|
+
* @sideeffect Ends impersonations; deletes old rows.
|
|
17828
|
+
*/
|
|
17829
|
+
async sweep() {
|
|
17830
|
+
const now = /* @__PURE__ */ new Date();
|
|
17831
|
+
const enabled = await service.isEnabled();
|
|
17832
|
+
const due = await query().findMany({
|
|
17833
|
+
where: enabled ? { state: "active", expiresAt: { $lte: now } } : { state: "active" },
|
|
17834
|
+
select: ["documentId", "expiresAt"],
|
|
17835
|
+
limit: SWEEP_BATCH
|
|
17836
|
+
});
|
|
17837
|
+
let ended = 0;
|
|
17838
|
+
for (const row of due) {
|
|
17839
|
+
const expired = new Date(row.expiresAt).getTime() <= now.getTime();
|
|
17840
|
+
try {
|
|
17841
|
+
if (await service.end(row.documentId, { reason: expired ? "expired" : "disabled" })) {
|
|
17842
|
+
ended += 1;
|
|
17843
|
+
}
|
|
17844
|
+
} catch (err) {
|
|
17845
|
+
log.warn("[IMPERSONATION] Ending failed:", err?.name || "Error");
|
|
17846
|
+
}
|
|
17847
|
+
}
|
|
17848
|
+
try {
|
|
17849
|
+
await query().deleteMany({
|
|
17850
|
+
where: {
|
|
17851
|
+
state: { $ne: "active" },
|
|
17852
|
+
endedAt: { $lt: new Date(now.getTime() - ENDED_RETENTION_MS) }
|
|
17853
|
+
}
|
|
17854
|
+
});
|
|
17855
|
+
} catch (err) {
|
|
17856
|
+
log.debug("[IMPERSONATION] Old rows were not deleted:", err?.name || "Error");
|
|
17857
|
+
}
|
|
17858
|
+
return ended;
|
|
17859
|
+
},
|
|
17860
|
+
/**
|
|
17861
|
+
* Active impersonations of the given target types, newest first.
|
|
17862
|
+
*
|
|
17863
|
+
* @param {{targetTypes: Array<'user'|'admin'>, viewer: any}} input Kinds the caller may see.
|
|
17864
|
+
* @returns {Promise<object[]>} DTOs.
|
|
17865
|
+
*/
|
|
17866
|
+
async listActive({ targetTypes, viewer }) {
|
|
17867
|
+
if (!targetTypes.length) return [];
|
|
17868
|
+
await service.sweep();
|
|
17869
|
+
const rows = await query().findMany({
|
|
17870
|
+
where: { state: "active", targetType: { $in: targetTypes } },
|
|
17871
|
+
orderBy: { startedAt: "desc" },
|
|
17872
|
+
limit: 100
|
|
17873
|
+
});
|
|
17874
|
+
const userIds = rows.filter((row) => row.targetType === "user").map((row) => row.targetId);
|
|
17875
|
+
const adminIds = [
|
|
17876
|
+
...new Set(
|
|
17877
|
+
rows.flatMap((row) => [row.actorId, row.targetType === "admin" ? row.targetId : null]).filter(Boolean).map(Number).filter(Number.isInteger)
|
|
17878
|
+
)
|
|
17879
|
+
];
|
|
17880
|
+
const users = userIds.length ? await strapi2.db.query(USER_UID).findMany({
|
|
17881
|
+
where: { documentId: { $in: userIds } },
|
|
17882
|
+
select: ["documentId", "username", "email"]
|
|
17883
|
+
}) : [];
|
|
17884
|
+
const admins = adminIds.length ? await strapi2.db.query("admin::user").findMany({
|
|
17885
|
+
where: { id: { $in: adminIds } },
|
|
17886
|
+
select: ["id", "firstname", "lastname", "username", "email"]
|
|
17887
|
+
}) : [];
|
|
17888
|
+
const context = {
|
|
17889
|
+
users: new Map(users.map((user) => [user.documentId, user])),
|
|
17890
|
+
admins: new Map(admins.map((admin) => [String(admin.id), admin])),
|
|
17891
|
+
viewer
|
|
17892
|
+
};
|
|
17893
|
+
return rows.map((row) => service.toDto(row, context));
|
|
17894
|
+
},
|
|
17895
|
+
/**
|
|
17896
|
+
* One impersonation row as the admin API returns it (no codes, hashes,
|
|
17897
|
+
* session or device references).
|
|
17898
|
+
*
|
|
17899
|
+
* @param {any} row Row.
|
|
17900
|
+
* @param {{users?: Map<string, any>, admins?: Map<string, any>, actor?: any, viewer?: any}}
|
|
17901
|
+
* context Lookups for labels.
|
|
17902
|
+
* @returns {object} DTO.
|
|
17903
|
+
*/
|
|
17904
|
+
toDto(row, context = {}) {
|
|
17905
|
+
const actor = context.actor || context.admins?.get(String(row.actorId));
|
|
17906
|
+
const user = row.targetType === "user" ? context.users?.get(row.targetId) : null;
|
|
17907
|
+
const targetAdmin = row.targetType === "admin" ? context.admins?.get(String(row.targetId)) : null;
|
|
17908
|
+
const viewerId = context.viewer?.id ?? context.actor?.id;
|
|
17909
|
+
return {
|
|
17910
|
+
id: row.documentId,
|
|
17911
|
+
targetType: row.targetType,
|
|
17912
|
+
targetId: row.targetId,
|
|
17913
|
+
targetLabel: user ? String(user.username || user.email || "").slice(0, 120) : adminLabel(targetAdmin),
|
|
17914
|
+
actorId: row.actorId,
|
|
17915
|
+
actorLabel: adminLabel(actor),
|
|
17916
|
+
startedByYou: viewerId != null && String(viewerId) === String(row.actorId),
|
|
17917
|
+
reason: row.reason,
|
|
17918
|
+
durationMinutes: row.durationMinutes,
|
|
17919
|
+
handoff: row.handoff,
|
|
17920
|
+
credentialIssued: Boolean(row.credentialIssuedAt),
|
|
17921
|
+
startedAt: new Date(row.startedAt).toISOString(),
|
|
17922
|
+
expiresAt: new Date(row.expiresAt).toISOString(),
|
|
17923
|
+
state: row.state
|
|
17924
|
+
};
|
|
17925
|
+
},
|
|
17926
|
+
/**
|
|
17927
|
+
* Loads one impersonation for the request guard (5-second cache).
|
|
17928
|
+
*
|
|
17929
|
+
* @param {string} documentId Impersonation id.
|
|
17930
|
+
* @returns {Promise<{id: string, actorId: string, state: string, expiresAt: number}|null>}
|
|
17931
|
+
*/
|
|
17932
|
+
async loadForGuard(documentId) {
|
|
17933
|
+
const cached = recordCache.get(documentId);
|
|
17934
|
+
if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
|
|
17935
|
+
const row = await query().findOne({
|
|
17936
|
+
where: { documentId, targetType: "user" },
|
|
17937
|
+
select: ["documentId", "actorId", "state", "expiresAt"]
|
|
17938
|
+
});
|
|
17939
|
+
const value = row ? {
|
|
17940
|
+
id: row.documentId,
|
|
17941
|
+
actorId: row.actorId,
|
|
17942
|
+
state: row.state,
|
|
17943
|
+
expiresAt: new Date(row.expiresAt).getTime()
|
|
17944
|
+
} : null;
|
|
17945
|
+
remember(recordCache, documentId, { value, at: Date.now() });
|
|
17946
|
+
return value;
|
|
17947
|
+
},
|
|
17948
|
+
/**
|
|
17949
|
+
* The impersonation a Users & Permissions token belongs to, or null. A
|
|
17950
|
+
* legacy token carries the `msmImp` claim; a refresh-mode token names
|
|
17951
|
+
* its session, whose metadata carries the mark. The signature is checked
|
|
17952
|
+
* by Strapi afterwards.
|
|
17953
|
+
*
|
|
17954
|
+
* @param {string} token Access or refresh token.
|
|
17955
|
+
* @returns {Promise<string|null>} Impersonation id.
|
|
17956
|
+
*/
|
|
17957
|
+
async impersonationOfToken(token) {
|
|
17958
|
+
const payload = decodeJwtPayload(token);
|
|
17959
|
+
if (!payload) return null;
|
|
17960
|
+
if (typeof payload.msmImp === "string" && DOCUMENT_ID_PATTERN.test(payload.msmImp)) {
|
|
17961
|
+
return payload.msmImp;
|
|
17962
|
+
}
|
|
17963
|
+
const sessionId = payload.sessionId;
|
|
17964
|
+
if (typeof sessionId !== "string" || !/^[a-f0-9]{16,64}$/i.test(sessionId)) return null;
|
|
17965
|
+
if (nativeSessionCache.has(sessionId)) return nativeSessionCache.get(sessionId);
|
|
17966
|
+
let id = null;
|
|
17967
|
+
try {
|
|
17968
|
+
const session = await strapi2.db.query(NATIVE_SESSION_UID).findOne({
|
|
17969
|
+
where: { sessionId, origin: NATIVE_ORIGIN },
|
|
17970
|
+
select: ["metadata", "deviceId"]
|
|
17971
|
+
});
|
|
17972
|
+
const mark = session?.metadata?.msmImpersonation;
|
|
17973
|
+
if (typeof mark === "string" && DOCUMENT_ID_PATTERN.test(mark)) id = mark;
|
|
17974
|
+
else if (typeof session?.deviceId === "string" && session.deviceId.startsWith(DEVICE_PREFIX)) {
|
|
17975
|
+
id = "unknown";
|
|
17976
|
+
}
|
|
17977
|
+
if (session) remember(nativeSessionCache, sessionId, id);
|
|
17978
|
+
} catch (err) {
|
|
17979
|
+
log.warn("[IMPERSONATION] Session lookup failed:", err?.name || "Error");
|
|
17980
|
+
throw err;
|
|
17981
|
+
}
|
|
17982
|
+
return id;
|
|
17983
|
+
},
|
|
17984
|
+
/**
|
|
17985
|
+
* Records a refused Content API call made while impersonating (one event
|
|
17986
|
+
* per impersonation and reason per minute).
|
|
17987
|
+
*
|
|
17988
|
+
* @param {{id: string, actorId: string}} impersonation Impersonation.
|
|
17989
|
+
* @param {string} reason Refusal reason.
|
|
17990
|
+
* @returns {void}
|
|
17991
|
+
*/
|
|
17992
|
+
recordRefusedCall(impersonation, reason) {
|
|
17993
|
+
const key = `${impersonation.id}|${reason}`;
|
|
17994
|
+
const now = Date.now();
|
|
17995
|
+
const last = refusals.get(key);
|
|
17996
|
+
if (last !== void 0 && now - last < REFUSAL_DEDUP_MS) return;
|
|
17997
|
+
remember(refusals, key, now);
|
|
17998
|
+
record({
|
|
17999
|
+
event: EVENTS.REFUSED,
|
|
18000
|
+
actorType: "admin",
|
|
18001
|
+
actorId: impersonation.actorId,
|
|
18002
|
+
targetType: "user",
|
|
18003
|
+
targetId: null,
|
|
18004
|
+
meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
|
|
18005
|
+
});
|
|
18006
|
+
},
|
|
18007
|
+
/**
|
|
18008
|
+
* Emails the user that their account was opened (best effort, no
|
|
18009
|
+
* admin names; the reason is escaped).
|
|
18010
|
+
*
|
|
18011
|
+
* @param {{email?: string, username?: string}} user Target user.
|
|
18012
|
+
* @param {{reason: string, durationMinutes: number}} value Start values.
|
|
18013
|
+
* @param {Date} expiresAt End time.
|
|
18014
|
+
* @returns {void}
|
|
18015
|
+
* @sideeffect Sends one email through Strapi's email plugin when it is installed.
|
|
18016
|
+
*/
|
|
18017
|
+
notifyUser(user, value, expiresAt) {
|
|
18018
|
+
const emailPlugin = strapi2.plugin("email");
|
|
18019
|
+
if (!emailPlugin || typeof user?.email !== "string" || !user.email) return;
|
|
18020
|
+
const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
|
|
18021
|
+
const escapeText = (text2) => typeof notifications?.escapeHtml === "function" ? notifications.escapeHtml(text2) : String(text2).replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
|
|
18022
|
+
const minutes = value.durationMinutes;
|
|
18023
|
+
const until = expiresAt.toISOString().replace("T", " ").slice(0, 16);
|
|
18024
|
+
const text = [
|
|
18025
|
+
"An administrator opened your account for support.",
|
|
18026
|
+
`Reason: ${value.reason}`,
|
|
18027
|
+
`Duration: up to ${minutes} minutes (until ${until} UTC).`,
|
|
18028
|
+
"They act as you while this lasts but cannot change your password, email address or sessions.",
|
|
18029
|
+
"If you did not expect this, please contact support."
|
|
18030
|
+
].join("\n");
|
|
18031
|
+
const html = `<p>An administrator opened your account for support.</p><p><strong>Reason:</strong> ${escapeText(
|
|
18032
|
+
value.reason
|
|
18033
|
+
)}<br><strong>Duration:</strong> up to ${minutes} minutes (until ${escapeText(until)} UTC).</p><p>They act as you while this lasts but cannot change your password, email address or sessions.</p><p>If you did not expect this, please contact support.</p>`;
|
|
18034
|
+
Promise.resolve().then(
|
|
18035
|
+
() => emailPlugin.service("email").send({ to: user.email, subject: "Your account was opened by support", text, html })
|
|
18036
|
+
).catch((err) => {
|
|
18037
|
+
log.warn("[IMPERSONATION] Notification email failed:", err?.name || "Error");
|
|
18038
|
+
});
|
|
18039
|
+
}
|
|
18040
|
+
};
|
|
18041
|
+
return service;
|
|
18042
|
+
};
|
|
18043
|
+
module2.exports.UID = UID;
|
|
18044
|
+
module2.exports.ImpersonationError = ImpersonationError;
|
|
18045
|
+
module2.exports.DEVICE_PREFIX = DEVICE_PREFIX;
|
|
18046
|
+
}
|
|
18047
|
+
});
|
|
18048
|
+
|
|
18049
|
+
// server/src/controllers/impersonation.js
|
|
18050
|
+
var require_impersonation2 = __commonJS({
|
|
18051
|
+
"server/src/controllers/impersonation.js"(exports2, module2) {
|
|
18052
|
+
"use strict";
|
|
18053
|
+
var { DOCUMENT_ID_PATTERN } = require_impersonation_rules();
|
|
18054
|
+
var { ImpersonationError } = require_impersonation();
|
|
18055
|
+
var { sendServerError } = require_http_errors();
|
|
18056
|
+
var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
|
|
18057
|
+
function callerCan(ctx, action) {
|
|
18058
|
+
try {
|
|
18059
|
+
return ctx?.state?.userAbility?.can?.(action) === true;
|
|
18060
|
+
} catch {
|
|
18061
|
+
return false;
|
|
18062
|
+
}
|
|
18063
|
+
}
|
|
18064
|
+
function visibleTargetTypes(ctx) {
|
|
18065
|
+
return callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [];
|
|
18066
|
+
}
|
|
18067
|
+
var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
|
|
18068
|
+
async function respond(ctx, operation, handler) {
|
|
18069
|
+
try {
|
|
18070
|
+
return await handler();
|
|
18071
|
+
} catch (err) {
|
|
18072
|
+
if (err instanceof ImpersonationError && REPLY[err.status]) {
|
|
18073
|
+
return ctx[REPLY[err.status]](err.message, err.details);
|
|
18074
|
+
}
|
|
18075
|
+
strapi.log.error(
|
|
18076
|
+
`[magic-sessionmanager/impersonation] ${operation} failed:`,
|
|
18077
|
+
err?.name || "Error"
|
|
18078
|
+
);
|
|
18079
|
+
return sendServerError(ctx, 500, "Impersonation request failed");
|
|
18080
|
+
}
|
|
18081
|
+
}
|
|
18082
|
+
function requirePerson(ctx, targetType, targetId) {
|
|
18083
|
+
if (ctx.state?.auth?.strategy?.name === "admin") return;
|
|
18084
|
+
const service = strapi.plugin("magic-sessionmanager").service("impersonation");
|
|
18085
|
+
service.recordRefused({
|
|
18086
|
+
actorId: ctx.state?.user?.id,
|
|
18087
|
+
targetType,
|
|
18088
|
+
targetId,
|
|
18089
|
+
reason: "api-token",
|
|
18090
|
+
via: "admin-token"
|
|
18091
|
+
});
|
|
18092
|
+
throw new ImpersonationError(403, "API tokens cannot impersonate", { reason: "api-token" });
|
|
18093
|
+
}
|
|
18094
|
+
module2.exports = ({ strapi: app }) => {
|
|
18095
|
+
const service = () => app.plugin("magic-sessionmanager").service("impersonation");
|
|
18096
|
+
return {
|
|
18097
|
+
/**
|
|
18098
|
+
* Feature state for the admin UI.
|
|
18099
|
+
*
|
|
18100
|
+
* @route GET /magic-sessionmanager/impersonation/status
|
|
18101
|
+
* @auth Admin JWT or admin API token; `access`.
|
|
18102
|
+
* @returns {Promise<void>} `{ data: { enabled, handoff, frontendOrigin, durations, mode } }`.
|
|
18103
|
+
*/
|
|
18104
|
+
async status(ctx) {
|
|
18105
|
+
ctx.body = { data: await service().status() };
|
|
18106
|
+
},
|
|
18107
|
+
/**
|
|
18108
|
+
* Starts an impersonation of an app user.
|
|
18109
|
+
*
|
|
18110
|
+
* @route POST /magic-sessionmanager/impersonation/users/:userId
|
|
18111
|
+
* @auth Admin JWT only (admin API tokens are refused); `access` + `impersonate.users`.
|
|
18112
|
+
* @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30|60, notifyUser?: boolean }`.
|
|
18113
|
+
* @returns {Promise<void>} 201 `{ data: { impersonation, handoff } }`; `handoff` is either
|
|
18114
|
+
* `{ type: 'frontend', url, field, code, codeExpiresAt }` or `{ type: 'token', jwt,
|
|
18115
|
+
* refreshToken?, expiresAt }`, shown once.
|
|
18116
|
+
* Answers 400 for an invalid body, user id or a blocked account, 403 when the feature is
|
|
18117
|
+
* off, for API tokens or when one is already active, 404 for an unknown user.
|
|
18118
|
+
* @sideeffect Creates the impersonation and, for the token hand-off, its session; logs
|
|
18119
|
+
* `impersonation.started` or `.refused`; may email the user.
|
|
18120
|
+
*/
|
|
18121
|
+
async startUser(ctx) {
|
|
18122
|
+
ctx.set("Cache-Control", "no-store");
|
|
18123
|
+
return respond(ctx, "start", async () => {
|
|
18124
|
+
const { userId } = ctx.params;
|
|
18125
|
+
requirePerson(ctx, "user", userId);
|
|
18126
|
+
const result = await service().startForUser({
|
|
18127
|
+
actor: ctx.state.user,
|
|
18128
|
+
userDocumentId: userId,
|
|
18129
|
+
body: ctx.request.body,
|
|
18130
|
+
ctx
|
|
18131
|
+
});
|
|
18132
|
+
ctx.status = 201;
|
|
18133
|
+
ctx.body = { data: result };
|
|
18134
|
+
});
|
|
18135
|
+
},
|
|
18136
|
+
/**
|
|
18137
|
+
* Active impersonations the caller may see: app users with
|
|
18138
|
+
* `impersonate.users`.
|
|
18139
|
+
*
|
|
18140
|
+
* @route GET /magic-sessionmanager/impersonation/active
|
|
18141
|
+
* @auth Admin JWT or admin API token; `access` + `impersonate.users`.
|
|
18142
|
+
* @returns {Promise<void>} `{ data: Impersonation[] }` (at most 100).
|
|
18143
|
+
*/
|
|
18144
|
+
async listActive(ctx) {
|
|
18145
|
+
return respond(ctx, "list", async () => {
|
|
18146
|
+
const data = await service().listActive({
|
|
18147
|
+
targetTypes: visibleTargetTypes(ctx),
|
|
18148
|
+
viewer: ctx.state.user
|
|
18149
|
+
});
|
|
18150
|
+
ctx.body = { data };
|
|
18151
|
+
});
|
|
18152
|
+
},
|
|
18153
|
+
/**
|
|
18154
|
+
* Ends an active impersonation now.
|
|
18155
|
+
*
|
|
18156
|
+
* @route POST /magic-sessionmanager/impersonation/:id/end
|
|
18157
|
+
* @auth Admin JWT or admin API token; `access` + the impersonate action of its kind.
|
|
18158
|
+
* @returns {Promise<void>} `{ data: { ended: boolean } }`.
|
|
18159
|
+
* Answers 404 for an unknown id or a kind the caller may not see.
|
|
18160
|
+
* @sideeffect Revokes the credential; logs `impersonation.ended`.
|
|
18161
|
+
*/
|
|
18162
|
+
async end(ctx) {
|
|
18163
|
+
return respond(ctx, "end", async () => {
|
|
18164
|
+
const { id } = ctx.params;
|
|
18165
|
+
if (typeof id !== "string" || !DOCUMENT_ID_PATTERN.test(id)) {
|
|
18166
|
+
throw new ImpersonationError(404, "Impersonation not found");
|
|
18167
|
+
}
|
|
18168
|
+
const row = await app.db.query("plugin::magic-sessionmanager.impersonation").findOne({ where: { documentId: id }, select: ["documentId", "targetType", "state"] });
|
|
18169
|
+
if (!row || !visibleTargetTypes(ctx).includes(row.targetType)) {
|
|
18170
|
+
throw new ImpersonationError(404, "Impersonation not found");
|
|
18171
|
+
}
|
|
18172
|
+
const ended = row.state === "active" ? await service().end(id, { reason: "ended", endedBy: ctx.state.user.id }) : false;
|
|
18173
|
+
ctx.body = { data: { ended } };
|
|
18174
|
+
});
|
|
18175
|
+
},
|
|
18176
|
+
/**
|
|
18177
|
+
* Exchanges a one-time hand-off code for the impersonation credential.
|
|
18178
|
+
* Public on purpose: the code is the credential (32 random bytes, stored
|
|
18179
|
+
* hashed, valid 60 seconds, single use). Every invalid, used or expired
|
|
18180
|
+
* code gets the same 400.
|
|
18181
|
+
*
|
|
18182
|
+
* @route POST /api/magic-sessionmanager/impersonation/exchange
|
|
18183
|
+
* @auth None (rate-limited per IP address).
|
|
18184
|
+
* @param {any} ctx Body `{ code: string }`.
|
|
18185
|
+
* @returns {Promise<void>} `{ data: { jwt, refreshToken?, expiresAt, user, impersonation } }`.
|
|
18186
|
+
* Answers 400 for any unusable code.
|
|
18187
|
+
* @sideeffect Consumes the code; creates the credential and its session.
|
|
18188
|
+
*/
|
|
18189
|
+
async exchange(ctx) {
|
|
18190
|
+
const body = ctx.request.body;
|
|
18191
|
+
const valid = body && typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 1 && typeof body.code === "string";
|
|
18192
|
+
ctx.set("Cache-Control", "no-store");
|
|
18193
|
+
return respond(ctx, "exchange", async () => {
|
|
18194
|
+
const result = valid ? await service().exchange(body.code, ctx) : null;
|
|
18195
|
+
if (!result) throw new ImpersonationError(400, "Invalid or expired code");
|
|
18196
|
+
ctx.body = { data: result };
|
|
18197
|
+
});
|
|
18198
|
+
}
|
|
18199
|
+
};
|
|
18200
|
+
};
|
|
18201
|
+
module2.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
|
|
18202
|
+
}
|
|
18203
|
+
});
|
|
18204
|
+
|
|
16743
18205
|
// server/src/controllers/index.js
|
|
16744
18206
|
var require_controllers = __commonJS({
|
|
16745
18207
|
"server/src/controllers/index.js"(exports2, module2) {
|
|
@@ -16752,6 +18214,7 @@ var require_controllers = __commonJS({
|
|
|
16752
18214
|
var lockouts = require_lockouts();
|
|
16753
18215
|
var selfService = require_self_service();
|
|
16754
18216
|
var webhooks = require_webhooks();
|
|
18217
|
+
var impersonation = require_impersonation2();
|
|
16755
18218
|
module2.exports = {
|
|
16756
18219
|
session,
|
|
16757
18220
|
settings,
|
|
@@ -16760,7 +18223,8 @@ var require_controllers = __commonJS({
|
|
|
16760
18223
|
"admin-activity": adminActivity,
|
|
16761
18224
|
lockouts,
|
|
16762
18225
|
"self-service": selfService,
|
|
16763
|
-
webhooks
|
|
18226
|
+
webhooks,
|
|
18227
|
+
impersonation
|
|
16764
18228
|
};
|
|
16765
18229
|
}
|
|
16766
18230
|
});
|
|
@@ -21003,12 +22467,14 @@ var require_services = __commonJS({
|
|
|
21003
22467
|
var notifications = require_notifications();
|
|
21004
22468
|
var securityLog = require_security_log();
|
|
21005
22469
|
var webhooks = require_webhooks2();
|
|
22470
|
+
var impersonation = require_impersonation();
|
|
21006
22471
|
module2.exports = {
|
|
21007
22472
|
session,
|
|
21008
22473
|
geolocation,
|
|
21009
22474
|
notifications,
|
|
21010
22475
|
"security-log": securityLog,
|
|
21011
|
-
webhooks
|
|
22476
|
+
webhooks,
|
|
22477
|
+
impersonation
|
|
21012
22478
|
};
|
|
21013
22479
|
}
|
|
21014
22480
|
});
|