@shellui/core 0.7.0 → 0.8.0
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/LICENSE +21 -0
- package/README.md +2 -0
- package/package.json +2 -2
- package/schemas/shellui.config.schema.json +45 -2
- package/src/app.tsx +2 -0
- package/src/features/auth/AuthProvider.tsx +212 -97
- package/src/features/auth/appBackend/configSchema.spec.ts +1 -0
- package/src/features/auth/appBackend/frameAuth.ts +5 -0
- package/src/features/auth/backends/shellui.spec.ts +110 -0
- package/src/features/auth/backends/shellui.ts +47 -20
- package/src/features/auth/backends/types.ts +5 -0
- package/src/features/auth/hooks/useAuth.tsx +6 -1
- package/src/features/auth/types.ts +5 -0
- package/src/features/auth/utils/bffAuthClient.spec.ts +313 -0
- package/src/features/auth/utils/bffAuthClient.ts +171 -49
- package/src/features/auth/utils/buildSessionFromParams.ts +5 -2
- package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +12 -0
- package/src/features/auth/utils/buildSessionFromTokenPayload.ts +3 -1
- package/src/features/auth/utils/canRestoreStoredSession.spec.ts +140 -4
- package/src/features/auth/utils/canRestoreStoredSession.ts +47 -0
- package/src/features/auth/utils/cliCallback.ts +5 -0
- package/src/features/auth/utils/identityBrowserLogout.spec.ts +185 -0
- package/src/features/auth/utils/identityBrowserLogout.ts +174 -0
- package/src/features/auth/utils/index.ts +21 -3
- package/src/features/auth/utils/isBffAuthEnabled.ts +10 -2
- package/src/features/auth/utils/normalizeAuthSettings.spec.ts +9 -0
- package/src/features/auth/utils/normalizeAuthSettings.ts +3 -1
- package/src/features/auth/utils/pkce.spec.ts +29 -1
- package/src/features/auth/utils/pkce.ts +106 -2
- package/src/features/config/types.ts +37 -5
- package/src/features/mcp/mcpActivityErrorCodeI18n.spec.ts +32 -0
- package/src/features/mcp/mcpActivityErrorCodeI18n.ts +30 -0
- package/src/features/mcp/mcpAgentActivityMerge.spec.ts +91 -0
- package/src/features/mcp/mcpAgentActivityMerge.ts +53 -0
- package/src/features/mcp/mcpAgentActivityPresentation.spec.ts +129 -0
- package/src/features/mcp/mcpAgentActivityPresentation.ts +201 -0
- package/src/features/mcp/mcpAgentsConnect.spec.ts +215 -0
- package/src/features/mcp/mcpAgentsConnect.ts +189 -0
- package/src/features/mcp/mcpToolActivityRegistry.spec.ts +9 -0
- package/src/features/mcp/mcpToolActivityRegistry.ts +20 -0
- package/src/features/mcp/mcpToolApprovalsApi.spec.ts +113 -0
- package/src/features/mcp/mcpToolApprovalsApi.ts +162 -0
- package/src/features/mcp/personalAgentsApi.spec.ts +661 -0
- package/src/features/mcp/personalAgentsApi.ts +697 -0
- package/src/features/settings/SettingsIcons.tsx +28 -0
- package/src/features/settings/SettingsRoutes.tsx +8 -0
- package/src/features/settings/SettingsView.tsx +90 -26
- package/src/features/settings/components/McpAgentActivitySection.spec.tsx +255 -0
- package/src/features/settings/components/McpAgentActivitySection.tsx +481 -0
- package/src/features/settings/components/McpAgents.spec.tsx +336 -0
- package/src/features/settings/components/McpAgents.tsx +654 -0
- package/src/features/settings/components/McpPendingApprovals.spec.tsx +201 -0
- package/src/features/settings/components/McpPendingApprovals.tsx +168 -0
- package/src/features/settings/components/McpPersonalStatusPrefetch.tsx +21 -0
- package/src/features/settings/hooks/useMcpPendingToolApprovals.ts +69 -0
- package/src/features/settings/hooks/useMcpPersonalStatus.ts +83 -0
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +44 -1
- package/src/features/settings/utils/buildSettingsForPropagation.ts +30 -1
- package/src/features/settings/utils/isMcpAgentsSettingsEligible.spec.ts +25 -0
- package/src/features/settings/utils/isMcpAgentsSettingsEligible.ts +14 -0
- package/src/features/settings/utils/loadMcpPersonalStatus.spec.ts +76 -0
- package/src/features/settings/utils/loadMcpPersonalStatus.ts +84 -0
- package/src/features/settings/utils/mcpPersonalStatusCache.spec.ts +77 -0
- package/src/features/settings/utils/mcpPersonalStatusCache.ts +95 -0
- package/src/features/settings/utils/shouldShowMcpAgentsSettings.spec.ts +66 -0
- package/src/features/settings/utils/shouldShowMcpAgentsSettings.ts +16 -0
- package/src/i18n/translations/en/settings.json +201 -0
- package/src/i18n/translations/fr/settings.json +201 -0
- package/src/index.ts +1 -0
- package/src/service-worker/sw.ts +4 -2
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
|
2
2
|
import type { AuthSession } from '../types';
|
|
3
3
|
import { AuthRequestError } from '../utils/authRequestError';
|
|
4
|
+
import { finishShellSignOut } from '../utils/identityBrowserLogout';
|
|
4
5
|
import { generateCodeChallenge } from '../utils/pkce';
|
|
5
6
|
import { WEB_PKCE_FLOW_PARAM, takeWebPkceVerifier } from '../utils/webPkce';
|
|
6
7
|
import { createShellUIAuthBackend } from './shellui';
|
|
@@ -346,3 +347,112 @@ describe('shellui backend deleteAccount', () => {
|
|
|
346
347
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
347
348
|
});
|
|
348
349
|
});
|
|
350
|
+
|
|
351
|
+
describe('shellui identity browser logout', () => {
|
|
352
|
+
const fetchMock = vi.fn();
|
|
353
|
+
const session = { accessToken: 'access-1', refreshToken: 'refresh-1' } as AuthSession;
|
|
354
|
+
const returnTo = 'https://app.example.com/docs?q=a+b&next=%2Fapps';
|
|
355
|
+
|
|
356
|
+
beforeEach(() => {
|
|
357
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
afterEach(() => {
|
|
361
|
+
fetchMock.mockReset();
|
|
362
|
+
vi.unstubAllGlobals();
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
test('revokes with bearer before navigating to the encoded logout URL', async () => {
|
|
366
|
+
const order: string[] = [];
|
|
367
|
+
fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
368
|
+
const url = String(input);
|
|
369
|
+
order.push(`${init?.method ?? 'GET'} ${url}`);
|
|
370
|
+
if (url.includes('/api/v1/logout')) {
|
|
371
|
+
expect(init?.credentials).toBeUndefined();
|
|
372
|
+
expect((init?.headers as Record<string, string>).Authorization).toBe('Bearer access-1');
|
|
373
|
+
expect(JSON.parse(String(init?.body))).toEqual({ refresh_token: 'refresh-1' });
|
|
374
|
+
return new Response(null, { status: 204 });
|
|
375
|
+
}
|
|
376
|
+
return jsonResponse(200, { logout_url: 'https://auth.example.com/oauth/logout' });
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
const backend = createShellUIAuthBackend({
|
|
380
|
+
backendUrl: 'https://auth.example.com',
|
|
381
|
+
companyId: 7,
|
|
382
|
+
});
|
|
383
|
+
const resolveLogoutUrl = backend.resolveIdentityBrowserLogoutUrl;
|
|
384
|
+
if (!resolveLogoutUrl) throw new Error('Expected an identity browser logout resolver.');
|
|
385
|
+
const navigated: string[] = [];
|
|
386
|
+
const didNavigate = await finishShellSignOut({
|
|
387
|
+
revoke: () => backend.logout(session),
|
|
388
|
+
clearLocal: () => {
|
|
389
|
+
order.push('clear');
|
|
390
|
+
},
|
|
391
|
+
readBrowserLogoutUrl: () => resolveLogoutUrl(returnTo),
|
|
392
|
+
navigate: (url) => {
|
|
393
|
+
order.push('navigate');
|
|
394
|
+
navigated.push(url);
|
|
395
|
+
},
|
|
396
|
+
initiatedHere: true,
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
expect(didNavigate).toBe(true);
|
|
400
|
+
expect(order).toEqual([
|
|
401
|
+
'POST https://auth.example.com/api/v1/logout',
|
|
402
|
+
'clear',
|
|
403
|
+
'GET https://auth.example.com/api/v1/settings?company_id=7',
|
|
404
|
+
'navigate',
|
|
405
|
+
]);
|
|
406
|
+
const target = new URL(navigated[0] as string);
|
|
407
|
+
expect(`${target.origin}${target.pathname}`).toBe('https://auth.example.com/oauth/logout');
|
|
408
|
+
expect(target.searchParams.get('company_id')).toBe('7');
|
|
409
|
+
expect(target.searchParams.get('return_to')).toBe(returnTo);
|
|
410
|
+
expect(navigated[0]).toContain(`return_to=${encodeURIComponent(returnTo)}`);
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
test('keeps token revoke and skips navigation when logout_url is absent', async () => {
|
|
414
|
+
fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
|
|
415
|
+
if (String(input).includes('/api/v1/logout')) return new Response(null, { status: 204 });
|
|
416
|
+
return jsonResponse(200, { methods: ['magic_link'] });
|
|
417
|
+
});
|
|
418
|
+
const backend = createShellUIAuthBackend({
|
|
419
|
+
backendUrl: 'https://auth.example.com',
|
|
420
|
+
companyId: '7',
|
|
421
|
+
});
|
|
422
|
+
const resolveLogoutUrl = backend.resolveIdentityBrowserLogoutUrl;
|
|
423
|
+
if (!resolveLogoutUrl) throw new Error('Expected an identity browser logout resolver.');
|
|
424
|
+
const navigate = vi.fn();
|
|
425
|
+
const didNavigate = await finishShellSignOut({
|
|
426
|
+
revoke: () => backend.logout(session),
|
|
427
|
+
clearLocal: () => {},
|
|
428
|
+
readBrowserLogoutUrl: () => resolveLogoutUrl(returnTo),
|
|
429
|
+
navigate,
|
|
430
|
+
initiatedHere: true,
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
expect(didNavigate).toBe(false);
|
|
434
|
+
expect(navigate).not.toHaveBeenCalled();
|
|
435
|
+
const logoutCall = fetchMock.mock.calls.find((call) =>
|
|
436
|
+
String(call[0]).includes('/api/v1/logout'),
|
|
437
|
+
) as [string, RequestInit] | undefined;
|
|
438
|
+
expect(logoutCall?.[1].method).toBe('POST');
|
|
439
|
+
expect((logoutCall?.[1].headers as Record<string, string>).Authorization).toBe(
|
|
440
|
+
'Bearer access-1',
|
|
441
|
+
);
|
|
442
|
+
expect(String(fetchMock.mock.calls[0]?.[0])).toContain('/api/v1/logout');
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
test('does not follow a logout_url on another origin', async () => {
|
|
446
|
+
fetchMock.mockResolvedValue(
|
|
447
|
+
jsonResponse(200, { logout_url: 'https://evil.example/oauth/logout' }),
|
|
448
|
+
);
|
|
449
|
+
const backend = createShellUIAuthBackend({
|
|
450
|
+
backendUrl: 'https://auth.example.com',
|
|
451
|
+
companyId: 7,
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
const resolveLogoutUrl = backend.resolveIdentityBrowserLogoutUrl;
|
|
455
|
+
if (!resolveLogoutUrl) throw new Error('Expected an identity browser logout resolver.');
|
|
456
|
+
await expect(resolveLogoutUrl(returnTo)).resolves.toBeNull();
|
|
457
|
+
});
|
|
458
|
+
});
|
|
@@ -10,7 +10,8 @@ import {
|
|
|
10
10
|
import { AuthRequestError } from '../utils/authRequestError';
|
|
11
11
|
import { clearWebPkce, prepareWebPkce } from '../utils/webPkce';
|
|
12
12
|
import { getShellUILoginCompanyId } from '../utils/clientLoginContext';
|
|
13
|
-
import
|
|
13
|
+
import { buildIdentityBrowserLogoutUrl } from '../utils/identityBrowserLogout';
|
|
14
|
+
import type { AuthSession, AuthSettings, UserPreferences } from '../types';
|
|
14
15
|
import type { AuthBackend } from './types';
|
|
15
16
|
|
|
16
17
|
const USER_PREFERENCES_ENDPOINT = '/api/v1/preferences';
|
|
@@ -19,6 +20,13 @@ const OAUTH_SESSION_ENDPOINT = '/api/v1/oauth/session';
|
|
|
19
20
|
const MAGIC_LINK_REQUEST_ENDPOINT = '/api/v1/magic-link/request';
|
|
20
21
|
const USER_ENDPOINT = '/api/v1/user';
|
|
21
22
|
|
|
23
|
+
const EMPTY_AUTH_SETTINGS: AuthSettings = {
|
|
24
|
+
methods: [],
|
|
25
|
+
oauthProviders: [],
|
|
26
|
+
oauthClients: [],
|
|
27
|
+
logoutUrl: null,
|
|
28
|
+
};
|
|
29
|
+
|
|
22
30
|
const parseAuthErrorPayload = (
|
|
23
31
|
payload: Record<string, unknown> | null,
|
|
24
32
|
response: Response,
|
|
@@ -39,6 +47,24 @@ export const createShellUIAuthBackend = ({
|
|
|
39
47
|
backendUrl: string | null;
|
|
40
48
|
companyId?: string | number;
|
|
41
49
|
}): AuthBackend => {
|
|
50
|
+
const loadAuthSettings = async (): Promise<AuthSettings> => {
|
|
51
|
+
if (!backendUrl) return EMPTY_AUTH_SETTINGS;
|
|
52
|
+
const endpoint = new URL(`${backendUrl}/api/v1/settings`);
|
|
53
|
+
const selectedCompanyId = getShellUILoginCompanyId(companyId);
|
|
54
|
+
if (selectedCompanyId) {
|
|
55
|
+
endpoint.searchParams.set('company_id', selectedCompanyId);
|
|
56
|
+
}
|
|
57
|
+
const response = await fetch(endpoint.toString(), {
|
|
58
|
+
method: 'GET',
|
|
59
|
+
headers: { Accept: 'application/json' },
|
|
60
|
+
});
|
|
61
|
+
if (!response.ok) {
|
|
62
|
+
throw new Error(`HTTP ${response.status}`);
|
|
63
|
+
}
|
|
64
|
+
const payload = (await response.json()) as unknown;
|
|
65
|
+
return normalizeAuthSettings(payload);
|
|
66
|
+
};
|
|
67
|
+
|
|
42
68
|
const refreshWithStoredToken = async (
|
|
43
69
|
storedSession: AuthSession,
|
|
44
70
|
nowSeconds: number,
|
|
@@ -206,6 +232,25 @@ export const createShellUIAuthBackend = ({
|
|
|
206
232
|
}),
|
|
207
233
|
});
|
|
208
234
|
},
|
|
235
|
+
resolveIdentityBrowserLogoutUrl: async (returnTo) => {
|
|
236
|
+
if (!backendUrl) return null;
|
|
237
|
+
const selectedCompanyId = getShellUILoginCompanyId(companyId);
|
|
238
|
+
if (!selectedCompanyId) return null;
|
|
239
|
+
let settings: AuthSettings;
|
|
240
|
+
try {
|
|
241
|
+
settings = await loadAuthSettings();
|
|
242
|
+
} catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
const logoutUrl = settings.logoutUrl;
|
|
246
|
+
if (!logoutUrl) return null;
|
|
247
|
+
try {
|
|
248
|
+
if (new URL(logoutUrl).origin !== new URL(backendUrl).origin) return null;
|
|
249
|
+
} catch {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
return buildIdentityBrowserLogoutUrl(logoutUrl, selectedCompanyId, returnTo);
|
|
253
|
+
},
|
|
209
254
|
supportsAccountDeletion: true,
|
|
210
255
|
deleteAccount: async (session) => {
|
|
211
256
|
if (!backendUrl) {
|
|
@@ -273,25 +318,7 @@ export const createShellUIAuthBackend = ({
|
|
|
273
318
|
const savedName = typeof metadata?.name === 'string' ? metadata.name : name;
|
|
274
319
|
return { name: savedName };
|
|
275
320
|
},
|
|
276
|
-
getAuthSettings:
|
|
277
|
-
if (!backendUrl) {
|
|
278
|
-
return { methods: [], oauthProviders: [], oauthClients: [] };
|
|
279
|
-
}
|
|
280
|
-
const endpoint = new URL(`${backendUrl}/api/v1/settings`);
|
|
281
|
-
const selectedCompanyId = getShellUILoginCompanyId(companyId);
|
|
282
|
-
if (selectedCompanyId) {
|
|
283
|
-
endpoint.searchParams.set('company_id', selectedCompanyId);
|
|
284
|
-
}
|
|
285
|
-
const response = await fetch(endpoint.toString(), {
|
|
286
|
-
method: 'GET',
|
|
287
|
-
headers: { Accept: 'application/json' },
|
|
288
|
-
});
|
|
289
|
-
if (!response.ok) {
|
|
290
|
-
throw new Error(`HTTP ${response.status}`);
|
|
291
|
-
}
|
|
292
|
-
const payload = (await response.json()) as unknown;
|
|
293
|
-
return normalizeAuthSettings(payload);
|
|
294
|
-
},
|
|
321
|
+
getAuthSettings: () => loadAuthSettings(),
|
|
295
322
|
sendMagicLink: async (email, redirectPath, options) => {
|
|
296
323
|
if (!backendUrl) {
|
|
297
324
|
throw new Error('Missing Shellui backend URL.');
|
|
@@ -35,6 +35,11 @@ export interface AuthBackend {
|
|
|
35
35
|
) => void | Promise<void>;
|
|
36
36
|
startWeb3Ethereum: () => Promise<AuthSession | null>;
|
|
37
37
|
logout: (session: AuthSession | null) => Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Absolute identity browser logout URL for `returnTo`, or null when this
|
|
40
|
+
* backend has no `logout_url`. Does not navigate and does not revoke tokens.
|
|
41
|
+
*/
|
|
42
|
+
resolveIdentityBrowserLogoutUrl?: (returnTo: string) => Promise<string | null>;
|
|
38
43
|
/** Whether {@link deleteAccount} is implemented for this backend. */
|
|
39
44
|
supportsAccountDeletion: boolean;
|
|
40
45
|
/** Permanently delete the signed-in user for the session's company. */
|
|
@@ -39,7 +39,12 @@ export interface AuthContextValue {
|
|
|
39
39
|
sendMagicLink: (email: string, redirectPath?: string) => Promise<void>;
|
|
40
40
|
syncUserPreferences: (preferences: UserPreferences) => Promise<void>;
|
|
41
41
|
loadUserPreferences: () => Promise<UserPreferences | null>;
|
|
42
|
-
|
|
42
|
+
/**
|
|
43
|
+
* Sign out. `returnTo` is a shell path or same-origin URL to open afterwards.
|
|
44
|
+
* When identity exposes `logout_url`, the browser is sent there and identity
|
|
45
|
+
* redirects to `returnTo`. Otherwise the shell opens `returnTo` itself.
|
|
46
|
+
*/
|
|
47
|
+
logout: (options?: { returnTo?: string }) => Promise<void>;
|
|
43
48
|
/** Whether the configured auth backend supports self-service account deletion. */
|
|
44
49
|
supportsAccountDeletion: boolean;
|
|
45
50
|
/** Delete the signed-in account for the current company, then sign out. */
|
|
@@ -41,6 +41,11 @@ export interface AuthSettings {
|
|
|
41
41
|
provider: string;
|
|
42
42
|
label: string;
|
|
43
43
|
}>;
|
|
44
|
+
/**
|
|
45
|
+
* Identity browser logout URL from `GET /api/v1/settings` (`logout_url`).
|
|
46
|
+
* Null on older identity services that do not send it.
|
|
47
|
+
*/
|
|
48
|
+
logoutUrl?: string | null;
|
|
44
49
|
}
|
|
45
50
|
|
|
46
51
|
export type UserPreferences = {
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import type { AuthSession } from '../types';
|
|
3
|
+
import { AUTH_PROFILE_STORAGE_KEY, AUTH_REFRESH_STORAGE_KEY } from './authStorageKeys';
|
|
4
|
+
import { persistAuthSession, readStoredAuthSession } from './authSessionPersistence';
|
|
5
|
+
import { AuthRequestError } from './authRequestError';
|
|
6
|
+
import { isUnauthorizedRefreshError, planStoredSessionBoot } from './canRestoreStoredSession';
|
|
7
|
+
import {
|
|
8
|
+
exchangeAuthCodeViaBff,
|
|
9
|
+
exchangeShellSessionCode,
|
|
10
|
+
logoutBffAuthSession,
|
|
11
|
+
probeBffAuthRoutes,
|
|
12
|
+
refreshBffAuthSession,
|
|
13
|
+
rememberHostCookieSession,
|
|
14
|
+
resetBffRouteProbeForTests,
|
|
15
|
+
resolveBffAuthRoutes,
|
|
16
|
+
} from './bffAuthClient';
|
|
17
|
+
|
|
18
|
+
const now = 1_700_000_000;
|
|
19
|
+
|
|
20
|
+
function accessJwt(email = 'ada@example.com') {
|
|
21
|
+
const payload = Buffer.from(
|
|
22
|
+
JSON.stringify({ sub: 'user-1', email, user_metadata: { name: 'Ada' } }),
|
|
23
|
+
).toString('base64url');
|
|
24
|
+
return `eyJhbGciOiJub25lIn0.${payload}.sig`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function storageMock(): Storage {
|
|
28
|
+
const data = new Map<string, string>();
|
|
29
|
+
return {
|
|
30
|
+
getItem: (key: string) => data.get(key) ?? null,
|
|
31
|
+
setItem: (key: string, value: string) => {
|
|
32
|
+
data.set(key, value);
|
|
33
|
+
},
|
|
34
|
+
removeItem: (key: string) => {
|
|
35
|
+
data.delete(key);
|
|
36
|
+
},
|
|
37
|
+
clear: () => data.clear(),
|
|
38
|
+
key: () => null,
|
|
39
|
+
get length() {
|
|
40
|
+
return data.size;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function jsonResponse(status: number, body: unknown, contentType = 'application/json') {
|
|
46
|
+
return {
|
|
47
|
+
ok: status >= 200 && status < 300,
|
|
48
|
+
status,
|
|
49
|
+
headers: {
|
|
50
|
+
get: (name: string) => (name.toLowerCase() === 'content-type' ? contentType : null),
|
|
51
|
+
},
|
|
52
|
+
json: async () => body,
|
|
53
|
+
} as unknown as Response;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const baseSession = (): AuthSession => ({
|
|
57
|
+
accessToken: accessJwt(),
|
|
58
|
+
refreshToken: '',
|
|
59
|
+
tokenType: 'bearer',
|
|
60
|
+
expiresAt: now + 300,
|
|
61
|
+
provider: 'github',
|
|
62
|
+
userId: 'user-1',
|
|
63
|
+
userEmail: 'ada@example.com',
|
|
64
|
+
userName: 'Ada',
|
|
65
|
+
userAvatarUrl: null,
|
|
66
|
+
userIsStaff: false,
|
|
67
|
+
userIsCompanyOwner: false,
|
|
68
|
+
userGroups: [],
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe('host cookie session', () => {
|
|
72
|
+
const fetchMock = vi.fn();
|
|
73
|
+
|
|
74
|
+
beforeEach(() => {
|
|
75
|
+
resetBffRouteProbeForTests();
|
|
76
|
+
fetchMock.mockReset();
|
|
77
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
78
|
+
vi.stubGlobal('window', { location: { origin: 'https://shell.example' } });
|
|
79
|
+
vi.stubGlobal('localStorage', storageMock());
|
|
80
|
+
vi.stubGlobal('sessionStorage', storageMock());
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
afterEach(() => {
|
|
84
|
+
resetBffRouteProbeForTests();
|
|
85
|
+
vi.unstubAllGlobals();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('exchanges the auth code on the host and stores no refresh token', async () => {
|
|
89
|
+
fetchMock.mockResolvedValue(
|
|
90
|
+
jsonResponse(200, {
|
|
91
|
+
access_token: accessJwt(),
|
|
92
|
+
refresh_token: 'refresh-secret',
|
|
93
|
+
expires_in: 300,
|
|
94
|
+
token_type: 'bearer',
|
|
95
|
+
user: { id: 'user-1', email: 'ada@example.com', name: 'Ada' },
|
|
96
|
+
}),
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
const session = await exchangeAuthCodeViaBff({
|
|
100
|
+
authCode: 'code-1',
|
|
101
|
+
redirectTo: 'https://shell.example/login/callback',
|
|
102
|
+
codeVerifier: 'verifier-1',
|
|
103
|
+
nowSeconds: now,
|
|
104
|
+
});
|
|
105
|
+
if (!session) throw new Error('expected a session');
|
|
106
|
+
const stored = rememberHostCookieSession(session);
|
|
107
|
+
|
|
108
|
+
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
109
|
+
expect(fetchMock.mock.calls[0][0]).toBe('/api/auth/session');
|
|
110
|
+
expect(init.method).toBe('POST');
|
|
111
|
+
expect(init.credentials).toBe('include');
|
|
112
|
+
expect(JSON.parse(init.body as string)).toEqual({
|
|
113
|
+
auth_code: 'code-1',
|
|
114
|
+
redirect_to: 'https://shell.example/login/callback',
|
|
115
|
+
code_verifier: 'verifier-1',
|
|
116
|
+
});
|
|
117
|
+
expect(stored.refreshToken).toBe('');
|
|
118
|
+
expect(stored.accessToken).toBe(accessJwt());
|
|
119
|
+
expect(stored.userEmail).toBe('ada@example.com');
|
|
120
|
+
expect(sessionStorage.getItem(AUTH_REFRESH_STORAGE_KEY)).toBeNull();
|
|
121
|
+
const profile = localStorage.getItem(AUTH_PROFILE_STORAGE_KEY) ?? '';
|
|
122
|
+
expect(profile).not.toContain('refresh-secret');
|
|
123
|
+
expect(profile).not.toContain(accessJwt());
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('refreshes from the cookie and still does not keep a refresh token', async () => {
|
|
127
|
+
fetchMock.mockResolvedValue(
|
|
128
|
+
jsonResponse(200, {
|
|
129
|
+
access_token: accessJwt('ada@example.com'),
|
|
130
|
+
refresh_token: 'rotated-refresh',
|
|
131
|
+
expires_in: 300,
|
|
132
|
+
token_type: 'bearer',
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
const next = await refreshBffAuthSession(baseSession(), now);
|
|
136
|
+
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
137
|
+
expect(fetchMock.mock.calls[0][0]).toBe('/api/auth/refresh');
|
|
138
|
+
expect(init.method).toBe('POST');
|
|
139
|
+
expect(init.credentials).toBe('include');
|
|
140
|
+
expect(init.body).toBeUndefined();
|
|
141
|
+
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
|
142
|
+
expect(next?.refreshToken).toBe('');
|
|
143
|
+
expect(next?.accessToken).toContain('eyJ');
|
|
144
|
+
expect(JSON.stringify(next)).not.toContain('rotated-refresh');
|
|
145
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it('signs out through the host without sending a refresh token', async () => {
|
|
149
|
+
fetchMock.mockResolvedValue(jsonResponse(204, {}));
|
|
150
|
+
await logoutBffAuthSession('access-1');
|
|
151
|
+
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
152
|
+
expect(fetchMock.mock.calls[0][0]).toBe('/api/auth/logout');
|
|
153
|
+
expect(init.method).toBe('POST');
|
|
154
|
+
expect(init.credentials).toBe('include');
|
|
155
|
+
expect(init.body).toBeUndefined();
|
|
156
|
+
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer access-1');
|
|
157
|
+
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
|
158
|
+
expect(JSON.stringify(init.headers)).not.toContain('refresh');
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('restores a new tab from the profile and the host cookie', async () => {
|
|
162
|
+
rememberHostCookieSession({ ...baseSession(), refreshToken: 'must-not-stick' });
|
|
163
|
+
const stored = readStoredAuthSession();
|
|
164
|
+
if (!stored) throw new Error('expected a stored profile');
|
|
165
|
+
expect(stored.accessToken).toBe('');
|
|
166
|
+
expect(stored.refreshToken).toBe('');
|
|
167
|
+
expect(planStoredSessionBoot(stored, true)).toEqual({ action: 'refresh', session: stored });
|
|
168
|
+
|
|
169
|
+
const renewed = accessJwt();
|
|
170
|
+
fetchMock.mockResolvedValue(
|
|
171
|
+
jsonResponse(200, {
|
|
172
|
+
access_token: renewed,
|
|
173
|
+
refresh_token: 'rotated-refresh',
|
|
174
|
+
expires_in: 300,
|
|
175
|
+
}),
|
|
176
|
+
);
|
|
177
|
+
const next = await refreshBffAuthSession(stored, now);
|
|
178
|
+
if (!next) throw new Error('expected a refreshed session');
|
|
179
|
+
rememberHostCookieSession(next);
|
|
180
|
+
expect(next.accessToken).toBe(renewed);
|
|
181
|
+
expect(next.refreshToken).toBe('');
|
|
182
|
+
expect(sessionStorage.getItem(AUTH_REFRESH_STORAGE_KEY)).toBeNull();
|
|
183
|
+
expect(localStorage.getItem(AUTH_PROFILE_STORAGE_KEY)).not.toContain('rotated-refresh');
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it('treats a missing cookie as one failed refresh, not a retry loop', async () => {
|
|
187
|
+
fetchMock.mockResolvedValue(jsonResponse(401, { error: 'missing refresh cookie' }));
|
|
188
|
+
const error = await refreshBffAuthSession(baseSession(), now).catch((err) => err);
|
|
189
|
+
expect(isUnauthorizedRefreshError(error)).toBe(true);
|
|
190
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it('falls back once when the host routes are absent', async () => {
|
|
194
|
+
fetchMock.mockResolvedValue(jsonResponse(200, '<html></html>', 'text/html'));
|
|
195
|
+
const direct = vi.fn(async () => ({ ...baseSession(), refreshToken: 'direct-refresh' }));
|
|
196
|
+
const session = await exchangeShellSessionCode({
|
|
197
|
+
useBff: true,
|
|
198
|
+
authCode: 'code-1',
|
|
199
|
+
redirectTo: 'https://shell.example/login/callback',
|
|
200
|
+
codeVerifier: 'verifier-1',
|
|
201
|
+
nowSeconds: now,
|
|
202
|
+
exchangeDirect: direct,
|
|
203
|
+
});
|
|
204
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
205
|
+
expect(direct).toHaveBeenCalledTimes(1);
|
|
206
|
+
expect(session?.refreshToken).toBe('direct-refresh');
|
|
207
|
+
|
|
208
|
+
fetchMock.mockClear();
|
|
209
|
+
direct.mockClear();
|
|
210
|
+
const again = await resolveBffAuthRoutes({ backendType: 'shellui', explicitlyDisabled: false });
|
|
211
|
+
expect(again).toBe(false);
|
|
212
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it('does not exchange the code again when identity returns 400 without error_code', async () => {
|
|
216
|
+
fetchMock.mockResolvedValue(jsonResponse(400, { error: 'Origin does not match redirect_to.' }));
|
|
217
|
+
const direct = vi.fn();
|
|
218
|
+
const error = await exchangeShellSessionCode({
|
|
219
|
+
useBff: true,
|
|
220
|
+
authCode: 'code-1',
|
|
221
|
+
redirectTo: 'https://shell.example/login/callback',
|
|
222
|
+
codeVerifier: 'verifier-1',
|
|
223
|
+
nowSeconds: now,
|
|
224
|
+
exchangeDirect: direct,
|
|
225
|
+
}).catch((err) => err);
|
|
226
|
+
expect(error).toBeInstanceOf(AuthRequestError);
|
|
227
|
+
expect((error as AuthRequestError).code).toBeNull();
|
|
228
|
+
expect(direct).not.toHaveBeenCalled();
|
|
229
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it('does not fall back when identity rejects the code', async () => {
|
|
233
|
+
fetchMock.mockResolvedValue(
|
|
234
|
+
jsonResponse(400, { error: 'Auth code already used.', error_code: 'auth_code_used' }),
|
|
235
|
+
);
|
|
236
|
+
const direct = vi.fn();
|
|
237
|
+
const error = await exchangeShellSessionCode({
|
|
238
|
+
useBff: true,
|
|
239
|
+
authCode: 'code-1',
|
|
240
|
+
redirectTo: 'https://shell.example/login/callback',
|
|
241
|
+
nowSeconds: now,
|
|
242
|
+
exchangeDirect: direct,
|
|
243
|
+
}).catch((err) => err);
|
|
244
|
+
expect(error).toBeInstanceOf(AuthRequestError);
|
|
245
|
+
expect((error as AuthRequestError).code).toBe('auth_code_used');
|
|
246
|
+
expect(direct).not.toHaveBeenCalled();
|
|
247
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it('probes once and treats HTML as routes absent', async () => {
|
|
251
|
+
fetchMock.mockResolvedValue(jsonResponse(200, '<!doctype html>', 'text/html; charset=utf-8'));
|
|
252
|
+
expect(await probeBffAuthRoutes()).toBe(false);
|
|
253
|
+
expect(await probeBffAuthRoutes()).toBe(false);
|
|
254
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
255
|
+
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
256
|
+
expect(init.method).toBe('GET');
|
|
257
|
+
expect((init.headers as Record<string, string>).Accept).toBe('application/json');
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it('uses the host when the probe reports ready', async () => {
|
|
261
|
+
fetchMock.mockResolvedValue(jsonResponse(200, { ready: true }));
|
|
262
|
+
expect(await resolveBffAuthRoutes({ backendType: 'shellui', explicitlyDisabled: false })).toBe(
|
|
263
|
+
true,
|
|
264
|
+
);
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('does not probe when BFF is explicitly off', async () => {
|
|
268
|
+
fetchMock.mockResolvedValue(jsonResponse(200, { ready: true }));
|
|
269
|
+
expect(await resolveBffAuthRoutes({ backendType: 'shellui', explicitlyDisabled: true })).toBe(
|
|
270
|
+
false,
|
|
271
|
+
);
|
|
272
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it('leaves Supabase on the direct session', async () => {
|
|
276
|
+
fetchMock.mockResolvedValue(jsonResponse(200, { ready: true }));
|
|
277
|
+
expect(await resolveBffAuthRoutes({ backendType: 'supabase', explicitlyDisabled: false })).toBe(
|
|
278
|
+
false,
|
|
279
|
+
);
|
|
280
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
describe('default mode without the host', () => {
|
|
285
|
+
beforeEach(() => {
|
|
286
|
+
resetBffRouteProbeForTests();
|
|
287
|
+
vi.stubGlobal('localStorage', storageMock());
|
|
288
|
+
vi.stubGlobal('sessionStorage', storageMock());
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
afterEach(() => {
|
|
292
|
+
vi.unstubAllGlobals();
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it('exchanges on the page and stores the refresh token', async () => {
|
|
296
|
+
const direct = vi.fn(async () => ({ ...baseSession(), refreshToken: 'page-refresh' }));
|
|
297
|
+
const session = await exchangeShellSessionCode({
|
|
298
|
+
useBff: false,
|
|
299
|
+
authCode: 'code-1',
|
|
300
|
+
redirectTo: 'https://shell.example/login/callback',
|
|
301
|
+
nowSeconds: now,
|
|
302
|
+
exchangeDirect: direct,
|
|
303
|
+
});
|
|
304
|
+
if (!session) throw new Error('expected a session');
|
|
305
|
+
persistAuthSession(session);
|
|
306
|
+
expect(direct).toHaveBeenCalledTimes(1);
|
|
307
|
+
expect(session.refreshToken).toBe('page-refresh');
|
|
308
|
+
expect(sessionStorage.getItem(AUTH_REFRESH_STORAGE_KEY)).toBe('page-refresh');
|
|
309
|
+
const stored = readStoredAuthSession();
|
|
310
|
+
expect(stored?.refreshToken).toBe('page-refresh');
|
|
311
|
+
expect(stored?.accessToken).toBe('');
|
|
312
|
+
});
|
|
313
|
+
});
|