@shellui/core 0.6.2 → 0.7.0-alpha.10

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 (85) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +147 -70
  3. package/src/app.tsx +2 -0
  4. package/src/components/ContentView.tsx +21 -30
  5. package/src/components/iframeUrlSafety.spec.ts +67 -0
  6. package/src/components/iframeUrlSafety.ts +50 -0
  7. package/src/components/ui/sidebar.tsx +11 -5
  8. package/src/features/admin/AdminView.tsx +9 -6
  9. package/src/features/auth/AuthProvider.tsx +49 -5
  10. package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
  11. package/src/features/auth/appBackend/appBackendSessions.spec.ts +329 -0
  12. package/src/features/auth/appBackend/appBackendSessions.ts +443 -0
  13. package/src/features/auth/appBackend/childFrames.spec.ts +328 -0
  14. package/src/features/auth/appBackend/childFrames.ts +180 -0
  15. package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
  16. package/src/features/auth/appBackend/frameAuth.ts +204 -0
  17. package/src/features/auth/appBackend/identity.spec.ts +201 -0
  18. package/src/features/auth/appBackend/identity.ts +173 -0
  19. package/src/features/auth/appBackend/silentSignIn.spec.ts +225 -0
  20. package/src/features/auth/appBackend/silentSignIn.ts +254 -0
  21. package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
  22. package/src/features/auth/appBackend/tokenExchange.ts +76 -0
  23. package/src/features/auth/backends/shellui.spec.ts +51 -19
  24. package/src/features/auth/backends/shellui.ts +20 -5
  25. package/src/features/auth/backends/types.ts +7 -2
  26. package/src/features/auth/components/LoginView.tsx +40 -18
  27. package/src/features/auth/components/OAuthCallbackView.tsx +33 -4
  28. package/src/features/auth/utils/authRequestError.ts +3 -0
  29. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
  30. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
  31. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +29 -0
  32. package/src/features/auth/utils/canRestoreStoredSession.ts +12 -0
  33. package/src/features/auth/utils/index.ts +16 -1
  34. package/src/features/auth/utils/loginCancelTarget.spec.ts +73 -0
  35. package/src/features/auth/utils/loginCancelTarget.ts +45 -0
  36. package/src/features/auth/utils/loginPanelFrame.spec.ts +24 -0
  37. package/src/features/auth/utils/loginPanelFrame.ts +14 -0
  38. package/src/features/auth/utils/resolveSdkLoginRedirectPath.spec.ts +41 -0
  39. package/src/features/auth/utils/resolveSdkLoginRedirectPath.ts +31 -0
  40. package/src/features/auth/utils/webPkce.spec.ts +119 -0
  41. package/src/features/auth/utils/webPkce.ts +169 -0
  42. package/src/features/chromeActions/computeActionInsets.ts +7 -4
  43. package/src/features/config/types.ts +70 -3
  44. package/src/features/layouts/appbar/AppBarLayout.tsx +63 -30
  45. package/src/features/layouts/chrome/CollapsedDesktopTitlebar.tsx +12 -23
  46. package/src/features/layouts/chrome/ContentDragOverlay.tsx +5 -6
  47. package/src/features/layouts/chrome/DesktopChrome.tsx +37 -0
  48. package/src/features/layouts/chrome/DesktopHistoryButtons.tsx +15 -4
  49. package/src/features/layouts/chrome/MacStrip.tsx +33 -0
  50. package/src/features/layouts/chrome/constants.ts +33 -8
  51. package/src/features/layouts/chrome/index.ts +8 -0
  52. package/src/features/layouts/chrome/stripDragMap.ts +35 -0
  53. package/src/features/layouts/chrome/stripNoDrag.spec.tsx +103 -0
  54. package/src/features/layouts/chrome/useScrollHideChrome.ts +3 -8
  55. package/src/features/layouts/filterNavigationForAuthState.spec.ts +5 -3
  56. package/src/features/layouts/floating/FloatingBottomDock.tsx +199 -20
  57. package/src/features/layouts/floating/FloatingLayout.tsx +13 -8
  58. package/src/features/layouts/floating/FloatingSidebar.tsx +144 -70
  59. package/src/features/layouts/floating/computeFloatingInsets.ts +22 -4
  60. package/src/features/layouts/floating/useFloatingChrome.ts +3 -1
  61. package/src/features/layouts/floating/useSoftKeyboard.spec.ts +39 -0
  62. package/src/features/layouts/floating/useSoftKeyboard.ts +82 -0
  63. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +38 -10
  64. package/src/features/layouts/sidebar/NavigationContent.tsx +14 -6
  65. package/src/features/layouts/sidebar/SidebarIcons.tsx +3 -9
  66. package/src/features/layouts/sidebar/SidebarInner.tsx +50 -39
  67. package/src/features/layouts/sidebar/SidebarLayout.tsx +8 -11
  68. package/src/features/layouts/utils.ts +4 -3
  69. package/src/features/layouts/windows/DesktopDots.tsx +76 -0
  70. package/src/features/layouts/windows/WindowsLayout.tsx +184 -125
  71. package/src/features/layouts/windows/deskDots.spec.ts +52 -0
  72. package/src/features/layouts/windows/deskDots.ts +314 -0
  73. package/src/features/settings/SettingsProvider.tsx +198 -29
  74. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +379 -4
  75. package/src/features/settings/utils/buildSettingsForPropagation.ts +65 -39
  76. package/src/features/theme/applyTheme.ts +8 -0
  77. package/src/features/theme/navContrast.spec.ts +49 -0
  78. package/src/features/theme/navContrast.ts +108 -0
  79. package/src/features/transfers/transferQueue.spec.ts +6 -2
  80. package/src/i18n/translations/en/common.json +27 -0
  81. package/src/i18n/translations/fr/common.json +27 -0
  82. package/src/index.css +935 -46
  83. package/src/index.ts +2 -0
  84. package/src/routes/hooks/useNavigationItems.ts +14 -3
  85. package/src/routes/hooks/withShellSearch.spec.ts +13 -0
