@shellui/core 0.7.0-beta.1 → 0.8.0

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/package.json +3 -3
  4. package/schemas/shellui.config.schema.json +45 -2
  5. package/src/app.tsx +2 -0
  6. package/src/features/auth/AuthProvider.tsx +212 -97
  7. package/src/features/auth/appBackend/configSchema.spec.ts +1 -0
  8. package/src/features/auth/appBackend/frameAuth.ts +5 -0
  9. package/src/features/auth/backends/shellui.spec.ts +110 -0
  10. package/src/features/auth/backends/shellui.ts +47 -20
  11. package/src/features/auth/backends/types.ts +5 -0
  12. package/src/features/auth/hooks/useAuth.tsx +6 -1
  13. package/src/features/auth/types.ts +5 -0
  14. package/src/features/auth/utils/bffAuthClient.spec.ts +313 -0
  15. package/src/features/auth/utils/bffAuthClient.ts +171 -49
  16. package/src/features/auth/utils/buildSessionFromParams.ts +5 -2
  17. package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +12 -0
  18. package/src/features/auth/utils/buildSessionFromTokenPayload.ts +3 -1
  19. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +140 -4
  20. package/src/features/auth/utils/canRestoreStoredSession.ts +47 -0
  21. package/src/features/auth/utils/cliCallback.ts +5 -0
  22. package/src/features/auth/utils/identityBrowserLogout.spec.ts +185 -0
  23. package/src/features/auth/utils/identityBrowserLogout.ts +174 -0
  24. package/src/features/auth/utils/index.ts +21 -3
  25. package/src/features/auth/utils/isBffAuthEnabled.ts +10 -2
  26. package/src/features/auth/utils/normalizeAuthSettings.spec.ts +9 -0
  27. package/src/features/auth/utils/normalizeAuthSettings.ts +3 -1
  28. package/src/features/auth/utils/pkce.spec.ts +29 -1
  29. package/src/features/auth/utils/pkce.ts +106 -2
  30. package/src/features/config/types.ts +37 -5
  31. package/src/features/mcp/mcpActivityErrorCodeI18n.spec.ts +32 -0
  32. package/src/features/mcp/mcpActivityErrorCodeI18n.ts +30 -0
  33. package/src/features/mcp/mcpAgentActivityMerge.spec.ts +91 -0
  34. package/src/features/mcp/mcpAgentActivityMerge.ts +53 -0
  35. package/src/features/mcp/mcpAgentActivityPresentation.spec.ts +129 -0
  36. package/src/features/mcp/mcpAgentActivityPresentation.ts +201 -0
  37. package/src/features/mcp/mcpAgentsConnect.spec.ts +215 -0
  38. package/src/features/mcp/mcpAgentsConnect.ts +189 -0
  39. package/src/features/mcp/mcpToolActivityRegistry.spec.ts +9 -0
  40. package/src/features/mcp/mcpToolActivityRegistry.ts +20 -0
  41. package/src/features/mcp/mcpToolApprovalsApi.spec.ts +113 -0
  42. package/src/features/mcp/mcpToolApprovalsApi.ts +162 -0
  43. package/src/features/mcp/personalAgentsApi.spec.ts +661 -0
  44. package/src/features/mcp/personalAgentsApi.ts +697 -0
  45. package/src/features/settings/SettingsIcons.tsx +28 -0
  46. package/src/features/settings/SettingsRoutes.tsx +8 -0
  47. package/src/features/settings/SettingsView.tsx +90 -26
  48. package/src/features/settings/components/McpAgentActivitySection.spec.tsx +255 -0
  49. package/src/features/settings/components/McpAgentActivitySection.tsx +481 -0
  50. package/src/features/settings/components/McpAgents.spec.tsx +336 -0
  51. package/src/features/settings/components/McpAgents.tsx +654 -0
  52. package/src/features/settings/components/McpPendingApprovals.spec.tsx +201 -0
  53. package/src/features/settings/components/McpPendingApprovals.tsx +168 -0
  54. package/src/features/settings/components/McpPersonalStatusPrefetch.tsx +21 -0
  55. package/src/features/settings/hooks/useMcpPendingToolApprovals.ts +69 -0
  56. package/src/features/settings/hooks/useMcpPersonalStatus.ts +83 -0
  57. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +44 -1
  58. package/src/features/settings/utils/buildSettingsForPropagation.ts +30 -1
  59. package/src/features/settings/utils/isMcpAgentsSettingsEligible.spec.ts +25 -0
  60. package/src/features/settings/utils/isMcpAgentsSettingsEligible.ts +14 -0
  61. package/src/features/settings/utils/loadMcpPersonalStatus.spec.ts +76 -0
  62. package/src/features/settings/utils/loadMcpPersonalStatus.ts +84 -0
  63. package/src/features/settings/utils/mcpPersonalStatusCache.spec.ts +77 -0
  64. package/src/features/settings/utils/mcpPersonalStatusCache.ts +95 -0
  65. package/src/features/settings/utils/shouldShowMcpAgentsSettings.spec.ts +66 -0
  66. package/src/features/settings/utils/shouldShowMcpAgentsSettings.ts +16 -0
  67. package/src/i18n/translations/en/settings.json +201 -0
  68. package/src/i18n/translations/fr/settings.json +201 -0
  69. package/src/index.ts +1 -0
  70. package/src/service-worker/sw.ts +4 -2
