@rapidmx/web-client 0.15.1 → 0.16.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 (189) hide show
  1. package/README.md +373 -373
  2. package/apps/admin/branding/index.tsx +39 -39
  3. package/apps/admin/data-requests/index.tsx +482 -480
  4. package/apps/admin/domains/[uid].tsx +164 -164
  5. package/apps/admin/escrow-scopes/[uid].tsx +348 -348
  6. package/apps/admin/index.tsx +127 -124
  7. package/apps/admin/mailboxes/[uid].tsx +269 -224
  8. package/apps/admin/mailboxes/new/index.tsx +28 -28
  9. package/apps/admin/plugins/index.tsx +15 -15
  10. package/apps/admin/retention-policy/index.tsx +39 -39
  11. package/apps/admin/signing-certificates/index.tsx +343 -343
  12. package/apps/escrow/audit-log/index.tsx +196 -196
  13. package/apps/escrow/matters/[uid].tsx +621 -621
  14. package/apps/shared/auth/adminAccess.ts +99 -99
  15. package/apps/shared/components/admin/layout/AdminShell.tsx +378 -378
  16. package/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.tsx +238 -0
  17. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -152
  18. package/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.tsx +194 -0
  19. package/apps/shared/components/admin/settings/BrandingForm.tsx +423 -423
  20. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -119
  21. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +50 -3
  22. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +198 -198
  23. package/apps/shared/components/admin/settings/PluginsManager.tsx +1545 -1545
  24. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +182 -182
  25. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -288
  26. package/apps/shared/components/admin/setup/SetupWizard.tsx +444 -444
  27. package/apps/shared/components/admin/usePagedList.tsx +129 -129
  28. package/apps/shared/components/calendar/EventEditor.tsx +5 -10
  29. package/apps/shared/components/calendar/EventFormParts.tsx +16 -47
  30. package/apps/shared/components/calendar/EventModal.tsx +206 -206
  31. package/apps/shared/components/calendar/GuestInput.tsx +100 -0
  32. package/apps/shared/components/calendar/MonthView.tsx +185 -185
  33. package/apps/shared/components/calendar/RecurrenceEditor.tsx +227 -227
  34. package/apps/shared/components/calendar/RequestChangeForm.tsx +23 -54
  35. package/apps/shared/components/calendar/SplitDayView.tsx +144 -144
  36. package/apps/shared/components/calendar/TimeGridView.tsx +246 -246
  37. package/apps/shared/components/calendar/allDay.ts +124 -124
  38. package/apps/shared/components/calendar/eventForm.ts +2 -2
  39. package/apps/shared/components/calendar/eventFormat.ts +49 -22
  40. package/apps/shared/components/calendar/layout/CalendarShell.tsx +201 -200
  41. package/apps/shared/components/contacts/ContactForm.tsx +383 -383
  42. package/apps/shared/components/contacts/ContactsSidebar.tsx +1 -1
  43. package/apps/shared/components/contacts/ContactsToolbar.tsx +103 -98
  44. package/apps/shared/components/contacts/layout/ContactsShell.tsx +217 -216
  45. package/apps/shared/components/escrow/layout/EscrowShell.tsx +155 -155
  46. package/apps/shared/components/layout/AppShell.tsx +480 -480
  47. package/apps/shared/components/layout/FloatingActionButton.tsx +31 -0
  48. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -398
  49. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -168
  50. package/apps/shared/components/layout/ResponsiveToolbar.tsx +315 -315
  51. package/apps/shared/components/layout/ThemeSwitch.tsx +84 -84
  52. package/apps/shared/components/layout/UserMenu.tsx +439 -424
  53. package/apps/shared/components/mail/ConversationList.tsx +323 -323
  54. package/apps/shared/components/mail/ConversationThreadPane.tsx +612 -491
  55. package/apps/shared/components/mail/MailSelectionBar.tsx +236 -227
  56. package/apps/shared/components/mail/MessageDetailPane.tsx +1559 -1559
  57. package/apps/shared/components/mail/compose/ComposeContext.tsx +312 -312
  58. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -422
  59. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1681 -1677
  60. package/apps/shared/components/mail/compose/RecipientInput.tsx +54 -11
  61. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -147
  62. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -60
  63. package/apps/shared/components/mail/compose/quotedBody.ts +161 -161
  64. package/apps/shared/components/mail/layout/FolderBadgeChip.tsx +21 -0
  65. package/apps/shared/components/mail/layout/MailShell.tsx +137 -113
  66. package/apps/shared/components/mail/layout/SidebarSection.tsx +66 -0
  67. package/apps/shared/components/mail/reading/PendingMessageCard.tsx +68 -0
  68. package/apps/shared/components/mail/verificationSeals.ts +125 -125
  69. package/apps/shared/components/rules/RuleBuilder.tsx +311 -311
  70. package/apps/shared/components/settings/SigningCertificateCard.tsx +344 -344
  71. package/apps/shared/components/settings/layout/SettingsShell.tsx +255 -254
  72. package/apps/shared/components/tasks/TasksSidebar.tsx +1 -1
  73. package/apps/shared/components/tasks/layout/TasksShell.tsx +218 -217
  74. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -51
  75. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -62
  76. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -84
  77. package/apps/shared/keyboard/dispatch.ts +124 -124
  78. package/apps/shared/keyboard/format.ts +89 -89
  79. package/apps/shared/keyboard/keymap.ts +114 -114
  80. package/apps/shared/keyboard/registry.ts +65 -65
  81. package/apps/shared/keyboard/targets.ts +79 -79
  82. package/apps/shared/mail/folderCounts.ts +17 -0
  83. package/apps/shared/mail/folderTree.ts +143 -143
  84. package/apps/shared/mail/listAllPages.ts +39 -39
  85. package/apps/shared/mail/newMailNotifications.ts +171 -171
  86. package/apps/shared/mail/outbox/outgoingReplies.ts +192 -0
  87. package/apps/shared/mail/outbox/sendJob.ts +19 -1
  88. package/apps/shared/mail/outbox/sendOutcomes.ts +13 -4
  89. package/apps/shared/mail/primaryMailbox.ts +71 -0
  90. package/apps/shared/mail/useCollapsedSections.ts +146 -0
  91. package/apps/shared/mail/useMailConnection.ts +205 -203
  92. package/apps/shared/mail/useMailLiveUpdates.ts +277 -277
  93. package/apps/shared/mail/useMarkMessageRead.ts +47 -47
  94. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  95. package/apps/shared/navigation/AppRouter.tsx +300 -300
  96. package/apps/shared/navigation/routerContext.tsx +83 -83
  97. package/apps/shared/notifications/store.ts +560 -560
  98. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -114
  99. package/apps/shared/search/crossMailboxSearch.ts +169 -0
  100. package/apps/shared/search/localIndexBuilder.ts +481 -481
  101. package/apps/shared/signing/enrollmentStorage.ts +33 -33
  102. package/apps/shared/signing/enrollmentTracker.ts +385 -385
  103. package/apps/shared/signing/enrollmentView.ts +251 -251
  104. package/apps/shared/signing/useNow.ts +19 -19
  105. package/apps/shared/signing/useSigningEnrollmentWatcher.ts +90 -90
  106. package/apps/shared/styles/app.css +396 -386
  107. package/apps/www/calendar/index.tsx +578 -571
  108. package/apps/www/contacts/[uid].tsx +109 -109
  109. package/apps/www/contacts/index.tsx +6 -0
  110. package/apps/www/index.tsx +2847 -2479
  111. package/apps/www/messages/[uid].tsx +135 -135
  112. package/apps/www/settings/auto-reply/index.tsx +133 -133
  113. package/apps/www/settings/encryption/index.tsx +1287 -1287
  114. package/apps/www/settings/filters/[uid].tsx +176 -176
  115. package/apps/www/settings/filters/index.tsx +102 -102
  116. package/apps/www/settings/filters/new/index.tsx +140 -140
  117. package/apps/www/settings/labels/index.tsx +204 -204
  118. package/apps/www/settings/privacy/index.tsx +492 -492
  119. package/apps/www/settings/profile/index.tsx +248 -248
  120. package/apps/www/settings/read-receipts/index.tsx +147 -147
  121. package/apps/www/settings/sharing/index.tsx +256 -256
  122. package/apps/www/settings/signatures/[uid].tsx +172 -172
  123. package/apps/www/settings/signatures/index.tsx +88 -88
  124. package/apps/www/settings/signatures/new/index.tsx +135 -135
  125. package/apps/www/tasks/index.tsx +649 -649
  126. package/dist/apps/admin/data-requests/index.js +1 -1
  127. package/dist/apps/admin/index.js +2 -1
  128. package/dist/apps/admin/mailboxes/[uid].js +12 -2
  129. package/dist/apps/shared/components/admin/layout/AdminShell.js +2 -2
  130. package/dist/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.d.ts +35 -0
  131. package/dist/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.js +115 -0
  132. package/dist/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.d.ts +16 -0
  133. package/dist/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.js +92 -0
  134. package/dist/apps/shared/components/admin/settings/BrandingForm.js +3 -3
  135. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +25 -3
  136. package/dist/apps/shared/components/calendar/EventEditor.js +5 -10
  137. package/dist/apps/shared/components/calendar/EventFormParts.d.ts +3 -2
  138. package/dist/apps/shared/components/calendar/EventFormParts.js +5 -16
  139. package/dist/apps/shared/components/calendar/GuestInput.d.ts +45 -0
  140. package/dist/apps/shared/components/calendar/GuestInput.js +30 -0
  141. package/dist/apps/shared/components/calendar/RequestChangeForm.js +11 -22
  142. package/dist/apps/shared/components/calendar/eventForm.d.ts +2 -2
  143. package/dist/apps/shared/components/calendar/eventFormat.d.ts +21 -8
  144. package/dist/apps/shared/components/calendar/eventFormat.js +50 -23
  145. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +3 -2
  146. package/dist/apps/shared/components/contacts/ContactsSidebar.js +1 -1
  147. package/dist/apps/shared/components/contacts/ContactsToolbar.d.ts +3 -1
  148. package/dist/apps/shared/components/contacts/ContactsToolbar.js +4 -2
  149. package/dist/apps/shared/components/contacts/layout/ContactsShell.js +4 -3
  150. package/dist/apps/shared/components/layout/FloatingActionButton.d.ts +13 -0
  151. package/dist/apps/shared/components/layout/FloatingActionButton.js +9 -0
  152. package/dist/apps/shared/components/layout/UserMenu.d.ts +4 -1
  153. package/dist/apps/shared/components/layout/UserMenu.js +6 -5
  154. package/dist/apps/shared/components/mail/ConversationThreadPane.js +127 -22
  155. package/dist/apps/shared/components/mail/MailSelectionBar.d.ts +6 -1
  156. package/dist/apps/shared/components/mail/MailSelectionBar.js +3 -3
  157. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +8 -4
  158. package/dist/apps/shared/components/mail/compose/RecipientInput.d.ts +21 -1
  159. package/dist/apps/shared/components/mail/compose/RecipientInput.js +18 -10
  160. package/dist/apps/shared/components/mail/layout/FolderBadgeChip.d.ts +6 -0
  161. package/dist/apps/shared/components/mail/layout/FolderBadgeChip.js +9 -0
  162. package/dist/apps/shared/components/mail/layout/MailShell.d.ts +5 -0
  163. package/dist/apps/shared/components/mail/layout/MailShell.js +64 -45
  164. package/dist/apps/shared/components/mail/layout/SidebarSection.d.ts +23 -0
  165. package/dist/apps/shared/components/mail/layout/SidebarSection.js +16 -0
  166. package/dist/apps/shared/components/mail/reading/PendingMessageCard.d.ts +14 -0
  167. package/dist/apps/shared/components/mail/reading/PendingMessageCard.js +16 -0
  168. package/dist/apps/shared/components/settings/layout/SettingsShell.js +6 -5
  169. package/dist/apps/shared/components/tasks/TasksSidebar.js +1 -1
  170. package/dist/apps/shared/components/tasks/layout/TasksShell.js +4 -3
  171. package/dist/apps/shared/mail/folderCounts.d.ts +10 -0
  172. package/dist/apps/shared/mail/folderCounts.js +12 -0
  173. package/dist/apps/shared/mail/outbox/outgoingReplies.d.ts +80 -0
  174. package/dist/apps/shared/mail/outbox/outgoingReplies.js +131 -0
  175. package/dist/apps/shared/mail/outbox/sendJob.d.ts +5 -1
  176. package/dist/apps/shared/mail/outbox/sendJob.js +14 -1
  177. package/dist/apps/shared/mail/outbox/sendOutcomes.js +13 -4
  178. package/dist/apps/shared/mail/primaryMailbox.d.ts +29 -0
  179. package/dist/apps/shared/mail/primaryMailbox.js +61 -0
  180. package/dist/apps/shared/mail/useCollapsedSections.d.ts +32 -0
  181. package/dist/apps/shared/mail/useCollapsedSections.js +110 -0
  182. package/dist/apps/shared/mail/useMailConnection.js +3 -1
  183. package/dist/apps/shared/search/crossMailboxSearch.d.ts +72 -0
  184. package/dist/apps/shared/search/crossMailboxSearch.js +136 -0
  185. package/dist/apps/shared/styles/app.css +396 -386
  186. package/dist/apps/www/calendar/index.js +3 -2
  187. package/dist/apps/www/contacts/index.js +3 -1
  188. package/dist/apps/www/index.js +426 -189
  189. package/package.json +2 -2
