@shellui/core 0.6.1 → 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/README.md +1 -1
- 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/admin/AdminView.tsx +18 -4
- package/src/features/auth/AuthProvider.tsx +42 -2
- 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/desktopSignIn.spec.ts +41 -0
- package/src/features/auth/utils/desktopSignIn.ts +38 -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/chromeActions/ChromeActionsHost.tsx +7 -1
- package/src/features/chromeActions/computeActionInsets.ts +6 -0
- package/src/features/config/types.ts +41 -0
- package/src/features/layouts/appbar/AppBarLayout.tsx +39 -9
- package/src/features/layouts/chrome/ContentDragOverlay.tsx +14 -7
- package/src/features/layouts/chrome/DesktopChrome.tsx +3 -1
- package/src/features/layouts/floating/FloatingLayout.tsx +4 -1
- package/src/features/layouts/floating/FloatingSidebar.tsx +84 -28
- package/src/features/layouts/floating/computeFloatingInsets.spec.ts +19 -0
- package/src/features/layouts/floating/computeFloatingInsets.ts +40 -8
- package/src/features/layouts/floating/layoutChromeStore.ts +13 -0
- package/src/features/layouts/floating/useFloatingChrome.ts +11 -5
- package/src/features/layouts/fullscreen/FullscreenLayout.tsx +3 -0
- package/src/features/layouts/sidebar/SidebarInner.tsx +5 -0
- package/src/features/layouts/sidebar/SidebarLayout.tsx +1 -0
- package/src/features/layouts/windows/WindowsLayout.tsx +106 -46
- package/src/features/security/trustedFrames.spec.ts +17 -1
- package/src/features/security/trustedFrames.ts +31 -9
- package/src/features/settings/SettingsProvider.tsx +48 -32
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +374 -0
- package/src/features/settings/utils/buildSettingsForPropagation.ts +70 -35
- package/src/i18n/translations/en/common.json +2 -0
- package/src/i18n/translations/fr/common.json +2 -0
- package/src/index.css +16 -1
- package/src/index.ts +1 -0
- package/src/lib/z-index.ts +5 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { useEffect, useMemo, useRef } from 'react';
|
|
2
|
+
import { useConfig } from '../../config/useConfig';
|
|
3
|
+
import { useAuth } from '../hooks/useAuth';
|
|
4
|
+
import {
|
|
5
|
+
endAppBackendSessions,
|
|
6
|
+
ensureConfiguredAppBackends,
|
|
7
|
+
resetAppBackendSilentAttempts,
|
|
8
|
+
} from './appBackendSessions';
|
|
9
|
+
import { listDistinctAppBackends } from './identity';
|
|
10
|
+
import { isSilentAuthCallbackFrame } from './silentSignIn';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* While the shell has a session, sign in to each embedded app's identity server.
|
|
14
|
+
* The shell session itself is unchanged.
|
|
15
|
+
*/
|
|
16
|
+
export function AppBackendSessionHost() {
|
|
17
|
+
const { config } = useConfig();
|
|
18
|
+
const { session, isLoading } = useAuth();
|
|
19
|
+
const signedInUserRef = useRef<string | null>(null);
|
|
20
|
+
const configRef = useRef(config);
|
|
21
|
+
configRef.current = config;
|
|
22
|
+
|
|
23
|
+
const identityKey = useMemo(
|
|
24
|
+
() =>
|
|
25
|
+
listDistinctAppBackends(config)
|
|
26
|
+
.map((identity) => `${identity.key}|${identity.provider ?? ''}`)
|
|
27
|
+
.join('\n'),
|
|
28
|
+
[config],
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
const signedIn = Boolean(session?.accessToken);
|
|
32
|
+
const userId = session?.userId ?? null;
|
|
33
|
+
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
if (typeof window === 'undefined' || window.parent !== window) return;
|
|
36
|
+
if (isSilentAuthCallbackFrame()) return;
|
|
37
|
+
if (isLoading) return;
|
|
38
|
+
if (!signedIn) {
|
|
39
|
+
void endAppBackendSessions();
|
|
40
|
+
signedInUserRef.current = null;
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (signedInUserRef.current !== userId) {
|
|
44
|
+
signedInUserRef.current = userId;
|
|
45
|
+
resetAppBackendSilentAttempts();
|
|
46
|
+
}
|
|
47
|
+
let cancelled = false;
|
|
48
|
+
void (async () => {
|
|
49
|
+
if (cancelled) return;
|
|
50
|
+
await ensureConfiguredAppBackends(configRef.current, { allowSilent: true });
|
|
51
|
+
})();
|
|
52
|
+
return () => {
|
|
53
|
+
cancelled = true;
|
|
54
|
+
};
|
|
55
|
+
}, [identityKey, isLoading, signedIn, userId]);
|
|
56
|
+
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
vi.mock('../../config/useConfig', () => ({ useConfig: () => ({ config: {} }) }));
|
|
4
|
+
import { createAuthBackend } from '../backends';
|
|
5
|
+
import type { AuthSession } from '../types';
|
|
6
|
+
import { AUTH_REFRESH_STORAGE_KEY } from '../utils/authStorageKeys';
|
|
7
|
+
import {
|
|
8
|
+
APP_BACKEND_REFRESH_PREFIX,
|
|
9
|
+
endAppBackendSessions,
|
|
10
|
+
ensureAppBackendSession,
|
|
11
|
+
getAppBackendSession,
|
|
12
|
+
setAppBackendFactory,
|
|
13
|
+
setAppBackendSignIn,
|
|
14
|
+
} from './appBackendSessions';
|
|
15
|
+
import { resolveAppBackendConfig } from './identity';
|
|
16
|
+
import { runSilentPkceSignIn } from './silentSignIn';
|
|
17
|
+
|
|
18
|
+
const SHELL_TOKEN = 'shell-access-token';
|
|
19
|
+
const FOREIGN_TOKEN = 'foreign-access-token';
|
|
20
|
+
const FOREIGN_REFRESH = 'foreign-refresh-token';
|
|
21
|
+
|
|
22
|
+
function session(accessToken: string, refreshToken = FOREIGN_REFRESH): AuthSession {
|
|
23
|
+
return {
|
|
24
|
+
accessToken,
|
|
25
|
+
refreshToken,
|
|
26
|
+
tokenType: 'bearer',
|
|
27
|
+
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
|
28
|
+
provider: 'google',
|
|
29
|
+
userId: 'user-foreign',
|
|
30
|
+
userEmail: 'foreign@example.com',
|
|
31
|
+
userName: 'Foreign',
|
|
32
|
+
userAvatarUrl: null,
|
|
33
|
+
userIsStaff: false,
|
|
34
|
+
userIsCompanyOwner: false,
|
|
35
|
+
userGroups: ['directory'],
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function identityFor(url: string, companyId?: number) {
|
|
40
|
+
const identity = resolveAppBackendConfig(
|
|
41
|
+
{ url, companyId, provider: 'google', type: 'shellui' },
|
|
42
|
+
{ backend: { type: 'shellui', url: 'https://id.example.com', companyId: 1 } },
|
|
43
|
+
);
|
|
44
|
+
if (!identity) throw new Error('expected identity');
|
|
45
|
+
return identity;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function installStorage(): Storage {
|
|
49
|
+
const map = new Map<string, string>();
|
|
50
|
+
const storage = {
|
|
51
|
+
get length() {
|
|
52
|
+
return map.size;
|
|
53
|
+
},
|
|
54
|
+
clear: () => map.clear(),
|
|
55
|
+
getItem: (key: string) => map.get(key) ?? null,
|
|
56
|
+
key: (index: number) => [...map.keys()][index] ?? null,
|
|
57
|
+
removeItem: (key: string) => {
|
|
58
|
+
map.delete(key);
|
|
59
|
+
},
|
|
60
|
+
setItem: (key: string, value: string) => {
|
|
61
|
+
map.set(key, String(value));
|
|
62
|
+
},
|
|
63
|
+
} as Storage;
|
|
64
|
+
vi.stubGlobal('sessionStorage', storage);
|
|
65
|
+
return storage;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
describe('app backend sessions', () => {
|
|
69
|
+
const refreshAuthSession = vi.fn();
|
|
70
|
+
const exchangeOAuthSessionCode = vi.fn();
|
|
71
|
+
const logout = vi.fn(async () => {});
|
|
72
|
+
const factory = vi.fn(() => ({ refreshAuthSession, exchangeOAuthSessionCode, logout }));
|
|
73
|
+
const signIn = vi.fn();
|
|
74
|
+
|
|
75
|
+
beforeEach(() => {
|
|
76
|
+
installStorage();
|
|
77
|
+
refreshAuthSession.mockReset();
|
|
78
|
+
exchangeOAuthSessionCode.mockReset();
|
|
79
|
+
logout.mockClear();
|
|
80
|
+
factory.mockClear();
|
|
81
|
+
signIn.mockReset();
|
|
82
|
+
signIn.mockResolvedValue({ ok: false, reason: 'not-configured' });
|
|
83
|
+
setAppBackendFactory(factory);
|
|
84
|
+
setAppBackendSignIn(signIn);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
afterEach(async () => {
|
|
88
|
+
await endAppBackendSessions();
|
|
89
|
+
setAppBackendFactory(createAuthBackend);
|
|
90
|
+
setAppBackendSignIn(runSilentPkceSignIn);
|
|
91
|
+
vi.unstubAllGlobals();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('stores only the refresh token and keeps two servers apart', async () => {
|
|
95
|
+
const directory = identityFor('https://id.directory.example', 4);
|
|
96
|
+
const billing = identityFor('https://id.billing.example', 8);
|
|
97
|
+
signIn.mockImplementation(async (input: { backendUrl: string }) => ({
|
|
98
|
+
ok: true,
|
|
99
|
+
authCode: `code-${input.backendUrl}`,
|
|
100
|
+
redirectTo: 'https://shell.example/login/callback?shellui_silent=1',
|
|
101
|
+
codeVerifier: 'verifier-value-verifier-value-verifier-value',
|
|
102
|
+
}));
|
|
103
|
+
exchangeOAuthSessionCode.mockImplementation(async ({ authCode }: { authCode: string }) =>
|
|
104
|
+
session(
|
|
105
|
+
authCode === 'code-https://id.directory.example' ? FOREIGN_TOKEN : 'billing-token',
|
|
106
|
+
`refresh-${authCode}`,
|
|
107
|
+
),
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
const directoryToken = await ensureAppBackendSession(directory, { allowSilent: true });
|
|
111
|
+
const billingToken = await ensureAppBackendSession(billing, { allowSilent: true });
|
|
112
|
+
|
|
113
|
+
expect(directoryToken).toBe(FOREIGN_TOKEN);
|
|
114
|
+
expect(billingToken).toBe('billing-token');
|
|
115
|
+
expect(getAppBackendSession(directory.key)?.accessToken).toBe(FOREIGN_TOKEN);
|
|
116
|
+
expect(getAppBackendSession(billing.key)?.accessToken).toBe('billing-token');
|
|
117
|
+
expect(factory).toHaveBeenCalledWith(
|
|
118
|
+
expect.objectContaining({ url: 'https://id.directory.example' }),
|
|
119
|
+
);
|
|
120
|
+
expect(factory).toHaveBeenCalledWith(
|
|
121
|
+
expect.objectContaining({ url: 'https://id.billing.example' }),
|
|
122
|
+
);
|
|
123
|
+
expect(JSON.stringify(factory.mock.calls)).not.toContain(SHELL_TOKEN);
|
|
124
|
+
|
|
125
|
+
const stored = JSON.stringify(
|
|
126
|
+
Object.fromEntries(
|
|
127
|
+
[...Array(sessionStorage.length).keys()].map((index) => {
|
|
128
|
+
const key = sessionStorage.key(index) ?? '';
|
|
129
|
+
return [key, sessionStorage.getItem(key)];
|
|
130
|
+
}),
|
|
131
|
+
),
|
|
132
|
+
);
|
|
133
|
+
expect(stored).not.toContain(FOREIGN_TOKEN);
|
|
134
|
+
expect(stored).not.toContain('billing-token');
|
|
135
|
+
expect(stored).toContain('refresh-code-https://id.directory.example');
|
|
136
|
+
expect(signIn.mock.calls[0][0]).not.toHaveProperty('accessToken');
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('refreshes a stored session without silent sign-in', async () => {
|
|
140
|
+
const directory = identityFor('https://id.directory.example', 4);
|
|
141
|
+
sessionStorage.setItem(
|
|
142
|
+
`${APP_BACKEND_REFRESH_PREFIX}${encodeURIComponent(directory.key)}`,
|
|
143
|
+
'stored-refresh',
|
|
144
|
+
);
|
|
145
|
+
refreshAuthSession.mockResolvedValue(session(FOREIGN_TOKEN, 'rotated-refresh'));
|
|
146
|
+
|
|
147
|
+
const token = await ensureAppBackendSession(directory, { allowSilent: true });
|
|
148
|
+
|
|
149
|
+
expect(token).toBe(FOREIGN_TOKEN);
|
|
150
|
+
expect(signIn).not.toHaveBeenCalled();
|
|
151
|
+
expect(exchangeOAuthSessionCode).not.toHaveBeenCalled();
|
|
152
|
+
expect(
|
|
153
|
+
sessionStorage.getItem(`${APP_BACKEND_REFRESH_PREFIX}${encodeURIComponent(directory.key)}`),
|
|
154
|
+
).toBe('rotated-refresh');
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('does not silent-sign-in a supabase override', async () => {
|
|
158
|
+
const identity = resolveAppBackendConfig(
|
|
159
|
+
{
|
|
160
|
+
type: 'supabase',
|
|
161
|
+
url: 'https://abc.supabase.co',
|
|
162
|
+
publishableKey: 'pk',
|
|
163
|
+
provider: 'google',
|
|
164
|
+
},
|
|
165
|
+
{ backend: { type: 'shellui', url: 'https://id.example.com' } },
|
|
166
|
+
);
|
|
167
|
+
if (!identity) throw new Error('expected identity');
|
|
168
|
+
const token = await ensureAppBackendSession(identity, { allowSilent: true });
|
|
169
|
+
expect(token).toBeNull();
|
|
170
|
+
expect(signIn).not.toHaveBeenCalled();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it('clears app refresh tokens and leaves the shell refresh token', async () => {
|
|
174
|
+
const directory = identityFor('https://id.directory.example', 4);
|
|
175
|
+
signIn.mockResolvedValue({
|
|
176
|
+
ok: true,
|
|
177
|
+
authCode: 'code-1',
|
|
178
|
+
redirectTo: 'https://shell.example/login/callback?shellui_silent=1',
|
|
179
|
+
codeVerifier: 'verifier-value-verifier-value-verifier-value',
|
|
180
|
+
});
|
|
181
|
+
exchangeOAuthSessionCode.mockResolvedValue(session(FOREIGN_TOKEN));
|
|
182
|
+
await ensureAppBackendSession(directory, { allowSilent: true });
|
|
183
|
+
sessionStorage.setItem(AUTH_REFRESH_STORAGE_KEY, 'shell-refresh');
|
|
184
|
+
|
|
185
|
+
await endAppBackendSessions();
|
|
186
|
+
|
|
187
|
+
expect(getAppBackendSession(directory.key)).toBeNull();
|
|
188
|
+
expect(sessionStorage.getItem(AUTH_REFRESH_STORAGE_KEY)).toBe('shell-refresh');
|
|
189
|
+
expect(logout).toHaveBeenCalledWith(expect.objectContaining({ accessToken: FOREIGN_TOKEN }));
|
|
190
|
+
const dumped = JSON.stringify(
|
|
191
|
+
[...Array(sessionStorage.length).keys()].map((index) => sessionStorage.key(index)),
|
|
192
|
+
);
|
|
193
|
+
expect(dumped).not.toContain(APP_BACKEND_REFRESH_PREFIX);
|
|
194
|
+
});
|
|
195
|
+
});
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { getLogger } from '@shellui/sdk';
|
|
2
|
+
import type { BackendConfig, ShellUIConfig } from '../../config/types';
|
|
3
|
+
import { createAuthBackend } from '../backends';
|
|
4
|
+
import type { AuthBackend } from '../backends/types';
|
|
5
|
+
import type { AuthSession } from '../types';
|
|
6
|
+
import { accessTokenRefreshDue } from '../utils/accessTokenRefreshDue';
|
|
7
|
+
import {
|
|
8
|
+
listDistinctAppBackends,
|
|
9
|
+
resolveFrameAppBackend,
|
|
10
|
+
type ResolvedAppBackend,
|
|
11
|
+
} from './identity';
|
|
12
|
+
import { runSilentPkceSignIn, type SilentSignInOutcome } from './silentSignIn';
|
|
13
|
+
|
|
14
|
+
const logger = getLogger('shellcore');
|
|
15
|
+
|
|
16
|
+
/** Tab-scoped refresh tokens for app identity servers. Not the shell refresh key. */
|
|
17
|
+
export const APP_BACKEND_REFRESH_PREFIX = 'shellui.auth.app.refresh.';
|
|
18
|
+
|
|
19
|
+
type AppBackendClient = Pick<
|
|
20
|
+
AuthBackend,
|
|
21
|
+
'refreshAuthSession' | 'exchangeOAuthSessionCode' | 'logout'
|
|
22
|
+
>;
|
|
23
|
+
|
|
24
|
+
type StoredEntry = {
|
|
25
|
+
identity: ResolvedAppBackend;
|
|
26
|
+
session: AuthSession;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const memory = new Map<string, StoredEntry>();
|
|
30
|
+
const refreshTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
31
|
+
const inFlight = new Map<string, Promise<string | null>>();
|
|
32
|
+
const silentAttempted = new Set<string>();
|
|
33
|
+
const listeners = new Set<() => void>();
|
|
34
|
+
|
|
35
|
+
let backendFactory: (config: BackendConfig) => AppBackendClient = createAuthBackend;
|
|
36
|
+
let signInImpl: (input: {
|
|
37
|
+
backendUrl: string;
|
|
38
|
+
provider: string;
|
|
39
|
+
companyId?: string | number;
|
|
40
|
+
}) => Promise<SilentSignInOutcome> = runSilentPkceSignIn;
|
|
41
|
+
|
|
42
|
+
export function setAppBackendFactory(factory: (config: BackendConfig) => AppBackendClient): void {
|
|
43
|
+
backendFactory = factory;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function setAppBackendSignIn(
|
|
47
|
+
signIn: (input: {
|
|
48
|
+
backendUrl: string;
|
|
49
|
+
provider: string;
|
|
50
|
+
companyId?: string | number;
|
|
51
|
+
}) => Promise<SilentSignInOutcome>,
|
|
52
|
+
): void {
|
|
53
|
+
signInImpl = signIn;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function resetAppBackendSilentAttempts(): void {
|
|
57
|
+
silentAttempted.clear();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function subscribeAppBackendSessions(listener: () => void): () => void {
|
|
61
|
+
listeners.add(listener);
|
|
62
|
+
return () => {
|
|
63
|
+
listeners.delete(listener);
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function getAppBackendSession(key: string): AuthSession | null {
|
|
68
|
+
return memory.get(key)?.session ?? null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function notify(): void {
|
|
72
|
+
for (const listener of listeners) listener();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function storageKey(key: string): string {
|
|
76
|
+
return `${APP_BACKEND_REFRESH_PREFIX}${encodeURIComponent(key)}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function readRefresh(key: string): string | null {
|
|
80
|
+
try {
|
|
81
|
+
return sessionStorage.getItem(storageKey(key));
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function writeRefresh(key: string, refreshToken: string | null): void {
|
|
88
|
+
try {
|
|
89
|
+
if (refreshToken) sessionStorage.setItem(storageKey(key), refreshToken);
|
|
90
|
+
else sessionStorage.removeItem(storageKey(key));
|
|
91
|
+
} catch {
|
|
92
|
+
// Ignore quota / private mode.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function clearAllRefresh(): void {
|
|
97
|
+
try {
|
|
98
|
+
const doomed: string[] = [];
|
|
99
|
+
for (let i = 0; i < sessionStorage.length; i += 1) {
|
|
100
|
+
const key = sessionStorage.key(i);
|
|
101
|
+
if (key?.startsWith(APP_BACKEND_REFRESH_PREFIX)) doomed.push(key);
|
|
102
|
+
}
|
|
103
|
+
for (const key of doomed) sessionStorage.removeItem(key);
|
|
104
|
+
} catch {
|
|
105
|
+
// Ignore.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function toBackendConfig(identity: ResolvedAppBackend): BackendConfig {
|
|
110
|
+
return {
|
|
111
|
+
type: identity.type,
|
|
112
|
+
url: identity.url,
|
|
113
|
+
...(identity.companyId !== undefined ? { companyId: identity.companyId } : {}),
|
|
114
|
+
...(identity.publishableKey ? { publishableKey: identity.publishableKey } : {}),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function sessionForRefresh(refreshToken: string, accessToken = ''): AuthSession {
|
|
119
|
+
return {
|
|
120
|
+
accessToken,
|
|
121
|
+
refreshToken,
|
|
122
|
+
tokenType: 'bearer',
|
|
123
|
+
expiresAt: 0,
|
|
124
|
+
provider: null,
|
|
125
|
+
userId: null,
|
|
126
|
+
userEmail: null,
|
|
127
|
+
userName: null,
|
|
128
|
+
userAvatarUrl: null,
|
|
129
|
+
userIsStaff: false,
|
|
130
|
+
userIsCompanyOwner: false,
|
|
131
|
+
userGroups: [],
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function clearTimer(key: string): void {
|
|
136
|
+
const timer = refreshTimers.get(key);
|
|
137
|
+
if (timer) clearTimeout(timer);
|
|
138
|
+
refreshTimers.delete(key);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function remember(identity: ResolvedAppBackend, session: AuthSession): void {
|
|
142
|
+
memory.set(identity.key, { identity, session });
|
|
143
|
+
writeRefresh(identity.key, session.refreshToken || null);
|
|
144
|
+
clearTimer(identity.key);
|
|
145
|
+
const now = Date.now() / 1000;
|
|
146
|
+
const delaySec = Math.max(5, session.expiresAt - now - 90);
|
|
147
|
+
const timer = setTimeout(() => {
|
|
148
|
+
void ensureAppBackendSession(identity, { allowSilent: false });
|
|
149
|
+
}, delaySec * 1000);
|
|
150
|
+
if (typeof timer === 'object' && timer && 'unref' in timer) {
|
|
151
|
+
timer.unref();
|
|
152
|
+
}
|
|
153
|
+
refreshTimers.set(identity.key, timer);
|
|
154
|
+
notify();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function forget(key: string): void {
|
|
158
|
+
memory.delete(key);
|
|
159
|
+
writeRefresh(key, null);
|
|
160
|
+
clearTimer(key);
|
|
161
|
+
notify();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function isUnauthorized(err: unknown): boolean {
|
|
165
|
+
const message = err instanceof Error ? err.message : '';
|
|
166
|
+
return /\b401\b/.test(message);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function doEnsure(
|
|
170
|
+
identity: ResolvedAppBackend,
|
|
171
|
+
allowSilent: boolean,
|
|
172
|
+
): Promise<string | null> {
|
|
173
|
+
const now = Math.floor(Date.now() / 1000);
|
|
174
|
+
const current = memory.get(identity.key)?.session ?? null;
|
|
175
|
+
if (current?.accessToken && !accessTokenRefreshDue(current.expiresAt, now)) {
|
|
176
|
+
return current.accessToken;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const refreshToken = current?.refreshToken || readRefresh(identity.key);
|
|
180
|
+
if (refreshToken) {
|
|
181
|
+
try {
|
|
182
|
+
const next = await backendFactory(toBackendConfig(identity)).refreshAuthSession(
|
|
183
|
+
current ? { ...current, refreshToken } : sessionForRefresh(refreshToken),
|
|
184
|
+
now,
|
|
185
|
+
);
|
|
186
|
+
if (next?.accessToken) {
|
|
187
|
+
remember(identity, next);
|
|
188
|
+
return next.accessToken;
|
|
189
|
+
}
|
|
190
|
+
forget(identity.key);
|
|
191
|
+
} catch (err) {
|
|
192
|
+
if (isUnauthorized(err)) forget(identity.key);
|
|
193
|
+
else return current?.accessToken ?? null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (!allowSilent || identity.type !== 'shellui' || !identity.provider) return null;
|
|
198
|
+
if (silentAttempted.has(identity.key)) return null;
|
|
199
|
+
silentAttempted.add(identity.key);
|
|
200
|
+
|
|
201
|
+
let outcome: SilentSignInOutcome;
|
|
202
|
+
try {
|
|
203
|
+
outcome = await signInImpl({
|
|
204
|
+
backendUrl: identity.url,
|
|
205
|
+
provider: identity.provider,
|
|
206
|
+
companyId: identity.companyId,
|
|
207
|
+
});
|
|
208
|
+
} catch {
|
|
209
|
+
logger.info('Silent sign-in did not complete for an app identity server', {
|
|
210
|
+
url: identity.url,
|
|
211
|
+
});
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
if (!outcome.ok) {
|
|
215
|
+
logger.info('Silent sign-in did not complete for an app identity server', {
|
|
216
|
+
url: identity.url,
|
|
217
|
+
reason: outcome.reason,
|
|
218
|
+
});
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
try {
|
|
223
|
+
const session = await backendFactory(toBackendConfig(identity)).exchangeOAuthSessionCode({
|
|
224
|
+
authCode: outcome.authCode,
|
|
225
|
+
redirectTo: outcome.redirectTo,
|
|
226
|
+
codeVerifier: outcome.codeVerifier,
|
|
227
|
+
nowSeconds: Math.floor(Date.now() / 1000),
|
|
228
|
+
});
|
|
229
|
+
if (!session?.accessToken) return null;
|
|
230
|
+
remember(identity, session);
|
|
231
|
+
return session.accessToken;
|
|
232
|
+
} catch {
|
|
233
|
+
logger.info('Silent sign-in did not complete for an app identity server', {
|
|
234
|
+
url: identity.url,
|
|
235
|
+
});
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function ensureAppBackendSession(
|
|
241
|
+
identity: ResolvedAppBackend,
|
|
242
|
+
options?: { allowSilent?: boolean },
|
|
243
|
+
): Promise<string | null> {
|
|
244
|
+
const existing = inFlight.get(identity.key);
|
|
245
|
+
if (existing) return existing;
|
|
246
|
+
const allowSilent = options?.allowSilent !== false;
|
|
247
|
+
const run = doEnsure(identity, allowSilent).finally(() => {
|
|
248
|
+
if (inFlight.get(identity.key) === run) inFlight.delete(identity.key);
|
|
249
|
+
});
|
|
250
|
+
inFlight.set(identity.key, run);
|
|
251
|
+
return run;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export async function refreshAppBackendSessionIfDue(
|
|
255
|
+
frameSrc: string,
|
|
256
|
+
config?: ShellUIConfig,
|
|
257
|
+
): Promise<void> {
|
|
258
|
+
const resolved = resolveFrameAppBackend(frameSrc, config);
|
|
259
|
+
if (resolved.kind !== 'foreign') return;
|
|
260
|
+
await ensureAppBackendSession(resolved.identity, { allowSilent: false });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export async function ensureConfiguredAppBackends(
|
|
264
|
+
config: ShellUIConfig | undefined,
|
|
265
|
+
options?: { allowSilent?: boolean },
|
|
266
|
+
): Promise<void> {
|
|
267
|
+
const identities = listDistinctAppBackends(config);
|
|
268
|
+
for (const identity of identities) {
|
|
269
|
+
await ensureAppBackendSession(identity, options);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Drop every app session. Refresh tokens for the shell session are left in place. */
|
|
274
|
+
export async function endAppBackendSessions(): Promise<void> {
|
|
275
|
+
const snapshot = [...memory.values()];
|
|
276
|
+
memory.clear();
|
|
277
|
+
for (const timer of refreshTimers.values()) clearTimeout(timer);
|
|
278
|
+
refreshTimers.clear();
|
|
279
|
+
inFlight.clear();
|
|
280
|
+
silentAttempted.clear();
|
|
281
|
+
clearAllRefresh();
|
|
282
|
+
notify();
|
|
283
|
+
await Promise.all(
|
|
284
|
+
snapshot.map(async (entry) => {
|
|
285
|
+
try {
|
|
286
|
+
await backendFactory(toBackendConfig(entry.identity)).logout(entry.session);
|
|
287
|
+
} catch {
|
|
288
|
+
// The local session is already gone.
|
|
289
|
+
}
|
|
290
|
+
}),
|
|
291
|
+
);
|
|
292
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
|
|
6
|
+
const schemaPath = resolve(
|
|
7
|
+
dirname(fileURLToPath(import.meta.url)),
|
|
8
|
+
'../../../../schemas/shellui.config.schema.json',
|
|
9
|
+
);
|
|
10
|
+
|
|
11
|
+
describe('shellui.config schema app backend', () => {
|
|
12
|
+
const schema = JSON.parse(readFileSync(schemaPath, 'utf8')) as {
|
|
13
|
+
definitions: Record<
|
|
14
|
+
string,
|
|
15
|
+
{
|
|
16
|
+
properties?: Record<string, unknown>;
|
|
17
|
+
required?: string[];
|
|
18
|
+
additionalProperties?: boolean;
|
|
19
|
+
}
|
|
20
|
+
>;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
it('adds an optional per-app backend and keeps existing item fields', () => {
|
|
24
|
+
const navigationItem = schema.definitions.NavigationItem;
|
|
25
|
+
const appBackend = schema.definitions.AppBackendConfig;
|
|
26
|
+
expect(navigationItem.additionalProperties).toBe(false);
|
|
27
|
+
expect(navigationItem.required).toEqual(['label', 'path', 'url']);
|
|
28
|
+
expect(navigationItem.properties?.backend).toBeTruthy();
|
|
29
|
+
expect(navigationItem.properties?.email).toBeTruthy();
|
|
30
|
+
expect(navigationItem.properties?.storage).toBeTruthy();
|
|
31
|
+
expect(navigationItem.properties?.hosting).toBeTruthy();
|
|
32
|
+
expect(navigationItem.properties?.safeForAuthToken).toBeTruthy();
|
|
33
|
+
expect(appBackend.additionalProperties).toBe(false);
|
|
34
|
+
expect(appBackend.required).toEqual(['url']);
|
|
35
|
+
expect(appBackend.properties?.url).toBeTruthy();
|
|
36
|
+
expect(appBackend.properties?.type).toBeTruthy();
|
|
37
|
+
expect(appBackend.properties?.companyId).toBeTruthy();
|
|
38
|
+
expect(appBackend.properties?.provider).toBeTruthy();
|
|
39
|
+
expect(appBackend.properties?.publishableKey).toBeTruthy();
|
|
40
|
+
});
|
|
41
|
+
});
|