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
@@ -1477,10 +1477,249 @@ var require_policy_settings = __commonJS({
1477
1477
  }
1478
1478
  });
1479
1479
 
1480
+ // server/src/utils/webhook-delivery.js
1481
+ var require_webhook_delivery = __commonJS({
1482
+ "server/src/utils/webhook-delivery.js"(exports, module) {
1483
+ "use strict";
1484
+ var crypto = __require("node:crypto");
1485
+ var dns = __require("node:dns");
1486
+ var https = __require("node:https");
1487
+ var net = __require("node:net");
1488
+ var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
1489
+ var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
1490
+ var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
1491
+ var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
1492
+ var TIMEOUT_MS = 5e3;
1493
+ var DEADLINE_MS = 1e4;
1494
+ var MAX_RESPONSE_BYTES = 64 * 1024;
1495
+ var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
1496
+ var BLOCKED = (() => {
1497
+ const list = new net.BlockList();
1498
+ for (const [address, prefix] of [
1499
+ ["0.0.0.0", 8],
1500
+ ["10.0.0.0", 8],
1501
+ ["100.64.0.0", 10],
1502
+ ["127.0.0.0", 8],
1503
+ ["169.254.0.0", 16],
1504
+ ["172.16.0.0", 12],
1505
+ ["192.0.0.0", 24],
1506
+ ["192.0.2.0", 24],
1507
+ ["192.88.99.0", 24],
1508
+ ["192.168.0.0", 16],
1509
+ ["198.18.0.0", 15],
1510
+ ["198.51.100.0", 24],
1511
+ ["203.0.113.0", 24],
1512
+ ["224.0.0.0", 4],
1513
+ ["240.0.0.0", 4]
1514
+ ]) {
1515
+ list.addSubnet(address, prefix, "ipv4");
1516
+ }
1517
+ for (const [address, prefix] of [
1518
+ // IPv4-compatible (::a.b.c.d, deprecated) and IPv4-translated
1519
+ // (::ffff:0:a.b.c.d, RFC 2765) forms, which include the unspecified and
1520
+ // loopback addresses (security review 2, hardening 1).
1521
+ ["::", 96],
1522
+ ["::ffff:0:0:0", 96],
1523
+ // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
1524
+ // checks them against the IPv4 rules above, and a listed /96 would
1525
+ // match every IPv4 address.
1526
+ ["64:ff9b::", 96],
1527
+ ["64:ff9b:1::", 48],
1528
+ ["100::", 64],
1529
+ ["2001::", 23],
1530
+ ["2001:db8::", 32],
1531
+ ["2002::", 16],
1532
+ ["fc00::", 7],
1533
+ ["fe80::", 10],
1534
+ ["fec0::", 10],
1535
+ ["ff00::", 8]
1536
+ ]) {
1537
+ list.addSubnet(address, prefix, "ipv6");
1538
+ }
1539
+ return list;
1540
+ })();
1541
+ function isBlockedAddress(address) {
1542
+ let value = String(address || "").trim();
1543
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
1544
+ value = value.slice(7);
1545
+ }
1546
+ const version = net.isIP(value);
1547
+ if (version === 0) return true;
1548
+ return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
1549
+ }
1550
+ function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
1551
+ const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
1552
+ return `t=${timestamp},v1=${digest}`;
1553
+ }
1554
+ function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
1555
+ const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
1556
+ if (!match) return false;
1557
+ const timestamp = Number(match[1]);
1558
+ if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
1559
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
1560
+ const given = Buffer.from(match[2], "hex");
1561
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
1562
+ }
1563
+ var DeliveryError = class extends Error {
1564
+ /**
1565
+ * @param {string} code Stable code.
1566
+ * @param {boolean} retryable Whether another attempt may succeed.
1567
+ * @param {number|null} [status] HTTP status, when there was one.
1568
+ */
1569
+ constructor(code, retryable, status = null) {
1570
+ super(code);
1571
+ this.name = "DeliveryError";
1572
+ this.code = code;
1573
+ this.retryable = retryable;
1574
+ this.status = status;
1575
+ }
1576
+ };
1577
+ var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
1578
+ function httpsPost({ url, address, headers, body, timeoutMs, deadlineMs = DEADLINE_MS }) {
1579
+ return new Promise((resolve, reject) => {
1580
+ const request = https.request(
1581
+ {
1582
+ protocol: "https:",
1583
+ hostname: url.hostname,
1584
+ port: url.port || 443,
1585
+ path: `${url.pathname}${url.search}`,
1586
+ method: "POST",
1587
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
1588
+ servername: net.isIP(url.hostname) ? void 0 : url.hostname,
1589
+ timeout: timeoutMs,
1590
+ signal: AbortSignal.timeout(deadlineMs),
1591
+ // Pinned to the address that passed the check: no second lookup.
1592
+ lookup: (_hostname, options, callback) => {
1593
+ if (options && options.all) callback(null, [address]);
1594
+ else callback(null, address.address, address.family);
1595
+ }
1596
+ },
1597
+ (response) => {
1598
+ let received = 0;
1599
+ response.on("data", (chunk) => {
1600
+ received += chunk.length;
1601
+ if (received > MAX_RESPONSE_BYTES) response.destroy();
1602
+ });
1603
+ response.on("end", () => resolve(response.statusCode || 0));
1604
+ response.on("close", () => resolve(response.statusCode || 0));
1605
+ response.on("error", () => resolve(response.statusCode || 0));
1606
+ }
1607
+ );
1608
+ request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
1609
+ request.on(
1610
+ "error",
1611
+ (err) => reject(
1612
+ err instanceof DeliveryError ? err : err?.name === "AbortError" ? new DeliveryError("timeout", true) : new DeliveryError("network_error", true)
1613
+ )
1614
+ );
1615
+ request.end(body);
1616
+ });
1617
+ }
1618
+ async function deliverOnce({
1619
+ url,
1620
+ body,
1621
+ headers,
1622
+ resolve = resolveAll,
1623
+ post = httpsPost,
1624
+ timeoutMs = TIMEOUT_MS,
1625
+ deadlineMs = DEADLINE_MS
1626
+ }) {
1627
+ let parsed;
1628
+ try {
1629
+ parsed = new URL(url);
1630
+ } catch {
1631
+ throw new DeliveryError("invalid_url", false);
1632
+ }
1633
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
1634
+ throw new DeliveryError("invalid_url", false);
1635
+ }
1636
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
1637
+ let addresses;
1638
+ if (net.isIP(host)) {
1639
+ addresses = [{ address: host, family: net.isIP(host) }];
1640
+ } else {
1641
+ try {
1642
+ addresses = await resolve(host);
1643
+ } catch {
1644
+ throw new DeliveryError("dns_failed", true);
1645
+ }
1646
+ }
1647
+ if (!Array.isArray(addresses) || addresses.length === 0)
1648
+ throw new DeliveryError("dns_failed", true);
1649
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
1650
+ throw new DeliveryError("address_not_allowed", false);
1651
+ }
1652
+ const status = await post({
1653
+ url: parsed,
1654
+ address: addresses[0],
1655
+ headers,
1656
+ body,
1657
+ timeoutMs,
1658
+ deadlineMs
1659
+ });
1660
+ if (status >= 200 && status < 300) return { status };
1661
+ if (status >= 300 && status < 400)
1662
+ throw new DeliveryError("redirect_not_followed", false, status);
1663
+ throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
1664
+ }
1665
+ function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
1666
+ const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
1667
+ return {
1668
+ id,
1669
+ body,
1670
+ headers: {
1671
+ "Content-Type": "application/json",
1672
+ "User-Agent": USER_AGENT,
1673
+ [EVENT_HEADER]: event,
1674
+ [DELIVERY_HEADER]: id,
1675
+ [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
1676
+ }
1677
+ };
1678
+ }
1679
+ async function deliverWithRetries({
1680
+ delays = RETRY_DELAYS_MS,
1681
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
1682
+ ...request
1683
+ }) {
1684
+ let attempts = 0;
1685
+ let last = { ok: false, status: null, code: "not_sent" };
1686
+ for (const delay of delays) {
1687
+ if (delay > 0) await sleep(delay);
1688
+ attempts += 1;
1689
+ try {
1690
+ const { status } = await deliverOnce(request);
1691
+ return { ok: true, status, code: null, attempts };
1692
+ } catch (err) {
1693
+ const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
1694
+ last = { ok: false, status: error.status, code: error.code };
1695
+ if (!error.retryable) break;
1696
+ }
1697
+ }
1698
+ return { ...last, attempts };
1699
+ }
1700
+ module.exports = {
1701
+ DEADLINE_MS,
1702
+ DELIVERY_HEADER,
1703
+ DeliveryError,
1704
+ EVENT_HEADER,
1705
+ RETRY_DELAYS_MS,
1706
+ SIGNATURE_HEADER,
1707
+ buildSignedRequest,
1708
+ deliverOnce,
1709
+ deliverWithRetries,
1710
+ isBlockedAddress,
1711
+ signPayload,
1712
+ verifySignature
1713
+ };
1714
+ }
1715
+ });
1716
+
1480
1717
  // server/src/utils/detection-settings.js
