strapi-plugin-magic-sessionmanager 4.16.1 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +76 -0
- package/README.md +119 -25
- package/dist/admin/{Analytics-CMR62DiD.js → Analytics-C8fV6LDV.js} +1 -1
- package/dist/admin/{Analytics-FcRt0X62.mjs → Analytics-CBspdl1I.mjs} +1 -1
- package/dist/admin/{App-CmytGbze.js → App-D92MTQmn.js} +33 -170
- package/dist/admin/{App-DBieSWB0.mjs → App-PLwqaRSQ.mjs} +3 -140
- package/dist/admin/{OnlineUsersWidget-Lzx9XB74.js → OnlineUsersWidget-CiKapC1B.js} +1 -1
- package/dist/admin/{OnlineUsersWidget-zP9Hl_it.mjs → OnlineUsersWidget-CwfBJdIX.mjs} +1 -1
- package/dist/admin/{Settings-CZOPusQK.mjs → Settings-CMgL-Aub.mjs} +2013 -78
- package/dist/admin/{Settings-1v--SXC0.js → Settings-Duil_4jv.js} +2017 -82
- package/dist/admin/dashboardModel-BhUonEqc.mjs +189 -0
- package/dist/admin/dashboardModel-sksvIc1c.js +188 -0
- package/dist/admin/{de-y_9mdVT7.js → de-CnInuvMY.js} +196 -11
- package/dist/admin/{de-D3TSA066.mjs → de-D2BqfY1f.mjs} +196 -11
- package/dist/admin/{en-B60I97bK.mjs → en-BPy208we.mjs} +196 -11
- package/dist/admin/{en-CIQB8nfI.js → en-KnmmYHTF.js} +196 -11
- package/dist/admin/{es-CJEL_iGC.mjs → es-B4VNeT0A.mjs} +196 -11
- package/dist/admin/{es-DHhHzlRY.js → es-D1NGCAJK.js} +196 -11
- package/dist/admin/{fr-BfBK_iuV.mjs → fr-AwhLN1BC.mjs} +196 -11
- package/dist/admin/{fr-D86FTt1w.js → fr-D1KNyogi.js} +196 -11
- package/dist/admin/{index-tt61o2VH.mjs → index-BmnC2BPs.mjs} +40 -38
- package/dist/admin/{index-CSJJn4qy.js → index-Bnt0Jq6O.js} +12 -10
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/{pt-C3PSvC7z.mjs → pt-D6m1TijL.mjs} +196 -11
- package/dist/admin/{pt-BE-FT-L8.js → pt-EKThRXPY.js} +196 -11
- package/dist/server/index.js +3230 -129
- package/dist/server/index.mjs +3230 -129
- package/package.json +1 -1
- package/dist/admin/riskData-BVs9GpgD.js +0 -26
- package/dist/admin/riskData-CI1gm2yI.mjs +0 -27
package/dist/server/index.js
CHANGED
|
@@ -126,6 +126,11 @@ var require_coordination = __commonJS({
|
|
|
126
126
|
throw new TypeError("coordination key must be a non-empty string of at most 191 characters");
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
|
+
function assertRegistryKey(key) {
|
|
130
|
+
if (typeof key !== "string" || !/^[a-z0-9:-]{1,180}$/.test(key)) {
|
|
131
|
+
throw new TypeError('registry key must be 1-180 lowercase letters, digits, ":" or "-"');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
129
134
|
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
130
135
|
var LockTimeoutError = class extends Error {
|
|
131
136
|
constructor(name) {
|
|
@@ -138,6 +143,7 @@ var require_coordination = __commonJS({
|
|
|
138
143
|
const leases = /* @__PURE__ */ new Map();
|
|
139
144
|
const revisions = /* @__PURE__ */ new Map();
|
|
140
145
|
const lockTails = /* @__PURE__ */ new Map();
|
|
146
|
+
const registry = /* @__PURE__ */ new Map();
|
|
141
147
|
const pruneCounters = (now) => {
|
|
142
148
|
if (counters.size < 5e3) return;
|
|
143
149
|
for (const [k, v] of counters) {
|
|
@@ -167,13 +173,14 @@ var require_coordination = __commonJS({
|
|
|
167
173
|
if (!entry) return null;
|
|
168
174
|
return { hits: entry.hits, windowStart: entry.windowStart, blockedUntil: entry.blockedUntil };
|
|
169
175
|
},
|
|
170
|
-
async block(key, untilMs) {
|
|
176
|
+
async block(key, untilMs, { windowStart } = {}) {
|
|
171
177
|
const entry = counters.get(key) || {
|
|
172
178
|
hits: 0,
|
|
173
179
|
windowStart: 0,
|
|
174
180
|
blockedUntil: 0,
|
|
175
181
|
expiresAt: 0
|
|
176
182
|
};
|
|
183
|
+
if (Number.isFinite(windowStart)) entry.windowStart = windowStart;
|
|
177
184
|
if (entry.blockedUntil < untilMs) entry.blockedUntil = untilMs;
|
|
178
185
|
entry.expiresAt = Math.max(entry.expiresAt, untilMs);
|
|
179
186
|
counters.set(key, entry);
|
|
@@ -228,8 +235,33 @@ var require_coordination = __commonJS({
|
|
|
228
235
|
},
|
|
229
236
|
async cacheSet() {
|
|
230
237
|
},
|
|
238
|
+
async registryPut(key, value, ttlMs, now = Date.now()) {
|
|
239
|
+
registry.set(key, { value, expiresAt: now + ttlMs });
|
|
240
|
+
},
|
|
241
|
+
async registryList(prefix, limit = 200, now = Date.now()) {
|
|
242
|
+
const out = [];
|
|
243
|
+
for (const [key, entry] of registry) {
|
|
244
|
+
if (entry.expiresAt <= now) {
|
|
245
|
+
registry.delete(key);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (key.startsWith(prefix) && out.length < limit) out.push({ key, value: entry.value });
|
|
249
|
+
}
|
|
250
|
+
return out;
|
|
251
|
+
},
|
|
252
|
+
async registryDelete(key) {
|
|
253
|
+
registry.delete(key);
|
|
254
|
+
},
|
|
255
|
+
async registryTake(key, now = Date.now()) {
|
|
256
|
+
const entry = registry.get(key);
|
|
257
|
+
registry.delete(key);
|
|
258
|
+
return entry && entry.expiresAt > now ? entry.value : null;
|
|
259
|
+
},
|
|
231
260
|
async prune(now = Date.now()) {
|
|
232
261
|
let removed = 0;
|
|
262
|
+
for (const [k, v] of registry) {
|
|
263
|
+
if (v.expiresAt <= now) registry.delete(k);
|
|
264
|
+
}
|
|
233
265
|
for (const [k, v] of counters) {
|
|
234
266
|
if (v.expiresAt <= now && v.blockedUntil <= now) {
|
|
235
267
|
counters.delete(k);
|
|
@@ -243,6 +275,7 @@ var require_coordination = __commonJS({
|
|
|
243
275
|
leases.clear();
|
|
244
276
|
revisions.clear();
|
|
245
277
|
lockTails.clear();
|
|
278
|
+
registry.clear();
|
|
246
279
|
}
|
|
247
280
|
};
|
|
248
281
|
}
|
|
@@ -384,14 +417,18 @@ var require_coordination = __commonJS({
|
|
|
384
417
|
await knex(TABLES.counters).where({ k: key }).andWhere("hits", ">", 0).update({ hits: knex.raw("hits - 1") });
|
|
385
418
|
},
|
|
386
419
|
peek: readCounter,
|
|
387
|
-
async block(key, untilMs) {
|
|
420
|
+
async block(key, untilMs, { windowStart } = {}) {
|
|
388
421
|
await ensureCounterRow(key, untilMs);
|
|
389
422
|
await knex(TABLES.counters).where({ k: key }).andWhere("blocked_until", "<", untilMs).update({
|
|
390
423
|
blocked_until: untilMs,
|
|
391
424
|
expires_at: knex.raw("CASE WHEN expires_at < ? THEN ? ELSE expires_at END", [
|
|
392
425
|
untilMs,
|
|
393
426
|
untilMs
|
|
394
|
-
])
|
|
427
|
+
]),
|
|
428
|
+
// Moves the counting window so it ends when the lock ends: the
|
|
429
|
+
// hits stay (requests already in flight are still turned away),
|
|
430
|
+
// and the first attempt after the lock starts a new window.
|
|
431
|
+
...Number.isFinite(windowStart) ? { window_start: Math.trunc(windowStart) } : {}
|
|
395
432
|
});
|
|
396
433
|
},
|
|
397
434
|
async clear(key) {
|
|
@@ -469,6 +506,42 @@ var require_coordination = __commonJS({
|
|
|
469
506
|
const expiresAt = ttlMs === Infinity ? NEVER_EXPIRES : now + ttlMs;
|
|
470
507
|
await knex(TABLES.cache).insert({ k: key, v: JSON.stringify(value), expires_at: expiresAt }).onConflict("k").merge(["v", "expires_at"]);
|
|
471
508
|
},
|
|
509
|
+
/**
|
|
510
|
+
* Listable entries live in the cache table under their own key prefix
|
|
511
|
+
* (`reg:`), so they share its expiry index and pruning.
|
|
512
|
+
*/
|
|
513
|
+
async registryPut(key, value, ttlMs, now = Date.now()) {
|
|
514
|
+
await knex(TABLES.cache).insert({ k: `reg:${key}`, v: JSON.stringify(value), expires_at: now + ttlMs }).onConflict("k").merge(["v", "expires_at"]);
|
|
515
|
+
},
|
|
516
|
+
async registryList(prefix, limit = 200, now = Date.now()) {
|
|
517
|
+
const rows = await knex(TABLES.cache).select("k", "v").where("k", "like", `reg:${prefix}%`).andWhere("expires_at", ">", now).orderBy("k", "asc").limit(limit);
|
|
518
|
+
const out = [];
|
|
519
|
+
for (const row of rows) {
|
|
520
|
+
try {
|
|
521
|
+
out.push({ key: String(row.k).slice(4), value: JSON.parse(row.v) });
|
|
522
|
+
} catch {
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return out;
|
|
526
|
+
},
|
|
527
|
+
async registryDelete(key) {
|
|
528
|
+
await knex(TABLES.cache).where({ k: `reg:${key}` }).del();
|
|
529
|
+
},
|
|
530
|
+
/**
|
|
531
|
+
* Reads and deletes an entry. Only the caller whose DELETE removed the
|
|
532
|
+
* row gets the value, so parallel takes of one key yield it once.
|
|
533
|
+
*/
|
|
534
|
+
async registryTake(key, now = Date.now()) {
|
|
535
|
+
const row = await knex(TABLES.cache).select("v", "expires_at").where({ k: `reg:${key}` }).first();
|
|
536
|
+
if (!row) return null;
|
|
537
|
+
const deleted = await knex(TABLES.cache).where({ k: `reg:${key}`, expires_at: row.expires_at }).del();
|
|
538
|
+
if (toNumber(deleted) !== 1 || toNumber(row.expires_at) <= now) return null;
|
|
539
|
+
try {
|
|
540
|
+
return JSON.parse(row.v);
|
|
541
|
+
} catch {
|
|
542
|
+
return null;
|
|
543
|
+
}
|
|
544
|
+
},
|
|
472
545
|
async prune(now = Date.now()) {
|
|
473
546
|
const counters = await knex(TABLES.counters).where("expires_at", "<", now).andWhere("blocked_until", "<", now).del();
|
|
474
547
|
const cache = await knex(TABLES.cache).where("expires_at", "<", now).del();
|
|
@@ -549,10 +622,17 @@ var require_coordination = __commonJS({
|
|
|
549
622
|
assertKey(key);
|
|
550
623
|
return counterCall("counter read", "peek", [key]);
|
|
551
624
|
},
|
|
552
|
-
/**
|
|
553
|
-
|
|
625
|
+
/**
|
|
626
|
+
* Raises the block deadline of `key` to `untilMs` (never lowers it).
|
|
627
|
+
* With `windowStart` the counting window is moved (see the lockout).
|
|
628
|
+
*/
|
|
629
|
+
block(key, untilMs, options) {
|
|
554
630
|
assertKey(key);
|
|
555
|
-
return counterCall(
|
|
631
|
+
return counterCall(
|
|
632
|
+
"counter block",
|
|
633
|
+
"block",
|
|
634
|
+
options ? [key, untilMs, options] : [key, untilMs]
|
|
635
|
+
);
|
|
556
636
|
},
|
|
557
637
|
/** Removes counter `key`. */
|
|
558
638
|
clear(key) {
|
|
@@ -652,6 +732,66 @@ var require_coordination = __commonJS({
|
|
|
652
732
|
() => sharedMemory.cacheSet(key, value, ttlMs)
|
|
653
733
|
);
|
|
654
734
|
},
|
|
735
|
+
/**
|
|
736
|
+
* Stores a listable entry (for example an active sign-in lock) until
|
|
737
|
+
* `ttlMs` from now. Unlike the cache it also works in memory mode, and
|
|
738
|
+
* entries can be listed by key prefix. Keys use lowercase letters,
|
|
739
|
+
* digits, `:` and `-` only, so they are free of LIKE wildcards.
|
|
740
|
+
*
|
|
741
|
+
* @param {string} key Entry key (at most 180 characters).
|
|
742
|
+
* @param {unknown} value JSON-serialisable value.
|
|
743
|
+
* @param {number} ttlMs Lifetime in milliseconds.
|
|
744
|
+
* @returns {Promise<void>}
|
|
745
|
+
*/
|
|
746
|
+
registryPut(key, value, ttlMs) {
|
|
747
|
+
assertRegistryKey(key);
|
|
748
|
+
return run(
|
|
749
|
+
"registry write",
|
|
750
|
+
(backend) => backend.registryPut(key, value, ttlMs),
|
|
751
|
+
() => sharedMemory.registryPut(key, value, ttlMs)
|
|
752
|
+
);
|
|
753
|
+
},
|
|
754
|
+
/**
|
|
755
|
+
* Unexpired entries whose key starts with `prefix`, ordered by key.
|
|
756
|
+
*
|
|
757
|
+
* @param {string} prefix Key prefix (letters, digits, `:` and `-` only).
|
|
758
|
+
* @param {number} [limit] Most entries returned.
|
|
759
|
+
* @returns {Promise<Array<{key: string, value: any}>>}
|
|
760
|
+
*/
|
|
761
|
+
registryList(prefix, limit = 200) {
|
|
762
|
+
if (typeof prefix !== "string" || !/^[a-z0-9:-]{1,180}$/.test(prefix)) {
|
|
763
|
+
throw new TypeError('registry prefix must be letters, digits, ":" or "-"');
|
|
764
|
+
}
|
|
765
|
+
return run(
|
|
766
|
+
"registry read",
|
|
767
|
+
(backend) => backend.registryList(prefix, limit),
|
|
768
|
+
() => sharedMemory.registryList(prefix, limit)
|
|
769
|
+
);
|
|
770
|
+
},
|
|
771
|
+
/**
|
|
772
|
+
* Takes a listable entry once: returns its value and removes it. Of
|
|
773
|
+
* several concurrent takes (any process) at most one gets the value.
|
|
774
|
+
*
|
|
775
|
+
* @param {string} key Entry key.
|
|
776
|
+
* @returns {Promise<any|null>} Value, or null when absent, expired or taken.
|
|
777
|
+
*/
|
|
778
|
+
registryTake(key) {
|
|
779
|
+
assertRegistryKey(key);
|
|
780
|
+
return run(
|
|
781
|
+
"registry take",
|
|
782
|
+
(backend) => backend.registryTake(key),
|
|
783
|
+
() => sharedMemory.registryTake(key)
|
|
784
|
+
);
|
|
785
|
+
},
|
|
786
|
+
/** Removes a listable entry. */
|
|
787
|
+
registryDelete(key) {
|
|
788
|
+
assertRegistryKey(key);
|
|
789
|
+
return run(
|
|
790
|
+
"registry delete",
|
|
791
|
+
(backend) => backend.registryDelete(key),
|
|
792
|
+
() => sharedMemory.registryDelete(key)
|
|
793
|
+
);
|
|
794
|
+
},
|
|
655
795
|
prune() {
|
|
656
796
|
return run(
|
|
657
797
|
"prune",
|
|
@@ -805,7 +945,7 @@ var require_content_api_permissions = __commonJS({
|
|
|
805
945
|
"server/src/utils/content-api-permissions.js"(exports2, module2) {
|
|
806
946
|
"use strict";
|
|
807
947
|
var { withPluginStoreKey } = require_plugin_store();
|
|
808
|
-
var CONTENT_API_PERMISSIONS_VERSION =
|
|
948
|
+
var CONTENT_API_PERMISSIONS_VERSION = 3;
|
|
809
949
|
var CONTENT_API_PERMISSIONS_VERSION_KEY = "contentApiPermissionsVersion";
|
|
810
950
|
var AUTHENTICATED_ROLE_UID = "plugin::users-permissions.role";
|
|
811
951
|
async function preserveAuthenticatedRolePermissionChoice(strapi2, role) {
|
|
@@ -984,11 +1124,575 @@ var require_security_log_settings = __commonJS({
|
|
|
984
1124
|
}
|
|
985
1125
|
});
|
|
986
1126
|
|
|
1127
|
+
// server/src/utils/policy-settings.js
|
|
1128
|
+
var require_policy_settings = __commonJS({
|
|
1129
|
+
"server/src/utils/policy-settings.js"(exports2, module2) {
|
|
1130
|
+
"use strict";
|
|
1131
|
+
var net = require("node:net");
|
|
1132
|
+
var POLICY_DEFAULTS = Object.freeze({
|
|
1133
|
+
maxFailedLoginsPerAccount: 0,
|
|
1134
|
+
lockoutWindowMinutes: 15,
|
|
1135
|
+
lockoutDurationMinutes: 15,
|
|
1136
|
+
lockoutTrustedAddresses: Object.freeze([]),
|
|
1137
|
+
lockoutNotifyUser: false,
|
|
1138
|
+
recordUserSignInEvents: true,
|
|
1139
|
+
maxSessionsPerUser: 0,
|
|
1140
|
+
sessionLimitPolicy: "end-oldest",
|
|
1141
|
+
endOtherSessionsOnPasswordChange: true,
|
|
1142
|
+
roleRules: Object.freeze([])
|
|
1143
|
+
});
|
|
1144
|
+
var POLICY_KEYS = Object.freeze(Object.keys(POLICY_DEFAULTS));
|
|
1145
|
+
var POLICY_RANGES = Object.freeze({
|
|
1146
|
+
maxFailedLoginsPerAccount: Object.freeze([0, 100]),
|
|
1147
|
+
lockoutWindowMinutes: Object.freeze([1, 1440]),
|
|
1148
|
+
lockoutDurationMinutes: Object.freeze([1, 10080]),
|
|
1149
|
+
maxSessionsPerUser: Object.freeze([0, 100])
|
|
1150
|
+
});
|
|
1151
|
+
var ROLE_RULE_RANGES = Object.freeze({
|
|
1152
|
+
maxSessionsPerUser: Object.freeze([0, 100]),
|
|
1153
|
+
inactivityTimeout: Object.freeze([1, 1440]),
|
|
1154
|
+
maxFailedLoginsPerAccount: Object.freeze([0, 100])
|
|
1155
|
+
});
|
|
1156
|
+
var ROLE_RULE_FIELDS = Object.freeze(Object.keys(ROLE_RULE_RANGES));
|
|
1157
|
+
var SESSION_LIMIT_POLICIES = Object.freeze(["end-oldest", "refuse"]);
|
|
1158
|
+
var BOOLEAN_KEYS = Object.freeze([
|
|
1159
|
+
"lockoutNotifyUser",
|
|
1160
|
+
"recordUserSignInEvents",
|
|
1161
|
+
"endOtherSessionsOnPasswordChange"
|
|
1162
|
+
]);
|
|
1163
|
+
var MAX_TRUSTED_ADDRESSES = 100;
|
|
1164
|
+
var MAX_ROLE_RULES = 50;
|
|
1165
|
+
var ROLE_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
|
|
1166
|
+
function parseInteger(value) {
|
|
1167
|
+
if (typeof value === "number") return Number.isInteger(value) ? value : null;
|
|
1168
|
+
if (typeof value === "string" && /^\s*-?\d{1,9}\s*$/.test(value)) {
|
|
1169
|
+
return Number.parseInt(value, 10);
|
|
1170
|
+
}
|
|
1171
|
+
return null;
|
|
1172
|
+
}
|
|
1173
|
+
function parseTrustedAddress(value) {
|
|
1174
|
+
if (typeof value !== "string") return null;
|
|
1175
|
+
const text = value.trim();
|
|
1176
|
+
if (!text || text.length > 64) return null;
|
|
1177
|
+
const [rawAddress, rawPrefix, extra] = text.split("/");
|
|
1178
|
+
if (extra !== void 0) return null;
|
|
1179
|
+
let address = rawAddress;
|
|
1180
|
+
if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
|
|
1181
|
+
address = address.slice(7);
|
|
1182
|
+
}
|
|
1183
|
+
const version = net.isIP(address);
|
|
1184
|
+
if (version === 0) return null;
|
|
1185
|
+
const family = version === 4 ? "ipv4" : "ipv6";
|
|
1186
|
+
if (rawPrefix === void 0) {
|
|
1187
|
+
return { text: address.toLowerCase(), address, prefix: null, family };
|
|
1188
|
+
}
|
|
1189
|
+
if (!/^\d{1,3}$/.test(rawPrefix)) return null;
|
|
1190
|
+
const prefix = Number(rawPrefix);
|
|
1191
|
+
if (prefix > (family === "ipv4" ? 32 : 128)) return null;
|
|
1192
|
+
return { text: `${address.toLowerCase()}/${prefix}`, address, prefix, family };
|
|
1193
|
+
}
|
|
1194
|
+
var blockListCache = /* @__PURE__ */ new Map();
|
|
1195
|
+
function trustedAddressList(entries) {
|
|
1196
|
+
const key = entries.join("\n");
|
|
1197
|
+
const cached = blockListCache.get(key);
|
|
1198
|
+
if (cached) return cached;
|
|
1199
|
+
const list = new net.BlockList();
|
|
1200
|
+
for (const entry of entries) {
|
|
1201
|
+
const parsed = parseTrustedAddress(entry);
|
|
1202
|
+
if (!parsed) continue;
|
|
1203
|
+
if (parsed.prefix === null) list.addAddress(parsed.address, parsed.family);
|
|
1204
|
+
else list.addSubnet(parsed.address, parsed.prefix, parsed.family);
|
|
1205
|
+
}
|
|
1206
|
+
if (blockListCache.size > 20) blockListCache.clear();
|
|
1207
|
+
blockListCache.set(key, list);
|
|
1208
|
+
return list;
|
|
1209
|
+
}
|
|
1210
|
+
function isTrustedAddress(entries, ip) {
|
|
1211
|
+
if (!entries.length || typeof ip !== "string") return false;
|
|
1212
|
+
let address = ip.trim();
|
|
1213
|
+
if (address.toLowerCase().startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
|
|
1214
|
+
address = address.slice(7);
|
|
1215
|
+
}
|
|
1216
|
+
const version = net.isIP(address);
|
|
1217
|
+
if (version === 0) return false;
|
|
1218
|
+
try {
|
|
1219
|
+
return trustedAddressList(entries).check(address, version === 4 ? "ipv4" : "ipv6");
|
|
1220
|
+
} catch {
|
|
1221
|
+
return false;
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
function normalizeRoleRules(value) {
|
|
1225
|
+
if (!Array.isArray(value)) return [];
|
|
1226
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1227
|
+
const out = [];
|
|
1228
|
+
for (const raw of value.slice(0, MAX_ROLE_RULES)) {
|
|
1229
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
|
|
1230
|
+
const role = typeof raw.role === "string" ? raw.role : "";
|
|
1231
|
+
if (!ROLE_ID_PATTERN.test(role) || seen.has(role)) continue;
|
|
1232
|
+
const rule = { role };
|
|
1233
|
+
for (const field of ROLE_RULE_FIELDS) {
|
|
1234
|
+
const [min, max] = (
|
|
1235
|
+
/** @type {any} */
|
|
1236
|
+
ROLE_RULE_RANGES[field]
|
|
1237
|
+
);
|
|
1238
|
+
const number = raw[field] === null || raw[field] === void 0 ? null : parseInteger(raw[field]);
|
|
1239
|
+
rule[field] = number !== null && number >= min && number <= max ? number : null;
|
|
1240
|
+
}
|
|
1241
|
+
seen.add(role);
|
|
1242
|
+
out.push(rule);
|
|
1243
|
+
}
|
|
1244
|
+
return out;
|
|
1245
|
+
}
|
|
1246
|
+
function normalizePolicySettings(stored) {
|
|
1247
|
+
const out = {};
|
|
1248
|
+
if (!stored || typeof stored !== "object") return out;
|
|
1249
|
+
for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
|
|
1250
|
+
if (stored[key] === void 0) continue;
|
|
1251
|
+
const number = parseInteger(stored[key]);
|
|
1252
|
+
out[key] = number !== null && number >= min && number <= max ? number : (
|
|
1253
|
+
/** @type {any} */
|
|
1254
|
+
POLICY_DEFAULTS[key]
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
for (const key of BOOLEAN_KEYS) {
|
|
1258
|
+
if (stored[key] !== void 0) out[key] = stored[key] === true;
|
|
1259
|
+
}
|
|
1260
|
+
if (stored.sessionLimitPolicy !== void 0) {
|
|
1261
|
+
out.sessionLimitPolicy = SESSION_LIMIT_POLICIES.includes(
|
|
1262
|
+
/** @type {string} */
|
|
1263
|
+
stored.sessionLimitPolicy
|
|
1264
|
+
) ? stored.sessionLimitPolicy : POLICY_DEFAULTS.sessionLimitPolicy;
|
|
1265
|
+
}
|
|
1266
|
+
if (stored.lockoutTrustedAddresses !== void 0) {
|
|
1267
|
+
out.lockoutTrustedAddresses = Array.isArray(stored.lockoutTrustedAddresses) ? stored.lockoutTrustedAddresses.slice(0, MAX_TRUSTED_ADDRESSES).map(parseTrustedAddress).filter(Boolean).map((entry) => (
|
|
1268
|
+
/** @type {any} */
|
|
1269
|
+
entry.text
|
|
1270
|
+
)) : [];
|
|
1271
|
+
}
|
|
1272
|
+
if (stored.roleRules !== void 0) out.roleRules = normalizeRoleRules(stored.roleRules);
|
|
1273
|
+
return out;
|
|
1274
|
+
}
|
|
1275
|
+
function validatePolicySettings(body) {
|
|
1276
|
+
const values = {};
|
|
1277
|
+
const errors = [];
|
|
1278
|
+
const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
|
|
1279
|
+
for (const [key, [min, max]] of Object.entries(POLICY_RANGES)) {
|
|
1280
|
+
if (!has(key)) continue;
|
|
1281
|
+
const number = parseInteger(body[key]);
|
|
1282
|
+
if (number === null || number < min || number > max) {
|
|
1283
|
+
errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
|
|
1284
|
+
} else {
|
|
1285
|
+
values[key] = number;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
for (const key of BOOLEAN_KEYS) {
|
|
1289
|
+
if (!has(key)) continue;
|
|
1290
|
+
if (typeof body[key] !== "boolean") {
|
|
1291
|
+
errors.push({ path: [key], message: `${key} must be a boolean` });
|
|
1292
|
+
} else {
|
|
1293
|
+
values[key] = body[key];
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
if (has("sessionLimitPolicy")) {
|
|
1297
|
+
if (!SESSION_LIMIT_POLICIES.includes(
|
|
1298
|
+
/** @type {string} */
|
|
1299
|
+
body.sessionLimitPolicy
|
|
1300
|
+
)) {
|
|
1301
|
+
errors.push({
|
|
1302
|
+
path: ["sessionLimitPolicy"],
|
|
1303
|
+
message: `sessionLimitPolicy must be one of: ${SESSION_LIMIT_POLICIES.join(", ")}`
|
|
1304
|
+
});
|
|
1305
|
+
} else {
|
|
1306
|
+
values.sessionLimitPolicy = body.sessionLimitPolicy;
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
if (has("lockoutTrustedAddresses")) {
|
|
1310
|
+
const list = body.lockoutTrustedAddresses;
|
|
1311
|
+
if (!Array.isArray(list) || list.length > MAX_TRUSTED_ADDRESSES) {
|
|
1312
|
+
errors.push({
|
|
1313
|
+
path: ["lockoutTrustedAddresses"],
|
|
1314
|
+
message: `lockoutTrustedAddresses must be a list of at most ${MAX_TRUSTED_ADDRESSES} IP addresses or CIDR ranges`
|
|
1315
|
+
});
|
|
1316
|
+
} else {
|
|
1317
|
+
const parsed = list.map(parseTrustedAddress);
|
|
1318
|
+
const invalid = parsed.findIndex((entry) => entry === null);
|
|
1319
|
+
if (invalid !== -1) {
|
|
1320
|
+
errors.push({
|
|
1321
|
+
path: ["lockoutTrustedAddresses", invalid],
|
|
1322
|
+
message: "Each trusted address must be an IP address or a CIDR range such as 192.0.2.0/24"
|
|
1323
|
+
});
|
|
1324
|
+
} else {
|
|
1325
|
+
values.lockoutTrustedAddresses = [
|
|
1326
|
+
...new Set(parsed.map((entry) => (
|
|
1327
|
+
/** @type {any} */
|
|
1328
|
+
entry.text
|
|
1329
|
+
)))
|
|
1330
|
+
];
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
if (has("roleRules")) {
|
|
1335
|
+
const rules = body.roleRules;
|
|
1336
|
+
if (!Array.isArray(rules) || rules.length > MAX_ROLE_RULES) {
|
|
1337
|
+
errors.push({
|
|
1338
|
+
path: ["roleRules"],
|
|
1339
|
+
message: `roleRules must be a list of at most ${MAX_ROLE_RULES} rules`
|
|
1340
|
+
});
|
|
1341
|
+
} else {
|
|
1342
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1343
|
+
const clean = [];
|
|
1344
|
+
rules.forEach((raw, index) => {
|
|
1345
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
1346
|
+
errors.push({ path: ["roleRules", index], message: "A role rule must be an object" });
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
const role = raw.role;
|
|
1350
|
+
if (typeof role !== "string" || !ROLE_ID_PATTERN.test(role)) {
|
|
1351
|
+
errors.push({ path: ["roleRules", index, "role"], message: "Choose a role" });
|
|
1352
|
+
return;
|
|
1353
|
+
}
|
|
1354
|
+
if (seen.has(role)) {
|
|
1355
|
+
errors.push({
|
|
1356
|
+
path: ["roleRules", index, "role"],
|
|
1357
|
+
message: "This role already has a rule"
|
|
1358
|
+
});
|
|
1359
|
+
return;
|
|
1360
|
+
}
|
|
1361
|
+
seen.add(role);
|
|
1362
|
+
const rule = { role };
|
|
1363
|
+
let overrides = 0;
|
|
1364
|
+
for (const field of ROLE_RULE_FIELDS) {
|
|
1365
|
+
const [min, max] = (
|
|
1366
|
+
/** @type {any} */
|
|
1367
|
+
ROLE_RULE_RANGES[field]
|
|
1368
|
+
);
|
|
1369
|
+
const rawValue = raw[field];
|
|
1370
|
+
if (rawValue === null || rawValue === void 0 || rawValue === "") {
|
|
1371
|
+
rule[field] = null;
|
|
1372
|
+
continue;
|
|
1373
|
+
}
|
|
1374
|
+
const number = parseInteger(rawValue);
|
|
1375
|
+
if (number === null || number < min || number > max) {
|
|
1376
|
+
errors.push({
|
|
1377
|
+
path: ["roleRules", index, field],
|
|
1378
|
+
message: `${field} must be empty or an integer between ${min} and ${max}`
|
|
1379
|
+
});
|
|
1380
|
+
continue;
|
|
1381
|
+
}
|
|
1382
|
+
rule[field] = number;
|
|
1383
|
+
overrides += 1;
|
|
1384
|
+
}
|
|
1385
|
+
if (overrides === 0 && !errors.some((e) => e.path[1] === index)) {
|
|
1386
|
+
errors.push({
|
|
1387
|
+
path: ["roleRules", index],
|
|
1388
|
+
message: "A role rule needs at least one value"
|
|
1389
|
+
});
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
clean.push(rule);
|
|
1393
|
+
});
|
|
1394
|
+
if (!errors.some((e) => e.path[0] === "roleRules")) values.roleRules = clean;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
return { values, errors };
|
|
1398
|
+
}
|
|
1399
|
+
function policyValue(settings, key) {
|
|
1400
|
+
const source = settings && typeof settings === "object" ? settings : {};
|
|
1401
|
+
const clean = normalizePolicySettings({ [key]: source[key] });
|
|
1402
|
+
return clean[key] !== void 0 ? clean[key] : POLICY_DEFAULTS[key];
|
|
1403
|
+
}
|
|
1404
|
+
function roleRuleFor(settings, roleDocumentId) {
|
|
1405
|
+
if (!roleDocumentId) return null;
|
|
1406
|
+
const rules = (
|
|
1407
|
+
/** @type {any[]} */
|
|
1408
|
+
policyValue(settings, "roleRules")
|
|
1409
|
+
);
|
|
1410
|
+
return rules.find((rule) => rule.role === roleDocumentId) || null;
|
|
1411
|
+
}
|
|
1412
|
+
function hasRoleOverride(settings, field) {
|
|
1413
|
+
const rules = (
|
|
1414
|
+
/** @type {any[]} */
|
|
1415
|
+
policyValue(settings, "roleRules")
|
|
1416
|
+
);
|
|
1417
|
+
return rules.some((rule) => rule[field] !== null && rule[field] !== void 0);
|
|
1418
|
+
}
|
|
1419
|
+
function resolveLockoutPolicy(settings) {
|
|
1420
|
+
const source = settings && typeof settings === "object" ? settings : {};
|
|
1421
|
+
const ipRaw = parseInteger(source.maxFailedLogins);
|
|
1422
|
+
return {
|
|
1423
|
+
ipMax: ipRaw !== null && ipRaw >= 0 && ipRaw <= 100 ? ipRaw : 0,
|
|
1424
|
+
accountMax: policyValue(source, "maxFailedLoginsPerAccount"),
|
|
1425
|
+
accountMaxByRole: hasRoleOverride(source, "maxFailedLoginsPerAccount"),
|
|
1426
|
+
windowMs: policyValue(source, "lockoutWindowMinutes") * 60 * 1e3,
|
|
1427
|
+
durationMs: policyValue(source, "lockoutDurationMinutes") * 60 * 1e3,
|
|
1428
|
+
trusted: policyValue(source, "lockoutTrustedAddresses"),
|
|
1429
|
+
notifyUser: policyValue(source, "lockoutNotifyUser"),
|
|
1430
|
+
record: policyValue(source, "recordUserSignInEvents")
|
|
1431
|
+
};
|
|
1432
|
+
}
|
|
1433
|
+
function accountThresholdFor(settings, roleDocumentId) {
|
|
1434
|
+
const rule = roleRuleFor(settings, roleDocumentId);
|
|
1435
|
+
if (rule && rule.maxFailedLoginsPerAccount !== null) return rule.maxFailedLoginsPerAccount;
|
|
1436
|
+
return policyValue(settings, "maxFailedLoginsPerAccount");
|
|
1437
|
+
}
|
|
1438
|
+
function sessionLimitFor(settings, roleDocumentId) {
|
|
1439
|
+
const rule = roleRuleFor(settings, roleDocumentId);
|
|
1440
|
+
const limit = rule && rule.maxSessionsPerUser !== null ? rule.maxSessionsPerUser : policyValue(settings, "maxSessionsPerUser");
|
|
1441
|
+
return { limit, policy: policyValue(settings, "sessionLimitPolicy") };
|
|
1442
|
+
}
|
|
1443
|
+
function inactivityTimeoutFor(settings, roleDocumentId) {
|
|
1444
|
+
const rule = roleRuleFor(settings, roleDocumentId);
|
|
1445
|
+
if (rule && rule.inactivityTimeout !== null) return rule.inactivityTimeout * 60 * 1e3;
|
|
1446
|
+
const general = Number(settings?.inactivityTimeout);
|
|
1447
|
+
return Number.isFinite(general) && general > 0 ? general : 15 * 60 * 1e3;
|
|
1448
|
+
}
|
|
1449
|
+
module2.exports = {
|
|
1450
|
+
POLICY_DEFAULTS,
|
|
1451
|
+
POLICY_KEYS,
|
|
1452
|
+
POLICY_RANGES,
|
|
1453
|
+
ROLE_RULE_FIELDS,
|
|
1454
|
+
ROLE_RULE_RANGES,
|
|
1455
|
+
SESSION_LIMIT_POLICIES,
|
|
1456
|
+
MAX_ROLE_RULES,
|
|
1457
|
+
MAX_TRUSTED_ADDRESSES,
|
|
1458
|
+
accountThresholdFor,
|
|
1459
|
+
hasRoleOverride,
|
|
1460
|
+
inactivityTimeoutFor,
|
|
1461
|
+
isTrustedAddress,
|
|
1462
|
+
normalizePolicySettings,
|
|
1463
|
+
normalizeRoleRules,
|
|
1464
|
+
parseTrustedAddress,
|
|
1465
|
+
policyValue,
|
|
1466
|
+
resolveLockoutPolicy,
|
|
1467
|
+
roleRuleFor,
|
|
1468
|
+
sessionLimitFor,
|
|
1469
|
+
validatePolicySettings
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
});
|
|
1473
|
+
|
|
1474
|
+
// server/src/utils/detection-settings.js
|
|
1475
|
+
var require_detection_settings = __commonJS({
|
|
1476
|
+
"server/src/utils/detection-settings.js"(exports2, module2) {
|
|
1477
|
+
"use strict";
|
|
1478
|
+
var WEBHOOK_EVENTS = Object.freeze([
|
|
1479
|
+
"login.success",
|
|
1480
|
+
"login.suspicious",
|
|
1481
|
+
"login.new_location",
|
|
1482
|
+
"login.new_device",
|
|
1483
|
+
"login.impossible_travel",
|
|
1484
|
+
"login.failed",
|
|
1485
|
+
"login.refused",
|
|
1486
|
+
"lockout",
|
|
1487
|
+
"lockout.lifted",
|
|
1488
|
+
"session.limit",
|
|
1489
|
+
"password.changed",
|
|
1490
|
+
"user.not_me"
|
|
1491
|
+
]);
|
|
1492
|
+
var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
|
|
1493
|
+
"login.suspicious",
|
|
1494
|
+
"login.new_location",
|
|
1495
|
+
"login.new_device",
|
|
1496
|
+
"login.impossible_travel",
|
|
1497
|
+
"lockout",
|
|
1498
|
+
"user.not_me"
|
|
1499
|
+
]);
|
|
1500
|
+
var LEGACY_WEBHOOK_EVENTS = Object.freeze([
|
|
1501
|
+
"login.success",
|
|
1502
|
+
"login.suspicious",
|
|
1503
|
+
"login.new_location"
|
|
1504
|
+
]);
|
|
1505
|
+
var IMPOSSIBLE_TRAVEL_ACTIONS = Object.freeze(["alert", "reauthenticate"]);
|
|
1506
|
+
var DETECTION_DEFAULTS = Object.freeze({
|
|
1507
|
+
alertOnNewDevice: false,
|
|
1508
|
+
alertOnImpossibleTravel: false,
|
|
1509
|
+
impossibleTravelEnabled: false,
|
|
1510
|
+
impossibleTravelSpeedKmh: 1e3,
|
|
1511
|
+
impossibleTravelMinDistanceKm: 500,
|
|
1512
|
+
impossibleTravelAction: "alert",
|
|
1513
|
+
webhookEvents: DEFAULT_WEBHOOK_EVENTS,
|
|
1514
|
+
genericWebhookEnabled: false,
|
|
1515
|
+
genericWebhookUrl: "",
|
|
1516
|
+
sessionIpAnonymize: false
|
|
1517
|
+
});
|
|
1518
|
+
var DETECTION_KEYS = Object.freeze(Object.keys(DETECTION_DEFAULTS));
|
|
1519
|
+
var PROTECTED_DETECTION_KEYS = Object.freeze([
|
|
1520
|
+
"impossibleTravelEnabled",
|
|
1521
|
+
"impossibleTravelSpeedKmh",
|
|
1522
|
+
"impossibleTravelMinDistanceKm",
|
|
1523
|
+
"impossibleTravelAction",
|
|
1524
|
+
"webhookEvents",
|
|
1525
|
+
"genericWebhookEnabled",
|
|
1526
|
+
"genericWebhookUrl",
|
|
1527
|
+
"genericWebhookSecret",
|
|
1528
|
+
"sessionIpAnonymize"
|
|
1529
|
+
]);
|
|
1530
|
+
var RANGES = Object.freeze({
|
|
1531
|
+
impossibleTravelSpeedKmh: Object.freeze([100, 5e3]),
|
|
1532
|
+
impossibleTravelMinDistanceKm: Object.freeze([50, 2e4])
|
|
1533
|
+
});
|
|
1534
|
+
var BOOLEAN_KEYS = Object.freeze([
|
|
1535
|
+
"alertOnNewDevice",
|
|
1536
|
+
"alertOnImpossibleTravel",
|
|
1537
|
+
"impossibleTravelEnabled",
|
|
1538
|
+
"genericWebhookEnabled",
|
|
1539
|
+
"sessionIpAnonymize"
|
|
1540
|
+
]);
|
|
1541
|
+
var MAX_URL_LENGTH = 2048;
|
|
1542
|
+
function parseInteger(value) {
|
|
1543
|
+
if (typeof value === "number") return Number.isInteger(value) ? value : null;
|
|
1544
|
+
if (typeof value === "string" && /^\s*\d{1,9}\s*$/.test(value)) return Number.parseInt(value, 10);
|
|
1545
|
+
return null;
|
|
1546
|
+
}
|
|
1547
|
+
function normalizeWebhookUrl(value) {
|
|
1548
|
+
if (typeof value !== "string") return null;
|
|
1549
|
+
const trimmed = value.trim();
|
|
1550
|
+
if (!trimmed || trimmed.length > MAX_URL_LENGTH) return null;
|
|
1551
|
+
let parsed;
|
|
1552
|
+
try {
|
|
1553
|
+
parsed = new URL(trimmed);
|
|
1554
|
+
} catch {
|
|
1555
|
+
return null;
|
|
1556
|
+
}
|
|
1557
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password) return null;
|
|
1558
|
+
const host = parsed.hostname.toLowerCase();
|
|
1559
|
+
if (!host || host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) {
|
|
1560
|
+
return null;
|
|
1561
|
+
}
|
|
1562
|
+
return parsed.toString();
|
|
1563
|
+
}
|
|
1564
|
+
function normalizeEventList(value) {
|
|
1565
|
+
if (!Array.isArray(value)) return null;
|
|
1566
|
+
return [...new Set(value.filter((event) => WEBHOOK_EVENTS.includes(event)))];
|
|
1567
|
+
}
|
|
1568
|
+
function normalizeDetectionSettings(stored) {
|
|
1569
|
+
const out = {};
|
|
1570
|
+
if (!stored || typeof stored !== "object") return out;
|
|
1571
|
+
for (const key of BOOLEAN_KEYS) if (stored[key] !== void 0) out[key] = stored[key] === true;
|
|
1572
|
+
for (const [key, [min, max]] of Object.entries(RANGES)) {
|
|
1573
|
+
if (stored[key] === void 0) continue;
|
|
1574
|
+
const number = parseInteger(stored[key]);
|
|
1575
|
+
out[key] = number !== null && number >= min && number <= max ? number : (
|
|
1576
|
+
/** @type {any} */
|
|
1577
|
+
DETECTION_DEFAULTS[key]
|
|
1578
|
+
);
|
|
1579
|
+
}
|
|
1580
|
+
if (stored.impossibleTravelAction !== void 0) {
|
|
1581
|
+
out.impossibleTravelAction = IMPOSSIBLE_TRAVEL_ACTIONS.includes(
|
|
1582
|
+
/** @type {string} */
|
|
1583
|
+
stored.impossibleTravelAction
|
|
1584
|
+
) ? stored.impossibleTravelAction : "alert";
|
|
1585
|
+
}
|
|
1586
|
+
if (stored.webhookEvents !== void 0) {
|
|
1587
|
+
out.webhookEvents = normalizeEventList(stored.webhookEvents) || [...DEFAULT_WEBHOOK_EVENTS];
|
|
1588
|
+
}
|
|
1589
|
+
if (stored.genericWebhookUrl !== void 0) {
|
|
1590
|
+
out.genericWebhookUrl = normalizeWebhookUrl(stored.genericWebhookUrl) || "";
|
|
1591
|
+
}
|
|
1592
|
+
return out;
|
|
1593
|
+
}
|
|
1594
|
+
function validateDetectionSettings(body) {
|
|
1595
|
+
const values = {};
|
|
1596
|
+
const errors = [];
|
|
1597
|
+
const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
|
|
1598
|
+
for (const key of BOOLEAN_KEYS) {
|
|
1599
|
+
if (!has(key)) continue;
|
|
1600
|
+
if (typeof body[key] !== "boolean")
|
|
1601
|
+
errors.push({ path: [key], message: `${key} must be a boolean` });
|
|
1602
|
+
else values[key] = body[key];
|
|
1603
|
+
}
|
|
1604
|
+
for (const [key, [min, max]] of Object.entries(RANGES)) {
|
|
1605
|
+
if (!has(key)) continue;
|
|
1606
|
+
const number = parseInteger(body[key]);
|
|
1607
|
+
if (number === null || number < min || number > max) {
|
|
1608
|
+
errors.push({ path: [key], message: `${key} must be an integer between ${min} and ${max}` });
|
|
1609
|
+
} else {
|
|
1610
|
+
values[key] = number;
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
if (has("impossibleTravelAction")) {
|
|
1614
|
+
if (!IMPOSSIBLE_TRAVEL_ACTIONS.includes(
|
|
1615
|
+
/** @type {string} */
|
|
1616
|
+
body.impossibleTravelAction
|
|
1617
|
+
)) {
|
|
1618
|
+
errors.push({
|
|
1619
|
+
path: ["impossibleTravelAction"],
|
|
1620
|
+
message: `impossibleTravelAction must be one of: ${IMPOSSIBLE_TRAVEL_ACTIONS.join(", ")}`
|
|
1621
|
+
});
|
|
1622
|
+
} else {
|
|
1623
|
+
values.impossibleTravelAction = body.impossibleTravelAction;
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
if (has("webhookEvents")) {
|
|
1627
|
+
const list = body.webhookEvents;
|
|
1628
|
+
if (!Array.isArray(list) || list.length > WEBHOOK_EVENTS.length || list.some((event) => !WEBHOOK_EVENTS.includes(event))) {
|
|
1629
|
+
errors.push({
|
|
1630
|
+
path: ["webhookEvents"],
|
|
1631
|
+
message: `webhookEvents must be a list of: ${WEBHOOK_EVENTS.join(", ")}`
|
|
1632
|
+
});
|
|
1633
|
+
} else {
|
|
1634
|
+
values.webhookEvents = [...new Set(list)];
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
if (has("genericWebhookUrl")) {
|
|
1638
|
+
const raw = body.genericWebhookUrl;
|
|
1639
|
+
if (typeof raw !== "string") {
|
|
1640
|
+
errors.push({ path: ["genericWebhookUrl"], message: "genericWebhookUrl must be a string" });
|
|
1641
|
+
} else if (!raw.trim()) {
|
|
1642
|
+
values.genericWebhookUrl = "";
|
|
1643
|
+
} else {
|
|
1644
|
+
const url = normalizeWebhookUrl(raw);
|
|
1645
|
+
if (!url) {
|
|
1646
|
+
errors.push({
|
|
1647
|
+
path: ["genericWebhookUrl"],
|
|
1648
|
+
message: "genericWebhookUrl must be an https URL without credentials on a public host name"
|
|
1649
|
+
});
|
|
1650
|
+
} else {
|
|
1651
|
+
values.genericWebhookUrl = url;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
return { values, errors };
|
|
1656
|
+
}
|
|
1657
|
+
function resolveDetectionSettings(settings) {
|
|
1658
|
+
const source = settings && typeof settings === "object" ? settings : {};
|
|
1659
|
+
const clean = normalizeDetectionSettings(
|
|
1660
|
+
Object.fromEntries(
|
|
1661
|
+
DETECTION_KEYS.map((key) => [key, source[key]]).filter(([, v]) => v !== void 0)
|
|
1662
|
+
)
|
|
1663
|
+
);
|
|
1664
|
+
return (
|
|
1665
|
+
/** @type {any} */
|
|
1666
|
+
{
|
|
1667
|
+
...DETECTION_DEFAULTS,
|
|
1668
|
+
webhookEvents: [...DEFAULT_WEBHOOK_EVENTS],
|
|
1669
|
+
...clean
|
|
1670
|
+
}
|
|
1671
|
+
);
|
|
1672
|
+
}
|
|
1673
|
+
module2.exports = {
|
|
1674
|
+
DEFAULT_WEBHOOK_EVENTS,
|
|
1675
|
+
DETECTION_DEFAULTS,
|
|
1676
|
+
DETECTION_KEYS,
|
|
1677
|
+
PROTECTED_DETECTION_KEYS,
|
|
1678
|
+
IMPOSSIBLE_TRAVEL_ACTIONS,
|
|
1679
|
+
LEGACY_WEBHOOK_EVENTS,
|
|
1680
|
+
WEBHOOK_EVENTS,
|
|
1681
|
+
normalizeDetectionSettings,
|
|
1682
|
+
normalizeWebhookUrl,
|
|
1683
|
+
resolveDetectionSettings,
|
|
1684
|
+
validateDetectionSettings
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
});
|
|
1688
|
+
|
|
987
1689
|
// server/src/utils/settings-loader.js
|
|
988
1690
|
var require_settings_loader = __commonJS({
|
|
989
1691
|
"server/src/utils/settings-loader.js"(exports2, module2) {
|
|
990
1692
|
"use strict";
|
|
991
1693
|
var { getCoordinator } = require_coordination();
|
|
1694
|
+
var { normalizePolicySettings } = require_policy_settings();
|
|
1695
|
+
var { normalizeDetectionSettings } = require_detection_settings();
|
|
992
1696
|
var PLUGIN_ID = "magic-sessionmanager";
|
|
993
1697
|
var SETTINGS_KEY = "settings";
|
|
994
1698
|
var CACHE_TTL_MS = 30 * 1e3;
|
|
@@ -1120,6 +1824,11 @@ var require_settings_loader = __commonJS({
|
|
|
1120
1824
|
if (stored.trustedProxies !== void 0) {
|
|
1121
1825
|
out.trustedProxies = stored.trustedProxies;
|
|
1122
1826
|
}
|
|
1827
|
+
Object.assign(out, normalizePolicySettings(stored));
|
|
1828
|
+
Object.assign(out, normalizeDetectionSettings(stored));
|
|
1829
|
+
if (typeof stored.genericWebhookSecret === "string") {
|
|
1830
|
+
out.genericWebhookSecret = stored.genericWebhookSecret;
|
|
1831
|
+
}
|
|
1123
1832
|
return out;
|
|
1124
1833
|
}
|
|
1125
1834
|
async function getPluginSettings(strapi2) {
|
|
@@ -1230,7 +1939,18 @@ var require_security_log_model = __commonJS({
|
|
|
1230
1939
|
// 4.17: always recorded (no switch), never values.
|
|
1231
1940
|
SETTINGS_UPDATED: "settings.updated",
|
|
1232
1941
|
LOG_RETENTION_PURGED: "security-log.retention.purged",
|
|
1233
|
-
LOG_READ: "security-log.read"
|
|
1942
|
+
LOG_READ: "security-log.read",
|
|
1943
|
+
// App users (Users & Permissions), 4.17.
|
|
1944
|
+
USER_SIGN_IN_FAILED: "user.sign-in.failed",
|
|
1945
|
+
USER_SIGN_IN_REFUSED: "user.sign-in.refused",
|
|
1946
|
+
USER_LOCKOUT: "user.lockout",
|
|
1947
|
+
USER_LOCKOUT_LIFTED: "user.lockout.lifted",
|
|
1948
|
+
USER_SESSION_LIMIT: "user.session.limit",
|
|
1949
|
+
USER_PASSWORD_CHANGE_ENDED: "user.password-change.ended-others",
|
|
1950
|
+
USER_NEW_DEVICE: "user.sign-in.new-device",
|
|
1951
|
+
USER_IMPOSSIBLE_TRAVEL: "user.sign-in.impossible-travel",
|
|
1952
|
+
USER_NOT_ME: "user.not-me",
|
|
1953
|
+
USER_DATA_EXPORTED: "user.data.exported"
|
|
1234
1954
|
});
|
|
1235
1955
|
var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
|
|
1236
1956
|
SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
|
|
@@ -1238,7 +1958,7 @@ var require_security_log_model = __commonJS({
|
|
|
1238
1958
|
SECURITY_EVENTS.LOG_READ
|
|
1239
1959
|
]);
|
|
1240
1960
|
function dropRankOf(event) {
|
|
1241
|
-
if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
|
|
1961
|
+
if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT || USER_SIGN_IN_EVENTS.includes(event)) {
|
|
1242
1962
|
return { rank: 0, family: "failed" };
|
|
1243
1963
|
}
|
|
1244
1964
|
if (event === SECURITY_EVENTS.ADMIN_CONTENT_VIEW) return { rank: 1, family: "content-view" };
|
|
@@ -1247,6 +1967,19 @@ var require_security_log_model = __commonJS({
|
|
|
1247
1967
|
}
|
|
1248
1968
|
return { rank: 3, family: "account" };
|
|
1249
1969
|
}
|
|
1970
|
+
var USER_SIGN_IN_EVENTS = Object.freeze([
|
|
1971
|
+
SECURITY_EVENTS.USER_SIGN_IN_FAILED,
|
|
1972
|
+
SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
|
|
1973
|
+
SECURITY_EVENTS.USER_LOCKOUT
|
|
1974
|
+
]);
|
|
1975
|
+
var REFUSAL_REASONS = Object.freeze([
|
|
1976
|
+
"lockout",
|
|
1977
|
+
"too-many-attempts",
|
|
1978
|
+
"session-limit",
|
|
1979
|
+
"country",
|
|
1980
|
+
"risk",
|
|
1981
|
+
"location-unavailable"
|
|
1982
|
+
]);
|
|
1250
1983
|
var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
|
|
1251
1984
|
var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
|
|
1252
1985
|
var ADMIN_SIGN_IN_EVENTS = Object.freeze([
|
|
@@ -1277,6 +2010,7 @@ var require_security_log_model = __commonJS({
|
|
|
1277
2010
|
function recordingSwitchOf(event) {
|
|
1278
2011
|
if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
|
|
1279
2012
|
if (event.startsWith("admin.content.")) return "content";
|
|
2013
|
+
if (USER_SIGN_IN_EVENTS.includes(event)) return "userSignIns";
|
|
1280
2014
|
return "always";
|
|
1281
2015
|
}
|
|
1282
2016
|
var CONTENT_MANAGER_HANDLERS = Object.freeze({
|
|
@@ -1457,6 +2191,8 @@ var require_security_log_model = __commonJS({
|
|
|
1457
2191
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
1458
2192
|
}
|
|
1459
2193
|
module2.exports = {
|
|
2194
|
+
REFUSAL_REASONS,
|
|
2195
|
+
USER_SIGN_IN_EVENTS,
|
|
1460
2196
|
ACTOR_TYPES,
|
|
1461
2197
|
ADMIN_CONTENT_EVENTS,
|
|
1462
2198
|
ADMIN_SIGN_IN_EVENTS,
|
|
@@ -1715,10 +2451,19 @@ var require_register = __commonJS({
|
|
|
1715
2451
|
// secrets) and the security log. The other settings stay on `access`.
|
|
1716
2452
|
{
|
|
1717
2453
|
section: "plugins",
|
|
1718
|
-
displayName: "Change protected settings (location lookup, webhooks, security log)",
|
|
2454
|
+
displayName: "Change protected settings (location lookup, webhooks, security log, sign-in policies)",
|
|
1719
2455
|
uid: "settings.update",
|
|
1720
2456
|
subCategory: "Settings",
|
|
1721
2457
|
pluginName: "magic-sessionmanager"
|
|
2458
|
+
},
|
|
2459
|
+
// Lifting a sign-in lock of an app user or IP address (4.17). Seeing the
|
|
2460
|
+
// locks only needs plugin access.
|
|
2461
|
+
{
|
|
2462
|
+
section: "plugins",
|
|
2463
|
+
displayName: "Unlock locked sign-ins",
|
|
2464
|
+
uid: "lockouts.unlock",
|
|
2465
|
+
subCategory: "General",
|
|
2466
|
+
pluginName: "magic-sessionmanager"
|
|
1722
2467
|
}
|
|
1723
2468
|
]);
|
|
1724
2469
|
disableGraphqlShadowCrud(strapi2, log);
|
|
@@ -1769,6 +2514,20 @@ var require_register = __commonJS({
|
|
|
1769
2514
|
} catch (err) {
|
|
1770
2515
|
log.warn("[lifecycle] afterUpdate hook failed:", err?.name || "Error");
|
|
1771
2516
|
}
|
|
2517
|
+
},
|
|
2518
|
+
/**
|
|
2519
|
+
* Deleting an app user deletes what the security log holds about them.
|
|
2520
|
+
*
|
|
2521
|
+
* @param {object} event
|
|
2522
|
+
*/
|
|
2523
|
+
async afterDelete(event) {
|
|
2524
|
+
try {
|
|
2525
|
+
const documentId = event?.result?.documentId;
|
|
2526
|
+
if (!documentId) return;
|
|
2527
|
+
await strapi2.plugin("magic-sessionmanager").service("security-log").deleteUserData(documentId);
|
|
2528
|
+
} catch (err) {
|
|
2529
|
+
log.warn("[lifecycle] Security events of a deleted user stay:", err?.name || "Error");
|
|
2530
|
+
}
|
|
1772
2531
|
}
|
|
1773
2532
|
});
|
|
1774
2533
|
log.info("[SUCCESS] Plugin registered successfully");
|
|
@@ -1941,7 +2700,13 @@ var require_encryption = __commonJS({
|
|
|
1941
2700
|
function getEncryptionKeyCheck() {
|
|
1942
2701
|
return crypto.createHmac("sha256", getEncryptionKey()).update("magic-sessionmanager:encryption-key-check:v1").digest("hex").slice(0, 16);
|
|
1943
2702
|
}
|
|
2703
|
+
function derivePurposeKey(purpose) {
|
|
2704
|
+
return Buffer.from(
|
|
2705
|
+
crypto.hkdfSync("sha256", getEncryptionKey(), "magic-sessionmanager", `msm:${purpose}`, 32)
|
|
2706
|
+
);
|
|
2707
|
+
}
|
|
1944
2708
|
module2.exports = {
|
|
2709
|
+
derivePurposeKey,
|
|
1945
2710
|
getEncryptionKeyCheck,
|
|
1946
2711
|
encryptToken,
|
|
1947
2712
|
decryptToken,
|
|
@@ -2203,13 +2968,15 @@ var require_login_alerts = __commonJS({
|
|
|
2203
2968
|
"server/src/utils/login-alerts.js"(exports2, module2) {
|
|
2204
2969
|
"use strict";
|
|
2205
2970
|
var { evaluateLoginRisk } = require_risk_data();
|
|
2971
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
2206
2972
|
async function dispatchLoginAlerts({
|
|
2207
2973
|
settings,
|
|
2208
2974
|
notificationService,
|
|
2209
2975
|
user,
|
|
2210
2976
|
session,
|
|
2211
2977
|
geoData,
|
|
2212
|
-
isNewLocation = false
|
|
2978
|
+
isNewLocation = false,
|
|
2979
|
+
webhooks = null
|
|
2213
2980
|
}) {
|
|
2214
2981
|
const attempted = { webhookEvent: null, emails: [] };
|
|
2215
2982
|
if (!geoData) return attempted;
|
|
@@ -2243,8 +3010,22 @@ var require_login_alerts = __commonJS({
|
|
|
2243
3010
|
await notificationService.sendNewLocationAlert({ user, session, geoData });
|
|
2244
3011
|
}
|
|
2245
3012
|
}
|
|
2246
|
-
|
|
2247
|
-
|
|
3013
|
+
const webhookEvent = risk.isSuspicious ? "login.suspicious" : isNewLocation ? "login.new_location" : "login.success";
|
|
3014
|
+
const selected = resolveDetectionSettings(settings).webhookEvents.includes(webhookEvent);
|
|
3015
|
+
if (selected && webhooks) {
|
|
3016
|
+
webhooks.emit(
|
|
3017
|
+
webhookEvent,
|
|
3018
|
+
{
|
|
3019
|
+
userId: user?.documentId || null,
|
|
3020
|
+
ip: session?.ipAddress || null,
|
|
3021
|
+
userAgent: session?.userAgent || null,
|
|
3022
|
+
geo: geoData,
|
|
3023
|
+
details: null
|
|
3024
|
+
},
|
|
3025
|
+
{ chat: false }
|
|
3026
|
+
);
|
|
3027
|
+
}
|
|
3028
|
+
if (settings.enableWebhooks && selected) {
|
|
2248
3029
|
attempted.webhookEvent = webhookEvent;
|
|
2249
3030
|
const targets = [];
|
|
2250
3031
|
if (settings.discordWebhookUrl) {
|
|
@@ -3471,39 +4252,734 @@ var require_admin_activity_capture = __commonJS({
|
|
|
3471
4252
|
`[security-log] Retention removed ${removed.expired} expired events and ${removed.orphans} of deleted admins`
|
|
3472
4253
|
);
|
|
3473
4254
|
}
|
|
3474
|
-
};
|
|
3475
|
-
try {
|
|
3476
|
-
if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
|
|
3477
|
-
else await job();
|
|
3478
|
-
} catch (err) {
|
|
3479
|
-
log.warn("[security-log] Retention failed:", err?.name || "Error");
|
|
4255
|
+
};
|
|
4256
|
+
try {
|
|
4257
|
+
if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
|
|
4258
|
+
else await job();
|
|
4259
|
+
} catch (err) {
|
|
4260
|
+
log.warn("[security-log] Retention failed:", err?.name || "Error");
|
|
4261
|
+
}
|
|
4262
|
+
};
|
|
4263
|
+
try {
|
|
4264
|
+
strapi2.cron.add({ [jobName]: { task: retention, options: { rule: "17 3 * * *" } } });
|
|
4265
|
+
cleanups.push(() => strapi2.cron.remove(jobName));
|
|
4266
|
+
} catch (err) {
|
|
4267
|
+
log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
|
|
4268
|
+
}
|
|
4269
|
+
return async () => {
|
|
4270
|
+
for (const cleanup of cleanups.splice(0)) {
|
|
4271
|
+
try {
|
|
4272
|
+
cleanup();
|
|
4273
|
+
} catch {
|
|
4274
|
+
}
|
|
4275
|
+
}
|
|
4276
|
+
try {
|
|
4277
|
+
await strapi2.plugin("magic-sessionmanager")?.service(SERVICE)?.stop();
|
|
4278
|
+
} catch {
|
|
4279
|
+
}
|
|
4280
|
+
};
|
|
4281
|
+
}
|
|
4282
|
+
module2.exports = {
|
|
4283
|
+
authErrorNamesKnownAdmins,
|
|
4284
|
+
createCaptureMiddleware,
|
|
4285
|
+
installAdminActivityCapture,
|
|
4286
|
+
observeAuthentication,
|
|
4287
|
+
observeContentManager
|
|
4288
|
+
};
|
|
4289
|
+
}
|
|
4290
|
+
});
|
|
4291
|
+
|
|
4292
|
+
// server/src/utils/login-lockout.js
|
|
4293
|
+
var require_login_lockout = __commonJS({
|
|
4294
|
+
"server/src/utils/login-lockout.js"(exports2, module2) {
|
|
4295
|
+
"use strict";
|
|
4296
|
+
var { hashedKey } = require_coordination();
|
|
4297
|
+
var { isTrustedAddress } = require_policy_settings();
|
|
4298
|
+
var LOCK_PREFIX = "lock:";
|
|
4299
|
+
var KEY_PATTERN = /^(lf|la):[a-f0-9]{48}$/;
|
|
4300
|
+
var MAX_LISTED_LOCKS = 200;
|
|
4301
|
+
function normalizeIdentifier(identifier) {
|
|
4302
|
+
if (typeof identifier !== "string") return null;
|
|
4303
|
+
const value = identifier.trim().toLowerCase();
|
|
4304
|
+
if (!value || value.length > 254) return null;
|
|
4305
|
+
return value;
|
|
4306
|
+
}
|
|
4307
|
+
var ipKey = (ip) => hashedKey("lf", ip);
|
|
4308
|
+
var accountKey = (identifier) => hashedKey("la", identifier);
|
|
4309
|
+
function createLoginLockout(coordinator, { now = () => Date.now() } = {}) {
|
|
4310
|
+
const remainingSeconds = async (key) => {
|
|
4311
|
+
if (!key) return 0;
|
|
4312
|
+
const entry = await coordinator.peek(key);
|
|
4313
|
+
const until = Number(entry?.blockedUntil) || 0;
|
|
4314
|
+
const left = until - now();
|
|
4315
|
+
return left > 0 ? Math.ceil(left / 1e3) : 0;
|
|
4316
|
+
};
|
|
4317
|
+
const release = async (reservation) => {
|
|
4318
|
+
if (reservation.ipKey) await coordinator.release(reservation.ipKey);
|
|
4319
|
+
if (reservation.accountKey) await coordinator.release(reservation.accountKey);
|
|
4320
|
+
};
|
|
4321
|
+
return {
|
|
4322
|
+
normalizeIdentifier,
|
|
4323
|
+
/**
|
|
4324
|
+
* Checks the locks and counts the attempt before the password check.
|
|
4325
|
+
*
|
|
4326
|
+
* @param {{ip: string|null, identifier: string|null, policy: LockoutPolicy,
|
|
4327
|
+
* accountMax: number}} input Client IP, normalised identifier, policy and the
|
|
4328
|
+
* account threshold for this account's role.
|
|
4329
|
+
* @returns {Promise<{outcome: 'allow'|'locked'|'busy', retryAfter: number,
|
|
4330
|
+
* lockedKind: 'ip'|'account'|null, reservation: Reservation}>} Decision.
|
|
4331
|
+
* @sideeffect Increments the shared counters.
|
|
4332
|
+
*/
|
|
4333
|
+
async reserve({ ip, identifier, policy, accountMax }) {
|
|
4334
|
+
const countIp = policy.ipMax > 0 && typeof ip === "string" && ip && ip !== "unknown" ? !isTrustedAddress(policy.trusted, ip) : false;
|
|
4335
|
+
const countAccount = accountMax > 0 && typeof identifier === "string" && !!identifier;
|
|
4336
|
+
const reservation = {
|
|
4337
|
+
ipKey: countIp ? ipKey(
|
|
4338
|
+
/** @type {string} */
|
|
4339
|
+
ip
|
|
4340
|
+
) : null,
|
|
4341
|
+
ipHits: 0,
|
|
4342
|
+
accountKey: countAccount ? accountKey(
|
|
4343
|
+
/** @type {string} */
|
|
4344
|
+
identifier
|
|
4345
|
+
) : null,
|
|
4346
|
+
accountHits: 0
|
|
4347
|
+
};
|
|
4348
|
+
if (!reservation.ipKey && !reservation.accountKey) {
|
|
4349
|
+
return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
|
|
4350
|
+
}
|
|
4351
|
+
const [ipLeft, accountLeft] = await Promise.all([
|
|
4352
|
+
remainingSeconds(reservation.ipKey),
|
|
4353
|
+
remainingSeconds(reservation.accountKey)
|
|
4354
|
+
]);
|
|
4355
|
+
if (ipLeft > 0 || accountLeft > 0) {
|
|
4356
|
+
return {
|
|
4357
|
+
outcome: "locked",
|
|
4358
|
+
retryAfter: Math.max(ipLeft, accountLeft),
|
|
4359
|
+
lockedKind: accountLeft >= ipLeft && accountLeft > 0 ? "account" : "ip",
|
|
4360
|
+
reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
|
|
4361
|
+
};
|
|
4362
|
+
}
|
|
4363
|
+
if (reservation.ipKey) {
|
|
4364
|
+
reservation.ipHits = (await coordinator.hit(reservation.ipKey, policy.windowMs)).hits;
|
|
4365
|
+
}
|
|
4366
|
+
if (reservation.accountKey) {
|
|
4367
|
+
reservation.accountHits = (await coordinator.hit(reservation.accountKey, policy.windowMs)).hits;
|
|
4368
|
+
}
|
|
4369
|
+
if (reservation.ipKey && reservation.ipHits > policy.ipMax || reservation.accountKey && reservation.accountHits > accountMax) {
|
|
4370
|
+
await release(reservation);
|
|
4371
|
+
return { outcome: "busy", retryAfter: 1, lockedKind: null, reservation };
|
|
4372
|
+
}
|
|
4373
|
+
return { outcome: "allow", retryAfter: 0, lockedKind: null, reservation };
|
|
4374
|
+
},
|
|
4375
|
+
/**
|
|
4376
|
+
* Records the result of the sign-in.
|
|
4377
|
+
*
|
|
4378
|
+
* @param {Reservation} reservation From `reserve`.
|
|
4379
|
+
* @param {'success'|'failure'|'neutral'} result Outcome of the handler.
|
|
4380
|
+
* @param {{policy: LockoutPolicy, accountMax: number, display?: LockDisplay}} options
|
|
4381
|
+
* Policy, account threshold and what the lock list shows.
|
|
4382
|
+
* @returns {Promise<Array<{kind: 'ip'|'account', id: string, failures: number, until: number}>>}
|
|
4383
|
+
* Locks this request created.
|
|
4384
|
+
* @sideeffect Clears, releases or blocks shared counters; writes lock entries.
|
|
4385
|
+
*/
|
|
4386
|
+
async settle(reservation, result, { policy, accountMax, display = {} }) {
|
|
4387
|
+
if (result === "success") {
|
|
4388
|
+
for (const key of [reservation.ipKey, reservation.accountKey]) {
|
|
4389
|
+
if (!key) continue;
|
|
4390
|
+
await coordinator.clear(key);
|
|
4391
|
+
}
|
|
4392
|
+
return [];
|
|
4393
|
+
}
|
|
4394
|
+
if (result !== "failure") {
|
|
4395
|
+
await release(reservation);
|
|
4396
|
+
return [];
|
|
4397
|
+
}
|
|
4398
|
+
const locks = [];
|
|
4399
|
+
const until = now() + policy.durationMs;
|
|
4400
|
+
const candidates = [
|
|
4401
|
+
reservation.ipKey && reservation.ipHits >= policy.ipMax ? {
|
|
4402
|
+
kind: (
|
|
4403
|
+
/** @type {const} */
|
|
4404
|
+
"ip"
|
|
4405
|
+
),
|
|
4406
|
+
id: reservation.ipKey,
|
|
4407
|
+
failures: reservation.ipHits
|
|
4408
|
+
} : null,
|
|
4409
|
+
reservation.accountKey && reservation.accountHits >= accountMax ? {
|
|
4410
|
+
kind: (
|
|
4411
|
+
/** @type {const} */
|
|
4412
|
+
"account"
|
|
4413
|
+
),
|
|
4414
|
+
id: reservation.accountKey,
|
|
4415
|
+
failures: reservation.accountHits
|
|
4416
|
+
} : null
|
|
4417
|
+
];
|
|
4418
|
+
for (const lock of candidates) {
|
|
4419
|
+
if (!lock) continue;
|
|
4420
|
+
await coordinator.block(lock.id, until, { windowStart: until - policy.windowMs });
|
|
4421
|
+
await coordinator.registryPut(
|
|
4422
|
+
`${LOCK_PREFIX}${lock.id}`,
|
|
4423
|
+
{
|
|
4424
|
+
kind: lock.kind,
|
|
4425
|
+
ip: lock.kind === "ip" ? display.ip || null : null,
|
|
4426
|
+
user: lock.kind === "account" ? display.userDocumentId || null : null,
|
|
4427
|
+
failures: lock.failures,
|
|
4428
|
+
lockedAt: now(),
|
|
4429
|
+
until
|
|
4430
|
+
},
|
|
4431
|
+
policy.durationMs
|
|
4432
|
+
);
|
|
4433
|
+
locks.push({ ...lock, until });
|
|
4434
|
+
}
|
|
4435
|
+
return locks;
|
|
4436
|
+
},
|
|
4437
|
+
/**
|
|
4438
|
+
* Active locks, soonest end last.
|
|
4439
|
+
*
|
|
4440
|
+
* @returns {Promise<Array<{id: string, kind: 'ip'|'account', ip: string|null,
|
|
4441
|
+
* user: string|null, failures: number, lockedAt: number, until: number}>>} Locks.
|
|
4442
|
+
*/
|
|
4443
|
+
async listLocks() {
|
|
4444
|
+
const entries = await coordinator.registryList(LOCK_PREFIX, MAX_LISTED_LOCKS);
|
|
4445
|
+
const current = now();
|
|
4446
|
+
return entries.map(({ key, value }) => ({
|
|
4447
|
+
id: key.slice(LOCK_PREFIX.length),
|
|
4448
|
+
kind: value?.kind === "account" ? "account" : "ip",
|
|
4449
|
+
ip: typeof value?.ip === "string" ? value.ip : null,
|
|
4450
|
+
user: typeof value?.user === "string" ? value.user : null,
|
|
4451
|
+
failures: Number(value?.failures) || 0,
|
|
4452
|
+
lockedAt: Number(value?.lockedAt) || 0,
|
|
4453
|
+
until: Number(value?.until) || 0
|
|
4454
|
+
})).filter((lock) => KEY_PATTERN.test(lock.id) && lock.until > current).sort((a, b) => b.lockedAt - a.lockedAt);
|
|
4455
|
+
},
|
|
4456
|
+
/**
|
|
4457
|
+
* Lifts a lock: deletes the counter and the list entry.
|
|
4458
|
+
*
|
|
4459
|
+
* @param {string} id Lock id from `listLocks` (`lf:…` or `la:…`).
|
|
4460
|
+
* @returns {Promise<{kind: 'ip'|'account', ip: string|null, user: string|null}|null>}
|
|
4461
|
+
* The lifted lock, or null when the id is invalid or nothing was locked.
|
|
4462
|
+
* @sideeffect Deletes the shared counter and the lock entry.
|
|
4463
|
+
*/
|
|
4464
|
+
async unlock(id) {
|
|
4465
|
+
if (typeof id !== "string" || !KEY_PATTERN.test(id)) return null;
|
|
4466
|
+
const entries = await coordinator.registryList(`${LOCK_PREFIX}${id}`, 1);
|
|
4467
|
+
const entry = entries.find((candidate) => candidate.key === `${LOCK_PREFIX}${id}`);
|
|
4468
|
+
const counter = await coordinator.peek(id);
|
|
4469
|
+
const blocked = Number(counter?.blockedUntil) > now();
|
|
4470
|
+
await coordinator.clear(id);
|
|
4471
|
+
await coordinator.registryDelete(`${LOCK_PREFIX}${id}`);
|
|
4472
|
+
if (!entry && !blocked) return null;
|
|
4473
|
+
return {
|
|
4474
|
+
kind: id.startsWith("la:") ? "account" : "ip",
|
|
4475
|
+
ip: typeof entry?.value?.ip === "string" ? entry.value.ip : null,
|
|
4476
|
+
user: typeof entry?.value?.user === "string" ? entry.value.user : null
|
|
4477
|
+
};
|
|
3480
4478
|
}
|
|
3481
4479
|
};
|
|
4480
|
+
}
|
|
4481
|
+
module2.exports = {
|
|
4482
|
+
LOCK_ID_PATTERN: KEY_PATTERN,
|
|
4483
|
+
accountKey,
|
|
4484
|
+
createLoginLockout,
|
|
4485
|
+
ipKey,
|
|
4486
|
+
normalizeIdentifier
|
|
4487
|
+
};
|
|
4488
|
+
}
|
|
4489
|
+
});
|
|
4490
|
+
|
|
4491
|
+
// server/src/utils/sign-in-policies.js
|
|
4492
|
+
var require_sign_in_policies = __commonJS({
|
|
4493
|
+
"server/src/utils/sign-in-policies.js"(exports2, module2) {
|
|
4494
|
+
"use strict";
|
|
4495
|
+
var { anonymizeIp, normalizeIp } = require_admin_request_info();
|
|
4496
|
+
var { getCoordinator, hashedKey } = require_coordination();
|
|
4497
|
+
var { resolveSecurityLogSettings } = require_security_log_settings();
|
|
4498
|
+
var { hasRoleOverride, inactivityTimeoutFor, sessionLimitFor } = require_policy_settings();
|
|
4499
|
+
var { normalizeIdentifier } = require_login_lockout();
|
|
4500
|
+
var USER_UID = "plugin::users-permissions.user";
|
|
4501
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
4502
|
+
var MAX_SESSIONS_CHECKED = 500;
|
|
4503
|
+
function readSignInIdentifier(ctx) {
|
|
4504
|
+
const body = ctx?.request?.body;
|
|
4505
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
|
4506
|
+
return normalizeIdentifier(body.identifier) || normalizeIdentifier(body.email);
|
|
4507
|
+
}
|
|
4508
|
+
async function findAccountByIdentifier(strapi2, identifier) {
|
|
4509
|
+
if (!identifier) return null;
|
|
4510
|
+
const rows = await strapi2.db.query(USER_UID).findMany({
|
|
4511
|
+
where: { $or: [{ email: identifier }, { username: identifier }] },
|
|
4512
|
+
select: ["documentId", "email", "username"],
|
|
4513
|
+
populate: { role: { select: ["documentId"] } },
|
|
4514
|
+
limit: 2
|
|
4515
|
+
});
|
|
4516
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
4517
|
+
const account = list.find((row) => String(row.email || "").toLowerCase() === identifier) || list[0];
|
|
4518
|
+
if (!account?.documentId) return null;
|
|
4519
|
+
return {
|
|
4520
|
+
documentId: account.documentId,
|
|
4521
|
+
email: typeof account.email === "string" ? account.email : null,
|
|
4522
|
+
username: typeof account.username === "string" ? account.username : null,
|
|
4523
|
+
role: account.role?.documentId || null
|
|
4524
|
+
};
|
|
4525
|
+
}
|
|
4526
|
+
async function findUserRole(strapi2, userDocumentId) {
|
|
4527
|
+
if (!userDocumentId) return null;
|
|
4528
|
+
const user = await strapi2.db.query(USER_UID).findOne({
|
|
4529
|
+
where: { documentId: userDocumentId },
|
|
4530
|
+
select: ["id"],
|
|
4531
|
+
populate: { role: { select: ["documentId"] } }
|
|
4532
|
+
});
|
|
4533
|
+
return user?.role?.documentId || null;
|
|
4534
|
+
}
|
|
4535
|
+
function displayIp(settings, ip) {
|
|
4536
|
+
const options = resolveSecurityLogSettings(settings);
|
|
4537
|
+
if (!options.storeIp) return null;
|
|
4538
|
+
const normalized = normalizeIp(ip || "");
|
|
4539
|
+
if (!normalized) return null;
|
|
4540
|
+
return options.anonymizeIp ? anonymizeIp(normalized) : normalized;
|
|
4541
|
+
}
|
|
4542
|
+
function recordUserEvent(strapi2, input) {
|
|
3482
4543
|
try {
|
|
3483
|
-
strapi2.
|
|
3484
|
-
|
|
3485
|
-
} catch (err) {
|
|
3486
|
-
log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
|
|
4544
|
+
strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(input);
|
|
4545
|
+
} catch {
|
|
3487
4546
|
}
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
4547
|
+
try {
|
|
4548
|
+
return strapi2.plugin("magic-sessionmanager").service("security-log").record(input) === true;
|
|
4549
|
+
} catch {
|
|
4550
|
+
return false;
|
|
4551
|
+
}
|
|
4552
|
+
}
|
|
4553
|
+
function isOpenSession(session, idleMs, maxAgeDays, now) {
|
|
4554
|
+
if (session.isActive !== true) return false;
|
|
4555
|
+
const login = session.loginTime ? new Date(session.loginTime).getTime() : NaN;
|
|
4556
|
+
const last = session.lastActive ? new Date(session.lastActive).getTime() : login;
|
|
4557
|
+
if (Number.isFinite(last) && now - last > idleMs) return false;
|
|
4558
|
+
if (Number.isFinite(login) && now - login > maxAgeDays * 24 * 60 * 60 * 1e3) return false;
|
|
4559
|
+
return true;
|
|
4560
|
+
}
|
|
4561
|
+
async function createSessionWithinLimit({
|
|
4562
|
+
strapi: strapi2,
|
|
4563
|
+
settings,
|
|
4564
|
+
userDocumentId,
|
|
4565
|
+
create,
|
|
4566
|
+
sessionService
|
|
4567
|
+
}) {
|
|
4568
|
+
const possible = sessionLimitFor(settings, null).limit > 0 || hasRoleOverride(settings, "maxSessionsPerUser");
|
|
4569
|
+
if (!possible) return { session: await create(), refused: false, ended: 0, limit: 0 };
|
|
4570
|
+
const role = await findUserRole(strapi2, userDocumentId);
|
|
4571
|
+
const { limit, policy } = sessionLimitFor(settings, role);
|
|
4572
|
+
if (limit <= 0) return { session: await create(), refused: false, ended: 0, limit: 0 };
|
|
4573
|
+
return getCoordinator(strapi2).withLock(hashedKey("session-limit", userDocumentId), async () => {
|
|
4574
|
+
const session = await create();
|
|
4575
|
+
if (!session?.documentId) return { session, refused: false, ended: 0, limit };
|
|
4576
|
+
const now = Date.now();
|
|
4577
|
+
const idleMs = inactivityTimeoutFor(settings, role);
|
|
4578
|
+
const maxAgeDays = Number(settings.maxSessionAgeDays) || 30;
|
|
4579
|
+
const rows = await strapi2.documents(SESSION_UID).findMany({
|
|
4580
|
+
filters: { user: { documentId: userDocumentId }, isActive: true },
|
|
4581
|
+
fields: ["documentId", "isActive", "loginTime", "lastActive"],
|
|
4582
|
+
sort: [{ loginTime: "asc" }, { id: "asc" }],
|
|
4583
|
+
limit: MAX_SESSIONS_CHECKED
|
|
4584
|
+
});
|
|
4585
|
+
const open = (Array.isArray(rows) ? rows : []).filter(
|
|
4586
|
+
(row) => isOpenSession(row, idleMs, maxAgeDays, now)
|
|
4587
|
+
);
|
|
4588
|
+
if (open.length <= limit) return { session, refused: false, ended: 0, limit };
|
|
4589
|
+
if (policy === "refuse") {
|
|
4590
|
+
await sessionService.terminateSession({ sessionId: session.documentId, reason: "manual" });
|
|
4591
|
+
return { session, refused: true, ended: 0, limit };
|
|
4592
|
+
}
|
|
4593
|
+
const others = open.filter((row) => row.documentId !== session.documentId);
|
|
4594
|
+
const excess = open.length - limit;
|
|
4595
|
+
let ended = 0;
|
|
4596
|
+
for (const row of others.slice(0, excess)) {
|
|
4597
|
+
const result = await sessionService.terminateSession({
|
|
4598
|
+
sessionId: row.documentId,
|
|
4599
|
+
reason: "manual"
|
|
4600
|
+
});
|
|
4601
|
+
ended += Number(result?.terminatedCount) || 0;
|
|
4602
|
+
}
|
|
4603
|
+
return { session, refused: false, ended, limit };
|
|
4604
|
+
});
|
|
4605
|
+
}
|
|
4606
|
+
function createRefusalDedup({ windowMs = 60 * 1e3, maxKeys = 5e3 } = {}) {
|
|
4607
|
+
const seen = /* @__PURE__ */ new Map();
|
|
4608
|
+
return (key, now = Date.now()) => {
|
|
4609
|
+
const last = seen.get(key);
|
|
4610
|
+
if (last !== void 0 && now - last < windowMs) return false;
|
|
4611
|
+
seen.delete(key);
|
|
4612
|
+
seen.set(key, now);
|
|
4613
|
+
if (seen.size > maxKeys) seen.delete(
|
|
4614
|
+
/** @type {string} */
|
|
4615
|
+
seen.keys().next().value
|
|
4616
|
+
);
|
|
4617
|
+
return true;
|
|
4618
|
+
};
|
|
4619
|
+
}
|
|
4620
|
+
function createAddressCap({ max = 30, windowMs = 60 * 60 * 1e3, maxKeys = 5e3 } = {}) {
|
|
4621
|
+
const counts = /* @__PURE__ */ new Map();
|
|
4622
|
+
return (ip, now = Date.now()) => {
|
|
4623
|
+
const key = anonymizeIp(normalizeIp(ip || "")) || "-";
|
|
4624
|
+
const windowStart = Math.floor(now / windowMs) * windowMs;
|
|
4625
|
+
const entry = counts.get(key);
|
|
4626
|
+
if (!entry || entry.windowStart !== windowStart) {
|
|
4627
|
+
counts.delete(key);
|
|
4628
|
+
counts.set(key, { count: 1, windowStart });
|
|
4629
|
+
if (counts.size > maxKeys) counts.delete(
|
|
4630
|
+
/** @type {string} */
|
|
4631
|
+
counts.keys().next().value
|
|
4632
|
+
);
|
|
4633
|
+
return true;
|
|
4634
|
+
}
|
|
4635
|
+
entry.count += 1;
|
|
4636
|
+
return entry.count <= max;
|
|
4637
|
+
};
|
|
4638
|
+
}
|
|
4639
|
+
function refusalReasonOfGeoDecision(reason) {
|
|
4640
|
+
const value = String(reason || "");
|
|
4641
|
+
if (value.startsWith("country_")) return "country";
|
|
4642
|
+
if (value.startsWith("geo_lookup_unavailable")) return "location-unavailable";
|
|
4643
|
+
return "risk";
|
|
4644
|
+
}
|
|
4645
|
+
module2.exports = {
|
|
4646
|
+
createAddressCap,
|
|
4647
|
+
createRefusalDedup,
|
|
4648
|
+
refusalReasonOfGeoDecision,
|
|
4649
|
+
createSessionWithinLimit,
|
|
4650
|
+
displayIp,
|
|
4651
|
+
findAccountByIdentifier,
|
|
4652
|
+
findUserRole,
|
|
4653
|
+
isOpenSession,
|
|
4654
|
+
readSignInIdentifier,
|
|
4655
|
+
recordUserEvent
|
|
4656
|
+
};
|
|
4657
|
+
}
|
|
4658
|
+
});
|
|
4659
|
+
|
|
4660
|
+
// server/src/utils/upgrade-defaults.js
|
|
4661
|
+
var require_upgrade_defaults = __commonJS({
|
|
4662
|
+
"server/src/utils/upgrade-defaults.js"(exports2, module2) {
|
|
4663
|
+
"use strict";
|
|
4664
|
+
var { withPluginStoreKey } = require_plugin_store();
|
|
4665
|
+
var { notifySettingsChanged } = require_settings_loader();
|
|
4666
|
+
var { LEGACY_WEBHOOK_EVENTS } = require_detection_settings();
|
|
4667
|
+
var PROFILE_KEY = "defaultsProfile";
|
|
4668
|
+
var UPGRADE_STEPS = Object.freeze([
|
|
4669
|
+
Object.freeze({
|
|
4670
|
+
version: 1,
|
|
4671
|
+
release: "4.17.0",
|
|
4672
|
+
// Before 4.17 a password change kept the user's other sessions.
|
|
4673
|
+
legacy: Object.freeze({ endOtherSessionsOnPasswordChange: false })
|
|
4674
|
+
}),
|
|
4675
|
+
Object.freeze({
|
|
4676
|
+
version: 2,
|
|
4677
|
+
release: "sign-in signals and signed webhook",
|
|
4678
|
+
// Before, Discord and Slack received every sign-in (success, new
|
|
4679
|
+
// country, suspicious). New installations leave out every sign-in.
|
|
4680
|
+
legacy: Object.freeze({ webhookEvents: LEGACY_WEBHOOK_EVENTS })
|
|
4681
|
+
})
|
|
4682
|
+
]);
|
|
4683
|
+
async function applyUpgradeDefaults(strapi2, log, steps = UPGRADE_STEPS) {
|
|
4684
|
+
const latest = steps.length ? steps[steps.length - 1].version : 0;
|
|
4685
|
+
const outcome = await withPluginStoreKey(strapi2, "settings", async (store) => {
|
|
4686
|
+
const profile = Number(await store.get({ key: PROFILE_KEY })) || 0;
|
|
4687
|
+
if (profile >= latest) return { existing: profile > 0, applied: [], changed: false };
|
|
4688
|
+
const stored = await store.get({ key: "settings" });
|
|
4689
|
+
let existing = profile > 0;
|
|
4690
|
+
if (!existing) {
|
|
4691
|
+
const permissionsVersion = await store.get({ key: "contentApiPermissionsVersion" });
|
|
4692
|
+
const legacyFlag = await store.get({ key: "contentApiPermissionsInitialized" });
|
|
4693
|
+
existing = stored !== null && stored !== void 0 || permissionsVersion !== null && permissionsVersion !== void 0 || legacyFlag === true;
|
|
4694
|
+
}
|
|
4695
|
+
const applied = [];
|
|
4696
|
+
if (existing) {
|
|
4697
|
+
const settings = stored && typeof stored === "object" ? { ...stored } : {};
|
|
4698
|
+
for (const step of steps) {
|
|
4699
|
+
if (step.version <= profile) continue;
|
|
4700
|
+
for (const [key, value] of Object.entries(step.legacy)) {
|
|
4701
|
+
if (settings[key] !== void 0) continue;
|
|
4702
|
+
settings[key] = Array.isArray(value) ? [...value] : value;
|
|
4703
|
+
applied.push(key);
|
|
4704
|
+
}
|
|
3493
4705
|
}
|
|
4706
|
+
if (applied.length) await store.set({ key: "settings", value: settings });
|
|
3494
4707
|
}
|
|
4708
|
+
await store.set({ key: PROFILE_KEY, value: latest });
|
|
4709
|
+
return { existing, applied, changed: applied.length > 0 };
|
|
4710
|
+
});
|
|
4711
|
+
if (outcome.changed) {
|
|
4712
|
+
await notifySettingsChanged(strapi2);
|
|
4713
|
+
log.info(
|
|
4714
|
+
`[UPGRADE] Kept the previous behaviour of ${outcome.applied.length} setting(s) on this existing installation`
|
|
4715
|
+
);
|
|
4716
|
+
}
|
|
4717
|
+
return { existing: outcome.existing, applied: outcome.applied };
|
|
4718
|
+
}
|
|
4719
|
+
module2.exports = { PROFILE_KEY, UPGRADE_STEPS, applyUpgradeDefaults };
|
|
4720
|
+
}
|
|
4721
|
+
});
|
|
4722
|
+
|
|
4723
|
+
// server/src/utils/not-me-link.js
|
|
4724
|
+
var require_not_me_link = __commonJS({
|
|
4725
|
+
"server/src/utils/not-me-link.js"(exports2, module2) {
|
|
4726
|
+
"use strict";
|
|
4727
|
+
var crypto = require("node:crypto");
|
|
4728
|
+
var { derivePurposeKey } = require_encryption();
|
|
4729
|
+
var LIFETIME_MS = 72 * 60 * 60 * 1e3;
|
|
4730
|
+
var NONCE_PREFIX = "notme:";
|
|
4731
|
+
var DOCUMENT_ID = /^[A-Za-z0-9]{1,64}$/;
|
|
4732
|
+
var TOKEN_PATTERN = /^[A-Za-z0-9_-]{20,400}\.[A-Za-z0-9_-]{43}$/;
|
|
4733
|
+
var signingKey = () => derivePurposeKey("not-me-link");
|
|
4734
|
+
var sign = (payload) => crypto.createHmac("sha256", signingKey()).update(payload).digest("base64url");
|
|
4735
|
+
async function issueNotMeToken(coordinator, { sessionId, userId, now = Date.now() }) {
|
|
4736
|
+
if (!DOCUMENT_ID.test(String(sessionId)) || !DOCUMENT_ID.test(String(userId))) return null;
|
|
4737
|
+
const nonce = crypto.randomBytes(18).toString("hex");
|
|
4738
|
+
const payload = Buffer.from(
|
|
4739
|
+
JSON.stringify({ s: sessionId, u: userId, e: now + LIFETIME_MS, n: nonce })
|
|
4740
|
+
).toString("base64url");
|
|
4741
|
+
await coordinator.registryPut(
|
|
4742
|
+
`${NONCE_PREFIX}${nonce}`,
|
|
4743
|
+
{ s: sessionId, u: userId },
|
|
4744
|
+
LIFETIME_MS
|
|
4745
|
+
);
|
|
4746
|
+
return `${payload}.${sign(payload)}`;
|
|
4747
|
+
}
|
|
4748
|
+
function readNotMeToken(token, { now = Date.now() } = {}) {
|
|
4749
|
+
if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) return null;
|
|
4750
|
+
const [payload, signature] = token.split(".");
|
|
4751
|
+
const expected = Buffer.from(sign(payload));
|
|
4752
|
+
const given = Buffer.from(signature);
|
|
4753
|
+
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null;
|
|
4754
|
+
let claims;
|
|
4755
|
+
try {
|
|
4756
|
+
claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
4757
|
+
} catch {
|
|
4758
|
+
return null;
|
|
4759
|
+
}
|
|
4760
|
+
if (!claims || !DOCUMENT_ID.test(String(claims.s)) || !DOCUMENT_ID.test(String(claims.u)) || !/^[a-f0-9]{36}$/.test(String(claims.n)) || !Number.isFinite(claims.e) || claims.e <= now) {
|
|
4761
|
+
return null;
|
|
4762
|
+
}
|
|
4763
|
+
return { sessionId: claims.s, userId: claims.u, nonce: claims.n, expiresAt: claims.e };
|
|
4764
|
+
}
|
|
4765
|
+
async function consumeNotMeToken(coordinator, token) {
|
|
4766
|
+
const claims = readNotMeToken(token);
|
|
4767
|
+
if (!claims) return null;
|
|
4768
|
+
const stored = await coordinator.registryTake(`${NONCE_PREFIX}${claims.nonce}`);
|
|
4769
|
+
if (!stored || stored.s !== claims.sessionId || stored.u !== claims.userId) return null;
|
|
4770
|
+
return { sessionId: claims.sessionId, userId: claims.userId };
|
|
4771
|
+
}
|
|
4772
|
+
module2.exports = { LIFETIME_MS, consumeNotMeToken, issueNotMeToken, readNotMeToken };
|
|
4773
|
+
}
|
|
4774
|
+
});
|
|
4775
|
+
|
|
4776
|
+
// server/src/utils/sign-in-signals.js
|
|
4777
|
+
var require_sign_in_signals = __commonJS({
|
|
4778
|
+
"server/src/utils/sign-in-signals.js"(exports2, module2) {
|
|
4779
|
+
"use strict";
|
|
4780
|
+
var crypto = require("node:crypto");
|
|
4781
|
+
var { derivePurposeKey } = require_encryption();
|
|
4782
|
+
var { parseUserAgent } = require_user_agent_parser();
|
|
4783
|
+
var { getCoordinator } = require_coordination();
|
|
4784
|
+
var { normalizeApiPrefix } = require_auth_routes();
|
|
4785
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
4786
|
+
var { issueNotMeToken } = require_not_me_link();
|
|
4787
|
+
var { SECURITY_EVENTS } = require_security_log_model();
|
|
4788
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
4789
|
+
var HISTORY = 50;
|
|
4790
|
+
var EARTH_RADIUS_KM = 6371.0088;
|
|
4791
|
+
function deviceFamilies(userAgent) {
|
|
4792
|
+
const parsed = parseUserAgent(typeof userAgent === "string" ? userAgent.slice(0, 500) : "");
|
|
4793
|
+
return {
|
|
4794
|
+
browser: String(parsed.browserName || "unknown"),
|
|
4795
|
+
os: String(parsed.osName || "unknown"),
|
|
4796
|
+
deviceType: String(parsed.deviceType || "unknown")
|
|
4797
|
+
};
|
|
4798
|
+
}
|
|
4799
|
+
function family(value) {
|
|
4800
|
+
return String(value || "unknown").replace(/\s+[\d.]+$/, "").trim();
|
|
4801
|
+
}
|
|
4802
|
+
function deviceKeyOf(userAgent, deviceId) {
|
|
4803
|
+
const { browser, os, deviceType } = deviceFamilies(userAgent);
|
|
4804
|
+
const id = typeof deviceId === "string" && deviceId.length <= 128 ? deviceId : "";
|
|
4805
|
+
return crypto.createHmac("sha256", derivePurposeKey("device")).update(`${browser}|${os}|${deviceType}|${id}`).digest("hex").slice(0, 32);
|
|
4806
|
+
}
|
|
4807
|
+
function requestDeviceId(ctx) {
|
|
4808
|
+
const value = ctx?.request?.body?.deviceId;
|
|
4809
|
+
return typeof value === "string" && value && value.length <= 128 ? value : null;
|
|
4810
|
+
}
|
|
4811
|
+
function distanceKm(a, b) {
|
|
4812
|
+
const rad = (deg) => deg * Math.PI / 180;
|
|
4813
|
+
const dLat = rad(b.lat - a.lat);
|
|
4814
|
+
const dLon = rad(b.lon - a.lon);
|
|
4815
|
+
const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
|
|
4816
|
+
return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)));
|
|
4817
|
+
}
|
|
4818
|
+
function pointOf(geo) {
|
|
4819
|
+
const lat = Number(geo?.latitude);
|
|
4820
|
+
const lon = Number(geo?.longitude);
|
|
4821
|
+
if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
|
|
4822
|
+
return null;
|
|
4823
|
+
}
|
|
4824
|
+
if (geo?.latitude === null || geo?.longitude === null) return null;
|
|
4825
|
+
return { lat: Math.round(lat * 10) / 10, lon: Math.round(lon * 10) / 10 };
|
|
4826
|
+
}
|
|
4827
|
+
function evaluateTravel(previous, current, { speedKmh, minDistanceKm }) {
|
|
4828
|
+
if (!previous?.point || !current?.point) return null;
|
|
4829
|
+
const km = distanceKm(previous.point, current.point);
|
|
4830
|
+
const hours = Math.max(current.at - previous.at, 60 * 1e3) / (60 * 60 * 1e3);
|
|
4831
|
+
const speed = km / hours;
|
|
4832
|
+
return {
|
|
4833
|
+
flagged: km >= minDistanceKm && speed > speedKmh,
|
|
4834
|
+
distanceKm: Math.round(km),
|
|
4835
|
+
speedKmh: Math.round(speed)
|
|
4836
|
+
};
|
|
4837
|
+
}
|
|
4838
|
+
async function previousSessions(strapi2, userDocumentId, exceptSessionId) {
|
|
4839
|
+
const rows = await strapi2.documents(SESSION_UID).findMany({
|
|
4840
|
+
filters: { user: { documentId: userDocumentId }, documentId: { $ne: exceptSessionId } },
|
|
4841
|
+
fields: [
|
|
4842
|
+
"documentId",
|
|
4843
|
+
"loginTime",
|
|
4844
|
+
"deviceKey",
|
|
4845
|
+
"browserName",
|
|
4846
|
+
"osName",
|
|
4847
|
+
"deviceType",
|
|
4848
|
+
"geoLocation"
|
|
4849
|
+
],
|
|
4850
|
+
sort: [{ loginTime: "desc" }, { id: "desc" }],
|
|
4851
|
+
limit: HISTORY
|
|
4852
|
+
});
|
|
4853
|
+
return Array.isArray(rows) ? rows : [];
|
|
4854
|
+
}
|
|
4855
|
+
function isNewDevice(previous, { deviceKey, userAgent }) {
|
|
4856
|
+
if (previous.length === 0) return false;
|
|
4857
|
+
if (previous.some((row) => row.deviceKey && row.deviceKey === deviceKey)) return false;
|
|
4858
|
+
const families = deviceFamilies(userAgent);
|
|
4859
|
+
return !previous.some(
|
|
4860
|
+
(row) => !row.deviceKey && family(row.browserName) === families.browser && family(row.osName) === families.os
|
|
4861
|
+
);
|
|
4862
|
+
}
|
|
4863
|
+
function storedLocation(row) {
|
|
4864
|
+
let geo = row?.geoLocation;
|
|
4865
|
+
if (typeof geo === "string") {
|
|
3495
4866
|
try {
|
|
3496
|
-
|
|
4867
|
+
geo = JSON.parse(geo);
|
|
3497
4868
|
} catch {
|
|
4869
|
+
geo = null;
|
|
3498
4870
|
}
|
|
4871
|
+
}
|
|
4872
|
+
return {
|
|
4873
|
+
point: pointOf(geo),
|
|
4874
|
+
country: typeof geo?.country_code === "string" ? geo.country_code : null
|
|
4875
|
+
};
|
|
4876
|
+
}
|
|
4877
|
+
async function notMeUrl(strapi2, sessionId, userId) {
|
|
4878
|
+
const base = String(strapi2.config.get("server.absoluteUrl") || "").replace(/\/+$/, "");
|
|
4879
|
+
if (!/^https?:\/\/[^/]+/.test(base)) return null;
|
|
4880
|
+
const token = await issueNotMeToken(getCoordinator(strapi2), { sessionId, userId });
|
|
4881
|
+
if (!token) return null;
|
|
4882
|
+
const prefix = normalizeApiPrefix(strapi2.config.get("api.rest.prefix", "/api"));
|
|
4883
|
+
return `${base}${prefix}/magic-sessionmanager/not-me?token=${encodeURIComponent(token)}`;
|
|
4884
|
+
}
|
|
4885
|
+
async function runSignInSignals({
|
|
4886
|
+
strapi: strapi2,
|
|
4887
|
+
settings,
|
|
4888
|
+
user,
|
|
4889
|
+
userDocumentId,
|
|
4890
|
+
session,
|
|
4891
|
+
geoData,
|
|
4892
|
+
deviceKey,
|
|
4893
|
+
userAgent,
|
|
4894
|
+
ip,
|
|
4895
|
+
record,
|
|
4896
|
+
now = Date.now()
|
|
4897
|
+
}) {
|
|
4898
|
+
const outcome = { newDevice: false, travel: null, reauthenticate: false };
|
|
4899
|
+
const detection = resolveDetectionSettings(settings);
|
|
4900
|
+
const plugin = strapi2.plugin("magic-sessionmanager");
|
|
4901
|
+
const emails = settings.enableEmailAlerts === true;
|
|
4902
|
+
const hasWebhookTarget = detection.genericWebhookEnabled && !!detection.genericWebhookUrl || settings.enableWebhooks === true && !!(settings.discordWebhookUrl || settings.slackWebhookUrl);
|
|
4903
|
+
const wantNewDevice = emails && detection.alertOnNewDevice || hasWebhookTarget && detection.webhookEvents.includes("login.new_device");
|
|
4904
|
+
const wantTravel = detection.impossibleTravelEnabled;
|
|
4905
|
+
if (!wantNewDevice && !wantTravel || !session?.documentId) return outcome;
|
|
4906
|
+
const previous = await previousSessions(strapi2, userDocumentId, session.documentId);
|
|
4907
|
+
const families = deviceFamilies(userAgent);
|
|
4908
|
+
let link;
|
|
4909
|
+
const linkOnce = async () => {
|
|
4910
|
+
if (link === void 0) link = await notMeUrl(strapi2, session.documentId, userDocumentId);
|
|
4911
|
+
return link;
|
|
3499
4912
|
};
|
|
4913
|
+
const notifications = plugin.service("notifications");
|
|
4914
|
+
const facts = { user, session, geoData, device: { browser: families.browser, os: families.os } };
|
|
4915
|
+
if (wantNewDevice && isNewDevice(previous, { deviceKey, userAgent })) {
|
|
4916
|
+
outcome.newDevice = true;
|
|
4917
|
+
record({
|
|
4918
|
+
event: SECURITY_EVENTS.USER_NEW_DEVICE,
|
|
4919
|
+
actorType: "user",
|
|
4920
|
+
actorId: userDocumentId,
|
|
4921
|
+
targetType: "user",
|
|
4922
|
+
targetId: userDocumentId,
|
|
4923
|
+
ip,
|
|
4924
|
+
userAgent,
|
|
4925
|
+
meta: { browser: families.browser, os: families.os, deviceType: families.deviceType }
|
|
4926
|
+
});
|
|
4927
|
+
if (emails && detection.alertOnNewDevice) {
|
|
4928
|
+
const url = await linkOnce();
|
|
4929
|
+
notifications.sendSignInSignalEmail("newDevice", { ...facts, link: url }).catch(() => {
|
|
4930
|
+
});
|
|
4931
|
+
}
|
|
4932
|
+
}
|
|
4933
|
+
if (wantTravel) {
|
|
4934
|
+
const before = previous.find((row) => storedLocation(row).point);
|
|
4935
|
+
const result = before ? evaluateTravel(
|
|
4936
|
+
{ point: storedLocation(before).point, at: new Date(before.loginTime).getTime() },
|
|
4937
|
+
{ point: pointOf(geoData), at: now },
|
|
4938
|
+
{
|
|
4939
|
+
speedKmh: detection.impossibleTravelSpeedKmh,
|
|
4940
|
+
minDistanceKm: detection.impossibleTravelMinDistanceKm
|
|
4941
|
+
}
|
|
4942
|
+
) : null;
|
|
4943
|
+
if (result?.flagged) {
|
|
4944
|
+
outcome.travel = result;
|
|
4945
|
+
record({
|
|
4946
|
+
event: SECURITY_EVENTS.USER_IMPOSSIBLE_TRAVEL,
|
|
4947
|
+
actorType: "user",
|
|
4948
|
+
actorId: userDocumentId,
|
|
4949
|
+
targetType: "user",
|
|
4950
|
+
targetId: userDocumentId,
|
|
4951
|
+
ip,
|
|
4952
|
+
userAgent,
|
|
4953
|
+
meta: {
|
|
4954
|
+
distanceKm: result.distanceKm,
|
|
4955
|
+
speedKmh: result.speedKmh,
|
|
4956
|
+
from: storedLocation(before).country,
|
|
4957
|
+
to: typeof geoData?.country_code === "string" ? geoData.country_code : null,
|
|
4958
|
+
action: detection.impossibleTravelAction
|
|
4959
|
+
}
|
|
4960
|
+
});
|
|
4961
|
+
if (emails && detection.alertOnImpossibleTravel) {
|
|
4962
|
+
const url = await linkOnce();
|
|
4963
|
+
notifications.sendSignInSignalEmail("impossibleTravel", { ...facts, travel: result, link: url }).catch(() => {
|
|
4964
|
+
});
|
|
4965
|
+
}
|
|
4966
|
+
outcome.reauthenticate = detection.impossibleTravelAction === "reauthenticate";
|
|
4967
|
+
}
|
|
4968
|
+
}
|
|
4969
|
+
return outcome;
|
|
3500
4970
|
}
|
|
3501
4971
|
module2.exports = {
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
4972
|
+
notMeUrl,
|
|
4973
|
+
runSignInSignals,
|
|
4974
|
+
deviceFamilies,
|
|
4975
|
+
deviceKeyOf,
|
|
4976
|
+
distanceKm,
|
|
4977
|
+
evaluateTravel,
|
|
4978
|
+
isNewDevice,
|
|
4979
|
+
pointOf,
|
|
4980
|
+
previousSessions,
|
|
4981
|
+
requestDeviceId,
|
|
4982
|
+
storedLocation
|
|
3507
4983
|
};
|
|
3508
4984
|
}
|
|
3509
4985
|
});
|
|
@@ -7602,12 +9078,7 @@ var require_bootstrap = __commonJS({
|
|
|
7602
9078
|
var { REVOCATION_UID } = require_session_revocation();
|
|
7603
9079
|
var { getNativeSessionManager } = require_native_session_manager();
|
|
7604
9080
|
var { CONTENT_API_PERMISSIONS_VERSION } = require_content_api_permissions();
|
|
7605
|
-
var {
|
|
7606
|
-
getCoordinator,
|
|
7607
|
-
hashedKey,
|
|
7608
|
-
initCoordination,
|
|
7609
|
-
LockTimeoutError
|
|
7610
|
-
} = require_coordination();
|
|
9081
|
+
var { getCoordinator, initCoordination, LockTimeoutError } = require_coordination();
|
|
7611
9082
|
var { removeLegacyLicenseData, withPluginStoreKey } = require_plugin_store();
|
|
7612
9083
|
var {
|
|
7613
9084
|
normalizeApiPrefix,
|
|
@@ -7637,8 +9108,28 @@ var require_bootstrap = __commonJS({
|
|
|
7637
9108
|
migrateSecurityLog,
|
|
7638
9109
|
warnUnboundedProxyTrust
|
|
7639
9110
|
} = require_security_log_hardening();
|
|
9111
|
+
var { createLoginLockout } = require_login_lockout();
|
|
9112
|
+
var {
|
|
9113
|
+
accountThresholdFor,
|
|
9114
|
+
inactivityTimeoutFor,
|
|
9115
|
+
hasRoleOverride,
|
|
9116
|
+
resolveLockoutPolicy
|
|
9117
|
+
} = require_policy_settings();
|
|
9118
|
+
var {
|
|
9119
|
+
createAddressCap,
|
|
9120
|
+
createRefusalDedup,
|
|
9121
|
+
createSessionWithinLimit,
|
|
9122
|
+
displayIp,
|
|
9123
|
+
findAccountByIdentifier,
|
|
9124
|
+
readSignInIdentifier,
|
|
9125
|
+
recordUserEvent,
|
|
9126
|
+
refusalReasonOfGeoDecision
|
|
9127
|
+
} = require_sign_in_policies();
|
|
9128
|
+
var { SECURITY_EVENTS, USER_SIGN_IN_EVENTS } = require_security_log_model();
|
|
9129
|
+
var { applyUpgradeDefaults } = require_upgrade_defaults();
|
|
9130
|
+
var { deviceKeyOf, requestDeviceId, runSignInSignals } = require_sign_in_signals();
|
|
9131
|
+
var { anonymizeIp, normalizeIp } = require_admin_request_info();
|
|
7640
9132
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
7641
|
-
var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
|
|
7642
9133
|
var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
7643
9134
|
var JOB_LEASES = Object.freeze({
|
|
7644
9135
|
idleCleanup: "job:idle-cleanup",
|
|
@@ -7680,6 +9171,11 @@ var require_bootstrap = __commonJS({
|
|
|
7680
9171
|
try {
|
|
7681
9172
|
const coordinator = await initCoordination(strapi2, log);
|
|
7682
9173
|
await checkEncryptionKeyConsistency(strapi2, log);
|
|
9174
|
+
try {
|
|
9175
|
+
await applyUpgradeDefaults(strapi2, log);
|
|
9176
|
+
} catch (err) {
|
|
9177
|
+
log.warn("[UPGRADE] Previous defaults could not be kept:", err?.name || "Error");
|
|
9178
|
+
}
|
|
7683
9179
|
await ensureSessionLookupIndexes(strapi2, log);
|
|
7684
9180
|
await registerSessionAwareAuthStrategy(strapi2);
|
|
7685
9181
|
await removeLegacyLicenseRows(strapi2, log);
|
|
@@ -7841,6 +9337,27 @@ var require_bootstrap = __commonJS({
|
|
|
7841
9337
|
}
|
|
7842
9338
|
}
|
|
7843
9339
|
function mountPreLoginGeoGuard({ strapi: strapi2, log }) {
|
|
9340
|
+
const shouldRecordRefusal = createRefusalDedup();
|
|
9341
|
+
const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
|
|
9342
|
+
const recordRefusal = async (ctx, settings, ip, decisionReason) => {
|
|
9343
|
+
if (!resolveLockoutPolicy(settings).record) return;
|
|
9344
|
+
const reason = refusalReasonOfGeoDecision(decisionReason);
|
|
9345
|
+
const identifier = readSignInIdentifier(ctx);
|
|
9346
|
+
if (!shouldRecordRefusal(`${reason}|${ip}|${identifier || ""}`)) return;
|
|
9347
|
+
const account = await findAccountByIdentifier(strapi2, identifier).catch(() => null);
|
|
9348
|
+
if (!account && !shouldRecordUnknownAccount(`refused|${anonymizeIp(normalizeIp(ip || "")) || "none"}`)) {
|
|
9349
|
+
return;
|
|
9350
|
+
}
|
|
9351
|
+
recordUserEvent(strapi2, {
|
|
9352
|
+
event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
|
|
9353
|
+
actorType: "user",
|
|
9354
|
+
targetType: "user",
|
|
9355
|
+
targetId: account?.documentId || null,
|
|
9356
|
+
ip,
|
|
9357
|
+
userAgent: ctx.request?.headers?.["user-agent"] || null,
|
|
9358
|
+
meta: { reason }
|
|
9359
|
+
});
|
|
9360
|
+
};
|
|
7844
9361
|
strapi2.server.use(async (ctx, next) => {
|
|
7845
9362
|
if (!shouldRunPreAuthGeoGuard(apiPathOf(strapi2, ctx), ctx.method)) {
|
|
7846
9363
|
return next();
|
|
@@ -7860,6 +9377,7 @@ var require_bootstrap = __commonJS({
|
|
|
7860
9377
|
const decision = evaluateGeoFirewall(settings, geoData);
|
|
7861
9378
|
if (decision.blocked) {
|
|
7862
9379
|
log.warn(`[PRE-BLOCKED] Login rejected (${decision.reason})`);
|
|
9380
|
+
await recordRefusal(ctx, settings, ip, decision.reason);
|
|
7863
9381
|
ctx.status = 403;
|
|
7864
9382
|
ctx.body = {
|
|
7865
9383
|
error: {
|
|
@@ -7878,6 +9396,7 @@ var require_bootstrap = __commonJS({
|
|
|
7878
9396
|
const failureDecision = evaluateGeoFirewall(settings, { _status: "error" });
|
|
7879
9397
|
if (failureDecision.blocked) {
|
|
7880
9398
|
log.warn("[PRE-BLOCKED] Login rejected because GeoIP lookup failed");
|
|
9399
|
+
await recordRefusal(ctx, settings, ip, "geo_lookup_unavailable:error");
|
|
7881
9400
|
ctx.status = 403;
|
|
7882
9401
|
ctx.body = {
|
|
7883
9402
|
error: {
|
|
@@ -8077,53 +9596,95 @@ var require_bootstrap = __commonJS({
|
|
|
8077
9596
|
}
|
|
8078
9597
|
}
|
|
8079
9598
|
function mountFailedLoginLockout({ strapi: strapi2, log }) {
|
|
8080
|
-
const
|
|
8081
|
-
const
|
|
8082
|
-
const
|
|
9599
|
+
const lockout = createLoginLockout(getCoordinator(strapi2));
|
|
9600
|
+
const shouldRecordRefusal = createRefusalDedup();
|
|
9601
|
+
const shouldRecordUnknownAccount = createRefusalDedup({ windowMs: 5 * 60 * 1e3 });
|
|
9602
|
+
const underAddressCap = createAddressCap();
|
|
9603
|
+
const unknownAccountKey = (ip) => `unknown|${anonymizeIp(normalizeIp(ip || "")) || "none"}`;
|
|
8083
9604
|
strapi2.server.use(async (ctx, next) => {
|
|
8084
9605
|
if (!isFailedLoginTrackedPath(apiPathOf(strapi2, ctx), ctx.method)) return next();
|
|
8085
9606
|
const settings = await getRequestSettings(strapi2, ctx);
|
|
8086
|
-
const
|
|
8087
|
-
|
|
8088
|
-
|
|
8089
|
-
|
|
8090
|
-
const
|
|
8091
|
-
const
|
|
8092
|
-
|
|
9607
|
+
const policy = resolveLockoutPolicy(settings);
|
|
9608
|
+
const accountPossible = policy.accountMax > 0 || policy.accountMaxByRole;
|
|
9609
|
+
if (policy.ipMax <= 0 && !accountPossible && !policy.record) return next();
|
|
9610
|
+
const rawIp = getClientIp(ctx);
|
|
9611
|
+
const ip = rawIp && rawIp !== "unknown" ? rawIp : null;
|
|
9612
|
+
const identifier = readSignInIdentifier(ctx);
|
|
9613
|
+
const userAgent = ctx.request?.headers?.["user-agent"] || null;
|
|
9614
|
+
let account;
|
|
9615
|
+
const loadAccount = async () => {
|
|
9616
|
+
if (account !== void 0) return account;
|
|
9617
|
+
let found = null;
|
|
9618
|
+
if (identifier) {
|
|
9619
|
+
try {
|
|
9620
|
+
found = await findAccountByIdentifier(strapi2, identifier);
|
|
9621
|
+
} catch (err) {
|
|
9622
|
+
log.debug("[LOCKOUT] Account lookup failed:", err?.name || "Error");
|
|
9623
|
+
}
|
|
9624
|
+
}
|
|
9625
|
+
account = found;
|
|
9626
|
+
return account;
|
|
9627
|
+
};
|
|
9628
|
+
if (policy.accountMaxByRole) await loadAccount();
|
|
9629
|
+
const accountMax = accountThresholdFor(settings, account?.role || null);
|
|
9630
|
+
const event = (name, meta) => {
|
|
9631
|
+
const signInFamily = USER_SIGN_IN_EVENTS.includes(name);
|
|
9632
|
+
if (signInFamily && !policy.record) return false;
|
|
9633
|
+
if (signInFamily && !underAddressCap(ip)) return false;
|
|
9634
|
+
return recordUserEvent(strapi2, {
|
|
9635
|
+
event: name,
|
|
9636
|
+
actorType: "user",
|
|
9637
|
+
actorId: null,
|
|
9638
|
+
targetType: "user",
|
|
9639
|
+
targetId: account?.documentId || null,
|
|
9640
|
+
ip,
|
|
9641
|
+
userAgent,
|
|
9642
|
+
meta
|
|
9643
|
+
});
|
|
9644
|
+
};
|
|
9645
|
+
const refusedOnce = (reason, meta) => {
|
|
9646
|
+
if (!policy.record) return;
|
|
9647
|
+
if (!account) {
|
|
9648
|
+
if (!shouldRecordUnknownAccount(`refused|${unknownAccountKey(ip)}`)) return;
|
|
9649
|
+
event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, unknownAccount: true, ...meta });
|
|
9650
|
+
return;
|
|
9651
|
+
}
|
|
9652
|
+
if (!shouldRecordRefusal(`${reason}|${ip || ""}|${identifier || ""}`)) return;
|
|
9653
|
+
event(SECURITY_EVENTS.USER_SIGN_IN_REFUSED, { reason, ...meta });
|
|
9654
|
+
};
|
|
9655
|
+
let decision;
|
|
8093
9656
|
try {
|
|
8094
|
-
|
|
9657
|
+
decision = await lockout.reserve({ ip, identifier, policy, accountMax });
|
|
8095
9658
|
} catch (err) {
|
|
8096
|
-
log.debug("[LOCKOUT] Counter
|
|
9659
|
+
log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
|
|
9660
|
+
decision = {
|
|
9661
|
+
outcome: "allow",
|
|
9662
|
+
retryAfter: 0,
|
|
9663
|
+
lockedKind: null,
|
|
9664
|
+
reservation: { ipKey: null, ipHits: 0, accountKey: null, accountHits: 0 }
|
|
9665
|
+
};
|
|
8097
9666
|
}
|
|
8098
|
-
|
|
8099
|
-
ctx.set("Retry-After", String(
|
|
8100
|
-
log.warn(
|
|
9667
|
+
if (decision.outcome === "locked") {
|
|
9668
|
+
ctx.set("Retry-After", String(decision.retryAfter));
|
|
9669
|
+
log.warn(
|
|
9670
|
+
`[LOCKOUT] Rejected sign-in from a locked client (${decision.retryAfter}s remaining)`
|
|
9671
|
+
);
|
|
9672
|
+
if (policy.record) await loadAccount();
|
|
9673
|
+
refusedOnce("lockout", { lock: decision.lockedKind });
|
|
8101
9674
|
ctx.status = 429;
|
|
8102
9675
|
ctx.body = {
|
|
8103
9676
|
error: {
|
|
8104
9677
|
status: 429,
|
|
8105
9678
|
name: "TooManyRequestsError",
|
|
8106
9679
|
message: "Too many failed login attempts. Please try again later.",
|
|
8107
|
-
details: { retryAfter:
|
|
9680
|
+
details: { retryAfter: decision.retryAfter }
|
|
8108
9681
|
}
|
|
8109
9682
|
};
|
|
8110
|
-
};
|
|
8111
|
-
if (existing && existing.blockedUntil > now) {
|
|
8112
|
-
rejectLocked(Math.ceil((existing.blockedUntil - now) / 1e3));
|
|
8113
9683
|
return;
|
|
8114
9684
|
}
|
|
8115
|
-
|
|
8116
|
-
|
|
8117
|
-
|
|
8118
|
-
} catch (err) {
|
|
8119
|
-
log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
|
|
8120
|
-
}
|
|
8121
|
-
if (reserved && reserved.hits > maxFailed) {
|
|
8122
|
-
try {
|
|
8123
|
-
await coordinator.release(key);
|
|
8124
|
-
} catch (err) {
|
|
8125
|
-
log.debug("[LOCKOUT] Counter release failed:", err?.name || "Error");
|
|
8126
|
-
}
|
|
9685
|
+
if (decision.outcome === "busy") {
|
|
9686
|
+
if (policy.record) await loadAccount();
|
|
9687
|
+
refusedOnce("too-many-attempts", {});
|
|
8127
9688
|
ctx.set("Retry-After", "1");
|
|
8128
9689
|
ctx.status = 429;
|
|
8129
9690
|
ctx.body = {
|
|
@@ -8143,18 +9704,43 @@ var require_bootstrap = __commonJS({
|
|
|
8143
9704
|
thrown = err;
|
|
8144
9705
|
}
|
|
8145
9706
|
const status = thrown ? statusOfThrownError(thrown) : ctx.status;
|
|
9707
|
+
const result = !thrown && status === 200 && ctx.body && ctx.body.jwt ? "success" : status >= 400 && status < 500 && status !== 429 ? "failure" : "neutral";
|
|
9708
|
+
if (result === "failure") {
|
|
9709
|
+
if (policy.record || decision.reservation.accountKey) await loadAccount();
|
|
9710
|
+
if (account) {
|
|
9711
|
+
event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status });
|
|
9712
|
+
} else if (shouldRecordUnknownAccount(`failed|${unknownAccountKey(ip)}`)) {
|
|
9713
|
+
event(SECURITY_EVENTS.USER_SIGN_IN_FAILED, { status, unknownAccount: true });
|
|
9714
|
+
}
|
|
9715
|
+
}
|
|
8146
9716
|
try {
|
|
8147
|
-
|
|
8148
|
-
|
|
8149
|
-
|
|
8150
|
-
|
|
8151
|
-
|
|
8152
|
-
|
|
8153
|
-
|
|
8154
|
-
|
|
9717
|
+
const locks = await lockout.settle(decision.reservation, result, {
|
|
9718
|
+
policy,
|
|
9719
|
+
accountMax,
|
|
9720
|
+
display: {
|
|
9721
|
+
ip: displayIp(settings, ip),
|
|
9722
|
+
userDocumentId: account?.documentId || null
|
|
9723
|
+
}
|
|
9724
|
+
});
|
|
9725
|
+
for (const lock of locks) {
|
|
9726
|
+
const minutes = Math.round(policy.durationMs / 6e4);
|
|
9727
|
+
log.warn(
|
|
9728
|
+
`[LOCKOUT] ${lock.kind === "ip" ? "Client" : "Account"} locked for ${minutes}min after ${lock.failures} failed sign-ins`
|
|
9729
|
+
);
|
|
9730
|
+
event(SECURITY_EVENTS.USER_LOCKOUT, {
|
|
9731
|
+
kind: lock.kind,
|
|
9732
|
+
failures: lock.failures,
|
|
9733
|
+
minutes
|
|
9734
|
+
});
|
|
9735
|
+
if (lock.kind === "account" && policy.notifyUser && account?.email) {
|
|
9736
|
+
const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
|
|
9737
|
+
notifications.sendAccountLockedEmail({
|
|
9738
|
+
user: account,
|
|
9739
|
+
minutes,
|
|
9740
|
+
until: lock.until
|
|
9741
|
+
}).catch(() => {
|
|
9742
|
+
});
|
|
8155
9743
|
}
|
|
8156
|
-
} else if (reserved) {
|
|
8157
|
-
await coordinator.release(key);
|
|
8158
9744
|
}
|
|
8159
9745
|
} catch (err) {
|
|
8160
9746
|
log.debug("[LOCKOUT] Counter update failed:", err?.name || "Error");
|
|
@@ -8181,6 +9767,54 @@ var require_bootstrap = __commonJS({
|
|
|
8181
9767
|
};
|
|
8182
9768
|
return byName[err?.name] || 500;
|
|
8183
9769
|
}
|
|
9770
|
+
function optionalService(strapi2, name) {
|
|
9771
|
+
try {
|
|
9772
|
+
return strapi2.plugin("magic-sessionmanager").service(name) || null;
|
|
9773
|
+
} catch {
|
|
9774
|
+
return null;
|
|
9775
|
+
}
|
|
9776
|
+
}
|
|
9777
|
+
function refuseSessionLimit({ ctx, strapi: strapi2, limit }) {
|
|
9778
|
+
stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
|
|
9779
|
+
ctx.status = 403;
|
|
9780
|
+
ctx.body = {
|
|
9781
|
+
data: null,
|
|
9782
|
+
error: {
|
|
9783
|
+
status: 403,
|
|
9784
|
+
name: "ForbiddenError",
|
|
9785
|
+
message: "Too many active sessions. Sign out on another device and try again.",
|
|
9786
|
+
details: { code: "SESSION_LIMIT_REACHED", limit }
|
|
9787
|
+
}
|
|
9788
|
+
};
|
|
9789
|
+
}
|
|
9790
|
+
async function endOtherSessionsAfterPasswordChange({
|
|
9791
|
+
strapi: strapi2,
|
|
9792
|
+
ctx,
|
|
9793
|
+
log,
|
|
9794
|
+
sessionService,
|
|
9795
|
+
userDocumentId,
|
|
9796
|
+
currentSessionId
|
|
9797
|
+
}) {
|
|
9798
|
+
const settings = await getPluginSettings(strapi2);
|
|
9799
|
+
if (settings.endOtherSessionsOnPasswordChange !== true) return;
|
|
9800
|
+
if (!userDocumentId) throw new Error("password change owner could not be resolved");
|
|
9801
|
+
const { terminatedCount } = await sessionService.terminateSession({
|
|
9802
|
+
userId: userDocumentId,
|
|
9803
|
+
exceptSessionId: currentSessionId,
|
|
9804
|
+
reason: "logout"
|
|
9805
|
+
});
|
|
9806
|
+
recordUserEvent(strapi2, {
|
|
9807
|
+
event: SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED,
|
|
9808
|
+
actorType: "user",
|
|
9809
|
+
actorId: userDocumentId,
|
|
9810
|
+
targetType: "user",
|
|
9811
|
+
targetId: userDocumentId,
|
|
9812
|
+
ip: getClientIp(ctx),
|
|
9813
|
+
userAgent: ctx.request?.headers?.["user-agent"] || null,
|
|
9814
|
+
meta: { ended: Number(terminatedCount) || 0 }
|
|
9815
|
+
});
|
|
9816
|
+
log.info("[PASSWORD] Ended the other sessions after a password change");
|
|
9817
|
+
}
|
|
8184
9818
|
function mountLoginInterceptor({ strapi: strapi2, log, sessionService }) {
|
|
8185
9819
|
strapi2.server.use(async (ctx, next) => {
|
|
8186
9820
|
const apiPath = apiPathOf(strapi2, ctx);
|
|
@@ -8231,6 +9865,7 @@ var require_bootstrap = __commonJS({
|
|
|
8231
9865
|
filters: { tokenHash: hashToken(previousAccessToken), isActive: true },
|
|
8232
9866
|
fields: ["documentId"]
|
|
8233
9867
|
});
|
|
9868
|
+
let currentSidecarId;
|
|
8234
9869
|
if (matchingSession) {
|
|
8235
9870
|
const rotated = await sessionService.rotateSessionTokens({
|
|
8236
9871
|
sessionId: matchingSession.documentId,
|
|
@@ -8241,6 +9876,7 @@ var require_bootstrap = __commonJS({
|
|
|
8241
9876
|
});
|
|
8242
9877
|
if (!rotated)
|
|
8243
9878
|
throw new Error("current sidecar changed before native password rotation was linked");
|
|
9879
|
+
currentSidecarId = matchingSession.documentId;
|
|
8244
9880
|
log.info("[PASSWORD] Native session link updated");
|
|
8245
9881
|
} else {
|
|
8246
9882
|
const userAgent = ctx.request.headers?.["user-agent"] || "unknown";
|
|
@@ -8256,7 +9892,16 @@ var require_bootstrap = __commonJS({
|
|
|
8256
9892
|
if (!createdSidecar?.documentId) {
|
|
8257
9893
|
throw new Error("native password-change sidecar creation returned no documentId");
|
|
8258
9894
|
}
|
|
9895
|
+
currentSidecarId = createdSidecar.documentId;
|
|
8259
9896
|
}
|
|
9897
|
+
await endOtherSessionsAfterPasswordChange({
|
|
9898
|
+
strapi: strapi2,
|
|
9899
|
+
ctx,
|
|
9900
|
+
log,
|
|
9901
|
+
sessionService,
|
|
9902
|
+
userDocumentId: nativeSession2.userDocumentId,
|
|
9903
|
+
currentSessionId: currentSidecarId
|
|
9904
|
+
});
|
|
8260
9905
|
} catch (err) {
|
|
8261
9906
|
if (nativeSessionManager2 && nativeSession2) {
|
|
8262
9907
|
await compensateNativeSession({ nativeSessionManager: nativeSessionManager2, nativeSession: nativeSession2, log });
|
|
@@ -8293,8 +9938,21 @@ var require_bootstrap = __commonJS({
|
|
|
8293
9938
|
accessToken: ctx.body.jwt,
|
|
8294
9939
|
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName)
|
|
8295
9940
|
});
|
|
8296
|
-
if (!rotated) throw new Error("current session changed before token rotation");
|
|
8297
|
-
log.info("[PASSWORD] Legacy session tokens rotated");
|
|
9941
|
+
if (!rotated) throw new Error("current session changed before token rotation");
|
|
9942
|
+
log.info("[PASSWORD] Legacy session tokens rotated");
|
|
9943
|
+
const owner = await strapi2.documents(SESSION_UID).findOne({
|
|
9944
|
+
documentId: matchingSession.documentId,
|
|
9945
|
+
fields: ["documentId"],
|
|
9946
|
+
populate: { user: { fields: ["documentId"] } }
|
|
9947
|
+
});
|
|
9948
|
+
await endOtherSessionsAfterPasswordChange({
|
|
9949
|
+
strapi: strapi2,
|
|
9950
|
+
ctx,
|
|
9951
|
+
log,
|
|
9952
|
+
sessionService,
|
|
9953
|
+
userDocumentId: owner?.user?.documentId || null,
|
|
9954
|
+
currentSessionId: matchingSession.documentId
|
|
9955
|
+
});
|
|
8298
9956
|
} catch (err) {
|
|
8299
9957
|
failClosedAuthResponse({
|
|
8300
9958
|
ctx,
|
|
@@ -8337,19 +9995,58 @@ var require_bootstrap = __commonJS({
|
|
|
8337
9995
|
throw new Error(`could not resolve documentId for user ${user.id || "unknown"}`);
|
|
8338
9996
|
}
|
|
8339
9997
|
const geoData = ctx.state?.__magicSessionGeoData || null;
|
|
8340
|
-
const
|
|
9998
|
+
const requestSettings = await getPluginSettings(strapi2);
|
|
9999
|
+
const isReset = isPasswordResetRequest(apiPath, ctx.method);
|
|
10000
|
+
const deviceKey = deviceKeyOf(userAgent, requestDeviceId(ctx));
|
|
10001
|
+
const create = () => sessionService.createSession({
|
|
8341
10002
|
userId: userDocId,
|
|
8342
10003
|
ip,
|
|
8343
10004
|
userAgent,
|
|
8344
10005
|
token: ctx.body.jwt,
|
|
8345
10006
|
refreshToken: getOutgoingRefreshToken(ctx, refreshCookieName),
|
|
8346
10007
|
geoData,
|
|
10008
|
+
deviceKey,
|
|
8347
10009
|
...nativeSession ? { nativeSessionId: nativeSession.sessionId } : {}
|
|
8348
10010
|
});
|
|
10011
|
+
const limited = isReset ? { session: await create(), refused: false, ended: 0, limit: 0 } : await createSessionWithinLimit({
|
|
10012
|
+
strapi: strapi2,
|
|
10013
|
+
settings: requestSettings,
|
|
10014
|
+
userDocumentId: userDocId,
|
|
10015
|
+
create,
|
|
10016
|
+
sessionService
|
|
10017
|
+
});
|
|
10018
|
+
const newSession = limited.session;
|
|
8349
10019
|
if (!newSession?.documentId) {
|
|
8350
10020
|
throw new Error(`session creation returned no documentId for user ${userDocId}`);
|
|
8351
10021
|
}
|
|
8352
|
-
if (
|
|
10022
|
+
if (limited.refused) {
|
|
10023
|
+
recordUserEvent(strapi2, {
|
|
10024
|
+
event: SECURITY_EVENTS.USER_SIGN_IN_REFUSED,
|
|
10025
|
+
actorType: "user",
|
|
10026
|
+
actorId: userDocId,
|
|
10027
|
+
targetType: "user",
|
|
10028
|
+
targetId: userDocId,
|
|
10029
|
+
ip,
|
|
10030
|
+
userAgent,
|
|
10031
|
+
meta: { reason: "session-limit", limit: limited.limit }
|
|
10032
|
+
});
|
|
10033
|
+
refuseSessionLimit({ ctx, strapi: strapi2, limit: limited.limit });
|
|
10034
|
+
log.info("[LIMIT] Sign-in refused: the user reached the session limit");
|
|
10035
|
+
return;
|
|
10036
|
+
}
|
|
10037
|
+
if (limited.ended > 0) {
|
|
10038
|
+
recordUserEvent(strapi2, {
|
|
10039
|
+
event: SECURITY_EVENTS.USER_SESSION_LIMIT,
|
|
10040
|
+
actorType: "system",
|
|
10041
|
+
targetType: "user",
|
|
10042
|
+
targetId: userDocId,
|
|
10043
|
+
ip,
|
|
10044
|
+
userAgent,
|
|
10045
|
+
meta: { ended: limited.ended, limit: limited.limit }
|
|
10046
|
+
});
|
|
10047
|
+
log.info(`[LIMIT] Ended ${limited.ended} older session(s) to stay within the limit`);
|
|
10048
|
+
}
|
|
10049
|
+
if (isReset) {
|
|
8353
10050
|
await sessionService.terminateSession({
|
|
8354
10051
|
userId: userDocId,
|
|
8355
10052
|
exceptSessionId: newSession.documentId,
|
|
@@ -8358,9 +10055,45 @@ var require_bootstrap = __commonJS({
|
|
|
8358
10055
|
log.info("[PASSWORD] Ended older sessions after password reset");
|
|
8359
10056
|
}
|
|
8360
10057
|
log.info("[SUCCESS] End-user session metadata created");
|
|
10058
|
+
let signals = { reauthenticate: false };
|
|
10059
|
+
if (!isReset) {
|
|
10060
|
+
try {
|
|
10061
|
+
signals = await runSignInSignals({
|
|
10062
|
+
strapi: strapi2,
|
|
10063
|
+
settings: requestSettings,
|
|
10064
|
+
user,
|
|
10065
|
+
userDocumentId: userDocId,
|
|
10066
|
+
session: newSession,
|
|
10067
|
+
geoData,
|
|
10068
|
+
deviceKey,
|
|
10069
|
+
userAgent: userAgent === "unknown" ? null : userAgent,
|
|
10070
|
+
ip,
|
|
10071
|
+
record: (input) => recordUserEvent(strapi2, input)
|
|
10072
|
+
});
|
|
10073
|
+
} catch (signalErr) {
|
|
10074
|
+
log.warn("[SIGNALS] Sign-in signals failed (non-fatal):", signalErr?.name || "Error");
|
|
10075
|
+
}
|
|
10076
|
+
}
|
|
10077
|
+
if (signals.reauthenticate) {
|
|
10078
|
+
await sessionService.terminateSession({ userId: userDocId, reason: "manual" });
|
|
10079
|
+
stripAuthTokensFromResponse(ctx, getRefreshCookieName(strapi2));
|
|
10080
|
+
ctx.status = 401;
|
|
10081
|
+
ctx.body = {
|
|
10082
|
+
data: null,
|
|
10083
|
+
error: {
|
|
10084
|
+
status: 401,
|
|
10085
|
+
name: "UnauthorizedError",
|
|
10086
|
+
message: "Please sign in again.",
|
|
10087
|
+
details: { code: "REAUTHENTICATION_REQUIRED" }
|
|
10088
|
+
}
|
|
10089
|
+
};
|
|
10090
|
+
log.info("[SIGNALS] Impossible travel: every session ended, a new sign-in is required");
|
|
10091
|
+
return;
|
|
10092
|
+
}
|
|
8361
10093
|
try {
|
|
8362
10094
|
const settings = await getPluginSettings(strapi2);
|
|
8363
|
-
|
|
10095
|
+
const genericWebhook = settings.genericWebhookEnabled === true;
|
|
10096
|
+
if (!geoData || !(settings.enableEmailAlerts || settings.enableWebhooks || genericWebhook)) {
|
|
8364
10097
|
return;
|
|
8365
10098
|
}
|
|
8366
10099
|
const notificationService = strapi2.plugin("magic-sessionmanager").service("notifications");
|
|
@@ -8412,7 +10145,8 @@ var require_bootstrap = __commonJS({
|
|
|
8412
10145
|
user,
|
|
8413
10146
|
session: newSession,
|
|
8414
10147
|
geoData,
|
|
8415
|
-
isNewLocation
|
|
10148
|
+
isNewLocation,
|
|
10149
|
+
webhooks: optionalService(strapi2, "webhooks")
|
|
8416
10150
|
});
|
|
8417
10151
|
} catch (notifErr) {
|
|
8418
10152
|
log.warn("Notification failed:", notifErr?.name || "Error");
|
|
@@ -8750,7 +10484,7 @@ var require_bootstrap = __commonJS({
|
|
|
8750
10484
|
);
|
|
8751
10485
|
return false;
|
|
8752
10486
|
}
|
|
8753
|
-
const
|
|
10487
|
+
const baseActions = [
|
|
8754
10488
|
"plugin::magic-sessionmanager.session.logout",
|
|
8755
10489
|
"plugin::magic-sessionmanager.session.logoutAll",
|
|
8756
10490
|
"plugin::magic-sessionmanager.session.logoutOthers",
|
|
@@ -8759,6 +10493,8 @@ var require_bootstrap = __commonJS({
|
|
|
8759
10493
|
"plugin::magic-sessionmanager.session.getCurrentSession",
|
|
8760
10494
|
"plugin::magic-sessionmanager.session.terminateOwnSession"
|
|
8761
10495
|
];
|
|
10496
|
+
const version3Actions = ["plugin::magic-sessionmanager.self-service.exportOwnData"];
|
|
10497
|
+
const requiredActions = Number(effectiveVersion) === 2 ? version3Actions : [...baseActions, ...version3Actions];
|
|
8762
10498
|
const existingPermissions = await strapi2.documents(PERMISSION_UID).findMany({
|
|
8763
10499
|
filters: {
|
|
8764
10500
|
role: authenticatedRole.id,
|
|
@@ -9040,11 +10776,13 @@ var require_bootstrap = __commonJS({
|
|
|
9040
10776
|
strapi2.log.debug("[magic-sessionmanager] [JWT] No documentId found in relaxed mode");
|
|
9041
10777
|
return decoded;
|
|
9042
10778
|
}
|
|
10779
|
+
const needsRole = hasRoleOverride(settings, "inactivityTimeout");
|
|
9043
10780
|
let userRecord;
|
|
9044
10781
|
try {
|
|
9045
10782
|
userRecord = await strapi2.documents("plugin::users-permissions.user").findOne({
|
|
9046
10783
|
documentId: userDocId,
|
|
9047
|
-
fields: ["documentId", "blocked"]
|
|
10784
|
+
fields: ["documentId", "blocked"],
|
|
10785
|
+
...needsRole ? { populate: { role: { fields: ["documentId"] } } } : {}
|
|
9048
10786
|
});
|
|
9049
10787
|
} catch (err) {
|
|
9050
10788
|
if (strictMode) {
|
|
@@ -9113,7 +10851,10 @@ var require_bootstrap = __commonJS({
|
|
|
9113
10851
|
setSessionRejectionReason(tokenHashValue, "expired");
|
|
9114
10852
|
return null;
|
|
9115
10853
|
}
|
|
9116
|
-
const inactivityTimeout =
|
|
10854
|
+
const inactivityTimeout = inactivityTimeoutFor(
|
|
10855
|
+
settings,
|
|
10856
|
+
userRecord?.role?.documentId || null
|
|
10857
|
+
);
|
|
9117
10858
|
const lastActiveMs = thisSession.lastActive ? new Date(thisSession.lastActive).getTime() : thisSession.loginTime ? new Date(thisSession.loginTime).getTime() : 0;
|
|
9118
10859
|
const idleFor = Date.now() - lastActiveMs;
|
|
9119
10860
|
if (idleFor > inactivityTimeout) {
|
|
@@ -9268,6 +11009,11 @@ var require_destroy = __commonJS({
|
|
|
9268
11009
|
}
|
|
9269
11010
|
strapi2.sessionManagerAdminActivityUninstall = null;
|
|
9270
11011
|
}
|
|
11012
|
+
try {
|
|
11013
|
+
strapi2.plugin("magic-sessionmanager")?.service("webhooks")?.stop?.();
|
|
11014
|
+
} catch (err) {
|
|
11015
|
+
log.warn("Failed to stop webhook deliveries:", err?.name || "Error");
|
|
11016
|
+
}
|
|
9271
11017
|
log.info("[SUCCESS] Plugin cleanup completed");
|
|
9272
11018
|
};
|
|
9273
11019
|
}
|
|
@@ -9309,6 +11055,9 @@ var require_config = __commonJS({
|
|
|
9309
11055
|
discordWebhookUrl: "",
|
|
9310
11056
|
slackWebhookUrl: "",
|
|
9311
11057
|
trustedProxies: null,
|
|
11058
|
+
// Sign-in and session policies (4.17). Existing installations keep
|
|
11059
|
+
// `endOtherSessionsOnPasswordChange: false` (utils/upgrade-defaults.js).
|
|
11060
|
+
endOtherSessionsOnPasswordChange: true,
|
|
9312
11061
|
// Cross-process state for pm2 cluster / several replicas. `enabled:
|
|
9313
11062
|
// false` keeps every counter, lease and cache per process (the pre-4.10
|
|
9314
11063
|
// behaviour). `counterStore` may supply an object with async
|
|
@@ -9479,6 +11228,12 @@ var require_schema = __commonJS({
|
|
|
9479
11228
|
},
|
|
9480
11229
|
osName: {
|
|
9481
11230
|
type: "string"
|
|
11231
|
+
},
|
|
11232
|
+
deviceKey: {
|
|
11233
|
+
type: "string",
|
|
11234
|
+
maxLength: 64,
|
|
11235
|
+
configurable: false,
|
|
11236
|
+
private: true
|
|
9482
11237
|
}
|
|
9483
11238
|
}
|
|
9484
11239
|
};
|
|
@@ -9719,6 +11474,57 @@ var require_content_api = __commonJS({
|
|
|
9719
11474
|
description: "Get sessions by userId (user can only see own sessions)"
|
|
9720
11475
|
}
|
|
9721
11476
|
},
|
|
11477
|
+
// ================== SELF-SERVICE (4.17) ==================
|
|
11478
|
+
{
|
|
11479
|
+
method: "GET",
|
|
11480
|
+
path: "/my-data",
|
|
11481
|
+
handler: "self-service.exportOwnData",
|
|
11482
|
+
config: {
|
|
11483
|
+
auth: { strategies: ["users-permissions"] },
|
|
11484
|
+
// An export reads every own session and event: 3 per hour per user.
|
|
11485
|
+
middlewares: [
|
|
11486
|
+
{
|
|
11487
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11488
|
+
config: { max: 3, window: 60 * 60 * 1e3 }
|
|
11489
|
+
}
|
|
11490
|
+
],
|
|
11491
|
+
description: "Download own sessions and security events as JSON (GDPR Art. 15)"
|
|
11492
|
+
}
|
|
11493
|
+
},
|
|
11494
|
+
{
|
|
11495
|
+
method: "GET",
|
|
11496
|
+
path: "/not-me",
|
|
11497
|
+
handler: "self-service.notMePage",
|
|
11498
|
+
config: {
|
|
11499
|
+
// Public on purpose: opened from the "This wasn't me" email. Only
|
|
11500
|
+
// shows a confirmation; the signed token is checked, nothing changes.
|
|
11501
|
+
auth: false,
|
|
11502
|
+
middlewares: [
|
|
11503
|
+
{
|
|
11504
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11505
|
+
config: { max: 30, window: 6e4 }
|
|
11506
|
+
}
|
|
11507
|
+
],
|
|
11508
|
+
description: `Confirmation page of the "This wasn't me" email link (public)`
|
|
11509
|
+
}
|
|
11510
|
+
},
|
|
11511
|
+
{
|
|
11512
|
+
method: "POST",
|
|
11513
|
+
path: "/not-me",
|
|
11514
|
+
handler: "self-service.notMeConfirm",
|
|
11515
|
+
config: {
|
|
11516
|
+
// Public on purpose: the signed, expiring, single-use token from the
|
|
11517
|
+
// email is the authorisation.
|
|
11518
|
+
auth: false,
|
|
11519
|
+
middlewares: [
|
|
11520
|
+
{
|
|
11521
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11522
|
+
config: { max: 10, window: 6e4 }
|
|
11523
|
+
}
|
|
11524
|
+
],
|
|
11525
|
+
description: `End the session of a "This wasn't me" link (public, single-use token)`
|
|
11526
|
+
}
|
|
11527
|
+
},
|
|
9722
11528
|
// ================== OWN SESSION MANAGEMENT ==================
|
|
9723
11529
|
{
|
|
9724
11530
|
method: "DELETE",
|
|
@@ -9743,6 +11549,8 @@ var require_admin = __commonJS({
|
|
|
9743
11549
|
var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
|
|
9744
11550
|
var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
|
|
9745
11551
|
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
11552
|
+
var LOCKOUTS_UNLOCK_ACTION = "plugin::magic-sessionmanager.lockouts.unlock";
|
|
11553
|
+
var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
|
|
9746
11554
|
var adminPolicy = () => [
|
|
9747
11555
|
"admin::isAuthenticatedAdmin",
|
|
9748
11556
|
{
|
|
@@ -9996,6 +11804,54 @@ var require_admin = __commonJS({
|
|
|
9996
11804
|
description: "Get one export batch of Content Manager activity of admins (admin)"
|
|
9997
11805
|
}
|
|
9998
11806
|
},
|
|
11807
|
+
// ===================== SIGN-IN LOCKS AND ROLE RULES =====================
|
|
11808
|
+
{
|
|
11809
|
+
method: "GET",
|
|
11810
|
+
path: "/lockouts",
|
|
11811
|
+
handler: "lockouts.list",
|
|
11812
|
+
config: {
|
|
11813
|
+
policies: adminPolicy(),
|
|
11814
|
+
middlewares: adminReadRateLimit(),
|
|
11815
|
+
description: "List the active sign-in locks (admin)"
|
|
11816
|
+
}
|
|
11817
|
+
},
|
|
11818
|
+
{
|
|
11819
|
+
method: "POST",
|
|
11820
|
+
path: "/lockouts/unlock",
|
|
11821
|
+
handler: "lockouts.unlock",
|
|
11822
|
+
config: {
|
|
11823
|
+
policies: adminSessionsPolicy([LOCKOUTS_UNLOCK_ACTION]),
|
|
11824
|
+
middlewares: adminSignOutRateLimit(),
|
|
11825
|
+
description: "Lift one sign-in lock (admin)"
|
|
11826
|
+
}
|
|
11827
|
+
},
|
|
11828
|
+
{
|
|
11829
|
+
method: "GET",
|
|
11830
|
+
path: "/roles",
|
|
11831
|
+
handler: "lockouts.roles",
|
|
11832
|
+
config: {
|
|
11833
|
+
policies: adminPolicy(),
|
|
11834
|
+
middlewares: adminReadRateLimit(),
|
|
11835
|
+
description: "List Users & Permissions roles for per-role rules (admin)"
|
|
11836
|
+
}
|
|
11837
|
+
},
|
|
11838
|
+
// ============================ SIGNED WEBHOOK ============================
|
|
11839
|
+
{
|
|
11840
|
+
method: "POST",
|
|
11841
|
+
path: "/webhook/test",
|
|
11842
|
+
handler: "webhooks.sendTest",
|
|
11843
|
+
config: {
|
|
11844
|
+
// Sends to the stored URL: same permission as changing it.
|
|
11845
|
+
policies: adminSessionsPolicy([SETTINGS_UPDATE_ACTION]),
|
|
11846
|
+
middlewares: [
|
|
11847
|
+
{
|
|
11848
|
+
name: "plugin::magic-sessionmanager.rate-limit",
|
|
11849
|
+
config: { profile: "write", max: 5, window: 6e4 }
|
|
11850
|
+
}
|
|
11851
|
+
],
|
|
11852
|
+
description: "Send a signed test event to the stored webhook URL (admin)"
|
|
11853
|
+
}
|
|
11854
|
+
},
|
|
9999
11855
|
// ============================ GEOLOCATION ============================
|
|
10000
11856
|
{
|
|
10001
11857
|
method: "GET",
|
|
@@ -12328,6 +14184,8 @@ var require_settings_access = __commonJS({
|
|
|
12328
14184
|
"server/src/utils/settings-access.js"(exports2, module2) {
|
|
12329
14185
|
"use strict";
|
|
12330
14186
|
var { SECURITY_LOG_KEYS } = require_security_log_settings();
|
|
14187
|
+
var { POLICY_KEYS } = require_policy_settings();
|
|
14188
|
+
var { PROTECTED_DETECTION_KEYS } = require_detection_settings();
|
|
12331
14189
|
var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
|
|
12332
14190
|
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
12333
14191
|
var GEO_SETTINGS_KEYS = Object.freeze([
|
|
@@ -12344,11 +14202,20 @@ var require_settings_access = __commonJS({
|
|
|
12344
14202
|
var PROTECTED_SETTINGS_KEYS = Object.freeze([
|
|
12345
14203
|
...GEO_SETTINGS_KEYS,
|
|
12346
14204
|
...WEBHOOK_SETTINGS_KEYS,
|
|
12347
|
-
...SECURITY_LOG_KEYS
|
|
14205
|
+
...SECURITY_LOG_KEYS,
|
|
14206
|
+
// Sign-in and session policies (lockout, trusted addresses, session
|
|
14207
|
+
// limit, password-change sign-out, recording switch, per-role rules).
|
|
14208
|
+
...POLICY_KEYS,
|
|
14209
|
+
// Signed webhook, event selection, impossible travel and shortened IPs.
|
|
14210
|
+
...PROTECTED_DETECTION_KEYS
|
|
12348
14211
|
]);
|
|
12349
14212
|
var WEBHOOK_SECRETS = Object.freeze([
|
|
12350
14213
|
{ key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
|
|
12351
|
-
{ key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" }
|
|
14214
|
+
{ key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" },
|
|
14215
|
+
{ key: "genericWebhookUrl", has: "hasGenericWebhook", hint: "genericWebhookHint" }
|
|
14216
|
+
]);
|
|
14217
|
+
var WRITE_ONLY_SECRETS = Object.freeze([
|
|
14218
|
+
{ key: "genericWebhookSecret", has: "hasGenericWebhookSecret" }
|
|
12352
14219
|
]);
|
|
12353
14220
|
function sameValue(a, b) {
|
|
12354
14221
|
if (a === b) return true;
|
|
@@ -12396,6 +14263,11 @@ var require_settings_access = __commonJS({
|
|
|
12396
14263
|
out[has] = typeof value === "string" && value.trim().length > 0;
|
|
12397
14264
|
out[hint] = webhookHint(value);
|
|
12398
14265
|
}
|
|
14266
|
+
for (const { key, has } of WRITE_ONLY_SECRETS) {
|
|
14267
|
+
const value = out[key];
|
|
14268
|
+
delete out[key];
|
|
14269
|
+
out[has] = typeof value === "string" && value.length > 0;
|
|
14270
|
+
}
|
|
12399
14271
|
return out;
|
|
12400
14272
|
}
|
|
12401
14273
|
module2.exports = {
|
|
@@ -12405,6 +14277,7 @@ var require_settings_access = __commonJS({
|
|
|
12405
14277
|
SETTINGS_UPDATE_ACTION,
|
|
12406
14278
|
WEBHOOK_SECRETS,
|
|
12407
14279
|
WEBHOOK_SETTINGS_KEYS,
|
|
14280
|
+
WRITE_ONLY_SECRETS,
|
|
12408
14281
|
callerCan,
|
|
12409
14282
|
changedKeys,
|
|
12410
14283
|
missingSettingsPermission,
|
|
@@ -12437,6 +14310,10 @@ var require_settings = __commonJS({
|
|
|
12437
14310
|
missingSettingsPermission,
|
|
12438
14311
|
toPublicSettings
|
|
12439
14312
|
} = require_settings_access();
|
|
14313
|
+
var { POLICY_DEFAULTS, validatePolicySettings } = require_policy_settings();
|
|
14314
|
+
var { DETECTION_DEFAULTS, validateDetectionSettings } = require_detection_settings();
|
|
14315
|
+
var { encryptToken } = require_encryption();
|
|
14316
|
+
var WEBHOOK_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
|
|
12440
14317
|
var path = require("node:path");
|
|
12441
14318
|
var ALLOWED_WEBHOOK_DOMAINS = {
|
|
12442
14319
|
discord: ["discord.com", "discordapp.com"],
|
|
@@ -12468,11 +14345,9 @@ var require_settings = __commonJS({
|
|
|
12468
14345
|
}
|
|
12469
14346
|
}
|
|
12470
14347
|
function sanitizeEmailTemplates(templates) {
|
|
12471
|
-
const defaults =
|
|
12472
|
-
|
|
12473
|
-
|
|
12474
|
-
vpnProxy: { subject: "", html: "", text: "" }
|
|
12475
|
-
};
|
|
14348
|
+
const defaults = Object.fromEntries(
|
|
14349
|
+
Object.keys(DEFAULT_EMAIL_TEMPLATES).map((key) => [key, { subject: "", html: "", text: "" }])
|
|
14350
|
+
);
|
|
12476
14351
|
if (!templates || typeof templates !== "object") return defaults;
|
|
12477
14352
|
let sanitizeHtml;
|
|
12478
14353
|
try {
|
|
@@ -12578,7 +14453,11 @@ var require_settings = __commonJS({
|
|
|
12578
14453
|
var DEFAULT_EMAIL_TEMPLATES = {
|
|
12579
14454
|
suspiciousLogin: { subject: "", html: "", text: "" },
|
|
12580
14455
|
newLocation: { subject: "", html: "", text: "" },
|
|
12581
|
-
vpnProxy: { subject: "", html: "", text: "" }
|
|
14456
|
+
vpnProxy: { subject: "", html: "", text: "" },
|
|
14457
|
+
// 4.17: sent to a user whose account was locked after failed sign-ins.
|
|
14458
|
+
accountLocked: { subject: "", html: "", text: "" },
|
|
14459
|
+
newDevice: { subject: "", html: "", text: "" },
|
|
14460
|
+
impossibleTravel: { subject: "", html: "", text: "" }
|
|
12582
14461
|
};
|
|
12583
14462
|
var DEFAULT_SETTINGS = {
|
|
12584
14463
|
inactivityTimeout: 15,
|
|
@@ -12611,7 +14490,13 @@ var require_settings = __commonJS({
|
|
|
12611
14490
|
strictSessionEnforcement: false,
|
|
12612
14491
|
trustedProxies: false,
|
|
12613
14492
|
emailTemplates: DEFAULT_EMAIL_TEMPLATES,
|
|
12614
|
-
...SECURITY_LOG_DEFAULTS
|
|
14493
|
+
...SECURITY_LOG_DEFAULTS,
|
|
14494
|
+
...POLICY_DEFAULTS,
|
|
14495
|
+
lockoutTrustedAddresses: [],
|
|
14496
|
+
roleRules: [],
|
|
14497
|
+
...DETECTION_DEFAULTS,
|
|
14498
|
+
webhookEvents: [...DETECTION_DEFAULTS.webhookEvents],
|
|
14499
|
+
genericWebhookSecret: ""
|
|
12615
14500
|
};
|
|
12616
14501
|
function mergeSettingsWithDefaults(stored) {
|
|
12617
14502
|
const safeStored = stored && typeof stored === "object" ? stored : {};
|
|
@@ -12819,6 +14704,25 @@ var require_settings = __commonJS({
|
|
|
12819
14704
|
const securityLog = validateSecurityLogSettings(body);
|
|
12820
14705
|
errors.push(...securityLog.errors);
|
|
12821
14706
|
Object.assign(next, securityLog.values);
|
|
14707
|
+
const policies2 = validatePolicySettings(body);
|
|
14708
|
+
errors.push(...policies2.errors);
|
|
14709
|
+
Object.assign(next, policies2.values);
|
|
14710
|
+
const detection = validateDetectionSettings(body);
|
|
14711
|
+
errors.push(...detection.errors);
|
|
14712
|
+
Object.assign(next, detection.values);
|
|
14713
|
+
if (has("genericWebhookSecret")) {
|
|
14714
|
+
const secret = body.genericWebhookSecret;
|
|
14715
|
+
if (secret === "") {
|
|
14716
|
+
next.genericWebhookSecret = "";
|
|
14717
|
+
} else if (typeof secret !== "string" || !WEBHOOK_SECRET_PATTERN.test(secret)) {
|
|
14718
|
+
errors.push({
|
|
14719
|
+
path: ["genericWebhookSecret"],
|
|
14720
|
+
message: "genericWebhookSecret must be 32 to 256 printable characters without spaces"
|
|
14721
|
+
});
|
|
14722
|
+
} else {
|
|
14723
|
+
next.genericWebhookSecret = encryptToken(secret);
|
|
14724
|
+
}
|
|
14725
|
+
}
|
|
12822
14726
|
if (errors.length > 0) return { errors };
|
|
12823
14727
|
const settings = {};
|
|
12824
14728
|
for (const key of Object.keys(DEFAULT_SETTINGS)) {
|
|
@@ -12848,7 +14752,7 @@ var require_settings = __commonJS({
|
|
|
12848
14752
|
}
|
|
12849
14753
|
var FORBIDDEN_MESSAGES = Object.freeze({
|
|
12850
14754
|
"admin-activity-permission": 'Changing the security log settings needs "View admin activity".',
|
|
12851
|
-
"settings-update-permission": 'Changing location lookup, webhook
|
|
14755
|
+
"settings-update-permission": 'Changing location lookup, webhook, security log, sign-in policy or detection settings needs "Change protected settings".'
|
|
12852
14756
|
});
|
|
12853
14757
|
function recordSettingsChange(ctx, keys) {
|
|
12854
14758
|
if (!keys.length) return;
|
|
@@ -12868,6 +14772,16 @@ var require_settings = __commonJS({
|
|
|
12868
14772
|
} catch {
|
|
12869
14773
|
}
|
|
12870
14774
|
}
|
|
14775
|
+
async function findUnknownRoles(rules) {
|
|
14776
|
+
if (!Array.isArray(rules) || rules.length === 0) return [];
|
|
14777
|
+
const ids = rules.map((rule) => rule.role);
|
|
14778
|
+
const rows = await strapi.db.query("plugin::users-permissions.role").findMany({ where: { documentId: { $in: ids } }, select: ["documentId"] });
|
|
14779
|
+
const known = new Set((Array.isArray(rows) ? rows : []).map((row) => row.documentId));
|
|
14780
|
+
return rules.map((rule, index) => known.has(rule.role) ? null : index).filter((index) => index !== null).map((index) => ({
|
|
14781
|
+
path: ["roleRules", index, "role"],
|
|
14782
|
+
message: "This role does not exist any more"
|
|
14783
|
+
}));
|
|
14784
|
+
}
|
|
12871
14785
|
module2.exports = {
|
|
12872
14786
|
/**
|
|
12873
14787
|
* Returns current plugin settings in user-facing units. Legacy custom MMDB
|
|
@@ -12952,6 +14866,8 @@ var require_settings = __commonJS({
|
|
|
12952
14866
|
};
|
|
12953
14867
|
const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
|
|
12954
14868
|
if (errors.length > 0) return { errors };
|
|
14869
|
+
const roleErrors = await findUnknownRoles(sanitizedSettings.roleRules);
|
|
14870
|
+
if (roleErrors.length > 0) return { errors: roleErrors };
|
|
12955
14871
|
const changed = changedKeys(
|
|
12956
14872
|
{
|
|
12957
14873
|
...sanitizedSettings,
|
|
@@ -13007,6 +14923,7 @@ var require_settings = __commonJS({
|
|
|
13007
14923
|
},
|
|
13008
14924
|
DEFAULT_SETTINGS,
|
|
13009
14925
|
mergeSettingsWithDefaults,
|
|
14926
|
+
toPublicSettings,
|
|
13010
14927
|
validateSettingsUpdate
|
|
13011
14928
|
};
|
|
13012
14929
|
}
|
|
@@ -14324,23 +16241,490 @@ var require_admin_activity = __commonJS({
|
|
|
14324
16241
|
);
|
|
14325
16242
|
},
|
|
14326
16243
|
/**
|
|
14327
|
-
* One export batch (500 rows, keyset cursor) of Content Manager activity.
|
|
16244
|
+
* One export batch (500 rows, keyset cursor) of Content Manager activity.
|
|
16245
|
+
*
|
|
16246
|
+
* @route GET /magic-sessionmanager/admin-activity/content/export
|
|
16247
|
+
* @auth As listContentActivity.
|
|
16248
|
+
* @param {Context} ctx Same filters as the list, plus `cursor`.
|
|
16249
|
+
* @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
|
|
16250
|
+
*/
|
|
16251
|
+
async exportContentActivity(ctx) {
|
|
16252
|
+
return handle(
|
|
16253
|
+
ctx,
|
|
16254
|
+
activityExportSchema,
|
|
16255
|
+
(query) => {
|
|
16256
|
+
auditTokenRead(ctx, "content", true);
|
|
16257
|
+
return service().exportBatch("content", query, query.cursor || null, viewerOf(ctx));
|
|
16258
|
+
},
|
|
16259
|
+
"activity export"
|
|
16260
|
+
);
|
|
16261
|
+
}
|
|
16262
|
+
};
|
|
16263
|
+
};
|
|
16264
|
+
}
|
|
16265
|
+
});
|
|
16266
|
+
|
|
16267
|
+
// server/src/controllers/lockouts.js
|
|
16268
|
+
var require_lockouts = __commonJS({
|
|
16269
|
+
"server/src/controllers/lockouts.js"(exports2, module2) {
|
|
16270
|
+
"use strict";
|
|
16271
|
+
var { getCoordinator } = require_coordination();
|
|
16272
|
+
var { LOCK_ID_PATTERN, createLoginLockout } = require_login_lockout();
|
|
16273
|
+
var { getRequestIp, getRequestUserAgent } = require_admin_request_info();
|
|
16274
|
+
var { SECURITY_EVENTS } = require_security_log_model();
|
|
16275
|
+
var { sendServerError, sendValidationError } = require_http_errors();
|
|
16276
|
+
var { createLogger } = require_logger();
|
|
16277
|
+
var USER_UID = "plugin::users-permissions.user";
|
|
16278
|
+
var ROLE_UID = "plugin::users-permissions.role";
|
|
16279
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
16280
|
+
const log = createLogger(strapi2);
|
|
16281
|
+
const lockout = () => createLoginLockout(getCoordinator(strapi2));
|
|
16282
|
+
return {
|
|
16283
|
+
/**
|
|
16284
|
+
* Lists the active sign-in locks: locked IP addresses (shown as the
|
|
16285
|
+
* security log stores IPs) and locked accounts with their user.
|
|
16286
|
+
*
|
|
16287
|
+
* @route GET /magic-sessionmanager/lockouts
|
|
16288
|
+
* @auth admin session or admin API token
|
|
16289
|
+
* @access plugin::magic-sessionmanager.access
|
|
16290
|
+
* @param {any} ctx Koa context.
|
|
16291
|
+
* @returns {Promise<void>} `{ data: Lock[], meta: { total } }`; 500 on store failure.
|
|
16292
|
+
*/
|
|
16293
|
+
async list(ctx) {
|
|
16294
|
+
try {
|
|
16295
|
+
const locks = await lockout().listLocks();
|
|
16296
|
+
const ids = [...new Set(locks.map((lock) => lock.user).filter(Boolean))];
|
|
16297
|
+
const users = ids.length ? await strapi2.db.query(USER_UID).findMany({
|
|
16298
|
+
where: { documentId: { $in: ids } },
|
|
16299
|
+
select: ["documentId", "username", "email"]
|
|
16300
|
+
}) : [];
|
|
16301
|
+
const byId = new Map(
|
|
16302
|
+
(Array.isArray(users) ? users : []).map((user) => [user.documentId, user])
|
|
16303
|
+
);
|
|
16304
|
+
const data = locks.map((lock) => {
|
|
16305
|
+
const user = lock.user ? byId.get(lock.user) : null;
|
|
16306
|
+
return {
|
|
16307
|
+
id: lock.id,
|
|
16308
|
+
kind: lock.kind,
|
|
16309
|
+
ip: lock.kind === "ip" ? lock.ip : null,
|
|
16310
|
+
user: user ? { documentId: user.documentId, username: user.username, email: user.email } : null,
|
|
16311
|
+
failures: lock.failures,
|
|
16312
|
+
lockedAt: new Date(lock.lockedAt).toISOString(),
|
|
16313
|
+
until: new Date(lock.until).toISOString()
|
|
16314
|
+
};
|
|
16315
|
+
});
|
|
16316
|
+
ctx.body = { data, meta: { total: data.length } };
|
|
16317
|
+
} catch (err) {
|
|
16318
|
+
log.error("[lockouts] List failed:", err?.name || "Error");
|
|
16319
|
+
return sendServerError(ctx, 500, "Locks could not be loaded");
|
|
16320
|
+
}
|
|
16321
|
+
},
|
|
16322
|
+
/**
|
|
16323
|
+
* Lifts one lock. The admin who lifted it is recorded in the security log.
|
|
16324
|
+
*
|
|
16325
|
+
* @route POST /magic-sessionmanager/lockouts/unlock
|
|
16326
|
+
* @auth admin session or admin API token
|
|
16327
|
+
* @access plugin::magic-sessionmanager.access + plugin::magic-sessionmanager.lockouts.unlock
|
|
16328
|
+
* @param {any} ctx Koa context; body `{ id }` from the list.
|
|
16329
|
+
* @returns {Promise<void>} `{ data: { unlocked: true, kind } }`; 400 invalid id; 404 not locked.
|
|
16330
|
+
* @sideeffect Deletes the shared lock counter and list entry; writes `user.lockout.lifted`.
|
|
16331
|
+
*/
|
|
16332
|
+
async unlock(ctx) {
|
|
16333
|
+
const body = ctx.request?.body;
|
|
16334
|
+
const id = body && typeof body === "object" && !Array.isArray(body) ? body.id : void 0;
|
|
16335
|
+
const extra = body && typeof body === "object" ? Object.keys(body).filter((key) => key !== "id") : [];
|
|
16336
|
+
if (typeof id !== "string" || !LOCK_ID_PATTERN.test(id) || extra.length > 0) {
|
|
16337
|
+
return sendValidationError(ctx, "Invalid lock", [
|
|
16338
|
+
{ path: ["id"], message: "id must be a lock id from the list" }
|
|
16339
|
+
]);
|
|
16340
|
+
}
|
|
16341
|
+
try {
|
|
16342
|
+
const lifted = await lockout().unlock(id);
|
|
16343
|
+
if (!lifted) return ctx.notFound("This lock has already ended");
|
|
16344
|
+
try {
|
|
16345
|
+
const liftEvent = {
|
|
16346
|
+
event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
|
|
16347
|
+
actorType: "admin",
|
|
16348
|
+
actorId: ctx.state?.user?.id ?? null,
|
|
16349
|
+
targetType: lifted.kind === "account" ? "user" : "ip",
|
|
16350
|
+
targetId: lifted.kind === "account" ? lifted.user : null,
|
|
16351
|
+
meta: { kind: lifted.kind }
|
|
16352
|
+
};
|
|
16353
|
+
strapi2.plugin("magic-sessionmanager").service("webhooks")?.emitSecurityEvent?.(liftEvent);
|
|
16354
|
+
strapi2.plugin("magic-sessionmanager").service("security-log").record({
|
|
16355
|
+
event: SECURITY_EVENTS.USER_LOCKOUT_LIFTED,
|
|
16356
|
+
actorType: "admin",
|
|
16357
|
+
actorId: ctx.state?.user?.id ?? null,
|
|
16358
|
+
targetType: lifted.kind === "account" ? "user" : "ip",
|
|
16359
|
+
targetId: lifted.kind === "account" ? lifted.user : null,
|
|
16360
|
+
ip: getRequestIp(ctx),
|
|
16361
|
+
userAgent: getRequestUserAgent(ctx),
|
|
16362
|
+
meta: { kind: lifted.kind }
|
|
16363
|
+
});
|
|
16364
|
+
} catch {
|
|
16365
|
+
}
|
|
16366
|
+
ctx.body = { data: { unlocked: true, kind: lifted.kind } };
|
|
16367
|
+
} catch (err) {
|
|
16368
|
+
log.error("[lockouts] Unlock failed:", err?.name || "Error");
|
|
16369
|
+
return sendServerError(ctx, 500, "The lock could not be lifted");
|
|
16370
|
+
}
|
|
16371
|
+
},
|
|
16372
|
+
/**
|
|
16373
|
+
* Users & Permissions roles for the per-role rules (the Public role has
|
|
16374
|
+
* no signed-in users and is left out).
|
|
16375
|
+
*
|
|
16376
|
+
* @route GET /magic-sessionmanager/roles
|
|
16377
|
+
* @auth admin session or admin API token
|
|
16378
|
+
* @access plugin::magic-sessionmanager.access
|
|
16379
|
+
* @param {any} ctx Koa context.
|
|
16380
|
+
* @returns {Promise<void>} `{ data: [{ documentId, name, type }] }`.
|
|
16381
|
+
*/
|
|
16382
|
+
async roles(ctx) {
|
|
16383
|
+
try {
|
|
16384
|
+
const rows = await strapi2.db.query(ROLE_UID).findMany({
|
|
16385
|
+
select: ["documentId", "name", "type"],
|
|
16386
|
+
where: { type: { $ne: "public" } },
|
|
16387
|
+
orderBy: { name: "asc" },
|
|
16388
|
+
limit: 200
|
|
16389
|
+
});
|
|
16390
|
+
ctx.body = {
|
|
16391
|
+
data: (Array.isArray(rows) ? rows : []).map((role) => ({
|
|
16392
|
+
documentId: role.documentId,
|
|
16393
|
+
name: role.name,
|
|
16394
|
+
type: role.type
|
|
16395
|
+
}))
|
|
16396
|
+
};
|
|
16397
|
+
} catch (err) {
|
|
16398
|
+
log.error("[lockouts] Roles could not be listed:", err?.name || "Error");
|
|
16399
|
+
return sendServerError(ctx, 500, "Roles could not be loaded");
|
|
16400
|
+
}
|
|
16401
|
+
}
|
|
16402
|
+
};
|
|
16403
|
+
};
|
|
16404
|
+
}
|
|
16405
|
+
});
|
|
16406
|
+
|
|
16407
|
+
// server/src/controllers/self-service.js
|
|
16408
|
+
var require_self_service = __commonJS({
|
|
16409
|
+
"server/src/controllers/self-service.js"(exports2, module2) {
|
|
16410
|
+
"use strict";
|
|
16411
|
+
var { getCoordinator } = require_coordination();
|
|
16412
|
+
var { consumeNotMeToken, readNotMeToken } = require_not_me_link();
|
|
16413
|
+
var { recordUserEvent } = require_sign_in_policies();
|
|
16414
|
+
var { resolveUserDocumentId } = require_resolve_user();
|
|
16415
|
+
var { SECURITY_EVENTS } = require_security_log_model();
|
|
16416
|
+
var { sendServerError } = require_http_errors();
|
|
16417
|
+
var { createLogger } = require_logger();
|
|
16418
|
+
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
16419
|
+
var EVENT_UID = "plugin::magic-sessionmanager.security-event";
|
|
16420
|
+
var USER_UID = "plugin::users-permissions.user";
|
|
16421
|
+
var EXPORT_LIMIT = 5e3;
|
|
16422
|
+
var EXPORT_BATCH = 500;
|
|
16423
|
+
var PAGE_TEXT = Object.freeze({
|
|
16424
|
+
en: {
|
|
16425
|
+
title: "Was this sign-in not you?",
|
|
16426
|
+
body: "Sign the device of that sign-in out now. Then change your password.",
|
|
16427
|
+
one: "Sign out that device",
|
|
16428
|
+
all: "Sign out everywhere",
|
|
16429
|
+
done: "Done. The session was ended. Change your password now.",
|
|
16430
|
+
doneAll: "Done. Every session of your account was ended. Change your password now.",
|
|
16431
|
+
invalid: "This link is no longer valid. It works once and expires after 72 hours."
|
|
16432
|
+
},
|
|
16433
|
+
de: {
|
|
16434
|
+
title: "Waren Sie das nicht?",
|
|
16435
|
+
body: "Melden Sie das Ger\xE4t dieser Anmeldung jetzt ab. \xC4ndern Sie danach Ihr Passwort.",
|
|
16436
|
+
one: "Dieses Ger\xE4t abmelden",
|
|
16437
|
+
all: "\xDCberall abmelden",
|
|
16438
|
+
done: "Erledigt. Die Sitzung wurde beendet. \xC4ndern Sie jetzt Ihr Passwort.",
|
|
16439
|
+
doneAll: "Erledigt. Alle Sitzungen Ihres Kontos wurden beendet. \xC4ndern Sie jetzt Ihr Passwort.",
|
|
16440
|
+
invalid: "Dieser Link ist nicht mehr g\xFCltig. Er funktioniert einmal und l\xE4uft nach 72 Stunden ab."
|
|
16441
|
+
},
|
|
16442
|
+
fr: {
|
|
16443
|
+
title: "Cette connexion n\u2019\xE9tait pas vous ?",
|
|
16444
|
+
body: "D\xE9connectez maintenant l\u2019appareil de cette connexion, puis changez votre mot de passe.",
|
|
16445
|
+
one: "D\xE9connecter cet appareil",
|
|
16446
|
+
all: "Se d\xE9connecter partout",
|
|
16447
|
+
done: "C\u2019est fait. La session a \xE9t\xE9 termin\xE9e. Changez maintenant votre mot de passe.",
|
|
16448
|
+
doneAll: "C\u2019est fait. Toutes les sessions de votre compte ont \xE9t\xE9 termin\xE9es. Changez maintenant votre mot de passe.",
|
|
16449
|
+
invalid: "Ce lien n\u2019est plus valide. Il fonctionne une fois et expire apr\xE8s 72 heures."
|
|
16450
|
+
},
|
|
16451
|
+
es: {
|
|
16452
|
+
title: "\xBFEste inicio de sesi\xF3n no fue usted?",
|
|
16453
|
+
body: "Cierre ahora la sesi\xF3n del dispositivo de ese inicio de sesi\xF3n y despu\xE9s cambie su contrase\xF1a.",
|
|
16454
|
+
one: "Cerrar la sesi\xF3n de ese dispositivo",
|
|
16455
|
+
all: "Cerrar sesi\xF3n en todas partes",
|
|
16456
|
+
done: "Hecho. La sesi\xF3n ha terminado. Cambie ahora su contrase\xF1a.",
|
|
16457
|
+
doneAll: "Hecho. Todas las sesiones de su cuenta han terminado. Cambie ahora su contrase\xF1a.",
|
|
16458
|
+
invalid: "Este enlace ya no es v\xE1lido. Funciona una vez y caduca a las 72 horas."
|
|
16459
|
+
},
|
|
16460
|
+
pt: {
|
|
16461
|
+
title: "Este in\xEDcio de sess\xE3o n\xE3o foi seu?",
|
|
16462
|
+
body: "Termine agora a sess\xE3o do dispositivo desse in\xEDcio de sess\xE3o e depois altere a sua palavra-passe.",
|
|
16463
|
+
one: "Terminar a sess\xE3o desse dispositivo",
|
|
16464
|
+
all: "Terminar sess\xE3o em todo o lado",
|
|
16465
|
+
done: "Feito. A sess\xE3o foi terminada. Altere agora a sua palavra-passe.",
|
|
16466
|
+
doneAll: "Feito. Todas as sess\xF5es da sua conta foram terminadas. Altere agora a sua palavra-passe.",
|
|
16467
|
+
invalid: "Esta liga\xE7\xE3o j\xE1 n\xE3o \xE9 v\xE1lida. Funciona uma vez e expira ap\xF3s 72 horas."
|
|
16468
|
+
}
|
|
16469
|
+
});
|
|
16470
|
+
function pageLanguage(ctx) {
|
|
16471
|
+
const header = String(ctx.request?.headers?.["accept-language"] || "").slice(0, 200);
|
|
16472
|
+
for (const part of header.split(",")) {
|
|
16473
|
+
const code = part.trim().slice(0, 2).toLowerCase();
|
|
16474
|
+
if (Object.prototype.hasOwnProperty.call(PAGE_TEXT, code)) {
|
|
16475
|
+
return (
|
|
16476
|
+
/** @type {keyof typeof PAGE_TEXT} */
|
|
16477
|
+
code
|
|
16478
|
+
);
|
|
16479
|
+
}
|
|
16480
|
+
}
|
|
16481
|
+
return "en";
|
|
16482
|
+
}
|
|
16483
|
+
var escapeHtml = (value) => String(value ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
16484
|
+
function sendPage(ctx, status, lang, title, body) {
|
|
16485
|
+
ctx.status = status;
|
|
16486
|
+
ctx.set("Content-Type", "text/html; charset=utf-8");
|
|
16487
|
+
ctx.set(
|
|
16488
|
+
"Content-Security-Policy",
|
|
16489
|
+
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
|
|
16490
|
+
);
|
|
16491
|
+
ctx.set("Referrer-Policy", "no-referrer");
|
|
16492
|
+
ctx.set("Cache-Control", "no-store");
|
|
16493
|
+
ctx.set("X-Robots-Tag", "noindex");
|
|
16494
|
+
ctx.body = `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>
|
|
16495
|
+
<style>body{font-family:system-ui,sans-serif;max-width:36rem;margin:3rem auto;padding:0 1rem;line-height:1.5;color:#212134;background:#fff}button{font:inherit;padding:.6rem 1rem;margin:.25rem .5rem .25rem 0;border-radius:4px;border:1px solid #4945ff;background:#4945ff;color:#fff;cursor:pointer}button.secondary{background:#fff;color:#4945ff}@media (prefers-color-scheme:dark){body{background:#181826;color:#eaeaef}button.secondary{background:#181826}}</style></head>
|
|
16496
|
+
<body><main><h1>${escapeHtml(title)}</h1>${body}</main></body></html>`;
|
|
16497
|
+
}
|
|
16498
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
16499
|
+
const log = createLogger(strapi2);
|
|
16500
|
+
return {
|
|
16501
|
+
/**
|
|
16502
|
+
* Confirmation page of the "This wasn't me" link. Uses nothing.
|
|
16503
|
+
*
|
|
16504
|
+
* @route GET /api/magic-sessionmanager/not-me?token=
|
|
16505
|
+
* @auth none (public on purpose: the link is opened from an email; the
|
|
16506
|
+
* signed token is checked, and nothing changes until the POST)
|
|
16507
|
+
* @param {any} ctx Koa context.
|
|
16508
|
+
* @returns {Promise<void>} 200 page with two buttons, or 410 when the link is invalid.
|
|
16509
|
+
*/
|
|
16510
|
+
async notMePage(ctx) {
|
|
16511
|
+
const lang = pageLanguage(ctx);
|
|
16512
|
+
const text = PAGE_TEXT[lang];
|
|
16513
|
+
const token = typeof ctx.query?.token === "string" ? ctx.query.token : "";
|
|
16514
|
+
if (!readNotMeToken(token)) {
|
|
16515
|
+
return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
|
|
16516
|
+
}
|
|
16517
|
+
const form = (scope, label, className) => `<form method="post" style="display:inline"><input type="hidden" name="token" value="${escapeHtml(token)}"><input type="hidden" name="scope" value="${scope}"><button type="submit"${className ? ` class="${className}"` : ""}>${escapeHtml(label)}</button></form>`;
|
|
16518
|
+
return sendPage(
|
|
16519
|
+
ctx,
|
|
16520
|
+
200,
|
|
16521
|
+
lang,
|
|
16522
|
+
text.title,
|
|
16523
|
+
`<p>${escapeHtml(text.body)}</p>${form("session", text.one, "")}${form("all", text.all, "secondary")}`
|
|
16524
|
+
);
|
|
16525
|
+
},
|
|
16526
|
+
/**
|
|
16527
|
+
* Uses a "This wasn't me" token: ends that session, or every session of
|
|
16528
|
+
* the user with `scope=all`, and records `user.not-me`.
|
|
16529
|
+
*
|
|
16530
|
+
* @route POST /api/magic-sessionmanager/not-me
|
|
16531
|
+
* @auth none (public on purpose; the signed single-use token authorises)
|
|
16532
|
+
* @param {any} ctx Koa context; body `{ token, scope?: 'session'|'all' }` (form or JSON).
|
|
16533
|
+
* @returns {Promise<void>} 200 page (or JSON `{ ended }` with Accept: application/json);
|
|
16534
|
+
* 410 when the token is invalid, expired or used.
|
|
16535
|
+
* @sideeffect Ends sessions (and native sessions); writes a security event.
|
|
16536
|
+
*/
|
|
16537
|
+
async notMeConfirm(ctx) {
|
|
16538
|
+
const lang = pageLanguage(ctx);
|
|
16539
|
+
const text = PAGE_TEXT[lang];
|
|
16540
|
+
const wantsJson = String(ctx.request?.headers?.accept || "").includes("application/json");
|
|
16541
|
+
const body = ctx.request?.body && typeof ctx.request.body === "object" ? ctx.request.body : {};
|
|
16542
|
+
const scope = body.scope === "all" ? "all" : "session";
|
|
16543
|
+
const claims = await consumeNotMeToken(getCoordinator(strapi2), body.token);
|
|
16544
|
+
if (!claims) {
|
|
16545
|
+
if (wantsJson) {
|
|
16546
|
+
ctx.status = 410;
|
|
16547
|
+
ctx.body = {
|
|
16548
|
+
data: null,
|
|
16549
|
+
error: { status: 410, name: "GoneError", message: "This link is no longer valid" }
|
|
16550
|
+
};
|
|
16551
|
+
return;
|
|
16552
|
+
}
|
|
16553
|
+
return sendPage(ctx, 410, lang, text.title, `<p>${escapeHtml(text.invalid)}</p>`);
|
|
16554
|
+
}
|
|
16555
|
+
try {
|
|
16556
|
+
const sessionService = strapi2.plugin("magic-sessionmanager").service("session");
|
|
16557
|
+
let ended = 0;
|
|
16558
|
+
if (scope === "all") {
|
|
16559
|
+
ended = Number(
|
|
16560
|
+
(await sessionService.terminateSession({ userId: claims.userId, reason: "manual" }))?.terminatedCount
|
|
16561
|
+
) || 0;
|
|
16562
|
+
} else {
|
|
16563
|
+
const session = await strapi2.documents(SESSION_UID).findFirst({
|
|
16564
|
+
filters: { documentId: claims.sessionId, user: { documentId: claims.userId } },
|
|
16565
|
+
fields: ["documentId", "isActive"]
|
|
16566
|
+
});
|
|
16567
|
+
if (session?.isActive) {
|
|
16568
|
+
ended = Number(
|
|
16569
|
+
(await sessionService.terminateSession({
|
|
16570
|
+
sessionId: session.documentId,
|
|
16571
|
+
reason: "manual"
|
|
16572
|
+
}))?.terminatedCount
|
|
16573
|
+
) || 0;
|
|
16574
|
+
}
|
|
16575
|
+
}
|
|
16576
|
+
recordUserEvent(strapi2, {
|
|
16577
|
+
event: SECURITY_EVENTS.USER_NOT_ME,
|
|
16578
|
+
actorType: "user",
|
|
16579
|
+
actorId: claims.userId,
|
|
16580
|
+
targetType: "user",
|
|
16581
|
+
targetId: claims.userId,
|
|
16582
|
+
ip: ctx.request?.ip || null,
|
|
16583
|
+
userAgent: ctx.request?.headers?.["user-agent"] || null,
|
|
16584
|
+
meta: { scope, ended }
|
|
16585
|
+
});
|
|
16586
|
+
if (wantsJson) {
|
|
16587
|
+
ctx.body = { data: { ended, scope } };
|
|
16588
|
+
return;
|
|
16589
|
+
}
|
|
16590
|
+
return sendPage(
|
|
16591
|
+
ctx,
|
|
16592
|
+
200,
|
|
16593
|
+
lang,
|
|
16594
|
+
text.title,
|
|
16595
|
+
`<p>${escapeHtml(scope === "all" ? text.doneAll : text.done)}</p>`
|
|
16596
|
+
);
|
|
16597
|
+
} catch (err) {
|
|
16598
|
+
log.error("[not-me] Ending the session failed:", err?.name || "Error");
|
|
16599
|
+
return sendServerError(ctx, 500, "The session could not be ended");
|
|
16600
|
+
}
|
|
16601
|
+
},
|
|
16602
|
+
/**
|
|
16603
|
+
* The signed-in user's own sessions and security events as JSON (GDPR
|
|
16604
|
+
* Art. 15). Tokens, token hashes, device keys and native ids are never
|
|
16605
|
+
* included. At most 5,000 rows of each kind, newest first.
|
|
16606
|
+
*
|
|
16607
|
+
* @route GET /api/magic-sessionmanager/my-data
|
|
16608
|
+
* @auth users-permissions JWT (own data only; the user comes from the token)
|
|
16609
|
+
* @access plugin::magic-sessionmanager.self-service.exportOwnData (Authenticated role)
|
|
16610
|
+
* @param {any} ctx Koa context.
|
|
16611
|
+
* @returns {Promise<void>} 200 JSON attachment; 401 without a user.
|
|
16612
|
+
* @sideeffect Writes a `user.data.exported` security event.
|
|
16613
|
+
*/
|
|
16614
|
+
async exportOwnData(ctx) {
|
|
16615
|
+
const authUser = ctx.state?.user;
|
|
16616
|
+
const userDocumentId = authUser?.documentId || (authUser?.id ? await resolveUserDocumentId(strapi2, authUser.id) : null);
|
|
16617
|
+
if (!userDocumentId) return ctx.unauthorized("Authentication required");
|
|
16618
|
+
try {
|
|
16619
|
+
const user = await strapi2.db.query(USER_UID).findOne({
|
|
16620
|
+
where: { documentId: userDocumentId },
|
|
16621
|
+
select: ["documentId", "username", "email", "createdAt"]
|
|
16622
|
+
});
|
|
16623
|
+
const sessions = [];
|
|
16624
|
+
for (let start = 0; start < EXPORT_LIMIT; start += EXPORT_BATCH) {
|
|
16625
|
+
const rows = await strapi2.documents(SESSION_UID).findMany({
|
|
16626
|
+
filters: { user: { documentId: userDocumentId } },
|
|
16627
|
+
fields: [
|
|
16628
|
+
"documentId",
|
|
16629
|
+
"loginTime",
|
|
16630
|
+
"lastActive",
|
|
16631
|
+
"logoutTime",
|
|
16632
|
+
"isActive",
|
|
16633
|
+
"terminationReason",
|
|
16634
|
+
"ipAddress",
|
|
16635
|
+
"userAgent",
|
|
16636
|
+
"deviceType",
|
|
16637
|
+
"browserName",
|
|
16638
|
+
"osName",
|
|
16639
|
+
"geoLocation"
|
|
16640
|
+
],
|
|
16641
|
+
sort: [{ loginTime: "desc" }, { id: "desc" }],
|
|
16642
|
+
start,
|
|
16643
|
+
limit: EXPORT_BATCH
|
|
16644
|
+
});
|
|
16645
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
16646
|
+
sessions.push(...list.map(({ id: _id, ...row }) => row));
|
|
16647
|
+
if (list.length < EXPORT_BATCH) break;
|
|
16648
|
+
}
|
|
16649
|
+
const events = await strapi2.db.query(EVENT_UID).findMany({
|
|
16650
|
+
where: {
|
|
16651
|
+
$or: [
|
|
16652
|
+
{ targetType: "user", targetId: userDocumentId },
|
|
16653
|
+
{ actorType: "user", actorId: userDocumentId }
|
|
16654
|
+
]
|
|
16655
|
+
},
|
|
16656
|
+
select: ["event", "createdAt", "ip", "userAgent", "geo", "meta"],
|
|
16657
|
+
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
16658
|
+
limit: EXPORT_LIMIT
|
|
16659
|
+
});
|
|
16660
|
+
recordUserEvent(strapi2, {
|
|
16661
|
+
event: SECURITY_EVENTS.USER_DATA_EXPORTED,
|
|
16662
|
+
actorType: "user",
|
|
16663
|
+
actorId: userDocumentId,
|
|
16664
|
+
targetType: "user",
|
|
16665
|
+
targetId: userDocumentId,
|
|
16666
|
+
ip: ctx.request?.ip || null,
|
|
16667
|
+
userAgent: ctx.request?.headers?.["user-agent"] || null,
|
|
16668
|
+
meta: { sessions: sessions.length, events: Array.isArray(events) ? events.length : 0 }
|
|
16669
|
+
});
|
|
16670
|
+
ctx.set("Content-Disposition", 'attachment; filename="my-session-data.json"');
|
|
16671
|
+
ctx.set("Cache-Control", "no-store");
|
|
16672
|
+
ctx.body = {
|
|
16673
|
+
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
16674
|
+
user: user ? { documentId: user.documentId, username: user.username, email: user.email } : { documentId: userDocumentId },
|
|
16675
|
+
sessions,
|
|
16676
|
+
securityEvents: (Array.isArray(events) ? events : []).map(({ id: _id, ...row }) => row)
|
|
16677
|
+
};
|
|
16678
|
+
} catch (err) {
|
|
16679
|
+
log.error("[my-data] Export failed:", err?.name || "Error");
|
|
16680
|
+
return sendServerError(ctx, 500, "Your data could not be exported");
|
|
16681
|
+
}
|
|
16682
|
+
}
|
|
16683
|
+
};
|
|
16684
|
+
};
|
|
16685
|
+
}
|
|
16686
|
+
});
|
|
16687
|
+
|
|
16688
|
+
// server/src/controllers/webhooks.js
|
|
16689
|
+
var require_webhooks = __commonJS({
|
|
16690
|
+
"server/src/controllers/webhooks.js"(exports2, module2) {
|
|
16691
|
+
"use strict";
|
|
16692
|
+
var { sendServerError } = require_http_errors();
|
|
16693
|
+
var { createLogger } = require_logger();
|
|
16694
|
+
var RESULT_CODES = /* @__PURE__ */ new Set([
|
|
16695
|
+
"no_url",
|
|
16696
|
+
"no_secret",
|
|
16697
|
+
"invalid_url",
|
|
16698
|
+
"dns_failed",
|
|
16699
|
+
"address_not_allowed",
|
|
16700
|
+
"timeout",
|
|
16701
|
+
"network_error",
|
|
16702
|
+
"redirect_not_followed"
|
|
16703
|
+
]);
|
|
16704
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
16705
|
+
const log = createLogger(strapi2);
|
|
16706
|
+
return {
|
|
16707
|
+
/**
|
|
16708
|
+
* Sends one signed `test` event to the stored URL, without retries.
|
|
14328
16709
|
*
|
|
14329
|
-
* @route
|
|
14330
|
-
* @auth
|
|
14331
|
-
* @
|
|
14332
|
-
* @
|
|
16710
|
+
* @route POST /magic-sessionmanager/webhook/test
|
|
16711
|
+
* @auth admin session or admin API token
|
|
16712
|
+
* @access plugin::magic-sessionmanager.access
|
|
16713
|
+
* @param {any} ctx Koa context.
|
|
16714
|
+
* @returns {Promise<void>} `{ data: { ok, status, code } }` (status of the receiver's answer;
|
|
16715
|
+
* code: no_url, no_secret, invalid_url, dns_failed, address_not_allowed, timeout,
|
|
16716
|
+
* network_error, redirect_not_followed or http_<status>).
|
|
16717
|
+
* @sideeffect One HTTPS request to the stored webhook URL.
|
|
14333
16718
|
*/
|
|
14334
|
-
async
|
|
14335
|
-
|
|
14336
|
-
|
|
14337
|
-
|
|
14338
|
-
|
|
14339
|
-
|
|
14340
|
-
|
|
14341
|
-
|
|
14342
|
-
|
|
14343
|
-
);
|
|
16719
|
+
async sendTest(ctx) {
|
|
16720
|
+
try {
|
|
16721
|
+
const result = await strapi2.plugin("magic-sessionmanager").service("webhooks").sendTest();
|
|
16722
|
+
const code = result.code === null || RESULT_CODES.has(result.code) || /^http_\d{3}$/.test(result.code) ? result.code : "network_error";
|
|
16723
|
+
ctx.body = { data: { ok: result.ok === true, status: result.status ?? null, code } };
|
|
16724
|
+
} catch (err) {
|
|
16725
|
+
log.error("[webhooks] Test send failed:", err?.name || "Error");
|
|
16726
|
+
return sendServerError(ctx, 500, "The test event could not be sent");
|
|
16727
|
+
}
|
|
14344
16728
|
}
|
|
14345
16729
|
};
|
|
14346
16730
|
};
|
|
@@ -14356,12 +16740,18 @@ var require_controllers = __commonJS({
|
|
|
14356
16740
|
var geoip = require_geoip();
|
|
14357
16741
|
var adminSessions = require_admin_sessions2();
|
|
14358
16742
|
var adminActivity = require_admin_activity();
|
|
16743
|
+
var lockouts = require_lockouts();
|
|
16744
|
+
var selfService = require_self_service();
|
|
16745
|
+
var webhooks = require_webhooks();
|
|
14359
16746
|
module2.exports = {
|
|
14360
16747
|
session,
|
|
14361
16748
|
settings,
|
|
14362
16749
|
geoip,
|
|
14363
16750
|
"admin-sessions": adminSessions,
|
|
14364
|
-
"admin-activity": adminActivity
|
|
16751
|
+
"admin-activity": adminActivity,
|
|
16752
|
+
lockouts,
|
|
16753
|
+
"self-service": selfService,
|
|
16754
|
+
webhooks
|
|
14365
16755
|
};
|
|
14366
16756
|
}
|
|
14367
16757
|
});
|
|
@@ -14376,6 +16766,10 @@ var require_session2 = __commonJS({
|
|
|
14376
16766
|
var { resolveUserDocumentId } = require_resolve_user();
|
|
14377
16767
|
var { enhanceSessions, shouldResolveGeoData } = require_enhance_session();
|
|
14378
16768
|
var { getPluginSettings } = require_settings_loader();
|
|
16769
|
+
var { hasRoleOverride, inactivityTimeoutFor } = require_policy_settings();
|
|
16770
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
16771
|
+
var { anonymizeIp, normalizeIp } = require_admin_request_info();
|
|
16772
|
+
var { pointOf } = require_sign_in_signals();
|
|
14379
16773
|
var {
|
|
14380
16774
|
cleanupExpiredAccessTokenRevocations,
|
|
14381
16775
|
persistAccessTokenRevocation
|
|
@@ -14707,6 +17101,7 @@ var require_session2 = __commonJS({
|
|
|
14707
17101
|
* @param {string} [params.refreshToken] - Refresh token (will be encrypted)
|
|
14708
17102
|
* @param {string} [params.nativeSessionId] - Native Users & Permissions session ID.
|
|
14709
17103
|
* @param {object} [params.geoData]
|
|
17104
|
+
* @param {string} [params.deviceKey] Device key from utils/sign-in-signals.js.
|
|
14710
17105
|
* @returns {Promise<object>} Created session
|
|
14711
17106
|
* @throws {Error} When userId is missing
|
|
14712
17107
|
*/
|
|
@@ -14717,11 +17112,13 @@ var require_session2 = __commonJS({
|
|
|
14717
17112
|
token,
|
|
14718
17113
|
refreshToken,
|
|
14719
17114
|
nativeSessionId,
|
|
14720
|
-
geoData
|
|
17115
|
+
geoData,
|
|
17116
|
+
deviceKey
|
|
14721
17117
|
}) {
|
|
14722
17118
|
if (!userId) {
|
|
14723
17119
|
throw new Error("createSession: userId is required");
|
|
14724
17120
|
}
|
|
17121
|
+
const privacy = await getPluginSettings(strapi2).then(resolveDetectionSettings).catch(() => ({}));
|
|
14725
17122
|
try {
|
|
14726
17123
|
const now = /* @__PURE__ */ new Date();
|
|
14727
17124
|
const sessionId = generateSessionId(userId);
|
|
@@ -14731,7 +17128,9 @@ var require_session2 = __commonJS({
|
|
|
14731
17128
|
const tokenHashValue = token ? hashToken(token) : null;
|
|
14732
17129
|
const refreshTokenHashValue = refreshToken ? hashToken(refreshToken) : null;
|
|
14733
17130
|
const parsedUA = parseUserAgent(userAgent);
|
|
14734
|
-
const
|
|
17131
|
+
const rawIp = (typeof ip === "string" ? ip : "unknown").substring(0, 45);
|
|
17132
|
+
const safeIp = privacy.sessionIpAnonymize && normalizeIp(rawIp) ? anonymizeIp(normalizeIp(rawIp)) || rawIp : rawIp;
|
|
17133
|
+
const point = privacy.impossibleTravelEnabled ? pointOf(geoData) : null;
|
|
14735
17134
|
const safeUa = (typeof userAgent === "string" ? userAgent : "unknown").substring(0, 500);
|
|
14736
17135
|
const session = await strapi2.documents(SESSION_UID).create({
|
|
14737
17136
|
data: {
|
|
@@ -14759,8 +17158,10 @@ var require_session2 = __commonJS({
|
|
|
14759
17158
|
timezone: geoData.timezone,
|
|
14760
17159
|
// Marks the stored score as real risk data; without a
|
|
14761
17160
|
// risk source the score is null (not a fake 100).
|
|
14762
|
-
...geoData.riskSource ? { riskSource: geoData.riskSource } : {}
|
|
17161
|
+
...geoData.riskSource ? { riskSource: geoData.riskSource } : {},
|
|
17162
|
+
...point ? { latitude: point.lat, longitude: point.lon } : {}
|
|
14763
17163
|
} : null,
|
|
17164
|
+
...typeof deviceKey === "string" && /^[a-f0-9]{32}$/.test(deviceKey) ? { deviceKey } : {},
|
|
14764
17165
|
securityScore: geoData?.riskSource ? geoData.securityScore ?? null : null
|
|
14765
17166
|
}
|
|
14766
17167
|
});
|
|
@@ -15352,12 +17753,13 @@ var require_session2 = __commonJS({
|
|
|
15352
17753
|
const settings = await getPluginSettings(strapi2);
|
|
15353
17754
|
const nativeManager = getNativeSessionManager(strapi2);
|
|
15354
17755
|
const inactivityTimeout = settings.inactivityTimeout || 15 * 60 * 1e3;
|
|
17756
|
+
const perRole = hasRoleOverride(settings, "inactivityTimeout");
|
|
15355
17757
|
const now = /* @__PURE__ */ new Date();
|
|
15356
17758
|
const cutoffTime = new Date(now.getTime() - inactivityTimeout);
|
|
15357
17759
|
log.info(
|
|
15358
17760
|
`[CLEANUP] Cleaning up sessions inactive since before ${cutoffTime.toISOString()}`
|
|
15359
17761
|
);
|
|
15360
|
-
if (useDbDirect && !nativeManager) {
|
|
17762
|
+
if (useDbDirect && !nativeManager && !perRole) {
|
|
15361
17763
|
try {
|
|
15362
17764
|
const deactivated = await strapi2.db.connection("magic_sessions").where("is_active", true).andWhere(function whereIdle() {
|
|
15363
17765
|
this.where("last_active", "<", cutoffTime).orWhere(function whereNullLastActive() {
|
|
@@ -15386,7 +17788,9 @@ var require_session2 = __commonJS({
|
|
|
15386
17788
|
const batch = await strapi2.documents(SESSION_UID).findMany({
|
|
15387
17789
|
filters: { isActive: true },
|
|
15388
17790
|
fields: ["documentId", "lastActive", "loginTime", "nativeSessionId"],
|
|
15389
|
-
populate: {
|
|
17791
|
+
populate: {
|
|
17792
|
+
user: perRole ? { fields: ["id", "documentId"], populate: { role: { fields: ["documentId"] } } } : { fields: ["id", "documentId"] }
|
|
17793
|
+
},
|
|
15390
17794
|
limit: BATCH,
|
|
15391
17795
|
start,
|
|
15392
17796
|
sort: { loginTime: "asc" }
|
|
@@ -15394,8 +17798,11 @@ var require_session2 = __commonJS({
|
|
|
15394
17798
|
if (!batch || batch.length === 0) break;
|
|
15395
17799
|
for (const session of batch) {
|
|
15396
17800
|
const lastActiveTime = session.lastActive ? new Date(session.lastActive) : session.loginTime ? new Date(session.loginTime) : null;
|
|
15397
|
-
|
|
15398
|
-
|
|
17801
|
+
const sessionCutoff = perRole ? new Date(
|
|
17802
|
+
now.getTime() - inactivityTimeoutFor(settings, session.user?.role?.documentId || null)
|
|
17803
|
+
) : cutoffTime;
|
|
17804
|
+
if (lastActiveTime && lastActiveTime < sessionCutoff) {
|
|
17805
|
+
sessionsToDeactivate.push({ ...session, cutoff: sessionCutoff });
|
|
15399
17806
|
}
|
|
15400
17807
|
}
|
|
15401
17808
|
if (batch.length < BATCH) break;
|
|
@@ -15414,8 +17821,8 @@ var require_session2 = __commonJS({
|
|
|
15414
17821
|
documentId: session.documentId,
|
|
15415
17822
|
isActive: true,
|
|
15416
17823
|
$or: [
|
|
15417
|
-
{ lastActive: { $lt:
|
|
15418
|
-
{ lastActive: { $null: true }, loginTime: { $lt:
|
|
17824
|
+
{ lastActive: { $lt: session.cutoff } },
|
|
17825
|
+
{ lastActive: { $null: true }, loginTime: { $lt: session.cutoff } }
|
|
15419
17826
|
]
|
|
15420
17827
|
};
|
|
15421
17828
|
if (nativeManager) {
|
|
@@ -16450,6 +18857,98 @@ var require_notifications = __commonJS({
|
|
|
16450
18857
|
if (geoData.isThreat) warnings.push("Threat");
|
|
16451
18858
|
return warnings;
|
|
16452
18859
|
}
|
|
18860
|
+
var POLICY_TEMPLATES = Object.freeze({
|
|
18861
|
+
accountLocked: Object.freeze({
|
|
18862
|
+
subject: "Your account was locked after failed sign-ins",
|
|
18863
|
+
html: `<html>
|
|
18864
|
+
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
|
|
18865
|
+
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
|
|
18866
|
+
<h2>Your account was temporarily locked</h2>
|
|
18867
|
+
<p>Hello {{user.username}},</p>
|
|
18868
|
+
<p>There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.</p>
|
|
18869
|
+
<p>If these attempts were not yours, change your password after the lock ends.</p>
|
|
18870
|
+
<p style="color: #666; font-size: 12px;">This is an automated security notification.</p>
|
|
18871
|
+
</div>
|
|
18872
|
+
</body>
|
|
18873
|
+
</html>`,
|
|
18874
|
+
text: `Your account was temporarily locked
|
|
18875
|
+
|
|
18876
|
+
Hello {{user.username}},
|
|
18877
|
+
|
|
18878
|
+
There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
|
|
18879
|
+
|
|
18880
|
+
If these attempts were not yours, change your password after the lock ends.`
|
|
18881
|
+
}),
|
|
18882
|
+
newDevice: Object.freeze({
|
|
18883
|
+
subject: "New sign-in to your account",
|
|
18884
|
+
html: `<html>
|
|
18885
|
+
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
|
|
18886
|
+
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
|
|
18887
|
+
<h2>New sign-in to your account</h2>
|
|
18888
|
+
<p>Hello {{user.username}},</p>
|
|
18889
|
+
<p>Your account was just used on a device we have not seen before.</p>
|
|
18890
|
+
<ul>
|
|
18891
|
+
<li>Time: {{session.loginTime}}</li>
|
|
18892
|
+
<li>Device: {{device.browser}} on {{device.os}}</li>
|
|
18893
|
+
<li>Location: {{geo.city}}, {{geo.country}}</li>
|
|
18894
|
+
<li>IP address: {{session.ipAddress}}</li>
|
|
18895
|
+
</ul>
|
|
18896
|
+
<p>If this was you, you can ignore this email.</p>
|
|
18897
|
+
<p>If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
|
|
18898
|
+
<p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
|
|
18899
|
+
</div>
|
|
18900
|
+
</body>
|
|
18901
|
+
</html>`,
|
|
18902
|
+
text: `New sign-in to your account
|
|
18903
|
+
|
|
18904
|
+
Hello {{user.username}},
|
|
18905
|
+
|
|
18906
|
+
Your account was just used on a device we have not seen before.
|
|
18907
|
+
|
|
18908
|
+
Time: {{session.loginTime}}
|
|
18909
|
+
Device: {{device.browser}} on {{device.os}}
|
|
18910
|
+
Location: {{geo.city}}, {{geo.country}}
|
|
18911
|
+
IP address: {{session.ipAddress}}
|
|
18912
|
+
|
|
18913
|
+
If this was not you, sign this device out and change your password:
|
|
18914
|
+
{{link.notMe}}
|
|
18915
|
+
|
|
18916
|
+
The link works once and expires after 72 hours.`
|
|
18917
|
+
}),
|
|
18918
|
+
impossibleTravel: Object.freeze({
|
|
18919
|
+
subject: "Unusual sign-in to your account",
|
|
18920
|
+
html: `<html>
|
|
18921
|
+
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
|
|
18922
|
+
<div style="max-width: 600px; margin: 0 auto; padding: 20px;">
|
|
18923
|
+
<h2>Unusual sign-in to your account</h2>
|
|
18924
|
+
<p>Hello {{user.username}},</p>
|
|
18925
|
+
<p>Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.</p>
|
|
18926
|
+
<ul>
|
|
18927
|
+
<li>Time: {{session.loginTime}}</li>
|
|
18928
|
+
<li>Location: {{geo.city}}, {{geo.country}}</li>
|
|
18929
|
+
<li>Device: {{device.browser}} on {{device.os}}</li>
|
|
18930
|
+
</ul>
|
|
18931
|
+
<p>A VPN or a mobile network can cause this. If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
|
|
18932
|
+
<p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
|
|
18933
|
+
</div>
|
|
18934
|
+
</body>
|
|
18935
|
+
</html>`,
|
|
18936
|
+
text: `Unusual sign-in to your account
|
|
18937
|
+
|
|
18938
|
+
Hello {{user.username}},
|
|
18939
|
+
|
|
18940
|
+
Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.
|
|
18941
|
+
|
|
18942
|
+
Time: {{session.loginTime}}
|
|
18943
|
+
Location: {{geo.city}}, {{geo.country}}
|
|
18944
|
+
Device: {{device.browser}} on {{device.os}}
|
|
18945
|
+
|
|
18946
|
+
A VPN or a mobile network can cause this. If this was not you, sign this device out and change your password:
|
|
18947
|
+
{{link.notMe}}
|
|
18948
|
+
|
|
18949
|
+
The link works once and expires after 72 hours.`
|
|
18950
|
+
})
|
|
18951
|
+
});
|
|
16453
18952
|
var ALLOWED_WEBHOOK_HOSTS = ["discord.com", "discordapp.com", "hooks.slack.com"];
|
|
16454
18953
|
var WEBHOOK_TIMEOUT_MS = 5e3;
|
|
16455
18954
|
module2.exports = ({ strapi: strapi2 }) => ({
|
|
@@ -16555,9 +19054,91 @@ Account: {{user.email}}
|
|
|
16555
19054
|
Time: {{session.loginTime}}
|
|
16556
19055
|
IP: {{session.ipAddress}}
|
|
16557
19056
|
VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
16558
|
-
}
|
|
19057
|
+
},
|
|
19058
|
+
...POLICY_TEMPLATES
|
|
16559
19059
|
};
|
|
16560
19060
|
},
|
|
19061
|
+
/**
|
|
19062
|
+
* One template by key. A stored template without html and text falls back
|
|
19063
|
+
* to the default of that key.
|
|
19064
|
+
*
|
|
19065
|
+
* @param {string} key Template key.
|
|
19066
|
+
* @returns {Promise<{subject: string, html: string, text: string}>} Template.
|
|
19067
|
+
*/
|
|
19068
|
+
async getTemplate(key) {
|
|
19069
|
+
const templates = await this.getEmailTemplates();
|
|
19070
|
+
const template = templates?.[key];
|
|
19071
|
+
if (template && (template.html || template.text)) {
|
|
19072
|
+
return {
|
|
19073
|
+
subject: template.subject || POLICY_TEMPLATES[key]?.subject || "",
|
|
19074
|
+
html: template.html || "",
|
|
19075
|
+
text: template.text || ""
|
|
19076
|
+
};
|
|
19077
|
+
}
|
|
19078
|
+
return { ...POLICY_TEMPLATES[key] };
|
|
19079
|
+
},
|
|
19080
|
+
/**
|
|
19081
|
+
* Emails a user about a sign-in from a new device or an impossible
|
|
19082
|
+
* travel, with the "This wasn't me" link.
|
|
19083
|
+
*
|
|
19084
|
+
* @param {'newDevice'|'impossibleTravel'} key Template.
|
|
19085
|
+
* @param {{user: object, session: object, geoData?: object|null, device: object,
|
|
19086
|
+
* travel?: object|null, link: string|null}} data Values.
|
|
19087
|
+
* @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
|
|
19088
|
+
* @sideeffect Sends one email.
|
|
19089
|
+
*/
|
|
19090
|
+
async sendSignInSignalEmail(key, data) {
|
|
19091
|
+
try {
|
|
19092
|
+
if (!data?.user?.email) return false;
|
|
19093
|
+
const template = await this.getTemplate(key);
|
|
19094
|
+
const values = { ...data, geoData: data.geoData || {}, link: { notMe: data.link } };
|
|
19095
|
+
await strapi2.plugin("email").service("email").send({
|
|
19096
|
+
to: data.user.email,
|
|
19097
|
+
subject: this.replaceVariables(template.subject, values),
|
|
19098
|
+
html: this.replaceVariables(template.html, values),
|
|
19099
|
+
text: this.replaceVariables(template.text, values)
|
|
19100
|
+
});
|
|
19101
|
+
strapi2.log.info(`[magic-sessionmanager/notifications] ${key} email sent`);
|
|
19102
|
+
return true;
|
|
19103
|
+
} catch (err) {
|
|
19104
|
+
strapi2.log.error(
|
|
19105
|
+
`[magic-sessionmanager/notifications] ${key} email failed:`,
|
|
19106
|
+
err?.name || "Error"
|
|
19107
|
+
);
|
|
19108
|
+
return false;
|
|
19109
|
+
}
|
|
19110
|
+
},
|
|
19111
|
+
/**
|
|
19112
|
+
* Emails a user that their account was locked after failed sign-ins.
|
|
19113
|
+
* Sent through Strapi's email plugin, so a provider plugin such as Magic
|
|
19114
|
+
* Mail delivers it when installed.
|
|
19115
|
+
*
|
|
19116
|
+
* @param {{user: {email?: string, username?: string}, minutes: number, until: number}} params
|
|
19117
|
+
* Account, lock duration in minutes and lock end (epoch ms).
|
|
19118
|
+
* @returns {Promise<boolean>} Whether the mail was handed to the email plugin.
|
|
19119
|
+
* @sideeffect Sends one email.
|
|
19120
|
+
*/
|
|
19121
|
+
async sendAccountLockedEmail({ user, minutes, until }) {
|
|
19122
|
+
try {
|
|
19123
|
+
if (!user?.email) return false;
|
|
19124
|
+
const template = await this.getTemplate("accountLocked");
|
|
19125
|
+
const data = { user, lock: { minutes, until } };
|
|
19126
|
+
await strapi2.plugin("email").service("email").send({
|
|
19127
|
+
to: user.email,
|
|
19128
|
+
subject: this.replaceVariables(template.subject, data),
|
|
19129
|
+
html: this.replaceVariables(template.html, data),
|
|
19130
|
+
text: this.replaceVariables(template.text, data)
|
|
19131
|
+
});
|
|
19132
|
+
strapi2.log.info("[magic-sessionmanager/notifications] Account lock email sent");
|
|
19133
|
+
return true;
|
|
19134
|
+
} catch (err) {
|
|
19135
|
+
strapi2.log.error(
|
|
19136
|
+
"[magic-sessionmanager/notifications] Account lock email failed:",
|
|
19137
|
+
err?.name || "Error"
|
|
19138
|
+
);
|
|
19139
|
+
return false;
|
|
19140
|
+
}
|
|
19141
|
+
},
|
|
16561
19142
|
/**
|
|
16562
19143
|
* HTML-escapes a string to prevent XSS when it is interpolated into an
|
|
16563
19144
|
* HTML email template. Non-string inputs are coerced to strings first.
|
|
@@ -16595,6 +19176,26 @@ VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
|
|
|
16595
19176
|
result = result.replace(/\{\{reason\.isVpn\}\}/g, data.reason?.isVpn ? "Yes" : "No");
|
|
16596
19177
|
result = result.replace(/\{\{reason\.isProxy\}\}/g, data.reason?.isProxy ? "Yes" : "No");
|
|
16597
19178
|
result = result.replace(/\{\{reason\.isThreat\}\}/g, data.reason?.isThreat ? "Yes" : "No");
|
|
19179
|
+
result = result.replace(
|
|
19180
|
+
/\{\{lock\.minutes\}\}/g,
|
|
19181
|
+
esc(Number.isFinite(data.lock?.minutes) ? String(data.lock.minutes) : "N/A")
|
|
19182
|
+
);
|
|
19183
|
+
result = result.replace(
|
|
19184
|
+
/\{\{lock\.until\}\}/g,
|
|
19185
|
+
esc(Number.isFinite(data.lock?.until) ? new Date(data.lock.until).toUTCString() : "N/A")
|
|
19186
|
+
);
|
|
19187
|
+
result = result.replace(/\{\{device\.browser\}\}/g, esc(data.device?.browser || "Unknown"));
|
|
19188
|
+
result = result.replace(/\{\{device\.os\}\}/g, esc(data.device?.os || "Unknown"));
|
|
19189
|
+
result = result.replace(
|
|
19190
|
+
/\{\{travel\.distanceKm\}\}/g,
|
|
19191
|
+
esc(Number.isFinite(data.travel?.distanceKm) ? String(data.travel.distanceKm) : "N/A")
|
|
19192
|
+
);
|
|
19193
|
+
result = result.replace(
|
|
19194
|
+
/\{\{travel\.speedKmh\}\}/g,
|
|
19195
|
+
esc(Number.isFinite(data.travel?.speedKmh) ? String(data.travel.speedKmh) : "N/A")
|
|
19196
|
+
);
|
|
19197
|
+
const link = typeof data.link?.notMe === "string" && /^https?:\/\//.test(data.link.notMe) ? data.link.notMe : "";
|
|
19198
|
+
result = result.replace(/\{\{link\.notMe\}\}/g, esc(link));
|
|
16598
19199
|
const score = data.reason?.securityScore;
|
|
16599
19200
|
result = result.replace(
|
|
16600
19201
|
/\{\{reason\.securityScore\}\}/g,
|
|
@@ -17102,9 +19703,12 @@ var require_security_log = __commonJS({
|
|
|
17102
19703
|
};
|
|
17103
19704
|
const buildRows = async (batch, options, settings) => {
|
|
17104
19705
|
const groups = /* @__PURE__ */ new Map();
|
|
19706
|
+
const recordUserSignIns = settings.recordUserSignInEvents !== false;
|
|
17105
19707
|
const wanted = batch.filter((entry) => {
|
|
17106
19708
|
const gate = recordingSwitchOf(entry.event);
|
|
17107
|
-
|
|
19709
|
+
if (gate === "always") return true;
|
|
19710
|
+
if (gate === "userSignIns") return recordUserSignIns;
|
|
19711
|
+
return gate === "signIns" ? options.signIns : options.content;
|
|
17108
19712
|
});
|
|
17109
19713
|
if (!wanted.length) return { rows: [], groups };
|
|
17110
19714
|
const emails = [
|
|
@@ -17590,6 +20194,29 @@ var require_security_log = __commonJS({
|
|
|
17590
20194
|
* @returns {Promise<void>}
|
|
17591
20195
|
* @sideeffect Deletes and updates rows of the security event table.
|
|
17592
20196
|
*/
|
|
20197
|
+
/**
|
|
20198
|
+
* Deletes what the log holds about an app user whose account was
|
|
20199
|
+
* deleted: events about the account and events the user caused.
|
|
20200
|
+
*
|
|
20201
|
+
* @param {string} userDocumentId Deleted user's documentId.
|
|
20202
|
+
* @returns {Promise<void>}
|
|
20203
|
+
* @sideeffect Deletes rows of the security event table.
|
|
20204
|
+
*/
|
|
20205
|
+
async deleteUserData(userDocumentId) {
|
|
20206
|
+
const key = toId(userDocumentId);
|
|
20207
|
+
if (!key) return;
|
|
20208
|
+
queue = queue.filter(
|
|
20209
|
+
(entry) => !(entry.targetType === "user" && String(entry.targetId) === key) && !(entry.actorType === "user" && String(entry.actorId) === key)
|
|
20210
|
+
);
|
|
20211
|
+
await events().deleteMany({
|
|
20212
|
+
where: {
|
|
20213
|
+
$or: [
|
|
20214
|
+
{ targetType: "user", targetId: key },
|
|
20215
|
+
{ actorType: "user", actorId: key }
|
|
20216
|
+
]
|
|
20217
|
+
}
|
|
20218
|
+
});
|
|
20219
|
+
},
|
|
17593
20220
|
async deleteAdminData(adminId) {
|
|
17594
20221
|
const id = toAdminId(adminId);
|
|
17595
20222
|
if (!id) return;
|
|
@@ -17862,6 +20489,478 @@ var require_security_log = __commonJS({
|
|
|
17862
20489
|
}
|
|
17863
20490
|
});
|
|
17864
20491
|
|
|
20492
|
+
// server/src/utils/webhook-delivery.js
|
|
20493
|
+
var require_webhook_delivery = __commonJS({
|
|
20494
|
+
"server/src/utils/webhook-delivery.js"(exports2, module2) {
|
|
20495
|
+
"use strict";
|
|
20496
|
+
var crypto = require("node:crypto");
|
|
20497
|
+
var dns = require("node:dns");
|
|
20498
|
+
var https = require("node:https");
|
|
20499
|
+
var net = require("node:net");
|
|
20500
|
+
var SIGNATURE_HEADER = "X-Magic-Sessionmanager-Signature";
|
|
20501
|
+
var EVENT_HEADER = "X-Magic-Sessionmanager-Event";
|
|
20502
|
+
var DELIVERY_HEADER = "X-Magic-Sessionmanager-Delivery";
|
|
20503
|
+
var USER_AGENT = "Strapi-Magic-SessionManager-Webhook/2.0";
|
|
20504
|
+
var TIMEOUT_MS = 5e3;
|
|
20505
|
+
var MAX_RESPONSE_BYTES = 64 * 1024;
|
|
20506
|
+
var RETRY_DELAYS_MS = Object.freeze([0, 2e3, 1e4]);
|
|
20507
|
+
var BLOCKED = (() => {
|
|
20508
|
+
const list = new net.BlockList();
|
|
20509
|
+
for (const [address, prefix] of [
|
|
20510
|
+
["0.0.0.0", 8],
|
|
20511
|
+
["10.0.0.0", 8],
|
|
20512
|
+
["100.64.0.0", 10],
|
|
20513
|
+
["127.0.0.0", 8],
|
|
20514
|
+
["169.254.0.0", 16],
|
|
20515
|
+
["172.16.0.0", 12],
|
|
20516
|
+
["192.0.0.0", 24],
|
|
20517
|
+
["192.0.2.0", 24],
|
|
20518
|
+
["192.88.99.0", 24],
|
|
20519
|
+
["192.168.0.0", 16],
|
|
20520
|
+
["198.18.0.0", 15],
|
|
20521
|
+
["198.51.100.0", 24],
|
|
20522
|
+
["203.0.113.0", 24],
|
|
20523
|
+
["224.0.0.0", 4],
|
|
20524
|
+
["240.0.0.0", 4]
|
|
20525
|
+
]) {
|
|
20526
|
+
list.addSubnet(address, prefix, "ipv4");
|
|
20527
|
+
}
|
|
20528
|
+
for (const [address, prefix] of [
|
|
20529
|
+
["::", 128],
|
|
20530
|
+
["::1", 128],
|
|
20531
|
+
// IPv4-mapped addresses (::ffff:0:0/96) are not listed: BlockList
|
|
20532
|
+
// checks them against the IPv4 rules above, and a listed /96 would
|
|
20533
|
+
// match every IPv4 address.
|
|
20534
|
+
["64:ff9b::", 96],
|
|
20535
|
+
["64:ff9b:1::", 48],
|
|
20536
|
+
["100::", 64],
|
|
20537
|
+
["2001::", 23],
|
|
20538
|
+
["2001:db8::", 32],
|
|
20539
|
+
["2002::", 16],
|
|
20540
|
+
["fc00::", 7],
|
|
20541
|
+
["fe80::", 10],
|
|
20542
|
+
["fec0::", 10],
|
|
20543
|
+
["ff00::", 8]
|
|
20544
|
+
]) {
|
|
20545
|
+
list.addSubnet(address, prefix, "ipv6");
|
|
20546
|
+
}
|
|
20547
|
+
return list;
|
|
20548
|
+
})();
|
|
20549
|
+
function isBlockedAddress(address) {
|
|
20550
|
+
let value = String(address || "").trim();
|
|
20551
|
+
if (value.toLowerCase().startsWith("::ffff:") && net.isIPv4(value.slice(7))) {
|
|
20552
|
+
value = value.slice(7);
|
|
20553
|
+
}
|
|
20554
|
+
const version = net.isIP(value);
|
|
20555
|
+
if (version === 0) return true;
|
|
20556
|
+
return BLOCKED.check(value, version === 4 ? "ipv4" : "ipv6");
|
|
20557
|
+
}
|
|
20558
|
+
function signPayload(secret, body, timestamp = Math.floor(Date.now() / 1e3)) {
|
|
20559
|
+
const digest = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
|
20560
|
+
return `t=${timestamp},v1=${digest}`;
|
|
20561
|
+
}
|
|
20562
|
+
function verifySignature(secret, body, header, { toleranceSeconds = 300, now = Date.now() } = {}) {
|
|
20563
|
+
const match = /^t=(\d{1,12}),v1=([a-f0-9]{64})$/.exec(String(header || ""));
|
|
20564
|
+
if (!match) return false;
|
|
20565
|
+
const timestamp = Number(match[1]);
|
|
20566
|
+
if (Math.abs(now / 1e3 - timestamp) > toleranceSeconds) return false;
|
|
20567
|
+
const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest();
|
|
20568
|
+
const given = Buffer.from(match[2], "hex");
|
|
20569
|
+
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
|
|
20570
|
+
}
|
|
20571
|
+
var DeliveryError = class extends Error {
|
|
20572
|
+
/**
|
|
20573
|
+
* @param {string} code Stable code.
|
|
20574
|
+
* @param {boolean} retryable Whether another attempt may succeed.
|
|
20575
|
+
* @param {number|null} [status] HTTP status, when there was one.
|
|
20576
|
+
*/
|
|
20577
|
+
constructor(code, retryable, status = null) {
|
|
20578
|
+
super(code);
|
|
20579
|
+
this.name = "DeliveryError";
|
|
20580
|
+
this.code = code;
|
|
20581
|
+
this.retryable = retryable;
|
|
20582
|
+
this.status = status;
|
|
20583
|
+
}
|
|
20584
|
+
};
|
|
20585
|
+
var resolveAll = (hostname) => dns.promises.lookup(hostname, { all: true, verbatim: true });
|
|
20586
|
+
function httpsPost({ url, address, headers, body, timeoutMs }) {
|
|
20587
|
+
return new Promise((resolve, reject) => {
|
|
20588
|
+
const request = https.request(
|
|
20589
|
+
{
|
|
20590
|
+
protocol: "https:",
|
|
20591
|
+
hostname: url.hostname,
|
|
20592
|
+
port: url.port || 443,
|
|
20593
|
+
path: `${url.pathname}${url.search}`,
|
|
20594
|
+
method: "POST",
|
|
20595
|
+
headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
|
|
20596
|
+
servername: net.isIP(url.hostname) ? void 0 : url.hostname,
|
|
20597
|
+
timeout: timeoutMs,
|
|
20598
|
+
// Pinned to the address that passed the check: no second lookup.
|
|
20599
|
+
lookup: (_hostname, options, callback) => {
|
|
20600
|
+
if (options && options.all) callback(null, [address]);
|
|
20601
|
+
else callback(null, address.address, address.family);
|
|
20602
|
+
}
|
|
20603
|
+
},
|
|
20604
|
+
(response) => {
|
|
20605
|
+
let received = 0;
|
|
20606
|
+
response.on("data", (chunk) => {
|
|
20607
|
+
received += chunk.length;
|
|
20608
|
+
if (received > MAX_RESPONSE_BYTES) response.destroy();
|
|
20609
|
+
});
|
|
20610
|
+
response.on("end", () => resolve(response.statusCode || 0));
|
|
20611
|
+
response.on("close", () => resolve(response.statusCode || 0));
|
|
20612
|
+
response.on("error", () => resolve(response.statusCode || 0));
|
|
20613
|
+
}
|
|
20614
|
+
);
|
|
20615
|
+
request.on("timeout", () => request.destroy(new DeliveryError("timeout", true)));
|
|
20616
|
+
request.on(
|
|
20617
|
+
"error",
|
|
20618
|
+
(err) => reject(err instanceof DeliveryError ? err : new DeliveryError("network_error", true))
|
|
20619
|
+
);
|
|
20620
|
+
request.end(body);
|
|
20621
|
+
});
|
|
20622
|
+
}
|
|
20623
|
+
async function deliverOnce({
|
|
20624
|
+
url,
|
|
20625
|
+
body,
|
|
20626
|
+
headers,
|
|
20627
|
+
resolve = resolveAll,
|
|
20628
|
+
post = httpsPost,
|
|
20629
|
+
timeoutMs = TIMEOUT_MS
|
|
20630
|
+
}) {
|
|
20631
|
+
let parsed;
|
|
20632
|
+
try {
|
|
20633
|
+
parsed = new URL(url);
|
|
20634
|
+
} catch {
|
|
20635
|
+
throw new DeliveryError("invalid_url", false);
|
|
20636
|
+
}
|
|
20637
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
|
|
20638
|
+
throw new DeliveryError("invalid_url", false);
|
|
20639
|
+
}
|
|
20640
|
+
const host = parsed.hostname.replace(/^\[|\]$/g, "");
|
|
20641
|
+
let addresses;
|
|
20642
|
+
if (net.isIP(host)) {
|
|
20643
|
+
addresses = [{ address: host, family: net.isIP(host) }];
|
|
20644
|
+
} else {
|
|
20645
|
+
try {
|
|
20646
|
+
addresses = await resolve(host);
|
|
20647
|
+
} catch {
|
|
20648
|
+
throw new DeliveryError("dns_failed", true);
|
|
20649
|
+
}
|
|
20650
|
+
}
|
|
20651
|
+
if (!Array.isArray(addresses) || addresses.length === 0)
|
|
20652
|
+
throw new DeliveryError("dns_failed", true);
|
|
20653
|
+
if (addresses.some((entry) => isBlockedAddress(entry.address))) {
|
|
20654
|
+
throw new DeliveryError("address_not_allowed", false);
|
|
20655
|
+
}
|
|
20656
|
+
const status = await post({ url: parsed, address: addresses[0], headers, body, timeoutMs });
|
|
20657
|
+
if (status >= 200 && status < 300) return { status };
|
|
20658
|
+
if (status >= 300 && status < 400)
|
|
20659
|
+
throw new DeliveryError("redirect_not_followed", false, status);
|
|
20660
|
+
throw new DeliveryError(`http_${status}`, status === 429 || status >= 500, status);
|
|
20661
|
+
}
|
|
20662
|
+
function buildSignedRequest({ event, data, secret, id = crypto.randomUUID(), now = /* @__PURE__ */ new Date() }) {
|
|
20663
|
+
const body = JSON.stringify({ id, event, createdAt: now.toISOString(), data });
|
|
20664
|
+
return {
|
|
20665
|
+
id,
|
|
20666
|
+
body,
|
|
20667
|
+
headers: {
|
|
20668
|
+
"Content-Type": "application/json",
|
|
20669
|
+
"User-Agent": USER_AGENT,
|
|
20670
|
+
[EVENT_HEADER]: event,
|
|
20671
|
+
[DELIVERY_HEADER]: id,
|
|
20672
|
+
[SIGNATURE_HEADER]: signPayload(secret, body, Math.floor(now.getTime() / 1e3))
|
|
20673
|
+
}
|
|
20674
|
+
};
|
|
20675
|
+
}
|
|
20676
|
+
async function deliverWithRetries({
|
|
20677
|
+
delays = RETRY_DELAYS_MS,
|
|
20678
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
|
|
20679
|
+
...request
|
|
20680
|
+
}) {
|
|
20681
|
+
let attempts = 0;
|
|
20682
|
+
let last = { ok: false, status: null, code: "not_sent" };
|
|
20683
|
+
for (const delay of delays) {
|
|
20684
|
+
if (delay > 0) await sleep(delay);
|
|
20685
|
+
attempts += 1;
|
|
20686
|
+
try {
|
|
20687
|
+
const { status } = await deliverOnce(request);
|
|
20688
|
+
return { ok: true, status, code: null, attempts };
|
|
20689
|
+
} catch (err) {
|
|
20690
|
+
const error = err instanceof DeliveryError ? err : new DeliveryError("network_error", true);
|
|
20691
|
+
last = { ok: false, status: error.status, code: error.code };
|
|
20692
|
+
if (!error.retryable) break;
|
|
20693
|
+
}
|
|
20694
|
+
}
|
|
20695
|
+
return { ...last, attempts };
|
|
20696
|
+
}
|
|
20697
|
+
module2.exports = {
|
|
20698
|
+
DELIVERY_HEADER,
|
|
20699
|
+
DeliveryError,
|
|
20700
|
+
EVENT_HEADER,
|
|
20701
|
+
RETRY_DELAYS_MS,
|
|
20702
|
+
SIGNATURE_HEADER,
|
|
20703
|
+
buildSignedRequest,
|
|
20704
|
+
deliverOnce,
|
|
20705
|
+
deliverWithRetries,
|
|
20706
|
+
isBlockedAddress,
|
|
20707
|
+
signPayload,
|
|
20708
|
+
verifySignature
|
|
20709
|
+
};
|
|
20710
|
+
}
|
|
20711
|
+
});
|
|
20712
|
+
|
|
20713
|
+
// server/src/services/webhooks.js
|
|
20714
|
+
var require_webhooks2 = __commonJS({
|
|
20715
|
+
"server/src/services/webhooks.js"(exports2, module2) {
|
|
20716
|
+
"use strict";
|
|
20717
|
+
var { decryptToken } = require_encryption();
|
|
20718
|
+
var { getPluginSettings } = require_settings_loader();
|
|
20719
|
+
var { resolveDetectionSettings } = require_detection_settings();
|
|
20720
|
+
var { resolveSecurityLogSettings } = require_security_log_settings();
|
|
20721
|
+
var { anonymizeIp, normalizeIp } = require_admin_request_info();
|
|
20722
|
+
var { SECURITY_EVENTS } = require_security_log_model();
|
|
20723
|
+
var {
|
|
20724
|
+
buildSignedRequest,
|
|
20725
|
+
deliverOnce,
|
|
20726
|
+
deliverWithRetries
|
|
20727
|
+
} = require_webhook_delivery();
|
|
20728
|
+
var { createLogger } = require_logger();
|
|
20729
|
+
var EVENT_OF_SECURITY_EVENT = Object.freeze({
|
|
20730
|
+
[SECURITY_EVENTS.USER_SIGN_IN_FAILED]: "login.failed",
|
|
20731
|
+
[SECURITY_EVENTS.USER_SIGN_IN_REFUSED]: "login.refused",
|
|
20732
|
+
[SECURITY_EVENTS.USER_LOCKOUT]: "lockout",
|
|
20733
|
+
[SECURITY_EVENTS.USER_LOCKOUT_LIFTED]: "lockout.lifted",
|
|
20734
|
+
[SECURITY_EVENTS.USER_SESSION_LIMIT]: "session.limit",
|
|
20735
|
+
[SECURITY_EVENTS.USER_PASSWORD_CHANGE_ENDED]: "password.changed",
|
|
20736
|
+
"user.sign-in.new-device": "login.new_device",
|
|
20737
|
+
"user.sign-in.impossible-travel": "login.impossible_travel",
|
|
20738
|
+
"user.not-me": "user.not_me"
|
|
20739
|
+
});
|
|
20740
|
+
var CHAT_TITLES = Object.freeze({
|
|
20741
|
+
"login.failed": "Failed sign-in",
|
|
20742
|
+
"login.refused": "Refused sign-in",
|
|
20743
|
+
"login.new_device": "Sign-in from a new device",
|
|
20744
|
+
"login.impossible_travel": "Impossible travel",
|
|
20745
|
+
lockout: "Sign-in locked",
|
|
20746
|
+
"lockout.lifted": "Sign-in lock lifted",
|
|
20747
|
+
"session.limit": "Session limit reached",
|
|
20748
|
+
"password.changed": "Other sessions ended after a password change",
|
|
20749
|
+
"user.not_me": "User reported a sign-in as not theirs",
|
|
20750
|
+
test: "Test message"
|
|
20751
|
+
});
|
|
20752
|
+
var MAX_PARALLEL = 4;
|
|
20753
|
+
var MAX_QUEUE = 500;
|
|
20754
|
+
module2.exports = ({ strapi: strapi2 }) => {
|
|
20755
|
+
const log = createLogger(strapi2);
|
|
20756
|
+
const queue = [];
|
|
20757
|
+
let running = 0;
|
|
20758
|
+
let stopped = false;
|
|
20759
|
+
const pump = () => {
|
|
20760
|
+
while (!stopped && running < MAX_PARALLEL && queue.length) {
|
|
20761
|
+
const job = (
|
|
20762
|
+
/** @type {() => Promise<void>} */
|
|
20763
|
+
queue.shift()
|
|
20764
|
+
);
|
|
20765
|
+
running += 1;
|
|
20766
|
+
job().catch(() => {
|
|
20767
|
+
}).finally(() => {
|
|
20768
|
+
running -= 1;
|
|
20769
|
+
pump();
|
|
20770
|
+
});
|
|
20771
|
+
}
|
|
20772
|
+
};
|
|
20773
|
+
const enqueue = (job) => {
|
|
20774
|
+
if (stopped) return;
|
|
20775
|
+
if (queue.length >= MAX_QUEUE) {
|
|
20776
|
+
queue.shift();
|
|
20777
|
+
log.warn("[webhooks] Queue full; the oldest delivery was dropped");
|
|
20778
|
+
}
|
|
20779
|
+
queue.push(job);
|
|
20780
|
+
pump();
|
|
20781
|
+
};
|
|
20782
|
+
const secretOf = (settings) => {
|
|
20783
|
+
const stored = settings?.genericWebhookSecret;
|
|
20784
|
+
if (typeof stored !== "string" || !stored) return null;
|
|
20785
|
+
try {
|
|
20786
|
+
return decryptToken(stored) || null;
|
|
20787
|
+
} catch {
|
|
20788
|
+
return null;
|
|
20789
|
+
}
|
|
20790
|
+
};
|
|
20791
|
+
const dataOf = (settings, input) => {
|
|
20792
|
+
const options = resolveSecurityLogSettings(settings);
|
|
20793
|
+
const ip = options.storeIp ? normalizeIp(input.ip || "") : null;
|
|
20794
|
+
return {
|
|
20795
|
+
user: input.userId ? { documentId: String(input.userId) } : null,
|
|
20796
|
+
ip: ip && options.anonymizeIp ? anonymizeIp(ip) : ip,
|
|
20797
|
+
userAgent: typeof input.userAgent === "string" ? input.userAgent.slice(0, 256) : null,
|
|
20798
|
+
location: input.geo && (input.geo.country_code || input.geo.city) ? { country: input.geo.country_code || null, city: input.geo.city || null } : null,
|
|
20799
|
+
details: input.details || null
|
|
20800
|
+
};
|
|
20801
|
+
};
|
|
20802
|
+
const chatBody = (kind, event, data) => {
|
|
20803
|
+
const title = CHAT_TITLES[event] || event;
|
|
20804
|
+
const fields = [
|
|
20805
|
+
["User", data.user?.documentId || "-"],
|
|
20806
|
+
["IP", data.ip || "-"],
|
|
20807
|
+
...Object.entries(data.details || {}).slice(0, 6).map(([key, value]) => [key, String(value)])
|
|
20808
|
+
];
|
|
20809
|
+
if (kind === "discord") {
|
|
20810
|
+
return {
|
|
20811
|
+
embeds: [
|
|
20812
|
+
{
|
|
20813
|
+
title,
|
|
20814
|
+
color: 5793266,
|
|
20815
|
+
fields: fields.map(([name, value]) => ({
|
|
20816
|
+
name,
|
|
20817
|
+
value: value.slice(0, 200),
|
|
20818
|
+
inline: true
|
|
20819
|
+
})),
|
|
20820
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
20821
|
+
footer: { text: "Magic Session Manager" }
|
|
20822
|
+
}
|
|
20823
|
+
]
|
|
20824
|
+
};
|
|
20825
|
+
}
|
|
20826
|
+
return {
|
|
20827
|
+
text: title,
|
|
20828
|
+
attachments: [
|
|
20829
|
+
{
|
|
20830
|
+
color: "#2563eb",
|
|
20831
|
+
blocks: [
|
|
20832
|
+
{ type: "header", text: { type: "plain_text", text: title } },
|
|
20833
|
+
{
|
|
20834
|
+
type: "section",
|
|
20835
|
+
fields: fields.map(([name, value]) => ({
|
|
20836
|
+
type: "mrkdwn",
|
|
20837
|
+
text: `*${name}*
|
|
20838
|
+
${value.slice(0, 200)}`
|
|
20839
|
+
}))
|
|
20840
|
+
}
|
|
20841
|
+
]
|
|
20842
|
+
}
|
|
20843
|
+
]
|
|
20844
|
+
};
|
|
20845
|
+
};
|
|
20846
|
+
const service = {
|
|
20847
|
+
EVENT_OF_SECURITY_EVENT,
|
|
20848
|
+
/**
|
|
20849
|
+
* Whether an event is selected.
|
|
20850
|
+
*
|
|
20851
|
+
* @param {Record<string, any>} settings Merged settings.
|
|
20852
|
+
* @param {string} event Webhook event.
|
|
20853
|
+
* @returns {boolean} True when selected.
|
|
20854
|
+
*/
|
|
20855
|
+
isSelected(settings, event) {
|
|
20856
|
+
return resolveDetectionSettings(settings).webhookEvents.includes(event);
|
|
20857
|
+
},
|
|
20858
|
+
/**
|
|
20859
|
+
* Queues an event for the signed webhook and, for non-sign-in events,
|
|
20860
|
+
* Discord and Slack. Sign-in events (`login.success`, `login.suspicious`,
|
|
20861
|
+
* `login.new_location`) reach Discord and Slack through the login alerts
|
|
20862
|
+
* with their richer message. Returns at once.
|
|
20863
|
+
*
|
|
20864
|
+
* @param {string} event Webhook event.
|
|
20865
|
+
* @param {{userId?: string|null, ip?: string|null, userAgent?: string|null, geo?: any,
|
|
20866
|
+
* details?: Record<string, unknown>|null}} input Event facts.
|
|
20867
|
+
* @param {{chat?: boolean}} [options] Whether Discord/Slack get it here.
|
|
20868
|
+
* @returns {void}
|
|
20869
|
+
*/
|
|
20870
|
+
emit(event, input, { chat = true } = {}) {
|
|
20871
|
+
enqueue(async () => {
|
|
20872
|
+
const settings = await getPluginSettings(strapi2);
|
|
20873
|
+
if (!service.isSelected(settings, event)) return;
|
|
20874
|
+
const data = dataOf(settings, input);
|
|
20875
|
+
const detection = resolveDetectionSettings(settings);
|
|
20876
|
+
const secret = secretOf(settings);
|
|
20877
|
+
if (detection.genericWebhookEnabled && detection.genericWebhookUrl && secret) {
|
|
20878
|
+
const request = buildSignedRequest({ event, data, secret });
|
|
20879
|
+
const result = await deliverWithRetries({ url: detection.genericWebhookUrl, ...request });
|
|
20880
|
+
if (!result.ok) {
|
|
20881
|
+
log.warn(
|
|
20882
|
+
`[webhooks] Signed webhook delivery failed (${result.code}, ${result.attempts} attempts)`
|
|
20883
|
+
);
|
|
20884
|
+
}
|
|
20885
|
+
}
|
|
20886
|
+
if (chat && settings.enableWebhooks) {
|
|
20887
|
+
const notifications = strapi2.plugin("magic-sessionmanager").service("notifications");
|
|
20888
|
+
const targets = [
|
|
20889
|
+
["discord", settings.discordWebhookUrl],
|
|
20890
|
+
["slack", settings.slackWebhookUrl]
|
|
20891
|
+
].filter(([, url]) => typeof url === "string" && url);
|
|
20892
|
+
await Promise.allSettled(
|
|
20893
|
+
targets.map(
|
|
20894
|
+
([kind, url]) => notifications.sendWebhook({
|
|
20895
|
+
event,
|
|
20896
|
+
data: chatBody(kind, event, data),
|
|
20897
|
+
webhookUrl: url
|
|
20898
|
+
})
|
|
20899
|
+
)
|
|
20900
|
+
);
|
|
20901
|
+
}
|
|
20902
|
+
});
|
|
20903
|
+
},
|
|
20904
|
+
/**
|
|
20905
|
+
* Emits the webhook event that belongs to a security log event, if any.
|
|
20906
|
+
*
|
|
20907
|
+
* @param {{event: string, actorType?: string, actorId?: any, targetId?: any, ip?: any,
|
|
20908
|
+
* userAgent?: any, meta?: any}} input Security event input.
|
|
20909
|
+
* @returns {void}
|
|
20910
|
+
*/
|
|
20911
|
+
emitSecurityEvent(input) {
|
|
20912
|
+
const event = EVENT_OF_SECURITY_EVENT[input?.event];
|
|
20913
|
+
if (!event) return;
|
|
20914
|
+
service.emit(event, {
|
|
20915
|
+
userId: input.targetId || (input.actorType === "user" ? input.actorId : null) || null,
|
|
20916
|
+
// An admin's own address is not sent for admin actions.
|
|
20917
|
+
ip: input.actorType === "admin" ? null : input.ip,
|
|
20918
|
+
userAgent: input.actorType === "admin" ? null : input.userAgent,
|
|
20919
|
+
details: input.meta || null
|
|
20920
|
+
});
|
|
20921
|
+
},
|
|
20922
|
+
/**
|
|
20923
|
+
* Sends one `test` event to the signed webhook now, without retries.
|
|
20924
|
+
*
|
|
20925
|
+
* @returns {Promise<{ok: boolean, status: number|null, code: string|null}>} Result.
|
|
20926
|
+
*/
|
|
20927
|
+
async sendTest() {
|
|
20928
|
+
const settings = await getPluginSettings(strapi2);
|
|
20929
|
+
const detection = resolveDetectionSettings(settings);
|
|
20930
|
+
const secret = secretOf(settings);
|
|
20931
|
+
if (!detection.genericWebhookUrl) return { ok: false, status: null, code: "no_url" };
|
|
20932
|
+
if (!secret) return { ok: false, status: null, code: "no_secret" };
|
|
20933
|
+
const request = buildSignedRequest({
|
|
20934
|
+
event: "test",
|
|
20935
|
+
data: { user: null, ip: null, userAgent: null, location: null, details: { test: true } },
|
|
20936
|
+
secret
|
|
20937
|
+
});
|
|
20938
|
+
try {
|
|
20939
|
+
const { status } = await deliverOnce({ url: detection.genericWebhookUrl, ...request });
|
|
20940
|
+
return { ok: true, status, code: null };
|
|
20941
|
+
} catch (err) {
|
|
20942
|
+
return {
|
|
20943
|
+
ok: false,
|
|
20944
|
+
status: Number.isInteger(err?.status) ? err.status : null,
|
|
20945
|
+
code: typeof err?.code === "string" ? err.code : "network_error"
|
|
20946
|
+
};
|
|
20947
|
+
}
|
|
20948
|
+
},
|
|
20949
|
+
/**
|
|
20950
|
+
* Stops new deliveries (plugin destroy).
|
|
20951
|
+
*
|
|
20952
|
+
* @returns {void}
|
|
20953
|
+
*/
|
|
20954
|
+
stop() {
|
|
20955
|
+
stopped = true;
|
|
20956
|
+
queue.length = 0;
|
|
20957
|
+
}
|
|
20958
|
+
};
|
|
20959
|
+
return service;
|
|
20960
|
+
};
|
|
20961
|
+
}
|
|
20962
|
+
});
|
|
20963
|
+
|
|
17865
20964
|
// server/src/services/index.js
|
|
17866
20965
|
var require_services = __commonJS({
|
|
17867
20966
|
"server/src/services/index.js"(exports2, module2) {
|
|
@@ -17870,11 +20969,13 @@ var require_services = __commonJS({
|
|
|
17870
20969
|
var geolocation = require_geolocation();
|
|
17871
20970
|
var notifications = require_notifications();
|
|
17872
20971
|
var securityLog = require_security_log();
|
|
20972
|
+
var webhooks = require_webhooks2();
|
|
17873
20973
|
module2.exports = {
|
|
17874
20974
|
session,
|
|
17875
20975
|
geolocation,
|
|
17876
20976
|
notifications,
|
|
17877
|
-
"security-log": securityLog
|
|
20977
|
+
"security-log": securityLog,
|
|
20978
|
+
webhooks
|
|
17878
20979
|
};
|
|
17879
20980
|
}
|
|
17880
20981
|
});
|