@shellui/core 0.6.2 → 0.7.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +147 -70
  3. package/src/app.tsx +2 -0
  4. package/src/components/ContentView.tsx +21 -30
  5. package/src/components/iframeUrlSafety.spec.ts +67 -0
  6. package/src/components/iframeUrlSafety.ts +50 -0
  7. package/src/components/ui/sidebar.tsx +11 -5
  8. package/src/features/admin/AdminView.tsx +9 -6
  9. package/src/features/auth/AuthProvider.tsx +49 -5
  10. package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
  11. package/src/features/auth/appBackend/appBackendSessions.spec.ts +329 -0
  12. package/src/features/auth/appBackend/appBackendSessions.ts +443 -0
  13. package/src/features/auth/appBackend/childFrames.spec.ts +328 -0
  14. package/src/features/auth/appBackend/childFrames.ts +180 -0
  15. package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
  16. package/src/features/auth/appBackend/frameAuth.ts +204 -0
  17. package/src/features/auth/appBackend/identity.spec.ts +201 -0
  18. package/src/features/auth/appBackend/identity.ts +173 -0
  19. package/src/features/auth/appBackend/silentSignIn.spec.ts +225 -0
  20. package/src/features/auth/appBackend/silentSignIn.ts +254 -0
  21. package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
  22. package/src/features/auth/appBackend/tokenExchange.ts +76 -0
  23. package/src/features/auth/backends/shellui.spec.ts +51 -19
  24. package/src/features/auth/backends/shellui.ts +20 -5
  25. package/src/features/auth/backends/types.ts +7 -2
  26. package/src/features/auth/components/LoginView.tsx +40 -18
  27. package/src/features/auth/components/OAuthCallbackView.tsx +33 -4
  28. package/src/features/auth/utils/authRequestError.ts +3 -0
  29. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
  30. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
  31. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +29 -0
  32. package/src/features/auth/utils/canRestoreStoredSession.ts +12 -0
  33. package/src/features/auth/utils/index.ts +16 -1
  34. package/src/features/auth/utils/loginCancelTarget.spec.ts +73 -0
  35. package/src/features/auth/utils/loginCancelTarget.ts +45 -0
  36. package/src/features/auth/utils/loginPanelFrame.spec.ts +24 -0
  37. package/src/features/auth/utils/loginPanelFrame.ts +14 -0
  38. package/src/features/auth/utils/resolveSdkLoginRedirectPath.spec.ts +41 -0
  39. package/src/features/auth/utils/resolveSdkLoginRedirectPath.ts +31 -0
  40. package/src/features/auth/utils/webPkce.spec.ts +119 -0
  41. package/src/features/auth/utils/webPkce.ts +169 -0
  42. package/src/features/chromeActions/computeActionInsets.ts +7 -4
  43. package/src/features/config/types.ts +70 -3
  44. package/src/features/layouts/appbar/AppBarLayout.tsx +63 -30
  45. package/src/features/layouts/chrome/CollapsedDesktopTitlebar.tsx +12 -23
  46. package/src/features/layouts/chrome/ContentDragOverlay.tsx +5 -6
  47. package/src/features/layouts/chrome/DesktopChrome.tsx +37 -0
  48. package/src/features/layouts/chrome/DesktopHistoryButtons.tsx +15 -4
  49. package/src/features/layouts/chrome/MacStrip.tsx +33 -0
  50. package/src/features/layouts/chrome/constants.ts +33 -8
  51. package/src/features/layouts/chrome/index.ts +8 -0
  52. package/src/features/layouts/chrome/stripDragMap.ts +35 -0
  53. package/src/features/layouts/chrome/stripNoDrag.spec.tsx +103 -0
  54. package/src/features/layouts/chrome/useScrollHideChrome.ts +3 -8
  55. package/src/features/layouts/filterNavigationForAuthState.spec.ts +5 -3
  56. package/src/features/layouts/floating/FloatingBottomDock.tsx +199 -20
  57. package/src/features/layouts/floating/FloatingLayout.tsx +13 -8
  58. package/src/features/layouts/floating/FloatingSidebar.tsx +144 -70
  59. package/src/features/layouts/floating/computeFloatingInsets.ts +22 -4
  60. package/src/features/layouts/floating/useFloatingChrome.ts +3 -1
  61. package/src/features/layouts/floating/useSoftKeyboard.spec.ts +39 -0
  62. package/src/features/layouts/floating/useSoftKeyboard.ts +82 -0
  63. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +38 -10
  64. package/src/features/layouts/sidebar/NavigationContent.tsx +14 -6
  65. package/src/features/layouts/sidebar/SidebarIcons.tsx +3 -9
  66. package/src/features/layouts/sidebar/SidebarInner.tsx +50 -39
  67. package/src/features/layouts/sidebar/SidebarLayout.tsx +8 -11
  68. package/src/features/layouts/utils.ts +4 -3
  69. package/src/features/layouts/windows/DesktopDots.tsx +76 -0
  70. package/src/features/layouts/windows/WindowsLayout.tsx +184 -125
  71. package/src/features/layouts/windows/deskDots.spec.ts +52 -0
  72. package/src/features/layouts/windows/deskDots.ts +314 -0
  73. package/src/features/settings/SettingsProvider.tsx +198 -29
  74. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +379 -4
  75. package/src/features/settings/utils/buildSettingsForPropagation.ts +65 -39
  76. package/src/features/theme/applyTheme.ts +8 -0
  77. package/src/features/theme/navContrast.spec.ts +49 -0
  78. package/src/features/theme/navContrast.ts +108 -0
  79. package/src/features/transfers/transferQueue.spec.ts +6 -2
  80. package/src/i18n/translations/en/common.json +27 -0
  81. package/src/i18n/translations/fr/common.json +27 -0
  82. package/src/index.css +935 -46
  83. package/src/index.ts +2 -0
  84. package/src/routes/hooks/useNavigationItems.ts +14 -3
  85. package/src/routes/hooks/withShellSearch.spec.ts +13 -0
