@rapidmx/web-client 0.4.0 → 0.5.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 (169) hide show
  1. package/apps/admin/audit-log/index.tsx +35 -8
  2. package/apps/admin/data-requests/index.tsx +480 -485
  3. package/apps/admin/distribution-lists/[uid].tsx +19 -1
  4. package/apps/admin/escrow-scopes/[uid].tsx +348 -237
  5. package/apps/admin/escrow-scopes/new/index.tsx +8 -2
  6. package/apps/admin/index.tsx +19 -1
  7. package/apps/admin/ingest-queue/index.tsx +44 -5
  8. package/apps/admin/mailboxes/[uid].tsx +211 -184
  9. package/apps/admin/quarantine/index.tsx +46 -14
  10. package/apps/admin/transport-rules/[uid].tsx +30 -1
  11. package/apps/admin/transport-rules/_transportRuleConfig.tsx +38 -2
  12. package/apps/admin/transport-rules/index.tsx +24 -6
  13. package/apps/admin/transport-rules/new/index.tsx +30 -1
  14. package/apps/escrow/_layout.tsx +2 -3
  15. package/apps/escrow/audit-log/index.tsx +196 -168
  16. package/apps/escrow/matters/[uid].tsx +621 -521
  17. package/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.tsx +22 -1
  18. package/apps/shared/components/admin/layout/AdminShell.tsx +3 -1
  19. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -0
  20. package/apps/shared/components/admin/mailboxes/ResourceSettingsCard.tsx +3 -3
  21. package/apps/shared/components/admin/mailboxes/ShareAccessCard.tsx +55 -11
  22. package/apps/shared/components/admin/settings/BrandingForm.tsx +15 -4
  23. package/apps/shared/components/admin/settings/DomainDnsSetup.tsx +18 -7
  24. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +10 -2
  25. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +6 -0
  26. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +45 -12
  27. package/apps/shared/components/admin/settings/PluginsManager.tsx +1235 -595
  28. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +174 -98
  29. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +49 -13
  30. package/apps/shared/components/admin/setup/SetupWizard.tsx +150 -34
  31. package/apps/shared/components/admin/signOut.ts +79 -0
  32. package/apps/shared/components/admin/usePagedList.tsx +129 -0
  33. package/apps/shared/components/calendar/EventModal.tsx +717 -549
  34. package/apps/shared/components/calendar/MonthView.tsx +173 -139
  35. package/apps/shared/components/calendar/RecurrenceEditor.tsx +222 -180
  36. package/apps/shared/components/calendar/SplitDayView.tsx +143 -137
  37. package/apps/shared/components/calendar/TimeGridView.tsx +244 -198
  38. package/apps/shared/components/calendar/allDay.ts +124 -0
  39. package/apps/shared/components/calendar/layout/CalendarShell.tsx +1 -1
  40. package/apps/shared/components/contacts/ContactDetailPane.tsx +100 -21
  41. package/apps/shared/components/contacts/ContactForm.tsx +377 -348
  42. package/apps/shared/components/contacts/ContactsSidebar.tsx +6 -2
  43. package/apps/shared/components/contacts/KeyChangeReview.tsx +192 -0
  44. package/apps/shared/components/contacts/contactKeys.ts +78 -0
  45. package/apps/shared/components/escrow/layout/EscrowShell.tsx +148 -134
  46. package/apps/shared/components/layout/AppShell.tsx +87 -15
  47. package/apps/shared/components/layout/BrandingChrome.tsx +48 -10
  48. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +389 -298
  49. package/apps/shared/components/layout/MailboxProvisioning.tsx +19 -3
  50. package/apps/shared/components/layout/RecoveryCodeUnlock.tsx +350 -0
  51. package/apps/shared/components/layout/UnlockPromptProvider.tsx +257 -128
  52. package/apps/shared/components/mail/ConversationThreadPane.tsx +216 -181
  53. package/apps/shared/components/mail/MessageDetailPane.tsx +1318 -630
  54. package/apps/shared/components/mail/compose/ComposeContext.tsx +20 -15
  55. package/apps/shared/components/mail/compose/ComposeWindow.tsx +854 -132
  56. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -0
  57. package/apps/shared/components/mail/layout/MailShell.tsx +12 -2
  58. package/apps/shared/components/mail/pinnedSigners.ts +124 -0
  59. package/apps/shared/components/mail/verificationSeals.ts +125 -0
  60. package/apps/shared/components/mail/writableMailboxes.ts +101 -0
  61. package/apps/shared/components/rules/RuleBuilder.tsx +311 -276
  62. package/apps/shared/mail/listAllPages.ts +39 -0
  63. package/apps/shared/search/LocalIndexLifecycle.tsx +64 -55
  64. package/apps/shared/search/localIndexBuilder.ts +481 -179
  65. package/apps/shared/search/localIndexRpcClient.ts +228 -28
  66. package/apps/shared/search/localIndexSchema.ts +15 -6
  67. package/apps/shared/search/localIndexStorage.ts +98 -0
  68. package/apps/shared/search/localIndexVFS.ts +32 -1
  69. package/apps/shared/search/localIndexWorker.ts +648 -186
  70. package/apps/www/calendar/index.tsx +438 -417
  71. package/apps/www/contacts/[uid].tsx +21 -2
  72. package/apps/www/contacts/index.tsx +116 -12
  73. package/apps/www/index.tsx +1314 -1041
  74. package/apps/www/messages/[uid].tsx +18 -6
  75. package/apps/www/settings/auto-reply/index.tsx +134 -129
  76. package/apps/www/settings/booking-types/[uid].tsx +306 -300
  77. package/apps/www/settings/encryption/index.tsx +739 -216
  78. package/apps/www/settings/filters/[uid].tsx +171 -155
  79. package/apps/www/settings/filters/new/index.tsx +8 -1
  80. package/apps/www/settings/focused-inbox/index.tsx +150 -148
  81. package/apps/www/settings/privacy/index.tsx +494 -436
  82. package/apps/www/settings/read-receipts/index.tsx +148 -125
  83. package/apps/www/settings/sharing/index.tsx +17 -14
  84. package/apps/www/tasks/index.tsx +638 -579
  85. package/dist/apps/admin/audit-log/index.js +38 -8
  86. package/dist/apps/admin/data-requests/index.js +52 -72
  87. package/dist/apps/admin/distribution-lists/[uid].js +1 -1
  88. package/dist/apps/admin/escrow-scopes/[uid].js +91 -12
  89. package/dist/apps/admin/escrow-scopes/new/index.js +8 -3
  90. package/dist/apps/admin/index.js +4 -1
  91. package/dist/apps/admin/ingest-queue/index.js +24 -6
  92. package/dist/apps/admin/mailboxes/[uid].js +20 -4
  93. package/dist/apps/admin/quarantine/index.js +20 -11
  94. package/dist/apps/admin/transport-rules/[uid].js +18 -2
  95. package/dist/apps/admin/transport-rules/_transportRuleConfig.js +19 -0
  96. package/dist/apps/admin/transport-rules/index.js +22 -6
  97. package/dist/apps/admin/transport-rules/new/index.js +18 -2
  98. package/dist/apps/escrow/_layout.js +3 -3
  99. package/dist/apps/escrow/audit-log/index.js +26 -1
  100. package/dist/apps/escrow/matters/[uid].js +77 -42
  101. package/dist/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.js +11 -2
  102. package/dist/apps/shared/components/admin/layout/AdminShell.js +3 -1
  103. package/dist/apps/shared/components/admin/mailboxes/EscrowScopeCard.js +72 -0
  104. package/dist/apps/shared/components/admin/mailboxes/ResourceSettingsCard.js +3 -3
  105. package/dist/apps/shared/components/admin/mailboxes/ShareAccessCard.js +22 -4
  106. package/dist/apps/shared/components/admin/settings/BrandingForm.js +15 -4
  107. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.js +13 -7
  108. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +7 -2
  109. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +6 -0
  110. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +34 -12
  111. package/dist/apps/shared/components/admin/settings/PluginsManager.js +390 -78
  112. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +40 -11
  113. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +29 -13
  114. package/dist/apps/shared/components/admin/setup/SetupWizard.js +87 -21
  115. package/dist/apps/shared/components/admin/signOut.js +75 -0
  116. package/dist/apps/shared/components/admin/usePagedList.js +99 -0
  117. package/dist/apps/shared/components/calendar/EventModal.js +142 -21
  118. package/dist/apps/shared/components/calendar/MonthView.js +12 -5
  119. package/dist/apps/shared/components/calendar/RecurrenceEditor.js +40 -5
  120. package/dist/apps/shared/components/calendar/SplitDayView.js +10 -4
  121. package/dist/apps/shared/components/calendar/TimeGridView.js +23 -7
  122. package/dist/apps/shared/components/calendar/allDay.js +111 -0
  123. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +1 -1
  124. package/dist/apps/shared/components/contacts/ContactDetailPane.js +43 -5
  125. package/dist/apps/shared/components/contacts/ContactForm.js +32 -10
  126. package/dist/apps/shared/components/contacts/ContactsSidebar.js +2 -2
  127. package/dist/apps/shared/components/contacts/KeyChangeReview.js +63 -0
  128. package/dist/apps/shared/components/contacts/contactKeys.js +64 -0
  129. package/dist/apps/shared/components/escrow/layout/EscrowShell.js +24 -5
  130. package/dist/apps/shared/components/layout/AppShell.js +83 -14
  131. package/dist/apps/shared/components/layout/BrandingChrome.js +45 -10
  132. package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +49 -12
  133. package/dist/apps/shared/components/layout/MailboxProvisioning.js +10 -2
  134. package/dist/apps/shared/components/layout/RecoveryCodeUnlock.js +174 -0
  135. package/dist/apps/shared/components/layout/UnlockPromptProvider.js +73 -14
  136. package/dist/apps/shared/components/mail/ConversationThreadPane.js +50 -12
  137. package/dist/apps/shared/components/mail/MessageDetailPane.js +441 -36
  138. package/dist/apps/shared/components/mail/compose/ComposeContext.js +9 -6
  139. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +699 -128
  140. package/dist/apps/shared/components/mail/compose/composeFlushRegistry.js +50 -0
  141. package/dist/apps/shared/components/mail/layout/MailShell.js +12 -3
  142. package/dist/apps/shared/components/mail/pinnedSigners.js +98 -0
  143. package/dist/apps/shared/components/mail/verificationSeals.js +112 -0
  144. package/dist/apps/shared/components/mail/writableMailboxes.js +87 -0
  145. package/dist/apps/shared/components/rules/RuleBuilder.js +34 -6
  146. package/dist/apps/shared/mail/listAllPages.js +25 -0
  147. package/dist/apps/shared/search/LocalIndexLifecycle.js +58 -54
  148. package/dist/apps/shared/search/localIndexBuilder.js +292 -37
  149. package/dist/apps/shared/search/localIndexRpcClient.js +188 -25
  150. package/dist/apps/shared/search/localIndexSchema.js +12 -6
  151. package/dist/apps/shared/search/localIndexStorage.js +86 -0
  152. package/dist/apps/shared/search/localIndexVFS.js +68 -40
  153. package/dist/apps/shared/search/localIndexWorker.js +519 -173
  154. package/dist/apps/www/calendar/index.js +28 -10
  155. package/dist/apps/www/contacts/[uid].js +13 -2
  156. package/dist/apps/www/contacts/index.js +80 -10
  157. package/dist/apps/www/index.js +339 -108
  158. package/dist/apps/www/messages/[uid].js +18 -6
  159. package/dist/apps/www/settings/auto-reply/index.js +9 -4
  160. package/dist/apps/www/settings/booking-types/[uid].js +17 -12
  161. package/dist/apps/www/settings/encryption/index.js +514 -97
  162. package/dist/apps/www/settings/filters/[uid].js +22 -7
  163. package/dist/apps/www/settings/filters/new/index.js +8 -2
  164. package/dist/apps/www/settings/focused-inbox/index.js +3 -1
  165. package/dist/apps/www/settings/privacy/index.js +57 -22
  166. package/dist/apps/www/settings/read-receipts/index.js +10 -3
  167. package/dist/apps/www/settings/sharing/index.js +7 -11
  168. package/dist/apps/www/tasks/index.js +50 -10
  169. package/package.json +2 -2
