@shellui/core 0.3.1 → 0.4.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 (59) hide show
  1. package/package.json +2 -2
  2. package/src/app.tsx +11 -1
  3. package/src/components/ui/dialog.tsx +26 -6
  4. package/src/components/ui/sonner.tsx +9 -5
  5. package/src/features/admin/AdminView.tsx +1 -20
  6. package/src/features/auth/AuthProvider.tsx +68 -13
  7. package/src/features/auth/backends/shellui.ts +8 -1
  8. package/src/features/auth/components/AccessPendingView.tsx +112 -0
  9. package/src/features/auth/components/LoginView.tsx +17 -0
  10. package/src/features/auth/components/OAuthCallbackView.tsx +211 -48
  11. package/src/features/auth/hooks/useAuth.tsx +8 -1
  12. package/src/features/auth/utils/authRequestError.spec.ts +52 -0
  13. package/src/features/auth/utils/authRequestError.ts +45 -0
  14. package/src/features/auth/utils/index.ts +7 -0
  15. package/src/features/auth/utils/isTokenAutoRefreshDisabled.spec.ts +71 -0
  16. package/src/features/auth/utils/isTokenAutoRefreshDisabled.ts +18 -0
  17. package/src/features/config/types.ts +46 -0
  18. package/src/features/layouts/AppLayout.tsx +3 -3
  19. package/src/features/layouts/OverlayShell.tsx +10 -6
  20. package/src/features/modal/ModalContext.spec.ts +77 -0
  21. package/src/features/modal/ModalContext.tsx +12 -50
  22. package/src/features/modal/validateAndNormalizeUrl.ts +96 -0
  23. package/src/features/settings/SettingsIcons.tsx +35 -0
  24. package/src/features/settings/SettingsProvider.tsx +69 -4
  25. package/src/features/settings/SettingsRoutes.tsx +14 -6
  26. package/src/features/settings/SettingsView.tsx +11 -5
  27. package/src/features/settings/components/Advanced.tsx +117 -44
  28. package/src/features/settings/components/Develop.tsx +38 -0
  29. package/src/features/settings/components/Storage.tsx +138 -0
  30. package/src/features/settings/components/develop/StoragePickerTestButtons.tsx +148 -0
  31. package/src/features/settings/components/develop/UploadToastTestButton.tsx +29 -0
  32. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +54 -0
  33. package/src/features/settings/utils/buildSettingsForPropagation.ts +34 -0
  34. package/src/features/settings/utils/toSettingsUser.spec.ts +4 -0
  35. package/src/features/settings/utils/toSettingsUser.ts +2 -0
  36. package/src/features/storage/StorageBridge.tsx +50 -0
  37. package/src/features/storage/StoragePickerContext.tsx +214 -0
  38. package/src/features/storage/api.spec.ts +303 -0
  39. package/src/features/storage/api.ts +414 -0
  40. package/src/features/storage/handleRequest.spec.ts +88 -0
  41. package/src/features/storage/handleRequest.ts +53 -0
  42. package/src/features/storage/quota.spec.ts +151 -0
  43. package/src/features/storage/quota.ts +104 -0
  44. package/src/features/storage/uploads/UploadToastCard.tsx +442 -0
  45. package/src/features/storage/uploads/UploadToaster.tsx +41 -0
  46. package/src/features/storage/uploads/handleTrackedUpload.spec.ts +170 -0
  47. package/src/features/storage/uploads/handleTrackedUpload.ts +97 -0
  48. package/src/features/storage/uploads/types.ts +24 -0
  49. package/src/features/storage/uploads/uploadQueue.spec.ts +118 -0
  50. package/src/features/storage/uploads/uploadQueue.ts +349 -0
  51. package/src/features/storage/uploads/useUploadQueue.ts +30 -0
  52. package/src/i18n/translations/en/common.json +33 -0
  53. package/src/i18n/translations/en/settings.json +47 -4
  54. package/src/i18n/translations/fr/common.json +33 -0
  55. package/src/i18n/translations/fr/settings.json +47 -4
  56. package/src/index.css +2 -1
  57. package/src/index.ts +2 -0
  58. package/src/lib/z-index.ts +9 -3
  59. package/src/service-worker/register.ts +4 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shellui/core",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "ShellUI Core - Core React application runtime",
