@shellui/core 0.6.2 → 0.7.0-alpha.10

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 (85) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +147 -70
  3. package/src/app.tsx +2 -0
  4. package/src/components/ContentView.tsx +21 -30
  5. package/src/components/iframeUrlSafety.spec.ts +67 -0
  6. package/src/components/iframeUrlSafety.ts +50 -0
  7. package/src/components/ui/sidebar.tsx +11 -5
  8. package/src/features/admin/AdminView.tsx +9 -6
  9. package/src/features/auth/AuthProvider.tsx +49 -5
  10. package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
  11. package/src/features/auth/appBackend/appBackendSessions.spec.ts +329 -0
  12. package/src/features/auth/appBackend/appBackendSessions.ts +443 -0
  13. package/src/features/auth/appBackend/childFrames.spec.ts +328 -0
  14. package/src/features/auth/appBackend/childFrames.ts +180 -0
  15. package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
  16. package/src/features/auth/appBackend/frameAuth.ts +204 -0
  17. package/src/features/auth/appBackend/identity.spec.ts +201 -0
  18. package/src/features/auth/appBackend/identity.ts +173 -0
  19. package/src/features/auth/appBackend/silentSignIn.spec.ts +225 -0
  20. package/src/features/auth/appBackend/silentSignIn.ts +254 -0
  21. package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
  22. package/src/features/auth/appBackend/tokenExchange.ts +76 -0
  23. package/src/features/auth/backends/shellui.spec.ts +51 -19
  24. package/src/features/auth/backends/shellui.ts +20 -5
  25. package/src/features/auth/backends/types.ts +7 -2
  26. package/src/features/auth/components/LoginView.tsx +40 -18
  27. package/src/features/auth/components/OAuthCallbackView.tsx +33 -4
  28. package/src/features/auth/utils/authRequestError.ts +3 -0
  29. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
  30. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
  31. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +29 -0
  32. package/src/features/auth/utils/canRestoreStoredSession.ts +12 -0
  33. package/src/features/auth/utils/index.ts +16 -1
  34. package/src/features/auth/utils/loginCancelTarget.spec.ts +73 -0
  35. package/src/features/auth/utils/loginCancelTarget.ts +45 -0
  36. package/src/features/auth/utils/loginPanelFrame.spec.ts +24 -0
  37. package/src/features/auth/utils/loginPanelFrame.ts +14 -0
  38. package/src/features/auth/utils/resolveSdkLoginRedirectPath.spec.ts +41 -0
  39. package/src/features/auth/utils/resolveSdkLoginRedirectPath.ts +31 -0
  40. package/src/features/auth/utils/webPkce.spec.ts +119 -0
  41. package/src/features/auth/utils/webPkce.ts +169 -0
  42. package/src/features/chromeActions/computeActionInsets.ts +7 -4
  43. package/src/features/config/types.ts +70 -3
  44. package/src/features/layouts/appbar/AppBarLayout.tsx +63 -30
  45. package/src/features/layouts/chrome/CollapsedDesktopTitlebar.tsx +12 -23
  46. package/src/features/layouts/chrome/ContentDragOverlay.tsx +5 -6
  47. package/src/features/layouts/chrome/DesktopChrome.tsx +37 -0
  48. package/src/features/layouts/chrome/DesktopHistoryButtons.tsx +15 -4
  49. package/src/features/layouts/chrome/MacStrip.tsx +33 -0
  50. package/src/features/layouts/chrome/constants.ts +33 -8
  51. package/src/features/layouts/chrome/index.ts +8 -0
  52. package/src/features/layouts/chrome/stripDragMap.ts +35 -0
  53. package/src/features/layouts/chrome/stripNoDrag.spec.tsx +103 -0
  54. package/src/features/layouts/chrome/useScrollHideChrome.ts +3 -8
  55. package/src/features/layouts/filterNavigationForAuthState.spec.ts +5 -3
  56. package/src/features/layouts/floating/FloatingBottomDock.tsx +199 -20
  57. package/src/features/layouts/floating/FloatingLayout.tsx +13 -8
  58. package/src/features/layouts/floating/FloatingSidebar.tsx +144 -70
  59. package/src/features/layouts/floating/computeFloatingInsets.ts +22 -4
  60. package/src/features/layouts/floating/useFloatingChrome.ts +3 -1
  61. package/src/features/layouts/floating/useSoftKeyboard.spec.ts +39 -0
  62. package/src/features/layouts/floating/useSoftKeyboard.ts +82 -0
  63. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +38 -10
  64. package/src/features/layouts/sidebar/NavigationContent.tsx +14 -6
  65. package/src/features/layouts/sidebar/SidebarIcons.tsx +3 -9
  66. package/src/features/layouts/sidebar/SidebarInner.tsx +50 -39
  67. package/src/features/layouts/sidebar/SidebarLayout.tsx +8 -11
  68. package/src/features/layouts/utils.ts +4 -3
  69. package/src/features/layouts/windows/DesktopDots.tsx +76 -0
  70. package/src/features/layouts/windows/WindowsLayout.tsx +184 -125
  71. package/src/features/layouts/windows/deskDots.spec.ts +52 -0
  72. package/src/features/layouts/windows/deskDots.ts +314 -0
  73. package/src/features/settings/SettingsProvider.tsx +198 -29
  74. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +379 -4
  75. package/src/features/settings/utils/buildSettingsForPropagation.ts +65 -39
  76. package/src/features/theme/applyTheme.ts +8 -0
  77. package/src/features/theme/navContrast.spec.ts +49 -0
  78. package/src/features/theme/navContrast.ts +108 -0
  79. package/src/features/transfers/transferQueue.spec.ts +6 -2
  80. package/src/i18n/translations/en/common.json +27 -0
  81. package/src/i18n/translations/fr/common.json +27 -0
  82. package/src/index.css +935 -46
  83. package/src/index.ts +2 -0
  84. package/src/routes/hooks/useNavigationItems.ts +14 -3
  85. package/src/routes/hooks/withShellSearch.spec.ts +13 -0
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Windows layout desktop: calm dot field on a canvas.
3
+ * Ported from the layouts redesign reference (`desk-dots.js`), itself derived from
4
+ * the shellui.com hero dots: three to four times slower, half the travel, no pointer play.
5
+ * Decorative only. The caller mounts it on an `aria-hidden` host.
6
+ */
7
+ export const DESK_DOTS = {
8
+ /** Grid spacing in px (same as the website). */
9
+ spacing: 24,
10
+ /** Dot radius in px. */
11
+ radius: 1.1,
12
+ /** Base alpha of `--foreground` in light mode. */
13
+ alphaLight: 0.15,
14
+ /** Base alpha of `--foreground` in dark mode. */
15
+ alphaDark: 0.11,
16
+ /** One dot in this many is tinted with `--primary`. */
17
+ accentEvery: 11,
18
+ /** Accent base alpha; rises with the gust. */
19
+ accentAlpha: 0.22,
20
+ /** Extra alpha at full displacement. */
21
+ gustLift: 0.16,
22
+ /** Max displacement in px. */
23
+ gustPx: 3.5,
24
+ /** Width of a wind front in px. */
25
+ frontWidth: 170,
26
+ /** Front slant in degrees. */
27
+ slantDeg: 18,
28
+ /** Time for one front to cross the desktop, ms range. */
29
+ crossMs: [30000, 40000] as const,
30
+ /** Gap between fronts, ms range. */
31
+ everyMs: [9000, 15000] as const,
32
+ spring: 0.035,
33
+ damp: 0.88,
34
+ /** Frame cap. */
35
+ fps: 30,
36
+ /** Device pixel ratio cap. */
37
+ dprMax: 2,
38
+ } as const;
39
+
40
+ export type DeskDotsOptions = Partial<{
41
+ [K in keyof typeof DESK_DOTS]: (typeof DESK_DOTS)[K] extends readonly [number, number]
42
+ ? readonly [number, number]
43
+ : number;
44
+ }>;
45
+
46
+ export interface DeskDotsHandle {
47
+ /** True while the desktop is covered (maximized window) or a window is dragged or resized. */
48
+ pause: (paused: boolean) => void;
49
+ /** Draw count and total draw time, for profiling. */
50
+ stats: { frames: number; ms: number };
51
+ destroy: () => void;
52
+ }
53
+
54
+ type Rgb = [number, number, number];
55
+
56
+ const BUCKETS = 6;
57
+
58
+ /** Alpha for a bucket: base dots and accent dots rise with the gust. */
59
+ export function bucketAlpha(
60
+ accent: boolean,
61
+ bucket: number,
62
+ dark: boolean,
63
+ p: { alphaLight: number; alphaDark: number; accentAlpha: number; gustLift: number } = DESK_DOTS,
64
+ ): number {
65
+ const m = (bucket + 0.5) / BUCKETS;
66
+ if (accent) return p.accentAlpha + p.gustLift * 1.6 * m;
67
+ return (dark ? p.alphaDark : p.alphaLight) + p.gustLift * m;
68
+ }
69
+
70
+ /** Grid size for a host box: columns and rows of dots. */
71
+ export function gridSize(width: number, height: number, spacing: number = DESK_DOTS.spacing) {
72
+ const cols = Math.max(0, Math.ceil(width / spacing));
73
+ const rows = Math.max(0, Math.ceil(height / spacing));
74
+ return { cols, rows, count: cols * rows };
75
+ }
76
+
77
+ /** Same 1 in N pattern as the reference: stable across relayouts. */
78
+ export function isAccentDot(col: number, row: number, every: number = DESK_DOTS.accentEvery) {
79
+ return (col * 7 + row * 3) % every === 0;
80
+ }
81
+
82
+ export function mountDeskDots(host: HTMLElement, opts: DeskDotsOptions = {}): DeskDotsHandle {
83
+ const P = { ...DESK_DOTS, ...opts };
84
+ const stats = { frames: 0, ms: 0 };
85
+ const canvas = document.createElement('canvas');
86
+ canvas.setAttribute('aria-hidden', 'true');
87
+ canvas.style.position = 'absolute';
88
+ canvas.style.inset = '0';
89
+ canvas.style.width = '100%';
90
+ canvas.style.height = '100%';
91
+ canvas.style.pointerEvents = 'none';
92
+ const ctx = canvas.getContext('2d', { alpha: true });
93
+ if (!ctx) {
94
+ return { pause: () => {}, stats, destroy: () => {} };
95
+ }
96
+ host.appendChild(canvas);
97
+ host.setAttribute('data-live', 'true');
98
+
99
+ const slant = Math.tan((P.slantDeg * Math.PI) / 180);
100
+ const smooth = (t: number) => t * t * (3 - 2 * t);
101
+ const rnd = (a: number, b: number) => a + Math.random() * (b - a);
102
+
103
+ let w = 0;
104
+ let h = 0;
105
+ let n = 0;
106
+ let X = new Float32Array(0);
107
+ let Y = new Float32Array(0);
108
+ let OX = new Float32Array(0);
109
+ let OY = new Float32Array(0);
110
+ let VX = new Float32Array(0);
111
+ let VY = new Float32Array(0);
112
+ let S = new Float32Array(0);
113
+ let PH = new Float32Array(0);
114
+ let AC = new Uint8Array(0);
115
+ let fronts: { t: number; v: number; x: number }[] = [];
116
+ let nextAt = 0;
117
+ let raf = 0;
118
+ let last = 0;
119
+ let paused = false;
120
+ let settled = false;
121
+ let destroyed = false;
122
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
123
+ let layoutTimer: ReturnType<typeof setTimeout> | undefined;
124
+ let fg: Rgb = [17, 24, 39];
125
+ let pr: Rgb = [227, 165, 18];
126
+ let dark = false;
127
+
128
+ // Theme colours: resolve any CSS colour (oklch included) through a 1 x 1 canvas.
129
+ const probe = document.createElement('canvas');
130
+ probe.width = 1;
131
+ probe.height = 1;
132
+ const pctx = probe.getContext('2d', { willReadFrequently: true });
133
+ const toRgb = (css: string, fallback: Rgb): Rgb => {
134
+ if (!pctx || !css) return fallback;
135
+ pctx.clearRect(0, 0, 1, 1);
136
+ pctx.fillStyle = '#000';
137
+ pctx.fillStyle = css;
138
+ pctx.fillRect(0, 0, 1, 1);
139
+ const d = pctx.getImageData(0, 0, 1, 1).data;
140
+ return [d[0], d[1], d[2]];
141
+ };
142
+
143
+ const paths: Path2D[] = new Array(BUCKETS * 2);
144
+ function draw() {
145
+ if (!ctx) return;
146
+ const t0 = performance.now();
147
+ ctx.clearRect(0, 0, w, h);
148
+ for (let k = 0; k < paths.length; k++) paths[k] = new Path2D();
149
+ for (let i = 0; i < n; i++) {
150
+ const m = Math.min(1, Math.hypot(OX[i], OY[i]) / P.gustPx);
151
+ const b = Math.min(BUCKETS - 1, (m * BUCKETS) | 0);
152
+ const p = paths[AC[i] * BUCKETS + b];
153
+ const x = X[i] + OX[i];
154
+ const y = Y[i] + OY[i];
155
+ p.moveTo(x + P.radius, y);
156
+ p.arc(x, y, P.radius, 0, Math.PI * 2);
157
+ }
158
+ for (let a = 0; a < 2; a++) {
159
+ const c = a ? pr : fg;
160
+ for (let b = 0; b < BUCKETS; b++) {
161
+ const al = bucketAlpha(a === 1, b, dark, P);
162
+ ctx.fillStyle = `rgba(${c[0]},${c[1]},${c[2]},${al.toFixed(3)})`;
163
+ ctx.fill(paths[a * BUCKETS + b]);
164
+ }
165
+ }
166
+ stats.frames++;
167
+ stats.ms += performance.now() - t0;
168
+ }
169
+
170
+ function readTheme() {
171
+ const cs = getComputedStyle(host);
172
+ fg = toRgb(cs.getPropertyValue('--foreground').trim(), fg);
173
+ pr = toRgb(cs.getPropertyValue('--primary').trim(), pr);
174
+ dark = document.documentElement.classList.contains('dark');
175
+ settled = false;
176
+ draw();
177
+ }
178
+
179
+ function layout() {
180
+ if (!ctx) return;
181
+ const dpr = Math.min(window.devicePixelRatio || 1, P.dprMax);
182
+ w = host.clientWidth;
183
+ h = host.clientHeight;
184
+ canvas.width = Math.round(w * dpr);
185
+ canvas.height = Math.round(h * dpr);
186
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
187
+ const { cols, rows, count } = gridSize(w, h, P.spacing);
188
+ n = count;
189
+ X = new Float32Array(n);
190
+ Y = new Float32Array(n);
191
+ OX = new Float32Array(n);
192
+ OY = new Float32Array(n);
193
+ VX = new Float32Array(n);
194
+ VY = new Float32Array(n);
195
+ S = new Float32Array(n);
196
+ PH = new Float32Array(n);
197
+ AC = new Uint8Array(n);
198
+ const x0 = (w - (cols - 1) * P.spacing) / 2;
199
+ const y0 = P.spacing / 2;
200
+ let i = 0;
201
+ for (let r = 0; r < rows; r++) {
202
+ for (let c = 0; c < cols; c++, i++) {
203
+ X[i] = x0 + c * P.spacing;
204
+ Y[i] = y0 + r * P.spacing;
205
+ S[i] = 0.6 + Math.random() * 0.4;
206
+ PH[i] = Math.random() * Math.PI * 2;
207
+ AC[i] = isAccentDot(c, r, P.accentEvery) ? 1 : 0;
208
+ }
209
+ }
210
+ settled = false;
211
+ draw();
212
+ kick();
213
+ }
214
+
215
+ function step(now: number) {
216
+ raf = 0;
217
+ if (paused || destroyed || document.hidden) return;
218
+ if (now - last < 1000 / P.fps - 1) {
219
+ raf = requestAnimationFrame(step);
220
+ return;
221
+ }
222
+ last = now;
223
+ if (!nextAt) nextAt = now + rnd(800, 2500);
224
+ if (now >= nextAt) {
225
+ fronts.push({
226
+ t: now,
227
+ v: (w + 2 * P.frontWidth + h * slant) / rnd(P.crossMs[0], P.crossMs[1]),
228
+ x: 0,
229
+ });
230
+ nextAt = now + rnd(P.everyMs[0], P.everyMs[1]);
231
+ }
232
+ for (const f of fronts) f.x = (now - f.t) * f.v - P.frontWidth - h * slant;
233
+ fronts = fronts.filter((f) => f.x < w + P.frontWidth);
234
+ let energy = 0;
235
+ for (let i = 0; i < n; i++) {
236
+ let tx = 0;
237
+ let ty = 0;
238
+ for (const f of fronts) {
239
+ const k = 1 - Math.abs(X[i] - f.x - (h - Y[i]) * slant) / P.frontWidth;
240
+ if (k > 0) {
241
+ const g = P.gustPx * S[i] * smooth(k);
242
+ tx += g;
243
+ ty += g * 0.25 * Math.sin(PH[i]);
244
+ }
245
+ }
246
+ VX[i] = (VX[i] + (tx - OX[i]) * P.spring) * P.damp;
247
+ VY[i] = (VY[i] + (ty - OY[i]) * P.spring) * P.damp;
248
+ OX[i] += VX[i];
249
+ OY[i] += VY[i];
250
+ energy += Math.abs(VX[i]) + Math.abs(VY[i]) + Math.abs(OX[i]);
251
+ }
252
+ // Idle: no front on screen and every dot at rest. Stop until the next front.
253
+ if (!fronts.length && energy < n * 0.002) {
254
+ if (!settled) {
255
+ OX.fill(0);
256
+ OY.fill(0);
257
+ draw();
258
+ settled = true;
259
+ }
260
+ clearTimeout(idleTimer);
261
+ idleTimer = setTimeout(kick, Math.max(0, nextAt - performance.now()));
262
+ return;
263
+ }
264
+ settled = false;
265
+ draw();
266
+ raf = requestAnimationFrame(step);
267
+ }
268
+
269
+ function kick() {
270
+ if (!raf && !paused && !destroyed && !document.hidden) raf = requestAnimationFrame(step);
271
+ }
272
+
273
+ function stop() {
274
+ cancelAnimationFrame(raf);
275
+ raf = 0;
276
+ }
277
+
278
+ const ro =
279
+ typeof ResizeObserver !== 'undefined'
280
+ ? new ResizeObserver(() => {
281
+ clearTimeout(layoutTimer);
282
+ layoutTimer = setTimeout(layout, 150);
283
+ })
284
+ : null;
285
+ ro?.observe(host);
286
+ // applyTheme writes vars inline on <html>, so watch style as well as class.
287
+ const mo = new MutationObserver(readTheme);
288
+ mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });
289
+ const onVisibility = () => (document.hidden ? stop() : kick());
290
+ document.addEventListener('visibilitychange', onVisibility);
291
+
292
+ readTheme();
293
+ layout();
294
+
295
+ return {
296
+ pause(value: boolean) {
297
+ paused = value;
298
+ if (paused) stop();
299
+ else kick();
300
+ },
301
+ stats,
302
+ destroy() {
303
+ destroyed = true;
304
+ stop();
305
+ clearTimeout(idleTimer);
306
+ clearTimeout(layoutTimer);
307
+ ro?.disconnect();
308
+ mo.disconnect();
309
+ document.removeEventListener('visibilitychange', onVisibility);
310
+ canvas.remove();
311
+ host.removeAttribute('data-live');
312
+ },
313
+ };
314
+ }
@@ -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,7 +20,36 @@ import {
19
20
  import { SettingsContext } from './SettingsContext';
20
21
  import { useConfig } from '../config/useConfig';
21
22
  import { useAuth } from '../auth/hooks/useAuth';
22
- import { isTrustedFrameForAuthToken } from '../security/trustedFrames';
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,
49
+ getAppBackendSession,
50
+ refreshAppBackendSessionIfDue,
51
+ subscribeAppBackendSessions,
52
+ } from '../auth/appBackend/appBackendSessions';
23
53
  import { isMainLayoutFrame } from '../layouts/floating/layoutChromeStore';
