@shellui/core 0.5.0 → 0.5.2

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 (51) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +98 -33
  3. package/src/app.tsx +2 -0
  4. package/src/components/ContentView.tsx +3 -5
  5. package/src/components/contentIframeSandbox.spec.ts +25 -0
  6. package/src/components/contentIframeSandbox.ts +43 -0
  7. package/src/features/auth/AuthProvider.tsx +156 -33
  8. package/src/features/auth/backends/index.ts +2 -0
  9. package/src/features/auth/backends/shellui.ts +43 -35
  10. package/src/features/auth/backends/supabase.ts +1 -0
  11. package/src/features/auth/backends/types.ts +5 -0
  12. package/src/features/auth/components/LoginView.tsx +5 -1
  13. package/src/features/auth/components/OAuthCallbackView.tsx +115 -44
  14. package/src/features/auth/constants/oauth.ts +2 -0
  15. package/src/features/auth/hooks/useAuth.tsx +4 -0
  16. package/src/features/auth/utils/authSessionPersistence.spec.ts +93 -0
  17. package/src/features/auth/utils/authSessionPersistence.ts +138 -0
  18. package/src/features/auth/utils/authStorageKeys.ts +8 -0
  19. package/src/features/auth/utils/bffAuthClient.ts +107 -0
  20. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +22 -0
  21. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +17 -0
  22. package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +29 -0
  23. package/src/features/auth/utils/buildSessionFromTokenPayload.ts +24 -0
  24. package/src/features/auth/utils/index.ts +18 -3
  25. package/src/features/auth/utils/isBffAuthEnabled.ts +12 -0
  26. package/src/features/config/types.ts +49 -2
  27. package/src/features/messaging/MessagingSecurityBootstrap.tsx +19 -0
  28. package/src/features/messaging/deriveAllowedMessageOrigins.spec.ts +86 -0
  29. package/src/features/messaging/deriveAllowedMessageOrigins.ts +74 -0
  30. package/src/features/modal/ModalContext.spec.ts +13 -2
  31. package/src/features/modal/validateAndNormalizeUrl.ts +9 -23
  32. package/src/features/security/trustedFrames.spec.ts +129 -0
  33. package/src/features/security/trustedFrames.ts +79 -0
  34. package/src/features/security/urlAllowlist.spec.ts +99 -0
  35. package/src/features/security/urlAllowlist.ts +122 -0
  36. package/src/features/settings/SettingsProvider.tsx +10 -46
  37. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +23 -1
  38. package/src/features/settings/utils/buildSettingsForPropagation.ts +7 -0
  39. package/src/features/storage/StorageBridge.spec.ts +82 -0
  40. package/src/features/storage/StorageBridge.tsx +25 -3
  41. package/src/features/storage/StoragePickerContext.tsx +3 -4
  42. package/src/features/storage/uploads/uploadQueue.ts +2 -5
  43. package/src/routes/components/NavigationItemRoute.tsx +30 -15
  44. package/src/routes/utils/navigationRouteAccess.spec.ts +85 -0
  45. package/src/routes/utils/navigationRouteAccess.ts +43 -0
  46. package/src/features/auth/utils/clearStoredAuthSession.spec.ts +0 -23
  47. package/src/features/auth/utils/clearStoredAuthSession.ts +0 -10
  48. package/src/features/auth/utils/persistAuthSession.spec.ts +0 -35
  49. package/src/features/auth/utils/persistAuthSession.ts +0 -12
  50. package/src/features/auth/utils/readStoredAuthSession.spec.ts +0 -34
  51. package/src/features/auth/utils/readStoredAuthSession.ts +0 -14
@@ -0,0 +1,24 @@
1
+ import type { AuthSession } from '../types';
2
+ import { buildSessionFromParams } from './buildSessionFromParams';
3
+
4
+ export const tokenPayloadToUrlParams = (
5
+ payload: Record<string, unknown> | null | undefined,
6
+ ): URLSearchParams => {
7
+ const params = new URLSearchParams();
8
+ if (!payload) return params;
9
+ if (typeof payload.access_token === 'string') params.set('access_token', payload.access_token);
10
+ if (typeof payload.refresh_token === 'string') params.set('refresh_token', payload.refresh_token);
11
+ if (typeof payload.expires_at === 'number' || typeof payload.expires_at === 'string') {
12
+ params.set('expires_at', String(payload.expires_at));
13
+ }
14
+ if (typeof payload.expires_in === 'number' || typeof payload.expires_in === 'string') {
15
+ params.set('expires_in', String(payload.expires_in));
16
+ }
17
+ if (typeof payload.token_type === 'string') params.set('token_type', payload.token_type);
18
+ return params;
19
+ };
20
+
21
+ export const buildSessionFromTokenPayload = (
22
+ payload: Record<string, unknown> | null | undefined,
23
+ nowSeconds: number,
24
+ ): AuthSession | null => buildSessionFromParams(tokenPayloadToUrlParams(payload), nowSeconds);
@@ -4,7 +4,12 @@ export {
4
4
  getShellUILoginDeviceId,
5
5
  } from './clientLoginContext';
