@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,461 +1,463 @@
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 { useSessionRefresh } 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
+ // A refused refresh means the sign-in has ended: open compose windows save what they hold (the access token still works for a while) and the
206
+ // browser goes to sign-in. Not while viewing as another user - the refresh cookie is the admin's own, and refreshing would end the impersonation.
207
+ useSessionRefresh(userUid, authServerUrl, { paused: impersonating, beforeRedirect: () => flushComposeDrafts(LOGOUT_TIMEOUT_MS) });
208
+ // Any request this app makes that the server answers with a 401 - the session ended - raises one "Your session expired" pop-up with a
209
+ // Sign in action (see `notifySessionExpired()`), whichever request noticed first, a background refresh included.
210
+ useEffect(() => {
211
+ setSignInUrl(authServerUrl);
212
+ if (!userUid) {
213
+ return;
214
+ }
215
+ setApiUnauthorizedObserver(() => void notifySessionExpired());
216
+ return () => setApiUnauthorizedObserver(undefined);
217
+ }, [userUid, authServerUrl]);
218
+ // Mounted here, not scoped to Mail/Settings (the only shells that actually read unlocked keys),
219
+ // specifically so activity in *any* app resets the idle clock - see that hook's own doc comment.
220
+ useIdleKeyTimeout();
221
+
222
+ // An administrator on a server that hasn't finished first-run setup is sent to the setup wizard. The status
223
+ // check is admin-only, so it's only made for a trusted caller - everyone else would just get a 403 on every
224
+ // page load. Any failure is ignored.
225
+ useEffect(() => {
226
+ if (!userUid || impersonating || !trusted) {
227
+ return;
228
+ }
229
+ getSetupStatus()
230
+ .then((status) => {
231
+ if (status.required) {
232
+ window.location.href = "/admin/setup";
233
+ }
234
+ })
235
+ .catch(() => undefined);
236
+ }, [userUid, impersonating, trusted]);
237
+
238
+ // Another tab signing out (this app's `handleSignOut`, or the admin/escrow consoles' `signOutOfConsole()`)
239
+ // ended this session too - its auth cookie is gone - so this tab destroys its own unlocked keys and every
240
+ // local search index on the device, then leaves as well. The consoles have no local-index client of their
241
+ // own, so this is what actually removes the indexes after a console sign-out (the console also records a
242
+ // pending deletion, retried on the next mail load, in case no mail tab is open). `destroyAllLocalIndexes()`
243
+ // announces the sign-out on this same channel, which this tab then hears itself, so the ref is set first:
244
+ // each tab reacts once, and the tab that started the sign-out ignores its own announcement.
245
+ useEffect(() => {
246
+ if (!userUid || typeof BroadcastChannel === "undefined") {
247
+ return;
248
+ }
249
+ const channel = new BroadcastChannel(SIGN_OUT_CHANNEL);
250
+ channel.addEventListener("message", (event: MessageEvent<{ type?: string }>) => {
251
+ if (event.data?.type !== "sign-out" || signingOutRef.current) {
252
+ return;
253
+ }
254
+ signingOutRef.current = true;
255
+ // Compose windows must not ask "Leave site?" - that would let this forced navigation be cancelled.
256
+ markSigningOut();
257
+ destroyUnlockedKeys();
258
+ clearPinnedSignerCache();
259
+ clearAppearanceCache();
260
+ // Bounded by its own timeout and never rejects - awaited so navigating doesn't kill the Worker mid-delete.
261
+ void destroyAllLocalIndexes().then(() => {
262
+ window.location.href = authServerUrl ?? "/";
263
+ });
264
+ });
265
+ return () => channel.close();
266
+ }, [userUid, authServerUrl]);
267
+
268
+ async function handleSignOut() {
269
+ signingOutRef.current = true;
270
+ // Before flushing and navigating: compose windows then skip their "Leave site?" prompt, which could
271
+ // otherwise cancel the sign-out's own navigation.
272
+ markSigningOut();
273
+ // Unlocked private keys never outlive an explicit sign-out.
274
+ destroyUnlockedKeys();
275
+ // Trusted signer pins read from contacts don't outlive the session either.
276
+ clearPinnedSignerCache();
277
+ clearAppearanceCache();
278
+ // Open compose windows save edits still waiting on their autosave debounce while the session is still
279
+ // valid - logout invalidates it. Bounded the same way as logout itself, and never rejects.
280
+ await flushComposeDrafts(LOGOUT_TIMEOUT_MS);
281
+ // The Tier 2 local index MUST be destroyed on explicit logout, the same as unlocked keys themselves
282
+ // (spec §11). Destroys every index on this device (not only mailboxes opened this page load) and is
283
+ // awaited before navigating - a navigation tears down the Worker mid-delete otherwise.
284
+ // destroyAllLocalIndexes() is bounded by its own timeout and never rejects, so sign-out can't hang.
285
+ // In parallel, auth-server's logout clears the auth cookie and invalidates the session's refresh
286
+ // token - without it, "Sign Out" would only navigate away from a still-valid session.
287
+ await Promise.all([destroyAllLocalIndexes(), logOutOfAuthServer(authServerUrl)]);
288
+ window.location.href = authServerUrl ?? "/";
289
+ }
290
+
291
+ async function handleStopImpersonating() {
292
+ setStoppingImpersonation(true);
293
+ try {
294
+ await stopImpersonating(impersonationBaseUrl ?? "");
295
+ } catch {
296
+ // Navigate either way: a failed call leaves the impersonator cookie (and this banner) exactly as
297
+ // they were, so there's nothing else useful to show — matching this app's other network-error
298
+ // handling, which surfaces via a full reload rather than an inline retry affordance.
299
+ } finally {
300
+ window.location.href = "/admin";
301
+ }
302
+ }
303
+
304
+ // 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),
305
+ // 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:
306
+ // the layout effect reads it before that hook's effect runs, this one (declared after it) writes it back.
307
+ const pageTitleRef = useRef("");
308
+ useLayoutEffect(() => {
309
+ pageTitleRef.current = document.title;
310
+ }, [fetchedBranding?.title]);
311
+ useEffect(() => {
312
+ if (inFrame) {
313
+ document.title = pageTitleRef.current;
314
+ }
315
+ }, [fetchedBranding?.title, inFrame]);
316
+ // 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
317
+ // of it, so a new pathname is what puts the count back. (A folder change is shallow and keeps the title.)
318
+ useUnreadTitle(inboxUnreadTotal(mail.mailboxFolders, mail.folderCounts.counts), { enabled: inFrame, resetKey: pathname });
319
+
320
+ if (!userUid) {
321
+ return <div className="min-h-screen" />;
322
+ }
323
+
324
+ const apps = appRailItems(pluginNav);
325
+ // The header title: "settings" has no rail item, everything else is labelled by its own rail item.
326
+ const activeLabel = active === "settings" ? "Settings" : apps.find((app) => app.id === active)?.label;
327
+ // 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
328
+ // 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.
329
+ const customHeader = header !== null;
330
+ // 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.
331
+ const menuInHeader = !!header?.hasUserMenu;
332
+ const menuInFooter = customHeader && !!header && !menuInHeader && !!footer?.hasUserMenu;
333
+ const renderUserMenu = (placement: "down" | "up") => (
334
+ <UserMenu
335
+ userUid={userUid}
336
+ authServerUrl={authServerUrl}
337
+ onSignOut={handleSignOut}
338
+ // An impersonating administrator acts as the impersonated user, so the console link is hidden then.
339
+ showAdminLink={!!trusted && !impersonating}
340
+ detectAdmin={!trusted && !impersonating}
341
+ trustedRoles={trustedRoles}
342
+ showSettingsLink
343
+ showNotificationSettings
344
+ onShowShortcuts={() => setShortcutsOpen(true)}
345
+ onShowNotifications={() => setHistoryOpen(true)}
346
+ unseenErrors={unseenErrors}
347
+ placement={placement}
348
+ />
349
+ );
350
+
351
+ return (
352
+ // Mounted here, not scoped to Mail/Settings, for the same reason as useIdleKeyTimeout() above -
353
+ // ComposeWindow's sign/encrypt toggles and MessageDetailPane's encrypted-message view (both Mail)
354
+ // are today's only useUnlockPrompt() callers, but this needs to be available to any app shell.
355
+ // 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
356
+ // `appearance` it was given and what this browser cached.
357
+ <AppearanceProvider userUid={userUid} initial={appearance} lookUp={inFrame}>
358
+ <ShortcutProvider>
359
+ <MailConnectionContext.Provider value={inFrame ? mail : null}>
360
+ <GlobalShortcuts authServerUrl={authServerUrl} onToggleHelp={() => setShortcutsOpen((open) => !open)} />
361
+ <ShortcutsDialog open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
362
+ <UnlockPromptProvider>
363
+ <UnlockBridge />
364
+ {/* An impersonating admin acts with the impersonated user's access, so their own trusted role
365
+ mustn't skip the per-mailbox checks. */}
366
+ <ComposeProvider userUid={userUid} trusted={!!trusted && !impersonating}>
367
+ <div className="rr-frame-bg min-h-screen flex flex-col">
368
+ {!hideChrome && customHeader && (
369
+ <FrameBrandingHeader
370
+ parsed={header}
371
+ userMenu={menuInHeader ? renderUserMenu("down") : undefined}
372
+ fallbackMenu={header && !menuInHeader && !menuInFooter ? renderUserMenu("down") : undefined}
373
+ appTitle={activeLabel}
374
+ />
375
+ )}
376
+ {impersonating && !hideChrome && (
377
+ <div className="h-10 shrink-0 bg-warning text-warning-contrast flex items-center justify-center gap-3 text-sm font-medium px-4">
378
+ <span>
379
+ You are viewing as <strong>{userUid}</strong>.
380
+ </span>
381
+ <button
382
+ type="button"
383
+ onClick={handleStopImpersonating}
384
+ disabled={stoppingImpersonation}
385
+ className="underline hover:no-underline disabled:opacity-60"
386
+ >
387
+ {stoppingImpersonation ? "Returning to admin…" : "Return to admin"}
388
+ </button>
389
+ </div>
390
+ )}
391
+ <div className="flex-1 flex min-h-0">
392
+ {!hideChrome && (
393
+ <nav
394
+ aria-label="Apps"
395
+ className={[
396
+ "hidden md:flex w-16 shrink-0 bg-surface border-r border-border flex-col items-center gap-1",
397
+ // Under a custom header the rail starts with the app icons; without one its own icon is flush with the top of the window.
398
+ customHeader ? "py-3" : "pb-3",
399
+ ].join(" ")}
400
+ >
401
+ {!customHeader && (
402
+ <RailIcon src={iconSrc} />
403
+ )}
404
+ {apps.map(({ id, href, label, icon: Icon }) => (
405
+ <a
406
+ key={id}
407
+ href={href}
408
+ aria-label={label}
409
+ aria-current={id === active ? "page" : undefined}
410
+ title={label}
411
+ className={[
412
+ "w-10 h-10 flex items-center justify-center rounded-sm",
413
+ id === active
414
+ ? "bg-primary/10 text-primary-dark"
415
+ : "text-text-muted hover:bg-surface-alt hover:text-text",
416
+ ].join(" ")}
417
+ >
418
+ <Icon size={20} aria-hidden="true" />
419
+ </a>
420
+ ))}
421
+ </nav>
422
+ )}
423
+ {!hideChrome && <BottomTabBar apps={apps} active={active} />}
424
+ <div className="flex-1 flex flex-col min-w-0">
425
+ {!hideChrome && !customHeader && (
426
+ <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">
427
+ <span className="font-display font-bold text-lg uppercase tracking-wide">{activeLabel}</span>
428
+ {renderUserMenu("down")}
429
+ </header>
430
+ )}
431
+ {/* The one pop-up stack for the whole app: right under the header row, so it never covers the account menu. */}
432
+ <NotificationCenter />
433
+ <div
434
+ id="app-content"
435
+ tabIndex={-1}
436
+ aria-busy={busy || undefined}
437
+ className={["flex-1 flex min-h-0 outline-none", hideChrome ? "" : "pb-14 md:pb-0"].join(" ")}
438
+ >
439
+ {children}
440
+ </div>
441
+ </div>
442
+ </div>
443
+ {!hideChrome && <FrameBrandingFooter parsed={footer} userMenu={menuInFooter ? renderUserMenu("up") : undefined} appTitle={activeLabel} />}
444
+ </div>
445
+ </ComposeProvider>
446
+ </UnlockPromptProvider>
447
+ <NotificationHistoryDialog open={historyOpen} onClose={() => setHistoryOpen(false)} />
448
+ </MailConnectionContext.Provider>
449
+ </ShortcutProvider>
450
+ </AppearanceProvider>
451
+ );
452
+ }
453
+
454
+ /**
455
+ * What a page's own shell (`MailShell`, `CalendarShell`, ...) renders around its content. Outside the client-side router it
456
+ * 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
457
+ * page - and stays mounted as the page is replaced - so this is only its children; everything it would have been given comes from
458
+ * the shell instead (the props are the same for every page, and `active` is the route's).
459
+ */
460
+ export default function AppShell(props: PropsWithChildren<AppShellProps>) {
461
+ const inFrame = useInAppFrame();
462
+ return inFrame ? <>{props.children}</> : <AppChrome {...props} />;
463
+ }