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

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shellui/core",
3
- "version": "0.7.0-alpha.3",
3
+ "version": "0.7.0-alpha.4",
4
4
  "description": "Shellui Core - Core React application runtime",
5
5
  "main": "src/index.ts",
6
6
  "type": "module",
@@ -73,7 +73,7 @@
73
73
  "workbox-routing": "^7.4.0",
74
74
  "workbox-strategies": "^7.4.0",
75
75
  "workbox-window": "^7.4.0",
76
- "@shellui/sdk": "0.7.0-alpha.3"
76
+ "@shellui/sdk": "0.7.0-alpha.4"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "react": "^18.0.0 || ^19.0.0",
@@ -260,6 +260,10 @@
260
260
  "$ref": "#/definitions/AppBackendConfig",
261
261
  "description": "Identity server for this embedded app when it is not the shell `backend`. The shell keeps a separate session and sends this URL plus that session's access token. Omit to use the shell backend and token. The shell token is never sent when this server differs."
262
262
  },
263
+ "childFrames": {
264
+ "$ref": "#/definitions/ChildFramesConfig",
265
+ "description": "Lets this app host other Shellui apps in its own iframes (`createAppFrame`). Off when omitted. Only exact origins listed here are accepted."
266
+ },
263
267
  "email": {
264
268
  "$ref": "#/definitions/EmailConfig",
265
269
  "description": "Email service for this app. Omit to use the shell `email` when the app uses the shell identity server. When `backend` names a different server and this is omitted, the app receives no email URL."
@@ -336,6 +340,28 @@
336
340
  "enum": ["shellui", "supabase"],
337
341
  "description": "Supported backend providers for auth/API communication."
338
342
  },
