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
@@ -258,6 +258,11 @@ var require_coordination = __commonJS({
258
258
  async registryDelete(key) {
259
259
  registry.delete(key);
260
260
  },
261
+ async registryTake(key, now = Date.now()) {
262
+ const entry = registry.get(key);
263
+ registry.delete(key);
264
+ return entry && entry.expiresAt > now ? entry.value : null;
265
+ },
261
266
  async prune(now = Date.now()) {
262
267
  let removed = 0;
263
268
  for (const [k, v] of registry) {
@@ -528,6 +533,21 @@ var require_coordination = __commonJS({
528
533
  async registryDelete(key) {
529
534
  await knex(TABLES.cache).where({ k: `reg:${key}` }).del();
530
535
  },
536
+ /**
537
+ * Reads and deletes an entry. Only the caller whose DELETE removed the
538
+ * row gets the value, so parallel takes of one key yield it once.
539
+ */
540
+ async registryTake(key, now = Date.now()) {
541
+ const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: `reg:${key}` }).first();
542
+ if (!row) return null;
543
+ const deleted = await knex(TABLES.cache).where({ k: `reg:${key}`, expires_at: row.expires_at }).del();
544
+ if (toNumber(deleted) !== 1 || toNumber(row.expires_at) <= now) return null;
545
+ try {
546
+ return JSON.parse(row.v);
547
+ } catch {
548
+ return null;
549
+ }
550
+ },
531
551
  async prune(now = Date.now()) {
532
552
  const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
533
553
  const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
@@ -754,6 +774,21 @@ var require_coordination = __commonJS({
754
774
  () => sharedMemory.registryList(prefix, limit)
755
775
  );
756
776
  },
777
+ /**
778
+ * Takes a listable entry once: returns its value and removes it. Of
779
+ * several concurrent takes (any process) at most one gets the value.
780
+ *
781
+ * @param {string} key Entry key.
782
+ * @returns {Promise<any|null>} Value, or null when absent, expired or taken.
783
+ */
784
+ registryTake(key) {
785
+ assertRegistryKey(key);
786
+ return run(
787
+ "registry take",
788
+ (backend) => backend.registryTake(key),
789
+ () => sharedMemory.registryTake(key)
790
+ );
791
+ },
757
792
  /** Removes a listable entry. */
758
793
  registryDelete(key) {
759
794
  assertRegistryKey(key);
@@ -916,7 +951,7 @@ var require_content_api_permissions = __commonJS({
916
951
  "server/src/utils/content-api-permissions.js"(exports, module) {
917
952
  "use strict";
918
953
  var { withPluginStoreKey } = require_plugin_store();
919
- var CONTENT_API_PERMISSIONS_VERSION = 2;
954
+ var CONTENT_API_PERMISSIONS_VERSION = 3;
920
955
  var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
921
956
  var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
922
957
  async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
@@ -1442,12 +1477,228 @@ var require_policy_settings = __commonJS({
1442
1477
  }
1443
1478
  });
1444
1479
 
1480
+ // server/src/utils/detection-settings.js
1481
+ var require_detection_settings = __commonJS({
1482
+ "server/src/utils/detection-settings.js"(exports, module) {
1483
+ "use strict";
1484
+ var WEBHOOK_EVENTS = Object.freeze([
1485
+ "login.success",
1486
+ "login.suspicious",
1487
+ "login.new_location",
1488
+ "login.new_device",
1489
+ "login.impossible_travel",
1490
+ "login.failed",
1491
+ "login.refused",
1492
+ "lockout",
1493
+ "lockout.lifted",
1494
+ "session.limit",
1495
+ "password.changed",
1496
+ "user.not_me"
1497
+ ]);
1498
+ var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
1499
+ "login.suspicious",
1500
+ "login.new_location",
1501
+ "login.new_device",
1502
+ "login.impossible_travel",
1503
+ "lockout",
1504
+ "user.not_me"
1505
+ ]);
1506
+ var LEGACY_WEBHOOK_EVENTS = Object.freeze([
1507
+ "login.success",
1508
+ "login.suspicious",
1509
+ "login.new_location"
1510
+ ]);
1511
+ var IMPOSSIBLE_TRAVEL_ACTIONS = Object.freeze(["alert", "reauthenticate"]);
1512
+ var DETECTION_DEFAULTS = Object.freeze({
1513
+ alertOnNewDevice: false,
1514
+ alertOnImpossibleTravel: false,
1515
+ impossibleTravelEnabled: false,
1516
+ impossibleTravelSpeedKmh: 1e3,
1517
+ impossibleTravelMinDistanceKm: 500,
1518
+ impossibleTravelAction: "alert",
1519
+ webhookEvents: DEFAULT_WEBHOOK_EVENTS,
1520
+ genericWebhookEnabled: false,
1521
+ genericWebhookUrl: "",
1522
+ sessionIpAnonymize: false
1523
+ });
1524
+ var DETECTION_KEYS = Object.freeze(Object.keys(DETECTION_DEFAULTS));
1525
+ var PROTECTED_DETECTION_KEYS = Object.freeze([
1526
+ "impossibleTravelEnabled",
1527
+ "impossibleTravelSpeedKmh",
1528
+ "impossibleTravelMinDistanceKm",
1529
+ "impossibleTravelAction",
1530
+ "webhookEvents",
1531
+ "genericWebhookEnabled",
1532
+ "genericWebhookUrl",
1533
+ "genericWebhookSecret",
1534
+ "sessionIpAnonymize"
1535
+ ]);
1536
+ var RANGES = Object.freeze({
1537
+ impossibleTravelSpeedKmh: Object.freeze([100, 5e3]),
1538
+ impossibleTravelMinDistanceKm: Object.freeze([50, 2e4])
1539
+ });
1540
+ var BOOLEAN_KEYS = Object.freeze([
1541
+ "alertOnNewDevice",
1542
+ "alertOnImpossibleTravel",
1543
+ "impossibleTravelEnabled",
1544
+ "genericWebhookEnabled",
1545
+ "sessionIpAnonymize"
1546
+ ]);
1547
+ var MAX_URL_LENGTH = 2048;
1548
+ function parseInteger(value) {
1549
+ if (typeof value === "number") return Number.isInteger(value) ? value : null;
1550
+ if (typeof value === "string" && /^\s*\d{1,9}\s*$/.test(value)) return Number.parseInt(value, 10);
1551
+ return null;
1552
+ }
1553
+ function normalizeWebhookUrl(value) {
1554
+ if (typeof value !== "string") return null;
1555
+ const trimmed = value.trim();
1556
+ if (!trimmed || trimmed.length > MAX_URL_LENGTH) return null;
1557
+ let parsed;
1558
+ try {
1559
+ parsed = new URL(trimmed);
1560
+ } catch {
1561
+ return null;
1562
+ }
1563
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) return null;
1564
+ const host = parsed.hostname.toLowerCase();
1565
+ if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
1566
+ return null;
1567
+ }
1568
+ return parsed.toString();
1569
+ }
1570
+ function normalizeEventList(value) {
1571
+ if (!Array.isArray(value)) return null;
1572
+ return [...new Set(value.filter((event) => WEBHOOK_EVENTS.includes(event)))];
1573
+ }
1574
+ function normalizeDetectionSettings(stored) {
1575
+ const out = {};
1576
+ if (!stored || typeof stored !== "object") return out;
1577
+ for (const key of BOOLEAN_KEYS) if (stored[key] !== void 0) out[key] = stored[key] === true;
1578
+ for (const [key, [min, max]] of Object.entries(RANGES)) {
1579
+ if (stored[key] === void 0) continue;
1580
+ const number = parseInteger(stored[key]);
1581
+ out[key] = number !== null && number >= min && number <= max ? number : (
1582
+ /** @type {any} */
1583
+ DETECTION_DEFAULTS[key]
1584
+ );
1585
+ }
1586
+ if (stored.impossibleTravelAction !== void 0) {
1587
+ out.impossibleTravelAction = IMPOSSIBLE_TRAVEL_ACTIONS.includes(
1588
+ /** @type {string} */
1589
+ stored.impossibleTravelAction
1590
+ ) ? stored.impossibleTravelAction : "alert";
1591
+ }
1592
+ if (stored.webhookEvents !== void 0) {
1593
+ out.webhookEvents = normalizeEventList(stored.webhookEvents) || [...DEFAULT_WEBHOOK_EVENTS];
1594
+ }
1595
+ if (stored.genericWebhookUrl !== void 0) {
1596
+ out.genericWebhookUrl = normalizeWebhookUrl(stored.genericWebhookUrl) || "";
1597
+ }
1598
+ return out;
1599
+ }
1600
+ function validateDetectionSettings(body) {
1601
+ const values = {};
1602
+ const errors = [];
1603
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
1604
+ for (const key of BOOLEAN_KEYS) {
1605
+ if (!has(key)) continue;
1606
+ if (typeof body[key] !== "boolean")
1607
+ errors.push({ path: [key], message: `${key} must be a boolean` });
1608
+ else values[key] = body[key];
1609
+ }
1610
+ for (const [key, [min, max]] of Object.entries(RANGES)) {
1611
+ if (!has(key)) continue;
1612
+ const number = parseInteger(body[key]);
1613
+ if (number === null || number < min || number > max) {
1614
+ errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
1615
+ } else {
1616
+ values[key] = number;
1617
+ }
1618
+ }
1619
+ if (has("impossibleTravelAction")) {
1620
+ if (!IMPOSSIBLE_TRAVEL_ACTIONS.includes(
1621
+ /** @type {string} */
1622
+ body.impossibleTravelAction
1623
+ )) {
1624
+ errors.push({
1625
+ path: ["impossibleTravelAction"],
1626
+ message: `impossibleTravelAction must be one of: ${IMPOSSIBLE_TRAVEL_ACTIONS.join(", ")}`
1627
+ });
1628
+ } else {
1629
+ values.impossibleTravelAction = body.impossibleTravelAction;
1630
+ }
1631
+ }
1632
+ if (has("webhookEvents")) {
1633
+ const list = body.webhookEvents;
1634
+ if (!Array.isArray(list) || list.length > WEBHOOK_EVENTS.length || list.some((event) => !WEBHOOK_EVENTS.includes(event))) {
1635
+ errors.push({
1636
+ path: ["webhookEvents"],
1637
+ message: `webhookEvents must be a list of: ${WEBHOOK_EVENTS.join(", ")}`
1638
+ });
1639
+ } else {
1640
+ values.webhookEvents = [...new Set(list)];
1641
+ }
1642
+ }
1643
+ if (has("genericWebhookUrl")) {
1644
+ const raw = body.genericWebhookUrl;
1645
+ if (typeof raw !== "string") {
1646
+ errors.push({ path: ["genericWebhookUrl"], message: "genericWebhookUrl must be a string" });
1647
+ } else if (!raw.trim()) {
1648
+ values.genericWebhookUrl = "";
1649
+ } else {
1650
+ const url = normalizeWebhookUrl(raw);
1651
+ if (!url) {
1652
+ errors.push({
1653
+ path: ["genericWebhookUrl"],
1654
+ message: "genericWebhookUrl must be an https URL without credentials on a public host name"
1655
+ });
1656
+ } else {
1657
+ values.genericWebhookUrl = url;
1658
+ }
1659
+ }
1660
+ }
1661
+ return { values, errors };
1662
+ }
1663
+ function resolveDetectionSettings(settings) {
1664
+ const source = settings && typeof settings === "object" ? settings : {};
1665
+ const clean = normalizeDetectionSettings(
1666
+ Object.fromEntries(
1667
+ DETECTION_KEYS.map((key) => [key, source[key]]).filter(([, v]) => v !== void 0)
1668
+ )
1669
+ );
1670
+ return (
1671
+ /** @type {any} */
1672
+ {
1673
+ ...DETECTION_DEFAULTS,
1674
+ webhookEvents: [...DEFAULT_WEBHOOK_EVENTS],
1675
+ ...clean
1676
+ }
1677
+ );
1678
+ }
1679
+ module.exports = {
1680
+ DEFAULT_WEBHOOK_EVENTS,
1681
+ DETECTION_DEFAULTS,
1682
+ DETECTION_KEYS,
1683
+ PROTECTED_DETECTION_KEYS,
1684
+ IMPOSSIBLE_TRAVEL_ACTIONS,
1685
+ LEGACY_WEBHOOK_EVENTS,
1686
+ WEBHOOK_EVENTS,
1687
+ normalizeDetectionSettings,
1688
+ normalizeWebhookUrl,
1689
+ resolveDetectionSettings,
1690
+ validateDetectionSettings
1691
+ };
1692
+ }
1693
+ });
1694
+
1445
1695
  // server/src/utils/settings-loader.js
1446
1696
  var require_settings_loader = __commonJS({
1447
1697
  "server/src/utils/settings-loader.js"(exports, module) {
1448
1698
  "use strict";
1449
1699
  var { getCoordinator } = require_coordination();
1450
1700
  var { normalizePolicySettings } = require_policy_settings();
1701
+ var { normalizeDetectionSettings } = require_detection_settings();
1451
1702
  var PLUGIN_ID = "magic-sessionmanager";
1452
1703
  var SETTINGS_KEY = "settings";
1453
1704
  var CACHE_TTL_MS = 30 * 1e3;
@@ -1580,6 +1831,10 @@ var require_settings_loader = __commonJS({
1580
1831
  out.trustedProxies = stored.trustedProxies;
1581
1832
  }
1582
1833
  Object.assign(out, normalizePolicySettings(stored));
1834
+ Object.assign(out, normalizeDetectionSettings(stored));
1835
+ if (typeof stored.genericWebhookSecret === "string") {
1836
+ out.genericWebhookSecret = stored.genericWebhookSecret;
1837
+ }
1583
1838
  return out;
1584
1839
  }
1585
1840
  async function getPluginSettings(strapi2) {
@@ -1697,7 +1952,11 @@ var require_security_log_model = __commonJS({
1697
1952
  USER_LOCKOUT: "user.lockout",
1698
1953
  USER_LOCKOUT_LIFTED: "user.lockout.lifted",
1699
1954
  USER_SESSION_LIMIT: "user.session.limit",
1700
- USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others"
1955
+ USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others",
1956
+ USER_NEW_DEVICE: "user.sign-in.new-device",
1957
+ USER_IMPOSSIBLE_TRAVEL: "user.sign-in.impossible-travel",
1958
+ USER_NOT_ME: "user.not-me",
1959
+ USER_DATA_EXPORTED: "user.data.exported"
1701
1960
  });
1702
1961
  var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
1703
1962
  SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
@@ -2447,7 +2706,13 @@ var require_encryption = __commonJS({
2447
2706
  function getEncryptionKeyCheck() {
2448
2707
  return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
2449
2708
  }
2709
+ function derivePurposeKey(purpose) {
2710
+ return Buffer.from(
2711
+ crypto.hkdfSync("sha256", getEncryptionKey(), "magic-sessionmanager", `msm:${purpose}`, 32)
2712
+ );
2713
+ }
2450
2714
  module.exports = {
2715
+ derivePurposeKey,
2451
2716
  getEncryptionKeyCheck,
2452
2717
  encryptToken,
2453
2718
  decryptToken,
@@ -2709,13 +2974,15 @@ var require_login_alerts = __commonJS({
2709
2974
  "server/src/utils/login-alerts.js"(exports, module) {
2710
2975
  "use strict";
2711
2976
  var { evaluateLoginRisk } = require_risk_data();
2977
+ var { resolveDetectionSettings } = require_detection_settings();
2712
2978
  async function dispatchLoginAlerts({
2713
2979
  settings,
2714
2980
  notificationService,
2715
2981
  user,
2716
2982
  session,
2717
2983
  geoData,
2718
- isNewLocation = false
2984
+ isNewLocation = false,
2985
+ webhooks = null
2719
2986
  }) {
2720
2987
  const attempted = { webhookEvent: null, emails: [] };
2721
2988
  if (!geoData) return attempted;
@@ -2749,8 +3016,22 @@ var require_login_alerts = __commonJS({
2749
3016
  await notificationService.sendNewLocationAlert({ user, session, geoData });
2750
3017
  }
2751
3018
  }
2752
- if (settings.enableWebhooks) {
2753
- const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
3019
+ const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
3020
+ const selected = resolveDetectionSettings(settings).webhookEvents.includes(webhookEvent);
3021
+ if (selected && webhooks) {
3022
+ webhooks.emit(
3023
+ webhookEvent,
3024
+ {
3025
+ userId: user?.documentId || null,
3026
+ ip: session?.ipAddress || null,
3027
+ userAgent: session?.userAgent || null,
3028
+ geo: geoData,
3029
+ details: null
3030
+ },
3031
+ { chat: false }
3032
+ );
3033
+ }
3034
+ if (settings.enableWebhooks && selected) {
2754
3035
  attempted.webhookEvent = webhookEvent;
2755
3036
  const targets = [];
2756
3037
  if (settings.discordWebhookUrl) {
@@ -4265,6 +4546,10 @@ var require_sign_in_policies = __commonJS({
4265
4546
  return options.anonymizeIp ? anonymizeIp(normalized) : normalized;
4266
4547
  }
4267
4548
  function recordUserEvent(strapi2, input) {
4549
+ try {
4550
+ strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(input);
4551
+ } catch {
4552
+ }
4268
4553
  try {
4269
4554
  return strapi2.plugin("magic-sessionmanager").service("security-log").record(input) === true;
4270
4555
  } catch {
@@ -4384,6 +4669,7 @@ var require_upgrade_defaults = __commonJS({
4384
4669
  "use strict";
4385
4670
  var { withPluginStoreKey } = require_plugin_store();
4386
4671
  var { notifySettingsChanged } = require_settings_loader();
4672
+ var { LEGACY_WEBHOOK_EVENTS } = require_detection_settings();
4387
4673
  var PROFILE_KEY = "defaultsProfile";
4388
4674
  var UPGRADE_STEPS = Object.freeze([
4389
4675
  Object.freeze({
@@ -4391,6 +4677,13 @@ var require_upgrade_defaults = __commonJS({
4391
4677
  release: "4.17.0",
4392
4678
  // Before 4.17 a password change kept the user's other sessions.
4393
4679
  legacy: Object.freeze({ endOtherSessionsOnPasswordChange: false })
4680
+ }),
4681
+ Object.freeze({
4682
+ version: 2,
4683
+ release: "sign-in signals and signed webhook",
4684
+ // Before, Discord and Slack received every sign-in (success, new
4685
+ // country, suspicious). New installations leave out every sign-in.
4686
+ legacy: Object.freeze({ webhookEvents: LEGACY_WEBHOOK_EVENTS })
4394
4687
  })
4395
4688
  ]);
4396
4689
  async function applyUpgradeDefaults(strapi2, log, steps = UPGRADE_STEPS) {
@@ -4412,7 +4705,7 @@ var require_upgrade_defaults = __commonJS({
4412
4705
  if (step.version <= profile) continue;
4413
4706
  for (const [key, value] of Object.entries(step.legacy)) {
4414
4707
  if (settings[key] !== void 0) continue;
4415
- settings[key] = value;
4708
+ settings[key] = Array.isArray(value) ? [...value] : value;
4416
4709
  applied.push(key);
4417
4710
  }
4418
4711
  }
@@ -4433,6 +4726,270 @@ var require_upgrade_defaults = __commonJS({
4433
4726
  }
4434
4727
  });
4435
4728
 
4729
+ // server/src/utils/not-me-link.js
4730
+ var require_not_me_link = __commonJS({
4731
+ "server/src/utils/not-me-link.js"(exports, module) {
4732
+ "use strict";
4733
+ var crypto = __require("node:crypto");
4734
+ var { derivePurposeKey } = require_encryption();
4735
+ var LIFETIME_MS = 72 * 60 * 60 * 1e3;
4736
+ var NONCE_PREFIX = "notme:";
4737
+ var DOCUMENT_ID = /^[A-Za-z0-9]{1,64}$/;
4738
+ var TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,400}\.[A-Za-z0-9_-]{43}$/;
4739
+ var signingKey = () => derivePurposeKey("not-me-link");
4740
+ var sign = (payload) => crypto.createHmac("sha256", signingKey()).update(payload).digest("base64url");
4741
+ async function issueNotMeToken(coordinator, { sessionId, userId, now = Date.now() }) {
4742
+ if (!DOCUMENT_ID.test(String(sessionId)) || !DOCUMENT_ID.test(String(userId))) return null;
4743
+ const nonce = crypto.randomBytes(18).toString("hex");
4744
+ const payload = Buffer.from(
4745
+ JSON.stringify({ s: sessionId, u: userId, e: now + LIFETIME_MS, n: nonce })
4746
+ ).toString("base64url");
4747
+ await coordinator.registryPut(
4748
+ `${NONCE_PREFIX}${nonce}`,
4749
+ { s: sessionId, u: userId },
4750
+ LIFETIME_MS
4751
+ );
4752
+ return `${payload}.${sign(payload)}`;
4753
+ }
4754
+ function readNotMeToken(token, { now = Date.now() } = {}) {
4755
+ if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) return null;
4756
+ const [payload, signature] = token.split(".");
4757
+ const expected = Buffer.from(sign(payload));
4758
+ const given = Buffer.from(signature);
4759
+ if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null;
4760
+ let claims;
4761
+ try {
4762
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
4763
+ } catch {
4764
+ return null;
4765
+ }
4766
+ 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) {
4767
+ return null;
4768
+ }
4769
+ return { sessionId: claims.s, userId: claims.u, nonce: claims.n, expiresAt: claims.e };
4770
+ }
4771
+ async function consumeNotMeToken(coordinator, token) {
4772
+ const claims = readNotMeToken(token);
4773
+ if (!claims) return null;
4774
+ const stored = await coordinator.registryTake(`${NONCE_PREFIX}${claims.nonce}`);
4775
+ if (!stored || stored.s !== claims.sessionId || stored.u !== claims.userId) return null;
4776
+ return { sessionId: claims.sessionId, userId: claims.userId };
4777
+ }
4778
+ module.exports = { LIFETIME_MS, consumeNotMeToken, issueNotMeToken, readNotMeToken };
4779
+ }
4780
+ });
4781
+
4782
+ // server/src/utils/sign-in-signals.js
4783
+ var require_sign_in_signals = __commonJS({
4784
+ "server/src/utils/sign-in-signals.js"(exports, module) {
4785
+ "use strict";
4786
+ var crypto = __require("node:crypto");
4787
+ var { derivePurposeKey } = require_encryption();
4788
+ var { parseUserAgent } = require_user_agent_parser();
4789
+ var { getCoordinator } = require_coordination();
4790
+ var { normalizeApiPrefix } = require_auth_routes();
4791
+ var { resolveDetectionSettings } = require_detection_settings();
4792
+ var { issueNotMeToken } = require_not_me_link();
4793
+ var { SECURITY_EVENTS } = require_security_log_model();
4794
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
4795
+ var HISTORY = 50;
4796
+ var EARTH_RADIUS_KM = 6371.0088;
4797
+ function deviceFamilies(userAgent) {
4798
+ const parsed = parseUserAgent(typeof userAgent === "string" ? userAgent.slice(0, 500) : "");
4799
+ return {
4800
+ browser: String(parsed.browserName || "unknown"),
4801
+ os: String(parsed.osName || "unknown"),
4802
+ deviceType: String(parsed.deviceType || "unknown")
4803
+ };
4804
+ }
4805
+ function family(value) {
4806
+ return String(value || "unknown").replace(/\s+[\d.]+$/, "").trim();
4807
+ }
4808
+ function deviceKeyOf(userAgent, deviceId) {
4809
+ const { browser, os, deviceType } = deviceFamilies(userAgent);
4810
+ const id = typeof deviceId === "string" && deviceId.length <= 128 ? deviceId : "";
4811
+ return crypto.createHmac("sha256", derivePurposeKey("device")).update(`${browser}|${os}|${deviceType}|${id}`).digest("hex").slice(0, 32);
4812
+ }
4813
+ function requestDeviceId(ctx) {
4814
+ const value = ctx?.request?.body?.deviceId;
4815
+ return typeof value === "string" && value && value.length <= 128 ? value : null;
4816
+ }
4817
+ function distanceKm(a, b) {
4818
+ const rad = (deg) => deg * Math.PI / 180;
4819
+ const dLat = rad(b.lat - a.lat);
4820
+ const dLon = rad(b.lon - a.lon);
4821
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
4822
+ return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)));
4823
+ }
4824
+ function pointOf(geo) {
4825
+ const lat = Number(geo?.latitude);
4826
+ const lon = Number(geo?.longitude);
4827
+ if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
4828
+ return null;
4829
+ }
4830
+ if (geo?.latitude === null || geo?.longitude === null) return null;
4831
+ return { lat: Math.round(lat * 10) / 10, lon: Math.round(lon * 10) / 10 };
4832
+ }
4833
+ function evaluateTravel(previous, current, { speedKmh, minDistanceKm }) {
4834
+ if (!previous?.point || !current?.point) return null;
4835
+ const km = distanceKm(previous.point, current.point);
4836
+ const hours = Math.max(current.at - previous.at, 60 * 1e3) / (60 * 60 * 1e3);
4837
+ const speed = km / hours;
4838
+ return {
4839
+ flagged: km >= minDistanceKm && speed > speedKmh,
4840
+ distanceKm: Math.round(km),
4841
+ speedKmh: Math.round(speed)
4842
+ };
4843
+ }
4844
+ async function previousSessions(strapi2, userDocumentId, exceptSessionId) {
4845
+ const rows = await strapi2.documents(SESSION_UID).findMany({
4846
+ filters: { user: { documentId: userDocumentId }, documentId: { $ne: exceptSessionId } },
4847
+ fields: [
4848
+ "documentId",
4849
+ "loginTime",
4850
+ "deviceKey",
4851
+ "browserName",
4852
+ "osName",
4853
+ "deviceType",
4854
+ "geoLocation"
4855
+ ],
4856
+ sort: [{ loginTime: "desc" }, { id: "desc" }],
4857
+ limit: HISTORY
4858
+ });
4859
+ return Array.isArray(rows) ? rows : [];
4860
+ }
4861
+ function isNewDevice(previous, { deviceKey, userAgent }) {
4862
+ if (previous.length === 0) return false;
4863
+ if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
4864
+ const families = deviceFamilies(userAgent);
4865
+ return !previous.some(
4866
+ (row) => !row.deviceKey && family(row.browserName) === families.browser && family(row.osName) === families.os
4867
+ );
4868
+ }
4869
+ function storedLocation(row) {
4870
+ let geo = row?.geoLocation;
4871
+ if (typeof geo === "string") {
4872
+ try {
4873
+ geo = JSON.parse(geo);
4874
+ } catch {
4875
+ geo = null;
4876
+ }
4877
+ }
4878
+ return {
4879
+ point: pointOf(geo),
4880
+ country: typeof geo?.country_code === "string" ? geo.country_code : null
4881
+ };
4882
+ }
4883
+ async function notMeUrl(strapi2, sessionId, userId) {
4884
+ const base = String(strapi2.config.get("server.absoluteUrl") || "").replace(/\/+$/, "");
4885
+ if (!/^https?:\/\/[^/]+/.test(base)) return null;
4886
+ const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
4887
+ if (!token) return null;
4888
+ const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
4889
+ return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
4890
+ }
4891
+ async function runSignInSignals({
4892
+ strapi: strapi2,
4893
+ settings,
4894
+ user,
4895
+ userDocumentId,
4896
+ session,
4897
+ geoData,
4898
+ deviceKey,
4899
+ userAgent,
4900
+ ip,
4901
+ record,
4902
+ now = Date.now()
4903
+ }) {
4904
+ const outcome = { newDevice: false, travel: null, reauthenticate: false };
4905
+ const detection = resolveDetectionSettings(settings);
4906
+ const plugin = strapi2.plugin("magic-sessionmanager");
4907
+ const emails = settings.enableEmailAlerts === true;
4908
+ const hasWebhookTarget = detection.genericWebhookEnabled && !!detection.genericWebhookUrl || settings.enableWebhooks === true && !!(settings.discordWebhookUrl || settings.slackWebhookUrl);
4909
+ const wantNewDevice = emails && detection.alertOnNewDevice || hasWebhookTarget && detection.webhookEvents.includes("login.new_device");
4910
+ const wantTravel = detection.impossibleTravelEnabled;
4911
+ if (!wantNewDevice && !wantTravel || !session?.documentId) return outcome;
4912
+ const previous = await previousSessions(strapi2, userDocumentId, session.documentId);
4913
+ const families = deviceFamilies(userAgent);
4914
+ let link;
4915
+ const linkOnce = async () => {
4916
+ if (link === void 0) link = await notMeUrl(strapi2, session.documentId, userDocumentId);
4917
+ return link;
4918
+ };
4919
+ const notifications = plugin.service("notifications");
4920
+ const facts = { user, session, geoData, device: { browser: families.browser, os: families.os } };
4921
+ if (wantNewDevice && isNewDevice(previous, { deviceKey, userAgent })) {
4922
+ outcome.newDevice = true;
4923
+ record({
4924
+ event: SECURITY_EVENTS.USER_NEW_DEVICE,
4925
+ actorType: "user",
4926
+ actorId: userDocumentId,
4927
+ targetType: "user",
4928
+ targetId: userDocumentId,
4929
+ ip,
4930
+ userAgent,
4931
+ meta: { browser: families.browser, os: families.os, deviceType: families.deviceType }
4932
+ });
4933
+ if (emails && detection.alertOnNewDevice) {
4934
+ const url = await linkOnce();
4935
+ notifications.sendSignInSignalEmail("newDevice", { ...facts, link: url }).catch(() => {
4936
+ });
4937
+ }
4938
+ }
4939
+ if (wantTravel) {
4940
+ const before = previous.find((row) => storedLocation(row).point);
4941
+ const result = before ? evaluateTravel(
4942
+ { point: storedLocation(before).point, at: new Date(before.loginTime).getTime() },
4943
+ { point: pointOf(geoData), at: now },
4944
+ {
4945
+ speedKmh: detection.impossibleTravelSpeedKmh,
4946
+ minDistanceKm: detection.impossibleTravelMinDistanceKm
4947
+ }
4948
+ ) : null;
4949
+ if (result?.flagged) {
4950
+ outcome.travel = result;
4951
+ record({
4952
+ event: SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
4953
+ actorType: "user",
4954
+ actorId: userDocumentId,
4955
+ targetType: "user",
4956
+ targetId: userDocumentId,
4957
+ ip,
4958
+ userAgent,
4959
+ meta: {
4960
+ distanceKm: result.distanceKm,
4961
+ speedKmh: result.speedKmh,
4962
+ from: storedLocation(before).country,
4963
+ to: typeof geoData?.country_code === "string" ? geoData.country_code : null,
4964
+ action: detection.impossibleTravelAction
4965
+ }
4966
+ });
4967
+ if (emails && detection.alertOnImpossibleTravel) {
4968
+ const url = await linkOnce();
4969
+ notifications.sendSignInSignalEmail("impossibleTravel", { ...facts, travel: result, link: url }).catch(() => {
4970
+ });
4971
+ }
4972
+ outcome.reauthenticate = detection.impossibleTravelAction === "reauthenticate";
4973
+ }
4974
+ }
4975
+ return outcome;
4976
+ }
4977
+ module.exports = {
4978
+ notMeUrl,
4979
+ runSignInSignals,
4980
+ deviceFamilies,
4981
+ deviceKeyOf,
4982
+ distanceKm,
4983
+ evaluateTravel,
4984
+ isNewDevice,
4985
+ pointOf,
4986
+ previousSessions,
4987
+ requestDeviceId,
4988
+ storedLocation
4989
+ };
4990
+ }
4991
+ });
4992
+
4436
4993
  // server/src/middlewares/session-rejection-headers.js
4437
4994
  var require_session_rejection_headers = __commonJS({
4438
4995
  "server/src/middlewares/session-rejection-headers.js"(exports, module) {
@@ -8576,6 +9133,7 @@ var require_bootstrap = __commonJS({
8576
9133
  } = require_sign_in_policies();
8577
9134
  var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
8578
9135
  var { applyUpgradeDefaults } = require_upgrade_defaults();
9136
+ var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
8579
9137
  var { anonymizeIp, normalizeIp } = require_admin_request_info();
8580
9138
  var SESSION_UID = "plugin::magic-sessionmanager.session";
8581
9139
  var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -9215,6 +9773,13 @@ var require_bootstrap = __commonJS({
9215
9773
  };
9216
9774
  return byName[err?.name] || 500;
9217
9775
  }
9776
+ function optionalService(strapi2, name) {
9777
+ try {
9778
+ return strapi2.plugin("magic-sessionmanager").service(name) || null;
9779
+ } catch {
9780
+ return null;
9781
+ }
9782
+ }
9218
9783
  function refuseSessionLimit({ ctx, strapi: strapi2, limit }) {
9219
9784
  stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
9220
9785
  ctx.status = 403;
@@ -9438,6 +10003,7 @@ var require_bootstrap = __commonJS({
9438
10003
  const geoData = ctx.state?.__magicSessionGeoData || null;
9439
10004
  const requestSettings = await getPluginSettings(strapi2);
9440
10005
  const isReset = isPasswordResetRequest(apiPath, ctx.method);
10006
+ const deviceKey = deviceKeyOf(userAgent, requestDeviceId(ctx));
9441
10007
  const create = () => sessionService.createSession({
9442
10008
  userId: userDocId,
9443
10009
  ip,
@@ -9445,6 +10011,7 @@ var require_bootstrap = __commonJS({
9445
10011
  token: ctx.body.jwt,
9446
10012
  refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
9447
10013
  geoData,
10014
+ deviceKey,
9448
10015
  ...nativeSession ? { nativeSessionId: nativeSession.sessionId } : {}
9449
10016
  });
9450
10017
  const limited = isReset ? { session: await create(), refused: false, ended: 0, limit: 0 } : await createSessionWithinLimit({
@@ -9494,9 +10061,45 @@ var require_bootstrap = __commonJS({
9494
10061
  log.info("[PASSWORD] Ended older sessions after password reset");
9495
10062
  }
9496
10063
  log.info("[SUCCESS] End-user session metadata created");
10064
+ let signals = { reauthenticate: false };
10065
+ if (!isReset) {
10066
+ try {
10067
+ signals = await runSignInSignals({
10068
+ strapi: strapi2,
10069
+ settings: requestSettings,
10070
+ user,
10071
+ userDocumentId: userDocId,
10072
+ session: newSession,
10073
+ geoData,
10074
+ deviceKey,
10075
+ userAgent: userAgent === "unknown" ? null : userAgent,
10076
+ ip,
10077
+ record: (input) => recordUserEvent(strapi2, input)
10078
+ });
10079
+ } catch (signalErr) {
10080
+ log.warn("[SIGNALS] Sign-in signals failed (non-fatal):", signalErr?.name || "Error");
10081
+ }
10082
+ }
10083
+ if (signals.reauthenticate) {
10084
+ await sessionService.terminateSession({ userId: userDocId, reason: "manual" });
10085
+ stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
10086
+ ctx.status = 401;
10087
+ ctx.body = {
10088
+ data: null,
10089
+ error: {
10090
+ status: 401,
10091
+ name: "UnauthorizedError",
10092
+ message: "Please sign in again.",
10093
+ details: { code: "REAUTHENTICATION_REQUIRED" }
10094
+ }
10095
+ };
10096
+ log.info("[SIGNALS] Impossible travel: every session ended, a new sign-in is required");
10097
+ return;
10098
+ }
9497
10099
  try {
9498
10100
  const settings = await getPluginSettings(strapi2);
9499
- if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks)) {
10101
+ const genericWebhook = settings.genericWebhookEnabled === true;
10102
+ if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks || genericWebhook)) {
9500
10103
  return;
9501
10104
  }
9502
10105
  const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
@@ -9548,7 +10151,8 @@ var require_bootstrap = __commonJS({
9548
10151
  user,
9549
10152
  session: newSession,
9550
10153
  geoData,
9551
- isNewLocation
10154
+ isNewLocation,
10155
+ webhooks: optionalService(strapi2, "webhooks")
9552
10156
  });
9553
10157
  } catch (notifErr) {
9554
10158
  log.warn("Notification failed:", notifErr?.name || "Error");
@@ -9886,7 +10490,7 @@ var require_bootstrap = __commonJS({
9886
10490
  );
9887
10491
  return false;
9888
10492
  }
9889
- const requiredActions = [
10493
+ const baseActions = [
9890
10494
  "plugin::magic-sessionmanager.session.logout",
9891
10495
  "plugin::magic-sessionmanager.session.logoutAll",
9892
10496
  "plugin::magic-sessionmanager.session.logoutOthers",
@@ -9895,6 +10499,8 @@ var require_bootstrap = __commonJS({
9895
10499
  "plugin::magic-sessionmanager.session.getCurrentSession",
9896
10500
  "plugin::magic-sessionmanager.session.terminateOwnSession"
9897
10501
  ];
10502
+ const version3Actions = ["plugin::magic-sessionmanager.self-service.exportOwnData"];
10503
+ const requiredActions = Number(effectiveVersion) === 2 ? version3Actions : [...baseActions, ...version3Actions];
9898
10504
  const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
9899
10505
  filters: {
9900
10506
  role: authenticatedRole.id,
@@ -10409,6 +11015,11 @@ var require_destroy = __commonJS({
10409
11015
  }
10410
11016
  strapi2.sessionManagerAdminActivityUninstall = null;
10411
11017
  }
11018
+ try {
11019
+ strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
11020
+ } catch (err) {
11021
+ log.warn("Failed to stop webhook deliveries:", err?.name || "Error");
11022
+ }
10412
11023
  log.info("[SUCCESS] Plugin cleanup completed");
10413
11024
  };
10414
11025
  }
@@ -10623,6 +11234,12 @@ var require_schema = __commonJS({
10623
11234
  },
10624
11235
  osName: {
10625
11236
  type: "string"
11237
+ },
11238
+ deviceKey: {
11239
+ type: "string",
11240
+ maxLength: 64,
11241
+ configurable: false,
11242
+ private: true
10626
11243
  }
10627
11244
  }
10628
11245
  };
@@ -10863,6 +11480,57 @@ var require_content_api = __commonJS({
10863
11480
  description: "Get sessions by userId (user can only see own sessions)"
10864
11481
  }
10865
11482
  },
11483
+ // ================== SELF-SERVICE (4.17) ==================
11484
+ {
11485
+ method: "GET",
11486
+ path: "/my-data",
11487
+ handler: "self-service.exportOwnData",
11488
+ config: {
11489
+ auth: { strategies: ["users-permissions"] },
11490
+ // An export reads every own session and event: 3 per hour per user.
11491
+ middlewares: [
11492
+ {
11493
+ name: "plugin::magic-sessionmanager.rate-limit",
11494
+ config: { max: 3, window: 60 * 60 * 1e3 }
11495
+ }
11496
+ ],
11497
+ description: "Download own sessions and security events as JSON (GDPR Art. 15)"
11498
+ }
11499
+ },
11500
+ {
11501
+ method: "GET",
11502
+ path: "/not-me",
11503
+ handler: "self-service.notMePage",
11504
+ config: {
11505
+ // Public on purpose: opened from the "This wasn't me" email. Only
11506
+ // shows a confirmation; the signed token is checked, nothing changes.
11507
+ auth: false,
11508
+ middlewares: [
11509
+ {
11510
+ name: "plugin::magic-sessionmanager.rate-limit",
11511
+ config: { max: 30, window: 6e4 }
11512
+ }
11513
+ ],
11514
+ description: `Confirmation page of the "This wasn't me" email link (public)`
11515
+ }
11516
+ },
11517
+ {
11518
+ method: "POST",
11519
+ path: "/not-me",
11520
+ handler: "self-service.notMeConfirm",
11521
+ config: {
11522
+ // Public on purpose: the signed, expiring, single-use token from the
11523
+ // email is the authorisation.
11524
+ auth: false,
11525
+ middlewares: [
11526
+ {
11527
+ name: "plugin::magic-sessionmanager.rate-limit",
11528
+ config: { max: 10, window: 6e4 }
11529
+ }
11530
+ ],
11531
+ description: `End the session of a "This wasn't me" link (public, single-use token)`
11532
+ }
11533
+ },
10866
11534
  // ================== OWN SESSION MANAGEMENT ==================
10867
11535
  {
10868
11536
  method: "DELETE",
@@ -10888,6 +11556,7 @@ var require_admin = __commonJS({
10888
11556
  var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
10889
11557
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
10890
11558
  var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
11559
+ var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
10891
11560
  var adminPolicy = () => [
10892
11561
  "admin::isAuthenticatedAdmin",
10893
11562
  {
@@ -11172,15 +11841,32 @@ var require_admin = __commonJS({
11172
11841
  description: "List Users & Permissions roles for per-role rules (admin)"
11173
11842
  }
11174
11843
  },
11175
- // ============================ GEOLOCATION ============================
11844
+ // ============================ SIGNED WEBHOOK ============================
11176
11845
  {
11177
- method: "GET",
11178
- path: "/geolocation/:ipAddress",
11179
- handler: "session.getIpGeolocation",
11846
+ method: "POST",
11847
+ path: "/webhook/test",
11848
+ handler: "webhooks.sendTest",
11180
11849
  config: {
11181
- policies: adminPolicy(),
11182
- description: "Get IP geolocation data (admin)"
11183
- }
11850
+ // Sends to the stored URL: same permission as changing it.
11851
+ policies: adminSessionsPolicy([SETTINGS_UPDATE_ACTION]),
11852
+ middlewares: [
11853
+ {
11854
+ name: "plugin::magic-sessionmanager.rate-limit",
11855
+ config: { profile: "write", max: 5, window: 6e4 }
11856
+ }
11857
+ ],
11858
+ description: "Send a signed test event to the stored webhook URL (admin)"
11859
+ }
11860
+ },
11861
+ // ============================ GEOLOCATION ============================
11862
+ {
11863
+ method: "GET",
11864
+ path: "/geolocation/:ipAddress",
11865
+ handler: "session.getIpGeolocation",
11866
+ config: {
11867
+ policies: adminPolicy(),
11868
+ description: "Get IP geolocation data (admin)"
11869
+ }
11184
11870
  },
11185
11871
  {
11186
11872
  method: "GET",
@@ -13505,6 +14191,7 @@ var require_settings_access = __commonJS({
13505
14191
  "use strict";
13506
14192
  var { SECURITY_LOG_KEYS } = require_security_log_settings();
13507
14193
  var { POLICY_KEYS } = require_policy_settings();
14194
+ var { PROTECTED_DETECTION_KEYS } = require_detection_settings();
13508
14195
  var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
13509
14196
  var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
13510
14197
  var GEO_SETTINGS_KEYS = Object.freeze([
@@ -13524,11 +14211,17 @@ var require_settings_access = __commonJS({
13524
14211
  ...SECURITY_LOG_KEYS,
13525
14212
  // Sign-in and session policies (lockout, trusted addresses, session
13526
14213
  // limit, password-change sign-out, recording switch, per-role rules).
13527
- ...POLICY_KEYS
14214
+ ...POLICY_KEYS,
14215
+ // Signed webhook, event selection, impossible travel and shortened IPs.
14216
+ ...PROTECTED_DETECTION_KEYS
13528
14217
  ]);
13529
14218
  var WEBHOOK_SECRETS = Object.freeze([
13530
14219
  { key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
13531
- { key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" }
14220
+ { key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" },
14221
+ { key: "genericWebhookUrl", has: "hasGenericWebhook", hint: "genericWebhookHint" }
14222
+ ]);
14223
+ var WRITE_ONLY_SECRETS = Object.freeze([
14224
+ { key: "genericWebhookSecret", has: "hasGenericWebhookSecret" }
13532
14225
  ]);
13533
14226
  function sameValue(a, b) {
13534
14227
  if (a === b) return true;
@@ -13576,6 +14269,11 @@ var require_settings_access = __commonJS({
13576
14269
  out[has] = typeof value === "string" && value.trim().length > 0;
13577
14270
  out[hint] = webhookHint(value);
13578
14271
  }
14272
+ for (const { key, has } of WRITE_ONLY_SECRETS) {
14273
+ const value = out[key];
14274
+ delete out[key];
14275
+ out[has] = typeof value === "string" && value.length > 0;
14276
+ }
13579
14277
  return out;
13580
14278
  }
13581
14279
  module.exports = {
@@ -13585,6 +14283,7 @@ var require_settings_access = __commonJS({
13585
14283
  SETTINGS_UPDATE_ACTION,
13586
14284
  WEBHOOK_SECRETS,
13587
14285
  WEBHOOK_SETTINGS_KEYS,
14286
+ WRITE_ONLY_SECRETS,
13588
14287
  callerCan,
13589
14288
  changedKeys,
13590
14289
  missingSettingsPermission,
@@ -13618,6 +14317,9 @@ var require_settings = __commonJS({
13618
14317
  toPublicSettings
13619
14318
  } = require_settings_access();
13620
14319
  var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
14320
+ var { DETECTION_DEFAULTS, validateDetectionSettings } = require_detection_settings();
14321
+ var { encryptToken } = require_encryption();
14322
+ var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
13621
14323
  var path = __require("node:path");
13622
14324
  var ALLOWED_WEBHOOK_DOMAINS = {
13623
14325
  discord: ["discord.com", "discordapp.com"],
@@ -13759,7 +14461,9 @@ var require_settings = __commonJS({
13759
14461
  newLocation: { subject: "", html: "", text: "" },
13760
14462
  vpnProxy: { subject: "", html: "", text: "" },
13761
14463
  // 4.17: sent to a user whose account was locked after failed sign-ins.
13762
- accountLocked: { subject: "", html: "", text: "" }
14464
+ accountLocked: { subject: "", html: "", text: "" },
14465
+ newDevice: { subject: "", html: "", text: "" },
14466
+ impossibleTravel: { subject: "", html: "", text: "" }
13763
14467
  };
13764
14468
  var DEFAULT_SETTINGS = {
13765
14469
  inactivityTimeout: 15,
@@ -13795,7 +14499,10 @@ var require_settings = __commonJS({
13795
14499
  ...SECURITY_LOG_DEFAULTS,
13796
14500
  ...POLICY_DEFAULTS,
13797
14501
  lockoutTrustedAddresses: [],
13798
- roleRules: []
14502
+ roleRules: [],
14503
+ ...DETECTION_DEFAULTS,
14504
+ webhookEvents: [...DETECTION_DEFAULTS.webhookEvents],
14505
+ genericWebhookSecret: ""
13799
14506
  };
13800
14507
  function mergeSettingsWithDefaults(stored) {
13801
14508
  const safeStored = stored && typeof stored === "object" ? stored : {};
@@ -14006,6 +14713,22 @@ var require_settings = __commonJS({
14006
14713
  const policies = validatePolicySettings(body);
14007
14714
  errors.push(...policies.errors);
14008
14715
  Object.assign(next, policies.values);
14716
+ const detection = validateDetectionSettings(body);
14717
+ errors.push(...detection.errors);
14718
+ Object.assign(next, detection.values);
14719
+ if (has("genericWebhookSecret")) {
14720
+ const secret = body.genericWebhookSecret;
14721
+ if (secret === "") {
14722
+ next.genericWebhookSecret = "";
14723
+ } else if (typeof secret !== "string" || !WEBHOOK_SECRET_PATTERN.test(secret)) {
14724
+ errors.push({
14725
+ path: ["genericWebhookSecret"],
14726
+ message: "genericWebhookSecret must be 32 to 256 printable characters without spaces"
14727
+ });
14728
+ } else {
14729
+ next.genericWebhookSecret = encryptToken(secret);
14730
+ }
14731
+ }
14009
14732
  if (errors.length > 0) return { errors };
14010
14733
  const settings = {};
14011
14734
  for (const key of Object.keys(DEFAULT_SETTINGS)) {
@@ -14035,7 +14758,7 @@ var require_settings = __commonJS({
14035
14758
  }
14036
14759
  var FORBIDDEN_MESSAGES = Object.freeze({
14037
14760
  "admin-activity-permission": 'Changing the security log settings needs "View admin activity".',
14038
- "settings-update-permission": 'Changing location lookup, webhook or security log settings needs "Change protected settings".'
14761
+ "settings-update-permission": 'Changing location lookup, webhook, security log, sign-in policy or detection settings needs "Change protected settings".'
14039
14762
  });
14040
14763
  function recordSettingsChange(ctx, keys) {
14041
14764
  if (!keys.length) return;
@@ -14206,6 +14929,7 @@ var require_settings = __commonJS({
14206
14929
  },
14207
14930
  DEFAULT_SETTINGS,
14208
14931
  mergeSettingsWithDefaults,
14932
+ toPublicSettings,
14209
14933
  validateSettingsUpdate
14210
14934
  };
14211
14935
  }
@@ -15624,6 +16348,15 @@ var require_lockouts = __commonJS({
15624
16348
  const lifted = await lockout().unlock(id);
15625
16349
  if (!lifted) return ctx.notFound("This lock has already ended");
15626
16350
  try {
16351
+ const liftEvent = {
16352
+ event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
16353
+ actorType: "admin",
16354
+ actorId: ctx.state?.user?.id ?? null,
16355
+ targetType: lifted.kind === "account" ? "user" : "ip",
16356
+ targetId: lifted.kind === "account" ? lifted.user : null,
16357
+ meta: { kind: lifted.kind }
16358
+ };
16359
+ strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(liftEvent);
15627
16360
  strapi2.plugin("magic-sessionmanager").service("security-log").record({
15628
16361
  event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
15629
16362
  actorType: "admin",
@@ -15677,6 +16410,333 @@ var require_lockouts = __commonJS({
15677
16410
  }
15678
16411
  });
15679
16412
 
16413
+ // server/src/controllers/self-service.js
16414
+ var require_self_service = __commonJS({
16415
+ "server/src/controllers/self-service.js"(exports, module) {
16416
+ "use strict";
16417
+ var { getCoordinator } = require_coordination();
16418
+ var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
16419
+ var { recordUserEvent } = require_sign_in_policies();
16420
+ var { resolveUserDocumentId } = require_resolve_user();
16421
+ var { SECURITY_EVENTS } = require_security_log_model();
16422
+ var { sendServerError } = require_http_errors();
16423
+ var { createLogger } = require_logger();
16424
+ var SESSION_UID = "plugin::magic-sessionmanager.session";
16425
+ var EVENT_UID = "plugin::magic-sessionmanager.security-event";
16426
+ var USER_UID = "plugin::users-permissions.user";
16427
+ var EXPORT_LIMIT = 5e3;
16428
+ var EXPORT_BATCH = 500;
16429
+ var PAGE_TEXT = Object.freeze({
16430
+ en: {
16431
+ title: "Was this sign-in not you?",
16432
+ body: "Sign the device of that sign-in out now. Then change your password.",
16433
+ one: "Sign out that device",
16434
+ all: "Sign out everywhere",
16435
+ done: "Done. The session was ended. Change your password now.",
16436
+ doneAll: "Done. Every session of your account was ended. Change your password now.",
16437
+ invalid: "This link is no longer valid. It works once and expires after 72 hours."
16438
+ },
16439
+ de: {
16440
+ title: "Waren Sie das nicht?",
16441
+ body: "Melden Sie das Ger\xE4t dieser Anmeldung jetzt ab. \xC4ndern Sie danach Ihr Passwort.",
16442
+ one: "Dieses Ger\xE4t abmelden",
16443
+ all: "\xDCberall abmelden",
16444
+ done: "Erledigt. Die Sitzung wurde beendet. \xC4ndern Sie jetzt Ihr Passwort.",
16445
+ doneAll: "Erledigt. Alle Sitzungen Ihres Kontos wurden beendet. \xC4ndern Sie jetzt Ihr Passwort.",
16446
+ invalid: "Dieser Link ist nicht mehr g\xFCltig. Er funktioniert einmal und l\xE4uft nach 72 Stunden ab."
16447
+ },
16448
+ fr: {
16449
+ title: "Cette connexion n\u2019\xE9tait pas vous ?",
16450
+ body: "D\xE9connectez maintenant l\u2019appareil de cette connexion, puis changez votre mot de passe.",
16451
+ one: "D\xE9connecter cet appareil",
16452
+ all: "Se d\xE9connecter partout",
16453
+ done: "C\u2019est fait. La session a \xE9t\xE9 termin\xE9e. Changez maintenant votre mot de passe.",
16454
+ doneAll: "C\u2019est fait. Toutes les sessions de votre compte ont \xE9t\xE9 termin\xE9es. Changez maintenant votre mot de passe.",
16455
+ invalid: "Ce lien n\u2019est plus valide. Il fonctionne une fois et expire apr\xE8s 72 heures."
16456
+ },
16457
+ es: {
16458
+ title: "\xBFEste inicio de sesi\xF3n no fue usted?",
16459
+ body: "Cierre ahora la sesi\xF3n del dispositivo de ese inicio de sesi\xF3n y despu\xE9s cambie su contrase\xF1a.",
16460
+ one: "Cerrar la sesi\xF3n de ese dispositivo",
16461
+ all: "Cerrar sesi\xF3n en todas partes",
16462
+ done: "Hecho. La sesi\xF3n ha terminado. Cambie ahora su contrase\xF1a.",
16463
+ doneAll: "Hecho. Todas las sesiones de su cuenta han terminado. Cambie ahora su contrase\xF1a.",
16464
+ invalid: "Este enlace ya no es v\xE1lido. Funciona una vez y caduca a las 72 horas."
16465
+ },
16466
+ pt: {
16467
+ title: "Este in\xEDcio de sess\xE3o n\xE3o foi seu?",
16468
+ body: "Termine agora a sess\xE3o do dispositivo desse in\xEDcio de sess\xE3o e depois altere a sua palavra-passe.",
16469
+ one: "Terminar a sess\xE3o desse dispositivo",
16470
+ all: "Terminar sess\xE3o em todo o lado",
16471
+ done: "Feito. A sess\xE3o foi terminada. Altere agora a sua palavra-passe.",
16472
+ doneAll: "Feito. Todas as sess\xF5es da sua conta foram terminadas. Altere agora a sua palavra-passe.",
16473
+ invalid: "Esta liga\xE7\xE3o j\xE1 n\xE3o \xE9 v\xE1lida. Funciona uma vez e expira ap\xF3s 72 horas."
16474
+ }
16475
+ });
16476
+ function pageLanguage(ctx) {
16477
+ const header = String(ctx.request?.headers?.["accept-language"] || "").slice(0, 200);
16478
+ for (const part of header.split(",")) {
16479
+ const code = part.trim().slice(0, 2).toLowerCase();
16480
+ if (Object.prototype.hasOwnProperty.call(PAGE_TEXT, code)) {
16481
+ return (
16482
+ /** @type {keyof typeof PAGE_TEXT} */
16483
+ code
16484
+ );
16485
+ }
16486
+ }
16487
+ return "en";
16488
+ }
16489
+ var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
16490
+ function sendPage(ctx, status, lang, title, body) {
16491
+ ctx.status = status;
16492
+ ctx.set("Content-Type", "text/html; charset=utf-8");
16493
+ ctx.set(
16494
+ "Content-Security-Policy",
16495
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
16496
+ );
16497
+ ctx.set("Referrer-Policy", "no-referrer");
16498
+ ctx.set("Cache-Control", "no-store");
16499
+ ctx.set("X-Robots-Tag", "noindex");
16500
+ 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>
16501
+ <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>
16502
+ <body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
16503
+ }
16504
+ module.exports = ({ strapi: strapi2 }) => {
16505
+ const log = createLogger(strapi2);
16506
+ return {
16507
+ /**
16508
+ * Confirmation page of the "This wasn't me" link. Uses nothing.
16509
+ *
16510
+ * @route GET /api/magic-sessionmanager/not-me?token=
16511
+ * @auth none (public on purpose: the link is opened from an email; the
16512
+ * signed token is checked, and nothing changes until the POST)
16513
+ * @param {any} ctx Koa context.
16514
+ * @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
16515
+ */
16516
+ async notMePage(ctx) {
16517
+ const lang = pageLanguage(ctx);
16518
+ const text = PAGE_TEXT[lang];
16519
+ const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
16520
+ if (!readNotMeToken(token)) {
16521
+ return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
16522
+ }
16523
+ 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>`;
16524
+ return sendPage(
16525
+ ctx,
16526
+ 200,
16527
+ lang,
16528
+ text.title,
16529
+ `<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
16530
+ );
16531
+ },
16532
+ /**
16533
+ * Uses a "This wasn't me" token: ends that session, or every session of
16534
+ * the user with `scope=all`, and records `user.not-me`.
16535
+ *
16536
+ * @route POST /api/magic-sessionmanager/not-me
16537
+ * @auth none (public on purpose; the signed single-use token authorises)
16538
+ * @param {any} ctx Koa context; body `{ token, scope?: 'session'|'all' }` (form or JSON).
16539
+ * @returns {Promise<void>} 200 page (or JSON `{ ended }` with Accept: application/json);
16540
+ * 410 when the token is invalid, expired or used.
16541
+ * @sideeffect Ends sessions (and native sessions); writes a security event.
16542
+ */
16543
+ async notMeConfirm(ctx) {
16544
+ const lang = pageLanguage(ctx);
16545
+ const text = PAGE_TEXT[lang];
16546
+ const wantsJson = String(ctx.request?.headers?.accept || "").includes("application/json");
16547
+ const body = ctx.request?.body && typeof ctx.request.body === "object" ? ctx.request.body : {};
16548
+ const scope = body.scope === "all" ? "all" : "session";
16549
+ const claims = await consumeNotMeToken(getCoordinator(strapi2), body.token);
16550
+ if (!claims) {
16551
+ if (wantsJson) {
16552
+ ctx.status = 410;
16553
+ ctx.body = {
16554
+ data: null,
16555
+ error: { status: 410, name: "GoneError", message: "This link is no longer valid" }
16556
+ };
16557
+ return;
16558
+ }
16559
+ return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
16560
+ }
16561
+ try {
16562
+ const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
16563
+ let ended = 0;
16564
+ if (scope === "all") {
16565
+ ended = Number(
16566
+ (await sessionService.terminateSession({ userId: claims.userId, reason: "manual" }))?.terminatedCount
16567
+ ) || 0;
16568
+ } else {
16569
+ const session = await strapi2.documents(SESSION_UID).findFirst({
16570
+ filters: { documentId: claims.sessionId, user: { documentId: claims.userId } },
16571
+ fields: ["documentId", "isActive"]
16572
+ });
16573
+ if (session?.isActive) {
16574
+ ended = Number(
16575
+ (await sessionService.terminateSession({
16576
+ sessionId: session.documentId,
16577
+ reason: "manual"
16578
+ }))?.terminatedCount
16579
+ ) || 0;
16580
+ }
16581
+ }
16582
+ recordUserEvent(strapi2, {
16583
+ event: SECURITY_EVENTS.USER_NOT_ME,
16584
+ actorType: "user",
16585
+ actorId: claims.userId,
16586
+ targetType: "user",
16587
+ targetId: claims.userId,
16588
+ ip: ctx.request?.ip || null,
16589
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
16590
+ meta: { scope, ended }
16591
+ });
16592
+ if (wantsJson) {
16593
+ ctx.body = { data: { ended, scope } };
16594
+ return;
16595
+ }
16596
+ return sendPage(
16597
+ ctx,
16598
+ 200,
16599
+ lang,
16600
+ text.title,
16601
+ `<p>${escapeHtml(scope === "all" ? text.doneAll : text.done)}</p>`
16602
+ );
16603
+ } catch (err) {
16604
+ log.error("[not-me] Ending the session failed:", err?.name || "Error");
16605
+ return sendServerError(ctx, 500, "The session could not be ended");
16606
+ }
16607
+ },
16608
+ /**
16609
+ * The signed-in user's own sessions and security events as JSON (GDPR
16610
+ * Art. 15). Tokens, token hashes, device keys and native ids are never
16611
+ * included. At most 5,000 rows of each kind, newest first.
16612
+ *
16613
+ * @route GET /api/magic-sessionmanager/my-data
16614
+ * @auth users-permissions JWT (own data only; the user comes from the token)
16615
+ * @access plugin::magic-sessionmanager.self-service.exportOwnData (Authenticated role)
16616
+ * @param {any} ctx Koa context.
16617
+ * @returns {Promise<void>} 200 JSON attachment; 401 without a user.
16618
+ * @sideeffect Writes a `user.data.exported` security event.
16619
+ */
16620
+ async exportOwnData(ctx) {
16621
+ const authUser = ctx.state?.user;
16622
+ const userDocumentId = authUser?.documentId || (authUser?.id ? await resolveUserDocumentId(strapi2, authUser.id) : null);
16623
+ if (!userDocumentId) return ctx.unauthorized("Authentication required");
16624
+ try {
16625
+ const user = await strapi2.db.query(USER_UID).findOne({
16626
+ where: { documentId: userDocumentId },
16627
+ select: ["documentId", "username", "email", "createdAt"]
16628
+ });
16629
+ const sessions = [];
16630
+ for (let start = 0; start < EXPORT_LIMIT; start += EXPORT_BATCH) {
16631
+ const rows = await strapi2.documents(SESSION_UID).findMany({
16632
+ filters: { user: { documentId: userDocumentId } },
16633
+ fields: [
16634
+ "documentId",
16635
+ "loginTime",
16636
+ "lastActive",
16637
+ "logoutTime",
16638
+ "isActive",
16639
+ "terminationReason",
16640
+ "ipAddress",
16641
+ "userAgent",
16642
+ "deviceType",
16643
+ "browserName",
16644
+ "osName",
16645
+ "geoLocation"
16646
+ ],
16647
+ sort: [{ loginTime: "desc" }, { id: "desc" }],
16648
+ start,
16649
+ limit: EXPORT_BATCH
16650
+ });
16651
+ const list = Array.isArray(rows) ? rows : [];
16652
+ sessions.push(...list.map(({ id: _id, ...row }) => row));
16653
+ if (list.length < EXPORT_BATCH) break;
16654
+ }
16655
+ const events = await strapi2.db.query(EVENT_UID).findMany({
16656
+ where: {
16657
+ $or: [
16658
+ { targetType: "user", targetId: userDocumentId },
16659
+ { actorType: "user", actorId: userDocumentId }
16660
+ ]
16661
+ },
16662
+ select: ["event", "createdAt", "ip", "userAgent", "geo", "meta"],
16663
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
16664
+ limit: EXPORT_LIMIT
16665
+ });
16666
+ recordUserEvent(strapi2, {
16667
+ event: SECURITY_EVENTS.USER_DATA_EXPORTED,
16668
+ actorType: "user",
16669
+ actorId: userDocumentId,
16670
+ targetType: "user",
16671
+ targetId: userDocumentId,
16672
+ ip: ctx.request?.ip || null,
16673
+ userAgent: ctx.request?.headers?.["user-agent"] || null,
16674
+ meta: { sessions: sessions.length, events: Array.isArray(events) ? events.length : 0 }
16675
+ });
16676
+ ctx.set("Content-Disposition", 'attachment; filename="my-session-data.json"');
16677
+ ctx.set("Cache-Control", "no-store");
16678
+ ctx.body = {
16679
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
16680
+ user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
16681
+ sessions,
16682
+ securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
16683
+ };
16684
+ } catch (err) {
16685
+ log.error("[my-data] Export failed:", err?.name || "Error");
16686
+ return sendServerError(ctx, 500, "Your data could not be exported");
16687
+ }
16688
+ }
16689
+ };
16690
+ };
16691
+ }
16692
+ });
16693
+
16694
+ // server/src/controllers/webhooks.js
16695
+ var require_webhooks = __commonJS({
16696
+ "server/src/controllers/webhooks.js"(exports, module) {
16697
+ "use strict";
16698
+ var { sendServerError } = require_http_errors();
16699
+ var { createLogger } = require_logger();
16700
+ var RESULT_CODES = /* @__PURE__ */ new Set([
16701
+ "no_url",
16702
+ "no_secret",
16703
+ "invalid_url",
16704
+ "dns_failed",
16705
+ "address_not_allowed",
16706
+ "timeout",
16707
+ "network_error",
16708
+ "redirect_not_followed"
16709
+ ]);
16710
+ module.exports = ({ strapi: strapi2 }) => {
16711
+ const log = createLogger(strapi2);
16712
+ return {
16713
+ /**
16714
+ * Sends one signed `test` event to the stored URL, without retries.
16715
+ *
16716
+ * @route POST /magic-sessionmanager/webhook/test
16717
+ * @auth admin session or admin API token
16718
+ * @access plugin::magic-sessionmanager.access
16719
+ * @param {any} ctx Koa context.
16720
+ * @returns {Promise<void>} `{ data: { ok, status, code } }` (status of the receiver's answer;
16721
+ * code: no_url, no_secret, invalid_url, dns_failed, address_not_allowed, timeout,
16722
+ * network_error, redirect_not_followed or http_<status>).
16723
+ * @sideeffect One HTTPS request to the stored webhook URL.
16724
+ */
16725
+ async sendTest(ctx) {
16726
+ try {
16727
+ const result = await strapi2.plugin("magic-sessionmanager").service("webhooks").sendTest();
16728
+ const code = result.code === null || RESULT_CODES.has(result.code) || /^http_\d{3}$/.test(result.code) ? result.code : "network_error";
16729
+ ctx.body = { data: { ok: result.ok === true, status: result.status ?? null, code } };
16730
+ } catch (err) {
16731
+ log.error("[webhooks] Test send failed:", err?.name || "Error");
16732
+ return sendServerError(ctx, 500, "The test event could not be sent");
16733
+ }
16734
+ }
16735
+ };
16736
+ };
16737
+ }
16738
+ });
16739
+
15680
16740
  // server/src/controllers/index.js
15681
16741
  var require_controllers = __commonJS({
15682
16742
  "server/src/controllers/index.js"(exports, module) {
@@ -15687,13 +16747,17 @@ var require_controllers = __commonJS({
15687
16747
  var adminSessions = require_admin_sessions2();
15688
16748
  var adminActivity = require_admin_activity();
15689
16749
  var lockouts = require_lockouts();
16750
+ var selfService = require_self_service();
16751
+ var webhooks = require_webhooks();
15690
16752
  module.exports = {
15691
16753
  session,
15692
16754
  settings,
15693
16755
  geoip,
15694
16756
  "admin-sessions": adminSessions,
15695
16757
  "admin-activity": adminActivity,
15696
- lockouts
16758
+ lockouts,
16759
+ "self-service": selfService,
16760
+ webhooks
15697
16761
  };
15698
16762
  }
15699
16763
  });
@@ -15709,6 +16773,9 @@ var require_session2 = __commonJS({
15709
16773
  var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
15710
16774
  var { getPluginSettings } = require_settings_loader();
15711
16775
  var { hasRoleOverride, inactivityTimeoutFor } = require_policy_settings();
16776
+ var { resolveDetectionSettings } = require_detection_settings();
16777
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
16778
+ var { pointOf } = require_sign_in_signals();
15712
16779
  var {
15713
16780
  cleanupExpiredAccessTokenRevocations,
15714
16781
  persistAccessTokenRevocation
@@ -16040,6 +17107,7 @@ var require_session2 = __commonJS({
16040
17107
  * @param {string} [params.refreshToken] - Refresh token (will be encrypted)
16041
17108
  * @param {string} [params.nativeSessionId] - Native Users & Permissions session ID.
16042
17109
  * @param {object} [params.geoData]
17110
+ * @param {string} [params.deviceKey] Device key from utils/sign-in-signals.js.
16043
17111
  * @returns {Promise<object>} Created session
16044
17112
  * @throws {Error} When userId is missing
16045
17113
  */
@@ -16050,11 +17118,13 @@ var require_session2 = __commonJS({
16050
17118
  token,
16051
17119
  refreshToken,
16052
17120
  nativeSessionId,
16053
- geoData
17121
+ geoData,
17122
+ deviceKey
16054
17123
  }) {
16055
17124
  if (!userId) {
16056
17125
  throw new Error("createSession: userId is required");
16057
17126
  }
17127
+ const privacy = await getPluginSettings(strapi2).then(resolveDetectionSettings).catch(() => ({}));
16058
17128
  try {
16059
17129
  const now = /* @__PURE__ */ new Date();
16060
17130
  const sessionId = generateSessionId(userId);
@@ -16064,7 +17134,9 @@ var require_session2 = __commonJS({
16064
17134
  const tokenHashValue = token ? hashToken(token) : null;
16065
17135
  const refreshTokenHashValue = refreshToken ? hashToken(refreshToken) : null;
16066
17136
  const parsedUA = parseUserAgent(userAgent);
16067
- const safeIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
17137
+ const rawIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
17138
+ const safeIp = privacy.sessionIpAnonymize && normalizeIp(rawIp) ? anonymizeIp(normalizeIp(rawIp)) || rawIp : rawIp;
17139
+ const point = privacy.impossibleTravelEnabled ? pointOf(geoData) : null;
16068
17140
  const safeUa = (typeof userAgent === "string" ? userAgent : "unknown").substring(0, 500);
16069
17141
  const session = await strapi2.documents(SESSION_UID).create({
16070
17142
  data: {
@@ -16092,8 +17164,10 @@ var require_session2 = __commonJS({
16092
17164
  timezone: geoData.timezone,
16093
17165
  // Marks the stored score as real risk data; without a
16094
17166
  // risk source the score is null (not a fake 100).
16095
- ...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
17167
+ ...geoData.riskSource ? { riskSource: geoData.riskSource } : {},
17168
+ ...point ? { latitude: point.lat, longitude: point.lon } : {}
16096
17169
  } : null,
17170
+ ...typeof deviceKey === "string" && /^[a-f0-9]{32}$/.test(deviceKey) ? { deviceKey } : {},
16097
17171
  securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
16098
17172
  }
16099
17173
  });
@@ -17810,6 +18884,75 @@ Hello {{user.username}},
17810
18884
  There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
17811
18885
 
17812
18886
  If these attempts were not yours, change your password after the lock ends.`
18887
+ }),
18888
+ newDevice: Object.freeze({
18889
+ subject: "New sign-in to your account",
18890
+ html: `<html>
18891
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
18892
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
18893
+ <h2>New sign-in to your account</h2>
18894
+ <p>Hello {{user.username}},</p>
18895
+ <p>Your account was just used on a device we have not seen before.</p>
18896
+ <ul>
18897
+ <li>Time: {{session.loginTime}}</li>
18898
+ <li>Device: {{device.browser}} on {{device.os}}</li>
18899
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
18900
+ <li>IP address: {{session.ipAddress}}</li>
18901
+ </ul>
18902
+ <p>If this was you, you can ignore this email.</p>
18903
+ <p>If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
18904
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
18905
+ </div>
18906
+ </body>
18907
+ </html>`,
18908
+ text: `New sign-in to your account
18909
+
18910
+ Hello {{user.username}},
18911
+
18912
+ Your account was just used on a device we have not seen before.
18913
+
18914
+ Time: {{session.loginTime}}
18915
+ Device: {{device.browser}} on {{device.os}}
18916
+ Location: {{geo.city}}, {{geo.country}}
18917
+ IP address: {{session.ipAddress}}
18918
+
18919
+ If this was not you, sign this device out and change your password:
18920
+ {{link.notMe}}
18921
+
18922
+ The link works once and expires after 72 hours.`
18923
+ }),
18924
+ impossibleTravel: Object.freeze({
18925
+ subject: "Unusual sign-in to your account",
18926
+ html: `<html>
18927
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
18928
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
18929
+ <h2>Unusual sign-in to your account</h2>
18930
+ <p>Hello {{user.username}},</p>
18931
+ <p>Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.</p>
18932
+ <ul>
18933
+ <li>Time: {{session.loginTime}}</li>
18934
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
18935
+ <li>Device: {{device.browser}} on {{device.os}}</li>
18936
+ </ul>
18937
+ <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>
18938
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
18939
+ </div>
18940
+ </body>
18941
+ </html>`,
18942
+ text: `Unusual sign-in to your account
18943
+
18944
+ Hello {{user.username}},
18945
+
18946
+ Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.
18947
+
18948
+ Time: {{session.loginTime}}
18949
+ Location: {{geo.city}}, {{geo.country}}
18950
+ Device: {{device.browser}} on {{device.os}}
18951
+
18952
+ A VPN or a mobile network can cause this. If this was not you, sign this device out and change your password:
18953
+ {{link.notMe}}
18954
+
18955
+ The link works once and expires after 72 hours.`
17813
18956
  })
17814
18957
  });
17815
18958
  var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
@@ -17940,6 +19083,37 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
17940
19083
  }
17941
19084
  return { ...POLICY_TEMPLATES[key] };
17942
19085
  },
19086
+ /**
19087
+ * Emails a user about a sign-in from a new device or an impossible
19088
+ * travel, with the "This wasn't me" link.
19089
+ *
19090
+ * @param {'newDevice'|'impossibleTravel'} key Template.
19091
+ * @param {{user: object, session: object, geoData?: object|null, device: object,
19092
+ * travel?: object|null, link: string|null}} data Values.
19093
+ * @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
19094
+ * @sideeffect Sends one email.
19095
+ */
19096
+ async sendSignInSignalEmail(key, data) {
19097
+ try {
19098
+ if (!data?.user?.email) return false;
19099
+ const template = await this.getTemplate(key);
19100
+ const values = { ...data, geoData: data.geoData || {}, link: { notMe: data.link } };
19101
+ await strapi2.plugin("email").service("email").send({
19102
+ to: data.user.email,
19103
+ subject: this.replaceVariables(template.subject, values),
19104
+ html: this.replaceVariables(template.html, values),
19105
+ text: this.replaceVariables(template.text, values)
19106
+ });
19107
+ strapi2.log.info(`[magic-sessionmanager/notifications] ${key} email sent`);
19108
+ return true;
19109
+ } catch (err) {
19110
+ strapi2.log.error(
19111
+ `[magic-sessionmanager/notifications] ${key} email failed:`,
19112
+ err?.name || "Error"
19113
+ );
19114
+ return false;
19115
+ }
19116
+ },
17943
19117
  /**
17944
19118
  * Emails a user that their account was locked after failed sign-ins.
17945
19119
  * Sent through Strapi's email plugin, so a provider plugin such as Magic
@@ -18016,6 +19190,18 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
18016
19190
  /\{\{lock\.until\}\}/g,
18017
19191
  esc(Number.isFinite(data.lock?.until) ? new Date(data.lock.until).toUTCString() : "N/A")
18018
19192
  );
19193
+ result = result.replace(/\{\{device\.browser\}\}/g, esc(data.device?.browser || "Unknown"));
19194
+ result = result.replace(/\{\{device\.os\}\}/g, esc(data.device?.os || "Unknown"));
19195
+ result = result.replace(
19196
+ /\{\{travel\.distanceKm\}\}/g,
19197
+ esc(Number.isFinite(data.travel?.distanceKm) ? String(data.travel.distanceKm) : "N/A")
19198
+ );
19199
+ result = result.replace(
19200
+ /\{\{travel\.speedKmh\}\}/g,
19201
+ esc(Number.isFinite(data.travel?.speedKmh) ? String(data.travel.speedKmh) : "N/A")
19202
+ );
19203
+ const link = typeof data.link?.notMe === "string" && /^https?:\/\//.test(data.link.notMe) ? data.link.notMe : "";
19204
+ result = result.replace(/\{\{link\.notMe\}\}/g, esc(link));
18019
19205
  const score = data.reason?.securityScore;
18020
19206
  result = result.replace(
18021
19207
  /\{\{reason\.securityScore\}\}/g,
@@ -19309,6 +20495,478 @@ var require_security_log = __commonJS({
19309
20495
  }
19310
20496
  });
19311
20497
 
20498
+ // server/src/utils/webhook-delivery.js
20499
+ var require_webhook_delivery = __commonJS({
20500
+ "server/src/utils/webhook-delivery.js"(exports, module) {
20501
+ "use strict";
20502
+ var crypto = __require("node:crypto");
20503
+ var dns = __require("node:dns");
20504
+ var https = __require("node:https");
20505
+ var net = __require("node:net");
20506
+ var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
20507
+ var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
20508
+ var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
20509
+ var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
20510
+ var TIMEOUT_MS = 5e3;
20511
+ var MAX_RESPONSE_BYTES = 64 * 1024;
20512
+ var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
20513
+ var BLOCKED = (() => {
20514
+ const list = new net.BlockList();
20515
+ for (const [address, prefix] of [
20516
+ ["0.0.0.0", 8],
20517
+ ["10.0.0.0", 8],
20518
+ ["100.64.0.0", 10],
20519
+ ["127.0.0.0", 8],
20520
+ ["169.254.0.0", 16],
20521
+ ["172.16.0.0", 12],
20522
+ ["192.0.0.0", 24],
20523
+ ["192.0.2.0", 24],
20524
+ ["192.88.99.0", 24],
20525
+ ["192.168.0.0", 16],
20526
+ ["198.18.0.0", 15],
20527
+ ["198.51.100.0", 24],
20528
+ ["203.0.113.0", 24],
20529
+ ["224.0.0.0", 4],
20530
+ ["240.0.0.0", 4]
20531
+ ]) {
20532
+ list.addSubnet(address, prefix, "ipv4");
20533
+ }
20534
+ for (const [address, prefix] of [
20535
+ ["::", 128],
20536
+ ["::1", 128],
20537
+ // IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
20538
+ // checks them against the IPv4 rules above, and a listed /96 would
20539
+ // match every IPv4 address.
20540
+ ["64:ff9b::", 96],
20541
+ ["64:ff9b:1::", 48],
20542
+ ["100::", 64],
20543
+ ["2001::", 23],
20544
+ ["2001:db8::", 32],
20545
+ ["2002::", 16],
20546
+ ["fc00::", 7],
20547
+ ["fe80::", 10],
20548
+ ["fec0::", 10],
20549
+ ["ff00::", 8]
20550
+ ]) {
20551
+ list.addSubnet(address, prefix, "ipv6");
20552
+ }
20553
+ return list;
20554
+ })();
20555
+ function isBlockedAddress(address) {
20556
+ let value = String(address || "").trim();
20557
+ if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
20558
+ value = value.slice(7);
20559
+ }
20560
+ const version = net.isIP(value);
20561
+ if (version === 0) return true;
20562
+ return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
20563
+ }
20564
+ function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
20565
+ const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
20566
+ return `t=${timestamp},v1=${digest}`;
20567
+ }
20568
+ function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
20569
+ const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
20570
+ if (!match) return false;
20571
+ const timestamp = Number(match[1]);
20572
+ if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
20573
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
20574
+ const given = Buffer.from(match[2], "hex");
20575
+ return given.length === expected.length && crypto.timingSafeEqual(given, expected);
20576
+ }
20577
+ var DeliveryError = class extends Error {
20578
+ /**
20579
+ * @param {string} code Stable code.
20580
+ * @param {boolean} retryable Whether another attempt may succeed.
20581
+ * @param {number|null} [status] HTTP status, when there was one.
20582
+ */
20583
+ constructor(code, retryable, status = null) {
20584
+ super(code);
20585
+ this.name = "DeliveryError";
20586
+ this.code = code;
20587
+ this.retryable = retryable;
20588
+ this.status = status;
20589
+ }
20590
+ };
20591
+ var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
20592
+ function httpsPost({ url, address, headers, body, timeoutMs }) {
20593
+ return new Promise((resolve, reject) => {
20594
+ const request = https.request(
20595
+ {
20596
+ protocol: "https:",
20597
+ hostname: url.hostname,
20598
+ port: url.port || 443,
20599
+ path: `${url.pathname}${url.search}`,
20600
+ method: "POST",
20601
+ headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
20602
+ servername: net.isIP(url.hostname) ? void 0 : url.hostname,
20603
+ timeout: timeoutMs,
20604
+ // Pinned to the address that passed the check: no second lookup.
20605
+ lookup: (_hostname, options, callback) => {
20606
+ if (options && options.all) callback(null, [address]);
20607
+ else callback(null, address.address, address.family);
20608
+ }
20609
+ },
20610
+ (response) => {
20611
+ let received = 0;
20612
+ response.on("data", (chunk) => {
20613
+ received += chunk.length;
20614
+ if (received > MAX_RESPONSE_BYTES) response.destroy();
20615
+ });
20616
+ response.on("end", () => resolve(response.statusCode || 0));
20617
+ response.on("close", () => resolve(response.statusCode || 0));
20618
+ response.on("error", () => resolve(response.statusCode || 0));
20619
+ }
20620
+ );
20621
+ request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
20622
+ request.on(
20623
+ "error",
20624
+ (err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
20625
+ );
20626
+ request.end(body);
20627
+ });
20628
+ }
20629
+ async function deliverOnce({
20630
+ url,
20631
+ body,
20632
+ headers,
20633
+ resolve = resolveAll,
20634
+ post = httpsPost,
20635
+ timeoutMs = TIMEOUT_MS
20636
+ }) {
20637
+ let parsed;
20638
+ try {
20639
+ parsed = new URL(url);
20640
+ } catch {
20641
+ throw new DeliveryError("invalid_url", false);
20642
+ }
20643
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
20644
+ throw new DeliveryError("invalid_url", false);
20645
+ }
20646
+ const host = parsed.hostname.replace(/^\[|\]$/g, "");
20647
+ let addresses;
20648
+ if (net.isIP(host)) {
20649
+ addresses = [{ address: host, family: net.isIP(host) }];
20650
+ } else {
20651
+ try {
20652
+ addresses = await resolve(host);
20653
+ } catch {
20654
+ throw new DeliveryError("dns_failed", true);
20655
+ }
20656
+ }
20657
+ if (!Array.isArray(addresses) || addresses.length === 0)
20658
+ throw new DeliveryError("dns_failed", true);
20659
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
20660
+ throw new DeliveryError("address_not_allowed", false);
20661
+ }
20662
+ const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
20663
+ if (status >= 200 && status < 300) return { status };
20664
+ if (status >= 300 && status < 400)
20665
+ throw new DeliveryError("redirect_not_followed", false, status);
20666
+ throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
20667
+ }
20668
+ function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
20669
+ const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
20670
+ return {
20671
+ id,
20672
+ body,
20673
+ headers: {
20674
+ "Content-Type": "application/json",
20675
+ "User-Agent": USER_AGENT,
20676
+ [EVENT_HEADER]: event,
20677
+ [DELIVERY_HEADER]: id,
20678
+ [SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
20679
+ }
20680
+ };
20681
+ }
20682
+ async function deliverWithRetries({
20683
+ delays = RETRY_DELAYS_MS,
20684
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
20685
+ ...request
20686
+ }) {
20687
+ let attempts = 0;
20688
+ let last = { ok: false, status: null, code: "not_sent" };
20689
+ for (const delay of delays) {
20690
+ if (delay > 0) await sleep(delay);
20691
+ attempts += 1;
20692
+ try {
20693
+ const { status } = await deliverOnce(request);
20694
+ return { ok: true, status, code: null, attempts };
20695
+ } catch (err) {
20696
+ const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
20697
+ last = { ok: false, status: error.status, code: error.code };
20698
+ if (!error.retryable) break;
20699
+ }
20700
+ }
20701
+ return { ...last, attempts };
20702
+ }
20703
+ module.exports = {
20704
+ DELIVERY_HEADER,
20705
+ DeliveryError,
20706
+ EVENT_HEADER,
20707
+ RETRY_DELAYS_MS,
20708
+ SIGNATURE_HEADER,
20709
+ buildSignedRequest,
20710
+ deliverOnce,
20711
+ deliverWithRetries,
20712
+ isBlockedAddress,
20713
+ signPayload,
20714
+ verifySignature
20715
+ };
20716
+ }
20717
+ });
20718
+
20719
+ // server/src/services/webhooks.js
20720
+ var require_webhooks2 = __commonJS({
20721
+ "server/src/services/webhooks.js"(exports, module) {
20722
+ "use strict";
20723
+ var { decryptToken } = require_encryption();
20724
+ var { getPluginSettings } = require_settings_loader();
20725
+ var { resolveDetectionSettings } = require_detection_settings();
20726
+ var { resolveSecurityLogSettings } = require_security_log_settings();
20727
+ var { anonymizeIp, normalizeIp } = require_admin_request_info();
20728
+ var { SECURITY_EVENTS } = require_security_log_model();
20729
+ var {
20730
+ buildSignedRequest,
20731
+ deliverOnce,
20732
+ deliverWithRetries
20733
+ } = require_webhook_delivery();
20734
+ var { createLogger } = require_logger();
20735
+ var EVENT_OF_SECURITY_EVENT = Object.freeze({
20736
+ [SECURITY_EVENTS.USER_SIGN_IN_FAILED]: "login.failed",
20737
+ [SECURITY_EVENTS.USER_SIGN_IN_REFUSED]: "login.refused",
20738
+ [SECURITY_EVENTS.USER_LOCKOUT]: "lockout",
20739
+ [SECURITY_EVENTS.USER_LOCKOUT_LIFTED]: "lockout.lifted",
20740
+ [SECURITY_EVENTS.USER_SESSION_LIMIT]: "session.limit",
20741
+ [SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED]: "password.changed",
20742
+ "user.sign-in.new-device": "login.new_device",
20743
+ "user.sign-in.impossible-travel": "login.impossible_travel",
20744
+ "user.not-me": "user.not_me"
20745
+ });
20746
+ var CHAT_TITLES = Object.freeze({
20747
+ "login.failed": "Failed sign-in",
20748
+ "login.refused": "Refused sign-in",
20749
+ "login.new_device": "Sign-in from a new device",
20750
+ "login.impossible_travel": "Impossible travel",
20751
+ lockout: "Sign-in locked",
20752
+ "lockout.lifted": "Sign-in lock lifted",
20753
+ "session.limit": "Session limit reached",
20754
+ "password.changed": "Other sessions ended after a password change",
20755
+ "user.not_me": "User reported a sign-in as not theirs",
20756
+ test: "Test message"
20757
+ });
20758
+ var MAX_PARALLEL = 4;
20759
+ var MAX_QUEUE = 500;
20760
+ module.exports = ({ strapi: strapi2 }) => {
20761
+ const log = createLogger(strapi2);
20762
+ const queue = [];
20763
+ let running = 0;
20764
+ let stopped = false;
20765
+ const pump = () => {
20766
+ while (!stopped && running < MAX_PARALLEL && queue.length) {
20767
+ const job = (
20768
+ /** @type {() => Promise<void>} */
20769
+ queue.shift()
20770
+ );
20771
+ running += 1;
20772
+ job().catch(() => {
20773
+ }).finally(() => {
20774
+ running -= 1;
20775
+ pump();
20776
+ });
20777
+ }
20778
+ };
20779
+ const enqueue = (job) => {
20780
+ if (stopped) return;
20781
+ if (queue.length >= MAX_QUEUE) {
20782
+ queue.shift();
20783
+ log.warn("[webhooks] Queue full; the oldest delivery was dropped");
20784
+ }
20785
+ queue.push(job);
20786
+ pump();
20787
+ };
20788
+ const secretOf = (settings) => {
20789
+ const stored = settings?.genericWebhookSecret;
20790
+ if (typeof stored !== "string" || !stored) return null;
20791
+ try {
20792
+ return decryptToken(stored) || null;
20793
+ } catch {
20794
+ return null;
20795
+ }
20796
+ };
20797
+ const dataOf = (settings, input) => {
20798
+ const options = resolveSecurityLogSettings(settings);
20799
+ const ip = options.storeIp ? normalizeIp(input.ip || "") : null;
20800
+ return {
20801
+ user: input.userId ? { documentId: String(input.userId) } : null,
20802
+ ip: ip && options.anonymizeIp ? anonymizeIp(ip) : ip,
20803
+ userAgent: typeof input.userAgent === "string" ? input.userAgent.slice(0, 256) : null,
20804
+ location: input.geo && (input.geo.country_code || input.geo.city) ? { country: input.geo.country_code || null, city: input.geo.city || null } : null,
20805
+ details: input.details || null
20806
+ };
20807
+ };
20808
+ const chatBody = (kind, event, data) => {
20809
+ const title = CHAT_TITLES[event] || event;
20810
+ const fields = [
20811
+ ["User", data.user?.documentId || "-"],
20812
+ ["IP", data.ip || "-"],
20813
+ ...Object.entries(data.details || {}).slice(0, 6).map(([key, value]) => [key, String(value)])
20814
+ ];
20815
+ if (kind === "discord") {
20816
+ return {
20817
+ embeds: [
20818
+ {
20819
+ title,
20820
+ color: 5793266,
20821
+ fields: fields.map(([name, value]) => ({
20822
+ name,
20823
+ value: value.slice(0, 200),
20824
+ inline: true
20825
+ })),
20826
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
20827
+ footer: { text: "Magic Session Manager" }
20828
+ }
20829
+ ]
20830
+ };
20831
+ }
20832
+ return {
20833
+ text: title,
20834
+ attachments: [
20835
+ {
20836
+ color: "#2563eb",
20837
+ blocks: [
20838
+ { type: "header", text: { type: "plain_text", text: title } },
20839
+ {
20840
+ type: "section",
20841
+ fields: fields.map(([name, value]) => ({
20842
+ type: "mrkdwn",
20843
+ text: `*${name}*
20844
+ ${value.slice(0, 200)}`
20845
+ }))
20846
+ }
20847
+ ]
20848
+ }
20849
+ ]
20850
+ };
20851
+ };
20852
+ const service = {
20853
+ EVENT_OF_SECURITY_EVENT,
20854
+ /**
20855
+ * Whether an event is selected.
20856
+ *
20857
+ * @param {Record<string, any>} settings Merged settings.
20858
+ * @param {string} event Webhook event.
20859
+ * @returns {boolean} True when selected.
20860
+ */
20861
+ isSelected(settings, event) {
20862
+ return resolveDetectionSettings(settings).webhookEvents.includes(event);
20863
+ },
20864
+ /**
20865
+ * Queues an event for the signed webhook and, for non-sign-in events,
20866
+ * Discord and Slack. Sign-in events (`login.success`, `login.suspicious`,
20867
+ * `login.new_location`) reach Discord and Slack through the login alerts
20868
+ * with their richer message. Returns at once.
20869
+ *
20870
+ * @param {string} event Webhook event.
20871
+ * @param {{userId?: string|null, ip?: string|null, userAgent?: string|null, geo?: any,
20872
+ * details?: Record<string, unknown>|null}} input Event facts.
20873
+ * @param {{chat?: boolean}} [options] Whether Discord/Slack get it here.
20874
+ * @returns {void}
20875
+ */
20876
+ emit(event, input, { chat = true } = {}) {
20877
+ enqueue(async () => {
20878
+ const settings = await getPluginSettings(strapi2);
20879
+ if (!service.isSelected(settings, event)) return;
20880
+ const data = dataOf(settings, input);
20881
+ const detection = resolveDetectionSettings(settings);
20882
+ const secret = secretOf(settings);
20883
+ if (detection.genericWebhookEnabled && detection.genericWebhookUrl && secret) {
20884
+ const request = buildSignedRequest({ event, data, secret });
20885
+ const result = await deliverWithRetries({ url: detection.genericWebhookUrl, ...request });
20886
+ if (!result.ok) {
20887
+ log.warn(
20888
+ `[webhooks] Signed webhook delivery failed (${result.code}, ${result.attempts} attempts)`
20889
+ );
20890
+ }
20891
+ }
20892
+ if (chat && settings.enableWebhooks) {
20893
+ const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
20894
+ const targets = [
20895
+ ["discord", settings.discordWebhookUrl],
20896
+ ["slack", settings.slackWebhookUrl]
20897
+ ].filter(([, url]) => typeof url === "string" && url);
20898
+ await Promise.allSettled(
20899
+ targets.map(
20900
+ ([kind, url]) => notifications.sendWebhook({
20901
+ event,
20902
+ data: chatBody(kind, event, data),
20903
+ webhookUrl: url
20904
+ })
20905
+ )
20906
+ );
20907
+ }
20908
+ });
20909
+ },
20910
+ /**
20911
+ * Emits the webhook event that belongs to a security log event, if any.
20912
+ *
20913
+ * @param {{event: string, actorType?: string, actorId?: any, targetId?: any, ip?: any,
20914
+ * userAgent?: any, meta?: any}} input Security event input.
20915
+ * @returns {void}
20916
+ */
20917
+ emitSecurityEvent(input) {
20918
+ const event = EVENT_OF_SECURITY_EVENT[input?.event];
20919
+ if (!event) return;
20920
+ service.emit(event, {
20921
+ userId: input.targetId || (input.actorType === "user" ? input.actorId : null) || null,
20922
+ // An admin's own address is not sent for admin actions.
20923
+ ip: input.actorType === "admin" ? null : input.ip,
20924
+ userAgent: input.actorType === "admin" ? null : input.userAgent,
20925
+ details: input.meta || null
20926
+ });
20927
+ },
20928
+ /**
20929
+ * Sends one `test` event to the signed webhook now, without retries.
20930
+ *
20931
+ * @returns {Promise<{ok: boolean, status: number|null, code: string|null}>} Result.
20932
+ */
20933
+ async sendTest() {
20934
+ const settings = await getPluginSettings(strapi2);
20935
+ const detection = resolveDetectionSettings(settings);
20936
+ const secret = secretOf(settings);
20937
+ if (!detection.genericWebhookUrl) return { ok: false, status: null, code: "no_url" };
20938
+ if (!secret) return { ok: false, status: null, code: "no_secret" };
20939
+ const request = buildSignedRequest({
20940
+ event: "test",
20941
+ data: { user: null, ip: null, userAgent: null, location: null, details: { test: true } },
20942
+ secret
20943
+ });
20944
+ try {
20945
+ const { status } = await deliverOnce({ url: detection.genericWebhookUrl, ...request });
20946
+ return { ok: true, status, code: null };
20947
+ } catch (err) {
20948
+ return {
20949
+ ok: false,
20950
+ status: Number.isInteger(err?.status) ? err.status : null,
20951
+ code: typeof err?.code === "string" ? err.code : "network_error"
20952
+ };
20953
+ }
20954
+ },
20955
+ /**
20956
+ * Stops new deliveries (plugin destroy).
20957
+ *
20958
+ * @returns {void}
20959
+ */
20960
+ stop() {
20961
+ stopped = true;
20962
+ queue.length = 0;
20963
+ }
20964
+ };
20965
+ return service;
20966
+ };
20967
+ }
20968
+ });
20969
+
19312
20970
  // server/src/services/index.js
19313
20971
  var require_services = __commonJS({
19314
20972
  "server/src/services/index.js"(exports, module) {
@@ -19317,11 +20975,13 @@ var require_services = __commonJS({
19317
20975
  var geolocation = require_geolocation();
19318
20976
  var notifications = require_notifications();
19319
20977
  var securityLog = require_security_log();
20978
+ var webhooks = require_webhooks2();
19320
20979
  module.exports = {
19321
20980
  session,
19322
20981
  geolocation,
19323
20982
  notifications,
19324
- "security-log": securityLog
20983
+ "security-log": securityLog,
20984
+ webhooks
19325
20985
  };
19326
20986
  }
19327
20987
  });