strapi-plugin-magic-sessionmanager 4.17.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +78 -18
  3. package/dist/admin/{Analytics-BTIByTUY.js → Analytics-C8fV6LDV.js} +1 -1
  4. package/dist/admin/{Analytics-B-p2Q7th.mjs → Analytics-CBspdl1I.mjs} +1 -1
  5. package/dist/admin/{App-CH6635JB.js → App-D92MTQmn.js} +2 -2
  6. package/dist/admin/{App-DmesuM2g.mjs → App-PLwqaRSQ.mjs} +2 -2
  7. package/dist/admin/{OnlineUsersWidget-TlOp8nie.js → OnlineUsersWidget-CiKapC1B.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-CuqeQ0tb.mjs → OnlineUsersWidget-CwfBJdIX.mjs} +1 -1
  9. package/dist/admin/{Settings-C4IgGBjQ.mjs → Settings-CMgL-Aub.mjs} +866 -38
  10. package/dist/admin/{Settings-DtP_H4JS.js → Settings-Duil_4jv.js} +866 -38
  11. package/dist/admin/{dashboardModel-0ROcWcB1.mjs → dashboardModel-BhUonEqc.mjs} +1 -1
  12. package/dist/admin/{dashboardModel-BSJhZdXI.js → dashboardModel-sksvIc1c.js} +1 -1
  13. package/dist/admin/{de-C_ooq6EF.js → de-CnInuvMY.js} +87 -3
  14. package/dist/admin/{de-BoahnYIP.mjs → de-D2BqfY1f.mjs} +87 -3
  15. package/dist/admin/{en-DHme92L-.mjs → en-BPy208we.mjs} +87 -3
  16. package/dist/admin/{en-CuUVE2K0.js → en-KnmmYHTF.js} +87 -3
  17. package/dist/admin/{es-CjcTgS9Z.mjs → es-B4VNeT0A.mjs} +87 -3
  18. package/dist/admin/{es-lbDNXcQi.js → es-D1NGCAJK.js} +87 -3
  19. package/dist/admin/{fr-BPwnrSaC.mjs → fr-AwhLN1BC.mjs} +87 -3
  20. package/dist/admin/{fr-RtypjgGp.js → fr-D1KNyogi.js} +87 -3
  21. package/dist/admin/{index-B102RF2H.mjs → index-BmnC2BPs.mjs} +9 -9
  22. package/dist/admin/{index-w0OuPYFm.js → index-Bnt0Jq6O.js} +9 -9
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +1 -1
  25. package/dist/admin/{pt-D5FHSP2y.mjs → pt-D6m1TijL.mjs} +87 -3
  26. package/dist/admin/{pt-BMCAKRQ4.js → pt-EKThRXPY.js} +87 -3
  27. package/dist/server/index.js +1686 -26
  28. package/dist/server/index.mjs +1686 -26
  29. package/package.json +1 -1
