@shellui/core 0.6.2 → 0.7.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +29 -2
- package/src/features/auth/utils/authRequestError.ts +3 -0
- package/src/features/auth/utils/index.ts +9 -0
- 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 +96 -0
- package/src/features/auth/utils/webPkce.ts +152 -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
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { describe, expect, test } from 'vitest';
|
|
2
|
+
import type { NavigationItem } from '../../config/types';
|
|
3
|
+
import { getLoginCancelTarget, isPublicNavigationPage } from './loginCancelTarget';
|
|
4
|
+
|
|
5
|
+
const item = (path: string, extra: Partial<NavigationItem> = {}): NavigationItem => ({
|
|
6
|
+
label: path || 'Home',
|
|
7
|
+
path,
|
|
8
|
+
url: `/app/#/${path}`,
|
|
9
|
+
...extra,
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
describe('getLoginCancelTarget', () => {
|
|
13
|
+
test('goes to / when the homepage is public', () => {
|
|
14
|
+
expect(getLoginCancelTarget({ navigation: [item(''), item('docs')] })).toBe('/');
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('goes to / when there is no root item (HomeView)', () => {
|
|
18
|
+
expect(getLoginCancelTarget({ navigation: [item('files', { requiresAuth: true })] })).toBe('/');
|
|
19
|
+
expect(getLoginCancelTarget({ navigation: [] })).toBe('/');
|
|
20
|
+
expect(getLoginCancelTarget(undefined)).toBe('/');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('goes to the first public page when the homepage requires auth', () => {
|
|
24
|
+
const navigation = [
|
|
25
|
+
item('', { requiresAuth: true }),
|
|
26
|
+
{ title: 'Group', items: [item('files', { requiresAuth: true }), item('docs')] },
|
|
27
|
+
];
|
|
28
|
+
expect(getLoginCancelTarget({ navigation })).toBe('/docs');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test('returns null when every page requires auth', () => {
|
|
32
|
+
const navigation = [
|
|
33
|
+
item('', { requiresAuth: true }),
|
|
34
|
+
item('files', { requiresAuth: true }),
|
|
35
|
+
item('admin', { requiresStaff: true }),
|
|
36
|
+
item('private', { hideWhenLoggedOut: true }),
|
|
37
|
+
];
|
|
38
|
+
expect(getLoginCancelTarget({ navigation })).toBeNull();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('ignores settings, login, external, dev-mode and hidden entries', () => {
|
|
42
|
+
const navigation = [
|
|
43
|
+
item('', { requiresAuth: true }),
|
|
44
|
+
item('settings', { url: '/__settings', openIn: 'modal' }),
|
|
45
|
+
item('login', { url: '/login', openIn: 'modal' }),
|
|
46
|
+
item('login-page', { url: '/login' }),
|
|
47
|
+
item('website', { url: 'https://shellui.com/', openIn: 'external' }),
|
|
48
|
+
item('drawer', { openIn: 'drawer' }),
|
|
49
|
+
item('dev', { requiresDevMode: true }),
|
|
50
|
+
item('secret', { hidden: true }),
|
|
51
|
+
];
|
|
52
|
+
expect(getLoginCancelTarget({ navigation })).toBeNull();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('follows start_url', () => {
|
|
56
|
+
const navigation = [item('files', { requiresAuth: true }), item('docs')];
|
|
57
|
+
expect(getLoginCancelTarget({ navigation, start_url: '/docs' })).toBe('/');
|
|
58
|
+
expect(getLoginCancelTarget({ navigation, start_url: 'files' })).toBe('/docs');
|
|
59
|
+
expect(
|
|
60
|
+
getLoginCancelTarget({
|
|
61
|
+
navigation: [item('files', { requiresAuth: true })],
|
|
62
|
+
start_url: '/files',
|
|
63
|
+
}),
|
|
64
|
+
).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('isPublicNavigationPage', () => {
|
|
69
|
+
test('plain page items are public', () => {
|
|
70
|
+
expect(isPublicNavigationPage(item('docs'))).toBe(true);
|
|
71
|
+
expect(isPublicNavigationPage(item('docs', { openIn: 'default' }))).toBe(true);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { NavigationGroup, NavigationItem } from '../../config/types';
|
|
2
|
+
import {
|
|
3
|
+
findMatchingNavigationItem,
|
|
4
|
+
flattenNavigationItems,
|
|
5
|
+
getNavPathPrefix,
|
|
6
|
+
isLoginNavigationUrl,
|
|
7
|
+
} from '../../layouts/utils';
|
|
8
|
+
|
|
9
|
+
type CancelTargetConfig = {
|
|
10
|
+
navigation?: (NavigationItem | NavigationGroup)[];
|
|
11
|
+
start_url?: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/** A nav item a signed-out user can open as a page in the main area. */
|
|
15
|
+
export function isPublicNavigationPage(item: NavigationItem): boolean {
|
|
16
|
+
if (item.requiresAuth || item.requiresStaff || item.hideWhenLoggedOut) return false;
|
|
17
|
+
if (item.requiresDevMode || item.hidden) return false;
|
|
18
|
+
if (item.openIn && item.openIn !== 'default') return false;
|
|
19
|
+
return !isLoginNavigationUrl(item.url);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Where the login page Cancel button should go, or `null` to hide it.
|
|
24
|
+
* Prefers `/` (or `start_url`) when public, else the first public nav page.
|
|
25
|
+
* `/` without a root item or `start_url` shows the built-in HomeView, which is public.
|
|
26
|
+
*/
|
|
27
|
+
export function getLoginCancelTarget(config: CancelTargetConfig | undefined): string | null {
|
|
28
|
+
const items = flattenNavigationItems(config?.navigation ?? []);
|
|
29
|
+
const startUrl = config?.start_url?.trim();
|
|
30
|
+
const landing = startUrl ? (startUrl.startsWith('/') ? startUrl : `/${startUrl}`) : '/';
|
|
31
|
+
const landingPath = landing.split(/[?#]/)[0] || '/';
|
|
32
|
+
|
|
33
|
+
const landingItem = findMatchingNavigationItem(items, landingPath);
|
|
34
|
+
if (!landingItem) {
|
|
35
|
+
// No nav item owns the landing path: HomeView or a built-in shell route.
|
|
36
|
+
if (!startUrl || !isLoginNavigationUrl(landingPath)) return '/';
|
|
37
|
+
} else if (isPublicNavigationPage(landingItem)) {
|
|
38
|
+
return '/';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const fallback = items.find(
|
|
42
|
+
(item) => item !== landingItem && item.path !== '' && isPublicNavigationPage(item),
|
|
43
|
+
);
|
|
44
|
+
return fallback ? getNavPathPrefix(fallback) : null;
|
|
45
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const addIframe = vi.fn(() => 'frame-1');
|
|
4
|
+
const removeIframe = vi.fn();
|
|
5
|
+
vi.mock('@shellui/sdk', () => ({ addIframe, removeIframe }));
|
|
6
|
+
|
|
7
|
+
const { registerLoginPanelFrame } = await import('./loginPanelFrame');
|
|
8
|
+
|
|
9
|
+
describe('registerLoginPanelFrame', () => {
|
|
10
|
+
it('registers the panel iframe so settings reach it, and unregisters on cleanup', () => {
|
|
11
|
+
const node = {} as HTMLIFrameElement;
|
|
12
|
+
const cleanup = registerLoginPanelFrame(node);
|
|
13
|
+
expect(addIframe).toHaveBeenCalledWith(node);
|
|
14
|
+
expect(removeIframe).not.toHaveBeenCalled();
|
|
15
|
+
cleanup();
|
|
16
|
+
expect(removeIframe).toHaveBeenCalledWith('frame-1');
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('does nothing without a node', () => {
|
|
20
|
+
addIframe.mockClear();
|
|
21
|
+
registerLoginPanelFrame(null)();
|
|
22
|
+
expect(addIframe).not.toHaveBeenCalled();
|
|
23
|
+
});
|
|
24
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { addIframe, removeIframe } from '@shellui/sdk';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Register the login side panel iframe with the SDK frame registry so it receives
|
|
5
|
+
* SHELLUI_SETTINGS broadcasts (theme, language) like main content frames.
|
|
6
|
+
* Returns a cleanup that unregisters it.
|
|
7
|
+
*/
|
|
8
|
+
export function registerLoginPanelFrame(node: HTMLIFrameElement | null): () => void {
|
|
9
|
+
if (!node) return () => {};
|
|
10
|
+
const iframeId = addIframe(node);
|
|
11
|
+
return () => {
|
|
12
|
+
removeIframe(iframeId);
|
|
13
|
+
};
|
|
14
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { generateCodeChallenge } from './pkce';
|
|
3
|
+
import {
|
|
4
|
+
WEB_PKCE_FLOW_PARAM,
|
|
5
|
+
isMagicLinkFlowId,
|
|
6
|
+
isWebPkceErrorCode,
|
|
7
|
+
prepareWebPkce,
|
|
8
|
+
takeWebPkceVerifier,
|
|
9
|
+
} from './webPkce';
|
|
10
|
+
|
|
11
|
+
function memoryStorage(seed: [string, string][] = []): Storage {
|
|
12
|
+
const map = new Map<string, string>(seed);
|
|
13
|
+
return {
|
|
14
|
+
get length() {
|
|
15
|
+
return map.size;
|
|
16
|
+
},
|
|
17
|
+
key: (i: number) => Array.from(map.keys())[i] ?? null,
|
|
18
|
+
getItem: (k: string) => map.get(k) ?? null,
|
|
19
|
+
setItem: (k: string, v: string) => void map.set(k, String(v)),
|
|
20
|
+
removeItem: (k: string) => void map.delete(k),
|
|
21
|
+
clear: () => map.clear(),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function storedVerifier(store: Storage): string {
|
|
26
|
+
const keys = Array.from({ length: store.length }, (_, i) => store.key(i) as string);
|
|
27
|
+
const key = keys.find((k) => k.startsWith('shellui.auth.pkce.'));
|
|
28
|
+
expect(key).toBeTruthy();
|
|
29
|
+
return (JSON.parse(store.getItem(key as string) as string) as { verifier: string }).verifier;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('webPkce', () => {
|
|
33
|
+
beforeEach(() => {
|
|
34
|
+
vi.stubGlobal('sessionStorage', memoryStorage());
|
|
35
|
+
vi.stubGlobal('localStorage', memoryStorage());
|
|
36
|
+
});
|
|
37
|
+
afterEach(() => {
|
|
38
|
+
vi.useRealTimers();
|
|
39
|
+
vi.unstubAllGlobals();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('adds only the flow id to redirect_to and keeps the verifier in sessionStorage', async () => {
|
|
43
|
+
const prepared = await prepareWebPkce(
|
|
44
|
+
'https://app.test/login/callback?provider=google',
|
|
45
|
+
'oauth',
|
|
46
|
+
);
|
|
47
|
+
const url = new URL(prepared.redirectTo);
|
|
48
|
+
expect(url.searchParams.get('provider')).toBe('google');
|
|
49
|
+
expect(url.searchParams.get(WEB_PKCE_FLOW_PARAM)).toBe(prepared.flowId);
|
|
50
|
+
const verifier = storedVerifier(sessionStorage);
|
|
51
|
+
expect(verifier).toMatch(/^[A-Za-z0-9_-]{43,128}$/);
|
|
52
|
+
expect(prepared.redirectTo).not.toContain(verifier);
|
|
53
|
+
expect(prepared.challenge).toBe(await generateCodeChallenge(verifier));
|
|
54
|
+
expect(localStorage.length).toBe(0);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('keeps concurrent flows apart and is single use', async () => {
|
|
58
|
+
const a = await prepareWebPkce('https://app.test/cb', 'oauth');
|
|
59
|
+
const b = await prepareWebPkce('https://app.test/cb', 'oauth');
|
|
60
|
+
expect(a.flowId).not.toBe(b.flowId);
|
|
61
|
+
const va = takeWebPkceVerifier(a.flowId);
|
|
62
|
+
const vb = takeWebPkceVerifier(b.flowId);
|
|
63
|
+
expect(va).toBeTruthy();
|
|
64
|
+
expect(vb).toBeTruthy();
|
|
65
|
+
expect(va).not.toBe(vb);
|
|
66
|
+
expect(takeWebPkceVerifier(a.flowId)).toBeNull();
|
|
67
|
+
expect(sessionStorage.length).toBe(0);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('stores a magic link verifier in localStorage only, readable from another tab', async () => {
|
|
71
|
+
const prepared = await prepareWebPkce('https://app.test/cb', 'magic_link');
|
|
72
|
+
expect(isMagicLinkFlowId(prepared.flowId)).toBe(true);
|
|
73
|
+
expect(sessionStorage.length).toBe(0);
|
|
74
|
+
sessionStorage.clear();
|
|
75
|
+
expect(takeWebPkceVerifier(prepared.flowId)).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
76
|
+
expect(localStorage.length).toBe(0);
|
|
77
|
+
expect(takeWebPkceVerifier(prepared.flowId)).toBeNull();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('expires a magic link verifier after 15 minutes', async () => {
|
|
81
|
+
vi.useFakeTimers();
|
|
82
|
+
const prepared = await prepareWebPkce('https://app.test/cb', 'magic_link');
|
|
83
|
+
vi.advanceTimersByTime(15 * 60 * 1000 + 1);
|
|
84
|
+
expect(takeWebPkceVerifier(prepared.flowId)).toBeNull();
|
|
85
|
+
expect(localStorage.length).toBe(0);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('rejects malformed flow ids and knows the PKCE error codes', () => {
|
|
89
|
+
expect(takeWebPkceVerifier('../x')).toBeNull();
|
|
90
|
+
expect(takeWebPkceVerifier(null)).toBeNull();
|
|
91
|
+
expect(isMagicLinkFlowId(`o${'0'.repeat(32)}`)).toBe(false);
|
|
92
|
+
expect(isWebPkceErrorCode('pkce_verification_failed')).toBe(true);
|
|
93
|
+
expect(isWebPkceErrorCode('pkce_required')).toBe(true);
|
|
94
|
+
expect(isWebPkceErrorCode('other')).toBe(false);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
@@ -0,0 +1,152 @@
|
|
|
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
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface PreparedWebPkce {
|
|
37
|
+
flowId: string;
|
|
38
|
+
challenge: string;
|
|
39
|
+
/** `redirectTo` with the flow id added. */
|
|
40
|
+
redirectTo: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function store(kind: 'session' | 'local'): Storage | null {
|
|
44
|
+
try {
|
|
45
|
+
const s = kind === 'session' ? globalThis.sessionStorage : globalThis.localStorage;
|
|
46
|
+
return s ?? null;
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function randomFlowId(kind: WebPkceFlowKind): string {
|
|
53
|
+
const bytes = new Uint8Array(16);
|
|
54
|
+
crypto.getRandomValues(bytes);
|
|
55
|
+
const mark = kind === 'magic_link' ? MAGIC_LINK_FLOW_MARK : 'o';
|
|
56
|
+
return mark + Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function write(s: Storage | null, key: string, value: StoredVerifier): boolean {
|
|
60
|
+
if (!s) return false;
|
|
61
|
+
try {
|
|
62
|
+
s.setItem(key, JSON.stringify(value));
|
|
63
|
+
return true;
|
|
64
|
+
} catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function readAndRemove(s: Storage | null, key: string, maxAgeMs: number): string | null {
|
|
70
|
+
if (!s) return null;
|
|
71
|
+
try {
|
|
72
|
+
const raw = s.getItem(key);
|
|
73
|
+
if (!raw) return null;
|
|
74
|
+
s.removeItem(key);
|
|
75
|
+
const parsed = JSON.parse(raw) as StoredVerifier;
|
|
76
|
+
if (typeof parsed?.verifier !== 'string' || typeof parsed.createdAt !== 'number') return null;
|
|
77
|
+
if (Date.now() - parsed.createdAt > maxAgeMs) return null;
|
|
78
|
+
return parsed.verifier;
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Drop expired magic link verifiers left by flows that were never finished. */
|
|
85
|
+
function pruneMagicLinkVerifiers(): void {
|
|
86
|
+
const s = store('local');
|
|
87
|
+
if (!s) return;
|
|
88
|
+
try {
|
|
89
|
+
for (let i = s.length - 1; i >= 0; i -= 1) {
|
|
90
|
+
const key = s.key(i);
|
|
91
|
+
if (!key?.startsWith(MAGIC_LINK_PREFIX)) continue;
|
|
92
|
+
try {
|
|
93
|
+
const parsed = JSON.parse(s.getItem(key) ?? '') as StoredVerifier;
|
|
94
|
+
if (Date.now() - parsed.createdAt <= MAGIC_LINK_MAX_AGE_MS) continue;
|
|
95
|
+
} catch {
|
|
96
|
+
// unreadable: remove
|
|
97
|
+
}
|
|
98
|
+
s.removeItem(key);
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
// ignore
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function prepareWebPkce(
|
|
106
|
+
redirectTo: string,
|
|
107
|
+
kind: WebPkceFlowKind,
|
|
108
|
+
): Promise<PreparedWebPkce> {
|
|
109
|
+
const { verifier, challenge } = await createPkcePair();
|
|
110
|
+
const flowId = randomFlowId(kind);
|
|
111
|
+
const entry = { verifier, createdAt: Date.now() };
|
|
112
|
+
if (kind === 'magic_link') {
|
|
113
|
+
pruneMagicLinkVerifiers();
|
|
114
|
+
write(store('local'), MAGIC_LINK_PREFIX + flowId, entry);
|
|
115
|
+
} else {
|
|
116
|
+
write(store('session'), SESSION_PREFIX + flowId, entry);
|
|
117
|
+
}
|
|
118
|
+
const url = new URL(redirectTo);
|
|
119
|
+
url.searchParams.set(WEB_PKCE_FLOW_PARAM, flowId);
|
|
120
|
+
return { flowId, challenge, redirectTo: url.toString() };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Read the verifier for a callback and remove every stored copy. */
|
|
124
|
+
export function takeWebPkceVerifier(flowId: string | null | undefined): string | null {
|
|
125
|
+
const id = flowId?.trim();
|
|
126
|
+
if (!id || !FLOW_ID_PATTERN.test(id)) return null;
|
|
127
|
+
if (isMagicLinkFlowId(id)) {
|
|
128
|
+
return readAndRemove(store('local'), MAGIC_LINK_PREFIX + id, MAGIC_LINK_MAX_AGE_MS);
|
|
129
|
+
}
|
|
130
|
+
return readAndRemove(store('session'), SESSION_PREFIX + id, OAUTH_MAX_AGE_MS);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function isMagicLinkFlowId(flowId: string | null | undefined): boolean {
|
|
134
|
+
return !!flowId && flowId.startsWith(MAGIC_LINK_FLOW_MARK) && FLOW_ID_PATTERN.test(flowId);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Remove a flow's verifier, e.g. when starting it failed. */
|
|
138
|
+
export function clearWebPkce(flowId: string): void {
|
|
139
|
+
takeWebPkceVerifier(flowId);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export const WEB_PKCE_ERROR_CODES = [
|
|
143
|
+
'pkce_required',
|
|
144
|
+
'invalid_code_challenge',
|
|
145
|
+
'invalid_code_challenge_method',
|
|
146
|
+
'invalid_code_verifier',
|
|
147
|
+
'pkce_verification_failed',
|
|
148
|
+
] as const;
|
|
149
|
+
|
|
150
|
+
export function isWebPkceErrorCode(code: string | null | undefined): boolean {
|
|
151
|
+
return !!code && (WEB_PKCE_ERROR_CODES as readonly string[]).includes(code);
|
|
152
|
+
}
|
|
@@ -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. */
|
|
@@ -19,7 +19,12 @@ import {
|
|
|
19
19
|
import { SettingsContext } from './SettingsContext';
|
|
20
20
|
import { useConfig } from '../config/useConfig';
|
|
21
21
|
import { useAuth } from '../auth/hooks/useAuth';
|
|
22
|
-
import {
|
|
22
|
+
import { frameAuthPropagationOptions } from '../auth/appBackend/frameAuth';
|
|
23
|
+
import {
|
|
24
|
+
getAppBackendSession,
|
|
25
|
+
refreshAppBackendSessionIfDue,
|
|
26
|
+
subscribeAppBackendSessions,
|
|
27
|
+
} from '../auth/appBackend/appBackendSessions';
|
|
23
28
|
import { isMainLayoutFrame } from '../layouts/floating/layoutChromeStore';
|
|
24
29
|
import { defaultTheme } from '../theme/themes';
|
|
25
30
|
import {
|
|
@@ -192,26 +197,29 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
192
197
|
return defaultSettings;
|
|
193
198
|
});
|
|
194
199
|
|
|
195
|
-
const isTrustedFrameForAuthTokenCallback = useCallback(
|
|
196
|
-
(frameSrc: string): boolean => isTrustedFrameForAuthToken(frameSrc, config),
|
|
197
|
-
[config],
|
|
198
|
-
);
|
|
199
|
-
|
|
200
200
|
const accessTokenRef = useRef<string | null>(session?.accessToken ?? null);
|
|
201
201
|
accessTokenRef.current = session?.accessToken ?? null;
|
|
202
202
|
|
|
203
|
+
const authOptionsForFrame = useCallback(
|
|
204
|
+
(frameSrc: string) =>
|
|
205
|
+
frameAuthPropagationOptions({
|
|
206
|
+
frameSrc,
|
|
207
|
+
config,
|
|
208
|
+
shellAccessToken: accessTokenRef.current,
|
|
209
|
+
getAppSession: getAppBackendSession,
|
|
210
|
+
}),
|
|
211
|
+
[config],
|
|
212
|
+
);
|
|
213
|
+
|
|
203
214
|
const propagateSettingsToIframes = useCallback(
|
|
204
215
|
(baseSettings: Settings) => {
|
|
205
216
|
const iframes = shellui.frameRegistry.getLiveIframes();
|
|
206
217
|
if (iframes.length === 0) return;
|
|
207
218
|
const lang = baseSettings.language?.code || 'en';
|
|
208
|
-
const accessToken = accessTokenRef.current;
|
|
209
219
|
for (const [uuid, iframe] of iframes) {
|
|
210
220
|
const frameSrc = iframe?.src ?? '';
|
|
211
|
-
const includeAuthAccessToken = isTrustedFrameForAuthTokenCallback(frameSrc);
|
|
212
221
|
const settingsToPropagate = buildSettingsForPropagation(baseSettings, config, lang, {
|
|
213
|
-
|
|
214
|
-
accessToken,
|
|
222
|
+
...authOptionsForFrame(frameSrc),
|
|
215
223
|
includeLayoutChrome: isMainLayoutFrame(iframe),
|
|
216
224
|
frameUuid: uuid,
|
|
217
225
|
});
|
|
@@ -222,19 +230,17 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
222
230
|
});
|
|
223
231
|
}
|
|
224
232
|
},
|
|
225
|
-
[
|
|
233
|
+
[authOptionsForFrame, config],
|
|
226
234
|
);
|
|
227
235
|
|
|
228
236
|
const pushSettingsToFrame = useCallback(
|
|
229
237
|
(iframeUuid: string, frameSrc: string, baseSettings: Settings) => {
|
|
230
238
|
const lang = baseSettings.language?.code || 'en';
|
|
231
|
-
const includeAuthAccessToken = isTrustedFrameForAuthTokenCallback(frameSrc);
|
|
232
239
|
const iframe = shellui.frameRegistry
|
|
233
240
|
.getAllIframes()
|
|
234
241
|
.find(([uuid]) => uuid === iframeUuid)?.[1];
|
|
235
242
|
const settingsToPropagate = buildSettingsForPropagation(baseSettings, config, lang, {
|
|
236
|
-
|
|
237
|
-
accessToken: accessTokenRef.current,
|
|
243
|
+
...authOptionsForFrame(frameSrc),
|
|
238
244
|
includeLayoutChrome: isMainLayoutFrame(iframe),
|
|
239
245
|
frameUuid: iframeUuid,
|
|
240
246
|
});
|
|
@@ -244,7 +250,7 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
244
250
|
to: [iframeUuid],
|
|
245
251
|
});
|
|
246
252
|
},
|
|
247
|
-
[
|
|
253
|
+
[authOptionsForFrame, config],
|
|
248
254
|
);
|
|
249
255
|
|
|
250
256
|
const applyHandoffToken = useCallback((token: string | null | undefined) => {
|
|
@@ -256,6 +262,13 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
256
262
|
return deliverSessionHandoff(() => propagateSettingsToIframes(base));
|
|
257
263
|
}, [propagateSettingsToIframes]);
|
|
258
264
|
|
|
265
|
+
useEffect(() => {
|
|
266
|
+
return subscribeAppBackendSessions(() => {
|
|
267
|
+
if (typeof window === 'undefined' || window.parent !== window) return;
|
|
268
|
+
handoffSettingsToIframes();
|
|
269
|
+
});
|
|
270
|
+
}, [handoffSettingsToIframes]);
|
|
271
|
+
|
|
259
272
|
// When the shell rotates the JWT, `authUser` often does not change, so the user-sync effect
|
|
260
273
|
// above skips — still push `SHELLUI_SETTINGS` so trusted iframes get the new `accessToken`.
|
|
261
274
|
// The follow-up turn covers an app that subscribes after the first post.
|
|
@@ -482,28 +495,30 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
482
495
|
// not the JWT that died while the tab was hidden.
|
|
483
496
|
const token = await refreshFrameAccessTokenIfNeeded();
|
|
484
497
|
applyHandoffToken(token);
|
|
498
|
+
const requestingPath = (message.from ?? []).filter(Boolean);
|
|
499
|
+
const [firstHopIframeUuid] = requestingPath;
|
|
500
|
+
const requestingFrame = firstHopIframeUuid
|
|
501
|
+
? shellui.frameRegistry
|
|
502
|
+
.getAllIframes()
|
|
503
|
+
.find(([uuid]) => uuid === firstHopIframeUuid)?.[1]
|
|
504
|
+
: undefined;
|
|
505
|
+
if (requestingFrame?.src) {
|
|
506
|
+
await refreshAppBackendSessionIfDue(requestingFrame.src, config);
|
|
507
|
+
}
|
|
485
508
|
|
|
486
509
|
const send = () => {
|
|
487
510
|
const currentSettings = settingsRef.current ?? defaultSettings;
|
|
488
|
-
const requestingPath = (message.from ?? []).filter(Boolean);
|
|
489
511
|
|
|
490
512
|
if (requestingPath.length > 0) {
|
|
491
|
-
const [firstHopIframeUuid] = requestingPath;
|
|
492
|
-
const frame = shellui.frameRegistry
|
|
493
|
-
.getAllIframes()
|
|
494
|
-
.find(([uuid]) => uuid === firstHopIframeUuid)?.[1];
|
|
495
513
|
const lang = currentSettings.language?.code || 'en';
|
|
496
|
-
const
|
|
497
|
-
? isTrustedFrameForAuthTokenCallback(frame.src ?? '')
|
|
498
|
-
: false;
|
|
514
|
+
const frameSrc = requestingFrame?.src ?? '';
|
|
499
515
|
const settingsToPropagate = buildSettingsForPropagation(
|
|
500
516
|
currentSettings,
|
|
501
517
|
config,
|
|
502
518
|
lang,
|
|
503
519
|
{
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
includeLayoutChrome: isMainLayoutFrame(frame),
|
|
520
|
+
...authOptionsForFrame(frameSrc),
|
|
521
|
+
includeLayoutChrome: isMainLayoutFrame(requestingFrame),
|
|
507
522
|
frameUuid: firstHopIframeUuid,
|
|
508
523
|
},
|
|
509
524
|
);
|
|
@@ -565,12 +580,10 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
565
580
|
void (async () => {
|
|
566
581
|
const token = await refreshFrameAccessTokenIfNeeded();
|
|
567
582
|
applyHandoffToken(token);
|
|
583
|
+
const frameSrc = iframe?.src ?? '';
|
|
584
|
+
if (frameSrc) await refreshAppBackendSessionIfDue(frameSrc, config);
|
|
568
585
|
deliverSessionHandoff(() =>
|
|
569
|
-
pushSettingsToFrame(
|
|
570
|
-
iframeUuid,
|
|
571
|
-
iframe?.src ?? '',
|
|
572
|
-
settingsRef.current ?? defaultSettings,
|
|
573
|
-
),
|
|
586
|
+
pushSettingsToFrame(iframeUuid, frameSrc, settingsRef.current ?? defaultSettings),
|
|
574
587
|
);
|
|
575
588
|
})();
|
|
576
589
|
},
|
|
@@ -583,8 +596,8 @@ export function SettingsProvider({ children }: { children: ReactNode }) {
|
|
|
583
596
|
cleanupInitialized();
|
|
584
597
|
};
|
|
585
598
|
}, [
|
|
599
|
+
authOptionsForFrame,
|
|
586
600
|
config,
|
|
587
|
-
isTrustedFrameForAuthTokenCallback,
|
|
588
601
|
applyHandoffToken,
|
|
589
602
|
propagateSettingsToIframes,
|
|
590
603
|
pushSettingsToFrame,
|