@rapidmx/web-client 0.19.0 → 0.20.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 (131) 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/diagnostics/HostCard.tsx +2 -0
  16. package/apps/shared/components/admin/diagnostics/PressureTiles.tsx +108 -0
  17. package/apps/shared/components/admin/diagnostics/PvcTable.tsx +20 -6
  18. package/apps/shared/components/admin/diagnostics/diagnosticsApi.ts +21 -2
  19. package/apps/shared/components/admin/layout/AdminShell.tsx +384 -384
  20. package/apps/shared/components/admin/mailboxes/EraseLeftoverDataDialog.tsx +238 -238
  21. package/apps/shared/components/admin/mailboxes/EscrowScopeCard.tsx +152 -152
  22. package/apps/shared/components/admin/mailboxes/LeftoverMailboxesSection.tsx +194 -194
  23. package/apps/shared/components/admin/settings/BrandingForm.tsx +423 -423
  24. package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +119 -119
  25. package/apps/shared/components/admin/settings/MailboxPolicyForm.tsx +198 -198
  26. package/apps/shared/components/admin/settings/PluginsManager.tsx +2093 -1620
  27. package/apps/shared/components/admin/settings/RetentionPolicyForm.tsx +182 -182
  28. package/apps/shared/components/admin/settings/pluginPreferences.ts +34 -0
  29. package/apps/shared/components/admin/setup/EscrowSetupStep.tsx +288 -288
  30. package/apps/shared/components/admin/setup/SetupWizard.tsx +446 -446
  31. package/apps/shared/components/admin/usePagedList.tsx +129 -129
  32. package/apps/shared/components/calendar/EventModal.tsx +206 -206
  33. package/apps/shared/components/calendar/MonthView.tsx +185 -185
  34. package/apps/shared/components/calendar/RecurrenceEditor.tsx +227 -227
  35. package/apps/shared/components/calendar/SplitDayView.tsx +144 -144
  36. package/apps/shared/components/calendar/TimeGridView.tsx +246 -246
  37. package/apps/shared/components/calendar/allDay.ts +124 -124
  38. package/apps/shared/components/contacts/ContactForm.tsx +383 -383
  39. package/apps/shared/components/contacts/ContactsToolbar.tsx +103 -103
  40. package/apps/shared/components/escrow/layout/EscrowShell.tsx +155 -155
  41. package/apps/shared/components/layout/AppShell.tsx +461 -461
  42. package/apps/shared/components/layout/KeyEnrollmentGate.tsx +398 -398
  43. package/apps/shared/components/layout/MailboxProvisioning.tsx +168 -168
  44. package/apps/shared/components/layout/ResponsiveToolbar.tsx +315 -315
  45. package/apps/shared/components/layout/ThemeSwitch.tsx +84 -84
  46. package/apps/shared/components/layout/UserMenu.tsx +439 -439
  47. package/apps/shared/components/mail/ConversationList.tsx +332 -323
  48. package/apps/shared/components/mail/ConversationThreadPane.tsx +613 -613
  49. package/apps/shared/components/mail/MailSelectionBar.tsx +240 -240
  50. package/apps/shared/components/mail/MenuButton.tsx +404 -404
  51. package/apps/shared/components/mail/MessageDetailPane.tsx +1757 -1757
  52. package/apps/shared/components/mail/compose/ComposeContext.tsx +312 -312
  53. package/apps/shared/components/mail/compose/ComposeToolbar.tsx +422 -422
  54. package/apps/shared/components/mail/compose/ComposeWindow.tsx +1681 -1681
  55. package/apps/shared/components/mail/compose/RichTextEditor.tsx +147 -147
  56. package/apps/shared/components/mail/compose/composeFlushRegistry.ts +60 -60
  57. package/apps/shared/components/mail/compose/quotedBody.ts +161 -161
  58. package/apps/shared/components/mail/listPreferences.ts +3 -3
  59. package/apps/shared/components/mail/reading/MessageMoreMenu.tsx +258 -258
  60. package/apps/shared/components/mail/reading/MessageSourceDialog.tsx +79 -79
  61. package/apps/shared/components/mail/reading/messageExport.ts +59 -59
  62. package/apps/shared/components/mail/reading/printMessage.ts +99 -99
  63. package/apps/shared/components/mail/reading/useMessageActions.ts +443 -443
  64. package/apps/shared/components/mail/verificationSeals.ts +125 -125
  65. package/apps/shared/components/rules/RuleBuilder.tsx +311 -311
  66. package/apps/shared/components/settings/SigningCertificateCard.tsx +344 -344
  67. package/apps/shared/keyboard/GlobalShortcuts.tsx +51 -51
  68. package/apps/shared/keyboard/ShortcutProvider.tsx +62 -62
  69. package/apps/shared/keyboard/ShortcutsDialog.tsx +84 -84
  70. package/apps/shared/keyboard/dispatch.ts +124 -124
  71. package/apps/shared/keyboard/format.ts +89 -89
  72. package/apps/shared/keyboard/keymap.ts +114 -114
  73. package/apps/shared/keyboard/registry.ts +65 -65
  74. package/apps/shared/keyboard/targets.ts +79 -79
  75. package/apps/shared/mail/folderOfType.ts +49 -49
  76. package/apps/shared/mail/folderTree.ts +143 -143
  77. package/apps/shared/mail/listAllPages.ts +39 -39
  78. package/apps/shared/mail/newMailNotifications.ts +171 -171
  79. package/apps/shared/mail/outbox/sendJob.ts +445 -445
  80. package/apps/shared/mail/outbox/sendOutcomes.ts +155 -155
  81. package/apps/shared/mail/reportNotices.ts +66 -66
  82. package/apps/shared/mail/senderBlocking.ts +141 -141
  83. package/apps/shared/mail/useMailConnection.ts +205 -205
  84. package/apps/shared/mail/useMailLiveUpdates.ts +277 -277
  85. package/apps/shared/mail/useMailboxUpdateAccess.ts +60 -60
  86. package/apps/shared/mail/useMarkMessageRead.ts +47 -47
  87. package/apps/shared/mail/useNewMailNotifications.ts +178 -178
  88. package/apps/shared/notifications/store.ts +560 -560
  89. package/apps/shared/search/LocalIndexLifecycle.tsx +114 -114
  90. package/apps/shared/search/localIndexBuilder.ts +481 -481
  91. package/apps/shared/signing/enrollmentStorage.ts +33 -33
  92. package/apps/shared/signing/enrollmentTracker.ts +385 -385
  93. package/apps/shared/signing/enrollmentView.ts +251 -251
  94. package/apps/shared/signing/useNow.ts +19 -19
  95. package/apps/shared/signing/useSigningEnrollmentWatcher.ts +90 -90
  96. package/apps/shared/styles/app.css +396 -396
  97. package/apps/www/calendar/index.tsx +581 -581
  98. package/apps/www/contacts/[uid].tsx +112 -112
  99. package/apps/www/index.tsx +3012 -2962
  100. package/apps/www/messages/[uid].tsx +139 -139
  101. package/apps/www/settings/auto-reply/index.tsx +136 -136
  102. package/apps/www/settings/blocked-senders/index.tsx +303 -303
  103. package/apps/www/settings/encryption/index.tsx +1290 -1290
  104. package/apps/www/settings/filters/[uid].tsx +179 -179
  105. package/apps/www/settings/filters/index.tsx +105 -105
  106. package/apps/www/settings/filters/new/index.tsx +165 -165
  107. package/apps/www/settings/labels/index.tsx +207 -207
  108. package/apps/www/settings/privacy/index.tsx +495 -495
  109. package/apps/www/settings/profile/index.tsx +251 -251
  110. package/apps/www/settings/read-receipts/index.tsx +150 -150
  111. package/apps/www/settings/sharing/index.tsx +259 -259
  112. package/apps/www/settings/signatures/[uid].tsx +175 -175
  113. package/apps/www/settings/signatures/index.tsx +91 -91
  114. package/apps/www/settings/signatures/new/index.tsx +138 -138
  115. package/apps/www/tasks/index.tsx +654 -654
  116. package/dist/apps/shared/components/admin/diagnostics/HostCard.js +2 -1
  117. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.d.ts +22 -0
  118. package/dist/apps/shared/components/admin/diagnostics/PressureTiles.js +52 -0
  119. package/dist/apps/shared/components/admin/diagnostics/PvcTable.js +9 -4
  120. package/dist/apps/shared/components/admin/diagnostics/diagnosticsApi.d.ts +35 -2
  121. package/dist/apps/shared/components/admin/settings/BrandingForm.js +3 -3
  122. package/dist/apps/shared/components/admin/settings/PluginsManager.js +267 -35
  123. package/dist/apps/shared/components/admin/settings/pluginPreferences.d.ts +2 -0
  124. package/dist/apps/shared/components/admin/settings/pluginPreferences.js +35 -0
  125. package/dist/apps/shared/components/mail/ConversationList.d.ts +10 -3
  126. package/dist/apps/shared/components/mail/ConversationList.js +9 -5
  127. package/dist/apps/shared/components/mail/listPreferences.d.ts +1 -1
  128. package/dist/apps/shared/components/mail/reading/printMessage.js +11 -11
  129. package/dist/apps/shared/styles/app.css +396 -396
  130. package/dist/apps/www/index.js +51 -10
  131. package/package.json +2 -2