343
+ "ChildFramesConfig": {
344
+ "type": "object",
345
+ "properties": {
346
+ "origins": {
347
+ "type": "array",
348
+ "items": {
349
+ "type": "string"
350
+ },
351
+ "description": "Exact origins of child apps, such as `https://admin.shellui.com`. No wildcards."
352
+ },
353
+ "backendOrigins": {
354
+ "type": "array",
355
+ "items": {
356
+ "type": "string"
357
+ },
358
+ "description": "Exact origins of identity servers a child may sign in to, such as `https://id.eu.shellui.com`. The shell keeps a separate session per server and never sends its own token to a child. Omit to give children no token."
359
+ }
360
+ },
361
+ "required": ["origins"],
362
+ "additionalProperties": false,
363
+ "description": "Child apps an embedded app may host, and the identity servers they may use."
364
+ },
339
365
  "EmailConfig": {
340
366
  "type": "object",
341
367
  "properties": {
@@ -0,0 +1,172 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import type { ShellUIConfig } from '../../config/types';
3
+ import {
4
+ addChildFrame,
5
+ clearChildFrames,
6
+ findChildFrame,
7
+ listChildFrames,
8
+ removeChildFrame,
9
+ validateChildFrameRegistration,
10
+ } from './childFrames';
11
+ import { childFrameAuthPropagationOptions } from './frameAuth';
12
+ import type { AuthSession } from '../types';
13
+
14
+ const config: ShellUIConfig = {
15
+ backend: { type: 'shellui', url: 'https://id.example.com', companyId: 1 },
16
+ navigation: [
17
+ {
18
+ label: 'Dashboard',
19
+ path: '',
20
+ url: 'https://dashboard.example.com/',
21
+ safeForAuthToken: true,
22
+ childFrames: {
23
+ origins: ['https://admin.example.com', 'https://*.example.com', '*'],
24
+ backendOrigins: ['https://id.eu.example.com'],
25
+ },
26
+ },
27
+ { label: 'Other', path: 'other', url: 'https://other.example.com/' },
28
+ ],
29
+ };
30
+
31
+ const host = 'https://dashboard.example.com/';
32
+ const good = {
33
+ frameId: 'child-1',
34
+ url: 'https://admin.example.com/companies?x=1',
35
+ backend: { url: 'https://id.eu.example.com', companyId: 'abc' },
36
+ };
37
+
38
+ afterEach(() => clearChildFrames());
39
+
40
+ describe('validateChildFrameRegistration', () => {
41
+ it('accepts an allowed child and backend', () => {
42
+ const result = validateChildFrameRegistration({
43
+ from: ['h1'],
44
+ hostSrc: host,
45
+ payload: good,
46
+ config,
47
+ });
48
+ expect(result.ok).toBe(true);
49
+ if (!result.ok) return;
50
+ expect(result.entry.hostUuid).toBe('h1');
51
+ expect(result.entry.identity?.url).toBe('https://id.eu.example.com');
52
+ expect(result.entry.identity?.companyId).toBe('abc');
53
+ });
54
+
55
+ it('rejects a message relayed from deeper than one hop', () => {
56
+ const result = validateChildFrameRegistration({
57
+ from: ['h1', 'child'],
58
+ hostSrc: host,
59
+ payload: good,
60
+ config,
61
+ });
62
+ expect(result).toEqual({ ok: false, reason: 'not sent by a direct app frame' });
63
+ });
64
+
65
+ it('rejects hosts without childFrames', () => {
66
+ const result = validateChildFrameRegistration({
67
+ from: ['h1'],
68
+ hostSrc: 'https://other.example.com/',
69
+ payload: good,
70
+ config,
71
+ });
72
+ expect(result.ok).toBe(false);
73
+ });
74
+
75
+ it('only matches exact origins, never wildcards', () => {
76
+ for (const url of [
77
+ 'https://evil.example.com/',
78
+ 'https://admin.example.com.evil.io/',
79
+ 'javascript:alert(1)',
80
+ ]) {
81
+ const result = validateChildFrameRegistration({
82
+ from: ['h1'],
83
+ hostSrc: host,
84
+ payload: { ...good, url },
85
+ config,
86
+ });
87
+ expect(result.ok).toBe(false);
88
+ }
89
+ });
90
+
91
+ it('rejects a backend that is not allowlisted', () => {
92
+ const result = validateChildFrameRegistration({
93
+ from: ['h1'],
94
+ hostSrc: host,
95
+ payload: { ...good, backend: { url: 'https://id.example.com' } },
96
+ config,
97
+ });
98
+ expect(result).toEqual({ ok: false, reason: 'child identity server is not allowed' });
99
+ });
100
+
101
+ it('accepts a child without backend and gives it no identity', () => {
102
+ const result = validateChildFrameRegistration({
103
+ from: ['h1'],
104
+ hostSrc: host,
105
+ payload: { ...good, backend: null },
106
+ config,
107
+ });
108
+ expect(result.ok && result.entry.identity).toBeNull();
109
+ });
110
+ });
111
+
112
+ describe('child frame registry', () => {
113
+ it('finds by host and child path, and drops entries for gone hosts', () => {
114
+ const result = validateChildFrameRegistration({
115
+ from: ['h1'],
116
+ hostSrc: host,
117
+ payload: good,
118
+ config,
119
+ });
120
+ if (!result.ok) throw new Error(result.reason);
121
+ addChildFrame(result.entry);
122
+ expect(findChildFrame(['h1', 'child-1'])).toBe(result.entry);
123
+ expect(findChildFrame(['h1'])).toBeNull();
124
+ expect(findChildFrame(['h2', 'child-1'])).toBeNull();
125
+ expect(listChildFrames(() => false)).toEqual([]);
126
+ expect(findChildFrame(['h1', 'child-1'])).toBeNull();
127
+ addChildFrame(result.entry);
128
+ removeChildFrame('h1', 'child-1');
129
+ expect(findChildFrame(['h1', 'child-1'])).toBeNull();
130
+ });
131
+ });
132
+
133
+ describe('childFrameAuthPropagationOptions', () => {
134
+ const session = {
135
+ accessToken: 'regional-token',
136
+ refreshToken: 'r',
137
+ expiresAt: 9999999999,
138
+ userId: 'u1',
139
+ userEmail: 'a@b.c',
140
+ userName: 'A',
141
+ } as AuthSession;
142
+
143
+ it('sends the regional session and backend, and no shared services', () => {
144
+ const result = validateChildFrameRegistration({
145
+ from: ['h1'],
146
+ hostSrc: host,
147
+ payload: good,
148
+ config,
149
+ });
150
+ if (!result.ok) throw new Error(result.reason);
151
+ const options = childFrameAuthPropagationOptions({
152
+ identity: result.entry.identity,
153
+ getAppSession: (key) => (key === result.entry.identity?.key ? session : null),
154
+ });
155
+ expect(options.accessToken).toBe('regional-token');
156
+ expect(options.authBackendBaseUrl).toBe('https://id.eu.example.com');
157
+ expect(options.settingsUser?.id).toBe('u1');
158
+ expect(options.storage).toBeNull();
159
+ expect(options.email).toBeNull();
160
+ expect(options.hosting).toBeNull();
161
+ });
162
+
163
+ it('sends no token when the child has no identity', () => {
164
+ const options = childFrameAuthPropagationOptions({
165
+ identity: null,
166
+ getAppSession: () => session,
167
+ });
168
+ expect(options.accessToken).toBeNull();
169
+ expect(options.includeAuthAccessToken).toBe(false);
170
+ expect(options.settingsUser).toBeNull();
171
+ });
172
+ });
@@ -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);
@@ -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.
@@ -19,8 +19,21 @@ import {
19
19
  import { SettingsContext } from './SettingsContext';
20
20
  import { useConfig } from '../config/useConfig';
21
21
  import { useAuth } from '../auth/hooks/useAuth';
22
- import { frameAuthPropagationOptions } from '../auth/appBackend/frameAuth';
23
22
  import {
23
+ childFrameAuthPropagationOptions,
24
+ frameAuthPropagationOptions,
25
+ } from '../auth/appBackend/frameAuth';
26
+ import {
27
+ addChildFrame,
28
+ findChildFrame,
29
+ listChildFrames,
30
+ removeChildFrame,
31
+ validateChildFrameRegistration,
32
+ type ChildFrameEntry,
33
+ } from '../auth/appBackend/childFrames';
34
+ import { resolveFrameNavigationItem } from '../auth/appBackend/identity';
35
+ import {
36
+ ensureAppBackendSession,
24
37
  getAppBackendSession,
25
38
  refreshAppBackendSessionIfDue,
26
39
  subscribeAppBackendSessions,
@@ -211,10 +224,44 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
211
224
  [config],
212
225
  );
213
226
 
227
+ /** Settings for a child app hosted by an embedded app. Never carries the shell token. */
228
+ const pushSettingsToChildFrame = useCallback(
229
+ (entry: ChildFrameEntry | null, path: string[], baseSettings: Settings) => {
230
+ const lang = baseSettings.language?.code || 'en';
231
+ const settingsToPropagate = buildSettingsForPropagation(baseSettings, config, lang, {
232
+ ...childFrameAuthPropagationOptions({
233
+ identity: entry?.identity ?? null,
234
+ getAppSession: getAppBackendSession,
235
+ }),
236
+ includeLayoutChrome: false,
237
+ frameUuid: path[path.length - 1],
238
+ });
239
+ shellui.sendMessage({
240
+ type: 'SHELLUI_SETTINGS',
241
+ payload: { settings: settingsToPropagate },
242
+ to: path,
243
+ });
244
+ },
245
+ [config],
246
+ );
247
+
248
+ const propagateSettingsToChildFrames = useCallback(
249
+ (baseSettings: Settings) => {
250
+ const live = new Set(shellui.frameRegistry.getLiveIframes().map(([uuid]) => uuid));
251
+ const known = new Set(shellui.frameRegistry.getAllIframes().map(([uuid]) => uuid));
252
+ for (const entry of listChildFrames((uuid) => known.has(uuid))) {
253
+ if (!live.has(entry.hostUuid)) continue;
254
+ pushSettingsToChildFrame(entry, [entry.hostUuid, entry.frameId], baseSettings);
255
+ }
256
+ },
257
+ [pushSettingsToChildFrame],
258
+ );
259
+
214
260
  const propagateSettingsToIframes = useCallback(
215
261
  (baseSettings: Settings) => {
216
262
  const iframes = shellui.frameRegistry.getLiveIframes();
217
263
  if (iframes.length === 0) return;
264
+ propagateSettingsToChildFrames(baseSettings);
218
265
  const lang = baseSettings.language?.code || 'en';
219
266
  for (const [uuid, iframe] of iframes) {
220
267
  const frameSrc = iframe?.src ?? '';
@@ -230,7 +277,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
230
277
  });
231
278
  }
232
279
  },
233
- [authOptionsForFrame, config],
280
+ [authOptionsForFrame, config, propagateSettingsToChildFrames],
234
281
  );
