@shellui/core 0.6.2 → 0.7.0-alpha.10

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 (85) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +147 -70
  3. package/src/app.tsx +2 -0
  4. package/src/components/ContentView.tsx +21 -30
  5. package/src/components/iframeUrlSafety.spec.ts +67 -0
  6. package/src/components/iframeUrlSafety.ts +50 -0
  7. package/src/components/ui/sidebar.tsx +11 -5
  8. package/src/features/admin/AdminView.tsx +9 -6
  9. package/src/features/auth/AuthProvider.tsx +49 -5
  10. package/src/features/auth/appBackend/AppBackendSessionHost.tsx +58 -0
  11. package/src/features/auth/appBackend/appBackendSessions.spec.ts +329 -0
  12. package/src/features/auth/appBackend/appBackendSessions.ts +443 -0
  13. package/src/features/auth/appBackend/childFrames.spec.ts +328 -0
  14. package/src/features/auth/appBackend/childFrames.ts +180 -0
  15. package/src/features/auth/appBackend/configSchema.spec.ts +41 -0
  16. package/src/features/auth/appBackend/frameAuth.ts +204 -0
  17. package/src/features/auth/appBackend/identity.spec.ts +201 -0
  18. package/src/features/auth/appBackend/identity.ts +173 -0
  19. package/src/features/auth/appBackend/silentSignIn.spec.ts +225 -0
  20. package/src/features/auth/appBackend/silentSignIn.ts +254 -0
  21. package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
  22. package/src/features/auth/appBackend/tokenExchange.ts +76 -0
  23. package/src/features/auth/backends/shellui.spec.ts +51 -19
  24. package/src/features/auth/backends/shellui.ts +20 -5
  25. package/src/features/auth/backends/types.ts +7 -2
  26. package/src/features/auth/components/LoginView.tsx +40 -18
  27. package/src/features/auth/components/OAuthCallbackView.tsx +33 -4
  28. package/src/features/auth/utils/authRequestError.ts +3 -0
  29. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
  30. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
  31. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +29 -0
  32. package/src/features/auth/utils/canRestoreStoredSession.ts +12 -0
  33. package/src/features/auth/utils/index.ts +16 -1
  34. package/src/features/auth/utils/loginCancelTarget.spec.ts +73 -0
  35. package/src/features/auth/utils/loginCancelTarget.ts +45 -0
  36. package/src/features/auth/utils/loginPanelFrame.spec.ts +24 -0
  37. package/src/features/auth/utils/loginPanelFrame.ts +14 -0
  38. package/src/features/auth/utils/resolveSdkLoginRedirectPath.spec.ts +41 -0
  39. package/src/features/auth/utils/resolveSdkLoginRedirectPath.ts +31 -0
  40. package/src/features/auth/utils/webPkce.spec.ts +119 -0
  41. package/src/features/auth/utils/webPkce.ts +169 -0
  42. package/src/features/chromeActions/computeActionInsets.ts +7 -4
  43. package/src/features/config/types.ts +70 -3
  44. package/src/features/layouts/appbar/AppBarLayout.tsx +63 -30
  45. package/src/features/layouts/chrome/CollapsedDesktopTitlebar.tsx +12 -23
  46. package/src/features/layouts/chrome/ContentDragOverlay.tsx +5 -6
  47. package/src/features/layouts/chrome/DesktopChrome.tsx +37 -0
  48. package/src/features/layouts/chrome/DesktopHistoryButtons.tsx +15 -4
  49. package/src/features/layouts/chrome/MacStrip.tsx +33 -0
  50. package/src/features/layouts/chrome/constants.ts +33 -8
  51. package/src/features/layouts/chrome/index.ts +8 -0
  52. package/src/features/layouts/chrome/stripDragMap.ts +35 -0
  53. package/src/features/layouts/chrome/stripNoDrag.spec.tsx +103 -0
  54. package/src/features/layouts/chrome/useScrollHideChrome.ts +3 -8
  55. package/src/features/layouts/filterNavigationForAuthState.spec.ts +5 -3
  56. package/src/features/layouts/floating/FloatingBottomDock.tsx +199 -20
  57. package/src/features/layouts/floating/FloatingLayout.tsx +13 -8
  58. package/src/features/layouts/floating/FloatingSidebar.tsx +144 -70
  59. package/src/features/layouts/floating/computeFloatingInsets.ts +22 -4
  60. package/src/features/layouts/floating/useFloatingChrome.ts +3 -1
  61. package/src/features/layouts/floating/useSoftKeyboard.spec.ts +39 -0
  62. package/src/features/layouts/floating/useSoftKeyboard.ts +82 -0
  63. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +38 -10
  64. package/src/features/layouts/sidebar/NavigationContent.tsx +14 -6
  65. package/src/features/layouts/sidebar/SidebarIcons.tsx +3 -9
  66. package/src/features/layouts/sidebar/SidebarInner.tsx +50 -39
  67. package/src/features/layouts/sidebar/SidebarLayout.tsx +8 -11
  68. package/src/features/layouts/utils.ts +4 -3
  69. package/src/features/layouts/windows/DesktopDots.tsx +76 -0
  70. package/src/features/layouts/windows/WindowsLayout.tsx +184 -125
  71. package/src/features/layouts/windows/deskDots.spec.ts +52 -0
  72. package/src/features/layouts/windows/deskDots.ts +314 -0
  73. package/src/features/settings/SettingsProvider.tsx +198 -29
  74. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +379 -4
  75. package/src/features/settings/utils/buildSettingsForPropagation.ts +65 -39
  76. package/src/features/theme/applyTheme.ts +8 -0
  77. package/src/features/theme/navContrast.spec.ts +49 -0
  78. package/src/features/theme/navContrast.ts +108 -0
  79. package/src/features/transfers/transferQueue.spec.ts +6 -2
  80. package/src/i18n/translations/en/common.json +27 -0
  81. package/src/i18n/translations/fr/common.json +27 -0
  82. package/src/index.css +935 -46
  83. package/src/index.ts +2 -0
  84. package/src/routes/hooks/useNavigationItems.ts +14 -3
  85. package/src/routes/hooks/withShellSearch.spec.ts +13 -0
