@shellui/core 0.5.0 → 0.5.1

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 (51) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +98 -33
  3. package/src/app.tsx +2 -0
  4. package/src/components/ContentView.tsx +3 -5
  5. package/src/components/contentIframeSandbox.spec.ts +25 -0
  6. package/src/components/contentIframeSandbox.ts +43 -0
  7. package/src/features/auth/AuthProvider.tsx +156 -33
  8. package/src/features/auth/backends/index.ts +2 -0
  9. package/src/features/auth/backends/shellui.ts +43 -35
  10. package/src/features/auth/backends/supabase.ts +1 -0
  11. package/src/features/auth/backends/types.ts +5 -0
  12. package/src/features/auth/components/LoginView.tsx +5 -1
  13. package/src/features/auth/components/OAuthCallbackView.tsx +115 -44
  14. package/src/features/auth/constants/oauth.ts +2 -0
  15. package/src/features/auth/hooks/useAuth.tsx +4 -0
  16. package/src/features/auth/utils/authSessionPersistence.spec.ts +93 -0
  17. package/src/features/auth/utils/authSessionPersistence.ts +138 -0
  18. package/src/features/auth/utils/authStorageKeys.ts +8 -0
  19. package/src/features/auth/utils/bffAuthClient.ts +107 -0
  20. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +22 -0
  21. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +17 -0
  22. package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +29 -0
  23. package/src/features/auth/utils/buildSessionFromTokenPayload.ts +24 -0
  24. package/src/features/auth/utils/index.ts +18 -3
  25. package/src/features/auth/utils/isBffAuthEnabled.ts +12 -0
  26. package/src/features/config/types.ts +49 -2
  27. package/src/features/messaging/MessagingSecurityBootstrap.tsx +19 -0
  28. package/src/features/messaging/deriveAllowedMessageOrigins.spec.ts +86 -0
  29. package/src/features/messaging/deriveAllowedMessageOrigins.ts +74 -0
  30. package/src/features/modal/ModalContext.spec.ts +13 -2
  31. package/src/features/modal/validateAndNormalizeUrl.ts +9 -23
  32. package/src/features/security/trustedFrames.spec.ts +129 -0
  33. package/src/features/security/trustedFrames.ts +79 -0
  34. package/src/features/security/urlAllowlist.spec.ts +99 -0
  35. package/src/features/security/urlAllowlist.ts +122 -0
  36. package/src/features/settings/SettingsProvider.tsx +10 -46
  37. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +23 -1
  38. package/src/features/settings/utils/buildSettingsForPropagation.ts +7 -0
  39. package/src/features/storage/StorageBridge.spec.ts +82 -0
  40. package/src/features/storage/StorageBridge.tsx +25 -3
  41. package/src/features/storage/StoragePickerContext.tsx +3 -4
  42. package/src/features/storage/uploads/uploadQueue.ts +2 -5
  43. package/src/routes/components/NavigationItemRoute.tsx +30 -15
  44. package/src/routes/utils/navigationRouteAccess.spec.ts +85 -0
  45. package/src/routes/utils/navigationRouteAccess.ts +43 -0
  46. package/src/features/auth/utils/clearStoredAuthSession.spec.ts +0 -23
  47. package/src/features/auth/utils/clearStoredAuthSession.ts +0 -10
  48. package/src/features/auth/utils/persistAuthSession.spec.ts +0 -35
  49. package/src/features/auth/utils/persistAuthSession.ts +0 -12
  50. package/src/features/auth/utils/readStoredAuthSession.spec.ts +0 -34
  51. package/src/features/auth/utils/readStoredAuthSession.ts +0 -14
@@ -1,8 +1,10 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react';
2
2
  import { useLocation, useNavigate } from 'react-router';
3
3
  import urls from '../../../constants/urls';
