@shellui/core 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +2 -2
  2. package/src/app.tsx +31 -3
  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 +5 -49
  6. package/src/features/admin/config.ts +15 -0
  7. package/src/features/admin/index.ts +4 -0
  8. package/src/features/admin/routes.tsx +14 -0
  9. package/src/features/admin/utils.ts +79 -0
  10. package/src/features/auth/AuthProvider.tsx +68 -13
  11. package/src/features/auth/backends/shellui.ts +8 -1
  12. package/src/features/auth/components/AccessPendingView.tsx +112 -0
  13. package/src/features/auth/components/LoginButton.tsx +5 -10
  14. package/src/features/auth/components/LoginView.tsx +20 -2
  15. package/src/features/auth/components/OAuthCallbackView.tsx +211 -50
  16. package/src/features/auth/hooks/useAuth.tsx +8 -1
  17. package/src/features/auth/utils/authRequestError.spec.ts +52 -0
  18. package/src/features/auth/utils/authRequestError.ts +45 -0
  19. package/src/features/auth/utils/buildAuthUrlWithNext.spec.ts +18 -0
  20. package/src/features/auth/utils/buildAuthUrlWithNext.ts +12 -0
  21. package/src/features/auth/utils/index.ts +8 -0
  22. package/src/features/auth/utils/isTokenAutoRefreshDisabled.spec.ts +71 -0
  23. package/src/features/auth/utils/isTokenAutoRefreshDisabled.ts +18 -0
  24. package/src/features/config/ConfigProvider.ts +1 -1
  25. package/src/features/config/types.ts +46 -5
  26. package/src/features/layouts/AppLayout.tsx +3 -3
  27. package/src/features/layouts/OverlayShell.tsx +17 -28
  28. package/src/features/layouts/resolveSdkNavigatePath.spec.ts +55 -0
  29. package/src/features/layouts/resolveSdkNavigatePath.ts +68 -0
  30. package/src/features/settings/SettingsIcons.tsx +35 -0
  31. package/src/features/settings/SettingsProvider.tsx +79 -10
  32. package/src/features/settings/SettingsRoutes.tsx +14 -6
  33. package/src/features/settings/SettingsView.tsx +11 -5
  34. package/src/features/settings/components/Advanced.tsx +117 -44
  35. package/src/features/settings/components/Develop.tsx +38 -0
  36. package/src/features/settings/components/ServiceWorker.tsx +52 -25
  37. package/src/features/settings/components/Storage.tsx +138 -0
  38. package/src/features/settings/components/UpdateApp.tsx +1 -1
  39. package/src/features/settings/components/develop/StoragePickerTestButtons.tsx +148 -0
  40. package/src/features/settings/components/develop/UploadToastTestButton.tsx +29 -0
  41. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +55 -1
  42. package/src/features/settings/utils/buildSettingsForPropagation.ts +34 -0
  43. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +1 -1
  44. package/src/features/settings/utils/toSettingsUser.spec.ts +4 -0
  45. package/src/features/settings/utils/toSettingsUser.ts +2 -0
  46. package/src/features/sonner/SonnerContext.tsx +44 -60
  47. package/src/features/storage/StorageBridge.tsx +50 -0
  48. package/src/features/storage/StoragePickerContext.tsx +214 -0
  49. package/src/features/storage/api.spec.ts +303 -0
  50. package/src/features/storage/api.ts +414 -0
  51. package/src/features/storage/handleRequest.spec.ts +88 -0
  52. package/src/features/storage/handleRequest.ts +53 -0
  53. package/src/features/storage/quota.spec.ts +151 -0
  54. package/src/features/storage/quota.ts +104 -0
  55. package/src/features/storage/uploads/UploadToastCard.tsx +442 -0
  56. package/src/features/storage/uploads/UploadToaster.tsx +41 -0
  57. package/src/features/storage/uploads/handleTrackedUpload.spec.ts +170 -0
  58. package/src/features/storage/uploads/handleTrackedUpload.ts +97 -0
  59. package/src/features/storage/uploads/types.ts +24 -0
  60. package/src/features/storage/uploads/uploadQueue.spec.ts +118 -0
  61. package/src/features/storage/uploads/uploadQueue.ts +349 -0
  62. package/src/features/storage/uploads/useUploadQueue.ts +30 -0
  63. package/src/i18n/translations/en/common.json +33 -0
  64. package/src/i18n/translations/en/settings.json +56 -4
  65. package/src/i18n/translations/fr/common.json +33 -0
  66. package/src/i18n/translations/fr/settings.json +56 -4
  67. package/src/index.css +2 -1
  68. package/src/index.ts +2 -0
  69. package/src/lib/z-index.ts +9 -3
  70. package/src/routes/components/NavigationItemRoute.tsx +2 -1
  71. package/src/routes/routes.tsx +2 -13
  72. package/src/service-worker/register.ts +217 -101
  73. package/src/service-worker/sw-dev.ts +5 -1
  74. package/src/service-worker/sw.ts +5 -1
  75. package/src/shellui-target.d.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shellui/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
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.0"
65
+ "@shellui/sdk": "0.4.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "react": "^18.0.0 || ^19.0.0",
package/src/app.tsx CHANGED
@@ -10,10 +10,20 @@ 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';
16
- import { registerServiceWorker, unregisterServiceWorker, isTauri } from './service-worker/register';
20
+ import {
21
+ registerServiceWorker,
22
+ unregisterServiceWorker,
23
+ isTauri,
24
+ isServiceWorkerEnabledInSettings,
25
+ ensureServiceWorkerDisabledWhenOff,
26
+ } from './service-worker/register';
17
27
  import { useSettings } from './features/settings/hooks/useSettings';
