@shellui/core 0.7.0-alpha.1 → 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 (69) hide show
  1. package/package.json +2 -2
  2. package/schemas/shellui.config.schema.json +37 -4
  3. package/src/components/ContentView.tsx +19 -8
  4. package/src/components/ui/sidebar.tsx +11 -5
  5. package/src/features/admin/AdminView.tsx +9 -6
  6. package/src/features/auth/AuthProvider.tsx +25 -4
  7. package/src/features/auth/appBackend/appBackendSessions.spec.ts +134 -0
  8. package/src/features/auth/appBackend/appBackendSessions.ts +168 -17
  9. package/src/features/auth/appBackend/childFrames.spec.ts +328 -0
  10. package/src/features/auth/appBackend/childFrames.ts +180 -0
  11. package/src/features/auth/appBackend/frameAuth.ts +47 -10
  12. package/src/features/auth/appBackend/silentSignIn.spec.ts +18 -0
  13. package/src/features/auth/appBackend/silentSignIn.ts +15 -1
  14. package/src/features/auth/appBackend/tokenExchange.spec.ts +98 -0
  15. package/src/features/auth/appBackend/tokenExchange.ts +76 -0
  16. package/src/features/auth/components/OAuthCallbackView.tsx +7 -5
  17. package/src/features/auth/utils/buildOAuthSessionRedirectTo.spec.ts +42 -1
  18. package/src/features/auth/utils/buildOAuthSessionRedirectTo.ts +23 -0
  19. package/src/features/auth/utils/canRestoreStoredSession.spec.ts +29 -0
  20. package/src/features/auth/utils/canRestoreStoredSession.ts +12 -0
  21. package/src/features/auth/utils/index.ts +7 -1
  22. package/src/features/auth/utils/resolveSdkLoginRedirectPath.spec.ts +41 -0
  23. package/src/features/auth/utils/resolveSdkLoginRedirectPath.ts +31 -0
  24. package/src/features/auth/utils/webPkce.spec.ts +23 -0
  25. package/src/features/auth/utils/webPkce.ts +23 -6
  26. package/src/features/chromeActions/computeActionInsets.ts +7 -4
  27. package/src/features/config/types.ts +30 -4
  28. package/src/features/layouts/appbar/AppBarLayout.tsx +63 -30
  29. package/src/features/layouts/chrome/CollapsedDesktopTitlebar.tsx +12 -23
  30. package/src/features/layouts/chrome/ContentDragOverlay.tsx +5 -6
  31. package/src/features/layouts/chrome/DesktopChrome.tsx +37 -0
  32. package/src/features/layouts/chrome/DesktopHistoryButtons.tsx +15 -4
  33. package/src/features/layouts/chrome/MacStrip.tsx +33 -0
  34. package/src/features/layouts/chrome/constants.ts +33 -8
  35. package/src/features/layouts/chrome/index.ts +8 -0
  36. package/src/features/layouts/chrome/stripDragMap.ts +35 -0
  37. package/src/features/layouts/chrome/stripNoDrag.spec.tsx +103 -0
  38. package/src/features/layouts/chrome/useScrollHideChrome.ts +3 -8
  39. package/src/features/layouts/filterNavigationForAuthState.spec.ts +5 -3
  40. package/src/features/layouts/floating/FloatingBottomDock.tsx +199 -20
  41. package/src/features/layouts/floating/FloatingLayout.tsx +13 -8
  42. package/src/features/layouts/floating/FloatingSidebar.tsx +144 -70
  43. package/src/features/layouts/floating/computeFloatingInsets.ts +22 -4
  44. package/src/features/layouts/floating/useFloatingChrome.ts +3 -1
  45. package/src/features/layouts/floating/useSoftKeyboard.spec.ts +39 -0
  46. package/src/features/layouts/floating/useSoftKeyboard.ts +82 -0
  47. package/src/features/layouts/fullscreen/FullscreenLayout.tsx +38 -10
  48. package/src/features/layouts/sidebar/NavigationContent.tsx +14 -6
  49. package/src/features/layouts/sidebar/SidebarIcons.tsx +3 -9
  50. package/src/features/layouts/sidebar/SidebarInner.tsx +50 -39
  51. package/src/features/layouts/sidebar/SidebarLayout.tsx +8 -11
  52. package/src/features/layouts/utils.ts +4 -3
  53. package/src/features/layouts/windows/DesktopDots.tsx +76 -0
  54. package/src/features/layouts/windows/WindowsLayout.tsx +184 -125
  55. package/src/features/layouts/windows/deskDots.spec.ts +52 -0
  56. package/src/features/layouts/windows/deskDots.ts +314 -0
  57. package/src/features/settings/SettingsProvider.tsx +158 -2
  58. package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +8 -7
  59. package/src/features/settings/utils/buildSettingsForPropagation.ts +4 -6
  60. package/src/features/theme/applyTheme.ts +8 -0
  61. package/src/features/theme/navContrast.spec.ts +49 -0
  62. package/src/features/theme/navContrast.ts +108 -0
  63. package/src/features/transfers/transferQueue.spec.ts +6 -2
  64. package/src/i18n/translations/en/common.json +25 -0
  65. package/src/i18n/translations/fr/common.json +25 -0
  66. package/src/index.css +935 -46
  67. package/src/index.ts +1 -0
  68. package/src/routes/hooks/useNavigationItems.ts +14 -3
  69. package/src/routes/hooks/withShellSearch.spec.ts +13 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shellui/core",
