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