strapi-plugin-magic-sessionmanager 4.17.0 → 4.19.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.
- package/CHANGELOG.md +59 -0
- package/README.md +115 -53
- package/dist/admin/{Analytics-BTIByTUY.js → Analytics-AzG-hPvn.js} +1 -1
- package/dist/admin/{Analytics-B-p2Q7th.mjs → Analytics-DSXe9BPn.mjs} +1 -1
- package/dist/admin/{App-DmesuM2g.mjs → App-7UDfLwMK.mjs} +1132 -163
- package/dist/admin/{App-CH6635JB.js → App-D08oGxy4.js} +1129 -160
- package/dist/admin/{OnlineUsersWidget-TlOp8nie.js → OnlineUsersWidget-CK0_o7Jk.js} +1 -1
- package/dist/admin/{OnlineUsersWidget-CuqeQ0tb.mjs → OnlineUsersWidget-DIhJZ77w.mjs} +1 -1
- package/dist/admin/{Settings-C4IgGBjQ.mjs → Settings-CneNJppG.mjs} +866 -38
- package/dist/admin/{Settings-DtP_H4JS.js → Settings-DnNBDP1I.js} +866 -38
- package/dist/admin/{dashboardModel-BSJhZdXI.js → dashboardModel-CjU0V7Sx.js} +1 -1
- package/dist/admin/{dashboardModel-0ROcWcB1.mjs → dashboardModel-OyQ_39aF.mjs} +1 -1
- package/dist/admin/{de-C_ooq6EF.js → de-CJZtJdhC.js} +151 -6
- package/dist/admin/{de-BoahnYIP.mjs → de-DvYUwhjB.mjs} +151 -6
- package/dist/admin/{en-DHme92L-.mjs → en-B8m9k-qd.mjs} +151 -6
- package/dist/admin/{en-CuUVE2K0.js → en-BZ2YkNIU.js} +151 -6
- package/dist/admin/{es-lbDNXcQi.js → es-BBsMtof1.js} +151 -6
- package/dist/admin/{es-CjcTgS9Z.mjs → es-DBH36rrX.mjs} +151 -6
- package/dist/admin/{fr-BPwnrSaC.mjs → fr-CLvB1rGe.mjs} +151 -6
- package/dist/admin/{fr-RtypjgGp.js → fr-Cw6nc38j.js} +151 -6
- package/dist/admin/{index-B102RF2H.mjs → index-5Zb3GVml.mjs} +9 -9
- package/dist/admin/{index-w0OuPYFm.js → index-BSUrdxxt.js} +9 -9
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/{pt-D5FHSP2y.mjs → pt-CVht14if.mjs} +151 -6
- package/dist/admin/{pt-BMCAKRQ4.js → pt-CjnMe7Z-.js} +151 -6
- package/dist/server/index.js +1725 -32
- package/dist/server/index.mjs +1725 -32
- package/package.json +1 -1
package/dist/server/index.js
CHANGED
|
@@ -252,6 +252,11 @@ var require_coordination = __commonJS({
|
|
|
252
252
|
async registryDelete(key) {
|
|
253
253
|
registry.delete(key);
|
|
254
254
|
},
|
|
255
|
+
async registryTake(key, now = Date.now()) {
|
|
256
|
+
const entry = registry.get(key);
|
|
257
|
+
registry.delete(key);
|
|
258
|
+
return entry && entry.expiresAt > now ? entry.value : null;
|
|
259
|
+
},
|
|
255
260
|
async prune(now = Date.now()) {
|
|
256
261
|
let removed = 0;
|
|
257
262
|
for (const [k, v] of registry) {
|
|
@@ -522,6 +527,21 @@ var require_coordination = __commonJS({
|
|
|
522
527
|
async registryDelete(key) {
|
|
523
528
|
await knex(TABLES.cache).where({ k: `reg:${key}` }).del();
|
|
524
529
|
},
|
|
530
|
+
/**
|
|
531
|
+
* Reads and deletes an entry. Only the caller whose DELETE removed the
|
|
532
|
+
* row gets the value, so parallel takes of one key yield it once.
|
|
533
|
+
*/
|
|
534
|
+
async registryTake(key, now = Date.now()) {
|
|
535
|
+
const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: `reg:${key}` }).first();
|
|
536
|
+
if (!row) return null;
|
|
537
|
+
const deleted = await knex(TABLES.cache).where({ k: `reg:${key}`, expires_at: row.expires_at }).del();
|
|
538
|
+
if (toNumber(deleted) !== 1 || toNumber(row.expires_at) <= now) return null;
|
|
539
|
+
try {
|
|
540
|
+
return JSON.parse(row.v);
|
|
541
|
+
} catch {
|
|
542
|
+
return null;
|
|
543
|
+
}
|
|
544
|
+
},
|
|
525
545
|
async prune(now = Date.now()) {
|
|
526
546
|
const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
|
|
527
547
|
const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
|
|
@@ -748,6 +768,21 @@ var require_coordination = __commonJS({
|
|
|
748
768
|
() => sharedMemory.registryList(prefix, limit)
|
|
749
769
|
);
|
|
750
770
|
},
|
|
771
|
+
/**
|
|
772
|
+
* Takes a listable entry once: returns its value and removes it. Of
|
|
773
|
+
* several concurrent takes (any process) at most one gets the value.
|
|
774
|
+
*
|
|
775
|
+
* @param {string} key Entry key.
|
|
776
|
+
* @returns {Promise<any|null>} Value, or null when absent, expired or taken.
|
|
777
|
+
*/
|
|
778
|
+
registryTake(key) {
|
|
779
|
+
assertRegistryKey(key);
|
|
780
|
+
return run(
|
|
781
|
+
"registry take",
|
|
782
|
+
(backend) => backend.registryTake(key),
|
|
783
|
+
() => sharedMemory.registryTake(key)
|
|
784
|
+
);
|
|
785
|
+
},
|
|
751
786
|
/** Removes a listable entry. */
|
|
752
787
|
registryDelete(key) {
|
|
753
788
|
assertRegistryKey(key);
|
|
@@ -910,7 +945,7 @@ var require_content_api_permissions = __commonJS({
|
|
|
910
945
|
"server/src/utils/content-api-permissions.js"(exports2, module2) {
|
|
911
946
|
"use strict";
|
|
912
947
|
var { withPluginStoreKey } = require_plugin_store();
|
|
913
|
-
var CONTENT_API_PERMISSIONS_VERSION =
|
|
948
|
+
var CONTENT_API_PERMISSIONS_VERSION = 3;
|
|
914
949
|
var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
|
|
915
950
|
var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
|
|
916
951
|
async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
|
|
@@ -1436,12 +1471,228 @@ var require_policy_settings = __commonJS({
|
|
|
1436
1471
|
}
|
|
1437
1472
|
});
|
|
1438
1473
|
|
|
1474
|
+
// server/src/utils/detection-settings.js
|
|
1475
|
+
var require_detection_settings = __commonJS({
|
|
1476
|
+
"server/src/utils/detection-settings.js"(exports2, module2) {
|
|
1477
|
+
"use strict";
|
|
1478
|
+
var WEBHOOK_EVENTS = Object.freeze([
|
|
1479
|
+
"login.success",
|
|
1480
|
+
"login.suspicious",
|
|
1481
|
+
"login.new_location",
|
|
1482
|
+
"login.new_device",
|
|
1483
|
+
"login.impossible_travel",
|
|
1484
|
+
"login.failed",
|
|
1485
|
+
"login.refused",
|
|
1486
|
+
"lockout",
|
|
1487
|
+
"lockout.lifted",
|
|
1488
|
+
"session.limit",
|
|
1489
|
+
"password.changed",
|
|
1490
|
+
"user.not_me"
|
|
1491
|
+
]);
|
|
1492
|
+
var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
|
|
1493
|
+
"login.suspicious",
|
|
1494
|
+
"login.new_location",
|
|
1495
|
+
"login.new_device",
|
|
1496
|
+
"login.impossible_travel",
|
|
1497
|
+
"lockout",
|
|
1498
|
+
"user.not_me"
|
|
1499
|
+
]);
|
|
1500
|
+
var LEGACY_WEBHOOK_EVENTS = Object.freeze([
|
|
1501
|
+
"login.success",
|
|
1502
|
+
"login.suspicious",
|
|
1503
|
+
"login.new_location"
|
|
1504
|
+
]);
|
|
1505
|
+
var IMPOSSIBLE_TRAVEL_ACTIONS = Object.freeze(["alert", "reauthenticate"]);
|
|
1506
|
+
var DETECTION_DEFAULTS = Object.freeze({
|
|
1507
|
+
alertOnNewDevice: false,
|
|
1508
|
+
alertOnImpossibleTravel: false,
|
|
1509
|
+
impossibleTravelEnabled: false,
|
|
1510
|
+
impossibleTravelSpeedKmh: 1e3,
|
|
1511
|
+
impossibleTravelMinDistanceKm: 500,
|
|
1512
|
+
impossibleTravelAction: "alert",
|
|
1513
|
+
webhookEvents: DEFAULT_WEBHOOK_EVENTS,
|
|
1514
|
+
genericWebhookEnabled: false,
|
|
1515
|
+
genericWebhookUrl: "",
|
|
1516
|
+
sessionIpAnonymize: false
|
|
1517
|
+
});
|
|
1518
|
+
var DETECTION_KEYS = Object.freeze(Object.keys(DETECTION_DEFAULTS));
|
|
1519
|
+
var PROTECTED_DETECTION_KEYS = Object.freeze([
|
|
1520
|
+
"impossibleTravelEnabled",
|
|
1521
|
+
"impossibleTravelSpeedKmh",
|
|
1522
|
+
"impossibleTravelMinDistanceKm",
|
|
1523
|
+
"impossibleTravelAction",
|
|
1524
|
+
"webhookEvents",
|
|
1525
|
+
"genericWebhookEnabled",
|
|
1526
|
+
"genericWebhookUrl",
|
|
1527
|
+
"genericWebhookSecret",
|
|
1528
|
+
"sessionIpAnonymize"
|
|
1529
|
+
]);
|
|
1530
|
+
var RANGES = Object.freeze({
|
|
1531
|
+
impossibleTravelSpeedKmh: Object.freeze([100, 5e3]),
|
|
1532
|
+
impossibleTravelMinDistanceKm: Object.freeze([50, 2e4])
|
|
1533
|
+
});
|
|
1534
|
+
var BOOLEAN_KEYS = Object.freeze([
|
|
1535
|
+
"alertOnNewDevice",
|
|
1536
|
+
"alertOnImpossibleTravel",
|
|
1537
|
+
"impossibleTravelEnabled",
|
|
1538
|
+
"genericWebhookEnabled",
|
|
1539
|
+
"sessionIpAnonymize"
|
|
1540
|
+
]);
|
|
1541
|
+
var MAX_URL_LENGTH = 2048;
|
|
1542
|
+
function parseInteger(value) {
|
|
1543
|
+
if (typeof value === "number") return Number.isInteger(value) ? value : null;
|
|
1544
|
+
if (typeof value === "string" && /^\s*\d{1,9}\s*$/.test(value)) return Number.parseInt(value, 10);
|
|
1545
|
+
return null;
|
|
1546
|
+
}
|
|
1547
|
+
function normalizeWebhookUrl(value) {
|
|
1548
|
+
if (typeof value !== "string") return null;
|
|
1549
|
+
const trimmed = value.trim();
|
|
1550
|
+
if (!trimmed || trimmed.length > MAX_URL_LENGTH) return null;
|
|
1551
|
+
let parsed;
|
|
1552
|
+
try {
|
|
1553
|
+
parsed = new URL(trimmed);
|
|
1554
|
+
} catch {
|
|
1555
|
+
return null;
|
|
1556
|
+
}
|
|
1557
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password) return null;
|
|
1558
|
+
const host = parsed.hostname.toLowerCase();
|
|
1559
|
+
if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
|
|
1560
|
+
return null;
|
|
1561
|
+
}
|
|
1562
|
+
return parsed.toString();
|
|
1563
|
+
}
|
|
1564
|
+
function normalizeEventList(value) {
|
|
1565
|
+
if (!Array.isArray(value)) return null;
|
|
1566
|
+
return [...new Set(value.filter((event) => WEBHOOK_EVENTS.includes(event)))];
|
|
1567
|
+
}
|
|
1568
|
+
function normalizeDetectionSettings(stored) {
|
|
1569
|
+
const out = {};
|
|
1570
|
+
if (!stored || typeof stored !== "object") return out;
|
|
1571
|
+
for (const key of BOOLEAN_KEYS) if (stored[key] !== void 0) out[key] = stored[key] === true;
|
|
1572
|
+
for (const [key, [min, max]] of Object.entries(RANGES)) {
|
|
1573
|
+
if (stored[key] === void 0) continue;
|
|
1574
|
+
const number = parseInteger(stored[key]);
|
|
1575
|
+
out[key] = number !== null && number >= min && number <= max ? number : (
|
|
1576
|
+
/** @type {any} */
|
|
1577
|
+
DETECTION_DEFAULTS[key]
|
|
1578
|
+
);
|
|
1579
|
+
}
|
|
1580
|
+
if (stored.impossibleTravelAction !== void 0) {
|
|
1581
|
+
out.impossibleTravelAction = IMPOSSIBLE_TRAVEL_ACTIONS.includes(
|
|
1582
|
+
/** @type {string} */
|
|
1583
|
+
stored.impossibleTravelAction
|
|
1584
|
+
) ? stored.impossibleTravelAction : "alert";
|
|
1585
|
+
}
|
|
1586
|
+
if (stored.webhookEvents !== void 0) {
|
|
1587
|
+
out.webhookEvents = normalizeEventList(stored.webhookEvents) || [...DEFAULT_WEBHOOK_EVENTS];
|
|
1588
|
+
}
|
|
1589
|
+
if (stored.genericWebhookUrl !== void 0) {
|
|
1590
|
+
out.genericWebhookUrl = normalizeWebhookUrl(stored.genericWebhookUrl) || "";
|
|
1591
|
+
}
|
|
1592
|
+
return out;
|
|
1593
|
+
}
|
|
1594
|
+
function validateDetectionSettings(body) {
|
|
1595
|
+
const values = {};
|
|
1596
|
+
const errors = [];
|
|
1597
|
+
const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
|
|
1598
|
+
for (const key of BOOLEAN_KEYS) {
|
|
1599
|
+
if (!has(key)) continue;
|
|
1600
|
+
if (typeof body[key] !== "boolean")
|
|
1601
|
+
errors.push({ path: [key], message: `${key} must be a boolean` });
|
|
1602
|
+
else values[key] = body[key];
|
|
1603
|
+
}
|
|
1604
|
+
for (const [key, [min, max]] of Object.entries(RANGES)) {
|
|
1605
|
+
if (!has(key)) continue;
|
|
1606
|
+
const number = parseInteger(body[key]);
|
|
1607
|
+
if (number === null || number < min || number > max) {
|
|
1608
|
+
errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
|
|
1609
|
+
} else {
|
|
1610
|
+
values[key] = number;
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
if (has("impossibleTravelAction")) {
|
|
1614
|
+
if (!IMPOSSIBLE_TRAVEL_ACTIONS.includes(
|
|
1615
|
+
/** @type {string} */
|
|
1616
|
+
body.impossibleTravelAction
|
|
1617
|
+
)) {
|
|
1618
|
+
errors.push({
|
|
1619
|
+
path: ["impossibleTravelAction"],
|
|
1620
|
+
message: `impossibleTravelAction must be one of: ${IMPOSSIBLE_TRAVEL_ACTIONS.join(", ")}`
|
|
1621
|
+
});
|
|
1622
|
+
} else {
|
|
1623
|
+
values.impossibleTravelAction = body.impossibleTravelAction;
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
if (has("webhookEvents")) {
|
|
1627
|
+
const list = body.webhookEvents;
|
|
1628
|
+
if (!Array.isArray(list) || list.length > WEBHOOK_EVENTS.length || list.some((event) => !WEBHOOK_EVENTS.includes(event))) {
|
|
1629
|
+
errors.push({
|
|
1630
|
+
path: ["webhookEvents"],
|
|
1631
|
+
message: `webhookEvents must be a list of: ${WEBHOOK_EVENTS.join(", ")}`
|
|
1632
|
+
});
|
|
1633
|
+
} else {
|
|
1634
|
+
values.webhookEvents = [...new Set(list)];
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
if (has("genericWebhookUrl")) {
|
|
1638
|
+
const raw = body.genericWebhookUrl;
|
|
1639
|
+
if (typeof raw !== "string") {
|
|
1640
|
+
errors.push({ path: ["genericWebhookUrl"], message: "genericWebhookUrl must be a string" });
|
|
1641
|
+
} else if (!raw.trim()) {
|
|
1642
|
+
values.genericWebhookUrl = "";
|
|
1643
|
+
} else {
|
|
1644
|
+
const url = normalizeWebhookUrl(raw);
|
|
1645
|
+
if (!url) {
|
|
1646
|
+
errors.push({
|
|
1647
|
+
path: ["genericWebhookUrl"],
|
|
1648
|
+
message: "genericWebhookUrl must be an https URL without credentials on a public host name"
|
|
1649
|
+
});
|
|
1650
|
+
} else {
|
|
1651
|
+
values.genericWebhookUrl = url;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
return { values, errors };
|
|
1656
|
+
}
|
|
1657
|
+
function resolveDetectionSettings(settings) {
|
|
1658
|
+
const source = settings && typeof settings === "object" ? settings : {};
|
|
1659
|
+
const clean = normalizeDetectionSettings(
|
|
1660
|
+
Object.fromEntries(
|
|
1661
|
+
DETECTION_KEYS.map((key) => [key, source[key]]).filter(([, v]) => v !== void 0)
|
|
1662
|
+
)
|
|
1663
|
+
);
|
|
1664
|
+
return (
|
|
1665
|
+
/** @type {any} */
|
|
1666
|
+
{
|
|
1667
|
+
...DETECTION_DEFAULTS,
|
|
1668
|
+
webhookEvents: [...DEFAULT_WEBHOOK_EVENTS],
|
|
1669
|
+
...clean
|
|
1670
|
+
}
|
|
1671
|
+
);
|
|
1672
|
+
}
|
|
1673
|
+
module2.exports = {
|
|
1674
|
+
DEFAULT_WEBHOOK_EVENTS,
|
|
1675
|
+
DETECTION_DEFAULTS,
|
|
1676
|
+
DETECTION_KEYS,
|
|
1677
|
+
PROTECTED_DETECTION_KEYS,
|
|
1678
|
+
IMPOSSIBLE_TRAVEL_ACTIONS,
|
|
1679
|
+
LEGACY_WEBHOOK_EVENTS,
|
|
1680
|
+
WEBHOOK_EVENTS,
|
|
1681
|
+
normalizeDetectionSettings,
|
|
1682
|
+
normalizeWebhookUrl,
|
|
1683
|
+
resolveDetectionSettings,
|
|
1684
|
+
validateDetectionSettings
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
});
|
|
1688
|
+
|
|
1439
1689
|
// server/src/utils/settings-loader.js
|
|
1440
1690
|
var require_settings_loader = __commonJS({
|
|
1441
1691
|
"server/src/utils/settings-loader.js"(exports2, module2) {
|
|
1442
1692
|
"use strict";
|
|
1443
1693
|
var { getCoordinator } = require_coordination();
|
|
1444
1694
|
var { normalizePolicySettings } = require_policy_settings();
|
|
1695
|
+
var { normalizeDetectionSettings } = require_detection_settings();
|
|
1445
1696
|
var PLUGIN_ID = "magic-sessionmanager";
|
|
1446
1697
|
var SETTINGS_KEY = "settings";
|
|
1447
1698
|
var CACHE_TTL_MS = 30 * 1e3;
|
|
@@ -1574,6 +1825,10 @@ var require_settings_loader = __commonJS({
|
|
|
1574
1825
|
out.trustedProxies = stored.trustedProxies;
|
|
1575
1826
|
}
|
|
1576
1827
|
Object.assign(out, normalizePolicySettings(stored));
|
|
1828
|
+
Object.assign(out, normalizeDetectionSettings(stored));
|
|
1829
|
+
if (typeof stored.genericWebhookSecret === "string") {
|
|
1830
|
+
out.genericWebhookSecret = stored.genericWebhookSecret;
|
|
1831
|
+
}
|
|
1577
1832
|
return out;
|
|
1578
1833
|
}
|
|
1579
1834
|
async function getPluginSettings(strapi2) {
|
|
@@ -1691,7 +1946,11 @@ var require_security_log_model = __commonJS({
|
|
|
1691
1946
|
USER_LOCKOUT: "user.lockout",
|
|
1692
1947
|
USER_LOCKOUT_LIFTED: "user.lockout.lifted",
|
|
1693
1948
|
USER_SESSION_LIMIT: "user.session.limit",
|
|
1694
|
-
USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others"
|
|
1949
|
+
USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others",
|
|
1950
|
+
USER_NEW_DEVICE: "user.sign-in.new-device",
|
|
1951
|
+
USER_IMPOSSIBLE_TRAVEL: "user.sign-in.impossible-travel",
|
|
1952
|
+
USER_NOT_ME: "user.not-me",
|
|
1953
|
+
USER_DATA_EXPORTED: "user.data.exported"
|
|
1695
1954
|
});
|
|
1696
1955
|
var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
|
|
1697
1956
|
SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
|
|
@@ -1730,11 +1989,17 @@ var require_security_log_model = __commonJS({
|
|
|
1730
1989
|
SECURITY_EVENTS.ADMIN_SIGN_OUT,
|
|
1731
1990
|
SECURITY_EVENTS.ADMIN_SESSION_REVOKED
|
|
1732
1991
|
]);
|
|
1992
|
+
var ADMIN_LOG_EVENTS = Object.freeze([
|
|
1993
|
+
SECURITY_EVENTS.SETTINGS_UPDATED,
|
|
1994
|
+
SECURITY_EVENTS.LOG_READ,
|
|
1995
|
+
SECURITY_EVENTS.LOG_RETENTION_PURGED
|
|
1996
|
+
]);
|
|
1733
1997
|
var SIGN_IN_FILTERS = Object.freeze({
|
|
1734
|
-
all: ADMIN_SIGN_IN_EVENTS,
|
|
1998
|
+
all: [...ADMIN_SIGN_IN_EVENTS, ...ADMIN_LOG_EVENTS],
|
|
1735
1999
|
succeeded: [SECURITY_EVENTS.ADMIN_SIGN_IN],
|
|
1736
2000
|
failed: [SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED, SECURITY_EVENTS.ADMIN_LOCKOUT],
|
|
1737
|
-
"signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED]
|
|
2001
|
+
"signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED],
|
|
2002
|
+
changes: ADMIN_LOG_EVENTS
|
|
1738
2003
|
});
|
|
1739
2004
|
var CONTENT_ACTIONS = Object.freeze([
|
|
1740
2005
|
"view",
|
|
@@ -1936,6 +2201,7 @@ var require_security_log_model = __commonJS({
|
|
|
1936
2201
|
USER_SIGN_IN_EVENTS,
|
|
1937
2202
|
ACTOR_TYPES,
|
|
1938
2203
|
ADMIN_CONTENT_EVENTS,
|
|
2204
|
+
ADMIN_LOG_EVENTS,
|
|
1939
2205
|
ADMIN_SIGN_IN_EVENTS,
|
|
1940
2206
|
CONTENT_ACTIONS,
|
|
1941
2207
|
CONTENT_MANAGER_HANDLERS,
|
|
@@ -2441,7 +2707,13 @@ var require_encryption = __commonJS({
|
|
|
2441
2707
|
function getEncryptionKeyCheck() {
|
|
2442
2708
|
return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
|
|
2443
2709
|
}
|
|
2710
|
+
function derivePurposeKey(purpose) {
|
|
2711
|
+
return Buffer.from(
|
|
2712
|
+
crypto.hkdfSync("sha256", getEncryptionKey(), "magic-sessionmanager", `msm:${purpose}`, 32)
|
|
2713
|
+
);
|
|
2714
|
+
}
|
|
2444
2715
|
module2.exports = {
|
|
2716
|
+
derivePurposeKey,
|
|
2445
2717
|
getEncryptionKeyCheck,
|
|
2446
2718
|
encryptToken,
|
|
2447
2719
|
decryptToken,
|
|
@@ -2703,13 +2975,15 @@ var require_login_alerts = __commonJS({
|
|
|
2703
2975
|
"server/src/utils/login-alerts.js"(exports2, module2) {
|
|
2704
2976
|
"use strict";
|
|
2705
2977
|
var { evaluateLoginRisk } = require_risk_data();
|
|
2978
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
2706
2979
|
async function dispatchLoginAlerts({
|
|
2707
2980
|
settings,
|
|
2708
2981
|
notificationService,
|
|
2709
2982
|
user,
|
|
2710
2983
|
session,
|
|
2711
2984
|
geoData,
|
|
2712
|
-
isNewLocation = false
|
|
2985
|
+
isNewLocation = false,
|
|
2986
|
+
webhooks = null
|
|
2713
2987
|
}) {
|
|
2714
2988
|
const attempted = { webhookEvent: null, emails: [] };
|
|
2715
2989
|
if (!geoData) return attempted;
|
|
@@ -2743,8 +3017,22 @@ var require_login_alerts = __commonJS({
|
|
|
2743
3017
|
await notificationService.sendNewLocationAlert({ user, session, geoData });
|
|
2744
3018
|
}
|
|
2745
3019
|
}
|
|
2746
|
-
|
|
2747
|
-
|
|
3020
|
+
const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
|
|
3021
|
+
const selected = resolveDetectionSettings(settings).webhookEvents.includes(webhookEvent);
|
|
3022
|
+
if (selected && webhooks) {
|
|
3023
|
+
webhooks.emit(
|
|
3024
|
+
webhookEvent,
|
|
3025
|
+
{
|
|
3026
|
+
userId: user?.documentId || null,
|
|
3027
|
+
ip: session?.ipAddress || null,
|
|
3028
|
+
userAgent: session?.userAgent || null,
|
|
3029
|
+
geo: geoData,
|
|
3030
|
+
details: null
|
|
3031
|
+
},
|
|
3032
|
+
{ chat: false }
|
|
3033
|
+
);
|
|
3034
|
+
}
|
|
3035
|
+
if (settings.enableWebhooks && selected) {
|
|
2748
3036
|
attempted.webhookEvent = webhookEvent;
|
|
2749
3037
|
const targets = [];
|
|
2750
3038
|
if (settings.discordWebhookUrl) {
|
|
@@ -4259,6 +4547,10 @@ var require_sign_in_policies = __commonJS({
|
|
|
4259
4547
|
return options.anonymizeIp ? anonymizeIp(normalized) : normalized;
|
|
4260
4548
|
}
|
|
4261
4549
|
function recordUserEvent(strapi2, input) {
|
|
4550
|
+
try {
|
|
4551
|
+
strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(input);
|
|
4552
|
+
} catch {
|
|
4553
|
+
}
|
|
4262
4554
|
try {
|
|
4263
4555
|
return strapi2.plugin("magic-sessionmanager").service("security-log").record(input) === true;
|
|
4264
4556
|
} catch {
|
|
@@ -4378,6 +4670,7 @@ var require_upgrade_defaults = __commonJS({
|
|
|
4378
4670
|
"use strict";
|
|
4379
4671
|
var { withPluginStoreKey } = require_plugin_store();
|
|
4380
4672
|
var { notifySettingsChanged } = require_settings_loader();
|
|
4673
|
+
var { LEGACY_WEBHOOK_EVENTS } = require_detection_settings();
|
|
4381
4674
|
var PROFILE_KEY = "defaultsProfile";
|
|
4382
4675
|
var UPGRADE_STEPS = Object.freeze([
|
|
4383
4676
|
Object.freeze({
|
|
@@ -4385,6 +4678,13 @@ var require_upgrade_defaults = __commonJS({
|
|
|
4385
4678
|
release: "4.17.0",
|
|
4386
4679
|
// Before 4.17 a password change kept the user's other sessions.
|
|
4387
4680
|
legacy: Object.freeze({ endOtherSessionsOnPasswordChange: false })
|
|
4681
|
+
}),
|
|
4682
|
+
Object.freeze({
|
|
4683
|
+
version: 2,
|
|
4684
|
+
release: "sign-in signals and signed webhook",
|
|
4685
|
+
// Before, Discord and Slack received every sign-in (success, new
|
|
4686
|
+
// country, suspicious). New installations leave out every sign-in.
|
|
4687
|
+
legacy: Object.freeze({ webhookEvents: LEGACY_WEBHOOK_EVENTS })
|
|
4388
4688
|
})
|
|
4389
4689
|
]);
|
|
4390
4690
|
async function applyUpgradeDefaults(strapi2, log, steps = UPGRADE_STEPS) {
|
|
@@ -4406,7 +4706,7 @@ var require_upgrade_defaults = __commonJS({
|
|
|
4406
4706
|
if (step.version <= profile) continue;
|
|
4407
4707
|
for (const [key, value] of Object.entries(step.legacy)) {
|
|
4408
4708
|
if (settings[key] !== void 0) continue;
|
|
4409
|
-
settings[key] = value;
|
|
4709
|
+
settings[key] = Array.isArray(value) ? [...value] : value;
|
|
4410
4710
|
applied.push(key);
|
|
4411
4711
|
}
|
|
4412
4712
|
}
|
|
@@ -4427,6 +4727,270 @@ var require_upgrade_defaults = __commonJS({
|
|
|
4427
4727
|
}
|
|
4428
4728
|
});
|
|
4429
4729
|
|
|
4730
|
+
// server/src/utils/not-me-link.js
|
|
4731
|
+
var require_not_me_link = __commonJS({
|
|
4732
|
+
"server/src/utils/not-me-link.js"(exports2, module2) {
|
|
4733
|
+
"use strict";
|
|
4734
|
+
var crypto = require("node:crypto");
|
|
4735
|
+
var { derivePurposeKey } = require_encryption();
|
|
4736
|
+
var LIFETIME_MS = 72 * 60 * 60 * 1e3;
|
|
4737
|
+
var NONCE_PREFIX = "notme:";
|
|
4738
|
+
var DOCUMENT_ID = /^[A-Za-z0-9]{1,64}$/;
|
|
4739
|
+
var TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,400}\.[A-Za-z0-9_-]{43}$/;
|
|
4740
|
+
var signingKey = () => derivePurposeKey("not-me-link");
|
|
4741
|
+
var sign = (payload) => crypto.createHmac("sha256", signingKey()).update(payload).digest("base64url");
|
|
4742
|
+
async function issueNotMeToken(coordinator, { sessionId, userId, now = Date.now() }) {
|
|
4743
|
+
if (!DOCUMENT_ID.test(String(sessionId)) || !DOCUMENT_ID.test(String(userId))) return null;
|
|
4744
|
+
const nonce = crypto.randomBytes(18).toString("hex");
|
|
4745
|
+
const payload = Buffer.from(
|
|
4746
|
+
JSON.stringify({ s: sessionId, u: userId, e: now + LIFETIME_MS, n: nonce })
|
|
4747
|
+
).toString("base64url");
|
|
4748
|
+
await coordinator.registryPut(
|
|
4749
|
+
`${NONCE_PREFIX}${nonce}`,
|
|
4750
|
+
{ s: sessionId, u: userId },
|
|
4751
|
+
LIFETIME_MS
|
|
4752
|
+
);
|
|
4753
|
+
return `${payload}.${sign(payload)}`;
|
|
4754
|
+
}
|
|
4755
|
+
function readNotMeToken(token, { now = Date.now() } = {}) {
|
|
4756
|
+
if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) return null;
|
|
4757
|
+
const [payload, signature] = token.split(".");
|
|
4758
|
+
const expected = Buffer.from(sign(payload));
|
|
4759
|
+
const given = Buffer.from(signature);
|
|
4760
|
+
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null;
|
|
4761
|
+
let claims;
|
|
4762
|
+
try {
|
|
4763
|
+
claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
4764
|
+
} catch {
|
|
4765
|
+
return null;
|
|
4766
|
+
}
|
|
4767
|
+
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) {
|
|
4768
|
+
return null;
|
|
4769
|
+
}
|
|
4770
|
+
return { sessionId: claims.s, userId: claims.u, nonce: claims.n, expiresAt: claims.e };
|
|
4771
|
+
}
|
|
4772
|
+
async function consumeNotMeToken(coordinator, token) {
|
|
4773
|
+
const claims = readNotMeToken(token);
|
|
4774
|
+
if (!claims) return null;
|
|
4775
|
+
const stored = await coordinator.registryTake(`${NONCE_PREFIX}${claims.nonce}`);
|
|
4776
|
+
if (!stored || stored.s !== claims.sessionId || stored.u !== claims.userId) return null;
|
|
4777
|
+
return { sessionId: claims.sessionId, userId: claims.userId };
|
|
4778
|
+
}
|
|
4779
|
+
module2.exports = { LIFETIME_MS, consumeNotMeToken, issueNotMeToken, readNotMeToken };
|
|
4780
|
+
}
|
|
4781
|
+
});
|
|
4782
|
+
|
|
4783
|
+
// server/src/utils/sign-in-signals.js
|
|
4784
|
+
var require_sign_in_signals = __commonJS({
|
|
4785
|
+
"server/src/utils/sign-in-signals.js"(exports2, module2) {
|
|
4786
|
+
"use strict";
|
|
4787
|
+
var crypto = require("node:crypto");
|
|
4788
|
+
var { derivePurposeKey } = require_encryption();
|
|
4789
|
+
var { parseUserAgent } = require_user_agent_parser();
|
|
4790
|
+
var { getCoordinator } = require_coordination();
|
|
4791
|
+
var { normalizeApiPrefix } = require_auth_routes();
|
|
4792
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
4793
|
+
var { issueNotMeToken } = require_not_me_link();
|
|
4794
|
+
var { SECURITY_EVENTS } = require_security_log_model();
|
|
4795
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
4796
|
+
var HISTORY = 50;
|
|
4797
|
+
var EARTH_RADIUS_KM = 6371.0088;
|
|
4798
|
+
function deviceFamilies(userAgent) {
|
|
4799
|
+
const parsed = parseUserAgent(typeof userAgent === "string" ? userAgent.slice(0, 500) : "");
|
|
4800
|
+
return {
|
|
4801
|
+
browser: String(parsed.browserName || "unknown"),
|
|
4802
|
+
os: String(parsed.osName || "unknown"),
|
|
4803
|
+
deviceType: String(parsed.deviceType || "unknown")
|
|
4804
|
+
};
|
|
4805
|
+
}
|
|
4806
|
+
function family(value) {
|
|
4807
|
+
return String(value || "unknown").replace(/\s+[\d.]+$/, "").trim();
|
|
4808
|
+
}
|
|
4809
|
+
function deviceKeyOf(userAgent, deviceId) {
|
|
4810
|
+
const { browser, os, deviceType } = deviceFamilies(userAgent);
|
|
4811
|
+
const id = typeof deviceId === "string" && deviceId.length <= 128 ? deviceId : "";
|
|
4812
|
+
return crypto.createHmac("sha256", derivePurposeKey("device")).update(`${browser}|${os}|${deviceType}|${id}`).digest("hex").slice(0, 32);
|
|
4813
|
+
}
|
|
4814
|
+
function requestDeviceId(ctx) {
|
|
4815
|
+
const value = ctx?.request?.body?.deviceId;
|
|
4816
|
+
return typeof value === "string" && value && value.length <= 128 ? value : null;
|
|
4817
|
+
}
|
|
4818
|
+
function distanceKm(a, b) {
|
|
4819
|
+
const rad = (deg) => deg * Math.PI / 180;
|
|
4820
|
+
const dLat = rad(b.lat - a.lat);
|
|
4821
|
+
const dLon = rad(b.lon - a.lon);
|
|
4822
|
+
const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
|
|
4823
|
+
return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)));
|
|
4824
|
+
}
|
|
4825
|
+
function pointOf(geo) {
|
|
4826
|
+
const lat = Number(geo?.latitude);
|
|
4827
|
+
const lon = Number(geo?.longitude);
|
|
4828
|
+
if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
|
|
4829
|
+
return null;
|
|
4830
|
+
}
|
|
4831
|
+
if (geo?.latitude === null || geo?.longitude === null) return null;
|
|
4832
|
+
return { lat: Math.round(lat * 10) / 10, lon: Math.round(lon * 10) / 10 };
|
|
4833
|
+
}
|
|
4834
|
+
function evaluateTravel(previous, current, { speedKmh, minDistanceKm }) {
|
|
4835
|
+
if (!previous?.point || !current?.point) return null;
|
|
4836
|
+
const km = distanceKm(previous.point, current.point);
|
|
4837
|
+
const hours = Math.max(current.at - previous.at, 60 * 1e3) / (60 * 60 * 1e3);
|
|
4838
|
+
const speed = km / hours;
|
|
4839
|
+
return {
|
|
4840
|
+
flagged: km >= minDistanceKm && speed > speedKmh,
|
|
4841
|
+
distanceKm: Math.round(km),
|
|
4842
|
+
speedKmh: Math.round(speed)
|
|
4843
|
+
};
|
|
4844
|
+
}
|
|
4845
|
+
async function previousSessions(strapi2, userDocumentId, exceptSessionId) {
|
|
4846
|
+
const rows = await strapi2.documents(SESSION_UID).findMany({
|
|
4847
|
+
filters: { user: { documentId: userDocumentId }, documentId: { $ne: exceptSessionId } },
|
|
4848
|
+
fields: [
|
|
4849
|
+
"documentId",
|
|
4850
|
+
"loginTime",
|
|
4851
|
+
"deviceKey",
|
|
4852
|
+
"browserName",
|
|
4853
|
+
"osName",
|
|
4854
|
+
"deviceType",
|
|
4855
|
+
"geoLocation"
|
|
4856
|
+
],
|
|
4857
|
+
sort: [{ loginTime: "desc" }, { id: "desc" }],
|
|
4858
|
+
limit: HISTORY
|
|
4859
|
+
});
|
|
4860
|
+
return Array.isArray(rows) ? rows : [];
|
|
4861
|
+
}
|
|
4862
|
+
function isNewDevice(previous, { deviceKey, userAgent }) {
|
|
4863
|
+
if (previous.length === 0) return false;
|
|
4864
|
+
if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
|
|
4865
|
+
const families = deviceFamilies(userAgent);
|
|
4866
|
+
return !previous.some(
|
|
4867
|
+
(row) => !row.deviceKey && family(row.browserName) === families.browser && family(row.osName) === families.os
|
|
4868
|
+
);
|
|
4869
|
+
}
|
|
4870
|
+
function storedLocation(row) {
|
|
4871
|
+
let geo = row?.geoLocation;
|
|
4872
|
+
if (typeof geo === "string") {
|
|
4873
|
+
try {
|
|
4874
|
+
geo = JSON.parse(geo);
|
|
4875
|
+
} catch {
|
|
4876
|
+
geo = null;
|
|
4877
|
+
}
|
|
4878
|
+
}
|
|
4879
|
+
return {
|
|
4880
|
+
point: pointOf(geo),
|
|
4881
|
+
country: typeof geo?.country_code === "string" ? geo.country_code : null
|
|
4882
|
+
};
|
|
4883
|
+
}
|
|
4884
|
+
async function notMeUrl(strapi2, sessionId, userId) {
|
|
4885
|
+
const base = String(strapi2.config.get("server.absoluteUrl") || "").replace(/\/+$/, "");
|
|
4886
|
+
if (!/^https?:\/\/[^/]+/.test(base)) return null;
|
|
4887
|
+
const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
|
|
4888
|
+
if (!token) return null;
|
|
4889
|
+
const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
|
|
4890
|
+
return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
|
|
4891
|
+
}
|
|
4892
|
+
async function runSignInSignals({
|
|
4893
|
+
strapi: strapi2,
|
|
4894
|
+
settings,
|
|
4895
|
+
user,
|
|
4896
|
+
userDocumentId,
|
|
4897
|
+
session,
|
|
4898
|
+
geoData,
|
|
4899
|
+
deviceKey,
|
|
4900
|
+
userAgent,
|
|
4901
|
+
ip,
|
|
4902
|
+
record,
|
|
4903
|
+
now = Date.now()
|
|
4904
|
+
}) {
|
|
4905
|
+
const outcome = { newDevice: false, travel: null, reauthenticate: false };
|
|
4906
|
+
const detection = resolveDetectionSettings(settings);
|
|
4907
|
+
const plugin = strapi2.plugin("magic-sessionmanager");
|
|
4908
|
+
const emails = settings.enableEmailAlerts === true;
|
|
4909
|
+
const hasWebhookTarget = detection.genericWebhookEnabled && !!detection.genericWebhookUrl || settings.enableWebhooks === true && !!(settings.discordWebhookUrl || settings.slackWebhookUrl);
|
|
4910
|
+
const wantNewDevice = emails && detection.alertOnNewDevice || hasWebhookTarget && detection.webhookEvents.includes("login.new_device");
|
|
4911
|
+
const wantTravel = detection.impossibleTravelEnabled;
|
|
4912
|
+
if (!wantNewDevice && !wantTravel || !session?.documentId) return outcome;
|
|
4913
|
+
const previous = await previousSessions(strapi2, userDocumentId, session.documentId);
|
|
4914
|
+
const families = deviceFamilies(userAgent);
|
|
4915
|
+
let link;
|
|
4916
|
+
const linkOnce = async () => {
|
|
4917
|
+
if (link === void 0) link = await notMeUrl(strapi2, session.documentId, userDocumentId);
|
|
4918
|
+
return link;
|
|
4919
|
+
};
|
|
4920
|
+
const notifications = plugin.service("notifications");
|
|
4921
|
+
const facts = { user, session, geoData, device: { browser: families.browser, os: families.os } };
|
|
4922
|
+
if (wantNewDevice && isNewDevice(previous, { deviceKey, userAgent })) {
|
|
4923
|
+
outcome.newDevice = true;
|
|
4924
|
+
record({
|
|
4925
|
+
event: SECURITY_EVENTS.USER_NEW_DEVICE,
|
|
4926
|
+
actorType: "user",
|
|
4927
|
+
actorId: userDocumentId,
|
|
4928
|
+
targetType: "user",
|
|
4929
|
+
targetId: userDocumentId,
|
|
4930
|
+
ip,
|
|
4931
|
+
userAgent,
|
|
4932
|
+
meta: { browser: families.browser, os: families.os, deviceType: families.deviceType }
|
|
4933
|
+
});
|
|
4934
|
+
if (emails && detection.alertOnNewDevice) {
|
|
4935
|
+
const url = await linkOnce();
|
|
4936
|
+
notifications.sendSignInSignalEmail("newDevice", { ...facts, link: url }).catch(() => {
|
|
4937
|
+
});
|
|
4938
|
+
}
|
|
4939
|
+
}
|
|
4940
|
+
if (wantTravel) {
|
|
4941
|
+
const before = previous.find((row) => storedLocation(row).point);
|
|
4942
|
+
const result = before ? evaluateTravel(
|
|
4943
|
+
{ point: storedLocation(before).point, at: new Date(before.loginTime).getTime() },
|
|
4944
|
+
{ point: pointOf(geoData), at: now },
|
|
4945
|
+
{
|
|
4946
|
+
speedKmh: detection.impossibleTravelSpeedKmh,
|
|
4947
|
+
minDistanceKm: detection.impossibleTravelMinDistanceKm
|
|
4948
|
+
}
|
|
4949
|
+
) : null;
|
|
4950
|
+
if (result?.flagged) {
|
|
4951
|
+
outcome.travel = result;
|
|
4952
|
+
record({
|
|
4953
|
+
event: SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
|
|
4954
|
+
actorType: "user",
|
|
4955
|
+
actorId: userDocumentId,
|
|
4956
|
+
targetType: "user",
|
|
4957
|
+
targetId: userDocumentId,
|
|
4958
|
+
ip,
|
|
4959
|
+
userAgent,
|
|
4960
|
+
meta: {
|
|
4961
|
+
distanceKm: result.distanceKm,
|
|
4962
|
+
speedKmh: result.speedKmh,
|
|
4963
|
+
from: storedLocation(before).country,
|
|
4964
|
+
to: typeof geoData?.country_code === "string" ? geoData.country_code : null,
|
|
4965
|
+
action: detection.impossibleTravelAction
|
|
4966
|
+
}
|
|
4967
|
+
});
|
|
4968
|
+
if (emails && detection.alertOnImpossibleTravel) {
|
|
4969
|
+
const url = await linkOnce();
|
|
4970
|
+
notifications.sendSignInSignalEmail("impossibleTravel", { ...facts, travel: result, link: url }).catch(() => {
|
|
4971
|
+
});
|
|
4972
|
+
}
|
|
4973
|
+
outcome.reauthenticate = detection.impossibleTravelAction === "reauthenticate";
|
|
4974
|
+
}
|
|
4975
|
+
}
|
|
4976
|
+
return outcome;
|
|
4977
|
+
}
|
|
4978
|
+
module2.exports = {
|
|
4979
|
+
notMeUrl,
|
|
4980
|
+
runSignInSignals,
|
|
4981
|
+
deviceFamilies,
|
|
4982
|
+
deviceKeyOf,
|
|
4983
|
+
distanceKm,
|
|
4984
|
+
evaluateTravel,
|
|
4985
|
+
isNewDevice,
|
|
4986
|
+
pointOf,
|
|
4987
|
+
previousSessions,
|
|
4988
|
+
requestDeviceId,
|
|
4989
|
+
storedLocation
|
|
4990
|
+
};
|
|
4991
|
+
}
|
|
4992
|
+
});
|
|
4993
|
+
|
|
4430
4994
|
// server/src/middlewares/session-rejection-headers.js
|
|
4431
4995
|
var require_session_rejection_headers = __commonJS({
|
|
4432
4996
|
"server/src/middlewares/session-rejection-headers.js"(exports2, module2) {
|
|
@@ -8570,6 +9134,7 @@ var require_bootstrap = __commonJS({
|
|
|
8570
9134
|
} = require_sign_in_policies();
|
|
8571
9135
|
var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
|
|
8572
9136
|
var { applyUpgradeDefaults } = require_upgrade_defaults();
|
|
9137
|
+
var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
|
|
8573
9138
|
var { anonymizeIp, normalizeIp } = require_admin_request_info();
|
|
8574
9139
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
8575
9140
|
var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -9209,6 +9774,13 @@ var require_bootstrap = __commonJS({
|
|
|
9209
9774
|
};
|
|
9210
9775
|
return byName[err?.name] || 500;
|
|
9211
9776
|
}
|
|
9777
|
+
function optionalService(strapi2, name) {
|
|
9778
|
+
try {
|
|
9779
|
+
return strapi2.plugin("magic-sessionmanager").service(name) || null;
|
|
9780
|
+
} catch {
|
|
9781
|
+
return null;
|
|
9782
|
+
}
|
|
9783
|
+
}
|
|
9212
9784
|
function refuseSessionLimit({ ctx, strapi: strapi2, limit }) {
|
|
9213
9785
|
stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
|
|
9214
9786
|
ctx.status = 403;
|
|
@@ -9432,6 +10004,7 @@ var require_bootstrap = __commonJS({
|
|
|
9432
10004
|
const geoData = ctx.state?.__magicSessionGeoData || null;
|
|
9433
10005
|
const requestSettings = await getPluginSettings(strapi2);
|
|
9434
10006
|
const isReset = isPasswordResetRequest(apiPath, ctx.method);
|
|
10007
|
+
const deviceKey = deviceKeyOf(userAgent, requestDeviceId(ctx));
|
|
9435
10008
|
const create = () => sessionService.createSession({
|
|
9436
10009
|
userId: userDocId,
|
|
9437
10010
|
ip,
|
|
@@ -9439,6 +10012,7 @@ var require_bootstrap = __commonJS({
|
|
|
9439
10012
|
token: ctx.body.jwt,
|
|
9440
10013
|
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
|
|
9441
10014
|
geoData,
|
|
10015
|
+
deviceKey,
|
|
9442
10016
|
...nativeSession ? { nativeSessionId: nativeSession.sessionId } : {}
|
|
9443
10017
|
});
|
|
9444
10018
|
const limited = isReset ? { session: await create(), refused: false, ended: 0, limit: 0 } : await createSessionWithinLimit({
|
|
@@ -9488,9 +10062,45 @@ var require_bootstrap = __commonJS({
|
|
|
9488
10062
|
log.info("[PASSWORD] Ended older sessions after password reset");
|
|
9489
10063
|
}
|
|
9490
10064
|
log.info("[SUCCESS] End-user session metadata created");
|
|
10065
|
+
let signals = { reauthenticate: false };
|
|
10066
|
+
if (!isReset) {
|
|
10067
|
+
try {
|
|
10068
|
+
signals = await runSignInSignals({
|
|
10069
|
+
strapi: strapi2,
|
|
10070
|
+
settings: requestSettings,
|
|
10071
|
+
user,
|
|
10072
|
+
userDocumentId: userDocId,
|
|
10073
|
+
session: newSession,
|
|
10074
|
+
geoData,
|
|
10075
|
+
deviceKey,
|
|
10076
|
+
userAgent: userAgent === "unknown" ? null : userAgent,
|
|
10077
|
+
ip,
|
|
10078
|
+
record: (input) => recordUserEvent(strapi2, input)
|
|
10079
|
+
});
|
|
10080
|
+
} catch (signalErr) {
|
|
10081
|
+
log.warn("[SIGNALS] Sign-in signals failed (non-fatal):", signalErr?.name || "Error");
|
|
10082
|
+
}
|
|
10083
|
+
}
|
|
10084
|
+
if (signals.reauthenticate) {
|
|
10085
|
+
await sessionService.terminateSession({ userId: userDocId, reason: "manual" });
|
|
10086
|
+
stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
|
|
10087
|
+
ctx.status = 401;
|
|
10088
|
+
ctx.body = {
|
|
10089
|
+
data: null,
|
|
10090
|
+
error: {
|
|
10091
|
+
status: 401,
|
|
10092
|
+
name: "UnauthorizedError",
|
|
10093
|
+
message: "Please sign in again.",
|
|
10094
|
+
details: { code: "REAUTHENTICATION_REQUIRED" }
|
|
10095
|
+
}
|
|
10096
|
+
};
|
|
10097
|
+
log.info("[SIGNALS] Impossible travel: every session ended, a new sign-in is required");
|
|
10098
|
+
return;
|
|
10099
|
+
}
|
|
9491
10100
|
try {
|
|
9492
10101
|
const settings = await getPluginSettings(strapi2);
|
|
9493
|
-
|
|
10102
|
+
const genericWebhook = settings.genericWebhookEnabled === true;
|
|
10103
|
+
if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks || genericWebhook)) {
|
|
9494
10104
|
return;
|
|
9495
10105
|
}
|
|
9496
10106
|
const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
|
|
@@ -9542,7 +10152,8 @@ var require_bootstrap = __commonJS({
|
|
|
9542
10152
|
user,
|
|
9543
10153
|
session: newSession,
|
|
9544
10154
|
geoData,
|
|
9545
|
-
isNewLocation
|
|
10155
|
+
isNewLocation,
|
|
10156
|
+
webhooks: optionalService(strapi2, "webhooks")
|
|
9546
10157
|
});
|
|
9547
10158
|
} catch (notifErr) {
|
|
9548
10159
|
log.warn("Notification failed:", notifErr?.name || "Error");
|
|
@@ -9880,7 +10491,7 @@ var require_bootstrap = __commonJS({
|
|
|
9880
10491
|
);
|
|
9881
10492
|
return false;
|
|
9882
10493
|
}
|
|
9883
|
-
const
|
|
10494
|
+
const baseActions = [
|
|
9884
10495
|
"plugin::magic-sessionmanager.session.logout",
|
|
9885
10496
|
"plugin::magic-sessionmanager.session.logoutAll",
|
|
9886
10497
|
"plugin::magic-sessionmanager.session.logoutOthers",
|
|
@@ -9889,6 +10500,8 @@ var require_bootstrap = __commonJS({
|
|
|
9889
10500
|
"plugin::magic-sessionmanager.session.getCurrentSession",
|
|
9890
10501
|
"plugin::magic-sessionmanager.session.terminateOwnSession"
|
|
9891
10502
|
];
|
|
10503
|
+
const version3Actions = ["plugin::magic-sessionmanager.self-service.exportOwnData"];
|
|
10504
|
+
const requiredActions = Number(effectiveVersion) === 2 ? version3Actions : [...baseActions, ...version3Actions];
|
|
9892
10505
|
const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
|
|
9893
10506
|
filters: {
|
|
9894
10507
|
role: authenticatedRole.id,
|
|
@@ -10403,6 +11016,11 @@ var require_destroy = __commonJS({
|
|
|
10403
11016
|
}
|
|
10404
11017
|
strapi2.sessionManagerAdminActivityUninstall = null;
|
|
10405
11018
|
}
|
|
11019
|
+
try {
|
|
11020
|
+
strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
|
|
11021
|
+
} catch (err) {
|
|
11022
|
+
log.warn("Failed to stop webhook deliveries:", err?.name || "Error");
|
|
11023
|
+
}
|
|
10406
11024
|
log.info("[SUCCESS] Plugin cleanup completed");
|
|
10407
11025
|
};
|
|
10408
11026
|
}
|
|
@@ -10617,6 +11235,12 @@ var require_schema = __commonJS({
|
|
|
10617
11235
|
},
|
|
10618
11236
|
osName: {
|
|
10619
11237
|
type: "string"
|
|
11238
|
+
},
|
|
11239
|
+
deviceKey: {
|
|
11240
|
+
type: "string",
|
|
11241
|
+
maxLength: 64,
|
|
11242
|
+
configurable: false,
|
|
11243
|
+
private: true
|
|
10620
11244
|
}
|
|
10621
11245
|
}
|
|
10622
11246
|
};
|
|
@@ -10857,6 +11481,57 @@ var require_content_api = __commonJS({
|
|
|
10857
11481
|
description: "Get sessions by userId (user can only see own sessions)"
|
|
10858
11482
|
}
|
|
10859
11483
|
},
|
|
11484
|
+
// ================== SELF-SERVICE (4.17) ==================
|
|
11485
|
+
{
|
|
11486
|
+
method: "GET",
|
|
11487
|
+
path: "/my-data",
|
|
11488
|
+
handler: "self-service.exportOwnData",
|
|
11489
|
+
config: {
|
|
11490
|
+
auth: { strategies: ["users-permissions"] },
|
|
11491
|
+
// An export reads every own session and event: 3 per hour per user.
|
|
11492
|
+
middlewares: [
|
|
11493
|
+
{
|
|
11494
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11495
|
+
config: { max: 3, window: 60 * 60 * 1e3 }
|
|
11496
|
+
}
|
|
11497
|
+
],
|
|
11498
|
+
description: "Download own sessions and security events as JSON (GDPR Art. 15)"
|
|
11499
|
+
}
|
|
11500
|
+
},
|
|
11501
|
+
{
|
|
11502
|
+
method: "GET",
|
|
11503
|
+
path: "/not-me",
|
|
11504
|
+
handler: "self-service.notMePage",
|
|
11505
|
+
config: {
|
|
11506
|
+
// Public on purpose: opened from the "This wasn't me" email. Only
|
|
11507
|
+
// shows a confirmation; the signed token is checked, nothing changes.
|
|
11508
|
+
auth: false,
|
|
11509
|
+
middlewares: [
|
|
11510
|
+
{
|
|
11511
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11512
|
+
config: { max: 30, window: 6e4 }
|
|
11513
|
+
}
|
|
11514
|
+
],
|
|
11515
|
+
description: `Confirmation page of the "This wasn't me" email link (public)`
|
|
11516
|
+
}
|
|
11517
|
+
},
|
|
11518
|
+
{
|
|
11519
|
+
method: "POST",
|
|
11520
|
+
path: "/not-me",
|
|
11521
|
+
handler: "self-service.notMeConfirm",
|
|
11522
|
+
config: {
|
|
11523
|
+
// Public on purpose: the signed, expiring, single-use token from the
|
|
11524
|
+
// email is the authorisation.
|
|
11525
|
+
auth: false,
|
|
11526
|
+
middlewares: [
|
|
11527
|
+
{
|
|
11528
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11529
|
+
config: { max: 10, window: 6e4 }
|
|
11530
|
+
}
|
|
11531
|
+
],
|
|
11532
|
+
description: `End the session of a "This wasn't me" link (public, single-use token)`
|
|
11533
|
+
}
|
|
11534
|
+
},
|
|
10860
11535
|
// ================== OWN SESSION MANAGEMENT ==================
|
|
10861
11536
|
{
|
|
10862
11537
|
method: "DELETE",
|
|
@@ -10882,6 +11557,7 @@ var require_admin = __commonJS({
|
|
|
10882
11557
|
var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
|
|
10883
11558
|
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
10884
11559
|
var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
|
|
11560
|
+
var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
|
|
10885
11561
|
var adminPolicy = () => [
|
|
10886
11562
|
"admin::isAuthenticatedAdmin",
|
|
10887
11563
|
{
|
|
@@ -11166,13 +11842,30 @@ var require_admin = __commonJS({
|
|
|
11166
11842
|
description: "List Users & Permissions roles for per-role rules (admin)"
|
|
11167
11843
|
}
|
|
11168
11844
|
},
|
|
11169
|
-
// ============================
|
|
11845
|
+
// ============================ SIGNED WEBHOOK ============================
|
|
11170
11846
|
{
|
|
11171
|
-
method: "
|
|
11172
|
-
path: "/
|
|
11173
|
-
handler: "
|
|
11847
|
+
method: "POST",
|
|
11848
|
+
path: "/webhook/test",
|
|
11849
|
+
handler: "webhooks.sendTest",
|
|
11174
11850
|
config: {
|
|
11175
|
-
|
|
11851
|
+
// Sends to the stored URL: same permission as changing it.
|
|
11852
|
+
policies: adminSessionsPolicy([SETTINGS_UPDATE_ACTION]),
|
|
11853
|
+
middlewares: [
|
|
11854
|
+
{
|
|
11855
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11856
|
+
config: { profile: "write", max: 5, window: 6e4 }
|
|
11857
|
+
}
|
|
11858
|
+
],
|
|
11859
|
+
description: "Send a signed test event to the stored webhook URL (admin)"
|
|
11860
|
+
}
|
|
11861
|
+
},
|
|
11862
|
+
// ============================ GEOLOCATION ============================
|
|
11863
|
+
{
|
|
11864
|
+
method: "GET",
|
|
11865
|
+
path: "/geolocation/:ipAddress",
|
|
11866
|
+
handler: "session.getIpGeolocation",
|
|
11867
|
+
config: {
|
|
11868
|
+
policies: adminPolicy(),
|
|
11176
11869
|
description: "Get IP geolocation data (admin)"
|
|
11177
11870
|
}
|
|
11178
11871
|
},
|
|
@@ -13499,6 +14192,7 @@ var require_settings_access = __commonJS({
|
|
|
13499
14192
|
"use strict";
|
|
13500
14193
|
var { SECURITY_LOG_KEYS } = require_security_log_settings();
|
|
13501
14194
|
var { POLICY_KEYS } = require_policy_settings();
|
|
14195
|
+
var { PROTECTED_DETECTION_KEYS } = require_detection_settings();
|
|
13502
14196
|
var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
|
|
13503
14197
|
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
13504
14198
|
var GEO_SETTINGS_KEYS = Object.freeze([
|
|
@@ -13518,11 +14212,17 @@ var require_settings_access = __commonJS({
|
|
|
13518
14212
|
...SECURITY_LOG_KEYS,
|
|
13519
14213
|
// Sign-in and session policies (lockout, trusted addresses, session
|
|
13520
14214
|
// limit, password-change sign-out, recording switch, per-role rules).
|
|
13521
|
-
...POLICY_KEYS
|
|
14215
|
+
...POLICY_KEYS,
|
|
14216
|
+
// Signed webhook, event selection, impossible travel and shortened IPs.
|
|
14217
|
+
...PROTECTED_DETECTION_KEYS
|
|
13522
14218
|
]);
|
|
13523
14219
|
var WEBHOOK_SECRETS = Object.freeze([
|
|
13524
14220
|
{ key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
|
|
13525
|
-
{ key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" }
|
|
14221
|
+
{ key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" },
|
|
14222
|
+
{ key: "genericWebhookUrl", has: "hasGenericWebhook", hint: "genericWebhookHint" }
|
|
14223
|
+
]);
|
|
14224
|
+
var WRITE_ONLY_SECRETS = Object.freeze([
|
|
14225
|
+
{ key: "genericWebhookSecret", has: "hasGenericWebhookSecret" }
|
|
13526
14226
|
]);
|
|
13527
14227
|
function sameValue(a, b) {
|
|
13528
14228
|
if (a === b) return true;
|
|
@@ -13570,6 +14270,11 @@ var require_settings_access = __commonJS({
|
|
|
13570
14270
|
out[has] = typeof value === "string" && value.trim().length > 0;
|
|
13571
14271
|
out[hint] = webhookHint(value);
|
|
13572
14272
|
}
|
|
14273
|
+
for (const { key, has } of WRITE_ONLY_SECRETS) {
|
|
14274
|
+
const value = out[key];
|
|
14275
|
+
delete out[key];
|
|
14276
|
+
out[has] = typeof value === "string" && value.length > 0;
|
|
14277
|
+
}
|
|
13573
14278
|
return out;
|
|
13574
14279
|
}
|
|
13575
14280
|
module2.exports = {
|
|
@@ -13579,6 +14284,7 @@ var require_settings_access = __commonJS({
|
|
|
13579
14284
|
SETTINGS_UPDATE_ACTION,
|
|
13580
14285
|
WEBHOOK_SECRETS,
|
|
13581
14286
|
WEBHOOK_SETTINGS_KEYS,
|
|
14287
|
+
WRITE_ONLY_SECRETS,
|
|
13582
14288
|
callerCan,
|
|
13583
14289
|
changedKeys,
|
|
13584
14290
|
missingSettingsPermission,
|
|
@@ -13612,6 +14318,9 @@ var require_settings = __commonJS({
|
|
|
13612
14318
|
toPublicSettings
|
|
13613
14319
|
} = require_settings_access();
|
|
13614
14320
|
var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
|
|
14321
|
+
var { DETECTION_DEFAULTS, validateDetectionSettings } = require_detection_settings();
|
|
14322
|
+
var { encryptToken } = require_encryption();
|
|
14323
|
+
var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
|
|
13615
14324
|
var path = require("node:path");
|
|
13616
14325
|
var ALLOWED_WEBHOOK_DOMAINS = {
|
|
13617
14326
|
discord: ["discord.com", "discordapp.com"],
|
|
@@ -13753,7 +14462,9 @@ var require_settings = __commonJS({
|
|
|
13753
14462
|
newLocation: { subject: "", html: "", text: "" },
|
|
13754
14463
|
vpnProxy: { subject: "", html: "", text: "" },
|
|
13755
14464
|
// 4.17: sent to a user whose account was locked after failed sign-ins.
|
|
13756
|
-
accountLocked: { subject: "", html: "", text: "" }
|
|
14465
|
+
accountLocked: { subject: "", html: "", text: "" },
|
|
14466
|
+
newDevice: { subject: "", html: "", text: "" },
|
|
14467
|
+
impossibleTravel: { subject: "", html: "", text: "" }
|
|
13757
14468
|
};
|
|
13758
14469
|
var DEFAULT_SETTINGS = {
|
|
13759
14470
|
inactivityTimeout: 15,
|
|
@@ -13789,7 +14500,10 @@ var require_settings = __commonJS({
|
|
|
13789
14500
|
...SECURITY_LOG_DEFAULTS,
|
|
13790
14501
|
...POLICY_DEFAULTS,
|
|
13791
14502
|
lockoutTrustedAddresses: [],
|
|
13792
|
-
roleRules: []
|
|
14503
|
+
roleRules: [],
|
|
14504
|
+
...DETECTION_DEFAULTS,
|
|
14505
|
+
webhookEvents: [...DETECTION_DEFAULTS.webhookEvents],
|
|
14506
|
+
genericWebhookSecret: ""
|
|
13793
14507
|
};
|
|
13794
14508
|
function mergeSettingsWithDefaults(stored) {
|
|
13795
14509
|
const safeStored = stored && typeof stored === "object" ? stored : {};
|
|
@@ -14000,6 +14714,22 @@ var require_settings = __commonJS({
|
|
|
14000
14714
|
const policies2 = validatePolicySettings(body);
|
|
14001
14715
|
errors.push(...policies2.errors);
|
|
14002
14716
|
Object.assign(next, policies2.values);
|
|
14717
|
+
const detection = validateDetectionSettings(body);
|
|
14718
|
+
errors.push(...detection.errors);
|
|
14719
|
+
Object.assign(next, detection.values);
|
|
14720
|
+
if (has("genericWebhookSecret")) {
|
|
14721
|
+
const secret = body.genericWebhookSecret;
|
|
14722
|
+
if (secret === "") {
|
|
14723
|
+
next.genericWebhookSecret = "";
|
|
14724
|
+
} else if (typeof secret !== "string" || !WEBHOOK_SECRET_PATTERN.test(secret)) {
|
|
14725
|
+
errors.push({
|
|
14726
|
+
path: ["genericWebhookSecret"],
|
|
14727
|
+
message: "genericWebhookSecret must be 32 to 256 printable characters without spaces"
|
|
14728
|
+
});
|
|
14729
|
+
} else {
|
|
14730
|
+
next.genericWebhookSecret = encryptToken(secret);
|
|
14731
|
+
}
|
|
14732
|
+
}
|
|
14003
14733
|
if (errors.length > 0) return { errors };
|
|
14004
14734
|
const settings = {};
|
|
14005
14735
|
for (const key of Object.keys(DEFAULT_SETTINGS)) {
|
|
@@ -14029,7 +14759,7 @@ var require_settings = __commonJS({
|
|
|
14029
14759
|
}
|
|
14030
14760
|
var FORBIDDEN_MESSAGES = Object.freeze({
|
|
14031
14761
|
"admin-activity-permission": 'Changing the security log settings needs "View admin activity".',
|
|
14032
|
-
"settings-update-permission": 'Changing location lookup, webhook
|
|
14762
|
+
"settings-update-permission": 'Changing location lookup, webhook, security log, sign-in policy or detection settings needs "Change protected settings".'
|
|
14033
14763
|
});
|
|
14034
14764
|
function recordSettingsChange(ctx, keys) {
|
|
14035
14765
|
if (!keys.length) return;
|
|
@@ -14200,6 +14930,7 @@ var require_settings = __commonJS({
|
|
|
14200
14930
|
},
|
|
14201
14931
|
DEFAULT_SETTINGS,
|
|
14202
14932
|
mergeSettingsWithDefaults,
|
|
14933
|
+
toPublicSettings,
|
|
14203
14934
|
validateSettingsUpdate
|
|
14204
14935
|
};
|
|
14205
14936
|
}
|
|
@@ -15453,12 +16184,14 @@ var require_admin_activity = __commonJS({
|
|
|
15453
16184
|
* @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
|
|
15454
16185
|
* read rate limit.
|
|
15455
16186
|
* @param {Context} ctx Reads `ctx.query.adminId` (optional positive integer), `event`
|
|
15456
|
-
* (`all`|`succeeded`|`failed`|`signed-out`), `from`/`to` (ISO dates), `page`, `pageSize`
|
|
16187
|
+
* (`all`|`succeeded`|`failed`|`signed-out`|`changes`), `from`/`to` (ISO dates), `page`, `pageSize`
|
|
15457
16188
|
* (1..100, default 20).
|
|
15458
16189
|
* @returns {Promise<unknown>} 200 `{ data: SignInRow[], meta: { pagination, recording,
|
|
15459
16190
|
* identity } }`; 400 ValidationError with field errors; 500 fixed message. Rows hold IP
|
|
15460
|
-
* address (possibly anonymised), location, browser, OS
|
|
15461
|
-
*
|
|
16191
|
+
* address (possibly anonymised), location, browser, OS, the stored user agent (at most
|
|
16192
|
+
* 256 characters) and session state; `event=changes` (also part of `all` without
|
|
16193
|
+
* `adminId`) lists settings changes (key names), token reads and retention runs. Never
|
|
16194
|
+
* the device id, a typed email or a token. Admin names are empty without
|
|
15462
16195
|
* `admin::users.read` (`meta.identity.names` false).
|
|
15463
16196
|
* @sideeffect A read with an admin API token queues a `security-log.read` event.
|
|
15464
16197
|
*/
|
|
@@ -15618,6 +16351,15 @@ var require_lockouts = __commonJS({
|
|
|
15618
16351
|
const lifted = await lockout().unlock(id);
|
|
15619
16352
|
if (!lifted) return ctx.notFound("This lock has already ended");
|
|
15620
16353
|
try {
|
|
16354
|
+
const liftEvent = {
|
|
16355
|
+
event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
|
|
16356
|
+
actorType: "admin",
|
|
16357
|
+
actorId: ctx.state?.user?.id ?? null,
|
|
16358
|
+
targetType: lifted.kind === "account" ? "user" : "ip",
|
|
16359
|
+
targetId: lifted.kind === "account" ? lifted.user : null,
|
|
16360
|
+
meta: { kind: lifted.kind }
|
|
16361
|
+
};
|
|
16362
|
+
strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(liftEvent);
|
|
15621
16363
|
strapi2.plugin("magic-sessionmanager").service("security-log").record({
|
|
15622
16364
|
event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
|
|
15623
16365
|
actorType: "admin",
|
|
@@ -15671,6 +16413,333 @@ var require_lockouts = __commonJS({
|
|
|
15671
16413
|
}
|
|
15672
16414
|
});
|
|
15673
16415
|
|
|
16416
|
+
// server/src/controllers/self-service.js
|
|
16417
|
+
var require_self_service = __commonJS({
|
|
16418
|
+
"server/src/controllers/self-service.js"(exports2, module2) {
|
|
16419
|
+
"use strict";
|
|
16420
|
+
var { getCoordinator } = require_coordination();
|
|
16421
|
+
var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
|
|
16422
|
+
var { recordUserEvent } = require_sign_in_policies();
|
|
16423
|
+
var { resolveUserDocumentId } = require_resolve_user();
|
|
16424
|
+
var { SECURITY_EVENTS } = require_security_log_model();
|
|
16425
|
+
var { sendServerError } = require_http_errors();
|
|
16426
|
+
var { createLogger } = require_logger();
|
|
16427
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
16428
|
+
var EVENT_UID = "plugin::magic-sessionmanager.security-event";
|
|
16429
|
+
var USER_UID = "plugin::users-permissions.user";
|
|
16430
|
+
var EXPORT_LIMIT = 5e3;
|
|
16431
|
+
var EXPORT_BATCH = 500;
|
|
16432
|
+
var PAGE_TEXT = Object.freeze({
|
|
16433
|
+
en: {
|
|
16434
|
+
title: "Was this sign-in not you?",
|
|
16435
|
+
body: "Sign the device of that sign-in out now. Then change your password.",
|
|
16436
|
+
one: "Sign out that device",
|
|
16437
|
+
all: "Sign out everywhere",
|
|
16438
|
+
done: "Done. The session was ended. Change your password now.",
|
|
16439
|
+
doneAll: "Done. Every session of your account was ended. Change your password now.",
|
|
16440
|
+
invalid: "This link is no longer valid. It works once and expires after 72 hours."
|
|
16441
|
+
},
|
|
16442
|
+
de: {
|
|
16443
|
+
title: "Waren Sie das nicht?",
|
|
16444
|
+
body: "Melden Sie das Ger\xE4t dieser Anmeldung jetzt ab. \xC4ndern Sie danach Ihr Passwort.",
|
|
16445
|
+
one: "Dieses Ger\xE4t abmelden",
|
|
16446
|
+
all: "\xDCberall abmelden",
|
|
16447
|
+
done: "Erledigt. Die Sitzung wurde beendet. \xC4ndern Sie jetzt Ihr Passwort.",
|
|
16448
|
+
doneAll: "Erledigt. Alle Sitzungen Ihres Kontos wurden beendet. \xC4ndern Sie jetzt Ihr Passwort.",
|
|
16449
|
+
invalid: "Dieser Link ist nicht mehr g\xFCltig. Er funktioniert einmal und l\xE4uft nach 72 Stunden ab."
|
|
16450
|
+
},
|
|
16451
|
+
fr: {
|
|
16452
|
+
title: "Cette connexion n\u2019\xE9tait pas vous ?",
|
|
16453
|
+
body: "D\xE9connectez maintenant l\u2019appareil de cette connexion, puis changez votre mot de passe.",
|
|
16454
|
+
one: "D\xE9connecter cet appareil",
|
|
16455
|
+
all: "Se d\xE9connecter partout",
|
|
16456
|
+
done: "C\u2019est fait. La session a \xE9t\xE9 termin\xE9e. Changez maintenant votre mot de passe.",
|
|
16457
|
+
doneAll: "C\u2019est fait. Toutes les sessions de votre compte ont \xE9t\xE9 termin\xE9es. Changez maintenant votre mot de passe.",
|
|
16458
|
+
invalid: "Ce lien n\u2019est plus valide. Il fonctionne une fois et expire apr\xE8s 72 heures."
|
|
16459
|
+
},
|
|
16460
|
+
es: {
|
|
16461
|
+
title: "\xBFEste inicio de sesi\xF3n no fue usted?",
|
|
16462
|
+
body: "Cierre ahora la sesi\xF3n del dispositivo de ese inicio de sesi\xF3n y despu\xE9s cambie su contrase\xF1a.",
|
|
16463
|
+
one: "Cerrar la sesi\xF3n de ese dispositivo",
|
|
16464
|
+
all: "Cerrar sesi\xF3n en todas partes",
|
|
16465
|
+
done: "Hecho. La sesi\xF3n ha terminado. Cambie ahora su contrase\xF1a.",
|
|
16466
|
+
doneAll: "Hecho. Todas las sesiones de su cuenta han terminado. Cambie ahora su contrase\xF1a.",
|
|
16467
|
+
invalid: "Este enlace ya no es v\xE1lido. Funciona una vez y caduca a las 72 horas."
|
|
16468
|
+
},
|
|
16469
|
+
pt: {
|
|
16470
|
+
title: "Este in\xEDcio de sess\xE3o n\xE3o foi seu?",
|
|
16471
|
+
body: "Termine agora a sess\xE3o do dispositivo desse in\xEDcio de sess\xE3o e depois altere a sua palavra-passe.",
|
|
16472
|
+
one: "Terminar a sess\xE3o desse dispositivo",
|
|
16473
|
+
all: "Terminar sess\xE3o em todo o lado",
|
|
16474
|
+
done: "Feito. A sess\xE3o foi terminada. Altere agora a sua palavra-passe.",
|
|
16475
|
+
doneAll: "Feito. Todas as sess\xF5es da sua conta foram terminadas. Altere agora a sua palavra-passe.",
|
|
16476
|
+
invalid: "Esta liga\xE7\xE3o j\xE1 n\xE3o \xE9 v\xE1lida. Funciona uma vez e expira ap\xF3s 72 horas."
|
|
16477
|
+
}
|
|
16478
|
+
});
|
|
16479
|
+
function pageLanguage(ctx) {
|
|
16480
|
+
const header = String(ctx.request?.headers?.["accept-language"] || "").slice(0, 200);
|
|
16481
|
+
for (const part of header.split(",")) {
|
|
16482
|
+
const code = part.trim().slice(0, 2).toLowerCase();
|
|
16483
|
+
if (Object.prototype.hasOwnProperty.call(PAGE_TEXT, code)) {
|
|
16484
|
+
return (
|
|
16485
|
+
/** @type {keyof typeof PAGE_TEXT} */
|
|
16486
|
+
code
|
|
16487
|
+
);
|
|
16488
|
+
}
|
|
16489
|
+
}
|
|
16490
|
+
return "en";
|
|
16491
|
+
}
|
|
16492
|
+
var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
16493
|
+
function sendPage(ctx, status, lang, title, body) {
|
|
16494
|
+
ctx.status = status;
|
|
16495
|
+
ctx.set("Content-Type", "text/html; charset=utf-8");
|
|
16496
|
+
ctx.set(
|
|
16497
|
+
"Content-Security-Policy",
|
|
16498
|
+
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
|
|
16499
|
+
);
|
|
16500
|
+
ctx.set("Referrer-Policy", "no-referrer");
|
|
16501
|
+
ctx.set("Cache-Control", "no-store");
|
|
16502
|
+
ctx.set("X-Robots-Tag", "noindex");
|
|
16503
|
+
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>
|
|
16504
|
+
<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>
|
|
16505
|
+
<body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
|
|
16506
|
+
}
|
|
16507
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
16508
|
+
const log = createLogger(strapi2);
|
|
16509
|
+
return {
|
|
16510
|
+
/**
|
|
16511
|
+
* Confirmation page of the "This wasn't me" link. Uses nothing.
|
|
16512
|
+
*
|
|
16513
|
+
* @route GET /api/magic-sessionmanager/not-me?token=
|
|
16514
|
+
* @auth none (public on purpose: the link is opened from an email; the
|
|
16515
|
+
* signed token is checked, and nothing changes until the POST)
|
|
16516
|
+
* @param {any} ctx Koa context.
|
|
16517
|
+
* @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
|
|
16518
|
+
*/
|
|
16519
|
+
async notMePage(ctx) {
|
|
16520
|
+
const lang = pageLanguage(ctx);
|
|
16521
|
+
const text = PAGE_TEXT[lang];
|
|
16522
|
+
const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
|
|
16523
|
+
if (!readNotMeToken(token)) {
|
|
16524
|
+
return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
|
|
16525
|
+
}
|
|
16526
|
+
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>`;
|
|
16527
|
+
return sendPage(
|
|
16528
|
+
ctx,
|
|
16529
|
+
200,
|
|
16530
|
+
lang,
|
|
16531
|
+
text.title,
|
|
16532
|
+
`<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
|
|
16533
|
+
);
|
|
16534
|
+
},
|
|
16535
|
+
/**
|
|
16536
|
+
* Uses a "This wasn't me" token: ends that session, or every session of
|
|
16537
|
+
* the user with `scope=all`, and records `user.not-me`.
|
|
16538
|
+
*
|
|
16539
|
+
* @route POST /api/magic-sessionmanager/not-me
|
|
16540
|
+
* @auth none (public on purpose; the signed single-use token authorises)
|
|
16541
|
+
* @param {any} ctx Koa context; body `{ token, scope?: 'session'|'all' }` (form or JSON).
|
|
16542
|
+
* @returns {Promise<void>} 200 page (or JSON `{ ended }` with Accept: application/json);
|
|
16543
|
+
* 410 when the token is invalid, expired or used.
|
|
16544
|
+
* @sideeffect Ends sessions (and native sessions); writes a security event.
|
|
16545
|
+
*/
|
|
16546
|
+
async notMeConfirm(ctx) {
|
|
16547
|
+
const lang = pageLanguage(ctx);
|
|
16548
|
+
const text = PAGE_TEXT[lang];
|
|
16549
|
+
const wantsJson = String(ctx.request?.headers?.accept || "").includes("application/json");
|
|
16550
|
+
const body = ctx.request?.body && typeof ctx.request.body === "object" ? ctx.request.body : {};
|
|
16551
|
+
const scope = body.scope === "all" ? "all" : "session";
|
|
16552
|
+
const claims = await consumeNotMeToken(getCoordinator(strapi2), body.token);
|
|
16553
|
+
if (!claims) {
|
|
16554
|
+
if (wantsJson) {
|
|
16555
|
+
ctx.status = 410;
|
|
16556
|
+
ctx.body = {
|
|
16557
|
+
data: null,
|
|
16558
|
+
error: { status: 410, name: "GoneError", message: "This link is no longer valid" }
|
|
16559
|
+
};
|
|
16560
|
+
return;
|
|
16561
|
+
}
|
|
16562
|
+
return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
|
|
16563
|
+
}
|
|
16564
|
+
try {
|
|
16565
|
+
const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
|
|
16566
|
+
let ended = 0;
|
|
16567
|
+
if (scope === "all") {
|
|
16568
|
+
ended = Number(
|
|
16569
|
+
(await sessionService.terminateSession({ userId: claims.userId, reason: "manual" }))?.terminatedCount
|
|
16570
|
+
) || 0;
|
|
16571
|
+
} else {
|
|
16572
|
+
const session = await strapi2.documents(SESSION_UID).findFirst({
|
|
16573
|
+
filters: { documentId: claims.sessionId, user: { documentId: claims.userId } },
|
|
16574
|
+
fields: ["documentId", "isActive"]
|
|
16575
|
+
});
|
|
16576
|
+
if (session?.isActive) {
|
|
16577
|
+
ended = Number(
|
|
16578
|
+
(await sessionService.terminateSession({
|
|
16579
|
+
sessionId: session.documentId,
|
|
16580
|
+
reason: "manual"
|
|
16581
|
+
}))?.terminatedCount
|
|
16582
|
+
) || 0;
|
|
16583
|
+
}
|
|
16584
|
+
}
|
|
16585
|
+
recordUserEvent(strapi2, {
|
|
16586
|
+
event: SECURITY_EVENTS.USER_NOT_ME,
|
|
16587
|
+
actorType: "user",
|
|
16588
|
+
actorId: claims.userId,
|
|
16589
|
+
targetType: "user",
|
|
16590
|
+
targetId: claims.userId,
|
|
16591
|
+
ip: ctx.request?.ip || null,
|
|
16592
|
+
userAgent: ctx.request?.headers?.["user-agent"] || null,
|
|
16593
|
+
meta: { scope, ended }
|
|
16594
|
+
});
|
|
16595
|
+
if (wantsJson) {
|
|
16596
|
+
ctx.body = { data: { ended, scope } };
|
|
16597
|
+
return;
|
|
16598
|
+
}
|
|
16599
|
+
return sendPage(
|
|
16600
|
+
ctx,
|
|
16601
|
+
200,
|
|
16602
|
+
lang,
|
|
16603
|
+
text.title,
|
|
16604
|
+
`<p>${escapeHtml(scope === "all" ? text.doneAll : text.done)}</p>`
|
|
16605
|
+
);
|
|
16606
|
+
} catch (err) {
|
|
16607
|
+
log.error("[not-me] Ending the session failed:", err?.name || "Error");
|
|
16608
|
+
return sendServerError(ctx, 500, "The session could not be ended");
|
|
16609
|
+
}
|
|
16610
|
+
},
|
|
16611
|
+
/**
|
|
16612
|
+
* The signed-in user's own sessions and security events as JSON (GDPR
|
|
16613
|
+
* Art. 15). Tokens, token hashes, device keys and native ids are never
|
|
16614
|
+
* included. At most 5,000 rows of each kind, newest first.
|
|
16615
|
+
*
|
|
16616
|
+
* @route GET /api/magic-sessionmanager/my-data
|
|
16617
|
+
* @auth users-permissions JWT (own data only; the user comes from the token)
|
|
16618
|
+
* @access plugin::magic-sessionmanager.self-service.exportOwnData (Authenticated role)
|
|
16619
|
+
* @param {any} ctx Koa context.
|
|
16620
|
+
* @returns {Promise<void>} 200 JSON attachment; 401 without a user.
|
|
16621
|
+
* @sideeffect Writes a `user.data.exported` security event.
|
|
16622
|
+
*/
|
|
16623
|
+
async exportOwnData(ctx) {
|
|
16624
|
+
const authUser = ctx.state?.user;
|
|
16625
|
+
const userDocumentId = authUser?.documentId || (authUser?.id ? await resolveUserDocumentId(strapi2, authUser.id) : null);
|
|
16626
|
+
if (!userDocumentId) return ctx.unauthorized("Authentication required");
|
|
16627
|
+
try {
|
|
16628
|
+
const user = await strapi2.db.query(USER_UID).findOne({
|
|
16629
|
+
where: { documentId: userDocumentId },
|
|
16630
|
+
select: ["documentId", "username", "email", "createdAt"]
|
|
16631
|
+
});
|
|
16632
|
+
const sessions = [];
|
|
16633
|
+
for (let start = 0; start < EXPORT_LIMIT; start += EXPORT_BATCH) {
|
|
16634
|
+
const rows = await strapi2.documents(SESSION_UID).findMany({
|
|
16635
|
+
filters: { user: { documentId: userDocumentId } },
|
|
16636
|
+
fields: [
|
|
16637
|
+
"documentId",
|
|
16638
|
+
"loginTime",
|
|
16639
|
+
"lastActive",
|
|
16640
|
+
"logoutTime",
|
|
16641
|
+
"isActive",
|
|
16642
|
+
"terminationReason",
|
|
16643
|
+
"ipAddress",
|
|
16644
|
+
"userAgent",
|
|
16645
|
+
"deviceType",
|
|
16646
|
+
"browserName",
|
|
16647
|
+
"osName",
|
|
16648
|
+
"geoLocation"
|
|
16649
|
+
],
|
|
16650
|
+
sort: [{ loginTime: "desc" }, { id: "desc" }],
|
|
16651
|
+
start,
|
|
16652
|
+
limit: EXPORT_BATCH
|
|
16653
|
+
});
|
|
16654
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
16655
|
+
sessions.push(...list.map(({ id: _id, ...row }) => row));
|
|
16656
|
+
if (list.length < EXPORT_BATCH) break;
|
|
16657
|
+
}
|
|
16658
|
+
const events = await strapi2.db.query(EVENT_UID).findMany({
|
|
16659
|
+
where: {
|
|
16660
|
+
$or: [
|
|
16661
|
+
{ targetType: "user", targetId: userDocumentId },
|
|
16662
|
+
{ actorType: "user", actorId: userDocumentId }
|
|
16663
|
+
]
|
|
16664
|
+
},
|
|
16665
|
+
select: ["event", "createdAt", "ip", "userAgent", "geo", "meta"],
|
|
16666
|
+
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
16667
|
+
limit: EXPORT_LIMIT
|
|
16668
|
+
});
|
|
16669
|
+
recordUserEvent(strapi2, {
|
|
16670
|
+
event: SECURITY_EVENTS.USER_DATA_EXPORTED,
|
|
16671
|
+
actorType: "user",
|
|
16672
|
+
actorId: userDocumentId,
|
|
16673
|
+
targetType: "user",
|
|
16674
|
+
targetId: userDocumentId,
|
|
16675
|
+
ip: ctx.request?.ip || null,
|
|
16676
|
+
userAgent: ctx.request?.headers?.["user-agent"] || null,
|
|
16677
|
+
meta: { sessions: sessions.length, events: Array.isArray(events) ? events.length : 0 }
|
|
16678
|
+
});
|
|
16679
|
+
ctx.set("Content-Disposition", 'attachment; filename="my-session-data.json"');
|
|
16680
|
+
ctx.set("Cache-Control", "no-store");
|
|
16681
|
+
ctx.body = {
|
|
16682
|
+
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
16683
|
+
user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
|
|
16684
|
+
sessions,
|
|
16685
|
+
securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
|
|
16686
|
+
};
|
|
16687
|
+
} catch (err) {
|
|
16688
|
+
log.error("[my-data] Export failed:", err?.name || "Error");
|
|
16689
|
+
return sendServerError(ctx, 500, "Your data could not be exported");
|
|
16690
|
+
}
|
|
16691
|
+
}
|
|
16692
|
+
};
|
|
16693
|
+
};
|
|
16694
|
+
}
|
|
16695
|
+
});
|
|
16696
|
+
|
|
16697
|
+
// server/src/controllers/webhooks.js
|
|
16698
|
+
var require_webhooks = __commonJS({
|
|
16699
|
+
"server/src/controllers/webhooks.js"(exports2, module2) {
|
|
16700
|
+
"use strict";
|
|
16701
|
+
var { sendServerError } = require_http_errors();
|
|
16702
|
+
var { createLogger } = require_logger();
|
|
16703
|
+
var RESULT_CODES = /* @__PURE__ */ new Set([
|
|
16704
|
+
"no_url",
|
|
16705
|
+
"no_secret",
|
|
16706
|
+
"invalid_url",
|
|
16707
|
+
"dns_failed",
|
|
16708
|
+
"address_not_allowed",
|
|
16709
|
+
"timeout",
|
|
16710
|
+
"network_error",
|
|
16711
|
+
"redirect_not_followed"
|
|
16712
|
+
]);
|
|
16713
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
16714
|
+
const log = createLogger(strapi2);
|
|
16715
|
+
return {
|
|
16716
|
+
/**
|
|
16717
|
+
* Sends one signed `test` event to the stored URL, without retries.
|
|
16718
|
+
*
|
|
16719
|
+
* @route POST /magic-sessionmanager/webhook/test
|
|
16720
|
+
* @auth admin session or admin API token
|
|
16721
|
+
* @access plugin::magic-sessionmanager.access
|
|
16722
|
+
* @param {any} ctx Koa context.
|
|
16723
|
+
* @returns {Promise<void>} `{ data: { ok, status, code } }` (status of the receiver's answer;
|
|
16724
|
+
* code: no_url, no_secret, invalid_url, dns_failed, address_not_allowed, timeout,
|
|
16725
|
+
* network_error, redirect_not_followed or http_<status>).
|
|
16726
|
+
* @sideeffect One HTTPS request to the stored webhook URL.
|
|
16727
|
+
*/
|
|
16728
|
+
async sendTest(ctx) {
|
|
16729
|
+
try {
|
|
16730
|
+
const result = await strapi2.plugin("magic-sessionmanager").service("webhooks").sendTest();
|
|
16731
|
+
const code = result.code === null || RESULT_CODES.has(result.code) || /^http_\d{3}$/.test(result.code) ? result.code : "network_error";
|
|
16732
|
+
ctx.body = { data: { ok: result.ok === true, status: result.status ?? null, code } };
|
|
16733
|
+
} catch (err) {
|
|
16734
|
+
log.error("[webhooks] Test send failed:", err?.name || "Error");
|
|
16735
|
+
return sendServerError(ctx, 500, "The test event could not be sent");
|
|
16736
|
+
}
|
|
16737
|
+
}
|
|
16738
|
+
};
|
|
16739
|
+
};
|
|
16740
|
+
}
|
|
16741
|
+
});
|
|
16742
|
+
|
|
15674
16743
|
// server/src/controllers/index.js
|
|
15675
16744
|
var require_controllers = __commonJS({
|
|
15676
16745
|
"server/src/controllers/index.js"(exports2, module2) {
|
|
@@ -15681,13 +16750,17 @@ var require_controllers = __commonJS({
|
|
|
15681
16750
|
var adminSessions = require_admin_sessions2();
|
|
15682
16751
|
var adminActivity = require_admin_activity();
|
|
15683
16752
|
var lockouts = require_lockouts();
|
|
16753
|
+
var selfService = require_self_service();
|
|
16754
|
+
var webhooks = require_webhooks();
|
|
15684
16755
|
module2.exports = {
|
|
15685
16756
|
session,
|
|
15686
16757
|
settings,
|
|
15687
16758
|
geoip,
|
|
15688
16759
|
"admin-sessions": adminSessions,
|
|
15689
16760
|
"admin-activity": adminActivity,
|
|
15690
|
-
lockouts
|
|
16761
|
+
lockouts,
|
|
16762
|
+
"self-service": selfService,
|
|
16763
|
+
webhooks
|
|
15691
16764
|
};
|
|
15692
16765
|
}
|
|
15693
16766
|
});
|
|
@@ -15703,6 +16776,9 @@ var require_session2 = __commonJS({
|
|
|
15703
16776
|
var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
|
|
15704
16777
|
var { getPluginSettings } = require_settings_loader();
|
|
15705
16778
|
var { hasRoleOverride, inactivityTimeoutFor } = require_policy_settings();
|
|
16779
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
16780
|
+
var { anonymizeIp, normalizeIp } = require_admin_request_info();
|
|
16781
|
+
var { pointOf } = require_sign_in_signals();
|
|
15706
16782
|
var {
|
|
15707
16783
|
cleanupExpiredAccessTokenRevocations,
|
|
15708
16784
|
persistAccessTokenRevocation
|
|
@@ -16034,6 +17110,7 @@ var require_session2 = __commonJS({
|
|
|
16034
17110
|
* @param {string} [params.refreshToken] - Refresh token (will be encrypted)
|
|
16035
17111
|
* @param {string} [params.nativeSessionId] - Native Users & Permissions session ID.
|
|
16036
17112
|
* @param {object} [params.geoData]
|
|
17113
|
+
* @param {string} [params.deviceKey] Device key from utils/sign-in-signals.js.
|
|
16037
17114
|
* @returns {Promise<object>} Created session
|
|
16038
17115
|
* @throws {Error} When userId is missing
|
|
16039
17116
|
*/
|
|
@@ -16044,11 +17121,13 @@ var require_session2 = __commonJS({
|
|
|
16044
17121
|
token,
|
|
16045
17122
|
refreshToken,
|
|
16046
17123
|
nativeSessionId,
|
|
16047
|
-
geoData
|
|
17124
|
+
geoData,
|
|
17125
|
+
deviceKey
|
|
16048
17126
|
}) {
|
|
16049
17127
|
if (!userId) {
|
|
16050
17128
|
throw new Error("createSession: userId is required");
|
|
16051
17129
|
}
|
|
17130
|
+
const privacy = await getPluginSettings(strapi2).then(resolveDetectionSettings).catch(() => ({}));
|
|
16052
17131
|
try {
|
|
16053
17132
|
const now = /* @__PURE__ */ new Date();
|
|
16054
17133
|
const sessionId = generateSessionId(userId);
|
|
@@ -16058,7 +17137,9 @@ var require_session2 = __commonJS({
|
|
|
16058
17137
|
const tokenHashValue = token ? hashToken(token) : null;
|
|
16059
17138
|
const refreshTokenHashValue = refreshToken ? hashToken(refreshToken) : null;
|
|
16060
17139
|
const parsedUA = parseUserAgent(userAgent);
|
|
16061
|
-
const
|
|
17140
|
+
const rawIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
|
|
17141
|
+
const safeIp = privacy.sessionIpAnonymize && normalizeIp(rawIp) ? anonymizeIp(normalizeIp(rawIp)) || rawIp : rawIp;
|
|
17142
|
+
const point = privacy.impossibleTravelEnabled ? pointOf(geoData) : null;
|
|
16062
17143
|
const safeUa = (typeof userAgent === "string" ? userAgent : "unknown").substring(0, 500);
|
|
16063
17144
|
const session = await strapi2.documents(SESSION_UID).create({
|
|
16064
17145
|
data: {
|
|
@@ -16086,8 +17167,10 @@ var require_session2 = __commonJS({
|
|
|
16086
17167
|
timezone: geoData.timezone,
|
|
16087
17168
|
// Marks the stored score as real risk data; without a
|
|
16088
17169
|
// risk source the score is null (not a fake 100).
|
|
16089
|
-
...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
|
|
17170
|
+
...geoData.riskSource ? { riskSource: geoData.riskSource } : {},
|
|
17171
|
+
...point ? { latitude: point.lat, longitude: point.lon } : {}
|
|
16090
17172
|
} : null,
|
|
17173
|
+
...typeof deviceKey === "string" && /^[a-f0-9]{32}$/.test(deviceKey) ? { deviceKey } : {},
|
|
16091
17174
|
securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
|
|
16092
17175
|
}
|
|
16093
17176
|
});
|
|
@@ -17804,6 +18887,75 @@ Hello {{user.username}},
|
|
|
17804
18887
|
There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
|
|
17805
18888
|
|
|
17806
18889
|
If these attempts were not yours, change your password after the lock ends.`
|
|
18890
|
+
}),
|
|
18891
|
+
newDevice: Object.freeze({
|
|
18892
|
+
subject: "New sign-in to your account",
|
|
18893
|
+
html: `<html>
|
|
18894
|
+
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
|
|
18895
|
+
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
|
|
18896
|
+
<h2>New sign-in to your account</h2>
|
|
18897
|
+
<p>Hello {{user.username}},</p>
|
|
18898
|
+
<p>Your account was just used on a device we have not seen before.</p>
|
|
18899
|
+
<ul>
|
|
18900
|
+
<li>Time: {{session.loginTime}}</li>
|
|
18901
|
+
<li>Device: {{device.browser}} on {{device.os}}</li>
|
|
18902
|
+
<li>Location: {{geo.city}}, {{geo.country}}</li>
|
|
18903
|
+
<li>IP address: {{session.ipAddress}}</li>
|
|
18904
|
+
</ul>
|
|
18905
|
+
<p>If this was you, you can ignore this email.</p>
|
|
18906
|
+
<p>If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
|
|
18907
|
+
<p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
|
|
18908
|
+
</div>
|
|
18909
|
+
</body>
|
|
18910
|
+
</html>`,
|
|
18911
|
+
text: `New sign-in to your account
|
|
18912
|
+
|
|
18913
|
+
Hello {{user.username}},
|
|
18914
|
+
|
|
18915
|
+
Your account was just used on a device we have not seen before.
|
|
18916
|
+
|
|
18917
|
+
Time: {{session.loginTime}}
|
|
18918
|
+
Device: {{device.browser}} on {{device.os}}
|
|
18919
|
+
Location: {{geo.city}}, {{geo.country}}
|
|
18920
|
+
IP address: {{session.ipAddress}}
|
|
18921
|
+
|
|
18922
|
+
If this was not you, sign this device out and change your password:
|
|
18923
|
+
{{link.notMe}}
|
|
18924
|
+
|
|
18925
|
+
The link works once and expires after 72 hours.`
|
|
18926
|
+
}),
|
|
18927
|
+
impossibleTravel: Object.freeze({
|
|
18928
|
+
subject: "Unusual sign-in to your account",
|
|
18929
|
+
html: `<html>
|
|
18930
|
+
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
|
|
18931
|
+
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
|
|
18932
|
+
<h2>Unusual sign-in to your account</h2>
|
|
18933
|
+
<p>Hello {{user.username}},</p>
|
|
18934
|
+
<p>Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.</p>
|
|
18935
|
+
<ul>
|
|
18936
|
+
<li>Time: {{session.loginTime}}</li>
|
|
18937
|
+
<li>Location: {{geo.city}}, {{geo.country}}</li>
|
|
18938
|
+
<li>Device: {{device.browser}} on {{device.os}}</li>
|
|
18939
|
+
</ul>
|
|
18940
|
+
<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>
|
|
18941
|
+
<p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
|
|
18942
|
+
</div>
|
|
18943
|
+
</body>
|
|
18944
|
+
</html>`,
|
|
18945
|
+
text: `Unusual sign-in to your account
|
|
18946
|
+
|
|
18947
|
+
Hello {{user.username}},
|
|
18948
|
+
|
|
18949
|
+
Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.
|
|
18950
|
+
|
|
18951
|
+
Time: {{session.loginTime}}
|
|
18952
|
+
Location: {{geo.city}}, {{geo.country}}
|
|
18953
|
+
Device: {{device.browser}} on {{device.os}}
|
|
18954
|
+
|
|
18955
|
+
A VPN or a mobile network can cause this. If this was not you, sign this device out and change your password:
|
|
18956
|
+
{{link.notMe}}
|
|
18957
|
+
|
|
18958
|
+
The link works once and expires after 72 hours.`
|
|
17807
18959
|
})
|
|
17808
18960
|
});
|
|
17809
18961
|
var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
|
|
@@ -17934,6 +19086,37 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
17934
19086
|
}
|
|
17935
19087
|
return { ...POLICY_TEMPLATES[key] };
|
|
17936
19088
|
},
|
|
19089
|
+
/**
|
|
19090
|
+
* Emails a user about a sign-in from a new device or an impossible
|
|
19091
|
+
* travel, with the "This wasn't me" link.
|
|
19092
|
+
*
|
|
19093
|
+
* @param {'newDevice'|'impossibleTravel'} key Template.
|
|
19094
|
+
* @param {{user: object, session: object, geoData?: object|null, device: object,
|
|
19095
|
+
* travel?: object|null, link: string|null}} data Values.
|
|
19096
|
+
* @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
|
|
19097
|
+
* @sideeffect Sends one email.
|
|
19098
|
+
*/
|
|
19099
|
+
async sendSignInSignalEmail(key, data) {
|
|
19100
|
+
try {
|
|
19101
|
+
if (!data?.user?.email) return false;
|
|
19102
|
+
const template = await this.getTemplate(key);
|
|
19103
|
+
const values = { ...data, geoData: data.geoData || {}, link: { notMe: data.link } };
|
|
19104
|
+
await strapi2.plugin("email").service("email").send({
|
|
19105
|
+
to: data.user.email,
|
|
19106
|
+
subject: this.replaceVariables(template.subject, values),
|
|
19107
|
+
html: this.replaceVariables(template.html, values),
|
|
19108
|
+
text: this.replaceVariables(template.text, values)
|
|
19109
|
+
});
|
|
19110
|
+
strapi2.log.info(`[magic-sessionmanager/notifications] ${key} email sent`);
|
|
19111
|
+
return true;
|
|
19112
|
+
} catch (err) {
|
|
19113
|
+
strapi2.log.error(
|
|
19114
|
+
`[magic-sessionmanager/notifications] ${key} email failed:`,
|
|
19115
|
+
err?.name || "Error"
|
|
19116
|
+
);
|
|
19117
|
+
return false;
|
|
19118
|
+
}
|
|
19119
|
+
},
|
|
17937
19120
|
/**
|
|
17938
19121
|
* Emails a user that their account was locked after failed sign-ins.
|
|
17939
19122
|
* Sent through Strapi's email plugin, so a provider plugin such as Magic
|
|
@@ -18010,6 +19193,18 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
18010
19193
|
/\{\{lock\.until\}\}/g,
|
|
18011
19194
|
esc(Number.isFinite(data.lock?.until) ? new Date(data.lock.until).toUTCString() : "N/A")
|
|
18012
19195
|
);
|
|
19196
|
+
result = result.replace(/\{\{device\.browser\}\}/g, esc(data.device?.browser || "Unknown"));
|
|
19197
|
+
result = result.replace(/\{\{device\.os\}\}/g, esc(data.device?.os || "Unknown"));
|
|
19198
|
+
result = result.replace(
|
|
19199
|
+
/\{\{travel\.distanceKm\}\}/g,
|
|
19200
|
+
esc(Number.isFinite(data.travel?.distanceKm) ? String(data.travel.distanceKm) : "N/A")
|
|
19201
|
+
);
|
|
19202
|
+
result = result.replace(
|
|
19203
|
+
/\{\{travel\.speedKmh\}\}/g,
|
|
19204
|
+
esc(Number.isFinite(data.travel?.speedKmh) ? String(data.travel.speedKmh) : "N/A")
|
|
19205
|
+
);
|
|
19206
|
+
const link = typeof data.link?.notMe === "string" && /^https?:\/\//.test(data.link.notMe) ? data.link.notMe : "";
|
|
19207
|
+
result = result.replace(/\{\{link\.notMe\}\}/g, esc(link));
|
|
18013
19208
|
const score = data.reason?.securityScore;
|
|
18014
19209
|
result = result.replace(
|
|
18015
19210
|
/\{\{reason\.securityScore\}\}/g,
|
|
@@ -18399,6 +19594,10 @@ var require_security_log = __commonJS({
|
|
|
18399
19594
|
function isUnknownAccountFailure(entry) {
|
|
18400
19595
|
return entry.event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED && !toId(entry.actorId) && !toId(entry.targetId) && typeof entry.attemptedEmail !== "string";
|
|
18401
19596
|
}
|
|
19597
|
+
function settingKeysOf(value) {
|
|
19598
|
+
if (typeof value !== "string") return [];
|
|
19599
|
+
return value.split(",").map((key) => key.trim()).filter((key) => /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(key)).slice(0, 50);
|
|
19600
|
+
}
|
|
18402
19601
|
module2.exports = ({ strapi: strapi2 }) => {
|
|
18403
19602
|
const log = createLogger(strapi2);
|
|
18404
19603
|
let queue = [];
|
|
@@ -19120,16 +20319,21 @@ var require_security_log = __commonJS({
|
|
|
19120
20319
|
})).sort((a, b) => a.name.localeCompare(b.name));
|
|
19121
20320
|
}
|
|
19122
20321
|
async function shapeSignIns(rows, viewer) {
|
|
19123
|
-
const admins = await loadAdmins(rows.flatMap((row) => [row.targetId, row.actorId]));
|
|
19124
20322
|
const nameOf = (user) => viewer.canReadAdmins === true ? adminName(user) : "";
|
|
19125
20323
|
const states = await sessionStates(rows);
|
|
20324
|
+
const admins = await loadAdmins([
|
|
20325
|
+
...rows.flatMap((row) => [row.targetId, row.actorId]),
|
|
20326
|
+
...[...states.values()].map((state) => state.endedBy)
|
|
20327
|
+
]);
|
|
19126
20328
|
return rows.map((row) => {
|
|
19127
20329
|
const meta = toObject(row.meta);
|
|
19128
|
-
const
|
|
20330
|
+
const ownAction = (row.event === SECURITY_EVENTS.SETTINGS_UPDATED || row.event === SECURITY_EVENTS.LOG_READ) && row.actorType === "admin";
|
|
20331
|
+
const admin = row.targetType === "admin" ? admins.get(Number(row.targetId)) : ownAction ? admins.get(Number(row.actorId)) : void 0;
|
|
19129
20332
|
const revoked = row.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
|
|
19130
20333
|
const actor = revoked ? admins.get(Number(row.actorId)) : void 0;
|
|
19131
20334
|
const described = describeUserAgent(row.userAgent || null);
|
|
19132
20335
|
const state = states.get(Number(row.id));
|
|
20336
|
+
const endedBy = state?.endedBy ? admins.get(Number(state.endedBy)) : void 0;
|
|
19133
20337
|
return {
|
|
19134
20338
|
id: Number(row.id),
|
|
19135
20339
|
event: row.event,
|
|
@@ -19145,9 +20349,24 @@ var require_security_log = __commonJS({
|
|
|
19145
20349
|
browser: described.browserName,
|
|
19146
20350
|
os: described.osName,
|
|
19147
20351
|
deviceType: described.deviceType,
|
|
20352
|
+
userAgent: typeof row.userAgent === "string" && row.userAgent ? row.userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null,
|
|
19148
20353
|
admin: admin ? { id: Number(admin.id), name: nameOf(admin) } : null,
|
|
19149
20354
|
actor: actor ? { id: Number(actor.id), name: nameOf(actor) } : null,
|
|
19150
|
-
|
|
20355
|
+
sessionsEnded: revoked && Number.isInteger(meta.ended) && meta.ended >= 0 ? meta.ended : null,
|
|
20356
|
+
change: row.event === SECURITY_EVENTS.SETTINGS_UPDATED ? { keys: settingKeysOf(meta.keys), viaToken: meta.via === "admin-token" } : null,
|
|
20357
|
+
read: row.event === SECURITY_EVENTS.LOG_READ ? {
|
|
20358
|
+
list: meta.list === "content" ? "content" : "sign-ins",
|
|
20359
|
+
exported: meta.exported === true
|
|
20360
|
+
} : null,
|
|
20361
|
+
purge: row.event === SECURITY_EVENTS.LOG_RETENTION_PURGED ? {
|
|
20362
|
+
count: Number.isInteger(meta.count) ? meta.count : null,
|
|
20363
|
+
retentionDays: Number.isInteger(meta.retentionDays) ? meta.retentionDays : null
|
|
20364
|
+
} : null,
|
|
20365
|
+
session: row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && state ? {
|
|
20366
|
+
state: state.state,
|
|
20367
|
+
endedAt: toIso(state.endedAt),
|
|
20368
|
+
endedBy: endedBy ? { id: Number(endedBy.id), name: nameOf(endedBy) } : null
|
|
20369
|
+
} : null
|
|
19151
20370
|
};
|
|
19152
20371
|
});
|
|
19153
20372
|
}
|
|
@@ -19303,6 +20522,478 @@ var require_security_log = __commonJS({
|
|
|
19303
20522
|
}
|
|
19304
20523
|
});
|
|
19305
20524
|
|
|
20525
|
+
// server/src/utils/webhook-delivery.js
|
|
20526
|
+
var require_webhook_delivery = __commonJS({
|
|
20527
|
+
"server/src/utils/webhook-delivery.js"(exports2, module2) {
|
|
20528
|
+
"use strict";
|
|
20529
|
+
var crypto = require("node:crypto");
|
|
20530
|
+
var dns = require("node:dns");
|
|
20531
|
+
var https = require("node:https");
|
|
20532
|
+
var net = require("node:net");
|
|
20533
|
+
var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
|
|
20534
|
+
var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
|
|
20535
|
+
var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
|
|
20536
|
+
var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
|
|
20537
|
+
var TIMEOUT_MS = 5e3;
|
|
20538
|
+
var MAX_RESPONSE_BYTES = 64 * 1024;
|
|
20539
|
+
var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
|
|
20540
|
+
var BLOCKED = (() => {
|
|
20541
|
+
const list = new net.BlockList();
|
|
20542
|
+
for (const [address, prefix] of [
|
|
20543
|
+
["0.0.0.0", 8],
|
|
20544
|
+
["10.0.0.0", 8],
|
|
20545
|
+
["100.64.0.0", 10],
|
|
20546
|
+
["127.0.0.0", 8],
|
|
20547
|
+
["169.254.0.0", 16],
|
|
20548
|
+
["172.16.0.0", 12],
|
|
20549
|
+
["192.0.0.0", 24],
|
|
20550
|
+
["192.0.2.0", 24],
|
|
20551
|
+
["192.88.99.0", 24],
|
|
20552
|
+
["192.168.0.0", 16],
|
|
20553
|
+
["198.18.0.0", 15],
|
|
20554
|
+
["198.51.100.0", 24],
|
|
20555
|
+
["203.0.113.0", 24],
|
|
20556
|
+
["224.0.0.0", 4],
|
|
20557
|
+
["240.0.0.0", 4]
|
|
20558
|
+
]) {
|
|
20559
|
+
list.addSubnet(address, prefix, "ipv4");
|
|
20560
|
+
}
|
|
20561
|
+
for (const [address, prefix] of [
|
|
20562
|
+
["::", 128],
|
|
20563
|
+
["::1", 128],
|
|
20564
|
+
// IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
|
|
20565
|
+
// checks them against the IPv4 rules above, and a listed /96 would
|
|
20566
|
+
// match every IPv4 address.
|
|
20567
|
+
["64:ff9b::", 96],
|
|
20568
|
+
["64:ff9b:1::", 48],
|
|
20569
|
+
["100::", 64],
|
|
20570
|
+
["2001::", 23],
|
|
20571
|
+
["2001:db8::", 32],
|
|
20572
|
+
["2002::", 16],
|
|
20573
|
+
["fc00::", 7],
|
|
20574
|
+
["fe80::", 10],
|
|
20575
|
+
["fec0::", 10],
|
|
20576
|
+
["ff00::", 8]
|
|
20577
|
+
]) {
|
|
20578
|
+
list.addSubnet(address, prefix, "ipv6");
|
|
20579
|
+
}
|
|
20580
|
+
return list;
|
|
20581
|
+
})();
|
|
20582
|
+
function isBlockedAddress(address) {
|
|
20583
|
+
let value = String(address || "").trim();
|
|
20584
|
+
if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
|
|
20585
|
+
value = value.slice(7);
|
|
20586
|
+
}
|
|
20587
|
+
const version = net.isIP(value);
|
|
20588
|
+
if (version === 0) return true;
|
|
20589
|
+
return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
|
|
20590
|
+
}
|
|
20591
|
+
function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
|
|
20592
|
+
const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
|
20593
|
+
return `t=${timestamp},v1=${digest}`;
|
|
20594
|
+
}
|
|
20595
|
+
function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
|
|
20596
|
+
const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
|
|
20597
|
+
if (!match) return false;
|
|
20598
|
+
const timestamp = Number(match[1]);
|
|
20599
|
+
if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
|
|
20600
|
+
const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
|
|
20601
|
+
const given = Buffer.from(match[2], "hex");
|
|
20602
|
+
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
|
|
20603
|
+
}
|
|
20604
|
+
var DeliveryError = class extends Error {
|
|
20605
|
+
/**
|
|
20606
|
+
* @param {string} code Stable code.
|
|
20607
|
+
* @param {boolean} retryable Whether another attempt may succeed.
|
|
20608
|
+
* @param {number|null} [status] HTTP status, when there was one.
|
|
20609
|
+
*/
|
|
20610
|
+
constructor(code, retryable, status = null) {
|
|
20611
|
+
super(code);
|
|
20612
|
+
this.name = "DeliveryError";
|
|
20613
|
+
this.code = code;
|
|
20614
|
+
this.retryable = retryable;
|
|
20615
|
+
this.status = status;
|
|
20616
|
+
}
|
|
20617
|
+
};
|
|
20618
|
+
var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
|
|
20619
|
+
function httpsPost({ url, address, headers, body, timeoutMs }) {
|
|
20620
|
+
return new Promise((resolve, reject) => {
|
|
20621
|
+
const request = https.request(
|
|
20622
|
+
{
|
|
20623
|
+
protocol: "https:",
|
|
20624
|
+
hostname: url.hostname,
|
|
20625
|
+
port: url.port || 443,
|
|
20626
|
+
path: `${url.pathname}${url.search}`,
|
|
20627
|
+
method: "POST",
|
|
20628
|
+
headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
|
|
20629
|
+
servername: net.isIP(url.hostname) ? void 0 : url.hostname,
|
|
20630
|
+
timeout: timeoutMs,
|
|
20631
|
+
// Pinned to the address that passed the check: no second lookup.
|
|
20632
|
+
lookup: (_hostname, options, callback) => {
|
|
20633
|
+
if (options && options.all) callback(null, [address]);
|
|
20634
|
+
else callback(null, address.address, address.family);
|
|
20635
|
+
}
|
|
20636
|
+
},
|
|
20637
|
+
(response) => {
|
|
20638
|
+
let received = 0;
|
|
20639
|
+
response.on("data", (chunk) => {
|
|
20640
|
+
received += chunk.length;
|
|
20641
|
+
if (received > MAX_RESPONSE_BYTES) response.destroy();
|
|
20642
|
+
});
|
|
20643
|
+
response.on("end", () => resolve(response.statusCode || 0));
|
|
20644
|
+
response.on("close", () => resolve(response.statusCode || 0));
|
|
20645
|
+
response.on("error", () => resolve(response.statusCode || 0));
|
|
20646
|
+
}
|
|
20647
|
+
);
|
|
20648
|
+
request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
|
|
20649
|
+
request.on(
|
|
20650
|
+
"error",
|
|
20651
|
+
(err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
|
|
20652
|
+
);
|
|
20653
|
+
request.end(body);
|
|
20654
|
+
});
|
|
20655
|
+
}
|
|
20656
|
+
async function deliverOnce({
|
|
20657
|
+
url,
|
|
20658
|
+
body,
|
|
20659
|
+
headers,
|
|
20660
|
+
resolve = resolveAll,
|
|
20661
|
+
post = httpsPost,
|
|
20662
|
+
timeoutMs = TIMEOUT_MS
|
|
20663
|
+
}) {
|
|
20664
|
+
let parsed;
|
|
20665
|
+
try {
|
|
20666
|
+
parsed = new URL(url);
|
|
20667
|
+
} catch {
|
|
20668
|
+
throw new DeliveryError("invalid_url", false);
|
|
20669
|
+
}
|
|
20670
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
|
|
20671
|
+
throw new DeliveryError("invalid_url", false);
|
|
20672
|
+
}
|
|
20673
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, "");
|
|
20674
|
+
let addresses;
|
|
20675
|
+
if (net.isIP(host)) {
|
|
20676
|
+
addresses = [{ address: host, family: net.isIP(host) }];
|
|
20677
|
+
} else {
|
|
20678
|
+
try {
|
|
20679
|
+
addresses = await resolve(host);
|
|
20680
|
+
} catch {
|
|
20681
|
+
throw new DeliveryError("dns_failed", true);
|
|
20682
|
+
}
|
|
20683
|
+
}
|
|
20684
|
+
if (!Array.isArray(addresses) || addresses.length === 0)
|
|
20685
|
+
throw new DeliveryError("dns_failed", true);
|
|
20686
|
+
if (addresses.some((entry) => isBlockedAddress(entry.address))) {
|
|
20687
|
+
throw new DeliveryError("address_not_allowed", false);
|
|
20688
|
+
}
|
|
20689
|
+
const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
|
|
20690
|
+
if (status >= 200 && status < 300) return { status };
|
|
20691
|
+
if (status >= 300 && status < 400)
|
|
20692
|
+
throw new DeliveryError("redirect_not_followed", false, status);
|
|
20693
|
+
throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
|
|
20694
|
+
}
|
|
20695
|
+
function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
|
|
20696
|
+
const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
|
|
20697
|
+
return {
|
|
20698
|
+
id,
|
|
20699
|
+
body,
|
|
20700
|
+
headers: {
|
|
20701
|
+
"Content-Type": "application/json",
|
|
20702
|
+
"User-Agent": USER_AGENT,
|
|
20703
|
+
[EVENT_HEADER]: event,
|
|
20704
|
+
[DELIVERY_HEADER]: id,
|
|
20705
|
+
[SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
|
|
20706
|
+
}
|
|
20707
|
+
};
|
|
20708
|
+
}
|
|
20709
|
+
async function deliverWithRetries({
|
|
20710
|
+
delays = RETRY_DELAYS_MS,
|
|
20711
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
|
|
20712
|
+
...request
|
|
20713
|
+
}) {
|
|
20714
|
+
let attempts = 0;
|
|
20715
|
+
let last = { ok: false, status: null, code: "not_sent" };
|
|
20716
|
+
for (const delay of delays) {
|
|
20717
|
+
if (delay > 0) await sleep(delay);
|
|
20718
|
+
attempts += 1;
|
|
20719
|
+
try {
|
|
20720
|
+
const { status } = await deliverOnce(request);
|
|
20721
|
+
return { ok: true, status, code: null, attempts };
|
|
20722
|
+
} catch (err) {
|
|
20723
|
+
const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
|
|
20724
|
+
last = { ok: false, status: error.status, code: error.code };
|
|
20725
|
+
if (!error.retryable) break;
|
|
20726
|
+
}
|
|
20727
|
+
}
|
|
20728
|
+
return { ...last, attempts };
|
|
20729
|
+
}
|
|
20730
|
+
module2.exports = {
|
|
20731
|
+
DELIVERY_HEADER,
|
|
20732
|
+
DeliveryError,
|
|
20733
|
+
EVENT_HEADER,
|
|
20734
|
+
RETRY_DELAYS_MS,
|
|
20735
|
+
SIGNATURE_HEADER,
|
|
20736
|
+
buildSignedRequest,
|
|
20737
|
+
deliverOnce,
|
|
20738
|
+
deliverWithRetries,
|
|
20739
|
+
isBlockedAddress,
|
|
20740
|
+
signPayload,
|
|
20741
|
+
verifySignature
|
|
20742
|
+
};
|
|
20743
|
+
}
|
|
20744
|
+
});
|
|
20745
|
+
|
|
20746
|
+
// server/src/services/webhooks.js
|
|
20747
|
+
var require_webhooks2 = __commonJS({
|
|
20748
|
+
"server/src/services/webhooks.js"(exports2, module2) {
|
|
20749
|
+
"use strict";
|
|
20750
|
+
var { decryptToken } = require_encryption();
|
|
20751
|
+
var { getPluginSettings } = require_settings_loader();
|
|
20752
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
20753
|
+
var { resolveSecurityLogSettings } = require_security_log_settings();
|
|
20754
|
+
var { anonymizeIp, normalizeIp } = require_admin_request_info();
|
|
20755
|
+
var { SECURITY_EVENTS } = require_security_log_model();
|
|
20756
|
+
var {
|
|
20757
|
+
buildSignedRequest,
|
|
20758
|
+
deliverOnce,
|
|
20759
|
+
deliverWithRetries
|
|
20760
|
+
} = require_webhook_delivery();
|
|
20761
|
+
var { createLogger } = require_logger();
|
|
20762
|
+
var EVENT_OF_SECURITY_EVENT = Object.freeze({
|
|
20763
|
+
[SECURITY_EVENTS.USER_SIGN_IN_FAILED]: "login.failed",
|
|
20764
|
+
[SECURITY_EVENTS.USER_SIGN_IN_REFUSED]: "login.refused",
|
|
20765
|
+
[SECURITY_EVENTS.USER_LOCKOUT]: "lockout",
|
|
20766
|
+
[SECURITY_EVENTS.USER_LOCKOUT_LIFTED]: "lockout.lifted",
|
|
20767
|
+
[SECURITY_EVENTS.USER_SESSION_LIMIT]: "session.limit",
|
|
20768
|
+
[SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED]: "password.changed",
|
|
20769
|
+
"user.sign-in.new-device": "login.new_device",
|
|
20770
|
+
"user.sign-in.impossible-travel": "login.impossible_travel",
|
|
20771
|
+
"user.not-me": "user.not_me"
|
|
20772
|
+
});
|
|
20773
|
+
var CHAT_TITLES = Object.freeze({
|
|
20774
|
+
"login.failed": "Failed sign-in",
|
|
20775
|
+
"login.refused": "Refused sign-in",
|
|
20776
|
+
"login.new_device": "Sign-in from a new device",
|
|
20777
|
+
"login.impossible_travel": "Impossible travel",
|
|
20778
|
+
lockout: "Sign-in locked",
|
|
20779
|
+
"lockout.lifted": "Sign-in lock lifted",
|
|
20780
|
+
"session.limit": "Session limit reached",
|
|
20781
|
+
"password.changed": "Other sessions ended after a password change",
|
|
20782
|
+
"user.not_me": "User reported a sign-in as not theirs",
|
|
20783
|
+
test: "Test message"
|
|
20784
|
+
});
|
|
20785
|
+
var MAX_PARALLEL = 4;
|
|
20786
|
+
var MAX_QUEUE = 500;
|
|
20787
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
20788
|
+
const log = createLogger(strapi2);
|
|
20789
|
+
const queue = [];
|
|
20790
|
+
let running = 0;
|
|
20791
|
+
let stopped = false;
|
|
20792
|
+
const pump = () => {
|
|
20793
|
+
while (!stopped && running < MAX_PARALLEL && queue.length) {
|
|
20794
|
+
const job = (
|
|
20795
|
+
/** @type {() => Promise<void>} */
|
|
20796
|
+
queue.shift()
|
|
20797
|
+
);
|
|
20798
|
+
running += 1;
|
|
20799
|
+
job().catch(() => {
|
|
20800
|
+
}).finally(() => {
|
|
20801
|
+
running -= 1;
|
|
20802
|
+
pump();
|
|
20803
|
+
});
|
|
20804
|
+
}
|
|
20805
|
+
};
|
|
20806
|
+
const enqueue = (job) => {
|
|
20807
|
+
if (stopped) return;
|
|
20808
|
+
if (queue.length >= MAX_QUEUE) {
|
|
20809
|
+
queue.shift();
|
|
20810
|
+
log.warn("[webhooks] Queue full; the oldest delivery was dropped");
|
|
20811
|
+
}
|
|
20812
|
+
queue.push(job);
|
|
20813
|
+
pump();
|
|
20814
|
+
};
|
|
20815
|
+
const secretOf = (settings) => {
|
|
20816
|
+
const stored = settings?.genericWebhookSecret;
|
|
20817
|
+
if (typeof stored !== "string" || !stored) return null;
|
|
20818
|
+
try {
|
|
20819
|
+
return decryptToken(stored) || null;
|
|
20820
|
+
} catch {
|
|
20821
|
+
return null;
|
|
20822
|
+
}
|
|
20823
|
+
};
|
|
20824
|
+
const dataOf = (settings, input) => {
|
|
20825
|
+
const options = resolveSecurityLogSettings(settings);
|
|
20826
|
+
const ip = options.storeIp ? normalizeIp(input.ip || "") : null;
|
|
20827
|
+
return {
|
|
20828
|
+
user: input.userId ? { documentId: String(input.userId) } : null,
|
|
20829
|
+
ip: ip && options.anonymizeIp ? anonymizeIp(ip) : ip,
|
|
20830
|
+
userAgent: typeof input.userAgent === "string" ? input.userAgent.slice(0, 256) : null,
|
|
20831
|
+
location: input.geo && (input.geo.country_code || input.geo.city) ? { country: input.geo.country_code || null, city: input.geo.city || null } : null,
|
|
20832
|
+
details: input.details || null
|
|
20833
|
+
};
|
|
20834
|
+
};
|
|
20835
|
+
const chatBody = (kind, event, data) => {
|
|
20836
|
+
const title = CHAT_TITLES[event] || event;
|
|
20837
|
+
const fields = [
|
|
20838
|
+
["User", data.user?.documentId || "-"],
|
|
20839
|
+
["IP", data.ip || "-"],
|
|
20840
|
+
...Object.entries(data.details || {}).slice(0, 6).map(([key, value]) => [key, String(value)])
|
|
20841
|
+
];
|
|
20842
|
+
if (kind === "discord") {
|
|
20843
|
+
return {
|
|
20844
|
+
embeds: [
|
|
20845
|
+
{
|
|
20846
|
+
title,
|
|
20847
|
+
color: 5793266,
|
|
20848
|
+
fields: fields.map(([name, value]) => ({
|
|
20849
|
+
name,
|
|
20850
|
+
value: value.slice(0, 200),
|
|
20851
|
+
inline: true
|
|
20852
|
+
})),
|
|
20853
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
20854
|
+
footer: { text: "Magic Session Manager" }
|
|
20855
|
+
}
|
|
20856
|
+
]
|
|
20857
|
+
};
|
|
20858
|
+
}
|
|
20859
|
+
return {
|
|
20860
|
+
text: title,
|
|
20861
|
+
attachments: [
|
|
20862
|
+
{
|
|
20863
|
+
color: "#2563eb",
|
|
20864
|
+
blocks: [
|
|
20865
|
+
{ type: "header", text: { type: "plain_text", text: title } },
|
|
20866
|
+
{
|
|
20867
|
+
type: "section",
|
|
20868
|
+
fields: fields.map(([name, value]) => ({
|
|
20869
|
+
type: "mrkdwn",
|
|
20870
|
+
text: `*${name}*
|
|
20871
|
+
${value.slice(0, 200)}`
|
|
20872
|
+
}))
|
|
20873
|
+
}
|
|
20874
|
+
]
|
|
20875
|
+
}
|
|
20876
|
+
]
|
|
20877
|
+
};
|
|
20878
|
+
};
|
|
20879
|
+
const service = {
|
|
20880
|
+
EVENT_OF_SECURITY_EVENT,
|
|
20881
|
+
/**
|
|
20882
|
+
* Whether an event is selected.
|
|
20883
|
+
*
|
|
20884
|
+
* @param {Record<string, any>} settings Merged settings.
|
|
20885
|
+
* @param {string} event Webhook event.
|
|
20886
|
+
* @returns {boolean} True when selected.
|
|
20887
|
+
*/
|
|
20888
|
+
isSelected(settings, event) {
|
|
20889
|
+
return resolveDetectionSettings(settings).webhookEvents.includes(event);
|
|
20890
|
+
},
|
|
20891
|
+
/**
|
|
20892
|
+
* Queues an event for the signed webhook and, for non-sign-in events,
|
|
20893
|
+
* Discord and Slack. Sign-in events (`login.success`, `login.suspicious`,
|
|
20894
|
+
* `login.new_location`) reach Discord and Slack through the login alerts
|
|
20895
|
+
* with their richer message. Returns at once.
|
|
20896
|
+
*
|
|
20897
|
+
* @param {string} event Webhook event.
|
|
20898
|
+
* @param {{userId?: string|null, ip?: string|null, userAgent?: string|null, geo?: any,
|
|
20899
|
+
* details?: Record<string, unknown>|null}} input Event facts.
|
|
20900
|
+
* @param {{chat?: boolean}} [options] Whether Discord/Slack get it here.
|
|
20901
|
+
* @returns {void}
|
|
20902
|
+
*/
|
|
20903
|
+
emit(event, input, { chat = true } = {}) {
|
|
20904
|
+
enqueue(async () => {
|
|
20905
|
+
const settings = await getPluginSettings(strapi2);
|
|
20906
|
+
if (!service.isSelected(settings, event)) return;
|
|
20907
|
+
const data = dataOf(settings, input);
|
|
20908
|
+
const detection = resolveDetectionSettings(settings);
|
|
20909
|
+
const secret = secretOf(settings);
|
|
20910
|
+
if (detection.genericWebhookEnabled && detection.genericWebhookUrl && secret) {
|
|
20911
|
+
const request = buildSignedRequest({ event, data, secret });
|
|
20912
|
+
const result = await deliverWithRetries({ url: detection.genericWebhookUrl, ...request });
|
|
20913
|
+
if (!result.ok) {
|
|
20914
|
+
log.warn(
|
|
20915
|
+
`[webhooks] Signed webhook delivery failed (${result.code}, ${result.attempts} attempts)`
|
|
20916
|
+
);
|
|
20917
|
+
}
|
|
20918
|
+
}
|
|
20919
|
+
if (chat && settings.enableWebhooks) {
|
|
20920
|
+
const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
|
|
20921
|
+
const targets = [
|
|
20922
|
+
["discord", settings.discordWebhookUrl],
|
|
20923
|
+
["slack", settings.slackWebhookUrl]
|
|
20924
|
+
].filter(([, url]) => typeof url === "string" && url);
|
|
20925
|
+
await Promise.allSettled(
|
|
20926
|
+
targets.map(
|
|
20927
|
+
([kind, url]) => notifications.sendWebhook({
|
|
20928
|
+
event,
|
|
20929
|
+
data: chatBody(kind, event, data),
|
|
20930
|
+
webhookUrl: url
|
|
20931
|
+
})
|
|
20932
|
+
)
|
|
20933
|
+
);
|
|
20934
|
+
}
|
|
20935
|
+
});
|
|
20936
|
+
},
|
|
20937
|
+
/**
|
|
20938
|
+
* Emits the webhook event that belongs to a security log event, if any.
|
|
20939
|
+
*
|
|
20940
|
+
* @param {{event: string, actorType?: string, actorId?: any, targetId?: any, ip?: any,
|
|
20941
|
+
* userAgent?: any, meta?: any}} input Security event input.
|
|
20942
|
+
* @returns {void}
|
|
20943
|
+
*/
|
|
20944
|
+
emitSecurityEvent(input) {
|
|
20945
|
+
const event = EVENT_OF_SECURITY_EVENT[input?.event];
|
|
20946
|
+
if (!event) return;
|
|
20947
|
+
service.emit(event, {
|
|
20948
|
+
userId: input.targetId || (input.actorType === "user" ? input.actorId : null) || null,
|
|
20949
|
+
// An admin's own address is not sent for admin actions.
|
|
20950
|
+
ip: input.actorType === "admin" ? null : input.ip,
|
|
20951
|
+
userAgent: input.actorType === "admin" ? null : input.userAgent,
|
|
20952
|
+
details: input.meta || null
|
|
20953
|
+
});
|
|
20954
|
+
},
|
|
20955
|
+
/**
|
|
20956
|
+
* Sends one `test` event to the signed webhook now, without retries.
|
|
20957
|
+
*
|
|
20958
|
+
* @returns {Promise<{ok: boolean, status: number|null, code: string|null}>} Result.
|
|
20959
|
+
*/
|
|
20960
|
+
async sendTest() {
|
|
20961
|
+
const settings = await getPluginSettings(strapi2);
|
|
20962
|
+
const detection = resolveDetectionSettings(settings);
|
|
20963
|
+
const secret = secretOf(settings);
|
|
20964
|
+
if (!detection.genericWebhookUrl) return { ok: false, status: null, code: "no_url" };
|
|
20965
|
+
if (!secret) return { ok: false, status: null, code: "no_secret" };
|
|
20966
|
+
const request = buildSignedRequest({
|
|
20967
|
+
event: "test",
|
|
20968
|
+
data: { user: null, ip: null, userAgent: null, location: null, details: { test: true } },
|
|
20969
|
+
secret
|
|
20970
|
+
});
|
|
20971
|
+
try {
|
|
20972
|
+
const { status } = await deliverOnce({ url: detection.genericWebhookUrl, ...request });
|
|
20973
|
+
return { ok: true, status, code: null };
|
|
20974
|
+
} catch (err) {
|
|
20975
|
+
return {
|
|
20976
|
+
ok: false,
|
|
20977
|
+
status: Number.isInteger(err?.status) ? err.status : null,
|
|
20978
|
+
code: typeof err?.code === "string" ? err.code : "network_error"
|
|
20979
|
+
};
|
|
20980
|
+
}
|
|
20981
|
+
},
|
|
20982
|
+
/**
|
|
20983
|
+
* Stops new deliveries (plugin destroy).
|
|
20984
|
+
*
|
|
20985
|
+
* @returns {void}
|
|
20986
|
+
*/
|
|
20987
|
+
stop() {
|
|
20988
|
+
stopped = true;
|
|
20989
|
+
queue.length = 0;
|
|
20990
|
+
}
|
|
20991
|
+
};
|
|
20992
|
+
return service;
|
|
20993
|
+
};
|
|
20994
|
+
}
|
|
20995
|
+
});
|
|
20996
|
+
|
|
19306
20997
|
// server/src/services/index.js
|
|
19307
20998
|
var require_services = __commonJS({
|
|
19308
20999
|
"server/src/services/index.js"(exports2, module2) {
|
|
@@ -19311,11 +21002,13 @@ var require_services = __commonJS({
|
|
|
19311
21002
|
var geolocation = require_geolocation();
|
|
19312
21003
|
var notifications = require_notifications();
|
|
19313
21004
|
var securityLog = require_security_log();
|
|
21005
|
+
var webhooks = require_webhooks2();
|
|
19314
21006
|
module2.exports = {
|
|
19315
21007
|
session,
|
|
19316
21008
|
geolocation,
|
|
19317
21009
|
notifications,
|
|
19318
|
-
"security-log": securityLog
|
|
21010
|
+
"security-log": securityLog,
|
|
21011
|
+
webhooks
|
|
19319
21012
|
};
|
|
19320
21013
|
}
|
|
19321
21014
|
});
|