6
6
  export { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
7
+ export { buildOAuthSessionRedirectTo } from './buildOAuthSessionRedirectTo';
7
8
  export { buildSessionFromParams } from './buildSessionFromParams';
9
+ export {
10
+ buildSessionFromTokenPayload,
11
+ tokenPayloadToUrlParams,
12
+ } from './buildSessionFromTokenPayload';
8
13
  export { hashHasOAuthTokens } from './hashHasOAuthTokens';
9
14
  export {
10
15
  AuthRequestError,
@@ -19,7 +24,19 @@ export {
19
24
  redirectCliCallbackError,
20
25
  redirectToCliCallback,
21
26
  } from './cliCallback';
22
- export { clearStoredAuthSession } from './clearStoredAuthSession';
27
+ export {
28
+ clearStoredAuthSession,
29
+ persistAuthProfile,
30
+ persistAuthSession,
31
+ readStoredAuthSession,
32
+ } from './authSessionPersistence';
33
+ export type { PersistedAuthProfile } from './authSessionPersistence';
34
+ export {
35
+ establishBffAuthSession,
36
+ logoutBffAuthSession,
37
+ refreshBffAuthSession,
38
+ } from './bffAuthClient';
39
+ export { isBffAuthEnabledFromConfig, useIsBffAuthEnabled } from './isBffAuthEnabled';
23
40
  export { decodeJwtPayload } from './decodeJwtPayload';
24
41
  export { formatProviderLabel } from './formatProviderLabel';
25
42
  export { getAccessTokenFromSdkSettings, getUserFromSdkSettings } from './getUserFromSdkSettings';
@@ -32,6 +49,4 @@ export { isTokenAutoRefreshDisabled } from './isTokenAutoRefreshDisabled';
32
49
  export { normalizeAuthSettings } from './normalizeAuthSettings';
33
50
  export { normalizeNextPath } from './normalizeNextPath';
34
51
  export { normalizeRedirectPath } from './normalizeRedirectPath';
35
- export { persistAuthSession } from './persistAuthSession';
36
- export { readStoredAuthSession } from './readStoredAuthSession';
37
52
  export { toAuthSessionFromSettingsUser } from './toAuthSessionFromSettingsUser';
@@ -0,0 +1,12 @@
1
+ import { useConfig } from '../../config/useConfig';
2
+
3
+ /** Whether same-origin BFF auth routes should handle refresh (HttpOnly cookie). */
4
+ export const isBffAuthEnabledFromConfig = (
5
+ security: { bffAuth?: { enabled?: boolean } } | undefined,
6
+ ): boolean => security?.bffAuth?.enabled === true;
7
+
8
+ /** React hook — reads `security.bffAuth.enabled` from shell config. */
9
+ export const useIsBffAuthEnabled = (): boolean => {
10
+ const { config } = useConfig();
11
+ return isBffAuthEnabledFromConfig(config.security);
12
+ };
@@ -58,8 +58,8 @@ export interface NavigationItem {
58
58
  settings?: string;
59
59
  /**
60
60
  * Trust control for auth token sharing to iframe apps.
61
- * - undefined/true: trusted (default), token can be shared
62
- * - false: untrusted, token is never shared
61
+ * - undefined/false: untrusted (default), access token is not shared
62
+ * - true: trusted, access token can be shared (opt-in)
63
63
  */
64
64
  safeForAuthToken?: boolean;
65
65
  }
@@ -159,6 +159,51 @@ export interface BackendLoginConfig {
159
159
  panelImage?: string;
160
160
  }
161
161
 
162
+ /** Same-origin BFF auth for HttpOnly refresh cookies (see docs/features/security.md). */
163
+ export interface BffAuthConfig {
164
+ /**
165
+ * When true, refresh tokens are stored in an HttpOnly cookie via `/api/auth/*`
166
+ * served by the shell host (CLI dev server or your production reverse proxy).
167
+ * Default: false (refresh stays in sessionStorage until you enable BFF).
168
+ */
169
+ enabled?: boolean;
170
+ /** HttpOnly cookie name. Default: `shellui_refresh`. */
171
+ cookieName?: string;
172
+ }
173
+
174
+ /** Shell document security headers (CSP, staged rollout). */
175
+ export interface CspConfig {
176
+ /**
177
+ * Emit an enforcing `Content-Security-Policy` header.
178
+ * Default: false (report-only) so playgrounds keep working during rollout.
179
+ */
180
+ enforce?: boolean;
181
+ /**
182
+ * Emit `Content-Security-Policy-Report-Only`.
183
+ * Default: true when `security.csp` is present.
184
+ */
185
+ reportOnly?: boolean;
186
+ /** Optional CSP violation report endpoint (`report-uri` / `report-to`). */
187
+ reportUri?: string;
188
+ /** Extra hosts for `connect-src` (companion APIs, analytics, etc.). */
189
+ connectSrc?: string[];
190
+ /** Extra hosts for `frame-src` (companion iframes). */
191
+ frameSrc?: string[];
192
+ }
193
+
194
+ /**
195
+ * Host security options. Additive namespace for postMessage, CSP, BFF auth, etc.
196
+ */
197
+ export interface SecurityConfig {
198
+ /**
199
+ * Extra http(s) origins (or absolute URLs) allowed for Shellui postMessage traffic.
200
+ * Unioned with origins derived from navigation, storage, and admin URLs.
201
+ */
202
+ allowedMessageOrigins?: string[];
203
+ bffAuth?: BffAuthConfig;
204
+ csp?: CspConfig;
205
+ }
206
+
162
207
  /** Backend API configuration. */
163
208
  export interface BackendConfig {
164
209
  /** Backend provider type. */
@@ -323,6 +368,8 @@ export interface ShellUIConfig {
323
368
  sentry?: SentryConfig;
324
369
  /** Backend communication config. Defaults to undefined (no backend integration). */
325
370
  backend?: BackendConfig;
371
+ /** Host security (postMessage allowlist, BFF auth, CSP — see docs/features/security.md). */
372
+ security?: SecurityConfig;
326
373
  /** Cookie consent: list of cookies by category; accepted ids are stored in settings. */
327
374
  cookieConsent?: CookieConsentConfig;
328
375
  /** Legal documents content rendered as markdown. */
@@ -0,0 +1,19 @@
1
+ import { useEffect } from 'react';
2
+ import { shellui } from '@shellui/sdk';
3
+ import { useConfig } from '../config/useConfig';
4
+ import { deriveAllowedMessageOrigins } from './deriveAllowedMessageOrigins';
5
+
6
+ /**
7
+ * Applies config-derived companion origins to the SDK message security policy.
8
+ */
9
+ export function MessagingSecurityBootstrap() {
10
+ const { config } = useConfig();
11
+
12
+ useEffect(() => {
13
+ shellui.configureMessageSecurity({
14
+ allowedOrigins: deriveAllowedMessageOrigins(config),
15
+ });
16
+ }, [config]);
17
+
18
+ return null;
19
+ }
@@ -0,0 +1,86 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { deriveAllowedMessageOrigins } from './deriveAllowedMessageOrigins';
3
+ import type { ShellUIConfig } from '../config/types';
4
+
5
+ describe('deriveAllowedMessageOrigins', () => {
6
+ it('collects origins from navigation, storage, and admin URLs', () => {
7
+ const config = {
8
+ navigation: [
9
+ {
10
+ label: 'App',
11
+ path: 'app',
12
+ url: 'http://localhost:3000/',
13
+ },
14
+ {
15
+ title: 'Group',
16
+ items: [
17
+ {
18
+ label: 'Files',
19
+ path: 'files',
20
+ url: 'https://files.example.com/app/',
21
+ },
22
+ ],
23
+ },
24
+ ],
25
+ storage: {
26
+ url: 'https://storage.example.com',
27
+ filesUrl: 'https://files.example.com/explorer/',
28
+ },
29
+ administration: {
30
+ navigation: [
31
+ {
32
+ label: 'Admin app',
33
+ path: 'admin-app',
34
+ url: 'https://admin.example.com/panel/',
35
+ },
36
+ ],
37
+ },
38
+ } as ShellUIConfig;
39
+
40
+ const origins = deriveAllowedMessageOrigins(config);
41
+ expect(origins).toContain('http://localhost:3000');
42
+ expect(origins).toContain('https://admin.example.com');
43
+ expect(origins).toContain('https://files.example.com');
44
+ expect(origins).toContain('https://storage.example.com');
45
+ });
46
+
47
+ it('unions security.allowedMessageOrigins with derived origins', () => {
48
+ const config = {
49
+ navigation: [{ label: 'App', path: 'app', url: 'http://localhost:3000/' }],
50
+ security: {
51
+ allowedMessageOrigins: ['https://preview.example.com', 'http://127.0.0.1:4173/preview/'],
52
+ },
53
+ } as ShellUIConfig;
54
+
55
+ const origins = deriveAllowedMessageOrigins(config);
56
+ expect(origins).toContain('http://localhost:3000');
57
+ expect(origins).toContain('https://preview.example.com');
58
+ expect(origins).toContain('http://127.0.0.1:4173');
59
+ });
60
+
61
+ it('keeps derive-only behavior when security.allowedMessageOrigins is empty or omitted', () => {
62
+ const base = {
63
+ navigation: [{ label: 'App', path: 'app', url: 'http://localhost:3000/' }],
64
+ } as ShellUIConfig;
65
+
66
+ const derivedOnly = deriveAllowedMessageOrigins(base);
67
+ expect(derivedOnly).toContain('http://localhost:3000');
68
+ expect(
69
+ deriveAllowedMessageOrigins({ ...base, security: { allowedMessageOrigins: [] } }),
70
+ ).toEqual(derivedOnly);
71
+ });
72
+
73
+ it('skips invalid security.allowedMessageOrigins entries without throwing', () => {
74
+ const config = {
75
+ navigation: [{ label: 'App', path: 'app', url: 'http://localhost:3000/' }],
76
+ security: {
77
+ allowedMessageOrigins: ['https://preview.example.com', 'javascript:alert(1)', '', 42],
78
+ },
79
+ } as unknown as ShellUIConfig;
80
+
81
+ const origins = deriveAllowedMessageOrigins(config);
82
+ expect(origins).toContain('http://localhost:3000');
83
+ expect(origins).toContain('https://preview.example.com');
84
+ expect(origins).not.toContain('javascript:alert(1)');
85
+ });
86
+ });
@@ -0,0 +1,74 @@
1
+ import { collectOriginsFromUrls, getLogger } from '@shellui/sdk';
2
+ import { getAdminContentUrl } from '../admin/config';
3
+ import type { ShellUIConfig } from '../config/types';
4
+
5
+ const logger = getLogger('shellcore');
6
+
7
+ function collectConfiguredMessageOrigins(config?: ShellUIConfig | null): string[] {
8
+ const raw = config?.security?.allowedMessageOrigins;
9
+ if (!Array.isArray(raw) || raw.length === 0) {
10
+ return [];
11
+ }
12
+
13
+ const valid = new Set<string>();
14
+ const invalid: string[] = [];
15
+
16
+ for (const entry of raw) {
17
+ if (typeof entry !== 'string') {
18
+ invalid.push(String(entry));
19
+ continue;
20
+ }
21
+ const trimmed = entry.trim();
22
+ if (!trimmed) {
23
+ invalid.push(entry);
24
+ continue;
25
+ }
26
+ const [origin] = collectOriginsFromUrls(trimmed);
27
+ if (origin) {
28
+ valid.add(origin);
29
+ } else {
30
+ invalid.push(trimmed);
31
+ }
32
+ }
33
+
34
+ if (invalid.length > 0) {
35
+ logger.warn(
36
+ 'Ignoring invalid security.allowedMessageOrigins entries (expected http(s) origins or URLs)',
37
+ { invalid },
38
+ );
39
+ }
40
+
41
+ return [...valid];
42
+ }
43
+
44
+ /** Origins permitted for inbound/outbound Shellui postMessage traffic on this host. */
45
+ export function deriveAllowedMessageOrigins(config?: ShellUIConfig | null): string[] {
46
+ const urls: (string | undefined | null)[] = [
47
+ config?.storage?.url,
48
+ config?.storage?.filesUrl,
49
+ getAdminContentUrl(config ?? undefined),
50
+ ];
51
+
52
+ for (const item of config?.administration?.navigation ?? []) {
53
+ if (item.openIn === 'external') continue;
54
+ urls.push(item.url);
55
+ }
56
+
57
+ for (const entry of config?.navigation ?? []) {
58
+ if ('items' in entry) {
59
+ for (const item of entry.items) {
60
+ if (item.openIn === 'external') continue;
61
+ urls.push(item.url);
62
+ urls.push(item.settings);
63
+ }
64
+ } else {
65
+ if (entry.openIn === 'external') continue;
66
+ urls.push(entry.url);
67
+ urls.push(entry.settings);
68
+ }
69
+ }
70
+
71
+ const derived = collectOriginsFromUrls(...urls);
72
+ const configured = collectConfiguredMessageOrigins(config);
73
+ return [...new Set([...derived, ...configured])];
74
+ }
@@ -1,4 +1,4 @@
1
- import { describe, expect, it } from 'vitest';
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
  import { DEFAULT_ADMIN_URL } from '../admin/config';
3
3
  import type { ShellUIConfig } from '../config/types';
4
4
  import { validateAndNormalizeUrl } from './validateAndNormalizeUrl';
@@ -36,12 +36,23 @@ describe('validateAndNormalizeUrl', () => {
36
36
  expect(validateAndNormalizeUrl('/settings')).toBe('/settings');
37
37
  });
38
38
 
39
- it('allows localhost urls', () => {
39
+ afterEach(() => {
40
+ vi.unstubAllEnvs();
41
+ });
42
+
43
+ it('allows localhost urls in development builds', () => {
44
+ vi.stubEnv('NODE_ENV', 'development');
40
45
  expect(validateAndNormalizeUrl('http://localhost:5175/#/select')).toBe(
41
46
  'http://localhost:5175/#/select',
42
47
  );
43
48
  });
44
49
 
50
+ it('rejects localhost urls in production builds', () => {
51
+ vi.stubEnv('NODE_ENV', 'production');
52
+ expect(validateAndNormalizeUrl('http://localhost:5175/#/select', config)).toBeNull();
53
+ expect(validateAndNormalizeUrl('http://127.0.0.1:5175/#/select', config)).toBeNull();
54
+ });
55
+
45
56
  it('rejects unrelated origins', () => {
46
57
  expect(validateAndNormalizeUrl('https://evil.example.com/form', config)).toBeNull();
47
58
  });
@@ -1,20 +1,6 @@
1
1
  import { getAdminContentUrl } from '../admin/config';
2
2
  import type { ShellUIConfig } from '../config/types';
3
-
4
- const originFromAbsoluteUrl = (value: string | undefined | null): string | null => {
5
- if (!value || typeof value !== 'string') {
6
- return null;
7
- }
8
- const trimmed = value.trim();
9
- if (!trimmed.startsWith('http://') && !trimmed.startsWith('https://')) {
10
- return null;
11
- }
12
- try {
13
- return new URL(trimmed).origin;
14
- } catch {
15
- return null;
16
- }
17
- };
3
+ import { isAllowedIframeOrigin, originFromAbsoluteUrl } from '../security/urlAllowlist';
18
4
 
19
5
  /** Origins allowed in modal iframes: storage service/files app, admin panel, and administration nav apps. */
20
6
  const getAllowedModalOrigins = (config?: ShellUIConfig | null): Set<string> => {
@@ -41,7 +27,7 @@ const getAllowedModalOrigins = (config?: ShellUIConfig | null): Set<string> => {
41
27
  };
42
28
 
43
29
  /**
44
- * Validates and normalizes a URL to ensure it's from the same domain, localhost,
30
+ * Validates and normalizes a URL to ensure it's from the same domain, localhost (dev only),
45
31
  * storage, or administration origins configured on the host.
46
32
  * @param url - The URL or path to validate
47
33
  * @param config - Host config used to allow storage and administration origins
@@ -61,13 +47,13 @@ export const validateAndNormalizeUrl = (
61
47
  const urlObj = new URL(url);
62
48
  const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';
63
49
 
64
- // Allow same origin
65
- if (urlObj.origin === currentOrigin) {
66
- return url;
67
- }
68
-
69
- // Allow localhost URLs (for development)
70
- if (urlObj.hostname === 'localhost' || urlObj.hostname === '127.0.0.1') {
50
+ if (
51
+ isAllowedIframeOrigin(urlObj.origin, {
52
+ allowLocalhost: true,
53
+ config,
54
+ currentOrigin,
55
+ })
56
+ ) {
71
57
  return url;
72
58
  }
73
59
 
@@ -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
+ }