@bevel-software/platform-core-frontend 0.37.0 → 0.39.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 (35) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +22 -10
  3. package/src/core/__tests__/AppChrome.test.tsx +27 -10
  4. package/src/core/__tests__/ShellRoutes.test.tsx +43 -2
  5. package/src/core/registry.ts +43 -2
  6. package/src/core/shell-paths.ts +30 -0
  7. package/src/lib/api.ts +7 -1
  8. package/src/modules/auth/__tests__/LoginScreen.test.tsx +9 -0
  9. package/src/modules/auth/__tests__/useAuthState.test.ts +92 -0
  10. package/src/modules/auth/components/LoginScreen.tsx +2 -0
  11. package/src/modules/auth/hooks/useAuthState.ts +4 -1
  12. package/src/modules/auth/index.ts +2 -0
  13. package/src/modules/auth/state/accountStorage.ts +32 -0
  14. package/src/modules/auth/state/tokenAccount.ts +53 -0
  15. package/src/modules/layout/index.ts +1 -1
  16. package/src/modules/settings/components/SettingsLayout.tsx +52 -9
  17. package/src/modules/settings/components/SettingsNav.tsx +24 -3
  18. package/src/modules/settings/components/__tests__/SettingsLayout.test.tsx +266 -5
  19. package/src/modules/settings/index.ts +1 -1
  20. package/src/modules/settings/settings-nav-items.tsx +130 -10
  21. package/src/modules/toolbar/commands/__tests__/actions.test.tsx +20 -5
  22. package/src/modules/toolbar/commands/actions.tsx +1 -0
  23. package/src/modules/toolbar/components/ProfileMenu.tsx +13 -1
  24. package/src/modules/toolbar/components/Toolbar.tsx +3 -2
  25. package/src/modules/toolbar/components/__tests__/ProfileMenu.app-sections.test.tsx +87 -0
  26. package/src/modules/toolbar/components/__tests__/ProfileMenu.test.tsx +1 -0
  27. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +2 -1
  28. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.tools.test.tsx +80 -32
  29. package/src/modules/workspace/components/renderers/__tests__/htmlToolBridge.test.ts +78 -8
  30. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +10 -3
  31. package/src/modules/workspace/components/renderers/__tests__/pageConsentMemory.test.ts +177 -0
  32. package/src/modules/workspace/components/renderers/__tests__/useHtmlToolBridge.test.tsx +249 -23
  33. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +52 -16
  34. package/src/modules/workspace/components/renderers/pageConsentMemory.ts +75 -0
  35. package/src/modules/workspace/components/renderers/useHtmlToolBridge.tsx +46 -11
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.37.0",
3
+ "version": "0.39.0",
4
4
  "description": "Open-source core UI of the Bevel platform (raw TS/TSX source): workspace explorer/viewer, branches & change requests, Library, secrets, tools, access control.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -45,7 +45,7 @@
45
45
  "tailwind-merge": "^3.5.0",
46
46
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
47
47
  "yaml": "^2.9.0",
48
- "@bevel-software/platform-shared": "0.37.0"
48
+ "@bevel-software/platform-shared": "0.39.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@modelcontextprotocol/client": "^2.3.1",
@@ -36,6 +36,7 @@ import { MaintenanceOverlay } from '../modules/layout/components/MaintenanceOver
36
36
  import { AdminProvider } from '../modules/admin/state/admin.context';
37
37
  import { RolesCorruptedBanner } from '../modules/admin/components/RolesCorruptedBanner';
38
38
  import { SettingsLayout } from '../modules/settings/components/SettingsLayout';
39
+ import { registrySettingsPages } from '../modules/settings';
39
40
  import { DeploymentPage } from '../modules/settings/components/DeploymentPage';
40
41
  import { SecretsPage } from '../modules/secrets-vault/components/SecretsPage';
41
42
  import { AccountPage } from '../modules/auth/components/AccountPage';
@@ -53,7 +54,7 @@ import { OpenChangeRequestDialog } from '../modules/pr/components/OpenChangeRequ
53
54
  import { ChangeRequestLink } from '../modules/change-requests/components/ChangeRequestLink';
54
55
  import { useMediaQuery } from '../modules/layout/hooks/useMediaQuery';
55
56
  import { NARROW_QUERY } from '../modules/layout/breakpoints';
