@shellui/core 0.6.1 → 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.
Files changed (59) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -2
  3. package/schemas/shellui.config.schema.json +116 -72
  4. package/src/app.tsx +2 -0
  5. package/src/components/ContentView.tsx +2 -22
  6. package/src/components/iframeUrlSafety.spec.ts +67 -0
  7. package/src/components/iframeUrlSafety.ts +50 -0
  8. package/src/features/admin/AdminView.tsx +18 -4
  9. package/src/features/auth/AuthProvider.tsx +42 -2
  10. package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
  11. package/src/features/auth/appBackend/appBackendSessions.spec.ts +195 -0
  12. package/src/features/auth/appBackend/appBackendSessions.ts +292 -0
  13. package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
  14. package/src/features/auth/appBackend/frameAuth.ts +167 -0
  15. package/src/features/auth/appBackend/identity.spec.ts +201 -0
  16. package/src/features/auth/appBackend/identity.ts +173 -0
  17. package/src/features/auth/appBackend/silentSignIn.spec.ts +207 -0
  18. package/src/features/auth/appBackend/silentSignIn.ts +240 -0
  19. package/src/features/auth/backends/shellui.spec.ts +51 -19
  20. package/src/features/auth/backends/shellui.ts +20 -5
  21. package/src/features/auth/backends/types.ts +7 -2
  22. package/src/features/auth/components/LoginView.tsx +40 -18
  23. package/src/features/auth/components/OAuthCallbackView.tsx +29 -2
  24. package/src/features/auth/utils/authRequestError.ts +3 -0
  25. package/src/features/auth/utils/desktopSignIn.spec.ts +41 -0
  26. package/src/features/auth/utils/desktopSignIn.ts +38 -0
  27. package/src/features/auth/utils/index.ts +9 -0
  28. package/src/features/auth/utils/loginCancelTarget.spec.ts +73 -0
  29. package/src/features/auth/utils/loginCancelTarget.ts +45 -0
  30. package/src/features/auth/utils/loginPanelFrame.spec.ts +24 -0
  31. package/src/features/auth/utils/loginPanelFrame.ts +14 -0
  32. package/src/features/auth/utils/webPkce.spec.ts +96 -0
  33. package/src/features/auth/utils/webPkce.ts +152 -0
  34. package/src/features/chromeActions/ChromeActionsHost.tsx +7 -1
  35. package/src/features/chromeActions/computeActionInsets.ts +6 -0
  36. package/src/features/config/types.ts +41 -0
  37. package/src/features/layouts/appbar/AppBarLayout.tsx +39 -9
  38. package/src/features/layouts/chrome/ContentDragOverlay.tsx +14 -7
  39. package/src/features/layouts/chrome/DesktopChrome.tsx +3 -1
  40. package/src/features/layouts/floating/FloatingLayout.tsx +4 -1
  41. package/src/features/layouts/floating/FloatingSidebar.tsx +84 -28
  42. package/src/features/layouts/floating/computeFloatingInsets.spec.ts +19 -0
  43. package/src/features/layouts/floating/computeFloatingInsets.ts +40 -8
  44. package/src/features/layouts/floating/layoutChromeStore.ts +13 -0
  45. package/src/features/layouts/floating/useFloatingChrome.ts +11 -5
  46. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +3 -0
  47. package/src/features/layouts/sidebar/SidebarInner.tsx +5 -0
  48. package/src/features/layouts/sidebar/SidebarLayout.tsx +1 -0
  49. package/src/features/layouts/windows/WindowsLayout.tsx +106 -46
  50. package/src/features/security/trustedFrames.spec.ts +17 -1
  51. package/src/features/security/trustedFrames.ts +31 -9
  52. package/src/features/settings/SettingsProvider.tsx +48 -32
  53. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +374 -0
  54. package/src/features/settings/utils/buildSettingsForPropagation.ts +70 -35
  55. package/src/i18n/translations/en/common.json +2 -0
  56. package/src/i18n/translations/fr/common.json +2 -0
  57. package/src/index.css +16 -1
  58. package/src/index.ts +1 -0
  59. package/src/lib/z-index.ts +5 -0