1481
1718
  var require_detection_settings = __commonJS({
1482
1719
  "server/src/utils/detection-settings.js"(exports, module) {
1483
1720
  "use strict";
1721
+ var net = __require("node:net");
1722
+ var { isBlockedAddress } = require_webhook_delivery();
1484
1723
  var WEBHOOK_EVENTS = Object.freeze([
1485
1724
  "login.success",
1486
1725
  "login.suspicious",
@@ -1565,6 +1804,8 @@ var require_detection_settings = __commonJS({
1565
1804
  if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
1566
1805
  return null;
1567
1806
  }
1807
+ const literal = host.replace(/^\[|\]$/g, "");
1808
+ if (net.isIP(literal) && isBlockedAddress(literal)) return null;
1568
1809
  return parsed.toString();
1569
1810
  }
1570
1811
  function normalizeEventList(value) {
@@ -1935,6 +2176,89 @@ var require_impersonation_rules = __commonJS({
1935
2176
  }
1936
2177
  });
1937
2178
 
2179
+ // server/src/utils/trusted-proxies.js
2180
+ var require_trusted_proxies = __commonJS({
2181
+ "server/src/utils/trusted-proxies.js"(exports, module) {
2182
+ "use strict";
2183
+ var { parseTrustedAddress } = require_policy_settings();
2184
+ var MAX_TRUSTED_PROXIES = 50;
2185
+ function normalizeTrustedProxies(value) {
2186
+ if (!Array.isArray(value)) return [];
2187
+ const out = [];
2188
+ for (const entry of value.slice(0, MAX_TRUSTED_PROXIES)) {
2189
+ const parsed = parseTrustedAddress(entry);
2190
+ if (parsed && !out.includes(parsed.text)) out.push(parsed.text);
2191
+ }
2192
+ return out;
2193
+ }
2194
+ function isLegacyTrustAll(value) {
2195
+ return value === true;
2196
+ }
2197
+ function validateTrustedProxies(value) {
2198
+ if (typeof value === "boolean") return { value: [], error: null, legacyTrue: value };
2199
+ if (!Array.isArray(value) || value.length > MAX_TRUSTED_PROXIES) {
2200
+ return {
2201
+ value: null,
2202
+ legacyTrue: false,
2203
+ error: {
2204
+ path: ["trustedProxies"],
2205
+ message: `trustedProxies must be a list of at most ${MAX_TRUSTED_PROXIES} IP addresses or CIDR ranges`
2206
+ }
2207
+ };
2208
+ }
2209
+ const parsed = value.map(parseTrustedAddress);
2210
+ const invalid = parsed.findIndex((entry) => entry === null);
2211
+ if (invalid !== -1) {
2212
+ return {
2213
+ value: null,
2214
+ legacyTrue: false,
2215
+ error: {
2216
+ path: ["trustedProxies", invalid],
2217
+ message: "Each trusted proxy must be an IP address or a CIDR range such as 10.0.0.0/8"
2218
+ }
2219
+ };
2220
+ }
2221
+ return {
2222
+ value: [...new Set(parsed.map((entry) => (
2223
+ /** @type {any} */
2224
+ entry.text
2225
+ )))],
2226
+ error: null,
2227
+ legacyTrue: false
2228
+ };
2229
+ }
2230
+ var LEGACY_WARNING = "[CONFIG] trustedProxies: true no longer makes the plugin read CF-Connecting-IP, True-Client-IP, X-Real-IP or the left-most X-Forwarded-For entry (a client can set them). The client IP now comes from Strapi's server.proxy settings (koa, ipHeader, maxIpsCount). To trust specific proxies instead, set trustedProxies to a list of their IP addresses or CIDR ranges.";
2231
+ async function migrateLegacyProxyTrust(strapi2, log) {
2232
+ const { withPluginStoreKey } = require_plugin_store();
2233
+ const { notifySettingsChanged } = require_settings_loader();
2234
+ const config = isLegacyTrustAll(
2235
+ strapi2.config.get("plugin::magic-sessionmanager")?.trustedProxies
2236
+ );
2237
+ const store = strapi2.store({ type: "plugin", name: "magic-sessionmanager" });
2238
+ let stored = isLegacyTrustAll((await store.get({ key: "settings" }))?.trustedProxies);
2239
+ if (stored) {
2240
+ stored = await withPluginStoreKey(strapi2, "settings", async (scoped) => {
2241
+ const value = await scoped.get({ key: "settings" });
2242
+ if (!value || !isLegacyTrustAll(value.trustedProxies)) return false;
2243
+ await scoped.set({ key: "settings", value: { ...value, trustedProxies: [] } });
2244
+ return true;
2245
+ });
2246
+ if (stored) await notifySettingsChanged(strapi2);
2247
+ }
2248
+ if (stored || config) log.warn(LEGACY_WARNING);
2249
+ return { stored, config };
2250
+ }
2251
+ module.exports = {
2252
+ LEGACY_WARNING,
2253
+ MAX_TRUSTED_PROXIES,
2254
+ isLegacyTrustAll,
2255
+ migrateLegacyProxyTrust,
2256
+ normalizeTrustedProxies,
2257
+ validateTrustedProxies
2258
+ };
2259
+ }
2260
+ });
2261
+
1938
2262
  // server/src/utils/settings-loader.js
1939
2263
  var require_settings_loader = __commonJS({
1940
2264
  "server/src/utils/settings-loader.js"(exports, module) {
@@ -1943,6 +2267,7 @@ var require_settings_loader = __commonJS({
1943
2267
  var { normalizePolicySettings } = require_policy_settings();
1944
2268
  var { normalizeDetectionSettings } = require_detection_settings();
1945
2269
  var { normalizeImpersonationSettings } = require_impersonation_rules();
2270
+ var { normalizeTrustedProxies } = require_trusted_proxies();
1946
2271
  var PLUGIN_ID = "magic-sessionmanager";
1947
2272
  var SETTINGS_KEY = "settings";
1948
2273
  var CACHE_TTL_MS = 30 * 1e3;
@@ -2072,7 +2397,8 @@ var require_settings_loader = __commonJS({
2072
2397
  out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 7, 730);
2073
2398
  }
2074
2399
  if (stored.trustedProxies !== void 0) {
2075
- out.trustedProxies = stored.trustedProxies;
2400
+ const proxies = normalizeTrustedProxies(stored.trustedProxies);
2401
+ if (proxies.length > 0) out.trustedProxies = proxies;
2076
2402
  }
2077
2403
  Object.assign(out, normalizePolicySettings(stored));
2078
2404
  Object.assign(out, normalizeDetectionSettings(stored));
@@ -2191,6 +2517,8 @@ var require_security_log_model = __commonJS({
2191
2517
  SETTINGS_UPDATED: "settings.updated",
2192
2518
  LOG_RETENTION_PURGED: "security-log.retention.purged",
2193
2519
  LOG_READ: "security-log.read",
2520
+ // 4.22.1: SESSION_ENCRYPTION_KEY shorter than 32 bytes, once per key.
2521
+ CONFIG_WEAK_KEY: "config.encryption-key.weak",
2194
2522
  // App users (Users & Permissions), 4.17.
2195
2523
  USER_SIGN_IN_FAILED: "user.sign-in.failed",
2196
2524
  USER_SIGN_IN_REFUSED: "user.sign-in.refused",
@@ -2254,7 +2582,8 @@ var require_security_log_model = __commonJS({
2254
2582
  var ADMIN_LOG_EVENTS = Object.freeze([
2255
2583
  SECURITY_EVENTS.SETTINGS_UPDATED,
2256
2584
  SECURITY_EVENTS.LOG_READ,
2257
- SECURITY_EVENTS.LOG_RETENTION_PURGED
2585
+ SECURITY_EVENTS.LOG_RETENTION_PURGED,
2586
+ SECURITY_EVENTS.CONFIG_WEAK_KEY
2258
2587
  ]);
2259
2588
  var SIGN_IN_FILTERS = Object.freeze({
2260
2589
  all: [...ADMIN_SIGN_IN_EVENTS, ...ADMIN_LOG_EVENTS],
@@ -2663,15 +2992,187 @@ var require_security_log_hardening = __commonJS({
2663
2992
  }
2664
2993
  });
2665
2994
 
2666
- // server/src/register.js
2667
- var require_register = __commonJS({
2668
- "server/src/register.js"(exports, module) {
2995
+ // server/src/utils/graphql-impersonation-guard.js
2996
+ var require_graphql_impersonation_guard = __commonJS({
2997
+ "server/src/utils/graphql-impersonation-guard.js"(exports, module) {
2669
2998
  "use strict";
2670
- var { createLogger } = require_logger();
2671
- var { createContentApiPermissionsLifecycle } = require_content_api_permissions();
2672
- var { isCallerRevocationScope } = require_block_revocation_scope();
2999
+ var { errors } = __require("@strapi/utils");
3000
+ var MARK = /* @__PURE__ */ Symbol.for("magic-sessionmanager.graphql-impersonation-guard");
3001
+ var MESSAGE = "Not allowed while impersonating";
3002
+ var REASON = "impersonation-mutation";
3003
+ function impersonationRefusal() {
3004
+ const error = new errors.ForbiddenError(MESSAGE, { reason: REASON });
3005
+ Object.defineProperty(error, "extensions", {
3006
+ value: {
3007
+ code: "FORBIDDEN",
3008
+ http: { status: 403 },
3009
+ error: { name: "ForbiddenError", message: MESSAGE, details: { reason: REASON } }
3010
+ },
3011
+ enumerable: false
3012
+ });
3013
+ return error;
3014
+ }
3015
+ function impersonationOf(contextValue) {
3016
+ const mark = contextValue?.koaContext?.state?.magicImpersonation ?? contextValue?.state?.magicImpersonation;
3017
+ return mark && typeof mark === "object" && typeof mark.id === "string" ? mark : null;
3018
+ }
3019
+ function createImpersonationApolloPlugin(strapi2) {
3020
+ return {
3021
+ [MARK]: true,
3022
+ async requestDidStart() {
3023
+ return {
3024
+ /**
3025
+ * @param {any} requestContext Apollo request context.
3026
+ * @returns {Promise<void>}
3027
+ * @throws {Error} ForbiddenError (HTTP 403, code FORBIDDEN) for a mutation while impersonating.
3028
+ */
3029
+ async didResolveOperation(requestContext) {
3030
+ if (requestContext?.operation?.operation !== "mutation") return;
3031
+ const impersonation = impersonationOf(requestContext.contextValue);
3032
+ if (!impersonation) return;
3033
+ try {
3034
+ strapi2.plugin("magic-sessionmanager").service("impersonation").recordRefusedCall(impersonation, "mutation");
3035
+ } catch {
3036
+ }
3037
+ throw impersonationRefusal();
3038
+ }
3039
+ };
3040
+ }
3041
+ };
3042
+ }
3043
+ function installGraphqlImpersonationGuard(strapi2, log) {
3044
+ let graphql;
3045
+ try {
3046
+ graphql = strapi2.plugin("graphql") || null;
3047
+ } catch {
3048
+ graphql = null;
3049
+ }
3050
+ if (!graphql) return false;
3051
+ if (typeof strapi2.config?.get !== "function" || typeof strapi2.config?.set !== "function") {
3052
+ return false;
3053
+ }
3054
+ try {
3055
+ const key = "plugin::graphql.apolloServer";
3056
+ const current = strapi2.config.get(key);
3057
+ const server = current && typeof current === "object" ? current : {};
3058
+ const plugins = Array.isArray(server.plugins) ? server.plugins : [];
3059
+ if (plugins.some((plugin) => plugin && plugin[MARK])) return true;
3060
+ strapi2.config.set(key, {
3061
+ ...server,
3062
+ plugins: [...plugins, createImpersonationApolloPlugin(strapi2)]
3063
+ });
3064
+ } catch (err) {
3065
+ log?.warn?.("[IMPERSONATION] GraphQL guard could not be installed:", err?.name || "Error");
3066
+ return false;
3067
+ }
3068
+ log?.info?.("[IMPERSONATION] GraphQL mutations are refused while impersonating");
3069
+ return true;
3070
+ }
3071
+ module.exports = {
3072
+ createImpersonationApolloPlugin,
3073
+ impersonationRefusal,
3074
+ installGraphqlImpersonationGuard
3075
+ };
3076
+ }
3077
+ });
3078
+
3079
+ // server/src/utils/auth-controller-guard.js
3080
+ var require_auth_controller_guard = __commonJS({
3081
+ "server/src/utils/auth-controller-guard.js"(exports, module) {
3082
+ "use strict";
3083
+ var WRAPPED = /* @__PURE__ */ Symbol.for("magic-sessionmanager.auth-controller.wrapped");
3084
+ var GUARDED_ACTIONS = Object.freeze({
3085
+ callback: "callback",
3086
+ register: "newSession",
3087
+ resetPassword: "newSession",
3088
+ emailConfirmation: "newSession"
3089
+ });
3090
+ var handlersByStrapi = /* @__PURE__ */ new WeakMap();
3091
+ function installAuthControllerGuard(strapi2, log) {
3092
+ let controller;
3093
+ try {
3094
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3095
+ } catch {
3096
+ controller = null;
3097
+ }
3098
+ if (!controller || typeof controller !== "object") {
3099
+ log?.warn?.(
3100
+ "[AUTH] Users & Permissions auth controller not found; sign-in checks use paths only"
3101
+ );
3102
+ return [];
3103
+ }
3104
+ const wrapped = [];
3105
+ for (const [action, kind] of Object.entries(GUARDED_ACTIONS)) {
3106
+ const original = controller[action];
3107
+ if (typeof original !== "function") continue;
3108
+ if (original[WRAPPED]) {
3109
+ wrapped.push(action);
3110
+ continue;
3111
+ }
3112
+ const guarded = async function magicSessionAuthGuard(ctx, ...rest) {
3113
+ const run = () => original.call(this, ctx, ...rest);
3114
+ const handlers = handlersByStrapi.get(strapi2);
3115
+ if (!handlers || typeof handlers[kind] !== "function") return run();
3116
+ return handlers[kind](ctx, run);
3117
+ };
3118
+ Object.defineProperty(guarded, WRAPPED, { value: original });
3119
+ controller[action] = guarded;
3120
+ wrapped.push(action);
3121
+ }
3122
+ return wrapped;
3123
+ }
3124
+ function setAuthControllerHandlers(strapi2, handlers) {
3125
+ if (handlers) handlersByStrapi.set(strapi2, handlers);
3126
+ else handlersByStrapi.delete(strapi2);
3127
+ }
3128
+ function uninstallAuthControllerGuard(strapi2) {
3129
+ setAuthControllerHandlers(strapi2, null);
3130
+ let controller;
3131
+ try {
3132
+ controller = strapi2.plugin("users-permissions")?.controller("auth");
3133
+ } catch {
3134
+ return;
3135
+ }
3136
+ if (!controller) return;
3137
+ for (const action of Object.keys(GUARDED_ACTIONS)) {
3138
+ const original = controller[action]?.[WRAPPED];
3139
+ if (typeof original === "function") controller[action] = original;
3140
+ }
3141
+ }
3142
+ var INVALID_CREDENTIALS_MESSAGE = "Invalid identifier or password";
3143
+ function classifyCallbackOutcome(thrown, ctx) {
3144
+ if (thrown) {
3145
+ const error = (
3146
+ /** @type {any} */
3147
+ thrown
3148
+ );
3149
+ return error?.name === "ValidationError" && error?.message === INVALID_CREDENTIALS_MESSAGE ? "failure" : "neutral";
3150
+ }
3151
+ const body = ctx?.body;
3152
+ return body && typeof body === "object" && body.jwt ? "success" : "neutral";
3153
+ }
3154
+ module.exports = {
3155
+ GUARDED_ACTIONS,
3156
+ INVALID_CREDENTIALS_MESSAGE,
3157
+ classifyCallbackOutcome,
3158
+ installAuthControllerGuard,
3159
+ setAuthControllerHandlers,
3160
+ uninstallAuthControllerGuard
3161
+ };
3162
+ }
3163
+ });
3164
+
3165
+ // server/src/register.js
3166
+ var require_register = __commonJS({
3167
+ "server/src/register.js"(exports, module) {
3168
+ "use strict";
3169
+ var { createLogger } = require_logger();
3170
+ var { createContentApiPermissionsLifecycle } = require_content_api_permissions();
3171
+ var { isCallerRevocationScope } = require_block_revocation_scope();
2673
3172
  var { checkStrapiVersion } = require_strapi_version();
2674
3173
  var { disableGraphqlShadowCrud } = require_security_log_hardening();
3174
+ var { installGraphqlImpersonationGuard } = require_graphql_impersonation_guard();
3175
+ var { installAuthControllerGuard } = require_auth_controller_guard();
2675
3176
  var USER_UID = "plugin::users-permissions.user";
2676
3177
  module.exports = async ({ strapi: strapi2 }) => {
2677
3178
  const log = createLogger(strapi2);
@@ -2716,6 +3217,17 @@ var require_register = __commonJS({
2716
3217
  subCategory: "Admin panel",
2717
3218
  pluginName: "magic-sessionmanager"
2718
3219
  },
3220
+ // App-user security activity (4.22): failed and refused sign-ins,
3221
+ // lockouts, new devices, impossible travel, "This wasn't me", data
3222
+ // exports and impersonations of Users & Permissions accounts, with IP
3223
+ // addresses. Separate from plugin access because it shows personal data.
3224
+ {
3225
+ section: "plugins",
3226
+ displayName: "View app-user security activity",
3227
+ uid: "user-activity.read",
3228
+ subCategory: "General",
3229
+ pluginName: "magic-sessionmanager"
3230
+ },
2719
3231
  // Protected settings (4.17): IP location lookup (whether and where IP
2720
3232
  // addresses are sent), team notification webhooks (the URLs are
2721
3233
  // secrets) and the security log. The other settings stay on `access`.
@@ -2759,6 +3271,8 @@ var require_register = __commonJS({
2759
3271
  }
2760
3272
  ]);
2761
3273
  disableGraphqlShadowCrud(strapi2, log);
3274
+ installGraphqlImpersonationGuard(strapi2, log);
3275
+ installAuthControllerGuard(strapi2, log);
2762
3276
  try {
2763
3277
  strapi2.db.lifecycles.subscribe(createContentApiPermissionsLifecycle(strapi2));
2764
3278
  } catch (err) {
@@ -2834,42 +3348,69 @@ var require_register = __commonJS({
2834
3348
  var require_getClientIp = __commonJS({
2835
3349
  "server/src/utils/getClientIp.js"(exports, module) {
2836
3350
  "use strict";
2837
- function isProxyTrusted(ctx) {
2838
- try {
2839
- const app = ctx?.app;
2840
- if (app && app.proxy === true) return true;
2841
- } catch {
3351
+ var net = __require("node:net");
3352
+ var { isTrustedAddress } = require_policy_settings();
3353
+ var { normalizeTrustedProxies } = require_trusted_proxies();
3354
+ var MAX_FORWARDED_LENGTH = 2048;
3355
+ var MAX_FORWARDED_HOPS = 20;
3356
+ var cleanIp = (ip) => {
3357
+ if (!ip) return "unknown";
3358
+ let value = String(ip).trim();
3359
+ if (value.startsWith("[")) {
3360
+ const bracketEnd = value.indexOf("]");
3361
+ if (bracketEnd !== -1) {
3362
+ value = value.substring(1, bracketEnd);
3363
+ }
2842
3364
  }
3365
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.substring(7))) {
3366
+ value = value.substring(7);
3367
+ }
3368
+ if (value.includes(".") && value.includes(":") && value.indexOf(":") === value.lastIndexOf(":")) {
3369
+ value = value.split(":")[0];
3370
+ }
3371
+ return value || "unknown";
3372
+ };
3373
+ function trustedProxyList(ctx) {
3374
+ const fromSettings = ctx?.state?.__magicSessionSettings?.trustedProxies;
3375
+ if (fromSettings !== void 0) return normalizeTrustedProxies(fromSettings);
2843
3376
  try {
2844
- const config = ctx?.state?.__magicSessionSettings || ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager") || {};
2845
- const trusted = config.trustedProxies;
2846
- if (trusted === true) return true;
2847
- if (Array.isArray(trusted) && trusted.length > 0) return true;
3377
+ const config = ctx?.app?.context?.strapi?.config?.get?.("plugin::magic-sessionmanager");
3378
+ return normalizeTrustedProxies(config?.trustedProxies);
2848
3379
  } catch {
3380
+ return [];
2849
3381
  }
2850
- return false;
3382
+ }
3383
+ function socketAddress(ctx) {
3384
+ const raw = ctx?.req?.socket?.remoteAddress ?? ctx?.request?.socket?.remoteAddress;
3385
+ const cleaned = cleanIp(raw);
3386
+ return cleaned !== "unknown" && net.isIP(cleaned) ? cleaned : null;
3387
+ }
3388
+ function rightMostUntrustedHop(ctx, proxies) {
3389
+ const headers = ctx?.request?.headers || ctx?.request?.header || {};
3390
+ let header = headers["x-forwarded-for"];
3391
+ if (Array.isArray(header)) header = header.join(",");
3392
+ if (typeof header !== "string" || !header) return null;
3393
+ const hops = header.slice(0, MAX_FORWARDED_LENGTH).split(",").map((hop) => cleanIp(hop)).slice(-MAX_FORWARDED_HOPS);
3394
+ let lastValid = null;
3395
+ for (let index = hops.length - 1; index >= 0; index--) {
3396
+ const hop = hops[index];
3397
+ if (!net.isIP(hop)) return lastValid;
3398
+ if (!isTrustedAddress(proxies, hop)) return hop;
3399
+ lastValid = hop;
3400
+ }
3401
+ return lastValid;
2851
3402
  }
2852
3403
  var getClientIp = (ctx) => {
2853
3404
  try {
2854
- const headers = ctx.request.headers || ctx.request.header || {};
2855
- const trusted = isProxyTrusted(ctx);
2856
- if (trusted) {
2857
- if (headers["cf-connecting-ip"]) return cleanIp(headers["cf-connecting-ip"]);
2858
- if (headers["true-client-ip"]) return cleanIp(headers["true-client-ip"]);
2859
- if (headers["x-real-ip"]) return cleanIp(headers["x-real-ip"]);
2860
- if (headers["x-forwarded-for"]) {
2861
- const forwardedIps = headers["x-forwarded-for"].split(",");
2862
- const clientIp = forwardedIps[0].trim();
2863
- if (clientIp) return cleanIp(clientIp);
2864
- }
2865
- if (headers["x-client-ip"]) return cleanIp(headers["x-client-ip"]);
2866
- if (headers["x-cluster-client-ip"]) return cleanIp(headers["x-cluster-client-ip"]);
2867
- if (headers["forwarded"]) {
2868
- const match = headers["forwarded"].match(/for=([^;,\s]+)/);
2869
- if (match && match[1]) return cleanIp(match[1].replace(/"/g, ""));
2870
- }
2871
- }
2872
- if (ctx.request.ip) return cleanIp(ctx.request.ip);
3405
+ const proxies = trustedProxyList(ctx);
3406
+ if (proxies.length > 0) {
3407
+ const peer = socketAddress(ctx);
3408
+ if (peer && isTrustedAddress(proxies, peer)) {
3409
+ return rightMostUntrustedHop(ctx, proxies) || peer;
3410
+ }
3411
+ if (peer) return peer;
3412
+ }
3413
+ if (ctx?.request?.ip) return cleanIp(ctx.request.ip);
2873
3414
  return "unknown";
2874
3415
  } catch (error) {
2875
3416
  if (ctx?.app?.context?.strapi?.log?.debug) {
@@ -2881,24 +3422,8 @@ var require_getClientIp = __commonJS({
2881
3422
  return "unknown";
2882
3423
  }
2883
3424
  };
2884
- var cleanIp = (ip) => {
2885
- if (!ip) return "unknown";
2886
- ip = String(ip).trim();
2887
- if (ip.startsWith("[")) {
2888
- const bracketEnd = ip.indexOf("]");
2889
- if (bracketEnd !== -1) {
2890
- ip = ip.substring(1, bracketEnd);
2891
- }
2892
- }
2893
- if (ip.startsWith("::ffff:")) {
2894
- ip = ip.substring(7);
2895
- }
2896
- if (ip.includes(".") && ip.includes(":") && ip.indexOf(":") === ip.lastIndexOf(":")) {
2897
- ip = ip.split(":")[0];
2898
- }
2899
- return ip || "unknown";
2900
- };
2901
3425
  module.exports = getClientIp;
3426
+ module.exports.cleanIp = cleanIp;
2902
3427
  }
2903
3428
  });
2904
3429
 
@@ -2911,10 +3436,22 @@ var require_encryption = __commonJS({
2911
3436
  var IV_LENGTH = 16;
2912
3437
  var AUTH_TAG_LENGTH = 16;
2913
3438
  var warnedMissingKey = false;
3439
+ var warnedShortKey = false;
3440
+ var MIN_KEY_BYTES = 32;
3441
+ function isEncryptionKeyShort() {
3442
+ const envKey = process.env.SESSION_ENCRYPTION_KEY;
3443
+ return typeof envKey === "string" && envKey.length > 0 ? Buffer.byteLength(envKey, "utf8") < MIN_KEY_BYTES : false;
3444
+ }
2914
3445
  var isProduction = () => process.env.NODE_ENV === "production";
2915
3446
  function getEncryptionKey() {
2916
3447
  const envKey = process.env.SESSION_ENCRYPTION_KEY;
2917
3448
  if (envKey && envKey.length > 0) {
3449
+ if (!warnedShortKey && isEncryptionKeyShort()) {
3450
+ warnedShortKey = true;
3451
+ console.warn(
3452
+ `[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).`
3453
+ );
3454
+ }
2918
3455
  return crypto.createHash("sha256").update(envKey).digest();
2919
3456
  }
2920
3457
  if (isProduction()) {
@@ -2998,6 +3535,8 @@ var require_encryption = __commonJS({
2998
3535
  );
2999
3536
  }
3000
3537
  module.exports = {
3538
+ MIN_KEY_BYTES,
3539
+ isEncryptionKeyShort,
3001
3540
  derivePurposeKey,
3002
3541
  getEncryptionKeyCheck,
3003
3542
  encryptToken,
@@ -3547,7 +4086,6 @@ var require_auth_routes = __commonJS({
3547
4086
  "POST /api/magic-link/login-totp"
3548
4087
  ]);
3549
4088
  var FAILED_LOGIN_ROUTES = /* @__PURE__ */ new Set([
3550
- "POST /api/auth/local",
3551
4089
  "POST /api/magic-link/login-totp",
3552
4090
  "POST /api/magic-link/otp/verify",
3553
4091
  "POST /api/magic-link/verify-mfa-totp"
@@ -3590,18 +4128,24 @@ var require_auth_routes = __commonJS({
3590
4128
  if (!trimmed) return DEFAULT_API_PREFIX;
3591
4129
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
3592
4130
  }
4131
+ function normalizeRequestPath(path) {
4132
+ const value = path.toLowerCase().replace(/\/{2,}/g, "/");
4133
+ return value.length > 1 ? value.replace(/\/+$/, "") || "/" : value;
4134
+ }
3593
4135
  function toCanonicalApiPath(path, prefix) {
3594
4136
  if (typeof path !== "string") return null;
3595
- const normalized = normalizeApiPrefix(prefix);
3596
- if (normalized === DEFAULT_API_PREFIX) return path;
3597
- if (path === normalized) return DEFAULT_API_PREFIX;
3598
- if (path.startsWith(`${normalized}/`)) {
3599
- return `${DEFAULT_API_PREFIX}${path.slice(normalized.length)}`;
4137
+ const normalizedPath = normalizeRequestPath(path);
4138
+ const normalized = normalizeApiPrefix(prefix).toLowerCase();
4139
+ if (normalized === DEFAULT_API_PREFIX) return normalizedPath;
4140
+ if (normalizedPath === normalized) return DEFAULT_API_PREFIX;
4141
+ if (normalizedPath.startsWith(`${normalized}/`)) {
4142
+ return `${DEFAULT_API_PREFIX}${normalizedPath.slice(normalized.length)}`;
3600
4143
  }
3601
4144
  return null;
3602
4145
  }
3603
4146
  module.exports = {
3604
4147
  normalizeApiPrefix,
4148
+ normalizeRequestPath,
3605
4149
  toCanonicalApiPath,
3606
4150
  classifyJwtIssuingRequest,
3607
4151
  isFailedLoginTrackedPath,
@@ -4261,6 +4805,15 @@ var require_admin_request_info = __commonJS({
4261
4805
  }
4262
4806
  return null;
4263
4807
  }
4808
+ function ipBucket(ip) {
4809
+ const value = normalizeIp(typeof ip === "string" ? ip : "");
4810
+ if (!value) return null;
4811
+ if (net.isIPv4(value)) return value;
4812
+ if (net.isIPv6(value)) {
4813
+ return `${ipv6Groups(value).slice(0, 4).map((group) => group.toString(16)).join(":")}::/64`;
4814
+ }
4815
+ return null;
4816
+ }
4264
4817
  function getRequestUserAgent(ctx) {
4265
4818
  const value = ctx?.request?.headers?.["user-agent"];
4266
4819
  if (typeof value !== "string" || !value.trim()) return null;
@@ -4287,6 +4840,7 @@ var require_admin_request_info = __commonJS({
4287
4840
  module.exports = {
4288
4841
  MAX_USER_AGENT_LENGTH,
4289
4842
  anonymizeIp,
4843
+ ipBucket,
4290
4844
  describeUserAgent,
4291
4845
  getRequestIp,
4292
4846
  getSocketIp,
@@ -4587,6 +5141,7 @@ var require_login_lockout = __commonJS({
4587
5141
  "use strict";
4588
5142
  var { hashedKey } = require_coordination();
4589
5143
  var { isTrustedAddress } = require_policy_settings();
5144
+ var { ipBucket } = require_admin_request_info();
4590
5145
  var LOCK_PREFIX = "lock:";
4591
5146
  var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
4592
5147
  var MAX_LISTED_LOCKS = 200;
@@ -4596,7 +5151,7 @@ var require_login_lockout = __commonJS({
4596
5151
  if (!value || value.length > 254) return null;
4597
5152
  return value;
4598
5153
  }
4599
- var ipKey = (ip) => hashedKey("lf", ip);
5154
+ var ipKey = (ip) => hashedKey("lf", ipBucket(ip) || ip);
4600
5155
  var accountKey = (identifier) => hashedKey("la", identifier);
4601
5156
  function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
4602
5157
  const remainingSeconds = async (key) => {
@@ -4616,15 +5171,18 @@ var require_login_lockout = __commonJS({
4616
5171
  * Checks the locks and counts the attempt before the password check.
4617
5172
  *
4618
5173
  * @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
4619
- * accountMax: number}} input Client IP, normalised identifier, policy and the
4620
- * account threshold for this account's role.
5174
+ * accountMax: number, accountExempt?: boolean}} input Client IP, normalised
5175
+ * identifier, policy, the account threshold for this account's role, and
5176
+ * whether the request comes from a device the account is known to use.
4621
5177
  * @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
4622
5178
  * lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
4623
5179
  * @sideeffect Increments the shared counters.
4624
5180
  */
4625
- async reserve({ ip, identifier, policy, accountMax }) {
4626
- const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
4627
- const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
5181
+ async reserve({ ip, identifier, policy, accountMax, accountExempt = false }) {
5182
+ const knownIp = typeof ip === "string" && !!ip && ip !== "unknown";
5183
+ const trusted = knownIp && isTrustedAddress(policy.trusted, ip);
5184
+ const countIp = policy.ipMax > 0 && knownIp && !trusted;
5185
+ const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier && !trusted && accountExempt !== true;
4628
5186
  const reservation = {
4629
5187
  ipKey: countIp ? ipKey(
4630
5188
  /** @type {string} */
@@ -4677,10 +5235,8 @@ var require_login_lockout = __commonJS({
4677
5235
  */
4678
5236
  async settle(reservation, result, { policy, accountMax, display = {} }) {
4679
5237
  if (result === "success") {
4680
- for (const key of [reservation.ipKey, reservation.accountKey]) {
4681
- if (!key) continue;
4682
- await coordinator.clear(key);
4683
- }
5238
+ if (reservation.ipKey) await coordinator.release(reservation.ipKey);
5239
+ if (reservation.accountKey) await coordinator.clear(reservation.accountKey);
4684
5240
  return [];
4685
5241
  }
4686
5242
  if (result !== "failure") {
@@ -5144,6 +5700,15 @@ var require_sign_in_signals = __commonJS({
5144
5700
  });
5145
5701
  return Array.isArray(rows) ? rows : [];
5146
5702
  }
5703
+ async function isRecognizedDevice(strapi2, userDocumentId, { userAgent, deviceId }) {
5704
+ if (typeof userDocumentId !== "string" || !userDocumentId) return false;
5705
+ if (typeof deviceId !== "string" || !deviceId) return false;
5706
+ const deviceKey = deviceKeyOf(userAgent || "", deviceId);
5707
+ const count = await strapi2.documents(SESSION_UID).count({
5708
+ filters: { user: { documentId: userDocumentId }, deviceKey }
5709
+ });
5710
+ return Number(count) > 0;
5711
+ }
5147
5712
  function isNewDevice(previous, { deviceKey, userAgent }) {
5148
5713
  if (previous.length === 0) return false;
5149
5714
  if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
@@ -5172,7 +5737,7 @@ var require_sign_in_signals = __commonJS({
5172
5737
  const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
5173
5738
  if (!token) return null;
5174
5739
  const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
5175
- return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
5740
+ return `${base}${prefix}/magic-sessionmanager/not-me#token=${encodeURIComponent(token)}`;
5176
5741
  }
5177
5742
  async function runSignInSignals({
5178
5743
  strapi: strapi2,
@@ -5261,6 +5826,7 @@ var require_sign_in_signals = __commonJS({
5261
5826
  return outcome;
5262
5827
  }
5263
5828
  module.exports = {
5829
+ isRecognizedDevice,
5264
5830
  notMeUrl,
5265
5831
  runSignInSignals,
5266
5832
  deviceFamilies,
@@ -5365,7 +5931,11 @@ var require_impersonation_guard = __commonJS({
5365
5931
  `impersonation-${restricted}`
5366
5932
  );
5367
5933
  }
5368
- ctx.state.magicImpersonation = { id: impersonation.id, actorId: impersonation.actorId };
5934
+ ctx.state.magicImpersonation = {
5935
+ id: impersonation.id,
5936
+ actorId: impersonation.actorId,
5937
+ targetId: impersonation.targetId || null
5938
+ };
5369
5939
  try {
5370
5940
  await next();
5371
5941
  } finally {
@@ -9459,7 +10029,13 @@ var require_bootstrap = __commonJS({
9459
10029
  "server/src/bootstrap.js"(exports, module) {
9460
10030
  "use strict";
9461
10031
  var getClientIp = require_getClientIp();
9462
- var { encryptToken, getEncryptionKeyCheck, hashToken } = require_encryption();
10032
+ var {
10033
+ MIN_KEY_BYTES,
10034
+ encryptToken,
10035
+ getEncryptionKeyCheck,
10036
+ hashToken,
10037
+ isEncryptionKeyShort
10038
+ } = require_encryption();
9463
10039
  var { createLogger } = require_logger();
9464
10040
  var { resolveUserDocumentId } = require_resolve_user();
9465
10041
  var { getPluginSettings, getSessionCreationGraceMs } = require_settings_loader();
@@ -9470,7 +10046,12 @@ var require_bootstrap = __commonJS({
9470
10046
  var { REVOCATION_UID } = require_session_revocation();
9471
10047
  var { getNativeSessionManager } = require_native_session_manager();
9472
10048
  var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
9473
- var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
10049
+ var {
10050
+ getCoordinator,
10051
+ hashedKey,
10052
+ initCoordination,
10053
+ LockTimeoutError
10054
+ } = require_coordination();
9474
10055
  var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
9475
10056
  var {
9476
10057
  normalizeApiPrefix,
@@ -9519,8 +10100,20 @@ var require_bootstrap = __commonJS({
9519
10100
  } = require_sign_in_policies();
9520
10101
  var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
9521
10102
  var { applyUpgradeDefaults } = require_upgrade_defaults();
9522
- var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
10103
+ var {
10104
+ deviceKeyOf,
10105
+ isRecognizedDevice,
10106
+ requestDeviceId,
10107
+ runSignInSignals
10108
+ } = require_sign_in_signals();
9523
10109
  var { anonymizeIp, normalizeIp } = require_admin_request_info();
10110
+ var { migrateLegacyProxyTrust } = require_trusted_proxies();
10111
+ var { errors: utilsErrors } = __require("@strapi/utils");
10112
+ var {
10113
+ classifyCallbackOutcome,
10114
+ setAuthControllerHandlers
10115
+ } = require_auth_controller_guard();
10116
+ var { normalizePath } = require_impersonation_rules();
9524
10117
  var SESSION_UID = "plugin::magic-sessionmanager.session";
9525
10118
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
9526
10119
  var JOB_LEASES = Object.freeze({
@@ -9563,6 +10156,12 @@ var require_bootstrap = __commonJS({
9563
10156
  try {
9564
10157
  const coordinator = await initCoordination(strapi2, log);
9565
10158
  await checkEncryptionKeyConsistency(strapi2, log);
10159
+ await warnShortEncryptionKey(strapi2, log);
10160
+ try {
10161
+ await migrateLegacyProxyTrust(strapi2, log);
10162
+ } catch (err) {
10163
+ log.warn("[CONFIG] trustedProxies could not be migrated:", err?.name || "Error");
10164
+ }
9566
10165
  try {
9567
10166
  await applyUpgradeDefaults(strapi2, log);
9568
10167
  } catch (err) {
@@ -9676,8 +10275,9 @@ var require_bootstrap = __commonJS({
9676
10275
  impersonationSweep.unref?.();
9677
10276
  strapi2.sessionManagerIntervals.impersonationSweep = impersonationSweep;
9678
10277
  strapi2.plugin("magic-sessionmanager").service("impersonation").checkHandoffSetup();
9679
- mountPreLoginGeoGuard({ strapi: strapi2, log });
9680
- mountFailedLoginLockout({ strapi: strapi2, log });
10278
+ const geoCheck = mountPreLoginGeoGuard({ strapi: strapi2, log });
10279
+ const lockoutGuard = mountFailedLoginLockout({ strapi: strapi2, log });
10280
+ connectAuthControllerGuard({ strapi: strapi2, geoCheck, lockoutGuard });
9681
10281
  mountLogoutRoute({ strapi: strapi2, log, sessionService });
9682
10282
  mountLoginInterceptor({ strapi: strapi2, log, sessionService });
9683
10283
  mountRefreshTokenInterceptor({ strapi: strapi2, log, sessionService });
@@ -9735,6 +10335,28 @@ var require_bootstrap = __commonJS({
9735
10335
  log.debug("[CONFIG] Encryption key consistency check skipped:", err?.name || "Error");
9736
10336
  }
9737
10337
  }
10338
+ async function warnShortEncryptionKey(strapi2, log) {
10339
+ if (!isEncryptionKeyShort()) return false;
10340
+ log.error(
10341
+ `[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).`
10342
+ );
10343
+ try {
10344
+ const coordinator = getCoordinator(strapi2);
10345
+ const check = getEncryptionKeyCheck();
10346
+ const marker = "instance:weak-encryption-key-recorded";
10347
+ if (await coordinator.cacheGet(marker) === check) return true;
10348
+ const recorded = strapi2.plugin("magic-sessionmanager").service("security-log").record({
10349
+ event: SECURITY_EVENTS.CONFIG_WEAK_KEY,
10350
+ actorType: "system",
10351
+ targetType: "config",
10352
+ meta: { minBytes: MIN_KEY_BYTES }
10353
+ });
10354
+ if (recorded !== false) await coordinator.cacheSet(marker, check, Infinity);
10355
+ } catch (err) {
10356
+ log.debug("[SECURITY] Weak key event not recorded:", err?.name || "Error");
10357
+ }
10358
+ return true;
10359
+ }
9738
10360
  function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
9739
10361
  const shouldRecordRefusal = createRefusalDedup();
9740
10362
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
@@ -9757,19 +10379,14 @@ var require_bootstrap = __commonJS({
9757
10379
  meta: { reason }
9758
10380
  });
9759
10381
  };
9760
- strapi2.server.use(async (ctx, next) => {
9761
- if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
9762
- return next();
9763
- }
10382
+ const check = async (ctx) => {
10383
+ if (ctx.state?.__magicSessionGeoChecked) return null;
10384
+ if (ctx.state) ctx.state.__magicSessionGeoChecked = true;
9764
10385
  const settings = await getRequestSettings(strapi2, ctx);
9765
10386
  const needsGeoCheck = settings.blockSuspiciousSessions || settings.enableGeofencing || settings.enableGeolocation;
9766
- if (!needsGeoCheck) {
9767
- return next();
9768
- }
10387
+ if (!needsGeoCheck) return null;
9769
10388
  const ip = getClientIp(ctx);
9770
- if (!ip || ip === "unknown") {
9771
- return next();
9772
- }
10389
+ if (!ip || ip === "unknown") return null;
9773
10390
  try {
9774
10391
  const geolocationService = strapi2.plugin("magic-sessionmanager").service("geolocation");
9775
10392
  const geoData = await geolocationService.getIpInfo(ip);
@@ -9777,16 +10394,11 @@ var require_bootstrap = __commonJS({
9777
10394
  if (decision.blocked) {
9778
10395
  log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
9779
10396
  await recordRefusal(ctx, settings, ip, decision.reason);
9780
- ctx.status = 403;
9781
- ctx.body = {
9782
- error: {
9783
- status: 403,
9784
- name: "ForbiddenError",
9785
- message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
9786
- }
9787
- };
9788
10397
  ctx.state.__magicSessionGeoData = geoData;
9789
- return;
10398
+ return {
10399
+ status: 403,
10400
+ message: decision.reason?.startsWith("geo_lookup_unavailable:") ? "Login temporarily unavailable. Please contact support." : "Login blocked for security reasons. Please contact support."
10401
+ };
9790
10402
  }
9791
10403
  if (decision.status === "ok") {
9792
10404
  ctx.state.__magicSessionGeoData = geoData;
@@ -9796,21 +10408,31 @@ var require_bootstrap = __commonJS({
9796
10408
  if (failureDecision.blocked) {
9797
10409
  log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
9798
10410
  await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
9799
- ctx.status = 403;
9800
- ctx.body = {
9801
- error: {
9802
- status: 403,
9803
- name: "ForbiddenError",
9804
- message: "Login temporarily unavailable. Please contact support."
9805
- }
10411
+ return {
10412
+ status: 403,
10413
+ message: "Login temporarily unavailable. Please contact support."
9806
10414
  };
9807
- return;
9808
10415
  }
9809
10416
  log.debug("Pre-login geo guard error (allowing by configured policy):", err?.name || "Error");
9810
10417
  }
10418
+ return null;
10419
+ };
10420
+ strapi2.server.use(async (ctx, next) => {
10421
+ if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
10422
+ return next();
10423
+ }
10424
+ const refusal = await check(ctx);
10425
+ if (refusal) {
10426
+ ctx.status = refusal.status;
10427
+ ctx.body = {
10428
+ error: { status: refusal.status, name: "ForbiddenError", message: refusal.message }
10429
+ };
10430
+ return;
10431
+ }
9811
10432
  await next();
9812
10433
  });
9813
10434
  log.info("[SUCCESS] Pre-login geo guard mounted");
10435
+ return check;
9814
10436
  }
9815
10437
  function mountLogoutRoute({ strapi: strapi2, log, sessionService }) {
9816
10438
  const logoutPath = `${normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"))}/auth/logout`;
@@ -9996,16 +10618,16 @@ var require_bootstrap = __commonJS({
9996
10618
  }
9997
10619
  function mountFailedLoginLockout({ strapi: strapi2, log }) {
9998
10620
  const lockout = createLoginLockout(getCoordinator(strapi2));
10621
+ const coordinator = getCoordinator(strapi2);
9999
10622
  const shouldRecordRefusal = createRefusalDedup();
10000
10623
  const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
10001
10624
  const underAddressCap = createAddressCap();
10002
10625
  const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
10003
- strapi2.server.use(async (ctx, next) => {
10004
- if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
10626
+ const guard = async (ctx, run, classify, refuse) => {
10005
10627
  const settings = await getRequestSettings(strapi2, ctx);
10006
10628
  const policy = resolveLockoutPolicy(settings);
10007
10629
  const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
10008
- if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
10630
+ if (policy.ipMax <= 0 && !accountPossible && !policy.record) return run();
10009
10631
  const rawIp = getClientIp(ctx);
10010
10632
  const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
10011
10633
  const identifier = readSignInIdentifier(ctx);
@@ -10026,6 +10648,15 @@ var require_bootstrap = __commonJS({
10026
10648
  };
10027
10649
  if (policy.accountMaxByRole) await loadAccount();
10028
10650
  const accountMax = accountThresholdFor(settings, account?.role || null);
10651
+ let accountExempt = false;
10652
+ const deviceId = requestDeviceId(ctx);
10653
+ if (accountMax > 0 && identifier && deviceId) {
10654
+ await loadAccount();
10655
+ accountExempt = await isRecognizedDevice(strapi2, account?.documentId || null, {
10656
+ userAgent,
10657
+ deviceId
10658
+ }).catch(() => false);
10659
+ }
10029
10660
  const event = (name, meta) => {
10030
10661
  const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
10031
10662
  if (signInFamily && !policy.record) return false;
@@ -10053,7 +10684,7 @@ var require_bootstrap = __commonJS({
10053
10684
  };
10054
10685
  let decision;
10055
10686
  try {
10056
- decision = await lockout.reserve({ ip, identifier, policy, accountMax });
10687
+ decision = await lockout.reserve({ ip, identifier, policy, accountMax, accountExempt });
10057
10688
  } catch (err) {
10058
10689
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10059
10690
  decision = {
@@ -10064,47 +10695,38 @@ var require_bootstrap = __commonJS({
10064
10695
  };
10065
10696
  }
10066
10697
  if (decision.outcome === "locked") {
10067
- ctx.set("Retry-After", String(decision.retryAfter));
10068
10698
  log.warn(
10069
10699
  `[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
10070
10700
  );
10071
10701
  if (policy.record) await loadAccount();
10072
10702
  refusedOnce("lockout", { lock: decision.lockedKind });
10073
- ctx.status = 429;
10074
- ctx.body = {
10075
- error: {
10076
- status: 429,
10077
- name: "TooManyRequestsError",
10078
- message: "Too many failed login attempts. Please try again later.",
10079
- details: { retryAfter: decision.retryAfter }
10080
- }
10081
- };
10082
- return;
10703
+ return refuse(ctx, {
10704
+ status: 429,
10705
+ name: "TooManyRequestsError",
10706
+ message: "Too many failed login attempts. Please try again later.",
10707
+ retryAfter: decision.retryAfter
10708
+ });
10083
10709
  }
10084
10710
  if (decision.outcome === "busy") {
10085
10711
  if (policy.record) await loadAccount();
10086
10712
  refusedOnce("too-many-attempts", {});
10087
- ctx.set("Retry-After", "1");
10088
- ctx.status = 429;
10089
- ctx.body = {
10090
- error: {
10091
- status: 429,
10092
- name: "TooManyRequestsError",
10093
- message: "Too many login attempts at once. Please try again.",
10094
- details: { retryAfter: 1 }
10095
- }
10096
- };
10097
- return;
10713
+ return refuse(ctx, {
10714
+ status: 429,
10715
+ name: "TooManyRequestsError",
10716
+ message: "Too many login attempts at once. Please try again.",
10717
+ retryAfter: 1
10718
+ });
10098
10719
  }
10099
10720
  let thrown = null;
10721
+ let returned;
10100
10722
  try {
10101
- await next();
10723
+ returned = await run();
10102
10724
  } catch (err) {
10103
10725
  thrown = err;
10104
10726
  }
10105
- const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10106
- const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
10727
+ const result = classify(thrown, ctx);
10107
10728
  if (result === "failure") {
10729
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10108
10730
  if (policy.record || decision.reservation.accountKey) await loadAccount();
10109
10731
  if (account) {
10110
10732
  event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
@@ -10132,21 +10754,93 @@ var require_bootstrap = __commonJS({
10132
10754
  minutes
10133
10755
  });
10134
10756
  if (lock.kind === "account" && policy.notifyUser && account?.email) {
10135
- const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
10136
- notifications.sendAccountLockedEmail({
10137
- user: account,
10138
- minutes,
10139
- until: lock.until
10140
- }).catch(() => {
10141
- });
10757
+ const mailWindowMs = Math.max(policy.windowMs, policy.durationMs);
10758
+ const sent = await coordinator.hit(hashedKey("lm", lock.id), mailWindowMs).then((entry) => Number(entry?.hits) || 0).catch(() => 1);
10759
+ if (sent === 1) {
10760
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
10761
+ notifications.sendAccountLockedEmail({
10762
+ user: account,
10763
+ minutes,
10764
+ until: lock.until
10765
+ }).catch(() => {
10766
+ });
10767
+ }
10142
10768
  }
10143
10769
  }
10144
10770
  } catch (err) {
10145
10771
  log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
10146
10772
  }
10147
10773
  if (thrown) throw thrown;
10774
+ return returned;
10775
+ };
10776
+ strapi2.server.use(async (ctx, next) => {
10777
+ if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
10778
+ return guard(ctx, next, classifyRouteOutcome, refuseOverHttp);
10148
10779
  });
10149
10780
  log.info("[SUCCESS] Failed-login lockout middleware mounted");
10781
+ return guard;
10782
+ }
10783
+ function classifyRouteOutcome(thrown, ctx) {
10784
+ const status = thrown ? statusOfThrownError(thrown) : ctx.status;
10785
+ if (!thrown && status === 200 && ctx.body && ctx.body.jwt) return "success";
10786
+ return status === 400 || status === 401 ? "failure" : "neutral";
10787
+ }
10788
+ function refuseOverHttp(ctx, refusal) {
10789
+ ctx.set("Retry-After", String(refusal.retryAfter));
10790
+ ctx.status = refusal.status;
10791
+ ctx.body = {
10792
+ error: {
10793
+ status: refusal.status,
10794
+ name: refusal.name,
10795
+ message: refusal.message,
10796
+ details: { retryAfter: refusal.retryAfter }
10797
+ }
10798
+ };
10799
+ }
10800
+ function isGraphqlRequest(strapi2, ctx) {
10801
+ let endpoint = "/graphql";
10802
+ try {
10803
+ endpoint = strapi2.plugin("graphql")?.config?.("endpoint") || endpoint;
10804
+ } catch {
10805
+ }
10806
+ const original = String(ctx.originalUrl || ctx.url || "").split("?")[0];
10807
+ return normalizePath(original) === normalizePath(endpoint);
10808
+ }
10809
+ function createAuthControllerHandlers({ strapi: strapi2, geoCheck, lockoutGuard }) {
10810
+ const refuse = (ctx, refusal) => {
10811
+ if (refusal.retryAfter) ctx.set("Retry-After", String(refusal.retryAfter));
10812
+ if (isGraphqlRequest(strapi2, ctx)) {
10813
+ const details = refusal.retryAfter ? { retryAfter: refusal.retryAfter } : {};
10814
+ throw refusal.status === 429 ? new utilsErrors.RateLimitError(refusal.message, details) : new utilsErrors.ForbiddenError(refusal.message, details);
10815
+ }
10816
+ if (refusal.status === 429) return refuseOverHttp(ctx, refusal);
10817
+ ctx.status = refusal.status;
10818
+ ctx.body = {
10819
+ error: { status: refusal.status, name: refusal.name, message: refusal.message }
10820
+ };
10821
+ return void 0;
10822
+ };
10823
+ const geoFirst = async (ctx) => {
10824
+ const refusal = await geoCheck(ctx);
10825
+ if (!refusal) return false;
10826
+ refuse(ctx, { ...refusal, name: "ForbiddenError", retryAfter: 0 });
10827
+ return true;
10828
+ };
10829
+ return {
10830
+ async callback(ctx, run) {
10831
+ if (await geoFirst(ctx)) return void 0;
10832
+ const provider = ctx.params?.provider || "local";
10833
+ if (provider !== "local") return run();
10834
+ return lockoutGuard(ctx, run, classifyCallbackOutcome, refuse);
10835
+ },
10836
+ async newSession(ctx, run) {
10837
+ if (await geoFirst(ctx)) return void 0;
10838
+ return run();
10839
+ }
10840
+ };
10841
+ }
10842
+ function connectAuthControllerGuard(deps) {
10843
+ setAuthControllerHandlers(deps.strapi, createAuthControllerHandlers(deps));
10150
10844
  }
10151
10845
  function statusOfThrownError(err) {
10152
10846
  const status = Number(err?.status ?? err?.statusCode);
@@ -11356,6 +12050,8 @@ var require_bootstrap = __commonJS({
11356
12050
  }
11357
12051
  }
11358
12052
  module.exports.__private = {
12053
+ warnShortEncryptionKey,
12054
+ createAuthControllerHandlers,
11359
12055
  registerSessionAwareAuthStrategy,
11360
12056
  mountFailedLoginLockout,
11361
12057
  ensureSessionLookupIndexes,
@@ -11375,6 +12071,7 @@ var require_destroy = __commonJS({
11375
12071
  "server/src/destroy.js"(exports, module) {
11376
12072
  "use strict";
11377
12073
  var { createLogger } = require_logger();
12074
+ var { uninstallAuthControllerGuard } = require_auth_controller_guard();
11378
12075
  module.exports = async ({ strapi: strapi2 }) => {
11379
12076
  const log = createLogger(strapi2);
11380
12077
  if (strapi2.sessionManagerIntervals) {
@@ -11408,6 +12105,11 @@ var require_destroy = __commonJS({
11408
12105
  }
11409
12106
  strapi2.sessionManagerAdminActivityUninstall = null;
11410
12107
  }
12108
+ try {
12109
+ uninstallAuthControllerGuard(strapi2);
12110
+ } catch (err) {
12111
+ log.warn("Failed to restore the Users & Permissions auth controller:", err?.name || "Error");
12112
+ }
11411
12113
  try {
11412
12114
  strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
11413
12115
  } catch (err) {
@@ -12125,6 +12827,7 @@ var require_admin = __commonJS({
12125
12827
  var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
12126
12828
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
12127
12829
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
12830
+ var USER_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.user-activity.read";
12128
12831
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
12129
12832
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
12130
12833
  var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
@@ -12386,6 +13089,27 @@ var require_admin = __commonJS({
12386
13089
  description: "Get one export batch of Content Manager activity of admins (admin)"
12387
13090
  }
12388
13091
  },
13092
+ // ===================== APP-USER SECURITY ACTIVITY (4.22) =====================
13093
+ {
13094
+ method: "GET",
13095
+ path: "/user-activity",
13096
+ handler: "user-activity.list",
13097
+ config: {
13098
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
13099
+ middlewares: adminReadRateLimit(),
13100
+ description: "List the security activity of app users (admin)"
13101
+ }
13102
+ },
13103
+ {
13104
+ method: "GET",
13105
+ path: "/user-activity/export",
13106
+ handler: "user-activity.export",
13107
+ config: {
13108
+ policies: adminSessionsPolicy([USER_ACTIVITY_READ_ACTION]),
13109
+ middlewares: adminReadRateLimit(),
13110
+ description: "Get one export batch of the security activity of app users (admin)"
13111
+ }
13112
+ },
12389
13113
  // ===================== SIGN-IN LOCKS AND ROLE RULES =====================
12390
13114
  {
12391
13115
  method: "GET",
@@ -14859,7 +15583,13 @@ var require_settings_access = __commonJS({
14859
15583
  // Signed webhook, event selection, impossible travel and shortened IPs.
14860
15584
  ...PROTECTED_DETECTION_KEYS,
14861
15585
  // Impersonation switch (4.20): whether admins can act as app users.
14862
- ...IMPERSONATION_KEYS
15586
+ ...IMPERSONATION_KEYS,
15587
+ // Security review 2 (4.22.1): which proxies may name the client address
15588
+ // (H2), the IP lockout threshold (H2) and the alert email texts, which go
15589
+ // to app users from the site's own address (hardening 6).
15590
+ "trustedProxies",
15591
+ "maxFailedLogins",
15592
+ "emailTemplates"
14863
15593
  ]);
14864
15594
  var WEBHOOK_SECRETS = Object.freeze([
14865
15595
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
@@ -14969,6 +15699,7 @@ var require_settings = __commonJS({
14969
15699
  validateImpersonationSettings
14970
15700
  } = require_impersonation_rules();
14971
15701
  var { encryptToken } = require_encryption();
15702
+ var { normalizeTrustedProxies, validateTrustedProxies } = require_trusted_proxies();
14972
15703
  var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
14973
15704
  var path = __require("node:path");
14974
15705
  var ALLOWED_WEBHOOK_DOMAINS = {
@@ -15144,7 +15875,9 @@ var require_settings = __commonJS({
15144
15875
  discordWebhookUrl: "",
15145
15876
  slackWebhookUrl: "",
15146
15877
  strictSessionEnforcement: false,
15147
- trustedProxies: false,
15878
+ // A list of proxy addresses or CIDR ranges since 4.22.1; the legacy
15879
+ // boolean is read as an empty list (Strapi's server.proxy settings decide).
15880
+ trustedProxies: [],
15148
15881
  emailTemplates: DEFAULT_EMAIL_TEMPLATES,
15149
15882
  ...SECURITY_LOG_DEFAULTS,
15150
15883
  ...POLICY_DEFAULTS,
@@ -15165,7 +15898,8 @@ var require_settings = __commonJS({
15165
15898
  ...DEFAULT_EMAIL_TEMPLATES,
15166
15899
  ...storedTemplates
15167
15900
  },
15168
- geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath)
15901
+ geoIpDatabasePath: getSafeGeoIpFilename(safeStored.geoIpDatabasePath),
15902
+ trustedProxies: normalizeTrustedProxies(safeStored.trustedProxies)
15169
15903
  };
15170
15904
  }
15171
15905
  var INTEGER_SETTING_RANGES = {
@@ -15190,8 +15924,7 @@ var require_settings = __commonJS({
15190
15924
  "alertOnNewLocation",
15191
15925
  "alertOnVpnProxy",
15192
15926
  "enableWebhooks",
15193
- "strictSessionEnforcement",
15194
- "trustedProxies"
15927
+ "strictSessionEnforcement"
15195
15928
  ];
15196
15929
  var GEO_IP_PROVIDER_VALUES = ["auto", "local-mmdb", "ipapi", "disabled"];
15197
15930
  var GEO_LOOKUP_FAILURE_MODE_VALUES = ["auto", "allow", "block"];
@@ -15265,6 +15998,11 @@ var require_settings = __commonJS({
15265
15998
  next[key] = body[key];
15266
15999
  }
15267
16000
  }
16001
+ if (has("trustedProxies")) {
16002
+ const proxies = validateTrustedProxies(body.trustedProxies);
16003
+ if (proxies.error) errors.push(proxies.error);
16004
+ else next.trustedProxies = proxies.value;
16005
+ }
15268
16006
  for (const key of ["allowedCountries", "blockedCountries"]) {
15269
16007
  if (!has(key)) continue;
15270
16008
  const list = body[key];
@@ -15383,6 +16121,15 @@ var require_settings = __commonJS({
15383
16121
  next.genericWebhookSecret = encryptToken(secret);
15384
16122
  }
15385
16123
  }
16124
+ const urlChanges = typeof next.genericWebhookUrl === "string" && next.genericWebhookUrl !== "" && next.genericWebhookUrl !== (current.genericWebhookUrl || "");
16125
+ const secretStored = typeof current.genericWebhookSecret === "string" && current.genericWebhookSecret !== "";
16126
+ const secretGiven = typeof next.genericWebhookSecret === "string" && next.genericWebhookSecret !== "";
16127
+ if (urlChanges && secretStored && !secretGiven) {
16128
+ errors.push({
16129
+ path: ["genericWebhookSecret"],
16130
+ message: "Enter the webhook secret again when you change the webhook URL"
16131
+ });
16132
+ }
15386
16133
  if (errors.length > 0) return { errors };
15387
16134
  const settings = {};
15388
16135
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -16740,29 +17487,70 @@ var require_admin_sessions2 = __commonJS({
16740
17487
  }
16741
17488
  });
16742
17489
 
16743
- // server/src/controllers/admin-activity.js
16744
- var require_admin_activity = __commonJS({
16745
- "server/src/controllers/admin-activity.js"(exports, module) {
17490
+ // server/src/utils/event-query.js
17491
+ var require_event_query = __commonJS({
17492
+ "server/src/utils/event-query.js"(exports, module) {
16746
17493
  "use strict";
16747
17494
  var { z } = __require("@strapi/utils");
16748
- var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
16749
17495
  var { parseInput } = require_admin_sessions();
16750
17496
  var { sendServerError, sendValidationError } = require_http_errors();
16751
- var { createLogger } = require_logger();
16752
- var { callerCan } = require_settings_access();
16753
17497
  var MAX_PAGE_SIZE = 100;
16754
- var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
16755
17498
  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();
16756
- var common = {
16757
- adminId: adminIdField,
17499
+ var periodAndPaging = () => ({
16758
17500
  from: dateField("from"),
16759
17501
  to: dateField("to"),
16760
17502
  page: z.coerce.number().int().min(1).max(1e6).default(1),
16761
17503
  pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
16762
- };
16763
- var signInQuerySchema = z.strictObject({
16764
- ...common,
16765
- event: z.enum(
17504
+ });
17505
+ var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
17506
+ async function handleEventQuery(ctx, schema, run, { log, logPrefix, operation, failureMessage }) {
17507
+ const parsed = parseInput(schema, ctx.query);
17508
+ if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
17509
+ const query = parsed.value;
17510
+ if (query.from && query.to && query.from > query.to) {
17511
+ return sendValidationError(ctx, "Invalid query", [
17512
+ { path: ["from"], message: "from must not be after to" }
17513
+ ]);
17514
+ }
17515
+ try {
17516
+ ctx.body = await run(query);
17517
+ return ctx.body;
17518
+ } catch (error) {
17519
+ log.error(
17520
+ `${logPrefix}: ${operation} failed`,
17521
+ /** @type {any} */
17522
+ error?.name || "Error"
17523
+ );
17524
+ return sendServerError(ctx, 500, failureMessage);
17525
+ }
17526
+ }
17527
+ module.exports = {
17528
+ MAX_PAGE_SIZE,
17529
+ cursorField,
17530
+ dateField,
17531
+ handleEventQuery,
17532
+ periodAndPaging
17533
+ };
17534
+ }
17535
+ });
17536
+
17537
+ // server/src/controllers/admin-activity.js
17538
+ var require_admin_activity = __commonJS({
17539
+ "server/src/controllers/admin-activity.js"(exports, module) {
17540
+ "use strict";
17541
+ var { z } = __require("@strapi/utils");
17542
+ var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
17543
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
17544
+ var { createLogger } = require_logger();
17545
+ var { callerCan } = require_settings_access();
17546
+ var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
17547
+ var common = {
17548
+ adminId: adminIdField,
17549
+ ...periodAndPaging()
17550
+ };
17551
+ var signInQuerySchema = z.strictObject({
17552
+ ...common,
17553
+ event: z.enum(
16766
17554
  /** @type {[string, ...string[]]} */
16767
17555
  Object.keys(SIGN_IN_FILTERS)
16768
17556
  ).default("all")
@@ -16778,7 +17566,6 @@ var require_admin_activity = __commonJS({
16778
17566
  "contentType must be a content type uid"
16779
17567
  ).optional()
16780
17568
  });
16781
- var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
16782
17569
  var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
16783
17570
  cursor: cursorField
16784
17571
  });
@@ -16811,27 +17598,12 @@ var require_admin_activity = __commonJS({
16811
17598
  } catch {
16812
17599
  }
16813
17600
  };
16814
- const handle = async (ctx, schema, run, operation) => {
16815
- const parsed = parseInput(schema, ctx.query);
16816
- if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
16817
- const query = parsed.value;
16818
- if (query.from && query.to && query.from > query.to) {
16819
- return sendValidationError(ctx, "Invalid query", [
16820
- { path: ["from"], message: "from must not be after to" }
16821
- ]);
16822
- }
16823
- try {
16824
- ctx.body = await run(query);
16825
- return ctx.body;
16826
- } catch (error) {
16827
- log.error(
16828
- `Admin activity: ${operation} failed`,
16829
- /** @type {any} */
16830
- error?.name || "Error"
16831
- );
16832
- return sendServerError(ctx, 500, "Admin activity could not be loaded.");
16833
- }
16834
- };
17601
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
17602
+ log,
17603
+ logPrefix: "Admin activity",
17604
+ operation,
17605
+ failureMessage: "Admin activity could not be loaded."
17606
+ });
16835
17607
  return {
16836
17608
  /**
16837
17609
  * One page of the admin sign-in history: sign-ins, failed attempts,
@@ -17070,10 +17842,43 @@ var require_lockouts = __commonJS({
17070
17842
  }
17071
17843
  });
17072
17844
 
17845
+ // server/src/utils/user-export.js
17846
+ var require_user_export = __commonJS({
17847
+ "server/src/utils/user-export.js"(exports, module) {
17848
+ "use strict";
17849
+ var { SECURITY_EVENTS } = require_security_log_model();
17850
+ var IMPERSONATION_TEXT = Object.freeze({
17851
+ [SECURITY_EVENTS.IMPERSONATION_STARTED]: "An administrator opened your account",
17852
+ [SECURITY_EVENTS.IMPERSONATION_ENDED]: "The administrator access to your account ended",
17853
+ [SECURITY_EVENTS.IMPERSONATION_EXPIRED]: "The administrator access to your account ended",
17854
+ [SECURITY_EVENTS.IMPERSONATION_REFUSED]: "An administrator access to your account was refused"
17855
+ });
17856
+ function toUserExportEvent(row) {
17857
+ const { id: _id, ...rest } = row || {};
17858
+ const text = IMPERSONATION_TEXT[rest.event];
17859
+ if (!text) return rest;
17860
+ const minutes = Number(rest.meta?.durationMinutes);
17861
+ return {
17862
+ event: rest.event,
17863
+ createdAt: rest.createdAt,
17864
+ ip: null,
17865
+ userAgent: null,
17866
+ geo: null,
17867
+ meta: {
17868
+ description: text,
17869
+ ...Number.isInteger(minutes) && minutes > 0 ? { durationMinutes: minutes } : {}
17870
+ }
17871
+ };
17872
+ }
17873
+ module.exports = { IMPERSONATION_TEXT, toUserExportEvent };
17874
+ }
17875
+ });
17876
+
17073
17877
  // server/src/controllers/self-service.js
17074
17878
  var require_self_service = __commonJS({
17075
17879
  "server/src/controllers/self-service.js"(exports, module) {
17076
17880
  "use strict";
17881
+ var crypto = __require("node:crypto");
17077
17882
  var { getCoordinator } = require_coordination();
17078
17883
  var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
17079
17884
  var { recordUserEvent } = require_sign_in_policies();
@@ -17081,6 +17886,7 @@ var require_self_service = __commonJS({
17081
17886
  var { SECURITY_EVENTS } = require_security_log_model();
17082
17887
  var { sendServerError } = require_http_errors();
17083
17888
  var { createLogger } = require_logger();
17889
+ var { toUserExportEvent } = require_user_export();
17084
17890
  var SESSION_UID = "plugin::magic-sessionmanager.session";
17085
17891
  var EVENT_UID = "plugin::magic-sessionmanager.security-event";
17086
17892
  var USER_UID = "plugin::users-permissions.user";
@@ -17147,19 +17953,21 @@ var require_self_service = __commonJS({
17147
17953
  return "en";
17148
17954
  }
17149
17955
  var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
17150
- function sendPage(ctx, status, lang, title, body) {
17956
+ 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);})();`;
17957
+ var FRAGMENT_SCRIPT_HASH = `sha256-${crypto.createHash("sha256").update(FRAGMENT_SCRIPT).digest("base64")}`;
17958
+ function sendPage(ctx, status, lang, title, body, { withScript = false } = {}) {
17151
17959
  ctx.status = status;
17152
17960
  ctx.set("Content-Type", "text/html; charset=utf-8");
17153
17961
  ctx.set(
17154
17962
  "Content-Security-Policy",
17155
- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
17963
+ `default-src 'none'; style-src 'unsafe-inline'; ${withScript ? `script-src '${FRAGMENT_SCRIPT_HASH}'; ` : ""}form-action 'self'; frame-ancestors 'none'; base-uri 'none'`
17156
17964
  );
17157
17965
  ctx.set("Referrer-Policy", "no-referrer");
17158
17966
  ctx.set("Cache-Control", "no-store");
17159
17967
  ctx.set("X-Robots-Tag", "noindex");
17160
17968
  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>
17161
17969
  <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>
17162
- <body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
17970
+ <body><main><h1>${escapeHtml(title)}</h1>${body}</main>${withScript ? `<script>${FRAGMENT_SCRIPT}</script>` : ""}</body></html>`;
17163
17971
  }
17164
17972
  module.exports = ({ strapi: strapi2 }) => {
17165
17973
  const log = createLogger(strapi2);
@@ -17167,17 +17975,20 @@ var require_self_service = __commonJS({
17167
17975
  /**
17168
17976
  * Confirmation page of the "This wasn't me" link. Uses nothing.
17169
17977
  *
17170
- * @route GET /api/magic-sessionmanager/not-me?token=
17978
+ * @route GET /api/magic-sessionmanager/not-me (token in `#token=`; `?token=` before 4.22.1)
17171
17979
  * @auth none (public on purpose: the link is opened from an email; the
17172
17980
  * signed token is checked, and nothing changes until the POST)
17173
17981
  * @param {any} ctx Koa context.
17174
- * @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
17982
+ * @returns {Promise<void>} 200 page with two buttons, or 410 when a `?token=` link is
17983
+ * invalid. Without `?token=` the page is served with the hashed script that copies the
17984
+ * fragment token into the forms; the POST checks it.
17175
17985
  */
17176
17986
  async notMePage(ctx) {
17177
17987
  const lang = pageLanguage(ctx);
17178
17988
  const text = PAGE_TEXT[lang];
17179
- const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
17180
- if (!readNotMeToken(token)) {
17989
+ const hasQueryToken = typeof ctx.query?.token === "string" && ctx.query.token !== "";
17990
+ const token = hasQueryToken ? ctx.query.token : "";
17991
+ if (hasQueryToken && !readNotMeToken(token)) {
17181
17992
  return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
17182
17993
  }
17183
17994
  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>`;
@@ -17186,7 +17997,8 @@ var require_self_service = __commonJS({
17186
17997
  200,
17187
17998
  lang,
17188
17999
  text.title,
17189
- `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
18000
+ `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`,
18001
+ { withScript: !hasQueryToken }
17190
18002
  );
17191
18003
  },
17192
18004
  /**
@@ -17339,7 +18151,9 @@ var require_self_service = __commonJS({
17339
18151
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
17340
18152
  user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
17341
18153
  sessions,
17342
- securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
18154
+ // Impersonation events show a fixed text and the duration only
18155
+ // (security review 2, L3): the admin's reason stays internal.
18156
+ securityEvents: (Array.isArray(events) ? events : []).map(toUserExportEvent)
17343
18157
  };
17344
18158
  } catch (err) {
17345
18159
  log.error("[my-data] Export failed:", err?.name || "Error");
@@ -17899,7 +18713,8 @@ var require_impersonation = __commonJS({
17899
18713
  * Caller (with roles), target id and request body.
17900
18714
  * @returns {Promise<object>} Impersonation DTO plus the preview.
17901
18715
  * @throws {ImpersonationError} 400 invalid body or id; 403 feature off, self, Super Admin
17902
- * or not a subset of the caller's permissions; 404 unknown admin.
18716
+ * (callers with `admin::users.read`) or not a subset of the caller's permissions; 404
18717
+ * unknown admin, or a Super Admin for callers without `admin::users.read`.
17903
18718
  * @sideeffect Creates an impersonation row; queues `impersonation.started` or `.refused`.
17904
18719
  */
17905
18720
  async previewAdmin({ actor, adminId, body, canReadAdmins }) {
@@ -17929,6 +18744,15 @@ var require_impersonation = __commonJS({
17929
18744
  ]);
17930
18745
  if (!target) throw new ImpersonationError(404, "Admin not found");
17931
18746
  const refusal = await previewRefusal(strapi2, caller || actor, target);
18747
+ if (refusal?.reason === "super-admin" && !canReadAdmins) {
18748
+ service.recordRefused({
18749
+ actorId,
18750
+ targetType: "admin",
18751
+ targetId: adminId,
18752
+ reason: "super-admin"
18753
+ });
18754
+ throw new ImpersonationError(404, "Admin not found");
18755
+ }
17932
18756
  if (refusal) {
17933
18757
  const messages = {
17934
18758
  self: "You cannot view yourself as another admin",
@@ -18338,25 +19162,32 @@ var require_impersonation = __commonJS({
18338
19162
  };
18339
19163
  },
18340
19164
  /**
18341
- * Loads one impersonation for the request guard (5-second cache).
19165
+ * Loads one impersonation for the request guard. Only a finished (or
19166
+ * unknown) impersonation is cached for 5 seconds; an active one is read
19167
+ * on every request, so ending it on one process takes effect on every
19168
+ * other process at once (security review 2, hardening 4).
18342
19169
  *
18343
19170
  * @param {string} documentId Impersonation id.
18344
- * @returns {Promise<{id: string, actorId: string, state: string, expiresAt: number}|null>}
19171
+ * @returns {Promise<{id: string, actorId: string, targetId: string|null, state: string,
19172
+ * expiresAt: number}|null>}
18345
19173
  */
18346
19174
  async loadForGuard(documentId) {
18347
19175
  const cached = recordCache.get(documentId);
18348
19176
  if (cached && Date.now() - cached.at < RECORD_CACHE_MS) return cached.value;
18349
19177
  const row = await query().findOne({
18350
19178
  where: { documentId, targetType: "user" },
18351
- select: ["documentId", "actorId", "state", "expiresAt"]
19179
+ select: ["documentId", "actorId", "targetId", "state", "expiresAt"]
18352
19180
  });
18353
19181
  const value = row ? {
18354
19182
  id: row.documentId,
18355
19183
  actorId: row.actorId,
19184
+ targetId: typeof row.targetId === "string" ? row.targetId : null,
18356
19185
  state: row.state,
18357
19186
  expiresAt: new Date(row.expiresAt).getTime()
18358
19187
  } : null;
18359
- remember(recordCache, documentId, { value, at: Date.now() });
19188
+ if (!value || value.state !== "active") {
19189
+ remember(recordCache, documentId, { value, at: Date.now() });
19190
+ }
18360
19191
  return value;
18361
19192
  },
18362
19193
  /**
@@ -18399,7 +19230,10 @@ var require_impersonation = __commonJS({
18399
19230
  * Records a refused Content API call made while impersonating (one event
18400
19231
  * per impersonation and reason per minute).
18401
19232
  *
18402
- * @param {{id: string, actorId: string}} impersonation Impersonation.
19233
+ * The impersonated user is the target (since 4.22), so the refusal shows
19234
+ * in that user's security activity and is deleted with the account.
19235
+ *
19236
+ * @param {{id: string, actorId: string, targetId?: string|null}} impersonation Impersonation.
18403
19237
  * @param {string} reason Refusal reason.
18404
19238
  * @returns {void}
18405
19239
  */
@@ -18414,7 +19248,7 @@ var require_impersonation = __commonJS({
18414
19248
  actorType: "admin",
18415
19249
  actorId: impersonation.actorId,
18416
19250
  targetType: "user",
18417
- targetId: null,
19251
+ targetId: impersonation.targetId || null,
18418
19252
  meta: { refusal: `call-${reason}`, impersonation: impersonation.id }
18419
19253
  });
18420
19254
  },
@@ -18672,6 +19506,265 @@ var require_impersonation2 = __commonJS({
18672
19506
  }
18673
19507
  });
18674
19508
 
19509
+ // server/src/utils/user-activity-model.js
19510
+ var require_user_activity_model = __commonJS({
19511
+ "server/src/utils/user-activity-model.js"(exports, module) {
19512
+ "use strict";
19513
+ var { REFUSAL_REASONS, SECURITY_EVENTS, toObject } = require_security_log_model();
19514
+ var USER_ACCOUNT_EVENTS = Object.freeze([
19515
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
19516
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
19517
+ SECURITY_EVENTS.USER_LOCKOUT,
19518
+ SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
19519
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
19520
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
19521
+ SECURITY_EVENTS.USER_NEW_DEVICE,
19522
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
19523
+ SECURITY_EVENTS.USER_NOT_ME,
19524
+ SECURITY_EVENTS.USER_DATA_EXPORTED
19525
+ ]);
19526
+ var USER_IMPERSONATION_EVENTS = Object.freeze([
19527
+ SECURITY_EVENTS.IMPERSONATION_STARTED,
19528
+ SECURITY_EVENTS.IMPERSONATION_ENDED,
19529
+ SECURITY_EVENTS.IMPERSONATION_EXPIRED,
19530
+ SECURITY_EVENTS.IMPERSONATION_REFUSED
19531
+ ]);
19532
+ var USER_ACTIVITY_EVENTS = Object.freeze([...USER_ACCOUNT_EVENTS, ...USER_IMPERSONATION_EVENTS]);
19533
+ var USER_ACTIVITY_FILTERS = Object.freeze({
19534
+ all: USER_ACTIVITY_EVENTS,
19535
+ failed: Object.freeze([
19536
+ SECURITY_EVENTS.USER_SIGN_IN_FAILED,
19537
+ SECURITY_EVENTS.USER_SIGN_IN_REFUSED
19538
+ ]),
19539
+ lockouts: Object.freeze([SECURITY_EVENTS.USER_LOCKOUT, SECURITY_EVENTS.USER_LOCKOUT_LIFTED]),
19540
+ suspicious: Object.freeze([
19541
+ SECURITY_EVENTS.USER_NEW_DEVICE,
19542
+ SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
19543
+ SECURITY_EVENTS.USER_NOT_ME
19544
+ ]),
19545
+ sessions: Object.freeze([
19546
+ SECURITY_EVENTS.USER_SESSION_LIMIT,
19547
+ SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED
19548
+ ]),
19549
+ privacy: Object.freeze([SECURITY_EVENTS.USER_DATA_EXPORTED]),
19550
+ impersonation: USER_IMPERSONATION_EVENTS
19551
+ });
19552
+ var USER_DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
19553
+ function userActivityWhere(query, { retentionDays, now = /* @__PURE__ */ new Date() }) {
19554
+ const group = (
19555
+ /** @type {Record<string, readonly string[]>} */
19556
+ USER_ACTIVITY_FILTERS[query.event || "all"] || USER_ACTIVITY_FILTERS.all
19557
+ );
19558
+ const account = group.filter((event) => USER_ACCOUNT_EVENTS.includes(event));
19559
+ const impersonation = group.filter((event) => USER_IMPERSONATION_EVENTS.includes(event));
19560
+ const kinds = [];
19561
+ if (account.length) kinds.push({ event: { $in: account } });
19562
+ if (impersonation.length) kinds.push({ event: { $in: impersonation }, targetType: "user" });
19563
+ const conditions = [kinds.length === 1 ? kinds[0] : { $or: kinds }];
19564
+ if (query.userId) conditions.push({ targetType: "user", targetId: String(query.userId) });
19565
+ const days = Number.isInteger(retentionDays) && retentionDays > 0 ? retentionDays : 90;
19566
+ const cutoff = new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
19567
+ const from = query.from && query.from > cutoff ? query.from : cutoff;
19568
+ conditions.push({ createdAt: { $gte: from } });
19569
+ if (query.to) conditions.push({ createdAt: { $lte: query.to } });
19570
+ return { $and: conditions };
19571
+ }
19572
+ var count = (value, max = 1e6) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max ? value : null;
19573
+ var oneOf = (value, allowed) => typeof value === "string" && allowed.includes(value) ? value : null;
19574
+ var countryCode = (value) => typeof value === "string" && /^[A-Z]{2}$/.test(value) ? value : null;
19575
+ var code = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value) ? value : null;
19576
+ function userEventFacts(event, storedMeta, viewer = {}) {
19577
+ const meta = toObject(storedMeta);
19578
+ switch (event) {
19579
+ case SECURITY_EVENTS.USER_SIGN_IN_FAILED:
19580
+ return { status: count(meta.status, 599), unknownAccount: meta.unknownAccount === true };
19581
+ case SECURITY_EVENTS.USER_SIGN_IN_REFUSED:
19582
+ return {
19583
+ reason: oneOf(meta.reason, REFUSAL_REASONS),
19584
+ limit: count(meta.limit, 1e4),
19585
+ lock: oneOf(meta.lock, ["ip", "account"]),
19586
+ unknownAccount: meta.unknownAccount === true
19587
+ };
19588
+ case SECURITY_EVENTS.USER_LOCKOUT:
19589
+ return {
19590
+ kind: oneOf(meta.kind, ["ip", "account"]),
19591
+ failures: count(meta.failures, 1e5),
19592
+ minutes: count(meta.minutes, 1e6)
19593
+ };
19594
+ case SECURITY_EVENTS.USER_LOCKOUT_LIFTED:
19595
+ return { kind: oneOf(meta.kind, ["ip", "account"]) };
19596
+ case SECURITY_EVENTS.USER_SESSION_LIMIT:
19597
+ return { ended: count(meta.ended, 1e5), limit: count(meta.limit, 1e4) };
19598
+ case SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED:
19599
+ return { ended: count(meta.ended, 1e5) };
19600
+ case SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL:
19601
+ return {
19602
+ distanceKm: count(meta.distanceKm, 5e4),
19603
+ speedKmh: count(meta.speedKmh, 1e7),
19604
+ from: countryCode(meta.from),
19605
+ to: countryCode(meta.to),
19606
+ action: oneOf(meta.action, ["alert", "reauthenticate"])
19607
+ };
19608
+ case SECURITY_EVENTS.USER_NOT_ME:
19609
+ return { scope: oneOf(meta.scope, ["session", "all"]), ended: count(meta.ended, 1e5) };
19610
+ case SECURITY_EVENTS.USER_DATA_EXPORTED:
19611
+ return { sessions: count(meta.sessions, 1e6), events: count(meta.events, 1e6) };
19612
+ case SECURITY_EVENTS.IMPERSONATION_STARTED:
19613
+ case SECURITY_EVENTS.IMPERSONATION_ENDED:
19614
+ case SECURITY_EVENTS.IMPERSONATION_EXPIRED:
19615
+ case SECURITY_EVENTS.IMPERSONATION_REFUSED: {
19616
+ const reason = viewer.canSeeImpersonationReason === true && typeof meta.reason === "string" && meta.reason.trim() ? meta.reason.trim().slice(0, 255) : null;
19617
+ return {
19618
+ durationMinutes: count(meta.durationMinutes, 1440),
19619
+ handoff: oneOf(meta.handoff, ["frontend", "token"]),
19620
+ endReason: oneOf(meta.endReason, ["ended", "disabled", "failed"]),
19621
+ refusal: code(meta.refusal),
19622
+ reason
19623
+ };
19624
+ }
19625
+ default:
19626
+ return {};
19627
+ }
19628
+ }
19629
+ function userEventAddress(row, options, anonymize) {
19630
+ if (!options.storeIp) return { ipAddress: null, ipAnonymized: false, keepLocation: false };
19631
+ const stored = typeof row.ip === "string" && row.ip ? row.ip : null;
19632
+ const alreadyShortened = toObject(row.meta).ipAnonymized === true;
19633
+ if (!stored) return { ipAddress: null, ipAnonymized: false, keepLocation: true };
19634
+ if (options.anonymizeIp && !alreadyShortened) {
19635
+ const shortened = anonymize(stored);
19636
+ return { ipAddress: shortened || null, ipAnonymized: Boolean(shortened), keepLocation: true };
19637
+ }
19638
+ return { ipAddress: stored, ipAnonymized: alreadyShortened, keepLocation: true };
19639
+ }
19640
+ module.exports = {
19641
+ USER_ACCOUNT_EVENTS,
19642
+ USER_ACTIVITY_EVENTS,
19643
+ USER_ACTIVITY_FILTERS,
19644
+ USER_DOCUMENT_ID_PATTERN,
19645
+ USER_IMPERSONATION_EVENTS,
19646
+ userActivityWhere,
19647
+ userEventAddress,
19648
+ userEventFacts
19649
+ };
19650
+ }
19651
+ });
19652
+
19653
+ // server/src/controllers/user-activity.js
19654
+ var require_user_activity = __commonJS({
19655
+ "server/src/controllers/user-activity.js"(exports, module) {
19656
+ "use strict";
19657
+ var { z } = __require("@strapi/utils");
19658
+ var { USER_ACTIVITY_FILTERS } = require_user_activity_model();
19659
+ var { cursorField, handleEventQuery, periodAndPaging } = require_event_query();
19660
+ var { createLogger } = require_logger();
19661
+ var { callerCan } = require_settings_access();
19662
+ var IMPERSONATE_USERS_ACTION = "plugin::magic-sessionmanager.impersonate.users";
19663
+ var listQuerySchema = z.strictObject({
19664
+ event: z.enum(
19665
+ /** @type {[string, ...string[]]} */
19666
+ Object.keys(USER_ACTIVITY_FILTERS)
19667
+ ).default("all"),
19668
+ userId: z.string().regex(/^[A-Za-z0-9]{1,64}$/, "userId must be the documentId of a user").optional(),
19669
+ ...periodAndPaging()
19670
+ });
19671
+ var exportQuerySchema = listQuerySchema.omit({ page: true, pageSize: true }).extend({
19672
+ cursor: cursorField
19673
+ });
19674
+ module.exports = ({ strapi: strapi2 }) => {
19675
+ const log = createLogger(strapi2);
19676
+ const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
19677
+ const viewerOf = (ctx) => ({
19678
+ ability: (
19679
+ /** @type {any} */
19680
+ ctx.state?.userAbility || null
19681
+ ),
19682
+ canReadAdmins: callerCan(ctx, "admin::users.read"),
19683
+ canSeeImpersonationReason: callerCan(ctx, IMPERSONATE_USERS_ACTION)
19684
+ });
19685
+ const audit = (ctx, exported) => {
19686
+ const state = (
19687
+ /** @type {any} */
19688
+ ctx.state
19689
+ );
19690
+ const viaToken = state?.auth?.strategy?.name === "admin-token";
19691
+ if (!viaToken && !exported) return;
19692
+ try {
19693
+ service().recordLogRead({
19694
+ adminId: state?.user?.id,
19695
+ tokenId: viaToken ? state?.auth?.credentials?.id : null,
19696
+ list: "user-activity",
19697
+ exported,
19698
+ via: viaToken ? "admin-token" : "admin-panel"
19699
+ });
19700
+ } catch {
19701
+ }
19702
+ };
19703
+ const handle = (ctx, schema, run, operation) => handleEventQuery(ctx, schema, run, {
19704
+ log,
19705
+ logPrefix: "User activity",
19706
+ operation,
19707
+ failureMessage: "Security activity could not be loaded."
19708
+ });
19709
+ return {
19710
+ /**
19711
+ * One page of the app-user security activity, newest first.
19712
+ *
19713
+ * @route GET /magic-sessionmanager/user-activity
19714
+ * @auth Admin JWT or admin API token; admin::hasPermissions access + user-activity.read;
19715
+ * read rate limit.
19716
+ * @param {Context} ctx Reads `ctx.query.event` (`all`|`failed`|`lockouts`|`suspicious`|
19717
+ * `sessions`|`privacy`|`impersonation`), `userId` (documentId of a Users & Permissions
19718
+ * user), `from`/`to` (ISO dates), `page`, `pageSize` (1..100, default 20). Unknown keys
19719
+ * are a 400.
19720
+ * @returns {Promise<unknown>} 200 `{ data: UserEventRow[], meta: { pagination, recording,
19721
+ * identity } }`; 400 ValidationError with field errors; 500 fixed message. Rows hold the
19722
+ * event, time, the user (`{ id, documentId, email, username }`, email and username empty
19723
+ * unless the caller may read that user in the Content Manager), the admin who acted
19724
+ * (name empty without `admin::users.read`), the event's facts (numbers and codes; the
19725
+ * impersonation reason only with `impersonate.users`), IP address as the current
19726
+ * switches allow it, location, browser, OS and the stored user agent. Rows older than
19727
+ * the retention period are left out.
19728
+ * @sideeffect A read with an admin API token queues a `security-log.read` event.
19729
+ */
19730
+ async list(ctx) {
19731
+ return handle(
19732
+ ctx,
19733
+ listQuerySchema,
19734
+ (query) => {
19735
+ audit(ctx, false);
19736
+ return service().listUserActivity(query, viewerOf(ctx));
19737
+ },
19738
+ "list"
19739
+ );
19740
+ },
19741
+ /**
19742
+ * One export batch (500 rows, keyset cursor) of the app-user security activity.
19743
+ *
19744
+ * @route GET /magic-sessionmanager/user-activity/export
19745
+ * @auth As list.
19746
+ * @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
19747
+ * @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
19748
+ * @sideeffect The first batch of an export (no `cursor`) queues a `security-log.read` event
19749
+ * with `list: 'user-activity'`, `exported: true` and `via` (`admin-panel` or
19750
+ * `admin-token`).
19751
+ */
19752
+ async export(ctx) {
19753
+ return handle(
19754
+ ctx,
19755
+ exportQuerySchema,
19756
+ (query) => {
19757
+ if (!query.cursor) audit(ctx, true);
19758
+ return service().exportBatch("user-activity", query, query.cursor || null, viewerOf(ctx));
19759
+ },
19760
+ "export"
19761
+ );
19762
+ }
19763
+ };
19764
+ };
19765
+ }
19766
+ });
19767
+
18675
19768
  // server/src/controllers/index.js
18676
19769
  var require_controllers = __commonJS({
18677
19770
  "server/src/controllers/index.js"(exports, module) {
@@ -18685,6 +19778,7 @@ var require_controllers = __commonJS({
18685
19778
  var selfService = require_self_service();
18686
19779
  var webhooks = require_webhooks();
18687
19780
  var impersonation = require_impersonation2();
19781
+ var userActivity = require_user_activity();
18688
19782
  module.exports = {
18689
19783
  session,
18690
19784
  settings,
@@ -18694,7 +19788,8 @@ var require_controllers = __commonJS({
18694
19788
  lockouts,
18695
19789
  "self-service": selfService,
18696
19790
  webhooks,
18697
- impersonation
19791
+ impersonation,
19792
+ "user-activity": userActivity
18698
19793
  };
18699
19794
  }
18700
19795
  });
@@ -21470,6 +22565,12 @@ var require_security_log = __commonJS({
21470
22565
  normalizeIp
21471
22566
  } = require_admin_request_info();
21472
22567
  var { resolveSecurityLogSettings } = require_security_log_settings();
22568
+ var {
22569
+ USER_ACTIVITY_EVENTS,
22570
+ userActivityWhere,
22571
+ userEventAddress,
22572
+ userEventFacts
22573
+ } = require_user_activity_model();
21473
22574
  var { getPluginSettings } = require_settings_loader();
21474
22575
  var { shouldResolveGeoData } = require_enhance_session();
21475
22576
  var { createLogger } = require_logger();
@@ -21477,6 +22578,7 @@ var require_security_log = __commonJS({
21477
22578
  var ADMIN_USER_UID = "admin::user";
21478
22579
  var ADMIN_SESSION_UID = "admin::session";
21479
22580
  var PERMISSION_UID = "admin::permission";
22581
+ var USER_UID = "plugin::users-permissions.user";
21480
22582
  var SUPER_ADMIN_CODE = "strapi-super-admin";
21481
22583
  var FLUSH_DELAY_MS = 1e3;
21482
22584
  var FLUSH_BATCH = 200;
@@ -21493,6 +22595,7 @@ var require_security_log = __commonJS({
21493
22595
  var EXPORT_BATCH = 500;
21494
22596
  var DELETE_BATCH = 1e3;
21495
22597
  var MAX_DELETE_STEPS = 200;
22598
+ var AUDITED_LISTS = Object.freeze(["sign-ins", "content", "user-activity"]);
21496
22599
  function toId(value) {
21497
22600
  if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
21498
22601
  if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
@@ -21868,13 +22971,35 @@ var require_security_log = __commonJS({
21868
22971
  * @sideeffect Queues one always-on security event.
21869
22972
  */
21870
22973
  recordTokenRead(input) {
21871
- const now = Date.now();
21872
- const tokenId = toId(input?.tokenId);
21873
- const key = `${tokenId || "-"}|${input?.list}|${input?.exported ? "export" : "list"}`;
21874
- const last = readAudits.get(key);
21875
- if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
21876
- readAudits.set(key, now);
21877
- pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
22974
+ return service.recordLogRead({ ...input, via: "admin-token" });
22975
+ },
22976
+ /**
22977
+ * Records a read of the security log (`security-log.read`, always on).
22978
+ * Reads with an admin API token (4.17) are recorded once per token, list
22979
+ * and kind within 5 minutes. An export of the app-user activity from the
22980
+ * admin panel (4.22) is recorded each time it starts: it takes personal
22981
+ * data of app users out of Strapi.
22982
+ *
22983
+ * @param {{adminId: unknown, tokenId?: unknown, list: 'sign-ins'|'content'|'user-activity',
22984
+ * exported: boolean, via: 'admin-token'|'admin-panel'}} input Who read what, and how.
22985
+ * @returns {boolean} Whether an event was queued.
22986
+ * @sideeffect Queues one always-on security event.
22987
+ */
22988
+ recordLogRead(input) {
22989
+ const via = input?.via === "admin-panel" ? "admin-panel" : "admin-token";
22990
+ const list = AUDITED_LISTS.includes(
22991
+ /** @type {string} */
22992
+ input?.list
22993
+ ) ? input.list : "sign-ins";
22994
+ const tokenId = via === "admin-token" ? toId(input?.tokenId) : null;
22995
+ if (via === "admin-token") {
22996
+ const now = Date.now();
22997
+ const key = `${tokenId || "-"}|${list}|${input?.exported ? "export" : "list"}`;
22998
+ const last = readAudits.get(key);
22999
+ if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
23000
+ readAudits.set(key, now);
23001
+ pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
23002
+ }
21878
23003
  return service.record({
21879
23004
  event: SECURITY_EVENTS.LOG_READ,
21880
23005
  actorType: "admin",
@@ -21885,9 +23010,9 @@ var require_security_log = __commonJS({
21885
23010
  targetType: "security-log",
21886
23011
  targetId: null,
21887
23012
  meta: {
21888
- list: input?.list === "content" ? "content" : "sign-ins",
23013
+ list,
21889
23014
  exported: input?.exported === true,
21890
- via: "admin-token",
23015
+ via,
21891
23016
  ...tokenId ? { tokenId } : {}
21892
23017
  }
21893
23018
  });
@@ -22024,16 +23149,63 @@ var require_security_log = __commonJS({
22024
23149
  };
22025
23150
  },
22026
23151
  /**
22027
- * One export batch (newest first, keyset on id) of either list.
23152
+ * One page of the app-user security activity (4.22), newest first:
23153
+ * failed and refused sign-ins, lockouts, session limits, sign-outs after
23154
+ * a password change, new devices, impossible travel, "This wasn't me",
23155
+ * data exports and impersonations of app users. Rows older than the
23156
+ * retention period are not returned; IP addresses follow the current
23157
+ * "Store" and "Anonymise" switches.
23158
+ *
23159
+ * @param {{event?: string, userId?: string, from?: Date|null, to?: Date|null,
23160
+ * page: number, pageSize: number}} query Parsed filters.
23161
+ * @param {Viewer} [viewer] Reader (user emails need Content Manager read access to the
23162
+ * user; admin names `admin::users.read`; impersonation reasons `impersonate.users`).
23163
+ * @returns {Promise<{data: object[], meta: object}>} Response body.
23164
+ */
23165
+ async listUserActivity(query, viewer = {}) {
23166
+ const settings = await readSettingsOrDefaults();
23167
+ const options = resolveSecurityLogSettings(settings);
23168
+ const where = userActivityWhere(query, options);
23169
+ const [total, rows] = await Promise.all([
23170
+ events().count({ where }),
23171
+ events().findMany({
23172
+ where,
23173
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
23174
+ offset: (query.page - 1) * query.pageSize,
23175
+ limit: query.pageSize
23176
+ })
23177
+ ]);
23178
+ const shaped = await shapeUserEvents(Array.isArray(rows) ? rows : [], viewer, options);
23179
+ return {
23180
+ data: shaped.data,
23181
+ meta: {
23182
+ pagination: paginationOf(query, total),
23183
+ recording: {
23184
+ ipAddresses: options.storeIp,
23185
+ anonymizeIp: options.anonymizeIp,
23186
+ retentionDays: options.retentionDays,
23187
+ userSignIns: settings.recordUserSignInEvents !== false
23188
+ },
23189
+ identity: {
23190
+ users: shaped.usersVisible,
23191
+ names: viewer.canReadAdmins === true,
23192
+ impersonationReasons: viewer.canSeeImpersonationReason === true
23193
+ }
23194
+ }
23195
+ };
23196
+ },
23197
+ /**
23198
+ * One export batch (newest first, keyset on id) of a list.
22028
23199
  *
22029
- * @param {'sign-ins'|'content'} kind List.
23200
+ * @param {'sign-ins'|'content'|'user-activity'} kind List.
22030
23201
  * @param {any} query Parsed filters (as for the list).
22031
23202
  * @param {number|null} cursor Id below which to continue.
22032
23203
  * @param {Viewer} [viewer] Reader; the same title and name rules as the lists.
22033
23204
  * @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
22034
23205
  */
22035
23206
  async exportBatch(kind, query, cursor, viewer = {}) {
22036
- const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
23207
+ const options = kind === "user-activity" ? resolveSecurityLogSettings(await readSettingsOrDefaults()) : null;
23208
+ const base = kind === "sign-ins" ? signInWhere(query) : kind === "user-activity" && options ? userActivityWhere(query, options) : activityWhere(query);
22037
23209
  const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
22038
23210
  const rows = await events().findMany({
22039
23211
  where,
@@ -22041,7 +23213,11 @@ var require_security_log = __commonJS({
22041
23213
  limit: EXPORT_BATCH
22042
23214
  });
22043
23215
  const list = Array.isArray(rows) ? rows : [];
22044
- const data = kind === "sign-ins" ? await shapeSignIns(list, viewer) : await shapeActivity(list, viewer);
23216
+ let data;
23217
+ if (kind === "sign-ins") data = await shapeSignIns(list, viewer);
23218
+ else if (kind === "user-activity" && options) {
23219
+ data = (await shapeUserEvents(list, viewer, options)).data;
23220
+ } else data = await shapeActivity(list, viewer);
22045
23221
  const last = list[list.length - 1];
22046
23222
  return {
22047
23223
  data,
@@ -22217,14 +23393,15 @@ var require_security_log = __commonJS({
22217
23393
  if (query.to) conditions.push({ createdAt: { $lte: query.to } });
22218
23394
  return { $and: conditions };
22219
23395
  }
22220
- async function recordingFlags() {
22221
- let settings;
23396
+ async function readSettingsOrDefaults() {
22222
23397
  try {
22223
- settings = await getPluginSettings(strapi2);
23398
+ return await getPluginSettings(strapi2) || {};
22224
23399
  } catch {
22225
- settings = {};
23400
+ return {};
22226
23401
  }
22227
- const options = resolveSecurityLogSettings(settings);
23402
+ }
23403
+ async function recordingFlags() {
23404
+ const options = resolveSecurityLogSettings(await readSettingsOrDefaults());
22228
23405
  return {
22229
23406
  signIns: options.signIns,
22230
23407
  contentActivity: options.content,
@@ -22289,8 +23466,9 @@ var require_security_log = __commonJS({
22289
23466
  sessionsEnded: revoked && Number.isInteger(meta.ended) && meta.ended >= 0 ? meta.ended : null,
22290
23467
  change: row.event === SECURITY_EVENTS.SETTINGS_UPDATED ? { keys: settingKeysOf(meta.keys), viaToken: meta.via === "admin-token" } : null,
22291
23468
  read: row.event === SECURITY_EVENTS.LOG_READ ? {
22292
- list: meta.list === "content" ? "content" : "sign-ins",
22293
- exported: meta.exported === true
23469
+ list: AUDITED_LISTS.includes(meta.list) ? meta.list : "sign-ins",
23470
+ exported: meta.exported === true,
23471
+ via: meta.via === "admin-panel" ? "admin-panel" : "admin-token"
22294
23472
  } : null,
22295
23473
  purge: row.event === SECURITY_EVENTS.LOG_RETENTION_PURGED ? {
22296
23474
  count: Number.isInteger(meta.count) ? meta.count : null,
@@ -22449,231 +23627,100 @@ var require_security_log = __commonJS({
22449
23627
  };
22450
23628
  });
22451
23629
  }
22452
- return service;
22453
- };
22454
- module.exports.EVENT_UID = EVENT_UID;
22455
- module.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
22456
- }
22457
- });
22458
-
22459
- // server/src/utils/webhook-delivery.js
22460
- var require_webhook_delivery = __commonJS({
22461
- "server/src/utils/webhook-delivery.js"(exports, module) {
22462
- "use strict";
22463
- var crypto = __require("node:crypto");
22464
- var dns = __require("node:dns");
22465
- var https = __require("node:https");
22466
- var net = __require("node:net");
22467
- var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
22468
- var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
22469
- var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
22470
- var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
22471
- var TIMEOUT_MS = 5e3;
22472
- var MAX_RESPONSE_BYTES = 64 * 1024;
22473
- var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
22474
- var BLOCKED = (() => {
22475
- const list = new net.BlockList();
22476
- for (const [address, prefix] of [
22477
- ["0.0.0.0", 8],
22478
- ["10.0.0.0", 8],
22479
- ["100.64.0.0", 10],
22480
- ["127.0.0.0", 8],
22481
- ["169.254.0.0", 16],
22482
- ["172.16.0.0", 12],
22483
- ["192.0.0.0", 24],
22484
- ["192.0.2.0", 24],
22485
- ["192.88.99.0", 24],
22486
- ["192.168.0.0", 16],
22487
- ["198.18.0.0", 15],
22488
- ["198.51.100.0", 24],
22489
- ["203.0.113.0", 24],
22490
- ["224.0.0.0", 4],
22491
- ["240.0.0.0", 4]
22492
- ]) {
22493
- list.addSubnet(address, prefix, "ipv4");
22494
- }
22495
- for (const [address, prefix] of [
22496
- ["::", 128],
22497
- ["::1", 128],
22498
- // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
22499
- // checks them against the IPv4 rules above, and a listed /96 would
22500
- // match every IPv4 address.
22501
- ["64:ff9b::", 96],
22502
- ["64:ff9b:1::", 48],
22503
- ["100::", 64],
22504
- ["2001::", 23],
22505
- ["2001:db8::", 32],
22506
- ["2002::", 16],
22507
- ["fc00::", 7],
22508
- ["fe80::", 10],
22509
- ["fec0::", 10],
22510
- ["ff00::", 8]
22511
- ]) {
22512
- list.addSubnet(address, prefix, "ipv6");
22513
- }
22514
- return list;
22515
- })();
22516
- function isBlockedAddress(address) {
22517
- let value = String(address || "").trim();
22518
- if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
22519
- value = value.slice(7);
22520
- }
22521
- const version = net.isIP(value);
22522
- if (version === 0) return true;
22523
- return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
22524
- }
22525
- function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
22526
- const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
22527
- return `t=${timestamp},v1=${digest}`;
22528
- }
22529
- function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
22530
- const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
22531
- if (!match) return false;
22532
- const timestamp = Number(match[1]);
22533
- if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
22534
- const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
22535
- const given = Buffer.from(match[2], "hex");
22536
- return given.length === expected.length && crypto.timingSafeEqual(given, expected);
22537
- }
22538
- var DeliveryError = class extends Error {
22539
- /**
22540
- * @param {string} code Stable code.
22541
- * @param {boolean} retryable Whether another attempt may succeed.
22542
- * @param {number|null} [status] HTTP status, when there was one.
22543
- */
22544
- constructor(code, retryable, status = null) {
22545
- super(code);
22546
- this.name = "DeliveryError";
22547
- this.code = code;
22548
- this.retryable = retryable;
22549
- this.status = status;
22550
- }
22551
- };
22552
- var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
22553
- function httpsPost({ url, address, headers, body, timeoutMs }) {
22554
- return new Promise((resolve, reject) => {
22555
- const request = https.request(
22556
- {
22557
- protocol: "https:",
22558
- hostname: url.hostname,
22559
- port: url.port || 443,
22560
- path: `${url.pathname}${url.search}`,
22561
- method: "POST",
22562
- headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
22563
- servername: net.isIP(url.hostname) ? void 0 : url.hostname,
22564
- timeout: timeoutMs,
22565
- // Pinned to the address that passed the check: no second lookup.
22566
- lookup: (_hostname, options, callback) => {
22567
- if (options && options.all) callback(null, [address]);
22568
- else callback(null, address.address, address.family);
22569
- }
22570
- },
22571
- (response) => {
22572
- let received = 0;
22573
- response.on("data", (chunk) => {
22574
- received += chunk.length;
22575
- if (received > MAX_RESPONSE_BYTES) response.destroy();
22576
- });
22577
- response.on("end", () => resolve(response.statusCode || 0));
22578
- response.on("close", () => resolve(response.statusCode || 0));
22579
- response.on("error", () => resolve(response.statusCode || 0));
23630
+ async function loadAppUsers(documentIds, ability) {
23631
+ const users = /* @__PURE__ */ new Map();
23632
+ if (!strapi2.contentTypes?.[USER_UID]) return { users, visible: false };
23633
+ let checker = null;
23634
+ if (ability) {
23635
+ try {
23636
+ const checkers = strapi2.plugin("content-manager")?.service("permission-checker");
23637
+ const candidate = checkers?.create({ userAbility: ability, model: USER_UID }) || null;
23638
+ checker = candidate && !candidate.cannot.read() ? candidate : null;
23639
+ } catch {
23640
+ checker = null;
22580
23641
  }
22581
- );
22582
- request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
22583
- request.on(
22584
- "error",
22585
- (err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
22586
- );
22587
- request.end(body);
22588
- });
22589
- }
22590
- async function deliverOnce({
22591
- url,
22592
- body,
22593
- headers,
22594
- resolve = resolveAll,
22595
- post = httpsPost,
22596
- timeoutMs = TIMEOUT_MS
22597
- }) {
22598
- let parsed;
22599
- try {
22600
- parsed = new URL(url);
22601
- } catch {
22602
- throw new DeliveryError("invalid_url", false);
22603
- }
22604
- if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
22605
- throw new DeliveryError("invalid_url", false);
22606
- }
22607
- const host = parsed.hostname.replace(/^\[|\]$/g, "");
22608
- let addresses;
22609
- if (net.isIP(host)) {
22610
- addresses = [{ address: host, family: net.isIP(host) }];
22611
- } else {
22612
- try {
22613
- addresses = await resolve(host);
22614
- } catch {
22615
- throw new DeliveryError("dns_failed", true);
22616
23642
  }
22617
- }
22618
- if (!Array.isArray(addresses) || addresses.length === 0)
22619
- throw new DeliveryError("dns_failed", true);
22620
- if (addresses.some((entry) => isBlockedAddress(entry.address))) {
22621
- throw new DeliveryError("address_not_allowed", false);
22622
- }
22623
- const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
22624
- if (status >= 200 && status < 300) return { status };
22625
- if (status >= 300 && status < 400)
22626
- throw new DeliveryError("redirect_not_followed", false, status);
22627
- throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
22628
- }
22629
- function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
22630
- const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
22631
- return {
22632
- id,
22633
- body,
22634
- headers: {
22635
- "Content-Type": "application/json",
22636
- "User-Agent": USER_AGENT,
22637
- [EVENT_HEADER]: event,
22638
- [DELIVERY_HEADER]: id,
22639
- [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
22640
- }
22641
- };
22642
- }
22643
- async function deliverWithRetries({
22644
- delays = RETRY_DELAYS_MS,
22645
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
22646
- ...request
22647
- }) {
22648
- let attempts = 0;
22649
- let last = { ok: false, status: null, code: "not_sent" };
22650
- for (const delay of delays) {
22651
- if (delay > 0) await sleep(delay);
22652
- attempts += 1;
22653
- try {
22654
- const { status } = await deliverOnce(request);
22655
- return { ok: true, status, code: null, attempts };
22656
- } catch (err) {
22657
- const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
22658
- last = { ok: false, status: error.status, code: error.code };
22659
- if (!error.retryable) break;
23643
+ const ids = [
23644
+ ...new Set(
23645
+ documentIds.filter((id) => typeof id === "string" && /^[A-Za-z0-9]{1,64}$/.test(id))
23646
+ )
23647
+ ];
23648
+ if (!ids.length) return { users, visible: Boolean(checker) };
23649
+ const attributes = strapi2.contentTypes[USER_UID].attributes || {};
23650
+ const found = await strapi2.db.query(USER_UID).findMany({
23651
+ select: ["id", "documentId", "email", "username"],
23652
+ where: { documentId: { $in: ids } },
23653
+ ...attributes.createdBy ? { populate: { createdBy: { select: ["id"] } } } : {},
23654
+ limit: ids.length * 2
23655
+ });
23656
+ for (const user of Array.isArray(found) ? found : []) {
23657
+ const may = (field) => {
23658
+ if (!checker) return false;
23659
+ try {
23660
+ return checker.can.read(user, field) === true;
23661
+ } catch {
23662
+ return false;
23663
+ }
23664
+ };
23665
+ const email = may("email") && typeof user.email === "string" ? user.email : "";
23666
+ const username = may("username") && typeof user.username === "string" ? user.username : "";
23667
+ users.set(String(user.documentId), {
23668
+ id: Number(user.id),
23669
+ documentId: String(user.documentId),
23670
+ email: email.slice(0, 254),
23671
+ username: username.slice(0, 200)
23672
+ });
22660
23673
  }
23674
+ return { users, visible: Boolean(checker) };
22661
23675
  }
22662
- return { ...last, attempts };
22663
- }
22664
- module.exports = {
22665
- DELIVERY_HEADER,
22666
- DeliveryError,
22667
- EVENT_HEADER,
22668
- RETRY_DELAYS_MS,
22669
- SIGNATURE_HEADER,
22670
- buildSignedRequest,
22671
- deliverOnce,
22672
- deliverWithRetries,
22673
- isBlockedAddress,
22674
- signPayload,
22675
- verifySignature
23676
+ async function shapeUserEvents(rows, viewer, options) {
23677
+ const list = rows.filter((row) => USER_ACTIVITY_EVENTS.includes(row.event));
23678
+ const { users, visible } = await loadAppUsers(
23679
+ list.filter((row) => row.targetType === "user").map((row) => row.targetId),
23680
+ viewer.ability || null
23681
+ );
23682
+ const admins = await loadAdmins(
23683
+ list.filter((row) => row.actorType === "admin").map((row) => row.actorId)
23684
+ );
23685
+ const data = list.map((row) => {
23686
+ const byAdmin = row.actorType === "admin";
23687
+ const userAgent = !byAdmin && typeof row.userAgent === "string" && row.userAgent ? row.userAgent : null;
23688
+ const described = describeUserAgent(userAgent);
23689
+ const address = byAdmin ? { ipAddress: null, ipAnonymized: false, keepLocation: false } : userEventAddress(row, options, (ip) => anonymizeIp(normalizeIp(ip)));
23690
+ const user = row.targetType === "user" && typeof row.targetId === "string" ? users.get(row.targetId) || null : null;
23691
+ const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
23692
+ let actor = null;
23693
+ if (row.actorType === "system") actor = { type: "system", id: null, name: "" };
23694
+ else if (row.actorType === "admin" && toAdminId(row.actorId)) {
23695
+ actor = {
23696
+ type: "admin",
23697
+ id: Number(row.actorId),
23698
+ name: admin && viewer.canReadAdmins === true ? adminName(admin) : ""
23699
+ };
23700
+ }
23701
+ return {
23702
+ id: Number(row.id),
23703
+ event: row.event,
23704
+ at: toIso(row.createdAt),
23705
+ target: row.targetType === "ip" ? "ip" : "user",
23706
+ user,
23707
+ actor,
23708
+ details: userEventFacts(row.event, row.meta, viewer),
23709
+ ipAddress: address.ipAddress,
23710
+ ipAnonymized: address.ipAnonymized,
23711
+ location: address.keepLocation ? toLocation(row.geo) : null,
23712
+ browser: described.browserName,
23713
+ os: described.osName,
23714
+ deviceType: described.deviceType,
23715
+ userAgent: userAgent ? userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null
23716
+ };
23717
+ });
23718
+ return { data, usersVisible: visible };
23719
+ }
23720
+ return service;
22676
23721
  };
23722
+ module.exports.EVENT_UID = EVENT_UID;
23723
+ module.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
22677
23724
  }
22678
23725
  });
22679
23726
 
@@ -22955,12 +24002,14 @@ var require_rate_limit = __commonJS({
22955
24002
  "use strict";
22956
24003
  var { getPluginSettings } = require_settings_loader();
22957
24004
  var { getCoordinator, hashedKey, __resetMemoryForTests } = require_coordination();
24005
+ var { ipBucket } = require_admin_request_info();
22958
24006
  var callerKey = (ctx) => {
22959
24007
  const userId = ctx.state?.user?.id;
22960
24008
  if (userId) return `u:${userId}`;
22961
24009
  const tokenId = ctx.state?.auth?.credentials?.id ?? ctx.state?.auth?.credentials?.token ?? null;
22962
24010
  if (tokenId) return `t:${String(tokenId).slice(-16)}`;
22963
- return `ip:${ctx.request.ip || ctx.ip || "unknown"}`;
24011
+ const ip = ctx.request.ip || ctx.ip || "";
24012
+ return `ip:${ipBucket(ip) || ip || "unknown"}`;
22964
24013
  };
22965
24014
  var routeKey = (ctx) => {
22966
24015
  const route = ctx.state?.route;