@@ -0,0 +1,443 @@
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
+ import {
14
+ describeAppSessionFailure,
15
+ exchangeShellTokenForAppSession,
16
+ type TokenExchangeOutcome,
17
+ } from './tokenExchange';
18
+ import { refreshFrameAccessTokenIfNeeded } from '../utils/frameSessionRefresher';
19
+ import { decodeJwtPayload } from '../utils/decodeJwtPayload';
20
+
21
+ const logger = getLogger('shellcore');
22
+
23
+ /** Why the last session attempt for an app identity server failed (no secrets). */
24
+ const lastFailure = new Map<string, string>();
25
+
26
+ export function getAppBackendSessionFailure(key: string): string | null {
27
+ return lastFailure.get(key) ?? null;
28
+ }
29
+
30
+ /** Let the next ensure call try silent sign-in again (user asked to retry). */
31
+ export function allowSilentRetry(key: string): void {
32
+ silentAttempted.delete(key);
33
+ failedShellToken.delete(key);
34
+ }
35
+
36
+ /** Identity servers that trust the shell's global identity get a session by token exchange. */
37
+ export function usesTokenExchange(identity: ResolvedAppBackend): boolean {
38
+ return identity.type === 'shellui' && identity.provider === 'upstream';
39
+ }
40
+
41
+ function fail(identity: ResolvedAppBackend, reason: string): null {
42
+ lastFailure.set(identity.key, reason);
43
+ logger.warn('App session: no session for an app identity server', {
44
+ url: identity.url,
45
+ companyId: identity.companyId ?? null,
46
+ reason,
47
+ hint: describeAppSessionFailure(reason),
48
+ });
49
+ return null;
50
+ }
51
+
52
+ /** Tab-scoped refresh tokens for app identity servers. Not the shell refresh key. */
53
+ export const APP_BACKEND_REFRESH_PREFIX = 'shellui.auth.app.refresh.';
54
+
55
+ type AppBackendClient = Pick<
56
+ AuthBackend,
57
+ 'refreshAuthSession' | 'exchangeOAuthSessionCode' | 'logout'
58
+ >;
59
+
60
+ type StoredEntry = {
61
+ identity: ResolvedAppBackend;
62
+ session: AuthSession;
63
+ };
64
+
65
+ const memory = new Map<string, StoredEntry>();
66
+ const refreshTimers = new Map<string, ReturnType<typeof setTimeout>>();
67
+ const inFlight = new Map<string, Promise<string | null>>();
68
+ const silentAttempted = new Set<string>();
69
+ /** Shell token that last failed an exchange, so the same token is not retried in a loop. Memory only. */
70
+ const failedShellToken = new Map<string, string>();
71
+ const listeners = new Set<() => void>();
72
+
73
+ let backendFactory: (config: BackendConfig) => AppBackendClient = createAuthBackend;
74
+ let signInImpl: (input: {
75
+ backendUrl: string;
76
+ provider: string;
77
+ companyId?: string | number;
78
+ }) => Promise<SilentSignInOutcome> = runSilentPkceSignIn;
79
+
80
+ let shellTokenImpl: () => Promise<string | null | undefined> = refreshFrameAccessTokenIfNeeded;
81
+ let exchangeImpl: typeof exchangeShellTokenForAppSession = exchangeShellTokenForAppSession;
82
+
83
+ export function setAppBackendTokenExchange(
84
+ shellToken: () => Promise<string | null | undefined>,
85
+ exchange: (
86
+ input: Parameters<typeof exchangeShellTokenForAppSession>[0],
87
+ ) => Promise<TokenExchangeOutcome> = exchangeShellTokenForAppSession,
88
+ ): void {
89
+ shellTokenImpl = shellToken;
90
+ exchangeImpl = exchange;
91
+ }
92
+
93
+ export function resetAppBackendTokenExchange(): void {
94
+ shellTokenImpl = refreshFrameAccessTokenIfNeeded;
95
+ exchangeImpl = exchangeShellTokenForAppSession;
96
+ }
97
+
98
+ export function setAppBackendFactory(factory: (config: BackendConfig) => AppBackendClient): void {
99
+ backendFactory = factory;
100
+ }
101
+
102
+ export function setAppBackendSignIn(
103
+ signIn: (input: {
104
+ backendUrl: string;
105
+ provider: string;
106
+ companyId?: string | number;
107
+ }) => Promise<SilentSignInOutcome>,
108
+ ): void {
109
+ signInImpl = signIn;
110
+ }
111
+
112
+ export function resetAppBackendSilentAttempts(): void {
113
+ silentAttempted.clear();
114
+ failedShellToken.clear();
115
+ }
116
+
117
+ export function subscribeAppBackendSessions(listener: () => void): () => void {
118
+ listeners.add(listener);
119
+ return () => {
120
+ listeners.delete(listener);
121
+ };
122
+ }
123
+
124
+ export function getAppBackendSession(key: string): AuthSession | null {
125
+ return memory.get(key)?.session ?? null;
126
+ }
127
+
128
+ function notify(): void {
129
+ for (const listener of listeners) listener();
130
+ }
131
+
132
+ function storageKey(key: string): string {
133
+ return `${APP_BACKEND_REFRESH_PREFIX}${encodeURIComponent(key)}`;
134
+ }
135
+
136
+ function readRefresh(key: string): string | null {
137
+ try {
138
+ return sessionStorage.getItem(storageKey(key));
139
+ } catch {
140
+ return null;
141
+ }
142
+ }
143
+
144
+ function writeRefresh(key: string, refreshToken: string | null): void {
145
+ try {
146
+ if (refreshToken) sessionStorage.setItem(storageKey(key), refreshToken);
147
+ else sessionStorage.removeItem(storageKey(key));
148
+ } catch {
149
+ // Ignore quota / private mode.
150
+ }
151
+ }
152
+
153
+ function clearAllRefresh(): void {
154
+ try {
155
+ const doomed: string[] = [];
156
+ for (let i = 0; i < sessionStorage.length; i += 1) {
157
+ const key = sessionStorage.key(i);
158
+ if (key?.startsWith(APP_BACKEND_REFRESH_PREFIX)) doomed.push(key);
159
+ }
160
+ for (const key of doomed) sessionStorage.removeItem(key);
161
+ } catch {
162
+ // Ignore.
163
+ }
164
+ }
165
+
166
+ function toBackendConfig(identity: ResolvedAppBackend): BackendConfig {
167
+ return {
168
+ type: identity.type,
169
+ url: identity.url,
170
+ ...(identity.companyId !== undefined ? { companyId: identity.companyId } : {}),
171
+ ...(identity.publishableKey ? { publishableKey: identity.publishableKey } : {}),
172
+ };
173
+ }
174
+
175
+ function sessionForRefresh(refreshToken: string, accessToken = ''): AuthSession {
176
+ return {
177
+ accessToken,
178
+ refreshToken,
179
+ tokenType: 'bearer',
180
+ expiresAt: 0,
181
+ provider: null,
182
+ userId: null,
183
+ userEmail: null,
184
+ userName: null,
185
+ userAvatarUrl: null,
186
+ userIsStaff: false,
187
+ userIsCompanyOwner: false,
188
+ userGroups: [],
189
+ };
190
+ }
191
+
192
+ function clearTimer(key: string): void {
193
+ const timer = refreshTimers.get(key);
194
+ if (timer) clearTimeout(timer);
195
+ refreshTimers.delete(key);
196
+ }
197
+
198
+ function remember(identity: ResolvedAppBackend, session: AuthSession): void {
199
+ memory.set(identity.key, { identity, session });
200
+ writeRefresh(identity.key, session.refreshToken || null);
201
+ clearTimer(identity.key);
202
+ const now = Date.now() / 1000;
203
+ const delaySec = Math.max(5, session.expiresAt - now - 90);
204
+ const timer = setTimeout(() => {
205
+ void ensureAppBackendSession(identity, { allowSilent: false });
206
+ }, delaySec * 1000);
207
+ if (typeof timer === 'object' && timer && 'unref' in timer) {
208
+ timer.unref();
209
+ }
210
+ refreshTimers.set(identity.key, timer);
211
+ notify();
212
+ }
213
+
214
+ function forget(key: string): void {
215
+ memory.delete(key);
216
+ writeRefresh(key, null);
217
+ clearTimer(key);
218
+ notify();
219
+ }
220
+
221
+ function isUnauthorized(err: unknown): boolean {
222
+ const message = err instanceof Error ? err.message : '';
223
+ return /\b401\b/.test(message);
224
+ }
225
+
226
+ async function doEnsure(
227
+ identity: ResolvedAppBackend,
228
+ allowSilent: boolean,
229
+ ): Promise<string | null> {
230
+ if (usesTokenExchange(identity)) return ensureByTokenExchange(identity);
231
+ const now = Math.floor(Date.now() / 1000);
232
+ const current = memory.get(identity.key)?.session ?? null;
233
+ if (current?.accessToken && !accessTokenRefreshDue(current.expiresAt, now)) {
234
+ return current.accessToken;
235
+ }
236
+
237
+ const refreshToken = current?.refreshToken || readRefresh(identity.key);
238
+ if (refreshToken) {
239
+ try {
240
+ const next = await backendFactory(toBackendConfig(identity)).refreshAuthSession(
241
+ current ? { ...current, refreshToken } : sessionForRefresh(refreshToken),
242
+ now,
243
+ );
244
+ if (next?.accessToken) {
245
+ remember(identity, next);
246
+ return next.accessToken;
247
+ }
248
+ forget(identity.key);
249
+ } catch (err) {
250
+ if (isUnauthorized(err)) forget(identity.key);
251
+ else return current?.accessToken ?? null;
252
+ }
253
+ }
254
+
255
+ if (!allowSilent) return null;
256
+ if (identity.type !== 'shellui' || !identity.provider) {
257
+ return fail(identity, 'silent_sign_in_unsupported');
258
+ }
259
+ if (silentAttempted.has(identity.key)) {
260
+ return null;
261
+ }
262
+ silentAttempted.add(identity.key);
263
+
264
+ let outcome: SilentSignInOutcome;
265
+ try {
266
+ outcome = await signInImpl({
267
+ backendUrl: identity.url,
268
+ provider: identity.provider,
269
+ companyId: identity.companyId,
270
+ });
271
+ } catch {
272
+ return fail(identity, 'silent_sign_in_error');
273
+ }
274
+ if (!outcome.ok) return fail(identity, outcome.reason);
275
+ logger.info('App session: silent sign-in returned a code, exchanging it', { url: identity.url });
276
+
277
+ try {
278
+ const session = await backendFactory(toBackendConfig(identity)).exchangeOAuthSessionCode({
279
+ authCode: outcome.authCode,
280
+ redirectTo: outcome.redirectTo,
281
+ codeVerifier: outcome.codeVerifier,
282
+ nowSeconds: Math.floor(Date.now() / 1000),
283
+ });
284
+ if (!session?.accessToken) return fail(identity, 'token_exchange_empty');
285
+ remember(identity, session);
286
+ lastFailure.delete(identity.key);
287
+ logger.info('App session: signed in to app identity server', { url: identity.url });
288
+ return session.accessToken;
289
+ } catch (err) {
290
+ const message = err instanceof Error ? err.message.slice(0, 200) : '';
291
+ return fail(identity, `token_exchange_failed${message ? `: ${message}` : ''}`);
292
+ }
293
+ }
294
+
295
+ function shellSubject(token: string): string | null {
296
+ const sub = decodeJwtPayload(token)?.sub;
297
+ return typeof sub === 'string' || typeof sub === 'number' ? `${sub}` : null;
298
+ }
299
+
300
+ function subjectKey(key: string): string {
301
+ return `${storageKey(key)}#sub`;
302
+ }
303
+
304
+ function readSubject(key: string): string | null {
305
+ try {
306
+ return sessionStorage.getItem(subjectKey(key));
307
+ } catch {
308
+ return null;
309
+ }
310
+ }
311
+
312
+ function writeSubject(key: string, sub: string | null): void {
313
+ try {
314
+ if (sub) sessionStorage.setItem(subjectKey(key), sub);
315
+ else sessionStorage.removeItem(subjectKey(key));
316
+ } catch {
317
+ // Ignore.
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Regional session for an upstream identity server:
323
+ * keep it while valid, renew it with its own refresh token, and exchange the shell token
324
+ * only when there is none, the refresh fails, or the shell user changed.
325
+ */
326
+ async function ensureByTokenExchange(identity: ResolvedAppBackend): Promise<string | null> {
327
+ let shellToken: string | null | undefined;
328
+ try {
329
+ shellToken = await shellTokenImpl();
330
+ } catch {
331
+ shellToken = null;
332
+ }
333
+ if (!shellToken) {
334
+ forget(identity.key);
335
+ writeSubject(identity.key, null);
336
+ return fail(identity, 'no_shell_session');
337
+ }
338
+ const subject = shellSubject(shellToken);
339
+ if (readSubject(identity.key) !== subject) {
340
+ // Another shell user, or a session from before subjects were kept: never reuse it.
341
+ forget(identity.key);
342
+ writeSubject(identity.key, null);
343
+ }
344
+
345
+ const now = Math.floor(Date.now() / 1000);
346
+ const current = memory.get(identity.key)?.session ?? null;
347
+ if (current?.accessToken && !accessTokenRefreshDue(current.expiresAt, now)) {
348
+ return current.accessToken;
349
+ }
350
+ const refreshToken = current?.refreshToken || readRefresh(identity.key);
351
+ if (refreshToken) {
352
+ try {
353
+ const next = await backendFactory(toBackendConfig(identity)).refreshAuthSession(
354
+ current ? { ...current, refreshToken } : sessionForRefresh(refreshToken),
355
+ now,
356
+ );
357
+ if (next?.accessToken) {
358
+ remember(identity, next);
359
+ return next.accessToken;
360
+ }
361
+ } catch {
362
+ // Fall through to a new exchange.
363
+ }
364
+ forget(identity.key);
365
+ }
366
+
367
+ if (failedShellToken.get(identity.key) === shellToken) return null;
368
+ const outcome = await exchangeImpl({
369
+ backendUrl: identity.url,
370
+ companyId: identity.companyId,
371
+ shellAccessToken: shellToken,
372
+ nowSeconds: now,
373
+ });
374
+ if (!outcome.ok) {
375
+ failedShellToken.set(identity.key, shellToken);
376
+ forget(identity.key);
377
+ return fail(identity, outcome.reason);
378
+ }
379
+ failedShellToken.delete(identity.key);
380
+ writeSubject(identity.key, subject);
381
+ remember(identity, outcome.session);
382
+ lastFailure.delete(identity.key);
383
+ logger.info('App session: token exchange succeeded', {
384
+ url: identity.url,
385
+ companyId: identity.companyId ?? null,
386
+ });
387
+ return outcome.session.accessToken;
388
+ }
389
+
390
+ export function ensureAppBackendSession(
391
+ identity: ResolvedAppBackend,
392
+ options?: { allowSilent?: boolean },
393
+ ): Promise<string | null> {
394
+ const existing = inFlight.get(identity.key);
395
+ if (existing) return existing;
396
+ const allowSilent = options?.allowSilent !== false;
397
+ const run = doEnsure(identity, allowSilent).finally(() => {
398
+ if (inFlight.get(identity.key) === run) inFlight.delete(identity.key);
399
+ });
400
+ inFlight.set(identity.key, run);
401
+ return run;
402
+ }
403
+
404
+ export async function refreshAppBackendSessionIfDue(
405
+ frameSrc: string,
406
+ config?: ShellUIConfig,
407
+ ): Promise<void> {
408
+ const resolved = resolveFrameAppBackend(frameSrc, config);
409
+ if (resolved.kind !== 'foreign') return;
410
+ await ensureAppBackendSession(resolved.identity, { allowSilent: false });
411
+ }
412
+
413
+ export async function ensureConfiguredAppBackends(
414
+ config: ShellUIConfig | undefined,
415
+ options?: { allowSilent?: boolean },
416
+ ): Promise<void> {
417
+ const identities = listDistinctAppBackends(config);
418
+ for (const identity of identities) {
419
+ await ensureAppBackendSession(identity, options);
420
+ }
421
+ }
422
+
423
+ /** Drop every app session. Refresh tokens for the shell session are left in place. */
424
+ export async function endAppBackendSessions(): Promise<void> {
425
+ const snapshot = [...memory.values()];
426
+ memory.clear();
427
+ for (const timer of refreshTimers.values()) clearTimeout(timer);
428
+ refreshTimers.clear();
429
+ inFlight.clear();
430
+ silentAttempted.clear();
431
+ failedShellToken.clear();
432
+ clearAllRefresh();
433
+ notify();
434
+ await Promise.all(
435
+ snapshot.map(async (entry) => {
436
+ try {
437
+ await backendFactory(toBackendConfig(entry.identity)).logout(entry.session);
438
+ } catch {
439
+ // The local session is already gone.
440
+ }
441
+ }),
442
+ );
443
+ }