56
- import { setSidebarCollapsed } from '../modules/layout/state/sidebar';
57
+ import { setSidebarCollapsed } from '../modules/layout';
57
58
  import {
58
59
  activeAppId,
59
60
  appHostingPath,
@@ -74,6 +75,7 @@ import {
74
75
  } from './registry';
75
76
  import { withCoreModuleContributions } from './core-contributions';
76
77
  import { KnowledgeSurface } from './KnowledgeSurface';
78
+ import { SHELL_PATHS } from './shell-paths';
77
79
  import { isLibraryLocation } from '../modules/library/routes/library-paths';
78
80
  import { EmbedView } from '../modules/embed/components/EmbedView';
79
81
  import { EmbedLinkPage } from '../modules/embed/components/EmbedLinkPage';
@@ -193,8 +195,8 @@ const CORE_BANNERS: BannerDef[] = [
193
195
  * comment at the `<Routes>` block below).
194
196
  */
195
197
  const CORE_TOP_LEVEL_ROUTES: RouteDef[] = [
196
- { path: '/embed', element: <EmbedView /> },
197
- { path: '/embed/link', element: <EmbedLinkPage /> },
198
+ { path: SHELL_PATHS.embed, element: <EmbedView /> },
199
+ { path: SHELL_PATHS.embedLink, element: <EmbedLinkPage /> },
198
200
  ];
199
201
 
200
202
  /**
@@ -324,6 +326,11 @@ export function AppChrome() {
324
326
  () => [...registry.apps].sort((a, b) => (a.order ?? 100) - (b.order ?? 100)),
325
327
  [registry],
326
328
  );
329
+ // The settings pages the registry's rows bring, mounted under the settings layout with core's.
330
+ const settingsPages = useMemo(
331
+ () => registrySettingsPages(registry).map((row) => ({ path: row.path, element: row.page })),
332
+ [registry],
333
+ );
327
334
  // A claimed app (a library item page at its canonical /workspace URL) wins
328
335
  // over the prefix rule — the switcher highlights the surface on screen.
329
336
  const [claimedApp, setClaimedApp] = useState<string | null>(null);
@@ -362,7 +369,7 @@ export function AppChrome() {
362
369
  <div className="flex-1 min-h-0">
363
370
  {/* Switching routes swaps EVERYTHING below the toolbar: an app
364
371
  surface, a standalone settings page, or a redirect. */}
365
- <ShellRoutes apps={apps} />
372
+ <ShellRoutes apps={apps} settingsPages={settingsPages} />
366
373
  </div>
367
374
  </div>
368
375
  </InviteDialogProvider>
@@ -414,7 +421,7 @@ function ConnectToolsRedirect() {
414
421
  return <Navigate to={`${CONNECT_TOOLS_PATH}${search}${hash}`} replace />;
415
422
  }
416
423
 
