fix(desktop): isolate remote runtime auth and embeds

Fix remote Desktop runtime bootstrapping across context-panel session chats, additional windows, and host switches.\n\n- Bootstrap embedded session-chat frames through a same-origin parent handshake that supplies the active endpoint, bearer token, runtime headers, local origin, and a credential-free relay descriptor.\n- Keep relay pairing grants out of iframe state and explicitly rebind the SDK after embedded bootstrap or relay restoration.\n- Preserve each additional and Mini Chat window's own init script instead of overwriting it when the main window's host configuration changes.\n- Replace direct iframe global calls with same-origin postMessage synchronization for theme, chat settings, and visibility.\n\nHarden Desktop host authentication and probing.\n\n- Bind password, passkey, session-status, and token-persistence completions to the runtime identity that started them, so a late result cannot alter a newly selected host.\n- Cancel active passkey operations and reset transient auth UI state on endpoint changes.\n- Verify stored client authentication via /auth/session for direct and relay host probes, distinguishing reachable hosts from hosts that require re-authentication.\n- Bound every relay probe request with an aborting timeout so a stalled auth request cannot hang refresh or host switching.\n\nAdd regression coverage for the embedded bootstrap handshake, credential-free relay descriptor exposure, runtime configuration, stale password completion after an A-to-B switch, and SDK errors that carry a zero response status.\n\nAlso preserve SDK response status on session-message loader errors so callers can distinguish transport and server failures.
This commit is contained in:
Bohdan Triapitsyn
2026-07-30 17:43:39 +03:00
parent 4ae3debf54
commit 3b00c91893
19 changed files with 819 additions and 159 deletions
@@ -1,4 +1,4 @@
import { describe, expect, mock, test } from 'bun:test';
import { afterEach, describe, expect, mock, test } from 'bun:test';
type ComponentFn<P extends Record<string, unknown> = Record<string, unknown>> = (props: P) => unknown;
@@ -16,12 +16,43 @@ const hookRecords = new Map<unknown, HookRecord>();
let currentRecord: HookRecord | null = null;
let hookIndex = 0;
let pendingEffects: Array<() => void> = [];
const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
afterEach(() => {
if (originalWindow) {
Object.defineProperty(globalThis, 'window', originalWindow);
} else {
Reflect.deleteProperty(globalThis, 'window');
}
});
const resetHarness = () => {
hookRecords.clear();
currentRecord = null;
hookIndex = 0;
pendingEffects = [];
runtimeApiBaseUrl = '';
runtimeKey = 'local';
runtimeEndpointChangedListener = null;
desktopInvoke = async () => null;
desktopHostsGetCalls = 0;
desktopHostsSetCalls = 0;
runtimeSwitchCalls = 0;
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: {
isSecureContext: false,
localStorage: {
getItem: () => null,
setItem: () => undefined,
},
setTimeout: (callback: () => void) => {
queueMicrotask(callback);
return 0;
},
clearTimeout: () => undefined,
},
});
};
const shallowEqualDeps = (left?: unknown[], right?: unknown[]): boolean => {
@@ -149,6 +180,13 @@ const reactJsxRuntime = {
let desktopShell = false;
let runtimeFetchRejects = true;
let runtimeApiBaseUrl = '';
let runtimeKey = 'local';
let runtimeEndpointChangedListener: (() => void) | null = null;
let desktopInvoke: () => Promise<unknown> = async () => null;
let desktopHostsGetCalls = 0;
let desktopHostsSetCalls = 0;
let runtimeSwitchCalls = 0;
mock.module('react/jsx-runtime', () => reactJsxRuntime);
mock.module('react/jsx-dev-runtime', () => reactJsxRuntime);
@@ -172,7 +210,7 @@ mock.module('@/components/ui/checkbox', () => ({
}));
mock.module('@/components/ui/input', () => ({
Input: () => null,
Input: (props: JSXProps) => ({ type: 'input', props }),
}));
mock.module('@/components/ui', () => ({
@@ -200,7 +238,7 @@ mock.module('@/lib/i18n', () => ({
}));
mock.module('@/lib/desktop', () => ({
invokeDesktop: mock(() => Promise.resolve(null)),
invokeDesktop: () => desktopInvoke(),
isDesktopShell: mock(() => desktopShell),
isVSCodeRuntime: mock(() => false),
}));
@@ -232,14 +270,26 @@ mock.module('@/lib/runtime-auth', () => ({
}));
mock.module('@/lib/runtime-switch', () => ({
getRuntimeApiBaseUrl: mock(() => ''),
subscribeRuntimeEndpointChanged: mock(() => () => {}),
switchRuntimeEndpoint: mock(() => undefined),
getRuntimeApiBaseUrl: () => runtimeApiBaseUrl,
getRuntimeKey: () => runtimeKey,
subscribeRuntimeEndpointChanged: (listener: () => void) => {
runtimeEndpointChangedListener = listener;
return () => {
if (runtimeEndpointChangedListener === listener) runtimeEndpointChangedListener = null;
};
},
switchRuntimeEndpoint: () => { runtimeSwitchCalls += 1; },
}));
mock.module('@/lib/desktopHosts', () => ({
desktopHostsGet: mock(() => Promise.resolve(null)),
desktopHostsSet: mock(() => Promise.resolve()),
desktopHostsGet: () => {
desktopHostsGetCalls += 1;
return Promise.resolve(null);
},
desktopHostsSet: () => {
desktopHostsSetCalls += 1;
return Promise.resolve();
},
getDesktopHostApiUrl: mock(() => ''),
normalizeHostUrl: mock(() => ''),
}));
@@ -288,6 +338,21 @@ const collectText = (node: unknown): string => {
return '';
};
const findElement = (node: unknown, type: string): { type: string; props: JSXProps } | null => {
if (!node || typeof node !== 'object') return null;
const element = node as { type?: unknown; props?: JSXProps };
if (element.type === type && element.props) return { type, props: element.props };
const children = element.props?.children;
if (Array.isArray(children)) {
for (const child of children) {
const match = findElement(child, type);
if (match) return match;
}
return null;
}
return findElement(children, type);
};
describe('SessionAuthGate status-check failure behavior', () => {
test('keeps non-desktop status-check rejection on the error screen', async () => {
resetHarness();
@@ -312,4 +377,37 @@ describe('SessionAuthGate status-check failure behavior', () => {
expect(text).toContain('sessionAuth.locked.unlockTitle');
expect(text).not.toContain('sessionAuth.error.networkTitle');
});
test('discards a password completion after switching to another host', async () => {
resetHarness();
desktopShell = true;
runtimeFetchRejects = false;
runtimeApiBaseUrl = 'https://host-a.example';
runtimeKey = 'host:a';
let resolveLogin: (value: unknown) => void = () => {
throw new Error('Password login did not start');
};
desktopInvoke = () => new Promise((resolve) => { resolveLogin = resolve; });
const lockedTree = await renderGate();
const input = findElement(lockedTree, 'input');
expect(input).not.toBeNull();
(input?.props.onChange as (event: { target: { value: string } }) => void)({ target: { value: 'password-a' } });
const passwordTree = await renderGate();
const form = findElement(passwordTree, 'form');
expect(form).not.toBeNull();
const pending = (form?.props.onSubmit as (event: { preventDefault: () => void }) => Promise<void>)({ preventDefault: () => undefined });
await Promise.resolve();
runtimeApiBaseUrl = 'https://host-b.example';
runtimeKey = 'host:b';
runtimeEndpointChangedListener?.();
resolveLogin({ token: 'token-a' });
await pending;
expect(desktopHostsGetCalls).toBe(0);
expect(desktopHostsSetCalls).toBe(0);
expect(runtimeSwitchCalls).toBe(0);
});
});
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test';
import { resolveStatusCheckFailureState } from './sessionAuthGateState';
import { resolveStatusCheckFailureState, runtimeIdentityMatches } from './sessionAuthGateState';
describe('resolveStatusCheckFailureState', () => {
test('keeps the desktop-shell password login fallback intact', () => {
@@ -10,4 +10,18 @@ describe('resolveStatusCheckFailureState', () => {
test('uses the network error screen for non-desktop status-check failures', () => {
expect(resolveStatusCheckFailureState({})).toBe('error');
});
test('rejects async auth results after switching hosts', () => {
expect(runtimeIdentityMatches(
{ apiBaseUrl: 'https://host-a.example', runtimeKey: 'host:a' },
{ apiBaseUrl: 'https://host-b.example', runtimeKey: 'host:b' },
)).toBe(false);
});
test('accepts a credential refresh for the same host', () => {
expect(runtimeIdentityMatches(
{ apiBaseUrl: 'https://host-a.example', runtimeKey: 'host:a' },
{ apiBaseUrl: 'https://host-a.example', runtimeKey: 'host:a' },
)).toBe(true);
});
});
@@ -13,9 +13,9 @@ import { Icon } from "@/components/icon/Icon";
import { useI18n } from '@/lib/i18n';
import { runtimeFetch } from '@/lib/runtime-fetch';
import { getRuntimeExtraHeadersSync } from '@/lib/runtime-auth';
import { getRuntimeApiBaseUrl, subscribeRuntimeEndpointChanged, switchRuntimeEndpoint } from '@/lib/runtime-switch';
import { getRuntimeApiBaseUrl, getRuntimeKey, subscribeRuntimeEndpointChanged, switchRuntimeEndpoint } from '@/lib/runtime-switch';
import { desktopHostsGet, desktopHostsSet, getDesktopHostApiUrl, normalizeHostUrl } from '@/lib/desktopHosts';
import { resolveStatusCheckFailureState, type GateState } from './sessionAuthGateState';
import { resolveStatusCheckFailureState, runtimeIdentityMatches, type GateState, type RuntimeIdentity } from './sessionAuthGateState';
import {
authenticateWithPasskey,
cancelPasskeyCeremony,
@@ -160,20 +160,34 @@ const shouldUseDesktopShellPasswordLogin = (): boolean => {
return isDesktopShell() && !isLocalDesktopRuntime();
};
const captureRuntimeIdentity = (): RuntimeIdentity => ({
apiBaseUrl: getRuntimeApiBaseUrl(),
runtimeKey: getRuntimeKey(),
});
const isRuntimeIdentityActive = (identity: RuntimeIdentity): boolean => {
return runtimeIdentityMatches(identity, captureRuntimeIdentity());
};
type DesktopPasswordLoginResult = {
token: string;
status?: number;
};
const issueDesktopClientTokenViaShell = async (password: string, trustDevice: boolean): Promise<DesktopPasswordLoginResult | null> => {
const issueDesktopClientTokenViaShell = async (
password: string,
trustDevice: boolean,
runtime: RuntimeIdentity,
requestHeaders: Record<string, string>,
): Promise<DesktopPasswordLoginResult | null> => {
if (!isDesktopShell() || typeof window === 'undefined') {
return null;
}
const response = await invokeDesktop('desktop_remote_password_login', {
url: getRuntimeApiBaseUrl(),
url: runtime.apiBaseUrl,
password,
trustDevice,
requestHeaders: getRuntimeExtraHeadersSync(),
requestHeaders,
}).catch(() => null);
if (!response || typeof response !== 'object') {
return null;
@@ -186,22 +200,22 @@ const issueDesktopClientTokenViaShell = async (password: string, trustDevice: bo
};
};
const persistDesktopClientToken = async (apiBaseUrl: string, clientToken: string): Promise<void> => {
if (!isDesktopShell() || !clientToken) return;
const persistDesktopClientToken = async (runtime: RuntimeIdentity, clientToken: string): Promise<boolean> => {
if (!isDesktopShell() || !clientToken || !isRuntimeIdentityActive(runtime)) return false;
const cfg = await desktopHostsGet().catch(() => null);
if (!cfg) return;
if (cfg.localOrigin && sameOrigin(cfg.localOrigin, apiBaseUrl)) {
if (!cfg || !isRuntimeIdentityActive(runtime)) return false;
if (cfg.localOrigin && sameOrigin(cfg.localOrigin, runtime.apiBaseUrl)) {
await desktopHostsSet({
hosts: cfg.hosts,
defaultHostId: cfg.defaultHostId,
initialHostChoiceCompleted: cfg.initialHostChoiceCompleted,
localClientToken: clientToken,
}).catch(() => undefined);
return;
return isRuntimeIdentityActive(runtime);
}
let changed = false;
const hosts = cfg.hosts.map((host) => {
if (!sameOrigin(getDesktopHostApiUrl(host), apiBaseUrl)) {
if (!sameOrigin(getDesktopHostApiUrl(host), runtime.apiBaseUrl)) {
return host;
}
if (host.clientToken === clientToken) {
@@ -210,24 +224,31 @@ const persistDesktopClientToken = async (apiBaseUrl: string, clientToken: string
changed = true;
return { ...host, clientToken };
});
if (!changed) return;
if (!changed) return true;
if (!isRuntimeIdentityActive(runtime)) return false;
await desktopHostsSet({
hosts,
defaultHostId: cfg.defaultHostId,
initialHostChoiceCompleted: cfg.initialHostChoiceCompleted,
}).catch(() => undefined);
return isRuntimeIdentityActive(runtime);
};
const applyDesktopClientToken = async (clientToken: string): Promise<void> => {
if (!clientToken) return;
const apiBaseUrl = getRuntimeApiBaseUrl();
const requestHeaders = getRuntimeExtraHeadersSync();
await persistDesktopClientToken(apiBaseUrl, clientToken);
const applyDesktopClientToken = async (
clientToken: string,
runtime: RuntimeIdentity,
requestHeaders: Record<string, string>,
): Promise<boolean> => {
if (!clientToken || !isRuntimeIdentityActive(runtime)) return false;
if (!await persistDesktopClientToken(runtime, clientToken)) return false;
if (!isRuntimeIdentityActive(runtime)) return false;
switchRuntimeEndpoint({
apiBaseUrl,
apiBaseUrl: runtime.apiBaseUrl,
clientToken,
requestHeaders: Object.keys(requestHeaders).length > 0 ? requestHeaders : null,
runtimeKey: runtime.runtimeKey,
});
return true;
};
const AuthShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
@@ -338,17 +359,21 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
window.localStorage.setItem(TRUST_DEVICE_STORAGE_KEY, trustDevice ? 'true' : 'false');
}, [trustDevice]);
const refreshPasskeyStatus = React.useCallback(async () => {
const refreshPasskeyStatus = React.useCallback(async (runtime = captureRuntimeIdentity()) => {
if (skipAuth) {
return defaultPasskeyStatus;
}
try {
const nextStatus = await fetchPasskeyStatus();
setPasskeyStatus(nextStatus);
if (isRuntimeIdentityActive(runtime)) {
setPasskeyStatus(nextStatus);
}
return nextStatus;
} catch {
setPasskeyStatus(defaultPasskeyStatus);
if (isRuntimeIdentityActive(runtime)) {
setPasskeyStatus(defaultPasskeyStatus);
}
return defaultPasskeyStatus;
}
}, [skipAuth]);
@@ -423,14 +448,19 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
return;
}
const runtime = captureRuntimeIdentity();
setState((prev) => (prev === 'authenticated' ? prev : 'pending'));
try {
const [response, latestPasskeyStatus] = await Promise.all([
fetchSessionStatus(),
refreshPasskeyStatus(),
refreshPasskeyStatus(runtime),
]);
const responseText = await response.text();
if (!isRuntimeIdentityActive(runtime)) {
return;
}
if (response.ok) {
resetTransientRetry();
setState('authenticated');
@@ -472,6 +502,9 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
setState('error');
setIsTunnelLocked(false);
} catch (error) {
if (!isRuntimeIdentityActive(runtime)) {
return;
}
console.warn('Failed to check session status:', error);
if (resolveStatusCheckFailureState({ shouldUseDesktopShellPasswordLogin: shouldUseDesktopShellPasswordLogin() }) === 'locked') {
setState('locked');
@@ -504,10 +537,14 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
}
return subscribeRuntimeEndpointChanged(() => {
cancelPasskeyCeremony();
setPassword('');
setErrorMessage('');
setRetryAfter(undefined);
setIsTunnelLocked(false);
setIsSubmitting(false);
setActivePasskeyAction(null);
setIsPasskeyBusy(false);
resetTransientRetry();
setState('pending');
void checkStatus();
@@ -547,15 +584,19 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
};
const registerPasskeyForCurrentSession = React.useCallback(async () => {
const runtime = captureRuntimeIdentity();
setActivePasskeyAction('register');
setIsPasskeyBusy(true);
try {
await registerCurrentDevicePasskey();
} finally {
setActivePasskeyAction(null);
setIsPasskeyBusy(false);
if (isRuntimeIdentityActive(runtime)) {
setActivePasskeyAction(null);
setIsPasskeyBusy(false);
}
}
await refreshPasskeyStatus();
if (!isRuntimeIdentityActive(runtime)) return;
await refreshPasskeyStatus(runtime);
}, [refreshPasskeyStatus]);
const cancelActivePasskey = React.useCallback(() => {
@@ -576,16 +617,19 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
cancelActivePasskey();
}
const runtime = captureRuntimeIdentity();
const requestHeaders = getRuntimeExtraHeadersSync();
setIsSubmitting(true);
setErrorMessage('');
try {
if (shouldUseDesktopShellPasswordLogin()) {
const shellLogin = await issueDesktopClientTokenViaShell(password, trustDevice);
const shellLogin = await issueDesktopClientTokenViaShell(password, trustDevice, runtime, requestHeaders);
if (!isRuntimeIdentityActive(runtime)) return;
if (shellLogin?.token) {
setPassword('');
setIsTunnelLocked(false);
await applyDesktopClientToken(shellLogin.token);
if (!await applyDesktopClientToken(shellLogin.token, runtime, requestHeaders)) return;
setState('authenticated');
return;
}
@@ -604,8 +648,10 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
}
const response = await submitPassword(password, trustDevice);
if (!isRuntimeIdentityActive(runtime)) return;
if (response.ok) {
const payload = await response.json().catch(() => null) as { clientToken?: unknown } | null;
if (!isRuntimeIdentityActive(runtime)) return;
const shouldUseClientToken = shouldIssueDesktopClientToken();
let clientToken = '';
if (shouldUseClientToken) {
@@ -613,18 +659,21 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
? payload.clientToken.trim()
: '';
if (!clientToken) {
const shellLogin = await issueDesktopClientTokenViaShell(password, trustDevice);
const shellLogin = await issueDesktopClientTokenViaShell(password, trustDevice, runtime, requestHeaders);
if (!isRuntimeIdentityActive(runtime)) return;
clientToken = shellLogin?.token || await issueDesktopClientToken();
if (!isRuntimeIdentityActive(runtime)) return;
}
}
setPassword('');
setIsTunnelLocked(false);
if (clientToken) {
await applyDesktopClientToken(clientToken);
if (!await applyDesktopClientToken(clientToken, runtime, requestHeaders)) return;
}
if (enrollPasskey && supportsPasskeys) {
try {
await registerPasskeyForCurrentSession();
if (!isRuntimeIdentityActive(runtime)) return;
toast.success(t('sessionAuth.toast.passkeyAdded'));
setState('authenticated');
return;
@@ -662,14 +711,16 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
setIsTunnelLocked(false);
setState('error');
} catch (error) {
if (!isRuntimeIdentityActive(runtime)) return;
console.warn('Failed to submit UI password:', error);
const shellLogin = shouldUseDesktopShellPasswordLogin()
? await issueDesktopClientTokenViaShell(password, trustDevice)
? await issueDesktopClientTokenViaShell(password, trustDevice, runtime, requestHeaders)
: null;
if (!isRuntimeIdentityActive(runtime)) return;
if (shellLogin?.token) {
setPassword('');
setIsTunnelLocked(false);
await applyDesktopClientToken(shellLogin.token);
if (!await applyDesktopClientToken(shellLogin.token, runtime, requestHeaders)) return;
setState('authenticated');
return;
}
@@ -689,7 +740,9 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
setIsTunnelLocked(false);
setState('error');
} finally {
setIsSubmitting(false);
if (isRuntimeIdentityActive(runtime)) {
setIsSubmitting(false);
}
}
}, [cancelActivePasskey, isPasskeyBusy, isSubmitting, isTunnelLocked, password, registerPasskeyForCurrentSession, supportsPasskeys, t, trustDevice]);
@@ -706,6 +759,8 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
setIsPasskeyBusy(true);
setActivePasskeyAction('auth');
setErrorMessage('');
const runtime = captureRuntimeIdentity();
const requestHeaders = getRuntimeExtraHeadersSync();
try {
const payload = await authenticateWithPasskey(trustDevice, {
@@ -716,13 +771,15 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
const clientToken = shouldIssueDesktopClientToken() && typeof payload?.clientToken === 'string' && payload.clientToken.trim()
? payload.clientToken.trim()
: '';
if (!isRuntimeIdentityActive(runtime)) return;
if (clientToken) {
await applyDesktopClientToken(clientToken);
if (!await applyDesktopClientToken(clientToken, runtime, requestHeaders)) return;
}
setPassword('');
setState('authenticated');
} catch (error) {
if (!isRuntimeIdentityActive(runtime)) return;
if (isPasskeyCeremonyAbort(error)) {
setErrorMessage('');
} else {
@@ -730,8 +787,10 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
setErrorMessage(message);
}
} finally {
setActivePasskeyAction(null);
setIsPasskeyBusy(false);
if (isRuntimeIdentityActive(runtime)) {
setActivePasskeyAction(null);
setIsPasskeyBusy(false);
}
}
}, [cancelActivePasskey, isPasskeyBusy, isSubmitting, supportsPasskeys, t, trustDevice]);
@@ -1,5 +1,14 @@
export type GateState = 'pending' | 'authenticated' | 'locked' | 'error' | 'rate-limited';
export type RuntimeIdentity = {
apiBaseUrl: string;
runtimeKey: string;
};
export const runtimeIdentityMatches = (left: RuntimeIdentity, right: RuntimeIdentity): boolean => {
return left.apiBaseUrl === right.apiBaseUrl && left.runtimeKey === right.runtimeKey;
};
export const resolveStatusCheckFailureState = (options: {
shouldUseDesktopShellPasswordLogin?: boolean;
}): Exclude<GateState, 'pending' | 'authenticated' | 'rate-limited'> => {