strapi-plugin-magic-sessionmanager 4.19.1 → 4.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +189 -35
  3. package/dist/admin/{Analytics-BElmzyNJ.js → Analytics-BqdZIBV4.js} +1 -1
  4. package/dist/admin/{Analytics-BqFlgLnN.mjs → Analytics-C-OLLzoB.mjs} +1 -1
  5. package/dist/admin/{App-0thsC_P9.mjs → App-BswHmNQT.mjs} +338 -4
  6. package/dist/admin/{App-D_J2eeEG.js → App-Cx9v6n_7.js} +337 -3
  7. package/dist/admin/{OnlineUsersWidget-DMZBwqdY.js → OnlineUsersWidget-BRmQPPp9.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-BgJ1ws-5.mjs → OnlineUsersWidget-Dusgjc1d.mjs} +1 -1
  9. package/dist/admin/{Settings-FOkui_ke.js → Settings-DWGuf_Z3.js} +288 -65
  10. package/dist/admin/{Settings-QN3Mu4AQ.mjs → Settings-DZyQheUS.mjs} +258 -35
  11. package/dist/admin/{de-CEyi4lpp.js → de-24TPqzG6.js} +94 -1
  12. package/dist/admin/{de-uGKSKVYD.mjs → de-DUnrmFWk.mjs} +94 -1
  13. package/dist/admin/{en-CSXeJYKy.js → en-8mBSkWOF.js} +94 -1
  14. package/dist/admin/{en-Yu7tfwqx.mjs → en-D8J__tyF.mjs} +94 -1
  15. package/dist/admin/{es-iNG9Amf9.mjs → es-BgpgWdk0.mjs} +94 -1
  16. package/dist/admin/{es-BrKqXhAU.js → es-ChUKey-Q.js} +94 -1
  17. package/dist/admin/{fr-DKZNfdlH.js → fr-DE_CWmgq.js} +94 -1
  18. package/dist/admin/{fr-CaFICHlf.mjs → fr-k1MHYKJo.mjs} +94 -1
  19. package/dist/admin/{index-DEYtqPc3.js → index-Ceh3Q1Ki.js} +622 -46
  20. package/dist/admin/{index-h-ksmM8A.mjs → index-meLDPPwt.mjs} +638 -62
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +2 -2
  23. package/dist/admin/{pt-IEagyVDL.js → pt-BjqU5ioB.js} +94 -1
  24. package/dist/admin/{pt-Bz2hWVrq.mjs → pt-DPO4DmDc.mjs} +94 -1
  25. package/dist/admin/{settingsTabs-D02CuEvs.mjs → settingsTabs-C1q5iMMw.mjs} +5 -1
  26. package/dist/admin/{settingsTabs-N4TFn-mw.js → settingsTabs-CfquZuKH.js} +5 -1
  27. package/dist/server/index.js +1965 -15
  28. package/dist/server/index.mjs +1965 -15
  29. package/package.json +1 -1
@@ -1692,6 +1692,249 @@ var require_detection_settings = __commonJS({
1692
1692
  }
1693
1693
  });
1694
1694
 
1695
+ // server/src/utils/impersonation-rules.js
1696
+ var require_impersonation_rules = __commonJS({
1697
+ "server/src/utils/impersonation-rules.js"(exports, module) {
1698
+ "use strict";
1699
+ var IMPERSONATION_DEFAULTS = Object.freeze({ impersonationEnabled: false });
1700
+ var IMPERSONATION_KEYS = Object.freeze(Object.keys(IMPERSONATION_DEFAULTS));
1701
+ var USER_DURATIONS = Object.freeze([15, 30, 60]);
1702
+ var ADMIN_DURATIONS = Object.freeze([15, 30]);
1703
+ var REASON_MIN = 3;
1704
+ var REASON_MAX = 255;
1705
+ var CODE_TTL_MS = 60 * 1e3;
1706
+ var IMPERSONATION_HEADER = "X-Magic-Impersonation";
1707
+ var CODE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
1708
+ var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
1709
+ var ADMIN_ID_PATTERN = /^[1-9][0-9]{0,15}$/;
1710
+ var LOOPBACK_HOSTS = Object.freeze(["localhost", "127.0.0.1", "[::1]"]);
1711
+ function normalizeImpersonationSettings(stored) {
1712
+ return { impersonationEnabled: stored?.impersonationEnabled === true };
1713
+ }
1714
+ function validateImpersonationSettings(body) {
1715
+ const values = {};
1716
+ const errors = [];
1717
+ if (Object.prototype.hasOwnProperty.call(body, "impersonationEnabled")) {
1718
+ if (typeof body.impersonationEnabled !== "boolean") {
1719
+ errors.push({
1720
+ path: ["impersonationEnabled"],
1721
+ message: "impersonationEnabled must be a boolean"
1722
+ });
1723
+ } else {
1724
+ values.impersonationEnabled = body.impersonationEnabled;
1725
+ }
1726
+ }
1727
+ return { values, errors };
1728
+ }
1729
+ function parseHandoffUrl(value, env) {
1730
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return null;
1731
+ let url;
1732
+ try {
1733
+ url = new URL(value);
1734
+ } catch {
1735
+ return null;
1736
+ }
1737
+ if (url.username || url.password || url.hash) return null;
1738
+ if (url.protocol === "https:") return url;
1739
+ if (url.protocol === "http:" && !env.production && LOOPBACK_HOSTS.includes(url.hostname)) {
1740
+ return url;
1741
+ }
1742
+ return null;
1743
+ }
1744
+ function validateImpersonationConfig(config, env) {
1745
+ if (config === void 0 || config === null) return;
1746
+ if (typeof config !== "object" || Array.isArray(config)) {
1747
+ throw new Error("impersonation must be an object");
1748
+ }
1749
+ const { frontendUrl, allowedFrontendOrigins } = (
1750
+ /** @type {any} */
1751
+ config
1752
+ );
1753
+ const unknown = Object.keys(config).filter(
1754
+ (key) => !["frontendUrl", "allowedFrontendOrigins"].includes(key)
1755
+ );
1756
+ if (unknown.length > 0) throw new Error("impersonation has unknown keys");
1757
+ if (allowedFrontendOrigins !== void 0 && allowedFrontendOrigins !== null) {
1758
+ if (!Array.isArray(allowedFrontendOrigins) || allowedFrontendOrigins.length > 20) {
1759
+ throw new Error("impersonation.allowedFrontendOrigins must be a list of at most 20 origins");
1760
+ }
1761
+ for (const origin of allowedFrontendOrigins) {
1762
+ const url2 = parseHandoffUrl(origin, env);
1763
+ if (!url2 || url2.origin !== origin) {
1764
+ throw new Error(
1765
+ "impersonation.allowedFrontendOrigins entries must be https origins without a path"
1766
+ );
1767
+ }
1768
+ }
1769
+ }
1770
+ if (frontendUrl === void 0 || frontendUrl === null || frontendUrl === "") return;
1771
+ const url = parseHandoffUrl(frontendUrl, env);
1772
+ if (!url || url.search) {
1773
+ throw new Error(
1774
+ "impersonation.frontendUrl must be an https URL without user info, query or fragment"
1775
+ );
1776
+ }
1777
+ if (Array.isArray(allowedFrontendOrigins) && !allowedFrontendOrigins.includes(url.origin)) {
1778
+ throw new Error("impersonation.frontendUrl must use an origin of allowedFrontendOrigins");
1779
+ }
1780
+ }
1781
+ function resolveFrontendHandoff(config, env) {
1782
+ try {
1783
+ validateImpersonationConfig(config, env);
1784
+ } catch {
1785
+ return null;
1786
+ }
1787
+ const url = parseHandoffUrl(
1788
+ /** @type {any} */
1789
+ config?.frontendUrl,
1790
+ env
1791
+ );
1792
+ return url ? { url: url.toString(), origin: url.origin } : null;
1793
+ }
1794
+ function cleanReason(value) {
1795
+ if (typeof value !== "string" || value.length > REASON_MAX * 4) return null;
1796
+ const clean = value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
1797
+ if (clean.length < REASON_MIN || clean.length > REASON_MAX) return null;
1798
+ return clean;
1799
+ }
1800
+ function validateStartBody(body, { durations, notify }) {
1801
+ const errors = [];
1802
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
1803
+ return { value: null, errors: [{ path: [], message: "Body must be an object" }] };
1804
+ }
1805
+ const allowed = ["reason", "durationMinutes", ...notify ? ["notifyUser"] : []];
1806
+ for (const key of Object.keys(body)) {
1807
+ if (!allowed.includes(key)) errors.push({ path: [key], message: "Unknown field" });
1808
+ }
1809
+ const source = (
1810
+ /** @type {Record<string, unknown>} */
1811
+ body
1812
+ );
1813
+ const reason = cleanReason(source.reason);
1814
+ if (reason === null) {
1815
+ errors.push({
1816
+ path: ["reason"],
1817
+ message: `reason must be ${REASON_MIN} to ${REASON_MAX} characters`
1818
+ });
1819
+ }
1820
+ const duration = source.durationMinutes;
1821
+ if (typeof duration !== "number" || !durations.includes(duration)) {
1822
+ errors.push({
1823
+ path: ["durationMinutes"],
1824
+ message: `durationMinutes must be one of: ${durations.join(", ")}`
1825
+ });
1826
+ }
1827
+ if (notify && source.notifyUser !== void 0 && typeof source.notifyUser !== "boolean") {
1828
+ errors.push({ path: ["notifyUser"], message: "notifyUser must be a boolean" });
1829
+ }
1830
+ if (errors.length > 0) return { value: null, errors };
1831
+ return {
1832
+ value: {
1833
+ reason: (
1834
+ /** @type {string} */
1835
+ reason
1836
+ ),
1837
+ durationMinutes: (
1838
+ /** @type {number} */
1839
+ duration
1840
+ ),
1841
+ notifyUser: source.notifyUser === true
1842
+ },
1843
+ errors
1844
+ };
1845
+ }
1846
+ function normalizePath(path) {
1847
+ const value = String(path || "").toLowerCase().replace(/\/{2,}/g, "/");
1848
+ return value.length > 1 ? value.replace(/\/+$/, "") || "/" : value;
1849
+ }
1850
+ var PLUGIN_READ_ROUTES = Object.freeze([
1851
+ /^\/magic-sessionmanager\/my-sessions$/,
1852
+ /^\/magic-sessionmanager\/current-session$/,
1853
+ /^\/magic-sessionmanager\/user\/[^/]{1,64}\/sessions$/
1854
+ ]);
1855
+ function classifyRestrictedRequest(method, path, apiPrefix = "/api") {
1856
+ const verb = String(method || "").toUpperCase();
1857
+ const normalized = normalizePath(path);
1858
+ const prefix = normalizePath(apiPrefix || "/api");
1859
+ const base = prefix === "/" ? "" : prefix;
1860
+ if (!(normalized === base || normalized.startsWith(`${base}/`))) return null;
1861
+ const rest = normalized.slice(base.length) || "/";
1862
+ const isRead = verb === "GET" || verb === "HEAD";
1863
+ if (rest === "/auth" || rest.startsWith("/auth/")) {
1864
+ if (verb === "POST" && rest === "/auth/refresh") return null;
1865
+ if (isRead && rest === "/auth/sessions") return null;
1866
+ if (rest === "/auth/logout" || rest.startsWith("/auth/sessions")) return "sessions";
1867
+ return "credentials";
1868
+ }
1869
+ if (rest === "/connect" || rest.startsWith("/connect/")) return "credentials";
1870
+ if (rest === "/users" || rest.startsWith("/users/")) return isRead ? null : "account";
1871
+ if (rest.startsWith("/magic-sessionmanager/") || rest === "/magic-sessionmanager") {
1872
+ const sub = rest.slice("/magic-sessionmanager".length);
1873
+ if (isRead && PLUGIN_READ_ROUTES.some((pattern) => pattern.test(`/magic-sessionmanager${sub}`)))
1874
+ return null;
1875
+ if (sub === "/my-data" || sub === "/not-me") return "account";
1876
+ return "sessions";
1877
+ }
1878
+ if (rest.startsWith("/magic-link/") || rest.startsWith("/passwordless/")) {
1879
+ return "credentials";
1880
+ }
1881
+ return null;
1882
+ }
1883
+ var GRAPHQL_RESTRICTED = /\b(login|register|forgotPassword|resetPassword|changePassword|emailConfirmation|createUsersPermissionsUser|updateUsersPermissionsUser|deleteUsersPermissionsUser)\b/;
1884
+ var MAX_GRAPHQL_LENGTH = 100 * 1024;
1885
+ function isRestrictedGraphqlRequest(body, queryString) {
1886
+ const documents = [];
1887
+ const collect = (value) => {
1888
+ if (value && typeof value === "object" && typeof value.query === "string") {
1889
+ documents.push(value.query);
1890
+ }
1891
+ };
1892
+ if (Array.isArray(body)) body.slice(0, 50).forEach(collect);
1893
+ else collect(body);
1894
+ if (typeof queryString === "string") documents.push(queryString);
1895
+ return documents.some((text) => {
1896
+ if (text.length > MAX_GRAPHQL_LENGTH) return true;
1897
+ return /\bmutation\b/.test(text) && GRAPHQL_RESTRICTED.test(text);
1898
+ });
1899
+ }
1900
+ function decodeJwtPayload(token) {
1901
+ if (typeof token !== "string" || token.length > 8192) return null;
1902
+ const parts = token.split(".");
1903
+ if (parts.length !== 3 || !parts[1]) return null;
1904
+ try {
1905
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
1906
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : null;
1907
+ } catch {
1908
+ return null;
1909
+ }
1910
+ }
1911
+ module.exports = {
1912
+ ADMIN_DURATIONS,
1913
+ ADMIN_ID_PATTERN,
1914
+ CODE_PATTERN,
1915
+ CODE_TTL_MS,
1916
+ DOCUMENT_ID_PATTERN,
1917
+ IMPERSONATION_DEFAULTS,
1918
+ IMPERSONATION_HEADER,
1919
+ IMPERSONATION_KEYS,
1920
+ REASON_MAX,
1921
+ REASON_MIN,
1922
+ USER_DURATIONS,
1923
+ classifyRestrictedRequest,
1924
+ cleanReason,
1925
+ decodeJwtPayload,
1926
+ isRestrictedGraphqlRequest,
1927
+ normalizeImpersonationSettings,
1928
+ normalizePath,
1929
+ parseHandoffUrl,
1930
+ resolveFrontendHandoff,
1931
+ validateImpersonationConfig,
1932
+ validateImpersonationSettings,
1933
+ validateStartBody
1934
+ };
1935
+ }
1936
+ });
1937
+
1695
1938
  // server/src/utils/settings-loader.js
