@shellui/core 0.7.0-alpha.4 → 0.7.0-alpha.6
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 +2 -2
- package/schemas/shellui.config.schema.json +11 -4
- package/src/features/auth/AuthProvider.tsx +3 -3
- package/src/features/auth/appBackend/appBackendSessions.spec.ts +134 -0
- package/src/features/auth/appBackend/appBackendSessions.ts +168 -17
- package/src/features/auth/appBackend/childFrames.spec.ts +99 -0
- package/src/features/auth/appBackend/childFrames.ts +45 -2
- package/src/features/auth/appBackend/frameAuth.ts +9 -2
- package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
- package/src/features/auth/appBackend/tokenExchange.ts +76 -0
- package/src/features/auth/utils/webPkce.spec.ts +2 -2
- package/src/features/config/types.ts +13 -4
- package/src/features/settings/SettingsProvider.tsx +42 -1
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +8 -7
- package/src/features/settings/utils/buildSettingsForPropagation.ts +4 -6
- package/src/features/transfers/transferQueue.spec.ts +6 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shellui/core",
|
|
3
|
-
"version": "0.7.0-alpha.
|
|
3
|
+
"version": "0.7.0-alpha.6",
|
|
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.
|
|
76
|
+
"@shellui/sdk": "0.7.0-alpha.6"
|
|
77
77
|
},
|
|
78
78
|
"peerDependencies": {
|
|
79
79
|
"react": "^18.0.0 || ^19.0.0",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
},
|
|
80
80
|
"email": {
|
|
81
81
|
"$ref": "#/definitions/EmailConfig",
|
|
82
|
-
"description": "Email-service connection. Propagated to iframes via SDK settings.
|
|
82
|
+
"description": "Email-service connection. Propagated to iframes via SDK settings. Without `url`, the shell sends no email service (`null`). `showInAdmin: false` hides Admin → Email."
|
|
83
83
|
},
|
|
84
84
|
"theme": {
|
|
85
85
|
"$ref": "#/definitions/ThemeRef",
|
|
@@ -328,7 +328,7 @@
|
|
|
328
328
|
},
|
|
329
329
|
"provider": {
|
|
330
330
|
"type": "string",
|
|
331
|
-
"description": "OAuth
|
|
331
|
+
"description": "`upstream`: the shell gets the app session by OAuth token exchange (RFC 8693), trading its own access token at this server. Recommended for Shellui regions. Any other value, such as `google`, is the OAuth provider for silent sign-in. When omitted, the shell uses the first `backend.login.oauthProviders` entry."
|
|
332
332
|
}
|
|
333
333
|
},
|
|
334
334
|
"required": ["url"],
|
|
@@ -356,6 +356,13 @@
|
|
|
356
356
|
"type": "string"
|
|
357
357
|
},
|
|
358
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
|
+
"serviceOrigins": {
|
|
361
|
+
"type": "array",
|
|
362
|
+
"items": {
|
|
363
|
+
"type": "string"
|
|
364
|
+
},
|
|
365
|
+
"description": "Exact origins of service URLs (email, storage, hosting) a host may pass to a child with `ShelluiFrame` or `createAppFrame`, such as `https://storage.eu.shellui.com`. No wildcards. A URL outside this list, or a missing one, reaches the child as `null`. Omit to send children no service URLs."
|
|
359
366
|
}
|
|
360
367
|
},
|
|
361
368
|
"required": ["origins"],
|
|
@@ -367,7 +374,7 @@
|
|
|
367
374
|
"properties": {
|
|
368
375
|
"url": {
|
|
369
376
|
"type": "string",
|
|
370
|
-
"description": "Base URL of email-service.
|
|
377
|
+
"description": "Base URL of email-service. Required for apps to get email. There is no built-in default. Local: `http://localhost:8003`."
|
|
371
378
|
},
|
|
372
379
|
"showInAdmin": {
|
|
373
380
|
"type": "boolean",
|
|
@@ -375,7 +382,7 @@
|
|
|
375
382
|
}
|
|
376
383
|
},
|
|
377
384
|
"additionalProperties": false,
|
|
378
|
-
"description": "Optional email-service wiring for Admin → Email and iframe apps.
|
|
385
|
+
"description": "Optional email-service wiring for Admin → Email and iframe apps. The shell never invents a URL: without `url`, apps get no email service."
|
|
379
386
|
},
|
|
380
387
|
"StorageConfig": {
|
|
381
388
|
"type": "object",
|
|
@@ -861,8 +861,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
861
861
|
});
|
|
862
862
|
} catch (err) {
|
|
863
863
|
reply('error');
|
|
864
|
-
const
|
|
865
|
-
if (
|
|
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 (
|
|
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
|
|
198
|
-
if (
|
|
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
|
-
|
|
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
|
|
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(
|
|
@@ -170,3 +170,102 @@ describe('childFrameAuthPropagationOptions', () => {
|
|
|
170
170
|
expect(options.settingsUser).toBeNull();
|
|
171
171
|
});
|
|
172
172
|
});
|
|
173
|
+
|
|
174
|
+
describe('child frame service URLs', () => {
|
|
175
|
+
const withServices: ShellUIConfig = {
|
|
176
|
+
...config,
|
|
177
|
+
navigation: [
|
|
178
|
+
{
|
|
179
|
+
label: 'Dashboard',
|
|
180
|
+
path: '',
|
|
181
|
+
url: 'https://dashboard.example.com/',
|
|
182
|
+
childFrames: {
|
|
183
|
+
origins: ['https://admin.example.com'],
|
|
184
|
+
backendOrigins: ['https://id.eu.example.com'],
|
|
185
|
+
serviceOrigins: [
|
|
186
|
+
'https://email.eu.example.com',
|
|
187
|
+
'https://storage.eu.example.com',
|
|
188
|
+
'https://*.example.com',
|
|
189
|
+
'*',
|
|
190
|
+
],
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
],
|
|
194
|
+
};
|
|
195
|
+
const register = (services: unknown, cfg: ShellUIConfig = withServices) =>
|
|
196
|
+
validateChildFrameRegistration({
|
|
197
|
+
from: ['h1'],
|
|
198
|
+
hostSrc: host,
|
|
199
|
+
payload: { ...good, services },
|
|
200
|
+
config: cfg,
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('forwards allowed service URLs to the child settings', () => {
|
|
204
|
+
const result = register({
|
|
205
|
+
email: 'https://email.eu.example.com/',
|
|
206
|
+
storage: 'https://storage.eu.example.com',
|
|
207
|
+
});
|
|
208
|
+
expect(result.ok).toBe(true);
|
|
209
|
+
if (!result.ok) return;
|
|
210
|
+
expect(result.entry.services).toEqual({
|
|
211
|
+
email: 'https://email.eu.example.com',
|
|
212
|
+
storage: 'https://storage.eu.example.com',
|
|
213
|
+
hosting: null,
|
|
214
|
+
});
|
|
215
|
+
expect(result.entry.rejectedServices).toEqual([]);
|
|
216
|
+
const options = childFrameAuthPropagationOptions({
|
|
217
|
+
identity: result.entry.identity,
|
|
218
|
+
getAppSession: () => null,
|
|
219
|
+
services: result.entry.services,
|
|
220
|
+
});
|
|
221
|
+
expect(options.email).toEqual({ url: 'https://email.eu.example.com' });
|
|
222
|
+
expect(options.storage).toEqual({ url: 'https://storage.eu.example.com' });
|
|
223
|
+
expect(options.hosting).toBeNull();
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('drops a service URL whose origin is not allowed', () => {
|
|
227
|
+
const result = register({
|
|
228
|
+
storage: 'https://evil.example.org',
|
|
229
|
+
hosting: 'javascript:alert(1)',
|
|
230
|
+
});
|
|
231
|
+
expect(result.ok).toBe(true);
|
|
232
|
+
if (!result.ok) return;
|
|
233
|
+
expect(result.entry.services).toEqual({ email: null, storage: null, hosting: null });
|
|
234
|
+
expect(result.entry.rejectedServices).toEqual(['storage', 'hosting']);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('never matches a wildcard entry', () => {
|
|
238
|
+
const result = register({ hosting: 'https://hosting.example.com' });
|
|
239
|
+
expect(result.ok).toBe(true);
|
|
240
|
+
if (!result.ok) return;
|
|
241
|
+
expect(result.entry.services.hosting).toBeNull();
|
|
242
|
+
expect(result.entry.rejectedServices).toEqual(['hosting']);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it('sends null for missing services, without falling back to the shell', () => {
|
|
246
|
+
const shellWithServices: ShellUIConfig = {
|
|
247
|
+
...withServices,
|
|
248
|
+
email: { url: 'https://email.example.com' },
|
|
249
|
+
storage: { url: 'https://storage.example.com' },
|
|
250
|
+
hosting: { url: 'https://hosting.example.com' },
|
|
251
|
+
};
|
|
252
|
+
const result = register(undefined, shellWithServices);
|
|
253
|
+
expect(result.ok).toBe(true);
|
|
254
|
+
if (!result.ok) return;
|
|
255
|
+
expect(result.entry.services).toEqual({ email: null, storage: null, hosting: null });
|
|
256
|
+
const options = childFrameAuthPropagationOptions({
|
|
257
|
+
identity: result.entry.identity,
|
|
258
|
+
getAppSession: () => null,
|
|
259
|
+
services: result.entry.services,
|
|
260
|
+
});
|
|
261
|
+
expect(options).toMatchObject({ email: null, storage: null, hosting: null });
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it('drops every service URL when serviceOrigins is not configured', () => {
|
|
265
|
+
const result = register({ email: 'https://email.eu.example.com' }, config);
|
|
266
|
+
expect(result.ok).toBe(true);
|
|
267
|
+
if (!result.ok) return;
|
|
268
|
+
expect(result.entry.services.email).toBeNull();
|
|
269
|
+
expect(result.entry.rejectedServices).toEqual(['email']);
|
|
270
|
+
});
|
|
271
|
+
});
|
|
@@ -11,8 +11,16 @@ export type ChildFrameEntry = {
|
|
|
11
11
|
frameId: string;
|
|
12
12
|
url: string;
|
|
13
13
|
identity: ResolvedAppBackend | null;
|
|
14
|
+
/** Host-supplied service URLs that passed `childFrames.serviceOrigins`. Others are `null`. */
|
|
15
|
+
services: ChildFrameServices;
|
|
16
|
+
/** Service keys dropped because the URL was invalid or its origin not allowed. */
|
|
17
|
+
rejectedServices: ChildFrameServiceKey[];
|
|
14
18
|
};
|
|
15
19
|
|
|
20
|
+
export type ChildFrameServiceKey = 'email' | 'storage' | 'hosting';
|
|
21
|
+
export type ChildFrameServices = Record<ChildFrameServiceKey, string | null>;
|
|
22
|
+
const SERVICE_KEYS: readonly ChildFrameServiceKey[] = ['email', 'storage', 'hosting'];
|
|
23
|
+
|
|
16
24
|
export type ChildFrameRegistration =
|
|
17
25
|
| { ok: true; entry: ChildFrameEntry }
|
|
18
26
|
| { ok: false; reason: string };
|
|
@@ -45,6 +53,32 @@ function originList(values: unknown): Set<string> {
|
|
|
45
53
|
return out;
|
|
46
54
|
}
|
|
47
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Keep each host-supplied service URL only when it is http(s) and its origin is
|
|
58
|
+
* exactly in `allowed`. Missing or rejected values become `null`: the child never
|
|
59
|
+
* falls back to the shell's own services or to a built-in default.
|
|
60
|
+
*/
|
|
61
|
+
export function resolveChildFrameServices(
|
|
62
|
+
input: unknown,
|
|
63
|
+
allowedOrigins: unknown,
|
|
64
|
+
): { services: ChildFrameServices; rejected: ChildFrameServiceKey[] } {
|
|
65
|
+
const allowed = originList(allowedOrigins);
|
|
66
|
+
const raw = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;
|
|
67
|
+
const services: ChildFrameServices = { email: null, storage: null, hosting: null };
|
|
68
|
+
const rejected: ChildFrameServiceKey[] = [];
|
|
69
|
+
for (const key of SERVICE_KEYS) {
|
|
70
|
+
const value = raw[key];
|
|
71
|
+
if (value === undefined || value === null || value === '') continue;
|
|
72
|
+
const origin = exactOrigin(value);
|
|
73
|
+
if (origin && allowed.has(origin)) {
|
|
74
|
+
services[key] = `${value}`.trim().replace(/\/+$/, '');
|
|
75
|
+
} else {
|
|
76
|
+
rejected.push(key);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { services, rejected };
|
|
80
|
+
}
|
|
81
|
+
|
|
48
82
|
/**
|
|
49
83
|
* Check a `SHELLUI_CHILD_FRAME_REGISTER` message. `from` must be exactly one hop:
|
|
50
84
|
* a child app cannot register frames by sending the message through its host.
|
|
@@ -59,7 +93,7 @@ export function validateChildFrameRegistration(input: {
|
|
|
59
93
|
if (from.length !== 1) return { ok: false, reason: 'not sent by a direct app frame' };
|
|
60
94
|
if (!input.hostSrc) return { ok: false, reason: 'unknown host frame' };
|
|
61
95
|
const payload = input.payload as
|
|
62
|
-
| { frameId?: unknown; url?: unknown; backend?: unknown }
|
|
96
|
+
| { frameId?: unknown; url?: unknown; backend?: unknown; services?: unknown }
|
|
63
97
|
| null
|
|
64
98
|
| undefined;
|
|
65
99
|
const frameId = typeof payload?.frameId === 'string' ? payload.frameId.trim() : '';
|
|
@@ -102,9 +136,18 @@ export function validateChildFrameRegistration(input: {
|
|
|
102
136
|
if (!identity) return { ok: false, reason: 'child identity server is invalid' };
|
|
103
137
|
}
|
|
104
138
|
|
|
139
|
+
const { services, rejected } = resolveChildFrameServices(payload?.services, rules.serviceOrigins);
|
|
140
|
+
|
|
105
141
|
return {
|
|
106
142
|
ok: true,
|
|
107
|
-
entry: {
|
|
143
|
+
entry: {
|
|
144
|
+
hostUuid: from[0],
|
|
145
|
+
frameId,
|
|
146
|
+
url: payload?.url as string,
|
|
147
|
+
identity,
|
|
148
|
+
services,
|
|
149
|
+
rejectedServices: rejected,
|
|
150
|
+
},
|
|
108
151
|
};
|
|
109
152
|
}
|
|
110
153
|
|
|
@@ -174,13 +174,16 @@ export function frameAuthPropagationOptions(input: {
|
|
|
174
174
|
/**
|
|
175
175
|
* Auth fields for a child app hosted inside an embedded app (`createAppFrame`).
|
|
176
176
|
* The shell token is never sent. With no allowed identity server the child gets
|
|
177
|
-
* no token
|
|
177
|
+
* no token and no user. Service URLs are the ones the host passed and the shell
|
|
178
|
+
* allowed (`childFrames.serviceOrigins`); any other service is `null`.
|
|
178
179
|
*/
|
|
179
180
|
export function childFrameAuthPropagationOptions(input: {
|
|
180
181
|
identity: ResolvedAppBackend | null;
|
|
181
182
|
getAppSession: (key: string) => AuthSession | null;
|
|
183
|
+
services?: Partial<Record<'email' | 'storage' | 'hosting', string | null>> | null;
|
|
182
184
|
}): FrameAuthPropagationOptions {
|
|
183
185
|
const { identity, getAppSession } = input;
|
|
186
|
+
const allowed = input.services ?? {};
|
|
184
187
|
const session = identity ? getAppSession(identity.key) : null;
|
|
185
188
|
return toPropagationOptions({
|
|
186
189
|
includeAuthAccessToken: Boolean(identity),
|
|
@@ -189,6 +192,10 @@ export function childFrameAuthPropagationOptions(input: {
|
|
|
189
192
|
authBackendBaseUrl: identity?.type === 'shellui' ? identity.url : null,
|
|
190
193
|
overrideUser: true,
|
|
191
194
|
settingsUser: settingsUserFromSession(session),
|
|
192
|
-
services:
|
|
195
|
+
services: {
|
|
196
|
+
email: allowed.email ? { url: allowed.email } : null,
|
|
197
|
+
storage: allowed.storage ? { url: allowed.storage } : null,
|
|
198
|
+
hosting: allowed.hosting ? { url: allowed.hosting } : null,
|
|
199
|
+
},
|
|
193
200
|
});
|
|
194
201
|
}
|
|
@@ -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 =
|
|
112
|
+
const id = `o${'0'.repeat(32)}`;
|
|
113
113
|
sessionStorage.setItem(
|
|
114
|
-
|
|
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 });
|
|
@@ -252,6 +252,13 @@ export interface ChildFramesConfig {
|
|
|
252
252
|
* and never sends its own token to a child. Omit to give children no token.
|
|
253
253
|
*/
|
|
254
254
|
backendOrigins?: string[];
|
|
255
|
+
/**
|
|
256
|
+
* Exact origins of service URLs (email, storage, hosting) a host may pass to
|
|
257
|
+
* a child with `ShelluiFrame` or `createAppFrame`, such as
|
|
258
|
+
* `https://storage.eu.shellui.com`. No wildcards. A URL outside this list, or
|
|
259
|
+
* a missing one, reaches the child as `null`. Omit to send children no service URLs.
|
|
260
|
+
*/
|
|
261
|
+
serviceOrigins?: string[];
|
|
255
262
|
}
|
|
256
263
|
|
|
257
264
|
/**
|
|
@@ -268,7 +275,9 @@ export interface AppBackendConfig {
|
|
|
268
275
|
/** Public key when `type` is `supabase`. */
|
|
269
276
|
publishableKey?: string;
|
|
270
277
|
/**
|
|
271
|
-
*
|
|
278
|
+
* `upstream`: the shell gets the app session by OAuth token exchange (RFC 8693),
|
|
279
|
+
* trading its own access token at this server. Recommended for Shellui regions.
|
|
280
|
+
* Any other value, such as `google`, is the OAuth provider for silent sign-in.
|
|
272
281
|
* When omitted, the shell uses the first `backend.login.oauthProviders` entry.
|
|
273
282
|
*/
|
|
274
283
|
provider?: string;
|
|
@@ -357,12 +366,12 @@ export interface HostingConfig {
|
|
|
357
366
|
|
|
358
367
|
/**
|
|
359
368
|
* Optional email-service wiring for Admin → Email and iframe apps.
|
|
360
|
-
*
|
|
369
|
+
* The shell never invents a URL: without `url`, apps get no email service.
|
|
361
370
|
*/
|
|
362
371
|
export interface EmailConfig {
|
|
363
372
|
/**
|
|
364
373
|
* Base URL of email-service.
|
|
365
|
-
*
|
|
374
|
+
* Required for apps to get email. There is no built-in default.
|
|
366
375
|
* Local: `http://localhost:8003`.
|
|
367
376
|
*/
|
|
368
377
|
url?: string;
|
|
@@ -447,7 +456,7 @@ export interface ShellUIConfig {
|
|
|
447
456
|
hosting?: HostingConfig;
|
|
448
457
|
/**
|
|
449
458
|
* Email-service connection. Propagated to iframes via SDK settings.
|
|
450
|
-
*
|
|
459
|
+
* Without `url`, the shell sends no email service (`null`).
|
|
451
460
|
* `showInAdmin: false` hides Admin → Email.
|
|
452
461
|
*/
|
|
453
462
|
email?: EmailConfig;
|
|
@@ -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,
|
|
@@ -232,6 +244,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
232
244
|
...childFrameAuthPropagationOptions({
|
|
233
245
|
identity: entry?.identity ?? null,
|
|
234
246
|
getAppSession: getAppBackendSession,
|
|
247
|
+
services: entry?.services ?? null,
|
|
235
248
|
}),
|
|
236
249
|
includeLayoutChrome: false,
|
|
237
250
|
frameUuid: path[path.length - 1],
|
|
@@ -676,10 +689,38 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
676
689
|
}
|
|
677
690
|
addChildFrame(result.entry);
|
|
678
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
|
+
});
|
|
679
704
|
void (async () => {
|
|
705
|
+
let ok = true;
|
|
706
|
+
let reason: string | null = null;
|
|
680
707
|
if (entry.identity) {
|
|
681
|
-
|
|
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');
|
|
682
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 });
|
|
683
724
|
deliverSessionHandoff(() =>
|
|
684
725
|
pushSettingsToChildFrame(
|
|
685
726
|
entry,
|
|
@@ -287,25 +287,26 @@ describe('buildSettingsForPropagation', () => {
|
|
|
287
287
|
expect(result.email).toEqual({ url: 'http://localhost:8003' });
|
|
288
288
|
});
|
|
289
289
|
|
|
290
|
-
it('
|
|
290
|
+
it('sends no email when email is set without url (no built-in default)', () => {
|
|
291
291
|
const config = {
|
|
292
292
|
email: {},
|
|
293
293
|
} as ShellUIConfig;
|
|
294
294
|
|
|
295
295
|
const result = buildSettingsForPropagation(baseSettings, config, 'en');
|
|
296
|
-
expect(result.email).
|
|
296
|
+
expect(result.email).toBeNull();
|
|
297
297
|
});
|
|
298
298
|
|
|
299
|
-
it('propagates showInAdmin false for email
|
|
299
|
+
it('propagates showInAdmin false for email', () => {
|
|
300
300
|
const config = {
|
|
301
301
|
email: {
|
|
302
|
+
url: 'http://localhost:8003',
|
|
302
303
|
showInAdmin: false,
|
|
303
304
|
},
|
|
304
305
|
} as ShellUIConfig;
|
|
305
306
|
|
|
306
307
|
const result = buildSettingsForPropagation(baseSettings, config, 'en');
|
|
307
308
|
expect(result.email).toEqual({
|
|
308
|
-
url: '
|
|
309
|
+
url: 'http://localhost:8003',
|
|
309
310
|
showInAdmin: false,
|
|
310
311
|
});
|
|
311
312
|
});
|
|
@@ -560,7 +561,7 @@ describe('buildSettingsForPropagation', () => {
|
|
|
560
561
|
expect(json).not.toContain('https://email.shellui.com');
|
|
561
562
|
});
|
|
562
563
|
|
|
563
|
-
it('
|
|
564
|
+
it('sends no email when a foreign app sets an empty email object', () => {
|
|
564
565
|
const withEmptyEmail = {
|
|
565
566
|
...appConfig,
|
|
566
567
|
navigation: (appConfig.navigation ?? []).map((item) =>
|
|
@@ -580,7 +581,7 @@ describe('buildSettingsForPropagation', () => {
|
|
|
580
581
|
'en',
|
|
581
582
|
options,
|
|
582
583
|
);
|
|
583
|
-
expect(result.email).
|
|
584
|
+
expect(result.email).toBeNull();
|
|
584
585
|
expect(result.storage).toBeNull();
|
|
585
586
|
expect(result.hosting).toBeNull();
|
|
586
587
|
const json = JSON.stringify(result);
|
|
@@ -618,7 +619,7 @@ describe('buildSettingsForPropagation', () => {
|
|
|
618
619
|
);
|
|
619
620
|
expect(result.accessToken).toBe(shellToken);
|
|
620
621
|
expect(result.authBackendBaseUrl).toBe('https://id.example.com');
|
|
621
|
-
expect(result.email).
|
|
622
|
+
expect(result.email).toBeNull();
|
|
622
623
|
expect(result.storage).toEqual(shellServices.storage);
|
|
623
624
|
expect(result.hosting).toEqual(shellServices.hosting);
|
|
624
625
|
});
|
|
@@ -15,15 +15,13 @@ import {
|
|
|
15
15
|
getPublishedLayoutChrome,
|
|
16
16
|
} from '../../layouts/floating/layoutChromeStore';
|
|
17
17
|
|
|
18
|
-
/** Production email-service origin. No trailing slash. */
|
|
19
|
-
const DEFAULT_EMAIL_SERVICE_URL = 'https://email.shellui.com';
|
|
20
|
-
|
|
21
18
|
const propagateEmail = (email: EmailConfig | null | undefined): SettingsEmail | null => {
|
|
22
|
-
|
|
23
|
-
const url = email
|
|
19
|
+
// No built-in default: email must come from config or the host app.
|
|
20
|
+
const url = email?.url?.trim().replace(/\/+$/, '') || null;
|
|
21
|
+
if (!url) return null;
|
|
24
22
|
return {
|
|
25
23
|
url,
|
|
26
|
-
...(email
|
|
24
|
+
...(email?.showInAdmin === false ? { showInAdmin: false } : {}),
|
|
27
25
|
};
|
|
28
26
|
};
|
|
29
27
|
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|