@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
@@ -1,6 +1,8 @@
1
1
  import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
2
2
  import type { AuthSession } from '../types';
3
3
  import { AuthRequestError } from '../utils/authRequestError';
4
+ import { generateCodeChallenge } from '../utils/pkce';
5
+ import { WEB_PKCE_FLOW_PARAM, takeWebPkceVerifier } from '../utils/webPkce';
4
6
  import { createShellUIAuthBackend } from './shellui';
5
7
 
6
8
  vi.mock('../../config/useConfig', () => ({ useConfig: () => ({ config: {} }) }));
@@ -11,16 +13,27 @@ const jsonResponse = (status: number, body: unknown) =>
11
13
  headers: { 'Content-Type': 'application/json' },
12
14
  });
13
15
 
16
+ function memoryStorage(seed: [string, string][] = []): Storage {
17
+ const map = new Map<string, string>(seed);
18
+ return {
19
+ get length() {
20
+ return map.size;
21
+ },
22
+ key: (i: number) => Array.from(map.keys())[i] ?? null,
23
+ getItem: (k: string) => map.get(k) ?? null,
24
+ setItem: (k: string, v: string) => void map.set(k, String(v)),
25
+ removeItem: (k: string) => void map.delete(k),
26
+ clear: () => map.clear(),
27
+ };
28
+ }
29
+
14
30
  describe('shellui backend sendMagicLink', () => {
15
31
  const fetchMock = vi.fn();
16
32
 
17
33
  beforeEach(() => {
18
- const storage = new Map<string, string>([['shellui_auth_client_device_id', 'device-1']]);
19
34
  vi.stubGlobal('window', { location: { origin: 'https://app.example.com' } });
20
- vi.stubGlobal('localStorage', {
21
- getItem: (key: string) => storage.get(key) ?? null,
22
- setItem: (key: string, value: string) => storage.set(key, value),
23
- });
35
+ vi.stubGlobal('localStorage', memoryStorage([['shellui_auth_client_device_id', 'device-1']]));
36
+ vi.stubGlobal('sessionStorage', memoryStorage());
24
37
  vi.stubGlobal('fetch', fetchMock);
25
38
  });
26
39
 
@@ -46,13 +59,23 @@ describe('shellui backend sendMagicLink', () => {
46
59
  expect(body).toMatchObject({
47
60
  company_id: 7,
48
61
  email: 'ada@acme.com',
49
- redirect_to: 'https://app.example.com/login/callback?next=%2Fapps',
50
62
  client_device_id: 'device-1',
63
+ code_challenge_method: 'S256',
51
64
  });
65
+ const redirect = new URL(body.redirect_to as string);
66
+ expect(`${redirect.origin}${redirect.pathname}`).toBe('https://app.example.com/login/callback');
67
+ expect(redirect.searchParams.get('next')).toBe('/apps');
68
+ const flowId = redirect.searchParams.get(WEB_PKCE_FLOW_PARAM);
69
+ expect(flowId).toMatch(/^m[0-9a-f]{32}$/);
70
+ expect(body.code_challenge).toMatch(/^[A-Za-z0-9_-]{43}$/);
71
+ expect(body).not.toHaveProperty('code_verifier');
52
72
  expect(body).not.toHaveProperty('email_redirect_to');
53
73
  expect(body).not.toHaveProperty('language');
54
- expect(body).not.toHaveProperty('code_challenge');
55
- expect(body).not.toHaveProperty('code_challenge_method');
74
+ // The verifier waits in localStorage for the tab the email link opens.
75
+ const verifier = takeWebPkceVerifier(flowId);
76
+ expect(verifier).toBeTruthy();
77
+ expect(body.redirect_to as string).not.toContain(verifier as string);
78
+ expect(body.code_challenge).toBe(await generateCodeChallenge(verifier as string));
56
79
  });
57
80
 
58
81
  test('desktop magic link sends the custom scheme and an S256 challenge', async () => {
@@ -152,6 +175,9 @@ describe('shellui backend OAuth session', () => {
152
175
  auth_code: 'session-code',
153
176
  redirect_to: 'https://app.example.com/login/callback',
154
177
  });
178
+ // The browser sets Origin. The exchange is a plain cross-origin POST.
179
+ expect(init.credentials).toBeUndefined();
180
+ expect(Object.keys(init.headers as Record<string, string>)).not.toContain('Origin');
155
181
  });
156
182
 
157
183
  test('desktop exchange adds code_verifier and nothing else', async () => {
@@ -180,34 +206,40 @@ describe('shellui backend OAuth session', () => {
180
206
  });
181
207
 
182
208
  describe('shellui backend startOAuth', () => {
183
- test('keeps the http redirect and does not send PKCE', () => {
209
+ test('sends an S256 challenge and keeps the verifier out of the URL', async () => {
184
210
  const assign = vi.fn();
185
211
  vi.stubGlobal('window', {
186
212
  location: { origin: 'https://app.example.com', assign },
187
213
  });
188
- vi.stubGlobal('localStorage', {
189
- getItem: () => null,
190
- setItem: () => undefined,
191
- });
214
+ vi.stubGlobal('localStorage', memoryStorage());
215
+ vi.stubGlobal('sessionStorage', memoryStorage());
192
216
  const backend = createShellUIAuthBackend({
193
217
  backendUrl: 'https://auth.example.com',
194
218
  companyId: 7,
195
219
  });
196
220
 
197
- backend.startOAuth('github', '/login/callback', 4);
221
+ await backend.startOAuth('github', '/login/callback', 4);
198
222
 
199
223
  expect(assign).toHaveBeenCalledTimes(1);
200
224
  const url = new URL(String(assign.mock.calls[0]?.[0]));
201
225
  expect(`${url.origin}${url.pathname}`).toBe('https://auth.example.com/api/v1/authorize');
202
226
  expect(url.searchParams.get('provider')).toBe('github');
203
- expect(url.searchParams.get('redirect_to')).toBe(
204
- 'https://app.example.com/login/callback?provider=github&company_oauth_client_id=4',
205
- );
227
+ const redirect = new URL(url.searchParams.get('redirect_to') as string);
228
+ expect(redirect.searchParams.get('provider')).toBe('github');
229
+ expect(redirect.searchParams.get('company_oauth_client_id')).toBe('4');
230
+ const flowId = redirect.searchParams.get(WEB_PKCE_FLOW_PARAM);
231
+ expect(flowId).toMatch(/^o[0-9a-f]{32}$/);
206
232
  expect(url.searchParams.get('company_id')).toBe('7');
207
233
  expect(url.searchParams.get('company_oauth_client_id')).toBe('4');
208
- expect(url.searchParams.has('code_challenge')).toBe(false);
209
- expect(url.searchParams.has('code_challenge_method')).toBe(false);
234
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256');
210
235
  expect(url.searchParams.has('code_verifier')).toBe(false);
236
+ expect(localStorage.getItem(`shellui.auth.pkce.magic.${flowId}`)).toBeNull();
237
+ const verifier = takeWebPkceVerifier(flowId);
238
+ expect(verifier).toBeTruthy();
239
+ expect(url.toString()).not.toContain(verifier as string);
240
+ expect(url.searchParams.get('code_challenge')).toBe(
241
+ await generateCodeChallenge(verifier as string),
242
+ );
211
243
  vi.unstubAllGlobals();
212
244
  });
213
245
  });
@@ -8,6 +8,7 @@ import {
8
8
  normalizeRedirectPath,
9
9
  } from '../utils';
10
10
  import { AuthRequestError } from '../utils/authRequestError';
11
+ import { clearWebPkce, prepareWebPkce } from '../utils/webPkce';
11
12
  import { getShellUILoginCompanyId } from '../utils/clientLoginContext';
12
13
  import type { AuthSession, UserPreferences } from '../types';
13
14
  import type { AuthBackend } from './types';
@@ -140,7 +141,7 @@ export const createShellUIAuthBackend = ({
140
141
  if (!currentSession?.refreshToken) return null;
141
142
  return refreshWithStoredToken(currentSession, nowSeconds);
142
143
  },
143
- startOAuth: (provider, redirectPath, oauthClientId) => {
144
+ startOAuth: async (provider, redirectPath, oauthClientId) => {
144
145
  if (!backendUrl) {
145
146
  throw new Error('Missing Shellui backend URL.');
146
147
  }
@@ -158,10 +159,12 @@ export const createShellUIAuthBackend = ({
158
159
  String(Math.trunc(oauthClientId)),
159
160
  );
160
161
  }
161
- const redirectTo = redirectToUrl.toString();
162
+ const pkce = await prepareWebPkce(redirectToUrl.toString(), 'oauth');
162
163
  const authorizeUrl = new URL(`${backendUrl}/api/v1/authorize`);
163
164
  authorizeUrl.searchParams.set('provider', provider);
164
- authorizeUrl.searchParams.set('redirect_to', redirectTo);
165
+ authorizeUrl.searchParams.set('redirect_to', pkce.redirectTo);
166
+ authorizeUrl.searchParams.set('code_challenge', pkce.challenge);
167
+ authorizeUrl.searchParams.set('code_challenge_method', 'S256');
165
168
  if (
166
169
  typeof oauthClientId === 'number' &&
167
170
  Number.isFinite(oauthClientId) &&
@@ -297,12 +300,23 @@ export const createShellUIAuthBackend = ({
297
300
  if (!selectedCompanyId) {
298
301
  throw new Error('Missing company_id for magic link request.');
299
302
  }
303
+ // Desktop passes its own custom-scheme redirect and challenge. The web flow
304
+ // creates a magic link PKCE pair here.
305
+ const webPkce = options?.codeChallenge
306
+ ? null
307
+ : await prepareWebPkce(
308
+ options?.redirectTo ??
309
+ `${window.location.origin}${normalizeRedirectPath(redirectPath)}`,
310
+ 'magic_link',
311
+ );
300
312
  const redirectTo =
301
- options?.redirectTo ?? `${window.location.origin}${normalizeRedirectPath(redirectPath)}`;
313
+ webPkce?.redirectTo ??
314
+ options?.redirectTo ??
315
+ `${window.location.origin}${normalizeRedirectPath(redirectPath)}`;
302
316
  const clientTz = getShellUILoginClientTimezone();
303
317
  const clientDeviceId = getShellUILoginDeviceId();
304
318
  const language = options?.language?.trim();
305
- const codeChallenge = options?.codeChallenge?.trim();
319
+ const codeChallenge = webPkce?.challenge ?? options?.codeChallenge?.trim();
306
320
  const response = await fetch(`${backendUrl}${MAGIC_LINK_REQUEST_ENDPOINT}`, {
307
321
  method: 'POST',
308
322
  headers: {
@@ -322,6 +336,7 @@ export const createShellUIAuthBackend = ({
322
336
  }),
323
337
  });
324
338
  if (!response.ok) {
339
+ if (webPkce) clearWebPkce(webPkce.flowId);
325
340
  const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
326
341
  const err = payload?.error ?? payload?.detail;
327
342
  const message =
@@ -27,7 +27,12 @@ export interface AuthBackend {
27
27
  session: AuthSession | null,
28
28
  nowSeconds: number,
29
29
  ) => Promise<AuthSession | null>;
30
- startOAuth: (provider: string, redirectPath: string, oauthClientId?: number) => void;
30
+ /** May resolve after creating the PKCE pair; then the page navigates away. */
31
+ startOAuth: (
32
+ provider: string,
33
+ redirectPath: string,
34
+ oauthClientId?: number,
35
+ ) => void | Promise<void>;
31
36
  startWeb3Ethereum: () => Promise<AuthSession | null>;
32
37
  logout: (session: AuthSession | null) => Promise<void>;
33
38
  /** Whether {@link deleteAccount} is implemented for this backend. */
@@ -49,7 +54,7 @@ export interface AuthBackend {
49
54
  language?: string;
50
55
  /** Custom-scheme redirect for desktop sign-in. Omit to keep the web origin. */
51
56
  redirectTo?: string;
52
- /** S256 challenge for a desktop magic link. Omit on the web flow. */
57
+ /** S256 challenge for a desktop magic link. Omit on the web flow, which creates its own. */
53
58
  codeChallenge?: string;
54
59
  },
55
60
  ) => Promise<void>;
@@ -1,4 +1,12 @@
1
- import { useCallback, useEffect, useMemo, useState, type FormEvent } from 'react';
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useLayoutEffect,
5
+ useMemo,
6
+ useRef,
7
+ useState,
8
+ type FormEvent,
9
+ } from 'react';
2
10
  import { useTranslation } from 'react-i18next';
3
11
  import { useLocation, useNavigate } from 'react-router';
4
12
  import { shellui } from '@shellui/sdk';
@@ -22,6 +30,7 @@ import {
22
30
  normalizeNextPath,
23
31
  redirectToCliCallback,
24
32
  resolveLoginSettings,
33
+ getLoginCancelTarget,
25
34
  } from '../utils';
26
35
  import { AppBrandIcon } from '../../layouts/branding/AppBrandIcon';
27
36
  import { DESKTOP_TITLEBAR_HEIGHT_PX } from '../../layouts/chrome/constants';
@@ -29,6 +38,7 @@ import { useMacTrafficLights } from '../../layouts/chrome/runtime';
29
38
  import { validateLoginPanelUrl } from '../../security/urlAllowlist';
30
39
  import { AccessPendingView } from './AccessPendingView';
31
40
  import { LoginPreferencesControls } from './LoginPreferencesControls';
41
+ import { registerLoginPanelFrame } from '../utils/loginPanelFrame';
32
42
 
33
43
  /** Shared top inset for login chrome when traffic lights are absent. */
34
44
  const LOGIN_CHROME_PAD_Y = '2rem';
@@ -108,6 +118,8 @@ export const LoginView = () => {
108
118
  sendMagicLink,
109
119
  session,
110
120
  } = useAuth();
121
+ // Cancel goes to a page reachable without signing in; hidden when there is none (#104).
122
+ const loginCancelTarget = useMemo(() => getLoginCancelTarget(config), [config]);
111
123
  const configuredSettings = useMemo<AuthSettings>(
112
124
  () => resolveLoginSettings(config.backend),
113
125
  [config.backend],
@@ -487,6 +499,13 @@ export const LoginView = () => {
487
499
  const panelImage = config.backend?.login?.panelImage?.trim() || null;
488
500
  const hasCustomPanel = Boolean(panelUrl || panelImage);
489
501
  const legalDocuments = useMemo(() => getLegalDocuments(config), [config]);
502
+ const panelIframeRef = useRef<HTMLIFrameElement>(null);
503
+ // Register the side panel frame so theme and language changes reach it live.
504
+ // Deps cover every state that can mount or unmount the iframe.
505
+ useLayoutEffect(
506
+ () => registerLoginPanelFrame(panelIframeRef.current),
507
+ [panelUrl, isIframeView, isAuthenticated, oauthBounceCode],
508
+ );
490
509
 
491
510
  if (isAuthenticated) {
492
511
  return null;
@@ -558,6 +577,7 @@ export const LoginView = () => {
558
577
  >
559
578
  {panelUrl ? (
560
579
  <iframe
580
+ ref={panelIframeRef}
561
581
  src={panelUrl}
562
582
  title={t('loginPage.brandingIframeTitle')}
563
583
  className="h-full w-full border-0"
@@ -835,23 +855,25 @@ export const LoginView = () => {
835
855
  <p className="text-sm text-muted-foreground">{t('loginPage.noMethodsEnabled')}</p>
836
856
  )}
837
857
 
838
- <div className="flex justify-end">
839
- <Button
840
- type="button"
841
- variant="link"
842
- size="sm"
843
- className="h-auto px-0 text-xs font-normal text-muted-foreground/80 hover:text-muted-foreground"
844
- onClick={() => {
845
- if (isIframeView) {
846
- shellui.closeModal();
847
- return;
848
- }
849
- navigate('/');
850
- }}
851
- >
852
- {t('loginPage.cancel')}
853
- </Button>
854
- </div>
858
+ {(isIframeView || loginCancelTarget) && (
859
+ <div className="flex justify-end">
860
+ <Button
861
+ type="button"
862
+ variant="link"
863
+ size="sm"
864
+ className="h-auto px-0 text-xs font-normal text-muted-foreground/80 hover:text-muted-foreground"
865
+ onClick={() => {
866
+ if (isIframeView) {
867
+ shellui.closeModal();
868
+ return;
869
+ }
870
+ if (loginCancelTarget) navigate(loginCancelTarget);
871
+ }}
872
+ >
873
+ {t('loginPage.cancel')}
874
+ </Button>
875
+ </div>
876
+ )}
855
877
  </div>
856
878
  </div>
857
879
  </div>
@@ -1,11 +1,11 @@
1
- import { useEffect, useMemo, useRef, useState } from 'react';
1
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
2
2
  import { useTranslation } from 'react-i18next';
3
3
  import { useLocation, useNavigate } from 'react-router';
4
4
  import urls from '../../../constants/urls';
5
5
  import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
6
6
  import {
7
7
  buildAuthUrlWithNext,
8
- buildOAuthSessionRedirectTo,
8
+ resolveOAuthSessionRedirectTo,
9
9
  captureCliCallbackFromSearch,
10
10
  hashHasOAuthTokens,
11
11
  inferAccessPendingErrorCode,
@@ -15,6 +15,11 @@ import {
15
15
  redirectCliCallbackError,
16
16
  redirectToCliCallback,
17
17
  } from '../utils';
18
+ import { WEB_PKCE_FLOW_PARAM, isMagicLinkFlowId, takeWebPkceFlow } from '../utils/webPkce';
19
+ import {
20
+ isSilentAuthCallbackFrame,
21
+ publishSilentAuthCallbackResult,
22
+ } from '../appBackend/silentSignIn';
18
23
  import { useAuth } from '../hooks/useAuth';
19
24
  import { AccessPendingView } from './AccessPendingView';
20
25
 
@@ -112,13 +117,19 @@ export const OAuthCallbackView = () => {
112
117
  captureCliCallbackFromSearch(location.search);
113
118
  }, [location.search]);
114
119
 
120
+ useLayoutEffect(() => {
121
+ publishSilentAuthCallbackResult();
122
+ }, [location.search]);
123
+
115
124
  useEffect(() => {
125
+ if (isSilentAuthCallbackFrame()) return;
116
126
  if (!isAuthenticated || !session) return;
117
127
  if (redirectToCliCallback(session)) return;
118
128
  navigate(nextPath, { replace: true });
119
129
  }, [isAuthenticated, navigate, nextPath, session]);
120
130
 
121
131
  useEffect(() => {
132
+ if (isSilentAuthCallbackFrame()) return;
122
133
  if (isAuthenticated) return;
123
134
  // Identity bounce lands with tokens in the hash; AuthProvider restores the session.
124
135
  // Stay on "Completing…" while hash is present or auth bootstrap is still running.
@@ -220,14 +231,32 @@ export const OAuthCallbackView = () => {
220
231
 
221
232
  let cancelled = false;
222
233
  const runSessionExchange = async () => {
223
- const redirectTo = buildOAuthSessionRedirectTo(
234
+ const pkceFlowId = params.get(WEB_PKCE_FLOW_PARAM);
235
+ const pkceFlow = takeWebPkceFlow(pkceFlowId);
236
+ const codeVerifier = pkceFlow?.verifier ?? undefined;
237
+ const redirectTo = resolveOAuthSessionRedirectTo(
238
+ pkceFlow?.redirectTo,
224
239
  window.location.origin,
225
240
  location.pathname,
226
241
  location.search,
227
242
  );
243
+ if (!codeVerifier && isMagicLinkFlowId(pkceFlowId)) {
244
+ // The magic link verifier lives only in the browser that asked for the link.
245
+ // Do not send the code: it stays unused.
246
+ applyExchangeFailure(
247
+ authCode,
248
+ {
249
+ ok: false,
250
+ error: t('loginPage.magicLinkOtherBrowser'),
251
+ errorCode: 'magic_link_other_browser',
252
+ },
253
+ cancelled,
254
+ );
255
+ return;
256
+ }
228
257
  let result: { ok: boolean; error?: string | null; errorCode?: string | null };
229
258
  try {
230
- result = await completeOAuthSessionCallback({ authCode, redirectTo });
259
+ result = await completeOAuthSessionCallback({ authCode, redirectTo, codeVerifier });
231
260
  } catch (err) {
232
261
  result = {
233
262
  ok: false,
@@ -1,3 +1,5 @@
1
+ import { isWebPkceErrorCode } from './webPkce';
2
+
1
3
  export class AuthRequestError extends Error {
2
4
  readonly code: string | null;
3
5
  /** Extra fields from the error response body (e.g. `companies` for `last_company_owner`). */
@@ -19,6 +21,7 @@ export function isAccessPendingErrorCode(code: string | null | undefined): boole
19
21
  /** i18n key when the shell replaces a backend sign-in sentence with its own copy. */
20
22
  export function loginErrorMessageKey(code: string | null | undefined): string | null {
21
23
  if (code === 'magic_link_staff_disabled') return 'loginPage.magicLinkStaffDisabled';
24
+ if (isWebPkceErrorCode(code)) return 'loginPage.pkceFailed';
22
25
  return null;
23
26
  }
24
27
 
@@ -1,6 +1,9 @@
1
1
  import { describe, expect, test } from 'vitest';
2
2
  import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
3
- import { buildOAuthSessionRedirectTo } from './buildOAuthSessionRedirectTo';
3
+ import {
4
+ buildOAuthSessionRedirectTo,
5
+ resolveOAuthSessionRedirectTo,
6
+ } from './buildOAuthSessionRedirectTo';
4
7
 
5
8
  describe('buildOAuthSessionRedirectTo', () => {
6
9
  test('strips shellui_auth_code and keeps other query params', () => {
@@ -20,3 +23,41 @@ describe('buildOAuthSessionRedirectTo', () => {
20
23
  ).toBe('http://127.0.0.1:8765/callback');
21
24
  });
22
25
  });
26
+
27
+ describe('resolveOAuthSessionRedirectTo', () => {
28
+ const start =
29
+ 'https://playground.shellui.com/login/callback?provider=github&shellui_pkce_flow=o0123';
30
+
31
+ test('uses the stored start value when the host added a trailing slash', () => {
32
+ expect(
33
+ resolveOAuthSessionRedirectTo(
34
+ start,
35
+ 'https://playground.shellui.com',
36
+ '/login/callback/',
37
+ '?provider=github&shellui_pkce_flow=o0123&shellui_auth_code=abc',
38
+ ),
39
+ ).toBe(start);
40
+ });
41
+
42
+ test('falls back to the current URL when nothing was stored', () => {
43
+ expect(
44
+ resolveOAuthSessionRedirectTo(
45
+ null,
46
+ 'https://playground.shellui.com',
47
+ '/login/callback/',
48
+ '?provider=github&shellui_auth_code=abc',
49
+ ),
50
+ ).toBe('https://playground.shellui.com/login/callback/?provider=github');
51
+ });
52
+
53
+ test('ignores a stored value for another origin', () => {
54
+ expect(
55
+ resolveOAuthSessionRedirectTo(
56
+ 'https://evil.test/login/callback',
57
+ 'https://playground.shellui.com',
58
+ '/login/callback',
59
+ '?shellui_auth_code=abc',
60
+ ),
61
+ ).toBe('https://playground.shellui.com/login/callback');
62
+ });
63
+ });
@@ -15,3 +15,26 @@ export function buildOAuthSessionRedirectTo(
15
15
  url.search = params.toString();
16
16
  return url.toString();
17
17
  }
18
+
19
+ /**
20
+ * Pick the `redirect_to` for the session exchange. Identity compares it exactly
21
+ * with the value sent at sign-in start, so prefer that stored value. A static
22
+ * host can add a trailing slash on the way back (GitHub Pages turns
23
+ * `/login/callback` into `/login/callback/`). Fall back to the current URL when
24
+ * nothing was stored or the stored value is for another origin.
25
+ */
26
+ export function resolveOAuthSessionRedirectTo(
27
+ storedRedirectTo: string | null | undefined,
28
+ origin: string,
29
+ pathname: string,
30
+ search: string,
31
+ ): string {
32
+ if (storedRedirectTo) {
33
+ try {
34
+ if (new URL(storedRedirectTo).origin === origin) return storedRedirectTo;
35
+ } catch {
36
+ // invalid stored value: rebuild from the current URL
37
+ }
38
+ }
39
+ return buildOAuthSessionRedirectTo(origin, pathname, search);
40
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { AuthSession } from '../types';
3
+ import { canRestoreStoredSession } from './canRestoreStoredSession';
4
+
5
+ const base = {
6
+ accessToken: '',
7
+ refreshToken: '',
8
+ tokenType: 'bearer',
9
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
10
+ provider: 'github',
11
+ } as unknown as AuthSession;
12
+
13
+ describe('canRestoreStoredSession', () => {
14
+ it('rejects a profile without tokens, as seen in a new tab', () => {
15
+ expect(canRestoreStoredSession(base, false)).toBe(false);
16
+ });
17
+
18
+ it('accepts a refresh token', () => {
19
+ expect(canRestoreStoredSession({ ...base, refreshToken: 'r' }, false)).toBe(true);
20
+ });
21
+
22
+ it('accepts an access token', () => {
23
+ expect(canRestoreStoredSession({ ...base, accessToken: 'a' }, false)).toBe(true);
24
+ });
25
+
26
+ it('accepts a token-less profile when BFF cookies can refresh it', () => {
27
+ expect(canRestoreStoredSession(base, true)).toBe(true);
28
+ });
29
+ });
@@ -0,0 +1,12 @@
1
+ import type { AuthSession } from '../types';
2
+
3
+ /**
4
+ * Whether a stored session snapshot can become a signed-in session on boot.
5
+ *
6
+ * The access token lives in memory only and the refresh token is tab-scoped
7
+ * (sessionStorage), while the profile is shared in localStorage. A new tab
8
+ * therefore sees the profile without any token. Without a token, or a refresh
9
+ * token or BFF cookie to get one, the snapshot must not count as signed in.
10
+ */
11
+ export const canRestoreStoredSession = (stored: AuthSession, bffAuthEnabled: boolean): boolean =>
12
+ Boolean(stored.accessToken || stored.refreshToken || bffAuthEnabled);
@@ -4,7 +4,12 @@ export {
4
4
  getShellUILoginDeviceId,
5
5
  } from './clientLoginContext';
6
6
  export { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
7
- export { buildOAuthSessionRedirectTo } from './buildOAuthSessionRedirectTo';
7
+ export { resolveSdkLoginRedirectPath } from './resolveSdkLoginRedirectPath';
8
+ export { getLoginCancelTarget, isPublicNavigationPage } from './loginCancelTarget';
9
+ export {
10
+ buildOAuthSessionRedirectTo,
11
+ resolveOAuthSessionRedirectTo,
12
+ } from './buildOAuthSessionRedirectTo';
8
13
  export { buildSessionFromParams } from './buildSessionFromParams';
9
14
  export {
10
15
  buildSessionFromTokenPayload,
@@ -47,6 +52,7 @@ export { getPreferredBackendProvider } from './getPreferredBackendProvider';
47
52
  export { getProviderVisual } from './getProviderVisual';
48
53
  export { isLoginMethod } from './isLoginMethod';
49
54
  export { resolveLoginSettings } from './resolveLoginSettings';
55
+ export { canRestoreStoredSession } from './canRestoreStoredSession';
50
56
  export { isSessionExpired } from './isSessionExpired';
51
57
  export { isTokenAutoRefreshDisabled } from './isTokenAutoRefreshDisabled';
52
58
  export { normalizeAuthSettings } from './normalizeAuthSettings';
@@ -55,3 +61,12 @@ export { normalizeRedirectPath } from './normalizeRedirectPath';
55
61
  export { shareInFlight } from './shareInFlight';
56
62
  export type { InFlightSlot } from './shareInFlight';
57
63
  export { toAuthSessionFromSettingsUser } from './toAuthSessionFromSettingsUser';
64
+ export {
65
+ WEB_PKCE_FLOW_PARAM,
66
+ prepareWebPkce,
67
+ takeWebPkceVerifier,
68
+ takeWebPkceFlow,
69
+ clearWebPkce,
70
+ isWebPkceErrorCode,
71
+ isMagicLinkFlowId,
72
+ } from './webPkce';
@@ -0,0 +1,73 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import type { NavigationItem } from '../../config/types';
3
+ import { getLoginCancelTarget, isPublicNavigationPage } from './loginCancelTarget';
4
+
5
+ const item = (path: string, extra: Partial<NavigationItem> = {}): NavigationItem => ({
6
+ label: path || 'Home',
7
+ path,
8
+ url: `/app/#/${path}`,
9
+ ...extra,
10
+ });
11
+
12
+ describe('getLoginCancelTarget', () => {
13
+ test('goes to / when the homepage is public', () => {
14
+ expect(getLoginCancelTarget({ navigation: [item(''), item('docs')] })).toBe('/');
15
+ });
16
+
17
+ test('goes to / when there is no root item (HomeView)', () => {
18
+ expect(getLoginCancelTarget({ navigation: [item('files', { requiresAuth: true })] })).toBe('/');
19
+ expect(getLoginCancelTarget({ navigation: [] })).toBe('/');
20
+ expect(getLoginCancelTarget(undefined)).toBe('/');
21
+ });
22
+
23
+ test('goes to the first public page when the homepage requires auth', () => {
24
+ const navigation = [
25
+ item('', { requiresAuth: true }),
26
+ { title: 'Group', items: [item('files', { requiresAuth: true }), item('docs')] },
27
+ ];
28
+ expect(getLoginCancelTarget({ navigation })).toBe('/docs');
29
+ });
30
+
31
+ test('returns null when every page requires auth', () => {
32
+ const navigation = [
33
+ item('', { requiresAuth: true }),
34
+ item('files', { requiresAuth: true }),
35
+ item('admin', { requiresStaff: true }),
36
+ item('private', { hideWhenLoggedOut: true }),
37
+ ];
38
+ expect(getLoginCancelTarget({ navigation })).toBeNull();
39
+ });
40
+
41
+ test('ignores settings, login, external, dev-mode and hidden entries', () => {
42
+ const navigation = [
43
+ item('', { requiresAuth: true }),
44
+ item('settings', { url: '/__settings', openIn: 'modal' }),
45
+ item('login', { url: '/login', openIn: 'modal' }),
46
+ item('login-page', { url: '/login' }),
47
+ item('website', { url: 'https://shellui.com/', openIn: 'external' }),
48
+ item('drawer', { openIn: 'drawer' }),
49
+ item('dev', { requiresDevMode: true }),
50
+ item('secret', { hidden: true }),
51
+ ];
52
+ expect(getLoginCancelTarget({ navigation })).toBeNull();
53
+ });
54
+
55
+ test('follows start_url', () => {
56
+ const navigation = [item('files', { requiresAuth: true }), item('docs')];
57
+ expect(getLoginCancelTarget({ navigation, start_url: '/docs' })).toBe('/');
58
+ expect(getLoginCancelTarget({ navigation, start_url: 'files' })).toBe('/docs');
59
+ expect(
60
+ getLoginCancelTarget({
61
+ navigation: [item('files', { requiresAuth: true })],
62
+ start_url: '/files',
63
+ }),
64
+ ).toBeNull();
65
+ });
66
+ });
67
+
68
+ describe('isPublicNavigationPage', () => {
69
+ test('plain page items are public', () => {
70
+ expect(isPublicNavigationPage(item('docs'))).toBe(true);
71
+ expect(isPublicNavigationPage(item('docs', { openIn: 'default' }))).toBe(true);
72
+ });
73
+ });