@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,385 +1,385 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import { useSyncExternalStore } from "react";
6
- import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
7
- import {
8
- CurrentSignEnrollment,
9
- EnrollmentResult,
10
- checkNowRetryAfterSeconds,
11
- checkSignEnrollmentNow,
12
- checkSignEnrollmentStatus,
13
- } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
14
- import { SIGNING_ENROLLMENT_UNKNOWN } from "@rapidmx/react-shared/crypto/signingProviderApi.js";
15
- import { storeSignEnrollment } from "./enrollmentStorage.js";
16
- import { resetSigningInfo } from "./signingInfo.js";
17
-
18
- /** The code of the 404 the server answers for an enrollment id it does not know (another provider after a configuration change, one long gone).
19
- * Re-exported from react-shared's `signingProviderApi.js` (R6's) rather than a second copy of the literal. */
20
- export const UNKNOWN_ENROLLMENT_CODE = SIGNING_ENROLLMENT_UNKNOWN;
21
-
22
- /**
23
- * Follows the signing-certificate enrollments this browser knows about, one per mailbox, for everyone who wants to show or react to one:
24
- * the Settings > Encryption card and the app frame's watcher share it, so an enrollment is asked about once however many look at it.
25
- *
26
- * An enrollment is a real e-mail round trip with a public CA (minutes), so it is read - not hammered: after the first answer it asks again
27
- * after 15 s, then 30 s, then every 60 s, **only while the page is visible** (a hidden tab asks nothing; coming back to the front, or the
28
- * window taking focus, asks at once and starts the backoff over), and it stops for good when the enrollment is issued or failed.
29
- * `checkNow()` is the user's "Check status": it asks the server to re-check with the CA, with a cooldown so it can't be spammed.
30
- *
31
- * Framework-free apart from the `useSyncExternalStore` hook at the bottom; safe where there is no window (nothing runs until `watch()`).
32
- */
33
-
34
- /** The wait before each re-read of a pending enrollment: the last value repeats. */
35
- export const ENROLLMENT_POLL_DELAYS_MS = [15_000, 30_000, 60_000];
36
-
37
- /** How long "Check status" stays unavailable after a check (the server refuses one within about ten seconds of the last). */
38
- export const ENROLLMENT_CHECK_COOLDOWN_MS = 10_000;
39
-
40
- /** What came of the last manual check. */
41
- export type CheckOutcome = "changed" | "unchanged" | "limited" | "failed";
42
-
43
- export interface EnrollmentSnapshot {
44
- mailboxUid: string;
45
- enrollmentId: string;
46
- /** The latest answer. `null` until the server has answered (or when its answers never arrive). */
47
- result: EnrollmentResult | null;
48
- /** When this browser last got an answer (its own clock), or `null`. */
49
- answeredAt: number | null;
50
- /** A read is in flight. */
51
- checking: boolean;
52
- /** A manual check is in flight: the button's busy state. */
53
- checkingNow: boolean;
54
- /** "Check status" is unavailable until this time (epoch ms); `0` when it is available. */
55
- retryAt: number;
56
- /** The last read did not get an answer (offline, a server error) - what is shown is what was known. */
57
- offline: boolean;
58
- /** The server no longer knows this enrollment (404). */
59
- gone: boolean;
60
- /** The last manual check, for the words under the button. */
61
- lastCheck: { at: number; outcome: CheckOutcome } | null;
62
- }
63
-
64
- interface Entry {
65
- snapshot: EnrollmentSnapshot;
66
- refs: number;
67
- timer: ReturnType<typeof setTimeout> | undefined;
68
- /** Reads since the backoff began: picks the next delay. */
69
- attempt: number;
70
- /** A timer came due while the page was hidden: nothing is scheduled until it is visible again. */
71
- paused: boolean;
72
- /** Ended while this browser was watching a pending enrollment: worth announcing once. */
73
- expectPending: boolean;
74
- announced: boolean;
75
- }
76
-
77
- const entries = new Map<string, Entry>();
78
- const listeners = new Set<() => void>();
79
- const terminalListeners = new Set<(snapshot: EnrollmentSnapshot) => void>();
80
- let environmentBound = false;
81
-
82
- function isVisible(): boolean {
83
- return typeof document === "undefined" || document.visibilityState === "visible";
84
- }
85
-
86
- function isTerminal(result: EnrollmentResult | null): boolean {
87
- return result?.status === "issued" || result?.status === "failed";
88
- }
89
-
90
- function emit(): void {
91
- listeners.forEach((listener) => listener());
92
- }
93
-
94
- function update(entry: Entry, patch: Partial<EnrollmentSnapshot>): void {
95
- entry.snapshot = { ...entry.snapshot, ...patch };
96
- emit();
97
- }
98
-
99
- function isCurrent(entry: Entry): boolean {
100
- return entries.get(entry.snapshot.mailboxUid) === entry;
101
- }
102
-
103
- function stop(entry: Entry): void {
104
- clearTimeout(entry.timer);
105
- entry.timer = undefined;
106
- entry.paused = false;
107
- }
108
-
109
- function schedule(entry: Entry): void {
110
- stop(entry);
111
- const delay = ENROLLMENT_POLL_DELAYS_MS[Math.min(entry.attempt, ENROLLMENT_POLL_DELAYS_MS.length - 1)];
112
- entry.attempt += 1;
113
- entry.timer = setTimeout(() => {
114
- entry.timer = undefined;
115
- // (Whatever replaces or ends an entry clears its timer first, so this one is always for the entry as it is.)
116
- if (!isVisible()) {
117
- entry.paused = true;
118
- return;
119
- }
120
- void read(entry);
121
- }, delay);
122
- }
123
-
124
- /** Puts an answer on the entry and decides what happens next: keep asking, or end (and tell the watchers once). */
125
- function apply(entry: Entry, result: EnrollmentResult, patch: Partial<EnrollmentSnapshot> = {}): void {
126
- if (!isCurrent(entry)) {
127
- return;
128
- }
129
- update(entry, { result, answeredAt: Date.now(), offline: false, gone: false, checking: false, ...patch });
130
- if (!isTerminal(result)) {
131
- schedule(entry);
132
- return;
133
- }
134
- stop(entry);
135
- // The enrollment is over: nothing is pending, so the id is not kept (it is what blocks a rotation across a reload).
136
- storeSignEnrollment(entry.snapshot.mailboxUid, null);
137
- if (entry.expectPending && !entry.announced) {
138
- entry.announced = true;
139
- terminalListeners.forEach((listener) => listener(entry.snapshot));
140
- }
141
- }
142
-
143
- /** A failed read: the server no longer has the enrollment (nothing is pending), or it could not be reached (assume it is still going). */
144
- function fail(entry: Entry, err: unknown, patch: Partial<EnrollmentSnapshot> = {}): void {
145
- if (!isCurrent(entry)) {
146
- return;
147
- }
148
- if (err instanceof ApiRequestError && err.status === 404) {
149
- stop(entry);
150
- storeSignEnrollment(entry.snapshot.mailboxUid, null);
151
- update(entry, { gone: true, offline: false, checking: false, ...patch });
152
- return;
153
- }
154
- update(entry, { offline: true, checking: false, ...patch });
155
- schedule(entry);
156
- }
157
-
158
- async function read(entry: Entry): Promise<void> {
159
- update(entry, { checking: true });
160
- try {
161
- apply(entry, await checkSignEnrollmentStatus(entry.snapshot.mailboxUid, entry.snapshot.enrollmentId));
162
- } catch (err) {
163
- fail(entry, err);
164
- }
165
- }
166
-
167
- function resume(): void {
168
- if (!isVisible()) {
169
- return;
170
- }
171
- entries.forEach((entry) => {
172
- if (entry.paused && !isTerminal(entry.snapshot.result)) {
173
- entry.paused = false;
174
- entry.attempt = 0;
175
- void read(entry);
176
- }
177
- });
178
- }
179
-
180
- function bindEnvironment(): void {
181
- if (!environmentBound && typeof document !== "undefined") {
182
- environmentBound = true;
183
- document.addEventListener("visibilitychange", resume);
184
- window.addEventListener("focus", resume);
185
- window.addEventListener("online", resume);
186
- }
187
- }
188
-
189
- function unbindEnvironment(): void {
190
- if (environmentBound && entries.size === 0) {
191
- environmentBound = false;
192
- document.removeEventListener("visibilitychange", resume);
193
- window.removeEventListener("focus", resume);
194
- window.removeEventListener("online", resume);
195
- }
196
- }
197
-
198
- export interface WatchOptions {
199
- /** What is already known (a `getCurrentSignEnrollment()` answer): shown at once and not asked again first. */
200
- initial?: EnrollmentResult;
201
- /** This enrollment was pending when it was stored, so its ending is news (a stored id, a pending one found on the server). Default `true`. */
202
- expectPending?: boolean;
203
- }
204
-
205
- /**
206
- * Starts following `enrollmentId` for `mailboxUid` (one enrollment per mailbox; a different id replaces the old one) and returns the
207
- * function that lets go. Reads it now unless `initial` says what it is, then keeps reading with backoff while it is pending. Following is
208
- * shared, and a pending enrollment stays followed after everyone has let go (until it ends); an ended one is forgotten.
209
- */
210
- export function watchEnrollment(mailboxUid: string, enrollmentId: string, options: WatchOptions = {}): () => void {
211
- const { initial, expectPending = true } = options;
212
- let entry = entries.get(mailboxUid);
213
- if (entry && entry.snapshot.enrollmentId !== enrollmentId) {
214
- stop(entry);
215
- entry = undefined;
216
- }
217
- if (entry) {
218
- entry.refs += 1;
219
- entry.expectPending ||= expectPending && !isTerminal(entry.snapshot.result);
220
- if (initial && !entry.snapshot.result) {
221
- apply(entry, initial);
222
- }
223
- } else {
224
- const created: Entry = {
225
- snapshot: {
226
- mailboxUid,
227
- enrollmentId,
228
- result: null,
229
- answeredAt: null,
230
- checking: false,
231
- checkingNow: false,
232
- retryAt: 0,
233
- offline: false,
234
- gone: false,
235
- lastCheck: null,
236
- },
237
- refs: 1,
238
- timer: undefined,
239
- attempt: 0,
240
- paused: false,
241
- expectPending,
242
- announced: false,
243
- };
244
- entries.set(mailboxUid, created);
245
- bindEnvironment();
246
- emit();
247
- if (initial) {
248
- apply(created, initial);
249
- } else {
250
- void read(created);
251
- }
252
- }
253
- const held = entries.get(mailboxUid)!;
254
- let released = false;
255
- return () => {
256
- if (released) {
257
- return;
258
- }
259
- released = true;
260
- held.refs -= 1;
261
- // A pending enrollment is followed on with nobody looking - that is what lets the frame tell the user it finished wherever they are, and
262
- // what the next visit to the page shows at once. One that ended (or that the server no longer knows) has nothing left to follow.
263
- if (held.refs <= 0 && isCurrent(held) && (isTerminal(held.snapshot.result) || held.snapshot.gone)) {
264
- stop(held);
265
- entries.delete(mailboxUid);
266
- unbindEnvironment();
267
- emit();
268
- }
269
- };
270
- }
271
-
272
- /** Whether a manual check changed what the user sees: the step, the state or the progress. */
273
- function differs(before: EnrollmentResult | null, after: EnrollmentResult): boolean {
274
- return !before || before.status !== after.status || before.stage !== after.stage || before.progress !== after.progress;
275
- }
276
-
277
- /** "Check status": asks the server to re-check with the CA now. Does nothing while one is under way or within the cooldown. */
278
- export async function checkEnrollmentNow(mailboxUid: string): Promise<void> {
279
- const entry = entries.get(mailboxUid);
280
- if (!entry || entry.snapshot.checkingNow || entry.snapshot.retryAt > Date.now() || isTerminal(entry.snapshot.result)) {
281
- return;
282
- }
283
- const before = entry.snapshot.result;
284
- update(entry, { checkingNow: true, checking: true });
285
- entry.attempt = 0;
286
- const done = (outcome: CheckOutcome, patch: Partial<EnrollmentSnapshot> = {}) => ({
287
- checkingNow: false,
288
- lastCheck: { at: Date.now(), outcome },
289
- ...patch,
290
- });
291
- try {
292
- const result = await checkSignEnrollmentNow(mailboxUid, entry.snapshot.enrollmentId);
293
- apply(entry, result, done(differs(before, result) ? "changed" : "unchanged", { retryAt: Date.now() + ENROLLMENT_CHECK_COOLDOWN_MS }));
294
- return;
295
- } catch (err) {
296
- const seconds = checkNowRetryAfterSeconds(err);
297
- if (seconds !== undefined) {
298
- update(entry, done("limited", { retryAt: Date.now() + seconds * 1000, checking: false }));
299
- return;
300
- }
301
- if (err instanceof ApiRequestError && err.status === 404 && err.code === UNKNOWN_ENROLLMENT_CODE) {
302
- // The server says this enrollment does not exist: there is nothing to fall back to.
303
- fail(entry, err, done("failed"));
304
- return;
305
- }
306
- if (!(err instanceof ApiRequestError && [404, 405, 501].includes(err.status))) {
307
- if (isCurrent(entry)) {
308
- update(entry, done("failed", { checking: false }));
309
- }
310
- return;
311
- }
312
- }
313
- // A server without the check endpoint: a plain read is the "check" it has - and a 404 there says the enrollment itself is gone.
314
- try {
315
- const result = await checkSignEnrollmentStatus(mailboxUid, entry.snapshot.enrollmentId);
316
- apply(entry, result, done(differs(before, result) ? "changed" : "unchanged", { retryAt: Date.now() + ENROLLMENT_CHECK_COOLDOWN_MS }));
317
- } catch (err) {
318
- fail(entry, err, done("failed"));
319
- }
320
- }
321
-
322
- /** Adopts an enrollment the server reported (`getCurrentSignEnrollment()`) - see `watchEnrollment()`. */
323
- export function watchCurrentEnrollment(mailboxUid: string, current: CurrentSignEnrollment, expectPending = true): () => void {
324
- const { enrollmentId, ...result } = current;
325
- return watchEnrollment(mailboxUid, enrollmentId, { initial: result, expectPending });
326
- }
327
-
328
- /** Puts an answer the caller got itself (the reply to a cancel that found the certificate already issued) on `mailboxUid`'s enrollment, if it is the one followed. */
329
- export function recordEnrollmentResult(mailboxUid: string, enrollmentId: string, result: EnrollmentResult): void {
330
- const entry = entries.get(mailboxUid);
331
- if (entry && entry.snapshot.enrollmentId === enrollmentId) {
332
- apply(entry, result);
333
- }
334
- }
335
-
336
- /** Stops following `mailboxUid`'s enrollment altogether (it was cancelled): nothing is kept, whoever else was watching. */
337
- export function forgetEnrollment(mailboxUid: string): void {
338
- const entry = entries.get(mailboxUid);
339
- if (entry) {
340
- stop(entry);
341
- entries.delete(mailboxUid);
342
- unbindEnvironment();
343
- emit();
344
- }
345
- }
346
-
347
- /** The current state of `mailboxUid`'s followed enrollment, or `undefined` when none is followed. */
348
- export function getEnrollmentSnapshot(mailboxUid: string): EnrollmentSnapshot | undefined {
349
- return entries.get(mailboxUid)?.snapshot;
350
- }
351
-
352
- export function subscribeToEnrollments(listener: () => void): () => void {
353
- listeners.add(listener);
354
- return () => {
355
- listeners.delete(listener);
356
- };
357
- }
358
-
359
- /** Called once when an enrollment this browser was following ends (issued or failed) - the frame's watcher raises the pop-up. */
360
- export function onEnrollmentEnded(listener: (snapshot: EnrollmentSnapshot) => void): () => void {
361
- terminalListeners.add(listener);
362
- return () => {
363
- terminalListeners.delete(listener);
364
- };
365
- }
366
-
367
- /** `mailboxUid`'s followed enrollment, kept current (`undefined` when none is followed). */
368
- export function useEnrollmentSnapshot(mailboxUid: string | undefined): EnrollmentSnapshot | undefined {
369
- return useSyncExternalStore(
370
- subscribeToEnrollments,
371
- () => (mailboxUid ? getEnrollmentSnapshot(mailboxUid) : undefined),
372
- () => undefined,
373
- );
374
- }
375
-
376
- /** Forgets everything and stops every timer: for tests, which share the module. */
377
- export function resetEnrollmentTracker(): void {
378
- resetSigningInfo();
379
- entries.forEach(stop);
380
- entries.clear();
381
- listeners.clear();
382
- terminalListeners.clear();
383
- unbindEnvironment();
384
- environmentBound = false;
385
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import { useSyncExternalStore } from "react";
6
+ import { ApiRequestError } from "@rapidmx/react-shared/util/api.js";
7
+ import {
8
+ CurrentSignEnrollment,
9
+ EnrollmentResult,
10
+ checkNowRetryAfterSeconds,
11
+ checkSignEnrollmentNow,
12
+ checkSignEnrollmentStatus,
13
+ } from "@rapidmx/react-shared/crypto/keyvaultApi.js";
14
+ import { SIGNING_ENROLLMENT_UNKNOWN } from "@rapidmx/react-shared/crypto/signingProviderApi.js";
15
+ import { storeSignEnrollment } from "./enrollmentStorage.js";
16
+ import { resetSigningInfo } from "./signingInfo.js";
17
+
18
+ /** The code of the 404 the server answers for an enrollment id it does not know (another provider after a configuration change, one long gone).
19
+ * Re-exported from react-shared's `signingProviderApi.js` (R6's) rather than a second copy of the literal. */
20
+ export const UNKNOWN_ENROLLMENT_CODE = SIGNING_ENROLLMENT_UNKNOWN;
21
+
22
+ /**
23
+ * Follows the signing-certificate enrollments this browser knows about, one per mailbox, for everyone who wants to show or react to one:
24
+ * the Settings > Encryption card and the app frame's watcher share it, so an enrollment is asked about once however many look at it.
25
+ *
26
+ * An enrollment is a real e-mail round trip with a public CA (minutes), so it is read - not hammered: after the first answer it asks again
27
+ * after 15 s, then 30 s, then every 60 s, **only while the page is visible** (a hidden tab asks nothing; coming back to the front, or the
28
+ * window taking focus, asks at once and starts the backoff over), and it stops for good when the enrollment is issued or failed.
29
+ * `checkNow()` is the user's "Check status": it asks the server to re-check with the CA, with a cooldown so it can't be spammed.
30
+ *
31
+ * Framework-free apart from the `useSyncExternalStore` hook at the bottom; safe where there is no window (nothing runs until `watch()`).
32
+ */
33
+
34
+ /** The wait before each re-read of a pending enrollment: the last value repeats. */
35
+ export const ENROLLMENT_POLL_DELAYS_MS = [15_000, 30_000, 60_000];
36
+
37
+ /** How long "Check status" stays unavailable after a check (the server refuses one within about ten seconds of the last). */
38
+ export const ENROLLMENT_CHECK_COOLDOWN_MS = 10_000;
39
+
40
+ /** What came of the last manual check. */
41
+ export type CheckOutcome = "changed" | "unchanged" | "limited" | "failed";
42
+
43
+ export interface EnrollmentSnapshot {
44
+ mailboxUid: string;
45
+ enrollmentId: string;
46
+ /** The latest answer. `null` until the server has answered (or when its answers never arrive). */
47
+ result: EnrollmentResult | null;
48
+ /** When this browser last got an answer (its own clock), or `null`. */
49
+ answeredAt: number | null;
50
+ /** A read is in flight. */
51
+ checking: boolean;
52
+ /** A manual check is in flight: the button's busy state. */
53
+ checkingNow: boolean;
54
+ /** "Check status" is unavailable until this time (epoch ms); `0` when it is available. */
55
+ retryAt: number;
56
+ /** The last read did not get an answer (offline, a server error) - what is shown is what was known. */
57
+ offline: boolean;
58
+ /** The server no longer knows this enrollment (404). */
59
+ gone: boolean;
60
+ /** The last manual check, for the words under the button. */
61
+ lastCheck: { at: number; outcome: CheckOutcome } | null;
62
+ }
63
+
64
+ interface Entry {
65
+ snapshot: EnrollmentSnapshot;
66
+ refs: number;
67
+ timer: ReturnType<typeof setTimeout> | undefined;
68
+ /** Reads since the backoff began: picks the next delay. */
69
+ attempt: number;
70
+ /** A timer came due while the page was hidden: nothing is scheduled until it is visible again. */
71
+ paused: boolean;
72
+ /** Ended while this browser was watching a pending enrollment: worth announcing once. */
73
+ expectPending: boolean;
74
+ announced: boolean;
75
+ }
76
+
77
+ const entries = new Map<string, Entry>();
78
+ const listeners = new Set<() => void>();
79
+ const terminalListeners = new Set<(snapshot: EnrollmentSnapshot) => void>();
80
+ let environmentBound = false;
81
+
82
+ function isVisible(): boolean {
83
+ return typeof document === "undefined" || document.visibilityState === "visible";
84
+ }
85
+
86
+ function isTerminal(result: EnrollmentResult | null): boolean {
87
+ return result?.status === "issued" || result?.status === "failed";
88
+ }
89
+
90
+ function emit(): void {
91
+ listeners.forEach((listener) => listener());
92
+ }
93
+
94
+ function update(entry: Entry, patch: Partial<EnrollmentSnapshot>): void {
95
+ entry.snapshot = { ...entry.snapshot, ...patch };
96
+ emit();
97
+ }
98
+
99
+ function isCurrent(entry: Entry): boolean {
100
+ return entries.get(entry.snapshot.mailboxUid) === entry;
101
+ }
102
+
103
+ function stop(entry: Entry): void {
104
+ clearTimeout(entry.timer);
105
+ entry.timer = undefined;
106
+ entry.paused = false;
107
+ }
108
+
109
+ function schedule(entry: Entry): void {
110
+ stop(entry);
111
+ const delay = ENROLLMENT_POLL_DELAYS_MS[Math.min(entry.attempt, ENROLLMENT_POLL_DELAYS_MS.length - 1)];
112
+ entry.attempt += 1;
113
+ entry.timer = setTimeout(() => {
114
+ entry.timer = undefined;
115
+ // (Whatever replaces or ends an entry clears its timer first, so this one is always for the entry as it is.)
116
+ if (!isVisible()) {
117
+ entry.paused = true;
118
+ return;
119
+ }
120
+ void read(entry);
121
+ }, delay);
122
+ }
123
+
124
+ /** Puts an answer on the entry and decides what happens next: keep asking, or end (and tell the watchers once). */
125
+ function apply(entry: Entry, result: EnrollmentResult, patch: Partial<EnrollmentSnapshot> = {}): void {
126
+ if (!isCurrent(entry)) {
127
+ return;
128
+ }
129
+ update(entry, { result, answeredAt: Date.now(), offline: false, gone: false, checking: false, ...patch });
130
+ if (!isTerminal(result)) {
131
+ schedule(entry);
132
+ return;
133
+ }
134
+ stop(entry);
135
+ // The enrollment is over: nothing is pending, so the id is not kept (it is what blocks a rotation across a reload).
136
+ storeSignEnrollment(entry.snapshot.mailboxUid, null);
137
+ if (entry.expectPending && !entry.announced) {
138
+ entry.announced = true;
139
+ terminalListeners.forEach((listener) => listener(entry.snapshot));
140
+ }
141
+ }
142
+
143
+ /** A failed read: the server no longer has the enrollment (nothing is pending), or it could not be reached (assume it is still going). */
144
+ function fail(entry: Entry, err: unknown, patch: Partial<EnrollmentSnapshot> = {}): void {
145
+ if (!isCurrent(entry)) {
146
+ return;
147
+ }
148
+ if (err instanceof ApiRequestError && err.status === 404) {
149
+ stop(entry);
150
+ storeSignEnrollment(entry.snapshot.mailboxUid, null);
151
+ update(entry, { gone: true, offline: false, checking: false, ...patch });
152
+ return;
153
+ }
154
+ update(entry, { offline: true, checking: false, ...patch });
155
+ schedule(entry);
156
+ }
157
+
158
+ async function read(entry: Entry): Promise<void> {
159
+ update(entry, { checking: true });
160
+ try {
161
+ apply(entry, await checkSignEnrollmentStatus(entry.snapshot.mailboxUid, entry.snapshot.enrollmentId));
162
+ } catch (err) {
163
+ fail(entry, err);
164
+ }
165
+ }
166
+
167
+ function resume(): void {
168
+ if (!isVisible()) {
169
+ return;
170
+ }
171
+ entries.forEach((entry) => {
172
+ if (entry.paused && !isTerminal(entry.snapshot.result)) {
173
+ entry.paused = false;
174
+ entry.attempt = 0;
175
+ void read(entry);
176
+ }
177
+ });
178
+ }
179
+
180
+ function bindEnvironment(): void {
181
+ if (!environmentBound && typeof document !== "undefined") {
182
+ environmentBound = true;
183
+ document.addEventListener("visibilitychange", resume);
184
+ window.addEventListener("focus", resume);
185
+ window.addEventListener("online", resume);
186
+ }
187
+ }
188
+
189
+ function unbindEnvironment(): void {
190
+ if (environmentBound && entries.size === 0) {
191
+ environmentBound = false;
192
+ document.removeEventListener("visibilitychange", resume);
193
+ window.removeEventListener("focus", resume);
194
+ window.removeEventListener("online", resume);
195
+ }
196
+ }
197
+
198
+ export interface WatchOptions {
199
+ /** What is already known (a `getCurrentSignEnrollment()` answer): shown at once and not asked again first. */
200
+ initial?: EnrollmentResult;
201
+ /** This enrollment was pending when it was stored, so its ending is news (a stored id, a pending one found on the server). Default `true`. */
202
+ expectPending?: boolean;
203
+ }
204
+
205
+ /**
206
+ * Starts following `enrollmentId` for `mailboxUid` (one enrollment per mailbox; a different id replaces the old one) and returns the
207
+ * function that lets go. Reads it now unless `initial` says what it is, then keeps reading with backoff while it is pending. Following is
208
+ * shared, and a pending enrollment stays followed after everyone has let go (until it ends); an ended one is forgotten.
209
+ */
210
+ export function watchEnrollment(mailboxUid: string, enrollmentId: string, options: WatchOptions = {}): () => void {
211
+ const { initial, expectPending = true } = options;
212
+ let entry = entries.get(mailboxUid);
213
+ if (entry && entry.snapshot.enrollmentId !== enrollmentId) {
214
+ stop(entry);
215
+ entry = undefined;
216
+ }
217
+ if (entry) {
218
+ entry.refs += 1;
219
+ entry.expectPending ||= expectPending && !isTerminal(entry.snapshot.result);
220
+ if (initial && !entry.snapshot.result) {
221
+ apply(entry, initial);
222
+ }
223
+ } else {
224
+ const created: Entry = {
225
+ snapshot: {
226
+ mailboxUid,
227
+ enrollmentId,
228
+ result: null,
229
+ answeredAt: null,
230
+ checking: false,
231
+ checkingNow: false,
232
+ retryAt: 0,
233
+ offline: false,
234
+ gone: false,
235
+ lastCheck: null,
236
+ },
237
+ refs: 1,
238
+ timer: undefined,
239
+ attempt: 0,
240
+ paused: false,
241
+ expectPending,
242
+ announced: false,
243
+ };
244
+ entries.set(mailboxUid, created);
245
+ bindEnvironment();
246
+ emit();
247
+ if (initial) {
248
+ apply(created, initial);
249
+ } else {
250
+ void read(created);
251
+ }
252
+ }
253
+ const held = entries.get(mailboxUid)!;
254
+ let released = false;
255
+ return () => {
256
+ if (released) {
257
+ return;
258
+ }
259
+ released = true;
260
+ held.refs -= 1;
261
+ // A pending enrollment is followed on with nobody looking - that is what lets the frame tell the user it finished wherever they are, and
262
+ // what the next visit to the page shows at once. One that ended (or that the server no longer knows) has nothing left to follow.
263
+ if (held.refs <= 0 && isCurrent(held) && (isTerminal(held.snapshot.result) || held.snapshot.gone)) {
264
+ stop(held);
265
+ entries.delete(mailboxUid);
266
+ unbindEnvironment();
267
+ emit();
268
+ }
269
+ };
270
+ }
271
+
272
+ /** Whether a manual check changed what the user sees: the step, the state or the progress. */
273
+ function differs(before: EnrollmentResult | null, after: EnrollmentResult): boolean {
274
+ return !before || before.status !== after.status || before.stage !== after.stage || before.progress !== after.progress;
275
+ }
276
+
277
+ /** "Check status": asks the server to re-check with the CA now. Does nothing while one is under way or within the cooldown. */
278
+ export async function checkEnrollmentNow(mailboxUid: string): Promise<void> {
279
+ const entry = entries.get(mailboxUid);
280
+ if (!entry || entry.snapshot.checkingNow || entry.snapshot.retryAt > Date.now() || isTerminal(entry.snapshot.result)) {
281
+ return;
282
+ }
283
+ const before = entry.snapshot.result;
284
+ update(entry, { checkingNow: true, checking: true });
285
+ entry.attempt = 0;
286
+ const done = (outcome: CheckOutcome, patch: Partial<EnrollmentSnapshot> = {}) => ({
287
+ checkingNow: false,
288
+ lastCheck: { at: Date.now(), outcome },
289
+ ...patch,
290
+ });
291
+ try {
292
+ const result = await checkSignEnrollmentNow(mailboxUid, entry.snapshot.enrollmentId);
293
+ apply(entry, result, done(differs(before, result) ? "changed" : "unchanged", { retryAt: Date.now() + ENROLLMENT_CHECK_COOLDOWN_MS }));
294
+ return;
295
+ } catch (err) {
296
+ const seconds = checkNowRetryAfterSeconds(err);
297
+ if (seconds !== undefined) {
298
+ update(entry, done("limited", { retryAt: Date.now() + seconds * 1000, checking: false }));
299
+ return;
300
+ }
301
+ if (err instanceof ApiRequestError && err.status === 404 && err.code === UNKNOWN_ENROLLMENT_CODE) {
302
+ // The server says this enrollment does not exist: there is nothing to fall back to.
303
+ fail(entry, err, done("failed"));
304
+ return;
305
+ }
306
+ if (!(err instanceof ApiRequestError && [404, 405, 501].includes(err.status))) {
307
+ if (isCurrent(entry)) {
308
+ update(entry, done("failed", { checking: false }));
309
+ }
310
+ return;
311
+ }
312
+ }
313
+ // A server without the check endpoint: a plain read is the "check" it has - and a 404 there says the enrollment itself is gone.
314
+ try {
315
+ const result = await checkSignEnrollmentStatus(mailboxUid, entry.snapshot.enrollmentId);
316
+ apply(entry, result, done(differs(before, result) ? "changed" : "unchanged", { retryAt: Date.now() + ENROLLMENT_CHECK_COOLDOWN_MS }));
317
+ } catch (err) {
318
+ fail(entry, err, done("failed"));
319
+ }
320
+ }
321
+
322
+ /** Adopts an enrollment the server reported (`getCurrentSignEnrollment()`) - see `watchEnrollment()`. */
323
+ export function watchCurrentEnrollment(mailboxUid: string, current: CurrentSignEnrollment, expectPending = true): () => void {
324
+ const { enrollmentId, ...result } = current;
325
+ return watchEnrollment(mailboxUid, enrollmentId, { initial: result, expectPending });
326
+ }
327
+
328
+ /** Puts an answer the caller got itself (the reply to a cancel that found the certificate already issued) on `mailboxUid`'s enrollment, if it is the one followed. */
329
+ export function recordEnrollmentResult(mailboxUid: string, enrollmentId: string, result: EnrollmentResult): void {
330
+ const entry = entries.get(mailboxUid);
331
+ if (entry && entry.snapshot.enrollmentId === enrollmentId) {
332
+ apply(entry, result);
333
+ }
334
+ }
335
+
336
+ /** Stops following `mailboxUid`'s enrollment altogether (it was cancelled): nothing is kept, whoever else was watching. */
337
+ export function forgetEnrollment(mailboxUid: string): void {
338
+ const entry = entries.get(mailboxUid);
339
+ if (entry) {
340
+ stop(entry);
341
+ entries.delete(mailboxUid);
342
+ unbindEnvironment();
343
+ emit();
344
+ }
345
+ }
346
+
347
+ /** The current state of `mailboxUid`'s followed enrollment, or `undefined` when none is followed. */
348
+ export function getEnrollmentSnapshot(mailboxUid: string): EnrollmentSnapshot | undefined {
349
+ return entries.get(mailboxUid)?.snapshot;
350
+ }
351
+
352
+ export function subscribeToEnrollments(listener: () => void): () => void {
353
+ listeners.add(listener);
354
+ return () => {
355
+ listeners.delete(listener);
356
+ };
357
+ }
358
+
359
+ /** Called once when an enrollment this browser was following ends (issued or failed) - the frame's watcher raises the pop-up. */
360
+ export function onEnrollmentEnded(listener: (snapshot: EnrollmentSnapshot) => void): () => void {
361
+ terminalListeners.add(listener);
362
+ return () => {
363
+ terminalListeners.delete(listener);
364
+ };
365
+ }
366
+
367
+ /** `mailboxUid`'s followed enrollment, kept current (`undefined` when none is followed). */
368
+ export function useEnrollmentSnapshot(mailboxUid: string | undefined): EnrollmentSnapshot | undefined {
369
+ return useSyncExternalStore(
370
+ subscribeToEnrollments,
371
+ () => (mailboxUid ? getEnrollmentSnapshot(mailboxUid) : undefined),
372
+ () => undefined,
373
+ );
374
+ }
375
+
376
+ /** Forgets everything and stops every timer: for tests, which share the module. */
377
+ export function resetEnrollmentTracker(): void {
378
+ resetSigningInfo();
379
+ entries.forEach(stop);
380
+ entries.clear();
381
+ listeners.clear();
382
+ terminalListeners.clear();
383
+ unbindEnvironment();
384
+ environmentBound = false;
385
+ }