@@ -0,0 +1,185 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import type { NavigationItem } from '../../config/types';
3
+ import {
4
+ buildIdentityBrowserLogoutUrl,
5
+ finishShellSignOut,
6
+ readIdentityLogoutUrl,
7
+ resolveLogoutReturnTo,
8
+ } from './identityBrowserLogout';
9
+
10
+ const origin = 'https://app.example.com';
11
+
12
+ const item = (path: string, extra?: Partial<NavigationItem>): NavigationItem =>
13
+ ({
14
+ label: path || 'home',
15
+ path,
16
+ url: 'https://app.example.com/',
17
+ ...extra,
18
+ }) as NavigationItem;
19
+
20
+ describe('buildIdentityBrowserLogoutUrl', () => {
21
+ test('encodes company_id and return_to and keeps an existing query', () => {
22
+ const logout = buildIdentityBrowserLogoutUrl(
23
+ 'https://auth.example.com/oauth/logout?from=settings',
24
+ '7',
25
+ 'https://app.example.com/docs?q=a+b&next=%2Fapps',
26
+ );
27
+
28
+ expect(logout).toBeTruthy();
29
+ const url = new URL(logout as string);
30
+ expect(`${url.origin}${url.pathname}`).toBe('https://auth.example.com/oauth/logout');
31
+ expect(url.searchParams.get('from')).toBe('settings');
32
+ expect(url.searchParams.get('company_id')).toBe('7');
33
+ expect(url.searchParams.get('return_to')).toBe(
34
+ 'https://app.example.com/docs?q=a+b&next=%2Fapps',
35
+ );
36
+ expect(logout).toContain(
37
+ `return_to=${encodeURIComponent('https://app.example.com/docs?q=a+b&next=%2Fapps')}`,
38
+ );
39
+ expect(logout).not.toContain(' ');
40
+ expect(logout).not.toContain('#');
41
+ });
42
+
43
+ test('rejects a non-http logout URL, a bad company id, and a relative return', () => {
44
+ expect(
45
+ buildIdentityBrowserLogoutUrl('javascript:alert(1)', '7', 'https://app.example.com/'),
46
+ ).toBe(null);
47
+ expect(
48
+ buildIdentityBrowserLogoutUrl(
49
+ 'https://auth.example.com/oauth/logout',
50
+ 'acme',
51
+ 'https://app.example.com/',
52
+ ),
53
+ ).toBe(null);
54
+ expect(
55
+ buildIdentityBrowserLogoutUrl('https://auth.example.com/oauth/logout', '7', '/docs'),
56
+ ).toBe(null);
57
+ expect(readIdentityLogoutUrl(' https://auth.example.com/oauth/logout ')).toBe(
58
+ 'https://auth.example.com/oauth/logout',
59
+ );
60
+ expect(readIdentityLogoutUrl('/oauth/logout')).toBeNull();
61
+ expect(readIdentityLogoutUrl('https://user:pass@auth.example.com/oauth/logout')).toBeNull();
62
+ });
63
+ });
64
+
65
+ describe('resolveLogoutReturnTo', () => {
66
+ test('keeps a public page and strips auth params', () => {
67
+ expect(
68
+ resolveLogoutReturnTo({
69
+ origin,
70
+ pathname: '/docs',
71
+ search: '?q=1&shellui_auth_code=one-time&shellui_pkce_flow=oabc',
72
+ navigation: [item('docs')],
73
+ }),
74
+ ).toBe('https://app.example.com/docs?q=1');
75
+ });
76
+
77
+ test('uses the shell origin root for a guarded route and for the OAuth callback', () => {
78
+ const navigation = [item(''), item('billing', { requiresAuth: true })];
79
+ expect(
80
+ resolveLogoutReturnTo({
81
+ origin,
82
+ pathname: '/billing/invoices',
83
+ search: '?x=1',
84
+ navigation,
85
+ }),
86
+ ).toBe('https://app.example.com/');
87
+ expect(
88
+ resolveLogoutReturnTo({
89
+ origin,
90
+ pathname: '/login/callback',
91
+ search: '?shellui_auth_code=still-valid&next=%2Fapps',
92
+ navigation,
93
+ }),
94
+ ).toBe('https://app.example.com/');
95
+ });
96
+
97
+ test('accepts an explicit same-origin path and rejects another origin', () => {
98
+ expect(
99
+ resolveLogoutReturnTo({
100
+ origin,
101
+ pathname: '/billing',
102
+ search: '',
103
+ navigation: [item('billing', { requiresAuth: true })],
104
+ returnTo: '/login?next=%2F__settings%2Fuser',
105
+ }),
106
+ ).toBe('https://app.example.com/login?next=%2F__settings%2Fuser');
107
+ expect(
108
+ resolveLogoutReturnTo({
109
+ origin,
110
+ pathname: '/',
111
+ search: '',
112
+ returnTo: 'https://evil.example/phish',
113
+ }),
114
+ ).toBeNull();
115
+ });
116
+ });
117
+
118
+ describe('finishShellSignOut', () => {
119
+ test('revokes and clears before navigating', async () => {
120
+ const order: string[] = [];
121
+ const navigated = await finishShellSignOut({
122
+ revoke: async () => {
123
+ order.push('revoke');
124
+ },
125
+ clearLocal: () => {
126
+ order.push('clear');
127
+ },
128
+ readBrowserLogoutUrl: async () => {
129
+ order.push('settings');
130
+ return 'https://auth.example.com/oauth/logout?company_id=7&return_to=https%3A%2F%2Fapp.example.com%2F';
131
+ },
132
+ navigate: () => {
133
+ order.push('navigate');
134
+ },
135
+ initiatedHere: true,
136
+ });
137
+
138
+ expect(navigated).toBe(true);
139
+ expect(order).toEqual(['revoke', 'clear', 'settings', 'navigate']);
140
+ });
141
+
142
+ test('still clears when revoke fails, and skips navigation without logout_url', async () => {
143
+ const order: string[] = [];
144
+ const navigated = await finishShellSignOut({
145
+ revoke: async () => {
146
+ order.push('revoke');
147
+ throw new Error('offline');
148
+ },
149
+ clearLocal: () => {
150
+ order.push('clear');
151
+ },
152
+ readBrowserLogoutUrl: async () => null,
153
+ navigate: () => {
154
+ order.push('navigate');
155
+ },
156
+ initiatedHere: true,
157
+ });
158
+
159
+ expect(navigated).toBe(false);
160
+ expect(order).toEqual(['revoke', 'clear']);
161
+ });
162
+
163
+ test('a tab that did not start sign-out clears tokens and does not navigate', async () => {
164
+ const order: string[] = [];
165
+ const navigated = await finishShellSignOut({
166
+ revoke: async () => {
167
+ order.push('revoke');
168
+ },
169
+ clearLocal: () => {
170
+ order.push('clear');
171
+ },
172
+ readBrowserLogoutUrl: async () => {
173
+ order.push('settings');
174
+ return 'https://auth.example.com/oauth/logout';
175
+ },
176
+ navigate: () => {
177
+ order.push('navigate');
178
+ },
179
+ initiatedHere: false,
180
+ });
181
+
182
+ expect(navigated).toBe(false);
183
+ expect(order).toEqual(['revoke', 'clear']);
184
+ });
185
+ });
@@ -0,0 +1,174 @@
1
+ import type { NavigationGroup, NavigationItem } from '../../config/types';
2
+ import urls from '../../../constants/urls';
3
+ import { flattenNavigationItems, getNavPathPrefix } from '../../layouts/utils';
4
+ import { SILENT_AUTH_QUERY, SILENT_AUTH_STATE_QUERY } from '../appBackend/silentSignIn';
5
+ import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
6
+ import { WEB_PKCE_FLOW_PARAM } from './webPkce';
7
+
8
+ /**
9
+ * Query keys that must not ride along on `return_to`.
10
+ * A leftover `shellui_auth_code` would be exchanged again after identity sends
11
+ * the browser back, which signs the user in and can start another logout.
12
+ */
13
+ const RETURN_TO_STRIP_PARAMS = [
14
+ SHELLUI_AUTH_CODE_PARAM,
15
+ WEB_PKCE_FLOW_PARAM,
16
+ 'shellui_oauth_error',
17
+ 'shellui_oauth_error_code',
18
+ SILENT_AUTH_QUERY,
19
+ SILENT_AUTH_STATE_QUERY,
20
+ 'access_token',
21
+ 'refresh_token',
22
+ 'code_verifier',
23
+ ] as const;
24
+
25
+ const stripReturnToParams = (url: URL) => {
26
+ for (const key of RETURN_TO_STRIP_PARAMS) url.searchParams.delete(key);
27
+ // Identity drops fragments before the allowlist check, so the landing URL
28
+ // would not include one. Leave it off the request.
29
+ url.hash = '';
30
+ };
31
+
32
+ /**
33
+ * Absolute http(s) URL on `origin`, or null when `value` points somewhere else.
34
+ */
35
+ export const sameOriginAppUrl = (origin: string, value: string): string | null => {
36
+ let url: URL;
37
+ try {
38
+ url = new URL(value, origin);
39
+ } catch {
40
+ return null;
41
+ }
42
+ if (url.origin !== origin) return null;
43
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
44
+ stripReturnToParams(url);
45
+ return url.toString();
46
+ };
47
+
48
+ const leavesProtectedRoute = (
49
+ pathname: string,
50
+ navigation: (NavigationItem | NavigationGroup)[] | undefined,
51
+ ): boolean => {
52
+ const required = flattenNavigationItems(navigation ?? []).filter((item) => item.requiresAuth);
53
+ return required.some((item) => {
54
+ const pathPrefix = getNavPathPrefix(item);
55
+ return (
56
+ pathname === pathPrefix || pathname.startsWith(`${pathPrefix === '/' ? '' : pathPrefix}/`)
57
+ );
58
+ });
59
+ };
60
+
61
+ /**
62
+ * Where the browser should land after identity logout.
63
+ * Protected routes and `/login/callback` use the shell origin root, matching
64
+ * the account-menu sign-out that leaves a guarded page before the session ends.
65
+ * An explicit `returnTo` (a shell path or same-origin URL) wins.
66
+ */
67
+ export const resolveLogoutReturnTo = (input: {
68
+ origin: string;
69
+ pathname: string;
70
+ search: string;
71
+ navigation?: (NavigationItem | NavigationGroup)[];
72
+ returnTo?: string;
73
+ }): string | null => {
74
+ const explicit = input.returnTo?.trim();
75
+ if (explicit) return sameOriginAppUrl(input.origin, explicit);
76
+
77
+ const pathname = input.pathname || '/';
78
+ if (
79
+ pathname === urls.loginCallback ||
80
+ pathname.startsWith(`${urls.loginCallback}/`) ||
81
+ leavesProtectedRoute(pathname, input.navigation)
82
+ ) {
83
+ return sameOriginAppUrl(input.origin, '/');
84
+ }
85
+
86
+ const rawSearch = input.search.startsWith('?') ? input.search.slice(1) : input.search;
87
+ const search = rawSearch ? `?${rawSearch}` : '';
88
+ return sameOriginAppUrl(input.origin, `${pathname}${search}`);
89
+ };
90
+
91
+ const isHttpUrl = (value: string): URL | null => {
92
+ try {
93
+ const url = new URL(value);
94
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
95
+ if (url.username || url.password) return null;
96
+ if (!url.hostname) return null;
97
+ return url;
98
+ } catch {
99
+ return null;
100
+ }
101
+ };
102
+
103
+ /**
104
+ * `logout_url` from `GET /api/v1/settings`, as an http(s) URL with no userinfo.
105
+ * Anything else is treated as an older identity service with no browser logout.
106
+ */
107
+ export const readIdentityLogoutUrl = (value: unknown): string | null => {
108
+ if (typeof value !== 'string') return null;
109
+ const url = isHttpUrl(value.trim());
110
+ if (!url) return null;
111
+ url.hash = '';
112
+ return url.toString();
113
+ };
114
+
115
+ /**
116
+ * Top-level GET `logout_url?company_id=&return_to=`.
117
+ * `return_to` is encoded once so `&`, `+`, and spaces survive the redirect.
118
+ */
119
+ export const buildIdentityBrowserLogoutUrl = (
120
+ logoutUrl: string,
121
+ companyId: string,
122
+ returnTo: string,
123
+ ): string | null => {
124
+ const company = companyId.trim();
125
+ if (!/^\d+$/.test(company)) return null;
126
+ const base = isHttpUrl(logoutUrl.trim());
127
+ const target = isHttpUrl(returnTo.trim());
128
+ if (!base || !target) return null;
129
+
130
+ const params = new URLSearchParams(base.search);
131
+ params.set('company_id', company);
132
+ params.set('return_to', target.toString());
133
+ base.search = params.toString();
134
+ base.hash = '';
135
+ return base.toString();
136
+ };
137
+
138
+ export type ShellSignOutActions = {
139
+ /** `POST /api/v1/logout` with the Bearer token. Runs before local cleanup. */
140
+ revoke: () => Promise<void>;
141
+ clearLocal: () => void;
142
+ /** Null when settings have no `logout_url` (older identity). */
143
+ readBrowserLogoutUrl: () => Promise<string | null>;
144
+ navigate: (url: string) => void;
145
+ /**
146
+ * False for a tab that only mirrored a sign-out, and for a frame that is not
147
+ * the top window. Those paths clear tokens and do not navigate.
148
+ */
149
+ initiatedHere: boolean;
150
+ };
151
+
152
+ /**
153
+ * Bearer revoke, then local tokens, then optional identity browser navigation.
154
+ * Returns true when this call navigated.
155
+ */
156
+ export const finishShellSignOut = async (actions: ShellSignOutActions): Promise<boolean> => {
157
+ try {
158
+ await actions.revoke();
159
+ } catch {
160
+ // A failed revoke still ends the local session.
161
+ }
162
+ actions.clearLocal();
163
+ if (!actions.initiatedHere) return false;
164
+
165
+ let url: string | null = null;
166
+ try {
167
+ url = await actions.readBrowserLogoutUrl();
168
+ } catch {
169
+ url = null;
170
+ }
171
+ if (!url) return false;
172
+ actions.navigate(url);
173
+ return true;
174
+ };
@@ -26,6 +26,7 @@ export {
26
26
  export {
27
27
  CLI_CALLBACK_PARAM,
28
28
  captureCliCallbackFromSearch,
29
+ hasPendingCliCallback,
29
30
  isLoopbackCliCallbackUrl,
30
31
  redirectCliCallbackError,
31
32
  redirectToCliCallback,
@@ -39,11 +40,23 @@ export {
39
40
  } from './authSessionPersistence';
40
41
  export type { PersistedAuthProfile } from './authSessionPersistence';
41
42
  export {
42
- establishBffAuthSession,
43
+ BffRouteMissingError,
44
+ exchangeAuthCodeViaBff,
45
+ exchangeShellSessionCode,
46
+ isBffRouteMissingError,
43
47
  logoutBffAuthSession,
48
+ markBffRoutesUnavailable,
49
+ probeBffAuthRoutes,
50
+ rememberHostCookieSession,
44
51
  refreshBffAuthSession,
52
+ resetBffRouteProbeForTests,
53
+ resolveBffAuthRoutes,
45
54
  } from './bffAuthClient';
46
- export { isBffAuthEnabledFromConfig, useIsBffAuthEnabled } from './isBffAuthEnabled';
55
+ export {
56
+ isBffAuthEnabledFromConfig,
57
+ isBffAuthExplicitlyDisabled,
58
+ useIsBffAuthEnabled,
59
+ } from './isBffAuthEnabled';
47
60
  export { decodeJwtPayload } from './decodeJwtPayload';
48
61
  export { formatProviderLabel } from './formatProviderLabel';
49
62
  export { getAccessTokenFromSdkSettings, getUserFromSdkSettings } from './getUserFromSdkSettings';
@@ -52,7 +65,12 @@ export { getPreferredBackendProvider } from './getPreferredBackendProvider';
52
65
  export { getProviderVisual } from './getProviderVisual';
53
66
  export { isLoginMethod } from './isLoginMethod';
54
67
  export { resolveLoginSettings } from './resolveLoginSettings';
55
- export { canRestoreStoredSession } from './canRestoreStoredSession';
68
+ export {
69
+ canRestoreStoredSession,
70
+ isUnauthorizedRefreshError,
71
+ planStoredSessionBoot,
72
+ } from './canRestoreStoredSession';
73
+ export type { StoredSessionBootPlan } from './canRestoreStoredSession';
56
74
  export { isSessionExpired } from './isSessionExpired';
57
75
  export { isTokenAutoRefreshDisabled } from './isTokenAutoRefreshDisabled';
58
76
  export { normalizeAuthSettings } from './normalizeAuthSettings';
@@ -1,11 +1,19 @@
1
1
  import { useConfig } from '../../config/useConfig';
2
2
 
3
- /** Whether same-origin BFF auth routes should handle refresh (HttpOnly cookie). */
3
+ /**
4
+ * `security.bffAuth.enabled === true`.
5
+ * The page does not treat this as proof the routes exist. See `resolveBffAuthRoutes`.
6
+ */
4
7
  export const isBffAuthEnabledFromConfig = (
5
8
  security: { bffAuth?: { enabled?: boolean } } | undefined,
6
9
  ): boolean => security?.bffAuth?.enabled === true;
7
10
 
8
- /** React hook — reads `security.bffAuth.enabled` from shell config. */
11
+ /** `security.bffAuth.enabled === false` turns the host routes and the page probe off. */
12
+ export const isBffAuthExplicitlyDisabled = (
13
+ security: { bffAuth?: { enabled?: boolean } } | undefined,
14
+ ): boolean => security?.bffAuth?.enabled === false;
15
+
16
+ /** React hook. Reads the explicit `security.bffAuth.enabled` flag, not the probe. */
9
17
  export const useIsBffAuthEnabled = (): boolean => {
10
18
  const { config } = useConfig();
11
19
  return isBffAuthEnabledFromConfig(config.security);
@@ -25,6 +25,7 @@ describe('normalizeAuthSettings', () => {
25
25
  methods: [],
26
26
  oauthProviders: [],
27
27
  oauthClients: [],
28
+ logoutUrl: null,
28
29
  });
29
30
 
30
31
  const result = normalizeAuthSettings([{ loginMethod: 'both', oauth_provider: 'GitLab' }]);
@@ -57,4 +58,12 @@ describe('normalizeAuthSettings', () => {
57
58
  ]);
58
59
  expect(result.oauthProviders).toEqual(expect.arrayContaining(['github', 'google']));
59
60
  });
61
+
62
+ it('reads logout_url and ignores a value that is not an http(s) URL', () => {
63
+ expect(
64
+ normalizeAuthSettings({ logout_url: 'https://auth.example.com/oauth/logout' }).logoutUrl,
65
+ ).toBe('https://auth.example.com/oauth/logout');
66
+ expect(normalizeAuthSettings({ logout_url: 'javascript:alert(1)' }).logoutUrl).toBeNull();
67
+ expect(normalizeAuthSettings({ methods: ['oauth'] }).logoutUrl).toBeNull();
68
+ });
60
69
  });
