fix: restore desktop remote authentication
Fixes switching and unlocking password-protected remote instances Stores SSH forwarded host client tokens from saved UI passwords Avoids unnecessary auth churn when no runtime headers are configured
This commit is contained in:
@@ -12,6 +12,7 @@ import { OpenChamberLogo } from '@/components/ui/OpenChamberLogo';
|
||||
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 { desktopHostsGet, desktopHostsSet, getDesktopHostApiUrl, normalizeHostUrl } from '@/lib/desktopHosts';
|
||||
import {
|
||||
@@ -129,20 +130,30 @@ const shouldUseDesktopShellPasswordLogin = (): boolean => {
|
||||
return isDesktopShell() && !isLocalDesktopRuntime();
|
||||
};
|
||||
|
||||
const issueDesktopClientTokenViaShell = async (password: string, trustDevice: boolean): Promise<string> => {
|
||||
type DesktopPasswordLoginResult = {
|
||||
token: string;
|
||||
status?: number;
|
||||
};
|
||||
|
||||
const issueDesktopClientTokenViaShell = async (password: string, trustDevice: boolean): Promise<DesktopPasswordLoginResult | null> => {
|
||||
if (!isDesktopShell() || typeof window === 'undefined') {
|
||||
return '';
|
||||
return null;
|
||||
}
|
||||
const response = await invokeDesktop('desktop_remote_password_login', {
|
||||
url: getRuntimeApiBaseUrl(),
|
||||
password,
|
||||
trustDevice,
|
||||
requestHeaders: getRuntimeExtraHeadersSync(),
|
||||
}).catch(() => null);
|
||||
if (!response || typeof response !== 'object') {
|
||||
return '';
|
||||
return null;
|
||||
}
|
||||
const token = (response as { token?: unknown }).token;
|
||||
return typeof token === 'string' ? token.trim() : '';
|
||||
const status = (response as { status?: unknown }).status;
|
||||
return {
|
||||
token: typeof token === 'string' ? token.trim() : '',
|
||||
...(typeof status === 'number' ? { status } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
const persistDesktopClientToken = async (apiBaseUrl: string, clientToken: string): Promise<void> => {
|
||||
@@ -180,8 +191,13 @@ const persistDesktopClientToken = async (apiBaseUrl: string, clientToken: string
|
||||
const applyDesktopClientToken = async (clientToken: string): Promise<void> => {
|
||||
if (!clientToken) return;
|
||||
const apiBaseUrl = getRuntimeApiBaseUrl();
|
||||
const requestHeaders = getRuntimeExtraHeadersSync();
|
||||
await persistDesktopClientToken(apiBaseUrl, clientToken);
|
||||
switchRuntimeEndpoint({ apiBaseUrl, clientToken });
|
||||
switchRuntimeEndpoint({
|
||||
apiBaseUrl,
|
||||
clientToken,
|
||||
requestHeaders: Object.keys(requestHeaders).length > 0 ? requestHeaders : null,
|
||||
});
|
||||
};
|
||||
|
||||
const AuthShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
@@ -486,15 +502,43 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({ children }) =>
|
||||
setErrorMessage('');
|
||||
|
||||
try {
|
||||
if (shouldUseDesktopShellPasswordLogin()) {
|
||||
const shellLogin = await issueDesktopClientTokenViaShell(password, trustDevice);
|
||||
if (shellLogin?.token) {
|
||||
setPassword('');
|
||||
setIsTunnelLocked(false);
|
||||
await applyDesktopClientToken(shellLogin.token);
|
||||
setState('authenticated');
|
||||
return;
|
||||
}
|
||||
if (shellLogin?.status === 401) {
|
||||
setErrorMessage(t('sessionAuth.error.incorrectPassword'));
|
||||
setIsTunnelLocked(false);
|
||||
setState('locked');
|
||||
return;
|
||||
}
|
||||
if (shellLogin?.status === 429) {
|
||||
setRetryAfter(undefined);
|
||||
setIsTunnelLocked(false);
|
||||
setState('rate-limited');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const response = await submitPassword(password, trustDevice);
|
||||
if (response.ok) {
|
||||
const payload = await response.json().catch(() => null) as { clientToken?: unknown } | null;
|
||||
const shouldUseClientToken = shouldIssueDesktopClientToken();
|
||||
const clientToken = shouldUseClientToken
|
||||
? (typeof payload?.clientToken === 'string' && payload.clientToken.trim()
|
||||
let clientToken = '';
|
||||
if (shouldUseClientToken) {
|
||||
clientToken = typeof payload?.clientToken === 'string' && payload.clientToken.trim()
|
||||
? payload.clientToken.trim()
|
||||
: await issueDesktopClientTokenViaShell(password, trustDevice) || await issueDesktopClientToken())
|
||||
: '';
|
||||
: '';
|
||||
if (!clientToken) {
|
||||
const shellLogin = await issueDesktopClientTokenViaShell(password, trustDevice);
|
||||
clientToken = shellLogin?.token || await issueDesktopClientToken();
|
||||
}
|
||||
}
|
||||
setPassword('');
|
||||
setIsTunnelLocked(false);
|
||||
if (clientToken) {
|
||||
@@ -541,16 +585,28 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({ children }) =>
|
||||
setState('error');
|
||||
} catch (error) {
|
||||
console.warn('Failed to submit UI password:', error);
|
||||
const clientToken = shouldUseDesktopShellPasswordLogin()
|
||||
const shellLogin = shouldUseDesktopShellPasswordLogin()
|
||||
? await issueDesktopClientTokenViaShell(password, trustDevice)
|
||||
: '';
|
||||
if (clientToken) {
|
||||
: null;
|
||||
if (shellLogin?.token) {
|
||||
setPassword('');
|
||||
setIsTunnelLocked(false);
|
||||
await applyDesktopClientToken(clientToken);
|
||||
await applyDesktopClientToken(shellLogin.token);
|
||||
setState('authenticated');
|
||||
return;
|
||||
}
|
||||
if (shellLogin?.status === 401) {
|
||||
setErrorMessage(t('sessionAuth.error.incorrectPassword'));
|
||||
setIsTunnelLocked(false);
|
||||
setState('locked');
|
||||
return;
|
||||
}
|
||||
if (shellLogin?.status === 429) {
|
||||
setRetryAfter(undefined);
|
||||
setIsTunnelLocked(false);
|
||||
setState('rate-limited');
|
||||
return;
|
||||
}
|
||||
setErrorMessage(t('sessionAuth.error.networkRetry'));
|
||||
setIsTunnelLocked(false);
|
||||
setState('error');
|
||||
|
||||
@@ -115,4 +115,34 @@ describe('runtime auth headers', () => {
|
||||
clearRuntimeAuthCredentialProvider();
|
||||
}
|
||||
});
|
||||
|
||||
test('does not remint URL auth token when setting equivalent empty runtime headers', async () => {
|
||||
const previousFetch = globalThis.fetch;
|
||||
let fetchCount = 0;
|
||||
try {
|
||||
clearRuntimeUrlAuthToken();
|
||||
setRuntimeBearerToken('runtime-token');
|
||||
setRuntimeExtraHeaders(null);
|
||||
globalThis.fetch = (async () => {
|
||||
fetchCount += 1;
|
||||
return new Response(JSON.stringify({ token: `url-token-${fetchCount}`, expiresAt: Date.now() + 60_000 }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
const firstToken = await refreshRuntimeUrlAuthToken('https://runtime.example');
|
||||
setRuntimeExtraHeaders({});
|
||||
const secondToken = await refreshRuntimeUrlAuthToken('https://runtime.example');
|
||||
|
||||
expect(firstToken).toBe('url-token-1');
|
||||
expect(secondToken).toBe('url-token-1');
|
||||
expect(fetchCount).toBe(1);
|
||||
} finally {
|
||||
globalThis.fetch = previousFetch;
|
||||
clearRuntimeUrlAuthToken();
|
||||
setRuntimeExtraHeaders(null);
|
||||
clearRuntimeAuthCredentialProvider();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,6 +29,12 @@ const sanitizeRuntimeExtraHeaders = (headers: Record<string, string> | null | un
|
||||
return next;
|
||||
};
|
||||
|
||||
const runtimeExtraHeadersEqual = (left: Record<string, string>, right: Record<string, string>): boolean => {
|
||||
const leftEntries = Object.entries(left);
|
||||
if (leftEntries.length !== Object.keys(right).length) return false;
|
||||
return leftEntries.every(([key, value]) => right[key] === value);
|
||||
};
|
||||
|
||||
const normalizeBearerToken = (token: string | null | undefined): string => {
|
||||
if (typeof token !== 'string') return '';
|
||||
return token.trim();
|
||||
@@ -95,7 +101,9 @@ export const setRuntimeBearerToken = (token: string | null | undefined): void =>
|
||||
export const setRuntimeExtraHeaders = (headers: Record<string, string> | null | undefined): void => {
|
||||
// These headers are for runtime HTTP fetches and URL-token minting. Browser-owned
|
||||
// realtime transports (EventSource/WebSocket) cannot attach arbitrary headers.
|
||||
runtimeExtraHeaders = sanitizeRuntimeExtraHeaders(headers);
|
||||
const next = sanitizeRuntimeExtraHeaders(headers);
|
||||
if (runtimeExtraHeadersEqual(runtimeExtraHeaders, next)) return;
|
||||
runtimeExtraHeaders = next;
|
||||
resetRuntimeAuthGeneration();
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { getRuntimeApiBaseUrl, switchRuntimeEndpoint } from './runtime-switch';
|
||||
import { clearRuntimeUrlAuthToken, setRuntimeExtraHeaders } from './runtime-auth';
|
||||
|
||||
describe('runtime endpoint switching', () => {
|
||||
test('does not throw when Electron preload globals are read-only', () => {
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
const previousFetch = globalThis.fetch;
|
||||
const runtimeWindow = {
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
dispatchEvent: () => true,
|
||||
};
|
||||
|
||||
try {
|
||||
clearRuntimeUrlAuthToken();
|
||||
setRuntimeExtraHeaders(null);
|
||||
globalThis.fetch = (async () => new Response(JSON.stringify({ token: 'url-token', expiresAt: Date.now() + 60_000 }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})) as typeof fetch;
|
||||
Object.defineProperty(runtimeWindow, '__OPENCHAMBER_API_BASE_URL__', {
|
||||
configurable: true,
|
||||
value: 'http://127.0.0.1:3000',
|
||||
writable: false,
|
||||
});
|
||||
Object.defineProperty(runtimeWindow, '__OPENCHAMBER_CLIENT_TOKEN__', {
|
||||
configurable: true,
|
||||
value: '',
|
||||
writable: false,
|
||||
});
|
||||
Object.defineProperty(runtimeWindow, '__OPENCHAMBER_RUNTIME_HEADERS__', {
|
||||
configurable: true,
|
||||
value: {},
|
||||
writable: false,
|
||||
});
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
configurable: true,
|
||||
value: runtimeWindow,
|
||||
});
|
||||
|
||||
let thrown: unknown = null;
|
||||
try {
|
||||
switchRuntimeEndpoint({
|
||||
apiBaseUrl: 'https://remote.example',
|
||||
clientToken: 'client-token',
|
||||
requestHeaders: null,
|
||||
});
|
||||
} catch (error) {
|
||||
thrown = error;
|
||||
}
|
||||
expect(thrown).toBeNull();
|
||||
expect(getRuntimeApiBaseUrl()).toBe('https://remote.example');
|
||||
} finally {
|
||||
globalThis.fetch = previousFetch;
|
||||
clearRuntimeUrlAuthToken();
|
||||
setRuntimeExtraHeaders(null);
|
||||
if (previousWindow) {
|
||||
Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
} else {
|
||||
Reflect.deleteProperty(globalThis, 'window');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,23 @@ const RUNTIME_ENDPOINT_CHANGED_EVENT = 'openchamber:runtime-endpoint-changed';
|
||||
let activeApiBaseUrl = '';
|
||||
let activeRuntimeKey = '';
|
||||
|
||||
const setWindowRuntimeValue = <K extends '__OPENCHAMBER_API_BASE_URL__' | '__OPENCHAMBER_CLIENT_TOKEN__' | '__OPENCHAMBER_RUNTIME_HEADERS__'>(
|
||||
runtimeWindow: typeof window & {
|
||||
__OPENCHAMBER_API_BASE_URL__?: string;
|
||||
__OPENCHAMBER_CLIENT_TOKEN__?: string;
|
||||
__OPENCHAMBER_RUNTIME_HEADERS__?: Record<string, string>;
|
||||
},
|
||||
key: K,
|
||||
value: (typeof runtimeWindow)[K],
|
||||
): void => {
|
||||
try {
|
||||
runtimeWindow[key] = value;
|
||||
} catch {
|
||||
// Electron preload exposes some initial globals through contextBridge, which
|
||||
// makes them read-only. Runtime switching must still update in-memory state.
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeRuntimeUrlKey = (value: string): string => {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
@@ -81,9 +98,9 @@ export const switchRuntimeEndpoint = (options: { apiBaseUrl: string; clientToken
|
||||
__OPENCHAMBER_CLIENT_TOKEN__?: string;
|
||||
__OPENCHAMBER_RUNTIME_HEADERS__?: Record<string, string>;
|
||||
};
|
||||
runtimeWindow.__OPENCHAMBER_API_BASE_URL__ = apiBaseUrl;
|
||||
runtimeWindow.__OPENCHAMBER_CLIENT_TOKEN__ = options.clientToken || undefined;
|
||||
runtimeWindow.__OPENCHAMBER_RUNTIME_HEADERS__ = options.requestHeaders || undefined;
|
||||
setWindowRuntimeValue(runtimeWindow, '__OPENCHAMBER_API_BASE_URL__', apiBaseUrl);
|
||||
setWindowRuntimeValue(runtimeWindow, '__OPENCHAMBER_CLIENT_TOKEN__', options.clientToken || undefined);
|
||||
setWindowRuntimeValue(runtimeWindow, '__OPENCHAMBER_RUNTIME_HEADERS__', options.requestHeaders || undefined);
|
||||
}
|
||||
configureRuntimeUrlResolver({ apiBaseUrl, realtimeBaseUrl: apiBaseUrl });
|
||||
setRuntimeExtraHeaders(options.requestHeaders || null);
|
||||
|
||||
Reference in New Issue
Block a user