@rapidmx/web-client 0.20.0 → 0.21.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 (118) hide show
  1. package/README.md +381 -381
  2. package/apps/admin/branding/index.tsx +39 -39
  3. package/apps/admin/data-requests/index.tsx +482 -482
  4. package/apps/admin/domains/[uid].tsx +166 -166
  5. package/apps/admin/escrow-scopes/[uid].tsx +350 -350
  6. package/apps/admin/index.tsx +129 -129
  7. package/apps/admin/mailboxes/[uid].tsx +271 -271
  8. package/apps/admin/mailboxes/new/index.tsx +30 -30
  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 +384 -384
  16. package/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.tsx +238 -238
  17. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -152
  18. package/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.tsx +194 -194
  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/MailboxPolicyForm.tsx +198 -198
  22. package/apps/shared/components/admin/settings/PluginsManager.tsx +2093 -2093
  23. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +182 -182
  24. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -288
  25. package/apps/shared/components/admin/setup/SetupWizard.tsx +446 -446
  26. package/apps/shared/components/admin/usePagedList.tsx +129 -129
  27. package/apps/shared/components/calendar/EventModal.tsx +206 -206
  28. package/apps/shared/components/calendar/MonthView.tsx +185 -185
  29. package/apps/shared/components/calendar/RecurrenceEditor.tsx +227 -227
  30. package/apps/shared/components/calendar/SplitDayView.tsx +144 -144
  31. package/apps/shared/components/calendar/TimeGridView.tsx +246 -246
  32. package/apps/shared/components/calendar/allDay.ts +124 -124
  33. package/apps/shared/components/contacts/ContactForm.tsx +383 -383
  34. package/apps/shared/components/contacts/ContactsToolbar.tsx +103 -103
  35. package/apps/shared/components/escrow/layout/EscrowShell.tsx +155 -155
  36. package/apps/shared/components/layout/AppShell.tsx +463 -461
  37. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -398
  38. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -168
  39. package/apps/shared/components/layout/ResponsiveToolbar.tsx +315 -315
  40. package/apps/shared/components/layout/ThemeSwitch.tsx +84 -84
  41. package/apps/shared/components/layout/UserMenu.tsx +439 -439
  42. package/apps/shared/components/mail/ConversationList.tsx +332 -332
  43. package/apps/shared/components/mail/ConversationThreadPane.tsx +613 -613
  44. package/apps/shared/components/mail/MailSelectionBar.tsx +240 -240
  45. package/apps/shared/components/mail/MenuButton.tsx +404 -404
  46. package/apps/shared/components/mail/MessageDetailPane.tsx +1757 -1757
  47. package/apps/shared/components/mail/compose/ComposeContext.tsx +312 -312
  48. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -422
  49. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1705 -1681
  50. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -147
  51. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -60
  52. package/apps/shared/components/mail/compose/quotedBody.ts +161 -161
  53. package/apps/shared/components/mail/reading/MessageMoreMenu.tsx +258 -258
  54. package/apps/shared/components/mail/reading/MessageSourceDialog.tsx +79 -79
  55. package/apps/shared/components/mail/reading/messageExport.ts +59 -59
  56. package/apps/shared/components/mail/reading/printMessage.ts +99 -99
  57. package/apps/shared/components/mail/reading/useMessageActions.ts +443 -443
  58. package/apps/shared/components/mail/verificationSeals.ts +125 -125
  59. package/apps/shared/components/rules/RuleBuilder.tsx +311 -311
  60. package/apps/shared/components/settings/SigningCertificateCard.tsx +344 -344
  61. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -51
  62. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -62
  63. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -84
  64. package/apps/shared/keyboard/dispatch.ts +124 -124
  65. package/apps/shared/keyboard/format.ts +89 -89
  66. package/apps/shared/keyboard/keymap.ts +114 -114
  67. package/apps/shared/keyboard/registry.ts +65 -65
  68. package/apps/shared/keyboard/targets.ts +79 -79
  69. package/apps/shared/mail/folderOfType.ts +49 -49
  70. package/apps/shared/mail/folderTree.ts +143 -143
  71. package/apps/shared/mail/listAllPages.ts +39 -39
  72. package/apps/shared/mail/newMailNotifications.ts +171 -171
  73. package/apps/shared/mail/outbox/sendJob.ts +445 -445
  74. package/apps/shared/mail/outbox/sendOutcomes.ts +155 -155
  75. package/apps/shared/mail/reportNotices.ts +66 -66
  76. package/apps/shared/mail/senderBlocking.ts +141 -141
  77. package/apps/shared/mail/useMailConnection.ts +205 -205
  78. package/apps/shared/mail/useMailLiveUpdates.ts +277 -277
  79. package/apps/shared/mail/useMailboxUpdateAccess.ts +60 -60
  80. package/apps/shared/mail/useMarkMessageRead.ts +47 -47
  81. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  82. package/apps/shared/notifications/store.ts +560 -560
  83. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -114
  84. package/apps/shared/search/localIndexBuilder.ts +481 -481
  85. package/apps/shared/signing/enrollmentStorage.ts +33 -33
  86. package/apps/shared/signing/enrollmentTracker.ts +385 -385
  87. package/apps/shared/signing/enrollmentView.ts +251 -251
  88. package/apps/shared/signing/useNow.ts +19 -19
  89. package/apps/shared/signing/useSigningEnrollmentWatcher.ts +90 -90
  90. package/apps/shared/styles/app.css +396 -396
  91. package/apps/www/calendar/index.tsx +581 -581
  92. package/apps/www/contacts/[uid].tsx +112 -112
  93. package/apps/www/index.tsx +3012 -3012
  94. package/apps/www/messages/[uid].tsx +139 -139
  95. package/apps/www/settings/auto-reply/index.tsx +136 -136
  96. package/apps/www/settings/blocked-senders/index.tsx +303 -303
  97. package/apps/www/settings/encryption/index.tsx +1290 -1290
  98. package/apps/www/settings/filters/[uid].tsx +179 -179
  99. package/apps/www/settings/filters/index.tsx +105 -105
  100. package/apps/www/settings/filters/new/index.tsx +165 -165
  101. package/apps/www/settings/labels/index.tsx +207 -207
  102. package/apps/www/settings/privacy/index.tsx +495 -495
  103. package/apps/www/settings/profile/index.tsx +251 -251
  104. package/apps/www/settings/read-receipts/index.tsx +150 -150
  105. package/apps/www/settings/sharing/index.tsx +259 -259
  106. package/apps/www/settings/signatures/[uid].tsx +175 -175
  107. package/apps/www/settings/signatures/index.tsx +91 -91
  108. package/apps/www/settings/signatures/new/index.tsx +138 -138
  109. package/apps/www/tasks/index.tsx +654 -654
  110. package/dist/apps/shared/components/admin/layout/AdminShell.js +2 -2
  111. package/dist/apps/shared/components/admin/settings/BrandingForm.js +3 -3
  112. package/dist/apps/shared/components/escrow/layout/EscrowShell.js +2 -2
  113. package/dist/apps/shared/components/layout/AppShell.js +4 -2
  114. package/dist/apps/shared/components/mail/compose/ComposeWindow.d.ts +7 -1
  115. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +20 -1
  116. package/dist/apps/shared/components/mail/reading/printMessage.js +11 -11
  117. package/dist/apps/shared/styles/app.css +396 -396
  118. 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
+ }