24
54
  import { defaultTheme } from '../theme/themes';
25
55
  import {
@@ -192,26 +222,64 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
192
222
  return defaultSettings;
193
223
  });
194
224
 
195
- const isTrustedFrameForAuthTokenCallback = useCallback(
196
- (frameSrc: string): boolean => isTrustedFrameForAuthToken(frameSrc, config),
225
+ const accessTokenRef = useRef<string | null>(session?.accessToken ?? null);
226
+ accessTokenRef.current = session?.accessToken ?? null;
227
+
228
+ const authOptionsForFrame = useCallback(
229
+ (frameSrc: string) =>
230
+ frameAuthPropagationOptions({
231
+ frameSrc,
232
+ config,
233
+ shellAccessToken: accessTokenRef.current,
234
+ getAppSession: getAppBackendSession,
235
+ }),
197
236
  [config],
198
237
  );
199
238
 
200
- const accessTokenRef = useRef<string | null>(session?.accessToken ?? null);
201
- accessTokenRef.current = session?.accessToken ?? null;
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
+ services: entry?.services ?? null,
248
+ }),
249
+ includeLayoutChrome: false,
250
+ frameUuid: path[path.length - 1],
251
+ });
252
+ shellui.sendMessage({
253
+ type: 'SHELLUI_SETTINGS',
254
+ payload: { settings: settingsToPropagate },
255
+ to: path,
256
+ });
257
+ },
258
+ [config],
259
+ );
260
+
261
+ const propagateSettingsToChildFrames = useCallback(
262
+ (baseSettings: Settings) => {
263
+ const live = new Set(shellui.frameRegistry.getLiveIframes().map(([uuid]) => uuid));
264
+ const known = new Set(shellui.frameRegistry.getAllIframes().map(([uuid]) => uuid));
265
+ for (const entry of listChildFrames((uuid) => known.has(uuid))) {
266
+ if (!live.has(entry.hostUuid)) continue;
267
+ pushSettingsToChildFrame(entry, [entry.hostUuid, entry.frameId], baseSettings);
268
+ }
269
+ },
270
+ [pushSettingsToChildFrame],
271
+ );
202
272
 
