strapi-plugin-magic-sessionmanager 4.20.0 → 4.22.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 (33) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +104 -50
  3. package/dist/admin/{Analytics-B5GnwMtH.js → Analytics-DeDLGiCe.js} +1 -1
  4. package/dist/admin/{Analytics-B-MVQ6dQ.mjs → Analytics-WbCUmkQQ.mjs} +1 -1
  5. package/dist/admin/{App-xBOmg4g9.js → App-Bkv-W0Sv.js} +1640 -2561
  6. package/dist/admin/{App-DzbP5VPQ.mjs → App-C4bihk2K.mjs} +1610 -2531
  7. package/dist/admin/{OnlineUsersWidget-FuPPPCCV.js → OnlineUsersWidget-CSvNe2rC.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-Bf3BICmx.mjs → OnlineUsersWidget-q0Z6nbbO.mjs} +1 -1
  9. package/dist/admin/{Settings-hpkloyO6.mjs → Settings-avD0DbXP.mjs} +17 -9
  10. package/dist/admin/{Settings-WRIXHLDa.js → Settings-xokFI5LO.js} +59 -51
  11. package/dist/admin/dashboardModel-BBNRgcEr.mjs +170 -0
  12. package/dist/admin/dashboardModel-D4389iIV.js +169 -0
  13. package/dist/admin/{de-Bzd14FzX.mjs → de-BQlEdBMr.mjs} +104 -4
  14. package/dist/admin/{de-Uqb30N5n.js → de-HcJ19LKI.js} +104 -4
  15. package/dist/admin/{en-CDBcocLk.js → en-DI-98CPM.js} +105 -5
  16. package/dist/admin/{en-DovyVwa5.mjs → en-DzuXWL1W.mjs} +105 -5
  17. package/dist/admin/{es-BygJxl1J.mjs → es-BfyED9YI.mjs} +104 -4
  18. package/dist/admin/{es-DA1X0RPv.js → es-Cm0Eklav.js} +104 -4
  19. package/dist/admin/{fr-CPPA27jW.js → fr-C3nzszsI.js} +104 -4
  20. package/dist/admin/{fr-DONxL73-.mjs → fr-CzFNGWq0.mjs} +104 -4
  21. package/dist/admin/index-6zc5D8eb.mjs +4729 -0
  22. package/dist/admin/index-Dk5Jqe5U.js +4730 -0
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +2 -2
  25. package/dist/admin/{pt-BMuwyaan.js → pt-BPZ6chPT.js} +104 -4
  26. package/dist/admin/{pt-D2yGNz2N.mjs → pt-DmyQnGI_.mjs} +104 -4
  27. package/dist/server/index.js +1048 -67
  28. package/dist/server/index.mjs +1048 -67
  29. package/package.json +1 -1
  30. package/dist/admin/index-DsaGGK7x.mjs +0 -2297
  31. package/dist/admin/index-Q_D-5LlE.js +0 -2298
  32. package/dist/admin/settingsTabs--7IsqMdn.mjs +0 -437
  33. package/dist/admin/settingsTabs-Dxlevody.js +0 -436
