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