235
282
 
236
283
  const pushSettingsToFrame = useCallback(
@@ -502,6 +549,26 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
502
549
  .getAllIframes()
503
550
  .find(([uuid]) => uuid === firstHopIframeUuid)?.[1]
504
551
  : undefined;
552
+ // A child app hosted by an embedded app gets its own session, never the host's.
553
+ const childEntry = findChildFrame(requestingPath);
554
+ const hostEmbedsApps = Boolean(
555
+ requestingFrame?.src &&
556
+ resolveFrameNavigationItem(requestingFrame.src, config)?.childFrames,
557
+ );
558
+ const isHostedChild = requestingPath.length > 1 && (childEntry || hostEmbedsApps);
559
+ if (isHostedChild) {
560
+ if (childEntry?.identity) {
561
+ await ensureAppBackendSession(childEntry.identity, { allowSilent: true });
562
+ }
563
+ deliverSessionHandoff(() =>
564
+ pushSettingsToChildFrame(
565
+ childEntry,
566
+ requestingPath,
567
+ settingsRef.current ?? defaultSettings,
568
+ ),
569
+ );
570
+ return;
571
+ }
505
572
  if (requestingFrame?.src) {
506
573
  await refreshAppBackendSessionIfDue(requestingFrame.src, config);
507
574
  }
@@ -589,13 +656,61 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
589
656
  },
