@shellui/core 0.7.0-alpha.1 → 0.7.0-alpha.10

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 (69) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +37 -4
  3. package/src/components/ContentView.tsx +19 -8
  4. package/src/components/ui/sidebar.tsx +11 -5
  5. package/src/features/admin/AdminView.tsx +9 -6
  6. package/src/features/auth/AuthProvider.tsx +25 -4
  7. package/src/features/auth/appBackend/appBackendSessions.spec.ts +134 -0
  8. package/src/features/auth/appBackend/appBackendSessions.ts +168 -17
  9. package/src/features/auth/appBackend/childFrames.spec.ts +328 -0
  10. package/src/features/auth/appBackend/childFrames.ts +180 -0
  11. package/src/features/auth/appBackend/frameAuth.ts +47 -10
  12. package/src/features/auth/appBackend/silentSignIn.spec.ts +18 -0
  13. package/src/features/auth/appBackend/silentSignIn.ts +15 -1
  14. package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
  15. package/src/features/auth/appBackend/tokenExchange.ts +76 -0
  16. package/src/features/auth/components/OAuthCallbackView.tsx +7 -5
  17. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
  18. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
  19. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +29 -0
  20. package/src/features/auth/utils/canRestoreStoredSession.ts +12 -0
  21. package/src/features/auth/utils/index.ts +7 -1
  22. package/src/features/auth/utils/resolveSdkLoginRedirectPath.spec.ts +41 -0
  23. package/src/features/auth/utils/resolveSdkLoginRedirectPath.ts +31 -0
  24. package/src/features/auth/utils/webPkce.spec.ts +23 -0
  25. package/src/features/auth/utils/webPkce.ts +23 -6
  26. package/src/features/chromeActions/computeActionInsets.ts +7 -4
  27. package/src/features/config/types.ts +30 -4
  28. package/src/features/layouts/appbar/AppBarLayout.tsx +63 -30
  29. package/src/features/layouts/chrome/CollapsedDesktopTitlebar.tsx +12 -23
  30. package/src/features/layouts/chrome/ContentDragOverlay.tsx +5 -6
  31. package/src/features/layouts/chrome/DesktopChrome.tsx +37 -0
  32. package/src/features/layouts/chrome/DesktopHistoryButtons.tsx +15 -4
  33. package/src/features/layouts/chrome/MacStrip.tsx +33 -0
  34. package/src/features/layouts/chrome/constants.ts +33 -8
  35. package/src/features/layouts/chrome/index.ts +8 -0
  36. package/src/features/layouts/chrome/stripDragMap.ts +35 -0
  37. package/src/features/layouts/chrome/stripNoDrag.spec.tsx +103 -0
  38. package/src/features/layouts/chrome/useScrollHideChrome.ts +3 -8
  39. package/src/features/layouts/filterNavigationForAuthState.spec.ts +5 -3
  40. package/src/features/layouts/floating/FloatingBottomDock.tsx +199 -20
  41. package/src/features/layouts/floating/FloatingLayout.tsx +13 -8
  42. package/src/features/layouts/floating/FloatingSidebar.tsx +144 -70
  43. package/src/features/layouts/floating/computeFloatingInsets.ts +22 -4
  44. package/src/features/layouts/floating/useFloatingChrome.ts +3 -1
  45. package/src/features/layouts/floating/useSoftKeyboard.spec.ts +39 -0
  46. package/src/features/layouts/floating/useSoftKeyboard.ts +82 -0
  47. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +38 -10
  48. package/src/features/layouts/sidebar/NavigationContent.tsx +14 -6
  49. package/src/features/layouts/sidebar/SidebarIcons.tsx +3 -9
  50. package/src/features/layouts/sidebar/SidebarInner.tsx +50 -39
  51. package/src/features/layouts/sidebar/SidebarLayout.tsx +8 -11
  52. package/src/features/layouts/utils.ts +4 -3
  53. package/src/features/layouts/windows/DesktopDots.tsx +76 -0
  54. package/src/features/layouts/windows/WindowsLayout.tsx +184 -125
  55. package/src/features/layouts/windows/deskDots.spec.ts +52 -0
  56. package/src/features/layouts/windows/deskDots.ts +314 -0
  57. package/src/features/settings/SettingsProvider.tsx +158 -2
  58. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +8 -7
  59. package/src/features/settings/utils/buildSettingsForPropagation.ts +4 -6
  60. package/src/features/theme/applyTheme.ts +8 -0
  61. package/src/features/theme/navContrast.spec.ts +49 -0
  62. package/src/features/theme/navContrast.ts +108 -0
  63. package/src/features/transfers/transferQueue.spec.ts +6 -2
  64. package/src/i18n/translations/en/common.json +25 -0
  65. package/src/i18n/translations/fr/common.json +25 -0
  66. package/src/index.css +935 -46
  67. package/src/index.ts +1 -0
  68. package/src/routes/hooks/useNavigationItems.ts +14 -3
  69. package/src/routes/hooks/withShellSearch.spec.ts +13 -0