203
273
  const propagateSettingsToIframes = useCallback(
204
274
  (baseSettings: Settings) => {
205
275
  const iframes = shellui.frameRegistry.getLiveIframes();
206
276
  if (iframes.length === 0) return;
277
+ propagateSettingsToChildFrames(baseSettings);
207
278
  const lang = baseSettings.language?.code || 'en';
208
- const accessToken = accessTokenRef.current;
209
279
  for (const [uuid, iframe] of iframes) {
210
280
  const frameSrc = iframe?.src ?? '';
211
- const includeAuthAccessToken = isTrustedFrameForAuthTokenCallback(frameSrc);
212
281
  const settingsToPropagate = buildSettingsForPropagation(baseSettings, config, lang, {
213
- includeAuthAccessToken,
214
- accessToken,
282
+ ...authOptionsForFrame(frameSrc),
215
283
  includeLayoutChrome: isMainLayoutFrame(iframe),
216
284
  frameUuid: uuid,
217
285
  });
@@ -222,19 +290,17 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
222
290
  });
223
291
  }
224
292
  },
225
- [config, isTrustedFrameForAuthTokenCallback],
293
+ [authOptionsForFrame, config, propagateSettingsToChildFrames],
226
294
  );
227
295
 
228
296
  const pushSettingsToFrame = useCallback(
229
297
  (iframeUuid: string, frameSrc: string, baseSettings: Settings) => {
230
298
  const lang = baseSettings.language?.code || 'en';
231
- const includeAuthAccessToken = isTrustedFrameForAuthTokenCallback(frameSrc);
232
299
  const iframe = shellui.frameRegistry
233
300
  .getAllIframes()
234
301
  .find(([uuid]) => uuid === iframeUuid)?.[1];
235
302
  const settingsToPropagate = buildSettingsForPropagation(baseSettings, config, lang, {
236
- includeAuthAccessToken,
237
- accessToken: accessTokenRef.current,
303
+ ...authOptionsForFrame(frameSrc),
238
304
  includeLayoutChrome: isMainLayoutFrame(iframe),
239
305
  frameUuid: iframeUuid,
240
306
  });
@@ -244,7 +310,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
244
310
  to: [iframeUuid],
245
311
  });
