strapi-plugin-magic-sessionmanager 4.16.1 → 4.18.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 (31) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +119 -25
  3. package/dist/admin/{Analytics-CMR62DiD.js → Analytics-C8fV6LDV.js} +1 -1
  4. package/dist/admin/{Analytics-FcRt0X62.mjs → Analytics-CBspdl1I.mjs} +1 -1
  5. package/dist/admin/{App-CmytGbze.js → App-D92MTQmn.js} +33 -170
  6. package/dist/admin/{App-DBieSWB0.mjs → App-PLwqaRSQ.mjs} +3 -140
  7. package/dist/admin/{OnlineUsersWidget-Lzx9XB74.js → OnlineUsersWidget-CiKapC1B.js} +1 -1
  8. package/dist/admin/{OnlineUsersWidget-zP9Hl_it.mjs → OnlineUsersWidget-CwfBJdIX.mjs} +1 -1
  9. package/dist/admin/{Settings-CZOPusQK.mjs → Settings-CMgL-Aub.mjs} +2013 -78
  10. package/dist/admin/{Settings-1v--SXC0.js → Settings-Duil_4jv.js} +2017 -82
  11. package/dist/admin/dashboardModel-BhUonEqc.mjs +189 -0
  12. package/dist/admin/dashboardModel-sksvIc1c.js +188 -0
  13. package/dist/admin/{de-y_9mdVT7.js → de-CnInuvMY.js} +196 -11
  14. package/dist/admin/{de-D3TSA066.mjs → de-D2BqfY1f.mjs} +196 -11
  15. package/dist/admin/{en-B60I97bK.mjs → en-BPy208we.mjs} +196 -11
  16. package/dist/admin/{en-CIQB8nfI.js → en-KnmmYHTF.js} +196 -11
  17. package/dist/admin/{es-CJEL_iGC.mjs → es-B4VNeT0A.mjs} +196 -11
  18. package/dist/admin/{es-DHhHzlRY.js → es-D1NGCAJK.js} +196 -11
  19. package/dist/admin/{fr-BfBK_iuV.mjs → fr-AwhLN1BC.mjs} +196 -11
  20. package/dist/admin/{fr-D86FTt1w.js → fr-D1KNyogi.js} +196 -11
  21. package/dist/admin/{index-tt61o2VH.mjs → index-BmnC2BPs.mjs} +40 -38
  22. package/dist/admin/{index-CSJJn4qy.js → index-Bnt0Jq6O.js} +12 -10
  23. package/dist/admin/index.js +1 -1
  24. package/dist/admin/index.mjs +1 -1
  25. package/dist/admin/{pt-C3PSvC7z.mjs → pt-D6m1TijL.mjs} +196 -11
  26. package/dist/admin/{pt-BE-FT-L8.js → pt-EKThRXPY.js} +196 -11
  27. package/dist/server/index.js +3230 -129
  28. package/dist/server/index.mjs +3230 -129
  29. package/package.json +1 -1
  30. package/dist/admin/riskData-BVs9GpgD.js +0 -26
  31. package/dist/admin/riskData-CI1gm2yI.mjs +0 -27
@@ -1,13 +1,14 @@
1
1
  import { jsx, jsxs, Fragment as Fragment$1 } from "react/jsx-runtime";
2
2
  import { useState, useCallback, createContext, useContext, useMemo, useId, Fragment, useRef, useEffect, useLayoutEffect } from "react";
3
- import { Field, Typography, Switch, Box, TextInput, Flex, Button, Link, SingleSelect, SingleSelectOption, Accordion, Alert, Badge, Radio, Dialog, Tag, Combobox, ComboboxOption, NumberInput, Divider, Tabs, Textarea, Checkbox } from "@strapi/design-system";
4
- import { ConfirmDialog, useNotification, useFetchClient, useQueryParams, useRBAC, Page, Form, Blocker, useForm } from "@strapi/strapi/admin";
5
- import { EyeStriked, Eye, Key, Duplicate, Cross, Plus, Trash, Download, Check } from "@strapi/icons";
3
+ import { Field, Typography, Switch, Box, TextInput, Flex, Button, Link, SingleSelect, SingleSelectOption, Accordion, Table, Thead, Tr, Th, VisuallyHidden, Tbody, Td, Modal, NumberInput, IconButton, Alert, Badge, Radio, Loader, EmptyStateLayout, Textarea, Dialog, Tag, Combobox, ComboboxOption, Divider, Tabs, Checkbox } from "@strapi/design-system";
4
+ import { useFetchClient, useNotification, useRBAC, ConfirmDialog, useQueryParams, Page, Form, Blocker, useForm } from "@strapi/strapi/admin";
5
+ import { EyeStriked, Eye, Key, Duplicate, Plus, Pencil, Trash, Lock, ArrowClockwise, Cross, Download, Check } from "@strapi/icons";
6
6
  import styled from "styled-components";
7
- import { F as ReadableParagraphs, b as getTranslation, m as logSafeAdminError, R as ReadableText, G as EqualGrid, n as PersistentAlert, P as PropertyList, H as formatSessionDate, C as ConfirmAction, I as refocusIfLost, l as pluginId, s as isCancelledRequest, J as requireSuccessfulMutation, o as pluginPermissions, w as PageShell } from "./index-tt61o2VH.mjs";
7
+ import { y as ReadableParagraphs, b as getTranslation, l as logSafeAdminError, R as ReadableText, f as pluginId, n as isCancelledRequest, h as PersistentAlert, z as EqualGrid, u as useSessionFormatters, j as pluginPermissions, C as ConfirmAction, P as PropertyList, A as formatSessionDate, B as refocusIfLost, F as requireSuccessfulMutation, q as PageShell } from "./index-BmnC2BPs.mjs";
8
8
  import { useIntl } from "react-intl";
9
9
  import { S as SectionCard } from "./SectionCard-D51bv4Hi.mjs";
