@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.
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.5",
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.5"
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": {
@@ -861,8 +861,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
861
861
  });
862
862
  } catch (err) {
863
863
  reply('error');
864
- const errorCode = getAuthRequestErrorCode(err);
865
- if (errorCode === 'last_company_owner') {
864
+ const deleteErrorCode = getAuthRequestErrorCode(err);
865
+ if (deleteErrorCode === 'last_company_owner') {
866
866
  const companies =
867
867
  err instanceof AuthRequestError && Array.isArray(err.details.companies)
868
868
  ? (err.details.companies as Array<{ name?: unknown }>)
@@ -880,7 +880,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
880
880
  });
881
881
  return;
882
882
  }
883
- if (errorCode === 'recent_login_required') {
883
+ if (deleteErrorCode === 'recent_login_required') {
884
884
  shellui.dialog({
885
885
  title: t('userAccount.deleteAccount.reauthTitle'),
886
886
  description: t('userAccount.deleteAccount.reauthDescription'),
@@ -11,6 +11,8 @@ import {
11
11
  getAppBackendSession,
12
12
  setAppBackendFactory,
13
13
  setAppBackendSignIn,
14
+ setAppBackendTokenExchange,
15
+ resetAppBackendTokenExchange,
14
16
  } from './appBackendSessions';
15
17
  import { resolveAppBackendConfig } from './identity';
16
18
  import { runSilentPkceSignIn } from './silentSignIn';
@@ -192,4 +194,136 @@ describe('app backend sessions', () => {
192
194
  );
193
195
  expect(dumped).not.toContain(APP_BACKEND_REFRESH_PREFIX);
194
196
  });
197
+
198
+ describe('token exchange for upstream identity servers', () => {
199
+ const exchange = vi.fn();
200
+ const jwt = (sub: string, jti: string) =>
201
+ `h.${btoa(JSON.stringify({ sub, jti })).replace(/=+$/, '')}.s`;
202
+ let shellToken: string | null = jwt('1', 'g1');
203
+
204
+ function upstream(companyId?: number) {
205
+ const identity = resolveAppBackendConfig(
206
+ { url: 'https://id.eu.example', companyId, provider: 'upstream', type: 'shellui' },
207
+ { backend: { type: 'shellui', url: 'https://id.example.com', companyId: 1 } },
208
+ );
209
+ if (!identity) throw new Error('expected identity');
210
+ return identity;
211
+ }
212
+
213
+ function due(accessToken: string, refreshToken: string): AuthSession {
214
+ return {
215
+ ...session(accessToken, refreshToken),
216
+ expiresAt: Math.floor(Date.now() / 1000) + 10,
217
+ };
218
+ }
219
+
220
+ function stored(): string {
221
+ return JSON.stringify(
222
+ [...Array(sessionStorage.length).keys()].map((index) => {
223
+ const key = sessionStorage.key(index) ?? '';
224
+ return [key, sessionStorage.getItem(key)];
225
+ }),
226
+ );
227
+ }
228
+
229
+ beforeEach(() => {
230
+ shellToken = jwt('1', 'g1');
231
+ exchange.mockReset();
232
+ setAppBackendTokenExchange(async () => shellToken, exchange);
233
+ });
234
+
235
+ afterEach(() => {
236
+ resetAppBackendTokenExchange();
237
+ });
238
+
239
+ it('exchanges the shell token at the regional server and never uses silent sign-in', async () => {
240
+ exchange.mockResolvedValue({ ok: true, session: session('regional-1', 'regional-refresh') });
241
+ const identity = upstream(5);
242
+
243
+ const token = await ensureAppBackendSession(identity, { allowSilent: false });
244
+
245
+ expect(token).toBe('regional-1');
246
+ expect(exchange).toHaveBeenCalledWith(
247
+ expect.objectContaining({
248
+ backendUrl: 'https://id.eu.example',
249
+ companyId: 5,
250
+ shellAccessToken: shellToken,
251
+ }),
252
+ );
253
+ expect(signIn).not.toHaveBeenCalled();
254
+ expect(getAppBackendSession(identity.key)?.accessToken).toBe('regional-1');
255
+ expect(stored()).toContain('regional-refresh');
256
+ expect(stored()).not.toContain('regional-1"');
257
+ expect(stored()).not.toContain(shellToken);
258
+ });
259
+
260
+ it('renews with the regional refresh token, not a new exchange', async () => {
261
+ exchange.mockResolvedValueOnce({ ok: true, session: due('regional-old', 'regional-r1') });
262
+ const identity = upstream(5);
263
+ await ensureAppBackendSession(identity);
264
+ refreshAuthSession.mockResolvedValueOnce(session('regional-new', 'regional-r2'));
265
+
266
+ shellToken = jwt('1', 'g2');
267
+ expect(await ensureAppBackendSession(identity)).toBe('regional-new');
268
+ expect(refreshAuthSession).toHaveBeenCalledWith(
269
+ expect.objectContaining({ refreshToken: 'regional-r1' }),
270
+ expect.any(Number),
271
+ );
272
+ expect(factory).toHaveBeenCalledWith(
273
+ expect.objectContaining({ url: 'https://id.eu.example' }),
274
+ );
275
+ expect(exchange).toHaveBeenCalledTimes(1);
276
+ expect(stored()).toContain('regional-r2');
277
+ });
278
+
279
+ it('exchanges again when the regional refresh fails', async () => {
280
+ exchange.mockResolvedValueOnce({ ok: true, session: due('regional-old', 'regional-r1') });
281
+ const identity = upstream(5);
282
+ await ensureAppBackendSession(identity);
283
+ refreshAuthSession.mockRejectedValueOnce(new Error('HTTP 401'));
284
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-new', 'regional-r3') });
285
+
286
+ expect(await ensureAppBackendSession(identity)).toBe('regional-new');
287
+ expect(exchange).toHaveBeenCalledTimes(2);
288
+ });
289
+
290
+ it('drops the regional session and exchanges when the shell user changes', async () => {
291
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-ada', 'r-ada') });
292
+ const identity = upstream(5);
293
+ await ensureAppBackendSession(identity);
294
+
295
+ shellToken = jwt('2', 'g9');
296
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-bob', 'r-bob') });
297
+ expect(await ensureAppBackendSession(identity)).toBe('regional-bob');
298
+ expect(refreshAuthSession).not.toHaveBeenCalled();
299
+ expect(stored()).not.toContain('r-ada');
300
+ });
301
+
302
+ it('does not retry a failed exchange until the shell token changes', async () => {
303
+ exchange.mockResolvedValue({ ok: false, reason: 'invalid_grant' });
304
+ const identity = upstream(5);
305
+
306
+ expect(await ensureAppBackendSession(identity)).toBeNull();
307
+ expect(await ensureAppBackendSession(identity)).toBeNull();
308
+ expect(exchange).toHaveBeenCalledTimes(1);
309
+
310
+ shellToken = jwt('1', 'g2');
311
+ exchange.mockResolvedValue({ ok: true, session: session('regional-2') });
312
+ expect(await ensureAppBackendSession(identity)).toBe('regional-2');
313
+ });
314
+
315
+ it('clears the regional session on shell sign-out', async () => {
316
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-1', 'r1') });
317
+ const identity = upstream(5);
318
+ await ensureAppBackendSession(identity);
319
+
320
+ await endAppBackendSessions();
321
+ expect(getAppBackendSession(identity.key)).toBeNull();
322
+ expect(sessionStorage.length).toBe(0);
323
+
324
+ shellToken = null;
325
+ expect(await ensureAppBackendSession(identity)).toBeNull();
326
+ expect(exchange).toHaveBeenCalledTimes(1);
327
+ });
328
+ });
195
329
  });
@@ -10,9 +10,45 @@ import {
10
10
  type ResolvedAppBackend,
11
11
  } from './identity';
12
12
  import { runSilentPkceSignIn, type SilentSignInOutcome } from './silentSignIn';
13
+ import {
14
+ describeAppSessionFailure,
15
+ exchangeShellTokenForAppSession,
16
+ type TokenExchangeOutcome,
17
+ } from './tokenExchange';
18
+ import { refreshFrameAccessTokenIfNeeded } from '../utils/frameSessionRefresher';
19
+ import { decodeJwtPayload } from '../utils/decodeJwtPayload';
13
20
 
14
21
  const logger = getLogger('shellcore');
15
22
 
23
+ /** Why the last session attempt for an app identity server failed (no secrets). */
24
+ const lastFailure = new Map<string, string>();
25
+
26
+ export function getAppBackendSessionFailure(key: string): string | null {
27
+ return lastFailure.get(key) ?? null;
28
+ }
29
+
30
+ /** Let the next ensure call try silent sign-in again (user asked to retry). */
31
+ export function allowSilentRetry(key: string): void {
32
+ silentAttempted.delete(key);
33
+ failedShellToken.delete(key);
34
+ }
35
+
36
+ /** Identity servers that trust the shell's global identity get a session by token exchange. */
37
+ export function usesTokenExchange(identity: ResolvedAppBackend): boolean {
38
+ return identity.type === 'shellui' && identity.provider === 'upstream';
39
+ }
40
+
41
+ function fail(identity: ResolvedAppBackend, reason: string): null {
42
+ lastFailure.set(identity.key, reason);
43
+ logger.warn('App session: no session for an app identity server', {
44
+ url: identity.url,
45
+ companyId: identity.companyId ?? null,
46
+ reason,
47
+ hint: describeAppSessionFailure(reason),
48
+ });
49
+ return null;
50
+ }
51
+
16
52
  /** Tab-scoped refresh tokens for app identity servers. Not the shell refresh key. */
17
53
  export const APP_BACKEND_REFRESH_PREFIX = 'shellui.auth.app.refresh.';
18
54
 
@@ -30,6 +66,8 @@ const memory = new Map<string, StoredEntry>();
30
66
  const refreshTimers = new Map<string, ReturnType<typeof setTimeout>>();
31
67
  const inFlight = new Map<string, Promise<string | null>>();
32
68
  const silentAttempted = new Set<string>();
69
+ /** Shell token that last failed an exchange, so the same token is not retried in a loop. Memory only. */
70
+ const failedShellToken = new Map<string, string>();
33
71
  const listeners = new Set<() => void>();
34
72
 
35
73
  let backendFactory: (config: BackendConfig) => AppBackendClient = createAuthBackend;
@@ -39,6 +77,24 @@ let signInImpl: (input: {
39
77
  companyId?: string | number;
40
78
  }) => Promise<SilentSignInOutcome> = runSilentPkceSignIn;
41
79
 
80
+ let shellTokenImpl: () => Promise<string | null | undefined> = refreshFrameAccessTokenIfNeeded;
81
+ let exchangeImpl: typeof exchangeShellTokenForAppSession = exchangeShellTokenForAppSession;
82
+
83
+ export function setAppBackendTokenExchange(
84
+ shellToken: () => Promise<string | null | undefined>,
85
+ exchange: (
86
+ input: Parameters<typeof exchangeShellTokenForAppSession>[0],
87
+ ) => Promise<TokenExchangeOutcome> = exchangeShellTokenForAppSession,
88
+ ): void {
89
+ shellTokenImpl = shellToken;
90
+ exchangeImpl = exchange;
91
+ }
92
+
93
+ export function resetAppBackendTokenExchange(): void {
94
+ shellTokenImpl = refreshFrameAccessTokenIfNeeded;
95
+ exchangeImpl = exchangeShellTokenForAppSession;
96
+ }
97
+
42
98
  export function setAppBackendFactory(factory: (config: BackendConfig) => AppBackendClient): void {
43
99
  backendFactory = factory;
44
100
  }
@@ -55,6 +111,7 @@ export function setAppBackendSignIn(
55
111
 
56
112
  export function resetAppBackendSilentAttempts(): void {
57
113
  silentAttempted.clear();
114
+ failedShellToken.clear();
58
115
  }
59
116
 
60
117
  export function subscribeAppBackendSessions(listener: () => void): () => void {
@@ -170,6 +227,7 @@ async function doEnsure(
170
227
  identity: ResolvedAppBackend,
171
228
  allowSilent: boolean,
172
229
  ): Promise<string | null> {
230
+ if (usesTokenExchange(identity)) return ensureByTokenExchange(identity);
173
231
  const now = Math.floor(Date.now() / 1000);
174
232
  const current = memory.get(identity.key)?.session ?? null;
175
233
  if (current?.accessToken && !accessTokenRefreshDue(current.expiresAt, now)) {
@@ -194,8 +252,13 @@ async function doEnsure(
194
252
  }
195
253
  }
196
254
 
197
- if (!allowSilent || identity.type !== 'shellui' || !identity.provider) return null;
198
- if (silentAttempted.has(identity.key)) return null;
255
+ if (!allowSilent) return null;
256
+ if (identity.type !== 'shellui' || !identity.provider) {
257
+ return fail(identity, 'silent_sign_in_unsupported');
258
+ }
259
+ if (silentAttempted.has(identity.key)) {
260
+ return null;
261
+ }
199
262
  silentAttempted.add(identity.key);
200
263
 
201
264
  let outcome: SilentSignInOutcome;
@@ -206,18 +269,10 @@ async function doEnsure(
206
269
  companyId: identity.companyId,
207
270
  });
208
271
  } catch {
209
- logger.info('Silent sign-in did not complete for an app identity server', {
210
- url: identity.url,
211
- });
212
- return null;
213
- }
214
- if (!outcome.ok) {
215
- logger.info('Silent sign-in did not complete for an app identity server', {
216
- url: identity.url,
217
- reason: outcome.reason,
218
- });
219
- return null;
272
+ return fail(identity, 'silent_sign_in_error');
220
273
  }
274
+ if (!outcome.ok) return fail(identity, outcome.reason);
275
+ logger.info('App session: silent sign-in returned a code, exchanging it', { url: identity.url });
221
276
 
222
277
  try {
223
278
  const session = await backendFactory(toBackendConfig(identity)).exchangeOAuthSessionCode({
@@ -226,17 +281,112 @@ async function doEnsure(
226
281
  codeVerifier: outcome.codeVerifier,
227
282
  nowSeconds: Math.floor(Date.now() / 1000),
228
283
  });
229
- if (!session?.accessToken) return null;
284
+ if (!session?.accessToken) return fail(identity, 'token_exchange_empty');
230
285
  remember(identity, session);
286
+ lastFailure.delete(identity.key);
287
+ logger.info('App session: signed in to app identity server', { url: identity.url });
231
288
  return session.accessToken;
289
+ } catch (err) {
290
+ const message = err instanceof Error ? err.message.slice(0, 200) : '';
291
+ return fail(identity, `token_exchange_failed${message ? `: ${message}` : ''}`);
292
+ }
293
+ }
294
+
295
+ function shellSubject(token: string): string | null {
296
+ const sub = decodeJwtPayload(token)?.sub;
297
+ return typeof sub === 'string' || typeof sub === 'number' ? `${sub}` : null;
298
+ }
299
+
300
+ function subjectKey(key: string): string {
301
+ return `${storageKey(key)}#sub`;
302
+ }
303
+
304
+ function readSubject(key: string): string | null {
305
+ try {
306
+ return sessionStorage.getItem(subjectKey(key));
232
307
  } catch {
233
- logger.info('Silent sign-in did not complete for an app identity server', {
234
- url: identity.url,
235
- });
236
308
  return null;
237
309
  }
238
310
  }
239
311
 
312
+ function writeSubject(key: string, sub: string | null): void {
313
+ try {
314
+ if (sub) sessionStorage.setItem(subjectKey(key), sub);
315
+ else sessionStorage.removeItem(subjectKey(key));
316
+ } catch {
317
+ // Ignore.
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Regional session for an upstream identity server:
323
+ * keep it while valid, renew it with its own refresh token, and exchange the shell token
324
+ * only when there is none, the refresh fails, or the shell user changed.
325
+ */
326
+ async function ensureByTokenExchange(identity: ResolvedAppBackend): Promise<string | null> {
327
+ let shellToken: string | null | undefined;
328
+ try {
329
+ shellToken = await shellTokenImpl();
330
+ } catch {
331
+ shellToken = null;
332
+ }
333
+ if (!shellToken) {
334
+ forget(identity.key);
335
+ writeSubject(identity.key, null);
336
+ return fail(identity, 'no_shell_session');
337
+ }
338
+ const subject = shellSubject(shellToken);
339
+ if (readSubject(identity.key) !== subject) {
340
+ // Another shell user, or a session from before subjects were kept: never reuse it.
341
+ forget(identity.key);
342
+ writeSubject(identity.key, null);
343
+ }
344
+
345
+ const now = Math.floor(Date.now() / 1000);
346
+ const current = memory.get(identity.key)?.session ?? null;
347
+ if (current?.accessToken && !accessTokenRefreshDue(current.expiresAt, now)) {
348
+ return current.accessToken;
349
+ }
350
+ const refreshToken = current?.refreshToken || readRefresh(identity.key);
351
+ if (refreshToken) {
352
+ try {
353
+ const next = await backendFactory(toBackendConfig(identity)).refreshAuthSession(
354
+ current ? { ...current, refreshToken } : sessionForRefresh(refreshToken),
355
+ now,
356
+ );
357
+ if (next?.accessToken) {
358
+ remember(identity, next);
359
+ return next.accessToken;
360
+ }
361
+ } catch {
362
+ // Fall through to a new exchange.
363
+ }
364
+ forget(identity.key);
365
+ }
366
+
367
+ if (failedShellToken.get(identity.key) === shellToken) return null;
368
+ const outcome = await exchangeImpl({
369
+ backendUrl: identity.url,
370
+ companyId: identity.companyId,
371
+ shellAccessToken: shellToken,
372
+ nowSeconds: now,
373
+ });
374
+ if (!outcome.ok) {
375
+ failedShellToken.set(identity.key, shellToken);
376
+ forget(identity.key);
377
+ return fail(identity, outcome.reason);
378
+ }
379
+ failedShellToken.delete(identity.key);
380
+ writeSubject(identity.key, subject);
381
+ remember(identity, outcome.session);
382
+ lastFailure.delete(identity.key);
383
+ logger.info('App session: token exchange succeeded', {
384
+ url: identity.url,
385
+ companyId: identity.companyId ?? null,
386
+ });
387
+ return outcome.session.accessToken;
388
+ }
389
+
240
390
  export function ensureAppBackendSession(
241
391
  identity: ResolvedAppBackend,
242
392
  options?: { allowSilent?: boolean },
@@ -278,6 +428,7 @@ export async function endAppBackendSessions(): Promise<void> {
278
428
  refreshTimers.clear();
279
429
  inFlight.clear();
280
430
  silentAttempted.clear();
431
+ failedShellToken.clear();
281
432
  clearAllRefresh();
282
433
  notify();
283
434
  await Promise.all(
@@ -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
+ });