@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
@@ -1,4 +1,12 @@
1
- import { useCallback, useEffect, useMemo, useState, type FormEvent } from 'react';
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
- <div className="flex justify-end">
839
- <Button
840
- type="button"
841
- variant="link"
842
- size="sm"
843
- className="h-auto px-0 text-xs font-normal text-muted-foreground/80 hover:text-muted-foreground"
844
- onClick={() => {
845
- if (isIframeView) {
846
- shellui.closeModal();
847
- return;
848
- }
849
- navigate('/');
850
- }}
851
- >
852
- {t('loginPage.cancel')}
853
- </Button>
854
- </div>
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
 
@@ -159,4 +159,45 @@ describe('desktop sign-in', () => {
159
159
  expect(invoke).toHaveBeenCalledWith('plugin:deep-link|get_current');
160
160
  expect(events[0]).toMatchObject({ type: 'code', authCode: 'from-launch' });
161
161
  });
162
+
163
+ test('brings the window forward for each sign-in link, even a spent one', async () => {
164
+ const invoke = vi.fn(async (_cmd: string, _args?: Record<string, unknown>) => null);
165
+ vi.stubGlobal('window', {
166
+ __TAURI_INTERNALS__: { invoke, metadata: { currentWindow: { label: 'main' } } },
167
+ });
168
+ setActiveDesktopScheme(SCHEME);
169
+ await createAndStoreDesktopPkce(SCHEME);
170
+
171
+ const callback = 'shellui-playground://callback?shellui_auth_code=focus-code';
172
+ handleDesktopAuthCallback(callback);
173
+ handleDesktopAuthCallback(callback);
174
+ handleDesktopAuthCallback('other-app://callback?shellui_auth_code=focus-code');
175
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(6));
176
+
177
+ for (const cmd of [
178
+ 'plugin:window|unminimize',
179
+ 'plugin:window|show',
180
+ 'plugin:window|set_focus',
181
+ ]) {
182
+ expect(invoke.mock.calls.filter((call) => call[0] === cmd)).toEqual([
183
+ [cmd, { label: 'main' }],
184
+ [cmd, { label: 'main' }],
185
+ ]);
186
+ }
187
+ });
188
+
189
+ test('a login page in an iframe leaves deep links to the top-level shell', async () => {
190
+ const invoke = vi.fn(async () => ['shellui-playground://callback?shellui_auth_code=x']);
191
+ const parent = {};
192
+ vi.stubGlobal('window', {
193
+ parent,
194
+ __TAURI_INTERNALS__: { invoke, transformCallback: () => 9 },
195
+ });
196
+ setActiveDesktopScheme(SCHEME);
197
+ await createAndStoreDesktopPkce(SCHEME);
198
+
199
+ await ensureDesktopDeepLinkListener();
200
+
201
+ expect(invoke).not.toHaveBeenCalled();
202
+ });
162
203
  });
@@ -28,6 +28,8 @@ export type DesktopAuthOpenUrl = (url: string) => void | Promise<void>;
28
28
 
29
29
  export type DesktopAuthUrlListener = (urls: string[]) => void;
30
30
 
31
+ export type DesktopAuthFocusWindow = () => void | Promise<void>;
32
+
31
33
  /**
32
34
  * Subscribe to OS deep links. Wire `@tauri-apps/plugin-deep-link` `onOpenUrl`.
33
35
  * Return an unsubscribe function when the plugin provides one.
@@ -41,6 +43,8 @@ export interface DesktopAuthAdapters {
41
43
  openUrl: DesktopAuthOpenUrl;
42
44
  /** Optional. When omitted, the shell listens with Tauri's deep-link plugin IPC. */
43
45
  onOpenUrl?: DesktopAuthOnOpenUrl;
46
+ /** Optional. When omitted, the shell focuses its window with Tauri's window plugin IPC. */
47
+ focusWindow?: DesktopAuthFocusWindow;
44
48
  }
45
49
 
46
50
  export type DesktopAuthEvent =