3
- "version": "0.7.0-alpha.1",
3
+ "version": "0.7.0-alpha.10",
4
4
  "description": "Shellui Core - Core React application runtime",
5
5
  "main": "src/index.ts",
6
6
  "type": "module",
@@ -73,7 +73,7 @@
73
73
  "workbox-routing": "^7.4.0",
74
74
  "workbox-strategies": "^7.4.0",
75
75
  "workbox-window": "^7.4.0",
76
- "@shellui/sdk": "0.7.0-alpha.1"
76
+ "@shellui/sdk": "0.7.0-alpha.10"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "react": "^18.0.0 || ^19.0.0",
@@ -79,7 +79,7 @@
79
79
  },
80
80
  "email": {
81
81
  "$ref": "#/definitions/EmailConfig",
82
- "description": "Email-service connection. Propagated to iframes via SDK settings. When `email` is set and `url` is omitted, the shell sends `https://email.shellui.com`. `showInAdmin: false` hides Admin → Email."
82
+ "description": "Email-service connection. Propagated to iframes via SDK settings. Without `url`, the shell sends no email service (`null`). `showInAdmin: false` hides Admin → Email."
83
83
  },
84
84
  "theme": {
85
85
  "$ref": "#/definitions/ThemeRef",
@@ -260,6 +260,10 @@
260
260
  "$ref": "#/definitions/AppBackendConfig",
261
261
  "description": "Identity server for this embedded app when it is not the shell `backend`. The shell keeps a separate session and sends this URL plus that session's access token. Omit to use the shell backend and token. The shell token is never sent when this server differs."
262
262
  },
263
+ "childFrames": {
264
+ "$ref": "#/definitions/ChildFramesConfig",
265
+ "description": "Lets this app host other Shellui apps in its own iframes (`createAppFrame`). Off when omitted. Only exact origins listed here are accepted."
266
+ },
263
267
  "email": {
264
268
  "$ref": "#/definitions/EmailConfig",
265
269
  "description": "Email service for this app. Omit to use the shell `email` when the app uses the shell identity server. When `backend` names a different server and this is omitted, the app receives no email URL."
@@ -324,7 +328,7 @@
324
328
  },
325
329
  "provider": {
326
330
  "type": "string",
327
- "description": "OAuth provider for silent sign-in, such as `google`. When omitted, the shell uses the first `backend.login.oauthProviders` entry."
331
+ "description": "`upstream`: the shell gets the app session by OAuth token exchange (RFC 8693), trading its own access token at this server. Recommended for Shellui regions. Any other value, such as `google`, is the OAuth provider for silent sign-in. When omitted, the shell uses the first `backend.login.oauthProviders` entry."
328
332
  }
329
333
  },
330
334
  "required": ["url"],
@@ -336,12 +340,41 @@
336
340
  "enum": ["shellui", "supabase"],
337
341
  "description": "Supported backend providers for auth/API communication."
338
342
  },