@@ -1,4 +1,5 @@
1
1
  import type { AuthSettings, LoginMethod } from '../types';
2
+ import { readIdentityLogoutUrl } from './identityBrowserLogout';
2
3
  import { isLoginMethod } from './isLoginMethod';
3
4
 
4
5
  const NON_OAUTH_EXTERNAL_PROVIDERS = new Set(['email', 'phone', 'sms']);
@@ -8,7 +9,7 @@ const WEB3_EXTERNAL_PROVIDERS = new Set(['ethereum', 'solana', 'web3_ethereum',
8
9
  export const normalizeAuthSettings = (payload: unknown): AuthSettings => {
9
10
  const record = Array.isArray(payload) ? payload[0] : payload;
10
11
  if (!record || typeof record !== 'object') {
11
- return { methods: [], oauthProviders: [], oauthClients: [] };
12
+ return { methods: [], oauthProviders: [], oauthClients: [], logoutUrl: null };
12
13
  }
13
14
 
14
15
  const obj = record as Record<string, unknown>;
@@ -67,5 +68,6 @@ export const normalizeAuthSettings = (payload: unknown): AuthSettings => {
67
68
  methods: Array.from(methods),
68
69
  oauthProviders: Array.from(oauthProvidersSet),
69
70
  oauthClients,
71
+ logoutUrl: readIdentityLogoutUrl(obj.logout_url),
70
72
  };
71
73
  };
@@ -1,9 +1,13 @@
1
- import { describe, expect, test } from 'vitest';
1
+ import { afterEach, describe, expect, test, vi } from 'vitest';
2
2
  import { createPkcePair, generateCodeChallenge, generateCodeVerifier } from './pkce';
3
3
 
4
4
  const UNRESERVED = /^[A-Za-z0-9\-._~]+$/;
5
5
 
6
6
  describe('PKCE S256', () => {
7
+ afterEach(() => {
8
+ vi.unstubAllGlobals();
9
+ });
10
+
7
11
  test('verifier is 43 unreserved characters and the challenge is its SHA-256', async () => {
8
12
  const verifier = generateCodeVerifier();
9
13
  expect(verifier.length).toBe(43);
@@ -33,4 +37,28 @@ describe('PKCE S256', () => {
33
37
  test('rejects a verifier outside the identity-service length', async () => {
34
38
  await expect(generateCodeChallenge('short')).rejects.toThrow(/43 to 128/);
35
39
  });
40
+
41
+ test('matches the RFC 7636 Appendix B S256 vector', async () => {
42
+ // https://datatracker.ietf.org/doc/html/rfc7636#appendix-B
43
+ const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
44
+ await expect(generateCodeChallenge(verifier)).resolves.toBe(
45
+ 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
46
+ );
47
+ });
48
+
49
+ test('falls back when crypto.subtle is missing (HTTP LAN / Tailscale)', async () => {
50
+ vi.stubGlobal('crypto', {
51
+ getRandomValues: crypto.getRandomValues.bind(crypto),
52
+ subtle: undefined,
53
+ });
54
+
55
+ const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
56
+ await expect(generateCodeChallenge(verifier)).resolves.toBe(
57
+ 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
58
+ );
59
+
60
+ const pair = await createPkcePair();
61
+ expect(pair.verifier.length).toBe(43);
62
+ expect(pair.challenge.length).toBe(43);
63
+ });
36
64
  });
@@ -1,6 +1,9 @@
1
1
  /**
2
2
  * PKCE S256 (RFC 7636). The verifier stays in the app. Only the challenge is sent.
3
3
  * 32 random bytes encode to 43 base64url characters, inside the 43-128 range.
4
+ *
5
+ * `crypto.subtle` is missing on non-secure HTTP origins (LAN / Tailscale IPs).
6
+ * SHA-256 then falls back to a pure JS digest so magic link and OAuth still work.
4
7
  */
5
8
 
6
9
  const VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;
@@ -13,6 +16,107 @@ function base64UrlEncode(bytes: Uint8Array): string {
13
16
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
14
17
  }
15
18
 
19
+ /** Compact SHA-256 for insecure browser contexts where SubtleCrypto is unavailable. */
20
+ function sha256Fallback(message: Uint8Array): Uint8Array {
21
+ const K = new Uint32Array([
22
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
23
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
24
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
25
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
26
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
27
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
28
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
29
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
30
+ ]);
31
+
32
+ const bitLen = message.length * 8;
33
+ const withPad = new Uint8Array((message.length + 9 + 63) & ~63);
34
+ withPad.set(message);
35
+ withPad[message.length] = 0x80;
36
+ const view = new DataView(withPad.buffer);
37
+ view.setUint32(withPad.length - 4, bitLen >>> 0, false);
38
+ // Messages used here are short PKCE verifiers; high 32 bits stay 0.
39
+
40
+ let h0 = 0x6a09e667;
41
+ let h1 = 0xbb67ae85;
42
+ let h2 = 0x3c6ef372;
43
+ let h3 = 0xa54ff53a;
44
+ let h4 = 0x510e527f;
45
+ let h5 = 0x9b05688c;
46
+ let h6 = 0x1f83d9ab;
47
+ let h7 = 0x5be0cd19;
48
+
49
+ const w = new Uint32Array(64);
50
+ const rotr = (x: number, n: number) => (x >>> n) | (x << (32 - n));
51
+
52
+ for (let i = 0; i < withPad.length; i += 64) {
53
+ for (let t = 0; t < 16; t += 1) {
54
+ w[t] = view.getUint32(i + t * 4, false);
55
+ }
56
+ for (let t = 16; t < 64; t += 1) {
57
+ const s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >>> 3);
58
+ const s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >>> 10);
59
+ w[t] = (w[t - 16] + s0 + w[t - 7] + s1) >>> 0;
60
+ }
61
+
62
+ let a = h0;
63
+ let b = h1;
64
+ let c = h2;
65
+ let d = h3;
66
+ let e = h4;
67
+ let f = h5;
68
+ let g = h6;
69
+ let h = h7;
70
+
71
+ for (let t = 0; t < 64; t += 1) {
72
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
73
+ const ch = (e & f) ^ (~e & g);
74
+ const temp1 = (h + S1 + ch + K[t] + w[t]) >>> 0;
75
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
76
+ const maj = (a & b) ^ (a & c) ^ (b & c);
77
+ const temp2 = (S0 + maj) >>> 0;
78
+
79
+ h = g;
80
+ g = f;
81
+ f = e;
82
+ e = (d + temp1) >>> 0;
83
+ d = c;
84
+ c = b;
85
+ b = a;
86
+ a = (temp1 + temp2) >>> 0;
87
+ }
88
+
89
+ h0 = (h0 + a) >>> 0;
90
+ h1 = (h1 + b) >>> 0;
91
+ h2 = (h2 + c) >>> 0;
92
+ h3 = (h3 + d) >>> 0;
93
+ h4 = (h4 + e) >>> 0;
94
+ h5 = (h5 + f) >>> 0;
95
+ h6 = (h6 + g) >>> 0;
96
+ h7 = (h7 + h) >>> 0;
97
+ }
98
+
99
+ const out = new Uint8Array(32);
100
+ const outView = new DataView(out.buffer);
101
+ outView.setUint32(0, h0, false);
102
+ outView.setUint32(4, h1, false);
103
+ outView.setUint32(8, h2, false);
104
+ outView.setUint32(12, h3, false);
105
+ outView.setUint32(16, h4, false);
106
+ outView.setUint32(20, h5, false);
107
+ outView.setUint32(24, h6, false);
108
+ outView.setUint32(28, h7, false);
109
+ return out;
110
+ }
111
+
112
+ async function sha256(bytes: Uint8Array): Promise<Uint8Array> {
113
+ const subtle = globalThis.crypto?.subtle;
114
+ if (subtle?.digest) {
115
+ return new Uint8Array(await subtle.digest('SHA-256', bytes));
116
+ }
117
+ return sha256Fallback(bytes);
118
+ }
119
+
16
120
  export function generateCodeVerifier(): string {
17
121
  const bytes = new Uint8Array(32);
18
122
  crypto.getRandomValues(bytes);
@@ -27,8 +131,8 @@ export async function generateCodeChallenge(verifier: string): Promise<string> {
27
131
  if (!VERIFIER_PATTERN.test(verifier)) {
28
132
  throw new Error('PKCE verifier must be 43 to 128 unreserved characters.');
29
133
  }
30
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
31
- return base64UrlEncode(new Uint8Array(digest));
134
+ const digest = await sha256(new TextEncoder().encode(verifier));
135
+ return base64UrlEncode(digest);
32
136
  }
33
137
 
34
138
  export async function createPkcePair(): Promise<{ verifier: string; challenge: string }> {