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:
@@ -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;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user