@shellui/core 0.6.2 → 0.7.0-alpha.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.
- package/package.json +2 -2
- package/schemas/shellui.config.schema.json +116 -72
- package/src/app.tsx +2 -0
- package/src/components/ContentView.tsx +2 -22
- package/src/components/iframeUrlSafety.spec.ts +67 -0
- package/src/components/iframeUrlSafety.ts +50 -0
- package/src/features/auth/AuthProvider.tsx +24 -1
- package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
- package/src/features/auth/appBackend/appBackendSessions.spec.ts +195 -0
- package/src/features/auth/appBackend/appBackendSessions.ts +292 -0
- package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
- package/src/features/auth/appBackend/frameAuth.ts +167 -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 +207 -0
- package/src/features/auth/appBackend/silentSignIn.ts +240 -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 +29 -2
- package/src/features/auth/utils/authRequestError.ts +3 -0
- package/src/features/auth/utils/index.ts +9 -0
- 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/webPkce.spec.ts +96 -0
- package/src/features/auth/utils/webPkce.ts +152 -0
- package/src/features/config/types.ts +41 -0
- package/src/features/settings/SettingsProvider.tsx +45 -32
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +374 -0
- package/src/features/settings/utils/buildSettingsForPropagation.ts +61 -33
- package/src/i18n/translations/en/common.json +2 -0
- package/src/i18n/translations/fr/common.json +2 -0
- package/src/index.ts +1 -0
|
@@ -0,0 +1,240 @@
|
|
|
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
|
+
export function buildSilentAuthorizeUrl(input: {
|
|
96
|
+
backendUrl: string;
|
|
97
|
+
provider: string;
|
|
98
|
+
redirectTo: string;
|
|
99
|
+
codeChallenge: string;
|
|
100
|
+
companyId?: string | number;
|
|
101
|
+
clientTimezone?: string;
|
|
102
|
+
clientDeviceId?: string;
|
|
103
|
+
}): string {
|
|
104
|
+
const authorizeUrl = new URL(`${input.backendUrl.replace(/\/+$/, '')}/api/v1/authorize`);
|
|
105
|
+
authorizeUrl.searchParams.set('provider', input.provider);
|
|
106
|
+
authorizeUrl.searchParams.set('redirect_to', input.redirectTo);
|
|
107
|
+
authorizeUrl.searchParams.set('code_challenge', input.codeChallenge);
|
|
108
|
+
authorizeUrl.searchParams.set('code_challenge_method', PKCE_CHALLENGE_METHOD);
|
|
109
|
+
authorizeUrl.searchParams.set('prompt', 'none');
|
|
110
|
+
authorizeUrl.searchParams.set('token_delivery', 'code');
|
|
111
|
+
const companyId = getShellUILoginCompanyId(input.companyId);
|
|
112
|
+
if (companyId) authorizeUrl.searchParams.set('company_id', companyId);
|
|
113
|
+
if (input.clientTimezone) authorizeUrl.searchParams.set('client_timezone', input.clientTimezone);
|
|
114
|
+
if (input.clientDeviceId) authorizeUrl.searchParams.set('client_device_id', input.clientDeviceId);
|
|
115
|
+
return authorizeUrl.toString();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export type SilentSignInOutcome =
|
|
119
|
+
| { ok: true; authCode: string; redirectTo: string; codeVerifier: string }
|
|
120
|
+
| { ok: false; reason: string };
|
|
121
|
+
|
|
122
|
+
export type SilentAuthFrame = {
|
|
123
|
+
contentWindow: unknown;
|
|
124
|
+
remove: () => void;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
export type SilentAuthHost = {
|
|
128
|
+
origin: string;
|
|
129
|
+
callbackPath: string;
|
|
130
|
+
timeoutMs?: number;
|
|
131
|
+
createFrame: (src: string) => SilentAuthFrame;
|
|
132
|
+
listen: (fn: (event: { origin: string; source: unknown; data: unknown }) => void) => () => void;
|
|
133
|
+
clientTimezone?: string;
|
|
134
|
+
clientDeviceId?: string;
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
function browserSilentHost(): SilentAuthHost {
|
|
138
|
+
return {
|
|
139
|
+
origin: window.location.origin,
|
|
140
|
+
callbackPath: urls.loginCallback,
|
|
141
|
+
timeoutMs: DEFAULT_SILENT_TIMEOUT_MS,
|
|
142
|
+
clientTimezone: getShellUILoginClientTimezone() || undefined,
|
|
143
|
+
clientDeviceId: getShellUILoginDeviceId() || undefined,
|
|
144
|
+
listen(fn) {
|
|
145
|
+
const handler = (event: MessageEvent) => {
|
|
146
|
+
fn({ origin: event.origin, source: event.source, data: event.data });
|
|
147
|
+
};
|
|
148
|
+
window.addEventListener('message', handler);
|
|
149
|
+
return () => window.removeEventListener('message', handler);
|
|
150
|
+
},
|
|
151
|
+
createFrame(src) {
|
|
152
|
+
const iframe = document.createElement('iframe');
|
|
153
|
+
iframe.title = 'Identity sign-in';
|
|
154
|
+
iframe.setAttribute('aria-hidden', 'true');
|
|
155
|
+
iframe.tabIndex = -1;
|
|
156
|
+
iframe.style.cssText =
|
|
157
|
+
'position:fixed;width:0;height:0;border:0;opacity:0;pointer-events:none';
|
|
158
|
+
document.body.appendChild(iframe);
|
|
159
|
+
const handle = {
|
|
160
|
+
contentWindow: iframe.contentWindow,
|
|
161
|
+
remove() {
|
|
162
|
+
iframe.remove();
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
// Navigate after the caller stores this handle so a fast callback can be matched.
|
|
166
|
+
queueMicrotask(() => {
|
|
167
|
+
iframe.src = src;
|
|
168
|
+
});
|
|
169
|
+
return handle;
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* PKCE sign-in in a hidden frame. `prompt=none` asks the identity server not to
|
|
176
|
+
* show UI. The verifier stays in the shell. The frame only posts the one-time code.
|
|
177
|
+
*/
|
|
178
|
+
export async function runSilentPkceSignIn(
|
|
179
|
+
input: {
|
|
180
|
+
backendUrl: string;
|
|
181
|
+
provider: string;
|
|
182
|
+
companyId?: string | number;
|
|
183
|
+
},
|
|
184
|
+
host: SilentAuthHost = browserSilentHost(),
|
|
185
|
+
): Promise<SilentSignInOutcome> {
|
|
186
|
+
if (!host.origin || host.origin === '*' || host.origin === 'null') {
|
|
187
|
+
return { ok: false, reason: 'invalid_origin' };
|
|
188
|
+
}
|
|
189
|
+
const provider = input.provider.trim().toLowerCase();
|
|
190
|
+
if (!provider) return { ok: false, reason: 'missing_provider' };
|
|
191
|
+
|
|
192
|
+
const { verifier, challenge } = await createPkcePair();
|
|
193
|
+
const state =
|
|
194
|
+
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
|
195
|
+
? crypto.randomUUID()
|
|
196
|
+
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
197
|
+
const redirectTo = `${host.origin}${host.callbackPath}?${SILENT_AUTH_QUERY}=1&${SILENT_AUTH_STATE_QUERY}=${encodeURIComponent(state)}`;
|
|
198
|
+
const authorizeUrl = buildSilentAuthorizeUrl({
|
|
199
|
+
backendUrl: input.backendUrl,
|
|
200
|
+
provider,
|
|
201
|
+
redirectTo,
|
|
202
|
+
codeChallenge: challenge,
|
|
203
|
+
companyId: input.companyId,
|
|
204
|
+
clientTimezone: host.clientTimezone,
|
|
205
|
+
clientDeviceId: host.clientDeviceId,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
return new Promise((resolve) => {
|
|
209
|
+
let settled = false;
|
|
210
|
+
let frame: SilentAuthFrame | null = null;
|
|
211
|
+
let stop = () => {};
|
|
212
|
+
const finish = (outcome: SilentSignInOutcome) => {
|
|
213
|
+
if (settled) return;
|
|
214
|
+
settled = true;
|
|
215
|
+
clearTimeout(timer);
|
|
216
|
+
stop();
|
|
217
|
+
frame?.remove();
|
|
218
|
+
resolve(outcome);
|
|
219
|
+
};
|
|
220
|
+
const timer = setTimeout(
|
|
221
|
+
() => finish({ ok: false, reason: 'timeout' }),
|
|
222
|
+
host.timeoutMs ?? DEFAULT_SILENT_TIMEOUT_MS,
|
|
223
|
+
);
|
|
224
|
+
stop = host.listen((event) => {
|
|
225
|
+
if (!frame?.contentWindow) return;
|
|
226
|
+
const result = readSilentAuthMessage(event, {
|
|
227
|
+
origin: host.origin,
|
|
228
|
+
source: frame.contentWindow,
|
|
229
|
+
state,
|
|
230
|
+
});
|
|
231
|
+
if (!result) return;
|
|
232
|
+
if (!result.ok) {
|
|
233
|
+
finish({ ok: false, reason: result.errorCode || result.error });
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
finish({ ok: true, authCode: result.authCode, redirectTo, codeVerifier: verifier });
|
|
237
|
+
});
|
|
238
|
+
frame = host.createFrame(authorizeUrl);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
|
2
2
|
import type { AuthSession } from '../types';
|
|
3
3
|
import { AuthRequestError } from '../utils/authRequestError';
|
|
4
|
+
import { generateCodeChallenge } from '../utils/pkce';
|
|
5
|
+
import { WEB_PKCE_FLOW_PARAM, takeWebPkceVerifier } from '../utils/webPkce';
|
|
4
6
|
import { createShellUIAuthBackend } from './shellui';
|
|
5
7
|
|
|
6
8
|
vi.mock('../../config/useConfig', () => ({ useConfig: () => ({ config: {} }) }));
|
|
@@ -11,16 +13,27 @@ const jsonResponse = (status: number, body: unknown) =>
|
|
|
11
13
|
headers: { 'Content-Type': 'application/json' },
|
|
12
14
|
});
|
|
13
15
|
|
|
16
|
+
function memoryStorage(seed: [string, string][] = []): Storage {
|
|
17
|
+
const map = new Map<string, string>(seed);
|
|
18
|
+
return {
|
|
19
|
+
get length() {
|
|
20
|
+
return map.size;
|
|
21
|
+
},
|
|
22
|
+
key: (i: number) => Array.from(map.keys())[i] ?? null,
|
|
23
|
+
getItem: (k: string) => map.get(k) ?? null,
|
|
24
|
+
setItem: (k: string, v: string) => void map.set(k, String(v)),
|
|
25
|
+
removeItem: (k: string) => void map.delete(k),
|
|
26
|
+
clear: () => map.clear(),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
14
30
|
describe('shellui backend sendMagicLink', () => {
|
|
15
31
|
const fetchMock = vi.fn();
|
|
16
32
|
|
|
17
33
|
beforeEach(() => {
|
|
18
|
-
const storage = new Map<string, string>([['shellui_auth_client_device_id', 'device-1']]);
|
|
19
34
|
vi.stubGlobal('window', { location: { origin: 'https://app.example.com' } });
|
|
20
|
-
vi.stubGlobal('localStorage',
|
|
21
|
-
|
|
22
|
-
setItem: (key: string, value: string) => storage.set(key, value),
|
|
23
|
-
});
|
|
35
|
+
vi.stubGlobal('localStorage', memoryStorage([['shellui_auth_client_device_id', 'device-1']]));
|
|
36
|
+
vi.stubGlobal('sessionStorage', memoryStorage());
|
|
24
37
|
vi.stubGlobal('fetch', fetchMock);
|
|
25
38
|
});
|
|
26
39
|
|
|
@@ -46,13 +59,23 @@ describe('shellui backend sendMagicLink', () => {
|
|
|
46
59
|
expect(body).toMatchObject({
|
|
47
60
|
company_id: 7,
|
|
48
61
|
email: 'ada@acme.com',
|
|
49
|
-
redirect_to: 'https://app.example.com/login/callback?next=%2Fapps',
|
|
50
62
|
client_device_id: 'device-1',
|
|
63
|
+
code_challenge_method: 'S256',
|
|
51
64
|
});
|
|
65
|
+
const redirect = new URL(body.redirect_to as string);
|
|
66
|
+
expect(`${redirect.origin}${redirect.pathname}`).toBe('https://app.example.com/login/callback');
|
|
67
|
+
expect(redirect.searchParams.get('next')).toBe('/apps');
|
|
68
|
+
const flowId = redirect.searchParams.get(WEB_PKCE_FLOW_PARAM);
|
|
69
|
+
expect(flowId).toMatch(/^m[0-9a-f]{32}$/);
|
|
70
|
+
expect(body.code_challenge).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
71
|
+
expect(body).not.toHaveProperty('code_verifier');
|
|
52
72
|
expect(body).not.toHaveProperty('email_redirect_to');
|
|
53
73
|
expect(body).not.toHaveProperty('language');
|
|
54
|
-
|
|
55
|
-
|
|
74
|
+
// The verifier waits in localStorage for the tab the email link opens.
|
|
75
|
+
const verifier = takeWebPkceVerifier(flowId);
|
|
76
|
+
expect(verifier).toBeTruthy();
|
|
77
|
+
expect(body.redirect_to as string).not.toContain(verifier as string);
|
|
78
|
+
expect(body.code_challenge).toBe(await generateCodeChallenge(verifier as string));
|
|
56
79
|
});
|
|
57
80
|
|
|
58
81
|
test('desktop magic link sends the custom scheme and an S256 challenge', async () => {
|
|
@@ -152,6 +175,9 @@ describe('shellui backend OAuth session', () => {
|
|
|
152
175
|
auth_code: 'session-code',
|
|
153
176
|
redirect_to: 'https://app.example.com/login/callback',
|
|
154
177
|
});
|
|
178
|
+
// The browser sets Origin. The exchange is a plain cross-origin POST.
|
|
179
|
+
expect(init.credentials).toBeUndefined();
|
|
180
|
+
expect(Object.keys(init.headers as Record<string, string>)).not.toContain('Origin');
|
|
155
181
|
});
|
|
156
182
|
|
|
157
183
|
test('desktop exchange adds code_verifier and nothing else', async () => {
|
|
@@ -180,34 +206,40 @@ describe('shellui backend OAuth session', () => {
|
|
|
180
206
|
});
|
|
181
207
|
|
|
182
208
|
describe('shellui backend startOAuth', () => {
|
|
183
|
-
test('
|
|
209
|
+
test('sends an S256 challenge and keeps the verifier out of the URL', async () => {
|
|
184
210
|
const assign = vi.fn();
|
|
185
211
|
vi.stubGlobal('window', {
|
|
186
212
|
location: { origin: 'https://app.example.com', assign },
|
|
187
213
|
});
|
|
188
|
-
vi.stubGlobal('localStorage',
|
|
189
|
-
|
|
190
|
-
setItem: () => undefined,
|
|
191
|
-
});
|
|
214
|
+
vi.stubGlobal('localStorage', memoryStorage());
|
|
215
|
+
vi.stubGlobal('sessionStorage', memoryStorage());
|
|
192
216
|
const backend = createShellUIAuthBackend({
|
|
193
217
|
backendUrl: 'https://auth.example.com',
|
|
194
218
|
companyId: 7,
|
|
195
219
|
});
|
|
196
220
|
|
|
197
|
-
backend.startOAuth('github', '/login/callback', 4);
|
|
221
|
+
await backend.startOAuth('github', '/login/callback', 4);
|
|
198
222
|
|
|
199
223
|
expect(assign).toHaveBeenCalledTimes(1);
|
|
200
224
|
const url = new URL(String(assign.mock.calls[0]?.[0]));
|
|
201
225
|
expect(`${url.origin}${url.pathname}`).toBe('https://auth.example.com/api/v1/authorize');
|
|
202
226
|
expect(url.searchParams.get('provider')).toBe('github');
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
);
|
|
227
|
+
const redirect = new URL(url.searchParams.get('redirect_to') as string);
|
|
228
|
+
expect(redirect.searchParams.get('provider')).toBe('github');
|
|
229
|
+
expect(redirect.searchParams.get('company_oauth_client_id')).toBe('4');
|
|
230
|
+
const flowId = redirect.searchParams.get(WEB_PKCE_FLOW_PARAM);
|
|
231
|
+
expect(flowId).toMatch(/^o[0-9a-f]{32}$/);
|
|
206
232
|
expect(url.searchParams.get('company_id')).toBe('7');
|
|
207
233
|
expect(url.searchParams.get('company_oauth_client_id')).toBe('4');
|
|
208
|
-
expect(url.searchParams.
|
|
209
|
-
expect(url.searchParams.has('code_challenge_method')).toBe(false);
|
|
234
|
+
expect(url.searchParams.get('code_challenge_method')).toBe('S256');
|
|
210
235
|
expect(url.searchParams.has('code_verifier')).toBe(false);
|
|
236
|
+
expect(localStorage.getItem(`shellui.auth.pkce.magic.${flowId}`)).toBeNull();
|
|
237
|
+
const verifier = takeWebPkceVerifier(flowId);
|
|
238
|
+
expect(verifier).toBeTruthy();
|
|
239
|
+
expect(url.toString()).not.toContain(verifier as string);
|
|
240
|
+
expect(url.searchParams.get('code_challenge')).toBe(
|
|
241
|
+
await generateCodeChallenge(verifier as string),
|
|
242
|
+
);
|
|
211
243
|
vi.unstubAllGlobals();
|
|
212
244
|
});
|
|
213
245
|
});
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
normalizeRedirectPath,
|
|
9
9
|
} from '../utils';
|
|
10
10
|
import { AuthRequestError } from '../utils/authRequestError';
|
|
11
|
+
import { clearWebPkce, prepareWebPkce } from '../utils/webPkce';
|
|
11
12
|
import { getShellUILoginCompanyId } from '../utils/clientLoginContext';
|
|
12
13
|
import type { AuthSession, UserPreferences } from '../types';
|
|
13
14
|
import type { AuthBackend } from './types';
|
|
@@ -140,7 +141,7 @@ export const createShellUIAuthBackend = ({
|
|
|
140
141
|
if (!currentSession?.refreshToken) return null;
|
|
141
142
|
return refreshWithStoredToken(currentSession, nowSeconds);
|
|
142
143
|
},
|
|
143
|
-
startOAuth: (provider, redirectPath, oauthClientId) => {
|
|
144
|
+
startOAuth: async (provider, redirectPath, oauthClientId) => {
|
|
144
145
|
if (!backendUrl) {
|
|
145
146
|
throw new Error('Missing Shellui backend URL.');
|
|
146
147
|
}
|
|
@@ -158,10 +159,12 @@ export const createShellUIAuthBackend = ({
|
|
|
158
159
|
String(Math.trunc(oauthClientId)),
|
|
159
160
|
);
|
|
160
161
|
}
|
|
161
|
-
const
|
|
162
|
+
const pkce = await prepareWebPkce(redirectToUrl.toString(), 'oauth');
|
|
162
163
|
const authorizeUrl = new URL(`${backendUrl}/api/v1/authorize`);
|
|
163
164
|
authorizeUrl.searchParams.set('provider', provider);
|
|
164
|
-
authorizeUrl.searchParams.set('redirect_to', redirectTo);
|
|
165
|
+
authorizeUrl.searchParams.set('redirect_to', pkce.redirectTo);
|
|
166
|
+
authorizeUrl.searchParams.set('code_challenge', pkce.challenge);
|
|
167
|
+
authorizeUrl.searchParams.set('code_challenge_method', 'S256');
|
|
165
168
|
if (
|
|
166
169
|
typeof oauthClientId === 'number' &&
|
|
167
170
|
Number.isFinite(oauthClientId) &&
|
|
@@ -297,12 +300,23 @@ export const createShellUIAuthBackend = ({
|
|
|
297
300
|
if (!selectedCompanyId) {
|
|
298
301
|
throw new Error('Missing company_id for magic link request.');
|
|
299
302
|
}
|
|
303
|
+
// Desktop passes its own custom-scheme redirect and challenge. The web flow
|
|
304
|
+
// creates a magic link PKCE pair here.
|
|
305
|
+
const webPkce = options?.codeChallenge
|
|
306
|
+
? null
|
|
307
|
+
: await prepareWebPkce(
|
|
308
|
+
options?.redirectTo ??
|
|
309
|
+
`${window.location.origin}${normalizeRedirectPath(redirectPath)}`,
|
|
310
|
+
'magic_link',
|
|
311
|
+
);
|
|
300
312
|
const redirectTo =
|
|
301
|
-
|
|
313
|
+
webPkce?.redirectTo ??
|
|
314
|
+
options?.redirectTo ??
|
|
315
|
+
`${window.location.origin}${normalizeRedirectPath(redirectPath)}`;
|
|
302
316
|
const clientTz = getShellUILoginClientTimezone();
|
|
303
317
|
const clientDeviceId = getShellUILoginDeviceId();
|
|
304
318
|
const language = options?.language?.trim();
|
|
305
|
-
const codeChallenge = options?.codeChallenge?.trim();
|
|
319
|
+
const codeChallenge = webPkce?.challenge ?? options?.codeChallenge?.trim();
|
|
306
320
|
const response = await fetch(`${backendUrl}${MAGIC_LINK_REQUEST_ENDPOINT}`, {
|
|
307
321
|
method: 'POST',
|
|
308
322
|
headers: {
|
|
@@ -322,6 +336,7 @@ export const createShellUIAuthBackend = ({
|
|
|
322
336
|
}),
|
|
323
337
|
});
|
|
324
338
|
if (!response.ok) {
|
|
339
|
+
if (webPkce) clearWebPkce(webPkce.flowId);
|
|
325
340
|
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
|
326
341
|
const err = payload?.error ?? payload?.detail;
|
|
327
342
|
const message =
|
|
@@ -27,7 +27,12 @@ export interface AuthBackend {
|
|
|
27
27
|
session: AuthSession | null,
|
|
28
28
|
nowSeconds: number,
|
|
29
29
|
) => Promise<AuthSession | null>;
|
|
30
|
-
|
|
30
|
+
/** May resolve after creating the PKCE pair; then the page navigates away. */
|
|
31
|
+
startOAuth: (
|
|
32
|
+
provider: string,
|
|
33
|
+
redirectPath: string,
|
|
34
|
+
oauthClientId?: number,
|
|
35
|
+
) => void | Promise<void>;
|
|
31
36
|
startWeb3Ethereum: () => Promise<AuthSession | null>;
|
|
32
37
|
logout: (session: AuthSession | null) => Promise<void>;
|
|
33
38
|
/** Whether {@link deleteAccount} is implemented for this backend. */
|
|
@@ -49,7 +54,7 @@ export interface AuthBackend {
|
|
|
49
54
|
language?: string;
|
|
50
55
|
/** Custom-scheme redirect for desktop sign-in. Omit to keep the web origin. */
|
|
51
56
|
redirectTo?: string;
|
|
52
|
-
/** S256 challenge for a desktop magic link. Omit on the web flow. */
|
|
57
|
+
/** S256 challenge for a desktop magic link. Omit on the web flow, which creates its own. */
|
|
53
58
|
codeChallenge?: string;
|
|
54
59
|
},
|
|
55
60
|
) => Promise<void>;
|
|
@@ -1,4 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
useCallback,
|
|
3
|
+
useEffect,
|
|
4
|
+
useLayoutEffect,
|
|
5
|
+
useMemo,
|
|
6
|
+
useRef,
|
|
7
|
+
useState,
|
|
8
|
+
type FormEvent,
|
|
9
|
+
} from 'react';
|
|
2
10
|
import { useTranslation } from 'react-i18next';
|
|
3
11
|
import { useLocation, useNavigate } from 'react-router';
|
|
4
12
|
import { shellui } from '@shellui/sdk';
|
|
@@ -22,6 +30,7 @@ import {
|
|
|
22
30
|
normalizeNextPath,
|
|
23
31
|
redirectToCliCallback,
|
|
24
32
|
resolveLoginSettings,
|
|
33
|
+
getLoginCancelTarget,
|
|
25
34
|
} from '../utils';
|
|
26
35
|
import { AppBrandIcon } from '../../layouts/branding/AppBrandIcon';
|
|
27
36
|
import { DESKTOP_TITLEBAR_HEIGHT_PX } from '../../layouts/chrome/constants';
|
|
@@ -29,6 +38,7 @@ import { useMacTrafficLights } from '../../layouts/chrome/runtime';
|
|
|
29
38
|
import { validateLoginPanelUrl } from '../../security/urlAllowlist';
|
|
30
39
|
import { AccessPendingView } from './AccessPendingView';
|
|
31
40
|
import { LoginPreferencesControls } from './LoginPreferencesControls';
|
|
41
|
+
import { registerLoginPanelFrame } from '../utils/loginPanelFrame';
|
|
32
42
|
|
|
33
43
|
/** Shared top inset for login chrome when traffic lights are absent. */
|
|
34
44
|
const LOGIN_CHROME_PAD_Y = '2rem';
|
|
@@ -108,6 +118,8 @@ export const LoginView = () => {
|
|
|
108
118
|
sendMagicLink,
|
|
109
119
|
session,
|
|
110
120
|
} = useAuth();
|
|
121
|
+
// Cancel goes to a page reachable without signing in; hidden when there is none (#104).
|
|
122
|
+
const loginCancelTarget = useMemo(() => getLoginCancelTarget(config), [config]);
|
|
111
123
|
const configuredSettings = useMemo<AuthSettings>(
|
|
112
124
|
() => resolveLoginSettings(config.backend),
|
|
113
125
|
[config.backend],
|
|
@@ -487,6 +499,13 @@ export const LoginView = () => {
|
|
|
487
499
|
const panelImage = config.backend?.login?.panelImage?.trim() || null;
|
|
488
500
|
const hasCustomPanel = Boolean(panelUrl || panelImage);
|
|
489
501
|
const legalDocuments = useMemo(() => getLegalDocuments(config), [config]);
|
|
502
|
+
const panelIframeRef = useRef<HTMLIFrameElement>(null);
|
|
503
|
+
// Register the side panel frame so theme and language changes reach it live.
|
|
504
|
+
// Deps cover every state that can mount or unmount the iframe.
|
|
505
|
+
useLayoutEffect(
|
|
506
|
+
() => registerLoginPanelFrame(panelIframeRef.current),
|
|
507
|
+
[panelUrl, isIframeView, isAuthenticated, oauthBounceCode],
|
|
508
|
+
);
|
|
490
509
|
|
|
491
510
|
if (isAuthenticated) {
|
|
492
511
|
return null;
|
|
@@ -558,6 +577,7 @@ export const LoginView = () => {
|
|
|
558
577
|
>
|
|
559
578
|
{panelUrl ? (
|
|
560
579
|
<iframe
|
|
580
|
+
ref={panelIframeRef}
|
|
561
581
|
src={panelUrl}
|
|
562
582
|
title={t('loginPage.brandingIframeTitle')}
|
|
563
583
|
className="h-full w-full border-0"
|
|
@@ -835,23 +855,25 @@ export const LoginView = () => {
|
|
|
835
855
|
<p className="text-sm text-muted-foreground">{t('loginPage.noMethodsEnabled')}</p>
|
|
836
856
|
)}
|
|
837
857
|
|
|
838
|
-
|
|
839
|
-
<
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
858
|
+
{(isIframeView || loginCancelTarget) && (
|
|
859
|
+
<div className="flex justify-end">
|
|
860
|
+
<Button
|
|
861
|
+
type="button"
|
|
862
|
+
variant="link"
|
|
863
|
+
size="sm"
|
|
864
|
+
className="h-auto px-0 text-xs font-normal text-muted-foreground/80 hover:text-muted-foreground"
|
|
865
|
+
onClick={() => {
|
|
866
|
+
if (isIframeView) {
|
|
867
|
+
shellui.closeModal();
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
if (loginCancelTarget) navigate(loginCancelTarget);
|
|
871
|
+
}}
|
|
872
|
+
>
|
|
873
|
+
{t('loginPage.cancel')}
|
|
874
|
+
</Button>
|
|
875
|
+
</div>
|
|
876
|
+
)}
|
|
855
877
|
</div>
|
|
856
878
|
</div>
|
|
857
879
|
</div>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
1
|
+
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
2
2
|
import { useTranslation } from 'react-i18next';
|
|
3
3
|
import { useLocation, useNavigate } from 'react-router';
|
|
4
4
|
import urls from '../../../constants/urls';
|
|
@@ -15,6 +15,11 @@ import {
|
|
|
15
15
|
redirectCliCallbackError,
|
|
16
16
|
redirectToCliCallback,
|
|
17
17
|
} from '../utils';
|
|
18
|
+
import { WEB_PKCE_FLOW_PARAM, isMagicLinkFlowId, takeWebPkceVerifier } from '../utils/webPkce';
|
|
19
|
+
import {
|
|
20
|
+
isSilentAuthCallbackFrame,
|
|
21
|
+
publishSilentAuthCallbackResult,
|
|
22
|
+
} from '../appBackend/silentSignIn';
|
|
18
23
|
import { useAuth } from '../hooks/useAuth';
|
|
19
24
|
import { AccessPendingView } from './AccessPendingView';
|
|
20
25
|
|
|
@@ -112,13 +117,19 @@ export const OAuthCallbackView = () => {
|
|
|
112
117
|
captureCliCallbackFromSearch(location.search);
|
|
113
118
|
}, [location.search]);
|
|
114
119
|
|
|
120
|
+
useLayoutEffect(() => {
|
|
121
|
+
publishSilentAuthCallbackResult();
|
|
122
|
+
}, [location.search]);
|
|
123
|
+
|
|
115
124
|
useEffect(() => {
|
|
125
|
+
if (isSilentAuthCallbackFrame()) return;
|
|
116
126
|
if (!isAuthenticated || !session) return;
|
|
117
127
|
if (redirectToCliCallback(session)) return;
|
|
118
128
|
navigate(nextPath, { replace: true });
|
|
119
129
|
}, [isAuthenticated, navigate, nextPath, session]);
|
|
120
130
|
|
|
121
131
|
useEffect(() => {
|
|
132
|
+
if (isSilentAuthCallbackFrame()) return;
|
|
122
133
|
if (isAuthenticated) return;
|
|
123
134
|
// Identity bounce lands with tokens in the hash; AuthProvider restores the session.
|
|
124
135
|
// Stay on "Completing…" while hash is present or auth bootstrap is still running.
|
|
@@ -225,9 +236,25 @@ export const OAuthCallbackView = () => {
|
|
|
225
236
|
location.pathname,
|
|
226
237
|
location.search,
|
|
227
238
|
);
|
|
239
|
+
const pkceFlowId = params.get(WEB_PKCE_FLOW_PARAM);
|
|
240
|
+
const codeVerifier = takeWebPkceVerifier(pkceFlowId) ?? undefined;
|
|
241
|
+
if (!codeVerifier && isMagicLinkFlowId(pkceFlowId)) {
|
|
242
|
+
// The magic link verifier lives only in the browser that asked for the link.
|
|
243
|
+
// Do not send the code: it stays unused.
|
|
244
|
+
applyExchangeFailure(
|
|
245
|
+
authCode,
|
|
246
|
+
{
|
|
247
|
+
ok: false,
|
|
248
|
+
error: t('loginPage.magicLinkOtherBrowser'),
|
|
249
|
+
errorCode: 'magic_link_other_browser',
|
|
250
|
+
},
|
|
251
|
+
cancelled,
|
|
252
|
+
);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
228
255
|
let result: { ok: boolean; error?: string | null; errorCode?: string | null };
|
|
229
256
|
try {
|
|
230
|
-
result = await completeOAuthSessionCallback({ authCode, redirectTo });
|
|
257
|
+
result = await completeOAuthSessionCallback({ authCode, redirectTo, codeVerifier });
|
|
231
258
|
} catch (err) {
|
|
232
259
|
result = {
|
|
233
260
|
ok: false,
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isWebPkceErrorCode } from './webPkce';
|
|
2
|
+
|
|
1
3
|
export class AuthRequestError extends Error {
|
|
2
4
|
readonly code: string | null;
|
|
3
5
|
/** Extra fields from the error response body (e.g. `companies` for `last_company_owner`). */
|
|
@@ -19,6 +21,7 @@ export function isAccessPendingErrorCode(code: string | null | undefined): boole
|
|
|
19
21
|
/** i18n key when the shell replaces a backend sign-in sentence with its own copy. */
|
|
20
22
|
export function loginErrorMessageKey(code: string | null | undefined): string | null {
|
|
21
23
|
if (code === 'magic_link_staff_disabled') return 'loginPage.magicLinkStaffDisabled';
|
|
24
|
+
if (isWebPkceErrorCode(code)) return 'loginPage.pkceFailed';
|
|
22
25
|
return null;
|
|
23
26
|
}
|
|
24
27
|
|
|
@@ -4,6 +4,7 @@ export {
|
|
|
4
4
|
getShellUILoginDeviceId,
|
|
5
5
|
} from './clientLoginContext';
|
|
6
6
|
export { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
|
|
7
|
+
export { getLoginCancelTarget, isPublicNavigationPage } from './loginCancelTarget';
|
|
7
8
|
export { buildOAuthSessionRedirectTo } from './buildOAuthSessionRedirectTo';
|
|
8
9
|
export { buildSessionFromParams } from './buildSessionFromParams';
|
|
9
10
|
export {
|
|
@@ -55,3 +56,11 @@ export { normalizeRedirectPath } from './normalizeRedirectPath';
|
|
|
55
56
|
export { shareInFlight } from './shareInFlight';
|
|
56
57
|
export type { InFlightSlot } from './shareInFlight';
|
|
57
58
|
export { toAuthSessionFromSettingsUser } from './toAuthSessionFromSettingsUser';
|
|
59
|
+
export {
|
|
60
|
+
WEB_PKCE_FLOW_PARAM,
|
|
61
|
+
prepareWebPkce,
|
|
62
|
+
takeWebPkceVerifier,
|
|
63
|
+
clearWebPkce,
|
|
64
|
+
isWebPkceErrorCode,
|
|
65
|
+
isMagicLinkFlowId,
|
|
66
|
+
} from './webPkce';
|