strapi-plugin-magic-sessionmanager 4.21.0 → 4.22.1

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 (33) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +92 -47
  3. package/dist/admin/{Analytics-BqdZIBV4.js → Analytics-B7BAjApz.js} +1 -1
  4. package/dist/admin/{Analytics-C-OLLzoB.mjs → Analytics-CIHgaURb.mjs} +1 -1
  5. package/dist/admin/{App-BswHmNQT.mjs → App-CPE-CQGz.mjs} +1309 -2564
  6. package/dist/admin/{App-Cx9v6n_7.js → App-DJkJC06E.js} +1336 -2591
  7. package/dist/admin/{OnlineUsersWidget-BRmQPPp9.js → OnlineUsersWidget-CcjNfzzf.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Dusgjc1d.mjs → OnlineUsersWidget-Dou2hxGY.mjs} +1 -1
  9. package/dist/admin/{Settings-DWGuf_Z3.js → Settings--eEiHv_a.js} +104 -81
  10. package/dist/admin/{Settings-DZyQheUS.mjs → Settings-h_exWUiI.mjs} +62 -39
  11. package/dist/admin/dashboardModel-DNT_l-Bk.js +169 -0
  12. package/dist/admin/dashboardModel-fApbKGay.mjs +170 -0
  13. package/dist/admin/{de-DUnrmFWk.mjs → de-Wz5Emtrb.mjs} +79 -7
  14. package/dist/admin/{de-24TPqzG6.js → de-oBmcAcXj.js} +79 -7
  15. package/dist/admin/{en-8mBSkWOF.js → en-B1TN5F62.js} +80 -8
  16. package/dist/admin/{en-D8J__tyF.mjs → en-B_1Ka64U.mjs} +80 -8
  17. package/dist/admin/{es-ChUKey-Q.js → es-Bb515J0p.js} +79 -7
  18. package/dist/admin/{es-BgpgWdk0.mjs → es-CVgw4zsj.mjs} +79 -7
  19. package/dist/admin/{fr-k1MHYKJo.mjs → fr-0AgMxTFc.mjs} +79 -7
  20. package/dist/admin/{fr-DE_CWmgq.js → fr-yDdwunmg.js} +79 -7
  21. package/dist/admin/index-DVQ7tdTC.mjs +4746 -0
  22. package/dist/admin/index-qtN2dOm4.js +4747 -0
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +2 -2
  25. package/dist/admin/{pt-BjqU5ioB.js → pt-BAB07LY-.js} +79 -7
  26. package/dist/admin/{pt-DPO4DmDc.mjs → pt-DtM74ffN.mjs} +79 -7
  27. package/dist/server/index.js +1487 -438
  28. package/dist/server/index.mjs +1487 -438
  29. package/package.json +4 -3
  30. package/dist/admin/index-Ceh3Q1Ki.js +0 -2308
  31. package/dist/admin/index-meLDPPwt.mjs +0 -2307
  32. package/dist/admin/settingsTabs-C1q5iMMw.mjs +0 -437
  33. package/dist/admin/settingsTabs-CfquZuKH.js +0 -436
@@ -1471,10 +1471,249 @@ var require_policy_settings = __commonJS({
1471
1471
  }
1472
1472
  });
1473
1473
 
1474
+ // server/src/utils/webhook-delivery.js
1475
+ var require_webhook_delivery = __commonJS({
1476
+ "server/src/utils/webhook-delivery.js"(exports2, module2) {
1477
+ "use strict";
1478
+ var crypto = require("node:crypto");
1479
+ var dns = require("node:dns");
1480
+ var https = require("node:https");
1481
+ var net = require("node:net");
1482
+ var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
1483
+ var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
1484
+ var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
1485
+ var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
1486
+ var TIMEOUT_MS = 5e3;
1487
+ var DEADLINE_MS = 1e4;
1488
+ var MAX_RESPONSE_BYTES = 64 * 1024;
1489
+ var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
1490
+ var BLOCKED = (() => {
1491
+ const list = new net.BlockList();
1492
+ for (const [address, prefix] of [
1493
+ ["0.0.0.0", 8],
1494
+ ["10.0.0.0", 8],
1495
+ ["100.64.0.0", 10],
1496
+ ["127.0.0.0", 8],
1497
+ ["169.254.0.0", 16],
1498
+ ["172.16.0.0", 12],
1499
+ ["192.0.0.0", 24],
1500
+ ["192.0.2.0", 24],
1501
+ ["192.88.99.0", 24],
1502
+ ["192.168.0.0", 16],
1503
+ ["198.18.0.0", 15],
1504
+ ["198.51.100.0", 24],
1505
+ ["203.0.113.0", 24],
1506
+ ["224.0.0.0", 4],
1507
+ ["240.0.0.0", 4]
1508
+ ]) {
1509
+ list.addSubnet(address, prefix, "ipv4");
1510
+ }
1511
+ for (const [address, prefix] of [
1512
+ // IPv4-compatible (::a.b.c.d, deprecated) and IPv4-translated
1513
+ // (::ffff:0:a.b.c.d, RFC 2765) forms, which include the unspecified and
1514
+ // loopback addresses (security review 2, hardening 1).
1515
+ ["::", 96],
1516
+ ["::ffff:0:0:0", 96],
1517
+ // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
1518
+ // checks them against the IPv4 rules above, and a listed /96 would
1519
+ // match every IPv4 address.
1520
+ ["64:ff9b::", 96],
1521
+ ["64:ff9b:1::", 48],
1522
+ ["100::", 64],
1523
+ ["2001::", 23],
1524
+ ["2001:db8::", 32],
1525
+ ["2002::", 16],
1526
+ ["fc00::", 7],
1527
+ ["fe80::", 10],
1528
+ ["fec0::", 10],
1529
+ ["ff00::", 8]
1530
+ ]) {
1531
+ list.addSubnet(address, prefix, "ipv6");
1532
+ }
1533
+ return list;
1534
+ })();
1535
+ function isBlockedAddress(address) {
1536
+ let value = String(address || "").trim();
1537
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
1538
+ value = value.slice(7);
1539
+ }
1540
+ const version = net.isIP(value);
1541
+ if (version === 0) return true;
1542
+ return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
1543
+ }
1544
+ function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
1545
+ const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
1546
+ return `t=${timestamp},v1=${digest}`;
1547
+ }
1548
+ function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
1549
+ const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
1550
+ if (!match) return false;
1551
+ const timestamp = Number(match[1]);
1552
+ if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
1553
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
1554
+ const given = Buffer.from(match[2], "hex");
1555
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
1556
+ }
1557
+ var DeliveryError = class extends Error {
1558
+ /**
1559
+ * @param {string} code Stable code.
1560
+ * @param {boolean} retryable Whether another attempt may succeed.
1561
+ * @param {number|null} [status] HTTP status, when there was one.
1562
+ */
1563
+ constructor(code, retryable, status = null) {
1564
+ super(code);
1565
+ this.name = "DeliveryError";
1566
+ this.code = code;
1567
+ this.retryable = retryable;
1568
+ this.status = status;
1569
+ }
1570
+ };
1571
+ var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
1572
+ function httpsPost({ url, address, headers, body, timeoutMs, deadlineMs = DEADLINE_MS }) {
1573
+ return new Promise((resolve, reject) => {
1574
+ const request = https.request(
1575
+ {
1576
+ protocol: "https:",
1577
+ hostname: url.hostname,
1578
+ port: url.port || 443,
1579
+ path: `${url.pathname}${url.search}`,
1580
+ method: "POST",
1581
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
1582
+ servername: net.isIP(url.hostname) ? void 0 : url.hostname,
1583
+ timeout: timeoutMs,
1584
+ signal: AbortSignal.timeout(deadlineMs),
1585
+ // Pinned to the address that passed the check: no second lookup.
1586
+ lookup: (_hostname, options, callback) => {
1587
+ if (options && options.all) callback(null, [address]);
1588
+ else callback(null, address.address, address.family);
1589
+ }
1590
+ },
1591
+ (response) => {
1592
+ let received = 0;
1593
+ response.on("data", (chunk) => {
1594
+ received += chunk.length;
1595
+ if (received > MAX_RESPONSE_BYTES) response.destroy();
1596
+ });
1597
+ response.on("end", () => resolve(response.statusCode || 0));
1598
+ response.on("close", () => resolve(response.statusCode || 0));
1599
+ response.on("error", () => resolve(response.statusCode || 0));
1600
+ }
1601
+ );
1602
+ request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
1603
+ request.on(
1604
+ "error",
1605
+ (err) => reject(
1606
+ err instanceof DeliveryError ? err : err?.name === "AbortError" ? new DeliveryError("timeout", true) : new DeliveryError("network_error", true)
1607
+ )
1608
+ );
1609
+ request.end(body);
1610
+ });
1611
+ }
1612
+ async function deliverOnce({
1613
+ url,
1614
+ body,
1615
+ headers,
1616
+ resolve = resolveAll,
1617
+ post = httpsPost,
1618
+ timeoutMs = TIMEOUT_MS,
1619
+ deadlineMs = DEADLINE_MS
1620
+ }) {
1621
+ let parsed;
1622
+ try {
1623
+ parsed = new URL(url);
1624
+ } catch {
1625
+ throw new DeliveryError("invalid_url", false);
1626
+ }
1627
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
1628
+ throw new DeliveryError("invalid_url", false);
1629
+ }
1630
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
1631
+ let addresses;
1632
+ if (net.isIP(host)) {
1633
+ addresses = [{ address: host, family: net.isIP(host) }];
1634
+ } else {
1635
+ try {
1636
+ addresses = await resolve(host);
1637
+ } catch {
1638
+ throw new DeliveryError("dns_failed", true);
1639
+ }
1640
+ }
1641
+ if (!Array.isArray(addresses) || addresses.length === 0)
1642
+ throw new DeliveryError("dns_failed", true);
1643
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
1644
+ throw new DeliveryError("address_not_allowed", false);
1645
+ }
1646
+ const status = await post({
1647
+ url: parsed,
1648
+ address: addresses[0],
1649
+ headers,
1650
+ body,
1651
+ timeoutMs,
1652
+ deadlineMs
1653
+ });
1654
+ if (status >= 200 && status < 300) return { status };
1655
+ if (status >= 300 && status < 400)
1656
+ throw new DeliveryError("redirect_not_followed", false, status);
1657
+ throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
1658
+ }
1659
+ function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
1660
+ const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
1661
+ return {
1662
+ id,
1663
+ body,
1664
+ headers: {
1665
+ "Content-Type": "application/json",
1666
+ "User-Agent": USER_AGENT,
1667
+ [EVENT_HEADER]: event,
1668
+ [DELIVERY_HEADER]: id,
1669
+ [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
1670
+ }
1671
+ };
1672
+ }
1673
+ async function deliverWithRetries({
1674
+ delays = RETRY_DELAYS_MS,
1675
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
1676
+ ...request
1677
+ }) {
1678
+ let attempts = 0;
1679
+ let last = { ok: false, status: null, code: "not_sent" };
1680
+ for (const delay of delays) {
1681
+ if (delay > 0) await sleep(delay);
1682
+ attempts += 1;
1683
+ try {
1684
+ const { status } = await deliverOnce(request);
1685
+ return { ok: true, status, code: null, attempts };
1686
+ } catch (err) {
1687
+ const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
1688
+ last = { ok: false, status: error.status, code: error.code };
1689
+ if (!error.retryable) break;
1690
+ }
1691
+ }
1692
+ return { ...last, attempts };
1693
+ }
1694
+ module2.exports = {
1695
+ DEADLINE_MS,
1696
+ DELIVERY_HEADER,
1697
+ DeliveryError,
1698
+ EVENT_HEADER,
1699
+ RETRY_DELAYS_MS,
1700
+ SIGNATURE_HEADER,
1701
+ buildSignedRequest,
1702
+ deliverOnce,
1703
+ deliverWithRetries,
1704
+ isBlockedAddress,
1705
+ signPayload,
1706
+ verifySignature
1707
+ };
1708
+ }
1709
+ });
1710
+
1474
1711
  // server/src/utils/detection-settings.js
