@shellui/core 0.7.0-alpha.4 → 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.4",
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.4"
76
+ "@shellui/sdk": "0.7.0-alpha.5"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "react": "^18.0.0 || ^19.0.0",
@@ -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,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 });
@@ -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,
@@ -32,8 +33,19 @@ import {
32
33
  type ChildFrameEntry,
33
34
  } from '../auth/appBackend/childFrames';
34
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
+ }
35
45
  import {
36
46
  ensureAppBackendSession,
47
+ allowSilentRetry,
48
+ getAppBackendSessionFailure,
37
49
  getAppBackendSession,
38
50
  refreshAppBackendSessionIfDue,
39
51
  subscribeAppBackendSessions,
@@ -676,10 +688,31 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
676
688
  }
677
689
  addChildFrame(result.entry);
678
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
+ });
679
696
  void (async () => {
697
+ let ok = true;
698
+ let reason: string | null = null;
680
699
  if (entry.identity) {
681
- await ensureAppBackendSession(entry.identity, { allowSilent: true });
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');
682
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 });
683
716
  deliverSessionHandoff(() =>
684
717
  pushSettingsToChildFrame(
685
718
  entry,
@@ -47,14 +47,18 @@ describe('transferQueue', () => {
47
47
  expect(summary.active).toBe(2);
48
48
  expect(summary.activeUploads).toBe(1);
49
49
  expect(summary.activeDownloads).toBe(1);
50
- expect(getItemPercent(getTransferQueue().find((i) => i.id === 'dl')!)).toBe(25);
50
+ const download = getTransferQueue().find((i) => i.id === 'dl');
51
+ expect(download).toBeDefined();
52
+ expect(getItemPercent(download as NonNullable<typeof download>)).toBe(25);
51
53
  expect(getTransferQueue().find((i) => i.id === 'dl')?.bytesTransferred).toBe(175_000_000);
52
54
  });
53
55
 
54
56
  it('supports ratio-only progress when size is unknown', () => {
55
57
  addTransfer({ id: 'dl', kind: 'download', name: 'Model', size: 0 });
56
58
  setTransferProgress('dl', { ratio: 0.4 });
57
- expect(getItemPercent(getTransferQueue()[0]!)).toBe(40);
59
+ const [item] = getTransferQueue();
60
+ expect(item).toBeDefined();
61
+ expect(getItemPercent(item as NonNullable<typeof item>)).toBe(40);
58
62
  expect(getTransferSummary().percent).toBe(40);
59
63
  });
60
64