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