@@ -0,0 +1,180 @@
1
+ import type { ShellUIConfig } from '../../config/types';
2
+ import {
3
+ resolveAppBackendConfig,
4
+ resolveFrameNavigationItem,
5
+ type ResolvedAppBackend,
6
+ } from './identity';
7
+
8
+ /** A child app hosted by an embedded app, as accepted by the shell. */
9
+ export type ChildFrameEntry = {
10
+ hostUuid: string;
11
+ frameId: string;
12
+ url: string;
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[];
18
+ };
19
+
20
+ export type ChildFrameServiceKey = 'email' | 'storage' | 'files' | 'hosting';
21
+ export type ChildFrameServices = Record<ChildFrameServiceKey, string | null>;
22
+ const SERVICE_KEYS: readonly ChildFrameServiceKey[] = ['email', 'storage', 'files', 'hosting'];
23
+
24
+ export type ChildFrameRegistration =
25
+ | { ok: true; entry: ChildFrameEntry }
26
+ | { ok: false; reason: string };
27
+
28
+ const entries = new Map<string, ChildFrameEntry>();
29
+
30
+ function entryKey(hostUuid: string, frameId: string): string {
31
+ return `${hostUuid}\n${frameId}`;
32
+ }
33
+
34
+ function exactOrigin(value: unknown): string | null {
35
+ if (typeof value !== 'string') return null;
36
+ try {
37
+ const url = new URL(value);
38
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
39
+ return url.origin;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ function originList(values: unknown): Set<string> {
46
+ const out = new Set<string>();
47
+ if (!Array.isArray(values)) return out;
48
+ for (const value of values) {
49
+ // Only exact origins count. A path, wildcard or `*` never matches.
50
+ const origin = exactOrigin(value);
51
+ if (origin && origin === `${value}`.trim().replace(/\/$/, '')) out.add(origin);
52
+ }
53
+ return out;
54
+ }
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, files: 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
+
82
+ /**
83
+ * Check a `SHELLUI_CHILD_FRAME_REGISTER` message. `from` must be exactly one hop:
84
+ * a child app cannot register frames by sending the message through its host.
85
+ */
86
+ export function validateChildFrameRegistration(input: {
87
+ from: readonly string[] | undefined;
88
+ hostSrc: string | null | undefined;
89
+ payload: unknown;
90
+ config?: ShellUIConfig;
91
+ }): ChildFrameRegistration {
92
+ const from = (input.from ?? []).filter(Boolean);
93
+ if (from.length !== 1) return { ok: false, reason: 'not sent by a direct app frame' };
94
+ if (!input.hostSrc) return { ok: false, reason: 'unknown host frame' };
95
+ const payload = input.payload as
96
+ | { frameId?: unknown; url?: unknown; backend?: unknown; services?: unknown }
97
+ | null
98
+ | undefined;
99
+ const frameId = typeof payload?.frameId === 'string' ? payload.frameId.trim() : '';
100
+ if (!frameId) return { ok: false, reason: 'missing frameId' };
101
+ const childOrigin = exactOrigin(payload?.url);
102
+ if (!childOrigin) return { ok: false, reason: 'child URL is not http(s)' };
103
+
104
+ const item = resolveFrameNavigationItem(input.hostSrc, input.config);
105
+ const rules = item?.childFrames;
106
+ if (!rules) return { ok: false, reason: 'host app may not embed apps' };
107
+ if (!originList(rules.origins).has(childOrigin)) {
108
+ return { ok: false, reason: 'child origin is not allowed' };
109
+ }
110
+
111
+ let identity: ResolvedAppBackend | null = null;
112
+ const backend = payload?.backend as
113
+ | { url?: unknown; companyId?: unknown; type?: unknown; provider?: unknown }
114
+ | null
115
+ | undefined;
116
+ if (backend) {
117
+ const backendOrigin = exactOrigin(backend.url);
118
+ if (!backendOrigin || !originList(rules.backendOrigins).has(backendOrigin)) {
119
+ return { ok: false, reason: 'child identity server is not allowed' };
120
+ }
121
+ const companyId =
122
+ typeof backend.companyId === 'string' || typeof backend.companyId === 'number'
123
+ ? backend.companyId
124
+ : undefined;
125
+ const type =
126
+ backend.type === 'shellui' || backend.type === 'supabase' ? backend.type : undefined;
127
+ identity = resolveAppBackendConfig(
128
+ {
129
+ url: backend.url as string,
130
+ ...(companyId !== undefined ? { companyId } : {}),
131
+ ...(type ? { type } : {}),
132
+ ...(typeof backend.provider === 'string' ? { provider: backend.provider } : {}),
133
+ },
134
+ input.config,
135
+ );
136
+ if (!identity) return { ok: false, reason: 'child identity server is invalid' };
137
+ }
138
+
139
+ const { services, rejected } = resolveChildFrameServices(payload?.services, rules.serviceOrigins);
140
+
141
+ return {
142
+ ok: true,
143
+ entry: {
144
+ hostUuid: from[0],
145
+ frameId,
146
+ url: payload?.url as string,
147
+ identity,
148
+ services,
149
+ rejectedServices: rejected,
150
+ },
151
+ };
152
+ }
153
+
154
+ export function addChildFrame(entry: ChildFrameEntry): void {
155
+ entries.set(entryKey(entry.hostUuid, entry.frameId), entry);
156
+ }
157
+
158
+ export function removeChildFrame(hostUuid: string, frameId: string): void {
159
+ entries.delete(entryKey(hostUuid, frameId));
160
+ }
161
+
162
+ /** The registered child for a `from` path such as `[host, child, ...]`. */
163
+ export function findChildFrame(path: readonly string[]): ChildFrameEntry | null {
164
+ if (path.length < 2) return null;
165
+ return entries.get(entryKey(path[0], path[1])) ?? null;
166
+ }
167
+
168
+ /** Children whose host frame is still registered. Others are dropped. */
169
+ export function listChildFrames(isHostKnown: (uuid: string) => boolean): ChildFrameEntry[] {
170
+ const out: ChildFrameEntry[] = [];
171
+ for (const [key, entry] of entries) {
172
+ if (!isHostKnown(entry.hostUuid)) entries.delete(key);
173
+ else out.push(entry);
174
+ }
175
+ return out;
176
+ }
177
+
178
+ export function clearChildFrames(): void {
179
+ entries.clear();
180
+ }
@@ -140,14 +140,7 @@ export function resolveFrameAuthDelivery(input: {
140
140
  );
141
141
  }
142
142
 
143
- /** Options for `buildSettingsForPropagation`. Shell frames omit the override keys. */
144
- export function frameAuthPropagationOptions(input: {
145
- frameSrc: string;
146
- config?: ShellUIConfig;
147
- shellAccessToken: string | null;
148
- getAppSession: (key: string) => AuthSession | null;
149
- shellOrigin?: string | null;
150
- }): {
143
+ export type FrameAuthPropagationOptions = {
151
144
  includeAuthAccessToken: boolean;
152
145
  accessToken: string | null;
153
146
  authBackendBaseUrl?: string | null;
@@ -155,8 +148,9 @@ export function frameAuthPropagationOptions(input: {
155
148
  storage?: StorageConfig | null;
156
149
  email?: EmailConfig | null;
157
150
  hosting?: HostingConfig | null;
158
- } {
159
- const delivery = resolveFrameAuthDelivery(input);
151
+ };
152
+
153
+ function toPropagationOptions(delivery: FrameAuthDelivery): FrameAuthPropagationOptions {
160
154
  return {
161
155
  includeAuthAccessToken: delivery.includeAuthAccessToken,
162
156
  accessToken: delivery.accessToken,
@@ -165,3 +159,46 @@ export function frameAuthPropagationOptions(input: {
165
159
  ...delivery.services,
166
160
  };
167
161
  }
162
+
163
+ /** Options for `buildSettingsForPropagation`. Shell frames omit the override keys. */
164
+ export function frameAuthPropagationOptions(input: {
165
+ frameSrc: string;
166
+ config?: ShellUIConfig;
167
+ shellAccessToken: string | null;
168
+ getAppSession: (key: string) => AuthSession | null;
169
+ shellOrigin?: string | null;
170
+ }): FrameAuthPropagationOptions {
171
+ return toPropagationOptions(resolveFrameAuthDelivery(input));
172
+ }
173
+
174
+ /**
175
+ * Auth fields for a child app hosted inside an embedded app (`createAppFrame`).
176
+ * The shell token is never sent. With no allowed identity server the child gets
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`.
179
+ */
180
+ export function childFrameAuthPropagationOptions(input: {
181
+ identity: ResolvedAppBackend | null;
182
+ getAppSession: (key: string) => AuthSession | null;
183
+ services?: Partial<Record<'email' | 'storage' | 'files' | 'hosting', string | null>> | null;
184
+ }): FrameAuthPropagationOptions {
185
+ const { identity, getAppSession } = input;
186
+ const allowed = input.services ?? {};
187
+ const session = identity ? getAppSession(identity.key) : null;
188
+ return toPropagationOptions({
189
+ includeAuthAccessToken: Boolean(identity),
190
+ accessToken: session?.accessToken ?? null,
191
+ overrideAuthBackend: true,
192
+ authBackendBaseUrl: identity?.type === 'shellui' ? identity.url : null,
193
+ overrideUser: true,
194
+ settingsUser: settingsUserFromSession(session),
195
+ services: {
196
+ email: allowed.email ? { url: allowed.email } : null,
197
+ // The files app URL rides on storage and is dropped when storage is not allowed.
198
+ storage: allowed.storage
199
+ ? { url: allowed.storage, ...(allowed.files ? { filesUrl: allowed.files } : {}) }
200
+ : null,
201
+ hosting: allowed.hosting ? { url: allowed.hosting } : null,
202
+ },
203
+ });
204
+ }
@@ -10,6 +10,24 @@ import {
10
10
  } from './silentSignIn';
11
11
 
12
12
  describe('buildSilentAuthorizeUrl', () => {
13
+ it('uses the federation entry for a regional identity server', () => {
14
+ const url = new URL(
15
+ buildSilentAuthorizeUrl({
16
+ backendUrl: 'https://id.eu.example/',
17
+ provider: 'upstream',
18
+ redirectTo: 'https://shell.example/login/callback?shellui_silent=1',
19
+ codeChallenge: 'challenge-value',
20
+ companyId: 7,
21
+ }),
22
+ );
23
+ expect(`${url.origin}${url.pathname}`).toBe('https://id.eu.example/oauth/silent-signin');
24
+ expect(url.searchParams.get('company_id')).toBe('7');
25
+ expect(url.searchParams.get('code_challenge')).toBe('challenge-value');
26
+ expect(url.searchParams.get('redirect_to')).toBe(
27
+ 'https://shell.example/login/callback?shellui_silent=1',
28
+ );
29
+ });
30
+
13
31
  it('uses PKCE, prompt=none, and code delivery without a shell token', () => {
14
32
  const shellToken = 'shell-access-token.should.not.appear';
15
33
  const url = new URL(
@@ -92,6 +92,9 @@ export function publishSilentAuthCallbackResult(win: Window = window): boolean {
92
92
  return true;
93
93
  }
94
94
 
95
+ /** Provider name of a regional identity server's trusted upstream (identity federation). */
96
+ export const FEDERATION_PROVIDER = 'upstream';
97
+
95
98
  export function buildSilentAuthorizeUrl(input: {
96
99
  backendUrl: string;
97
100
  provider: string;
@@ -101,7 +104,18 @@ export function buildSilentAuthorizeUrl(input: {
101
104
  clientTimezone?: string;
102
105
  clientDeviceId?: string;
103
106
  }): string {
104
- const authorizeUrl = new URL(`${input.backendUrl.replace(/\/+$/, '')}/api/v1/authorize`);
107
+ const base = input.backendUrl.replace(/\/+$/, '');
108
+ if (input.provider === FEDERATION_PROVIDER) {
109
+ // A regional identity server signs in through its trusted upstream (global identity).
110
+ // It has its own prompt=none entry and returns the usual PKCE code to `redirect_to`.
111
+ const federated = new URL(`${base}/oauth/silent-signin`);
112
+ federated.searchParams.set('redirect_to', input.redirectTo);
113
+ federated.searchParams.set('code_challenge', input.codeChallenge);
114
+ const federatedCompany = getShellUILoginCompanyId(input.companyId);
115
+ if (federatedCompany) federated.searchParams.set('company_id', federatedCompany);
116
+ return federated.toString();
117
+ }
118
+ const authorizeUrl = new URL(`${base}/api/v1/authorize`);
105
119
  authorizeUrl.searchParams.set('provider', input.provider);
106
120
  authorizeUrl.searchParams.set('redirect_to', input.redirectTo);
107
121
  authorizeUrl.searchParams.set('code_challenge', input.codeChallenge);
@@ -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
+ }
@@ -5,7 +5,7 @@ import urls from '../../../constants/urls';
5
5
  import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
6
6
  import {
7
7
  buildAuthUrlWithNext,
8
- buildOAuthSessionRedirectTo,
8
+ resolveOAuthSessionRedirectTo,
9
9
  captureCliCallbackFromSearch,
10
10
  hashHasOAuthTokens,
11
11
  inferAccessPendingErrorCode,
@@ -15,7 +15,7 @@ import {
15
15
  redirectCliCallbackError,
16
16
  redirectToCliCallback,
17
17
  } from '../utils';
18
- import { WEB_PKCE_FLOW_PARAM, isMagicLinkFlowId, takeWebPkceVerifier } from '../utils/webPkce';
18
+ import { WEB_PKCE_FLOW_PARAM, isMagicLinkFlowId, takeWebPkceFlow } from '../utils/webPkce';
19
19
  import {
20
20
  isSilentAuthCallbackFrame,
21
21
  publishSilentAuthCallbackResult,
@@ -231,13 +231,15 @@ export const OAuthCallbackView = () => {
231
231
 
232
232
  let cancelled = false;
233
233
  const runSessionExchange = async () => {
234
- const redirectTo = buildOAuthSessionRedirectTo(
234
+ const pkceFlowId = params.get(WEB_PKCE_FLOW_PARAM);
235
+ const pkceFlow = takeWebPkceFlow(pkceFlowId);
236
+ const codeVerifier = pkceFlow?.verifier ?? undefined;
237
+ const redirectTo = resolveOAuthSessionRedirectTo(
238
+ pkceFlow?.redirectTo,
235
239
  window.location.origin,
236
240
  location.pathname,
237
241
  location.search,
238
242
  );
239
- const pkceFlowId = params.get(WEB_PKCE_FLOW_PARAM);
240
- const codeVerifier = takeWebPkceVerifier(pkceFlowId) ?? undefined;
241
243
  if (!codeVerifier && isMagicLinkFlowId(pkceFlowId)) {
242
244
  // The magic link verifier lives only in the browser that asked for the link.
243
245
  // Do not send the code: it stays unused.
@@ -1,6 +1,9 @@
1
1
  import { describe, expect, test } from 'vitest';
2
2
  import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
3
- import { buildOAuthSessionRedirectTo } from './buildOAuthSessionRedirectTo';
3
+ import {
4
+ buildOAuthSessionRedirectTo,
5
+ resolveOAuthSessionRedirectTo,
6
+ } from './buildOAuthSessionRedirectTo';
4
7
 
5
8
  describe('buildOAuthSessionRedirectTo', () => {
6
9
  test('strips shellui_auth_code and keeps other query params', () => {
@@ -20,3 +23,41 @@ describe('buildOAuthSessionRedirectTo', () => {
20
23
  ).toBe('http://127.0.0.1:8765/callback');
21
24
  });
22
25
  });
26
+
27
+ describe('resolveOAuthSessionRedirectTo', () => {
28
+ const start =
29
+ 'https://playground.shellui.com/login/callback?provider=github&shellui_pkce_flow=o0123';
30
+
31
+ test('uses the stored start value when the host added a trailing slash', () => {
32
+ expect(
33
+ resolveOAuthSessionRedirectTo(
34
+ start,
35
+ 'https://playground.shellui.com',
36
+ '/login/callback/',
37
+ '?provider=github&shellui_pkce_flow=o0123&shellui_auth_code=abc',
38
+ ),
39
+ ).toBe(start);
40
+ });
41
+
42
+ test('falls back to the current URL when nothing was stored', () => {
43
+ expect(
44
+ resolveOAuthSessionRedirectTo(
45
+ null,
46
+ 'https://playground.shellui.com',
47
+ '/login/callback/',
48
+ '?provider=github&shellui_auth_code=abc',
49
+ ),
50
+ ).toBe('https://playground.shellui.com/login/callback/?provider=github');
51
+ });
52
+
53
+ test('ignores a stored value for another origin', () => {
54
+ expect(
55
+ resolveOAuthSessionRedirectTo(
56
+ 'https://evil.test/login/callback',
57
+ 'https://playground.shellui.com',
58
+ '/login/callback',
59
+ '?shellui_auth_code=abc',
60
+ ),
61
+ ).toBe('https://playground.shellui.com/login/callback');
62
+ });
63
+ });
@@ -15,3 +15,26 @@ export function buildOAuthSessionRedirectTo(
15
15
  url.search = params.toString();
16
16
  return url.toString();
17
17
  }
18
+
19
+ /**
20
+ * Pick the `redirect_to` for the session exchange. Identity compares it exactly
21
+ * with the value sent at sign-in start, so prefer that stored value. A static
22
+ * host can add a trailing slash on the way back (GitHub Pages turns
23
+ * `/login/callback` into `/login/callback/`). Fall back to the current URL when
24
+ * nothing was stored or the stored value is for another origin.
25
+ */
26
+ export function resolveOAuthSessionRedirectTo(
27
+ storedRedirectTo: string | null | undefined,
28
+ origin: string,
29
+ pathname: string,
30
+ search: string,
31
+ ): string {
32
+ if (storedRedirectTo) {
33
+ try {
34
+ if (new URL(storedRedirectTo).origin === origin) return storedRedirectTo;
35
+ } catch {
36
+ // invalid stored value: rebuild from the current URL
37
+ }
38
+ }
39
+ return buildOAuthSessionRedirectTo(origin, pathname, search);
40
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { AuthSession } from '../types';
3
+ import { canRestoreStoredSession } from './canRestoreStoredSession';
4
+
5
+ const base = {
6
+ accessToken: '',
7
+ refreshToken: '',
8
+ tokenType: 'bearer',
9
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
10
+ provider: 'github',
11
+ } as unknown as AuthSession;
12
+
13
+ describe('canRestoreStoredSession', () => {
14
+ it('rejects a profile without tokens, as seen in a new tab', () => {
15
+ expect(canRestoreStoredSession(base, false)).toBe(false);
16
+ });
17
+
18
+ it('accepts a refresh token', () => {
19
+ expect(canRestoreStoredSession({ ...base, refreshToken: 'r' }, false)).toBe(true);
20
+ });
21
+
22
+ it('accepts an access token', () => {
23
+ expect(canRestoreStoredSession({ ...base, accessToken: 'a' }, false)).toBe(true);
24
+ });
25
+
26
+ it('accepts a token-less profile when BFF cookies can refresh it', () => {
27
+ expect(canRestoreStoredSession(base, true)).toBe(true);
28
+ });
29
+ });
@@ -0,0 +1,12 @@
1
+ import type { AuthSession } from '../types';
2
+
3
+ /**
4
+ * Whether a stored session snapshot can become a signed-in session on boot.
5
+ *
6
+ * The access token lives in memory only and the refresh token is tab-scoped
7
+ * (sessionStorage), while the profile is shared in localStorage. A new tab
8
+ * therefore sees the profile without any token. Without a token, or a refresh
9
+ * token or BFF cookie to get one, the snapshot must not count as signed in.
10
+ */
11
+ export const canRestoreStoredSession = (stored: AuthSession, bffAuthEnabled: boolean): boolean =>
12
+ Boolean(stored.accessToken || stored.refreshToken || bffAuthEnabled);
@@ -4,8 +4,12 @@ export {
4
4
  getShellUILoginDeviceId,
5
5
  } from './clientLoginContext';
6
6
  export { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
7
+ export { resolveSdkLoginRedirectPath } from './resolveSdkLoginRedirectPath';
7
8
  export { getLoginCancelTarget, isPublicNavigationPage } from './loginCancelTarget';
8
- export { buildOAuthSessionRedirectTo } from './buildOAuthSessionRedirectTo';
9
+ export {
10
+ buildOAuthSessionRedirectTo,
11
+ resolveOAuthSessionRedirectTo,
12
+ } from './buildOAuthSessionRedirectTo';
9
13
  export { buildSessionFromParams } from './buildSessionFromParams';
10
14
  export {
11
15
  buildSessionFromTokenPayload,
@@ -48,6 +52,7 @@ export { getPreferredBackendProvider } from './getPreferredBackendProvider';
48
52
  export { getProviderVisual } from './getProviderVisual';
49
53
  export { isLoginMethod } from './isLoginMethod';
50
54
  export { resolveLoginSettings } from './resolveLoginSettings';
55
+ export { canRestoreStoredSession } from './canRestoreStoredSession';
51
56
  export { isSessionExpired } from './isSessionExpired';
52
57
  export { isTokenAutoRefreshDisabled } from './isTokenAutoRefreshDisabled';
53
58
  export { normalizeAuthSettings } from './normalizeAuthSettings';
@@ -60,6 +65,7 @@ export {
60
65
  WEB_PKCE_FLOW_PARAM,
61
66
  prepareWebPkce,
62
67
  takeWebPkceVerifier,
68
+ takeWebPkceFlow,
63
69
  clearWebPkce,
64
70
  isWebPkceErrorCode,
65
71
  isMagicLinkFlowId,