246
312
  },
247
- [config, isTrustedFrameForAuthTokenCallback],
313
+ [authOptionsForFrame, config],
248
314
  );
249
315
 
250
316
  const applyHandoffToken = useCallback((token: string | null | undefined) => {
@@ -256,6 +322,13 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
256
322
  return deliverSessionHandoff(() => propagateSettingsToIframes(base));
257
323
  }, [propagateSettingsToIframes]);
258
324
 
325
+ useEffect(() => {
326
+ return subscribeAppBackendSessions(() => {
327
+ if (typeof window === 'undefined' || window.parent !== window) return;
328
+ handoffSettingsToIframes();
329
+ });
330
+ }, [handoffSettingsToIframes]);
331
+
259
332
  // When the shell rotates the JWT, `authUser` often does not change, so the user-sync effect
260
333
  // above skips — still push `SHELLUI_SETTINGS` so trusted iframes get the new `accessToken`.
261
334
  // The follow-up turn covers an app that subscribes after the first post.
@@ -482,28 +555,50 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
482
555
  // not the JWT that died while the tab was hidden.
483
556
  const token = await refreshFrameAccessTokenIfNeeded();
484
557
  applyHandoffToken(token);
558
+ const requestingPath = (message.from ?? []).filter(Boolean);
559
+ const [firstHopIframeUuid] = requestingPath;
560
+ const requestingFrame = firstHopIframeUuid
561
+ ? shellui.frameRegistry
562
+ .getAllIframes()
563
+ .find(([uuid]) => uuid === firstHopIframeUuid)?.[1]
564
+ : undefined;
565
+ // A child app hosted by an embedded app gets its own session, never the host's.
566
+ const childEntry = findChildFrame(requestingPath);
567
+ const hostEmbedsApps = Boolean(
568
+ requestingFrame?.src &&
569
+ resolveFrameNavigationItem(requestingFrame.src, config)?.childFrames,
570
+ );
571
+ const isHostedChild = requestingPath.length > 1 && (childEntry || hostEmbedsApps);
572
+ if (isHostedChild) {
573
+ if (childEntry?.identity) {
574
+ await ensureAppBackendSession(childEntry.identity, { allowSilent: true });
575
+ }
576
+ deliverSessionHandoff(() =>
577
+ pushSettingsToChildFrame(
578
+ childEntry,
579
+ requestingPath,
580
+ settingsRef.current ?? defaultSettings,
581
+ ),
582
+ );
583
+ return;
584
+ }
585
+ if (requestingFrame?.src) {
586
+ await refreshAppBackendSessionIfDue(requestingFrame.src, config);
587
+ }
485
588
 