1696
1939
  var require_settings_loader = __commonJS({
1697
1940
  "server/src/utils/settings-loader.js"(exports, module) {
@@ -1699,6 +1942,7 @@ var require_settings_loader = __commonJS({
1699
1942
  var { getCoordinator } = require_coordination();
1700
1943
  var { normalizePolicySettings } = require_policy_settings();
1701
1944
  var { normalizeDetectionSettings } = require_detection_settings();
1945
+ var { normalizeImpersonationSettings } = require_impersonation_rules();
1702
1946
  var PLUGIN_ID = "magic-sessionmanager";
1703
1947
  var SETTINGS_KEY = "settings";
1704
1948
  var CACHE_TTL_MS = 30 * 1e3;
@@ -1835,6 +2079,7 @@ var require_settings_loader = __commonJS({
1835
2079
  if (typeof stored.genericWebhookSecret === "string") {
1836
2080
  out.genericWebhookSecret = stored.genericWebhookSecret;
1837
2081
  }
2082
+ Object.assign(out, normalizeImpersonationSettings(stored));
1838
2083
  return out;
1839
2084
  }
1840
2085
  async function getPluginSettings(strapi2) {
@@ -1956,12 +2201,23 @@ var require_security_log_model = __commonJS({
1956
2201
  USER_NEW_DEVICE: "user.sign-in.new-device",
1957
2202
  USER_IMPOSSIBLE_TRAVEL: "user.sign-in.impossible-travel",
1958
2203
  USER_NOT_ME: "user.not-me",
1959
- USER_DATA_EXPORTED: "user.data.exported"
2204
+ USER_DATA_EXPORTED: "user.data.exported",
2205
+ // Impersonation (4.20): always recorded while the feature is on; the actor
2206
+ // is the real admin, the target the app user. `meta` holds the reason and
2207
+ // the duration, never a code or token.
2208
+ IMPERSONATION_STARTED: "impersonation.started",
2209
+ IMPERSONATION_ENDED: "impersonation.ended",
2210
+ IMPERSONATION_EXPIRED: "impersonation.expired",
2211
+ IMPERSONATION_REFUSED: "impersonation.refused"
1960
2212
  });
1961
2213
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
1962
2214
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
1963
2215
  SECURITY_EVENTS.SETTINGS_UPDATED,
1964
- SECURITY_EVENTS.LOG_READ
2216
+ SECURITY_EVENTS.LOG_READ,
2217
+ SECURITY_EVENTS.IMPERSONATION_STARTED,
2218
+ SECURITY_EVENTS.IMPERSONATION_ENDED,
2219
+ SECURITY_EVENTS.IMPERSONATION_EXPIRED,
2220
+ SECURITY_EVENTS.IMPERSONATION_REFUSED
1965
2221
  ]);
1966
2222
  function dropRankOf(event) {
1967
2223
  if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
@@ -2249,7 +2505,8 @@ var require_security_log_hardening = __commonJS({
2249
2505
  var INTERNAL_TYPES = Object.freeze([
2250
2506
  `plugin::${PLUGIN_ID}.session`,
2251
2507
  `plugin::${PLUGIN_ID}.revoked-token`,
2252
- EVENT_UID
2508
+ EVENT_UID,
2509
+ `plugin::${PLUGIN_ID}.impersonation`
2253
2510
  ]);
2254
2511
  var MIGRATIONS_KEY = "migrations";
2255
2512
  var MIGRATION_BATCH = 500;
@@ -2477,6 +2734,28 @@ var require_register = __commonJS({
2477
2734
  uid: "lockouts.unlock",
2478
2735
  subCategory: "General",
2479
2736
  pluginName: "magic-sessionmanager"
2737
+ },
2738
+ // Impersonation of app users (4.20): a short-lived credential for one
2739
+ // Users & Permissions user, with a reason, logged. Super Admin holds it
2740
+ // automatically; other roles only when granted. Works only while the
2741
+ // Impersonation switch in the settings is on.
2742
+ {
2743
+ section: "plugins",
2744
+ displayName: "Impersonate app users",
2745
+ uid: "impersonate.users",
2746
+ subCategory: "Impersonation",
2747
+ pluginName: "magic-sessionmanager"
2748
+ },
2749
+ // "View as admin" (4.20): a read-only preview of which content types and
2750
+ // actions another admin can use. Never a Super Admin, never oneself, and
2751
+ // for non-Super-Admins only admins whose permissions are a subset of
2752
+ // their own.
2753
+ {
2754
+ section: "plugins",
2755
+ displayName: "View as admin (read-only permission preview)",
2756
+ uid: "impersonate.admins",
2757
+ subCategory: "Impersonation",
2758
+ pluginName: "magic-sessionmanager"
2480
2759
  }
2481
2760
  ]);
2482
2761
  disableGraphqlShadowCrud(strapi2, log);
@@ -4997,6 +5276,106 @@ var require_sign_in_signals = __commonJS({
4997
5276
  }
4998
5277
  });
4999
5278
 
5279
+ // server/src/middlewares/impersonation-guard.js
5280
+ var require_impersonation_guard = __commonJS({
5281
+ "server/src/middlewares/impersonation-guard.js"(exports, module) {
5282
+ "use strict";
5283
+ var { extractBearerToken } = require_extract_token();
5284
+ var { getIncomingRefreshToken, getRefreshCookieName } = require_refresh_token();
5285
+ var {
5286
+ IMPERSONATION_HEADER,
5287
+ classifyRestrictedRequest,
5288
+ isRestrictedGraphqlRequest,
5289
+ normalizePath
5290
+ } = require_impersonation_rules();
5291
+ function reply(ctx, status, name, message, reason) {
5292
+ ctx.status = status;
5293
+ ctx.body = { data: null, error: { status, name, message, details: { reason } } };
5294
+ }
5295
+ function markResponse(ctx) {
5296
+ ctx.set(IMPERSONATION_HEADER, "true");
5297
+ if (!ctx.response.get("Access-Control-Allow-Origin")) return;
5298
+ const exposed = ctx.response.get("Access-Control-Expose-Headers");
5299
+ const list = exposed ? exposed.split(",").map((item) => item.trim()) : [];
5300
+ if (!list.some((item) => item.toLowerCase() === IMPERSONATION_HEADER.toLowerCase())) {
5301
+ ctx.set("Access-Control-Expose-Headers", [...list, IMPERSONATION_HEADER].join(", "));
5302
+ }
5303
+ }
5304
+ module.exports = (_config, { strapi: strapi2 }) => {
5305
+ const service = () => strapi2.plugin("magic-sessionmanager").service("impersonation");
5306
+ return async function impersonationGuard(ctx, next) {
5307
+ const prefix = normalizePath(strapi2.config.get("api.rest.prefix", "/api") || "/api");
5308
+ const path = normalizePath(ctx.path);
5309
+ const graphqlEndpoint = normalizePath(
5310
+ strapi2.plugin("graphql")?.config?.("endpoint") || "/graphql"
5311
+ );
5312
+ const isGraphql = path === graphqlEndpoint;
5313
+ const base = prefix === "/" ? "" : prefix;
5314
+ const isContentApi = path === base || path.startsWith(`${base}/`);
5315
+ if (!isGraphql && !isContentApi) return next();
5316
+ let impersonationId = null;
5317
+ try {
5318
+ const bearer = extractBearerToken(ctx);
5319
+ if (bearer) impersonationId = await service().impersonationOfToken(bearer);
5320
+ if (!impersonationId && ctx.method === "POST" && path === `${base}/auth/refresh`) {
5321
+ const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
5322
+ if (refreshToken) impersonationId = await service().impersonationOfToken(refreshToken);
5323
+ }
5324
+ } catch {
5325
+ return reply(
5326
+ ctx,
5327
+ 503,
5328
+ "ServiceUnavailableError",
5329
+ "Session check unavailable",
5330
+ "impersonation-check"
5331
+ );
5332
+ }
5333
+ if (!impersonationId) return next();
5334
+ markResponse(ctx);
5335
+ let impersonation;
5336
+ try {
5337
+ impersonation = await service().loadForGuard(impersonationId);
5338
+ } catch {
5339
+ return reply(
5340
+ ctx,
5341
+ 503,
5342
+ "ServiceUnavailableError",
5343
+ "Session check unavailable",
5344
+ "impersonation-check"
5345
+ );
5346
+ }
5347
+ if (!impersonation || impersonation.state !== "active") {
5348
+ return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-ended");
5349
+ }
5350
+ if (Date.now() >= impersonation.expiresAt) {
5351
+ try {
5352
+ await service().end(impersonation.id, { reason: "expired" });
5353
+ } catch {
5354
+ }
5355
+ return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-expired");
5356
+ }
5357
+ const restricted = isGraphql ? isRestrictedGraphqlRequest(ctx.request?.body, ctx.query?.query) ? "credentials" : null : classifyRestrictedRequest(ctx.method, path, prefix);
5358
+ if (restricted) {
5359
+ service().recordRefusedCall(impersonation, restricted);
5360
+ return reply(
5361
+ ctx,
5362
+ 403,
5363
+ "ForbiddenError",
5364
+ "Not allowed while impersonating",
5365
+ `impersonation-${restricted}`
5366
+ );
5367
+ }
5368
+ ctx.state.magicImpersonation = { id: impersonation.id, actorId: impersonation.actorId };
5369
+ try {
5370
+ await next();
5371
+ } finally {
5372
+ markResponse(ctx);
5373
+ }
5374
+ };
5375
+ };
5376
+ }
5377
+ });
5378
+
5000
5379
  // server/src/middlewares/session-rejection-headers.js
5001
5380
  var require_session_rejection_headers = __commonJS({
5002
5381
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -9290,6 +9669,13 @@ var require_bootstrap = __commonJS({
9290
9669
  5 * 60 * 1e3
9291
9670
  );
9292
9671
  log.info("[TIME] Dynamic cleanup + retention scheduled");
9672
+ strapi2.server.use(require_impersonation_guard()({}, { strapi: strapi2 }));
9673
+ const impersonationSweep = setInterval(() => {
9674
+ strapi2.plugin("magic-sessionmanager").service("impersonation").sweep().catch((err) => log.warn("[IMPERSONATION] Sweep failed:", err?.name || "Error"));
9675
+ }, 30 * 1e3);
9676
+ impersonationSweep.unref?.();
9677
+ strapi2.sessionManagerIntervals.impersonationSweep = impersonationSweep;
9678
+ strapi2.plugin("magic-sessionmanager").service("impersonation").checkHandoffSetup();
9293
9679
  mountPreLoginGeoGuard({ strapi: strapi2, log });
9294
9680
  mountFailedLoginLockout({ strapi: strapi2, log });
9295
9681
  mountLogoutRoute({ strapi: strapi2, log, sessionService });
@@ -11036,6 +11422,7 @@ var require_destroy = __commonJS({
11036
11422
  var require_config = __commonJS({
11037
11423
  "server/src/config/index.js"(exports, module) {
11038
11424
  "use strict";
11425
+ var { validateImpersonationConfig } = require_impersonation_rules();
11039
11426
  module.exports = {
11040
11427
  default: {
11041
11428
  debug: false,
@@ -11109,6 +11496,9 @@ var require_config = __commonJS({
11109
11496
  if (config.geoLookupFailureMode !== void 0 && !["auto", "allow", "block"].includes(config.geoLookupFailureMode)) {
11110
11497
  throw new Error("geoLookupFailureMode must be one of: auto, allow, block");
11111
11498
  }
11499
+ validateImpersonationConfig(config.impersonation, {
11500
+ production: process.env.NODE_ENV === "production"
11501
+ });
11112
11502
  if (config.coordination !== void 0 && config.coordination !== null) {
11113
11503
  const coordination = config.coordination;
11114
11504
  if (typeof coordination !== "object" || Array.isArray(coordination)) {
@@ -11381,6 +11771,153 @@ var require_schema3 = __commonJS({
11381
11771
  }
11382
11772
  });
11383
11773
 
11774
+ // server/src/content-types/impersonation/schema.json
11775
+ var require_schema4 = __commonJS({
11776
+ "server/src/content-types/impersonation/schema.json"(exports, module) {
11777
+ module.exports = {
11778
+ kind: "collectionType",
11779
+ collectionName: "magic_sessions_impersonations",
11780
+ info: {
11781
+ singularName: "impersonation",
11782
+ pluralName: "impersonations",
11783
+ displayName: "Impersonation",
11784
+ description: "Time-limited impersonations of app users and permission previews of admins, started by an admin with a reason"
11785
+ },
11786
+ options: {
11787
+ draftAndPublish: false,
11788
+ comment: ""
11789
+ },
11790
+ pluginOptions: {
11791
+ "content-manager": {
11792
+ visible: false
11793
+ },
11794
+ "content-type-builder": {
11795
+ visible: false
11796
+ }
11797
+ },
11798
+ indexes: [
11799
+ {
11800
+ name: "msm_impersonations_state",
11801
+ columns: ["state", "expires_at"]
11802
+ },
11803
+ {
11804
+ name: "msm_impersonations_code",
11805
+ columns: ["code_hash"]
11806
+ },
11807
+ {
11808
+ name: "msm_impersonations_target",
11809
+ columns: ["target_type", "target_id", "state"]
11810
+ }
11811
+ ],
11812
+ attributes: {
11813
+ targetType: {
11814
+ type: "enumeration",
11815
+ enum: ["user", "admin"],
11816
+ required: true
11817
+ },
11818
+ targetId: {
11819
+ type: "string",
11820
+ maxLength: 64,
11821
+ required: true
11822
+ },
11823
+ actorId: {
11824
+ type: "string",
11825
+ maxLength: 64,
11826
+ required: true
11827
+ },
11828
+ state: {
11829
+ type: "enumeration",
11830
+ enum: ["active", "ended", "expired"],
11831
+ required: true,
11832
+ default: "active"
11833
+ },
11834
+ reason: {
11835
+ type: "string",
11836
+ maxLength: 255,
11837
+ required: true
11838
+ },
11839
+ durationMinutes: {
11840
+ type: "integer",
11841
+ min: 1,
11842
+ max: 60,
11843
+ required: true
11844
+ },
11845
+ handoff: {
11846
+ type: "enumeration",
11847
+ enum: ["frontend", "token", "preview"],
11848
+ required: true
11849
+ },
11850
+ notifyUser: {
11851
+ type: "boolean",
11852
+ default: false
11853
+ },
11854
+ startedAt: {
11855
+ type: "datetime",
11856
+ required: true
11857
+ },
11858
+ expiresAt: {
11859
+ type: "datetime",
11860
+ required: true
11861
+ },
11862
+ endedAt: {
11863
+ type: "datetime"
11864
+ },
11865
+ endReason: {
11866
+ type: "string",
11867
+ maxLength: 32
11868
+ },
11869
+ endedBy: {
11870
+ type: "string",
11871
+ maxLength: 64
11872
+ },
11873
+ codeHash: {
11874
+ type: "string",
11875
+ maxLength: 64,
11876
+ private: true,
11877
+ configurable: false
11878
+ },
11879
+ codeExpiresAt: {
11880
+ type: "datetime",
11881
+ private: true,
11882
+ configurable: false
11883
+ },
11884
+ credentialIssuedAt: {
11885
+ type: "datetime"
11886
+ },
11887
+ sessionDocumentId: {
11888
+ type: "string",
11889
+ maxLength: 64,
11890
+ private: true,
11891
+ configurable: false
11892
+ },
11893
+ nativeUserId: {
11894
+ type: "string",
11895
+ maxLength: 64,
11896
+ private: true,
11897
+ configurable: false
11898
+ },
11899
+ nativeDeviceId: {
11900
+ type: "string",
11901
+ maxLength: 80,
11902
+ private: true,
11903
+ configurable: false
11904
+ },
11905
+ tokenHash: {
11906
+ type: "string",
11907
+ maxLength: 64,
11908
+ private: true,
11909
+ configurable: false
11910
+ },
11911
+ tokenExpiresAt: {
11912
+ type: "datetime",
11913
+ private: true,
11914
+ configurable: false
11915
+ }
11916
+ }
11917
+ };
11918
+ }
11919
+ });
11920
+
11384
11921
  // server/src/content-types/index.js
11385
11922
  var require_content_types = __commonJS({
11386
11923
  "server/src/content-types/index.js"(exports, module) {
@@ -11388,6 +11925,7 @@ var require_content_types = __commonJS({
11388
11925
  var session = require_schema();
11389
11926
  var revokedToken = require_schema2();
11390
11927
  var securityEvent = require_schema3();
11928
+ var impersonation = require_schema4();
11391
11929
  module.exports = {
11392
11930
  session: {
11393
11931
  schema: session
@@ -11401,6 +11939,12 @@ var require_content_types = __commonJS({
11401
11939
  // Content-Type Builder.
11402
11940
  "security-event": {
11403
11941
  schema: securityEvent
11942
+ },
11943
+ // Time-limited impersonations (4.20): who opened which account, why and
11944
+ // until when. Ended rows are deleted after 7 days; the security log keeps
11945
+ // the record. Hidden from the Content Manager and the Content-Type Builder.
11946
+ impersonation: {
11947
+ schema: impersonation
11404
11948
  }
11405
11949
  };
11406
11950
  }
@@ -11538,6 +12082,25 @@ var require_content_api = __commonJS({
11538
12082
  description: `End the session of a "This wasn't me" link (public, single-use token)`
11539
12083
  }
11540
12084
  },
12085
+ // ================== IMPERSONATION HAND-OFF (4.20) ==================
12086
+ {
12087
+ method: "POST",
12088
+ path: "/impersonation/exchange",
12089
+ handler: "impersonation.exchange",
12090
+ config: {
12091
+ // Public on purpose: the one-time code is the credential (32 random
12092
+ // bytes, stored hashed, 60 seconds, single use). Every invalid code
12093
+ // gets the same 400.
12094
+ auth: false,
12095
+ middlewares: [
12096
+ {
12097
+ name: "plugin::magic-sessionmanager.rate-limit",
12098
+ config: { max: 10, window: 6e4 }
12099
+ }
12100
+ ],
12101
+ description: "Exchange a one-time impersonation code for a short-lived credential"
12102
+ }
12103
+ },
11541
12104
  // ================== OWN SESSION MANAGEMENT ==================
11542
12105
  {
11543
12106
  method: "DELETE",
@@ -11564,6 +12127,12 @@ var require_admin = __commonJS({
11564
12127
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
11565
12128
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
11566
12129
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12130
+ var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
12131
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
12132
+ var impersonationListPolicy = () => [
12133
+ ...adminPolicy(),
12134
+ "plugin::magic-sessionmanager.can-impersonate"
12135
+ ];
11567
12136
  var adminPolicy = () => [
11568
12137
  "admin::isAuthenticatedAdmin",
11569
12138
  {
@@ -11903,21 +12472,88 @@ var require_admin = __commonJS({
11903
12472
  }
11904
12473
  },
11905
12474
  // ============================ SETTINGS ============================
12475
+ // ================== IMPERSONATION (4.20) ==================
11906
12476
  {
11907
12477
  method: "GET",
11908
- path: "/settings",
11909
- handler: "settings.getSettings",
12478
+ path: "/impersonation/status",
12479
+ handler: "impersonation.status",
11910
12480
  config: {
11911
12481
  policies: adminPolicy(),
11912
- description: "Get plugin settings (admin)"
12482
+ middlewares: adminReadRateLimit()
11913
12483
  }
11914
12484
  },
11915
12485
  {
11916
- method: "PUT",
11917
- path: "/settings",
11918
- handler: "settings.updateSettings",
12486
+ method: "POST",
12487
+ path: "/impersonation/users/:userId",
12488
+ handler: "impersonation.startUser",
11919
12489
  config: {
11920
- policies: adminPolicy(),
12490
+ policies: adminSessionsPolicy([IMPERSONATE_USERS_ACTION]),
12491
+ // Ten starts per ten minutes per admin.
12492
+ middlewares: [
12493
+ {
12494
+ name: "plugin::magic-sessionmanager.rate-limit",
12495
+ config: { max: 10, window: 10 * 60 * 1e3 }
12496
+ }
12497
+ ]
12498
+ }
12499
+ },
12500
+ {
12501
+ method: "POST",
12502
+ path: "/impersonation/admins/:adminId/preview",
12503
+ handler: "impersonation.previewAdmin",
12504
+ config: {
12505
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12506
+ // Ten previews per ten minutes per admin.
12507
+ middlewares: [
12508
+ {
12509
+ name: "plugin::magic-sessionmanager.rate-limit",
12510
+ config: { max: 10, window: 10 * 60 * 1e3 }
12511
+ }
12512
+ ]
12513
+ }
12514
+ },
12515
+ {
12516
+ method: "GET",
12517
+ path: "/impersonation/previews/:id",
12518
+ handler: "impersonation.getPreview",
12519
+ config: {
12520
+ policies: adminSessionsPolicy([IMPERSONATE_ADMINS_ACTION]),
12521
+ middlewares: adminReadRateLimit()
12522
+ }
12523
+ },
12524
+ {
12525
+ method: "GET",
12526
+ path: "/impersonation/active",
12527
+ handler: "impersonation.listActive",
12528
+ config: {
12529
+ policies: impersonationListPolicy(),
12530
+ middlewares: adminReadRateLimit()
12531
+ }
12532
+ },
12533
+ {
12534
+ method: "POST",
12535
+ path: "/impersonation/:id/end",
12536
+ handler: "impersonation.end",
12537
+ config: {
12538
+ policies: impersonationListPolicy(),
12539
+ middlewares: adminSignOutRateLimit()
12540
+ }
12541
+ },
12542
+ {
12543
+ method: "GET",
12544
+ path: "/settings",
12545
+ handler: "settings.getSettings",
12546
+ config: {
12547
+ policies: adminPolicy(),
12548
+ description: "Get plugin settings (admin)"
12549
+ }
12550
+ },
12551
+ {
12552
+ method: "PUT",
12553
+ path: "/settings",
12554
+ handler: "settings.updateSettings",
12555
+ config: {
12556
+ policies: adminPolicy(),
11921
12557
  description: "Update plugin settings (admin)"
11922
12558
  }
11923
12559
  }
@@ -14199,6 +14835,7 @@ var require_settings_access = __commonJS({
14199
14835
  var { SECURITY_LOG_KEYS } = require_security_log_settings();
14200
14836
  var { POLICY_KEYS } = require_policy_settings();
14201
14837
  var { PROTECTED_DETECTION_KEYS } = require_detection_settings();
14838
+ var { IMPERSONATION_KEYS } = require_impersonation_rules();
14202
14839
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
14203
14840
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
14204
14841
  var GEO_SETTINGS_KEYS = Object.freeze([
@@ -14220,7 +14857,9 @@ var require_settings_access = __commonJS({
14220
14857
  // limit, password-change sign-out, recording switch, per-role rules).
14221
14858
  ...POLICY_KEYS,
14222
14859
  // Signed webhook, event selection, impossible travel and shortened IPs.
14223
- ...PROTECTED_DETECTION_KEYS
14860
+ ...PROTECTED_DETECTION_KEYS,
14861
+ // Impersonation switch (4.20): whether admins can act as app users.
14862
+ ...IMPERSONATION_KEYS
14224
14863
  ]);
14225
14864
  var WEBHOOK_SECRETS = Object.freeze([
14226
14865
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
@@ -14325,6 +14964,10 @@ var require_settings = __commonJS({
14325
14964
  } = require_settings_access();
14326
14965
  var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
14327
14966
  var { DETECTION_DEFAULTS, validateDetectionSettings } = require_detection_settings();
14967
+ var {
14968
+ IMPERSONATION_DEFAULTS,
14969
+ validateImpersonationSettings
14970
+ } = require_impersonation_rules();
14328
14971
  var { encryptToken } = require_encryption();
14329
14972
  var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
14330
14973
  var path = __require("node:path");
@@ -14509,7 +15152,8 @@ var require_settings = __commonJS({
14509
15152
  roleRules: [],
14510
15153
  ...DETECTION_DEFAULTS,
14511
15154
  webhookEvents: [...DETECTION_DEFAULTS.webhookEvents],
14512
- genericWebhookSecret: ""
15155
+ genericWebhookSecret: "",
15156
+ ...IMPERSONATION_DEFAULTS
14513
15157
  };
14514
15158
  function mergeSettingsWithDefaults(stored) {
14515
15159
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -14723,6 +15367,9 @@ var require_settings = __commonJS({
14723
15367
  const detection = validateDetectionSettings(body);
14724
15368
  errors.push(...detection.errors);
14725
15369
  Object.assign(next, detection.values);
15370
+ const impersonation = validateImpersonationSettings(body);
15371
+ errors.push(...impersonation.errors);
15372
+ Object.assign(next, impersonation.values);
14726
15373
  if (has("genericWebhookSecret")) {
14727
15374
  const secret = body.genericWebhookSecret;
14728
15375
  if (secret === "") {
@@ -14910,6 +15557,10 @@ var require_settings = __commonJS({
14910
15557
  return sendValidationError(ctx, "Invalid settings", outcome.errors);
14911
15558
  }
14912
15559
  recordSettingsChange(ctx, outcome.changed);
15560
+ if (outcome.changed.includes("impersonationEnabled") && !outcome.settings.impersonationEnabled) {
15561
+ strapi.plugin("magic-sessionmanager").service("impersonation").sweep().catch(() => {
15562
+ });
15563
+ }
14913
15564
  strapi.log.info(
14914
15565
  `[magic-sessionmanager/settings] Settings updated (${outcome.changed.length} keys changed)`
14915
15566
  );
@@ -16746,6 +17397,1281 @@ var require_webhooks = __commonJS({
16746
17397
  }
16747
17398
  });
16748
17399
 
17400
+ // server/src/utils/permission-subset.js
17401
+ var require_permission_subset = __commonJS({
17402
+ "server/src/utils/permission-subset.js"(exports, module) {
17403
+ "use strict";
17404
+ function grantsNothing(permission) {
17405
+ const fields = permission?.properties?.fields;
17406
+ return Array.isArray(fields) && fields.length === 0;
17407
+ }
17408
+ function parametersKey(value) {
17409
+ const normalize = (input) => {
17410
+ if (Array.isArray(input)) {
17411
+ return input.every((item) => typeof item === "string") ? [...new Set(input)].sort() : input.map(normalize);
17412
+ }
17413
+ if (input && typeof input === "object") {
17414
+ return Object.fromEntries(
17415
+ Object.keys(input).filter((key) => input[key] !== void 0).sort().map((key) => [key, normalize(input[key])])
17416
+ );
17417
+ }
17418
+ return input;
17419
+ };
17420
+ return JSON.stringify(normalize(value ?? {}));
17421
+ }
17422
+ function coversValue(held, property, value) {
17423
+ const allowed = held.properties?.[property];
17424
+ if (allowed === void 0 || allowed === null) return true;
17425
+ if (value === null || !Array.isArray(allowed)) return false;
17426
+ return allowed.some(
17427
+ (entry) => entry === value || property === "fields" && value.startsWith(`${entry}.`)
17428
+ );
17429
+ }
17430
+ function coversCondition(held, condition) {
17431
+ const conditions = held.conditions ?? [];
17432
+ if (conditions.length === 0) return true;
17433
+ return condition !== null && conditions.includes(condition);
17434
+ }
17435
+ function isPermissionCovered(requested, held) {
17436
+ if (grantsNothing(requested)) return true;
17437
+ const subject = requested.subject ?? null;
17438
+ const parameters = parametersKey(requested.actionParameters);
17439
+ const matching = held.filter(
17440
+ (permission) => permission.action === requested.action && (permission.subject ?? null) === subject && parametersKey(permission.actionParameters) === parameters && !grantsNothing(permission)
17441
+ );
17442
+ if (matching.length === 0) return false;
17443
+ const properties = [
17444
+ .../* @__PURE__ */ new Set([
17445
+ ...Object.keys(requested.properties ?? {}),
17446
+ ...matching.flatMap((permission) => Object.keys(permission.properties ?? {}))
17447
+ ])
17448
+ ];
17449
+ const dimensions = [];
17450
+ for (const property of properties) {
17451
+ const values = requested.properties?.[property];
17452
+ if (!Array.isArray(values)) dimensions.push({ property, values: [null] });
17453
+ else if (values.length > 0) {
17454
+ dimensions.push({ property, values: [...new Set(values.map(String))] });
17455
+ }
17456
+ }
17457
+ const conditions = (requested.conditions ?? []).length === 0 ? [null] : [...new Set(requested.conditions)];
17458
+ const walk = (index, picked, condition) => {
17459
+ if (index === dimensions.length) {
17460
+ return matching.some(
17461
+ (permission) => Object.entries(picked).every(
17462
+ ([property2, value]) => coversValue(permission, property2, value)
17463
+ ) && coversCondition(permission, condition)
17464
+ );
17465
+ }
17466
+ const { property, values } = dimensions[index];
17467
+ return values.every((value) => walk(index + 1, { ...picked, [property]: value }, condition));
17468
+ };
17469
+ return conditions.every((condition) => walk(0, {}, condition));
17470
+ }
17471
+ function uncoveredPermissions(target, actor) {
17472
+ return target.filter((permission) => !isPermissionCovered(permission, actor));
17473
+ }
17474
+ function toEnforced(permissions, context) {
17475
+ const out = [];
17476
+ for (const permission of permissions) {
17477
+ const conditions = permission.conditions ?? [];
17478
+ const registered = conditions.filter((id) => context.isConditionRegistered(id));
17479
+ if (conditions.length > 0 && registered.length === 0) continue;
17480
+ const properties = { ...permission.properties ?? {} };
17481
+ if (context.appliesLocales(permission)) {
17482
+ if (properties.locales === void 0) properties.locales = [];
17483
+ } else {
17484
+ delete properties.locales;
17485
+ }
17486
+ out.push({ ...permission, conditions: registered, properties });
17487
+ }
17488
+ return out;
17489
+ }
17490
+ module.exports = { isPermissionCovered, toEnforced, uncoveredPermissions };
17491
+ }
17492
+ });
17493
+
17494
+ // server/src/utils/admin-preview.js
17495
+ var require_admin_preview = __commonJS({
17496
+ "server/src/utils/admin-preview.js"(exports, module) {
17497
+ "use strict";
17498
+ var { toEnforced, uncoveredPermissions } = require_permission_subset();
17499
+ var SUPER_ADMIN_CODE = "strapi-super-admin";
17500
+ function isSuperAdmin(user) {
17501
+ return (user?.roles || []).some((role) => role?.code === SUPER_ADMIN_CODE);
17502
+ }
17503
+ async function loadAdmin(strapi2, id) {
17504
+ return strapi2.db.query("admin::user").findOne({
17505
+ where: { id },
17506
+ select: ["id", "firstname", "lastname", "username", "email", "isActive"],
17507
+ populate: { roles: { select: ["id", "name", "code"] } }
17508
+ });
17509
+ }
17510
+ async function effectivePermissions(strapi2, user) {
17511
+ const service = strapi2.admin.services.permission;
17512
+ const raw = await service.findUserPermissions(user);
17513
+ const appliesCache = /* @__PURE__ */ new Map();
17514
+ for (const permission of raw) {
17515
+ const key = `${permission.action}::${permission.subject}`;
17516
+ if (appliesCache.has(key)) continue;
17517
+ let applies;
17518
+ try {
17519
+ applies = Boolean(permission.subject) && service.actionProvider.has(permission.action) && await service.actionProvider.appliesToProperty(
17520
+ "locales",
17521
+ permission.action,
17522
+ permission.subject
17523
+ ) === true;
17524
+ } catch {
17525
+ applies = false;
17526
+ }
17527
+ appliesCache.set(key, applies);
17528
+ }
17529
+ return toEnforced(raw, {
17530
+ isConditionRegistered: (id) => {
17531
+ try {
17532
+ return service.conditionProvider.has(id) === true;
17533
+ } catch {
17534
+ return false;
17535
+ }
17536
+ },
17537
+ appliesLocales: (permission) => appliesCache.get(`${permission.action}::${permission.subject}`) === true
17538
+ });
17539
+ }
17540
+ async function previewRefusal(strapi2, actor, target) {
17541
+ if (String(actor.id) === String(target.id)) return { reason: "self" };
17542
+ if (isSuperAdmin(target)) return { reason: "super-admin" };
17543
+ if (isSuperAdmin(actor)) return null;
17544
+ const [held, wanted] = await Promise.all([
17545
+ effectivePermissions(strapi2, actor),
17546
+ effectivePermissions(strapi2, target)
17547
+ ]);
17548
+ const uncovered = uncoveredPermissions(wanted, held);
17549
+ return uncovered.length > 0 ? { reason: "not-subset", uncovered: uncovered.length } : null;
17550
+ }
17551
+ function contentAction(action) {
17552
+ const match = /^plugin::content-manager\.explorer\.([a-z-]+)$/.exec(action);
17553
+ return match ? match[1] : action;
17554
+ }
17555
+ async function buildPreview(strapi2, target) {
17556
+ const permissions = await effectivePermissions(strapi2, target);
17557
+ const provider = strapi2.admin.services.permission.actionProvider;
17558
+ const types = /* @__PURE__ */ new Map();
17559
+ const other = [];
17560
+ for (const permission of permissions) {
17561
+ const contentType = permission.subject ? strapi2.contentTypes?.[permission.subject] : null;
17562
+ if (contentType && permission.action.startsWith("plugin::content-manager.explorer.")) {
17563
+ const entry = types.get(permission.subject) || {
17564
+ uid: permission.subject,
17565
+ name: String(contentType.info?.displayName || permission.subject).slice(0, 120),
17566
+ kind: contentType.kind === "singleType" ? "single" : "collection",
17567
+ actions: []
17568
+ };
17569
+ const fields = permission.properties?.fields;
17570
+ const locales = permission.properties?.locales;
17571
+ entry.actions.push({
17572
+ action: contentAction(permission.action),
17573
+ fields: Array.isArray(fields) ? fields.length : null,
17574
+ locales: Array.isArray(locales) ? locales.slice(0, 20) : null,
17575
+ conditions: (permission.conditions || []).slice(0, 10)
17576
+ });
17577
+ types.set(permission.subject, entry);
17578
+ continue;
17579
+ }
17580
+ let definition;
17581
+ try {
17582
+ definition = provider.get(permission.action);
17583
+ } catch {
17584
+ definition = null;
17585
+ }
17586
+ other.push({
17587
+ action: permission.action,
17588
+ name: String(definition?.displayName || permission.action).slice(0, 160),
17589
+ section: String(definition?.section || "other"),
17590
+ scope: definition?.pluginName ? String(definition.pluginName) : null
17591
+ });
17592
+ }
17593
+ const order = ["create", "read", "update", "delete", "publish"];
17594
+ const contentTypes = [...types.values()].map((entry) => ({
17595
+ ...entry,
17596
+ actions: entry.actions.sort(
17597
+ (a, b) => (order.indexOf(a.action) + 1 || 99) - (order.indexOf(b.action) + 1 || 99) || a.action.localeCompare(b.action)
17598
+ )
17599
+ })).sort((a, b) => a.name.localeCompare(b.name));
17600
+ other.sort((a, b) => a.section.localeCompare(b.section) || a.name.localeCompare(b.name));
17601
+ return {
17602
+ admin: {
17603
+ id: target.id,
17604
+ name: [target.firstname, target.lastname].filter(Boolean).join(" ").trim() || target.username || "",
17605
+ active: target.isActive === true,
17606
+ roles: (target.roles || []).map((role) => ({ name: role.name }))
17607
+ },
17608
+ contentTypes,
17609
+ otherPermissions: other.slice(0, 500)
17610
+ };
17611
+ }
17612
+ module.exports = {
17613
+ buildPreview,
17614
+ effectivePermissions,
17615
+ isSuperAdmin,
17616
+ loadAdmin,
17617
+ previewRefusal
17618
+ };
17619
+ }
17620
+ });
17621
+
17622
+ // server/src/services/impersonation.js
17623
+ var require_impersonation = __commonJS({
17624
+ "server/src/services/impersonation.js"(exports, module) {
17625
+ "use strict";
17626
+ var crypto = __require("node:crypto");
17627
+ var { createLogger } = require_logger();
17628
+ var { hashToken } = require_encryption();
17629
+ var getClientIp = require_getClientIp();
17630
+ var { getPluginSettings } = require_settings_loader();
17631
+ var { getNativeSessionManager } = require_native_session_manager();
17632
+ var { REVOCATION_UID } = require_session_revocation();
17633
+ var { buildPreview, loadAdmin, previewRefusal } = require_admin_preview();
17634
+ var {
17635
+ ADMIN_DURATIONS,
17636
+ ADMIN_ID_PATTERN,
17637
+ CODE_PATTERN,
17638
+ CODE_TTL_MS,
17639
+ DOCUMENT_ID_PATTERN,
17640
+ USER_DURATIONS,
17641
+ decodeJwtPayload,
17642
+ resolveFrontendHandoff,
17643
+ validateStartBody
17644
+ } = require_impersonation_rules();
17645
+ var UID = "plugin::magic-sessionmanager.impersonation";
17646
+ var USER_UID = "plugin::users-permissions.user";
17647
+ var NATIVE_SESSION_UID = "admin::session";
17648
+ var NATIVE_ORIGIN = "users-permissions";
17649
+ var DEVICE_PREFIX = "msm-impersonation-";
17650
+ var MAX_CACHE = 1e4;
17651
+ var RECORD_CACHE_MS = 5e3;
17652
+ var REFUSAL_DEDUP_MS = 60 * 1e3;
17653
+ var ENDED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
17654
+ var SWEEP_BATCH = 100;
17655
+ var ImpersonationError = class extends Error {
17656
+ /**
17657
+ * @param {400|403|404} status HTTP status.
17658
+ * @param {string} message Fixed message.
17659
+ * @param {Record<string, unknown>} [details] Safe details.
17660
+ */
17661
+ constructor(status, message, details = {}) {
17662
+ super(message);
17663
+ this.name = "ImpersonationError";
17664
+ this.status = status;
17665
+ this.details = details;
17666
+ }
17667
+ };
17668
+ var EVENTS = Object.freeze({
17669
+ STARTED: "impersonation.started",
17670
+ ENDED: "impersonation.ended",
17671
+ EXPIRED: "impersonation.expired",
17672
+ REFUSED: "impersonation.refused"
17673
+ });
17674
+ function remember(map, key, value) {
17675
+ map.delete(key);
17676
+ map.set(key, value);
17677
+ if (map.size > MAX_CACHE) map.delete(map.keys().next().value);
17678
+ }
17679
+ function adminLabel(admin) {
17680
+ if (!admin) return "";
17681
+ const name = [admin.firstname, admin.lastname].filter(Boolean).join(" ").trim();
17682
+ return (name || admin.username || admin.email || "").slice(0, 120);
17683
+ }
17684
+ module.exports = ({ strapi: strapi2 }) => {
17685
+ const log = createLogger(strapi2);
17686
+ const nativeSessionCache = /* @__PURE__ */ new Map();
17687
+ const recordCache = /* @__PURE__ */ new Map();
17688
+ const refusals = /* @__PURE__ */ new Map();
17689
+ const query = () => strapi2.db.query(UID);
17690
+ const securityLog = () => strapi2.plugin("magic-sessionmanager").service("security-log");
17691
+ const record = (input) => {
17692
+ try {
17693
+ securityLog()?.record(input);
17694
+ } catch {
17695
+ }
17696
+ };
17697
+ const isProduction = () => process.env.NODE_ENV === "production";
17698
+ const service = {
17699
+ EVENTS,
17700
+ /**
17701
+ * Whether the feature switch is on.
17702
+ *
17703
+ * @returns {Promise<boolean>}
17704
+ */
17705
+ async isEnabled() {
17706
+ try {
17707
+ const settings = await getPluginSettings(strapi2);
17708
+ return settings?.impersonationEnabled === true;
17709
+ } catch {
17710
+ return false;
17711
+ }
17712
+ },
17713
+ /**
17714
+ * The configured frontend hand-off, or null for the token fallback.
17715
+ *
17716
+ * @returns {{url: string, origin: string}|null}
17717
+ */
17718
+ frontendHandoff() {
17719
+ return resolveFrontendHandoff(
17720
+ strapi2.config.get("plugin::magic-sessionmanager.impersonation"),
17721
+ {
17722
+ production: isProduction()
17723
+ }
17724
+ );
17725
+ },
17726
+ /**
17727
+ * Warns once at start-up when the frontend hand-off cannot work: the
17728
+ * admin panel posts the one-time code to `impersonation.frontendUrl`, and
17729
+ * Strapi's default Content-Security-Policy (`form-action 'self'`, from
17730
+ * `strapi::security`) blocks that unless the frontend origin is listed.
17731
+ *
17732
+ * @returns {boolean} Whether the setup looks complete (true without a frontend URL).
17733
+ */
17734
+ checkHandoffSetup() {
17735
+ const frontend = service.frontendHandoff();
17736
+ if (!frontend) return true;
17737
+ let directives;
17738
+ try {
17739
+ const entry = (strapi2.config.get("middlewares") || []).find(
17740
+ (item) => item === "strapi::security" || item?.name === "strapi::security"
17741
+ );
17742
+ directives = typeof entry === "object" ? entry?.config?.contentSecurityPolicy?.directives : null;
17743
+ } catch {
17744
+ directives = null;
17745
+ }
17746
+ const formAction = directives?.["form-action"] ?? directives?.formAction;
17747
+ const list = Array.isArray(formAction) ? formAction.map(String) : [];
17748
+ if (list.includes(frontend.origin)) return true;
17749
+ log.warn(
17750
+ "[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)"
17751
+ );
17752
+ return false;
17753
+ },
17754
+ /**
17755
+ * What the admin UI needs to know before it offers impersonation.
17756
+ *
17757
+ * @returns {Promise<{enabled: boolean, handoff: 'frontend'|'token', frontendOrigin: string|null,
17758
+ * durations: number[], mode: 'refresh'|'legacy'}>}
17759
+ */
17760
+ async status() {
17761
+ const frontend = service.frontendHandoff();
17762
+ return {
17763
+ enabled: await service.isEnabled(),
17764
+ handoff: frontend ? "frontend" : "token",
17765
+ frontendOrigin: frontend ? frontend.origin : null,
17766
+ durations: [...USER_DURATIONS],
17767
+ adminDurations: [...ADMIN_DURATIONS],
17768
+ mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
17769
+ };
17770
+ },
17771
+ /**
17772
+ * Records a refused start.
17773
+ *
17774
+ * @param {{actorId: unknown, targetType: 'user'|'admin', targetId: unknown, reason: string,
17775
+ * via?: string}} input Who tried what and why it was refused.
17776
+ * @returns {void}
17777
+ */
17778
+ recordRefused({ actorId, targetType, targetId, reason, via }) {
17779
+ record({
17780
+ event: EVENTS.REFUSED,
17781
+ actorType: "admin",
17782
+ actorId: actorId == null ? null : String(actorId),
17783
+ targetType,
17784
+ targetId: targetId == null ? null : String(targetId).slice(0, 64),
17785
+ meta: { refusal: reason, ...via ? { via } : {} }
17786
+ });
17787
+ },
17788
+ /**
17789
+ * Starts an impersonation of an app user.
17790
+ *
17791
+ * @param {{actor: any, userDocumentId: unknown, body: unknown, ctx: any}} input Caller,
17792
+ * target and request body.
17793
+ * @returns {Promise<object>} Impersonation DTO plus the hand-off.
17794
+ * @throws {ImpersonationError} 400 invalid body, id or blocked user; 403 feature off or
17795
+ * already active; 404 unknown user.
17796
+ * @sideeffect Creates an impersonation row; with the token hand-off also a session; queues
17797
+ * `impersonation.started`; may send an email to the user.
17798
+ */
17799
+ async startForUser({ actor, userDocumentId, body, ctx }) {
17800
+ const actorId = String(actor.id);
17801
+ const refuse = (reason, status, message) => {
17802
+ service.recordRefused({ actorId, targetType: "user", targetId: userDocumentId, reason });
17803
+ return new ImpersonationError(status, message, { reason });
17804
+ };
17805
+ if (!await service.isEnabled()) {
17806
+ throw refuse("disabled", 403, "Impersonation is turned off");
17807
+ }
17808
+ if (typeof userDocumentId !== "string" || !DOCUMENT_ID_PATTERN.test(userDocumentId)) {
17809
+ throw new ImpersonationError(400, "Invalid user id");
17810
+ }
17811
+ const { value, errors: fieldErrors } = validateStartBody(body, {
17812
+ durations: USER_DURATIONS,
17813
+ notify: true
17814
+ });
17815
+ if (!value) {
17816
+ throw new ImpersonationError(400, "Invalid impersonation request", {
17817
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
17818
+ });
17819
+ }
17820
+ const user = await strapi2.db.query(USER_UID).findOne({
17821
+ where: { documentId: userDocumentId },
17822
+ select: ["id", "documentId", "username", "email", "blocked"]
17823
+ });
17824
+ if (!user) throw new ImpersonationError(404, "User not found");
17825
+ if (user.blocked === true) {
17826
+ throw refuse("blocked", 400, "Blocked accounts cannot be impersonated");
17827
+ }
17828
+ await service.sweep();
17829
+ const running = await query().findOne({
17830
+ where: { targetType: "user", targetId: user.documentId, state: "active" },
17831
+ select: ["id"]
17832
+ });
17833
+ if (running) {
17834
+ throw refuse("already-active", 403, "An impersonation of this user is active");
17835
+ }
17836
+ const now = /* @__PURE__ */ new Date();
17837
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
17838
+ const frontend = service.frontendHandoff();
17839
+ const code = frontend ? crypto.randomBytes(32).toString("base64url") : null;
17840
+ const row = await query().create({
17841
+ data: {
17842
+ targetType: "user",
17843
+ targetId: user.documentId,
17844
+ actorId,
17845
+ state: "active",
17846
+ reason: value.reason,
17847
+ durationMinutes: value.durationMinutes,
17848
+ handoff: frontend ? "frontend" : "token",
17849
+ notifyUser: value.notifyUser,
17850
+ startedAt: now,
17851
+ expiresAt,
17852
+ ...code ? { codeHash: hashToken(code), codeExpiresAt: new Date(now.getTime() + CODE_TTL_MS) } : {}
17853
+ }
17854
+ });
17855
+ let handoff;
17856
+ try {
17857
+ if (frontend) {
17858
+ handoff = {
17859
+ type: "frontend",
17860
+ url: frontend.url,
17861
+ field: "code",
17862
+ code,
17863
+ codeExpiresAt: new Date(now.getTime() + CODE_TTL_MS).toISOString()
17864
+ };
17865
+ } else {
17866
+ const credential = await service.issueCredential(row, user, ctx);
17867
+ handoff = { type: "token", ...credential };
17868
+ }
17869
+ } catch (err) {
17870
+ await service.end(row.documentId, { reason: "failed", endedBy: actorId, silent: true });
17871
+ throw err;
17872
+ }
17873
+ record({
17874
+ event: EVENTS.STARTED,
17875
+ actorType: "admin",
17876
+ actorId,
17877
+ targetType: "user",
17878
+ targetId: user.documentId,
17879
+ meta: {
17880
+ reason: value.reason,
17881
+ durationMinutes: value.durationMinutes,
17882
+ handoff: frontend ? "frontend" : "token",
17883
+ notifyUser: value.notifyUser
17884
+ }
17885
+ });
17886
+ log.info(`[IMPERSONATION] Started (${value.durationMinutes} min, ${handoff.type})`);
17887
+ if (value.notifyUser) service.notifyUser(user, value, expiresAt);
17888
+ return {
17889
+ impersonation: service.toDto(row, { users: /* @__PURE__ */ new Map([[user.documentId, user]]), actor }),
17890
+ handoff
17891
+ };
17892
+ },
17893
+ /**
17894
+ * Starts a read-only permission preview of another admin ("View as
17895
+ * admin"). No session or token is created; the preview can be read by
17896
+ * the admin who started it until it ends.
17897
+ *
17898
+ * @param {{actor: any, adminId: unknown, body: unknown, canReadAdmins: boolean}} input
17899
+ * Caller (with roles), target id and request body.
17900
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17901
+ * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17902
+ * or not a subset of the caller's permissions; 404 unknown admin.
17903
+ * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17904
+ */
17905
+ async previewAdmin({ actor, adminId, body, canReadAdmins }) {
17906
+ const actorId = String(actor.id);
17907
+ const refuse = (reason, status, message, extra = {}) => {
17908
+ service.recordRefused({ actorId, targetType: "admin", targetId: adminId, reason });
17909
+ return new ImpersonationError(status, message, { reason, ...extra });
17910
+ };
17911
+ if (!await service.isEnabled()) {
17912
+ throw refuse("disabled", 403, "Impersonation is turned off");
17913
+ }
17914
+ if (typeof adminId !== "string" || !ADMIN_ID_PATTERN.test(adminId)) {
17915
+ throw new ImpersonationError(404, "Admin not found");
17916
+ }
17917
+ const { value, errors: fieldErrors } = validateStartBody(body, {
17918
+ durations: ADMIN_DURATIONS,
17919
+ notify: false
17920
+ });
17921
+ if (!value) {
17922
+ throw new ImpersonationError(400, "Invalid preview request", {
17923
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
17924
+ });
17925
+ }
17926
+ const [caller, target] = await Promise.all([
17927
+ loadAdmin(strapi2, actor.id),
17928
+ loadAdmin(strapi2, Number(adminId))
17929
+ ]);
17930
+ if (!target) throw new ImpersonationError(404, "Admin not found");
17931
+ const refusal = await previewRefusal(strapi2, caller || actor, target);
17932
+ if (refusal) {
17933
+ const messages = {
17934
+ self: "You cannot view yourself as another admin",
17935
+ "super-admin": "Super Admins cannot be viewed as another admin",
17936
+ "not-subset": "This admin has permissions that you do not have"
17937
+ };
17938
+ throw refuse(
17939
+ refusal.reason,
17940
+ 403,
17941
+ messages[refusal.reason],
17942
+ refusal.uncovered ? { uncovered: refusal.uncovered } : {}
17943
+ );
17944
+ }
17945
+ await service.sweep();
17946
+ const now = /* @__PURE__ */ new Date();
17947
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
17948
+ const row = await query().create({
17949
+ data: {
17950
+ targetType: "admin",
17951
+ targetId: String(target.id),
17952
+ actorId,
17953
+ state: "active",
17954
+ reason: value.reason,
17955
+ durationMinutes: value.durationMinutes,
17956
+ handoff: "preview",
17957
+ notifyUser: false,
17958
+ startedAt: now,
17959
+ expiresAt
17960
+ }
17961
+ });
17962
+ record({
17963
+ event: EVENTS.STARTED,
17964
+ actorType: "admin",
17965
+ actorId,
17966
+ targetType: "admin",
17967
+ targetId: String(target.id),
17968
+ meta: {
17969
+ reason: value.reason,
17970
+ durationMinutes: value.durationMinutes,
17971
+ handoff: "preview"
17972
+ }
17973
+ });
17974
+ const preview = await buildPreview(strapi2, target);
17975
+ if (!canReadAdmins) preview.admin.name = "";
17976
+ return {
17977
+ impersonation: service.toDto(row, {
17978
+ admins: /* @__PURE__ */ new Map([
17979
+ [String(target.id), canReadAdmins ? target : null],
17980
+ [actorId, caller || actor]
17981
+ ]),
17982
+ viewer: actor
17983
+ }),
17984
+ preview
17985
+ };
17986
+ },
17987
+ /**
17988
+ * The preview of a running admin preview, for the admin who started it.
17989
+ * An expired one is ended and answers 404 like an unknown one.
17990
+ *
17991
+ * @param {{id: unknown, viewer: any, canReadAdmins: boolean}} input Preview id and caller.
17992
+ * @returns {Promise<object>} Impersonation DTO plus the preview.
17993
+ * @throws {ImpersonationError} 404 unknown, ended, expired or started by someone else.
17994
+ */
17995
+ async getPreview({ id, viewer, canReadAdmins }) {
17996
+ if (typeof id !== "string" || !DOCUMENT_ID_PATTERN.test(id)) {
17997
+ throw new ImpersonationError(404, "Preview not found");
17998
+ }
17999
+ const row = await query().findOne({
18000
+ where: { documentId: id, targetType: "admin", state: "active" }
18001
+ });
18002
+ if (!row || String(row.actorId) !== String(viewer.id)) {
18003
+ throw new ImpersonationError(404, "Preview not found");
18004
+ }
18005
+ if (new Date(row.expiresAt).getTime() <= Date.now()) {
18006
+ await service.end(row.documentId, { reason: "expired" });
18007
+ throw new ImpersonationError(404, "Preview not found");
18008
+ }
18009
+ const target = await loadAdmin(strapi2, Number(row.targetId));
18010
+ if (!target) {
18011
+ await service.end(row.documentId, { reason: "failed", silent: true });
18012
+ throw new ImpersonationError(404, "Preview not found");
18013
+ }
18014
+ const preview = await buildPreview(strapi2, target);
18015
+ if (!canReadAdmins) preview.admin.name = "";
18016
+ return {
18017
+ impersonation: service.toDto(row, {
18018
+ admins: /* @__PURE__ */ new Map([[String(target.id), canReadAdmins ? target : null]]),
18019
+ viewer
18020
+ }),
18021
+ preview
18022
+ };
18023
+ },
18024
+ /**
18025
+ * Mints the short-lived credential of an impersonation and links its
18026
+ * Magic session row.
18027
+ *
18028
+ * @param {any} row Impersonation row.
18029
+ * @param {{id: number, documentId: string}} user Target user.
18030
+ * @param {any} ctx Request context (IP and user agent of the session row).
18031
+ * @returns {Promise<{jwt: string, refreshToken?: string, expiresAt: string}>}
18032
+ * @throws {Error} When the credential cannot be minted.
18033
+ * @sideeffect Creates a Strapi session (refresh mode) and a Magic session row.
18034
+ */
18035
+ async issueCredential(row, user, ctx) {
18036
+ const now = Date.now();
18037
+ const expiresAt = new Date(row.expiresAt);
18038
+ const remainingSeconds = Math.floor((expiresAt.getTime() - now) / 1e3);
18039
+ if (remainingSeconds < 5) throw new ImpersonationError(403, "Impersonation ended");
18040
+ const native = getNativeSessionManager(strapi2);
18041
+ const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
18042
+ const headers = ctx?.request?.headers || {};
18043
+ const refs = { credentialIssuedAt: new Date(now) };
18044
+ let jwt;
18045
+ let refreshToken;
18046
+ let nativeSessionId;
18047
+ if (native) {
18048
+ const deviceId = `${DEVICE_PREFIX}${crypto.randomBytes(12).toString("hex")}`;
18049
+ const manager = strapi2.sessionManager(NATIVE_ORIGIN);
18050
+ await query().update({
18051
+ where: { id: row.id },
18052
+ data: { nativeUserId: String(user.id), nativeDeviceId: deviceId }
18053
+ });
18054
+ const refresh = await manager.generateRefreshToken(String(user.id), deviceId, {
18055
+ type: "session",
18056
+ metadata: {
18057
+ loginAt: new Date(now).toISOString(),
18058
+ deviceName: "Impersonation",
18059
+ msmImpersonation: row.documentId
18060
+ }
18061
+ });
18062
+ const access = await manager.generateAccessToken(refresh.token);
18063
+ if (!access || "error" in access) throw new Error("Access token could not be minted");
18064
+ jwt = access.token;
18065
+ refreshToken = refresh.token;
18066
+ nativeSessionId = refresh.sessionId;
18067
+ remember(nativeSessionCache, refresh.sessionId, row.documentId);
18068
+ } else {
18069
+ jwt = strapi2.plugin("users-permissions").service("jwt").issue({ id: user.id, msmImp: row.documentId }, { expiresIn: remainingSeconds });
18070
+ refs.tokenHash = hashToken(jwt);
18071
+ refs.tokenExpiresAt = expiresAt;
18072
+ }
18073
+ const session = await sessionService.createSession({
18074
+ userId: user.documentId,
18075
+ ip: getClientIp(ctx),
18076
+ userAgent: headers["user-agent"] || "unknown",
18077
+ token: jwt,
18078
+ ...nativeSessionId ? { nativeSessionId } : {}
18079
+ });
18080
+ if (session?.documentId) refs.sessionDocumentId = session.documentId;
18081
+ await query().update({ where: { id: row.id }, data: refs });
18082
+ recordCache.delete(row.documentId);
18083
+ return {
18084
+ jwt,
18085
+ ...refreshToken ? { refreshToken } : {},
18086
+ expiresAt: expiresAt.toISOString()
18087
+ };
18088
+ },
18089
+ /**
18090
+ * Exchanges a one-time hand-off code for the credential. The code is
18091
+ * single use (atomic update) and valid for 60 seconds; every failure
18092
+ * answers the same.
18093
+ *
18094
+ * @param {unknown} code Code from the request body.
18095
+ * @param {any} ctx Request context.
18096
+ * @returns {Promise<object|null>} Credential response, or null for any invalid code.
18097
+ * @sideeffect Consumes the code; creates the credential and its session.
18098
+ */
18099
+ async exchange(code, ctx) {
18100
+ if (typeof code !== "string" || !CODE_PATTERN.test(code)) return null;
18101
+ if (!await service.isEnabled()) return null;
18102
+ const codeHash = hashToken(code);
18103
+ const now = /* @__PURE__ */ new Date();
18104
+ const row = await query().findOne({
18105
+ where: { codeHash, state: "active" }
18106
+ });
18107
+ if (!row) return null;
18108
+ const claimed = await query().updateMany({
18109
+ where: {
18110
+ id: row.id,
18111
+ codeHash,
18112
+ state: "active",
18113
+ credentialIssuedAt: { $null: true },
18114
+ codeExpiresAt: { $gt: now },
18115
+ expiresAt: { $gt: now }
18116
+ },
18117
+ data: { codeHash: null, codeExpiresAt: null, credentialIssuedAt: now }
18118
+ });
18119
+ if (Number(claimed?.count) !== 1) return null;
18120
+ const user = await strapi2.db.query(USER_UID).findOne({
18121
+ where: { documentId: row.targetId },
18122
+ select: ["id", "documentId", "username", "email", "blocked"]
18123
+ });
18124
+ if (!user || user.blocked === true) {
18125
+ await service.end(row.documentId, { reason: "failed", silent: true });
18126
+ return null;
18127
+ }
18128
+ try {
18129
+ const credential = await service.issueCredential(row, user, ctx);
18130
+ return {
18131
+ ...credential,
18132
+ user: { id: user.id, documentId: user.documentId, username: user.username },
18133
+ impersonation: { id: row.documentId, expiresAt: new Date(row.expiresAt).toISOString() }
18134
+ };
18135
+ } catch (err) {
18136
+ await service.end(row.documentId, { reason: "failed", silent: true });
18137
+ throw err;
18138
+ }
18139
+ },
18140
+ /**
18141
+ * Ends an impersonation: revokes its credential first (idempotent), then
18142
+ * marks the row ended once (atomic), so one event is recorded.
18143
+ *
18144
+ * @param {string} documentId Impersonation id.
18145
+ * @param {{reason?: 'ended'|'expired'|'disabled'|'failed', endedBy?: string|null,
18146
+ * silent?: boolean}} [options] Why and by whom.
18147
+ * @returns {Promise<boolean>} Whether this call ended it.
18148
+ * @sideeffect Revokes sessions and tokens; updates the row; queues an event.
18149
+ */
18150
+ async end(documentId, { reason = "ended", endedBy = null, silent = false } = {}) {
18151
+ const row = await query().findOne({ where: { documentId } });
18152
+ if (!row) return false;
18153
+ await service.revoke(row, reason === "expired" ? "expired" : "manual");
18154
+ const claimed = await query().updateMany({
18155
+ where: { id: row.id, state: "active" },
18156
+ data: {
18157
+ state: reason === "expired" ? "expired" : "ended",
18158
+ endedAt: /* @__PURE__ */ new Date(),
18159
+ endReason: reason,
18160
+ endedBy: endedBy == null ? null : String(endedBy),
18161
+ codeHash: null,
18162
+ codeExpiresAt: null
18163
+ }
18164
+ });
18165
+ recordCache.delete(documentId);
18166
+ if (Number(claimed?.count) !== 1) return false;
18167
+ if (!silent) {
18168
+ record({
18169
+ event: reason === "expired" ? EVENTS.EXPIRED : EVENTS.ENDED,
18170
+ actorType: endedBy ? "admin" : "system",
18171
+ actorId: endedBy ? String(endedBy) : null,
18172
+ targetType: row.targetType,
18173
+ targetId: row.targetId,
18174
+ meta: {
18175
+ startedBy: row.actorId,
18176
+ durationMinutes: row.durationMinutes,
18177
+ ...reason === "expired" ? {} : { endReason: reason }
18178
+ }
18179
+ });
18180
+ }
18181
+ log.info(`[IMPERSONATION] Ended (${reason})`);
18182
+ return true;
18183
+ },
18184
+ /**
18185
+ * Revokes everything minted for an impersonation. Safe to repeat.
18186
+ *
18187
+ * @param {any} row Impersonation row.
18188
+ * @param {'manual'|'expired'} sessionReason Termination reason of the Magic session row.
18189
+ * @returns {Promise<void>}
18190
+ * @sideeffect Deletes Strapi session rows, writes a revocation record, ends the Magic session.
18191
+ */
18192
+ async revoke(row, sessionReason) {
18193
+ if (row.nativeUserId && row.nativeDeviceId) {
18194
+ try {
18195
+ await strapi2.sessionManager(NATIVE_ORIGIN).invalidateRefreshToken(String(row.nativeUserId), String(row.nativeDeviceId));
18196
+ } catch (err) {
18197
+ log.error("[IMPERSONATION] Session revocation failed:", err?.name || "Error");
18198
+ }
18199
+ }
18200
+ if (row.tokenHash) {
18201
+ try {
18202
+ const documents = strapi2.documents(REVOCATION_UID);
18203
+ const existing = await documents.findFirst({
18204
+ filters: { tokenHash: row.tokenHash },
18205
+ fields: ["documentId"]
18206
+ });
18207
+ if (!existing) {
18208
+ await documents.create({
18209
+ data: {
18210
+ tokenHash: row.tokenHash,
18211
+ expiresAt: row.tokenExpiresAt || row.expiresAt,
18212
+ revokedAt: /* @__PURE__ */ new Date()
18213
+ }
18214
+ });
18215
+ }
18216
+ } catch (err) {
18217
+ log.error("[IMPERSONATION] Token revocation failed:", err?.name || "Error");
18218
+ }
18219
+ }
18220
+ if (row.sessionDocumentId) {
18221
+ try {
18222
+ await strapi2.plugin("magic-sessionmanager").service("session").terminateSession({ sessionId: row.sessionDocumentId, reason: sessionReason });
18223
+ } catch (err) {
18224
+ log.warn("[IMPERSONATION] Session row could not be ended:", err?.name || "Error");
18225
+ }
18226
+ }
18227
+ },
18228
+ /**
18229
+ * Ends expired impersonations, and all of them while the feature is off;
18230
+ * deletes rows that ended more than 7 days ago (the security log keeps
18231
+ * the record). Bounded per run; safe on several processes.
18232
+ *
18233
+ * @returns {Promise<number>} Number ended by this run.
18234
+ * @sideeffect Ends impersonations; deletes old rows.
18235
+ */
18236
+ async sweep() {
18237
+ const now = /* @__PURE__ */ new Date();
18238
+ const enabled = await service.isEnabled();
18239
+ const due = await query().findMany({
18240
+ where: enabled ? { state: "active", expiresAt: { $lte: now } } : { state: "active" },
18241
+ select: ["documentId", "expiresAt"],
18242
+ limit: SWEEP_BATCH
18243
+ });
18244
+ let ended = 0;
18245
+ for (const row of due) {
18246
+ const expired = new Date(row.expiresAt).getTime() <= now.getTime();
18247
+ try {
18248
+ if (await service.end(row.documentId, { reason: expired ? "expired" : "disabled" })) {
18249
+ ended += 1;
18250
+ }
18251
+ } catch (err) {
18252
+ log.warn("[IMPERSONATION] Ending failed:", err?.name || "Error");
18253
+ }
18254
+ }
18255
+ try {
18256
+ await query().deleteMany({
18257
+ where: {
18258
+ state: { $ne: "active" },
18259
+ endedAt: { $lt: new Date(now.getTime() - ENDED_RETENTION_MS) }
18260
+ }
18261
+ });
18262
+ } catch (err) {
18263
+ log.debug("[IMPERSONATION] Old rows were not deleted:", err?.name || "Error");
18264
+ }
18265
+ return ended;
18266
+ },
18267
+ /**
18268
+ * Active impersonations of the given target types, newest first. Admin
18269
+ * names are shown only to callers who may read admin users (as in the
18270
+ * Admin panel view); the caller's own name always.
18271
+ *
18272
+ * @param {{targetTypes: Array<'user'|'admin'>, viewer: any, canReadAdmins?: boolean}} input
18273
+ * Kinds the caller may see.
18274
+ * @returns {Promise<object[]>} DTOs.
18275
+ */
18276
+ async listActive({ targetTypes, viewer, canReadAdmins = true }) {
18277
+ if (!targetTypes.length) return [];
18278
+ await service.sweep();
18279
+ const rows = await query().findMany({
18280
+ where: { state: "active", targetType: { $in: targetTypes } },
18281
+ orderBy: { startedAt: "desc" },
18282
+ limit: 100
18283
+ });
18284
+ const userIds = rows.filter((row) => row.targetType === "user").map((row) => row.targetId);
18285
+ const adminIds = [
18286
+ ...new Set(
18287
+ rows.flatMap((row) => [row.actorId, row.targetType === "admin" ? row.targetId : null]).filter(Boolean).map(Number).filter(Number.isInteger)
18288
+ )
18289
+ ];
18290
+ const users = userIds.length ? await strapi2.db.query(USER_UID).findMany({
18291
+ where: { documentId: { $in: userIds } },
18292
+ select: ["documentId", "username", "email"]
18293
+ }) : [];
18294
+ const admins = adminIds.length ? await strapi2.db.query("admin::user").findMany({
18295
+ where: {
18296
+ id: {
18297
+ $in: canReadAdmins ? adminIds : adminIds.filter((id) => String(id) === String(viewer?.id))
18298
+ }
18299
+ },
18300
+ select: ["id", "firstname", "lastname", "username", "email"]
18301
+ }) : [];
18302
+ const context = {
18303
+ users: new Map(users.map((user) => [user.documentId, user])),
18304
+ admins: new Map(admins.map((admin) => [String(admin.id), admin])),
18305
+ viewer
18306
+ };
18307
+ return rows.map((row) => service.toDto(row, context));
18308
+ },
18309
+ /**
18310
+ * One impersonation row as the admin API returns it (no codes, hashes,
18311
+ * session or device references).
18312
+ *
18313
+ * @param {any} row Row.
18314
+ * @param {{users?: Map<string, any>, admins?: Map<string, any>, actor?: any, viewer?: any}}
18315
+ * context Lookups for labels.
18316
+ * @returns {object} DTO.
18317
+ */
18318
+ toDto(row, context = {}) {
18319
+ const actor = context.actor || context.admins?.get(String(row.actorId));
18320
+ const user = row.targetType === "user" ? context.users?.get(row.targetId) : null;
18321
+ const targetAdmin = row.targetType === "admin" ? context.admins?.get(String(row.targetId)) : null;
18322
+ const viewerId = context.viewer?.id ?? context.actor?.id;
18323
+ return {
18324
+ id: row.documentId,
18325
+ targetType: row.targetType,
18326
+ targetId: row.targetId,
18327
+ targetLabel: user ? String(user.username || user.email || "").slice(0, 120) : adminLabel(targetAdmin),
18328
+ actorId: row.actorId,
18329
+ actorLabel: adminLabel(actor),
18330
+ startedByYou: viewerId != null && String(viewerId) === String(row.actorId),
18331
+ reason: row.reason,
18332
+ durationMinutes: row.durationMinutes,
18333
+ handoff: row.handoff,
18334
+ credentialIssued: Boolean(row.credentialIssuedAt),
18335
+ startedAt: new Date(row.startedAt).toISOString(),
18336
+ expiresAt: new Date(row.expiresAt).toISOString(),
18337
+ state: row.state
18338
+ };
18339
+ },
18340
+ /**
18341
+ * Loads one impersonation for the request guard (5-second cache).
18342
+ *
18343
+ * @param {string} documentId Impersonation id.
18344
+ * @returns {Promise<{id: string, actorId: string, state: string, expiresAt: number}|null>}
18345
+ */
18346
+ async loadForGuard(documentId) {
18347
+ const cached = recordCache.get(documentId);
18348
+ if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
18349
+ const row = await query().findOne({
18350
+ where: { documentId, targetType: "user" },
18351
+ select: ["documentId", "actorId", "state", "expiresAt"]
18352
+ });
18353
+ const value = row ? {
18354
+ id: row.documentId,
18355
+ actorId: row.actorId,
18356
+ state: row.state,
18357
+ expiresAt: new Date(row.expiresAt).getTime()
18358
+ } : null;
18359
+ remember(recordCache, documentId, { value, at: Date.now() });
18360
+ return value;
18361
+ },
18362
+ /**
18363
+ * The impersonation a Users & Permissions token belongs to, or null. A
18364
+ * legacy token carries the `msmImp` claim; a refresh-mode token names
18365
+ * its session, whose metadata carries the mark. The signature is checked
18366
+ * by Strapi afterwards.
18367
+ *
18368
+ * @param {string} token Access or refresh token.
18369
+ * @returns {Promise<string|null>} Impersonation id.
18370
+ */
18371
+ async impersonationOfToken(token) {
18372
+ const payload = decodeJwtPayload(token);
18373
+ if (!payload) return null;
18374
+ if (typeof payload.msmImp === "string" && DOCUMENT_ID_PATTERN.test(payload.msmImp)) {
18375
+ return payload.msmImp;
18376
+ }
18377
+ const sessionId = payload.sessionId;
18378
+ if (typeof sessionId !== "string" || !/^[a-f0-9]{16,64}$/i.test(sessionId)) return null;
18379
+ if (nativeSessionCache.has(sessionId)) return nativeSessionCache.get(sessionId);
18380
+ let id = null;
18381
+ try {
18382
+ const session = await strapi2.db.query(NATIVE_SESSION_UID).findOne({
18383
+ where: { sessionId, origin: NATIVE_ORIGIN },
18384
+ select: ["metadata", "deviceId"]
18385
+ });
18386
+ const mark = session?.metadata?.msmImpersonation;
18387
+ if (typeof mark === "string" && DOCUMENT_ID_PATTERN.test(mark)) id = mark;
18388
+ else if (typeof session?.deviceId === "string" && session.deviceId.startsWith(DEVICE_PREFIX)) {
18389
+ id = "unknown";
18390
+ }
18391
+ if (session) remember(nativeSessionCache, sessionId, id);
18392
+ } catch (err) {
18393
+ log.warn("[IMPERSONATION] Session lookup failed:", err?.name || "Error");
18394
+ throw err;
18395
+ }
18396
+ return id;
18397
+ },
18398
+ /**
18399
+ * Records a refused Content API call made while impersonating (one event
18400
+ * per impersonation and reason per minute).
18401
+ *
18402
+ * @param {{id: string, actorId: string}} impersonation Impersonation.
18403
+ * @param {string} reason Refusal reason.
18404
+ * @returns {void}
18405
+ */
18406
+ recordRefusedCall(impersonation, reason) {
18407
+ const key = `${impersonation.id}|${reason}`;
18408
+ const now = Date.now();
18409
+ const last = refusals.get(key);
18410
+ if (last !== void 0 && now - last < REFUSAL_DEDUP_MS) return;
18411
+ remember(refusals, key, now);
18412
+ record({
18413
+ event: EVENTS.REFUSED,
18414
+ actorType: "admin",
18415
+ actorId: impersonation.actorId,
18416
+ targetType: "user",
18417
+ targetId: null,
18418
+ meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
18419
+ });
18420
+ },
18421
+ /**
18422
+ * Emails the user that their account was opened (best effort, no
18423
+ * admin names; the reason is escaped).
18424
+ *
18425
+ * @param {{email?: string, username?: string}} user Target user.
18426
+ * @param {{reason: string, durationMinutes: number}} value Start values.
18427
+ * @param {Date} expiresAt End time.
18428
+ * @returns {void}
18429
+ * @sideeffect Sends one email through Strapi's email plugin when it is installed.
18430
+ */
18431
+ notifyUser(user, value, expiresAt) {
18432
+ const emailPlugin = strapi2.plugin("email");
18433
+ if (!emailPlugin || typeof user?.email !== "string" || !user.email) return;
18434
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
18435
+ const escapeText = (text2) => typeof notifications?.escapeHtml === "function" ? notifications.escapeHtml(text2) : String(text2).replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
18436
+ const minutes = value.durationMinutes;
18437
+ const until = expiresAt.toISOString().replace("T", " ").slice(0, 16);
18438
+ const text = [
18439
+ "An administrator opened your account for support.",
18440
+ `Reason: ${value.reason}`,
18441
+ `Duration: up to ${minutes} minutes (until ${until} UTC).`,
18442
+ "They act as you while this lasts but cannot change your password, email address or sessions.",
18443
+ "If you did not expect this, please contact support."
18444
+ ].join("\n");
18445
+ const html = `<p>An administrator opened your account for support.</p><p><strong>Reason:</strong> ${escapeText(
18446
+ value.reason
18447
+ )}<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>`;
18448
+ Promise.resolve().then(
18449
+ () => emailPlugin.service("email").send({ to: user.email, subject: "Your account was opened by support", text, html })
18450
+ ).catch((err) => {
18451
+ log.warn("[IMPERSONATION] Notification email failed:", err?.name || "Error");
18452
+ });
18453
+ }
18454
+ };
18455
+ return service;
18456
+ };
18457
+ module.exports.UID = UID;
18458
+ module.exports.ImpersonationError = ImpersonationError;
18459
+ module.exports.DEVICE_PREFIX = DEVICE_PREFIX;
18460
+ }
18461
+ });
18462
+
18463
+ // server/src/controllers/impersonation.js
18464
+ var require_impersonation2 = __commonJS({
18465
+ "server/src/controllers/impersonation.js"(exports, module) {
18466
+ "use strict";
18467
+ var { DOCUMENT_ID_PATTERN } = require_impersonation_rules();
18468
+ var { ImpersonationError } = require_impersonation();
18469
+ var { sendServerError } = require_http_errors();
18470
+ var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18471
+ var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
18472
+ function callerCan(ctx, action) {
18473
+ try {
18474
+ return ctx?.state?.userAbility?.can?.(action) === true;
18475
+ } catch {
18476
+ return false;
18477
+ }
18478
+ }
18479
+ function visibleTargetTypes(ctx) {
18480
+ return [
18481
+ ...callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [],
18482
+ ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) ? ["admin"] : []
18483
+ ];
18484
+ }
18485
+ var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
18486
+ async function respond(ctx, operation, handler) {
18487
+ try {
18488
+ return await handler();
18489
+ } catch (err) {
18490
+ if (err instanceof ImpersonationError && REPLY[err.status]) {
18491
+ return ctx[REPLY[err.status]](err.message, err.details);
18492
+ }
18493
+ strapi.log.error(
18494
+ `[magic-sessionmanager/impersonation] ${operation} failed:`,
18495
+ err?.name || "Error"
18496
+ );
18497
+ return sendServerError(ctx, 500, "Impersonation request failed");
18498
+ }
18499
+ }
18500
+ function requirePerson(ctx, targetType, targetId) {
18501
+ if (ctx.state?.auth?.strategy?.name === "admin") return;
18502
+ const service = strapi.plugin("magic-sessionmanager").service("impersonation");
18503
+ service.recordRefused({
18504
+ actorId: ctx.state?.user?.id,
18505
+ targetType,
18506
+ targetId,
18507
+ reason: "api-token",
18508
+ via: "admin-token"
18509
+ });
18510
+ throw new ImpersonationError(403, "API tokens cannot impersonate", { reason: "api-token" });
18511
+ }
18512
+ module.exports = ({ strapi: app }) => {
18513
+ const service = () => app.plugin("magic-sessionmanager").service("impersonation");
18514
+ return {
18515
+ /**
18516
+ * Feature state for the admin UI.
18517
+ *
18518
+ * @route GET /magic-sessionmanager/impersonation/status
18519
+ * @auth Admin JWT or admin API token; `access`.
18520
+ * @returns {Promise<void>} `{ data: { enabled, handoff, frontendOrigin, durations, mode } }`.
18521
+ */
18522
+ async status(ctx) {
18523
+ ctx.body = { data: await service().status() };
18524
+ },
18525
+ /**
18526
+ * Starts an impersonation of an app user.
18527
+ *
18528
+ * @route POST /magic-sessionmanager/impersonation/users/:userId
18529
+ * @auth Admin JWT only (admin API tokens are refused); `access` + `impersonate.users`.
18530
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30|60, notifyUser?: boolean }`.
18531
+ * @returns {Promise<void>} 201 `{ data: { impersonation, handoff } }`; `handoff` is either
18532
+ * `{ type: 'frontend', url, field, code, codeExpiresAt }` or `{ type: 'token', jwt,
18533
+ * refreshToken?, expiresAt }`, shown once.
18534
+ * Answers 400 for an invalid body, user id or a blocked account, 403 when the feature is
18535
+ * off, for API tokens or when one is already active, 404 for an unknown user.
18536
+ * @sideeffect Creates the impersonation and, for the token hand-off, its session; logs
18537
+ * `impersonation.started` or `.refused`; may email the user.
18538
+ */
18539
+ async startUser(ctx) {
18540
+ ctx.set("Cache-Control", "no-store");
18541
+ return respond(ctx, "start", async () => {
18542
+ const { userId } = ctx.params;
18543
+ requirePerson(ctx, "user", userId);
18544
+ const result = await service().startForUser({
18545
+ actor: ctx.state.user,
18546
+ userDocumentId: userId,
18547
+ body: ctx.request.body,
18548
+ ctx
18549
+ });
18550
+ ctx.status = 201;
18551
+ ctx.body = { data: result };
18552
+ });
18553
+ },
18554
+ /**
18555
+ * Active impersonations the caller may see: app users with
18556
+ * `impersonate.users`, admin previews with `impersonate.admins`. Admin
18557
+ * names need `admin::users.read`, as in the Admin panel view.
18558
+ *
18559
+ * @route GET /magic-sessionmanager/impersonation/active
18560
+ * @auth Admin JWT or admin API token; `access` + one of the impersonate actions.
18561
+ * @returns {Promise<void>} `{ data: Impersonation[] }` (at most 100).
18562
+ */
18563
+ async listActive(ctx) {
18564
+ return respond(ctx, "list", async () => {
18565
+ const data = await service().listActive({
18566
+ targetTypes: visibleTargetTypes(ctx),
18567
+ viewer: ctx.state.user,
18568
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18569
+ });
18570
+ ctx.body = { data };
18571
+ });
18572
+ },
18573
+ /**
18574
+ * Ends an active impersonation now.
18575
+ *
18576
+ * @route POST /magic-sessionmanager/impersonation/:id/end
18577
+ * @auth Admin JWT or admin API token; `access` + the impersonate action of its kind
18578
+ * (`impersonate.users` for app users, `impersonate.admins` for admin previews).
18579
+ * @returns {Promise<void>} `{ data: { ended: boolean } }`.
18580
+ * Answers 404 for an unknown id or a kind the caller may not see.
18581
+ * @sideeffect Revokes the credential; logs `impersonation.ended`.
18582
+ */
18583
+ async end(ctx) {
18584
+ return respond(ctx, "end", async () => {
18585
+ const { id } = ctx.params;
18586
+ if (typeof id !== "string" || !DOCUMENT_ID_PATTERN.test(id)) {
18587
+ throw new ImpersonationError(404, "Impersonation not found");
18588
+ }
18589
+ const row = await app.db.query("plugin::magic-sessionmanager.impersonation").findOne({ where: { documentId: id }, select: ["documentId", "targetType", "state"] });
18590
+ if (!row || !visibleTargetTypes(ctx).includes(row.targetType)) {
18591
+ throw new ImpersonationError(404, "Impersonation not found");
18592
+ }
18593
+ const ended = row.state === "active" ? await service().end(id, { reason: "ended", endedBy: ctx.state.user.id }) : false;
18594
+ ctx.body = { data: { ended } };
18595
+ });
18596
+ },
18597
+ /**
18598
+ * Starts a read-only permission preview of another admin ("View as
18599
+ * admin"): which content types and actions they can use. No session or
18600
+ * token is created.
18601
+ *
18602
+ * @route POST /magic-sessionmanager/impersonation/admins/:adminId/preview
18603
+ * @auth Admin JWT only (admin API tokens are refused); `access` + `impersonate.admins`.
18604
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30 }`.
18605
+ * @returns {Promise<void>} 201 `{ data: { impersonation, preview } }`. Answers 403 with
18606
+ * `details.reason` `disabled`, `api-token`, `self`, `super-admin` or `not-subset`,
18607
+ * 400 for an invalid body and 404 for an unknown admin.
18608
+ * @sideeffect Creates a preview row; logs `impersonation.started` or `.refused`.
18609
+ */
18610
+ async previewAdmin(ctx) {
18611
+ ctx.set("Cache-Control", "no-store");
18612
+ return respond(ctx, "preview", async () => {
18613
+ const { adminId } = ctx.params;
18614
+ requirePerson(ctx, "admin", adminId);
18615
+ const result = await service().previewAdmin({
18616
+ actor: ctx.state.user,
18617
+ adminId,
18618
+ body: ctx.request.body,
18619
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18620
+ });
18621
+ ctx.status = 201;
18622
+ ctx.body = { data: result };
18623
+ });
18624
+ },
18625
+ /**
18626
+ * Reads a running admin preview; only the admin who started it.
18627
+ *
18628
+ * @route GET /magic-sessionmanager/impersonation/previews/:id
18629
+ * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
18630
+ * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
18631
+ * expired or started by someone else.
18632
+ */
18633
+ async getPreview(ctx) {
18634
+ ctx.set("Cache-Control", "no-store");
18635
+ return respond(ctx, "preview", async () => {
18636
+ ctx.body = {
18637
+ data: await service().getPreview({
18638
+ id: ctx.params.id,
18639
+ viewer: ctx.state.user,
18640
+ canReadAdmins: callerCan(ctx, "admin::users.read")
18641
+ })
18642
+ };
18643
+ });
18644
+ },
18645
+ /**
18646
+ * Exchanges a one-time hand-off code for the impersonation credential.
18647
+ * Public on purpose: the code is the credential (32 random bytes, stored
18648
+ * hashed, valid 60 seconds, single use). Every invalid, used or expired
18649
+ * code gets the same 400.
18650
+ *
18651
+ * @route POST /api/magic-sessionmanager/impersonation/exchange
18652
+ * @auth None (rate-limited per IP address).
18653
+ * @param {any} ctx Body `{ code: string }`.
18654
+ * @returns {Promise<void>} `{ data: { jwt, refreshToken?, expiresAt, user, impersonation } }`.
18655
+ * Answers 400 for any unusable code.
18656
+ * @sideeffect Consumes the code; creates the credential and its session.
18657
+ */
18658
+ async exchange(ctx) {
18659
+ const body = ctx.request.body;
18660
+ const valid = body && typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 1 && typeof body.code === "string";
18661
+ ctx.set("Cache-Control", "no-store");
18662
+ return respond(ctx, "exchange", async () => {
18663
+ const result = valid ? await service().exchange(body.code, ctx) : null;
18664
+ if (!result) throw new ImpersonationError(400, "Invalid or expired code");
18665
+ ctx.body = { data: result };
18666
+ });
18667
+ }
18668
+ };
18669
+ };
18670
+ module.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
18671
+ module.exports.IMPERSONATE_ADMINS_ACTION = IMPERSONATE_ADMINS_ACTION;
18672
+ }
18673
+ });
18674
+
16749
18675
  // server/src/controllers/index.js
16750
18676
  var require_controllers = __commonJS({
16751
18677
  "server/src/controllers/index.js"(exports, module) {
@@ -16758,6 +18684,7 @@ var require_controllers = __commonJS({
16758
18684
  var lockouts = require_lockouts();
16759
18685
  var selfService = require_self_service();
16760
18686
  var webhooks = require_webhooks();
18687
+ var impersonation = require_impersonation2();
16761
18688
  module.exports = {
16762
18689
  session,
16763
18690
  settings,
@@ -16766,7 +18693,8 @@ var require_controllers = __commonJS({
16766
18693
  "admin-activity": adminActivity,
16767
18694
  lockouts,
16768
18695
  "self-service": selfService,
16769
- webhooks
18696
+ webhooks,
18697
+ impersonation
16770
18698
  };
16771
18699
  }
16772
18700
  });
@@ -21009,12 +22937,14 @@ var require_services = __commonJS({
21009
22937
  var notifications = require_notifications();
21010
22938
  var securityLog = require_security_log();
21011
22939
  var webhooks = require_webhooks2();
22940
+ var impersonation = require_impersonation();
21012
22941
  module.exports = {
21013
22942
  session,
21014
22943
  geolocation,
21015
22944
  notifications,
21016
22945
  "security-log": securityLog,
21017
- webhooks
22946
+ webhooks,
22947
+ impersonation
21018
22948
  };
21019
22949
  }
21020
22950
  });
@@ -21222,13 +23152,33 @@ var require_session_required = __commonJS({
21222
23152
  }
21223
23153
  });
21224
23154
 
23155
+ // server/src/policies/can-impersonate.js
23156
+ var require_can_impersonate = __commonJS({
23157
+ "server/src/policies/can-impersonate.js"(exports, module) {
23158
+ "use strict";
23159
+ module.exports = (policyContext) => {
23160
+ const ability = policyContext?.state?.userAbility;
23161
+ const can = (action) => {
23162
+ try {
23163
+ return ability?.can?.(action) === true;
23164
+ } catch {
23165
+ return false;
23166
+ }
23167
+ };
23168
+ return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins");
23169
+ };
23170
+ }
23171
+ });
23172
+
21225
23173
  // server/src/policies/index.js
21226
23174
  var require_policies = __commonJS({
21227
23175
  "server/src/policies/index.js"(exports, module) {
21228
23176
  "use strict";
21229
23177
  var sessionRequired = require_session_required();
23178
+ var canImpersonate = require_can_impersonate();
21230
23179
  module.exports = {
21231
- "session-required": sessionRequired
23180
+ "session-required": sessionRequired,
23181
+ "can-impersonate": canImpersonate
21232
23182
  };
21233
23183
  }
21234
23184
  });