@shellui/core 0.5.0-beta.3 → 0.5.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 (108) hide show
  1. package/README.md +5 -5
  2. package/package.json +3 -2
  3. package/schemas/shellui.config.schema.json +98 -33
  4. package/src/app.tsx +10 -4
  5. package/src/components/ContentView.tsx +3 -5
  6. package/src/components/contentIframeSandbox.spec.ts +25 -0
  7. package/src/components/contentIframeSandbox.ts +43 -0
  8. package/src/components/ui/dialog.tsx +5 -1
  9. package/src/components/ui/dropdown-menu.tsx +39 -4
  10. package/src/components/ui/sheet.tsx +1 -1
  11. package/src/components/ui/sidebar.tsx +3 -2
  12. package/src/components/ui/tabs.tsx +52 -0
  13. package/src/constants/urls.ts +1 -0
  14. package/src/features/auth/AuthProvider.tsx +169 -35
  15. package/src/features/auth/backends/index.ts +2 -0
  16. package/src/features/auth/backends/shellui.ts +43 -35
  17. package/src/features/auth/backends/supabase.ts +1 -0
  18. package/src/features/auth/backends/types.ts +5 -0
  19. package/src/features/auth/components/LoginView.tsx +5 -1
  20. package/src/features/auth/components/OAuthCallbackView.tsx +115 -44
  21. package/src/features/auth/constants/oauth.ts +2 -0
  22. package/src/features/auth/hooks/useAuth.tsx +4 -0
  23. package/src/features/auth/utils/authSessionPersistence.spec.ts +93 -0
  24. package/src/features/auth/utils/authSessionPersistence.ts +138 -0
  25. package/src/features/auth/utils/authStorageKeys.ts +8 -0
  26. package/src/features/auth/utils/bffAuthClient.ts +107 -0
  27. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +22 -0
  28. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +17 -0
  29. package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +29 -0
  30. package/src/features/auth/utils/buildSessionFromTokenPayload.ts +24 -0
  31. package/src/features/auth/utils/index.ts +18 -3
  32. package/src/features/auth/utils/isBffAuthEnabled.ts +12 -0
  33. package/src/features/chromeActions/ChromeActionIcons.tsx +261 -0
  34. package/src/features/chromeActions/ChromeActionsDemoView.tsx +149 -0
  35. package/src/features/chromeActions/ChromeActionsHost.tsx +1511 -0
  36. package/src/features/chromeActions/ChromeActionsProvider.tsx +141 -0
  37. package/src/features/chromeActions/chromeActionsStore.spec.ts +61 -0
  38. package/src/features/chromeActions/chromeActionsStore.ts +77 -0
  39. package/src/features/chromeActions/computeActionInsets.spec.ts +360 -0
  40. package/src/features/chromeActions/computeActionInsets.ts +326 -0
  41. package/src/features/chromeActions/index.ts +26 -0
  42. package/src/features/chromeActions/resolveUuidForRemoveIframe.spec.ts +49 -0
  43. package/src/features/config/types.ts +49 -2
  44. package/src/features/layouts/AppLayout.tsx +4 -4
  45. package/src/features/layouts/OverlayShell.tsx +60 -12
  46. package/src/features/layouts/app-bar-inset/AppBarInsetLayout.tsx +1 -1
  47. package/src/features/layouts/appbar/AppBarLayout.tsx +194 -89
  48. package/src/features/layouts/chrome/DesktopChrome.tsx +17 -3
  49. package/src/features/layouts/chrome/InsetMobileRadiusOverlay.tsx +18 -0
  50. package/src/features/layouts/chrome/index.ts +8 -0
  51. package/src/features/layouts/chrome/runtime.ts +73 -0
  52. package/src/features/layouts/chrome/useScrollHideChrome.ts +210 -0
  53. package/src/features/layouts/floating/FloatingBottomDock.tsx +410 -0
  54. package/src/features/layouts/floating/FloatingLayout.tsx +31 -21
  55. package/src/features/layouts/floating/FloatingStatusScrim.tsx +36 -0
  56. package/src/features/layouts/floating/computeFloatingInsets.spec.ts +5 -5
  57. package/src/features/layouts/floating/computeFloatingInsets.ts +64 -12
  58. package/src/features/layouts/floating/isShellOwnedPath.spec.ts +2 -0
  59. package/src/features/layouts/floating/isShellOwnedPath.ts +1 -0
  60. package/src/features/layouts/floating/layoutChromeStore.spec.ts +138 -0
  61. package/src/features/layouts/floating/layoutChromeStore.ts +169 -6
  62. package/src/features/layouts/floating/useFloatingChrome.ts +20 -30
  63. package/src/features/layouts/sidebar/SidebarLayout.tsx +87 -31
  64. package/src/features/layouts/sidebar-inset/SidebarInsetLayout.tsx +1 -1
  65. package/src/features/layouts/windows/WindowsLayout.tsx +240 -110
  66. package/src/features/messaging/MessagingSecurityBootstrap.tsx +19 -0
  67. package/src/features/messaging/deriveAllowedMessageOrigins.spec.ts +86 -0
  68. package/src/features/messaging/deriveAllowedMessageOrigins.ts +74 -0
  69. package/src/features/modal/ModalContext.spec.ts +13 -2
  70. package/src/features/modal/validateAndNormalizeUrl.ts +9 -23
  71. package/src/features/overlays/ResponsiveModal.tsx +201 -21
  72. package/src/features/overlays/overlaySize.spec.ts +18 -0
  73. package/src/features/overlays/overlaySize.ts +89 -0
  74. package/src/features/security/trustedFrames.spec.ts +129 -0
  75. package/src/features/security/trustedFrames.ts +79 -0
  76. package/src/features/security/urlAllowlist.spec.ts +99 -0
  77. package/src/features/security/urlAllowlist.ts +122 -0
  78. package/src/features/settings/SettingsProvider.tsx +38 -54
  79. package/src/features/settings/components/Develop.tsx +2 -0
  80. package/src/features/settings/components/develop/ChromeActionsTestButtons.tsx +63 -0
  81. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +23 -1
  82. package/src/features/settings/utils/buildSettingsForPropagation.ts +7 -0
  83. package/src/features/storage/StorageBridge.spec.ts +82 -0
  84. package/src/features/storage/StorageBridge.tsx +25 -3
  85. package/src/features/storage/StoragePickerContext.tsx +3 -4
  86. package/src/features/storage/uploads/uploadQueue.spec.ts +56 -1
  87. package/src/features/storage/uploads/uploadQueue.ts +44 -6
  88. package/src/features/theme/applyTheme.ts +23 -5
  89. package/src/hooks/use-mobile.tsx +21 -7
  90. package/src/i18n/translations/en/settings.json +9 -0
  91. package/src/i18n/translations/fr/settings.json +9 -0
  92. package/src/index.css +264 -124
  93. package/src/index.html +6 -4
  94. package/src/index.ts +8 -0
  95. package/src/routes/components/NavigationItemRoute.tsx +30 -15
  96. package/src/routes/components/RouteFallback.tsx +15 -0
  97. package/src/routes/routes.tsx +14 -0
  98. package/src/routes/utils/navigationRouteAccess.spec.ts +85 -0
  99. package/src/routes/utils/navigationRouteAccess.ts +43 -0
  100. package/src/features/auth/utils/clearStoredAuthSession.spec.ts +0 -23
  101. package/src/features/auth/utils/clearStoredAuthSession.ts +0 -10
  102. package/src/features/auth/utils/persistAuthSession.spec.ts +0 -35
  103. package/src/features/auth/utils/persistAuthSession.ts +0 -12
  104. package/src/features/auth/utils/readStoredAuthSession.spec.ts +0 -34
  105. package/src/features/auth/utils/readStoredAuthSession.ts +0 -14
  106. package/src/features/layouts/floating/FloatingFadeMask.tsx +0 -22
  107. package/src/features/layouts/floating/FloatingTabBar.tsx +0 -437
  108. package/src/features/layouts/floating/FloatingTabIndicator.tsx +0 -216