486
589
  const send = () => {
487
590
  const currentSettings = settingsRef.current ?? defaultSettings;
488
- const requestingPath = (message.from ?? []).filter(Boolean);
489
591
 
490
592
  if (requestingPath.length > 0) {
491
- const [firstHopIframeUuid] = requestingPath;
492
- const frame = shellui.frameRegistry
493
- .getAllIframes()
494
- .find(([uuid]) => uuid === firstHopIframeUuid)?.[1];
495
593
  const lang = currentSettings.language?.code || 'en';
496
- const includeAuthAccessToken = frame
497
- ? isTrustedFrameForAuthTokenCallback(frame.src ?? '')
498
- : false;
594
+ const frameSrc = requestingFrame?.src ?? '';
499
595
  const settingsToPropagate = buildSettingsForPropagation(
500
596
  currentSettings,
501
597
  config,
502
598
  lang,
503
599
  {
504
- includeAuthAccessToken,
505
- accessToken: accessTokenRef.current,
506
- includeLayoutChrome: isMainLayoutFrame(frame),
600
+ ...authOptionsForFrame(frameSrc),
601
+ includeLayoutChrome: isMainLayoutFrame(requestingFrame),
507
602
  frameUuid: firstHopIframeUuid,
508
603
  },
509
604
  );
@@ -565,10 +660,71 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
565
660
  void (async () => {
566
661
  const token = await refreshFrameAccessTokenIfNeeded();
567
662
  applyHandoffToken(token);
663
+ const frameSrc = iframe?.src ?? '';
664
+ if (frameSrc) await refreshAppBackendSessionIfDue(frameSrc, config);
568
665
  deliverSessionHandoff(() =>
569
- pushSettingsToFrame(
570
- iframeUuid,
571
- iframe?.src ?? '',
666
+ pushSettingsToFrame(iframeUuid, frameSrc, settingsRef.current ?? defaultSettings),
667
+ );
668
+ })();
669
+ },
670
+ );
671
+
672
+ const cleanupChildRegister = shellui.addMessageListener(
673
+ 'SHELLUI_CHILD_FRAME_REGISTER',
674
+ (message: ShellUIMessage) => {
675
+ if (typeof window === 'undefined' || window.parent !== window) return;
676
+ const from = (message.from ?? []).filter(Boolean);
677
+ const hostSrc = shellui.frameRegistry
678
+ .getAllIframes()
679
+ .find(([uuid]) => uuid === from[0])?.[1]?.src;
680
+ const result = validateChildFrameRegistration({
681
+ from,
682
+ hostSrc,
683
+ payload: message.payload,
684
+ config,
685
+ });
686
+ if (!result.ok) {
687
+ logger.warn('Rejected a child app frame', { reason: result.reason });
688
+ return;
689
+ }
690
+ addChildFrame(result.entry);
691
+ const { entry } = result;
692
+ if (entry.rejectedServices.length) {
693
+ // Keys only: the URLs themselves stay out of the log.
694
+ logger.warn('Dropped child app service URLs not in childFrames.serviceOrigins', {
695
+ origin: safeOrigin(entry.url),
696
+ services: entry.rejectedServices,
697
+ });
698
+ }
699
+ logger.info('Child app frame registered', {
700
+ origin: safeOrigin(entry.url),
701
+ identity: entry.identity?.url ?? null,
702
+ companyId: entry.identity?.companyId ?? null,
703
+ });
704
+ void (async () => {
705
+ let ok = true;
706
+ let reason: string | null = null;
707
+ if (entry.identity) {
708
+ // A (re)registration is a fresh mount or a user retry: allow one more silent try.
709
+ allowSilentRetry(entry.identity.key);
710
+ const token = await ensureAppBackendSession(entry.identity, { allowSilent: true });
711
+ ok = Boolean(token);
712
+ reason = ok ? null : (getAppBackendSessionFailure(entry.identity.key) ?? 'no_session');
713
+ }
714
+ shellui.sendMessage({
715
+ type: CHILD_FRAME_SESSION,
716
+ payload: {
717
+ frameId: entry.frameId,
718
+ ok,
719
+ ...(reason ? { reason, hint: describeAppSessionFailure(reason) } : {}),
720
+ } as unknown as ShellUIMessage['payload'],
721
+ to: [entry.hostUuid],
722
+ });
723
+ logger.info('Child app frame session', { origin: safeOrigin(entry.url), ok, reason });
724
+ deliverSessionHandoff(() =>
725
+ pushSettingsToChildFrame(
726
+ entry,
727
+ [entry.hostUuid, entry.frameId],
572
728
  settingsRef.current ?? defaultSettings,
573
729
  ),
574
730
  );
@@ -576,15 +732,28 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
576
732
  },
577
733
  );
578
734
 
735
+ const cleanupChildUnregister = shellui.addMessageListener(
736
+ 'SHELLUI_CHILD_FRAME_UNREGISTER',
737
+ (message: ShellUIMessage) => {
738
+ const from = (message.from ?? []).filter(Boolean);
739
+ const frameId = (message.payload as { frameId?: unknown } | null)?.frameId;
740
+ if (from.length !== 1 || typeof frameId !== 'string') return;
741
+ removeChildFrame(from[0], frameId);
742
+ },
743
+ );
744
+
579
745
  return () => {
580
746
  cleanup();
581
747
  cleanupSettings();
582
748
  cleanupSettingsRequested();
583
749
  cleanupInitialized();
750
+ cleanupChildRegister();
751
+ cleanupChildUnregister();
584
752
  };
585
753
  }, [
754
+ pushSettingsToChildFrame,
755
+ authOptionsForFrame,
586
756
  config,
587
- isTrustedFrameForAuthTokenCallback,
588
757
  applyHandoffToken,
589
758
  propagateSettingsToIframes,
590
759
  pushSettingsToFrame,