@@ -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,41 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import urls from '../../../constants/urls';
3
+ import { resolveSdkLoginRedirectPath } from './resolveSdkLoginRedirectPath';
4
+
5
+ describe('resolveSdkLoginRedirectPath', () => {
6
+ it('returns to the callback with the current page as next', () => {
7
+ expect(resolveSdkLoginRedirectPath(undefined, '/account')).toBe(
8
+ `${urls.loginCallback}?next=%2Faccount`,
9
+ );
10
+ expect(resolveSdkLoginRedirectPath('', '/files?tab=shared')).toBe(
11
+ `${urls.loginCallback}?next=%2Ffiles%3Ftab%3Dshared`,
12
+ );
13
+ });
14
+
15
+ it('uses redirectPath as the page after sign-in', () => {
16
+ expect(resolveSdkLoginRedirectPath('/dashboard', '/account')).toBe(
17
+ `${urls.loginCallback}?next=%2Fdashboard`,
18
+ );
19
+ });
20
+
21
+ it('keeps an explicit callback path', () => {
22
+ const callback = `${urls.loginCallback}?next=%2Fapps`;
23
+ expect(resolveSdkLoginRedirectPath(callback, '/account')).toBe(callback);
24
+ expect(resolveSdkLoginRedirectPath(urls.loginCallback, '/account')).toBe(urls.loginCallback);
25
+ });
26
+
27
+ it('falls back to the current page when redirectPath is the login page', () => {
28
+ expect(resolveSdkLoginRedirectPath(urls.login, '/account')).toBe(
29
+ `${urls.loginCallback}?next=%2Faccount`,
30
+ );
31
+ });
32
+
33
+ it('never sends people back to login or to another origin', () => {
34
+ expect(resolveSdkLoginRedirectPath(undefined, urls.login)).toBe(urls.loginCallback);
35
+ expect(resolveSdkLoginRedirectPath(undefined, '/')).toBe(urls.loginCallback);
36
+ expect(resolveSdkLoginRedirectPath('//evil.example.com', '/account')).toBe(
37
+ `${urls.loginCallback}?next=%2Faccount`,
38
+ );
39
+ expect(resolveSdkLoginRedirectPath('https://evil.example.com', '/')).toBe(urls.loginCallback);
40
+ });
41
+ });
@@ -0,0 +1,31 @@
1
+ import urls from '../../../constants/urls';
2
+ import { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
3
+ import { normalizeNextPath } from './normalizeNextPath';
4
+
5
+ const isCallbackPath = (value: string) =>
6
+ value === urls.loginCallback || value.startsWith(`${urls.loginCallback}?`);
7
+
8
+ const pageAfterSignIn = (value: string | null | undefined): string | null => {
9
+ const next = normalizeNextPath(value?.trim() || null);
10
+ return next && !isCallbackPath(next) ? next : null;
11
+ };
12
+
13
+ /**
14
+ * Pick the `redirect_to` path for a `SHELLUI_LOGIN` request from an app.
15
+ *
16
+ * Only the callback route exchanges the OAuth code, so the request always
17
+ * returns there. `redirectPath` names the page to open after sign-in. With no
18
+ * usable `redirectPath`, people come back to the page they started from.
19
+ * An explicit callback path is kept as is.
20
+ */
21
+ export const resolveSdkLoginRedirectPath = (
22
+ redirectPath: string | null | undefined,
23
+ currentPath: string,
24
+ ): string => {
25
+ const requested = redirectPath?.trim();
26
+ if (requested && isCallbackPath(requested)) {
27
+ return requested;
28
+ }
29
+ const next = pageAfterSignIn(requested) ?? pageAfterSignIn(currentPath);
30
+ return buildAuthUrlWithNext(urls.loginCallback, next);
31
+ };
@@ -0,0 +1,119 @@
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
+ takeWebPkceFlow,
9
+ takeWebPkceVerifier,
10
+ } from './webPkce';
11
+
12
+ function memoryStorage(seed: [string, string][] = []): Storage {
13
+ const map = new Map<string, string>(seed);
14
+ return {
15
+ get length() {
16
+ return map.size;
17
+ },
18
+ key: (i: number) => Array.from(map.keys())[i] ?? null,
19
+ getItem: (k: string) => map.get(k) ?? null,
20
+ setItem: (k: string, v: string) => void map.set(k, String(v)),
21
+ removeItem: (k: string) => void map.delete(k),
22
+ clear: () => map.clear(),
23
+ };
24
+ }
25
+
26
+ function storedVerifier(store: Storage): string {
27
+ const keys = Array.from({ length: store.length }, (_, i) => store.key(i) as string);
28
+ const key = keys.find((k) => k.startsWith('shellui.auth.pkce.'));
29
+ expect(key).toBeTruthy();
30
+ return (JSON.parse(store.getItem(key as string) as string) as { verifier: string }).verifier;
31
+ }
32
+
33
+ describe('webPkce', () => {
34
+ beforeEach(() => {
35
+ vi.stubGlobal('sessionStorage', memoryStorage());
36
+ vi.stubGlobal('localStorage', memoryStorage());
37
+ });
38
+ afterEach(() => {
39
+ vi.useRealTimers();
40
+ vi.unstubAllGlobals();
41
+ });
42
+
43
+ it('adds only the flow id to redirect_to and keeps the verifier in sessionStorage', async () => {
44
+ const prepared = await prepareWebPkce(
45
+ 'https://app.test/login/callback?provider=google',
46
+ 'oauth',
47
+ );
48
+ const url = new URL(prepared.redirectTo);
49
+ expect(url.searchParams.get('provider')).toBe('google');
50
+ expect(url.searchParams.get(WEB_PKCE_FLOW_PARAM)).toBe(prepared.flowId);
51
+ const verifier = storedVerifier(sessionStorage);
52
+ expect(verifier).toMatch(/^[A-Za-z0-9_-]{43,128}$/);
53
+ expect(prepared.redirectTo).not.toContain(verifier);
54
+ expect(prepared.challenge).toBe(await generateCodeChallenge(verifier));
55
+ expect(localStorage.length).toBe(0);
56
+ });
57
+
58
+ it('keeps concurrent flows apart and is single use', async () => {
59
+ const a = await prepareWebPkce('https://app.test/cb', 'oauth');
60
+ const b = await prepareWebPkce('https://app.test/cb', 'oauth');
61
+ expect(a.flowId).not.toBe(b.flowId);
62
+ const va = takeWebPkceVerifier(a.flowId);
63
+ const vb = takeWebPkceVerifier(b.flowId);
64
+ expect(va).toBeTruthy();
65
+ expect(vb).toBeTruthy();
66
+ expect(va).not.toBe(vb);
67
+ expect(takeWebPkceVerifier(a.flowId)).toBeNull();
68
+ expect(sessionStorage.length).toBe(0);
69
+ });
70
+
71
+ it('stores a magic link verifier in localStorage only, readable from another tab', async () => {
72
+ const prepared = await prepareWebPkce('https://app.test/cb', 'magic_link');
73
+ expect(isMagicLinkFlowId(prepared.flowId)).toBe(true);
74
+ expect(sessionStorage.length).toBe(0);
75
+ sessionStorage.clear();
76
+ expect(takeWebPkceVerifier(prepared.flowId)).toMatch(/^[A-Za-z0-9_-]{43}$/);
77
+ expect(localStorage.length).toBe(0);
78
+ expect(takeWebPkceVerifier(prepared.flowId)).toBeNull();
79
+ });
80
+
81
+ it('expires a magic link verifier after 15 minutes', async () => {
82
+ vi.useFakeTimers();
83
+ const prepared = await prepareWebPkce('https://app.test/cb', 'magic_link');
84
+ vi.advanceTimersByTime(15 * 60 * 1000 + 1);
85
+ expect(takeWebPkceVerifier(prepared.flowId)).toBeNull();
86
+ expect(localStorage.length).toBe(0);
87
+ });
88
+
89
+ it('rejects malformed flow ids and knows the PKCE error codes', () => {
90
+ expect(takeWebPkceVerifier('../x')).toBeNull();
91
+ expect(takeWebPkceVerifier(null)).toBeNull();
92
+ expect(isMagicLinkFlowId(`o${'0'.repeat(32)}`)).toBe(false);
93
+ expect(isWebPkceErrorCode('pkce_verification_failed')).toBe(true);
94
+ expect(isWebPkceErrorCode('pkce_required')).toBe(true);
95
+ expect(isWebPkceErrorCode('other')).toBe(false);
96
+ });
97
+
98
+ it('returns the exact start redirect_to with the verifier, single use', async () => {
99
+ for (const kind of ['oauth', 'magic_link'] as const) {
100
+ const prepared = await prepareWebPkce(
101
+ 'https://app.test/login/callback?provider=github',
102
+ kind,
103
+ );
104
+ const taken = takeWebPkceFlow(prepared.flowId);
105
+ expect(taken?.redirectTo).toBe(prepared.redirectTo);
106
+ expect(taken?.verifier).toMatch(/^[A-Za-z0-9_-]{43,128}$/);
107
+ expect(takeWebPkceFlow(prepared.flowId)).toBeNull();
108
+ }
109
+ });
110
+
111
+ it('returns a null redirect_to for an entry stored without one', () => {
112
+ const id = `o${'0'.repeat(32)}`;
113
+ sessionStorage.setItem(
114
+ `shellui.auth.pkce.${id}`,
115
+ JSON.stringify({ verifier: 'v'.repeat(43), createdAt: Date.now() }),
116
+ );
117
+ expect(takeWebPkceFlow(id)).toEqual({ verifier: 'v'.repeat(43), redirectTo: null });
118
+ });
119
+ });
@@ -0,0 +1,169 @@
1
+ import { createPkcePair } from './pkce';
2
+
3
+ /**
4
+ * S256 PKCE for web sign-in (identity-service 0.9.0 and later).
5
+ *
6
+ * Each flow gets a random id. Only the id goes on `redirect_to` as
7
+ * `shellui_pkce_flow`, so the callback can find its own verifier and two
8
+ * sign-ins started in parallel do not overwrite each other. The verifier is
9
+ * never put in a URL.
10
+ *
11
+ * OAuth and SAML keep the verifier in `sessionStorage`: the callback lands in
12
+ * the tab that started the flow. A magic link opens from the email, often in a
13
+ * new tab with an empty `sessionStorage`, so that flow alone keeps the
14
+ * verifier in `localStorage`, keyed by the flow id, for 15 minutes. It is
15
+ * single use and removed on read, so the link only works in the browser that
16
+ * requested it.
17
+ */
18
+
19
+ export const WEB_PKCE_FLOW_PARAM = 'shellui_pkce_flow';
20
+ const SESSION_PREFIX = 'shellui.auth.pkce.';
21
+ const MAGIC_LINK_PREFIX = 'shellui.auth.pkce.magic.';
22
+ /** A magic link only works for 15 minutes in the browser that requested it. */
23
+ const MAGIC_LINK_MAX_AGE_MS = 15 * 60 * 1000;
24
+ const OAUTH_MAX_AGE_MS = 30 * 60 * 1000;
25
+ /** Magic link flow ids start with `m`, OAuth and SAML ids with `o`. */
26
+ const MAGIC_LINK_FLOW_MARK = 'm';
27
+ const FLOW_ID_PATTERN = /^[mo][0-9a-f]{32}$/;
28
+
29
+ export type WebPkceFlowKind = 'oauth' | 'magic_link';
30
+
31
+ interface StoredVerifier {
32
+ verifier: string;
33
+ createdAt: number;
34
+ /** Exact `redirect_to` sent at sign-in start. The exchange must send it back unchanged. */
35
+ redirectTo?: string;
36
+ }
37
+
38
+ export interface TakenWebPkceFlow {
39
+ verifier: string;
40
+ /** Exact `redirect_to` from sign-in start, or null when an older entry has none. */
41
+ redirectTo: string | null;
42
+ }
43
+
44
+ export interface PreparedWebPkce {
45
+ flowId: string;
46
+ challenge: string;
47
+ /** `redirectTo` with the flow id added. */
48
+ redirectTo: string;
49
+ }
50
+
51
+ function store(kind: 'session' | 'local'): Storage | null {
52
+ try {
53
+ const s = kind === 'session' ? globalThis.sessionStorage : globalThis.localStorage;
54
+ return s ?? null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ function randomFlowId(kind: WebPkceFlowKind): string {
61
+ const bytes = new Uint8Array(16);
62
+ crypto.getRandomValues(bytes);
63
+ const mark = kind === 'magic_link' ? MAGIC_LINK_FLOW_MARK : 'o';
64
+ return mark + Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
65
+ }
66
+
67
+ function write(s: Storage | null, key: string, value: StoredVerifier): boolean {
68
+ if (!s) return false;
69
+ try {
70
+ s.setItem(key, JSON.stringify(value));
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ function readAndRemove(s: Storage | null, key: string, maxAgeMs: number): TakenWebPkceFlow | null {
78
+ if (!s) return null;
79
+ try {
80
+ const raw = s.getItem(key);
81
+ if (!raw) return null;
82
+ s.removeItem(key);
83
+ const parsed = JSON.parse(raw) as StoredVerifier;
84
+ if (typeof parsed?.verifier !== 'string' || typeof parsed.createdAt !== 'number') return null;
85
+ if (Date.now() - parsed.createdAt > maxAgeMs) return null;
86
+ const redirectTo = typeof parsed.redirectTo === 'string' ? parsed.redirectTo : null;
87
+ return { verifier: parsed.verifier, redirectTo };
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+
93
+ /** Drop expired magic link verifiers left by flows that were never finished. */
94
+ function pruneMagicLinkVerifiers(): void {
95
+ const s = store('local');
96
+ if (!s) return;
97
+ try {
98
+ for (let i = s.length - 1; i >= 0; i -= 1) {
99
+ const key = s.key(i);
100
+ if (!key?.startsWith(MAGIC_LINK_PREFIX)) continue;
101
+ try {
102
+ const parsed = JSON.parse(s.getItem(key) ?? '') as StoredVerifier;
103
+ if (Date.now() - parsed.createdAt <= MAGIC_LINK_MAX_AGE_MS) continue;
104
+ } catch {
105
+ // unreadable: remove
106
+ }
107
+ s.removeItem(key);
108
+ }
109
+ } catch {
110
+ // ignore
111
+ }
112
+ }
113
+
114
+ export async function prepareWebPkce(
115
+ redirectTo: string,
116
+ kind: WebPkceFlowKind,
117
+ ): Promise<PreparedWebPkce> {
118
+ const { verifier, challenge } = await createPkcePair();
119
+ const flowId = randomFlowId(kind);
120
+ const url = new URL(redirectTo);
121
+ url.searchParams.set(WEB_PKCE_FLOW_PARAM, flowId);
122
+ const finalRedirectTo = url.toString();
123
+ // Static hosts such as GitHub Pages can redirect `/login/callback` to
124
+ // `/login/callback/`, so the callback URL is not always the one sent at start.
125
+ const entry: StoredVerifier = { verifier, createdAt: Date.now(), redirectTo: finalRedirectTo };
126
+ if (kind === 'magic_link') {
127
+ pruneMagicLinkVerifiers();
128
+ write(store('local'), MAGIC_LINK_PREFIX + flowId, entry);
129
+ } else {
130
+ write(store('session'), SESSION_PREFIX + flowId, entry);
131
+ }
132
+ return { flowId, challenge, redirectTo: finalRedirectTo };
133
+ }
134
+
135
+ /** Read the verifier for a callback and remove every stored copy. */
136
+ export function takeWebPkceVerifier(flowId: string | null | undefined): string | null {
137
+ return takeWebPkceFlow(flowId)?.verifier ?? null;
138
+ }
139
+
140
+ /** Read the verifier and the exact start `redirect_to` for a callback, single use. */
141
+ export function takeWebPkceFlow(flowId: string | null | undefined): TakenWebPkceFlow | null {
142
+ const id = flowId?.trim();
143
+ if (!id || !FLOW_ID_PATTERN.test(id)) return null;
144
+ if (isMagicLinkFlowId(id)) {
145
+ return readAndRemove(store('local'), MAGIC_LINK_PREFIX + id, MAGIC_LINK_MAX_AGE_MS);
146
+ }
147
+ return readAndRemove(store('session'), SESSION_PREFIX + id, OAUTH_MAX_AGE_MS);
148
+ }
149
+
150
+ export function isMagicLinkFlowId(flowId: string | null | undefined): boolean {
151
+ return !!flowId && flowId.startsWith(MAGIC_LINK_FLOW_MARK) && FLOW_ID_PATTERN.test(flowId);
152
+ }
153
+
154
+ /** Remove a flow's verifier, e.g. when starting it failed. */
155
+ export function clearWebPkce(flowId: string): void {
156
+ takeWebPkceVerifier(flowId);
157
+ }
158
+
159
+ export const WEB_PKCE_ERROR_CODES = [
160
+ 'pkce_required',
161
+ 'invalid_code_challenge',
162
+ 'invalid_code_challenge_method',
163
+ 'invalid_code_verifier',
164
+ 'pkce_verification_failed',
165
+ ] as const;
166
+
167
+ export function isWebPkceErrorCode(code: string | null | undefined): boolean {
168
+ return !!code && (WEB_PKCE_ERROR_CODES as readonly string[]).includes(code);
169
+ }
@@ -1,6 +1,6 @@
1
1
  import type { LayoutChromeInsets, LayoutChromeViewport } from '@shellui/sdk';
2
- import { DESKTOP_TITLEBAR_HEIGHT_PX } from '../layouts/chrome/constants';
3
- import { isTauriRuntime } from '../layouts/chrome/runtime';
2
+ import { DESKTOP_TITLEBAR_HEIGHT_PX, SHELL_HEADER_HEIGHT_PX } from '../layouts/chrome/constants';
3
+ import { isMacOSDesktop, isTauriRuntime } from '../layouts/chrome/runtime';
4
4
  import {
5
5
  FLOATING_CHROME_MARGIN,
6
6
  FLOATING_CONTENT_CLEARANCE,
@@ -96,8 +96,11 @@ export function chromeActionsTopMargin(
96
96
  const { layout, viewport } = context;
97
97
  if (layout === 'floating') {
98
98
  if (isTauriRuntime() && viewport === 'desktop') {
99
- // Center the row in the overlay titlebar, then nudge it off the window edge.
100
- return Math.round((DESKTOP_TITLEBAR_HEIGHT_PX - chromeActionsTopBarHeight(viewport)) / 2) + 4;
99
+ // Center the row in the title bar band, then nudge it off the window edge.
100
+ // macOS: 32px strip, (32 - 32) / 2 + 4 = 4. The row starts right of the panel or,
101
+ // collapsed, right of the strip glass group, so it never enters the lights safe area.
102
+ const band = isMacOSDesktop() ? DESKTOP_TITLEBAR_HEIGHT_PX : SHELL_HEADER_HEIGHT_PX;
103
+ return Math.round((band - chromeActionsTopBarHeight(viewport)) / 2) + 4;
101
104
  }
102
105
  return viewport === 'desktop' ? CHROME_ACTIONS_TOP_MARGIN_DESKTOP : CHROME_ACTIONS_TOP_MARGIN;
103
106
  }
@@ -62,6 +62,32 @@ export interface NavigationItem {
62
62
  * - true: trusted, access token can be shared (opt-in)
63
63
  */
64
64
  safeForAuthToken?: boolean;
65
+ /**
66
+ * Identity server for this embedded app when it is not the shell `backend`.
67
+ * The shell keeps a separate session and sends this URL plus that session's
68
+ * access token. Omit to use the shell backend and token.
69
+ * The shell token is never sent when this server differs.
70
+ */
71
+ backend?: AppBackendConfig;
72
+ /**
73
+ * Lets this app host other Shellui apps in its own iframes (`createAppFrame`).
74
+ * Off when omitted. Only exact origins listed here are accepted.
75
+ */
76
+ childFrames?: ChildFramesConfig;
77
+ /**
78
+ * Email service for this app. Omit to use the shell `email` when the app uses
79
+ * the shell identity server. When `backend` names a different server and this
80
+ * is omitted, the app receives no email URL.
81
+ */
82
+ email?: EmailConfig;
83
+ /**
84
+ * Storage service for this app. Same fallback as `email`.
85
+ */
86
+ storage?: StorageConfig;
87
+ /**
88
+ * Hosting service for this app. Same fallback as `email`.
89
+ */
90
+ hosting?: HostingConfig;
65
91
  }
66
92
 
67
93
  export interface NavigationGroup {
@@ -216,6 +242,47 @@ export interface AuthConfig {
216
242
  desktopScheme?: string;
217
243
  }
218
244
 
245
+ /** Child apps an embedded app may host, and the identity servers they may use. */
246
+ export interface ChildFramesConfig {
247
+ /** Exact origins of child apps, such as `https://admin.shellui.com`. No wildcards. */
248
+ origins: string[];
249
+ /**
250
+ * Exact origins of identity servers a child may sign in to, such as
251
+ * `https://id.eu.shellui.com`. The shell keeps a separate session per server
252
+ * and never sends its own token to a child. Omit to give children no token.
253
+ */
254
+ backendOrigins?: string[];
255
+ /**
256
+ * Exact origins of service URLs (email, storage, hosting) a host may pass to
257
+ * a child with `ShelluiFrame` or `createAppFrame`, such as
258
+ * `https://storage.eu.shellui.com`. No wildcards. A URL outside this list, or
259
+ * a missing one, reaches the child as `null`. Omit to send children no service URLs.
260
+ */
261
+ serviceOrigins?: string[];
262
+ }
263
+
264
+ /**
265
+ * Identity server for one embedded app when it differs from the shell `backend`.
266
+ * `type` defaults to the shell backend type. `companyId` is not copied from the shell.
267
+ */
268
+ export interface AppBackendConfig {
269
+ /** `shellui` or `supabase`. When omitted, the shell backend type is used. */
270
+ type?: BackendType;
271
+ /** Base URL of this app's identity server. */
272
+ url: string;
273
+ /** Tenant id for this server. Not taken from the shell `backend.companyId`. */
274
+ companyId?: string | number;
275
+ /** Public key when `type` is `supabase`. */
276
+ publishableKey?: string;
277
+ /**
278
+ * `upstream`: the shell gets the app session by OAuth token exchange (RFC 8693),
279
+ * trading its own access token at this server. Recommended for Shellui regions.
280
+ * Any other value, such as `google`, is the OAuth provider for silent sign-in.
281
+ * When omitted, the shell uses the first `backend.login.oauthProviders` entry.
282
+ */
283
+ provider?: string;
284
+ }
285
+
219
286
  /** Backend API configuration. */
220
287
  export interface BackendConfig {
221
288
  /** Backend provider type. */
@@ -299,12 +366,12 @@ export interface HostingConfig {
299
366
 
300
367
  /**
301
368
  * Optional email-service wiring for Admin → Email and iframe apps.
302
- * When `email` is set and `url` is omitted, the shell uses `https://email.shellui.com`.
369
+ * The shell never invents a URL: without `url`, apps get no email service.
303
370
  */
304
371
  export interface EmailConfig {
305
372
  /**
306
373
  * Base URL of email-service.
307
- * Default: `https://email.shellui.com` when `email` is set and this is omitted.
374
+ * Required for apps to get email. There is no built-in default.
308
375
  * Local: `http://localhost:8003`.
309
376
  */
310
377
  url?: string;
@@ -389,7 +456,7 @@ export interface ShellUIConfig {
389
456
  hosting?: HostingConfig;
390
457
  /**
391
458
  * Email-service connection. Propagated to iframes via SDK settings.
392
- * When `email` is set and `url` is omitted, the shell sends `https://email.shellui.com`.
459
+ * Without `url`, the shell sends no email service (`null`).
393
460
  * `showInAdmin: false` hides Admin → Email.
394
461
  */
395
462
  email?: EmailConfig;