590
657
  );
591
658
 
659
+ const cleanupChildRegister = shellui.addMessageListener(
660
+ 'SHELLUI_CHILD_FRAME_REGISTER',
661
+ (message: ShellUIMessage) => {
662
+ if (typeof window === 'undefined' || window.parent !== window) return;
663
+ const from = (message.from ?? []).filter(Boolean);
664
+ const hostSrc = shellui.frameRegistry
665
+ .getAllIframes()
666
+ .find(([uuid]) => uuid === from[0])?.[1]?.src;
667
+ const result = validateChildFrameRegistration({
668
+ from,
669
+ hostSrc,
670
+ payload: message.payload,
671
+ config,
672
+ });
673
+ if (!result.ok) {
674
+ logger.warn('Rejected a child app frame', { reason: result.reason });
675
+ return;
676
+ }
677
+ addChildFrame(result.entry);
678
+ const { entry } = result;
679
+ void (async () => {
680
+ if (entry.identity) {
681
+ await ensureAppBackendSession(entry.identity, { allowSilent: true });
682
+ }
683
+ deliverSessionHandoff(() =>
684
+ pushSettingsToChildFrame(
685
+ entry,
686
+ [entry.hostUuid, entry.frameId],
687
+ settingsRef.current ?? defaultSettings,
688
+ ),
689
+ );
690
+ })();
691
+ },
692
+ );
693
+
694
+ const cleanupChildUnregister = shellui.addMessageListener(
695
+ 'SHELLUI_CHILD_FRAME_UNREGISTER',
696
+ (message: ShellUIMessage) => {
697
+ const from = (message.from ?? []).filter(Boolean);
698
+ const frameId = (message.payload as { frameId?: unknown } | null)?.frameId;
699
+ if (from.length !== 1 || typeof frameId !== 'string') return;
700
+ removeChildFrame(from[0], frameId);
701
+ },
702
+ );
703
+
592
704
  return () => {
593
705
  cleanup();
594
706
  cleanupSettings();
595
707
  cleanupSettingsRequested();
596
708
  cleanupInitialized();
709
+ cleanupChildRegister();
710
+ cleanupChildUnregister();
597
711
  };
