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
@@ -1477,10 +1477,249 @@ var require_policy_settings = __commonJS({
1477
1477
  }
1478
1478
  });
1479
1479
 
1480
+ // server/src/utils/webhook-delivery.js
1481
+ var require_webhook_delivery = __commonJS({
1482
+ "server/src/utils/webhook-delivery.js"(exports, module) {
1483
+ "use strict";
1484
+ var crypto = __require("node:crypto");
1485
+ var dns = __require("node:dns");
1486
+ var https = __require("node:https");
1487
+ var net = __require("node:net");
1488
+ var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
1489
+ var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
1490
+ var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
1491
+ var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
1492
+ var TIMEOUT_MS = 5e3;
1493
+ var DEADLINE_MS = 1e4;
1494
+ var MAX_RESPONSE_BYTES = 64 * 1024;
1495
+ var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
1496
+ var BLOCKED = (() => {
1497
+ const list = new net.BlockList();
1498
+ for (const [address, prefix] of [
1499
+ ["0.0.0.0", 8],
1500
+ ["10.0.0.0", 8],
1501
+ ["100.64.0.0", 10],
1502
+ ["127.0.0.0", 8],
1503
+ ["169.254.0.0", 16],
1504
+ ["172.16.0.0", 12],
1505
+ ["192.0.0.0", 24],
1506
+ ["192.0.2.0", 24],
1507
+ ["192.88.99.0", 24],
1508
+ ["192.168.0.0", 16],
1509
+ ["198.18.0.0", 15],
1510
+ ["198.51.100.0", 24],
1511
+ ["203.0.113.0", 24],
1512
+ ["224.0.0.0", 4],
1513
+ ["240.0.0.0", 4]
1514
+ ]) {
1515
+ list.addSubnet(address, prefix, "ipv4");
1516
+ }
1517
+ for (const [address, prefix] of [
1518
+ // IPv4-compatible (::a.b.c.d, deprecated) and IPv4-translated
1519
+ // (::ffff:0:a.b.c.d, RFC 2765) forms, which include the unspecified and
1520
+ // loopback addresses (security review 2, hardening 1).
1521
+ ["::", 96],
1522
+ ["::ffff:0:0:0", 96],
1523
+ // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
1524
+ // checks them against the IPv4 rules above, and a listed /96 would
1525
+ // match every IPv4 address.
1526
+ ["64:ff9b::", 96],
1527
+ ["64:ff9b:1::", 48],
1528
+ ["100::", 64],
1529
+ ["2001::", 23],
1530
+ ["2001:db8::", 32],
1531
+ ["2002::", 16],
1532
+ ["fc00::", 7],
1533
+ ["fe80::", 10],
1534
+ ["fec0::", 10],
1535
+ ["ff00::", 8]
1536
+ ]) {
1537
+ list.addSubnet(address, prefix, "ipv6");
1538
+ }
1539
+ return list;
1540
+ })();
1541
+ function isBlockedAddress(address) {
1542
+ let value = String(address || "").trim();
1543
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
1544
+ value = value.slice(7);
1545
+ }
1546
+ const version = net.isIP(value);
1547
+ if (version === 0) return true;
1548
+ return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
1549
+ }
1550
+ function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
1551
+ const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
1552
+ return `t=${timestamp},v1=${digest}`;
1553
+ }
1554
+ function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
1555
+ const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
1556
+ if (!match) return false;
1557
+ const timestamp = Number(match[1]);
1558
+ if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
1559
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
1560
+ const given = Buffer.from(match[2], "hex");
1561
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
1562
+ }
1563
+ var DeliveryError = class extends Error {
1564
+ /**
1565
+ * @param {string} code Stable code.
1566
+ * @param {boolean} retryable Whether another attempt may succeed.
1567
+ * @param {number|null} [status] HTTP status, when there was one.
1568
+ */
1569
+ constructor(code, retryable, status = null) {
1570
+ super(code);
1571
+ this.name = "DeliveryError";
1572
+ this.code = code;
1573
+ this.retryable = retryable;
1574
+ this.status = status;
1575
+ }
1576
+ };
1577
+ var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
1578
+ function httpsPost({ url, address, headers, body, timeoutMs, deadlineMs = DEADLINE_MS }) {
1579
+ return new Promise((resolve, reject) => {
1580
+ const request = https.request(
1581
+ {
1582
+ protocol: "https:",
1583
+ hostname: url.hostname,
1584
+ port: url.port || 443,
1585
+ path: `${url.pathname}${url.search}`,
1586
+ method: "POST",
1587
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
1588
+ servername: net.isIP(url.hostname) ? void 0 : url.hostname,
1589
+ timeout: timeoutMs,
1590
+ signal: AbortSignal.timeout(deadlineMs),
1591
+ // Pinned to the address that passed the check: no second lookup.
1592
+ lookup: (_hostname, options, callback) => {
1593
+ if (options && options.all) callback(null, [address]);
1594
+ else callback(null, address.address, address.family);
1595
+ }
1596
+ },
1597
+ (response) => {
1598
+ let received = 0;
1599
+ response.on("data", (chunk) => {
1600
+ received += chunk.length;
1601
+ if (received > MAX_RESPONSE_BYTES) response.destroy();
1602
+ });
1603
+ response.on("end", () => resolve(response.statusCode || 0));
1604
+ response.on("close", () => resolve(response.statusCode || 0));
1605
+ response.on("error", () => resolve(response.statusCode || 0));
1606
+ }
1607
+ );
1608
+ request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
1609
+ request.on(
1610
+ "error",
1611
+ (err) => reject(
1612
+ err instanceof DeliveryError ? err : err?.name === "AbortError" ? new DeliveryError("timeout", true) : new DeliveryError("network_error", true)
1613
+ )
1614
+ );
1615
+ request.end(body);
1616
+ });
1617
+ }
1618
+ async function deliverOnce({
1619
+ url,
1620
+ body,
1621
+ headers,
1622
+ resolve = resolveAll,
1623
+ post = httpsPost,
1624
+ timeoutMs = TIMEOUT_MS,
1625
+ deadlineMs = DEADLINE_MS
1626
+ }) {
1627
+ let parsed;
1628
+ try {
1629
+ parsed = new URL(url);
1630
+ } catch {
1631
+ throw new DeliveryError("invalid_url", false);
1632
+ }
1633
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
1634
+ throw new DeliveryError("invalid_url", false);
1635
+ }
1636
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
1637
+ let addresses;
1638
+ if (net.isIP(host)) {
1639
+ addresses = [{ address: host, family: net.isIP(host) }];
1640
+ } else {
1641
+ try {
1642
+ addresses = await resolve(host);
1643
+ } catch {
1644
+ throw new DeliveryError("dns_failed", true);
1645
+ }
1646
+ }
1647
+ if (!Array.isArray(addresses) || addresses.length === 0)
1648
+ throw new DeliveryError("dns_failed", true);
1649
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
1650
+ throw new DeliveryError("address_not_allowed", false);
1651
+ }
1652
+ const status = await post({
1653
+ url: parsed,
1654
+ address: addresses[0],
1655
+ headers,
1656
+ body,
1657
+ timeoutMs,
1658
+ deadlineMs
1659
+ });
1660
+ if (status >= 200 && status < 300) return { status };
1661
+ if (status >= 300 && status < 400)
1662
+ throw new DeliveryError("redirect_not_followed", false, status);
1663
+ throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
1664
+ }
1665
+ function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
1666
+ const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
1667
+ return {
1668
+ id,
1669
+ body,
1670
+ headers: {
1671
+ "Content-Type": "application/json",
1672
+ "User-Agent": USER_AGENT,
1673
+ [EVENT_HEADER]: event,
1674
+ [DELIVERY_HEADER]: id,
1675
+ [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
1676
+ }
1677
+ };
1678
+ }
1679
+ async function deliverWithRetries({
1680
+ delays = RETRY_DELAYS_MS,
1681
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
1682
+ ...request
1683
+ }) {
1684
+ let attempts = 0;
1685
+ let last = { ok: false, status: null, code: "not_sent" };
1686
+ for (const delay of delays) {
1687
+ if (delay > 0) await sleep(delay);
1688
+ attempts += 1;
1689
+ try {
1690
+ const { status } = await deliverOnce(request);
1691
+ return { ok: true, status, code: null, attempts };
1692
+ } catch (err) {
1693
+ const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
1694
+ last = { ok: false, status: error.status, code: error.code };
1695
+ if (!error.retryable) break;
1696
+ }
1697
+ }
1698
+ return { ...last, attempts };
1699
+ }
1700
+ module.exports = {
1701
+ DEADLINE_MS,
1702
+ DELIVERY_HEADER,
1703
+ DeliveryError,
1704
+ EVENT_HEADER,
1705
+ RETRY_DELAYS_MS,
1706
+ SIGNATURE_HEADER,
1707
+ buildSignedRequest,
1708
+ deliverOnce,
1709
+ deliverWithRetries,
1710
+ isBlockedAddress,
1711
+ signPayload,
1712
+ verifySignature
1713
+ };
1714
+ }
1715
+ });
1716
+
1480
1717
  // server/src/utils/detection-settings.js
