@rapidmx/web-client 0.3.0 → 0.4.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 (102) hide show
  1. package/apps/admin/branding/index.tsx +39 -404
  2. package/apps/admin/domains/[uid].tsx +92 -259
  3. package/apps/admin/encryption-policy/index.tsx +19 -0
  4. package/apps/admin/index.tsx +100 -82
  5. package/apps/admin/mailbox-policy/index.tsx +19 -0
  6. package/apps/admin/mailboxes/new/index.tsx +28 -291
  7. package/apps/admin/plugins/index.tsx +15 -0
  8. package/apps/admin/retention-policy/index.tsx +39 -132
  9. package/apps/admin/setup/index.tsx +15 -0
  10. package/apps/shared/components/admin/layout/AdminShell.tsx +249 -210
  11. package/apps/shared/components/admin/settings/BrandingForm.tsx +374 -0
  12. package/apps/shared/components/admin/settings/DomainDnsSetup.tsx +176 -0
  13. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +104 -0
  14. package/apps/shared/components/admin/settings/LoadedSettingsForm.tsx +34 -0
  15. package/apps/shared/components/admin/settings/MailboxCreateForm.tsx +302 -0
  16. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +119 -0
  17. package/apps/shared/components/admin/settings/PluginsManager.tsx +595 -0
  18. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +98 -0
  19. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +254 -0
  20. package/apps/shared/components/admin/setup/SetupWizard.tsx +300 -0
  21. package/apps/shared/components/calendar/CalendarListSidebar.tsx +120 -76
  22. package/apps/shared/components/calendar/EventModal.tsx +40 -4
  23. package/apps/shared/components/calendar/layout/CalendarShell.tsx +80 -99
  24. package/apps/shared/components/contacts/ContactForm.tsx +38 -4
  25. package/apps/shared/components/layout/AppShell.tsx +198 -169
  26. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +298 -265
  27. package/apps/shared/components/layout/UnlockPromptProvider.tsx +128 -0
  28. package/apps/shared/components/mail/MessageDetailPane.tsx +630 -595
  29. package/apps/shared/components/mail/compose/ComposeContext.tsx +8 -3
  30. package/apps/shared/components/mail/compose/ComposeWindow.tsx +930 -765
  31. package/apps/shared/components/mail/layout/MailShell.tsx +408 -302
  32. package/apps/shared/components/settings/layout/SettingsShell.tsx +1 -0
  33. package/apps/shared/mail/findWellKnownFolderUid.ts +13 -0
  34. package/apps/shared/search/LocalIndexLifecycle.tsx +89 -0
  35. package/apps/shared/search/localIndexBlockCipher.ts +83 -0
  36. package/apps/shared/search/localIndexBuilder.ts +179 -0
  37. package/apps/shared/search/localIndexKey.ts +27 -0
  38. package/apps/shared/search/localIndexRpcClient.ts +116 -0
  39. package/apps/shared/search/localIndexSchema.ts +227 -0
  40. package/apps/shared/search/localIndexSizePreference.ts +88 -0
  41. package/apps/shared/search/localIndexVFS.ts +235 -0
  42. package/apps/shared/search/localIndexWorker.ts +464 -0
  43. package/apps/shared/search/searchTier2.ts +79 -0
  44. package/apps/shared/search/wa-sqlite-shims.d.ts +44 -0
  45. package/apps/www/calendar/index.tsx +31 -21
  46. package/apps/www/contacts/index.tsx +33 -6
  47. package/apps/www/index.tsx +661 -106
  48. package/apps/www/messages/[uid].tsx +5 -1
  49. package/apps/www/settings/encryption/index.tsx +63 -1
  50. package/apps/www/settings/sharing/index.tsx +271 -0
  51. package/apps/www/tasks/index.tsx +53 -4
  52. package/dist/apps/admin/branding/index.js +4 -98
  53. package/dist/apps/admin/domains/[uid].js +5 -68
  54. package/dist/apps/admin/encryption-policy/index.js +8 -0
  55. package/dist/apps/admin/index.js +14 -1
  56. package/dist/apps/admin/mailbox-policy/index.js +8 -0
  57. package/dist/apps/admin/mailboxes/new/index.js +4 -89
  58. package/dist/apps/admin/plugins/index.js +6 -0
  59. package/dist/apps/admin/retention-policy/index.js +3 -36
  60. package/dist/apps/admin/setup/index.js +6 -0
  61. package/dist/apps/shared/components/admin/layout/AdminShell.js +34 -3
  62. package/dist/apps/shared/components/admin/settings/BrandingForm.js +105 -0
  63. package/dist/apps/shared/components/admin/settings/DomainDnsSetup.js +77 -0
  64. package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +57 -0
  65. package/dist/apps/shared/components/admin/settings/LoadedSettingsForm.js +25 -0
  66. package/dist/apps/shared/components/admin/settings/MailboxCreateForm.js +106 -0
  67. package/dist/apps/shared/components/admin/settings/MailboxPolicyForm.js +52 -0
  68. package/dist/apps/shared/components/admin/settings/PluginsManager.js +260 -0
  69. package/dist/apps/shared/components/admin/settings/RetentionPolicyForm.js +44 -0
  70. package/dist/apps/shared/components/admin/setup/EscrowSetupStep.js +131 -0
  71. package/dist/apps/shared/components/admin/setup/SetupWizard.js +142 -0
  72. package/dist/apps/shared/components/calendar/CalendarListSidebar.js +24 -13
  73. package/dist/apps/shared/components/calendar/EventModal.js +16 -4
  74. package/dist/apps/shared/components/calendar/layout/CalendarShell.js +47 -39
  75. package/dist/apps/shared/components/contacts/ContactForm.js +16 -5
  76. package/dist/apps/shared/components/layout/AppShell.js +30 -7
  77. package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +15 -3
  78. package/dist/apps/shared/components/layout/UnlockPromptProvider.js +77 -0
  79. package/dist/apps/shared/components/mail/MessageDetailPane.js +27 -2
  80. package/dist/apps/shared/components/mail/compose/ComposeContext.js +2 -2
  81. package/dist/apps/shared/components/mail/compose/ComposeWindow.js +134 -14
  82. package/dist/apps/shared/components/mail/layout/MailShell.js +106 -40
  83. package/dist/apps/shared/components/settings/layout/SettingsShell.js +1 -0
  84. package/dist/apps/shared/mail/findWellKnownFolderUid.js +12 -0
  85. package/dist/apps/shared/search/LocalIndexLifecycle.js +76 -0
  86. package/dist/apps/shared/search/localIndexBlockCipher.js +63 -0
  87. package/dist/apps/shared/search/localIndexBuilder.js +153 -0
  88. package/dist/apps/shared/search/localIndexKey.js +25 -0
  89. package/dist/apps/shared/search/localIndexRpcClient.js +78 -0
  90. package/dist/apps/shared/search/localIndexSchema.js +179 -0
  91. package/dist/apps/shared/search/localIndexSizePreference.js +78 -0
  92. package/dist/apps/shared/search/localIndexVFS.js +230 -0
  93. package/dist/apps/shared/search/localIndexWorker.js +341 -0
  94. package/dist/apps/shared/search/searchTier2.js +38 -0
  95. package/dist/apps/www/calendar/index.js +14 -12
  96. package/dist/apps/www/contacts/index.js +15 -6
  97. package/dist/apps/www/index.js +496 -94
  98. package/dist/apps/www/messages/[uid].js +5 -1
  99. package/dist/apps/www/settings/encryption/index.js +30 -2
  100. package/dist/apps/www/settings/sharing/index.js +128 -0
  101. package/dist/apps/www/tasks/index.js +27 -5
  102. package/package.json +3 -2