598
712
  }, [
713
+ pushSettingsToChildFrame,
599
714
  authOptionsForFrame,
600
715
  config,
601
716
  applyHandoffToken,
package/src/index.ts CHANGED
@@ -27,6 +27,7 @@ export type {
27
27
  BackendType,
28
28
  BackendConfig,
29
29
  AppBackendConfig,
30
+ ChildFramesConfig,
30
31
  AuthConfig,
31
32
  AdministrationConfig,
32
33
  StorageConfig,
@@ -61,7 +61,7 @@ export function useNavigationItems() {
61
61
  const navHashPath = getHashPathFromUrl(navigationItem.url).replace(/^\/+|\/+$/g, '');
62
62
  const segments = [navHashPath, subPath].filter(Boolean);
63
63
  const fullHashPath = `/${segments.join('/')}`;
64
- return `${base}#${fullHashPath}`;
64
+ return `${base}#${fullHashPath}${location.search}`;
65
65
  }
66
66
 
67
67
  let finalUrl = navigationItem.url;
@@ -71,8 +71,9 @@ export function useNavigationItems() {
71
71
  : `${navigationItem.url}/`;
72
72
  finalUrl = `${baseUrl}${subPath}`;
73
73
  }
74
- return finalUrl;
75
- }, [navigationItem, location.pathname]);
74
+ // Deep links keep their query (`/app/users?page=2` opens the app at `?page=2`).
75
+ return withShellSearch(finalUrl, location.search);
76
+ }, [navigationItem, location.pathname, location.search]);
76
77
 
77
78
  return {
78
79
  url,
@@ -82,3 +83,13 @@ export function useNavigationItems() {
82
83
  navigationItems,
83
84
  };
84
85
  }
86
+
87
+ /** Adds the shell query to an app URL, before any hash. */
88
+ export function withShellSearch(url: string, search: string): string {
89
+ const query = search.replace(/^\?/, '');
90
+ if (!query) return url;
91
+ const hashAt = url.indexOf('#');
92
+ const beforeHash = hashAt >= 0 ? url.slice(0, hashAt) : url;
93
+ const hash = hashAt >= 0 ? url.slice(hashAt) : '';
94
+ return `${beforeHash}${beforeHash.includes('?') ? '&' : '?'}${query}${hash}`;
95
+ }
@@ -0,0 +1,13 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { withShellSearch } from './useNavigationItems';
3
+
4
+ describe('withShellSearch', () => {
5
+ it('keeps the deep-link query', () => {
6
+ expect(withShellSearch('/app/users/7', '?tab=x')).toBe('/app/users/7?tab=x');
7
+ expect(withShellSearch('https://a.example/x?a=1', '?b=2')).toBe('https://a.example/x?a=1&b=2');
8
+ expect(withShellSearch('https://a.example/#/users', '?b=2')).toBe(
9
+ 'https://a.example/?b=2#/users',
10
+ );
11
+ expect(withShellSearch('/app', '')).toBe('/app');
12
+ });
13
+ });