@@ -3,34 +3,59 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  // Copyright (C) 2026 Jean-Philippe Steinmetz
4
4
  // SPDX-License-Identifier: MPL-2.0
5
5
  ///////////////////////////////////////////////////////////////////////////////
6
- import { useState } from "react";
6
+ import { useEffect, useState } from "react";
7
7
  import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
8
  import { MIN_AUDIT_LOG_RETENTION_DAYS, updateRetentionPolicy } from "@rapidmx/react-shared/admin/retentionPolicyApi.js";
9
9
  import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
10
10
  import Button from "@rapidmx/react-shared/components/buttons/Button.js";
11
+ import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
11
12
  const INPUT_CLASS = "w-full text-sm py-2 px-3 border border-border rounded-sm bg-surface text-text focus:outline-none focus:border-primary";
13
+ /** Whether saving `next` days newly starts purging (nothing was configured) or purges sooner than `saved` days. */
14
+ function shortensRetention(next, saved) {
15
+ return next != null && (saved == null || next < saved);
16
+ }
12
17
  /** The retention policy editor, shared by the Retention Policy page and the setup wizard. */
13
- export default function RetentionPolicyForm({ policy, onChange }) {
18
+ export default function RetentionPolicyForm({ policy, onChange, onDirtyChange, }) {
14
19
  const [messageRetentionDays, setMessageRetentionDays] = useState(policy.messageRetentionDays?.toString() ?? "");
15
20
  const [auditLogRetentionDays, setAuditLogRetentionDays] = useState(policy.auditLogRetentionDays?.toString() ?? "");
16
21
  const [error, setError] = useState(null);
17
22
  const [saving, setSaving] = useState(false);
18
23
  const [saved, setSaved] = useState(false);
19
- async function handleSubmit(e) {
24
+ // Edits are unsaved until they match what was loaded or last saved.
25
+ const snapshot = JSON.stringify([messageRetentionDays, auditLogRetentionDays]);
26
+ const [savedSnapshot, setSavedSnapshot] = useState(snapshot);
27
+ const dirty = snapshot !== savedSnapshot;
28
+ useEffect(() => onDirtyChange?.(dirty), [dirty]);
29
+ // The retention currently in effect, and a pending save that would newly start or shorten either period - which
30
+ // permanently deletes existing mail or audit-log entries on the next purge run, so it's confirmed first.
31
+ const [savedMessageDays, setSavedMessageDays] = useState(policy.messageRetentionDays);
32
+ const [savedAuditDays, setSavedAuditDays] = useState(policy.auditLogRetentionDays);
33
+ const [pendingPatch, setPendingPatch] = useState(null);
34
+ function handleSubmit(e) {
20
35
  e.preventDefault();
36
+ // A blank field is sent as `null`, which clears a configured age back to no automatic purge.
37
+ const patch = {
38
+ messageRetentionDays: messageRetentionDays.trim() === "" ? null : Number(messageRetentionDays),
39
+ auditLogRetentionDays: auditLogRetentionDays.trim() === "" ? null : Number(auditLogRetentionDays),
40
+ };
41
+ if (shortensRetention(patch.messageRetentionDays, savedMessageDays) ||
42
+ shortensRetention(patch.auditLogRetentionDays, savedAuditDays)) {
43
+ setPendingPatch(patch);
44
+ return;
45
+ }
46
+ void save(patch);
47
+ }
48
+ async function save(patch) {
49
+ setPendingPatch(null);
21
50
  setError(null);
22
51
  setSaved(false);
23
52
  setSaving(true);
24
53
  try {
25
- const patch = {};
26
- if (messageRetentionDays.trim() !== "") {
27
- patch.messageRetentionDays = Number(messageRetentionDays);
28
- }
29
- if (auditLogRetentionDays.trim() !== "") {
30
- patch.auditLogRetentionDays = Number(auditLogRetentionDays);
31
- }
32
54
  const updated = await updateRetentionPolicy(patch);
55
+ setSavedMessageDays(updated.messageRetentionDays);
56
+ setSavedAuditDays(updated.auditLogRetentionDays);
33
57
  onChange(updated);
58
+ setSavedSnapshot(snapshot);
34
59
  setSaved(true);
35
60
  }
36
61
  catch (err) {
@@ -40,5 +65,9 @@ export default function RetentionPolicyForm({ policy, onChange }) {
40
65
  setSaving(false);
41
66
  }
42
67
  }
43
- return (_jsxs("div", { className: "max-w-xl", children: [_jsx("h1", { className: "text-xl font-bold uppercase tracking-wide mb-1", children: "Retention Policy" }), _jsx("p", { className: "text-sm text-text-muted mb-5", children: "Automatically and permanently deletes mail/audit-log entries older than the configured age. Leave a field blank for no automatic purge. This does not apply to a mailbox that is a custodian on an active legal hold \u2014 a held message is skipped and retried on a later run once the hold is lifted." }), error && _jsx(Alert, { children: error }), saved && !error && _jsx("div", { className: "mb-4 text-sm text-success font-medium", children: "Saved." }), _jsxs("form", { onSubmit: handleSubmit, className: "flex flex-col gap-4", children: [_jsxs("label", { className: "flex flex-col gap-1.5 text-sm", children: [_jsx("span", { className: "font-semibold", children: "Message retention (days)" }), _jsx("input", { "aria-label": "Message retention (days)", type: "number", min: 1, className: INPUT_CLASS, value: messageRetentionDays, onChange: (e) => setMessageRetentionDays(e.target.value), placeholder: "No automatic purge" }), _jsx("span", { className: "text-xs text-text-muted", children: "Applies to any message, in any folder, regardless of age." })] }), _jsxs("label", { className: "flex flex-col gap-1.5 text-sm", children: [_jsx("span", { className: "font-semibold", children: "Audit log retention (days)" }), _jsx("input", { "aria-label": "Audit log retention (days)", type: "number", min: MIN_AUDIT_LOG_RETENTION_DAYS, className: INPUT_CLASS, value: auditLogRetentionDays, onChange: (e) => setAuditLogRetentionDays(e.target.value), placeholder: "Keep forever" }), _jsxs("span", { className: "text-xs text-text-muted", children: ["Cannot be set below ", MIN_AUDIT_LOG_RETENTION_DAYS, " days. Never applies to the tamper-evident escrow audit chain."] })] }), _jsx("div", { children: _jsx(Button, { type: "submit", loading: saving, disabled: saving, className: "!w-auto", children: "Save" }) })] })] }));
68
+ return (_jsxs("div", { className: "max-w-xl", children: [_jsx("h1", { className: "text-xl font-bold uppercase tracking-wide mb-1", children: "Retention Policy" }), _jsx("p", { className: "text-sm text-text-muted mb-5", children: "Automatically and permanently deletes mail/audit-log entries older than the configured age. Leave a field blank for no automatic purge. This does not apply to a mailbox that is a custodian on an active legal hold \u2014 a held message is skipped and retried on a later run once the hold is lifted." }), error && _jsx(Alert, { children: error }), saved && !error && _jsx("div", { className: "mb-4 text-sm text-success font-medium", children: "Saved." }), _jsxs("form", { onSubmit: handleSubmit, className: "flex flex-col gap-4", children: [_jsxs("label", { className: "flex flex-col gap-1.5 text-sm", children: [_jsx("span", { className: "font-semibold", children: "Message retention (days)" }), _jsx("input", { "aria-label": "Message retention (days)", type: "number", min: 1, className: INPUT_CLASS, value: messageRetentionDays, onChange: (e) => setMessageRetentionDays(e.target.value), placeholder: "No automatic purge" }), _jsx("span", { className: "text-xs text-text-muted", children: "Applies to any message, in any folder, regardless of age." })] }), _jsxs("label", { className: "flex flex-col gap-1.5 text-sm", children: [_jsx("span", { className: "font-semibold", children: "Audit log retention (days)" }), _jsx("input", { "aria-label": "Audit log retention (days)", type: "number", min: MIN_AUDIT_LOG_RETENTION_DAYS, className: INPUT_CLASS, value: auditLogRetentionDays, onChange: (e) => setAuditLogRetentionDays(e.target.value), placeholder: "Keep forever" }), _jsxs("span", { className: "text-xs text-text-muted", children: ["Cannot be set below ", MIN_AUDIT_LOG_RETENTION_DAYS, " days. Never applies to the tamper-evident escrow audit chain."] })] }), _jsx("div", { children: _jsx(Button, { type: "submit", loading: saving, disabled: saving, className: "!w-auto", children: "Save" }) })] }), _jsxs(Modal, { open: pendingPatch !== null, onClose: () => setPendingPatch(null), title: "Delete older data?", children: [shortensRetention(pendingPatch?.messageRetentionDays, savedMessageDays) && (_jsxs("p", { className: "text-sm mb-3", children: [savedMessageDays == null
69
+ ? "Mail isn't deleted automatically today."
70
+ : `Mail is currently kept for ${savedMessageDays} days.`, " ", "With this change, every message older than ", _jsxs("strong", { children: [pendingPatch?.messageRetentionDays, " days"] }), ", in every mailbox and folder, is permanently deleted on the next purge run - and so on from then on. Mailboxes on an active legal hold are skipped."] })), shortensRetention(pendingPatch?.auditLogRetentionDays, savedAuditDays) && (_jsxs("p", { className: "text-sm mb-3", children: [savedAuditDays == null
71
+ ? "Audit-log entries are kept forever today."
72
+ : `Audit-log entries are currently kept for ${savedAuditDays} days.`, " ", "With this change, every audit-log entry older than", " ", _jsxs("strong", { children: [pendingPatch?.auditLogRetentionDays, " days"] }), " is permanently deleted on the next purge run. The escrow audit chain is never purged."] })), _jsx("p", { className: "text-sm font-semibold text-danger mb-4", children: "Deleted data can\u2019t be recovered." }), _jsxs("div", { className: "flex gap-3 justify-end", children: [_jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: () => setPendingPatch(null), children: "Cancel" }), _jsx(Button, { type: "button", className: "!w-auto !bg-none !bg-danger !border-danger hover:!bg-danger", onClick: () => void save(pendingPatch), children: "Save and delete older data" })] })] })] }));
44
73
  }
@@ -11,8 +11,10 @@ import { toDatetimeLocal } from "@rapidmx/react-shared/util/dateInput.js";
11
11
  import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
12
12
  import Button from "@rapidmx/react-shared/components/buttons/Button.js";
13
13
  import FormField from "@rapidmx/react-shared/components/forms/FormField.js";
14
- import EscrowScopeKeyAndHoldersFields, { emptyEscrowScopeKeyAndHoldersValue, } from "../escrowScopes/EscrowScopeKeyAndHoldersFields.js";
14
+ import EscrowScopeKeyAndHoldersFields, { emptyEscrowScopeKeyAndHoldersValue, selfAsHolderError, } from "../escrowScopes/EscrowScopeKeyAndHoldersFields.js";
15
15
  const INPUT_CLASS = "w-full text-sm py-2.5 px-3 border border-border rounded-sm bg-surface text-text focus:outline-none focus:border-primary";
16
+ /** How long a download's object URL is kept, since some browsers are still reading it after the click returns. */
17
+ export const DOWNLOAD_URL_LIFETIME_MS = 60000;
16
18
  /** Offers `text` to the browser as a file download. */
17
19
  export function downloadTextFile(filename, text, type = "application/x-pem-file") {
18
20
  const url = URL.createObjectURL(new Blob([text], { type }));
@@ -22,7 +24,7 @@ export function downloadTextFile(filename, text, type = "application/x-pem-file"
22
24
  document.body.appendChild(link);
23
25
  link.click();
24
26
  link.remove();
25
- URL.revokeObjectURL(url);
27
+ setTimeout(() => URL.revokeObjectURL(url), DOWNLOAD_URL_LIFETIME_MS);
26
28
  }
27
29
  function fileSafe(name) {
28
30
  return name.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "escrow";
@@ -33,12 +35,13 @@ function fileSafe(name) {
33
35
  * generate the key pair here (downloading the private key, which never leaves the browser), paste in an existing
34
36
  * certificate, or go without escrow.
35
37
  */
36
- export default function EscrowSetupStep() {
38
+ export default function EscrowSetupStep({ adminUid }) {
37
39
  const [scopes, setScopes] = useState(null);
38
40
  const [mode, setMode] = useState("none");
39
41
  const [name, setName] = useState("Escrow");
40
42
  const [validYears, setValidYears] = useState(5);
41
43
  const [generated, setGenerated] = useState(null);
44
+ const [downloadedPrivateKey, setDownloadedPrivateKey] = useState(false);
42
45
  const [savedPrivateKey, setSavedPrivateKey] = useState(false);
43
46
  const [keyAndHolders, setKeyAndHolders] = useState(emptyEscrowScopeKeyAndHoldersValue());
44
47
  const [error, setError] = useState(null);
@@ -52,6 +55,7 @@ export default function EscrowSetupStep() {
52
55
  setMode(next);
53
56
  setError(null);
54
57
  setGenerated(null);
58
+ setDownloadedPrivateKey(false);
55
59
  setSavedPrivateKey(false);
56
60
  setKeyAndHolders(emptyEscrowScopeKeyAndHoldersValue());
57
61
  }
@@ -88,7 +92,17 @@ export default function EscrowSetupStep() {
88
92
  setError("A name is required.");
89
93
  return;
90
94
  }
91
- if (!keyAndHolders.publicKey.trim() || !keyAndHolders.keyType.trim() || !keyAndHolders.fingerprint.trim()) {
95
+ // Generated keys are used exactly as generated; only a pasted-in certificate's fields come from the form.
96
+ const publicKey = generated
97
+ ? generated.publicKey
98
+ : {
99
+ publicKey: keyAndHolders.publicKey.trim(),
100
+ type: keyAndHolders.keyType.trim(),
101
+ fingerprint: keyAndHolders.fingerprint.trim(),
102
+ notBefore: new Date(keyAndHolders.notBefore).getTime(),
103
+ notAfter: new Date(keyAndHolders.notAfter).getTime(),
104
+ };
105
+ if (!publicKey.publicKey || !publicKey.type || !publicKey.fingerprint) {
92
106
  setError("The public key, its type, and its fingerprint are all required.");
93
107
  return;
94
108
  }
@@ -100,17 +114,16 @@ export default function EscrowSetupStep() {
100
114
  setError("Required holders must be between 1 and the number of holders.");
101
115
  return;
102
116
  }
117
+ const selfError = selfAsHolderError(keyAndHolders.holderUserUids, adminUid);
118
+ if (selfError) {
119
+ setError(selfError);
120
+ return;
121
+ }
103
122
  setBusy(true);
104
123
  try {
105
124
  const created = await createEscrowScope({
106
125
  name: name.trim(),
107
- publicKey: {
108
- publicKey: keyAndHolders.publicKey.trim(),
109
- type: keyAndHolders.keyType.trim(),
110
- fingerprint: keyAndHolders.fingerprint.trim(),
111
- notBefore: new Date(keyAndHolders.notBefore).getTime(),
112
- notAfter: new Date(keyAndHolders.notAfter).getTime(),
113
- },
126
+ publicKey,
114
127
  holderUserUids: keyAndHolders.holderUserUids,
115
128
  requiredHolders: keyAndHolders.requiredHolders,
116
129
  notifySubjectOnAccess: keyAndHolders.notifySubjectOnAccess,
@@ -126,6 +139,9 @@ export default function EscrowSetupStep() {
126
139
  setBusy(false);
127
140
  }
128
141
  }
129
- const scopeForm = (_jsxs("form", { onSubmit: create, className: "flex flex-col gap-5", children: [_jsx(EscrowScopeKeyAndHoldersFields, { value: keyAndHolders, onChange: setKeyAndHolders, disabled: mode === "generate" && busy }), _jsx("div", { children: _jsx(Button, { type: "submit", loading: busy, disabled: busy, className: "!w-auto", children: "Create escrow scope" }) })] }));
130
- return (_jsxs("div", { className: "flex flex-col gap-5 max-w-3xl", children: [_jsxs("div", { children: [_jsx("h2", { className: "text-lg font-bold uppercase tracking-wide mb-1", children: "Escrow" }), _jsx("p", { className: "text-sm text-text-muted", children: "Escrow lets a group of trusted holders - for example your legal or compliance team - recover a mailbox\u2019s encrypted mail when they all agree to. It\u2019s optional. Without it, mail that someone encrypts can\u2019t be recovered if they lose their keys, by anyone." })] }), scopes && scopes.length > 0 && (_jsxs("div", { role: "status", className: "text-sm py-2 px-3 rounded-sm bg-surface-alt text-text", children: ["Escrow scopes set up: ", scopes.map((scope) => scope.name).join(", "), "."] })), error && _jsx(Alert, { children: error }), _jsxs("fieldset", { className: "flex flex-col gap-2 text-sm", children: [_jsx("legend", { className: "font-semibold mb-1", children: "How do you want to set up escrow?" }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "radio", name: "escrow-mode", checked: mode === "generate", onChange: () => chooseMode("generate") }), "Generate new escrow keys in this browser"] }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "radio", name: "escrow-mode", checked: mode === "existing", onChange: () => chooseMode("existing") }), "Use a certificate I already have"] }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "radio", name: "escrow-mode", checked: mode === "none", onChange: () => chooseMode("none") }), scopes && scopes.length > 0 ? "Don't add another escrow scope" : "Don't use escrow"] })] }), mode !== "none" && (_jsxs("div", { className: "bg-surface border border-border rounded-md p-6", children: [_jsx(FormField, { label: "Escrow scope name", htmlFor: "escrowName", children: _jsx("input", { id: "escrowName", type: "text", className: INPUT_CLASS, value: name, disabled: !!generated, onChange: (e) => setName(e.target.value) }) }), mode === "generate" && !generated && (_jsxs(_Fragment, { children: [_jsx(FormField, { label: "Keys valid for", htmlFor: "escrowValidYears", children: _jsx("select", { id: "escrowValidYears", className: INPUT_CLASS, value: validYears, onChange: (e) => setValidYears(Number(e.target.value)), children: [1, 2, 5, 10].map((years) => (_jsxs("option", { value: years, children: [years, " ", years === 1 ? "year" : "years"] }, years))) }) }), _jsx(Button, { type: "button", className: "!w-auto", loading: busy, disabled: busy, onClick: () => void generate(), children: "Generate keys" })] })), mode === "generate" && generated && (_jsxs("div", { className: "flex flex-col gap-3 text-sm", children: [_jsx(Alert, { children: "Download the private key now and give it to your escrow holders. It isn\u2019t stored anywhere else - if it\u2019s lost, no escrowed mail can ever be recovered." }), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx(Button, { type: "button", className: "!w-auto", onClick: () => downloadTextFile(`${fileSafe(name)}-private-key.pem`, generated.privateKeyPem), children: "Download private key" }), _jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: () => downloadTextFile(`${fileSafe(name)}-certificate.pem`, generated.certificatePem), children: "Download certificate" })] }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "checkbox", checked: savedPrivateKey, onChange: (e) => setSavedPrivateKey(e.target.checked) }), "I\u2019ve saved the private key somewhere safe"] })] }))] })), mode === "existing" && scopeForm, mode === "generate" && generated && savedPrivateKey && scopeForm] }));
142
+ const scopeForm = (_jsxs("form", { onSubmit: create, className: "flex flex-col gap-5", children: [_jsx(EscrowScopeKeyAndHoldersFields, { value: keyAndHolders, onChange: setKeyAndHolders, disabled: mode === "generate" && busy, keyReadOnly: mode === "generate" }), _jsx("div", { children: _jsx(Button, { type: "submit", loading: busy, disabled: busy, className: "!w-auto", children: "Create escrow scope" }) })] }));
143
+ return (_jsxs("div", { className: "flex flex-col gap-5 max-w-3xl", children: [_jsxs("div", { children: [_jsx("h2", { className: "text-lg font-bold uppercase tracking-wide mb-1", children: "Escrow" }), _jsx("p", { className: "text-sm text-text-muted", children: "Escrow lets a group of trusted holders - for example your legal or compliance team - recover a mailbox\u2019s encrypted mail when they all agree to. It\u2019s optional. Without it, mail that someone encrypts can\u2019t be recovered if they lose their keys, by anyone." })] }), scopes && scopes.length > 0 && (_jsxs("div", { role: "status", className: "text-sm py-2 px-3 rounded-sm bg-surface-alt text-text", children: ["Escrow scopes set up: ", scopes.map((scope) => scope.name).join(", "), "."] })), error && _jsx(Alert, { children: error }), _jsxs("fieldset", { className: "flex flex-col gap-2 text-sm", children: [_jsx("legend", { className: "font-semibold mb-1", children: "How do you want to set up escrow?" }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "radio", name: "escrow-mode", checked: mode === "generate", onChange: () => chooseMode("generate") }), "Generate new escrow keys in this browser"] }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "radio", name: "escrow-mode", checked: mode === "existing", onChange: () => chooseMode("existing") }), "Use a certificate I already have"] }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "radio", name: "escrow-mode", checked: mode === "none", onChange: () => chooseMode("none") }), scopes && scopes.length > 0 ? "Don't add another escrow scope" : "Don't use escrow"] })] }), mode !== "none" && (_jsxs("div", { className: "bg-surface border border-border rounded-md p-6", children: [_jsx(FormField, { label: "Escrow scope name", htmlFor: "escrowName", children: _jsx("input", { id: "escrowName", type: "text", className: INPUT_CLASS, value: name, disabled: !!generated, onChange: (e) => setName(e.target.value) }) }), mode === "generate" && !generated && (_jsxs(_Fragment, { children: [_jsx(FormField, { label: "Keys valid for", htmlFor: "escrowValidYears", children: _jsx("select", { id: "escrowValidYears", className: INPUT_CLASS, value: validYears, onChange: (e) => setValidYears(Number(e.target.value)), children: [1, 2, 5, 10].map((years) => (_jsxs("option", { value: years, children: [years, " ", years === 1 ? "year" : "years"] }, years))) }) }), _jsx(Button, { type: "button", className: "!w-auto", loading: busy, disabled: busy, onClick: () => void generate(), children: "Generate keys" })] })), mode === "generate" && generated && (_jsxs("div", { className: "flex flex-col gap-3 text-sm", children: [_jsx(Alert, { children: "Download the private key now and give it to your escrow holders. It isn\u2019t stored anywhere else - if it\u2019s lost, no escrowed mail can ever be recovered." }), _jsx(Alert, { children: "You\u2019re downloading this private key, so you must not also be one of its holders: pick holders other than yourself, hand the key over, and delete your copy once they have it. Otherwise one person could both configure escrow and recover mail with it." }), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx(Button, { type: "button", className: "!w-auto", onClick: () => {
144
+ downloadTextFile(`${fileSafe(name)}-private-key.pem`, generated.privateKeyPem);
145
+ setDownloadedPrivateKey(true);
146
+ }, children: "Download private key" }), _jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: () => downloadTextFile(`${fileSafe(name)}-certificate.pem`, generated.certificatePem), children: "Download certificate" })] }), _jsxs("label", { className: "flex items-center gap-2", children: [_jsx("input", { type: "checkbox", checked: savedPrivateKey, disabled: !downloadedPrivateKey, onChange: (e) => setSavedPrivateKey(e.target.checked) }), "I\u2019ve saved the private key somewhere safe"] }), !downloadedPrivateKey && (_jsx("p", { className: "text-xs text-text-muted", children: "Download the private key before continuing." }))] }))] })), mode === "existing" && scopeForm, mode === "generate" && generated && savedPrivateKey && scopeForm] }));
131
147
  }