343
+ "ChildFramesConfig": {
344
+ "type": "object",
345
+ "properties": {
346
+ "origins": {
347
+ "type": "array",
348
+ "items": {
349
+ "type": "string"
350
+ },
351
+ "description": "Exact origins of child apps, such as `https://admin.shellui.com`. No wildcards."
352
+ },
353
+ "backendOrigins": {
354
+ "type": "array",
355
+ "items": {
356
+ "type": "string"
357
+ },
358
+ "description": "Exact origins of identity servers a child may sign in to, such as `https://id.eu.shellui.com`. The shell keeps a separate session per server and never sends its own token to a child. Omit to give children no token."
359
+ },
360
+ "serviceOrigins": {
361
+ "type": "array",
362
+ "items": {
363
+ "type": "string"
364
+ },
365
+ "description": "Exact origins of service URLs (email, storage, files, hosting) a host may pass to a child with `ShelluiFrame` or `createAppFrame`, such as `https://storage.eu.shellui.com`. No wildcards. A URL outside this list, or a missing one, reaches the child as `null`. Omit to send children no service URLs."
366
+ }
367
+ },
368
+ "required": ["origins"],
369
+ "additionalProperties": false,
370
+ "description": "Child apps an embedded app may host, and the identity servers they may use."
371
+ },
339
372
  "EmailConfig": {
340
373
  "type": "object",
341
374
  "properties": {
342
375
  "url": {
343
376
  "type": "string",
344
- "description": "Base URL of email-service. Default: `https://email.shellui.com` when `email` is set and this is omitted. Local: `http://localhost:8003`."
377
+ "description": "Base URL of email-service. Required for apps to get email. There is no built-in default. Local: `http://localhost:8003`."
345
378
  },
346
379
  "showInAdmin": {
347
380
  "type": "boolean",
@@ -349,7 +382,7 @@
349
382
  }
350
383
  },
351
384
  "additionalProperties": false,
352
- "description": "Optional email-service wiring for Admin → Email and iframe apps. When `email` is set and `url` is omitted, the shell uses `https://email.shellui.com`."
385
+ "description": "Optional email-service wiring for Admin → Email and iframe apps. The shell never invents a URL: without `url`, apps get no email service."
353
386
  },
