strapi-plugin-magic-sessionmanager 4.19.0 → 4.20.0

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