@@ -1,9 +1,9 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  ///////////////////////////////////////////////////////////////////////////////
3
3
  // Copyright (C) 2026 Jean-Philippe Steinmetz
4
4
  // SPDX-License-Identifier: MPL-2.0
5
5
  ///////////////////////////////////////////////////////////////////////////////
6
- import { useEffect, useState } from "react";
6
+ import { useEffect, useRef, useState } from "react";
7
7
  import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
8
  import { getRetentionPolicy } from "@rapidmx/react-shared/admin/retentionPolicyApi.js";
9
9
  import { getMailboxPolicy } from "@rapidmx/react-shared/admin/mailboxPolicyApi.js";
@@ -15,6 +15,7 @@ import { listMailboxes } from "@rapidmx/react-shared/mail/mailApi.js";
15
15
  import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
16
16
  import Button from "@rapidmx/react-shared/components/buttons/Button.js";
17
17
  import FormField from "@rapidmx/react-shared/components/forms/FormField.js";
18
+ import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
18
19
  import BrandingForm from "../settings/BrandingForm.js";
19
20
  import DomainDnsSetup from "../settings/DomainDnsSetup.js";
20
21
  import EncryptionPolicyForm, { isEncryptionEnabled } from "../settings/EncryptionPolicyForm.js";
@@ -36,6 +37,9 @@ export const SETUP_STEPS = [
36
37
  function isStepId(value) {
37
38
  return SETUP_STEPS.some((step) => step.id === value);
38
39
  }
40
+ function errorMessage(err, fallback) {
41
+ return err instanceof ApiRequestError ? err.message : fallback;
42
+ }
39
43
  /**
40
44
  * The first-run setup wizard. Each step saves as the administrator works through it; the wizard itself only records
41
45
  * which step they're on (so leaving and coming back resumes there) and, at the end, that setup is finished. Every step
@@ -43,14 +47,31 @@ function isStepId(value) {
43
47
  */
44
48
  export default function SetupWizard({ userUid }) {
45
49
  const [step, setStep] = useState(null);
50
+ const [status, setStatus] = useState();
46
51
  const [domains, setDomains] = useState([]);
52
+ const [domainsError, setDomainsError] = useState(null);
47
53
  const [encryption, setEncryption] = useState(null);
48
54
  const [finishing, setFinishing] = useState(false);
49
55
  const [error, setError] = useState(null);
50
- useEffect(() => {
51
- void Promise.all([getSetupStatus().catch(() => undefined), listDomains({ limit: 25 }).catch(() => [])]).then(([status, list]) => {
56
+ /** Which of the settings step's forms have edits that haven't been saved. */
57
+ const [unsaved, setUnsaved] = useState({});
58
+ /** The step the administrator asked to go to while the settings step had unsaved edits. */
59
+ const [leavingTo, setLeavingTo] = useState(null);
60
+ const [progressFailed, setProgressFailed] = useState(false);
61
+ /** Step saves run one at a time, and only the latest step still waiting is saved. */
62
+ const progress = useRef({ running: null, next: null });
63
+ function loadDomains() {
64
+ return listDomains({ limit: 25 })
65
+ .then((list) => {
52
66
  setDomains(list);
53
- setStep(isStepId(status?.currentStep) ? status.currentStep : "plugins");
67
+ setDomainsError(null);
68
+ })
69
+ .catch((err) => setDomainsError(errorMessage(err, "Could not load your domains.")));
70
+ }
71
+ useEffect(() => {
72
+ void Promise.all([getSetupStatus().catch(() => undefined), loadDomains()]).then(([loaded]) => {
73
+ setStatus(loaded);
74
+ setStep(isStepId(loaded?.currentStep) ? loaded.currentStep : "plugins");
54
75
  });
55
76
  }, []);
56
77
  useEffect(() => {
@@ -66,40 +87,80 @@ export default function SetupWizard({ userUid }) {
66
87
  const index = SETUP_STEPS.findIndex((s) => s.id === step);
67
88
  const current = SETUP_STEPS[index];
68
89
  const last = index === SETUP_STEPS.length - 1;
90
+ /** Records the step the administrator is on. Progress is a convenience for resuming, so a failure is only noted. */
91
+ function saveProgress(next) {
92
+ const queue = progress.current;
93
+ queue.next = next;
94
+ if (queue.running) {
95
+ return;
96
+ }
97
+ queue.running = (async () => {
98
+ while (queue.next) {
99
+ const target = queue.next;
100
+ queue.next = null;
101
+ try {
102
+ await saveSetupStep(target);
103
+ setProgressFailed(false);
104
+ }
105
+ catch (err) {
106
+ console.warn("Could not save setup progress", err);
107
+ setProgressFailed(true);
108
+ }
109
+ }
110
+ queue.running = null;
111
+ })();
112
+ }
69
113
  function goTo(next) {
70
114
  setError(null);
115
+ setLeavingTo(null);
116
+ setUnsaved({});
71
117
  setStep(next);
72
- // Progress is a convenience for resuming - failing to record it shouldn't stop the administrator.
73
- void saveSetupStep(next).catch(() => undefined);
118
+ saveProgress(next);
74
119
  window.scrollTo?.(0, 0);
75
120
  }
121
+ /** Goes to `next`, first asking whether to discard any unsaved server settings. */
122
+ function requestGoTo(next) {
123
+ // Going to the step already shown would clear the unsaved-edit tracking while the forms keep their edits.
124
+ if (next === step) {
125
+ return;
126
+ }
127
+ if (step === "settings" && Object.values(unsaved).some(Boolean)) {
128
+ setLeavingTo(next);
129
+ return;
130
+ }
131
+ goTo(next);
132
+ }
133
+ const trackUnsaved = (form) => (dirty) => setUnsaved((prev) => ({ ...prev, [form]: dirty }));
76
134
  async function finish() {
77
135
  setFinishing(true);
78
136
  setError(null);
79
137
  try {
138
+ // Let a step still being recorded land first, so it can't arrive after setup is marked finished.
139
+ await progress.current.running;
80
140
  await completeSetup();
81
141
  window.location.href = "/admin";
82
142
  }
83
143
  catch (err) {
84
- setError(err instanceof ApiRequestError ? err.message : "Could not finish setup.");
144
+ setError(errorMessage(err, "Could not finish setup."));
85
145
  setFinishing(false);
86
146
  }
87
147
  }
88
- const blocked = step === "domain" && domains.length === 0;
89
- return (_jsxs("div", { className: "flex flex-col gap-6", children: [_jsxs("div", { children: [_jsx("h1", { className: "text-xl font-bold uppercase tracking-wide mb-1", children: "Set up your server" }), _jsx("p", { className: "text-sm text-text-muted", children: "You can change any of these settings later from the admin console." })] }), _jsx("ol", { "aria-label": "Setup steps", className: "flex flex-wrap gap-2", children: SETUP_STEPS.map((s, i) => (_jsx("li", { children: _jsxs("button", { type: "button", "aria-current": s.id === step ? "step" : undefined,
148
+ const noDomain = domains.length === 0;
149
+ const blocked = (step === "domain" || last) && noDomain;
150
+ return (_jsxs("div", { className: "flex flex-col gap-6", children: [_jsxs("div", { className: "flex items-start justify-between gap-4", children: [_jsxs("div", { children: [_jsx("h1", { className: "text-xl font-bold uppercase tracking-wide mb-1", children: "Set up your server" }), _jsx("p", { className: "text-sm text-text-muted", children: "You can change any of these settings later from the admin console." })] }), status && !status.required && (_jsx("a", { href: "/admin", className: "text-sm text-primary-dark underline whitespace-nowrap", children: "Exit setup" }))] }), domainsError && (_jsx(Alert, { children: _jsxs("span", { className: "flex flex-wrap items-center gap-2", children: [domainsError, _jsx(Button, { type: "button", variant: "secondary", className: "!w-auto !py-1 !px-2 !text-xs", onClick: () => void loadDomains(), children: "Retry" })] }) })), _jsx("ol", { "aria-label": "Setup steps", className: "flex flex-wrap gap-2", children: SETUP_STEPS.map((s, i) => (_jsx("li", { children: _jsxs("button", { type: "button", "aria-current": s.id === step ? "step" : undefined,
90
151
  // Steps after the domain need somewhere to put mail first.
91
- disabled: i > 1 && domains.length === 0, onClick: () => goTo(s.id), className: [
152
+ disabled: i > 1 && noDomain, onClick: () => requestGoTo(s.id), className: [
92
153
  "text-sm py-1.5 px-3 rounded-pill border disabled:opacity-50",
93
154
  s.id === step
94
155
  ? "bg-primary/10 border-primary text-primary-dark font-semibold"
95
156
  : i < index
96
157
  ? "border-border text-text"
97
158
  : "border-border text-text-muted",
98
- ].join(" "), children: [i + 1, ". ", s.title, i < index && _jsx("span", { className: "sr-only", children: " (done)" })] }) }, s.id))) }), _jsxs("section", { "aria-labelledby": "setup-step-title", className: "flex flex-col gap-5", children: [_jsxs("div", { children: [_jsxs("h2", { id: "setup-step-title", className: "text-lg font-bold", children: ["Step ", index + 1, " of ", SETUP_STEPS.length, ": ", current.title] }), _jsx("p", { className: "text-sm text-text-muted", children: current.intro })] }), step === "plugins" && _jsx(PluginsManager, {}), step === "domain" && _jsx(DomainStep, { domains: domains, onCreated: (domain) => setDomains((prev) => [...prev, domain]) }), step === "settings" && (_jsxs("div", { className: "flex flex-col gap-10", children: [_jsx(LoadedSettingsForm, { load: getEncryptionPolicy, loadErrorMessage: "Could not load the encryption policy.", children: (policy, onChange) => (_jsx(EncryptionPolicyForm, { policy: policy, onChange: (updated) => {
159
+ ].join(" "), children: [i + 1, ". ", s.title, i < index && _jsx("span", { className: "sr-only", children: " (done)" })] }) }, s.id))) }), _jsxs("section", { "aria-labelledby": "setup-step-title", className: "flex flex-col gap-5", children: [_jsxs("div", { children: [_jsxs("h2", { id: "setup-step-title", className: "text-lg font-bold", children: ["Step ", index + 1, " of ", SETUP_STEPS.length, ": ", current.title] }), _jsx("p", { className: "text-sm text-text-muted", children: current.intro })] }), step === "plugins" && _jsx(PluginsManager, {}), step === "domain" && _jsx(DomainStep, { domains: domains, onCreated: (domain) => setDomains((prev) => [...prev, domain]) }), step === "settings" && (_jsxs("div", { className: "flex flex-col gap-10", children: [_jsx(LoadedSettingsForm, { load: getEncryptionPolicy, loadErrorMessage: "Could not load the encryption policy.", children: (policy, onChange) => (_jsx(EncryptionPolicyForm, { policy: policy, onDirtyChange: trackUnsaved("encryption"), onChange: (updated) => {
99
160
  onChange(updated);
100
161
  setEncryption(updated);
101
- } })) }), _jsx(LoadedSettingsForm, { load: getRetentionPolicy, loadErrorMessage: "Could not load the retention policy.", children: (policy, onChange) => _jsx(RetentionPolicyForm, { policy: policy, onChange: onChange }) }), _jsx(LoadedSettingsForm, { load: getMailboxPolicy, loadErrorMessage: "Could not load the mailbox policy.", children: (policy, onChange) => _jsx(MailboxPolicyForm, { policy: policy, onChange: onChange }) })] })), step === "escrow" &&
102
- (encryption && !isEncryptionEnabled(encryption) ? (_jsx("p", { role: "status", className: "text-sm py-2 px-3 rounded-sm bg-surface-alt text-text", children: "End-to-end encryption is turned off, so escrow isn\u2019t needed. You can set it up later if you turn encryption on." })) : (_jsx(EscrowSetupStep, {}))), step === "branding" && (_jsx(LoadedSettingsForm, { load: getBranding, loadErrorMessage: "Could not load branding.", children: (branding, onChange) => _jsx(BrandingForm, { branding: branding, onChange: onChange }) })), step === "mailboxes" && _jsx(MailboxesStep, { userUid: userUid, domain: domains.find((d) => d.verified)?.name ?? domains[0]?.name })] }), error && _jsx(Alert, { children: error }), _jsxs("div", { className: "flex items-center gap-3 border-t border-border pt-5", children: [index > 0 && (_jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: () => goTo(SETUP_STEPS[index - 1].id), children: "Back" })), _jsx("div", { className: "flex-1" }), blocked && _jsx("span", { className: "text-sm text-text-muted", children: "Add a domain to continue." }), last ? (_jsx(Button, { type: "button", className: "!w-auto", loading: finishing, disabled: finishing, onClick: () => void finish(), children: "Finish setup" })) : (_jsx(Button, { type: "button", className: "!w-auto", disabled: blocked, onClick: () => goTo(SETUP_STEPS[index + 1].id), children: "Continue" }))] })] }));
162
+ } })) }), _jsx(LoadedSettingsForm, { load: getRetentionPolicy, loadErrorMessage: "Could not load the retention policy.", children: (policy, onChange) => _jsx(RetentionPolicyForm, { policy: policy, onChange: onChange, onDirtyChange: trackUnsaved("retention") }) }), _jsx(LoadedSettingsForm, { load: getMailboxPolicy, loadErrorMessage: "Could not load the mailbox policy.", children: (policy, onChange) => _jsx(MailboxPolicyForm, { policy: policy, onChange: onChange, onDirtyChange: trackUnsaved("mailbox") }) })] })), step === "escrow" &&
163
+ (encryption && !isEncryptionEnabled(encryption) ? (_jsx("p", { role: "status", className: "text-sm py-2 px-3 rounded-sm bg-surface-alt text-text", children: "End-to-end encryption is turned off, so escrow isn\u2019t needed. You can set it up later if you turn encryption on." })) : (_jsx(EscrowSetupStep, { adminUid: userUid }))), step === "branding" && (_jsx(LoadedSettingsForm, { load: getBranding, loadErrorMessage: "Could not load branding.", children: (branding, onChange) => _jsx(BrandingForm, { branding: branding, onChange: onChange }) })), step === "mailboxes" && _jsx(MailboxesStep, { userUid: userUid, domain: domains.find((d) => d.verified)?.name ?? domains[0]?.name })] }), error && _jsx(Alert, { children: error }), _jsxs("div", { className: "flex items-center gap-3 border-t border-border pt-5", children: [index > 0 && (_jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: () => requestGoTo(SETUP_STEPS[index - 1].id), children: "Back" })), _jsx("div", { className: "flex-1" }), progressFailed && _jsx("span", { className: "text-xs text-text-muted", children: "Your place in setup couldn\u2019t be saved." }), blocked && _jsx("span", { className: "text-sm text-text-muted", children: last ? "Add a domain before finishing setup." : "Add a domain to continue." }), last ? (_jsx(Button, { type: "button", className: "!w-auto", loading: finishing, disabled: finishing || blocked, onClick: () => void finish(), children: "Finish setup" })) : (_jsx(Button, { type: "button", className: "!w-auto", disabled: blocked, onClick: () => requestGoTo(SETUP_STEPS[index + 1].id), children: "Continue" }))] }), leavingTo && (_jsxs(Modal, { open: true, onClose: () => setLeavingTo(null), title: "Discard unsaved changes?", children: [_jsx("p", { className: "text-sm mb-4", children: "Some server settings on this step have changes that haven\u2019t been saved." }), _jsxs("div", { className: "flex gap-2 justify-end", children: [_jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: () => setLeavingTo(null), children: "Keep editing" }), _jsx(Button, { type: "button", className: "!w-auto", onClick: () => goTo(leavingTo), children: "Discard changes" })] })] }))] }));
103
164
  }
104
165
  function DomainStep({ domains, onCreated }) {
105
166
  const [name, setName] = useState("");
@@ -118,7 +179,7 @@ function DomainStep({ domains, onCreated }) {
118
179
  setName("");
119
180
  }
120
181
  catch (err) {
121
- setError(err instanceof ApiRequestError ? err.message : "Could not add the domain.");
182
+ setError(errorMessage(err, "Could not add the domain."));
122
183
  }
123
184
  finally {
124
185
  setSaving(false);
@@ -128,15 +189,20 @@ function DomainStep({ domains, onCreated }) {
128
189
  }
129
190
  function MailboxesStep({ userUid, domain }) {
130
191
  const [mailboxes, setMailboxes] = useState([]);
192
+ const [loaded, setLoaded] = useState(false);
193
+ const [error, setError] = useState(null);
131
194
  const [formKey, setFormKey] = useState(0);
132
195
  useEffect(() => {
133
196
  listMailboxes({ limit: 100 })
134
- .then(setMailboxes)
135
- .catch(() => undefined);
197
+ .then((list) =>
198
+ // Keep any mailbox created here while the list was loading.
199
+ setMailboxes((prev) => [...list, ...prev.filter((mine) => !list.some((mailbox) => mailbox.uid === mine.uid))]))
200
+ .catch((err) => setError(`${errorMessage(err, "Could not load the existing mailboxes.")} Check the Mailboxes page before creating your own, so you don't create it twice.`))
201
+ .finally(() => setLoaded(true));
136
202
  }, []);
137
203
  const hasOwn = mailboxes.some((mailbox) => mailbox.ownerUserUid === userUid);
138
- return (_jsxs("div", { className: "flex flex-col gap-5 max-w-xl", children: [mailboxes.length > 0 && (_jsxs("div", { children: [_jsx("h3", { className: "text-sm font-bold uppercase tracking-wide mb-2", children: "Mailboxes created" }), _jsx("ul", { className: "text-sm flex flex-col gap-1", children: mailboxes.map((mailbox) => (_jsxs("li", { children: [mailbox.displayName, " <", mailbox.primarySmtpAddress, ">", mailbox.ownerUserUid === userUid && _jsx("span", { className: "text-text-muted", children: " (yours)" })] }, mailbox.uid))) })] })), _jsx("h3", { className: "text-base font-bold", children: hasOwn ? "Add another mailbox" : "Your mailbox" }), _jsx(MailboxCreateForm, { submitLabel: "Create mailbox", defaults: hasOwn ? { domain } : { localPart: "admin", domain, displayName: "Administrator", ownerUserUid: userUid }, onCreated: (mailbox) => {
139
- setMailboxes((prev) => [...prev, mailbox]);
140
- setFormKey((k) => k + 1);
141
- } }, formKey)] }));
204
+ return (_jsxs("div", { className: "flex flex-col gap-5 max-w-xl", children: [error && _jsx(Alert, { children: error }), mailboxes.length > 0 && (_jsxs("div", { children: [_jsx("h3", { className: "text-sm font-bold uppercase tracking-wide mb-2", children: "Mailboxes created" }), _jsx("ul", { className: "text-sm flex flex-col gap-1", children: mailboxes.map((mailbox) => (_jsxs("li", { children: [mailbox.displayName, " <", mailbox.primarySmtpAddress, ">", mailbox.ownerUserUid === userUid && _jsx("span", { className: "text-text-muted", children: " (yours)" })] }, mailbox.uid))) })] })), !loaded ? (_jsx("p", { className: "text-sm text-text-muted", children: "Loading\u2026" })) : (_jsxs(_Fragment, { children: [_jsx("h3", { className: "text-base font-bold", children: hasOwn ? "Add another mailbox" : "Your mailbox" }), _jsx(MailboxCreateForm, { submitLabel: "Create mailbox", defaults: hasOwn ? { domain } : { localPart: "admin", domain, displayName: "Administrator", ownerUserUid: userUid }, onCreated: (mailbox) => {
205
+ setMailboxes((prev) => [...prev, mailbox]);
206
+ setFormKey((k) => k + 1);
207
+ } }, formKey)] }))] }));
142
208
  }
@@ -0,0 +1,75 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import { authApiFetch } from "@rapidmx/react-shared/util/api.js";
6
+ /**
7
+ * The cross-tab sign-out channel - must stay identical to `SIGN_OUT_CHANNEL` in
8
+ * `apps/shared/search/localIndexRpcClient.ts` (the channel `AppShell` listens on and `destroyAllLocalIndexes()`
9
+ * announces on). Duplicated rather than imported so the admin/escrow consoles don't pull the local-search Worker
10
+ * client into their bundles; `test/apps/admin/_components/signOut.test.ts` fails if the two ever drift apart.
11
+ */
12
+ export const CONSOLE_SIGN_OUT_CHANNEL = "rapidmx-localsearch";
13
+ /** How long sign-out waits for auth-server's logout before navigating anyway (same bound as `AppShell`). */
14
+ export const CONSOLE_LOGOUT_TIMEOUT_MS = 3000;
15
+ /**
16
+ * The local search index's pending-deletions `localStorage` key - must stay identical to `PENDING_DELETIONS_KEY`
17
+ * in `apps/shared/search/localIndexRpcClient.ts`, duplicated for the same bundle reason as the channel above
18
+ * (the test checks it). `"*"` is that module's "every index on this device" entry.
19
+ */
20
+ export const CONSOLE_PENDING_DELETIONS_KEY = "rapidmx-localsearch-pending-deletions";
21
+ const ALL_LOCAL_INDEXES = "*";
22
+ /** Records that every local search index on this device must be deleted. The consoles can't delete them
23
+ * themselves (no local-index client here); the next mail page load retries recorded deletions before opening
24
+ * any index. With storage blocked nothing is recorded, and only an open mail tab hearing the broadcast deletes
25
+ * them. */
26
+ function markLocalIndexesForDeletion() {
27
+ try {
28
+ localStorage.setItem(CONSOLE_PENDING_DELETIONS_KEY, JSON.stringify([ALL_LOCAL_INDEXES]));
29
+ }
30
+ catch {
31
+ // See the doc comment.
32
+ }
33
+ }
34
+ /** Tells every other tab of this origin that the session ended (`{ type: "sign-out" }`, `AppShell`'s message).
35
+ * An open mail tab then destroys its unlocked keys and every local search index on the device, and leaves too.
36
+ * A no-op where BroadcastChannel is unavailable. */
37
+ function broadcastSignOut() {
38
+ if (typeof BroadcastChannel === "undefined") {
39
+ return;
40
+ }
41
+ const channel = new BroadcastChannel(CONSOLE_SIGN_OUT_CHANNEL);
42
+ channel.postMessage({ type: "sign-out" });
43
+ channel.close();
44
+ }
45
+ /** Calls auth-server's logout (`POST ${authServerUrl}/api/auth/logout`, credentials included), bounded by
46
+ * `CONSOLE_LOGOUT_TIMEOUT_MS`. Never rejects - a failure must not keep the user from leaving. */
47
+ async function logOutOfAuthServer(authServerUrl) {
48
+ if (!authServerUrl) {
49
+ return;
50
+ }
51
+ const controller = new AbortController();
52
+ const timer = setTimeout(() => controller.abort(), CONSOLE_LOGOUT_TIMEOUT_MS);
53
+ try {
54
+ await authApiFetch(authServerUrl, "/auth/logout", { method: "POST", signal: controller.signal });
55
+ }
56
+ catch {
57
+ // Navigate anyway.
58
+ }
59
+ finally {
60
+ clearTimeout(timer);
61
+ }
62
+ }
63
+ /**
64
+ * Sign-out for `AdminShell`/`EscrowShell`: announces the sign-out to other tabs, ends the auth-server session
65
+ * (clears the auth cookie and invalidates the refresh token - navigating alone would leave the session valid),
66
+ * then navigates to auth-server (or `/`). Mirrors `AppShell.handleSignOut`, except that the consoles hold no
67
+ * unlocked keys and can't delete local search indexes in their own tab: they record every index for deletion
68
+ * (finished by the next mail page load) and rely on an open mail tab hearing the broadcast to delete them now.
69
+ */
70
+ export async function signOutOfConsole(authServerUrl) {
71
+ markLocalIndexesForDeletion();
72
+ broadcastSignOut();
73
+ await logOutOfAuthServer(authServerUrl);
74
+ window.location.href = authServerUrl ?? "/";
75
+ }
@@ -0,0 +1,99 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ ///////////////////////////////////////////////////////////////////////////////
3
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
4
+ // SPDX-License-Identifier: MPL-2.0
5
+ ///////////////////////////////////////////////////////////////////////////////
6
+ import { useRef, useState } from "react";
7
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
8
+ import Button from "@rapidmx/react-shared/components/buttons/Button.js";
9
+ /** Page size for the async-request lists (the server returns them newest first and caps `limit` at 500). */
10
+ export const REQUEST_LIST_PAGE_SIZE = 50;
11
+ /**
12
+ * A newest-first list fetched a page at a time with "Load more". Only the most recently started `reload()`'s
13
+ * responses are applied, so a slow earlier fetch (e.g. the mount fetch racing a reload after a create) can't
14
+ * overwrite a newer list, and a "Load more" that was in flight during a reload is dropped.
15
+ *
16
+ * Paging is by offset, so "Load more" re-reads the previous page alongside the next one and continues after the last
17
+ * row already shown: rows created since shift older rows onto later pages (repeats are skipped), and rows deleted
18
+ * since shift them onto earlier pages (which a plain next-page fetch would silently skip). If that row can't be found
19
+ * in the two pages at all (it was deleted, or more than a page of rows came or went), the list reloads from the start.
20
+ */
21
+ export function usePagedList(fetchPage, errorMessage) {
22
+ const pageSize = REQUEST_LIST_PAGE_SIZE;
23
+ const [items, setItems] = useState([]);
24
+ const [loading, setLoading] = useState(true);
25
+ const [loadError, setLoadError] = useState(null);
26
+ const [hasMore, setHasMore] = useState(false);
27
+ const [loadingMore, setLoadingMore] = useState(false);
28
+ const generation = useRef(0);
29
+ const nextPage = useRef(0);
30
+ const loaded = useRef(items);
31
+ loaded.current = items;
32
+ function describe(err) {
33
+ return err instanceof ApiRequestError ? err.message : errorMessage;
34
+ }
35
+ async function reload() {
36
+ const current = ++generation.current;
37
+ try {
38
+ const data = await fetchPage({ limit: pageSize, page: 0 });
39
+ if (current !== generation.current)
40
+ return;
41
+ setItems(data);
42
+ setHasMore(data.length === pageSize);
43
+ setLoadError(null);
44
+ nextPage.current = 1;
45
+ }
46
+ catch (err) {
47
+ if (current === generation.current)
48
+ setLoadError(describe(err));
49
+ }
50
+ finally {
51
+ if (current === generation.current)
52
+ setLoading(false);
53
+ }
54
+ }
55
+ async function loadMore() {
56
+ const current = generation.current;
57
+ const page = nextPage.current;
58
+ setLoadingMore(true);
59
+ try {
60
+ const [previous, data] = await Promise.all([
61
+ fetchPage({ limit: pageSize, page: page - 1 }),
62
+ fetchPage({ limit: pageSize, page }),
63
+ ]);
64
+ if (current !== generation.current)
65
+ return;
66
+ const window = [...previous, ...data];
67
+ // "Load more" is only offered after a full page, so at least one row is shown.
68
+ const lastShown = loaded.current[loaded.current.length - 1].uid;
69
+ const boundary = window.map((item) => item.uid).lastIndexOf(lastShown);
70
+ if (boundary === -1) {
71
+ await reload();
72
+ return;
73
+ }
74
+ const after = window.slice(boundary + 1);
75
+ setItems((prev) => [...prev, ...after.filter((item) => !prev.some((existing) => existing.uid === item.uid))]);
76
+ setHasMore(data.length === pageSize);
77
+ setLoadError(null);
78
+ nextPage.current = page + 1;
79
+ }
80
+ catch (err) {
81
+ if (current === generation.current)
82
+ setLoadError(describe(err));
83
+ }
84
+ finally {
85
+ setLoadingMore(false);
86
+ }
87
+ }
88
+ function replaceItem(item) {
89
+ setItems((prev) => prev.map((existing) => (existing.uid === item.uid ? item : existing)));
90
+ }
91
+ return { items, loading, loadError, hasMore, loadingMore, reload, loadMore, replaceItem };
92
+ }
93
+ /** The "Load more" button for a `usePagedList()` list - renders nothing once there's nothing more to load. */
94
+ export function LoadMoreButton({ list, label }) {
95
+ if (!list.hasMore) {
96
+ return null;
97
+ }
98
+ return (_jsx("div", { className: "mt-3", children: _jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", loading: list.loadingMore, disabled: list.loadingMore, onClick: () => void list.loadMore(), children: label }) }));
99
+ }