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:
+22
-14
@@ -4,6 +4,10 @@ import { registerSW } from 'virtual:pwa-register';
|
||||
import type { RuntimeAPIs } from '@openchamber/ui/lib/api/types';
|
||||
import { getStoredMobileLayoutPreference } from '@openchamber/ui/lib/mobileLayoutPreference';
|
||||
import type { HostedSurface } from '@openchamber/ui/lib/runtimeSurface';
|
||||
import {
|
||||
isEmbeddedSessionChat,
|
||||
requestEmbeddedSessionRuntimeBootstrap,
|
||||
} from '@openchamber/ui/components/layout/contextPanelEmbeddedChat';
|
||||
import '@openchamber/ui/index.css';
|
||||
import '@openchamber/ui/styles/fonts';
|
||||
|
||||
@@ -14,8 +18,6 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
window.__OPENCHAMBER_RUNTIME_APIS__ = createConfiguredWebAPIs();
|
||||
|
||||
const isCoarsePointer = (): boolean => {
|
||||
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
|
||||
return false;
|
||||
@@ -104,18 +106,24 @@ const unregisterDevelopmentServiceWorkers = (): void => {
|
||||
});
|
||||
};
|
||||
|
||||
if (hostedSurface === 'mobile') {
|
||||
void import('@openchamber/ui/apps/renderMobileApp')
|
||||
.then(({ renderMobileApp }) => {
|
||||
renderMobileApp(window.__OPENCHAMBER_RUNTIME_APIS__ ?? createConfiguredWebAPIs());
|
||||
});
|
||||
} else {
|
||||
// Hold the render (HTML splash stays up) until a desktop relay-host restore
|
||||
// has picked its transport — otherwise the app boots against a not-yet-chosen
|
||||
// endpoint and flashes the auth screen before the tunnel connects. Resolves
|
||||
// immediately when no relay host is involved.
|
||||
void getDesktopRelayRestoreReady().then(() => import('@openchamber/ui/main'));
|
||||
}
|
||||
const start = async (): Promise<void> => {
|
||||
const embeddedBootstrap = isEmbeddedSessionChat()
|
||||
? await requestEmbeddedSessionRuntimeBootstrap()
|
||||
: null;
|
||||
window.__OPENCHAMBER_RUNTIME_APIS__ = createConfiguredWebAPIs(embeddedBootstrap);
|
||||
|
||||
if (hostedSurface === 'mobile') {
|
||||
const { renderMobileApp } = await import('@openchamber/ui/apps/renderMobileApp');
|
||||
renderMobileApp(window.__OPENCHAMBER_RUNTIME_APIS__);
|
||||
return;
|
||||
}
|
||||
|
||||
// Hold the render until a desktop relay-host restore has picked its transport.
|
||||
await getDesktopRelayRestoreReady();
|
||||
await import('@openchamber/ui/main');
|
||||
};
|
||||
|
||||
void start();
|
||||
|
||||
if (import.meta.env.PROD) {
|
||||
registerPwaServiceWorker();
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterAll, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
vi.mock('@openchamber/ui/lib/runtime-auth', () => ({
|
||||
getRuntimeBearerTokenSync: vi.fn(() => ''),
|
||||
getRuntimeExtraHeadersSync: vi.fn(() => ({})),
|
||||
refreshLocalRuntimeUrlAuthToken: vi.fn(() => Promise.resolve()),
|
||||
refreshRuntimeUrlAuthToken: vi.fn(() => Promise.resolve()),
|
||||
setRuntimeBearerToken: vi.fn(),
|
||||
setRuntimeExtraHeaders: vi.fn(),
|
||||
}));
|
||||
vi.mock('@openchamber/ui/lib/runtime-fetch', () => ({ installRuntimeFetchBridge: vi.fn() }));
|
||||
vi.mock('@openchamber/ui/lib/runtime-switch', () => ({
|
||||
getRuntimeApiBaseUrl: vi.fn(() => ''),
|
||||
getRuntimeKey: vi.fn(() => 'local'),
|
||||
initializeRuntimeEndpoint: vi.fn(),
|
||||
switchRuntimeEndpoint: vi.fn(),
|
||||
}));
|
||||
vi.mock('@openchamber/ui/lib/desktopRelayRestore', () => ({ restoreDesktopRelayRuntime: vi.fn(() => Promise.resolve()) }));
|
||||
vi.mock('@openchamber/ui/lib/runtime-url', () => ({ configureRuntimeUrlResolver: vi.fn(() => ({})) }));
|
||||
vi.mock('@openchamber/ui/lib/opencode/client', () => ({ opencodeClient: { reconnectToRuntimeBaseUrl: vi.fn() } }));
|
||||
vi.mock('./api', () => ({ createWebAPIs: vi.fn() }));
|
||||
|
||||
import { setRuntimeBearerToken, setRuntimeExtraHeaders } from '@openchamber/ui/lib/runtime-auth';
|
||||
import { initializeRuntimeEndpoint, switchRuntimeEndpoint } from '@openchamber/ui/lib/runtime-switch';
|
||||
import { restoreDesktopRelayRuntime } from '@openchamber/ui/lib/desktopRelayRestore';
|
||||
import { opencodeClient } from '@openchamber/ui/lib/opencode/client';
|
||||
import { createConfiguredWebAPIs, readRuntimeBootstrapConfig } from './runtimeConfig';
|
||||
|
||||
const originalWindow = globalThis.window;
|
||||
|
||||
const installWindow = (value: Record<string, unknown>) => {
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value,
|
||||
});
|
||||
};
|
||||
|
||||
const makeWindow = (search = ''): Record<string, unknown> => {
|
||||
const value: Record<string, unknown> = {
|
||||
location: { origin: 'openchamber-ui://app', search },
|
||||
setTimeout: vi.fn(() => 1),
|
||||
};
|
||||
value.parent = value;
|
||||
return value;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
installWindow(makeWindow());
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: originalWindow,
|
||||
});
|
||||
});
|
||||
|
||||
describe('readRuntimeBootstrapConfig', () => {
|
||||
test('reads the runtime injected into the current window', () => {
|
||||
const current = makeWindow();
|
||||
current.__OPENCHAMBER_API_BASE_URL__ = ' https://remote.example.com ';
|
||||
current.__OPENCHAMBER_CLIENT_TOKEN__ = ' remote-token ';
|
||||
current.__OPENCHAMBER_LOCAL_ORIGIN__ = ' http://127.0.0.1:3000 ';
|
||||
current.__OPENCHAMBER_RUNTIME_HEADERS__ = { 'x-openchamber-relay': 'relay-value' };
|
||||
current.__OPENCHAMBER_RELAY_HOST_ID__ = ' remote-host ';
|
||||
installWindow(current);
|
||||
|
||||
expect(readRuntimeBootstrapConfig()).toEqual({
|
||||
apiBaseUrl: 'https://remote.example.com',
|
||||
clientToken: 'remote-token',
|
||||
localOrigin: 'http://127.0.0.1:3000',
|
||||
runtimeHeaders: { 'x-openchamber-relay': 'relay-value' },
|
||||
relayHostId: 'remote-host',
|
||||
});
|
||||
});
|
||||
|
||||
test('does not read runtime credentials directly from a parent window', () => {
|
||||
const parent = makeWindow();
|
||||
parent.__OPENCHAMBER_API_BASE_URL__ = 'https://remote.example.com';
|
||||
parent.__OPENCHAMBER_CLIENT_TOKEN__ = 'remote-token';
|
||||
const child = makeWindow('?ocPanel=session-chat&sessionId=ses_child');
|
||||
child.parent = parent;
|
||||
installWindow(child);
|
||||
|
||||
expect(readRuntimeBootstrapConfig()).toEqual({
|
||||
apiBaseUrl: '',
|
||||
clientToken: '',
|
||||
localOrigin: '',
|
||||
runtimeHeaders: undefined,
|
||||
relayHostId: '',
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('createConfiguredWebAPIs', () => {
|
||||
test('applies an embedded handshake before restoring its relay host', () => {
|
||||
const bootstrap = {
|
||||
apiBaseUrl: 'https://remote.example.com',
|
||||
clientToken: 'client-token',
|
||||
localOrigin: 'openchamber-ui://app',
|
||||
runtimeHeaders: { 'x-runtime': 'value' },
|
||||
relayHostId: 'host-1',
|
||||
};
|
||||
|
||||
createConfiguredWebAPIs(bootstrap);
|
||||
|
||||
expect(initializeRuntimeEndpoint).toHaveBeenCalledWith({
|
||||
apiBaseUrl: bootstrap.apiBaseUrl,
|
||||
runtimeKey: null,
|
||||
});
|
||||
expect(setRuntimeBearerToken).toHaveBeenCalledWith(bootstrap.clientToken);
|
||||
expect(setRuntimeExtraHeaders).toHaveBeenCalledWith(bootstrap.runtimeHeaders);
|
||||
expect(restoreDesktopRelayRuntime).toHaveBeenCalledWith(bootstrap.relayHostId);
|
||||
expect(opencodeClient.reconnectToRuntimeBaseUrl).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('activates an embedded relay without relying on Electron preload IPC', () => {
|
||||
const relay = {
|
||||
relayUrl: 'wss://relay.example.com',
|
||||
serverId: 'server-1',
|
||||
hostEncPubJwk: { kty: 'EC', crv: 'P-256', x: 'public-x', y: 'public-y' },
|
||||
};
|
||||
const bootstrap = {
|
||||
apiBaseUrl: 'openchamber-ui://app',
|
||||
clientToken: 'client-token',
|
||||
localOrigin: 'http://127.0.0.1:3000',
|
||||
relayHostId: 'host-1',
|
||||
relay,
|
||||
};
|
||||
|
||||
createConfiguredWebAPIs(bootstrap);
|
||||
|
||||
expect(switchRuntimeEndpoint).toHaveBeenCalledWith({
|
||||
apiBaseUrl: bootstrap.apiBaseUrl,
|
||||
clientToken: bootstrap.clientToken,
|
||||
requestHeaders: null,
|
||||
runtimeKey: 'host:host-1',
|
||||
relay,
|
||||
});
|
||||
expect(restoreDesktopRelayRuntime).not.toHaveBeenCalled();
|
||||
expect(opencodeClient.reconnectToRuntimeBaseUrl).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { getRuntimeExtraHeadersSync, refreshLocalRuntimeUrlAuthToken, refreshRuntimeUrlAuthToken, setRuntimeBearerToken, setRuntimeExtraHeaders } from '@openchamber/ui/lib/runtime-auth';
|
||||
import { installRuntimeFetchBridge } from '@openchamber/ui/lib/runtime-fetch';
|
||||
import { initializeRuntimeEndpoint } from '@openchamber/ui/lib/runtime-switch';
|
||||
import { initializeRuntimeEndpoint, switchRuntimeEndpoint } from '@openchamber/ui/lib/runtime-switch';
|
||||
import { restoreDesktopRelayRuntime } from '@openchamber/ui/lib/desktopRelayRestore';
|
||||
import { configureRuntimeUrlResolver } from '@openchamber/ui/lib/runtime-url';
|
||||
import type { EmbeddedSessionRuntimeBootstrap } from '@openchamber/ui/components/layout/contextPanelEmbeddedChat';
|
||||
import { opencodeClient } from '@openchamber/ui/lib/opencode/client';
|
||||
import { createWebAPIs } from './api';
|
||||
|
||||
const sameOrigin = (left: string, right: string): boolean => {
|
||||
@@ -20,24 +22,29 @@ declare global {
|
||||
__OPENCHAMBER_CLIENT_TOKEN__?: string;
|
||||
__OPENCHAMBER_RUNTIME_HEADERS__?: Record<string, string>;
|
||||
__OPENCHAMBER_LOCAL_ORIGIN__?: string;
|
||||
__OPENCHAMBER_RELAY_HOST_ID__?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export const readRuntimeBootstrapConfig = (): EmbeddedSessionRuntimeBootstrap => {
|
||||
const readString = (value: unknown): string => typeof value === 'string' ? value.trim() : '';
|
||||
|
||||
return {
|
||||
apiBaseUrl: readString(window.__OPENCHAMBER_API_BASE_URL__),
|
||||
clientToken: readString(window.__OPENCHAMBER_CLIENT_TOKEN__),
|
||||
localOrigin: readString(window.__OPENCHAMBER_LOCAL_ORIGIN__),
|
||||
runtimeHeaders: window.__OPENCHAMBER_RUNTIME_HEADERS__,
|
||||
relayHostId: readString(window.__OPENCHAMBER_RELAY_HOST_ID__),
|
||||
};
|
||||
};
|
||||
|
||||
// Resolved once the desktop relay-host restore (if any) has picked a transport.
|
||||
// Immediately-resolved everywhere else. See createConfiguredWebAPIs.
|
||||
let desktopRelayRestoreReady: Promise<void> = Promise.resolve();
|
||||
export const getDesktopRelayRestoreReady = (): Promise<void> => desktopRelayRestoreReady;
|
||||
|
||||
export const createConfiguredWebAPIs = () => {
|
||||
const apiBaseUrl = typeof window.__OPENCHAMBER_API_BASE_URL__ === 'string'
|
||||
? window.__OPENCHAMBER_API_BASE_URL__.trim()
|
||||
: '';
|
||||
const clientToken = typeof window.__OPENCHAMBER_CLIENT_TOKEN__ === 'string'
|
||||
? window.__OPENCHAMBER_CLIENT_TOKEN__.trim()
|
||||
: '';
|
||||
const localOrigin = typeof window.__OPENCHAMBER_LOCAL_ORIGIN__ === 'string'
|
||||
? window.__OPENCHAMBER_LOCAL_ORIGIN__.trim()
|
||||
: '';
|
||||
export const createConfiguredWebAPIs = (bootstrap?: EmbeddedSessionRuntimeBootstrap | null) => {
|
||||
const { apiBaseUrl, clientToken, localOrigin, runtimeHeaders, relayHostId, relay } = bootstrap ?? readRuntimeBootstrapConfig();
|
||||
|
||||
const urls = configureRuntimeUrlResolver({
|
||||
apiBaseUrl: apiBaseUrl || undefined,
|
||||
@@ -48,7 +55,19 @@ export const createConfiguredWebAPIs = () => {
|
||||
runtimeKey: sameOrigin(apiBaseUrl, localOrigin) ? 'local' : null,
|
||||
});
|
||||
setRuntimeBearerToken(clientToken || null);
|
||||
setRuntimeExtraHeaders(window.__OPENCHAMBER_RUNTIME_HEADERS__ || null);
|
||||
setRuntimeExtraHeaders(runtimeHeaders || null);
|
||||
if (relay) {
|
||||
switchRuntimeEndpoint({
|
||||
apiBaseUrl,
|
||||
clientToken: clientToken || null,
|
||||
requestHeaders: runtimeHeaders || null,
|
||||
runtimeKey: relayHostId ? `host:${relayHostId}` : null,
|
||||
relay,
|
||||
});
|
||||
}
|
||||
// createWebAPIs imports UI stores, which instantiate the SDK singleton before
|
||||
// an embedded frame's asynchronous parent bootstrap is available.
|
||||
opencodeClient.reconnectToRuntimeBaseUrl();
|
||||
void refreshRuntimeUrlAuthToken(apiBaseUrl || undefined).catch(() => {});
|
||||
if (localOrigin && !sameOrigin(apiBaseUrl, localOrigin) && Object.keys(getRuntimeExtraHeadersSync()).length > 0) {
|
||||
void refreshLocalRuntimeUrlAuthToken(localOrigin).catch(() => {});
|
||||
@@ -60,11 +79,16 @@ export const createConfiguredWebAPIs = () => {
|
||||
// relay host is involved. main.tsx holds the app render on this promise so
|
||||
// the user sees the splash instead of a transient auth screen against an
|
||||
// endpoint that is still being selected.
|
||||
const relayHostId = (window as typeof window & { __OPENCHAMBER_RELAY_HOST_ID__?: string }).__OPENCHAMBER_RELAY_HOST_ID__;
|
||||
desktopRelayRestoreReady = Promise.race([
|
||||
restoreDesktopRelayRuntime(typeof relayHostId === 'string' && relayHostId ? relayHostId : undefined).catch(() => {}),
|
||||
// Never hold the app hostage: a stuck probe/tunnel gives up to the UI.
|
||||
new Promise<void>((resolve) => { window.setTimeout(resolve, 10_000); }),
|
||||
]);
|
||||
desktopRelayRestoreReady = relay
|
||||
? Promise.resolve()
|
||||
: Promise.race([
|
||||
restoreDesktopRelayRuntime(relayHostId || undefined).catch(() => {}),
|
||||
// Never hold the app hostage: a stuck probe/tunnel gives up to the UI.
|
||||
new Promise<void>((resolve) => { window.setTimeout(resolve, 10_000); }),
|
||||
]).then(() => {
|
||||
// Relay-capable windows may select a reachable direct leg before React
|
||||
// subscribes to runtime-change events, so bind the SDK explicitly.
|
||||
opencodeClient.reconnectToRuntimeBaseUrl();
|
||||
});
|
||||
return createWebAPIs({ urls });
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user