@@ -10,8 +10,8 @@ import { useConfig } from '../config/useConfig';
10
10
  import type { NavigationItem } from '../config/types';
11
11
  import { AppLayout } from '../layouts/AppLayout';
12
12
  import {
13
- MAC_TRAFFIC_LIGHTS_GAP_PX,
14
- MAC_TRAFFIC_LIGHTS_WIDTH_PX,
13
+ DESKTOP_TITLEBAR_HEIGHT_PX,
14
+ MAC_LIGHTS_SAFE_PX,
15
15
  isShellUiRootWindow,
16
16
  SafeAreaTopbarOffset,
17
17
  SafeAreaTopbarStrip,
@@ -74,9 +74,9 @@ export const AdminView = () => {
74
74
 
75
75
  const showSafeAreaTopbar = isShellUiRootWindow();
76
76
  const trafficLights = useMacTrafficLights();
77
- const chromeInset = trafficLights
78
- ? MAC_TRAFFIC_LIGHTS_WIDTH_PX + MAC_TRAFFIC_LIGHTS_GAP_PX
79
- : undefined;
77
+ const chromeInset = trafficLights ? MAC_LIGHTS_SAFE_PX : undefined;
78
+ // macOS desktop: the header is the 32px strip, controls centre on the lights line.
79
+ const macStrip = trafficLights && !isMobile;
80
80
  const headerStyle = {
81
81
  paddingLeft: chromeInset ?? 'max(0.5rem, var(--shellui-safe-area-left))',
82
82
  paddingRight: 'max(0.75rem, var(--shellui-safe-area-right))',
@@ -85,7 +85,7 @@ export const AdminView = () => {
85
85
  paddingTop: 'var(--shellui-safe-area-top)',
86
86
  height: `calc(${ADMIN_HEADER_HEIGHT_PX}px + var(--shellui-safe-area-top))`,
87
87
  }
88
- : { height: ADMIN_HEADER_HEIGHT_PX }),
88
+ : { height: macStrip ? DESKTOP_TITLEBAR_HEIGHT_PX : ADMIN_HEADER_HEIGHT_PX }),
89
89
  } as const;
