strapi-plugin-magic-sessionmanager 4.22.0 → 4.23.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 (35) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +163 -119
  3. package/dist/admin/ActiveImpersonationsCard-CbyOAlrL.mjs +396 -0
  4. package/dist/admin/ActiveImpersonationsCard-D1CVmV-w.js +395 -0
  5. package/dist/admin/{Analytics-WbCUmkQQ.mjs → Analytics-DGAHD19E.mjs} +1 -1
  6. package/dist/admin/{Analytics-DeDLGiCe.js → Analytics-_WA68oHb.js} +1 -1
  7. package/dist/admin/{App-Bkv-W0Sv.js → App-CfhAQ17e.js} +304 -104
  8. package/dist/admin/{App-C4bihk2K.mjs → App-VB66H73A.mjs} +276 -76
  9. package/dist/admin/ImpersonationTabBanner-B6Ps5-oe.mjs +244 -0
  10. package/dist/admin/ImpersonationTabBanner-DdwXNmh4.js +244 -0
  11. package/dist/admin/{OnlineUsersWidget-q0Z6nbbO.mjs → OnlineUsersWidget-2u-fYMb7.mjs} +1 -1
  12. package/dist/admin/{OnlineUsersWidget-CSvNe2rC.js → OnlineUsersWidget-CmBqFLAA.js} +1 -1
  13. package/dist/admin/{Settings-xokFI5LO.js → Settings-BBs2FDp7.js} +87 -266
  14. package/dist/admin/{Settings-avD0DbXP.mjs → Settings-CKDNGJhl.mjs} +79 -258
  15. package/dist/admin/{de-BQlEdBMr.mjs → de-CK-HuY41.mjs} +48 -7
  16. package/dist/admin/{de-HcJ19LKI.js → de-CSRQPn6F.js} +48 -7
  17. package/dist/admin/{en-DI-98CPM.js → en-DCtAgGEa.js} +48 -7
  18. package/dist/admin/{en-DzuXWL1W.mjs → en-KZ5ajaAR.mjs} +48 -7
  19. package/dist/admin/{es-BfyED9YI.mjs → es-B7k8taWV.mjs} +48 -7
  20. package/dist/admin/{es-Cm0Eklav.js → es-CKT00l4K.js} +48 -7
  21. package/dist/admin/{fr-C3nzszsI.js → fr-B2EdBFSb.js} +48 -7
  22. package/dist/admin/{fr-CzFNGWq0.mjs → fr-Q2gmYqCn.mjs} +48 -7
  23. package/dist/admin/{index-6zc5D8eb.mjs → index-BPbs1GyP.mjs} +386 -61
  24. package/dist/admin/{index-Dk5Jqe5U.js → index-Cho0XGZ1.js} +340 -15
  25. package/dist/admin/index.js +1 -1
  26. package/dist/admin/index.mjs +2 -2
  27. package/dist/admin/{pt-BPZ6chPT.js → pt-CcMUcqDy.js} +48 -7
  28. package/dist/admin/{pt-DmyQnGI_.mjs → pt-CmxZTaf2.mjs} +48 -7
  29. package/dist/admin/useBreakpoint-CoBfu0Ov.js +62 -0
  30. package/dist/admin/useBreakpoint-CuyIc2qy.mjs +63 -0
  31. package/dist/server/index.js +1809 -400
  32. package/dist/server/index.mjs +1809 -400
  33. package/package.json +9 -4
  34. package/dist/admin/dashboardModel-BBNRgcEr.mjs +0 -170
  35. package/dist/admin/dashboardModel-D4389iIV.js +0 -169
@@ -1471,10 +1471,249 @@ var require_policy_settings = __commonJS({
1471
1471
  }
1472
1472
  });
1473
1473
 
1474
+ // server/src/utils/webhook-delivery.js
1475
+ var require_webhook_delivery = __commonJS({
1476
+ "server/src/utils/webhook-delivery.js"(exports2, module2) {
1477
+ "use strict";
1478
+ var crypto = require("node:crypto");
1479
+ var dns = require("node:dns");
1480
+ var https = require("node:https");
1481
+ var net = require("node:net");
1482
+ var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
1483
+ var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
1484
+ var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
1485
+ var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
1486
+ var TIMEOUT_MS = 5e3;
1487
+ var DEADLINE_MS = 1e4;
1488
+ var MAX_RESPONSE_BYTES = 64 * 1024;
1489
+ var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
1490
+ var BLOCKED = (() => {
1491
+ const list = new net.BlockList();
1492
+ for (const [address, prefix] of [
1493
+ ["0.0.0.0", 8],
1494
+ ["10.0.0.0", 8],
1495
+ ["100.64.0.0", 10],
1496
+ ["127.0.0.0", 8],
1497
+ ["169.254.0.0", 16],
1498
+ ["172.16.0.0", 12],
1499
+ ["192.0.0.0", 24],
1500
+ ["192.0.2.0", 24],
1501
+ ["192.88.99.0", 24],
1502
+ ["192.168.0.0", 16],
1503
+ ["198.18.0.0", 15],
1504
+ ["198.51.100.0", 24],
1505
+ ["203.0.113.0", 24],
1506
+ ["224.0.0.0", 4],
1507
+ ["240.0.0.0", 4]
1508
+ ]) {
1509
+ list.addSubnet(address, prefix, "ipv4");
1510
+ }
1511
+ for (const [address, prefix] of [
1512
+ // IPv4-compatible (::a.b.c.d, deprecated) and IPv4-translated
1513
+ // (::ffff:0:a.b.c.d, RFC 2765) forms, which include the unspecified and
1514
+ // loopback addresses (security review 2, hardening 1).
1515
+ ["::", 96],
1516
+ ["::ffff:0:0:0", 96],
1517
+ // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
1518
+ // checks them against the IPv4 rules above, and a listed /96 would
1519
+ // match every IPv4 address.
1520
+ ["64:ff9b::", 96],
1521
+ ["64:ff9b:1::", 48],
1522
+ ["100::", 64],
1523
+ ["2001::", 23],
1524
+ ["2001:db8::", 32],
1525
+ ["2002::", 16],
1526
+ ["fc00::", 7],
1527
+ ["fe80::", 10],
1528
+ ["fec0::", 10],
1529
+ ["ff00::", 8]
1530
+ ]) {
1531
+ list.addSubnet(address, prefix, "ipv6");
1532
+ }
1533
+ return list;
1534
+ })();
1535
+ function isBlockedAddress(address) {
1536
+ let value = String(address || "").trim();
1537
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
1538
+ value = value.slice(7);
1539
+ }
1540
+ const version = net.isIP(value);
1541
+ if (version === 0) return true;
1542
+ return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
1543
+ }
1544
+ function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
1545
+ const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
1546
+ return `t=${timestamp},v1=${digest}`;
1547
+ }
1548
+ function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
1549
+ const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
1550
+ if (!match) return false;
1551
+ const timestamp = Number(match[1]);
1552
+ if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
1553
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
1554
+ const given = Buffer.from(match[2], "hex");
1555
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
1556
+ }
1557
+ var DeliveryError = class extends Error {
1558
+ /**
1559
+ * @param {string} code Stable code.
1560
+ * @param {boolean} retryable Whether another attempt may succeed.
1561
+ * @param {number|null} [status] HTTP status, when there was one.
1562
+ */
1563
+ constructor(code, retryable, status = null) {
1564
+ super(code);
1565
+ this.name = "DeliveryError";
1566
+ this.code = code;
1567
+ this.retryable = retryable;
1568
+ this.status = status;
1569
+ }
1570
+ };
1571
+ var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
1572
+ function httpsPost({ url, address, headers, body, timeoutMs, deadlineMs = DEADLINE_MS }) {
1573
+ return new Promise((resolve, reject) => {
1574
+ const request = https.request(
1575
+ {
1576
+ protocol: "https:",
1577
+ hostname: url.hostname,
1578
+ port: url.port || 443,
1579
+ path: `${url.pathname}${url.search}`,
1580
+ method: "POST",
1581
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
1582
+ servername: net.isIP(url.hostname) ? void 0 : url.hostname,
1583
+ timeout: timeoutMs,
1584
+ signal: AbortSignal.timeout(deadlineMs),
1585
+ // Pinned to the address that passed the check: no second lookup.
1586
+ lookup: (_hostname, options, callback) => {
1587
+ if (options && options.all) callback(null, [address]);
1588
+ else callback(null, address.address, address.family);
1589
+ }
1590
+ },
1591
+ (response) => {
1592
+ let received = 0;
1593
+ response.on("data", (chunk) => {
1594
+ received += chunk.length;
1595
+ if (received > MAX_RESPONSE_BYTES) response.destroy();
1596
+ });
1597
+ response.on("end", () => resolve(response.statusCode || 0));
1598
+ response.on("close", () => resolve(response.statusCode || 0));
1599
+ response.on("error", () => resolve(response.statusCode || 0));
1600
+ }
1601
+ );
1602
+ request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
1603
+ request.on(
1604
+ "error",
1605
+ (err) => reject(
1606
+ err instanceof DeliveryError ? err : err?.name === "AbortError" ? new DeliveryError("timeout", true) : new DeliveryError("network_error", true)
1607
+ )
1608
+ );
1609
+ request.end(body);
1610
+ });
1611
+ }
1612
+ async function deliverOnce({
1613
+ url,
1614
+ body,
1615
+ headers,
1616
+ resolve = resolveAll,
1617
+ post = httpsPost,
1618
+ timeoutMs = TIMEOUT_MS,
1619
+ deadlineMs = DEADLINE_MS
1620
+ }) {
1621
+ let parsed;
1622
+ try {
1623
+ parsed = new URL(url);
1624
+ } catch {
1625
+ throw new DeliveryError("invalid_url", false);
1626
+ }
1627
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
1628
+ throw new DeliveryError("invalid_url", false);
1629
+ }
1630
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
1631
+ let addresses;
1632
+ if (net.isIP(host)) {
1633
+ addresses = [{ address: host, family: net.isIP(host) }];
1634
+ } else {
1635
+ try {
1636
+ addresses = await resolve(host);
1637
+ } catch {
1638
+ throw new DeliveryError("dns_failed", true);
1639
+ }
1640
+ }
1641
+ if (!Array.isArray(addresses) || addresses.length === 0)
1642
+ throw new DeliveryError("dns_failed", true);
1643
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
1644
+ throw new DeliveryError("address_not_allowed", false);
1645
+ }
1646
+ const status = await post({
1647
+ url: parsed,
1648
+ address: addresses[0],
1649
+ headers,
1650
+ body,
1651
+ timeoutMs,
1652
+ deadlineMs
1653
+ });
1654
+ if (status >= 200 && status < 300) return { status };
1655
+ if (status >= 300 && status < 400)
1656
+ throw new DeliveryError("redirect_not_followed", false, status);
1657
+ throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
1658
+ }
1659
+ function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
1660
+ const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
1661
+ return {
1662
+ id,
1663
+ body,
1664
+ headers: {
1665
+ "Content-Type": "application/json",
1666
+ "User-Agent": USER_AGENT,
1667
+ [EVENT_HEADER]: event,
1668
+ [DELIVERY_HEADER]: id,
1669
+ [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
1670
+ }
1671
+ };
1672
+ }
1673
+ async function deliverWithRetries({
1674
+ delays = RETRY_DELAYS_MS,
1675
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
1676
+ ...request
1677
+ }) {
1678
+ let attempts = 0;
1679
+ let last = { ok: false, status: null, code: "not_sent" };
1680
+ for (const delay of delays) {
1681
+ if (delay > 0) await sleep(delay);
1682
+ attempts += 1;
1683
+ try {
1684
+ const { status } = await deliverOnce(request);
1685
+ return { ok: true, status, code: null, attempts };
1686
+ } catch (err) {
1687
+ const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
1688
+ last = { ok: false, status: error.status, code: error.code };
1689
+ if (!error.retryable) break;
1690
+ }
1691
+ }
1692
+ return { ...last, attempts };
1693
+ }
1694
+ module2.exports = {
1695
+ DEADLINE_MS,
1696
+ DELIVERY_HEADER,
1697
+ DeliveryError,
1698
+ EVENT_HEADER,
1699
+ RETRY_DELAYS_MS,
1700
+ SIGNATURE_HEADER,
1701
+ buildSignedRequest,
1702
+ deliverOnce,
1703
+ deliverWithRetries,
1704
+ isBlockedAddress,
1705
+ signPayload,
1706
+ verifySignature
1707
+ };
1708
+ }
1709
+ });
1710
+
1474
1711
  // server/src/utils/detection-settings.js
