@rapidmx/web-client 0.3.1 → 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 (202) hide show
  1. package/apps/admin/audit-log/index.tsx +35 -8
  2. package/apps/admin/branding/index.tsx +39 -404
  3. package/apps/admin/data-requests/index.tsx +480 -485
  4. package/apps/admin/distribution-lists/[uid].tsx +19 -1
  5. package/apps/admin/domains/[uid].tsx +92 -259
  6. package/apps/admin/encryption-policy/index.tsx +19 -0
  7. package/apps/admin/escrow-scopes/[uid].tsx +348 -237
  8. package/apps/admin/escrow-scopes/new/index.tsx +8 -2
  9. package/apps/admin/index.tsx +118 -82
  10. package/apps/admin/ingest-queue/index.tsx +44 -5
  11. package/apps/admin/mailbox-policy/index.tsx +19 -0
  12. package/apps/admin/mailboxes/[uid].tsx +211 -184
  13. package/apps/admin/mailboxes/new/index.tsx +28 -291
  14. package/apps/admin/plugins/index.tsx +15 -0
  15. package/apps/admin/quarantine/index.tsx +46 -14
  16. package/apps/admin/retention-policy/index.tsx +39 -132
  17. package/apps/admin/setup/index.tsx +15 -0
  18. package/apps/admin/transport-rules/[uid].tsx +30 -1
  19. package/apps/admin/transport-rules/_transportRuleConfig.tsx +38 -2
  20. package/apps/admin/transport-rules/index.tsx +24 -6
  21. package/apps/admin/transport-rules/new/index.tsx +30 -1
  22. package/apps/escrow/_layout.tsx +2 -3
  23. package/apps/escrow/audit-log/index.tsx +196 -168
  24. package/apps/escrow/matters/[uid].tsx +621 -521
  25. package/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.tsx +22 -1
  26. package/apps/shared/components/admin/layout/AdminShell.tsx +251 -210
  27. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -0
  28. package/apps/shared/components/admin/mailboxes/ResourceSettingsCard.tsx +3 -3
  29. package/apps/shared/components/admin/mailboxes/ShareAccessCard.tsx +55 -11
  30. package/apps/shared/components/admin/settings/BrandingForm.tsx +385 -0
  31. package/apps/shared/components/admin/settings/DomainDnsSetup.tsx +187 -0
  32. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +112 -0
  33. package/apps/shared/components/admin/settings/LoadedSettingsForm.tsx +34 -0
  34. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +308 -0
  35. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +152 -0
  36. package/apps/shared/components/admin/settings/PluginsManager.tsx +1235 -0
  37. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +174 -0
  38. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +290 -0
  39. package/apps/shared/components/admin/setup/SetupWizard.tsx +416 -0
  40. package/apps/shared/components/admin/signOut.ts +79 -0
  41. package/apps/shared/components/admin/usePagedList.tsx +129 -0
  42. package/apps/shared/components/calendar/CalendarListSidebar.tsx +120 -76
  43. package/apps/shared/components/calendar/EventModal.tsx +717 -513
  44. package/apps/shared/components/calendar/MonthView.tsx +173 -139
  45. package/apps/shared/components/calendar/RecurrenceEditor.tsx +222 -180
  46. package/apps/shared/components/calendar/SplitDayView.tsx +143 -137
  47. package/apps/shared/components/calendar/TimeGridView.tsx +244 -198
  48. package/apps/shared/components/calendar/allDay.ts +124 -0
  49. package/apps/shared/components/calendar/layout/CalendarShell.tsx +80 -99
  50. package/apps/shared/components/contacts/ContactDetailPane.tsx +100 -21
  51. package/apps/shared/components/contacts/ContactForm.tsx +377 -314
  52. package/apps/shared/components/contacts/ContactsSidebar.tsx +6 -2
  53. package/apps/shared/components/contacts/KeyChangeReview.tsx +192 -0
  54. package/apps/shared/components/contacts/contactKeys.ts +78 -0
  55. package/apps/shared/components/escrow/layout/EscrowShell.tsx +148 -134
  56. package/apps/shared/components/layout/AppShell.tsx +270 -169
  57. package/apps/shared/components/layout/BrandingChrome.tsx +48 -10
  58. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +150 -26
  59. package/apps/shared/components/layout/MailboxProvisioning.tsx +19 -3
  60. package/apps/shared/components/layout/RecoveryCodeUnlock.tsx +350 -0
  61. package/apps/shared/components/layout/UnlockPromptProvider.tsx +257 -0
  62. package/apps/shared/components/mail/ConversationThreadPane.tsx +216 -181
  63. package/apps/shared/components/mail/MessageDetailPane.tsx +799 -76
  64. package/apps/shared/components/mail/compose/ComposeContext.tsx +26 -16
  65. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1652 -765
  66. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -0
  67. package/apps/shared/components/mail/layout/MailShell.tsx +418 -302
  68. package/apps/shared/components/mail/pinnedSigners.ts +124 -0
  69. package/apps/shared/components/mail/verificationSeals.ts +125 -0
  70. package/apps/shared/components/mail/writableMailboxes.ts +101 -0
  71. package/apps/shared/components/rules/RuleBuilder.tsx +311 -276
  72. package/apps/shared/components/settings/layout/SettingsShell.tsx +1 -0
  73. package/apps/shared/mail/findWellKnownFolderUid.ts +13 -0
  74. package/apps/shared/mail/listAllPages.ts +39 -0
  75. package/apps/shared/search/LocalIndexLifecycle.tsx +98 -0
  76. package/apps/shared/search/localIndexBlockCipher.ts +83 -0
  77. package/apps/shared/search/localIndexBuilder.ts +481 -0
  78. package/apps/shared/search/localIndexKey.ts +27 -0
  79. package/apps/shared/search/localIndexRpcClient.ts +316 -0
  80. package/apps/shared/search/localIndexSchema.ts +236 -0
  81. package/apps/shared/search/localIndexSizePreference.ts +88 -0
  82. package/apps/shared/search/localIndexStorage.ts +98 -0
  83. package/apps/shared/search/localIndexVFS.ts +266 -0
  84. package/apps/shared/search/localIndexWorker.ts +926 -0
  85. package/apps/shared/search/searchTier2.ts +79 -0
  86. package/apps/shared/search/wa-sqlite-shims.d.ts +44 -0
  87. package/apps/www/calendar/index.tsx +438 -407
  88. package/apps/www/contacts/[uid].tsx +21 -2
  89. package/apps/www/contacts/index.tsx +148 -17
  90. package/apps/www/index.tsx +1314 -486
  91. package/apps/www/messages/[uid].tsx +23 -7
  92. package/apps/www/settings/auto-reply/index.tsx +134 -129
  93. package/apps/www/settings/booking-types/[uid].tsx +306 -300
  94. package/apps/www/settings/encryption/index.tsx +800 -215
  95. package/apps/www/settings/filters/[uid].tsx +171 -155
  96. package/apps/www/settings/filters/new/index.tsx +8 -1
  97. package/apps/www/settings/focused-inbox/index.tsx +150 -148
  98. package/apps/www/settings/privacy/index.tsx +494 -436
  99. package/apps/www/settings/read-receipts/index.tsx +148 -125
  100. package/apps/www/settings/sharing/index.tsx +274 -0
  101. package/apps/www/tasks/index.tsx +638 -530
  102. package/dist/apps/admin/audit-log/index.js +38 -8
  103. package/dist/apps/admin/branding/index.js +4 -98
  104. package/dist/apps/admin/data-requests/index.js +52 -72
  105. package/dist/apps/admin/distribution-lists/[uid].js +1 -1
  106. package/dist/apps/admin/domains/[uid].js +5 -68
  107. package/dist/apps/admin/encryption-policy/index.js +8 -0
  108. package/dist/apps/admin/escrow-scopes/[uid].js +91 -12
  109. package/dist/apps/admin/escrow-scopes/new/index.js +8 -3
  110. package/dist/apps/admin/index.js +17 -1
  111. package/dist/apps/admin/ingest-queue/index.js +24 -6
  112. package/dist/apps/admin/mailbox-policy/index.js +8 -0
  113. package/dist/apps/admin/mailboxes/[uid].js +20 -4
  114. package/dist/apps/admin/mailboxes/new/index.js +4 -89
  115. package/dist/apps/admin/plugins/index.js +6 -0
  116. package/dist/apps/admin/quarantine/index.js +20 -11
  117. package/dist/apps/admin/retention-policy/index.js +3 -36
  118. package/dist/apps/admin/setup/index.js +6 -0
  119. package/dist/apps/admin/transport-rules/[uid].js +18 -2
  120. package/dist/apps/admin/transport-rules/_transportRuleConfig.js +19 -0
  121. package/dist/apps/admin/transport-rules/index.js +22 -6
  122. package/dist/apps/admin/transport-rules/new/index.js +18 -2
  123. package/dist/apps/escrow/_layout.js +3 -3
  124. package/dist/apps/escrow/audit-log/index.js +26 -1
  125. package/dist/apps/escrow/matters/[uid].js +77 -42
  126. package/dist/apps/shared/components/admin/escrowScopes/EscrowScopeKeyAndHoldersFields.js +11 -2
  127. package/dist/apps/shared/components/admin/layout/AdminShell.js +37 -4
  128. package/dist/apps/shared/components/admin/mailboxes/EscrowScopeCard.js +72 -0
  129. package/dist/apps/shared/components/admin/mailboxes/ResourceSettingsCard.js +3 -3
  130. package/dist/apps/shared/components/admin/mailboxes/ShareAccessCard.js +22 -4
  131. package/dist/apps/shared/components/admin/settings/BrandingForm.js +116 -0
  132. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.js +83 -0
  133. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +62 -0
  134. package/dist/apps/shared/components/admin/settings/LoadedSettingsForm.js +25 -0
  135. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +112 -0
  136. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +74 -0
  137. package/dist/apps/shared/components/admin/settings/PluginsManager.js +572 -0
  138. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +73 -0
  139. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +147 -0
  140. package/dist/apps/shared/components/admin/setup/SetupWizard.js +208 -0
  141. package/dist/apps/shared/components/admin/signOut.js +75 -0
  142. package/dist/apps/shared/components/admin/usePagedList.js +99 -0
  143. package/dist/apps/shared/components/calendar/CalendarListSidebar.js +24 -13
  144. package/dist/apps/shared/components/calendar/EventModal.js +154 -21
  145. package/dist/apps/shared/components/calendar/MonthView.js +12 -5
  146. package/dist/apps/shared/components/calendar/RecurrenceEditor.js +40 -5
  147. package/dist/apps/shared/components/calendar/SplitDayView.js +10 -4
  148. package/dist/apps/shared/components/calendar/TimeGridView.js +23 -7
  149. package/dist/apps/shared/components/calendar/allDay.js +111 -0
  150. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +47 -39
  151. package/dist/apps/shared/components/contacts/ContactDetailPane.js +43 -5
  152. package/dist/apps/shared/components/contacts/ContactForm.js +45 -12
  153. package/dist/apps/shared/components/contacts/ContactsSidebar.js +2 -2
  154. package/dist/apps/shared/components/contacts/KeyChangeReview.js +63 -0
  155. package/dist/apps/shared/components/contacts/contactKeys.js +64 -0
  156. package/dist/apps/shared/components/escrow/layout/EscrowShell.js +24 -5
  157. package/dist/apps/shared/components/layout/AppShell.js +100 -8
  158. package/dist/apps/shared/components/layout/BrandingChrome.js +45 -10
  159. package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +63 -14
  160. package/dist/apps/shared/components/layout/MailboxProvisioning.js +10 -2
  161. package/dist/apps/shared/components/layout/RecoveryCodeUnlock.js +174 -0
  162. package/dist/apps/shared/components/layout/UnlockPromptProvider.js +136 -0
  163. package/dist/apps/shared/components/mail/ConversationThreadPane.js +50 -12
  164. package/dist/apps/shared/components/mail/MessageDetailPane.js +464 -34
  165. package/dist/apps/shared/components/mail/compose/ComposeContext.js +9 -6
  166. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +807 -116
  167. package/dist/apps/shared/components/mail/compose/composeFlushRegistry.js +50 -0
  168. package/dist/apps/shared/components/mail/layout/MailShell.js +116 -41
  169. package/dist/apps/shared/components/mail/pinnedSigners.js +98 -0
  170. package/dist/apps/shared/components/mail/verificationSeals.js +112 -0
  171. package/dist/apps/shared/components/mail/writableMailboxes.js +87 -0
  172. package/dist/apps/shared/components/rules/RuleBuilder.js +34 -6
  173. package/dist/apps/shared/components/settings/layout/SettingsShell.js +1 -0
  174. package/dist/apps/shared/mail/findWellKnownFolderUid.js +12 -0
  175. package/dist/apps/shared/mail/listAllPages.js +25 -0
  176. package/dist/apps/shared/search/LocalIndexLifecycle.js +80 -0
  177. package/dist/apps/shared/search/localIndexBlockCipher.js +63 -0
  178. package/dist/apps/shared/search/localIndexBuilder.js +408 -0
  179. package/dist/apps/shared/search/localIndexKey.js +25 -0
  180. package/dist/apps/shared/search/localIndexRpcClient.js +241 -0
  181. package/dist/apps/shared/search/localIndexSchema.js +185 -0
  182. package/dist/apps/shared/search/localIndexSizePreference.js +78 -0
  183. package/dist/apps/shared/search/localIndexStorage.js +86 -0
  184. package/dist/apps/shared/search/localIndexVFS.js +258 -0
  185. package/dist/apps/shared/search/localIndexWorker.js +687 -0
  186. package/dist/apps/shared/search/searchTier2.js +38 -0
  187. package/dist/apps/www/calendar/index.js +38 -18
  188. package/dist/apps/www/contacts/[uid].js +13 -2
  189. package/dist/apps/www/contacts/index.js +94 -15
  190. package/dist/apps/www/index.js +770 -137
  191. package/dist/apps/www/messages/[uid].js +23 -7
  192. package/dist/apps/www/settings/auto-reply/index.js +9 -4
  193. package/dist/apps/www/settings/booking-types/[uid].js +17 -12
  194. package/dist/apps/www/settings/encryption/index.js +541 -96
  195. package/dist/apps/www/settings/filters/[uid].js +22 -7
  196. package/dist/apps/www/settings/filters/new/index.js +8 -2
  197. package/dist/apps/www/settings/focused-inbox/index.js +3 -1
  198. package/dist/apps/www/settings/privacy/index.js +57 -22
  199. package/dist/apps/www/settings/read-receipts/index.js +10 -3
  200. package/dist/apps/www/settings/sharing/index.js +124 -0
  201. package/dist/apps/www/tasks/index.js +76 -14
  202. package/package.json +3 -2
