@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,204 @@
1
+ import type { Settings } from '@shellui/sdk';
2
+ import type {
3
+ EmailConfig,
4
+ HostingConfig,
5
+ NavigationItem,
6
+ ShellUIConfig,
7
+ StorageConfig,
8
+ } from '../../config/types';
9
+ import { isShellSettingsFrameSrc, isTrustedFrameForAuthToken } from '../../security/trustedFrames';
10
+ import urls from '../../../constants/urls';
11
+ import type { AuthSession } from '../types';
12
+ import {
13
+ resolveFrameAppBackend,
14
+ resolveFrameNavigationItem,
15
+ type ResolvedAppBackend,
16
+ } from './identity';
17
+
18
+ /** Present keys replace the shell service. `null` sends no URL for that service. */
19
+ export type FrameServiceOverrides = {
20
+ storage?: StorageConfig | null;
21
+ email?: EmailConfig | null;
22
+ hosting?: HostingConfig | null;
23
+ };
24
+
25
+ export type FrameAuthDelivery = {
26
+ includeAuthAccessToken: boolean;
27
+ /** Never the shell token when the frame's backend differs. */
28
+ accessToken: string | null;
29
+ overrideAuthBackend: boolean;
30
+ authBackendBaseUrl: string | null;
31
+ overrideUser: boolean;
32
+ settingsUser: Settings['user'];
33
+ services: FrameServiceOverrides;
34
+ };
35
+
36
+ const settingsUserFromSession = (session: AuthSession | null): Settings['user'] => {
37
+ if (!session) return null;
38
+ return {
39
+ id: session.userId,
40
+ email: session.userEmail,
41
+ name: session.userName,
42
+ profilePicture: session.userAvatarUrl,
43
+ authProvider: session.provider,
44
+ groups: session.userGroups?.length ? [...session.userGroups] : null,
45
+ isStaff: session.userIsStaff,
46
+ isCompanyOwner: session.userIsCompanyOwner,
47
+ };
48
+ };
49
+
50
+ function currentShellOrigin(explicit?: string | null): string | null {
51
+ if (explicit) return explicit;
52
+ const origin = globalThis.window?.location?.origin;
53
+ return typeof origin === 'string' && origin.length > 0 ? origin : null;
54
+ }
55
+
56
+ function shellDelivery(
57
+ frameSrc: string,
58
+ config: ShellUIConfig | undefined,
59
+ shellAccessToken: string | null,
60
+ ): FrameAuthDelivery {
61
+ return {
62
+ includeAuthAccessToken: isTrustedFrameForAuthToken(frameSrc, config),
63
+ accessToken: shellAccessToken,
64
+ overrideAuthBackend: false,
65
+ authBackendBaseUrl: null,
66
+ overrideUser: false,
67
+ settingsUser: null,
68
+ services: {},
69
+ };
70
+ }
71
+
72
+ function foreignDelivery(
73
+ frameSrc: string,
74
+ config: ShellUIConfig | undefined,
75
+ identity: ResolvedAppBackend | null,
76
+ session: AuthSession | null,
77
+ services: FrameServiceOverrides,
78
+ ): FrameAuthDelivery {
79
+ const trusted = isTrustedFrameForAuthToken(frameSrc, config);
80
+ const foreignToken = session?.accessToken ?? null;
81
+ return {
82
+ includeAuthAccessToken: trusted,
83
+ accessToken: trusted ? foreignToken : null,
84
+ overrideAuthBackend: true,
85
+ authBackendBaseUrl: identity?.type === 'shellui' ? identity.url : null,
86
+ overrideUser: true,
87
+ settingsUser: settingsUserFromSession(session),
88
+ services,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * A service field on the item replaces the shell value.
94
+ * When the item's identity server differs and the field is absent, send none.
95
+ */
96
+ function serviceOverrides(item: NavigationItem | null, failClosed: boolean): FrameServiceOverrides {
97
+ const overrides: FrameServiceOverrides = {};
98
+ if (item?.storage !== undefined) overrides.storage = item.storage;
99
+ else if (failClosed) overrides.storage = null;
100
+ if (item?.email !== undefined) overrides.email = item.email;
101
+ else if (failClosed) overrides.email = null;
102
+ if (item?.hosting !== undefined) overrides.hosting = item.hosting;
103
+ else if (failClosed) overrides.hosting = null;
104
+ return overrides;
105
+ }
106
+
107
+ /**
108
+ * Per-frame auth fields for `SHELLUI_SETTINGS`.
109
+ * No app `backend` (or the same server as the shell) keeps today's token and URL.
110
+ */
111
+ export function resolveFrameAuthDelivery(input: {
112
+ frameSrc: string;
113
+ config?: ShellUIConfig;
114
+ shellAccessToken: string | null;
115
+ getAppSession: (key: string) => AuthSession | null;
116
+ shellOrigin?: string | null;
117
+ }): FrameAuthDelivery {
118
+ const { frameSrc, config, shellAccessToken, getAppSession } = input;
119
+ const shellOrigin = currentShellOrigin(input.shellOrigin);
120
+ if (shellOrigin && isShellSettingsFrameSrc(frameSrc, shellOrigin, urls.settings)) {
121
+ return shellDelivery(frameSrc, config, shellAccessToken);
122
+ }
123
+
124
+ const resolved = resolveFrameAppBackend(frameSrc, config);
125
+ const item = resolveFrameNavigationItem(frameSrc, config);
126
+ const failClosed = resolved.kind !== 'shell';
127
+ const services = serviceOverrides(item, failClosed);
128
+ if (resolved.kind === 'shell') {
129
+ return { ...shellDelivery(frameSrc, config, shellAccessToken), services };
130
+ }
131
+ if (resolved.kind === 'withhold') {
132
+ return foreignDelivery(frameSrc, config, null, null, services);
133
+ }
134
+ return foreignDelivery(
135
+ frameSrc,
136
+ config,
137
+ resolved.identity,
138
+ getAppSession(resolved.identity.key),
139
+ services,
140
+ );
141
+ }
142
+
143
+ export type FrameAuthPropagationOptions = {
144
+ includeAuthAccessToken: boolean;
145
+ accessToken: string | null;
146
+ authBackendBaseUrl?: string | null;
147
+ settingsUser?: Settings['user'];
148
+ storage?: StorageConfig | null;
149
+ email?: EmailConfig | null;
150
+ hosting?: HostingConfig | null;
151
+ };
152
+
153
+ function toPropagationOptions(delivery: FrameAuthDelivery): FrameAuthPropagationOptions {
154
+ return {
155
+ includeAuthAccessToken: delivery.includeAuthAccessToken,
156
+ accessToken: delivery.accessToken,
157
+ ...(delivery.overrideAuthBackend ? { authBackendBaseUrl: delivery.authBackendBaseUrl } : {}),
158
+ ...(delivery.overrideUser ? { settingsUser: delivery.settingsUser } : {}),
159
+ ...delivery.services,
160
+ };
161
+ }
162
+
163
+ /** Options for `buildSettingsForPropagation`. Shell frames omit the override keys. */
164
+ export function frameAuthPropagationOptions(input: {
165
+ frameSrc: string;
166
+ config?: ShellUIConfig;
167
+ shellAccessToken: string | null;
168
+ getAppSession: (key: string) => AuthSession | null;
169
+ shellOrigin?: string | null;
170
+ }): FrameAuthPropagationOptions {
171
+ return toPropagationOptions(resolveFrameAuthDelivery(input));
172
+ }
173
+
174
+ /**
175
+ * Auth fields for a child app hosted inside an embedded app (`createAppFrame`).
176
+ * The shell token is never sent. With no allowed identity server the child gets
177
+ * no token and no user. Service URLs are the ones the host passed and the shell
178
+ * allowed (`childFrames.serviceOrigins`); any other service is `null`.
179
+ */
180
+ export function childFrameAuthPropagationOptions(input: {
181
+ identity: ResolvedAppBackend | null;
182
+ getAppSession: (key: string) => AuthSession | null;
183
+ services?: Partial<Record<'email' | 'storage' | 'files' | 'hosting', string | null>> | null;
184
+ }): FrameAuthPropagationOptions {
185
+ const { identity, getAppSession } = input;
186
+ const allowed = input.services ?? {};
187
+ const session = identity ? getAppSession(identity.key) : null;
188
+ return toPropagationOptions({
189
+ includeAuthAccessToken: Boolean(identity),
190
+ accessToken: session?.accessToken ?? null,
191
+ overrideAuthBackend: true,
192
+ authBackendBaseUrl: identity?.type === 'shellui' ? identity.url : null,
193
+ overrideUser: true,
194
+ settingsUser: settingsUserFromSession(session),
195
+ services: {
196
+ email: allowed.email ? { url: allowed.email } : null,
197
+ // The files app URL rides on storage and is dropped when storage is not allowed.
198
+ storage: allowed.storage
199
+ ? { url: allowed.storage, ...(allowed.files ? { filesUrl: allowed.files } : {}) }
200
+ : null,
201
+ hosting: allowed.hosting ? { url: allowed.hosting } : null,
202
+ },
203
+ });
204
+ }
@@ -0,0 +1,201 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { ShellUIConfig } from '../../config/types';
3
+ import { listDistinctAppBackends, normalizeBackendUrl, resolveFrameAppBackend } from './identity';
4
+
5
+ const shellBackend = {
6
+ type: 'shellui' as const,
7
+ url: 'https://id.example.com/',
8
+ companyId: 1,
9
+ login: { oauthProviders: ['google'] },
10
+ };
11
+
12
+ function config(extra?: Partial<ShellUIConfig>): ShellUIConfig {
13
+ return {
14
+ backend: shellBackend,
15
+ navigation: [
16
+ {
17
+ label: 'Billing',
18
+ path: 'billing',
19
+ url: 'https://billing.example/',
20
+ safeForAuthToken: true,
21
+ },
22
+ ],
23
+ ...extra,
24
+ };
25
+ }
26
+
27
+ describe('normalizeBackendUrl', () => {
28
+ it('drops a trailing slash and lowercases the host', () => {
29
+ expect(normalizeBackendUrl('HTTPS://ID.Example.com/')).toBe('https://id.example.com');
30
+ });
31
+
32
+ it('rejects non-http URLs', () => {
33
+ expect(normalizeBackendUrl('javascript:alert(1)')).toBeNull();
34
+ expect(normalizeBackendUrl('')).toBeNull();
35
+ });
36
+ });
37
+
38
+ describe('resolveFrameAppBackend', () => {
39
+ it('falls back to the shell backend when the item has no override', () => {
40
+ expect(resolveFrameAppBackend('https://billing.example/', config())).toEqual({ kind: 'shell' });
41
+ });
42
+
43
+ it('falls back when the override URL is the shell server, including a trailing slash', () => {
44
+ const next = config({
45
+ navigation: [
46
+ {
47
+ label: 'Billing',
48
+ path: 'billing',
49
+ url: 'https://billing.example/',
50
+ safeForAuthToken: true,
51
+ backend: { url: 'https://id.example.com/' },
52
+ },
53
+ ],
54
+ });
55
+ expect(resolveFrameAppBackend('https://billing.example/app', next)).toEqual({ kind: 'shell' });
56
+ });
57
+
58
+ it('falls back when companyId is omitted on the same server', () => {
59
+ const next = config({
60
+ navigation: [
61
+ {
62
+ label: 'Billing',
63
+ path: 'billing',
64
+ url: 'https://billing.example/',
65
+ backend: { url: 'https://id.example.com', type: 'shellui' },
66
+ },
67
+ ],
68
+ });
69
+ expect(resolveFrameAppBackend('https://billing.example/', next).kind).toBe('shell');
70
+ });
71
+
72
+ it('treats a different URL as a foreign identity server', () => {
73
+ const next = config({
74
+ navigation: [
75
+ {
76
+ label: 'Directory',
77
+ path: 'directory',
78
+ url: 'https://directory.example/',
79
+ safeForAuthToken: true,
80
+ backend: { url: 'https://id.directory.example/', companyId: 4, provider: 'Google' },
81
+ },
82
+ ],
83
+ });
84
+ const resolved = resolveFrameAppBackend('https://directory.example/people', next);
85
+ expect(resolved.kind).toBe('foreign');
86
+ if (resolved.kind !== 'foreign') return;
87
+ expect(resolved.identity.url).toBe('https://id.directory.example');
88
+ expect(resolved.identity.companyId).toBe(4);
89
+ expect(resolved.identity.provider).toBe('google');
90
+ expect(resolved.identity.key).not.toContain('https://id.example.com');
91
+ });
92
+
93
+ it('treats a different company id on the same URL as a foreign server', () => {
94
+ const next = config({
95
+ navigation: [
96
+ {
97
+ label: 'Directory',
98
+ path: 'directory',
99
+ url: 'https://directory.example/',
100
+ backend: { url: 'https://id.example.com', companyId: 9 },
101
+ },
102
+ ],
103
+ });
104
+ expect(resolveFrameAppBackend('https://directory.example/', next).kind).toBe('foreign');
105
+ });
106
+
107
+ it('withholds the shell session when the override URL cannot be used', () => {
108
+ const next = config({
109
+ navigation: [
110
+ {
111
+ label: 'Directory',
112
+ path: 'directory',
113
+ url: 'https://directory.example/',
114
+ backend: { url: 'not a url' },
115
+ },
116
+ ],
117
+ });
118
+ expect(resolveFrameAppBackend('https://directory.example/', next)).toEqual({
119
+ kind: 'withhold',
120
+ });
121
+ });
122
+
123
+ it('lets a more specific item without a backend keep the shell session', () => {
124
+ const next = config({
125
+ navigation: [
126
+ {
127
+ label: 'Apps',
128
+ path: 'apps',
129
+ url: 'https://apps.example/',
130
+ backend: { url: 'https://id.other.example' },
131
+ },
132
+ {
133
+ label: 'Billing',
134
+ path: 'billing',
135
+ url: 'https://apps.example/billing',
136
+ safeForAuthToken: true,
137
+ },
138
+ ],
139
+ });
140
+ expect(resolveFrameAppBackend('https://apps.example/billing/invoices', next).kind).toBe(
141
+ 'shell',
142
+ );
143
+ expect(resolveFrameAppBackend('https://apps.example/other', next).kind).toBe('foreign');
144
+ });
145
+
146
+ it('ignores external items and reads administration items', () => {
147
+ const next = config({
148
+ navigation: [
149
+ {
150
+ label: 'Away',
151
+ path: 'away',
152
+ url: 'https://directory.example/',
153
+ openIn: 'external',
154
+ backend: { url: 'https://id.external.example' },
155
+ },
156
+ ],
157
+ administration: {
158
+ title: 'Admin',
159
+ navigation: [
160
+ {
161
+ label: 'Directory',
162
+ path: 'directory',
163
+ url: 'https://directory.example/',
164
+ backend: { url: 'https://id.directory.example' },
165
+ },
166
+ ],
167
+ },
168
+ });
169
+ const resolved = resolveFrameAppBackend('https://directory.example/', next);
170
+ expect(resolved.kind).toBe('foreign');
171
+ if (resolved.kind !== 'foreign') return;
172
+ expect(resolved.identity.url).toBe('https://id.directory.example');
173
+ });
174
+
175
+ it('lists each foreign server once', () => {
176
+ const next = config({
177
+ navigation: [
178
+ {
179
+ label: 'One',
180
+ path: 'one',
181
+ url: 'https://one.example/',
182
+ backend: { url: 'https://id.other.example' },
183
+ },
184
+ {
185
+ label: 'Two',
186
+ path: 'two',
187
+ url: 'https://two.example/',
188
+ backend: { url: 'https://id.other.example/' },
189
+ },
190
+ {
191
+ label: 'Billing',
192
+ path: 'billing',
193
+ url: 'https://billing.example/',
194
+ },
195
+ ],
196
+ });
197
+ expect(listDistinctAppBackends(next).map((item) => item.url)).toEqual([
198
+ 'https://id.other.example',
199
+ ]);
200
+ });
201
+ });
@@ -0,0 +1,173 @@
1
+ import type { AppBackendConfig, NavigationItem, ShellUIConfig } from '../../config/types';
2
+ import { isFrameForAppUrl } from '../../layouts/utils';
3
+ import { flattenNavigationItems } from '../../settings/utils/flattenNavigationItems';
4
+
5
+ export type ResolvedAppBackend = {
6
+ key: string;
7
+ type: 'shellui' | 'supabase';
8
+ url: string;
9
+ companyId?: string | number;
10
+ publishableKey?: string;
11
+ provider: string | null;
12
+ };
13
+
14
+ export type FrameAppBackend =
15
+ | { kind: 'shell' }
16
+ | { kind: 'foreign'; identity: ResolvedAppBackend }
17
+ | { kind: 'withhold' };
18
+
19
+ /** http(s) base URL without trailing slash, query, or hash. Host is lowercased. */
20
+ export function normalizeBackendUrl(raw: string | null | undefined): string | null {
21
+ const trimmed = raw?.trim() ?? '';
22
+ if (!trimmed) return null;
23
+ try {
24
+ const url = new URL(trimmed);
25
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
26
+ const path = url.pathname.replace(/\/+$/, '');
27
+ return `${url.origin}${path === '/' ? '' : path}`;
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ function companyKey(companyId: string | number | undefined): string {
34
+ if (companyId === undefined || companyId === null) return '';
35
+ const text = `${companyId}`.trim();
36
+ return text;
37
+ }
38
+
39
+ export function appBackendKey(parts: {
40
+ type: string;
41
+ url: string;
42
+ companyId?: string | number;
43
+ }): string {
44
+ return `${parts.type}\n${parts.url}\n${companyKey(parts.companyId)}`;
45
+ }
46
+
47
+ function shellProvider(config?: ShellUIConfig): string | null {
48
+ const providers = config?.backend?.login?.oauthProviders;
49
+ const first = providers?.find((provider) => typeof provider === 'string' && provider.trim());
50
+ return first ? first.trim().toLowerCase() : null;
51
+ }
52
+
53
+ function resolveType(
54
+ override: AppBackendConfig,
55
+ config?: ShellUIConfig,
56
+ ): 'shellui' | 'supabase' | null {
57
+ const type = override.type ?? config?.backend?.type ?? 'shellui';
58
+ if (type === 'shellui' || type === 'supabase') return type;
59
+ return null;
60
+ }
61
+
62
+ /**
63
+ * Same server as the shell when type and URL match and the app does not name
64
+ * a different tenant. An omitted `companyId` keeps the shell session.
65
+ */
66
+ export function isDistinctFromShell(identity: ResolvedAppBackend, config?: ShellUIConfig): boolean {
67
+ const shell = config?.backend;
68
+ const shellUrl = normalizeBackendUrl(shell?.url);
69
+ if (!shell?.type || !shellUrl) return true;
70
+ if (identity.type !== shell.type || identity.url !== shellUrl) return true;
71
+ if (companyKey(identity.companyId) === '') return false;
72
+ return `${identity.companyId}` !== `${shell.companyId ?? ''}`;
73
+ }
74
+
75
+ export function resolveAppBackendConfig(
76
+ override: AppBackendConfig | undefined,
77
+ config?: ShellUIConfig,
78
+ ): ResolvedAppBackend | null {
79
+ if (!override) return null;
80
+ const type = resolveType(override, config);
81
+ const url = normalizeBackendUrl(override.url);
82
+ if (!type || !url) return null;
83
+ const provider = override.provider?.trim().toLowerCase() || shellProvider(config);
84
+ const companyId = companyKey(override.companyId) === '' ? undefined : override.companyId;
85
+ return {
86
+ type,
87
+ url,
88
+ ...(companyId !== undefined ? { companyId } : {}),
89
+ ...(override.publishableKey?.trim() ? { publishableKey: override.publishableKey.trim() } : {}),
90
+ provider,
91
+ key: appBackendKey({ type, url, companyId }),
92
+ };
93
+ }
94
+
95
+ function embeddedItems(config?: ShellUIConfig): NavigationItem[] {
96
+ const top = flattenNavigationItems(config?.navigation ?? []);
97
+ const admin = config?.administration?.navigation ?? [];
98
+ return [...top, ...admin].filter(
99
+ (item) => item.openIn !== 'external' && Boolean(item.url?.trim()),
100
+ );
101
+ }
102
+
103
+ /** Longer pathname wins so a site-root item does not override a nested app. */
104
+ export function appUrlSpecificity(appUrl: string): number {
105
+ try {
106
+ const url = new URL(appUrl, 'http://localhost');
107
+ const path = url.pathname.replace(/\/+$/, '');
108
+ const hash = (url.hash || '').replace(/^#\/?/, '').replace(/\/+$/, '');
109
+ return path.length * 1000 + hash.length;
110
+ } catch {
111
+ return 0;
112
+ }
113
+ }
114
+
115
+ function hasDistinctBackend(item: NavigationItem, config?: ShellUIConfig): boolean {
116
+ if (!item.backend) return false;
117
+ const identity = resolveAppBackendConfig(item.backend, config);
118
+ if (!identity) return true;
119
+ return isDistinctFromShell(identity, config);
120
+ }
121
+
122
+ function matchingItems(frameSrc: string, config?: ShellUIConfig): NavigationItem[] {
123
+ const matches = embeddedItems(config).filter((item) => isFrameMatch(frameSrc, item.url));
124
+ matches.sort((a, b) => {
125
+ const score = appUrlSpecificity(b.url) - appUrlSpecificity(a.url);
126
+ if (score !== 0) return score;
127
+ const aForeign = hasDistinctBackend(a, config) ? 1 : 0;
128
+ const bForeign = hasDistinctBackend(b, config) ? 1 : 0;
129
+ return bForeign - aForeign;
130
+ });
131
+ return matches;
132
+ }
133
+
134
+ /** Most specific embedded item for this frame, if any. */
135
+ export function resolveFrameNavigationItem(
136
+ frameSrc: string,
137
+ config?: ShellUIConfig,
138
+ ): NavigationItem | null {
139
+ return matchingItems(frameSrc, config)[0] ?? null;
140
+ }
141
+
142
+ /**
143
+ * Which identity server a frame should use.
144
+ * `shell` keeps today's single backend. `withhold` means the item named a backend
145
+ * we cannot use, so the shell token must not be sent. `foreign` is a different server.
146
+ */
147
+ export function resolveFrameAppBackend(frameSrc: string, config?: ShellUIConfig): FrameAppBackend {
148
+ const winner = matchingItems(frameSrc, config)[0];
149
+ if (!winner?.backend) return { kind: 'shell' };
150
+ const identity = resolveAppBackendConfig(winner.backend, config);
151
+ if (!identity) return { kind: 'withhold' };
152
+ if (!isDistinctFromShell(identity, config)) return { kind: 'shell' };
153
+ return { kind: 'foreign', identity };
154
+ }
155
+
156
+ function isFrameMatch(frameSrc: string, appUrl: string): boolean {
157
+ return isFrameForAppUrl(frameSrc, appUrl);
158
+ }
159
+
160
+ /** Distinct foreign identity servers referenced by embedded apps. */
161
+ export function listDistinctAppBackends(config?: ShellUIConfig): ResolvedAppBackend[] {
162
+ const seen = new Set<string>();
163
+ const list: ResolvedAppBackend[] = [];
164
+ for (const item of embeddedItems(config)) {
165
+ if (!item.backend) continue;
166
+ const identity = resolveAppBackendConfig(item.backend, config);
167
+ if (!identity || !isDistinctFromShell(identity, config)) continue;
168
+ if (seen.has(identity.key)) continue;
169
+ seen.add(identity.key);
170
+ list.push(identity);
171
+ }
172
+ return list;
173
+ }