90
90
 
91
91
  return (
@@ -102,11 +102,13 @@ export const AdminView = () => {
102
102
  {...(trafficLights
103
103
  ? { 'data-shellui-drag-region': '', 'data-tauri-drag-region': '' }
104
104
  : {})}
105
+ {...(macStrip ? { 'data-shellui-mac-strip': '' } : {})}
105
106
  >
106
107
  <Button
107
108
  type="button"
108
109
  variant="ghost"
109
110
  size="sm"
111
+ className={macStrip ? 'h-6 px-2 text-[13px]' : undefined}
110
112
  data-shellui-no-drag=""
111
113
  onClick={() => navigate('/')}
112
114
  >
@@ -127,6 +129,7 @@ export const AdminView = () => {
127
129
  </Button>
128
130
  <div
129
131
  data-shellui-no-drag=""
132
+ data-shellui-strip-end=""
130
133
  className="flex items-center gap-2"
131
134
  >
132
135
  <LoginButton
@@ -11,6 +11,8 @@ import urls from '../../constants/urls';
11
11
  import { useConfig } from '../config/useConfig';
12
12
  import { useIsTauriRuntime } from '../layouts/chrome/runtime';
13
13
  import { isShellSettingsFrameMessage } from '../security/trustedFrames';
14
+ import { endAppBackendSessions } from './appBackend/appBackendSessions';
15
+ import { isSilentAuthCallbackFrame } from './appBackend/silentSignIn';
14
16
  import { createAuthBackend } from './backends';
15
17
  import { AuthContext, type AuthContextValue, type OAuthCallbackResult } from './hooks/useAuth';
16
18
  import type { AuthEvent, AuthSession, AuthUser, UserPreferences } from './types';
@@ -25,6 +27,7 @@ import {
25
27
  hasStoredAuthSession,
26
28
  inferAccessPendingErrorCode,
27
29
  isBffAuthEnabledFromConfig,
30
+ canRestoreStoredSession,
28
31
  isSessionExpired,
29
32
  isTokenAutoRefreshDisabled,
30
33
  logoutBffAuthSession,
@@ -36,6 +39,7 @@ import {
36
39
  type InFlightSlot,
37
40
  } from './utils';
38
41
  import { buildAuthUrlWithNext } from './utils/buildAuthUrlWithNext';
42
+ import { resolveSdkLoginRedirectPath } from './utils/resolveSdkLoginRedirectPath';
39
43
  import {
40
44
  beginDesktopOAuth,
41
45
  clearDesktopPkce,
@@ -196,6 +200,16 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
196
200
  return;
197
201
  }
198
202
 
203
+ // The hidden frame that finishes sign-in for another identity server must
204
+ // not read or write the shell session (sessionStorage is shared).
205
+ if (isSilentAuthCallbackFrame()) {
206
+ if (!cancelled) {
207
+ setSession(null);
208
+ setIsLoading(false);
209
+ }
210
+ return;
211
+ }
212
+
199
213
  const isIframe = window.parent !== window;
200
214
  const now = Math.floor(Date.now() / 1000);
201
215
  const sessionFromHash = backend.readSessionFromCallback(window.location.hash, now);
@@ -240,6 +254,17 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
240
254
  return;
241
255
  }
242
256
 
257
+ // A new tab has the shared profile but not the tab-scoped refresh token. Treat it as
258
+ // signed out instead of a signed-in session with no token. Keep storage: another tab
259
+ // may still own this session.
260
+ if (!canRestoreStoredSession(stored, bffAuthEnabled)) {
261
+ if (!cancelled) {
262
+ setSession(null);
263
+ setIsLoading(false);
264
+ }
265
+ return;
266
+ }
267
+
243
268
  const applyRestoredSession = async (source: AuthSession) => {
244
269
  try {
245
270
  const restored = await shareInFlight(restoreRefreshSlot, () =>
@@ -391,7 +416,12 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
391
416
  });
392
417
  return true;
393
418
  }
394
- backend.startOAuth(provider, redirectPath, oauthClientId);
419
+ void Promise.resolve(backend.startOAuth(provider, redirectPath, oauthClientId)).catch(
420
+ (err) => {
421
+ setError(err instanceof Error ? err.message : 'Unable to start OAuth login.');
422
+ setErrorCode(err instanceof AuthRequestError ? err.code : null);
423
+ },
424
+ );
395
425
  return true;
396
426
  } catch (err) {
397
427
  setError(err instanceof Error ? err.message : 'Unable to start OAuth login.');
@@ -624,6 +654,12 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
624
654
  // Even if API sign-out fails, still clear local session.
625
655
  }
626
656
 
657
+ try {
658
+ await endAppBackendSessions();
659
+ } catch {
660
+ // App-server sign-out is best effort. The shell session still clears.
661
+ }
662
+
627
663
  clearStoredAuthSession();
628
664
  setSession(null);
629
665
  setAuthEvent(null);
@@ -826,8 +862,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
826
862
  });