18
28
 
19
29
  const AppContent = () => {
@@ -28,13 +38,24 @@ const AppContent = () => {
28
38
  }
29
39
  }, [config?.favicon]);
30
40
 
41
+ // Unregister any stale service worker as early as possible when the setting is off
42
+ useLayoutEffect(() => {
43
+ if (isTauri()) {
44
+ void unregisterServiceWorker();
45
+ return;
46
+ }
47
+ if (!isServiceWorkerEnabledInSettings()) {
48
+ void ensureServiceWorkerDisabledWhenOff();
49
+ }
50
+ }, []);
51
+
31
52
  // Register or unregister service worker based on setting
32
53
  useEffect(() => {
33
54
  if (isTauri()) {
34
55
  unregisterServiceWorker();
35
56
  return;
36
57
  }
37
- const serviceWorkerEnabled = settings?.serviceWorker?.enabled ?? false; // Default to enabled
58
+ const serviceWorkerEnabled = settings?.serviceWorker?.enabled ?? false;
38
59
 
39
60
  // Don't register service worker if navigation is empty or undefined
40
61
  // This helps prevent issues in development or misconfigured apps
@@ -53,6 +74,7 @@ const AppContent = () => {
53
74
  });
54
75
  } else {
55
76
  unregisterServiceWorker();
77
+ void ensureServiceWorkerDisabledWhenOff();
56
78
  }
57
79
  }, [settings?.serviceWorker?.enabled, config?.navigation]);
58
80
 
