@shellui/core 0.6.0-beta.1 → 0.6.1

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 (30) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -2
  3. package/schemas/shellui.config.schema.json +15 -0
  4. package/src/features/auth/AuthProvider.tsx +167 -69
  5. package/src/features/auth/backends/shellui.spec.ts +115 -0
  6. package/src/features/auth/backends/shellui.ts +8 -2
  7. package/src/features/auth/backends/types.ts +9 -1
  8. package/src/features/auth/components/LoginView.tsx +5 -1
  9. package/src/features/auth/components/OAuthCallbackView.tsx +12 -3
  10. package/src/features/auth/hooks/useAuth.tsx +1 -0
  11. package/src/features/auth/utils/accessTokenRefreshDue.spec.ts +15 -0
  12. package/src/features/auth/utils/accessTokenRefreshDue.ts +8 -0
  13. package/src/features/auth/utils/authRequestError.spec.ts +11 -0
  14. package/src/features/auth/utils/authRequestError.ts +6 -0
  15. package/src/features/auth/utils/desktopAuthCallback.spec.ts +68 -0
  16. package/src/features/auth/utils/desktopAuthCallback.ts +126 -0
  17. package/src/features/auth/utils/desktopSignIn.spec.ts +162 -0
  18. package/src/features/auth/utils/desktopSignIn.ts +445 -0
  19. package/src/features/auth/utils/frameSessionRefresher.spec.ts +23 -0
  20. package/src/features/auth/utils/frameSessionRefresher.ts +21 -0
  21. package/src/features/auth/utils/index.ts +1 -0
  22. package/src/features/auth/utils/pkce.spec.ts +36 -0
  23. package/src/features/auth/utils/pkce.ts +38 -0
  24. package/src/features/config/types.ts +17 -0
  25. package/src/features/settings/SettingsProvider.tsx +83 -31
  26. package/src/i18n/translations/en/common.json +4 -1
  27. package/src/i18n/translations/en/settings.json +1 -0
  28. package/src/i18n/translations/fr/common.json +4 -1
  29. package/src/i18n/translations/fr/settings.json +1 -0
  30. package/src/index.ts +6 -0
package/README.md CHANGED
@@ -6,7 +6,7 @@ React runtime for the Shellui host. `@shellui/cli` depends on this package. Inst
6
6
  npm install @shellui/core
7
7
  ```
8
8
 
9
- The 0.6.0 pre-release is on the `beta` tag: `npm install @shellui/core@beta`.
9
+ Shellui **0.6.1** is the current stable release: `npm install @shellui/core@0.6.1`.
10
10
 
11
11
  ```typescript
12
12
  import type { ShellUIConfig } from '@shellui/core';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shellui/core",
3
- "version": "0.6.0-beta.1",
3
+ "version": "0.6.1",
4
4
  "description": "Shellui Core - Core React application runtime",
5
5
  "main": "src/index.ts",
6
6
  "type": "module",
@@ -73,7 +73,7 @@
73
73
  "workbox-routing": "^7.4.0",
74
74
  "workbox-strategies": "^7.4.0",
75
75
  "workbox-window": "^7.4.0",
76
- "@shellui/sdk": "0.6.0-beta.1"
76
+ "@shellui/sdk": "0.6.1"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "react": "^18.0.0 || ^19.0.0",
@@ -119,6 +119,10 @@
119
119
  "$ref": "#/definitions/BackendConfig",
120
120
  "description": "Backend communication config. Defaults to undefined (no backend integration)."
121
121
  },
122
+ "auth": {
123
+ "$ref": "#/definitions/AuthConfig",
124
+ "description": "Desktop sign-in scheme for a Tauri shell. See `auth.desktopScheme`. Browser shells ignore this block."
125
+ },
122
126
  "security": {
123
127
  "$ref": "#/definitions/SecurityConfig",
124
128
  "description": "Host security (postMessage allowlist, BFF auth, CSP — see docs/features/security.md)."
@@ -892,6 +896,17 @@
892
896
  "additionalProperties": false,
893
897
  "description": "Sentry error reporting configuration. Only used in production; ignored in dev."
894
898
  },