@@ -0,0 +1,207 @@
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 PKCE, prompt=none, and code delivery without a shell token', () => {
14
+ const shellToken = 'shell-access-token.should.not.appear';
15
+ const url = new URL(
16
+ buildSilentAuthorizeUrl({
17
+ backendUrl: 'https://id.other.example/',
18
+ provider: 'google',
19
+ redirectTo:
20
+ 'https://shell.example/login/callback?shellui_silent=1&shellui_silent_state=abc',
21
+ codeChallenge: 'challenge-value',
22
+ companyId: 4,
23
+ }),
24
+ );
25
+ expect(`${url.origin}${url.pathname}`).toBe('https://id.other.example/api/v1/authorize');
26
+ expect(url.searchParams.get('prompt')).toBe('none');
27
+ expect(url.searchParams.get('token_delivery')).toBe('code');
28
+ expect(url.searchParams.get('code_challenge')).toBe('challenge-value');
29
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256');
30
+ expect(url.searchParams.get('provider')).toBe('google');
31
+ expect(url.searchParams.get('company_id')).toBe('4');
32
+ expect(url.searchParams.get('code_verifier')).toBeNull();
33
+ expect(url.searchParams.get('access_token')).toBeNull();
34
+ expect(url.toString()).not.toContain(shellToken);
35
+ });
36
+ });
37
+
38
+ describe('readSilentAuthMessage', () => {
39
+ const source = { id: 'frame' };
40
+ const expected = { origin: 'https://shell.example', source, state: 'state-1' };
41
+
42
+ it('accepts a matching code from the opened frame', () => {
43
+ expect(
44
+ readSilentAuthMessage(
45
+ {
46
+ origin: 'https://shell.example',
47
+ source,
48
+ data: { type: SILENT_AUTH_RESULT_TYPE, state: 'state-1', authCode: 'one-time' },
49
+ },
50
+ expected,
51
+ ),
52
+ ).toEqual({ ok: true, authCode: 'one-time' });
53
+ });
54
+
55
+ it('rejects a wildcard origin, a different source, and a different state', () => {
56
+ const data = { type: SILENT_AUTH_RESULT_TYPE, state: 'state-1', authCode: 'one-time' };
57
+ expect(
58
+ readSilentAuthMessage({ origin: '*', source, data }, { ...expected, origin: '*' }),
59
+ ).toBeNull();
60
+ expect(
61
+ readSilentAuthMessage({ origin: 'https://evil.example', source, data }, expected),
62
+ ).toBeNull();
63
+ expect(
64
+ readSilentAuthMessage(
65
+ { origin: 'https://shell.example', source: { id: 'other' }, data },
66
+ expected,
67
+ ),
68
+ ).toBeNull();
69
+ expect(
70
+ readSilentAuthMessage(
71
+ {
72
+ origin: 'https://shell.example',
73
+ source,
74
+ data: { type: SILENT_AUTH_RESULT_TYPE, state: 'other', authCode: 'one-time' },
75
+ },
76
+ expected,
77
+ ),
78
+ ).toBeNull();
79
+ });
80
+ });
81
+
82
+ describe('publishSilentAuthCallbackResult', () => {
83
+ it('posts to the same origin and never to *', () => {
84
+ const postMessage = vi.fn();
85
+ const parent = { location: { origin: 'https://shell.example' }, postMessage };
86
+ const win = {
87
+ parent,
88
+ location: {
89
+ origin: 'https://shell.example',
90
+ search: '?shellui_silent=1&shellui_silent_state=abc&shellui_auth_code=one-time',
91
+ },
92
+ } as unknown as Window;
93
+
94
+ expect(publishSilentAuthCallbackResult(win)).toBe(true);
95
+ expect(postMessage).toHaveBeenCalledTimes(1);
96
+ expect(postMessage.mock.calls[0][1]).toBe('https://shell.example');
97
+ expect(postMessage.mock.calls[0][1]).not.toBe('*');
98
+ expect(postMessage.mock.calls[0][0]).toMatchObject({
99
+ type: SILENT_AUTH_RESULT_TYPE,
100
+ state: 'abc',
101
+ authCode: 'one-time',
102
+ });
103
+ });
104
+
105
+ it('does not post the code to a cross-origin parent', () => {
106
+ const postMessage = vi.fn();
107
+ const parent = { postMessage };
108
+ Object.defineProperty(parent, 'location', {
109
+ get() {
110
+ throw new Error('cross-origin');
111
+ },
112
+ });
113
+ const win = {
114
+ parent,
115
+ location: {
116
+ origin: 'https://shell.example',
117
+ search: '?shellui_silent=1&shellui_silent_state=abc&shellui_auth_code=one-time',
118
+ },
119
+ } as unknown as Window;
120
+
121
+ expect(publishSilentAuthCallbackResult(win)).toBe(true);
122
+ expect(postMessage).not.toHaveBeenCalled();
123
+ });
124
+
125
+ it('ignores a top-level window', () => {
126
+ const win = {
127
+ location: {
128
+ origin: 'https://shell.example',
129
+ search: '?shellui_silent=1&shellui_silent_state=abc',
130
+ },
131
+ } as unknown as Window;
132
+ (win as { parent: Window }).parent = win;
133
+ expect(publishSilentAuthCallbackResult(win)).toBe(false);
134
+ });
135
+ });
136
+
137
+ describe('runSilentPkceSignIn', () => {
138
+ function host(): SilentAuthHost & {
139
+ frame: SilentAuthFrame;
140
+ src: () => string;
141
+ deliver: (event: { origin: string; source: unknown; data: unknown }) => void;
142
+ } {
143
+ const frame: SilentAuthFrame = { contentWindow: { id: 'frame' }, remove: vi.fn() };
144
+ let deliver = (_event: { origin: string; source: unknown; data: unknown }) => {};
145
+ let src = '';
146
+ return {
147
+ frame,
148
+ origin: 'https://shell.example',
149
+ callbackPath: '/login/callback',
150
+ timeoutMs: 50,
151
+ src: () => src,
152
+ deliver: (event) => deliver(event),
153
+ createFrame(next) {
154
+ src = next;
155
+ return frame;
156
+ },
157
+ listen(fn) {
158
+ deliver = fn;
159
+ return () => {};
160
+ },
161
+ };
162
+ }
163
+
164
+ it('returns the code and verifier for a matching frame message', async () => {
165
+ const silent = host();
166
+ const pending = runSilentPkceSignIn(
167
+ { backendUrl: 'https://id.other.example', provider: 'google', companyId: 4 },
168
+ silent,
169
+ );
170
+ await vi.waitUntil(() => silent.src() !== '');
171
+ const authorize = new URL(silent.src());
172
+ const redirect = new URL(authorize.searchParams.get('redirect_to') ?? '');
173
+ const state = redirect.searchParams.get('shellui_silent_state') ?? '';
174
+ expect(authorize.searchParams.get('prompt')).toBe('none');
175
+ expect(authorize.toString()).not.toContain('code_verifier');
176
+
177
+ silent.deliver({
178
+ origin: 'https://evil.example',
179
+ source: silent.frame.contentWindow,
180
+ data: { type: SILENT_AUTH_RESULT_TYPE, state, authCode: 'stolen' },
181
+ });
182
+ silent.deliver({
183
+ origin: 'https://shell.example',
184
+ source: silent.frame.contentWindow,
185
+ data: { type: SILENT_AUTH_RESULT_TYPE, state, authCode: 'one-time' },
186
+ });
187
+
188
+ const outcome = await pending;
189
+ expect(outcome.ok).toBe(true);
190
+ if (!outcome.ok) return;
191
+ expect(outcome.authCode).toBe('one-time');
192
+ expect(outcome.redirectTo).toBe(redirect.toString());
193
+ expect(outcome.codeVerifier).toMatch(/^[A-Za-z0-9\-._~]{43,128}$/);
194
+ expect(authorize.toString()).not.toContain(outcome.codeVerifier);
195
+ expect(silent.frame.remove).toHaveBeenCalled();
196
+ });
197
+
198
+ it('times out without a result', async () => {
199
+ const silent = host();
200
+ const outcome = await runSilentPkceSignIn(
201
+ { backendUrl: 'https://id.other.example', provider: 'google' },
202
+ silent,
203
+ );
204
+ expect(outcome).toEqual({ ok: false, reason: 'timeout' });
205
+ expect(silent.frame.remove).toHaveBeenCalled();
206
+ });
207
+ });
@@ -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
- getItem: (key: string) => storage.get(key) ?? null,
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
- expect(body).not.toHaveProperty('code_challenge');
55
- expect(body).not.toHaveProperty('code_challenge_method');
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('keeps the http redirect and does not send PKCE', () => {
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
- getItem: () => null,
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
- expect(url.searchParams.get('redirect_to')).toBe(
204
- 'https://app.example.com/login/callback?provider=github&company_oauth_client_id=4',
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.has('code_challenge')).toBe(false);
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 redirectTo = redirectToUrl.toString();
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
- options?.redirectTo ?? `${window.location.origin}${normalizeRedirectPath(redirectPath)}`;
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
- startOAuth: (provider: string, redirectPath: string, oauthClientId?: number) => void;
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>;