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