@shellui/core 0.6.2 → 0.7.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/schemas/shellui.config.schema.json +116 -72
- package/src/app.tsx +2 -0
- package/src/components/ContentView.tsx +2 -22
- package/src/components/iframeUrlSafety.spec.ts +67 -0
- package/src/components/iframeUrlSafety.ts +50 -0
- package/src/features/auth/AuthProvider.tsx +24 -1
- package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
- package/src/features/auth/appBackend/appBackendSessions.spec.ts +195 -0
- package/src/features/auth/appBackend/appBackendSessions.ts +292 -0
- package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
- package/src/features/auth/appBackend/frameAuth.ts +167 -0
- package/src/features/auth/appBackend/identity.spec.ts +201 -0
- package/src/features/auth/appBackend/identity.ts +173 -0
- package/src/features/auth/appBackend/silentSignIn.spec.ts +207 -0
- package/src/features/auth/appBackend/silentSignIn.ts +240 -0
- package/src/features/auth/backends/shellui.spec.ts +51 -19
- package/src/features/auth/backends/shellui.ts +20 -5
- package/src/features/auth/backends/types.ts +7 -2
- package/src/features/auth/components/LoginView.tsx +40 -18
- package/src/features/auth/components/OAuthCallbackView.tsx +33 -4
- package/src/features/auth/utils/authRequestError.ts +3 -0
- package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
- package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
- package/src/features/auth/utils/index.ts +14 -1
- package/src/features/auth/utils/loginCancelTarget.spec.ts +73 -0
- package/src/features/auth/utils/loginCancelTarget.ts +45 -0
- package/src/features/auth/utils/loginPanelFrame.spec.ts +24 -0
- package/src/features/auth/utils/loginPanelFrame.ts +14 -0
- package/src/features/auth/utils/webPkce.spec.ts +119 -0
- package/src/features/auth/utils/webPkce.ts +169 -0
- package/src/features/config/types.ts +41 -0
- package/src/features/settings/SettingsProvider.tsx +45 -32
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +374 -0
- package/src/features/settings/utils/buildSettingsForPropagation.ts +61 -33
- package/src/i18n/translations/en/common.json +2 -0
- package/src/i18n/translations/fr/common.json +2 -0
- package/src/index.ts +1 -0
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { describe, expect, test } from 'vitest';
|
|
2
2
|
import { SHELLUI_AUTH_CODE_PARAM } from '../constants/oauth';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
buildOAuthSessionRedirectTo,
|
|
5
|
+
resolveOAuthSessionRedirectTo,
|
|
6
|
+
} from './buildOAuthSessionRedirectTo';
|
|
4
7
|
|
|
5
8
|
describe('buildOAuthSessionRedirectTo', () => {
|
|
6
9
|
test('strips shellui_auth_code and keeps other query params', () => {
|
|
@@ -20,3 +23,41 @@ describe('buildOAuthSessionRedirectTo', () => {
|
|
|
20
23
|
).toBe('http://127.0.0.1:8765/callback');
|
|
21
24
|
});
|
|
22
25
|
});
|
|
26
|
+
|
|
27
|
+
describe('resolveOAuthSessionRedirectTo', () => {
|
|
28
|
+
const start =
|
|
29
|
+
'https://playground.shellui.com/login/callback?provider=github&shellui_pkce_flow=o0123';
|
|
30
|
+
|
|
31
|
+
test('uses the stored start value when the host added a trailing slash', () => {
|
|
32
|
+
expect(
|
|
33
|
+
resolveOAuthSessionRedirectTo(
|
|
34
|
+
start,
|
|
35
|
+
'https://playground.shellui.com',
|
|
36
|
+
'/login/callback/',
|
|
37
|
+
'?provider=github&shellui_pkce_flow=o0123&shellui_auth_code=abc',
|
|
38
|
+
),
|
|
39
|
+
).toBe(start);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('falls back to the current URL when nothing was stored', () => {
|
|
43
|
+
expect(
|
|
44
|
+
resolveOAuthSessionRedirectTo(
|
|
45
|
+
null,
|
|
46
|
+
'https://playground.shellui.com',
|
|
47
|
+
'/login/callback/',
|
|
48
|
+
'?provider=github&shellui_auth_code=abc',
|
|
49
|
+
),
|
|
50
|
+
).toBe('https://playground.shellui.com/login/callback/?provider=github');
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('ignores a stored value for another origin', () => {
|
|
54
|
+
expect(
|
|
55
|
+
resolveOAuthSessionRedirectTo(
|
|
56
|
+
'https://evil.test/login/callback',
|
|
57
|
+
'https://playground.shellui.com',
|
|
58
|
+
'/login/callback',
|
|
59
|
+
'?shellui_auth_code=abc',
|
|
60
|
+
),
|
|
61
|
+
).toBe('https://playground.shellui.com/login/callback');
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -15,3 +15,26 @@ export function buildOAuthSessionRedirectTo(
|
|
|
15
15
|
url.search = params.toString();
|
|
16
16
|
return url.toString();
|
|
17
17
|
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Pick the `redirect_to` for the session exchange. Identity compares it exactly
|
|
21
|
+
* with the value sent at sign-in start, so prefer that stored value. A static
|
|
22
|
+
* host can add a trailing slash on the way back (GitHub Pages turns
|
|
23
|
+
* `/login/callback` into `/login/callback/`). Fall back to the current URL when
|
|
24
|
+
* nothing was stored or the stored value is for another origin.
|
|
25
|
+
*/
|
|
26
|
+
export function resolveOAuthSessionRedirectTo(
|
|
27
|
+
storedRedirectTo: string | null | undefined,
|
|
28
|
+
origin: string,
|
|
29
|
+
pathname: string,
|
|
30
|
+
search: string,
|
|
31
|
+
): string {
|
|
32
|
+
if (storedRedirectTo) {
|
|
33
|
+
try {
|
|
34
|
+
if (new URL(storedRedirectTo).origin === origin) return storedRedirectTo;
|
|
35
|
+
} catch {
|
|
36
|
+
// invalid stored value: rebuild from the current URL
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return buildOAuthSessionRedirectTo(origin, pathname, search);
|
|
40
|
+
}
|
|
@@ -4,7 +4,11 @@ export {
|
|
|
4
4
|
getShellUILoginDeviceId,
|
|
5
5
|
} from './clientLoginContext';
|
|
6
6
|
export { buildAuthUrlWithNext } from './buildAuthUrlWithNext';
|
|
7
|
-
export {
|
|
7
|
+
export { getLoginCancelTarget, isPublicNavigationPage } from './loginCancelTarget';
|
|
8
|
+
export {
|
|
9
|
+
buildOAuthSessionRedirectTo,
|
|
10
|
+
resolveOAuthSessionRedirectTo,
|
|
11
|
+
} from './buildOAuthSessionRedirectTo';
|
|
8
12
|
export { buildSessionFromParams } from './buildSessionFromParams';
|
|
9
13
|
export {
|
|
10
14
|
buildSessionFromTokenPayload,
|
|
@@ -55,3 +59,12 @@ export { normalizeRedirectPath } from './normalizeRedirectPath';
|
|
|
55
59
|
export { shareInFlight } from './shareInFlight';
|
|
56
60
|
export type { InFlightSlot } from './shareInFlight';
|
|
57
61
|
export { toAuthSessionFromSettingsUser } from './toAuthSessionFromSettingsUser';
|
|
62
|
+
export {
|
|
63
|
+
WEB_PKCE_FLOW_PARAM,
|
|
64
|
+
prepareWebPkce,
|
|
65
|
+
takeWebPkceVerifier,
|
|
66
|
+
takeWebPkceFlow,
|
|
67
|
+
clearWebPkce,
|
|
68
|
+
isWebPkceErrorCode,
|
|
69
|
+
isMagicLinkFlowId,
|
|
70
|
+
} 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,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
|
+
}
|
|
@@ -62,6 +62,27 @@ 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
|
+
* Email service for this app. Omit to use the shell `email` when the app uses
|
|
74
|
+
* the shell identity server. When `backend` names a different server and this
|
|
75
|
+
* is omitted, the app receives no email URL.
|
|
76
|
+
*/
|
|
77
|
+
email?: EmailConfig;
|
|
78
|
+
/**
|
|
79
|
+
* Storage service for this app. Same fallback as `email`.
|
|
80
|
+
*/
|
|
81
|
+
storage?: StorageConfig;
|
|
82
|
+
/**
|
|
83
|
+
* Hosting service for this app. Same fallback as `email`.
|
|
84
|
+
*/
|
|
85
|
+
hosting?: HostingConfig;
|
|
65
86
|
}
|
|
66
87
|
|
|
67
88
|
export interface NavigationGroup {
|
|
@@ -216,6 +237,26 @@ export interface AuthConfig {
|
|
|
216
237
|
desktopScheme?: string;
|
|
217
238
|
}
|
|
218
239
|
|
|
240
|
+
/**
|
|
241
|
+
* Identity server for one embedded app when it differs from the shell `backend`.
|
|
242
|
+
* `type` defaults to the shell backend type. `companyId` is not copied from the shell.
|
|
243
|
+
*/
|
|
244
|
+
export interface AppBackendConfig {
|
|
245
|
+
/** `shellui` or `supabase`. When omitted, the shell backend type is used. */
|
|
246
|
+
type?: BackendType;
|
|
247
|
+
/** Base URL of this app's identity server. */
|
|
248
|
+
url: string;
|
|
249
|
+
/** Tenant id for this server. Not taken from the shell `backend.companyId`. */
|
|
250
|
+
companyId?: string | number;
|
|
251
|
+
/** Public key when `type` is `supabase`. */
|
|
252
|
+
publishableKey?: string;
|
|
253
|
+
/**
|
|
254
|
+
* OAuth provider for silent sign-in, such as `google`.
|
|
255
|
+
* When omitted, the shell uses the first `backend.login.oauthProviders` entry.
|
|
256
|
+
*/
|
|
257
|
+
provider?: string;
|
|
258
|
+
}
|
|
259
|
+
|
|
219
260
|
/** Backend API configuration. */
|
|
220
261
|
export interface BackendConfig {
|
|
221
262
|
/** Backend provider type. */
|