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'> => {
@@ -434,8 +434,9 @@ export function DesktopHostSwitcherDialog({
const localClientToken = await getLocalClientToken();
const results = await Promise.all(
hosts.map(async (h) => {
const clientToken = h.id === LOCAL_HOST_ID ? localClientToken : (h.clientToken || '');
const probeRelayLeg = async (): Promise<HostStatus> => {
const res = await probeRelayDesktopHost(h.relay!).catch((): HostProbeResult => ({ status: 'unreachable', latencyMs: 0 }));
const res = await probeRelayDesktopHost(h.relay!, { clientToken, requestHeaders: h.requestHeaders || null }).catch((): HostProbeResult => ({ status: 'unreachable', latencyMs: 0 }));
return { status: res.status, latencyMs: res.latencyMs, ...(res.status === 'ok' ? { via: 'relay' as const } : {}) };
};
// Relay-only host: no HTTP address — probe through the E2EE tunnel.
@@ -446,7 +447,6 @@ export function DesktopHostSwitcherDialog({
if (!url) {
return [h.id, { status: 'unreachable' as const, latencyMs: 0 } satisfies HostStatus] as const;
}
const clientToken = h.id === LOCAL_HOST_ID ? localClientToken : (h.clientToken || '');
const res = await desktopHostProbe(url, { clientToken: clientToken || null, requestHeaders: h.requestHeaders || null }).catch((): HostProbeResult => ({ status: 'unreachable', latencyMs: 0 }));
// Multi-transport host away from its network: the direct leg fails
// but the relay may still reach it.
@@ -572,7 +572,7 @@ export function DesktopHostSwitcherDialog({
}
let relayProbeTunnel: ReturnType<typeof createRelayTunnelClient> | undefined;
if (!transport && host.relay) {
const probe = await probeRelayDesktopHost(host.relay, { keepTunnel: true })
const probe = await probeRelayDesktopHost(host.relay, { keepTunnel: true, clientToken: clientToken || null, requestHeaders: host.requestHeaders || null })
.catch((): HostProbeResult => ({ status: 'unreachable', latencyMs: 0 }));
if (probe.status === 'ok') {
finalStatus = { status: probe.status, latencyMs: probe.latencyMs, via: 'relay' };
@@ -27,14 +27,21 @@ import { setExternallyViewedSession, useDirectoryStore } from '@/sync/sync-conte
import { ContextPanelContent } from './ContextSidebarTab';
import { toast } from '@/components/ui';
import { runtimeFetch } from '@/lib/runtime-fetch';
import { refreshRuntimeUrlAuthToken } from '@/lib/runtime-auth';
import { getRuntimeBearerTokenSync, getRuntimeExtraHeadersSync, refreshRuntimeUrlAuthToken } from '@/lib/runtime-auth';
import { getRuntimeUrlResolver } from '@/lib/runtime-url';
import { getRuntimeApiBaseUrl } from '@/lib/runtime-switch';
import { getRuntimeApiBaseUrl, getRuntimeKey } from '@/lib/runtime-switch';
import { getActiveRelayDescriptor } from '@/lib/relay/runtime-tunnel';
import { getPreviewTargetRecoveryAction } from '@/lib/preview/proxy-response';
import { Icon } from "@/components/icon/Icon";
import { OpenChamberLogo } from "@/components/ui/OpenChamberLogo";
import { invokeDesktopCommand } from '@/lib/desktopNative';
import { getOrCreateEmbeddedSessionChatURL, type EmbeddedSessionChatURLCacheEntry } from './contextPanelEmbeddedChat';
import {
EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST,
EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE,
getOrCreateEmbeddedSessionChatURL,
type EmbeddedSessionChatURLCacheEntry,
type EmbeddedSessionRuntimeBootstrap,
} from './contextPanelEmbeddedChat';
import { getContextSurfaceWidthFraction } from '@/lib/surfaces/registry';
import {
type PreviewElementMetadata,
@@ -2538,19 +2545,6 @@ export const ContextPanel: React.FC = () => {
continue;
}
const directThemeSync = (frameWindow as unknown as {
__openchamberApplyThemeSync?: (themePayload: typeof payload) => void;
}).__openchamberApplyThemeSync;
if (typeof directThemeSync === 'function') {
try {
directThemeSync(payload);
continue;
} catch {
// fallback to postMessage below
}
}
frameWindow.postMessage(
{
type: 'openchamber:theme-sync',
@@ -2569,18 +2563,6 @@ export const ContextPanel: React.FC = () => {
const frameWindow = frame.contentWindow;
if (!frameWindow) continue;
const directSync = (frameWindow as unknown as {
__openchamberApplyChatSettingsSync?: (settings: typeof payload) => void;
}).__openchamberApplyChatSettingsSync;
if (typeof directSync === 'function') {
try {
directSync(payload);
continue;
} catch {
// fallback to postMessage below
}
}
frameWindow.postMessage({ type: 'openchamber:chat-settings-sync', payload }, window.location.origin);
}
}, [allowPromptingSubagentSessions]);
@@ -2597,19 +2579,6 @@ export const ContextPanel: React.FC = () => {
}
const payload = { visible: activeChatTabID === tabID };
const directVisibilitySync = (frameWindow as unknown as {
__openchamberSetEmbeddedVisibility?: (visibilityPayload: typeof payload) => void;
}).__openchamberSetEmbeddedVisibility;
if (typeof directVisibilitySync === 'function') {
try {
directVisibilitySync(payload);
continue;
} catch {
// fallback to postMessage below
}
}
frameWindow.postMessage(
{
type: 'openchamber:embedded-visibility',
@@ -2636,7 +2605,27 @@ export const ContextPanel: React.FC = () => {
return;
}
const data = event.data as { type?: unknown };
const data = event.data as { type?: unknown; requestId?: unknown };
if (data?.type === EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST) {
if (typeof data.requestId !== 'string' || !data.requestId) return;
const runtimeKey = getRuntimeKey();
const payload: EmbeddedSessionRuntimeBootstrap = {
apiBaseUrl: getRuntimeApiBaseUrl(),
clientToken: getRuntimeBearerTokenSync(),
localOrigin: typeof window.__OPENCHAMBER_LOCAL_ORIGIN__ === 'string'
? window.__OPENCHAMBER_LOCAL_ORIGIN__
: '',
runtimeHeaders: getRuntimeExtraHeadersSync(),
relayHostId: runtimeKey.startsWith('host:') ? runtimeKey.slice('host:'.length) : '',
relay: getActiveRelayDescriptor() ?? undefined,
};
(event.source as WindowProxy | null)?.postMessage({
type: EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE,
requestId: data.requestId,
payload,
}, event.origin);
return;
}
if (data?.type === 'openchamber:theme-sync-request') {
postThemeSyncToEmbeddedChat();
return;
@@ -3,9 +3,12 @@ import { getDefaultTheme } from '@/lib/theme/themes';
import type { Theme } from '@/types/theme';
import {
buildEmbeddedSessionChatURL,
EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST,
EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE,
getOrCreateEmbeddedSessionChatURL,
getEmbeddedSessionChatOriginSessionId,
isEmbeddedSessionChat,
requestEmbeddedSessionRuntimeBootstrap,
resetEmbeddedSessionChatCache,
type EmbeddedSessionChatURLCacheEntry,
} from './contextPanelEmbeddedChat';
@@ -207,3 +210,137 @@ describe('getEmbeddedSessionChatOriginSessionId', () => {
expect(getEmbeddedSessionChatOriginSessionId()).toBe('ses_child');
});
});
describe('embedded runtime bootstrap handshake', () => {
test('accepts only the matching response from the same-origin parent', async () => {
let messageListener: ((event: MessageEvent) => void) | null = null;
let requestCount = 0;
let retryCleared = false;
const parent = {
postMessage(message: { type?: string; requestId?: string }, targetOrigin: string) {
requestCount += 1;
expect(message.type).toBe(EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST);
queueMicrotask(() => {
messageListener?.({
origin: 'https://wrong.example.com',
source: parent,
data: {
type: EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE,
requestId: message.requestId,
payload: null,
},
} as unknown as MessageEvent);
if (requestCount === 1) return;
messageListener?.({
origin: targetOrigin,
source: parent,
data: {
type: EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE,
requestId: 'different-request',
payload: null,
},
} as unknown as MessageEvent);
messageListener?.({
origin: targetOrigin,
source: parent,
data: {
type: EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE,
requestId: message.requestId,
payload: {
apiBaseUrl: 'https://remote.example.com',
clientToken: 'client-token',
localOrigin: 'openchamber-ui://app',
runtimeHeaders: { 'x-runtime': 'value' },
relayHostId: 'host-1',
relay: {
relayUrl: 'wss://relay.example.com',
serverId: 'server-1',
hostEncPubJwk: { kty: 'EC', crv: 'P-256', x: 'public-x', y: 'public-y' },
},
},
},
} as unknown as MessageEvent);
});
},
};
const url = new URL('openchamber-ui://app/index.html?ocPanel=session-chat&sessionId=ses_1');
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: {
location: { origin: url.origin, search: url.search },
parent,
addEventListener: (type: string, listener: (event: MessageEvent) => void) => {
if (type === 'message') messageListener = listener;
},
removeEventListener: (type: string, listener: (event: MessageEvent) => void) => {
if (type === 'message' && messageListener === listener) messageListener = null;
},
setTimeout: globalThis.setTimeout.bind(globalThis),
clearTimeout: globalThis.clearTimeout.bind(globalThis),
setInterval: globalThis.setInterval.bind(globalThis),
clearInterval: (interval: ReturnType<typeof setInterval>) => {
retryCleared = true;
globalThis.clearInterval(interval);
},
},
});
resetEmbeddedSessionChatCache();
const result = await requestEmbeddedSessionRuntimeBootstrap();
expect(result).toEqual({
apiBaseUrl: 'https://remote.example.com',
clientToken: 'client-token',
localOrigin: 'openchamber-ui://app',
runtimeHeaders: { 'x-runtime': 'value' },
relayHostId: 'host-1',
relay: {
relayUrl: 'wss://relay.example.com',
serverId: 'server-1',
hostEncPubJwk: { kty: 'EC', crv: 'P-256', x: 'public-x', y: 'public-y' },
},
});
expect(requestCount).toBe(2);
expect(retryCleared).toBe(true);
expect(messageListener).toBeNull();
});
test('cleans up its listener and retry when the bootstrap times out', async () => {
let messageListener: ((event: MessageEvent) => void) | null = null;
let timeoutCallback: () => void = () => {
throw new Error('Timeout was not scheduled');
};
let timeoutCleared = false;
let retryCleared = false;
const parent = { postMessage() {} };
const url = new URL('openchamber-ui://app/index.html?ocPanel=session-chat&sessionId=ses_1');
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: {
location: { origin: url.origin, search: url.search },
parent,
addEventListener: (type: string, listener: (event: MessageEvent) => void) => {
if (type === 'message') messageListener = listener;
},
removeEventListener: (type: string, listener: (event: MessageEvent) => void) => {
if (type === 'message' && messageListener === listener) messageListener = null;
},
setTimeout: (callback: () => void) => {
timeoutCallback = callback;
return 1;
},
clearTimeout: () => { timeoutCleared = true; },
setInterval: () => 2,
clearInterval: () => { retryCleared = true; },
},
});
resetEmbeddedSessionChatCache();
const resultPromise = requestEmbeddedSessionRuntimeBootstrap();
timeoutCallback();
expect(await resultPromise).toBeNull();
expect(timeoutCleared).toBe(true);
expect(retryCleared).toBe(true);
expect(messageListener).toBeNull();
});
});
@@ -1,4 +1,5 @@
import type { Theme } from '@/types/theme';
import type { RelayRuntimeDescriptor } from '@/lib/relay/runtime-tunnel';
export type EmbeddedSessionChatThemeBootstrap = {
mode: 'light' | 'dark' | 'system';
@@ -12,6 +13,93 @@ export type EmbeddedSessionChatURLCacheEntry = {
src: string;
};
export type EmbeddedSessionRuntimeBootstrap = {
apiBaseUrl: string;
clientToken: string;
localOrigin: string;
runtimeHeaders?: Record<string, string>;
relayHostId: string;
relay?: Omit<RelayRuntimeDescriptor, 'grant'>;
};
export const EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST = 'openchamber:embedded-runtime-bootstrap-request';
export const EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE = 'openchamber:embedded-runtime-bootstrap-response';
const EMBEDDED_RUNTIME_BOOTSTRAP_TIMEOUT_MS = 5_000;
const EMBEDDED_RUNTIME_BOOTSTRAP_RETRY_MS = 100;
const isStringRecord = (value: unknown): value is Record<string, string> => (
value !== null
&& typeof value === 'object'
&& !Array.isArray(value)
&& Object.values(value).every((entry) => typeof entry === 'string')
);
const isRuntimeBootstrap = (value: unknown): value is EmbeddedSessionRuntimeBootstrap => {
if (!value || typeof value !== 'object') return false;
const candidate = value as Partial<EmbeddedSessionRuntimeBootstrap>;
if (
typeof candidate.apiBaseUrl !== 'string'
|| typeof candidate.clientToken !== 'string'
|| typeof candidate.localOrigin !== 'string'
|| typeof candidate.relayHostId !== 'string'
) {
return false;
}
if (candidate.runtimeHeaders !== undefined && !isStringRecord(candidate.runtimeHeaders)) {
return false;
}
const relay = candidate.relay;
if (relay === undefined) return true;
return relay !== null
&& typeof relay === 'object'
&& !('grant' in relay)
&& typeof relay.relayUrl === 'string'
&& typeof relay.serverId === 'string'
&& relay.hostEncPubJwk !== null
&& typeof relay.hostEncPubJwk === 'object'
&& !Array.isArray(relay.hostEncPubJwk);
};
export const requestEmbeddedSessionRuntimeBootstrap = (): Promise<EmbeddedSessionRuntimeBootstrap | null> => {
if (!isEmbeddedSessionChat() || typeof window === 'undefined' || window.parent === window) {
return Promise.resolve(null);
}
const requestId = typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
? crypto.randomUUID()
: `${Date.now()}-${Math.random()}`;
return new Promise((resolve) => {
let settled = false;
let retry = 0;
let timeout = 0;
const finish = (value: EmbeddedSessionRuntimeBootstrap | null) => {
if (settled) return;
settled = true;
window.clearTimeout(timeout);
window.clearInterval(retry);
window.removeEventListener('message', handleMessage);
resolve(value);
};
const handleMessage = (event: MessageEvent) => {
if (event.origin !== window.location.origin || event.source !== window.parent) return;
const data = event.data as { type?: unknown; requestId?: unknown; payload?: unknown };
if (data?.type !== EMBEDDED_RUNTIME_BOOTSTRAP_RESPONSE || data.requestId !== requestId) return;
finish(isRuntimeBootstrap(data.payload) ? data.payload : null);
};
timeout = window.setTimeout(() => finish(null), EMBEDDED_RUNTIME_BOOTSTRAP_TIMEOUT_MS);
const sendRequest = () => {
window.parent.postMessage({ type: EMBEDDED_RUNTIME_BOOTSTRAP_REQUEST, requestId }, window.location.origin);
};
retry = window.setInterval(sendRequest, EMBEDDED_RUNTIME_BOOTSTRAP_RETRY_MS);
window.addEventListener('message', handleMessage);
sendRequest();
});
};
const buildEmbeddedSessionChatURLSignature = (
sessionID: string,
directory: string | null,
@@ -125,4 +213,4 @@ export const getEmbeddedSessionChatOriginSessionId = (): string | null => {
} catch {
return null;
}
};
};
@@ -751,7 +751,7 @@ export const RemoteInstancesPage: React.FC = () => {
if (!showInstanceManagement || directHosts.length === 0) return;
let cancelled = false;
void Promise.all(directHosts.map(async (host) => {
const relayProbe = () => probeRelayDesktopHost(host.relay!).catch((): HostProbeResult => ({ status: 'unreachable', latencyMs: 0 }));
const relayProbe = () => probeRelayDesktopHost(host.relay!, { clientToken: host.clientToken || null, requestHeaders: host.requestHeaders || null }).catch((): HostProbeResult => ({ status: 'unreachable', latencyMs: 0 }));
// Relay-only host: tunnel probe. Multi-transport host: direct first,
// relay as the away-from-home fallback.
if (host.relay && !host.apiUrl) {
+34 -16
View File
@@ -409,19 +409,34 @@ export const desktopInstallIdGet = async (): Promise<string> => {
const RELAY_PROBE_TIMEOUT_MS = 8_000;
const fetchRelayProbe = async (
tunnel: ReturnType<typeof createRelayTunnelClient>,
path: string,
init?: RequestInit,
): Promise<Response> => {
const controller = new AbortController();
const timer = window.setTimeout(() => controller.abort(), RELAY_PROBE_TIMEOUT_MS);
try {
return await tunnel.fetch(path, { ...init, signal: controller.signal });
} finally {
window.clearTimeout(timer);
}
};
/**
* Reachability check for a relay host: open a throwaway E2EE tunnel and hit
* /health. Relay hosts have no HTTP address for `desktopHostProbe`. Hard
* timeout: a ghost relay registration (relay lost the host, host doesn't know)
* leaves the tunnel in `connecting` forever the probe must report
* unreachable instead of hanging every status/switch flow with it.
* Reachability and client-auth check for a relay host: open a throwaway E2EE
* tunnel, verify `/health`, then verify `/auth/session` with the saved bearer.
* Relay hosts have no HTTP address for `desktopHostProbe`. Hard timeout: a
* ghost relay registration (relay lost the host, host doesn't know) leaves the
* tunnel in `connecting` forever the probe must report unreachable instead
* of hanging every status/switch flow with it.
*/
export const probeRelayDesktopHost = async (
relay: DesktopHostRelay,
// With `keepTunnel`, an 'ok' probe RETURNS its live tunnel (the caller owns
// it — typically adopting it as the runtime tunnel, skipping a second
// WebSocket connect + E2EE handshake); every other outcome closes it.
options?: { keepTunnel?: boolean },
options?: { keepTunnel?: boolean; clientToken?: string | null; requestHeaders?: Record<string, string> | null },
): Promise<HostProbeResult & { tunnel?: ReturnType<typeof createRelayTunnelClient> }> => {
const tunnel = createRelayTunnelClient({
relayUrl: relay.relayUrl,
@@ -431,16 +446,19 @@ export const probeRelayDesktopHost = async (
const startedAt = Date.now();
let keep = false;
try {
const response = await Promise.race([
tunnel.fetch('/health'),
new Promise<null>((resolve) => {
const timer = window.setTimeout(() => resolve(null), RELAY_PROBE_TIMEOUT_MS);
if (typeof timer !== 'number' && typeof (timer as { unref?: () => void }).unref === 'function') {
(timer as unknown as { unref: () => void }).unref();
}
}),
]);
if (!response?.ok) return { status: 'unreachable', latencyMs: 0 };
const response = await fetchRelayProbe(tunnel, '/health');
if (!response.ok) return { status: 'unreachable', latencyMs: 0 };
const headers = new Headers({ Accept: 'application/json' });
for (const [name, value] of Object.entries(options?.requestHeaders || {})) {
if (name.toLowerCase() !== 'authorization') headers.set(name, value);
}
const clientToken = options?.clientToken?.trim();
if (clientToken) headers.set('Authorization', `Bearer ${clientToken}`);
const sessionResponse = await fetchRelayProbe(tunnel, '/auth/session', { headers });
if (sessionResponse.status === 401 || sessionResponse.status === 403) {
return { status: 'auth', latencyMs: Math.max(0, Date.now() - startedAt) };
}
if (!sessionResponse.ok) return { status: 'unreachable', latencyMs: 0 };
keep = options?.keepTunnel === true;
return { status: 'ok', latencyMs: Math.max(0, Date.now() - startedAt), ...(keep ? { tunnel } : {}) };
} catch {
@@ -22,6 +22,14 @@ const descriptorsEqual = (a: RelayRuntimeDescriptor, b: RelayRuntimeDescriptor):
JSON.stringify(a.hostEncPubJwk) === JSON.stringify(b.hostEncPubJwk);
export const getActiveRelayTunnel = (): RelayTunnelClient | null => activeTunnel;
export const getActiveRelayDescriptor = (): Omit<RelayRuntimeDescriptor, 'grant'> | null => {
if (!activeTunnel || !activeDescriptor) return null;
return {
relayUrl: activeDescriptor.relayUrl,
serverId: activeDescriptor.serverId,
hostEncPubJwk: { ...activeDescriptor.hostEncPubJwk },
};
};
export const isRelayModeActive = (): boolean => activeTunnel !== null;
@@ -7,8 +7,36 @@ import {
switchRuntimeEndpoint,
} from './runtime-switch';
import { clearRuntimeUrlAuthToken, setRuntimeExtraHeaders } from './runtime-auth';
import {
activateRelayTunnel,
deactivateRelayTunnel,
getActiveRelayDescriptor,
} from './relay/runtime-tunnel';
describe('runtime endpoint switching', () => {
test('exposes a credential-free copy of the active relay descriptor', () => {
const descriptor = {
relayUrl: 'wss://relay.example.com',
serverId: 'server-1',
hostEncPubJwk: { kty: 'EC', crv: 'P-256', x: 'public-x', y: 'public-y' },
grant: 'one-time-secret',
};
try {
activateRelayTunnel(descriptor);
const exposed = getActiveRelayDescriptor();
expect(exposed).toEqual({
relayUrl: descriptor.relayUrl,
serverId: descriptor.serverId,
hostEncPubJwk: descriptor.hostEncPubJwk,
});
expect(exposed).not.toBe(descriptor);
expect(exposed?.hostEncPubJwk).not.toBe(descriptor.hostEncPubJwk);
} finally {
deactivateRelayTunnel();
}
});
test('notifies listeners before and after mutating the active endpoint', () => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
const previousFetch = globalThis.fetch;
@@ -140,6 +140,7 @@ describe("SessionMessageLoader", () => {
await loader.ensure(target, { force: true })
expect(loader.getSnapshot(target).status).toBe("error")
expect((loader.getSnapshot(target).error as Error & { status?: number }).status).toBe(400)
expect(store.getState().message[target.sessionID]?.[0]?.id).toBe("cached")
fail = false
@@ -149,6 +150,20 @@ describe("SessionMessageLoader", () => {
childStores.disposeAll()
})
test("propagates a zero response status on SDK errors", async () => {
const { childStores, loader } = createLoader(async () => ({
error: { message: "network rejected" },
response: { status: 0 },
}))
const target = { directory: "/repo", sessionID: "session-a" }
await loader.ensure(target, { force: true })
expect((loader.getSnapshot(target).error as Error & { status?: number }).status).toBe(0)
loader.dispose()
childStores.disposeAll()
})
test("prevents an evicted in-flight request from repopulating the store", async () => {
const pending = deferred<ReturnType<typeof response>>()
const { childStores, loader } = createLoader(async () => pending.promise)
@@ -98,7 +98,10 @@ const assertSdkSuccess = (result: {
}, operation: string): void => {
if (!result.error) return
const status = result.response?.status
throw new Error(`${operation} failed${status ? ` (${status})` : ""}: ${formatSdkError(result.error)}`)
const message = `${operation} failed${status ? ` (${status})` : ""}: ${formatSdkError(result.error)}`
const error = new Error(message) as Error & { status?: number }
if (status !== undefined) error.status = status
throw error
}
const sortParts = (parts: Part[]): Part[] => parts