10
- import { g as getRiskAvailability, r as riskDependentControl } from "./riskData-CI1gm2yI.mjs";
10
+ import { u as useElementWidth, b as RowActions, s as shouldIsolateActionKey, o as getRiskAvailability, q as riskDependentControl } from "./dashboardModel-BhUonEqc.mjs";
11
+ import { EmptyPermissions } from "@strapi/icons/symbols";
11
12
  const SETTINGS_TAB_IDS = Object.freeze([
12
13
  "sessions",
13
14
  "login-protection",
@@ -34,10 +35,24 @@ const SETTINGS_TAB_FIELDS = Object.freeze({
34
35
  "cleanupInterval",
35
36
  "cleanupUseDbDirect",
36
37
  "strictSessionEnforcement",
37
- "sessionCreationGraceMs"
38
+ "sessionCreationGraceMs",
39
+ "maxSessionsPerUser",
40
+ "sessionLimitPolicy",
41
+ "endOtherSessionsOnPasswordChange",
42
+ "roleRules"
38
43
  ],
39
44
  "login-protection": [
40
45
  "maxFailedLogins",
46
+ "maxFailedLoginsPerAccount",
47
+ "lockoutWindowMinutes",
48
+ "lockoutDurationMinutes",
49
+ "lockoutTrustedAddresses",
50
+ "lockoutNotifyUser",
51
+ "recordUserSignInEvents",
52
+ "impossibleTravelEnabled",
53
+ "impossibleTravelSpeedKmh",
54
+ "impossibleTravelMinDistanceKm",
55
+ "impossibleTravelAction",
41
56
  "trustedProxies",
42
57
  "blockSuspiciousSessions",
43
58
  "geoLookupFailureMode",
@@ -59,9 +74,15 @@ const SETTINGS_TAB_FIELDS = Object.freeze({
59
74
  "emailTemplates",
60
75
  "enableWebhooks",
61
76
  "discordWebhookUrl",
62
- "slackWebhookUrl"
77
+ "slackWebhookUrl",
78
+ "alertOnNewDevice",
79
+ "alertOnImpossibleTravel",
80
+ "webhookEvents",
81
+ "genericWebhookEnabled",
82
+ "genericWebhookUrl",
83
+ "genericWebhookSecret"
63
84
  ],
64
- "data-retention": ["retentionDays"],
85
+ "data-retention": ["retentionDays", "sessionIpAnonymize"],
65
86
  "admin-activity": [
66
87
  "adminSignInHistory",
67
88
  "adminContentActivity",
@@ -87,7 +108,37 @@ const SETTINGS_FIELD_LABELS = Object.freeze({
87
108
  cleanupUseDbDirect: ["settings.config.sessions.idleMethod.label", "Idle check method"],
88
109
  strictSessionEnforcement: ["settings.config.token.check.label", "Strict token check"],
89
110
  sessionCreationGraceMs: ["settings.config.token.grace.label", "Grace period after sign-in"],
90
- maxFailedLogins: ["settings.config.failed.lockout.label", "Temporary IP lockout after"],
111
+ maxFailedLogins: ["settings.config.failed.lockout.label", "Lock an IP address after"],
112
+ maxFailedLoginsPerAccount: ["settings.config.failed.account.label", "Lock an account after"],
113
+ lockoutWindowMinutes: ["settings.config.failed.window.label", "Count failed sign-ins within"],
114
+ lockoutDurationMinutes: ["settings.config.failed.duration.label", "Lock for"],
115
+ lockoutTrustedAddresses: ["settings.config.failed.trusted.label", "Trusted addresses"],
116
+ lockoutNotifyUser: [
117
+ "settings.config.failed.notify.label",
118
+ "Email the user when their account is locked"
119
+ ],
120
+ recordUserSignInEvents: [
121
+ "settings.config.failed.record.label",
122
+ "Record failed and refused sign-ins"
123
+ ],
124
+ maxSessionsPerUser: ["settings.config.sessionLimit.max.label", "Open sessions per user"],
125
+ sessionLimitPolicy: ["settings.config.sessionLimit.policy.label", "When the limit is reached"],
126
+ endOtherSessionsOnPasswordChange: [
127
+ "settings.config.passwordChange.label",
128
+ "End other sessions after a password change"
129
+ ],
130
+ roleRules: ["settings.roleRules.title", "Different rules for some roles"],
131
+ impossibleTravelEnabled: ["settings.config.travel.enable.label", "Detect impossible travel"],
132
+ impossibleTravelSpeedKmh: ["settings.config.travel.speed.label", "Faster than"],
133
+ impossibleTravelMinDistanceKm: ["settings.config.travel.distance.label", "Over at least"],
134
+ impossibleTravelAction: ["settings.config.travel.action.label", "Then"],
135
+ alertOnNewDevice: ["settings.config.email.newDevice.label", "Sign-in from a new device"],
136
+ alertOnImpossibleTravel: ["settings.config.email.travel.label", "Impossible travel"],
137
+ webhookEvents: ["settings.webhookEvents.title", "Events to send"],
138
+ genericWebhookEnabled: ["settings.signedWebhook.enable.label", "Send to the signed webhook"],
139
+ genericWebhookUrl: ["settings.signedWebhook.url.label", "Webhook URL"],
140
+ genericWebhookSecret: ["settings.signedWebhook.secret.label", "Signing secret"],
141
+ sessionIpAnonymize: ["settings.config.privacy.shortIp.label", "Shorten IP addresses of sessions"],
91
142
  trustedProxies: ["settings.config.clientIp.trustProxy.label", "Trust proxy headers"],
92
143
  blockSuspiciousSessions: [
93
144
  "settings.config.suspicious.reject.label",
@@ -733,6 +784,441 @@ const TermList = ({ items, label, code = false }) => /* @__PURE__ */ jsx(Terms,
733
784
  ) }),
734
785
  /* @__PURE__ */ jsx("dd", { children: /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral700", children: item.description }) })
735
786
  ] }, item.id)) });
787
+ const POLICY_FORM_DEFAULTS = Object.freeze({
788
+ maxFailedLoginsPerAccount: 0,
789
+ lockoutWindowMinutes: 15,
790
+ lockoutDurationMinutes: 15,
791
+ lockoutTrustedAddresses: Object.freeze([]),
792
+ lockoutNotifyUser: false,
793
+ recordUserSignInEvents: true,
794
+ maxSessionsPerUser: 0,
795
+ sessionLimitPolicy: "end-oldest",
796
+ endOtherSessionsOnPasswordChange: true,
797
+ roleRules: Object.freeze([])
798
+ });
799
+ const POLICY_RANGES = Object.freeze({
800
+ maxFailedLoginsPerAccount: Object.freeze({ min: 0, max: 100 }),
801
+ lockoutWindowMinutes: Object.freeze({ min: 1, max: 1440 }),
802
+ lockoutDurationMinutes: Object.freeze({ min: 1, max: 10080 }),
803
+ maxSessionsPerUser: Object.freeze({ min: 0, max: 100 })
804
+ });
805
+ const ROLE_RULE_RANGES = Object.freeze({
806
+ maxSessionsPerUser: Object.freeze({ min: 0, max: 100 }),
807
+ inactivityTimeout: Object.freeze({ min: 1, max: 1440 }),
808
+ maxFailedLoginsPerAccount: Object.freeze({ min: 0, max: 100 })
809
+ });
810
+ const ROLE_RULE_FIELDS = Object.freeze(Object.keys(ROLE_RULE_RANGES));
811
+ const MAX_TRUSTED_ADDRESSES = 100;
812
+ const message$2 = (messageId, defaultMessage, values) => ({ messageId, defaultMessage, values });
813
+ function validateWholeNumber(value, { min, max }) {
814
+ if (value === void 0 || value === null || value === "") {
815
+ return message$2("settings.validation.required", "Enter a value.");
816
+ }
817
+ const number = Number(value);
818
+ if (!Number.isInteger(number) || number < min || number > max) {
819
+ return message$2("settings.validation.range", "Enter a whole number from {min} to {max}.", {
820
+ min,
821
+ max
822
+ });
823
+ }
824
+ return null;
825
+ }
826
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
827
+ const IPV6_CHARS = /^[0-9a-f:.]{2,45}$/i;
828
+ function isTrustedAddressLine(line) {
829
+ const value = String(line || "").trim();
830
+ if (!value || value.length > 64) return false;
831
+ const [address, prefix, extra] = value.split("/");
832
+ if (extra !== void 0) return false;
833
+ const v4 = IPV4.test(address);
834
+ const v6 = !v4 && address.includes(":") && IPV6_CHARS.test(address) && !address.includes(":::");
835
+ if (!v4 && !v6) return false;
836
+ if (prefix === void 0) return true;
837
+ if (!/^\d{1,3}$/.test(prefix)) return false;
838
+ return Number(prefix) <= (v4 ? 32 : 128);
839
+ }
840
+ function parseTrustedAddressText(text) {
841
+ return String(text || "").split(/[\n,]/).map((line) => line.trim()).filter(Boolean);
842
+ }
843
+ function formatTrustedAddressText(list) {
844
+ return Array.isArray(list) ? list.join("\n") : "";
845
+ }
846
+ function validatePolicyFields(settings) {
847
+ const source = settings || {};
848
+ const errors = {};
849
+ for (const [key, range] of Object.entries(POLICY_RANGES)) {
850
+ if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
851
+ const error = validateWholeNumber(source[key], range);
852
+ if (error) errors[key] = error;
853
+ }
854
+ const entries = Array.isArray(source.lockoutTrustedAddresses) ? source.lockoutTrustedAddresses : [];
855
+ if (entries.length > MAX_TRUSTED_ADDRESSES) {
856
+ errors.lockoutTrustedAddresses = message$2(
857
+ "settings.validation.trustedTooMany",
858
+ "Enter at most {max} addresses.",
859
+ { max: MAX_TRUSTED_ADDRESSES }
860
+ );
861
+ } else {
862
+ const invalid = entries.find((entry) => !isTrustedAddressLine(entry));
863
+ if (invalid !== void 0) {
864
+ errors.lockoutTrustedAddresses = message$2(
865
+ "settings.validation.trustedAddress",
866
+ '"{value}" is not an IP address or CIDR range. Use for example 192.0.2.10 or 192.0.2.0/24.',
867
+ { value: String(invalid).slice(0, 64) }
868
+ );
869
+ }
870
+ }
871
+ return errors;
872
+ }
873
+ function validateRoleRule(draft, takenRoles = []) {
874
+ const errors = {};
875
+ if (!draft?.role) {
876
+ errors.role = message$2("settings.roleRules.validation.role", "Choose a role.");
877
+ } else if (takenRoles.includes(draft.role)) {
878
+ errors.role = message$2(
879
+ "settings.roleRules.validation.duplicate",
880
+ "This role already has a rule."
881
+ );
882
+ }
883
+ let values = 0;
884
+ for (const field of ROLE_RULE_FIELDS) {
885
+ const value = draft?.[field];
886
+ if (value === void 0 || value === null || value === "") continue;
887
+ const error = validateWholeNumber(value, ROLE_RULE_RANGES[field]);
888
+ if (error) errors[field] = error;
889
+ else values += 1;
890
+ }
891
+ if (values === 0 && !ROLE_RULE_FIELDS.some((field) => errors[field])) {
892
+ errors.form = message$2(
893
+ "settings.roleRules.validation.empty",
894
+ "Set at least one value. Empty fields use the general setting."
895
+ );
896
+ }
897
+ return errors;
898
+ }
899
+ function toRoleRule(draft) {
900
+ const rule = { role: draft.role };
901
+ for (const field of ROLE_RULE_FIELDS) {
902
+ const value = draft[field];
903
+ rule[field] = value === void 0 || value === null || value === "" ? null : Number(value);
904
+ }
905
+ return rule;
906
+ }
907
+ function upsertRoleRule(rules, rule, previousRole = null) {
908
+ const list = Array.isArray(rules) ? rules : [];
909
+ const key = previousRole || rule.role;
910
+ const index = list.findIndex((candidate) => candidate.role === key);
911
+ if (index === -1) return [...list, rule];
912
+ return list.map((candidate, position) => position === index ? rule : candidate);
913
+ }
914
+ function removeRoleRule(rules, role) {
915
+ return (Array.isArray(rules) ? rules : []).filter((rule) => rule.role !== role);
916
+ }
917
+ function sortLocks(locks) {
918
+ return (Array.isArray(locks) ? locks : []).slice().sort((a, b) => {
919
+ const until = Date.parse(b.until) - Date.parse(a.until);
920
+ return Number.isFinite(until) && until !== 0 ? until : String(a.id).localeCompare(b.id);
921
+ });
922
+ }
923
+ const TABLE_MIN_WIDTH$1 = 640;
924
+ const keepActionKeys$1 = (event) => {
925
+ if (shouldIsolateActionKey(event.key, true)) event.stopPropagation();
926
+ };
927
+ const EMPTY_DRAFT = Object.freeze({
928
+ role: "",
929
+ maxSessionsPerUser: void 0,
930
+ inactivityTimeout: void 0,
931
+ maxFailedLoginsPerAccount: void 0
932
+ });
933
+ const RuleValue = ({ value, format }) => {
934
+ const { t } = useSettingsTranslate();
935
+ if (value === null || value === void 0) {
936
+ return /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", children: t("settings.roleRules.general", "General setting") });
937
+ }
938
+ return /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: format(value) });
939
+ };
940
+ const RoleRulesSection = ({ form }) => {
941
+ const { t, tError } = useSettingsTranslate();
942
+ const { get } = useFetchClient();
943
+ const { settings, handleChange } = form;
944
+ const locked = form.canChangeProtected === false;
945
+ const rules = Array.isArray(settings.roleRules) ? settings.roleRules : [];
946
+ const [roles, setRoles] = useState(null);
947
+ const [rolesError, setRolesError] = useState(false);
948
+ const [dialog, setDialog] = useState(null);
949
+ const [draft, setDraft] = useState(EMPTY_DRAFT);
950
+ const [showErrors, setShowErrors] = useState(false);
951
+ const addRef = useRef(null);
952
+ const returnFocusRef = useRef(null);
953
+ const [widthRef, width] = useElementWidth();
954
+ useEffect(() => {
955
+ let active = true;
956
+ get(`/${pluginId}/roles`).then(({ data }) => {
957
+ if (!active) return;
958
+ if (!Array.isArray(data?.data)) throw new Error("Invalid role list");
959
+ setRoles(data.data);
960
+ }).catch((err) => {
961
+ if (!active || isCancelledRequest(err)) return;
962
+ logSafeAdminError("roles", err);
963
+ setRolesError(true);
964
+ });
965
+ return () => {
966
+ active = false;
967
+ };
968
+ }, [get]);
969
+ const roleName = (documentId) => roles?.find((role) => role.documentId === documentId)?.name || t("settings.roleRules.unknownRole", "Removed role");
970
+ const minutes = (value) => t("settings.roleRules.minutes", "{count, plural, one {# minute} other {# minutes}}", {
971
+ count: value
972
+ });
973
+ const sessions = (value) => value === 0 ? t("settings.roleRules.noLimit", "No limit") : t("settings.roleRules.sessions", "{count, plural, one {# session} other {# sessions}}", {
974
+ count: value
975
+ });
976
+ const failures = (value) => value === 0 ? t("settings.roleRules.noAccountLock", "Off") : t("settings.roleRules.failures", "{count, plural, one {# failure} other {# failures}}", {
977
+ count: value
978
+ });
979
+ const open = (rule, trigger) => {
980
+ returnFocusRef.current = trigger || addRef.current;
981
+ setShowErrors(false);
982
+ setDraft(
983
+ rule ? {
984
+ role: rule.role,
985
+ maxSessionsPerUser: rule.maxSessionsPerUser ?? void 0,
986
+ inactivityTimeout: rule.inactivityTimeout ?? void 0,
987
+ maxFailedLoginsPerAccount: rule.maxFailedLoginsPerAccount ?? void 0
988
+ } : EMPTY_DRAFT
989
+ );
990
+ setDialog({ editing: rule ? rule.role : null });
991
+ };
992
+ const close = () => {
993
+ setDialog(null);
994
+ window.requestAnimationFrame?.(() => {
995
+ const target = returnFocusRef.current?.isConnected ? returnFocusRef.current : addRef.current;
996
+ target?.focus?.();
997
+ });
998
+ };
999
+ const taken = rules.map((rule) => rule.role).filter((role) => role !== dialog?.editing);
1000
+ const draftErrors = validateRoleRule(draft, taken);
1001
+ const submit = () => {
1002
+ if (Object.keys(draftErrors).length > 0) {
1003
+ setShowErrors(true);
1004
+ return;
1005
+ }
1006
+ handleChange("roleRules", upsertRoleRule(rules, toRoleRule(draft), dialog?.editing));
1007
+ close();
1008
+ };
1009
+ const fieldError = (key) => showErrors ? tError(draftErrors[key]) : void 0;
1010
+ const availableRoles = (roles || []).filter((role) => !taken.includes(role.documentId));
1011
+ const asTable = width === 0 || width >= TABLE_MIN_WIDTH$1;
1012
+ const actions = (rule) => {
1013
+ const name = roleName(rule.role);
1014
+ return /* @__PURE__ */ jsxs(RowActions, { onKeyDown: keepActionKeys$1, children: [
1015
+ /* @__PURE__ */ jsx(
1016
+ IconButton,
1017
+ {
1018
+ variant: "ghost",
1019
+ disabled: locked,
1020
+ label: t("settings.roleRules.edit", "Edit the rule for {role}", { role: name }),
1021
+ onClick: (event) => open(rule, event.currentTarget),
1022
+ children: /* @__PURE__ */ jsx(Pencil, {})
1023
+ }
1024
+ ),
1025
+ /* @__PURE__ */ jsx(
1026
+ IconButton,
1027
+ {
1028
+ variant: "ghost",
1029
+ disabled: locked,
1030
+ label: t("settings.roleRules.remove", "Remove the rule for {role}", { role: name }),
1031
+ onClick: () => {
1032
+ handleChange("roleRules", removeRoleRule(rules, rule.role));
1033
+ window.requestAnimationFrame?.(() => addRef.current?.focus?.());
1034
+ },
1035
+ children: /* @__PURE__ */ jsx(Trash, {})
1036
+ }
1037
+ )
1038
+ ] });
1039
+ };
1040
+ return /* @__PURE__ */ jsxs(
1041
+ AdvancedSection,
1042
+ {
1043
+ label: t("settings.roleRules.title", "Different rules for some roles"),
1044
+ hasError: Object.keys(form.errors || {}).some((key) => key.startsWith("roleRules")),
1045
+ children: [
1046
+ /* @__PURE__ */ jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t(
1047
+ "settings.roleRules.intro",
1048
+ "Give a Users & Permissions role its own session limit, inactivity timeout or account lockout. Empty values use the general setting. The overview still counts sessions as idle by the general timeout."
1049
+ ) }),
1050
+ locked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null,
1051
+ rolesError ? /* @__PURE__ */ jsx(
1052
+ PersistentAlert,
1053
+ {
1054
+ variant: "warning",
1055
+ closeLabel: t("common.close", "Close"),
1056
+ title: t("settings.roleRules.rolesError", "Roles could not be loaded."),
1057
+ children: t(
1058
+ "settings.roleRules.rolesErrorBody",
1059
+ "Existing rules still apply. Reload the page to add or edit rules."
1060
+ )
1061
+ }
1062
+ ) : null,
1063
+ /* @__PURE__ */ jsx("div", { ref: widthRef, children: rules.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", tag: "p", children: t(
1064
+ "settings.roleRules.empty",
1065
+ "No role has its own rules. Every role uses the general settings."
1066
+ ) }) : asTable ? /* @__PURE__ */ jsx(Box, { hasRadius: true, borderColor: "neutral150", "data-role-rules-table": "", children: /* @__PURE__ */ jsxs(Table, { colCount: 5, rowCount: rules.length + 1, children: [
1067
+ /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
1068
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.roleRules.col.role", "Role") }) }),
1069
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.roleRules.col.sessions", "Session limit") }) }),
1070
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.roleRules.col.idle", "Inactivity timeout") }) }),
1071
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.roleRules.col.lockout", "Account lockout") }) }),
1072
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("settings.roleRules.col.actions", "Actions") }) })
1073
+ ] }) }),
1074
+ /* @__PURE__ */ jsx(Tbody, { children: rules.map((rule) => /* @__PURE__ */ jsxs(Tr, { "data-role-rule": rule.role, children: [
1075
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: roleName(rule.role) }) }),
1076
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(RuleValue, { value: rule.maxSessionsPerUser, format: sessions }) }),
1077
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(RuleValue, { value: rule.inactivityTimeout, format: minutes }) }),
1078
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(RuleValue, { value: rule.maxFailedLoginsPerAccount, format: failures }) }),
1079
+ /* @__PURE__ */ jsx(Td, { children: actions(rule) })
1080
+ ] }, rule.role)) })
1081
+ ] }) }) : /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 2, tag: "ul", children: rules.map((rule) => /* @__PURE__ */ jsx(
1082
+ Box,
1083
+ {
1084
+ tag: "li",
1085
+ padding: 4,
1086
+ hasRadius: true,
1087
+ borderColor: "neutral150",
1088
+ "data-role-rule": rule.role,
1089
+ children: /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "flex-start", gap: 3, children: [
1090
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, children: [
1091
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", textColor: "neutral800", children: roleName(rule.role) }),
1092
+ [
1093
+ [
1094
+ "settings.roleRules.col.sessions",
1095
+ "Session limit",
1096
+ rule.maxSessionsPerUser,
1097
+ sessions
1098
+ ],
1099
+ [
1100
+ "settings.roleRules.col.idle",
1101
+ "Inactivity timeout",
1102
+ rule.inactivityTimeout,
1103
+ minutes
1104
+ ],
1105
+ [
1106
+ "settings.roleRules.col.lockout",
1107
+ "Account lockout",
1108
+ rule.maxFailedLoginsPerAccount,
1109
+ failures
1110
+ ]
1111
+ ].map(([id, label, value, format]) => /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("settings.roleRules.line", "{label}: {value}", {
1112
+ label: t(id, label),
1113
+ value: value === null || value === void 0 ? t("settings.roleRules.general", "General setting") : format(value)
1114
+ }) }, id))
1115
+ ] }),
1116
+ actions(rule)
1117
+ ] })
1118
+ },
1119
+ rule.role
1120
+ )) }) }),
1121
+ /* @__PURE__ */ jsxs(Flex, { gap: 3, wrap: "wrap", alignItems: "center", children: [
1122
+ /* @__PURE__ */ jsx(
1123
+ Button,
1124
+ {
1125
+ ref: addRef,
1126
+ variant: "secondary",
1127
+ startIcon: /* @__PURE__ */ jsx(Plus, {}),
1128
+ disabled: locked || roles !== null && availableRoles.length === 0 && !dialog,
1129
+ onClick: () => open(null, addRef.current),
1130
+ children: t("settings.roleRules.add", "Add rule")
1131
+ }
1132
+ ),
1133
+ roles !== null && roles.length > 0 && availableRoles.length === 0 ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", "data-role-rules-full": "", children: t(
1134
+ "settings.roleRules.allRoles",
1135
+ "Every role already has a rule. Edit a rule to change it."
1136
+ ) }) : null
1137
+ ] }),
1138
+ /* @__PURE__ */ jsx(Modal.Root, { open: Boolean(dialog), onOpenChange: (next) => next ? null : close(), children: /* @__PURE__ */ jsxs(Modal.Content, { "aria-describedby": void 0, children: [
1139
+ /* @__PURE__ */ jsx(Modal.Header, { closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsx(Modal.Title, { children: dialog?.editing ? t("settings.roleRules.dialog.editTitle", "Edit the rule for {role}", {
1140
+ role: roleName(dialog.editing)
1141
+ }) : t("settings.roleRules.dialog.addTitle", "Add a rule for a role") }) }),
1142
+ /* @__PURE__ */ jsx(Modal.Body, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 5, children: [
1143
+ /* @__PURE__ */ jsx(
1144
+ FormField,
1145
+ {
1146
+ id: "role-rule-role",
1147
+ name: "role",
1148
+ label: t("settings.roleRules.col.role", "Role"),
1149
+ error: fieldError("role"),
1150
+ required: true,
1151
+ children: /* @__PURE__ */ jsx(
1152
+ SingleSelect,
1153
+ {
1154
+ value: draft.role || void 0,
1155
+ placeholder: t("settings.roleRules.dialog.rolePlaceholder", "Choose a role"),
1156
+ onChange: (value) => setDraft((previous) => ({ ...previous, role: value })),
1157
+ children: (roles || []).filter(
1158
+ (role) => role.documentId === draft.role || !taken.includes(role.documentId)
1159
+ ).map((role) => /* @__PURE__ */ jsx(SingleSelectOption, { value: role.documentId, children: role.name }, role.documentId))
1160
+ }
1161
+ )
1162
+ }
1163
+ ),
1164
+ [
1165
+ [
1166
+ "maxSessionsPerUser",
1167
+ "role-rule-sessions",
1168
+ t("settings.config.sessionLimit.max.label", "Open sessions per user"),
1169
+ t("settings.roleRules.dialog.sessionsHint", "0 means no limit for this role."),
1170
+ t("settings.roleRules.dialog.sessionsSuffix", "sessions")
1171
+ ],
1172
+ [
1173
+ "inactivityTimeout",
1174
+ "role-rule-idle",
1175
+ t("settings.config.sessions.inactivity.label", "Inactivity timeout"),
1176
+ t("settings.roleRules.dialog.idleHint", "From 1 to 1440 minutes."),
1177
+ t("settings.config.failed.minutes.suffix", "minutes")
1178
+ ],
1179
+ [
1180
+ "maxFailedLoginsPerAccount",
1181
+ "role-rule-lockout",
1182
+ t("settings.config.failed.account.label", "Lock an account after"),
1183
+ t(
1184
+ "settings.roleRules.dialog.lockoutHint",
1185
+ "0 turns the account lockout off for this role."
1186
+ ),
1187
+ t("settings.config.failed.lockout.suffix", "failed sign-ins")
1188
+ ]
1189
+ ].map(([key, id, label, hint, suffix]) => /* @__PURE__ */ jsx(
1190
+ FormField,
1191
+ {
1192
+ id,
1193
+ name: key,
1194
+ label,
1195
+ description: `${hint} ${t("settings.roleRules.dialog.emptyHint", "Leave empty to use the general setting.")}`,
1196
+ suffix,
1197
+ error: fieldError(key),
1198
+ children: /* @__PURE__ */ jsx(
1199
+ NumberInput,
1200
+ {
1201
+ value: draft[key],
1202
+ onValueChange: (value) => setDraft((previous) => ({ ...previous, [key]: value })),
1203
+ min: ROLE_RULE_RANGES[key].min,
1204
+ max: ROLE_RULE_RANGES[key].max,
1205
+ step: 1
1206
+ }
1207
+ )
1208
+ },
1209
+ key
1210
+ )),
1211
+ showErrors && draftErrors.form ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "danger600", tag: "p", role: "alert", children: tError(draftErrors.form) }) : null
1212
+ ] }) }),
1213
+ /* @__PURE__ */ jsxs(Modal.Footer, { children: [
1214
+ /* @__PURE__ */ jsx(Modal.Close, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", children: t("common.cancel", "Cancel") }) }),
1215
+ /* @__PURE__ */ jsx(Button, { onClick: submit, children: dialog?.editing ? t("settings.roleRules.dialog.apply", "Apply") : t("settings.roleRules.dialog.add", "Add rule") })
1216
+ ] })
1217
+ ] }) })
1218
+ ]
1219
+ }
1220
+ );
1221
+ };
736
1222
  const REJECTION_REASONS = [
737
1223
  ["logout", "settings.config.rejected.reason.logout", "The user signed out."],
738
1224
  [
@@ -763,10 +1249,12 @@ const formatReasonCodes = (locale) => {
763
1249
  }
764
1250
  };
765
1251
  const SessionsTab = ({ form }) => {
766
- const { t, locale } = useSettingsTranslate();
1252
+ const { t, tError, locale } = useSettingsTranslate();
767
1253
  const units = useOptionLabels();
768
1254
  const encryptionKeyDraft = useEncryptionKeyDraft();
769
- const { settings, handleChange, relaxedWarningDismissed, setRelaxedWarningDismissed } = form;
1255
+ const { settings, handleChange, relaxedWarningDismissed, setRelaxedWarningDismissed, errors } = form;
1256
+ const sessionLimit = Number(settings.maxSessionsPerUser) || 0;
1257
+ const locked = form.canChangeProtected === false;
770
1258
  const lastSeenTooSlow = Number(settings.lastSeenRateLimit) * 2 > Number(settings.inactivityTimeout) * 60;
771
1259
  return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
772
1260
  /* @__PURE__ */ jsx(IntroText, { children: t(
@@ -957,6 +1445,127 @@ const SessionsTab = ({ form }) => {
957
1445
  ]
958
1446
  }
959
1447
  ),
1448
+ /* @__PURE__ */ jsxs(
1449
+ SectionCard,
1450
+ {
1451
+ id: "session-limit",
1452
+ title: t("settings.config.sessionLimit.title", "Concurrent sessions"),
1453
+ subtitle: t(
1454
+ "settings.config.sessionLimit.intro",
1455
+ "Limits how many sessions one user can have open at the same time."
1456
+ ),
1457
+ children: [
1458
+ locked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null,
1459
+ /* @__PURE__ */ jsx(EqualGrid, { columns: 2, stackBelow: "medium", gap: 6, children: /* @__PURE__ */ jsx(
1460
+ FormField,
1461
+ {
1462
+ id: "max-sessions-per-user",
1463
+ name: "maxSessionsPerUser",
1464
+ label: t("settings.config.sessionLimit.max.label", "Open sessions per user"),
1465
+ description: t(
1466
+ "settings.config.sessionLimit.max.hint",
1467
+ "0 means no limit. Sessions that are idle or past their maximum age do not count."
1468
+ ),
1469
+ suffix: t("settings.roleRules.dialog.sessionsSuffix", "sessions"),
1470
+ error: tError(errors.maxSessionsPerUser),
1471
+ required: true,
1472
+ children: /* @__PURE__ */ jsx(
1473
+ NumberInput,
1474
+ {
1475
+ value: settings.maxSessionsPerUser,
1476
+ onValueChange: (value) => handleChange("maxSessionsPerUser", value ?? ""),
1477
+ disabled: locked,
1478
+ min: POLICY_RANGES.maxSessionsPerUser.min,
1479
+ max: POLICY_RANGES.maxSessionsPerUser.max,
1480
+ step: 1
1481
+ },
1482
+ form.draftVersion
1483
+ )
1484
+ }
1485
+ ) }),
1486
+ sessionLimit > 0 ? /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-session-limit-policy": "", children: [
1487
+ /* @__PURE__ */ jsx(
1488
+ Typography,
1489
+ {
1490
+ id: "session-limit-policy-label",
1491
+ variant: "pi",
1492
+ fontWeight: "bold",
1493
+ tag: "div",
1494
+ textColor: "neutral800",
1495
+ children: t("settings.config.sessionLimit.policy.label", "When the limit is reached")
1496
+ }
1497
+ ),
1498
+ /* @__PURE__ */ jsxs(
1499
+ Radio.Group,
1500
+ {
1501
+ "aria-labelledby": "session-limit-policy-label",
1502
+ value: settings.sessionLimitPolicy || "end-oldest",
1503
+ disabled: locked,
1504
+ onValueChange: (value) => handleChange("sessionLimitPolicy", value),
1505
+ children: [
1506
+ /* @__PURE__ */ jsx(Radio.Item, { value: "end-oldest", children: t("settings.config.sessionLimit.policy.endOldest", "End the oldest session") }),
1507
+ /* @__PURE__ */ jsx(Radio.Item, { value: "refuse", children: t("settings.config.sessionLimit.policy.refuse", "Refuse the new sign-in") })
1508
+ ]
1509
+ }
1510
+ ),
1511
+ settings.sessionLimitPolicy === "refuse" ? /* @__PURE__ */ jsx(
1512
+ Alert,
1513
+ {
1514
+ variant: "warning",
1515
+ closeLabel: t("common.close", "Close"),
1516
+ title: t(
1517
+ "settings.config.sessionLimit.refuse.title",
1518
+ "Users can lock themselves out"
1519
+ ),
1520
+ children: t(
1521
+ "settings.config.sessionLimit.refuse.body",
1522
+ "A user who reaches the limit cannot sign in on a new device until another session ends or times out. The app receives 403 with the code SESSION_LIMIT_REACHED."
1523
+ )
1524
+ }
1525
+ ) : null
1526
+ ] }) : null
1527
+ ]
1528
+ }
1529
+ ),
1530
+ /* @__PURE__ */ jsxs(
1531
+ SectionCard,
1532
+ {
1533
+ id: "password-change",
1534
+ title: t("settings.config.passwordChange.title", "Password change"),
1535
+ children: [
1536
+ locked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null,
1537
+ /* @__PURE__ */ jsx(
1538
+ SettingsToggleRow,
1539
+ {
1540
+ id: "end-other-sessions-on-password-change",
1541
+ title: t(
1542
+ "settings.config.passwordChange.label",
1543
+ "End other sessions after a password change"
1544
+ ),
1545
+ description: t(
1546
+ "settings.config.passwordChange.hint",
1547
+ "When a user changes their password, every other session of that user ends. The session that made the change stays. A password reset always ends the other sessions."
1548
+ ),
1549
+ checked: settings.endOtherSessionsOnPasswordChange === true,
1550
+ disabled: locked,
1551
+ onChange: (checked) => handleChange("endOtherSessionsOnPasswordChange", checked)
1552
+ }
1553
+ )
1554
+ ]
1555
+ }
1556
+ ),
1557
+ /* @__PURE__ */ jsx(
1558
+ SectionCard,
1559
+ {
1560
+ id: "role-rules",
1561
+ title: t("settings.roleRules.cardTitle", "Roles"),
1562
+ subtitle: t(
1563
+ "settings.roleRules.cardIntro",
1564
+ "Optional. Most installations need no role rules."
1565
+ ),
1566
+ children: /* @__PURE__ */ jsx(RoleRulesSection, { form })
1567
+ }
1568
+ ),
960
1569
  /* @__PURE__ */ jsxs(
961
1570
  SectionCard,
962
1571
  {
@@ -1010,7 +1619,14 @@ function areSettingsEqual(left, right) {
1010
1619
  (key, index) => key === rightKeys[index] && areSettingsEqual(left[key], right[key])
1011
1620
  );
1012
1621
  }
1013
- const TEMPLATE_KEYS = Object.freeze(["suspiciousLogin", "newLocation", "vpnProxy"]);
1622
+ const TEMPLATE_KEYS = Object.freeze([
1623
+ "suspiciousLogin",
1624
+ "newLocation",
1625
+ "vpnProxy",
1626
+ "accountLocked",
1627
+ "newDevice",
1628
+ "impossibleTravel"
1629
+ ]);
1014
1630
  const TEMPLATE_LIMITS = Object.freeze({ subject: 200, html: 1e4, text: 5e3 });
1015
1631
  const TEMPLATE_VARIABLE_DEFINITIONS = Object.freeze({
1016
1632
  "{{user.email}}": {
@@ -1060,6 +1676,30 @@ const TEMPLATE_VARIABLE_DEFINITIONS = Object.freeze({
1060
1676
  "{{reason.securityScore}}": {
1061
1677
  messageId: "settings.email.templates.variable.securityScore",
1062
1678
  defaultMessage: "Security score (0 to 100)"
1679
+ },
1680
+ "{{lock.minutes}}": {
1681
+ messageId: "settings.email.templates.variable.lockMinutes",
1682
+ defaultMessage: "Lock duration in minutes"
1683
+ },
1684
+ "{{lock.until}}": {
1685
+ messageId: "settings.email.templates.variable.lockUntil",
1686
+ defaultMessage: "Time the lock ends (UTC)"
1687
+ },
1688
+ "{{device.browser}}": {
1689
+ messageId: "settings.email.templates.variable.deviceBrowser",
1690
+ defaultMessage: "Browser of the sign-in"
1691
+ },
1692
+ "{{device.os}}": {
1693
+ messageId: "settings.email.templates.variable.deviceOs",
1694
+ defaultMessage: "Operating system of the sign-in"
1695
+ },
1696
+ "{{travel.distanceKm}}": {
1697
+ messageId: "settings.email.templates.variable.travelDistance",
1698
+ defaultMessage: "Distance from the previous sign-in in km"
1699
+ },
1700
+ "{{link.notMe}}": {
1701
+ messageId: "settings.email.templates.variable.notMe",
1702
+ defaultMessage: "“This wasn’t me” link (works once, 72 hours)"
1063
1703
  }
1064
1704
  });
1065
1705
  const TEMPLATE_VARIABLES = Object.freeze({
@@ -1097,6 +1737,29 @@ const TEMPLATE_VARIABLES = Object.freeze({
1097
1737
  "{{session.userAgent}}",
1098
1738
  "{{reason.isVpn}}",
1099
1739
  "{{reason.isProxy}}"
1740
+ ],
1741
+ accountLocked: ["{{user.email}}", "{{user.username}}", "{{lock.minutes}}", "{{lock.until}}"],
1742
+ newDevice: [
1743
+ "{{user.email}}",
1744
+ "{{user.username}}",
1745
+ "{{session.loginTime}}",
1746
+ "{{session.ipAddress}}",
1747
+ "{{geo.city}}",
1748
+ "{{geo.country}}",
1749
+ "{{device.browser}}",
1750
+ "{{device.os}}",
1751
+ "{{link.notMe}}"
1752
+ ],
1753
+ impossibleTravel: [
1754
+ "{{user.email}}",
1755
+ "{{user.username}}",
1756
+ "{{session.loginTime}}",
1757
+ "{{geo.city}}",
1758
+ "{{geo.country}}",
1759
+ "{{device.browser}}",
1760
+ "{{device.os}}",
1761
+ "{{travel.distanceKm}}",
1762
+ "{{link.notMe}}"
1100
1763
  ]
1101
1764
  });
1102
1765
  const TEMPLATE_PREVIEW_VALUES = Object.freeze({
@@ -1111,7 +1774,13 @@ const TEMPLATE_PREVIEW_VALUES = Object.freeze({
1111
1774
  "{{reason.isVpn}}": "true",
1112
1775
  "{{reason.isProxy}}": "false",
1113
1776
  "{{reason.isThreat}}": "false",
1114
- "{{reason.securityScore}}": "35"
1777
+ "{{reason.securityScore}}": "35",
1778
+ "{{lock.minutes}}": "15",
1779
+ "{{lock.until}}": "Fri, 06 Nov 2026 09:56:00 GMT",
1780
+ "{{device.browser}}": "Firefox",
1781
+ "{{device.os}}": "macOS",
1782
+ "{{travel.distanceKm}}": "16032",
1783
+ "{{link.notMe}}": "https://app.example.com/api/magic-sessionmanager/not-me?token=preview"
1115
1784
  });
1116
1785
  function updateEmailTemplate(templates, templateKey, field, value) {
1117
1786
  return { ...templates, [templateKey]: { ...templates[templateKey], [field]: value } };
@@ -1372,6 +2041,97 @@ Login Details:
1372
2041
  - IP Address: {{session.ipAddress}}
1373
2042
  - Location: {{geo.city}}, {{geo.country}}
1374
2043
  - VPN: {{reason.isVpn}}, Proxy: {{reason.isProxy}}`
2044
+ },
2045
+ // Same default as server/src/services/notifications.js (4.17).
2046
+ accountLocked: {
2047
+ subject: "Your account was locked after failed sign-ins",
2048
+ html: `<html>
2049
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
2050
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
2051
+ <h2>Your account was temporarily locked</h2>
2052
+ <p>Hello {{user.username}},</p>
2053
+ <p>There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.</p>
2054
+ <p>If these attempts were not yours, change your password after the lock ends.</p>
2055
+ <p style="color: #666; font-size: 12px;">This is an automated security notification.</p>
2056
+ </div>
2057
+ </body>
2058
+ </html>`,
2059
+ text: `Your account was temporarily locked
2060
+
2061
+ Hello {{user.username}},
2062
+
2063
+ There were several failed sign-in attempts for your account. To protect it, sign-in is locked for {{lock.minutes}} minutes, until {{lock.until}}.
2064
+
2065
+ If these attempts were not yours, change your password after the lock ends.`
2066
+ },
2067
+ newDevice: {
2068
+ subject: "New sign-in to your account",
2069
+ html: `<html>
2070
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
2071
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
2072
+ <h2>New sign-in to your account</h2>
2073
+ <p>Hello {{user.username}},</p>
2074
+ <p>Your account was just used on a device we have not seen before.</p>
2075
+ <ul>
2076
+ <li>Time: {{session.loginTime}}</li>
2077
+ <li>Device: {{device.browser}} on {{device.os}}</li>
2078
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
2079
+ <li>IP address: {{session.ipAddress}}</li>
2080
+ </ul>
2081
+ <p>If this was you, you can ignore this email.</p>
2082
+ <p>If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
2083
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
2084
+ </div>
2085
+ </body>
2086
+ </html>`,
2087
+ text: `New sign-in to your account
2088
+
2089
+ Hello {{user.username}},
2090
+
2091
+ Your account was just used on a device we have not seen before.
2092
+
2093
+ Time: {{session.loginTime}}
2094
+ Device: {{device.browser}} on {{device.os}}
2095
+ Location: {{geo.city}}, {{geo.country}}
2096
+ IP address: {{session.ipAddress}}
2097
+
2098
+ If this was not you, sign this device out and change your password:
2099
+ {{link.notMe}}
2100
+
2101
+ The link works once and expires after 72 hours.`
2102
+ },
2103
+ impossibleTravel: {
2104
+ subject: "Unusual sign-in to your account",
2105
+ html: `<html>
2106
+ <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
2107
+ <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
2108
+ <h2>Unusual sign-in to your account</h2>
2109
+ <p>Hello {{user.username}},</p>
2110
+ <p>Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.</p>
2111
+ <ul>
2112
+ <li>Time: {{session.loginTime}}</li>
2113
+ <li>Location: {{geo.city}}, {{geo.country}}</li>
2114
+ <li>Device: {{device.browser}} on {{device.os}}</li>
2115
+ </ul>
2116
+ <p>A VPN or a mobile network can cause this. If this was not you, <a href="{{link.notMe}}">sign this device out</a> and change your password.</p>
2117
+ <p style="color: #666; font-size: 12px;">The link works once and expires after 72 hours.</p>
2118
+ </div>
2119
+ </body>
2120
+ </html>`,
2121
+ text: `Unusual sign-in to your account
2122
+
2123
+ Hello {{user.username}},
2124
+
2125
+ Your account was used about {{travel.distanceKm}} km away from your previous sign-in, sooner than anyone could travel that far.
2126
+
2127
+ Time: {{session.loginTime}}
2128
+ Location: {{geo.city}}, {{geo.country}}
2129
+ Device: {{device.browser}} on {{device.os}}
2130
+
2131
+ A VPN or a mobile network can cause this. If this was not you, sign this device out and change your password:
2132
+ {{link.notMe}}
2133
+
2134
+ The link works once and expires after 72 hours.`
1375
2135
  }
1376
2136
  });
1377
2137
  function fillMissingTemplates(templates) {
@@ -1391,6 +2151,156 @@ function fillMissingTemplates(templates) {
1391
2151
  })
1392
2152
  );
1393
2153
  }
2154
+ const SIGNALS_FORM_DEFAULTS = Object.freeze({
2155
+ alertOnNewDevice: false,
2156
+ alertOnImpossibleTravel: false,
2157
+ impossibleTravelEnabled: false,
2158
+ impossibleTravelSpeedKmh: 1e3,
2159
+ impossibleTravelMinDistanceKm: 500,
2160
+ impossibleTravelAction: "alert",
2161
+ webhookEvents: Object.freeze([
2162
+ "login.suspicious",
2163
+ "login.new_location",
2164
+ "login.new_device",
2165
+ "login.impossible_travel",
2166
+ "lockout",
2167
+ "user.not_me"
2168
+ ]),
2169
+ genericWebhookEnabled: false,
2170
+ // Read-only facts from the server: the URL and the secret are write-only.
2171
+ hasGenericWebhook: false,
2172
+ genericWebhookHint: null,
2173
+ hasGenericWebhookSecret: false,
2174
+ sessionIpAnonymize: false
2175
+ });
2176
+ const WEBHOOK_EVENT_OPTIONS = Object.freeze([
2177
+ ["login.success", "settings.webhookEvents.loginSuccess", "Every successful sign-in"],
2178
+ ["login.suspicious", "settings.webhookEvents.loginSuspicious", "Suspicious sign-in"],
2179
+ ["login.new_location", "settings.webhookEvents.loginNewLocation", "Sign-in from a new country"],
2180
+ ["login.new_device", "settings.webhookEvents.loginNewDevice", "Sign-in from a new device"],
2181
+ ["login.impossible_travel", "settings.webhookEvents.impossibleTravel", "Impossible travel"],
2182
+ ["login.failed", "settings.webhookEvents.loginFailed", "Failed sign-in"],
2183
+ ["login.refused", "settings.webhookEvents.loginRefused", "Refused sign-in"],
2184
+ ["lockout", "settings.webhookEvents.lockout", "IP address or account locked"],
2185
+ ["lockout.lifted", "settings.webhookEvents.lockoutLifted", "Lock lifted by an admin"],
2186
+ ["session.limit", "settings.webhookEvents.sessionLimit", "Session limit reached"],
2187
+ [
2188
+ "password.changed",
2189
+ "settings.webhookEvents.passwordChanged",
2190
+ "Sessions ended after a password change"
2191
+ ],
2192
+ ["user.not_me", "settings.webhookEvents.notMe", `"This wasn't me" used`]
2193
+ ]);
2194
+ const SIGNALS_RANGES = Object.freeze({
2195
+ impossibleTravelSpeedKmh: Object.freeze({ min: 100, max: 5e3 }),
2196
+ impossibleTravelMinDistanceKm: Object.freeze({ min: 50, max: 2e4 })
2197
+ });
2198
+ const RETENTION_PRESETS = Object.freeze({
2199
+ minimal: Object.freeze({ retentionDays: 7, securityLogRetentionDays: 30 }),
2200
+ standard: Object.freeze({ retentionDays: 90, securityLogRetentionDays: 90 }),
2201
+ extended: Object.freeze({ retentionDays: 365, securityLogRetentionDays: 365 })
2202
+ });
2203
+ const message$1 = (messageId, defaultMessage, values) => ({ messageId, defaultMessage, values });
2204
+ function currentRetentionPreset(settings) {
2205
+ const match = Object.entries(RETENTION_PRESETS).find(
2206
+ ([, values]) => Number(settings?.retentionDays) === values.retentionDays && Number(settings?.securityLogRetentionDays) === values.securityLogRetentionDays
2207
+ );
2208
+ return match ? match[0] : "custom";
2209
+ }
2210
+ function isWebhookUrl(value) {
2211
+ if (typeof value !== "string" || value.length > 2048) return false;
2212
+ try {
2213
+ const url = new URL(value.trim());
2214
+ const host = url.hostname.toLowerCase();
2215
+ return url.protocol === "https:" && !url.username && !url.password && !!host && host !== "localhost" && !host.endsWith(".localhost") && !host.endsWith(".local");
2216
+ } catch {
2217
+ return false;
2218
+ }
2219
+ }
2220
+ function validateSignalFields(settings) {
2221
+ const source = settings || {};
2222
+ const errors = {};
2223
+ for (const [key, { min, max }] of Object.entries(SIGNALS_RANGES)) {
2224
+ if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
2225
+ const value = source[key];
2226
+ const number = Number(value);
2227
+ if (value === void 0 || value === null || value === "") {
2228
+ errors[key] = message$1("settings.validation.required", "Enter a value.");
2229
+ } else if (!Number.isInteger(number) || number < min || number > max) {
2230
+ errors[key] = message$1(
2231
+ "settings.validation.range",
2232
+ "Enter a whole number from {min} to {max}.",
2233
+ {
2234
+ min,
2235
+ max
2236
+ }
2237
+ );
2238
+ }
2239
+ }
2240
+ if (typeof source.genericWebhookUrl === "string" && source.genericWebhookUrl && !isWebhookUrl(source.genericWebhookUrl)) {
2241
+ errors.genericWebhookUrl = message$1(
2242
+ "settings.validation.webhookUrl",
2243
+ "Enter an https address without a user name or password, for example https://hooks.example.com/sessions."
2244
+ );
2245
+ }
2246
+ if (typeof source.genericWebhookSecret === "string" && source.genericWebhookSecret && !/^[\x21-\x7e]{32,256}$/.test(source.genericWebhookSecret)) {
2247
+ errors.genericWebhookSecret = message$1(
2248
+ "settings.validation.webhookSecret",
2249
+ "Use 32 to 256 characters without spaces, or generate one."
2250
+ );
2251
+ }
2252
+ return errors;
2253
+ }
2254
+ function generateWebhookSecret(cryptoApi = globalThis.crypto) {
2255
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(48));
2256
+ let binary = "";
2257
+ for (const byte of bytes) binary += String.fromCharCode(byte);
2258
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2259
+ }
2260
+ function describeWebhookTest(result) {
2261
+ if (result?.ok) {
2262
+ return {
2263
+ ...message$1("settings.signedWebhook.test.ok", "Delivered. The receiver answered {status}.", {
2264
+ status: result.status
2265
+ }),
2266
+ tone: "success"
2267
+ };
2268
+ }
2269
+ const code = String(result?.code || "network_error");
2270
+ const known = {
2271
+ no_url: ["settings.signedWebhook.test.noUrl", "Save a URL first."],
2272
+ no_secret: ["settings.signedWebhook.test.noSecret", "Save a secret first."],
2273
+ invalid_url: [
2274
+ "settings.signedWebhook.test.invalidUrl",
2275
+ "The saved URL is not a valid https address."
2276
+ ],
2277
+ dns_failed: ["settings.signedWebhook.test.dns", "The host name could not be resolved."],
2278
+ address_not_allowed: [
2279
+ "settings.signedWebhook.test.blocked",
2280
+ "Not sent: the host resolves to a private, local or reserved address."
2281
+ ],
2282
+ timeout: [
2283
+ "settings.signedWebhook.test.timeout",
2284
+ "The receiver did not answer within 5 seconds."
2285
+ ],
2286
+ redirect_not_followed: [
2287
+ "settings.signedWebhook.test.redirect",
2288
+ "The receiver answered with a redirect. Redirects are not followed; use the final URL."
2289
+ ],
2290
+ network_error: ["settings.signedWebhook.test.network", "The connection failed."]
2291
+ };
2292
+ if (known[code]) return { ...message$1(known[code][0], known[code][1]), tone: "danger" };
2293
+ const status = /^http_(\d{3})$/.exec(code);
2294
+ if (status) {
2295
+ return {
2296
+ ...message$1("settings.signedWebhook.test.http", "The receiver answered {status}.", {
2297
+ status: Number(status[1])
2298
+ }),
2299
+ tone: "danger"
2300
+ };
2301
+ }
2302
+ return { ...message$1(known.network_error[0], known.network_error[1]), tone: "danger" };
2303
+ }
1394
2304
  const SETTINGS_DEFAULTS = Object.freeze({
1395
2305
  inactivityTimeout: 15,
1396
2306
  cleanupInterval: 30,
@@ -1428,9 +2338,16 @@ const SETTINGS_DEFAULTS = Object.freeze({
1428
2338
  securityLogStoreIp: true,
1429
2339
  securityLogAnonymizeIp: false,
1430
2340
  securityLogGeoLookup: false,
1431
- securityLogRetentionDays: 90
2341
+ securityLogRetentionDays: 90,
2342
+ ...POLICY_FORM_DEFAULTS,
2343
+ ...SIGNALS_FORM_DEFAULTS
1432
2344
  });
1433
- const WRITE_ONLY_SETTINGS_KEYS = Object.freeze(["discordWebhookUrl", "slackWebhookUrl"]);
2345
+ const WRITE_ONLY_SETTINGS_KEYS = Object.freeze([
2346
+ "discordWebhookUrl",
2347
+ "slackWebhookUrl",
2348
+ "genericWebhookUrl",
2349
+ "genericWebhookSecret"
2350
+ ]);
1434
2351
  const MAX_FAILED_LOGINS_RANGE = Object.freeze({ min: 0, max: 100 });
1435
2352
  const WEBHOOK_HOSTS = Object.freeze({
1436
2353
  discordWebhookUrl: ["discord.com", "discordapp.com"],
@@ -1451,6 +2368,9 @@ function normalizeSettings(loaded) {
1451
2368
  ...loaded,
1452
2369
  allowedCountries: Array.isArray(loaded.allowedCountries) ? loaded.allowedCountries : [],
1453
2370
  blockedCountries: Array.isArray(loaded.blockedCountries) ? loaded.blockedCountries : [],
2371
+ lockoutTrustedAddresses: Array.isArray(loaded.lockoutTrustedAddresses) ? loaded.lockoutTrustedAddresses : [],
2372
+ roleRules: Array.isArray(loaded.roleRules) ? loaded.roleRules : [],
2373
+ webhookEvents: Array.isArray(loaded.webhookEvents) ? loaded.webhookEvents : [...SIGNALS_FORM_DEFAULTS.webhookEvents],
1454
2374
  emailTemplates: fillMissingTemplates(loaded.emailTemplates)
1455
2375
  };
1456
2376
  }
@@ -1500,6 +2420,8 @@ function validateSettings(settings) {
1500
2420
  const source = settings || {};
1501
2421
  const maxFailed = validateMaxFailedLogins(source.maxFailedLogins);
1502
2422
  if (maxFailed) errors.maxFailedLogins = maxFailed;
2423
+ Object.assign(errors, validatePolicyFields(source));
2424
+ Object.assign(errors, validateSignalFields(source));
1503
2425
  if (!isAllowedWebhookUrl(source.discordWebhookUrl, WEBHOOK_HOSTS.discordWebhookUrl)) {
1504
2426
  errors.discordWebhookUrl = message(
1505
2427
  "settings.validation.webhookDiscord",
@@ -1543,6 +2465,453 @@ function getAdjustedFields(submitted, stored, previous) {
1543
2465
  (key) => !WRITE_ONLY_SETTINGS_KEYS.includes(key) && !areSettingsEqual(source[key], stored?.[key]) && (previous === void 0 || !areSettingsEqual(source[key], previous?.[key]))
1544
2466
  );
1545
2467
  }
2468
+ const TABLE_MIN_WIDTH = 640;
2469
+ const keepActionKeys = (event) => {
2470
+ if (shouldIsolateActionKey(event.key, true)) event.stopPropagation();
2471
+ };
2472
+ const LockTarget = ({ lock }) => {
2473
+ const { t } = useSettingsTranslate();
2474
+ if (lock.kind === "ip") {
2475
+ return /* @__PURE__ */ jsx(
2476
+ Typography,
2477
+ {
2478
+ variant: "omega",
2479
+ textColor: "neutral800",
2480
+ tag: "p",
2481
+ style: { overflowWrap: "anywhere" },
2482
+ children: lock.ip || t("settings.lockouts.ipHidden", "IP address not stored")
2483
+ }
2484
+ );
2485
+ }
2486
+ if (!lock.user) {
2487
+ return /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral600", children: t("settings.lockouts.unknownAccount", "Account that does not exist") });
2488
+ }
2489
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 1, minWidth: 0, width: "100%", children: [
2490
+ /* @__PURE__ */ jsx(
2491
+ Typography,
2492
+ {
2493
+ variant: "omega",
2494
+ fontWeight: "semiBold",
2495
+ textColor: "neutral800",
2496
+ tag: "p",
2497
+ style: { overflowWrap: "anywhere" },
2498
+ children: lock.user.username || lock.user.email
2499
+ }
2500
+ ),
2501
+ lock.user.email && lock.user.username ? /* @__PURE__ */ jsx(
2502
+ Typography,
2503
+ {
2504
+ variant: "pi",
2505
+ textColor: "neutral600",
2506
+ tag: "p",
2507
+ style: { overflowWrap: "anywhere" },
2508
+ children: lock.user.email
2509
+ }
2510
+ ) : null
2511
+ ] });
2512
+ };
2513
+ const KindBadge = ({ kind }) => {
2514
+ const { t } = useSettingsTranslate();
2515
+ return /* @__PURE__ */ jsx(Badge, { backgroundColor: "neutral150", textColor: "neutral800", children: kind === "ip" ? t("settings.lockouts.kind.ip", "IP address") : t("settings.lockouts.kind.account", "Account") });
2516
+ };
2517
+ const lockName = (lock, t) => {
2518
+ if (lock.kind === "ip")
2519
+ return lock.ip || t("settings.lockouts.ipHidden", "IP address not stored");
2520
+ if (lock.user) return lock.user.username || lock.user.email;
2521
+ return t("settings.lockouts.unknownAccount", "Account that does not exist");
2522
+ };
2523
+ const LockedNowCard = () => {
2524
+ const { t } = useSettingsTranslate();
2525
+ const { get, post } = useFetchClient();
2526
+ const { toggleNotification } = useNotification();
2527
+ const { formatDate } = useSessionFormatters();
2528
+ const {
2529
+ isLoading: permissionsLoading,
2530
+ allowedActions: { canUnlock }
2531
+ } = useRBAC(pluginPermissions.lockoutsUnlock);
2532
+ const [widthRef, width] = useElementWidth();
2533
+ const [locks, setLocks] = useState(null);
2534
+ const [error, setError] = useState(false);
2535
+ const [refreshing, setRefreshing] = useState(false);
2536
+ const refreshRef = useRef(null);
2537
+ const requestRef = useRef(0);
2538
+ const apply = useCallback(async (request, pending) => {
2539
+ try {
2540
+ const { data } = await pending;
2541
+ if (request !== requestRef.current) return;
2542
+ if (!Array.isArray(data?.data)) throw new Error("Invalid lock list");
2543
+ setLocks(sortLocks(data.data));
2544
+ setError(false);
2545
+ } catch (err) {
2546
+ if (isCancelledRequest(err) || request !== requestRef.current) return;
2547
+ logSafeAdminError("lockouts", err);
2548
+ setError(true);
2549
+ } finally {
2550
+ if (request === requestRef.current) setRefreshing(false);
2551
+ }
2552
+ }, []);
2553
+ const load = useCallback(() => {
2554
+ const request = ++requestRef.current;
2555
+ setRefreshing(true);
2556
+ return apply(request, get(`/${pluginId}/lockouts`));
2557
+ }, [apply, get]);
2558
+ useEffect(() => {
2559
+ apply(++requestRef.current, get(`/${pluginId}/lockouts`));
2560
+ }, [apply, get]);
2561
+ const unlock = async (lock) => {
2562
+ try {
2563
+ await post(`/${pluginId}/lockouts/unlock`, { id: lock.id });
2564
+ toggleNotification({
2565
+ type: "success",
2566
+ message: t("settings.lockouts.unlocked", "{name} was unlocked.", {
2567
+ name: lockName(lock, t)
2568
+ })
2569
+ });
2570
+ } catch (err) {
2571
+ if (err?.response?.status === 404) {
2572
+ toggleNotification({
2573
+ type: "info",
2574
+ message: t("settings.lockouts.alreadyEnded", "This lock had already ended.")
2575
+ });
2576
+ } else {
2577
+ logSafeAdminError("lockouts", err);
2578
+ toggleNotification({
2579
+ type: "danger",
2580
+ message: t("settings.lockouts.unlockFailed", "The lock could not be lifted.")
2581
+ });
2582
+ throw err;
2583
+ }
2584
+ } finally {
2585
+ await load();
2586
+ }
2587
+ };
2588
+ const showActions = !permissionsLoading && canUnlock;
2589
+ const asTable = width === 0 || width >= TABLE_MIN_WIDTH;
2590
+ const unlockAction = (lock) => showActions ? /* @__PURE__ */ jsx(
2591
+ ConfirmAction,
2592
+ {
2593
+ fallbackFocusRef: refreshRef,
2594
+ title: t("settings.lockouts.confirm.title", "Unlock {name}?", { name: lockName(lock, t) }),
2595
+ body: lock.kind === "ip" ? t(
2596
+ "settings.lockouts.confirm.bodyIp",
2597
+ "Sign-ins from this address are allowed again at once, and its failed attempts are reset. This is recorded in the security log."
2598
+ ) : t(
2599
+ "settings.lockouts.confirm.bodyAccount",
2600
+ "Sign-ins to this account are allowed again at once, and its failed attempts are reset. This is recorded in the security log."
2601
+ ),
2602
+ confirmLabel: t("settings.lockouts.confirm.action", "Unlock"),
2603
+ variant: "default",
2604
+ onConfirm: () => unlock(lock),
2605
+ trigger: /* @__PURE__ */ jsx(
2606
+ IconButton,
2607
+ {
2608
+ variant: "ghost",
2609
+ label: t("settings.lockouts.unlockLabel", "Unlock {name}", { name: lockName(lock, t) }),
2610
+ children: /* @__PURE__ */ jsx(Key, {})
2611
+ }
2612
+ )
2613
+ },
2614
+ lock.id
2615
+ ) : null;
2616
+ const ends = (lock) => /* @__PURE__ */ jsx(Typography, { tag: "time", dateTime: lock.until, variant: "omega", textColor: "neutral800", children: formatDate(lock.until, { hour: "2-digit", minute: "2-digit" }) });
2617
+ let content;
2618
+ if (locks === null && !error) {
2619
+ content = /* @__PURE__ */ jsx(Flex, { justifyContent: "center", padding: 6, children: /* @__PURE__ */ jsx(Loader, { small: true, children: t("settings.lockouts.loading", "Loading locks…") }) });
2620
+ } else if (error && locks === null) {
2621
+ content = /* @__PURE__ */ jsx(
2622
+ PersistentAlert,
2623
+ {
2624
+ variant: "danger",
2625
+ closeLabel: t("common.close", "Close"),
2626
+ title: t("settings.lockouts.error", "Locks could not be loaded."),
2627
+ action: /* @__PURE__ */ jsx(Button, { variant: "tertiary", onClick: load, children: t("common.tryAgain", "Try again") }),
2628
+ children: t("settings.lockouts.errorBody", "Sign-ins are still checked; only this list is missing.")
2629
+ }
2630
+ );
2631
+ } else if (locks.length === 0) {
2632
+ content = /* @__PURE__ */ jsx(
2633
+ EmptyStateLayout,
2634
+ {
2635
+ icon: /* @__PURE__ */ jsx(EmptyPermissions, { width: "16rem", height: "8rem" }),
2636
+ content: t(
2637
+ "settings.lockouts.empty",
2638
+ "Nothing is locked. Locked IP addresses and accounts appear here until their lock ends."
2639
+ )
2640
+ }
2641
+ );
2642
+ } else if (asTable) {
2643
+ content = /* @__PURE__ */ jsx(Box, { hasRadius: true, borderColor: "neutral150", "data-locks-table": "", children: /* @__PURE__ */ jsxs(Table, { colCount: showActions ? 5 : 4, rowCount: locks.length + 1, "aria-busy": refreshing, children: [
2644
+ /* @__PURE__ */ jsx(Thead, { children: /* @__PURE__ */ jsxs(Tr, { children: [
2645
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.lockouts.col.locked", "Locked") }) }),
2646
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.lockouts.col.kind", "Type") }) }),
2647
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.lockouts.col.failures", "Failed sign-ins") }) }),
2648
+ /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: t("settings.lockouts.col.until", "Locked until") }) }),
2649
+ showActions ? /* @__PURE__ */ jsx(Th, { children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("settings.lockouts.col.actions", "Actions") }) }) : null
2650
+ ] }) }),
2651
+ /* @__PURE__ */ jsx(Tbody, { children: locks.map((lock) => /* @__PURE__ */ jsxs(Tr, { "data-lock-row": lock.kind, children: [
2652
+ /* @__PURE__ */ jsx(Td, { style: { maxWidth: 0, width: "40%" }, children: /* @__PURE__ */ jsx(LockTarget, { lock }) }),
2653
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(KindBadge, { kind: lock.kind }) }),
2654
+ /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: lock.failures }) }),
2655
+ /* @__PURE__ */ jsx(Td, { children: ends(lock) }),
2656
+ showActions ? /* @__PURE__ */ jsx(Td, { children: /* @__PURE__ */ jsx(RowActions, { onKeyDown: keepActionKeys, children: unlockAction(lock) }) }) : null
2657
+ ] }, lock.id)) })
2658
+ ] }) });
2659
+ } else {
2660
+ content = /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 2, tag: "ul", "data-locks-list": "", children: locks.map((lock) => /* @__PURE__ */ jsx(
2661
+ Box,
2662
+ {
2663
+ tag: "li",
2664
+ padding: 4,
2665
+ hasRadius: true,
2666
+ borderColor: "neutral150",
2667
+ "data-lock-row": lock.kind,
2668
+ children: /* @__PURE__ */ jsxs(Flex, { justifyContent: "space-between", alignItems: "flex-start", gap: 3, children: [
2669
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 2, minWidth: 0, children: [
2670
+ /* @__PURE__ */ jsx(LockTarget, { lock }),
2671
+ /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
2672
+ /* @__PURE__ */ jsx(KindBadge, { kind: lock.kind }),
2673
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t("settings.lockouts.summary", "{count} failed, until {time}", {
2674
+ count: lock.failures,
2675
+ time: formatDate(lock.until, { hour: "2-digit", minute: "2-digit" })
2676
+ }) })
2677
+ ] })
2678
+ ] }),
2679
+ /* @__PURE__ */ jsx(RowActions, { onKeyDown: keepActionKeys, children: unlockAction(lock) })
2680
+ ] })
2681
+ },
2682
+ lock.id
2683
+ )) });
2684
+ }
2685
+ return /* @__PURE__ */ jsx(
2686
+ SectionCard,
2687
+ {
2688
+ id: "locked-now",
2689
+ title: t("settings.lockouts.title", "Locked now"),
2690
+ subtitle: t(
2691
+ "settings.lockouts.intro",
2692
+ "IP addresses and accounts that are refused right now after failed sign-ins."
2693
+ ),
2694
+ action: /* @__PURE__ */ jsx(
2695
+ Button,
2696
+ {
2697
+ ref: refreshRef,
2698
+ variant: "tertiary",
2699
+ startIcon: /* @__PURE__ */ jsx(ArrowClockwise, {}),
2700
+ onClick: load,
2701
+ loading: refreshing && locks !== null,
2702
+ children: t("settings.lockouts.refresh", "Refresh")
2703
+ }
2704
+ ),
2705
+ children: /* @__PURE__ */ jsxs("div", { ref: widthRef, "aria-live": "polite", children: [
2706
+ error && locks !== null ? /* @__PURE__ */ jsx(Box, { paddingBottom: 3, children: /* @__PURE__ */ jsx(
2707
+ PersistentAlert,
2708
+ {
2709
+ variant: "warning",
2710
+ closeLabel: t("common.close", "Close"),
2711
+ title: t("settings.lockouts.refreshErrorTitle", "Not refreshed"),
2712
+ children: t(
2713
+ "settings.lockouts.refreshError",
2714
+ "The list could not be refreshed. It shows the last known locks."
2715
+ )
2716
+ }
2717
+ ) }) : null,
2718
+ content,
2719
+ locks && locks.length > 0 && !showActions && !permissionsLoading ? /* @__PURE__ */ jsx(Box, { paddingTop: 3, children: /* @__PURE__ */ jsxs(Flex, { gap: 2, alignItems: "center", children: [
2720
+ /* @__PURE__ */ jsx(Lock, { "aria-hidden": true, fill: "neutral600" }),
2721
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(
2722
+ "settings.lockouts.noUnlock",
2723
+ 'Unlocking needs the "Unlock locked sign-ins" permission.'
2724
+ ) })
2725
+ ] }) }) : null,
2726
+ /* @__PURE__ */ jsx(VisuallyHidden, { children: locks ? t(
2727
+ "settings.lockouts.count",
2728
+ "{count, plural, =0 {No locks} one {# lock} other {# locks}}",
2729
+ {
2730
+ count: locks.length
2731
+ }
2732
+ ) : null })
2733
+ ] })
2734
+ }
2735
+ );
2736
+ };
2737
+ const TrustedAddressesField = ({ form, disabled = false }) => {
2738
+ const { t, tError } = useSettingsTranslate();
2739
+ const { settings, handleChange, errors, draftVersion } = form;
2740
+ const [text, setText] = useState(
2741
+ () => formatTrustedAddressText(settings.lockoutTrustedAddresses)
2742
+ );
2743
+ const [version, setVersion] = useState(draftVersion);
2744
+ if (version !== draftVersion) {
2745
+ setVersion(draftVersion);
2746
+ setText(formatTrustedAddressText(settings.lockoutTrustedAddresses));
2747
+ }
2748
+ return /* @__PURE__ */ jsx(
2749
+ FormField,
2750
+ {
2751
+ id: "lockout-trusted-addresses",
2752
+ name: "lockoutTrustedAddresses",
2753
+ label: t("settings.config.failed.trusted.label", "Trusted addresses"),
2754
+ description: t(
2755
+ "settings.config.failed.trusted.hint",
2756
+ "One IP address or CIDR range per line, for example 192.0.2.10 or 192.0.2.0/24. These addresses are never locked by IP; accounts can still be locked. Use it for an office network or a server that signs in for many users."
2757
+ ),
2758
+ error: tError(errors.lockoutTrustedAddresses),
2759
+ children: /* @__PURE__ */ jsx(
2760
+ Textarea,
2761
+ {
2762
+ value: text,
2763
+ placeholder: "192.0.2.0/24",
2764
+ disabled,
2765
+ onChange: (event) => {
2766
+ setText(event.target.value);
2767
+ handleChange("lockoutTrustedAddresses", parseTrustedAddressText(event.target.value));
2768
+ }
2769
+ }
2770
+ )
2771
+ }
2772
+ );
2773
+ };
2774
+ const ImpossibleTravelCard = ({ form }) => {
2775
+ const { t, tError } = useSettingsTranslate();
2776
+ const { settings, handleChange, errors } = form;
2777
+ const lookupOff = !settings.enableGeolocation;
2778
+ const enabled = settings.impossibleTravelEnabled === true;
2779
+ const locked = form.canChangeProtected === false;
2780
+ return /* @__PURE__ */ jsxs(
2781
+ SectionCard,
2782
+ {
2783
+ id: "impossible-travel",
2784
+ title: t("settings.config.travel.title", "Impossible travel"),
2785
+ subtitle: t(
2786
+ "settings.config.travel.intro",
2787
+ "Flags a sign-in that is farther from the user's previous sign-in than anyone could travel in the time between."
2788
+ ),
2789
+ children: [
2790
+ lookupOff ? /* @__PURE__ */ jsx(RequiresGeolocation, {}) : null,
2791
+ locked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null,
2792
+ /* @__PURE__ */ jsx(
2793
+ SettingsToggleRow,
2794
+ {
2795
+ id: "impossible-travel-enabled",
2796
+ title: t("settings.config.travel.enable.label", "Detect impossible travel"),
2797
+ description: t(
2798
+ "settings.config.travel.enable.hint",
2799
+ "Needs a location database with cities (coordinates). While this is on, the location of each sign-in is stored rounded to about 11 km. VPNs and mobile networks can cause false alarms."
2800
+ ),
2801
+ checked: enabled,
2802
+ disabled: locked || lookupOff && !enabled,
2803
+ onChange: (checked) => handleChange("impossibleTravelEnabled", checked)
2804
+ }
2805
+ ),
2806
+ enabled ? /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, "data-travel-action": "", children: [
2807
+ /* @__PURE__ */ jsx(
2808
+ Typography,
2809
+ {
2810
+ id: "impossible-travel-action-label",
2811
+ variant: "pi",
2812
+ fontWeight: "bold",
2813
+ tag: "div",
2814
+ textColor: "neutral800",
2815
+ children: t("settings.config.travel.action.label", "Then")
2816
+ }
2817
+ ),
2818
+ /* @__PURE__ */ jsxs(
2819
+ Radio.Group,
2820
+ {
2821
+ "aria-labelledby": "impossible-travel-action-label",
2822
+ value: settings.impossibleTravelAction || "alert",
2823
+ disabled: locked,
2824
+ onValueChange: (value) => handleChange("impossibleTravelAction", value),
2825
+ children: [
2826
+ /* @__PURE__ */ jsx(Radio.Item, { value: "alert", children: t("settings.config.travel.action.alert", "Record it and alert") }),
2827
+ /* @__PURE__ */ jsx(Radio.Item, { value: "reauthenticate", children: t("settings.config.travel.action.reauthenticate", "Require a new sign-in") })
2828
+ ]
2829
+ }
2830
+ ),
2831
+ settings.impossibleTravelAction === "reauthenticate" ? /* @__PURE__ */ jsx(
2832
+ Alert,
2833
+ {
2834
+ variant: "warning",
2835
+ closeLabel: t("common.close", "Close"),
2836
+ title: t("settings.config.travel.reauth.title", "Every session of the user ends"),
2837
+ children: t(
2838
+ "settings.config.travel.reauth.body",
2839
+ "The flagged sign-in gets 401 with the code REAUTHENTICATION_REQUIRED and all sessions of the user end. Signing in again from the new place works."
2840
+ )
2841
+ }
2842
+ ) : null,
2843
+ /* @__PURE__ */ jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t(
2844
+ "settings.config.travel.alerts",
2845
+ "The email to the user and the webhook event are chosen under Alerts."
2846
+ ) })
2847
+ ] }) : null,
2848
+ /* @__PURE__ */ jsx(
2849
+ AdvancedSection,
2850
+ {
2851
+ hasError: fieldHasError(errors, "impossibleTravelSpeedKmh") || fieldHasError(errors, "impossibleTravelMinDistanceKm"),
2852
+ disabled: !enabled,
2853
+ children: /* @__PURE__ */ jsxs(EqualGrid, { columns: 2, stackBelow: "medium", gap: 6, children: [
2854
+ /* @__PURE__ */ jsx(
2855
+ FormField,
2856
+ {
2857
+ id: "impossible-travel-speed",
2858
+ name: "impossibleTravelSpeedKmh",
2859
+ label: t("settings.config.travel.speed.label", "Faster than"),
2860
+ description: t(
2861
+ "settings.config.travel.speed.hint",
2862
+ "From 100 to 5000. A plane flies at about 900 km/h."
2863
+ ),
2864
+ suffix: t("settings.config.travel.speed.suffix", "km/h"),
2865
+ error: tError(errors.impossibleTravelSpeedKmh),
2866
+ required: true,
2867
+ children: /* @__PURE__ */ jsx(
2868
+ NumberInput,
2869
+ {
2870
+ value: settings.impossibleTravelSpeedKmh,
2871
+ disabled: locked,
2872
+ onValueChange: (value) => handleChange("impossibleTravelSpeedKmh", value ?? ""),
2873
+ min: SIGNALS_RANGES.impossibleTravelSpeedKmh.min,
2874
+ max: SIGNALS_RANGES.impossibleTravelSpeedKmh.max,
2875
+ step: 50
2876
+ },
2877
+ form.draftVersion
2878
+ )
2879
+ }
2880
+ ),
2881
+ /* @__PURE__ */ jsx(
2882
+ FormField,
2883
+ {
2884
+ id: "impossible-travel-distance",
2885
+ name: "impossibleTravelMinDistanceKm",
2886
+ label: t("settings.config.travel.distance.label", "Over at least"),
2887
+ description: t(
2888
+ "settings.config.travel.distance.hint",
2889
+ "Shorter distances are never flagged (location data is not precise)."
2890
+ ),
2891
+ suffix: t("settings.config.travel.distance.suffix", "km"),
2892
+ error: tError(errors.impossibleTravelMinDistanceKm),
2893
+ required: true,
2894
+ children: /* @__PURE__ */ jsx(
2895
+ NumberInput,
2896
+ {
2897
+ value: settings.impossibleTravelMinDistanceKm,
2898
+ disabled: locked,
2899
+ onValueChange: (value) => handleChange("impossibleTravelMinDistanceKm", value ?? ""),
2900
+ min: SIGNALS_RANGES.impossibleTravelMinDistanceKm.min,
2901
+ max: SIGNALS_RANGES.impossibleTravelMinDistanceKm.max,
2902
+ step: 50
2903
+ },
2904
+ form.draftVersion
2905
+ )
2906
+ }
2907
+ )
2908
+ ] })
2909
+ }
2910
+ )
2911
+ ]
2912
+ }
2913
+ );
2914
+ };
1546
2915
  const COUNTRIES = [
1547
2916
  { code: "DE", name: "Germany", flag: "🇩🇪" },
1548
2917
  { code: "AT", name: "Austria", flag: "🇦🇹" },
@@ -1938,20 +3307,59 @@ const CountryListEditor = ({ settings, handleChange }) => {
1938
3307
  ] })
1939
3308
  ] });
1940
3309
  };
3310
+ const describeLockout = (t, { ip, account, window: window2, duration }) => {
3311
+ if (ip === 0 && account === 0) {
3312
+ return t(
3313
+ "settings.config.failed.lockout.offBoth",
3314
+ "The lockout is off. Failed sign-ins are not limited."
3315
+ );
3316
+ }
3317
+ const parts = [];
3318
+ if (ip > 0) {
3319
+ parts.push(
3320
+ t(
3321
+ "settings.config.failed.preview.ip",
3322
+ "{count, plural, one {# failed sign-in} other {# failed sign-ins}} from one IP address within {window, plural, one {# minute} other {# minutes}} lock that address for {duration, plural, one {# minute} other {# minutes}}.",
3323
+ { count: ip, window: window2, duration }
3324
+ )
3325
+ );
3326
+ }
3327
+ if (account > 0) {
3328
+ parts.push(
3329
+ t(
3330
+ "settings.config.failed.preview.account",
3331
+ "{count, plural, one {# failed sign-in} other {# failed sign-ins}} for one account within {window, plural, one {# minute} other {# minutes}} lock that account for {duration, plural, one {# minute} other {# minutes}}, from every address.",
3332
+ { count: account, window: window2, duration }
3333
+ )
3334
+ );
3335
+ }
3336
+ return parts.join(" ");
3337
+ };
1941
3338
  const LoginProtectionTab = ({ form }) => {
1942
3339
  const { t, tError } = useSettingsTranslate();
1943
3340
  const { settings, handleChange, errors } = form;
1944
3341
  const maxFailedError = tError(errors.maxFailedLogins);
1945
3342
  const maxFailedValue = Number(settings.maxFailedLogins);
3343
+ const accountValue = Number(settings.maxFailedLoginsPerAccount) || 0;
3344
+ const accountByRole = (settings.roleRules || []).some(
3345
+ (rule) => rule.maxFailedLoginsPerAccount !== null && rule.maxFailedLoginsPerAccount !== void 0
3346
+ );
3347
+ const lockoutPreview = describeLockout(t, {
3348
+ ip: maxFailedValue,
3349
+ account: accountValue,
3350
+ window: Number(settings.lockoutWindowMinutes) || 15,
3351
+ duration: Number(settings.lockoutDurationMinutes) || 15
3352
+ });
1946
3353
  const lookupOff = !settings.enableGeolocation;
1947
3354
  const locked = form.canChangeProtected === false;
3355
+ const policyLocked = locked;
1948
3356
  const risk = getRiskAvailability(form.geoIp.status);
1949
3357
  const reject = riskDependentControl(settings.blockSuspiciousSessions, risk.state);
1950
3358
  const autoStillRejects = reject.savedOnButInactive && (settings.geoLookupFailureMode || "auto") === "auto";
1951
3359
  return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
1952
3360
  /* @__PURE__ */ jsx(IntroText, { children: t(
1953
3361
  "settings.config.loginProtection.intro",
1954
- "These rules check new sign-ins before they succeed. Existing sessions are not affected, and refused sign-ins are not recorded."
3362
+ "These rules check new sign-ins before they succeed. Existing sessions are not affected. Failed and refused sign-ins are recorded in the security log while recording is on."
1955
3363
  ) }),
1956
3364
  /* @__PURE__ */ jsxs(
1957
3365
  SectionCard,
@@ -1959,63 +3367,180 @@ const LoginProtectionTab = ({ form }) => {
1959
3367
  title: t("settings.config.failed.title", "Failed sign-ins"),
1960
3368
  subtitle: t(
1961
3369
  "settings.config.failed.intro",
1962
- "Slows down password guessing from one IP address."
3370
+ "Slows down password guessing. Counts are shared by every server process."
1963
3371
  ),
1964
3372
  children: [
1965
- /* @__PURE__ */ jsx(EqualGrid, { columns: 2, stackBelow: "medium", gap: 6, children: /* @__PURE__ */ jsx(
1966
- FormField,
1967
- {
1968
- id: "max-failed-logins",
1969
- name: "maxFailedLogins",
1970
- label: t("settings.config.failed.lockout.label", "Temporary IP lockout after"),
1971
- description: t(
1972
- "settings.config.failed.lockout.hint",
1973
- "A whole number from 0 to 100. 0 turns the lockout off."
1974
- ),
1975
- suffix: t("settings.config.failed.lockout.suffix", "failed sign-ins"),
1976
- error: maxFailedError,
1977
- required: true,
1978
- children: /* @__PURE__ */ jsx(
1979
- NumberInput,
1980
- {
1981
- value: settings.maxFailedLogins,
1982
- onValueChange: (value) => handleChange("maxFailedLogins", value),
1983
- min: MAX_FAILED_LOGINS_RANGE.min,
1984
- max: MAX_FAILED_LOGINS_RANGE.max,
1985
- step: 1
1986
- },
1987
- form.draftVersion
1988
- )
1989
- }
1990
- ) }),
1991
- !maxFailedError ? /* @__PURE__ */ jsx(
3373
+ policyLocked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null,
3374
+ /* @__PURE__ */ jsxs(EqualGrid, { columns: 2, stackBelow: "medium", gap: 6, children: [
3375
+ /* @__PURE__ */ jsx(
3376
+ FormField,
3377
+ {
3378
+ id: "max-failed-logins",
3379
+ name: "maxFailedLogins",
3380
+ label: t("settings.config.failed.lockout.label", "Lock an IP address after"),
3381
+ description: t(
3382
+ "settings.config.failed.lockout.hint",
3383
+ "A whole number from 0 to 100. 0 turns the IP lockout off."
3384
+ ),
3385
+ suffix: t("settings.config.failed.lockout.suffix", "failed sign-ins"),
3386
+ error: maxFailedError,
3387
+ required: true,
3388
+ children: /* @__PURE__ */ jsx(
3389
+ NumberInput,
3390
+ {
3391
+ value: settings.maxFailedLogins,
3392
+ onValueChange: (value) => handleChange("maxFailedLogins", value),
3393
+ min: MAX_FAILED_LOGINS_RANGE.min,
3394
+ max: MAX_FAILED_LOGINS_RANGE.max,
3395
+ step: 1
3396
+ },
3397
+ form.draftVersion
3398
+ )
3399
+ }
3400
+ ),
3401
+ /* @__PURE__ */ jsx(
3402
+ FormField,
3403
+ {
3404
+ id: "max-failed-logins-account",
3405
+ name: "maxFailedLoginsPerAccount",
3406
+ label: t("settings.config.failed.account.label", "Lock an account after"),
3407
+ description: t(
3408
+ "settings.config.failed.account.hint",
3409
+ "Counts failed sign-ins for one account from any address. 0 turns it off. Anyone who knows an account name can lock it, so keep this higher than the IP limit."
3410
+ ),
3411
+ suffix: t("settings.config.failed.lockout.suffix", "failed sign-ins"),
3412
+ error: tError(errors.maxFailedLoginsPerAccount),
3413
+ required: true,
3414
+ children: /* @__PURE__ */ jsx(
3415
+ NumberInput,
3416
+ {
3417
+ value: settings.maxFailedLoginsPerAccount,
3418
+ onValueChange: (value) => handleChange("maxFailedLoginsPerAccount", value ?? ""),
3419
+ disabled: policyLocked,
3420
+ min: POLICY_RANGES.maxFailedLoginsPerAccount.min,
3421
+ max: POLICY_RANGES.maxFailedLoginsPerAccount.max,
3422
+ step: 1
3423
+ },
3424
+ form.draftVersion
3425
+ )
3426
+ }
3427
+ ),
3428
+ /* @__PURE__ */ jsx(
3429
+ FormField,
3430
+ {
3431
+ id: "lockout-window",
3432
+ name: "lockoutWindowMinutes",
3433
+ label: t("settings.config.failed.window.label", "Count failed sign-ins within"),
3434
+ description: t(
3435
+ "settings.config.failed.window.hint",
3436
+ "Failures older than this no longer count."
3437
+ ),
3438
+ suffix: t("settings.config.failed.minutes.suffix", "minutes"),
3439
+ error: tError(errors.lockoutWindowMinutes),
3440
+ required: true,
3441
+ children: /* @__PURE__ */ jsx(
3442
+ NumberInput,
3443
+ {
3444
+ value: settings.lockoutWindowMinutes,
3445
+ onValueChange: (value) => handleChange("lockoutWindowMinutes", value ?? ""),
3446
+ disabled: policyLocked,
3447
+ min: POLICY_RANGES.lockoutWindowMinutes.min,
3448
+ max: POLICY_RANGES.lockoutWindowMinutes.max,
3449
+ step: 1
3450
+ },
3451
+ form.draftVersion
3452
+ )
3453
+ }
3454
+ ),
3455
+ /* @__PURE__ */ jsx(
3456
+ FormField,
3457
+ {
3458
+ id: "lockout-duration",
3459
+ name: "lockoutDurationMinutes",
3460
+ label: t("settings.config.failed.duration.label", "Lock for"),
3461
+ description: t(
3462
+ "settings.config.failed.duration.hint",
3463
+ "A locked IP address or account is refused for this long. Admins can unlock it earlier."
3464
+ ),
3465
+ suffix: t("settings.config.failed.minutes.suffix", "minutes"),
3466
+ error: tError(errors.lockoutDurationMinutes),
3467
+ required: true,
3468
+ children: /* @__PURE__ */ jsx(
3469
+ NumberInput,
3470
+ {
3471
+ value: settings.lockoutDurationMinutes,
3472
+ onValueChange: (value) => handleChange("lockoutDurationMinutes", value ?? ""),
3473
+ disabled: policyLocked,
3474
+ min: POLICY_RANGES.lockoutDurationMinutes.min,
3475
+ max: POLICY_RANGES.lockoutDurationMinutes.max,
3476
+ step: 1
3477
+ },
3478
+ form.draftVersion
3479
+ )
3480
+ }
3481
+ )
3482
+ ] }),
3483
+ !maxFailedError && !errors.maxFailedLoginsPerAccount ? /* @__PURE__ */ jsx(
1992
3484
  Box,
1993
3485
  {
1994
3486
  padding: 3,
1995
- background: maxFailedValue === 0 ? "warning100" : "neutral100",
3487
+ background: maxFailedValue === 0 && accountValue === 0 ? "warning100" : "neutral100",
1996
3488
  hasRadius: true,
1997
3489
  "aria-live": "polite",
1998
3490
  children: /* @__PURE__ */ jsx(
1999
3491
  ReadableParagraphs,
2000
3492
  {
2001
3493
  variant: "pi",
2002
- textColor: maxFailedValue === 0 ? "warning700" : "neutral700",
3494
+ textColor: maxFailedValue === 0 && accountValue === 0 ? "warning700" : "neutral700",
2003
3495
  tag: "p",
2004
- text: maxFailedValue === 0 ? t(
2005
- "settings.config.failed.lockout.off",
2006
- "The temporary IP lockout is off. Failed sign-ins are not limited."
2007
- ) : t(
2008
- "settings.config.failed.lockout.preview",
2009
- "After {count, plural, one {# failed sign-in} other {# failed sign-ins}} from one IP address within 15 minutes, that address is refused for 15 minutes. User accounts are not blocked. Counted per server process.",
2010
- { count: maxFailedValue }
2011
- )
3496
+ text: lockoutPreview
2012
3497
  }
2013
3498
  )
2014
3499
  }
2015
- ) : null
3500
+ ) : null,
3501
+ /* @__PURE__ */ jsx(
3502
+ SettingsToggleRow,
3503
+ {
3504
+ id: "lockout-notify-user",
3505
+ title: t(
3506
+ "settings.config.failed.notify.label",
3507
+ "Email the user when their account is locked"
3508
+ ),
3509
+ description: t(
3510
+ "settings.config.failed.notify.hint",
3511
+ "Sent through Strapi's email plugin (and Magic Mail when installed). The text is in Alerts, Email templates."
3512
+ ),
3513
+ checked: !!settings.lockoutNotifyUser,
3514
+ disabled: policyLocked || accountValue === 0 && !accountByRole,
3515
+ onChange: (checked) => handleChange("lockoutNotifyUser", checked)
3516
+ }
3517
+ ),
3518
+ /* @__PURE__ */ jsx(
3519
+ SettingsToggleRow,
3520
+ {
3521
+ id: "record-user-sign-in-events",
3522
+ title: t("settings.config.failed.record.label", "Record failed and refused sign-ins"),
3523
+ description: t(
3524
+ "settings.config.failed.record.hint",
3525
+ "Writes failed sign-ins, refused sign-ins and locks to the security log, with the IP address as the log stores it."
3526
+ ),
3527
+ checked: settings.recordUserSignInEvents !== false,
3528
+ disabled: policyLocked,
3529
+ onChange: (checked) => handleChange("recordUserSignInEvents", checked)
3530
+ }
3531
+ ),
3532
+ /* @__PURE__ */ jsx(
3533
+ AdvancedSection,
3534
+ {
3535
+ label: t("settings.config.failed.trusted.section", "Trusted addresses"),
3536
+ hasError: fieldHasError(errors, "lockoutTrustedAddresses"),
3537
+ children: /* @__PURE__ */ jsx(TrustedAddressesField, { form, disabled: policyLocked })
3538
+ }
3539
+ )
2016
3540
  ]
2017
3541
  }
2018
3542
  ),
3543
+ /* @__PURE__ */ jsx(LockedNowCard, {}),
2019
3544
  /* @__PURE__ */ jsx(
2020
3545
  SectionCard,
2021
3546
  {
@@ -2116,6 +3641,7 @@ const LoginProtectionTab = ({ form }) => {
2116
3641
  ]
2117
3642
  }
2118
3643
  ),
3644
+ /* @__PURE__ */ jsx(ImpossibleTravelCard, { form }),
2119
3645
  /* @__PURE__ */ jsxs(
2120
3646
  SectionCard,
2121
3647
  {
@@ -2149,7 +3675,18 @@ const LoginProtectionTab = ({ form }) => {
2149
3675
  {
2150
3676
  id: "lockout",
2151
3677
  term: t("settings.config.refused.lockout.response", "429 with Retry-After"),
2152
- description: t("settings.config.refused.lockout.cause", "Temporary IP lockout")
3678
+ description: t(
3679
+ "settings.config.refused.lockout.cause",
3680
+ "Locked IP address or account after failed sign-ins"
3681
+ )
3682
+ },
3683
+ {
3684
+ id: "limit",
3685
+ term: t("settings.config.refused.limit.response", "403 SESSION_LIMIT_REACHED"),
3686
+ description: t(
3687
+ "settings.config.refused.limit.cause",
3688
+ 'Session limit reached with "Refuse the new sign-in"'
3689
+ )
2153
3690
  },
2154
3691
  {
2155
3692
  id: "rule",
@@ -2173,7 +3710,10 @@ const LoginProtectionTab = ({ form }) => {
2173
3710
  ]
2174
3711
  }
2175
3712
  ),
2176
- /* @__PURE__ */ jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t("settings.config.refused.noLog", "Session Manager keeps no log of refused sign-ins.") })
3713
+ /* @__PURE__ */ jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t(
3714
+ "settings.config.refused.log",
3715
+ 'Refused sign-ins are written to the security log while "Record failed and refused sign-ins" is on.'
3716
+ ) })
2177
3717
  ] })
2178
3718
  ] });
2179
3719
  };
@@ -2725,7 +4265,10 @@ const PreviewFrame = styled.iframe`
2725
4265
  const TEMPLATE_TAB_LABELS = {
2726
4266
  suspiciousLogin: ["settings.email.templates.tab.suspicious", "Suspicious sign-in"],
2727
4267
  newLocation: ["settings.email.templates.tab.newLocation", "New country"],
2728
- vpnProxy: ["settings.email.templates.tab.vpnProxy", "VPN or proxy"]
4268
+ vpnProxy: ["settings.email.templates.tab.vpnProxy", "VPN or proxy"],
4269
+ accountLocked: ["settings.email.templates.tab.accountLocked", "Account locked"],
4270
+ newDevice: ["settings.email.templates.tab.newDevice", "New device"],
4271
+ impossibleTravel: ["settings.email.templates.tab.impossibleTravel", "Impossible travel"]
2729
4272
  };
2730
4273
  const BlockLabel = ({ children }) => /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "bold", tag: "div", textColor: "neutral800", children });
2731
4274
  const TemplateEditor = ({ templateKey, template, templates, handleChange, copyValue, errors }) => {
@@ -3073,6 +4616,299 @@ const WebhookUrlField = ({
3073
4616
  stored ? /* @__PURE__ */ jsx(Flex, { gap: 2, wrap: "wrap", children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", size: "S", onClick: cancel, children: t("settings.webhooks.cancelReplace", "Keep the saved URL") }) }) : null
3074
4617
  ] }) });
3075
4618
  };
4619
+ const WriteOnlyField = ({
4620
+ field,
4621
+ saved,
4622
+ form,
4623
+ label,
4624
+ hint,
4625
+ type,
4626
+ placeholder,
4627
+ savedHint = null,
4628
+ disabled = false,
4629
+ extra
4630
+ }) => {
4631
+ const { t, tError } = useSettingsTranslate();
4632
+ const { settings, handleChange, errors } = form;
4633
+ const draft = settings[field];
4634
+ const [editing, setEditing] = useState(false);
4635
+ const removing = draft === "";
4636
+ const showInput = editing || !saved || typeof draft === "string" && draft !== "";
4637
+ if (!showInput) {
4638
+ return /* @__PURE__ */ jsx(FormField, { id: `generic-${field}`, name: field, label, description: hint, children: /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", alignItems: "center", children: [
4639
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: removing ? "danger600" : "neutral800", children: removing ? t("settings.signedWebhook.removed", "Removed when you save.") : t("settings.signedWebhook.saved", "Saved. It is never shown again.") }),
4640
+ savedHint && !removing ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: savedHint }) : null,
4641
+ !removing ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
4642
+ /* @__PURE__ */ jsx(
4643
+ Button,
4644
+ {
4645
+ variant: "tertiary",
4646
+ startIcon: /* @__PURE__ */ jsx(Pencil, {}),
4647
+ disabled,
4648
+ onClick: () => setEditing(true),
4649
+ children: t("settings.signedWebhook.replace", "Replace")
4650
+ }
4651
+ ),
4652
+ /* @__PURE__ */ jsx(
4653
+ Button,
4654
+ {
4655
+ variant: "danger-light",
4656
+ startIcon: /* @__PURE__ */ jsx(Trash, {}),
4657
+ disabled,
4658
+ onClick: () => handleChange(field, ""),
4659
+ children: t("settings.signedWebhook.remove", "Remove")
4660
+ }
4661
+ )
4662
+ ] }) : /* @__PURE__ */ jsx(
4663
+ Button,
4664
+ {
4665
+ variant: "tertiary",
4666
+ disabled,
4667
+ onClick: () => handleChange(field, void 0),
4668
+ children: t("settings.signedWebhook.keep", "Keep it")
4669
+ }
4670
+ )
4671
+ ] }) });
4672
+ }
4673
+ return /* @__PURE__ */ jsx(
4674
+ FormField,
4675
+ {
4676
+ id: `generic-${field}`,
4677
+ name: field,
4678
+ label,
4679
+ description: hint,
4680
+ error: tError(errors[field]),
4681
+ children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
4682
+ /* @__PURE__ */ jsx(
4683
+ TextInput,
4684
+ {
4685
+ type,
4686
+ value: typeof draft === "string" ? draft : "",
4687
+ placeholder,
4688
+ disabled,
4689
+ autoComplete: "off",
4690
+ spellCheck: false,
4691
+ onChange: (event) => handleChange(field, event.target.value || void 0)
4692
+ }
4693
+ ),
4694
+ extra || saved ? /* @__PURE__ */ jsxs(Flex, { gap: 2, wrap: "wrap", children: [
4695
+ extra,
4696
+ saved ? /* @__PURE__ */ jsx(
4697
+ Button,
4698
+ {
4699
+ variant: "tertiary",
4700
+ onClick: () => {
4701
+ handleChange(field, void 0);
4702
+ setEditing(false);
4703
+ },
4704
+ children: t("settings.signedWebhook.keepSaved", "Keep the saved value")
4705
+ }
4706
+ ) : null
4707
+ ] }) : null
4708
+ ] })
4709
+ }
4710
+ );
4711
+ };
4712
+ const SignedWebhookCard = ({ form }) => {
4713
+ const { t } = useSettingsTranslate();
4714
+ const { post } = useFetchClient();
4715
+ const { settings, handleChange } = form;
4716
+ const [testing, setTesting] = useState(false);
4717
+ const [result, setResult] = useState(null);
4718
+ const locked = form.canChangeProtected === false;
4719
+ const pendingWriteOnly = settings.genericWebhookUrl !== void 0 || settings.genericWebhookSecret !== void 0;
4720
+ const sendTest = async () => {
4721
+ setTesting(true);
4722
+ setResult(null);
4723
+ try {
4724
+ const { data } = await post(`/${pluginId}/webhook/test`, {});
4725
+ setResult(describeWebhookTest(data?.data));
4726
+ } catch (err) {
4727
+ logSafeAdminError("webhook-test", err);
4728
+ setResult({
4729
+ messageId: "settings.signedWebhook.test.failed",
4730
+ defaultMessage: "The test could not be started.",
4731
+ tone: "danger"
4732
+ });
4733
+ } finally {
4734
+ setTesting(false);
4735
+ }
4736
+ };
4737
+ return /* @__PURE__ */ jsxs(
4738
+ SectionCard,
4739
+ {
4740
+ id: "signed-webhook",
4741
+ title: t("settings.signedWebhook.title", "Signed webhook"),
4742
+ subtitle: t(
4743
+ "settings.signedWebhook.intro",
4744
+ "Sends the selected events as signed JSON to your own endpoint, for example a SIEM. Only https; private and local addresses are refused, redirects are not followed."
4745
+ ),
4746
+ children: [
4747
+ /* @__PURE__ */ jsx(
4748
+ SettingsToggleRow,
4749
+ {
4750
+ id: "generic-webhook-enabled",
4751
+ title: t("settings.signedWebhook.enable.label", "Send to the signed webhook"),
4752
+ description: t(
4753
+ "settings.signedWebhook.enable.hint",
4754
+ "Failed deliveries are retried twice (after 2 and 10 seconds). Data sent: user documentId, IP as the security log stores it, browser, country and city, and the event details. No email addresses."
4755
+ ),
4756
+ checked: settings.genericWebhookEnabled === true,
4757
+ disabled: locked,
4758
+ onChange: (checked) => handleChange("genericWebhookEnabled", checked)
4759
+ }
4760
+ ),
4761
+ locked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null,
4762
+ /* @__PURE__ */ jsxs(EqualGrid, { columns: 2, stackBelow: "medium", gap: 6, children: [
4763
+ /* @__PURE__ */ jsx(
4764
+ WriteOnlyField,
4765
+ {
4766
+ field: "genericWebhookUrl",
4767
+ saved: settings.hasGenericWebhook === true,
4768
+ savedHint: settings.genericWebhookHint,
4769
+ disabled: locked,
4770
+ form,
4771
+ type: "url",
4772
+ label: t("settings.signedWebhook.url.label", "Webhook URL"),
4773
+ hint: t(
4774
+ "settings.signedWebhook.url.hint",
4775
+ "https only. Treat it like a password: it may contain a token."
4776
+ ),
4777
+ placeholder: "https://hooks.example.com/sessions"
4778
+ }
4779
+ ),
4780
+ /* @__PURE__ */ jsx(
4781
+ WriteOnlyField,
4782
+ {
4783
+ field: "genericWebhookSecret",
4784
+ saved: settings.hasGenericWebhookSecret === true,
4785
+ disabled: locked,
4786
+ form,
4787
+ type: "text",
4788
+ label: t("settings.signedWebhook.secret.label", "Signing secret"),
4789
+ hint: t(
4790
+ "settings.signedWebhook.secret.hint",
4791
+ "Your endpoint uses it to verify the signature. Copy it before you save: it is never shown again."
4792
+ ),
4793
+ extra: /* @__PURE__ */ jsxs(Fragment$1, { children: [
4794
+ /* @__PURE__ */ jsx(
4795
+ Button,
4796
+ {
4797
+ variant: "secondary",
4798
+ startIcon: /* @__PURE__ */ jsx(Key, {}),
4799
+ disabled: locked,
4800
+ onClick: () => handleChange("genericWebhookSecret", generateWebhookSecret()),
4801
+ children: t("settings.signedWebhook.generate", "Generate")
4802
+ }
4803
+ ),
4804
+ typeof settings.genericWebhookSecret === "string" && settings.genericWebhookSecret ? /* @__PURE__ */ jsx(
4805
+ Button,
4806
+ {
4807
+ variant: "tertiary",
4808
+ onClick: () => form.copyValue(
4809
+ settings.genericWebhookSecret,
4810
+ t("settings.signedWebhook.copied", "Secret copied."),
4811
+ "webhook-secret"
4812
+ ),
4813
+ children: t("settings.signedWebhook.copy", "Copy")
4814
+ }
4815
+ ) : null
4816
+ ] })
4817
+ }
4818
+ )
4819
+ ] }),
4820
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 2, children: [
4821
+ /* @__PURE__ */ jsx(
4822
+ Button,
4823
+ {
4824
+ variant: "secondary",
4825
+ startIcon: /* @__PURE__ */ jsx(Check, {}),
4826
+ loading: testing,
4827
+ disabled: locked || pendingWriteOnly || !settings.hasGenericWebhook,
4828
+ onClick: sendTest,
4829
+ children: t("settings.signedWebhook.test.action", "Send test")
4830
+ }
4831
+ ),
4832
+ pendingWriteOnly ? /* @__PURE__ */ jsx(ReadableText, { variant: "pi", textColor: "neutral600", tag: "p", children: t(
4833
+ "settings.signedWebhook.test.saveFirst",
4834
+ "Save first: the test uses the saved URL and secret."
4835
+ ) }) : null,
4836
+ /* @__PURE__ */ jsx(Box, { "aria-live": "polite", "data-webhook-test-result": "", children: result ? /* @__PURE__ */ jsx(
4837
+ Typography,
4838
+ {
4839
+ variant: "pi",
4840
+ textColor: result.tone === "success" ? "success600" : "danger600",
4841
+ children: t(result.messageId, result.defaultMessage, result.values)
4842
+ }
4843
+ ) : null })
4844
+ ] })
4845
+ ]
4846
+ }
4847
+ );
4848
+ };
4849
+ const EventGrid = styled.div`
4850
+ container-type: inline-size;
4851
+ min-width: 0;
4852
+
4853
+ & > ul {
4854
+ display: grid;
4855
+ grid-template-columns: minmax(0, 1fr);
4856
+ gap: ${({ theme }) => theme.spaces[3]};
4857
+ align-items: center;
4858
+ margin: 0;
4859
+ padding: 0;
4860
+ list-style: none;
4861
+ }
4862
+
4863
+ /* Every item starts on the row line (an inherited li + li margin
4864
+ offset the second column). */
4865
+ & > ul > li {
4866
+ margin: 0;
4867
+ }
4868
+
4869
+ @container (min-width: 520px) {
4870
+ & > ul {
4871
+ grid-template-columns: repeat(2, minmax(0, 1fr));
4872
+ }
4873
+ }
4874
+ `;
4875
+ const WebhookEventsCard = ({ form }) => {
4876
+ const { t } = useSettingsTranslate();
4877
+ const { settings, handleChange } = form;
4878
+ const locked = form.canChangeProtected === false;
4879
+ const selected = Array.isArray(settings.webhookEvents) ? settings.webhookEvents : [];
4880
+ const toggle = (event, checked) => {
4881
+ const next = checked ? [.../* @__PURE__ */ new Set([...selected, event])] : selected.filter((value) => value !== event);
4882
+ handleChange(
4883
+ "webhookEvents",
4884
+ WEBHOOK_EVENT_OPTIONS.map(([value]) => value).filter((value) => next.includes(value))
4885
+ );
4886
+ };
4887
+ return /* @__PURE__ */ jsxs(
4888
+ SectionCard,
4889
+ {
4890
+ id: "webhook-events",
4891
+ title: t("settings.webhookEvents.title", "Events to send"),
4892
+ subtitle: t(
4893
+ "settings.webhookEvents.intro",
4894
+ "Applies to Discord, Slack and the signed webhook. Every successful sign-in is usually too much; choose the events your team acts on."
4895
+ ),
4896
+ children: [
4897
+ locked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null,
4898
+ /* @__PURE__ */ jsx(EventGrid, { children: /* @__PURE__ */ jsx("ul", { "aria-label": t("settings.webhookEvents.title", "Events to send"), children: WEBHOOK_EVENT_OPTIONS.map(([event, id, label]) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(Flex, { alignItems: "center", minWidth: 0, children: /* @__PURE__ */ jsx(
4899
+ Checkbox,
4900
+ {
4901
+ checked: selected.includes(event),
4902
+ disabled: locked,
4903
+ onCheckedChange: (checked) => toggle(event, checked === true),
4904
+ "data-webhook-event": event,
4905
+ children: t(id, label)
4906
+ }
4907
+ ) }) }, event)) }) })
4908
+ ]
4909
+ }
4910
+ );
4911
+ };
3076
4912
  const WEBHOOK_EVENTS = Object.freeze({
3077
4913
  suspicious: "login.suspicious",
3078
4914
  newLocation: "login.new_location",
@@ -3108,7 +4944,13 @@ const AlertTypeCell = ({ checked, disabled, children }) => /* @__PURE__ */ jsx(
3108
4944
  const AlertsTab = ({ form }) => {
3109
4945
  const { t, tError } = useSettingsTranslate();
3110
4946
  const { settings, handleChange, errors } = form;
3111
- const hintIds = { suspicious: useId(), newCountry: useId(), vpnProxy: useId() };
4947
+ const hintIds = {
4948
+ suspicious: useId(),
4949
+ newCountry: useId(),
4950
+ vpnProxy: useId(),
4951
+ newDevice: useId(),
4952
+ travel: useId()
4953
+ };
3112
4954
  const lookupOff = !settings.enableGeolocation;
3113
4955
  const emailTypesDisabled = lookupOff || !settings.enableEmailAlerts;
3114
4956
  const webhookFieldsDisabled = lookupOff || !settings.enableWebhooks;
@@ -3144,6 +4986,25 @@ const AlertsTab = ({ form }) => {
3144
4986
  "settings.config.email.vpnProxy.hint",
3145
4987
  "Sign-in from a VPN, or from a public or residential proxy."
3146
4988
  )
4989
+ },
4990
+ {
4991
+ field: "alertOnNewDevice",
4992
+ hintId: hintIds.newDevice,
4993
+ label: t("settings.config.email.newDevice.label", "Sign-in from a new device"),
4994
+ hint: t(
4995
+ "settings.config.email.newDevice.hint",
4996
+ `Browser and system not seen in the user's last 50 sessions. With a "This wasn't me" link that signs that device out.`
4997
+ )
4998
+ },
4999
+ {
5000
+ field: "alertOnImpossibleTravel",
5001
+ hintId: hintIds.travel,
5002
+ needsTravel: true,
5003
+ label: t("settings.config.email.travel.label", "Impossible travel"),
5004
+ hint: t(
5005
+ "settings.config.email.travel.hint",
5006
+ `Farther from the previous sign-in than anyone could travel. With a "This wasn't me" link.`
5007
+ )
3147
5008
  }
3148
5009
  ];
3149
5010
  return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
@@ -3181,9 +5042,10 @@ const AlertsTab = ({ form }) => {
3181
5042
  /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 3, children: [
3182
5043
  /* @__PURE__ */ jsx(Typography, { variant: "pi", fontWeight: "bold", tag: "div", textColor: "neutral800", children: t("settings.config.email.types.label", "Send an email for") }),
3183
5044
  !lookupOff && !settings.enableEmailAlerts ? /* @__PURE__ */ jsx(RequiresNotice, { children: t("settings.config.requires.emailAlerts", "Requires Send security emails") }) : null,
3184
- /* @__PURE__ */ jsx(EmailTypeGrid, { children: /* @__PURE__ */ jsx("div", { children: emailTypes.map(({ field, needsRiskData, hintId, label, hint }) => {
5045
+ /* @__PURE__ */ jsx(EmailTypeGrid, { children: /* @__PURE__ */ jsx("div", { children: emailTypes.map(({ field, needsRiskData, needsTravel, hintId, label, hint }) => {
3185
5046
  const control = needsRiskData ? riskDependentControl(settings[field], risk.state) : { checked: settings[field], disabled: false, savedOnButInactive: false };
3186
- const disabled = emailTypesDisabled || control.disabled;
5047
+ const travelOff = needsTravel && settings.impossibleTravelEnabled !== true;
5048
+ const disabled = emailTypesDisabled || control.disabled || travelOff;
3187
5049
  return /* @__PURE__ */ jsxs(AlertTypeCell, { checked: control.checked, disabled, children: [
3188
5050
  /* @__PURE__ */ jsx(
3189
5051
  Checkbox,
@@ -3196,7 +5058,8 @@ const AlertsTab = ({ form }) => {
3196
5058
  }
3197
5059
  ),
3198
5060
  /* @__PURE__ */ jsx(ReadableText, { id: hintId, variant: "pi", textColor: "neutral600", tag: "p", children: hint }),
3199
- !lookupOff && control.disabled ? /* @__PURE__ */ jsx(RiskSourceNotice, { savedOn: control.savedOnButInactive }) : null
5061
+ !lookupOff && control.disabled ? /* @__PURE__ */ jsx(RiskSourceNotice, { savedOn: control.savedOnButInactive }) : null,
5062
+ travelOff ? /* @__PURE__ */ jsx(RequiresNotice, { tab: "login-protection", children: t("settings.config.requires.travel", "Requires Detect impossible travel") }) : null
3200
5063
  ] }, field);
3201
5064
  }) }) })
3202
5065
  ] }),
@@ -3224,7 +5087,7 @@ const AlertsTab = ({ form }) => {
3224
5087
  title: t("settings.config.webhooks.title", "Team notifications (webhooks)"),
3225
5088
  subtitle: t(
3226
5089
  "settings.config.webhooks.intro",
3227
- "Posts every sign-in to Discord or Slack as 'suspicious', 'new country' or 'success'."
5090
+ "Posts the selected events to Discord or Slack."
3228
5091
  ),
3229
5092
  children: [
3230
5093
  /* @__PURE__ */ jsx(
@@ -3234,7 +5097,7 @@ const AlertsTab = ({ form }) => {
3234
5097
  title: t("settings.config.webhooks.enable.label", "Send team notifications"),
3235
5098
  description: t(
3236
5099
  "settings.config.webhooks.enable.hint",
3237
- "Event per sign-in: {suspicious}, otherwise {newLocation}, otherwise {success}.",
5100
+ "A sign-in is sent as {suspicious}, otherwise {newLocation}, otherwise {success}, when that event is selected below.",
3238
5101
  WEBHOOK_EVENTS
3239
5102
  ),
3240
5103
  checked: settings.enableWebhooks,
@@ -3297,7 +5160,9 @@ const AlertsTab = ({ form }) => {
3297
5160
  ] })
3298
5161
  ]
3299
5162
  }
3300
- )
5163
+ ),
5164
+ /* @__PURE__ */ jsx(WebhookEventsCard, { form }),
5165
+ /* @__PURE__ */ jsx(SignedWebhookCard, { form })
3301
5166
  ] });
3302
5167
  };
3303
5168
  const DangerButton = styled(Button)`
@@ -3308,27 +5173,97 @@ const DataRetentionTab = ({ form }) => {
3308
5173
  const { t } = useSettingsTranslate();
3309
5174
  const units = useOptionLabels();
3310
5175
  const { settings, handleChange, handleCleanInactive } = form;
5176
+ const {
5177
+ allowedActions: { canRead: canReadLog }
5178
+ } = useRBAC(pluginPermissions.adminActivityRead);
5179
+ const locked = form.canChangeProtected === false;
5180
+ const canChangeLogRetention = canReadLog && !locked;
5181
+ const preset = currentRetentionPreset(settings);
5182
+ const applyPreset = (key) => {
5183
+ const values = RETENTION_PRESETS[key];
5184
+ if (!values) return;
5185
+ handleChange("retentionDays", values.retentionDays);
5186
+ if (canChangeLogRetention) {
5187
+ handleChange("securityLogRetentionDays", values.securityLogRetentionDays);
5188
+ }
5189
+ };
3311
5190
  return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
3312
5191
  /* @__PURE__ */ jsx(IntroText, { children: t(
3313
5192
  "settings.config.retention.intro",
3314
5193
  "Ended sessions stay in the history until they are deleted. The tokens of deleted sessions stay revoked."
3315
5194
  ) }),
3316
- /* @__PURE__ */ jsx(SectionCard, { title: t("settings.config.retention.title", "History retention"), children: /* @__PURE__ */ jsx(EqualGrid, { columns: 2, stackBelow: "medium", gap: 6, children: /* @__PURE__ */ jsx(
3317
- PresetSelect,
5195
+ /* @__PURE__ */ jsx(SectionCard, { title: t("settings.config.retention.title", "History retention"), children: /* @__PURE__ */ jsxs(EqualGrid, { columns: 2, stackBelow: "medium", gap: 6, children: [
5196
+ /* @__PURE__ */ jsx(
5197
+ FormField,
5198
+ {
5199
+ id: "retention-preset",
5200
+ name: "retentionPreset",
5201
+ label: t("settings.config.retention.preset.label", "Retention preset"),
5202
+ description: canChangeLogRetention ? t(
5203
+ "settings.config.retention.preset.hint",
5204
+ "Sets how long ended sessions and security events are kept. You can still change each value."
5205
+ ) : t(
5206
+ "settings.config.retention.preset.hintSessionsOnly",
5207
+ 'Sets how long ended sessions are kept. The security log retention needs "View admin activity" and "Change protected settings".'
5208
+ ),
5209
+ children: /* @__PURE__ */ jsxs(SingleSelect, { value: preset, onChange: (value) => applyPreset(value), children: [
5210
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "minimal", children: t("settings.config.retention.preset.minimal", "Minimal: 7 days, events 30 days") }),
5211
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "standard", children: t(
5212
+ "settings.config.retention.preset.standard",
5213
+ "Standard: 90 days, events 90 days"
5214
+ ) }),
5215
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "extended", children: t(
5216
+ "settings.config.retention.preset.extended",
5217
+ "Extended: 365 days, events 365 days"
5218
+ ) }),
5219
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "custom", disabled: true, children: t("settings.config.retention.preset.custom", "Custom values") })
5220
+ ] })
5221
+ }
5222
+ ),
5223
+ /* @__PURE__ */ jsx(
5224
+ PresetSelect,
5225
+ {
5226
+ id: "session-retention-period",
5227
+ name: "retentionDays",
5228
+ label: t("settings.config.retention.keep.label", "Keep ended sessions for"),
5229
+ description: t(
5230
+ "settings.config.retention.keep.hint",
5231
+ "Checked once a day, the first time about 24 hours after the server starts. Open sessions are never deleted by retention. 'Forever' keeps them."
5232
+ ),
5233
+ value: settings.retentionDays,
5234
+ presets: SELECT_PRESETS.retentionDays,
5235
+ format: units.retentionDays,
5236
+ onChange: (value) => handleChange("retentionDays", value)
5237
+ }
5238
+ )
5239
+ ] }) }),
5240
+ /* @__PURE__ */ jsxs(
5241
+ SectionCard,
3318
5242
  {
3319
- id: "session-retention-period",
3320
- name: "retentionDays",
3321
- label: t("settings.config.retention.keep.label", "Keep ended sessions for"),
3322
- description: t(
3323
- "settings.config.retention.keep.hint",
3324
- "Checked once a day, the first time about 24 hours after the server starts. Open sessions are never deleted by retention. 'Forever' keeps them."
5243
+ title: t("settings.config.privacy.title", "Privacy"),
5244
+ subtitle: t(
5245
+ "settings.config.privacy.intro",
5246
+ "What Session Manager records about app users. The README has a fact sheet for data protection and works councils."
3325
5247
  ),
3326
- value: settings.retentionDays,
3327
- presets: SELECT_PRESETS.retentionDays,
3328
- format: units.retentionDays,
3329
- onChange: (value) => handleChange("retentionDays", value)
5248
+ children: [
5249
+ /* @__PURE__ */ jsx(
5250
+ SettingsToggleRow,
5251
+ {
5252
+ id: "session-ip-anonymize",
5253
+ title: t("settings.config.privacy.shortIp.label", "Shorten IP addresses of sessions"),
5254
+ description: t(
5255
+ "settings.config.privacy.shortIp.hint",
5256
+ "Stores 203.0.113.0 instead of 203.0.113.42 (IPv6: the first 48 bits) for new sessions. Country rules and lockouts still use the full address while the request runs. Existing sessions are not changed."
5257
+ ),
5258
+ checked: settings.sessionIpAnonymize === true,
5259
+ disabled: locked,
5260
+ onChange: (checked) => handleChange("sessionIpAnonymize", checked)
5261
+ }
5262
+ ),
5263
+ locked ? /* @__PURE__ */ jsx(ProtectedNotice, {}) : null
5264
+ ]
3330
5265
  }
3331
- ) }) }),
5266
+ ),
3332
5267
  /* @__PURE__ */ jsx(
3333
5268
  SectionCard,
3334
5269
  {