1481
1718
  var require_detection_settings = __commonJS({
1482
1719
  "server/src/utils/detection-settings.js"(exports, module) {
1483
1720
  "use strict";
1721
+ var net = __require("node:net");
1722
+ var { isBlockedAddress } = require_webhook_delivery();
1484
1723
  var WEBHOOK_EVENTS = Object.freeze([
1485
1724
  "login.success",
1486
1725
  "login.suspicious",
@@ -1565,6 +1804,8 @@ var require_detection_settings = __commonJS({
1565
1804
  if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
1566
1805
  return null;
1567
1806
  }
1807
+ const literal = host.replace(/^\[|\]$/g, "");
1808
+ if (net.isIP(literal) && isBlockedAddress(literal)) return null;
1568
1809
  return parsed.toString();
1569
1810
  }
1570
1811
  function normalizeEventList(value) {
@@ -1935,6 +2176,89 @@ var require_impersonation_rules = __commonJS({
1935
2176
  }
1936
2177
  });
1937
2178
 
2179
+ // server/src/utils/trusted-proxies.js
2180
+ var require_trusted_proxies = __commonJS({
2181
+ "server/src/utils/trusted-proxies.js"(exports, module) {
2182
+ "use strict";
2183
+ var { parseTrustedAddress } = require_policy_settings();
2184
+ var MAX_TRUSTED_PROXIES = 50;
2185
+ function normalizeTrustedProxies(value) {
2186
+ if (!Array.isArray(value)) return [];
2187
+ const out = [];
2188
+ for (const entry of value.slice(0, MAX_TRUSTED_PROXIES)) {
2189
+ const parsed = parseTrustedAddress(entry);
2190
+ if (parsed && !out.includes(parsed.text)) out.push(parsed.text);
2191
+ }
2192
+ return out;
2193
+ }
2194
+ function isLegacyTrustAll(value) {
2195
+ return value === true;
2196
+ }
2197
+ function validateTrustedProxies(value) {
2198
+ if (typeof value === "boolean") return { value: [], error: null, legacyTrue: value };
2199
+ if (!Array.isArray(value) || value.length > MAX_TRUSTED_PROXIES) {
2200
+ return {
2201
+ value: null,
2202
+ legacyTrue: false,
2203
+ error: {
2204
+ path: ["trustedProxies"],
2205
+ message: `trustedProxies must be a list of at most ${MAX_TRUSTED_PROXIES} IP addresses or CIDR ranges`
2206
+ }
2207
+ };
2208
+ }
2209
+ const parsed = value.map(parseTrustedAddress);
2210
+ const invalid = parsed.findIndex((entry) => entry === null);
2211
+ if (invalid !== -1) {
2212
+ return {
2213
+ value: null,
2214
+ legacyTrue: false,
2215
+ error: {
2216
+ path: ["trustedProxies", invalid],
2217
+ message: "Each trusted proxy must be an IP address or a CIDR range such as 10.0.0.0/8"
2218
+ }
2219
+ };
2220
+ }
2221
+ return {
2222
+ value: [...new Set(parsed.map((entry) => (
2223
+ /** @type {any} */
2224
+ entry.text
2225
+ )))],
2226
+ error: null,
2227
+ legacyTrue: false
2228
+ };
2229
+ }
2230
+ 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.";
2231
+ async function migrateLegacyProxyTrust(strapi2, log) {
2232
+ const { withPluginStoreKey } = require_plugin_store();
2233
+ const { notifySettingsChanged } = require_settings_loader();
2234
+ const config = isLegacyTrustAll(
2235
+ strapi2.config.get("plugin::magic-sessionmanager")?.trustedProxies
2236
+ );
2237
+ const store = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
2238
+ let stored = isLegacyTrustAll((await store.get({ key: "settings" }))?.trustedProxies);
2239
+ if (stored) {
2240
+ stored = await withPluginStoreKey(strapi2, "settings", async (scoped) => {
2241
+ const value = await scoped.get({ key: "settings" });
2242
+ if (!value || !isLegacyTrustAll(value.trustedProxies)) return false;
2243
+ await scoped.set({ key: "settings", value: { ...value, trustedProxies: [] } });
2244
+ return true;
2245
+ });
2246
+ if (stored) await notifySettingsChanged(strapi2);
2247
+ }
2248
+ if (stored || config) log.warn(LEGACY_WARNING);
2249
+ return { stored, config };
2250
+ }
2251
+ module.exports = {
2252
+ LEGACY_WARNING,
2253
+ MAX_TRUSTED_PROXIES,
2254
+ isLegacyTrustAll,
2255
+ migrateLegacyProxyTrust,
2256
+ normalizeTrustedProxies,
2257
+ validateTrustedProxies
2258
+ };
2259
+ }
2260
+ });
2261
+
1938
2262
  // server/src/utils/settings-loader.js
1939
2263
  var require_settings_loader = __commonJS({
1940
2264
  "server/src/utils/settings-loader.js"(exports, module) {
@@ -1943,6 +2267,7 @@ var require_settings_loader = __commonJS({
1943
2267
  var { normalizePolicySettings } = require_policy_settings();
1944
2268
  var { normalizeDetectionSettings } = require_detection_settings();
1945
2269
  var { normalizeImpersonationSettings } = require_impersonation_rules();
2270
+ var { normalizeTrustedProxies } = require_trusted_proxies();
1946
2271
  var PLUGIN_ID = "magic-sessionmanager";
1947
2272
  var SETTINGS_KEY = "settings";
1948
2273
  var CACHE_TTL_MS = 30 * 1e3;
@@ -2072,7 +2397,8 @@ var require_settings_loader = __commonJS({
2072
2397
  out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 7, 730);
2073
2398
  }
2074
2399
  if (stored.trustedProxies !== void 0) {
2075
- out.trustedProxies = stored.trustedProxies;
2400
+ const proxies = normalizeTrustedProxies(stored.trustedProxies);
2401
+ if (proxies.length > 0) out.trustedProxies = proxies;
2076
2402
  }
2077
2403
  Object.assign(out, normalizePolicySettings(stored));
2078
2404
  Object.assign(out, normalizeDetectionSettings(stored));
@@ -2191,6 +2517,8 @@ var require_security_log_model = __commonJS({
2191
2517
  SETTINGS_UPDATED: "settings.updated",
2192
2518
  LOG_RETENTION_PURGED: "security-log.retention.purged",
2193
2519
  LOG_READ: "security-log.read",
2520
+ // 4.22.1: SESSION_ENCRYPTION_KEY shorter than 32 bytes, once per key.
2521
+ CONFIG_WEAK_KEY: "config.encryption-key.weak",
2194
2522
  // App users (Users & Permissions), 4.17.
2195
2523
  USER_SIGN_IN_FAILED: "user.sign-in.failed",
2196
2524
  USER_SIGN_IN_REFUSED: "user.sign-in.refused",
@@ -2208,7 +2536,11 @@ var require_security_log_model = __commonJS({
2208
2536
  IMPERSONATION_STARTED: "impersonation.started",
2209
2537
  IMPERSONATION_ENDED: "impersonation.ended",
2210
2538
  IMPERSONATION_EXPIRED: "impersonation.expired",
2211
- IMPERSONATION_REFUSED: "impersonation.refused"
2539
+ IMPERSONATION_REFUSED: "impersonation.refused",
2540
+ // 4.23: a change made while signed in as another admin. Actor = the real
2541
+ // admin, target and `meta.impersonating` = the admin signed in as, plus
2542
+ // the method and path (no query, no body).
2543
+ IMPERSONATION_WRITE: "impersonation.write"
2212
2544
  });
2213
2545
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
2214
2546
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
@@ -2217,7 +2549,8 @@ var require_security_log_model = __commonJS({
2217
2549
  SECURITY_EVENTS.IMPERSONATION_STARTED,
2218
2550
  SECURITY_EVENTS.IMPERSONATION_ENDED,
2219
2551
  SECURITY_EVENTS.IMPERSONATION_EXPIRED,
2220
- SECURITY_EVENTS.IMPERSONATION_REFUSED
2552
+ SECURITY_EVENTS.IMPERSONATION_REFUSED,
2553
+ SECURITY_EVENTS.IMPERSONATION_WRITE
2221
2554
  ]);
2222
2555
  function dropRankOf(event) {
2223
2556
  if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
@@ -2254,14 +2587,23 @@ var require_security_log_model = __commonJS({
2254
2587
  var ADMIN_LOG_EVENTS = Object.freeze([
2255
2588
  SECURITY_EVENTS.SETTINGS_UPDATED,
2256
2589
  SECURITY_EVENTS.LOG_READ,
2257
- SECURITY_EVENTS.LOG_RETENTION_PURGED
2590
+ SECURITY_EVENTS.LOG_RETENTION_PURGED,
2591
+ SECURITY_EVENTS.CONFIG_WEAK_KEY
2592
+ ]);
2593
+ var ADMIN_IMPERSONATION_EVENTS = Object.freeze([
2594
+ SECURITY_EVENTS.IMPERSONATION_STARTED,
2595
+ SECURITY_EVENTS.IMPERSONATION_ENDED,
2596
+ SECURITY_EVENTS.IMPERSONATION_EXPIRED,
2597
+ SECURITY_EVENTS.IMPERSONATION_REFUSED,
2598
+ SECURITY_EVENTS.IMPERSONATION_WRITE
2258
2599
  ]);
2259
2600
  var SIGN_IN_FILTERS = Object.freeze({
2260
2601
  all: [...ADMIN_SIGN_IN_EVENTS, ...ADMIN_LOG_EVENTS],
2261
2602
  succeeded: [SECURITY_EVENTS.ADMIN_SIGN_IN],
2262
2603
  failed: [SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED, SECURITY_EVENTS.ADMIN_LOCKOUT],
2263
2604
  "signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED],
2264
- changes: ADMIN_LOG_EVENTS
2605
+ changes: ADMIN_LOG_EVENTS,
2606
+ impersonation: ADMIN_IMPERSONATION_EVENTS
2265
2607
  });
2266
2608
  var CONTENT_ACTIONS = Object.freeze([
2267
2609
  "view",
@@ -2463,6 +2805,7 @@ var require_security_log_model = __commonJS({
2463
2805
  USER_SIGN_IN_EVENTS,
2464
2806
  ACTOR_TYPES,
2465
2807
  ADMIN_CONTENT_EVENTS,
2808
+ ADMIN_IMPERSONATION_EVENTS,
2466
2809
  ADMIN_LOG_EVENTS,
2467
2810
  ADMIN_SIGN_IN_EVENTS,
2468
2811
  CONTENT_ACTIONS,
@@ -2663,7 +3006,177 @@ var require_security_log_hardening = __commonJS({
2663
3006
  }
2664
3007
  });
2665
3008
 
2666
- // server/src/register.js
3009
+ // server/src/utils/graphql-impersonation-guard.js
3010
+ var require_graphql_impersonation_guard = __commonJS({
3011
+ "server/src/utils/graphql-impersonation-guard.js"(exports, module) {
3012
+ "use strict";
3013
+ var { errors } = __require("@strapi/utils");
3014
+ var MARK = /* @__PURE__ */ Symbol.for("magic-sessionmanager.graphql-impersonation-guard");
3015
+ var MESSAGE = "Not allowed while impersonating";
3016
+ var REASON = "impersonation-mutation";
3017
+ function impersonationRefusal() {
3018
+ const error = new errors.ForbiddenError(MESSAGE, { reason: REASON });
3019
+ Object.defineProperty(error, "extensions", {
3020
+ value: {
3021
+ code: "FORBIDDEN",
3022
+ http: { status: 403 },
3023
+ error: { name: "ForbiddenError", message: MESSAGE, details: { reason: REASON } }
3024
+ },
3025
+ enumerable: false
3026
+ });
3027
+ return error;
3028
+ }
3029
+ function impersonationOf(contextValue) {
3030
+ const mark = contextValue?.koaContext?.state?.magicImpersonation ?? contextValue?.state?.magicImpersonation;
3031
+ return mark && typeof mark === "object" && typeof mark.id === "string" ? mark : null;
3032
+ }
3033
+ function createImpersonationApolloPlugin(strapi2) {
3034
+ return {
3035
+ [MARK]: true,
3036
+ async requestDidStart() {
3037
+ return {
3038
+ /**
3039
+ * @param {any} requestContext Apollo request context.
3040
+ * @returns {Promise<void>}
3041
+ * @throws {Error} ForbiddenError (HTTP 403, code FORBIDDEN) for a mutation while impersonating.
3042
+ */
3043
+ async didResolveOperation(requestContext) {
3044
+ if (requestContext?.operation?.operation !== "mutation") return;
3045
+ const impersonation = impersonationOf(requestContext.contextValue);
3046
+ if (!impersonation) return;
3047
+ try {
3048
+ strapi2.plugin("magic-sessionmanager").service("impersonation").recordRefusedCall(impersonation, "mutation");
3049
+ } catch {
3050
+ }
3051
+ throw impersonationRefusal();
3052
+ }
3053
+ };
3054
+ }
3055
+ };
3056
+ }
3057
+ function installGraphqlImpersonationGuard(strapi2, log) {
3058
+ let graphql;
3059
+ try {
3060
+ graphql = strapi2.plugin("graphql") || null;
3061
+ } catch {
3062
+ graphql = null;
3063
+ }
3064
+ if (!graphql) return false;
3065
+ if (typeof strapi2.config?.get !== "function" || typeof strapi2.config?.set !== "function") {
3066
+ return false;
3067
+ }
3068
+ try {
3069
+ const key = "plugin::graphql.apolloServer";
3070
+ const current = strapi2.config.get(key);
3071
+ const server = current && typeof current === "object" ? current : {};
3072
+ const plugins = Array.isArray(server.plugins) ? server.plugins : [];
3073
+ if (plugins.some((plugin) => plugin && plugin[MARK])) return true;
3074
+ strapi2.config.set(key, {
3075
+ ...server,
3076
+ plugins: [...plugins, createImpersonationApolloPlugin(strapi2)]
3077
+ });
3078
+ } catch (err) {
3079
+ log?.warn?.("[IMPERSONATION] GraphQL guard could not be installed:", err?.name || "Error");
3080
+ return false;
3081
+ }
3082
+ log?.info?.("[IMPERSONATION] GraphQL mutations are refused while impersonating");
3083
+ return true;
3084
+ }
3085
+ module.exports = {
3086
+ createImpersonationApolloPlugin,
3087
+ impersonationRefusal,
3088
+ installGraphqlImpersonationGuard
3089
+ };
3090
+ }
3091
+ });
3092
+
3093
+ // server/src/utils/auth-controller-guard.js
3094
+ var require_auth_controller_guard = __commonJS({
3095
+ "server/src/utils/auth-controller-guard.js"(exports, module) {
3096
+ "use strict";
3097
+ var WRAPPED = /* @__PURE__ */ Symbol.for("magic-sessionmanager.auth-controller.wrapped");
3098
+ var GUARDED_ACTIONS = Object.freeze({
3099
+ callback: "callback",
3100
+ register: "newSession",
3101
+ resetPassword: "newSession",
3102
+ emailConfirmation: "newSession"
3103
+ });
3104
+ var handlersByStrapi = /* @__PURE__ */ new WeakMap();
3105
+ function installAuthControllerGuard(strapi2, log) {
3106
+ let controller;
3107
+ try {
3108
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3109
+ } catch {
3110
+ controller = null;
3111
+ }
3112
+ if (!controller || typeof controller !== "object") {
3113
+ log?.warn?.(
3114
+ "[AUTH] Users & Permissions auth controller not found; sign-in checks use paths only"
3115
+ );
3116
+ return [];
3117
+ }
3118
+ const wrapped = [];
3119
+ for (const [action, kind] of Object.entries(GUARDED_ACTIONS)) {
3120
+ const original = controller[action];
3121
+ if (typeof original !== "function") continue;
3122
+ if (original[WRAPPED]) {
3123
+ wrapped.push(action);
3124
+ continue;
3125
+ }
3126
+ const guarded = async function magicSessionAuthGuard(ctx, ...rest) {
3127
+ const run = () => original.call(this, ctx, ...rest);
3128
+ const handlers = handlersByStrapi.get(strapi2);
3129
+ if (!handlers || typeof handlers[kind] !== "function") return run();
3130
+ return handlers[kind](ctx, run);
3131
+ };
3132
+ Object.defineProperty(guarded, WRAPPED, { value: original });
3133
+ controller[action] = guarded;
3134
+ wrapped.push(action);
3135
+ }
3136
+ return wrapped;
3137
+ }
3138
+ function setAuthControllerHandlers(strapi2, handlers) {
3139
+ if (handlers) handlersByStrapi.set(strapi2, handlers);
3140
+ else handlersByStrapi.delete(strapi2);
3141
+ }
3142
+ function uninstallAuthControllerGuard(strapi2) {
3143
+ setAuthControllerHandlers(strapi2, null);
3144
+ let controller;
3145
+ try {
3146
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3147
+ } catch {
3148
+ return;
3149
+ }
3150
+ if (!controller) return;
3151
+ for (const action of Object.keys(GUARDED_ACTIONS)) {
3152
+ const original = controller[action]?.[WRAPPED];
3153
+ if (typeof original === "function") controller[action] = original;
3154
+ }
3155
+ }
3156
+ var INVALID_CREDENTIALS_MESSAGE = "Invalid identifier or password";
3157
+ function classifyCallbackOutcome(thrown, ctx) {
3158
+ if (thrown) {
3159
+ const error = (
3160
+ /** @type {any} */
3161
+ thrown
3162
+ );
3163
+ return error?.name === "ValidationError" && error?.message === INVALID_CREDENTIALS_MESSAGE ? "failure" : "neutral";
3164
+ }
3165
+ const body = ctx?.body;
3166
+ return body && typeof body === "object" && body.jwt ? "success" : "neutral";
3167
+ }
3168
+ module.exports = {
3169
+ GUARDED_ACTIONS,
3170
+ INVALID_CREDENTIALS_MESSAGE,
3171
+ classifyCallbackOutcome,
3172
+ installAuthControllerGuard,
3173
+ setAuthControllerHandlers,
3174
+ uninstallAuthControllerGuard
3175
+ };
3176
+ }
3177
+ });
3178
+
3179
+ // server/src/register.js
2667
3180
  var require_register = __commonJS({
2668
3181
  "server/src/register.js"(exports, module) {
2669
3182
  "use strict";
@@ -2672,6 +3185,8 @@ var require_register = __commonJS({
2672
3185
  var { isCallerRevocationScope } = require_block_revocation_scope();
2673
3186
  var { checkStrapiVersion } = require_strapi_version();
2674
3187
  var { disableGraphqlShadowCrud } = require_security_log_hardening();
3188
+ var { installGraphqlImpersonationGuard } = require_graphql_impersonation_guard();
3189
+ var { installAuthControllerGuard } = require_auth_controller_guard();
2675
3190
  var USER_UID = "plugin::users-permissions.user";
2676
3191
  module.exports = async ({ strapi: strapi2 }) => {
2677
3192
  const log = createLogger(strapi2);
@@ -2763,13 +3278,25 @@ var require_register = __commonJS({
2763
3278
  // their own.
2764
3279
  {
2765
3280
  section: "plugins",
2766
- displayName: "View as admin (read-only permission preview)",
3281
+ displayName: "View admin permissions (read-only preview)",
2767
3282
  uid: "impersonate.admins",
2768
3283
  subCategory: "Impersonation",
2769
3284
  pluginName: "magic-sessionmanager"
3285
+ },
3286
+ // "Sign in as this admin" (4.23): a real admin session of another admin
3287
+ // in a separate tab, read-only unless changes are allowed. The same
3288
+ // anti-escalation rules as the preview; only on tested Strapi releases.
3289
+ {
3290
+ section: "plugins",
3291
+ displayName: "Sign in as another admin",
3292
+ uid: "impersonate.admins.sign-in",
3293
+ subCategory: "Impersonation",
3294
+ pluginName: "magic-sessionmanager"
2770
3295
  }
2771
3296
  ]);
2772
3297
  disableGraphqlShadowCrud(strapi2, log);
3298
+ installGraphqlImpersonationGuard(strapi2, log);
3299
+ installAuthControllerGuard(strapi2, log);
2773
3300
  try {
2774
3301
  strapi2.db.lifecycles.subscribe(createContentApiPermissionsLifecycle(strapi2));
2775
3302
  } catch (err) {
@@ -2845,42 +3372,69 @@ var require_register = __commonJS({
2845
3372
  var require_getClientIp = __commonJS({
2846
3373
  "server/src/utils/getClientIp.js"(exports, module) {
2847
3374
  "use strict";
2848
- function isProxyTrusted(ctx) {
2849
- try {
2850
- const app = ctx?.app;
2851
- if (app && app.proxy === true) return true;
2852
- } catch {
3375
+ var net = __require("node:net");
3376
+ var { isTrustedAddress } = require_policy_settings();
3377
+ var { normalizeTrustedProxies } = require_trusted_proxies();
3378
+ var MAX_FORWARDED_LENGTH = 2048;
3379
+ var MAX_FORWARDED_HOPS = 20;
3380
+ var cleanIp = (ip) => {
3381
+ if (!ip) return "unknown";
3382
+ let value = String(ip).trim();
3383
+ if (value.startsWith("[")) {
3384
+ const bracketEnd = value.indexOf("]");
3385
+ if (bracketEnd !== -1) {
3386
+ value = value.substring(1, bracketEnd);
3387
+ }
3388
+ }
3389
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.substring(7))) {
3390
+ value = value.substring(7);
2853
3391
  }
3392
+ if (value.includes(".") && value.includes(":") && value.indexOf(":") === value.lastIndexOf(":")) {
3393
+ value = value.split(":")[0];
3394
+ }
3395
+ return value || "unknown";
3396
+ };
3397
+ function trustedProxyList(ctx) {
3398
+ const fromSettings = ctx?.state?.__magicSessionSettings?.trustedProxies;
3399
+ if (fromSettings !== void 0) return normalizeTrustedProxies(fromSettings);
2854
3400
  try {
2855
- const config = ctx?.state?.__magicSessionSettings || ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager") || {};
2856
- const trusted = config.trustedProxies;
2857
- if (trusted === true) return true;
2858
- if (Array.isArray(trusted) && trusted.length > 0) return true;
3401
+ const config = ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager");
3402
+ return normalizeTrustedProxies(config?.trustedProxies);
2859
3403
  } catch {
3404
+ return [];
2860
3405
  }
2861
- return false;
3406
+ }
3407
+ function socketAddress(ctx) {
3408
+ const raw = ctx?.req?.socket?.remoteAddress ?? ctx?.request?.socket?.remoteAddress;
3409
+ const cleaned = cleanIp(raw);
3410
+ return cleaned !== "unknown" && net.isIP(cleaned) ? cleaned : null;
3411
+ }
3412
+ function rightMostUntrustedHop(ctx, proxies) {
3413
+ const headers = ctx?.request?.headers || ctx?.request?.header || {};
3414
+ let header = headers["x-forwarded-for"];
3415
+ if (Array.isArray(header)) header = header.join(",");
3416
+ if (typeof header !== "string" || !header) return null;
3417
+ const hops = header.slice(0, MAX_FORWARDED_LENGTH).split(",").map((hop) => cleanIp(hop)).slice(-MAX_FORWARDED_HOPS);
3418
+ let lastValid = null;
3419
+ for (let index = hops.length - 1; index >= 0; index--) {
3420
+ const hop = hops[index];
3421
+ if (!net.isIP(hop)) return lastValid;
3422
+ if (!isTrustedAddress(proxies, hop)) return hop;
3423
+ lastValid = hop;
3424
+ }
3425
+ return lastValid;
2862
3426
  }
2863
3427
  var getClientIp = (ctx) => {
2864
3428
  try {
2865
- const headers = ctx.request.headers || ctx.request.header || {};
2866
- const trusted = isProxyTrusted(ctx);
2867
- if (trusted) {
2868
- if (headers["cf-connecting-ip"]) return cleanIp(headers["cf-connecting-ip"]);
2869
- if (headers["true-client-ip"]) return cleanIp(headers["true-client-ip"]);
2870
- if (headers["x-real-ip"]) return cleanIp(headers["x-real-ip"]);
2871
- if (headers["x-forwarded-for"]) {
2872
- const forwardedIps = headers["x-forwarded-for"].split(",");
2873
- const clientIp = forwardedIps[0].trim();
2874
- if (clientIp) return cleanIp(clientIp);
2875
- }
2876
- if (headers["x-client-ip"]) return cleanIp(headers["x-client-ip"]);
2877
- if (headers["x-cluster-client-ip"]) return cleanIp(headers["x-cluster-client-ip"]);
2878
- if (headers["forwarded"]) {
2879
- const match = headers["forwarded"].match(/for=([^;,\s]+)/);
2880
- if (match && match[1]) return cleanIp(match[1].replace(/"/g, ""));
2881
- }
2882
- }
2883
- if (ctx.request.ip) return cleanIp(ctx.request.ip);
3429
+ const proxies = trustedProxyList(ctx);
3430
+ if (proxies.length > 0) {
3431
+ const peer = socketAddress(ctx);
3432
+ if (peer && isTrustedAddress(proxies, peer)) {
3433
+ return rightMostUntrustedHop(ctx, proxies) || peer;
3434
+ }
3435
+ if (peer) return peer;
3436
+ }
3437
+ if (ctx?.request?.ip) return cleanIp(ctx.request.ip);
2884
3438
  return "unknown";
2885
3439
  } catch (error) {
2886
3440
  if (ctx?.app?.context?.strapi?.log?.debug) {
@@ -2892,24 +3446,8 @@ var require_getClientIp = __commonJS({
2892
3446
  return "unknown";
2893
3447
  }
2894
3448
  };
2895
- var cleanIp = (ip) => {
2896
- if (!ip) return "unknown";
2897
- ip = String(ip).trim();
2898
- if (ip.startsWith("[")) {
2899
- const bracketEnd = ip.indexOf("]");
2900
- if (bracketEnd !== -1) {
2901
- ip = ip.substring(1, bracketEnd);
2902
- }
2903
- }
2904
- if (ip.startsWith("::ffff:")) {
2905
- ip = ip.substring(7);
2906
- }
2907
- if (ip.includes(".") && ip.includes(":") && ip.indexOf(":") === ip.lastIndexOf(":")) {
2908
- ip = ip.split(":")[0];
2909
- }
2910
- return ip || "unknown";
2911
- };
2912
3449
  module.exports = getClientIp;
3450
+ module.exports.cleanIp = cleanIp;
2913
3451
  }
2914
3452
  });
2915
3453
 
@@ -2922,10 +3460,22 @@ var require_encryption = __commonJS({
2922
3460
  var IV_LENGTH = 16;
2923
3461
  var AUTH_TAG_LENGTH = 16;
2924
3462
  var warnedMissingKey = false;
3463
+ var warnedShortKey = false;
3464
+ var MIN_KEY_BYTES = 32;
3465
+ function isEncryptionKeyShort() {
3466
+ const envKey = process.env.SESSION_ENCRYPTION_KEY;
3467
+ return typeof envKey === "string" && envKey.length > 0 ? Buffer.byteLength(envKey, "utf8") < MIN_KEY_BYTES : false;
3468
+ }
2925
3469
  var isProduction = () => process.env.NODE_ENV === "production";
2926
3470
  function getEncryptionKey() {
2927
3471
  const envKey = process.env.SESSION_ENCRYPTION_KEY;
2928
3472
  if (envKey && envKey.length > 0) {
3473
+ if (!warnedShortKey && isEncryptionKeyShort()) {
3474
+ warnedShortKey = true;
3475
+ console.warn(
3476
+ `[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).`
3477
+ );
3478
+ }
2929
3479
  return crypto.createHash("sha256").update(envKey).digest();
2930
3480
  }
2931
3481
  if (isProduction()) {
@@ -3009,6 +3559,8 @@ var require_encryption = __commonJS({
3009
3559
  );
3010
3560
  }
3011
3561
  module.exports = {
3562
+ MIN_KEY_BYTES,
3563
+ isEncryptionKeyShort,
3012
3564
  derivePurposeKey,
3013
3565
  getEncryptionKeyCheck,
3014
3566
  encryptToken,
@@ -3558,7 +4110,6 @@ var require_auth_routes = __commonJS({
3558
4110
  "POST /api/magic-link/login-totp"
3559
4111
  ]);
3560
4112
  var FAILED_LOGIN_ROUTES = /* @__PURE__ */ new Set([
3561
- "POST /api/auth/local",
3562
4113
  "POST /api/magic-link/login-totp",
3563
4114
  "POST /api/magic-link/otp/verify",
3564
4115
  "POST /api/magic-link/verify-mfa-totp"
@@ -3601,18 +4152,24 @@ var require_auth_routes = __commonJS({
3601
4152
  if (!trimmed) return DEFAULT_API_PREFIX;
3602
4153
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
3603
4154
  }
4155
+ function normalizeRequestPath(path) {
4156
+ const value = path.toLowerCase().replace(/\/{2,}/g, "/");
4157
+ return value.length > 1 ? value.replace(/\/+$/, "") || "/" : value;
4158
+ }
3604
4159
  function toCanonicalApiPath(path, prefix) {
3605
4160
  if (typeof path !== "string") return null;
3606
- const normalized = normalizeApiPrefix(prefix);
3607
- if (normalized === DEFAULT_API_PREFIX) return path;
3608
- if (path === normalized) return DEFAULT_API_PREFIX;
3609
- if (path.startsWith(`${normalized}/`)) {
3610
- return `${DEFAULT_API_PREFIX}${path.slice(normalized.length)}`;
4161
+ const normalizedPath = normalizeRequestPath(path);
4162
+ const normalized = normalizeApiPrefix(prefix).toLowerCase();
4163
+ if (normalized === DEFAULT_API_PREFIX) return normalizedPath;
4164
+ if (normalizedPath === normalized) return DEFAULT_API_PREFIX;
4165
+ if (normalizedPath.startsWith(`${normalized}/`)) {
4166
+ return `${DEFAULT_API_PREFIX}${normalizedPath.slice(normalized.length)}`;
3611
4167
  }
3612
4168
  return null;
3613
4169
  }
3614
4170
  module.exports = {
3615
4171
  normalizeApiPrefix,
4172
+ normalizeRequestPath,
3616
4173
  toCanonicalApiPath,
3617
4174
  classifyJwtIssuingRequest,
3618
4175
  isFailedLoginTrackedPath,
@@ -4272,6 +4829,15 @@ var require_admin_request_info = __commonJS({
4272
4829
  }
4273
4830
  return null;
4274
4831
  }
4832
+ function ipBucket(ip) {
4833
+ const value = normalizeIp(typeof ip === "string" ? ip : "");
4834
+ if (!value) return null;
4835
+ if (net.isIPv4(value)) return value;
4836
+ if (net.isIPv6(value)) {
4837
+ return `${ipv6Groups(value).slice(0, 4).map((group) => group.toString(16)).join(":")}::/64`;
4838
+ }
4839
+ return null;
4840
+ }
4275
4841
  function getRequestUserAgent(ctx) {
4276
4842
  const value = ctx?.request?.headers?.["user-agent"];
4277
4843
  if (typeof value !== "string" || !value.trim()) return null;
@@ -4298,6 +4864,7 @@ var require_admin_request_info = __commonJS({
4298
4864
  module.exports = {
4299
4865
  MAX_USER_AGENT_LENGTH,
4300
4866
  anonymizeIp,
4867
+ ipBucket,
4301
4868
  describeUserAgent,
4302
4869
  getRequestIp,
4303
4870
  getSocketIp,
@@ -4598,6 +5165,7 @@ var require_login_lockout = __commonJS({
4598
5165
  "use strict";
4599
5166
  var { hashedKey } = require_coordination();
4600
5167
  var { isTrustedAddress } = require_policy_settings();
5168
+ var { ipBucket } = require_admin_request_info();
4601
5169
  var LOCK_PREFIX = "lock:";
4602
5170
  var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
4603
5171
  var MAX_LISTED_LOCKS = 200;
@@ -4607,7 +5175,7 @@ var require_login_lockout = __commonJS({
4607
5175
  if (!value || value.length > 254) return null;
4608
5176
  return value;
4609
5177
  }
4610
- var ipKey = (ip) => hashedKey("lf", ip);
5178
+ var ipKey = (ip) => hashedKey("lf", ipBucket(ip) || ip);
4611
5179
  var accountKey = (identifier) => hashedKey("la", identifier);
4612
5180
  function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
4613
5181
  const remainingSeconds = async (key) => {
@@ -4627,15 +5195,18 @@ var require_login_lockout = __commonJS({
4627
5195
  * Checks the locks and counts the attempt before the password check.
4628
5196
  *
4629
5197
  * @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
4630
- * accountMax: number}} input Client IP, normalised identifier, policy and the
4631
- * account threshold for this account's role.
5198
+ * accountMax: number, accountExempt?: boolean}} input Client IP, normalised
5199
+ * identifier, policy, the account threshold for this account's role, and
5200
+ * whether the request comes from a device the account is known to use.
4632
5201
  * @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
4633
5202
  * lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
4634
5203
  * @sideeffect Increments the shared counters.
4635
5204
  */
4636
- async reserve({ ip, identifier, policy, accountMax }) {
4637
- const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
4638
- const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
5205
+ async reserve({ ip, identifier, policy, accountMax, accountExempt = false }) {
5206
+ const knownIp = typeof ip === "string" && !!ip && ip !== "unknown";
5207
+ const trusted = knownIp && isTrustedAddress(policy.trusted, ip);
5208
+ const countIp = policy.ipMax > 0 && knownIp && !trusted;
5209
+ const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier && !trusted && accountExempt !== true;
4639
5210
  const reservation = {
4640
5211
  ipKey: countIp ? ipKey(
4641
5212
  /** @type {string} */
@@ -4688,10 +5259,8 @@ var require_login_lockout = __commonJS({
4688
5259
  */
4689
5260
  async settle(reservation, result, { policy, accountMax, display = {} }) {
4690
5261
  if (result === "success") {
4691
- for (const key of [reservation.ipKey, reservation.accountKey]) {
4692
- if (!key) continue;
4693
- await coordinator.clear(key);
4694
- }
5262
+ if (reservation.ipKey) await coordinator.release(reservation.ipKey);
5263
+ if (reservation.accountKey) await coordinator.clear(reservation.accountKey);
4695
5264
  return [];
4696
5265
  }
4697
5266
  if (result !== "failure") {
@@ -5155,6 +5724,15 @@ var require_sign_in_signals = __commonJS({
5155
5724
  });
5156
5725
  return Array.isArray(rows) ? rows : [];
5157
5726
  }
5727
+ async function isRecognizedDevice(strapi2, userDocumentId, { userAgent, deviceId }) {
5728
+ if (typeof userDocumentId !== "string" || !userDocumentId) return false;
5729
+ if (typeof deviceId !== "string" || !deviceId) return false;
5730
+ const deviceKey = deviceKeyOf(userAgent || "", deviceId);
5731
+ const count = await strapi2.documents(SESSION_UID).count({
5732
+ filters: { user: { documentId: userDocumentId }, deviceKey }
5733
+ });
5734
+ return Number(count) > 0;
5735
+ }
5158
5736
  function isNewDevice(previous, { deviceKey, userAgent }) {
5159
5737
  if (previous.length === 0) return false;
5160
5738
  if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
@@ -5183,7 +5761,7 @@ var require_sign_in_signals = __commonJS({
5183
5761
  const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
5184
5762
  if (!token) return null;
5185
5763
  const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
5186
- return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
5764
+ return `${base}${prefix}/magic-sessionmanager/not-me#token=${encodeURIComponent(token)}`;
5187
5765
  }
5188
5766
  async function runSignInSignals({
5189
5767
  strapi: strapi2,
@@ -5272,6 +5850,7 @@ var require_sign_in_signals = __commonJS({
5272
5850
  return outcome;
5273
5851
  }
5274
5852
  module.exports = {
5853
+ isRecognizedDevice,
5275
5854
  notMeUrl,
5276
5855
  runSignInSignals,
5277
5856
  deviceFamilies,
@@ -5376,7 +5955,11 @@ var require_impersonation_guard = __commonJS({
5376
5955
  `impersonation-${restricted}`
5377
5956
  );
5378
5957
  }
5379
- ctx.state.magicImpersonation = { id: impersonation.id, actorId: impersonation.actorId };
5958
+ ctx.state.magicImpersonation = {
5959
+ id: impersonation.id,
5960
+ actorId: impersonation.actorId,
5961
+ targetId: impersonation.targetId || null
5962
+ };
5380
5963
  try {
5381
5964
  await next();
5382
5965
  } finally {
@@ -5387,6 +5970,237 @@ var require_impersonation_guard = __commonJS({
5387
5970
  }
5388
5971
  });
5389
5972
 
5973
+ // server/src/utils/admin-sign-in-rules.js
5974
+ var require_admin_sign_in_rules = __commonJS({
5975
+ "server/src/utils/admin-sign-in-rules.js"(exports, module) {
5976
+ "use strict";
5977
+ var { REASON_MAX, REASON_MIN, cleanReason, normalizePath } = require_impersonation_rules();
5978
+ var ADMIN_SIGN_IN_ACTION = "plugin::magic-sessionmanager.impersonate.admins.sign-in";
5979
+ var TESTED_STRAPI = Object.freeze({ major: 5, minMinor: 50, maxMinor: 64 });
5980
+ var ADMIN_SIGN_IN_DURATIONS = Object.freeze([15, 30]);
5981
+ var ADMIN_DEVICE_PREFIX = "msm-admin-impersonation-";
5982
+ var LANDING_PATH = "/plugins/magic-sessionmanager/impersonate/land";
5983
+ function adminSignInSupport(version) {
5984
+ const match = typeof version === "string" ? /^(\d+)\.(\d+)\.(\d+)/.exec(version.trim()) : null;
5985
+ if (!match) return { supported: false, version: null, reason: "unknown-version" };
5986
+ const [major, minor] = [Number(match[1]), Number(match[2])];
5987
+ const clean = `${match[1]}.${match[2]}.${match[3]}`;
5988
+ const supported = major === TESTED_STRAPI.major && minor >= TESTED_STRAPI.minMinor && minor <= TESTED_STRAPI.maxMinor;
5989
+ return { supported, version: clean, reason: supported ? null : "untested-version" };
5990
+ }
5991
+ function allowedSignInDurations(accessTokenLifespanSeconds) {
5992
+ const seconds = Number(accessTokenLifespanSeconds);
5993
+ const lifespan = Number.isFinite(seconds) && seconds > 0 ? seconds : 30 * 60;
5994
+ return ADMIN_SIGN_IN_DURATIONS.filter((minutes) => minutes * 60 <= lifespan);
5995
+ }
5996
+ function validateSignInBody(body, durations) {
5997
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
5998
+ return { value: null, errors: [{ path: [], message: "Body must be an object" }] };
5999
+ }
6000
+ const errors = [];
6001
+ const source = (
6002
+ /** @type {Record<string, unknown>} */
6003
+ body
6004
+ );
6005
+ for (const key of Object.keys(source)) {
6006
+ if (!["reason", "durationMinutes", "allowChanges"].includes(key)) {
6007
+ errors.push({ path: [key], message: "Unknown field" });
6008
+ }
6009
+ }
6010
+ const reason = cleanReason(source.reason);
6011
+ if (reason === null) {
6012
+ errors.push({
6013
+ path: ["reason"],
6014
+ message: `reason must be ${REASON_MIN} to ${REASON_MAX} characters`
6015
+ });
6016
+ }
6017
+ const duration = source.durationMinutes;
6018
+ if (typeof duration !== "number" || !durations.includes(duration)) {
6019
+ errors.push({
6020
+ path: ["durationMinutes"],
6021
+ message: `durationMinutes must be one of: ${durations.join(", ")}`
6022
+ });
6023
+ }
6024
+ if (source.allowChanges !== void 0 && typeof source.allowChanges !== "boolean") {
6025
+ errors.push({ path: ["allowChanges"], message: "allowChanges must be a boolean" });
6026
+ }
6027
+ if (errors.length) return { value: null, errors };
6028
+ return {
6029
+ value: {
6030
+ reason: (
6031
+ /** @type {string} */
6032
+ reason
6033
+ ),
6034
+ durationMinutes: (
6035
+ /** @type {number} */
6036
+ duration
6037
+ ),
6038
+ allowChanges: source.allowChanges === true
6039
+ },
6040
+ errors
6041
+ };
6042
+ }
6043
+ var SAFE_METHODS = Object.freeze(["GET", "HEAD", "OPTIONS"]);
6044
+ var READ_ONLY_POSTS = Object.freeze(["/admin/permissions/check"]);
6045
+ var IDENTITY_PREFIXES = Object.freeze([
6046
+ "/admin/users",
6047
+ "/admin/roles",
6048
+ "/admin/api-tokens",
6049
+ "/admin/transfer",
6050
+ "/admin/providers",
6051
+ "/admin/register",
6052
+ "/admin/register-admin",
6053
+ "/admin/registration-info",
6054
+ "/admin/forgot-password",
6055
+ "/admin/reset-password",
6056
+ "/admin/renew-token",
6057
+ "/admin/login",
6058
+ "/admin/sessions",
6059
+ "/magic-sessionmanager"
6060
+ ]);
6061
+ var SELF_PATHS = Object.freeze({
6062
+ state: "/magic-sessionmanager/admin-impersonation/self",
6063
+ end: "/magic-sessionmanager/admin-impersonation/self/end"
6064
+ });
6065
+ function under(path, prefix) {
6066
+ return path === prefix || path.startsWith(`${prefix}/`);
6067
+ }
6068
+ function classifyAdminImpersonationRequest(method, rawPath) {
6069
+ const verb = String(method || "").toUpperCase();
6070
+ const path = normalizePath(rawPath);
6071
+ if (path === SELF_PATHS.state || path === SELF_PATHS.end) return "self";
6072
+ if (verb === "POST" && path === "/admin/logout") return "logout";
6073
+ if (SAFE_METHODS.includes(verb)) return "read";
6074
+ if (verb === "POST" && READ_ONLY_POSTS.includes(path)) return "read";
6075
+ if (IDENTITY_PREFIXES.some((prefix) => under(path, prefix))) return "identity";
6076
+ return "write";
6077
+ }
6078
+ function recordedPath(rawPath) {
6079
+ return String(rawPath || "").split("?")[0].slice(0, 200);
6080
+ }
6081
+ module.exports = {
6082
+ ADMIN_DEVICE_PREFIX,
6083
+ ADMIN_SIGN_IN_ACTION,
6084
+ ADMIN_SIGN_IN_DURATIONS,
6085
+ IDENTITY_PREFIXES,
6086
+ LANDING_PATH,
6087
+ READ_ONLY_POSTS,
6088
+ SELF_PATHS,
6089
+ TESTED_STRAPI,
6090
+ adminSignInSupport,
6091
+ allowedSignInDurations,
6092
+ classifyAdminImpersonationRequest,
6093
+ recordedPath,
6094
+ validateSignInBody
6095
+ };
6096
+ }
6097
+ });
6098
+
6099
+ // server/src/middlewares/admin-impersonation-guard.js
6100
+ var require_admin_impersonation_guard = __commonJS({
6101
+ "server/src/middlewares/admin-impersonation-guard.js"(exports, module) {
6102
+ "use strict";
6103
+ var { extractBearerToken } = require_extract_token();
6104
+ var { IMPERSONATION_HEADER, normalizePath } = require_impersonation_rules();
6105
+ var { classifyAdminImpersonationRequest, recordedPath } = require_admin_sign_in_rules();
6106
+ function reply(ctx, status, name, message, reason) {
6107
+ ctx.status = status;
6108
+ ctx.body = { data: null, error: { status, name, message, details: { reason } } };
6109
+ }
6110
+ module.exports = (_config, { strapi: strapi2 }) => {
6111
+ const service = () => strapi2.plugin("magic-sessionmanager").service("impersonation");
6112
+ return async function adminImpersonationGuard(ctx, next) {
6113
+ const prefix = normalizePath(strapi2.config.get("api.rest.prefix", "/api") || "/api");
6114
+ const path = normalizePath(ctx.path);
6115
+ const base = prefix === "/" ? "" : prefix;
6116
+ if (base && (path === base || path.startsWith(`${base}/`))) return next();
6117
+ const bearer = extractBearerToken(ctx);
6118
+ if (!bearer) return next();
6119
+ let impersonationId;
6120
+ let impersonation;
6121
+ try {
6122
+ impersonationId = await service().adminImpersonationOfToken(bearer);
6123
+ if (!impersonationId) return next();
6124
+ impersonation = impersonationId === "unknown" ? null : await service().loadAdminForGuard(impersonationId);
6125
+ } catch {
6126
+ return reply(
6127
+ ctx,
6128
+ 503,
6129
+ "ServiceUnavailableError",
6130
+ "Session check unavailable",
6131
+ "impersonation-check"
6132
+ );
6133
+ }
6134
+ ctx.set(IMPERSONATION_HEADER, "true");
6135
+ const kind = classifyAdminImpersonationRequest(ctx.method, path);
6136
+ if (!impersonation || impersonation.state !== "active") {
6137
+ if (kind === "logout") {
6138
+ ctx.body = { data: {} };
6139
+ return void 0;
6140
+ }
6141
+ return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-ended");
6142
+ }
6143
+ if (Date.now() >= impersonation.expiresAt) {
6144
+ try {
6145
+ await service().end(impersonation.id, { reason: "expired" });
6146
+ } catch {
6147
+ }
6148
+ if (kind === "logout") {
6149
+ ctx.body = { data: {} };
6150
+ return void 0;
6151
+ }
6152
+ return reply(ctx, 401, "UnauthorizedError", "Impersonation ended", "impersonation-expired");
6153
+ }
6154
+ if (kind === "logout") {
6155
+ await service().end(impersonation.id, { reason: "ended", endedBy: impersonation.actorId });
6156
+ ctx.body = { data: {} };
6157
+ return void 0;
6158
+ }
6159
+ const method = String(ctx.method).toUpperCase();
6160
+ const recorded = recordedPath(ctx.path);
6161
+ if (kind === "identity" || kind === "write" && !impersonation.allowChanges) {
6162
+ const reason = kind === "identity" ? "identity" : "read-only";
6163
+ service().recordRefusedAdminCall(impersonation, reason, { method, path: recorded });
6164
+ return reply(
6165
+ ctx,
6166
+ 403,
6167
+ "ForbiddenError",
6168
+ kind === "identity" ? "Not allowed while signed in as another admin" : "Read-only: changes were not allowed for this sign-in",
6169
+ `impersonation-${reason}`
6170
+ );
6171
+ }
6172
+ ctx.state.magicAdminImpersonation = {
6173
+ id: impersonation.id,
6174
+ actorId: impersonation.actorId,
6175
+ targetId: impersonation.targetId,
6176
+ allowChanges: impersonation.allowChanges,
6177
+ expiresAt: impersonation.expiresAt
6178
+ };
6179
+ let failedStatus = 0;
6180
+ try {
6181
+ await next();
6182
+ } catch (err) {
6183
+ failedStatus = Number(
6184
+ /** @type {any} */
6185
+ err?.status
6186
+ ) || 500;
6187
+ throw err;
6188
+ } finally {
6189
+ ctx.set(IMPERSONATION_HEADER, "true");
6190
+ if (kind === "write") {
6191
+ service().recordAdminWrite(impersonation, {
6192
+ method,
6193
+ path: recorded,
6194
+ status: failedStatus || Number(ctx.status) || 0
6195
+ });
6196
+ }
6197
+ }
6198
+ return void 0;
6199
+ };
6200
+ };
6201
+ }
6202
+ });
6203
+
5390
6204
  // server/src/middlewares/session-rejection-headers.js
5391
6205
  var require_session_rejection_headers = __commonJS({
5392
6206
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -9470,7 +10284,13 @@ var require_bootstrap = __commonJS({
9470
10284
  "server/src/bootstrap.js"(exports, module) {
9471
10285
  "use strict";
9472
10286
  var getClientIp = require_getClientIp();
9473
- var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
10287
+ var {
10288
+ MIN_KEY_BYTES,
10289
+ encryptToken,
10290
+ getEncryptionKeyCheck,
10291
+ hashToken,
10292
+ isEncryptionKeyShort
10293
+ } = require_encryption();
9474
10294
  var { createLogger } = require_logger();
9475
10295
  var { resolveUserDocumentId } = require_resolve_user();
9476
10296
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -9481,7 +10301,12 @@ var require_bootstrap = __commonJS({
9481
10301
  var { REVOCATION_UID } = require_session_revocation();
9482
10302
  var { getNativeSessionManager } = require_native_session_manager();
9483
10303
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
9484
- var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
10304
+ var {
10305
+ getCoordinator,
10306
+ hashedKey,
10307
+ initCoordination,
10308
+ LockTimeoutError
10309
+ } = require_coordination();
9485
10310
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
9486
10311
  var {
9487
10312
  normalizeApiPrefix,
@@ -9530,8 +10355,20 @@ var require_bootstrap = __commonJS({
9530
10355
  } = require_sign_in_policies();
9531
10356
  var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
9532
10357
  var { applyUpgradeDefaults } = require_upgrade_defaults();
9533
- var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
10358
+ var {
10359
+ deviceKeyOf,
10360
+ isRecognizedDevice,
10361
+ requestDeviceId,
10362
+ runSignInSignals
10363
+ } = require_sign_in_signals();
9534
10364
  var { anonymizeIp, normalizeIp } = require_admin_request_info();
10365
+ var { migrateLegacyProxyTrust } = require_trusted_proxies();
10366
+ var { errors: utilsErrors } = __require("@strapi/utils");
10367
+ var {
10368
+ classifyCallbackOutcome,
10369
+ setAuthControllerHandlers
10370
+ } = require_auth_controller_guard();
10371
+ var { normalizePath } = require_impersonation_rules();
9535
10372
  var SESSION_UID = "plugin::magic-sessionmanager.session";
9536
10373
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
9537
10374
  var JOB_LEASES = Object.freeze({
@@ -9574,6 +10411,12 @@ var require_bootstrap = __commonJS({
9574
10411
  try {
9575
10412
  const coordinator = await initCoordination(strapi2, log);
9576
10413
  await checkEncryptionKeyConsistency(strapi2, log);
10414
+ await warnShortEncryptionKey(strapi2, log);
10415
+ try {
10416
+ await migrateLegacyProxyTrust(strapi2, log);
10417
+ } catch (err) {
10418
+ log.warn("[CONFIG] trustedProxies could not be migrated:", err?.name || "Error");
10419
+ }
9577
10420
  try {
9578
10421
  await applyUpgradeDefaults(strapi2, log);
9579
10422
  } catch (err) {
@@ -9681,14 +10524,16 @@ var require_bootstrap = __commonJS({
9681
10524
  );
9682
10525
  log.info("[TIME] Dynamic cleanup + retention scheduled");
9683
10526
  strapi2.server.use(require_impersonation_guard()({}, { strapi: strapi2 }));
10527
+ strapi2.server.use(require_admin_impersonation_guard()({}, { strapi: strapi2 }));
9684
10528
  const impersonationSweep = setInterval(() => {
9685
10529
  strapi2.plugin("magic-sessionmanager").service("impersonation").sweep().catch((err) => log.warn("[IMPERSONATION] Sweep failed:", err?.name || "Error"));
9686
10530
  }, 30 * 1e3);
9687
10531
  impersonationSweep.unref?.();
9688
10532
  strapi2.sessionManagerIntervals.impersonationSweep = impersonationSweep;
9689
10533
  strapi2.plugin("magic-sessionmanager").service("impersonation").checkHandoffSetup();
9690
- mountPreLoginGeoGuard({ strapi: strapi2, log });
9691
- mountFailedLoginLockout({ strapi: strapi2, log });
10534
+ const geoCheck = mountPreLoginGeoGuard({ strapi: strapi2, log });
10535
+ const lockoutGuard = mountFailedLoginLockout({ strapi: strapi2, log });
10536
+ connectAuthControllerGuard({ strapi: strapi2, geoCheck, lockoutGuard });
9692
10537
  mountLogoutRoute({ strapi: strapi2, log, sessionService });
9693
10538
  mountLoginInterceptor({ strapi: strapi2, log, sessionService });
9694
10539
  mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
@@ -9746,6 +10591,28 @@ var require_bootstrap = __commonJS({
9746
10591
  log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
9747
10592
  }
9748
10593
  }
10594
+ async function warnShortEncryptionKey(strapi2, log) {
10595
+ if (!isEncryptionKeyShort()) return false;
10596
+ log.error(
10597
+ `[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).`
10598
+ );
10599
+ try {
10600
+ const coordinator = getCoordinator(strapi2);
10601
+ const check = getEncryptionKeyCheck();
10602
+ const marker = "instance:weak-encryption-key-recorded";
10603
+ if (await coordinator.cacheGet(marker) === check) return true;
10604
+ const recorded = strapi2.plugin("magic-sessionmanager").service("security-log").record({
10605
+ event: SECURITY_EVENTS.CONFIG_WEAK_KEY,
10606
+ actorType: "system",
10607
+ targetType: "config",
10608
+ meta: { minBytes: MIN_KEY_BYTES }
10609
+ });
10610
+ if (recorded !== false) await coordinator.cacheSet(marker, check, Infinity);
10611
+ } catch (err) {
10612
+ log.debug("[SECURITY] Weak key event not recorded:", err?.name || "Error");
10613
+ }
10614
+ return true;
10615
+ }
9749
10616
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
9750
10617
  const shouldRecordRefusal = createRefusalDedup();
9751
10618
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
@@ -9768,19 +10635,14 @@ var require_bootstrap = __commonJS({
9768
10635
  meta: { reason }
9769
10636
  });
9770
10637
  };
9771
- strapi2.server.use(async (ctx, next) => {
9772
- if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
9773
- return next();
9774
- }
10638
+ const check = async (ctx) => {
10639
+ if (ctx.state?.__magicSessionGeoChecked) return null;
10640
+ if (ctx.state) ctx.state.__magicSessionGeoChecked = true;
9775
10641
  const settings = await getRequestSettings(strapi2, ctx);
9776
10642
  const needsGeoCheck = settings.blockSuspiciousSessions || settings.enableGeofencing || settings.enableGeolocation;
9777
- if (!needsGeoCheck) {
9778
- return next();
9779
- }
10643
+ if (!needsGeoCheck) return null;
9780
10644
  const ip = getClientIp(ctx);
9781
- if (!ip || ip === "unknown") {
9782
- return next();
9783
- }
10645
+ if (!ip || ip === "unknown") return null;
9784
10646
  try {
9785
10647
  const geolocationService = strapi2.plugin("magic-sessionmanager").service("geolocation");
9786
10648
  const geoData = await geolocationService.getIpInfo(ip);
@@ -9788,16 +10650,11 @@ var require_bootstrap = __commonJS({
9788
10650
  if (decision.blocked) {
9789
10651
  log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
9790
10652
  await recordRefusal(ctx, settings, ip, decision.reason);
9791
- ctx.status = 403;
9792
- ctx.body = {
9793
- error: {
9794
- status: 403,
9795
- name: "ForbiddenError",
9796
- message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
9797
- }
9798
- };
9799
10653
  ctx.state.__magicSessionGeoData = geoData;
9800
- return;
10654
+ return {
10655
+ status: 403,
10656
+ message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
10657
+ };
9801
10658
  }
9802
10659
  if (decision.status === "ok") {
9803
10660
  ctx.state.__magicSessionGeoData = geoData;
@@ -9807,21 +10664,31 @@ var require_bootstrap = __commonJS({
9807
10664
  if (failureDecision.blocked) {
9808
10665
  log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
9809
10666
  await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
9810
- ctx.status = 403;
9811
- ctx.body = {
9812
- error: {
9813
- status: 403,
9814
- name: "ForbiddenError",
9815
- message: "Login temporarily unavailable. Please contact support."
9816
- }
10667
+ return {
10668
+ status: 403,
10669
+ message: "Login temporarily unavailable. Please contact support."
9817
10670
  };
9818
- return;
9819
10671
  }
9820
10672
  log.debug("Pre-login geo guard error (allowing by configured policy):", err?.name || "Error");
9821
10673
  }
10674
+ return null;
10675
+ };
10676
+ strapi2.server.use(async (ctx, next) => {
10677
+ if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
10678
+ return next();
10679
+ }
10680
+ const refusal = await check(ctx);
10681
+ if (refusal) {
10682
+ ctx.status = refusal.status;
10683
+ ctx.body = {
10684
+ error: { status: refusal.status, name: "ForbiddenError", message: refusal.message }
10685
+ };
10686
+ return;
10687
+ }
9822
10688
  await next();
9823
10689
  });
9824
10690
  log.info("[SUCCESS] Pre-login geo guard mounted");
10691
+ return check;
9825
10692
  }
9826
10693
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
9827
10694
  const logoutPath = `${normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"))}/auth/logout`;
@@ -10007,16 +10874,16 @@ var require_bootstrap = __commonJS({
10007
10874
  }
10008
10875
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
10009
10876
  const lockout = createLoginLockout(getCoordinator(strapi2));
10877
+ const coordinator = getCoordinator(strapi2);
10010
10878
  const shouldRecordRefusal = createRefusalDedup();
10011
10879
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
10012
10880
  const underAddressCap = createAddressCap();
10013
10881
  const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
10014
- strapi2.server.use(async (ctx, next) => {
10015
- if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
10882
+ const guard = async (ctx, run, classify, refuse) => {
10016
10883
  const settings = await getRequestSettings(strapi2, ctx);
10017
10884
  const policy = resolveLockoutPolicy(settings);
10018
10885
  const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
10019
- if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
10886
+ if (policy.ipMax <= 0 && !accountPossible && !policy.record) return run();
10020
10887
  const rawIp = getClientIp(ctx);
10021
10888
  const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
10022
10889
  const identifier = readSignInIdentifier(ctx);
@@ -10037,6 +10904,15 @@ var require_bootstrap = __commonJS({
10037
10904
  };
10038
10905
  if (policy.accountMaxByRole) await loadAccount();
10039
10906
  const accountMax = accountThresholdFor(settings, account?.role || null);
10907
+ let accountExempt = false;
10908
+ const deviceId = requestDeviceId(ctx);
10909
+ if (accountMax > 0 && identifier && deviceId) {
10910
+ await loadAccount();
10911
+ accountExempt = await isRecognizedDevice(strapi2, account?.documentId || null, {
10912
+ userAgent,
10913
+ deviceId
10914
+ }).catch(() => false);
10915
+ }
10040
10916
  const event = (name, meta) => {
10041
10917
  const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
10042
10918
  if (signInFamily && !policy.record) return false;
@@ -10064,7 +10940,7 @@ var require_bootstrap = __commonJS({
10064
10940
  };
10065
10941
  let decision;
10066
10942
  try {
10067
- decision = await lockout.reserve({ ip, identifier, policy, accountMax });
10943
+ decision = await lockout.reserve({ ip, identifier, policy, accountMax, accountExempt });
10068
10944
  } catch (err) {
10069
10945
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10070
10946
  decision = {
@@ -10075,47 +10951,38 @@ var require_bootstrap = __commonJS({
10075
10951
  };
10076
10952
  }
10077
10953
  if (decision.outcome === "locked") {
10078
- ctx.set("Retry-After", String(decision.retryAfter));
10079
10954
  log.warn(
10080
10955
  `[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
10081
10956
  );
10082
10957
  if (policy.record) await loadAccount();
10083
10958
  refusedOnce("lockout", { lock: decision.lockedKind });
10084
- ctx.status = 429;
10085
- ctx.body = {
10086
- error: {
10087
- status: 429,
10088
- name: "TooManyRequestsError",
10089
- message: "Too many failed login attempts. Please try again later.",
10090
- details: { retryAfter: decision.retryAfter }
10091
- }
10092
- };
10093
- return;
10959
+ return refuse(ctx, {
10960
+ status: 429,
10961
+ name: "TooManyRequestsError",
10962
+ message: "Too many failed login attempts. Please try again later.",
10963
+ retryAfter: decision.retryAfter
10964
+ });
10094
10965
  }
10095
10966
  if (decision.outcome === "busy") {
10096
10967
  if (policy.record) await loadAccount();
10097
10968
  refusedOnce("too-many-attempts", {});
10098
- ctx.set("Retry-After", "1");
10099
- ctx.status = 429;
10100
- ctx.body = {
10101
- error: {
10102
- status: 429,
10103
- name: "TooManyRequestsError",
10104
- message: "Too many login attempts at once. Please try again.",
10105
- details: { retryAfter: 1 }
10106
- }
10107
- };
10108
- return;
10969
+ return refuse(ctx, {
10970
+ status: 429,
10971
+ name: "TooManyRequestsError",
10972
+ message: "Too many login attempts at once. Please try again.",
10973
+ retryAfter: 1
10974
+ });
10109
10975
  }
10110
10976
  let thrown = null;
10977
+ let returned;
10111
10978
  try {
10112
- await next();
10979
+ returned = await run();
10113
10980
  } catch (err) {
10114
10981
  thrown = err;
10115
10982
  }
10116
- const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10117
- const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
10983
+ const result = classify(thrown, ctx);
10118
10984
  if (result === "failure") {
10985
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10119
10986
  if (policy.record || decision.reservation.accountKey) await loadAccount();
10120
10987
  if (account) {
10121
10988
  event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
@@ -10143,21 +11010,93 @@ var require_bootstrap = __commonJS({
10143
11010
  minutes
10144
11011
  });
10145
11012
  if (lock.kind === "account" && policy.notifyUser && account?.email) {
10146
- const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
10147
- notifications.sendAccountLockedEmail({
10148
- user: account,
10149
- minutes,
10150
- until: lock.until
10151
- }).catch(() => {
10152
- });
11013
+ const mailWindowMs = Math.max(policy.windowMs, policy.durationMs);
11014
+ const sent = await coordinator.hit(hashedKey("lm", lock.id), mailWindowMs).then((entry) => Number(entry?.hits) || 0).catch(() => 1);
11015
+ if (sent === 1) {
11016
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
11017
+ notifications.sendAccountLockedEmail({
11018
+ user: account,
11019
+ minutes,
11020
+ until: lock.until
11021
+ }).catch(() => {
11022
+ });
11023
+ }
10153
11024
  }
10154
11025
  }
10155
11026
  } catch (err) {
10156
11027
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10157
11028
  }
10158
11029
  if (thrown) throw thrown;
11030
+ return returned;
11031
+ };
11032
+ strapi2.server.use(async (ctx, next) => {
11033
+ if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
11034
+ return guard(ctx, next, classifyRouteOutcome, refuseOverHttp);
10159
11035
  });
10160
11036
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
11037
+ return guard;
11038
+ }
11039
+ function classifyRouteOutcome(thrown, ctx) {
11040
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
11041
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) return "success";
11042
+ return status === 400 || status === 401 ? "failure" : "neutral";
11043
+ }
11044
+ function refuseOverHttp(ctx, refusal) {
11045
+ ctx.set("Retry-After", String(refusal.retryAfter));
11046
+ ctx.status = refusal.status;
11047
+ ctx.body = {
11048
+ error: {
11049
+ status: refusal.status,
11050
+ name: refusal.name,
11051
+ message: refusal.message,
11052
+ details: { retryAfter: refusal.retryAfter }
11053
+ }
11054
+ };
11055
+ }
11056
+ function isGraphqlRequest(strapi2, ctx) {
11057
+ let endpoint = "/graphql";
11058
+ try {
11059
+ endpoint = strapi2.plugin("graphql")?.config?.("endpoint") || endpoint;
11060
+ } catch {
11061
+ }
11062
+ const original = String(ctx.originalUrl || ctx.url || "").split("?")[0];
11063
+ return normalizePath(original) === normalizePath(endpoint);
11064
+ }
11065
+ function createAuthControllerHandlers({ strapi: strapi2, geoCheck, lockoutGuard }) {
11066
+ const refuse = (ctx, refusal) => {
11067
+ if (refusal.retryAfter) ctx.set("Retry-After", String(refusal.retryAfter));
11068
+ if (isGraphqlRequest(strapi2, ctx)) {
11069
+ const details = refusal.retryAfter ? { retryAfter: refusal.retryAfter } : {};
11070
+ throw refusal.status === 429 ? new utilsErrors.RateLimitError(refusal.message, details) : new utilsErrors.ForbiddenError(refusal.message, details);
11071
+ }
11072
+ if (refusal.status === 429) return refuseOverHttp(ctx, refusal);
11073
+ ctx.status = refusal.status;
11074
+ ctx.body = {
11075
+ error: { status: refusal.status, name: refusal.name, message: refusal.message }
11076
+ };
11077
+ return void 0;
11078
+ };
11079
+ const geoFirst = async (ctx) => {
11080
+ const refusal = await geoCheck(ctx);
11081
+ if (!refusal) return false;
11082
+ refuse(ctx, { ...refusal, name: "ForbiddenError", retryAfter: 0 });
11083
+ return true;
11084
+ };
11085
+ return {
11086
+ async callback(ctx, run) {
11087
+ if (await geoFirst(ctx)) return void 0;
11088
+ const provider = ctx.params?.provider || "local";
11089
+ if (provider !== "local") return run();
11090
+ return lockoutGuard(ctx, run, classifyCallbackOutcome, refuse);
11091
+ },
11092
+ async newSession(ctx, run) {
11093
+ if (await geoFirst(ctx)) return void 0;
11094
+ return run();
11095
+ }
11096
+ };
11097
+ }
11098
+ function connectAuthControllerGuard(deps) {
11099
+ setAuthControllerHandlers(deps.strapi, createAuthControllerHandlers(deps));
10161
11100
  }
10162
11101
  function statusOfThrownError(err) {
10163
11102
  const status = Number(err?.status ?? err?.statusCode);
@@ -11367,6 +12306,8 @@ var require_bootstrap = __commonJS({
11367
12306
  }
11368
12307
  }
11369
12308
  module.exports.__private = {
12309
+ warnShortEncryptionKey,
12310
+ createAuthControllerHandlers,
11370
12311
  registerSessionAwareAuthStrategy,
11371
12312
  mountFailedLoginLockout,
11372
12313
  ensureSessionLookupIndexes,
@@ -11386,6 +12327,7 @@ var require_destroy = __commonJS({
11386
12327
  "server/src/destroy.js"(exports, module) {
11387
12328
  "use strict";
11388
12329
  var { createLogger } = require_logger();
12330
+ var { uninstallAuthControllerGuard } = require_auth_controller_guard();
11389
12331
  module.exports = async ({ strapi: strapi2 }) => {
11390
12332
  const log = createLogger(strapi2);
11391
12333
  if (strapi2.sessionManagerIntervals) {
@@ -11419,6 +12361,11 @@ var require_destroy = __commonJS({
11419
12361
  }
11420
12362
  strapi2.sessionManagerAdminActivityUninstall = null;
11421
12363
  }
12364
+ try {
12365
+ uninstallAuthControllerGuard(strapi2);
12366
+ } catch (err) {
12367
+ log.warn("Failed to restore the Users & Permissions auth controller:", err?.name || "Error");
12368
+ }
11422
12369
  try {
11423
12370
  strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
11424
12371
  } catch (err) {
@@ -11792,7 +12739,7 @@ var require_schema4 = __commonJS({
11792
12739
  singularName: "impersonation",
11793
12740
  pluralName: "impersonations",
11794
12741
  displayName: "Impersonation",
11795
- description: "Time-limited impersonations of app users and permission previews of admins, started by an admin with a reason"
12742
+ description: "Time-limited impersonations of app users, permission previews of admins and sign-ins as another admin, started by an admin with a reason"
11796
12743
  },
11797
12744
  options: {
11798
12745
  draftAndPublish: false,
@@ -11855,13 +12802,17 @@ var require_schema4 = __commonJS({
11855
12802
  },
11856
12803
  handoff: {
11857
12804
  type: "enumeration",
11858
- enum: ["frontend", "token", "preview"],
12805
+ enum: ["frontend", "token", "preview", "admin-session"],
11859
12806
  required: true
11860
12807
  },
11861
12808
  notifyUser: {
11862
12809
  type: "boolean",
11863
12810
  default: false
11864
12811
  },
12812
+ allowChanges: {
12813
+ type: "boolean",
12814
+ default: false
12815
+ },
11865
12816
  startedAt: {
11866
12817
  type: "datetime",
11867
12818
  required: true
@@ -12141,6 +13092,7 @@ var require_admin = __commonJS({
12141
13092
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12142
13093
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
12143
13094
  var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
13095
+ var ADMIN_SIGN_IN_ACTION = "plugin::magic-sessionmanager.impersonate.admins.sign-in";
12144
13096
  var impersonationListPolicy = () => [
12145
13097
  ...adminPolicy(),
12146
13098
  "plugin::magic-sessionmanager.can-impersonate"
@@ -12545,6 +13497,59 @@ var require_admin = __commonJS({
12545
13497
  ]
12546
13498
  }
12547
13499
  },
13500
+ // Sign in as this admin (4.23).
13501
+ {
13502
+ method: "POST",
13503
+ path: "/impersonation/admins/:adminId/sign-in",
13504
+ handler: "impersonation.signInAdmin",
13505
+ config: {
13506
+ policies: adminSessionsPolicy([ADMIN_SIGN_IN_ACTION]),
13507
+ middlewares: [
13508
+ {
13509
+ name: "plugin::magic-sessionmanager.rate-limit",
13510
+ config: { max: 10, window: 10 * 60 * 1e3 }
13511
+ }
13512
+ ]
13513
+ }
13514
+ },
13515
+ {
13516
+ method: "POST",
13517
+ path: "/admin-impersonation/exchange",
13518
+ handler: "impersonation.exchangeAdmin",
13519
+ config: {
13520
+ // The code is bound to the admin who started the sign-in, who must
13521
+ // still hold the action.
13522
+ policies: adminSessionsPolicy([ADMIN_SIGN_IN_ACTION]),
13523
+ middlewares: [
13524
+ {
13525
+ name: "plugin::magic-sessionmanager.rate-limit",
13526
+ config: { max: 10, window: 6e4 }
13527
+ }
13528
+ ]
13529
+ }
13530
+ },
13531
+ {
13532
+ method: "GET",
13533
+ path: "/admin-impersonation/self",
13534
+ handler: "impersonation.adminSelf",
13535
+ config: {
13536
+ // The impersonation tab holds the target's token, and the target may
13537
+ // not have plugin access. The admin impersonation guard recognises
13538
+ // the session (signed token + session marker) before routing; the
13539
+ // handler answers 401 to everybody else.
13540
+ auth: false,
13541
+ middlewares: adminReadRateLimit()
13542
+ }
13543
+ },
13544
+ {
13545
+ method: "POST",
13546
+ path: "/admin-impersonation/self/end",
13547
+ handler: "impersonation.endAdminSelf",
13548
+ config: {
13549
+ auth: false,
13550
+ middlewares: adminSignOutRateLimit()
13551
+ }
13552
+ },
12548
13553
  {
12549
13554
  method: "GET",
12550
13555
  path: "/impersonation/previews/:id",
@@ -14892,7 +15897,13 @@ var require_settings_access = __commonJS({
14892
15897
  // Signed webhook, event selection, impossible travel and shortened IPs.
14893
15898
  ...PROTECTED_DETECTION_KEYS,
14894
15899
  // Impersonation switch (4.20): whether admins can act as app users.
14895
- ...IMPERSONATION_KEYS
15900
+ ...IMPERSONATION_KEYS,
15901
+ // Security review 2 (4.22.1): which proxies may name the client address
15902
+ // (H2), the IP lockout threshold (H2) and the alert email texts, which go
15903
+ // to app users from the site's own address (hardening 6).
15904
+ "trustedProxies",
15905
+ "maxFailedLogins",
15906
+ "emailTemplates"
14896
15907
  ]);
14897
15908
  var WEBHOOK_SECRETS = Object.freeze([
14898
15909
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
@@ -15002,6 +16013,7 @@ var require_settings = __commonJS({
15002
16013
  validateImpersonationSettings
15003
16014
  } = require_impersonation_rules();
15004
16015
  var { encryptToken } = require_encryption();
16016
+ var { normalizeTrustedProxies, validateTrustedProxies } = require_trusted_proxies();
15005
16017
  var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
15006
16018
  var path = __require("node:path");
15007
16019
  var ALLOWED_WEBHOOK_DOMAINS = {
@@ -15177,7 +16189,9 @@ var require_settings = __commonJS({
15177
16189
  discordWebhookUrl: "",
15178
16190
  slackWebhookUrl: "",
15179
16191
  strictSessionEnforcement: false,
15180
- trustedProxies: false,
16192
+ // A list of proxy addresses or CIDR ranges since 4.22.1; the legacy
16193
+ // boolean is read as an empty list (Strapi's server.proxy settings decide).
16194
+ trustedProxies: [],
15181
16195
  emailTemplates: DEFAULT_EMAIL_TEMPLATES,
15182
16196
  ...SECURITY_LOG_DEFAULTS,
15183
16197
  ...POLICY_DEFAULTS,
@@ -15198,7 +16212,8 @@ var require_settings = __commonJS({
15198
16212
  ...DEFAULT_EMAIL_TEMPLATES,
15199
16213
  ...storedTemplates
15200
16214
  },
15201
- geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath)
16215
+ geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath),
16216
+ trustedProxies: normalizeTrustedProxies(safeStored.trustedProxies)
15202
16217
  };
15203
16218
  }
15204
16219
  var INTEGER_SETTING_RANGES = {
@@ -15223,8 +16238,7 @@ var require_settings = __commonJS({
15223
16238
  "alertOnNewLocation",
15224
16239
  "alertOnVpnProxy",
15225
16240
  "enableWebhooks",
15226
- "strictSessionEnforcement",
15227
- "trustedProxies"
16241
+ "strictSessionEnforcement"
15228
16242
  ];
15229
16243
  var GEO_IP_PROVIDER_VALUES = ["auto", "local-mmdb", "ipapi", "disabled"];
15230
16244
  var GEO_LOOKUP_FAILURE_MODE_VALUES = ["auto", "allow", "block"];
@@ -15298,6 +16312,11 @@ var require_settings = __commonJS({
15298
16312
  next[key] = body[key];
15299
16313
  }
15300
16314
  }
16315
+ if (has("trustedProxies")) {
16316
+ const proxies = validateTrustedProxies(body.trustedProxies);
16317
+ if (proxies.error) errors.push(proxies.error);
16318
+ else next.trustedProxies = proxies.value;
16319
+ }
15301
16320
  for (const key of ["allowedCountries", "blockedCountries"]) {
15302
16321
  if (!has(key)) continue;
15303
16322
  const list = body[key];
@@ -15416,6 +16435,15 @@ var require_settings = __commonJS({
15416
16435
  next.genericWebhookSecret = encryptToken(secret);
15417
16436
  }
15418
16437
  }
16438
+ const urlChanges = typeof next.genericWebhookUrl === "string" && next.genericWebhookUrl !== "" && next.genericWebhookUrl !== (current.genericWebhookUrl || "");
16439
+ const secretStored = typeof current.genericWebhookSecret === "string" && current.genericWebhookSecret !== "";
16440
+ const secretGiven = typeof next.genericWebhookSecret === "string" && next.genericWebhookSecret !== "";
16441
+ if (urlChanges && secretStored && !secretGiven) {
16442
+ errors.push({
16443
+ path: ["genericWebhookSecret"],
16444
+ message: "Enter the webhook secret again when you change the webhook URL"
16445
+ });
16446
+ }
15419
16447
  if (errors.length > 0) return { errors };
15420
16448
  const settings = {};
15421
16449
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -17128,10 +18156,43 @@ var require_lockouts = __commonJS({
17128
18156
  }
17129
18157
  });
17130
18158
 
18159
+ // server/src/utils/user-export.js
18160
+ var require_user_export = __commonJS({
18161
+ "server/src/utils/user-export.js"(exports, module) {
18162
+ "use strict";
18163
+ var { SECURITY_EVENTS } = require_security_log_model();
18164
+ var IMPERSONATION_TEXT = Object.freeze({
18165
+ [SECURITY_EVENTS.IMPERSONATION_STARTED]: "An administrator opened your account",
18166
+ [SECURITY_EVENTS.IMPERSONATION_ENDED]: "The administrator access to your account ended",
18167
+ [SECURITY_EVENTS.IMPERSONATION_EXPIRED]: "The administrator access to your account ended",
18168
+ [SECURITY_EVENTS.IMPERSONATION_REFUSED]: "An administrator access to your account was refused"
18169
+ });
18170
+ function toUserExportEvent(row) {
18171
+ const { id: _id, ...rest } = row || {};
18172
+ const text = IMPERSONATION_TEXT[rest.event];
18173
+ if (!text) return rest;
18174
+ const minutes = Number(rest.meta?.durationMinutes);
18175
+ return {
18176
+ event: rest.event,
18177
+ createdAt: rest.createdAt,
18178
+ ip: null,
18179
+ userAgent: null,
18180
+ geo: null,
18181
+ meta: {
18182
+ description: text,
18183
+ ...Number.isInteger(minutes) && minutes > 0 ? { durationMinutes: minutes } : {}
18184
+ }
18185
+ };
18186
+ }
18187
+ module.exports = { IMPERSONATION_TEXT, toUserExportEvent };
18188
+ }
18189
+ });
18190
+
17131
18191
  // server/src/controllers/self-service.js
17132
18192
  var require_self_service = __commonJS({
17133
18193
  "server/src/controllers/self-service.js"(exports, module) {
17134
18194
  "use strict";
18195
+ var crypto = __require("node:crypto");
17135
18196
  var { getCoordinator } = require_coordination();
17136
18197
  var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
17137
18198
  var { recordUserEvent } = require_sign_in_policies();
@@ -17139,6 +18200,7 @@ var require_self_service = __commonJS({
17139
18200
  var { SECURITY_EVENTS } = require_security_log_model();
17140
18201
  var { sendServerError } = require_http_errors();
17141
18202
  var { createLogger } = require_logger();
18203
+ var { toUserExportEvent } = require_user_export();
17142
18204
  var SESSION_UID = "plugin::magic-sessionmanager.session";
17143
18205
  var EVENT_UID = "plugin::magic-sessionmanager.security-event";
17144
18206
  var USER_UID = "plugin::users-permissions.user";
@@ -17205,19 +18267,21 @@ var require_self_service = __commonJS({
17205
18267
  return "en";
17206
18268
  }
17207
18269
  var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
17208
- function sendPage(ctx, status, lang, title, body) {
18270
+ 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);})();`;
18271
+ var FRAGMENT_SCRIPT_HASH = `sha256-${crypto.createHash("sha256").update(FRAGMENT_SCRIPT).digest("base64")}`;
18272
+ function sendPage(ctx, status, lang, title, body, { withScript = false } = {}) {
17209
18273
  ctx.status = status;
17210
18274
  ctx.set("Content-Type", "text/html; charset=utf-8");
17211
18275
  ctx.set(
17212
18276
  "Content-Security-Policy",
17213
- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
18277
+ `default-src 'none'; style-src 'unsafe-inline'; ${withScript ? `script-src '${FRAGMENT_SCRIPT_HASH}'; ` : ""}form-action 'self'; frame-ancestors 'none'; base-uri 'none'`
17214
18278
  );
17215
18279
  ctx.set("Referrer-Policy", "no-referrer");
17216
18280
  ctx.set("Cache-Control", "no-store");
17217
18281
  ctx.set("X-Robots-Tag", "noindex");
17218
18282
  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>
17219
18283
  <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>
17220
- <body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
18284
+ <body><main><h1>${escapeHtml(title)}</h1>${body}</main>${withScript ? `<script>${FRAGMENT_SCRIPT}</script>` : ""}</body></html>`;
17221
18285
  }
17222
18286
  module.exports = ({ strapi: strapi2 }) => {
17223
18287
  const log = createLogger(strapi2);
@@ -17225,17 +18289,20 @@ var require_self_service = __commonJS({
17225
18289
  /**
17226
18290
  * Confirmation page of the "This wasn't me" link. Uses nothing.
17227
18291
  *
17228
- * @route GET /api/magic-sessionmanager/not-me?token=
18292
+ * @route GET /api/magic-sessionmanager/not-me (token in `#token=`; `?token=` before 4.22.1)
17229
18293
  * @auth none (public on purpose: the link is opened from an email; the
17230
18294
  * signed token is checked, and nothing changes until the POST)
17231
18295
  * @param {any} ctx Koa context.
17232
- * @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
18296
+ * @returns {Promise<void>} 200 page with two buttons, or 410 when a `?token=` link is
18297
+ * invalid. Without `?token=` the page is served with the hashed script that copies the
18298
+ * fragment token into the forms; the POST checks it.
17233
18299
  */
17234
18300
  async notMePage(ctx) {
17235
18301
  const lang = pageLanguage(ctx);
17236
18302
  const text = PAGE_TEXT[lang];
17237
- const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
17238
- if (!readNotMeToken(token)) {
18303
+ const hasQueryToken = typeof ctx.query?.token === "string" && ctx.query.token !== "";
18304
+ const token = hasQueryToken ? ctx.query.token : "";
18305
+ if (hasQueryToken && !readNotMeToken(token)) {
17239
18306
  return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
17240
18307
  }
17241
18308
  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>`;
@@ -17244,7 +18311,8 @@ var require_self_service = __commonJS({
17244
18311
  200,
17245
18312
  lang,
17246
18313
  text.title,
17247
- `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
18314
+ `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`,
18315
+ { withScript: !hasQueryToken }
17248
18316
  );
17249
18317
  },
17250
18318
  /**
@@ -17397,7 +18465,9 @@ var require_self_service = __commonJS({
17397
18465
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
17398
18466
  user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
17399
18467
  sessions,
17400
- securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
18468
+ // Impersonation events show a fixed text and the duration only
18469
+ // (security review 2, L3): the admin's reason stays internal.
18470
+ securityEvents: (Array.isArray(events) ? events : []).map(toUserExportEvent)
17401
18471
  };
17402
18472
  } catch (err) {
17403
18473
  log.error("[my-data] Export failed:", err?.name || "Error");
@@ -17700,6 +18770,14 @@ var require_impersonation = __commonJS({
17700
18770
  resolveFrontendHandoff,
17701
18771
  validateStartBody
17702
18772
  } = require_impersonation_rules();
18773
+ var {
18774
+ ADMIN_DEVICE_PREFIX,
18775
+ ADMIN_SIGN_IN_ACTION,
18776
+ LANDING_PATH,
18777
+ adminSignInSupport,
18778
+ allowedSignInDurations,
18779
+ validateSignInBody
18780
+ } = require_admin_sign_in_rules();
17703
18781
  var UID = "plugin::magic-sessionmanager.impersonation";
17704
18782
  var USER_UID = "plugin::users-permissions.user";
17705
18783
  var NATIVE_SESSION_UID = "admin::session";
@@ -17727,7 +18805,8 @@ var require_impersonation = __commonJS({
17727
18805
  STARTED: "impersonation.started",
17728
18806
  ENDED: "impersonation.ended",
17729
18807
  EXPIRED: "impersonation.expired",
17730
- REFUSED: "impersonation.refused"
18808
+ REFUSED: "impersonation.refused",
18809
+ WRITE: "impersonation.write"
17731
18810
  });
17732
18811
  function remember(map, key, value) {
17733
18812
  map.delete(key);
@@ -17823,9 +18902,27 @@ var require_impersonation = __commonJS({
17823
18902
  frontendOrigin: frontend ? frontend.origin : null,
17824
18903
  durations: [...USER_DURATIONS],
17825
18904
  adminDurations: [...ADMIN_DURATIONS],
17826
- mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy"
18905
+ mode: getNativeSessionManager(strapi2) ? "refresh" : "legacy",
18906
+ adminSignIn: service.adminSignInStatus()
17827
18907
  };
17828
18908
  },
18909
+ /**
18910
+ * Whether "Sign in as this admin" can run on this Strapi: a tested
18911
+ * release, Strapi's session manager present, and at least one duration
18912
+ * that fits into one admin access token.
18913
+ *
18914
+ * @returns {{supported: boolean, version: string|null, reason: string|null, durations: number[]}}
18915
+ */
18916
+ adminSignInStatus() {
18917
+ const support = adminSignInSupport(strapi2.config.get("info.strapi"));
18918
+ const durations = allowedSignInDurations(
18919
+ strapi2.config.get("admin.auth.sessions.accessTokenLifespan", 30 * 60)
18920
+ );
18921
+ let reason = support.reason;
18922
+ if (!reason && typeof strapi2.sessionManager !== "function") reason = "no-session-manager";
18923
+ if (!reason && durations.length === 0) reason = "token-lifespan";
18924
+ return { supported: reason === null, version: support.version, reason, durations };
18925
+ },
17829
18926
  /**
17830
18927
  * Records a refused start.
17831
18928
  *
@@ -17957,7 +19054,8 @@ var require_impersonation = __commonJS({
17957
19054
  * Caller (with roles), target id and request body.
17958
19055
  * @returns {Promise<object>} Impersonation DTO plus the preview.
17959
19056
  * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17960
- * or not a subset of the caller's permissions; 404 unknown admin.
19057
+ * (callers with `admin::users.read`) or not a subset of the caller's permissions; 404
19058
+ * unknown admin, or a Super Admin for callers without `admin::users.read`.
17961
19059
  * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17962
19060
  */
17963
19061
  async previewAdmin({ actor, adminId, body, canReadAdmins }) {
@@ -17987,6 +19085,15 @@ var require_impersonation = __commonJS({
17987
19085
  ]);
17988
19086
  if (!target) throw new ImpersonationError(404, "Admin not found");
17989
19087
  const refusal = await previewRefusal(strapi2, caller || actor, target);
19088
+ if (refusal?.reason === "super-admin" && !canReadAdmins) {
19089
+ service.recordRefused({
19090
+ actorId,
19091
+ targetType: "admin",
19092
+ targetId: adminId,
19093
+ reason: "super-admin"
19094
+ });
19095
+ throw new ImpersonationError(404, "Admin not found");
19096
+ }
17990
19097
  if (refusal) {
17991
19098
  const messages = {
17992
19099
  self: "You cannot view yourself as another admin",
@@ -18079,6 +19186,416 @@ var require_impersonation = __commonJS({
18079
19186
  preview
18080
19187
  };
18081
19188
  },
19189
+ /**
19190
+ * Starts "Sign in as this admin" (4.23): checks every anti-escalation
19191
+ * rule, stores the impersonation with a one-time code (60 seconds,
19192
+ * stored hashed) and returns the landing path for a new tab. The Strapi
19193
+ * admin session is created only when that tab exchanges the code.
19194
+ *
19195
+ * @param {{actor: any, adminId: unknown, body: unknown, canReadAdmins: boolean,
19196
+ * nested?: boolean}} input Caller (with roles), target id, body; `nested` when the
19197
+ * request itself comes from an impersonation session.
19198
+ * @returns {Promise<{impersonation: object, handoff: {type: 'admin-tab', path: string,
19199
+ * code: string, codeExpiresAt: string}}>}
19200
+ * @throws {ImpersonationError} 400 invalid body; 403 off, unsupported Strapi, nested,
19201
+ * self, Super Admin, inactive, not a subset or already active; 404 unknown admin.
19202
+ * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
19203
+ */
19204
+ async startAdminSignIn({ actor, adminId, body, canReadAdmins, nested = false }) {
19205
+ const actorId = String(actor.id);
19206
+ const refuse = (reason, status, message, extra = {}) => {
19207
+ service.recordRefused({
19208
+ actorId,
19209
+ targetType: "admin",
19210
+ targetId: adminId,
19211
+ reason,
19212
+ via: "sign-in"
19213
+ });
19214
+ return new ImpersonationError(status, message, { reason, ...extra });
19215
+ };
19216
+ if (!await service.isEnabled()) {
19217
+ throw refuse("disabled", 403, "Impersonation is turned off");
19218
+ }
19219
+ const support = service.adminSignInStatus();
19220
+ if (!support.supported) {
19221
+ throw refuse("unsupported", 403, "Not available on this Strapi version", {
19222
+ cause: support.reason
19223
+ });
19224
+ }
19225
+ if (nested)
19226
+ throw refuse("nested", 403, "You cannot start an impersonation while impersonating");
19227
+ if (typeof adminId !== "string" || !ADMIN_ID_PATTERN.test(adminId)) {
19228
+ throw new ImpersonationError(404, "Admin not found");
19229
+ }
19230
+ const { value, errors: fieldErrors } = validateSignInBody(body, support.durations);
19231
+ if (!value) {
19232
+ throw new ImpersonationError(400, "Invalid sign-in request", {
19233
+ errors: fieldErrors.map((error) => ({ ...error, name: "ValidationError" }))
19234
+ });
19235
+ }
19236
+ const [caller, target] = await Promise.all([
19237
+ loadAdmin(strapi2, actor.id),
19238
+ loadAdmin(strapi2, Number(adminId))
19239
+ ]);
19240
+ if (!target) throw new ImpersonationError(404, "Admin not found");
19241
+ const refusal = await previewRefusal(strapi2, caller || actor, target);
19242
+ if (refusal?.reason === "super-admin" && !canReadAdmins) {
19243
+ service.recordRefused({
19244
+ actorId,
19245
+ targetType: "admin",
19246
+ targetId: adminId,
19247
+ reason: "super-admin",
19248
+ via: "sign-in"
19249
+ });
19250
+ throw new ImpersonationError(404, "Admin not found");
19251
+ }
19252
+ if (refusal) {
19253
+ const messages = {
19254
+ self: "You cannot sign in as yourself",
19255
+ "super-admin": "You cannot sign in as a Super Admin",
19256
+ "not-subset": "This admin has permissions that you do not have"
19257
+ };
19258
+ throw refuse(
19259
+ refusal.reason,
19260
+ 403,
19261
+ messages[refusal.reason],
19262
+ refusal.uncovered ? { uncovered: refusal.uncovered } : {}
19263
+ );
19264
+ }
19265
+ if (target.isActive !== true) {
19266
+ throw refuse("inactive", 403, "This admin account is not active");
19267
+ }
19268
+ await service.sweep();
19269
+ const running = await query().findOne({
19270
+ where: {
19271
+ targetType: "admin",
19272
+ targetId: String(target.id),
19273
+ handoff: "admin-session",
19274
+ state: "active"
19275
+ },
19276
+ select: ["id"]
19277
+ });
19278
+ if (running)
19279
+ throw refuse("already-active", 403, "Someone is already signed in as this admin");
19280
+ const now = /* @__PURE__ */ new Date();
19281
+ const expiresAt = new Date(now.getTime() + value.durationMinutes * 60 * 1e3);
19282
+ const code = crypto.randomBytes(32).toString("base64url");
19283
+ const codeExpiresAt = new Date(now.getTime() + CODE_TTL_MS);
19284
+ const row = await query().create({
19285
+ data: {
19286
+ targetType: "admin",
19287
+ targetId: String(target.id),
19288
+ actorId,
19289
+ state: "active",
19290
+ reason: value.reason,
19291
+ durationMinutes: value.durationMinutes,
19292
+ handoff: "admin-session",
19293
+ notifyUser: false,
19294
+ allowChanges: value.allowChanges,
19295
+ startedAt: now,
19296
+ expiresAt,
19297
+ codeHash: hashToken(code),
19298
+ codeExpiresAt
19299
+ }
19300
+ });
19301
+ record({
19302
+ event: EVENTS.STARTED,
19303
+ actorType: "admin",
19304
+ actorId,
19305
+ targetType: "admin",
19306
+ targetId: String(target.id),
19307
+ meta: {
19308
+ reason: value.reason,
19309
+ durationMinutes: value.durationMinutes,
19310
+ handoff: "admin-session",
19311
+ allowChanges: value.allowChanges
19312
+ }
19313
+ });
19314
+ log.info(
19315
+ `[IMPERSONATION] Admin sign-in started (${value.durationMinutes} min, ${value.allowChanges ? "changes allowed" : "read-only"})`
19316
+ );
19317
+ return {
19318
+ impersonation: service.toDto(row, {
19319
+ admins: /* @__PURE__ */ new Map([
19320
+ [String(target.id), canReadAdmins ? target : null],
19321
+ [actorId, caller || actor]
19322
+ ]),
19323
+ viewer: actor
19324
+ }),
19325
+ handoff: {
19326
+ type: "admin-tab",
19327
+ path: LANDING_PATH,
19328
+ cookieName: service.accessCookieName(),
19329
+ code,
19330
+ codeExpiresAt: codeExpiresAt.toISOString()
19331
+ }
19332
+ };
19333
+ },
19334
+ /**
19335
+ * Exchanges the one-time code of an admin sign-in for an admin access
19336
+ * token of the target, in the new tab. The request carries the starting
19337
+ * admin's own token, and only that admin can redeem the code. The Strapi
19338
+ * admin session is created here on a dedicated device id, marked in its
19339
+ * metadata, and expires with the impersonation; its refresh token never
19340
+ * leaves the server, so the tab cannot renew it.
19341
+ *
19342
+ * @param {{code: unknown, actor: any, ability: any}} input Code and the calling admin.
19343
+ * @returns {Promise<object|null>} `{ token, expiresAt, cookieName, impersonation }`, or null
19344
+ * for any unusable code.
19345
+ * @sideeffect Consumes the code; creates one Strapi admin session for the target.
19346
+ */
19347
+ async exchangeAdminCode({ code, actor, ability }) {
19348
+ if (typeof code !== "string" || !CODE_PATTERN.test(code)) return null;
19349
+ if (!await service.isEnabled() || !service.adminSignInStatus().supported) return null;
19350
+ const codeHash = hashToken(code);
19351
+ const now = /* @__PURE__ */ new Date();
19352
+ const row = await query().findOne({
19353
+ where: { codeHash, state: "active", handoff: "admin-session" }
19354
+ });
19355
+ if (!row || String(row.actorId) !== String(actor?.id)) return null;
19356
+ let stillAllowed;
19357
+ try {
19358
+ stillAllowed = ability?.can?.(ADMIN_SIGN_IN_ACTION) === true;
19359
+ } catch {
19360
+ stillAllowed = false;
19361
+ }
19362
+ if (!stillAllowed) return null;
19363
+ const claimed = await query().updateMany({
19364
+ where: {
19365
+ id: row.id,
19366
+ codeHash,
19367
+ state: "active",
19368
+ credentialIssuedAt: { $null: true },
19369
+ codeExpiresAt: { $gt: now },
19370
+ expiresAt: { $gt: now }
19371
+ },
19372
+ data: { codeHash: null, codeExpiresAt: null, credentialIssuedAt: now }
19373
+ });
19374
+ if (Number(claimed?.count) !== 1) return null;
19375
+ const target = await loadAdmin(strapi2, Number(row.targetId));
19376
+ if (!target || target.isActive !== true || await previewRefusal(strapi2, actor, target)) {
19377
+ await service.end(row.documentId, { reason: "failed", silent: true });
19378
+ return null;
19379
+ }
19380
+ try {
19381
+ const token = await service.issueAdminSession(row, target);
19382
+ return {
19383
+ token,
19384
+ expiresAt: new Date(row.expiresAt).toISOString(),
19385
+ cookieName: service.accessCookieName(),
19386
+ impersonation: {
19387
+ id: row.documentId,
19388
+ allowChanges: row.allowChanges === true,
19389
+ expiresAt: new Date(row.expiresAt).toISOString(),
19390
+ targetName: adminLabel(target),
19391
+ actorName: adminLabel(actor)
19392
+ }
19393
+ };
19394
+ } catch (err) {
19395
+ await service.end(row.documentId, { reason: "failed", silent: true });
19396
+ throw err;
19397
+ }
19398
+ },
19399
+ /**
19400
+ * Name of Strapi's admin access cookie (`admin.auth.cookie.name`,
19401
+ * default `jwtToken`), so the impersonation tab can hide it.
19402
+ *
19403
+ * @returns {string}
19404
+ */
19405
+ accessCookieName() {
19406
+ const configured = strapi2.config.get("admin.auth.cookie.name");
19407
+ return typeof configured === "string" && /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(configured.trim()) ? configured.trim() : "jwtToken";
19408
+ },
19409
+ /**
19410
+ * Creates the Strapi admin session of an admin sign-in and returns its
19411
+ * access token. The device id is recorded before the session exists, so
19412
+ * a failure below still revokes exactly this session.
19413
+ *
19414
+ * @param {any} row Impersonation row.
19415
+ * @param {any} target Target admin.
19416
+ * @returns {Promise<string>} Access token.
19417
+ * @throws {Error} When the session cannot be created.
19418
+ * @sideeffect Creates one `admin::session` row and shortens its expiry.
19419
+ */
19420
+ async issueAdminSession(row, target) {
19421
+ const expiresAt = new Date(row.expiresAt);
19422
+ if (expiresAt.getTime() - Date.now() < 5e3) {
19423
+ throw new ImpersonationError(403, "Impersonation ended");
19424
+ }
19425
+ const deviceId = `${ADMIN_DEVICE_PREFIX}${crypto.randomBytes(12).toString("hex")}`;
19426
+ await query().update({
19427
+ where: { id: row.id },
19428
+ data: { nativeUserId: String(target.id), nativeDeviceId: deviceId }
19429
+ });
19430
+ const manager = strapi2.sessionManager("admin");
19431
+ const refresh = await manager.generateRefreshToken(String(target.id), deviceId, {
19432
+ type: "session",
19433
+ metadata: {
19434
+ loginAt: (/* @__PURE__ */ new Date()).toISOString(),
19435
+ deviceName: "Impersonation",
19436
+ msmImpersonation: row.documentId
19437
+ }
19438
+ });
19439
+ await strapi2.db.query(NATIVE_SESSION_UID).update({
19440
+ where: { sessionId: refresh.sessionId },
19441
+ data: { expiresAt, absoluteExpiresAt: expiresAt }
19442
+ });
19443
+ const access = await manager.generateAccessToken(refresh.token);
19444
+ if (!access || "error" in access) throw new Error("Access token could not be minted");
19445
+ remember(nativeSessionCache, `admin:${refresh.sessionId}`, row.documentId);
19446
+ recordCache.delete(row.documentId);
19447
+ return access.token;
19448
+ },
19449
+ /**
19450
+ * Deletes the Strapi admin session of an admin sign-in, and only that
19451
+ * one: by its user and its own device id. Without a stored device id
19452
+ * nothing is deleted, because Strapi's `invalidateRefreshToken` without
19453
+ * a device id would delete every session of the target.
19454
+ *
19455
+ * @param {any} row Impersonation row.
19456
+ * @returns {Promise<void>}
19457
+ * @sideeffect Deletes `admin::session` rows of the impersonation device.
19458
+ */
19459
+ async revokeAdminSession(row) {
19460
+ const userId = row.nativeUserId ? String(row.nativeUserId) : "";
19461
+ const deviceId = row.nativeDeviceId ? String(row.nativeDeviceId) : "";
19462
+ if (!userId || !deviceId.startsWith(ADMIN_DEVICE_PREFIX)) return;
19463
+ try {
19464
+ await strapi2.sessionManager("admin").invalidateRefreshToken(userId, deviceId);
19465
+ } catch (err) {
19466
+ log.error("[IMPERSONATION] Admin session revocation failed:", err?.name || "Error");
19467
+ }
19468
+ },
19469
+ /**
19470
+ * The admin sign-in an admin access token belongs to, or null. The
19471
+ * signature is verified with Strapi's session manager; the session row
19472
+ * names the impersonation in its metadata (or by its device id, which
19473
+ * fails closed). Results are cached per session id (immutable).
19474
+ *
19475
+ * @param {string} token Bearer token.
19476
+ * @returns {Promise<string|null>} Impersonation id (`'unknown'` for a marked device
19477
+ * without readable metadata).
19478
+ * @throws {Error} When the session lookup fails.
19479
+ */
19480
+ async adminImpersonationOfToken(token) {
19481
+ const payload = decodeJwtPayload(token);
19482
+ if (!payload || payload.type !== "access") return null;
19483
+ const sessionId = payload.sessionId;
19484
+ if (typeof sessionId !== "string" || !/^[a-f0-9]{16,64}$/i.test(sessionId)) return null;
19485
+ const key = `admin:${sessionId}`;
19486
+ if (nativeSessionCache.has(key)) {
19487
+ return service.verifyAdminToken(token) ? nativeSessionCache.get(key) : null;
19488
+ }
19489
+ if (!service.verifyAdminToken(token)) return null;
19490
+ const session = await strapi2.db.query(NATIVE_SESSION_UID).findOne({
19491
+ where: { sessionId, origin: "admin" },
19492
+ select: ["metadata", "deviceId"]
19493
+ });
19494
+ let id = null;
19495
+ const mark = session?.metadata?.msmImpersonation;
19496
+ if (typeof mark === "string" && DOCUMENT_ID_PATTERN.test(mark)) id = mark;
19497
+ else if (typeof session?.deviceId === "string" && session.deviceId.startsWith(ADMIN_DEVICE_PREFIX)) {
19498
+ id = "unknown";
19499
+ }
19500
+ if (session) remember(nativeSessionCache, key, id);
19501
+ return id;
19502
+ },
19503
+ /**
19504
+ * Whether a token is a validly signed Strapi admin access token.
19505
+ *
19506
+ * @param {string} token Bearer token.
19507
+ * @returns {boolean}
19508
+ */
19509
+ verifyAdminToken(token) {
19510
+ try {
19511
+ return strapi2.sessionManager("admin").validateAccessToken(token)?.isValid === true;
19512
+ } catch {
19513
+ return false;
19514
+ }
19515
+ },
19516
+ /**
19517
+ * Loads an admin sign-in for the request guard (active rows are read on
19518
+ * every request, like `loadForGuard`).
19519
+ *
19520
+ * @param {string} documentId Impersonation id.
19521
+ * @returns {Promise<{id: string, actorId: string, targetId: string, state: string,
19522
+ * expiresAt: number, allowChanges: boolean}|null>}
19523
+ */
19524
+ async loadAdminForGuard(documentId) {
19525
+ const cached = recordCache.get(`admin:${documentId}`);
19526
+ if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
19527
+ const row = await query().findOne({
19528
+ where: { documentId, targetType: "admin", handoff: "admin-session" },
19529
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt", "allowChanges"]
19530
+ });
19531
+ const value = row ? {
19532
+ id: row.documentId,
19533
+ actorId: String(row.actorId),
19534
+ targetId: String(row.targetId),
19535
+ state: row.state,
19536
+ expiresAt: new Date(row.expiresAt).getTime(),
19537
+ allowChanges: row.allowChanges === true
19538
+ } : null;
19539
+ if (!value || value.state !== "active") {
19540
+ remember(recordCache, `admin:${documentId}`, { value, at: Date.now() });
19541
+ }
19542
+ return value;
19543
+ },
19544
+ /**
19545
+ * Records a change made while signed in as another admin: the real
19546
+ * admin is the actor, the target admin in `meta.impersonating`.
19547
+ *
19548
+ * @param {{id: string, actorId: string, targetId: string}} impersonation Impersonation.
19549
+ * @param {{method: string, path: string, status: number}} request What was done.
19550
+ * @returns {void}
19551
+ * @sideeffect Queues one always-on `impersonation.write` event.
19552
+ */
19553
+ recordAdminWrite(impersonation, { method, path, status }) {
19554
+ record({
19555
+ event: EVENTS.WRITE,
19556
+ actorType: "admin",
19557
+ actorId: impersonation.actorId,
19558
+ targetType: "admin",
19559
+ targetId: impersonation.targetId,
19560
+ meta: {
19561
+ impersonation: impersonation.id,
19562
+ impersonating: impersonation.targetId,
19563
+ method,
19564
+ route: path,
19565
+ status
19566
+ }
19567
+ });
19568
+ },
19569
+ /**
19570
+ * Records a refused admin API call of an admin sign-in (one event per
19571
+ * impersonation and reason per minute).
19572
+ *
19573
+ * @param {{id: string, actorId: string, targetId: string}} impersonation Impersonation.
19574
+ * @param {string} reason `read-only` or `identity`.
19575
+ * @param {{method: string, path: string}} request Refused request.
19576
+ * @returns {void}
19577
+ */
19578
+ recordRefusedAdminCall(impersonation, reason, { method, path }) {
19579
+ const key = `${impersonation.id}|admin-${reason}`;
19580
+ const now = Date.now();
19581
+ const last = refusals.get(key);
19582
+ if (last !== void 0 && now - last < REFUSAL_DEDUP_MS) return;
19583
+ remember(refusals, key, now);
19584
+ record({
19585
+ event: EVENTS.REFUSED,
19586
+ actorType: "admin",
19587
+ actorId: impersonation.actorId,
19588
+ targetType: "admin",
19589
+ targetId: impersonation.targetId,
19590
+ meta: {
19591
+ refusal: `call-${reason}`,
19592
+ impersonation: impersonation.id,
19593
+ impersonating: impersonation.targetId,
19594
+ method,
19595
+ route: path
19596
+ }
19597
+ });
19598
+ },
18082
19599
  /**
18083
19600
  * Mints the short-lived credential of an impersonation and links its
18084
19601
  * Magic session row.
@@ -18248,6 +19765,10 @@ var require_impersonation = __commonJS({
18248
19765
  * @sideeffect Deletes Strapi session rows, writes a revocation record, ends the Magic session.
18249
19766
  */
18250
19767
  async revoke(row, sessionReason) {
19768
+ if (row.handoff === "admin-session") {
19769
+ await service.revokeAdminSession(row);
19770
+ return;
19771
+ }
18251
19772
  if (row.nativeUserId && row.nativeDeviceId) {
18252
19773
  try {
18253
19774
  await strapi2.sessionManager(NATIVE_ORIGIN).invalidateRefreshToken(String(row.nativeUserId), String(row.nativeDeviceId));
@@ -18389,6 +19910,7 @@ var require_impersonation = __commonJS({
18389
19910
  reason: row.reason,
18390
19911
  durationMinutes: row.durationMinutes,
18391
19912
  handoff: row.handoff,
19913
+ allowChanges: row.allowChanges === true,
18392
19914
  credentialIssued: Boolean(row.credentialIssuedAt),
18393
19915
  startedAt: new Date(row.startedAt).toISOString(),
18394
19916
  expiresAt: new Date(row.expiresAt).toISOString(),
@@ -18396,7 +19918,10 @@ var require_impersonation = __commonJS({
18396
19918
  };
18397
19919
  },
18398
19920
  /**
18399
- * Loads one impersonation for the request guard (5-second cache).
19921
+ * Loads one impersonation for the request guard. Only a finished (or
19922
+ * unknown) impersonation is cached for 5 seconds; an active one is read
19923
+ * on every request, so ending it on one process takes effect on every
19924
+ * other process at once (security review 2, hardening 4).
18400
19925
  *
18401
19926
  * @param {string} documentId Impersonation id.
18402
19927
  * @returns {Promise<{id: string, actorId: string, targetId: string|null, state: string,
@@ -18416,7 +19941,9 @@ var require_impersonation = __commonJS({
18416
19941
  state: row.state,
18417
19942
  expiresAt: new Date(row.expiresAt).getTime()
18418
19943
  } : null;
18419
- remember(recordCache, documentId, { value, at: Date.now() });
19944
+ if (!value || value.state !== "active") {
19945
+ remember(recordCache, documentId, { value, at: Date.now() });
19946
+ }
18420
19947
  return value;
18421
19948
  },
18422
19949
  /**
@@ -18532,6 +20059,7 @@ var require_impersonation2 = __commonJS({
18532
20059
  var { sendServerError } = require_http_errors();
18533
20060
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
18534
20061
  var IMPERSONATE_ADMINS_ACTION = "plugin::magic-sessionmanager.impersonate.admins";
20062
+ var { ADMIN_SIGN_IN_ACTION } = require_admin_sign_in_rules();
18535
20063
  function callerCan(ctx, action) {
18536
20064
  try {
18537
20065
  return ctx?.state?.userAbility?.can?.(action) === true;
@@ -18542,7 +20070,7 @@ var require_impersonation2 = __commonJS({
18542
20070
  function visibleTargetTypes(ctx) {
18543
20071
  return [
18544
20072
  ...callerCan(ctx, IMPERSONATE_USERS_ACTION) ? ["user"] : [],
18545
- ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) ? ["admin"] : []
20073
+ ...callerCan(ctx, IMPERSONATE_ADMINS_ACTION) || callerCan(ctx, ADMIN_SIGN_IN_ACTION) ? ["admin"] : []
18546
20074
  ];
18547
20075
  }
18548
20076
  var REPLY = Object.freeze({ 400: "badRequest", 403: "forbidden", 404: "notFound" });
@@ -18675,34 +20203,132 @@ var require_impersonation2 = __commonJS({
18675
20203
  return respond(ctx, "preview", async () => {
18676
20204
  const { adminId } = ctx.params;
18677
20205
  requirePerson(ctx, "admin", adminId);
18678
- const result = await service().previewAdmin({
20206
+ const result = await service().previewAdmin({
20207
+ actor: ctx.state.user,
20208
+ adminId,
20209
+ body: ctx.request.body,
20210
+ canReadAdmins: callerCan(ctx, "admin::users.read")
20211
+ });
20212
+ ctx.status = 201;
20213
+ ctx.body = { data: result };
20214
+ });
20215
+ },
20216
+ /**
20217
+ * Reads a running admin preview; only the admin who started it.
20218
+ *
20219
+ * @route GET /magic-sessionmanager/impersonation/previews/:id
20220
+ * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
20221
+ * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
20222
+ * expired or started by someone else.
20223
+ */
20224
+ async getPreview(ctx) {
20225
+ ctx.set("Cache-Control", "no-store");
20226
+ return respond(ctx, "preview", async () => {
20227
+ ctx.body = {
20228
+ data: await service().getPreview({
20229
+ id: ctx.params.id,
20230
+ viewer: ctx.state.user,
20231
+ canReadAdmins: callerCan(ctx, "admin::users.read")
20232
+ })
20233
+ };
20234
+ });
20235
+ },
20236
+ /**
20237
+ * Starts "Sign in as this admin" (4.23). Returns the landing path of the
20238
+ * new tab and a one-time code for it; no session exists yet.
20239
+ *
20240
+ * @route POST /magic-sessionmanager/impersonation/admins/:adminId/sign-in
20241
+ * @auth Admin JWT only (admin API tokens and impersonation sessions are refused);
20242
+ * `access` + `admin-sessions.read` + `impersonate.admins.sign-in`.
20243
+ * @param {any} ctx Body `{ reason: string(3..255), durationMinutes: 15|30,
20244
+ * allowChanges?: boolean }`.
20245
+ * @returns {Promise<void>} 201 `{ data: { impersonation, handoff: { type: 'admin-tab', path,
20246
+ * code, codeExpiresAt } } }`. Answers 403 with `details.reason` `disabled`, `unsupported`,
20247
+ * `api-token`, `nested`, `self`, `super-admin`, `not-subset`, `inactive` or
20248
+ * `already-active`, 400 for an invalid body and 404 for an unknown admin.
20249
+ * @sideeffect Creates an impersonation row; logs `impersonation.started` or `.refused`.
20250
+ */
20251
+ async signInAdmin(ctx) {
20252
+ ctx.set("Cache-Control", "no-store");
20253
+ return respond(ctx, "sign-in", async () => {
20254
+ const { adminId } = ctx.params;
20255
+ requirePerson(ctx, "admin", adminId);
20256
+ const result = await service().startAdminSignIn({
18679
20257
  actor: ctx.state.user,
18680
20258
  adminId,
18681
20259
  body: ctx.request.body,
18682
- canReadAdmins: callerCan(ctx, "admin::users.read")
20260
+ canReadAdmins: callerCan(ctx, "admin::users.read"),
20261
+ nested: Boolean(ctx.state.magicAdminImpersonation)
18683
20262
  });
18684
20263
  ctx.status = 201;
18685
20264
  ctx.body = { data: result };
18686
20265
  });
18687
20266
  },
18688
20267
  /**
18689
- * Reads a running admin preview; only the admin who started it.
20268
+ * Exchanges the one-time code of an admin sign-in for the target's
20269
+ * access token. Called by the new tab with the starting admin's own
20270
+ * token; only that admin can redeem the code. Every unusable code gets
20271
+ * the same 400.
18690
20272
  *
18691
- * @route GET /magic-sessionmanager/impersonation/previews/:id
18692
- * @auth Admin JWT or admin API token; `access` + `impersonate.admins`.
18693
- * @returns {Promise<void>} `{ data: { impersonation, preview } }`; 404 when unknown, ended,
18694
- * expired or started by someone else.
20273
+ * @route POST /magic-sessionmanager/admin-impersonation/exchange
20274
+ * @auth Admin JWT of the admin who started it (still holding `impersonate.admins.sign-in`).
20275
+ * @param {any} ctx Body `{ code: string }`.
20276
+ * @returns {Promise<void>} `{ data: { token, expiresAt, cookieName, impersonation } }`.
20277
+ * @sideeffect Consumes the code; creates one Strapi admin session for the target.
18695
20278
  */
18696
- async getPreview(ctx) {
20279
+ async exchangeAdmin(ctx) {
18697
20280
  ctx.set("Cache-Control", "no-store");
18698
- return respond(ctx, "preview", async () => {
18699
- ctx.body = {
18700
- data: await service().getPreview({
18701
- id: ctx.params.id,
18702
- viewer: ctx.state.user,
18703
- canReadAdmins: callerCan(ctx, "admin::users.read")
18704
- })
18705
- };
20281
+ const body = ctx.request.body;
20282
+ 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;
20283
+ return respond(ctx, "exchange", async () => {
20284
+ const result = valid ? await service().exchangeAdminCode({
20285
+ code: body.code,
20286
+ actor: ctx.state.user,
20287
+ ability: ctx.state.userAbility
20288
+ }) : null;
20289
+ if (!result) throw new ImpersonationError(400, "Invalid or expired code");
20290
+ ctx.body = { data: result };
20291
+ });
20292
+ },
20293
+ /**
20294
+ * State of the admin sign-in of the calling tab, for its banner.
20295
+ *
20296
+ * @route GET /magic-sessionmanager/admin-impersonation/self
20297
+ * @auth The impersonation session's own token (checked by the admin impersonation guard);
20298
+ * 401 for any other caller.
20299
+ * @returns {Promise<void>} `{ data: { id, expiresAt, allowChanges } }`.
20300
+ */
20301
+ async adminSelf(ctx) {
20302
+ ctx.set("Cache-Control", "no-store");
20303
+ const current = ctx.state.magicAdminImpersonation;
20304
+ if (!current) return ctx.unauthorized("Not an impersonation session");
20305
+ ctx.body = {
20306
+ data: {
20307
+ id: current.id,
20308
+ expiresAt: new Date(current.expiresAt).toISOString(),
20309
+ allowChanges: current.allowChanges === true
20310
+ }
20311
+ };
20312
+ return void 0;
20313
+ },
20314
+ /**
20315
+ * Ends the admin sign-in of the calling tab: deletes its own Strapi
20316
+ * session and nothing else.
20317
+ *
20318
+ * @route POST /magic-sessionmanager/admin-impersonation/self/end
20319
+ * @auth The impersonation session's own token; 401 for any other caller.
20320
+ * @returns {Promise<void>} `{ data: { ended: boolean } }`.
20321
+ * @sideeffect Ends the impersonation; logs `impersonation.ended`.
20322
+ */
20323
+ async endAdminSelf(ctx) {
20324
+ const current = ctx.state.magicAdminImpersonation;
20325
+ if (!current) return ctx.unauthorized("Not an impersonation session");
20326
+ return respond(ctx, "end", async () => {
20327
+ const ended = await service().end(current.id, {
20328
+ reason: "ended",
20329
+ endedBy: current.actorId
20330
+ });
20331
+ ctx.body = { data: { ended } };
18706
20332
  });
18707
20333
  },
18708
20334
  /**
@@ -18732,6 +20358,7 @@ var require_impersonation2 = __commonJS({
18732
20358
  };
18733
20359
  module.exports.IMPERSONATE_USERS_ACTION = IMPERSONATE_USERS_ACTION;
18734
20360
  module.exports.IMPERSONATE_ADMINS_ACTION = IMPERSONATE_ADMINS_ACTION;
20361
+ module.exports.ADMIN_SIGN_IN_ACTION = ADMIN_SIGN_IN_ACTION;
18735
20362
  }
18736
20363
  });
18737
20364
 
@@ -22606,6 +24233,7 @@ var require_security_log = __commonJS({
22606
24233
  function signInWhere(query) {
22607
24234
  const conditions = [{ event: { $in: [...SIGN_IN_FILTERS[query.event || "all"]] } }];
22608
24235
  if (query.adminId) conditions.push({ targetType: "admin", targetId: String(query.adminId) });
24236
+ else if (query.event === "impersonation") conditions.push({ targetType: "admin" });
22609
24237
  if (query.from) conditions.push({ createdAt: { $gte: query.from } });
22610
24238
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
22611
24239
  return { $and: conditions };
@@ -22953,227 +24581,6 @@ var require_security_log = __commonJS({
22953
24581
  }
22954
24582
  });
22955
24583
 
22956
- // server/src/utils/webhook-delivery.js
22957
- var require_webhook_delivery = __commonJS({
22958
- "server/src/utils/webhook-delivery.js"(exports, module) {
22959
- "use strict";
22960
- var crypto = __require("node:crypto");
22961
- var dns = __require("node:dns");
22962
- var https = __require("node:https");
22963
- var net = __require("node:net");
22964
- var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
22965
- var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
22966
- var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
22967
- var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
22968
- var TIMEOUT_MS = 5e3;
22969
- var MAX_RESPONSE_BYTES = 64 * 1024;
22970
- var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
22971
- var BLOCKED = (() => {
22972
- const list = new net.BlockList();
22973
- for (const [address, prefix] of [
22974
- ["0.0.0.0", 8],
22975
- ["10.0.0.0", 8],
22976
- ["100.64.0.0", 10],
22977
- ["127.0.0.0", 8],
22978
- ["169.254.0.0", 16],
22979
- ["172.16.0.0", 12],
22980
- ["192.0.0.0", 24],
22981
- ["192.0.2.0", 24],
22982
- ["192.88.99.0", 24],
22983
- ["192.168.0.0", 16],
22984
- ["198.18.0.0", 15],
22985
- ["198.51.100.0", 24],
22986
- ["203.0.113.0", 24],
22987
- ["224.0.0.0", 4],
22988
- ["240.0.0.0", 4]
22989
- ]) {
22990
- list.addSubnet(address, prefix, "ipv4");
22991
- }
22992
- for (const [address, prefix] of [
22993
- ["::", 128],
22994
- ["::1", 128],
22995
- // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
22996
- // checks them against the IPv4 rules above, and a listed /96 would
22997
- // match every IPv4 address.
22998
- ["64:ff9b::", 96],
22999
- ["64:ff9b:1::", 48],
23000
- ["100::", 64],
23001
- ["2001::", 23],
23002
- ["2001:db8::", 32],
23003
- ["2002::", 16],
23004
- ["fc00::", 7],
23005
- ["fe80::", 10],
23006
- ["fec0::", 10],
23007
- ["ff00::", 8]
23008
- ]) {
23009
- list.addSubnet(address, prefix, "ipv6");
23010
- }
23011
- return list;
23012
- })();
23013
- function isBlockedAddress(address) {
23014
- let value = String(address || "").trim();
23015
- if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
23016
- value = value.slice(7);
23017
- }
23018
- const version = net.isIP(value);
23019
- if (version === 0) return true;
23020
- return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
23021
- }
23022
- function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
23023
- const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
23024
- return `t=${timestamp},v1=${digest}`;
23025
- }
23026
- function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
23027
- const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
23028
- if (!match) return false;
23029
- const timestamp = Number(match[1]);
23030
- if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
23031
- const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
23032
- const given = Buffer.from(match[2], "hex");
23033
- return given.length === expected.length && crypto.timingSafeEqual(given, expected);
23034
- }
23035
- var DeliveryError = class extends Error {
23036
- /**
23037
- * @param {string} code Stable code.
23038
- * @param {boolean} retryable Whether another attempt may succeed.
23039
- * @param {number|null} [status] HTTP status, when there was one.
23040
- */
23041
- constructor(code, retryable, status = null) {
23042
- super(code);
23043
- this.name = "DeliveryError";
23044
- this.code = code;
23045
- this.retryable = retryable;
23046
- this.status = status;
23047
- }
23048
- };
23049
- var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
23050
- function httpsPost({ url, address, headers, body, timeoutMs }) {
23051
- return new Promise((resolve, reject) => {
23052
- const request = https.request(
23053
- {
23054
- protocol: "https:",
23055
- hostname: url.hostname,
23056
- port: url.port || 443,
23057
- path: `${url.pathname}${url.search}`,
23058
- method: "POST",
23059
- headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
23060
- servername: net.isIP(url.hostname) ? void 0 : url.hostname,
23061
- timeout: timeoutMs,
23062
- // Pinned to the address that passed the check: no second lookup.
23063
- lookup: (_hostname, options, callback) => {
23064
- if (options && options.all) callback(null, [address]);
23065
- else callback(null, address.address, address.family);
23066
- }
23067
- },
23068
- (response) => {
23069
- let received = 0;
23070
- response.on("data", (chunk) => {
23071
- received += chunk.length;
23072
- if (received > MAX_RESPONSE_BYTES) response.destroy();
23073
- });
23074
- response.on("end", () => resolve(response.statusCode || 0));
23075
- response.on("close", () => resolve(response.statusCode || 0));
23076
- response.on("error", () => resolve(response.statusCode || 0));
23077
- }
23078
- );
23079
- request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
23080
- request.on(
23081
- "error",
23082
- (err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
23083
- );
23084
- request.end(body);
23085
- });
23086
- }
23087
- async function deliverOnce({
23088
- url,
23089
- body,
23090
- headers,
23091
- resolve = resolveAll,
23092
- post = httpsPost,
23093
- timeoutMs = TIMEOUT_MS
23094
- }) {
23095
- let parsed;
23096
- try {
23097
- parsed = new URL(url);
23098
- } catch {
23099
- throw new DeliveryError("invalid_url", false);
23100
- }
23101
- if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
23102
- throw new DeliveryError("invalid_url", false);
23103
- }
23104
- const host = parsed.hostname.replace(/^\[|\]$/g, "");
23105
- let addresses;
23106
- if (net.isIP(host)) {
23107
- addresses = [{ address: host, family: net.isIP(host) }];
23108
- } else {
23109
- try {
23110
- addresses = await resolve(host);
23111
- } catch {
23112
- throw new DeliveryError("dns_failed", true);
23113
- }
23114
- }
23115
- if (!Array.isArray(addresses) || addresses.length === 0)
23116
- throw new DeliveryError("dns_failed", true);
23117
- if (addresses.some((entry) => isBlockedAddress(entry.address))) {
23118
- throw new DeliveryError("address_not_allowed", false);
23119
- }
23120
- const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
23121
- if (status >= 200 && status < 300) return { status };
23122
- if (status >= 300 && status < 400)
23123
- throw new DeliveryError("redirect_not_followed", false, status);
23124
- throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
23125
- }
23126
- function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
23127
- const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
23128
- return {
23129
- id,
23130
- body,
23131
- headers: {
23132
- "Content-Type": "application/json",
23133
- "User-Agent": USER_AGENT,
23134
- [EVENT_HEADER]: event,
23135
- [DELIVERY_HEADER]: id,
23136
- [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
23137
- }
23138
- };
23139
- }
23140
- async function deliverWithRetries({
23141
- delays = RETRY_DELAYS_MS,
23142
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
23143
- ...request
23144
- }) {
23145
- let attempts = 0;
23146
- let last = { ok: false, status: null, code: "not_sent" };
23147
- for (const delay of delays) {
23148
- if (delay > 0) await sleep(delay);
23149
- attempts += 1;
23150
- try {
23151
- const { status } = await deliverOnce(request);
23152
- return { ok: true, status, code: null, attempts };
23153
- } catch (err) {
23154
- const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
23155
- last = { ok: false, status: error.status, code: error.code };
23156
- if (!error.retryable) break;
23157
- }
23158
- }
23159
- return { ...last, attempts };
23160
- }
23161
- module.exports = {
23162
- DELIVERY_HEADER,
23163
- DeliveryError,
23164
- EVENT_HEADER,
23165
- RETRY_DELAYS_MS,
23166
- SIGNATURE_HEADER,
23167
- buildSignedRequest,
23168
- deliverOnce,
23169
- deliverWithRetries,
23170
- isBlockedAddress,
23171
- signPayload,
23172
- verifySignature
23173
- };
23174
- }
23175
- });
23176
-
23177
24584
  // server/src/services/webhooks.js
23178
24585
  var require_webhooks2 = __commonJS({
23179
24586
  "server/src/services/webhooks.js"(exports, module) {
@@ -23452,12 +24859,14 @@ var require_rate_limit = __commonJS({
23452
24859
  "use strict";
23453
24860
  var { getPluginSettings } = require_settings_loader();
23454
24861
  var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
24862
+ var { ipBucket } = require_admin_request_info();
23455
24863
  var callerKey = (ctx) => {
23456
24864
  const userId = ctx.state?.user?.id;
23457
24865
  if (userId) return `u:${userId}`;
23458
24866
  const tokenId = ctx.state?.auth?.credentials?.id ?? ctx.state?.auth?.credentials?.token ?? null;
23459
24867
  if (tokenId) return `t:${String(tokenId).slice(-16)}`;
23460
- return `ip:${ctx.request.ip || ctx.ip || "unknown"}`;
24868
+ const ip = ctx.request.ip || ctx.ip || "";
24869
+ return `ip:${ipBucket(ip) || ip || "unknown"}`;
23461
24870
  };
23462
24871
  var routeKey = (ctx) => {
23463
24872
  const route = ctx.state?.route;
@@ -23662,7 +25071,7 @@ var require_can_impersonate = __commonJS({
23662
25071
  return false;
23663
25072
  }
23664
25073
  };
23665
- return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins");
25074
+ return can("plugin::magic-sessionmanager.impersonate.users") || can("plugin::magic-sessionmanager.impersonate.admins") || can("plugin::magic-sessionmanager.impersonate.admins.sign-in");
23666
25075
  };
23667
25076
  }
23668
25077
  });