strapi-plugin-magic-sessionmanager 4.19.1 → 4.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +136 -1
  3. package/dist/admin/{Analytics-BqFlgLnN.mjs → Analytics-B-MVQ6dQ.mjs} +1 -1
  4. package/dist/admin/{Analytics-BElmzyNJ.js → Analytics-B5GnwMtH.js} +1 -1
  5. package/dist/admin/{App-0thsC_P9.mjs → App-DzbP5VPQ.mjs} +2 -2
  6. package/dist/admin/{App-D_J2eeEG.js → App-xBOmg4g9.js} +2 -2
  7. package/dist/admin/{OnlineUsersWidget-BgJ1ws-5.mjs → OnlineUsersWidget-Bf3BICmx.mjs} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-DMZBwqdY.js → OnlineUsersWidget-FuPPPCCV.js} +1 -1
  9. package/dist/admin/{Settings-FOkui_ke.js → Settings-WRIXHLDa.js} +280 -65
  10. package/dist/admin/{Settings-QN3Mu4AQ.mjs → Settings-hpkloyO6.mjs} +250 -35
  11. package/dist/admin/{de-uGKSKVYD.mjs → de-Bzd14FzX.mjs} +63 -1
  12. package/dist/admin/{de-CEyi4lpp.js → de-Uqb30N5n.js} +63 -1
  13. package/dist/admin/{en-CSXeJYKy.js → en-CDBcocLk.js} +63 -1
  14. package/dist/admin/{en-Yu7tfwqx.mjs → en-DovyVwa5.mjs} +63 -1
  15. package/dist/admin/{es-iNG9Amf9.mjs → es-BygJxl1J.mjs} +63 -1
  16. package/dist/admin/{es-BrKqXhAU.js → es-DA1X0RPv.js} +63 -1
  17. package/dist/admin/{fr-DKZNfdlH.js → fr-CPPA27jW.js} +63 -1
  18. package/dist/admin/{fr-CaFICHlf.mjs → fr-DONxL73-.mjs} +63 -1
  19. package/dist/admin/{index-h-ksmM8A.mjs → index-DsaGGK7x.mjs} +627 -61
  20. package/dist/admin/{index-DEYtqPc3.js → index-Q_D-5LlE.js} +612 -46
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +2 -2
  23. package/dist/admin/{pt-IEagyVDL.js → pt-BMuwyaan.js} +63 -1
  24. package/dist/admin/{pt-Bz2hWVrq.mjs → pt-D2yGNz2N.mjs} +63 -1
  25. package/dist/admin/{settingsTabs-D02CuEvs.mjs → settingsTabs--7IsqMdn.mjs} +5 -1
  26. package/dist/admin/{settingsTabs-N4TFn-mw.js → settingsTabs-Dxlevody.js} +5 -1
  27. package/dist/server/index.js +1485 -19
  28. package/dist/server/index.mjs +1485 -19
  29. package/package.json +1 -1
@@ -1052,6 +1052,606 @@ const ActionStack = styled__default.default.div`
1052
1052
  text-align: center;
1053
1053
  }
1054
1054
  `;
