@shellui/core 0.3.0 → 0.3.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 (32) hide show
  1. package/package.json +2 -2
  2. package/src/app.tsx +20 -2
  3. package/src/features/admin/AdminView.tsx +6 -31
  4. package/src/features/admin/config.ts +15 -0
  5. package/src/features/admin/index.ts +4 -0
  6. package/src/features/admin/routes.tsx +14 -0
  7. package/src/features/admin/utils.ts +79 -0
  8. package/src/features/auth/components/LoginButton.tsx +5 -10
  9. package/src/features/auth/components/LoginView.tsx +3 -2
  10. package/src/features/auth/components/OAuthCallbackView.tsx +2 -4
  11. package/src/features/auth/utils/buildAuthUrlWithNext.spec.ts +18 -0
  12. package/src/features/auth/utils/buildAuthUrlWithNext.ts +12 -0
  13. package/src/features/auth/utils/index.ts +1 -0
  14. package/src/features/config/ConfigProvider.ts +1 -1
  15. package/src/features/config/types.ts +0 -5
  16. package/src/features/layouts/OverlayShell.tsx +7 -22
  17. package/src/features/layouts/resolveSdkNavigatePath.spec.ts +55 -0
  18. package/src/features/layouts/resolveSdkNavigatePath.ts +68 -0
  19. package/src/features/settings/SettingsProvider.tsx +10 -6
  20. package/src/features/settings/components/ServiceWorker.tsx +52 -25
  21. package/src/features/settings/components/UpdateApp.tsx +1 -1
  22. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +1 -1
  23. package/src/features/settings/utils/mergePreferencesIntoSettings.spec.ts +1 -1
  24. package/src/features/sonner/SonnerContext.tsx +44 -60
  25. package/src/i18n/translations/en/settings.json +9 -0
  26. package/src/i18n/translations/fr/settings.json +9 -0
  27. package/src/routes/components/NavigationItemRoute.tsx +2 -1
  28. package/src/routes/routes.tsx +2 -13
  29. package/src/service-worker/register.ts +214 -90
  30. package/src/service-worker/sw-dev.ts +5 -1
  31. package/src/service-worker/sw.ts +5 -1
  32. 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.3.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.0"
65
+ "@shellui/sdk": "0.3.1"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "react": "^18.0.0 || ^19.0.0",
package/src/app.tsx CHANGED
@@ -13,7 +13,13 @@ import { AuthProvider } from './features/auth/AuthProvider';
13
13
  import './features/sentry/initSentry';
14
14
  import './i18n/config'; // Initialize i18n
15
15
  import './index.css';
16
- import { registerServiceWorker, unregisterServiceWorker, isTauri } from './service-worker/register';
16
+ import {
17
+ registerServiceWorker,
18
+ unregisterServiceWorker,
19
+ isTauri,
20
+ isServiceWorkerEnabledInSettings,
21
+ ensureServiceWorkerDisabledWhenOff,
22
+ } from './service-worker/register';
17
23
  import { useSettings } from './features/settings/hooks/useSettings';
18
24
 
19
25
  const AppContent = () => {
@@ -28,13 +34,24 @@ const AppContent = () => {
28
34
  }
29
35
  }, [config?.favicon]);
30
36
 
37
+ // Unregister any stale service worker as early as possible when the setting is off
38
+ useLayoutEffect(() => {
39
+ if (isTauri()) {
40
+ void unregisterServiceWorker();
41
+ return;
42
+ }
43
+ if (!isServiceWorkerEnabledInSettings()) {
44
+ void ensureServiceWorkerDisabledWhenOff();
45
+ }
46
+ }, []);
47
+
31
48
  // Register or unregister service worker based on setting
32
49
  useEffect(() => {
33
50
  if (isTauri()) {
34
51
  unregisterServiceWorker();
35
52
  return;
36
53
  }
37
- const serviceWorkerEnabled = settings?.serviceWorker?.enabled ?? false; // Default to enabled
54
+ const serviceWorkerEnabled = settings?.serviceWorker?.enabled ?? false;
38
55
 
39
56
  // Don't register service worker if navigation is empty or undefined
40
57
  // This helps prevent issues in development or misconfigured apps
@@ -53,6 +70,7 @@ const AppContent = () => {
53
70
  });
54
71
  } else {
55
72
  unregisterServiceWorker();
73
+ void ensureServiceWorkerDisabledWhenOff();
56
74
  }
