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