@@ -105,11 +127,17 @@ const App = () => {
105
127
  return (
106
128
  <ConfigProvider>
107
129
  <AuthProvider>
130
+ <StorageBridge />
108
131
  <SettingsProvider>
109
132
  <ThemeProvider>
110
133
  <I18nProvider>
111
134
  <DialogProvider>
112
- <AppContent />
135
+ <SonnerProvider>
136
+ {/* Toaster + upload progress live at ShellUI root so they survive navigation. */}
137
+ <Toaster />
138
+ <UploadToaster />
139
+ <AppContent />
140
+ </SonnerProvider>
113
141
  </DialogProvider>
114
142
  </I18nProvider>
115
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,32 +1,15 @@
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
- import urls from '../../constants/urls';
6
4
  import { ContentView } from '../../components/ContentView';
7
5
  import { LoginButton } from '../auth/components/LoginButton';
8
6
  import { useAuth } from '../auth/hooks/useAuth';
9
7
  import { useConfig } from '../config/useConfig';
10
8
  import type { NavigationItem } from '../config/types';
11
- import { getBaseUrlWithoutHash } from '../layouts/utils';
12
- import { AdminForbiddenAccess } from './components/AdminForbiddenAccess';
13
9
  import { AppLayout } from '../layouts/AppLayout';
14
-
15
- /** Admin microfrontend uses hash routes (e.g. createHashRouter); sync shell `/admin/...` with iframe `#/...`. */
16
- function buildAdminIframeSrc(
17
- baseAdminContentUrl: string,
18
- normalizedAdminPath: string,
19
- pathname: string,
20
- search: string,
21
- ): string {
22
- const pathAfterAdmin = pathname.startsWith(normalizedAdminPath)
23
- ? pathname.slice(normalizedAdminPath.length)
24
- : '';
25
- const segment = pathAfterAdmin.replace(/^\/+|\/+$/g, '');
26
- const hashRoute = segment ? `/${segment}` : '/';
27
- const originBase = getBaseUrlWithoutHash(baseAdminContentUrl).replace(/\/+$/, '');
28
- return `${originBase}/#${hashRoute}${search}`;
29
- }
10
+ import { AdminForbiddenAccess } from './components/AdminForbiddenAccess';
11
+ import { getAdminContentUrl, getAdminPath } from './config';
12
+ import { buildAdminIframeSrc } from './utils';
30
13
 
31
14
  const AdminAccessGuard = ({ allow }: { allow: boolean }) => {
32
15
  if (!allow) {
@@ -36,25 +19,13 @@ const AdminAccessGuard = ({ allow }: { allow: boolean }) => {
36
19
  };
37
20
 
38
21
  export const AdminView = () => {
39
- const { t } = useTranslation('common');
40
22
  const navigate = useNavigate();
41
23
  const location = useLocation();
42
24
  const { config } = useConfig();
43
25
  const { user } = useAuth();
44
- const isStaff = Boolean(user?.isStaff);
45
26
  const canOpenAdminPanel = Boolean(user?.isStaff || user?.isCompanyOwner);
46
- const djangoAdminHref = useMemo(() => {
47
- if (config.backend?.type !== 'shellui' || !config.backend.url?.trim()) {
48
- return null;
49
- }
50
- return `${config.backend.url.replace(/\/+$/, '')}/admin`;
51
- }, [config.backend?.type, config.backend?.url]);
52
- const configuredAdminPathname = config.backend?.adminPathname?.trim();
53
- const adminPath =
54
- configuredAdminPathname && configuredAdminPathname.startsWith('/')
55
- ? configuredAdminPathname
56
- : urls.admin;
57
- const baseAdminContentUrl = config.backend?.adminUrl?.trim() || urls.settings;
27
+ const adminPath = getAdminPath(config);
28
+ const baseAdminContentUrl = getAdminContentUrl(config);
58
29
  const initialAdminContentUrlRef = useRef<string | null>(null);
59
30
  if (!initialAdminContentUrlRef.current) {
60
31
  const normalizedAdminPath = adminPath.replace(/\/+$/, '');
@@ -111,21 +82,6 @@ export const AdminView = () => {
111
82
  Back to home
112
83
  </Button>
113
84
  <div className="flex items-center gap-2">
114
- {isStaff && djangoAdminHref ? (
115
- <Button
116
- variant="outline"
117
- size="sm"
118
- asChild
119
- >
120
- <a
121
- href={djangoAdminHref}
122
- target="_blank"
123
- rel="noopener noreferrer"
124
- >
125
- {t('adminShell.djangoAdmin')}
126
- </a>
127
- </Button>
128
- ) : null}
129
85
  <LoginButton
130
86
  variant="appbar"
131
87
  logoutOnly
@@ -0,0 +1,15 @@
1
+ import urls from '../../constants/urls';
2
+ import type { ShellUIConfig } from '../config/types';
3
+
4
+ export const DEFAULT_ADMIN_URL = 'https://admin.shellui.com';
5
+
6
+ /** Shell route path for the embedded admin panel. */
7
+ export function getAdminPath(config?: ShellUIConfig): string {
8
+ const configured = config?.backend?.adminPathname?.trim();
9
+ return configured && configured.startsWith('/') ? configured : urls.admin;
10
+ }
11
+
12
+ /** Iframe content URL for the admin panel (config override or production default). */
13
+ export function getAdminContentUrl(config?: ShellUIConfig): string {
14
+ return config?.backend?.adminUrl?.trim() || DEFAULT_ADMIN_URL;
15
+ }
@@ -0,0 +1,4 @@
1
+ export { DEFAULT_ADMIN_URL, getAdminPath, getAdminContentUrl } from './config';
2
+ export { buildAdminIframeSrc, getDjangoAdminHref, isAdminFrame, isAdminPath } from './utils';
3
+ export { createAdminRoute } from './routes';
4
+ export { AdminView } from './AdminView';
@@ -0,0 +1,14 @@
1
+ import { lazy } from 'react';
2
+ import type { RouteObject } from 'react-router';
3
+ import type { ShellUIConfig } from '../config/types';
4
+ import { getAdminPath } from './config';
5
+
6
+ const AdminView = lazy(() => import('./AdminView').then((m) => ({ default: m.AdminView })));
7
+
8
+ export function createAdminRoute(config: ShellUIConfig): RouteObject {
9
+ const adminPath = getAdminPath(config);
10
+ return {
11
+ path: `${adminPath.replace(/^\//, '')}/*`,
12
+ element: <AdminView />,
13
+ };
14
+ }
@@ -0,0 +1,79 @@
1
+ import type { ShellUIConfig } from '../config/types';
2
+ import { getBaseUrlWithoutHash, getHashPathFromUrl } from '../layouts/utils';
3
+ import { getAdminContentUrl, getAdminPath } from './config';
4
+
5
+ const toAbsoluteUrl = (url: string): URL | null => {
6
+ try {
7
+ return new URL(
8
+ url,
9
+ typeof window !== 'undefined' ? window.location.origin : 'http://localhost',
10
+ );
11
+ } catch {
12
+ return null;
13
+ }
14
+ };
15
+
16
+ const normalizePath = (value: string): string => {
17
+ const trimmed = value.trim();
18
+ if (!trimmed) return '/';
19
+ const withoutTrailing = trimmed.replace(/\/+$/, '');
20
+ return withoutTrailing || '/';
21
+ };
22
+
23
+ const normalizeHashPath = (value: string): string => {
24
+ return value.replace(/^#\/?/, '').replace(/\/+$/, '');
25
+ };
26
+
27
+ const isFrameForIframeUrl = (frameSrc: string, itemUrl: string): boolean => {
28
+ const frame = toAbsoluteUrl(frameSrc);
29
+ const item = toAbsoluteUrl(itemUrl);
30
+ if (!frame || !item) return false;
31
+ if (frame.origin !== item.origin) return false;
32
+
33
+ const itemPathname = normalizePath(item.pathname);
34
+ const framePathname = normalizePath(frame.pathname);
35
+ if (framePathname !== itemPathname && !framePathname.startsWith(`${itemPathname}/`)) {
36
+ return false;
37
+ }
38
+
39
+ const itemHashPath = normalizeHashPath(item.hash || getHashPathFromUrl(itemUrl));
40
+ if (!itemHashPath) {
41
+ return true;
42
+ }
43
+
44
+ const frameHashPath = normalizeHashPath(frame.hash);
45
+ return frameHashPath === itemHashPath || frameHashPath.startsWith(`${itemHashPath}/`);
46
+ };
47
+
48
+ /** Whether an iframe src belongs to the embedded admin microfrontend. */
49
+ export function isAdminFrame(frameSrc: string, config?: ShellUIConfig): boolean {
50
+ return isFrameForIframeUrl(frameSrc, getAdminContentUrl(config));
51
+ }
52
+
53
+ /** Admin microfrontend uses hash routes (e.g. createHashRouter); sync shell `/admin/...` with iframe `#/...`. */
54
+ export function buildAdminIframeSrc(
55
+ baseAdminContentUrl: string,
56
+ normalizedAdminPath: string,
57
+ pathname: string,
58
+ search: string,
59
+ ): string {
60
+ const pathAfterAdmin = pathname.startsWith(normalizedAdminPath)
61
+ ? pathname.slice(normalizedAdminPath.length)
62
+ : '';
63
+ const segment = pathAfterAdmin.replace(/^\/+|\/+$/g, '');
64
+ const hashRoute = segment ? `/${segment}` : '/';
65
+ const originBase = getBaseUrlWithoutHash(baseAdminContentUrl).replace(/\/+$/, '');
66
+ return `${originBase}/#${hashRoute}${search}`;
67
+ }
68
+
69
+ export function isAdminPath(pathname: string, config?: ShellUIConfig): boolean {
70
+ const adminPath = getAdminPath(config);
71
+ return pathname === adminPath || pathname.startsWith(`${adminPath}/`);
72
+ }
73
+
74
+ export function getDjangoAdminHref(config?: ShellUIConfig): string | null {
75
+ if (config?.backend?.type !== 'shellui' || !config.backend.url?.trim()) {
76
+ return null;
77
+ }
78
+ return `${config.backend.url.replace(/\/+$/, '')}/admin`;
79
+ }
@@ -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')