@shellui/core 0.6.0 → 0.6.2
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/README.md +1 -1
- package/package.json +2 -2
- package/schemas/shellui.config.schema.json +15 -0
- package/src/features/admin/AdminView.tsx +18 -4
- package/src/features/auth/AuthProvider.tsx +184 -69
- package/src/features/auth/backends/shellui.spec.ts +115 -0
- package/src/features/auth/backends/shellui.ts +8 -2
- package/src/features/auth/backends/types.ts +9 -1
- package/src/features/auth/hooks/useAuth.tsx +1 -0
- package/src/features/auth/utils/accessTokenRefreshDue.spec.ts +15 -0
- package/src/features/auth/utils/accessTokenRefreshDue.ts +8 -0
- package/src/features/auth/utils/desktopAuthCallback.spec.ts +68 -0
- package/src/features/auth/utils/desktopAuthCallback.ts +126 -0
- package/src/features/auth/utils/desktopSignIn.spec.ts +203 -0
- package/src/features/auth/utils/desktopSignIn.ts +483 -0
- package/src/features/auth/utils/frameSessionRefresher.spec.ts +23 -0
- package/src/features/auth/utils/frameSessionRefresher.ts +21 -0
- package/src/features/auth/utils/pkce.spec.ts +36 -0
- package/src/features/auth/utils/pkce.ts +38 -0
- package/src/features/chromeActions/ChromeActionsHost.tsx +7 -1
- package/src/features/chromeActions/computeActionInsets.ts +6 -0
- package/src/features/config/types.ts +17 -0
- package/src/features/layouts/appbar/AppBarLayout.tsx +39 -9
- package/src/features/layouts/chrome/ContentDragOverlay.tsx +14 -7
- package/src/features/layouts/chrome/DesktopChrome.tsx +3 -1
- package/src/features/layouts/floating/FloatingLayout.tsx +4 -1
- package/src/features/layouts/floating/FloatingSidebar.tsx +84 -28
- package/src/features/layouts/floating/computeFloatingInsets.spec.ts +19 -0
- package/src/features/layouts/floating/computeFloatingInsets.ts +40 -8
- package/src/features/layouts/floating/layoutChromeStore.ts +13 -0
- package/src/features/layouts/floating/useFloatingChrome.ts +11 -5
- package/src/features/layouts/fullscreen/FullscreenLayout.tsx +3 -0
- package/src/features/layouts/sidebar/SidebarInner.tsx +5 -0
- package/src/features/layouts/sidebar/SidebarLayout.tsx +1 -0
- package/src/features/layouts/windows/WindowsLayout.tsx +106 -46
- package/src/features/security/trustedFrames.spec.ts +17 -1
- package/src/features/security/trustedFrames.ts +31 -9
- package/src/features/settings/SettingsProvider.tsx +86 -31
- package/src/features/settings/utils/buildSettingsForPropagation.ts +9 -2
- package/src/index.css +16 -1
- package/src/index.ts +6 -0
- package/src/lib/z-index.ts +5 -0
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ React runtime for the Shellui host. `@shellui/cli` depends on this package. Inst
|
|
|
6
6
|
npm install @shellui/core
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
Shellui **0.6.
|
|
9
|
+
Shellui **0.6.2** is the current stable release: `npm install @shellui/core@0.6.2`.
|
|
10
10
|
|
|
11
11
|
```typescript
|
|
12
12
|
import type { ShellUIConfig } from '@shellui/core';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shellui/core",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"description": "Shellui Core - Core React application runtime",
|
|
5
5
|
"main": "src/index.ts",
|
|
6
6
|
"type": "module",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"workbox-routing": "^7.4.0",
|
|
74
74
|
"workbox-strategies": "^7.4.0",
|
|
75
75
|
"workbox-window": "^7.4.0",
|
|
76
|
-
"@shellui/sdk": "0.6.
|
|
76
|
+
"@shellui/sdk": "0.6.2"
|
|
77
77
|
},
|
|
78
78
|
"peerDependencies": {
|
|
79
79
|
"react": "^18.0.0 || ^19.0.0",
|
|
@@ -119,6 +119,10 @@
|
|
|
119
119
|
"$ref": "#/definitions/BackendConfig",
|
|
120
120
|
"description": "Backend communication config. Defaults to undefined (no backend integration)."
|
|
121
121
|
},
|
|
122
|
+
"auth": {
|
|
123
|
+
"$ref": "#/definitions/AuthConfig",
|
|
124
|
+
"description": "Desktop sign-in scheme for a Tauri shell. See `auth.desktopScheme`. Browser shells ignore this block."
|
|
125
|
+
},
|
|
122
126
|
"security": {
|
|
123
127
|
"$ref": "#/definitions/SecurityConfig",
|
|
124
128
|
"description": "Host security (postMessage allowlist, BFF auth, CSP — see docs/features/security.md)."
|
|
@@ -892,6 +896,17 @@
|
|
|
892
896
|
"additionalProperties": false,
|
|
893
897
|
"description": "Sentry error reporting configuration. Only used in production; ignored in dev."
|
|
894
898
|
},
|
|
899
|
+
"AuthConfig": {
|
|
900
|
+
"type": "object",
|
|
901
|
+
"properties": {
|
|
902
|
+
"desktopScheme": {
|
|
903
|
+
"type": "string",
|
|
904
|
+
"description": "Custom URL scheme for Tauri sign-in, such as `shellui-playground`. Lowercase. Not `http`, `https`, or another browser scheme."
|
|
905
|
+
}
|
|
906
|
+
},
|
|
907
|
+
"additionalProperties": false,
|
|
908
|
+
"description": "Desktop (Tauri) sign-in. Ignored in the browser, so the web OAuth redirect stays as it is. The scheme must match the OAuth application's `desktop_redirect_scheme`."
|
|
909
|
+
},
|
|
895
910
|
"BackendConfig": {
|
|
896
911
|
"type": "object",
|
|
897
912
|
"properties": {
|
|
@@ -10,10 +10,13 @@ import { useConfig } from '../config/useConfig';
|
|
|
10
10
|
import type { NavigationItem } from '../config/types';
|
|
11
11
|
import { AppLayout } from '../layouts/AppLayout';
|
|
12
12
|
import {
|
|
13
|
+
MAC_TRAFFIC_LIGHTS_GAP_PX,
|
|
14
|
+
MAC_TRAFFIC_LIGHTS_WIDTH_PX,
|
|
13
15
|
isShellUiRootWindow,
|
|
14
16
|
SafeAreaTopbarOffset,
|
|
15
17
|
SafeAreaTopbarStrip,
|
|
16
|
-
|
|
18
|
+
useMacTrafficLights,
|
|
19
|
+
} from '../layouts/chrome';
|
|
17
20
|
import { AdminForbiddenAccess } from './components/AdminForbiddenAccess';
|
|
18
21
|
import { getAdminContentUrl, getAdminPath } from './config';
|
|
19
22
|
import { buildAdminIframeSrc } from './utils';
|
|
@@ -70,8 +73,12 @@ export const AdminView = () => {
|
|
|
70
73
|
}, [config?.title]);
|
|
71
74
|
|
|
72
75
|
const showSafeAreaTopbar = isShellUiRootWindow();
|
|
76
|
+
const trafficLights = useMacTrafficLights();
|
|
77
|
+
const chromeInset = trafficLights
|
|
78
|
+
? MAC_TRAFFIC_LIGHTS_WIDTH_PX + MAC_TRAFFIC_LIGHTS_GAP_PX
|
|
79
|
+
: undefined;
|
|
73
80
|
const headerStyle = {
|
|
74
|
-
paddingLeft: 'max(0.5rem, var(--shellui-safe-area-left))',
|
|
81
|
+
paddingLeft: chromeInset ?? 'max(0.5rem, var(--shellui-safe-area-left))',
|
|
75
82
|
paddingRight: 'max(0.75rem, var(--shellui-safe-area-right))',
|
|
76
83
|
...(isMobile && showSafeAreaTopbar
|
|
77
84
|
? {
|
|
@@ -90,13 +97,17 @@ export const AdminView = () => {
|
|
|
90
97
|
<SafeAreaTopbarOffset enabled={showSafeAreaTopbar} />
|
|
91
98
|
<SafeAreaTopbarStrip enabled={showSafeAreaTopbar} />
|
|
92
99
|
<header
|
|
93
|
-
className="flex shrink-0 items-center justify-between border-b bg-card"
|
|
100
|
+
className="relative z-[46] flex shrink-0 items-center justify-between border-b bg-card select-none"
|
|
94
101
|
style={headerStyle}
|
|
102
|
+
{...(trafficLights
|
|
103
|
+
? { 'data-shellui-drag-region': '', 'data-tauri-drag-region': '' }
|
|
104
|
+
: {})}
|
|
95
105
|
>
|
|
96
106
|
<Button
|
|
97
107
|
type="button"
|
|
98
108
|
variant="ghost"
|
|
99
109
|
size="sm"
|
|
110
|
+
data-shellui-no-drag=""
|
|
100
111
|
onClick={() => navigate('/')}
|
|
101
112
|
>
|
|
102
113
|
<svg
|
|
@@ -114,7 +125,10 @@ export const AdminView = () => {
|
|
|
114
125
|
</svg>
|
|
115
126
|
Back to home
|
|
116
127
|
</Button>
|
|
117
|
-
<div
|
|
128
|
+
<div
|
|
129
|
+
data-shellui-no-drag=""
|
|
130
|
+
className="flex items-center gap-2"
|
|
131
|
+
>
|
|
118
132
|
<LoginButton
|
|
119
133
|
variant="appbar"
|
|
120
134
|
logoutOnly
|
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
2
2
|
import { useTranslation } from 'react-i18next';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
bindVisibleResume,
|
|
5
|
+
getLogger,
|
|
6
|
+
postShellMessage,
|
|
7
|
+
shellui,
|
|
8
|
+
type Settings,
|
|
9
|
+
} from '@shellui/sdk';
|
|
4
10
|
import urls from '../../constants/urls';
|
|
5
11
|
import { useConfig } from '../config/useConfig';
|
|
12
|
+
import { useIsTauriRuntime } from '../layouts/chrome/runtime';
|
|
6
13
|
import { isShellSettingsFrameMessage } from '../security/trustedFrames';
|
|
7
14
|
import { createAuthBackend } from './backends';
|
|
8
15
|
import { AuthContext, type AuthContextValue, type OAuthCallbackResult } from './hooks/useAuth';
|
|
@@ -29,12 +36,24 @@ import {
|
|
|
29
36
|
type InFlightSlot,
|
|
30
37
|
} from './utils';
|
|
31
38
|
import { buildAuthUrlWithNext } from './utils/buildAuthUrlWithNext';
|
|
39
|
+
import {
|
|
40
|
+
beginDesktopOAuth,
|
|
41
|
+
clearDesktopPkce,
|
|
42
|
+
createAndStoreDesktopPkce,
|
|
43
|
+
desktopSignInBlockReason,
|
|
44
|
+
ensureDesktopDeepLinkListener,
|
|
45
|
+
isLiveTauriRuntime,
|
|
46
|
+
setActiveDesktopScheme,
|
|
47
|
+
shouldUseDesktopSignIn,
|
|
48
|
+
subscribeDesktopAuth,
|
|
49
|
+
} from './utils/desktopSignIn';
|
|
50
|
+
import { normalizeDesktopScheme } from './utils/desktopAuthCallback';
|
|
32
51
|
import type { DeleteAccountResultStatus, UpdateProfileResult } from './shellAccountRequests';
|
|
52
|
+
import { accessTokenRefreshDue } from './utils/accessTokenRefreshDue';
|
|
53
|
+
import { registerFrameSessionRefresher } from './utils/frameSessionRefresher';
|
|
33
54
|
|
|
34
55
|
const logger = getLogger('shellcore');
|
|
35
56
|
|
|
36
|
-
/** Refresh the access token this many seconds before `expiresAt` so API calls stay valid (JWT exp is absolute). */
|
|
37
|
-
const PROACTIVE_REFRESH_LEEWAY_SECONDS = 90;
|
|
38
57
|
/** Periodic check while the shell tab is open (also mitigates background-tab timer throttling). */
|
|
39
58
|
const TOKEN_REFRESH_TICK_MS = 45_000;
|
|
40
59
|
|
|
@@ -66,6 +85,7 @@ type LoginMessagePayload = {
|
|
|
66
85
|
export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
67
86
|
const { config } = useConfig();
|
|
68
87
|
const { i18n } = useTranslation();
|
|
88
|
+
const tauriRuntime = useIsTauriRuntime();
|
|
69
89
|
const bffAuthEnabled = isBffAuthEnabledFromConfig(config.security);
|
|
70
90
|
const backend = useMemo(
|
|
71
91
|
() => createAuthBackend(config.backend),
|
|
@@ -97,6 +117,60 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
97
117
|
[backend, bffAuthEnabled],
|
|
98
118
|
);
|
|
99
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Refresh when the access token is inside the leeway (or already expired) and
|
|
122
|
+
* return the token iframes should use. Concurrent callers share one request
|
|
123
|
+
* so a visibility resume and a SETTINGS_REQUESTED reply cannot rotate twice.
|
|
124
|
+
*/
|
|
125
|
+
const ensureFreshAccessToken = useCallback(async (): Promise<string | null> => {
|
|
126
|
+
const current = sessionRef.current;
|
|
127
|
+
if (!current?.accessToken) return null;
|
|
128
|
+
if (!bffAuthEnabled && !current.refreshToken) return current.accessToken;
|
|
129
|
+
|
|
130
|
+
const now = Math.floor(Date.now() / 1000);
|
|
131
|
+
if (!accessTokenRefreshDue(current.expiresAt, now)) return current.accessToken;
|
|
132
|
+
|
|
133
|
+
if (isTokenAutoRefreshDisabled()) {
|
|
134
|
+
if (!skippedRefreshLoggedRef.current) {
|
|
135
|
+
skippedRefreshLoggedRef.current = true;
|
|
136
|
+
logger.info('Skipped token refresh because Develop → Disable token auto-refresh is on', {
|
|
137
|
+
expiresAt: current.expiresAt,
|
|
138
|
+
secondsLeft: current.expiresAt - now,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return current.accessToken;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (refreshInFlightRef.current) return refreshInFlightRef.current;
|
|
145
|
+
|
|
146
|
+
const flight: { current: Promise<string | null> | null } = { current: null };
|
|
147
|
+
flight.current = (async () => {
|
|
148
|
+
try {
|
|
149
|
+
const next = await refreshAuthSession(current, now);
|
|
150
|
+
if (!next) return sessionRef.current?.accessToken ?? null;
|
|
151
|
+
persistAuthSession(next, { storeRefreshToken: !bffAuthEnabled });
|
|
152
|
+
sessionRef.current = next;
|
|
153
|
+
setSession(next);
|
|
154
|
+
return next.accessToken;
|
|
155
|
+
} catch (err) {
|
|
156
|
+
logger.error('Token refresh failed', { err });
|
|
157
|
+
const message = err instanceof Error ? err.message : '';
|
|
158
|
+
if (/\b401\b/.test(message)) {
|
|
159
|
+
clearStoredAuthSession();
|
|
160
|
+
sessionRef.current = null;
|
|
161
|
+
setSession(null);
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
return sessionRef.current?.accessToken ?? null;
|
|
165
|
+
} finally {
|
|
166
|
+
if (refreshInFlightRef.current === flight.current) refreshInFlightRef.current = null;
|
|
167
|
+
}
|
|
168
|
+
})();
|
|
169
|
+
|
|
170
|
+
refreshInFlightRef.current = flight.current;
|
|
171
|
+
return flight.current;
|
|
172
|
+
}, [bffAuthEnabled, refreshAuthSession]);
|
|
173
|
+
|
|
100
174
|
const [session, setSession] = useState<AuthSession | null>(null);
|
|
101
175
|
const [isLoading, setIsLoading] = useState(hasInitialSessionToResolve);
|
|
102
176
|
const [error, setError] = useState<string | null>(null);
|
|
@@ -104,7 +178,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
104
178
|
const [authEvent, setAuthEvent] = useState<AuthEvent>(null);
|
|
105
179
|
const sessionRef = useRef<AuthSession | null>(null);
|
|
106
180
|
sessionRef.current = session;
|
|
107
|
-
const refreshInFlightRef = useRef(
|
|
181
|
+
const refreshInFlightRef = useRef<Promise<string | null> | null>(null);
|
|
182
|
+
const skippedRefreshLoggedRef = useRef(false);
|
|
108
183
|
/** Bumps on every preferences sync so a slower older PUT can’t overwrite a newer theme. */
|
|
109
184
|
const preferencesSyncGenRef = useRef(0);
|
|
110
185
|
|
|
@@ -236,6 +311,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
236
311
|
};
|
|
237
312
|
}, [backend, bffAuthEnabled, commitAuthSession, refreshAuthSession]);
|
|
238
313
|
|
|
314
|
+
useEffect(() => {
|
|
315
|
+
if (typeof window === 'undefined' || window.parent !== window) return;
|
|
316
|
+
return registerFrameSessionRefresher(() => ensureFreshAccessToken());
|
|
317
|
+
}, [ensureFreshAccessToken]);
|
|
318
|
+
|
|
239
319
|
useEffect(() => {
|
|
240
320
|
if (typeof window === 'undefined' || window.parent !== window || isLoading) {
|
|
241
321
|
return;
|
|
@@ -244,75 +324,20 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
244
324
|
return;
|
|
245
325
|
}
|
|
246
326
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
const runRefresh = async () => {
|
|
251
|
-
if (cancelled) return;
|
|
252
|
-
const current = sessionRef.current;
|
|
253
|
-
if (!current || refreshInFlightRef.current) return;
|
|
254
|
-
if (!bffAuthEnabled && !current.refreshToken) return;
|
|
255
|
-
|
|
256
|
-
const now = Math.floor(Date.now() / 1000);
|
|
257
|
-
const secondsLeft = current.expiresAt - now;
|
|
258
|
-
if (secondsLeft > PROACTIVE_REFRESH_LEEWAY_SECONDS && !isSessionExpired(current)) {
|
|
259
|
-
return;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// Re-read when refresh is due so Develop → disableTokenAutoRefresh takes effect without remount.
|
|
263
|
-
if (isTokenAutoRefreshDisabled()) {
|
|
264
|
-
if (!skippedRefreshLogged) {
|
|
265
|
-
skippedRefreshLogged = true;
|
|
266
|
-
logger.info('Skipped token refresh because Develop → Disable token auto-refresh is on', {
|
|
267
|
-
expiresAt: current.expiresAt,
|
|
268
|
-
secondsLeft,
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
return;
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
refreshInFlightRef.current = true;
|
|
275
|
-
try {
|
|
276
|
-
const next = await refreshAuthSession(current, now);
|
|
277
|
-
if (cancelled || !next) return;
|
|
278
|
-
persistAuthSession(next, { storeRefreshToken: !bffAuthEnabled });
|
|
279
|
-
sessionRef.current = next;
|
|
280
|
-
setSession(next);
|
|
281
|
-
} catch (err) {
|
|
282
|
-
logger.error('Token refresh failed', { err });
|
|
283
|
-
const message = err instanceof Error ? err.message : '';
|
|
284
|
-
if (/\b401\b/.test(message)) {
|
|
285
|
-
clearStoredAuthSession();
|
|
286
|
-
sessionRef.current = null;
|
|
287
|
-
setSession(null);
|
|
288
|
-
}
|
|
289
|
-
} finally {
|
|
290
|
-
refreshInFlightRef.current = false;
|
|
291
|
-
}
|
|
292
|
-
};
|
|
293
|
-
|
|
294
|
-
const maybeRefreshFromTimer = () => {
|
|
295
|
-
void runRefresh();
|
|
296
|
-
};
|
|
297
|
-
|
|
298
|
-
const maybeRefreshOnResume = () => {
|
|
299
|
-
if (cancelled || document.visibilityState !== 'visible') return;
|
|
300
|
-
// Use the same proactive leeway as the timer (do not wait until already expired).
|
|
301
|
-
void runRefresh();
|
|
327
|
+
const maybeRefresh = () => {
|
|
328
|
+
void ensureFreshAccessToken();
|
|
302
329
|
};
|
|
303
330
|
|
|
304
|
-
|
|
305
|
-
const intervalId = window.setInterval(
|
|
306
|
-
|
|
307
|
-
|
|
331
|
+
maybeRefresh();
|
|
332
|
+
const intervalId = window.setInterval(maybeRefresh, TOKEN_REFRESH_TICK_MS);
|
|
333
|
+
// visibilitychange, focus, and pageshow. Background tabs throttle the interval.
|
|
334
|
+
const stopResume = bindVisibleResume(maybeRefresh);
|
|
308
335
|
|
|
309
336
|
return () => {
|
|
310
|
-
cancelled = true;
|
|
311
337
|
window.clearInterval(intervalId);
|
|
312
|
-
|
|
313
|
-
window.removeEventListener('focus', maybeRefreshOnResume);
|
|
338
|
+
stopResume();
|
|
314
339
|
};
|
|
315
|
-
}, [bffAuthEnabled,
|
|
340
|
+
}, [bffAuthEnabled, ensureFreshAccessToken, isLoading, session, session?.expiresAt]);
|
|
316
341
|
|
|
317
342
|
useEffect(() => {
|
|
318
343
|
if (typeof window === 'undefined' || window.parent === window) {
|
|
@@ -346,6 +371,26 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
346
371
|
try {
|
|
347
372
|
setError(null);
|
|
348
373
|
setErrorCode(null);
|
|
374
|
+
const liveTauri = tauriRuntime || isLiveTauriRuntime();
|
|
375
|
+
const blocked = desktopSignInBlockReason(config, liveTauri);
|
|
376
|
+
if (blocked) {
|
|
377
|
+
setError(blocked);
|
|
378
|
+
setErrorCode('invalid_desktop_scheme');
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
if (shouldUseDesktopSignIn(config, liveTauri)) {
|
|
382
|
+
void beginDesktopOAuth({
|
|
383
|
+
backendUrl: config.backend?.url ?? '',
|
|
384
|
+
companyId: config.backend?.companyId,
|
|
385
|
+
provider,
|
|
386
|
+
oauthClientId,
|
|
387
|
+
scheme: config.auth?.desktopScheme ?? '',
|
|
388
|
+
}).catch((err) => {
|
|
389
|
+
setError(err instanceof Error ? err.message : 'Unable to start desktop sign-in.');
|
|
390
|
+
setErrorCode(err instanceof AuthRequestError ? err.code : null);
|
|
391
|
+
});
|
|
392
|
+
return true;
|
|
393
|
+
}
|
|
349
394
|
backend.startOAuth(provider, redirectPath, oauthClientId);
|
|
350
395
|
return true;
|
|
351
396
|
} catch (err) {
|
|
@@ -354,7 +399,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
354
399
|
return false;
|
|
355
400
|
}
|
|
356
401
|
},
|
|
357
|
-
[backend],
|
|
402
|
+
[backend, config, tauriRuntime],
|
|
358
403
|
);
|
|
359
404
|
|
|
360
405
|
const persistOAuthSession = useCallback(
|
|
@@ -387,9 +432,11 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
387
432
|
async ({
|
|
388
433
|
authCode,
|
|
389
434
|
redirectTo,
|
|
435
|
+
codeVerifier,
|
|
390
436
|
}: {
|
|
391
437
|
authCode: string;
|
|
392
438
|
redirectTo: string;
|
|
439
|
+
codeVerifier?: string;
|
|
393
440
|
}): Promise<OAuthCallbackResult> => {
|
|
394
441
|
try {
|
|
395
442
|
setError(null);
|
|
@@ -398,6 +445,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
398
445
|
const nextSession = await backend.exchangeOAuthSessionCode({
|
|
399
446
|
authCode,
|
|
400
447
|
redirectTo,
|
|
448
|
+
codeVerifier,
|
|
401
449
|
nowSeconds: now,
|
|
402
450
|
});
|
|
403
451
|
if (!nextSession) {
|
|
@@ -478,7 +526,30 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
478
526
|
|
|
479
527
|
const sendMagicLink = useCallback(
|
|
480
528
|
async (email: string, redirectPath = urls.loginCallback) => {
|
|
529
|
+
const liveTauri = tauriRuntime || isLiveTauriRuntime();
|
|
481
530
|
try {
|
|
531
|
+
if (shouldUseDesktopSignIn(config, liveTauri)) {
|
|
532
|
+
const scheme = normalizeDesktopScheme(config.auth?.desktopScheme);
|
|
533
|
+
if (!scheme) {
|
|
534
|
+
throw new Error(
|
|
535
|
+
'auth.desktopScheme must be a lowercase custom scheme such as shellui-playground.',
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
setActiveDesktopScheme(scheme);
|
|
539
|
+
const prepared = await createAndStoreDesktopPkce(scheme);
|
|
540
|
+
try {
|
|
541
|
+
await backend.sendMagicLink(email, redirectPath, {
|
|
542
|
+
language: i18n.resolvedLanguage ?? i18n.language,
|
|
543
|
+
redirectTo: prepared.redirectTo,
|
|
544
|
+
codeChallenge: prepared.challenge,
|
|
545
|
+
});
|
|
546
|
+
} catch (sendError) {
|
|
547
|
+
clearDesktopPkce();
|
|
548
|
+
throw sendError;
|
|
549
|
+
}
|
|
550
|
+
void ensureDesktopDeepLinkListener({ replayLaunchUrl: false });
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
482
553
|
await backend.sendMagicLink(email, redirectPath, {
|
|
483
554
|
language: i18n.resolvedLanguage ?? i18n.language,
|
|
484
555
|
});
|
|
@@ -488,7 +559,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
488
559
|
throw new Error(message);
|
|
489
560
|
}
|
|
490
561
|
},
|
|
491
|
-
[backend, i18n],
|
|
562
|
+
[backend, config, i18n, tauriRuntime],
|
|
492
563
|
);
|
|
493
564
|
|
|
494
565
|
const syncUserPreferences = useCallback(
|
|
@@ -560,6 +631,50 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
|
|
560
631
|
setErrorCode(null);
|
|
561
632
|
}, [backend, bffAuthEnabled, session]);
|
|
562
633
|
|
|
634
|
+
useEffect(() => {
|
|
635
|
+
if (typeof window === 'undefined' || window.parent !== window) return;
|
|
636
|
+
const liveTauri = tauriRuntime || isLiveTauriRuntime();
|
|
637
|
+
if (!shouldUseDesktopSignIn(config, liveTauri)) return;
|
|
638
|
+
const scheme = normalizeDesktopScheme(config.auth?.desktopScheme);
|
|
639
|
+
if (!scheme) return;
|
|
640
|
+
setActiveDesktopScheme(scheme);
|
|
641
|
+
let cancelled = false;
|
|
642
|
+
|
|
643
|
+
// The login page may sit in a modal or drawer iframe that cannot see this result.
|
|
644
|
+
const finishOverlayLogin = (failure: string | null) => {
|
|
645
|
+
postShellMessage({ type: 'SHELLUI_CLOSE_MODAL', payload: {} });
|
|
646
|
+
postShellMessage({ type: 'SHELLUI_CLOSE_DRAWER', payload: {} });
|
|
647
|
+
if (failure === null || window.location.pathname === urls.login) return;
|
|
648
|
+
shellui.toast({
|
|
649
|
+
type: 'error',
|
|
650
|
+
title: i18n.getFixedT(null, 'common')('loginPage.signInCouldNotContinue'),
|
|
651
|
+
description: failure || undefined,
|
|
652
|
+
});
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
const unsubscribe = subscribeDesktopAuth((event) => {
|
|
656
|
+
if (cancelled) return;
|
|
657
|
+
if (event.type === 'error') {
|
|
658
|
+
setError(event.message);
|
|
659
|
+
setErrorCode(event.errorCode);
|
|
660
|
+
finishOverlayLogin(event.message);
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
void completeOAuthSessionCallback({
|
|
664
|
+
authCode: event.authCode,
|
|
665
|
+
redirectTo: event.redirectTo,
|
|
666
|
+
codeVerifier: event.codeVerifier,
|
|
667
|
+
}).then((result) => {
|
|
668
|
+
if (!cancelled) finishOverlayLogin(result.ok ? null : (result.error ?? ''));
|
|
669
|
+
});
|
|
670
|
+
});
|
|
671
|
+
void ensureDesktopDeepLinkListener({ replayLaunchUrl: true });
|
|
672
|
+
return () => {
|
|
673
|
+
cancelled = true;
|
|
674
|
+
unsubscribe();
|
|
675
|
+
};
|
|
676
|
+
}, [completeOAuthSessionCallback, config, i18n, tauriRuntime]);
|
|
677
|
+
|
|
563
678
|
useEffect(() => {
|
|
564
679
|
if (typeof window === 'undefined' || window.parent !== window) {
|
|
565
680
|
return;
|
|
@@ -51,6 +51,28 @@ describe('shellui backend sendMagicLink', () => {
|
|
|
51
51
|
});
|
|
52
52
|
expect(body).not.toHaveProperty('email_redirect_to');
|
|
53
53
|
expect(body).not.toHaveProperty('language');
|
|
54
|
+
expect(body).not.toHaveProperty('code_challenge');
|
|
55
|
+
expect(body).not.toHaveProperty('code_challenge_method');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test('desktop magic link sends the custom scheme and an S256 challenge', async () => {
|
|
59
|
+
fetchMock.mockResolvedValue(jsonResponse(200, { ok: true }));
|
|
60
|
+
const backend = createShellUIAuthBackend({
|
|
61
|
+
backendUrl: 'https://auth.example.com',
|
|
62
|
+
companyId: 7,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
await backend.sendMagicLink('ada@acme.com', '/login/callback', {
|
|
66
|
+
redirectTo: 'shellui-playground://callback',
|
|
67
|
+
codeChallenge: 'a'.repeat(43),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
71
|
+
const body = JSON.parse(init.body as string) as Record<string, unknown>;
|
|
72
|
+
expect(body.redirect_to).toBe('shellui-playground://callback');
|
|
73
|
+
expect(body.code_challenge).toBe('a'.repeat(43));
|
|
74
|
+
expect(body.code_challenge_method).toBe('S256');
|
|
75
|
+
expect(body).not.toHaveProperty('code_verifier');
|
|
54
76
|
});
|
|
55
77
|
|
|
56
78
|
test('sends the UI language so the email is localized', async () => {
|
|
@@ -97,6 +119,99 @@ describe('shellui backend sendMagicLink', () => {
|
|
|
97
119
|
});
|
|
98
120
|
});
|
|
99
121
|
|
|
122
|
+
describe('shellui backend OAuth session', () => {
|
|
123
|
+
const fetchMock = vi.fn();
|
|
124
|
+
|
|
125
|
+
beforeEach(() => {
|
|
126
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
afterEach(() => {
|
|
130
|
+
fetchMock.mockReset();
|
|
131
|
+
vi.unstubAllGlobals();
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test('web exchange posts auth_code and redirect_to only', async () => {
|
|
135
|
+
fetchMock.mockResolvedValue(
|
|
136
|
+
jsonResponse(200, {
|
|
137
|
+
access_token: 'header.payload.sig',
|
|
138
|
+
refresh_token: 'refresh-1',
|
|
139
|
+
expires_in: 3600,
|
|
140
|
+
token_type: 'bearer',
|
|
141
|
+
}),
|
|
142
|
+
);
|
|
143
|
+
const backend = createShellUIAuthBackend({ backendUrl: 'https://auth.example.com' });
|
|
144
|
+
await backend.exchangeOAuthSessionCode({
|
|
145
|
+
authCode: 'session-code',
|
|
146
|
+
redirectTo: 'https://app.example.com/login/callback',
|
|
147
|
+
nowSeconds: 1_700_000_000,
|
|
148
|
+
});
|
|
149
|
+
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
150
|
+
expect(url).toBe('https://auth.example.com/api/v1/oauth/session');
|
|
151
|
+
expect(JSON.parse(init.body as string)).toEqual({
|
|
152
|
+
auth_code: 'session-code',
|
|
153
|
+
redirect_to: 'https://app.example.com/login/callback',
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test('desktop exchange adds code_verifier and nothing else', async () => {
|
|
158
|
+
fetchMock.mockResolvedValue(
|
|
159
|
+
jsonResponse(200, {
|
|
160
|
+
access_token: 'header.payload.sig',
|
|
161
|
+
refresh_token: 'refresh-1',
|
|
162
|
+
expires_in: 3600,
|
|
163
|
+
token_type: 'bearer',
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
const backend = createShellUIAuthBackend({ backendUrl: 'https://auth.example.com' });
|
|
167
|
+
await backend.exchangeOAuthSessionCode({
|
|
168
|
+
authCode: 'session-code',
|
|
169
|
+
redirectTo: 'shellui-playground://callback',
|
|
170
|
+
codeVerifier: 'verifier-value',
|
|
171
|
+
nowSeconds: 1_700_000_000,
|
|
172
|
+
});
|
|
173
|
+
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
|
174
|
+
expect(JSON.parse(init.body as string)).toEqual({
|
|
175
|
+
auth_code: 'session-code',
|
|
176
|
+
redirect_to: 'shellui-playground://callback',
|
|
177
|
+
code_verifier: 'verifier-value',
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
describe('shellui backend startOAuth', () => {
|
|
183
|
+
test('keeps the http redirect and does not send PKCE', () => {
|
|
184
|
+
const assign = vi.fn();
|
|
185
|
+
vi.stubGlobal('window', {
|
|
186
|
+
location: { origin: 'https://app.example.com', assign },
|
|
187
|
+
});
|
|
188
|
+
vi.stubGlobal('localStorage', {
|
|
189
|
+
getItem: () => null,
|
|
190
|
+
setItem: () => undefined,
|
|
191
|
+
});
|
|
192
|
+
const backend = createShellUIAuthBackend({
|
|
193
|
+
backendUrl: 'https://auth.example.com',
|
|
194
|
+
companyId: 7,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
backend.startOAuth('github', '/login/callback', 4);
|
|
198
|
+
|
|
199
|
+
expect(assign).toHaveBeenCalledTimes(1);
|
|
200
|
+
const url = new URL(String(assign.mock.calls[0]?.[0]));
|
|
201
|
+
expect(`${url.origin}${url.pathname}`).toBe('https://auth.example.com/api/v1/authorize');
|
|
202
|
+
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
|
+
);
|
|
206
|
+
expect(url.searchParams.get('company_id')).toBe('7');
|
|
207
|
+
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);
|
|
210
|
+
expect(url.searchParams.has('code_verifier')).toBe(false);
|
|
211
|
+
vi.unstubAllGlobals();
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
|
|
100
215
|
describe('shellui backend updateProfile', () => {
|
|
101
216
|
const fetchMock = vi.fn();
|
|
102
217
|
const session = { accessToken: 'access-1' } as AuthSession;
|
|
@@ -72,7 +72,7 @@ export const createShellUIAuthBackend = ({
|
|
|
72
72
|
const hashParams = new URLSearchParams(locationHash.replace(/^#/, ''));
|
|
73
73
|
return buildSessionFromParams(hashParams, nowSeconds);
|
|
74
74
|
},
|
|
75
|
-
exchangeOAuthSessionCode: async ({ authCode, redirectTo, nowSeconds }) => {
|
|
75
|
+
exchangeOAuthSessionCode: async ({ authCode, redirectTo, codeVerifier, nowSeconds }) => {
|
|
76
76
|
if (!backendUrl) {
|
|
77
77
|
throw new Error('Missing Shellui backend URL.');
|
|
78
78
|
}
|
|
@@ -85,6 +85,7 @@ export const createShellUIAuthBackend = ({
|
|
|
85
85
|
body: JSON.stringify({
|
|
86
86
|
auth_code: authCode,
|
|
87
87
|
redirect_to: redirectTo,
|
|
88
|
+
...(codeVerifier ? { code_verifier: codeVerifier } : {}),
|
|
88
89
|
}),
|
|
89
90
|
});
|
|
90
91
|
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
|
@@ -296,10 +297,12 @@ export const createShellUIAuthBackend = ({
|
|
|
296
297
|
if (!selectedCompanyId) {
|
|
297
298
|
throw new Error('Missing company_id for magic link request.');
|
|
298
299
|
}
|
|
299
|
-
const redirectTo =
|
|
300
|
+
const redirectTo =
|
|
301
|
+
options?.redirectTo ?? `${window.location.origin}${normalizeRedirectPath(redirectPath)}`;
|
|
300
302
|
const clientTz = getShellUILoginClientTimezone();
|
|
301
303
|
const clientDeviceId = getShellUILoginDeviceId();
|
|
302
304
|
const language = options?.language?.trim();
|
|
305
|
+
const codeChallenge = options?.codeChallenge?.trim();
|
|
303
306
|
const response = await fetch(`${backendUrl}${MAGIC_LINK_REQUEST_ENDPOINT}`, {
|
|
304
307
|
method: 'POST',
|
|
305
308
|
headers: {
|
|
@@ -310,6 +313,9 @@ export const createShellUIAuthBackend = ({
|
|
|
310
313
|
company_id: Number(selectedCompanyId),
|
|
311
314
|
email,
|
|
312
315
|
redirect_to: redirectTo,
|
|
316
|
+
...(codeChallenge
|
|
317
|
+
? { code_challenge: codeChallenge, code_challenge_method: 'S256' }
|
|
318
|
+
: {}),
|
|
313
319
|
...(clientTz ? { client_timezone: clientTz } : {}),
|
|
314
320
|
...(clientDeviceId ? { client_device_id: clientDeviceId } : {}),
|
|
315
321
|
...(language ? { language } : {}),
|
|
@@ -7,6 +7,8 @@ export interface AuthBackend {
|
|
|
7
7
|
exchangeOAuthSessionCode: (params: {
|
|
8
8
|
authCode: string;
|
|
9
9
|
redirectTo: string;
|
|
10
|
+
/** PKCE verifier for a custom-scheme desktop redirect. Omit on the web flow. */
|
|
11
|
+
codeVerifier?: string;
|
|
10
12
|
nowSeconds: number;
|
|
11
13
|
}) => Promise<AuthSession | null>;
|
|
12
14
|
exchangeOAuthCode: (params: {
|
|
@@ -43,7 +45,13 @@ export interface AuthBackend {
|
|
|
43
45
|
sendMagicLink: (
|
|
44
46
|
email: string,
|
|
45
47
|
redirectPath: string,
|
|
46
|
-
options?: {
|
|
48
|
+
options?: {
|
|
49
|
+
language?: string;
|
|
50
|
+
/** Custom-scheme redirect for desktop sign-in. Omit to keep the web origin. */
|
|
51
|
+
redirectTo?: string;
|
|
52
|
+
/** S256 challenge for a desktop magic link. Omit on the web flow. */
|
|
53
|
+
codeChallenge?: string;
|
|
54
|
+
},
|
|
47
55
|
) => Promise<void>;
|
|
48
56
|
syncUserPreferences: (session: AuthSession | null, preferences: UserPreferences) => Promise<void>;
|
|
49
57
|
loadUserPreferences: (session: AuthSession | null) => Promise<UserPreferences | null>;
|