1475
1712
  var require_detection_settings = __commonJS({
1476
1713
  "server/src/utils/detection-settings.js"(exports2, module2) {
1477
1714
  "use strict";
1715
+ var net = require("node:net");
1716
+ var { isBlockedAddress } = require_webhook_delivery();
1478
1717
  var WEBHOOK_EVENTS = Object.freeze([
1479
1718
  "login.success",
1480
1719
  "login.suspicious",
@@ -1559,6 +1798,8 @@ var require_detection_settings = __commonJS({
1559
1798
  if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
1560
1799
  return null;
1561
1800
  }
1801
+ const literal = host.replace(/^\[|\]$/g, "");
1802
+ if (net.isIP(literal) && isBlockedAddress(literal)) return null;
1562
1803
  return parsed.toString();
1563
1804
  }
1564
1805
  function normalizeEventList(value) {
@@ -1929,6 +2170,89 @@ var require_impersonation_rules = __commonJS({
1929
2170
  }
1930
2171
  });
1931
2172
 
2173
+ // server/src/utils/trusted-proxies.js
2174
+ var require_trusted_proxies = __commonJS({
2175
+ "server/src/utils/trusted-proxies.js"(exports2, module2) {
2176
+ "use strict";
2177
+ var { parseTrustedAddress } = require_policy_settings();
2178
+ var MAX_TRUSTED_PROXIES = 50;
2179
+ function normalizeTrustedProxies(value) {
2180
+ if (!Array.isArray(value)) return [];
2181
+ const out = [];
2182
+ for (const entry of value.slice(0, MAX_TRUSTED_PROXIES)) {
2183
+ const parsed = parseTrustedAddress(entry);
2184
+ if (parsed && !out.includes(parsed.text)) out.push(parsed.text);
2185
+ }
2186
+ return out;
2187
+ }
2188
+ function isLegacyTrustAll(value) {
2189
+ return value === true;
2190
+ }
2191
+ function validateTrustedProxies(value) {
2192
+ if (typeof value === "boolean") return { value: [], error: null, legacyTrue: value };
2193
+ if (!Array.isArray(value) || value.length > MAX_TRUSTED_PROXIES) {
2194
+ return {
2195
+ value: null,
2196
+ legacyTrue: false,
2197
+ error: {
2198
+ path: ["trustedProxies"],
2199
+ message: `trustedProxies must be a list of at most ${MAX_TRUSTED_PROXIES} IP addresses or CIDR ranges`
2200
+ }
2201
+ };
2202
+ }
2203
+ const parsed = value.map(parseTrustedAddress);
2204
+ const invalid = parsed.findIndex((entry) => entry === null);
2205
+ if (invalid !== -1) {
2206
+ return {
2207
+ value: null,
2208
+ legacyTrue: false,
2209
+ error: {
2210
+ path: ["trustedProxies", invalid],
2211
+ message: "Each trusted proxy must be an IP address or a CIDR range such as 10.0.0.0/8"
2212
+ }
2213
+ };
2214
+ }
2215
+ return {
2216
+ value: [...new Set(parsed.map((entry) => (
2217
+ /** @type {any} */
2218
+ entry.text
2219
+ )))],
2220
+ error: null,
2221
+ legacyTrue: false
2222
+ };
2223
+ }
2224
+ var LEGACY_WARNING = "[CONFIG] trustedProxies: true no longer makes the plugin read CF-Connecting-IP, True-Client-IP, X-Real-IP or the left-most X-Forwarded-For entry (a client can set them). The client IP now comes from Strapi's server.proxy settings (koa, ipHeader, maxIpsCount). To trust specific proxies instead, set trustedProxies to a list of their IP addresses or CIDR ranges.";
2225
+ async function migrateLegacyProxyTrust(strapi2, log) {
2226
+ const { withPluginStoreKey } = require_plugin_store();
2227
+ const { notifySettingsChanged } = require_settings_loader();
2228
+ const config2 = isLegacyTrustAll(
2229
+ strapi2.config.get("plugin::magic-sessionmanager")?.trustedProxies
2230
+ );
2231
+ const store = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
2232
+ let stored = isLegacyTrustAll((await store.get({ key: "settings" }))?.trustedProxies);
2233
+ if (stored) {
2234
+ stored = await withPluginStoreKey(strapi2, "settings", async (scoped) => {
2235
+ const value = await scoped.get({ key: "settings" });
2236
+ if (!value || !isLegacyTrustAll(value.trustedProxies)) return false;
2237
+ await scoped.set({ key: "settings", value: { ...value, trustedProxies: [] } });
2238
+ return true;
2239
+ });
2240
+ if (stored) await notifySettingsChanged(strapi2);
2241
+ }
2242
+ if (stored || config2) log.warn(LEGACY_WARNING);
2243
+ return { stored, config: config2 };
2244
+ }
2245
+ module2.exports = {
2246
+ LEGACY_WARNING,
2247
+ MAX_TRUSTED_PROXIES,
2248
+ isLegacyTrustAll,
2249
+ migrateLegacyProxyTrust,
2250
+ normalizeTrustedProxies,
2251
+ validateTrustedProxies
2252
+ };
2253
+ }
2254
+ });
2255
+
1932
2256
  // server/src/utils/settings-loader.js
1933
2257
  var require_settings_loader = __commonJS({
1934
2258
  "server/src/utils/settings-loader.js"(exports2, module2) {
@@ -1937,6 +2261,7 @@ var require_settings_loader = __commonJS({
1937
2261
  var { normalizePolicySettings } = require_policy_settings();
1938
2262
  var { normalizeDetectionSettings } = require_detection_settings();
1939
2263
  var { normalizeImpersonationSettings } = require_impersonation_rules();
2264
+ var { normalizeTrustedProxies } = require_trusted_proxies();
1940
2265
  var PLUGIN_ID = "magic-sessionmanager";
1941
2266
  var SETTINGS_KEY = "settings";
1942
2267
  var CACHE_TTL_MS = 30 * 1e3;
@@ -2066,7 +2391,8 @@ var require_settings_loader = __commonJS({
2066
2391
  out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 7, 730);
2067
2392
  }
2068
2393
  if (stored.trustedProxies !== void 0) {
2069
- out.trustedProxies = stored.trustedProxies;
2394
+ const proxies = normalizeTrustedProxies(stored.trustedProxies);
2395
+ if (proxies.length > 0) out.trustedProxies = proxies;
2070
2396
  }
2071
2397
  Object.assign(out, normalizePolicySettings(stored));
2072
2398
  Object.assign(out, normalizeDetectionSettings(stored));
@@ -2185,6 +2511,8 @@ var require_security_log_model = __commonJS({
2185
2511
  SETTINGS_UPDATED: "settings.updated",
2186
2512
  LOG_RETENTION_PURGED: "security-log.retention.purged",
2187
2513
  LOG_READ: "security-log.read",
2514
+ // 4.22.1: SESSION_ENCRYPTION_KEY shorter than 32 bytes, once per key.
2515
+ CONFIG_WEAK_KEY: "config.encryption-key.weak",
2188
2516
  // App users (Users & Permissions), 4.17.
2189
2517
  USER_SIGN_IN_FAILED: "user.sign-in.failed",
2190
2518
  USER_SIGN_IN_REFUSED: "user.sign-in.refused",
@@ -2248,7 +2576,8 @@ var require_security_log_model = __commonJS({
2248
2576
  var ADMIN_LOG_EVENTS = Object.freeze([
2249
2577
  SECURITY_EVENTS.SETTINGS_UPDATED,
2250
2578
  SECURITY_EVENTS.LOG_READ,
2251
- SECURITY_EVENTS.LOG_RETENTION_PURGED
2579
+ SECURITY_EVENTS.LOG_RETENTION_PURGED,
2580
+ SECURITY_EVENTS.CONFIG_WEAK_KEY
2252
2581
  ]);
2253
2582
  var SIGN_IN_FILTERS = Object.freeze({
2254
2583
  all: [...ADMIN_SIGN_IN_EVENTS, ...ADMIN_LOG_EVENTS],
@@ -2657,15 +2986,187 @@ var require_security_log_hardening = __commonJS({
2657
2986
  }
2658
2987
  });
2659
2988
 
2660
- // server/src/register.js
2661
- var require_register = __commonJS({
2662
- "server/src/register.js"(exports2, module2) {
2989
+ // server/src/utils/graphql-impersonation-guard.js
2990
+ var require_graphql_impersonation_guard = __commonJS({
2991
+ "server/src/utils/graphql-impersonation-guard.js"(exports2, module2) {
2663
2992
  "use strict";
2664
- var { createLogger } = require_logger();
2665
- var { createContentApiPermissionsLifecycle } = require_content_api_permissions();
2666
- var { isCallerRevocationScope } = require_block_revocation_scope();
2993
+ var { errors } = require("@strapi/utils");
2994
+ var MARK = /* @__PURE__ */ Symbol.for("magic-sessionmanager.graphql-impersonation-guard");
2995
+ var MESSAGE = "Not allowed while impersonating";
2996
+ var REASON = "impersonation-mutation";
2997
+ function impersonationRefusal() {
2998
+ const error = new errors.ForbiddenError(MESSAGE, { reason: REASON });
2999
+ Object.defineProperty(error, "extensions", {
3000
+ value: {
3001
+ code: "FORBIDDEN",
3002
+ http: { status: 403 },
3003
+ error: { name: "ForbiddenError", message: MESSAGE, details: { reason: REASON } }
3004
+ },
3005
+ enumerable: false
3006
+ });
3007
+ return error;
3008
+ }
3009
+ function impersonationOf(contextValue) {
3010
+ const mark = contextValue?.koaContext?.state?.magicImpersonation ?? contextValue?.state?.magicImpersonation;
3011
+ return mark && typeof mark === "object" && typeof mark.id === "string" ? mark : null;
3012
+ }
3013
+ function createImpersonationApolloPlugin(strapi2) {
3014
+ return {
3015
+ [MARK]: true,
3016
+ async requestDidStart() {
3017
+ return {
3018
+ /**
3019
+ * @param {any} requestContext Apollo request context.
3020
+ * @returns {Promise<void>}
3021
+ * @throws {Error} ForbiddenError (HTTP 403, code FORBIDDEN) for a mutation while impersonating.
3022
+ */
3023
+ async didResolveOperation(requestContext) {
3024
+ if (requestContext?.operation?.operation !== "mutation") return;
3025
+ const impersonation = impersonationOf(requestContext.contextValue);
3026
+ if (!impersonation) return;
3027
+ try {
3028
+ strapi2.plugin("magic-sessionmanager").service("impersonation").recordRefusedCall(impersonation, "mutation");
3029
+ } catch {
3030
+ }
3031
+ throw impersonationRefusal();
3032
+ }
3033
+ };
3034
+ }
3035
+ };
3036
+ }
3037
+ function installGraphqlImpersonationGuard(strapi2, log) {
3038
+ let graphql;
3039
+ try {
3040
+ graphql = strapi2.plugin("graphql") || null;
3041
+ } catch {
3042
+ graphql = null;
3043
+ }
3044
+ if (!graphql) return false;
3045
+ if (typeof strapi2.config?.get !== "function" || typeof strapi2.config?.set !== "function") {
3046
+ return false;
3047
+ }
3048
+ try {
3049
+ const key = "plugin::graphql.apolloServer";
3050
+ const current = strapi2.config.get(key);
3051
+ const server = current && typeof current === "object" ? current : {};
3052
+ const plugins = Array.isArray(server.plugins) ? server.plugins : [];
3053
+ if (plugins.some((plugin) => plugin && plugin[MARK])) return true;
3054
+ strapi2.config.set(key, {
3055
+ ...server,
3056
+ plugins: [...plugins, createImpersonationApolloPlugin(strapi2)]
3057
+ });
3058
+ } catch (err) {
3059
+ log?.warn?.("[IMPERSONATION] GraphQL guard could not be installed:", err?.name || "Error");
3060
+ return false;
3061
+ }
3062
+ log?.info?.("[IMPERSONATION] GraphQL mutations are refused while impersonating");
3063
+ return true;
3064
+ }
3065
+ module2.exports = {
3066
+ createImpersonationApolloPlugin,
3067
+ impersonationRefusal,
3068
+ installGraphqlImpersonationGuard
3069
+ };
3070
+ }
3071
+ });
3072
+
3073
+ // server/src/utils/auth-controller-guard.js
3074
+ var require_auth_controller_guard = __commonJS({
3075
+ "server/src/utils/auth-controller-guard.js"(exports2, module2) {
3076
+ "use strict";
3077
+ var WRAPPED = /* @__PURE__ */ Symbol.for("magic-sessionmanager.auth-controller.wrapped");
3078
+ var GUARDED_ACTIONS = Object.freeze({
3079
+ callback: "callback",
3080
+ register: "newSession",
3081
+ resetPassword: "newSession",
3082
+ emailConfirmation: "newSession"
3083
+ });
3084
+ var handlersByStrapi = /* @__PURE__ */ new WeakMap();
3085
+ function installAuthControllerGuard(strapi2, log) {
3086
+ let controller;
3087
+ try {
3088
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3089
+ } catch {
3090
+ controller = null;
3091
+ }
3092
+ if (!controller || typeof controller !== "object") {
3093
+ log?.warn?.(
3094
+ "[AUTH] Users & Permissions auth controller not found; sign-in checks use paths only"
3095
+ );
3096
+ return [];
3097
+ }
3098
+ const wrapped = [];
3099
+ for (const [action, kind] of Object.entries(GUARDED_ACTIONS)) {
3100
+ const original = controller[action];
3101
+ if (typeof original !== "function") continue;
3102
+ if (original[WRAPPED]) {
3103
+ wrapped.push(action);
3104
+ continue;
3105
+ }
3106
+ const guarded = async function magicSessionAuthGuard(ctx, ...rest) {
3107
+ const run = () => original.call(this, ctx, ...rest);
3108
+ const handlers = handlersByStrapi.get(strapi2);
3109
+ if (!handlers || typeof handlers[kind] !== "function") return run();
3110
+ return handlers[kind](ctx, run);
3111
+ };
3112
+ Object.defineProperty(guarded, WRAPPED, { value: original });
3113
+ controller[action] = guarded;
3114
+ wrapped.push(action);
3115
+ }
3116
+ return wrapped;
3117
+ }
3118
+ function setAuthControllerHandlers(strapi2, handlers) {
3119
+ if (handlers) handlersByStrapi.set(strapi2, handlers);
3120
+ else handlersByStrapi.delete(strapi2);
3121
+ }
3122
+ function uninstallAuthControllerGuard(strapi2) {
3123
+ setAuthControllerHandlers(strapi2, null);
3124
+ let controller;
3125
+ try {
3126
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3127
+ } catch {
3128
+ return;
3129
+ }
3130
+ if (!controller) return;
3131
+ for (const action of Object.keys(GUARDED_ACTIONS)) {
3132
+ const original = controller[action]?.[WRAPPED];
3133
+ if (typeof original === "function") controller[action] = original;
3134
+ }
3135
+ }
3136
+ var INVALID_CREDENTIALS_MESSAGE = "Invalid identifier or password";
3137
+ function classifyCallbackOutcome(thrown, ctx) {
3138
+ if (thrown) {
3139
+ const error = (
3140
+ /** @type {any} */
3141
+ thrown
3142
+ );
3143
+ return error?.name === "ValidationError" && error?.message === INVALID_CREDENTIALS_MESSAGE ? "failure" : "neutral";
3144
+ }
3145
+ const body = ctx?.body;
3146
+ return body && typeof body === "object" && body.jwt ? "success" : "neutral";
3147
+ }
3148
+ module2.exports = {
3149
+ GUARDED_ACTIONS,
3150
+ INVALID_CREDENTIALS_MESSAGE,
3151
+ classifyCallbackOutcome,
3152
+ installAuthControllerGuard,
3153
+ setAuthControllerHandlers,
3154
+ uninstallAuthControllerGuard
3155
+ };
3156
+ }
3157
+ });
3158
+
3159
+ // server/src/register.js
3160
+ var require_register = __commonJS({
3161
+ "server/src/register.js"(exports2, module2) {
3162
+ "use strict";
3163
+ var { createLogger } = require_logger();
3164
+ var { createContentApiPermissionsLifecycle } = require_content_api_permissions();
3165
+ var { isCallerRevocationScope } = require_block_revocation_scope();
2667
3166
  var { checkStrapiVersion } = require_strapi_version();
2668
3167
  var { disableGraphqlShadowCrud } = require_security_log_hardening();
3168
+ var { installGraphqlImpersonationGuard } = require_graphql_impersonation_guard();
3169
+ var { installAuthControllerGuard } = require_auth_controller_guard();
2669
3170
  var USER_UID = "plugin::users-permissions.user";
2670
3171
  module2.exports = async ({ strapi: strapi2 }) => {
2671
3172
  const log = createLogger(strapi2);
@@ -2710,6 +3211,17 @@ var require_register = __commonJS({
2710
3211
  subCategory: "Admin panel",
2711
3212
  pluginName: "magic-sessionmanager"
2712
3213
  },
3214
+ // App-user security activity (4.22): failed and refused sign-ins,
3215
+ // lockouts, new devices, impossible travel, "This wasn't me", data
3216
+ // exports and impersonations of Users & Permissions accounts, with IP
3217
+ // addresses. Separate from plugin access because it shows personal data.
3218
+ {
3219
+ section: "plugins",
3220
+ displayName: "View app-user security activity",
3221
+ uid: "user-activity.read",
3222
+ subCategory: "General",
3223
+ pluginName: "magic-sessionmanager"
3224
+ },
2713
3225
  // Protected settings (4.17): IP location lookup (whether and where IP
2714
3226
  // addresses are sent), team notification webhooks (the URLs are
2715
3227
  // secrets) and the security log. The other settings stay on `access`.
@@ -2753,6 +3265,8 @@ var require_register = __commonJS({
2753
3265
  }
2754
3266
  ]);
2755
3267
  disableGraphqlShadowCrud(strapi2, log);
3268
+ installGraphqlImpersonationGuard(strapi2, log);
3269
+ installAuthControllerGuard(strapi2, log);
2756
3270
  try {
2757
3271
  strapi2.db.lifecycles.subscribe(createContentApiPermissionsLifecycle(strapi2));
2758
3272
  } catch (err) {
@@ -2828,42 +3342,69 @@ var require_register = __commonJS({
2828
3342
  var require_getClientIp = __commonJS({
2829
3343
  "server/src/utils/getClientIp.js"(exports2, module2) {
2830
3344
  "use strict";
2831
- function isProxyTrusted(ctx) {
2832
- try {
2833
- const app = ctx?.app;
2834
- if (app && app.proxy === true) return true;
2835
- } catch {
3345
+ var net = require("node:net");
3346
+ var { isTrustedAddress } = require_policy_settings();
3347
+ var { normalizeTrustedProxies } = require_trusted_proxies();
3348
+ var MAX_FORWARDED_LENGTH = 2048;
3349
+ var MAX_FORWARDED_HOPS = 20;
3350
+ var cleanIp = (ip) => {
3351
+ if (!ip) return "unknown";
3352
+ let value = String(ip).trim();
3353
+ if (value.startsWith("[")) {
3354
+ const bracketEnd = value.indexOf("]");
3355
+ if (bracketEnd !== -1) {
3356
+ value = value.substring(1, bracketEnd);
3357
+ }
2836
3358
  }
3359
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.substring(7))) {
3360
+ value = value.substring(7);
3361
+ }
3362
+ if (value.includes(".") && value.includes(":") && value.indexOf(":") === value.lastIndexOf(":")) {
3363
+ value = value.split(":")[0];
3364
+ }
3365
+ return value || "unknown";
3366
+ };
3367
+ function trustedProxyList(ctx) {
3368
+ const fromSettings = ctx?.state?.__magicSessionSettings?.trustedProxies;
3369
+ if (fromSettings !== void 0) return normalizeTrustedProxies(fromSettings);
2837
3370
  try {
2838
- const config2 = ctx?.state?.__magicSessionSettings || ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager") || {};
2839
- const trusted = config2.trustedProxies;
2840
- if (trusted === true) return true;
2841
- if (Array.isArray(trusted) && trusted.length > 0) return true;
3371
+ const config2 = ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager");
3372
+ return normalizeTrustedProxies(config2?.trustedProxies);
2842
3373
  } catch {
3374
+ return [];
2843
3375
  }
2844
- return false;
3376
+ }
3377
+ function socketAddress(ctx) {
3378
+ const raw = ctx?.req?.socket?.remoteAddress ?? ctx?.request?.socket?.remoteAddress;
3379
+ const cleaned = cleanIp(raw);
3380
+ return cleaned !== "unknown" && net.isIP(cleaned) ? cleaned : null;
3381
+ }
3382
+ function rightMostUntrustedHop(ctx, proxies) {
3383
+ const headers = ctx?.request?.headers || ctx?.request?.header || {};
3384
+ let header = headers["x-forwarded-for"];
3385
+ if (Array.isArray(header)) header = header.join(",");
3386
+ if (typeof header !== "string" || !header) return null;
3387
+ const hops = header.slice(0, MAX_FORWARDED_LENGTH).split(",").map((hop) => cleanIp(hop)).slice(-MAX_FORWARDED_HOPS);
3388
+ let lastValid = null;
3389
+ for (let index = hops.length - 1; index >= 0; index--) {
3390
+ const hop = hops[index];
3391
+ if (!net.isIP(hop)) return lastValid;
3392
+ if (!isTrustedAddress(proxies, hop)) return hop;
3393
+ lastValid = hop;
3394
+ }
3395
+ return lastValid;
2845
3396
  }
2846
3397
  var getClientIp = (ctx) => {
2847
3398
  try {
2848
- const headers = ctx.request.headers || ctx.request.header || {};
2849
- const trusted = isProxyTrusted(ctx);
2850
- if (trusted) {
2851
- if (headers["cf-connecting-ip"]) return cleanIp(headers["cf-connecting-ip"]);
2852
- if (headers["true-client-ip"]) return cleanIp(headers["true-client-ip"]);
2853
- if (headers["x-real-ip"]) return cleanIp(headers["x-real-ip"]);
2854
- if (headers["x-forwarded-for"]) {
2855
- const forwardedIps = headers["x-forwarded-for"].split(",");
2856
- const clientIp = forwardedIps[0].trim();
2857
- if (clientIp) return cleanIp(clientIp);
2858
- }
2859
- if (headers["x-client-ip"]) return cleanIp(headers["x-client-ip"]);
2860
- if (headers["x-cluster-client-ip"]) return cleanIp(headers["x-cluster-client-ip"]);
2861
- if (headers["forwarded"]) {
2862
- const match = headers["forwarded"].match(/for=([^;,\s]+)/);
2863
- if (match && match[1]) return cleanIp(match[1].replace(/"/g, ""));
2864
- }
2865
- }
2866
- if (ctx.request.ip) return cleanIp(ctx.request.ip);
3399
+ const proxies = trustedProxyList(ctx);
3400
+ if (proxies.length > 0) {
3401
+ const peer = socketAddress(ctx);
3402
+ if (peer && isTrustedAddress(proxies, peer)) {
3403
+ return rightMostUntrustedHop(ctx, proxies) || peer;
3404
+ }
3405
+ if (peer) return peer;
3406
+ }
3407
+ if (ctx?.request?.ip) return cleanIp(ctx.request.ip);
2867
3408
  return "unknown";
2868
3409
  } catch (error) {
2869
3410
  if (ctx?.app?.context?.strapi?.log?.debug) {
@@ -2875,24 +3416,8 @@ var require_getClientIp = __commonJS({
2875
3416
  return "unknown";
2876
3417
  }
2877
3418
  };
2878
- var cleanIp = (ip) => {
2879
- if (!ip) return "unknown";
2880
- ip = String(ip).trim();
2881
- if (ip.startsWith("[")) {
2882
- const bracketEnd = ip.indexOf("]");
2883
- if (bracketEnd !== -1) {
2884
- ip = ip.substring(1, bracketEnd);
2885
- }
2886
- }
2887
- if (ip.startsWith("::ffff:")) {
2888
- ip = ip.substring(7);
2889
- }
2890
- if (ip.includes(".") && ip.includes(":") && ip.indexOf(":") === ip.lastIndexOf(":")) {
2891
- ip = ip.split(":")[0];
2892
- }
2893
- return ip || "unknown";
2894
- };
2895
3419
  module2.exports = getClientIp;
3420
+ module2.exports.cleanIp = cleanIp;
2896
3421
  }
2897
3422
  });
2898
3423
 
@@ -2905,10 +3430,22 @@ var require_encryption = __commonJS({
2905
3430
  var IV_LENGTH = 16;
2906
3431
  var AUTH_TAG_LENGTH = 16;
2907
3432
  var warnedMissingKey = false;
3433
+ var warnedShortKey = false;
3434
+ var MIN_KEY_BYTES = 32;
3435
+ function isEncryptionKeyShort() {
3436
+ const envKey = process.env.SESSION_ENCRYPTION_KEY;
3437
+ return typeof envKey === "string" && envKey.length > 0 ? Buffer.byteLength(envKey, "utf8") < MIN_KEY_BYTES : false;
3438
+ }
2908
3439
  var isProduction = () => process.env.NODE_ENV === "production";
2909
3440
  function getEncryptionKey() {
2910
3441
  const envKey = process.env.SESSION_ENCRYPTION_KEY;
2911
3442
  if (envKey && envKey.length > 0) {
3443
+ if (!warnedShortKey && isEncryptionKeyShort()) {
3444
+ warnedShortKey = true;
3445
+ console.warn(
3446
+ `[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).`
3447
+ );
3448
+ }
2912
3449
  return crypto.createHash("sha256").update(envKey).digest();
2913
3450
  }
2914
3451
  if (isProduction()) {
@@ -2992,6 +3529,8 @@ var require_encryption = __commonJS({
2992
3529
  );
2993
3530
  }
2994
3531
  module2.exports = {
3532
+ MIN_KEY_BYTES,
3533
+ isEncryptionKeyShort,
2995
3534
  derivePurposeKey,
2996
3535
  getEncryptionKeyCheck,
2997
3536
  encryptToken,
@@ -3541,7 +4080,6 @@ var require_auth_routes = __commonJS({
3541
4080
  "POST /api/magic-link/login-totp"
3542
4081
  ]);
3543
4082
  var FAILED_LOGIN_ROUTES = /* @__PURE__ */ new Set([
3544
- "POST /api/auth/local",
3545
4083
  "POST /api/magic-link/login-totp",
3546
4084
  "POST /api/magic-link/otp/verify",
3547
4085
  "POST /api/magic-link/verify-mfa-totp"
@@ -3584,18 +4122,24 @@ var require_auth_routes = __commonJS({
3584
4122
  if (!trimmed) return DEFAULT_API_PREFIX;
3585
4123
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
3586
4124
  }
4125
+ function normalizeRequestPath(path) {
4126
+ const value = path.toLowerCase().replace(/\/{2,}/g, "/");
4127
+ return value.length > 1 ? value.replace(/\/+$/, "") || "/" : value;
4128
+ }
3587
4129
  function toCanonicalApiPath(path, prefix) {
3588
4130
  if (typeof path !== "string") return null;
3589
- const normalized = normalizeApiPrefix(prefix);
3590
- if (normalized === DEFAULT_API_PREFIX) return path;
3591
- if (path === normalized) return DEFAULT_API_PREFIX;
3592
- if (path.startsWith(`${normalized}/`)) {
3593
- return `${DEFAULT_API_PREFIX}${path.slice(normalized.length)}`;
4131
+ const normalizedPath = normalizeRequestPath(path);
4132
+ const normalized = normalizeApiPrefix(prefix).toLowerCase();
4133
+ if (normalized === DEFAULT_API_PREFIX) return normalizedPath;
4134
+ if (normalizedPath === normalized) return DEFAULT_API_PREFIX;
4135
+ if (normalizedPath.startsWith(`${normalized}/`)) {
4136
+ return `${DEFAULT_API_PREFIX}${normalizedPath.slice(normalized.length)}`;
3594
4137
  }
3595
4138
  return null;
3596
4139
  }
3597
4140
  module2.exports = {
3598
4141
  normalizeApiPrefix,
4142
+ normalizeRequestPath,
3599
4143
  toCanonicalApiPath,
3600
4144
  classifyJwtIssuingRequest,
3601
4145
  isFailedLoginTrackedPath,
@@ -4255,6 +4799,15 @@ var require_admin_request_info = __commonJS({
4255
4799
  }
4256
4800
  return null;
4257
4801
  }
4802
+ function ipBucket(ip) {
4803
+ const value = normalizeIp(typeof ip === "string" ? ip : "");
4804
+ if (!value) return null;
4805
+ if (net.isIPv4(value)) return value;
4806
+ if (net.isIPv6(value)) {
4807
+ return `${ipv6Groups(value).slice(0, 4).map((group) => group.toString(16)).join(":")}::/64`;
4808
+ }
4809
+ return null;
4810
+ }
4258
4811
  function getRequestUserAgent(ctx) {
4259
4812
  const value = ctx?.request?.headers?.["user-agent"];
4260
4813
  if (typeof value !== "string" || !value.trim()) return null;
@@ -4281,6 +4834,7 @@ var require_admin_request_info = __commonJS({
4281
4834
  module2.exports = {
4282
4835
  MAX_USER_AGENT_LENGTH,
4283
4836
  anonymizeIp,
4837
+ ipBucket,
4284
4838
  describeUserAgent,
4285
4839
  getRequestIp,
4286
4840
  getSocketIp,
@@ -4581,6 +5135,7 @@ var require_login_lockout = __commonJS({
4581
5135
  "use strict";
4582
5136
  var { hashedKey } = require_coordination();
4583
5137
  var { isTrustedAddress } = require_policy_settings();
5138
+ var { ipBucket } = require_admin_request_info();
4584
5139
  var LOCK_PREFIX = "lock:";
4585
5140
  var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
4586
5141
  var MAX_LISTED_LOCKS = 200;
@@ -4590,7 +5145,7 @@ var require_login_lockout = __commonJS({
4590
5145
  if (!value || value.length > 254) return null;
4591
5146
  return value;
4592
5147
  }
4593
- var ipKey = (ip) => hashedKey("lf", ip);
5148
+ var ipKey = (ip) => hashedKey("lf", ipBucket(ip) || ip);
4594
5149
  var accountKey = (identifier) => hashedKey("la", identifier);
4595
5150
  function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
4596
5151
  const remainingSeconds = async (key) => {
@@ -4610,15 +5165,18 @@ var require_login_lockout = __commonJS({
4610
5165
  * Checks the locks and counts the attempt before the password check.
4611
5166
  *
4612
5167
  * @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
4613
- * accountMax: number}} input Client IP, normalised identifier, policy and the
4614
- * account threshold for this account's role.
5168
+ * accountMax: number, accountExempt?: boolean}} input Client IP, normalised
5169
+ * identifier, policy, the account threshold for this account's role, and
5170
+ * whether the request comes from a device the account is known to use.
4615
5171
  * @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
4616
5172
  * lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
4617
5173
  * @sideeffect Increments the shared counters.
4618
5174
  */
4619
- async reserve({ ip, identifier, policy, accountMax }) {
4620
- const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
4621
- const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
5175
+ async reserve({ ip, identifier, policy, accountMax, accountExempt = false }) {
5176
+ const knownIp = typeof ip === "string" && !!ip && ip !== "unknown";
5177
+ const trusted = knownIp && isTrustedAddress(policy.trusted, ip);
5178
+ const countIp = policy.ipMax > 0 && knownIp && !trusted;
5179
+ const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier && !trusted && accountExempt !== true;
4622
5180
  const reservation = {
4623
5181
  ipKey: countIp ? ipKey(
4624
5182
  /** @type {string} */
@@ -4671,10 +5229,8 @@ var require_login_lockout = __commonJS({
4671
5229
  */
4672
5230
  async settle(reservation, result, { policy, accountMax, display = {} }) {
4673
5231
  if (result === "success") {
4674
- for (const key of [reservation.ipKey, reservation.accountKey]) {
4675
- if (!key) continue;
4676
- await coordinator.clear(key);
4677
- }
5232
+ if (reservation.ipKey) await coordinator.release(reservation.ipKey);
5233
+ if (reservation.accountKey) await coordinator.clear(reservation.accountKey);
4678
5234
  return [];
4679
5235
  }
4680
5236
  if (result !== "failure") {
@@ -5138,6 +5694,15 @@ var require_sign_in_signals = __commonJS({
5138
5694
  });
5139
5695
  return Array.isArray(rows) ? rows : [];
5140
5696
  }
5697
+ async function isRecognizedDevice(strapi2, userDocumentId, { userAgent, deviceId }) {
5698
+ if (typeof userDocumentId !== "string" || !userDocumentId) return false;
5699
+ if (typeof deviceId !== "string" || !deviceId) return false;
5700
+ const deviceKey = deviceKeyOf(userAgent || "", deviceId);
5701
+ const count = await strapi2.documents(SESSION_UID).count({
5702
+ filters: { user: { documentId: userDocumentId }, deviceKey }
5703
+ });
5704
+ return Number(count) > 0;
5705
+ }
5141
5706
  function isNewDevice(previous, { deviceKey, userAgent }) {
5142
5707
  if (previous.length === 0) return false;
5143
5708
  if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
@@ -5166,7 +5731,7 @@ var require_sign_in_signals = __commonJS({
5166
5731
  const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
5167
5732
  if (!token) return null;
5168
5733
  const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
5169
- return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
5734
+ return `${base}${prefix}/magic-sessionmanager/not-me#token=${encodeURIComponent(token)}`;
5170
5735
  }
5171
5736
  async function runSignInSignals({
5172
5737
  strapi: strapi2,
@@ -5255,6 +5820,7 @@ var require_sign_in_signals = __commonJS({
5255
5820
  return outcome;
5256
5821
  }
5257
5822
  module2.exports = {
5823
+ isRecognizedDevice,
5258
5824
  notMeUrl,
5259
5825
  runSignInSignals,
5260
5826
  deviceFamilies,
@@ -5359,7 +5925,11 @@ var require_impersonation_guard = __commonJS({
5359
5925
  `impersonation-${restricted}`
5360
5926
  );
5361
5927
  }
5362
- ctx.state.magicImpersonation = { id: impersonation.id, actorId: impersonation.actorId };
5928
+ ctx.state.magicImpersonation = {
5929
+ id: impersonation.id,
5930
+ actorId: impersonation.actorId,
5931
+ targetId: impersonation.targetId || null
5932
+ };
5363
5933
  try {
5364
5934
  await next();
5365
5935
  } finally {
@@ -9453,7 +10023,13 @@ var require_bootstrap = __commonJS({
9453
10023
  "server/src/bootstrap.js"(exports2, module2) {
9454
10024
  "use strict";
9455
10025
  var getClientIp = require_getClientIp();
9456
- var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
10026
+ var {
10027
+ MIN_KEY_BYTES,
10028
+ encryptToken,
10029
+ getEncryptionKeyCheck,
10030
+ hashToken,
10031
+ isEncryptionKeyShort
10032
+ } = require_encryption();
9457
10033
  var { createLogger } = require_logger();
9458
10034
  var { resolveUserDocumentId } = require_resolve_user();
9459
10035
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -9464,7 +10040,12 @@ var require_bootstrap = __commonJS({
9464
10040
  var { REVOCATION_UID } = require_session_revocation();
9465
10041
  var { getNativeSessionManager } = require_native_session_manager();
9466
10042
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
9467
- var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
10043
+ var {
10044
+ getCoordinator,
10045
+ hashedKey,
10046
+ initCoordination,
10047
+ LockTimeoutError
10048
+ } = require_coordination();
9468
10049
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
9469
10050
  var {
9470
10051
  normalizeApiPrefix,
@@ -9513,8 +10094,20 @@ var require_bootstrap = __commonJS({
9513
10094
  } = require_sign_in_policies();
9514
10095
  var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
9515
10096
  var { applyUpgradeDefaults } = require_upgrade_defaults();
9516
- var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
10097
+ var {
10098
+ deviceKeyOf,
10099
+ isRecognizedDevice,
10100
+ requestDeviceId,
10101
+ runSignInSignals
10102
+ } = require_sign_in_signals();
9517
10103
  var { anonymizeIp, normalizeIp } = require_admin_request_info();
10104
+ var { migrateLegacyProxyTrust } = require_trusted_proxies();
10105
+ var { errors: utilsErrors } = require("@strapi/utils");
10106
+ var {
10107
+ classifyCallbackOutcome,
10108
+ setAuthControllerHandlers
10109
+ } = require_auth_controller_guard();
10110
+ var { normalizePath } = require_impersonation_rules();
9518
10111
  var SESSION_UID = "plugin::magic-sessionmanager.session";
9519
10112
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
9520
10113
  var JOB_LEASES = Object.freeze({
@@ -9557,6 +10150,12 @@ var require_bootstrap = __commonJS({
9557
10150
  try {
9558
10151
  const coordinator = await initCoordination(strapi2, log);
9559
10152
  await checkEncryptionKeyConsistency(strapi2, log);
10153
+ await warnShortEncryptionKey(strapi2, log);
10154
+ try {
10155
+ await migrateLegacyProxyTrust(strapi2, log);
10156
+ } catch (err) {
10157
+ log.warn("[CONFIG] trustedProxies could not be migrated:", err?.name || "Error");
10158
+ }
9560
10159
  try {
9561
10160
  await applyUpgradeDefaults(strapi2, log);
9562
10161
  } catch (err) {
@@ -9670,8 +10269,9 @@ var require_bootstrap = __commonJS({
9670
10269
  impersonationSweep.unref?.();
9671
10270
  strapi2.sessionManagerIntervals.impersonationSweep = impersonationSweep;
9672
10271
  strapi2.plugin("magic-sessionmanager").service("impersonation").checkHandoffSetup();
9673
- mountPreLoginGeoGuard({ strapi: strapi2, log });
9674
- mountFailedLoginLockout({ strapi: strapi2, log });
10272
+ const geoCheck = mountPreLoginGeoGuard({ strapi: strapi2, log });
10273
+ const lockoutGuard = mountFailedLoginLockout({ strapi: strapi2, log });
10274
+ connectAuthControllerGuard({ strapi: strapi2, geoCheck, lockoutGuard });
9675
10275
  mountLogoutRoute({ strapi: strapi2, log, sessionService });
9676
10276
  mountLoginInterceptor({ strapi: strapi2, log, sessionService });
9677
10277
  mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
@@ -9729,6 +10329,28 @@ var require_bootstrap = __commonJS({
9729
10329
  log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
9730
10330
  }
9731
10331
  }
10332
+ async function warnShortEncryptionKey(strapi2, log) {
10333
+ if (!isEncryptionKeyShort()) return false;
10334
+ log.error(
10335
+ `[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).`
10336
+ );
10337
+ try {
10338
+ const coordinator = getCoordinator(strapi2);
10339
+ const check = getEncryptionKeyCheck();
10340
+ const marker = "instance:weak-encryption-key-recorded";
10341
+ if (await coordinator.cacheGet(marker) === check) return true;
10342
+ const recorded = strapi2.plugin("magic-sessionmanager").service("security-log").record({
10343
+ event: SECURITY_EVENTS.CONFIG_WEAK_KEY,
10344
+ actorType: "system",
10345
+ targetType: "config",
10346
+ meta: { minBytes: MIN_KEY_BYTES }
10347
+ });
10348
+ if (recorded !== false) await coordinator.cacheSet(marker, check, Infinity);
10349
+ } catch (err) {
10350
+ log.debug("[SECURITY] Weak key event not recorded:", err?.name || "Error");
10351
+ }
10352
+ return true;
10353
+ }
9732
10354
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
9733
10355
  const shouldRecordRefusal = createRefusalDedup();
9734
10356
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
@@ -9751,19 +10373,14 @@ var require_bootstrap = __commonJS({
9751
10373
  meta: { reason }
9752
10374
  });
9753
10375
  };
9754
- strapi2.server.use(async (ctx, next) => {
9755
- if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
9756
- return next();
9757
- }
10376
+ const check = async (ctx) => {
10377
+ if (ctx.state?.__magicSessionGeoChecked) return null;
10378
+ if (ctx.state) ctx.state.__magicSessionGeoChecked = true;
9758
10379
  const settings = await getRequestSettings(strapi2, ctx);
9759
10380
  const needsGeoCheck = settings.blockSuspiciousSessions || settings.enableGeofencing || settings.enableGeolocation;
9760
- if (!needsGeoCheck) {
9761
- return next();
9762
- }
10381
+ if (!needsGeoCheck) return null;
9763
10382
  const ip = getClientIp(ctx);
9764
- if (!ip || ip === "unknown") {
9765
- return next();
9766
- }
10383
+ if (!ip || ip === "unknown") return null;
9767
10384
  try {
9768
10385
  const geolocationService = strapi2.plugin("magic-sessionmanager").service("geolocation");
9769
10386
  const geoData = await geolocationService.getIpInfo(ip);
@@ -9771,16 +10388,11 @@ var require_bootstrap = __commonJS({
9771
10388
  if (decision.blocked) {
9772
10389
  log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
9773
10390
  await recordRefusal(ctx, settings, ip, decision.reason);
9774
- ctx.status = 403;
9775
- ctx.body = {
9776
- error: {
9777
- status: 403,
9778
- name: "ForbiddenError",
9779
- message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
9780
- }
9781
- };
9782
10391
  ctx.state.__magicSessionGeoData = geoData;
9783
- return;
10392
+ return {
10393
+ status: 403,
10394
+ message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
10395
+ };
9784
10396
  }
9785
10397
  if (decision.status === "ok") {
9786
10398
  ctx.state.__magicSessionGeoData = geoData;
@@ -9790,21 +10402,31 @@ var require_bootstrap = __commonJS({
9790
10402
  if (failureDecision.blocked) {
9791
10403
  log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
9792
10404
  await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
9793
- ctx.status = 403;
9794
- ctx.body = {
9795
- error: {
9796
- status: 403,
9797
- name: "ForbiddenError",
9798
- message: "Login temporarily unavailable. Please contact support."
9799
- }
10405
+ return {
10406
+ status: 403,
10407
+ message: "Login temporarily unavailable. Please contact support."
9800
10408
  };
9801
- return;
9802
10409
  }
9803
10410
  log.debug("Pre-login geo guard error (allowing by configured policy):", err?.name || "Error");
9804
10411
  }
10412
+ return null;
10413
+ };
10414
+ strapi2.server.use(async (ctx, next) => {
10415
+ if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
10416
+ return next();
10417
+ }
10418
+ const refusal = await check(ctx);
10419
+ if (refusal) {
10420
+ ctx.status = refusal.status;
10421
+ ctx.body = {
10422
+ error: { status: refusal.status, name: "ForbiddenError", message: refusal.message }
10423
+ };
10424
+ return;
10425
+ }
9805
10426
  await next();
9806
10427
  });
9807
10428
  log.info("[SUCCESS] Pre-login geo guard mounted");
10429
+ return check;
9808
10430
  }
9809
10431
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
9810
10432
  const logoutPath = `${normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"))}/auth/logout`;
@@ -9990,16 +10612,16 @@ var require_bootstrap = __commonJS({
9990
10612
  }
9991
10613
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
9992
10614
  const lockout = createLoginLockout(getCoordinator(strapi2));
10615
+ const coordinator = getCoordinator(strapi2);
9993
10616
  const shouldRecordRefusal = createRefusalDedup();
9994
10617
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
9995
10618
  const underAddressCap = createAddressCap();
9996
10619
  const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
9997
- strapi2.server.use(async (ctx, next) => {
9998
- if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
10620
+ const guard = async (ctx, run, classify, refuse) => {
9999
10621
  const settings = await getRequestSettings(strapi2, ctx);
10000
10622
  const policy = resolveLockoutPolicy(settings);
10001
10623
  const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
10002
- if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
10624
+ if (policy.ipMax <= 0 && !accountPossible && !policy.record) return run();
10003
10625
  const rawIp = getClientIp(ctx);
10004
10626
  const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
10005
10627
  const identifier = readSignInIdentifier(ctx);
@@ -10020,6 +10642,15 @@ var require_bootstrap = __commonJS({
10020
10642
  };
10021
10643
  if (policy.accountMaxByRole) await loadAccount();
10022
10644
  const accountMax = accountThresholdFor(settings, account?.role || null);
10645
+ let accountExempt = false;
10646
+ const deviceId = requestDeviceId(ctx);
10647
+ if (accountMax > 0 && identifier && deviceId) {
10648
+ await loadAccount();
10649
+ accountExempt = await isRecognizedDevice(strapi2, account?.documentId || null, {
10650
+ userAgent,
10651
+ deviceId
10652
+ }).catch(() => false);
10653
+ }
10023
10654
  const event = (name, meta) => {
10024
10655
  const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
10025
10656
  if (signInFamily && !policy.record) return false;
@@ -10047,7 +10678,7 @@ var require_bootstrap = __commonJS({
10047
10678
  };
10048
10679
  let decision;
10049
10680
  try {
10050
- decision = await lockout.reserve({ ip, identifier, policy, accountMax });
10681
+ decision = await lockout.reserve({ ip, identifier, policy, accountMax, accountExempt });
10051
10682
  } catch (err) {
10052
10683
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10053
10684
  decision = {
@@ -10058,47 +10689,38 @@ var require_bootstrap = __commonJS({
10058
10689
  };
10059
10690
  }
10060
10691
  if (decision.outcome === "locked") {
10061
- ctx.set("Retry-After", String(decision.retryAfter));
10062
10692
  log.warn(
10063
10693
  `[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
10064
10694
  );
10065
10695
  if (policy.record) await loadAccount();
10066
10696
  refusedOnce("lockout", { lock: decision.lockedKind });
10067
- ctx.status = 429;
10068
- ctx.body = {
10069
- error: {
10070
- status: 429,
10071
- name: "TooManyRequestsError",
10072
- message: "Too many failed login attempts. Please try again later.",
10073
- details: { retryAfter: decision.retryAfter }
10074
- }
10075
- };
10076
- return;
10697
+ return refuse(ctx, {
10698
+ status: 429,
10699
+ name: "TooManyRequestsError",
10700
+ message: "Too many failed login attempts. Please try again later.",
10701
+ retryAfter: decision.retryAfter
10702
+ });
10077
10703
  }
10078
10704
  if (decision.outcome === "busy") {
10079
10705
  if (policy.record) await loadAccount();
10080
10706
  refusedOnce("too-many-attempts", {});
10081
- ctx.set("Retry-After", "1");
10082
- ctx.status = 429;
10083
- ctx.body = {
10084
- error: {
10085
- status: 429,
10086
- name: "TooManyRequestsError",
10087
- message: "Too many login attempts at once. Please try again.",
10088
- details: { retryAfter: 1 }
10089
- }
10090
- };
10091
- return;
10707
+ return refuse(ctx, {
10708
+ status: 429,
10709
+ name: "TooManyRequestsError",
10710
+ message: "Too many login attempts at once. Please try again.",
10711
+ retryAfter: 1
10712
+ });
10092
10713
  }
10093
10714
  let thrown = null;
10715
+ let returned;
10094
10716
  try {
10095
- await next();
10717
+ returned = await run();
10096
10718
  } catch (err) {
10097
10719
  thrown = err;
10098
10720
  }
10099
- const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10100
- const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
10721
+ const result = classify(thrown, ctx);
10101
10722
  if (result === "failure") {
10723
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10102
10724
  if (policy.record || decision.reservation.accountKey) await loadAccount();
10103
10725
  if (account) {
10104
10726
  event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
@@ -10126,21 +10748,93 @@ var require_bootstrap = __commonJS({
10126
10748
  minutes
10127
10749
  });
10128
10750
  if (lock.kind === "account" && policy.notifyUser && account?.email) {
10129
- const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
10130
- notifications.sendAccountLockedEmail({
10131
- user: account,
10132
- minutes,
10133
- until: lock.until
10134
- }).catch(() => {
10135
- });
10751
+ const mailWindowMs = Math.max(policy.windowMs, policy.durationMs);
10752
+ const sent = await coordinator.hit(hashedKey("lm", lock.id), mailWindowMs).then((entry) => Number(entry?.hits) || 0).catch(() => 1);
10753
+ if (sent === 1) {
10754
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
10755
+ notifications.sendAccountLockedEmail({
10756
+ user: account,
10757
+ minutes,
10758
+ until: lock.until
10759
+ }).catch(() => {
10760
+ });
10761
+ }
10136
10762
  }
10137
10763
  }
10138
10764
  } catch (err) {
10139
10765
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10140
10766
  }
10141
10767
  if (thrown) throw thrown;
10768
+ return returned;
10769
+ };
10770
+ strapi2.server.use(async (ctx, next) => {
10771
+ if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
10772
+ return guard(ctx, next, classifyRouteOutcome, refuseOverHttp);
10142
10773
  });
10143
10774
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
10775
+ return guard;
10776
+ }
10777
+ function classifyRouteOutcome(thrown, ctx) {
10778
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10779
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) return "success";
10780
+ return status === 400 || status === 401 ? "failure" : "neutral";
10781
+ }
10782
+ function refuseOverHttp(ctx, refusal) {
10783
+ ctx.set("Retry-After", String(refusal.retryAfter));
10784
+ ctx.status = refusal.status;
10785
+ ctx.body = {
10786
+ error: {
10787
+ status: refusal.status,
10788
+ name: refusal.name,
10789
+ message: refusal.message,
10790
+ details: { retryAfter: refusal.retryAfter }
10791
+ }
10792
+ };
10793
+ }
10794
+ function isGraphqlRequest(strapi2, ctx) {
10795
+ let endpoint = "/graphql";
10796
+ try {
10797
+ endpoint = strapi2.plugin("graphql")?.config?.("endpoint") || endpoint;
10798
+ } catch {
10799
+ }
10800
+ const original = String(ctx.originalUrl || ctx.url || "").split("?")[0];
10801
+ return normalizePath(original) === normalizePath(endpoint);
10802
+ }
10803
+ function createAuthControllerHandlers({ strapi: strapi2, geoCheck, lockoutGuard }) {
10804
+ const refuse = (ctx, refusal) => {
10805
+ if (refusal.retryAfter) ctx.set("Retry-After", String(refusal.retryAfter));
10806
+ if (isGraphqlRequest(strapi2, ctx)) {
10807
+ const details = refusal.retryAfter ? { retryAfter: refusal.retryAfter } : {};
10808
+ throw refusal.status === 429 ? new utilsErrors.RateLimitError(refusal.message, details) : new utilsErrors.ForbiddenError(refusal.message, details);
10809
+ }
10810
+ if (refusal.status === 429) return refuseOverHttp(ctx, refusal);
10811
+ ctx.status = refusal.status;
10812
+ ctx.body = {
10813
+ error: { status: refusal.status, name: refusal.name, message: refusal.message }
10814
+ };
10815
+ return void 0;
10816
+ };
10817
+ const geoFirst = async (ctx) => {
10818
+ const refusal = await geoCheck(ctx);
10819
+ if (!refusal) return false;
10820
+ refuse(ctx, { ...refusal, name: "ForbiddenError", retryAfter: 0 });
10821
+ return true;
10822
+ };
10823
+ return {
10824
+ async callback(ctx, run) {
10825
+ if (await geoFirst(ctx)) return void 0;
10826
+ const provider = ctx.params?.provider || "local";
10827
+ if (provider !== "local") return run();
10828
+ return lockoutGuard(ctx, run, classifyCallbackOutcome, refuse);
10829
+ },
10830
+ async newSession(ctx, run) {
10831
+ if (await geoFirst(ctx)) return void 0;
10832
+ return run();
10833
+ }
10834
+ };
10835
+ }
10836
+ function connectAuthControllerGuard(deps) {
10837
+ setAuthControllerHandlers(deps.strapi, createAuthControllerHandlers(deps));
10144
10838
  }
10145
10839
  function statusOfThrownError(err) {
10146
10840
  const status = Number(err?.status ?? err?.statusCode);
@@ -11350,6 +12044,8 @@ var require_bootstrap = __commonJS({
11350
12044
  }
11351
12045
  }
11352
12046
  module2.exports.__private = {
12047
+ warnShortEncryptionKey,
12048
+ createAuthControllerHandlers,
11353
12049
  registerSessionAwareAuthStrategy,
11354
12050
  mountFailedLoginLockout,
11355
12051
  ensureSessionLookupIndexes,
@@ -11369,6 +12065,7 @@ var require_destroy = __commonJS({
11369
12065
  "server/src/destroy.js"(exports2, module2) {
11370
12066
  "use strict";
11371
12067
  var { createLogger } = require_logger();
12068
+ var { uninstallAuthControllerGuard } = require_auth_controller_guard();
11372
12069
  module2.exports = async ({ strapi: strapi2 }) => {
11373
12070
  const log = createLogger(strapi2);
11374
12071
  if (strapi2.sessionManagerIntervals) {
@@ -11402,6 +12099,11 @@ var require_destroy = __commonJS({
11402
12099
  }
11403
12100
  strapi2.sessionManagerAdminActivityUninstall = null;
11404
12101
  }
12102
+ try {
12103
+ uninstallAuthControllerGuard(strapi2);
12104
+ } catch (err) {
12105
+ log.warn("Failed to restore the Users & Permissions auth controller:", err?.name || "Error");
12106
+ }
11405
12107
  try {
11406
12108
  strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
11407
12109
  } catch (err) {
@@ -12119,6 +12821,7 @@ var require_admin = __commonJS({
12119
12821
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
12120
12822
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
12121
12823
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12824
+ var USER_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.user-activity.read";
12122
12825
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12123
12826
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12124
12827
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
@@ -12380,6 +13083,27 @@ var require_admin = __commonJS({
12380
13083
  description: "Get one export batch of Content Manager activity of admins (admin)"
12381
13084
  }
12382
13085
  },
13086
+ // ===================== APP-USER SECURITY ACTIVITY (4.22) =====================
13087
+ {
13088
+ method: "GET",
13089
+ path: "/user-activity",
13090
+ handler: "user-activity.list",
13091
+ config: {
13092
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
13093
+ middlewares: adminReadRateLimit(),
13094
+ description: "List the security activity of app users (admin)"
13095
+ }
13096
+ },
13097
+ {
13098
+ method: "GET",
13099
+ path: "/user-activity/export",
13100
+ handler: "user-activity.export",
13101
+ config: {
13102
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
13103
+ middlewares: adminReadRateLimit(),
13104
+ description: "Get one export batch of the security activity of app users (admin)"
13105
+ }
13106
+ },
12383
13107
  // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
12384
13108
  {
12385
13109
  method: "GET",
@@ -14853,7 +15577,13 @@ var require_settings_access = __commonJS({
14853
15577
  // Signed webhook, event selection, impossible travel and shortened IPs.
14854
15578
  ...PROTECTED_DETECTION_KEYS,
14855
15579
  // Impersonation switch (4.20): whether admins can act as app users.
14856
- ...IMPERSONATION_KEYS
15580
+ ...IMPERSONATION_KEYS,
15581
+ // Security review 2 (4.22.1): which proxies may name the client address
15582
+ // (H2), the IP lockout threshold (H2) and the alert email texts, which go
15583
+ // to app users from the site's own address (hardening 6).
15584
+ "trustedProxies",
15585
+ "maxFailedLogins",
15586
+ "emailTemplates"
14857
15587
  ]);
14858
15588
  var WEBHOOK_SECRETS = Object.freeze([
14859
15589
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
@@ -14963,6 +15693,7 @@ var require_settings = __commonJS({
14963
15693
  validateImpersonationSettings
14964
15694
  } = require_impersonation_rules();
14965
15695
  var { encryptToken } = require_encryption();
15696
+ var { normalizeTrustedProxies, validateTrustedProxies } = require_trusted_proxies();
14966
15697
  var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
14967
15698
  var path = require("node:path");
14968
15699
  var ALLOWED_WEBHOOK_DOMAINS = {
@@ -15138,7 +15869,9 @@ var require_settings = __commonJS({
15138
15869
  discordWebhookUrl: "",
15139
15870
  slackWebhookUrl: "",
15140
15871
  strictSessionEnforcement: false,
15141
- trustedProxies: false,
15872
+ // A list of proxy addresses or CIDR ranges since 4.22.1; the legacy
15873
+ // boolean is read as an empty list (Strapi's server.proxy settings decide).
15874
+ trustedProxies: [],
15142
15875
  emailTemplates: DEFAULT_EMAIL_TEMPLATES,
15143
15876
  ...SECURITY_LOG_DEFAULTS,
15144
15877
  ...POLICY_DEFAULTS,
@@ -15159,7 +15892,8 @@ var require_settings = __commonJS({
15159
15892
  ...DEFAULT_EMAIL_TEMPLATES,
15160
15893
  ...storedTemplates
15161
15894
  },
15162
- geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath)
15895
+ geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath),
15896
+ trustedProxies: normalizeTrustedProxies(safeStored.trustedProxies)
15163
15897
  };
15164
15898
  }
15165
15899
  var INTEGER_SETTING_RANGES = {
@@ -15184,8 +15918,7 @@ var require_settings = __commonJS({
15184
15918
  "alertOnNewLocation",
15185
15919
  "alertOnVpnProxy",
15186
15920
  "enableWebhooks",
15187
- "strictSessionEnforcement",
15188
- "trustedProxies"
15921
+ "strictSessionEnforcement"
15189
15922
  ];
15190
15923
  var GEO_IP_PROVIDER_VALUES = ["auto", "local-mmdb", "ipapi", "disabled"];
15191
15924
  var GEO_LOOKUP_FAILURE_MODE_VALUES = ["auto", "allow", "block"];
@@ -15259,6 +15992,11 @@ var require_settings = __commonJS({
15259
15992
  next[key] = body[key];
15260
15993
  }
15261
15994
  }
15995
+ if (has("trustedProxies")) {
15996
+ const proxies = validateTrustedProxies(body.trustedProxies);
15997
+ if (proxies.error) errors.push(proxies.error);
15998
+ else next.trustedProxies = proxies.value;
15999
+ }
15262
16000
  for (const key of ["allowedCountries", "blockedCountries"]) {
15263
16001
  if (!has(key)) continue;
15264
16002
  const list = body[key];
@@ -15377,6 +16115,15 @@ var require_settings = __commonJS({
15377
16115
  next.genericWebhookSecret = encryptToken(secret);
15378
16116
  }
15379
16117
  }
16118
+ const urlChanges = typeof next.genericWebhookUrl === "string" && next.genericWebhookUrl !== "" && next.genericWebhookUrl !== (current.genericWebhookUrl || "");
16119
+ const secretStored = typeof current.genericWebhookSecret === "string" && current.genericWebhookSecret !== "";
16120
+ const secretGiven = typeof next.genericWebhookSecret === "string" && next.genericWebhookSecret !== "";
16121
+ if (urlChanges && secretStored && !secretGiven) {
16122
+ errors.push({
16123
+ path: ["genericWebhookSecret"],
16124
+ message: "Enter the webhook secret again when you change the webhook URL"
16125
+ });
16126
+ }
15380
16127
  if (errors.length > 0) return { errors };
15381
16128
  const settings = {};
15382
16129
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -16734,29 +17481,70 @@ var require_admin_sessions2 = __commonJS({
16734
17481
  }
16735
17482
  });
16736
17483
 
16737
- // server/src/controllers/admin-activity.js
16738
- var require_admin_activity = __commonJS({
16739
- "server/src/controllers/admin-activity.js"(exports2, module2) {
17484
+ // server/src/utils/event-query.js
17485
+ var require_event_query = __commonJS({
17486
+ "server/src/utils/event-query.js"(exports2, module2) {
16740
17487
  "use strict";
16741
17488
  var { z } = require("@strapi/utils");
16742
- var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
16743
17489
  var { parseInput } = require_admin_sessions();
16744
17490
  var { sendServerError, sendValidationError } = require_http_errors();
16745
- var { createLogger } = require_logger();
16746
- var { callerCan } = require_settings_access();
16747
17491
  var MAX_PAGE_SIZE = 100;
16748
- var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
16749
17492
  var dateField = (name) => z.string().max(40, `${name} must be an ISO 8601 date`).refine((value) => !Number.isNaN(Date.parse(value)), `${name} must be an ISO 8601 date`).transform((value) => new Date(value)).optional();
16750
- var common = {
16751
- adminId: adminIdField,
17493
+ var periodAndPaging = () => ({
16752
17494
  from: dateField("from"),
16753
17495
  to: dateField("to"),
16754
17496
  page: z.coerce.number().int().min(1).max(1e6).default(1),
16755
17497
  pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16756
- };
16757
- var signInQuerySchema = z.strictObject({
16758
- ...common,
16759
- event: z.enum(
17498
+ });
17499
+ var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
17500
+ async function handleEventQuery(ctx, schema, run, { log, logPrefix, operation, failureMessage }) {
17501
+ const parsed = parseInput(schema, ctx.query);
17502
+ if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
17503
+ const query = parsed.value;
17504
+ if (query.from && query.to && query.from > query.to) {
17505
+ return sendValidationError(ctx, "Invalid query", [
17506
+ { path: ["from"], message: "from must not be after to" }
17507
+ ]);
17508
+ }
17509
+ try {
17510
+ ctx.body = await run(query);
17511
+ return ctx.body;
17512
+ } catch (error) {
17513
+ log.error(
17514
+ `${logPrefix}: ${operation} failed`,
17515
+ /** @type {any} */
17516
+ error?.name || "Error"
17517
+ );
17518
+ return sendServerError(ctx, 500, failureMessage);
17519
+ }
17520
+ }
17521
+ module2.exports = {
17522
+ MAX_PAGE_SIZE,
17523
+ cursorField,
17524
+ dateField,
17525
+ handleEventQuery,
17526
+ periodAndPaging
17527
+ };
17528
+ }
17529
+ });
17530
+
17531
+ // server/src/controllers/admin-activity.js
17532
+ var require_admin_activity = __commonJS({
17533
+ "server/src/controllers/admin-activity.js"(exports2, module2) {
17534
+ "use strict";
17535
+ var { z } = require("@strapi/utils");
17536
+ var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
17537
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
17538
+ var { createLogger } = require_logger();
17539
+ var { callerCan } = require_settings_access();
17540
+ var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
17541
+ var common = {
17542
+ adminId: adminIdField,
17543
+ ...periodAndPaging()
17544
+ };
17545
+ var signInQuerySchema = z.strictObject({
17546
+ ...common,
17547
+ event: z.enum(
16760
17548
  /** @type {[string, ...string[]]} */
16761
17549
  Object.keys(SIGN_IN_FILTERS)
16762
17550
  ).default("all")
@@ -16772,7 +17560,6 @@ var require_admin_activity = __commonJS({
16772
17560
  "contentType must be a content type uid"
16773
17561
  ).optional()
16774
17562
  });
16775
- var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16776
17563
  var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
16777
17564
  cursor: cursorField
16778
17565
  });
@@ -16805,27 +17592,12 @@ var require_admin_activity = __commonJS({
16805
17592
  } catch {
16806
17593
  }
16807
17594
  };
16808
- const handle = async (ctx, schema, run, operation) => {
16809
- const parsed = parseInput(schema, ctx.query);
16810
- if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16811
- const query = parsed.value;
16812
- if (query.from && query.to && query.from > query.to) {
16813
- return sendValidationError(ctx, "Invalid query", [
16814
- { path: ["from"], message: "from must not be after to" }
16815
- ]);
16816
- }
16817
- try {
16818
- ctx.body = await run(query);
16819
- return ctx.body;
16820
- } catch (error) {
16821
- log.error(
16822
- `Admin activity: ${operation} failed`,
16823
- /** @type {any} */
16824
- error?.name || "Error"
16825
- );
16826
- return sendServerError(ctx, 500, "Admin activity could not be loaded.");
16827
- }
16828
- };
17595
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
17596
+ log,
17597
+ logPrefix: "Admin activity",
17598
+ operation,
17599
+ failureMessage: "Admin activity could not be loaded."
17600
+ });
16829
17601
  return {
16830
17602
  /**
16831
17603
  * One page of the admin sign-in history: sign-ins, failed attempts,
@@ -17064,10 +17836,43 @@ var require_lockouts = __commonJS({
17064
17836
  }
17065
17837
  });
17066
17838
 
17839
+ // server/src/utils/user-export.js
17840
+ var require_user_export = __commonJS({
17841
+ "server/src/utils/user-export.js"(exports2, module2) {
17842
+ "use strict";
17843
+ var { SECURITY_EVENTS } = require_security_log_model();
17844
+ var IMPERSONATION_TEXT = Object.freeze({
17845
+ [SECURITY_EVENTS.IMPERSONATION_STARTED]: "An administrator opened your account",
17846
+ [SECURITY_EVENTS.IMPERSONATION_ENDED]: "The administrator access to your account ended",
17847
+ [SECURITY_EVENTS.IMPERSONATION_EXPIRED]: "The administrator access to your account ended",
17848
+ [SECURITY_EVENTS.IMPERSONATION_REFUSED]: "An administrator access to your account was refused"
17849
+ });
17850
+ function toUserExportEvent(row) {
17851
+ const { id: _id, ...rest } = row || {};
17852
+ const text = IMPERSONATION_TEXT[rest.event];
17853
+ if (!text) return rest;
17854
+ const minutes = Number(rest.meta?.durationMinutes);
17855
+ return {
17856
+ event: rest.event,
17857
+ createdAt: rest.createdAt,
17858
+ ip: null,
17859
+ userAgent: null,
17860
+ geo: null,
17861
+ meta: {
17862
+ description: text,
17863
+ ...Number.isInteger(minutes) && minutes > 0 ? { durationMinutes: minutes } : {}
17864
+ }
17865
+ };
17866
+ }
17867
+ module2.exports = { IMPERSONATION_TEXT, toUserExportEvent };
17868
+ }
17869
+ });
17870
+
17067
17871
  // server/src/controllers/self-service.js
17068
17872
  var require_self_service = __commonJS({
17069
17873
  "server/src/controllers/self-service.js"(exports2, module2) {
17070
17874
  "use strict";
17875
+ var crypto = require("node:crypto");
17071
17876
  var { getCoordinator } = require_coordination();
17072
17877
  var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
17073
17878
  var { recordUserEvent } = require_sign_in_policies();
@@ -17075,6 +17880,7 @@ var require_self_service = __commonJS({
17075
17880
  var { SECURITY_EVENTS } = require_security_log_model();
17076
17881
  var { sendServerError } = require_http_errors();
17077
17882
  var { createLogger } = require_logger();
17883
+ var { toUserExportEvent } = require_user_export();
17078
17884
  var SESSION_UID = "plugin::magic-sessionmanager.session";
17079
17885
  var EVENT_UID = "plugin::magic-sessionmanager.security-event";
17080
17886
  var USER_UID = "plugin::users-permissions.user";
@@ -17141,19 +17947,21 @@ var require_self_service = __commonJS({
17141
17947
  return "en";
17142
17948
  }
17143
17949
  var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
17144
- function sendPage(ctx, status, lang, title, body) {
17950
+ 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);})();`;
17951
+ var FRAGMENT_SCRIPT_HASH = `sha256-${crypto.createHash("sha256").update(FRAGMENT_SCRIPT).digest("base64")}`;
17952
+ function sendPage(ctx, status, lang, title, body, { withScript = false } = {}) {
17145
17953
  ctx.status = status;
17146
17954
  ctx.set("Content-Type", "text/html; charset=utf-8");
17147
17955
  ctx.set(
17148
17956
  "Content-Security-Policy",
17149
- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
17957
+ `default-src 'none'; style-src 'unsafe-inline'; ${withScript ? `script-src '${FRAGMENT_SCRIPT_HASH}'; ` : ""}form-action 'self'; frame-ancestors 'none'; base-uri 'none'`
17150
17958
  );
17151
17959
  ctx.set("Referrer-Policy", "no-referrer");
17152
17960
  ctx.set("Cache-Control", "no-store");
17153
17961
  ctx.set("X-Robots-Tag", "noindex");
17154
17962
  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>
17155
17963
  <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>
17156
- <body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
17964
+ <body><main><h1>${escapeHtml(title)}</h1>${body}</main>${withScript ? `<script>${FRAGMENT_SCRIPT}</script>` : ""}</body></html>`;
17157
17965
  }
17158
17966
  module2.exports = ({ strapi: strapi2 }) => {
17159
17967
  const log = createLogger(strapi2);
@@ -17161,17 +17969,20 @@ var require_self_service = __commonJS({
17161
17969
  /**
17162
17970
  * Confirmation page of the "This wasn't me" link. Uses nothing.
17163
17971
  *
17164
- * @route GET /api/magic-sessionmanager/not-me?token=
17972
+ * @route GET /api/magic-sessionmanager/not-me (token in `#token=`; `?token=` before 4.22.1)
17165
17973
  * @auth none (public on purpose: the link is opened from an email; the
17166
17974
  * signed token is checked, and nothing changes until the POST)
17167
17975
  * @param {any} ctx Koa context.
17168
- * @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
17976
+ * @returns {Promise<void>} 200 page with two buttons, or 410 when a `?token=` link is
17977
+ * invalid. Without `?token=` the page is served with the hashed script that copies the
17978
+ * fragment token into the forms; the POST checks it.
17169
17979
  */
17170
17980
  async notMePage(ctx) {
17171
17981
  const lang = pageLanguage(ctx);
17172
17982
  const text = PAGE_TEXT[lang];
17173
- const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
17174
- if (!readNotMeToken(token)) {
17983
+ const hasQueryToken = typeof ctx.query?.token === "string" && ctx.query.token !== "";
17984
+ const token = hasQueryToken ? ctx.query.token : "";
17985
+ if (hasQueryToken && !readNotMeToken(token)) {
17175
17986
  return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
17176
17987
  }
17177
17988
  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>`;
@@ -17180,7 +17991,8 @@ var require_self_service = __commonJS({
17180
17991
  200,
17181
17992
  lang,
17182
17993
  text.title,
17183
- `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
17994
+ `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`,
17995
+ { withScript: !hasQueryToken }
17184
17996
  );
17185
17997
  },
17186
17998
  /**
@@ -17333,7 +18145,9 @@ var require_self_service = __commonJS({
17333
18145
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
17334
18146
  user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
17335
18147
  sessions,
17336
- securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
18148
+ // Impersonation events show a fixed text and the duration only
18149
+ // (security review 2, L3): the admin's reason stays internal.
18150
+ securityEvents: (Array.isArray(events) ? events : []).map(toUserExportEvent)
17337
18151
  };
17338
18152
  } catch (err) {
17339
18153
  log.error("[my-data] Export failed:", err?.name || "Error");
@@ -17893,7 +18707,8 @@ var require_impersonation = __commonJS({
17893
18707
  * Caller (with roles), target id and request body.
17894
18708
  * @returns {Promise<object>} Impersonation DTO plus the preview.
17895
18709
  * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17896
- * or not a subset of the caller's permissions; 404 unknown admin.
18710
+ * (callers with `admin::users.read`) or not a subset of the caller's permissions; 404
18711
+ * unknown admin, or a Super Admin for callers without `admin::users.read`.
17897
18712
  * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17898
18713
  */
17899
18714
  async previewAdmin({ actor, adminId, body, canReadAdmins }) {
@@ -17923,6 +18738,15 @@ var require_impersonation = __commonJS({
17923
18738
  ]);
17924
18739
  if (!target) throw new ImpersonationError(404, "Admin not found");
17925
18740
  const refusal = await previewRefusal(strapi2, caller || actor, target);
18741
+ if (refusal?.reason === "super-admin" && !canReadAdmins) {
18742
+ service.recordRefused({
18743
+ actorId,
18744
+ targetType: "admin",
18745
+ targetId: adminId,
18746
+ reason: "super-admin"
18747
+ });
18748
+ throw new ImpersonationError(404, "Admin not found");
18749
+ }
17926
18750
  if (refusal) {
17927
18751
  const messages = {
17928
18752
  self: "You cannot view yourself as another admin",
@@ -18332,25 +19156,32 @@ var require_impersonation = __commonJS({
18332
19156
  };
18333
19157
  },
18334
19158
  /**
18335
- * Loads one impersonation for the request guard (5-second cache).
19159
+ * Loads one impersonation for the request guard. Only a finished (or
19160
+ * unknown) impersonation is cached for 5 seconds; an active one is read
19161
+ * on every request, so ending it on one process takes effect on every
19162
+ * other process at once (security review 2, hardening 4).
18336
19163
  *
18337
19164
  * @param {string} documentId Impersonation id.
18338
- * @returns {Promise<{id: string, actorId: string, state: string, expiresAt: number}|null>}
19165
+ * @returns {Promise<{id: string, actorId: string, targetId: string|null, state: string,
19166
+ * expiresAt: number}|null>}
18339
19167
  */
18340
19168
  async loadForGuard(documentId) {
18341
19169
  const cached = recordCache.get(documentId);
18342
19170
  if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
18343
19171
  const row = await query().findOne({
18344
19172
  where: { documentId, targetType: "user" },
18345
- select: ["documentId", "actorId", "state", "expiresAt"]
19173
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt"]
18346
19174
  });
18347
19175
  const value = row ? {
18348
19176
  id: row.documentId,
18349
19177
  actorId: row.actorId,
19178
+ targetId: typeof row.targetId === "string" ? row.targetId : null,
18350
19179
  state: row.state,
18351
19180
  expiresAt: new Date(row.expiresAt).getTime()
18352
19181
  } : null;
18353
- remember(recordCache, documentId, { value, at: Date.now() });
19182
+ if (!value || value.state !== "active") {
19183
+ remember(recordCache, documentId, { value, at: Date.now() });
19184
+ }
18354
19185
  return value;
18355
19186
  },
18356
19187
  /**
@@ -18393,7 +19224,10 @@ var require_impersonation = __commonJS({
18393
19224
  * Records a refused Content API call made while impersonating (one event
18394
19225
  * per impersonation and reason per minute).
18395
19226
  *
18396
- * @param {{id: string, actorId: string}} impersonation Impersonation.
19227
+ * The impersonated user is the target (since 4.22), so the refusal shows
19228
+ * in that user's security activity and is deleted with the account.
19229
+ *
19230
+ * @param {{id: string, actorId: string, targetId?: string|null}} impersonation Impersonation.
18397
19231
  * @param {string} reason Refusal reason.
18398
19232
  * @returns {void}
18399
19233
  */
@@ -18408,7 +19242,7 @@ var require_impersonation = __commonJS({
18408
19242
  actorType: "admin",
18409
19243
  actorId: impersonation.actorId,
18410
19244
  targetType: "user",
18411
- targetId: null,
19245
+ targetId: impersonation.targetId || null,
18412
19246
  meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
18413
19247
  });
18414
19248
  },
@@ -18666,6 +19500,265 @@ var require_impersonation2 = __commonJS({
18666
19500
  }
18667
19501
  });
18668
19502
 
19503
+ // server/src/utils/user-activity-model.js
19504
+ var require_user_activity_model = __commonJS({
19505
+ "server/src/utils/user-activity-model.js"(exports2, module2) {
19506
+ "use strict";
19507
+ var { REFUSAL_REASONS, SECURITY_EVENTS, toObject } = require_security_log_model();
19508
+ var USER_ACCOUNT_EVENTS = Object.freeze([
19509
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
19510
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
19511
+ SECURITY_EVENTS.USER_LOCKOUT,
19512
+ SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
19513
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
19514
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
19515
+ SECURITY_EVENTS.USER_NEW_DEVICE,
19516
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
19517
+ SECURITY_EVENTS.USER_NOT_ME,
19518
+ SECURITY_EVENTS.USER_DATA_EXPORTED
19519
+ ]);
19520
+ var USER_IMPERSONATION_EVENTS = Object.freeze([
19521
+ SECURITY_EVENTS.IMPERSONATION_STARTED,
19522
+ SECURITY_EVENTS.IMPERSONATION_ENDED,
19523
+ SECURITY_EVENTS.IMPERSONATION_EXPIRED,
19524
+ SECURITY_EVENTS.IMPERSONATION_REFUSED
19525
+ ]);
19526
+ var USER_ACTIVITY_EVENTS = Object.freeze([...USER_ACCOUNT_EVENTS, ...USER_IMPERSONATION_EVENTS]);
19527
+ var USER_ACTIVITY_FILTERS = Object.freeze({
19528
+ all: USER_ACTIVITY_EVENTS,
19529
+ failed: Object.freeze([
19530
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
19531
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED
19532
+ ]),
19533
+ lockouts: Object.freeze([SECURITY_EVENTS.USER_LOCKOUT, SECURITY_EVENTS.USER_LOCKOUT_LIFTED]),
19534
+ suspicious: Object.freeze([
19535
+ SECURITY_EVENTS.USER_NEW_DEVICE,
19536
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
19537
+ SECURITY_EVENTS.USER_NOT_ME
19538
+ ]),
19539
+ sessions: Object.freeze([
19540
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
19541
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED
19542
+ ]),
19543
+ privacy: Object.freeze([SECURITY_EVENTS.USER_DATA_EXPORTED]),
19544
+ impersonation: USER_IMPERSONATION_EVENTS
19545
+ });
19546
+ var USER_DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
19547
+ function userActivityWhere(query, { retentionDays, now = /* @__PURE__ */ new Date() }) {
19548
+ const group = (
19549
+ /** @type {Record<string, readonly string[]>} */
19550
+ USER_ACTIVITY_FILTERS[query.event || "all"] || USER_ACTIVITY_FILTERS.all
19551
+ );
19552
+ const account = group.filter((event) => USER_ACCOUNT_EVENTS.includes(event));
19553
+ const impersonation = group.filter((event) => USER_IMPERSONATION_EVENTS.includes(event));
19554
+ const kinds = [];
19555
+ if (account.length) kinds.push({ event: { $in: account } });
19556
+ if (impersonation.length) kinds.push({ event: { $in: impersonation }, targetType: "user" });
19557
+ const conditions = [kinds.length === 1 ? kinds[0] : { $or: kinds }];
19558
+ if (query.userId) conditions.push({ targetType: "user", targetId: String(query.userId) });
19559
+ const days = Number.isInteger(retentionDays) && retentionDays > 0 ? retentionDays : 90;
19560
+ const cutoff = new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
19561
+ const from = query.from && query.from > cutoff ? query.from : cutoff;
19562
+ conditions.push({ createdAt: { $gte: from } });
19563
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
19564
+ return { $and: conditions };
19565
+ }
19566
+ var count = (value, max = 1e6) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max ? value : null;
19567
+ var oneOf = (value, allowed) => typeof value === "string" && allowed.includes(value) ? value : null;
19568
+ var countryCode = (value) => typeof value === "string" && /^[A-Z]{2}$/.test(value) ? value : null;
19569
+ var code = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value) ? value : null;
19570
+ function userEventFacts(event, storedMeta, viewer = {}) {
19571
+ const meta = toObject(storedMeta);
19572
+ switch (event) {
19573
+ case SECURITY_EVENTS.USER_SIGN_IN_FAILED:
19574
+ return { status: count(meta.status, 599), unknownAccount: meta.unknownAccount === true };
19575
+ case SECURITY_EVENTS.USER_SIGN_IN_REFUSED:
19576
+ return {
19577
+ reason: oneOf(meta.reason, REFUSAL_REASONS),
19578
+ limit: count(meta.limit, 1e4),
19579
+ lock: oneOf(meta.lock, ["ip", "account"]),
19580
+ unknownAccount: meta.unknownAccount === true
19581
+ };
19582
+ case SECURITY_EVENTS.USER_LOCKOUT:
19583
+ return {
19584
+ kind: oneOf(meta.kind, ["ip", "account"]),
19585
+ failures: count(meta.failures, 1e5),
19586
+ minutes: count(meta.minutes, 1e6)
19587
+ };
19588
+ case SECURITY_EVENTS.USER_LOCKOUT_LIFTED:
19589
+ return { kind: oneOf(meta.kind, ["ip", "account"]) };
19590
+ case SECURITY_EVENTS.USER_SESSION_LIMIT:
19591
+ return { ended: count(meta.ended, 1e5), limit: count(meta.limit, 1e4) };
19592
+ case SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED:
19593
+ return { ended: count(meta.ended, 1e5) };
19594
+ case SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL:
19595
+ return {
19596
+ distanceKm: count(meta.distanceKm, 5e4),
19597
+ speedKmh: count(meta.speedKmh, 1e7),
19598
+ from: countryCode(meta.from),
19599
+ to: countryCode(meta.to),
19600
+ action: oneOf(meta.action, ["alert", "reauthenticate"])
19601
+ };
19602
+ case SECURITY_EVENTS.USER_NOT_ME:
19603
+ return { scope: oneOf(meta.scope, ["session", "all"]), ended: count(meta.ended, 1e5) };
19604
+ case SECURITY_EVENTS.USER_DATA_EXPORTED:
19605
+ return { sessions: count(meta.sessions, 1e6), events: count(meta.events, 1e6) };
19606
+ case SECURITY_EVENTS.IMPERSONATION_STARTED:
19607
+ case SECURITY_EVENTS.IMPERSONATION_ENDED:
19608
+ case SECURITY_EVENTS.IMPERSONATION_EXPIRED:
19609
+ case SECURITY_EVENTS.IMPERSONATION_REFUSED: {
19610
+ const reason = viewer.canSeeImpersonationReason === true && typeof meta.reason === "string" && meta.reason.trim() ? meta.reason.trim().slice(0, 255) : null;
19611
+ return {
19612
+ durationMinutes: count(meta.durationMinutes, 1440),
19613
+ handoff: oneOf(meta.handoff, ["frontend", "token"]),
19614
+ endReason: oneOf(meta.endReason, ["ended", "disabled", "failed"]),
19615
+ refusal: code(meta.refusal),
19616
+ reason
19617
+ };
19618
+ }
19619
+ default:
19620
+ return {};
19621
+ }
19622
+ }
19623
+ function userEventAddress(row, options, anonymize) {
19624
+ if (!options.storeIp) return { ipAddress: null, ipAnonymized: false, keepLocation: false };
19625
+ const stored = typeof row.ip === "string" && row.ip ? row.ip : null;
19626
+ const alreadyShortened = toObject(row.meta).ipAnonymized === true;
19627
+ if (!stored) return { ipAddress: null, ipAnonymized: false, keepLocation: true };
19628
+ if (options.anonymizeIp && !alreadyShortened) {
19629
+ const shortened = anonymize(stored);
19630
+ return { ipAddress: shortened || null, ipAnonymized: Boolean(shortened), keepLocation: true };
19631
+ }
19632
+ return { ipAddress: stored, ipAnonymized: alreadyShortened, keepLocation: true };
19633
+ }
19634
+ module2.exports = {
19635
+ USER_ACCOUNT_EVENTS,
19636
+ USER_ACTIVITY_EVENTS,
19637
+ USER_ACTIVITY_FILTERS,
19638
+ USER_DOCUMENT_ID_PATTERN,
19639
+ USER_IMPERSONATION_EVENTS,
19640
+ userActivityWhere,
19641
+ userEventAddress,
19642
+ userEventFacts
19643
+ };
19644
+ }
19645
+ });
19646
+
19647
+ // server/src/controllers/user-activity.js
19648
+ var require_user_activity = __commonJS({
19649
+ "server/src/controllers/user-activity.js"(exports2, module2) {
19650
+ "use strict";
19651
+ var { z } = require("@strapi/utils");
19652
+ var { USER_ACTIVITY_FILTERS } = require_user_activity_model();
19653
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
19654
+ var { createLogger } = require_logger();
19655
+ var { callerCan } = require_settings_access();
19656
+ var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
19657
+ var listQuerySchema = z.strictObject({
19658
+ event: z.enum(
19659
+ /** @type {[string, ...string[]]} */
19660
+ Object.keys(USER_ACTIVITY_FILTERS)
19661
+ ).default("all"),
19662
+ userId: z.string().regex(/^[A-Za-z0-9]{1,64}$/, "userId must be the documentId of a user").optional(),
19663
+ ...periodAndPaging()
19664
+ });
19665
+ var exportQuerySchema = listQuerySchema.omit({ page: true, pageSize: true }).extend({
19666
+ cursor: cursorField
19667
+ });
19668
+ module2.exports = ({ strapi: strapi2 }) => {
19669
+ const log = createLogger(strapi2);
19670
+ const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
19671
+ const viewerOf = (ctx) => ({
19672
+ ability: (
19673
+ /** @type {any} */
19674
+ ctx.state?.userAbility || null
19675
+ ),
19676
+ canReadAdmins: callerCan(ctx, "admin::users.read"),
19677
+ canSeeImpersonationReason: callerCan(ctx, IMPERSONATE_USERS_ACTION)
19678
+ });
19679
+ const audit = (ctx, exported) => {
19680
+ const state = (
19681
+ /** @type {any} */
19682
+ ctx.state
19683
+ );
19684
+ const viaToken = state?.auth?.strategy?.name === "admin-token";
19685
+ if (!viaToken && !exported) return;
19686
+ try {
19687
+ service().recordLogRead({
19688
+ adminId: state?.user?.id,
19689
+ tokenId: viaToken ? state?.auth?.credentials?.id : null,
19690
+ list: "user-activity",
19691
+ exported,
19692
+ via: viaToken ? "admin-token" : "admin-panel"
19693
+ });
19694
+ } catch {
19695
+ }
19696
+ };
19697
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
19698
+ log,
19699
+ logPrefix: "User activity",
19700
+ operation,
19701
+ failureMessage: "Security activity could not be loaded."
19702
+ });
19703
+ return {
19704
+ /**
19705
+ * One page of the app-user security activity, newest first.
19706
+ *
19707
+ * @route GET /magic-sessionmanager/user-activity
19708
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + user-activity.read;
19709
+ * read rate limit.
19710
+ * @param {Context} ctx Reads `ctx.query.event` (`all`|`failed`|`lockouts`|`suspicious`|
19711
+ * `sessions`|`privacy`|`impersonation`), `userId` (documentId of a Users & Permissions
19712
+ * user), `from`/`to` (ISO dates), `page`, `pageSize` (1..100, default 20). Unknown keys
19713
+ * are a 400.
19714
+ * @returns {Promise<unknown>} 200 `{ data: UserEventRow[], meta: { pagination, recording,
19715
+ * identity } }`; 400 ValidationError with field errors; 500 fixed message. Rows hold the
19716
+ * event, time, the user (`{ id, documentId, email, username }`, email and username empty
19717
+ * unless the caller may read that user in the Content Manager), the admin who acted
19718
+ * (name empty without `admin::users.read`), the event's facts (numbers and codes; the
19719
+ * impersonation reason only with `impersonate.users`), IP address as the current
19720
+ * switches allow it, location, browser, OS and the stored user agent. Rows older than
19721
+ * the retention period are left out.
19722
+ * @sideeffect A read with an admin API token queues a `security-log.read` event.
19723
+ */
19724
+ async list(ctx) {
19725
+ return handle(
19726
+ ctx,
19727
+ listQuerySchema,
19728
+ (query) => {
19729
+ audit(ctx, false);
19730
+ return service().listUserActivity(query, viewerOf(ctx));
19731
+ },
19732
+ "list"
19733
+ );
19734
+ },
19735
+ /**
19736
+ * One export batch (500 rows, keyset cursor) of the app-user security activity.
19737
+ *
19738
+ * @route GET /magic-sessionmanager/user-activity/export
19739
+ * @auth As list.
19740
+ * @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
19741
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
19742
+ * @sideeffect The first batch of an export (no `cursor`) queues a `security-log.read` event
19743
+ * with `list: 'user-activity'`, `exported: true` and `via` (`admin-panel` or
19744
+ * `admin-token`).
19745
+ */
19746
+ async export(ctx) {
19747
+ return handle(
19748
+ ctx,
19749
+ exportQuerySchema,
19750
+ (query) => {
19751
+ if (!query.cursor) audit(ctx, true);
19752
+ return service().exportBatch("user-activity", query, query.cursor || null, viewerOf(ctx));
19753
+ },
19754
+ "export"
19755
+ );
19756
+ }
19757
+ };
19758
+ };
19759
+ }
19760
+ });
19761
+
18669
19762
  // server/src/controllers/index.js
18670
19763
  var require_controllers = __commonJS({
18671
19764
  "server/src/controllers/index.js"(exports2, module2) {
@@ -18679,6 +19772,7 @@ var require_controllers = __commonJS({
18679
19772
  var selfService = require_self_service();
18680
19773
  var webhooks = require_webhooks();
18681
19774
  var impersonation = require_impersonation2();
19775
+ var userActivity = require_user_activity();
18682
19776
  module2.exports = {
18683
19777
  session,
18684
19778
  settings,
@@ -18688,7 +19782,8 @@ var require_controllers = __commonJS({
18688
19782
  lockouts,
18689
19783
  "self-service": selfService,
18690
19784
  webhooks,
18691
- impersonation
19785
+ impersonation,
19786
+ "user-activity": userActivity
18692
19787
  };
18693
19788
  }
18694
19789
  });
@@ -21464,6 +22559,12 @@ var require_security_log = __commonJS({
21464
22559
  normalizeIp
21465
22560
  } = require_admin_request_info();
21466
22561
  var { resolveSecurityLogSettings } = require_security_log_settings();
22562
+ var {
22563
+ USER_ACTIVITY_EVENTS,
22564
+ userActivityWhere,
22565
+ userEventAddress,
22566
+ userEventFacts
22567
+ } = require_user_activity_model();
21467
22568
  var { getPluginSettings } = require_settings_loader();
21468
22569
  var { shouldResolveGeoData } = require_enhance_session();
21469
22570
  var { createLogger } = require_logger();
@@ -21471,6 +22572,7 @@ var require_security_log = __commonJS({
21471
22572
  var ADMIN_USER_UID = "admin::user";
21472
22573
  var ADMIN_SESSION_UID = "admin::session";
21473
22574
  var PERMISSION_UID = "admin::permission";
22575
+ var USER_UID = "plugin::users-permissions.user";
21474
22576
  var SUPER_ADMIN_CODE = "strapi-super-admin";
21475
22577
  var FLUSH_DELAY_MS = 1e3;
21476
22578
  var FLUSH_BATCH = 200;
@@ -21487,6 +22589,7 @@ var require_security_log = __commonJS({
21487
22589
  var EXPORT_BATCH = 500;
21488
22590
  var DELETE_BATCH = 1e3;
21489
22591
  var MAX_DELETE_STEPS = 200;
22592
+ var AUDITED_LISTS = Object.freeze(["sign-ins", "content", "user-activity"]);
21490
22593
  function toId(value) {
21491
22594
  if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
21492
22595
  if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
@@ -21862,13 +22965,35 @@ var require_security_log = __commonJS({
21862
22965
  * @sideeffect Queues one always-on security event.
21863
22966
  */
21864
22967
  recordTokenRead(input) {
21865
- const now = Date.now();
21866
- const tokenId = toId(input?.tokenId);
21867
- const key = `${tokenId || "-"}|${input?.list}|${input?.exported ? "export" : "list"}`;
21868
- const last = readAudits.get(key);
21869
- if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
21870
- readAudits.set(key, now);
21871
- pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
22968
+ return service.recordLogRead({ ...input, via: "admin-token" });
22969
+ },
22970
+ /**
22971
+ * Records a read of the security log (`security-log.read`, always on).
22972
+ * Reads with an admin API token (4.17) are recorded once per token, list
22973
+ * and kind within 5 minutes. An export of the app-user activity from the
22974
+ * admin panel (4.22) is recorded each time it starts: it takes personal
22975
+ * data of app users out of Strapi.
22976
+ *
22977
+ * @param {{adminId: unknown, tokenId?: unknown, list: 'sign-ins'|'content'|'user-activity',
22978
+ * exported: boolean, via: 'admin-token'|'admin-panel'}} input Who read what, and how.
22979
+ * @returns {boolean} Whether an event was queued.
22980
+ * @sideeffect Queues one always-on security event.
22981
+ */
22982
+ recordLogRead(input) {
22983
+ const via = input?.via === "admin-panel" ? "admin-panel" : "admin-token";
22984
+ const list = AUDITED_LISTS.includes(
22985
+ /** @type {string} */
22986
+ input?.list
22987
+ ) ? input.list : "sign-ins";
22988
+ const tokenId = via === "admin-token" ? toId(input?.tokenId) : null;
22989
+ if (via === "admin-token") {
22990
+ const now = Date.now();
22991
+ const key = `${tokenId || "-"}|${list}|${input?.exported ? "export" : "list"}`;
22992
+ const last = readAudits.get(key);
22993
+ if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
22994
+ readAudits.set(key, now);
22995
+ pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
22996
+ }
21872
22997
  return service.record({
21873
22998
  event: SECURITY_EVENTS.LOG_READ,
21874
22999
  actorType: "admin",
@@ -21879,9 +23004,9 @@ var require_security_log = __commonJS({
21879
23004
  targetType: "security-log",
21880
23005
  targetId: null,
21881
23006
  meta: {
21882
- list: input?.list === "content" ? "content" : "sign-ins",
23007
+ list,
21883
23008
  exported: input?.exported === true,
21884
- via: "admin-token",
23009
+ via,
21885
23010
  ...tokenId ? { tokenId } : {}
21886
23011
  }
21887
23012
  });
@@ -22018,16 +23143,63 @@ var require_security_log = __commonJS({
22018
23143
  };
22019
23144
  },
22020
23145
  /**
22021
- * One export batch (newest first, keyset on id) of either list.
23146
+ * One page of the app-user security activity (4.22), newest first:
23147
+ * failed and refused sign-ins, lockouts, session limits, sign-outs after
23148
+ * a password change, new devices, impossible travel, "This wasn't me",
23149
+ * data exports and impersonations of app users. Rows older than the
23150
+ * retention period are not returned; IP addresses follow the current
23151
+ * "Store" and "Anonymise" switches.
23152
+ *
23153
+ * @param {{event?: string, userId?: string, from?: Date|null, to?: Date|null,
23154
+ * page: number, pageSize: number}} query Parsed filters.
23155
+ * @param {Viewer} [viewer] Reader (user emails need Content Manager read access to the
23156
+ * user; admin names `admin::users.read`; impersonation reasons `impersonate.users`).
23157
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
23158
+ */
23159
+ async listUserActivity(query, viewer = {}) {
23160
+ const settings = await readSettingsOrDefaults();
23161
+ const options = resolveSecurityLogSettings(settings);
23162
+ const where = userActivityWhere(query, options);
23163
+ const [total, rows] = await Promise.all([
23164
+ events().count({ where }),
23165
+ events().findMany({
23166
+ where,
23167
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
23168
+ offset: (query.page - 1) * query.pageSize,
23169
+ limit: query.pageSize
23170
+ })
23171
+ ]);
23172
+ const shaped = await shapeUserEvents(Array.isArray(rows) ? rows : [], viewer, options);
23173
+ return {
23174
+ data: shaped.data,
23175
+ meta: {
23176
+ pagination: paginationOf(query, total),
23177
+ recording: {
23178
+ ipAddresses: options.storeIp,
23179
+ anonymizeIp: options.anonymizeIp,
23180
+ retentionDays: options.retentionDays,
23181
+ userSignIns: settings.recordUserSignInEvents !== false
23182
+ },
23183
+ identity: {
23184
+ users: shaped.usersVisible,
23185
+ names: viewer.canReadAdmins === true,
23186
+ impersonationReasons: viewer.canSeeImpersonationReason === true
23187
+ }
23188
+ }
23189
+ };
23190
+ },
23191
+ /**
23192
+ * One export batch (newest first, keyset on id) of a list.
22022
23193
  *
22023
- * @param {'sign-ins'|'content'} kind List.
23194
+ * @param {'sign-ins'|'content'|'user-activity'} kind List.
22024
23195
  * @param {any} query Parsed filters (as for the list).
22025
23196
  * @param {number|null} cursor Id below which to continue.
22026
23197
  * @param {Viewer} [viewer] Reader; the same title and name rules as the lists.
22027
23198
  * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
22028
23199
  */
22029
23200
  async exportBatch(kind, query, cursor, viewer = {}) {
22030
- const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
23201
+ const options = kind === "user-activity" ? resolveSecurityLogSettings(await readSettingsOrDefaults()) : null;
23202
+ const base = kind === "sign-ins" ? signInWhere(query) : kind === "user-activity" && options ? userActivityWhere(query, options) : activityWhere(query);
22031
23203
  const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
22032
23204
  const rows = await events().findMany({
22033
23205
  where,
@@ -22035,7 +23207,11 @@ var require_security_log = __commonJS({
22035
23207
  limit: EXPORT_BATCH
22036
23208
  });
22037
23209
  const list = Array.isArray(rows) ? rows : [];
22038
- const data = kind === "sign-ins" ? await shapeSignIns(list, viewer) : await shapeActivity(list, viewer);
23210
+ let data;
23211
+ if (kind === "sign-ins") data = await shapeSignIns(list, viewer);
23212
+ else if (kind === "user-activity" && options) {
23213
+ data = (await shapeUserEvents(list, viewer, options)).data;
23214
+ } else data = await shapeActivity(list, viewer);
22039
23215
  const last = list[list.length - 1];
22040
23216
  return {
22041
23217
  data,
@@ -22211,14 +23387,15 @@ var require_security_log = __commonJS({
22211
23387
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
22212
23388
  return { $and: conditions };
22213
23389
  }
22214
- async function recordingFlags() {
22215
- let settings;
23390
+ async function readSettingsOrDefaults() {
22216
23391
  try {
22217
- settings = await getPluginSettings(strapi2);
23392
+ return await getPluginSettings(strapi2) || {};
22218
23393
  } catch {
22219
- settings = {};
23394
+ return {};
22220
23395
  }
22221
- const options = resolveSecurityLogSettings(settings);
23396
+ }
23397
+ async function recordingFlags() {
23398
+ const options = resolveSecurityLogSettings(await readSettingsOrDefaults());
22222
23399
  return {
22223
23400
  signIns: options.signIns,
22224
23401
  contentActivity: options.content,
@@ -22283,8 +23460,9 @@ var require_security_log = __commonJS({
22283
23460
  sessionsEnded: revoked && Number.isInteger(meta.ended) && meta.ended >= 0 ? meta.ended : null,
22284
23461
  change: row.event === SECURITY_EVENTS.SETTINGS_UPDATED ? { keys: settingKeysOf(meta.keys), viaToken: meta.via === "admin-token" } : null,
22285
23462
  read: row.event === SECURITY_EVENTS.LOG_READ ? {
22286
- list: meta.list === "content" ? "content" : "sign-ins",
22287
- exported: meta.exported === true
23463
+ list: AUDITED_LISTS.includes(meta.list) ? meta.list : "sign-ins",
23464
+ exported: meta.exported === true,
23465
+ via: meta.via === "admin-panel" ? "admin-panel" : "admin-token"
22288
23466
  } : null,
22289
23467
  purge: row.event === SECURITY_EVENTS.LOG_RETENTION_PURGED ? {
22290
23468
  count: Number.isInteger(meta.count) ? meta.count : null,
@@ -22443,231 +23621,100 @@ var require_security_log = __commonJS({
22443
23621
  };
22444
23622
  });
22445
23623
  }
22446
- return service;
22447
- };
22448
- module2.exports.EVENT_UID = EVENT_UID;
22449
- module2.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
22450
- }
22451
- });
22452
-
22453
- // server/src/utils/webhook-delivery.js
22454
- var require_webhook_delivery = __commonJS({
22455
- "server/src/utils/webhook-delivery.js"(exports2, module2) {
22456
- "use strict";
22457
- var crypto = require("node:crypto");
22458
- var dns = require("node:dns");
22459
- var https = require("node:https");
22460
- var net = require("node:net");
22461
- var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
22462
- var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
22463
- var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
22464
- var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
22465
- var TIMEOUT_MS = 5e3;
22466
- var MAX_RESPONSE_BYTES = 64 * 1024;
22467
- var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
22468
- var BLOCKED = (() => {
22469
- const list = new net.BlockList();
22470
- for (const [address, prefix] of [
22471
- ["0.0.0.0", 8],
22472
- ["10.0.0.0", 8],
22473
- ["100.64.0.0", 10],
22474
- ["127.0.0.0", 8],
22475
- ["169.254.0.0", 16],
22476
- ["172.16.0.0", 12],
22477
- ["192.0.0.0", 24],
22478
- ["192.0.2.0", 24],
22479
- ["192.88.99.0", 24],
22480
- ["192.168.0.0", 16],
22481
- ["198.18.0.0", 15],
22482
- ["198.51.100.0", 24],
22483
- ["203.0.113.0", 24],
22484
- ["224.0.0.0", 4],
22485
- ["240.0.0.0", 4]
22486
- ]) {
22487
- list.addSubnet(address, prefix, "ipv4");
22488
- }
22489
- for (const [address, prefix] of [
22490
- ["::", 128],
22491
- ["::1", 128],
22492
- // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
22493
- // checks them against the IPv4 rules above, and a listed /96 would
22494
- // match every IPv4 address.
22495
- ["64:ff9b::", 96],
22496
- ["64:ff9b:1::", 48],
22497
- ["100::", 64],
22498
- ["2001::", 23],
22499
- ["2001:db8::", 32],
22500
- ["2002::", 16],
22501
- ["fc00::", 7],
22502
- ["fe80::", 10],
22503
- ["fec0::", 10],
22504
- ["ff00::", 8]
22505
- ]) {
22506
- list.addSubnet(address, prefix, "ipv6");
22507
- }
22508
- return list;
22509
- })();
22510
- function isBlockedAddress(address) {
22511
- let value = String(address || "").trim();
22512
- if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
22513
- value = value.slice(7);
22514
- }
22515
- const version = net.isIP(value);
22516
- if (version === 0) return true;
22517
- return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
22518
- }
22519
- function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
22520
- const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
22521
- return `t=${timestamp},v1=${digest}`;
22522
- }
22523
- function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
22524
- const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
22525
- if (!match) return false;
22526
- const timestamp = Number(match[1]);
22527
- if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
22528
- const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
22529
- const given = Buffer.from(match[2], "hex");
22530
- return given.length === expected.length && crypto.timingSafeEqual(given, expected);
22531
- }
22532
- var DeliveryError = class extends Error {
22533
- /**
22534
- * @param {string} code Stable code.
22535
- * @param {boolean} retryable Whether another attempt may succeed.
22536
- * @param {number|null} [status] HTTP status, when there was one.
22537
- */
22538
- constructor(code, retryable, status = null) {
22539
- super(code);
22540
- this.name = "DeliveryError";
22541
- this.code = code;
22542
- this.retryable = retryable;
22543
- this.status = status;
22544
- }
22545
- };
22546
- var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
22547
- function httpsPost({ url, address, headers, body, timeoutMs }) {
22548
- return new Promise((resolve, reject) => {
22549
- const request = https.request(
22550
- {
22551
- protocol: "https:",
22552
- hostname: url.hostname,
22553
- port: url.port || 443,
22554
- path: `${url.pathname}${url.search}`,
22555
- method: "POST",
22556
- headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
22557
- servername: net.isIP(url.hostname) ? void 0 : url.hostname,
22558
- timeout: timeoutMs,
22559
- // Pinned to the address that passed the check: no second lookup.
22560
- lookup: (_hostname, options, callback) => {
22561
- if (options && options.all) callback(null, [address]);
22562
- else callback(null, address.address, address.family);
22563
- }
22564
- },
22565
- (response) => {
22566
- let received = 0;
22567
- response.on("data", (chunk) => {
22568
- received += chunk.length;
22569
- if (received > MAX_RESPONSE_BYTES) response.destroy();
22570
- });
22571
- response.on("end", () => resolve(response.statusCode || 0));
22572
- response.on("close", () => resolve(response.statusCode || 0));
22573
- response.on("error", () => resolve(response.statusCode || 0));
23624
+ async function loadAppUsers(documentIds, ability) {
23625
+ const users = /* @__PURE__ */ new Map();
23626
+ if (!strapi2.contentTypes?.[USER_UID]) return { users, visible: false };
23627
+ let checker = null;
23628
+ if (ability) {
23629
+ try {
23630
+ const checkers = strapi2.plugin("content-manager")?.service("permission-checker");
23631
+ const candidate = checkers?.create({ userAbility: ability, model: USER_UID }) || null;
23632
+ checker = candidate && !candidate.cannot.read() ? candidate : null;
23633
+ } catch {
23634
+ checker = null;
22574
23635
  }
22575
- );
22576
- request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
22577
- request.on(
22578
- "error",
22579
- (err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
22580
- );
22581
- request.end(body);
22582
- });
22583
- }
22584
- async function deliverOnce({
22585
- url,
22586
- body,
22587
- headers,
22588
- resolve = resolveAll,
22589
- post = httpsPost,
22590
- timeoutMs = TIMEOUT_MS
22591
- }) {
22592
- let parsed;
22593
- try {
22594
- parsed = new URL(url);
22595
- } catch {
22596
- throw new DeliveryError("invalid_url", false);
22597
- }
22598
- if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
22599
- throw new DeliveryError("invalid_url", false);
22600
- }
22601
- const host = parsed.hostname.replace(/^\[|\]$/g, "");
22602
- let addresses;
22603
- if (net.isIP(host)) {
22604
- addresses = [{ address: host, family: net.isIP(host) }];
22605
- } else {
22606
- try {
22607
- addresses = await resolve(host);
22608
- } catch {
22609
- throw new DeliveryError("dns_failed", true);
22610
23636
  }
22611
- }
22612
- if (!Array.isArray(addresses) || addresses.length === 0)
22613
- throw new DeliveryError("dns_failed", true);
22614
- if (addresses.some((entry) => isBlockedAddress(entry.address))) {
22615
- throw new DeliveryError("address_not_allowed", false);
22616
- }
22617
- const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
22618
- if (status >= 200 && status < 300) return { status };
22619
- if (status >= 300 && status < 400)
22620
- throw new DeliveryError("redirect_not_followed", false, status);
22621
- throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
22622
- }
22623
- function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
22624
- const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
22625
- return {
22626
- id,
22627
- body,
22628
- headers: {
22629
- "Content-Type": "application/json",
22630
- "User-Agent": USER_AGENT,
22631
- [EVENT_HEADER]: event,
22632
- [DELIVERY_HEADER]: id,
22633
- [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
22634
- }
22635
- };
22636
- }
22637
- async function deliverWithRetries({
22638
- delays = RETRY_DELAYS_MS,
22639
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
22640
- ...request
22641
- }) {
22642
- let attempts = 0;
22643
- let last = { ok: false, status: null, code: "not_sent" };
22644
- for (const delay of delays) {
22645
- if (delay > 0) await sleep(delay);
22646
- attempts += 1;
22647
- try {
22648
- const { status } = await deliverOnce(request);
22649
- return { ok: true, status, code: null, attempts };
22650
- } catch (err) {
22651
- const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
22652
- last = { ok: false, status: error.status, code: error.code };
22653
- if (!error.retryable) break;
23637
+ const ids = [
23638
+ ...new Set(
23639
+ documentIds.filter((id) => typeof id === "string" && /^[A-Za-z0-9]{1,64}$/.test(id))
23640
+ )
23641
+ ];
23642
+ if (!ids.length) return { users, visible: Boolean(checker) };
23643
+ const attributes = strapi2.contentTypes[USER_UID].attributes || {};
23644
+ const found = await strapi2.db.query(USER_UID).findMany({
23645
+ select: ["id", "documentId", "email", "username"],
23646
+ where: { documentId: { $in: ids } },
23647
+ ...attributes.createdBy ? { populate: { createdBy: { select: ["id"] } } } : {},
23648
+ limit: ids.length * 2
23649
+ });
23650
+ for (const user of Array.isArray(found) ? found : []) {
23651
+ const may = (field) => {
23652
+ if (!checker) return false;
23653
+ try {
23654
+ return checker.can.read(user, field) === true;
23655
+ } catch {
23656
+ return false;
23657
+ }
23658
+ };
23659
+ const email = may("email") && typeof user.email === "string" ? user.email : "";
23660
+ const username = may("username") && typeof user.username === "string" ? user.username : "";
23661
+ users.set(String(user.documentId), {
23662
+ id: Number(user.id),
23663
+ documentId: String(user.documentId),
23664
+ email: email.slice(0, 254),
23665
+ username: username.slice(0, 200)
23666
+ });
22654
23667
  }
23668
+ return { users, visible: Boolean(checker) };
22655
23669
  }
22656
- return { ...last, attempts };
22657
- }
22658
- module2.exports = {
22659
- DELIVERY_HEADER,
22660
- DeliveryError,
22661
- EVENT_HEADER,
22662
- RETRY_DELAYS_MS,
22663
- SIGNATURE_HEADER,
22664
- buildSignedRequest,
22665
- deliverOnce,
22666
- deliverWithRetries,
22667
- isBlockedAddress,
22668
- signPayload,
22669
- verifySignature
23670
+ async function shapeUserEvents(rows, viewer, options) {
23671
+ const list = rows.filter((row) => USER_ACTIVITY_EVENTS.includes(row.event));
23672
+ const { users, visible } = await loadAppUsers(
23673
+ list.filter((row) => row.targetType === "user").map((row) => row.targetId),
23674
+ viewer.ability || null
23675
+ );
23676
+ const admins = await loadAdmins(
23677
+ list.filter((row) => row.actorType === "admin").map((row) => row.actorId)
23678
+ );
23679
+ const data = list.map((row) => {
23680
+ const byAdmin = row.actorType === "admin";
23681
+ const userAgent = !byAdmin && typeof row.userAgent === "string" && row.userAgent ? row.userAgent : null;
23682
+ const described = describeUserAgent(userAgent);
23683
+ const address = byAdmin ? { ipAddress: null, ipAnonymized: false, keepLocation: false } : userEventAddress(row, options, (ip) => anonymizeIp(normalizeIp(ip)));
23684
+ const user = row.targetType === "user" && typeof row.targetId === "string" ? users.get(row.targetId) || null : null;
23685
+ const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
23686
+ let actor = null;
23687
+ if (row.actorType === "system") actor = { type: "system", id: null, name: "" };
23688
+ else if (row.actorType === "admin" && toAdminId(row.actorId)) {
23689
+ actor = {
23690
+ type: "admin",
23691
+ id: Number(row.actorId),
23692
+ name: admin && viewer.canReadAdmins === true ? adminName(admin) : ""
23693
+ };
23694
+ }
23695
+ return {
23696
+ id: Number(row.id),
23697
+ event: row.event,
23698
+ at: toIso(row.createdAt),
23699
+ target: row.targetType === "ip" ? "ip" : "user",
23700
+ user,
23701
+ actor,
23702
+ details: userEventFacts(row.event, row.meta, viewer),
23703
+ ipAddress: address.ipAddress,
23704
+ ipAnonymized: address.ipAnonymized,
23705
+ location: address.keepLocation ? toLocation(row.geo) : null,
23706
+ browser: described.browserName,
23707
+ os: described.osName,
23708
+ deviceType: described.deviceType,
23709
+ userAgent: userAgent ? userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null
23710
+ };
23711
+ });
23712
+ return { data, usersVisible: visible };
23713
+ }
23714
+ return service;
22670
23715
  };
23716
+ module2.exports.EVENT_UID = EVENT_UID;
23717
+ module2.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
22671
23718
  }
22672
23719
  });
22673
23720
 
@@ -22949,12 +23996,14 @@ var require_rate_limit = __commonJS({
22949
23996
  "use strict";
22950
23997
  var { getPluginSettings } = require_settings_loader();
22951
23998
  var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
23999
+ var { ipBucket } = require_admin_request_info();
22952
24000
  var callerKey = (ctx) => {
22953
24001
  const userId = ctx.state?.user?.id;
22954
24002
  if (userId) return `u:${userId}`;
22955
24003
  const tokenId = ctx.state?.auth?.credentials?.id ?? ctx.state?.auth?.credentials?.token ?? null;
22956
24004
  if (tokenId) return `t:${String(tokenId).slice(-16)}`;
22957
- return `ip:${ctx.request.ip || ctx.ip || "unknown"}`;
24005
+ const ip = ctx.request.ip || ctx.ip || "";
24006
+ return `ip:${ipBucket(ip) || ip || "unknown"}`;
22958
24007
  };
22959
24008
  var routeKey = (ctx) => {
22960
24009
  const route = ctx.state?.route;