@@ -1,265 +1,298 @@
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 } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
11
- import {
12
- ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE,
13
- getUnlockedKeys,
14
- unlockWithPassword,
15
- } from "@rapidmx/react-shared/crypto/keySession.js";
16
- import { buildAad, generateMasterKey, sealWithKey } from "@rapidmx/react-shared/crypto/masterKey.js";
17
- import { buildPasswordWrap, buildRecoveryWraps } from "@rapidmx/react-shared/crypto/masterKeyWraps.js";
18
- import { exportPrivateKeyPkcs8, generateKeyPairWithCsr } from "@rapidmx/react-shared/crypto/keys.js";
19
-
20
- type Status = "checking" | "setup_password" | "enrolling" | "show_recovery_codes" | "unlock" | "unlocking" | "ready";
21
-
22
- const MIN_PASSWORD_LENGTH = 8;
23
-
24
- async function provisionEncryptionKey(
25
- mailboxUid: string,
26
- mailboxAddress: string,
27
- password: string,
28
- ): Promise<{ recoveryCodes: string[] }> {
29
- const mk = generateMasterKey();
30
- const passwordWrap = await buildPasswordWrap(mailboxUid, mk, password);
31
- const { wraps: recoveryWraps, codes: recoveryCodes } = await buildRecoveryWraps(mailboxUid, mk);
32
-
33
- // Only the encryption key is provisioned here. The signing key's spec-required public-CA enrolment
34
- // (RFC 8823 ACME automation) is a real but genuinely asynchronous flow (a live email round-trip with
35
- // a public CA, likely minutes) - it's a deliberate opt-in action in Settings > Encryption
36
- // ("Enable digital signatures"), not something to block first-sign-in mailbox setup on.
37
- const { keyPair, csrPem } = await generateKeyPairWithCsr(mailboxAddress, "encrypt");
38
- const privateKeyRaw = await exportPrivateKeyPkcs8(keyPair.privateKey);
39
- const wrappedKeySealed = await sealWithKey(mk, privateKeyRaw, buildAad(mailboxUid, ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE));
40
-
41
- await enrollKey(mailboxUid, {
42
- useType: "encrypt",
43
- csr: csrPem,
44
- wrappedKey: { ciphertext: wrappedKeySealed.ciphertext, nonce: wrappedKeySealed.nonce, algorithm: "AES-256-GCM" },
45
- masterKeyWraps: [passwordWrap, ...recoveryWraps],
46
- });
47
-
48
- return { recoveryCodes };
49
- }
50
-
51
- export interface KeyEnrollmentGateProps {
52
- /** Undefined while the caller's mailbox hasn't resolved yet (or has none) - renders `children`
53
- * unchanged in that case, so this component can be mounted unconditionally at a stable tree
54
- * position (see this component's own doc comment for why that matters). */
55
- mailboxUid?: string;
56
- mailboxAddress?: string;
57
- /** The mailbox's currently-published public keys (`Mailbox.keys`) - needed to unlock an
58
- * already-enrolled vault (see `unlockWithPassword()`'s own signature), not just to provision a new
59
- * one. Treated as empty when undefined - a mailbox with no public keys published yet has nothing to
60
- * unlock, so this only affects the already-enrolled path. */
61
- mailboxKeys?: PublicKey[];
62
- children: React.ReactNode;
63
- }
64
-
65
- /**
66
- * Gates a mailbox's normal content behind one-time E2E encryption key setup, per
67
- * `specs/end-to-end_encryption.md`'s "Generate signing and encryption keypairs on the client's device on
68
- * first sign-in." Rendered by `MailShell` wrapping its own returned content unconditionally, not only
69
- * once a mailbox is resolved — mounting this component at a *different* tree position depending on
70
- * `mailboxUid`'s readiness (e.g. only wrapping once ready, rendering bare content beforehand) would make
71
- * `children` (real `AppShell` chrome) itself remount the moment `mailboxUid` resolves, tearing down any
72
- * state/effects it had already started. Always wrapping keeps `AppShell` mounted continuously across
73
- * that transition; this component simply passes `children` through untouched while `mailboxUid` is
74
- * still unresolved, and only starts its own check once a real `mailboxUid` is supplied.
75
- *
76
- * A `getKeyVault()` failure (network error, server not yet wired up to serve this endpoint) also renders
77
- * `children` unchanged rather than blocking mail entirely - encryption is optional and gradual by design
78
- * (the spec's own "near zero frictionless experience" goal), not a hard prerequisite for reading mail.
79
- */
80
- export default function KeyEnrollmentGate({ mailboxUid, mailboxAddress, mailboxKeys, children }: KeyEnrollmentGateProps) {
81
- const [status, setStatus] = useState<Status>(mailboxUid ? "checking" : "ready");
82
- const [password, setPassword] = useState("");
83
- const [confirmPassword, setConfirmPassword] = useState("");
84
- const [error, setError] = useState<string | null>(null);
85
- const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
86
- const [codesSaved, setCodesSaved] = useState(false);
87
-
88
- useEffect(() => {
89
- if (!mailboxUid) {
90
- return;
91
- }
92
- // A remount within the same browser session (e.g. navigating between pages) shouldn't re-prompt
93
- // for a password the in-memory session store (`keySession.ts`) already has unwrapped - only a
94
- // fresh session (reload, new tab, post-logout) has nothing there.
95
- if (getUnlockedKeys(mailboxUid)) {
96
- setStatus("ready");
97
- return;
98
- }
99
- let cancelled = false;
100
- getKeyVault(mailboxUid)
101
- .then((vault) => {
102
- if (!cancelled) {
103
- setStatus(vault.wrappedKeys.length > 0 ? "unlock" : "setup_password");
104
- }
105
- })
106
- .catch(() => {
107
- if (!cancelled) {
108
- setStatus("ready");
109
- }
110
- });
111
- return () => {
112
- cancelled = true;
113
- };
114
- }, [mailboxUid]);
115
-
116
- async function handleUnlock(e: React.FormEvent) {
117
- e.preventDefault();
118
- setError(null);
119
- setStatus("unlocking");
120
- try {
121
- // Only reachable via "unlock", which the effect above only ever sets once mailboxUid was
122
- // defined.
123
- await unlockWithPassword(mailboxUid!, mailboxKeys ?? [], password);
124
- setStatus("ready");
125
- } catch {
126
- // Deliberately generic - see `unlockWithPassword()`'s own doc comment: it throws the same way
127
- // for "no password wrap enrolled" and "wrong password" today, and this UI has no way to tell
128
- // those apart without leaking which is which to a potential attacker guessing passwords.
129
- setError("Incorrect password.");
130
- setStatus("unlock");
131
- }
132
- }
133
-
134
- async function handleSetPassword(e: React.FormEvent) {
135
- e.preventDefault();
136
- if (password.length < MIN_PASSWORD_LENGTH) {
137
- setError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters.`);
138
- return;
139
- }
140
- if (password !== confirmPassword) {
141
- setError("Passwords do not match.");
142
- return;
143
- }
144
- setError(null);
145
- setStatus("enrolling");
146
- try {
147
- // Only reachable via "setup_password", which the effect above only ever sets once mailboxUid
148
- // was defined (and mailboxAddress necessarily came with it - see KeyEnrollmentGateProps).
149
- const { recoveryCodes: codes } = await provisionEncryptionKey(mailboxUid!, mailboxAddress!, password);
150
- setRecoveryCodes(codes);
151
- setStatus("show_recovery_codes");
152
- } catch (err) {
153
- setError(err instanceof ApiRequestError ? err.message : "Could not set up encryption for this mailbox.");
154
- setStatus("setup_password");
155
- }
156
- }
157
-
158
- if (status === "checking") {
159
- return null;
160
- }
161
-
162
- if (status === "unlock" || status === "unlocking") {
163
- const unlocking = status === "unlocking";
164
- return (
165
- <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
166
- <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
167
- <h1 className="text-lg font-bold mb-2">Unlock your mailbox</h1>
168
- <p className="text-sm text-text-muted mb-5">
169
- Enter your encryption password to unlock signing and reading protected mail this session.
170
- </p>
171
- {error && <Alert>{error}</Alert>}
172
- <form onSubmit={handleUnlock}>
173
- <FormField label="Encryption password" htmlFor="key-unlock-password">
174
- <input
175
- id="key-unlock-password"
176
- type="password"
177
- className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
178
- value={password}
179
- onChange={(e) => setPassword(e.target.value)}
180
- disabled={unlocking}
181
- autoComplete="current-password"
182
- />
183
- </FormField>
184
- <Button type="submit" loading={unlocking} disabled={unlocking}>
185
- Unlock
186
- </Button>
187
- </form>
188
- </div>
189
- </div>
190
- );
191
- }
192
-
193
- if (status === "setup_password" || status === "enrolling") {
194
- const enrolling = status === "enrolling";
195
- return (
196
- <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
197
- <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
198
- <h1 className="text-lg font-bold mb-2">Protect your mailbox</h1>
199
- <p className="text-sm text-text-muted mb-5">
200
- Choose a password to protect your encryption keys. This is separate from your sign-in
201
- password and is never sent to the server.
202
- </p>
203
- {error && <Alert>{error}</Alert>}
204
- <form onSubmit={handleSetPassword}>
205
- <FormField label="Encryption password" htmlFor="key-enrollment-password">
206
- <input
207
- id="key-enrollment-password"
208
- type="password"
209
- className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
210
- value={password}
211
- onChange={(e) => setPassword(e.target.value)}
212
- disabled={enrolling}
213
- autoComplete="new-password"
214
- />
215
- </FormField>
216
- <FormField label="Confirm password" htmlFor="key-enrollment-password-confirm">
217
- <input
218
- id="key-enrollment-password-confirm"
219
- type="password"
220
- className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
221
- value={confirmPassword}
222
- onChange={(e) => setConfirmPassword(e.target.value)}
223
- disabled={enrolling}
224
- autoComplete="new-password"
225
- />
226
- </FormField>
227
- <Button type="submit" loading={enrolling} disabled={enrolling}>
228
- Continue
229
- </Button>
230
- </form>
231
- </div>
232
- </div>
233
- );
234
- }
235
-
236
- if (status === "show_recovery_codes") {
237
- return (
238
- <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
239
- <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
240
- <h1 className="text-lg font-bold mb-2">Save your recovery codes</h1>
241
- <p className="text-sm text-text-muted mb-5">
242
- If you lose your password, these codes are the only way to recover your encrypted mail.
243
- Each code can be used once. Store them somewhere safe — they will not be shown again.
244
- </p>
245
- <ul className="grid grid-cols-2 gap-2 mb-5 font-mono text-sm">
246
- {recoveryCodes.map((code) => (
247
- <li key={code} className="bg-surface-alt rounded-sm py-1.5 px-2 text-center">
248
- {code}
249
- </li>
250
- ))}
251
- </ul>
252
- <label className="flex items-center gap-2 text-sm mb-4">
253
- <input type="checkbox" checked={codesSaved} onChange={(e) => setCodesSaved(e.target.checked)} />
254
- I have saved these recovery codes in a safe place.
255
- </label>
256
- <Button type="button" disabled={!codesSaved} onClick={() => setStatus("ready")}>
257
- Continue
258
- </Button>
259
- </div>
260
- </div>
261
- );
262
- }
263
-
264
- return <>{children}</>;
265
- }
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 } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
11
+ import {
12
+ ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE,
13
+ getUnlockedKeys,
14
+ unlockWithPassword,
15
+ } from "@rapidmx/react-shared/crypto/keySession.js";
16
+ import { buildAad, generateMasterKey, sealWithKey } from "@rapidmx/react-shared/crypto/masterKey.js";
17
+ import { buildPasswordWrap, buildRecoveryWraps } from "@rapidmx/react-shared/crypto/masterKeyWraps.js";
18
+ import { exportPrivateKeyPkcs8, generateKeyPairWithCsr } from "@rapidmx/react-shared/crypto/keys.js";
19
+
20
+ type Status = "checking" | "setup_password" | "enrolling" | "show_recovery_codes" | "unlock" | "unlocking" | "ready";
21
+
22
+ const MIN_PASSWORD_LENGTH = 8;
23
+
24
+ async function provisionEncryptionKey(
25
+ mailboxUid: string,
26
+ mailboxAddress: string,
27
+ password: string,
28
+ ): Promise<{ recoveryCodes: string[] }> {
29
+ const mk = generateMasterKey();
30
+ const passwordWrap = await buildPasswordWrap(mailboxUid, mk, password);
31
+ const { wraps: recoveryWraps, codes: recoveryCodes } = await buildRecoveryWraps(mailboxUid, mk);
32
+
33
+ // Only the encryption key is provisioned here. The signing key's spec-required public-CA enrolment
34
+ // (RFC 8823 ACME automation) is a real but genuinely asynchronous flow (a live email round-trip with
35
+ // a public CA, likely minutes) - it's a deliberate opt-in action in Settings > Encryption
36
+ // ("Enable digital signatures"), not something to block first-sign-in mailbox setup on.
37
+ const { keyPair, csrPem } = await generateKeyPairWithCsr(mailboxAddress, "encrypt");
38
+ const privateKeyRaw = await exportPrivateKeyPkcs8(keyPair.privateKey);
39
+ const wrappedKeySealed = await sealWithKey(mk, privateKeyRaw, buildAad(mailboxUid, ENCRYPTION_PRIVATE_KEY_AAD_PURPOSE));
40
+
41
+ await enrollKey(mailboxUid, {
42
+ useType: "encrypt",
43
+ csr: csrPem,
44
+ wrappedKey: { ciphertext: wrappedKeySealed.ciphertext, nonce: wrappedKeySealed.nonce, algorithm: "AES-256-GCM" },
45
+ masterKeyWraps: [passwordWrap, ...recoveryWraps],
46
+ });
47
+
48
+ return { recoveryCodes };
49
+ }
50
+
51
+ export interface KeyEnrollmentGateProps {
52
+ /** Undefined while the caller's mailbox hasn't resolved yet (or has none) - renders `children`
53
+ * unchanged in that case, so this component can be mounted unconditionally at a stable tree
54
+ * position (see this component's own doc comment for why that matters). */
55
+ mailboxUid?: string;
56
+ mailboxAddress?: string;
57
+ /** The mailbox's currently-published public keys (`Mailbox.keys`) - needed to unlock an
58
+ * already-enrolled vault (see `unlockWithPassword()`'s own signature), not just to provision a new
59
+ * one. Treated as empty when undefined - a mailbox with no public keys published yet has nothing to
60
+ * unlock, so this only affects the already-enrolled path. */
61
+ mailboxKeys?: PublicKey[];
62
+ /**
63
+ * `true` (default) preserves this component's original behavior: a mailbox with an existing vault
64
+ * but no unlocked session blocks `children` behind a full-page unlock form. Set to `false` for a
65
+ * mount point that shouldn't block merely because a mailbox resolved - `MailShell` does this, since
66
+ * unlocking is only actually required to sign/encrypt a compose, read an already-encrypted message,
67
+ * or change encryption settings (see `UnlockPromptProvider.tsx`'s `useUnlockPrompt()`, which those
68
+ * specific call sites use instead). Has no effect on first-time provisioning
69
+ * (`setup_password`/`enrolling`/`show_recovery_codes`), which still always blocks regardless - that
70
+ * only ever happens once per mailbox and is a genuine prerequisite, not the source of "unlock keeps
71
+ * popping up" friction this prop exists to avoid.
72
+ */
73
+ blocking?: boolean;
74
+ children: React.ReactNode;
75
+ }
76
+
77
+ /**
78
+ * Gates a mailbox's normal content behind one-time E2E encryption key setup, per
79
+ * `specs/end-to-end_encryption.md`'s "Generate signing and encryption keypairs on the client's device on
80
+ * first sign-in." Rendered by `MailShell` wrapping its own returned content unconditionally, not only
81
+ * once a mailbox is resolved — mounting this component at a *different* tree position depending on
82
+ * `mailboxUid`'s readiness (e.g. only wrapping once ready, rendering bare content beforehand) would make
83
+ * `children` (real `AppShell` chrome) itself remount the moment `mailboxUid` resolves, tearing down any
84
+ * state/effects it had already started. Always wrapping keeps `AppShell` mounted continuously across
85
+ * that transition; this component simply passes `children` through untouched while `mailboxUid` is
86
+ * still unresolved, and only starts its own check once a real `mailboxUid` is supplied.
87
+ *
88
+ * A `getKeyVault()` failure (network error, server not yet wired up to serve this endpoint) also renders
89
+ * `children` unchanged rather than blocking mail entirely - encryption is optional and gradual by design
90
+ * (the spec's own "near zero frictionless experience" goal), not a hard prerequisite for reading mail.
91
+ */
92
+ export default function KeyEnrollmentGate({
93
+ mailboxUid,
94
+ mailboxAddress,
95
+ mailboxKeys,
96
+ blocking = true,
97
+ children,
98
+ }: KeyEnrollmentGateProps) {
99
+ const [status, setStatus] = useState<Status>(mailboxUid ? "checking" : "ready");
100
+ const [password, setPassword] = useState("");
101
+ const [confirmPassword, setConfirmPassword] = useState("");
102
+ const [error, setError] = useState<string | null>(null);
103
+ const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
104
+ const [codesSaved, setCodesSaved] = useState(false);
105
+ const [codesCopied, setCodesCopied] = useState(false);
106
+
107
+ useEffect(() => {
108
+ if (!mailboxUid) {
109
+ return;
110
+ }
111
+ // A remount within the same browser session (e.g. navigating between pages) shouldn't re-prompt
112
+ // for a password the in-memory session store (`keySession.ts`) already has unwrapped - only a
113
+ // fresh session (reload, new tab, post-logout) has nothing there.
114
+ if (getUnlockedKeys(mailboxUid)) {
115
+ setStatus("ready");
116
+ return;
117
+ }
118
+ let cancelled = false;
119
+ getKeyVault(mailboxUid)
120
+ .then((vault) => {
121
+ if (!cancelled) {
122
+ setStatus(vault.wrappedKeys.length > 0 ? "unlock" : "setup_password");
123
+ }
124
+ })
125
+ .catch(() => {
126
+ if (!cancelled) {
127
+ setStatus("ready");
128
+ }
129
+ });
130
+ return () => {
131
+ cancelled = true;
132
+ };
133
+ }, [mailboxUid]);
134
+
135
+ async function handleUnlock(e: React.FormEvent) {
136
+ e.preventDefault();
137
+ setError(null);
138
+ setStatus("unlocking");
139
+ try {
140
+ // Only reachable via "unlock", which the effect above only ever sets once mailboxUid was
141
+ // defined.
142
+ await unlockWithPassword(mailboxUid!, mailboxKeys ?? [], password);
143
+ setStatus("ready");
144
+ } catch {
145
+ // Deliberately generic - see `unlockWithPassword()`'s own doc comment: it throws the same way
146
+ // for "no password wrap enrolled" and "wrong password" today, and this UI has no way to tell
147
+ // those apart without leaking which is which to a potential attacker guessing passwords.
148
+ setError("Incorrect password.");
149
+ setStatus("unlock");
150
+ }
151
+ }
152
+
153
+ async function handleSetPassword(e: React.FormEvent) {
154
+ e.preventDefault();
155
+ if (password.length < MIN_PASSWORD_LENGTH) {
156
+ setError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters.`);
157
+ return;
158
+ }
159
+ if (password !== confirmPassword) {
160
+ setError("Passwords do not match.");
161
+ return;
162
+ }
163
+ setError(null);
164
+ setStatus("enrolling");
165
+ try {
166
+ // Only reachable via "setup_password", which the effect above only ever sets once mailboxUid
167
+ // was defined (and mailboxAddress necessarily came with it - see KeyEnrollmentGateProps).
168
+ const { recoveryCodes: codes } = await provisionEncryptionKey(mailboxUid!, mailboxAddress!, password);
169
+ setRecoveryCodes(codes);
170
+ setStatus("show_recovery_codes");
171
+ } catch (err) {
172
+ setError(err instanceof ApiRequestError ? err.message : "Could not set up encryption for this mailbox.");
173
+ setStatus("setup_password");
174
+ }
175
+ }
176
+
177
+ async function handleCopyCodes() {
178
+ try {
179
+ await navigator.clipboard.writeText(recoveryCodes.join("\n"));
180
+ setCodesCopied(true);
181
+ setTimeout(() => setCodesCopied(false), 2000);
182
+ } catch {
183
+ // Clipboard access can be denied by the browser - the codes are still selectable/copyable by
184
+ // hand from the list below.
185
+ }
186
+ }
187
+
188
+ if (status === "checking") {
189
+ return null;
190
+ }
191
+
192
+ if ((status === "unlock" || status === "unlocking") && blocking) {
193
+ const unlocking = status === "unlocking";
194
+ return (
195
+ <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
196
+ <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
197
+ <h1 className="text-lg font-bold mb-2">Unlock your mailbox</h1>
198
+ <p className="text-sm text-text-muted mb-5">
199
+ Enter your encryption password to unlock signing and reading protected mail this session.
200
+ </p>
201
+ {error && <Alert>{error}</Alert>}
202
+ <form onSubmit={handleUnlock}>
203
+ <FormField label="Encryption password" htmlFor="key-unlock-password">
204
+ <input
205
+ id="key-unlock-password"
206
+ type="password"
207
+ className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
208
+ value={password}
209
+ onChange={(e) => setPassword(e.target.value)}
210
+ disabled={unlocking}
211
+ autoComplete="current-password"
212
+ />
213
+ </FormField>
214
+ <Button type="submit" loading={unlocking} disabled={unlocking}>
215
+ Unlock
216
+ </Button>
217
+ </form>
218
+ </div>
219
+ </div>
220
+ );
221
+ }
222
+
223
+ if (status === "setup_password" || status === "enrolling") {
224
+ const enrolling = status === "enrolling";
225
+ return (
226
+ <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
227
+ <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
228
+ <h1 className="text-lg font-bold mb-2">Protect your mailbox</h1>
229
+ <p className="text-sm text-text-muted mb-5">
230
+ Choose a password to protect your encryption keys. This is separate from your sign-in
231
+ password and is never sent to the server.
232
+ </p>
233
+ {error && <Alert>{error}</Alert>}
234
+ <form onSubmit={handleSetPassword}>
235
+ <FormField label="Encryption password" htmlFor="key-enrollment-password">
236
+ <input
237
+ id="key-enrollment-password"
238
+ type="password"
239
+ className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
240
+ value={password}
241
+ onChange={(e) => setPassword(e.target.value)}
242
+ disabled={enrolling}
243
+ autoComplete="new-password"
244
+ />
245
+ </FormField>
246
+ <FormField label="Confirm password" htmlFor="key-enrollment-password-confirm">
247
+ <input
248
+ id="key-enrollment-password-confirm"
249
+ type="password"
250
+ className="w-full text-sm border border-border rounded-sm py-1.5 px-2 bg-surface"
251
+ value={confirmPassword}
252
+ onChange={(e) => setConfirmPassword(e.target.value)}
253
+ disabled={enrolling}
254
+ autoComplete="new-password"
255
+ />
256
+ </FormField>
257
+ <Button type="submit" loading={enrolling} disabled={enrolling}>
258
+ Continue
259
+ </Button>
260
+ </form>
261
+ </div>
262
+ </div>
263
+ );
264
+ }
265
+
266
+ if (status === "show_recovery_codes") {
267
+ return (
268
+ <div className="min-h-screen flex items-center justify-center p-8 bg-surface-alt">
269
+ <div className="w-full max-w-md bg-surface border border-border rounded-md p-8">
270
+ <h1 className="text-lg font-bold mb-2">Save your recovery codes</h1>
271
+ <p className="text-sm text-text-muted mb-5">
272
+ If you lose your password, these codes are the only way to recover your encrypted mail.
273
+ Each code can be used once. Store them somewhere safe — they will not be shown again.
274
+ </p>
275
+ <ul className="grid grid-cols-2 gap-2 mb-3 font-mono text-sm">
276
+ {recoveryCodes.map((code) => (
277
+ <li key={code} className="bg-surface-alt rounded-sm py-1.5 px-2 text-center">
278
+ {code}
279
+ </li>
280
+ ))}
281
+ </ul>
282
+ <Button type="button" variant="secondary" className="!w-auto mb-5" onClick={handleCopyCodes}>
283
+ {codesCopied ? "Copied" : "Copy codes to clipboard"}
284
+ </Button>
285
+ <label className="flex items-center gap-2 text-sm mb-4">
286
+ <input type="checkbox" checked={codesSaved} onChange={(e) => setCodesSaved(e.target.checked)} />
287
+ I have saved these recovery codes in a safe place.
288
+ </label>
289
+ <Button type="button" disabled={!codesSaved} onClick={() => setStatus("ready")}>
290
+ Continue
291
+ </Button>
292
+ </div>
293
+ </div>
294
+ );
295
+ }
296
+
297
+ return <>{children}</>;
298
+ }