5
5
  "main": "src/index.ts",
6
6
  "type": "module",
@@ -62,7 +62,7 @@
62
62
  "workbox-routing": "^7.4.0",
63
63
  "workbox-strategies": "^7.4.0",
64
64
  "workbox-window": "^7.4.0",
65
- "@shellui/sdk": "0.3.1"
65
+ "@shellui/sdk": "0.4.1"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "react": "^18.0.0 || ^19.0.0",
package/src/app.tsx CHANGED
@@ -10,6 +10,10 @@ import { I18nProvider } from './i18n/I18nProvider';
10
10
  import { DialogProvider } from './features/alertDialog/DialogContext';
11
11
  import { CookieConsentModal } from './features/cookieConsent/CookieConsentModal';
12
12
  import { AuthProvider } from './features/auth/AuthProvider';
13
+ import { StorageBridge } from './features/storage/StorageBridge';
14
+ import { SonnerProvider } from './features/sonner/SonnerContext';
15
+ import { Toaster } from './components/ui/sonner';
16
+ import { UploadToaster } from './features/storage/uploads/UploadToaster';
13
17
  import './features/sentry/initSentry';
14
18
  import './i18n/config'; // Initialize i18n
15
19
  import './index.css';
@@ -123,11 +127,17 @@ const App = () => {
123
127
  return (
124
128
  <ConfigProvider>
125
129
  <AuthProvider>
130
+ <StorageBridge />
126
131
  <SettingsProvider>
127
132
  <ThemeProvider>
128
133
  <I18nProvider>
129
134
  <DialogProvider>
130
- <AppContent />
135
+ <SonnerProvider>
136
+ {/* Toaster + upload progress live at ShellUI root so they survive navigation. */}
137
+ <Toaster />
138
+ <UploadToaster />
139
+ <AppContent />
140
+ </SonnerProvider>
131
141
  </DialogProvider>
132
142
  </I18nProvider>
133
143
  </ThemeProvider>
@@ -22,12 +22,12 @@ const DialogClose = DialogPrimitive.Close;
22
22
  const DialogOverlay = forwardRef<
23
23
  ElementRef<typeof DialogPrimitive.Overlay>,
24
24
  ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
25
- >(({ className, ...props }, ref) => (
25
+ >(({ className, style, ...props }, ref) => (
26
26
  <DialogPrimitive.Overlay
27
27
  ref={ref}
28
28
  data-dialog-overlay
29
29
  className={cn('fixed inset-0 bg-[hsl(var(--background)/0.8)] backdrop-blur-[1px]', className)}
30
- style={{ zIndex: Z_INDEX.MODAL_OVERLAY }}
30
+ style={{ zIndex: Z_INDEX.MODAL_OVERLAY, ...style }}
31
31
  {...props}
32
32
  />
33
33
  ));
@@ -36,10 +36,24 @@ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
36
36
  interface DialogContentProps extends ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
37
37
  /** When true, the default close (X) button is not rendered. Escape and overlay still close. */
38
38
  hideCloseButton?: boolean;
39
+ overlayZIndex?: number;
40
+ contentZIndex?: number;
39
41
  }
40
42
 
41
43
  const DialogContent = forwardRef<ElementRef<typeof DialogPrimitive.Content>, DialogContentProps>(
42
- ({ className, children, onPointerDownOutside, hideCloseButton, ...props }, ref) => {
44
+ (
45
+ {
46
+ className,
47
+ children,
48
+ onPointerDownOutside,
49
+ hideCloseButton,
50
+ overlayZIndex,
51
+ contentZIndex,
52
+ style,
53
+ ...props
54
+ },
55
+ ref,
56
+ ) => {
43
57
  const hasContent = Children.count(children) > 2;
44
58
 
45
59
  const handlePointerDownOutside = useCallback(
@@ -49,7 +63,7 @@ const DialogContent = forwardRef<ElementRef<typeof DialogPrimitive.Content>, Dia
49
63
  >[0],
50
64
  ) => {
51
65
  const target = event?.target as Element | null;
52
- if (target?.closest?.('[data-sonner-toaster]')) {
66
+ if (target?.closest?.('[data-sonner-toaster], [data-upload-toast]')) {
53
67
  event.preventDefault();
54
68
  }
55
69
  onPointerDownOutside?.(event);
@@ -59,7 +73,9 @@ const DialogContent = forwardRef<ElementRef<typeof DialogPrimitive.Content>, Dia
59
73
 
60
74
  return (
61
75
  <DialogPortal>
62
- <DialogOverlay />
76
+ <DialogOverlay
77
+ style={overlayZIndex !== undefined ? { zIndex: overlayZIndex } : undefined}
78
+ />
63
79
  <DialogPrimitive.Content
64
80
  ref={ref}
65
81
  data-dialog-content
@@ -69,7 +85,11 @@ const DialogContent = forwardRef<ElementRef<typeof DialogPrimitive.Content>, Dia
69
85
  'data-[has-content=false]:gap-0 data-[has-content=false]:[&>[data-dialog-header]]:border-b-0 data-[has-content=false]:[&>[data-dialog-header]]:pb-0',
70
86
  className,
71
87
  )}
72
- style={{ backgroundColor: 'hsl(var(--background))', zIndex: Z_INDEX.MODAL_CONTENT }}
88
+ style={{
89
+ backgroundColor: 'hsl(var(--background))',
90
+ zIndex: contentZIndex ?? Z_INDEX.MODAL_CONTENT,
91
+ ...style,
92
+ }}
73
93
  onPointerDownOutside={handlePointerDownOutside}
74
94
  {...props}
75
95
  >
@@ -5,7 +5,8 @@ import { Z_INDEX } from '../../lib/z-index';
5
5
 
6
6
  type ToasterProps = ComponentProps<typeof Sonner>;
7
7
 
8
- const TOAST_BUTTON_SELECTOR = '[data-close-button], [data-cancel], [data-action]';
8
+ const TOAST_BUTTON_SELECTOR =
9
+ '[data-close-button], [data-cancel], [data-action], [data-upload-action]';
9
10
 
10
11
  /**
11
12
  * Ensures toast action, cancel, and close buttons respond to pointer/touch on iPad
@@ -21,13 +22,16 @@ function useToastButtonPointerFix() {
21
22
  // When a modal is open (e.g. Radix), body has pointer-events: none so the toaster
22
23
  // may never receive the event on iPad. Use document capture + elementFromPoint so we
23
24
  // still detect touches over the toaster and trigger the button.
24
- const toaster = document.querySelector('[data-sonner-toaster]');
25
- if (!toaster) return;
25
+ const sonnerToaster = document.querySelector('[data-sonner-toaster]');
26
+ const uploadToast = document.querySelector('[data-upload-toast]');
27
+ if (!sonnerToaster && !uploadToast) return;
26
28
  const elementUnderPoint = document.elementFromPoint(ev.clientX, ev.clientY);
27
29
  if (!elementUnderPoint?.isConnected) return;
28
30
  const button = (elementUnderPoint as HTMLElement).closest?.(TOAST_BUTTON_SELECTOR);
29
- if (!button || !toaster.contains(button) || button.getAttribute('data-disabled') === 'true')
30
- return;
31
+ const inToastLayer =
32
+ Boolean(button && sonnerToaster?.contains(button)) ||
33
+ Boolean(button && uploadToast?.contains(button));
34
+ if (!button || !inToastLayer || button.getAttribute('data-disabled') === 'true') return;
31
35
  ev.preventDefault();
32
36
  ev.stopImmediatePropagation();
33
37
  const clickEvent = new MouseEvent('click', {
@@ -1,5 +1,4 @@
1
1
  import { useEffect, useMemo, useRef } from 'react';
2
- import { useTranslation } from 'react-i18next';
3
2
  import { Outlet, Route, Routes, useLocation, useNavigate } from 'react-router';
4
3
  import { Button } from '../../components/ui/button';
5
4
  import { ContentView } from '../../components/ContentView';
@@ -10,7 +9,7 @@ import type { NavigationItem } from '../config/types';
10
9
  import { AppLayout } from '../layouts/AppLayout';
11
10
  import { AdminForbiddenAccess } from './components/AdminForbiddenAccess';
12
11
  import { getAdminContentUrl, getAdminPath } from './config';
13
- import { buildAdminIframeSrc, getDjangoAdminHref } from './utils';
12
+ import { buildAdminIframeSrc } from './utils';
14
13
 
15
14
  const AdminAccessGuard = ({ allow }: { allow: boolean }) => {
16
15
  if (!allow) {
@@ -20,14 +19,11 @@ const AdminAccessGuard = ({ allow }: { allow: boolean }) => {
20
19
  };
21
20
 
22
21
  export const AdminView = () => {
23
- const { t } = useTranslation('common');
24
22
  const navigate = useNavigate();
25
23
  const location = useLocation();
26
24
  const { config } = useConfig();
27
25
  const { user } = useAuth();
28
- const isStaff = Boolean(user?.isStaff);
29
26
  const canOpenAdminPanel = Boolean(user?.isStaff || user?.isCompanyOwner);
30
- const djangoAdminHref = useMemo(() => getDjangoAdminHref(config), [config]);
31
27
  const adminPath = getAdminPath(config);
32
28
  const baseAdminContentUrl = getAdminContentUrl(config);
33
29
  const initialAdminContentUrlRef = useRef<string | null>(null);
@@ -86,21 +82,6 @@ export const AdminView = () => {
86
82
  Back to home
87
83
  </Button>
88
84
  <div className="flex items-center gap-2">
89
- {isStaff && djangoAdminHref ? (
90
- <Button
91
- variant="outline"
92
- size="sm"
93
- asChild
94
- >
95
- <a
96
- href={djangoAdminHref}
97
- target="_blank"
98
- rel="noopener noreferrer"
99
- >
100
- {t('adminShell.djangoAdmin')}
101
- </a>
102
- </Button>
103
- ) : null}
104
85
  <LoginButton
105
86
  variant="appbar"
106
87
  logoutOnly
@@ -3,13 +3,17 @@ import { getLogger, shellui, type Settings } from '@shellui/sdk';
3
3
  import urls from '../../constants/urls';
4
4
  import { useConfig } from '../config/useConfig';
5
5
  import { createAuthBackend } from './backends';
6
- import { AuthContext, type AuthContextValue } from './hooks/useAuth';
6
+ import { AuthContext, type AuthContextValue, type OAuthCallbackResult } from './hooks/useAuth';
7
7
  import type { AuthEvent, AuthSession, AuthUser, UserPreferences } from './types';
8
8
  import {
9
+ AuthRequestError,
9
10
  clearStoredAuthSession,
10
11
  getAccessTokenFromSdkSettings,
12
+ getAuthRequestErrorCode,
11
13
  getUserFromSdkSettings,
14
+ inferAccessPendingErrorCode,
12
15
  isSessionExpired,
16
+ isTokenAutoRefreshDisabled,
13
17
  persistAuthSession,
14
18
  readStoredAuthSession,
15
19
  toAuthSessionFromSettingsUser,
@@ -40,6 +44,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
40
44
  const [session, setSession] = useState<AuthSession | null>(null);
41
45
  const [isLoading, setIsLoading] = useState(true);
42
46
  const [error, setError] = useState<string | null>(null);
47
+ const [errorCode, setErrorCode] = useState<string | null>(null);
43
48
  const [authEvent, setAuthEvent] = useState<AuthEvent>(null);
44
49
  const sessionRef = useRef<AuthSession | null>(null);
45
50
  sessionRef.current = session;
@@ -51,6 +56,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
51
56
  const initializeSession = async () => {
52
57
  setIsLoading(true);
53
58
  setError(null);
59
+ setErrorCode(null);
54
60
 
55
61
  if (typeof window === 'undefined') {
56
62
  setIsLoading(false);
@@ -104,6 +110,18 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
104
110
  return;
105
111
  }
106
112
 
113
+ // Keep the expired session so apps can exercise 401 / re-auth flows locally.
114
+ if (isTokenAutoRefreshDisabled()) {
115
+ logger.info(
116
+ 'Skipped session restore refresh because Develop → Disable token auto-refresh is on',
117
+ );
118
+ if (!cancelled) {
119
+ setSession(stored);
120
+ setIsLoading(false);
121
+ }
122
+ return;
123
+ }
124
+
107
125
  try {
108
126
  const restored = await backend.restoreSession(stored, now);
109
127
  if (!restored) {
@@ -144,6 +162,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
144
162
  }
145
163
 
146
164
  let cancelled = false;
165
+ let skippedRefreshLogged = false;
147
166
 
148
167
  const runRefresh = async () => {
149
168
  if (cancelled) return;
@@ -156,6 +175,18 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
156
175
  return;
157
176
  }
158
177
 
178
+ // Re-read when refresh is due so Develop → disableTokenAutoRefresh takes effect without remount.
179
+ if (isTokenAutoRefreshDisabled()) {
180
+ if (!skippedRefreshLogged) {
181
+ skippedRefreshLogged = true;
182
+ logger.info('Skipped token refresh because Develop → Disable token auto-refresh is on', {
183
+ expiresAt: current.expiresAt,
184
+ secondsLeft,
185
+ });
186
+ }
187
+ return;
188
+ }
189
+
159
190
  refreshInFlightRef.current = true;
160
191
  try {
161
192
  const next = await backend.refreshAuthSession(current, now);
@@ -182,8 +213,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
182
213
 
183
214
  const maybeRefreshOnResume = () => {
184
215
  if (cancelled || document.visibilityState !== 'visible') return;
185
- const current = sessionRef.current;
186
- if (!current?.refreshToken || !isSessionExpired(current)) return;
216
+ // Use the same proactive leeway as the timer (do not wait until already expired).
187
217
  void runRefresh();
188
218
  };
189
219
 
@@ -214,14 +244,15 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
214
244
  );
215
245
  };
216
246
 
247
+ // Parent shell pushes rotated JWTs via `SHELLUI_SETTINGS` (and sometimes UPDATED).
248
+ const cleanupSettings = shellui.addMessageListener('SHELLUI_SETTINGS', syncSessionFromSettings);
217
249
  const cleanupSettingsUpdated = shellui.addMessageListener(
218
250
  'SHELLUI_SETTINGS_UPDATED',
219
- (message) => {
220
- syncSessionFromSettings(message);
221
- },
251
+ syncSessionFromSettings,
222
252
  );
223
253
 
224
254
  return () => {
255
+ cleanupSettings();
225
256
  cleanupSettingsUpdated();
226
257
  };
227
258
  }, []);
@@ -230,10 +261,12 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
230
261
  (provider: string, redirectPath = urls.login, oauthClientId?: number) => {
231
262
  try {
232
263
  setError(null);
264
+ setErrorCode(null);
233
265
  backend.startOAuth(provider, redirectPath, oauthClientId);
234
266
  return true;
235
267
  } catch (err) {
236
268
  setError(err instanceof Error ? err.message : 'Unable to start OAuth login.');
269
+ setErrorCode(err instanceof AuthRequestError ? err.code : null);
237
270
  return false;
238
271
  }
239
272
  },
@@ -251,9 +284,10 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
251
284
  code: string;
252
285
  redirectUri: string;
253
286
  oauthClientId?: number;
254
- }) => {
287
+ }): Promise<OAuthCallbackResult> => {
255
288
  try {
256
289
  setError(null);
290
+ setErrorCode(null);
257
291
  const now = Math.floor(Date.now() / 1000);
258
292
  const nextSession = await backend.exchangeOAuthCode({
259
293
  provider,
@@ -263,16 +297,24 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
263
297
  nowSeconds: now,
264
298
  });
265
299
  if (!nextSession) {
266
- setError('Unable to complete OAuth login.');
267
- return false;
300
+ const message = 'Unable to complete OAuth login.';
301
+ setError(message);
302
+ setErrorCode(null);
303
+ return { ok: false, error: message, errorCode: null };
268
304
  }
269
305
  persistAuthSession(nextSession);
270
306
  setSession(nextSession);
271
307
  setAuthEvent('oauth_callback');
272
- return true;
308
+ return { ok: true };
273
309
  } catch (err) {
274
- setError(err instanceof Error ? err.message : 'Unable to complete OAuth login.');
275
- return false;
310
+ const message = err instanceof Error ? err.message : 'Unable to complete OAuth login.';
311
+ const oauthErrorCode =
312
+ getAuthRequestErrorCode(err) ??
313
+ inferAccessPendingErrorCode(message) ??
314
+ (err instanceof AuthRequestError ? err.code : null);
315
+ setError(message);
316
+ setErrorCode(oauthErrorCode);
317
+ return { ok: false, error: message, errorCode: oauthErrorCode };
276
318
  }
277
319
  },
278
320
  [backend],
@@ -281,9 +323,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
281
323
  const startWeb3Ethereum = useCallback(async () => {
282
324
  try {
283
325
  setError(null);
326
+ setErrorCode(null);
284
327
  const nextSession = await backend.startWeb3Ethereum();
285
328
  if (!nextSession) {
286
329
  setError('Unable to complete Ethereum wallet login.');
330
+ setErrorCode(null);
287
331
  return false;
288
332
  }
289
333
  persistAuthSession(nextSession);
@@ -291,6 +335,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
291
335
  return true;
292
336
  } catch (err) {
293
337
  setError(err instanceof Error ? err.message : 'Unable to start Ethereum wallet login.');
338
+ setErrorCode(err instanceof AuthRequestError ? err.code : null);
294
339
  return false;
295
340
  }
296
341
  }, [backend]);
@@ -316,7 +361,14 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
316
361
  const now = Math.floor(Date.now() / 1000);
317
362
  let nextSession: AuthSession | null = null;
318
363
  try {
319
- nextSession = session ? await backend.refreshAuthSession(session, now) : null;
364
+ if (session && isTokenAutoRefreshDisabled()) {
365
+ logger.info(
366
+ 'Skipped token refresh after preferences sync because Develop → Disable token auto-refresh is on',
367
+ );
368
+ nextSession = null;
369
+ } else {
370
+ nextSession = session ? await backend.refreshAuthSession(session, now) : null;
371
+ }
320
372
  } catch (refreshErr) {
321
373
  logger.error('Failed to refresh auth session after syncing preferences', { refreshErr });
322
374
  }
@@ -358,6 +410,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
358
410
  setSession(null);
359
411
  setAuthEvent(null);
360
412
  setError(null);
413
+ setErrorCode(null);
361
414
  }, [backend, session]);
362
415
 
363
416
  useEffect(() => {
@@ -431,6 +484,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
431
484
  isAuthenticated: session !== null && !isSessionExpired(session),
432
485
  isLoading,
433
486
  error,
487
+ errorCode,
434
488
  authEvent,
435
489
  clearAuthEvent,
436
490
  completeOAuthCallback,
@@ -447,6 +501,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
447
501
  user,
448
502
  isLoading,
449
503
  error,
504
+ errorCode,
450
505
  authEvent,
451
506
  clearAuthEvent,
452
507
  completeOAuthCallback,
@@ -6,6 +6,7 @@ import {
6
6
  normalizeAuthSettings,
7
7
  normalizeRedirectPath,
8
8
  } from '../utils';
9
+ import { AuthRequestError } from '../utils/authRequestError';
9
10
  import { getShellUILoginCompanyId } from '../utils/clientLoginContext';
10
11
  import type { AuthSession, UserPreferences } from '../types';
11
12
  import type { AuthBackend } from './types';
@@ -100,7 +101,13 @@ export const createShellUIAuthBackend = ({
100
101
  const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
101
102
  if (!response.ok) {
102
103
  const err = payload?.error ?? payload?.detail;
103
- throw new Error(typeof err === 'string' && err.trim() ? err : `HTTP ${response.status}`);
104
+ const message = typeof err === 'string' && err.trim() ? err : `HTTP ${response.status}`;
105
+ let errorCode = typeof payload?.error_code === 'string' ? payload.error_code.trim() : null;
106
+ // Exchange uses 403 only for company join denial; default the code if omitted.
107
+ if (!errorCode && response.status === 403) {
108
+ errorCode = 'access_pending';
109
+ }
110
+ throw new AuthRequestError(message, errorCode);
104
111
  }
105
112
  const refreshParams = new URLSearchParams();
106
113
  if (typeof payload?.access_token === 'string')
@@ -0,0 +1,112 @@
1
+ import { Button } from '../../../components/ui/button';
2
+ import { cn } from '../../../lib/utils';
3
+
4
+ type Props = {
5
+ message?: string | null;
6
+ code?: string | null;
7
+ onBackToLogin: () => void;
8
+ };
9
+
10
+ type AccessState = 'pending' | 'denied';
11
+
12
+ function resolveState(code: string | null | undefined): AccessState {
13
+ return code === 'access_denied' ? 'denied' : 'pending';
14
+ }
15
+
16
+ /**
17
+ * Shown when OAuth identity succeeded but company policy blocks tokens.
18
+ * Intentionally not framed as a technical failure.
19
+ */
20
+ export const AccessPendingView = ({ message, code, onBackToLogin }: Props) => {
21
+ const state = resolveState(code);
22
+ const isDenied = state === 'denied';
23
+
24
+ const statusLabel = isDenied ? 'Organization policy' : 'Pending approval';
25
+ const title = isDenied
26
+ ? 'Access is not available for your account'
27
+ : 'Your account is awaiting approval';
28
+ const lead = isDenied
29
+ ? 'Your sign-in was verified, but this organization only admits users from approved email domains. Your domain is not on that list.'
30
+ : 'Your sign-in was verified. This organization requires an administrator to enable new accounts before you can continue.';
31
+ const nextSteps = isDenied
32
+ ? 'An administrator has been notified. If you believe you should have access, contact your organization admin — they can enable your membership.'
33
+ : 'An administrator has been notified and will review your request. You will receive an email when access is enabled.';
34
+
35
+ const backendDetail = message?.trim() || null;
36
+ const detailLower = backendDetail?.toLowerCase() ?? '';
37
+ const showBackendDetail =
38
+ Boolean(backendDetail) &&
39
+ !detailLower.includes('waiting for an administrator') &&
40
+ !detailLower.includes('email domain is not authorized');
41
+
42
+ return (
43
+ <main className="flex min-h-full items-center justify-center bg-background px-6 py-12">
44
+ <div className="w-full max-w-xl animate-in fade-in-0 slide-in-from-bottom-3 duration-500">
45
+ <section
46
+ className="border border-border bg-card"
47
+ aria-labelledby="access-status-title"
48
+ >
49
+ <header className="border-b border-border px-8 py-6">
50
+ <div className="flex flex-wrap items-center gap-3">
51
+ <span
52
+ className={cn(
53
+ 'inline-flex items-center gap-2 border px-2.5 py-1 font-mono text-[10px] font-medium uppercase tracking-[0.14em]',
54
+ isDenied
55
+ ? 'border-foreground/25 bg-muted text-foreground'
56
+ : 'border-foreground/20 bg-background text-foreground',
57
+ )}
58
+ >
59
+ <span
60
+ className={cn(
61
+ 'size-1.5 shrink-0 rounded-full',
62
+ isDenied ? 'bg-foreground/70' : 'bg-foreground',
63
+ )}
64
+ aria-hidden
65
+ />
66
+ {statusLabel}
67
+ </span>
68
+ <span className="font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">
69
+ {isDenied ? 'Ref. access_denied' : 'Ref. access_pending'}
70
+ </span>
71
+ </div>
72
+ <h1
73
+ id="access-status-title"
74
+ className="mt-5 text-2xl font-semibold tracking-tight text-foreground md:text-[1.75rem]"
75
+ >
76
+ {title}
77
+ </h1>
78
+ </header>
79
+
80
+ <div className="space-y-5 px-8 py-6">
81
+ <p className="text-[15px] leading-relaxed text-foreground/90">{lead}</p>
82
+
83
+ <div className="border border-border bg-muted/30 px-4 py-3">
84
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-muted-foreground">
85
+ What happens next
86
+ </p>
87
+ <p className="mt-2 text-sm leading-relaxed text-foreground/85">{nextSteps}</p>
88
+ </div>
89
+
90
+ {showBackendDetail ? (
91
+ <p className="font-mono text-[11px] leading-relaxed text-muted-foreground">
92
+ Detail: {backendDetail}
93
+ </p>
94
+ ) : null}
95
+ </div>
96
+
97
+ <footer className="flex flex-wrap items-center justify-between gap-3 border-t border-border px-8 py-5">
98
+ <p className="text-xs text-muted-foreground">You can close this page safely.</p>
99
+ <Button
100
+ type="button"
101
+ variant="outline"
102
+ size="sm"
103
+ onClick={onBackToLogin}
104
+ >
105
+ Back to login
106
+ </Button>
107
+ </footer>
108
+ </section>
109
+ </div>
110
+ </main>
111
+ );
112
+ };
@@ -14,9 +14,11 @@ import {
14
14
  getOAuthProviderCandidates,
15
15
  getPreferredBackendProvider,
16
16
  getProviderVisual,
17
+ isAccessPendingErrorCode,
17
18
  isLoginMethod,
18
19
  normalizeNextPath,
19
20
  } from '../utils';
21
+ import { AccessPendingView } from './AccessPendingView';
20
22
 
21
23
  const LAST_USED_LOGIN_STORAGE_KEY = 'shellui.auth.last_used_login';
22
24
 
@@ -113,6 +115,7 @@ export const LoginView = () => {
113
115
  const [magicLinkError, setMagicLinkError] = useState<string | null>(null);
114
116
  const [methodError, setMethodError] = useState<string | null>(null);
115
117
  const [oauthBounceError, setOauthBounceError] = useState<string | null>(null);
118
+ const [oauthBounceCode, setOauthBounceCode] = useState<string | null>(null);
116
119
  const [lastUsedLogin, setLastUsedLogin] = useState<LastUsedLogin | null>(
117
120
  readLastUsedLoginFromStorage,
118
121
  );
@@ -147,6 +150,7 @@ export const LoginView = () => {
147
150
  ? ` Add this origin in shellui-auth (Django admin or shellui-admin → Company → Login redirect URLs), for example: ${typeof window !== 'undefined' ? `${window.location.origin}/login` : '/login'}.`
148
151
  : '';
149
152
  setOauthBounceError(`${baseMsg}${hint}`);
153
+ setOauthBounceCode(code);
150
154
  }, [location.hash, location.pathname, location.search, navigate]);
151
155
 
152
156
  useEffect(() => {
@@ -385,6 +389,19 @@ export const LoginView = () => {
385
389
  return null;
386
390
  }
387
391
 
392
+ if (isAccessPendingErrorCode(oauthBounceCode)) {
393
+ return (
394
+ <AccessPendingView
395
+ message={oauthBounceError}
396
+ code={oauthBounceCode}
397
+ onBackToLogin={() => {
398
+ setOauthBounceError(null);
399
+ setOauthBounceCode(null);
400
+ }}
401
+ />
402
+ );
403
+ }
404
+
388
405
  return (
389
406
  <main className="flex min-h-full w-full bg-background">
390
407
  {!isIframeView && (