899
+ "AuthConfig": {
900
+ "type": "object",
901
+ "properties": {
902
+ "desktopScheme": {
903
+ "type": "string",
904
+ "description": "Custom URL scheme for Tauri sign-in, such as `shellui-playground`. Lowercase. Not `http`, `https`, or another browser scheme."
905
+ }
906
+ },
907
+ "additionalProperties": false,
908
+ "description": "Desktop (Tauri) sign-in. Ignored in the browser, so the web OAuth redirect stays as it is. The scheme must match the OAuth application's `desktop_redirect_scheme`."
909
+ },
895
910
  "BackendConfig": {
896
911
  "type": "object",
897
912
  "properties": {
@@ -1,8 +1,15 @@
1
1
  import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
2
  import { useTranslation } from 'react-i18next';
3
- import { getLogger, postShellMessage, shellui, type Settings } from '@shellui/sdk';
3
+ import {
4
+ bindVisibleResume,
5
+ getLogger,
6
+ postShellMessage,
7
+ shellui,
8
+ type Settings,
9
+ } from '@shellui/sdk';
4
10
  import urls from '../../constants/urls';
5
11
  import { useConfig } from '../config/useConfig';
12
+ import { useIsTauriRuntime } from '../layouts/chrome/runtime';
6
13
  import { isShellSettingsFrameMessage } from '../security/trustedFrames';
7
14
  import { createAuthBackend } from './backends';
8
15
  import { AuthContext, type AuthContextValue, type OAuthCallbackResult } from './hooks/useAuth';
@@ -29,12 +36,24 @@ import {
29
36
  type InFlightSlot,
30
37
  } from './utils';
31
38
  import { buildAuthUrlWithNext } from './utils/buildAuthUrlWithNext';
39
+ import {
40
+ beginDesktopOAuth,
41
+ clearDesktopPkce,
42
+ createAndStoreDesktopPkce,
43
+ desktopSignInBlockReason,
44
+ ensureDesktopDeepLinkListener,
45
+ isLiveTauriRuntime,
46
+ setActiveDesktopScheme,
47
+ shouldUseDesktopSignIn,
48
+ subscribeDesktopAuth,
49
+ } from './utils/desktopSignIn';
50
+ import { normalizeDesktopScheme } from './utils/desktopAuthCallback';
32
51
  import type { DeleteAccountResultStatus, UpdateProfileResult } from './shellAccountRequests';
52
+ import { accessTokenRefreshDue } from './utils/accessTokenRefreshDue';
53
+ import { registerFrameSessionRefresher } from './utils/frameSessionRefresher';
33
54
 
34
55
  const logger = getLogger('shellcore');
35
56
 
36
- /** Refresh the access token this many seconds before `expiresAt` so API calls stay valid (JWT exp is absolute). */
37
- const PROACTIVE_REFRESH_LEEWAY_SECONDS = 90;
38
57
  /** Periodic check while the shell tab is open (also mitigates background-tab timer throttling). */
39
58
  const TOKEN_REFRESH_TICK_MS = 45_000;
40
59
 
@@ -66,6 +85,7 @@ type LoginMessagePayload = {
66
85
  export const AuthProvider = ({ children }: { children: ReactNode }) => {
67
86
  const { config } = useConfig();
68
87
  const { i18n } = useTranslation();
88
+ const tauriRuntime = useIsTauriRuntime();
69
89
  const bffAuthEnabled = isBffAuthEnabledFromConfig(config.security);
70
90
  const backend = useMemo(
71
91
  () => createAuthBackend(config.backend),
@@ -97,6 +117,60 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
97
117
  [backend, bffAuthEnabled],
98
118
  );
99
119
 
120
+ /**
121
+ * Refresh when the access token is inside the leeway (or already expired) and
122
+ * return the token iframes should use. Concurrent callers share one request
123
+ * so a visibility resume and a SETTINGS_REQUESTED reply cannot rotate twice.
124
+ */
125
+ const ensureFreshAccessToken = useCallback(async (): Promise<string | null> => {
126
+ const current = sessionRef.current;
127
+ if (!current?.accessToken) return null;
128
+ if (!bffAuthEnabled && !current.refreshToken) return current.accessToken;
129
+
130
+ const now = Math.floor(Date.now() / 1000);
131
+ if (!accessTokenRefreshDue(current.expiresAt, now)) return current.accessToken;
132
+
133
+ if (isTokenAutoRefreshDisabled()) {
134
+ if (!skippedRefreshLoggedRef.current) {
135
+ skippedRefreshLoggedRef.current = true;
136
+ logger.info('Skipped token refresh because Develop → Disable token auto-refresh is on', {
137
+ expiresAt: current.expiresAt,
138
+ secondsLeft: current.expiresAt - now,
139
+ });
140
+ }
141
+ return current.accessToken;
142
+ }
143
+
144
+ if (refreshInFlightRef.current) return refreshInFlightRef.current;
145
+
146
+ const flight: { current: Promise<string | null> | null } = { current: null };
147
+ flight.current = (async () => {
148
+ try {
149
+ const next = await refreshAuthSession(current, now);
150
+ if (!next) return sessionRef.current?.accessToken ?? null;
151
+ persistAuthSession(next, { storeRefreshToken: !bffAuthEnabled });
152
+ sessionRef.current = next;
153
+ setSession(next);
154
+ return next.accessToken;
155
+ } catch (err) {
156
+ logger.error('Token refresh failed', { err });
157
+ const message = err instanceof Error ? err.message : '';
158
+ if (/\b401\b/.test(message)) {
159
+ clearStoredAuthSession();
160
+ sessionRef.current = null;
161
+ setSession(null);
162
+ return null;
163
+ }
164
+ return sessionRef.current?.accessToken ?? null;
165
+ } finally {
166
+ if (refreshInFlightRef.current === flight.current) refreshInFlightRef.current = null;
167
+ }
168
+ })();
169
+
170
+ refreshInFlightRef.current = flight.current;
171
+ return flight.current;
172
+ }, [bffAuthEnabled, refreshAuthSession]);
173
+
100
174
  const [session, setSession] = useState<AuthSession | null>(null);
101
175
  const [isLoading, setIsLoading] = useState(hasInitialSessionToResolve);
102
176
  const [error, setError] = useState<string | null>(null);
@@ -104,7 +178,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
104
178
  const [authEvent, setAuthEvent] = useState<AuthEvent>(null);
105
179
  const sessionRef = useRef<AuthSession | null>(null);
106
180
  sessionRef.current = session;
107
- const refreshInFlightRef = useRef(false);
181
+ const refreshInFlightRef = useRef<Promise<string | null> | null>(null);
182
+ const skippedRefreshLoggedRef = useRef(false);
108
183
  /** Bumps on every preferences sync so a slower older PUT can’t overwrite a newer theme. */
109
184
  const preferencesSyncGenRef = useRef(0);
110
185
 
@@ -236,6 +311,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
236
311
  };
237
312
  }, [backend, bffAuthEnabled, commitAuthSession, refreshAuthSession]);
238
313
 
314
+ useEffect(() => {
315
+ if (typeof window === 'undefined' || window.parent !== window) return;
316
+ return registerFrameSessionRefresher(() => ensureFreshAccessToken());
317
+ }, [ensureFreshAccessToken]);
318
+
239
319
  useEffect(() => {
240
320
  if (typeof window === 'undefined' || window.parent !== window || isLoading) {
241
321
  return;
@@ -244,75 +324,20 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
244
324
  return;
245
325
  }
246
326
 
247
- let cancelled = false;
248
- let skippedRefreshLogged = false;
249
-
250
- const runRefresh = async () => {
251
- if (cancelled) return;
252
- const current = sessionRef.current;
253
- if (!current || refreshInFlightRef.current) return;
254
- if (!bffAuthEnabled && !current.refreshToken) return;
255
-
256
- const now = Math.floor(Date.now() / 1000);
257
- const secondsLeft = current.expiresAt - now;
258
- if (secondsLeft > PROACTIVE_REFRESH_LEEWAY_SECONDS && !isSessionExpired(current)) {
259
- return;
260
- }
261
-
262
- // Re-read when refresh is due so Develop → disableTokenAutoRefresh takes effect without remount.
263
- if (isTokenAutoRefreshDisabled()) {
264
- if (!skippedRefreshLogged) {
265
- skippedRefreshLogged = true;
266
- logger.info('Skipped token refresh because Develop → Disable token auto-refresh is on', {
267
- expiresAt: current.expiresAt,
268
- secondsLeft,
269
- });
270
- }
271
- return;
272
- }
273
-
274
- refreshInFlightRef.current = true;
275
- try {
276
- const next = await refreshAuthSession(current, now);
277
- if (cancelled || !next) return;
278
- persistAuthSession(next, { storeRefreshToken: !bffAuthEnabled });
279
- sessionRef.current = next;
280
- setSession(next);
281
- } catch (err) {
282
- logger.error('Token refresh failed', { err });
283
- const message = err instanceof Error ? err.message : '';
284
- if (/\b401\b/.test(message)) {
285
- clearStoredAuthSession();
286
- sessionRef.current = null;
287
- setSession(null);
288
- }
289
- } finally {
290
- refreshInFlightRef.current = false;
291
- }
327
+ const maybeRefresh = () => {
328
+ void ensureFreshAccessToken();
292
329
  };
293
330
 
294
- const maybeRefreshFromTimer = () => {
295
- void runRefresh();
296
- };
297
-
298
- const maybeRefreshOnResume = () => {
299
- if (cancelled || document.visibilityState !== 'visible') return;
300
- // Use the same proactive leeway as the timer (do not wait until already expired).
301
- void runRefresh();
302
- };
303
-
304
- maybeRefreshFromTimer();
305
- const intervalId = window.setInterval(maybeRefreshFromTimer, TOKEN_REFRESH_TICK_MS);
306
- document.addEventListener('visibilitychange', maybeRefreshOnResume);
307
- window.addEventListener('focus', maybeRefreshOnResume);
331
+ maybeRefresh();
332
+ const intervalId = window.setInterval(maybeRefresh, TOKEN_REFRESH_TICK_MS);
333
+ // visibilitychange, focus, and pageshow. Background tabs throttle the interval.
334
+ const stopResume = bindVisibleResume(maybeRefresh);
308
335
 
309
336
  return () => {
310
- cancelled = true;
311
337
  window.clearInterval(intervalId);
312
- document.removeEventListener('visibilitychange', maybeRefreshOnResume);
313
- window.removeEventListener('focus', maybeRefreshOnResume);
338
+ stopResume();
314
339
  };
315
- }, [bffAuthEnabled, isLoading, refreshAuthSession, session, session?.expiresAt]);
340
+ }, [bffAuthEnabled, ensureFreshAccessToken, isLoading, session, session?.expiresAt]);
316
341
 