354
387
  "StorageConfig": {
355
388
  "type": "object",
@@ -73,8 +73,10 @@ export const ContentView = ({
73
73
  const iframeRef = useRef<HTMLIFrameElement>(null);
74
74
  const cancelRevealRef = useRef<(() => void) | null>(null);
75
75
  const mountTimeRef = useRef(Date.now());
76
- /** Shell path last reported by the iframe — skip driving iframe when we caused the location change. */
76
+ /** Shell path last synced with the iframe. */
77
77
  const lastShellPathFromIframeRef = useRef<string | null>(null);
78
+ /** Iframe reports not rendered back yet: their echo must not drive the iframe. */
79
+ const pendingFromIframeRef = useRef<string[]>([]);
78
80
  const skipInitialShellSyncRef = useRef(true);
79
81
  const prevNavPathRef = useRef(navItem?.path ?? '');
80
82
 
@@ -119,9 +121,16 @@ export const ContentView = ({
119
121
  return;
120
122
  }
121
123
 
124
+ const echo = pendingFromIframeRef.current.indexOf(currentShellPath);
125
+ if (echo >= 0 && !navItemChanged) {
126
+ pendingFromIframeRef.current = pendingFromIframeRef.current.slice(echo + 1);
127
+ lastShellPathFromIframeRef.current = currentShellPath;
128
+ return;
129
+ }
122
130
  if (lastShellPathFromIframeRef.current === currentShellPath && !navItemChanged) {
123
131
  return;
124
132
  }
133
+ pendingFromIframeRef.current = [];
125
134
 
126
135
  lastShellPathFromIframeRef.current = currentShellPath;
127
136
  mountTimeRef.current = Date.now();
@@ -173,7 +182,7 @@ export const ContentView = ({
173
182
  return;
174
183
  }
175
184
 
176
- const { pathname, search, hash } = data.payload as ShellUIUrlPayload;
185
+ const { pathname, search, hash, replace } = data.payload as ShellUIUrlPayload;
177
186
  // Shell URL is always path + search only (no hash) so it's transparent whether the sub-app uses hash routing or not
178
187
  let pathSegment: string;
179
188
  if (isHashRouterNavItem(navItem) && hash) {
@@ -223,17 +232,19 @@ export const ContentView = ({
223
232
  const normalizedNewPathname = newPathParts?.[1]?.replace(/\/+$/, '') || '/';
224
233
  const normalizedNewPath = normalizedNewPathname + (newPathParts?.[2] || '');
225
234
 
226
- // Mark before navigate so the shell-sync effect does not reload the iframe
227
- lastShellPathFromIframeRef.current = normalizedNewPath;
228
-
229
235
  if (currentPath !== normalizedNewPath) {
230
236
  if (!isSafeShellPath(normalizedNewPath)) {
231
237
  logger.warn('ContentView: refused unsafe shell path from iframe', normalizedNewPath);
232
238
  return;
233
239
  }
234
- // Push — iframe pushState is replace-only when embedded, so the shell
235
- // is the sole owner of back/forward entries.
236
- navigate(newShellPath);
240
+ // Mark before navigate so the shell-sync effect does not drive the iframe back.
241
+ pendingFromIframeRef.current = [
242
+ ...pendingFromIframeRef.current.slice(-19),
243
+ normalizedNewPath,
244
+ ];
245
+ // Iframe pushState is replace-only when embedded, so the shell owns back and
246
+ // forward. A child redirect replaces, so it never adds an entry.
247
+ navigate(newShellPath, { replace: replace === true });
237
248
  }
238
249
  },
239
250
  );
@@ -1,6 +1,7 @@
1
1
  import * as React from 'react';
2
2
  import { cva, type VariantProps } from 'class-variance-authority';
3
3
  import { Slot } from '@radix-ui/react-slot';
4
+ import { useTranslation } from 'react-i18next';
4
5
 
5
6
  import { useIsMobile } from '../../hooks/use-mobile';
6
7
  import { cn } from '../../lib/utils';
@@ -260,6 +261,7 @@ function Sidebar({
260
261
  variant?: 'sidebar' | 'floating' | 'inset';
261
262
  collapsible?: 'offcanvas' | 'icon' | 'none';
262
263
  }) {
264
+ const { t } = useTranslation();
263
265
  const context = React.useContext(SidebarContext);
264
266
 
265
267
  if (collapsible === 'none') {
@@ -305,8 +307,8 @@ function Sidebar({
305
307
  side={side}
306
308
  >
307
309
  <SheetHeader className="sr-only">
308
- <SheetTitle>Sidebar</SheetTitle>
309
- <SheetDescription>Displays the mobile sidebar.</SheetDescription>
310
+ <SheetTitle>{t('desktopChrome.navigation')}</SheetTitle>
311
+ <SheetDescription>{t('shellChrome.sheetDescription')}</SheetDescription>
310
312
  </SheetHeader>
311
313
  <div className="flex h-full min-h-0 w-full flex-col overflow-hidden pt-[var(--shellui-safe-area-top)] pr-[var(--shellui-safe-area-right)] pl-[var(--shellui-safe-area-left)]">
312
314
  {children}
@@ -376,6 +378,7 @@ function Sidebar({
376
378
 
377
379
  function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
378
380
  const { toggleSidebar } = useSidebar();
381
+ const { t } = useTranslation();
379
382
 
380
383
  return (
381
384
  <Button
@@ -384,7 +387,7 @@ function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<t
384
387
  data-slot="sidebar-trigger"
385
388
  variant="ghost"
386
389
  size="icon"
387
- aria-label="Toggle Sidebar"
390
+ aria-label={t('shellChrome.toggleSidebar')}
388
391
  className={cn(
389
392
  'size-7 touch-manipulation select-none [-webkit-touch-callout:none]',
390
393
  className,
@@ -413,6 +416,7 @@ function SidebarRail({
413
416
  side?: 'left' | 'right';
414
417
  }) {
415
418
  const { toggleSidebar, state, width, setWidth, setIsResizing } = useSidebar();
419
+ const { t } = useTranslation();
416
420
  const dragRef = React.useRef<{
417
421
  startX: number;
418
422
  startWidth: number;
@@ -486,9 +490,11 @@ function SidebarRail({
486
490
  data-slot="sidebar-rail"
487
491
  data-shellui-no-drag=""
488
492
  data-placement={placement}
489
- aria-label={state === 'expanded' ? 'Resize Sidebar' : 'Toggle Sidebar'}
493
+ aria-label={
494
+ state === 'expanded' ? t('shellChrome.resizeSidebar') : t('shellChrome.toggleSidebar')
495
+ }
490
496
  tabIndex={-1}
491
- title={state === 'expanded' ? 'Drag to resize' : 'Toggle Sidebar'}
497
+ title={state === 'expanded' ? t('shellChrome.dragToResize') : t('shellChrome.toggleSidebar')}
492
498
  onClick={(event) => {
493
499
  if (didDragRef.current) {
494
500
  didDragRef.current = false;
@@ -10,8 +10,8 @@ import { useConfig } from '../config/useConfig';
10
10
  import type { NavigationItem } from '../config/types';
11
11
  import { AppLayout } from '../layouts/AppLayout';
12
12
  import {
13
- MAC_TRAFFIC_LIGHTS_GAP_PX,
14
- MAC_TRAFFIC_LIGHTS_WIDTH_PX,
13
+ DESKTOP_TITLEBAR_HEIGHT_PX,
14
+ MAC_LIGHTS_SAFE_PX,
15
15
  isShellUiRootWindow,
16
16
  SafeAreaTopbarOffset,
17
17
  SafeAreaTopbarStrip,
@@ -74,9 +74,9 @@ export const AdminView = () => {
74
74
 
75
75
  const showSafeAreaTopbar = isShellUiRootWindow();
76
76
  const trafficLights = useMacTrafficLights();
77
- const chromeInset = trafficLights
78
- ? MAC_TRAFFIC_LIGHTS_WIDTH_PX + MAC_TRAFFIC_LIGHTS_GAP_PX
79
- : undefined;
77
+ const chromeInset = trafficLights ? MAC_LIGHTS_SAFE_PX : undefined;
78
+ // macOS desktop: the header is the 32px strip, controls centre on the lights line.
79
+ const macStrip = trafficLights && !isMobile;
80
80
  const headerStyle = {
81
81
  paddingLeft: chromeInset ?? 'max(0.5rem, var(--shellui-safe-area-left))',
82
82
  paddingRight: 'max(0.75rem, var(--shellui-safe-area-right))',
@@ -85,7 +85,7 @@ export const AdminView = () => {
85
85
  paddingTop: 'var(--shellui-safe-area-top)',
86
86
  height: `calc(${ADMIN_HEADER_HEIGHT_PX}px + var(--shellui-safe-area-top))`,
87
87
  }
88
- : { height: ADMIN_HEADER_HEIGHT_PX }),
88
+ : { height: macStrip ? DESKTOP_TITLEBAR_HEIGHT_PX : ADMIN_HEADER_HEIGHT_PX }),
89
89
  } as const;
90
90
 
91
91
  return (
@@ -102,11 +102,13 @@ export const AdminView = () => {
102
102
  {...(trafficLights
103
103
  ? { 'data-shellui-drag-region': '', 'data-tauri-drag-region': '' }
104
104
  : {})}
105
+ {...(macStrip ? { 'data-shellui-mac-strip': '' } : {})}
105
106
  >
106
107
  <Button
107
108
  type="button"
108
109
  variant="ghost"
109
110
  size="sm"
111
+ className={macStrip ? 'h-6 px-2 text-[13px]' : undefined}
110
112
  data-shellui-no-drag=""
111
113
  onClick={() => navigate('/')}
112
114
  >
@@ -127,6 +129,7 @@ export const AdminView = () => {
127
129
  </Button>
128
130
  <div
129
131
  data-shellui-no-drag=""
132
+ data-shellui-strip-end=""
130
133
  className="flex items-center gap-2"
131
134
  >
132
135
  <LoginButton
@@ -27,6 +27,7 @@ import {
27
27
  hasStoredAuthSession,
28
28
  inferAccessPendingErrorCode,
29
29
  isBffAuthEnabledFromConfig,
30
+ canRestoreStoredSession,
30
31
  isSessionExpired,
31
32
  isTokenAutoRefreshDisabled,
32
33
  logoutBffAuthSession,
@@ -38,6 +39,7 @@ import {
38
39
  type InFlightSlot,
39
40
  } from './utils';
40
41
  import { buildAuthUrlWithNext } from './utils/buildAuthUrlWithNext';
42
+ import { resolveSdkLoginRedirectPath } from './utils/resolveSdkLoginRedirectPath';
41
43
  import {
42
44
  beginDesktopOAuth,
43
45
  clearDesktopPkce,
@@ -252,6 +254,17 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
252
254
  return;
253
255
  }
254
256
 
257
+ // A new tab has the shared profile but not the tab-scoped refresh token. Treat it as
258
+ // signed out instead of a signed-in session with no token. Keep storage: another tab
259
+ // may still own this session.
260
+ if (!canRestoreStoredSession(stored, bffAuthEnabled)) {
261
+ if (!cancelled) {
262
+ setSession(null);
263
+ setIsLoading(false);
264
+ }
265
+ return;
266
+ }
267
+
255
268
  const applyRestoredSession = async (source: AuthSession) => {
256
269
  try {
257
270
  const restored = await shareInFlight(restoreRefreshSlot, () =>
@@ -849,8 +862,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
849
862
  });
850
863
  } catch (err) {
851
864
  reply('error');
852
- const errorCode = getAuthRequestErrorCode(err);
853
- if (errorCode === 'last_company_owner') {
865
+ const deleteErrorCode = getAuthRequestErrorCode(err);
866
+ if (deleteErrorCode === 'last_company_owner') {
854
867
  const companies =
855
868
  err instanceof AuthRequestError && Array.isArray(err.details.companies)
856
869
  ? (err.details.companies as Array<{ name?: unknown }>)
@@ -868,7 +881,7 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
868
881
  });
869
882
  return;
870
883
  }
871
- if (errorCode === 'recent_login_required') {
884
+ if (deleteErrorCode === 'recent_login_required') {
872
885
  shellui.dialog({
873
886
  title: t('userAccount.deleteAccount.reauthTitle'),
874
887
  description: t('userAccount.deleteAccount.reauthDescription'),
@@ -930,7 +943,15 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
930
943
  return;
931
944
  }
932
945
 
933
- startOAuth(provider, payload.redirectPath || urls.login, payload.oauthClientId);
946
+ const currentPath =
947
+ typeof window !== 'undefined'
948
+ ? `${window.location.pathname}${window.location.search}`
949
+ : '/';
950
+ startOAuth(
951
+ provider,
952
+ resolveSdkLoginRedirectPath(payload.redirectPath, currentPath),
953
+ payload.oauthClientId,
954
+ );
934
955
  });
935
956
 
936
957
  return () => cleanup();
@@ -11,6 +11,8 @@ import {
11
11
  getAppBackendSession,
12
12
  setAppBackendFactory,
13
13
  setAppBackendSignIn,
14
+ setAppBackendTokenExchange,
15
+ resetAppBackendTokenExchange,
14
16
  } from './appBackendSessions';
15
17
  import { resolveAppBackendConfig } from './identity';
16
18
  import { runSilentPkceSignIn } from './silentSignIn';
@@ -192,4 +194,136 @@ describe('app backend sessions', () => {
192
194
  );
193
195
  expect(dumped).not.toContain(APP_BACKEND_REFRESH_PREFIX);
194
196
  });
197
+
198
+ describe('token exchange for upstream identity servers', () => {
199
+ const exchange = vi.fn();
200
+ const jwt = (sub: string, jti: string) =>
201
+ `h.${btoa(JSON.stringify({ sub, jti })).replace(/=+$/, '')}.s`;
202
+ let shellToken: string | null = jwt('1', 'g1');
203
+
204
+ function upstream(companyId?: number) {
205
+ const identity = resolveAppBackendConfig(
206
+ { url: 'https://id.eu.example', companyId, provider: 'upstream', type: 'shellui' },
207
+ { backend: { type: 'shellui', url: 'https://id.example.com', companyId: 1 } },
208
+ );
209
+ if (!identity) throw new Error('expected identity');
210
+ return identity;
211
+ }
212
+
213
+ function due(accessToken: string, refreshToken: string): AuthSession {
214
+ return {
215
+ ...session(accessToken, refreshToken),
216
+ expiresAt: Math.floor(Date.now() / 1000) + 10,
217
+ };
218
+ }
219
+
220
+ function stored(): string {
221
+ return JSON.stringify(
222
+ [...Array(sessionStorage.length).keys()].map((index) => {
223
+ const key = sessionStorage.key(index) ?? '';
224
+ return [key, sessionStorage.getItem(key)];
225
+ }),
226
+ );
227
+ }
228
+
229
+ beforeEach(() => {
230
+ shellToken = jwt('1', 'g1');
231
+ exchange.mockReset();
232
+ setAppBackendTokenExchange(async () => shellToken, exchange);
233
+ });
234
+
235
+ afterEach(() => {
236
+ resetAppBackendTokenExchange();
237
+ });
238
+
239
+ it('exchanges the shell token at the regional server and never uses silent sign-in', async () => {
240
+ exchange.mockResolvedValue({ ok: true, session: session('regional-1', 'regional-refresh') });
241
+ const identity = upstream(5);
242
+
243
+ const token = await ensureAppBackendSession(identity, { allowSilent: false });
244
+
245
+ expect(token).toBe('regional-1');
246
+ expect(exchange).toHaveBeenCalledWith(
247
+ expect.objectContaining({
248
+ backendUrl: 'https://id.eu.example',
249
+ companyId: 5,
250
+ shellAccessToken: shellToken,
251
+ }),
252
+ );
253
+ expect(signIn).not.toHaveBeenCalled();
254
+ expect(getAppBackendSession(identity.key)?.accessToken).toBe('regional-1');
255
+ expect(stored()).toContain('regional-refresh');
256
+ expect(stored()).not.toContain('regional-1"');
257
+ expect(stored()).not.toContain(shellToken);
258
+ });
259
+
260
+ it('renews with the regional refresh token, not a new exchange', async () => {
261
+ exchange.mockResolvedValueOnce({ ok: true, session: due('regional-old', 'regional-r1') });
262
+ const identity = upstream(5);
263
+ await ensureAppBackendSession(identity);
264
+ refreshAuthSession.mockResolvedValueOnce(session('regional-new', 'regional-r2'));
265
+
266
+ shellToken = jwt('1', 'g2');
267
+ expect(await ensureAppBackendSession(identity)).toBe('regional-new');
268
+ expect(refreshAuthSession).toHaveBeenCalledWith(
269
+ expect.objectContaining({ refreshToken: 'regional-r1' }),
270
+ expect.any(Number),
271
+ );
272
+ expect(factory).toHaveBeenCalledWith(
273
+ expect.objectContaining({ url: 'https://id.eu.example' }),
274
+ );
275
+ expect(exchange).toHaveBeenCalledTimes(1);
276
+ expect(stored()).toContain('regional-r2');
277
+ });
278
+
279
+ it('exchanges again when the regional refresh fails', async () => {
280
+ exchange.mockResolvedValueOnce({ ok: true, session: due('regional-old', 'regional-r1') });
281
+ const identity = upstream(5);
282
+ await ensureAppBackendSession(identity);
283
+ refreshAuthSession.mockRejectedValueOnce(new Error('HTTP 401'));
284
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-new', 'regional-r3') });
285
+
286
+ expect(await ensureAppBackendSession(identity)).toBe('regional-new');
287
+ expect(exchange).toHaveBeenCalledTimes(2);
288
+ });
289
+
290
+ it('drops the regional session and exchanges when the shell user changes', async () => {
291
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-ada', 'r-ada') });
292
+ const identity = upstream(5);
293
+ await ensureAppBackendSession(identity);
294
+
295
+ shellToken = jwt('2', 'g9');
296
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-bob', 'r-bob') });
297
+ expect(await ensureAppBackendSession(identity)).toBe('regional-bob');
298
+ expect(refreshAuthSession).not.toHaveBeenCalled();
299
+ expect(stored()).not.toContain('r-ada');
300
+ });
301
+
302
+ it('does not retry a failed exchange until the shell token changes', async () => {
303
+ exchange.mockResolvedValue({ ok: false, reason: 'invalid_grant' });
304
+ const identity = upstream(5);
305
+
306
+ expect(await ensureAppBackendSession(identity)).toBeNull();
307
+ expect(await ensureAppBackendSession(identity)).toBeNull();
308
+ expect(exchange).toHaveBeenCalledTimes(1);
309
+
310
+ shellToken = jwt('1', 'g2');
311
+ exchange.mockResolvedValue({ ok: true, session: session('regional-2') });
312
+ expect(await ensureAppBackendSession(identity)).toBe('regional-2');
313
+ });
314
+
315
+ it('clears the regional session on shell sign-out', async () => {
316
+ exchange.mockResolvedValueOnce({ ok: true, session: session('regional-1', 'r1') });
317
+ const identity = upstream(5);
318
+ await ensureAppBackendSession(identity);
319
+
320
+ await endAppBackendSessions();
321
+ expect(getAppBackendSession(identity.key)).toBeNull();
322
+ expect(sessionStorage.length).toBe(0);
323
+
324
+ shellToken = null;
325
+ expect(await ensureAppBackendSession(identity)).toBeNull();
326
+ expect(exchange).toHaveBeenCalledTimes(1);
327
+ });
328
+ });
195
329
  });