@@ -1,461 +1,461 @@
1
- ///////////////////////////////////////////////////////////////////////////////
2
- // Copyright (C) 2026 Jean-Philippe Steinmetz
3
- // SPDX-License-Identifier: MPL-2.0
4
- ///////////////////////////////////////////////////////////////////////////////
5
- import "../../styles/app.css";
6
- import React, { PropsWithChildren, useEffect, useLayoutEffect, useRef, useState } from "react";
7
- import type { IconType } from "react-icons";
8
- import {
9
- HiOutlineCalendarDays,
10
- HiOutlineClipboardDocumentList,
11
- HiOutlineEnvelope,
12
- HiOutlinePuzzlePiece,
13
- HiOutlineUsers,
14
- } from "react-icons/hi2";
15
- import { useRouter } from "@rapidrest/react/client";
16
- import { useRedirectIfUnauthenticated } from "@rapidmx/react-shared/auth/session.js";
17
- import { getSetupStatus } from "@rapidmx/react-shared/admin/setupApi.js";
18
- import { stopImpersonating } from "@rapidmx/react-shared/mail/mailApi.js";
19
- import useBranding from "@rapidmx/react-shared/branding/useBranding.js";
20
- import { useIdleKeyTimeout } from "@rapidmx/react-shared/crypto/useIdleKeyTimeout.js";
21
- import ComposeProvider from "../mail/compose/ComposeContext.js";
22
- import { flushComposeDrafts, markSigningOut } from "../mail/compose/composeFlushRegistry.js";
23
- import BottomTabBar, { NavItem } from "@rapidmx/react-shared/components/navigation/BottomTabBar.js";
24
- import { FrameBrandingFooter, FrameBrandingHeader, useBrandingHtml } from "./BrandingChrome.js";
25
- import RailIcon from "./RailIcon.js";
26
- import AppearanceProvider from "../../appearance/AppearanceProvider.js";
27
- import { clearAppearanceCache } from "../../appearance/appearanceCache.js";
28
- import type { Branding } from "@rapidmx/react-shared/branding/brandingApi.js";
29
- import UserMenu from "./UserMenu.js";
30
- import { UnlockPromptProvider } from "./UnlockPromptProvider.js";
31
- import { SIGN_OUT_CHANNEL, destroyAllLocalIndexes } from "../../search/localIndexRpcClient.js";
32
- import { authApiFetch, setApiUnauthorizedObserver } from "@rapidmx/react-shared/util/api.js";
33
- import { destroyUnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
34
- import { clearPinnedSignerCache } from "../mail/pinnedSigners.js";
35
- import { mergePluginNavItems, PluginNav, PluginNavProps } from "../../plugins/pluginNav.js";
36
- import { useInAppFrame } from "../../navigation/frameContext.js";
37
- import { APP_HREFS } from "../../navigation/appHrefs.js";
38
- import { useNavigate } from "../../navigation/index.js";
39
- import { GlobalShortcuts } from "../../keyboard/GlobalShortcuts.js";
40
- import { ShortcutProvider } from "../../keyboard/ShortcutProvider.js";
41
- import ShortcutsDialog from "../../keyboard/ShortcutsDialog.js";
42
- import { inboxUnreadTotal } from "../../mail/folderCounts.js";
43
- import { MailConnectionContext, useMailConnection } from "../../mail/useMailConnection.js";
44
- import { useUnreadTitle } from "../../mail/useUnreadTitle.js";
45
- import UnlockBridge from "../../mail/outbox/UnlockBridge.js";
46
- import NotificationCenter from "../../notifications/NotificationCenter.js";
47
- import { useHeaderHeightRef } from "../../notifications/headerOffset.js";
48
- import NotificationHistoryDialog from "../../notifications/NotificationHistoryDialog.js";
49
- import { notifySessionExpired, setSignInUrl } from "../../notifications/apiErrors.js";
50
- import { useUnseenErrorCount } from "../../notifications/useNotifications.js";
51
- import { useSigningEnrollmentWatcher } from "../../signing/useSigningEnrollmentWatcher.js";
52
- import { useCalendarReminders } from "../../calendar/useCalendarReminders.js";
53
-
54
- /** How long sign-out waits for auth-server's logout before navigating anyway. */
55
- export const LOGOUT_TIMEOUT_MS = 3_000;
56
-
57
- /**
58
- * Calls auth-server's logout (`POST /api/auth/logout`, cross-origin with credentials), which clears the auth
59
- * cookie and invalidates the session's refresh token. Bounded by `LOGOUT_TIMEOUT_MS` and never rejects - a
60
- * failure (unreachable server, CORS) must not keep the user from leaving.
61
- */
62
- async function logOutOfAuthServer(authServerUrl: string | undefined): Promise<void> {
63
- if (!authServerUrl) {
64
- return;
65
- }
66
- const controller = new AbortController();
67
- const timer = setTimeout(() => controller.abort(), LOGOUT_TIMEOUT_MS);
68
- try {
69
- await authApiFetch(authServerUrl, "/auth/logout", { method: "POST", signal: controller.signal });
70
- } catch {
71
- // Navigate anyway - see this function's doc comment.
72
- } finally {
73
- clearTimeout(timer);
74
- }
75
- }
76
-
77
- export type AppShellApp = "mail" | "calendar" | "contacts" | "tasks";
78
-
79
- /** `"settings"` is a valid `active` value but deliberately has no entry in `APPS` below — Settings is
80
- * reached via a `UserMenu` item, not a 5th rail icon (see `SettingsShell.tsx`), so it highlights no
81
- * rail/tab icon at all; only the header title needs to account for it. Any other string is a plugin's
82
- * `appRail` item id (see `PluginNav`). */
83
- export type AppShellActive = AppShellApp | "settings" | (string & {});
84
-
85
- export interface AppShellProps extends PluginNavProps {
86
- /** Which icon in the rail is highlighted as the current app — `"settings"` highlights none, and a plugin
87
- * app page passes its own `appRail` item id. */
88
- active: AppShellActive;
89
- /** Populated automatically by the framework from an authenticated request (e.g. a valid `jwt` cookie). */
90
- userUid?: string;
91
- /** auth-server's base URL, injected via the route's `fetchProps`. */
92
- authServerUrl?: string;
93
- /**
94
- * `true` when this session is an admin "log in as user" impersonation (a `jwt_impersonator` cookie is
95
- * present) — see `MailShell`'s original doc comment, unchanged now that this lives here. Drives the
96
- * "you are viewing as this user — stop impersonating" banner below.
97
- */
98
- impersonating?: boolean;
99
- /** Where `mailApi.ts`'s `stopImpersonating()` should call — see `MailShell`'s original doc comment. */
100
- impersonationBaseUrl?: string;
101
- /** `true` when the caller's JWT carries a trusted role — shows an "Admin Console" item in the user menu below. A token
102
- * only carries one once elevated, so a real administrator with an ordinary session is `false` here; the user menu
103
- * asks auth-server about them separately (see `UserMenu`'s `detectAdmin`). */
104
- trusted?: boolean;
105
- /** The role names the server treats as trusted (its `trusted_roles` config, injected via the route's `fetchProps`) -
106
- * what that lookup looks for. Absent means the server's own default, `["admin"]`. */
107
- trustedRoles?: string[];
108
- /** The deployment's branding as the server rendered the page (its `branding` prop). Used until the frame's own fetch answers, so a custom header is there from the first paint - and the frame knows to drop its own title bar - instead of appearing (and moving everything) once the request returns. */
109
- branding?: Branding;
110
- /** The signed-in user's stored appearance preferences as the server rendered the page (its `appearance` prop), so the first paint already wears the theme and background - see `AppearanceProvider`. */
111
- appearance?: unknown;
112
- }
113
-
114
- export interface AppDef {
115
- id: AppShellApp;
116
- href: string;
117
- label: string;
118
- icon: IconType;
119
- }
120
-
121
- export const APPS: AppDef[] = [
122
- { id: "mail", href: APP_HREFS.mail, label: "Mail", icon: HiOutlineEnvelope },
123
- { id: "calendar", href: APP_HREFS.calendar, label: "Calendar", icon: HiOutlineCalendarDays },
124
- { id: "contacts", href: APP_HREFS.contacts, label: "Contacts", icon: HiOutlineUsers },
125
- { id: "tasks", href: APP_HREFS.tasks, label: "Tasks", icon: HiOutlineClipboardDocumentList },
126
- ];
127
-
128
- /** Ids plugin `appRail` items can't take besides `APPS`' own - `"settings"` has no rail icon but is still a
129
- * core `active` value. */
130
- const RESERVED_APP_IDS = ["settings"];
131
-
132
- /** `APPS` followed by the plugins' `appRail` items (generic icon), core ids winning - see `mergePluginNavItems`. */
133
- export function appRailItems(pluginNav?: PluginNav): NavItem[] {
134
- return mergePluginNavItems<NavItem>(
135
- APPS,
136
- pluginNav?.appRail,
137
- ({ id, href, label }) => ({ id, href, label, icon: HiOutlinePuzzlePiece }),
138
- RESERVED_APP_IDS,
139
- );
140
- }
141
-
142
- /** What only the persistent frame (`apps/www/_shell.tsx`) passes to the chrome it keeps mounted. */
143
- export interface AppChromeProps extends AppShellProps {
144
- /** The router is loading the next page - the content is `aria-busy`. */
145
- busy?: boolean;
146
- /** A screen that takes over the window (`FrameTakeover`) is showing: the rail, header, banner and footer are hidden - not
147
- * unmounted, so what is inside them (and the page in the content region) keeps its state. */
148
- hideChrome?: boolean;
149
- }
150
-
151
- /**
152
- * The persistent chrome shared by every webmail app (Mail, Calendar, Contacts, Tasks): a left icon rail for
153
- * switching apps, a header with the current app's name and `UserMenu`, and the impersonation banner.
154
- * Each app's own shell (e.g. `MailShell`) renders its own contextual sidebar + content as `children`, inside
155
- * the area to the right of the icon rail and below the header.
156
- *
157
- * Rendered by the webmail's app shell (`apps/www/_shell.tsx`, the router's persistent client layout), once, for the life of the
158
- * page, so that moving between apps replaces only `children` - see `AppShell` below for what a page's own shell renders instead.
159
- */
160
- export function AppChrome({
161
- active,
162
- userUid,
163
- authServerUrl,
164
- impersonating,
165
- impersonationBaseUrl,
166
- trusted,
167
- trustedRoles,
168
- branding: initialBranding,
169
- appearance,
170
- pluginNav,
171
- busy,
172
- hideChrome,
173
- children,
174
- }: PropsWithChildren<AppChromeProps>) {
175
- const [stoppingImpersonation, setStoppingImpersonation] = useState(false);
176
- // The keyboard shortcuts dialog: opened by `?`/Ctrl+/ (`GlobalShortcuts`) and by the account menu's item.
177
- const [shortcutsOpen, setShortcutsOpen] = useState(false);
178
- // The pop-up history ("Recent notifications" in the account menu). The pop-ups themselves are drawn by `NotificationCenter`, below.
179
- const [historyOpen, setHistoryOpen] = useState(false);
180
- // Only the count is read, so the whole frame does not render again for every pop-up that comes and goes.
181
- const unseenErrors = useUnseenErrorCount();
182
- // The title bar's height for the pop-up stack, which sticks just below the header (a branding header publishes its own - `FrameBrandingHeader`).
183
- const headerRef = useHeaderHeightRef();
184
- const signingOutRef = useRef(false);
185
- const { branding: fetchedBranding, iconSrc: fetchedIconSrc } = useBranding();
186
- // The server's copy until the fetch answers, so the frame's shape (a custom header replaces the title bar) never changes after the first paint.
187
- const branding = fetchedBranding ?? initialBranding ?? null;
188
- const iconSrc = fetchedBranding ? fetchedIconSrc : initialBranding?.iconUrl || initialBranding?.logoUrl || fetchedIconSrc;
189
- // The custom header and footer, sanitized and with their `{USER_MENU}` / `{APP_TITLE}` placeholders (`undefined` until parsed, `null` when there is none).
190
- const header = useBrandingHtml(branding?.headerHtml);
191
- const footer = useBrandingHtml(branding?.footerHtml);
192
- // The mailboxes, their folders and the one push connection live here, in the frame that stays mounted as the router swaps pages - so
193
- // new-mail pop-ups, the folder counters and the tab title's unread count work in Calendar, Contacts, Tasks and Settings too, and moving
194
- // between apps never opens a second socket (the server allows ten per user). `MailShell` reads them from `MailConnectionContext`. Outside
195
- // the router (`AppShell` rendered as a page's own chrome: tests, plugin pages) it stays off, and a Mail shell owns its connection itself.
196
- const inFrame = useInAppFrame();
197
- const navigate = useNavigate();
198
- const { pathname } = useRouter();
199
- const mail = useMailConnection({ userUid, enabled: inFrame, open: navigate });
200
- // A signing certificate the user asked for is announced when it is issued (or fails), on whichever page they are - see the hook.
201
- useSigningEnrollmentWatcher({ userUid, mailboxes: mail.mailboxes, enabled: inFrame });
202
- // A meeting reminder pops up on whichever page they are - see the hook.
203
- useCalendarReminders({ userUid, enabled: inFrame });
204
-
205
- useRedirectIfUnauthenticated(userUid, authServerUrl);
206
- // Any request this app makes that the server answers with a 401 - the session ended - raises one "Your session expired" pop-up with a
207
- // Sign in action (see `notifySessionExpired()`), whichever request noticed first, a background refresh included.
208
- useEffect(() => {
209
- setSignInUrl(authServerUrl);
210
- if (!userUid) {
211
- return;
212
- }
213
- setApiUnauthorizedObserver(() => void notifySessionExpired());
214
- return () => setApiUnauthorizedObserver(undefined);
215
- }, [userUid, authServerUrl]);
216
- // Mounted here, not scoped to Mail/Settings (the only shells that actually read unlocked keys),
217
- // specifically so activity in *any* app resets the idle clock - see that hook's own doc comment.
218
- useIdleKeyTimeout();
219
-
220
- // An administrator on a server that hasn't finished first-run setup is sent to the setup wizard. The status
221
- // check is admin-only, so it's only made for a trusted caller - everyone else would just get a 403 on every
222
- // page load. Any failure is ignored.
223
- useEffect(() => {
224
- if (!userUid || impersonating || !trusted) {
225
- return;
226
- }
227
- getSetupStatus()
228
- .then((status) => {
229
- if (status.required) {
230
- window.location.href = "/admin/setup";
231
- }
232
- })
233
- .catch(() => undefined);
234
- }, [userUid, impersonating, trusted]);
235
-
236
- // Another tab signing out (this app's `handleSignOut`, or the admin/escrow consoles' `signOutOfConsole()`)
237
- // ended this session too - its auth cookie is gone - so this tab destroys its own unlocked keys and every
238
- // local search index on the device, then leaves as well. The consoles have no local-index client of their
239
- // own, so this is what actually removes the indexes after a console sign-out (the console also records a
240
- // pending deletion, retried on the next mail load, in case no mail tab is open). `destroyAllLocalIndexes()`
241
- // announces the sign-out on this same channel, which this tab then hears itself, so the ref is set first:
242
- // each tab reacts once, and the tab that started the sign-out ignores its own announcement.
243
- useEffect(() => {
244
- if (!userUid || typeof BroadcastChannel === "undefined") {
245
- return;
246
- }
247
- const channel = new BroadcastChannel(SIGN_OUT_CHANNEL);
248
- channel.addEventListener("message", (event: MessageEvent<{ type?: string }>) => {
249
- if (event.data?.type !== "sign-out" || signingOutRef.current) {
250
- return;
251
- }
252
- signingOutRef.current = true;
253
- // Compose windows must not ask "Leave site?" - that would let this forced navigation be cancelled.
254
- markSigningOut();
255
- destroyUnlockedKeys();
256
- clearPinnedSignerCache();
257
- clearAppearanceCache();
258
- // Bounded by its own timeout and never rejects - awaited so navigating doesn't kill the Worker mid-delete.
259
- void destroyAllLocalIndexes().then(() => {
260
- window.location.href = authServerUrl ?? "/";
261
- });
262
- });
263
- return () => channel.close();
264
- }, [userUid, authServerUrl]);
265
-
266
- async function handleSignOut() {
267
- signingOutRef.current = true;
268
- // Before flushing and navigating: compose windows then skip their "Leave site?" prompt, which could
269
- // otherwise cancel the sign-out's own navigation.
270
- markSigningOut();
271
- // Unlocked private keys never outlive an explicit sign-out.
272
- destroyUnlockedKeys();
273
- // Trusted signer pins read from contacts don't outlive the session either.
274
- clearPinnedSignerCache();
275
- clearAppearanceCache();
276
- // Open compose windows save edits still waiting on their autosave debounce while the session is still
277
- // valid - logout invalidates it. Bounded the same way as logout itself, and never rejects.
278
- await flushComposeDrafts(LOGOUT_TIMEOUT_MS);
279
- // The Tier 2 local index MUST be destroyed on explicit logout, the same as unlocked keys themselves
280
- // (spec §11). Destroys every index on this device (not only mailboxes opened this page load) and is
281
- // awaited before navigating - a navigation tears down the Worker mid-delete otherwise.
282
- // destroyAllLocalIndexes() is bounded by its own timeout and never rejects, so sign-out can't hang.
283
- // In parallel, auth-server's logout clears the auth cookie and invalidates the session's refresh
284
- // token - without it, "Sign Out" would only navigate away from a still-valid session.
285
- await Promise.all([destroyAllLocalIndexes(), logOutOfAuthServer(authServerUrl)]);
286
- window.location.href = authServerUrl ?? "/";
287
- }
288
-
289
- async function handleStopImpersonating() {
290
- setStoppingImpersonation(true);
291
- try {
292
- await stopImpersonating(impersonationBaseUrl ?? "");
293
- } catch {
294
- // Navigate either way: a failed call leaves the impersonator cookie (and this banner) exactly as
295
- // they were, so there's nothing else useful to show — matching this app's other network-error
296
- // handling, which surfaces via a full reload rather than an inline retry affordance.
297
- } finally {
298
- window.location.href = "/admin";
299
- }
300
- }
301
-
302
- // The tab's title in the frame is each page's own (its `title` export: rendered by the server, set again by the router on every navigation),
303
- // but `useBranding()` above sets it to the branding's title once its fetch answers - a title for a page that has none. The page's is put back:
304
- // the layout effect reads it before that hook's effect runs, this one (declared after it) writes it back.
305
- const pageTitleRef = useRef("");
306
- useLayoutEffect(() => {
307
- pageTitleRef.current = document.title;
308
- }, [fetchedBranding?.title]);
309
- useEffect(() => {
310
- if (inFrame) {
311
- document.title = pageTitleRef.current;
312
- }
313
- }, [fetchedBranding?.title, inFrame]);
314
- // The router sets the document's title to the page's own whenever the page changes, which drops the unread count this puts in front
315
- // of it, so a new pathname is what puts the count back. (A folder change is shallow and keeps the title.)
316
- useUnreadTitle(inboxUnreadTotal(mail.mailboxFolders, mail.folderCounts.counts), { enabled: inFrame, resetKey: pathname });
317
-
318
- if (!userUid) {
319
- return <div className="min-h-screen" />;
320
- }
321
-
322
- const apps = appRailItems(pluginNav);
323
- // The header title: "settings" has no rail item, everything else is labelled by its own rail item.
324
- const activeLabel = active === "settings" ? "Settings" : apps.find((app) => app.id === active)?.label;
325
- // A custom header (`Branding.headerHtml`) replaces the app's own title bar and the icon at the top of the rail: it is the top of the app, and the
326
- // account menu moves into it. While it is still being parsed it already counts, so the frame's shape doesn't change under the user.
327
- const customHeader = header !== null;
328
- // Where the one account menu lives: the header's `{USER_MENU}`, else the footer's, else a small cell at the header's right end - never lost.
329
- const menuInHeader = !!header?.hasUserMenu;
330
- const menuInFooter = customHeader && !!header && !menuInHeader && !!footer?.hasUserMenu;
331
- const renderUserMenu = (placement: "down" | "up") => (
332
- <UserMenu
333
- userUid={userUid}
334
- authServerUrl={authServerUrl}
335
- onSignOut={handleSignOut}
336
- // An impersonating administrator acts as the impersonated user, so the console link is hidden then.
337
- showAdminLink={!!trusted && !impersonating}
338
- detectAdmin={!trusted && !impersonating}
339
- trustedRoles={trustedRoles}
340
- showSettingsLink
341
- showNotificationSettings
342
- onShowShortcuts={() => setShortcutsOpen(true)}
343
- onShowNotifications={() => setHistoryOpen(true)}
344
- unseenErrors={unseenErrors}
345
- placement={placement}
346
- />
347
- );
348
-
349
- return (
350
- // Mounted here, not scoped to Mail/Settings, for the same reason as useIdleKeyTimeout() above -
351
- // ComposeWindow's sign/encrypt toggles and MessageDetailPane's encrypted-message view (both Mail)
352
- // are today's only useUnlockPrompt() callers, but this needs to be available to any app shell.
353
- // Asks the server for the user's appearance only in the persistent frame (every core page); a page that renders its own chrome (a plugin's) uses the
354
- // `appearance` it was given and what this browser cached.
355
- <AppearanceProvider userUid={userUid} initial={appearance} lookUp={inFrame}>
356
- <ShortcutProvider>
357
- <MailConnectionContext.Provider value={inFrame ? mail : null}>
358
- <GlobalShortcuts authServerUrl={authServerUrl} onToggleHelp={() => setShortcutsOpen((open) => !open)} />
359
- <ShortcutsDialog open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
360
- <UnlockPromptProvider>
361
- <UnlockBridge />
362
- {/* An impersonating admin acts with the impersonated user's access, so their own trusted role
363
- mustn't skip the per-mailbox checks. */}
364
- <ComposeProvider userUid={userUid} trusted={!!trusted && !impersonating}>
365
- <div className="rr-frame-bg min-h-screen flex flex-col">
366
- {!hideChrome && customHeader && (
367
- <FrameBrandingHeader
368
- parsed={header}
369
- userMenu={menuInHeader ? renderUserMenu("down") : undefined}
370
- fallbackMenu={header && !menuInHeader && !menuInFooter ? renderUserMenu("down") : undefined}
371
- appTitle={activeLabel}
372
- />
373
- )}
374
- {impersonating && !hideChrome && (
375
- <div className="h-10 shrink-0 bg-warning text-warning-contrast flex items-center justify-center gap-3 text-sm font-medium px-4">
376
- <span>
377
- You are viewing as <strong>{userUid}</strong>.
378
- </span>
379
- <button
380
- type="button"
381
- onClick={handleStopImpersonating}
382
- disabled={stoppingImpersonation}
383
- className="underline hover:no-underline disabled:opacity-60"
384
- >
385
- {stoppingImpersonation ? "Returning to admin…" : "Return to admin"}
386
- </button>
387
- </div>
388
- )}
389
- <div className="flex-1 flex min-h-0">
390
- {!hideChrome && (
391
- <nav
392
- aria-label="Apps"
393
- className={[
394
- "hidden md:flex w-16 shrink-0 bg-surface border-r border-border flex-col items-center gap-1",
395
- // Under a custom header the rail starts with the app icons; without one its own icon is flush with the top of the window.
396
- customHeader ? "py-3" : "pb-3",
397
- ].join(" ")}
398
- >
399
- {!customHeader && (
400
- <RailIcon src={iconSrc} />
401
- )}
402
- {apps.map(({ id, href, label, icon: Icon }) => (
403
- <a
404
- key={id}
405
- href={href}
406
- aria-label={label}
407
- aria-current={id === active ? "page" : undefined}
408
- title={label}
409
- className={[
410
- "w-10 h-10 flex items-center justify-center rounded-sm",
411
- id === active
412
- ? "bg-primary/10 text-primary-dark"
413
- : "text-text-muted hover:bg-surface-alt hover:text-text",
414
- ].join(" ")}
415
- >
416
- <Icon size={20} aria-hidden="true" />
417
- </a>
418
- ))}
419
- </nav>
420
- )}
421
- {!hideChrome && <BottomTabBar apps={apps} active={active} />}
422
- <div className="flex-1 flex flex-col min-w-0">
423
- {!hideChrome && !customHeader && (
424
- <header ref={headerRef} className="rr-solid sticky top-0 z-30 h-16 shrink-0 bg-surface border-b border-border flex items-center justify-between gap-4 px-6">
425
- <span className="font-display font-bold text-lg uppercase tracking-wide">{activeLabel}</span>
426
- {renderUserMenu("down")}
427
- </header>
428
- )}
429
- {/* The one pop-up stack for the whole app: right under the header row, so it never covers the account menu. */}
430
- <NotificationCenter />
431
- <div
432
- id="app-content"
433
- tabIndex={-1}
434
- aria-busy={busy || undefined}
435
- className={["flex-1 flex min-h-0 outline-none", hideChrome ? "" : "pb-14 md:pb-0"].join(" ")}
436
- >
437
- {children}
438
- </div>
439
- </div>
440
- </div>
441
- {!hideChrome && <FrameBrandingFooter parsed={footer} userMenu={menuInFooter ? renderUserMenu("up") : undefined} appTitle={activeLabel} />}
442
- </div>
443
- </ComposeProvider>
444
- </UnlockPromptProvider>
445
- <NotificationHistoryDialog open={historyOpen} onClose={() => setHistoryOpen(false)} />
446
- </MailConnectionContext.Provider>
447
- </ShortcutProvider>
448
- </AppearanceProvider>
449
- );
450
- }
451
-
452
- /**
453
- * What a page's own shell (`MailShell`, `CalendarShell`, ...) renders around its content. Outside the client-side router it
454
- * is the whole `AppChrome`, as it always was. Inside it (the router's app shell, `apps/www/_shell.tsx`) the chrome is already mounted above the
455
- * page - and stays mounted as the page is replaced - so this is only its children; everything it would have been given comes from
456
- * the shell instead (the props are the same for every page, and `active` is the route's).
457
- */
458
- export default function AppShell(props: PropsWithChildren<AppShellProps>) {
459
- const inFrame = useInAppFrame();
460
- return inFrame ? <>{props.children}</> : <AppChrome {...props} />;
461
- }
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2026 Jean-Philippe Steinmetz
3
+ // SPDX-License-Identifier: MPL-2.0
4
+ ///////////////////////////////////////////////////////////////////////////////
5
+ import "../../styles/app.css";
6
+ import React, { PropsWithChildren, useEffect, useLayoutEffect, useRef, useState } from "react";
7
+ import type { IconType } from "react-icons";
8
+ import {
9
+ HiOutlineCalendarDays,
10
+ HiOutlineClipboardDocumentList,
11
+ HiOutlineEnvelope,
12
+ HiOutlinePuzzlePiece,
13
+ HiOutlineUsers,
14
+ } from "react-icons/hi2";
15
+ import { useRouter } from "@rapidrest/react/client";
16
+ import { useRedirectIfUnauthenticated } from "@rapidmx/react-shared/auth/session.js";
17
+ import { getSetupStatus } from "@rapidmx/react-shared/admin/setupApi.js";
18
+ import { stopImpersonating } from "@rapidmx/react-shared/mail/mailApi.js";
19
+ import useBranding from "@rapidmx/react-shared/branding/useBranding.js";
20
+ import { useIdleKeyTimeout } from "@rapidmx/react-shared/crypto/useIdleKeyTimeout.js";
21
+ import ComposeProvider from "../mail/compose/ComposeContext.js";
22
+ import { flushComposeDrafts, markSigningOut } from "../mail/compose/composeFlushRegistry.js";
23
+ import BottomTabBar, { NavItem } from "@rapidmx/react-shared/components/navigation/BottomTabBar.js";
24
+ import { FrameBrandingFooter, FrameBrandingHeader, useBrandingHtml } from "./BrandingChrome.js";
25
+ import RailIcon from "./RailIcon.js";
26
+ import AppearanceProvider from "../../appearance/AppearanceProvider.js";
27
+ import { clearAppearanceCache } from "../../appearance/appearanceCache.js";
28
+ import type { Branding } from "@rapidmx/react-shared/branding/brandingApi.js";
29
+ import UserMenu from "./UserMenu.js";
30
+ import { UnlockPromptProvider } from "./UnlockPromptProvider.js";
31
+ import { SIGN_OUT_CHANNEL, destroyAllLocalIndexes } from "../../search/localIndexRpcClient.js";
32
+ import { authApiFetch, setApiUnauthorizedObserver } from "@rapidmx/react-shared/util/api.js";
33
+ import { destroyUnlockedKeys } from "@rapidmx/react-shared/crypto/keySession.js";
34
+ import { clearPinnedSignerCache } from "../mail/pinnedSigners.js";
35
+ import { mergePluginNavItems, PluginNav, PluginNavProps } from "../../plugins/pluginNav.js";
36
+ import { useInAppFrame } from "../../navigation/frameContext.js";
37
+ import { APP_HREFS } from "../../navigation/appHrefs.js";
38
+ import { useNavigate } from "../../navigation/index.js";
39
+ import { GlobalShortcuts } from "../../keyboard/GlobalShortcuts.js";
40
+ import { ShortcutProvider } from "../../keyboard/ShortcutProvider.js";
41
+ import ShortcutsDialog from "../../keyboard/ShortcutsDialog.js";
42
+ import { inboxUnreadTotal } from "../../mail/folderCounts.js";
43
+ import { MailConnectionContext, useMailConnection } from "../../mail/useMailConnection.js";
44
+ import { useUnreadTitle } from "../../mail/useUnreadTitle.js";
45
+ import UnlockBridge from "../../mail/outbox/UnlockBridge.js";
46
+ import NotificationCenter from "../../notifications/NotificationCenter.js";
47
+ import { useHeaderHeightRef } from "../../notifications/headerOffset.js";
48
+ import NotificationHistoryDialog from "../../notifications/NotificationHistoryDialog.js";
49
+ import { notifySessionExpired, setSignInUrl } from "../../notifications/apiErrors.js";
50
+ import { useUnseenErrorCount } from "../../notifications/useNotifications.js";
51
+ import { useSigningEnrollmentWatcher } from "../../signing/useSigningEnrollmentWatcher.js";
52
+ import { useCalendarReminders } from "../../calendar/useCalendarReminders.js";
53
+
54
+ /** How long sign-out waits for auth-server's logout before navigating anyway. */
55
+ export const LOGOUT_TIMEOUT_MS = 3_000;
56
+
57
+ /**
58
+ * Calls auth-server's logout (`POST /api/auth/logout`, cross-origin with credentials), which clears the auth
59
+ * cookie and invalidates the session's refresh token. Bounded by `LOGOUT_TIMEOUT_MS` and never rejects - a
60
+ * failure (unreachable server, CORS) must not keep the user from leaving.
61
+ */
62
+ async function logOutOfAuthServer(authServerUrl: string | undefined): Promise<void> {
63
+ if (!authServerUrl) {
64
+ return;
65
+ }
66
+ const controller = new AbortController();
67
+ const timer = setTimeout(() => controller.abort(), LOGOUT_TIMEOUT_MS);
68
+ try {
69
+ await authApiFetch(authServerUrl, "/auth/logout", { method: "POST", signal: controller.signal });
70
+ } catch {
71
+ // Navigate anyway - see this function's doc comment.
72
+ } finally {
73
+ clearTimeout(timer);
74
+ }
75
+ }
76
+
77
+ export type AppShellApp = "mail" | "calendar" | "contacts" | "tasks";
78
+
79
+ /** `"settings"` is a valid `active` value but deliberately has no entry in `APPS` below — Settings is
80
+ * reached via a `UserMenu` item, not a 5th rail icon (see `SettingsShell.tsx`), so it highlights no
81
+ * rail/tab icon at all; only the header title needs to account for it. Any other string is a plugin's
82
+ * `appRail` item id (see `PluginNav`). */
83
+ export type AppShellActive = AppShellApp | "settings" | (string & {});
84
+
85
+ export interface AppShellProps extends PluginNavProps {
86
+ /** Which icon in the rail is highlighted as the current app — `"settings"` highlights none, and a plugin
87
+ * app page passes its own `appRail` item id. */
88
+ active: AppShellActive;
89
+ /** Populated automatically by the framework from an authenticated request (e.g. a valid `jwt` cookie). */
90
+ userUid?: string;
91
+ /** auth-server's base URL, injected via the route's `fetchProps`. */
92
+ authServerUrl?: string;
93
+ /**
94
+ * `true` when this session is an admin "log in as user" impersonation (a `jwt_impersonator` cookie is
95
+ * present) — see `MailShell`'s original doc comment, unchanged now that this lives here. Drives the
96
+ * "you are viewing as this user — stop impersonating" banner below.
97
+ */
98
+ impersonating?: boolean;
99
+ /** Where `mailApi.ts`'s `stopImpersonating()` should call — see `MailShell`'s original doc comment. */
100
+ impersonationBaseUrl?: string;
101
+ /** `true` when the caller's JWT carries a trusted role — shows an "Admin Console" item in the user menu below. A token
102
+ * only carries one once elevated, so a real administrator with an ordinary session is `false` here; the user menu
103
+ * asks auth-server about them separately (see `UserMenu`'s `detectAdmin`). */
104
+ trusted?: boolean;
105
+ /** The role names the server treats as trusted (its `trusted_roles` config, injected via the route's `fetchProps`) -
106
+ * what that lookup looks for. Absent means the server's own default, `["admin"]`. */
107
+ trustedRoles?: string[];
108
+ /** The deployment's branding as the server rendered the page (its `branding` prop). Used until the frame's own fetch answers, so a custom header is there from the first paint - and the frame knows to drop its own title bar - instead of appearing (and moving everything) once the request returns. */
109
+ branding?: Branding;
110
+ /** The signed-in user's stored appearance preferences as the server rendered the page (its `appearance` prop), so the first paint already wears the theme and background - see `AppearanceProvider`. */
111
+ appearance?: unknown;
112
+ }
113
+
114
+ export interface AppDef {
115
+ id: AppShellApp;
116
+ href: string;
117
+ label: string;
118
+ icon: IconType;
119
+ }
120
+
121
+ export const APPS: AppDef[] = [
122
+ { id: "mail", href: APP_HREFS.mail, label: "Mail", icon: HiOutlineEnvelope },
123
+ { id: "calendar", href: APP_HREFS.calendar, label: "Calendar", icon: HiOutlineCalendarDays },
124
+ { id: "contacts", href: APP_HREFS.contacts, label: "Contacts", icon: HiOutlineUsers },
125
+ { id: "tasks", href: APP_HREFS.tasks, label: "Tasks", icon: HiOutlineClipboardDocumentList },
126
+ ];
127
+
128
+ /** Ids plugin `appRail` items can't take besides `APPS`' own - `"settings"` has no rail icon but is still a
129
+ * core `active` value. */
130
+ const RESERVED_APP_IDS = ["settings"];
131
+
132
+ /** `APPS` followed by the plugins' `appRail` items (generic icon), core ids winning - see `mergePluginNavItems`. */
133
+ export function appRailItems(pluginNav?: PluginNav): NavItem[] {
134
+ return mergePluginNavItems<NavItem>(
135
+ APPS,
136
+ pluginNav?.appRail,
137
+ ({ id, href, label }) => ({ id, href, label, icon: HiOutlinePuzzlePiece }),
138
+ RESERVED_APP_IDS,
139
+ );
140
+ }
141
+
142
+ /** What only the persistent frame (`apps/www/_shell.tsx`) passes to the chrome it keeps mounted. */
143
+ export interface AppChromeProps extends AppShellProps {
144
+ /** The router is loading the next page - the content is `aria-busy`. */
145
+ busy?: boolean;
146
+ /** A screen that takes over the window (`FrameTakeover`) is showing: the rail, header, banner and footer are hidden - not
147
+ * unmounted, so what is inside them (and the page in the content region) keeps its state. */
148
+ hideChrome?: boolean;
149
+ }
150
+
151
+ /**
152
+ * The persistent chrome shared by every webmail app (Mail, Calendar, Contacts, Tasks): a left icon rail for
153
+ * switching apps, a header with the current app's name and `UserMenu`, and the impersonation banner.
154
+ * Each app's own shell (e.g. `MailShell`) renders its own contextual sidebar + content as `children`, inside
155
+ * the area to the right of the icon rail and below the header.
156
+ *
157
+ * Rendered by the webmail's app shell (`apps/www/_shell.tsx`, the router's persistent client layout), once, for the life of the
158
+ * page, so that moving between apps replaces only `children` - see `AppShell` below for what a page's own shell renders instead.
159
+ */
160
+ export function AppChrome({
161
+ active,
162
+ userUid,
163
+ authServerUrl,
164
+ impersonating,
165
+ impersonationBaseUrl,
166
+ trusted,
167
+ trustedRoles,
168
+ branding: initialBranding,
169
+ appearance,
170
+ pluginNav,
171
+ busy,
172
+ hideChrome,
173
+ children,
174
+ }: PropsWithChildren<AppChromeProps>) {
175
+ const [stoppingImpersonation, setStoppingImpersonation] = useState(false);
176
+ // The keyboard shortcuts dialog: opened by `?`/Ctrl+/ (`GlobalShortcuts`) and by the account menu's item.
177
+ const [shortcutsOpen, setShortcutsOpen] = useState(false);
178
+ // The pop-up history ("Recent notifications" in the account menu). The pop-ups themselves are drawn by `NotificationCenter`, below.
179
+ const [historyOpen, setHistoryOpen] = useState(false);
180
+ // Only the count is read, so the whole frame does not render again for every pop-up that comes and goes.
181
+ const unseenErrors = useUnseenErrorCount();
182
+ // The title bar's height for the pop-up stack, which sticks just below the header (a branding header publishes its own - `FrameBrandingHeader`).
183
+ const headerRef = useHeaderHeightRef();
184
+ const signingOutRef = useRef(false);
185
+ const { branding: fetchedBranding, iconSrc: fetchedIconSrc } = useBranding();
186
+ // The server's copy until the fetch answers, so the frame's shape (a custom header replaces the title bar) never changes after the first paint.
187
+ const branding = fetchedBranding ?? initialBranding ?? null;
188
+ const iconSrc = fetchedBranding ? fetchedIconSrc : initialBranding?.iconUrl || initialBranding?.logoUrl || fetchedIconSrc;
189
+ // The custom header and footer, sanitized and with their `{USER_MENU}` / `{APP_TITLE}` placeholders (`undefined` until parsed, `null` when there is none).
190
+ const header = useBrandingHtml(branding?.headerHtml);
191
+ const footer = useBrandingHtml(branding?.footerHtml);
192
+ // The mailboxes, their folders and the one push connection live here, in the frame that stays mounted as the router swaps pages - so
193
+ // new-mail pop-ups, the folder counters and the tab title's unread count work in Calendar, Contacts, Tasks and Settings too, and moving
194
+ // between apps never opens a second socket (the server allows ten per user). `MailShell` reads them from `MailConnectionContext`. Outside
195
+ // the router (`AppShell` rendered as a page's own chrome: tests, plugin pages) it stays off, and a Mail shell owns its connection itself.
196
+ const inFrame = useInAppFrame();
197
+ const navigate = useNavigate();
198
+ const { pathname } = useRouter();
199
+ const mail = useMailConnection({ userUid, enabled: inFrame, open: navigate });
200
+ // A signing certificate the user asked for is announced when it is issued (or fails), on whichever page they are - see the hook.
201
+ useSigningEnrollmentWatcher({ userUid, mailboxes: mail.mailboxes, enabled: inFrame });
202
+ // A meeting reminder pops up on whichever page they are - see the hook.
203
+ useCalendarReminders({ userUid, enabled: inFrame });
204
+
205
+ useRedirectIfUnauthenticated(userUid, authServerUrl);
206
+ // Any request this app makes that the server answers with a 401 - the session ended - raises one "Your session expired" pop-up with a
207
+ // Sign in action (see `notifySessionExpired()`), whichever request noticed first, a background refresh included.
208
+ useEffect(() => {
209
+ setSignInUrl(authServerUrl);
210
+ if (!userUid) {
211
+ return;
212
+ }
213
+ setApiUnauthorizedObserver(() => void notifySessionExpired());
214
+ return () => setApiUnauthorizedObserver(undefined);
215
+ }, [userUid, authServerUrl]);
216
+ // Mounted here, not scoped to Mail/Settings (the only shells that actually read unlocked keys),
217
+ // specifically so activity in *any* app resets the idle clock - see that hook's own doc comment.
218
+ useIdleKeyTimeout();
219
+
220
+ // An administrator on a server that hasn't finished first-run setup is sent to the setup wizard. The status
221
+ // check is admin-only, so it's only made for a trusted caller - everyone else would just get a 403 on every
222
+ // page load. Any failure is ignored.
223
+ useEffect(() => {
224
+ if (!userUid || impersonating || !trusted) {
225
+ return;
226
+ }
227
+ getSetupStatus()
228
+ .then((status) => {
229
+ if (status.required) {
230
+ window.location.href = "/admin/setup";
231
+ }
232
+ })
233
+ .catch(() => undefined);
234
+ }, [userUid, impersonating, trusted]);
235
+
236
+ // Another tab signing out (this app's `handleSignOut`, or the admin/escrow consoles' `signOutOfConsole()`)
237
+ // ended this session too - its auth cookie is gone - so this tab destroys its own unlocked keys and every
238
+ // local search index on the device, then leaves as well. The consoles have no local-index client of their
239
+ // own, so this is what actually removes the indexes after a console sign-out (the console also records a
240
+ // pending deletion, retried on the next mail load, in case no mail tab is open). `destroyAllLocalIndexes()`
241
+ // announces the sign-out on this same channel, which this tab then hears itself, so the ref is set first:
242
+ // each tab reacts once, and the tab that started the sign-out ignores its own announcement.
243
+ useEffect(() => {
244
+ if (!userUid || typeof BroadcastChannel === "undefined") {
245
+ return;
246
+ }
247
+ const channel = new BroadcastChannel(SIGN_OUT_CHANNEL);
248
+ channel.addEventListener("message", (event: MessageEvent<{ type?: string }>) => {
249
+ if (event.data?.type !== "sign-out" || signingOutRef.current) {
250
+ return;
251
+ }
252
+ signingOutRef.current = true;
253
+ // Compose windows must not ask "Leave site?" - that would let this forced navigation be cancelled.
254
+ markSigningOut();
255
+ destroyUnlockedKeys();
256
+ clearPinnedSignerCache();
257
+ clearAppearanceCache();
258
+ // Bounded by its own timeout and never rejects - awaited so navigating doesn't kill the Worker mid-delete.
259
+ void destroyAllLocalIndexes().then(() => {
260
+ window.location.href = authServerUrl ?? "/";
261
+ });
262
+ });
263
+ return () => channel.close();
264
+ }, [userUid, authServerUrl]);
265
+
266
+ async function handleSignOut() {
267
+ signingOutRef.current = true;
268
+ // Before flushing and navigating: compose windows then skip their "Leave site?" prompt, which could
269
+ // otherwise cancel the sign-out's own navigation.
270
+ markSigningOut();
271
+ // Unlocked private keys never outlive an explicit sign-out.
272
+ destroyUnlockedKeys();
273
+ // Trusted signer pins read from contacts don't outlive the session either.
274
+ clearPinnedSignerCache();
275
+ clearAppearanceCache();
276
+ // Open compose windows save edits still waiting on their autosave debounce while the session is still
277
+ // valid - logout invalidates it. Bounded the same way as logout itself, and never rejects.
278
+ await flushComposeDrafts(LOGOUT_TIMEOUT_MS);
279
+ // The Tier 2 local index MUST be destroyed on explicit logout, the same as unlocked keys themselves
280
+ // (spec §11). Destroys every index on this device (not only mailboxes opened this page load) and is
281
+ // awaited before navigating - a navigation tears down the Worker mid-delete otherwise.
282
+ // destroyAllLocalIndexes() is bounded by its own timeout and never rejects, so sign-out can't hang.
283
+ // In parallel, auth-server's logout clears the auth cookie and invalidates the session's refresh
284
+ // token - without it, "Sign Out" would only navigate away from a still-valid session.
285
+ await Promise.all([destroyAllLocalIndexes(), logOutOfAuthServer(authServerUrl)]);
286
+ window.location.href = authServerUrl ?? "/";
287
+ }
288
+
289
+ async function handleStopImpersonating() {
290
+ setStoppingImpersonation(true);
291
+ try {
292
+ await stopImpersonating(impersonationBaseUrl ?? "");
293
+ } catch {
294
+ // Navigate either way: a failed call leaves the impersonator cookie (and this banner) exactly as
295
+ // they were, so there's nothing else useful to show — matching this app's other network-error
296
+ // handling, which surfaces via a full reload rather than an inline retry affordance.
297
+ } finally {
298
+ window.location.href = "/admin";
299
+ }
300
+ }
301
+
302
+ // The tab's title in the frame is each page's own (its `title` export: rendered by the server, set again by the router on every navigation),
303
+ // but `useBranding()` above sets it to the branding's title once its fetch answers - a title for a page that has none. The page's is put back:
304
+ // the layout effect reads it before that hook's effect runs, this one (declared after it) writes it back.
305
+ const pageTitleRef = useRef("");
306
+ useLayoutEffect(() => {
307
+ pageTitleRef.current = document.title;
308
+ }, [fetchedBranding?.title]);
309
+ useEffect(() => {
310
+ if (inFrame) {
311
+ document.title = pageTitleRef.current;
312
+ }
313
+ }, [fetchedBranding?.title, inFrame]);
314
+ // The router sets the document's title to the page's own whenever the page changes, which drops the unread count this puts in front
315
+ // of it, so a new pathname is what puts the count back. (A folder change is shallow and keeps the title.)
316
+ useUnreadTitle(inboxUnreadTotal(mail.mailboxFolders, mail.folderCounts.counts), { enabled: inFrame, resetKey: pathname });
317
+
318
+ if (!userUid) {
319
+ return <div className="min-h-screen" />;
320
+ }
321
+
322
+ const apps = appRailItems(pluginNav);
323
+ // The header title: "settings" has no rail item, everything else is labelled by its own rail item.
324
+ const activeLabel = active === "settings" ? "Settings" : apps.find((app) => app.id === active)?.label;
325
+ // A custom header (`Branding.headerHtml`) replaces the app's own title bar and the icon at the top of the rail: it is the top of the app, and the
326
+ // account menu moves into it. While it is still being parsed it already counts, so the frame's shape doesn't change under the user.
327
+ const customHeader = header !== null;
328
+ // Where the one account menu lives: the header's `{USER_MENU}`, else the footer's, else a small cell at the header's right end - never lost.
329
+ const menuInHeader = !!header?.hasUserMenu;
330
+ const menuInFooter = customHeader && !!header && !menuInHeader && !!footer?.hasUserMenu;
331
+ const renderUserMenu = (placement: "down" | "up") => (
332
+ <UserMenu
333
+ userUid={userUid}
334
+ authServerUrl={authServerUrl}
335
+ onSignOut={handleSignOut}
336
+ // An impersonating administrator acts as the impersonated user, so the console link is hidden then.
337
+ showAdminLink={!!trusted && !impersonating}
338
+ detectAdmin={!trusted && !impersonating}
339
+ trustedRoles={trustedRoles}
340
+ showSettingsLink
341
+ showNotificationSettings
342
+ onShowShortcuts={() => setShortcutsOpen(true)}
343
+ onShowNotifications={() => setHistoryOpen(true)}
344
+ unseenErrors={unseenErrors}
345
+ placement={placement}
346
+ />
347
+ );
348
+
349
+ return (
350
+ // Mounted here, not scoped to Mail/Settings, for the same reason as useIdleKeyTimeout() above -
351
+ // ComposeWindow's sign/encrypt toggles and MessageDetailPane's encrypted-message view (both Mail)
352
+ // are today's only useUnlockPrompt() callers, but this needs to be available to any app shell.
353
+ // Asks the server for the user's appearance only in the persistent frame (every core page); a page that renders its own chrome (a plugin's) uses the
354
+ // `appearance` it was given and what this browser cached.
355
+ <AppearanceProvider userUid={userUid} initial={appearance} lookUp={inFrame}>
356
+ <ShortcutProvider>
357
+ <MailConnectionContext.Provider value={inFrame ? mail : null}>
358
+ <GlobalShortcuts authServerUrl={authServerUrl} onToggleHelp={() => setShortcutsOpen((open) => !open)} />
359
+ <ShortcutsDialog open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
360
+ <UnlockPromptProvider>
361
+ <UnlockBridge />
362
+ {/* An impersonating admin acts with the impersonated user's access, so their own trusted role
363
+ mustn't skip the per-mailbox checks. */}
364
+ <ComposeProvider userUid={userUid} trusted={!!trusted && !impersonating}>
365
+ <div className="rr-frame-bg min-h-screen flex flex-col">
366
+ {!hideChrome && customHeader && (
367
+ <FrameBrandingHeader
368
+ parsed={header}
369
+ userMenu={menuInHeader ? renderUserMenu("down") : undefined}
370
+ fallbackMenu={header && !menuInHeader && !menuInFooter ? renderUserMenu("down") : undefined}
371
+ appTitle={activeLabel}
372
+ />
373
+ )}
374
+ {impersonating && !hideChrome && (
375
+ <div className="h-10 shrink-0 bg-warning text-warning-contrast flex items-center justify-center gap-3 text-sm font-medium px-4">
376
+ <span>
377
+ You are viewing as <strong>{userUid}</strong>.
378
+ </span>
379
+ <button
380
+ type="button"
381
+ onClick={handleStopImpersonating}
382
+ disabled={stoppingImpersonation}
383
+ className="underline hover:no-underline disabled:opacity-60"
384
+ >
385
+ {stoppingImpersonation ? "Returning to admin…" : "Return to admin"}
386
+ </button>
387
+ </div>
388
+ )}
389
+ <div className="flex-1 flex min-h-0">
390
+ {!hideChrome && (
391
+ <nav
392
+ aria-label="Apps"
393
+ className={[
394
+ "hidden md:flex w-16 shrink-0 bg-surface border-r border-border flex-col items-center gap-1",
395
+ // Under a custom header the rail starts with the app icons; without one its own icon is flush with the top of the window.
396
+ customHeader ? "py-3" : "pb-3",
397
+ ].join(" ")}
398
+ >
399
+ {!customHeader && (
400
+ <RailIcon src={iconSrc} />
401
+ )}
402
+ {apps.map(({ id, href, label, icon: Icon }) => (
403
+ <a
404
+ key={id}
405
+ href={href}
406
+ aria-label={label}
407
+ aria-current={id === active ? "page" : undefined}
408
+ title={label}
409
+ className={[
410
+ "w-10 h-10 flex items-center justify-center rounded-sm",
411
+ id === active
412
+ ? "bg-primary/10 text-primary-dark"
413
+ : "text-text-muted hover:bg-surface-alt hover:text-text",
414
+ ].join(" ")}
415
+ >
416
+ <Icon size={20} aria-hidden="true" />
417
+ </a>
418
+ ))}
419
+ </nav>
420
+ )}
421
+ {!hideChrome && <BottomTabBar apps={apps} active={active} />}
422
+ <div className="flex-1 flex flex-col min-w-0">
423
+ {!hideChrome && !customHeader && (
424
+ <header ref={headerRef} className="rr-solid sticky top-0 z-30 h-16 shrink-0 bg-surface border-b border-border flex items-center justify-between gap-4 px-6">
425
+ <span className="font-display font-bold text-lg uppercase tracking-wide">{activeLabel}</span>
426
+ {renderUserMenu("down")}
427
+ </header>
428
+ )}
429
+ {/* The one pop-up stack for the whole app: right under the header row, so it never covers the account menu. */}
430
+ <NotificationCenter />
431
+ <div
432
+ id="app-content"
433
+ tabIndex={-1}
434
+ aria-busy={busy || undefined}
435
+ className={["flex-1 flex min-h-0 outline-none", hideChrome ? "" : "pb-14 md:pb-0"].join(" ")}
436
+ >
437
+ {children}
438
+ </div>
439
+ </div>
440
+ </div>
441
+ {!hideChrome && <FrameBrandingFooter parsed={footer} userMenu={menuInFooter ? renderUserMenu("up") : undefined} appTitle={activeLabel} />}
442
+ </div>
443
+ </ComposeProvider>
444
+ </UnlockPromptProvider>
445
+ <NotificationHistoryDialog open={historyOpen} onClose={() => setHistoryOpen(false)} />
446
+ </MailConnectionContext.Provider>
447
+ </ShortcutProvider>
448
+ </AppearanceProvider>
449
+ );
450
+ }
451
+
452
+ /**
453
+ * What a page's own shell (`MailShell`, `CalendarShell`, ...) renders around its content. Outside the client-side router it
454
+ * is the whole `AppChrome`, as it always was. Inside it (the router's app shell, `apps/www/_shell.tsx`) the chrome is already mounted above the
455
+ * page - and stays mounted as the page is replaced - so this is only its children; everything it would have been given comes from
456
+ * the shell instead (the props are the same for every page, and `active` is the route's).
457
+ */
458
+ export default function AppShell(props: PropsWithChildren<AppShellProps>) {
459
+ const inFrame = useInAppFrame();
460
+ return inFrame ? <>{props.children}</> : <AppChrome {...props} />;
461
+ }