@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.
Files changed (42) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -2
  3. package/schemas/shellui.config.schema.json +15 -0
  4. package/src/features/admin/AdminView.tsx +18 -4
  5. package/src/features/auth/AuthProvider.tsx +184 -69
  6. package/src/features/auth/backends/shellui.spec.ts +115 -0
  7. package/src/features/auth/backends/shellui.ts +8 -2
  8. package/src/features/auth/backends/types.ts +9 -1
  9. package/src/features/auth/hooks/useAuth.tsx +1 -0
  10. package/src/features/auth/utils/accessTokenRefreshDue.spec.ts +15 -0
  11. package/src/features/auth/utils/accessTokenRefreshDue.ts +8 -0
  12. package/src/features/auth/utils/desktopAuthCallback.spec.ts +68 -0
  13. package/src/features/auth/utils/desktopAuthCallback.ts +126 -0
  14. package/src/features/auth/utils/desktopSignIn.spec.ts +203 -0
  15. package/src/features/auth/utils/desktopSignIn.ts +483 -0
  16. package/src/features/auth/utils/frameSessionRefresher.spec.ts +23 -0
  17. package/src/features/auth/utils/frameSessionRefresher.ts +21 -0
  18. package/src/features/auth/utils/pkce.spec.ts +36 -0
  19. package/src/features/auth/utils/pkce.ts +38 -0
  20. package/src/features/chromeActions/ChromeActionsHost.tsx +7 -1
  21. package/src/features/chromeActions/computeActionInsets.ts +6 -0
  22. package/src/features/config/types.ts +17 -0
  23. package/src/features/layouts/appbar/AppBarLayout.tsx +39 -9
  24. package/src/features/layouts/chrome/ContentDragOverlay.tsx +14 -7
  25. package/src/features/layouts/chrome/DesktopChrome.tsx +3 -1
  26. package/src/features/layouts/floating/FloatingLayout.tsx +4 -1
  27. package/src/features/layouts/floating/FloatingSidebar.tsx +84 -28
  28. package/src/features/layouts/floating/computeFloatingInsets.spec.ts +19 -0
  29. package/src/features/layouts/floating/computeFloatingInsets.ts +40 -8
  30. package/src/features/layouts/floating/layoutChromeStore.ts +13 -0
  31. package/src/features/layouts/floating/useFloatingChrome.ts +11 -5
  32. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +3 -0
  33. package/src/features/layouts/sidebar/SidebarInner.tsx +5 -0
  34. package/src/features/layouts/sidebar/SidebarLayout.tsx +1 -0
  35. package/src/features/layouts/windows/WindowsLayout.tsx +106 -46
  36. package/src/features/security/trustedFrames.spec.ts +17 -1
  37. package/src/features/security/trustedFrames.ts +31 -9
  38. package/src/features/settings/SettingsProvider.tsx +86 -31
  39. package/src/features/settings/utils/buildSettingsForPropagation.ts +9 -2
  40. package/src/index.css +16 -1
  41. package/src/index.ts +6 -0
  42. package/src/lib/z-index.ts +5 -0