417
- export function ShellRoutes({ apps }: { apps: AppDef[] }) {
424
+ export function ShellRoutes({ apps, settingsPages = [] }: { apps: AppDef[]; settingsPages?: RouteDef[] }) {
418
425
  return (
419
426
  <Routes>
420
427
  {apps.map((app) => (
@@ -432,7 +439,7 @@ export function ShellRoutes({ apps }: { apps: AppDef[] }) {
432
439
  `/connect` — the address the server hands out — is its permanent
433
440
  redirect, carrying the query (`?oauth=`) and the fragment
434
441
  (`#authorized`, `#error=`) those landings depend on. */}
435
- <Route path="/connect" element={<ConnectToolsRedirect />} />
442
+ <Route path={SHELL_PATHS.connect} element={<ConnectToolsRedirect />} />
436
443
  {/* A PATHLESS layout route: the child paths below stay byte-identical,
437
444
  which is what keeps `/secrets` the exact URL external OAuth redirects
438
445
  land on. Its only job is to keep the settings nav mounted across
@@ -449,8 +456,13 @@ export function ShellRoutes({ apps }: { apps: AppDef[] }) {
449
456
  {/* The Audit log replaced the admin Connection keys overview; links
450
457
  to the old address (bookmarks, the enterprise shell's older rows)
451
458
  land on it. */}
452
- <Route path="/connection-keys" element={<Navigate to="/audit-log" replace />} />
459
+ <Route path={SHELL_PATHS.connectionKeys} element={<Navigate to="/audit-log" replace />} />
453
460
  <Route path="/tools" element={<ToolsExplorerPage />} />
461
+ {/* The app's own settings pages (`AdminMenuItem.page`): under the
462
+ same layout, so they share the nav and are listed in it. */}
463
+ {settingsPages.map((page) => (
464
+ <Route key={page.path} path={page.path} element={page.element} />
465
+ ))}
454
466
  </Route>
455
467
  {/* `/` lands on Knowledge — or on the deep link an SSO sign-in carried
456
468
  through its round-trip (see `RootLanding`).
@@ -470,8 +482,8 @@ export function ShellRoutes({ apps }: { apps: AppDef[] }) {
470
482
 
471
483
  OUTSIDE the settings layout, like `/connect` above: these are landing
472
484
  and redirect targets, not settings destinations. */}
473
- <Route path="/" element={<RootLanding />} />
474
- <Route path="/auth/*" element={<RootLanding />} />
485
+ <Route path={SHELL_PATHS.root} element={<RootLanding />} />
486
+ <Route path={SHELL_PATHS.authReturn} element={<RootLanding />} />
475
487
  {/* The address every change-request link carries (the backend's
476
488
  change-request-link helper: `open_change_request`, the read tools,
477
489
  every summary's `url`). It opens the request itself, in the
@@ -479,7 +491,7 @@ export function ShellRoutes({ apps }: { apps: AppDef[] }) {
479
491
  Before this route existed the catch-all below swallowed the link.
480
492
  OUTSIDE the settings layout and the apps, like the `/connect`
481
493
  redirect: a landing target, not a destination with a nav row. */}
482
- <Route path="/change-requests/:number" element={<ChangeRequestLink />} />
494
+ <Route path={SHELL_PATHS.changeRequest} element={<ChangeRequestLink />} />
483
495
  <Route path="*" element={<Navigate to={KB_ROUTE_PREFIX} replace />} />
484
496
  </Routes>
485
497
  );
@@ -1,14 +1,9 @@
1
- import { fireEvent, render, screen } from '@testing-library/react';
1
+ import { fireEvent, render, screen, within } from '@testing-library/react';
2
2
  import { beforeEach, describe, expect, it, vi } from 'vitest';
3
3
  import { MemoryRouter, useNavigate } from 'react-router-dom';
4
4
  import { AppChrome } from '../CoreAppShell';
5
5
  import { AppRegistryContext, makeRegistry, type AppDef } from '../registry';
6
- import {
7
- setSidebarCollapsed,
8
- setSidebarNarrow,
9
- toggleSidebar,
10
- useSidebar,
11
- } from '../../modules/layout/state/sidebar';
6
+ import { setSidebarCollapsed, toggleSidebar, useSidebar } from '../../modules/layout';
12
7
 
13
8
  vi.mock('../../modules/toolbar/components/Toolbar', () => ({
14
9
  Toolbar: () => null,
@@ -87,9 +82,12 @@ function renderChrome(width: number) {
87
82
 
88
83
  beforeEach(() => {
89
84
  setViewportWidth(1400);
90
- // Module state: clear the breakpoint the previous test settled on so this
91
- // mount reads as a fresh crossing rather than a no-op.
92
- setSidebarNarrow(false);
85
+ // Module state: open the sidebar the previous test may have left collapsed.
86
+ // Its `narrow` flag needs no reset here, because nothing in this file sets
87
+ // it: only a mounted sidebar frame reports the breakpoint to the store, the
88
+ // narrow tests mount stand-in surfaces with no frame (the chrome collapses
89
+ // the sidebar from its own media query), and the one test that mounts a
90
+ // frame does so at a wide width.
93
91
  setSidebarCollapsed(false);
94
92
  });
95
93
 
@@ -123,3 +121,22 @@ describe('AppChrome: narrow navigation', () => {
123
121
  );
124
122
  });
125
123
  });
124
+
125
+ // The registry alone puts an app's settings page on screen: a row with a
126
+ // `path` and a `page`, and nothing handed to the routes by the test.
127
+ describe('AppChrome: a settings page the registry brings', () => {
128
+ it('mounts the page of a registry row at its path, inside the settings nav', () => {
129
+ setViewportWidth(1400);
130
+ const row = { id: 'executors', label: 'Executors', path: '/executors', page: <div data-testid="executors-page" /> };
131
+ render(
132
+ <MemoryRouter initialEntries={['/executors']}>
133
+ <AppRegistryContext.Provider value={makeRegistry({ apps, adminMenuItems: [row] })}>
134
+ <AppChrome />
135
+ </AppRegistryContext.Provider>
136
+ </MemoryRouter>,
137
+ );
138
+ expect(screen.getByTestId('executors-page')).toBeInTheDocument();
139
+ const settingsNav = screen.getByRole('navigation', { name: 'Settings' });
140
+ expect(within(settingsNav).getByRole('link', { name: 'Executors' })).toHaveAttribute('aria-current', 'page');
141
+ });
142
+ });
@@ -1,8 +1,9 @@
1
1
  import { describe, it, expect, vi } from 'vitest';
2
2
  import { render, screen, within } from '@testing-library/react';
3
- import { MemoryRouter, useLocation, useNavigationType } from 'react-router-dom';
3
+ import { MemoryRouter, createRoutesFromChildren, useLocation, useNavigationType, type RouteObject } from 'react-router-dom';
4
4
  import { ShellRoutes } from '../CoreAppShell';
5
- import type { AppDef } from '../registry';
5
+ import { registrySettingsPages } from '../../modules/settings';
6
+ import { AppRegistryContext, makeRegistry, type AdminMenuItem, type AppDef } from '../registry';
6
7
 
7
8
  // The /secrets standalone page fetches on mount — stub its data layer so the
8
9
  // route can render without a network. (The other standalone pages are not
@@ -192,3 +193,43 @@ describe('ShellRoutes — /connect', () => {
192
193
  expect(screen.getByTestId('navigation')).toHaveTextContent('REPLACE');
193
194
  });
194
195
  });
196
+
197
+ // An app's own settings page (`AdminMenuItem.page`) is mounted under the
198
+ // settings layout: at its own address, with the settings nav beside it.
199
+ describe('ShellRoutes with a settings page the registry brings', () => {
200
+ it('renders the page at its path, inside the settings nav, and lists it there', () => {
201
+ const row: AdminMenuItem = { id: 'executors', label: 'Executors', path: '/executors', page: <div data-testid="executors-page" /> };
202
+ render(
203
+ <AppRegistryContext.Provider value={makeRegistry({ adminMenuItems: [row] })}>
204
+ <MemoryRouter initialEntries={['/executors']}>
205
+ <ShellRoutes apps={apps} settingsPages={[{ path: '/executors', element: row.page! }]} />
206
+ </MemoryRouter>
207
+ </AppRegistryContext.Provider>,
208
+ );
209
+ expect(screen.getByTestId('executors-page')).toBeInTheDocument();
210
+ const nav = screen.getByRole('navigation', { name: 'Settings' });
211
+ expect(within(nav).getByRole('link', { name: 'Executors' })).toHaveAttribute('aria-current', 'page');
212
+ expect(within(nav).getByRole('link', { name: 'Secrets' })).toBeInTheDocument();
213
+ });
214
+
215
+ // The rule is read off the shell's own route table, so a route added to
216
+ // `ShellRoutes` that a registry page could still take over fails here.
217
+ it('lets no registry page take an address a route of the shell answers', () => {
218
+ const table = createRoutesFromChildren(ShellRoutes({ apps }).props.children);
219
+ const patterns = (routes: RouteObject[]): string[] =>
220
+ routes.flatMap((route) => [...(route.path ? [route.path] : []), ...patterns(route.children ?? [])]);
221
+ // The catch-all answers what nothing else does: it owns no address.
222
+ const owned = patterns(table).filter((pattern) => pattern !== '*');
223
+ expect(owned).toEqual(expect.arrayContaining(['/workspace/*', '/secrets', '/connect', '/', '/auth/*', '/change-requests/:number']));
224
+
225
+ for (const pattern of owned) {
226
+ // An address the pattern answers: a value for each parameter, a segment for a splat.
227
+ const address = pattern.replace(/:\w+/g, '1').replace(/\*$/, 'x');
228
+ const registry = makeRegistry({
229
+ apps,
230
+ adminMenuItems: [{ id: 'page', label: 'Page', path: address, page: <div /> }],
231
+ });
232
+ expect(registrySettingsPages(registry), `a page at ${address} (${pattern})`).toEqual([]);
233
+ }
234
+ });
235
+ });
@@ -89,12 +89,31 @@ export interface AdminMenuItemHelpers {
89
89
  * Skills & Tools is NOT one of these. It is an `AppDef`, reached from the app
90
90
  * switcher.
91
91
  */
92
+ /**
93
+ * A labelled section of the profile menu an app defines (see
94
+ * {@link AdminMenuItem.section}). Rows naming the same `id` share it; the
95
+ * label and order are the first such row's.
96
+ */
97
+ export interface AdminMenuSection {
98
+ id: string;
99
+ /** The section's heading, such as "Infrastructure only". */
100
+ label: string;
101
+ /** Position among the app's sections; 100 when absent. */
102
+ order?: number;
103
+ }
104
+
92
105
  export interface AdminMenuItem {
93
106
  id: string;
94
107
  label: ReactNode;
95
108
  icon?: ReactNode;
96
- /** 'admin' rows render under the "Admin only" section (admin users only). */
97
- section?: 'default' | 'admin';
109
+ /**
110
+ * 'admin' rows render under the "Admin only" section (admin users only).
111
+ * An {@link AdminMenuSection} puts the row under a section of the app's own,
112
+ * labelled, between the default rows and "Admin only" — for rows meant for
113
+ * the holders of a role the app defines. Who sees each row is still its
114
+ * `isShown`; the section shows while any of its rows does.
115
+ */
116
+ section?: 'default' | 'admin' | AdminMenuSection;
98
117
  /** Merge position among core + registered rows of the same section. */
99
118
  order?: number;
100
119
  /**
@@ -111,6 +130,28 @@ export interface AdminMenuItem {
111
130
  * typecheck for every row the enterprise shell already contributes.
112
131
  */
113
132
  path?: string;
133
+ /**
134
+ * The page this row opens at `path`: a settings page of the app's own.
135
+ *
136
+ * A row with a `path` and a `page` is mounted inside the settings layout
137
+ * beside core's pages, and listed in the settings nav under its section —
138
+ * so an app's settings are reached, linked to and switched between the way
139
+ * core's are, instead of each opening a dialog over whatever is behind it.
140
+ * `path` is one absolute address (`/agents-settings`), written as the
141
+ * browser and the router both read it. A row brings no page when its path
142
+ * is a route pattern (a parameter `:id`, a splat, an optional segment), has
143
+ * a query or a fragment, is relative, or is a spelling either of them would
144
+ * resolve to something else (`/teams/../secrets`, a doubled slash, a
145
+ * backslash, a percent-encoded letter). The page is mounted
146
+ * only at an address nothing else answers: not a settings page of core's,
147
+ * a route the shell answers itself, an app's path or anything under it, a
148
+ * top-level route of the registry, or a path an earlier row named (with or
149
+ * without a page), each as the router matches it (another case, a trailing
150
+ * slash and percent-encoding are the same address). A row that names such
151
+ * an address keeps its place in the dropdown, and its page is neither
152
+ * mounted nor listed in the settings nav.
153
+ */
154
+ page?: ReactElement;
114
155
  onSelect?(helpers: AdminMenuItemHelpers): void;
115
156
  /**
116
157
  * Whether the dropdown offers this row to `user` right now. Asked each time
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The route patterns the shell answers itself, besides the settings pages
3
+ * (which come from their menu rows) and the apps (which come from the
4
+ * registry). One definition for two readers: the shell mounts its routes at
5
+ * these (`CoreAppShell.tsx`), and a registry row's settings page is refused
6
+ * at any address one of them answers (`registrySettingsPages`). So a route of
7
+ * the shell cannot be mounted at one pattern and protected at another.
8
+ *
9
+ * The shell's catch-all is not here: it answers what nothing else does, and
10
+ * owns no address in particular.
11
+ *
12
+ * No imports, on purpose: the shell imports the settings module, and the
13
+ * settings module reads these, so this file sits below both.
14
+ */
15
+ export const SHELL_PATHS = {
16
+ /** The address the server hands out for "Connect your tools": a redirect into Skills & Tools. */
17
+ connect: '/connect',
18
+ /** The old Connection keys address: a redirect to the Audit log. */
19
+ connectionKeys: '/connection-keys',
20
+ /** The landing route. */
21
+ root: '/',
22
+ /** Where a single sign-on round-trip returns. */
23
+ authReturn: '/auth/*',
24
+ /** The address every change-request link carries. */
25
+ changeRequest: '/change-requests/:number',
26
+ /** The embed a chat host frames, outside the app. */
27
+ embed: '/embed',
28
+ /** The account-link page the embed sends an unlinked viewer to. */
29
+ embedLink: '/embed/link',
30
+ } as const;
package/src/lib/api.ts CHANGED
@@ -110,6 +110,12 @@ export interface AuthFetchOptions {
110
110
  * Network failures always signal, whatever this returns.
111
111
  */
112
112
  isApplicationResponse?: (response: Response) => boolean;
113
+ /**
114
+ * The session token to send instead of reading the stored one now: a caller
115
+ * that checked whose token it is sends exactly that token, never one another
116
+ * tab put in its place between the check and the request. `null` sends none.
117
+ */
118
+ token?: string | null;
113
119
  }
114
120
 
115
121
  /**
@@ -123,7 +129,7 @@ export async function authFetch(
123
129
  init?: RequestInit,
124
130
  opts: AuthFetchOptions = {},
125
131
  ): Promise<Response> {
126
- const token = getToken();
132
+ const token = opts.token !== undefined ? opts.token : getToken();
127
133
  const headers = new Headers(init?.headers);
128
134
  if (token) headers.set('Authorization', `Bearer ${token}`);
129
135
 
@@ -99,6 +99,15 @@ describe('LoginScreen', () => {
99
99
  }
100
100
  });
101
101
 
102
+ it("says the provider refused, not 'try again', when the callback reports denied", async () => {
103
+ vi.mocked(fetchLoginProviders).mockResolvedValue({ password: true, sso: [] });
104
+ sessionStorage.setItem('bevel_oauth_error', 'denied');
105
+ renderScreen();
106
+ const alert = screen.getByRole('alert');
107
+ expect(alert).toHaveTextContent('Your sign-in provider did not let you sign in.');
108
+ expect(alert).not.toHaveTextContent(/try again/i);
109
+ });
110
+
102
111
  it("clears an SSO callback's error once shown, so a later visit does not show it again", async () => {
103
112
  vi.mocked(fetchLoginProviders).mockResolvedValue({ password: true, sso: [] });
104
113
  sessionStorage.setItem('bevel_oauth_error', 'not_invited');
@@ -0,0 +1,92 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { act, renderHook, waitFor } from '@testing-library/react';
3
+ import { accountKeyPrefix, useAuthState } from '..';
4
+ import { getToken, setToken } from '../../../lib/api';
5
+
6
+ /**
7
+ * Signing out clears what the account kept in this browser, through the real
8
+ * hook and `localStorage`; only the server's answer about the session is stubbed.
9
+ */
10
+ const A_ENTRY = `${accountKeyPrefix('user-a')}htmlPage.allowedWrite.digest`;
11
+ const B_ENTRY = `${accountKeyPrefix('user-b')}htmlPage.allowedWrite.digest`;
12
+
13
+ /** The session the server answers: `user-a`, or an expired token. */
14
+ function stubSession(status = 200) {
15
+ vi.stubGlobal(
16
+ 'fetch',
17
+ vi.fn(async () =>
18
+ status === 200
19
+ ? new Response(JSON.stringify({ id: 'user-a', email: 'a@example.com', name: 'A' }), { status: 200, headers: { 'content-type': 'application/json' } })
20
+ : new Response('{}', { status }),
21
+ ),
22
+ );
23
+ }
24
+
25
+ async function signedIn() {
26
+ setToken('token-a');
27
+ stubSession();
28
+ const { result } = renderHook(() => useAuthState());
29
+ await waitFor(() => expect(result.current.user?.id).toBe('user-a'));
30
+ return result;
31
+ }
32
+
33
+ describe('useAuthState signing out', () => {
34
+ beforeEach(() => {
35
+ window.localStorage.clear();
36
+ window.localStorage.setItem(A_ENTRY, '1');
37
+ window.localStorage.setItem(B_ENTRY, '2');
38
+ window.localStorage.setItem('bevel.htmlPage.height', '300');
39
+ });
40
+ afterEach(() => {
41
+ vi.restoreAllMocks();
42
+ vi.unstubAllGlobals();
43
+ });
44
+
45
+ it("clears the signed-out account's entries and leaves another account's", async () => {
46
+ const auth = await signedIn();
47
+ expect(window.localStorage.getItem(A_ENTRY)).toBe('1');
48
+
49
+ act(() => auth.current.logout());
50
+
51
+ expect(auth.current.user).toBeNull();
52
+ expect(getToken()).toBeNull();
53
+ expect(window.localStorage.getItem(A_ENTRY)).toBeNull();
54
+ expect(window.localStorage.getItem(B_ENTRY)).toBe('2');
55
+ expect(window.localStorage.getItem('bevel.htmlPage.height')).toBe('300');
56
+ });
57
+
58
+ it("never reaches another account whose id starts with the signed-out one's, whatever the id holds", async () => {
59
+ const others = ['user-a.b', 'user-a/b', 'user-a%2Fb', 'user-a b', 'user-ab', 'user-a@example.com'];
60
+ for (const other of others) window.localStorage.setItem(`${accountKeyPrefix(other)}entry`, '1');
61
+ const auth = await signedIn();
62
+
63
+ act(() => auth.current.logout());
64
+
65
+ expect(window.localStorage.getItem(A_ENTRY)).toBeNull();
66
+ for (const other of others) expect(window.localStorage.getItem(`${accountKeyPrefix(other)}entry`)).toBe('1');
67
+ expect(new Set(others.map(accountKeyPrefix)).size).toBe(others.length);
68
+ });
69
+
70
+ it('still signs out when the storage cannot be listed', async () => {
71
+ const auth = await signedIn();
72
+ vi.spyOn(Storage.prototype, 'key').mockImplementation(() => {
73
+ throw new DOMException('The operation is insecure.', 'SecurityError');
74
+ });
75
+
76
+ act(() => auth.current.logout());
77
+
78
+ expect(auth.current.user).toBeNull();
79
+ expect(getToken()).toBeNull();
80
+ });
81
+
82
+ it('keeps the entries when a session ends without signing out: they are still only that account\'s', async () => {
83
+ setToken('expired');
84
+ stubSession(401);
85
+ const { result } = renderHook(() => useAuthState());
86
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
87
+
88
+ expect(result.current.user).toBeNull();
89
+ expect(window.localStorage.getItem(A_ENTRY)).toBe('1');
90
+ expect(window.localStorage.getItem(B_ENTRY)).toBe('2');
91
+ });
92
+ });
@@ -13,6 +13,8 @@ const OAUTH_ERROR_MESSAGES: Record<string, string> = {
13
13
  state: 'Sign-in could not be verified. Please try again.',
14
14
  auth: 'Sign-in failed. Please try again.',
15
15
  start: 'Could not start sign-in. Please try again.',
16
+ // The provider, or the person at its consent screen, refused (OAuth access_denied).
17
+ denied: 'Your sign-in provider did not let you sign in. Check your account with the provider, or ask the admin of this workspace.',
16
18
  not_configured: 'Single sign-on is not configured on this deployment.',
17
19
  admission: 'This workspace has no seat available for your account. Ask its admin.',
18
20
  // On file, switched off until an admin switches the account on.
@@ -3,6 +3,7 @@ import type { AuthUser } from '@bevel-software/platform-shared';
3
3
  import type { AuthContextValue } from '../state/auth.context';
4
4
  import { loginWithPassword, fetchCurrentUser } from '../services/auth.api';
5
5
  import { getToken, setToken, clearToken } from '../../../lib/api';
6
+ import { clearAccountStorage } from '../state/accountStorage';
6
7
  import { consumeSsoCallback, OAUTH_ERROR_KEY } from '../services/sso';
7
8
 
8
9
  export function useAuthState(): AuthContextValue {
@@ -44,10 +45,12 @@ export function useAuthState(): AuthContextValue {
44
45
  }, []);
45
46
 
46
47
  const logout = useCallback(() => {
48
+ // What the account kept in this browser leaves with it.
49
+ if (user) clearAccountStorage(user.id);
47
50
  clearToken();
48
51
  setTokenState(null);
49
52
  setUser(null);
50
- }, []);
53
+ }, [user]);
51
54
 
52
55
  return useMemo(() => ({
53
56
  user,
@@ -9,4 +9,6 @@ export type { AccountReferences, AccountSummary } from './services/account.api';
9
9
  export { takePostLoginRedirect } from './services/sso';
10
10
  export type { LoginProviders } from './services/sso';
11
11
  export { AuthContext, useAuth, type AuthContextValue } from './state/auth.context';
12
+ export { accountKeyPrefix } from './state/accountStorage';
13
+ export { AccountChangedError, accountFetch } from './state/tokenAccount';
12
14
  export { useSignInMethods } from './state/use-sign-in-methods';
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What one signed-in account keeps in this browser's `localStorage`: entries
3
+ * under a prefix that names the account, which signing out clears as one.
4
+ *
5
+ * The account id is URI-encoded and closed with a `/`, which encoding never
6
+ * leaves in an id, so no account's prefix is the start of another's, whatever
7
+ * its id holds.
8
+ */
9
+ const ACCOUNT_KEY_ROOT = 'bevel.account/';
10
+
11
+ /** The prefix of every entry this account keeps. May throw on an id that cannot be encoded: callers treat it as storage that will not store. */
12
+ export function accountKeyPrefix(accountId: string): string {
13
+ return `${ACCOUNT_KEY_ROOT}${encodeURIComponent(accountId)}/`;
14
+ }
15
+
16
+ /**
17
+ * Remove every entry this account keeps, and no other's. Never throws: signing
18
+ * out must finish whatever the browser's storage does, and a storage that
19
+ * cannot be touched is one nothing can be read back from either.
20
+ */
21
+ export function clearAccountStorage(accountId: string): void {
22
+ try {
23
+ const storage = window.localStorage;
24
+ const prefix = accountKeyPrefix(accountId);
25
+ const keys = Array.from({ length: storage.length }, (_, i) => storage.key(i));
26
+ for (const key of keys) {
27
+ if (key?.startsWith(prefix)) storage.removeItem(key);
28
+ }
29
+ } catch {
30
+ // Nothing more can be done here; the entries still answer to this account alone.
31
+ }
32
+ }
@@ -0,0 +1,53 @@
1
+ import { authFetch, getToken } from '../../../lib/api';
2
+
3
+ /**
4
+ * The account a session token belongs to: its `userId` claim, or null when
5
+ * there is no token or it cannot be read. The claim is read, not verified:
6
+ * the server verifies the token on every request, and this only asks whose it
7
+ * is. A token renewed for the same account (a password change) keeps its
8
+ * account.
9
+ */
10
+ function accountOf(token: string | null): string | null {
11
+ try {
12
+ const payload = token?.split('.')[1];
13
+ if (!payload) return null;
14
+ const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
15
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
16
+ const bytes = Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
17
+ const claims = JSON.parse(new TextDecoder().decode(bytes)) as { userId?: unknown };
18
+ return typeof claims.userId === 'string' && claims.userId ? claims.userId : null;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ /** What `accountFetch` throws, sending nothing, when the session is not the expected account's. */
25
+ export class AccountChangedError extends Error {
26
+ constructor() {
27
+ super('You signed in as another account in another tab. Reload this page to use its tools as that account.');
28
+ this.name = 'AccountChangedError';
29
+ }
30
+ }
31
+
32
+ /**
33
+ * A fetch that sends only as `accountId`. The stored session token is shared
34
+ * by every tab: a sign-in in another tab replaces it, while this tab's auth
35
+ * state still names the account it signed in as. Something decided for that
36
+ * account (a page's remembered Allow) must not reach the server with another
37
+ * account's token. Each request reads the token ONCE, throws
38
+ * `AccountChangedError` without sending anything unless it is `accountId`'s
39
+ * (no token, or one that cannot be read, included), and sends exactly that
40
+ * token, so a token swapped in after the check is never the one sent.
41
+ */
42
+ export function accountFetch(accountId: string): (input: string, init?: RequestInit) => Promise<Response> {
43
+ return async (input, init) => {
44
+ let token: string | null;
45
+ try {
46
+ token = getToken();
47
+ } catch {
48
+ token = null;
49
+ }
50
+ if (accountOf(token) !== accountId) throw new AccountChangedError();
51
+ return authFetch(input, init, { token });
52
+ };
53
+ }
@@ -6,4 +6,4 @@
6
6
  export { SETUP_COLUMN_HIDDEN_QUERY, TOOLBAR_STACK_QUERY } from './breakpoints';
7
7
  export { useMediaQuery } from './hooks/useMediaQuery';
8
8
  export { LayoutContext, useLayout } from './state/layout.context';
9
- export { toggleSidebar, useSidebar } from './state/sidebar';
9
+ export { setSidebarCollapsed, toggleSidebar, useSidebar } from './state/sidebar';