@@ -5,6 +5,7 @@ import type {
5
5
  OverlaySizeValue,
6
6
  DrawerPosition,
7
7
  } from '@shellui/sdk';
8
+ import { readSafeAreaInsetTop } from '../layouts/chrome/viewport';
8
9
 
9
10
  /** CSS max-height for overlays — matches --shellui-overlay-max-height in index.css. */
10
11
  const OVERLAY_MAX_HEIGHT_CSS = 'var(--shellui-overlay-max-height)';
@@ -281,3 +282,91 @@ export function resolveDismissOptions(
281
282
  showDragHandle,
282
283
  };
283
284
  }
285
+
286
+ /**
287
+ * Expanded bottom-sheet height leaves a tappable overlay band above the sheet:
288
+ * top safe-area inset + {@link SHEET_EXPANDED_TOP_GAP_PX}.
289
+ */
290
+ export const SHEET_EXPANDED_TOP_GAP_PX = 60;
291
+
292
+ /** CSS height for the expanded bottom-sheet chrome. */
293
+ export const SHEET_EXPANDED_HEIGHT_CSS = `calc(var(--shellui-app-height) - var(--shellui-safe-area-top) - ${SHEET_EXPANDED_TOP_GAP_PX}px)`;
294
+
295
+ /** Pixel height for the expanded snap (matches {@link SHEET_EXPANDED_HEIGHT_CSS}). */
296
+ export function sheetExpandedHeightPx(
297
+ viewportHeightPx?: number,
298
+ safeAreaTopPx?: number,
299
+ topGapPx = SHEET_EXPANDED_TOP_GAP_PX,
300
+ ): number {
301
+ const viewport = viewportHeightPx ?? (typeof window !== 'undefined' ? window.innerHeight : 0);
302
+ let safeTop = safeAreaTopPx;
303
+ if (safeTop === undefined) {
304
+ safeTop = typeof document !== 'undefined' ? readSafeAreaInsetTop() : 0;
305
+ }
306
+ return Math.max(0, Math.round(viewport - safeTop - topGapPx));
307
+ }
308
+
309
+ /** Vaul snap fraction for the expanded height (`height / viewport`). */
310
+ export function sheetExpandedSnapFraction(
311
+ viewportHeightPx?: number,
312
+ safeAreaTopPx?: number,
313
+ ): number {
314
+ const viewport = viewportHeightPx ?? (typeof window !== 'undefined' ? window.innerHeight : 0);
315
+ if (!(viewport > 0)) return 0.9;
316
+ return Number((sheetExpandedHeightPx(viewport, safeAreaTopPx) / viewport).toFixed(4));
317
+ }
318
+
319
+ /** Vertical drawer presets → window-height fraction (Vaul snapPoints). */
320
+ const VERTICAL_SNAP_BY_PRESET: Record<OverlaySizePreset, number> = {
321
+ sm: 0.4,
322
+ md: 0.55,
323
+ lg: 0.75,
324
+ xl: 0.9,
325
+ full: 1,
326
+ content: 0.5,
327
+ };
328
+
329
+ /**
330
+ * Resolve `[normal, expanded]` Vaul snap points for a bottom sheet.
331
+ * Returns null when the sheet is already near the expanded height (nothing useful to expand to).
332
+ */
333
+ export function resolveBottomSheetSnapPoints(
334
+ options?: OverlayOpenOptions | null,
335
+ reportedHeightPx?: number | null,
336
+ viewportHeightPx?: number,
337
+ safeAreaTopPx?: number,
338
+ ): number[] | null {
339
+ const viewport = viewportHeightPx ?? (typeof window !== 'undefined' ? window.innerHeight : 0);
340
+ if (!(viewport > 0)) return null;
341
+
342
+ const expanded = sheetExpandedSnapFraction(viewport, safeAreaTopPx);
343
+
344
+ let normal: number;
345
+ if (reportedHeightPx !== null && Number.isFinite(reportedHeightPx) && reportedHeightPx > 0) {
346
+ normal = reportedHeightPx / viewport;
347
+ } else {
348
+ const dynamic = isDynamicSizing(options);
349
+ const size = (dynamic ? 'content' : options?.size) as OverlaySizeValue | undefined;
350
+ if (!size) {
351
+ normal = 0.8;
352
+ } else if (isOverlaySizePreset(size)) {
353
+ if (size === 'full') return null;
354
+ normal = VERTICAL_SNAP_BY_PRESET[size];
355
+ } else if (typeof size === 'number' && Number.isFinite(size)) {
356
+ normal = size / viewport;
357
+ } else {
358
+ const raw = String(size).trim();
359
+ const vh = raw.match(/^([\d.]+)vh$/i);
360
+ const px = raw.match(/^([\d.]+)px$/i);
361
+ if (vh) normal = parseFloat(vh[1]) / 100;
362
+ else if (px) normal = parseFloat(px[1]) / viewport;
363
+ else normal = 0.8;
364
+ }
365
+ }
366
+
367
+ // Already near expanded — expand would be a no-op
368
+ if (normal >= expanded - 0.04) return null;
369
+ // Keep a meaningful gap between snaps
370
+ normal = Math.min(Math.max(normal, 0.2), expanded - 0.05);
371
+ return [Number(normal.toFixed(4)), expanded];
372
+ }
@@ -0,0 +1,129 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { ShellUIConfig } from '../config/types';
3
+ import {
4
+ getStorageRequestTrustDenial,
5
+ isRegisteredTrustedFrame,
6
+ isTrustedFrameForAuthToken,
7
+ resolveRegisteredFrameSrc,
8
+ } from './trustedFrames';
9
+
10
+ const config = {
11
+ navigation: [
12
+ {
13
+ label: 'Companion',
14
+ path: 'companion',
15
+ url: 'http://localhost:5175/',
16
+ safeForAuthToken: true,
17
+ },
18
+ {
19
+ label: 'Default companion',
20
+ path: 'default',
21
+ url: 'http://localhost:5198/',
22
+ },
23
+ {
24
+ label: 'Hostile embed',
25
+ path: 'hostile',
26
+ url: 'http://localhost:5199/',
27
+ safeForAuthToken: false,
28
+ },
29
+ ],
30
+ storage: {
31
+ url: 'http://localhost:8001',
32
+ filesUrl: 'http://localhost:5176/',
33
+ },
34
+ administration: {
35
+ title: 'Admin',
36
+ navigation: [
37
+ {
38
+ label: 'Billing',
39
+ path: 'billing',
40
+ url: 'http://localhost:5180/app',
41
+ },
42
+ ],
43
+ },
44
+ } as ShellUIConfig;
45
+
46
+ const trustedIframe = {
47
+ src: 'http://localhost:5175/company/docs',
48
+ } as HTMLIFrameElement;
49
+
50
+ const defaultIframe = {
51
+ src: 'http://localhost:5198/widget',
52
+ } as HTMLIFrameElement;
53
+
54
+ const hostileIframe = {
55
+ src: 'http://localhost:5199/widget',
56
+ } as HTMLIFrameElement;
57
+
58
+ const registry = {
59
+ getAllIframes: () =>
60
+ [
61
+ ['trusted-uuid', trustedIframe],
62
+ ['default-uuid', defaultIframe],
63
+ ['hostile-uuid', hostileIframe],
64
+ ] as Array<[string, HTMLIFrameElement]>,
65
+ };
66
+
67
+ describe('isTrustedFrameForAuthToken', () => {
68
+ it('does not trust navigation companions by default', () => {
69
+ expect(isTrustedFrameForAuthToken('http://localhost:5198/widget', config)).toBe(false);
70
+ });
71
+
72
+ it('allows navigation companions with safeForAuthToken: true', () => {
73
+ expect(isTrustedFrameForAuthToken('http://localhost:5175/company', config)).toBe(true);
74
+ });
75
+
76
+ it('denies navigation items marked safeForAuthToken: false', () => {
77
+ expect(isTrustedFrameForAuthToken('http://localhost:5199/widget', config)).toBe(false);
78
+ });
79
+
80
+ it('allows administration navigation and storage files explorer frames', () => {
81
+ expect(isTrustedFrameForAuthToken('http://localhost:5180/app/#/invoices', config)).toBe(true);
82
+ expect(isTrustedFrameForAuthToken('http://localhost:5176/#/select', config)).toBe(true);
83
+ });
84
+
85
+ it('denies unrelated origins', () => {
86
+ expect(isTrustedFrameForAuthToken('https://evil.example.com/payload', config)).toBe(false);
87
+ });
88
+ });
89
+
90
+ describe('resolveRegisteredFrameSrc', () => {
91
+ it('returns the src for a registered iframe uuid', () => {
92
+ expect(resolveRegisteredFrameSrc(['trusted-uuid'], registry)).toBe(
93
+ 'http://localhost:5175/company/docs',
94
+ );
95
+ });
96
+
97
+ it('returns null when the sender is not registered', () => {
98
+ expect(resolveRegisteredFrameSrc(['unknown-uuid'], registry)).toBeNull();
99
+ expect(resolveRegisteredFrameSrc(undefined, registry)).toBeNull();
100
+ });
101
+ });
102
+
103
+ describe('getStorageRequestTrustDenial', () => {
104
+ it('allows trusted companion frames', () => {
105
+ expect(getStorageRequestTrustDenial(['trusted-uuid'], registry, config)).toBeNull();
106
+ expect(isRegisteredTrustedFrame('http://localhost:5175/company', config)).toBe(true);
107
+ });
108
+
109
+ it('denies default (non-opt-in) companion frames', () => {
110
+ expect(getStorageRequestTrustDenial(['default-uuid'], registry, config)).toEqual({
111
+ message: 'Storage request rejected: untrusted frame',
112
+ status: 403,
113
+ });
114
+ });
115
+
116
+ it('denies hostile iframe requests without storage I/O', () => {
117
+ expect(getStorageRequestTrustDenial(['hostile-uuid'], registry, config)).toEqual({
118
+ message: 'Storage request rejected: untrusted frame',
119
+ status: 403,
120
+ });
121
+ });
122
+
123
+ it('denies unregistered senders', () => {
124
+ expect(getStorageRequestTrustDenial(['missing-uuid'], registry, config)).toEqual({
125
+ message: 'Storage request rejected: untrusted frame',
126
+ status: 403,
127
+ });
128
+ });
129
+ });
@@ -0,0 +1,79 @@
1
+ import type { ShellUIConfig } from '../config/types';
2
+ import { isAdminFrame } from '../admin/utils';
3
+ import { flattenNavigationItems, isFrameForAppUrl } from '../layouts/utils';
4
+
5
+ /** Minimal frame registry surface for trust checks (shared with #60 message gating). */
6
+ export type FrameRegistryLike = {
7
+ getAllIframes(): Array<[string, HTMLIFrameElement]>;
8
+ };
9
+
10
+ /**
11
+ * Whether an iframe `src` is trusted for privileged shell features (JWT sharing,
12
+ * StorageBridge). Navigation companions require `safeForAuthToken: true` (opt-in).
13
+ * First-party admin URLs and `storage.filesUrl` remain trusted by default.
14
+ */
15
+ export function isTrustedFrameForAuthToken(frameSrc: string, config?: ShellUIConfig): boolean {
16
+ if (isAdminFrame(frameSrc, config)) {
17
+ return true;
18
+ }
19
+
20
+ const adminNavItems = config?.administration?.navigation ?? [];
21
+ if (
22
+ adminNavItems.some(
23
+ (item) =>
24
+ item.openIn !== 'external' &&
25
+ Boolean(item.url?.trim()) &&
26
+ isFrameForAppUrl(frameSrc, item.url),
27
+ )
28
+ ) {
29
+ return true;
30
+ }
31
+
32
+ const filesUrl = config?.storage?.filesUrl?.trim();
33
+ if (filesUrl && isFrameForAppUrl(frameSrc, filesUrl)) {
34
+ return true;
35
+ }
36
+
37
+ const navigationItems = flattenNavigationItems(config?.navigation ?? []);
38
+ return navigationItems.some(
39
+ (item) => item.safeForAuthToken === true && isFrameForAppUrl(frameSrc, item.url),
40
+ );
41
+ }
42
+
43
+ /** Resolve the registered immediate sender iframe `src` from a postMessage `from` chain. */
44
+ export function resolveRegisteredFrameSrc(
45
+ from: string[] | undefined,
46
+ frameRegistry: FrameRegistryLike,
47
+ ): string | null {
48
+ const iframeUuid = from?.find(Boolean);
49
+ if (!iframeUuid) {
50
+ return null;
51
+ }
52
+
53
+ const frame = frameRegistry.getAllIframes().find(([uuid]) => uuid === iframeUuid)?.[1];
54
+ const frameSrc = frame?.src?.trim();
55
+ return frameSrc || null;
56
+ }
57
+
58
+ /** Whether a registered frame `src` passes the trusted-frame policy. */
59
+ export function isRegisteredTrustedFrame(frameSrc: string | null, config?: ShellUIConfig): boolean {
60
+ return Boolean(frameSrc && isTrustedFrameForAuthToken(frameSrc, config));
61
+ }
62
+
63
+ export type StorageTrustDenial = { message: string; status: 403 };
64
+
65
+ /**
66
+ * Returns a storage error when the request sender is missing from the frame
67
+ * registry or fails the trusted-frame policy. Call before any storage I/O.
68
+ */
69
+ export function getStorageRequestTrustDenial(
70
+ from: string[] | undefined,
71
+ frameRegistry: FrameRegistryLike,
72
+ config?: ShellUIConfig,
73
+ ): StorageTrustDenial | null {
74
+ const frameSrc = resolveRegisteredFrameSrc(from, frameRegistry);
75
+ if (!isRegisteredTrustedFrame(frameSrc, config)) {
76
+ return { message: 'Storage request rejected: untrusted frame', status: 403 };
77
+ }
78
+ return null;
79
+ }
@@ -0,0 +1,99 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import type { ShellUIConfig } from '../config/types';
3
+ import { isAllowedIframeOrigin, validateLoginPanelUrl } from './urlAllowlist';
4
+
5
+ const config = {
6
+ backend: {
7
+ type: 'shellui',
8
+ url: 'https://api.example.com',
9
+ loginUrl: 'https://app.example.com',
10
+ },
11
+ storage: {
12
+ url: 'https://storage.example.com',
13
+ filesUrl: 'https://files.example.com',
14
+ },
15
+ } as ShellUIConfig;
16
+
17
+ describe('isAllowedIframeOrigin', () => {
18
+ afterEach(() => {
19
+ vi.unstubAllEnvs();
20
+ });
21
+
22
+ it('allows the shell origin', () => {
23
+ expect(
24
+ isAllowedIframeOrigin('https://app.example.com', {
25
+ currentOrigin: 'https://app.example.com',
26
+ }),
27
+ ).toBe(true);
28
+ });
29
+
30
+ it('allows configured backend and storage origins', () => {
31
+ expect(isAllowedIframeOrigin('https://api.example.com', { config })).toBe(true);
32
+ expect(isAllowedIframeOrigin('https://storage.example.com', { config })).toBe(true);
33
+ });
34
+
35
+ it('allows localhost in development builds', () => {
36
+ vi.stubEnv('NODE_ENV', 'development');
37
+ expect(
38
+ isAllowedIframeOrigin('http://localhost:5176', {
39
+ allowLocalhost: true,
40
+ currentOrigin: 'https://app.example.com',
41
+ }),
42
+ ).toBe(true);
43
+ });
44
+
45
+ it('denies localhost in production builds', () => {
46
+ vi.stubEnv('NODE_ENV', 'production');
47
+ expect(
48
+ isAllowedIframeOrigin('http://localhost:5176', {
49
+ allowLocalhost: true,
50
+ currentOrigin: 'https://app.example.com',
51
+ }),
52
+ ).toBe(false);
53
+ });
54
+
55
+ it('denies unrelated origins', () => {
56
+ vi.stubEnv('NODE_ENV', 'production');
57
+ expect(
58
+ isAllowedIframeOrigin('https://evil.example.com', {
59
+ allowLocalhost: true,
60
+ config,
61
+ currentOrigin: 'https://app.example.com',
62
+ }),
63
+ ).toBe(false);
64
+ });
65
+ });
66
+
67
+ describe('validateLoginPanelUrl', () => {
68
+ afterEach(() => {
69
+ vi.unstubAllEnvs();
70
+ });
71
+
72
+ it('allows same-origin relative paths', () => {
73
+ expect(validateLoginPanelUrl('/login-branding/', config)).toBe('/login-branding/');
74
+ });
75
+
76
+ it('allows configured backend origin', () => {
77
+ expect(validateLoginPanelUrl('https://api.example.com/branding/', config)).toBe(
78
+ 'https://api.example.com/branding/',
79
+ );
80
+ });
81
+
82
+ it('allows localhost in development', () => {
83
+ vi.stubEnv('NODE_ENV', 'development');
84
+ expect(validateLoginPanelUrl('http://localhost:5176/login-branding/', config)).toBe(
85
+ 'http://localhost:5176/login-branding/',
86
+ );
87
+ });
88
+
89
+ it('rejects localhost in production', () => {
90
+ vi.stubEnv('NODE_ENV', 'production');
91
+ expect(validateLoginPanelUrl('http://localhost:5176/login-branding/', config)).toBeNull();
92
+ });
93
+
94
+ it('rejects non-http(s) schemes and untrusted origins', () => {
95
+ vi.stubEnv('NODE_ENV', 'production');
96
+ expect(validateLoginPanelUrl('javascript:alert(1)', config)).toBeNull();
97
+ expect(validateLoginPanelUrl('https://evil.example.com/panel', config)).toBeNull();
98
+ });
99
+ });
@@ -0,0 +1,122 @@
1
+ import type { ShellUIConfig } from '../config/types';
2
+
3
+ /** True when the shell is running a development build (localhost modal/panel exceptions apply). */
4
+ export const isShellDevelopment = (): boolean => process.env.NODE_ENV === 'development';
5
+
6
+ export const isLocalhostHostname = (hostname: string): boolean => {
7
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
8
+ return normalized === 'localhost' || normalized === '127.0.0.1' || normalized === '::1';
9
+ };
10
+
11
+ export const originFromAbsoluteUrl = (value: string | undefined | null): string | null => {
12
+ if (!value || typeof value !== 'string') {
13
+ return null;
14
+ }
15
+ const trimmed = value.trim();
16
+ if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
17
+ return null;
18
+ }
19
+ try {
20
+ return new URL(trimmed).origin;
21
+ } catch {
22
+ return null;
23
+ }
24
+ };
25
+
26
+ const getConfiguredTrustedOrigins = (config?: ShellUIConfig | null): Set<string> => {
27
+ const origins = new Set<string>();
28
+ const add = (value?: string | null) => {
29
+ const origin = originFromAbsoluteUrl(value);
30
+ if (origin) {
31
+ origins.add(origin);
32
+ }
33
+ };
34
+
35
+ add(config?.backend?.url);
36
+ add(config?.backend?.loginUrl);
37
+ add(config?.storage?.url);
38
+ add(config?.storage?.filesUrl);
39
+
40
+ return origins;
41
+ };
42
+
43
+ export type UrlAllowlistOptions = {
44
+ /** When true, loopback hostnames are allowed (development builds only). */
45
+ allowLocalhost?: boolean;
46
+ config?: ShellUIConfig | null;
47
+ /** Current shell origin; required to allow same-origin absolute URLs. */
48
+ currentOrigin?: string;
49
+ };
50
+
51
+ /**
52
+ * Whether an absolute http(s) URL origin is allowed for iframe embedding (modal, login panel).
53
+ * Relative paths are validated separately and resolve to the shell origin.
54
+ */
55
+ export const isAllowedIframeOrigin = (
56
+ origin: string,
57
+ { allowLocalhost = false, config, currentOrigin = '' }: UrlAllowlistOptions = {},
58
+ ): boolean => {
59
+ if (currentOrigin && origin === currentOrigin) {
60
+ return true;
61
+ }
62
+
63
+ if (allowLocalhost && isShellDevelopment()) {
64
+ try {
65
+ const { hostname } = new URL(origin);
66
+ if (isLocalhostHostname(hostname)) {
67
+ return true;
68
+ }
69
+ } catch {
70
+ // fall through
71
+ }
72
+ }
73
+
74
+ return getConfiguredTrustedOrigins(config).has(origin);
75
+ };
76
+
77
+ /**
78
+ * Validates login branding `panelUrl` before loading it in an unsandboxed iframe.
79
+ * Allows same-origin relative paths, same-origin absolute URLs, configured backend/login/storage
80
+ * origins, and loopback URLs in development only. Rejects other schemes and origins.
81
+ */
82
+ export const validateLoginPanelUrl = (
83
+ url: string | undefined | null,
84
+ config?: ShellUIConfig | null,
85
+ ): string | null => {
86
+ if (!url || typeof url !== 'string') {
87
+ return null;
88
+ }
89
+
90
+ const trimmed = url.trim();
91
+ if (!trimmed) {
92
+ return null;
93
+ }
94
+
95
+ // Relative paths resolve to the shell origin and are safe.
96
+ if (trimmed.startsWith('/') && !trimmed.startsWith('//')) {
97
+ return trimmed;
98
+ }
99
+
100
+ if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
101
+ return null;
102
+ }
103
+
104
+ try {
105
+ const urlObj = new URL(trimmed);
106
+ const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';
107
+
108
+ if (
109
+ isAllowedIframeOrigin(urlObj.origin, {
110
+ allowLocalhost: true,
111
+ config,
112
+ currentOrigin,
113
+ })
114
+ ) {
115
+ return trimmed;
116
+ }
117
+
118
+ return null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ };