@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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/package.json +2 -2
  4. package/schemas/shellui.config.schema.json +45 -2
  5. package/src/app.tsx +2 -0
  6. package/src/features/auth/AuthProvider.tsx +212 -97
  7. package/src/features/auth/appBackend/configSchema.spec.ts +1 -0
  8. package/src/features/auth/appBackend/frameAuth.ts +5 -0
  9. package/src/features/auth/backends/shellui.spec.ts +110 -0
  10. package/src/features/auth/backends/shellui.ts +47 -20
  11. package/src/features/auth/backends/types.ts +5 -0
  12. package/src/features/auth/hooks/useAuth.tsx +6 -1
  13. package/src/features/auth/types.ts +5 -0
  14. package/src/features/auth/utils/bffAuthClient.spec.ts +313 -0
  15. package/src/features/auth/utils/bffAuthClient.ts +171 -49
  16. package/src/features/auth/utils/buildSessionFromParams.ts +5 -2
  17. package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +12 -0
  18. package/src/features/auth/utils/buildSessionFromTokenPayload.ts +3 -1
  19. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +140 -4
  20. package/src/features/auth/utils/canRestoreStoredSession.ts +47 -0
  21. package/src/features/auth/utils/cliCallback.ts +5 -0
  22. package/src/features/auth/utils/identityBrowserLogout.spec.ts +185 -0
  23. package/src/features/auth/utils/identityBrowserLogout.ts +174 -0
  24. package/src/features/auth/utils/index.ts +21 -3
  25. package/src/features/auth/utils/isBffAuthEnabled.ts +10 -2
  26. package/src/features/auth/utils/normalizeAuthSettings.spec.ts +9 -0
  27. package/src/features/auth/utils/normalizeAuthSettings.ts +3 -1
  28. package/src/features/auth/utils/pkce.spec.ts +29 -1
  29. package/src/features/auth/utils/pkce.ts +106 -2
  30. package/src/features/config/types.ts +37 -5
  31. package/src/features/mcp/mcpActivityErrorCodeI18n.spec.ts +32 -0
  32. package/src/features/mcp/mcpActivityErrorCodeI18n.ts +30 -0
  33. package/src/features/mcp/mcpAgentActivityMerge.spec.ts +91 -0
  34. package/src/features/mcp/mcpAgentActivityMerge.ts +53 -0
  35. package/src/features/mcp/mcpAgentActivityPresentation.spec.ts +129 -0
  36. package/src/features/mcp/mcpAgentActivityPresentation.ts +201 -0
  37. package/src/features/mcp/mcpAgentsConnect.spec.ts +215 -0
  38. package/src/features/mcp/mcpAgentsConnect.ts +189 -0
  39. package/src/features/mcp/mcpToolActivityRegistry.spec.ts +9 -0
  40. package/src/features/mcp/mcpToolActivityRegistry.ts +20 -0
  41. package/src/features/mcp/mcpToolApprovalsApi.spec.ts +113 -0
  42. package/src/features/mcp/mcpToolApprovalsApi.ts +162 -0
  43. package/src/features/mcp/personalAgentsApi.spec.ts +661 -0
  44. package/src/features/mcp/personalAgentsApi.ts +697 -0
  45. package/src/features/settings/SettingsIcons.tsx +28 -0
  46. package/src/features/settings/SettingsRoutes.tsx +8 -0
  47. package/src/features/settings/SettingsView.tsx +90 -26
  48. package/src/features/settings/components/McpAgentActivitySection.spec.tsx +255 -0
  49. package/src/features/settings/components/McpAgentActivitySection.tsx +481 -0
  50. package/src/features/settings/components/McpAgents.spec.tsx +336 -0
  51. package/src/features/settings/components/McpAgents.tsx +654 -0
  52. package/src/features/settings/components/McpPendingApprovals.spec.tsx +201 -0
  53. package/src/features/settings/components/McpPendingApprovals.tsx +168 -0
  54. package/src/features/settings/components/McpPersonalStatusPrefetch.tsx +21 -0
  55. package/src/features/settings/hooks/useMcpPendingToolApprovals.ts +69 -0
  56. package/src/features/settings/hooks/useMcpPersonalStatus.ts +83 -0
  57. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +44 -1
  58. package/src/features/settings/utils/buildSettingsForPropagation.ts +30 -1
  59. package/src/features/settings/utils/isMcpAgentsSettingsEligible.spec.ts +25 -0
  60. package/src/features/settings/utils/isMcpAgentsSettingsEligible.ts +14 -0
  61. package/src/features/settings/utils/loadMcpPersonalStatus.spec.ts +76 -0
  62. package/src/features/settings/utils/loadMcpPersonalStatus.ts +84 -0
  63. package/src/features/settings/utils/mcpPersonalStatusCache.spec.ts +77 -0
  64. package/src/features/settings/utils/mcpPersonalStatusCache.ts +95 -0
  65. package/src/features/settings/utils/shouldShowMcpAgentsSettings.spec.ts +66 -0
  66. package/src/features/settings/utils/shouldShowMcpAgentsSettings.ts +16 -0
  67. package/src/i18n/translations/en/settings.json +201 -0
  68. package/src/i18n/translations/fr/settings.json +201 -0
  69. package/src/index.ts +1 -0
  70. package/src/service-worker/sw.ts +4 -2
@@ -1,5 +1,7 @@
1
1
  import type { AuthSession } from '../types';
2
- import { buildSessionFromParams } from './buildSessionFromParams';
2
+ import { AuthRequestError } from './authRequestError';
3
+ import { persistAuthSession } from './authSessionPersistence';
4
+ import { buildSessionFromTokenPayload } from './buildSessionFromTokenPayload';
3
5
 
4
6
  const BFF_SESSION_PATH = '/api/auth/session';
5
7
  const BFF_REFRESH_PATH = '/api/auth/refresh';
@@ -11,45 +13,134 @@ type BffTokenResponse = {
11
13
  expires_at?: number | string;
12
14
  expires_in?: number | string;
13
15
  token_type?: string;
16
+ error?: string;
17
+ error_code?: string;
18
+ detail?: string;
19
+ ready?: boolean;
14
20
  };
15
21
 
16
- const parseBffTokenResponse = (
17
- payload: BffTokenResponse,
18
- current: AuthSession,
19
- nowSeconds: number,
20
- ): AuthSession | null => {
21
- const params = new URLSearchParams();
22
- if (typeof payload.access_token === 'string') {
23
- params.set('access_token', payload.access_token);
22
+ /** The host answered with a document or 404, so these routes are not mounted. */
23
+ export class BffRouteMissingError extends Error {
24
+ constructor() {
25
+ super('BFF routes are not available');
26
+ this.name = 'BffRouteMissingError';
24
27
  }
25
- if (typeof payload.refresh_token === 'string') {
26
- params.set('refresh_token', payload.refresh_token);
27
- } else if (current.refreshToken) {
28
- params.set('refresh_token', current.refreshToken);
29
- }
30
- if (typeof payload.expires_at === 'number' || typeof payload.expires_at === 'string') {
31
- params.set('expires_at', String(payload.expires_at));
32
- }
33
- if (typeof payload.expires_in === 'number' || typeof payload.expires_in === 'string') {
34
- params.set('expires_in', String(payload.expires_in));
28
+ }
29
+
30
+ export const isBffRouteMissingError = (error: unknown): boolean =>
31
+ error instanceof BffRouteMissingError ||
32
+ (typeof error === 'object' &&
33
+ error !== null &&
34
+ (error as { name?: string }).name === 'BffRouteMissingError');
35
+
36
+ let probeResult: Promise<boolean> | null = null;
37
+
38
+ /** Drop the cached probe. Tests call this between cases. */
39
+ export function resetBffRouteProbeForTests(): void {
40
+ probeResult = null;
41
+ }
42
+
43
+ /** Later resolves report the routes as absent, without another probe. */
44
+ export function markBffRoutesUnavailable(): void {
45
+ probeResult = Promise.resolve(false);
46
+ }
47
+
48
+ const responseIsJson = (response: Response): boolean =>
49
+ (response.headers.get('content-type') ?? '').includes('application/json');
50
+
51
+ async function readJson(response: Response): Promise<BffTokenResponse | null> {
52
+ try {
53
+ const payload = (await response.json()) as unknown;
54
+ if (!payload || typeof payload !== 'object') return null;
55
+ return payload as BffTokenResponse;
56
+ } catch {
57
+ return null;
35
58
  }
36
- if (typeof payload.token_type === 'string') {
37
- params.set('token_type', payload.token_type);
59
+ }
60
+
61
+ /**
62
+ * One GET per page load. HTML from a static host, a 404, or a failed fetch
63
+ * means the routes are absent. The result is cached so a miss cannot loop.
64
+ */
65
+ export function probeBffAuthRoutes(): Promise<boolean> {
66
+ if (!probeResult) {
67
+ probeResult = (async () => {
68
+ try {
69
+ const response = await fetch(BFF_SESSION_PATH, {
70
+ method: 'GET',
71
+ credentials: 'same-origin',
72
+ headers: { Accept: 'application/json' },
73
+ redirect: 'manual',
74
+ });
75
+ if (!response.ok || !responseIsJson(response)) return false;
76
+ const payload = await readJson(response);
77
+ return payload?.ready === true;
78
+ } catch {
79
+ return false;
80
+ }
81
+ })();
38
82
  }
39
- const built = buildSessionFromParams(params, nowSeconds);
40
- if (!built) return null;
83
+ return probeResult;
84
+ }
85
+
86
+ /**
87
+ * Shellui page should try the host cookie when the backend is Shellui and
88
+ * `security.bffAuth.enabled` is not false. The probe decides whether the
89
+ * routes exist. Supabase and an explicit `false` skip the probe.
90
+ */
91
+ export async function resolveBffAuthRoutes(input: {
92
+ backendType: string | undefined;
93
+ explicitlyDisabled: boolean;
94
+ }): Promise<boolean> {
95
+ if (input.explicitlyDisabled || input.backendType !== 'shellui') return false;
96
+ if (typeof window === 'undefined') return false;
97
+ return probeBffAuthRoutes();
98
+ }
99
+
100
+ const sessionFromHostPayload = (
101
+ payload: BffTokenResponse,
102
+ current: AuthSession | null,
103
+ nowSeconds: number,
104
+ ): AuthSession | null => {
105
+ const { refresh_token: _dropped, ...rest } = payload;
106
+ const built = buildSessionFromTokenPayload(rest, nowSeconds, { refreshTokenRequired: false });
107
+ if (!built?.accessToken) return null;
41
108
  return {
42
109
  ...built,
43
- provider: built.provider ?? current.provider,
44
- userPreferences: current.userPreferences ?? built.userPreferences,
110
+ refreshToken: '',
111
+ provider: built.provider ?? current?.provider ?? null,
112
+ userPreferences: current?.userPreferences ?? built.userPreferences,
45
113
  };
46
114
  };
47
115
 
48
- /** Hand refresh token to BFF; HttpOnly cookie is set server-side. Returns session without refresh in memory. */
49
- export const establishBffAuthSession = async (
50
- session: AuthSession,
51
- nowSeconds: number,
52
- ): Promise<AuthSession | null> => {
116
+ const throwForHostResponse = (response: Response, payload: BffTokenResponse | null): never => {
117
+ if (response.status === 404 || !responseIsJson(response)) {
118
+ throw new BffRouteMissingError();
119
+ }
120
+ const err = payload?.error ?? payload?.detail;
121
+ const message =
122
+ typeof err === 'string' && err.trim()
123
+ ? `${err} (HTTP ${response.status})`
124
+ : `HTTP ${response.status}`;
125
+ const code = typeof payload?.error_code === 'string' ? payload.error_code.trim() : null;
126
+ throw new AuthRequestError(message, code);
127
+ };
128
+
129
+ /**
130
+ * Exchange a one-time auth code on the shell host. The refresh token stays in
131
+ * the host cookie. This request body never includes `refresh_token`.
132
+ */
133
+ export const exchangeAuthCodeViaBff = async ({
134
+ authCode,
135
+ redirectTo,
136
+ codeVerifier,
137
+ nowSeconds,
138
+ }: {
139
+ authCode: string;
140
+ redirectTo: string;
141
+ codeVerifier?: string;
142
+ nowSeconds: number;
143
+ }): Promise<AuthSession | null> => {
53
144
  const response = await fetch(BFF_SESSION_PATH, {
54
145
  method: 'POST',
55
146
  credentials: 'include',
@@ -58,22 +149,50 @@ export const establishBffAuthSession = async (
58
149
  'Content-Type': 'application/json',
59
150
  },
60
151
  body: JSON.stringify({
61
- refresh_token: session.refreshToken,
62
- access_token: session.accessToken,
63
- expires_at: session.expiresAt,
64
- token_type: session.tokenType,
152
+ auth_code: authCode,
153
+ redirect_to: redirectTo,
154
+ ...(codeVerifier ? { code_verifier: codeVerifier } : {}),
65
155
  }),
66
156
  });
67
- if (!response.ok) {
68
- throw new Error(`BFF session failed (HTTP ${response.status})`);
157
+ const payload = responseIsJson(response) ? await readJson(response) : null;
158
+ if (!response.ok || !responseIsJson(response)) {
159
+ throwForHostResponse(response, payload);
69
160
  }
70
- const payload = (await response.json()) as BffTokenResponse;
71
- const next = parseBffTokenResponse(payload, session, nowSeconds);
72
- if (!next) return null;
73
- return { ...next, refreshToken: '' };
161
+ if (!payload) return null;
162
+ return sessionFromHostPayload(payload, null, nowSeconds);
74
163
  };
75
164
 
76
- /** Refresh access token via same-origin BFF (HttpOnly refresh cookie). */
165
+ /**
166
+ * Code exchange for the shell session. When the host routes are up, the page
167
+ * does not call identity. A missing route falls back once to the direct
168
+ * exchange. An identity error does not fall back: the code may already be spent.
169
+ */
170
+ export async function exchangeShellSessionCode(input: {
171
+ useBff: boolean;
172
+ authCode: string;
173
+ redirectTo: string;
174
+ codeVerifier?: string;
175
+ nowSeconds: number;
176
+ exchangeDirect: () => Promise<AuthSession | null>;
177
+ }): Promise<AuthSession | null> {
178
+ if (!input.useBff) return input.exchangeDirect();
179
+ try {
180
+ return await exchangeAuthCodeViaBff(input);
181
+ } catch (error) {
182
+ if (!isBffRouteMissingError(error)) throw error;
183
+ markBffRoutesUnavailable();
184
+ return input.exchangeDirect();
185
+ }
186
+ }
187
+
188
+ /** Profile in localStorage, no refresh token in sessionStorage or in the returned session. */
189
+ export function rememberHostCookieSession(session: AuthSession): AuthSession {
190
+ const next = { ...session, refreshToken: '' };
191
+ persistAuthSession(next, { storeRefreshToken: false });
192
+ return next;
193
+ }
194
+
195
+ /** Refresh the access token from the shell-host cookie. */
77
196
  export const refreshBffAuthSession = async (
78
197
  current: AuthSession,
79
198
  nowSeconds: number,
@@ -81,27 +200,30 @@ export const refreshBffAuthSession = async (
81
200
  const response = await fetch(BFF_REFRESH_PATH, {
82
201
  method: 'POST',
83
202
  credentials: 'include',
84
- headers: { Accept: 'application/json' },
203
+ headers: {
204
+ Accept: 'application/json',
205
+ 'Content-Type': 'application/json',
206
+ },
85
207
  });
208
+ const payload = responseIsJson(response) ? await readJson(response) : null;
86
209
  if (!response.ok) {
87
- throw new Error(`HTTP ${response.status}`);
210
+ throwForHostResponse(response, payload);
88
211
  }
89
- const payload = (await response.json()) as BffTokenResponse;
90
- const next = parseBffTokenResponse(payload, current, nowSeconds);
91
- if (!next) return null;
92
- return { ...next, refreshToken: '' };
212
+ if (!payload) return null;
213
+ return sessionFromHostPayload(payload, current, nowSeconds);
93
214
  };
94
215
 
95
- /** Clear BFF HttpOnly cookie and optionally notify identity logout. */
216
+ /** Clear the host cookie. Identity revocation happens on the host, from the cookie. */
96
217
  export const logoutBffAuthSession = async (accessToken: string | null | undefined) => {
97
218
  await fetch(BFF_LOGOUT_PATH, {
98
219
  method: 'POST',
99
220
  credentials: 'include',
100
221
  headers: {
101
222
  Accept: 'application/json',
223
+ 'Content-Type': 'application/json',
102
224
  ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
103
225
  },
104
226
  }).catch(() => {
105
- // Best-effort; local session is cleared regardless.
227
+ // Local session is cleared either way.
106
228
  });
107
229
  };
@@ -5,10 +5,13 @@ import { decodeJwtPayload, normalizeJwtUserGroups } from './decodeJwtPayload';
5
5
  export const buildSessionFromParams = (
6
6
  params: URLSearchParams,
7
7
  nowSeconds: number,
8
+ options?: { refreshTokenRequired?: boolean },
8
9
  ): AuthSession | null => {
9
10
  const accessToken = params.get('access_token');
10
- const refreshToken = params.get('refresh_token');
11
- if (!accessToken || !refreshToken) return null;
11
+ const refreshToken = params.get('refresh_token') ?? '';
12
+ const refreshRequired = options?.refreshTokenRequired !== false;
13
+ if (!accessToken) return null;
14
+ if (refreshRequired && !refreshToken) return null;
12
15
 
13
16
  const expiresAtFromParam = Number(params.get('expires_at'));
14
17
  const expiresInFromParam = Number(params.get('expires_in'));
@@ -26,4 +26,16 @@ describe('buildSessionFromTokenPayload', () => {
26
26
  test('returns null when tokens are missing', () => {
27
27
  expect(buildSessionFromTokenPayload({ access_token: 'only-access' }, 0)).toBeNull();
28
28
  });
29
+
30
+ test('allows a missing refresh token when the host keeps it', () => {
31
+ const now = 1_700_000_000;
32
+ const session = buildSessionFromTokenPayload(
33
+ { access_token: 'access-only', expires_in: 300, token_type: 'bearer' },
34
+ now,
35
+ { refreshTokenRequired: false },
36
+ );
37
+ expect(session?.accessToken).toBe('access-only');
38
+ expect(session?.refreshToken).toBe('');
39
+ expect(session?.expiresAt).toBe(now + 300);
40
+ });
29
41
  });
@@ -21,4 +21,6 @@ export const tokenPayloadToUrlParams = (
21
21
  export const buildSessionFromTokenPayload = (
22
22
  payload: Record<string, unknown> | null | undefined,
23
23
  nowSeconds: number,
24
- ): AuthSession | null => buildSessionFromParams(tokenPayloadToUrlParams(payload), nowSeconds);
24
+ options?: { refreshTokenRequired?: boolean },
25
+ ): AuthSession | null =>
26
+ buildSessionFromParams(tokenPayloadToUrlParams(payload), nowSeconds, options);
@@ -1,14 +1,49 @@
1
- import { describe, expect, it } from 'vitest';
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
2
  import type { AuthSession } from '../types';
3
- import { canRestoreStoredSession } from './canRestoreStoredSession';
3
+ import { AUTH_PROFILE_STORAGE_KEY, AUTH_REFRESH_STORAGE_KEY } from './authStorageKeys';
4
+ import {
5
+ clearStoredAuthSession,
6
+ hasStoredAuthSession,
7
+ persistAuthSession,
8
+ readStoredAuthSession,
9
+ } from './authSessionPersistence';
10
+ import {
11
+ canRestoreStoredSession,
12
+ isUnauthorizedRefreshError,
13
+ planStoredSessionBoot,
14
+ } from './canRestoreStoredSession';
15
+
16
+ const future = Math.floor(Date.now() / 1000) + 3600;
17
+ const past = Math.floor(Date.now() / 1000) - 120;
4
18
 
5
19
  const base = {
6
20
  accessToken: '',
7
21
  refreshToken: '',
8
22
  tokenType: 'bearer',
9
- expiresAt: Math.floor(Date.now() / 1000) + 3600,
23
+ expiresAt: future,
10
24
  provider: 'github',
11
- } as unknown as AuthSession;
25
+ userId: 'user-1',
26
+ userEmail: 'a@example.com',
27
+ userName: 'Ada',
28
+ userAvatarUrl: null,
29
+ userIsStaff: false,
30
+ userIsCompanyOwner: false,
31
+ userGroups: [],
32
+ } as AuthSession;
33
+
34
+ const createStorageMock = () => {
35
+ const data = new Map<string, string>();
36
+ return {
37
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
38
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
39
+ removeItem: vi.fn((key: string) => data.delete(key)),
40
+ clear: vi.fn(() => data.clear()),
41
+ key: vi.fn(() => null),
42
+ get length() {
43
+ return data.size;
44
+ },
45
+ } as unknown as Storage;
46
+ };
12
47
 
13
48
  describe('canRestoreStoredSession', () => {
14
49
  it('rejects a profile without tokens, as seen in a new tab', () => {
@@ -27,3 +62,104 @@ describe('canRestoreStoredSession', () => {
27
62
  expect(canRestoreStoredSession(base, true)).toBe(true);
28
63
  });
29
64
  });
65
+
66
+ describe('planStoredSessionBoot', () => {
67
+ it('clears a profile that has no refresh token when BFF is off', () => {
68
+ expect(planStoredSessionBoot(base, false)).toEqual({ action: 'clear' });
69
+ });
70
+
71
+ it('refreshes a token-less profile through the BFF cookie', () => {
72
+ expect(planStoredSessionBoot(base, true)).toEqual({ action: 'refresh', session: base });
73
+ });
74
+
75
+ it('refreshes when a refresh token is present', () => {
76
+ const stored = { ...base, refreshToken: 'r' };
77
+ expect(planStoredSessionBoot(stored, false)).toEqual({ action: 'refresh', session: stored });
78
+ });
79
+
80
+ it('uses a still-valid access token', () => {
81
+ const stored = { ...base, accessToken: 'a' };
82
+ expect(planStoredSessionBoot(stored, false)).toEqual({ action: 'use', session: stored });
83
+ });
84
+
85
+ it('refreshes an expired access token when a refresh token exists', () => {
86
+ const stored = { ...base, accessToken: 'a', refreshToken: 'r', expiresAt: past };
87
+ expect(planStoredSessionBoot(stored, false)).toEqual({ action: 'refresh', session: stored });
88
+ });
89
+
90
+ it('clears an expired access token when nothing can refresh it', () => {
91
+ const stored = { ...base, accessToken: 'a', expiresAt: past };
92
+ expect(planStoredSessionBoot(stored, false)).toEqual({ action: 'clear' });
93
+ });
94
+
95
+ it('keeps an expired session when auto-refresh is disabled', () => {
96
+ const stored = { ...base, accessToken: 'a', expiresAt: past };
97
+ expect(planStoredSessionBoot(stored, false, { autoRefreshDisabled: true })).toEqual({
98
+ action: 'use',
99
+ session: stored,
100
+ });
101
+ });
102
+ });
103
+
104
+ describe('isUnauthorizedRefreshError', () => {
105
+ it('matches a BFF or identity 401', () => {
106
+ expect(isUnauthorizedRefreshError(new Error('HTTP 401'))).toBe(true);
107
+ expect(isUnauthorizedRefreshError(new Error('BFF session failed (HTTP 401)'))).toBe(true);
108
+ });
109
+
110
+ it('does not treat other failures as a rejected credential', () => {
111
+ expect(isUnauthorizedRefreshError(new Error('HTTP 500'))).toBe(false);
112
+ expect(isUnauthorizedRefreshError(new Error('HTTP 4010'))).toBe(false);
113
+ expect(isUnauthorizedRefreshError('HTTP 401')).toBe(false);
114
+ });
115
+ });
116
+
117
+ describe('stale profile is removed when it cannot be restored', () => {
118
+ beforeEach(() => {
119
+ Object.defineProperty(globalThis, 'localStorage', {
120
+ configurable: true,
121
+ value: createStorageMock(),
122
+ });
123
+ Object.defineProperty(globalThis, 'sessionStorage', {
124
+ configurable: true,
125
+ value: createStorageMock(),
126
+ });
127
+ });
128
+
129
+ it('drops the shared profile after the tab-scoped refresh token is gone', () => {
130
+ persistAuthSession({ ...base, accessToken: 'access', refreshToken: 'refresh' });
131
+ sessionStorage.removeItem(AUTH_REFRESH_STORAGE_KEY);
132
+
133
+ const stored = readStoredAuthSession();
134
+ if (!stored) {
135
+ throw new Error('expected a stored profile');
136
+ }
137
+ expect(localStorage.getItem(AUTH_PROFILE_STORAGE_KEY)).not.toBeNull();
138
+ expect(planStoredSessionBoot(stored, false).action).toBe('clear');
139
+
140
+ clearStoredAuthSession();
141
+ expect(hasStoredAuthSession()).toBe(false);
142
+ expect(readStoredAuthSession()).toBeNull();
143
+ });
144
+
145
+ it('keeps the profile when BFF can try the refresh cookie, and clears it after a 401', () => {
146
+ persistAuthSession(
147
+ { ...base, accessToken: 'access', refreshToken: 'refresh' },
148
+ {
149
+ storeRefreshToken: false,
150
+ },
151
+ );
152
+ const stored = readStoredAuthSession();
153
+ if (!stored) {
154
+ throw new Error('expected a stored profile');
155
+ }
156
+ expect(planStoredSessionBoot(stored, true).action).toBe('refresh');
157
+
158
+ const failure = new Error('HTTP 401');
159
+ expect(isUnauthorizedRefreshError(failure)).toBe(true);
160
+ if (isUnauthorizedRefreshError(failure)) {
161
+ clearStoredAuthSession();
162
+ }
163
+ expect(hasStoredAuthSession()).toBe(false);
164
+ });
165
+ });
@@ -1,4 +1,5 @@
1
1
  import type { AuthSession } from '../types';
2
+ import { isSessionExpired } from './isSessionExpired';
2
3
 
3
4
  /**
4
5
  * Whether a stored session snapshot can become a signed-in session on boot.
@@ -7,6 +8,52 @@ import type { AuthSession } from '../types';
7
8
  * (sessionStorage), while the profile is shared in localStorage. A new tab
8
9
  * therefore sees the profile without any token. Without a token, or a refresh
9
10
  * token or BFF cookie to get one, the snapshot must not count as signed in.
11
+ * A false result means the profile is stale: the caller clears it and shows login.
10
12
  */
11
13
  export const canRestoreStoredSession = (stored: AuthSession, bffAuthEnabled: boolean): boolean =>
12
14
  Boolean(stored.accessToken || stored.refreshToken || bffAuthEnabled);
15
+
16
+ /** Refresh failed because the cookie or refresh token was missing or rejected. */
17
+ export const isUnauthorizedRefreshError = (error: unknown): boolean => {
18
+ const message = error instanceof Error ? error.message : '';
19
+ return /\b401\b/.test(message);
20
+ };
21
+
22
+ export type StoredSessionBootPlan =
23
+ | { action: 'clear' }
24
+ | { action: 'use'; session: AuthSession }
25
+ | { action: 'refresh'; session: AuthSession };
26
+
27
+ /**
28
+ * What boot should do with a stored profile.
29
+ *
30
+ * `clear` — nothing can restore it (no refresh token and BFF is off, or the
31
+ * access token is expired and there is still nothing to refresh with). The
32
+ * caller deletes the profile so login is a normal signed-out page.
33
+ * `refresh` — a refresh token or the BFF cookie may mint a new access token.
34
+ * `use` — the access token is still valid, or auto-refresh is disabled on purpose.
35
+ */
36
+ export const planStoredSessionBoot = (
37
+ stored: AuthSession,
38
+ bffAuthEnabled: boolean,
39
+ options?: { autoRefreshDisabled?: boolean },
40
+ ): StoredSessionBootPlan => {
41
+ if (!canRestoreStoredSession(stored, bffAuthEnabled)) {
42
+ return { action: 'clear' };
43
+ }
44
+
45
+ const needsToken = !stored.accessToken || isSessionExpired(stored);
46
+ if (!needsToken) {
47
+ return { action: 'use', session: stored };
48
+ }
49
+
50
+ if (options?.autoRefreshDisabled) {
51
+ return { action: 'use', session: stored };
52
+ }
53
+
54
+ if (stored.refreshToken || bffAuthEnabled) {
55
+ return { action: 'refresh', session: stored };
56
+ }
57
+
58
+ return { action: 'clear' };
59
+ };
@@ -35,6 +35,11 @@ export function captureCliCallbackFromSearch(search: string): void {
35
35
  }
36
36
  }
37
37
 
38
+ /** True when `shellui login` is waiting for tokens on a loopback URL. */
39
+ export function hasPendingCliCallback(): boolean {
40
+ return readStoredCliCallback() !== null;
41
+ }
42
+
38
43
  function readStoredCliCallback(): string | null {
39
44
  if (typeof sessionStorage === 'undefined') return null;
40
45
  try {