57
75
  }, [settings?.serviceWorker?.enabled, config?.navigation]);
58
76
 
@@ -2,31 +2,15 @@ import { useEffect, useMemo, useRef } from 'react';
2
2
  import { useTranslation } from 'react-i18next';
3
3
  import { Outlet, Route, Routes, useLocation, useNavigate } from 'react-router';
4
4
  import { Button } from '../../components/ui/button';
5
- import urls from '../../constants/urls';
6
5
  import { ContentView } from '../../components/ContentView';
7
6
  import { LoginButton } from '../auth/components/LoginButton';
8
7
  import { useAuth } from '../auth/hooks/useAuth';
9
8
  import { useConfig } from '../config/useConfig';
10
9
  import type { NavigationItem } from '../config/types';
11
- import { getBaseUrlWithoutHash } from '../layouts/utils';
12
- import { AdminForbiddenAccess } from './components/AdminForbiddenAccess';
13
10
  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
- }
11
+ import { AdminForbiddenAccess } from './components/AdminForbiddenAccess';
12
+ import { getAdminContentUrl, getAdminPath } from './config';
13
+ import { buildAdminIframeSrc, getDjangoAdminHref } from './utils';
30
14
 
31
15
  const AdminAccessGuard = ({ allow }: { allow: boolean }) => {
32
16
  if (!allow) {
@@ -43,18 +27,9 @@ export const AdminView = () => {
43
27
  const { user } = useAuth();
44
28
  const isStaff = Boolean(user?.isStaff);
45
29
  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;
30
+ const djangoAdminHref = useMemo(() => getDjangoAdminHref(config), [config]);
31
+ const adminPath = getAdminPath(config);
32
+ const baseAdminContentUrl = getAdminContentUrl(config);
58
33
  const initialAdminContentUrlRef = useRef<string | null>(null);
59
34
  if (!initialAdminContentUrlRef.current) {
60
35
  const normalizedAdminPath = adminPath.replace(/\/+$/, '');
@@ -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
+ }
@@ -7,6 +7,8 @@ import { cn } from '../../../lib/utils';
7
7
  import { useAuth } from '../hooks/useAuth';
8
8
  import { UserIcon } from '../../settings/components/UserIcon';
9
9
  import { useConfig } from '../../config/useConfig';
10
+ import { getAdminPath } from '../../admin/config';
11
+ import { isAdminPath } from '../../admin/utils';
10
12
  import { flattenNavigationItems, getNavPathPrefix } from '../../layouts/utils';
11
13
  import { LogoutIcon, SidebarCaretIcon } from './LoginButtonIcons';
12
14
  import {
@@ -169,17 +171,10 @@ export const LoginButton = ({
169
171
  () => Boolean(user?.isStaff || user?.isCompanyOwner),
170
172
  [user?.isCompanyOwner, user?.isStaff],
171
173
  );
172
- const configuredAdminPathname = useMemo(
173
- () => config.backend?.adminPathname?.trim() ?? null,
174
- [config.backend?.adminPathname],
175
- );
176
- const adminPath =
177
- configuredAdminPathname && configuredAdminPathname.startsWith('/')
178
- ? configuredAdminPathname
179
- : urls.admin;
174
+ const adminPath = getAdminPath(config);
180
175
  const isOnAdminRoute = useMemo(
181
- () => location.pathname === adminPath || location.pathname.startsWith(`${adminPath}/`),
182
- [adminPath, location.pathname],
176
+ () => isAdminPath(location.pathname, config),
177
+ [config, location.pathname],
183
178
  );
184
179
 
185
180
  const openAdminPanel = useCallback(() => {
@@ -9,6 +9,7 @@ import { LegalDocumentsLinks } from '../../legal/LegalDocumentsLinks';
9
9
  import { useAuth } from '../hooks/useAuth';
10
10
  import type { AuthSettings, LoginMethod } from '../types';
11
11
  import {
12
+ buildAuthUrlWithNext,
12
13
  formatProviderLabel,
13
14
  getOAuthProviderCandidates,
14
15
  getPreferredBackendProvider,
@@ -121,10 +122,10 @@ export const LoginView = () => {
121
122
  return normalizeNextPath(params.get('next')) ?? '/';
122
123
  }, [location.search]);
123
124
  const loginPathWithNext = useMemo(() => {
124
- return `${urls.login}?next=${encodeURIComponent(nextPath)}`;
125
+ return buildAuthUrlWithNext(urls.login, nextPath);
125
126
  }, [nextPath]);
126
127
  const oauthCallbackPathWithNext = useMemo(() => {
127
- return `${urls.loginCallback}?next=${encodeURIComponent(nextPath)}`;
128
+ return buildAuthUrlWithNext(urls.loginCallback, nextPath);
128
129
  }, [nextPath]);
129
130
 
130
131
  useEffect(() => {
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react';
2
2
  import { useLocation, useNavigate } from 'react-router';
3
3
  import urls from '../../../constants/urls';
4
- import { normalizeNextPath } from '../utils';
4
+ import { buildAuthUrlWithNext, normalizeNextPath } from '../utils';
5
5
  import { useAuth } from '../hooks/useAuth';
6
6
 
7
7
  const toPositiveInt = (raw: string | null): number | undefined => {
@@ -96,9 +96,7 @@ export const OAuthCallbackView = () => {
96
96
  <button
97
97
  type="button"
98
98
  className="text-sm text-primary underline-offset-4 hover:underline"
99
- onClick={() =>
100
- navigate(`${urls.login}?next=${encodeURIComponent(nextPath)}`, { replace: true })
101
- }
99
+ onClick={() => navigate(buildAuthUrlWithNext(urls.login, nextPath), { replace: true })}
102
100
  >
103
101
  Return to login
104
102
  </button>
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import urls from '../../../constants/urls';
3
+ import { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
4
+
5
+ describe('buildAuthUrlWithNext', () => {
6
+ it('returns the base path when next is null, undefined, or root', () => {
7
+ expect(buildAuthUrlWithNext(urls.login, null)).toBe(urls.login);
8
+ expect(buildAuthUrlWithNext(urls.login, undefined)).toBe(urls.login);
9
+ expect(buildAuthUrlWithNext(urls.login, '/')).toBe(urls.login);
10
+ });
11
+
12
+ it('appends next when it points to a non-root path', () => {
13
+ expect(buildAuthUrlWithNext(urls.login, '/dashboard')).toBe(`${urls.login}?next=%2Fdashboard`);
14
+ expect(buildAuthUrlWithNext(urls.loginCallback, '/settings/user')).toBe(
15
+ `${urls.loginCallback}?next=%2Fsettings%2Fuser`,
16
+ );
17
+ });
18
+ });
@@ -0,0 +1,12 @@
1
+ const shouldIncludeNextParam = (nextPath: string | null | undefined): nextPath is string =>
2
+ Boolean(nextPath && nextPath !== '/');
3
+
4
+ export const buildAuthUrlWithNext = (
5
+ basePath: string,
6
+ nextPath: string | null | undefined,
7
+ ): string => {
8
+ if (!shouldIncludeNextParam(nextPath)) {
9
+ return basePath;
10
+ }
11
+ return `${basePath}?next=${encodeURIComponent(nextPath)}`;
12
+ };
@@ -3,6 +3,7 @@ export {
3
3
  getShellUILoginCompanyId,
4
4
  getShellUILoginDeviceId,
5
5
  } from './clientLoginContext';
6
+ export { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
6
7
  export { buildSessionFromParams } from './buildSessionFromParams';
7
8
  export { clearStoredAuthSession } from './clearStoredAuthSession';
8
9
  export { decodeJwtPayload } from './decodeJwtPayload';
@@ -27,7 +27,7 @@ export function ConfigProvider(props: ConfigProviderProps): ReturnType<typeof cr
27
27
  const [config] = useState<ShellUIConfig>(() => {
28
28
  try {
29
29
  const resolved = shelluiConfig ?? ({} as ShellUIConfig);
30
- if (typeof window !== 'undefined' && resolved.runtime === 'tauri') {
30
+ if (typeof window !== 'undefined' && __SHELLUI_TARGET__ === 'tauri') {
31
31
  (window as Window & { __SHELLUI_TAURI__?: boolean }).__SHELLUI_TAURI__ = true;
32
32
  }
33
33
  if (process.env.NODE_ENV === 'development' && !configLogged) {
@@ -189,9 +189,6 @@ export interface LegalDocumentsConfig {
189
189
  dataProcessingAgreement?: string;
190
190
  }
191
191
 
192
- /** When set to 'tauri', disables service worker and hides its settings (Tauri uses a different caching system). */
193
- export type RuntimeType = 'browser' | 'tauri';
194
-
195
192
  /** Supported backend providers for auth/API communication. */
196
193
  export type BackendType = 'shellui' | 'supabase';
197
194
 
@@ -229,8 +226,6 @@ export interface ShellUIConfig {
229
226
  title?: string;
230
227
  /** App version string (e.g. "1.2.0"). Shown in Settings > System > Update app. */
231
228
  version?: string;
232
- /** Set to 'tauri' when the app runs inside Tauri so service worker is disabled and hidden. */
233
- runtime?: RuntimeType;
234
229
  /** Favicon path (e.g. '/favicon.svg'). Used for the document link rel="icon". */
235
230
  favicon?: string;
236
231
  /** App icon path (e.g. '/favicon.svg'). Displayed before title/logo in sidebar header. */
@@ -10,7 +10,9 @@ import { ContentView } from '../../components/ContentView';
10
10
  import { useModal } from '../modal/ModalContext';
11
11
  import { useDrawer } from '../drawer/DrawerContext';
12
12
  import { useNavigationItems } from '../../routes/hooks/useNavigationItems';
13
+ import { useConfig } from '../config/useConfig';
13
14
  import { getNavPathPrefix, resolveLocalizedString } from './utils';
15
+ import { resolveSdkNavigatePath } from './resolveSdkNavigatePath';
14
16
 
15
17
  interface OverlayShellProps {
16
18
  children: ReactNode;
@@ -21,6 +23,7 @@ export const OverlayShell = ({ children }: OverlayShellProps) => {
21
23
  const location = useLocation();
22
24
  const navigate = useNavigate();
23
25
  const { navigationItems } = useNavigationItems();
26
+ const { config } = useConfig();
24
27
  const { isOpen, modalUrl, closeModal } = useModal();
25
28
  const {
26
29
  isOpen: isDrawerOpen,
@@ -59,27 +62,9 @@ export const OverlayShell = ({ children }: OverlayShellProps) => {
59
62
  closeModal();
60
63
  closeDrawer();
61
64
 
62
- let pathname: string;
63
-
64
- if (rawUrl.startsWith('http://') || rawUrl.startsWith('https://')) {
65
- try {
66
- pathname = new URL(rawUrl).pathname;
67
- } catch {
68
- pathname = rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`;
69
- }
70
- } else {
71
- pathname = rawUrl.startsWith('/') ? rawUrl : `/${rawUrl}`;
72
- }
73
-
74
- const isHomepage = pathname === '/' || pathname === '';
75
- const isAllowed =
76
- isHomepage ||
77
- navigationItems.some((item) => {
78
- const pathPrefix = getNavPathPrefix(item);
79
- return pathname === pathPrefix || pathname.startsWith(`${pathPrefix}/`);
80
- });
81
- if (isAllowed) {
82
- navigate(pathname || '/');
65
+ const resolvedPath = resolveSdkNavigatePath(rawUrl, config, navigationItems);
66
+ if (resolvedPath) {
67
+ navigate(resolvedPath);
83
68
  } else {
84
69
  shellui.toast({
85
70
  type: 'error',
@@ -90,7 +75,7 @@ export const OverlayShell = ({ children }: OverlayShellProps) => {
90
75
  }
91
76
  });
92
77
  return () => cleanup();
93
- }, [navigate, closeModal, closeDrawer, navigationItems, t]);
78
+ }, [navigate, closeModal, closeDrawer, config, navigationItems, t]);
94
79
  return (
95
80
  <>
96
81
  {children}
@@ -0,0 +1,55 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import urls from '../../../constants/urls';
3
+ import { DEFAULT_ADMIN_URL } from '../../admin/config';
4
+ import type { NavigationItem, ShellUIConfig } from '../../config/types';
5
+ import { resolveSdkNavigatePath } from './resolveSdkNavigatePath';
6
+
7
+ const navItems: NavigationItem[] = [
8
+ {
9
+ label: 'Docs',
10
+ path: 'docs',
11
+ url: 'https://docs.shellui.com',
12
+ },
13
+ {
14
+ label: 'Themes',
15
+ path: 'themes',
16
+ url: 'http://localhost:8000/app/#/themes',
17
+ useHashRouter: true,
18
+ },
19
+ ];
20
+
21
+ const config: ShellUIConfig = {
22
+ backend: {
23
+ type: 'shellui',
24
+ url: 'http://localhost:8000',
25
+ adminPathname: '/admin',
26
+ },
27
+ };
28
+
29
+ describe('resolveSdkNavigatePath', () => {
30
+ it('allows built-in shell routes', () => {
31
+ expect(resolveSdkNavigatePath('/admin', config, navItems)).toBe('/admin');
32
+ expect(resolveSdkNavigatePath(urls.login, config, navItems)).toBe(urls.login);
33
+ expect(resolveSdkNavigatePath(urls.settings, config, navItems)).toBe(urls.settings);
34
+ });
35
+
36
+ it('allows configured navigation paths', () => {
37
+ expect(resolveSdkNavigatePath('/docs', config, navItems)).toBe('/docs');
38
+ expect(resolveSdkNavigatePath('/themes/foo', config, navItems)).toBe('/themes/foo');
39
+ });
40
+
41
+ it('rejects external and absolute URLs', () => {
42
+ expect(resolveSdkNavigatePath(DEFAULT_ADMIN_URL, config, navItems)).toBeNull();
43
+ expect(resolveSdkNavigatePath(`${DEFAULT_ADMIN_URL}/#/users`, config, navItems)).toBeNull();
44
+ expect(resolveSdkNavigatePath('https://docs.shellui.com/page', config, navItems)).toBeNull();
45
+ expect(
46
+ resolveSdkNavigatePath('http://localhost:8000/app/#/themes/colors', config, navItems),
47
+ ).toBeNull();
48
+ expect(resolveSdkNavigatePath('https://evil.example.com', config, navItems)).toBeNull();
49
+ expect(resolveSdkNavigatePath('//evil.example.com/path', config, navItems)).toBeNull();
50
+ });
51
+
52
+ it('rejects unconfigured relative paths', () => {
53
+ expect(resolveSdkNavigatePath('/not-configured', config, navItems)).toBeNull();
54
+ });
55
+ });
@@ -0,0 +1,68 @@
1
+ import urls from '../../constants/urls';
2
+ import type { NavigationItem, ShellUIConfig } from '../config/types';
3
+ import { getAdminPath } from '../admin/config';
4
+ import { getNavPathPrefix } from './utils';
5
+
6
+ const toAbsoluteUrl = (url: string): URL | null => {
7
+ try {
8
+ return new URL(
9
+ url,
10
+ typeof window !== 'undefined' ? window.location.origin : 'http://localhost',
11
+ );
12
+ } catch {
13
+ return null;
14
+ }
15
+ };
16
+
17
+ const normalizeShellPath = (value: string): string => {
18
+ const trimmed = value.trim();
19
+ if (!trimmed) return '/';
20
+ const withoutTrailing = trimmed.replace(/\/+$/, '');
21
+ return withoutTrailing || '/';
22
+ };
23
+
24
+ const matchesAllowedShellPath = (pathname: string, allowedPrefixes: string[]): boolean => {
25
+ const normalized = normalizeShellPath(pathname);
26
+ if (normalized === '/') return true;
27
+ return allowedPrefixes.some((prefix) => {
28
+ if (prefix === '/') return normalized === '/';
29
+ return normalized === prefix || normalized.startsWith(`${prefix}/`);
30
+ });
31
+ };
32
+
33
+ /** Shell path prefixes registered in the router (built-in routes, config navigation, admin). */
34
+ export function getAllowedShellPathPrefixes(
35
+ config: ShellUIConfig | undefined,
36
+ navigationItems: NavigationItem[],
37
+ ): string[] {
38
+ const builtIn = Object.values(urls) as string[];
39
+ const navPrefixes = navigationItems.map(getNavPathPrefix);
40
+ const adminPath = getAdminPath(config);
41
+ return [...new Set(['/', ...builtIn, adminPath, ...navPrefixes].map(normalizeShellPath))];
42
+ }
43
+
44
+ /**
45
+ * Resolve an SDK navigate URL to a shell router path.
46
+ * Only relative shell paths are accepted — external URLs are rejected.
47
+ */
48
+ export function resolveSdkNavigatePath(
49
+ rawUrl: string,
50
+ config: ShellUIConfig | undefined,
51
+ navigationItems: NavigationItem[],
52
+ ): string | null {
53
+ const trimmed = rawUrl.trim();
54
+ if (!trimmed) return null;
55
+
56
+ if (trimmed.startsWith('http://') || trimmed.startsWith('https://') || trimmed.startsWith('//')) {
57
+ return null;
58
+ }
59
+
60
+ const parsed = toAbsoluteUrl(trimmed);
61
+ if (!parsed) return null;
62
+
63
+ const allowedPrefixes = getAllowedShellPathPrefixes(config, navigationItems);
64
+ if (matchesAllowedShellPath(parsed.pathname, allowedPrefixes)) {
65
+ return `${parsed.pathname}${parsed.search}` || '/';
66
+ }
67
+ return null;
68
+ }
@@ -10,6 +10,7 @@ import { SettingsContext } from './SettingsContext';
10
10
  import { useConfig } from '../config/useConfig';
11
11
  import type { NavigationItem } from '../config/types';
12
12
  import { useAuth } from '../auth/hooks/useAuth';
13
+ import { isAdminFrame } from '../admin/utils';
13
14
  import { defaultTheme } from '../theme/themes';
14
15
  import {
15
16
  buildSettingsForPropagation,
@@ -19,6 +20,7 @@ import {
19
20
  mergePreferencesIntoSettings,
20
21
  toSettingsUser,
21
22
  } from './utils';
23
+ import { unregisterServiceWorker } from '../../service-worker/register';
22
24
 
23
25
  const logger = getLogger('shellcore');
24
26
 
@@ -110,7 +112,7 @@ const defaultSettings: Settings = {
110
112
  consentedCookieHosts: [],
111
113
  },
112
114
  serviceWorker: {
113
- enabled: true,
115
+ enabled: false,
114
116
  },
115
117
  user: null,
116
118
  accessToken: null,
@@ -179,8 +181,8 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
179
181
  : (defaultSettings.cookieConsent?.consentedCookieHosts ?? []),
180
182
  },
181
183
  serviceWorker: {
182
- // Migrate from legacy "caching" key if present
183
- enabled: parsed.serviceWorker?.enabled ?? parsed.caching?.enabled ?? true,
184
+ // Migrate from legacy "caching" key if present; default off for new installs
185
+ enabled: parsed.serviceWorker?.enabled ?? parsed.caching?.enabled ?? false,
184
186
  },
185
187
  user: parsed.user ?? null,
186
188
  accessToken: null,
@@ -206,15 +208,14 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
206
208
 
207
209
  const isTrustedFrameForAuthToken = useCallback(
208
210
  (frameSrc: string): boolean => {
209
- const adminUrl = config?.backend?.adminUrl?.trim();
210
- if (adminUrl && isFrameForNavigationItem(frameSrc, adminUrl)) {
211
+ if (isAdminFrame(frameSrc, config)) {
211
212
  return true;
212
213
  }
213
214
  return navigationItems.some(
214
215
  (item) => item.safeForAuthToken !== false && isFrameForNavigationItem(frameSrc, item.url),
215
216
  );
216
217
  },
217
- [config?.backend?.adminUrl, navigationItems],
218
+ [config, navigationItems],
218
219
  );
219
220
 
220
221
  const propagateSettingsToIframes = useCallback(
@@ -576,6 +577,9 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
576
577
  }
577
578
  keysToRemove.forEach((key) => localStorage.removeItem(key));
578
579
 
580
+ // Stop any active service worker after reset (default is disabled)
581
+ void unregisterServiceWorker();
582
+
579
583
  // Reset settings to defaults
580
584
  const newSettings = defaultSettings;
581
585
  settingsRef.current = newSettings;