@@ -51,6 +55,7 @@ type TauriInternals = {
51
55
  invoke: (cmd: string, args?: Record<string, unknown>) => Promise<unknown>;
52
56
  transformCallback?: (callback: (data: unknown) => void, once?: boolean) => number;
53
57
  unregisterCallback?: (id: number) => void;
58
+ metadata?: { currentWindow?: { label?: string } };
54
59
  };
55
60
 
56
61
  let adapters: DesktopAuthAdapters | null = null;
@@ -314,6 +319,27 @@ export async function beginDesktopOAuth(input: {
314
319
  }
315
320
  }
316
321
 
322
+ /**
323
+ * The browser stays in front after it hands over the deep link.
324
+ * Needs `core:window:allow-unminimize`, `allow-show`, and `allow-set-focus`.
325
+ */
326
+ async function focusDesktopWindow(): Promise<void> {
327
+ if (adapters?.focusWindow) {
328
+ await adapters.focusWindow();
329
+ return;
330
+ }
331
+ const internals = getTauriInternals();
332
+ if (!internals?.invoke) return;
333
+ const label = internals.metadata?.currentWindow?.label || 'main';
334
+ for (const cmd of ['plugin:window|unminimize', 'plugin:window|show', 'plugin:window|set_focus']) {
335
+ try {
336
+ await internals.invoke(cmd, { label });
337
+ } catch {
338
+ // A capability without this window permission leaves the window where it is.
339
+ }
340
+ }
341
+ }
342
+
317
343
  /**
318
344
  * Feed one deep-link URL, for example from `@tauri-apps/plugin-deep-link` `onOpenUrl`.
319
345
  * Codes, verifiers, and tokens are not logged.
@@ -323,6 +349,8 @@ export function handleDesktopAuthCallback(rawUrl: string): void {
323
349
  if (!scheme || typeof rawUrl !== 'string' || !rawUrl) return;
324
350
  const parsed = parseDesktopAuthCallback(rawUrl, scheme);
325
351
  if (!parsed) return;
352
+ // A second "Return to app" click repeats a spent code. It should still raise the window.
353
+ void focusDesktopWindow().catch(() => undefined);
326
354
 
327
355
  if (parsed.kind === 'error') {
328
356
  clearDesktopPkce();
@@ -371,9 +399,19 @@ async function readCurrentDeepLinks(): Promise<void> {
371
399
  }
372
400
  }
373
401
 
402
+ /**
403
+ * A login page in a modal or drawer iframe shares the verifier through `sessionStorage`.
404
+ * Only the top-level shell takes deep links, so the iframe cannot spend it.
405
+ */
406
+ function isEmbeddedFrame(): boolean {
407
+ if (typeof window === 'undefined') return false;
408
+ return Boolean(window.parent) && window.parent !== window;
409
+ }
410
+
374
411
  export function ensureDesktopDeepLinkListener(options?: {
375
412
  replayLaunchUrl?: boolean;
376
413
  }): Promise<void> {
414
+ if (isEmbeddedFrame()) return Promise.resolve();
377
415
  const replay = options?.replayLaunchUrl !== false;
378
416
  if (listenerPromise) {
379
417
  if (replay && !replayedLaunchUrl) {
@@ -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';
@@ -0,0 +1,73 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import type { NavigationItem } from '../../config/types';
3
+ import { getLoginCancelTarget, isPublicNavigationPage } from './loginCancelTarget';
4
+
5
+ const item = (path: string, extra: Partial<NavigationItem> = {}): NavigationItem => ({
6
+ label: path || 'Home',
7
+ path,
8
+ url: `/app/#/${path}`,
9
+ ...extra,
10
+ });
11
+
12
+ describe('getLoginCancelTarget', () => {
13
+ test('goes to / when the homepage is public', () => {
14
+ expect(getLoginCancelTarget({ navigation: [item(''), item('docs')] })).toBe('/');
15
+ });
16
+
17
+ test('goes to / when there is no root item (HomeView)', () => {
18
+ expect(getLoginCancelTarget({ navigation: [item('files', { requiresAuth: true })] })).toBe('/');
19
+ expect(getLoginCancelTarget({ navigation: [] })).toBe('/');
20
+ expect(getLoginCancelTarget(undefined)).toBe('/');
21
+ });
22
+
23
+ test('goes to the first public page when the homepage requires auth', () => {
24
+ const navigation = [
25
+ item('', { requiresAuth: true }),
26
+ { title: 'Group', items: [item('files', { requiresAuth: true }), item('docs')] },
27
+ ];
28
+ expect(getLoginCancelTarget({ navigation })).toBe('/docs');
29
+ });
30
+
31
+ test('returns null when every page requires auth', () => {
32
+ const navigation = [
33
+ item('', { requiresAuth: true }),
34
+ item('files', { requiresAuth: true }),
35
+ item('admin', { requiresStaff: true }),
36
+ item('private', { hideWhenLoggedOut: true }),
37
+ ];
38
+ expect(getLoginCancelTarget({ navigation })).toBeNull();
39
+ });
40
+
41
+ test('ignores settings, login, external, dev-mode and hidden entries', () => {
42
+ const navigation = [
43
+ item('', { requiresAuth: true }),
44
+ item('settings', { url: '/__settings', openIn: 'modal' }),
45
+ item('login', { url: '/login', openIn: 'modal' }),
46
+ item('login-page', { url: '/login' }),
47
+ item('website', { url: 'https://shellui.com/', openIn: 'external' }),
48
+ item('drawer', { openIn: 'drawer' }),
49
+ item('dev', { requiresDevMode: true }),
50
+ item('secret', { hidden: true }),
51
+ ];
52
+ expect(getLoginCancelTarget({ navigation })).toBeNull();
53
+ });
54
+
55
+ test('follows start_url', () => {
56
+ const navigation = [item('files', { requiresAuth: true }), item('docs')];
57
+ expect(getLoginCancelTarget({ navigation, start_url: '/docs' })).toBe('/');
58
+ expect(getLoginCancelTarget({ navigation, start_url: 'files' })).toBe('/docs');
59
+ expect(
60
+ getLoginCancelTarget({
61
+ navigation: [item('files', { requiresAuth: true })],
62
+ start_url: '/files',
63
+ }),
64
+ ).toBeNull();
65
+ });
66
+ });
67
+
68
+ describe('isPublicNavigationPage', () => {
69
+ test('plain page items are public', () => {
70
+ expect(isPublicNavigationPage(item('docs'))).toBe(true);
71
+ expect(isPublicNavigationPage(item('docs', { openIn: 'default' }))).toBe(true);
72
+ });
73
+ });
@@ -0,0 +1,45 @@
1
+ import type { NavigationGroup, NavigationItem } from '../../config/types';
2
+ import {
3
+ findMatchingNavigationItem,
4
+ flattenNavigationItems,
5
+ getNavPathPrefix,
6
+ isLoginNavigationUrl,
7
+ } from '../../layouts/utils';
8
+
9
+ type CancelTargetConfig = {
10
+ navigation?: (NavigationItem | NavigationGroup)[];
11
+ start_url?: string;
12
+ };
13
+
14
+ /** A nav item a signed-out user can open as a page in the main area. */
15
+ export function isPublicNavigationPage(item: NavigationItem): boolean {
16
+ if (item.requiresAuth || item.requiresStaff || item.hideWhenLoggedOut) return false;
17
+ if (item.requiresDevMode || item.hidden) return false;
18
+ if (item.openIn && item.openIn !== 'default') return false;
19
+ return !isLoginNavigationUrl(item.url);
20
+ }
21
+
22
+ /**
23
+ * Where the login page Cancel button should go, or `null` to hide it.
24
+ * Prefers `/` (or `start_url`) when public, else the first public nav page.
25
+ * `/` without a root item or `start_url` shows the built-in HomeView, which is public.
26
+ */
27
+ export function getLoginCancelTarget(config: CancelTargetConfig | undefined): string | null {
28
+ const items = flattenNavigationItems(config?.navigation ?? []);
29
+ const startUrl = config?.start_url?.trim();
30
+ const landing = startUrl ? (startUrl.startsWith('/') ? startUrl : `/${startUrl}`) : '/';
31
+ const landingPath = landing.split(/[?#]/)[0] || '/';
32
+
33
+ const landingItem = findMatchingNavigationItem(items, landingPath);
34
+ if (!landingItem) {
35
+ // No nav item owns the landing path: HomeView or a built-in shell route.
36
+ if (!startUrl || !isLoginNavigationUrl(landingPath)) return '/';
37
+ } else if (isPublicNavigationPage(landingItem)) {
38
+ return '/';
39
+ }
40
+
41
+ const fallback = items.find(
42
+ (item) => item !== landingItem && item.path !== '' && isPublicNavigationPage(item),
43
+ );
44
+ return fallback ? getNavPathPrefix(fallback) : null;
45
+ }
@@ -0,0 +1,24 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ const addIframe = vi.fn(() => 'frame-1');
4
+ const removeIframe = vi.fn();
5
+ vi.mock('@shellui/sdk', () => ({ addIframe, removeIframe }));
6
+
7
+ const { registerLoginPanelFrame } = await import('./loginPanelFrame');
8
+
9
+ describe('registerLoginPanelFrame', () => {
10
+ it('registers the panel iframe so settings reach it, and unregisters on cleanup', () => {
11
+ const node = {} as HTMLIFrameElement;
12
+ const cleanup = registerLoginPanelFrame(node);
13
+ expect(addIframe).toHaveBeenCalledWith(node);
14
+ expect(removeIframe).not.toHaveBeenCalled();
15
+ cleanup();
16
+ expect(removeIframe).toHaveBeenCalledWith('frame-1');
17
+ });
18
+
19
+ it('does nothing without a node', () => {
20
+ addIframe.mockClear();
21
+ registerLoginPanelFrame(null)();
22
+ expect(addIframe).not.toHaveBeenCalled();
23
+ });
24
+ });
@@ -0,0 +1,14 @@
1
+ import { addIframe, removeIframe } from '@shellui/sdk';
2
+
3
+ /**
4
+ * Register the login side panel iframe with the SDK frame registry so it receives
5
+ * SHELLUI_SETTINGS broadcasts (theme, language) like main content frames.
6
+ * Returns a cleanup that unregisters it.
7
+ */
8
+ export function registerLoginPanelFrame(node: HTMLIFrameElement | null): () => void {
9
+ if (!node) return () => {};
10
+ const iframeId = addIframe(node);
11
+ return () => {
12
+ removeIframe(iframeId);
13
+ };
14
+ }
@@ -0,0 +1,96 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { generateCodeChallenge } from './pkce';
3
+ import {
4
+ WEB_PKCE_FLOW_PARAM,
5
+ isMagicLinkFlowId,
6
+ isWebPkceErrorCode,
7
+ prepareWebPkce,
8
+ takeWebPkceVerifier,
9
+ } from './webPkce';
10
+
11
+ function memoryStorage(seed: [string, string][] = []): Storage {
12
+ const map = new Map<string, string>(seed);
13
+ return {
14
+ get length() {
15
+ return map.size;
16
+ },
17
+ key: (i: number) => Array.from(map.keys())[i] ?? null,
18
+ getItem: (k: string) => map.get(k) ?? null,
19
+ setItem: (k: string, v: string) => void map.set(k, String(v)),
20
+ removeItem: (k: string) => void map.delete(k),
21
+ clear: () => map.clear(),
22
+ };
23
+ }
24
+
25
+ function storedVerifier(store: Storage): string {
26
+ const keys = Array.from({ length: store.length }, (_, i) => store.key(i) as string);
27
+ const key = keys.find((k) => k.startsWith('shellui.auth.pkce.'));
28
+ expect(key).toBeTruthy();
29
+ return (JSON.parse(store.getItem(key as string) as string) as { verifier: string }).verifier;
30
+ }
31
+
32
+ describe('webPkce', () => {
33
+ beforeEach(() => {
34
+ vi.stubGlobal('sessionStorage', memoryStorage());
35
+ vi.stubGlobal('localStorage', memoryStorage());
36
+ });
37
+ afterEach(() => {
38
+ vi.useRealTimers();
39
+ vi.unstubAllGlobals();
40
+ });
41
+
42
+ it('adds only the flow id to redirect_to and keeps the verifier in sessionStorage', async () => {
43
+ const prepared = await prepareWebPkce(
44
+ 'https://app.test/login/callback?provider=google',
45
+ 'oauth',
46
+ );
47
+ const url = new URL(prepared.redirectTo);
48
+ expect(url.searchParams.get('provider')).toBe('google');
49
+ expect(url.searchParams.get(WEB_PKCE_FLOW_PARAM)).toBe(prepared.flowId);
50
+ const verifier = storedVerifier(sessionStorage);
51
+ expect(verifier).toMatch(/^[A-Za-z0-9_-]{43,128}$/);
52
+ expect(prepared.redirectTo).not.toContain(verifier);
53
+ expect(prepared.challenge).toBe(await generateCodeChallenge(verifier));
54
+ expect(localStorage.length).toBe(0);
55
+ });
56
+
57
+ it('keeps concurrent flows apart and is single use', async () => {
58
+ const a = await prepareWebPkce('https://app.test/cb', 'oauth');
59
+ const b = await prepareWebPkce('https://app.test/cb', 'oauth');
60
+ expect(a.flowId).not.toBe(b.flowId);
61
+ const va = takeWebPkceVerifier(a.flowId);
62
+ const vb = takeWebPkceVerifier(b.flowId);
63
+ expect(va).toBeTruthy();
64
+ expect(vb).toBeTruthy();
65
+ expect(va).not.toBe(vb);
66
+ expect(takeWebPkceVerifier(a.flowId)).toBeNull();
67
+ expect(sessionStorage.length).toBe(0);
68
+ });
69
+
70
+ it('stores a magic link verifier in localStorage only, readable from another tab', async () => {
71
+ const prepared = await prepareWebPkce('https://app.test/cb', 'magic_link');
72
+ expect(isMagicLinkFlowId(prepared.flowId)).toBe(true);
73
+ expect(sessionStorage.length).toBe(0);
74
+ sessionStorage.clear();
75
+ expect(takeWebPkceVerifier(prepared.flowId)).toMatch(/^[A-Za-z0-9_-]{43}$/);
76
+ expect(localStorage.length).toBe(0);
77
+ expect(takeWebPkceVerifier(prepared.flowId)).toBeNull();
78
+ });
79
+
80
+ it('expires a magic link verifier after 15 minutes', async () => {
81
+ vi.useFakeTimers();
82
+ const prepared = await prepareWebPkce('https://app.test/cb', 'magic_link');
83
+ vi.advanceTimersByTime(15 * 60 * 1000 + 1);
84
+ expect(takeWebPkceVerifier(prepared.flowId)).toBeNull();
85
+ expect(localStorage.length).toBe(0);
86
+ });
87
+
88
+ it('rejects malformed flow ids and knows the PKCE error codes', () => {
89
+ expect(takeWebPkceVerifier('../x')).toBeNull();
90
+ expect(takeWebPkceVerifier(null)).toBeNull();
91
+ expect(isMagicLinkFlowId(`o${'0'.repeat(32)}`)).toBe(false);
92
+ expect(isWebPkceErrorCode('pkce_verification_failed')).toBe(true);
93
+ expect(isWebPkceErrorCode('pkce_required')).toBe(true);
94
+ expect(isWebPkceErrorCode('other')).toBe(false);
95
+ });
96
+ });