@shellui/core 0.7.0-alpha.3 → 0.7.0-alpha.5

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.
@@ -0,0 +1,137 @@
1
+ import type { ShellUIConfig } from '../../config/types';
2
+ import {
3
+ resolveAppBackendConfig,
4
+ resolveFrameNavigationItem,
5
+ type ResolvedAppBackend,
6
+ } from './identity';
7
+
8
+ /** A child app hosted by an embedded app, as accepted by the shell. */
9
+ export type ChildFrameEntry = {
10
+ hostUuid: string;
11
+ frameId: string;
12
+ url: string;
13
+ identity: ResolvedAppBackend | null;
14
+ };
15
+
16
+ export type ChildFrameRegistration =
17
+ | { ok: true; entry: ChildFrameEntry }
18
+ | { ok: false; reason: string };
19
+
20
+ const entries = new Map<string, ChildFrameEntry>();
21
+
22
+ function entryKey(hostUuid: string, frameId: string): string {
23
+ return `${hostUuid}\n${frameId}`;
24
+ }
25
+
26
+ function exactOrigin(value: unknown): string | null {
27
+ if (typeof value !== 'string') return null;
28
+ try {
29
+ const url = new URL(value);
30
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
31
+ return url.origin;
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ function originList(values: unknown): Set<string> {
38
+ const out = new Set<string>();
39
+ if (!Array.isArray(values)) return out;
40
+ for (const value of values) {
41
+ // Only exact origins count. A path, wildcard or `*` never matches.
42
+ const origin = exactOrigin(value);
43
+ if (origin && origin === `${value}`.trim().replace(/\/$/, '')) out.add(origin);
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /**
49
+ * Check a `SHELLUI_CHILD_FRAME_REGISTER` message. `from` must be exactly one hop:
50
+ * a child app cannot register frames by sending the message through its host.
51
+ */
52
+ export function validateChildFrameRegistration(input: {
53
+ from: readonly string[] | undefined;
54
+ hostSrc: string | null | undefined;
55
+ payload: unknown;
56
+ config?: ShellUIConfig;
57
+ }): ChildFrameRegistration {
58
+ const from = (input.from ?? []).filter(Boolean);
59
+ if (from.length !== 1) return { ok: false, reason: 'not sent by a direct app frame' };
60
+ if (!input.hostSrc) return { ok: false, reason: 'unknown host frame' };
61
+ const payload = input.payload as
62
+ | { frameId?: unknown; url?: unknown; backend?: unknown }
63
+ | null
64
+ | undefined;
65
+ const frameId = typeof payload?.frameId === 'string' ? payload.frameId.trim() : '';
66
+ if (!frameId) return { ok: false, reason: 'missing frameId' };
67
+ const childOrigin = exactOrigin(payload?.url);
68
+ if (!childOrigin) return { ok: false, reason: 'child URL is not http(s)' };
69
+
70
+ const item = resolveFrameNavigationItem(input.hostSrc, input.config);
71
+ const rules = item?.childFrames;
72
+ if (!rules) return { ok: false, reason: 'host app may not embed apps' };
73
+ if (!originList(rules.origins).has(childOrigin)) {
74
+ return { ok: false, reason: 'child origin is not allowed' };
75
+ }
76
+
77
+ let identity: ResolvedAppBackend | null = null;
78
+ const backend = payload?.backend as
79
+ | { url?: unknown; companyId?: unknown; type?: unknown; provider?: unknown }
80
+ | null
81
+ | undefined;
82
+ if (backend) {
83
+ const backendOrigin = exactOrigin(backend.url);
84
+ if (!backendOrigin || !originList(rules.backendOrigins).has(backendOrigin)) {
85
+ return { ok: false, reason: 'child identity server is not allowed' };
86
+ }
87
+ const companyId =
88
+ typeof backend.companyId === 'string' || typeof backend.companyId === 'number'
89
+ ? backend.companyId
90
+ : undefined;
91
+ const type =
92
+ backend.type === 'shellui' || backend.type === 'supabase' ? backend.type : undefined;
93
+ identity = resolveAppBackendConfig(
94
+ {
95
+ url: backend.url as string,
96
+ ...(companyId !== undefined ? { companyId } : {}),
97
+ ...(type ? { type } : {}),
98
+ ...(typeof backend.provider === 'string' ? { provider: backend.provider } : {}),
99
+ },
100
+ input.config,
101
+ );
102
+ if (!identity) return { ok: false, reason: 'child identity server is invalid' };
103
+ }
104
+
105
+ return {
106
+ ok: true,
107
+ entry: { hostUuid: from[0], frameId, url: payload?.url as string, identity },
108
+ };
109
+ }
110
+
111
+ export function addChildFrame(entry: ChildFrameEntry): void {
112
+ entries.set(entryKey(entry.hostUuid, entry.frameId), entry);
113
+ }
114
+
115
+ export function removeChildFrame(hostUuid: string, frameId: string): void {
116
+ entries.delete(entryKey(hostUuid, frameId));
117
+ }
118
+
119
+ /** The registered child for a `from` path such as `[host, child, ...]`. */
120
+ export function findChildFrame(path: readonly string[]): ChildFrameEntry | null {
121
+ if (path.length < 2) return null;
122
+ return entries.get(entryKey(path[0], path[1])) ?? null;
123
+ }
124
+
125
+ /** Children whose host frame is still registered. Others are dropped. */
126
+ export function listChildFrames(isHostKnown: (uuid: string) => boolean): ChildFrameEntry[] {
127
+ const out: ChildFrameEntry[] = [];
128
+ for (const [key, entry] of entries) {
129
+ if (!isHostKnown(entry.hostUuid)) entries.delete(key);
130
+ else out.push(entry);
131
+ }
132
+ return out;
133
+ }
134
+
135
+ export function clearChildFrames(): void {
136
+ entries.clear();
137
+ }
@@ -140,14 +140,7 @@ export function resolveFrameAuthDelivery(input: {
140
140
  );
141
141
  }
142
142
 
143
- /** Options for `buildSettingsForPropagation`. Shell frames omit the override keys. */
144
- export function frameAuthPropagationOptions(input: {
145
- frameSrc: string;
146
- config?: ShellUIConfig;
147
- shellAccessToken: string | null;
148
- getAppSession: (key: string) => AuthSession | null;
149
- shellOrigin?: string | null;
150
- }): {
143
+ export type FrameAuthPropagationOptions = {
151
144
  includeAuthAccessToken: boolean;
152
145
  accessToken: string | null;
153
146
  authBackendBaseUrl?: string | null;
@@ -155,8 +148,9 @@ export function frameAuthPropagationOptions(input: {
155
148
  storage?: StorageConfig | null;
156
149
  email?: EmailConfig | null;
157
150
  hosting?: HostingConfig | null;
158
- } {
159
- const delivery = resolveFrameAuthDelivery(input);
151
+ };
152
+
153
+ function toPropagationOptions(delivery: FrameAuthDelivery): FrameAuthPropagationOptions {
160
154
  return {
161
155
  includeAuthAccessToken: delivery.includeAuthAccessToken,
162
156
  accessToken: delivery.accessToken,
@@ -165,3 +159,36 @@ export function frameAuthPropagationOptions(input: {
165
159
  ...delivery.services,
166
160
  };
167
161
  }
162
+
163
+ /** Options for `buildSettingsForPropagation`. Shell frames omit the override keys. */
164
+ export function frameAuthPropagationOptions(input: {
165
+ frameSrc: string;
166
+ config?: ShellUIConfig;
167
+ shellAccessToken: string | null;
168
+ getAppSession: (key: string) => AuthSession | null;
169
+ shellOrigin?: string | null;
170
+ }): FrameAuthPropagationOptions {
171
+ return toPropagationOptions(resolveFrameAuthDelivery(input));
172
+ }
173
+
174
+ /**
175
+ * Auth fields for a child app hosted inside an embedded app (`createAppFrame`).
176
+ * The shell token is never sent. With no allowed identity server the child gets
177
+ * no token, no user and no service URLs.
178
+ */
179
+ export function childFrameAuthPropagationOptions(input: {
180
+ identity: ResolvedAppBackend | null;
181
+ getAppSession: (key: string) => AuthSession | null;
182
+ }): FrameAuthPropagationOptions {
183
+ const { identity, getAppSession } = input;
184
+ const session = identity ? getAppSession(identity.key) : null;
185
+ return toPropagationOptions({
186
+ includeAuthAccessToken: Boolean(identity),
187
+ accessToken: session?.accessToken ?? null,
188
+ overrideAuthBackend: true,
189
+ authBackendBaseUrl: identity?.type === 'shellui' ? identity.url : null,
190
+ overrideUser: true,
191
+ settingsUser: settingsUserFromSession(session),
192
+ services: serviceOverrides(null, true),
193
+ });
194
+ }
@@ -10,6 +10,24 @@ import {
10
10
  } from './silentSignIn';
11
11
 
12
12
  describe('buildSilentAuthorizeUrl', () => {
13
+ it('uses the federation entry for a regional identity server', () => {
14
+ const url = new URL(
15
+ buildSilentAuthorizeUrl({
16
+ backendUrl: 'https://id.eu.example/',
17
+ provider: 'upstream',
18
+ redirectTo: 'https://shell.example/login/callback?shellui_silent=1',
19
+ codeChallenge: 'challenge-value',
20
+ companyId: 7,
21
+ }),
22
+ );
23
+ expect(`${url.origin}${url.pathname}`).toBe('https://id.eu.example/oauth/silent-signin');
24
+ expect(url.searchParams.get('company_id')).toBe('7');
25
+ expect(url.searchParams.get('code_challenge')).toBe('challenge-value');
26
+ expect(url.searchParams.get('redirect_to')).toBe(
27
+ 'https://shell.example/login/callback?shellui_silent=1',
28
+ );
29
+ });
30
+
13
31
  it('uses PKCE, prompt=none, and code delivery without a shell token', () => {
14
32
  const shellToken = 'shell-access-token.should.not.appear';
15
33
  const url = new URL(
@@ -92,6 +92,9 @@ export function publishSilentAuthCallbackResult(win: Window = window): boolean {
92
92
  return true;
93
93
  }
94
94
 
95
+ /** Provider name of a regional identity server's trusted upstream (identity federation). */
96
+ export const FEDERATION_PROVIDER = 'upstream';
97
+
95
98
  export function buildSilentAuthorizeUrl(input: {
96
99
  backendUrl: string;
97
100
  provider: string;
@@ -101,7 +104,18 @@ export function buildSilentAuthorizeUrl(input: {
101
104
  clientTimezone?: string;
102
105
  clientDeviceId?: string;
103
106
  }): string {
104
- const authorizeUrl = new URL(`${input.backendUrl.replace(/\/+$/, '')}/api/v1/authorize`);
107
+ const base = input.backendUrl.replace(/\/+$/, '');
108
+ if (input.provider === FEDERATION_PROVIDER) {
109
+ // A regional identity server signs in through its trusted upstream (global identity).
110
+ // It has its own prompt=none entry and returns the usual PKCE code to `redirect_to`.
111
+ const federated = new URL(`${base}/oauth/silent-signin`);
112
+ federated.searchParams.set('redirect_to', input.redirectTo);
113
+ federated.searchParams.set('code_challenge', input.codeChallenge);
114
+ const federatedCompany = getShellUILoginCompanyId(input.companyId);
115
+ if (federatedCompany) federated.searchParams.set('company_id', federatedCompany);
116
+ return federated.toString();
117
+ }
118
+ const authorizeUrl = new URL(`${base}/api/v1/authorize`);
105
119
  authorizeUrl.searchParams.set('provider', input.provider);
106
120
  authorizeUrl.searchParams.set('redirect_to', input.redirectTo);
107
121
  authorizeUrl.searchParams.set('code_challenge', input.codeChallenge);
@@ -0,0 +1,98 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ ACCESS_TOKEN_TYPE,
4
+ TOKEN_EXCHANGE_GRANT,
5
+ describeAppSessionFailure,
6
+ exchangeShellTokenForAppSession,
7
+ } from './tokenExchange';
8
+
9
+ const NOW = 1_800_000_000;
10
+
11
+ function jsonResponse(status: number, body: unknown): Response {
12
+ return new Response(JSON.stringify(body), {
13
+ status,
14
+ headers: { 'Content-Type': 'application/json' },
15
+ });
16
+ }
17
+
18
+ describe('exchangeShellTokenForAppSession', () => {
19
+ afterEach(() => {
20
+ vi.unstubAllGlobals();
21
+ });
22
+
23
+ it('posts an RFC 8693 request to the regional server and returns its session', async () => {
24
+ const fetchMock = vi.fn(async () =>
25
+ jsonResponse(200, {
26
+ access_token: 'regional-access',
27
+ refresh_token: 'regional-refresh',
28
+ token_type: 'Bearer',
29
+ issued_token_type: ACCESS_TOKEN_TYPE,
30
+ expires_in: 300,
31
+ expires_at: NOW + 300,
32
+ }),
33
+ );
34
+ vi.stubGlobal('fetch', fetchMock);
35
+
36
+ const outcome = await exchangeShellTokenForAppSession({
37
+ backendUrl: 'https://id.eu.example',
38
+ companyId: 5,
39
+ shellAccessToken: 'global-access',
40
+ nowSeconds: NOW,
41
+ });
42
+
43
+ expect(outcome.ok && outcome.session.accessToken).toBe('regional-access');
44
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
45
+ expect(url).toBe('https://id.eu.example/oauth/token');
46
+ expect(init.method).toBe('POST');
47
+ expect(init.credentials).toBe('omit');
48
+ const body = new URLSearchParams(String(init.body));
49
+ expect(body.get('grant_type')).toBe(TOKEN_EXCHANGE_GRANT);
50
+ expect(body.get('subject_token')).toBe('global-access');
51
+ expect(body.get('subject_token_type')).toBe(ACCESS_TOKEN_TYPE);
52
+ expect(body.get('company_id')).toBe('5');
53
+ expect(url).not.toContain('global-access');
54
+ });
55
+
56
+ it('refuses without a numeric company id and sends nothing', async () => {
57
+ const fetchMock = vi.fn();
58
+ vi.stubGlobal('fetch', fetchMock);
59
+ const outcome = await exchangeShellTokenForAppSession({
60
+ backendUrl: 'https://id.eu.example',
61
+ shellAccessToken: 'global-access',
62
+ nowSeconds: NOW,
63
+ });
64
+ expect(outcome).toEqual({ ok: false, reason: 'missing_company_id' });
65
+ expect(fetchMock).not.toHaveBeenCalled();
66
+ });
67
+
68
+ it('reports the server error without the token', async () => {
69
+ vi.stubGlobal(
70
+ 'fetch',
71
+ vi.fn(async () =>
72
+ jsonResponse(400, { error: 'invalid_grant', error_description: 'User is not a member.' }),
73
+ ),
74
+ );
75
+ const outcome = await exchangeShellTokenForAppSession({
76
+ backendUrl: 'https://id.eu.example',
77
+ companyId: '5',
78
+ shellAccessToken: 'global-access',
79
+ nowSeconds: NOW,
80
+ });
81
+ expect(outcome).toEqual({ ok: false, reason: 'invalid_grant: User is not a member.' });
82
+ expect(describeAppSessionFailure('invalid_grant: User is not a member.')).toBeTruthy();
83
+ });
84
+
85
+ it('reports a server without token exchange', async () => {
86
+ vi.stubGlobal(
87
+ 'fetch',
88
+ vi.fn(async () => jsonResponse(404, {})),
89
+ );
90
+ const outcome = await exchangeShellTokenForAppSession({
91
+ backendUrl: 'https://id.eu.example',
92
+ companyId: 5,
93
+ shellAccessToken: 'global-access',
94
+ nowSeconds: NOW,
95
+ });
96
+ expect(outcome).toEqual({ ok: false, reason: 'token_exchange_unavailable' });
97
+ });
98
+ });
@@ -0,0 +1,76 @@
1
+ import { buildSessionFromTokenPayload } from '../utils/buildSessionFromTokenPayload';
2
+ import type { AuthSession } from '../types';
3
+
4
+ export const TOKEN_EXCHANGE_GRANT = 'urn:ietf:params:oauth:grant-type:token-exchange';
5
+ export const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
6
+
7
+ export type TokenExchangeOutcome =
8
+ | { ok: true; session: AuthSession }
9
+ | { ok: false; reason: string };
10
+
11
+ /**
12
+ * RFC 8693 token exchange against a regional identity server.
13
+ * The shell access token goes to that server only. Never pass it to a child app.
14
+ */
15
+ export async function exchangeShellTokenForAppSession(input: {
16
+ backendUrl: string;
17
+ companyId?: string | number;
18
+ shellAccessToken: string;
19
+ nowSeconds: number;
20
+ }): Promise<TokenExchangeOutcome> {
21
+ const companyId = `${input.companyId ?? ''}`.trim();
22
+ if (!/^\d+$/.test(companyId)) return { ok: false, reason: 'missing_company_id' };
23
+ if (!input.shellAccessToken) return { ok: false, reason: 'no_shell_session' };
24
+
25
+ const body = new URLSearchParams({
26
+ grant_type: TOKEN_EXCHANGE_GRANT,
27
+ subject_token: input.shellAccessToken,
28
+ subject_token_type: ACCESS_TOKEN_TYPE,
29
+ company_id: companyId,
30
+ });
31
+ let response: Response;
32
+ try {
33
+ response = await fetch(`${input.backendUrl}/oauth/token`, {
34
+ method: 'POST',
35
+ headers: {
36
+ Accept: 'application/json',
37
+ 'Content-Type': 'application/x-www-form-urlencoded',
38
+ },
39
+ body: body.toString(),
40
+ credentials: 'omit',
41
+ });
42
+ } catch {
43
+ return { ok: false, reason: 'token_exchange_unreachable' };
44
+ }
45
+ const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
46
+ if (!response.ok) {
47
+ if (response.status === 404) return { ok: false, reason: 'token_exchange_unavailable' };
48
+ const code = typeof payload?.error === 'string' ? payload.error : `http_${response.status}`;
49
+ const detail =
50
+ typeof payload?.error_description === 'string' ? payload.error_description.slice(0, 200) : '';
51
+ return { ok: false, reason: detail ? `${code}: ${detail}` : code };
52
+ }
53
+ const session = buildSessionFromTokenPayload(payload, input.nowSeconds);
54
+ if (!session?.accessToken) return { ok: false, reason: 'token_exchange_empty' };
55
+ return { ok: true, session };
56
+ }
57
+
58
+ const HINTS: Record<string, string> = {
59
+ missing_company_id:
60
+ 'Set the regional company id (regional_company_id) as companyId on this app backend.',
61
+ no_shell_session: 'The shell has no session access token to exchange. Sign in to the shell.',
62
+ token_exchange_unreachable:
63
+ 'The regional identity server did not answer. Check its URL and that OIDC_CORS_ALLOWED_ORIGINS lists this shell origin.',
64
+ token_exchange_unavailable:
65
+ 'The regional identity server does not offer token exchange. It needs role region, GLOBAL_ISSUER_URL, GLOBAL_JWKS and GLOBAL_ACCESS_TOKEN_AUDIENCE.',
66
+ invalid_request:
67
+ 'The regional identity server refused the request. Check OIDC_CORS_ALLOWED_ORIGINS lists this shell origin.',
68
+ invalid_target: 'The regional identity server does not know this company id.',
69
+ invalid_grant:
70
+ 'The regional identity server refused the shell token or this user for that company.',
71
+ };
72
+
73
+ export function describeAppSessionFailure(reason: string): string | undefined {
74
+ const code = reason.split(':')[0].trim();
75
+ return HINTS[code];
76
+ }
@@ -109,9 +109,9 @@ describe('webPkce', () => {
109
109
  });
110
110
 
111
111
  it('returns a null redirect_to for an entry stored without one', () => {
112
- const id = 'o' + '0'.repeat(32);
112
+ const id = `o${'0'.repeat(32)}`;
113
113
  sessionStorage.setItem(
114
- 'shellui.auth.pkce.' + id,
114
+ `shellui.auth.pkce.${id}`,
115
115
  JSON.stringify({ verifier: 'v'.repeat(43), createdAt: Date.now() }),
116
116
  );
117
117
  expect(takeWebPkceFlow(id)).toEqual({ verifier: 'v'.repeat(43), redirectTo: null });
@@ -69,6 +69,11 @@ export interface NavigationItem {
69
69
  * The shell token is never sent when this server differs.
70
70
  */
71
71
  backend?: AppBackendConfig;
72
+ /**
73
+ * Lets this app host other Shellui apps in its own iframes (`createAppFrame`).
74
+ * Off when omitted. Only exact origins listed here are accepted.
75
+ */
76
+ childFrames?: ChildFramesConfig;
72
77
  /**
73
78
  * Email service for this app. Omit to use the shell `email` when the app uses
74
79
  * the shell identity server. When `backend` names a different server and this
@@ -237,6 +242,18 @@ export interface AuthConfig {
237
242
  desktopScheme?: string;
238
243
  }
239
244
 
245
+ /** Child apps an embedded app may host, and the identity servers they may use. */
246
+ export interface ChildFramesConfig {
247
+ /** Exact origins of child apps, such as `https://admin.shellui.com`. No wildcards. */
248
+ origins: string[];
249
+ /**
250
+ * Exact origins of identity servers a child may sign in to, such as
251
+ * `https://id.eu.shellui.com`. The shell keeps a separate session per server
252
+ * and never sends its own token to a child. Omit to give children no token.
253
+ */
254
+ backendOrigins?: string[];
255
+ }
256
+
240
257
  /**
241
258
  * Identity server for one embedded app when it differs from the shell `backend`.
242
259
  * `type` defaults to the shell backend type. `companyId` is not copied from the shell.
@@ -9,6 +9,7 @@ import {
9
9
  } from 'react';
10
10
  import {
11
11
  bindVisibleResume,
12
+ CHILD_FRAME_SESSION,
12
13
  deliverSessionHandoff,
13
14
  getLogger,
14
15
  shellui,
@@ -19,8 +20,32 @@ import {
19
20
  import { SettingsContext } from './SettingsContext';
20
21
  import { useConfig } from '../config/useConfig';
21
22
  import { useAuth } from '../auth/hooks/useAuth';
22
- import { frameAuthPropagationOptions } from '../auth/appBackend/frameAuth';
23
23
  import {
24
+ childFrameAuthPropagationOptions,
25
+ frameAuthPropagationOptions,
26
+ } from '../auth/appBackend/frameAuth';
27
+ import {
28
+ addChildFrame,
29
+ findChildFrame,
30
+ listChildFrames,
31
+ removeChildFrame,
32
+ validateChildFrameRegistration,
33
+ type ChildFrameEntry,
34
+ } from '../auth/appBackend/childFrames';
35
+ import { resolveFrameNavigationItem } from '../auth/appBackend/identity';
36
+ import { describeAppSessionFailure } from '../auth/appBackend/tokenExchange';
37
+
38
+ function safeOrigin(url: string): string {
39
+ try {
40
+ return new URL(url).origin;
41
+ } catch {
42
+ return '';
43
+ }
44
+ }
45
+ import {
46
+ ensureAppBackendSession,
47
+ allowSilentRetry,
48
+ getAppBackendSessionFailure,
24
49
  getAppBackendSession,
25
50
  refreshAppBackendSessionIfDue,
26
51
  subscribeAppBackendSessions,
@@ -211,10 +236,44 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
211
236
  [config],
212
237
  );
213
238
 
239
+ /** Settings for a child app hosted by an embedded app. Never carries the shell token. */
240
+ const pushSettingsToChildFrame = useCallback(
241
+ (entry: ChildFrameEntry | null, path: string[], baseSettings: Settings) => {
242
+ const lang = baseSettings.language?.code || 'en';
243
+ const settingsToPropagate = buildSettingsForPropagation(baseSettings, config, lang, {
244
+ ...childFrameAuthPropagationOptions({
245
+ identity: entry?.identity ?? null,
246
+ getAppSession: getAppBackendSession,
247
+ }),
248
+ includeLayoutChrome: false,
249
+ frameUuid: path[path.length - 1],
250
+ });
251
+ shellui.sendMessage({
252
+ type: 'SHELLUI_SETTINGS',
253
+ payload: { settings: settingsToPropagate },
254
+ to: path,
255
+ });
256
+ },
257
+ [config],
258
+ );
259
+
260
+ const propagateSettingsToChildFrames = useCallback(
261
+ (baseSettings: Settings) => {
262
+ const live = new Set(shellui.frameRegistry.getLiveIframes().map(([uuid]) => uuid));
263
+ const known = new Set(shellui.frameRegistry.getAllIframes().map(([uuid]) => uuid));
264
+ for (const entry of listChildFrames((uuid) => known.has(uuid))) {
265
+ if (!live.has(entry.hostUuid)) continue;
266
+ pushSettingsToChildFrame(entry, [entry.hostUuid, entry.frameId], baseSettings);
267
+ }
268
+ },
269
+ [pushSettingsToChildFrame],
270
+ );
271
+
214
272
  const propagateSettingsToIframes = useCallback(
215
273
  (baseSettings: Settings) => {
216
274
  const iframes = shellui.frameRegistry.getLiveIframes();
217
275
  if (iframes.length === 0) return;
276
+ propagateSettingsToChildFrames(baseSettings);
218
277
  const lang = baseSettings.language?.code || 'en';
219
278
  for (const [uuid, iframe] of iframes) {
220
279
  const frameSrc = iframe?.src ?? '';
@@ -230,7 +289,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
230
289
  });
231
290
  }
232
291
  },
233
- [authOptionsForFrame, config],
292
+ [authOptionsForFrame, config, propagateSettingsToChildFrames],
234
293
  );
235
294
 
236
295
  const pushSettingsToFrame = useCallback(
@@ -502,6 +561,26 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
502
561
  .getAllIframes()
503
562
  .find(([uuid]) => uuid === firstHopIframeUuid)?.[1]
504
563
  : undefined;
564
+ // A child app hosted by an embedded app gets its own session, never the host's.
565
+ const childEntry = findChildFrame(requestingPath);
566
+ const hostEmbedsApps = Boolean(
567
+ requestingFrame?.src &&
568
+ resolveFrameNavigationItem(requestingFrame.src, config)?.childFrames,
569
+ );
570
+ const isHostedChild = requestingPath.length > 1 && (childEntry || hostEmbedsApps);
571
+ if (isHostedChild) {
572
+ if (childEntry?.identity) {
573
+ await ensureAppBackendSession(childEntry.identity, { allowSilent: true });
574
+ }
575
+ deliverSessionHandoff(() =>
576
+ pushSettingsToChildFrame(
577
+ childEntry,
578
+ requestingPath,
579
+ settingsRef.current ?? defaultSettings,
580
+ ),
581
+ );
582
+ return;
583
+ }
505
584
  if (requestingFrame?.src) {
506
585
  await refreshAppBackendSessionIfDue(requestingFrame.src, config);
507
586
  }
@@ -589,13 +668,82 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
589
668
  },
590
669
  );
591
670
 
671
+ const cleanupChildRegister = shellui.addMessageListener(
672
+ 'SHELLUI_CHILD_FRAME_REGISTER',
673
+ (message: ShellUIMessage) => {
674
+ if (typeof window === 'undefined' || window.parent !== window) return;
675
+ const from = (message.from ?? []).filter(Boolean);
676
+ const hostSrc = shellui.frameRegistry
677
+ .getAllIframes()
678
+ .find(([uuid]) => uuid === from[0])?.[1]?.src;
679
+ const result = validateChildFrameRegistration({
680
+ from,
681
+ hostSrc,
682
+ payload: message.payload,
683
+ config,
684
+ });
685
+ if (!result.ok) {
686
+ logger.warn('Rejected a child app frame', { reason: result.reason });
687
+ return;
688
+ }
689
+ addChildFrame(result.entry);
690
+ const { entry } = result;
691
+ logger.info('Child app frame registered', {
692
+ origin: safeOrigin(entry.url),
693
+ identity: entry.identity?.url ?? null,
694
+ companyId: entry.identity?.companyId ?? null,
695
+ });
696
+ void (async () => {
697
+ let ok = true;
698
+ let reason: string | null = null;
699
+ if (entry.identity) {
700
+ // A (re)registration is a fresh mount or a user retry: allow one more silent try.
701
+ allowSilentRetry(entry.identity.key);
702
+ const token = await ensureAppBackendSession(entry.identity, { allowSilent: true });
703
+ ok = Boolean(token);
704
+ reason = ok ? null : (getAppBackendSessionFailure(entry.identity.key) ?? 'no_session');
705
+ }
706
+ shellui.sendMessage({
707
+ type: CHILD_FRAME_SESSION,
708
+ payload: {
709
+ frameId: entry.frameId,
710
+ ok,
711
+ ...(reason ? { reason, hint: describeAppSessionFailure(reason) } : {}),
712
+ } as unknown as ShellUIMessage['payload'],
713
+ to: [entry.hostUuid],
714
+ });
715
+ logger.info('Child app frame session', { origin: safeOrigin(entry.url), ok, reason });
716
+ deliverSessionHandoff(() =>
717
+ pushSettingsToChildFrame(
718
+ entry,
719
+ [entry.hostUuid, entry.frameId],
720
+ settingsRef.current ?? defaultSettings,
721
+ ),
722
+ );
723
+ })();
724
+ },
725
+ );
726
+
727
+ const cleanupChildUnregister = shellui.addMessageListener(
728
+ 'SHELLUI_CHILD_FRAME_UNREGISTER',
729
+ (message: ShellUIMessage) => {
730
+ const from = (message.from ?? []).filter(Boolean);
731
+ const frameId = (message.payload as { frameId?: unknown } | null)?.frameId;
732
+ if (from.length !== 1 || typeof frameId !== 'string') return;
733
+ removeChildFrame(from[0], frameId);
734
+ },
735
+ );
736
+
592
737
  return () => {
593
738
  cleanup();
594
739
  cleanupSettings();
595
740
  cleanupSettingsRequested();
596
741
  cleanupInitialized();
742
+ cleanupChildRegister();
743
+ cleanupChildUnregister();
597
744
  };
598
745
  }, [
746
+ pushSettingsToChildFrame,
599
747
  authOptionsForFrame,
600
748
  config,
601
749
  applyHandoffToken,