@@ -0,0 +1,174 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ ///////////////////////////////////////////////////////////////////////////////
3
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
4
+ // SPDX-License-Identifier: MPL-2.0
5
+ ///////////////////////////////////////////////////////////////////////////////
6
+ /**
7
+ * Unlocking with a recovery code, and what has to happen after it. A recovery code is single-use: once it has opened
8
+ * the keys, the user may set a new encryption password (`replacePasswordWrap()`), and then the used code is removed
9
+ * (`consumeRecoveryCode()`). The order matters - react-shared's `replacePasswordWrap()` refuses unless another own
10
+ * unlock method remains, and the not-yet-consumed code is that method.
11
+ *
12
+ * `UnlockPromptProvider` and `KeyEnrollmentGate` both unlock with `startRecoveryUnlock()`, settle whatever was waiting
13
+ * on the unlock straight away, and then show `RecoveryFollowUpModal` for the follow-up steps.
14
+ */
15
+ import { useState } from "react";
16
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
17
+ import { getUnlockedKeys, unlockWithRecoveryCode } from "@rapidmx/react-shared/crypto/keySession.js";
18
+ import { getKeyVault } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
19
+ import { KeysLockedError } from "@rapidmx/react-shared/crypto/masterKey.js";
20
+ import { PasswordWrapReplaceError, consumeRecoveryCode, replacePasswordWrap, } from "@rapidmx/react-shared/crypto/masterKeyWraps.js";
21
+ import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
22
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
23
+ import Button from "@rapidmx/react-shared/components/buttons/Button.js";
24
+ import FormField from "@rapidmx/react-shared/components/forms/FormField.js";
25
+ /** The same minimum every other "set an encryption password" form in this app uses. */
26
+ export const MIN_PASSWORD_LENGTH = 8;
27
+ /** Where recovery codes are regenerated. */
28
+ export const ENCRYPTION_SETTINGS_HREF = "/settings/encryption";
29
+ /** Deliberately generic: a wrong code and a vault with no recovery codes fail the same way. */
30
+ export const RECOVERY_CODE_ERROR = "That recovery code didn't work.";
31
+ export const REPLACE_ROTATED_MESSAGE = "Your encryption keys were changed on another device after you unlocked, so your password wasn't changed and your recovery code wasn't used. Reload the page and unlock again.";
32
+ export const REPLACE_MULTIPLE_PASSWORDS_MESSAGE = "This mailbox has more than one encryption password, so it can't be replaced here. Nothing was changed. Remove the extra password in Settings > Encryption first.";
33
+ export const REPLACE_NO_OTHER_METHOD_MESSAGE = "Your password wasn't changed, because this mailbox would be left with no other way to unlock. Your recovery code may already have been used in another window. Nothing was changed.";
34
+ export const REPLACE_ADD_FAILED_RESTORED_MESSAGE = "Your new password couldn't be saved, so your old password still works. Nothing was changed. Try again.";
35
+ export const REPLACE_ADD_FAILED_NOT_RESTORED_MESSAGE = "Your new password couldn't be saved, and your old password couldn't be put back, so this mailbox has no password right now. Your recovery code still works. Try again, or keep the code for now.";
36
+ export const REPLACE_LOCKED_MESSAGE = "Your encryption keys were locked before your new password could be set, so nothing was changed and your recovery code still works. Unlock with it again to set a new password.";
37
+ export const REPLACE_GENERIC_MESSAGE = "Your new password couldn't be saved. Nothing was changed. Try again.";
38
+ export const CONSUME_FAILED_MESSAGE = "The recovery code you used couldn't be removed, so it may still work. Regenerate your recovery codes in Settings > Encryption to make sure it can't be used again.";
39
+ /**
40
+ * Unlocks `mailboxUid` with a recovery code (normalized by react-shared, so spacing and case don't matter). The
41
+ * vault's `masterKeyGeneration` is read first: if another device rotates the master key at any point after that read,
42
+ * the generation passed to `replacePasswordWrap()` later is stale and the replacement is refused, never written with
43
+ * a dead master key. A failed read just means no generation check. Rejects exactly as `unlockWithRecoveryCode()` does.
44
+ */
45
+ export async function startRecoveryUnlock(mailboxUid, mailboxKeys, code) {
46
+ const expectedMasterKeyGeneration = await getKeyVault(mailboxUid).then((vault) => vault.masterKeyGeneration, () => undefined);
47
+ const result = await unlockWithRecoveryCode(mailboxUid, mailboxKeys, code);
48
+ return {
49
+ mailboxUid,
50
+ recoveryMethodId: result.recoveryMethodId,
51
+ remainingRecoveryCodes: result.remainingRecoveryCodes,
52
+ expectedMasterKeyGeneration,
53
+ unopenableKeys: result.unopenableKeys,
54
+ };
55
+ }
56
+ /** A "use a recovery code instead" / "use your password instead" switch for an unlock form. */
57
+ export function UnlockModeToggle({ mode, disabled, onChange, }) {
58
+ return (_jsx(Button, { type: "button", variant: "text", className: "!w-auto", disabled: disabled, onClick: () => onChange(mode === "password" ? "recovery" : "password"), children: mode === "password" ? "Use a recovery code instead" : "Use your password instead" }));
59
+ }
60
+ function replaceFailure(err) {
61
+ if (err instanceof PasswordWrapReplaceError) {
62
+ switch (err.reason) {
63
+ case "master_key_rotated":
64
+ return { message: REPLACE_ROTATED_MESSAGE, blocked: { message: REPLACE_ROTATED_MESSAGE, reload: true } };
65
+ case "multiple_password_wraps":
66
+ return {
67
+ message: REPLACE_MULTIPLE_PASSWORDS_MESSAGE,
68
+ blocked: { message: REPLACE_MULTIPLE_PASSWORDS_MESSAGE, allowSecondary: true },
69
+ };
70
+ case "no_other_unlock_method":
71
+ return { message: REPLACE_NO_OTHER_METHOD_MESSAGE, blocked: { message: REPLACE_NO_OTHER_METHOD_MESSAGE } };
72
+ default:
73
+ return { message: err.restored ? REPLACE_ADD_FAILED_RESTORED_MESSAGE : REPLACE_ADD_FAILED_NOT_RESTORED_MESSAGE };
74
+ }
75
+ }
76
+ if (err instanceof KeysLockedError) {
77
+ return { message: REPLACE_LOCKED_MESSAGE, blocked: { message: REPLACE_LOCKED_MESSAGE } };
78
+ }
79
+ return { message: err instanceof ApiRequestError ? `${REPLACE_GENERIC_MESSAGE} (${err.message})` : REPLACE_GENERIC_MESSAGE };
80
+ }
81
+ /**
82
+ * The steps after a recovery-code unlock, shown once the keys are already open:
83
+ *
84
+ * 1. Offer a new encryption password. Optional ("Skip") - unless this was the last code, where it's required before the
85
+ * code is used up (otherwise only a forgotten password would remain); then "Keep this code for now" closes without
86
+ * consuming anything.
87
+ * 2. Remove the used code. A failure is reported but never blocks anything - the keys are already open.
88
+ * 3. Say how many codes are left, nudging towards regenerating them at two or fewer.
89
+ *
90
+ * Mount it with a `key` per follow-up so each unlock starts from step 1.
91
+ */
92
+ export function RecoveryFollowUpModal({ followUp, open = true, onDone }) {
93
+ const { mailboxUid, recoveryMethodId, remainingRecoveryCodes, expectedMasterKeyGeneration } = followUp;
94
+ const required = remainingRecoveryCodes === 0;
95
+ const [step, setStep] = useState("password");
96
+ const [newPassword, setNewPassword] = useState("");
97
+ const [confirmPassword, setConfirmPassword] = useState("");
98
+ const [error, setError] = useState(null);
99
+ const [blocked, setBlocked] = useState(null);
100
+ const [busy, setBusy] = useState(false);
101
+ const [passwordSet, setPasswordSet] = useState(false);
102
+ const [consumeFailed, setConsumeFailed] = useState(false);
103
+ async function consume() {
104
+ let failed = !recoveryMethodId;
105
+ if (recoveryMethodId) {
106
+ try {
107
+ await consumeRecoveryCode(mailboxUid, recoveryMethodId);
108
+ }
109
+ catch (err) {
110
+ // 404: already gone (e.g. consumed from another tab) - that's the outcome wanted.
111
+ failed = !(err instanceof ApiRequestError && err.status === 404);
112
+ }
113
+ }
114
+ setConsumeFailed(failed);
115
+ setStep("done");
116
+ }
117
+ async function handleSetPassword(e) {
118
+ e.preventDefault();
119
+ if (newPassword.length < MIN_PASSWORD_LENGTH) {
120
+ setError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters.`);
121
+ return;
122
+ }
123
+ if (newPassword !== confirmPassword) {
124
+ setError("Passwords do not match.");
125
+ return;
126
+ }
127
+ setError(null);
128
+ setBusy(true);
129
+ try {
130
+ // Read now, not at unlock time: an idle timeout or a lock elsewhere may have destroyed the keys since.
131
+ const unlocked = getUnlockedKeys(mailboxUid);
132
+ if (!unlocked || unlocked.destroyed) {
133
+ throw new KeysLockedError();
134
+ }
135
+ // Before consuming - the unused code is the other unlock method that makes replacing safe.
136
+ await replacePasswordWrap(mailboxUid, unlocked, newPassword, expectedMasterKeyGeneration);
137
+ }
138
+ catch (err) {
139
+ const failure = replaceFailure(err);
140
+ setBlocked(failure.blocked ?? null);
141
+ setError(failure.blocked ? null : failure.message);
142
+ setBusy(false);
143
+ return;
144
+ }
145
+ setNewPassword("");
146
+ setConfirmPassword("");
147
+ setPasswordSet(true);
148
+ await consume();
149
+ setBusy(false);
150
+ }
151
+ async function handleSkip() {
152
+ setError(null);
153
+ setBusy(true);
154
+ await consume();
155
+ setBusy(false);
156
+ }
157
+ const title = step === "done" ? "Recovery code used" : "Set a new encryption password";
158
+ const secondary = !blocked || !!blocked.allowSecondary;
159
+ function handleClose() {
160
+ if (busy) {
161
+ return;
162
+ }
163
+ // Closing the password step means the same as its secondary action - never a silent password change, and the
164
+ // last code is never consumed without a new password.
165
+ if (step === "password" && !required && secondary) {
166
+ void handleSkip();
167
+ return;
168
+ }
169
+ onDone();
170
+ }
171
+ return (_jsx(Modal, { open: open, onClose: handleClose, title: title, children: step === "password" ? (_jsxs(_Fragment, { children: [required ? (_jsx("p", { className: "text-sm text-text-muted mb-4", children: "That was your last recovery code. Set a new encryption password before it\u2019s used up - otherwise a password you\u2019ve forgotten would be the only way left to unlock this mailbox." })) : (_jsx("p", { className: "text-sm text-text-muted mb-4", children: "Your mailbox is unlocked. If you\u2019ve forgotten your encryption password, set a new one now. The recovery code you used will then be used up." })), blocked ? (_jsxs(_Fragment, { children: [_jsx(Alert, { children: blocked.message }), _jsxs("div", { className: "flex gap-2", children: [blocked.reload && (_jsx(Button, { type: "button", className: "!w-auto", onClick: () => window.location.reload(), children: "Reload page" })), !secondary && (_jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: onDone, children: "Close" }))] })] })) : (_jsxs("form", { onSubmit: handleSetPassword, children: [error && _jsx(Alert, { children: error }), _jsx(FormField, { label: "New encryption password", htmlFor: "recovery-new-password", children: _jsx("input", { id: "recovery-new-password", type: "password", className: "w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface", value: newPassword, onChange: (e) => setNewPassword(e.target.value), disabled: busy, autoComplete: "new-password", autoFocus: true }) }), _jsx(FormField, { label: "Confirm new password", htmlFor: "recovery-new-password-confirm", children: _jsx("input", { id: "recovery-new-password-confirm", type: "password", className: "w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface", value: confirmPassword, onChange: (e) => setConfirmPassword(e.target.value), disabled: busy, autoComplete: "new-password" }) }), _jsx(Button, { type: "submit", className: "!w-auto", loading: busy, disabled: busy, children: "Set password" })] })), secondary && (_jsx("div", { className: "mt-2", children: required ? (_jsx(Button, { type: "button", variant: "text", className: "!w-auto", disabled: busy, onClick: onDone, children: "Keep this code for now" })) : (_jsx(Button, { type: "button", variant: "text", className: "!w-auto", disabled: busy, onClick: handleSkip, children: "Skip" })) }))] })) : (_jsxs(_Fragment, { children: [passwordSet && _jsx("p", { className: "text-sm mb-3", children: "Your new encryption password is set." }), consumeFailed ? (_jsx("p", { role: "status", className: "mb-3 py-2 px-3 rounded-sm text-sm bg-warning/15 text-text", children: CONSUME_FAILED_MESSAGE })) : (_jsx("p", { className: "text-sm mb-3", children: "The recovery code you used has been used up and won\u2019t work again." })), _jsxs("p", { className: "text-sm mb-3", children: [remainingRecoveryCodes === 0
172
+ ? "You have no recovery codes left."
173
+ : `You have ${remainingRecoveryCodes} recovery ${remainingRecoveryCodes === 1 ? "code" : "codes"} left.`, remainingRecoveryCodes <= 2 && (_jsxs(_Fragment, { children: [" ", "Generate a new set in", " ", _jsx("a", { href: ENCRYPTION_SETTINGS_HREF, className: "text-primary-dark hover:underline", children: "Settings > Encryption" }), " ", "with Regenerate recovery codes."] }))] }), _jsx(Button, { type: "button", className: "!w-auto", onClick: onDone, children: "Done" })] })) }));
174
+ }
@@ -0,0 +1,136 @@
1
+ import { jsxs as _jsxs, 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 { createContext, useCallback, useContext, useRef, useState } from "react";
7
+ import { getUnlockedKeys, unlockWithPassword, UnopenableEncryptionKeyError, } from "@rapidmx/react-shared/crypto/keySession.js";
8
+ import Modal from "@rapidmx/react-shared/components/overlays/Modal.js";
9
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
10
+ import Button from "@rapidmx/react-shared/components/buttons/Button.js";
11
+ import FormField from "@rapidmx/react-shared/components/forms/FormField.js";
12
+ import { RECOVERY_CODE_ERROR, RecoveryFollowUpModal, UnlockModeToggle, startRecoveryUnlock, } from "./RecoveryCodeUnlock.js";
13
+ /** Shown instead of "Incorrect password" when the password was right but the mailbox's encryption key itself
14
+ * won't open (`UnopenableEncryptionKeyError`) - retrying can't fix that, so it must not read as a typo. */
15
+ export const UNOPENABLE_ENCRYPTION_KEY_MESSAGE = "Your password is correct, but one of your keys couldn't be opened, so encrypted mail can't be read or sent from this mailbox. Trying again won't help - contact support.";
16
+ /** `UNOPENABLE_ENCRYPTION_KEY_MESSAGE`'s counterpart for a recovery-code unlock. */
17
+ export const UNOPENABLE_ENCRYPTION_KEY_RECOVERY_MESSAGE = "Your recovery code is correct, but one of your keys couldn't be opened, so encrypted mail can't be read or sent from this mailbox. Trying again won't help - contact support.";
18
+ /** The error text for a failed `unlockWithPassword()` (or, with `method` `"recovery"`, `unlockWithRecoveryCode()`). */
19
+ export function unlockErrorMessage(err, method = "password") {
20
+ // Deliberately generic otherwise - see `unlockWithPassword()`'s own doc comment: a wrong password and a
21
+ // missing password wrap fail the same way, and telling them apart would help someone guessing passwords.
22
+ if (method === "recovery") {
23
+ return err instanceof UnopenableEncryptionKeyError ? UNOPENABLE_ENCRYPTION_KEY_RECOVERY_MESSAGE : RECOVERY_CODE_ERROR;
24
+ }
25
+ return err instanceof UnopenableEncryptionKeyError ? UNOPENABLE_ENCRYPTION_KEY_MESSAGE : "Incorrect password.";
26
+ }
27
+ /**
28
+ * A non-blocking notice after an unlock that succeeded without some signing keys (`UnlockResult.unopenableKeys`):
29
+ * mail can still be read, but not signed with those keys on this device.
30
+ */
31
+ export function UnopenableKeysNotice({ fingerprints, onDismiss }) {
32
+ return (_jsxs("div", { role: "status", className: "fixed bottom-4 right-4 z-50 max-w-sm bg-surface border border-border rounded-md p-3 text-sm shadow-lg flex flex-col gap-2", children: [_jsxs("p", { children: ["Unlocked, but ", fingerprints.length === 1 ? "one of your signing keys" : `${fingerprints.length} of your signing keys`, " ", "couldn\u2019t be opened, so mail can\u2019t be signed with ", fingerprints.length === 1 ? "it" : "them", ". Contact support."] }), _jsx("p", { className: "font-mono text-xs break-all text-text-muted", children: fingerprints.join(", ") }), _jsx("div", { children: _jsx(Button, { type: "button", variant: "secondary", className: "!w-auto", onClick: onDismiss, children: "Dismiss" }) })] }));
33
+ }
34
+ const UnlockPromptContext = createContext(null);
35
+ /**
36
+ * The on-demand counterpart to `KeyEnrollmentGate`'s blocking, first-sign-in-only provisioning flow.
37
+ * Per `specs/end-to-end_encryption.md`, unlocking is only actually *required* to (1) sign or encrypt an
38
+ * outgoing message, (2) read an already-encrypted message, or (3) change encryption settings that touch
39
+ * the master key - not merely to have a mailbox with an existing vault resolve. Mounted once in
40
+ * `AppShell.tsx` (shared by every top-level app shell: Mail, Calendar, Contacts, Tasks, Settings), so
41
+ * any of those three call sites (`ComposeWindow`'s sign/encrypt toggles, `MessageDetailPane`'s encrypted-
42
+ * message view, `Settings > Encryption`) can request an unlock right where it's needed via
43
+ * `useUnlockPrompt()`, instead of the whole app being blocked behind an unlock screen the moment a
44
+ * mailbox happens to resolve - see `KeyEnrollmentGate`'s `blocking` prop, which `MailShell` now sets to
45
+ * `false` for exactly this reason.
46
+ */
47
+ export function UnlockPromptProvider({ children }) {
48
+ const [pending, setPendingState] = useState(null);
49
+ // Mirrors `pending` synchronously, so two requests issued in the same tick see each other.
50
+ const pendingRef = useRef(null);
51
+ const [password, setPassword] = useState("");
52
+ const [error, setError] = useState(null);
53
+ const [unlocking, setUnlocking] = useState(false);
54
+ const [unopenableKeys, setUnopenableKeys] = useState(null);
55
+ const [mode, setMode] = useState("password");
56
+ const [code, setCode] = useState("");
57
+ // The steps after a recovery-code unlock (new password, using up the code). Shown only once the waiters are
58
+ // already settled - see `RecoveryCodeUnlock.tsx`.
59
+ const [followUp, setFollowUp] = useState(null);
60
+ function setPending(next) {
61
+ pendingRef.current = next;
62
+ setPendingState(next);
63
+ }
64
+ const requestUnlock = useCallback((mailboxUid, mailboxKeys) => {
65
+ const existing = getUnlockedKeys(mailboxUid);
66
+ if (existing) {
67
+ return Promise.resolve(existing);
68
+ }
69
+ return new Promise((resolve, reject) => {
70
+ const current = pendingRef.current;
71
+ if (current?.mailboxUid === mailboxUid) {
72
+ current.waiters.push({ resolve, reject });
73
+ return;
74
+ }
75
+ // A different mailbox's dialog is replacing this one - settle its callers rather than leaving
76
+ // their promises hanging forever.
77
+ current?.waiters.forEach((waiter) => waiter.reject(new Error("Unlock superseded by another request.")));
78
+ setPassword("");
79
+ setCode("");
80
+ setMode("password");
81
+ setError(null);
82
+ setPending({ mailboxUid, mailboxKeys, waiters: [{ resolve, reject }] });
83
+ });
84
+ }, []);
85
+ function handleCancel() {
86
+ pendingRef.current?.waiters.forEach((waiter) => waiter.reject(new Error("Unlock cancelled.")));
87
+ setPending(null);
88
+ }
89
+ async function handleSubmit(e) {
90
+ e.preventDefault();
91
+ // Only reachable via the form below, which never renders while `pending` is null.
92
+ const request = pending;
93
+ setError(null);
94
+ setUnlocking(true);
95
+ try {
96
+ const result = await (mode === "recovery"
97
+ ? startRecoveryUnlock(request.mailboxUid, request.mailboxKeys, code)
98
+ : unlockWithPassword(request.mailboxUid, request.mailboxKeys, password));
99
+ const recovery = mode === "recovery" ? result : null;
100
+ // Always reachable: the unlock just populated keySession.ts's session store for
101
+ // this exact mailboxUid, or threw before we get here.
102
+ const unlocked = getUnlockedKeys(request.mailboxUid);
103
+ request.waiters.forEach((waiter) => waiter.resolve(unlocked));
104
+ if (pendingRef.current === request) {
105
+ setPending(null);
106
+ }
107
+ if (result.unopenableKeys.length > 0) {
108
+ setUnopenableKeys(result.unopenableKeys);
109
+ }
110
+ setCode("");
111
+ setFollowUp(recovery);
112
+ }
113
+ catch (err) {
114
+ setError(unlockErrorMessage(err, mode));
115
+ }
116
+ finally {
117
+ setUnlocking(false);
118
+ }
119
+ }
120
+ function handleModeChange(next) {
121
+ setMode(next);
122
+ setError(null);
123
+ }
124
+ return (_jsxs(UnlockPromptContext.Provider, { value: { requestUnlock }, children: [children, unopenableKeys && _jsx(UnopenableKeysNotice, { fingerprints: unopenableKeys, onDismiss: () => setUnopenableKeys(null) }), followUp && (_jsx(RecoveryFollowUpModal, { followUp: followUp, open: !pending, onDone: () => setFollowUp(null) }, `${followUp.mailboxUid}:${followUp.recoveryMethodId}`)), _jsxs(Modal, { open: !!pending, onClose: handleCancel, title: "Unlock your mailbox", children: [_jsx("p", { className: "text-sm text-text-muted mb-5", children: mode === "password"
125
+ ? "Enter your encryption password to continue."
126
+ : "Enter one of your recovery codes to continue. Each code works once." }), error && _jsx(Alert, { children: error }), _jsxs("form", { onSubmit: handleSubmit, children: [mode === "password" ? (_jsx(FormField, { label: "Encryption password", htmlFor: "unlock-prompt-password", children: _jsx("input", { id: "unlock-prompt-password", type: "password", className: "w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface", value: password, onChange: (e) => setPassword(e.target.value), disabled: unlocking, autoComplete: "current-password", autoFocus: true }) })) : (_jsx(FormField, { label: "Recovery code", htmlFor: "unlock-prompt-recovery-code", children: _jsx("input", { id: "unlock-prompt-recovery-code", type: "text", className: "w-full text-sm font-mono border border-border rounded-sm py-1.5 px-2 bg-surface", value: code, onChange: (e) => setCode(e.target.value), disabled: unlocking, autoComplete: "off", autoCapitalize: "characters", spellCheck: false, autoFocus: true }) })), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { type: "submit", loading: unlocking, disabled: unlocking, children: "Unlock" }), _jsx(Button, { type: "button", variant: "secondary", onClick: handleCancel, disabled: unlocking, children: "Cancel" })] })] }), _jsx("div", { className: "mt-3", children: _jsx(UnlockModeToggle, { mode: mode, disabled: unlocking, onChange: handleModeChange }) })] })] }));
127
+ }
128
+ /** Throws outside an `<UnlockPromptProvider>` - every app shell mounts one (see `AppShell.tsx`), so
129
+ * reaching this from any real page is a wiring bug, not a runtime condition to degrade gracefully from. */
130
+ export function useUnlockPrompt() {
131
+ const ctx = useContext(UnlockPromptContext);
132
+ if (!ctx) {
133
+ throw new Error("useUnlockPrompt() must be used within an UnlockPromptProvider (see AppShell.tsx).");
134
+ }
135
+ return ctx;
136
+ }
@@ -3,7 +3,7 @@ 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 { 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 { getMessage, listAttachments, setMessageRead } from "@rapidmx/react-shared/mail/mailApi.js";
9
9
  import MessageDetailPane from "./MessageDetailPane.js";
@@ -22,16 +22,31 @@ export default function ConversationThreadPane({ conversation, folders, labels }
22
22
  const [expandedUids, setExpandedUids] = useState(new Set());
23
23
  const [loading, setLoading] = useState(false);
24
24
  const [error, setError] = useState(null);
25
+ // Bumped on every conversation switch - any in-flight load/attachments/mark-read response carrying an
26
+ // older generation belongs to a superseded conversation and is dropped rather than applied.
27
+ const generationRef = useRef(0);
28
+ // Message uids a mark-read / attachments request has already been issued for in the current
29
+ // generation, so re-running the effect below (every `messages`/`expandedUids` change) while one is
30
+ // still in flight never fires a duplicate - which for mark-read would also carry a stale `version`.
31
+ const markReadRequestedRef = useRef(new Set());
32
+ const attachmentsRequestedRef = useRef(new Set());
25
33
  useEffect(() => {
34
+ const generation = ++generationRef.current;
35
+ markReadRequestedRef.current = new Set();
36
+ attachmentsRequestedRef.current = new Set();
37
+ setMessages({});
38
+ setAttachmentsByUid({});
39
+ setExpandedUids(new Set());
26
40
  if (!conversation) {
27
- setMessages({});
28
- setExpandedUids(new Set());
41
+ setLoading(false);
29
42
  return;
30
43
  }
31
44
  setLoading(true);
32
45
  setError(null);
33
46
  Promise.all(conversation.messageUids.map((uid) => getMessage(uid)))
34
47
  .then((loaded) => {
48
+ if (generation !== generationRef.current)
49
+ return;
35
50
  setMessages(Object.fromEntries(loaded.map((m) => [m.uid, m])));
36
51
  // `messageUids` always has at least one entry — a `ConversationSummary` only ever
37
52
  // exists because it was grouped from real messages (see
@@ -39,32 +54,55 @@ export default function ConversationThreadPane({ conversation, folders, labels }
39
54
  const latestUid = conversation.messageUids[conversation.messageUids.length - 1];
40
55
  setExpandedUids(new Set([latestUid]));
41
56
  })
42
- .catch((err) => setError(err instanceof ApiRequestError ? err.message : "Could not load this conversation."))
43
- .finally(() => setLoading(false));
57
+ .catch((err) => {
58
+ if (generation !== generationRef.current)
59
+ return;
60
+ setError(err instanceof ApiRequestError ? err.message : "Could not load this conversation.");
61
+ })
62
+ .finally(() => {
63
+ if (generation === generationRef.current)
64
+ setLoading(false);
65
+ });
44
66
  }, [conversation?.conversationId]);
45
67
  // Lazily loads attachments and marks-as-read only for messages the reader has actually expanded —
46
68
  // mirrors `mailDetailHooks.ts`'s `useMessageAttachments`/`useMarkMessageRead`, reimplemented here
47
69
  // (rather than called in a loop, which the rules of hooks don't allow) since a thread can expand
48
70
  // more than one message at once, unlike the single-selected-message case those hooks were built for.
49
71
  useEffect(() => {
72
+ const generation = generationRef.current;
50
73
  for (const uid of expandedUids) {
51
74
  const message = messages[uid];
52
75
  if (!message)
53
76
  continue;
54
- if (message.hasAttachments && !attachmentsByUid[uid]) {
77
+ if (message.hasAttachments && !attachmentsRequestedRef.current.has(uid)) {
78
+ attachmentsRequestedRef.current.add(uid);
55
79
  listAttachments(message.folderUid, uid)
56
- .then((loaded) => setAttachmentsByUid((prev) => ({ ...prev, [uid]: loaded })))
80
+ .then((loaded) => {
81
+ if (generation === generationRef.current) {
82
+ setAttachmentsByUid((prev) => ({ ...prev, [uid]: loaded }));
83
+ }
84
+ })
57
85
  .catch(() => {
58
86
  // Best-effort, same as the mark-as-read catch below — `attachmentsByUid[uid] ??
59
- // []` already renders no attachments while this stays unset, so there is nothing
60
- // further to do on failure.
87
+ // []` already renders no attachments while this stays unset; forgetting the
88
+ // request just lets a later re-expand retry it.
89
+ attachmentsRequestedRef.current.delete(uid);
61
90
  });
62
91
  }
63
- if (!message.flags.read) {
92
+ // `message` is this render's latest copy, so the request carries its current `version`.
93
+ if (!message.flags.read && !markReadRequestedRef.current.has(uid)) {
94
+ markReadRequestedRef.current.add(uid);
64
95
  setMessageRead(message, true)
65
- .then((updated) => setMessages((prev) => ({ ...prev, [uid]: updated })))
96
+ .then((updated) => {
97
+ if (generation !== generationRef.current)
98
+ return;
99
+ // Never clobber a newer copy another action (label/classify/...) already patched in.
100
+ setMessages((prev) => (prev[uid].version > updated.version ? prev : { ...prev, [uid]: updated }));
101
+ })
66
102
  .catch(() => {
67
- // Best-effort — matches `useMarkMessageRead`'s own doc comment.
103
+ // Best-effort — matches `useMarkMessageRead`'s own doc comment. Forgetting the
104
+ // request lets a later effect run (e.g. a re-expand) retry with a fresh copy.
105
+ markReadRequestedRef.current.delete(uid);
68
106
  });
69
107
  }
70
108
  }