@@ -0,0 +1,4729 @@
1
+ import { useRef, useEffect, forwardRef, useId, Children, useCallback, useMemo, useState, useSyncExternalStore } from "react";
2
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
3
+ import { Monitor, CheckCircle, WarningCircle, Information, Server, Code, Phone, ExternalLink, Duplicate, SignOut, User, Eye, Webhooks, Clock, Stop, Download, Earth, Key, Stack, Lock, CrossCircle, Trash, Cog, Shield } from "@strapi/icons";
4
+ import { useIntl } from "react-intl";
5
+ import { Link as Link$1, NavLink } from "react-router-dom";
6
+ import { Typography, Flex, Box, Grid, VisuallyHidden, Badge, Tooltip, Dialog, Button, Link, Modal, Field, Textarea, SingleSelect, SingleSelectOption, Checkbox, TextInput, Tr, Td, TextButton, IconButton, Th, Table, Thead, Tbody, LinkButton, Loader } from "@strapi/design-system";
7
+ import { Page, Layouts, ConfirmDialog, useFetchClient, useNotification, useRBAC, useForm } from "@strapi/strapi/admin";
8
+ import styled, { css } from "styled-components";
9
+ const strapi = { "name": "magic-sessionmanager", "displayName": "Magic Sessionmanager" };
10
+ const pluginPkg = {
11
+ strapi
12
+ };
13
+ const pluginId$1 = "magic-sessionmanager";
14
+ const PLUGIN_ID = pluginId$1;
15
+ const Initializer = ({ setPlugin }) => {
16
+ const ref = useRef(setPlugin);
17
+ useEffect(() => {
18
+ if (ref.current) {
19
+ ref.current(pluginId$1);
20
+ }
21
+ }, []);
22
+ return null;
23
+ };
24
+ const PluginIcon = (props) => /* @__PURE__ */ jsx(Monitor, { "aria-hidden": true, focusable: false, ...props });
25
+ const TONES = {
26
+ danger: { background: "danger100", border: "danger200", icon: "danger700" },
27
+ success: { background: "success100", border: "success200", icon: "success700" },
28
+ warning: { background: "warning100", border: "warning200", icon: "warning700" },
29
+ default: { background: "primary100", border: "primary200", icon: "primary700" },
30
+ neutral: { background: "neutral0", border: "neutral200", icon: "neutral600" }
31
+ };
32
+ const AlertBody = styled(Typography)`
33
+ min-width: 0;
34
+
35
+ & > * {
36
+ display: inline;
37
+ max-width: none;
38
+ margin: 0;
39
+ font-size: inherit;
40
+ font-weight: inherit;
41
+ line-height: inherit;
42
+ color: inherit;
43
+ }
44
+ `;
45
+ const PersistentAlert = forwardRef(function PersistentAlert2({
46
+ variant = "default",
47
+ title,
48
+ titleAs = "p",
49
+ stacked = false,
50
+ action,
51
+ closeLabel: _closeLabel,
52
+ onClose: _onClose,
53
+ children,
54
+ ...rest
55
+ }, ref) {
56
+ const tone = TONES[variant] || TONES.default;
57
+ const Icon = variant === "success" ? CheckCircle : variant === "danger" || variant === "warning" ? WarningCircle : Information;
58
+ return /* @__PURE__ */ jsxs(
59
+ Flex,
60
+ {
61
+ ref,
62
+ alignItems: "flex-start",
63
+ background: tone.background,
64
+ borderColor: tone.border,
65
+ shadow: "filterShadow",
66
+ gap: 3,
67
+ hasRadius: true,
68
+ padding: 5,
69
+ paddingRight: 6,
70
+ "data-persistent-alert": "",
71
+ ...rest,
72
+ children: [
73
+ /* @__PURE__ */ jsx(Flex, { shrink: 0, width: "2rem", height: "2rem", children: /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, focusable: "false", width: "2rem", height: "2rem", fill: tone.icon }) }),
74
+ /* @__PURE__ */ jsxs(
75
+ Flex,
76
+ {
77
+ direction: stacked ? "column" : "row",
78
+ alignItems: stacked ? "stretch" : "start",
79
+ gap: action || stacked ? 2 : 1,
80
+ wrap: stacked ? "nowrap" : "wrap",
81
+ role: variant === "danger" ? "alert" : "status",
82
+ width: "100%",
83
+ minWidth: 0,
84
+ children: [
85
+ title ? /* @__PURE__ */ jsx(Typography, { fontWeight: "bold", textColor: "neutral800", tag: titleAs, children: title }) : null,
86
+ /* @__PURE__ */ jsx(AlertBody, { tag: "div", variant: "omega", textColor: "neutral800", children }),
87
+ action ? /* @__PURE__ */ jsx(Box, { children: action }) : null
88
+ ]
89
+ }
90
+ )
91
+ ]
92
+ }
93
+ );
94
+ });
95
+ const paragraphRhythm = css`
96
+ p {
97
+ max-width: 72ch;
98
+ margin-block: 0;
99
+ line-height: 1.6;
100
+ text-wrap: pretty;
101
+ }
102
+
103
+ p + p {
104
+ margin-block-start: ${({ theme }) => theme.spaces[3]};
105
+ }
106
+
107
+ li {
108
+ max-width: 72ch;
109
+ line-height: 1.6;
110
+ text-wrap: pretty;
111
+ }
112
+
113
+ li + li {
114
+ margin-block-start: ${({ theme }) => theme.spaces[2]};
115
+ }
116
+ `;
117
+ const ReadableText = styled(Typography)`
118
+ display: block;
119
+ width: 100%;
120
+ min-width: 0;
121
+ max-width: 72ch;
122
+ margin: 0;
123
+ line-height: 1.6;
124
+ text-wrap: pretty;
125
+
126
+ & + & {
127
+ margin-block-start: ${({ theme }) => theme.spaces[3]};
128
+ }
129
+ `;
130
+ const ParagraphGroup = styled.div`
131
+ display: block;
132
+ width: 100%;
133
+ min-width: 0;
134
+ `;
135
+ const InlineParagraphGroup = styled.span`
136
+ display: block;
137
+ width: 100%;
138
+ min-width: 0;
139
+ `;
140
+ const ReadableParagraphs = ({ id, text, ...typographyProps }) => {
141
+ const ParagraphContainer = typographyProps.tag === "span" ? InlineParagraphGroup : ParagraphGroup;
142
+ const paragraphs = String(text ?? "").split(/\n\s*\n/).map((paragraph) => paragraph.trim()).filter(Boolean);
143
+ return /* @__PURE__ */ jsx(ParagraphContainer, { id, "data-readable-paragraphs": "", children: paragraphs.map((paragraph, index2) => /* @__PURE__ */ jsx(
144
+ ReadableText,
145
+ {
146
+ ...typographyProps,
147
+ tag: typographyProps.tag || "p",
148
+ children: paragraph
149
+ },
150
+ `${id || "readable-paragraph"}-${index2}`
151
+ )) });
152
+ };
153
+ const PageContent = styled(Flex)`
154
+ width: 100%;
155
+ min-width: 0;
156
+
157
+ ${paragraphRhythm}
158
+ `;
159
+ const PageShell = ({
160
+ headingId,
161
+ title,
162
+ documentTitle,
163
+ subtitle,
164
+ primaryAction,
165
+ secondaryAction,
166
+ navigationAction,
167
+ startActions,
168
+ endActions,
169
+ children
170
+ }) => {
171
+ const generatedId = useId();
172
+ const titleId = headingId || `page-title-${generatedId.replace(/:/g, "")}`;
173
+ const hasActionBar = Boolean(startActions || endActions);
174
+ const tabTitle = documentTitle || (typeof title === "string" ? title : "");
175
+ return /* @__PURE__ */ jsxs(Page.Main, { "aria-labelledby": titleId, children: [
176
+ tabTitle ? /* @__PURE__ */ jsx(Page.Title, { children: tabTitle }) : null,
177
+ /* @__PURE__ */ jsx(
178
+ Layouts.Header,
179
+ {
180
+ id: titleId,
181
+ title,
182
+ subtitle,
183
+ primaryAction,
184
+ secondaryAction,
185
+ navigationAction
186
+ }
187
+ ),
188
+ hasActionBar ? /* @__PURE__ */ jsx(Layouts.Action, { startActions, endActions }) : null,
189
+ /* @__PURE__ */ jsx(Layouts.Content, { children: /* @__PURE__ */ jsx(
190
+ PageContent,
191
+ {
192
+ direction: "column",
193
+ alignItems: "stretch",
194
+ gap: 6,
195
+ paddingBottom: 8,
196
+ "data-text-rhythm": "page",
197
+ "data-page-shell": "",
198
+ children
199
+ }
200
+ ) })
201
+ ] });
202
+ };
203
+ const ALLOWED_COLUMNS = /* @__PURE__ */ new Set([1, 2, 3, 4, 6]);
204
+ function getGridItemSpans(columns, stackBelow = "medium") {
205
+ const count = ALLOWED_COLUMNS.has(columns) ? columns : 2;
206
+ const col = 12 / count;
207
+ const twoUp = count >= 2 ? 6 : 12;
208
+ if (stackBelow === "small") {
209
+ return { xs: 12, s: twoUp, m: twoUp, col };
210
+ }
211
+ return { xs: 12, s: 12, m: twoUp, col };
212
+ }
213
+ const EqualGrid = ({ columns = 2, stackBelow = "medium", gap = 6, label, children }) => {
214
+ const spans = getGridItemSpans(columns, stackBelow);
215
+ const items = Children.toArray(children).filter(Boolean);
216
+ return /* @__PURE__ */ jsx(
217
+ Grid.Root,
218
+ {
219
+ gap,
220
+ role: label ? "group" : void 0,
221
+ "aria-label": label,
222
+ "data-equal-grid": columns,
223
+ children: items.map((child, index2) => /* @__PURE__ */ jsx(
224
+ Grid.Item,
225
+ {
226
+ col: spans.col,
227
+ m: spans.m,
228
+ s: spans.s,
229
+ xs: spans.xs,
230
+ direction: "column",
231
+ alignItems: "stretch",
232
+ minWidth: 0,
233
+ children: child
234
+ },
235
+ child.key ?? index2
236
+ ))
237
+ }
238
+ );
239
+ };
240
+ const STAT_GRID_FOLD_REM = (4 * 200 + 3 * 16) / 10;
241
+ const DS_SMALL_REM = 52;
242
+ const StatGridFrame = styled.div`
243
+ container-type: inline-size;
244
+ min-width: 0;
245
+
246
+ @container (min-width: ${DS_SMALL_REM}rem) and (max-width: ${STAT_GRID_FOLD_REM - 0.01}rem) {
247
+ [data-equal-grid='4'] > * {
248
+ grid-column: span 6;
249
+ }
250
+ }
251
+
252
+ /* Rows without secondary lines: pin every value to the card bottom, so a
253
+ label that wraps onto two lines does not push its value off the row's line. */
254
+ &[data-align-values] [data-stat-body] {
255
+ flex: 1 1 auto;
256
+ }
257
+
258
+ &[data-align-values] [data-stat-text] {
259
+ justify-content: space-between;
260
+ }
261
+ `;
262
+ const StatGrid = ({ columns = 4, label, alignValues = false, children }) => /* @__PURE__ */ jsx(StatGridFrame, { "data-stat-grid": "", "data-align-values": alignValues ? "" : void 0, children: /* @__PURE__ */ jsx(EqualGrid, { columns, stackBelow: "small", gap: 4, label, children }) });
263
+ const IconTile = styled(Flex)`
264
+ align-self: flex-start;
265
+
266
+ svg {
267
+ width: ${({ theme }) => theme.spaces[5]};
268
+ height: ${({ theme }) => theme.spaces[5]};
269
+ }
270
+
271
+ svg path {
272
+ fill: ${({ theme, $tone }) => theme.colors[`${$tone}600`]};
273
+ }
274
+ `;
275
+ const STAT_TONES = /* @__PURE__ */ new Set([
276
+ "primary",
277
+ "success",
278
+ "warning",
279
+ "danger",
280
+ "neutral",
281
+ "secondary",
282
+ "alternative"
283
+ ]);
284
+ const CardButton = styled(Box)`
285
+ appearance: none;
286
+ font: inherit;
287
+ color: inherit;
288
+ text-align: start;
289
+ cursor: pointer;
290
+ width: 100%;
291
+
292
+ &:hover {
293
+ background: ${({ theme }) => theme.colors.primary100};
294
+ }
295
+ `;
296
+ const StatCard = ({
297
+ label,
298
+ value,
299
+ icon: Icon,
300
+ tone = "neutral",
301
+ description,
302
+ onClick,
303
+ pressed,
304
+ actionLabel
305
+ }) => {
306
+ const safeTone = STAT_TONES.has(tone) ? tone : "neutral";
307
+ const clickable = typeof onClick === "function";
308
+ const buttonProps = clickable ? {
309
+ tag: "button",
310
+ type: "button",
311
+ onClick,
312
+ "aria-pressed": Boolean(pressed),
313
+ "aria-label": actionLabel
314
+ } : {};
315
+ const Card = clickable ? CardButton : Box;
316
+ return /* @__PURE__ */ jsx(
317
+ Card,
318
+ {
319
+ ...buttonProps,
320
+ background: "neutral0",
321
+ hasRadius: true,
322
+ shadow: "tableShadow",
323
+ borderColor: clickable ? pressed ? "primary600" : "neutral150" : void 0,
324
+ padding: 4,
325
+ flex: "1 1 auto",
326
+ minWidth: 0,
327
+ "data-stat-card": safeTone,
328
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, height: "100%", children: [
329
+ /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "stretch", minWidth: 0, "data-stat-body": "", children: [
330
+ Icon ? /* @__PURE__ */ jsx(
331
+ IconTile,
332
+ {
333
+ $tone: safeTone,
334
+ background: `${safeTone}100`,
335
+ hasRadius: true,
336
+ padding: 2,
337
+ shrink: 0,
338
+ justifyContent: "center",
339
+ alignItems: "center",
340
+ "aria-hidden": true,
341
+ children: /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, focusable: false })
342
+ }
343
+ ) : null,
344
+ /* @__PURE__ */ jsxs(
345
+ Flex,
346
+ {
347
+ direction: "column",
348
+ alignItems: "flex-start",
349
+ gap: 1,
350
+ minWidth: 0,
351
+ flex: "1 1 auto",
352
+ "data-stat-text": "",
353
+ children: [
354
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", tag: "span", children: label }),
355
+ /* @__PURE__ */ jsx(Typography, { variant: "beta", textColor: "neutral800", tag: "span", children: value })
356
+ ]
357
+ }
358
+ )
359
+ ] }),
360
+ description ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", tag: "span", children: description }) : null
361
+ ] })
362
+ }
363
+ );
364
+ };
365
+ const MISSING_VALUE_GLYPH = "—";
366
+ const MISSING_VALUE_MESSAGE = Object.freeze({
367
+ messageId: "common.value.missing",
368
+ defaultMessage: "Not available"
369
+ });
370
+ function isMissingValue(value) {
371
+ if (value === null || value === void 0) return true;
372
+ if (typeof value === "number") return !Number.isFinite(value);
373
+ if (value instanceof Date) return !Number.isFinite(value.getTime());
374
+ if (typeof value === "string") {
375
+ const trimmed = value.trim();
376
+ return trimmed === "" || trimmed.toLowerCase() === "unknown";
377
+ }
378
+ return false;
379
+ }
380
+ function presentText(value) {
381
+ if (isMissingValue(value)) return "";
382
+ return String(value).trim();
383
+ }
384
+ const getTranslation = (id) => `${PLUGIN_ID}.${id}`;
385
+ const MissingValue = ({ textColor = "neutral600", variant }) => {
386
+ const { formatMessage } = useIntl();
387
+ const label = formatMessage({
388
+ id: getTranslation(MISSING_VALUE_MESSAGE.messageId),
389
+ defaultMessage: MISSING_VALUE_MESSAGE.defaultMessage
390
+ });
391
+ return /* @__PURE__ */ jsxs(Typography, { textColor, variant, "data-missing-value": "", children: [
392
+ /* @__PURE__ */ jsx("span", { "aria-hidden": "true", children: MISSING_VALUE_GLYPH }),
393
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: label })
394
+ ] });
395
+ };
396
+ const ValueOrMissing = ({ value, children, textColor, variant }) => {
397
+ if (isMissingValue(value)) return /* @__PURE__ */ jsx(MissingValue, { textColor, variant });
398
+ return /* @__PURE__ */ jsx(Fragment, { children: children ?? String(value) });
399
+ };
400
+ const List = styled.dl`
401
+ display: grid;
402
+ grid-template-columns: minmax(0, 1fr);
403
+ gap: ${({ theme }) => theme.spaces[4]};
404
+ column-gap: ${({ theme, $columnGap }) => theme.spaces[$columnGap ?? 4]};
405
+ margin: 0;
406
+ min-width: 0;
407
+
408
+ ${({ theme }) => theme.breakpoints.small} {
409
+ grid-template-columns: repeat(${({ $columns }) => $columns}, minmax(0, 1fr));
410
+ }
411
+
412
+ & > div {
413
+ display: flex;
414
+ flex-direction: column;
415
+ gap: ${({ theme }) => theme.spaces[1]};
416
+ min-width: 0;
417
+ }
418
+
419
+ & > div[data-span='full'] {
420
+ grid-column: 1 / -1;
421
+ }
422
+
423
+ dt,
424
+ dd {
425
+ margin: 0;
426
+ min-width: 0;
427
+ }
428
+
429
+ dd {
430
+ overflow-wrap: break-word;
431
+ }
432
+
433
+ dd[data-wrap='anywhere'] {
434
+ overflow-wrap: anywhere;
435
+ }
436
+ `;
437
+ const PropertyList = ({ items = [], columns = 2, label, columnGap }) => /* @__PURE__ */ jsx(
438
+ List,
439
+ {
440
+ $columns: columns === 1 ? 1 : 2,
441
+ $columnGap: columnGap,
442
+ "aria-label": label,
443
+ "data-property-list": "",
444
+ children: items.filter(Boolean).map((item) => {
445
+ const wrapsAnywhere = item.kind === "id" || item.kind === "email";
446
+ const missing = item.render === void 0 && isMissingValue(item.value);
447
+ return /* @__PURE__ */ jsxs("div", { "data-span": item.fullWidth ? "full" : void 0, children: [
448
+ /* @__PURE__ */ jsx("dt", { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: item.label }) }),
449
+ /* @__PURE__ */ jsx("dd", { "data-wrap": wrapsAnywhere ? "anywhere" : void 0, children: missing ? /* @__PURE__ */ jsx(MissingValue, { variant: "omega" }) : item.render ?? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: String(item.value) }) })
450
+ ] }, item.id);
451
+ })
452
+ }
453
+ );
454
+ const DEFAULT_DATE_OPTIONS = Object.freeze({ dateStyle: "medium", timeStyle: "short" });
455
+ const RELATIVE_UNITS = [
456
+ ["year", 365 * 24 * 60 * 60],
457
+ ["month", 30 * 24 * 60 * 60],
458
+ ["week", 7 * 24 * 60 * 60],
459
+ ["day", 24 * 60 * 60],
460
+ ["hour", 60 * 60],
461
+ ["minute", 60],
462
+ ["second", 1]
463
+ ];
464
+ function toValidDate(value) {
465
+ if (value === null || value === void 0 || value === "") return null;
466
+ const date = value instanceof Date ? value : new Date(value);
467
+ return Number.isFinite(date.getTime()) ? date : null;
468
+ }
469
+ function formatSessionDate(value, locale, fallback = "", options = DEFAULT_DATE_OPTIONS) {
470
+ const date = toValidDate(value);
471
+ if (!date) return fallback;
472
+ try {
473
+ return new Intl.DateTimeFormat(locale || "en", options).format(date);
474
+ } catch {
475
+ return new Intl.DateTimeFormat("en", options).format(date);
476
+ }
477
+ }
478
+ function getRelativeTimeParts(value, now = Date.now()) {
479
+ const date = toValidDate(value);
480
+ const reference = toValidDate(now);
481
+ if (!date || !reference) return null;
482
+ const diffSeconds = Math.round((date.getTime() - reference.getTime()) / 1e3);
483
+ const absolute = Math.abs(diffSeconds);
484
+ if (absolute < 45) return { value: 0, unit: "second" };
485
+ for (const [unit, seconds] of RELATIVE_UNITS) {
486
+ if (absolute >= seconds) {
487
+ const amount = Math.round(diffSeconds / seconds);
488
+ return { value: amount === 0 ? Math.sign(diffSeconds) : amount, unit };
489
+ }
490
+ }
491
+ return { value: 0, unit: "second" };
492
+ }
493
+ function formatRelative(value, locale, { now = Date.now(), fallback = "" } = {}) {
494
+ const parts = getRelativeTimeParts(value, now);
495
+ if (!parts) return fallback;
496
+ const options = { numeric: "auto" };
497
+ try {
498
+ return new Intl.RelativeTimeFormat(locale || "en", options).format(parts.value, parts.unit);
499
+ } catch {
500
+ return new Intl.RelativeTimeFormat("en", options).format(parts.value, parts.unit);
501
+ }
502
+ }
503
+ const API_CLIENTS = [
504
+ ["curl/", "cURL"],
505
+ ["postman", "Postman"],
506
+ ["insomnia", "Insomnia"],
507
+ ["okhttp", "OkHttp"],
508
+ ["python-requests", "Python Requests"],
509
+ ["axios/", "Axios"],
510
+ ["node-fetch", "node-fetch"],
511
+ ["undici", "undici"],
512
+ ["go-http-client", "Go HTTP client"],
513
+ ["cfnetwork/", "CFNetwork"],
514
+ ["dart/", "Dart"],
515
+ ["java/", "Java"],
516
+ ["wget/", "Wget"],
517
+ ["httpie/", "HTTPie"]
518
+ ];
519
+ const RUNTIME_AGENTS = Object.freeze({ node: "Node.js", deno: "Deno", bun: "Bun" });
520
+ const BOT_PATTERN = /bot\b|crawler|spider|slurp|headlesschrome/i;
521
+ const TABLET_PATTERN = /(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i;
522
+ const MOBILE_PATTERN = /Mobile|Android|iP(?:hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(?:hpw|web)OS|Opera M(?:obi|ini)/;
523
+ const LEGACY_DEVICE_LABELS = Object.freeze({
524
+ desktop: "Desktop",
525
+ mobile: "Mobile",
526
+ tablet: "Tablet",
527
+ api: "API Client",
528
+ bot: "Bot",
529
+ "": ""
530
+ });
531
+ const detectBrowser = (ua) => {
532
+ if (ua.includes("edg/") || ua.includes("edga/") || ua.includes("edgios/")) return "Edge";
533
+ if (ua.includes("opr/") || ua.includes("opera")) return "Opera";
534
+ if (ua.includes("firefox/") || ua.includes("fxios/")) return "Firefox";
535
+ if (ua.includes("chrome/") || ua.includes("crios/")) return "Chrome";
536
+ if (ua.includes("safari/")) return "Safari";
537
+ return "";
538
+ };
539
+ const detectOs = (ua) => {
540
+ if (ua.includes("android")) return "Android";
541
+ if (ua.includes("iphone") || ua.includes("ipad") || ua.includes("ipod")) return "iOS";
542
+ if (ua.includes("windows")) return "Windows";
543
+ if (ua.includes("cros")) return "ChromeOS";
544
+ if (ua.includes("mac os x") || ua.includes("macintosh")) return "macOS";
545
+ if (ua.includes("linux") || ua.includes("x11")) return "Linux";
546
+ return "";
547
+ };
548
+ const DESKTOP_OPERATING_SYSTEMS = /* @__PURE__ */ new Set(["Windows", "macOS", "Linux", "ChromeOS"]);
549
+ function parseUserAgent(userAgent) {
550
+ const raw = typeof userAgent === "string" ? userAgent.trim() : "";
551
+ if (!raw || raw.toLowerCase() === "unknown") {
552
+ return { deviceType: "", device: "", deviceIcon: "unknown", browser: "", os: "" };
553
+ }
554
+ const ua = raw.toLowerCase();
555
+ const runtime = RUNTIME_AGENTS[ua.split("/")[0]];
556
+ if (runtime && !ua.includes(" ")) {
557
+ return {
558
+ deviceType: "api",
559
+ device: LEGACY_DEVICE_LABELS.api,
560
+ deviceIcon: "api",
561
+ browser: runtime,
562
+ os: ""
563
+ };
564
+ }
565
+ const apiClient = API_CLIENTS.find(([needle]) => ua.includes(needle));
566
+ if (apiClient) {
567
+ return {
568
+ deviceType: "api",
569
+ device: LEGACY_DEVICE_LABELS.api,
570
+ deviceIcon: "api",
571
+ browser: apiClient[1],
572
+ os: detectOs(ua)
573
+ };
574
+ }
575
+ const browser = detectBrowser(ua);
576
+ const os = detectOs(ua);
577
+ let deviceType = "";
578
+ if (BOT_PATTERN.test(raw)) deviceType = "bot";
579
+ else if (TABLET_PATTERN.test(raw)) deviceType = "tablet";
580
+ else if (MOBILE_PATTERN.test(raw)) deviceType = "mobile";
581
+ else if (DESKTOP_OPERATING_SYSTEMS.has(os)) deviceType = "desktop";
582
+ return {
583
+ deviceType,
584
+ device: LEGACY_DEVICE_LABELS[deviceType],
585
+ deviceIcon: deviceType || "unknown",
586
+ browser,
587
+ os
588
+ };
589
+ }
590
+ const BROWSER_VERSION_PATTERNS = [
591
+ /\bEdg(?:A|iOS)?\/([\d.]+)/i,
592
+ /\bOPR\/([\d.]+)/i,
593
+ /\b(?:Chrome|CriOS)\/([\d.]+)/i,
594
+ /\bFirefox\/([\d.]+)/i,
595
+ /\bVersion\/([\d.]+).*Safari/i
596
+ ];
597
+ function getBrowserVersionFromUserAgent(userAgent) {
598
+ if (typeof userAgent !== "string" || !userAgent.trim() || userAgent.trim().toLowerCase() === "unknown") {
599
+ return "";
600
+ }
601
+ for (const pattern of BROWSER_VERSION_PATTERNS) {
602
+ const match = userAgent.match(pattern);
603
+ if (match?.[1]) return match[1];
604
+ }
605
+ return "";
606
+ }
607
+ const DEVICE_TYPE_MESSAGES = Object.freeze({
608
+ desktop: Object.freeze({ messageId: "common.device.type.desktop", defaultMessage: "Desktop" }),
609
+ mobile: Object.freeze({ messageId: "common.device.type.mobile", defaultMessage: "Mobile" }),
610
+ tablet: Object.freeze({ messageId: "common.device.type.tablet", defaultMessage: "Tablet" }),
611
+ api: Object.freeze({ messageId: "common.device.type.api", defaultMessage: "API client" }),
612
+ bot: Object.freeze({ messageId: "common.device.type.bot", defaultMessage: "Bot" }),
613
+ unknown: Object.freeze({
614
+ messageId: "common.device.type.unknown",
615
+ defaultMessage: "Unknown device"
616
+ })
617
+ });
618
+ const DEVICE_SUMMARY_MESSAGE = Object.freeze({
619
+ messageId: "common.device.summary",
620
+ defaultMessage: "{browser} · {os}"
621
+ });
622
+ const DEVICE_TYPE_ALIASES = Object.freeze({
623
+ desktop: "desktop",
624
+ laptop: "desktop",
625
+ pc: "desktop",
626
+ computer: "desktop",
627
+ mobile: "mobile",
628
+ phone: "mobile",
629
+ smartphone: "mobile",
630
+ tablet: "tablet",
631
+ "api client": "api",
632
+ api: "api",
633
+ apiclient: "api",
634
+ bot: "bot",
635
+ crawler: "bot"
636
+ });
637
+ function normalizeDeviceType(value) {
638
+ if (typeof value !== "string") return "";
639
+ const key = value.trim().toLowerCase().replace(/[\s_-]+/g, " ");
640
+ return DEVICE_TYPE_ALIASES[key] || DEVICE_TYPE_ALIASES[key.replace(/ /g, "")] || "";
641
+ }
642
+ function getDeviceTypeMessage(deviceType) {
643
+ return DEVICE_TYPE_MESSAGES[deviceType] || DEVICE_TYPE_MESSAGES.unknown;
644
+ }
645
+ const TRAILING_VERSION = /\s+v?\d[\w./-]*$/i;
646
+ function splitNameAndVersion(value) {
647
+ let name2 = presentText(value);
648
+ const versions = [];
649
+ while (TRAILING_VERSION.test(name2)) {
650
+ const match = name2.match(TRAILING_VERSION);
651
+ versions.unshift(match[0].trim());
652
+ name2 = name2.slice(0, match.index).trim();
653
+ }
654
+ return { name: presentText(name2), version: versions.join(" ") };
655
+ }
656
+ function getDevicePresentation(session = {}) {
657
+ const row = session || {};
658
+ const userAgent = presentText(row.userAgent);
659
+ const parsed = userAgent ? parseUserAgent(userAgent) : null;
660
+ const storedBrowser = splitNameAndVersion(row.browserName);
661
+ const storedOs = splitNameAndVersion(row.osName);
662
+ const deviceType = parsed ? parsed.deviceType : normalizeDeviceType(row.deviceType);
663
+ const browser = parsed?.browser || storedBrowser.name;
664
+ const os = parsed?.os || storedOs.name;
665
+ const browserVersion = userAgent && getBrowserVersionFromUserAgent(userAgent) || presentText(row.browserVersion) || storedBrowser.version;
666
+ let summary = { text: "" };
667
+ if (browser && os) {
668
+ summary = { ...DEVICE_SUMMARY_MESSAGE, values: { browser, os } };
669
+ } else if (browser || os) {
670
+ summary = { text: browser || os };
671
+ }
672
+ return {
673
+ deviceType,
674
+ hasDeviceType: Boolean(deviceType),
675
+ icon: deviceType || "unknown",
676
+ deviceTypeMessage: getDeviceTypeMessage(deviceType),
677
+ browser,
678
+ browserVersion,
679
+ browserLabel: browser,
680
+ os,
681
+ hasSummary: Boolean(browser || os),
682
+ summary
683
+ };
684
+ }
685
+ const SESSION_STATES = Object.freeze(["active", "idle", "ended"]);
686
+ const SESSION_END_REASONS = Object.freeze([
687
+ "logout",
688
+ "idle",
689
+ "expired",
690
+ "manual",
691
+ "blocked",
692
+ "unrecorded"
693
+ ]);
694
+ const RECORDED_END_REASONS = /* @__PURE__ */ new Set(["logout", "idle", "expired", "manual", "blocked"]);
695
+ const ACTIVE_DEFINITION = Object.freeze({
696
+ messageId: "common.status.active.definition",
697
+ defaultMessage: "Open and used within the inactivity timeout."
698
+ });
699
+ const SESSION_STATUS_PRESENTATION = Object.freeze({
700
+ active: Object.freeze({
701
+ tone: "success",
702
+ messageId: "common.status.active",
703
+ defaultMessage: "Active",
704
+ // B.3 tooltip and A.3 definition are the same sentence: one message.
705
+ help: ACTIVE_DEFINITION,
706
+ definition: ACTIVE_DEFINITION
707
+ }),
708
+ idle: Object.freeze({
709
+ tone: "warning",
710
+ messageId: "common.status.idle",
711
+ defaultMessage: "Idle",
712
+ help: Object.freeze({
713
+ messageId: "common.status.idle.help",
714
+ defaultMessage: "Still open. It ends on its next request or at the next idle check. A token refresh makes it active again."
715
+ }),
716
+ definition: Object.freeze({
717
+ messageId: "common.status.idle.definition",
718
+ defaultMessage: "Open, but not used for longer than the inactivity timeout. It ends on its next request or at the next idle check. A token refresh makes it active again."
719
+ })
720
+ }),
721
+ ended: Object.freeze({
722
+ tone: "neutral",
723
+ messageId: "common.status.ended",
724
+ defaultMessage: "Ended",
725
+ help: null,
726
+ definition: Object.freeze({
727
+ messageId: "common.status.ended.definition",
728
+ defaultMessage: "The session can no longer be used. The user has to sign in again on this device."
729
+ })
730
+ })
731
+ });
732
+ const SESSION_END_REASON_PRESENTATION = Object.freeze({
733
+ logout: Object.freeze({
734
+ messageId: "common.endReason.logout",
735
+ defaultMessage: "Logged out",
736
+ description: Object.freeze({
737
+ messageId: "common.endReason.logout.description",
738
+ defaultMessage: "The user signed out."
739
+ })
740
+ }),
741
+ idle: Object.freeze({
742
+ messageId: "common.endReason.idle",
743
+ defaultMessage: "Timed out",
744
+ description: Object.freeze({
745
+ messageId: "common.endReason.idle.description",
746
+ defaultMessage: "Not used for longer than the inactivity timeout."
747
+ })
748
+ }),
749
+ expired: Object.freeze({
750
+ messageId: "common.endReason.expired",
751
+ defaultMessage: "Expired",
752
+ description: Object.freeze({
753
+ messageId: "common.endReason.expired.description",
754
+ defaultMessage: "Reached the maximum session age."
755
+ })
756
+ }),
757
+ manual: Object.freeze({
758
+ messageId: "common.endReason.manual",
759
+ defaultMessage: "Ended manually",
760
+ description: Object.freeze({
761
+ messageId: "common.endReason.manual.description",
762
+ defaultMessage: "Ended from the Strapi admin, or by the user from another of their devices."
763
+ })
764
+ }),
765
+ blocked: Object.freeze({
766
+ messageId: "common.endReason.blocked",
767
+ defaultMessage: "User blocked",
768
+ description: Object.freeze({
769
+ messageId: "common.endReason.blocked.description",
770
+ defaultMessage: "Ended because the user account was blocked."
771
+ })
772
+ }),
773
+ unrecorded: Object.freeze({
774
+ messageId: "common.endReason.unrecorded",
775
+ defaultMessage: "Reason not recorded",
776
+ description: Object.freeze({
777
+ messageId: "common.endReason.unrecorded.description",
778
+ defaultMessage: "No end reason was stored, for example because the session ended in Strapi’s own session store or was recorded by an older plugin version."
779
+ })
780
+ })
781
+ });
782
+ function getSessionState(session = {}) {
783
+ const row = session || {};
784
+ if (row.isActive === true) return row.isTrulyActive ? "active" : "idle";
785
+ return "ended";
786
+ }
787
+ function getSessionStatus(session = {}) {
788
+ return getSessionState(session);
789
+ }
790
+ function getSessionEndReason(session = {}) {
791
+ const row = session || {};
792
+ if (row.isActive === true) return null;
793
+ const reason = typeof row.terminationReason === "string" ? row.terminationReason.trim().toLowerCase() : "";
794
+ return RECORDED_END_REASONS.has(reason) ? (
795
+ /** @type {any} */
796
+ reason
797
+ ) : "unrecorded";
798
+ }
799
+ function isNativeOnlySession(session) {
800
+ const id = session?.id;
801
+ return typeof id === "string" && id.startsWith("native_");
802
+ }
803
+ function isSessionStatus(status) {
804
+ return SESSION_STATES.includes(
805
+ /** @type {any} */
806
+ status
807
+ );
808
+ }
809
+ function isSessionEndReason(reason) {
810
+ return SESSION_END_REASONS.includes(
811
+ /** @type {any} */
812
+ reason
813
+ );
814
+ }
815
+ function getSessionStatusPresentation(statusOrSession) {
816
+ const status = typeof statusOrSession === "string" ? statusOrSession : getSessionState(statusOrSession);
817
+ const key = isSessionStatus(status) ? status : "ended";
818
+ return { status: key, ...SESSION_STATUS_PRESENTATION[key] };
819
+ }
820
+ function getEndReasonPresentation(reason) {
821
+ const key = isSessionEndReason(reason) ? reason : "unrecorded";
822
+ return { reason: key, ...SESSION_END_REASON_PRESENTATION[key] };
823
+ }
824
+ function getSessionEndReasonPresentation(session) {
825
+ const reason = getSessionEndReason(session);
826
+ return reason ? getEndReasonPresentation(reason) : null;
827
+ }
828
+ function useSessionFormatters() {
829
+ const { formatMessage, locale } = useIntl();
830
+ const translate = useCallback(
831
+ (descriptor, values) => formatMessage(
832
+ { id: getTranslation(descriptor.messageId), defaultMessage: descriptor.defaultMessage },
833
+ values
834
+ ),
835
+ [formatMessage]
836
+ );
837
+ return useMemo(() => {
838
+ const formatDate = (value, options) => formatSessionDate(value, locale, MISSING_VALUE_GLYPH, options);
839
+ const formatRelativeTime = (value, now) => formatRelative(value, locale, { now: now ?? Date.now(), fallback: MISSING_VALUE_GLYPH });
840
+ const statusLabel = (statusOrSession) => translate(getSessionStatusPresentation(statusOrSession));
841
+ const endReasonLabel = (sessionOrReason) => {
842
+ const reason = typeof sessionOrReason === "string" ? getEndReasonPresentation(sessionOrReason) : getSessionEndReasonPresentation(sessionOrReason);
843
+ return reason ? translate(reason) : "";
844
+ };
845
+ const deviceTypeLabel = (session) => translate(getDevicePresentation(session).deviceTypeMessage);
846
+ const deviceSummary = (session) => {
847
+ const { summary } = getDevicePresentation(session);
848
+ return summary.text ?? translate(summary, summary.values);
849
+ };
850
+ return {
851
+ locale,
852
+ formatDate,
853
+ formatRelativeTime,
854
+ translate,
855
+ statusLabel,
856
+ endReasonLabel,
857
+ deviceTypeLabel,
858
+ deviceSummary
859
+ };
860
+ }, [locale, translate]);
861
+ }
862
+ const NoWrap$1 = styled.span`
863
+ white-space: nowrap;
864
+ `;
865
+ const StatusDetail = ({ session, status }) => {
866
+ const { formatMessage } = useIntl();
867
+ const { formatDate, formatRelativeTime, endReasonLabel } = useSessionFormatters();
868
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
869
+ let text;
870
+ if (status === "ended") {
871
+ const endedAt = toValidDate(session.logoutTime);
872
+ text = t("common.status.ended.detail", "{reason} · {endedAt}", {
873
+ reason: /* @__PURE__ */ jsx(NoWrap$1, { children: endReasonLabel(session) }, "reason"),
874
+ endedAt: endedAt ? /* @__PURE__ */ jsx(NoWrap$1, { children: formatDate(endedAt) }, "ended-at") : /* @__PURE__ */ jsx(MissingValue, { variant: "pi" }, "ended-at")
875
+ });
876
+ } else {
877
+ const minutes = Number(session.minutesSinceActive);
878
+ const hasMinutes = session.minutesSinceActive !== null && session.minutesSinceActive !== void 0 && Number.isFinite(minutes);
879
+ text = status === "idle" && hasMinutes ? t("common.status.idle.detail", "Not used for {minutes} min", { minutes }) : t("common.status.active.detail", "Last active {time}", {
880
+ time: formatRelativeTime(session.lastActive || session.loginTime)
881
+ });
882
+ }
883
+ return /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", "data-status-detail": "", children: text });
884
+ };
885
+ const getBadgeColors = (tone) => tone === "warning" ? { backgroundColor: "warning200", textColor: "neutral800" } : { variant: tone };
886
+ const StatusBadge = ({ status, session, detail = false, showEndReason = false, size = "M" }) => {
887
+ const { formatMessage } = useIntl();
888
+ const presentation = getSessionStatusPresentation(status || session || {});
889
+ const translate = (descriptor) => formatMessage({
890
+ id: getTranslation(descriptor.messageId),
891
+ defaultMessage: descriptor.defaultMessage
892
+ });
893
+ const label = translate(presentation);
894
+ const badge = /* @__PURE__ */ jsx(
895
+ Badge,
896
+ {
897
+ ...getBadgeColors(presentation.tone),
898
+ size,
899
+ "data-session-status": presentation.status,
900
+ children: label
901
+ }
902
+ );
903
+ if (!(detail || showEndReason) || !session) return badge;
904
+ const reason = presentation.status === "ended" ? getSessionEndReasonPresentation(session) : null;
905
+ const help = reason ? reason.description : presentation.help;
906
+ const native = isNativeOnlySession(session);
907
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
908
+ /* @__PURE__ */ jsxs(Flex, { gap: 1, alignItems: "center", wrap: "wrap", children: [
909
+ help ? /* @__PURE__ */ jsx(Tooltip, { label: translate(help), children: /* @__PURE__ */ jsx("span", { children: badge }) }) : badge,
910
+ native ? /* @__PURE__ */ jsx(
911
+ Tooltip,
912
+ {
913
+ label: formatMessage({
914
+ id: getTranslation("common.status.nativeSession.help"),
915
+ defaultMessage: "Created by Strapi’s own session store. No device or location details were recorded."
916
+ }),
917
+ children: /* @__PURE__ */ jsx("span", { children: /* @__PURE__ */ jsx(Badge, { variant: "neutral", size, "data-native-session": "", children: formatMessage({
918
+ id: getTranslation("common.status.nativeSession"),
919
+ defaultMessage: "Strapi session"
920
+ }) }) })
921
+ }
922
+ ) : null
923
+ ] }),
924
+ /* @__PURE__ */ jsx(StatusDetail, { session, status: presentation.status })
925
+ ] });
926
+ };
927
+ const canTakeFocus = (element) => Boolean(
928
+ element?.isConnected && typeof element.focus === "function" && !element.disabled && element.getAttribute?.("aria-disabled") !== "true"
929
+ );
930
+ function pickFocusTarget(opener, fallback) {
931
+ if (canTakeFocus(opener)) return opener;
932
+ return canTakeFocus(fallback) ? fallback : null;
933
+ }
934
+ function restoreDialogFocus(event, opener, fallback) {
935
+ const target = pickFocusTarget(opener, fallback);
936
+ if (!target) return;
937
+ event.preventDefault();
938
+ target.focus();
939
+ }
940
+ function refocusIfLost(opener, fallback, doc = typeof document === "undefined" ? void 0 : document) {
941
+ if (!doc) return;
942
+ const active = doc.activeElement;
943
+ if (active && active !== doc.body) return;
944
+ pickFocusTarget(opener, fallback)?.focus();
945
+ }
946
+ const ConfirmAction = ({
947
+ trigger,
948
+ title,
949
+ body,
950
+ confirmLabel,
951
+ onConfirm,
952
+ variant = "danger",
953
+ disabled = false,
954
+ fallbackFocusRef,
955
+ isOpen,
956
+ onOpenChange,
957
+ returnFocusRef
958
+ }) => {
959
+ const [internalOpen, setInternalOpen] = useState(false);
960
+ const [busy, setBusy] = useState(false);
961
+ const triggerRef = useRef(null);
962
+ const controlled = !trigger;
963
+ const open = controlled ? Boolean(isOpen) : internalOpen;
964
+ const restoreFocus = () => {
965
+ if (typeof window === "undefined") return;
966
+ window.requestAnimationFrame(() => {
967
+ const active = document.activeElement;
968
+ if (active && active !== document.body) return;
969
+ const ownTrigger = controlled ? returnFocusRef?.current : triggerRef.current;
970
+ const target = pickFocusTarget(ownTrigger, fallbackFocusRef?.current);
971
+ if (target) target.focus();
972
+ });
973
+ };
974
+ const setOpen = (next) => {
975
+ if (controlled) onOpenChange?.(next);
976
+ else setInternalOpen(next);
977
+ };
978
+ const handleOpenChange = (next) => {
979
+ if (busy) return;
980
+ setOpen(next);
981
+ if (!next) restoreFocus();
982
+ };
983
+ const handleConfirm = async (event) => {
984
+ event?.preventDefault?.();
985
+ setBusy(true);
986
+ try {
987
+ await onConfirm();
988
+ setOpen(false);
989
+ restoreFocus();
990
+ } catch {
991
+ } finally {
992
+ setBusy(false);
993
+ }
994
+ };
995
+ return /* @__PURE__ */ jsxs(Dialog.Root, { open, onOpenChange: handleOpenChange, children: [
996
+ trigger ? /* @__PURE__ */ jsx(Dialog.Trigger, { ref: triggerRef, disabled, children: trigger }) : null,
997
+ /* @__PURE__ */ jsx(
998
+ ConfirmDialog,
999
+ {
1000
+ title,
1001
+ variant,
1002
+ endAction: /* @__PURE__ */ jsx(
1003
+ Button,
1004
+ {
1005
+ fullWidth: true,
1006
+ variant,
1007
+ onClick: handleConfirm,
1008
+ loading: busy,
1009
+ disabled: busy,
1010
+ children: confirmLabel
1011
+ }
1012
+ ),
1013
+ children: body
1014
+ }
1015
+ )
1016
+ ] });
1017
+ };
1018
+ const DEVICE_ICONS = {
1019
+ desktop: Monitor,
1020
+ mobile: Phone,
1021
+ tablet: Phone,
1022
+ api: Code,
1023
+ bot: Server,
1024
+ unknown: Information
1025
+ };
1026
+ const DeviceIcon = ({ icon }) => {
1027
+ const Icon = DEVICE_ICONS[icon] || Information;
1028
+ return /* @__PURE__ */ jsx(Icon, { "aria-hidden": true, focusable: false });
1029
+ };
1030
+ const TargetLink = styled(Link)`
1031
+ min-height: 3.2rem;
1032
+ display: inline-flex;
1033
+ align-items: center;
1034
+ align-self: flex-start;
1035
+ `;
1036
+ const ActionStack = styled.div`
1037
+ display: grid;
1038
+ grid-template-columns: minmax(0, 1fr);
1039
+ grid-auto-rows: 1fr;
1040
+ gap: ${({ theme }) => theme.spaces[2]};
1041
+ min-width: 0;
1042
+
1043
+ /* The buttons are the plugin's own children; wrapped labels centre
1044
+ through inheritance, not through a selector into the DS button. */
1045
+ & > button {
1046
+ height: auto;
1047
+ min-height: 3.2rem;
1048
+ padding-block: ${({ theme }) => theme.spaces[1]};
1049
+ text-align: center;
1050
+ }
1051
+ `;
1052
+ const pluginPermissions = {
1053
+ access: [{ action: `plugin::${pluginId$1}.access`, subject: null }],
1054
+ /** Strapi admin panel sessions (view). The server also requires `access`. */
1055
+ adminSessionsRead: [{ action: `plugin::${pluginId$1}.admin-sessions.read`, subject: null }],
1056
+ /** Signing admins out. The server also requires `access` and `admin-sessions.read`. */
1057
+ adminSessionsRevoke: [{ action: `plugin::${pluginId$1}.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$1}.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$1}.settings.update`, subject: null }],
1065
+ /**
1066
+ * App-user security activity (4.22): failed sign-ins, lockouts, new devices,
1067
+ * impersonations ... of Users & Permissions accounts, and its export. The
1068
+ * server also requires `access`.
1069
+ */
1070
+ userActivityRead: [{ action: `plugin::${pluginId$1}.user-activity.read`, subject: null }],
1071
+ /** Lifting a sign-in lock. The server also requires `access`. */
1072
+ lockoutsUnlock: [{ action: `plugin::${pluginId$1}.lockouts.unlock`, subject: null }],
1073
+ /**
1074
+ * Impersonating app users (4.20): start, list and end. The server also
1075
+ * requires `access` and the Impersonation switch.
1076
+ */
1077
+ impersonateUsers: [{ action: `plugin::${pluginId$1}.impersonate.users`, subject: null }],
1078
+ /**
1079
+ * "View as admin" (4.20): the read-only permission preview of another
1080
+ * admin. The server also requires `access`, the switch and the
1081
+ * anti-escalation rules.
1082
+ */
1083
+ impersonateAdmins: [{ action: `plugin::${pluginId$1}.impersonate.admins`, subject: null }]
1084
+ };
1085
+ const SAFE_SCOPE = /^[A-Za-z0-9_.:-]{1,48}$/;
1086
+ const CANCEL_NAMES = /* @__PURE__ */ new Set(["AbortError", "TimeoutError", "CanceledError"]);
1087
+ function safeGet(value, key) {
1088
+ try {
1089
+ return value && typeof value === "object" ? value[key] : void 0;
1090
+ } catch {
1091
+ return void 0;
1092
+ }
1093
+ }
1094
+ function isCancelledRequest(error) {
1095
+ const name2 = safeGet(error, "name");
1096
+ return typeof name2 === "string" && CANCEL_NAMES.has(name2);
1097
+ }
1098
+ function logSafeAdminError(scope, error) {
1099
+ if (isCancelledRequest(error)) return;
1100
+ const safeScope = typeof scope === "string" && SAFE_SCOPE.test(scope) ? scope : "admin";
1101
+ const directStatus = safeGet(error, "status");
1102
+ const status = Number.isInteger(directStatus) ? directStatus : safeGet(safeGet(error, "response"), "status");
1103
+ const statusSuffix = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
1104
+ console.warn(`[${safeScope}] Request failed${statusSuffix}`);
1105
+ }
1106
+ function useSettingsTranslate() {
1107
+ const { formatMessage, locale } = useIntl();
1108
+ const t = useCallback(
1109
+ (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values),
1110
+ [formatMessage]
1111
+ );
1112
+ const tError = useCallback(
1113
+ (descriptor) => descriptor ? t(descriptor.messageId, descriptor.defaultMessage, descriptor.values) : void 0,
1114
+ [t]
1115
+ );
1116
+ return { t, tError, locale };
1117
+ }
1118
+ async function copyText(value, clipboard = globalThis.navigator?.clipboard) {
1119
+ if (typeof value !== "string") {
1120
+ throw new TypeError("clipboard_value_must_be_text");
1121
+ }
1122
+ if (!clipboard || typeof clipboard.writeText !== "function") {
1123
+ throw new Error("clipboard_unavailable");
1124
+ }
1125
+ await clipboard.writeText(value);
1126
+ }
1127
+ const USER_IMPERSONATION_DURATIONS = Object.freeze([15, 30, 60]);
1128
+ const DEFAULT_IMPERSONATION_MINUTES = 15;
1129
+ const REASON_MIN = 3;
1130
+ const REASON_MAX = 255;
1131
+ function validateReason(value) {
1132
+ const clean = typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
1133
+ if (clean.length < REASON_MIN) {
1134
+ return {
1135
+ messageId: "impersonation.reason.tooShort",
1136
+ defaultMessage: "Enter a reason of at least {min} characters.",
1137
+ values: { min: REASON_MIN }
1138
+ };
1139
+ }
1140
+ if (clean.length > REASON_MAX) {
1141
+ return {
1142
+ messageId: "impersonation.reason.tooLong",
1143
+ defaultMessage: "Use at most {max} characters.",
1144
+ values: { max: REASON_MAX }
1145
+ };
1146
+ }
1147
+ return null;
1148
+ }
1149
+ function secondsUntil(iso, now = Date.now()) {
1150
+ const end = Date.parse(String(iso ?? ""));
1151
+ if (!Number.isFinite(end)) return 0;
1152
+ return Math.max(0, Math.floor((end - now) / 1e3));
1153
+ }
1154
+ function formatClock(seconds) {
1155
+ const total = Math.max(0, Math.floor(Number(seconds) || 0));
1156
+ const hours = Math.floor(total / 3600);
1157
+ const minutes = Math.floor(total % 3600 / 60);
1158
+ const rest = String(total % 60).padStart(2, "0");
1159
+ return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${rest}` : `${minutes}:${rest}`;
1160
+ }
1161
+ function submitFrontendHandoff(doc, handoff) {
1162
+ if (!doc || !handoff || typeof handoff.url !== "string" || typeof handoff.code !== "string") {
1163
+ return false;
1164
+ }
1165
+ let url;
1166
+ try {
1167
+ url = new URL(handoff.url);
1168
+ } catch {
1169
+ return false;
1170
+ }
1171
+ if (url.protocol !== "https:" && url.protocol !== "http:") return false;
1172
+ const form = doc.createElement("form");
1173
+ form.method = "POST";
1174
+ form.action = url.toString();
1175
+ form.target = "_blank";
1176
+ form.rel = "noopener noreferrer";
1177
+ form.style.display = "none";
1178
+ const input = doc.createElement("input");
1179
+ input.type = "hidden";
1180
+ input.name = typeof handoff.field === "string" && handoff.field ? handoff.field : "code";
1181
+ input.value = handoff.code;
1182
+ form.appendChild(input);
1183
+ doc.body.appendChild(form);
1184
+ try {
1185
+ form.submit();
1186
+ } finally {
1187
+ form.remove();
1188
+ }
1189
+ return true;
1190
+ }
1191
+ const dialogs = /* @__PURE__ */ new Map();
1192
+ const mounted = /* @__PURE__ */ new Map();
1193
+ const listeners = /* @__PURE__ */ new Set();
1194
+ const notify = () => {
1195
+ for (const listener of listeners) listener();
1196
+ };
1197
+ function subscribeImpersonationDialogs(listener) {
1198
+ listeners.add(listener);
1199
+ return () => listeners.delete(listener);
1200
+ }
1201
+ function getImpersonationDialog(key) {
1202
+ return dialogs.get(key) || null;
1203
+ }
1204
+ function registerImpersonationPanel(key, instance) {
1205
+ const list = [...mounted.get(key) || [], instance];
1206
+ mounted.set(key, list);
1207
+ const dialog = dialogs.get(key);
1208
+ if (dialog && (!dialog.owner || !list.includes(dialog.owner))) {
1209
+ dialogs.set(key, { ...dialog, owner: instance });
1210
+ notify();
1211
+ }
1212
+ return () => {
1213
+ const rest = (mounted.get(key) || []).filter((id) => id !== instance);
1214
+ if (rest.length) mounted.set(key, rest);
1215
+ else mounted.delete(key);
1216
+ const current = dialogs.get(key);
1217
+ if (current && current.owner === instance) {
1218
+ dialogs.set(key, { ...current, owner: rest[rest.length - 1] || null });
1219
+ notify();
1220
+ }
1221
+ };
1222
+ }
1223
+ function openImpersonationDialog(key, instance) {
1224
+ dialogs.set(key, { open: true, owner: instance, draft: {} });
1225
+ notify();
1226
+ }
1227
+ function saveImpersonationDraft(key, draft) {
1228
+ const current = dialogs.get(key);
1229
+ if (current) dialogs.set(key, { ...current, draft });
1230
+ }
1231
+ function closeImpersonationDialog(key) {
1232
+ if (dialogs.delete(key)) notify();
1233
+ }
1234
+ const REFUSALS = Object.freeze({
1235
+ disabled: ["impersonation.error.disabled", "Impersonation is turned off in the settings."],
1236
+ "already-active": [
1237
+ "impersonation.error.alreadyActive",
1238
+ "An impersonation of this user is already running. End it first."
1239
+ ],
1240
+ blocked: ["impersonation.error.blocked", "Blocked accounts cannot be impersonated."],
1241
+ "api-token": ["impersonation.error.apiToken", "API tokens cannot impersonate."]
1242
+ });
1243
+ function useSecondsLeft(expiresAt) {
1244
+ const [now, setNow] = useState(() => Date.now());
1245
+ useEffect(() => {
1246
+ if (!expiresAt) return void 0;
1247
+ const timer = window.setInterval(() => setNow(Date.now()), 1e3);
1248
+ return () => window.clearInterval(timer);
1249
+ }, [expiresAt]);
1250
+ return secondsUntil(expiresAt, now);
1251
+ }
1252
+ const SecretField = ({ label, value, name: name2 }) => {
1253
+ const { t } = useSettingsTranslate();
1254
+ const { toggleNotification } = useNotification();
1255
+ const copy = async () => {
1256
+ try {
1257
+ await copyText(value);
1258
+ toggleNotification({
1259
+ type: "success",
1260
+ message: t("impersonation.result.copied", "Copied to the clipboard.")
1261
+ });
1262
+ } catch {
1263
+ toggleNotification({
1264
+ type: "warning",
1265
+ message: t(
1266
+ "impersonation.result.copyFailed",
1267
+ "Copying failed. Select the text and copy it yourself."
1268
+ )
1269
+ });
1270
+ }
1271
+ };
1272
+ return /* @__PURE__ */ jsxs(Field.Root, { name: name2, children: [
1273
+ /* @__PURE__ */ jsx(Field.Label, { children: label }),
1274
+ /* @__PURE__ */ jsx(
1275
+ TextInput,
1276
+ {
1277
+ value,
1278
+ readOnly: true,
1279
+ onFocus: (event) => event.target.select(),
1280
+ endAction: /* @__PURE__ */ jsx(
1281
+ Field.Action,
1282
+ {
1283
+ label: t("impersonation.result.copy", "Copy {name}", { name: label }),
1284
+ onClick: copy,
1285
+ children: /* @__PURE__ */ jsx(Duplicate, {})
1286
+ }
1287
+ )
1288
+ }
1289
+ )
1290
+ ] });
1291
+ };
1292
+ const ImpersonateUserModal = ({
1293
+ open,
1294
+ onOpenChange,
1295
+ onCloseAutoFocus,
1296
+ user,
1297
+ status,
1298
+ onChanged
1299
+ }) => {
1300
+ const { t, tError } = useSettingsTranslate();
1301
+ const { post } = useFetchClient();
1302
+ const { toggleNotification } = useNotification();
1303
+ const notifyHintId = useId();
1304
+ const [saved] = useState(() => getImpersonationDialog(user.documentId)?.draft || {});
1305
+ const [reason, setReason] = useState(saved.reason ?? "");
1306
+ const [minutes, setMinutes] = useState(saved.minutes ?? DEFAULT_IMPERSONATION_MINUTES);
1307
+ const [notifyUser, setNotifyUser] = useState(saved.notifyUser === true);
1308
+ const [touched, setTouched] = useState(false);
1309
+ const [pending, setPending] = useState(null);
1310
+ const [failure, setFailure] = useState(null);
1311
+ const [result, setResult] = useState(saved.result ?? null);
1312
+ useEffect(() => {
1313
+ if (!open) return;
1314
+ saveImpersonationDraft(user.documentId, { reason, minutes, notifyUser, result });
1315
+ }, [open, user.documentId, reason, minutes, notifyUser, result]);
1316
+ const secondsLeft = useSecondsLeft(result?.impersonation?.expiresAt || null);
1317
+ const durations = Array.isArray(status?.durations) ? status.durations : USER_IMPERSONATION_DURATIONS;
1318
+ const reasonError = validateReason(reason);
1319
+ const showReasonError = touched && reasonError;
1320
+ const start = async () => {
1321
+ setTouched(true);
1322
+ if (reasonError) return;
1323
+ setPending("start");
1324
+ setFailure(null);
1325
+ try {
1326
+ const { data } = await post(
1327
+ `/${pluginId$1}/impersonation/users/${encodeURIComponent(user.documentId)}`,
1328
+ { reason: reason.trim(), durationMinutes: minutes, notifyUser }
1329
+ );
1330
+ setResult(data?.data || null);
1331
+ onChanged?.();
1332
+ } catch (err) {
1333
+ if (isCancelledRequest(err)) return;
1334
+ const response = err?.response;
1335
+ const reasonCode = response?.data?.error?.details?.reason;
1336
+ if (response?.status === 429) {
1337
+ setFailure(
1338
+ t(
1339
+ "impersonation.error.rateLimited",
1340
+ "Too many impersonations were started. Try again in a few minutes."
1341
+ )
1342
+ );
1343
+ } else if (REFUSALS[reasonCode]) {
1344
+ setFailure(t(...REFUSALS[reasonCode]));
1345
+ } else {
1346
+ logSafeAdminError("impersonation.start", err);
1347
+ setFailure(t("impersonation.error.start", "The impersonation could not be started."));
1348
+ }
1349
+ } finally {
1350
+ setPending(null);
1351
+ }
1352
+ };
1353
+ const end = async () => {
1354
+ if (!result?.impersonation?.id) return;
1355
+ setPending("end");
1356
+ try {
1357
+ await post(`/${pluginId$1}/impersonation/${result.impersonation.id}/end`, {});
1358
+ toggleNotification({
1359
+ type: "success",
1360
+ message: t("impersonation.ended", "Impersonation ended.")
1361
+ });
1362
+ onChanged?.();
1363
+ onOpenChange(false);
1364
+ } catch (err) {
1365
+ logSafeAdminError("impersonation.end", err);
1366
+ toggleNotification({
1367
+ type: "danger",
1368
+ message: t("impersonation.error.end", "The impersonation could not be ended.")
1369
+ });
1370
+ } finally {
1371
+ setPending(null);
1372
+ }
1373
+ };
1374
+ const openFrontend = () => {
1375
+ setFailure(null);
1376
+ const onViolation = (event) => {
1377
+ if (String(event?.violatedDirective || "").startsWith("form-action")) {
1378
+ setFailure(
1379
+ t(
1380
+ "impersonation.error.csp",
1381
+ "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.",
1382
+ { origin: status?.frontendOrigin || "" }
1383
+ )
1384
+ );
1385
+ }
1386
+ };
1387
+ document.addEventListener("securitypolicyviolation", onViolation);
1388
+ window.setTimeout(
1389
+ () => document.removeEventListener("securitypolicyviolation", onViolation),
1390
+ 3e3
1391
+ );
1392
+ if (!submitFrontendHandoff(document, result?.handoff)) {
1393
+ setFailure(t("impersonation.error.frontend", "The frontend could not be opened."));
1394
+ }
1395
+ };
1396
+ const handoff = result?.handoff;
1397
+ const clock = formatClock(secondsLeft);
1398
+ return /* @__PURE__ */ jsx(Modal.Root, { open, onOpenChange, children: /* @__PURE__ */ jsxs(Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
1399
+ /* @__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 }) }) }),
1400
+ /* @__PURE__ */ jsx(Modal.Body, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 4, children: [
1401
+ failure ? /* @__PURE__ */ jsx(PersistentAlert, { variant: "danger", closeLabel: t("common.close", "Close"), children: failure }) : null,
1402
+ !result ? /* @__PURE__ */ jsxs(Fragment, { children: [
1403
+ /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
1404
+ "impersonation.modal.intro",
1405
+ "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."
1406
+ ) }),
1407
+ /* @__PURE__ */ jsxs(
1408
+ Field.Root,
1409
+ {
1410
+ name: "reason",
1411
+ required: true,
1412
+ error: showReasonError ? tError(reasonError) : void 0,
1413
+ hint: t(
1414
+ "impersonation.reason.hint",
1415
+ "Stored in the security log and, if you email the user, shown to them."
1416
+ ),
1417
+ children: [
1418
+ /* @__PURE__ */ jsx(Field.Label, { children: t("impersonation.reason.label", "Reason") }),
1419
+ /* @__PURE__ */ jsx(
1420
+ Textarea,
1421
+ {
1422
+ value: reason,
1423
+ maxLength: REASON_MAX,
1424
+ placeholder: t("impersonation.reason.placeholder", "For example: ticket 4711"),
1425
+ onChange: (event) => setReason(event.target.value),
1426
+ onBlur: () => setTouched(true)
1427
+ }
1428
+ ),
1429
+ /* @__PURE__ */ jsx(Field.Hint, {}),
1430
+ /* @__PURE__ */ jsx(Field.Error, {})
1431
+ ]
1432
+ }
1433
+ ),
1434
+ /* @__PURE__ */ jsxs(Field.Root, { name: "durationMinutes", children: [
1435
+ /* @__PURE__ */ jsx(Field.Label, { children: t("impersonation.duration.label", "Duration") }),
1436
+ /* @__PURE__ */ jsx(
1437
+ SingleSelect,
1438
+ {
1439
+ value: String(minutes),
1440
+ onChange: (value) => setMinutes(Number(value)),
1441
+ children: durations.map((value) => /* @__PURE__ */ jsx(SingleSelectOption, { value: String(value), children: t(
1442
+ "impersonation.duration.minutes",
1443
+ "{count, plural, one {# minute} other {# minutes}}",
1444
+ {
1445
+ count: value
1446
+ }
1447
+ ) }, value))
1448
+ }
1449
+ )
1450
+ ] }),
1451
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, children: [
1452
+ /* @__PURE__ */ jsx(
1453
+ Checkbox,
1454
+ {
1455
+ checked: notifyUser,
1456
+ "aria-describedby": notifyHintId,
1457
+ onCheckedChange: (checked) => setNotifyUser(checked === true),
1458
+ children: t(
1459
+ "impersonation.notify.label",
1460
+ "Email the user that their account was opened"
1461
+ )
1462
+ }
1463
+ ),
1464
+ /* @__PURE__ */ jsx(Typography, { id: notifyHintId, variant: "pi", textColor: "neutral600", children: t(
1465
+ "impersonation.notify.hint",
1466
+ "Sent through Strapi’s email plugin, with the reason and the duration."
1467
+ ) })
1468
+ ] })
1469
+ ] }) : null,
1470
+ handoff?.type === "frontend" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1471
+ /* @__PURE__ */ jsx(PersistentAlert, { variant: "default", closeLabel: t("common.close", "Close"), children: t(
1472
+ "impersonation.result.frontendBody",
1473
+ "Open {origin} within one minute. The sign-in link works once and is sent without appearing in the address bar.",
1474
+ { origin: status?.frontendOrigin || "" }
1475
+ ) }),
1476
+ /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Button, { startIcon: /* @__PURE__ */ jsx(ExternalLink, {}), onClick: openFrontend, children: t("impersonation.result.openFrontend", "Open frontend") }) })
1477
+ ] }) : null,
1478
+ handoff?.type === "token" ? /* @__PURE__ */ jsxs(Fragment, { children: [
1479
+ /* @__PURE__ */ jsx(PersistentAlert, { variant: "warning", closeLabel: t("common.close", "Close"), children: t(
1480
+ "impersonation.result.tokenBody",
1481
+ "Shown only once. Anyone who has this token acts as {user} until it ends. Do not store or share it.",
1482
+ { user: user.label }
1483
+ ) }),
1484
+ /* @__PURE__ */ jsx(
1485
+ SecretField,
1486
+ {
1487
+ name: "jwt",
1488
+ label: t("impersonation.result.accessToken", "Access token"),
1489
+ value: handoff.jwt
1490
+ }
1491
+ ),
1492
+ handoff.refreshToken ? /* @__PURE__ */ jsx(
1493
+ SecretField,
1494
+ {
1495
+ name: "refreshToken",
1496
+ label: t("impersonation.result.refreshToken", "Refresh token"),
1497
+ value: handoff.refreshToken
1498
+ }
1499
+ ) : null
1500
+ ] }) : null,
1501
+ result ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", tag: "p", "aria-live": "polite", children: t("impersonation.result.endsIn", "Ends in {time}.", { time: clock }) }) : null
1502
+ ] }) }),
1503
+ /* @__PURE__ */ jsx(Modal.Footer, { children: result ? /* @__PURE__ */ jsxs(Fragment, { children: [
1504
+ /* @__PURE__ */ jsx(Button, { variant: "danger-light", onClick: end, loading: pending === "end", children: t("impersonation.end", "End impersonation") }),
1505
+ /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: t("impersonation.result.done", "Done") }) })
1506
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1507
+ /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: t("common.cancel", "Cancel") }) }),
1508
+ /* @__PURE__ */ jsx(Button, { onClick: start, loading: pending === "start", children: t("impersonation.start", "Start impersonation") })
1509
+ ] }) })
1510
+ ] }) });
1511
+ };
1512
+ const focusVisibleTrigger = (documentId, fallback) => {
1513
+ const candidates = [
1514
+ ...document.querySelectorAll(
1515
+ `[data-impersonation-trigger="${globalThis.CSS?.escape ? globalThis.CSS.escape(documentId) : documentId}"]`
1516
+ )
1517
+ ];
1518
+ const visible = candidates.find((node) => node.getClientRects().length > 0);
1519
+ (visible || fallback)?.focus?.();
1520
+ };
1521
+ const ImpersonationPanelSection = ({ documentId, userLabel }) => {
1522
+ const { t } = useSettingsTranslate();
1523
+ const { get, post } = useFetchClient();
1524
+ const { toggleNotification } = useNotification();
1525
+ const { formatDate } = useSessionFormatters();
1526
+ const {
1527
+ isLoading,
1528
+ allowedActions: { canUsers }
1529
+ } = useRBAC(pluginPermissions.impersonateUsers);
1530
+ const [status, setStatus] = useState(null);
1531
+ const [active, setActive] = useState(null);
1532
+ const instance = useId();
1533
+ const dialog = useSyncExternalStore(
1534
+ subscribeImpersonationDialogs,
1535
+ () => getImpersonationDialog(documentId)
1536
+ );
1537
+ const open = dialog?.open === true && dialog.owner === instance;
1538
+ useEffect(() => registerImpersonationPanel(documentId, instance), [documentId, instance]);
1539
+ const triggerRef = useRef(null);
1540
+ const endTriggerRef = useRef(null);
1541
+ const requestRef = useRef(0);
1542
+ const apply = useCallback(
1543
+ async (request, pending) => {
1544
+ try {
1545
+ const [statusResponse, listResponse] = await pending;
1546
+ if (request !== requestRef.current) return;
1547
+ setStatus(statusResponse?.data?.data || null);
1548
+ const rows = Array.isArray(listResponse?.data?.data) ? listResponse.data.data : [];
1549
+ setActive(
1550
+ rows.find((row) => row.targetType === "user" && row.targetId === documentId) || null
1551
+ );
1552
+ } catch (err) {
1553
+ if (isCancelledRequest(err) || request !== requestRef.current) return;
1554
+ logSafeAdminError("impersonation.panel", err);
1555
+ setStatus(null);
1556
+ }
1557
+ },
1558
+ [documentId]
1559
+ );
1560
+ const fetchState = useCallback(
1561
+ () => Promise.all([
1562
+ get(`/${pluginId$1}/impersonation/status`),
1563
+ get(`/${pluginId$1}/impersonation/active`)
1564
+ ]),
1565
+ [get]
1566
+ );
1567
+ const load = useCallback(() => apply(++requestRef.current, fetchState()), [apply, fetchState]);
1568
+ useEffect(() => {
1569
+ if (isLoading || !canUsers || !documentId) return;
1570
+ apply(++requestRef.current, fetchState());
1571
+ }, [apply, canUsers, documentId, fetchState, isLoading]);
1572
+ if (isLoading || !canUsers || !status?.enabled) return null;
1573
+ const end = async () => {
1574
+ try {
1575
+ await post(`/${pluginId$1}/impersonation/${active.id}/end`, {});
1576
+ toggleNotification({
1577
+ type: "success",
1578
+ message: t("impersonation.ended", "Impersonation ended.")
1579
+ });
1580
+ } catch (err) {
1581
+ logSafeAdminError("impersonation.end", err);
1582
+ toggleNotification({
1583
+ type: "danger",
1584
+ message: t("impersonation.error.end", "The impersonation could not be ended.")
1585
+ });
1586
+ throw err;
1587
+ } finally {
1588
+ await load();
1589
+ }
1590
+ };
1591
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-impersonation": "", children: [
1592
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: t("impersonation.panel.title", "Impersonation") }),
1593
+ active ? /* @__PURE__ */ jsxs(Fragment, { children: [
1594
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral800", tag: "p", children: t("impersonation.panel.running", "Running until {time}.", {
1595
+ time: formatDate(active.expiresAt, { hour: "2-digit", minute: "2-digit" })
1596
+ }) }),
1597
+ /* @__PURE__ */ jsx(
1598
+ ConfirmAction,
1599
+ {
1600
+ title: t("impersonation.confirm.title", "End the impersonation of {user}?", {
1601
+ user: userLabel
1602
+ }),
1603
+ body: t(
1604
+ "impersonation.confirm.body",
1605
+ "The short-lived sign-in stops working at once. This is recorded in the security log."
1606
+ ),
1607
+ confirmLabel: t("impersonation.end", "End impersonation"),
1608
+ onConfirm: end,
1609
+ fallbackFocusRef: triggerRef,
1610
+ trigger: /* @__PURE__ */ jsx(
1611
+ Button,
1612
+ {
1613
+ ref: endTriggerRef,
1614
+ "data-impersonation-trigger": documentId,
1615
+ fullWidth: true,
1616
+ size: "S",
1617
+ variant: "danger-light",
1618
+ startIcon: /* @__PURE__ */ jsx(SignOut, { "aria-hidden": true, focusable: false }),
1619
+ type: "button",
1620
+ children: t("impersonation.end", "End impersonation")
1621
+ }
1622
+ )
1623
+ }
1624
+ )
1625
+ ] }) : /* @__PURE__ */ jsx(
1626
+ Button,
1627
+ {
1628
+ ref: triggerRef,
1629
+ "data-impersonation-trigger": documentId,
1630
+ fullWidth: true,
1631
+ size: "S",
1632
+ variant: "secondary",
1633
+ startIcon: /* @__PURE__ */ jsx(User, { "aria-hidden": true, focusable: false }),
1634
+ onClick: () => openImpersonationDialog(documentId, instance),
1635
+ type: "button",
1636
+ children: t("impersonation.panel.start", "Impersonate…")
1637
+ }
1638
+ ),
1639
+ open ? /* @__PURE__ */ jsx(
1640
+ ImpersonateUserModal,
1641
+ {
1642
+ open: true,
1643
+ onOpenChange: (next) => {
1644
+ if (!next) {
1645
+ closeImpersonationDialog(documentId);
1646
+ load();
1647
+ window.setTimeout(
1648
+ () => focusVisibleTrigger(documentId, triggerRef.current || endTriggerRef.current),
1649
+ 0
1650
+ );
1651
+ }
1652
+ },
1653
+ onCloseAutoFocus: (event) => {
1654
+ event.preventDefault();
1655
+ focusVisibleTrigger(documentId, triggerRef.current || endTriggerRef.current);
1656
+ },
1657
+ user: { documentId, label: userLabel },
1658
+ status,
1659
+ onChanged: load
1660
+ }
1661
+ ) : null
1662
+ ] });
1663
+ };
1664
+ function useElementWidth() {
1665
+ const [width, setWidth] = useState(0);
1666
+ const observerRef = useRef(null);
1667
+ const ref = useCallback((node) => {
1668
+ observerRef.current?.disconnect();
1669
+ observerRef.current = null;
1670
+ if (!node || typeof ResizeObserver === "undefined") return;
1671
+ const observer = new ResizeObserver((entries) => {
1672
+ const next = Math.round(entries[0]?.contentRect?.width || 0);
1673
+ setWidth((previous) => previous === next ? previous : next);
1674
+ });
1675
+ observer.observe(node);
1676
+ observerRef.current = observer;
1677
+ }, []);
1678
+ useEffect(() => () => observerRef.current?.disconnect(), []);
1679
+ return [ref, width];
1680
+ }
1681
+ const CSV_HEADERS = Object.freeze([
1682
+ "ID",
1683
+ "Status",
1684
+ "User Email",
1685
+ "Username",
1686
+ "Device",
1687
+ "Browser",
1688
+ "OS",
1689
+ "IP Address",
1690
+ "Login Time",
1691
+ "Last Active",
1692
+ "Logout Time",
1693
+ "Minutes Idle",
1694
+ "End Reason"
1695
+ ]);
1696
+ const FORMULA_START = /^[\s\u00ad\u200b-\u200f\u2060-\u2064\ufeff]*[=+\-@\uff1d\uff0b\uff0d\uff20\t\r\n]/;
1697
+ const escapeCsvValue = (value) => {
1698
+ const text = String(value ?? "");
1699
+ const safe = typeof value === "string" && FORMULA_START.test(text) ? `'${text}` : text;
1700
+ return `"${safe.replace(/"/g, '""')}"`;
1701
+ };
1702
+ function toIsoTimestamp(value) {
1703
+ if (value === null || value === void 0 || value === "") return "";
1704
+ const date = value instanceof Date ? value : new Date(
1705
+ /** @type {any} */
1706
+ value
1707
+ );
1708
+ return Number.isFinite(date.getTime()) ? date.toISOString() : "";
1709
+ }
1710
+ function buildSessionCsv(sessions, {
1711
+ unavailableValue,
1712
+ getDeviceInfo,
1713
+ getSessionStatus: getSessionStatus2,
1714
+ getSessionEndReason: getSessionEndReason$1 = getSessionEndReason
1715
+ }) {
1716
+ const rows = Array.isArray(sessions) ? sessions : [];
1717
+ const csvRows = rows.map((session) => {
1718
+ const deviceInfo = getDeviceInfo(session, unavailableValue);
1719
+ const minutesIdle = Number.isFinite(session.minutesSinceActive) ? session.minutesSinceActive : "";
1720
+ return [
1721
+ session.id,
1722
+ getSessionStatus2(session),
1723
+ session.user?.email || "",
1724
+ session.user?.username || "",
1725
+ deviceInfo.device,
1726
+ deviceInfo.browser,
1727
+ deviceInfo.os,
1728
+ session.ipAddress || unavailableValue,
1729
+ toIsoTimestamp(session.loginTime),
1730
+ toIsoTimestamp(session.lastActive || session.loginTime),
1731
+ toIsoTimestamp(session.logoutTime),
1732
+ minutesIdle,
1733
+ getSessionEndReason$1(session) || ""
1734
+ ];
1735
+ });
1736
+ return [
1737
+ CSV_HEADERS.map(escapeCsvValue).join(","),
1738
+ ...csvRows.map((row) => row.map(escapeCsvValue).join(","))
1739
+ ].join("\n");
1740
+ }
1741
+ function buildSessionJson(sessions, {
1742
+ filterStatus,
1743
+ totalSessions,
1744
+ exportedAt,
1745
+ unavailableValue,
1746
+ getDeviceInfo,
1747
+ getSessionStatus: getSessionStatus2,
1748
+ getSessionEndReason: getSessionEndReason$1 = getSessionEndReason,
1749
+ truncated = false
1750
+ }) {
1751
+ const rows = Array.isArray(sessions) ? sessions : [];
1752
+ const exportData = {
1753
+ exportedAt,
1754
+ filter: filterStatus,
1755
+ totalSessions,
1756
+ exportedSessions: rows.length,
1757
+ ...truncated ? { truncated: true } : {},
1758
+ sessions: rows.map((session) => {
1759
+ const deviceInfo = getDeviceInfo(session, unavailableValue);
1760
+ return {
1761
+ id: session.id,
1762
+ status: getSessionStatus2(session),
1763
+ endReason: getSessionEndReason$1(session) || null,
1764
+ user: {
1765
+ id: session.user?.documentId || session.user?.id,
1766
+ email: session.user?.email,
1767
+ username: session.user?.username
1768
+ },
1769
+ device: {
1770
+ type: deviceInfo.device,
1771
+ browser: deviceInfo.browser,
1772
+ browserVersion: deviceInfo.browserVersion,
1773
+ os: deviceInfo.os
1774
+ },
1775
+ ipAddress: session.ipAddress || unavailableValue,
1776
+ loginTime: session.loginTime,
1777
+ lastActive: session.lastActive,
1778
+ logoutTime: session.logoutTime,
1779
+ minutesSinceActive: session.minutesSinceActive,
1780
+ isActive: session.isActive,
1781
+ isTrulyActive: session.isTrulyActive
1782
+ };
1783
+ })
1784
+ };
1785
+ return JSON.stringify(exportData, null, 2);
1786
+ }
1787
+ const SETTINGS_TAB_IDS = Object.freeze([
1788
+ "sessions",
1789
+ "login-protection",
1790
+ "location-data",
1791
+ "alerts",
1792
+ "data-retention",
1793
+ "impersonation",
1794
+ "admin-activity"
1795
+ ]);
1796
+ const PERMISSION_GATED_TABS = Object.freeze(["admin-activity"]);
1797
+ const DEFAULT_SETTINGS_TAB = "sessions";
1798
+ const SETTINGS_TAB_LABELS = Object.freeze({
1799
+ sessions: ["settings.config.tab.sessions", "Sessions"],
1800
+ "login-protection": ["settings.config.tab.loginProtection", "Login protection"],
1801
+ "location-data": ["settings.config.tab.locationData", "Location data"],
1802
+ alerts: ["settings.config.tab.alerts", "Alerts"],
1803
+ "data-retention": ["settings.config.tab.dataRetention", "Data and retention"],
1804
+ impersonation: ["settings.config.tab.impersonation", "Impersonation"],
1805
+ "admin-activity": ["settings.config.tab.adminActivity", "Admin activity"]
1806
+ });
1807
+ const SETTINGS_TAB_FIELDS = Object.freeze({
1808
+ sessions: [
1809
+ "inactivityTimeout",
1810
+ "maxSessionAgeDays",
1811
+ "lastSeenRateLimit",
1812
+ "cleanupInterval",
1813
+ "cleanupUseDbDirect",
1814
+ "strictSessionEnforcement",
1815
+ "sessionCreationGraceMs",
1816
+ "maxSessionsPerUser",
1817
+ "sessionLimitPolicy",
1818
+ "endOtherSessionsOnPasswordChange",
1819
+ "roleRules"
1820
+ ],
1821
+ "login-protection": [
1822
+ "maxFailedLogins",
1823
+ "maxFailedLoginsPerAccount",
1824
+ "lockoutWindowMinutes",
1825
+ "lockoutDurationMinutes",
1826
+ "lockoutTrustedAddresses",
1827
+ "lockoutNotifyUser",
1828
+ "recordUserSignInEvents",
1829
+ "impossibleTravelEnabled",
1830
+ "impossibleTravelSpeedKmh",
1831
+ "impossibleTravelMinDistanceKm",
1832
+ "impossibleTravelAction",
1833
+ "trustedProxies",
1834
+ "blockSuspiciousSessions",
1835
+ "geoLookupFailureMode",
1836
+ "enableGeofencing",
1837
+ "allowedCountries",
1838
+ "blockedCountries"
1839
+ ],
1840
+ "location-data": [
1841
+ "enableGeolocation",
1842
+ "enableSecurityScoring",
1843
+ "geoIpProvider",
1844
+ "geoIpDatabasePath"
1845
+ ],
1846
+ alerts: [
1847
+ "enableEmailAlerts",
1848
+ "alertOnSuspiciousLogin",
1849
+ "alertOnNewLocation",
1850
+ "alertOnVpnProxy",
1851
+ "emailTemplates",
1852
+ "enableWebhooks",
1853
+ "discordWebhookUrl",
1854
+ "slackWebhookUrl",
1855
+ "alertOnNewDevice",
1856
+ "alertOnImpossibleTravel",
1857
+ "webhookEvents",
1858
+ "genericWebhookEnabled",
1859
+ "genericWebhookUrl",
1860
+ "genericWebhookSecret"
1861
+ ],
1862
+ "data-retention": ["retentionDays", "sessionIpAnonymize"],
1863
+ impersonation: ["impersonationEnabled"],
1864
+ "admin-activity": [
1865
+ "adminSignInHistory",
1866
+ "adminContentActivity",
1867
+ "securityLogStoreIp",
1868
+ "securityLogAnonymizeIp",
1869
+ "securityLogGeoLookup",
1870
+ "securityLogRetentionDays"
1871
+ ]
1872
+ });
1873
+ const PRESERVED_SETTINGS_KEYS = Object.freeze([
1874
+ "rateLimitWriteMax",
1875
+ "rateLimitReadMax",
1876
+ "rateLimitWindowSeconds"
1877
+ ]);
1878
+ const SETTINGS_FIELD_LABELS = Object.freeze({
1879
+ inactivityTimeout: ["settings.config.sessions.inactivity.label", "Inactivity timeout"],
1880
+ maxSessionAgeDays: ["settings.config.sessions.maxAge.label", "Maximum session age"],
1881
+ lastSeenRateLimit: [
1882
+ "settings.config.sessions.lastSeen.label",
1883
+ 'Update "Last active" at most every'
1884
+ ],
1885
+ cleanupInterval: ["settings.config.sessions.idleCheck.label", "Run idle check every"],
1886
+ cleanupUseDbDirect: ["settings.config.sessions.idleMethod.label", "Idle check method"],
1887
+ strictSessionEnforcement: ["settings.config.token.check.label", "Strict token check"],
1888
+ sessionCreationGraceMs: ["settings.config.token.grace.label", "Grace period after sign-in"],
1889
+ maxFailedLogins: ["settings.config.failed.lockout.label", "Lock an IP address after"],
1890
+ maxFailedLoginsPerAccount: ["settings.config.failed.account.label", "Lock an account after"],
1891
+ lockoutWindowMinutes: ["settings.config.failed.window.label", "Count failed sign-ins within"],
1892
+ lockoutDurationMinutes: ["settings.config.failed.duration.label", "Lock for"],
1893
+ lockoutTrustedAddresses: ["settings.config.failed.trusted.label", "Trusted addresses"],
1894
+ lockoutNotifyUser: [
1895
+ "settings.config.failed.notify.label",
1896
+ "Email the user when their account is locked"
1897
+ ],
1898
+ recordUserSignInEvents: [
1899
+ "settings.config.failed.record.label",
1900
+ "Record failed and refused sign-ins"
1901
+ ],
1902
+ maxSessionsPerUser: ["settings.config.sessionLimit.max.label", "Open sessions per user"],
1903
+ sessionLimitPolicy: ["settings.config.sessionLimit.policy.label", "When the limit is reached"],
1904
+ endOtherSessionsOnPasswordChange: [
1905
+ "settings.config.passwordChange.label",
1906
+ "End other sessions after a password change"
1907
+ ],
1908
+ roleRules: ["settings.roleRules.title", "Different rules for some roles"],
1909
+ impossibleTravelEnabled: ["settings.config.travel.enable.label", "Detect impossible travel"],
1910
+ impossibleTravelSpeedKmh: ["settings.config.travel.speed.label", "Faster than"],
1911
+ impossibleTravelMinDistanceKm: ["settings.config.travel.distance.label", "Over at least"],
1912
+ impossibleTravelAction: ["settings.config.travel.action.label", "Then"],
1913
+ alertOnNewDevice: ["settings.config.email.newDevice.label", "Sign-in from a new device"],
1914
+ alertOnImpossibleTravel: ["settings.config.email.travel.label", "Impossible travel"],
1915
+ webhookEvents: ["settings.webhookEvents.title", "Events to send"],
1916
+ genericWebhookEnabled: ["settings.signedWebhook.enable.label", "Send to the signed webhook"],
1917
+ genericWebhookUrl: ["settings.signedWebhook.url.label", "Webhook URL"],
1918
+ genericWebhookSecret: ["settings.signedWebhook.secret.label", "Signing secret"],
1919
+ sessionIpAnonymize: ["settings.config.privacy.shortIp.label", "Shorten IP addresses of sessions"],
1920
+ trustedProxies: ["settings.config.clientIp.trustProxy.label", "Trust proxy headers"],
1921
+ blockSuspiciousSessions: [
1922
+ "settings.config.suspicious.reject.label",
1923
+ "Reject suspicious sign-ins"
1924
+ ],
1925
+ geoLookupFailureMode: [
1926
+ "settings.config.suspicious.failureMode.label",
1927
+ "If the location cannot be determined"
1928
+ ],
1929
+ enableGeofencing: ["settings.config.countries.enable.label", "Use country rules"],
1930
+ allowedCountries: ["settings.config.countries.list.label", "Countries"],
1931
+ blockedCountries: ["settings.config.countries.list.label", "Countries"],
1932
+ enableGeolocation: ["settings.config.lookup.enable.label", "IP location lookup"],
1933
+ enableSecurityScoring: ["settings.config.lookup.scoring.label", "Security scoring"],
1934
+ geoIpProvider: ["settings.config.provider.label", "Provider"],
1935
+ geoIpDatabasePath: ["settings.config.database.fileName.label", "Database file name"],
1936
+ enableEmailAlerts: ["settings.config.email.enable.label", "Send security emails"],
1937
+ alertOnSuspiciousLogin: ["settings.config.email.suspicious.label", "Suspicious sign-in"],
1938
+ alertOnNewLocation: ["settings.config.email.newCountry.label", "Sign-in from a new country"],
1939
+ alertOnVpnProxy: ["settings.config.email.vpnProxy.label", "VPN or proxy"],
1940
+ emailTemplates: ["settings.config.email.templates.field", "Email templates"],
1941
+ enableWebhooks: ["settings.config.webhooks.enable.label", "Send team notifications"],
1942
+ discordWebhookUrl: ["settings.config.webhooks.discord.label", "Discord webhook URL"],
1943
+ slackWebhookUrl: ["settings.config.webhooks.slack.label", "Slack webhook URL"],
1944
+ retentionDays: ["settings.config.retention.keep.label", "Keep ended sessions for"],
1945
+ impersonationEnabled: ["settings.impersonation.enable.label", "Allow impersonation"],
1946
+ adminSignInHistory: ["settings.config.adminActivity.signIns.label", "Record admin sign-ins"],
1947
+ adminContentActivity: [
1948
+ "settings.config.adminActivity.content.label",
1949
+ "Record Content Manager activity"
1950
+ ],
1951
+ securityLogStoreIp: ["settings.config.adminActivity.storeIp.label", "Store IP addresses"],
1952
+ securityLogAnonymizeIp: [
1953
+ "settings.config.adminActivity.anonymize.label",
1954
+ "Anonymise the last part of IP addresses"
1955
+ ],
1956
+ securityLogGeoLookup: [
1957
+ "settings.config.adminActivity.geoLookup.label",
1958
+ "Look up the location of security events"
1959
+ ],
1960
+ securityLogRetentionDays: [
1961
+ "settings.config.adminActivity.retention.label",
1962
+ "Keep security events for"
1963
+ ]
1964
+ });
1965
+ const SELECT_PRESETS = Object.freeze({
1966
+ inactivityTimeout: Object.freeze([5, 10, 15, 30, 60, 120]),
1967
+ maxSessionAgeDays: Object.freeze([1, 7, 14, 30, 60, 90, 180, 365]),
1968
+ lastSeenRateLimit: Object.freeze([10, 30, 60, 120, 300]),
1969
+ cleanupInterval: Object.freeze([15, 30, 60, 120]),
1970
+ sessionCreationGraceMs: Object.freeze([0, 2e3, 5e3, 1e4, 3e4]),
1971
+ retentionDays: Object.freeze([7, 30, 60, 90, 180, 365, -1]),
1972
+ securityLogRetentionDays: Object.freeze([7, 30, 90, 180, 365])
1973
+ });
1974
+ function resolveSettingsTab(value, tabs = SETTINGS_TAB_IDS) {
1975
+ const candidate = Array.isArray(value) ? value[0] : value;
1976
+ return tabs.includes(candidate) ? candidate : DEFAULT_SETTINGS_TAB;
1977
+ }
1978
+ function getVisibleSettingsTabs(canViewAdminActivity) {
1979
+ return SETTINGS_TAB_IDS.filter(
1980
+ (tab) => canViewAdminActivity || !PERMISSION_GATED_TABS.includes(tab)
1981
+ );
1982
+ }
1983
+ function buildTabSearch(search, tab) {
1984
+ const params = new URLSearchParams(typeof search === "string" ? search : "");
1985
+ params.set("tab", resolveSettingsTab(tab));
1986
+ return `?${params.toString()}`;
1987
+ }
1988
+ function fieldHasError(errors, field) {
1989
+ return Object.keys(errors || {}).some((path) => path === field || path.startsWith(`${field}.`));
1990
+ }
1991
+ function tabHasFieldErrors(errors, tab) {
1992
+ return (SETTINGS_TAB_FIELDS[tab] || []).some((field) => fieldHasError(errors, field));
1993
+ }
1994
+ function getErrorTab(errors) {
1995
+ return SETTINGS_TAB_IDS.find((tab) => tabHasFieldErrors(errors, tab));
1996
+ }
1997
+ function buildSelectOptions(presets, current) {
1998
+ const options = presets.map((value) => ({ value, custom: false }));
1999
+ const number = typeof current === "number" ? current : Number.parseInt(String(current ?? ""), 10);
2000
+ if (Number.isInteger(number) && !presets.includes(number)) {
2001
+ options.push({ value: number, custom: true });
2002
+ }
2003
+ return options;
2004
+ }
2005
+ function buildSavePayload(draft, saved) {
2006
+ const payload = { ...draft || {} };
2007
+ for (const key of PRESERVED_SETTINGS_KEYS) {
2008
+ if (saved && Object.prototype.hasOwnProperty.call(saved, key)) payload[key] = saved[key];
2009
+ }
2010
+ return payload;
2011
+ }
2012
+ function usesLocalDatabase(provider) {
2013
+ return provider === void 0 || provider === null || provider === "" || provider === "auto" || provider === "local-mmdb";
2014
+ }
2015
+ function getRevealScrollDelta(listRect, tabRect) {
2016
+ if (!listRect || !tabRect) return 0;
2017
+ if (tabRect.left < listRect.left - 0.5) return Math.round(tabRect.left - listRect.left);
2018
+ if (tabRect.right > listRect.right + 0.5) return Math.round(tabRect.right - listRect.right);
2019
+ return 0;
2020
+ }
2021
+ const SIGN_IN_FILTER_OPTIONS = Object.freeze(["all", "succeeded", "failed", "signed-out"]);
2022
+ const ALL_ADMINS_FILTER_OPTIONS = Object.freeze([...SIGN_IN_FILTER_OPTIONS, "changes"]);
2023
+ const ACTIVITY_ACTION_OPTIONS = Object.freeze([
2024
+ "all",
2025
+ "view",
2026
+ "create",
2027
+ "update",
2028
+ "publish",
2029
+ "unpublish",
2030
+ "discard",
2031
+ "delete",
2032
+ "clone"
2033
+ ]);
2034
+ const PERIOD_OPTIONS = Object.freeze(["1", "7", "30", "90", "all"]);
2035
+ const EVENT_PAGE_SIZE = 20;
2036
+ const MAX_EVENT_EXPORT_ROWS = 1e4;
2037
+ function periodStart(period, now = /* @__PURE__ */ new Date()) {
2038
+ const days = Number.parseInt(period, 10);
2039
+ if (!Number.isInteger(days) || days <= 0) return void 0;
2040
+ return new Date(now.getTime() - days * 24 * 60 * 60 * 1e3).toISOString();
2041
+ }
2042
+ function buildSignInParams(filters, now) {
2043
+ const params = {
2044
+ page: filters.page || 1,
2045
+ pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2046
+ event: ALL_ADMINS_FILTER_OPTIONS.includes(filters.event) ? filters.event : "all"
2047
+ };
2048
+ if (filters.adminId) params.adminId = String(filters.adminId);
2049
+ const from = periodStart(filters.period || "all", now);
2050
+ if (from) params.from = from;
2051
+ return params;
2052
+ }
2053
+ function buildActivityParams(filters, now) {
2054
+ const params = {
2055
+ page: filters.page || 1,
2056
+ pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2057
+ action: ACTIVITY_ACTION_OPTIONS.includes(filters.action) ? filters.action : "all"
2058
+ };
2059
+ if (filters.adminId) params.adminId = String(filters.adminId);
2060
+ if (filters.contentType && filters.contentType !== "all")
2061
+ params.contentType = filters.contentType;
2062
+ const from = periodStart(filters.period || "all", now);
2063
+ if (from) params.from = from;
2064
+ return params;
2065
+ }
2066
+ function toExportParams(params, cursor) {
2067
+ const { page: _page, pageSize: _pageSize, ...rest } = params;
2068
+ return cursor ? { ...rest, cursor } : rest;
2069
+ }
2070
+ const message$1 = (messageId, defaultMessage) => ({ messageId, defaultMessage });
2071
+ const FAILURE_REASONS = Object.freeze({
2072
+ invalid_credentials: message$1(
2073
+ "adminPanel.activity.reason.invalidCredentials",
2074
+ "Wrong email or password"
2075
+ ),
2076
+ account_inactive: message$1("adminPanel.activity.reason.accountInactive", "Account is deactivated"),
2077
+ login_not_allowed: message$1("adminPanel.activity.reason.notAllowed", "Sign-in is not allowed"),
2078
+ rate_limited: message$1("adminPanel.activity.reason.rateLimited", "Too many attempts")
2079
+ });
2080
+ const LOG_READ_DETAILS = Object.freeze({
2081
+ "sign-ins": [
2082
+ message$1("adminPanel.activity.read.signIns", "Sign-in history listed"),
2083
+ message$1("adminPanel.activity.read.signInsExport", "Sign-in history exported")
2084
+ ],
2085
+ content: [
2086
+ message$1("adminPanel.activity.read.content", "Content Manager activity listed"),
2087
+ message$1("adminPanel.activity.read.contentExport", "Content Manager activity exported")
2088
+ ],
2089
+ "user-activity": [
2090
+ message$1("adminPanel.activity.read.userActivity", "App-user security activity listed"),
2091
+ message$1("adminPanel.activity.read.userActivityExport", "App-user security activity exported")
2092
+ ]
2093
+ });
2094
+ const appUserEvent = (key, tone, icon, messageId, defaultMessage) => ({
2095
+ key,
2096
+ tone,
2097
+ icon,
2098
+ label: message$1(messageId, defaultMessage),
2099
+ detail: null
2100
+ });
2101
+ function getEventPresentation(row) {
2102
+ switch (row?.event) {
2103
+ case "admin.sign-in":
2104
+ return {
2105
+ key: "sign-in",
2106
+ tone: "success",
2107
+ icon: "signIn",
2108
+ label: message$1("adminPanel.activity.event.signIn", "Signed in"),
2109
+ detail: row.reason === "registration" ? message$1("adminPanel.activity.reason.registration", "First sign-in after registration") : row.reason === "password_reset" ? message$1(
2110
+ "adminPanel.activity.reason.passwordReset",
2111
+ "Signed in after a password reset"
2112
+ ) : null
2113
+ };
2114
+ case "admin.sign-in.failed":
2115
+ return {
2116
+ key: "failed",
2117
+ tone: "danger",
2118
+ icon: "failed",
2119
+ label: message$1("adminPanel.activity.event.failed", "Sign-in failed"),
2120
+ detail: FAILURE_REASONS[row.reason] || null
2121
+ };
2122
+ case "admin.lockout":
2123
+ return {
2124
+ key: "lockout",
2125
+ tone: "danger",
2126
+ icon: "lockout",
2127
+ label: message$1("adminPanel.activity.event.lockout", "Locked out"),
2128
+ detail: FAILURE_REASONS.rate_limited
2129
+ };
2130
+ case "admin.sign-out":
2131
+ return {
2132
+ key: "sign-out",
2133
+ tone: "neutral",
2134
+ icon: "signOut",
2135
+ label: message$1("adminPanel.activity.event.signOut", "Signed out"),
2136
+ detail: null
2137
+ };
2138
+ case "admin.session.revoked":
2139
+ return {
2140
+ key: "revoked",
2141
+ tone: "warning",
2142
+ icon: "revoked",
2143
+ label: message$1("adminPanel.activity.event.revoked", "Signed out by an admin"),
2144
+ detail: row.scope === "one_browser" ? message$1("adminPanel.activity.scope.oneBrowser", "One browser") : message$1("adminPanel.activity.scope.everywhere", "Every browser")
2145
+ };
2146
+ case "settings.updated":
2147
+ return {
2148
+ key: "settings",
2149
+ tone: "secondary",
2150
+ icon: "settings",
2151
+ label: message$1("adminPanel.activity.event.settings", "Settings changed"),
2152
+ detail: row.change?.viaToken ? message$1("adminPanel.activity.via.token", "With an admin API token") : null
2153
+ };
2154
+ case "security-log.read":
2155
+ return {
2156
+ key: "log-read",
2157
+ tone: "secondary",
2158
+ icon: row.read?.via === "admin-panel" ? "export" : "logRead",
2159
+ // 4.22: exports of the app-user activity from the admin panel are recorded too.
2160
+ label: row.read?.via === "admin-panel" ? message$1("adminPanel.activity.event.logExported", "Security log exported") : message$1("adminPanel.activity.event.logRead", "Log read with an API token"),
2161
+ detail: LOG_READ_DETAILS[row.read?.list || "sign-ins"]?.[row.read?.exported ? 1 : 0] || null
2162
+ };
2163
+ case "security-log.retention.purged":
2164
+ return {
2165
+ key: "purged",
2166
+ tone: "neutral",
2167
+ icon: "purged",
2168
+ label: message$1("adminPanel.activity.event.purged", "Old events deleted"),
2169
+ detail: null
2170
+ };
2171
+ // App-user events (4.17 / 4.18), listed by the app-user Security activity (4.22) only.
2172
+ // The admin lists never return them; the labels are plain because that view is about app
2173
+ // users already.
2174
+ case "user.sign-in.failed":
2175
+ return appUserEvent(
2176
+ "user-failed",
2177
+ "danger",
2178
+ "failed",
2179
+ "adminPanel.activity.event.userFailed",
2180
+ "Sign-in failed"
2181
+ );
2182
+ case "user.sign-in.refused":
2183
+ return appUserEvent(
2184
+ "user-refused",
2185
+ "danger",
2186
+ "refused",
2187
+ "adminPanel.activity.event.userRefused",
2188
+ "Sign-in refused"
2189
+ );
2190
+ case "user.lockout":
2191
+ return appUserEvent(
2192
+ "user-lockout",
2193
+ "danger",
2194
+ "lockout",
2195
+ "adminPanel.activity.event.userLockout",
2196
+ "Locked out"
2197
+ );
2198
+ case "user.lockout.lifted":
2199
+ return appUserEvent(
2200
+ "user-unlock",
2201
+ "secondary",
2202
+ "unlock",
2203
+ "adminPanel.activity.event.userUnlock",
2204
+ "Lock lifted"
2205
+ );
2206
+ case "user.session.limit":
2207
+ return appUserEvent(
2208
+ "user-limit",
2209
+ "warning",
2210
+ "limit",
2211
+ "adminPanel.activity.event.userLimit",
2212
+ "Session limit reached"
2213
+ );
2214
+ case "user.password-change.ended-others":
2215
+ return appUserEvent(
2216
+ "user-password",
2217
+ "warning",
2218
+ "password",
2219
+ "adminPanel.activity.event.userPassword",
2220
+ "Signed out after a password change"
2221
+ );
2222
+ case "user.sign-in.new-device":
2223
+ return appUserEvent(
2224
+ "user-device",
2225
+ "secondary",
2226
+ "device",
2227
+ "adminPanel.activity.event.userNewDevice",
2228
+ "Sign-in from a new device"
2229
+ );
2230
+ case "user.sign-in.impossible-travel":
2231
+ return appUserEvent(
2232
+ "user-travel",
2233
+ "danger",
2234
+ "travel",
2235
+ "adminPanel.activity.event.userTravel",
2236
+ "Impossible travel"
2237
+ );
2238
+ case "user.not-me":
2239
+ return appUserEvent(
2240
+ "user-not-me",
2241
+ "danger",
2242
+ "notMe",
2243
+ "adminPanel.activity.event.userNotMe",
2244
+ 'Reported as "This wasn’t me"'
2245
+ );
2246
+ case "user.data.exported":
2247
+ return appUserEvent(
2248
+ "user-export",
2249
+ "secondary",
2250
+ "export",
2251
+ "adminPanel.activity.event.userExport",
2252
+ "Personal data exported"
2253
+ );
2254
+ case "impersonation.started":
2255
+ return appUserEvent(
2256
+ "impersonation-started",
2257
+ "warning",
2258
+ "impersonation",
2259
+ "adminPanel.activity.event.impersonationStarted",
2260
+ "Impersonation started"
2261
+ );
2262
+ case "impersonation.ended":
2263
+ return appUserEvent(
2264
+ "impersonation-ended",
2265
+ "neutral",
2266
+ "impersonationEnd",
2267
+ "adminPanel.activity.event.impersonationEnded",
2268
+ "Impersonation ended"
2269
+ );
2270
+ case "impersonation.expired":
2271
+ return appUserEvent(
2272
+ "impersonation-expired",
2273
+ "neutral",
2274
+ "expired",
2275
+ "adminPanel.activity.event.impersonationExpired",
2276
+ "Impersonation timed out"
2277
+ );
2278
+ case "impersonation.refused":
2279
+ return appUserEvent(
2280
+ "impersonation-refused",
2281
+ "danger",
2282
+ "refused",
2283
+ "adminPanel.activity.event.impersonationRefused",
2284
+ "Impersonation request refused"
2285
+ );
2286
+ default:
2287
+ if (typeof row?.event === "string" && row.event.startsWith("impersonation.")) {
2288
+ return appUserEvent(
2289
+ "impersonation",
2290
+ "warning",
2291
+ "impersonation",
2292
+ "adminPanel.activity.event.impersonation",
2293
+ "Impersonation"
2294
+ );
2295
+ }
2296
+ if (typeof row?.event === "string" && row.event.startsWith("webhook.")) {
2297
+ return appUserEvent(
2298
+ "webhook",
2299
+ "neutral",
2300
+ "webhook",
2301
+ "adminPanel.activity.event.webhook",
2302
+ "Webhook delivery"
2303
+ );
2304
+ }
2305
+ return {
2306
+ key: "other",
2307
+ tone: "neutral",
2308
+ icon: "other",
2309
+ label: message$1("adminPanel.activity.event.other", "Security event"),
2310
+ detail: null
2311
+ };
2312
+ }
2313
+ }
2314
+ function getSessionStatePresentation(session) {
2315
+ switch (session?.state) {
2316
+ case "active":
2317
+ return {
2318
+ tone: "success",
2319
+ label: message$1("adminPanel.activity.session.active", "Still signed in")
2320
+ };
2321
+ case "signed-out":
2322
+ return {
2323
+ tone: "neutral",
2324
+ label: message$1("adminPanel.activity.session.signedOut", "Signed out")
2325
+ };
2326
+ case "ended":
2327
+ return {
2328
+ tone: "neutral",
2329
+ label: message$1("adminPanel.activity.session.ended", "Session ended")
2330
+ };
2331
+ default:
2332
+ return null;
2333
+ }
2334
+ }
2335
+ const RECENT_EVENT_LIMIT = 8;
2336
+ const ACTIVITY_PAGE_SIZE_OPTIONS = Object.freeze(["10", "20", "50", "100"]);
2337
+ const EVENT_TABLE_MIN_WIDTH = Object.freeze({ withAdmin: 800, withoutAdmin: 740 });
2338
+ const EVENT_TABLE_FULL_WIDTH = 1e3;
2339
+ function getEventListLayout(width, { showAdmin = false, wide = false, minWidth } = {}) {
2340
+ if (!width) return "full";
2341
+ const min = Number.isFinite(minWidth) && minWidth > 0 ? minWidth : showAdmin || wide ? EVENT_TABLE_MIN_WIDTH.withAdmin : EVENT_TABLE_MIN_WIDTH.withoutAdmin;
2342
+ if (width < min) return "stacked";
2343
+ return width >= EVENT_TABLE_FULL_WIDTH ? "full" : "table";
2344
+ }
2345
+ function getEventPlace(row) {
2346
+ return [row?.location?.city, row?.location?.country].filter(Boolean).join(", ");
2347
+ }
2348
+ function parseActivityPageQuery(query) {
2349
+ const source = query || {};
2350
+ const event = ALL_ADMINS_FILTER_OPTIONS.includes(String(source.event)) ? String(source.event) : "all";
2351
+ const period = PERIOD_OPTIONS.includes(String(source.period)) ? String(source.period) : "30";
2352
+ const adminId = /^[1-9][0-9]{0,11}$/.test(String(source.adminId ?? "")) ? Number(source.adminId) : null;
2353
+ const page = Number.parseInt(String(source.page ?? ""), 10);
2354
+ const pageSize = String(source.pageSize ?? "");
2355
+ return {
2356
+ event,
2357
+ period,
2358
+ adminId,
2359
+ page: Number.isInteger(page) && page > 0 ? page : 1,
2360
+ pageSize: ACTIVITY_PAGE_SIZE_OPTIONS.includes(pageSize) ? Number(pageSize) : EVENT_PAGE_SIZE
2361
+ };
2362
+ }
2363
+ function hasActivityPageFilters(view) {
2364
+ return view.event !== "all" || view.period !== "30" || view.adminId !== null;
2365
+ }
2366
+ function groupChangedSettings(keys) {
2367
+ const list = Array.isArray(keys) ? keys.filter((key) => typeof key === "string" && key) : [];
2368
+ const byTab = /* @__PURE__ */ new Map();
2369
+ const unknown = [];
2370
+ const seen = /* @__PURE__ */ new Set();
2371
+ for (const key of list) {
2372
+ const tab = SETTINGS_TAB_IDS.find((id) => SETTINGS_TAB_FIELDS[id]?.includes(key));
2373
+ const entry = SETTINGS_FIELD_LABELS[key];
2374
+ if (!tab || !entry) {
2375
+ if (!seen.has(`raw:${key}`)) unknown.push({ key, label: null });
2376
+ seen.add(`raw:${key}`);
2377
+ continue;
2378
+ }
2379
+ if (seen.has(`label:${entry[0]}`)) continue;
2380
+ seen.add(`label:${entry[0]}`);
2381
+ if (!byTab.has(tab)) byTab.set(tab, []);
2382
+ byTab.get(tab).push({ key, label: message$1(entry[0], entry[1]) });
2383
+ }
2384
+ const groups = SETTINGS_TAB_IDS.filter((tab) => byTab.has(tab)).map((tab) => ({
2385
+ tab,
2386
+ label: message$1(SETTINGS_TAB_LABELS[tab][0], SETTINGS_TAB_LABELS[tab][1]),
2387
+ fields: byTab.get(tab)
2388
+ }));
2389
+ if (unknown.length) groups.push({ tab: null, label: null, fields: unknown });
2390
+ return groups;
2391
+ }
2392
+ const ACTIVITY_ACTION_LABELS = Object.freeze({
2393
+ all: message$1("adminPanel.activity.action.all", "All actions"),
2394
+ view: message$1("adminPanel.activity.action.view", "Opened"),
2395
+ create: message$1("adminPanel.activity.action.create", "Created"),
2396
+ update: message$1("adminPanel.activity.action.update", "Edited"),
2397
+ publish: message$1("adminPanel.activity.action.publish", "Published"),
2398
+ unpublish: message$1("adminPanel.activity.action.unpublish", "Unpublished"),
2399
+ discard: message$1("adminPanel.activity.action.discard", "Discarded draft"),
2400
+ delete: message$1("adminPanel.activity.action.delete", "Deleted"),
2401
+ clone: message$1("adminPanel.activity.action.clone", "Duplicated")
2402
+ });
2403
+ function getActivityTone(action) {
2404
+ if (action === "publish") return "success";
2405
+ if (action === "delete") return "warning";
2406
+ return "neutral";
2407
+ }
2408
+ function getEntryPath(row) {
2409
+ const type = row?.contentType;
2410
+ if (!type?.exists || row.action === "delete") return null;
2411
+ const uid = encodeURIComponent(type.uid);
2412
+ const locale = row.entry?.locale ? `?plugins[i18n][locale]=${encodeURIComponent(row.entry.locale)}` : "";
2413
+ if (type.kind === "single") return `/content-manager/single-types/${uid}${locale}`;
2414
+ if (!row.entry?.documentId) return null;
2415
+ return `/content-manager/collection-types/${uid}/${encodeURIComponent(row.entry.documentId)}${locale}`;
2416
+ }
2417
+ const SIGN_IN_CSV_HEADERS = Object.freeze([
2418
+ "Time",
2419
+ "Event",
2420
+ "Reason",
2421
+ "Admin",
2422
+ "Admin ID",
2423
+ "IP Address",
2424
+ "IP Anonymized",
2425
+ "Country",
2426
+ "City",
2427
+ "Browser",
2428
+ "OS",
2429
+ "Device",
2430
+ "Session",
2431
+ "Signed Out By"
2432
+ ]);
2433
+ const ACTIVITY_CSV_HEADERS = Object.freeze([
2434
+ "Time",
2435
+ "Action",
2436
+ "Admin",
2437
+ "Admin ID",
2438
+ "Content Type",
2439
+ "Content Type UID",
2440
+ "Document ID",
2441
+ "Locale",
2442
+ "Title",
2443
+ "Entries"
2444
+ ]);
2445
+ const toCsv = (headers, rows) => [headers, ...rows].map((cells) => cells.map(escapeCsvValue).join(",")).join("\n");
2446
+ function buildSignInCsv(rows) {
2447
+ return toCsv(
2448
+ SIGN_IN_CSV_HEADERS,
2449
+ rows.map((row) => [
2450
+ row.at || "",
2451
+ row.event || "",
2452
+ row.reason || row.scope || "",
2453
+ row.admin?.name || "",
2454
+ row.admin?.id ?? "",
2455
+ row.ipAddress || "",
2456
+ row.ipAnonymized ? "yes" : "no",
2457
+ row.location?.country || "",
2458
+ row.location?.city || "",
2459
+ row.browser || "",
2460
+ row.os || "",
2461
+ row.deviceType || "",
2462
+ row.session?.state || "",
2463
+ row.actor?.name || ""
2464
+ ])
2465
+ );
2466
+ }
2467
+ function buildActivityCsv(rows) {
2468
+ return toCsv(
2469
+ ACTIVITY_CSV_HEADERS,
2470
+ rows.map((row) => [
2471
+ row.at || "",
2472
+ row.action || "",
2473
+ row.admin?.name || "",
2474
+ row.admin?.id ?? "",
2475
+ row.contentType?.name || "",
2476
+ row.contentType?.uid || "",
2477
+ row.entry?.documentId || "",
2478
+ row.entry?.locale || "",
2479
+ row.entry?.title || "",
2480
+ row.entry?.count ?? ""
2481
+ ])
2482
+ );
2483
+ }
2484
+ const pluginId = "magic-sessionmanager";
2485
+ const USER_ACTIVITY_FILTER_OPTIONS = Object.freeze([
2486
+ "all",
2487
+ "failed",
2488
+ "lockouts",
2489
+ "suspicious",
2490
+ "sessions",
2491
+ "privacy",
2492
+ "impersonation"
2493
+ ]);
2494
+ const USER_ACTIVITY_FILTER_LABELS = Object.freeze({
2495
+ all: ["userActivity.filter.all", "All events"],
2496
+ failed: ["userActivity.filter.failed", "Failed and refused sign-ins"],
2497
+ lockouts: ["userActivity.filter.lockouts", "Lockouts and unlocks"],
2498
+ suspicious: [
2499
+ "userActivity.filter.suspicious",
2500
+ "New devices, impossible travel, “This wasn’t me”"
2501
+ ],
2502
+ sessions: ["userActivity.filter.sessions", "Session limit and password change"],
2503
+ privacy: ["userActivity.filter.privacy", "Personal data exports"],
2504
+ impersonation: ["userActivity.filter.impersonation", "Impersonation"]
2505
+ });
2506
+ const USER_ACTIVITY_API_PATH = `/${pluginId}/user-activity`;
2507
+ const USER_ACTIVITY_PAGE_PATH = `/plugins/${pluginId}/app-users/activity`;
2508
+ const USER_ACTIVITY_SETTINGS_PATH = `/settings/${pluginId}/general?tab=login-protection`;
2509
+ const RECENT_USER_EVENT_LIMIT = 8;
2510
+ const PANEL_USER_EVENT_LIMIT = 3;
2511
+ const USER_UID = "plugin::users-permissions.user";
2512
+ const DOCUMENT_ID = /^[A-Za-z0-9]{1,64}$/;
2513
+ function userActivityPagePath(userId) {
2514
+ return typeof userId === "string" && DOCUMENT_ID.test(userId) ? `${USER_ACTIVITY_PAGE_PATH}?userId=${encodeURIComponent(userId)}` : USER_ACTIVITY_PAGE_PATH;
2515
+ }
2516
+ function getUserEntryPath(user) {
2517
+ if (!user || typeof user.documentId !== "string" || !DOCUMENT_ID.test(user.documentId)) {
2518
+ return null;
2519
+ }
2520
+ return `/content-manager/collection-types/${USER_UID}/${encodeURIComponent(user.documentId)}`;
2521
+ }
2522
+ function buildUserActivityParams(filters, now) {
2523
+ const params = {
2524
+ page: filters.page || 1,
2525
+ pageSize: filters.pageSize || EVENT_PAGE_SIZE,
2526
+ event: USER_ACTIVITY_FILTER_OPTIONS.includes(filters.event) ? filters.event : "all"
2527
+ };
2528
+ if (typeof filters.userId === "string" && DOCUMENT_ID.test(filters.userId)) {
2529
+ params.userId = filters.userId;
2530
+ }
2531
+ const from = periodStart(filters.period || "all", now);
2532
+ if (from) params.from = from;
2533
+ return params;
2534
+ }
2535
+ function parseUserActivityQuery(query) {
2536
+ const source = query || {};
2537
+ const event = USER_ACTIVITY_FILTER_OPTIONS.includes(String(source.event)) ? String(source.event) : "all";
2538
+ const period = PERIOD_OPTIONS.includes(String(source.period)) ? String(source.period) : "30";
2539
+ const userId = DOCUMENT_ID.test(String(source.userId ?? "")) ? String(source.userId) : null;
2540
+ const page = Number.parseInt(String(source.page ?? ""), 10);
2541
+ const pageSize = String(source.pageSize ?? "");
2542
+ return {
2543
+ event,
2544
+ period,
2545
+ userId,
2546
+ page: Number.isInteger(page) && page > 0 ? page : 1,
2547
+ pageSize: ACTIVITY_PAGE_SIZE_OPTIONS.includes(pageSize) ? Number(pageSize) : EVENT_PAGE_SIZE
2548
+ };
2549
+ }
2550
+ function hasUserActivityFilters(view) {
2551
+ return view.event !== "all" || view.period !== "30" || view.userId !== null;
2552
+ }
2553
+ const message = (messageId, defaultMessage, values) => ({
2554
+ messageId,
2555
+ defaultMessage,
2556
+ ...values ? { values } : {}
2557
+ });
2558
+ const REFUSAL_REASONS = Object.freeze({
2559
+ lockout: message("userActivity.detail.refused.lockout", "The account or IP address was locked"),
2560
+ "too-many-attempts": message(
2561
+ "userActivity.detail.refused.tooMany",
2562
+ "Too many sign-ins at the same time"
2563
+ ),
2564
+ country: message("userActivity.detail.refused.country", "Sign-ins from this country are blocked"),
2565
+ risk: message("userActivity.detail.refused.risk", "Risky address (VPN, proxy or Tor)"),
2566
+ "location-unavailable": message(
2567
+ "userActivity.detail.refused.location",
2568
+ "The location could not be checked"
2569
+ )
2570
+ });
2571
+ const IMPERSONATION_REFUSALS = Object.freeze({
2572
+ disabled: message("userActivity.detail.impersonation.disabled", "Impersonation is turned off"),
2573
+ blocked: message("userActivity.detail.impersonation.blocked", "The account is blocked"),
2574
+ "already-active": message(
2575
+ "userActivity.detail.impersonation.alreadyActive",
2576
+ "Someone is already impersonating this user"
2577
+ ),
2578
+ "api-token": message(
2579
+ "userActivity.detail.impersonation.apiToken",
2580
+ "Admin API tokens cannot impersonate"
2581
+ ),
2582
+ "call-credentials": message(
2583
+ "userActivity.detail.impersonation.callCredentials",
2584
+ "A sign-in, password or email request was blocked"
2585
+ ),
2586
+ "call-account": message(
2587
+ "userActivity.detail.impersonation.callAccount",
2588
+ "A data export or “This wasn’t me” request was blocked"
2589
+ ),
2590
+ "call-sessions": message(
2591
+ "userActivity.detail.impersonation.callSessions",
2592
+ "A request to end sessions was blocked"
2593
+ )
2594
+ });
2595
+ const UNKNOWN_ACCOUNT = message(
2596
+ "userActivity.detail.unknownAccount",
2597
+ "No account with this email or username"
2598
+ );
2599
+ function getUserEventDetail(row) {
2600
+ const d = row?.details || {};
2601
+ const parts = [];
2602
+ switch (row?.event) {
2603
+ case "user.sign-in.failed":
2604
+ if (d.unknownAccount) parts.push(UNKNOWN_ACCOUNT);
2605
+ break;
2606
+ case "user.sign-in.refused":
2607
+ if (d.reason === "session-limit") {
2608
+ parts.push(
2609
+ Number.isInteger(d.limit) ? message(
2610
+ "userActivity.detail.refused.limit",
2611
+ "Session limit of {limit, number} reached",
2612
+ { limit: d.limit }
2613
+ ) : message("userActivity.detail.refused.limitReached", "Session limit reached")
2614
+ );
2615
+ } else if (REFUSAL_REASONS[d.reason]) parts.push(REFUSAL_REASONS[d.reason]);
2616
+ if (d.unknownAccount) parts.push(UNKNOWN_ACCOUNT);
2617
+ break;
2618
+ case "user.lockout":
2619
+ if (Number.isInteger(d.minutes) && Number.isInteger(d.failures)) {
2620
+ parts.push(
2621
+ d.kind === "ip" ? message(
2622
+ "userActivity.detail.lockout.ip",
2623
+ "IP address locked for {minutes, plural, one {# minute} other {# minutes}} after {failures, plural, one {# failed sign-in} other {# failed sign-ins}}",
2624
+ { minutes: d.minutes, failures: d.failures }
2625
+ ) : message(
2626
+ "userActivity.detail.lockout.account",
2627
+ "Account locked for {minutes, plural, one {# minute} other {# minutes}} after {failures, plural, one {# failed sign-in} other {# failed sign-ins}}",
2628
+ { minutes: d.minutes, failures: d.failures }
2629
+ )
2630
+ );
2631
+ }
2632
+ break;
2633
+ case "user.lockout.lifted":
2634
+ parts.push(
2635
+ d.kind === "ip" ? message("userActivity.detail.unlock.ip", "An admin unlocked an IP address") : message("userActivity.detail.unlock.account", "An admin unlocked the account")
2636
+ );
2637
+ break;
2638
+ case "user.session.limit":
2639
+ if (Number.isInteger(d.ended)) {
2640
+ parts.push(
2641
+ Number.isInteger(d.limit) ? message(
2642
+ "userActivity.detail.limit.ended",
2643
+ "{ended, plural, one {# older session} other {# older sessions}} ended to stay within {limit, number}",
2644
+ { ended: d.ended, limit: d.limit }
2645
+ ) : message(
2646
+ "userActivity.detail.limit.endedOnly",
2647
+ "{ended, plural, one {# older session} other {# older sessions}} ended",
2648
+ { ended: d.ended }
2649
+ )
2650
+ );
2651
+ }
2652
+ break;
2653
+ case "user.password-change.ended-others":
2654
+ if (Number.isInteger(d.ended)) {
2655
+ parts.push(
2656
+ message(
2657
+ "userActivity.detail.password.ended",
2658
+ "{ended, plural, =0 {No other session was open} one {# other session ended} other {# other sessions ended}}",
2659
+ { ended: d.ended }
2660
+ )
2661
+ );
2662
+ }
2663
+ break;
2664
+ case "user.sign-in.impossible-travel":
2665
+ if (Number.isInteger(d.distanceKm) && Number.isInteger(d.speedKmh)) {
2666
+ parts.push(
2667
+ message(
2668
+ "userActivity.detail.travel.distance",
2669
+ "{distance, number} km from the last sign-in, {speed, number} km/h",
2670
+ { distance: d.distanceKm, speed: d.speedKmh }
2671
+ )
2672
+ );
2673
+ }
2674
+ if (d.from && d.to) {
2675
+ parts.push(
2676
+ message("userActivity.detail.travel.countries", "{from} to {to}", {
2677
+ from: d.from,
2678
+ to: d.to
2679
+ })
2680
+ );
2681
+ }
2682
+ if (d.action === "reauthenticate") {
2683
+ parts.push(
2684
+ message(
2685
+ "userActivity.detail.travel.reauthenticate",
2686
+ "All sessions ended, a new sign-in was required"
2687
+ )
2688
+ );
2689
+ }
2690
+ break;
2691
+ case "user.not-me":
2692
+ parts.push(
2693
+ d.scope === "all" ? message("userActivity.detail.notMe.all", "The user ended all their sessions") : message("userActivity.detail.notMe.session", "The user ended that session")
2694
+ );
2695
+ break;
2696
+ case "user.data.exported":
2697
+ if (Number.isInteger(d.sessions) && Number.isInteger(d.events)) {
2698
+ parts.push(
2699
+ message(
2700
+ "userActivity.detail.export.counts",
2701
+ "The user downloaded {count, plural, one {# session} other {# sessions}} and {events, plural, one {# security event} other {# security events}}",
2702
+ { count: d.sessions, events: d.events }
2703
+ )
2704
+ );
2705
+ }
2706
+ break;
2707
+ case "impersonation.started":
2708
+ if (Number.isInteger(d.durationMinutes)) {
2709
+ parts.push(
2710
+ message(
2711
+ "userActivity.detail.impersonation.duration",
2712
+ "For {minutes, plural, one {# minute} other {# minutes}}",
2713
+ { minutes: d.durationMinutes }
2714
+ )
2715
+ );
2716
+ }
2717
+ break;
2718
+ case "impersonation.ended":
2719
+ if (d.endReason === "disabled") {
2720
+ parts.push(
2721
+ message(
2722
+ "userActivity.detail.impersonation.endedDisabled",
2723
+ "Ended because impersonation was turned off"
2724
+ )
2725
+ );
2726
+ } else if (d.endReason === "failed") {
2727
+ parts.push(
2728
+ message("userActivity.detail.impersonation.endedFailed", "Could not be completed")
2729
+ );
2730
+ } else {
2731
+ parts.push(message("userActivity.detail.impersonation.endedByAdmin", "Ended by an admin"));
2732
+ }
2733
+ break;
2734
+ case "impersonation.expired":
2735
+ parts.push(message("userActivity.detail.impersonation.expired", "The time ran out"));
2736
+ break;
2737
+ case "impersonation.refused":
2738
+ if (IMPERSONATION_REFUSALS[d.refusal]) parts.push(IMPERSONATION_REFUSALS[d.refusal]);
2739
+ break;
2740
+ }
2741
+ return parts;
2742
+ }
2743
+ const USER_ACTIVITY_CSV_HEADERS = Object.freeze([
2744
+ "Time",
2745
+ "Event",
2746
+ "Reason",
2747
+ "User",
2748
+ "User ID",
2749
+ "User Document ID",
2750
+ "IP Address",
2751
+ "IP Anonymized",
2752
+ "Country",
2753
+ "City",
2754
+ "Browser",
2755
+ "OS",
2756
+ "Device",
2757
+ "Done By",
2758
+ "Done By Admin ID"
2759
+ ]);
2760
+ function buildUserActivityCsv(rows) {
2761
+ const lines = rows.map((row) => {
2762
+ const d = row.details || {};
2763
+ return [
2764
+ row.at || "",
2765
+ row.event || "",
2766
+ d.reason || d.refusal || d.endReason || d.kind || d.scope || "",
2767
+ row.user?.email || row.user?.username || "",
2768
+ row.user?.id ?? "",
2769
+ row.user?.documentId || "",
2770
+ row.ipAddress || "",
2771
+ row.ipAnonymized ? "yes" : "no",
2772
+ row.location?.country || "",
2773
+ row.location?.city || "",
2774
+ row.browser || "",
2775
+ row.os || "",
2776
+ row.deviceType || "",
2777
+ row.actor?.type === "system" ? "system" : row.actor?.name || "",
2778
+ row.actor?.type === "admin" ? row.actor.id ?? "" : ""
2779
+ ];
2780
+ });
2781
+ return [USER_ACTIVITY_CSV_HEADERS, ...lines].map((cells) => cells.map(escapeCsvValue).join(",")).join("\n");
2782
+ }
2783
+ const settingsGroupText = (t, group) => {
2784
+ const fields = group.fields.map(
2785
+ (field) => field.label ? t(field.label.messageId, field.label.defaultMessage) : field.key
2786
+ ).join(", ");
2787
+ return group.label ? t("adminPanel.activity.settingsGroup", "{tab}: {fields}", {
2788
+ tab: t(group.label.messageId, group.label.defaultMessage),
2789
+ fields
2790
+ }) : fields;
2791
+ };
2792
+ const changedSettingsText = (t, keys, { limit } = {}) => {
2793
+ const groups = groupChangedSettings(keys);
2794
+ const total = groups.reduce((sum, group) => sum + group.fields.length, 0);
2795
+ if (!total) return "";
2796
+ let budget = limit && limit > 0 ? limit : total;
2797
+ const shown = [];
2798
+ for (const group of groups) {
2799
+ if (budget <= 0) break;
2800
+ shown.push({ ...group, fields: group.fields.slice(0, budget) });
2801
+ budget -= Math.min(budget, group.fields.length);
2802
+ }
2803
+ const named = shown.reduce((sum, group) => sum + group.fields.length, 0);
2804
+ const text = shown.map((group) => settingsGroupText(t, group)).join(" · ");
2805
+ return named < total ? t("adminPanel.activity.settingsMore", "{names} and {count, number} more", {
2806
+ names: text,
2807
+ count: total - named
2808
+ }) : text;
2809
+ };
2810
+ const changedSettingsLines = (t, keys) => groupChangedSettings(keys).map((group) => settingsGroupText(t, group));
2811
+ const noAdminText = (t, row) => row?.event === "security-log.retention.purged" ? t("adminPanel.activity.system", "System") : t("adminPanel.activity.unknownAccount", "Unknown account");
2812
+ const deviceText = (t, row) => {
2813
+ if (row.browser && row.os) {
2814
+ return t("adminPanel.activity.browserOnOs", "{browser} on {os}", {
2815
+ browser: row.browser,
2816
+ os: row.os
2817
+ });
2818
+ }
2819
+ return row.browser || row.os || "";
2820
+ };
2821
+ const ipText = (t, row) => {
2822
+ if (!row.ipAddress) return "";
2823
+ return row.ipAnonymized ? t("adminPanel.activity.ipAnonymized", "{ip} (anonymised)", { ip: row.ipAddress }) : row.ipAddress;
2824
+ };
2825
+ const eventDetailText = (t, row, presentation, withActor) => {
2826
+ const parts = [];
2827
+ if (presentation.detail) {
2828
+ parts.push(t(presentation.detail.messageId, presentation.detail.defaultMessage));
2829
+ }
2830
+ if (Number.isInteger(row.attempts) && row.attempts > 1) {
2831
+ parts.push(
2832
+ t(
2833
+ "adminPanel.activity.attempts",
2834
+ "{count, plural, one {# attempt} other {# attempts}} within 5 minutes",
2835
+ { count: row.attempts }
2836
+ )
2837
+ );
2838
+ }
2839
+ const changed = changedSettingsText(t, row.change?.keys, { limit: 3 });
2840
+ if (changed) parts.push(changed);
2841
+ if (Number.isInteger(row.purge?.count)) {
2842
+ parts.push(
2843
+ Number.isInteger(row.purge?.retentionDays) ? t(
2844
+ "adminPanel.activity.purgedDetail",
2845
+ "{count, plural, one {# event} other {# events}}, older than {days, plural, one {# day} other {# days}}",
2846
+ { count: row.purge.count, days: row.purge.retentionDays }
2847
+ ) : t("adminPanel.activity.purgedCount", "{count, plural, one {# event} other {# events}}", {
2848
+ count: row.purge.count
2849
+ })
2850
+ );
2851
+ }
2852
+ if (withActor && row.actor?.name) {
2853
+ parts.push(t("adminPanel.activity.byAdmin", "by {name}", { name: row.actor.name }));
2854
+ }
2855
+ return parts.join(" · ");
2856
+ };
2857
+ const contentTypeText = (row) => [row.contentType?.name, row.entry?.locale].filter(Boolean).join(" · ");
2858
+ const userEventDetailText = (t, row, withActor = false) => {
2859
+ const parts = getUserEventDetail(row).map(
2860
+ (part) => t(part.messageId, part.defaultMessage, part.values)
2861
+ );
2862
+ if (withActor && row?.actor?.type === "admin" && row.actor.name) {
2863
+ parts.push(t("adminPanel.activity.byAdmin", "by {name}", { name: row.actor.name }));
2864
+ }
2865
+ return parts.join(" · ");
2866
+ };
2867
+ const userText = (t, row) => {
2868
+ const user = row?.user;
2869
+ if (user) {
2870
+ return user.email || user.username || t("userActivity.identity.placeholder", "User #{id}", { id: user.id });
2871
+ }
2872
+ if (row?.target === "ip") return t("userActivity.identity.ipLock", "IP address");
2873
+ return t("adminPanel.activity.unknownAccount", "Unknown account");
2874
+ };
2875
+ const doneByText = (t, row) => {
2876
+ if (row?.actor?.type === "system") return t("userActivity.doneBy.system", "Automatic");
2877
+ if (row?.actor?.type === "admin") {
2878
+ return row.actor.name || t("adminPanel.identity.placeholder", "Admin #{id}", { id: row.actor.id ?? "?" });
2879
+ }
2880
+ return "";
2881
+ };
2882
+ const useT = () => {
2883
+ const { formatMessage } = useIntl();
2884
+ return (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
2885
+ };
2886
+ const SHORT_DATE = Object.freeze({ dateStyle: "medium", timeStyle: "short" });
2887
+ const FULL_DATE = Object.freeze({ dateStyle: "full", timeStyle: "medium" });
2888
+ const EVENT_ICONS = Object.freeze({
2889
+ signIn: CheckCircle,
2890
+ failed: CrossCircle,
2891
+ lockout: Lock,
2892
+ signOut: SignOut,
2893
+ revoked: Shield,
2894
+ settings: Cog,
2895
+ logRead: Key,
2896
+ purged: Trash,
2897
+ refused: CrossCircle,
2898
+ unlock: Lock,
2899
+ limit: Stack,
2900
+ password: Key,
2901
+ device: Monitor,
2902
+ travel: Earth,
2903
+ notMe: WarningCircle,
2904
+ export: Download,
2905
+ impersonation: User,
2906
+ impersonationEnd: Stop,
2907
+ expired: Clock,
2908
+ webhook: Webhooks,
2909
+ other: Information
2910
+ });
2911
+ const ICON_FILL = Object.freeze({
2912
+ success: "success600",
2913
+ danger: "danger600",
2914
+ warning: "warning700",
2915
+ secondary: "secondary600",
2916
+ neutral: "neutral600"
2917
+ });
2918
+ const stopCellKeys = (event) => {
2919
+ if (event.key === "Enter" || event.key === " " || event.key === "Spacebar") {
2920
+ event.stopPropagation();
2921
+ }
2922
+ };
2923
+ const ClickableRow = styled(Tr)`
2924
+ cursor: pointer;
2925
+ `;
2926
+ const WrapCell = styled(Td)`
2927
+ white-space: normal;
2928
+ `;
2929
+ const NoWrap = styled.span`
2930
+ white-space: nowrap;
2931
+ `;
2932
+ const NameButton = styled(TextButton)`
2933
+ min-height: 3.2rem;
2934
+ text-align: start;
2935
+ `;
2936
+ const StackedList = styled.ul`
2937
+ margin: 0;
2938
+ padding: 0;
2939
+ list-style: none;
2940
+ border: 1px solid ${({ theme }) => theme.colors.neutral150};
2941
+ border-radius: ${({ theme }) => theme.borderRadius};
2942
+ background: ${({ theme }) => theme.colors.neutral0};
2943
+ min-width: 0;
2944
+
2945
+ & > li + li {
2946
+ border-top: 1px solid ${({ theme }) => theme.colors.neutral150};
2947
+ }
2948
+ `;
2949
+ const StackedItem = styled.li`
2950
+ cursor: pointer;
2951
+ min-width: 0;
2952
+ `;
2953
+ const BreakAnywhere = styled(Typography)`
2954
+ overflow-wrap: anywhere;
2955
+ `;
2956
+ const getEventBadgeColors = (tone) => tone === "danger" ? { backgroundColor: "danger100", textColor: "danger700" } : getBadgeColors(tone);
2957
+ const EventBadge = ({ presentation, nowrap = false }) => {
2958
+ const t = useT();
2959
+ const Icon = EVENT_ICONS[presentation.icon] || Information;
2960
+ return /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", shrink: 0, "data-event-kind": presentation.key, children: [
2961
+ /* @__PURE__ */ jsx(
2962
+ Icon,
2963
+ {
2964
+ "aria-hidden": "true",
2965
+ focusable: "false",
2966
+ width: "1.6rem",
2967
+ height: "1.6rem",
2968
+ fill: ICON_FILL[presentation.tone] || ICON_FILL.neutral
2969
+ }
2970
+ ),
2971
+ /* @__PURE__ */ jsx(Badge, { ...getEventBadgeColors(presentation.tone), "data-event-tone": presentation.tone, children: nowrap ? /* @__PURE__ */ jsx(NoWrap, { children: t(presentation.label.messageId, presentation.label.defaultMessage) }) : t(presentation.label.messageId, presentation.label.defaultMessage) })
2972
+ ] });
2973
+ };
2974
+ const EventTime = ({ value, compact = false }) => {
2975
+ const { formatDate, formatRelativeTime } = useSessionFormatters();
2976
+ const date = toValidDate(value);
2977
+ if (!date) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
2978
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
2979
+ /* @__PURE__ */ jsx(
2980
+ Typography,
2981
+ {
2982
+ tag: "time",
2983
+ dateTime: date.toISOString(),
2984
+ variant: compact ? "pi" : "omega",
2985
+ textColor: "neutral800",
2986
+ children: /* @__PURE__ */ jsx(NoWrap, { children: formatRelativeTime(date) })
2987
+ }
2988
+ ),
2989
+ compact ? null : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: /* @__PURE__ */ jsx(NoWrap, { children: formatDate(date, SHORT_DATE) }) })
2990
+ ] });
2991
+ };
2992
+ const AdminName = ({ admin, row, onOpenAdmin }) => {
2993
+ const t = useT();
2994
+ if (!admin) {
2995
+ return /* @__PURE__ */ jsx(Typography, { variant: onOpenAdmin ? "pi" : "omega", textColor: "neutral600", children: noAdminText(t, row) });
2996
+ }
2997
+ if (!onOpenAdmin) {
2998
+ return /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: admin.name });
2999
+ }
3000
+ return /* @__PURE__ */ jsx(
3001
+ NameButton,
3002
+ {
3003
+ onClick: (event) => {
3004
+ event.stopPropagation();
3005
+ onOpenAdmin(admin, event.currentTarget);
3006
+ },
3007
+ onKeyDown: stopCellKeys,
3008
+ "aria-label": t("adminPanel.activity.openAdmin", "Open the details of {name}", {
3009
+ name: admin.name
3010
+ }),
3011
+ children: admin.name
3012
+ }
3013
+ );
3014
+ };
3015
+ const SignInDetails = ({ row }) => {
3016
+ const t = useT();
3017
+ const ip = ipText(t, row);
3018
+ const second = [getEventPlace(row), deviceText(t, row)].filter(Boolean).join(" · ");
3019
+ if (!ip && !second) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3020
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3021
+ ip ? /* @__PURE__ */ jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: ip }) : null,
3022
+ second ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3023
+ ] });
3024
+ };
3025
+ const SessionState = ({ row }) => {
3026
+ const t = useT();
3027
+ const { formatRelativeTime } = useSessionFormatters();
3028
+ const state = getSessionStatePresentation(row.session);
3029
+ if (!state) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3030
+ const endedAt = toValidDate(row.session?.endedAt);
3031
+ const second = [
3032
+ endedAt ? formatRelativeTime(endedAt) : "",
3033
+ row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3034
+ ].filter(Boolean).join(" · ");
3035
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3036
+ /* @__PURE__ */ jsx(
3037
+ Typography,
3038
+ {
3039
+ variant: "omega",
3040
+ fontWeight: state.tone === "success" ? "semiBold" : void 0,
3041
+ textColor: state.tone === "success" ? "success600" : "neutral800",
3042
+ "data-session-state": row.session?.state,
3043
+ children: t(state.label.messageId, state.label.defaultMessage)
3044
+ }
3045
+ ),
3046
+ second ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: second }) : null
3047
+ ] });
3048
+ };
3049
+ const HeaderCell = ({ children, hidden = false, ...rest }) => /* @__PURE__ */ jsx(Th, { ...rest, children: hidden ? /* @__PURE__ */ jsx(VisuallyHidden, { children }) : /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children }) });
3050
+ const DetailsButton = ({ label, onOpen }) => /* @__PURE__ */ jsx(
3051
+ IconButton,
3052
+ {
3053
+ variant: "ghost",
3054
+ label,
3055
+ withTooltip: false,
3056
+ onClick: (event) => {
3057
+ event.stopPropagation();
3058
+ onOpen(event.currentTarget);
3059
+ },
3060
+ onKeyDown: stopCellKeys,
3061
+ "data-event-details": "",
3062
+ children: /* @__PURE__ */ jsx(Eye, {})
3063
+ }
3064
+ );
3065
+ const ActivityEntry = ({ row }) => {
3066
+ const t = useT();
3067
+ const path = getEntryPath(row);
3068
+ const name2 = row.entry?.count !== null && row.entry?.count !== void 0 ? t("adminPanel.activity.entries", "{count, plural, one {# entry} other {# entries}}", {
3069
+ count: row.entry.count
3070
+ }) : row.entry?.title || row.entry?.documentId || row.contentType?.name || "";
3071
+ if (!name2) return /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3072
+ if (!path) {
3073
+ return /* @__PURE__ */ jsx(BreakAnywhere, { variant: "omega", textColor: "neutral800", children: name2 });
3074
+ }
3075
+ return /* @__PURE__ */ jsx(
3076
+ TargetLink,
3077
+ {
3078
+ tag: Link$1,
3079
+ to: path,
3080
+ onClick: (event) => event.stopPropagation(),
3081
+ onKeyDown: stopCellKeys,
3082
+ "aria-label": t("adminPanel.activity.openEntry", "Open {entry} in the Content Manager", {
3083
+ entry: name2
3084
+ }),
3085
+ children: name2
3086
+ }
3087
+ );
3088
+ };
3089
+ const EventDetailsModal = ({ title, items, footerAction, onClose, onCloseAutoFocus }) => {
3090
+ const t = useT();
3091
+ return /* @__PURE__ */ jsx(Modal.Root, { open: true, onOpenChange: (open) => open ? null : onClose(), children: /* @__PURE__ */ jsxs(Modal.Content, { onCloseAutoFocus, "aria-describedby": void 0, children: [
3092
+ /* @__PURE__ */ jsx(Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsx(Modal.Title, { children: title }) }),
3093
+ /* @__PURE__ */ jsx(Modal.Body, { children: /* @__PURE__ */ jsx(Box, { background: "neutral100", hasRadius: true, padding: { initial: 4, medium: 6 }, children: /* @__PURE__ */ jsx(PropertyList, { columns: 2, items }) }) }),
3094
+ /* @__PURE__ */ jsxs(Modal.Footer, { children: [
3095
+ /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: t("common.close", "Close") }) }),
3096
+ footerAction || null
3097
+ ] })
3098
+ ] }) });
3099
+ };
3100
+ const useEventDetails = () => {
3101
+ const [selected, setSelected] = useState(null);
3102
+ const [opener, setOpener] = useState(null);
3103
+ const [container, setContainer] = useState(null);
3104
+ return {
3105
+ selected,
3106
+ setContainer,
3107
+ open: (row, trigger) => {
3108
+ const button = trigger?.matches?.("[data-event-details]") ? trigger : trigger?.querySelector?.("[data-event-details]");
3109
+ setOpener(button || null);
3110
+ setSelected(row);
3111
+ },
3112
+ close: () => setSelected(null),
3113
+ onCloseAutoFocus: (event) => restoreDialogFocus(event, opener, container)
3114
+ };
3115
+ };
3116
+ const signInDetails = (t, formatDate, row) => {
3117
+ const presentation = getEventPresentation(row);
3118
+ const label = t(presentation.label.messageId, presentation.label.defaultMessage);
3119
+ const state = getSessionStatePresentation(row.session);
3120
+ const revoked = presentation.key === "revoked";
3121
+ const adminName = row.admin?.name || noAdminText(t, row);
3122
+ const items = [
3123
+ {
3124
+ id: "event",
3125
+ label: t("adminPanel.activity.column.event", "Event"),
3126
+ render: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
3127
+ /* @__PURE__ */ jsx(EventBadge, { presentation }),
3128
+ presentation.detail ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(presentation.detail.messageId, presentation.detail.defaultMessage) }) : null
3129
+ ] })
3130
+ },
3131
+ {
3132
+ id: "time",
3133
+ label: t("adminPanel.activity.details.exactTime", "Exact time"),
3134
+ value: row.at ? formatDate(row.at, FULL_DATE) : null
3135
+ },
3136
+ { id: "admin", label: t("adminPanel.activity.column.admin", "Admin"), value: adminName }
3137
+ ];
3138
+ if (revoked) {
3139
+ items.push(
3140
+ {
3141
+ id: "actor",
3142
+ label: t("adminPanel.activity.column.doneBy", "Done by"),
3143
+ value: row.actor?.name || null
3144
+ },
3145
+ {
3146
+ id: "scope",
3147
+ label: t("adminPanel.activity.details.signedOutOf", "Signed out of"),
3148
+ value: Number.isInteger(row.sessionsEnded) && row.sessionsEnded >= 0 ? t(
3149
+ "adminPanel.activity.details.scopeCount",
3150
+ "{scope} ({count, plural, =0 {no open session} one {# session ended} other {# sessions ended}})",
3151
+ {
3152
+ scope: t(presentation.detail.messageId, presentation.detail.defaultMessage),
3153
+ count: row.sessionsEnded
3154
+ }
3155
+ ) : t(presentation.detail.messageId, presentation.detail.defaultMessage)
3156
+ }
3157
+ );
3158
+ }
3159
+ if (state) {
3160
+ const endedAt = toValidDate(row.session?.endedAt);
3161
+ items.push({
3162
+ id: "session",
3163
+ label: t("adminPanel.activity.column.session", "Session"),
3164
+ value: [
3165
+ t(state.label.messageId, state.label.defaultMessage),
3166
+ endedAt ? formatDate(endedAt, SHORT_DATE) : "",
3167
+ row.session?.endedBy?.name ? t("adminPanel.activity.byAdmin", "by {name}", { name: row.session.endedBy.name }) : ""
3168
+ ].filter(Boolean).join(" · ")
3169
+ });
3170
+ }
3171
+ if (row.change) {
3172
+ const lines = changedSettingsLines(t, row.change.keys);
3173
+ items.push({
3174
+ id: "settings",
3175
+ label: t("adminPanel.activity.details.changedSettings", "Changed settings"),
3176
+ ...lines.length ? {
3177
+ render: /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-changed-settings": "", children: lines.map((line) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: line }, line)) })
3178
+ } : { value: null },
3179
+ fullWidth: true
3180
+ });
3181
+ }
3182
+ if (row.purge) {
3183
+ items.push(
3184
+ {
3185
+ id: "purged",
3186
+ label: t("adminPanel.activity.details.deleted", "Deleted events"),
3187
+ value: Number.isInteger(row.purge.count) ? row.purge.count : null
3188
+ },
3189
+ {
3190
+ id: "retention",
3191
+ label: t("adminPanel.activity.details.retention", "Kept for"),
3192
+ value: Number.isInteger(row.purge.retentionDays) ? t("adminPanel.duration.days", "{count, plural, one {# day} other {# days}}", {
3193
+ count: row.purge.retentionDays
3194
+ }) : null
3195
+ }
3196
+ );
3197
+ }
3198
+ if (Number.isInteger(row.attempts) && row.attempts > 1) {
3199
+ items.push({
3200
+ id: "attempts",
3201
+ label: t("adminPanel.activity.details.attempts", "Attempts"),
3202
+ value: row.attempts
3203
+ });
3204
+ }
3205
+ items.push(
3206
+ {
3207
+ id: "ip",
3208
+ label: t("adminPanel.activity.details.ip", "IP address"),
3209
+ value: ipText(t, row) || null,
3210
+ kind: "id"
3211
+ },
3212
+ {
3213
+ id: "place",
3214
+ label: t("adminPanel.activity.details.location", "Location"),
3215
+ value: getEventPlace(row) || null
3216
+ },
3217
+ {
3218
+ id: "browser",
3219
+ label: t("adminPanel.activity.details.browser", "Browser"),
3220
+ value: row.browser || null
3221
+ },
3222
+ {
3223
+ id: "os",
3224
+ label: t("adminPanel.activity.details.os", "Operating system"),
3225
+ value: row.os || null
3226
+ },
3227
+ {
3228
+ id: "userAgent",
3229
+ label: t("adminPanel.activity.details.userAgent", "User agent"),
3230
+ value: row.userAgent || null,
3231
+ kind: "id",
3232
+ fullWidth: true
3233
+ },
3234
+ {
3235
+ id: "eventId",
3236
+ label: t("adminPanel.activity.details.eventId", "Event ID"),
3237
+ value: row.id,
3238
+ kind: "id"
3239
+ }
3240
+ );
3241
+ const title = row.admin?.name ? t("adminPanel.activity.details.title", "{event}: {name}", { event: label, name: adminName }) : label;
3242
+ const logEvent = ["settings", "log-read", "purged"].includes(presentation.key);
3243
+ const deviceFields = /* @__PURE__ */ new Set(["ip", "place", "browser", "os", "userAgent"]);
3244
+ return {
3245
+ title,
3246
+ items: logEvent ? items.filter(
3247
+ (item) => !deviceFields.has(item.id) || item.value !== null && item.value !== ""
3248
+ ) : items
3249
+ };
3250
+ };
3251
+ const activityDetails = (t, formatDate, row) => {
3252
+ const label = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3253
+ const action = t(label.messageId, label.defaultMessage);
3254
+ return {
3255
+ title: row.entry?.title ? t("adminPanel.activity.details.title", "{event}: {name}", {
3256
+ event: action,
3257
+ name: row.entry.title
3258
+ }) : action,
3259
+ items: [
3260
+ {
3261
+ id: "action",
3262
+ label: t("adminPanel.activity.column.action", "Action"),
3263
+ render: /* @__PURE__ */ jsx(Badge, { ...getBadgeColors(getActivityTone(row.action)), children: action })
3264
+ },
3265
+ {
3266
+ id: "time",
3267
+ label: t("adminPanel.activity.details.exactTime", "Exact time"),
3268
+ value: row.at ? formatDate(row.at, FULL_DATE) : null
3269
+ },
3270
+ {
3271
+ id: "entry",
3272
+ label: t("adminPanel.activity.column.entry", "Entry"),
3273
+ render: /* @__PURE__ */ jsx(ActivityEntry, { row })
3274
+ },
3275
+ {
3276
+ id: "admin",
3277
+ label: t("adminPanel.activity.column.admin", "Admin"),
3278
+ value: row.admin?.name || null
3279
+ },
3280
+ {
3281
+ id: "type",
3282
+ label: t("adminPanel.activity.column.contentType", "Content type"),
3283
+ value: row.contentType?.name || null
3284
+ },
3285
+ {
3286
+ id: "uid",
3287
+ label: t("adminPanel.activity.details.uid", "Content type UID"),
3288
+ value: row.contentType?.uid || null,
3289
+ kind: "id"
3290
+ },
3291
+ {
3292
+ id: "documentId",
3293
+ label: t("adminPanel.activity.details.documentId", "Document ID"),
3294
+ value: row.entry?.documentId || null,
3295
+ kind: "id"
3296
+ },
3297
+ {
3298
+ id: "locale",
3299
+ label: t("adminPanel.activity.details.locale", "Locale"),
3300
+ value: row.entry?.locale || null
3301
+ },
3302
+ {
3303
+ id: "eventId",
3304
+ label: t("adminPanel.activity.details.eventId", "Event ID"),
3305
+ value: row.id,
3306
+ kind: "id"
3307
+ }
3308
+ ]
3309
+ };
3310
+ };
3311
+ const userEventDetails = (t, formatDate, row) => {
3312
+ const presentation = getEventPresentation(row);
3313
+ const label = t(presentation.label.messageId, presentation.label.defaultMessage);
3314
+ const lines = getUserEventDetail(row).map(
3315
+ (part) => t(part.messageId, part.defaultMessage, part.values)
3316
+ );
3317
+ const who = userText(t, row);
3318
+ const doneBy = doneByText(t, row);
3319
+ const items = [
3320
+ {
3321
+ id: "event",
3322
+ label: t("adminPanel.activity.column.event", "Event"),
3323
+ render: /* @__PURE__ */ jsx(EventBadge, { presentation })
3324
+ },
3325
+ {
3326
+ id: "time",
3327
+ label: t("adminPanel.activity.details.exactTime", "Exact time"),
3328
+ value: row.at ? formatDate(row.at, FULL_DATE) : null
3329
+ },
3330
+ // Only events with facts get "What happened"; a dash there would say nothing.
3331
+ ...lines.length ? [
3332
+ {
3333
+ id: "what",
3334
+ label: t("userActivity.details.what", "What happened"),
3335
+ render: /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "flex-start", gap: 1, "data-event-facts": "", children: lines.map((line) => /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: line }, line)) }),
3336
+ fullWidth: true
3337
+ }
3338
+ ] : [],
3339
+ { id: "user", label: t("userActivity.column.user", "User"), value: who, kind: "id" }
3340
+ ];
3341
+ if (doneBy) {
3342
+ items.push({
3343
+ id: "doneBy",
3344
+ label: t("adminPanel.activity.column.doneBy", "Done by"),
3345
+ value: doneBy
3346
+ });
3347
+ }
3348
+ if (row.details?.reason && presentation.key.startsWith("impersonation")) {
3349
+ items.push({
3350
+ id: "reasonGiven",
3351
+ label: t("userActivity.details.reasonGiven", "Reason given"),
3352
+ value: row.details.reason,
3353
+ fullWidth: true
3354
+ });
3355
+ }
3356
+ items.push(
3357
+ {
3358
+ id: "ip",
3359
+ label: t("adminPanel.activity.details.ip", "IP address"),
3360
+ value: ipText(t, row) || null,
3361
+ kind: "id"
3362
+ },
3363
+ {
3364
+ id: "place",
3365
+ label: t("adminPanel.activity.details.location", "Location"),
3366
+ value: getEventPlace(row) || null
3367
+ },
3368
+ {
3369
+ id: "browser",
3370
+ label: t("adminPanel.activity.details.browser", "Browser"),
3371
+ value: row.browser || null
3372
+ },
3373
+ {
3374
+ id: "os",
3375
+ label: t("adminPanel.activity.details.os", "Operating system"),
3376
+ value: row.os || null
3377
+ },
3378
+ {
3379
+ id: "userAgent",
3380
+ label: t("adminPanel.activity.details.userAgent", "User agent"),
3381
+ value: row.userAgent || null,
3382
+ kind: "id",
3383
+ fullWidth: true
3384
+ },
3385
+ {
3386
+ id: "eventId",
3387
+ label: t("adminPanel.activity.details.eventId", "Event ID"),
3388
+ value: row.id,
3389
+ kind: "id"
3390
+ }
3391
+ );
3392
+ const deviceFields = /* @__PURE__ */ new Set(["ip", "place", "browser", "os", "userAgent"]);
3393
+ const byAdmin = row.actor?.type === "admin" || row.actor?.type === "system";
3394
+ return {
3395
+ title: t("adminPanel.activity.details.title", "{event}: {name}", { event: label, name: who }),
3396
+ items: byAdmin ? items.filter(
3397
+ (item) => !deviceFields.has(item.id) || item.value !== null && item.value !== ""
3398
+ ) : items
3399
+ };
3400
+ };
3401
+ const EventTable = ({
3402
+ rows,
3403
+ label,
3404
+ wide = false,
3405
+ busy = false,
3406
+ nameOf,
3407
+ badge,
3408
+ columns,
3409
+ stackedSubject,
3410
+ stackedDetail,
3411
+ details,
3412
+ detailsAction,
3413
+ rowKind
3414
+ }) => {
3415
+ const t = useT();
3416
+ const { formatRelativeTime } = useSessionFormatters();
3417
+ const [measureRef, width] = useElementWidth();
3418
+ const {
3419
+ selected,
3420
+ open: openDetails,
3421
+ close: closeDetails,
3422
+ onCloseAutoFocus,
3423
+ setContainer
3424
+ } = useEventDetails();
3425
+ const layout = getEventListLayout(width, { wide });
3426
+ const detailsLabel = (row) => t("adminPanel.activity.details.open", "Details of {event}, {time}", {
3427
+ event: nameOf(row),
3428
+ time: formatRelativeTime(row.at)
3429
+ });
3430
+ const kindOf = (row) => rowKind ? rowKind(row) : void 0;
3431
+ let list;
3432
+ if (layout === "stacked") {
3433
+ list = /* @__PURE__ */ jsx(StackedList, { "aria-label": label, "data-event-list": "stacked", children: rows.map((row) => {
3434
+ const subject = stackedSubject ? stackedSubject(row) : null;
3435
+ const detail = stackedDetail ? stackedDetail(row) : "";
3436
+ return /* @__PURE__ */ jsx(
3437
+ StackedItem,
3438
+ {
3439
+ "data-event-row": kindOf(row),
3440
+ "data-event-id": row.id,
3441
+ onClick: (event) => openDetails(row, event.currentTarget),
3442
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, padding: 3, minWidth: 0, children: [
3443
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", minWidth: 0, children: [
3444
+ badge(row),
3445
+ /* @__PURE__ */ jsxs(Flex, { gap: 1, alignItems: "center", marginLeft: "auto", children: [
3446
+ /* @__PURE__ */ jsx(EventTime, { value: row.at, compact: true }),
3447
+ /* @__PURE__ */ jsx(
3448
+ DetailsButton,
3449
+ {
3450
+ label: detailsLabel(row),
3451
+ onOpen: (trigger) => openDetails(row, trigger)
3452
+ }
3453
+ )
3454
+ ] })
3455
+ ] }),
3456
+ subject ? /* @__PURE__ */ jsx(Flex, { minWidth: 0, children: subject }) : null,
3457
+ detail ? /* @__PURE__ */ jsx(BreakAnywhere, { variant: "pi", textColor: "neutral600", children: detail }) : null
3458
+ ] })
3459
+ },
3460
+ row.id
3461
+ );
3462
+ }) });
3463
+ } else {
3464
+ const cols = columns(layout);
3465
+ list = /* @__PURE__ */ jsx(Box, { background: "neutral0", hasRadius: true, shadow: "tableShadow", "data-event-list": layout, children: /* @__PURE__ */ jsxs(
3466
+ Table,
3467
+ {
3468
+ colCount: cols.length + 2,
3469
+ rowCount: rows.length + 1,
3470
+ "aria-label": label,
3471
+ "aria-busy": busy,
3472
+ children: [
3473
+ /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
3474
+ /* @__PURE__ */ jsx(HeaderCell, { children: t("adminPanel.activity.column.time", "Time") }),
3475
+ cols.map((column) => /* @__PURE__ */ jsx(HeaderCell, { children: column.header }, column.id)),
3476
+ /* @__PURE__ */ jsx(HeaderCell, { hidden: true, children: t("adminPanel.table.actions", "Actions") })
3477
+ ] }) }),
3478
+ /* @__PURE__ */ jsx(Tbody, { children: rows.map((row) => /* @__PURE__ */ jsxs(
3479
+ ClickableRow,
3480
+ {
3481
+ "data-event-row": kindOf(row),
3482
+ "data-event-id": row.id,
3483
+ onClick: (event) => openDetails(row, event.currentTarget),
3484
+ children: [
3485
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(EventTime, { value: row.at }) }),
3486
+ cols.map(
3487
+ (column) => column.wrap === false ? /* @__PURE__ */ jsx(Td, { children: column.render(row, layout) }, column.id) : /* @__PURE__ */ jsx(WrapCell, { children: column.render(row, layout) }, column.id)
3488
+ ),
3489
+ /* @__PURE__ */ jsx(Td, { onClick: (event) => event.stopPropagation(), children: /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", gap: 1, onKeyDown: stopCellKeys, children: /* @__PURE__ */ jsx(
3490
+ DetailsButton,
3491
+ {
3492
+ label: detailsLabel(row),
3493
+ onOpen: (trigger) => openDetails(row, trigger)
3494
+ }
3495
+ ) }) })
3496
+ ]
3497
+ },
3498
+ row.id
3499
+ )) })
3500
+ ]
3501
+ }
3502
+ ) });
3503
+ }
3504
+ const content = selected ? details(selected) : null;
3505
+ return /* @__PURE__ */ jsxs(Box, { ref: measureRef, minWidth: 0, width: "100%", children: [
3506
+ /* @__PURE__ */ jsx(Box, { ref: setContainer, tabIndex: -1, minWidth: 0, children: list }),
3507
+ content ? /* @__PURE__ */ jsx(
3508
+ EventDetailsModal,
3509
+ {
3510
+ title: content.title,
3511
+ items: content.items,
3512
+ footerAction: detailsAction ? detailsAction(selected, closeDetails) : null,
3513
+ onClose: closeDetails,
3514
+ onCloseAutoFocus
3515
+ }
3516
+ ) : null
3517
+ ] });
3518
+ };
3519
+ const EventCell = ({ presentation, detail }) => /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
3520
+ /* @__PURE__ */ jsx(EventBadge, { presentation, nowrap: true }),
3521
+ detail ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: detail }) : null
3522
+ ] });
3523
+ const CellText = ({ text, strong = false }) => text ? /* @__PURE__ */ jsx(
3524
+ BreakAnywhere,
3525
+ {
3526
+ variant: "omega",
3527
+ fontWeight: strong ? "semiBold" : void 0,
3528
+ textColor: "neutral800",
3529
+ children: text
3530
+ }
3531
+ ) : /* @__PURE__ */ jsx(MissingValue, { variant: "omega" });
3532
+ const SignInEventTable = ({
3533
+ rows,
3534
+ label,
3535
+ showAdmin = false,
3536
+ onOpenAdmin,
3537
+ detailsAction,
3538
+ busy = false
3539
+ }) => {
3540
+ const t = useT();
3541
+ const { formatDate } = useSessionFormatters();
3542
+ const nameOf = (row) => {
3543
+ const presentation = getEventPresentation(row);
3544
+ return t(presentation.label.messageId, presentation.label.defaultMessage);
3545
+ };
3546
+ const adminName = (row) => /* @__PURE__ */ jsx(AdminName, { admin: row.admin, row, onOpenAdmin });
3547
+ return /* @__PURE__ */ jsx(
3548
+ EventTable,
3549
+ {
3550
+ rows,
3551
+ label,
3552
+ wide: showAdmin,
3553
+ busy,
3554
+ nameOf,
3555
+ rowKind: (row) => getEventPresentation(row).key,
3556
+ badge: (row) => /* @__PURE__ */ jsx(EventBadge, { presentation: getEventPresentation(row) }),
3557
+ columns: (layout) => [
3558
+ {
3559
+ id: "event",
3560
+ header: t("adminPanel.activity.column.event", "Event"),
3561
+ render: (row) => {
3562
+ const presentation = getEventPresentation(row);
3563
+ return /* @__PURE__ */ jsx(
3564
+ EventCell,
3565
+ {
3566
+ presentation,
3567
+ detail: eventDetailText(t, row, presentation, layout !== "full")
3568
+ }
3569
+ );
3570
+ }
3571
+ },
3572
+ ...showAdmin ? [
3573
+ {
3574
+ id: "admin",
3575
+ header: t("adminPanel.activity.column.admin", "Admin"),
3576
+ render: adminName
3577
+ }
3578
+ ] : [],
3579
+ {
3580
+ id: "details",
3581
+ header: t("adminPanel.activity.column.details", "IP address and device"),
3582
+ render: (row) => /* @__PURE__ */ jsx(SignInDetails, { row })
3583
+ },
3584
+ {
3585
+ id: "session",
3586
+ header: t("adminPanel.activity.column.session", "Session"),
3587
+ render: (row) => /* @__PURE__ */ jsx(SessionState, { row })
3588
+ },
3589
+ ...layout === "full" ? [
3590
+ {
3591
+ id: "doneBy",
3592
+ header: t("adminPanel.activity.column.doneBy", "Done by"),
3593
+ render: (row) => /* @__PURE__ */ jsx(CellText, { text: row.actor?.name || "" })
3594
+ }
3595
+ ] : []
3596
+ ],
3597
+ stackedSubject: showAdmin ? adminName : void 0,
3598
+ stackedDetail: (row) => {
3599
+ const presentation = getEventPresentation(row);
3600
+ const state = getSessionStatePresentation(row.session);
3601
+ return [
3602
+ eventDetailText(t, row, presentation, true),
3603
+ ipText(t, row),
3604
+ getEventPlace(row),
3605
+ deviceText(t, row),
3606
+ state ? t(state.label.messageId, state.label.defaultMessage) : ""
3607
+ ].filter(Boolean).join(" · ");
3608
+ },
3609
+ details: (row) => signInDetails(t, formatDate, row),
3610
+ detailsAction
3611
+ }
3612
+ );
3613
+ };
3614
+ const ActivityEventTable = ({ rows, label, showAdmin = false, busy = false }) => {
3615
+ const t = useT();
3616
+ const { formatDate } = useSessionFormatters();
3617
+ const actionOf = (row) => {
3618
+ const entry = ACTIVITY_ACTION_LABELS[row.action] || ACTIVITY_ACTION_LABELS.view;
3619
+ return t(entry.messageId, entry.defaultMessage);
3620
+ };
3621
+ const badge = (row) => /* @__PURE__ */ jsx(
3622
+ Badge,
3623
+ {
3624
+ ...getBadgeColors(getActivityTone(row.action)),
3625
+ "data-event-tone": getActivityTone(row.action),
3626
+ children: actionOf(row)
3627
+ }
3628
+ );
3629
+ return /* @__PURE__ */ jsx(
3630
+ EventTable,
3631
+ {
3632
+ rows,
3633
+ label,
3634
+ wide: showAdmin,
3635
+ busy,
3636
+ nameOf: actionOf,
3637
+ rowKind: (row) => row.action,
3638
+ badge,
3639
+ columns: () => [
3640
+ {
3641
+ id: "action",
3642
+ header: t("adminPanel.activity.column.action", "Action"),
3643
+ render: badge,
3644
+ wrap: false
3645
+ },
3646
+ {
3647
+ id: "entry",
3648
+ header: t("adminPanel.activity.column.entry", "Entry"),
3649
+ render: (row) => /* @__PURE__ */ jsx(ActivityEntry, { row })
3650
+ },
3651
+ {
3652
+ id: "type",
3653
+ header: t("adminPanel.activity.column.contentType", "Content type"),
3654
+ render: (row) => /* @__PURE__ */ jsx(CellText, { text: contentTypeText(row) })
3655
+ },
3656
+ ...showAdmin ? [
3657
+ {
3658
+ id: "admin",
3659
+ header: t("adminPanel.activity.column.admin", "Admin"),
3660
+ render: (row) => /* @__PURE__ */ jsx(AdminName, { admin: row.admin })
3661
+ }
3662
+ ] : []
3663
+ ],
3664
+ stackedSubject: (row) => /* @__PURE__ */ jsx(ActivityEntry, { row }),
3665
+ stackedDetail: (row) => [contentTypeText(row), showAdmin ? row.admin?.name : ""].filter(Boolean).join(" · "),
3666
+ details: (row) => activityDetails(t, formatDate, row)
3667
+ }
3668
+ );
3669
+ };
3670
+ const UserEventTable = ({ rows, label, showUser = true, busy = false, detailsAction }) => {
3671
+ const t = useT();
3672
+ const { formatDate } = useSessionFormatters();
3673
+ const nameOf = (row) => {
3674
+ const presentation = getEventPresentation(row);
3675
+ return t(presentation.label.messageId, presentation.label.defaultMessage);
3676
+ };
3677
+ const userCell = (row) => /* @__PURE__ */ jsx(CellText, { text: userText(t, row), strong: Boolean(row.user?.email || row.user?.username) });
3678
+ const openUser = (row) => {
3679
+ const path = row.user?.email || row.user?.username ? getUserEntryPath(row.user) : null;
3680
+ return path && showUser ? /* @__PURE__ */ jsx(LinkButton, { tag: Link$1, to: path, variant: "tertiary", "data-open-user": "", children: t("userActivity.details.openUser", "Open user") }) : null;
3681
+ };
3682
+ return /* @__PURE__ */ jsx(
3683
+ EventTable,
3684
+ {
3685
+ rows,
3686
+ label,
3687
+ wide: showUser,
3688
+ busy,
3689
+ nameOf,
3690
+ rowKind: (row) => getEventPresentation(row).key,
3691
+ badge: (row) => /* @__PURE__ */ jsx(EventBadge, { presentation: getEventPresentation(row) }),
3692
+ columns: (layout) => [
3693
+ {
3694
+ id: "event",
3695
+ header: t("adminPanel.activity.column.event", "Event"),
3696
+ render: (row) => /* @__PURE__ */ jsx(
3697
+ EventCell,
3698
+ {
3699
+ presentation: getEventPresentation(row),
3700
+ detail: userEventDetailText(t, row, layout !== "full")
3701
+ }
3702
+ )
3703
+ },
3704
+ ...showUser ? [{ id: "user", header: t("userActivity.column.user", "User"), render: userCell }] : [],
3705
+ {
3706
+ id: "details",
3707
+ header: t("adminPanel.activity.column.details", "IP address and device"),
3708
+ render: (row) => /* @__PURE__ */ jsx(SignInDetails, { row })
3709
+ },
3710
+ ...layout === "full" ? [
3711
+ {
3712
+ id: "doneBy",
3713
+ header: t("adminPanel.activity.column.doneBy", "Done by"),
3714
+ render: (row) => /* @__PURE__ */ jsx(CellText, { text: doneByText(t, row) })
3715
+ }
3716
+ ] : []
3717
+ ],
3718
+ stackedSubject: showUser ? userCell : void 0,
3719
+ stackedDetail: (row) => [userEventDetailText(t, row, true), ipText(t, row), getEventPlace(row), deviceText(t, row)].filter(Boolean).join(" · "),
3720
+ details: (row) => userEventDetails(t, formatDate, row),
3721
+ detailsAction: (row, close) => {
3722
+ const open = openUser(row);
3723
+ const extra = detailsAction ? detailsAction(row, close) : null;
3724
+ if (!open && !extra) return null;
3725
+ return /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
3726
+ open,
3727
+ extra
3728
+ ] });
3729
+ }
3730
+ }
3731
+ );
3732
+ };
3733
+ const ADMIN_FILTER_OPTIONS = Object.freeze(["all", "signed-in", "not-signed-in"]);
3734
+ const ADMIN_PAGE_SIZE_OPTIONS = Object.freeze(["10", "25", "50", "100"]);
3735
+ const ADMIN_DEFAULT_PAGE_SIZE = "25";
3736
+ const ADMIN_MAX_SEARCH_LENGTH = 100;
3737
+ function parseAdminPanelQuery(query = {}) {
3738
+ const page = Number.parseInt(String(query?.page ?? ""), 10);
3739
+ const pageSize = String(query?.pageSize ?? "");
3740
+ const filter = String(query?.filter ?? "");
3741
+ let search = "";
3742
+ if (typeof query?.search === "string") {
3743
+ try {
3744
+ search = decodeURIComponent(query.search).trim();
3745
+ } catch {
3746
+ search = query.search.trim();
3747
+ }
3748
+ }
3749
+ return {
3750
+ page: Number.isInteger(page) && page >= 1 && page <= 1e6 ? page : 1,
3751
+ pageSize: Number(
3752
+ ADMIN_PAGE_SIZE_OPTIONS.includes(pageSize) ? pageSize : ADMIN_DEFAULT_PAGE_SIZE
3753
+ ),
3754
+ filter: ADMIN_FILTER_OPTIONS.includes(filter) ? filter : "all",
3755
+ search: search.slice(0, ADMIN_MAX_SEARCH_LENGTH)
3756
+ };
3757
+ }
3758
+ function buildAdminListParams(state) {
3759
+ return {
3760
+ page: state.page,
3761
+ pageSize: state.pageSize,
3762
+ filter: state.filter,
3763
+ ...state.search ? { search: state.search } : {}
3764
+ };
3765
+ }
3766
+ function hasAdminFilters(state) {
3767
+ return state.filter !== "all" || Boolean(state.search);
3768
+ }
3769
+ function getAdminStatusPresentation(row) {
3770
+ if (row?.account === "invited") {
3771
+ return {
3772
+ key: "invited",
3773
+ tone: "secondary",
3774
+ label: { messageId: "adminPanel.status.invited", defaultMessage: "Invited" },
3775
+ detail: {
3776
+ messageId: "adminPanel.status.invited.detail",
3777
+ defaultMessage: "Invitation not accepted yet"
3778
+ }
3779
+ };
3780
+ }
3781
+ if (row?.account === "deactivated") {
3782
+ return {
3783
+ key: "deactivated",
3784
+ tone: "neutral",
3785
+ label: { messageId: "adminPanel.status.deactivated", defaultMessage: "Deactivated" },
3786
+ detail: {
3787
+ messageId: "adminPanel.status.deactivated.detail",
3788
+ defaultMessage: "Cannot sign in"
3789
+ }
3790
+ };
3791
+ }
3792
+ const count = Number(row?.sessionCount) || 0;
3793
+ if (count > 0) {
3794
+ return {
3795
+ key: "signed-in",
3796
+ tone: "success",
3797
+ label: { messageId: "adminPanel.status.signedIn", defaultMessage: "Signed in" },
3798
+ detail: {
3799
+ messageId: "adminPanel.status.signedIn.detail",
3800
+ defaultMessage: "{count, plural, one {# session} other {# sessions}}",
3801
+ values: { count }
3802
+ }
3803
+ };
3804
+ }
3805
+ return {
3806
+ key: "not-signed-in",
3807
+ tone: "neutral",
3808
+ label: { messageId: "adminPanel.status.notSignedIn", defaultMessage: "Not signed in" },
3809
+ detail: {
3810
+ messageId: "adminPanel.status.notSignedIn.detail",
3811
+ defaultMessage: "No open session"
3812
+ }
3813
+ };
3814
+ }
3815
+ function splitDuration(seconds) {
3816
+ const value = Number(seconds);
3817
+ if (!Number.isFinite(value) || value <= 0) return null;
3818
+ if (value % 86400 === 0) return { unit: "days", count: value / 86400 };
3819
+ if (value % 3600 === 0) return { unit: "hours", count: value / 3600 };
3820
+ return { unit: "minutes", count: Math.max(1, Math.round(value / 60)) };
3821
+ }
3822
+ function getSignOutErrorMessage(error) {
3823
+ const response = (
3824
+ /** @type {any} */
3825
+ error?.response
3826
+ );
3827
+ const status = Number(response?.status ?? /** @type {any} */
3828
+ error?.status);
3829
+ const reason = response?.data?.error?.details?.reason;
3830
+ if (status === 403 && reason === "super-admin-protected") {
3831
+ return {
3832
+ messageId: "adminPanel.signOut.error.protected",
3833
+ defaultMessage: "Only a Super Admin can sign out a Super Admin."
3834
+ };
3835
+ }
3836
+ if (status === 403) {
3837
+ return {
3838
+ messageId: "adminPanel.signOut.error.forbidden",
3839
+ defaultMessage: "You do not have permission to sign admins out."
3840
+ };
3841
+ }
3842
+ if (status === 404) {
3843
+ return {
3844
+ messageId: "adminPanel.signOut.error.gone",
3845
+ defaultMessage: "This session has already ended. The list is up to date now."
3846
+ };
3847
+ }
3848
+ if (status === 429) {
3849
+ return {
3850
+ messageId: "adminPanel.signOut.error.rateLimited",
3851
+ defaultMessage: "Too many sign-outs in a short time. Wait a minute and try again."
3852
+ };
3853
+ }
3854
+ return {
3855
+ messageId: "adminPanel.signOut.error.generic",
3856
+ defaultMessage: "The admin could not be signed out. Try again."
3857
+ };
3858
+ }
3859
+ function withIdentityPlaceholders(admin, placeholderName, identity) {
3860
+ if (!admin || typeof admin !== "object") return admin;
3861
+ const hidden = !admin.self && !admin.name;
3862
+ return {
3863
+ ...admin,
3864
+ name: admin.name || placeholderName(admin.id),
3865
+ identityHidden: hidden,
3866
+ rolesHidden: hidden && identity?.roles === false
3867
+ };
3868
+ }
3869
+ function withEventAdminNames(row, placeholderName) {
3870
+ if (!row || typeof row !== "object") return row;
3871
+ const fill = (admin) => admin && typeof admin === "object" && !admin.name && admin.type !== "system" && admin.id !== null && admin.id !== void 0 ? { ...admin, name: placeholderName(admin.id), identityHidden: true } : admin;
3872
+ return {
3873
+ ...row,
3874
+ ...row.admin !== void 0 ? { admin: fill(row.admin) } : {},
3875
+ ...row.actor !== void 0 ? { actor: fill(row.actor) } : {}
3876
+ };
3877
+ }
3878
+ function useEventList({ path, params, logKey }) {
3879
+ const { get } = useFetchClient();
3880
+ const { formatMessage } = useIntl();
3881
+ const fillNames = useCallback(
3882
+ (list) => list.map(
3883
+ (row) => withEventAdminNames(
3884
+ row,
3885
+ (id) => formatMessage(
3886
+ {
3887
+ id: getTranslation("adminPanel.identity.placeholder"),
3888
+ defaultMessage: "Admin #{id}"
3889
+ },
3890
+ { id }
3891
+ )
3892
+ )
3893
+ ),
3894
+ [formatMessage]
3895
+ );
3896
+ const [rows, setRows] = useState([]);
3897
+ const [meta, setMeta] = useState(null);
3898
+ const [page, setPage] = useState(1);
3899
+ const [loading, setLoading] = useState(true);
3900
+ const [loadingMore, setLoadingMore] = useState(false);
3901
+ const [error, setError] = useState(false);
3902
+ const requestRef = useRef(0);
3903
+ const key = JSON.stringify(params);
3904
+ const firstPage = Number(params?.page) > 0 ? Number(params.page) : 1;
3905
+ const load = useCallback(
3906
+ async (nextPage) => {
3907
+ const requestId = requestRef.current + 1;
3908
+ requestRef.current = requestId;
3909
+ if (nextPage === firstPage) setLoading(true);
3910
+ else setLoadingMore(true);
3911
+ try {
3912
+ const response = await get(path, { params: { ...JSON.parse(key), page: nextPage } });
3913
+ if (requestId !== requestRef.current) return;
3914
+ const body = response?.data || {};
3915
+ const data = fillNames(Array.isArray(body.data) ? body.data : []);
3916
+ setRows((current) => nextPage === firstPage ? data : [...current, ...data]);
3917
+ setMeta(body.meta || null);
3918
+ setPage(nextPage);
3919
+ setError(false);
3920
+ } catch (err) {
3921
+ if (requestId !== requestRef.current || isCancelledRequest(err)) return;
3922
+ setError(true);
3923
+ logSafeAdminError(logKey, err);
3924
+ } finally {
3925
+ if (requestId === requestRef.current) {
3926
+ setLoading(false);
3927
+ setLoadingMore(false);
3928
+ }
3929
+ }
3930
+ },
3931
+ [get, path, key, logKey, fillNames, firstPage]
3932
+ );
3933
+ useEffect(() => {
3934
+ load(firstPage);
3935
+ return () => {
3936
+ requestRef.current += 1;
3937
+ };
3938
+ }, [load, firstPage]);
3939
+ const pagination = meta?.pagination;
3940
+ const hasMore = Boolean(pagination && page < pagination.pageCount);
3941
+ const exportAll = useCallback(async () => {
3942
+ const all = [];
3943
+ let cursor = null;
3944
+ do {
3945
+ const response = await get(`${path}/export`, {
3946
+ params: toExportParams(JSON.parse(key), cursor)
3947
+ });
3948
+ const body = response?.data || {};
3949
+ if (!Array.isArray(body.data)) throw new Error("Invalid export response");
3950
+ all.push(...fillNames(body.data));
3951
+ cursor = typeof body.meta?.nextCursor === "string" ? body.meta.nextCursor : null;
3952
+ } while (cursor && all.length < MAX_EVENT_EXPORT_ROWS);
3953
+ return {
3954
+ rows: all.slice(0, MAX_EVENT_EXPORT_ROWS),
3955
+ capped: all.length > MAX_EVENT_EXPORT_ROWS || Boolean(cursor)
3956
+ };
3957
+ }, [get, path, key, fillNames]);
3958
+ return {
3959
+ rows,
3960
+ meta,
3961
+ loading,
3962
+ loadingMore,
3963
+ error,
3964
+ hasMore,
3965
+ loadMore: () => load(page + 1),
3966
+ reload: () => load(firstPage),
3967
+ exportAll
3968
+ };
3969
+ }
3970
+ function downloadCsv(content, name2) {
3971
+ const blob = new Blob([content], { type: "text/csv;charset=utf-8;" });
3972
+ const url = URL.createObjectURL(blob);
3973
+ const link = document.createElement("a");
3974
+ link.href = url;
3975
+ link.download = `${name2}-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.csv`;
3976
+ link.click();
3977
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
3978
+ }
3979
+ const UserActivityList = ({ documentId, userLabel }) => {
3980
+ const { formatMessage } = useIntl();
3981
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
3982
+ const params = useMemo(
3983
+ () => buildUserActivityParams({ userId: documentId, pageSize: PANEL_USER_EVENT_LIMIT }),
3984
+ [documentId]
3985
+ );
3986
+ const list = useEventList({ path: USER_ACTIVITY_API_PATH, params, logKey: "userActivity.panel" });
3987
+ const title = t("userActivity.panel.title", "Security activity");
3988
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-user-activity": "", children: [
3989
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: title }),
3990
+ list.loading && list.rows.length === 0 ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 2, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("adminPanel.activity.loading", "Loading events") }) }) : null,
3991
+ !list.loading && list.error ? /* @__PURE__ */ jsx(
3992
+ PersistentAlert,
3993
+ {
3994
+ variant: "danger",
3995
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: list.reload, children: t("common.tryAgain", "Try again") }),
3996
+ children: t("adminPanel.activity.error", "The events could not be loaded.")
3997
+ }
3998
+ ) : null,
3999
+ !list.loading && !list.error && list.rows.length === 0 ? /* @__PURE__ */ jsx(Box, { padding: 3, background: "neutral0", borderColor: "neutral200", hasRadius: true, children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t("userActivity.panel.empty", "No security events recorded for {user}.", {
4000
+ user: userLabel
4001
+ }) }) }) : null,
4002
+ list.rows.length > 0 ? /* @__PURE__ */ jsx(
4003
+ UserEventTable,
4004
+ {
4005
+ rows: list.rows,
4006
+ showUser: false,
4007
+ busy: list.loading,
4008
+ label: t("userActivity.panel.listLabel", "Security activity of {user}", {
4009
+ user: userLabel
4010
+ })
4011
+ }
4012
+ ) : null,
4013
+ /* @__PURE__ */ jsx(TargetLink, { tag: NavLink, to: userActivityPagePath(documentId), "data-user-activity-link": "", children: t("userActivity.panel.showAll", "Show all security activity") })
4014
+ ] });
4015
+ };
4016
+ const UserActivityPanelSection = ({ documentId, userLabel }) => {
4017
+ const {
4018
+ allowedActions: { canRead },
4019
+ isLoading
4020
+ } = useRBAC(pluginPermissions.userActivityRead);
4021
+ if (isLoading || !canRead || !documentId) return null;
4022
+ return /* @__PURE__ */ jsx(UserActivityList, { documentId, userLabel });
4023
+ };
4024
+ function requireSessionList(payload) {
4025
+ if (!Array.isArray(payload?.data)) throw new Error("Invalid session response");
4026
+ return payload.data;
4027
+ }
4028
+ function requireSuccessfulMutation(payload) {
4029
+ if (payload?.success !== true) throw new Error("Invalid mutation response");
4030
+ return payload;
4031
+ }
4032
+ const DEFAULT_SESSION_FILTER = "all";
4033
+ const SESSION_FILTER_OPTIONS = Object.freeze(["all", "open", "active", "idle", "ended"]);
4034
+ const DEFAULT_END_REASON_FILTER = "all";
4035
+ const END_REASON_FILTER_OPTIONS = Object.freeze(["all", ...SESSION_END_REASONS]);
4036
+ const VALID_SESSION_FILTERS = new Set(SESSION_FILTER_OPTIONS);
4037
+ const VALID_END_REASON_FILTERS = new Set(END_REASON_FILTER_OPTIONS);
4038
+ function isSessionFilter(value) {
4039
+ return typeof value === "string" && VALID_SESSION_FILTERS.has(value);
4040
+ }
4041
+ function isEndReasonFilter(value) {
4042
+ return typeof value === "string" && VALID_END_REASON_FILTERS.has(value);
4043
+ }
4044
+ function getManageableSessions(sessions) {
4045
+ if (!Array.isArray(sessions)) return [];
4046
+ return sessions.filter((session) => session?.isActive === true);
4047
+ }
4048
+ const USER_MODEL_UID = "plugin::users-permissions.user";
4049
+ const PANEL_SESSION_LIMIT = 5;
4050
+ const DASHBOARD_PATH = "/plugins/magic-sessionmanager";
4051
+ function isUserModel(model) {
4052
+ return model === USER_MODEL_UID;
4053
+ }
4054
+ const getActivity = (session) => toValidDate(session?.lastActive) || toValidDate(session?.loginTime);
4055
+ function getUserSessionSummary(sessions) {
4056
+ const rows = Array.isArray(sessions) ? sessions.filter((row) => row && typeof row === "object") : [];
4057
+ const open = rows.filter((session) => session.isActive === true);
4058
+ const activeCount = open.filter((session) => session.isTrulyActive === true).length;
4059
+ let lastActive = null;
4060
+ for (const session of rows) {
4061
+ const activity = getActivity(session);
4062
+ if (activity && (!lastActive || activity.getTime() > lastActive.getTime()))
4063
+ lastActive = activity;
4064
+ }
4065
+ return { isOnline: activeCount > 0, openCount: open.length, activeCount, lastActive };
4066
+ }
4067
+ function getVisiblePanelSessions(sessions, limit = PANEL_SESSION_LIMIT) {
4068
+ const rows = Array.isArray(sessions) ? [...sessions] : [];
4069
+ rows.sort(
4070
+ (a, b) => (getActivity(b)?.getTime() ?? -Infinity) - (getActivity(a)?.getTime() ?? -Infinity)
4071
+ );
4072
+ return { visible: rows.slice(0, limit), hiddenCount: Math.max(0, rows.length - limit) };
4073
+ }
4074
+ function endOpenSessions(sessions, reason) {
4075
+ if (!Array.isArray(sessions)) return [];
4076
+ return sessions.map(
4077
+ (session) => session?.isActive === true ? { ...session, isActive: false, isTrulyActive: false, terminationReason: reason } : session
4078
+ );
4079
+ }
4080
+ function getPanelUserLabel(user) {
4081
+ return presentText(user?.username) || presentText(user?.email);
4082
+ }
4083
+ function isNotFoundError(error) {
4084
+ if (!error || typeof error !== "object") return false;
4085
+ return error.status === 404 || error.response?.status === 404;
4086
+ }
4087
+ function buildUserSessionsHref(user) {
4088
+ const query = presentText(user?.email) || presentText(user?.username);
4089
+ if (!query) return DASHBOARD_PATH;
4090
+ return `${DASHBOARD_PATH}?${new URLSearchParams({ search: query }).toString()}`;
4091
+ }
4092
+ function planBlockedFormSync({ initialValues, modified, blocked }) {
4093
+ const hasBlockedField = Boolean(initialValues) && typeof initialValues === "object" && Object.prototype.hasOwnProperty.call(initialValues, "blocked");
4094
+ if (!hasBlockedField || typeof blocked !== "boolean") return { mode: "notice" };
4095
+ if (!modified) return { mode: "reset", initialValues: { ...initialValues, blocked } };
4096
+ return { mode: "change", field: "blocked", value: blocked };
4097
+ }
4098
+ function applyBlockedFormSync(plan, form) {
4099
+ try {
4100
+ if (plan.mode === "reset" && typeof form?.resetForm === "function") {
4101
+ form.resetForm(plan.initialValues);
4102
+ return true;
4103
+ }
4104
+ if (plan.mode === "change" && typeof form?.onChange === "function") {
4105
+ form.onChange(plan.field, plan.value);
4106
+ return true;
4107
+ }
4108
+ } catch {
4109
+ return false;
4110
+ }
4111
+ return false;
4112
+ }
4113
+ const FORM_CONSUMER = "MagicSessionManagerPanel";
4114
+ const PanelSessionCard = ({ session, t }) => {
4115
+ const { formatDate, formatRelativeTime, translate } = useSessionFormatters();
4116
+ const device = getDevicePresentation(session);
4117
+ const hasSummary = Boolean(device.browserLabel || device.os);
4118
+ const summary = hasSummary ? device.summary.text ?? translate(device.summary, device.summary.values) : "";
4119
+ const lastActivity = toValidDate(session.lastActive) || toValidDate(session.loginTime);
4120
+ const ipAddress = presentText(session.ipAddress);
4121
+ return /* @__PURE__ */ jsx(
4122
+ Box,
4123
+ {
4124
+ tag: "li",
4125
+ padding: 3,
4126
+ background: "neutral0",
4127
+ borderColor: "neutral200",
4128
+ hasRadius: true,
4129
+ minWidth: 0,
4130
+ "data-panel-session": "",
4131
+ children: /* @__PURE__ */ jsxs(Flex, { gap: 3, alignItems: "flex-start", minWidth: 0, children: [
4132
+ /* @__PURE__ */ jsx(
4133
+ Flex,
4134
+ {
4135
+ background: "neutral100",
4136
+ color: "neutral700",
4137
+ hasRadius: true,
4138
+ padding: 2,
4139
+ shrink: 0,
4140
+ justifyContent: "center",
4141
+ alignItems: "center",
4142
+ "aria-hidden": true,
4143
+ children: /* @__PURE__ */ jsx(DeviceIcon, { icon: device.icon })
4144
+ }
4145
+ ),
4146
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, flex: "1 1 auto", children: [
4147
+ /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "center", gap: 2, wrap: "wrap", children: [
4148
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: translate(device.deviceTypeMessage) }),
4149
+ /* @__PURE__ */ jsx(StatusBadge, { session, size: "S" })
4150
+ ] }),
4151
+ summary ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: summary }) : null,
4152
+ ipAddress ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.sessions.ip", "IP {ip}", { ip: ipAddress }) }) : null,
4153
+ lastActivity ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", title: formatDate(lastActivity), children: t("panel.sessions.lastActive", "Last active {time}", {
4154
+ time: formatRelativeTime(lastActivity)
4155
+ }) }) : null
4156
+ ] })
4157
+ ] })
4158
+ }
4159
+ );
4160
+ };
4161
+ const SessionInfoPanel = ({ documentId, model, document: document2 }) => {
4162
+ const { formatMessage } = useIntl();
4163
+ const { formatDate, formatRelativeTime } = useSessionFormatters();
4164
+ const {
4165
+ allowedActions: { canAccess },
4166
+ isLoading: permissionsLoading
4167
+ } = useRBAC(pluginPermissions.access);
4168
+ const [sessions, setSessions] = useState([]);
4169
+ const [loading, setLoading] = useState(true);
4170
+ const [loadError, setLoadError] = useState(false);
4171
+ const [reloadKey, setReloadKey] = useState(0);
4172
+ const [isBlocked, setIsBlocked] = useState(Boolean(document2?.blocked));
4173
+ const [pendingAction, setPendingAction] = useState(null);
4174
+ const [formOutOfSync, setFormOutOfSync] = useState(false);
4175
+ const panelRef = useRef(null);
4176
+ const blockToggleRef = useRef(null);
4177
+ const focusBlockToggle = useRef(false);
4178
+ const noOpenSessionsHintId = useId();
4179
+ const { get, post: postRequest } = useFetchClient();
4180
+ const { toggleNotification } = useNotification();
4181
+ const formInitialValues = useForm(FORM_CONSUMER, (state) => state.initialValues, false);
4182
+ const formModified = useForm(FORM_CONSUMER, (state) => state.modified, false);
4183
+ const formOnChange = useForm(FORM_CONSUMER, (state) => state.onChange, false);
4184
+ const formResetForm = useForm(FORM_CONSUMER, (state) => state.resetForm, false);
4185
+ const t = (id, defaultMessage, values) => formatMessage({ id: getTranslation(id), defaultMessage }, values);
4186
+ const userId = document2?.documentId || documentId;
4187
+ const isUserPanel = isUserModel(model);
4188
+ const persistedBlocked = Boolean(document2?.blocked);
4189
+ const userLabel = getPanelUserLabel(document2) || String(userId ?? "");
4190
+ useEffect(() => {
4191
+ setIsBlocked(persistedBlocked);
4192
+ setFormOutOfSync(false);
4193
+ }, [persistedBlocked, userId]);
4194
+ useEffect(() => {
4195
+ if (!focusBlockToggle.current || pendingAction !== null) return void 0;
4196
+ const expected = isBlocked ? "unblock" : "block";
4197
+ let attempts = 0;
4198
+ let timer;
4199
+ const tryFocus = () => {
4200
+ const button = blockToggleRef.current;
4201
+ if (button?.isConnected && !button.disabled && button.dataset.blockToggle === expected) {
4202
+ focusBlockToggle.current = false;
4203
+ button.focus();
4204
+ return;
4205
+ }
4206
+ attempts += 1;
4207
+ if (attempts < 20) timer = window.setTimeout(tryFocus, 25);
4208
+ else focusBlockToggle.current = false;
4209
+ };
4210
+ timer = window.setTimeout(tryFocus, 0);
4211
+ return () => window.clearTimeout(timer);
4212
+ }, [isBlocked, pendingAction]);
4213
+ useEffect(() => {
4214
+ if (model !== "plugin::users-permissions.user" || !userId || permissionsLoading || !canAccess) {
4215
+ setLoading(false);
4216
+ return void 0;
4217
+ }
4218
+ let cancelled = false;
4219
+ const fetchData = async () => {
4220
+ setLoading(true);
4221
+ setLoadError(false);
4222
+ try {
4223
+ const { data } = await get(`/magic-sessionmanager/user/${userId}/sessions`);
4224
+ if (cancelled) return;
4225
+ setSessions(requireSessionList(data));
4226
+ } catch (err) {
4227
+ if (!cancelled) setLoadError(true);
4228
+ logSafeAdminError("userSessions.load", err);
4229
+ } finally {
4230
+ if (!cancelled) setLoading(false);
4231
+ }
4232
+ };
4233
+ fetchData();
4234
+ return () => {
4235
+ cancelled = true;
4236
+ };
4237
+ }, [userId, model, get, reloadKey, canAccess, permissionsLoading]);
4238
+ const handleEndAll = async () => {
4239
+ if (!userId) return;
4240
+ setPendingAction("endAll");
4241
+ try {
4242
+ const response = await postRequest(`/magic-sessionmanager/user/${userId}/terminate-all`);
4243
+ requireSuccessfulMutation(response.data);
4244
+ setSessions((rows) => endOpenSessions(rows, "manual"));
4245
+ toggleNotification({
4246
+ type: "success",
4247
+ message: t("panel.notify.endAllSuccess", "All sessions of {user} ended.", {
4248
+ user: userLabel
4249
+ })
4250
+ });
4251
+ } catch (error) {
4252
+ toggleNotification({
4253
+ type: "danger",
4254
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.endAllError", "The sessions could not be ended. Please try again.")
4255
+ });
4256
+ logSafeAdminError("userSessions.endAll", error);
4257
+ throw error;
4258
+ } finally {
4259
+ setPendingAction(null);
4260
+ }
4261
+ };
4262
+ const changeBlocked = async (blocked) => {
4263
+ const response = await postRequest(`/magic-sessionmanager/user/${userId}/toggle-block`, {
4264
+ blocked
4265
+ });
4266
+ requireSuccessfulMutation(response.data);
4267
+ const newBlockedStatus = response.data.blocked === true;
4268
+ focusBlockToggle.current = newBlockedStatus !== isBlocked;
4269
+ setIsBlocked(newBlockedStatus);
4270
+ if (newBlockedStatus) setSessions((rows) => endOpenSessions(rows, "blocked"));
4271
+ const plan = planBlockedFormSync({
4272
+ initialValues: formInitialValues,
4273
+ modified: formModified,
4274
+ blocked: newBlockedStatus
4275
+ });
4276
+ const synced = applyBlockedFormSync(plan, { resetForm: formResetForm, onChange: formOnChange });
4277
+ setFormOutOfSync(!synced);
4278
+ return newBlockedStatus;
4279
+ };
4280
+ const handleBlock = async () => {
4281
+ if (!userId) return;
4282
+ setPendingAction("block");
4283
+ try {
4284
+ await changeBlocked(true);
4285
+ toggleNotification({
4286
+ type: "success",
4287
+ message: t("panel.notify.blockSuccess", "{user} is blocked.", { user: userLabel })
4288
+ });
4289
+ } catch (error) {
4290
+ toggleNotification({
4291
+ type: "danger",
4292
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.blockError", "The user could not be blocked. Please try again.")
4293
+ });
4294
+ logSafeAdminError("userSessions.block", error);
4295
+ throw error;
4296
+ } finally {
4297
+ setPendingAction(null);
4298
+ }
4299
+ };
4300
+ const handleUnblock = async () => {
4301
+ if (!userId) return;
4302
+ setPendingAction("unblock");
4303
+ try {
4304
+ await changeBlocked(false);
4305
+ toggleNotification({
4306
+ type: "success",
4307
+ message: t("panel.notify.unblockSuccess", "{user} can sign in again.", { user: userLabel })
4308
+ });
4309
+ } catch (error) {
4310
+ toggleNotification({
4311
+ type: "danger",
4312
+ message: isNotFoundError(error) ? t("panel.notify.userNotFound", "User not found.") : t("panel.notify.unblockError", "The block could not be removed. Please try again.")
4313
+ });
4314
+ logSafeAdminError("userSessions.unblock", error);
4315
+ } finally {
4316
+ setPendingAction(null);
4317
+ }
4318
+ };
4319
+ if (!isUserPanel) {
4320
+ return null;
4321
+ }
4322
+ if (permissionsLoading || !canAccess) {
4323
+ return null;
4324
+ }
4325
+ const title = t("panel.title", "Sessions");
4326
+ if (!userId) {
4327
+ return {
4328
+ title,
4329
+ content: /* @__PURE__ */ jsx(Box, { width: "100%", minWidth: 0, children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral700", tag: "p", children: t("panel.unsaved.description", "Save this user before you can manage sessions.") }) })
4330
+ };
4331
+ }
4332
+ if (loadError) {
4333
+ return {
4334
+ title,
4335
+ content: /* @__PURE__ */ jsx(Box, { width: "100%", minWidth: 0, children: /* @__PURE__ */ jsx(
4336
+ PersistentAlert,
4337
+ {
4338
+ variant: "danger",
4339
+ closeLabel: t("common.close", "Close"),
4340
+ action: /* @__PURE__ */ jsx(Button, { size: "S", variant: "secondary", onClick: () => setReloadKey((key) => key + 1), children: t("common.tryAgain", "Try again") }),
4341
+ children: t("panel.error.message", "Sessions could not be loaded.")
4342
+ }
4343
+ ) })
4344
+ };
4345
+ }
4346
+ const openSessions = getManageableSessions(sessions);
4347
+ const summary = getUserSessionSummary(sessions);
4348
+ const { visible, hiddenCount } = getVisiblePanelSessions(openSessions);
4349
+ const actionsDisabled = loading || pendingAction !== null;
4350
+ const hasOpenSessions = summary.openCount > 0;
4351
+ const endAllLabel = t("panel.actions.endAll", "End all sessions");
4352
+ const blockLabel = t("panel.actions.blockUser", "Block user");
4353
+ const unblockLabel = t("panel.actions.unblock", "Unblock user");
4354
+ return {
4355
+ title,
4356
+ content: /* @__PURE__ */ jsxs(
4357
+ Flex,
4358
+ {
4359
+ ref: panelRef,
4360
+ direction: "column",
4361
+ alignItems: "stretch",
4362
+ gap: 4,
4363
+ width: "100%",
4364
+ minWidth: 0,
4365
+ tabIndex: -1,
4366
+ children: [
4367
+ loading ? /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 2, "data-panel-summary": "", children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("panel.loading", "Loading sessions") }) }) : /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, "data-panel-summary": "", children: [
4368
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", wrap: "wrap", children: [
4369
+ /* @__PURE__ */ jsx(Badge, { variant: summary.isOnline ? "success" : "neutral", size: "M", children: summary.isOnline ? t("panel.status.online", "Online") : t("panel.status.notOnline", "Not online") }),
4370
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: t(
4371
+ "panel.summary.openCount",
4372
+ "{count, plural, one {# open session} other {# open sessions}}",
4373
+ { count: summary.openCount }
4374
+ ) })
4375
+ ] }),
4376
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.summary.openHint", "Active or idle") }),
4377
+ summary.lastActive ? /* @__PURE__ */ jsx(
4378
+ Typography,
4379
+ {
4380
+ variant: "pi",
4381
+ textColor: "neutral600",
4382
+ title: formatDate(summary.lastActive),
4383
+ children: t("panel.sessions.lastActive", "Last active {time}", {
4384
+ time: formatRelativeTime(summary.lastActive)
4385
+ })
4386
+ }
4387
+ ) : /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.summary.noSessions", "No sessions recorded") })
4388
+ ] }),
4389
+ isBlocked ? /* @__PURE__ */ jsx(PersistentAlert, { variant: "danger", closeLabel: t("common.close", "Close"), children: t("panel.blocked.message", "This account is blocked. The user cannot sign in.") }) : null,
4390
+ formOutOfSync ? /* @__PURE__ */ jsx(PersistentAlert, { variant: "warning", closeLabel: t("common.close", "Close"), children: t(
4391
+ "panel.form.reloadNotice",
4392
+ "Reload this page before saving, or the Blocked field will be overwritten."
4393
+ ) }) : null,
4394
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-actions": "", children: [
4395
+ /* @__PURE__ */ jsxs(ActionStack, { children: [
4396
+ /* @__PURE__ */ jsx(
4397
+ ConfirmAction,
4398
+ {
4399
+ title: t("panel.confirm.endAllTitle", "End all sessions of {user}?", {
4400
+ user: userLabel
4401
+ }),
4402
+ body: t(
4403
+ "panel.confirm.endAllBody",
4404
+ "{count, plural, one {# open session ends} other {# open sessions end}} on all devices. {user} can sign in again unless you also block the account.",
4405
+ { count: summary.openCount, user: userLabel }
4406
+ ),
4407
+ confirmLabel: endAllLabel,
4408
+ onConfirm: handleEndAll,
4409
+ fallbackFocusRef: panelRef,
4410
+ disabled: actionsDisabled || !hasOpenSessions,
4411
+ trigger: /* @__PURE__ */ jsx(
4412
+ Button,
4413
+ {
4414
+ fullWidth: true,
4415
+ size: "S",
4416
+ variant: "danger-light",
4417
+ startIcon: /* @__PURE__ */ jsx(SignOut, { "aria-hidden": true, focusable: false }),
4418
+ loading: pendingAction === "endAll",
4419
+ disabled: actionsDisabled || !hasOpenSessions,
4420
+ "aria-describedby": !loading && !hasOpenSessions ? noOpenSessionsHintId : void 0,
4421
+ type: "button",
4422
+ children: endAllLabel
4423
+ }
4424
+ )
4425
+ }
4426
+ ),
4427
+ isBlocked ? /* @__PURE__ */ jsx(
4428
+ Button,
4429
+ {
4430
+ ref: blockToggleRef,
4431
+ "data-block-toggle": "unblock",
4432
+ fullWidth: true,
4433
+ size: "S",
4434
+ variant: "secondary",
4435
+ startIcon: /* @__PURE__ */ jsx(CheckCircle, { "aria-hidden": true, focusable: false }),
4436
+ loading: pendingAction === "unblock",
4437
+ disabled: actionsDisabled,
4438
+ onClick: handleUnblock,
4439
+ type: "button",
4440
+ children: unblockLabel
4441
+ }
4442
+ ) : /* @__PURE__ */ jsx(
4443
+ ConfirmAction,
4444
+ {
4445
+ title: t("panel.confirm.blockTitle", "Block {user}?", { user: userLabel }),
4446
+ body: t(
4447
+ "panel.confirm.blockBody",
4448
+ "{user} can no longer sign in, and {count, plural, =0 {no open sessions are affected} one {# open session ends now} other {# open sessions end now}}. You can unblock the account later; ended sessions stay ended.",
4449
+ { count: summary.openCount, user: userLabel }
4450
+ ),
4451
+ confirmLabel: blockLabel,
4452
+ onConfirm: handleBlock,
4453
+ fallbackFocusRef: panelRef,
4454
+ disabled: actionsDisabled,
4455
+ trigger: /* @__PURE__ */ jsx(
4456
+ Button,
4457
+ {
4458
+ ref: blockToggleRef,
4459
+ "data-block-toggle": "block",
4460
+ fullWidth: true,
4461
+ size: "S",
4462
+ variant: "danger-light",
4463
+ startIcon: /* @__PURE__ */ jsx(Lock, { "aria-hidden": true, focusable: false }),
4464
+ loading: pendingAction === "block",
4465
+ disabled: actionsDisabled,
4466
+ type: "button",
4467
+ children: blockLabel
4468
+ }
4469
+ )
4470
+ }
4471
+ )
4472
+ ] }),
4473
+ !loading && !hasOpenSessions ? /* @__PURE__ */ jsx(Typography, { id: noOpenSessionsHintId, variant: "pi", textColor: "neutral600", children: t("panel.actions.noOpenSessions", "No open sessions") }) : null,
4474
+ /* @__PURE__ */ jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t(
4475
+ "panel.actions.hint",
4476
+ "End all sessions lets the user sign in again. Block user also prevents new sign-ins."
4477
+ ) })
4478
+ ] }),
4479
+ userId ? /* @__PURE__ */ jsx(ImpersonationPanelSection, { documentId: String(userId), userLabel }) : null,
4480
+ loading ? null : /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-panel-sessions": "", children: [
4481
+ /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", tag: "h3", children: t("panel.sessions.openTitle", "Open sessions") }),
4482
+ visible.length > 0 ? /* @__PURE__ */ jsx(
4483
+ Flex,
4484
+ {
4485
+ tag: "ul",
4486
+ direction: "column",
4487
+ alignItems: "stretch",
4488
+ gap: 2,
4489
+ margin: 0,
4490
+ padding: 0,
4491
+ style: { listStyle: "none" },
4492
+ children: visible.map((session) => /* @__PURE__ */ jsx(PanelSessionCard, { session, t }, session.id))
4493
+ }
4494
+ ) : /* @__PURE__ */ jsx(Box, { padding: 3, background: "neutral0", borderColor: "neutral200", hasRadius: true, children: /* @__PURE__ */ jsx(ReadableText, { variant: "omega", textColor: "neutral800", tag: "p", children: t(
4495
+ "panel.empty.noOpenSessions",
4496
+ "No open sessions. {user} is not signed in on any device.",
4497
+ { user: userLabel }
4498
+ ) }) }),
4499
+ hiddenCount > 0 ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("panel.sessions.more", "{count, plural, other {+# more}}", {
4500
+ count: hiddenCount
4501
+ }) }) : null
4502
+ ] }),
4503
+ /* @__PURE__ */ jsx(TargetLink, { tag: NavLink, to: buildUserSessionsHref(document2), children: t("panel.sessions.showAllLink", "Show all sessions") }),
4504
+ userId ? /* @__PURE__ */ jsx(UserActivityPanelSection, { documentId: String(userId), userLabel }) : null
4505
+ ]
4506
+ }
4507
+ )
4508
+ };
4509
+ };
4510
+ const prefixPluginTranslations = (data, pluginId2) => {
4511
+ const prefixed = {};
4512
+ Object.keys(data).forEach((key) => {
4513
+ prefixed[`${pluginId2}.${key}`] = data[key];
4514
+ });
4515
+ return prefixed;
4516
+ };
4517
+ const name = pluginPkg.strapi.name;
4518
+ const index = {
4519
+ register(app) {
4520
+ const pluginPermissions$1 = pluginPermissions.access;
4521
+ app.addMenuLink({
4522
+ to: `plugins/${pluginId$1}`,
4523
+ icon: PluginIcon,
4524
+ intlLabel: {
4525
+ id: `${pluginId$1}.plugin.name`,
4526
+ defaultMessage: pluginPkg.strapi.displayName
4527
+ },
4528
+ Component: () => import("./App-C4bihk2K.mjs"),
4529
+ permissions: pluginPermissions$1
4530
+ });
4531
+ app.addSettingsLink(
4532
+ {
4533
+ id: pluginId$1,
4534
+ intlLabel: { id: `${pluginId$1}.settings.section`, defaultMessage: "Session Manager" }
4535
+ },
4536
+ [
4537
+ {
4538
+ intlLabel: {
4539
+ id: `${pluginId$1}.settings.link.configuration`,
4540
+ defaultMessage: "Configuration"
4541
+ },
4542
+ id: "general",
4543
+ to: `${pluginId$1}/general`,
4544
+ Component: () => import("./Settings-avD0DbXP.mjs"),
4545
+ permissions: pluginPermissions$1
4546
+ },
4547
+ {
4548
+ intlLabel: {
4549
+ id: `${pluginId$1}.settings.link.analytics`,
4550
+ defaultMessage: "Analytics"
4551
+ },
4552
+ id: "analytics",
4553
+ to: `${pluginId$1}/analytics`,
4554
+ Component: () => import("./Analytics-WbCUmkQQ.mjs"),
4555
+ permissions: pluginPermissions$1
4556
+ }
4557
+ ]
4558
+ );
4559
+ app.registerPlugin({
4560
+ id: pluginId$1,
4561
+ initializer: Initializer,
4562
+ isReady: true,
4563
+ name
4564
+ });
4565
+ if ("widgets" in app && app.widgets && typeof app.widgets.register === "function") {
4566
+ app.widgets.register({
4567
+ icon: PluginIcon,
4568
+ title: {
4569
+ id: `${pluginId$1}.widget.online-users.title`,
4570
+ defaultMessage: "Online users"
4571
+ },
4572
+ link: {
4573
+ label: {
4574
+ id: `${pluginId$1}.widget.link`,
4575
+ defaultMessage: "Open Session Manager"
4576
+ },
4577
+ href: `/plugins/${pluginId$1}`
4578
+ },
4579
+ component: async () => {
4580
+ const component = await import("./OnlineUsersWidget-q0Z6nbbO.mjs");
4581
+ return component.default;
4582
+ },
4583
+ id: "online-users-widget",
4584
+ pluginId: pluginId$1,
4585
+ permissions: pluginPermissions$1
4586
+ });
4587
+ }
4588
+ },
4589
+ bootstrap(app) {
4590
+ try {
4591
+ const contentManagerPlugin = app.getPlugin("content-manager");
4592
+ if (contentManagerPlugin?.apis?.addEditViewSidePanel) {
4593
+ contentManagerPlugin.apis.addEditViewSidePanel([SessionInfoPanel]);
4594
+ }
4595
+ } catch (error) {
4596
+ logSafeAdminError("plugin.bootstrap", error);
4597
+ }
4598
+ },
4599
+ async registerTrads({ locales }) {
4600
+ const importedTrads = {
4601
+ en: () => import("./en-DzuXWL1W.mjs"),
4602
+ de: () => import("./de-BQlEdBMr.mjs"),
4603
+ es: () => import("./es-BfyED9YI.mjs"),
4604
+ fr: () => import("./fr-CzFNGWq0.mjs"),
4605
+ pt: () => import("./pt-DmyQnGI_.mjs")
4606
+ };
4607
+ const translatedLanguages = Object.keys(importedTrads).filter((lang) => locales.includes(lang));
4608
+ const translations = await Promise.all(
4609
+ translatedLanguages.map(
4610
+ (language) => importedTrads[language]().then(({ default: data }) => ({
4611
+ data: prefixPluginTranslations(data, pluginId$1),
4612
+ locale: language
4613
+ })).catch(() => ({
4614
+ data: {},
4615
+ locale: language
4616
+ }))
4617
+ )
4618
+ );
4619
+ return Promise.resolve(translations);
4620
+ }
4621
+ };
4622
+ export {
4623
+ getAdminStatusPresentation as $,
4624
+ ActivityEventTable as A,
4625
+ downloadCsv as B,
4626
+ ConfirmAction as C,
4627
+ DeviceIcon as D,
4628
+ MAX_EVENT_EXPORT_ROWS as E,
4629
+ isCancelledRequest as F,
4630
+ RECENT_EVENT_LIMIT as G,
4631
+ buildUserActivityParams as H,
4632
+ RECENT_USER_EVENT_LIMIT as I,
4633
+ USER_ACTIVITY_PAGE_PATH as J,
4634
+ UserEventTable as K,
4635
+ useElementWidth as L,
4636
+ MissingValue as M,
4637
+ SESSION_FILTER_OPTIONS as N,
4638
+ END_REASON_FILTER_OPTIONS as O,
4639
+ PropertyList as P,
4640
+ PageShell as Q,
4641
+ ReadableText as R,
4642
+ StatusBadge as S,
4643
+ StatGrid as T,
4644
+ USER_ACTIVITY_API_PATH as U,
4645
+ ValueOrMissing as V,
4646
+ StatCard as W,
4647
+ buildSessionCsv as X,
4648
+ buildSessionJson as Y,
4649
+ restoreDialogFocus as Z,
4650
+ requireSessionList as _,
4651
+ getEndReasonPresentation as a,
4652
+ getBadgeColors as a0,
4653
+ useSettingsTranslate as a1,
4654
+ useSecondsLeft as a2,
4655
+ validateReason as a3,
4656
+ REASON_MAX as a4,
4657
+ formatClock as a5,
4658
+ parseAdminPanelQuery as a6,
4659
+ buildAdminListParams as a7,
4660
+ withIdentityPlaceholders as a8,
4661
+ ADMIN_FILTER_OPTIONS as a9,
4662
+ getErrorTab as aA,
4663
+ copyText as aB,
4664
+ buildSavePayload as aC,
4665
+ SETTINGS_FIELD_LABELS as aD,
4666
+ requireSuccessfulMutation as aE,
4667
+ getVisibleSettingsTabs as aF,
4668
+ resolveSettingsTab as aG,
4669
+ getRevealScrollDelta as aH,
4670
+ SETTINGS_TAB_LABELS as aI,
4671
+ isSessionFilter as aJ,
4672
+ DEFAULT_SESSION_FILTER as aK,
4673
+ isEndReasonFilter as aL,
4674
+ DEFAULT_END_REASON_FILTER as aM,
4675
+ normalizeDeviceType as aN,
4676
+ getDeviceTypeMessage as aO,
4677
+ index as aP,
4678
+ ADMIN_PAGE_SIZE_OPTIONS as aa,
4679
+ ADMIN_DEFAULT_PAGE_SIZE as ab,
4680
+ hasAdminFilters as ac,
4681
+ getSignOutErrorMessage as ad,
4682
+ splitDuration as ae,
4683
+ parseActivityPageQuery as af,
4684
+ EVENT_PAGE_SIZE as ag,
4685
+ ACTIVITY_PAGE_SIZE_OPTIONS as ah,
4686
+ ALL_ADMINS_FILTER_OPTIONS as ai,
4687
+ hasActivityPageFilters as aj,
4688
+ parseUserActivityQuery as ak,
4689
+ userText as al,
4690
+ buildUserActivityCsv as am,
4691
+ USER_ACTIVITY_SETTINGS_PATH as an,
4692
+ USER_ACTIVITY_FILTER_OPTIONS as ao,
4693
+ USER_ACTIVITY_FILTER_LABELS as ap,
4694
+ hasUserActivityFilters as aq,
4695
+ ReadableParagraphs as ar,
4696
+ buildTabSearch as as,
4697
+ buildSelectOptions as at,
4698
+ EqualGrid as au,
4699
+ SELECT_PRESETS as av,
4700
+ fieldHasError as aw,
4701
+ usesLocalDatabase as ax,
4702
+ formatSessionDate as ay,
4703
+ refocusIfLost as az,
4704
+ getTranslation as b,
4705
+ getSessionStatus as c,
4706
+ getDevicePresentation as d,
4707
+ getSessionEndReasonPresentation as e,
4708
+ pluginId$1 as f,
4709
+ getSessionEndReason as g,
4710
+ PersistentAlert as h,
4711
+ isNativeOnlySession as i,
4712
+ pluginPermissions as j,
4713
+ SESSION_STATES as k,
4714
+ logSafeAdminError as l,
4715
+ SESSION_STATUS_PRESENTATION as m,
4716
+ buildSignInParams as n,
4717
+ useEventList as o,
4718
+ presentText as p,
4719
+ SignInEventTable as q,
4720
+ PERIOD_OPTIONS as r,
4721
+ buildSignInCsv as s,
4722
+ toValidDate as t,
4723
+ useSessionFormatters as u,
4724
+ SIGN_IN_FILTER_OPTIONS as v,
4725
+ buildActivityParams as w,
4726
+ buildActivityCsv as x,
4727
+ ACTIVITY_ACTION_OPTIONS as y,
4728
+ ACTIVITY_ACTION_LABELS as z
4729
+ };