827
863
  } catch (err) {
828
864
  reply('error');
829
- const errorCode = getAuthRequestErrorCode(err);
830
- if (errorCode === 'last_company_owner') {
865
+ const deleteErrorCode = getAuthRequestErrorCode(err);
866
+ if (deleteErrorCode === 'last_company_owner') {
831
867
  const companies =
832
868
  err instanceof AuthRequestError && Array.isArray(err.details.companies)
833
869
  ? (err.details.companies as Array<{ name?: unknown }>)
@@ -845,7 +881,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
845
881
  });
846
882
  return;
847
883
  }
848
- if (errorCode === 'recent_login_required') {
884
+ if (deleteErrorCode === 'recent_login_required') {
849
885
  shellui.dialog({
850
886
  title: t('userAccount.deleteAccount.reauthTitle'),
851
887
  description: t('userAccount.deleteAccount.reauthDescription'),
@@ -907,7 +943,15 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
907
943
  return;
908
944
  }
909
945
 
910
- startOAuth(provider, payload.redirectPath || urls.login, payload.oauthClientId);
946
+ const currentPath =
947
+ typeof window !== 'undefined'
948
+ ? `${window.location.pathname}${window.location.search}`
949
+ : '/';
950
+ startOAuth(
951
+ provider,
952
+ resolveSdkLoginRedirectPath(payload.redirectPath, currentPath),
953
+ payload.oauthClientId,
954
+ );
911
955
  });
912
956
 
913
957
  return () => cleanup();
@@ -0,0 +1,58 @@
1
+ import { useEffect, useMemo, useRef } from 'react';
2
+ import { useConfig } from '../../config/useConfig';
3
+ import { useAuth } from '../hooks/useAuth';
4
+ import {
5
+ endAppBackendSessions,
6
+ ensureConfiguredAppBackends,
7
+ resetAppBackendSilentAttempts,
8
+ } from './appBackendSessions';
9
+ import { listDistinctAppBackends } from './identity';
10
+ import { isSilentAuthCallbackFrame } from './silentSignIn';
11
+
12
+ /**
13
+ * While the shell has a session, sign in to each embedded app's identity server.
14
+ * The shell session itself is unchanged.
15
+ */
16
+ export function AppBackendSessionHost() {
17
+ const { config } = useConfig();
18
+ const { session, isLoading } = useAuth();
19
+ const signedInUserRef = useRef<string | null>(null);
20
+ const configRef = useRef(config);
21
+ configRef.current = config;
22
+
23
+ const identityKey = useMemo(
24
+ () =>
25
+ listDistinctAppBackends(config)
26
+ .map((identity) => `${identity.key}|${identity.provider ?? ''}`)
27
+ .join('\n'),
28
+ [config],
29
+ );
30
+
31
+ const signedIn = Boolean(session?.accessToken);
32
+ const userId = session?.userId ?? null;
33
+
34
+ useEffect(() => {
35
+ if (typeof window === 'undefined' || window.parent !== window) return;
36
+ if (isSilentAuthCallbackFrame()) return;
37
+ if (isLoading) return;
38
+ if (!signedIn) {
39
+ void endAppBackendSessions();
40
+ signedInUserRef.current = null;
41
+ return;
42
+ }
43
+ if (signedInUserRef.current !== userId) {
44
+ signedInUserRef.current = userId;
45
+ resetAppBackendSilentAttempts();
46
+ }
47
+ let cancelled = false;
48
+ void (async () => {
49
+ if (cancelled) return;
50
+ await ensureConfiguredAppBackends(configRef.current, { allowSilent: true });
51
+ })();
52
+ return () => {
53
+ cancelled = true;
54
+ };
55
+ }, [identityKey, isLoading, signedIn, userId]);
56
+
57
+ return null;
58
+ }
@@ -0,0 +1,329 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ vi.mock('../../config/useConfig', () => ({ useConfig: () => ({ config: {} }) }));
4
+ import { createAuthBackend } from '../backends';
5
+ import type { AuthSession } from '../types';
6
+ import { AUTH_REFRESH_STORAGE_KEY } from '../utils/authStorageKeys';
7
+ import {
8
+ APP_BACKEND_REFRESH_PREFIX,
9
+ endAppBackendSessions,
10
+ ensureAppBackendSession,
11
+ getAppBackendSession,
12
+ setAppBackendFactory,
13
+ setAppBackendSignIn,
14
+ setAppBackendTokenExchange,
15
+ resetAppBackendTokenExchange,
16
+ } from './appBackendSessions';
17
+ import { resolveAppBackendConfig } from './identity';
18
+ import { runSilentPkceSignIn } from './silentSignIn';
19
+
20
+ const SHELL_TOKEN = 'shell-access-token';
21
+ const FOREIGN_TOKEN = 'foreign-access-token';
22
+ const FOREIGN_REFRESH = 'foreign-refresh-token';
23
+
24
+ function session(accessToken: string, refreshToken = FOREIGN_REFRESH): AuthSession {
25
+ return {
26
+ accessToken,
27
+ refreshToken,
28
+ tokenType: 'bearer',
29
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
30
+ provider: 'google',
31
+ userId: 'user-foreign',
32
+ userEmail: 'foreign@example.com',
33
+ userName: 'Foreign',
34
+ userAvatarUrl: null,
35
+ userIsStaff: false,
36
+ userIsCompanyOwner: false,
37
+ userGroups: ['directory'],
38
+ };
39
+ }
40
+
41
+ function identityFor(url: string, companyId?: number) {
42
+ const identity = resolveAppBackendConfig(
43
+ { url, companyId, provider: 'google', type: 'shellui' },
44
+ { backend: { type: 'shellui', url: 'https://id.example.com', companyId: 1 } },
45
+ );
46
+ if (!identity) throw new Error('expected identity');
47
+ return identity;
48
+ }
49
+
50
+ function installStorage(): Storage {
51
+ const map = new Map<string, string>();
52
+ const storage = {
53
+ get length() {
54
+ return map.size;
55
+ },
56
+ clear: () => map.clear(),
57
+ getItem: (key: string) => map.get(key) ?? null,
58
+ key: (index: number) => [...map.keys()][index] ?? null,
59
+ removeItem: (key: string) => {
60
+ map.delete(key);
61
+ },
62
+ setItem: (key: string, value: string) => {
63
+ map.set(key, String(value));
64
+ },
65
+ } as Storage;
66
+ vi.stubGlobal('sessionStorage', storage);
67
+ return storage;
68
+ }
69
+
70
+ describe('app backend sessions', () => {
71
+ const refreshAuthSession = vi.fn();
72
+ const exchangeOAuthSessionCode = vi.fn();
73
+ const logout = vi.fn(async () => {});
74
+ const factory = vi.fn(() => ({ refreshAuthSession, exchangeOAuthSessionCode, logout }));
75
+ const signIn = vi.fn();
76
+
77
+ beforeEach(() => {
78
+ installStorage();
79
+ refreshAuthSession.mockReset();
80
+ exchangeOAuthSessionCode.mockReset();
81
+ logout.mockClear();
82
+ factory.mockClear();
83
+ signIn.mockReset();
84
+ signIn.mockResolvedValue({ ok: false, reason: 'not-configured' });
85
+ setAppBackendFactory(factory);
86
+ setAppBackendSignIn(signIn);
87
+ });
88
+
89
+ afterEach(async () => {
90
+ await endAppBackendSessions();
91
+ setAppBackendFactory(createAuthBackend);
92
+ setAppBackendSignIn(runSilentPkceSignIn);
93
+ vi.unstubAllGlobals();
94
+ });
95
+
96
+ it('stores only the refresh token and keeps two servers apart', async () => {
97
+ const directory = identityFor('https://id.directory.example', 4);
98
+ const billing = identityFor('https://id.billing.example', 8);
99
+ signIn.mockImplementation(async (input: { backendUrl: string }) => ({
100
+ ok: true,
101
+ authCode: `code-${input.backendUrl}`,
102
+ redirectTo: 'https://shell.example/login/callback?shellui_silent=1',
103
+ codeVerifier: 'verifier-value-verifier-value-verifier-value',
104
+ }));
105
+ exchangeOAuthSessionCode.mockImplementation(async ({ authCode }: { authCode: string }) =>
106
+ session(
107
+ authCode === 'code-https://id.directory.example' ? FOREIGN_TOKEN : 'billing-token',
108
+ `refresh-${authCode}`,
109
+ ),
110
+ );
111
+
112
+ const directoryToken = await ensureAppBackendSession(directory, { allowSilent: true });
113
+ const billingToken = await ensureAppBackendSession(billing, { allowSilent: true });
114
+
115
+ expect(directoryToken).toBe(FOREIGN_TOKEN);
116
+ expect(billingToken).toBe('billing-token');
117
+ expect(getAppBackendSession(directory.key)?.accessToken).toBe(FOREIGN_TOKEN);
118
+ expect(getAppBackendSession(billing.key)?.accessToken).toBe('billing-token');
119
+ expect(factory).toHaveBeenCalledWith(
120
+ expect.objectContaining({ url: 'https://id.directory.example' }),
121
+ );
122
+ expect(factory).toHaveBeenCalledWith(
123
+ expect.objectContaining({ url: 'https://id.billing.example' }),
124
+ );
125
+ expect(JSON.stringify(factory.mock.calls)).not.toContain(SHELL_TOKEN);
126
+
127
+ const stored = JSON.stringify(
128
+ Object.fromEntries(
129
+ [...Array(sessionStorage.length).keys()].map((index) => {
130
+ const key = sessionStorage.key(index) ?? '';
131
+ return [key, sessionStorage.getItem(key)];
132
+ }),
133
+ ),
134
+ );
135
+ expect(stored).not.toContain(FOREIGN_TOKEN);
136
+ expect(stored).not.toContain('billing-token');
137
+ expect(stored).toContain('refresh-code-https://id.directory.example');
138
+ expect(signIn.mock.calls[0][0]).not.toHaveProperty('accessToken');
139
+ });
140
+
141
+ it('refreshes a stored session without silent sign-in', async () => {
142
+ const directory = identityFor('https://id.directory.example', 4);
143
+ sessionStorage.setItem(
144
+ `${APP_BACKEND_REFRESH_PREFIX}${encodeURIComponent(directory.key)}`,
145
+ 'stored-refresh',
146
+ );
147
+ refreshAuthSession.mockResolvedValue(session(FOREIGN_TOKEN, 'rotated-refresh'));
148
+
149
+ const token = await ensureAppBackendSession(directory, { allowSilent: true });
150
+
151
+ expect(token).toBe(FOREIGN_TOKEN);
152
+ expect(signIn).not.toHaveBeenCalled();
153
+ expect(exchangeOAuthSessionCode).not.toHaveBeenCalled();
154
+ expect(
155
+ sessionStorage.getItem(`${APP_BACKEND_REFRESH_PREFIX}${encodeURIComponent(directory.key)}`),
156
+ ).toBe('rotated-refresh');
157
+ });
158
+
159
+ it('does not silent-sign-in a supabase override', async () => {
160
+ const identity = resolveAppBackendConfig(
161
+ {
162
+ type: 'supabase',
163
+ url: 'https://abc.supabase.co',
164
+ publishableKey: 'pk',
165
+ provider: 'google',
166
+ },
167
+ { backend: { type: 'shellui', url: 'https://id.example.com' } },
168
+ );
169
+ if (!identity) throw new Error('expected identity');
170
+ const token = await ensureAppBackendSession(identity, { allowSilent: true });
171
+ expect(token).toBeNull();
172
+ expect(signIn).not.toHaveBeenCalled();
173
+ });
174
+
175
+ it('clears app refresh tokens and leaves the shell refresh token', async () => {
176
+ const directory = identityFor('https://id.directory.example', 4);
177
+ signIn.mockResolvedValue({
178
+ ok: true,
179
+ authCode: 'code-1',
180
+ redirectTo: 'https://shell.example/login/callback?shellui_silent=1',
181
+ codeVerifier: 'verifier-value-verifier-value-verifier-value',
182
+ });
183
+ exchangeOAuthSessionCode.mockResolvedValue(session(FOREIGN_TOKEN));
184
+ await ensureAppBackendSession(directory, { allowSilent: true });
185
+ sessionStorage.setItem(AUTH_REFRESH_STORAGE_KEY, 'shell-refresh');
186
+
187
+ await endAppBackendSessions();
188
+
189
+ expect(getAppBackendSession(directory.key)).toBeNull();
190
+ expect(sessionStorage.getItem(AUTH_REFRESH_STORAGE_KEY)).toBe('shell-refresh');
191
+ expect(logout).toHaveBeenCalledWith(expect.objectContaining({ accessToken: FOREIGN_TOKEN }));
192
+ const dumped = JSON.stringify(
193
+ [...Array(sessionStorage.length).keys()].map((index) => sessionStorage.key(index)),
194
+ );
195
+ expect(dumped).not.toContain(APP_BACKEND_REFRESH_PREFIX);
196
+ });
197
+
198
+ describe('token exchange for upstream identity servers', () => {
199
+ const exchange = vi.fn();
200
+ const jwt = (sub: string, jti: string) =>
201
+ `h.${btoa(JSON.stringify({ sub, jti })).replace(/=+$/, '')}.s`;
202
+ let shellToken: string | null = jwt('1', 'g1');
203
+
204
+ function upstream(companyId?: number) {
205
+ const identity = resolveAppBackendConfig(
206
+ { url: 'https://id.eu.example', companyId, provider: 'upstream', type: 'shellui' },
207
+ { backend: { type: 'shellui', url: 'https://id.example.com', companyId: 1 } },
208
+ );
209
+ if (!identity) throw new Error('expected identity');
210
+ return identity;
211
+ }
212
+
213
+ function due(accessToken: string, refreshToken: string): AuthSession {
214
+ return {
215
+ ...session(accessToken, refreshToken),
216
+ expiresAt: Math.floor(Date.now() / 1000) + 10,
217
+ };
218
+ }
219
+
220
+ function stored(): string {
221
+ return JSON.stringify(
222
+ [...Array(sessionStorage.length).keys()].map((index) => {
223
+ const key = sessionStorage.key(index) ?? '';
224
+ return [key, sessionStorage.getItem(key)];
225
+ }),
226
+ );
227
+ }
228
+
229
+ beforeEach(() => {
230
+ shellToken = jwt('1', 'g1');
231
+ exchange.mockReset();
232
+ setAppBackendTokenExchange(async () => shellToken, exchange);
233
+ });
234
+
235
+ afterEach(() => {
236
+ resetAppBackendTokenExchange();
237
+ });
238
+
239
+ it('exchanges the shell token at the regional server and never uses silent sign-in', async () => {
240
+ exchange.mockResolvedValue({ ok: true, session: session('regional-1', 'regional-refresh') });
241
+ const identity = upstream(5);
242
+
243
+ const token = await ensureAppBackendSession(identity, { allowSilent: false });
244
+
245
+ expect(token).toBe('regional-1');
246
+ expect(exchange).toHaveBeenCalledWith(
247
+ expect.objectContaining({
248
+ backendUrl: 'https://id.eu.example',
249
+ companyId: 5,
250
+ shellAccessToken: shellToken,
251
+ }),
252
+ );
253
+ expect(signIn).not.toHaveBeenCalled();
254
+ expect(getAppBackendSession(identity.key)?.accessToken).toBe('regional-1');
255
+ expect(stored()).toContain('regional-refresh');
256
+ expect(stored()).not.toContain('regional-1"');
257
+ expect(stored()).not.toContain(shellToken);
258
+ });
259
+
260
+ it('renews with the regional refresh token, not a new exchange', async () => {
261
+ exchange.mockResolvedValueOnce({ ok: true, session: due('regional-old', 'regional-r1') });
262
+ const identity = upstream(5);
263
+ await ensureAppBackendSession(identity);
264
+ refreshAuthSession.mockResolvedValueOnce(session('regional-new', 'regional-r2'));
265
+
266
+ shellToken = jwt('1', 'g2');
267
+ expect(await ensureAppBackendSession(identity)).toBe('regional-new');
268
+ expect(refreshAuthSession).toHaveBeenCalledWith(
269
+ expect.objectContaining({ refreshToken: 'regional-r1' }),
270
+ expect.any(Number),
271
+ );
272
+ expect(factory).toHaveBeenCalledWith(
273
+ expect.objectContaining({ url: 'https://id.eu.example' }),
274
+ );
275
+ expect(exchange).toHaveBeenCalledTimes(1);
276
+ expect(stored()).toContain('regional-r2');
277
+ });
278
+
279
+ it('exchanges again when the regional refresh fails', async () => {
280
+ exchange.mockResolvedValueOnce({ ok: true, session: due('regional-old', 'regional-r1') });
281
+ const identity = upstream(5);
282
+ await ensureAppBackendSession(identity);
283
+ refreshAuthSession.mockRejectedValueOnce(new Error('HTTP 401'));
284
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-new', 'regional-r3') });
285
+
286
+ expect(await ensureAppBackendSession(identity)).toBe('regional-new');
287
+ expect(exchange).toHaveBeenCalledTimes(2);
288
+ });
289
+
290
+ it('drops the regional session and exchanges when the shell user changes', async () => {
291
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-ada', 'r-ada') });
292
+ const identity = upstream(5);
293
+ await ensureAppBackendSession(identity);
294
+
295
+ shellToken = jwt('2', 'g9');
296
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-bob', 'r-bob') });
297
+ expect(await ensureAppBackendSession(identity)).toBe('regional-bob');
298
+ expect(refreshAuthSession).not.toHaveBeenCalled();
299
+ expect(stored()).not.toContain('r-ada');
300
+ });
301
+
302
+ it('does not retry a failed exchange until the shell token changes', async () => {
303
+ exchange.mockResolvedValue({ ok: false, reason: 'invalid_grant' });
304
+ const identity = upstream(5);
305
+
306
+ expect(await ensureAppBackendSession(identity)).toBeNull();
307
+ expect(await ensureAppBackendSession(identity)).toBeNull();
308
+ expect(exchange).toHaveBeenCalledTimes(1);
309
+
310
+ shellToken = jwt('1', 'g2');
311
+ exchange.mockResolvedValue({ ok: true, session: session('regional-2') });
312
+ expect(await ensureAppBackendSession(identity)).toBe('regional-2');
313
+ });
314
+
315
+ it('clears the regional session on shell sign-out', async () => {
316
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-1', 'r1') });
317
+ const identity = upstream(5);
318
+ await ensureAppBackendSession(identity);
319
+
320
+ await endAppBackendSessions();
321
+ expect(getAppBackendSession(identity.key)).toBeNull();
322
+ expect(sessionStorage.length).toBe(0);
323
+
324
+ shellToken = null;
325
+ expect(await ensureAppBackendSession(identity)).toBeNull();
326
+ expect(exchange).toHaveBeenCalledTimes(1);
327
+ });
328
+ });
329
+ });