1475
1712
  var require_detection_settings = __commonJS({
1476
1713
  "server/src/utils/detection-settings.js"(exports2, module2) {
1477
1714
  "use strict";
1715
+ var net = require("node:net");
1716
+ var { isBlockedAddress } = require_webhook_delivery();
1478
1717
  var WEBHOOK_EVENTS = Object.freeze([
1479
1718
  "login.success",
1480
1719
  "login.suspicious",
@@ -1559,6 +1798,8 @@ var require_detection_settings = __commonJS({
1559
1798
  if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
1560
1799
  return null;
1561
1800
  }
1801
+ const literal = host.replace(/^\[|\]$/g, "");
1802
+ if (net.isIP(literal) && isBlockedAddress(literal)) return null;
1562
1803
  return parsed.toString();
1563
1804
  }
1564
1805
  function normalizeEventList(value) {
@@ -1929,6 +2170,89 @@ var require_impersonation_rules = __commonJS({
1929
2170
  }
1930
2171
  });
1931
2172
 
2173
+ // server/src/utils/trusted-proxies.js
2174
+ var require_trusted_proxies = __commonJS({
2175
+ "server/src/utils/trusted-proxies.js"(exports2, module2) {
2176
+ "use strict";
2177
+ var { parseTrustedAddress } = require_policy_settings();
2178
+ var MAX_TRUSTED_PROXIES = 50;
2179
+ function normalizeTrustedProxies(value) {
2180
+ if (!Array.isArray(value)) return [];
2181
+ const out = [];
2182
+ for (const entry of value.slice(0, MAX_TRUSTED_PROXIES)) {
2183
+ const parsed = parseTrustedAddress(entry);
2184
+ if (parsed && !out.includes(parsed.text)) out.push(parsed.text);
2185
+ }
2186
+ return out;
2187
+ }
2188
+ function isLegacyTrustAll(value) {
2189
+ return value === true;
2190
+ }
2191
+ function validateTrustedProxies(value) {
2192
+ if (typeof value === "boolean") return { value: [], error: null, legacyTrue: value };
2193
+ if (!Array.isArray(value) || value.length > MAX_TRUSTED_PROXIES) {
2194
+ return {
2195
+ value: null,
2196
+ legacyTrue: false,
2197
+ error: {
2198
+ path: ["trustedProxies"],
2199
+ message: `trustedProxies must be a list of at most ${MAX_TRUSTED_PROXIES} IP addresses or CIDR ranges`
2200
+ }
2201
+ };
2202
+ }
2203
+ const parsed = value.map(parseTrustedAddress);
2204
+ const invalid = parsed.findIndex((entry) => entry === null);
2205
+ if (invalid !== -1) {
2206
+ return {
2207
+ value: null,
2208
+ legacyTrue: false,
2209
+ error: {
2210
+ path: ["trustedProxies", invalid],
2211
+ message: "Each trusted proxy must be an IP address or a CIDR range such as 10.0.0.0/8"
2212
+ }
2213
+ };
2214
+ }
2215
+ return {
2216
+ value: [...new Set(parsed.map((entry) => (
2217
+ /** @type {any} */
2218
+ entry.text
2219
+ )))],
2220
+ error: null,
2221
+ legacyTrue: false
2222
+ };
2223
+ }
2224
+ var LEGACY_WARNING = "[CONFIG] trustedProxies: true no longer makes the plugin read CF-Connecting-IP, True-Client-IP, X-Real-IP or the left-most X-Forwarded-For entry (a client can set them). The client IP now comes from Strapi's server.proxy settings (koa, ipHeader, maxIpsCount). To trust specific proxies instead, set trustedProxies to a list of their IP addresses or CIDR ranges.";
2225
+ async function migrateLegacyProxyTrust(strapi2, log) {
2226
+ const { withPluginStoreKey } = require_plugin_store();
2227
+ const { notifySettingsChanged } = require_settings_loader();
2228
+ const config2 = isLegacyTrustAll(
2229
+ strapi2.config.get("plugin::magic-sessionmanager")?.trustedProxies
2230
+ );
2231
+ const store = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
2232
+ let stored = isLegacyTrustAll((await store.get({ key: "settings" }))?.trustedProxies);
2233
+ if (stored) {
2234
+ stored = await withPluginStoreKey(strapi2, "settings", async (scoped) => {
2235
+ const value = await scoped.get({ key: "settings" });
2236
+ if (!value || !isLegacyTrustAll(value.trustedProxies)) return false;
2237
+ await scoped.set({ key: "settings", value: { ...value, trustedProxies: [] } });
2238
+ return true;
2239
+ });
2240
+ if (stored) await notifySettingsChanged(strapi2);
2241
+ }
2242
+ if (stored || config2) log.warn(LEGACY_WARNING);
2243
+ return { stored, config: config2 };
2244
+ }
2245
+ module2.exports = {
2246
+ LEGACY_WARNING,
2247
+ MAX_TRUSTED_PROXIES,
2248
+ isLegacyTrustAll,
2249
+ migrateLegacyProxyTrust,
2250
+ normalizeTrustedProxies,
2251
+ validateTrustedProxies
2252
+ };
2253
+ }
2254
+ });
2255
+
1932
2256
  // server/src/utils/settings-loader.js
1933
2257
  var require_settings_loader = __commonJS({
1934
2258
  "server/src/utils/settings-loader.js"(exports2, module2) {
@@ -1937,6 +2261,7 @@ var require_settings_loader = __commonJS({
1937
2261
  var { normalizePolicySettings } = require_policy_settings();
1938
2262
  var { normalizeDetectionSettings } = require_detection_settings();
1939
2263
  var { normalizeImpersonationSettings } = require_impersonation_rules();
2264
+ var { normalizeTrustedProxies } = require_trusted_proxies();
1940
2265
  var PLUGIN_ID = "magic-sessionmanager";
1941
2266
  var SETTINGS_KEY = "settings";
1942
2267
  var CACHE_TTL_MS = 30 * 1e3;
@@ -2066,7 +2391,8 @@ var require_settings_loader = __commonJS({
2066
2391
  out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 7, 730);
2067
2392
  }
2068
2393
  if (stored.trustedProxies !== void 0) {
2069
- out.trustedProxies = stored.trustedProxies;
2394
+ const proxies = normalizeTrustedProxies(stored.trustedProxies);
2395
+ if (proxies.length > 0) out.trustedProxies = proxies;
2070
2396
  }
2071
2397
  Object.assign(out, normalizePolicySettings(stored));
2072
2398
  Object.assign(out, normalizeDetectionSettings(stored));
@@ -2185,6 +2511,8 @@ var require_security_log_model = __commonJS({
2185
2511
  SETTINGS_UPDATED: "settings.updated",
2186
2512
  LOG_RETENTION_PURGED: "security-log.retention.purged",
2187
2513
  LOG_READ: "security-log.read",
2514
+ // 4.22.1: SESSION_ENCRYPTION_KEY shorter than 32 bytes, once per key.
2515
+ CONFIG_WEAK_KEY: "config.encryption-key.weak",
2188
2516
  // App users (Users & Permissions), 4.17.
2189
2517
  USER_SIGN_IN_FAILED: "user.sign-in.failed",
2190
2518
  USER_SIGN_IN_REFUSED: "user.sign-in.refused",
@@ -2202,7 +2530,11 @@ var require_security_log_model = __commonJS({
2202
2530
  IMPERSONATION_STARTED: "impersonation.started",
2203
2531
  IMPERSONATION_ENDED: "impersonation.ended",
2204
2532
  IMPERSONATION_EXPIRED: "impersonation.expired",
2205
- IMPERSONATION_REFUSED: "impersonation.refused"
2533
+ IMPERSONATION_REFUSED: "impersonation.refused",
2534
+ // 4.23: a change made while signed in as another admin. Actor = the real
2535
+ // admin, target and `meta.impersonating` = the admin signed in as, plus
2536
+ // the method and path (no query, no body).
2537
+ IMPERSONATION_WRITE: "impersonation.write"
2206
2538
  });
2207
2539
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
2208
2540
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
@@ -2211,7 +2543,8 @@ var require_security_log_model = __commonJS({
2211
2543
  SECURITY_EVENTS.IMPERSONATION_STARTED,
2212
2544
  SECURITY_EVENTS.IMPERSONATION_ENDED,
2213
2545
  SECURITY_EVENTS.IMPERSONATION_EXPIRED,
2214
- SECURITY_EVENTS.IMPERSONATION_REFUSED
2546
+ SECURITY_EVENTS.IMPERSONATION_REFUSED,
2547
+ SECURITY_EVENTS.IMPERSONATION_WRITE
2215
2548
  ]);
2216
2549
  function dropRankOf(event) {
2217
2550
  if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
@@ -2248,14 +2581,23 @@ var require_security_log_model = __commonJS({
2248
2581
  var ADMIN_LOG_EVENTS = Object.freeze([
2249
2582
  SECURITY_EVENTS.SETTINGS_UPDATED,
2250
2583
  SECURITY_EVENTS.LOG_READ,
2251
- SECURITY_EVENTS.LOG_RETENTION_PURGED
2584
+ SECURITY_EVENTS.LOG_RETENTION_PURGED,
2585
+ SECURITY_EVENTS.CONFIG_WEAK_KEY
2586
+ ]);
2587
+ var ADMIN_IMPERSONATION_EVENTS = Object.freeze([
2588
+ SECURITY_EVENTS.IMPERSONATION_STARTED,
2589
+ SECURITY_EVENTS.IMPERSONATION_ENDED,
2590
+ SECURITY_EVENTS.IMPERSONATION_EXPIRED,
2591
+ SECURITY_EVENTS.IMPERSONATION_REFUSED,
2592
+ SECURITY_EVENTS.IMPERSONATION_WRITE
2252
2593
  ]);
2253
2594
  var SIGN_IN_FILTERS = Object.freeze({
2254
2595
  all: [...ADMIN_SIGN_IN_EVENTS, ...ADMIN_LOG_EVENTS],
2255
2596
  succeeded: [SECURITY_EVENTS.ADMIN_SIGN_IN],
2256
2597
  failed: [SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED, SECURITY_EVENTS.ADMIN_LOCKOUT],
2257
2598
  "signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED],
2258
- changes: ADMIN_LOG_EVENTS
2599
+ changes: ADMIN_LOG_EVENTS,
2600
+ impersonation: ADMIN_IMPERSONATION_EVENTS
2259
2601
  });
2260
2602
  var CONTENT_ACTIONS = Object.freeze([
2261
2603
  "view",
@@ -2457,6 +2799,7 @@ var require_security_log_model = __commonJS({
2457
2799
  USER_SIGN_IN_EVENTS,
2458
2800
  ACTOR_TYPES,
2459
2801
  ADMIN_CONTENT_EVENTS,
2802
+ ADMIN_IMPERSONATION_EVENTS,
2460
2803
  ADMIN_LOG_EVENTS,
2461
2804
  ADMIN_SIGN_IN_EVENTS,
2462
2805
  CONTENT_ACTIONS,
@@ -2657,7 +3000,177 @@ var require_security_log_hardening = __commonJS({
2657
3000
  }
2658
3001
  });
2659
3002
 
2660
- // server/src/register.js
3003
+ // server/src/utils/graphql-impersonation-guard.js
3004
+ var require_graphql_impersonation_guard = __commonJS({
3005
+ "server/src/utils/graphql-impersonation-guard.js"(exports2, module2) {
3006
+ "use strict";
3007
+ var { errors } = require("@strapi/utils");
3008
+ var MARK = /* @__PURE__ */ Symbol.for("magic-sessionmanager.graphql-impersonation-guard");
3009
+ var MESSAGE = "Not allowed while impersonating";
3010
+ var REASON = "impersonation-mutation";
3011
+ function impersonationRefusal() {
3012
+ const error = new errors.ForbiddenError(MESSAGE, { reason: REASON });
3013
+ Object.defineProperty(error, "extensions", {
3014
+ value: {
3015
+ code: "FORBIDDEN",
3016
+ http: { status: 403 },
3017
+ error: { name: "ForbiddenError", message: MESSAGE, details: { reason: REASON } }
3018
+ },
3019
+ enumerable: false
3020
+ });
3021
+ return error;
3022
+ }
3023
+ function impersonationOf(contextValue) {
3024
+ const mark = contextValue?.koaContext?.state?.magicImpersonation ?? contextValue?.state?.magicImpersonation;
3025
+ return mark && typeof mark === "object" && typeof mark.id === "string" ? mark : null;
3026
+ }
3027
+ function createImpersonationApolloPlugin(strapi2) {
3028
+ return {
3029
+ [MARK]: true,
3030
+ async requestDidStart() {
3031
+ return {
3032
+ /**
3033
+ * @param {any} requestContext Apollo request context.
3034
+ * @returns {Promise<void>}
3035
+ * @throws {Error} ForbiddenError (HTTP 403, code FORBIDDEN) for a mutation while impersonating.
3036
+ */
3037
+ async didResolveOperation(requestContext) {
3038
+ if (requestContext?.operation?.operation !== "mutation") return;
3039
+ const impersonation = impersonationOf(requestContext.contextValue);
3040
+ if (!impersonation) return;
3041
+ try {
3042
+ strapi2.plugin("magic-sessionmanager").service("impersonation").recordRefusedCall(impersonation, "mutation");
3043
+ } catch {
3044
+ }
3045
+ throw impersonationRefusal();
3046
+ }
3047
+ };
3048
+ }
3049
+ };
3050
+ }
3051
+ function installGraphqlImpersonationGuard(strapi2, log) {
3052
+ let graphql;
3053
+ try {
3054
+ graphql = strapi2.plugin("graphql") || null;
3055
+ } catch {
3056
+ graphql = null;
3057
+ }
3058
+ if (!graphql) return false;
3059
+ if (typeof strapi2.config?.get !== "function" || typeof strapi2.config?.set !== "function") {
3060
+ return false;
3061
+ }
3062
+ try {
3063
+ const key = "plugin::graphql.apolloServer";
3064
+ const current = strapi2.config.get(key);
3065
+ const server = current && typeof current === "object" ? current : {};
3066
+ const plugins = Array.isArray(server.plugins) ? server.plugins : [];
3067
+ if (plugins.some((plugin) => plugin && plugin[MARK])) return true;
3068
+ strapi2.config.set(key, {
3069
+ ...server,
3070
+ plugins: [...plugins, createImpersonationApolloPlugin(strapi2)]
3071
+ });
3072
+ } catch (err) {
3073
+ log?.warn?.("[IMPERSONATION] GraphQL guard could not be installed:", err?.name || "Error");
3074
+ return false;
3075
+ }
3076
+ log?.info?.("[IMPERSONATION] GraphQL mutations are refused while impersonating");
3077
+ return true;
3078
+ }
3079
+ module2.exports = {
3080
+ createImpersonationApolloPlugin,
3081
+ impersonationRefusal,
3082
+ installGraphqlImpersonationGuard
3083
+ };
3084
+ }
3085
+ });
3086
+
3087
+ // server/src/utils/auth-controller-guard.js
3088
+ var require_auth_controller_guard = __commonJS({
3089
+ "server/src/utils/auth-controller-guard.js"(exports2, module2) {
3090
+ "use strict";
3091
+ var WRAPPED = /* @__PURE__ */ Symbol.for("magic-sessionmanager.auth-controller.wrapped");
3092
+ var GUARDED_ACTIONS = Object.freeze({
3093
+ callback: "callback",
3094
+ register: "newSession",
3095
+ resetPassword: "newSession",
3096
+ emailConfirmation: "newSession"
3097
+ });
3098
+ var handlersByStrapi = /* @__PURE__ */ new WeakMap();
3099
+ function installAuthControllerGuard(strapi2, log) {
3100
+ let controller;
3101
+ try {
3102
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3103
+ } catch {
3104
+ controller = null;
3105
+ }
3106
+ if (!controller || typeof controller !== "object") {
3107
+ log?.warn?.(
3108
+ "[AUTH] Users & Permissions auth controller not found; sign-in checks use paths only"
3109
+ );
3110
+ return [];
3111
+ }
3112
+ const wrapped = [];
3113
+ for (const [action, kind] of Object.entries(GUARDED_ACTIONS)) {
3114
+ const original = controller[action];
3115
+ if (typeof original !== "function") continue;
3116
+ if (original[WRAPPED]) {
3117
+ wrapped.push(action);
3118
+ continue;
3119
+ }
3120
+ const guarded = async function magicSessionAuthGuard(ctx, ...rest) {
3121
+ const run = () => original.call(this, ctx, ...rest);
3122
+ const handlers = handlersByStrapi.get(strapi2);
3123
+ if (!handlers || typeof handlers[kind] !== "function") return run();
3124
+ return handlers[kind](ctx, run);
3125
+ };
3126
+ Object.defineProperty(guarded, WRAPPED, { value: original });
3127
+ controller[action] = guarded;
3128
+ wrapped.push(action);
3129
+ }
3130
+ return wrapped;
3131
+ }
3132
+ function setAuthControllerHandlers(strapi2, handlers) {
3133
+ if (handlers) handlersByStrapi.set(strapi2, handlers);
3134
+ else handlersByStrapi.delete(strapi2);
3135
+ }
3136
+ function uninstallAuthControllerGuard(strapi2) {
3137
+ setAuthControllerHandlers(strapi2, null);
3138
+ let controller;
3139
+ try {
3140
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3141
+ } catch {
3142
+ return;
3143
+ }
3144
+ if (!controller) return;
3145
+ for (const action of Object.keys(GUARDED_ACTIONS)) {
3146
+ const original = controller[action]?.[WRAPPED];
3147
+ if (typeof original === "function") controller[action] = original;
3148
+ }
3149
+ }
3150
+ var INVALID_CREDENTIALS_MESSAGE = "Invalid identifier or password";
3151
+ function classifyCallbackOutcome(thrown, ctx) {
3152
+ if (thrown) {
3153
+ const error = (
3154
+ /** @type {any} */
3155
+ thrown
3156
+ );
3157
+ return error?.name === "ValidationError" && error?.message === INVALID_CREDENTIALS_MESSAGE ? "failure" : "neutral";
3158
+ }
3159
+ const body = ctx?.body;
3160
+ return body && typeof body === "object" && body.jwt ? "success" : "neutral";
3161
+ }
3162
+ module2.exports = {
3163
+ GUARDED_ACTIONS,
3164
+ INVALID_CREDENTIALS_MESSAGE,
3165
+ classifyCallbackOutcome,
3166
+ installAuthControllerGuard,
3167
+ setAuthControllerHandlers,
3168
+ uninstallAuthControllerGuard
3169
+ };
3170
+ }
3171
+ });
3172
+
3173
+ // server/src/register.js
2661
3174
  var require_register = __commonJS({
2662
3175
  "server/src/register.js"(exports2, module2) {
2663
3176
  "use strict";
@@ -2666,6 +3179,8 @@ var require_register = __commonJS({
2666
3179
  var { isCallerRevocationScope } = require_block_revocation_scope();
2667
3180
  var { checkStrapiVersion } = require_strapi_version();
2668
3181
  var { disableGraphqlShadowCrud } = require_security_log_hardening();
3182
+ var { installGraphqlImpersonationGuard } = require_graphql_impersonation_guard();
3183
+ var { installAuthControllerGuard } = require_auth_controller_guard();
2669
3184
  var USER_UID = "plugin::users-permissions.user";
2670
3185
  module2.exports = async ({ strapi: strapi2 }) => {
2671
3186
  const log = createLogger(strapi2);
@@ -2757,13 +3272,25 @@ var require_register = __commonJS({
2757
3272
  // their own.
2758
3273
  {
2759
3274
  section: "plugins",
2760
- displayName: "View as admin (read-only permission preview)",
3275
+ displayName: "View admin permissions (read-only preview)",
2761
3276
  uid: "impersonate.admins",
2762
3277
  subCategory: "Impersonation",
2763
3278
  pluginName: "magic-sessionmanager"
3279
+ },
3280
+ // "Sign in as this admin" (4.23): a real admin session of another admin
3281
+ // in a separate tab, read-only unless changes are allowed. The same
3282
+ // anti-escalation rules as the preview; only on tested Strapi releases.
3283
+ {
3284
+ section: "plugins",
3285
+ displayName: "Sign in as another admin",
3286
+ uid: "impersonate.admins.sign-in",
3287
+ subCategory: "Impersonation",
3288
+ pluginName: "magic-sessionmanager"
2764
3289
  }
2765
3290
  ]);
2766
3291
  disableGraphqlShadowCrud(strapi2, log);
3292
+ installGraphqlImpersonationGuard(strapi2, log);
3293
+ installAuthControllerGuard(strapi2, log);
2767
3294
  try {
2768
3295
  strapi2.db.lifecycles.subscribe(createContentApiPermissionsLifecycle(strapi2));
2769
3296
  } catch (err) {
@@ -2839,42 +3366,69 @@ var require_register = __commonJS({
2839
3366
  var require_getClientIp = __commonJS({
2840
3367
  "server/src/utils/getClientIp.js"(exports2, module2) {
2841
3368
  "use strict";
2842
- function isProxyTrusted(ctx) {
2843
- try {
2844
- const app = ctx?.app;
2845
- if (app && app.proxy === true) return true;
2846
- } catch {
3369
+ var net = require("node:net");
3370
+ var { isTrustedAddress } = require_policy_settings();
3371
+ var { normalizeTrustedProxies } = require_trusted_proxies();
3372
+ var MAX_FORWARDED_LENGTH = 2048;
3373
+ var MAX_FORWARDED_HOPS = 20;
3374
+ var cleanIp = (ip) => {
3375
+ if (!ip) return "unknown";
3376
+ let value = String(ip).trim();
3377
+ if (value.startsWith("[")) {
3378
+ const bracketEnd = value.indexOf("]");
3379
+ if (bracketEnd !== -1) {
3380
+ value = value.substring(1, bracketEnd);
3381
+ }
3382
+ }
3383
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.substring(7))) {
3384
+ value = value.substring(7);
2847
3385
  }
3386
+ if (value.includes(".") && value.includes(":") && value.indexOf(":") === value.lastIndexOf(":")) {
3387
+ value = value.split(":")[0];
3388
+ }
3389
+ return value || "unknown";
3390
+ };
3391
+ function trustedProxyList(ctx) {
3392
+ const fromSettings = ctx?.state?.__magicSessionSettings?.trustedProxies;
3393
+ if (fromSettings !== void 0) return normalizeTrustedProxies(fromSettings);
2848
3394
  try {
2849
- const config2 = ctx?.state?.__magicSessionSettings || ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager") || {};
2850
- const trusted = config2.trustedProxies;
2851
- if (trusted === true) return true;
2852
- if (Array.isArray(trusted) && trusted.length > 0) return true;
3395
+ const config2 = ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager");
3396
+ return normalizeTrustedProxies(config2?.trustedProxies);
2853
3397
  } catch {
3398
+ return [];
2854
3399
  }
2855
- return false;
3400
+ }
3401
+ function socketAddress(ctx) {
3402
+ const raw = ctx?.req?.socket?.remoteAddress ?? ctx?.request?.socket?.remoteAddress;
3403
+ const cleaned = cleanIp(raw);
3404
+ return cleaned !== "unknown" && net.isIP(cleaned) ? cleaned : null;
3405
+ }
3406
+ function rightMostUntrustedHop(ctx, proxies) {
3407
+ const headers = ctx?.request?.headers || ctx?.request?.header || {};
3408
+ let header = headers["x-forwarded-for"];
3409
+ if (Array.isArray(header)) header = header.join(",");
3410
+ if (typeof header !== "string" || !header) return null;
3411
+ const hops = header.slice(0, MAX_FORWARDED_LENGTH).split(",").map((hop) => cleanIp(hop)).slice(-MAX_FORWARDED_HOPS);
3412
+ let lastValid = null;
3413
+ for (let index = hops.length - 1; index >= 0; index--) {
3414
+ const hop = hops[index];
3415
+ if (!net.isIP(hop)) return lastValid;
3416
+ if (!isTrustedAddress(proxies, hop)) return hop;
3417
+ lastValid = hop;
3418
+ }
3419
+ return lastValid;
2856
3420
  }
2857
3421
  var getClientIp = (ctx) => {
2858
3422
  try {
2859
- const headers = ctx.request.headers || ctx.request.header || {};
2860
- const trusted = isProxyTrusted(ctx);
2861
- if (trusted) {
2862
- if (headers["cf-connecting-ip"]) return cleanIp(headers["cf-connecting-ip"]);
2863
- if (headers["true-client-ip"]) return cleanIp(headers["true-client-ip"]);
2864
- if (headers["x-real-ip"]) return cleanIp(headers["x-real-ip"]);
2865
- if (headers["x-forwarded-for"]) {
2866
- const forwardedIps = headers["x-forwarded-for"].split(",");
2867
- const clientIp = forwardedIps[0].trim();
2868
- if (clientIp) return cleanIp(clientIp);
2869
- }
2870
- if (headers["x-client-ip"]) return cleanIp(headers["x-client-ip"]);
2871
- if (headers["x-cluster-client-ip"]) return cleanIp(headers["x-cluster-client-ip"]);
2872
- if (headers["forwarded"]) {
2873
- const match = headers["forwarded"].match(/for=([^;,\s]+)/);
2874
- if (match && match[1]) return cleanIp(match[1].replace(/"/g, ""));
2875
- }
2876
- }
2877
- if (ctx.request.ip) return cleanIp(ctx.request.ip);
3423
+ const proxies = trustedProxyList(ctx);
3424
+ if (proxies.length > 0) {
3425
+ const peer = socketAddress(ctx);
3426
+ if (peer && isTrustedAddress(proxies, peer)) {
3427
+ return rightMostUntrustedHop(ctx, proxies) || peer;
3428
+ }
3429
+ if (peer) return peer;
3430
+ }
3431
+ if (ctx?.request?.ip) return cleanIp(ctx.request.ip);
2878
3432
  return "unknown";
2879
3433
  } catch (error) {
2880
3434
  if (ctx?.app?.context?.strapi?.log?.debug) {
@@ -2886,24 +3440,8 @@ var require_getClientIp = __commonJS({
2886
3440
  return "unknown";
2887
3441
  }
2888
3442
  };
2889
- var cleanIp = (ip) => {
2890
- if (!ip) return "unknown";
2891
- ip = String(ip).trim();
2892
- if (ip.startsWith("[")) {
2893
- const bracketEnd = ip.indexOf("]");
2894
- if (bracketEnd !== -1) {
2895
- ip = ip.substring(1, bracketEnd);
2896
- }
2897
- }
2898
- if (ip.startsWith("::ffff:")) {
2899
- ip = ip.substring(7);
2900
- }
2901
- if (ip.includes(".") && ip.includes(":") && ip.indexOf(":") === ip.lastIndexOf(":")) {
2902
- ip = ip.split(":")[0];
2903
- }
2904
- return ip || "unknown";
2905
- };
2906
3443
  module2.exports = getClientIp;
3444
+ module2.exports.cleanIp = cleanIp;
2907
3445
  }
2908
3446
  });
2909
3447
 
@@ -2916,10 +3454,22 @@ var require_encryption = __commonJS({
2916
3454
  var IV_LENGTH = 16;
2917
3455
  var AUTH_TAG_LENGTH = 16;
2918
3456
  var warnedMissingKey = false;
3457
+ var warnedShortKey = false;
3458
+ var MIN_KEY_BYTES = 32;
3459
+ function isEncryptionKeyShort() {
3460
+ const envKey = process.env.SESSION_ENCRYPTION_KEY;
3461
+ return typeof envKey === "string" && envKey.length > 0 ? Buffer.byteLength(envKey, "utf8") < MIN_KEY_BYTES : false;
3462
+ }
2919
3463
  var isProduction = () => process.env.NODE_ENV === "production";
2920
3464
  function getEncryptionKey() {
2921
3465
  const envKey = process.env.SESSION_ENCRYPTION_KEY;
2922
3466
  if (envKey && envKey.length > 0) {
3467
+ if (!warnedShortKey && isEncryptionKeyShort()) {
3468
+ warnedShortKey = true;
3469
+ console.warn(
3470
+ `[magic-sessionmanager] SESSION_ENCRYPTION_KEY is shorter than ${MIN_KEY_BYTES} bytes. It still works, but the next major version will refuse to start with it. Use 32 random bytes (64 hex characters).`
3471
+ );
3472
+ }
2923
3473
  return crypto.createHash("sha256").update(envKey).digest();
2924
3474
  }
2925
3475
  if (isProduction()) {
@@ -3003,6 +3553,8 @@ var require_encryption = __commonJS({
3003
3553
  );
3004
3554
  }
3005
3555
  module2.exports = {
3556
+ MIN_KEY_BYTES,
3557
+ isEncryptionKeyShort,
3006
3558
  derivePurposeKey,
3007
3559
  getEncryptionKeyCheck,
3008
3560
  encryptToken,
@@ -3552,7 +4104,6 @@ var require_auth_routes = __commonJS({
3552
4104
  "POST /api/magic-link/login-totp"
3553
4105
  ]);
3554
4106
  var FAILED_LOGIN_ROUTES = /* @__PURE__ */ new Set([
3555
- "POST /api/auth/local",
3556
4107
  "POST /api/magic-link/login-totp",
3557
4108
  "POST /api/magic-link/otp/verify",
3558
4109
  "POST /api/magic-link/verify-mfa-totp"
@@ -3595,18 +4146,24 @@ var require_auth_routes = __commonJS({
3595
4146
  if (!trimmed) return DEFAULT_API_PREFIX;
3596
4147
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
3597
4148
  }
4149
+ function normalizeRequestPath(path) {
4150
+ const value = path.toLowerCase().replace(/\/{2,}/g, "/");
4151
+ return value.length > 1 ? value.replace(/\/+$/, "") || "/" : value;
4152
+ }
3598
4153
  function toCanonicalApiPath(path, prefix) {
3599
4154
  if (typeof path !== "string") return null;
3600
- const normalized = normalizeApiPrefix(prefix);
3601
- if (normalized === DEFAULT_API_PREFIX) return path;
3602
- if (path === normalized) return DEFAULT_API_PREFIX;
3603
- if (path.startsWith(`${normalized}/`)) {
3604
- return `${DEFAULT_API_PREFIX}${path.slice(normalized.length)}`;
4155
+ const normalizedPath = normalizeRequestPath(path);
4156
+ const normalized = normalizeApiPrefix(prefix).toLowerCase();
4157
+ if (normalized === DEFAULT_API_PREFIX) return normalizedPath;
4158
+ if (normalizedPath === normalized) return DEFAULT_API_PREFIX;
4159
+ if (normalizedPath.startsWith(`${normalized}/`)) {
4160
+ return `${DEFAULT_API_PREFIX}${normalizedPath.slice(normalized.length)}`;
3605
4161
  }
3606
4162
  return null;
3607
4163
  }
3608
4164
  module2.exports = {
3609
4165
  normalizeApiPrefix,
4166
+ normalizeRequestPath,
3610
4167
  toCanonicalApiPath,
3611
4168
  classifyJwtIssuingRequest,
3612
4169
  isFailedLoginTrackedPath,
@@ -4266,6 +4823,15 @@ var require_admin_request_info = __commonJS({
4266
4823
  }
4267
4824
  return null;
4268
4825
  }
4826
+ function ipBucket(ip) {
4827
+ const value = normalizeIp(typeof ip === "string" ? ip : "");
4828
+ if (!value) return null;
4829
+ if (net.isIPv4(value)) return value;
4830
+ if (net.isIPv6(value)) {
4831
+ return `${ipv6Groups(value).slice(0, 4).map((group) => group.toString(16)).join(":")}::/64`;
4832
+ }
4833
+ return null;
4834
+ }
4269
4835
  function getRequestUserAgent(ctx) {
4270
4836
  const value = ctx?.request?.headers?.["user-agent"];
4271
4837
  if (typeof value !== "string" || !value.trim()) return null;
@@ -4292,6 +4858,7 @@ var require_admin_request_info = __commonJS({
4292
4858
  module2.exports = {
4293
4859
  MAX_USER_AGENT_LENGTH,
4294
4860
  anonymizeIp,
4861
+ ipBucket,
4295
4862
  describeUserAgent,
4296
4863
  getRequestIp,
4297
4864
  getSocketIp,
@@ -4592,6 +5159,7 @@ var require_login_lockout = __commonJS({
4592
5159
  "use strict";
4593
5160
  var { hashedKey } = require_coordination();
4594
5161
  var { isTrustedAddress } = require_policy_settings();
5162
+ var { ipBucket } = require_admin_request_info();
4595
5163
  var LOCK_PREFIX = "lock:";
4596
5164
  var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
4597
5165
  var MAX_LISTED_LOCKS = 200;
@@ -4601,7 +5169,7 @@ var require_login_lockout = __commonJS({
4601
5169
  if (!value || value.length > 254) return null;
4602
5170
  return value;
4603
5171
  }
4604
- var ipKey = (ip) => hashedKey("lf", ip);
5172
+ var ipKey = (ip) => hashedKey("lf", ipBucket(ip) || ip);
4605
5173
  var accountKey = (identifier) => hashedKey("la", identifier);
4606
5174
  function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
4607
5175
  const remainingSeconds = async (key) => {
@@ -4621,15 +5189,18 @@ var require_login_lockout = __commonJS({
4621
5189
  * Checks the locks and counts the attempt before the password check.
4622
5190
  *
4623
5191
  * @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
4624
- * accountMax: number}} input Client IP, normalised identifier, policy and the
4625
- * account threshold for this account's role.
5192
+ * accountMax: number, accountExempt?: boolean}} input Client IP, normalised
5193
+ * identifier, policy, the account threshold for this account's role, and
5194
+ * whether the request comes from a device the account is known to use.
4626
5195
  * @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
4627
5196
  * lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
4628
5197
  * @sideeffect Increments the shared counters.
4629
5198
  */
4630
- async reserve({ ip, identifier, policy, accountMax }) {
4631
- const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
4632
- const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
5199
+ async reserve({ ip, identifier, policy, accountMax, accountExempt = false }) {
5200
+ const knownIp = typeof ip === "string" && !!ip && ip !== "unknown";
5201
+ const trusted = knownIp && isTrustedAddress(policy.trusted, ip);
5202
+ const countIp = policy.ipMax > 0 && knownIp && !trusted;
5203
+ const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier && !trusted && accountExempt !== true;
4633
5204
  const reservation = {
4634
5205
  ipKey: countIp ? ipKey(
4635
5206
  /** @type {string} */
@@ -4682,10 +5253,8 @@ var require_login_lockout = __commonJS({
4682
5253
  */
4683
5254
  async settle(reservation, result, { policy, accountMax, display = {} }) {
4684
5255
  if (result === "success") {
4685
- for (const key of [reservation.ipKey, reservation.accountKey]) {
4686
- if (!key) continue;
4687
- await coordinator.clear(key);
4688
- }
5256
+ if (reservation.ipKey) await coordinator.release(reservation.ipKey);
5257
+ if (reservation.accountKey) await coordinator.clear(reservation.accountKey);
4689
5258
  return [];
4690
5259
  }
4691
5260
  if (result !== "failure") {
@@ -5149,6 +5718,15 @@ var require_sign_in_signals = __commonJS({
5149
5718
  });
5150
5719
  return Array.isArray(rows) ? rows : [];
5151
5720
  }
5721
+ async function isRecognizedDevice(strapi2, userDocumentId, { userAgent, deviceId }) {
5722
+ if (typeof userDocumentId !== "string" || !userDocumentId) return false;
5723
+ if (typeof deviceId !== "string" || !deviceId) return false;
5724
+ const deviceKey = deviceKeyOf(userAgent || "", deviceId);
5725
+ const count = await strapi2.documents(SESSION_UID).count({
5726
+ filters: { user: { documentId: userDocumentId }, deviceKey }
5727
+ });
5728
+ return Number(count) > 0;
5729
+ }
5152
5730
  function isNewDevice(previous, { deviceKey, userAgent }) {
5153
5731
  if (previous.length === 0) return false;
5154
5732
  if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
@@ -5177,7 +5755,7 @@ var require_sign_in_signals = __commonJS({
5177
5755
  const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
5178
5756
  if (!token) return null;
5179
5757
  const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
5180
- return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
5758
+ return `${base}${prefix}/magic-sessionmanager/not-me#token=${encodeURIComponent(token)}`;
5181
5759
  }
5182
5760
  async function runSignInSignals({
5183
5761
  strapi: strapi2,
@@ -5266,6 +5844,7 @@ var require_sign_in_signals = __commonJS({
5266
5844
  return outcome;
5267
5845
  }
5268
5846
  module2.exports = {
5847
+ isRecognizedDevice,
5269
5848
  notMeUrl,
5270
5849
  runSignInSignals,
5271
5850
  deviceFamilies,
@@ -5370,7 +5949,11 @@ var require_impersonation_guard = __commonJS({
5370
5949
  `impersonation-${restricted}`
5371
5950
  );
5372
5951
  }
5373
- ctx.state.magicImpersonation = { id: impersonation.id, actorId: impersonation.actorId };
5952
+ ctx.state.magicImpersonation = {
5953
+ id: impersonation.id,
5954
+ actorId: impersonation.actorId,
5955
+ targetId: impersonation.targetId || null
5956
+ };
5374
5957
  try {
5375
5958
  await next();
5376
5959
  } finally {
@@ -5381,6 +5964,237 @@ var require_impersonation_guard = __commonJS({
5381
5964
  }
5382
5965
  });
5383
5966
 
5967
+ // server/src/utils/admin-sign-in-rules.js
5968
+ var require_admin_sign_in_rules = __commonJS({
5969
+ "server/src/utils/admin-sign-in-rules.js"(exports2, module2) {
5970
+ "use strict";
5971
+ var { REASON_MAX, REASON_MIN, cleanReason, normalizePath } = require_impersonation_rules();
5972
+ var ADMIN_SIGN_IN_ACTION = "plugin::magic-sessionmanager.impersonate.admins.sign-in";
5973
+ var TESTED_STRAPI = Object.freeze({ major: 5, minMinor: 50, maxMinor: 64 });
5974
+ var ADMIN_SIGN_IN_DURATIONS = Object.freeze([15, 30]);
5975
+ var ADMIN_DEVICE_PREFIX = "msm-admin-impersonation-";
5976
+ var LANDING_PATH = "/plugins/magic-sessionmanager/impersonate/land";
5977
+ function adminSignInSupport(version) {
5978
+ const match = typeof version === "string" ? /^(\d+)\.(\d+)\.(\d+)/.exec(version.trim()) : null;
5979
+ if (!match) return { supported: false, version: null, reason: "unknown-version" };
5980
+ const [major, minor] = [Number(match[1]), Number(match[2])];
5981
+ const clean = `${match[1]}.${match[2]}.${match[3]}`;
5982
+ const supported = major === TESTED_STRAPI.major && minor >= TESTED_STRAPI.minMinor && minor <= TESTED_STRAPI.maxMinor;
5983
+ return { supported, version: clean, reason: supported ? null : "untested-version" };
5984
+ }
5985
+ function allowedSignInDurations(accessTokenLifespanSeconds) {
5986
+ const seconds = Number(accessTokenLifespanSeconds);
5987
+ const lifespan = Number.isFinite(seconds) && seconds > 0 ? seconds : 30 * 60;
5988
+ return ADMIN_SIGN_IN_DURATIONS.filter((minutes) => minutes * 60 <= lifespan);
5989
+ }
5990
+ function validateSignInBody(body, durations) {
5991
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
5992
+ return { value: null, errors: [{ path: [], message: "Body must be an object" }] };
5993
+ }
5994
+ const errors = [];
5995
+ const source = (
5996
+ /** @type {Record<string, unknown>} */
5997
+ body
5998
+ );
5999
+ for (const key of Object.keys(source)) {
6000
+ if (!["reason", "durationMinutes", "allowChanges"].includes(key)) {
6001
+ errors.push({ path: [key], message: "Unknown field" });
6002
+ }
6003
+ }
6004
+ const reason = cleanReason(source.reason);
6005
+ if (reason === null) {
6006
+ errors.push({
6007
+ path: ["reason"],
6008
+ message: `reason must be ${REASON_MIN} to ${REASON_MAX} characters`
6009
+ });
6010
+ }
6011
+ const duration = source.durationMinutes;
6012
+ if (typeof duration !== "number" || !durations.includes(duration)) {
6013
+ errors.push({
6014
+ path: ["durationMinutes"],
6015
+ message: `durationMinutes must be one of: ${durations.join(", ")}`
6016
+ });
6017
+ }
6018
+ if (source.allowChanges !== void 0 && typeof source.allowChanges !== "boolean") {
6019
+ errors.push({ path: ["allowChanges"], message: "allowChanges must be a boolean" });
6020
+ }
6021
+ if (errors.length) return { value: null, errors };
6022
+ return {
6023
+ value: {
6024
+ reason: (
6025
+ /** @type {string} */
6026
+ reason
6027
+ ),
6028
+ durationMinutes: (
6029
+ /** @type {number} */
6030
+ duration
6031
+ ),
6032
+ allowChanges: source.allowChanges === true
6033
+ },
6034
+ errors
6035
+ };
6036
+ }
6037
+ var SAFE_METHODS = Object.freeze(["GET", "HEAD", "OPTIONS"]);
6038
+ var READ_ONLY_POSTS = Object.freeze(["/admin/permissions/check"]);
6039
+ var IDENTITY_PREFIXES = Object.freeze([
6040
+ "/admin/users",
6041
+ "/admin/roles",
6042
+ "/admin/api-tokens",
6043
+ "/admin/transfer",
6044
+ "/admin/providers",
6045
+ "/admin/register",
6046
+ "/admin/register-admin",
6047
+ "/admin/registration-info",
6048
+ "/admin/forgot-password",
6049
+ "/admin/reset-password",
6050
+ "/admin/renew-token",
6051
+ "/admin/login",
6052
+ "/admin/sessions",
6053
+ "/magic-sessionmanager"
6054
+ ]);
6055
+ var SELF_PATHS = Object.freeze({
6056
+ state: "/magic-sessionmanager/admin-impersonation/self",
6057
+ end: "/magic-sessionmanager/admin-impersonation/self/end"
6058
+ });
6059
+ function under(path, prefix) {
6060
+ return path === prefix || path.startsWith(`${prefix}/`);
6061
+ }
6062
+ function classifyAdminImpersonationRequest(method, rawPath) {
6063
+ const verb = String(method || "").toUpperCase();
6064
+ const path = normalizePath(rawPath);
6065
+ if (path === SELF_PATHS.state || path === SELF_PATHS.end) return "self";
6066
+ if (verb === "POST" && path === "/admin/logout") return "logout";
6067
+ if (SAFE_METHODS.includes(verb)) return "read";
6068
+ if (verb === "POST" && READ_ONLY_POSTS.includes(path)) return "read";
6069
+ if (IDENTITY_PREFIXES.some((prefix) => under(path, prefix))) return "identity";
6070
+ return "write";
6071
+ }
6072
+ function recordedPath(rawPath) {
6073
+ return String(rawPath || "").split("?")[0].slice(0, 200);
6074
+ }
6075
+ module2.exports = {
6076
+ ADMIN_DEVICE_PREFIX,
6077
+ ADMIN_SIGN_IN_ACTION,
6078
+ ADMIN_SIGN_IN_DURATIONS,
6079
+ IDENTITY_PREFIXES,
6080
+ LANDING_PATH,
6081
+ READ_ONLY_POSTS,
6082
+ SELF_PATHS,
6083
+ TESTED_STRAPI,
6084
+ adminSignInSupport,
6085
+ allowedSignInDurations,
6086
+ classifyAdminImpersonationRequest,
6087
+ recordedPath,
6088
+ validateSignInBody
6089
+ };
6090
+ }
6091
+ });
6092
+
6093
+ // server/src/middlewares/admin-impersonation-guard.js
6094
+ var require_admin_impersonation_guard = __commonJS({
6095
+ "server/src/middlewares/admin-impersonation-guard.js"(exports2, module2) {
6096
+ "use strict";
6097
+ var { extractBearerToken } = require_extract_token();
6098
+ var { IMPERSONATION_HEADER, normalizePath } = require_impersonation_rules();
6099
+ var { classifyAdminImpersonationRequest, recordedPath } = require_admin_sign_in_rules();
6100
+ function reply(ctx, status, name, message, reason) {
6101
+ ctx.status = status;
6102
+ ctx.body = { data: null, error: { status, name, message, details: { reason } } };
6103
+ }
6104
+ module2.exports = (_config, { strapi: strapi2 }) => {
6105
+ const service = () => strapi2.plugin("magic-sessionmanager").service("impersonation");
6106
+ return async function adminImpersonationGuard(ctx, next) {
6107
+ const prefix = normalizePath(strapi2.config.get("api.rest.prefix", "/api") || "/api");
6108
+ const path = normalizePath(ctx.path);
6109
+ const base = prefix === "/" ? "" : prefix;
6110
+ if (base && (path === base || path.startsWith(`${base}/`))) return next();
6111
+ const bearer = extractBearerToken(ctx);
6112
+ if (!bearer) return next();
6113
+ let impersonationId;
6114
+ let impersonation;
6115
+ try {
6116
+ impersonationId = await service().adminImpersonationOfToken(bearer);
6117
+ if (!impersonationId) return next();
6118
+ impersonation = impersonationId === "unknown" ? null : await service().loadAdminForGuard(impersonationId);
6119
+ } catch {
6120
+ return reply(
6121
+ ctx,
6122
+ 503,
6123
+ "ServiceUnavailableError",
6124
+ "Session check unavailable",
6125
+ "impersonation-check"
6126
+ );
6127
+ }
6128
+ ctx.set(IMPERSONATION_HEADER, "true");
6129
+ const kind = classifyAdminImpersonationRequest(ctx.method, path);
6130
+ if (!impersonation || impersonation.state !== "active") {
6131
+ if (kind === "logout") {
6132
+ ctx.body = { data: {} };
6133
+ return void 0;
6134
+ }
6135
+ return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-ended");
6136
+ }
6137
+ if (Date.now() >= impersonation.expiresAt) {
6138
+ try {
6139
+ await service().end(impersonation.id, { reason: "expired" });
6140
+ } catch {
6141
+ }
6142
+ if (kind === "logout") {
6143
+ ctx.body = { data: {} };
6144
+ return void 0;
6145
+ }
6146
+ return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-expired");
6147
+ }
6148
+ if (kind === "logout") {
6149
+ await service().end(impersonation.id, { reason: "ended", endedBy: impersonation.actorId });
6150
+ ctx.body = { data: {} };
6151
+ return void 0;
6152
+ }
6153
+ const method = String(ctx.method).toUpperCase();
6154
+ const recorded = recordedPath(ctx.path);
6155
+ if (kind === "identity" || kind === "write" && !impersonation.allowChanges) {
6156
+ const reason = kind === "identity" ? "identity" : "read-only";
6157
+ service().recordRefusedAdminCall(impersonation, reason, { method, path: recorded });
6158
+ return reply(
6159
+ ctx,
6160
+ 403,
6161
+ "ForbiddenError",
6162
+ kind === "identity" ? "Not allowed while signed in as another admin" : "Read-only: changes were not allowed for this sign-in",
6163
+ `impersonation-${reason}`
6164
+ );
6165
+ }
6166
+ ctx.state.magicAdminImpersonation = {
6167
+ id: impersonation.id,
6168
+ actorId: impersonation.actorId,
6169
+ targetId: impersonation.targetId,
6170
+ allowChanges: impersonation.allowChanges,
6171
+ expiresAt: impersonation.expiresAt
6172
+ };
6173
+ let failedStatus = 0;
6174
+ try {
6175
+ await next();
6176
+ } catch (err) {
6177
+ failedStatus = Number(
6178
+ /** @type {any} */
6179
+ err?.status
6180
+ ) || 500;
6181
+ throw err;
6182
+ } finally {
6183
+ ctx.set(IMPERSONATION_HEADER, "true");
6184
+ if (kind === "write") {
6185
+ service().recordAdminWrite(impersonation, {
6186
+ method,
6187
+ path: recorded,
6188
+ status: failedStatus || Number(ctx.status) || 0
6189
+ });
6190
+ }
6191
+ }
6192
+ return void 0;
6193
+ };
6194
+ };
6195
+ }
6196
+ });
6197
+
5384
6198
  // server/src/middlewares/session-rejection-headers.js
5385
6199
  var require_session_rejection_headers = __commonJS({
5386
6200
  "server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
@@ -9464,7 +10278,13 @@ var require_bootstrap = __commonJS({
9464
10278
  "server/src/bootstrap.js"(exports2, module2) {
9465
10279
  "use strict";
9466
10280
  var getClientIp = require_getClientIp();
9467
- var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
10281
+ var {
10282
+ MIN_KEY_BYTES,
10283
+ encryptToken,
10284
+ getEncryptionKeyCheck,
10285
+ hashToken,
10286
+ isEncryptionKeyShort
10287
+ } = require_encryption();
9468
10288
  var { createLogger } = require_logger();
9469
10289
  var { resolveUserDocumentId } = require_resolve_user();
9470
10290
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -9475,7 +10295,12 @@ var require_bootstrap = __commonJS({
9475
10295
  var { REVOCATION_UID } = require_session_revocation();
9476
10296
  var { getNativeSessionManager } = require_native_session_manager();
9477
10297
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
9478
- var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
10298
+ var {
10299
+ getCoordinator,
10300
+ hashedKey,
10301
+ initCoordination,
10302
+ LockTimeoutError
10303
+ } = require_coordination();
9479
10304
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
9480
10305
  var {
9481
10306
  normalizeApiPrefix,
@@ -9524,8 +10349,20 @@ var require_bootstrap = __commonJS({
9524
10349
  } = require_sign_in_policies();
9525
10350
  var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
9526
10351
  var { applyUpgradeDefaults } = require_upgrade_defaults();
9527
- var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
10352
+ var {
10353
+ deviceKeyOf,
10354
+ isRecognizedDevice,
10355
+ requestDeviceId,
10356
+ runSignInSignals
10357
+ } = require_sign_in_signals();
9528
10358
  var { anonymizeIp, normalizeIp } = require_admin_request_info();
10359
+ var { migrateLegacyProxyTrust } = require_trusted_proxies();
10360
+ var { errors: utilsErrors } = require("@strapi/utils");
10361
+ var {
10362
+ classifyCallbackOutcome,
10363
+ setAuthControllerHandlers
10364
+ } = require_auth_controller_guard();
10365
+ var { normalizePath } = require_impersonation_rules();
9529
10366
  var SESSION_UID = "plugin::magic-sessionmanager.session";
9530
10367
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
9531
10368
  var JOB_LEASES = Object.freeze({
@@ -9568,6 +10405,12 @@ var require_bootstrap = __commonJS({
9568
10405
  try {
9569
10406
  const coordinator = await initCoordination(strapi2, log);
9570
10407
  await checkEncryptionKeyConsistency(strapi2, log);
10408
+ await warnShortEncryptionKey(strapi2, log);
10409
+ try {
10410
+ await migrateLegacyProxyTrust(strapi2, log);
10411
+ } catch (err) {
10412
+ log.warn("[CONFIG] trustedProxies could not be migrated:", err?.name || "Error");
10413
+ }
9571
10414
  try {
9572
10415
  await applyUpgradeDefaults(strapi2, log);
9573
10416
  } catch (err) {
@@ -9675,14 +10518,16 @@ var require_bootstrap = __commonJS({
9675
10518
  );
9676
10519
  log.info("[TIME] Dynamic cleanup + retention scheduled");
9677
10520
  strapi2.server.use(require_impersonation_guard()({}, { strapi: strapi2 }));
10521
+ strapi2.server.use(require_admin_impersonation_guard()({}, { strapi: strapi2 }));
9678
10522
  const impersonationSweep = setInterval(() => {
9679
10523
  strapi2.plugin("magic-sessionmanager").service("impersonation").sweep().catch((err) => log.warn("[IMPERSONATION] Sweep failed:", err?.name || "Error"));
9680
10524
  }, 30 * 1e3);
9681
10525
  impersonationSweep.unref?.();
9682
10526
  strapi2.sessionManagerIntervals.impersonationSweep = impersonationSweep;
9683
10527
  strapi2.plugin("magic-sessionmanager").service("impersonation").checkHandoffSetup();
9684
- mountPreLoginGeoGuard({ strapi: strapi2, log });
9685
- mountFailedLoginLockout({ strapi: strapi2, log });
10528
+ const geoCheck = mountPreLoginGeoGuard({ strapi: strapi2, log });
10529
+ const lockoutGuard = mountFailedLoginLockout({ strapi: strapi2, log });
10530
+ connectAuthControllerGuard({ strapi: strapi2, geoCheck, lockoutGuard });
9686
10531
  mountLogoutRoute({ strapi: strapi2, log, sessionService });
9687
10532
  mountLoginInterceptor({ strapi: strapi2, log, sessionService });
9688
10533
  mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
@@ -9740,6 +10585,28 @@ var require_bootstrap = __commonJS({
9740
10585
  log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
9741
10586
  }
9742
10587
  }
10588
+ async function warnShortEncryptionKey(strapi2, log) {
10589
+ if (!isEncryptionKeyShort()) return false;
10590
+ log.error(
10591
+ `[SECURITY] SESSION_ENCRYPTION_KEY is shorter than ${MIN_KEY_BYTES} bytes, so stored tokens and secrets are only as safe as that short key. It still works in this version; the next major version will refuse to start with it. Generate a new key with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" (changing it signs users out and needs the webhook secret entered again).`
10592
+ );
10593
+ try {
10594
+ const coordinator = getCoordinator(strapi2);
10595
+ const check = getEncryptionKeyCheck();
10596
+ const marker = "instance:weak-encryption-key-recorded";
10597
+ if (await coordinator.cacheGet(marker) === check) return true;
10598
+ const recorded = strapi2.plugin("magic-sessionmanager").service("security-log").record({
10599
+ event: SECURITY_EVENTS.CONFIG_WEAK_KEY,
10600
+ actorType: "system",
10601
+ targetType: "config",
10602
+ meta: { minBytes: MIN_KEY_BYTES }
10603
+ });
10604
+ if (recorded !== false) await coordinator.cacheSet(marker, check, Infinity);
10605
+ } catch (err) {
10606
+ log.debug("[SECURITY] Weak key event not recorded:", err?.name || "Error");
10607
+ }
10608
+ return true;
10609
+ }
9743
10610
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
9744
10611
  const shouldRecordRefusal = createRefusalDedup();
9745
10612
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
@@ -9762,19 +10629,14 @@ var require_bootstrap = __commonJS({
9762
10629
  meta: { reason }
9763
10630
  });
9764
10631
  };
9765
- strapi2.server.use(async (ctx, next) => {
9766
- if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
9767
- return next();
9768
- }
10632
+ const check = async (ctx) => {
10633
+ if (ctx.state?.__magicSessionGeoChecked) return null;
10634
+ if (ctx.state) ctx.state.__magicSessionGeoChecked = true;
9769
10635
  const settings = await getRequestSettings(strapi2, ctx);
9770
10636
  const needsGeoCheck = settings.blockSuspiciousSessions || settings.enableGeofencing || settings.enableGeolocation;
9771
- if (!needsGeoCheck) {
9772
- return next();
9773
- }
10637
+ if (!needsGeoCheck) return null;
9774
10638
  const ip = getClientIp(ctx);
9775
- if (!ip || ip === "unknown") {
9776
- return next();
9777
- }
10639
+ if (!ip || ip === "unknown") return null;
9778
10640
  try {
9779
10641
  const geolocationService = strapi2.plugin("magic-sessionmanager").service("geolocation");
9780
10642
  const geoData = await geolocationService.getIpInfo(ip);
@@ -9782,16 +10644,11 @@ var require_bootstrap = __commonJS({
9782
10644
  if (decision.blocked) {
9783
10645
  log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
9784
10646
  await recordRefusal(ctx, settings, ip, decision.reason);
9785
- ctx.status = 403;
9786
- ctx.body = {
9787
- error: {
9788
- status: 403,
9789
- name: "ForbiddenError",
9790
- message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
9791
- }
9792
- };
9793
10647
  ctx.state.__magicSessionGeoData = geoData;
9794
- return;
10648
+ return {
10649
+ status: 403,
10650
+ message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
10651
+ };
9795
10652
  }
9796
10653
  if (decision.status === "ok") {
9797
10654
  ctx.state.__magicSessionGeoData = geoData;
@@ -9801,21 +10658,31 @@ var require_bootstrap = __commonJS({
9801
10658
  if (failureDecision.blocked) {
9802
10659
  log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
9803
10660
  await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
9804
- ctx.status = 403;
9805
- ctx.body = {
9806
- error: {
9807
- status: 403,
9808
- name: "ForbiddenError",
9809
- message: "Login temporarily unavailable. Please contact support."
9810
- }
10661
+ return {
10662
+ status: 403,
10663
+ message: "Login temporarily unavailable. Please contact support."
9811
10664
  };
9812
- return;
9813
10665
  }
9814
10666
  log.debug("Pre-login geo guard error (allowing by configured policy):", err?.name || "Error");
9815
10667
  }
10668
+ return null;
10669
+ };
10670
+ strapi2.server.use(async (ctx, next) => {
10671
+ if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
10672
+ return next();
10673
+ }
10674
+ const refusal = await check(ctx);
10675
+ if (refusal) {
10676
+ ctx.status = refusal.status;
10677
+ ctx.body = {
10678
+ error: { status: refusal.status, name: "ForbiddenError", message: refusal.message }
10679
+ };
10680
+ return;
10681
+ }
9816
10682
  await next();
9817
10683
  });
9818
10684
  log.info("[SUCCESS] Pre-login geo guard mounted");
10685
+ return check;
9819
10686
  }
9820
10687
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
9821
10688
  const logoutPath = `${normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"))}/auth/logout`;
@@ -10001,16 +10868,16 @@ var require_bootstrap = __commonJS({
10001
10868
  }
10002
10869
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
10003
10870
  const lockout = createLoginLockout(getCoordinator(strapi2));
10871
+ const coordinator = getCoordinator(strapi2);
10004
10872
  const shouldRecordRefusal = createRefusalDedup();
10005
10873
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
10006
10874
  const underAddressCap = createAddressCap();
10007
10875
  const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
10008
- strapi2.server.use(async (ctx, next) => {
10009
- if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
10876
+ const guard = async (ctx, run, classify, refuse) => {
10010
10877
  const settings = await getRequestSettings(strapi2, ctx);
10011
10878
  const policy = resolveLockoutPolicy(settings);
10012
10879
  const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
10013
- if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
10880
+ if (policy.ipMax <= 0 && !accountPossible && !policy.record) return run();
10014
10881
  const rawIp = getClientIp(ctx);
10015
10882
  const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
10016
10883
  const identifier = readSignInIdentifier(ctx);
@@ -10031,6 +10898,15 @@ var require_bootstrap = __commonJS({
10031
10898
  };
10032
10899
  if (policy.accountMaxByRole) await loadAccount();
10033
10900
  const accountMax = accountThresholdFor(settings, account?.role || null);
10901
+ let accountExempt = false;
10902
+ const deviceId = requestDeviceId(ctx);
10903
+ if (accountMax > 0 && identifier && deviceId) {
10904
+ await loadAccount();
10905
+ accountExempt = await isRecognizedDevice(strapi2, account?.documentId || null, {
10906
+ userAgent,
10907
+ deviceId
10908
+ }).catch(() => false);
10909
+ }
10034
10910
  const event = (name, meta) => {
10035
10911
  const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
10036
10912
  if (signInFamily && !policy.record) return false;
@@ -10058,7 +10934,7 @@ var require_bootstrap = __commonJS({
10058
10934
  };
10059
10935
  let decision;
10060
10936
  try {
10061
- decision = await lockout.reserve({ ip, identifier, policy, accountMax });
10937
+ decision = await lockout.reserve({ ip, identifier, policy, accountMax, accountExempt });
10062
10938
  } catch (err) {
10063
10939
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10064
10940
  decision = {
@@ -10069,47 +10945,38 @@ var require_bootstrap = __commonJS({
10069
10945
  };
10070
10946
  }
10071
10947
  if (decision.outcome === "locked") {
10072
- ctx.set("Retry-After", String(decision.retryAfter));
10073
10948
  log.warn(
10074
10949
  `[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
10075
10950
  );
10076
10951
  if (policy.record) await loadAccount();
10077
10952
  refusedOnce("lockout", { lock: decision.lockedKind });
10078
- ctx.status = 429;
10079
- ctx.body = {
10080
- error: {
10081
- status: 429,
10082
- name: "TooManyRequestsError",
10083
- message: "Too many failed login attempts. Please try again later.",
10084
- details: { retryAfter: decision.retryAfter }
10085
- }
10086
- };
10087
- return;
10953
+ return refuse(ctx, {
10954
+ status: 429,
10955
+ name: "TooManyRequestsError",
10956
+ message: "Too many failed login attempts. Please try again later.",
10957
+ retryAfter: decision.retryAfter
10958
+ });
10088
10959
  }
10089
10960
  if (decision.outcome === "busy") {
10090
10961
  if (policy.record) await loadAccount();
10091
10962
  refusedOnce("too-many-attempts", {});
10092
- ctx.set("Retry-After", "1");
10093
- ctx.status = 429;
10094
- ctx.body = {
10095
- error: {
10096
- status: 429,
10097
- name: "TooManyRequestsError",
10098
- message: "Too many login attempts at once. Please try again.",
10099
- details: { retryAfter: 1 }
10100
- }
10101
- };
10102
- return;
10963
+ return refuse(ctx, {
10964
+ status: 429,
10965
+ name: "TooManyRequestsError",
10966
+ message: "Too many login attempts at once. Please try again.",
10967
+ retryAfter: 1
10968
+ });
10103
10969
  }
10104
10970
  let thrown = null;
10971
+ let returned;
10105
10972
  try {
10106
- await next();
10973
+ returned = await run();
10107
10974
  } catch (err) {
10108
10975
  thrown = err;
10109
10976
  }
10110
- const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10111
- const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
10977
+ const result = classify(thrown, ctx);
10112
10978
  if (result === "failure") {
10979
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10113
10980
  if (policy.record || decision.reservation.accountKey) await loadAccount();
10114
10981
  if (account) {
10115
10982
  event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
@@ -10137,21 +11004,93 @@ var require_bootstrap = __commonJS({
10137
11004
  minutes
10138
11005
  });
10139
11006
  if (lock.kind === "account" && policy.notifyUser && account?.email) {
10140
- const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
10141
- notifications.sendAccountLockedEmail({
10142
- user: account,
10143
- minutes,
10144
- until: lock.until
10145
- }).catch(() => {
10146
- });
11007
+ const mailWindowMs = Math.max(policy.windowMs, policy.durationMs);
11008
+ const sent = await coordinator.hit(hashedKey("lm", lock.id), mailWindowMs).then((entry) => Number(entry?.hits) || 0).catch(() => 1);
11009
+ if (sent === 1) {
11010
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
11011
+ notifications.sendAccountLockedEmail({
11012
+ user: account,
11013
+ minutes,
11014
+ until: lock.until
11015
+ }).catch(() => {
11016
+ });
11017
+ }
10147
11018
  }
10148
11019
  }
10149
11020
  } catch (err) {
10150
11021
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10151
11022
  }
10152
11023
  if (thrown) throw thrown;
11024
+ return returned;
11025
+ };
11026
+ strapi2.server.use(async (ctx, next) => {
11027
+ if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
11028
+ return guard(ctx, next, classifyRouteOutcome, refuseOverHttp);
10153
11029
  });
10154
11030
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
11031
+ return guard;
11032
+ }
11033
+ function classifyRouteOutcome(thrown, ctx) {
11034
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
11035
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) return "success";
11036
+ return status === 400 || status === 401 ? "failure" : "neutral";
11037
+ }
11038
+ function refuseOverHttp(ctx, refusal) {
11039
+ ctx.set("Retry-After", String(refusal.retryAfter));
11040
+ ctx.status = refusal.status;
11041
+ ctx.body = {
11042
+ error: {
11043
+ status: refusal.status,
11044
+ name: refusal.name,
11045
+ message: refusal.message,
11046
+ details: { retryAfter: refusal.retryAfter }
11047
+ }
11048
+ };
11049
+ }
11050
+ function isGraphqlRequest(strapi2, ctx) {
11051
+ let endpoint = "/graphql";
11052
+ try {
11053
+ endpoint = strapi2.plugin("graphql")?.config?.("endpoint") || endpoint;
11054
+ } catch {
11055
+ }
11056
+ const original = String(ctx.originalUrl || ctx.url || "").split("?")[0];
11057
+ return normalizePath(original) === normalizePath(endpoint);
11058
+ }
11059
+ function createAuthControllerHandlers({ strapi: strapi2, geoCheck, lockoutGuard }) {
11060
+ const refuse = (ctx, refusal) => {
11061
+ if (refusal.retryAfter) ctx.set("Retry-After", String(refusal.retryAfter));
11062
+ if (isGraphqlRequest(strapi2, ctx)) {
11063
+ const details = refusal.retryAfter ? { retryAfter: refusal.retryAfter } : {};
11064
+ throw refusal.status === 429 ? new utilsErrors.RateLimitError(refusal.message, details) : new utilsErrors.ForbiddenError(refusal.message, details);
11065
+ }
11066
+ if (refusal.status === 429) return refuseOverHttp(ctx, refusal);
11067
+ ctx.status = refusal.status;
11068
+ ctx.body = {
11069
+ error: { status: refusal.status, name: refusal.name, message: refusal.message }
11070
+ };
11071
+ return void 0;
11072
+ };
11073
+ const geoFirst = async (ctx) => {
11074
+ const refusal = await geoCheck(ctx);
11075
+ if (!refusal) return false;
11076
+ refuse(ctx, { ...refusal, name: "ForbiddenError", retryAfter: 0 });
11077
+ return true;
11078
+ };
11079
+ return {
11080
+ async callback(ctx, run) {
11081
+ if (await geoFirst(ctx)) return void 0;
11082
+ const provider = ctx.params?.provider || "local";
11083
+ if (provider !== "local") return run();
11084
+ return lockoutGuard(ctx, run, classifyCallbackOutcome, refuse);
11085
+ },
11086
+ async newSession(ctx, run) {
11087
+ if (await geoFirst(ctx)) return void 0;
11088
+ return run();
11089
+ }
11090
+ };
11091
+ }
11092
+ function connectAuthControllerGuard(deps) {
11093
+ setAuthControllerHandlers(deps.strapi, createAuthControllerHandlers(deps));
10155
11094
  }
10156
11095
  function statusOfThrownError(err) {
10157
11096
  const status = Number(err?.status ?? err?.statusCode);
@@ -11361,6 +12300,8 @@ var require_bootstrap = __commonJS({
11361
12300
  }
11362
12301
  }
11363
12302
  module2.exports.__private = {
12303
+ warnShortEncryptionKey,
12304
+ createAuthControllerHandlers,
11364
12305
  registerSessionAwareAuthStrategy,
11365
12306
  mountFailedLoginLockout,
11366
12307
  ensureSessionLookupIndexes,
@@ -11380,6 +12321,7 @@ var require_destroy = __commonJS({
11380
12321
  "server/src/destroy.js"(exports2, module2) {
11381
12322
  "use strict";
11382
12323
  var { createLogger } = require_logger();
12324
+ var { uninstallAuthControllerGuard } = require_auth_controller_guard();
11383
12325
  module2.exports = async ({ strapi: strapi2 }) => {
11384
12326
  const log = createLogger(strapi2);
11385
12327
  if (strapi2.sessionManagerIntervals) {
@@ -11413,6 +12355,11 @@ var require_destroy = __commonJS({
11413
12355
  }
11414
12356
  strapi2.sessionManagerAdminActivityUninstall = null;
11415
12357
  }
12358
+ try {
12359
+ uninstallAuthControllerGuard(strapi2);
12360
+ } catch (err) {
12361
+ log.warn("Failed to restore the Users & Permissions auth controller:", err?.name || "Error");
12362
+ }
11416
12363
  try {
11417
12364
  strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
11418
12365
  } catch (err) {
@@ -11786,7 +12733,7 @@ var require_schema4 = __commonJS({
11786
12733
  singularName: "impersonation",
11787
12734
  pluralName: "impersonations",
11788
12735
  displayName: "Impersonation",
11789
- description: "Time-limited impersonations of app users and permission previews of admins, started by an admin with a reason"
12736
+ description: "Time-limited impersonations of app users, permission previews of admins and sign-ins as another admin, started by an admin with a reason"
11790
12737
  },
11791
12738
  options: {
11792
12739
  draftAndPublish: false,
@@ -11849,13 +12796,17 @@ var require_schema4 = __commonJS({
11849
12796
  },
11850
12797
  handoff: {
11851
12798
  type: "enumeration",
11852
- enum: ["frontend", "token", "preview"],
12799
+ enum: ["frontend", "token", "preview", "admin-session"],
11853
12800
  required: true
11854
12801
  },
11855
12802
  notifyUser: {
11856
12803
  type: "boolean",
11857
12804
  default: false
11858
12805
  },
12806
+ allowChanges: {
12807
+ type: "boolean",
12808
+ default: false
12809
+ },
11859
12810
  startedAt: {
11860
12811
  type: "datetime",
11861
12812
  required: true
@@ -12135,6 +13086,7 @@ var require_admin = __commonJS({
12135
13086
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12136
13087
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
12137
13088
  var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
13089
+ var ADMIN_SIGN_IN_ACTION = "plugin::magic-sessionmanager.impersonate.admins.sign-in";
12138
13090
  var impersonationListPolicy = () => [
12139
13091
  ...adminPolicy(),
12140
13092
  "plugin::magic-sessionmanager.can-impersonate"
@@ -12539,6 +13491,59 @@ var require_admin = __commonJS({
12539
13491
  ]
12540
13492
  }
12541
13493
  },
13494
+ // Sign in as this admin (4.23).
13495
+ {
13496
+ method: "POST",
13497
+ path: "/impersonation/admins/:adminId/sign-in",
13498
+ handler: "impersonation.signInAdmin",
13499
+ config: {
13500
+ policies: adminSessionsPolicy([ADMIN_SIGN_IN_ACTION]),
13501
+ middlewares: [
13502
+ {
13503
+ name: "plugin::magic-sessionmanager.rate-limit",
13504
+ config: { max: 10, window: 10 * 60 * 1e3 }
13505
+ }
13506
+ ]
13507
+ }
13508
+ },
13509
+ {
13510
+ method: "POST",
13511
+ path: "/admin-impersonation/exchange",
13512
+ handler: "impersonation.exchangeAdmin",
13513
+ config: {
13514
+ // The code is bound to the admin who started the sign-in, who must
13515
+ // still hold the action.
13516
+ policies: adminSessionsPolicy([ADMIN_SIGN_IN_ACTION]),
13517
+ middlewares: [
13518
+ {
13519
+ name: "plugin::magic-sessionmanager.rate-limit",
13520
+ config: { max: 10, window: 6e4 }
13521
+ }
13522
+ ]
13523
+ }
13524
+ },
13525
+ {
13526
+ method: "GET",
13527
+ path: "/admin-impersonation/self",
13528
+ handler: "impersonation.adminSelf",
13529
+ config: {
13530
+ // The impersonation tab holds the target's token, and the target may
13531
+ // not have plugin access. The admin impersonation guard recognises
13532
+ // the session (signed token + session marker) before routing; the
13533
+ // handler answers 401 to everybody else.
13534
+ auth: false,
13535
+ middlewares: adminReadRateLimit()
13536
+ }
13537
+ },
13538
+ {
13539
+ method: "POST",
13540
+ path: "/admin-impersonation/self/end",
13541
+ handler: "impersonation.endAdminSelf",
13542
+ config: {
13543
+ auth: false,
13544
+ middlewares: adminSignOutRateLimit()
13545
+ }
13546
+ },
12542
13547
  {
12543
13548
  method: "GET",
12544
13549
  path: "/impersonation/previews/:id",
@@ -14886,7 +15891,13 @@ var require_settings_access = __commonJS({
14886
15891
  // Signed webhook, event selection, impossible travel and shortened IPs.
14887
15892
  ...PROTECTED_DETECTION_KEYS,
14888
15893
  // Impersonation switch (4.20): whether admins can act as app users.
14889
- ...IMPERSONATION_KEYS
15894
+ ...IMPERSONATION_KEYS,
15895
+ // Security review 2 (4.22.1): which proxies may name the client address
15896
+ // (H2), the IP lockout threshold (H2) and the alert email texts, which go
15897
+ // to app users from the site's own address (hardening 6).
15898
+ "trustedProxies",
15899
+ "maxFailedLogins",
15900
+ "emailTemplates"
14890
15901
  ]);
14891
15902
  var WEBHOOK_SECRETS = Object.freeze([
14892
15903
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
@@ -14996,6 +16007,7 @@ var require_settings = __commonJS({
14996
16007
  validateImpersonationSettings
14997
16008
  } = require_impersonation_rules();
14998
16009
  var { encryptToken } = require_encryption();
16010
+ var { normalizeTrustedProxies, validateTrustedProxies } = require_trusted_proxies();
14999
16011
  var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
15000
16012
  var path = require("node:path");
15001
16013
  var ALLOWED_WEBHOOK_DOMAINS = {
@@ -15171,7 +16183,9 @@ var require_settings = __commonJS({
15171
16183
  discordWebhookUrl: "",
15172
16184
  slackWebhookUrl: "",
15173
16185
  strictSessionEnforcement: false,
15174
- trustedProxies: false,
16186
+ // A list of proxy addresses or CIDR ranges since 4.22.1; the legacy
16187
+ // boolean is read as an empty list (Strapi's server.proxy settings decide).
16188
+ trustedProxies: [],
15175
16189
  emailTemplates: DEFAULT_EMAIL_TEMPLATES,
15176
16190
  ...SECURITY_LOG_DEFAULTS,
15177
16191
  ...POLICY_DEFAULTS,
@@ -15192,7 +16206,8 @@ var require_settings = __commonJS({
15192
16206
  ...DEFAULT_EMAIL_TEMPLATES,
15193
16207
  ...storedTemplates
15194
16208
  },
15195
- geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath)
16209
+ geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath),
16210
+ trustedProxies: normalizeTrustedProxies(safeStored.trustedProxies)
15196
16211
  };
15197
16212
  }
15198
16213
  var INTEGER_SETTING_RANGES = {
@@ -15217,8 +16232,7 @@ var require_settings = __commonJS({
15217
16232
  "alertOnNewLocation",
15218
16233
  "alertOnVpnProxy",
15219
16234
  "enableWebhooks",
15220
- "strictSessionEnforcement",
15221
- "trustedProxies"
16235
+ "strictSessionEnforcement"
15222
16236
  ];
15223
16237
  var GEO_IP_PROVIDER_VALUES = ["auto", "local-mmdb", "ipapi", "disabled"];
15224
16238
  var GEO_LOOKUP_FAILURE_MODE_VALUES = ["auto", "allow", "block"];
@@ -15292,6 +16306,11 @@ var require_settings = __commonJS({
15292
16306
  next[key] = body[key];
15293
16307
  }
15294
16308
  }
16309
+ if (has("trustedProxies")) {
16310
+ const proxies = validateTrustedProxies(body.trustedProxies);
16311
+ if (proxies.error) errors.push(proxies.error);
16312
+ else next.trustedProxies = proxies.value;
16313
+ }
15295
16314
  for (const key of ["allowedCountries", "blockedCountries"]) {
15296
16315
  if (!has(key)) continue;
15297
16316
  const list = body[key];
@@ -15410,6 +16429,15 @@ var require_settings = __commonJS({
15410
16429
  next.genericWebhookSecret = encryptToken(secret);
15411
16430
  }
15412
16431
  }
16432
+ const urlChanges = typeof next.genericWebhookUrl === "string" && next.genericWebhookUrl !== "" && next.genericWebhookUrl !== (current.genericWebhookUrl || "");
16433
+ const secretStored = typeof current.genericWebhookSecret === "string" && current.genericWebhookSecret !== "";
16434
+ const secretGiven = typeof next.genericWebhookSecret === "string" && next.genericWebhookSecret !== "";
16435
+ if (urlChanges && secretStored && !secretGiven) {
16436
+ errors.push({
16437
+ path: ["genericWebhookSecret"],
16438
+ message: "Enter the webhook secret again when you change the webhook URL"
16439
+ });
16440
+ }
15413
16441
  if (errors.length > 0) return { errors };
15414
16442
  const settings = {};
15415
16443
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -17122,10 +18150,43 @@ var require_lockouts = __commonJS({
17122
18150
  }
17123
18151
  });
17124
18152
 
18153
+ // server/src/utils/user-export.js
18154
+ var require_user_export = __commonJS({
18155
+ "server/src/utils/user-export.js"(exports2, module2) {
18156
+ "use strict";
18157
+ var { SECURITY_EVENTS } = require_security_log_model();
18158
+ var IMPERSONATION_TEXT = Object.freeze({
18159
+ [SECURITY_EVENTS.IMPERSONATION_STARTED]: "An administrator opened your account",
18160
+ [SECURITY_EVENTS.IMPERSONATION_ENDED]: "The administrator access to your account ended",
18161
+ [SECURITY_EVENTS.IMPERSONATION_EXPIRED]: "The administrator access to your account ended",
18162
+ [SECURITY_EVENTS.IMPERSONATION_REFUSED]: "An administrator access to your account was refused"
18163
+ });
18164
+ function toUserExportEvent(row) {
18165
+ const { id: _id, ...rest } = row || {};
18166
+ const text = IMPERSONATION_TEXT[rest.event];
18167
+ if (!text) return rest;
18168
+ const minutes = Number(rest.meta?.durationMinutes);
18169
+ return {
18170
+ event: rest.event,
18171
+ createdAt: rest.createdAt,
18172
+ ip: null,
18173
+ userAgent: null,
18174
+ geo: null,
18175
+ meta: {
18176
+ description: text,
18177
+ ...Number.isInteger(minutes) && minutes > 0 ? { durationMinutes: minutes } : {}
18178
+ }
18179
+ };
18180
+ }
18181
+ module2.exports = { IMPERSONATION_TEXT, toUserExportEvent };
18182
+ }
18183
+ });
18184
+
17125
18185
  // server/src/controllers/self-service.js
17126
18186
  var require_self_service = __commonJS({
17127
18187
  "server/src/controllers/self-service.js"(exports2, module2) {
17128
18188
  "use strict";
18189
+ var crypto = require("node:crypto");
17129
18190
  var { getCoordinator } = require_coordination();
17130
18191
  var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
17131
18192
  var { recordUserEvent } = require_sign_in_policies();
@@ -17133,6 +18194,7 @@ var require_self_service = __commonJS({
17133
18194
  var { SECURITY_EVENTS } = require_security_log_model();
17134
18195
  var { sendServerError } = require_http_errors();
17135
18196
  var { createLogger } = require_logger();
18197
+ var { toUserExportEvent } = require_user_export();
17136
18198
  var SESSION_UID = "plugin::magic-sessionmanager.session";
17137
18199
  var EVENT_UID = "plugin::magic-sessionmanager.security-event";
17138
18200
  var USER_UID = "plugin::users-permissions.user";
@@ -17199,19 +18261,21 @@ var require_self_service = __commonJS({
17199
18261
  return "en";
17200
18262
  }
17201
18263
  var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
17202
- function sendPage(ctx, status, lang, title, body) {
18264
+ var FRAGMENT_SCRIPT = `(function(){var m=/[#&]token=([A-Za-z0-9_.%-]+)/.exec(location.hash);if(!m)return;var t=decodeURIComponent(m[1]);var f=document.querySelectorAll('input[name="token"]');for(var i=0;i<f.length;i++)f[i].value=t;if(history.replaceState)history.replaceState(null,'',location.pathname);})();`;
18265
+ var FRAGMENT_SCRIPT_HASH = `sha256-${crypto.createHash("sha256").update(FRAGMENT_SCRIPT).digest("base64")}`;
18266
+ function sendPage(ctx, status, lang, title, body, { withScript = false } = {}) {
17203
18267
  ctx.status = status;
17204
18268
  ctx.set("Content-Type", "text/html; charset=utf-8");
17205
18269
  ctx.set(
17206
18270
  "Content-Security-Policy",
17207
- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
18271
+ `default-src 'none'; style-src 'unsafe-inline'; ${withScript ? `script-src '${FRAGMENT_SCRIPT_HASH}'; ` : ""}form-action 'self'; frame-ancestors 'none'; base-uri 'none'`
17208
18272
  );
17209
18273
  ctx.set("Referrer-Policy", "no-referrer");
17210
18274
  ctx.set("Cache-Control", "no-store");
17211
18275
  ctx.set("X-Robots-Tag", "noindex");
17212
18276
  ctx.body = `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>
17213
18277
  <style>body{font-family:system-ui,sans-serif;max-width:36rem;margin:3rem auto;padding:0 1rem;line-height:1.5;color:#212134;background:#fff}button{font:inherit;padding:.6rem 1rem;margin:.25rem .5rem .25rem 0;border-radius:4px;border:1px solid #4945ff;background:#4945ff;color:#fff;cursor:pointer}button.secondary{background:#fff;color:#4945ff}@media (prefers-color-scheme:dark){body{background:#181826;color:#eaeaef}button.secondary{background:#181826}}</style></head>
17214
- <body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
18278
+ <body><main><h1>${escapeHtml(title)}</h1>${body}</main>${withScript ? `<script>${FRAGMENT_SCRIPT}</script>` : ""}</body></html>`;
17215
18279
  }
17216
18280
  module2.exports = ({ strapi: strapi2 }) => {
17217
18281
  const log = createLogger(strapi2);
@@ -17219,17 +18283,20 @@ var require_self_service = __commonJS({
17219
18283
  /**
17220
18284
  * Confirmation page of the "This wasn't me" link. Uses nothing.
17221
18285
  *
17222
- * @route GET /api/magic-sessionmanager/not-me?token=
18286
+ * @route GET /api/magic-sessionmanager/not-me (token in `#token=`; `?token=` before 4.22.1)
17223
18287
  * @auth none (public on purpose: the link is opened from an email; the
17224
18288
  * signed token is checked, and nothing changes until the POST)
17225
18289
  * @param {any} ctx Koa context.
17226
- * @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
18290
+ * @returns {Promise<void>} 200 page with two buttons, or 410 when a `?token=` link is
18291
+ * invalid. Without `?token=` the page is served with the hashed script that copies the
18292
+ * fragment token into the forms; the POST checks it.
17227
18293
  */
17228
18294
  async notMePage(ctx) {
17229
18295
  const lang = pageLanguage(ctx);
17230
18296
  const text = PAGE_TEXT[lang];
17231
- const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
17232
- if (!readNotMeToken(token)) {
18297
+ const hasQueryToken = typeof ctx.query?.token === "string" && ctx.query.token !== "";
18298
+ const token = hasQueryToken ? ctx.query.token : "";
18299
+ if (hasQueryToken && !readNotMeToken(token)) {
17233
18300
  return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
17234
18301
  }
17235
18302
  const form = (scope, label, className) => `<form method="post" style="display:inline"><input type="hidden" name="token" value="${escapeHtml(token)}"><input type="hidden" name="scope" value="${scope}"><button type="submit"${className ? ` class="${className}"` : ""}>${escapeHtml(label)}</button></form>`;
@@ -17238,7 +18305,8 @@ var require_self_service = __commonJS({
17238
18305
  200,
17239
18306
  lang,
17240
18307
  text.title,
17241
- `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
18308
+ `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`,
18309
+ { withScript: !hasQueryToken }
17242
18310
  );
17243
18311
  },
17244
18312
  /**
@@ -17391,7 +18459,9 @@ var require_self_service = __commonJS({
17391
18459
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
17392
18460
  user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
17393
18461
  sessions,
17394
- securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
18462
+ // Impersonation events show a fixed text and the duration only
18463
+ // (security review 2, L3): the admin's reason stays internal.
18464
+ securityEvents: (Array.isArray(events) ? events : []).map(toUserExportEvent)
17395
18465
  };
17396
18466
  } catch (err) {
17397
18467
  log.error("[my-data] Export failed:", err?.name || "Error");
@@ -17694,6 +18764,14 @@ var require_impersonation = __commonJS({
17694
18764
  resolveFrontendHandoff,
17695
18765
  validateStartBody
17696
18766
  } = require_impersonation_rules();
18767
+ var {
18768
+ ADMIN_DEVICE_PREFIX,
18769
+ ADMIN_SIGN_IN_ACTION,
18770
+ LANDING_PATH,
18771
+ adminSignInSupport,
18772
+ allowedSignInDurations,
18773
+ validateSignInBody
18774
+ } = require_admin_sign_in_rules();
17697
18775
  var UID = "plugin::magic-sessionmanager.impersonation";
17698
18776
  var USER_UID = "plugin::users-permissions.user";
17699
18777
  var NATIVE_SESSION_UID = "admin::session";
@@ -17721,7 +18799,8 @@ var require_impersonation = __commonJS({
17721
18799
  STARTED: "impersonation.started",
17722
18800
  ENDED: "impersonation.ended",
17723
18801
  EXPIRED: "impersonation.expired",
17724
- REFUSED: "impersonation.refused"
18802
+ REFUSED: "impersonation.refused",
18803
+ WRITE: "impersonation.write"
17725
18804
  });
17726
18805
  function remember(map, key, value) {
17727
18806
  map.delete(key);
@@ -17817,9 +18896,27 @@ var require_impersonation = __commonJS({
17817
18896
  frontendOrigin: frontend ? frontend.origin : null,
17818
18897
  durations: [...USER_DURATIONS],
17819
18898
  adminDurations: [...ADMIN_DURATIONS],
17820
- mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
18899
+ mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy",
18900
+ adminSignIn: service.adminSignInStatus()
17821
18901
  };
17822
18902
  },
18903
+ /**
18904
+ * Whether "Sign in as this admin" can run on this Strapi: a tested
18905
+ * release, Strapi's session manager present, and at least one duration
18906
+ * that fits into one admin access token.
18907
+ *
18908
+ * @returns {{supported: boolean, version: string|null, reason: string|null, durations: number[]}}
18909
+ */
18910
+ adminSignInStatus() {
18911
+ const support = adminSignInSupport(strapi2.config.get("info.strapi"));
18912
+ const durations = allowedSignInDurations(
18913
+ strapi2.config.get("admin.auth.sessions.accessTokenLifespan", 30 * 60)
18914
+ );
18915
+ let reason = support.reason;
18916
+ if (!reason && typeof strapi2.sessionManager !== "function") reason = "no-session-manager";
18917
+ if (!reason && durations.length === 0) reason = "token-lifespan";
18918
+ return { supported: reason === null, version: support.version, reason, durations };
18919
+ },
17823
18920
  /**
17824
18921
  * Records a refused start.
17825
18922
  *
@@ -17951,7 +19048,8 @@ var require_impersonation = __commonJS({
17951
19048
  * Caller (with roles), target id and request body.
17952
19049
  * @returns {Promise<object>} Impersonation DTO plus the preview.
17953
19050
  * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17954
- * or not a subset of the caller's permissions; 404 unknown admin.
19051
+ * (callers with `admin::users.read`) or not a subset of the caller's permissions; 404
19052
+ * unknown admin, or a Super Admin for callers without `admin::users.read`.
17955
19053
  * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17956
19054
  */
17957
19055
  async previewAdmin({ actor, adminId, body, canReadAdmins }) {
@@ -17981,6 +19079,15 @@ var require_impersonation = __commonJS({
17981
19079
  ]);
17982
19080
  if (!target) throw new ImpersonationError(404, "Admin not found");
17983
19081
  const refusal = await previewRefusal(strapi2, caller || actor, target);
19082
+ if (refusal?.reason === "super-admin" && !canReadAdmins) {
19083
+ service.recordRefused({
19084
+ actorId,
19085
+ targetType: "admin",
19086
+ targetId: adminId,
19087
+ reason: "super-admin"
19088
+ });
19089
+ throw new ImpersonationError(404, "Admin not found");
19090
+ }
17984
19091
  if (refusal) {
17985
19092
  const messages = {
17986
19093
  self: "You cannot view yourself as another admin",
@@ -18073,6 +19180,416 @@ var require_impersonation = __commonJS({
18073
19180
  preview
18074
19181
  };
18075
19182
  },
19183
+ /**
19184
+ * Starts "Sign in as this admin" (4.23): checks every anti-escalation
19185
+ * rule, stores the impersonation with a one-time code (60 seconds,
19186
+ * stored hashed) and returns the landing path for a new tab. The Strapi
19187
+ * admin session is created only when that tab exchanges the code.
19188
+ *
19189
+ * @param {{actor: any, adminId: unknown, body: unknown, canReadAdmins: boolean,
19190
+ * nested?: boolean}} input Caller (with roles), target id, body; `nested` when the
19191
+ * request itself comes from an impersonation session.
19192
+ * @returns {Promise<{impersonation: object, handoff: {type: 'admin-tab', path: string,
19193
+ * code: string, codeExpiresAt: string}}>}
19194
+ * @throws {ImpersonationError} 400 invalid body; 403 off, unsupported Strapi, nested,
19195
+ * self, Super Admin, inactive, not a subset or already active; 404 unknown admin.
19196
+ * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
19197
+ */
19198
+ async startAdminSignIn({ actor, adminId, body, canReadAdmins, nested = false }) {
19199
+ const actorId = String(actor.id);
19200
+ const refuse = (reason, status, message, extra = {}) => {
19201
+ service.recordRefused({
19202
+ actorId,
19203
+ targetType: "admin",
19204
+ targetId: adminId,
19205
+ reason,
19206
+ via: "sign-in"
19207
+ });
19208
+ return new ImpersonationError(status, message, { reason, ...extra });
19209
+ };
19210
+ if (!await service.isEnabled()) {
19211
+ throw refuse("disabled", 403, "Impersonation is turned off");
19212
+ }
19213
+ const support = service.adminSignInStatus();
19214
+ if (!support.supported) {
19215
+ throw refuse("unsupported", 403, "Not available on this Strapi version", {
19216
+ cause: support.reason
19217
+ });
19218
+ }
19219
+ if (nested)
19220
+ throw refuse("nested", 403, "You cannot start an impersonation while impersonating");
19221
+ if (typeof adminId !== "string" || !ADMIN_ID_PATTERN.test(adminId)) {
19222
+ throw new ImpersonationError(404, "Admin not found");
19223
+ }
19224
+ const { value, errors: fieldErrors } = validateSignInBody(body, support.durations);
19225
+ if (!value) {
19226
+ throw new ImpersonationError(400, "Invalid sign-in request", {
19227
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
19228
+ });
19229
+ }
19230
+ const [caller, target] = await Promise.all([
19231
+ loadAdmin(strapi2, actor.id),
19232
+ loadAdmin(strapi2, Number(adminId))
19233
+ ]);
19234
+ if (!target) throw new ImpersonationError(404, "Admin not found");
19235
+ const refusal = await previewRefusal(strapi2, caller || actor, target);
19236
+ if (refusal?.reason === "super-admin" && !canReadAdmins) {
19237
+ service.recordRefused({
19238
+ actorId,
19239
+ targetType: "admin",
19240
+ targetId: adminId,
19241
+ reason: "super-admin",
19242
+ via: "sign-in"
19243
+ });
19244
+ throw new ImpersonationError(404, "Admin not found");
19245
+ }
19246
+ if (refusal) {
19247
+ const messages = {
19248
+ self: "You cannot sign in as yourself",
19249
+ "super-admin": "You cannot sign in as a Super Admin",
19250
+ "not-subset": "This admin has permissions that you do not have"
19251
+ };
19252
+ throw refuse(
19253
+ refusal.reason,
19254
+ 403,
19255
+ messages[refusal.reason],
19256
+ refusal.uncovered ? { uncovered: refusal.uncovered } : {}
19257
+ );
19258
+ }
19259
+ if (target.isActive !== true) {
19260
+ throw refuse("inactive", 403, "This admin account is not active");
19261
+ }
19262
+ await service.sweep();
19263
+ const running = await query().findOne({
19264
+ where: {
19265
+ targetType: "admin",
19266
+ targetId: String(target.id),
19267
+ handoff: "admin-session",
19268
+ state: "active"
19269
+ },
19270
+ select: ["id"]
19271
+ });
19272
+ if (running)
19273
+ throw refuse("already-active", 403, "Someone is already signed in as this admin");
19274
+ const now = /* @__PURE__ */ new Date();
19275
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
19276
+ const code = crypto.randomBytes(32).toString("base64url");
19277
+ const codeExpiresAt = new Date(now.getTime() + CODE_TTL_MS);
19278
+ const row = await query().create({
19279
+ data: {
19280
+ targetType: "admin",
19281
+ targetId: String(target.id),
19282
+ actorId,
19283
+ state: "active",
19284
+ reason: value.reason,
19285
+ durationMinutes: value.durationMinutes,
19286
+ handoff: "admin-session",
19287
+ notifyUser: false,
19288
+ allowChanges: value.allowChanges,
19289
+ startedAt: now,
19290
+ expiresAt,
19291
+ codeHash: hashToken(code),
19292
+ codeExpiresAt
19293
+ }
19294
+ });
19295
+ record({
19296
+ event: EVENTS.STARTED,
19297
+ actorType: "admin",
19298
+ actorId,
19299
+ targetType: "admin",
19300
+ targetId: String(target.id),
19301
+ meta: {
19302
+ reason: value.reason,
19303
+ durationMinutes: value.durationMinutes,
19304
+ handoff: "admin-session",
19305
+ allowChanges: value.allowChanges
19306
+ }
19307
+ });
19308
+ log.info(
19309
+ `[IMPERSONATION] Admin sign-in started (${value.durationMinutes} min, ${value.allowChanges ? "changes allowed" : "read-only"})`
19310
+ );
19311
+ return {
19312
+ impersonation: service.toDto(row, {
19313
+ admins: /* @__PURE__ */ new Map([
19314
+ [String(target.id), canReadAdmins ? target : null],
19315
+ [actorId, caller || actor]
19316
+ ]),
19317
+ viewer: actor
19318
+ }),
19319
+ handoff: {
19320
+ type: "admin-tab",
19321
+ path: LANDING_PATH,
19322
+ cookieName: service.accessCookieName(),
19323
+ code,
19324
+ codeExpiresAt: codeExpiresAt.toISOString()
19325
+ }
19326
+ };
19327
+ },
19328
+ /**
19329
+ * Exchanges the one-time code of an admin sign-in for an admin access
19330
+ * token of the target, in the new tab. The request carries the starting
19331
+ * admin's own token, and only that admin can redeem the code. The Strapi
19332
+ * admin session is created here on a dedicated device id, marked in its
19333
+ * metadata, and expires with the impersonation; its refresh token never
19334
+ * leaves the server, so the tab cannot renew it.
19335
+ *
19336
+ * @param {{code: unknown, actor: any, ability: any}} input Code and the calling admin.
19337
+ * @returns {Promise<object|null>} `{ token, expiresAt, cookieName, impersonation }`, or null
19338
+ * for any unusable code.
19339
+ * @sideeffect Consumes the code; creates one Strapi admin session for the target.
19340
+ */
19341
+ async exchangeAdminCode({ code, actor, ability }) {
19342
+ if (typeof code !== "string" || !CODE_PATTERN.test(code)) return null;
19343
+ if (!await service.isEnabled() || !service.adminSignInStatus().supported) return null;
19344
+ const codeHash = hashToken(code);
19345
+ const now = /* @__PURE__ */ new Date();
19346
+ const row = await query().findOne({
19347
+ where: { codeHash, state: "active", handoff: "admin-session" }
19348
+ });
19349
+ if (!row || String(row.actorId) !== String(actor?.id)) return null;
19350
+ let stillAllowed;
19351
+ try {
19352
+ stillAllowed = ability?.can?.(ADMIN_SIGN_IN_ACTION) === true;
19353
+ } catch {
19354
+ stillAllowed = false;
19355
+ }
19356
+ if (!stillAllowed) return null;
19357
+ const claimed = await query().updateMany({
19358
+ where: {
19359
+ id: row.id,
19360
+ codeHash,
19361
+ state: "active",
19362
+ credentialIssuedAt: { $null: true },
19363
+ codeExpiresAt: { $gt: now },
19364
+ expiresAt: { $gt: now }
19365
+ },
19366
+ data: { codeHash: null, codeExpiresAt: null, credentialIssuedAt: now }
19367
+ });
19368
+ if (Number(claimed?.count) !== 1) return null;
19369
+ const target = await loadAdmin(strapi2, Number(row.targetId));
19370
+ if (!target || target.isActive !== true || await previewRefusal(strapi2, actor, target)) {
19371
+ await service.end(row.documentId, { reason: "failed", silent: true });
19372
+ return null;
19373
+ }
19374
+ try {
19375
+ const token = await service.issueAdminSession(row, target);
19376
+ return {
19377
+ token,
19378
+ expiresAt: new Date(row.expiresAt).toISOString(),
19379
+ cookieName: service.accessCookieName(),
19380
+ impersonation: {
19381
+ id: row.documentId,
19382
+ allowChanges: row.allowChanges === true,
19383
+ expiresAt: new Date(row.expiresAt).toISOString(),
19384
+ targetName: adminLabel(target),
19385
+ actorName: adminLabel(actor)
19386
+ }
19387
+ };
19388
+ } catch (err) {
19389
+ await service.end(row.documentId, { reason: "failed", silent: true });
19390
+ throw err;
19391
+ }
19392
+ },
19393
+ /**
19394
+ * Name of Strapi's admin access cookie (`admin.auth.cookie.name`,
19395
+ * default `jwtToken`), so the impersonation tab can hide it.
19396
+ *
19397
+ * @returns {string}
19398
+ */
19399
+ accessCookieName() {
19400
+ const configured = strapi2.config.get("admin.auth.cookie.name");
19401
+ return typeof configured === "string" && /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(configured.trim()) ? configured.trim() : "jwtToken";
19402
+ },
19403
+ /**
19404
+ * Creates the Strapi admin session of an admin sign-in and returns its
19405
+ * access token. The device id is recorded before the session exists, so
19406
+ * a failure below still revokes exactly this session.
19407
+ *
19408
+ * @param {any} row Impersonation row.
19409
+ * @param {any} target Target admin.
19410
+ * @returns {Promise<string>} Access token.
19411
+ * @throws {Error} When the session cannot be created.
19412
+ * @sideeffect Creates one `admin::session` row and shortens its expiry.
19413
+ */
19414
+ async issueAdminSession(row, target) {
19415
+ const expiresAt = new Date(row.expiresAt);
19416
+ if (expiresAt.getTime() - Date.now() < 5e3) {
19417
+ throw new ImpersonationError(403, "Impersonation ended");
19418
+ }
19419
+ const deviceId = `${ADMIN_DEVICE_PREFIX}${crypto.randomBytes(12).toString("hex")}`;
19420
+ await query().update({
19421
+ where: { id: row.id },
19422
+ data: { nativeUserId: String(target.id), nativeDeviceId: deviceId }
19423
+ });
19424
+ const manager = strapi2.sessionManager("admin");
19425
+ const refresh = await manager.generateRefreshToken(String(target.id), deviceId, {
19426
+ type: "session",
19427
+ metadata: {
19428
+ loginAt: (/* @__PURE__ */ new Date()).toISOString(),
19429
+ deviceName: "Impersonation",
19430
+ msmImpersonation: row.documentId
19431
+ }
19432
+ });
19433
+ await strapi2.db.query(NATIVE_SESSION_UID).update({
19434
+ where: { sessionId: refresh.sessionId },
19435
+ data: { expiresAt, absoluteExpiresAt: expiresAt }
19436
+ });
19437
+ const access = await manager.generateAccessToken(refresh.token);
19438
+ if (!access || "error" in access) throw new Error("Access token could not be minted");
19439
+ remember(nativeSessionCache, `admin:${refresh.sessionId}`, row.documentId);
19440
+ recordCache.delete(row.documentId);
19441
+ return access.token;
19442
+ },
19443
+ /**
19444
+ * Deletes the Strapi admin session of an admin sign-in, and only that
19445
+ * one: by its user and its own device id. Without a stored device id
19446
+ * nothing is deleted, because Strapi's `invalidateRefreshToken` without
19447
+ * a device id would delete every session of the target.
19448
+ *
19449
+ * @param {any} row Impersonation row.
19450
+ * @returns {Promise<void>}
19451
+ * @sideeffect Deletes `admin::session` rows of the impersonation device.
19452
+ */
19453
+ async revokeAdminSession(row) {
19454
+ const userId = row.nativeUserId ? String(row.nativeUserId) : "";
19455
+ const deviceId = row.nativeDeviceId ? String(row.nativeDeviceId) : "";
19456
+ if (!userId || !deviceId.startsWith(ADMIN_DEVICE_PREFIX)) return;
19457
+ try {
19458
+ await strapi2.sessionManager("admin").invalidateRefreshToken(userId, deviceId);
19459
+ } catch (err) {
19460
+ log.error("[IMPERSONATION] Admin session revocation failed:", err?.name || "Error");
19461
+ }
19462
+ },
19463
+ /**
19464
+ * The admin sign-in an admin access token belongs to, or null. The
19465
+ * signature is verified with Strapi's session manager; the session row
19466
+ * names the impersonation in its metadata (or by its device id, which
19467
+ * fails closed). Results are cached per session id (immutable).
19468
+ *
19469
+ * @param {string} token Bearer token.
19470
+ * @returns {Promise<string|null>} Impersonation id (`'unknown'` for a marked device
19471
+ * without readable metadata).
19472
+ * @throws {Error} When the session lookup fails.
19473
+ */
19474
+ async adminImpersonationOfToken(token) {
19475
+ const payload = decodeJwtPayload(token);
19476
+ if (!payload || payload.type !== "access") return null;
19477
+ const sessionId = payload.sessionId;
19478
+ if (typeof sessionId !== "string" || !/^[a-f0-9]{16,64}$/i.test(sessionId)) return null;
19479
+ const key = `admin:${sessionId}`;
19480
+ if (nativeSessionCache.has(key)) {
19481
+ return service.verifyAdminToken(token) ? nativeSessionCache.get(key) : null;
19482
+ }
19483
+ if (!service.verifyAdminToken(token)) return null;
19484
+ const session = await strapi2.db.query(NATIVE_SESSION_UID).findOne({
19485
+ where: { sessionId, origin: "admin" },
19486
+ select: ["metadata", "deviceId"]
19487
+ });
19488
+ let id = null;
19489
+ const mark = session?.metadata?.msmImpersonation;
19490
+ if (typeof mark === "string" && DOCUMENT_ID_PATTERN.test(mark)) id = mark;
19491
+ else if (typeof session?.deviceId === "string" && session.deviceId.startsWith(ADMIN_DEVICE_PREFIX)) {
19492
+ id = "unknown";
19493
+ }
19494
+ if (session) remember(nativeSessionCache, key, id);
19495
+ return id;
19496
+ },
19497
+ /**
19498
+ * Whether a token is a validly signed Strapi admin access token.
19499
+ *
19500
+ * @param {string} token Bearer token.
19501
+ * @returns {boolean}
19502
+ */
19503
+ verifyAdminToken(token) {
19504
+ try {
19505
+ return strapi2.sessionManager("admin").validateAccessToken(token)?.isValid === true;
19506
+ } catch {
19507
+ return false;
19508
+ }
19509
+ },
19510
+ /**
19511
+ * Loads an admin sign-in for the request guard (active rows are read on
19512
+ * every request, like `loadForGuard`).
19513
+ *
19514
+ * @param {string} documentId Impersonation id.
19515
+ * @returns {Promise<{id: string, actorId: string, targetId: string, state: string,
19516
+ * expiresAt: number, allowChanges: boolean}|null>}
19517
+ */
19518
+ async loadAdminForGuard(documentId) {
19519
+ const cached = recordCache.get(`admin:${documentId}`);
19520
+ if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
19521
+ const row = await query().findOne({
19522
+ where: { documentId, targetType: "admin", handoff: "admin-session" },
19523
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt", "allowChanges"]
19524
+ });
19525
+ const value = row ? {
19526
+ id: row.documentId,
19527
+ actorId: String(row.actorId),
19528
+ targetId: String(row.targetId),
19529
+ state: row.state,
19530
+ expiresAt: new Date(row.expiresAt).getTime(),
19531
+ allowChanges: row.allowChanges === true
19532
+ } : null;
19533
+ if (!value || value.state !== "active") {
19534
+ remember(recordCache, `admin:${documentId}`, { value, at: Date.now() });
19535
+ }
19536
+ return value;
19537
+ },
19538
+ /**
19539
+ * Records a change made while signed in as another admin: the real
19540
+ * admin is the actor, the target admin in `meta.impersonating`.
19541
+ *
19542
+ * @param {{id: string, actorId: string, targetId: string}} impersonation Impersonation.
19543
+ * @param {{method: string, path: string, status: number}} request What was done.
19544
+ * @returns {void}
19545
+ * @sideeffect Queues one always-on `impersonation.write` event.
19546
+ */
19547
+ recordAdminWrite(impersonation, { method, path, status }) {
19548
+ record({
19549
+ event: EVENTS.WRITE,
19550
+ actorType: "admin",
19551
+ actorId: impersonation.actorId,
19552
+ targetType: "admin",
19553
+ targetId: impersonation.targetId,
19554
+ meta: {
19555
+ impersonation: impersonation.id,
19556
+ impersonating: impersonation.targetId,
19557
+ method,
19558
+ route: path,
19559
+ status
19560
+ }
19561
+ });
19562
+ },
19563
+ /**
19564
+ * Records a refused admin API call of an admin sign-in (one event per
19565
+ * impersonation and reason per minute).
19566
+ *
19567
+ * @param {{id: string, actorId: string, targetId: string}} impersonation Impersonation.
19568
+ * @param {string} reason `read-only` or `identity`.
19569
+ * @param {{method: string, path: string}} request Refused request.
19570
+ * @returns {void}
19571
+ */
19572
+ recordRefusedAdminCall(impersonation, reason, { method, path }) {
19573
+ const key = `${impersonation.id}|admin-${reason}`;
19574
+ const now = Date.now();
19575
+ const last = refusals.get(key);
19576
+ if (last !== void 0 && now - last < REFUSAL_DEDUP_MS) return;
19577
+ remember(refusals, key, now);
19578
+ record({
19579
+ event: EVENTS.REFUSED,
19580
+ actorType: "admin",
19581
+ actorId: impersonation.actorId,
19582
+ targetType: "admin",
19583
+ targetId: impersonation.targetId,
19584
+ meta: {
19585
+ refusal: `call-${reason}`,
19586
+ impersonation: impersonation.id,
19587
+ impersonating: impersonation.targetId,
19588
+ method,
19589
+ route: path
19590
+ }
19591
+ });
19592
+ },
18076
19593
  /**
18077
19594
  * Mints the short-lived credential of an impersonation and links its
18078
19595
  * Magic session row.
@@ -18242,6 +19759,10 @@ var require_impersonation = __commonJS({
18242
19759
  * @sideeffect Deletes Strapi session rows, writes a revocation record, ends the Magic session.
18243
19760
  */
18244
19761
  async revoke(row, sessionReason) {
19762
+ if (row.handoff === "admin-session") {
19763
+ await service.revokeAdminSession(row);
19764
+ return;
19765
+ }
18245
19766
  if (row.nativeUserId && row.nativeDeviceId) {
18246
19767
  try {
18247
19768
  await strapi2.sessionManager(NATIVE_ORIGIN).invalidateRefreshToken(String(row.nativeUserId), String(row.nativeDeviceId));
@@ -18383,6 +19904,7 @@ var require_impersonation = __commonJS({
18383
19904
  reason: row.reason,
18384
19905
  durationMinutes: row.durationMinutes,
18385
19906
  handoff: row.handoff,
19907
+ allowChanges: row.allowChanges === true,
18386
19908
  credentialIssued: Boolean(row.credentialIssuedAt),
18387
19909
  startedAt: new Date(row.startedAt).toISOString(),
18388
19910
  expiresAt: new Date(row.expiresAt).toISOString(),
@@ -18390,7 +19912,10 @@ var require_impersonation = __commonJS({
18390
19912
  };
18391
19913
  },
18392
19914
  /**
18393
- * Loads one impersonation for the request guard (5-second cache).
19915
+ * Loads one impersonation for the request guard. Only a finished (or
19916
+ * unknown) impersonation is cached for 5 seconds; an active one is read
19917
+ * on every request, so ending it on one process takes effect on every
19918
+ * other process at once (security review 2, hardening 4).
18394
19919
  *
18395
19920
  * @param {string} documentId Impersonation id.
18396
19921
  * @returns {Promise<{id: string, actorId: string, targetId: string|null, state: string,
@@ -18410,7 +19935,9 @@ var require_impersonation = __commonJS({
18410
19935
  state: row.state,
18411
19936
  expiresAt: new Date(row.expiresAt).getTime()
18412
19937
  } : null;
18413
- remember(recordCache, documentId, { value, at: Date.now() });
19938
+ if (!value || value.state !== "active") {
19939
+ remember(recordCache, documentId, { value, at: Date.now() });
19940
+ }
18414
19941
  return value;
18415
19942
  },
18416
19943
  /**
@@ -18526,6 +20053,7 @@ var require_impersonation2 = __commonJS({
18526
20053
  var { sendServerError } = require_http_errors();
18527
20054
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18528
20055
  var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
20056
+ var { ADMIN_SIGN_IN_ACTION } = require_admin_sign_in_rules();
18529
20057
  function callerCan(ctx, action) {
18530
20058
  try {
18531
20059
  return ctx?.state?.userAbility?.can?.(action) === true;
@@ -18536,7 +20064,7 @@ var require_impersonation2 = __commonJS({
18536
20064
  function visibleTargetTypes(ctx) {
18537
20065
  return [
18538
20066
  ...callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [],
18539
- ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) ? ["admin"] : []
20067
+ ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) || callerCan(ctx, ADMIN_SIGN_IN_ACTION) ? ["admin"] : []
18540
20068
  ];
18541
20069
  }
18542
20070
  var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
@@ -18669,34 +20197,132 @@ var require_impersonation2 = __commonJS({
18669
20197
  return respond(ctx, "preview", async () => {
18670
20198
  const { adminId } = ctx.params;
18671
20199
  requirePerson(ctx, "admin", adminId);
18672
- const result = await service().previewAdmin({
20200
+ const result = await service().previewAdmin({
20201
+ actor: ctx.state.user,
20202
+ adminId,
20203
+ body: ctx.request.body,
20204
+ canReadAdmins: callerCan(ctx, "admin::users.read")
20205
+ });
20206
+ ctx.status = 201;
20207
+ ctx.body = { data: result };
20208
+ });
20209
+ },
20210
+ /**
20211
+ * Reads a running admin preview; only the admin who started it.
20212
+ *
20213
+ * @route GET /magic-sessionmanager/impersonation/previews/:id
20214
+ * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
20215
+ * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
20216
+ * expired or started by someone else.
20217
+ */
20218
+ async getPreview(ctx) {
20219
+ ctx.set("Cache-Control", "no-store");
20220
+ return respond(ctx, "preview", async () => {
20221
+ ctx.body = {
20222
+ data: await service().getPreview({
20223
+ id: ctx.params.id,
20224
+ viewer: ctx.state.user,
20225
+ canReadAdmins: callerCan(ctx, "admin::users.read")
20226
+ })
20227
+ };
20228
+ });
20229
+ },
20230
+ /**
20231
+ * Starts "Sign in as this admin" (4.23). Returns the landing path of the
20232
+ * new tab and a one-time code for it; no session exists yet.
20233
+ *
20234
+ * @route POST /magic-sessionmanager/impersonation/admins/:adminId/sign-in
20235
+ * @auth Admin JWT only (admin API tokens and impersonation sessions are refused);
20236
+ * `access` + `admin-sessions.read` + `impersonate.admins.sign-in`.
20237
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30,
20238
+ * allowChanges?: boolean }`.
20239
+ * @returns {Promise<void>} 201 `{ data: { impersonation, handoff: { type: 'admin-tab', path,
20240
+ * code, codeExpiresAt } } }`. Answers 403 with `details.reason` `disabled`, `unsupported`,
20241
+ * `api-token`, `nested`, `self`, `super-admin`, `not-subset`, `inactive` or
20242
+ * `already-active`, 400 for an invalid body and 404 for an unknown admin.
20243
+ * @sideeffect Creates an impersonation row; logs `impersonation.started` or `.refused`.
20244
+ */
20245
+ async signInAdmin(ctx) {
20246
+ ctx.set("Cache-Control", "no-store");
20247
+ return respond(ctx, "sign-in", async () => {
20248
+ const { adminId } = ctx.params;
20249
+ requirePerson(ctx, "admin", adminId);
20250
+ const result = await service().startAdminSignIn({
18673
20251
  actor: ctx.state.user,
18674
20252
  adminId,
18675
20253
  body: ctx.request.body,
18676
- canReadAdmins: callerCan(ctx, "admin::users.read")
20254
+ canReadAdmins: callerCan(ctx, "admin::users.read"),
20255
+ nested: Boolean(ctx.state.magicAdminImpersonation)
18677
20256
  });
18678
20257
  ctx.status = 201;
18679
20258
  ctx.body = { data: result };
18680
20259
  });
18681
20260
  },
18682
20261
  /**
18683
- * Reads a running admin preview; only the admin who started it.
20262
+ * Exchanges the one-time code of an admin sign-in for the target's
20263
+ * access token. Called by the new tab with the starting admin's own
20264
+ * token; only that admin can redeem the code. Every unusable code gets
20265
+ * the same 400.
18684
20266
  *
18685
- * @route GET /magic-sessionmanager/impersonation/previews/:id
18686
- * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
18687
- * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
18688
- * expired or started by someone else.
20267
+ * @route POST /magic-sessionmanager/admin-impersonation/exchange
20268
+ * @auth Admin JWT of the admin who started it (still holding `impersonate.admins.sign-in`).
20269
+ * @param {any} ctx Body `{ code: string }`.
20270
+ * @returns {Promise<void>} `{ data: { token, expiresAt, cookieName, impersonation } }`.
20271
+ * @sideeffect Consumes the code; creates one Strapi admin session for the target.
18689
20272
  */
18690
- async getPreview(ctx) {
20273
+ async exchangeAdmin(ctx) {
18691
20274
  ctx.set("Cache-Control", "no-store");
18692
- return respond(ctx, "preview", async () => {
18693
- ctx.body = {
18694
- data: await service().getPreview({
18695
- id: ctx.params.id,
18696
- viewer: ctx.state.user,
18697
- canReadAdmins: callerCan(ctx, "admin::users.read")
18698
- })
18699
- };
20275
+ const body = ctx.request.body;
20276
+ const valid = body && typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 1 && typeof body.code === "string" && ctx.state?.auth?.strategy?.name === "admin" && !ctx.state.magicAdminImpersonation;
20277
+ return respond(ctx, "exchange", async () => {
20278
+ const result = valid ? await service().exchangeAdminCode({
20279
+ code: body.code,
20280
+ actor: ctx.state.user,
20281
+ ability: ctx.state.userAbility
20282
+ }) : null;
20283
+ if (!result) throw new ImpersonationError(400, "Invalid or expired code");
20284
+ ctx.body = { data: result };
20285
+ });
20286
+ },
20287
+ /**
20288
+ * State of the admin sign-in of the calling tab, for its banner.
20289
+ *
20290
+ * @route GET /magic-sessionmanager/admin-impersonation/self
20291
+ * @auth The impersonation session's own token (checked by the admin impersonation guard);
20292
+ * 401 for any other caller.
20293
+ * @returns {Promise<void>} `{ data: { id, expiresAt, allowChanges } }`.
20294
+ */
20295
+ async adminSelf(ctx) {
20296
+ ctx.set("Cache-Control", "no-store");
20297
+ const current = ctx.state.magicAdminImpersonation;
20298
+ if (!current) return ctx.unauthorized("Not an impersonation session");
20299
+ ctx.body = {
20300
+ data: {
20301
+ id: current.id,
20302
+ expiresAt: new Date(current.expiresAt).toISOString(),
20303
+ allowChanges: current.allowChanges === true
20304
+ }
20305
+ };
20306
+ return void 0;
20307
+ },
20308
+ /**
20309
+ * Ends the admin sign-in of the calling tab: deletes its own Strapi
20310
+ * session and nothing else.
20311
+ *
20312
+ * @route POST /magic-sessionmanager/admin-impersonation/self/end
20313
+ * @auth The impersonation session's own token; 401 for any other caller.
20314
+ * @returns {Promise<void>} `{ data: { ended: boolean } }`.
20315
+ * @sideeffect Ends the impersonation; logs `impersonation.ended`.
20316
+ */
20317
+ async endAdminSelf(ctx) {
20318
+ const current = ctx.state.magicAdminImpersonation;
20319
+ if (!current) return ctx.unauthorized("Not an impersonation session");
20320
+ return respond(ctx, "end", async () => {
20321
+ const ended = await service().end(current.id, {
20322
+ reason: "ended",
20323
+ endedBy: current.actorId
20324
+ });
20325
+ ctx.body = { data: { ended } };
18700
20326
  });
18701
20327
  },
18702
20328
  /**
@@ -18726,6 +20352,7 @@ var require_impersonation2 = __commonJS({
18726
20352
  };
18727
20353
  module2.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
18728
20354
  module2.exports.IMPERSONATE_ADMINS_ACTION = IMPERSONATE_ADMINS_ACTION;
20355
+ module2.exports.ADMIN_SIGN_IN_ACTION = ADMIN_SIGN_IN_ACTION;
18729
20356
  }
18730
20357
  });
18731
20358
 
@@ -22600,6 +24227,7 @@ var require_security_log = __commonJS({
22600
24227
  function signInWhere(query) {
22601
24228
  const conditions = [{ event: { $in: [...SIGN_IN_FILTERS[query.event || "all"]] } }];
22602
24229
  if (query.adminId) conditions.push({ targetType: "admin", targetId: String(query.adminId) });
24230
+ else if (query.event === "impersonation") conditions.push({ targetType: "admin" });
22603
24231
  if (query.from) conditions.push({ createdAt: { $gte: query.from } });
22604
24232
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
22605
24233
  return { $and: conditions };
@@ -22947,227 +24575,6 @@ var require_security_log = __commonJS({
22947
24575
  }
22948
24576
  });
22949
24577
 
22950
- // server/src/utils/webhook-delivery.js
22951
- var require_webhook_delivery = __commonJS({
22952
- "server/src/utils/webhook-delivery.js"(exports2, module2) {
22953
- "use strict";
22954
- var crypto = require("node:crypto");
22955
- var dns = require("node:dns");
22956
- var https = require("node:https");
22957
- var net = require("node:net");
22958
- var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
22959
- var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
22960
- var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
22961
- var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
22962
- var TIMEOUT_MS = 5e3;
22963
- var MAX_RESPONSE_BYTES = 64 * 1024;
22964
- var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
22965
- var BLOCKED = (() => {
22966
- const list = new net.BlockList();
22967
- for (const [address, prefix] of [
22968
- ["0.0.0.0", 8],
22969
- ["10.0.0.0", 8],
22970
- ["100.64.0.0", 10],
22971
- ["127.0.0.0", 8],
22972
- ["169.254.0.0", 16],
22973
- ["172.16.0.0", 12],
22974
- ["192.0.0.0", 24],
22975
- ["192.0.2.0", 24],
22976
- ["192.88.99.0", 24],
22977
- ["192.168.0.0", 16],
22978
- ["198.18.0.0", 15],
22979
- ["198.51.100.0", 24],
22980
- ["203.0.113.0", 24],
22981
- ["224.0.0.0", 4],
22982
- ["240.0.0.0", 4]
22983
- ]) {
22984
- list.addSubnet(address, prefix, "ipv4");
22985
- }
22986
- for (const [address, prefix] of [
22987
- ["::", 128],
22988
- ["::1", 128],
22989
- // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
22990
- // checks them against the IPv4 rules above, and a listed /96 would
22991
- // match every IPv4 address.
22992
- ["64:ff9b::", 96],
22993
- ["64:ff9b:1::", 48],
22994
- ["100::", 64],
22995
- ["2001::", 23],
22996
- ["2001:db8::", 32],
22997
- ["2002::", 16],
22998
- ["fc00::", 7],
22999
- ["fe80::", 10],
23000
- ["fec0::", 10],
23001
- ["ff00::", 8]
23002
- ]) {
23003
- list.addSubnet(address, prefix, "ipv6");
23004
- }
23005
- return list;
23006
- })();
23007
- function isBlockedAddress(address) {
23008
- let value = String(address || "").trim();
23009
- if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
23010
- value = value.slice(7);
23011
- }
23012
- const version = net.isIP(value);
23013
- if (version === 0) return true;
23014
- return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
23015
- }
23016
- function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
23017
- const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
23018
- return `t=${timestamp},v1=${digest}`;
23019
- }
23020
- function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
23021
- const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
23022
- if (!match) return false;
23023
- const timestamp = Number(match[1]);
23024
- if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
23025
- const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
23026
- const given = Buffer.from(match[2], "hex");
23027
- return given.length === expected.length && crypto.timingSafeEqual(given, expected);
23028
- }
23029
- var DeliveryError = class extends Error {
23030
- /**
23031
- * @param {string} code Stable code.
23032
- * @param {boolean} retryable Whether another attempt may succeed.
23033
- * @param {number|null} [status] HTTP status, when there was one.
23034
- */
23035
- constructor(code, retryable, status = null) {
23036
- super(code);
23037
- this.name = "DeliveryError";
23038
- this.code = code;
23039
- this.retryable = retryable;
23040
- this.status = status;
23041
- }
23042
- };
23043
- var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
23044
- function httpsPost({ url, address, headers, body, timeoutMs }) {
23045
- return new Promise((resolve, reject) => {
23046
- const request = https.request(
23047
- {
23048
- protocol: "https:",
23049
- hostname: url.hostname,
23050
- port: url.port || 443,
23051
- path: `${url.pathname}${url.search}`,
23052
- method: "POST",
23053
- headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
23054
- servername: net.isIP(url.hostname) ? void 0 : url.hostname,
23055
- timeout: timeoutMs,
23056
- // Pinned to the address that passed the check: no second lookup.
23057
- lookup: (_hostname, options, callback) => {
23058
- if (options && options.all) callback(null, [address]);
23059
- else callback(null, address.address, address.family);
23060
- }
23061
- },
23062
- (response) => {
23063
- let received = 0;
23064
- response.on("data", (chunk) => {
23065
- received += chunk.length;
23066
- if (received > MAX_RESPONSE_BYTES) response.destroy();
23067
- });
23068
- response.on("end", () => resolve(response.statusCode || 0));
23069
- response.on("close", () => resolve(response.statusCode || 0));
23070
- response.on("error", () => resolve(response.statusCode || 0));
23071
- }
23072
- );
23073
- request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
23074
- request.on(
23075
- "error",
23076
- (err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
23077
- );
23078
- request.end(body);
23079
- });
23080
- }
23081
- async function deliverOnce({
23082
- url,
23083
- body,
23084
- headers,
23085
- resolve = resolveAll,
23086
- post = httpsPost,
23087
- timeoutMs = TIMEOUT_MS
23088
- }) {
23089
- let parsed;
23090
- try {
23091
- parsed = new URL(url);
23092
- } catch {
23093
- throw new DeliveryError("invalid_url", false);
23094
- }
23095
- if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
23096
- throw new DeliveryError("invalid_url", false);
23097
- }
23098
- const host = parsed.hostname.replace(/^\[|\]$/g, "");
23099
- let addresses;
23100
- if (net.isIP(host)) {
23101
- addresses = [{ address: host, family: net.isIP(host) }];
23102
- } else {
23103
- try {
23104
- addresses = await resolve(host);
23105
- } catch {
23106
- throw new DeliveryError("dns_failed", true);
23107
- }
23108
- }
23109
- if (!Array.isArray(addresses) || addresses.length === 0)
23110
- throw new DeliveryError("dns_failed", true);
23111
- if (addresses.some((entry) => isBlockedAddress(entry.address))) {
23112
- throw new DeliveryError("address_not_allowed", false);
23113
- }
23114
- const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
23115
- if (status >= 200 && status < 300) return { status };
23116
- if (status >= 300 && status < 400)
23117
- throw new DeliveryError("redirect_not_followed", false, status);
23118
- throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
23119
- }
23120
- function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
23121
- const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
23122
- return {
23123
- id,
23124
- body,
23125
- headers: {
23126
- "Content-Type": "application/json",
23127
- "User-Agent": USER_AGENT,
23128
- [EVENT_HEADER]: event,
23129
- [DELIVERY_HEADER]: id,
23130
- [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
23131
- }
23132
- };
23133
- }
23134
- async function deliverWithRetries({
23135
- delays = RETRY_DELAYS_MS,
23136
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
23137
- ...request
23138
- }) {
23139
- let attempts = 0;
23140
- let last = { ok: false, status: null, code: "not_sent" };
23141
- for (const delay of delays) {
23142
- if (delay > 0) await sleep(delay);
23143
- attempts += 1;
23144
- try {
23145
- const { status } = await deliverOnce(request);
23146
- return { ok: true, status, code: null, attempts };
23147
- } catch (err) {
23148
- const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
23149
- last = { ok: false, status: error.status, code: error.code };
23150
- if (!error.retryable) break;
23151
- }
23152
- }
23153
- return { ...last, attempts };
23154
- }
23155
- module2.exports = {
23156
- DELIVERY_HEADER,
23157
- DeliveryError,
23158
- EVENT_HEADER,
23159
- RETRY_DELAYS_MS,
23160
- SIGNATURE_HEADER,
23161
- buildSignedRequest,
23162
- deliverOnce,
23163
- deliverWithRetries,
23164
- isBlockedAddress,
23165
- signPayload,
23166
- verifySignature
23167
- };
23168
- }
23169
- });
23170
-
23171
24578
  // server/src/services/webhooks.js
23172
24579
  var require_webhooks2 = __commonJS({
23173
24580
  "server/src/services/webhooks.js"(exports2, module2) {
@@ -23446,12 +24853,14 @@ var require_rate_limit = __commonJS({
23446
24853
  "use strict";
23447
24854
  var { getPluginSettings } = require_settings_loader();
23448
24855
  var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
24856
+ var { ipBucket } = require_admin_request_info();
23449
24857
  var callerKey = (ctx) => {
23450
24858
  const userId = ctx.state?.user?.id;
23451
24859
  if (userId) return `u:${userId}`;
23452
24860
  const tokenId = ctx.state?.auth?.credentials?.id ?? ctx.state?.auth?.credentials?.token ?? null;
23453
24861
  if (tokenId) return `t:${String(tokenId).slice(-16)}`;
23454
- return `ip:${ctx.request.ip || ctx.ip || "unknown"}`;
24862
+ const ip = ctx.request.ip || ctx.ip || "";
24863
+ return `ip:${ipBucket(ip) || ip || "unknown"}`;
23455
24864
  };
23456
24865
  var routeKey = (ctx) => {
23457
24866
  const route = ctx.state?.route;
@@ -23656,7 +25065,7 @@ var require_can_impersonate = __commonJS({
23656
25065
  return false;
23657
25066
  }
23658
25067
  };
23659
- return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins");
25068
+ return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins") || can("plugin::magic-sessionmanager.impersonate.admins.sign-in");
23660
25069
  };
23661
25070
  }
23662
25071
  });