@shellui/core 0.6.2 → 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.
- package/package.json +2 -2
- package/schemas/shellui.config.schema.json +147 -70
- package/src/app.tsx +2 -0
- package/src/components/ContentView.tsx +21 -30
- package/src/components/iframeUrlSafety.spec.ts +67 -0
- package/src/components/iframeUrlSafety.ts +50 -0
- package/src/components/ui/sidebar.tsx +11 -5
- package/src/features/admin/AdminView.tsx +9 -6
- package/src/features/auth/AuthProvider.tsx +49 -5
- package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
- package/src/features/auth/appBackend/appBackendSessions.spec.ts +329 -0
- package/src/features/auth/appBackend/appBackendSessions.ts +443 -0
- package/src/features/auth/appBackend/childFrames.spec.ts +328 -0
- package/src/features/auth/appBackend/childFrames.ts +180 -0
- package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
- package/src/features/auth/appBackend/frameAuth.ts +204 -0
- package/src/features/auth/appBackend/identity.spec.ts +201 -0
- package/src/features/auth/appBackend/identity.ts +173 -0
- package/src/features/auth/appBackend/silentSignIn.spec.ts +225 -0
- package/src/features/auth/appBackend/silentSignIn.ts +254 -0
- package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
- package/src/features/auth/appBackend/tokenExchange.ts +76 -0
- package/src/features/auth/backends/shellui.spec.ts +51 -19
- package/src/features/auth/backends/shellui.ts +20 -5
- package/src/features/auth/backends/types.ts +7 -2
- package/src/features/auth/components/LoginView.tsx +40 -18
- package/src/features/auth/components/OAuthCallbackView.tsx +33 -4
- package/src/features/auth/utils/authRequestError.ts +3 -0
- package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
- package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
- package/src/features/auth/utils/canRestoreStoredSession.spec.ts +29 -0
- package/src/features/auth/utils/canRestoreStoredSession.ts +12 -0
- package/src/features/auth/utils/index.ts +16 -1
- package/src/features/auth/utils/loginCancelTarget.spec.ts +73 -0
- package/src/features/auth/utils/loginCancelTarget.ts +45 -0
- package/src/features/auth/utils/loginPanelFrame.spec.ts +24 -0
- package/src/features/auth/utils/loginPanelFrame.ts +14 -0
- package/src/features/auth/utils/resolveSdkLoginRedirectPath.spec.ts +41 -0
- package/src/features/auth/utils/resolveSdkLoginRedirectPath.ts +31 -0
- package/src/features/auth/utils/webPkce.spec.ts +119 -0
- package/src/features/auth/utils/webPkce.ts +169 -0
- package/src/features/chromeActions/computeActionInsets.ts +7 -4
- package/src/features/config/types.ts +70 -3
- package/src/features/layouts/appbar/AppBarLayout.tsx +63 -30
- package/src/features/layouts/chrome/CollapsedDesktopTitlebar.tsx +12 -23
- package/src/features/layouts/chrome/ContentDragOverlay.tsx +5 -6
- package/src/features/layouts/chrome/DesktopChrome.tsx +37 -0
- package/src/features/layouts/chrome/DesktopHistoryButtons.tsx +15 -4
- package/src/features/layouts/chrome/MacStrip.tsx +33 -0
- package/src/features/layouts/chrome/constants.ts +33 -8
- package/src/features/layouts/chrome/index.ts +8 -0
- package/src/features/layouts/chrome/stripDragMap.ts +35 -0
- package/src/features/layouts/chrome/stripNoDrag.spec.tsx +103 -0
- package/src/features/layouts/chrome/useScrollHideChrome.ts +3 -8
- package/src/features/layouts/filterNavigationForAuthState.spec.ts +5 -3
- package/src/features/layouts/floating/FloatingBottomDock.tsx +199 -20
- package/src/features/layouts/floating/FloatingLayout.tsx +13 -8
- package/src/features/layouts/floating/FloatingSidebar.tsx +144 -70
- package/src/features/layouts/floating/computeFloatingInsets.ts +22 -4
- package/src/features/layouts/floating/useFloatingChrome.ts +3 -1
- package/src/features/layouts/floating/useSoftKeyboard.spec.ts +39 -0
- package/src/features/layouts/floating/useSoftKeyboard.ts +82 -0
- package/src/features/layouts/fullscreen/FullscreenLayout.tsx +38 -10
- package/src/features/layouts/sidebar/NavigationContent.tsx +14 -6
- package/src/features/layouts/sidebar/SidebarIcons.tsx +3 -9
- package/src/features/layouts/sidebar/SidebarInner.tsx +50 -39
- package/src/features/layouts/sidebar/SidebarLayout.tsx +8 -11
- package/src/features/layouts/utils.ts +4 -3
- package/src/features/layouts/windows/DesktopDots.tsx +76 -0
- package/src/features/layouts/windows/WindowsLayout.tsx +184 -125
- package/src/features/layouts/windows/deskDots.spec.ts +52 -0
- package/src/features/layouts/windows/deskDots.ts +314 -0
- package/src/features/settings/SettingsProvider.tsx +198 -29
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +379 -4
- package/src/features/settings/utils/buildSettingsForPropagation.ts +65 -39
- package/src/features/theme/applyTheme.ts +8 -0
- package/src/features/theme/navContrast.spec.ts +49 -0
- package/src/features/theme/navContrast.ts +108 -0
- package/src/features/transfers/transferQueue.spec.ts +6 -2
- package/src/i18n/translations/en/common.json +27 -0
- package/src/i18n/translations/fr/common.json +27 -0
- package/src/index.css +935 -46
- package/src/index.ts +2 -0
- package/src/routes/hooks/useNavigationItems.ts +14 -3
- package/src/routes/hooks/withShellSearch.spec.ts +13 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
SILENT_AUTH_RESULT_TYPE,
|
|
4
|
+
buildSilentAuthorizeUrl,
|
|
5
|
+
publishSilentAuthCallbackResult,
|
|
6
|
+
readSilentAuthMessage,
|
|
7
|
+
runSilentPkceSignIn,
|
|
8
|
+
type SilentAuthFrame,
|
|
9
|
+
type SilentAuthHost,
|
|
10
|
+
} from './silentSignIn';
|
|
11
|
+
|
|
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
|
+
|
|
31
|
+
it('uses PKCE, prompt=none, and code delivery without a shell token', () => {
|
|
32
|
+
const shellToken = 'shell-access-token.should.not.appear';
|
|
33
|
+
const url = new URL(
|
|
34
|
+
buildSilentAuthorizeUrl({
|
|
35
|
+
backendUrl: 'https://id.other.example/',
|
|
36
|
+
provider: 'google',
|
|
37
|
+
redirectTo:
|
|
38
|
+
'https://shell.example/login/callback?shellui_silent=1&shellui_silent_state=abc',
|
|
39
|
+
codeChallenge: 'challenge-value',
|
|
40
|
+
companyId: 4,
|
|
41
|
+
}),
|
|
42
|
+
);
|
|
43
|
+
expect(`${url.origin}${url.pathname}`).toBe('https://id.other.example/api/v1/authorize');
|
|
44
|
+
expect(url.searchParams.get('prompt')).toBe('none');
|
|
45
|
+
expect(url.searchParams.get('token_delivery')).toBe('code');
|
|
46
|
+
expect(url.searchParams.get('code_challenge')).toBe('challenge-value');
|
|
47
|
+
expect(url.searchParams.get('code_challenge_method')).toBe('S256');
|
|
48
|
+
expect(url.searchParams.get('provider')).toBe('google');
|
|
49
|
+
expect(url.searchParams.get('company_id')).toBe('4');
|
|
50
|
+
expect(url.searchParams.get('code_verifier')).toBeNull();
|
|
51
|
+
expect(url.searchParams.get('access_token')).toBeNull();
|
|
52
|
+
expect(url.toString()).not.toContain(shellToken);
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('readSilentAuthMessage', () => {
|
|
57
|
+
const source = { id: 'frame' };
|
|
58
|
+
const expected = { origin: 'https://shell.example', source, state: 'state-1' };
|
|
59
|
+
|
|
60
|
+
it('accepts a matching code from the opened frame', () => {
|
|
61
|
+
expect(
|
|
62
|
+
readSilentAuthMessage(
|
|
63
|
+
{
|
|
64
|
+
origin: 'https://shell.example',
|
|
65
|
+
source,
|
|
66
|
+
data: { type: SILENT_AUTH_RESULT_TYPE, state: 'state-1', authCode: 'one-time' },
|
|
67
|
+
},
|
|
68
|
+
expected,
|
|
69
|
+
),
|
|
70
|
+
).toEqual({ ok: true, authCode: 'one-time' });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('rejects a wildcard origin, a different source, and a different state', () => {
|
|
74
|
+
const data = { type: SILENT_AUTH_RESULT_TYPE, state: 'state-1', authCode: 'one-time' };
|
|
75
|
+
expect(
|
|
76
|
+
readSilentAuthMessage({ origin: '*', source, data }, { ...expected, origin: '*' }),
|
|
77
|
+
).toBeNull();
|
|
78
|
+
expect(
|
|
79
|
+
readSilentAuthMessage({ origin: 'https://evil.example', source, data }, expected),
|
|
80
|
+
).toBeNull();
|
|
81
|
+
expect(
|
|
82
|
+
readSilentAuthMessage(
|
|
83
|
+
{ origin: 'https://shell.example', source: { id: 'other' }, data },
|
|
84
|
+
expected,
|
|
85
|
+
),
|
|
86
|
+
).toBeNull();
|
|
87
|
+
expect(
|
|
88
|
+
readSilentAuthMessage(
|
|
89
|
+
{
|
|
90
|
+
origin: 'https://shell.example',
|
|
91
|
+
source,
|
|
92
|
+
data: { type: SILENT_AUTH_RESULT_TYPE, state: 'other', authCode: 'one-time' },
|
|
93
|
+
},
|
|
94
|
+
expected,
|
|
95
|
+
),
|
|
96
|
+
).toBeNull();
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
describe('publishSilentAuthCallbackResult', () => {
|
|
101
|
+
it('posts to the same origin and never to *', () => {
|
|
102
|
+
const postMessage = vi.fn();
|
|
103
|
+
const parent = { location: { origin: 'https://shell.example' }, postMessage };
|
|
104
|
+
const win = {
|
|
105
|
+
parent,
|
|
106
|
+
location: {
|
|
107
|
+
origin: 'https://shell.example',
|
|
108
|
+
search: '?shellui_silent=1&shellui_silent_state=abc&shellui_auth_code=one-time',
|
|
109
|
+
},
|
|
110
|
+
} as unknown as Window;
|
|
111
|
+
|
|
112
|
+
expect(publishSilentAuthCallbackResult(win)).toBe(true);
|
|
113
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
114
|
+
expect(postMessage.mock.calls[0][1]).toBe('https://shell.example');
|
|
115
|
+
expect(postMessage.mock.calls[0][1]).not.toBe('*');
|
|
116
|
+
expect(postMessage.mock.calls[0][0]).toMatchObject({
|
|
117
|
+
type: SILENT_AUTH_RESULT_TYPE,
|
|
118
|
+
state: 'abc',
|
|
119
|
+
authCode: 'one-time',
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('does not post the code to a cross-origin parent', () => {
|
|
124
|
+
const postMessage = vi.fn();
|
|
125
|
+
const parent = { postMessage };
|
|
126
|
+
Object.defineProperty(parent, 'location', {
|
|
127
|
+
get() {
|
|
128
|
+
throw new Error('cross-origin');
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
const win = {
|
|
132
|
+
parent,
|
|
133
|
+
location: {
|
|
134
|
+
origin: 'https://shell.example',
|
|
135
|
+
search: '?shellui_silent=1&shellui_silent_state=abc&shellui_auth_code=one-time',
|
|
136
|
+
},
|
|
137
|
+
} as unknown as Window;
|
|
138
|
+
|
|
139
|
+
expect(publishSilentAuthCallbackResult(win)).toBe(true);
|
|
140
|
+
expect(postMessage).not.toHaveBeenCalled();
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('ignores a top-level window', () => {
|
|
144
|
+
const win = {
|
|
145
|
+
location: {
|
|
146
|
+
origin: 'https://shell.example',
|
|
147
|
+
search: '?shellui_silent=1&shellui_silent_state=abc',
|
|
148
|
+
},
|
|
149
|
+
} as unknown as Window;
|
|
150
|
+
(win as { parent: Window }).parent = win;
|
|
151
|
+
expect(publishSilentAuthCallbackResult(win)).toBe(false);
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
describe('runSilentPkceSignIn', () => {
|
|
156
|
+
function host(): SilentAuthHost & {
|
|
157
|
+
frame: SilentAuthFrame;
|
|
158
|
+
src: () => string;
|
|
159
|
+
deliver: (event: { origin: string; source: unknown; data: unknown }) => void;
|
|
160
|
+
} {
|
|
161
|
+
const frame: SilentAuthFrame = { contentWindow: { id: 'frame' }, remove: vi.fn() };
|
|
162
|
+
let deliver = (_event: { origin: string; source: unknown; data: unknown }) => {};
|
|
163
|
+
let src = '';
|
|
164
|
+
return {
|
|
165
|
+
frame,
|
|
166
|
+
origin: 'https://shell.example',
|
|
167
|
+
callbackPath: '/login/callback',
|
|
168
|
+
timeoutMs: 50,
|
|
169
|
+
src: () => src,
|
|
170
|
+
deliver: (event) => deliver(event),
|
|
171
|
+
createFrame(next) {
|
|
172
|
+
src = next;
|
|
173
|
+
return frame;
|
|
174
|
+
},
|
|
175
|
+
listen(fn) {
|
|
176
|
+
deliver = fn;
|
|
177
|
+
return () => {};
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
it('returns the code and verifier for a matching frame message', async () => {
|
|
183
|
+
const silent = host();
|
|
184
|
+
const pending = runSilentPkceSignIn(
|
|
185
|
+
{ backendUrl: 'https://id.other.example', provider: 'google', companyId: 4 },
|
|
186
|
+
silent,
|
|
187
|
+
);
|
|
188
|
+
await vi.waitUntil(() => silent.src() !== '');
|
|
189
|
+
const authorize = new URL(silent.src());
|
|
190
|
+
const redirect = new URL(authorize.searchParams.get('redirect_to') ?? '');
|
|
191
|
+
const state = redirect.searchParams.get('shellui_silent_state') ?? '';
|
|
192
|
+
expect(authorize.searchParams.get('prompt')).toBe('none');
|
|
193
|
+
expect(authorize.toString()).not.toContain('code_verifier');
|
|
194
|
+
|
|
195
|
+
silent.deliver({
|
|
196
|
+
origin: 'https://evil.example',
|
|
197
|
+
source: silent.frame.contentWindow,
|
|
198
|
+
data: { type: SILENT_AUTH_RESULT_TYPE, state, authCode: 'stolen' },
|
|
199
|
+
});
|
|
200
|
+
silent.deliver({
|
|
201
|
+
origin: 'https://shell.example',
|
|
202
|
+
source: silent.frame.contentWindow,
|
|
203
|
+
data: { type: SILENT_AUTH_RESULT_TYPE, state, authCode: 'one-time' },
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
const outcome = await pending;
|
|
207
|
+
expect(outcome.ok).toBe(true);
|
|
208
|
+
if (!outcome.ok) return;
|
|
209
|
+
expect(outcome.authCode).toBe('one-time');
|
|
210
|
+
expect(outcome.redirectTo).toBe(redirect.toString());
|
|
211
|
+
expect(outcome.codeVerifier).toMatch(/^[A-Za-z0-9\-._~]{43,128}$/);
|
|
212
|
+
expect(authorize.toString()).not.toContain(outcome.codeVerifier);
|
|
213
|
+
expect(silent.frame.remove).toHaveBeenCalled();
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('times out without a result', async () => {
|
|
217
|
+
const silent = host();
|
|
218
|
+
const outcome = await runSilentPkceSignIn(
|
|
219
|
+
{ backendUrl: 'https://id.other.example', provider: 'google' },
|
|
220
|
+
silent,
|
|
221
|
+
);
|
|
222
|
+
expect(outcome).toEqual({ ok: false, reason: 'timeout' });
|
|
223
|
+
expect(silent.frame.remove).toHaveBeenCalled();
|
|
224
|
+
});
|
|
225
|
+
});
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import urls from '../../../constants/urls';
|
|
2
|
+
import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
|
|
3
|
+
import {
|
|
4
|
+
getShellUILoginClientTimezone,
|
|
5
|
+
getShellUILoginCompanyId,
|
|
6
|
+
getShellUILoginDeviceId,
|
|
7
|
+
} from '../utils/clientLoginContext';
|
|
8
|
+
import { PKCE_CHALLENGE_METHOD } from '../utils/desktopSignIn';
|
|
9
|
+
import { createPkcePair } from '../utils/pkce';
|
|
10
|
+
|
|
11
|
+
export const SILENT_AUTH_QUERY = 'shellui_silent';
|
|
12
|
+
export const SILENT_AUTH_STATE_QUERY = 'shellui_silent_state';
|
|
13
|
+
export const SILENT_AUTH_RESULT_TYPE = 'SHELLUI_SILENT_AUTH_RESULT';
|
|
14
|
+
|
|
15
|
+
const DEFAULT_SILENT_TIMEOUT_MS = 15_000;
|
|
16
|
+
|
|
17
|
+
export function isSilentAuthCallbackSearch(search: string): boolean {
|
|
18
|
+
const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);
|
|
19
|
+
return (
|
|
20
|
+
params.get(SILENT_AUTH_QUERY) === '1' && Boolean(params.get(SILENT_AUTH_STATE_QUERY)?.trim())
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** True inside the hidden frame that completes sign-in for another identity server. */
|
|
25
|
+
export function isSilentAuthCallbackFrame(): boolean {
|
|
26
|
+
if (typeof window === 'undefined') return false;
|
|
27
|
+
if (window.parent === window) return false;
|
|
28
|
+
return isSilentAuthCallbackSearch(window.location.search);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type SilentAuthResult =
|
|
32
|
+
| { ok: true; authCode: string }
|
|
33
|
+
| { ok: false; error: string; errorCode: string | null };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Accept a silent-auth result only from the frame we opened, on this origin, for this state.
|
|
37
|
+
* A `*` target is never treated as a match.
|
|
38
|
+
*/
|
|
39
|
+
export function readSilentAuthMessage(
|
|
40
|
+
event: { origin: string; source: unknown; data: unknown },
|
|
41
|
+
expected: { origin: string; source: unknown; state: string },
|
|
42
|
+
): SilentAuthResult | null {
|
|
43
|
+
if (!expected.origin || expected.origin === 'null' || expected.origin === '*') return null;
|
|
44
|
+
if (!expected.state) return null;
|
|
45
|
+
if (event.origin !== expected.origin) return null;
|
|
46
|
+
if (event.source === null || event.source === undefined || event.source !== expected.source) {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
if (!event.data || typeof event.data !== 'object') return null;
|
|
50
|
+
const record = event.data as Record<string, unknown>;
|
|
51
|
+
if (record.type !== SILENT_AUTH_RESULT_TYPE) return null;
|
|
52
|
+
if (record.state !== expected.state) return null;
|
|
53
|
+
const authCode = typeof record.authCode === 'string' ? record.authCode.trim() : '';
|
|
54
|
+
if (authCode) return { ok: true, authCode };
|
|
55
|
+
const error =
|
|
56
|
+
typeof record.error === 'string' && record.error.trim()
|
|
57
|
+
? record.error.trim()
|
|
58
|
+
: 'silent_sign_in_failed';
|
|
59
|
+
const errorCode = typeof record.errorCode === 'string' ? record.errorCode : null;
|
|
60
|
+
return { ok: false, error, errorCode };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Hand the one-time code to the same-origin shell. Does not exchange it.
|
|
65
|
+
* Returns true when this document is the silent callback, including when the
|
|
66
|
+
* parent is cross-origin and the code must not be posted.
|
|
67
|
+
*/
|
|
68
|
+
export function publishSilentAuthCallbackResult(win: Window = window): boolean {
|
|
69
|
+
if (win.parent === win) return false;
|
|
70
|
+
if (!isSilentAuthCallbackSearch(win.location.search)) return false;
|
|
71
|
+
|
|
72
|
+
let parentOrigin: string | null = null;
|
|
73
|
+
try {
|
|
74
|
+
parentOrigin = win.parent.location.origin;
|
|
75
|
+
} catch {
|
|
76
|
+
parentOrigin = null;
|
|
77
|
+
}
|
|
78
|
+
const ownOrigin = win.location.origin;
|
|
79
|
+
if (!parentOrigin || parentOrigin !== ownOrigin || parentOrigin === '*') {
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const params = new URLSearchParams(win.location.search);
|
|
84
|
+
const payload = {
|
|
85
|
+
type: SILENT_AUTH_RESULT_TYPE,
|
|
86
|
+
state: params.get(SILENT_AUTH_STATE_QUERY) ?? '',
|
|
87
|
+
authCode: params.get(SHELLUI_AUTH_CODE_PARAM),
|
|
88
|
+
error: params.get('error') || params.get('shellui_oauth_error'),
|
|
89
|
+
errorCode: params.get('error') || params.get('shellui_oauth_error_code'),
|
|
90
|
+
};
|
|
91
|
+
win.parent.postMessage(payload, parentOrigin);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Provider name of a regional identity server's trusted upstream (identity federation). */
|
|
96
|
+
export const FEDERATION_PROVIDER = 'upstream';
|
|
97
|
+
|
|
98
|
+
export function buildSilentAuthorizeUrl(input: {
|
|
99
|
+
backendUrl: string;
|
|
100
|
+
provider: string;
|
|
101
|
+
redirectTo: string;
|
|
102
|
+
codeChallenge: string;
|
|
103
|
+
companyId?: string | number;
|
|
104
|
+
clientTimezone?: string;
|
|
105
|
+
clientDeviceId?: string;
|
|
106
|
+
}): string {
|
|
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`);
|
|
119
|
+
authorizeUrl.searchParams.set('provider', input.provider);
|
|
120
|
+
authorizeUrl.searchParams.set('redirect_to', input.redirectTo);
|
|
121
|
+
authorizeUrl.searchParams.set('code_challenge', input.codeChallenge);
|
|
122
|
+
authorizeUrl.searchParams.set('code_challenge_method', PKCE_CHALLENGE_METHOD);
|
|
123
|
+
authorizeUrl.searchParams.set('prompt', 'none');
|
|
124
|
+
authorizeUrl.searchParams.set('token_delivery', 'code');
|
|
125
|
+
const companyId = getShellUILoginCompanyId(input.companyId);
|
|
126
|
+
if (companyId) authorizeUrl.searchParams.set('company_id', companyId);
|
|
127
|
+
if (input.clientTimezone) authorizeUrl.searchParams.set('client_timezone', input.clientTimezone);
|
|
128
|
+
if (input.clientDeviceId) authorizeUrl.searchParams.set('client_device_id', input.clientDeviceId);
|
|
129
|
+
return authorizeUrl.toString();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export type SilentSignInOutcome =
|
|
133
|
+
| { ok: true; authCode: string; redirectTo: string; codeVerifier: string }
|
|
134
|
+
| { ok: false; reason: string };
|
|
135
|
+
|
|
136
|
+
export type SilentAuthFrame = {
|
|
137
|
+
contentWindow: unknown;
|
|
138
|
+
remove: () => void;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export type SilentAuthHost = {
|
|
142
|
+
origin: string;
|
|
143
|
+
callbackPath: string;
|
|
144
|
+
timeoutMs?: number;
|
|
145
|
+
createFrame: (src: string) => SilentAuthFrame;
|
|
146
|
+
listen: (fn: (event: { origin: string; source: unknown; data: unknown }) => void) => () => void;
|
|
147
|
+
clientTimezone?: string;
|
|
148
|
+
clientDeviceId?: string;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
function browserSilentHost(): SilentAuthHost {
|
|
152
|
+
return {
|
|
153
|
+
origin: window.location.origin,
|
|
154
|
+
callbackPath: urls.loginCallback,
|
|
155
|
+
timeoutMs: DEFAULT_SILENT_TIMEOUT_MS,
|
|
156
|
+
clientTimezone: getShellUILoginClientTimezone() || undefined,
|
|
157
|
+
clientDeviceId: getShellUILoginDeviceId() || undefined,
|
|
158
|
+
listen(fn) {
|
|
159
|
+
const handler = (event: MessageEvent) => {
|
|
160
|
+
fn({ origin: event.origin, source: event.source, data: event.data });
|
|
161
|
+
};
|
|
162
|
+
window.addEventListener('message', handler);
|
|
163
|
+
return () => window.removeEventListener('message', handler);
|
|
164
|
+
},
|
|
165
|
+
createFrame(src) {
|
|
166
|
+
const iframe = document.createElement('iframe');
|
|
167
|
+
iframe.title = 'Identity sign-in';
|
|
168
|
+
iframe.setAttribute('aria-hidden', 'true');
|
|
169
|
+
iframe.tabIndex = -1;
|
|
170
|
+
iframe.style.cssText =
|
|
171
|
+
'position:fixed;width:0;height:0;border:0;opacity:0;pointer-events:none';
|
|
172
|
+
document.body.appendChild(iframe);
|
|
173
|
+
const handle = {
|
|
174
|
+
contentWindow: iframe.contentWindow,
|
|
175
|
+
remove() {
|
|
176
|
+
iframe.remove();
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
// Navigate after the caller stores this handle so a fast callback can be matched.
|
|
180
|
+
queueMicrotask(() => {
|
|
181
|
+
iframe.src = src;
|
|
182
|
+
});
|
|
183
|
+
return handle;
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* PKCE sign-in in a hidden frame. `prompt=none` asks the identity server not to
|
|
190
|
+
* show UI. The verifier stays in the shell. The frame only posts the one-time code.
|
|
191
|
+
*/
|
|
192
|
+
export async function runSilentPkceSignIn(
|
|
193
|
+
input: {
|
|
194
|
+
backendUrl: string;
|
|
195
|
+
provider: string;
|
|
196
|
+
companyId?: string | number;
|
|
197
|
+
},
|
|
198
|
+
host: SilentAuthHost = browserSilentHost(),
|
|
199
|
+
): Promise<SilentSignInOutcome> {
|
|
200
|
+
if (!host.origin || host.origin === '*' || host.origin === 'null') {
|
|
201
|
+
return { ok: false, reason: 'invalid_origin' };
|
|
202
|
+
}
|
|
203
|
+
const provider = input.provider.trim().toLowerCase();
|
|
204
|
+
if (!provider) return { ok: false, reason: 'missing_provider' };
|
|
205
|
+
|
|
206
|
+
const { verifier, challenge } = await createPkcePair();
|
|
207
|
+
const state =
|
|
208
|
+
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
|
209
|
+
? crypto.randomUUID()
|
|
210
|
+
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
211
|
+
const redirectTo = `${host.origin}${host.callbackPath}?${SILENT_AUTH_QUERY}=1&${SILENT_AUTH_STATE_QUERY}=${encodeURIComponent(state)}`;
|
|
212
|
+
const authorizeUrl = buildSilentAuthorizeUrl({
|
|
213
|
+
backendUrl: input.backendUrl,
|
|
214
|
+
provider,
|
|
215
|
+
redirectTo,
|
|
216
|
+
codeChallenge: challenge,
|
|
217
|
+
companyId: input.companyId,
|
|
218
|
+
clientTimezone: host.clientTimezone,
|
|
219
|
+
clientDeviceId: host.clientDeviceId,
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
return new Promise((resolve) => {
|
|
223
|
+
let settled = false;
|
|
224
|
+
let frame: SilentAuthFrame | null = null;
|
|
225
|
+
let stop = () => {};
|
|
226
|
+
const finish = (outcome: SilentSignInOutcome) => {
|
|
227
|
+
if (settled) return;
|
|
228
|
+
settled = true;
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
stop();
|
|
231
|
+
frame?.remove();
|
|
232
|
+
resolve(outcome);
|
|
233
|
+
};
|
|
234
|
+
const timer = setTimeout(
|
|
235
|
+
() => finish({ ok: false, reason: 'timeout' }),
|
|
236
|
+
host.timeoutMs ?? DEFAULT_SILENT_TIMEOUT_MS,
|
|
237
|
+
);
|
|
238
|
+
stop = host.listen((event) => {
|
|
239
|
+
if (!frame?.contentWindow) return;
|
|
240
|
+
const result = readSilentAuthMessage(event, {
|
|
241
|
+
origin: host.origin,
|
|
242
|
+
source: frame.contentWindow,
|
|
243
|
+
state,
|
|
244
|
+
});
|
|
245
|
+
if (!result) return;
|
|
246
|
+
if (!result.ok) {
|
|
247
|
+
finish({ ok: false, reason: result.errorCode || result.error });
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
finish({ ok: true, authCode: result.authCode, redirectTo, codeVerifier: verifier });
|
|
251
|
+
});
|
|
252
|
+
frame = host.createFrame(authorizeUrl);
|
|
253
|
+
});
|
|
254
|
+
}
|
|
@@ -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
|
+
}
|