@@ -252,6 +252,11 @@ var require_coordination = __commonJS({
252
252
  async registryDelete(key) {
253
253
  registry.delete(key);
254
254
  },
255
+ async registryTake(key, now = Date.now()) {
256
+ const entry = registry.get(key);
257
+ registry.delete(key);
258
+ return entry && entry.expiresAt > now ? entry.value : null;
259
+ },
255
260
  async prune(now = Date.now()) {
256
261
  let removed = 0;
257
262
  for (const [k, v] of registry) {
@@ -522,6 +527,21 @@ var require_coordination = __commonJS({
522
527
  async registryDelete(key) {
523
528
  await knex(TABLES.cache).where({ k: `reg:${key}` }).del();
524
529
  },
530
+ /**
531
+ * Reads and deletes an entry. Only the caller whose DELETE removed the
532
+ * row gets the value, so parallel takes of one key yield it once.
533
+ */
534
+ async registryTake(key, now = Date.now()) {
535
+ const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: `reg:${key}` }).first();
536
+ if (!row) return null;
537
+ const deleted = await knex(TABLES.cache).where({ k: `reg:${key}`, expires_at: row.expires_at }).del();
538
+ if (toNumber(deleted) !== 1 || toNumber(row.expires_at) <= now) return null;
539
+ try {
540
+ return JSON.parse(row.v);
541
+ } catch {
542
+ return null;
543
+ }
544
+ },
525
545
  async prune(now = Date.now()) {
526
546
  const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
527
547
  const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
@@ -748,6 +768,21 @@ var require_coordination = __commonJS({
748
768
  () => sharedMemory.registryList(prefix, limit)
749
769
  );
750
770
  },
771
+ /**
772
+ * Takes a listable entry once: returns its value and removes it. Of
773
+ * several concurrent takes (any process) at most one gets the value.
774
+ *
775
+ * @param {string} key Entry key.
776
+ * @returns {Promise<any|null>} Value, or null when absent, expired or taken.
777
+ */
778
+ registryTake(key) {
779
+ assertRegistryKey(key);
780
+ return run(
781
+ "registry take",
782
+ (backend) => backend.registryTake(key),
783
+ () => sharedMemory.registryTake(key)
784
+ );
785
+ },
751
786
  /** Removes a listable entry. */
752
787
  registryDelete(key) {
753
788
  assertRegistryKey(key);
@@ -910,7 +945,7 @@ var require_content_api_permissions = __commonJS({
910
945
  "server/src/utils/content-api-permissions.js"(exports2, module2) {
911
946
  "use strict";
912
947
  var { withPluginStoreKey } = require_plugin_store();
913
- var CONTENT_API_PERMISSIONS_VERSION = 2;
948
+ var CONTENT_API_PERMISSIONS_VERSION = 3;
914
949
  var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
915
950
  var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
916
951
  async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
@@ -1436,12 +1471,228 @@ var require_policy_settings = __commonJS({
1436
1471
  }
1437
1472
  });
1438
1473
 
1474
+ // server/src/utils/detection-settings.js
1475
+ var require_detection_settings = __commonJS({
1476
+ "server/src/utils/detection-settings.js"(exports2, module2) {
1477
+ "use strict";
1478
+ var WEBHOOK_EVENTS = Object.freeze([
1479
+ "login.success",
1480
+ "login.suspicious",
1481
+ "login.new_location",
1482
+ "login.new_device",
1483
+ "login.impossible_travel",
1484
+ "login.failed",
1485
+ "login.refused",
1486
+ "lockout",
1487
+ "lockout.lifted",
1488
+ "session.limit",
1489
+ "password.changed",
1490
+ "user.not_me"
1491
+ ]);
1492
+ var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
1493
+ "login.suspicious",
1494
+ "login.new_location",
1495
+ "login.new_device",
1496
+ "login.impossible_travel",
1497
+ "lockout",
1498
+ "user.not_me"
1499
+ ]);
1500
+ var LEGACY_WEBHOOK_EVENTS = Object.freeze([
1501
+ "login.success",
1502
+ "login.suspicious",
1503
+ "login.new_location"
1504
+ ]);
1505
+ var IMPOSSIBLE_TRAVEL_ACTIONS = Object.freeze(["alert", "reauthenticate"]);
1506
+ var DETECTION_DEFAULTS = Object.freeze({
1507
+ alertOnNewDevice: false,
1508
+ alertOnImpossibleTravel: false,
1509
+ impossibleTravelEnabled: false,
1510
+ impossibleTravelSpeedKmh: 1e3,
1511
+ impossibleTravelMinDistanceKm: 500,
1512
+ impossibleTravelAction: "alert",
1513
+ webhookEvents: DEFAULT_WEBHOOK_EVENTS,
1514
+ genericWebhookEnabled: false,
1515
+ genericWebhookUrl: "",
1516
+ sessionIpAnonymize: false
1517
+ });
1518
+ var DETECTION_KEYS = Object.freeze(Object.keys(DETECTION_DEFAULTS));
1519
+ var PROTECTED_DETECTION_KEYS = Object.freeze([
1520
+ "impossibleTravelEnabled",
1521
+ "impossibleTravelSpeedKmh",
1522
+ "impossibleTravelMinDistanceKm",
1523
+ "impossibleTravelAction",
1524
+ "webhookEvents",
1525
+ "genericWebhookEnabled",
1526
+ "genericWebhookUrl",
1527
+ "genericWebhookSecret",
1528
+ "sessionIpAnonymize"
1529
+ ]);
1530
+ var RANGES = Object.freeze({
1531
+ impossibleTravelSpeedKmh: Object.freeze([100, 5e3]),
1532
+ impossibleTravelMinDistanceKm: Object.freeze([50, 2e4])
1533
+ });
1534
+ var BOOLEAN_KEYS = Object.freeze([
1535
+ "alertOnNewDevice",
1536
+ "alertOnImpossibleTravel",
1537
+ "impossibleTravelEnabled",
1538
+ "genericWebhookEnabled",
1539
+ "sessionIpAnonymize"
1540
+ ]);
1541
+ var MAX_URL_LENGTH = 2048;
1542
+ function parseInteger(value) {
1543
+ if (typeof value === "number") return Number.isInteger(value) ? value : null;
1544
+ if (typeof value === "string" && /^\s*\d{1,9}\s*$/.test(value)) return Number.parseInt(value, 10);
1545
+ return null;
1546
+ }
1547
+ function normalizeWebhookUrl(value) {
1548
+ if (typeof value !== "string") return null;
1549
+ const trimmed = value.trim();
1550
+ if (!trimmed || trimmed.length > MAX_URL_LENGTH) return null;
1551
+ let parsed;
1552
+ try {
1553
+ parsed = new URL(trimmed);
1554
+ } catch {
1555
+ return null;
1556
+ }
1557
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) return null;
1558
+ const host = parsed.hostname.toLowerCase();
1559
+ if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
1560
+ return null;
1561
+ }
1562
+ return parsed.toString();
1563
+ }
1564
+ function normalizeEventList(value) {
1565
+ if (!Array.isArray(value)) return null;
1566
+ return [...new Set(value.filter((event) => WEBHOOK_EVENTS.includes(event)))];
1567
+ }
1568
+ function normalizeDetectionSettings(stored) {
1569
+ const out = {};
1570
+ if (!stored || typeof stored !== "object") return out;
1571
+ for (const key of BOOLEAN_KEYS) if (stored[key] !== void 0) out[key] = stored[key] === true;
1572
+ for (const [key, [min, max]] of Object.entries(RANGES)) {
1573
+ if (stored[key] === void 0) continue;
1574
+ const number = parseInteger(stored[key]);
1575
+ out[key] = number !== null && number >= min && number <= max ? number : (
1576
+ /** @type {any} */
1577
+ DETECTION_DEFAULTS[key]
1578
+ );
1579
+ }
1580
+ if (stored.impossibleTravelAction !== void 0) {
1581
+ out.impossibleTravelAction = IMPOSSIBLE_TRAVEL_ACTIONS.includes(
1582
+ /** @type {string} */
1583
+ stored.impossibleTravelAction
1584
+ ) ? stored.impossibleTravelAction : "alert";
1585
+ }
1586
+ if (stored.webhookEvents !== void 0) {
1587
+ out.webhookEvents = normalizeEventList(stored.webhookEvents) || [...DEFAULT_WEBHOOK_EVENTS];
1588
+ }
1589
+ if (stored.genericWebhookUrl !== void 0) {
1590
+ out.genericWebhookUrl = normalizeWebhookUrl(stored.genericWebhookUrl) || "";
1591
+ }
1592
+ return out;
1593
+ }
1594
+ function validateDetectionSettings(body) {
1595
+ const values = {};
1596
+ const errors = [];
1597
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
1598
+ for (const key of BOOLEAN_KEYS) {
1599
+ if (!has(key)) continue;
1600
+ if (typeof body[key] !== "boolean")
1601
+ errors.push({ path: [key], message: `${key} must be a boolean` });
1602
+ else values[key] = body[key];
1603
+ }
1604
+ for (const [key, [min, max]] of Object.entries(RANGES)) {
1605
+ if (!has(key)) continue;
1606
+ const number = parseInteger(body[key]);
1607
+ if (number === null || number < min || number > max) {
1608
+ errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
1609
+ } else {
1610
+ values[key] = number;
1611
+ }
1612
+ }
1613
+ if (has("impossibleTravelAction")) {
1614
+ if (!IMPOSSIBLE_TRAVEL_ACTIONS.includes(
1615
+ /** @type {string} */
1616
+ body.impossibleTravelAction
1617
+ )) {
1618
+ errors.push({
1619
+ path: ["impossibleTravelAction"],
1620
+ message: `impossibleTravelAction must be one of: ${IMPOSSIBLE_TRAVEL_ACTIONS.join(", ")}`
1621
+ });
1622
+ } else {
1623
+ values.impossibleTravelAction = body.impossibleTravelAction;
1624
+ }
1625
+ }
1626
+ if (has("webhookEvents")) {
1627
+ const list = body.webhookEvents;
1628
+ if (!Array.isArray(list) || list.length > WEBHOOK_EVENTS.length || list.some((event) => !WEBHOOK_EVENTS.includes(event))) {
1629
+ errors.push({
1630
+ path: ["webhookEvents"],
1631
+ message: `webhookEvents must be a list of: ${WEBHOOK_EVENTS.join(", ")}`
1632
+ });
1633
+ } else {
1634
+ values.webhookEvents = [...new Set(list)];
1635
+ }
1636
+ }
1637
+ if (has("genericWebhookUrl")) {
1638
+ const raw = body.genericWebhookUrl;
1639
+ if (typeof raw !== "string") {
1640
+ errors.push({ path: ["genericWebhookUrl"], message: "genericWebhookUrl must be a string" });
1641
+ } else if (!raw.trim()) {
1642
+ values.genericWebhookUrl = "";
1643
+ } else {
1644
+ const url = normalizeWebhookUrl(raw);
1645
+ if (!url) {
1646
+ errors.push({
1647
+ path: ["genericWebhookUrl"],
1648
+ message: "genericWebhookUrl must be an https URL without credentials on a public host name"
1649
+ });
1650
+ } else {
1651
+ values.genericWebhookUrl = url;
1652
+ }
1653
+ }
1654
+ }
1655
+ return { values, errors };
1656
+ }
1657
+ function resolveDetectionSettings(settings) {
1658
+ const source = settings && typeof settings === "object" ? settings : {};
1659
+ const clean = normalizeDetectionSettings(
1660
+ Object.fromEntries(
1661
+ DETECTION_KEYS.map((key) => [key, source[key]]).filter(([, v]) => v !== void 0)
1662
+ )
1663
+ );
1664
+ return (
1665
+ /** @type {any} */
1666
+ {
1667
+ ...DETECTION_DEFAULTS,
1668
+ webhookEvents: [...DEFAULT_WEBHOOK_EVENTS],
1669
+ ...clean
1670
+ }
1671
+ );
1672
+ }
1673
+ module2.exports = {
1674
+ DEFAULT_WEBHOOK_EVENTS,
1675
+ DETECTION_DEFAULTS,
1676
+ DETECTION_KEYS,
1677
+ PROTECTED_DETECTION_KEYS,
1678
+ IMPOSSIBLE_TRAVEL_ACTIONS,
1679
+ LEGACY_WEBHOOK_EVENTS,
1680
+ WEBHOOK_EVENTS,
1681
+ normalizeDetectionSettings,
1682
+ normalizeWebhookUrl,
1683
+ resolveDetectionSettings,
1684
+ validateDetectionSettings
1685
+ };
1686
+ }
1687
+ });
1688
+
1439
1689
  // server/src/utils/settings-loader.js
1440
1690
  var require_settings_loader = __commonJS({
1441
1691
  "server/src/utils/settings-loader.js"(exports2, module2) {
1442
1692
  "use strict";
1443
1693
  var { getCoordinator } = require_coordination();
1444
1694
  var { normalizePolicySettings } = require_policy_settings();
1695
+ var { normalizeDetectionSettings } = require_detection_settings();
1445
1696
  var PLUGIN_ID = "magic-sessionmanager";
1446
1697
  var SETTINGS_KEY = "settings";
1447
1698
  var CACHE_TTL_MS = 30 * 1e3;
@@ -1574,6 +1825,10 @@ var require_settings_loader = __commonJS({
1574
1825
  out.trustedProxies = stored.trustedProxies;
1575
1826
  }
1576
1827
  Object.assign(out, normalizePolicySettings(stored));
1828
+ Object.assign(out, normalizeDetectionSettings(stored));
1829
+ if (typeof stored.genericWebhookSecret === "string") {
1830
+ out.genericWebhookSecret = stored.genericWebhookSecret;
1831
+ }
1577
1832
  return out;
1578
1833
  }
1579
1834
  async function getPluginSettings(strapi2) {
@@ -1691,7 +1946,11 @@ var require_security_log_model = __commonJS({
1691
1946
  USER_LOCKOUT: "user.lockout",
1692
1947
  USER_LOCKOUT_LIFTED: "user.lockout.lifted",
1693
1948
  USER_SESSION_LIMIT: "user.session.limit",
1694
- USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others"
1949
+ USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others",
1950
+ USER_NEW_DEVICE: "user.sign-in.new-device",
1951
+ USER_IMPOSSIBLE_TRAVEL: "user.sign-in.impossible-travel",
1952
+ USER_NOT_ME: "user.not-me",
1953
+ USER_DATA_EXPORTED: "user.data.exported"
1695
1954
  });
1696
1955
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
1697
1956
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
@@ -2441,7 +2700,13 @@ var require_encryption = __commonJS({
2441
2700
  function getEncryptionKeyCheck() {
2442
2701
  return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
2443
2702
  }
2703
+ function derivePurposeKey(purpose) {
2704
+ return Buffer.from(
2705
+ crypto.hkdfSync("sha256", getEncryptionKey(), "magic-sessionmanager", `msm:${purpose}`, 32)
2706
+ );
2707
+ }
2444
2708
  module2.exports = {
2709
+ derivePurposeKey,
2445
2710
  getEncryptionKeyCheck,
2446
2711
  encryptToken,
2447
2712
  decryptToken,
@@ -2703,13 +2968,15 @@ var require_login_alerts = __commonJS({
2703
2968
  "server/src/utils/login-alerts.js"(exports2, module2) {
2704
2969
  "use strict";
2705
2970
  var { evaluateLoginRisk } = require_risk_data();
2971
+ var { resolveDetectionSettings } = require_detection_settings();
2706
2972
  async function dispatchLoginAlerts({
2707
2973
  settings,
2708
2974
  notificationService,
2709
2975
  user,
2710
2976
  session,
2711
2977
  geoData,
2712
- isNewLocation = false
2978
+ isNewLocation = false,
2979
+ webhooks = null
2713
2980
  }) {
2714
2981
  const attempted = { webhookEvent: null, emails: [] };
2715
2982
  if (!geoData) return attempted;
@@ -2743,8 +3010,22 @@ var require_login_alerts = __commonJS({
2743
3010
  await notificationService.sendNewLocationAlert({ user, session, geoData });
2744
3011
  }
2745
3012
  }
2746
- if (settings.enableWebhooks) {
2747
- const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
3013
+ const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
3014
+ const selected = resolveDetectionSettings(settings).webhookEvents.includes(webhookEvent);
3015
+ if (selected && webhooks) {
3016
+ webhooks.emit(
3017
+ webhookEvent,
3018
+ {
3019
+ userId: user?.documentId || null,
3020
+ ip: session?.ipAddress || null,
3021
+ userAgent: session?.userAgent || null,
3022
+ geo: geoData,
3023
+ details: null
3024
+ },
3025
+ { chat: false }
3026
+ );
3027
+ }
3028
+ if (settings.enableWebhooks && selected) {
2748
3029
  attempted.webhookEvent = webhookEvent;
2749
3030
  const targets = [];
2750
3031
  if (settings.discordWebhookUrl) {
@@ -4259,6 +4540,10 @@ var require_sign_in_policies = __commonJS({
4259
4540
  return options.anonymizeIp ? anonymizeIp(normalized) : normalized;
4260
4541
  }
4261
4542
  function recordUserEvent(strapi2, input) {
4543
+ try {
4544
+ strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(input);
4545
+ } catch {
4546
+ }
4262
4547
  try {
4263
4548
  return strapi2.plugin("magic-sessionmanager").service("security-log").record(input) === true;
4264
4549
  } catch {
@@ -4378,6 +4663,7 @@ var require_upgrade_defaults = __commonJS({
4378
4663
  "use strict";
4379
4664
  var { withPluginStoreKey } = require_plugin_store();
4380
4665
  var { notifySettingsChanged } = require_settings_loader();
4666
+ var { LEGACY_WEBHOOK_EVENTS } = require_detection_settings();
4381
4667
  var PROFILE_KEY = "defaultsProfile";
4382
4668
  var UPGRADE_STEPS = Object.freeze([
4383
4669
  Object.freeze({
@@ -4385,6 +4671,13 @@ var require_upgrade_defaults = __commonJS({
4385
4671
  release: "4.17.0",
4386
4672
  // Before 4.17 a password change kept the user's other sessions.
4387
4673
  legacy: Object.freeze({ endOtherSessionsOnPasswordChange: false })
4674
+ }),
4675
+ Object.freeze({
4676
+ version: 2,
4677
+ release: "sign-in signals and signed webhook",
4678
+ // Before, Discord and Slack received every sign-in (success, new
4679
+ // country, suspicious). New installations leave out every sign-in.
4680
+ legacy: Object.freeze({ webhookEvents: LEGACY_WEBHOOK_EVENTS })
4388
4681
  })
4389
4682
  ]);
4390
4683
  async function applyUpgradeDefaults(strapi2, log, steps = UPGRADE_STEPS) {
@@ -4406,7 +4699,7 @@ var require_upgrade_defaults = __commonJS({
4406
4699
  if (step.version <= profile) continue;
4407
4700
  for (const [key, value] of Object.entries(step.legacy)) {
4408
4701
  if (settings[key] !== void 0) continue;
4409
- settings[key] = value;
4702
+ settings[key] = Array.isArray(value) ? [...value] : value;
4410
4703
  applied.push(key);
4411
4704
  }
4412
4705
  }
@@ -4427,6 +4720,270 @@ var require_upgrade_defaults = __commonJS({
4427
4720
  }
4428
4721
  });
4429
4722
 
4723
+ // server/src/utils/not-me-link.js
4724
+ var require_not_me_link = __commonJS({
4725
+ "server/src/utils/not-me-link.js"(exports2, module2) {
4726
+ "use strict";
4727
+ var crypto = require("node:crypto");
4728
+ var { derivePurposeKey } = require_encryption();
4729
+ var LIFETIME_MS = 72 * 60 * 60 * 1e3;
4730
+ var NONCE_PREFIX = "notme:";
4731
+ var DOCUMENT_ID = /^[A-Za-z0-9]{1,64}$/;
4732
+ var TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,400}\.[A-Za-z0-9_-]{43}$/;
4733
+ var signingKey = () => derivePurposeKey("not-me-link");
4734
+ var sign = (payload) => crypto.createHmac("sha256", signingKey()).update(payload).digest("base64url");
4735
+ async function issueNotMeToken(coordinator, { sessionId, userId, now = Date.now() }) {
4736
+ if (!DOCUMENT_ID.test(String(sessionId)) || !DOCUMENT_ID.test(String(userId))) return null;
4737
+ const nonce = crypto.randomBytes(18).toString("hex");
4738
+ const payload = Buffer.from(
4739
+ JSON.stringify({ s: sessionId, u: userId, e: now + LIFETIME_MS, n: nonce })
4740
+ ).toString("base64url");
4741
+ await coordinator.registryPut(
4742
+ `${NONCE_PREFIX}${nonce}`,
4743
+ { s: sessionId, u: userId },
4744
+ LIFETIME_MS
4745
+ );
4746
+ return `${payload}.${sign(payload)}`;
4747
+ }
4748
+ function readNotMeToken(token, { now = Date.now() } = {}) {
4749
+ if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) return null;
4750
+ const [payload, signature] = token.split(".");
4751
+ const expected = Buffer.from(sign(payload));
4752
+ const given = Buffer.from(signature);
4753
+ if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null;
4754
+ let claims;
4755
+ try {
4756
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
4757
+ } catch {
4758
+ return null;
4759
+ }
4760
+ if (!claims || !DOCUMENT_ID.test(String(claims.s)) || !DOCUMENT_ID.test(String(claims.u)) || !/^[a-f0-9]{36}$/.test(String(claims.n)) || !Number.isFinite(claims.e) || claims.e <= now) {
4761
+ return null;
4762
+ }
4763
+ return { sessionId: claims.s, userId: claims.u, nonce: claims.n, expiresAt: claims.e };
4764
+ }
4765
+ async function consumeNotMeToken(coordinator, token) {
4766
+ const claims = readNotMeToken(token);
4767
+ if (!claims) return null;
4768
+ const stored = await coordinator.registryTake(`${NONCE_PREFIX}${claims.nonce}`);
4769
+ if (!stored || stored.s !== claims.sessionId || stored.u !== claims.userId) return null;
4770
+ return { sessionId: claims.sessionId, userId: claims.userId };
4771
+ }
4772
+ module2.exports = { LIFETIME_MS, consumeNotMeToken, issueNotMeToken, readNotMeToken };
4773
+ }
4774
+ });
4775
+
4776
+ // server/src/utils/sign-in-signals.js
4777
+ var require_sign_in_signals = __commonJS({
4778
+ "server/src/utils/sign-in-signals.js"(exports2, module2) {
4779
+ "use strict";
4780
+ var crypto = require("node:crypto");
4781
+ var { derivePurposeKey } = require_encryption();
4782
+ var { parseUserAgent } = require_user_agent_parser();
4783
+ var { getCoordinator } = require_coordination();
4784
+ var { normalizeApiPrefix } = require_auth_routes();
4785
+ var { resolveDetectionSettings } = require_detection_settings();
4786
+ var { issueNotMeToken } = require_not_me_link();
4787
+ var { SECURITY_EVENTS } = require_security_log_model();
4788
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
4789
+ var HISTORY = 50;
4790
+ var EARTH_RADIUS_KM = 6371.0088;
4791
+ function deviceFamilies(userAgent) {
4792
+ const parsed = parseUserAgent(typeof userAgent === "string" ? userAgent.slice(0, 500) : "");
4793
+ return {
4794
+ browser: String(parsed.browserName || "unknown"),
4795
+ os: String(parsed.osName || "unknown"),
4796
+ deviceType: String(parsed.deviceType || "unknown")
4797
+ };
4798
+ }
4799
+ function family(value) {
4800
+ return String(value || "unknown").replace(/\s+[\d.]+$/, "").trim();
4801
+ }
4802
+ function deviceKeyOf(userAgent, deviceId) {
4803
+ const { browser, os, deviceType } = deviceFamilies(userAgent);
4804
+ const id = typeof deviceId === "string" && deviceId.length <= 128 ? deviceId : "";
4805
+ return crypto.createHmac("sha256", derivePurposeKey("device")).update(`${browser}|${os}|${deviceType}|${id}`).digest("hex").slice(0, 32);
4806
+ }
4807
+ function requestDeviceId(ctx) {
4808
+ const value = ctx?.request?.body?.deviceId;
4809
+ return typeof value === "string" && value && value.length <= 128 ? value : null;
4810
+ }
4811
+ function distanceKm(a, b) {
4812
+ const rad = (deg) => deg * Math.PI / 180;
4813
+ const dLat = rad(b.lat - a.lat);
4814
+ const dLon = rad(b.lon - a.lon);
4815
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
4816
+ return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)));
4817
+ }
4818
+ function pointOf(geo) {
4819
+ const lat = Number(geo?.latitude);
4820
+ const lon = Number(geo?.longitude);
4821
+ if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
4822
+ return null;
4823
+ }
4824
+ if (geo?.latitude === null || geo?.longitude === null) return null;
4825
+ return { lat: Math.round(lat * 10) / 10, lon: Math.round(lon * 10) / 10 };
4826
+ }
4827
+ function evaluateTravel(previous, current, { speedKmh, minDistanceKm }) {
4828
+ if (!previous?.point || !current?.point) return null;
4829
+ const km = distanceKm(previous.point, current.point);
4830
+ const hours = Math.max(current.at - previous.at, 60 * 1e3) / (60 * 60 * 1e3);
4831
+ const speed = km / hours;
4832
+ return {
4833
+ flagged: km >= minDistanceKm && speed > speedKmh,
4834
+ distanceKm: Math.round(km),
4835
+ speedKmh: Math.round(speed)
4836
+ };
4837
+ }
4838
+ async function previousSessions(strapi2, userDocumentId, exceptSessionId) {
4839
+ const rows = await strapi2.documents(SESSION_UID).findMany({
4840
+ filters: { user: { documentId: userDocumentId }, documentId: { $ne: exceptSessionId } },
4841
+ fields: [
4842
+ "documentId",
4843
+ "loginTime",
4844
+ "deviceKey",
4845
+ "browserName",
4846
+ "osName",
4847
+ "deviceType",
4848
+ "geoLocation"
4849
+ ],
4850
+ sort: [{ loginTime: "desc" }, { id: "desc" }],
4851
+ limit: HISTORY
4852
+ });
4853
+ return Array.isArray(rows) ? rows : [];
4854
+ }
4855
+ function isNewDevice(previous, { deviceKey, userAgent }) {
4856
+ if (previous.length === 0) return false;
4857
+ if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
4858
+ const families = deviceFamilies(userAgent);
4859
+ return !previous.some(
4860
+ (row) => !row.deviceKey && family(row.browserName) === families.browser && family(row.osName) === families.os
4861
+ );
4862
+ }
4863
+ function storedLocation(row) {
4864
+ let geo = row?.geoLocation;
4865
+ if (typeof geo === "string") {
4866
+ try {
4867
+ geo = JSON.parse(geo);
4868
+ } catch {
4869
+ geo = null;
4870
+ }
4871
+ }
4872
+ return {
4873
+ point: pointOf(geo),
4874
+ country: typeof geo?.country_code === "string" ? geo.country_code : null
4875
+ };
4876
+ }
4877
+ async function notMeUrl(strapi2, sessionId, userId) {
4878
+ const base = String(strapi2.config.get("server.absoluteUrl") || "").replace(/\/+$/, "");
4879
+ if (!/^https?:\/\/[^/]+/.test(base)) return null;
4880
+ const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
4881
+ if (!token) return null;
4882
+ const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
4883
+ return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
4884
+ }
4885
+ async function runSignInSignals({
4886
+ strapi: strapi2,
4887
+ settings,
4888
+ user,
4889
+ userDocumentId,
4890
+ session,
4891
+ geoData,
4892
+ deviceKey,
4893
+ userAgent,
4894
+ ip,
4895
+ record,
4896
+ now = Date.now()
4897
+ }) {
4898
+ const outcome = { newDevice: false, travel: null, reauthenticate: false };
4899
+ const detection = resolveDetectionSettings(settings);
4900
+ const plugin = strapi2.plugin("magic-sessionmanager");
4901
+ const emails = settings.enableEmailAlerts === true;
4902
+ const hasWebhookTarget = detection.genericWebhookEnabled && !!detection.genericWebhookUrl || settings.enableWebhooks === true && !!(settings.discordWebhookUrl || settings.slackWebhookUrl);
4903
+ const wantNewDevice = emails && detection.alertOnNewDevice || hasWebhookTarget && detection.webhookEvents.includes("login.new_device");
4904
+ const wantTravel = detection.impossibleTravelEnabled;
4905
+ if (!wantNewDevice && !wantTravel || !session?.documentId) return outcome;
4906
+ const previous = await previousSessions(strapi2, userDocumentId, session.documentId);
4907
+ const families = deviceFamilies(userAgent);
4908
+ let link;
4909
+ const linkOnce = async () => {
4910
+ if (link === void 0) link = await notMeUrl(strapi2, session.documentId, userDocumentId);
4911
+ return link;
4912
+ };
4913
+ const notifications = plugin.service("notifications");
4914
+ const facts = { user, session, geoData, device: { browser: families.browser, os: families.os } };
4915
+ if (wantNewDevice && isNewDevice(previous, { deviceKey, userAgent })) {
4916
+ outcome.newDevice = true;
4917
+ record({
4918
+ event: SECURITY_EVENTS.USER_NEW_DEVICE,
4919
+ actorType: "user",
4920
+ actorId: userDocumentId,
4921
+ targetType: "user",
4922
+ targetId: userDocumentId,
4923
+ ip,
4924
+ userAgent,
4925
+ meta: { browser: families.browser, os: families.os, deviceType: families.deviceType }
4926
+ });
4927
+ if (emails && detection.alertOnNewDevice) {
4928
+ const url = await linkOnce();
4929
+ notifications.sendSignInSignalEmail("newDevice", { ...facts, link: url }).catch(() => {
4930
+ });
4931
+ }
4932
+ }
4933
+ if (wantTravel) {
4934
+ const before = previous.find((row) => storedLocation(row).point);
4935
+ const result = before ? evaluateTravel(
4936
+ { point: storedLocation(before).point, at: new Date(before.loginTime).getTime() },
4937
+ { point: pointOf(geoData), at: now },
4938
+ {
4939
+ speedKmh: detection.impossibleTravelSpeedKmh,
4940
+ minDistanceKm: detection.impossibleTravelMinDistanceKm
4941
+ }
4942
+ ) : null;
4943
+ if (result?.flagged) {
4944
+ outcome.travel = result;
4945
+ record({
4946
+ event: SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
4947
+ actorType: "user",
4948
+ actorId: userDocumentId,
4949
+ targetType: "user",
4950
+ targetId: userDocumentId,
4951
+ ip,
4952
+ userAgent,
4953
+ meta: {
4954
+ distanceKm: result.distanceKm,
4955
+ speedKmh: result.speedKmh,
4956
+ from: storedLocation(before).country,
4957
+ to: typeof geoData?.country_code === "string" ? geoData.country_code : null,
4958
+ action: detection.impossibleTravelAction
4959
+ }
4960
+ });
4961
+ if (emails && detection.alertOnImpossibleTravel) {
4962
+ const url = await linkOnce();
4963
+ notifications.sendSignInSignalEmail("impossibleTravel", { ...facts, travel: result, link: url }).catch(() => {
4964
+ });
4965
+ }
4966
+ outcome.reauthenticate = detection.impossibleTravelAction === "reauthenticate";
4967
+ }
4968
+ }
4969
+ return outcome;
4970
+ }
4971
+ module2.exports = {
4972
+ notMeUrl,
4973
+ runSignInSignals,
4974
+ deviceFamilies,
4975
+ deviceKeyOf,
4976
+ distanceKm,
4977
+ evaluateTravel,
4978
+ isNewDevice,
4979
+ pointOf,
4980
+ previousSessions,
4981
+ requestDeviceId,
4982
+ storedLocation
4983
+ };
4984
+ }
4985
+ });
4986
+
4430
4987
  // server/src/middlewares/session-rejection-headers.js
4431
4988
  var require_session_rejection_headers = __commonJS({
4432
4989
  "server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
@@ -8570,6 +9127,7 @@ var require_bootstrap = __commonJS({
8570
9127
  } = require_sign_in_policies();
8571
9128
  var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
8572
9129
  var { applyUpgradeDefaults } = require_upgrade_defaults();
9130
+ var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
8573
9131
  var { anonymizeIp, normalizeIp } = require_admin_request_info();
8574
9132
  var SESSION_UID = "plugin::magic-sessionmanager.session";
8575
9133
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -9209,6 +9767,13 @@ var require_bootstrap = __commonJS({
9209
9767
  };
9210
9768
  return byName[err?.name] || 500;
9211
9769
  }
9770
+ function optionalService(strapi2, name) {
9771
+ try {
9772
+ return strapi2.plugin("magic-sessionmanager").service(name) || null;
9773
+ } catch {
9774
+ return null;
9775
+ }
9776
+ }
9212
9777
  function refuseSessionLimit({ ctx, strapi: strapi2, limit }) {
9213
9778
  stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
9214
9779
  ctx.status = 403;
@@ -9432,6 +9997,7 @@ var require_bootstrap = __commonJS({
9432
9997
  const geoData = ctx.state?.__magicSessionGeoData || null;
9433
9998
  const requestSettings = await getPluginSettings(strapi2);
9434
9999
  const isReset = isPasswordResetRequest(apiPath, ctx.method);
10000
+ const deviceKey = deviceKeyOf(userAgent, requestDeviceId(ctx));
9435
10001
  const create = () => sessionService.createSession({
9436
10002
  userId: userDocId,
9437
10003
  ip,
@@ -9439,6 +10005,7 @@ var require_bootstrap = __commonJS({
9439
10005
  token: ctx.body.jwt,
9440
10006
  refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
9441
10007
  geoData,
10008
+ deviceKey,
9442
10009
  ...nativeSession ? { nativeSessionId: nativeSession.sessionId } : {}
9443
10010
  });
9444
10011
  const limited = isReset ? { session: await create(), refused: false, ended: 0, limit: 0 } : await createSessionWithinLimit({
@@ -9488,9 +10055,45 @@ var require_bootstrap = __commonJS({
9488
10055
  log.info("[PASSWORD] Ended older sessions after password reset");
9489
10056
  }
9490
10057
  log.info("[SUCCESS] End-user session metadata created");
10058
+ let signals = { reauthenticate: false };
10059
+ if (!isReset) {
10060
+ try {
10061
+ signals = await runSignInSignals({
10062
+ strapi: strapi2,
10063
+ settings: requestSettings,
10064
+ user,
10065
+ userDocumentId: userDocId,
10066
+ session: newSession,
10067
+ geoData,
10068
+ deviceKey,
10069
+ userAgent: userAgent === "unknown" ? null : userAgent,
10070
+ ip,
10071
+ record: (input) => recordUserEvent(strapi2, input)
10072
+ });
10073
+ } catch (signalErr) {
10074
+ log.warn("[SIGNALS] Sign-in signals failed (non-fatal):", signalErr?.name || "Error");
10075
+ }
10076
+ }
10077
+ if (signals.reauthenticate) {
10078
+ await sessionService.terminateSession({ userId: userDocId, reason: "manual" });
10079
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
10080
+ ctx.status = 401;
10081
+ ctx.body = {
10082
+ data: null,
10083
+ error: {
10084
+ status: 401,
10085
+ name: "UnauthorizedError",
10086
+ message: "Please sign in again.",
10087
+ details: { code: "REAUTHENTICATION_REQUIRED" }
10088
+ }
10089
+ };
10090
+ log.info("[SIGNALS] Impossible travel: every session ended, a new sign-in is required");
10091
+ return;
10092
+ }
9491
10093
  try {
9492
10094
  const settings = await getPluginSettings(strapi2);
9493
- if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks)) {
10095
+ const genericWebhook = settings.genericWebhookEnabled === true;
10096
+ if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks || genericWebhook)) {
9494
10097
  return;
9495
10098
  }
9496
10099
  const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
@@ -9542,7 +10145,8 @@ var require_bootstrap = __commonJS({
9542
10145
  user,
9543
10146
  session: newSession,
9544
10147
  geoData,
9545
- isNewLocation
10148
+ isNewLocation,
10149
+ webhooks: optionalService(strapi2, "webhooks")
9546
10150
  });
9547
10151
  } catch (notifErr) {
9548
10152
  log.warn("Notification failed:", notifErr?.name || "Error");
@@ -9880,7 +10484,7 @@ var require_bootstrap = __commonJS({
9880
10484
  );
9881
10485
  return false;
9882
10486
  }
9883
- const requiredActions = [
10487
+ const baseActions = [
9884
10488
  "plugin::magic-sessionmanager.session.logout",
9885
10489
  "plugin::magic-sessionmanager.session.logoutAll",
9886
10490
  "plugin::magic-sessionmanager.session.logoutOthers",
@@ -9889,6 +10493,8 @@ var require_bootstrap = __commonJS({
9889
10493
  "plugin::magic-sessionmanager.session.getCurrentSession",
9890
10494
  "plugin::magic-sessionmanager.session.terminateOwnSession"
9891
10495
  ];
10496
+ const version3Actions = ["plugin::magic-sessionmanager.self-service.exportOwnData"];
10497
+ const requiredActions = Number(effectiveVersion) === 2 ? version3Actions : [...baseActions, ...version3Actions];
9892
10498
  const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
9893
10499
  filters: {
9894
10500
  role: authenticatedRole.id,
@@ -10403,6 +11009,11 @@ var require_destroy = __commonJS({
10403
11009
  }
10404
11010
  strapi2.sessionManagerAdminActivityUninstall = null;
10405
11011
  }
11012
+ try {
11013
+ strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
11014
+ } catch (err) {
11015
+ log.warn("Failed to stop webhook deliveries:", err?.name || "Error");
11016
+ }
10406
11017
  log.info("[SUCCESS] Plugin cleanup completed");
10407
11018
  };
10408
11019
  }
@@ -10617,6 +11228,12 @@ var require_schema = __commonJS({
10617
11228
  },
10618
11229
  osName: {
10619
11230
  type: "string"
11231
+ },
11232
+ deviceKey: {
11233
+ type: "string",
11234
+ maxLength: 64,
11235
+ configurable: false,
11236
+ private: true
10620
11237
  }
10621
11238
  }
10622
11239
  };
@@ -10857,6 +11474,57 @@ var require_content_api = __commonJS({
10857
11474
  description: "Get sessions by userId (user can only see own sessions)"
10858
11475
  }
10859
11476
  },
11477
+ // ================== SELF-SERVICE (4.17) ==================
11478
+ {
11479
+ method: "GET",
11480
+ path: "/my-data",
11481
+ handler: "self-service.exportOwnData",
11482
+ config: {
11483
+ auth: { strategies: ["users-permissions"] },
11484
+ // An export reads every own session and event: 3 per hour per user.
11485
+ middlewares: [
11486
+ {
11487
+ name: "plugin::magic-sessionmanager.rate-limit",
11488
+ config: { max: 3, window: 60 * 60 * 1e3 }
11489
+ }
11490
+ ],
11491
+ description: "Download own sessions and security events as JSON (GDPR Art. 15)"
11492
+ }
11493
+ },
11494
+ {
11495
+ method: "GET",
11496
+ path: "/not-me",
11497
+ handler: "self-service.notMePage",
11498
+ config: {
11499
+ // Public on purpose: opened from the "This wasn't me" email. Only
11500
+ // shows a confirmation; the signed token is checked, nothing changes.
11501
+ auth: false,
11502
+ middlewares: [
11503
+ {
11504
+ name: "plugin::magic-sessionmanager.rate-limit",
11505
+ config: { max: 30, window: 6e4 }
11506
+ }
11507
+ ],
11508
+ description: `Confirmation page of the "This wasn't me" email link (public)`
11509
+ }
11510
+ },
11511
+ {
11512
+ method: "POST",
11513
+ path: "/not-me",
11514
+ handler: "self-service.notMeConfirm",
11515
+ config: {
11516
+ // Public on purpose: the signed, expiring, single-use token from the
11517
+ // email is the authorisation.
11518
+ auth: false,
11519
+ middlewares: [
11520
+ {
11521
+ name: "plugin::magic-sessionmanager.rate-limit",
11522
+ config: { max: 10, window: 6e4 }
11523
+ }
11524
+ ],
11525
+ description: `End the session of a "This wasn't me" link (public, single-use token)`
11526
+ }
11527
+ },
10860
11528
  // ================== OWN SESSION MANAGEMENT ==================
10861
11529
  {
10862
11530
  method: "DELETE",
@@ -10882,6 +11550,7 @@ var require_admin = __commonJS({
10882
11550
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
10883
11551
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
10884
11552
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
11553
+ var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
10885
11554
  var adminPolicy = () => [
10886
11555
  "admin::isAuthenticatedAdmin",
10887
11556
  {
@@ -11166,15 +11835,32 @@ var require_admin = __commonJS({
11166
11835
  description: "List Users & Permissions roles for per-role rules (admin)"
11167
11836
  }
11168
11837
  },
11169
- // ============================ GEOLOCATION ============================
11838
+ // ============================ SIGNED WEBHOOK ============================
11170
11839
  {
11171
- method: "GET",
11172
- path: "/geolocation/:ipAddress",
11173
- handler: "session.getIpGeolocation",
11840
+ method: "POST",
11841
+ path: "/webhook/test",
11842
+ handler: "webhooks.sendTest",
11174
11843
  config: {
11175
- policies: adminPolicy(),
11176
- description: "Get IP geolocation data (admin)"
11177
- }
11844
+ // Sends to the stored URL: same permission as changing it.
11845
+ policies: adminSessionsPolicy([SETTINGS_UPDATE_ACTION]),
11846
+ middlewares: [
11847
+ {
11848
+ name: "plugin::magic-sessionmanager.rate-limit",
11849
+ config: { profile: "write", max: 5, window: 6e4 }
11850
+ }
11851
+ ],
11852
+ description: "Send a signed test event to the stored webhook URL (admin)"
11853
+ }
11854
+ },
11855
+ // ============================ GEOLOCATION ============================
11856
+ {
11857
+ method: "GET",
11858
+ path: "/geolocation/:ipAddress",
11859
+ handler: "session.getIpGeolocation",
11860
+ config: {
11861
+ policies: adminPolicy(),
11862
+ description: "Get IP geolocation data (admin)"
11863
+ }
11178
11864
  },
11179
11865
  {
11180
11866
  method: "GET",
@@ -13499,6 +14185,7 @@ var require_settings_access = __commonJS({
13499
14185
  "use strict";
13500
14186
  var { SECURITY_LOG_KEYS } = require_security_log_settings();
13501
14187
  var { POLICY_KEYS } = require_policy_settings();
14188
+ var { PROTECTED_DETECTION_KEYS } = require_detection_settings();
13502
14189
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
13503
14190
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
13504
14191
  var GEO_SETTINGS_KEYS = Object.freeze([
@@ -13518,11 +14205,17 @@ var require_settings_access = __commonJS({
13518
14205
  ...SECURITY_LOG_KEYS,
13519
14206
  // Sign-in and session policies (lockout, trusted addresses, session
13520
14207
  // limit, password-change sign-out, recording switch, per-role rules).
13521
- ...POLICY_KEYS
14208
+ ...POLICY_KEYS,
14209
+ // Signed webhook, event selection, impossible travel and shortened IPs.
14210
+ ...PROTECTED_DETECTION_KEYS
13522
14211
  ]);
13523
14212
  var WEBHOOK_SECRETS = Object.freeze([
13524
14213
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
13525
- { key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" }
14214
+ { key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" },
14215
+ { key: "genericWebhookUrl", has: "hasGenericWebhook", hint: "genericWebhookHint" }
14216
+ ]);
14217
+ var WRITE_ONLY_SECRETS = Object.freeze([
14218
+ { key: "genericWebhookSecret", has: "hasGenericWebhookSecret" }
13526
14219
  ]);
13527
14220
  function sameValue(a, b) {
13528
14221
  if (a === b) return true;
@@ -13570,6 +14263,11 @@ var require_settings_access = __commonJS({
13570
14263
  out[has] = typeof value === "string" && value.trim().length > 0;
13571
14264
  out[hint] = webhookHint(value);
13572
14265
  }
14266
+ for (const { key, has } of WRITE_ONLY_SECRETS) {
14267
+ const value = out[key];
14268
+ delete out[key];
14269
+ out[has] = typeof value === "string" && value.length > 0;
14270
+ }
13573
14271
  return out;
13574
14272
  }
13575
14273
  module2.exports = {
@@ -13579,6 +14277,7 @@ var require_settings_access = __commonJS({
13579
14277
  SETTINGS_UPDATE_ACTION,
13580
14278
  WEBHOOK_SECRETS,
13581
14279
  WEBHOOK_SETTINGS_KEYS,
14280
+ WRITE_ONLY_SECRETS,
13582
14281
  callerCan,
13583
14282
  changedKeys,
13584
14283
  missingSettingsPermission,
@@ -13612,6 +14311,9 @@ var require_settings = __commonJS({
13612
14311
  toPublicSettings
13613
14312
  } = require_settings_access();
13614
14313
  var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
14314
+ var { DETECTION_DEFAULTS, validateDetectionSettings } = require_detection_settings();
14315
+ var { encryptToken } = require_encryption();
14316
+ var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
13615
14317
  var path = require("node:path");
13616
14318
  var ALLOWED_WEBHOOK_DOMAINS = {
13617
14319
  discord: ["discord.com", "discordapp.com"],
@@ -13753,7 +14455,9 @@ var require_settings = __commonJS({
13753
14455
  newLocation: { subject: "", html: "", text: "" },
13754
14456
  vpnProxy: { subject: "", html: "", text: "" },
13755
14457
  // 4.17: sent to a user whose account was locked after failed sign-ins.
13756
- accountLocked: { subject: "", html: "", text: "" }
14458
+ accountLocked: { subject: "", html: "", text: "" },
14459
+ newDevice: { subject: "", html: "", text: "" },
14460
+ impossibleTravel: { subject: "", html: "", text: "" }
13757
14461
  };
13758
14462
  var DEFAULT_SETTINGS = {
13759
14463
  inactivityTimeout: 15,
@@ -13789,7 +14493,10 @@ var require_settings = __commonJS({
13789
14493
  ...SECURITY_LOG_DEFAULTS,
13790
14494
  ...POLICY_DEFAULTS,
13791
14495
  lockoutTrustedAddresses: [],
13792
- roleRules: []
14496
+ roleRules: [],
14497
+ ...DETECTION_DEFAULTS,
14498
+ webhookEvents: [...DETECTION_DEFAULTS.webhookEvents],
14499
+ genericWebhookSecret: ""
13793
14500
  };
13794
14501
  function mergeSettingsWithDefaults(stored) {
13795
14502
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -14000,6 +14707,22 @@ var require_settings = __commonJS({
14000
14707
  const policies2 = validatePolicySettings(body);
14001
14708
  errors.push(...policies2.errors);
14002
14709
  Object.assign(next, policies2.values);
14710
+ const detection = validateDetectionSettings(body);
14711
+ errors.push(...detection.errors);
14712
+ Object.assign(next, detection.values);
14713
+ if (has("genericWebhookSecret")) {
14714
+ const secret = body.genericWebhookSecret;
14715
+ if (secret === "") {
14716
+ next.genericWebhookSecret = "";
14717
+ } else if (typeof secret !== "string" || !WEBHOOK_SECRET_PATTERN.test(secret)) {
14718
+ errors.push({
14719
+ path: ["genericWebhookSecret"],
14720
+ message: "genericWebhookSecret must be 32 to 256 printable characters without spaces"
14721
+ });
14722
+ } else {
14723
+ next.genericWebhookSecret = encryptToken(secret);
14724
+ }
14725
+ }
14003
14726
  if (errors.length > 0) return { errors };
14004
14727
  const settings = {};
14005
14728
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -14029,7 +14752,7 @@ var require_settings = __commonJS({
14029
14752
  }
14030
14753
  var FORBIDDEN_MESSAGES = Object.freeze({
14031
14754
  "admin-activity-permission": 'Changing the security log settings needs "View admin activity".',
14032
- "settings-update-permission": 'Changing location lookup, webhook or security log settings needs "Change protected settings".'
14755
+ "settings-update-permission": 'Changing location lookup, webhook, security log, sign-in policy or detection settings needs "Change protected settings".'
14033
14756
  });
14034
14757
  function recordSettingsChange(ctx, keys) {
14035
14758
  if (!keys.length) return;
@@ -14200,6 +14923,7 @@ var require_settings = __commonJS({
14200
14923
  },
14201
14924
  DEFAULT_SETTINGS,
14202
14925
  mergeSettingsWithDefaults,
14926
+ toPublicSettings,
14203
14927
  validateSettingsUpdate
14204
14928
  };
14205
14929
  }
@@ -15618,6 +16342,15 @@ var require_lockouts = __commonJS({
15618
16342
  const lifted = await lockout().unlock(id);
15619
16343
  if (!lifted) return ctx.notFound("This lock has already ended");
15620
16344
  try {
16345
+ const liftEvent = {
16346
+ event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
16347
+ actorType: "admin",
16348
+ actorId: ctx.state?.user?.id ?? null,
16349
+ targetType: lifted.kind === "account" ? "user" : "ip",
16350
+ targetId: lifted.kind === "account" ? lifted.user : null,
16351
+ meta: { kind: lifted.kind }
16352
+ };
16353
+ strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(liftEvent);
15621
16354
  strapi2.plugin("magic-sessionmanager").service("security-log").record({
15622
16355
  event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
15623
16356
  actorType: "admin",
@@ -15671,6 +16404,333 @@ var require_lockouts = __commonJS({
15671
16404
  }
15672
16405
  });
15673
16406
 
16407
+ // server/src/controllers/self-service.js
16408
+ var require_self_service = __commonJS({
16409
+ "server/src/controllers/self-service.js"(exports2, module2) {
16410
+ "use strict";
16411
+ var { getCoordinator } = require_coordination();
16412
+ var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
16413
+ var { recordUserEvent } = require_sign_in_policies();
16414
+ var { resolveUserDocumentId } = require_resolve_user();
16415
+ var { SECURITY_EVENTS } = require_security_log_model();
16416
+ var { sendServerError } = require_http_errors();
16417
+ var { createLogger } = require_logger();
16418
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
16419
+ var EVENT_UID = "plugin::magic-sessionmanager.security-event";
16420
+ var USER_UID = "plugin::users-permissions.user";
16421
+ var EXPORT_LIMIT = 5e3;
16422
+ var EXPORT_BATCH = 500;
16423
+ var PAGE_TEXT = Object.freeze({
16424
+ en: {
16425
+ title: "Was this sign-in not you?",
16426
+ body: "Sign the device of that sign-in out now. Then change your password.",
16427
+ one: "Sign out that device",
16428
+ all: "Sign out everywhere",
16429
+ done: "Done. The session was ended. Change your password now.",
16430
+ doneAll: "Done. Every session of your account was ended. Change your password now.",
16431
+ invalid: "This link is no longer valid. It works once and expires after 72 hours."
16432
+ },
16433
+ de: {
16434
+ title: "Waren Sie das nicht?",
16435
+ body: "Melden Sie das Ger\xE4t dieser Anmeldung jetzt ab. \xC4ndern Sie danach Ihr Passwort.",
16436
+ one: "Dieses Ger\xE4t abmelden",
16437
+ all: "\xDCberall abmelden",
16438
+ done: "Erledigt. Die Sitzung wurde beendet. \xC4ndern Sie jetzt Ihr Passwort.",
16439
+ doneAll: "Erledigt. Alle Sitzungen Ihres Kontos wurden beendet. \xC4ndern Sie jetzt Ihr Passwort.",
16440
+ invalid: "Dieser Link ist nicht mehr g\xFCltig. Er funktioniert einmal und l\xE4uft nach 72 Stunden ab."
16441
+ },
16442
+ fr: {
16443
+ title: "Cette connexion n\u2019\xE9tait pas vous ?",
16444
+ body: "D\xE9connectez maintenant l\u2019appareil de cette connexion, puis changez votre mot de passe.",
16445
+ one: "D\xE9connecter cet appareil",
16446
+ all: "Se d\xE9connecter partout",
16447
+ done: "C\u2019est fait. La session a \xE9t\xE9 termin\xE9e. Changez maintenant votre mot de passe.",
16448
+ doneAll: "C\u2019est fait. Toutes les sessions de votre compte ont \xE9t\xE9 termin\xE9es. Changez maintenant votre mot de passe.",
16449
+ invalid: "Ce lien n\u2019est plus valide. Il fonctionne une fois et expire apr\xE8s 72 heures."
16450
+ },
16451
+ es: {
16452
+ title: "\xBFEste inicio de sesi\xF3n no fue usted?",
16453
+ body: "Cierre ahora la sesi\xF3n del dispositivo de ese inicio de sesi\xF3n y despu\xE9s cambie su contrase\xF1a.",
16454
+ one: "Cerrar la sesi\xF3n de ese dispositivo",
16455
+ all: "Cerrar sesi\xF3n en todas partes",
16456
+ done: "Hecho. La sesi\xF3n ha terminado. Cambie ahora su contrase\xF1a.",
16457
+ doneAll: "Hecho. Todas las sesiones de su cuenta han terminado. Cambie ahora su contrase\xF1a.",
16458
+ invalid: "Este enlace ya no es v\xE1lido. Funciona una vez y caduca a las 72 horas."
16459
+ },
16460
+ pt: {
16461
+ title: "Este in\xEDcio de sess\xE3o n\xE3o foi seu?",
16462
+ body: "Termine agora a sess\xE3o do dispositivo desse in\xEDcio de sess\xE3o e depois altere a sua palavra-passe.",
16463
+ one: "Terminar a sess\xE3o desse dispositivo",
16464
+ all: "Terminar sess\xE3o em todo o lado",
16465
+ done: "Feito. A sess\xE3o foi terminada. Altere agora a sua palavra-passe.",
16466
+ doneAll: "Feito. Todas as sess\xF5es da sua conta foram terminadas. Altere agora a sua palavra-passe.",
16467
+ invalid: "Esta liga\xE7\xE3o j\xE1 n\xE3o \xE9 v\xE1lida. Funciona uma vez e expira ap\xF3s 72 horas."
16468
+ }
16469
+ });
16470
+ function pageLanguage(ctx) {
16471
+ const header = String(ctx.request?.headers?.["accept-language"] || "").slice(0, 200);
16472
+ for (const part of header.split(",")) {
16473
+ const code = part.trim().slice(0, 2).toLowerCase();
16474
+ if (Object.prototype.hasOwnProperty.call(PAGE_TEXT, code)) {
16475
+ return (
16476
+ /** @type {keyof typeof PAGE_TEXT} */
16477
+ code
16478
+ );
16479
+ }
16480
+ }
16481
+ return "en";
16482
+ }
16483
+ var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
16484
+ function sendPage(ctx, status, lang, title, body) {
16485
+ ctx.status = status;
16486
+ ctx.set("Content-Type", "text/html; charset=utf-8");
16487
+ ctx.set(
16488
+ "Content-Security-Policy",
16489
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
16490
+ );
16491
+ ctx.set("Referrer-Policy", "no-referrer");
16492
+ ctx.set("Cache-Control", "no-store");
16493
+ ctx.set("X-Robots-Tag", "noindex");
16494
+ 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>
16495
+ <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>
16496
+ <body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
16497
+ }
16498
+ module2.exports = ({ strapi: strapi2 }) => {
16499
+ const log = createLogger(strapi2);
16500
+ return {
16501
+ /**
16502
+ * Confirmation page of the "This wasn't me" link. Uses nothing.
16503
+ *
16504
+ * @route GET /api/magic-sessionmanager/not-me?token=
16505
+ * @auth none (public on purpose: the link is opened from an email; the
16506
+ * signed token is checked, and nothing changes until the POST)
16507
+ * @param {any} ctx Koa context.
16508
+ * @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
16509
+ */
16510
+ async notMePage(ctx) {
16511
+ const lang = pageLanguage(ctx);
16512
+ const text = PAGE_TEXT[lang];
16513
+ const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
16514
+ if (!readNotMeToken(token)) {
16515
+ return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
16516
+ }
16517
+ 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>`;
16518
+ return sendPage(
16519
+ ctx,
16520
+ 200,
16521
+ lang,
16522
+ text.title,
16523
+ `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
16524
+ );
16525
+ },
16526
+ /**
16527
+ * Uses a "This wasn't me" token: ends that session, or every session of
16528
+ * the user with `scope=all`, and records `user.not-me`.
16529
+ *
16530
+ * @route POST /api/magic-sessionmanager/not-me
16531
+ * @auth none (public on purpose; the signed single-use token authorises)
16532
+ * @param {any} ctx Koa context; body `{ token, scope?: 'session'|'all' }` (form or JSON).
16533
+ * @returns {Promise<void>} 200 page (or JSON `{ ended }` with Accept: application/json);
16534
+ * 410 when the token is invalid, expired or used.
16535
+ * @sideeffect Ends sessions (and native sessions); writes a security event.
16536
+ */
16537
+ async notMeConfirm(ctx) {
16538
+ const lang = pageLanguage(ctx);
16539
+ const text = PAGE_TEXT[lang];
16540
+ const wantsJson = String(ctx.request?.headers?.accept || "").includes("application/json");
16541
+ const body = ctx.request?.body && typeof ctx.request.body === "object" ? ctx.request.body : {};
16542
+ const scope = body.scope === "all" ? "all" : "session";
16543
+ const claims = await consumeNotMeToken(getCoordinator(strapi2), body.token);
16544
+ if (!claims) {
16545
+ if (wantsJson) {
16546
+ ctx.status = 410;
16547
+ ctx.body = {
16548
+ data: null,
16549
+ error: { status: 410, name: "GoneError", message: "This link is no longer valid" }
16550
+ };
16551
+ return;
16552
+ }
16553
+ return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
16554
+ }
16555
+ try {
16556
+ const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
16557
+ let ended = 0;
16558
+ if (scope === "all") {
16559
+ ended = Number(
16560
+ (await sessionService.terminateSession({ userId: claims.userId, reason: "manual" }))?.terminatedCount
16561
+ ) || 0;
16562
+ } else {
16563
+ const session = await strapi2.documents(SESSION_UID).findFirst({
16564
+ filters: { documentId: claims.sessionId, user: { documentId: claims.userId } },
16565
+ fields: ["documentId", "isActive"]
16566
+ });
16567
+ if (session?.isActive) {
16568
+ ended = Number(
16569
+ (await sessionService.terminateSession({
16570
+ sessionId: session.documentId,
16571
+ reason: "manual"
16572
+ }))?.terminatedCount
16573
+ ) || 0;
16574
+ }
16575
+ }
16576
+ recordUserEvent(strapi2, {
16577
+ event: SECURITY_EVENTS.USER_NOT_ME,
16578
+ actorType: "user",
16579
+ actorId: claims.userId,
16580
+ targetType: "user",
16581
+ targetId: claims.userId,
16582
+ ip: ctx.request?.ip || null,
16583
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
16584
+ meta: { scope, ended }
16585
+ });
16586
+ if (wantsJson) {
16587
+ ctx.body = { data: { ended, scope } };
16588
+ return;
16589
+ }
16590
+ return sendPage(
16591
+ ctx,
16592
+ 200,
16593
+ lang,
16594
+ text.title,
16595
+ `<p>${escapeHtml(scope === "all" ? text.doneAll : text.done)}</p>`
16596
+ );
16597
+ } catch (err) {
16598
+ log.error("[not-me] Ending the session failed:", err?.name || "Error");
16599
+ return sendServerError(ctx, 500, "The session could not be ended");
16600
+ }
16601
+ },
16602
+ /**
16603
+ * The signed-in user's own sessions and security events as JSON (GDPR
16604
+ * Art. 15). Tokens, token hashes, device keys and native ids are never
16605
+ * included. At most 5,000 rows of each kind, newest first.
16606
+ *
16607
+ * @route GET /api/magic-sessionmanager/my-data
16608
+ * @auth users-permissions JWT (own data only; the user comes from the token)
16609
+ * @access plugin::magic-sessionmanager.self-service.exportOwnData (Authenticated role)
16610
+ * @param {any} ctx Koa context.
16611
+ * @returns {Promise<void>} 200 JSON attachment; 401 without a user.
16612
+ * @sideeffect Writes a `user.data.exported` security event.
16613
+ */
16614
+ async exportOwnData(ctx) {
16615
+ const authUser = ctx.state?.user;
16616
+ const userDocumentId = authUser?.documentId || (authUser?.id ? await resolveUserDocumentId(strapi2, authUser.id) : null);
16617
+ if (!userDocumentId) return ctx.unauthorized("Authentication required");
16618
+ try {
16619
+ const user = await strapi2.db.query(USER_UID).findOne({
16620
+ where: { documentId: userDocumentId },
16621
+ select: ["documentId", "username", "email", "createdAt"]
16622
+ });
16623
+ const sessions = [];
16624
+ for (let start = 0; start < EXPORT_LIMIT; start += EXPORT_BATCH) {
16625
+ const rows = await strapi2.documents(SESSION_UID).findMany({
16626
+ filters: { user: { documentId: userDocumentId } },
16627
+ fields: [
16628
+ "documentId",
16629
+ "loginTime",
16630
+ "lastActive",
16631
+ "logoutTime",
16632
+ "isActive",
16633
+ "terminationReason",
16634
+ "ipAddress",
16635
+ "userAgent",
16636
+ "deviceType",
16637
+ "browserName",
16638
+ "osName",
16639
+ "geoLocation"
16640
+ ],
16641
+ sort: [{ loginTime: "desc" }, { id: "desc" }],
16642
+ start,
16643
+ limit: EXPORT_BATCH
16644
+ });
16645
+ const list = Array.isArray(rows) ? rows : [];
16646
+ sessions.push(...list.map(({ id: _id, ...row }) => row));
16647
+ if (list.length < EXPORT_BATCH) break;
16648
+ }
16649
+ const events = await strapi2.db.query(EVENT_UID).findMany({
16650
+ where: {
16651
+ $or: [
16652
+ { targetType: "user", targetId: userDocumentId },
16653
+ { actorType: "user", actorId: userDocumentId }
16654
+ ]
16655
+ },
16656
+ select: ["event", "createdAt", "ip", "userAgent", "geo", "meta"],
16657
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16658
+ limit: EXPORT_LIMIT
16659
+ });
16660
+ recordUserEvent(strapi2, {
16661
+ event: SECURITY_EVENTS.USER_DATA_EXPORTED,
16662
+ actorType: "user",
16663
+ actorId: userDocumentId,
16664
+ targetType: "user",
16665
+ targetId: userDocumentId,
16666
+ ip: ctx.request?.ip || null,
16667
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
16668
+ meta: { sessions: sessions.length, events: Array.isArray(events) ? events.length : 0 }
16669
+ });
16670
+ ctx.set("Content-Disposition", 'attachment; filename="my-session-data.json"');
16671
+ ctx.set("Cache-Control", "no-store");
16672
+ ctx.body = {
16673
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
16674
+ user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
16675
+ sessions,
16676
+ securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
16677
+ };
16678
+ } catch (err) {
16679
+ log.error("[my-data] Export failed:", err?.name || "Error");
16680
+ return sendServerError(ctx, 500, "Your data could not be exported");
16681
+ }
16682
+ }
16683
+ };
16684
+ };
16685
+ }
16686
+ });
16687
+
16688
+ // server/src/controllers/webhooks.js
16689
+ var require_webhooks = __commonJS({
16690
+ "server/src/controllers/webhooks.js"(exports2, module2) {
16691
+ "use strict";
16692
+ var { sendServerError } = require_http_errors();
16693
+ var { createLogger } = require_logger();
16694
+ var RESULT_CODES = /* @__PURE__ */ new Set([
16695
+ "no_url",
16696
+ "no_secret",
16697
+ "invalid_url",
16698
+ "dns_failed",
16699
+ "address_not_allowed",
16700
+ "timeout",
16701
+ "network_error",
16702
+ "redirect_not_followed"
16703
+ ]);
16704
+ module2.exports = ({ strapi: strapi2 }) => {
16705
+ const log = createLogger(strapi2);
16706
+ return {
16707
+ /**
16708
+ * Sends one signed `test` event to the stored URL, without retries.
16709
+ *
16710
+ * @route POST /magic-sessionmanager/webhook/test
16711
+ * @auth admin session or admin API token
16712
+ * @access plugin::magic-sessionmanager.access
16713
+ * @param {any} ctx Koa context.
16714
+ * @returns {Promise<void>} `{ data: { ok, status, code } }` (status of the receiver's answer;
16715
+ * code: no_url, no_secret, invalid_url, dns_failed, address_not_allowed, timeout,
16716
+ * network_error, redirect_not_followed or http_<status>).
16717
+ * @sideeffect One HTTPS request to the stored webhook URL.
16718
+ */
16719
+ async sendTest(ctx) {
16720
+ try {
16721
+ const result = await strapi2.plugin("magic-sessionmanager").service("webhooks").sendTest();
16722
+ const code = result.code === null || RESULT_CODES.has(result.code) || /^http_\d{3}$/.test(result.code) ? result.code : "network_error";
16723
+ ctx.body = { data: { ok: result.ok === true, status: result.status ?? null, code } };
16724
+ } catch (err) {
16725
+ log.error("[webhooks] Test send failed:", err?.name || "Error");
16726
+ return sendServerError(ctx, 500, "The test event could not be sent");
16727
+ }
16728
+ }
16729
+ };
16730
+ };
16731
+ }
16732
+ });
16733
+
15674
16734
  // server/src/controllers/index.js
15675
16735
  var require_controllers = __commonJS({
15676
16736
  "server/src/controllers/index.js"(exports2, module2) {
@@ -15681,13 +16741,17 @@ var require_controllers = __commonJS({
15681
16741
  var adminSessions = require_admin_sessions2();
15682
16742
  var adminActivity = require_admin_activity();
15683
16743
  var lockouts = require_lockouts();
16744
+ var selfService = require_self_service();
16745
+ var webhooks = require_webhooks();
15684
16746
  module2.exports = {
15685
16747
  session,
15686
16748
  settings,
15687
16749
  geoip,
15688
16750
  "admin-sessions": adminSessions,
15689
16751
  "admin-activity": adminActivity,
15690
- lockouts
16752
+ lockouts,
16753
+ "self-service": selfService,
16754
+ webhooks
15691
16755
  };
15692
16756
  }
15693
16757
  });
@@ -15703,6 +16767,9 @@ var require_session2 = __commonJS({
15703
16767
  var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
15704
16768
  var { getPluginSettings } = require_settings_loader();
15705
16769
  var { hasRoleOverride, inactivityTimeoutFor } = require_policy_settings();
16770
+ var { resolveDetectionSettings } = require_detection_settings();
16771
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
16772
+ var { pointOf } = require_sign_in_signals();
15706
16773
  var {
15707
16774
  cleanupExpiredAccessTokenRevocations,
15708
16775
  persistAccessTokenRevocation
@@ -16034,6 +17101,7 @@ var require_session2 = __commonJS({
16034
17101
  * @param {string} [params.refreshToken] - Refresh token (will be encrypted)
16035
17102
  * @param {string} [params.nativeSessionId] - Native Users & Permissions session ID.
16036
17103
  * @param {object} [params.geoData]
17104
+ * @param {string} [params.deviceKey] Device key from utils/sign-in-signals.js.
16037
17105
  * @returns {Promise<object>} Created session
16038
17106
  * @throws {Error} When userId is missing
16039
17107
  */
@@ -16044,11 +17112,13 @@ var require_session2 = __commonJS({
16044
17112
  token,
16045
17113
  refreshToken,
16046
17114
  nativeSessionId,
16047
- geoData
17115
+ geoData,
17116
+ deviceKey
16048
17117
  }) {
16049
17118
  if (!userId) {
16050
17119
  throw new Error("createSession: userId is required");
16051
17120
  }
17121
+ const privacy = await getPluginSettings(strapi2).then(resolveDetectionSettings).catch(() => ({}));
16052
17122
  try {
16053
17123
  const now = /* @__PURE__ */ new Date();
16054
17124
  const sessionId = generateSessionId(userId);
@@ -16058,7 +17128,9 @@ var require_session2 = __commonJS({
16058
17128
  const tokenHashValue = token ? hashToken(token) : null;
16059
17129
  const refreshTokenHashValue = refreshToken ? hashToken(refreshToken) : null;
16060
17130
  const parsedUA = parseUserAgent(userAgent);
16061
- const safeIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
17131
+ const rawIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
17132
+ const safeIp = privacy.sessionIpAnonymize && normalizeIp(rawIp) ? anonymizeIp(normalizeIp(rawIp)) || rawIp : rawIp;
17133
+ const point = privacy.impossibleTravelEnabled ? pointOf(geoData) : null;
16062
17134
  const safeUa = (typeof userAgent === "string" ? userAgent : "unknown").substring(0, 500);
16063
17135
  const session = await strapi2.documents(SESSION_UID).create({
16064
17136
  data: {
@@ -16086,8 +17158,10 @@ var require_session2 = __commonJS({
16086
17158
  timezone: geoData.timezone,
16087
17159
  // Marks the stored score as real risk data; without a
16088
17160
  // risk source the score is null (not a fake 100).
16089
- ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
17161
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {},
17162
+ ...point ? { latitude: point.lat, longitude: point.lon } : {}
16090
17163
  } : null,
17164
+ ...typeof deviceKey === "string" && /^[a-f0-9]{32}$/.test(deviceKey) ? { deviceKey } : {},
16091
17165
  securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
16092
17166
  }
16093
17167
  });
@@ -17804,6 +18878,75 @@ Hello {{user.username}},
17804
18878
  There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
17805
18879
 
17806
18880
  If these attempts were not yours, change your password after the lock ends.`
18881
+ }),
18882
+ newDevice: Object.freeze({
18883
+ subject: "New sign-in to your account",
18884
+ html: `<html>
18885
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
18886
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
18887
+ <h2>New sign-in to your account</h2>
18888
+ <p>Hello {{user.username}},</p>
18889
+ <p>Your account was just used on a device we have not seen before.</p>
18890
+ <ul>
18891
+ <li>Time: {{session.loginTime}}</li>
18892
+ <li>Device: {{device.browser}} on {{device.os}}</li>
18893
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
18894
+ <li>IP address: {{session.ipAddress}}</li>
18895
+ </ul>
18896
+ <p>If this was you, you can ignore this email.</p>
18897
+ <p>If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
18898
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
18899
+ </div>
18900
+ </body>
18901
+ </html>`,
18902
+ text: `New sign-in to your account
18903
+
18904
+ Hello {{user.username}},
18905
+
18906
+ Your account was just used on a device we have not seen before.
18907
+
18908
+ Time: {{session.loginTime}}
18909
+ Device: {{device.browser}} on {{device.os}}
18910
+ Location: {{geo.city}}, {{geo.country}}
18911
+ IP address: {{session.ipAddress}}
18912
+
18913
+ If this was not you, sign this device out and change your password:
18914
+ {{link.notMe}}
18915
+
18916
+ The link works once and expires after 72 hours.`
18917
+ }),
18918
+ impossibleTravel: Object.freeze({
18919
+ subject: "Unusual sign-in to your account",
18920
+ html: `<html>
18921
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
18922
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
18923
+ <h2>Unusual sign-in to your account</h2>
18924
+ <p>Hello {{user.username}},</p>
18925
+ <p>Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.</p>
18926
+ <ul>
18927
+ <li>Time: {{session.loginTime}}</li>
18928
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
18929
+ <li>Device: {{device.browser}} on {{device.os}}</li>
18930
+ </ul>
18931
+ <p>A VPN or a mobile network can cause this. If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
18932
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
18933
+ </div>
18934
+ </body>
18935
+ </html>`,
18936
+ text: `Unusual sign-in to your account
18937
+
18938
+ Hello {{user.username}},
18939
+
18940
+ Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.
18941
+
18942
+ Time: {{session.loginTime}}
18943
+ Location: {{geo.city}}, {{geo.country}}
18944
+ Device: {{device.browser}} on {{device.os}}
18945
+
18946
+ A VPN or a mobile network can cause this. If this was not you, sign this device out and change your password:
18947
+ {{link.notMe}}
18948
+
18949
+ The link works once and expires after 72 hours.`
17807
18950
  })
17808
18951
  });
17809
18952
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
@@ -17934,6 +19077,37 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
17934
19077
  }
17935
19078
  return { ...POLICY_TEMPLATES[key] };
17936
19079
  },
19080
+ /**
19081
+ * Emails a user about a sign-in from a new device or an impossible
19082
+ * travel, with the "This wasn't me" link.
19083
+ *
19084
+ * @param {'newDevice'|'impossibleTravel'} key Template.
19085
+ * @param {{user: object, session: object, geoData?: object|null, device: object,
19086
+ * travel?: object|null, link: string|null}} data Values.
19087
+ * @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
19088
+ * @sideeffect Sends one email.
19089
+ */
19090
+ async sendSignInSignalEmail(key, data) {
19091
+ try {
19092
+ if (!data?.user?.email) return false;
19093
+ const template = await this.getTemplate(key);
19094
+ const values = { ...data, geoData: data.geoData || {}, link: { notMe: data.link } };
19095
+ await strapi2.plugin("email").service("email").send({
19096
+ to: data.user.email,
19097
+ subject: this.replaceVariables(template.subject, values),
19098
+ html: this.replaceVariables(template.html, values),
19099
+ text: this.replaceVariables(template.text, values)
19100
+ });
19101
+ strapi2.log.info(`[magic-sessionmanager/notifications] ${key} email sent`);
19102
+ return true;
19103
+ } catch (err) {
19104
+ strapi2.log.error(
19105
+ `[magic-sessionmanager/notifications] ${key} email failed:`,
19106
+ err?.name || "Error"
19107
+ );
19108
+ return false;
19109
+ }
19110
+ },
17937
19111
  /**
17938
19112
  * Emails a user that their account was locked after failed sign-ins.
17939
19113
  * Sent through Strapi's email plugin, so a provider plugin such as Magic
@@ -18010,6 +19184,18 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
18010
19184
  /\{\{lock\.until\}\}/g,
18011
19185
  esc(Number.isFinite(data.lock?.until) ? new Date(data.lock.until).toUTCString() : "N/A")
18012
19186
  );
19187
+ result = result.replace(/\{\{device\.browser\}\}/g, esc(data.device?.browser || "Unknown"));
19188
+ result = result.replace(/\{\{device\.os\}\}/g, esc(data.device?.os || "Unknown"));
19189
+ result = result.replace(
19190
+ /\{\{travel\.distanceKm\}\}/g,
19191
+ esc(Number.isFinite(data.travel?.distanceKm) ? String(data.travel.distanceKm) : "N/A")
19192
+ );
19193
+ result = result.replace(
19194
+ /\{\{travel\.speedKmh\}\}/g,
19195
+ esc(Number.isFinite(data.travel?.speedKmh) ? String(data.travel.speedKmh) : "N/A")
19196
+ );
19197
+ const link = typeof data.link?.notMe === "string" && /^https?:\/\//.test(data.link.notMe) ? data.link.notMe : "";
19198
+ result = result.replace(/\{\{link\.notMe\}\}/g, esc(link));
18013
19199
  const score = data.reason?.securityScore;
18014
19200
  result = result.replace(
18015
19201
  /\{\{reason\.securityScore\}\}/g,
@@ -19303,6 +20489,478 @@ var require_security_log = __commonJS({
19303
20489
  }
19304
20490
  });
19305
20491
 
20492
+ // server/src/utils/webhook-delivery.js
20493
+ var require_webhook_delivery = __commonJS({
20494
+ "server/src/utils/webhook-delivery.js"(exports2, module2) {
20495
+ "use strict";
20496
+ var crypto = require("node:crypto");
20497
+ var dns = require("node:dns");
20498
+ var https = require("node:https");
20499
+ var net = require("node:net");
20500
+ var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
20501
+ var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
20502
+ var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
20503
+ var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
20504
+ var TIMEOUT_MS = 5e3;
20505
+ var MAX_RESPONSE_BYTES = 64 * 1024;
20506
+ var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
20507
+ var BLOCKED = (() => {
20508
+ const list = new net.BlockList();
20509
+ for (const [address, prefix] of [
20510
+ ["0.0.0.0", 8],
20511
+ ["10.0.0.0", 8],
20512
+ ["100.64.0.0", 10],
20513
+ ["127.0.0.0", 8],
20514
+ ["169.254.0.0", 16],
20515
+ ["172.16.0.0", 12],
20516
+ ["192.0.0.0", 24],
20517
+ ["192.0.2.0", 24],
20518
+ ["192.88.99.0", 24],
20519
+ ["192.168.0.0", 16],
20520
+ ["198.18.0.0", 15],
20521
+ ["198.51.100.0", 24],
20522
+ ["203.0.113.0", 24],
20523
+ ["224.0.0.0", 4],
20524
+ ["240.0.0.0", 4]
20525
+ ]) {
20526
+ list.addSubnet(address, prefix, "ipv4");
20527
+ }
20528
+ for (const [address, prefix] of [
20529
+ ["::", 128],
20530
+ ["::1", 128],
20531
+ // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
20532
+ // checks them against the IPv4 rules above, and a listed /96 would
20533
+ // match every IPv4 address.
20534
+ ["64:ff9b::", 96],
20535
+ ["64:ff9b:1::", 48],
20536
+ ["100::", 64],
20537
+ ["2001::", 23],
20538
+ ["2001:db8::", 32],
20539
+ ["2002::", 16],
20540
+ ["fc00::", 7],
20541
+ ["fe80::", 10],
20542
+ ["fec0::", 10],
20543
+ ["ff00::", 8]
20544
+ ]) {
20545
+ list.addSubnet(address, prefix, "ipv6");
20546
+ }
20547
+ return list;
20548
+ })();
20549
+ function isBlockedAddress(address) {
20550
+ let value = String(address || "").trim();
20551
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
20552
+ value = value.slice(7);
20553
+ }
20554
+ const version = net.isIP(value);
20555
+ if (version === 0) return true;
20556
+ return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
20557
+ }
20558
+ function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
20559
+ const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
20560
+ return `t=${timestamp},v1=${digest}`;
20561
+ }
20562
+ function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
20563
+ const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
20564
+ if (!match) return false;
20565
+ const timestamp = Number(match[1]);
20566
+ if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
20567
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
20568
+ const given = Buffer.from(match[2], "hex");
20569
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
20570
+ }
20571
+ var DeliveryError = class extends Error {
20572
+ /**
20573
+ * @param {string} code Stable code.
20574
+ * @param {boolean} retryable Whether another attempt may succeed.
20575
+ * @param {number|null} [status] HTTP status, when there was one.
20576
+ */
20577
+ constructor(code, retryable, status = null) {
20578
+ super(code);
20579
+ this.name = "DeliveryError";
20580
+ this.code = code;
20581
+ this.retryable = retryable;
20582
+ this.status = status;
20583
+ }
20584
+ };
20585
+ var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
20586
+ function httpsPost({ url, address, headers, body, timeoutMs }) {
20587
+ return new Promise((resolve, reject) => {
20588
+ const request = https.request(
20589
+ {
20590
+ protocol: "https:",
20591
+ hostname: url.hostname,
20592
+ port: url.port || 443,
20593
+ path: `${url.pathname}${url.search}`,
20594
+ method: "POST",
20595
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
20596
+ servername: net.isIP(url.hostname) ? void 0 : url.hostname,
20597
+ timeout: timeoutMs,
20598
+ // Pinned to the address that passed the check: no second lookup.
20599
+ lookup: (_hostname, options, callback) => {
20600
+ if (options && options.all) callback(null, [address]);
20601
+ else callback(null, address.address, address.family);
20602
+ }
20603
+ },
20604
+ (response) => {
20605
+ let received = 0;
20606
+ response.on("data", (chunk) => {
20607
+ received += chunk.length;
20608
+ if (received > MAX_RESPONSE_BYTES) response.destroy();
20609
+ });
20610
+ response.on("end", () => resolve(response.statusCode || 0));
20611
+ response.on("close", () => resolve(response.statusCode || 0));
20612
+ response.on("error", () => resolve(response.statusCode || 0));
20613
+ }
20614
+ );
20615
+ request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
20616
+ request.on(
20617
+ "error",
20618
+ (err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
20619
+ );
20620
+ request.end(body);
20621
+ });
20622
+ }
20623
+ async function deliverOnce({
20624
+ url,
20625
+ body,
20626
+ headers,
20627
+ resolve = resolveAll,
20628
+ post = httpsPost,
20629
+ timeoutMs = TIMEOUT_MS
20630
+ }) {
20631
+ let parsed;
20632
+ try {
20633
+ parsed = new URL(url);
20634
+ } catch {
20635
+ throw new DeliveryError("invalid_url", false);
20636
+ }
20637
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
20638
+ throw new DeliveryError("invalid_url", false);
20639
+ }
20640
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
20641
+ let addresses;
20642
+ if (net.isIP(host)) {
20643
+ addresses = [{ address: host, family: net.isIP(host) }];
20644
+ } else {
20645
+ try {
20646
+ addresses = await resolve(host);
20647
+ } catch {
20648
+ throw new DeliveryError("dns_failed", true);
20649
+ }
20650
+ }
20651
+ if (!Array.isArray(addresses) || addresses.length === 0)
20652
+ throw new DeliveryError("dns_failed", true);
20653
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
20654
+ throw new DeliveryError("address_not_allowed", false);
20655
+ }
20656
+ const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
20657
+ if (status >= 200 && status < 300) return { status };
20658
+ if (status >= 300 && status < 400)
20659
+ throw new DeliveryError("redirect_not_followed", false, status);
20660
+ throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
20661
+ }
20662
+ function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
20663
+ const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
20664
+ return {
20665
+ id,
20666
+ body,
20667
+ headers: {
20668
+ "Content-Type": "application/json",
20669
+ "User-Agent": USER_AGENT,
20670
+ [EVENT_HEADER]: event,
20671
+ [DELIVERY_HEADER]: id,
20672
+ [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
20673
+ }
20674
+ };
20675
+ }
20676
+ async function deliverWithRetries({
20677
+ delays = RETRY_DELAYS_MS,
20678
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
20679
+ ...request
20680
+ }) {
20681
+ let attempts = 0;
20682
+ let last = { ok: false, status: null, code: "not_sent" };
20683
+ for (const delay of delays) {
20684
+ if (delay > 0) await sleep(delay);
20685
+ attempts += 1;
20686
+ try {
20687
+ const { status } = await deliverOnce(request);
20688
+ return { ok: true, status, code: null, attempts };
20689
+ } catch (err) {
20690
+ const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
20691
+ last = { ok: false, status: error.status, code: error.code };
20692
+ if (!error.retryable) break;
20693
+ }
20694
+ }
20695
+ return { ...last, attempts };
20696
+ }
20697
+ module2.exports = {
20698
+ DELIVERY_HEADER,
20699
+ DeliveryError,
20700
+ EVENT_HEADER,
20701
+ RETRY_DELAYS_MS,
20702
+ SIGNATURE_HEADER,
20703
+ buildSignedRequest,
20704
+ deliverOnce,
20705
+ deliverWithRetries,
20706
+ isBlockedAddress,
20707
+ signPayload,
20708
+ verifySignature
20709
+ };
20710
+ }
20711
+ });
20712
+
20713
+ // server/src/services/webhooks.js
20714
+ var require_webhooks2 = __commonJS({
20715
+ "server/src/services/webhooks.js"(exports2, module2) {
20716
+ "use strict";
20717
+ var { decryptToken } = require_encryption();
20718
+ var { getPluginSettings } = require_settings_loader();
20719
+ var { resolveDetectionSettings } = require_detection_settings();
20720
+ var { resolveSecurityLogSettings } = require_security_log_settings();
20721
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
20722
+ var { SECURITY_EVENTS } = require_security_log_model();
20723
+ var {
20724
+ buildSignedRequest,
20725
+ deliverOnce,
20726
+ deliverWithRetries
20727
+ } = require_webhook_delivery();
20728
+ var { createLogger } = require_logger();
20729
+ var EVENT_OF_SECURITY_EVENT = Object.freeze({
20730
+ [SECURITY_EVENTS.USER_SIGN_IN_FAILED]: "login.failed",
20731
+ [SECURITY_EVENTS.USER_SIGN_IN_REFUSED]: "login.refused",
20732
+ [SECURITY_EVENTS.USER_LOCKOUT]: "lockout",
20733
+ [SECURITY_EVENTS.USER_LOCKOUT_LIFTED]: "lockout.lifted",
20734
+ [SECURITY_EVENTS.USER_SESSION_LIMIT]: "session.limit",
20735
+ [SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED]: "password.changed",
20736
+ "user.sign-in.new-device": "login.new_device",
20737
+ "user.sign-in.impossible-travel": "login.impossible_travel",
20738
+ "user.not-me": "user.not_me"
20739
+ });
20740
+ var CHAT_TITLES = Object.freeze({
20741
+ "login.failed": "Failed sign-in",
20742
+ "login.refused": "Refused sign-in",
20743
+ "login.new_device": "Sign-in from a new device",
20744
+ "login.impossible_travel": "Impossible travel",
20745
+ lockout: "Sign-in locked",
20746
+ "lockout.lifted": "Sign-in lock lifted",
20747
+ "session.limit": "Session limit reached",
20748
+ "password.changed": "Other sessions ended after a password change",
20749
+ "user.not_me": "User reported a sign-in as not theirs",
20750
+ test: "Test message"
20751
+ });
20752
+ var MAX_PARALLEL = 4;
20753
+ var MAX_QUEUE = 500;
20754
+ module2.exports = ({ strapi: strapi2 }) => {
20755
+ const log = createLogger(strapi2);
20756
+ const queue = [];
20757
+ let running = 0;
20758
+ let stopped = false;
20759
+ const pump = () => {
20760
+ while (!stopped && running < MAX_PARALLEL && queue.length) {
20761
+ const job = (
20762
+ /** @type {() => Promise<void>} */
20763
+ queue.shift()
20764
+ );
20765
+ running += 1;
20766
+ job().catch(() => {
20767
+ }).finally(() => {
20768
+ running -= 1;
20769
+ pump();
20770
+ });
20771
+ }
20772
+ };
20773
+ const enqueue = (job) => {
20774
+ if (stopped) return;
20775
+ if (queue.length >= MAX_QUEUE) {
20776
+ queue.shift();
20777
+ log.warn("[webhooks] Queue full; the oldest delivery was dropped");
20778
+ }
20779
+ queue.push(job);
20780
+ pump();
20781
+ };
20782
+ const secretOf = (settings) => {
20783
+ const stored = settings?.genericWebhookSecret;
20784
+ if (typeof stored !== "string" || !stored) return null;
20785
+ try {
20786
+ return decryptToken(stored) || null;
20787
+ } catch {
20788
+ return null;
20789
+ }
20790
+ };
20791
+ const dataOf = (settings, input) => {
20792
+ const options = resolveSecurityLogSettings(settings);
20793
+ const ip = options.storeIp ? normalizeIp(input.ip || "") : null;
20794
+ return {
20795
+ user: input.userId ? { documentId: String(input.userId) } : null,
20796
+ ip: ip && options.anonymizeIp ? anonymizeIp(ip) : ip,
20797
+ userAgent: typeof input.userAgent === "string" ? input.userAgent.slice(0, 256) : null,
20798
+ location: input.geo && (input.geo.country_code || input.geo.city) ? { country: input.geo.country_code || null, city: input.geo.city || null } : null,
20799
+ details: input.details || null
20800
+ };
20801
+ };
20802
+ const chatBody = (kind, event, data) => {
20803
+ const title = CHAT_TITLES[event] || event;
20804
+ const fields = [
20805
+ ["User", data.user?.documentId || "-"],
20806
+ ["IP", data.ip || "-"],
20807
+ ...Object.entries(data.details || {}).slice(0, 6).map(([key, value]) => [key, String(value)])
20808
+ ];
20809
+ if (kind === "discord") {
20810
+ return {
20811
+ embeds: [
20812
+ {
20813
+ title,
20814
+ color: 5793266,
20815
+ fields: fields.map(([name, value]) => ({
20816
+ name,
20817
+ value: value.slice(0, 200),
20818
+ inline: true
20819
+ })),
20820
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
20821
+ footer: { text: "Magic Session Manager" }
20822
+ }
20823
+ ]
20824
+ };
20825
+ }
20826
+ return {
20827
+ text: title,
20828
+ attachments: [
20829
+ {
20830
+ color: "#2563eb",
20831
+ blocks: [
20832
+ { type: "header", text: { type: "plain_text", text: title } },
20833
+ {
20834
+ type: "section",
20835
+ fields: fields.map(([name, value]) => ({
20836
+ type: "mrkdwn",
20837
+ text: `*${name}*
20838
+ ${value.slice(0, 200)}`
20839
+ }))
20840
+ }
20841
+ ]
20842
+ }
20843
+ ]
20844
+ };
20845
+ };
20846
+ const service = {
20847
+ EVENT_OF_SECURITY_EVENT,
20848
+ /**
20849
+ * Whether an event is selected.
20850
+ *
20851
+ * @param {Record<string, any>} settings Merged settings.
20852
+ * @param {string} event Webhook event.
20853
+ * @returns {boolean} True when selected.
20854
+ */
20855
+ isSelected(settings, event) {
20856
+ return resolveDetectionSettings(settings).webhookEvents.includes(event);
20857
+ },
20858
+ /**
20859
+ * Queues an event for the signed webhook and, for non-sign-in events,
20860
+ * Discord and Slack. Sign-in events (`login.success`, `login.suspicious`,
20861
+ * `login.new_location`) reach Discord and Slack through the login alerts
20862
+ * with their richer message. Returns at once.
20863
+ *
20864
+ * @param {string} event Webhook event.
20865
+ * @param {{userId?: string|null, ip?: string|null, userAgent?: string|null, geo?: any,
20866
+ * details?: Record<string, unknown>|null}} input Event facts.
20867
+ * @param {{chat?: boolean}} [options] Whether Discord/Slack get it here.
20868
+ * @returns {void}
20869
+ */
20870
+ emit(event, input, { chat = true } = {}) {
20871
+ enqueue(async () => {
20872
+ const settings = await getPluginSettings(strapi2);
20873
+ if (!service.isSelected(settings, event)) return;
20874
+ const data = dataOf(settings, input);
20875
+ const detection = resolveDetectionSettings(settings);
20876
+ const secret = secretOf(settings);
20877
+ if (detection.genericWebhookEnabled && detection.genericWebhookUrl && secret) {
20878
+ const request = buildSignedRequest({ event, data, secret });
20879
+ const result = await deliverWithRetries({ url: detection.genericWebhookUrl, ...request });
20880
+ if (!result.ok) {
20881
+ log.warn(
20882
+ `[webhooks] Signed webhook delivery failed (${result.code}, ${result.attempts} attempts)`
20883
+ );
20884
+ }
20885
+ }
20886
+ if (chat && settings.enableWebhooks) {
20887
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
20888
+ const targets = [
20889
+ ["discord", settings.discordWebhookUrl],
20890
+ ["slack", settings.slackWebhookUrl]
20891
+ ].filter(([, url]) => typeof url === "string" && url);
20892
+ await Promise.allSettled(
20893
+ targets.map(
20894
+ ([kind, url]) => notifications.sendWebhook({
20895
+ event,
20896
+ data: chatBody(kind, event, data),
20897
+ webhookUrl: url
20898
+ })
20899
+ )
20900
+ );
20901
+ }
20902
+ });
20903
+ },
20904
+ /**
20905
+ * Emits the webhook event that belongs to a security log event, if any.
20906
+ *
20907
+ * @param {{event: string, actorType?: string, actorId?: any, targetId?: any, ip?: any,
20908
+ * userAgent?: any, meta?: any}} input Security event input.
20909
+ * @returns {void}
20910
+ */
20911
+ emitSecurityEvent(input) {
20912
+ const event = EVENT_OF_SECURITY_EVENT[input?.event];
20913
+ if (!event) return;
20914
+ service.emit(event, {
20915
+ userId: input.targetId || (input.actorType === "user" ? input.actorId : null) || null,
20916
+ // An admin's own address is not sent for admin actions.
20917
+ ip: input.actorType === "admin" ? null : input.ip,
20918
+ userAgent: input.actorType === "admin" ? null : input.userAgent,
20919
+ details: input.meta || null
20920
+ });
20921
+ },
20922
+ /**
20923
+ * Sends one `test` event to the signed webhook now, without retries.
20924
+ *
20925
+ * @returns {Promise<{ok: boolean, status: number|null, code: string|null}>} Result.
20926
+ */
20927
+ async sendTest() {
20928
+ const settings = await getPluginSettings(strapi2);
20929
+ const detection = resolveDetectionSettings(settings);
20930
+ const secret = secretOf(settings);
20931
+ if (!detection.genericWebhookUrl) return { ok: false, status: null, code: "no_url" };
20932
+ if (!secret) return { ok: false, status: null, code: "no_secret" };
20933
+ const request = buildSignedRequest({
20934
+ event: "test",
20935
+ data: { user: null, ip: null, userAgent: null, location: null, details: { test: true } },
20936
+ secret
20937
+ });
20938
+ try {
20939
+ const { status } = await deliverOnce({ url: detection.genericWebhookUrl, ...request });
20940
+ return { ok: true, status, code: null };
20941
+ } catch (err) {
20942
+ return {
20943
+ ok: false,
20944
+ status: Number.isInteger(err?.status) ? err.status : null,
20945
+ code: typeof err?.code === "string" ? err.code : "network_error"
20946
+ };
20947
+ }
20948
+ },
20949
+ /**
20950
+ * Stops new deliveries (plugin destroy).
20951
+ *
20952
+ * @returns {void}
20953
+ */
20954
+ stop() {
20955
+ stopped = true;
20956
+ queue.length = 0;
20957
+ }
20958
+ };
20959
+ return service;
20960
+ };
20961
+ }
20962
+ });
20963
+
19306
20964
  // server/src/services/index.js
19307
20965
  var require_services = __commonJS({
19308
20966
  "server/src/services/index.js"(exports2, module2) {
@@ -19311,11 +20969,13 @@ var require_services = __commonJS({
19311
20969
  var geolocation = require_geolocation();
19312
20970
  var notifications = require_notifications();
19313
20971
  var securityLog = require_security_log();
20972
+ var webhooks = require_webhooks2();
19314
20973
  module2.exports = {
19315
20974
  session,
19316
20975
  geolocation,
19317
20976
  notifications,
19318
- "security-log": securityLog
20977
+ "security-log": securityLog,
20978
+ webhooks
19319
20979
  };
19320
20980
  }
19321
20981
  });