1055
+ const pluginPermissions = {
1056
+ access: [{ action: `plugin::${pluginId}.access`, subject: null }],
1057
+ /** Strapi admin panel sessions (view). The server also requires `access`. */
1058
+ adminSessionsRead: [{ action: `plugin::${pluginId}.admin-sessions.read`, subject: null }],
1059
+ /** Signing admins out. The server also requires `access` and `admin-sessions.read`. */
1060
+ adminSessionsRevoke: [{ action: `plugin::${pluginId}.admin-sessions.revoke`, subject: null }],
1061
+ /** Admin sign-in history and Content Manager activity. The server also requires `access` and `admin-sessions.read`. */
1062
+ adminActivityRead: [{ action: `plugin::${pluginId}.admin-activity.read`, subject: null }],
1063
+ /**
1064
+ * Protected settings (4.17): location lookup, webhooks and the security log.
1065
+ * The server also requires `access` (and `admin-activity.read` for the log).
1066
+ */
1067
+ settingsUpdate: [{ action: `plugin::${pluginId}.settings.update`, subject: null }],
1068
+ /** Lifting a sign-in lock. The server also requires `access`. */
1069
+ lockoutsUnlock: [{ action: `plugin::${pluginId}.lockouts.unlock`, subject: null }],
1070
+ /**
1071
+ * Impersonating app users (4.20): start, list and end. The server also
1072
+ * requires `access` and the Impersonation switch.
1073
+ */
1074
+ impersonateUsers: [{ action: `plugin::${pluginId}.impersonate.users`, subject: null }]
1075
+ };
1076
+ const SAFE_SCOPE = /^[A-Za-z0-9_.:-]{1,48}$/;
1077
+ const CANCEL_NAMES = /* @__PURE__ */ new Set(["AbortError", "TimeoutError", "CanceledError"]);
1078
+ function safeGet(value, key) {
1079
+ try {
1080
+ return value && typeof value === "object" ? value[key] : void 0;
1081
+ } catch {
1082
+ return void 0;
1083
+ }
1084
+ }
1085
+ function isCancelledRequest(error) {
1086
+ const name2 = safeGet(error, "name");
1087
+ return typeof name2 === "string" && CANCEL_NAMES.has(name2);
1088
+ }
1089
+ function logSafeAdminError(scope, error) {
1090
+ if (isCancelledRequest(error)) return;
1091
+ const safeScope = typeof scope === "string" && SAFE_SCOPE.test(scope) ? scope : "admin";
1092
+ const directStatus = safeGet(error, "status");
1093
+ const status = Number.isInteger(directStatus) ? directStatus : safeGet(safeGet(error, "response"), "status");
1094
+ const statusSuffix = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
1095
+ console.warn(`[${safeScope}] Request failed${statusSuffix}`);
1096
+ }
1097
+ function useSettingsTranslate() {
1098
+ const { formatMessage, locale } = reactIntl.useIntl();
1099
+ const t = react.useCallback(
1100
+ (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values),
1101
+ [formatMessage]
1102
+ );
1103
+ const tError = react.useCallback(
1104
+ (descriptor) => descriptor ? t(descriptor.messageId, descriptor.defaultMessage, descriptor.values) : void 0,
1105
+ [t]
1106
+ );
1107
+ return { t, tError, locale };
1108
+ }
1109
+ async function copyText(value, clipboard = globalThis.navigator?.clipboard) {
1110
+ if (typeof value !== "string") {
1111
+ throw new TypeError("clipboard_value_must_be_text");
1112
+ }
1113
+ if (!clipboard || typeof clipboard.writeText !== "function") {
1114
+ throw new Error("clipboard_unavailable");
1115
+ }
1116
+ await clipboard.writeText(value);
1117
+ }
1118
+ const USER_IMPERSONATION_DURATIONS = Object.freeze([15, 30, 60]);
1119
+ const DEFAULT_IMPERSONATION_MINUTES = 15;
1120
+ const REASON_MIN = 3;
1121
+ const REASON_MAX = 255;
1122
+ function validateReason(value) {
1123
+ const clean = typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
1124
+ if (clean.length < REASON_MIN) {
1125
+ return {
1126
+ messageId: "impersonation.reason.tooShort",
1127
+ defaultMessage: "Enter a reason of at least {min} characters.",
1128
+ values: { min: REASON_MIN }
1129
+ };
1130
+ }
1131
+ if (clean.length > REASON_MAX) {
1132
+ return {
1133
+ messageId: "impersonation.reason.tooLong",
1134
+ defaultMessage: "Use at most {max} characters.",
1135
+ values: { max: REASON_MAX }
1136
+ };
1137
+ }
1138
+ return null;
1139
+ }
1140
+ function secondsUntil(iso, now = Date.now()) {
1141
+ const end = Date.parse(String(iso ?? ""));
1142
+ if (!Number.isFinite(end)) return 0;
1143
+ return Math.max(0, Math.floor((end - now) / 1e3));
1144
+ }
1145
+ function formatClock(seconds) {
1146
+ const total = Math.max(0, Math.floor(Number(seconds) || 0));
1147
+ const hours = Math.floor(total / 3600);
1148
+ const minutes = Math.floor(total % 3600 / 60);
1149
+ const rest = String(total % 60).padStart(2, "0");
1150
+ return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${rest}` : `${minutes}:${rest}`;
1151
+ }
1152
+ function submitFrontendHandoff(doc, handoff) {
1153
+ if (!doc || !handoff || typeof handoff.url !== "string" || typeof handoff.code !== "string") {
1154
+ return false;
1155
+ }
1156
+ let url;
1157
+ try {
1158
+ url = new URL(handoff.url);
1159
+ } catch {
1160
+ return false;
1161
+ }
1162
+ if (url.protocol !== "https:" && url.protocol !== "http:") return false;
1163
+ const form = doc.createElement("form");
1164
+ form.method = "POST";
1165
+ form.action = url.toString();
1166
+ form.target = "_blank";
1167
+ form.rel = "noopener noreferrer";
1168
+ form.style.display = "none";
1169
+ const input = doc.createElement("input");
1170
+ input.type = "hidden";
1171
+ input.name = typeof handoff.field === "string" && handoff.field ? handoff.field : "code";
1172
+ input.value = handoff.code;
1173
+ form.appendChild(input);
1174
+ doc.body.appendChild(form);
1175
+ try {
1176
+ form.submit();
1177
+ } finally {
1178
+ form.remove();
1179
+ }
1180
+ return true;
1181
+ }
1182
+ const dialogs = /* @__PURE__ */ new Map();
1183
+ const mounted = /* @__PURE__ */ new Map();
1184
+ const listeners = /* @__PURE__ */ new Set();
1185
+ const notify = () => {
1186
+ for (const listener of listeners) listener();
1187
+ };
1188
+ function subscribeImpersonationDialogs(listener) {
1189
+ listeners.add(listener);
1190
+ return () => listeners.delete(listener);
1191
+ }
1192
+ function getImpersonationDialog(key) {
1193
+ return dialogs.get(key) || null;
1194
+ }
1195
+ function registerImpersonationPanel(key, instance) {
1196
+ const list = [...mounted.get(key) || [], instance];
1197
+ mounted.set(key, list);
1198
+ const dialog = dialogs.get(key);
1199
+ if (dialog && (!dialog.owner || !list.includes(dialog.owner))) {
1200
+ dialogs.set(key, { ...dialog, owner: instance });
1201
+ notify();
1202
+ }
1203
+ return () => {
1204
+ const rest = (mounted.get(key) || []).filter((id) => id !== instance);
1205
+ if (rest.length) mounted.set(key, rest);
1206
+ else mounted.delete(key);
1207
+ const current = dialogs.get(key);
1208
+ if (current && current.owner === instance) {
1209
+ dialogs.set(key, { ...current, owner: rest[rest.length - 1] || null });
1210
+ notify();
1211
+ }
1212
+ };
1213
+ }
1214
+ function openImpersonationDialog(key, instance) {
1215
+ dialogs.set(key, { open: true, owner: instance, draft: {} });
1216
+ notify();
1217
+ }
1218
+ function saveImpersonationDraft(key, draft) {
1219
+ const current = dialogs.get(key);
1220
+ if (current) dialogs.set(key, { ...current, draft });
1221
+ }
1222
+ function closeImpersonationDialog(key) {
1223
+ if (dialogs.delete(key)) notify();
1224
+ }
1225
+ const REFUSALS = Object.freeze({
1226
+ disabled: ["impersonation.error.disabled", "Impersonation is turned off in the settings."],
1227
+ "already-active": [
1228
+ "impersonation.error.alreadyActive",
1229
+ "An impersonation of this user is already running. End it first."
1230
+ ],
1231
+ blocked: ["impersonation.error.blocked", "Blocked accounts cannot be impersonated."],
1232
+ "api-token": ["impersonation.error.apiToken", "API tokens cannot impersonate."]
1233
+ });
1234
+ function useSecondsLeft(expiresAt) {
1235
+ const [now, setNow] = react.useState(() => Date.now());
1236
+ react.useEffect(() => {
1237
+ if (!expiresAt) return void 0;
1238
+ const timer = window.setInterval(() => setNow(Date.now()), 1e3);
1239
+ return () => window.clearInterval(timer);
1240
+ }, [expiresAt]);
1241
+ return secondsUntil(expiresAt, now);
1242
+ }
1243
+ const SecretField = ({ label, value, name: name2 }) => {
1244
+ const { t } = useSettingsTranslate();
1245
+ const { toggleNotification } = StrapiAdmin.useNotification();
1246
+ const copy = async () => {
1247
+ try {
1248
+ await copyText(value);
1249
+ toggleNotification({
1250
+ type: "success",
1251
+ message: t("impersonation.result.copied", "Copied to the clipboard.")
1252
+ });
1253
+ } catch {
1254
+ toggleNotification({
1255
+ type: "warning",
1256
+ message: t(
1257
+ "impersonation.result.copyFailed",
1258
+ "Copying failed. Select the text and copy it yourself."
1259
+ )
1260
+ });
1261
+ }
1262
+ };
1263
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: name2, children: [
1264
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: label }),
1265
+ /* @__PURE__ */ jsxRuntime.jsx(
1266
+ designSystem.TextInput,
1267
+ {
1268
+ value,
1269
+ readOnly: true,
1270
+ onFocus: (event) => event.target.select(),
1271
+ endAction: /* @__PURE__ */ jsxRuntime.jsx(
1272
+ designSystem.Field.Action,
1273
+ {
1274
+ label: t("impersonation.result.copy", "Copy {name}", { name: label }),
1275
+ onClick: copy,
1276
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.Duplicate, {})
1277
+ }
1278
+ )
1279
+ }
1280
+ )
1281
+ ] });
1282
+ };
1283
+ const ImpersonateUserModal = ({
1284
+ open,
1285
+ onOpenChange,
1286
+ onCloseAutoFocus,
1287
+ user,
1288
+ status,
1289
+ onChanged
1290
+ }) => {
1291
+ const { t, tError } = useSettingsTranslate();
1292
+ const { post } = StrapiAdmin.useFetchClient();
1293
+ const { toggleNotification } = StrapiAdmin.useNotification();
1294
+ const notifyHintId = react.useId();
1295
+ const [saved] = react.useState(() => getImpersonationDialog(user.documentId)?.draft || {});
1296
+ const [reason, setReason] = react.useState(saved.reason ?? "");
1297
+ const [minutes, setMinutes] = react.useState(saved.minutes ?? DEFAULT_IMPERSONATION_MINUTES);
1298
+ const [notifyUser, setNotifyUser] = react.useState(saved.notifyUser === true);
1299
+ const [touched, setTouched] = react.useState(false);
1300
+ const [pending, setPending] = react.useState(null);
1301
+ const [failure, setFailure] = react.useState(null);
1302
+ const [result, setResult] = react.useState(saved.result ?? null);
1303
+ react.useEffect(() => {
1304
+ if (!open) return;
1305
+ saveImpersonationDraft(user.documentId, { reason, minutes, notifyUser, result });
1306
+ }, [open, user.documentId, reason, minutes, notifyUser, result]);
1307
+ const secondsLeft = useSecondsLeft(result?.impersonation?.expiresAt || null);
1308
+ const durations = Array.isArray(status?.durations) ? status.durations : USER_IMPERSONATION_DURATIONS;
1309
+ const reasonError = validateReason(reason);
1310
+ const showReasonError = touched && reasonError;
1311
+ const start = async () => {
1312
+ setTouched(true);
1313
+ if (reasonError) return;
1314
+ setPending("start");
1315
+ setFailure(null);
1316
+ try {
1317
+ const { data } = await post(
1318
+ `/${pluginId}/impersonation/users/${encodeURIComponent(user.documentId)}`,
1319
+ { reason: reason.trim(), durationMinutes: minutes, notifyUser }
1320
+ );
1321
+ setResult(data?.data || null);
1322
+ onChanged?.();
1323
+ } catch (err) {
1324
+ if (isCancelledRequest(err)) return;
1325
+ const response = err?.response;
1326
+ const reasonCode = response?.data?.error?.details?.reason;
1327
+ if (response?.status === 429) {
1328
+ setFailure(
1329
+ t(
1330
+ "impersonation.error.rateLimited",
1331
+ "Too many impersonations were started. Try again in a few minutes."
1332
+ )
1333
+ );
1334
+ } else if (REFUSALS[reasonCode]) {
1335
+ setFailure(t(...REFUSALS[reasonCode]));
1336
+ } else {
1337
+ logSafeAdminError("impersonation.start", err);
1338
+ setFailure(t("impersonation.error.start", "The impersonation could not be started."));
1339
+ }
1340
+ } finally {
1341
+ setPending(null);
1342
+ }
1343
+ };
1344
+ const end = async () => {
1345
+ if (!result?.impersonation?.id) return;
1346
+ setPending("end");
1347
+ try {
1348
+ await post(`/${pluginId}/impersonation/${result.impersonation.id}/end`, {});
1349
+ toggleNotification({
1350
+ type: "success",
1351
+ message: t("impersonation.ended", "Impersonation ended.")
1352
+ });
1353
+ onChanged?.();
1354
+ onOpenChange(false);
1355
+ } catch (err) {
1356
+ logSafeAdminError("impersonation.end", err);
1357
+ toggleNotification({
1358
+ type: "danger",
1359
+ message: t("impersonation.error.end", "The impersonation could not be ended.")
1360
+ });
1361
+ } finally {
1362
+ setPending(null);
1363
+ }
1364
+ };
1365
+ const openFrontend = () => {
1366
+ setFailure(null);
1367
+ const onViolation = (event) => {
1368
+ if (String(event?.violatedDirective || "").startsWith("form-action")) {
1369
+ setFailure(
1370
+ t(
1371
+ "impersonation.error.csp",
1372
+ "Your Strapi security settings block sending the sign-in to {origin}. Add this origin to form-action of the Content-Security-Policy (see the README), then start again.",
1373
+ { origin: status?.frontendOrigin || "" }
1374
+ )
1375
+ );
1376
+ }
1377
+ };
1378
+ document.addEventListener("securitypolicyviolation", onViolation);
1379
+ window.setTimeout(
1380
+ () => document.removeEventListener("securitypolicyviolation", onViolation),
1381
+ 3e3
1382
+ );
1383
+ if (!submitFrontendHandoff(document, result?.handoff)) {
1384
+ setFailure(t("impersonation.error.frontend", "The frontend could not be opened."));
1385
+ }
1386
+ };
1387
+ const handoff = result?.handoff;
1388
+ const clock = formatClock(secondsLeft);
1389
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Root, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
1390
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Title, { children: result ? t("impersonation.result.title", "Impersonating {user}", { user: user.label }) : t("impersonation.modal.title", "Impersonate {user}", { user: user.label }) }) }),
1391
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Body, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1392
+ failure ? /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "danger", closeLabel: t("common.close", "Close"), children: failure }) : null,
1393
+ !result ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1394
+ /* @__PURE__ */ jsxRuntime.jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
1395
+ "impersonation.modal.intro",
1396
+ "You get a short-lived sign-in as this user to reproduce a problem. Password, email address, account and sessions cannot be changed with it. It is recorded in the security log."
1397
+ ) }),
1398
+ /* @__PURE__ */ jsxRuntime.jsxs(
1399
+ designSystem.Field.Root,
1400
+ {
1401
+ name: "reason",
1402
+ required: true,
1403
+ error: showReasonError ? tError(reasonError) : void 0,
1404
+ hint: t(
1405
+ "impersonation.reason.hint",
1406
+ "Stored in the security log and, if you email the user, shown to them."
1407
+ ),
1408
+ children: [
1409
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("impersonation.reason.label", "Reason") }),
1410
+ /* @__PURE__ */ jsxRuntime.jsx(
1411
+ designSystem.Textarea,
1412
+ {
1413
+ value: reason,
1414
+ maxLength: REASON_MAX,
1415
+ placeholder: t("impersonation.reason.placeholder", "For example: ticket 4711"),
1416
+ onChange: (event) => setReason(event.target.value),
1417
+ onBlur: () => setTouched(true)
1418
+ }
1419
+ ),
1420
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Hint, {}),
1421
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Error, {})
1422
+ ]
1423
+ }
1424
+ ),
1425
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { name: "durationMinutes", children: [
1426
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: t("impersonation.duration.label", "Duration") }),
1427
+ /* @__PURE__ */ jsxRuntime.jsx(
1428
+ designSystem.SingleSelect,
1429
+ {
1430
+ value: String(minutes),
1431
+ onChange: (value) => setMinutes(Number(value)),
1432
+ children: durations.map((value) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: String(value), children: t(
1433
+ "impersonation.duration.minutes",
1434
+ "{count, plural, one {# minute} other {# minutes}}",
1435
+ {
1436
+ count: value
1437
+ }
1438
+ ) }, value))
1439
+ }
1440
+ )
1441
+ ] }),
1442
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 1, children: [
1443
+ /* @__PURE__ */ jsxRuntime.jsx(
1444
+ designSystem.Checkbox,
1445
+ {
1446
+ checked: notifyUser,
1447
+ "aria-describedby": notifyHintId,
1448
+ onCheckedChange: (checked) => setNotifyUser(checked === true),
1449
+ children: t(
1450
+ "impersonation.notify.label",
1451
+ "Email the user that their account was opened"
1452
+ )
1453
+ }
1454
+ ),
1455
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { id: notifyHintId, variant: "pi", textColor: "neutral600", children: t(
1456
+ "impersonation.notify.hint",
1457
+ "Sent through Strapi’s email plugin, with the reason and the duration."
1458
+ ) })
1459
+ ] })
1460
+ ] }) : null,
1461
+ handoff?.type === "frontend" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1462
+ /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "default", closeLabel: t("common.close", "Close"), children: t(
1463
+ "impersonation.result.frontendBody",
1464
+ "Open {origin} within one minute. The sign-in link works once and is sent without appearing in the address bar.",
1465
+ { origin: status?.frontendOrigin || "" }
1466
+ ) }),
1467
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.ExternalLink, {}), onClick: openFrontend, children: t("impersonation.result.openFrontend", "Open frontend") }) })
1468
+ ] }) : null,
1469
+ handoff?.type === "token" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1470
+ /* @__PURE__ */ jsxRuntime.jsx(PersistentAlert, { variant: "warning", closeLabel: t("common.close", "Close"), children: t(
1471
+ "impersonation.result.tokenBody",
1472
+ "Shown only once. Anyone who has this token acts as {user} until it ends. Do not store or share it.",
1473
+ { user: user.label }
1474
+ ) }),
1475
+ /* @__PURE__ */ jsxRuntime.jsx(
1476
+ SecretField,
1477
+ {
1478
+ name: "jwt",
1479
+ label: t("impersonation.result.accessToken", "Access token"),
1480
+ value: handoff.jwt
1481
+ }
1482
+ ),
1483
+ handoff.refreshToken ? /* @__PURE__ */ jsxRuntime.jsx(
1484
+ SecretField,
1485
+ {
1486
+ name: "refreshToken",
1487
+ label: t("impersonation.result.refreshToken", "Refresh token"),
1488
+ value: handoff.refreshToken
1489
+ }
1490
+ ) : null
1491
+ ] }) : null,
1492
+ result ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral800", tag: "p", "aria-live": "polite", children: t("impersonation.result.endsIn", "Ends in {time}.", { time: clock }) }) : null
1493
+ ] }) }),
1494
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Footer, { children: result ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1495
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "danger-light", onClick: end, loading: pending === "end", children: t("impersonation.end", "End impersonation") }),
1496
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: t("impersonation.result.done", "Done") }) })
1497
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1498
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Modal.Close, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", children: t("common.cancel", "Cancel") }) }),
1499
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { onClick: start, loading: pending === "start", children: t("impersonation.start", "Start impersonation") })
1500
+ ] }) })
1501
+ ] }) });
1502
+ };
1503
+ const focusVisibleTrigger = (documentId, fallback) => {
1504
+ const candidates = [
1505
+ ...document.querySelectorAll(
1506
+ `[data-impersonation-trigger="${globalThis.CSS?.escape ? globalThis.CSS.escape(documentId) : documentId}"]`
1507
+ )
1508
+ ];
1509
+ const visible = candidates.find((node) => node.getClientRects().length > 0);
1510
+ (visible || fallback)?.focus?.();
1511
+ };
1512
+ const ImpersonationPanelSection = ({ documentId, userLabel }) => {
1513
+ const { t } = useSettingsTranslate();
1514
+ const { get, post } = StrapiAdmin.useFetchClient();
1515
+ const { toggleNotification } = StrapiAdmin.useNotification();
1516
+ const { formatDate } = useSessionFormatters();
1517
+ const {
1518
+ isLoading,
1519
+ allowedActions: { canUsers }
1520
+ } = StrapiAdmin.useRBAC(pluginPermissions.impersonateUsers);
1521
+ const [status, setStatus] = react.useState(null);
1522
+ const [active, setActive] = react.useState(null);
1523
+ const instance = react.useId();
1524
+ const dialog = react.useSyncExternalStore(
1525
+ subscribeImpersonationDialogs,
1526
+ () => getImpersonationDialog(documentId)
1527
+ );
1528
+ const open = dialog?.open === true && dialog.owner === instance;
1529
+ react.useEffect(() => registerImpersonationPanel(documentId, instance), [documentId, instance]);
1530
+ const triggerRef = react.useRef(null);
1531
+ const endTriggerRef = react.useRef(null);
1532
+ const requestRef = react.useRef(0);
1533
+ const apply = react.useCallback(
1534
+ async (request, pending) => {
1535
+ try {
1536
+ const [statusResponse, listResponse] = await pending;
1537
+ if (request !== requestRef.current) return;
1538
+ setStatus(statusResponse?.data?.data || null);
1539
+ const rows = Array.isArray(listResponse?.data?.data) ? listResponse.data.data : [];
1540
+ setActive(
1541
+ rows.find((row) => row.targetType === "user" && row.targetId === documentId) || null
1542
+ );
1543
+ } catch (err) {
1544
+ if (isCancelledRequest(err) || request !== requestRef.current) return;
1545
+ logSafeAdminError("impersonation.panel", err);
1546
+ setStatus(null);
1547
+ }
1548
+ },
1549
+ [documentId]
1550
+ );
1551
+ const fetchState = react.useCallback(
1552
+ () => Promise.all([
1553
+ get(`/${pluginId}/impersonation/status`),
1554
+ get(`/${pluginId}/impersonation/active`)
1555
+ ]),
1556
+ [get]
1557
+ );
1558
+ const load = react.useCallback(() => apply(++requestRef.current, fetchState()), [apply, fetchState]);
1559
+ react.useEffect(() => {
1560
+ if (isLoading || !canUsers || !documentId) return;
1561
+ apply(++requestRef.current, fetchState());
1562
+ }, [apply, canUsers, documentId, fetchState, isLoading]);
1563
+ if (isLoading || !canUsers || !status?.enabled) return null;
1564
+ const end = async () => {
1565
+ try {
1566
+ await post(`/${pluginId}/impersonation/${active.id}/end`, {});
1567
+ toggleNotification({
1568
+ type: "success",
1569
+ message: t("impersonation.ended", "Impersonation ended.")
1570
+ });
1571
+ } catch (err) {
1572
+ logSafeAdminError("impersonation.end", err);
1573
+ toggleNotification({
1574
+ type: "danger",
1575
+ message: t("impersonation.error.end", "The impersonation could not be ended.")
1576
+ });
1577
+ throw err;
1578
+ } finally {
1579
+ await load();
1580
+ }
1581
+ };
1582
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-impersonation": "", children: [
1583
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: t("impersonation.panel.title", "Impersonation") }),
1584
+ active ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1585
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral800", tag: "p", children: t("impersonation.panel.running", "Running until {time}.", {
1586
+ time: formatDate(active.expiresAt, { hour: "2-digit", minute: "2-digit" })
1587
+ }) }),
1588
+ /* @__PURE__ */ jsxRuntime.jsx(
1589
+ ConfirmAction,
1590
+ {
1591
+ title: t("impersonation.confirm.title", "End the impersonation of {user}?", {
1592
+ user: userLabel
1593
+ }),
1594
+ body: t(
1595
+ "impersonation.confirm.body",
1596
+ "The short-lived sign-in stops working at once. This is recorded in the security log."
1597
+ ),
1598
+ confirmLabel: t("impersonation.end", "End impersonation"),
1599
+ onConfirm: end,
1600
+ fallbackFocusRef: triggerRef,
1601
+ trigger: /* @__PURE__ */ jsxRuntime.jsx(
1602
+ designSystem.Button,
1603
+ {
1604
+ ref: endTriggerRef,
1605
+ "data-impersonation-trigger": documentId,
1606
+ fullWidth: true,
1607
+ size: "S",
1608
+ variant: "danger-light",
1609
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.SignOut, { "aria-hidden": true, focusable: false }),
1610
+ type: "button",
1611
+ children: t("impersonation.end", "End impersonation")
1612
+ }
1613
+ )
1614
+ }
1615
+ )
1616
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(
1617
+ designSystem.Button,
1618
+ {
1619
+ ref: triggerRef,
1620
+ "data-impersonation-trigger": documentId,
1621
+ fullWidth: true,
1622
+ size: "S",
1623
+ variant: "secondary",
1624
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.User, { "aria-hidden": true, focusable: false }),
1625
+ onClick: () => openImpersonationDialog(documentId, instance),
1626
+ type: "button",
1627
+ children: t("impersonation.panel.start", "Impersonate…")
1628
+ }
1629
+ ),
1630
+ open ? /* @__PURE__ */ jsxRuntime.jsx(
1631
+ ImpersonateUserModal,
1632
+ {
1633
+ open: true,
1634
+ onOpenChange: (next) => {
1635
+ if (!next) {
1636
+ closeImpersonationDialog(documentId);
1637
+ load();
1638
+ window.setTimeout(
1639
+ () => focusVisibleTrigger(documentId, triggerRef.current || endTriggerRef.current),
1640
+ 0
1641
+ );
1642
+ }
1643
+ },
1644
+ onCloseAutoFocus: (event) => {
1645
+ event.preventDefault();
1646
+ focusVisibleTrigger(documentId, triggerRef.current || endTriggerRef.current);
1647
+ },
1648
+ user: { documentId, label: userLabel },
1649
+ status,
1650
+ onChanged: load
1651
+ }
1652
+ ) : null
1653
+ ] });
1654
+ };
1055
1655
  function requireSessionList(payload) {
1056
1656
  if (!Array.isArray(payload?.data)) throw new Error("Invalid session response");
1057
1657
  return payload.data;
@@ -1141,43 +1741,6 @@ function applyBlockedFormSync(plan, form) {
1141
1741
  }
1142
1742
  return false;
1143
1743
  }
1144
- const pluginPermissions = {
1145
- access: [{ action: `plugin::${pluginId}.access`, subject: null }],
1146
- /** Strapi admin panel sessions (view). The server also requires `access`. */
1147
- adminSessionsRead: [{ action: `plugin::${pluginId}.admin-sessions.read`, subject: null }],
1148
- /** Signing admins out. The server also requires `access` and `admin-sessions.read`. */
1149
- adminSessionsRevoke: [{ action: `plugin::${pluginId}.admin-sessions.revoke`, subject: null }],
1150
- /** Admin sign-in history and Content Manager activity. The server also requires `access` and `admin-sessions.read`. */
1151
- adminActivityRead: [{ action: `plugin::${pluginId}.admin-activity.read`, subject: null }],
1152
- /**
1153
- * Protected settings (4.17): location lookup, webhooks and the security log.
1154
- * The server also requires `access` (and `admin-activity.read` for the log).
1155
- */
1156
- settingsUpdate: [{ action: `plugin::${pluginId}.settings.update`, subject: null }],
1157
- /** Lifting a sign-in lock. The server also requires `access`. */
1158
- lockoutsUnlock: [{ action: `plugin::${pluginId}.lockouts.unlock`, subject: null }]
1159
- };
1160
- const SAFE_SCOPE = /^[A-Za-z0-9_.:-]{1,48}$/;
1161
- const CANCEL_NAMES = /* @__PURE__ */ new Set(["AbortError", "TimeoutError", "CanceledError"]);
1162
- function safeGet(value, key) {
1163
- try {
1164
- return value && typeof value === "object" ? value[key] : void 0;
1165
- } catch {
1166
- return void 0;
1167
- }
1168
- }
1169
- function isCancelledRequest(error) {
1170
- const name2 = safeGet(error, "name");
1171
- return typeof name2 === "string" && CANCEL_NAMES.has(name2);
1172
- }
1173
- function logSafeAdminError(scope, error) {
1174
- if (isCancelledRequest(error)) return;
1175
- const safeScope = typeof scope === "string" && SAFE_SCOPE.test(scope) ? scope : "admin";
1176
- const directStatus = safeGet(error, "status");
1177
- const status = Number.isInteger(directStatus) ? directStatus : safeGet(safeGet(error, "response"), "status");
1178
- const statusSuffix = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
1179
- console.warn(`[${safeScope}] Request failed${statusSuffix}`);
1180
- }
1181
1744
  const FORM_CONSUMER = "MagicSessionManagerPanel";
1182
1745
  const PanelSessionCard = ({ session, t }) => {
1183
1746
  const { formatDate, formatRelativeTime, translate } = useSessionFormatters();
@@ -1544,6 +2107,7 @@ const SessionInfoPanel = ({ documentId, model, document: document2 }) => {
1544
2107
  "End all sessions lets the user sign in again. Block user also prevents new sign-ins."
1545
2108
  ) })
1546
2109
  ] }),
2110
+ userId ? /* @__PURE__ */ jsxRuntime.jsx(ImpersonationPanelSection, { documentId: String(userId), userLabel }) : null,
1547
2111
  loading ? null : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-sessions": "", children: [
1548
2112
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: t("panel.sessions.openTitle", "Open sessions") }),
1549
2113
  visible.length > 0 ? /* @__PURE__ */ jsxRuntime.jsx(
@@ -1591,7 +2155,7 @@ const index = {
1591
2155
  id: `${pluginId}.plugin.name`,
1592
2156
  defaultMessage: pluginPkg.strapi.displayName
1593
2157
  },
1594
- Component: () => Promise.resolve().then(() => require("./App-D_J2eeEG.js")),
2158
+ Component: () => Promise.resolve().then(() => require("./App-xBOmg4g9.js")),
1595
2159
  permissions: pluginPermissions$1
1596
2160
  });
1597
2161
  app.addSettingsLink(
@@ -1607,7 +2171,7 @@ const index = {
1607
2171
  },
1608
2172
  id: "general",
1609
2173
  to: `${pluginId}/general`,
1610
- Component: () => Promise.resolve().then(() => require("./Settings-FOkui_ke.js")),
2174
+ Component: () => Promise.resolve().then(() => require("./Settings-WRIXHLDa.js")),
1611
2175
  permissions: pluginPermissions$1
1612
2176
  },
1613
2177
  {
@@ -1617,7 +2181,7 @@ const index = {
1617
2181
  },
1618
2182
  id: "analytics",
1619
2183
  to: `${pluginId}/analytics`,
1620
- Component: () => Promise.resolve().then(() => require("./Analytics-BElmzyNJ.js")),
2184
+ Component: () => Promise.resolve().then(() => require("./Analytics-B5GnwMtH.js")),
1621
2185
  permissions: pluginPermissions$1
1622
2186
  }
1623
2187
  ]
@@ -1643,7 +2207,7 @@ const index = {
1643
2207
  href: `/plugins/${pluginId}`
1644
2208
  },
1645
2209
  component: async () => {
1646
- const component = await Promise.resolve().then(() => require("./OnlineUsersWidget-DMZBwqdY.js"));
2210
+ const component = await Promise.resolve().then(() => require("./OnlineUsersWidget-FuPPPCCV.js"));
1647
2211
  return component.default;
1648
2212
  },
1649
2213
  id: "online-users-widget",
@@ -1664,11 +2228,11 @@ const index = {
1664
2228
  },
1665
2229
  async registerTrads({ locales }) {
1666
2230
  const importedTrads = {
1667
- en: () => Promise.resolve().then(() => require("./en-CSXeJYKy.js")),
1668
- de: () => Promise.resolve().then(() => require("./de-CEyi4lpp.js")),
1669
- es: () => Promise.resolve().then(() => require("./es-BrKqXhAU.js")),
1670
- fr: () => Promise.resolve().then(() => require("./fr-DKZNfdlH.js")),
1671
- pt: () => Promise.resolve().then(() => require("./pt-IEagyVDL.js"))
2231
+ en: () => Promise.resolve().then(() => require("./en-CDBcocLk.js")),
2232
+ de: () => Promise.resolve().then(() => require("./de-Uqb30N5n.js")),
2233
+ es: () => Promise.resolve().then(() => require("./es-DA1X0RPv.js")),
2234
+ fr: () => Promise.resolve().then(() => require("./fr-CPPA27jW.js")),
2235
+ pt: () => Promise.resolve().then(() => require("./pt-BMuwyaan.js"))
1672
2236
  };
1673
2237
  const translatedLanguages = Object.keys(importedTrads).filter((lang) => locales.includes(lang));
1674
2238
  const translations = await Promise.all(
@@ -1705,6 +2269,7 @@ exports.StatGrid = StatGrid;
1705
2269
  exports.StatusBadge = StatusBadge;
1706
2270
  exports.TargetLink = TargetLink;
1707
2271
  exports.ValueOrMissing = ValueOrMissing;
2272
+ exports.copyText = copyText;
1708
2273
  exports.formatSessionDate = formatSessionDate;
1709
2274
  exports.getBadgeColors = getBadgeColors;
1710
2275
  exports.getDevicePresentation = getDevicePresentation;
@@ -1730,3 +2295,4 @@ exports.requireSuccessfulMutation = requireSuccessfulMutation;
1730
2295
  exports.restoreDialogFocus = restoreDialogFocus;
1731
2296
  exports.toValidDate = toValidDate;
1732
2297
  exports.useSessionFormatters = useSessionFormatters;
2298
+ exports.useSettingsTranslate = useSettingsTranslate;