@@ -1,398 +1,398 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import React, { useEffect, useState } from "react";
6
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
7
- import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
8
- import Button from "@rapidmx/react-shared/components/buttons/Button.js";
9
- import FormField from "@rapidmx/react-shared/components/forms/FormField.js";
10
- import { enrollKey, getKeyVault, PublicKey, VaultAlreadyInitializedError } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
11
- import { UnopenableKeysNotice, unlockErrorMessage } from "./UnlockPromptProvider.js";
12
- import { FrameTakeover } from "../../navigation/frameContext.js";
13
- import { RecoveryFollowUp, RecoveryFollowUpModal, UnlockModeToggle, startRecoveryUnlock } from "./RecoveryCodeUnlock.js";
14
- import {
15
- ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE,
16
- getUnlockedKeys,
17
- unlockWithPassword,
18
- type UnlockResult,
19
- } from "@rapidmx/react-shared/crypto/keySession.js";
20
- import { buildAad, generateMasterKey, sealWithKey } from "@rapidmx/react-shared/crypto/masterKey.js";
21
- import { buildPasswordWrap, buildRecoveryWraps } from "@rapidmx/react-shared/crypto/masterKeyWraps.js";
22
- import { exportPrivateKeyPkcs8, generateKeyPairWithCsr } from "@rapidmx/react-shared/crypto/keys.js";
23
-
24
- type Status = "checking" | "setup_password" | "enrolling" | "already_set_up" | "show_recovery_codes" | "unlock" | "unlocking" | "ready";
25
-
26
- const MIN_PASSWORD_LENGTH = 8;
27
-
28
- async function provisionEncryptionKey(
29
- mailboxUid: string,
30
- mailboxAddress: string,
31
- password: string,
32
- ): Promise<{ recoveryCodes: string[] }> {
33
- const mk = generateMasterKey();
34
- const passwordWrap = await buildPasswordWrap(mailboxUid, mk, password);
35
- const { wraps: recoveryWraps, codes: recoveryCodes } = await buildRecoveryWraps(mailboxUid, mk);
36
-
37
- // Only the encryption key is provisioned here. The signing key's spec-required public-CA enrolment
38
- // (RFC 8823 ACME automation) is a real but genuinely asynchronous flow (a live email round-trip with
39
- // a public CA, likely minutes) - it's a deliberate opt-in action in Settings > Encryption
40
- // ("Enable digital signatures"), not something to block first-sign-in mailbox setup on.
41
- const { keyPair, csrPem } = await generateKeyPairWithCsr(mailboxAddress, "encrypt");
42
- const privateKeyRaw = await exportPrivateKeyPkcs8(keyPair.privateKey);
43
- const wrappedKeySealed = await sealWithKey(mk, privateKeyRaw, buildAad(mailboxUid, ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE));
44
-
45
- await enrollKey(mailboxUid, {
46
- useType: "encrypt",
47
- csr: csrPem,
48
- wrappedKey: { ciphertext: wrappedKeySealed.ciphertext, nonce: wrappedKeySealed.nonce, algorithm: "AES-256-GCM" },
49
- masterKeyWraps: [passwordWrap, ...recoveryWraps],
50
- });
51
-
52
- return { recoveryCodes };
53
- }
54
-
55
- export interface KeyEnrollmentGateProps {
56
- /** Undefined while the caller's mailbox hasn't resolved yet (or has none) - renders `children`
57
- * unchanged in that case, so this component can be mounted unconditionally at a stable tree
58
- * position (see this component's own doc comment for why that matters). */
59
- mailboxUid?: string;
60
- mailboxAddress?: string;
61
- /** The mailbox's currently-published public keys (`Mailbox.keys`) - needed to unlock an
62
- * already-enrolled vault (see `unlockWithPassword()`'s own signature), not just to provision a new
63
- * one. Treated as empty when undefined - a mailbox with no public keys published yet has nothing to
64
- * unlock, so this only affects the already-enrolled path. */
65
- mailboxKeys?: PublicKey[];
66
- /**
67
- * `true` (default) preserves this component's original behavior: a mailbox with an existing vault
68
- * but no unlocked session blocks `children` behind a full-page unlock form. Set to `false` for a
69
- * mount point that shouldn't block merely because a mailbox resolved - `MailShell` does this, since
70
- * unlocking is only actually required to sign/encrypt a compose, read an already-encrypted message,
71
- * or change encryption settings (see `UnlockPromptProvider.tsx`'s `useUnlockPrompt()`, which those
72
- * specific call sites use instead). Has no effect on first-time provisioning
73
- * (`setup_password`/`enrolling`/`show_recovery_codes`), which still always blocks regardless - that
74
- * only ever happens once per mailbox and is a genuine prerequisite, not the source of "unlock keeps
75
- * popping up" friction this prop exists to avoid.
76
- */
77
- blocking?: boolean;
78
- /**
79
- * `true` when the caller may provision this mailbox's first encryption key - i.e. they own it and aren't
80
- * an administrator impersonating them. `false` (default, so a caller that forgets it never provisions) for
81
- * a shared/delegated mailbox the caller doesn't own, or an impersonated session: a mailbox with no vault yet then
82
- * renders `children` instead of the "Protect your mailbox" setup, so a delegate never enrolls keys
83
- * (and recovery codes) for someone else's mailbox. Unlocking an existing vault is unaffected.
84
- */
85
- canProvision?: boolean;
86
- children: React.ReactNode;
87
- }
88
-
89
- /**
90
- * Gates a mailbox's normal content behind one-time E2E encryption key setup, per
91
- * `specs/end-to-end_encryption.md`'s "Generate signing and encryption keypairs on the client's device on
92
- * first sign-in." Rendered by `MailShell` wrapping its own returned content unconditionally, not only
93
- * once a mailbox is resolved — mounting this component at a *different* tree position depending on
94
- * `mailboxUid`'s readiness (e.g. only wrapping once ready, rendering bare content beforehand) would make
95
- * `children` (real `AppShell` chrome) itself remount the moment `mailboxUid` resolves, tearing down any
96
- * state/effects it had already started. Always wrapping keeps `AppShell` mounted continuously across
97
- * that transition; this component simply passes `children` through untouched while `mailboxUid` is
98
- * still unresolved, and only starts its own check once a real `mailboxUid` is supplied.
99
- *
100
- * A `getKeyVault()` failure (network error, server not yet wired up to serve this endpoint) also renders
101
- * `children` unchanged rather than blocking mail entirely - encryption is optional and gradual by design
102
- * (the spec's own "near zero frictionless experience" goal), not a hard prerequisite for reading mail.
103
- */
104
- export default function KeyEnrollmentGate({
105
- mailboxUid,
106
- mailboxAddress,
107
- mailboxKeys,
108
- blocking = true,
109
- canProvision = false,
110
- children,
111
- }: KeyEnrollmentGateProps) {
112
- const [status, setStatus] = useState<Status>(mailboxUid ? "checking" : "ready");
113
- const [password, setPassword] = useState("");
114
- const [confirmPassword, setConfirmPassword] = useState("");
115
- const [error, setError] = useState<string | null>(null);
116
- const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
117
- const [codesSaved, setCodesSaved] = useState(false);
118
- const [codesCopied, setCodesCopied] = useState(false);
119
- const [unopenableKeys, setUnopenableKeys] = useState<string[] | null>(null);
120
- const [unlockMode, setUnlockMode] = useState<"password" | "recovery">("password");
121
- const [recoveryCode, setRecoveryCode] = useState("");
122
- // Set after a recovery-code unlock: `children` render at once, with the follow-up steps in a dialog on top.
123
- const [followUp, setFollowUp] = useState<RecoveryFollowUp | null>(null);
124
-
125
- useEffect(() => {
126
- if (!mailboxUid) {
127
- return;
128
- }
129
- // A remount within the same browser session (e.g. navigating between pages) shouldn't re-prompt
130
- // for a password the in-memory session store (`keySession.ts`) already has unwrapped - only a
131
- // fresh session (reload, new tab, post-logout) has nothing there.
132
- if (getUnlockedKeys(mailboxUid)) {
133
- setStatus("ready");
134
- return;
135
- }
136
- let cancelled = false;
137
- getKeyVault(mailboxUid)
138
- .then((vault) => {
139
- if (!cancelled) {
140
- setStatus(vault.wrappedKeys.length > 0 ? "unlock" : canProvision ? "setup_password" : "ready");
141
- }
142
- })
143
- .catch(() => {
144
- if (!cancelled) {
145
- setStatus("ready");
146
- }
147
- });
148
- return () => {
149
- cancelled = true;
150
- };
151
- }, [mailboxUid, canProvision]);
152
-
153
- async function handleUnlock(e: React.FormEvent) {
154
- e.preventDefault();
155
- setError(null);
156
- setStatus("unlocking");
157
- try {
158
- // Only reachable via "unlock", which the effect above only ever sets once mailboxUid was
159
- // defined.
160
- const result: UnlockResult | RecoveryFollowUp = await (unlockMode === "recovery"
161
- ? startRecoveryUnlock(mailboxUid!, mailboxKeys ?? [], recoveryCode)
162
- : unlockWithPassword(mailboxUid!, mailboxKeys ?? [], password));
163
- const recovery = unlockMode === "recovery" ? (result as RecoveryFollowUp) : null;
164
- if (result.unopenableKeys.length > 0) {
165
- setUnopenableKeys(result.unopenableKeys);
166
- }
167
- setRecoveryCode("");
168
- setFollowUp(recovery);
169
- setStatus("ready");
170
- } catch (err) {
171
- // "Incorrect password." (or "That recovery code didn't work.") unless the secret was right but the
172
- // encryption key won't open - see `unlockErrorMessage()`.
173
- setError(unlockErrorMessage(err, unlockMode));
174
- setStatus("unlock");
175
- }
176
- }
177
-
178
- async function handleSetPassword(e: React.FormEvent) {
179
- e.preventDefault();
180
- if (password.length < MIN_PASSWORD_LENGTH) {
181
- setError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters.`);
182
- return;
183
- }
184
- if (password !== confirmPassword) {
185
- setError("Passwords do not match.");
186
- return;
187
- }
188
- setError(null);
189
- setStatus("enrolling");
190
- try {
191
- // The vault was only checked on mount - another tab or device may have set encryption up since.
192
- // Provisioning now would publish a second master key, orphaning whichever setup lost the race, so
193
- // re-check right before generating anything. restapi's enrollKey() also refuses (409) wraps for a
194
- // vault that already has them, for a race inside this window.
195
- // Only reachable via "setup_password", which the effect above only ever sets once mailboxUid
196
- // was defined (and mailboxAddress necessarily came with it - see KeyEnrollmentGateProps).
197
- const fresh = await getKeyVault(mailboxUid!);
198
- if (fresh.wrappedKeys.length > 0 || fresh.masterKeyWraps.length > 0) {
199
- setStatus("already_set_up");
200
- return;
201
- }
202
- const { recoveryCodes: codes } = await provisionEncryptionKey(mailboxUid!, mailboxAddress!, password);
203
- setRecoveryCodes(codes);
204
- setStatus("show_recovery_codes");
205
- } catch (err) {
206
- // Only a 409 that is really "the vault already has wraps" - an unrelated lost optimistic-lock race is shown
207
- // as an ordinary error.
208
- if (err instanceof VaultAlreadyInitializedError) {
209
- setStatus("already_set_up");
210
- return;
211
- }
212
- setError(err instanceof ApiRequestError ? err.message : "Could not set up encryption for this mailbox.");
213
- setStatus("setup_password");
214
- }
215
- }
216
-
217
- async function handleCopyCodes() {
218
- try {
219
- await navigator.clipboard.writeText(recoveryCodes.join("\n"));
220
- setCodesCopied(true);
221
- setTimeout(() => setCodesCopied(false), 2000);
222
- } catch {
223
- // Clipboard access can be denied by the browser - the codes are still selectable/copyable by
224
- // hand from the list below.
225
- }
226
- }
227
-
228
- if (status === "checking") {
229
- return null;
230
- }
231
-
232
- if ((status === "unlock" || status === "unlocking") && blocking) {
233
- const unlocking = status === "unlocking";
234
- return (
235
- <FrameTakeover>
236
- <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
237
- <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
238
- <h1 className="text-lg font-bold mb-2">Unlock your mailbox</h1>
239
- <p className="text-sm text-text-muted mb-5">
240
- {unlockMode === "password"
241
- ? "Enter your encryption password to unlock signing and reading protected mail this session."
242
- : "Enter one of your recovery codes to unlock signing and reading protected mail this session. Each code works once."}
243
- </p>
244
- {error && <Alert>{error}</Alert>}
245
- <form onSubmit={handleUnlock}>
246
- {unlockMode === "password" ? (
247
- <FormField label="Encryption password" htmlFor="key-unlock-password">
248
- <input
249
- id="key-unlock-password"
250
- type="password"
251
- className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
252
- value={password}
253
- onChange={(e) => setPassword(e.target.value)}
254
- disabled={unlocking}
255
- autoComplete="current-password"
256
- />
257
- </FormField>
258
- ) : (
259
- <FormField label="Recovery code" htmlFor="key-unlock-recovery-code">
260
- <input
261
- id="key-unlock-recovery-code"
262
- type="text"
263
- className="w-full text-sm font-mono border border-border rounded-sm py-1.5 px-2 bg-surface"
264
- value={recoveryCode}
265
- onChange={(e) => setRecoveryCode(e.target.value)}
266
- disabled={unlocking}
267
- autoComplete="off"
268
- autoCapitalize="characters"
269
- spellCheck={false}
270
- />
271
- </FormField>
272
- )}
273
- <Button type="submit" loading={unlocking} disabled={unlocking}>
274
- Unlock
275
- </Button>
276
- </form>
277
- <div className="mt-3">
278
- <UnlockModeToggle
279
- mode={unlockMode}
280
- disabled={unlocking}
281
- onChange={(next) => {
282
- setUnlockMode(next);
283
- setError(null);
284
- }}
285
- />
286
- </div>
287
- </div>
288
- </div>
289
- </FrameTakeover>
290
- );
291
- }
292
-
293
- if (status === "setup_password" || status === "enrolling") {
294
- const enrolling = status === "enrolling";
295
- return (
296
- <FrameTakeover>
297
- <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
298
- <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
299
- <h1 className="text-lg font-bold mb-2">Protect your mailbox</h1>
300
- <p className="text-sm text-text-muted mb-5">
301
- Choose a password to protect your encryption keys. This is separate from your sign-in
302
- password and is never sent to the server.
303
- </p>
304
- {error && <Alert>{error}</Alert>}
305
- <form onSubmit={handleSetPassword}>
306
- <FormField label="Encryption password" htmlFor="key-enrollment-password">
307
- <input
308
- id="key-enrollment-password"
309
- type="password"
310
- className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
311
- value={password}
312
- onChange={(e) => setPassword(e.target.value)}
313
- disabled={enrolling}
314
- autoComplete="new-password"
315
- />
316
- </FormField>
317
- <FormField label="Confirm password" htmlFor="key-enrollment-password-confirm">
318
- <input
319
- id="key-enrollment-password-confirm"
320
- type="password"
321
- className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
322
- value={confirmPassword}
323
- onChange={(e) => setConfirmPassword(e.target.value)}
324
- disabled={enrolling}
325
- autoComplete="new-password"
326
- />
327
- </FormField>
328
- <Button type="submit" loading={enrolling} disabled={enrolling}>
329
- Continue
330
- </Button>
331
- </form>
332
- </div>
333
- </div>
334
- </FrameTakeover>
335
- );
336
- }
337
-
338
- if (status === "already_set_up") {
339
- return (
340
- <FrameTakeover>
341
- <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
342
- <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
343
- <h1 className="text-lg font-bold mb-2">Encryption is already set up</h1>
344
- <p className="text-sm text-text-muted mb-5">
345
- This mailbox&rsquo;s encryption was set up in another tab or on another device while this
346
- page was open, so nothing was changed here. Reload the page and unlock with the password
347
- chosen there.
348
- </p>
349
- <Button type="button" onClick={() => window.location.reload()}>
350
- Reload
351
- </Button>
352
- </div>
353
- </div>
354
- </FrameTakeover>
355
- );
356
- }
357
-
358
- if (status === "show_recovery_codes") {
359
- return (
360
- <FrameTakeover>
361
- <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
362
- <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
363
- <h1 className="text-lg font-bold mb-2">Save your recovery codes</h1>
364
- <p className="text-sm text-text-muted mb-5">
365
- If you lose your password, these codes are the only way to recover your encrypted mail.
366
- Each code can be used once. Store them somewhere safe — they will not be shown again.
367
- </p>
368
- <ul className="grid grid-cols-2 gap-2 mb-3 font-mono text-sm">
369
- {recoveryCodes.map((code) => (
370
- <li key={code} className="bg-surface-alt rounded-sm py-1.5 px-2 text-center">
371
- {code}
372
- </li>
373
- ))}
374
- </ul>
375
- <Button type="button" variant="secondary" className="!w-auto mb-5" onClick={handleCopyCodes}>
376
- {codesCopied ? "Copied" : "Copy codes to clipboard"}
377
- </Button>
378
- <label className="flex items-center gap-2 text-sm mb-4">
379
- <input type="checkbox" checked={codesSaved} onChange={(e) => setCodesSaved(e.target.checked)} />
380
- I have saved these recovery codes in a safe place.
381
- </label>
382
- <Button type="button" disabled={!codesSaved} onClick={() => setStatus("ready")}>
383
- Continue
384
- </Button>
385
- </div>
386
- </div>
387
- </FrameTakeover>
388
- );
389
- }
390
-
391
- return (
392
- <>
393
- {children}
394
- {unopenableKeys && <UnopenableKeysNotice fingerprints={unopenableKeys} onDismiss={() => setUnopenableKeys(null)} />}
395
- {followUp && <RecoveryFollowUpModal followUp={followUp} onDone={() => setFollowUp(null)} />}
396
- </>
397
- );
398
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import React, { useEffect, useState } from "react";
6
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
7
+ import Alert from "@rapidmx/react-shared/components/feedback/Alert.js";
8
+ import Button from "@rapidmx/react-shared/components/buttons/Button.js";
9
+ import FormField from "@rapidmx/react-shared/components/forms/FormField.js";
10
+ import { enrollKey, getKeyVault, PublicKey, VaultAlreadyInitializedError } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
11
+ import { UnopenableKeysNotice, unlockErrorMessage } from "./UnlockPromptProvider.js";
12
+ import { FrameTakeover } from "../../navigation/frameContext.js";
13
+ import { RecoveryFollowUp, RecoveryFollowUpModal, UnlockModeToggle, startRecoveryUnlock } from "./RecoveryCodeUnlock.js";
14
+ import {
15
+ ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE,
16
+ getUnlockedKeys,
17
+ unlockWithPassword,
18
+ type UnlockResult,
19
+ } from "@rapidmx/react-shared/crypto/keySession.js";
20
+ import { buildAad, generateMasterKey, sealWithKey } from "@rapidmx/react-shared/crypto/masterKey.js";
21
+ import { buildPasswordWrap, buildRecoveryWraps } from "@rapidmx/react-shared/crypto/masterKeyWraps.js";
22
+ import { exportPrivateKeyPkcs8, generateKeyPairWithCsr } from "@rapidmx/react-shared/crypto/keys.js";
23
+
24
+ type Status = "checking" | "setup_password" | "enrolling" | "already_set_up" | "show_recovery_codes" | "unlock" | "unlocking" | "ready";
25
+
26
+ const MIN_PASSWORD_LENGTH = 8;
27
+
28
+ async function provisionEncryptionKey(
29
+ mailboxUid: string,
30
+ mailboxAddress: string,
31
+ password: string,
32
+ ): Promise<{ recoveryCodes: string[] }> {
33
+ const mk = generateMasterKey();
34
+ const passwordWrap = await buildPasswordWrap(mailboxUid, mk, password);
35
+ const { wraps: recoveryWraps, codes: recoveryCodes } = await buildRecoveryWraps(mailboxUid, mk);
36
+
37
+ // Only the encryption key is provisioned here. The signing key's spec-required public-CA enrolment
38
+ // (RFC 8823 ACME automation) is a real but genuinely asynchronous flow (a live email round-trip with
39
+ // a public CA, likely minutes) - it's a deliberate opt-in action in Settings > Encryption
40
+ // ("Enable digital signatures"), not something to block first-sign-in mailbox setup on.
41
+ const { keyPair, csrPem } = await generateKeyPairWithCsr(mailboxAddress, "encrypt");
42
+ const privateKeyRaw = await exportPrivateKeyPkcs8(keyPair.privateKey);
43
+ const wrappedKeySealed = await sealWithKey(mk, privateKeyRaw, buildAad(mailboxUid, ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE));
44
+
45
+ await enrollKey(mailboxUid, {
46
+ useType: "encrypt",
47
+ csr: csrPem,
48
+ wrappedKey: { ciphertext: wrappedKeySealed.ciphertext, nonce: wrappedKeySealed.nonce, algorithm: "AES-256-GCM" },
49
+ masterKeyWraps: [passwordWrap, ...recoveryWraps],
50
+ });
51
+
52
+ return { recoveryCodes };
53
+ }
54
+
55
+ export interface KeyEnrollmentGateProps {
56
+ /** Undefined while the caller's mailbox hasn't resolved yet (or has none) - renders `children`
57
+ * unchanged in that case, so this component can be mounted unconditionally at a stable tree
58
+ * position (see this component's own doc comment for why that matters). */
59
+ mailboxUid?: string;
60
+ mailboxAddress?: string;
61
+ /** The mailbox's currently-published public keys (`Mailbox.keys`) - needed to unlock an
62
+ * already-enrolled vault (see `unlockWithPassword()`'s own signature), not just to provision a new
63
+ * one. Treated as empty when undefined - a mailbox with no public keys published yet has nothing to
64
+ * unlock, so this only affects the already-enrolled path. */
65
+ mailboxKeys?: PublicKey[];
66
+ /**
67
+ * `true` (default) preserves this component's original behavior: a mailbox with an existing vault
68
+ * but no unlocked session blocks `children` behind a full-page unlock form. Set to `false` for a
69
+ * mount point that shouldn't block merely because a mailbox resolved - `MailShell` does this, since
70
+ * unlocking is only actually required to sign/encrypt a compose, read an already-encrypted message,
71
+ * or change encryption settings (see `UnlockPromptProvider.tsx`'s `useUnlockPrompt()`, which those
72
+ * specific call sites use instead). Has no effect on first-time provisioning
73
+ * (`setup_password`/`enrolling`/`show_recovery_codes`), which still always blocks regardless - that
74
+ * only ever happens once per mailbox and is a genuine prerequisite, not the source of "unlock keeps
75
+ * popping up" friction this prop exists to avoid.
76
+ */
77
+ blocking?: boolean;
78
+ /**
79
+ * `true` when the caller may provision this mailbox's first encryption key - i.e. they own it and aren't
80
+ * an administrator impersonating them. `false` (default, so a caller that forgets it never provisions) for
81
+ * a shared/delegated mailbox the caller doesn't own, or an impersonated session: a mailbox with no vault yet then
82
+ * renders `children` instead of the "Protect your mailbox" setup, so a delegate never enrolls keys
83
+ * (and recovery codes) for someone else's mailbox. Unlocking an existing vault is unaffected.
84
+ */
85
+ canProvision?: boolean;
86
+ children: React.ReactNode;
87
+ }
88
+
89
+ /**
90
+ * Gates a mailbox's normal content behind one-time E2E encryption key setup, per
91
+ * `specs/end-to-end_encryption.md`'s "Generate signing and encryption keypairs on the client's device on
92
+ * first sign-in." Rendered by `MailShell` wrapping its own returned content unconditionally, not only
93
+ * once a mailbox is resolved — mounting this component at a *different* tree position depending on
94
+ * `mailboxUid`'s readiness (e.g. only wrapping once ready, rendering bare content beforehand) would make
95
+ * `children` (real `AppShell` chrome) itself remount the moment `mailboxUid` resolves, tearing down any
96
+ * state/effects it had already started. Always wrapping keeps `AppShell` mounted continuously across
97
+ * that transition; this component simply passes `children` through untouched while `mailboxUid` is
98
+ * still unresolved, and only starts its own check once a real `mailboxUid` is supplied.
99
+ *
100
+ * A `getKeyVault()` failure (network error, server not yet wired up to serve this endpoint) also renders
101
+ * `children` unchanged rather than blocking mail entirely - encryption is optional and gradual by design
102
+ * (the spec's own "near zero frictionless experience" goal), not a hard prerequisite for reading mail.
103
+ */
104
+ export default function KeyEnrollmentGate({
105
+ mailboxUid,
106
+ mailboxAddress,
107
+ mailboxKeys,
108
+ blocking = true,
109
+ canProvision = false,
110
+ children,
111
+ }: KeyEnrollmentGateProps) {
112
+ const [status, setStatus] = useState<Status>(mailboxUid ? "checking" : "ready");
113
+ const [password, setPassword] = useState("");
114
+ const [confirmPassword, setConfirmPassword] = useState("");
115
+ const [error, setError] = useState<string | null>(null);
116
+ const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
117
+ const [codesSaved, setCodesSaved] = useState(false);
118
+ const [codesCopied, setCodesCopied] = useState(false);
119
+ const [unopenableKeys, setUnopenableKeys] = useState<string[] | null>(null);
120
+ const [unlockMode, setUnlockMode] = useState<"password" | "recovery">("password");
121
+ const [recoveryCode, setRecoveryCode] = useState("");
122
+ // Set after a recovery-code unlock: `children` render at once, with the follow-up steps in a dialog on top.
123
+ const [followUp, setFollowUp] = useState<RecoveryFollowUp | null>(null);
124
+
125
+ useEffect(() => {
126
+ if (!mailboxUid) {
127
+ return;
128
+ }
129
+ // A remount within the same browser session (e.g. navigating between pages) shouldn't re-prompt
130
+ // for a password the in-memory session store (`keySession.ts`) already has unwrapped - only a
131
+ // fresh session (reload, new tab, post-logout) has nothing there.
132
+ if (getUnlockedKeys(mailboxUid)) {
133
+ setStatus("ready");
134
+ return;
135
+ }
136
+ let cancelled = false;
137
+ getKeyVault(mailboxUid)
138
+ .then((vault) => {
139
+ if (!cancelled) {
140
+ setStatus(vault.wrappedKeys.length > 0 ? "unlock" : canProvision ? "setup_password" : "ready");
141
+ }
142
+ })
143
+ .catch(() => {
144
+ if (!cancelled) {
145
+ setStatus("ready");
146
+ }
147
+ });
148
+ return () => {
149
+ cancelled = true;
150
+ };
151
+ }, [mailboxUid, canProvision]);
152
+
153
+ async function handleUnlock(e: React.FormEvent) {
154
+ e.preventDefault();
155
+ setError(null);
156
+ setStatus("unlocking");
157
+ try {
158
+ // Only reachable via "unlock", which the effect above only ever sets once mailboxUid was
159
+ // defined.
160
+ const result: UnlockResult | RecoveryFollowUp = await (unlockMode === "recovery"
161
+ ? startRecoveryUnlock(mailboxUid!, mailboxKeys ?? [], recoveryCode)
162
+ : unlockWithPassword(mailboxUid!, mailboxKeys ?? [], password));
163
+ const recovery = unlockMode === "recovery" ? (result as RecoveryFollowUp) : null;
164
+ if (result.unopenableKeys.length > 0) {
165
+ setUnopenableKeys(result.unopenableKeys);
166
+ }
167
+ setRecoveryCode("");
168
+ setFollowUp(recovery);
169
+ setStatus("ready");
170
+ } catch (err) {
171
+ // "Incorrect password." (or "That recovery code didn't work.") unless the secret was right but the
172
+ // encryption key won't open - see `unlockErrorMessage()`.
173
+ setError(unlockErrorMessage(err, unlockMode));
174
+ setStatus("unlock");
175
+ }
176
+ }
177
+
178
+ async function handleSetPassword(e: React.FormEvent) {
179
+ e.preventDefault();
180
+ if (password.length < MIN_PASSWORD_LENGTH) {
181
+ setError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters.`);
182
+ return;
183
+ }
184
+ if (password !== confirmPassword) {
185
+ setError("Passwords do not match.");
186
+ return;
187
+ }
188
+ setError(null);
189
+ setStatus("enrolling");
190
+ try {
191
+ // The vault was only checked on mount - another tab or device may have set encryption up since.
192
+ // Provisioning now would publish a second master key, orphaning whichever setup lost the race, so
193
+ // re-check right before generating anything. restapi's enrollKey() also refuses (409) wraps for a
194
+ // vault that already has them, for a race inside this window.
195
+ // Only reachable via "setup_password", which the effect above only ever sets once mailboxUid
196
+ // was defined (and mailboxAddress necessarily came with it - see KeyEnrollmentGateProps).
197
+ const fresh = await getKeyVault(mailboxUid!);
198
+ if (fresh.wrappedKeys.length > 0 || fresh.masterKeyWraps.length > 0) {
199
+ setStatus("already_set_up");
200
+ return;
201
+ }
202
+ const { recoveryCodes: codes } = await provisionEncryptionKey(mailboxUid!, mailboxAddress!, password);
203
+ setRecoveryCodes(codes);
204
+ setStatus("show_recovery_codes");
205
+ } catch (err) {
206
+ // Only a 409 that is really "the vault already has wraps" - an unrelated lost optimistic-lock race is shown
207
+ // as an ordinary error.
208
+ if (err instanceof VaultAlreadyInitializedError) {
209
+ setStatus("already_set_up");
210
+ return;
211
+ }
212
+ setError(err instanceof ApiRequestError ? err.message : "Could not set up encryption for this mailbox.");
213
+ setStatus("setup_password");
214
+ }
215
+ }
216
+
217
+ async function handleCopyCodes() {
218
+ try {
219
+ await navigator.clipboard.writeText(recoveryCodes.join("\n"));
220
+ setCodesCopied(true);
221
+ setTimeout(() => setCodesCopied(false), 2000);
222
+ } catch {
223
+ // Clipboard access can be denied by the browser - the codes are still selectable/copyable by
224
+ // hand from the list below.
225
+ }
226
+ }
227
+
228
+ if (status === "checking") {
229
+ return null;
230
+ }
231
+
232
+ if ((status === "unlock" || status === "unlocking") && blocking) {
233
+ const unlocking = status === "unlocking";
234
+ return (
235
+ <FrameTakeover>
236
+ <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
237
+ <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
238
+ <h1 className="text-lg font-bold mb-2">Unlock your mailbox</h1>
239
+ <p className="text-sm text-text-muted mb-5">
240
+ {unlockMode === "password"
241
+ ? "Enter your encryption password to unlock signing and reading protected mail this session."
242
+ : "Enter one of your recovery codes to unlock signing and reading protected mail this session. Each code works once."}
243
+ </p>
244
+ {error && <Alert>{error}</Alert>}
245
+ <form onSubmit={handleUnlock}>
246
+ {unlockMode === "password" ? (
247
+ <FormField label="Encryption password" htmlFor="key-unlock-password">
248
+ <input
249
+ id="key-unlock-password"
250
+ type="password"
251
+ className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
252
+ value={password}
253
+ onChange={(e) => setPassword(e.target.value)}
254
+ disabled={unlocking}
255
+ autoComplete="current-password"
256
+ />
257
+ </FormField>
258
+ ) : (
259
+ <FormField label="Recovery code" htmlFor="key-unlock-recovery-code">
260
+ <input
261
+ id="key-unlock-recovery-code"
262
+ type="text"
263
+ className="w-full text-sm font-mono border border-border rounded-sm py-1.5 px-2 bg-surface"
264
+ value={recoveryCode}
265
+ onChange={(e) => setRecoveryCode(e.target.value)}
266
+ disabled={unlocking}
267
+ autoComplete="off"
268
+ autoCapitalize="characters"
269
+ spellCheck={false}
270
+ />
271
+ </FormField>
272
+ )}
273
+ <Button type="submit" loading={unlocking} disabled={unlocking}>
274
+ Unlock
275
+ </Button>
276
+ </form>
277
+ <div className="mt-3">
278
+ <UnlockModeToggle
279
+ mode={unlockMode}
280
+ disabled={unlocking}
281
+ onChange={(next) => {
282
+ setUnlockMode(next);
283
+ setError(null);
284
+ }}
285
+ />
286
+ </div>
287
+ </div>
288
+ </div>
289
+ </FrameTakeover>
290
+ );
291
+ }
292
+
293
+ if (status === "setup_password" || status === "enrolling") {
294
+ const enrolling = status === "enrolling";
295
+ return (
296
+ <FrameTakeover>
297
+ <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
298
+ <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
299
+ <h1 className="text-lg font-bold mb-2">Protect your mailbox</h1>
300
+ <p className="text-sm text-text-muted mb-5">
301
+ Choose a password to protect your encryption keys. This is separate from your sign-in
302
+ password and is never sent to the server.
303
+ </p>
304
+ {error && <Alert>{error}</Alert>}
305
+ <form onSubmit={handleSetPassword}>
306
+ <FormField label="Encryption password" htmlFor="key-enrollment-password">
307
+ <input
308
+ id="key-enrollment-password"
309
+ type="password"
310
+ className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
311
+ value={password}
312
+ onChange={(e) => setPassword(e.target.value)}
313
+ disabled={enrolling}
314
+ autoComplete="new-password"
315
+ />
316
+ </FormField>
317
+ <FormField label="Confirm password" htmlFor="key-enrollment-password-confirm">
318
+ <input
319
+ id="key-enrollment-password-confirm"
320
+ type="password"
321
+ className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
322
+ value={confirmPassword}
323
+ onChange={(e) => setConfirmPassword(e.target.value)}
324
+ disabled={enrolling}
325
+ autoComplete="new-password"
326
+ />
327
+ </FormField>
328
+ <Button type="submit" loading={enrolling} disabled={enrolling}>
329
+ Continue
330
+ </Button>
331
+ </form>
332
+ </div>
333
+ </div>
334
+ </FrameTakeover>
335
+ );
336
+ }
337
+
338
+ if (status === "already_set_up") {
339
+ return (
340
+ <FrameTakeover>
341
+ <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
342
+ <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
343
+ <h1 className="text-lg font-bold mb-2">Encryption is already set up</h1>
344
+ <p className="text-sm text-text-muted mb-5">
345
+ This mailbox&rsquo;s encryption was set up in another tab or on another device while this
346
+ page was open, so nothing was changed here. Reload the page and unlock with the password
347
+ chosen there.
348
+ </p>
349
+ <Button type="button" onClick={() => window.location.reload()}>
350
+ Reload
351
+ </Button>
352
+ </div>
353
+ </div>
354
+ </FrameTakeover>
355
+ );
356
+ }
357
+
358
+ if (status === "show_recovery_codes") {
359
+ return (
360
+ <FrameTakeover>
361
+ <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
362
+ <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
363
+ <h1 className="text-lg font-bold mb-2">Save your recovery codes</h1>
364
+ <p className="text-sm text-text-muted mb-5">
365
+ If you lose your password, these codes are the only way to recover your encrypted mail.
366
+ Each code can be used once. Store them somewhere safe — they will not be shown again.
367
+ </p>
368
+ <ul className="grid grid-cols-2 gap-2 mb-3 font-mono text-sm">
369
+ {recoveryCodes.map((code) => (
370
+ <li key={code} className="bg-surface-alt rounded-sm py-1.5 px-2 text-center">
371
+ {code}
372
+ </li>
373
+ ))}
374
+ </ul>
375
+ <Button type="button" variant="secondary" className="!w-auto mb-5" onClick={handleCopyCodes}>
376
+ {codesCopied ? "Copied" : "Copy codes to clipboard"}
377
+ </Button>
378
+ <label className="flex items-center gap-2 text-sm mb-4">
379
+ <input type="checkbox" checked={codesSaved} onChange={(e) => setCodesSaved(e.target.checked)} />
380
+ I have saved these recovery codes in a safe place.
381
+ </label>
382
+ <Button type="button" disabled={!codesSaved} onClick={() => setStatus("ready")}>
383
+ Continue
384
+ </Button>
385
+ </div>
386
+ </div>
387
+ </FrameTakeover>
388
+ );
389
+ }
390
+
391
+ return (
392
+ <>
393
+ {children}
394
+ {unopenableKeys && <UnopenableKeysNotice fingerprints={unopenableKeys} onDismiss={() => setUnopenableKeys(null)} />}
395
+ {followUp && <RecoveryFollowUpModal followUp={followUp} onDone={() => setFollowUp(null)} />}
396
+ </>
397
+ );
398
+ }