strapi-plugin-magic-sessionmanager 4.15.0 → 4.16.1
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 +77 -0
- package/README.md +112 -14
- package/dist/admin/{Analytics-Dbs5QXLb.js → Analytics-CMR62DiD.js} +1 -1
- package/dist/admin/{Analytics-HK6_TEmk.mjs → Analytics-FcRt0X62.mjs} +1 -1
- package/dist/admin/{App-7SxOBJP5.js → App-CmytGbze.js} +935 -88
- package/dist/admin/{App-BOFzZ5d8.mjs → App-DBieSWB0.mjs} +936 -89
- package/dist/admin/{OnlineUsersWidget-Dns_74xJ.js → OnlineUsersWidget-Lzx9XB74.js} +1 -1
- package/dist/admin/{OnlineUsersWidget-CoCxnww-.mjs → OnlineUsersWidget-zP9Hl_it.mjs} +1 -1
- package/dist/admin/{Settings-B6CrR-07.js → Settings-1v--SXC0.js} +350 -68
- package/dist/admin/{Settings-DYRShQ8W.mjs → Settings-CZOPusQK.mjs} +351 -69
- package/dist/admin/{de-B3mPtxsW.mjs → de-D3TSA066.mjs} +106 -2
- package/dist/admin/{de-bkkCvSxX.js → de-y_9mdVT7.js} +106 -2
- package/dist/admin/{en-BnU8BNkN.mjs → en-B60I97bK.mjs} +106 -2
- package/dist/admin/{en-DMICyIow.js → en-CIQB8nfI.js} +106 -2
- package/dist/admin/{es-BxMgfJ1Y.mjs → es-CJEL_iGC.mjs} +106 -2
- package/dist/admin/{es-OSzHGRIu.js → es-DHhHzlRY.js} +106 -2
- package/dist/admin/{fr-WPrbtx8k.mjs → fr-BfBK_iuV.mjs} +106 -2
- package/dist/admin/{fr-Bu_8miJ4.js → fr-D86FTt1w.js} +106 -2
- package/dist/admin/{index-CNSJITRX.js → index-CSJJn4qy.js} +18 -10
- package/dist/admin/{index-lnZBc5n0.mjs → index-tt61o2VH.mjs} +18 -10
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.mjs +1 -1
- package/dist/admin/{pt-B08xnb0K.js → pt-BE-FT-L8.js} +106 -2
- package/dist/admin/{pt-C41KyEDN.mjs → pt-C3PSvC7z.mjs} +106 -2
- package/dist/server/index.js +3114 -457
- package/dist/server/index.mjs +3114 -457
- package/package.json +1 -1
package/dist/server/index.mjs
CHANGED
|
@@ -901,6 +901,768 @@ var require_strapi_version = __commonJS({
|
|
|
901
901
|
}
|
|
902
902
|
});
|
|
903
903
|
|
|
904
|
+
// server/src/utils/security-log-settings.js
|
|
905
|
+
var require_security_log_settings = __commonJS({
|
|
906
|
+
"server/src/utils/security-log-settings.js"(exports, module) {
|
|
907
|
+
"use strict";
|
|
908
|
+
var SECURITY_LOG_DEFAULTS = Object.freeze({
|
|
909
|
+
adminSignInHistory: true,
|
|
910
|
+
adminContentActivity: false,
|
|
911
|
+
securityLogStoreIp: true,
|
|
912
|
+
securityLogAnonymizeIp: false,
|
|
913
|
+
securityLogGeoLookup: false,
|
|
914
|
+
securityLogRetentionDays: 90
|
|
915
|
+
});
|
|
916
|
+
var SECURITY_LOG_BOOLEAN_KEYS = Object.freeze([
|
|
917
|
+
"adminSignInHistory",
|
|
918
|
+
"adminContentActivity",
|
|
919
|
+
"securityLogStoreIp",
|
|
920
|
+
"securityLogAnonymizeIp",
|
|
921
|
+
"securityLogGeoLookup"
|
|
922
|
+
]);
|
|
923
|
+
var SECURITY_LOG_RETENTION_RANGE = Object.freeze({ min: 7, max: 730 });
|
|
924
|
+
var LEGACY_RETENTION_MIN = 1;
|
|
925
|
+
var SECURITY_LOG_KEYS = Object.freeze(Object.keys(SECURITY_LOG_DEFAULTS));
|
|
926
|
+
function resolveSecurityLogSettings(settings) {
|
|
927
|
+
const source = settings && typeof settings === "object" ? settings : {};
|
|
928
|
+
const flag = (key) => typeof source[key] === "boolean" ? (
|
|
929
|
+
/** @type {boolean} */
|
|
930
|
+
source[key]
|
|
931
|
+
) : (
|
|
932
|
+
/** @type {any} */
|
|
933
|
+
SECURITY_LOG_DEFAULTS[key]
|
|
934
|
+
);
|
|
935
|
+
const days = Number(source.securityLogRetentionDays);
|
|
936
|
+
const { min, max } = SECURITY_LOG_RETENTION_RANGE;
|
|
937
|
+
return {
|
|
938
|
+
signIns: flag("adminSignInHistory"),
|
|
939
|
+
content: flag("adminContentActivity"),
|
|
940
|
+
storeIp: flag("securityLogStoreIp"),
|
|
941
|
+
anonymizeIp: flag("securityLogAnonymizeIp"),
|
|
942
|
+
geoLookup: flag("securityLogGeoLookup"),
|
|
943
|
+
retentionDays: Number.isInteger(days) && days >= min && days <= max ? days : Number.isInteger(days) && days >= LEGACY_RETENTION_MIN && days < min ? min : SECURITY_LOG_DEFAULTS.securityLogRetentionDays
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
function legacyRetentionBelowMinimum(stored) {
|
|
947
|
+
if (!stored || typeof stored !== "object") return null;
|
|
948
|
+
const days = Number(stored.securityLogRetentionDays);
|
|
949
|
+
const { min } = SECURITY_LOG_RETENTION_RANGE;
|
|
950
|
+
return Number.isInteger(days) && days >= LEGACY_RETENTION_MIN && days < min ? days : null;
|
|
951
|
+
}
|
|
952
|
+
function validateSecurityLogSettings(body) {
|
|
953
|
+
const values = {};
|
|
954
|
+
const errors = [];
|
|
955
|
+
const has = (key) => Object.prototype.hasOwnProperty.call(body, key) && body[key] !== void 0;
|
|
956
|
+
for (const key of SECURITY_LOG_BOOLEAN_KEYS) {
|
|
957
|
+
if (!has(key)) continue;
|
|
958
|
+
if (typeof body[key] !== "boolean") {
|
|
959
|
+
errors.push({ path: [key], message: `${key} must be a boolean` });
|
|
960
|
+
} else {
|
|
961
|
+
values[key] = /** @type {boolean} */
|
|
962
|
+
body[key];
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
if (has("securityLogRetentionDays")) {
|
|
966
|
+
const raw = body.securityLogRetentionDays;
|
|
967
|
+
const value = typeof raw === "number" ? raw : typeof raw === "string" && /^\s*\d+\s*$/.test(raw) ? Number.parseInt(raw, 10) : NaN;
|
|
968
|
+
const { min, max } = SECURITY_LOG_RETENTION_RANGE;
|
|
969
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
970
|
+
errors.push({
|
|
971
|
+
path: ["securityLogRetentionDays"],
|
|
972
|
+
message: `securityLogRetentionDays must be an integer between ${min} and ${max}`
|
|
973
|
+
});
|
|
974
|
+
} else {
|
|
975
|
+
values.securityLogRetentionDays = value;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return { values, errors };
|
|
979
|
+
}
|
|
980
|
+
module.exports = {
|
|
981
|
+
LEGACY_RETENTION_MIN,
|
|
982
|
+
SECURITY_LOG_BOOLEAN_KEYS,
|
|
983
|
+
SECURITY_LOG_DEFAULTS,
|
|
984
|
+
SECURITY_LOG_KEYS,
|
|
985
|
+
SECURITY_LOG_RETENTION_RANGE,
|
|
986
|
+
legacyRetentionBelowMinimum,
|
|
987
|
+
resolveSecurityLogSettings,
|
|
988
|
+
validateSecurityLogSettings
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
|
|
993
|
+
// server/src/utils/settings-loader.js
|
|
994
|
+
var require_settings_loader = __commonJS({
|
|
995
|
+
"server/src/utils/settings-loader.js"(exports, module) {
|
|
996
|
+
"use strict";
|
|
997
|
+
var { getCoordinator } = require_coordination();
|
|
998
|
+
var PLUGIN_ID = "magic-sessionmanager";
|
|
999
|
+
var SETTINGS_KEY = "settings";
|
|
1000
|
+
var CACHE_TTL_MS = 30 * 1e3;
|
|
1001
|
+
var REVISION_CHECK_MS = 2 * 1e3;
|
|
1002
|
+
var SETTINGS_REVISION = "settings";
|
|
1003
|
+
var GEO_IP_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
|
|
1004
|
+
var GEO_LOOKUP_FAILURE_MODES = /* @__PURE__ */ new Set(["auto", "allow", "block"]);
|
|
1005
|
+
var cached = null;
|
|
1006
|
+
var cachedAt = 0;
|
|
1007
|
+
var cachedRevision = null;
|
|
1008
|
+
var revisionCheckedAt = 0;
|
|
1009
|
+
var generation = 0;
|
|
1010
|
+
function toIntInRange(value, fallback, min, max) {
|
|
1011
|
+
const n = Number.parseInt(value, 10);
|
|
1012
|
+
if (!Number.isFinite(n)) return fallback;
|
|
1013
|
+
return Math.max(min, Math.min(n, max));
|
|
1014
|
+
}
|
|
1015
|
+
function normalizeRetentionDays(value, fallback = 90) {
|
|
1016
|
+
const n = Number.parseInt(value, 10);
|
|
1017
|
+
if (!Number.isFinite(n)) return fallback;
|
|
1018
|
+
if (n === -1) return -1;
|
|
1019
|
+
return Math.max(1, Math.min(n, 365));
|
|
1020
|
+
}
|
|
1021
|
+
function getSessionCreationGraceMs(settings = {}) {
|
|
1022
|
+
if (!settings || settings.sessionCreationGraceMs === void 0) {
|
|
1023
|
+
return 5e3;
|
|
1024
|
+
}
|
|
1025
|
+
return toIntInRange(settings.sessionCreationGraceMs, 5e3, 0, 3e4);
|
|
1026
|
+
}
|
|
1027
|
+
function normalizeGeoIpProvider(value) {
|
|
1028
|
+
return GEO_IP_PROVIDERS.has(value) ? value : "auto";
|
|
1029
|
+
}
|
|
1030
|
+
function normalizeGeoLookupFailureMode(value) {
|
|
1031
|
+
return GEO_LOOKUP_FAILURE_MODES.has(value) ? value : "auto";
|
|
1032
|
+
}
|
|
1033
|
+
function normalizeGeoIpDatabasePath(value) {
|
|
1034
|
+
if (typeof value !== "string") return "";
|
|
1035
|
+
return value.replace(/\0/g, "").trim().slice(0, 1024);
|
|
1036
|
+
}
|
|
1037
|
+
function normalizeStoredSettings(stored) {
|
|
1038
|
+
if (!stored || typeof stored !== "object") return {};
|
|
1039
|
+
const out = {};
|
|
1040
|
+
if (stored.inactivityTimeout !== void 0) {
|
|
1041
|
+
const minutes = toIntInRange(stored.inactivityTimeout, 15, 1, 1440);
|
|
1042
|
+
out.inactivityTimeout = minutes * 60 * 1e3;
|
|
1043
|
+
}
|
|
1044
|
+
if (stored.cleanupInterval !== void 0) {
|
|
1045
|
+
const minutes = toIntInRange(stored.cleanupInterval, 30, 5, 1440);
|
|
1046
|
+
out.cleanupInterval = minutes * 60 * 1e3;
|
|
1047
|
+
}
|
|
1048
|
+
if (stored.lastSeenRateLimit !== void 0) {
|
|
1049
|
+
const seconds = toIntInRange(stored.lastSeenRateLimit, 30, 5, 300);
|
|
1050
|
+
out.lastSeenRateLimit = seconds * 1e3;
|
|
1051
|
+
}
|
|
1052
|
+
if (stored.retentionDays !== void 0) {
|
|
1053
|
+
out.retentionDays = normalizeRetentionDays(stored.retentionDays, 90);
|
|
1054
|
+
}
|
|
1055
|
+
if (stored.maxSessionAgeDays !== void 0) {
|
|
1056
|
+
out.maxSessionAgeDays = toIntInRange(stored.maxSessionAgeDays, 30, 1, 365);
|
|
1057
|
+
}
|
|
1058
|
+
if (stored.maxFailedLogins !== void 0) {
|
|
1059
|
+
out.maxFailedLogins = toIntInRange(stored.maxFailedLogins, 5, 0, 100);
|
|
1060
|
+
}
|
|
1061
|
+
const passthroughBooleans = [
|
|
1062
|
+
"enableGeolocation",
|
|
1063
|
+
"enableSecurityScoring",
|
|
1064
|
+
"blockSuspiciousSessions",
|
|
1065
|
+
"enableEmailAlerts",
|
|
1066
|
+
"alertOnSuspiciousLogin",
|
|
1067
|
+
"alertOnNewLocation",
|
|
1068
|
+
"alertOnVpnProxy",
|
|
1069
|
+
"enableWebhooks",
|
|
1070
|
+
"enableGeofencing",
|
|
1071
|
+
"strictSessionEnforcement",
|
|
1072
|
+
// Opt-in: use a single-statement SQL UPDATE in the cleanup job instead
|
|
1073
|
+
// of batching via the Document Service. Bypasses lifecycle hooks but
|
|
1074
|
+
// drains the backlog in one query on very large installations.
|
|
1075
|
+
"cleanupUseDbDirect",
|
|
1076
|
+
// Security event log (4.15).
|
|
1077
|
+
"adminSignInHistory",
|
|
1078
|
+
"adminContentActivity",
|
|
1079
|
+
"securityLogStoreIp",
|
|
1080
|
+
"securityLogAnonymizeIp",
|
|
1081
|
+
// Opt-in location lookup of security events (4.17).
|
|
1082
|
+
"securityLogGeoLookup"
|
|
1083
|
+
];
|
|
1084
|
+
if (stored.sessionCreationGraceMs !== void 0) {
|
|
1085
|
+
out.sessionCreationGraceMs = getSessionCreationGraceMs(stored);
|
|
1086
|
+
}
|
|
1087
|
+
if (stored.rateLimitWriteMax !== void 0) {
|
|
1088
|
+
out.rateLimitWriteMax = toIntInRange(stored.rateLimitWriteMax, 10, 1, 1e3);
|
|
1089
|
+
}
|
|
1090
|
+
if (stored.rateLimitReadMax !== void 0) {
|
|
1091
|
+
out.rateLimitReadMax = toIntInRange(stored.rateLimitReadMax, 120, 1, 1e4);
|
|
1092
|
+
}
|
|
1093
|
+
if (stored.rateLimitWindowSeconds !== void 0) {
|
|
1094
|
+
out.rateLimitWindowSeconds = toIntInRange(stored.rateLimitWindowSeconds, 60, 10, 3600);
|
|
1095
|
+
}
|
|
1096
|
+
for (const key of passthroughBooleans) {
|
|
1097
|
+
if (stored[key] !== void 0) out[key] = !!stored[key];
|
|
1098
|
+
}
|
|
1099
|
+
if (typeof stored.discordWebhookUrl === "string") {
|
|
1100
|
+
out.discordWebhookUrl = stored.discordWebhookUrl;
|
|
1101
|
+
}
|
|
1102
|
+
if (typeof stored.slackWebhookUrl === "string") {
|
|
1103
|
+
out.slackWebhookUrl = stored.slackWebhookUrl;
|
|
1104
|
+
}
|
|
1105
|
+
if (Array.isArray(stored.allowedCountries)) {
|
|
1106
|
+
out.allowedCountries = stored.allowedCountries;
|
|
1107
|
+
}
|
|
1108
|
+
if (Array.isArray(stored.blockedCountries)) {
|
|
1109
|
+
out.blockedCountries = stored.blockedCountries;
|
|
1110
|
+
}
|
|
1111
|
+
if (stored.geoIpProvider !== void 0) {
|
|
1112
|
+
out.geoIpProvider = normalizeGeoIpProvider(stored.geoIpProvider);
|
|
1113
|
+
}
|
|
1114
|
+
if (stored.geoIpDatabasePath !== void 0) {
|
|
1115
|
+
out.geoIpDatabasePath = normalizeGeoIpDatabasePath(stored.geoIpDatabasePath);
|
|
1116
|
+
}
|
|
1117
|
+
if (stored.geoLookupFailureMode !== void 0) {
|
|
1118
|
+
out.geoLookupFailureMode = normalizeGeoLookupFailureMode(stored.geoLookupFailureMode);
|
|
1119
|
+
}
|
|
1120
|
+
if (stored.emailTemplates && typeof stored.emailTemplates === "object") {
|
|
1121
|
+
out.emailTemplates = stored.emailTemplates;
|
|
1122
|
+
}
|
|
1123
|
+
if (stored.securityLogRetentionDays !== void 0) {
|
|
1124
|
+
out.securityLogRetentionDays = toIntInRange(stored.securityLogRetentionDays, 90, 7, 730);
|
|
1125
|
+
}
|
|
1126
|
+
if (stored.trustedProxies !== void 0) {
|
|
1127
|
+
out.trustedProxies = stored.trustedProxies;
|
|
1128
|
+
}
|
|
1129
|
+
return out;
|
|
1130
|
+
}
|
|
1131
|
+
async function getPluginSettings(strapi2) {
|
|
1132
|
+
const now = Date.now();
|
|
1133
|
+
const coordinator = getCoordinator(strapi2);
|
|
1134
|
+
if (cached && now - cachedAt < CACHE_TTL_MS) {
|
|
1135
|
+
if (now - revisionCheckedAt < REVISION_CHECK_MS) return cached;
|
|
1136
|
+
revisionCheckedAt = now;
|
|
1137
|
+
let revision2;
|
|
1138
|
+
try {
|
|
1139
|
+
revision2 = await coordinator.getRevision(SETTINGS_REVISION);
|
|
1140
|
+
} catch {
|
|
1141
|
+
return cached;
|
|
1142
|
+
}
|
|
1143
|
+
if (revision2 === cachedRevision) return cached;
|
|
1144
|
+
}
|
|
1145
|
+
const loadGeneration = generation;
|
|
1146
|
+
let revision;
|
|
1147
|
+
try {
|
|
1148
|
+
revision = await coordinator.getRevision(SETTINGS_REVISION);
|
|
1149
|
+
} catch {
|
|
1150
|
+
revision = null;
|
|
1151
|
+
}
|
|
1152
|
+
const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
|
|
1153
|
+
let storedSettings;
|
|
1154
|
+
try {
|
|
1155
|
+
const pluginStore = strapi2.store({ type: "plugin", name: PLUGIN_ID });
|
|
1156
|
+
const raw = await pluginStore.get({ key: SETTINGS_KEY });
|
|
1157
|
+
storedSettings = normalizeStoredSettings(raw);
|
|
1158
|
+
} catch {
|
|
1159
|
+
strapi2.log.error(
|
|
1160
|
+
`[${PLUGIN_ID}] settings-loader: store read failed; strict session enforcement is enabled and geolocation is disabled`
|
|
1161
|
+
);
|
|
1162
|
+
storedSettings = { strictSessionEnforcement: true, enableGeolocation: false };
|
|
1163
|
+
}
|
|
1164
|
+
const merged = { ...staticConfig, ...storedSettings };
|
|
1165
|
+
if (loadGeneration !== generation) return merged;
|
|
1166
|
+
cached = merged;
|
|
1167
|
+
cachedAt = now;
|
|
1168
|
+
cachedRevision = revision;
|
|
1169
|
+
revisionCheckedAt = now;
|
|
1170
|
+
return merged;
|
|
1171
|
+
}
|
|
1172
|
+
function getPluginSettingsSync(strapi2) {
|
|
1173
|
+
if (cached) return cached;
|
|
1174
|
+
return strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
|
|
1175
|
+
}
|
|
1176
|
+
function peekCachedSettings() {
|
|
1177
|
+
return cached;
|
|
1178
|
+
}
|
|
1179
|
+
function invalidateSettingsCache() {
|
|
1180
|
+
generation += 1;
|
|
1181
|
+
cached = null;
|
|
1182
|
+
cachedAt = 0;
|
|
1183
|
+
cachedRevision = null;
|
|
1184
|
+
revisionCheckedAt = 0;
|
|
1185
|
+
}
|
|
1186
|
+
async function getSettingsRevision(strapi2) {
|
|
1187
|
+
return getCoordinator(strapi2).getRevision(SETTINGS_REVISION);
|
|
1188
|
+
}
|
|
1189
|
+
async function notifySettingsChanged(strapi2) {
|
|
1190
|
+
invalidateSettingsCache();
|
|
1191
|
+
try {
|
|
1192
|
+
return await getCoordinator(strapi2).bumpRevision(SETTINGS_REVISION);
|
|
1193
|
+
} catch (err) {
|
|
1194
|
+
strapi2?.log?.warn?.(
|
|
1195
|
+
`[${PLUGIN_ID}] settings-loader: could not publish the settings revision:`,
|
|
1196
|
+
err?.name || "Error"
|
|
1197
|
+
);
|
|
1198
|
+
return null;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
module.exports = {
|
|
1202
|
+
getPluginSettings,
|
|
1203
|
+
getPluginSettingsSync,
|
|
1204
|
+
peekCachedSettings,
|
|
1205
|
+
invalidateSettingsCache,
|
|
1206
|
+
notifySettingsChanged,
|
|
1207
|
+
getSettingsRevision,
|
|
1208
|
+
normalizeStoredSettings,
|
|
1209
|
+
normalizeRetentionDays,
|
|
1210
|
+
getSessionCreationGraceMs,
|
|
1211
|
+
normalizeGeoIpProvider,
|
|
1212
|
+
normalizeGeoIpDatabasePath,
|
|
1213
|
+
normalizeGeoLookupFailureMode
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
|
|
1218
|
+
// server/src/utils/security-log-model.js
|
|
1219
|
+
var require_security_log_model = __commonJS({
|
|
1220
|
+
"server/src/utils/security-log-model.js"(exports, module) {
|
|
1221
|
+
"use strict";
|
|
1222
|
+
var SECURITY_EVENTS = Object.freeze({
|
|
1223
|
+
ADMIN_SIGN_IN: "admin.sign-in",
|
|
1224
|
+
ADMIN_SIGN_IN_FAILED: "admin.sign-in.failed",
|
|
1225
|
+
ADMIN_LOCKOUT: "admin.lockout",
|
|
1226
|
+
ADMIN_SIGN_OUT: "admin.sign-out",
|
|
1227
|
+
ADMIN_SESSION_REVOKED: "admin.session.revoked",
|
|
1228
|
+
ADMIN_CONTENT_VIEW: "admin.content.view",
|
|
1229
|
+
ADMIN_CONTENT_CREATE: "admin.content.create",
|
|
1230
|
+
ADMIN_CONTENT_UPDATE: "admin.content.update",
|
|
1231
|
+
ADMIN_CONTENT_PUBLISH: "admin.content.publish",
|
|
1232
|
+
ADMIN_CONTENT_UNPUBLISH: "admin.content.unpublish",
|
|
1233
|
+
ADMIN_CONTENT_DISCARD: "admin.content.discard",
|
|
1234
|
+
ADMIN_CONTENT_DELETE: "admin.content.delete",
|
|
1235
|
+
ADMIN_CONTENT_CLONE: "admin.content.clone",
|
|
1236
|
+
// 4.17: always recorded (no switch), never values.
|
|
1237
|
+
SETTINGS_UPDATED: "settings.updated",
|
|
1238
|
+
LOG_RETENTION_PURGED: "security-log.retention.purged",
|
|
1239
|
+
LOG_READ: "security-log.read"
|
|
1240
|
+
});
|
|
1241
|
+
var KEEP_WITHOUT_ACTOR_EVENTS = Object.freeze([
|
|
1242
|
+
SECURITY_EVENTS.ADMIN_SESSION_REVOKED,
|
|
1243
|
+
SECURITY_EVENTS.SETTINGS_UPDATED,
|
|
1244
|
+
SECURITY_EVENTS.LOG_READ
|
|
1245
|
+
]);
|
|
1246
|
+
function dropRankOf(event) {
|
|
1247
|
+
if (event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
|
|
1248
|
+
return { rank: 0, family: "failed" };
|
|
1249
|
+
}
|
|
1250
|
+
if (event === SECURITY_EVENTS.ADMIN_CONTENT_VIEW) return { rank: 1, family: "content-view" };
|
|
1251
|
+
if (event.startsWith("admin.content.") || event === SECURITY_EVENTS.LOG_READ) {
|
|
1252
|
+
return { rank: 2, family: "activity" };
|
|
1253
|
+
}
|
|
1254
|
+
return { rank: 3, family: "account" };
|
|
1255
|
+
}
|
|
1256
|
+
var EVENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}(\.[a-z][a-z0-9-]{0,30}){1,3}$/;
|
|
1257
|
+
var ACTOR_TYPES = Object.freeze(["admin", "user", "system"]);
|
|
1258
|
+
var ADMIN_SIGN_IN_EVENTS = Object.freeze([
|
|
1259
|
+
SECURITY_EVENTS.ADMIN_SIGN_IN,
|
|
1260
|
+
SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
|
|
1261
|
+
SECURITY_EVENTS.ADMIN_LOCKOUT,
|
|
1262
|
+
SECURITY_EVENTS.ADMIN_SIGN_OUT,
|
|
1263
|
+
SECURITY_EVENTS.ADMIN_SESSION_REVOKED
|
|
1264
|
+
]);
|
|
1265
|
+
var SIGN_IN_FILTERS = Object.freeze({
|
|
1266
|
+
all: ADMIN_SIGN_IN_EVENTS,
|
|
1267
|
+
succeeded: [SECURITY_EVENTS.ADMIN_SIGN_IN],
|
|
1268
|
+
failed: [SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED, SECURITY_EVENTS.ADMIN_LOCKOUT],
|
|
1269
|
+
"signed-out": [SECURITY_EVENTS.ADMIN_SIGN_OUT, SECURITY_EVENTS.ADMIN_SESSION_REVOKED]
|
|
1270
|
+
});
|
|
1271
|
+
var CONTENT_ACTIONS = Object.freeze([
|
|
1272
|
+
"view",
|
|
1273
|
+
"create",
|
|
1274
|
+
"update",
|
|
1275
|
+
"publish",
|
|
1276
|
+
"unpublish",
|
|
1277
|
+
"discard",
|
|
1278
|
+
"delete",
|
|
1279
|
+
"clone"
|
|
1280
|
+
]);
|
|
1281
|
+
var contentEvent = (action) => `admin.content.${action}`;
|
|
1282
|
+
var ADMIN_CONTENT_EVENTS = Object.freeze(CONTENT_ACTIONS.map(contentEvent));
|
|
1283
|
+
function recordingSwitchOf(event) {
|
|
1284
|
+
if (ADMIN_SIGN_IN_EVENTS.includes(event)) return "signIns";
|
|
1285
|
+
if (event.startsWith("admin.content.")) return "content";
|
|
1286
|
+
return "always";
|
|
1287
|
+
}
|
|
1288
|
+
var CONTENT_MANAGER_HANDLERS = Object.freeze({
|
|
1289
|
+
"collection-types.findOne": { action: "view", kind: "collection" },
|
|
1290
|
+
"collection-types.create": { action: "create", kind: "collection" },
|
|
1291
|
+
"collection-types.update": { action: "update", kind: "collection" },
|
|
1292
|
+
"collection-types.clone": { action: "clone", kind: "collection" },
|
|
1293
|
+
"collection-types.autoClone": { action: "clone", kind: "collection" },
|
|
1294
|
+
"collection-types.publish": { action: "publish", kind: "collection" },
|
|
1295
|
+
"collection-types.unpublish": { action: "unpublish", kind: "collection" },
|
|
1296
|
+
"collection-types.discard": { action: "discard", kind: "collection" },
|
|
1297
|
+
"collection-types.delete": { action: "delete", kind: "collection" },
|
|
1298
|
+
"collection-types.bulkDelete": { action: "delete", kind: "collection", bulk: true },
|
|
1299
|
+
"collection-types.bulkPublish": { action: "publish", kind: "collection", bulk: true },
|
|
1300
|
+
"collection-types.bulkUnpublish": { action: "unpublish", kind: "collection", bulk: true },
|
|
1301
|
+
"single-types.find": { action: "view", kind: "single" },
|
|
1302
|
+
"single-types.createOrUpdate": { action: "update", kind: "single" },
|
|
1303
|
+
"single-types.delete": { action: "delete", kind: "single" },
|
|
1304
|
+
"single-types.publish": { action: "publish", kind: "single" },
|
|
1305
|
+
"single-types.unpublish": { action: "unpublish", kind: "single" },
|
|
1306
|
+
"single-types.discard": { action: "discard", kind: "single" }
|
|
1307
|
+
});
|
|
1308
|
+
var UID_PATTERN = /^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/;
|
|
1309
|
+
var LOCALE_PATTERN = /^[A-Za-z0-9-]{1,20}$/;
|
|
1310
|
+
var DOCUMENT_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/;
|
|
1311
|
+
var MAX_META_BYTES = 2048;
|
|
1312
|
+
var MAX_META_KEYS = 16;
|
|
1313
|
+
function boundMeta(meta) {
|
|
1314
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
|
|
1315
|
+
const out = {};
|
|
1316
|
+
let keys = 0;
|
|
1317
|
+
for (const [key, value] of Object.entries(meta)) {
|
|
1318
|
+
if (keys >= MAX_META_KEYS) break;
|
|
1319
|
+
if (!/^[a-zA-Z][a-zA-Z0-9]{0,39}$/.test(key)) continue;
|
|
1320
|
+
if (value === null || typeof value === "boolean") out[key] = value;
|
|
1321
|
+
else if (typeof value === "number" && Number.isFinite(value)) out[key] = value;
|
|
1322
|
+
else if (typeof value === "string") out[key] = value.slice(0, 255);
|
|
1323
|
+
else continue;
|
|
1324
|
+
keys += 1;
|
|
1325
|
+
}
|
|
1326
|
+
if (!keys) return null;
|
|
1327
|
+
while (JSON.stringify(out).length > MAX_META_BYTES) {
|
|
1328
|
+
const longest = Object.keys(out).reduce(
|
|
1329
|
+
(a, b) => String(out[a] ?? "").length >= String(out[b] ?? "").length ? a : b
|
|
1330
|
+
);
|
|
1331
|
+
delete out[longest];
|
|
1332
|
+
}
|
|
1333
|
+
return Object.keys(out).length ? out : null;
|
|
1334
|
+
}
|
|
1335
|
+
function handlerName(handler) {
|
|
1336
|
+
if (typeof handler !== "string") return null;
|
|
1337
|
+
const parts = handler.split(".");
|
|
1338
|
+
if (parts.length < 2) return null;
|
|
1339
|
+
const tail = parts.slice(-2).join(".");
|
|
1340
|
+
return tail.includes("::") ? tail.split("::").pop() || null : tail;
|
|
1341
|
+
}
|
|
1342
|
+
function shaped(value, pattern) {
|
|
1343
|
+
return typeof value === "string" && pattern.test(value) ? value : null;
|
|
1344
|
+
}
|
|
1345
|
+
function describeContentManagerRequest({
|
|
1346
|
+
status,
|
|
1347
|
+
route,
|
|
1348
|
+
params,
|
|
1349
|
+
query,
|
|
1350
|
+
requestBody,
|
|
1351
|
+
responseBody
|
|
1352
|
+
}) {
|
|
1353
|
+
if (!(status >= 200 && status < 300)) return null;
|
|
1354
|
+
if (route?.info?.pluginName !== "content-manager") return null;
|
|
1355
|
+
const name = handlerName(route.handler);
|
|
1356
|
+
const mapping = name ? (
|
|
1357
|
+
/** @type {any} */
|
|
1358
|
+
CONTENT_MANAGER_HANDLERS[name]
|
|
1359
|
+
) : null;
|
|
1360
|
+
if (!mapping) return null;
|
|
1361
|
+
const contentType = shaped(params?.model, UID_PATTERN);
|
|
1362
|
+
if (!contentType) return null;
|
|
1363
|
+
const data = responseBody && typeof responseBody === "object" && !Array.isArray(responseBody) ? responseBody.data : null;
|
|
1364
|
+
const single = data && typeof data === "object" && !Array.isArray(data) ? data : null;
|
|
1365
|
+
let count = null;
|
|
1366
|
+
if (mapping.bulk) {
|
|
1367
|
+
const ids = requestBody?.documentIds;
|
|
1368
|
+
count = Array.isArray(ids) ? Math.min(ids.length, 1e5) : null;
|
|
1369
|
+
if (typeof responseBody?.data?.count === "number") count = responseBody.data.count;
|
|
1370
|
+
}
|
|
1371
|
+
const documentId = mapping.bulk ? null : shaped(params?.id, DOCUMENT_ID_PATTERN) || shaped(single?.documentId, DOCUMENT_ID_PATTERN);
|
|
1372
|
+
const locale = shaped(query?.locale, LOCALE_PATTERN) || shaped(single?.locale, LOCALE_PATTERN);
|
|
1373
|
+
return {
|
|
1374
|
+
action: mapping.action,
|
|
1375
|
+
kind: mapping.kind,
|
|
1376
|
+
contentType,
|
|
1377
|
+
documentId,
|
|
1378
|
+
locale,
|
|
1379
|
+
count
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
function pickEntryTitle(data, mainField) {
|
|
1383
|
+
if (!data || typeof data !== "object" || !mainField || mainField === "id") return null;
|
|
1384
|
+
const value = data[mainField];
|
|
1385
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
1386
|
+
if (typeof value !== "string") return null;
|
|
1387
|
+
const text = value.replace(/\s+/g, " ").trim();
|
|
1388
|
+
return text ? text.slice(0, 255) : null;
|
|
1389
|
+
}
|
|
1390
|
+
function safeReason(reason) {
|
|
1391
|
+
return typeof reason === "string" && /^[a-z][a-z0-9_-]{0,39}$/.test(reason) ? reason : null;
|
|
1392
|
+
}
|
|
1393
|
+
function deriveSessionStates(signIns, laterEvents, liveDevices) {
|
|
1394
|
+
const sorted = [...laterEvents].sort((a, b) => String(a.at).localeCompare(String(b.at)));
|
|
1395
|
+
const out = /* @__PURE__ */ new Map();
|
|
1396
|
+
for (const row of signIns) {
|
|
1397
|
+
if (!row.deviceHash) {
|
|
1398
|
+
out.set(row.id, { state: "unknown", endedAt: null, endedBy: null });
|
|
1399
|
+
continue;
|
|
1400
|
+
}
|
|
1401
|
+
let result = null;
|
|
1402
|
+
for (const event of sorted) {
|
|
1403
|
+
if (event.adminId !== row.adminId || String(event.at) <= String(row.at)) continue;
|
|
1404
|
+
const sameDevice = event.deviceHash === row.deviceHash;
|
|
1405
|
+
if (event.event === SECURITY_EVENTS.ADMIN_SIGN_IN && sameDevice) {
|
|
1406
|
+
result = { state: "ended", endedAt: null, endedBy: null };
|
|
1407
|
+
break;
|
|
1408
|
+
}
|
|
1409
|
+
const isEnd = event.event === SECURITY_EVENTS.ADMIN_SIGN_OUT || event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
|
|
1410
|
+
if (isEnd && (sameDevice || !event.deviceHash)) {
|
|
1411
|
+
result = {
|
|
1412
|
+
state: "signed-out",
|
|
1413
|
+
endedAt: event.at,
|
|
1414
|
+
endedBy: event.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED ? event.actorId : null
|
|
1415
|
+
};
|
|
1416
|
+
break;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
if (!result) {
|
|
1420
|
+
const live = liveDevices.get(row.adminId);
|
|
1421
|
+
result = live && live.has(row.deviceHash) ? { state: "active", endedAt: null, endedBy: null } : { state: "ended", endedAt: null, endedBy: null };
|
|
1422
|
+
}
|
|
1423
|
+
out.set(row.id, result);
|
|
1424
|
+
}
|
|
1425
|
+
return out;
|
|
1426
|
+
}
|
|
1427
|
+
function toLocation(value) {
|
|
1428
|
+
let geo = value;
|
|
1429
|
+
if (typeof geo === "string") {
|
|
1430
|
+
try {
|
|
1431
|
+
geo = JSON.parse(geo);
|
|
1432
|
+
} catch {
|
|
1433
|
+
return null;
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
if (!geo || typeof geo !== "object") return null;
|
|
1437
|
+
const text = (v) => typeof v === "string" && v.trim() ? v.trim().slice(0, 80) : null;
|
|
1438
|
+
const record = (
|
|
1439
|
+
/** @type {Record<string, unknown>} */
|
|
1440
|
+
geo
|
|
1441
|
+
);
|
|
1442
|
+
const location = {
|
|
1443
|
+
country: text(record.country),
|
|
1444
|
+
countryCode: text(record.countryCode ?? record.country_code),
|
|
1445
|
+
city: text(record.city)
|
|
1446
|
+
};
|
|
1447
|
+
return location.country || location.city ? location : null;
|
|
1448
|
+
}
|
|
1449
|
+
function toIso(value) {
|
|
1450
|
+
if (!value) return null;
|
|
1451
|
+
const date = value instanceof Date ? value : new Date(String(value));
|
|
1452
|
+
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
|
1453
|
+
}
|
|
1454
|
+
function toObject(value) {
|
|
1455
|
+
let parsed = value;
|
|
1456
|
+
if (typeof parsed === "string") {
|
|
1457
|
+
try {
|
|
1458
|
+
parsed = JSON.parse(parsed);
|
|
1459
|
+
} catch {
|
|
1460
|
+
return {};
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
1464
|
+
}
|
|
1465
|
+
module.exports = {
|
|
1466
|
+
ACTOR_TYPES,
|
|
1467
|
+
ADMIN_CONTENT_EVENTS,
|
|
1468
|
+
ADMIN_SIGN_IN_EVENTS,
|
|
1469
|
+
CONTENT_ACTIONS,
|
|
1470
|
+
CONTENT_MANAGER_HANDLERS,
|
|
1471
|
+
EVENT_NAME_PATTERN,
|
|
1472
|
+
KEEP_WITHOUT_ACTOR_EVENTS,
|
|
1473
|
+
MAX_META_BYTES,
|
|
1474
|
+
SECURITY_EVENTS,
|
|
1475
|
+
SIGN_IN_FILTERS,
|
|
1476
|
+
boundMeta,
|
|
1477
|
+
contentEvent,
|
|
1478
|
+
deriveSessionStates,
|
|
1479
|
+
describeContentManagerRequest,
|
|
1480
|
+
dropRankOf,
|
|
1481
|
+
handlerName,
|
|
1482
|
+
pickEntryTitle,
|
|
1483
|
+
recordingSwitchOf,
|
|
1484
|
+
safeReason,
|
|
1485
|
+
toIso,
|
|
1486
|
+
toLocation,
|
|
1487
|
+
toObject
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
});
|
|
1491
|
+
|
|
1492
|
+
// server/src/utils/security-log-hardening.js
|
|
1493
|
+
var require_security_log_hardening = __commonJS({
|
|
1494
|
+
"server/src/utils/security-log-hardening.js"(exports, module) {
|
|
1495
|
+
"use strict";
|
|
1496
|
+
var {
|
|
1497
|
+
legacyRetentionBelowMinimum,
|
|
1498
|
+
SECURITY_LOG_RETENTION_RANGE
|
|
1499
|
+
} = require_security_log_settings();
|
|
1500
|
+
var { withPluginStoreKey } = require_plugin_store();
|
|
1501
|
+
var { notifySettingsChanged } = require_settings_loader();
|
|
1502
|
+
var { toObject } = require_security_log_model();
|
|
1503
|
+
var PLUGIN_ID = "magic-sessionmanager";
|
|
1504
|
+
var PLUGIN_UID_PREFIX = `plugin::${PLUGIN_ID}.`;
|
|
1505
|
+
var EVENT_UID = `plugin::${PLUGIN_ID}.security-event`;
|
|
1506
|
+
var INTERNAL_TYPES = Object.freeze([
|
|
1507
|
+
`plugin::${PLUGIN_ID}.session`,
|
|
1508
|
+
`plugin::${PLUGIN_ID}.revoked-token`,
|
|
1509
|
+
EVENT_UID
|
|
1510
|
+
]);
|
|
1511
|
+
var MIGRATIONS_KEY = "migrations";
|
|
1512
|
+
var MIGRATION_BATCH = 500;
|
|
1513
|
+
var MAX_MIGRATION_STEPS = 400;
|
|
1514
|
+
var CM_MODEL_ROUTE = /^\/+content-manager\/+(?:collection-types|single-types|relations)\/+([^/]+)/i;
|
|
1515
|
+
function disableGraphqlShadowCrud(strapi2, log) {
|
|
1516
|
+
let graphql;
|
|
1517
|
+
try {
|
|
1518
|
+
graphql = strapi2.plugin("graphql");
|
|
1519
|
+
} catch {
|
|
1520
|
+
graphql = null;
|
|
1521
|
+
}
|
|
1522
|
+
if (!graphql) return [];
|
|
1523
|
+
try {
|
|
1524
|
+
const extension = graphql.service("extension");
|
|
1525
|
+
for (const uid of INTERNAL_TYPES) extension.shadowCRUD(uid).disable();
|
|
1526
|
+
return [...INTERNAL_TYPES];
|
|
1527
|
+
} catch (err) {
|
|
1528
|
+
log.warn("[security] GraphQL Shadow CRUD could not be disabled:", err?.name || "Error");
|
|
1529
|
+
return [];
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
function contentManagerModelOf(path) {
|
|
1533
|
+
if (typeof path !== "string") return null;
|
|
1534
|
+
const match = CM_MODEL_ROUTE.exec(path);
|
|
1535
|
+
if (!match) return null;
|
|
1536
|
+
try {
|
|
1537
|
+
return decodeURIComponent(match[1]);
|
|
1538
|
+
} catch {
|
|
1539
|
+
return null;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
function createInternalTypeGuard() {
|
|
1543
|
+
return async function internalTypeGuard(ctx, next) {
|
|
1544
|
+
const model = contentManagerModelOf(ctx.path);
|
|
1545
|
+
if (model && model.toLowerCase().startsWith(PLUGIN_UID_PREFIX)) {
|
|
1546
|
+
ctx.status = 404;
|
|
1547
|
+
ctx.body = {
|
|
1548
|
+
data: null,
|
|
1549
|
+
error: { status: 404, name: "NotFoundError", message: "Not Found", details: {} }
|
|
1550
|
+
};
|
|
1551
|
+
return void 0;
|
|
1552
|
+
}
|
|
1553
|
+
return next();
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
function hasUnboundedProxyTrust(strapi2) {
|
|
1557
|
+
const get = (key) => {
|
|
1558
|
+
try {
|
|
1559
|
+
return strapi2?.config?.get?.(key);
|
|
1560
|
+
} catch {
|
|
1561
|
+
return void 0;
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
const proxy = get("server.proxy");
|
|
1565
|
+
const koa = proxy === true || get("server.proxy.koa") === true;
|
|
1566
|
+
if (!koa) return false;
|
|
1567
|
+
const hops = Number(get("server.proxy.maxIpsCount"));
|
|
1568
|
+
return !(Number.isInteger(hops) && hops > 0);
|
|
1569
|
+
}
|
|
1570
|
+
function warnUnboundedProxyTrust(strapi2, log) {
|
|
1571
|
+
if (!hasUnboundedProxyTrust(strapi2)) return false;
|
|
1572
|
+
log.warn(
|
|
1573
|
+
"[security-log] server.proxy.koa is true but server.proxy.maxIpsCount is not set: Koa takes the left-most X-Forwarded-For entry, which the client chooses. Set maxIpsCount to the number of proxies in front of Strapi (usually 1) so stored sign-in addresses and IP rate limits cannot be spoofed."
|
|
1574
|
+
);
|
|
1575
|
+
return true;
|
|
1576
|
+
}
|
|
1577
|
+
async function raiseLegacyRetention(strapi2, log) {
|
|
1578
|
+
const store = strapi2.store({ type: "plugin", name: PLUGIN_ID });
|
|
1579
|
+
if (legacyRetentionBelowMinimum(await store.get({ key: "settings" })) === null) return null;
|
|
1580
|
+
const raised = await withPluginStoreKey(strapi2, "settings", async (scoped) => {
|
|
1581
|
+
const stored = await scoped.get({ key: "settings" });
|
|
1582
|
+
const old = legacyRetentionBelowMinimum(stored);
|
|
1583
|
+
if (old === null) return null;
|
|
1584
|
+
await scoped.set({
|
|
1585
|
+
key: "settings",
|
|
1586
|
+
value: { ...stored, securityLogRetentionDays: SECURITY_LOG_RETENTION_RANGE.min }
|
|
1587
|
+
});
|
|
1588
|
+
return old;
|
|
1589
|
+
});
|
|
1590
|
+
if (raised !== null) {
|
|
1591
|
+
await notifySettingsChanged(strapi2);
|
|
1592
|
+
log.info(
|
|
1593
|
+
`[security-log] Retention raised from ${raised} to ${SECURITY_LOG_RETENTION_RANGE.min} days (the minimum since 4.17).`
|
|
1594
|
+
);
|
|
1595
|
+
}
|
|
1596
|
+
return raised;
|
|
1597
|
+
}
|
|
1598
|
+
async function stripStoredTitles(strapi2) {
|
|
1599
|
+
const events = () => strapi2.db.query(EVENT_UID);
|
|
1600
|
+
let cursor = 0;
|
|
1601
|
+
let updated = 0;
|
|
1602
|
+
for (let step = 0; step < MAX_MIGRATION_STEPS; step += 1) {
|
|
1603
|
+
const rows = await events().findMany({
|
|
1604
|
+
select: ["id", "meta"],
|
|
1605
|
+
where: { id: { $gt: cursor }, event: { $startsWith: "admin.content." } },
|
|
1606
|
+
orderBy: { id: "asc" },
|
|
1607
|
+
limit: MIGRATION_BATCH
|
|
1608
|
+
});
|
|
1609
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
1610
|
+
if (!list.length) return { updated, done: true };
|
|
1611
|
+
for (const row of list) {
|
|
1612
|
+
const meta = toObject(row.meta);
|
|
1613
|
+
if (Object.prototype.hasOwnProperty.call(meta, "title")) {
|
|
1614
|
+
const { title: _title, ...rest } = meta;
|
|
1615
|
+
await events().update({
|
|
1616
|
+
where: { id: row.id },
|
|
1617
|
+
data: { meta: Object.keys(rest).length ? rest : null }
|
|
1618
|
+
});
|
|
1619
|
+
updated += 1;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
cursor = Number(list[list.length - 1].id);
|
|
1623
|
+
if (list.length < MIGRATION_BATCH) return { updated, done: true };
|
|
1624
|
+
}
|
|
1625
|
+
return { updated, done: false };
|
|
1626
|
+
}
|
|
1627
|
+
async function migrateSecurityLog(strapi2, log) {
|
|
1628
|
+
const retentionRaisedFrom = await raiseLegacyRetention(strapi2, log);
|
|
1629
|
+
const store = strapi2.store({ type: "plugin", name: PLUGIN_ID });
|
|
1630
|
+
const state = toObject(await store.get({ key: MIGRATIONS_KEY }));
|
|
1631
|
+
if (state.securityEventTitlesRemoved === true) {
|
|
1632
|
+
return { retentionRaisedFrom, titlesRemoved: 0, titlesDone: true };
|
|
1633
|
+
}
|
|
1634
|
+
const result = await stripStoredTitles(strapi2);
|
|
1635
|
+
if (result.updated > 0) {
|
|
1636
|
+
log.info(
|
|
1637
|
+
`[security-log] Removed stored entry titles from ${result.updated} Content Manager events.`
|
|
1638
|
+
);
|
|
1639
|
+
}
|
|
1640
|
+
if (result.done) {
|
|
1641
|
+
await withPluginStoreKey(strapi2, MIGRATIONS_KEY, async (scoped) => {
|
|
1642
|
+
const current = toObject(await scoped.get({ key: MIGRATIONS_KEY }));
|
|
1643
|
+
await scoped.set({
|
|
1644
|
+
key: MIGRATIONS_KEY,
|
|
1645
|
+
value: { ...current, securityEventTitlesRemoved: true }
|
|
1646
|
+
});
|
|
1647
|
+
});
|
|
1648
|
+
}
|
|
1649
|
+
return { retentionRaisedFrom, titlesRemoved: result.updated, titlesDone: result.done };
|
|
1650
|
+
}
|
|
1651
|
+
module.exports = {
|
|
1652
|
+
INTERNAL_TYPES,
|
|
1653
|
+
MIGRATIONS_KEY,
|
|
1654
|
+
contentManagerModelOf,
|
|
1655
|
+
createInternalTypeGuard,
|
|
1656
|
+
disableGraphqlShadowCrud,
|
|
1657
|
+
hasUnboundedProxyTrust,
|
|
1658
|
+
migrateSecurityLog,
|
|
1659
|
+
raiseLegacyRetention,
|
|
1660
|
+
stripStoredTitles,
|
|
1661
|
+
warnUnboundedProxyTrust
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
});
|
|
1665
|
+
|
|
904
1666
|
// server/src/register.js
|
|
905
1667
|
var require_register = __commonJS({
|
|
906
1668
|
"server/src/register.js"(exports, module) {
|
|
@@ -909,6 +1671,7 @@ var require_register = __commonJS({
|
|
|
909
1671
|
var { createContentApiPermissionsLifecycle } = require_content_api_permissions();
|
|
910
1672
|
var { isCallerRevocationScope } = require_block_revocation_scope();
|
|
911
1673
|
var { checkStrapiVersion } = require_strapi_version();
|
|
1674
|
+
var { disableGraphqlShadowCrud } = require_security_log_hardening();
|
|
912
1675
|
var USER_UID = "plugin::users-permissions.user";
|
|
913
1676
|
module.exports = async ({ strapi: strapi2 }) => {
|
|
914
1677
|
const log = createLogger(strapi2);
|
|
@@ -942,8 +1705,29 @@ var require_register = __commonJS({
|
|
|
942
1705
|
uid: "admin-sessions.revoke",
|
|
943
1706
|
subCategory: "Admin panel",
|
|
944
1707
|
pluginName: "magic-sessionmanager"
|
|
1708
|
+
},
|
|
1709
|
+
// Admin sign-in history and Content Manager activity (4.15): who signed
|
|
1710
|
+
// in from where and what each admin did. Separate from reading the
|
|
1711
|
+
// sessions, because it shows IP addresses and work activity.
|
|
1712
|
+
{
|
|
1713
|
+
section: "plugins",
|
|
1714
|
+
displayName: "View admin activity",
|
|
1715
|
+
uid: "admin-activity.read",
|
|
1716
|
+
subCategory: "Admin panel",
|
|
1717
|
+
pluginName: "magic-sessionmanager"
|
|
1718
|
+
},
|
|
1719
|
+
// Protected settings (4.17): IP location lookup (whether and where IP
|
|
1720
|
+
// addresses are sent), team notification webhooks (the URLs are
|
|
1721
|
+
// secrets) and the security log. The other settings stay on `access`.
|
|
1722
|
+
{
|
|
1723
|
+
section: "plugins",
|
|
1724
|
+
displayName: "Change protected settings (location lookup, webhooks, security log)",
|
|
1725
|
+
uid: "settings.update",
|
|
1726
|
+
subCategory: "Settings",
|
|
1727
|
+
pluginName: "magic-sessionmanager"
|
|
945
1728
|
}
|
|
946
1729
|
]);
|
|
1730
|
+
disableGraphqlShadowCrud(strapi2, log);
|
|
947
1731
|
try {
|
|
948
1732
|
strapi2.db.lifecycles.subscribe(createContentApiPermissionsLifecycle(strapi2));
|
|
949
1733
|
} catch (err) {
|
|
@@ -1188,241 +1972,34 @@ var require_resolve_user = __commonJS({
|
|
|
1188
1972
|
}
|
|
1189
1973
|
if (cache.size >= CACHE_MAX_SIZE) {
|
|
1190
1974
|
const keysToDelete = [...cache.keys()].slice(0, Math.floor(CACHE_MAX_SIZE / 4));
|
|
1191
|
-
keysToDelete.forEach((k) => cache.delete(k));
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
async function resolveUserDocumentId(strapi2, userId) {
|
|
1195
|
-
if (!userId) return null;
|
|
1196
|
-
if (typeof userId === "string" && isNaN(userId)) {
|
|
1197
|
-
return userId;
|
|
1198
|
-
}
|
|
1199
|
-
const numericId = typeof userId === "number" ? userId : parseInt(userId, 10);
|
|
1200
|
-
const cacheKey = `u_${numericId}`;
|
|
1201
|
-
const cached = cache.get(cacheKey);
|
|
1202
|
-
if (cached && Date.now() - cached.ts < CACHE_TTL) {
|
|
1203
|
-
return cached.documentId;
|
|
1204
|
-
}
|
|
1205
|
-
if (cache.size >= CACHE_MAX_SIZE) evict();
|
|
1206
|
-
try {
|
|
1207
|
-
const user = await strapi2.entityService.findOne(USER_UID, numericId, {
|
|
1208
|
-
fields: ["documentId"]
|
|
1209
|
-
});
|
|
1210
|
-
if (user?.documentId) {
|
|
1211
|
-
cache.set(cacheKey, { documentId: user.documentId, ts: Date.now() });
|
|
1212
|
-
return user.documentId;
|
|
1213
|
-
}
|
|
1214
|
-
} catch {
|
|
1215
|
-
}
|
|
1216
|
-
return null;
|
|
1217
|
-
}
|
|
1218
|
-
module.exports = { resolveUserDocumentId };
|
|
1219
|
-
}
|
|
1220
|
-
});
|
|
1221
|
-
|
|
1222
|
-
// server/src/utils/settings-loader.js
|
|
1223
|
-
var require_settings_loader = __commonJS({
|
|
1224
|
-
"server/src/utils/settings-loader.js"(exports, module) {
|
|
1225
|
-
"use strict";
|
|
1226
|
-
var { getCoordinator } = require_coordination();
|
|
1227
|
-
var PLUGIN_ID = "magic-sessionmanager";
|
|
1228
|
-
var SETTINGS_KEY = "settings";
|
|
1229
|
-
var CACHE_TTL_MS = 30 * 1e3;
|
|
1230
|
-
var REVISION_CHECK_MS = 2 * 1e3;
|
|
1231
|
-
var SETTINGS_REVISION = "settings";
|
|
1232
|
-
var GEO_IP_PROVIDERS = /* @__PURE__ */ new Set(["auto", "local-mmdb", "ipapi", "disabled"]);
|
|
1233
|
-
var GEO_LOOKUP_FAILURE_MODES = /* @__PURE__ */ new Set(["auto", "allow", "block"]);
|
|
1234
|
-
var cached = null;
|
|
1235
|
-
var cachedAt = 0;
|
|
1236
|
-
var cachedRevision = null;
|
|
1237
|
-
var revisionCheckedAt = 0;
|
|
1238
|
-
function toIntInRange(value, fallback, min, max) {
|
|
1239
|
-
const n = Number.parseInt(value, 10);
|
|
1240
|
-
if (!Number.isFinite(n)) return fallback;
|
|
1241
|
-
return Math.max(min, Math.min(n, max));
|
|
1242
|
-
}
|
|
1243
|
-
function normalizeRetentionDays(value, fallback = 90) {
|
|
1244
|
-
const n = Number.parseInt(value, 10);
|
|
1245
|
-
if (!Number.isFinite(n)) return fallback;
|
|
1246
|
-
if (n === -1) return -1;
|
|
1247
|
-
return Math.max(1, Math.min(n, 365));
|
|
1248
|
-
}
|
|
1249
|
-
function getSessionCreationGraceMs(settings = {}) {
|
|
1250
|
-
if (!settings || settings.sessionCreationGraceMs === void 0) {
|
|
1251
|
-
return 5e3;
|
|
1252
|
-
}
|
|
1253
|
-
return toIntInRange(settings.sessionCreationGraceMs, 5e3, 0, 3e4);
|
|
1254
|
-
}
|
|
1255
|
-
function normalizeGeoIpProvider(value) {
|
|
1256
|
-
return GEO_IP_PROVIDERS.has(value) ? value : "auto";
|
|
1257
|
-
}
|
|
1258
|
-
function normalizeGeoLookupFailureMode(value) {
|
|
1259
|
-
return GEO_LOOKUP_FAILURE_MODES.has(value) ? value : "auto";
|
|
1260
|
-
}
|
|
1261
|
-
function normalizeGeoIpDatabasePath(value) {
|
|
1262
|
-
if (typeof value !== "string") return "";
|
|
1263
|
-
return value.replace(/\0/g, "").trim().slice(0, 1024);
|
|
1264
|
-
}
|
|
1265
|
-
function normalizeStoredSettings(stored) {
|
|
1266
|
-
if (!stored || typeof stored !== "object") return {};
|
|
1267
|
-
const out = {};
|
|
1268
|
-
if (stored.inactivityTimeout !== void 0) {
|
|
1269
|
-
const minutes = toIntInRange(stored.inactivityTimeout, 15, 1, 1440);
|
|
1270
|
-
out.inactivityTimeout = minutes * 60 * 1e3;
|
|
1271
|
-
}
|
|
1272
|
-
if (stored.cleanupInterval !== void 0) {
|
|
1273
|
-
const minutes = toIntInRange(stored.cleanupInterval, 30, 5, 1440);
|
|
1274
|
-
out.cleanupInterval = minutes * 60 * 1e3;
|
|
1275
|
-
}
|
|
1276
|
-
if (stored.lastSeenRateLimit !== void 0) {
|
|
1277
|
-
const seconds = toIntInRange(stored.lastSeenRateLimit, 30, 5, 300);
|
|
1278
|
-
out.lastSeenRateLimit = seconds * 1e3;
|
|
1279
|
-
}
|
|
1280
|
-
if (stored.retentionDays !== void 0) {
|
|
1281
|
-
out.retentionDays = normalizeRetentionDays(stored.retentionDays, 90);
|
|
1282
|
-
}
|
|
1283
|
-
if (stored.maxSessionAgeDays !== void 0) {
|
|
1284
|
-
out.maxSessionAgeDays = toIntInRange(stored.maxSessionAgeDays, 30, 1, 365);
|
|
1285
|
-
}
|
|
1286
|
-
if (stored.maxFailedLogins !== void 0) {
|
|
1287
|
-
out.maxFailedLogins = toIntInRange(stored.maxFailedLogins, 5, 0, 100);
|
|
1288
|
-
}
|
|
1289
|
-
const passthroughBooleans = [
|
|
1290
|
-
"enableGeolocation",
|
|
1291
|
-
"enableSecurityScoring",
|
|
1292
|
-
"blockSuspiciousSessions",
|
|
1293
|
-
"enableEmailAlerts",
|
|
1294
|
-
"alertOnSuspiciousLogin",
|
|
1295
|
-
"alertOnNewLocation",
|
|
1296
|
-
"alertOnVpnProxy",
|
|
1297
|
-
"enableWebhooks",
|
|
1298
|
-
"enableGeofencing",
|
|
1299
|
-
"strictSessionEnforcement",
|
|
1300
|
-
// Opt-in: use a single-statement SQL UPDATE in the cleanup job instead
|
|
1301
|
-
// of batching via the Document Service. Bypasses lifecycle hooks but
|
|
1302
|
-
// drains the backlog in one query on very large installations.
|
|
1303
|
-
"cleanupUseDbDirect"
|
|
1304
|
-
];
|
|
1305
|
-
if (stored.sessionCreationGraceMs !== void 0) {
|
|
1306
|
-
out.sessionCreationGraceMs = getSessionCreationGraceMs(stored);
|
|
1307
|
-
}
|
|
1308
|
-
if (stored.rateLimitWriteMax !== void 0) {
|
|
1309
|
-
out.rateLimitWriteMax = toIntInRange(stored.rateLimitWriteMax, 10, 1, 1e3);
|
|
1310
|
-
}
|
|
1311
|
-
if (stored.rateLimitReadMax !== void 0) {
|
|
1312
|
-
out.rateLimitReadMax = toIntInRange(stored.rateLimitReadMax, 120, 1, 1e4);
|
|
1313
|
-
}
|
|
1314
|
-
if (stored.rateLimitWindowSeconds !== void 0) {
|
|
1315
|
-
out.rateLimitWindowSeconds = toIntInRange(stored.rateLimitWindowSeconds, 60, 10, 3600);
|
|
1316
|
-
}
|
|
1317
|
-
for (const key of passthroughBooleans) {
|
|
1318
|
-
if (stored[key] !== void 0) out[key] = !!stored[key];
|
|
1319
|
-
}
|
|
1320
|
-
if (typeof stored.discordWebhookUrl === "string") {
|
|
1321
|
-
out.discordWebhookUrl = stored.discordWebhookUrl;
|
|
1322
|
-
}
|
|
1323
|
-
if (typeof stored.slackWebhookUrl === "string") {
|
|
1324
|
-
out.slackWebhookUrl = stored.slackWebhookUrl;
|
|
1325
|
-
}
|
|
1326
|
-
if (Array.isArray(stored.allowedCountries)) {
|
|
1327
|
-
out.allowedCountries = stored.allowedCountries;
|
|
1328
|
-
}
|
|
1329
|
-
if (Array.isArray(stored.blockedCountries)) {
|
|
1330
|
-
out.blockedCountries = stored.blockedCountries;
|
|
1331
|
-
}
|
|
1332
|
-
if (stored.geoIpProvider !== void 0) {
|
|
1333
|
-
out.geoIpProvider = normalizeGeoIpProvider(stored.geoIpProvider);
|
|
1334
|
-
}
|
|
1335
|
-
if (stored.geoIpDatabasePath !== void 0) {
|
|
1336
|
-
out.geoIpDatabasePath = normalizeGeoIpDatabasePath(stored.geoIpDatabasePath);
|
|
1337
|
-
}
|
|
1338
|
-
if (stored.geoLookupFailureMode !== void 0) {
|
|
1339
|
-
out.geoLookupFailureMode = normalizeGeoLookupFailureMode(stored.geoLookupFailureMode);
|
|
1340
|
-
}
|
|
1341
|
-
if (stored.emailTemplates && typeof stored.emailTemplates === "object") {
|
|
1342
|
-
out.emailTemplates = stored.emailTemplates;
|
|
1343
|
-
}
|
|
1344
|
-
if (stored.trustedProxies !== void 0) {
|
|
1345
|
-
out.trustedProxies = stored.trustedProxies;
|
|
1346
|
-
}
|
|
1347
|
-
return out;
|
|
1348
|
-
}
|
|
1349
|
-
async function getPluginSettings(strapi2) {
|
|
1350
|
-
const now = Date.now();
|
|
1351
|
-
const coordinator = getCoordinator(strapi2);
|
|
1352
|
-
if (cached && now - cachedAt < CACHE_TTL_MS) {
|
|
1353
|
-
if (now - revisionCheckedAt < REVISION_CHECK_MS) return cached;
|
|
1354
|
-
revisionCheckedAt = now;
|
|
1355
|
-
let revision2;
|
|
1356
|
-
try {
|
|
1357
|
-
revision2 = await coordinator.getRevision(SETTINGS_REVISION);
|
|
1358
|
-
} catch {
|
|
1359
|
-
return cached;
|
|
1360
|
-
}
|
|
1361
|
-
if (revision2 === cachedRevision) return cached;
|
|
1362
|
-
}
|
|
1363
|
-
let revision;
|
|
1364
|
-
try {
|
|
1365
|
-
revision = await coordinator.getRevision(SETTINGS_REVISION);
|
|
1366
|
-
} catch {
|
|
1367
|
-
revision = null;
|
|
1368
|
-
}
|
|
1369
|
-
const staticConfig = strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
|
|
1370
|
-
let storedSettings;
|
|
1371
|
-
try {
|
|
1372
|
-
const pluginStore = strapi2.store({ type: "plugin", name: PLUGIN_ID });
|
|
1373
|
-
const raw = await pluginStore.get({ key: SETTINGS_KEY });
|
|
1374
|
-
storedSettings = normalizeStoredSettings(raw);
|
|
1375
|
-
} catch {
|
|
1376
|
-
strapi2.log.error(
|
|
1377
|
-
`[${PLUGIN_ID}] settings-loader: store read failed; strict session enforcement is enabled and geolocation is disabled`
|
|
1378
|
-
);
|
|
1379
|
-
storedSettings = { strictSessionEnforcement: true, enableGeolocation: false };
|
|
1380
|
-
}
|
|
1381
|
-
const merged = { ...staticConfig, ...storedSettings };
|
|
1382
|
-
cached = merged;
|
|
1383
|
-
cachedAt = now;
|
|
1384
|
-
cachedRevision = revision;
|
|
1385
|
-
revisionCheckedAt = now;
|
|
1386
|
-
return merged;
|
|
1387
|
-
}
|
|
1388
|
-
function getPluginSettingsSync(strapi2) {
|
|
1389
|
-
if (cached) return cached;
|
|
1390
|
-
return strapi2.config.get(`plugin::${PLUGIN_ID}`) || {};
|
|
1391
|
-
}
|
|
1392
|
-
function invalidateSettingsCache() {
|
|
1393
|
-
cached = null;
|
|
1394
|
-
cachedAt = 0;
|
|
1395
|
-
cachedRevision = null;
|
|
1396
|
-
revisionCheckedAt = 0;
|
|
1397
|
-
}
|
|
1398
|
-
async function getSettingsRevision(strapi2) {
|
|
1399
|
-
return getCoordinator(strapi2).getRevision(SETTINGS_REVISION);
|
|
1975
|
+
keysToDelete.forEach((k) => cache.delete(k));
|
|
1976
|
+
}
|
|
1400
1977
|
}
|
|
1401
|
-
async function
|
|
1402
|
-
|
|
1978
|
+
async function resolveUserDocumentId(strapi2, userId) {
|
|
1979
|
+
if (!userId) return null;
|
|
1980
|
+
if (typeof userId === "string" && isNaN(userId)) {
|
|
1981
|
+
return userId;
|
|
1982
|
+
}
|
|
1983
|
+
const numericId = typeof userId === "number" ? userId : parseInt(userId, 10);
|
|
1984
|
+
const cacheKey = `u_${numericId}`;
|
|
1985
|
+
const cached = cache.get(cacheKey);
|
|
1986
|
+
if (cached && Date.now() - cached.ts < CACHE_TTL) {
|
|
1987
|
+
return cached.documentId;
|
|
1988
|
+
}
|
|
1989
|
+
if (cache.size >= CACHE_MAX_SIZE) evict();
|
|
1403
1990
|
try {
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1991
|
+
const user = await strapi2.entityService.findOne(USER_UID, numericId, {
|
|
1992
|
+
fields: ["documentId"]
|
|
1993
|
+
});
|
|
1994
|
+
if (user?.documentId) {
|
|
1995
|
+
cache.set(cacheKey, { documentId: user.documentId, ts: Date.now() });
|
|
1996
|
+
return user.documentId;
|
|
1997
|
+
}
|
|
1998
|
+
} catch {
|
|
1411
1999
|
}
|
|
2000
|
+
return null;
|
|
1412
2001
|
}
|
|
1413
|
-
module.exports = {
|
|
1414
|
-
getPluginSettings,
|
|
1415
|
-
getPluginSettingsSync,
|
|
1416
|
-
invalidateSettingsCache,
|
|
1417
|
-
notifySettingsChanged,
|
|
1418
|
-
getSettingsRevision,
|
|
1419
|
-
normalizeStoredSettings,
|
|
1420
|
-
normalizeRetentionDays,
|
|
1421
|
-
getSessionCreationGraceMs,
|
|
1422
|
-
normalizeGeoIpProvider,
|
|
1423
|
-
normalizeGeoIpDatabasePath,
|
|
1424
|
-
normalizeGeoLookupFailureMode
|
|
1425
|
-
};
|
|
2002
|
+
module.exports = { resolveUserDocumentId };
|
|
1426
2003
|
}
|
|
1427
2004
|
});
|
|
1428
2005
|
|
|
@@ -2409,44 +2986,530 @@ var require_native_only_insight = __commonJS({
|
|
|
2409
2986
|
expiring: { within7Days: toCount(row.within7Days), within30Days: toCount(row.within30Days) }
|
|
2410
2987
|
};
|
|
2411
2988
|
}
|
|
2412
|
-
async function endNativeOnlySessions(strapi2, { now = /* @__PURE__ */ new Date(), maxRows = END_MAX_ROWS } = {}) {
|
|
2413
|
-
if (!canInspectNativeSessions(strapi2)) return { ended: 0, remaining: 0 };
|
|
2414
|
-
const t = tables(strapi2);
|
|
2415
|
-
const limit = Math.max(0, Math.min(END_MAX_ROWS, Math.floor(Number(maxRows) || 0)));
|
|
2416
|
-
const createdBefore = new Date(now.getTime() - END_MIN_AGE_MS);
|
|
2417
|
-
const idColumn = `${t.native}.${t.col.id}`;
|
|
2418
|
-
const oldEnough = (query) => query.andWhere(`${t.native}.${t.col.createdAt}`, "<", createdBefore);
|
|
2419
|
-
let ended = 0;
|
|
2420
|
-
let lastId = null;
|
|
2421
|
-
while (ended < limit) {
|
|
2422
|
-
const size = Math.min(END_BATCH_SIZE, limit - ended);
|
|
2423
|
-
const select = oldEnough(untrackedQuery(t, now)).select({ id: idColumn }).orderBy(idColumn, "asc").limit(size);
|
|
2424
|
-
if (lastId !== null) select.andWhere(idColumn, ">", lastId);
|
|
2425
|
-
const rows = await select;
|
|
2426
|
-
if (rows.length === 0) break;
|
|
2427
|
-
const ids = rows.map((row) => row.id);
|
|
2428
|
-
lastId = ids[ids.length - 1];
|
|
2429
|
-
const deleted = await oldEnough(untrackedQuery(t, now)).whereIn(idColumn, ids).del();
|
|
2430
|
-
ended += toCount(deleted);
|
|
2431
|
-
if (rows.length < size) break;
|
|
2989
|
+
async function endNativeOnlySessions(strapi2, { now = /* @__PURE__ */ new Date(), maxRows = END_MAX_ROWS } = {}) {
|
|
2990
|
+
if (!canInspectNativeSessions(strapi2)) return { ended: 0, remaining: 0 };
|
|
2991
|
+
const t = tables(strapi2);
|
|
2992
|
+
const limit = Math.max(0, Math.min(END_MAX_ROWS, Math.floor(Number(maxRows) || 0)));
|
|
2993
|
+
const createdBefore = new Date(now.getTime() - END_MIN_AGE_MS);
|
|
2994
|
+
const idColumn = `${t.native}.${t.col.id}`;
|
|
2995
|
+
const oldEnough = (query) => query.andWhere(`${t.native}.${t.col.createdAt}`, "<", createdBefore);
|
|
2996
|
+
let ended = 0;
|
|
2997
|
+
let lastId = null;
|
|
2998
|
+
while (ended < limit) {
|
|
2999
|
+
const size = Math.min(END_BATCH_SIZE, limit - ended);
|
|
3000
|
+
const select = oldEnough(untrackedQuery(t, now)).select({ id: idColumn }).orderBy(idColumn, "asc").limit(size);
|
|
3001
|
+
if (lastId !== null) select.andWhere(idColumn, ">", lastId);
|
|
3002
|
+
const rows = await select;
|
|
3003
|
+
if (rows.length === 0) break;
|
|
3004
|
+
const ids = rows.map((row) => row.id);
|
|
3005
|
+
lastId = ids[ids.length - 1];
|
|
3006
|
+
const deleted = await oldEnough(untrackedQuery(t, now)).whereIn(idColumn, ids).del();
|
|
3007
|
+
ended += toCount(deleted);
|
|
3008
|
+
if (rows.length < size) break;
|
|
3009
|
+
}
|
|
3010
|
+
const { total } = await countNativeOnly(strapi2, { now });
|
|
3011
|
+
return { ended, remaining: total };
|
|
3012
|
+
}
|
|
3013
|
+
module.exports = {
|
|
3014
|
+
TRACKING_STORE_KEY,
|
|
3015
|
+
MONTH_BUCKETS,
|
|
3016
|
+
DEVICE_SAMPLE_LIMIT,
|
|
3017
|
+
END_BATCH_SIZE,
|
|
3018
|
+
END_MAX_ROWS,
|
|
3019
|
+
END_MIN_AGE_MS,
|
|
3020
|
+
canInspectNativeSessions,
|
|
3021
|
+
getNativeTrackingSince,
|
|
3022
|
+
ensureNativeTrackingSince,
|
|
3023
|
+
countNativeOnly,
|
|
3024
|
+
deviceClassOf,
|
|
3025
|
+
getNativeOnlySummary,
|
|
3026
|
+
endNativeOnlySessions
|
|
3027
|
+
};
|
|
3028
|
+
}
|
|
3029
|
+
});
|
|
3030
|
+
|
|
3031
|
+
// server/src/utils/user-agent-parser.js
|
|
3032
|
+
var require_user_agent_parser = __commonJS({
|
|
3033
|
+
"server/src/utils/user-agent-parser.js"(exports, module) {
|
|
3034
|
+
"use strict";
|
|
3035
|
+
function parseUserAgent(userAgent) {
|
|
3036
|
+
if (!userAgent) {
|
|
3037
|
+
return {
|
|
3038
|
+
deviceType: "unknown",
|
|
3039
|
+
browserName: "unknown",
|
|
3040
|
+
browserVersion: null,
|
|
3041
|
+
osName: "unknown",
|
|
3042
|
+
osVersion: null
|
|
3043
|
+
};
|
|
3044
|
+
}
|
|
3045
|
+
let deviceType = "desktop";
|
|
3046
|
+
if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
|
|
3047
|
+
deviceType = "tablet";
|
|
3048
|
+
} else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
|
|
3049
|
+
deviceType = "mobile";
|
|
3050
|
+
} else if (/android(?!.*mobile)/i.test(userAgent)) {
|
|
3051
|
+
deviceType = "tablet";
|
|
3052
|
+
} else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
|
|
3053
|
+
deviceType = "bot";
|
|
3054
|
+
}
|
|
3055
|
+
let browserName = "unknown";
|
|
3056
|
+
let browserVersion = null;
|
|
3057
|
+
if (/edg\//i.test(userAgent)) {
|
|
3058
|
+
browserName = "Edge";
|
|
3059
|
+
browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
|
|
3060
|
+
} else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
|
|
3061
|
+
browserName = "Opera";
|
|
3062
|
+
browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
|
|
3063
|
+
} else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
|
|
3064
|
+
browserName = "Chrome";
|
|
3065
|
+
browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
|
|
3066
|
+
} else if (/firefox|fxios/i.test(userAgent)) {
|
|
3067
|
+
browserName = "Firefox";
|
|
3068
|
+
browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
|
|
3069
|
+
} else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
|
|
3070
|
+
browserName = "Safari";
|
|
3071
|
+
browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
|
|
3072
|
+
} else if (/msie|trident/i.test(userAgent)) {
|
|
3073
|
+
browserName = "Internet Explorer";
|
|
3074
|
+
browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
|
|
3075
|
+
}
|
|
3076
|
+
let osName = "unknown";
|
|
3077
|
+
let osVersion = null;
|
|
3078
|
+
if (/windows nt/i.test(userAgent)) {
|
|
3079
|
+
osName = "Windows";
|
|
3080
|
+
const winVersion = extractVersion(userAgent, /windows nt (\d+[.\d]*)/i);
|
|
3081
|
+
const winVersionMap = {
|
|
3082
|
+
"10.0": "10/11",
|
|
3083
|
+
6.3: "8.1",
|
|
3084
|
+
6.2: "8",
|
|
3085
|
+
6.1: "7",
|
|
3086
|
+
"6.0": "Vista",
|
|
3087
|
+
5.1: "XP"
|
|
3088
|
+
};
|
|
3089
|
+
osVersion = winVersionMap[winVersion] || winVersion;
|
|
3090
|
+
} else if (/iphone|ipad|ipod/i.test(userAgent)) {
|
|
3091
|
+
osName = "iOS";
|
|
3092
|
+
osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
|
|
3093
|
+
} else if (/mac os x/i.test(userAgent)) {
|
|
3094
|
+
osName = "macOS";
|
|
3095
|
+
osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
|
|
3096
|
+
} else if (/android/i.test(userAgent)) {
|
|
3097
|
+
osName = "Android";
|
|
3098
|
+
osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
|
|
3099
|
+
} else if (/linux/i.test(userAgent)) {
|
|
3100
|
+
osName = "Linux";
|
|
3101
|
+
} else if (/cros/i.test(userAgent)) {
|
|
3102
|
+
osName = "Chrome OS";
|
|
3103
|
+
}
|
|
3104
|
+
return {
|
|
3105
|
+
deviceType,
|
|
3106
|
+
browserName,
|
|
3107
|
+
browserVersion,
|
|
3108
|
+
osName,
|
|
3109
|
+
osVersion
|
|
3110
|
+
};
|
|
3111
|
+
}
|
|
3112
|
+
function extractVersion(userAgent, regex) {
|
|
3113
|
+
const match = userAgent.match(regex);
|
|
3114
|
+
return match ? match[1] : null;
|
|
3115
|
+
}
|
|
3116
|
+
function getDeviceDescription(parsed) {
|
|
3117
|
+
const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
|
|
3118
|
+
const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
|
|
3119
|
+
return `${browser} on ${os}`;
|
|
3120
|
+
}
|
|
3121
|
+
module.exports = {
|
|
3122
|
+
parseUserAgent,
|
|
3123
|
+
getDeviceDescription
|
|
3124
|
+
};
|
|
3125
|
+
}
|
|
3126
|
+
});
|
|
3127
|
+
|
|
3128
|
+
// server/src/utils/admin-request-info.js
|
|
3129
|
+
var require_admin_request_info = __commonJS({
|
|
3130
|
+
"server/src/utils/admin-request-info.js"(exports, module) {
|
|
3131
|
+
"use strict";
|
|
3132
|
+
var crypto = __require("node:crypto");
|
|
3133
|
+
var net = __require("node:net");
|
|
3134
|
+
var { parseUserAgent } = require_user_agent_parser();
|
|
3135
|
+
var MAX_USER_AGENT_LENGTH = 256;
|
|
3136
|
+
var MAX_DEVICE_ID_LENGTH = 200;
|
|
3137
|
+
function normalizeIp(value) {
|
|
3138
|
+
if (typeof value !== "string") return null;
|
|
3139
|
+
let ip = value.trim();
|
|
3140
|
+
if (!ip || ip.length > 100) return null;
|
|
3141
|
+
if (ip.startsWith("[")) {
|
|
3142
|
+
const end = ip.indexOf("]");
|
|
3143
|
+
ip = end === -1 ? ip.slice(1) : ip.slice(1, end);
|
|
3144
|
+
}
|
|
3145
|
+
if (/^::ffff:/i.test(ip) && net.isIPv4(ip.slice(7))) ip = ip.slice(7);
|
|
3146
|
+
if (ip.includes(".") && ip.split(":").length === 2) ip = ip.split(":")[0];
|
|
3147
|
+
const zone = ip.indexOf("%");
|
|
3148
|
+
if (zone !== -1) ip = ip.slice(0, zone);
|
|
3149
|
+
return net.isIP(ip) === 0 ? null : ip.toLowerCase();
|
|
3150
|
+
}
|
|
3151
|
+
function getRequestIp(ctx) {
|
|
3152
|
+
try {
|
|
3153
|
+
return normalizeIp(ctx?.request?.ip);
|
|
3154
|
+
} catch {
|
|
3155
|
+
return null;
|
|
3156
|
+
}
|
|
3157
|
+
}
|
|
3158
|
+
function getSocketIp(ctx) {
|
|
3159
|
+
try {
|
|
3160
|
+
return normalizeIp(ctx?.req?.socket?.remoteAddress ?? ctx?.request?.socket?.remoteAddress);
|
|
3161
|
+
} catch {
|
|
3162
|
+
return null;
|
|
3163
|
+
}
|
|
3164
|
+
}
|
|
3165
|
+
function ipv6Groups(ip) {
|
|
3166
|
+
let address = ip;
|
|
3167
|
+
let tail = [];
|
|
3168
|
+
const lastColon = address.lastIndexOf(":");
|
|
3169
|
+
const suffix = address.slice(lastColon + 1);
|
|
3170
|
+
if (net.isIPv4(suffix)) {
|
|
3171
|
+
const [a, b, c, d] = suffix.split(".").map(Number);
|
|
3172
|
+
tail = [a << 8 | b, c << 8 | d];
|
|
3173
|
+
address = `${address.slice(0, lastColon + 1)}0`;
|
|
3174
|
+
}
|
|
3175
|
+
const [head, rest] = address.includes("::") ? address.split("::") : [address, null];
|
|
3176
|
+
const left = head ? head.split(":") : [];
|
|
3177
|
+
const right = rest ? rest.split(":") : [];
|
|
3178
|
+
const fill = rest === null ? 0 : 8 - left.length - right.length;
|
|
3179
|
+
const groups = [...left, ...Array(Math.max(0, fill)).fill("0"), ...right].map(
|
|
3180
|
+
(g) => Number.parseInt(g || "0", 16)
|
|
3181
|
+
);
|
|
3182
|
+
if (tail.length) groups.splice(6, 2, ...tail);
|
|
3183
|
+
return groups.slice(0, 8);
|
|
3184
|
+
}
|
|
3185
|
+
function anonymizeIp(ip) {
|
|
3186
|
+
if (!ip) return null;
|
|
3187
|
+
if (net.isIPv4(ip)) {
|
|
3188
|
+
const parts = ip.split(".");
|
|
3189
|
+
return `${parts[0]}.${parts[1]}.${parts[2]}.0`;
|
|
3190
|
+
}
|
|
3191
|
+
if (net.isIPv6(ip)) {
|
|
3192
|
+
const groups = ipv6Groups(ip);
|
|
3193
|
+
return `${groups.slice(0, 3).map((group) => group.toString(16)).join(":")}::`;
|
|
3194
|
+
}
|
|
3195
|
+
return null;
|
|
3196
|
+
}
|
|
3197
|
+
function getRequestUserAgent(ctx) {
|
|
3198
|
+
const value = ctx?.request?.headers?.["user-agent"];
|
|
3199
|
+
if (typeof value !== "string" || !value.trim()) return null;
|
|
3200
|
+
return value.slice(0, MAX_USER_AGENT_LENGTH);
|
|
3201
|
+
}
|
|
3202
|
+
function describeUserAgent(userAgent) {
|
|
3203
|
+
if (!userAgent) return { browserName: null, osName: null, deviceType: null };
|
|
3204
|
+
const parsed = parseUserAgent(userAgent);
|
|
3205
|
+
const known = (value) => value && value !== "unknown" ? String(value) : null;
|
|
3206
|
+
const browser = known(parsed.browserName);
|
|
3207
|
+
const os = known(parsed.osName);
|
|
3208
|
+
return {
|
|
3209
|
+
browserName: browser ? (parsed.browserVersion ? `${browser} ${parsed.browserVersion}` : browser).slice(0, 60) : null,
|
|
3210
|
+
osName: os ? (parsed.osVersion ? `${os} ${parsed.osVersion}` : os).slice(0, 60) : null,
|
|
3211
|
+
deviceType: known(parsed.deviceType)?.slice(0, 20) || null
|
|
3212
|
+
};
|
|
3213
|
+
}
|
|
3214
|
+
function hashDeviceId(deviceId) {
|
|
3215
|
+
if (typeof deviceId !== "string" || !deviceId || deviceId.length > MAX_DEVICE_ID_LENGTH) {
|
|
3216
|
+
return null;
|
|
3217
|
+
}
|
|
3218
|
+
return crypto.createHash("sha256").update(deviceId).digest("hex");
|
|
3219
|
+
}
|
|
3220
|
+
module.exports = {
|
|
3221
|
+
MAX_USER_AGENT_LENGTH,
|
|
3222
|
+
anonymizeIp,
|
|
3223
|
+
describeUserAgent,
|
|
3224
|
+
getRequestIp,
|
|
3225
|
+
getSocketIp,
|
|
3226
|
+
getRequestUserAgent,
|
|
3227
|
+
hashDeviceId,
|
|
3228
|
+
normalizeIp
|
|
3229
|
+
};
|
|
3230
|
+
}
|
|
3231
|
+
});
|
|
3232
|
+
|
|
3233
|
+
// server/src/utils/admin-activity-capture.js
|
|
3234
|
+
var require_admin_activity_capture = __commonJS({
|
|
3235
|
+
"server/src/utils/admin-activity-capture.js"(exports, module) {
|
|
3236
|
+
"use strict";
|
|
3237
|
+
var {
|
|
3238
|
+
SECURITY_EVENTS,
|
|
3239
|
+
describeContentManagerRequest,
|
|
3240
|
+
handlerName,
|
|
3241
|
+
safeReason
|
|
3242
|
+
} = require_security_log_model();
|
|
3243
|
+
var { getRequestIp, getRequestUserAgent, getSocketIp } = require_admin_request_info();
|
|
3244
|
+
var { resolveSecurityLogSettings } = require_security_log_settings();
|
|
3245
|
+
var { getPluginSettings, peekCachedSettings } = require_settings_loader();
|
|
3246
|
+
var { migrateSecurityLog } = require_security_log_hardening();
|
|
3247
|
+
var SERVICE = "security-log";
|
|
3248
|
+
var AUTH_HANDLERS = Object.freeze({
|
|
3249
|
+
login: "authentication.login",
|
|
3250
|
+
registerAdmin: "authentication.registerAdmin",
|
|
3251
|
+
register: "authentication.register",
|
|
3252
|
+
resetPassword: "authentication.resetPassword"
|
|
3253
|
+
});
|
|
3254
|
+
var SESSION_CREATING = Object.freeze({
|
|
3255
|
+
[AUTH_HANDLERS.registerAdmin]: "registration",
|
|
3256
|
+
[AUTH_HANDLERS.register]: "registration",
|
|
3257
|
+
[AUTH_HANDLERS.resetPassword]: "password_reset"
|
|
3258
|
+
});
|
|
3259
|
+
function peekSwitches(strapi2) {
|
|
3260
|
+
const cached = peekCachedSettings();
|
|
3261
|
+
if (!cached) {
|
|
3262
|
+
getPluginSettings(strapi2).catch(() => {
|
|
3263
|
+
});
|
|
3264
|
+
return null;
|
|
3265
|
+
}
|
|
3266
|
+
return resolveSecurityLogSettings(cached);
|
|
3267
|
+
}
|
|
3268
|
+
function bodyDeviceId(ctx) {
|
|
3269
|
+
const value = ctx?.request?.body?.deviceId;
|
|
3270
|
+
return typeof value === "string" && value.length > 0 && value.length <= 200 ? value : null;
|
|
3271
|
+
}
|
|
3272
|
+
function requestFacts(ctx) {
|
|
3273
|
+
return {
|
|
3274
|
+
ip: ctx ? getRequestIp(ctx) : null,
|
|
3275
|
+
socketIp: ctx ? getSocketIp(ctx) : null,
|
|
3276
|
+
userAgent: ctx ? getRequestUserAgent(ctx) : null,
|
|
3277
|
+
deviceId: ctx ? bodyDeviceId(ctx) : null
|
|
3278
|
+
};
|
|
3279
|
+
}
|
|
3280
|
+
function currentRequestFacts(strapi2) {
|
|
3281
|
+
return requestFacts(currentContext(strapi2));
|
|
3282
|
+
}
|
|
3283
|
+
function authErrorNamesKnownAdmins(strapi2) {
|
|
3284
|
+
let version;
|
|
3285
|
+
try {
|
|
3286
|
+
version = strapi2?.config?.get?.("info.strapi");
|
|
3287
|
+
} catch {
|
|
3288
|
+
version = void 0;
|
|
3289
|
+
}
|
|
3290
|
+
if (typeof version !== "string") return true;
|
|
3291
|
+
const match = version.match(/^5\.(\d+)\./);
|
|
3292
|
+
if (!match) return true;
|
|
3293
|
+
return Number(match[1]) >= 58;
|
|
3294
|
+
}
|
|
3295
|
+
function currentContext(strapi2) {
|
|
3296
|
+
try {
|
|
3297
|
+
return strapi2.requestContext?.get?.() || null;
|
|
3298
|
+
} catch {
|
|
3299
|
+
return null;
|
|
3300
|
+
}
|
|
3301
|
+
}
|
|
3302
|
+
function attemptedEmailOf(ctx) {
|
|
3303
|
+
const email = ctx?.request?.body?.email;
|
|
3304
|
+
return typeof email === "string" && email.length <= 254 ? email : null;
|
|
3305
|
+
}
|
|
3306
|
+
function createCaptureMiddleware(strapi2, getService) {
|
|
3307
|
+
return async function adminActivityCapture(ctx, next) {
|
|
3308
|
+
let thrown = null;
|
|
3309
|
+
let result;
|
|
3310
|
+
try {
|
|
3311
|
+
result = await next();
|
|
3312
|
+
} catch (error) {
|
|
3313
|
+
thrown = error;
|
|
3314
|
+
}
|
|
3315
|
+
try {
|
|
3316
|
+
const route = ctx.state?.route;
|
|
3317
|
+
const plugin = route?.info?.pluginName;
|
|
3318
|
+
if (plugin === "content-manager") {
|
|
3319
|
+
if (!thrown) observeContentManager(strapi2, getService, ctx, route);
|
|
3320
|
+
} else if (plugin === "admin") {
|
|
3321
|
+
observeAuthentication(strapi2, getService, ctx, route, thrown);
|
|
3322
|
+
}
|
|
3323
|
+
} catch {
|
|
3324
|
+
}
|
|
3325
|
+
if (thrown) throw thrown;
|
|
3326
|
+
return result;
|
|
3327
|
+
};
|
|
3328
|
+
}
|
|
3329
|
+
function observeContentManager(strapi2, getService, ctx, route) {
|
|
3330
|
+
const adminId = ctx.state?.user?.id;
|
|
3331
|
+
const strategy = ctx.state?.auth?.strategy?.name;
|
|
3332
|
+
if (adminId === void 0 || strategy !== "admin" && strategy !== "admin-token") return;
|
|
3333
|
+
const switches = peekSwitches(strapi2);
|
|
3334
|
+
if (switches && !switches.content) return;
|
|
3335
|
+
const entry = describeContentManagerRequest({
|
|
3336
|
+
status: ctx.status,
|
|
3337
|
+
route,
|
|
3338
|
+
params: ctx.params,
|
|
3339
|
+
query: ctx.query,
|
|
3340
|
+
requestBody: ctx.request?.body,
|
|
3341
|
+
responseBody: ctx.body
|
|
3342
|
+
});
|
|
3343
|
+
if (!entry) return;
|
|
3344
|
+
getService()?.recordContentAction({ ...entry, adminUserId: adminId });
|
|
3345
|
+
}
|
|
3346
|
+
function observeAuthentication(strapi2, getService, ctx, route, thrown) {
|
|
3347
|
+
const name = handlerName(route?.handler);
|
|
3348
|
+
if (!name || !(name === AUTH_HANDLERS.login || name in SESSION_CREATING)) return;
|
|
3349
|
+
const switches = peekSwitches(strapi2);
|
|
3350
|
+
if (switches && !switches.signIns) return;
|
|
3351
|
+
const error = (
|
|
3352
|
+
/** @type {any} */
|
|
3353
|
+
thrown
|
|
3354
|
+
);
|
|
3355
|
+
const status = error ? error.name === "RateLimitError" ? 429 : Number(error.status) || 500 : Number(ctx.status);
|
|
3356
|
+
const facts = requestFacts(ctx);
|
|
3357
|
+
if (name === AUTH_HANDLERS.login) {
|
|
3358
|
+
if (status !== 429) return;
|
|
3359
|
+
getService()?.record({
|
|
3360
|
+
event: SECURITY_EVENTS.ADMIN_LOCKOUT,
|
|
3361
|
+
actorType: "admin",
|
|
3362
|
+
targetType: "admin",
|
|
3363
|
+
// Resolved to an existing admin in the background, then dropped.
|
|
3364
|
+
attemptedEmail: attemptedEmailOf(ctx),
|
|
3365
|
+
meta: { reason: "rate_limited", provider: "local" },
|
|
3366
|
+
...facts
|
|
3367
|
+
});
|
|
3368
|
+
return;
|
|
3369
|
+
}
|
|
3370
|
+
if (status < 200 || status >= 300) return;
|
|
3371
|
+
const userId = ctx.body?.data?.user?.id;
|
|
3372
|
+
if (userId === void 0) return;
|
|
3373
|
+
getService()?.record({
|
|
3374
|
+
event: SECURITY_EVENTS.ADMIN_SIGN_IN,
|
|
3375
|
+
actorType: "admin",
|
|
3376
|
+
actorId: userId,
|
|
3377
|
+
targetType: "admin",
|
|
3378
|
+
targetId: userId,
|
|
3379
|
+
meta: { reason: (
|
|
3380
|
+
/** @type {any} */
|
|
3381
|
+
SESSION_CREATING[name]
|
|
3382
|
+
), provider: "local" },
|
|
3383
|
+
...facts,
|
|
3384
|
+
// A password reset gives the browser a new device id server-side.
|
|
3385
|
+
deviceId: name === AUTH_HANDLERS.resetPassword ? null : facts.deviceId
|
|
3386
|
+
});
|
|
3387
|
+
}
|
|
3388
|
+
function installAdminActivityCapture(strapi2, { log, runExclusive }) {
|
|
3389
|
+
const getService = () => {
|
|
3390
|
+
const service = strapi2.plugin("magic-sessionmanager")?.service(SERVICE);
|
|
3391
|
+
return service && !service.isStopped() ? service : null;
|
|
3392
|
+
};
|
|
3393
|
+
const cleanups = [];
|
|
3394
|
+
const on = (event, listener) => {
|
|
3395
|
+
const off = strapi2.eventHub?.on?.(event, (payload) => {
|
|
3396
|
+
try {
|
|
3397
|
+
listener(payload);
|
|
3398
|
+
} catch {
|
|
3399
|
+
}
|
|
3400
|
+
});
|
|
3401
|
+
if (typeof off === "function") cleanups.push(off);
|
|
3402
|
+
};
|
|
3403
|
+
on("admin.auth.success", (payload) => {
|
|
3404
|
+
const switches = peekSwitches(strapi2);
|
|
3405
|
+
if (switches && !switches.signIns) return;
|
|
3406
|
+
const id = payload?.user?.id;
|
|
3407
|
+
getService()?.record({
|
|
3408
|
+
event: SECURITY_EVENTS.ADMIN_SIGN_IN,
|
|
3409
|
+
actorType: "admin",
|
|
3410
|
+
actorId: id,
|
|
3411
|
+
targetType: "admin",
|
|
3412
|
+
targetId: id,
|
|
3413
|
+
meta: { provider: safeReason(payload?.provider) || "local" },
|
|
3414
|
+
...currentRequestFacts(strapi2)
|
|
3415
|
+
});
|
|
3416
|
+
});
|
|
3417
|
+
on("admin.auth.error", (payload) => {
|
|
3418
|
+
const switches = peekSwitches(strapi2);
|
|
3419
|
+
if (switches && !switches.signIns) return;
|
|
3420
|
+
const id = payload?.user?.id ?? null;
|
|
3421
|
+
getService()?.record({
|
|
3422
|
+
event: SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
|
|
3423
|
+
actorType: "admin",
|
|
3424
|
+
actorId: id,
|
|
3425
|
+
targetType: "admin",
|
|
3426
|
+
targetId: id,
|
|
3427
|
+
...id === null && !authErrorNamesKnownAdmins(strapi2) ? { attemptedEmail: attemptedEmailOf(currentContext(strapi2)), actorFromEmail: true } : {},
|
|
3428
|
+
meta: {
|
|
3429
|
+
reason: safeReason(payload?.reason) || "invalid_credentials",
|
|
3430
|
+
provider: safeReason(payload?.provider) || "local"
|
|
3431
|
+
},
|
|
3432
|
+
...currentRequestFacts(strapi2)
|
|
3433
|
+
});
|
|
3434
|
+
});
|
|
3435
|
+
on("admin.logout", (payload) => {
|
|
3436
|
+
const switches = peekSwitches(strapi2);
|
|
3437
|
+
if (switches && !switches.signIns) return;
|
|
3438
|
+
const id = payload?.user?.id;
|
|
3439
|
+
getService()?.record({
|
|
3440
|
+
event: SECURITY_EVENTS.ADMIN_SIGN_OUT,
|
|
3441
|
+
actorType: "admin",
|
|
3442
|
+
actorId: id,
|
|
3443
|
+
targetType: "admin",
|
|
3444
|
+
targetId: id,
|
|
3445
|
+
...currentRequestFacts(strapi2)
|
|
3446
|
+
});
|
|
3447
|
+
});
|
|
3448
|
+
strapi2.server.use(createCaptureMiddleware(strapi2, getService));
|
|
3449
|
+
try {
|
|
3450
|
+
const unsubscribe = strapi2.db.lifecycles.subscribe({
|
|
3451
|
+
models: ["admin::user"],
|
|
3452
|
+
async afterDelete(event) {
|
|
3453
|
+
const id = event?.result?.id;
|
|
3454
|
+
if (id === void 0) return;
|
|
3455
|
+
try {
|
|
3456
|
+
await strapi2.plugin("magic-sessionmanager").service(SERVICE).deleteAdminData(id);
|
|
3457
|
+
} catch (err) {
|
|
3458
|
+
log.warn(
|
|
3459
|
+
"[security-log] Data of a deleted admin could not be removed:",
|
|
3460
|
+
err?.name || "Error"
|
|
3461
|
+
);
|
|
3462
|
+
}
|
|
3463
|
+
}
|
|
3464
|
+
});
|
|
3465
|
+
if (typeof unsubscribe === "function") cleanups.push(unsubscribe);
|
|
3466
|
+
} catch (err) {
|
|
3467
|
+
log.warn("[security-log] Could not watch admin deletions:", err?.name || "Error");
|
|
3468
|
+
}
|
|
3469
|
+
const jobName = "magic-sessionmanager-security-log-retention";
|
|
3470
|
+
const retention = async () => {
|
|
3471
|
+
const job = async () => {
|
|
3472
|
+
const service = strapi2.plugin("magic-sessionmanager").service(SERVICE);
|
|
3473
|
+
await migrateSecurityLog(strapi2, log);
|
|
3474
|
+
const removed = await service.cleanup();
|
|
3475
|
+
if (removed.expired || removed.orphans) {
|
|
3476
|
+
log.info(
|
|
3477
|
+
`[security-log] Retention removed ${removed.expired} expired events and ${removed.orphans} of deleted admins`
|
|
3478
|
+
);
|
|
3479
|
+
}
|
|
3480
|
+
};
|
|
3481
|
+
try {
|
|
3482
|
+
if (runExclusive) await runExclusive("job:security-log-retention", 23 * 60 * 60 * 1e3, job);
|
|
3483
|
+
else await job();
|
|
3484
|
+
} catch (err) {
|
|
3485
|
+
log.warn("[security-log] Retention failed:", err?.name || "Error");
|
|
3486
|
+
}
|
|
3487
|
+
};
|
|
3488
|
+
try {
|
|
3489
|
+
strapi2.cron.add({ [jobName]: { task: retention, options: { rule: "17 3 * * *" } } });
|
|
3490
|
+
cleanups.push(() => strapi2.cron.remove(jobName));
|
|
3491
|
+
} catch (err) {
|
|
3492
|
+
log.warn("[security-log] Retention job could not be scheduled:", err?.name || "Error");
|
|
2432
3493
|
}
|
|
2433
|
-
|
|
2434
|
-
|
|
3494
|
+
return async () => {
|
|
3495
|
+
for (const cleanup of cleanups.splice(0)) {
|
|
3496
|
+
try {
|
|
3497
|
+
cleanup();
|
|
3498
|
+
} catch {
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
try {
|
|
3502
|
+
await strapi2.plugin("magic-sessionmanager")?.service(SERVICE)?.stop();
|
|
3503
|
+
} catch {
|
|
3504
|
+
}
|
|
3505
|
+
};
|
|
2435
3506
|
}
|
|
2436
3507
|
module.exports = {
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
END_MIN_AGE_MS,
|
|
2443
|
-
canInspectNativeSessions,
|
|
2444
|
-
getNativeTrackingSince,
|
|
2445
|
-
ensureNativeTrackingSince,
|
|
2446
|
-
countNativeOnly,
|
|
2447
|
-
deviceClassOf,
|
|
2448
|
-
getNativeOnlySummary,
|
|
2449
|
-
endNativeOnlySessions
|
|
3508
|
+
authErrorNamesKnownAdmins,
|
|
3509
|
+
createCaptureMiddleware,
|
|
3510
|
+
installAdminActivityCapture,
|
|
3511
|
+
observeAuthentication,
|
|
3512
|
+
observeContentManager
|
|
2450
3513
|
};
|
|
2451
3514
|
}
|
|
2452
3515
|
});
|
|
@@ -6574,6 +7637,12 @@ var require_bootstrap = __commonJS({
|
|
|
6574
7637
|
isThenable
|
|
6575
7638
|
} = require_native_session_capture();
|
|
6576
7639
|
var { ensureNativeTrackingSince } = require_native_only_insight();
|
|
7640
|
+
var { installAdminActivityCapture } = require_admin_activity_capture();
|
|
7641
|
+
var {
|
|
7642
|
+
createInternalTypeGuard,
|
|
7643
|
+
migrateSecurityLog,
|
|
7644
|
+
warnUnboundedProxyTrust
|
|
7645
|
+
} = require_security_log_hardening();
|
|
6577
7646
|
var SESSION_UID = "plugin::magic-sessionmanager.session";
|
|
6578
7647
|
var FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1e3;
|
|
6579
7648
|
var RETENTION_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -6728,6 +7797,23 @@ var require_bootstrap = __commonJS({
|
|
|
6728
7797
|
log.info("[SUCCESS] Session-rejection-headers middleware mounted");
|
|
6729
7798
|
strapi2.server.use(require_last_seen()({ strapi: strapi2, sessionService }));
|
|
6730
7799
|
log.info("[SUCCESS] LastSeen middleware mounted");
|
|
7800
|
+
strapi2.server.use(createInternalTypeGuard());
|
|
7801
|
+
warnUnboundedProxyTrust(strapi2, log);
|
|
7802
|
+
const runExclusive = async (name, leaseMs, job) => {
|
|
7803
|
+
if (await coordinator.tryAcquireLease(name, leaseMs)) await job();
|
|
7804
|
+
};
|
|
7805
|
+
strapi2.sessionManagerAdminActivityUninstall = installAdminActivityCapture(strapi2, {
|
|
7806
|
+
log,
|
|
7807
|
+
runExclusive
|
|
7808
|
+
});
|
|
7809
|
+
log.info("[SUCCESS] Admin activity capture mounted");
|
|
7810
|
+
try {
|
|
7811
|
+
await runExclusive("job:security-log-migrations", 10 * 60 * 1e3, async () => {
|
|
7812
|
+
await migrateSecurityLog(strapi2, log);
|
|
7813
|
+
});
|
|
7814
|
+
} catch (err) {
|
|
7815
|
+
log.warn("[security-log] Migration failed:", err?.name || "Error");
|
|
7816
|
+
}
|
|
6731
7817
|
const contentApiPermissionsReady = await ensureContentApiPermissions(strapi2, log);
|
|
6732
7818
|
mountDeferredContentApiPermissionRetry({
|
|
6733
7819
|
strapi: strapi2,
|
|
@@ -8180,6 +9266,14 @@ var require_destroy = __commonJS({
|
|
|
8180
9266
|
}
|
|
8181
9267
|
strapi2.sessionManagerUnsubscribers = [];
|
|
8182
9268
|
}
|
|
9269
|
+
if (typeof strapi2.sessionManagerAdminActivityUninstall === "function") {
|
|
9270
|
+
try {
|
|
9271
|
+
await strapi2.sessionManagerAdminActivityUninstall();
|
|
9272
|
+
} catch (err) {
|
|
9273
|
+
log.warn("Failed to stop the admin activity capture:", err?.name || "Error");
|
|
9274
|
+
}
|
|
9275
|
+
strapi2.sessionManagerAdminActivityUninstall = null;
|
|
9276
|
+
}
|
|
8183
9277
|
log.info("[SUCCESS] Plugin cleanup completed");
|
|
8184
9278
|
};
|
|
8185
9279
|
}
|
|
@@ -8441,18 +9535,110 @@ var require_schema2 = __commonJS({
|
|
|
8441
9535
|
}
|
|
8442
9536
|
});
|
|
8443
9537
|
|
|
9538
|
+
// server/src/content-types/security-event/schema.json
|
|
9539
|
+
var require_schema3 = __commonJS({
|
|
9540
|
+
"server/src/content-types/security-event/schema.json"(exports, module) {
|
|
9541
|
+
module.exports = {
|
|
9542
|
+
kind: "collectionType",
|
|
9543
|
+
collectionName: "magic_sessions_security_events",
|
|
9544
|
+
info: {
|
|
9545
|
+
singularName: "security-event",
|
|
9546
|
+
pluralName: "security-events",
|
|
9547
|
+
displayName: "Security event",
|
|
9548
|
+
description: "Security event log: admin sign-ins, failed attempts, lockouts, sign-outs, who signed out whom, and Content Manager activity of admins"
|
|
9549
|
+
},
|
|
9550
|
+
options: {
|
|
9551
|
+
draftAndPublish: false,
|
|
9552
|
+
comment: ""
|
|
9553
|
+
},
|
|
9554
|
+
pluginOptions: {
|
|
9555
|
+
"content-manager": {
|
|
9556
|
+
visible: false
|
|
9557
|
+
},
|
|
9558
|
+
"content-type-builder": {
|
|
9559
|
+
visible: false
|
|
9560
|
+
}
|
|
9561
|
+
},
|
|
9562
|
+
indexes: [
|
|
9563
|
+
{
|
|
9564
|
+
name: "msm_security_events_actor",
|
|
9565
|
+
columns: ["actor_type", "actor_id", "created_at"]
|
|
9566
|
+
},
|
|
9567
|
+
{
|
|
9568
|
+
name: "msm_security_events_target",
|
|
9569
|
+
columns: ["target_type", "target_id", "created_at"]
|
|
9570
|
+
},
|
|
9571
|
+
{
|
|
9572
|
+
name: "msm_security_events_event",
|
|
9573
|
+
columns: ["event", "created_at"]
|
|
9574
|
+
},
|
|
9575
|
+
{
|
|
9576
|
+
name: "msm_security_events_created",
|
|
9577
|
+
columns: ["created_at"]
|
|
9578
|
+
}
|
|
9579
|
+
],
|
|
9580
|
+
attributes: {
|
|
9581
|
+
event: {
|
|
9582
|
+
type: "string",
|
|
9583
|
+
maxLength: 64,
|
|
9584
|
+
required: true
|
|
9585
|
+
},
|
|
9586
|
+
actorType: {
|
|
9587
|
+
type: "enumeration",
|
|
9588
|
+
enum: ["admin", "user", "system"],
|
|
9589
|
+
required: true
|
|
9590
|
+
},
|
|
9591
|
+
actorId: {
|
|
9592
|
+
type: "string",
|
|
9593
|
+
maxLength: 64
|
|
9594
|
+
},
|
|
9595
|
+
targetType: {
|
|
9596
|
+
type: "string",
|
|
9597
|
+
maxLength: 40
|
|
9598
|
+
},
|
|
9599
|
+
targetId: {
|
|
9600
|
+
type: "string",
|
|
9601
|
+
maxLength: 255
|
|
9602
|
+
},
|
|
9603
|
+
ip: {
|
|
9604
|
+
type: "string",
|
|
9605
|
+
maxLength: 45
|
|
9606
|
+
},
|
|
9607
|
+
userAgent: {
|
|
9608
|
+
type: "text",
|
|
9609
|
+
maxLength: 500
|
|
9610
|
+
},
|
|
9611
|
+
geo: {
|
|
9612
|
+
type: "json"
|
|
9613
|
+
},
|
|
9614
|
+
meta: {
|
|
9615
|
+
type: "json"
|
|
9616
|
+
}
|
|
9617
|
+
}
|
|
9618
|
+
};
|
|
9619
|
+
}
|
|
9620
|
+
});
|
|
9621
|
+
|
|
8444
9622
|
// server/src/content-types/index.js
|
|
8445
9623
|
var require_content_types = __commonJS({
|
|
8446
9624
|
"server/src/content-types/index.js"(exports, module) {
|
|
8447
9625
|
"use strict";
|
|
8448
9626
|
var session = require_schema();
|
|
8449
9627
|
var revokedToken = require_schema2();
|
|
9628
|
+
var securityEvent = require_schema3();
|
|
8450
9629
|
module.exports = {
|
|
8451
9630
|
session: {
|
|
8452
9631
|
schema: session
|
|
8453
9632
|
},
|
|
8454
9633
|
"revoked-token": {
|
|
8455
9634
|
schema: revokedToken
|
|
9635
|
+
},
|
|
9636
|
+
// One security event log (4.15): admin sign-ins and sign-outs, failed
|
|
9637
|
+
// attempts, lockouts, who signed out whom, Content Manager activity, and
|
|
9638
|
+
// later app-user security events. Hidden from the Content Manager and the
|
|
9639
|
+
// Content-Type Builder.
|
|
9640
|
+
"security-event": {
|
|
9641
|
+
schema: securityEvent
|
|
8456
9642
|
}
|
|
8457
9643
|
};
|
|
8458
9644
|
}
|
|
@@ -8562,6 +9748,7 @@ var require_admin = __commonJS({
|
|
|
8562
9748
|
var PLUGIN_ACCESS_ACTION = "plugin::magic-sessionmanager.access";
|
|
8563
9749
|
var ADMIN_SESSIONS_READ_ACTION = "plugin::magic-sessionmanager.admin-sessions.read";
|
|
8564
9750
|
var ADMIN_SESSIONS_REVOKE_ACTION = "plugin::magic-sessionmanager.admin-sessions.revoke";
|
|
9751
|
+
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
8565
9752
|
var adminPolicy = () => [
|
|
8566
9753
|
"admin::isAuthenticatedAdmin",
|
|
8567
9754
|
{
|
|
@@ -8774,6 +9961,47 @@ var require_admin = __commonJS({
|
|
|
8774
9961
|
description: "Sign a Strapi admin out of every browser (admin)"
|
|
8775
9962
|
}
|
|
8776
9963
|
},
|
|
9964
|
+
// ============== ADMIN SIGN-IN HISTORY AND CONTENT MANAGER ACTIVITY ==============
|
|
9965
|
+
{
|
|
9966
|
+
method: "GET",
|
|
9967
|
+
path: "/admin-activity/sign-ins",
|
|
9968
|
+
handler: "admin-activity.listSignIns",
|
|
9969
|
+
config: {
|
|
9970
|
+
policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
|
|
9971
|
+
middlewares: adminReadRateLimit(),
|
|
9972
|
+
description: "List the admin sign-in history (admin)"
|
|
9973
|
+
}
|
|
9974
|
+
},
|
|
9975
|
+
{
|
|
9976
|
+
method: "GET",
|
|
9977
|
+
path: "/admin-activity/sign-ins/export",
|
|
9978
|
+
handler: "admin-activity.exportSignIns",
|
|
9979
|
+
config: {
|
|
9980
|
+
policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
|
|
9981
|
+
middlewares: adminReadRateLimit(),
|
|
9982
|
+
description: "Get one export batch of the admin sign-in history (admin)"
|
|
9983
|
+
}
|
|
9984
|
+
},
|
|
9985
|
+
{
|
|
9986
|
+
method: "GET",
|
|
9987
|
+
path: "/admin-activity/content",
|
|
9988
|
+
handler: "admin-activity.listContentActivity",
|
|
9989
|
+
config: {
|
|
9990
|
+
policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
|
|
9991
|
+
middlewares: adminReadRateLimit(),
|
|
9992
|
+
description: "List Content Manager activity of admins (admin)"
|
|
9993
|
+
}
|
|
9994
|
+
},
|
|
9995
|
+
{
|
|
9996
|
+
method: "GET",
|
|
9997
|
+
path: "/admin-activity/content/export",
|
|
9998
|
+
handler: "admin-activity.exportContentActivity",
|
|
9999
|
+
config: {
|
|
10000
|
+
policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_ACTIVITY_READ_ACTION]),
|
|
10001
|
+
middlewares: adminReadRateLimit(),
|
|
10002
|
+
description: "Get one export batch of Content Manager activity of admins (admin)"
|
|
10003
|
+
}
|
|
10004
|
+
},
|
|
8777
10005
|
// ============================ GEOLOCATION ============================
|
|
8778
10006
|
{
|
|
8779
10007
|
method: "GET",
|
|
@@ -8825,136 +10053,39 @@ var require_admin = __commonJS({
|
|
|
8825
10053
|
method: "PUT",
|
|
8826
10054
|
path: "/settings",
|
|
8827
10055
|
handler: "settings.updateSettings",
|
|
8828
|
-
config: {
|
|
8829
|
-
policies: adminPolicy(),
|
|
8830
|
-
description: "Update plugin settings (admin)"
|
|
8831
|
-
}
|
|
8832
|
-
}
|
|
8833
|
-
];
|
|
8834
|
-
var devOnlyRoutes = [
|
|
8835
|
-
{
|
|
8836
|
-
method: "POST",
|
|
8837
|
-
path: "/sessions/:sessionId/simulate-timeout",
|
|
8838
|
-
handler: "session.simulateTimeout",
|
|
8839
|
-
config: {
|
|
8840
|
-
policies: adminPolicy(),
|
|
8841
|
-
description: "Simulate session timeout (dev-only, admin)"
|
|
8842
|
-
}
|
|
8843
|
-
}
|
|
8844
|
-
];
|
|
8845
|
-
module.exports = {
|
|
8846
|
-
type: "admin",
|
|
8847
|
-
routes: isDevEnvironment ? [...baseRoutes, ...devOnlyRoutes] : baseRoutes
|
|
8848
|
-
};
|
|
8849
|
-
}
|
|
8850
|
-
});
|
|
8851
|
-
|
|
8852
|
-
// server/src/routes/index.js
|
|
8853
|
-
var require_routes = __commonJS({
|
|
8854
|
-
"server/src/routes/index.js"(exports, module) {
|
|
8855
|
-
"use strict";
|
|
8856
|
-
var contentApi = require_content_api();
|
|
8857
|
-
var admin = require_admin();
|
|
8858
|
-
module.exports = {
|
|
8859
|
-
admin,
|
|
8860
|
-
"content-api": contentApi
|
|
8861
|
-
};
|
|
8862
|
-
}
|
|
8863
|
-
});
|
|
8864
|
-
|
|
8865
|
-
// server/src/utils/user-agent-parser.js
|
|
8866
|
-
var require_user_agent_parser = __commonJS({
|
|
8867
|
-
"server/src/utils/user-agent-parser.js"(exports, module) {
|
|
8868
|
-
"use strict";
|
|
8869
|
-
function parseUserAgent(userAgent) {
|
|
8870
|
-
if (!userAgent) {
|
|
8871
|
-
return {
|
|
8872
|
-
deviceType: "unknown",
|
|
8873
|
-
browserName: "unknown",
|
|
8874
|
-
browserVersion: null,
|
|
8875
|
-
osName: "unknown",
|
|
8876
|
-
osVersion: null
|
|
8877
|
-
};
|
|
8878
|
-
}
|
|
8879
|
-
let deviceType = "desktop";
|
|
8880
|
-
if (/ipad|tablet|kindle|silk/i.test(userAgent)) {
|
|
8881
|
-
deviceType = "tablet";
|
|
8882
|
-
} else if (/mobile|android.*mobile|iphone|ipod|blackberry|iemobile|opera mini|opera mobi/i.test(userAgent)) {
|
|
8883
|
-
deviceType = "mobile";
|
|
8884
|
-
} else if (/android(?!.*mobile)/i.test(userAgent)) {
|
|
8885
|
-
deviceType = "tablet";
|
|
8886
|
-
} else if (/bot|crawl|spider|slurp|mediapartners/i.test(userAgent)) {
|
|
8887
|
-
deviceType = "bot";
|
|
8888
|
-
}
|
|
8889
|
-
let browserName = "unknown";
|
|
8890
|
-
let browserVersion = null;
|
|
8891
|
-
if (/edg\//i.test(userAgent)) {
|
|
8892
|
-
browserName = "Edge";
|
|
8893
|
-
browserVersion = extractVersion(userAgent, /edg\/(\d+[.\d]*)/i);
|
|
8894
|
-
} else if (/opr\//i.test(userAgent) || /opera/i.test(userAgent)) {
|
|
8895
|
-
browserName = "Opera";
|
|
8896
|
-
browserVersion = extractVersion(userAgent, /(?:opr|opera)[\s/](\d+[.\d]*)/i);
|
|
8897
|
-
} else if (/chrome|crios/i.test(userAgent) && !/edg/i.test(userAgent)) {
|
|
8898
|
-
browserName = "Chrome";
|
|
8899
|
-
browserVersion = extractVersion(userAgent, /(?:chrome|crios)\/(\d+[.\d]*)/i);
|
|
8900
|
-
} else if (/firefox|fxios/i.test(userAgent)) {
|
|
8901
|
-
browserName = "Firefox";
|
|
8902
|
-
browserVersion = extractVersion(userAgent, /(?:firefox|fxios)\/(\d+[.\d]*)/i);
|
|
8903
|
-
} else if (/safari/i.test(userAgent) && !/chrome|chromium/i.test(userAgent)) {
|
|
8904
|
-
browserName = "Safari";
|
|
8905
|
-
browserVersion = extractVersion(userAgent, /version\/(\d+[.\d]*)/i);
|
|
8906
|
-
} else if (/msie|trident/i.test(userAgent)) {
|
|
8907
|
-
browserName = "Internet Explorer";
|
|
8908
|
-
browserVersion = extractVersion(userAgent, /(?:msie |rv:)(\d+[.\d]*)/i);
|
|
10056
|
+
config: {
|
|
10057
|
+
policies: adminPolicy(),
|
|
10058
|
+
description: "Update plugin settings (admin)"
|
|
10059
|
+
}
|
|
8909
10060
|
}
|
|
8910
|
-
|
|
8911
|
-
|
|
8912
|
-
|
|
8913
|
-
|
|
8914
|
-
|
|
8915
|
-
|
|
8916
|
-
|
|
8917
|
-
|
|
8918
|
-
|
|
8919
|
-
|
|
8920
|
-
"6.0": "Vista",
|
|
8921
|
-
5.1: "XP"
|
|
8922
|
-
};
|
|
8923
|
-
osVersion = winVersionMap[winVersion] || winVersion;
|
|
8924
|
-
} else if (/iphone|ipad|ipod/i.test(userAgent)) {
|
|
8925
|
-
osName = "iOS";
|
|
8926
|
-
osVersion = extractVersion(userAgent, /\bos (\d+[_.\d]*)/i)?.replace(/_/g, ".");
|
|
8927
|
-
} else if (/mac os x/i.test(userAgent)) {
|
|
8928
|
-
osName = "macOS";
|
|
8929
|
-
osVersion = extractVersion(userAgent, /mac os x (\d+[_.\d]*)/i)?.replace(/_/g, ".");
|
|
8930
|
-
} else if (/android/i.test(userAgent)) {
|
|
8931
|
-
osName = "Android";
|
|
8932
|
-
osVersion = extractVersion(userAgent, /android (\d+[.\d]*)/i);
|
|
8933
|
-
} else if (/linux/i.test(userAgent)) {
|
|
8934
|
-
osName = "Linux";
|
|
8935
|
-
} else if (/cros/i.test(userAgent)) {
|
|
8936
|
-
osName = "Chrome OS";
|
|
10061
|
+
];
|
|
10062
|
+
var devOnlyRoutes = [
|
|
10063
|
+
{
|
|
10064
|
+
method: "POST",
|
|
10065
|
+
path: "/sessions/:sessionId/simulate-timeout",
|
|
10066
|
+
handler: "session.simulateTimeout",
|
|
10067
|
+
config: {
|
|
10068
|
+
policies: adminPolicy(),
|
|
10069
|
+
description: "Simulate session timeout (dev-only, admin)"
|
|
10070
|
+
}
|
|
8937
10071
|
}
|
|
8938
|
-
|
|
8939
|
-
deviceType,
|
|
8940
|
-
browserName,
|
|
8941
|
-
browserVersion,
|
|
8942
|
-
osName,
|
|
8943
|
-
osVersion
|
|
8944
|
-
};
|
|
8945
|
-
}
|
|
8946
|
-
function extractVersion(userAgent, regex) {
|
|
8947
|
-
const match = userAgent.match(regex);
|
|
8948
|
-
return match ? match[1] : null;
|
|
8949
|
-
}
|
|
8950
|
-
function getDeviceDescription(parsed) {
|
|
8951
|
-
const browser = parsed.browserVersion ? `${parsed.browserName} ${parsed.browserVersion}` : parsed.browserName;
|
|
8952
|
-
const os = parsed.osVersion ? `${parsed.osName} ${parsed.osVersion}` : parsed.osName;
|
|
8953
|
-
return `${browser} on ${os}`;
|
|
8954
|
-
}
|
|
10072
|
+
];
|
|
8955
10073
|
module.exports = {
|
|
8956
|
-
|
|
8957
|
-
|
|
10074
|
+
type: "admin",
|
|
10075
|
+
routes: isDevEnvironment ? [...baseRoutes, ...devOnlyRoutes] : baseRoutes
|
|
10076
|
+
};
|
|
10077
|
+
}
|
|
10078
|
+
});
|
|
10079
|
+
|
|
10080
|
+
// server/src/routes/index.js
|
|
10081
|
+
var require_routes = __commonJS({
|
|
10082
|
+
"server/src/routes/index.js"(exports, module) {
|
|
10083
|
+
"use strict";
|
|
10084
|
+
var contentApi = require_content_api();
|
|
10085
|
+
var admin = require_admin();
|
|
10086
|
+
module.exports = {
|
|
10087
|
+
admin,
|
|
10088
|
+
"content-api": contentApi
|
|
8958
10089
|
};
|
|
8959
10090
|
}
|
|
8960
10091
|
});
|
|
@@ -11198,6 +12329,97 @@ var require_geoip_updater = __commonJS({
|
|
|
11198
12329
|
}
|
|
11199
12330
|
});
|
|
11200
12331
|
|
|
12332
|
+
// server/src/utils/settings-access.js
|
|
12333
|
+
var require_settings_access = __commonJS({
|
|
12334
|
+
"server/src/utils/settings-access.js"(exports, module) {
|
|
12335
|
+
"use strict";
|
|
12336
|
+
var { SECURITY_LOG_KEYS } = require_security_log_settings();
|
|
12337
|
+
var SETTINGS_UPDATE_ACTION = "plugin::magic-sessionmanager.settings.update";
|
|
12338
|
+
var ADMIN_ACTIVITY_READ_ACTION = "plugin::magic-sessionmanager.admin-activity.read";
|
|
12339
|
+
var GEO_SETTINGS_KEYS = Object.freeze([
|
|
12340
|
+
"enableGeolocation",
|
|
12341
|
+
"geoIpProvider",
|
|
12342
|
+
"geoLookupFailureMode",
|
|
12343
|
+
"geoIpDatabasePath"
|
|
12344
|
+
]);
|
|
12345
|
+
var WEBHOOK_SETTINGS_KEYS = Object.freeze([
|
|
12346
|
+
"enableWebhooks",
|
|
12347
|
+
"discordWebhookUrl",
|
|
12348
|
+
"slackWebhookUrl"
|
|
12349
|
+
]);
|
|
12350
|
+
var PROTECTED_SETTINGS_KEYS = Object.freeze([
|
|
12351
|
+
...GEO_SETTINGS_KEYS,
|
|
12352
|
+
...WEBHOOK_SETTINGS_KEYS,
|
|
12353
|
+
...SECURITY_LOG_KEYS
|
|
12354
|
+
]);
|
|
12355
|
+
var WEBHOOK_SECRETS = Object.freeze([
|
|
12356
|
+
{ key: "discordWebhookUrl", has: "hasDiscordWebhook", hint: "discordWebhookHint" },
|
|
12357
|
+
{ key: "slackWebhookUrl", has: "hasSlackWebhook", hint: "slackWebhookHint" }
|
|
12358
|
+
]);
|
|
12359
|
+
function sameValue(a, b) {
|
|
12360
|
+
if (a === b) return true;
|
|
12361
|
+
try {
|
|
12362
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
12363
|
+
} catch {
|
|
12364
|
+
return false;
|
|
12365
|
+
}
|
|
12366
|
+
}
|
|
12367
|
+
function changedKeys(next, current, keys) {
|
|
12368
|
+
return keys.filter((key) => !sameValue(next?.[key], current?.[key]));
|
|
12369
|
+
}
|
|
12370
|
+
function callerCan(ctx, action) {
|
|
12371
|
+
try {
|
|
12372
|
+
return ctx?.state?.userAbility?.can?.(action) === true;
|
|
12373
|
+
} catch {
|
|
12374
|
+
return false;
|
|
12375
|
+
}
|
|
12376
|
+
}
|
|
12377
|
+
function missingSettingsPermission(ctx, changed) {
|
|
12378
|
+
const touchesLog = changed.some((key) => SECURITY_LOG_KEYS.includes(key));
|
|
12379
|
+
if (touchesLog && !callerCan(ctx, ADMIN_ACTIVITY_READ_ACTION)) {
|
|
12380
|
+
return "admin-activity-permission";
|
|
12381
|
+
}
|
|
12382
|
+
const touchesProtected = changed.some((key) => PROTECTED_SETTINGS_KEYS.includes(key));
|
|
12383
|
+
if (touchesProtected && !callerCan(ctx, SETTINGS_UPDATE_ACTION)) {
|
|
12384
|
+
return "settings-update-permission";
|
|
12385
|
+
}
|
|
12386
|
+
return null;
|
|
12387
|
+
}
|
|
12388
|
+
function webhookHint(url) {
|
|
12389
|
+
if (typeof url !== "string" || !url.trim()) return null;
|
|
12390
|
+
try {
|
|
12391
|
+
const parsed = new URL(url.trim());
|
|
12392
|
+
return `${parsed.protocol}//${parsed.hostname}/\u2026`;
|
|
12393
|
+
} catch {
|
|
12394
|
+
return null;
|
|
12395
|
+
}
|
|
12396
|
+
}
|
|
12397
|
+
function toPublicSettings(settings) {
|
|
12398
|
+
const out = { ...settings || {} };
|
|
12399
|
+
for (const { key, has, hint } of WEBHOOK_SECRETS) {
|
|
12400
|
+
const value = out[key];
|
|
12401
|
+
delete out[key];
|
|
12402
|
+
out[has] = typeof value === "string" && value.trim().length > 0;
|
|
12403
|
+
out[hint] = webhookHint(value);
|
|
12404
|
+
}
|
|
12405
|
+
return out;
|
|
12406
|
+
}
|
|
12407
|
+
module.exports = {
|
|
12408
|
+
ADMIN_ACTIVITY_READ_ACTION,
|
|
12409
|
+
GEO_SETTINGS_KEYS,
|
|
12410
|
+
PROTECTED_SETTINGS_KEYS,
|
|
12411
|
+
SETTINGS_UPDATE_ACTION,
|
|
12412
|
+
WEBHOOK_SECRETS,
|
|
12413
|
+
WEBHOOK_SETTINGS_KEYS,
|
|
12414
|
+
callerCan,
|
|
12415
|
+
changedKeys,
|
|
12416
|
+
missingSettingsPermission,
|
|
12417
|
+
toPublicSettings,
|
|
12418
|
+
webhookHint
|
|
12419
|
+
};
|
|
12420
|
+
}
|
|
12421
|
+
});
|
|
12422
|
+
|
|
11201
12423
|
// server/src/controllers/settings.js
|
|
11202
12424
|
var require_settings = __commonJS({
|
|
11203
12425
|
"server/src/controllers/settings.js"(exports, module) {
|
|
@@ -11212,6 +12434,15 @@ var require_settings = __commonJS({
|
|
|
11212
12434
|
var { LockTimeoutError } = require_coordination();
|
|
11213
12435
|
var { resolveDatabaseTarget } = require_geoip_updater();
|
|
11214
12436
|
var { sendServerError, sendValidationError } = require_http_errors();
|
|
12437
|
+
var {
|
|
12438
|
+
SECURITY_LOG_DEFAULTS,
|
|
12439
|
+
validateSecurityLogSettings
|
|
12440
|
+
} = require_security_log_settings();
|
|
12441
|
+
var {
|
|
12442
|
+
changedKeys,
|
|
12443
|
+
missingSettingsPermission,
|
|
12444
|
+
toPublicSettings
|
|
12445
|
+
} = require_settings_access();
|
|
11215
12446
|
var path = __require("node:path");
|
|
11216
12447
|
var ALLOWED_WEBHOOK_DOMAINS = {
|
|
11217
12448
|
discord: ["discord.com", "discordapp.com"],
|
|
@@ -11385,7 +12616,8 @@ var require_settings = __commonJS({
|
|
|
11385
12616
|
slackWebhookUrl: "",
|
|
11386
12617
|
strictSessionEnforcement: false,
|
|
11387
12618
|
trustedProxies: false,
|
|
11388
|
-
emailTemplates: DEFAULT_EMAIL_TEMPLATES
|
|
12619
|
+
emailTemplates: DEFAULT_EMAIL_TEMPLATES,
|
|
12620
|
+
...SECURITY_LOG_DEFAULTS
|
|
11389
12621
|
};
|
|
11390
12622
|
function mergeSettingsWithDefaults(stored) {
|
|
11391
12623
|
const safeStored = stored && typeof stored === "object" ? stored : {};
|
|
@@ -11590,6 +12822,9 @@ var require_settings = __commonJS({
|
|
|
11590
12822
|
next.emailTemplates = sanitizeEmailTemplates(mergedTemplates);
|
|
11591
12823
|
}
|
|
11592
12824
|
}
|
|
12825
|
+
const securityLog = validateSecurityLogSettings(body);
|
|
12826
|
+
errors.push(...securityLog.errors);
|
|
12827
|
+
Object.assign(next, securityLog.values);
|
|
11593
12828
|
if (errors.length > 0) return { errors };
|
|
11594
12829
|
const settings = {};
|
|
11595
12830
|
for (const key of Object.keys(DEFAULT_SETTINGS)) {
|
|
@@ -11617,12 +12852,38 @@ var require_settings = __commonJS({
|
|
|
11617
12852
|
};
|
|
11618
12853
|
return ctx.body;
|
|
11619
12854
|
}
|
|
12855
|
+
var FORBIDDEN_MESSAGES = Object.freeze({
|
|
12856
|
+
"admin-activity-permission": 'Changing the security log settings needs "View admin activity".',
|
|
12857
|
+
"settings-update-permission": 'Changing location lookup, webhook or security log settings needs "Change protected settings".'
|
|
12858
|
+
});
|
|
12859
|
+
function recordSettingsChange(ctx, keys) {
|
|
12860
|
+
if (!keys.length) return;
|
|
12861
|
+
try {
|
|
12862
|
+
const strategy = ctx.state?.auth?.strategy?.name;
|
|
12863
|
+
strapi.plugin("magic-sessionmanager")?.service("security-log")?.record({
|
|
12864
|
+
event: "settings.updated",
|
|
12865
|
+
actorType: "admin",
|
|
12866
|
+
actorId: ctx.state?.user?.id ?? null,
|
|
12867
|
+
targetType: "settings",
|
|
12868
|
+
meta: {
|
|
12869
|
+
keys: keys.join(","),
|
|
12870
|
+
count: keys.length,
|
|
12871
|
+
...strategy === "admin-token" ? { via: "admin-token" } : {}
|
|
12872
|
+
}
|
|
12873
|
+
});
|
|
12874
|
+
} catch {
|
|
12875
|
+
}
|
|
12876
|
+
}
|
|
11620
12877
|
module.exports = {
|
|
11621
12878
|
/**
|
|
11622
12879
|
* Returns current plugin settings in user-facing units. Legacy custom MMDB
|
|
11623
|
-
* read paths are not returned as download destinations.
|
|
12880
|
+
* read paths are not returned as download destinations. Webhook URLs are
|
|
12881
|
+
* never returned: `hasDiscordWebhook` / `hasSlackWebhook` say whether one
|
|
12882
|
+
* is stored and `discordWebhookHint` / `slackWebhookHint` show only scheme
|
|
12883
|
+
* and host (4.17, F6).
|
|
11624
12884
|
*
|
|
11625
12885
|
* @route GET /magic-sessionmanager/settings
|
|
12886
|
+
* @auth Admin JWT or admin API token; admin::hasPermissions access.
|
|
11626
12887
|
* @returns {Promise<void>}
|
|
11627
12888
|
*/
|
|
11628
12889
|
async getSettings(ctx) {
|
|
@@ -11632,7 +12893,7 @@ var require_settings = __commonJS({
|
|
|
11632
12893
|
name: "magic-sessionmanager"
|
|
11633
12894
|
});
|
|
11634
12895
|
const storedSettings = await pluginStore.get({ key: "settings" });
|
|
11635
|
-
const settings = mergeSettingsWithDefaults(storedSettings);
|
|
12896
|
+
const settings = toPublicSettings(mergeSettingsWithDefaults(storedSettings));
|
|
11636
12897
|
const revision = await readRevision();
|
|
11637
12898
|
ctx.send({
|
|
11638
12899
|
settings,
|
|
@@ -11655,9 +12916,20 @@ var require_settings = __commonJS({
|
|
|
11655
12916
|
* Omitted fields keep their stored value. Invalid values are rejected with
|
|
11656
12917
|
* a 400 whose `error.details.errors` names each field; nothing is clamped
|
|
11657
12918
|
* or written in that case. Store failures return a 500 with a safe message.
|
|
12919
|
+
* Changing a security log setting (`adminSignInHistory`,
|
|
12920
|
+
* `adminContentActivity`, `securityLogStoreIp`, `securityLogAnonymizeIp`,
|
|
12921
|
+
* `securityLogGeoLookup`, `securityLogRetentionDays`) also needs
|
|
12922
|
+
* `admin-activity.read` (403 `admin-activity-permission`). Changing a
|
|
12923
|
+
* protected key (location lookup, webhooks, security log; see
|
|
12924
|
+
* utils/settings-access.js) needs `settings.update` (403
|
|
12925
|
+
* `settings-update-permission`). A webhook URL missing from the body keeps
|
|
12926
|
+
* its stored value; an empty string removes it.
|
|
11658
12927
|
*
|
|
11659
12928
|
* @route PUT /magic-sessionmanager/settings
|
|
12929
|
+
* @auth Admin JWT or admin API token; admin::hasPermissions access, plus the actions above.
|
|
11660
12930
|
* @returns {Promise<void>}
|
|
12931
|
+
* @sideeffect Writes the plugin store; queues an always-on `settings.updated` security event
|
|
12932
|
+
* with the actor id and the changed key names (no values).
|
|
11661
12933
|
*/
|
|
11662
12934
|
async updateSettings(ctx) {
|
|
11663
12935
|
try {
|
|
@@ -11686,25 +12958,43 @@ var require_settings = __commonJS({
|
|
|
11686
12958
|
};
|
|
11687
12959
|
const { settings: sanitizedSettings, errors } = validateSettingsUpdate(body, current);
|
|
11688
12960
|
if (errors.length > 0) return { errors };
|
|
12961
|
+
const changed = changedKeys(
|
|
12962
|
+
{
|
|
12963
|
+
...sanitizedSettings,
|
|
12964
|
+
geoIpDatabasePath: getSafeGeoIpFilename(sanitizedSettings.geoIpDatabasePath)
|
|
12965
|
+
},
|
|
12966
|
+
{ ...current, geoIpDatabasePath: getSafeGeoIpFilename(current.geoIpDatabasePath) },
|
|
12967
|
+
Object.keys(DEFAULT_SETTINGS)
|
|
12968
|
+
);
|
|
12969
|
+
const missing = missingSettingsPermission(ctx, changed);
|
|
12970
|
+
if (missing) return { forbidden: missing };
|
|
11689
12971
|
await pluginStore.set({
|
|
11690
12972
|
key: "settings",
|
|
11691
12973
|
value: sanitizedSettings
|
|
11692
12974
|
});
|
|
11693
12975
|
const revision = await notifySettingsChanged(strapi);
|
|
11694
|
-
return { settings: sanitizedSettings, revision };
|
|
12976
|
+
return { settings: sanitizedSettings, revision, changed };
|
|
11695
12977
|
});
|
|
12978
|
+
if (outcome.forbidden) {
|
|
12979
|
+
return ctx.forbidden(FORBIDDEN_MESSAGES[outcome.forbidden], {
|
|
12980
|
+
reason: outcome.forbidden
|
|
12981
|
+
});
|
|
12982
|
+
}
|
|
11696
12983
|
if (outcome.conflict) {
|
|
11697
12984
|
return sendSettingsConflict(ctx, outcome.currentRevision);
|
|
11698
12985
|
}
|
|
11699
12986
|
if (outcome.errors) {
|
|
11700
12987
|
return sendValidationError(ctx, "Invalid settings", outcome.errors);
|
|
11701
12988
|
}
|
|
11702
|
-
|
|
12989
|
+
recordSettingsChange(ctx, outcome.changed);
|
|
12990
|
+
strapi.log.info(
|
|
12991
|
+
`[magic-sessionmanager/settings] Settings updated (${outcome.changed.length} keys changed)`
|
|
12992
|
+
);
|
|
11703
12993
|
ctx.send({
|
|
11704
|
-
settings: {
|
|
12994
|
+
settings: toPublicSettings({
|
|
11705
12995
|
...outcome.settings,
|
|
11706
12996
|
geoIpDatabasePath: getSafeGeoIpFilename(outcome.settings.geoIpDatabasePath)
|
|
11707
|
-
},
|
|
12997
|
+
}),
|
|
11708
12998
|
...outcome.revision === null || outcome.revision === void 0 ? {} : { revision: outcome.revision },
|
|
11709
12999
|
success: true,
|
|
11710
13000
|
message: "Settings saved successfully!"
|
|
@@ -12183,7 +13473,11 @@ var require_geoip = __commonJS({
|
|
|
12183
13473
|
var require_admin_sessions = __commonJS({
|
|
12184
13474
|
"server/src/utils/admin-sessions.js"(exports, module) {
|
|
12185
13475
|
"use strict";
|
|
13476
|
+
var crypto = __require("node:crypto");
|
|
12186
13477
|
var { z } = __require("@strapi/utils");
|
|
13478
|
+
var { hashDeviceId } = require_admin_request_info();
|
|
13479
|
+
var { resolveSecurityLogSettings } = require_security_log_settings();
|
|
13480
|
+
var { getPluginSettings } = require_settings_loader();
|
|
12187
13481
|
var ADMIN_ORIGIN = "admin";
|
|
12188
13482
|
var SESSION_UID = "admin::session";
|
|
12189
13483
|
var ADMIN_USER_UID = "admin::user";
|
|
@@ -12192,6 +13486,23 @@ var require_admin_sessions = __commonJS({
|
|
|
12192
13486
|
var MAX_SEARCH_LENGTH = 100;
|
|
12193
13487
|
var MAX_ACTIVE_ROWS = 1e4;
|
|
12194
13488
|
var ADMIN_FILTERS = Object.freeze(["all", "signed-in", "not-signed-in"]);
|
|
13489
|
+
var REPEAT_SIGN_OUT_DELAY_MS = 1e3;
|
|
13490
|
+
var FULL_VISIBILITY = Object.freeze({ identity: true, roles: true });
|
|
13491
|
+
function visibilityOf(ability) {
|
|
13492
|
+
const can = (action) => {
|
|
13493
|
+
try {
|
|
13494
|
+
return ability?.can?.(action) === true;
|
|
13495
|
+
} catch {
|
|
13496
|
+
return false;
|
|
13497
|
+
}
|
|
13498
|
+
};
|
|
13499
|
+
const identity = can("admin::users.read");
|
|
13500
|
+
return { identity, roles: identity || can("admin::roles.read") };
|
|
13501
|
+
}
|
|
13502
|
+
function sessionHandle(sessionId) {
|
|
13503
|
+
if (typeof sessionId !== "string" || !sessionId) return "";
|
|
13504
|
+
return crypto.createHash("sha256").update(`magic-sessionmanager:admin-session:${sessionId}`).digest("hex").slice(0, 32);
|
|
13505
|
+
}
|
|
12195
13506
|
var DEFAULT_POLICY = Object.freeze({
|
|
12196
13507
|
accessTokenLifespan: 30 * 60,
|
|
12197
13508
|
idleSessionLifespan: 2 * 60 * 60,
|
|
@@ -12210,7 +13521,9 @@ var require_admin_sessions = __commonJS({
|
|
|
12210
13521
|
});
|
|
12211
13522
|
var sessionParamsSchema = z.strictObject({
|
|
12212
13523
|
adminId: z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer"),
|
|
12213
|
-
|
|
13524
|
+
// The `id` of a session from the list (an opaque handle since 4.17); a raw
|
|
13525
|
+
// Strapi session id is still accepted.
|
|
13526
|
+
sessionId: z.string().regex(/^[a-f0-9]{32}$/, "sessionId must be a session id from the list")
|
|
12214
13527
|
});
|
|
12215
13528
|
function parseInput(schema, input) {
|
|
12216
13529
|
const result = schema.safeParse(input ?? {});
|
|
@@ -12287,7 +13600,7 @@ var require_admin_sessions = __commonJS({
|
|
|
12287
13600
|
const existing = groups.get(key);
|
|
12288
13601
|
if (!existing) {
|
|
12289
13602
|
groups.set(key, {
|
|
12290
|
-
id: String(row.sessionId),
|
|
13603
|
+
id: sessionHandle(String(row.sessionId)),
|
|
12291
13604
|
device: typeof metadata.deviceName === "string" && metadata.deviceName.trim() ? metadata.deviceName.trim().slice(0, 120) : null,
|
|
12292
13605
|
signedInAt,
|
|
12293
13606
|
lastActiveAt,
|
|
@@ -12346,20 +13659,22 @@ var require_admin_sessions = __commonJS({
|
|
|
12346
13659
|
if (!row || row.origin !== ADMIN_ORIGIN || String(row.userId) !== String(userId)) return null;
|
|
12347
13660
|
return typeof row.deviceId === "string" ? row.deviceId : null;
|
|
12348
13661
|
}
|
|
12349
|
-
function toAdminRow(user, live, actor) {
|
|
13662
|
+
function toAdminRow(user, live, actor, visibility = FULL_VISIBILITY) {
|
|
12350
13663
|
const account = accountState(user);
|
|
12351
13664
|
const blockReason = signOutBlockReason(actor, user);
|
|
12352
13665
|
const sessionCount = account === "active" ? live?.count || 0 : 0;
|
|
13666
|
+
const self = String(actor?.id) === String(user.id);
|
|
13667
|
+
const identity = visibility.identity || self;
|
|
12353
13668
|
return {
|
|
12354
13669
|
id: Number(user.id),
|
|
12355
|
-
name: displayName(user),
|
|
12356
|
-
email: typeof user.email === "string" ? user.email : "",
|
|
12357
|
-
roles: (Array.isArray(user.roles) ? user.roles : []).map((role) => ({
|
|
13670
|
+
name: identity ? displayName(user) : "",
|
|
13671
|
+
email: identity && typeof user.email === "string" ? user.email : "",
|
|
13672
|
+
roles: identity || visibility.roles ? (Array.isArray(user.roles) ? user.roles : []).map((role) => ({
|
|
12358
13673
|
name: String(role?.name || ""),
|
|
12359
13674
|
superAdmin: role?.code === SUPER_ADMIN_CODE
|
|
12360
|
-
})),
|
|
13675
|
+
})) : [],
|
|
12361
13676
|
account,
|
|
12362
|
-
self
|
|
13677
|
+
self,
|
|
12363
13678
|
sessionCount,
|
|
12364
13679
|
lastActiveAt: account === "active" ? live?.lastActiveAt || null : null,
|
|
12365
13680
|
canSignOut: blockReason === null && sessionCount > 0,
|
|
@@ -12385,7 +13700,24 @@ var require_admin_sessions = __commonJS({
|
|
|
12385
13700
|
}
|
|
12386
13701
|
return map;
|
|
12387
13702
|
}
|
|
12388
|
-
async function
|
|
13703
|
+
async function readSignInRecording(strapi2) {
|
|
13704
|
+
try {
|
|
13705
|
+
const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
|
|
13706
|
+
return {
|
|
13707
|
+
signIns: options.signIns,
|
|
13708
|
+
ipAddresses: options.signIns && options.storeIp,
|
|
13709
|
+
anonymizeIp: options.signIns && options.storeIp && options.anonymizeIp
|
|
13710
|
+
};
|
|
13711
|
+
} catch {
|
|
13712
|
+
return { signIns: false, ipAddresses: false, anonymizeIp: false };
|
|
13713
|
+
}
|
|
13714
|
+
}
|
|
13715
|
+
async function listAdmins(strapi2, query, actor, visibility = FULL_VISIBILITY) {
|
|
13716
|
+
const identityMeta = {
|
|
13717
|
+
names: visibility.identity,
|
|
13718
|
+
emails: visibility.identity,
|
|
13719
|
+
roles: visibility.roles
|
|
13720
|
+
};
|
|
12389
13721
|
const policy = readSessionPolicy(strapi2);
|
|
12390
13722
|
if (!getAdminSessionManager(strapi2)) {
|
|
12391
13723
|
return {
|
|
@@ -12395,7 +13727,9 @@ var require_admin_sessions = __commonJS({
|
|
|
12395
13727
|
pagination: { page: 1, pageSize: query.pageSize, total: 0, pageCount: 1 },
|
|
12396
13728
|
stats: null,
|
|
12397
13729
|
policy,
|
|
12398
|
-
truncated: false
|
|
13730
|
+
truncated: false,
|
|
13731
|
+
recording: await readSignInRecording(strapi2),
|
|
13732
|
+
identity: identityMeta
|
|
12399
13733
|
}
|
|
12400
13734
|
};
|
|
12401
13735
|
}
|
|
@@ -12412,7 +13746,7 @@ var require_admin_sessions = __commonJS({
|
|
|
12412
13746
|
where: { id: { $in: liveIds }, ...activeAccountWhere }
|
|
12413
13747
|
})).map((row) => Number(row.id)) : [];
|
|
12414
13748
|
const conditions = [];
|
|
12415
|
-
if (query.search) {
|
|
13749
|
+
if (query.search && visibility.identity) {
|
|
12416
13750
|
const text = query.search;
|
|
12417
13751
|
conditions.push({
|
|
12418
13752
|
$or: [
|
|
@@ -12422,6 +13756,8 @@ var require_admin_sessions = __commonJS({
|
|
|
12422
13756
|
{ email: { $containsi: text } }
|
|
12423
13757
|
]
|
|
12424
13758
|
});
|
|
13759
|
+
} else if (query.search) {
|
|
13760
|
+
conditions.push({ id: /^[1-9][0-9]{0,11}$/.test(query.search) ? Number(query.search) : 0 });
|
|
12425
13761
|
}
|
|
12426
13762
|
if (query.filter === "signed-in")
|
|
12427
13763
|
conditions.push({ id: { $in: signedInIds.length ? signedInIds : [0] } });
|
|
@@ -12437,7 +13773,7 @@ var require_admin_sessions = __commonJS({
|
|
|
12437
13773
|
where,
|
|
12438
13774
|
select: ["id", "firstname", "lastname", "username", "email", "isActive", "blocked"],
|
|
12439
13775
|
populate: { roles: { select: ["id", "name", "code"] } },
|
|
12440
|
-
orderBy: [{ firstname: "asc" }, { lastname: "asc" }, { email: "asc" }, { id: "asc" }],
|
|
13776
|
+
orderBy: visibility.identity ? [{ firstname: "asc" }, { lastname: "asc" }, { email: "asc" }, { id: "asc" }] : [{ id: "asc" }],
|
|
12441
13777
|
offset: (query.page - 1) * query.pageSize,
|
|
12442
13778
|
limit: query.pageSize
|
|
12443
13779
|
})
|
|
@@ -12458,7 +13794,8 @@ var require_admin_sessions = __commonJS({
|
|
|
12458
13794
|
(user) => toAdminRow(
|
|
12459
13795
|
{ ...user, hasRegistrationToken: invited.has(Number(user.id)) },
|
|
12460
13796
|
summary.get(String(user.id)),
|
|
12461
|
-
actor
|
|
13797
|
+
actor,
|
|
13798
|
+
visibility
|
|
12462
13799
|
)
|
|
12463
13800
|
),
|
|
12464
13801
|
meta: {
|
|
@@ -12476,15 +13813,17 @@ var require_admin_sessions = __commonJS({
|
|
|
12476
13813
|
totalAdmins: Number(totalAdmins) || 0
|
|
12477
13814
|
},
|
|
12478
13815
|
policy,
|
|
12479
|
-
truncated
|
|
13816
|
+
truncated,
|
|
13817
|
+
recording: await readSignInRecording(strapi2),
|
|
13818
|
+
identity: identityMeta
|
|
12480
13819
|
}
|
|
12481
13820
|
};
|
|
12482
13821
|
}
|
|
12483
|
-
async function listAdminSessions(strapi2, adminId, actor) {
|
|
13822
|
+
async function listAdminSessions(strapi2, adminId, actor, visibility = FULL_VISIBILITY) {
|
|
12484
13823
|
const target = await findAdmin(strapi2, adminId);
|
|
12485
13824
|
if (!target) return null;
|
|
12486
13825
|
const supported = Boolean(getAdminSessionManager(strapi2));
|
|
12487
|
-
const adminRow = toAdminRow(target, void 0, actor);
|
|
13826
|
+
const adminRow = toAdminRow(target, void 0, actor, visibility);
|
|
12488
13827
|
if (!supported || adminRow.account !== "active") {
|
|
12489
13828
|
return {
|
|
12490
13829
|
data: [],
|
|
@@ -12509,6 +13848,20 @@ var require_admin_sessions = __commonJS({
|
|
|
12509
13848
|
}
|
|
12510
13849
|
};
|
|
12511
13850
|
}
|
|
13851
|
+
function repeatSignOut(strapi2, manager, args, delayMs) {
|
|
13852
|
+
const timer = setTimeout(
|
|
13853
|
+
() => {
|
|
13854
|
+
Promise.resolve().then(() => manager.invalidateRefreshToken(...args)).catch(
|
|
13855
|
+
(err) => strapi2.log?.warn?.(
|
|
13856
|
+
"[magic-sessionmanager] Repeated admin sign-out failed:",
|
|
13857
|
+
err?.name || "Error"
|
|
13858
|
+
)
|
|
13859
|
+
);
|
|
13860
|
+
},
|
|
13861
|
+
Math.max(0, delayMs)
|
|
13862
|
+
);
|
|
13863
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
13864
|
+
}
|
|
12512
13865
|
var AdminSignOutError = class extends Error {
|
|
12513
13866
|
/**
|
|
12514
13867
|
* @param {403|404|503} status HTTP status to answer.
|
|
@@ -12522,7 +13875,7 @@ var require_admin_sessions = __commonJS({
|
|
|
12522
13875
|
this.reason = reason || null;
|
|
12523
13876
|
}
|
|
12524
13877
|
};
|
|
12525
|
-
async function signOutAdmin(strapi2, { actor, adminId, sessionId }) {
|
|
13878
|
+
async function signOutAdmin(strapi2, { actor, adminId, sessionId }, { repeatDelayMs = REPEAT_SIGN_OUT_DELAY_MS } = {}) {
|
|
12526
13879
|
const manager = getAdminSessionManager(strapi2);
|
|
12527
13880
|
if (!manager) {
|
|
12528
13881
|
throw new AdminSignOutError(
|
|
@@ -12547,20 +13900,23 @@ var require_admin_sessions = __commonJS({
|
|
|
12547
13900
|
const currentDeviceId = self ? await findCurrentDeviceId(strapi2, { userId, sessionId: actor.sessionId }) : null;
|
|
12548
13901
|
let ended;
|
|
12549
13902
|
let signedOutSelf;
|
|
13903
|
+
let endedDeviceId = null;
|
|
12550
13904
|
if (sessionId) {
|
|
12551
|
-
const row =
|
|
12552
|
-
|
|
12553
|
-
|
|
12554
|
-
|
|
12555
|
-
if (!row || String(row.userId) !== userId || row.origin !== ADMIN_ORIGIN) {
|
|
13905
|
+
const row = rows.find(
|
|
13906
|
+
(candidate) => typeof candidate.sessionId === "string" && (sessionHandle(candidate.sessionId) === sessionId || candidate.sessionId === sessionId)
|
|
13907
|
+
);
|
|
13908
|
+
if (!row || String(row.userId) !== userId) {
|
|
12556
13909
|
throw new AdminSignOutError(404, "Session not found");
|
|
12557
13910
|
}
|
|
12558
13911
|
if (blockReason === "account-inactive") throw new AdminSignOutError(404, "Session not found");
|
|
12559
13912
|
await manager.invalidateRefreshToken(userId, String(row.deviceId));
|
|
13913
|
+
repeatSignOut(strapi2, manager, [userId, String(row.deviceId)], repeatDelayMs);
|
|
13914
|
+
endedDeviceId = String(row.deviceId);
|
|
12560
13915
|
ended = 1;
|
|
12561
13916
|
signedOutSelf = Boolean(currentDeviceId) && String(row.deviceId) === currentDeviceId;
|
|
12562
13917
|
} else {
|
|
12563
13918
|
await manager.invalidateRefreshToken(userId);
|
|
13919
|
+
repeatSignOut(strapi2, manager, [userId], repeatDelayMs);
|
|
12564
13920
|
ended = blockReason === "account-inactive" ? 0 : devices.length;
|
|
12565
13921
|
signedOutSelf = self && Boolean(currentDeviceId);
|
|
12566
13922
|
}
|
|
@@ -12569,6 +13925,18 @@ var require_admin_sessions = __commonJS({
|
|
|
12569
13925
|
target.id
|
|
12570
13926
|
)} scope=${scope} ended=${ended}`;
|
|
12571
13927
|
strapi2.log.info(audit);
|
|
13928
|
+
try {
|
|
13929
|
+
strapi2.plugin("magic-sessionmanager")?.service("security-log")?.record({
|
|
13930
|
+
event: "admin.session.revoked",
|
|
13931
|
+
actorType: "admin",
|
|
13932
|
+
actorId: Number(actor.id),
|
|
13933
|
+
targetType: "admin",
|
|
13934
|
+
targetId: Number(target.id),
|
|
13935
|
+
meta: { scope: scope === "one" ? "one_browser" : "everywhere", ended },
|
|
13936
|
+
deviceHash: endedDeviceId ? hashDeviceId(endedDeviceId) : null
|
|
13937
|
+
});
|
|
13938
|
+
} catch {
|
|
13939
|
+
}
|
|
12572
13940
|
try {
|
|
12573
13941
|
strapi2.eventHub?.emit?.("magic-sessionmanager.admin-sessions.signed-out", {
|
|
12574
13942
|
actorId: Number(actor.id),
|
|
@@ -12585,6 +13953,7 @@ var require_admin_sessions = __commonJS({
|
|
|
12585
13953
|
ADMIN_ORIGIN,
|
|
12586
13954
|
AdminSignOutError,
|
|
12587
13955
|
DEFAULT_POLICY,
|
|
13956
|
+
FULL_VISIBILITY,
|
|
12588
13957
|
MAX_PAGE_SIZE,
|
|
12589
13958
|
SUPER_ADMIN_CODE,
|
|
12590
13959
|
accountState,
|
|
@@ -12598,10 +13967,12 @@ var require_admin_sessions = __commonJS({
|
|
|
12598
13967
|
listQuerySchema,
|
|
12599
13968
|
parseInput,
|
|
12600
13969
|
readSessionPolicy,
|
|
13970
|
+
sessionHandle,
|
|
12601
13971
|
sessionParamsSchema,
|
|
12602
13972
|
signOutAdmin,
|
|
12603
13973
|
signOutBlockReason,
|
|
12604
|
-
summariseByAdmin
|
|
13974
|
+
summariseByAdmin,
|
|
13975
|
+
visibilityOf
|
|
12605
13976
|
};
|
|
12606
13977
|
}
|
|
12607
13978
|
});
|
|
@@ -12618,7 +13989,8 @@ var require_admin_sessions2 = __commonJS({
|
|
|
12618
13989
|
listQuerySchema,
|
|
12619
13990
|
parseInput,
|
|
12620
13991
|
sessionParamsSchema,
|
|
12621
|
-
signOutAdmin
|
|
13992
|
+
signOutAdmin,
|
|
13993
|
+
visibilityOf
|
|
12622
13994
|
} = require_admin_sessions();
|
|
12623
13995
|
var { sendServerError, sendValidationError } = require_http_errors();
|
|
12624
13996
|
var { createLogger } = require_logger();
|
|
@@ -12665,13 +14037,24 @@ var require_admin_sessions2 = __commonJS({
|
|
|
12665
14037
|
* @param {Context} ctx Reads `ctx.query.page` (1..1e6), `pageSize` (1..100), `search`
|
|
12666
14038
|
* (<= 100 chars, name or email) and `filter` (`all`|`signed-in`|`not-signed-in`).
|
|
12667
14039
|
* @returns {Promise<unknown>} 200 `{ data: AdminRow[], meta: { supported, pagination, stats,
|
|
12668
|
-
* policy, truncated } }`; 400 ValidationError with field errors; 500
|
|
14040
|
+
* policy, truncated, recording, identity } }`; 400 ValidationError with field errors; 500
|
|
14041
|
+
* fixed message. Name and email are empty (and search matches the id only) unless the
|
|
14042
|
+
* caller holds `admin::users.read`; role names need `admin::users.read` or
|
|
14043
|
+
* `admin::roles.read`.
|
|
12669
14044
|
*/
|
|
12670
14045
|
async listAdmins(ctx) {
|
|
12671
14046
|
const parsed = parseInput(listQuerySchema, ctx.query);
|
|
12672
14047
|
if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
|
|
12673
14048
|
try {
|
|
12674
|
-
ctx.body = await listAdmins(
|
|
14049
|
+
ctx.body = await listAdmins(
|
|
14050
|
+
strapi2,
|
|
14051
|
+
parsed.value,
|
|
14052
|
+
actorFrom(ctx),
|
|
14053
|
+
visibilityOf(
|
|
14054
|
+
/** @type {any} */
|
|
14055
|
+
ctx.state?.userAbility
|
|
14056
|
+
)
|
|
14057
|
+
);
|
|
12675
14058
|
return ctx.body;
|
|
12676
14059
|
} catch (error) {
|
|
12677
14060
|
return fail(ctx, error, "list");
|
|
@@ -12685,13 +14068,23 @@ var require_admin_sessions2 = __commonJS({
|
|
|
12685
14068
|
* read rate limit.
|
|
12686
14069
|
* @param {Context} ctx Reads `ctx.params.adminId` (positive integer).
|
|
12687
14070
|
* @returns {Promise<unknown>} 200 `{ data: SessionRow[], meta: { supported, admin, policy } }`;
|
|
12688
|
-
* 400 invalid id; 404 unknown admin; 500 fixed message. No tokens, device ids or hashes
|
|
14071
|
+
* 400 invalid id; 404 unknown admin; 500 fixed message. No tokens, device ids or hashes;
|
|
14072
|
+
* `SessionRow.id` is an opaque handle (not Strapi's session id). `meta.admin` follows the
|
|
14073
|
+
* list's identity rules.
|
|
12689
14074
|
*/
|
|
12690
14075
|
async listAdminSessions(ctx) {
|
|
12691
14076
|
const parsed = parseInput(adminParamsSchema, routeParams(ctx, ["adminId"]));
|
|
12692
14077
|
if (!parsed.ok) return sendValidationError(ctx, "Invalid parameters", parsed.errors);
|
|
12693
14078
|
try {
|
|
12694
|
-
const body = await listAdminSessions(
|
|
14079
|
+
const body = await listAdminSessions(
|
|
14080
|
+
strapi2,
|
|
14081
|
+
parsed.value.adminId,
|
|
14082
|
+
actorFrom(ctx),
|
|
14083
|
+
visibilityOf(
|
|
14084
|
+
/** @type {any} */
|
|
14085
|
+
ctx.state?.userAbility
|
|
14086
|
+
)
|
|
14087
|
+
);
|
|
12695
14088
|
if (!body) return ctx.notFound("Admin not found");
|
|
12696
14089
|
ctx.body = body;
|
|
12697
14090
|
return ctx.body;
|
|
@@ -12706,11 +14099,13 @@ var require_admin_sessions2 = __commonJS({
|
|
|
12706
14099
|
* @auth Admin JWT only (admin API tokens get 403); admin::hasPermissions access +
|
|
12707
14100
|
* admin-sessions.read + admin-sessions.revoke; write rate limit (10/min per admin).
|
|
12708
14101
|
* A Super Admin can only be signed out by a Super Admin or themselves.
|
|
12709
|
-
* @param {Context} ctx Reads `ctx.params.adminId` and `ctx.params.sessionId` (32 hex chars
|
|
14102
|
+
* @param {Context} ctx Reads `ctx.params.adminId` and `ctx.params.sessionId` (32 hex chars:
|
|
14103
|
+
* the `id` from the session list, or a raw Strapi session id).
|
|
12710
14104
|
* @returns {Promise<unknown>} 200 `{ data: { ended, signedOutSelf } }`; 400 invalid params;
|
|
12711
14105
|
* 403 not a browser session or Super Admin guard; 404 unknown admin, or a session that is
|
|
12712
14106
|
* not a live session of that admin; 503 no session manager; 500 fixed message.
|
|
12713
|
-
* @sideeffect Deletes the target browser's `admin::session` rows
|
|
14107
|
+
* @sideeffect Deletes the target browser's `admin::session` rows (and again about a second
|
|
14108
|
+
* later); writes an audit log line.
|
|
12714
14109
|
*/
|
|
12715
14110
|
async signOutSession(ctx) {
|
|
12716
14111
|
if (ctx.state?.auth?.strategy?.name !== "admin") {
|
|
@@ -12743,7 +14138,8 @@ var require_admin_sessions2 = __commonJS({
|
|
|
12743
14138
|
* @returns {Promise<unknown>} 200 `{ data: { ended, signedOutSelf } }`; 400 invalid id;
|
|
12744
14139
|
* 403 not a browser session or Super Admin guard; 404 unknown admin; 503 no session
|
|
12745
14140
|
* manager; 500 fixed message.
|
|
12746
|
-
* @sideeffect Deletes every `admin::session` row of the target admin
|
|
14141
|
+
* @sideeffect Deletes every `admin::session` row of the target admin (and again about a
|
|
14142
|
+
* second later); writes an audit log line.
|
|
12747
14143
|
*/
|
|
12748
14144
|
async signOutEverywhere(ctx) {
|
|
12749
14145
|
if (ctx.state?.auth?.strategy?.name !== "admin") {
|
|
@@ -12769,6 +14165,194 @@ var require_admin_sessions2 = __commonJS({
|
|
|
12769
14165
|
}
|
|
12770
14166
|
});
|
|
12771
14167
|
|
|
14168
|
+
// server/src/controllers/admin-activity.js
|
|
14169
|
+
var require_admin_activity = __commonJS({
|
|
14170
|
+
"server/src/controllers/admin-activity.js"(exports, module) {
|
|
14171
|
+
"use strict";
|
|
14172
|
+
var { z } = __require("@strapi/utils");
|
|
14173
|
+
var { CONTENT_ACTIONS, SIGN_IN_FILTERS } = require_security_log_model();
|
|
14174
|
+
var { parseInput } = require_admin_sessions();
|
|
14175
|
+
var { sendServerError, sendValidationError } = require_http_errors();
|
|
14176
|
+
var { createLogger } = require_logger();
|
|
14177
|
+
var { callerCan } = require_settings_access();
|
|
14178
|
+
var MAX_PAGE_SIZE = 100;
|
|
14179
|
+
var adminIdField = z.string().regex(/^[1-9][0-9]{0,11}$/, "adminId must be a positive integer").transform(Number).optional();
|
|
14180
|
+
var dateField = (name) => z.string().max(40, `${name} must be an ISO 8601 date`).refine((value) => !Number.isNaN(Date.parse(value)), `${name} must be an ISO 8601 date`).transform((value) => new Date(value)).optional();
|
|
14181
|
+
var common = {
|
|
14182
|
+
adminId: adminIdField,
|
|
14183
|
+
from: dateField("from"),
|
|
14184
|
+
to: dateField("to"),
|
|
14185
|
+
page: z.coerce.number().int().min(1).max(1e6).default(1),
|
|
14186
|
+
pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(20)
|
|
14187
|
+
};
|
|
14188
|
+
var signInQuerySchema = z.strictObject({
|
|
14189
|
+
...common,
|
|
14190
|
+
event: z.enum(
|
|
14191
|
+
/** @type {[string, ...string[]]} */
|
|
14192
|
+
Object.keys(SIGN_IN_FILTERS)
|
|
14193
|
+
).default("all")
|
|
14194
|
+
});
|
|
14195
|
+
var activityQuerySchema = z.strictObject({
|
|
14196
|
+
...common,
|
|
14197
|
+
action: z.enum(
|
|
14198
|
+
/** @type {[string, ...string[]]} */
|
|
14199
|
+
["all", ...CONTENT_ACTIONS]
|
|
14200
|
+
).default("all"),
|
|
14201
|
+
contentType: z.string().regex(
|
|
14202
|
+
/^(api|plugin)::[a-z0-9-]{1,80}\.[a-z0-9-]{1,80}$/,
|
|
14203
|
+
"contentType must be a content type uid"
|
|
14204
|
+
).optional()
|
|
14205
|
+
});
|
|
14206
|
+
var cursorField = z.string().regex(/^[1-9][0-9]{0,15}$/, "cursor must be a positive integer").transform(Number).optional();
|
|
14207
|
+
var signInExportSchema = signInQuerySchema.omit({ page: true, pageSize: true }).extend({
|
|
14208
|
+
cursor: cursorField
|
|
14209
|
+
});
|
|
14210
|
+
var activityExportSchema = activityQuerySchema.omit({ page: true, pageSize: true }).extend({
|
|
14211
|
+
cursor: cursorField
|
|
14212
|
+
});
|
|
14213
|
+
module.exports = ({ strapi: strapi2 }) => {
|
|
14214
|
+
const log = createLogger(strapi2);
|
|
14215
|
+
const service = () => strapi2.plugin("magic-sessionmanager").service("security-log");
|
|
14216
|
+
const viewerOf = (ctx) => ({
|
|
14217
|
+
ability: (
|
|
14218
|
+
/** @type {any} */
|
|
14219
|
+
ctx.state?.userAbility || null
|
|
14220
|
+
),
|
|
14221
|
+
canReadAdmins: callerCan(ctx, "admin::users.read")
|
|
14222
|
+
});
|
|
14223
|
+
const auditTokenRead = (ctx, list, exported) => {
|
|
14224
|
+
const state = (
|
|
14225
|
+
/** @type {any} */
|
|
14226
|
+
ctx.state
|
|
14227
|
+
);
|
|
14228
|
+
if (state?.auth?.strategy?.name !== "admin-token") return;
|
|
14229
|
+
try {
|
|
14230
|
+
service().recordTokenRead({
|
|
14231
|
+
adminId: state.user?.id,
|
|
14232
|
+
tokenId: state.auth?.credentials?.id,
|
|
14233
|
+
list,
|
|
14234
|
+
exported
|
|
14235
|
+
});
|
|
14236
|
+
} catch {
|
|
14237
|
+
}
|
|
14238
|
+
};
|
|
14239
|
+
const handle = async (ctx, schema, run, operation) => {
|
|
14240
|
+
const parsed = parseInput(schema, ctx.query);
|
|
14241
|
+
if (!parsed.ok) return sendValidationError(ctx, "Invalid query", parsed.errors);
|
|
14242
|
+
const query = parsed.value;
|
|
14243
|
+
if (query.from && query.to && query.from > query.to) {
|
|
14244
|
+
return sendValidationError(ctx, "Invalid query", [
|
|
14245
|
+
{ path: ["from"], message: "from must not be after to" }
|
|
14246
|
+
]);
|
|
14247
|
+
}
|
|
14248
|
+
try {
|
|
14249
|
+
ctx.body = await run(query);
|
|
14250
|
+
return ctx.body;
|
|
14251
|
+
} catch (error) {
|
|
14252
|
+
log.error(
|
|
14253
|
+
`Admin activity: ${operation} failed`,
|
|
14254
|
+
/** @type {any} */
|
|
14255
|
+
error?.name || "Error"
|
|
14256
|
+
);
|
|
14257
|
+
return sendServerError(ctx, 500, "Admin activity could not be loaded.");
|
|
14258
|
+
}
|
|
14259
|
+
};
|
|
14260
|
+
return {
|
|
14261
|
+
/**
|
|
14262
|
+
* One page of the admin sign-in history: sign-ins, failed attempts,
|
|
14263
|
+
* lockouts and sign-outs, newest first.
|
|
14264
|
+
*
|
|
14265
|
+
* @route GET /magic-sessionmanager/admin-activity/sign-ins
|
|
14266
|
+
* @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
|
|
14267
|
+
* read rate limit.
|
|
14268
|
+
* @param {Context} ctx Reads `ctx.query.adminId` (optional positive integer), `event`
|
|
14269
|
+
* (`all`|`succeeded`|`failed`|`signed-out`), `from`/`to` (ISO dates), `page`, `pageSize`
|
|
14270
|
+
* (1..100, default 20).
|
|
14271
|
+
* @returns {Promise<unknown>} 200 `{ data: SignInRow[], meta: { pagination, recording,
|
|
14272
|
+
* identity } }`; 400 ValidationError with field errors; 500 fixed message. Rows hold IP
|
|
14273
|
+
* address (possibly anonymised), location, browser, OS and session state; never the
|
|
14274
|
+
* device id, a typed email or a token. Admin names are empty without
|
|
14275
|
+
* `admin::users.read` (`meta.identity.names` false).
|
|
14276
|
+
* @sideeffect A read with an admin API token queues a `security-log.read` event.
|
|
14277
|
+
*/
|
|
14278
|
+
async listSignIns(ctx) {
|
|
14279
|
+
return handle(
|
|
14280
|
+
ctx,
|
|
14281
|
+
signInQuerySchema,
|
|
14282
|
+
(query) => {
|
|
14283
|
+
auditTokenRead(ctx, "sign-ins", false);
|
|
14284
|
+
return service().listSignIns(query, viewerOf(ctx));
|
|
14285
|
+
},
|
|
14286
|
+
"sign-ins"
|
|
14287
|
+
);
|
|
14288
|
+
},
|
|
14289
|
+
/**
|
|
14290
|
+
* One page of Content Manager activity, newest first.
|
|
14291
|
+
*
|
|
14292
|
+
* @route GET /magic-sessionmanager/admin-activity/content
|
|
14293
|
+
* @auth Admin JWT or admin API token; admin::hasPermissions access + admin-activity.read;
|
|
14294
|
+
* read rate limit.
|
|
14295
|
+
* @param {Context} ctx Reads `ctx.query.adminId`, `action` (`all` or an action),
|
|
14296
|
+
* `contentType` (uid), `from`/`to`, `page`, `pageSize`.
|
|
14297
|
+
* @returns {Promise<unknown>} 200 `{ data: ActivityRow[], meta: { pagination, recording,
|
|
14298
|
+
* identity, contentTypes, contentManagerAccess? } }`; 400; 500 fixed message. Entry titles
|
|
14299
|
+
* are resolved when read, only for entries the caller may read in the Content Manager.
|
|
14300
|
+
* @sideeffect A read with an admin API token queues a `security-log.read` event.
|
|
14301
|
+
*/
|
|
14302
|
+
async listContentActivity(ctx) {
|
|
14303
|
+
return handle(
|
|
14304
|
+
ctx,
|
|
14305
|
+
activityQuerySchema,
|
|
14306
|
+
(query) => {
|
|
14307
|
+
auditTokenRead(ctx, "content", false);
|
|
14308
|
+
return service().listContentActivity(query, viewerOf(ctx));
|
|
14309
|
+
},
|
|
14310
|
+
"content"
|
|
14311
|
+
);
|
|
14312
|
+
},
|
|
14313
|
+
/**
|
|
14314
|
+
* One export batch (500 rows, keyset cursor) of the sign-in history.
|
|
14315
|
+
*
|
|
14316
|
+
* @route GET /magic-sessionmanager/admin-activity/sign-ins/export
|
|
14317
|
+
* @auth As listSignIns.
|
|
14318
|
+
* @param {Context} ctx Same filters as the list, plus `cursor` from the previous batch.
|
|
14319
|
+
* @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
|
|
14320
|
+
*/
|
|
14321
|
+
async exportSignIns(ctx) {
|
|
14322
|
+
return handle(
|
|
14323
|
+
ctx,
|
|
14324
|
+
signInExportSchema,
|
|
14325
|
+
(query) => {
|
|
14326
|
+
auditTokenRead(ctx, "sign-ins", true);
|
|
14327
|
+
return service().exportBatch("sign-ins", query, query.cursor || null, viewerOf(ctx));
|
|
14328
|
+
},
|
|
14329
|
+
"sign-in export"
|
|
14330
|
+
);
|
|
14331
|
+
},
|
|
14332
|
+
/**
|
|
14333
|
+
* One export batch (500 rows, keyset cursor) of Content Manager activity.
|
|
14334
|
+
*
|
|
14335
|
+
* @route GET /magic-sessionmanager/admin-activity/content/export
|
|
14336
|
+
* @auth As listContentActivity.
|
|
14337
|
+
* @param {Context} ctx Same filters as the list, plus `cursor`.
|
|
14338
|
+
* @returns {Promise<unknown>} 200 `{ data, meta: { nextCursor } }`; 400; 500.
|
|
14339
|
+
*/
|
|
14340
|
+
async exportContentActivity(ctx) {
|
|
14341
|
+
return handle(
|
|
14342
|
+
ctx,
|
|
14343
|
+
activityExportSchema,
|
|
14344
|
+
(query) => {
|
|
14345
|
+
auditTokenRead(ctx, "content", true);
|
|
14346
|
+
return service().exportBatch("content", query, query.cursor || null, viewerOf(ctx));
|
|
14347
|
+
},
|
|
14348
|
+
"activity export"
|
|
14349
|
+
);
|
|
14350
|
+
}
|
|
14351
|
+
};
|
|
14352
|
+
};
|
|
14353
|
+
}
|
|
14354
|
+
});
|
|
14355
|
+
|
|
12772
14356
|
// server/src/controllers/index.js
|
|
12773
14357
|
var require_controllers = __commonJS({
|
|
12774
14358
|
"server/src/controllers/index.js"(exports, module) {
|
|
@@ -12777,11 +14361,13 @@ var require_controllers = __commonJS({
|
|
|
12777
14361
|
var settings = require_settings();
|
|
12778
14362
|
var geoip = require_geoip();
|
|
12779
14363
|
var adminSessions = require_admin_sessions2();
|
|
14364
|
+
var adminActivity = require_admin_activity();
|
|
12780
14365
|
module.exports = {
|
|
12781
14366
|
session,
|
|
12782
14367
|
settings,
|
|
12783
14368
|
geoip,
|
|
12784
|
-
"admin-sessions": adminSessions
|
|
14369
|
+
"admin-sessions": adminSessions,
|
|
14370
|
+
"admin-activity": adminActivity
|
|
12785
14371
|
};
|
|
12786
14372
|
}
|
|
12787
14373
|
});
|
|
@@ -14042,6 +15628,87 @@ var require_session2 = __commonJS({
|
|
|
14042
15628
|
}
|
|
14043
15629
|
});
|
|
14044
15630
|
|
|
15631
|
+
// server/src/utils/special-ip-ranges.js
|
|
15632
|
+
var require_special_ip_ranges = __commonJS({
|
|
15633
|
+
"server/src/utils/special-ip-ranges.js"(exports, module) {
|
|
15634
|
+
"use strict";
|
|
15635
|
+
var net = __require("node:net");
|
|
15636
|
+
var IPV4_SPECIAL = Object.freeze([
|
|
15637
|
+
["0.0.0.0", 8],
|
|
15638
|
+
// "this network"
|
|
15639
|
+
["10.0.0.0", 8],
|
|
15640
|
+
// private (RFC 1918)
|
|
15641
|
+
["100.64.0.0", 10],
|
|
15642
|
+
// shared address space / CGNAT (RFC 6598)
|
|
15643
|
+
["127.0.0.0", 8],
|
|
15644
|
+
// loopback
|
|
15645
|
+
["169.254.0.0", 16],
|
|
15646
|
+
// link-local
|
|
15647
|
+
["172.16.0.0", 12],
|
|
15648
|
+
// private (RFC 1918)
|
|
15649
|
+
["192.0.0.0", 24],
|
|
15650
|
+
// IETF protocol assignments
|
|
15651
|
+
["192.0.2.0", 24],
|
|
15652
|
+
// documentation TEST-NET-1
|
|
15653
|
+
["192.88.99.0", 24],
|
|
15654
|
+
// deprecated 6to4 relay anycast
|
|
15655
|
+
["192.168.0.0", 16],
|
|
15656
|
+
// private (RFC 1918)
|
|
15657
|
+
["198.18.0.0", 15],
|
|
15658
|
+
// benchmarking
|
|
15659
|
+
["198.51.100.0", 24],
|
|
15660
|
+
// documentation TEST-NET-2
|
|
15661
|
+
["203.0.113.0", 24],
|
|
15662
|
+
// documentation TEST-NET-3
|
|
15663
|
+
["224.0.0.0", 4],
|
|
15664
|
+
// multicast
|
|
15665
|
+
["240.0.0.0", 4]
|
|
15666
|
+
// reserved, includes 255.255.255.255
|
|
15667
|
+
]);
|
|
15668
|
+
var IPV6_SPECIAL = Object.freeze([
|
|
15669
|
+
["::", 96],
|
|
15670
|
+
// unspecified, loopback and deprecated IPv4-compatible addresses
|
|
15671
|
+
["64:ff9b:1::", 48],
|
|
15672
|
+
// local-use IPv4/IPv6 translation
|
|
15673
|
+
["100::", 64],
|
|
15674
|
+
// discard-only
|
|
15675
|
+
["100:0:0:1::", 64],
|
|
15676
|
+
// dummy prefix
|
|
15677
|
+
["2001::", 23],
|
|
15678
|
+
// IETF protocol assignments (Teredo, benchmarking, ORCHID)
|
|
15679
|
+
["2001:db8::", 32],
|
|
15680
|
+
// documentation
|
|
15681
|
+
["3fff::", 20],
|
|
15682
|
+
// documentation (RFC 9637)
|
|
15683
|
+
["5f00::", 16],
|
|
15684
|
+
// segment routing SIDs
|
|
15685
|
+
["fc00::", 7],
|
|
15686
|
+
// unique local
|
|
15687
|
+
["fe80::", 10],
|
|
15688
|
+
// link-local
|
|
15689
|
+
["fec0::", 10],
|
|
15690
|
+
// deprecated site-local
|
|
15691
|
+
["ff00::", 8]
|
|
15692
|
+
// multicast
|
|
15693
|
+
]);
|
|
15694
|
+
var blockList = new net.BlockList();
|
|
15695
|
+
for (const [network, prefix] of IPV4_SPECIAL) blockList.addSubnet(network, prefix, "ipv4");
|
|
15696
|
+
for (const [network, prefix] of IPV6_SPECIAL) blockList.addSubnet(network, prefix, "ipv6");
|
|
15697
|
+
function isSpecialPurposeIp(ip) {
|
|
15698
|
+
if (typeof ip !== "string") return true;
|
|
15699
|
+
let value = ip.trim();
|
|
15700
|
+
if (value.startsWith("[") && value.endsWith("]")) value = value.slice(1, -1);
|
|
15701
|
+
const zone = value.indexOf("%");
|
|
15702
|
+
if (zone !== -1) value = value.slice(0, zone);
|
|
15703
|
+
const version = net.isIP(value);
|
|
15704
|
+
if (version === 4) return blockList.check(value, "ipv4");
|
|
15705
|
+
if (version === 6) return blockList.check(value, "ipv6");
|
|
15706
|
+
return true;
|
|
15707
|
+
}
|
|
15708
|
+
module.exports = { IPV4_SPECIAL, IPV6_SPECIAL, isSpecialPurposeIp };
|
|
15709
|
+
}
|
|
15710
|
+
});
|
|
15711
|
+
|
|
14045
15712
|
// server/src/services/geolocation.js
|
|
14046
15713
|
var require_geolocation = __commonJS({
|
|
14047
15714
|
"server/src/services/geolocation.js"(exports, module) {
|
|
@@ -14057,6 +15724,7 @@ var require_geolocation = __commonJS({
|
|
|
14057
15724
|
} = require_geoip_updater();
|
|
14058
15725
|
var { calculateSecurityScore, getRiskLevel, noRiskData } = require_risk_data();
|
|
14059
15726
|
var { lookupRiskData } = require_risk_databases();
|
|
15727
|
+
var { isSpecialPurposeIp } = require_special_ip_ranges();
|
|
14060
15728
|
var GEO_API_TIMEOUT_MS = 4e3;
|
|
14061
15729
|
var IPAPI_SUCCESS_CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
14062
15730
|
var IPAPI_FAILURE_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
@@ -14346,30 +16014,12 @@ var require_geolocation = __commonJS({
|
|
|
14346
16014
|
return parts;
|
|
14347
16015
|
}
|
|
14348
16016
|
function isPrivateIpv4(ip) {
|
|
14349
|
-
|
|
14350
|
-
if (!parts) return false;
|
|
14351
|
-
const [a, b, c] = parts;
|
|
14352
|
-
return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
|
|
14353
|
-
}
|
|
14354
|
-
function getFirstHextet(ip) {
|
|
14355
|
-
const first = ip.split(":")[0];
|
|
14356
|
-
if (!first) return 0;
|
|
14357
|
-
const parsed = Number.parseInt(first, 16);
|
|
14358
|
-
return Number.isNaN(parsed) ? 0 : parsed;
|
|
16017
|
+
return Boolean(parseIpv4(ip)) && isSpecialPurposeIp(ip);
|
|
14359
16018
|
}
|
|
14360
16019
|
function isPrivateIpv6(ip) {
|
|
14361
|
-
|
|
14362
|
-
|
|
14363
|
-
|
|
14364
|
-
} catch {
|
|
14365
|
-
}
|
|
14366
|
-
if (lower === "::" || lower === "::1") return true;
|
|
14367
|
-
if (/^(?:0:){7}0$/.test(lower) || /^(?:0:){7}1$/.test(lower)) return true;
|
|
14368
|
-
if (lower.startsWith("::ffff:")) {
|
|
14369
|
-
return isPrivateIpv4(normalizeLookupIp(lower));
|
|
14370
|
-
}
|
|
14371
|
-
const firstHextet = getFirstHextet(lower);
|
|
14372
|
-
return (firstHextet & 65024) === 64512 || (firstHextet & 65472) === 65152;
|
|
16020
|
+
const mapped = normalizeLookupIp(ip);
|
|
16021
|
+
if (net.isIP(mapped) === 4) return isPrivateIpv4(mapped);
|
|
16022
|
+
return isSpecialPurposeIp(ip);
|
|
14373
16023
|
}
|
|
14374
16024
|
module.exports = ({ strapi: strapi2 }) => ({
|
|
14375
16025
|
/**
|
|
@@ -14433,6 +16083,43 @@ var require_geolocation = __commonJS({
|
|
|
14433
16083
|
}
|
|
14434
16084
|
return this.withRiskData(await this.getIpapiIpInfo(lookupIp), lookupIp);
|
|
14435
16085
|
},
|
|
16086
|
+
/**
|
|
16087
|
+
* Location of a security log event (4.17, security review F1). Stricter
|
|
16088
|
+
* than getIpInfo:
|
|
16089
|
+
* - the caller passes the anonymised address (/24, /48); it is never the
|
|
16090
|
+
* full address of an admin;
|
|
16091
|
+
* - with the provider `auto` (the default) or `local-mmdb` only the local
|
|
16092
|
+
* MMDB file is read; there is no fallback to ipapi.co;
|
|
16093
|
+
* - ipapi.co is used only when the host explicitly chose `ipapi`;
|
|
16094
|
+
* - special-purpose addresses and a disabled lookup return null.
|
|
16095
|
+
*
|
|
16096
|
+
* @param {string} anonymizedIp Anonymised address.
|
|
16097
|
+
* @returns {Promise<{country: string|null, country_code: string|null, city: string|null}|null>}
|
|
16098
|
+
* Location, or null when there is none.
|
|
16099
|
+
* @sideeffect Reads the local MMDB file; with the explicit `ipapi` provider, sends the
|
|
16100
|
+
* anonymised address to ipapi.co.
|
|
16101
|
+
*/
|
|
16102
|
+
async getSecurityLogLocation(anonymizedIp) {
|
|
16103
|
+
const lookupIp = normalizeLookupIp(anonymizedIp);
|
|
16104
|
+
if (!lookupIp || net.isIP(lookupIp) === 0 || this.isPrivateIp(lookupIp)) return null;
|
|
16105
|
+
const settings = await this.getGeoSettings();
|
|
16106
|
+
const provider = normalizeProvider(settings.geoIpProvider);
|
|
16107
|
+
if (settings.enableGeolocation === false || provider === "disabled") return null;
|
|
16108
|
+
let info;
|
|
16109
|
+
if (provider === "ipapi") {
|
|
16110
|
+
info = await this.getIpapiIpInfo(lookupIp);
|
|
16111
|
+
} else {
|
|
16112
|
+
const databasePath = resolveExistingDatabasePath(settings);
|
|
16113
|
+
if (!databasePath || !fs.existsSync(databasePath)) return null;
|
|
16114
|
+
info = await this.getLocalMmdbIpInfo(lookupIp, settings);
|
|
16115
|
+
}
|
|
16116
|
+
if (!info || info._status !== "ok") return null;
|
|
16117
|
+
return {
|
|
16118
|
+
country: info.country || null,
|
|
16119
|
+
country_code: info.country_code || null,
|
|
16120
|
+
city: info.city || null
|
|
16121
|
+
};
|
|
16122
|
+
},
|
|
14436
16123
|
/**
|
|
14437
16124
|
* Adds risk data (VPN, proxy, Tor, hosting) from the local risk databases
|
|
14438
16125
|
* to a location result. Location providers have none; without a risk
|
|
@@ -14694,8 +16381,9 @@ var require_geolocation = __commonJS({
|
|
|
14694
16381
|
return String.fromCodePoint(...codePoints);
|
|
14695
16382
|
},
|
|
14696
16383
|
/**
|
|
14697
|
-
* Returns true for IPs that belong to
|
|
14698
|
-
*
|
|
16384
|
+
* Returns true for IPs that belong to special-purpose ranges (private,
|
|
16385
|
+
* loopback, link-local, CGNAT, documentation, multicast, reserved; see
|
|
16386
|
+
* utils/special-ip-ranges.js).
|
|
14699
16387
|
* @param {string} ip
|
|
14700
16388
|
* @returns {boolean}
|
|
14701
16389
|
*/
|
|
@@ -15213,6 +16901,973 @@ Score: ${geoData.securityScore}/100`,
|
|
|
15213
16901
|
}
|
|
15214
16902
|
});
|
|
15215
16903
|
|
|
16904
|
+
// server/src/services/security-log.js
|
|
16905
|
+
var require_security_log = __commonJS({
|
|
16906
|
+
"server/src/services/security-log.js"(exports, module) {
|
|
16907
|
+
"use strict";
|
|
16908
|
+
var {
|
|
16909
|
+
ACTOR_TYPES,
|
|
16910
|
+
ADMIN_CONTENT_EVENTS,
|
|
16911
|
+
CONTENT_ACTIONS,
|
|
16912
|
+
EVENT_NAME_PATTERN,
|
|
16913
|
+
KEEP_WITHOUT_ACTOR_EVENTS,
|
|
16914
|
+
SECURITY_EVENTS,
|
|
16915
|
+
SIGN_IN_FILTERS,
|
|
16916
|
+
boundMeta,
|
|
16917
|
+
contentEvent,
|
|
16918
|
+
deriveSessionStates,
|
|
16919
|
+
dropRankOf,
|
|
16920
|
+
pickEntryTitle,
|
|
16921
|
+
recordingSwitchOf,
|
|
16922
|
+
safeReason,
|
|
16923
|
+
toIso,
|
|
16924
|
+
toLocation,
|
|
16925
|
+
toObject
|
|
16926
|
+
} = require_security_log_model();
|
|
16927
|
+
var {
|
|
16928
|
+
MAX_USER_AGENT_LENGTH,
|
|
16929
|
+
anonymizeIp,
|
|
16930
|
+
describeUserAgent,
|
|
16931
|
+
hashDeviceId,
|
|
16932
|
+
normalizeIp
|
|
16933
|
+
} = require_admin_request_info();
|
|
16934
|
+
var { resolveSecurityLogSettings } = require_security_log_settings();
|
|
16935
|
+
var { getPluginSettings } = require_settings_loader();
|
|
16936
|
+
var { shouldResolveGeoData } = require_enhance_session();
|
|
16937
|
+
var { createLogger } = require_logger();
|
|
16938
|
+
var EVENT_UID = "plugin::magic-sessionmanager.security-event";
|
|
16939
|
+
var ADMIN_USER_UID = "admin::user";
|
|
16940
|
+
var ADMIN_SESSION_UID = "admin::session";
|
|
16941
|
+
var PERMISSION_UID = "admin::permission";
|
|
16942
|
+
var SUPER_ADMIN_CODE = "strapi-super-admin";
|
|
16943
|
+
var FLUSH_DELAY_MS = 1e3;
|
|
16944
|
+
var FLUSH_BATCH = 200;
|
|
16945
|
+
var MAX_QUEUE = 2e3;
|
|
16946
|
+
var FAILED_WINDOW_MS = 5 * 60 * 1e3;
|
|
16947
|
+
var MAX_FAILED_ROWS_PER_IP = 30;
|
|
16948
|
+
var FAILED_CAP_WINDOW_MS = 60 * 60 * 1e3;
|
|
16949
|
+
var READ_AUDIT_DEDUP_MS = 5 * 60 * 1e3;
|
|
16950
|
+
var VIEW_DEDUP_MS = 10 * 60 * 1e3;
|
|
16951
|
+
var LOCKOUT_DEDUP_MS = 5 * 60 * 1e3;
|
|
16952
|
+
var MAX_DEDUP_KEYS = 2e4;
|
|
16953
|
+
var GEO_LOOKUPS_PER_FLUSH = 20;
|
|
16954
|
+
var MAIN_FIELD_TTL_MS = 5 * 60 * 1e3;
|
|
16955
|
+
var EXPORT_BATCH = 500;
|
|
16956
|
+
var DELETE_BATCH = 1e3;
|
|
16957
|
+
var MAX_DELETE_STEPS = 200;
|
|
16958
|
+
function toId(value) {
|
|
16959
|
+
if (typeof value === "number" && Number.isInteger(value) && value > 0) return String(value);
|
|
16960
|
+
if (typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value)) return value;
|
|
16961
|
+
return null;
|
|
16962
|
+
}
|
|
16963
|
+
function toAdminId(value) {
|
|
16964
|
+
const id = Number(value);
|
|
16965
|
+
return Number.isInteger(id) && id > 0 && id < 1e12 ? id : null;
|
|
16966
|
+
}
|
|
16967
|
+
function adminName(user) {
|
|
16968
|
+
if (!user) return "";
|
|
16969
|
+
const name = [user.firstname, user.lastname].filter((part) => typeof part === "string" && part.trim()).join(" ").trim();
|
|
16970
|
+
return (name || user.username || user.email || "").slice(0, 200);
|
|
16971
|
+
}
|
|
16972
|
+
function pruneDedup(map, now, windowMs) {
|
|
16973
|
+
if (map.size <= MAX_DEDUP_KEYS) return;
|
|
16974
|
+
for (const [key, at] of map) if (now - at >= windowMs) map.delete(key);
|
|
16975
|
+
while (map.size > MAX_DEDUP_KEYS) {
|
|
16976
|
+
const first = map.keys().next().value;
|
|
16977
|
+
if (first === void 0) break;
|
|
16978
|
+
map.delete(first);
|
|
16979
|
+
}
|
|
16980
|
+
}
|
|
16981
|
+
function deviceHashOf(meta) {
|
|
16982
|
+
const value = toObject(meta).deviceHash;
|
|
16983
|
+
return typeof value === "string" ? value : null;
|
|
16984
|
+
}
|
|
16985
|
+
function failedGroupOf(ip, at) {
|
|
16986
|
+
const anonIp = anonymizeIp(normalizeIp(ip));
|
|
16987
|
+
const windowStart = Math.floor(at / FAILED_WINDOW_MS) * FAILED_WINDOW_MS;
|
|
16988
|
+
return { key: `${anonIp || "-"}|${windowStart}`, anonIp, windowStart };
|
|
16989
|
+
}
|
|
16990
|
+
function isUnknownAccountFailure(entry) {
|
|
16991
|
+
return entry.event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED && !toId(entry.actorId) && !toId(entry.targetId) && typeof entry.attemptedEmail !== "string";
|
|
16992
|
+
}
|
|
16993
|
+
module.exports = ({ strapi: strapi2 }) => {
|
|
16994
|
+
const log = createLogger(strapi2);
|
|
16995
|
+
let queue = [];
|
|
16996
|
+
let timer = null;
|
|
16997
|
+
let flushing = null;
|
|
16998
|
+
let stopped = false;
|
|
16999
|
+
let dropped = {};
|
|
17000
|
+
const viewed = /* @__PURE__ */ new Map();
|
|
17001
|
+
const lockouts = /* @__PURE__ */ new Map();
|
|
17002
|
+
const mainFields = /* @__PURE__ */ new Map();
|
|
17003
|
+
const pendingFailed = /* @__PURE__ */ new Map();
|
|
17004
|
+
const storedFailed = /* @__PURE__ */ new Map();
|
|
17005
|
+
const failedRowsPerIp = /* @__PURE__ */ new Map();
|
|
17006
|
+
const readAudits = /* @__PURE__ */ new Map();
|
|
17007
|
+
const events = () => strapi2.db.query(EVENT_UID);
|
|
17008
|
+
const schedule = () => {
|
|
17009
|
+
if (timer || stopped) return;
|
|
17010
|
+
timer = setTimeout(() => {
|
|
17011
|
+
timer = null;
|
|
17012
|
+
service.flush().catch(() => {
|
|
17013
|
+
});
|
|
17014
|
+
}, FLUSH_DELAY_MS);
|
|
17015
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
17016
|
+
};
|
|
17017
|
+
const mainFieldOf = async (uid) => {
|
|
17018
|
+
const now = Date.now();
|
|
17019
|
+
const cachedField = mainFields.get(uid);
|
|
17020
|
+
if (cachedField && now - cachedField.at < MAIN_FIELD_TTL_MS) return cachedField.field;
|
|
17021
|
+
let field;
|
|
17022
|
+
try {
|
|
17023
|
+
const contentTypes = strapi2.plugin("content-manager")?.service("content-types");
|
|
17024
|
+
const configuration = contentTypes ? await contentTypes.findConfiguration({ uid }) : null;
|
|
17025
|
+
const configured = configuration?.settings?.mainField;
|
|
17026
|
+
field = typeof configured === "string" ? configured : null;
|
|
17027
|
+
} catch {
|
|
17028
|
+
field = null;
|
|
17029
|
+
}
|
|
17030
|
+
mainFields.set(uid, { field, at: now });
|
|
17031
|
+
return field;
|
|
17032
|
+
};
|
|
17033
|
+
const loadAdmins = async (ids) => {
|
|
17034
|
+
const unique = [...new Set(ids.map(toAdminId).filter((id) => id !== null))];
|
|
17035
|
+
if (!unique.length) return /* @__PURE__ */ new Map();
|
|
17036
|
+
const rows = await strapi2.db.query(ADMIN_USER_UID).findMany({
|
|
17037
|
+
where: { id: { $in: unique } },
|
|
17038
|
+
select: ["id", "firstname", "lastname", "username", "email"]
|
|
17039
|
+
});
|
|
17040
|
+
return new Map((Array.isArray(rows) ? rows : []).map((row) => [Number(row.id), row]));
|
|
17041
|
+
};
|
|
17042
|
+
const takeFailedRowBudget = (anonIp, at) => {
|
|
17043
|
+
const key = anonIp || "-";
|
|
17044
|
+
const windowStart = Math.floor(at / FAILED_CAP_WINDOW_MS) * FAILED_CAP_WINDOW_MS;
|
|
17045
|
+
const current = failedRowsPerIp.get(key);
|
|
17046
|
+
const state = current && current.windowStart === windowStart ? current : { windowStart, rows: 0 };
|
|
17047
|
+
if (state.rows >= MAX_FAILED_ROWS_PER_IP) return false;
|
|
17048
|
+
state.rows += 1;
|
|
17049
|
+
failedRowsPerIp.set(key, state);
|
|
17050
|
+
if (failedRowsPerIp.size > MAX_DEDUP_KEYS) {
|
|
17051
|
+
for (const [ip, value] of failedRowsPerIp) {
|
|
17052
|
+
if (value.windowStart !== windowStart) failedRowsPerIp.delete(ip);
|
|
17053
|
+
}
|
|
17054
|
+
}
|
|
17055
|
+
return true;
|
|
17056
|
+
};
|
|
17057
|
+
const writeFailedGroups = async (groups, options) => {
|
|
17058
|
+
for (const [key, group] of groups) {
|
|
17059
|
+
const known = storedFailed.get(key);
|
|
17060
|
+
if (known) {
|
|
17061
|
+
const row = await events().findOne({ select: ["id", "meta"], where: { id: known.id } });
|
|
17062
|
+
if (row) {
|
|
17063
|
+
known.count += group.count;
|
|
17064
|
+
const meta = toObject(row.meta);
|
|
17065
|
+
await events().update({
|
|
17066
|
+
where: { id: known.id },
|
|
17067
|
+
data: { meta: boundMeta({ ...meta, count: known.count }) }
|
|
17068
|
+
});
|
|
17069
|
+
continue;
|
|
17070
|
+
}
|
|
17071
|
+
storedFailed.delete(key);
|
|
17072
|
+
}
|
|
17073
|
+
const { entry } = group;
|
|
17074
|
+
const ip = options.storeIp ? group.anonIp : null;
|
|
17075
|
+
const occurredAt = entry.occurredAt || /* @__PURE__ */ new Date();
|
|
17076
|
+
const created = await events().create({
|
|
17077
|
+
data: {
|
|
17078
|
+
event: SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
|
|
17079
|
+
actorType: "admin",
|
|
17080
|
+
actorId: null,
|
|
17081
|
+
targetType: "admin",
|
|
17082
|
+
targetId: null,
|
|
17083
|
+
ip,
|
|
17084
|
+
userAgent: typeof entry.userAgent === "string" && entry.userAgent ? entry.userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null,
|
|
17085
|
+
geo: null,
|
|
17086
|
+
meta: boundMeta({
|
|
17087
|
+
...entry.meta || {},
|
|
17088
|
+
count: group.count,
|
|
17089
|
+
aggregated: true,
|
|
17090
|
+
...ip ? { ipAnonymized: true } : {}
|
|
17091
|
+
}),
|
|
17092
|
+
createdAt: occurredAt,
|
|
17093
|
+
updatedAt: occurredAt
|
|
17094
|
+
}
|
|
17095
|
+
});
|
|
17096
|
+
if (created?.id !== void 0) {
|
|
17097
|
+
storedFailed.set(key, {
|
|
17098
|
+
id: Number(created.id),
|
|
17099
|
+
count: group.count,
|
|
17100
|
+
windowStart: group.windowStart
|
|
17101
|
+
});
|
|
17102
|
+
}
|
|
17103
|
+
}
|
|
17104
|
+
const now = Date.now();
|
|
17105
|
+
for (const [key, value] of storedFailed) {
|
|
17106
|
+
if (now - value.windowStart > 2 * FAILED_WINDOW_MS) storedFailed.delete(key);
|
|
17107
|
+
}
|
|
17108
|
+
};
|
|
17109
|
+
const buildRows = async (batch, options, settings) => {
|
|
17110
|
+
const groups = /* @__PURE__ */ new Map();
|
|
17111
|
+
const wanted = batch.filter((entry) => {
|
|
17112
|
+
const gate = recordingSwitchOf(entry.event);
|
|
17113
|
+
return gate === "always" || (gate === "signIns" ? options.signIns : options.content);
|
|
17114
|
+
});
|
|
17115
|
+
if (!wanted.length) return { rows: [], groups };
|
|
17116
|
+
const emails = [
|
|
17117
|
+
...new Set(
|
|
17118
|
+
wanted.map((entry) => typeof entry.attemptedEmail === "string" ? entry.attemptedEmail : "").filter((email) => email && email.length <= 254).map((email) => email.toLowerCase())
|
|
17119
|
+
)
|
|
17120
|
+
];
|
|
17121
|
+
const byEmail = /* @__PURE__ */ new Map();
|
|
17122
|
+
if (emails.length) {
|
|
17123
|
+
const found = await strapi2.db.query(ADMIN_USER_UID).findMany({
|
|
17124
|
+
where: { email: { $in: emails } },
|
|
17125
|
+
select: ["id", "email"]
|
|
17126
|
+
});
|
|
17127
|
+
for (const row of Array.isArray(found) ? found : []) {
|
|
17128
|
+
byEmail.set(String(row.email).toLowerCase(), Number(row.id));
|
|
17129
|
+
}
|
|
17130
|
+
}
|
|
17131
|
+
const geoService = options.geoLookup && options.storeIp && shouldResolveGeoData(settings) ? strapi2.plugin("magic-sessionmanager").service("geolocation") : null;
|
|
17132
|
+
const geoCache = /* @__PURE__ */ new Map();
|
|
17133
|
+
let geoBudget = GEO_LOOKUPS_PER_FLUSH;
|
|
17134
|
+
const addToGroup = (entry) => {
|
|
17135
|
+
const at = (entry.occurredAt || /* @__PURE__ */ new Date()).getTime();
|
|
17136
|
+
const { key, anonIp, windowStart } = failedGroupOf(entry.ip, at);
|
|
17137
|
+
const group = groups.get(key);
|
|
17138
|
+
const count = Number.isInteger(entry.count) && Number(entry.count) > 0 ? Number(entry.count) : 1;
|
|
17139
|
+
if (group) group.count += count;
|
|
17140
|
+
else groups.set(key, { entry, count, anonIp, windowStart });
|
|
17141
|
+
};
|
|
17142
|
+
const rows = [];
|
|
17143
|
+
for (const entry of wanted) {
|
|
17144
|
+
let targetId = toId(entry.targetId);
|
|
17145
|
+
let actorId = toId(entry.actorId);
|
|
17146
|
+
if (!targetId && typeof entry.attemptedEmail === "string") {
|
|
17147
|
+
const found = byEmail.get(entry.attemptedEmail.toLowerCase());
|
|
17148
|
+
targetId = found ? String(found) : null;
|
|
17149
|
+
if (entry.actorFromEmail && !actorId) actorId = targetId;
|
|
17150
|
+
}
|
|
17151
|
+
const isFailure = entry.event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED || entry.event === SECURITY_EVENTS.ADMIN_LOCKOUT;
|
|
17152
|
+
if (entry.event === SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED && !targetId) {
|
|
17153
|
+
addToGroup(entry);
|
|
17154
|
+
continue;
|
|
17155
|
+
}
|
|
17156
|
+
const at = (entry.occurredAt || /* @__PURE__ */ new Date()).getTime();
|
|
17157
|
+
if (isFailure && !takeFailedRowBudget(anonymizeIp(normalizeIp(entry.ip)), at)) {
|
|
17158
|
+
addToGroup({
|
|
17159
|
+
...entry,
|
|
17160
|
+
event: SECURITY_EVENTS.ADMIN_SIGN_IN_FAILED,
|
|
17161
|
+
meta: { ...entry.meta || {}, reason: "over_limit" }
|
|
17162
|
+
});
|
|
17163
|
+
continue;
|
|
17164
|
+
}
|
|
17165
|
+
const ip = options.storeIp ? normalizeIp(entry.ip) : null;
|
|
17166
|
+
const storedIp = ip && options.anonymizeIp ? anonymizeIp(ip) : ip;
|
|
17167
|
+
const lookupIp = ip ? anonymizeIp(ip) : null;
|
|
17168
|
+
let geo = null;
|
|
17169
|
+
if (lookupIp && geoService) {
|
|
17170
|
+
if (geoCache.has(lookupIp)) {
|
|
17171
|
+
geo = geoCache.get(lookupIp) || null;
|
|
17172
|
+
} else if (geoBudget > 0) {
|
|
17173
|
+
geoBudget -= 1;
|
|
17174
|
+
try {
|
|
17175
|
+
geo = await geoService.getSecurityLogLocation(lookupIp) || null;
|
|
17176
|
+
} catch {
|
|
17177
|
+
geo = null;
|
|
17178
|
+
}
|
|
17179
|
+
geoCache.set(lookupIp, geo);
|
|
17180
|
+
}
|
|
17181
|
+
}
|
|
17182
|
+
const meta = { ...entry.meta || {} };
|
|
17183
|
+
const deviceHash = entry.deviceHash || hashDeviceId(entry.deviceId);
|
|
17184
|
+
if (deviceHash) meta.deviceHash = deviceHash;
|
|
17185
|
+
if (storedIp && options.anonymizeIp) meta.ipAnonymized = true;
|
|
17186
|
+
const socketIp = options.storeIp ? normalizeIp(entry.socketIp) : null;
|
|
17187
|
+
if (ip && socketIp && socketIp !== ip) meta.socketIp = anonymizeIp(socketIp);
|
|
17188
|
+
const occurredAt = entry.occurredAt || /* @__PURE__ */ new Date();
|
|
17189
|
+
rows.push({
|
|
17190
|
+
event: entry.event,
|
|
17191
|
+
actorType: entry.actorType,
|
|
17192
|
+
actorId,
|
|
17193
|
+
targetType: typeof entry.targetType === "string" ? entry.targetType.slice(0, 191) : null,
|
|
17194
|
+
targetId,
|
|
17195
|
+
ip: storedIp,
|
|
17196
|
+
userAgent: typeof entry.userAgent === "string" && entry.userAgent ? entry.userAgent.slice(0, MAX_USER_AGENT_LENGTH) : null,
|
|
17197
|
+
geo,
|
|
17198
|
+
meta: boundMeta(meta),
|
|
17199
|
+
createdAt: occurredAt,
|
|
17200
|
+
updatedAt: occurredAt
|
|
17201
|
+
});
|
|
17202
|
+
}
|
|
17203
|
+
return { rows, groups };
|
|
17204
|
+
};
|
|
17205
|
+
const deleteOlderThan = async (cutoff) => {
|
|
17206
|
+
let deleted = 0;
|
|
17207
|
+
for (let step = 0; step < MAX_DELETE_STEPS; step += 1) {
|
|
17208
|
+
const rows = await events().findMany({
|
|
17209
|
+
select: ["id"],
|
|
17210
|
+
where: { createdAt: { $lt: cutoff } },
|
|
17211
|
+
orderBy: { id: "asc" },
|
|
17212
|
+
limit: DELETE_BATCH
|
|
17213
|
+
});
|
|
17214
|
+
const ids = (Array.isArray(rows) ? rows : []).map((row) => row.id);
|
|
17215
|
+
if (!ids.length) break;
|
|
17216
|
+
const result = await events().deleteMany({ where: { id: { $in: ids } } });
|
|
17217
|
+
deleted += Number(result?.count ?? ids.length);
|
|
17218
|
+
if (ids.length < DELETE_BATCH) break;
|
|
17219
|
+
}
|
|
17220
|
+
return deleted;
|
|
17221
|
+
};
|
|
17222
|
+
const writeQueued = async () => {
|
|
17223
|
+
while (queue.length) {
|
|
17224
|
+
const batch = queue;
|
|
17225
|
+
queue = [];
|
|
17226
|
+
pendingFailed.clear();
|
|
17227
|
+
let settings;
|
|
17228
|
+
try {
|
|
17229
|
+
settings = await getPluginSettings(strapi2);
|
|
17230
|
+
} catch {
|
|
17231
|
+
return;
|
|
17232
|
+
}
|
|
17233
|
+
try {
|
|
17234
|
+
const options = resolveSecurityLogSettings(settings);
|
|
17235
|
+
const { rows, groups } = await buildRows(batch, options, settings);
|
|
17236
|
+
for (let i = 0; i < rows.length; i += FLUSH_BATCH) {
|
|
17237
|
+
await events().createMany({ data: rows.slice(i, i + FLUSH_BATCH) });
|
|
17238
|
+
}
|
|
17239
|
+
await writeFailedGroups(groups, options);
|
|
17240
|
+
} catch (err) {
|
|
17241
|
+
log.warn("[security-log] Events could not be written:", err?.name || "Error");
|
|
17242
|
+
}
|
|
17243
|
+
}
|
|
17244
|
+
const families = Object.entries(dropped).filter(([, n]) => n > 0);
|
|
17245
|
+
if (families.length) {
|
|
17246
|
+
log.warn(
|
|
17247
|
+
`[security-log] Queue full, events dropped: ${families.map(([family, n]) => `${family}=${n}`).join(", ")}`
|
|
17248
|
+
);
|
|
17249
|
+
dropped = {};
|
|
17250
|
+
}
|
|
17251
|
+
};
|
|
17252
|
+
const dropOne = () => {
|
|
17253
|
+
let index = -1;
|
|
17254
|
+
let lowest = 4;
|
|
17255
|
+
for (let i = 0; i < queue.length; i += 1) {
|
|
17256
|
+
const { rank } = dropRankOf(queue[i].event);
|
|
17257
|
+
if (rank < lowest) {
|
|
17258
|
+
lowest = rank;
|
|
17259
|
+
index = i;
|
|
17260
|
+
if (rank === 0) break;
|
|
17261
|
+
}
|
|
17262
|
+
}
|
|
17263
|
+
if (index === -1) return;
|
|
17264
|
+
const [removed] = queue.splice(index, 1);
|
|
17265
|
+
const { family } = dropRankOf(removed.event);
|
|
17266
|
+
const weight = Number.isInteger(removed.count) && Number(removed.count) > 0 ? Number(removed.count) : 1;
|
|
17267
|
+
dropped[family] = (dropped[family] || 0) + weight;
|
|
17268
|
+
for (const [key, value] of pendingFailed) if (value === removed) pendingFailed.delete(key);
|
|
17269
|
+
};
|
|
17270
|
+
const service = {
|
|
17271
|
+
/**
|
|
17272
|
+
* Queues one security event. Returns at once; nothing is awaited.
|
|
17273
|
+
* Unknown event names or actor types are ignored.
|
|
17274
|
+
*
|
|
17275
|
+
* @param {SecurityEventInput} input Event.
|
|
17276
|
+
* @returns {boolean} Whether the event was queued.
|
|
17277
|
+
* @sideeffect Adds to the in-memory queue; the flush stores it when its switch is on.
|
|
17278
|
+
*/
|
|
17279
|
+
record(input) {
|
|
17280
|
+
if (stopped || !input || typeof input.event !== "string") return false;
|
|
17281
|
+
if (!EVENT_NAME_PATTERN.test(input.event) || !ACTOR_TYPES.includes(input.actorType)) {
|
|
17282
|
+
return false;
|
|
17283
|
+
}
|
|
17284
|
+
const now = Date.now();
|
|
17285
|
+
if (input.event === SECURITY_EVENTS.ADMIN_LOCKOUT) {
|
|
17286
|
+
const who = String(input.attemptedEmail || input.targetId || "").toLowerCase();
|
|
17287
|
+
const key = `${who}|${input.ip || ""}`;
|
|
17288
|
+
const last = lockouts.get(key);
|
|
17289
|
+
if (last !== void 0 && now - last < LOCKOUT_DEDUP_MS) return false;
|
|
17290
|
+
lockouts.set(key, now);
|
|
17291
|
+
pruneDedup(lockouts, now, LOCKOUT_DEDUP_MS);
|
|
17292
|
+
}
|
|
17293
|
+
const entry = { ...input, occurredAt: input.occurredAt || new Date(now) };
|
|
17294
|
+
if (typeof entry.userAgent === "string") {
|
|
17295
|
+
entry.userAgent = entry.userAgent.slice(0, MAX_USER_AGENT_LENGTH);
|
|
17296
|
+
}
|
|
17297
|
+
if (isUnknownAccountFailure(entry)) {
|
|
17298
|
+
const { key } = failedGroupOf(entry.ip, now);
|
|
17299
|
+
const pending = pendingFailed.get(key);
|
|
17300
|
+
if (pending) {
|
|
17301
|
+
pending.count = (pending.count || 1) + 1;
|
|
17302
|
+
schedule();
|
|
17303
|
+
return true;
|
|
17304
|
+
}
|
|
17305
|
+
entry.aggregate = true;
|
|
17306
|
+
entry.count = 1;
|
|
17307
|
+
pendingFailed.set(key, entry);
|
|
17308
|
+
if (pendingFailed.size > MAX_DEDUP_KEYS) pendingFailed.clear();
|
|
17309
|
+
}
|
|
17310
|
+
queue.push(entry);
|
|
17311
|
+
while (queue.length > MAX_QUEUE) dropOne();
|
|
17312
|
+
schedule();
|
|
17313
|
+
return true;
|
|
17314
|
+
},
|
|
17315
|
+
/**
|
|
17316
|
+
* Records that an admin API token read the security log (4.17): one
|
|
17317
|
+
* `security-log.read` event per token and list within 5 minutes. Reads
|
|
17318
|
+
* from the admin panel (a person) are not recorded.
|
|
17319
|
+
*
|
|
17320
|
+
* @param {{adminId: unknown, tokenId: unknown, list: 'sign-ins'|'content',
|
|
17321
|
+
* exported: boolean}} input Who read what.
|
|
17322
|
+
* @returns {boolean} Whether an event was queued.
|
|
17323
|
+
* @sideeffect Queues one always-on security event.
|
|
17324
|
+
*/
|
|
17325
|
+
recordTokenRead(input) {
|
|
17326
|
+
const now = Date.now();
|
|
17327
|
+
const tokenId = toId(input?.tokenId);
|
|
17328
|
+
const key = `${tokenId || "-"}|${input?.list}|${input?.exported ? "export" : "list"}`;
|
|
17329
|
+
const last = readAudits.get(key);
|
|
17330
|
+
if (last !== void 0 && now - last < READ_AUDIT_DEDUP_MS) return false;
|
|
17331
|
+
readAudits.set(key, now);
|
|
17332
|
+
pruneDedup(readAudits, now, READ_AUDIT_DEDUP_MS);
|
|
17333
|
+
return service.record({
|
|
17334
|
+
event: SECURITY_EVENTS.LOG_READ,
|
|
17335
|
+
actorType: "admin",
|
|
17336
|
+
actorId: (
|
|
17337
|
+
/** @type {any} */
|
|
17338
|
+
input?.adminId ?? null
|
|
17339
|
+
),
|
|
17340
|
+
targetType: "security-log",
|
|
17341
|
+
targetId: null,
|
|
17342
|
+
meta: {
|
|
17343
|
+
list: input?.list === "content" ? "content" : "sign-ins",
|
|
17344
|
+
exported: input?.exported === true,
|
|
17345
|
+
via: "admin-token",
|
|
17346
|
+
...tokenId ? { tokenId } : {}
|
|
17347
|
+
}
|
|
17348
|
+
});
|
|
17349
|
+
},
|
|
17350
|
+
/**
|
|
17351
|
+
* Queues one Content Manager action of an admin as
|
|
17352
|
+
* `admin.content.<action>` with the entry as target (`targetType` = content
|
|
17353
|
+
* type uid, `targetId` = document id). Opening the same entry (same
|
|
17354
|
+
* admin, type, document and locale) again within 10 minutes, or right
|
|
17355
|
+
* after writing it, is not a new "view".
|
|
17356
|
+
*
|
|
17357
|
+
* Only the type uid, document id, locale and (bulk) count are queued;
|
|
17358
|
+
* the entry itself never is (4.17).
|
|
17359
|
+
*
|
|
17360
|
+
* @param {{adminUserId: number|string, action: string, kind: 'collection'|'single',
|
|
17361
|
+
* contentType: string, documentId: string|null, locale: string|null,
|
|
17362
|
+
* count: number|null}} input Action.
|
|
17363
|
+
* @returns {boolean} Whether the action was queued.
|
|
17364
|
+
*/
|
|
17365
|
+
recordContentAction(input) {
|
|
17366
|
+
if (stopped || !input || !CONTENT_ACTIONS.includes(input.action)) return false;
|
|
17367
|
+
const now = Date.now();
|
|
17368
|
+
const key = `${input.adminUserId}|${input.contentType}|${input.documentId || ""}|${input.locale || ""}`;
|
|
17369
|
+
if (input.documentId || input.kind === "single") {
|
|
17370
|
+
if (input.action === "view") {
|
|
17371
|
+
const last = viewed.get(key);
|
|
17372
|
+
if (last !== void 0 && now - last < VIEW_DEDUP_MS) return false;
|
|
17373
|
+
}
|
|
17374
|
+
viewed.delete(key);
|
|
17375
|
+
viewed.set(key, now);
|
|
17376
|
+
pruneDedup(viewed, now, VIEW_DEDUP_MS);
|
|
17377
|
+
}
|
|
17378
|
+
return service.record({
|
|
17379
|
+
event: contentEvent(input.action),
|
|
17380
|
+
actorType: "admin",
|
|
17381
|
+
actorId: input.adminUserId,
|
|
17382
|
+
targetType: input.contentType,
|
|
17383
|
+
targetId: input.documentId,
|
|
17384
|
+
meta: {
|
|
17385
|
+
kind: input.kind,
|
|
17386
|
+
locale: input.locale || null,
|
|
17387
|
+
...typeof input.count === "number" ? { count: input.count } : {}
|
|
17388
|
+
}
|
|
17389
|
+
});
|
|
17390
|
+
},
|
|
17391
|
+
/**
|
|
17392
|
+
* Writes everything queued. Concurrent calls share one run.
|
|
17393
|
+
*
|
|
17394
|
+
* @returns {Promise<void>}
|
|
17395
|
+
* @sideeffect Inserts rows into the security event table; may call the GeoIP provider.
|
|
17396
|
+
*/
|
|
17397
|
+
async flush() {
|
|
17398
|
+
if (flushing) return flushing;
|
|
17399
|
+
if (!queue.length) return void 0;
|
|
17400
|
+
flushing = writeQueued().finally(() => {
|
|
17401
|
+
flushing = null;
|
|
17402
|
+
});
|
|
17403
|
+
return flushing;
|
|
17404
|
+
},
|
|
17405
|
+
/**
|
|
17406
|
+
* Stops recording and writes what is queued (plugin destroy).
|
|
17407
|
+
*
|
|
17408
|
+
* @returns {Promise<void>}
|
|
17409
|
+
*/
|
|
17410
|
+
async stop() {
|
|
17411
|
+
stopped = true;
|
|
17412
|
+
if (timer) clearTimeout(timer);
|
|
17413
|
+
timer = null;
|
|
17414
|
+
await service.flush().catch(() => {
|
|
17415
|
+
});
|
|
17416
|
+
},
|
|
17417
|
+
/** @returns {boolean} Whether recording was stopped. */
|
|
17418
|
+
isStopped() {
|
|
17419
|
+
return stopped;
|
|
17420
|
+
},
|
|
17421
|
+
/**
|
|
17422
|
+
* One page of the admin sign-in history, newest first, with names of the
|
|
17423
|
+
* admins involved and the session state of each sign-in.
|
|
17424
|
+
*
|
|
17425
|
+
* @param {{adminId?: number, event?: keyof typeof SIGN_IN_FILTERS, from?: Date|null,
|
|
17426
|
+
* to?: Date|null, page: number, pageSize: number}} query Parsed filters.
|
|
17427
|
+
* @param {Viewer} [viewer] Reader (admin names need `admin::users.read`).
|
|
17428
|
+
* @returns {Promise<{data: object[], meta: object}>} Response body.
|
|
17429
|
+
*/
|
|
17430
|
+
async listSignIns(query, viewer = {}) {
|
|
17431
|
+
const where = signInWhere(query);
|
|
17432
|
+
const [total, rows] = await Promise.all([
|
|
17433
|
+
events().count({ where }),
|
|
17434
|
+
events().findMany({
|
|
17435
|
+
where,
|
|
17436
|
+
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
17437
|
+
offset: (query.page - 1) * query.pageSize,
|
|
17438
|
+
limit: query.pageSize
|
|
17439
|
+
})
|
|
17440
|
+
]);
|
|
17441
|
+
return {
|
|
17442
|
+
data: await shapeSignIns(Array.isArray(rows) ? rows : [], viewer),
|
|
17443
|
+
meta: {
|
|
17444
|
+
pagination: paginationOf(query, total),
|
|
17445
|
+
recording: await recordingFlags(),
|
|
17446
|
+
identity: { names: viewer.canReadAdmins === true }
|
|
17447
|
+
}
|
|
17448
|
+
};
|
|
17449
|
+
},
|
|
17450
|
+
/**
|
|
17451
|
+
* One page of Content Manager activity, newest first.
|
|
17452
|
+
*
|
|
17453
|
+
* @param {{adminId?: number, action?: string, contentType?: string, from?: Date|null,
|
|
17454
|
+
* to?: Date|null, page: number, pageSize: number}} query Parsed filters.
|
|
17455
|
+
* @param {Viewer} [viewer] Reader (titles need Content Manager read access to the entry and
|
|
17456
|
+
* its main field; admin names need `admin::users.read`).
|
|
17457
|
+
* @returns {Promise<{data: object[], meta: object}>} Response body.
|
|
17458
|
+
*/
|
|
17459
|
+
async listContentActivity(query, viewer = {}) {
|
|
17460
|
+
const where = activityWhere(query);
|
|
17461
|
+
const [total, rows] = await Promise.all([
|
|
17462
|
+
events().count({ where }),
|
|
17463
|
+
events().findMany({
|
|
17464
|
+
where,
|
|
17465
|
+
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
|
|
17466
|
+
offset: (query.page - 1) * query.pageSize,
|
|
17467
|
+
limit: query.pageSize
|
|
17468
|
+
})
|
|
17469
|
+
]);
|
|
17470
|
+
return {
|
|
17471
|
+
data: await shapeActivity(Array.isArray(rows) ? rows : [], viewer),
|
|
17472
|
+
meta: {
|
|
17473
|
+
pagination: paginationOf(query, total),
|
|
17474
|
+
recording: await recordingFlags(),
|
|
17475
|
+
identity: { names: viewer.canReadAdmins === true },
|
|
17476
|
+
contentTypes: listContentTypes(),
|
|
17477
|
+
...query.adminId ? { contentManagerAccess: await service.hasContentManagerAccess(query.adminId) } : {}
|
|
17478
|
+
}
|
|
17479
|
+
};
|
|
17480
|
+
},
|
|
17481
|
+
/**
|
|
17482
|
+
* One export batch (newest first, keyset on id) of either list.
|
|
17483
|
+
*
|
|
17484
|
+
* @param {'sign-ins'|'content'} kind List.
|
|
17485
|
+
* @param {any} query Parsed filters (as for the list).
|
|
17486
|
+
* @param {number|null} cursor Id below which to continue.
|
|
17487
|
+
* @param {Viewer} [viewer] Reader; the same title and name rules as the lists.
|
|
17488
|
+
* @returns {Promise<{data: object[], meta: {nextCursor: string|null}}>} Batch.
|
|
17489
|
+
*/
|
|
17490
|
+
async exportBatch(kind, query, cursor, viewer = {}) {
|
|
17491
|
+
const base = kind === "sign-ins" ? signInWhere(query) : activityWhere(query);
|
|
17492
|
+
const where = cursor ? { $and: [base, { id: { $lt: cursor } }] } : base;
|
|
17493
|
+
const rows = await events().findMany({
|
|
17494
|
+
where,
|
|
17495
|
+
orderBy: [{ id: "desc" }],
|
|
17496
|
+
limit: EXPORT_BATCH
|
|
17497
|
+
});
|
|
17498
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
17499
|
+
const data = kind === "sign-ins" ? await shapeSignIns(list, viewer) : await shapeActivity(list, viewer);
|
|
17500
|
+
const last = list[list.length - 1];
|
|
17501
|
+
return {
|
|
17502
|
+
data,
|
|
17503
|
+
meta: { nextCursor: list.length === EXPORT_BATCH && last ? String(last.id) : null }
|
|
17504
|
+
};
|
|
17505
|
+
},
|
|
17506
|
+
/**
|
|
17507
|
+
* Whether an admin can use the Content Manager: Super Admin, or a role
|
|
17508
|
+
* with any `plugin::content-manager.explorer.*` permission.
|
|
17509
|
+
*
|
|
17510
|
+
* @param {number} adminId Admin id.
|
|
17511
|
+
* @returns {Promise<boolean|null>} Null when the admin does not exist.
|
|
17512
|
+
*/
|
|
17513
|
+
async hasContentManagerAccess(adminId) {
|
|
17514
|
+
const user = await strapi2.db.query(ADMIN_USER_UID).findOne({
|
|
17515
|
+
where: { id: adminId },
|
|
17516
|
+
select: ["id"],
|
|
17517
|
+
populate: { roles: { select: ["id", "code"] } }
|
|
17518
|
+
});
|
|
17519
|
+
if (!user) return null;
|
|
17520
|
+
const roles = Array.isArray(user.roles) ? user.roles : [];
|
|
17521
|
+
if (roles.some((role) => role?.code === SUPER_ADMIN_CODE)) return true;
|
|
17522
|
+
const roleIds = roles.map((role) => role.id).filter((id) => id !== void 0);
|
|
17523
|
+
if (!roleIds.length) return false;
|
|
17524
|
+
const count = await strapi2.db.query(PERMISSION_UID).count({
|
|
17525
|
+
where: {
|
|
17526
|
+
role: { id: { $in: roleIds } },
|
|
17527
|
+
action: { $startsWith: "plugin::content-manager.explorer." }
|
|
17528
|
+
}
|
|
17529
|
+
});
|
|
17530
|
+
return Number(count) > 0;
|
|
17531
|
+
},
|
|
17532
|
+
/**
|
|
17533
|
+
* Retention for the whole log: deletes events older than the configured
|
|
17534
|
+
* number of days, and the events of admins that no longer exist (where a
|
|
17535
|
+
* deleted admin signed someone else out, only the actor is cleared).
|
|
17536
|
+
*
|
|
17537
|
+
* A run that deleted rows queues an always-on
|
|
17538
|
+
* `security-log.retention.purged` event with the counts (4.17).
|
|
17539
|
+
*
|
|
17540
|
+
* @param {{now?: Date}} [options] Clock for tests.
|
|
17541
|
+
* @returns {Promise<{expired: number, orphans: number}>} Deleted rows.
|
|
17542
|
+
* @sideeffect Deletes and updates rows of the security event table; queues one event.
|
|
17543
|
+
*/
|
|
17544
|
+
async cleanup({ now = /* @__PURE__ */ new Date() } = {}) {
|
|
17545
|
+
const options = resolveSecurityLogSettings(await getPluginSettings(strapi2));
|
|
17546
|
+
const cutoff = new Date(now.getTime() - options.retentionDays * 24 * 60 * 60 * 1e3);
|
|
17547
|
+
const expired = await deleteOlderThan(cutoff);
|
|
17548
|
+
const admins = await strapi2.db.query(ADMIN_USER_UID).findMany({ select: ["id"] });
|
|
17549
|
+
const existing = (Array.isArray(admins) ? admins : []).map((row) => String(row.id));
|
|
17550
|
+
let orphans = 0;
|
|
17551
|
+
if (existing.length) {
|
|
17552
|
+
const removed = await events().deleteMany({
|
|
17553
|
+
where: {
|
|
17554
|
+
$or: [
|
|
17555
|
+
{ targetType: "admin", targetId: { $notNull: true, $notIn: existing } },
|
|
17556
|
+
{
|
|
17557
|
+
actorType: "admin",
|
|
17558
|
+
actorId: { $notNull: true, $notIn: existing },
|
|
17559
|
+
event: { $notIn: [...KEEP_WITHOUT_ACTOR_EVENTS] }
|
|
17560
|
+
}
|
|
17561
|
+
]
|
|
17562
|
+
}
|
|
17563
|
+
});
|
|
17564
|
+
orphans = Number(removed?.count || 0);
|
|
17565
|
+
await events().updateMany({
|
|
17566
|
+
where: {
|
|
17567
|
+
event: { $in: [...KEEP_WITHOUT_ACTOR_EVENTS] },
|
|
17568
|
+
actorType: "admin",
|
|
17569
|
+
actorId: { $notNull: true, $notIn: existing }
|
|
17570
|
+
},
|
|
17571
|
+
data: { actorId: null }
|
|
17572
|
+
});
|
|
17573
|
+
}
|
|
17574
|
+
if (expired + orphans > 0) {
|
|
17575
|
+
service.record({
|
|
17576
|
+
event: SECURITY_EVENTS.LOG_RETENTION_PURGED,
|
|
17577
|
+
actorType: "system",
|
|
17578
|
+
targetType: "security-log",
|
|
17579
|
+
meta: {
|
|
17580
|
+
count: expired + orphans,
|
|
17581
|
+
expired,
|
|
17582
|
+
orphans,
|
|
17583
|
+
retentionDays: options.retentionDays
|
|
17584
|
+
}
|
|
17585
|
+
});
|
|
17586
|
+
}
|
|
17587
|
+
return { expired, orphans };
|
|
17588
|
+
},
|
|
17589
|
+
/**
|
|
17590
|
+
* Deletes what was recorded about an admin whose account was deleted:
|
|
17591
|
+
* events they did and events about their account. Where they signed
|
|
17592
|
+
* someone else out, changed settings or read the log with a token, the
|
|
17593
|
+
* actor reference is cleared and the event stays.
|
|
17594
|
+
*
|
|
17595
|
+
* @param {number} adminId Deleted admin id.
|
|
17596
|
+
* @returns {Promise<void>}
|
|
17597
|
+
* @sideeffect Deletes and updates rows of the security event table.
|
|
17598
|
+
*/
|
|
17599
|
+
async deleteAdminData(adminId) {
|
|
17600
|
+
const id = toAdminId(adminId);
|
|
17601
|
+
if (!id) return;
|
|
17602
|
+
const key = String(id);
|
|
17603
|
+
queue = queue.filter(
|
|
17604
|
+
(entry) => !(entry.actorType === "admin" && String(entry.actorId) === key) && !(entry.targetType === "admin" && String(entry.targetId) === key)
|
|
17605
|
+
);
|
|
17606
|
+
await events().deleteMany({
|
|
17607
|
+
where: {
|
|
17608
|
+
$or: [
|
|
17609
|
+
{ targetType: "admin", targetId: key },
|
|
17610
|
+
{
|
|
17611
|
+
actorType: "admin",
|
|
17612
|
+
actorId: key,
|
|
17613
|
+
event: { $notIn: [...KEEP_WITHOUT_ACTOR_EVENTS] }
|
|
17614
|
+
}
|
|
17615
|
+
]
|
|
17616
|
+
}
|
|
17617
|
+
});
|
|
17618
|
+
await events().updateMany({
|
|
17619
|
+
where: { event: { $in: [...KEEP_WITHOUT_ACTOR_EVENTS] }, actorType: "admin", actorId: key },
|
|
17620
|
+
data: { actorId: null }
|
|
17621
|
+
});
|
|
17622
|
+
}
|
|
17623
|
+
};
|
|
17624
|
+
function paginationOf(query, total) {
|
|
17625
|
+
const count = Number(total) || 0;
|
|
17626
|
+
return {
|
|
17627
|
+
page: query.page,
|
|
17628
|
+
pageSize: query.pageSize,
|
|
17629
|
+
total: count,
|
|
17630
|
+
pageCount: Math.max(1, Math.ceil(count / query.pageSize))
|
|
17631
|
+
};
|
|
17632
|
+
}
|
|
17633
|
+
function signInWhere(query) {
|
|
17634
|
+
const conditions = [{ event: { $in: [...SIGN_IN_FILTERS[query.event || "all"]] } }];
|
|
17635
|
+
if (query.adminId) conditions.push({ targetType: "admin", targetId: String(query.adminId) });
|
|
17636
|
+
if (query.from) conditions.push({ createdAt: { $gte: query.from } });
|
|
17637
|
+
if (query.to) conditions.push({ createdAt: { $lte: query.to } });
|
|
17638
|
+
return { $and: conditions };
|
|
17639
|
+
}
|
|
17640
|
+
function activityWhere(query) {
|
|
17641
|
+
const conditions = [
|
|
17642
|
+
{
|
|
17643
|
+
event: query.action && query.action !== "all" ? contentEvent(query.action) : { $in: [...ADMIN_CONTENT_EVENTS] }
|
|
17644
|
+
}
|
|
17645
|
+
];
|
|
17646
|
+
if (query.adminId) conditions.push({ actorType: "admin", actorId: String(query.adminId) });
|
|
17647
|
+
if (query.contentType) conditions.push({ targetType: query.contentType });
|
|
17648
|
+
if (query.from) conditions.push({ createdAt: { $gte: query.from } });
|
|
17649
|
+
if (query.to) conditions.push({ createdAt: { $lte: query.to } });
|
|
17650
|
+
return { $and: conditions };
|
|
17651
|
+
}
|
|
17652
|
+
async function recordingFlags() {
|
|
17653
|
+
let settings;
|
|
17654
|
+
try {
|
|
17655
|
+
settings = await getPluginSettings(strapi2);
|
|
17656
|
+
} catch {
|
|
17657
|
+
settings = {};
|
|
17658
|
+
}
|
|
17659
|
+
const options = resolveSecurityLogSettings(settings);
|
|
17660
|
+
return {
|
|
17661
|
+
signIns: options.signIns,
|
|
17662
|
+
contentActivity: options.content,
|
|
17663
|
+
ipAddresses: options.storeIp,
|
|
17664
|
+
anonymizeIp: options.anonymizeIp,
|
|
17665
|
+
retentionDays: options.retentionDays
|
|
17666
|
+
};
|
|
17667
|
+
}
|
|
17668
|
+
function listContentTypes() {
|
|
17669
|
+
return Object.entries(strapi2.contentTypes || {}).filter(([uid, type]) => {
|
|
17670
|
+
const visible = (
|
|
17671
|
+
/** @type {any} */
|
|
17672
|
+
type?.pluginOptions?.["content-manager"]?.visible
|
|
17673
|
+
);
|
|
17674
|
+
return uid.startsWith("api::") && visible !== false;
|
|
17675
|
+
}).map(([uid, type]) => ({
|
|
17676
|
+
uid,
|
|
17677
|
+
name: String(
|
|
17678
|
+
/** @type {any} */
|
|
17679
|
+
type?.info?.displayName || uid
|
|
17680
|
+
).slice(0, 120),
|
|
17681
|
+
kind: (
|
|
17682
|
+
/** @type {any} */
|
|
17683
|
+
type?.kind === "singleType" ? "single" : "collection"
|
|
17684
|
+
)
|
|
17685
|
+
})).sort((a, b) => a.name.localeCompare(b.name));
|
|
17686
|
+
}
|
|
17687
|
+
async function shapeSignIns(rows, viewer) {
|
|
17688
|
+
const admins = await loadAdmins(rows.flatMap((row) => [row.targetId, row.actorId]));
|
|
17689
|
+
const nameOf = (user) => viewer.canReadAdmins === true ? adminName(user) : "";
|
|
17690
|
+
const states = await sessionStates(rows);
|
|
17691
|
+
return rows.map((row) => {
|
|
17692
|
+
const meta = toObject(row.meta);
|
|
17693
|
+
const admin = row.targetType === "admin" ? admins.get(Number(row.targetId)) : void 0;
|
|
17694
|
+
const revoked = row.event === SECURITY_EVENTS.ADMIN_SESSION_REVOKED;
|
|
17695
|
+
const actor = revoked ? admins.get(Number(row.actorId)) : void 0;
|
|
17696
|
+
const described = describeUserAgent(row.userAgent || null);
|
|
17697
|
+
const state = states.get(Number(row.id));
|
|
17698
|
+
return {
|
|
17699
|
+
id: Number(row.id),
|
|
17700
|
+
event: row.event,
|
|
17701
|
+
reason: safeReason(meta.reason),
|
|
17702
|
+
provider: safeReason(meta.provider),
|
|
17703
|
+
// Failed sign-ins of unknown accounts are counted per address and 5 minutes (4.17).
|
|
17704
|
+
attempts: meta.aggregated === true && typeof meta.count === "number" ? meta.count : null,
|
|
17705
|
+
scope: revoked ? safeReason(meta.scope) : null,
|
|
17706
|
+
at: toIso(row.createdAt),
|
|
17707
|
+
ipAddress: row.ip || null,
|
|
17708
|
+
ipAnonymized: meta.ipAnonymized === true,
|
|
17709
|
+
location: toLocation(row.geo),
|
|
17710
|
+
browser: described.browserName,
|
|
17711
|
+
os: described.osName,
|
|
17712
|
+
deviceType: described.deviceType,
|
|
17713
|
+
admin: admin ? { id: Number(admin.id), name: nameOf(admin) } : null,
|
|
17714
|
+
actor: actor ? { id: Number(actor.id), name: nameOf(actor) } : null,
|
|
17715
|
+
session: row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && state ? { state: state.state, endedAt: toIso(state.endedAt) } : null
|
|
17716
|
+
};
|
|
17717
|
+
});
|
|
17718
|
+
}
|
|
17719
|
+
async function sessionStates(rows) {
|
|
17720
|
+
const list = rows.filter(
|
|
17721
|
+
(row) => row.event === SECURITY_EVENTS.ADMIN_SIGN_IN && toAdminId(row.targetId)
|
|
17722
|
+
);
|
|
17723
|
+
if (!list.length) return /* @__PURE__ */ new Map();
|
|
17724
|
+
const adminIds = [...new Set(list.map((row) => String(row.targetId)))];
|
|
17725
|
+
const oldest = new Date(
|
|
17726
|
+
Math.min(...list.map((row) => new Date(toIso(row.createdAt) || Date.now()).getTime()))
|
|
17727
|
+
);
|
|
17728
|
+
const later = await events().findMany({
|
|
17729
|
+
select: ["id", "event", "targetId", "actorId", "meta", "createdAt"],
|
|
17730
|
+
where: {
|
|
17731
|
+
targetType: "admin",
|
|
17732
|
+
targetId: { $in: adminIds },
|
|
17733
|
+
event: {
|
|
17734
|
+
$in: [
|
|
17735
|
+
SECURITY_EVENTS.ADMIN_SIGN_IN,
|
|
17736
|
+
SECURITY_EVENTS.ADMIN_SIGN_OUT,
|
|
17737
|
+
SECURITY_EVENTS.ADMIN_SESSION_REVOKED
|
|
17738
|
+
]
|
|
17739
|
+
},
|
|
17740
|
+
createdAt: { $gte: oldest }
|
|
17741
|
+
},
|
|
17742
|
+
orderBy: [{ createdAt: "asc" }],
|
|
17743
|
+
limit: 5e3
|
|
17744
|
+
});
|
|
17745
|
+
const live = /* @__PURE__ */ new Map();
|
|
17746
|
+
if (strapi2.contentTypes?.[ADMIN_SESSION_UID]) {
|
|
17747
|
+
const now = /* @__PURE__ */ new Date();
|
|
17748
|
+
const sessions = await strapi2.db.query(ADMIN_SESSION_UID).findMany({
|
|
17749
|
+
select: ["userId", "deviceId"],
|
|
17750
|
+
where: {
|
|
17751
|
+
origin: "admin",
|
|
17752
|
+
status: "active",
|
|
17753
|
+
userId: { $in: adminIds },
|
|
17754
|
+
expiresAt: { $gt: now },
|
|
17755
|
+
$or: [{ absoluteExpiresAt: { $null: true } }, { absoluteExpiresAt: { $gt: now } }]
|
|
17756
|
+
},
|
|
17757
|
+
limit: 1e4
|
|
17758
|
+
});
|
|
17759
|
+
for (const session of Array.isArray(sessions) ? sessions : []) {
|
|
17760
|
+
const hash = hashDeviceId(session.deviceId);
|
|
17761
|
+
if (!hash) continue;
|
|
17762
|
+
const key = String(session.userId);
|
|
17763
|
+
if (!live.has(key)) live.set(key, /* @__PURE__ */ new Set());
|
|
17764
|
+
live.get(key)?.add(hash);
|
|
17765
|
+
}
|
|
17766
|
+
}
|
|
17767
|
+
const toEvent = (row) => ({
|
|
17768
|
+
id: Number(row.id),
|
|
17769
|
+
adminId: String(row.targetId),
|
|
17770
|
+
event: row.event,
|
|
17771
|
+
actorId: row.actorId ? String(row.actorId) : null,
|
|
17772
|
+
deviceHash: deviceHashOf(row.meta),
|
|
17773
|
+
at: toIso(row.createdAt) || ""
|
|
17774
|
+
});
|
|
17775
|
+
return deriveSessionStates(
|
|
17776
|
+
list.map(toEvent),
|
|
17777
|
+
(Array.isArray(later) ? later : []).map(toEvent),
|
|
17778
|
+
live
|
|
17779
|
+
);
|
|
17780
|
+
}
|
|
17781
|
+
async function resolveTitles(rows, ability) {
|
|
17782
|
+
const titles = /* @__PURE__ */ new Map();
|
|
17783
|
+
if (!ability) return titles;
|
|
17784
|
+
let checkers;
|
|
17785
|
+
try {
|
|
17786
|
+
checkers = strapi2.plugin("content-manager")?.service("permission-checker");
|
|
17787
|
+
} catch {
|
|
17788
|
+
checkers = null;
|
|
17789
|
+
}
|
|
17790
|
+
if (!checkers) return titles;
|
|
17791
|
+
const byType = /* @__PURE__ */ new Map();
|
|
17792
|
+
for (const row of rows) {
|
|
17793
|
+
const uid = row.targetType;
|
|
17794
|
+
const id = toId(row.targetId);
|
|
17795
|
+
if (typeof uid !== "string" || !id || !uid.startsWith("api::") || !strapi2.contentTypes?.[uid]) {
|
|
17796
|
+
continue;
|
|
17797
|
+
}
|
|
17798
|
+
if (!byType.has(uid)) byType.set(uid, /* @__PURE__ */ new Set());
|
|
17799
|
+
byType.get(uid)?.add(id);
|
|
17800
|
+
}
|
|
17801
|
+
for (const [uid, ids] of byType) {
|
|
17802
|
+
try {
|
|
17803
|
+
const checker = checkers.create({ userAbility: ability, model: uid });
|
|
17804
|
+
if (checker.cannot.read()) continue;
|
|
17805
|
+
const mainField = await mainFieldOf(uid);
|
|
17806
|
+
const attributes = strapi2.contentTypes[uid]?.attributes || {};
|
|
17807
|
+
if (!mainField || mainField === "id" || !attributes[mainField]) continue;
|
|
17808
|
+
if (checker.cannot.read(null, mainField)) continue;
|
|
17809
|
+
const select = ["id", "documentId", mainField];
|
|
17810
|
+
if (attributes.locale) select.push("locale");
|
|
17811
|
+
if (attributes.publishedAt) select.push("publishedAt");
|
|
17812
|
+
const found = await strapi2.db.query(uid).findMany({
|
|
17813
|
+
select,
|
|
17814
|
+
where: { documentId: { $in: [...ids] } },
|
|
17815
|
+
...attributes.createdBy ? { populate: { createdBy: { select: ["id"] } } } : {},
|
|
17816
|
+
limit: Math.min(ids.size * 20, 1e4)
|
|
17817
|
+
});
|
|
17818
|
+
const ordered = (Array.isArray(found) ? found : []).sort(
|
|
17819
|
+
(a, b) => Number(Boolean(a.publishedAt)) - Number(Boolean(b.publishedAt))
|
|
17820
|
+
);
|
|
17821
|
+
for (const doc of ordered) {
|
|
17822
|
+
if (!checker.can.read(doc, mainField)) continue;
|
|
17823
|
+
const title = pickEntryTitle(doc, mainField);
|
|
17824
|
+
if (!title) continue;
|
|
17825
|
+
const exact = `${uid}|${doc.documentId}|${doc.locale || ""}`;
|
|
17826
|
+
const any = `${uid}|${doc.documentId}|`;
|
|
17827
|
+
if (!titles.has(exact)) titles.set(exact, title);
|
|
17828
|
+
if (!titles.has(any)) titles.set(any, title);
|
|
17829
|
+
}
|
|
17830
|
+
} catch {
|
|
17831
|
+
}
|
|
17832
|
+
}
|
|
17833
|
+
return titles;
|
|
17834
|
+
}
|
|
17835
|
+
async function shapeActivity(rows, viewer) {
|
|
17836
|
+
const admins = await loadAdmins(rows.map((row) => row.actorId));
|
|
17837
|
+
const titles = await resolveTitles(rows, viewer.ability || null);
|
|
17838
|
+
return rows.map((row) => {
|
|
17839
|
+
const meta = toObject(row.meta);
|
|
17840
|
+
const admin = row.actorType === "admin" ? admins.get(Number(row.actorId)) : void 0;
|
|
17841
|
+
const type = strapi2.contentTypes?.[row.targetType];
|
|
17842
|
+
return {
|
|
17843
|
+
id: Number(row.id),
|
|
17844
|
+
action: String(row.event).replace(/^admin\.content\./, ""),
|
|
17845
|
+
at: toIso(row.createdAt),
|
|
17846
|
+
contentType: {
|
|
17847
|
+
uid: row.targetType,
|
|
17848
|
+
name: String(type?.info?.displayName || row.targetType).slice(0, 120),
|
|
17849
|
+
kind: meta.kind === "single" ? "single" : "collection",
|
|
17850
|
+
exists: Boolean(type)
|
|
17851
|
+
},
|
|
17852
|
+
entry: {
|
|
17853
|
+
documentId: row.targetId || null,
|
|
17854
|
+
locale: typeof meta.locale === "string" ? meta.locale : null,
|
|
17855
|
+
title: titles.get(
|
|
17856
|
+
`${row.targetType}|${row.targetId}|${typeof meta.locale === "string" ? meta.locale : ""}`
|
|
17857
|
+
) || titles.get(`${row.targetType}|${row.targetId}|`) || null,
|
|
17858
|
+
count: typeof meta.count === "number" ? meta.count : null
|
|
17859
|
+
},
|
|
17860
|
+
admin: admin ? { id: Number(admin.id), name: viewer.canReadAdmins === true ? adminName(admin) : "" } : null
|
|
17861
|
+
};
|
|
17862
|
+
});
|
|
17863
|
+
}
|
|
17864
|
+
return service;
|
|
17865
|
+
};
|
|
17866
|
+
module.exports.EVENT_UID = EVENT_UID;
|
|
17867
|
+
module.exports.VIEW_DEDUP_MS = VIEW_DEDUP_MS;
|
|
17868
|
+
}
|
|
17869
|
+
});
|
|
17870
|
+
|
|
15216
17871
|
// server/src/services/index.js
|
|
15217
17872
|
var require_services = __commonJS({
|
|
15218
17873
|
"server/src/services/index.js"(exports, module) {
|
|
@@ -15220,10 +17875,12 @@ var require_services = __commonJS({
|
|
|
15220
17875
|
var session = require_session2();
|
|
15221
17876
|
var geolocation = require_geolocation();
|
|
15222
17877
|
var notifications = require_notifications();
|
|
17878
|
+
var securityLog = require_security_log();
|
|
15223
17879
|
module.exports = {
|
|
15224
17880
|
session,
|
|
15225
17881
|
geolocation,
|
|
15226
|
-
notifications
|
|
17882
|
+
notifications,
|
|
17883
|
+
"security-log": securityLog
|
|
15227
17884
|
};
|
|
15228
17885
|
}
|
|
15229
17886
|
});
|