4
+ import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
4
5
  import {
5
6
  buildAuthUrlWithNext,
7
+ buildOAuthSessionRedirectTo,
6
8
  captureCliCallbackFromSearch,
7
9
  hashHasOAuthTokens,
8
10
  inferAccessPendingErrorCode,
@@ -71,6 +73,7 @@ const looksLikeUsedOAuthCode = (message: string | null | undefined) => {
71
73
  const text = (message || '').toLowerCase();
72
74
  return (
73
75
  text.includes('bad_verification_code') ||
76
+ text.includes('auth_code') ||
74
77
  text.includes('code has already been used') ||
75
78
  text.includes('authorization code was already redeemed') ||
76
79
  text.includes('invalid_grant') ||
@@ -82,12 +85,20 @@ const looksLikeUsedOAuthCode = (message: string | null | undefined) => {
82
85
  export const OAuthCallbackView = () => {
83
86
  const location = useLocation();
84
87
  const navigate = useNavigate();
85
- const { completeOAuthCallback, isAuthenticated, isLoading, session } = useAuth();
88
+ const {
89
+ completeOAuthCallback,
90
+ completeOAuthSessionCallback,
91
+ isAuthenticated,
92
+ isLoading,
93
+ session,
94
+ } = useAuth();
86
95
  const [localError, setLocalError] = useState<string | null>(null);
87
96
  const [pendingAccess, setPendingAccess] = useState<PendingAccess | null>(null);
88
97
  const [isWorking, setIsWorking] = useState(true);
89
98
  /** OAuth `code` we already started exchanging (avoid double-spend / Strict Mode races). */
90
99
  const startedCodeRef = useRef<string | null>(null);
100
+ /** Session auth code we already started exchanging (identity 0.5.0 default delivery). */
101
+ const startedAuthCodeRef = useRef<string | null>(null);
91
102
  const nextPath = useMemo(() => {
92
103
  const params = new URLSearchParams(location.search);
93
104
  return normalizeNextPath(params.get('next')) ?? '/';
@@ -137,8 +148,105 @@ export const OAuthCallbackView = () => {
137
148
  return;
138
149
  }
139
150
 
151
+ const authCode = params.get(SHELLUI_AUTH_CODE_PARAM);
140
152
  const code = params.get('code');
141
153
  const provider = params.get('provider');
154
+
155
+ const applyExchangeFailure = (
156
+ exchangeKey: string,
157
+ result: { ok: boolean; error?: string | null; errorCode?: string | null },
158
+ cancelled: boolean,
159
+ ) => {
160
+ const pendingCode =
161
+ (isAccessPendingErrorCode(result.errorCode) ? result.errorCode : null) ??
162
+ inferAccessPendingErrorCode(result.error);
163
+
164
+ if (pendingCode) {
165
+ const pending: PendingAccess = {
166
+ message:
167
+ (result.error && result.error.trim()) ||
168
+ 'Your account was created and is waiting for an administrator to grant access.',
169
+ code: pendingCode,
170
+ };
171
+ writePendingForCode(exchangeKey, pending);
172
+ if (redirectCliCallbackError(pending.message, pending.code)) return;
173
+ setPendingAccess(pending);
174
+ setIsWorking(false);
175
+ if (!cancelled) {
176
+ navigate(buildLoginPendingUrl(nextPath, pending), { replace: true });
177
+ }
178
+ return;
179
+ }
180
+
181
+ const recovered = readPendingForCode(exchangeKey);
182
+ if (recovered && looksLikeUsedOAuthCode(result.error)) {
183
+ if (redirectCliCallbackError(recovered.message, recovered.code)) return;
184
+ setPendingAccess(recovered);
185
+ setIsWorking(false);
186
+ if (!cancelled) {
187
+ navigate(buildLoginPendingUrl(nextPath, recovered), { replace: true });
188
+ }
189
+ return;
190
+ }
191
+
192
+ const message = result.error ?? 'Unable to complete OAuth login.';
193
+ if (redirectCliCallbackError(message, result.errorCode)) return;
194
+ setLocalError(message);
195
+ setIsWorking(false);
196
+ };
197
+
198
+ if (authCode) {
199
+ const cachedPending = readPendingForCode(authCode);
200
+ if (cachedPending) {
201
+ if (redirectCliCallbackError(cachedPending.message, cachedPending.code)) return;
202
+ setPendingAccess(cachedPending);
203
+ setIsWorking(false);
204
+ navigate(buildLoginPendingUrl(nextPath, cachedPending), { replace: true });
205
+ return;
206
+ }
207
+
208
+ if (startedAuthCodeRef.current === authCode) {
209
+ return;
210
+ }
211
+ startedAuthCodeRef.current = authCode;
212
+
213
+ let cancelled = false;
214
+ const runSessionExchange = async () => {
215
+ const redirectTo = buildOAuthSessionRedirectTo(
216
+ window.location.origin,
217
+ location.pathname,
218
+ location.search,
219
+ );
220
+ let result: { ok: boolean; error?: string | null; errorCode?: string | null };
221
+ try {
222
+ result = await completeOAuthSessionCallback({ authCode, redirectTo });
223
+ } catch (err) {
224
+ result = {
225
+ ok: false,
226
+ error: err instanceof Error ? err.message : 'Unable to complete OAuth login.',
227
+ errorCode: null,
228
+ };
229
+ }
230
+
231
+ if (!result.ok) {
232
+ applyExchangeFailure(authCode, result, cancelled);
233
+ return;
234
+ }
235
+
236
+ clearPendingForCode(authCode);
237
+ if (typeof window !== 'undefined' && window.history?.replaceState) {
238
+ const cleaned = new URL(window.location.href);
239
+ cleaned.searchParams.delete(SHELLUI_AUTH_CODE_PARAM);
240
+ window.history.replaceState({}, document.title, cleaned.pathname + cleaned.search);
241
+ }
242
+ };
243
+
244
+ void runSessionExchange();
245
+ return () => {
246
+ cancelled = true;
247
+ };
248
+ }
249
+
142
250
  if (!code || !provider) {
143
251
  const message = 'Missing OAuth callback parameters.';
144
252
  if (redirectCliCallbackError(message)) return;
@@ -147,7 +255,6 @@ export const OAuthCallbackView = () => {
147
255
  return;
148
256
  }
149
257
 
150
- // If a previous attempt already learned this login is pending, show it without re-exchanging.
151
258
  const cachedPending = readPendingForCode(code);
152
259
  if (cachedPending) {
153
260
  if (redirectCliCallbackError(cachedPending.message, cachedPending.code)) return;
@@ -163,7 +270,7 @@ export const OAuthCallbackView = () => {
163
270
  startedCodeRef.current = code;
164
271
 
165
272
  let cancelled = false;
166
- const run = async () => {
273
+ const runLegacyExchange = async () => {
167
274
  const redirectUri = `${window.location.origin}${location.pathname}${location.search}`;
168
275
  let result: { ok: boolean; error?: string | null; errorCode?: string | null };
169
276
  try {
@@ -181,59 +288,21 @@ export const OAuthCallbackView = () => {
181
288
  };
182
289
  }
183
290
 
184
- // Always apply UI state — do not drop failures when the effect cleans up
185
- // (Strict Mode / callback identity changes), or the page stays on "Completing…".
186
291
  if (!result.ok) {
187
- const pendingCode =
188
- (isAccessPendingErrorCode(result.errorCode) ? result.errorCode : null) ??
189
- inferAccessPendingErrorCode(result.error);
190
-
191
- if (pendingCode) {
192
- const pending: PendingAccess = {
193
- message:
194
- (result.error && result.error.trim()) ||
195
- 'Your account was created and is waiting for an administrator to grant access.',
196
- code: pendingCode,
197
- };
198
- writePendingForCode(code, pending);
199
- if (redirectCliCallbackError(pending.message, pending.code)) return;
200
- setPendingAccess(pending);
201
- setIsWorking(false);
202
- if (!cancelled) {
203
- navigate(buildLoginPendingUrl(nextPath, pending), { replace: true });
204
- }
205
- return;
206
- }
207
-
208
- // Code was likely consumed by a cancelled first attempt that already marked pending.
209
- const recovered = readPendingForCode(code);
210
- if (recovered && looksLikeUsedOAuthCode(result.error)) {
211
- if (redirectCliCallbackError(recovered.message, recovered.code)) return;
212
- setPendingAccess(recovered);
213
- setIsWorking(false);
214
- if (!cancelled) {
215
- navigate(buildLoginPendingUrl(nextPath, recovered), { replace: true });
216
- }
217
- return;
218
- }
219
-
220
- const message = result.error ?? 'Unable to complete OAuth login.';
221
- if (redirectCliCallbackError(message, result.errorCode)) return;
222
- setLocalError(message);
223
- setIsWorking(false);
292
+ applyExchangeFailure(code, result, cancelled);
224
293
  return;
225
294
  }
226
295
 
227
296
  clearPendingForCode(code);
228
- // Session is set in AuthProvider; the authenticated effect handles CLI bounce / next.
229
297
  };
230
298
 
231
- void run();
299
+ void runLegacyExchange();
232
300
  return () => {
233
301
  cancelled = true;
234
302
  };
235
303
  }, [
236
304
  completeOAuthCallback,
305
+ completeOAuthSessionCallback,
237
306
  fragmentHasTokens,
238
307
  isAuthenticated,
239
308
  isLoading,
@@ -246,7 +315,9 @@ export const OAuthCallbackView = () => {
246
315
  const backToLogin = () => {
247
316
  const params = new URLSearchParams(location.search);
248
317
  const code = params.get('code');
318
+ const authCode = params.get(SHELLUI_AUTH_CODE_PARAM);
249
319
  if (code) clearPendingForCode(code);
320
+ if (authCode) clearPendingForCode(authCode);
250
321
  navigate(buildAuthUrlWithNext(urls.login, nextPath), { replace: true });
251
322
  };
252
323
 
@@ -0,0 +1,2 @@
1
+ /** One-time OAuth session code query param (identity-service 0.5.0+ default delivery). */
2
+ export const SHELLUI_AUTH_CODE_PARAM = 'shellui_auth_code';
@@ -18,6 +18,10 @@ export interface AuthContextValue {
18
18
  errorCode: string | null;
19
19
  authEvent: AuthEvent;
20
20
  clearAuthEvent: () => void;
21
+ completeOAuthSessionCallback: (params: {
22
+ authCode: string;
23
+ redirectTo: string;
24
+ }) => Promise<OAuthCallbackResult>;
21
25
  completeOAuthCallback: (params: {
22
26
  provider: string;
23
27
  code: string;
@@ -0,0 +1,93 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import type { AuthSession } from '../types';
3
+ import {
4
+ AUTH_PROFILE_STORAGE_KEY,
5
+ AUTH_REFRESH_STORAGE_KEY,
6
+ LEGACY_AUTH_SESSION_STORAGE_KEY,
7
+ } from './authStorageKeys';
8
+ import {
9
+ clearStoredAuthSession,
10
+ persistAuthSession,
11
+ readStoredAuthSession,
12
+ } from './authSessionPersistence';
13
+
14
+ const createStorageMock = () => {
15
+ const data = new Map<string, string>();
16
+ return {
17
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
18
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
19
+ removeItem: vi.fn((key: string) => data.delete(key)),
20
+ clear: vi.fn(() => data.clear()),
21
+ key: vi.fn(() => null),
22
+ get length() {
23
+ return data.size;
24
+ },
25
+ } as unknown as Storage;
26
+ };
27
+
28
+ const sampleSession = (): AuthSession => ({
29
+ accessToken: 'access-abc',
30
+ refreshToken: 'refresh-xyz',
31
+ tokenType: 'bearer',
32
+ expiresAt: 4_102_444_800,
33
+ provider: 'github',
34
+ userId: 'user-1',
35
+ userEmail: 'a@example.com',
36
+ userName: 'Ada',
37
+ userAvatarUrl: null,
38
+ userIsStaff: false,
39
+ userIsCompanyOwner: false,
40
+ userGroups: [],
41
+ });
42
+
43
+ describe('authSessionPersistence', () => {
44
+ beforeEach(() => {
45
+ Object.defineProperty(globalThis, 'localStorage', {
46
+ configurable: true,
47
+ value: createStorageMock(),
48
+ });
49
+ Object.defineProperty(globalThis, 'sessionStorage', {
50
+ configurable: true,
51
+ value: createStorageMock(),
52
+ });
53
+ });
54
+
55
+ it('stores profile in localStorage and refresh in sessionStorage', () => {
56
+ persistAuthSession(sampleSession());
57
+ expect(localStorage.setItem).toHaveBeenCalledWith(
58
+ AUTH_PROFILE_STORAGE_KEY,
59
+ expect.not.stringContaining('access-abc'),
60
+ );
61
+ expect(sessionStorage.setItem).toHaveBeenCalledWith(AUTH_REFRESH_STORAGE_KEY, 'refresh-xyz');
62
+ expect(localStorage.removeItem).toHaveBeenCalledWith(LEGACY_AUTH_SESSION_STORAGE_KEY);
63
+ });
64
+
65
+ it('omits refresh from sessionStorage when storeRefreshToken is false (BFF)', () => {
66
+ persistAuthSession(sampleSession(), { storeRefreshToken: false });
67
+ expect(sessionStorage.setItem).not.toHaveBeenCalled();
68
+ expect(sessionStorage.removeItem).toHaveBeenCalledWith(AUTH_REFRESH_STORAGE_KEY);
69
+ });
70
+
71
+ it('rehydrates session with empty access token until refresh', () => {
72
+ persistAuthSession(sampleSession());
73
+ const restored = readStoredAuthSession();
74
+ expect(restored?.refreshToken).toBe('refresh-xyz');
75
+ expect(restored?.accessToken).toBe('');
76
+ expect(restored?.userId).toBe('user-1');
77
+ });
78
+
79
+ it('migrates legacy monolithic localStorage session', () => {
80
+ const legacy = sampleSession();
81
+ vi.mocked(localStorage.getItem).mockReturnValueOnce(JSON.stringify(legacy));
82
+ const restored = readStoredAuthSession();
83
+ expect(restored?.accessToken).toBe('access-abc');
84
+ expect(localStorage.setItem).toHaveBeenCalledWith(AUTH_PROFILE_STORAGE_KEY, expect.any(String));
85
+ });
86
+
87
+ it('clears profile, refresh, and legacy keys', () => {
88
+ clearStoredAuthSession();
89
+ expect(localStorage.removeItem).toHaveBeenCalledWith(AUTH_PROFILE_STORAGE_KEY);
90
+ expect(sessionStorage.removeItem).toHaveBeenCalledWith(AUTH_REFRESH_STORAGE_KEY);
91
+ expect(localStorage.removeItem).toHaveBeenCalledWith(LEGACY_AUTH_SESSION_STORAGE_KEY);
92
+ });
93
+ });
@@ -0,0 +1,138 @@
1
+ import type { AuthSession } from '../types';
2
+ import {
3
+ AUTH_PROFILE_STORAGE_KEY,
4
+ AUTH_REFRESH_STORAGE_KEY,
5
+ LEGACY_AUTH_SESSION_STORAGE_KEY,
6
+ } from './authStorageKeys';
7
+
8
+ /** Fields stored in localStorage for reload UX (no secrets). */
9
+ export type PersistedAuthProfile = Omit<
10
+ AuthSession,
11
+ 'accessToken' | 'refreshToken' | 'tokenType'
12
+ > & {
13
+ tokenType?: string;
14
+ };
15
+
16
+ const profileFromSession = (session: AuthSession): PersistedAuthProfile => {
17
+ const { accessToken: _a, refreshToken: _r, ...profile } = session;
18
+ return profile;
19
+ };
20
+
21
+ const readRefreshFromSessionStorage = (): string | null => {
22
+ try {
23
+ return sessionStorage.getItem(AUTH_REFRESH_STORAGE_KEY);
24
+ } catch {
25
+ return null;
26
+ }
27
+ };
28
+
29
+ const writeRefreshToSessionStorage = (refreshToken: string | null | undefined) => {
30
+ try {
31
+ if (refreshToken) {
32
+ sessionStorage.setItem(AUTH_REFRESH_STORAGE_KEY, refreshToken);
33
+ } else {
34
+ sessionStorage.removeItem(AUTH_REFRESH_STORAGE_KEY);
35
+ }
36
+ } catch {
37
+ // Ignore quota / private mode.
38
+ }
39
+ };
40
+
41
+ const readLegacyMonolithicSession = (): AuthSession | null => {
42
+ try {
43
+ const raw = localStorage.getItem(LEGACY_AUTH_SESSION_STORAGE_KEY);
44
+ if (!raw) return null;
45
+ return JSON.parse(raw) as AuthSession;
46
+ } catch {
47
+ return null;
48
+ }
49
+ };
50
+
51
+ const clearLegacyMonolithicSession = () => {
52
+ try {
53
+ localStorage.removeItem(LEGACY_AUTH_SESSION_STORAGE_KEY);
54
+ } catch {
55
+ // Ignore.
56
+ }
57
+ };
58
+
59
+ const readProfile = (): PersistedAuthProfile | null => {
60
+ try {
61
+ const raw = localStorage.getItem(AUTH_PROFILE_STORAGE_KEY);
62
+ if (!raw) return null;
63
+ return JSON.parse(raw) as PersistedAuthProfile;
64
+ } catch {
65
+ return null;
66
+ }
67
+ };
68
+
69
+ const writeProfile = (profile: PersistedAuthProfile | null) => {
70
+ try {
71
+ if (profile) {
72
+ localStorage.setItem(AUTH_PROFILE_STORAGE_KEY, JSON.stringify(profile));
73
+ } else {
74
+ localStorage.removeItem(AUTH_PROFILE_STORAGE_KEY);
75
+ }
76
+ } catch {
77
+ // Ignore.
78
+ }
79
+ };
80
+
81
+ const mergeProfileAndTokens = (
82
+ profile: PersistedAuthProfile,
83
+ accessToken: string,
84
+ refreshToken: string,
85
+ ): AuthSession => ({
86
+ ...profile,
87
+ accessToken,
88
+ refreshToken,
89
+ tokenType: profile.tokenType ?? 'bearer',
90
+ });
91
+
92
+ /**
93
+ * Persist auth state with minimized blast radius:
94
+ * - Profile metadata in localStorage (no tokens)
95
+ * - Refresh token in sessionStorage (tab-scoped; omitted when `storeRefreshToken` is false for BFF)
96
+ * - Access token is never written to web storage (memory only)
97
+ */
98
+ export const persistAuthSession = (
99
+ session: AuthSession,
100
+ options?: { storeRefreshToken?: boolean },
101
+ ) => {
102
+ const storeRefresh = options?.storeRefreshToken !== false;
103
+ writeProfile(profileFromSession(session));
104
+ if (storeRefresh) {
105
+ writeRefreshToSessionStorage(session.refreshToken);
106
+ } else {
107
+ writeRefreshToSessionStorage(null);
108
+ }
109
+ clearLegacyMonolithicSession();
110
+ };
111
+
112
+ /** Read rehydratable session snapshot (access token empty until refresh). */
113
+ export const readStoredAuthSession = (): AuthSession | null => {
114
+ const legacy = readLegacyMonolithicSession();
115
+ if (legacy) {
116
+ persistAuthSession(legacy);
117
+ return legacy;
118
+ }
119
+
120
+ const profile = readProfile();
121
+ if (!profile) return null;
122
+
123
+ const refreshToken = readRefreshFromSessionStorage() ?? '';
124
+ return mergeProfileAndTokens(profile, '', refreshToken);
125
+ };
126
+
127
+ /** Remove all persisted auth keys (profile, refresh, legacy). */
128
+ export const clearStoredAuthSession = () => {
129
+ writeProfile(null);
130
+ writeRefreshToSessionStorage(null);
131
+ clearLegacyMonolithicSession();
132
+ };
133
+
134
+ /** Update profile metadata without touching refresh storage. */
135
+ export const persistAuthProfile = (session: AuthSession) => {
136
+ writeProfile(profileFromSession(session));
137
+ clearLegacyMonolithicSession();
138
+ };
@@ -0,0 +1,8 @@
1
+ /** Profile metadata persisted across reloads (no tokens). */
2
+ export const AUTH_PROFILE_STORAGE_KEY = 'shellui.auth.profile';
3
+
4
+ /** Tab-scoped refresh token when BFF is disabled (still JS-readable; prefer BFF). */
5
+ export const AUTH_REFRESH_STORAGE_KEY = 'shellui.auth.refresh';
6
+
7
+ /** Legacy monolithic session blob — migrated on read, then removed. */
8
+ export const LEGACY_AUTH_SESSION_STORAGE_KEY = 'shellui.auth.session';
@@ -0,0 +1,107 @@
1
+ import type { AuthSession } from '../types';
2
+ import { buildSessionFromParams } from './buildSessionFromParams';
3
+
4
+ const BFF_SESSION_PATH = '/api/auth/session';
5
+ const BFF_REFRESH_PATH = '/api/auth/refresh';
6
+ const BFF_LOGOUT_PATH = '/api/auth/logout';
7
+
8
+ type BffTokenResponse = {
9
+ access_token?: string;
10
+ refresh_token?: string;
11
+ expires_at?: number | string;
12
+ expires_in?: number | string;
13
+ token_type?: string;
14
+ };
15
+
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);
24
+ }
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));
35
+ }
36
+ if (typeof payload.token_type === 'string') {
37
+ params.set('token_type', payload.token_type);
38
+ }
39
+ const built = buildSessionFromParams(params, nowSeconds);
40
+ if (!built) return null;
41
+ return {
42
+ ...built,
43
+ provider: built.provider ?? current.provider,
44
+ userPreferences: current.userPreferences ?? built.userPreferences,
45
+ };
46
+ };
47
+
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> => {
53
+ const response = await fetch(BFF_SESSION_PATH, {
54
+ method: 'POST',
55
+ credentials: 'include',
56
+ headers: {
57
+ Accept: 'application/json',
58
+ 'Content-Type': 'application/json',
59
+ },
60
+ body: JSON.stringify({
61
+ refresh_token: session.refreshToken,
62
+ access_token: session.accessToken,
63
+ expires_at: session.expiresAt,
64
+ token_type: session.tokenType,
65
+ }),
66
+ });
67
+ if (!response.ok) {
68
+ throw new Error(`BFF session failed (HTTP ${response.status})`);
69
+ }
70
+ const payload = (await response.json()) as BffTokenResponse;
71
+ const next = parseBffTokenResponse(payload, session, nowSeconds);
72
+ if (!next) return null;
73
+ return { ...next, refreshToken: '' };
74
+ };
75
+
76
+ /** Refresh access token via same-origin BFF (HttpOnly refresh cookie). */
77
+ export const refreshBffAuthSession = async (
78
+ current: AuthSession,
79
+ nowSeconds: number,
80
+ ): Promise<AuthSession | null> => {
81
+ const response = await fetch(BFF_REFRESH_PATH, {
82
+ method: 'POST',
83
+ credentials: 'include',
84
+ headers: { Accept: 'application/json' },
85
+ });
86
+ if (!response.ok) {
87
+ throw new Error(`HTTP ${response.status}`);
88
+ }
89
+ const payload = (await response.json()) as BffTokenResponse;
90
+ const next = parseBffTokenResponse(payload, current, nowSeconds);
91
+ if (!next) return null;
92
+ return { ...next, refreshToken: '' };
93
+ };
94
+
95
+ /** Clear BFF HttpOnly cookie and optionally notify identity logout. */
96
+ export const logoutBffAuthSession = async (accessToken: string | null | undefined) => {
97
+ await fetch(BFF_LOGOUT_PATH, {
98
+ method: 'POST',
99
+ credentials: 'include',
100
+ headers: {
101
+ Accept: 'application/json',
102
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
103
+ },
104
+ }).catch(() => {
105
+ // Best-effort; local session is cleared regardless.
106
+ });
107
+ };
@@ -0,0 +1,22 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
3
+ import { buildOAuthSessionRedirectTo } from './buildOAuthSessionRedirectTo';
4
+
5
+ describe('buildOAuthSessionRedirectTo', () => {
6
+ test('strips shellui_auth_code and keeps other query params', () => {
7
+ const search = `?provider=github&next=%2F&${SHELLUI_AUTH_CODE_PARAM}=abc123`;
8
+ expect(buildOAuthSessionRedirectTo('http://localhost:4000', '/login/callback', search)).toBe(
9
+ 'http://localhost:4000/login/callback?provider=github&next=%2F',
10
+ );
11
+ });
12
+
13
+ test('returns pathname-only URL when only auth code was present', () => {
14
+ expect(
15
+ buildOAuthSessionRedirectTo(
16
+ 'http://127.0.0.1:8765',
17
+ '/callback',
18
+ `?${SHELLUI_AUTH_CODE_PARAM}=one-time`,
19
+ ),
20
+ ).toBe('http://127.0.0.1:8765/callback');
21
+ });
22
+ });
@@ -0,0 +1,17 @@
1
+ import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
2
+
3
+ /**
4
+ * Reconstruct the `redirect_to` URL for `POST /api/v1/oauth/session`.
5
+ * Strips the one-time auth code while preserving other callback query params.
6
+ */
7
+ export function buildOAuthSessionRedirectTo(
8
+ origin: string,
9
+ pathname: string,
10
+ search: string,
11
+ ): string {
12
+ const url = new URL(`${origin}${pathname}`);
13
+ const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);
14
+ params.delete(SHELLUI_AUTH_CODE_PARAM);
15
+ url.search = params.toString();
16
+ return url.toString();
17
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { buildSessionFromTokenPayload } from './buildSessionFromTokenPayload';
3
+
4
+ describe('buildSessionFromTokenPayload', () => {
5
+ test('maps token JSON to AuthSession', () => {
6
+ const now = 1_700_000_000;
7
+ const session = buildSessionFromTokenPayload(
8
+ {
9
+ access_token:
10
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1MSIsImVtYWlsIjoidUBleC5jb20ifQ.sig',
11
+ refresh_token: 'refresh-1',
12
+ expires_at: now + 300,
13
+ token_type: 'bearer',
14
+ },
15
+ now,
16
+ );
17
+ expect(session?.accessToken).toBe(
18
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1MSIsImVtYWlsIjoidUBleC5jb20ifQ.sig',
19
+ );
20
+ expect(session?.refreshToken).toBe('refresh-1');
21
+ expect(session?.expiresAt).toBe(now + 300);
22
+ expect(session?.userId).toBe('u1');
23
+ expect(session?.userEmail).toBe('u@ex.com');
24
+ });
25
+
26
+ test('returns null when tokens are missing', () => {
27
+ expect(buildSessionFromTokenPayload({ access_token: 'only-access' }, 0)).toBeNull();
28
+ });
29
+ });