@@ -0,0 +1,15 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { accessTokenRefreshDue, PROACTIVE_REFRESH_LEEWAY_SECONDS } from './accessTokenRefreshDue';
3
+
4
+ describe('accessTokenRefreshDue', () => {
5
+ const now = 1_700_000_000;
6
+
7
+ it('is due inside the leeway and when already expired', () => {
8
+ expect(accessTokenRefreshDue(now + PROACTIVE_REFRESH_LEEWAY_SECONDS, now)).toBe(true);
9
+ expect(accessTokenRefreshDue(now - 5, now)).toBe(true);
10
+ });
11
+
12
+ it('is not due while the token still has more than the leeway left', () => {
13
+ expect(accessTokenRefreshDue(now + PROACTIVE_REFRESH_LEEWAY_SECONDS + 1, now)).toBe(false);
14
+ });
15
+ });
@@ -0,0 +1,8 @@
1
+ /** Refresh the access token this many seconds before `expiresAt` so API calls stay valid. */
2
+ export const PROACTIVE_REFRESH_LEEWAY_SECONDS = 90;
3
+
4
+ /** True when the access token should be refreshed before it is handed to an iframe. */
5
+ export function accessTokenRefreshDue(expiresAt: number, nowSeconds: number): boolean {
6
+ if (!Number.isFinite(expiresAt)) return true;
7
+ return expiresAt - nowSeconds <= PROACTIVE_REFRESH_LEEWAY_SECONDS;
8
+ }
@@ -0,0 +1,68 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import {
3
+ desktopAuthErrorMessage,
4
+ desktopRedirectUri,
5
+ normalizeDesktopScheme,
6
+ parseDesktopAuthCallback,
7
+ } from './desktopAuthCallback';
8
+
9
+ const SCHEME = 'shellui-playground';
10
+
11
+ describe('desktop auth callback', () => {
12
+ test('accepts a lowercase custom scheme and refuses browser schemes', () => {
13
+ expect(normalizeDesktopScheme('shellui-playground')).toBe('shellui-playground');
14
+ expect(normalizeDesktopScheme('com.example.desktop')).toBe('com.example.desktop');
15
+ expect(normalizeDesktopScheme(' Shellui-Playground ')).toBeNull();
16
+ expect(normalizeDesktopScheme('http')).toBeNull();
17
+ expect(normalizeDesktopScheme('https')).toBeNull();
18
+ expect(normalizeDesktopScheme('javascript')).toBeNull();
19
+ expect(normalizeDesktopScheme('')).toBeNull();
20
+ expect(desktopRedirectUri(SCHEME)).toBe('shellui-playground://callback');
21
+ });
22
+
23
+ test('reads shellui_auth_code and keeps the redirect used at the start', () => {
24
+ const parsed = parseDesktopAuthCallback(
25
+ 'shellui-playground://callback?shellui_auth_code=one-time-code',
26
+ SCHEME,
27
+ );
28
+ expect(parsed).toEqual({
29
+ kind: 'code',
30
+ authCode: 'one-time-code',
31
+ redirectTo: 'shellui-playground://callback',
32
+ });
33
+ });
34
+
35
+ test('maps ?error= to a message and does not treat it as a code', () => {
36
+ const parsed = parseDesktopAuthCallback(
37
+ 'shellui-playground://callback?error=pkce_required',
38
+ SCHEME,
39
+ );
40
+ expect(parsed?.kind).toBe('error');
41
+ if (parsed?.kind !== 'error') return;
42
+ expect(parsed.errorCode).toBe('pkce_required');
43
+ expect(parsed.message).toBe(desktopAuthErrorMessage('pkce_required'));
44
+ expect(parsed.message.toLowerCase()).not.toContain('one-time');
45
+ expect(parsed).not.toHaveProperty('authCode');
46
+ expect(parsed).not.toHaveProperty('codeVerifier');
47
+ });
48
+
49
+ test('treats shellui_oauth_error on the deep link as a failed sign-in', () => {
50
+ const parsed = parseDesktopAuthCallback(
51
+ 'shellui-playground://callback?shellui_oauth_error=Sign-in%20stopped&shellui_oauth_error_code=pkce_required',
52
+ SCHEME,
53
+ );
54
+ expect(parsed).toMatchObject({
55
+ kind: 'error',
56
+ errorCode: 'pkce_required',
57
+ });
58
+ });
59
+
60
+ test('ignores a different scheme and a URL without a code', () => {
61
+ expect(
62
+ parseDesktopAuthCallback('other-app://callback?shellui_auth_code=abc', SCHEME),
63
+ ).toBeNull();
64
+ expect(parseDesktopAuthCallback('not a url', SCHEME)).toBeNull();
65
+ const missing = parseDesktopAuthCallback('shellui-playground://callback', SCHEME);
66
+ expect(missing).toMatchObject({ kind: 'error', errorCode: 'missing_auth_code' });
67
+ });
68
+ });
@@ -0,0 +1,126 @@
1
+ import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
2
+
3
+ /** Path identity-service returns to: `<scheme>://callback`. */
4
+ export const DESKTOP_AUTH_CALLBACK_HOST = 'callback';
5
+
6
+ const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*$/;
7
+
8
+ /** Browser and network schemes identity-service refuses for desktop redirects. */
9
+ const REFUSED_SCHEMES = new Set([
10
+ 'http',
11
+ 'https',
12
+ 'javascript',
13
+ 'data',
14
+ 'file',
15
+ 'vbscript',
16
+ 'about',
17
+ 'blob',
18
+ 'ftp',
19
+ 'mailto',
20
+ 'ws',
21
+ 'wss',
22
+ ]);
23
+
24
+ const ERROR_MESSAGES: Record<string, string> = {
25
+ pkce_required: 'Desktop sign-in needs a new attempt. Start sign-in again.',
26
+ invalid_code_challenge_method:
27
+ 'Desktop sign-in used an unsupported verification method. Start sign-in again.',
28
+ invalid_code_challenge: 'Desktop sign-in could not start verification. Start sign-in again.',
29
+ invalid_code_verifier: 'Desktop sign-in could not verify this attempt. Start sign-in again.',
30
+ pkce_verification_failed: 'Desktop sign-in could not verify this attempt. Start sign-in again.',
31
+ unregistered_scheme: 'This desktop scheme is not registered on the OAuth application.',
32
+ magic_link_expired: 'This email link has expired. Request a new one.',
33
+ magic_link_invalid: 'This email link is not valid. Request a new one.',
34
+ access_pending: 'Your account is waiting for an administrator to grant access.',
35
+ access_denied: 'Your account cannot access this organization.',
36
+ missing_auth_code: 'Desktop sign-in did not return a code. Start sign-in again.',
37
+ desktop_signin_expired: 'Desktop sign-in expired. Start sign-in again.',
38
+ };
39
+
40
+ const OAUTH_ERROR_PARAM = 'shellui_oauth_error';
41
+ const OAUTH_ERROR_CODE_PARAM = 'shellui_oauth_error_code';
42
+
43
+ export function normalizeDesktopScheme(value: unknown): string | null {
44
+ if (typeof value !== 'string') return null;
45
+ const scheme = value.trim().toLowerCase();
46
+ if (
47
+ !scheme ||
48
+ scheme !== value.trim() ||
49
+ !SCHEME_PATTERN.test(scheme) ||
50
+ REFUSED_SCHEMES.has(scheme)
51
+ ) {
52
+ return null;
53
+ }
54
+ return scheme;
55
+ }
56
+
57
+ export function desktopRedirectUri(scheme: string): string {
58
+ return `${scheme}://${DESKTOP_AUTH_CALLBACK_HOST}`;
59
+ }
60
+
61
+ export function desktopAuthErrorMessage(errorCode: string, detail?: string | null): string {
62
+ const known = ERROR_MESSAGES[errorCode];
63
+ if (known) return known;
64
+ if (detail && isSafeDisplayMessage(detail)) return detail;
65
+ return 'Desktop sign-in failed. Start sign-in again.';
66
+ }
67
+
68
+ function isSafeDisplayMessage(value: string): boolean {
69
+ const text = value.trim();
70
+ if (!text || text.length > 180) return false;
71
+ if (/bearer\s|eyJ|code_verifier|shellui_auth_code|verifier/i.test(text)) return false;
72
+ return true;
73
+ }
74
+
75
+ export type DesktopAuthCallback =
76
+ | { kind: 'code'; authCode: string; redirectTo: string }
77
+ | { kind: 'error'; errorCode: string; message: string; redirectTo: string };
78
+
79
+ /**
80
+ * Read a desktop deep link. Returns null when the scheme is not the one this
81
+ * app registered. Does not include the verifier.
82
+ */
83
+ export function parseDesktopAuthCallback(
84
+ rawUrl: string,
85
+ expectedScheme: string,
86
+ ): DesktopAuthCallback | null {
87
+ const scheme = normalizeDesktopScheme(expectedScheme);
88
+ if (!scheme) return null;
89
+
90
+ let url: URL;
91
+ try {
92
+ url = new URL(rawUrl);
93
+ } catch {
94
+ return null;
95
+ }
96
+
97
+ const callbackScheme = url.protocol.replace(/:$/, '').toLowerCase();
98
+ if (callbackScheme !== scheme) return null;
99
+
100
+ const redirectTo = desktopRedirectUri(scheme);
101
+ const errorCodeParam = (url.searchParams.get('error') || '').trim();
102
+ const oauthError = (url.searchParams.get(OAUTH_ERROR_PARAM) || '').trim();
103
+ const oauthErrorCode = (url.searchParams.get(OAUTH_ERROR_CODE_PARAM) || '').trim();
104
+
105
+ if (errorCodeParam || oauthError || oauthErrorCode) {
106
+ const errorCode = (oauthErrorCode || errorCodeParam || 'oauth_error').slice(0, 64);
107
+ return {
108
+ kind: 'error',
109
+ errorCode,
110
+ message: desktopAuthErrorMessage(errorCode, oauthError || null),
111
+ redirectTo,
112
+ };
113
+ }
114
+
115
+ const authCode = (url.searchParams.get(SHELLUI_AUTH_CODE_PARAM) || '').trim();
116
+ if (!authCode) {
117
+ return {
118
+ kind: 'error',
119
+ errorCode: 'missing_auth_code',
120
+ message: desktopAuthErrorMessage('missing_auth_code'),
121
+ redirectTo,
122
+ };
123
+ }
124
+
125
+ return { kind: 'code', authCode, redirectTo };
126
+ }
@@ -0,0 +1,203 @@
1
+ import { afterEach, describe, expect, test, vi } from 'vitest';
2
+ import {
3
+ beginDesktopOAuth,
4
+ buildDesktopAuthorizeUrl,
5
+ configureDesktopAuth,
6
+ ensureDesktopDeepLinkListener,
7
+ handleDesktopAuthCallback,
8
+ resetDesktopAuthState,
9
+ setActiveDesktopScheme,
10
+ shouldUseDesktopSignIn,
11
+ subscribeDesktopAuth,
12
+ createAndStoreDesktopPkce,
13
+ type DesktopAuthEvent,
14
+ } from './desktopSignIn';
15
+
16
+ const SCHEME = 'shellui-playground';
17
+
18
+ describe('desktop sign-in', () => {
19
+ afterEach(() => {
20
+ resetDesktopAuthState();
21
+ vi.unstubAllGlobals();
22
+ vi.restoreAllMocks();
23
+ });
24
+
25
+ test('browser runtime keeps the web flow even when a scheme is configured', () => {
26
+ expect(
27
+ shouldUseDesktopSignIn(
28
+ {
29
+ backend: { type: 'shellui', url: 'https://auth.example.com' },
30
+ auth: { desktopScheme: SCHEME },
31
+ },
32
+ false,
33
+ ),
34
+ ).toBe(false);
35
+ expect(
36
+ shouldUseDesktopSignIn(
37
+ { backend: { type: 'shellui', url: 'https://auth.example.com' } },
38
+ true,
39
+ ),
40
+ ).toBe(false);
41
+ expect(
42
+ shouldUseDesktopSignIn(
43
+ {
44
+ backend: { type: 'supabase', url: 'https://auth.example.com' },
45
+ auth: { desktopScheme: SCHEME },
46
+ },
47
+ true,
48
+ ),
49
+ ).toBe(false);
50
+ });
51
+
52
+ test('authorize URL sends the custom-scheme redirect and an S256 challenge', () => {
53
+ const url = new URL(
54
+ buildDesktopAuthorizeUrl({
55
+ backendUrl: 'https://auth.example.com/',
56
+ companyId: '7',
57
+ provider: 'github',
58
+ oauthClientId: 4,
59
+ redirectTo: 'shellui-playground://callback',
60
+ codeChallenge: 'challenge-value',
61
+ clientTimezone: 'Europe/Paris',
62
+ }),
63
+ );
64
+ expect(`${url.origin}${url.pathname}`).toBe('https://auth.example.com/api/v1/authorize');
65
+ expect(url.searchParams.get('redirect_to')).toBe('shellui-playground://callback');
66
+ expect(url.searchParams.get('code_challenge')).toBe('challenge-value');
67
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256');
68
+ expect(url.searchParams.get('company_id')).toBe('7');
69
+ expect(url.searchParams.get('company_oauth_client_id')).toBe('4');
70
+ expect(url.searchParams.get('provider')).toBe('github');
71
+ expect(url.searchParams.get('code_verifier')).toBeNull();
72
+ });
73
+
74
+ test('opens the injected browser and does not put the verifier on the URL', async () => {
75
+ const openUrl = vi.fn();
76
+ configureDesktopAuth({ openUrl });
77
+ await beginDesktopOAuth({
78
+ backendUrl: 'https://auth.example.com',
79
+ companyId: 7,
80
+ provider: 'github',
81
+ scheme: SCHEME,
82
+ });
83
+ expect(openUrl).toHaveBeenCalledTimes(1);
84
+ const opened = String(openUrl.mock.calls[0]?.[0]);
85
+ const url = new URL(opened);
86
+ expect(url.searchParams.get('redirect_to')).toBe('shellui-playground://callback');
87
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256');
88
+ expect(url.searchParams.get('code_challenge')?.length).toBeGreaterThanOrEqual(43);
89
+ expect(opened).not.toContain('code_verifier');
90
+ });
91
+
92
+ test('?error= clears the verifier and emits a message', async () => {
93
+ const log = vi.spyOn(console, 'log').mockImplementation(() => undefined);
94
+ setActiveDesktopScheme(SCHEME);
95
+ const prepared = await createAndStoreDesktopPkce(SCHEME);
96
+ const events: DesktopAuthEvent[] = [];
97
+ subscribeDesktopAuth((event) => events.push(event));
98
+
99
+ handleDesktopAuthCallback('shellui-playground://callback?error=unregistered_scheme');
100
+
101
+ expect(events).toEqual([
102
+ {
103
+ type: 'error',
104
+ errorCode: 'unregistered_scheme',
105
+ message: 'This desktop scheme is not registered on the OAuth application.',
106
+ },
107
+ ]);
108
+ handleDesktopAuthCallback('shellui-playground://callback?shellui_auth_code=later-code');
109
+ expect(events[events.length - 1]).toMatchObject({
110
+ type: 'error',
111
+ errorCode: 'desktop_signin_expired',
112
+ });
113
+ expect(JSON.stringify(events)).not.toContain(prepared.challenge);
114
+ expect(log).not.toHaveBeenCalled();
115
+ });
116
+
117
+ test('exchanges a deep link with the stored verifier once', async () => {
118
+ setActiveDesktopScheme(SCHEME);
119
+ await createAndStoreDesktopPkce(SCHEME);
120
+ const events: DesktopAuthEvent[] = [];
121
+ subscribeDesktopAuth((event) => events.push(event));
122
+
123
+ const callback = 'shellui-playground://callback?shellui_auth_code=session-code';
124
+ handleDesktopAuthCallback(callback);
125
+ handleDesktopAuthCallback(callback);
126
+
127
+ expect(events).toHaveLength(1);
128
+ expect(events[0]).toMatchObject({
129
+ type: 'code',
130
+ authCode: 'session-code',
131
+ redirectTo: 'shellui-playground://callback',
132
+ });
133
+ if (events[0]?.type !== 'code') return;
134
+ expect(events[0].codeVerifier.length).toBeGreaterThanOrEqual(43);
135
+ });
136
+
137
+ test('reads the deep-link plugin through Tauri IPC without importing it', async () => {
138
+ const invoke = vi.fn(async (cmd: string) => {
139
+ if (cmd === 'plugin:deep-link|get_current') {
140
+ return ['shellui-playground://callback?shellui_auth_code=from-launch'];
141
+ }
142
+ if (cmd === 'plugin:event|listen') return 4;
143
+ return null;
144
+ });
145
+ vi.stubGlobal('window', {
146
+ __TAURI_INTERNALS__: {
147
+ invoke,
148
+ transformCallback: () => 9,
149
+ unregisterCallback: () => undefined,
150
+ },
151
+ });
152
+ setActiveDesktopScheme(SCHEME);
153
+ await createAndStoreDesktopPkce(SCHEME);
154
+ const events: DesktopAuthEvent[] = [];
155
+ subscribeDesktopAuth((event) => events.push(event));
156
+
157
+ await ensureDesktopDeepLinkListener();
158
+
159
+ expect(invoke).toHaveBeenCalledWith('plugin:deep-link|get_current');
160
+ expect(events[0]).toMatchObject({ type: 'code', authCode: 'from-launch' });
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
+ });
203
+ });