317
342
  useEffect(() => {
318
343
  if (typeof window === 'undefined' || window.parent === window) {
@@ -346,6 +371,26 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
346
371
  try {
347
372
  setError(null);
348
373
  setErrorCode(null);
374
+ const liveTauri = tauriRuntime || isLiveTauriRuntime();
375
+ const blocked = desktopSignInBlockReason(config, liveTauri);
376
+ if (blocked) {
377
+ setError(blocked);
378
+ setErrorCode('invalid_desktop_scheme');
379
+ return false;
380
+ }
381
+ if (shouldUseDesktopSignIn(config, liveTauri)) {
382
+ void beginDesktopOAuth({
383
+ backendUrl: config.backend?.url ?? '',
384
+ companyId: config.backend?.companyId,
385
+ provider,
386
+ oauthClientId,
387
+ scheme: config.auth?.desktopScheme ?? '',
388
+ }).catch((err) => {
389
+ setError(err instanceof Error ? err.message : 'Unable to start desktop sign-in.');
390
+ setErrorCode(err instanceof AuthRequestError ? err.code : null);
391
+ });
392
+ return true;
393
+ }
349
394
  backend.startOAuth(provider, redirectPath, oauthClientId);
350
395
  return true;
351
396
  } catch (err) {
@@ -354,7 +399,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
354
399
  return false;
355
400
  }
356
401
  },
357
- [backend],
402
+ [backend, config, tauriRuntime],
358
403
  );
359
404
 
360
405
  const persistOAuthSession = useCallback(
@@ -387,9 +432,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
387
432
  async ({
388
433
  authCode,
389
434
  redirectTo,
435
+ codeVerifier,
390
436
  }: {
391
437
  authCode: string;
392
438
  redirectTo: string;
439
+ codeVerifier?: string;
393
440
  }): Promise<OAuthCallbackResult> => {
394
441
  try {
395
442
  setError(null);
@@ -398,6 +445,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
398
445
  const nextSession = await backend.exchangeOAuthSessionCode({
399
446
  authCode,
400
447
  redirectTo,
448
+ codeVerifier,
401
449
  nowSeconds: now,
402
450
  });
403
451
  if (!nextSession) {
@@ -478,7 +526,30 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
478
526
 
479
527
  const sendMagicLink = useCallback(
480
528
  async (email: string, redirectPath = urls.loginCallback) => {
529
+ const liveTauri = tauriRuntime || isLiveTauriRuntime();
481
530
  try {
531
+ if (shouldUseDesktopSignIn(config, liveTauri)) {
532
+ const scheme = normalizeDesktopScheme(config.auth?.desktopScheme);
533
+ if (!scheme) {
534
+ throw new Error(
535
+ 'auth.desktopScheme must be a lowercase custom scheme such as shellui-playground.',
536
+ );
537
+ }
538
+ setActiveDesktopScheme(scheme);
539
+ const prepared = await createAndStoreDesktopPkce(scheme);
540
+ try {
541
+ await backend.sendMagicLink(email, redirectPath, {
542
+ language: i18n.resolvedLanguage ?? i18n.language,
543
+ redirectTo: prepared.redirectTo,
544
+ codeChallenge: prepared.challenge,
545
+ });
546
+ } catch (sendError) {
547
+ clearDesktopPkce();
548
+ throw sendError;
549
+ }
550
+ void ensureDesktopDeepLinkListener({ replayLaunchUrl: false });
551
+ return;
552
+ }
482
553
  await backend.sendMagicLink(email, redirectPath, {
483
554
  language: i18n.resolvedLanguage ?? i18n.language,
484
555
  });
@@ -488,7 +559,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
488
559
  throw new Error(message);
489
560
  }
490
561
  },
491
- [backend, i18n],
562
+ [backend, config, i18n, tauriRuntime],
492
563
  );
493
564
 
494
565
  const syncUserPreferences = useCallback(
@@ -560,6 +631,33 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
560
631
  setErrorCode(null);
561
632
  }, [backend, bffAuthEnabled, session]);
562
633
 
634
+ useEffect(() => {
635
+ const liveTauri = tauriRuntime || isLiveTauriRuntime();
636
+ if (!shouldUseDesktopSignIn(config, liveTauri)) return;
637
+ const scheme = normalizeDesktopScheme(config.auth?.desktopScheme);
638
+ if (!scheme) return;
639
+ setActiveDesktopScheme(scheme);
640
+ let cancelled = false;
641
+ const unsubscribe = subscribeDesktopAuth((event) => {
642
+ if (cancelled) return;
643
+ if (event.type === 'error') {
644
+ setError(event.message);
645
+ setErrorCode(event.errorCode);
646
+ return;
647
+ }
648
+ void completeOAuthSessionCallback({
649
+ authCode: event.authCode,
650
+ redirectTo: event.redirectTo,
651
+ codeVerifier: event.codeVerifier,
652
+ });
653
+ });
654
+ void ensureDesktopDeepLinkListener({ replayLaunchUrl: true });
655
+ return () => {
656
+ cancelled = true;
657
+ unsubscribe();
658
+ };
659
+ }, [completeOAuthSessionCallback, config, tauriRuntime]);
660
+
563
661
  useEffect(() => {
564
662
  if (typeof window === 'undefined' || window.parent !== window) {
565
663
  return;
@@ -51,6 +51,28 @@ describe('shellui backend sendMagicLink', () => {
51
51
  });
52
52
  expect(body).not.toHaveProperty('email_redirect_to');
53
53
  expect(body).not.toHaveProperty('language');
54
+ expect(body).not.toHaveProperty('code_challenge');
55
+ expect(body).not.toHaveProperty('code_challenge_method');
56
+ });
57
+
58
+ test('desktop magic link sends the custom scheme and an S256 challenge', async () => {
59
+ fetchMock.mockResolvedValue(jsonResponse(200, { ok: true }));
60
+ const backend = createShellUIAuthBackend({
61
+ backendUrl: 'https://auth.example.com',
62
+ companyId: 7,
63
+ });
64
+
65
+ await backend.sendMagicLink('ada@acme.com', '/login/callback', {
66
+ redirectTo: 'shellui-playground://callback',
67
+ codeChallenge: 'a'.repeat(43),
68
+ });
69
+
70
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
71
+ const body = JSON.parse(init.body as string) as Record<string, unknown>;
72
+ expect(body.redirect_to).toBe('shellui-playground://callback');
73
+ expect(body.code_challenge).toBe('a'.repeat(43));
74
+ expect(body.code_challenge_method).toBe('S256');
75
+ expect(body).not.toHaveProperty('code_verifier');
54
76
  });
55
77
 
56
78
  test('sends the UI language so the email is localized', async () => {
@@ -97,6 +119,99 @@ describe('shellui backend sendMagicLink', () => {
97
119
  });
98
120
  });
99
121
 
122
+ describe('shellui backend OAuth session', () => {
123
+ const fetchMock = vi.fn();
124
+
125
+ beforeEach(() => {
126
+ vi.stubGlobal('fetch', fetchMock);
127
+ });
128
+
129
+ afterEach(() => {
130
+ fetchMock.mockReset();
131
+ vi.unstubAllGlobals();
132
+ });
133
+
134
+ test('web exchange posts auth_code and redirect_to only', async () => {
135
+ fetchMock.mockResolvedValue(
136
+ jsonResponse(200, {
137
+ access_token: 'header.payload.sig',
138
+ refresh_token: 'refresh-1',
139
+ expires_in: 3600,
140
+ token_type: 'bearer',
141
+ }),
142
+ );
143
+ const backend = createShellUIAuthBackend({ backendUrl: 'https://auth.example.com' });
144
+ await backend.exchangeOAuthSessionCode({
145
+ authCode: 'session-code',
146
+ redirectTo: 'https://app.example.com/login/callback',
147
+ nowSeconds: 1_700_000_000,
148
+ });
149
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
150
+ expect(url).toBe('https://auth.example.com/api/v1/oauth/session');
151
+ expect(JSON.parse(init.body as string)).toEqual({
152
+ auth_code: 'session-code',
153
+ redirect_to: 'https://app.example.com/login/callback',
154
+ });
155
+ });
156
+
157
+ test('desktop exchange adds code_verifier and nothing else', async () => {
158
+ fetchMock.mockResolvedValue(
159
+ jsonResponse(200, {
160
+ access_token: 'header.payload.sig',
161
+ refresh_token: 'refresh-1',
162
+ expires_in: 3600,
163
+ token_type: 'bearer',
164
+ }),
165
+ );
166
+ const backend = createShellUIAuthBackend({ backendUrl: 'https://auth.example.com' });
167
+ await backend.exchangeOAuthSessionCode({
168
+ authCode: 'session-code',
169
+ redirectTo: 'shellui-playground://callback',
170
+ codeVerifier: 'verifier-value',
171
+ nowSeconds: 1_700_000_000,
172
+ });
173
+ const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
174
+ expect(JSON.parse(init.body as string)).toEqual({
175
+ auth_code: 'session-code',
176
+ redirect_to: 'shellui-playground://callback',
177
+ code_verifier: 'verifier-value',
178
+ });
179
+ });
180
+ });
181
+
182
+ describe('shellui backend startOAuth', () => {
183
+ test('keeps the http redirect and does not send PKCE', () => {
184
+ const assign = vi.fn();
185
+ vi.stubGlobal('window', {
186
+ location: { origin: 'https://app.example.com', assign },
187
+ });
188
+ vi.stubGlobal('localStorage', {
189
+ getItem: () => null,
190
+ setItem: () => undefined,
191
+ });
192
+ const backend = createShellUIAuthBackend({
193
+ backendUrl: 'https://auth.example.com',
194
+ companyId: 7,
195
+ });
196
+
197
+ backend.startOAuth('github', '/login/callback', 4);
198
+
199
+ expect(assign).toHaveBeenCalledTimes(1);
200
+ const url = new URL(String(assign.mock.calls[0]?.[0]));
201
+ expect(`${url.origin}${url.pathname}`).toBe('https://auth.example.com/api/v1/authorize');
202
+ 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
+ );
206
+ expect(url.searchParams.get('company_id')).toBe('7');
207
+ 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);
210
+ expect(url.searchParams.has('code_verifier')).toBe(false);
211
+ vi.unstubAllGlobals();
212
+ });
213
+ });
214
+
100
215
  describe('shellui backend updateProfile', () => {
101
216
  const fetchMock = vi.fn();
102
217
  const session = { accessToken: 'access-1' } as AuthSession;
@@ -72,7 +72,7 @@ export const createShellUIAuthBackend = ({
72
72
  const hashParams = new URLSearchParams(locationHash.replace(/^#/, ''));
73
73
  return buildSessionFromParams(hashParams, nowSeconds);
74
74
  },
75
- exchangeOAuthSessionCode: async ({ authCode, redirectTo, nowSeconds }) => {
75
+ exchangeOAuthSessionCode: async ({ authCode, redirectTo, codeVerifier, nowSeconds }) => {
76
76
  if (!backendUrl) {
77
77
  throw new Error('Missing Shellui backend URL.');
78
78
  }
@@ -85,6 +85,7 @@ export const createShellUIAuthBackend = ({
85
85
  body: JSON.stringify({
86
86
  auth_code: authCode,
87
87
  redirect_to: redirectTo,
88
+ ...(codeVerifier ? { code_verifier: codeVerifier } : {}),
88
89
  }),
89
90
  });
90
91
  const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
@@ -296,10 +297,12 @@ export const createShellUIAuthBackend = ({
296
297
  if (!selectedCompanyId) {
297
298
  throw new Error('Missing company_id for magic link request.');
298
299
  }
299
- const redirectTo = `${window.location.origin}${normalizeRedirectPath(redirectPath)}`;
300
+ const redirectTo =
301
+ options?.redirectTo ?? `${window.location.origin}${normalizeRedirectPath(redirectPath)}`;
300
302
  const clientTz = getShellUILoginClientTimezone();
301
303
  const clientDeviceId = getShellUILoginDeviceId();
302
304
  const language = options?.language?.trim();
305
+ const codeChallenge = options?.codeChallenge?.trim();
303
306
  const response = await fetch(`${backendUrl}${MAGIC_LINK_REQUEST_ENDPOINT}`, {
304
307
  method: 'POST',
305
308
  headers: {
@@ -310,6 +313,9 @@ export const createShellUIAuthBackend = ({
310
313
  company_id: Number(selectedCompanyId),
311
314
  email,
312
315
  redirect_to: redirectTo,
316
+ ...(codeChallenge
317
+ ? { code_challenge: codeChallenge, code_challenge_method: 'S256' }
318
+ : {}),
313
319
  ...(clientTz ? { client_timezone: clientTz } : {}),
314
320
  ...(clientDeviceId ? { client_device_id: clientDeviceId } : {}),
315
321
  ...(language ? { language } : {}),
@@ -7,6 +7,8 @@ export interface AuthBackend {
7
7
  exchangeOAuthSessionCode: (params: {
8
8
  authCode: string;
9
9
  redirectTo: string;
10
+ /** PKCE verifier for a custom-scheme desktop redirect. Omit on the web flow. */
11
+ codeVerifier?: string;
10
12
  nowSeconds: number;
11
13
  }) => Promise<AuthSession | null>;
12
14
  exchangeOAuthCode: (params: {
@@ -43,7 +45,13 @@ export interface AuthBackend {
43
45
  sendMagicLink: (
44
46
  email: string,
45
47
  redirectPath: string,
46
- options?: { language?: string },
48
+ options?: {
49
+ language?: string;
50
+ /** Custom-scheme redirect for desktop sign-in. Omit to keep the web origin. */
51
+ redirectTo?: string;
52
+ /** S256 challenge for a desktop magic link. Omit on the web flow. */
53
+ codeChallenge?: string;
54
+ },
47
55
  ) => Promise<void>;
48
56
  syncUserPreferences: (session: AuthSession | null, preferences: UserPreferences) => Promise<void>;
49
57
  loadUserPreferences: (session: AuthSession | null) => Promise<UserPreferences | null>;
@@ -18,6 +18,7 @@ import {
18
18
  getPreferredBackendProvider,
19
19
  getProviderVisual,
20
20
  isAccessPendingErrorCode,
21
+ loginErrorMessageKey,
21
22
  normalizeNextPath,
22
23
  redirectToCliCallback,
23
24
  resolveLoginSettings,
@@ -158,7 +159,10 @@ export const LoginView = () => {
158
159
  const path = `${location.pathname}${qs ? `?${qs}` : ''}${location.hash}`;
159
160
  navigate(path, { replace: true });
160
161
  setOauthLoadingProvider(null);
161
- const baseMsg = rawErr.trim() || t('loginPage.signInCouldNotContinue');
162
+ const messageKey = loginErrorMessageKey(code);
163
+ const baseMsg = messageKey
164
+ ? t(messageKey)
165
+ : rawErr.trim() || t('loginPage.signInCouldNotContinue');
162
166
  const hint =
163
167
  code === 'redirect_not_allowed'
164
168
  ? t('loginPage.redirectNotAllowedHint', {
@@ -1,4 +1,5 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react';
2
+ import { useTranslation } from 'react-i18next';
2
3
  import { useLocation, useNavigate } from 'react-router';
3
4
  import urls from '../../../constants/urls';
4
5
  import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
@@ -9,6 +10,7 @@ import {
9
10
  hashHasOAuthTokens,
10
11
  inferAccessPendingErrorCode,
11
12
  isAccessPendingErrorCode,
13
+ loginErrorMessageKey,
12
14
  normalizeNextPath,
13
15
  redirectCliCallbackError,
14
16
  redirectToCliCallback,
@@ -85,6 +87,7 @@ const looksLikeUsedOAuthCode = (message: string | null | undefined) => {
85
87
  export const OAuthCallbackView = () => {
86
88
  const location = useLocation();
87
89
  const navigate = useNavigate();
90
+ const { t } = useTranslation();
88
91
  const {
89
92
  completeOAuthCallback,
90
93
  completeOAuthSessionCallback,
@@ -137,13 +140,15 @@ export const OAuthCallbackView = () => {
137
140
  const bounceError = params.get(SHELLUI_OAUTH_ERROR_PARAM);
138
141
  if (bounceError) {
139
142
  const bounceCode = params.get(SHELLUI_OAUTH_ERROR_CODE_PARAM) || 'oauth_error';
140
- if (redirectCliCallbackError(bounceError, bounceCode)) return;
143
+ const messageKey = loginErrorMessageKey(bounceCode);
144
+ const displayError = messageKey ? t(messageKey) : bounceError;
145
+ if (redirectCliCallbackError(displayError, bounceCode)) return;
141
146
  if (isAccessPendingErrorCode(bounceCode)) {
142
147
  setPendingAccess({ message: bounceError, code: bounceCode });
143
148
  setIsWorking(false);
144
149
  return;
145
150
  }
146
- setLocalError(bounceError);
151
+ setLocalError(displayError);
147
152
  setIsWorking(false);
148
153
  return;
149
154
  }
@@ -189,7 +194,10 @@ export const OAuthCallbackView = () => {
189
194
  return;
190
195
  }
191
196
 
192
- const message = result.error ?? 'Unable to complete OAuth login.';
197
+ const messageKey = loginErrorMessageKey(result.errorCode);
198
+ const message = messageKey
199
+ ? t(messageKey)
200
+ : (result.error ?? 'Unable to complete OAuth login.');
193
201
  if (redirectCliCallbackError(message, result.errorCode)) return;
194
202
  setLocalError(message);
195
203
  setIsWorking(false);
@@ -310,6 +318,7 @@ export const OAuthCallbackView = () => {
310
318
  location.search,
311
319
  navigate,
312
320
  nextPath,
321
+ t,
313
322
  ]);
314
323
 
315
324
  const backToLogin = () => {
@@ -25,6 +25,7 @@ export interface AuthContextValue {
25
25
  completeOAuthSessionCallback: (params: {
26
26
  authCode: string;
27
27
  redirectTo: string;
28
+ codeVerifier?: string;
28
29
  }) => Promise<OAuthCallbackResult>;
29
30
  completeOAuthCallback: (params: {
30
31
  provider: string;