feat: connection candidates refresh + relay identity hardening
Candidates refresh (server + mobile + desktop clients):
- GET /api/client-auth/connection/candidates returns the server's current
LAN URLs, relay candidate, and serverId for already-paired devices
- /health and /api/version expose serverId so clients can verify a learned
address belongs to the expected server before sending their bearer token
- mobile: refresh saved candidates over the live transport after every
connect/wake, hot-switch relay->LAN when a fresh address is reachable;
serverId gate on direct probes; token no longer sent to /health
- desktop: refresh stored host apiUrl after a relay connect and hot-switch
back to direct; electron probe verifies serverId before authenticated fetch
Fixes found while debugging a dead pairing:
- settings: strict reader that throws on corrupt/unreadable file instead of
returning {}; relay signing/encryption key generation is now gated on it,
so a swallowed read failure can no longer mint a new server identity and
orphan every paired device (loud log when a keypair IS generated)
- SessionAuthGate: bounded auto-retry for transient session-check failures
(initial request racing the relay tunnel's first WS attempt, startup 5xx)
This commit is contained in:
@@ -734,6 +734,12 @@ const probeConnectionCandidates = async (
|
||||
options?: { fast?: boolean },
|
||||
): Promise<ProbeResult> => {
|
||||
const requestOptions = options?.fast ? { totalTimeoutMs: MOBILE_FAST_PROBE_TIMEOUT_MS } : undefined;
|
||||
// Identity gate for direct probes: when the device knows its server's identity
|
||||
// (via its relay pairing), a direct candidate must report the SAME serverId in
|
||||
// /health before we send the bearer token to it — a re-assigned LAN address may
|
||||
// now belong to a different machine. Older servers omit serverId from /health;
|
||||
// the gate only rejects an explicit mismatch (matching today's behavior otherwise).
|
||||
const expectedServerId = relayCandidateOf({ candidates })?.serverId ?? null;
|
||||
for (const candidate of candidates) {
|
||||
if (candidate.kind === 'relay') {
|
||||
const outcome = await probeRelaySession(candidate.relay, token, undefined, options?.fast ? MOBILE_FAST_PROBE_TIMEOUT_MS : undefined);
|
||||
@@ -743,8 +749,18 @@ const probeConnectionCandidates = async (
|
||||
}
|
||||
const url = normalizeConnectionUrl(candidate.url) || candidate.url;
|
||||
const headers = token ? { Authorization: `Bearer ${token}` } : undefined;
|
||||
const health = await requestWithTimeout(`${url}/health`, { method: 'GET', headers }, requestOptions);
|
||||
// /health is unauthenticated by design — never send the bearer token to an
|
||||
// address whose identity has not been checked yet.
|
||||
const health = await requestWithTimeout(`${url}/health`, { method: 'GET' }, requestOptions);
|
||||
if (!health?.ok) continue;
|
||||
if (expectedServerId) {
|
||||
const payload = await health.json().catch(() => null);
|
||||
const reported = payload && typeof payload === 'object' ? (payload as Record<string, unknown>).serverId : null;
|
||||
if (typeof reported === 'string' && reported && reported !== expectedServerId) {
|
||||
logConnect('probe:server-id-mismatch', { url });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const session = await requestWithTimeout(`${url}/auth/session`, { method: 'GET', credentials: 'include', headers }, requestOptions);
|
||||
if (session?.status === 401) return { status: 'needs-login' };
|
||||
if (!session || (!session.ok && session.status !== 404)) continue;
|
||||
@@ -774,6 +790,10 @@ const switchToTransport = (
|
||||
} else {
|
||||
switchRuntimeEndpoint({ apiBaseUrl: transport.url, clientToken: token, runtimeKey: options?.runtimeKey });
|
||||
}
|
||||
// Every live connection is an opportunity to learn the server's CURRENT LAN
|
||||
// addresses (pairing-payload candidates go stale when DHCP reassigns the
|
||||
// host's IP). Background-only: never blocks or repaints the connect flow.
|
||||
scheduleCandidateRefresh();
|
||||
};
|
||||
|
||||
// Cold-launch auto-connect: silently reconnect to the most-recently-used saved
|
||||
@@ -864,6 +884,9 @@ const pairingCandidatesToMobile = (candidates: PairingEndpointCandidate[]): Mobi
|
||||
const establishLiveTransport = async (
|
||||
candidates: MobileTransportCandidate[],
|
||||
): Promise<LiveTransport | null> => {
|
||||
// Same identity gate as probeConnectionCandidates: a redeem/login must not send
|
||||
// its secret to a direct address that reports a different server identity.
|
||||
const expectedServerId = relayCandidateOf({ candidates })?.serverId ?? null;
|
||||
for (const candidate of candidates) {
|
||||
if (candidate.kind === 'relay') {
|
||||
const tunnel = createRelayTunnelClient(candidate.relay);
|
||||
@@ -876,7 +899,16 @@ const establishLiveTransport = async (
|
||||
const url = normalizeConnectionUrl(candidate.url) || candidate.url;
|
||||
const health = await requestWithTimeout(`${url}/health`, { method: 'GET' });
|
||||
logConnect('establish:direct:health', { ok: health?.ok === true, status: health?.status ?? null });
|
||||
if (health?.ok) return { kind: 'direct', url };
|
||||
if (!health?.ok) continue;
|
||||
if (expectedServerId) {
|
||||
const payload = await health.json().catch(() => null);
|
||||
const reported = payload && typeof payload === 'object' ? (payload as Record<string, unknown>).serverId : null;
|
||||
if (typeof reported === 'string' && reported && reported !== expectedServerId) {
|
||||
logConnect('establish:server-id-mismatch', { url });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return { kind: 'direct', url };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -963,7 +995,14 @@ export const reprobeActiveConnection = async (): Promise<ReprobeOutcome> => {
|
||||
// 2. No better transport — is the current one still alive on its live channel?
|
||||
if (currentIndex >= 0) {
|
||||
const stillValid = await validateActiveRuntimeSession({ url: getRuntimeApiBaseUrl(), clientToken: token }, { fast: true });
|
||||
if (stillValid) return 'unchanged';
|
||||
if (stillValid) {
|
||||
// Still on the same transport (typically: woke up on the relay, old LAN
|
||||
// candidate dead). Ask the server for its current LAN addresses in the
|
||||
// background — if it moved, the refreshed candidates trigger one more
|
||||
// re-probe and the hot-switch back to direct.
|
||||
scheduleCandidateRefresh();
|
||||
return 'unchanged';
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Current transport is dead — fall through to lower-priority candidates.
|
||||
@@ -977,6 +1016,99 @@ export const reprobeActiveConnection = async (): Promise<ReprobeOutcome> => {
|
||||
return 'unreachable';
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Candidate refresh: learn the server's CURRENT direct addresses over the live
|
||||
// (authenticated) runtime transport and update the saved candidate set, so a
|
||||
// device that paired under an old DHCP lease is not stuck on the relay forever.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Let the post-switch bootstrap traffic settle before adding our own request.
|
||||
const CANDIDATE_REFRESH_DELAY_MS = 5_000;
|
||||
|
||||
type CandidateRefreshResult = 'updated' | 'unchanged' | 'skipped';
|
||||
|
||||
let candidateRefreshInFlight = false;
|
||||
|
||||
// Fetch /api/client-auth/connection/candidates through the ACTIVE runtime
|
||||
// transport (direct or relay — runtimeFetch routes it) and merge the reported
|
||||
// LAN addresses into the active saved connection:
|
||||
// - fresh `lan` candidates REPLACE the previous http:// (LAN-class) direct
|
||||
// candidates — a LAN address the server no longer holds is dead weight that
|
||||
// slows every future re-probe;
|
||||
// - https:// (tunnel-class) direct candidates are preserved — the server does
|
||||
// not know its own public tunnel hostnames;
|
||||
// - the relay candidate is preserved as the last-resort transport.
|
||||
// Only runs for relay-paired connections: their token/runtime key derives from
|
||||
// the stable relay identity, so rewriting direct URLs cannot orphan the stored
|
||||
// token. The response must echo the connection's serverId or it is ignored.
|
||||
export const refreshActiveConnectionCandidates = async (): Promise<CandidateRefreshResult> => {
|
||||
if (candidateRefreshInFlight) return 'skipped';
|
||||
const active = findActiveConnection();
|
||||
if (!active) return 'skipped';
|
||||
const relay = relayCandidateOf(active);
|
||||
if (!relay) return 'skipped';
|
||||
candidateRefreshInFlight = true;
|
||||
try {
|
||||
const response = await raceWithTimeout(
|
||||
RELAY_CONNECT_TIMEOUT_MS,
|
||||
runtimeFetch('/api/client-auth/connection/candidates').then((r): Response | null => r).catch(() => null),
|
||||
);
|
||||
if (!response?.ok) return 'skipped';
|
||||
const payload = await response.json().catch(() => null) as { serverId?: unknown; candidates?: unknown } | null;
|
||||
// Identity gate: the refresh must come from the server this device paired
|
||||
// with. Old servers (no serverId) are skipped rather than trusted blindly.
|
||||
if (!payload || payload.serverId !== relay.serverId) return 'skipped';
|
||||
const reported = Array.isArray(payload.candidates) ? payload.candidates : [];
|
||||
const lanUrls: string[] = [];
|
||||
for (const entry of reported) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
if (record.type !== 'lan' || typeof record.url !== 'string') continue;
|
||||
try {
|
||||
const url = normalizeConnectionUrl(record.url);
|
||||
if (url && !lanUrls.includes(url)) lanUrls.push(url);
|
||||
} catch {
|
||||
// invalid URL → drop
|
||||
}
|
||||
}
|
||||
// No LAN reported (loopback-only bind or interface-scan failure): keep the
|
||||
// existing candidates — deleting them on a possibly-transient empty answer
|
||||
// would be silent data loss; a stale entry only costs one fast probe.
|
||||
if (lanUrls.length === 0) return 'skipped';
|
||||
const preservedHttps = directCandidates(active).filter((candidate) => candidate.url.startsWith('https://'));
|
||||
const next: MobileTransportCandidate[] = [
|
||||
...lanUrls.map((url): MobileTransportCandidate => ({ kind: 'direct', url })),
|
||||
...preservedHttps,
|
||||
{ kind: 'relay', relay },
|
||||
];
|
||||
const unchanged = JSON.stringify(active.candidates.map(serializeCandidate)) === JSON.stringify(next.map(serializeCandidate));
|
||||
if (unchanged) return 'unchanged';
|
||||
logConnect('candidates:refreshed', { lanCount: lanUrls.length });
|
||||
await upsertMobileConnection({ id: active.id, label: active.label, candidates: next });
|
||||
return 'updated';
|
||||
} finally {
|
||||
candidateRefreshInFlight = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Background candidate refresh + opportunistic hot-switch. Fire-and-forget by
|
||||
// design: no UI state, no rerenders — the only visible effect is the runtime
|
||||
// quietly switching relay → direct when a fresh LAN address turns out reachable
|
||||
// (reprobeActiveConnection re-reads storage and applies its usual identity-gated
|
||||
// probe + stable-runtime-key switch). Converges: a re-entered refresh reports
|
||||
// 'unchanged'/'skipped', which never triggers another re-probe.
|
||||
const scheduleCandidateRefresh = (): void => {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.setTimeout(() => {
|
||||
void (async () => {
|
||||
const result = await refreshActiveConnectionCandidates().catch((): CandidateRefreshResult => 'skipped');
|
||||
if (result === 'updated' && isRelayModeActive()) {
|
||||
await reprobeActiveConnection().catch(() => null);
|
||||
}
|
||||
})();
|
||||
}, CANDIDATE_REFRESH_DELAY_MS);
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared connection controller
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -27,6 +27,16 @@ import {
|
||||
} from '@/lib/passkeys';
|
||||
|
||||
const STATUS_CHECK_ENDPOINT = '/auth/session';
|
||||
// Transient-failure auto-retry for the initial session check. Over the relay the
|
||||
// very first /auth/session can race the tunnel's initial WebSocket attempt (a
|
||||
// failed attempt rejects requests queued on the channel even though the tunnel
|
||||
// immediately reconnects), and on a lossy link the first request can simply drop.
|
||||
// A single-shot check pins the gate on the error screen for a self-healing
|
||||
// condition, so network errors and non-auth server errors (5xx during startup)
|
||||
// retry a bounded number of times before surfacing the error UI. Definitive auth
|
||||
// answers (200/401/429) are never retried.
|
||||
const TRANSIENT_RETRY_MAX_ATTEMPTS = 4;
|
||||
const TRANSIENT_RETRY_BASE_DELAY_MS = 1_500;
|
||||
const TRUST_DEVICE_STORAGE_KEY = 'openchamber.uiAuth.trustDevice';
|
||||
const LOCAL_DESKTOP_CLIENT_KIND = 'desktop-local';
|
||||
const LOCAL_DESKTOP_CLIENT_DEDUPE_KEY = 'desktop-local';
|
||||
@@ -373,6 +383,40 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
|
||||
};
|
||||
}, [skipAuth]);
|
||||
|
||||
// Bounded retry scheduling for transient session-check failures. Lives in refs
|
||||
// so retries survive re-renders; the timer is cleared on unmount, endpoint
|
||||
// switch, and any definitive server answer.
|
||||
const transientRetryAttemptRef = React.useRef(0);
|
||||
const transientRetryTimerRef = React.useRef<number | null>(null);
|
||||
const checkStatusRef = React.useRef<(() => Promise<void>) | null>(null);
|
||||
|
||||
const clearTransientRetry = React.useCallback(() => {
|
||||
if (transientRetryTimerRef.current !== null) {
|
||||
window.clearTimeout(transientRetryTimerRef.current);
|
||||
transientRetryTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const resetTransientRetry = React.useCallback(() => {
|
||||
transientRetryAttemptRef.current = 0;
|
||||
clearTransientRetry();
|
||||
}, [clearTransientRetry]);
|
||||
|
||||
// Returns true when another attempt was scheduled (caller keeps the pending
|
||||
// UI); false when the retry budget is exhausted (caller shows the error UI).
|
||||
const scheduleTransientRetry = React.useCallback((): boolean => {
|
||||
if (transientRetryAttemptRef.current >= TRANSIENT_RETRY_MAX_ATTEMPTS) return false;
|
||||
transientRetryAttemptRef.current += 1;
|
||||
clearTransientRetry();
|
||||
transientRetryTimerRef.current = window.setTimeout(() => {
|
||||
transientRetryTimerRef.current = null;
|
||||
void checkStatusRef.current?.();
|
||||
}, TRANSIENT_RETRY_BASE_DELAY_MS * transientRetryAttemptRef.current);
|
||||
return true;
|
||||
}, [clearTransientRetry]);
|
||||
|
||||
React.useEffect(() => clearTransientRetry, [clearTransientRetry]);
|
||||
|
||||
const checkStatus = React.useCallback(async () => {
|
||||
if (skipAuth) {
|
||||
setState('authenticated');
|
||||
@@ -386,8 +430,9 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
|
||||
refreshPasskeyStatus(),
|
||||
]);
|
||||
const responseText = await response.text();
|
||||
|
||||
|
||||
if (response.ok) {
|
||||
resetTransientRetry();
|
||||
setState('authenticated');
|
||||
setIsTunnelLocked(false);
|
||||
setErrorMessage('');
|
||||
@@ -401,6 +446,7 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
|
||||
} catch {
|
||||
data = {};
|
||||
}
|
||||
resetTransientRetry();
|
||||
setIsTunnelLocked(data.tunnelLocked === true);
|
||||
setPasskeyStatus(latestPasskeyStatus);
|
||||
setState('locked');
|
||||
@@ -414,11 +460,15 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
|
||||
} catch {
|
||||
data = {};
|
||||
}
|
||||
resetTransientRetry();
|
||||
setRetryAfter(data.retryAfter);
|
||||
setIsTunnelLocked(false);
|
||||
setState('rate-limited');
|
||||
return;
|
||||
}
|
||||
// Non-auth server error (e.g. 502/503 while the backend is still coming
|
||||
// up) — transient; keep the pending UI and retry before surfacing.
|
||||
if (scheduleTransientRetry()) return;
|
||||
setState('error');
|
||||
setIsTunnelLocked(false);
|
||||
} catch (error) {
|
||||
@@ -429,10 +479,17 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
|
||||
setIsTunnelLocked(false);
|
||||
return;
|
||||
}
|
||||
// Network-level failure — over the relay this is typically the initial
|
||||
// tunnel attempt racing this request; it self-heals within seconds.
|
||||
if (scheduleTransientRetry()) return;
|
||||
setState('error');
|
||||
setIsTunnelLocked(false);
|
||||
}
|
||||
}, [refreshPasskeyStatus, skipAuth]);
|
||||
}, [refreshPasskeyStatus, resetTransientRetry, scheduleTransientRetry, skipAuth]);
|
||||
|
||||
React.useEffect(() => {
|
||||
checkStatusRef.current = checkStatus;
|
||||
}, [checkStatus]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (skipAuth) {
|
||||
@@ -451,10 +508,11 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
|
||||
setErrorMessage('');
|
||||
setRetryAfter(undefined);
|
||||
setIsTunnelLocked(false);
|
||||
resetTransientRetry();
|
||||
setState('pending');
|
||||
void checkStatus();
|
||||
});
|
||||
}, [checkStatus, skipAuth]);
|
||||
}, [checkStatus, resetTransientRetry, skipAuth]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!skipAuth && state === 'locked') {
|
||||
@@ -719,7 +777,7 @@ export const SessionAuthGate: React.FC<SessionAuthGateProps> = ({
|
||||
|
||||
if (state === 'error') {
|
||||
return (
|
||||
<ErrorScreen onRetry={() => void checkStatus()} errorType="network">
|
||||
<ErrorScreen onRetry={() => { resetTransientRetry(); void checkStatus(); }} errorType="network">
|
||||
{showHostSwitcher && (
|
||||
<div className="w-full max-w-xs">
|
||||
<DesktopHostSwitcherInline />
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
type DesktopHost,
|
||||
type HostProbeResult,
|
||||
} from '@/lib/desktopHosts';
|
||||
import { scheduleDesktopHostCandidateRefresh } from '@/lib/desktopRelayRestore';
|
||||
import { getRuntimeApiBaseUrl, getRuntimeKey, subscribeRuntimeEndpointChanged, switchRuntimeEndpoint } from '@/lib/runtime-switch';
|
||||
import {
|
||||
desktopSshConnect,
|
||||
@@ -519,6 +520,9 @@ export function DesktopHostSwitcherDialog({
|
||||
runtimeKey: runtimeKeyForHost(host),
|
||||
relay,
|
||||
});
|
||||
// On the relay: learn the server's current LAN address in the background
|
||||
// and hot-switch back to direct if the stored one merely went stale.
|
||||
scheduleDesktopHostCandidateRefresh(host.id);
|
||||
};
|
||||
|
||||
const origin = host.id === LOCAL_HOST_ID ? localOrigin : (normalizeHostUrl(host.url) || '');
|
||||
|
||||
@@ -325,13 +325,16 @@ export const probeRelayDesktopHost = async (relay: DesktopHostRelay): Promise<Ho
|
||||
}
|
||||
};
|
||||
|
||||
export const desktopHostProbe = async (url: string, options?: { clientToken?: string | null; requestHeaders?: Record<string, string> | null }): Promise<HostProbeResult> => {
|
||||
export const desktopHostProbe = async (url: string, options?: { clientToken?: string | null; requestHeaders?: Record<string, string> | null; expectedServerId?: string | null }): Promise<HostProbeResult> => {
|
||||
const invoke = getInvoke();
|
||||
if (!invoke) {
|
||||
return { status: 'unreachable', latencyMs: 0 };
|
||||
}
|
||||
|
||||
const raw = await invoke('desktop_host_probe', { url, clientToken: options?.clientToken || undefined, requestHeaders: options?.requestHeaders || undefined });
|
||||
// `expectedServerId` makes the main-process probe verify the address's
|
||||
// UNAUTHENTICATED /health identity before sending the bearer token — required
|
||||
// when probing an address learned at runtime rather than typed by the user.
|
||||
const raw = await invoke('desktop_host_probe', { url, clientToken: options?.clientToken || undefined, requestHeaders: options?.requestHeaders || undefined, expectedServerId: options?.expectedServerId || undefined });
|
||||
if (!isRecord(raw)) {
|
||||
return { status: 'unreachable', latencyMs: 0 };
|
||||
}
|
||||
|
||||
@@ -1,7 +1,99 @@
|
||||
import { isElectronShell } from '@/lib/desktop';
|
||||
import { desktopHostProbe, desktopHostsGet, getDesktopHostApiUrl, normalizeHostUrl } from '@/lib/desktopHosts';
|
||||
import { desktopHostProbe, desktopHostsGet, desktopHostsSet, getDesktopHostApiUrl, normalizeHostUrl } from '@/lib/desktopHosts';
|
||||
import { runtimeFetch } from '@/lib/runtime-fetch';
|
||||
import { getRuntimeKey, switchRuntimeEndpoint } from '@/lib/runtime-switch';
|
||||
|
||||
// Let the post-switch bootstrap traffic settle before the background refresh.
|
||||
const CANDIDATE_REFRESH_DELAY_MS = 5_000;
|
||||
|
||||
let candidateRefreshInFlight = false;
|
||||
|
||||
/**
|
||||
* Background candidate refresh for a relay-connected desktop host: ask the
|
||||
* server (over the live authenticated transport) for its CURRENT LAN addresses,
|
||||
* update the stored host's direct `apiUrl` if it moved (pairing-time addresses
|
||||
* go stale when DHCP reassigns the host machine's IP), then probe the fresh
|
||||
* address — identity-gated by the host's pinned relay serverId — and hot-switch
|
||||
* relay → direct when it is reachable. The runtime key stays `host:<id>`, so the
|
||||
* swap is a transport change, not an instance switch.
|
||||
*
|
||||
* This rewrites only the direct address of an ALREADY-TRUSTED host, learned from
|
||||
* that host itself over the E2EE tunnel pinned to its key — the token and trust
|
||||
* boundary are unchanged, so no user confirmation is required. An https apiUrl
|
||||
* (stable tunnel hostname) is never overwritten: the DHCP problem does not apply
|
||||
* to it and the server does not know its own public hostnames.
|
||||
*/
|
||||
export const refreshDesktopHostCandidates = async (hostId: string): Promise<void> => {
|
||||
if (!isElectronShell() || candidateRefreshInFlight) return;
|
||||
const runtimeKey = `host:${hostId}`;
|
||||
// The candidates fetch rides the active runtime's transport — only meaningful
|
||||
// while this host IS the active runtime.
|
||||
if (getRuntimeKey() !== runtimeKey) return;
|
||||
candidateRefreshInFlight = true;
|
||||
try {
|
||||
const config = await desktopHostsGet().catch(() => null);
|
||||
const host = config?.hosts.find((entry) => entry.id === hostId);
|
||||
if (!config || !host?.relay) return;
|
||||
const currentApiUrl = host.apiUrl ? normalizeHostUrl(host.apiUrl) : null;
|
||||
if (currentApiUrl && currentApiUrl.startsWith('https://')) return;
|
||||
|
||||
const response = await runtimeFetch('/api/client-auth/connection/candidates').catch(() => null);
|
||||
if (!response?.ok) return;
|
||||
const payload = await response.json().catch(() => null) as { serverId?: unknown; candidates?: unknown } | null;
|
||||
// Identity gate: the refresh must come from the server this host entry is
|
||||
// pinned to; anything else (including old servers without serverId) is ignored.
|
||||
if (!payload || payload.serverId !== host.relay.serverId) return;
|
||||
const reported = Array.isArray(payload.candidates) ? payload.candidates : [];
|
||||
const lanUrls: string[] = [];
|
||||
for (const entry of reported) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
if (record.type !== 'lan' || typeof record.url !== 'string') continue;
|
||||
const url = normalizeHostUrl(record.url);
|
||||
if (url && !lanUrls.includes(url)) lanUrls.push(url);
|
||||
}
|
||||
// Empty answer (loopback-only bind / scan failure) must not erase a stored
|
||||
// address — a stale one only costs a fast failed probe on the next start.
|
||||
if (lanUrls.length === 0) return;
|
||||
|
||||
const nextApiUrl = currentApiUrl && lanUrls.includes(currentApiUrl) ? currentApiUrl : lanUrls[0];
|
||||
if (nextApiUrl !== currentApiUrl) {
|
||||
await desktopHostsSet({
|
||||
hosts: config.hosts.map((entry) => (entry.id === hostId ? { ...entry, apiUrl: nextApiUrl } : entry)),
|
||||
defaultHostId: config.defaultHostId,
|
||||
initialHostChoiceCompleted: config.initialHostChoiceCompleted,
|
||||
}).catch(() => undefined);
|
||||
}
|
||||
|
||||
// We are on the relay for this host (the refresh call itself proves the
|
||||
// tunnel works) — if the fresh direct address answers AND proves the same
|
||||
// server identity, hot-switch to it.
|
||||
const probe = await desktopHostProbe(nextApiUrl, {
|
||||
clientToken: host.clientToken || null,
|
||||
requestHeaders: host.requestHeaders || null,
|
||||
expectedServerId: host.relay.serverId,
|
||||
}).catch(() => ({ status: 'unreachable' as const, latencyMs: 0 }));
|
||||
if (probe.status === 'unreachable' || probe.status === 'wrong-service' || probe.status === 'incompatible') return;
|
||||
if (getRuntimeKey() !== runtimeKey) return; // user switched away meanwhile
|
||||
switchRuntimeEndpoint({
|
||||
apiBaseUrl: nextApiUrl,
|
||||
clientToken: host.clientToken || null,
|
||||
requestHeaders: host.requestHeaders || null,
|
||||
runtimeKey,
|
||||
});
|
||||
} finally {
|
||||
candidateRefreshInFlight = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** Fire-and-forget wrapper: schedule the refresh after a relay switch settles. */
|
||||
export const scheduleDesktopHostCandidateRefresh = (hostId: string): void => {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.setTimeout(() => {
|
||||
void refreshDesktopHostCandidates(hostId).catch(() => undefined);
|
||||
}, CANDIDATE_REFRESH_DELAY_MS);
|
||||
};
|
||||
|
||||
/**
|
||||
* On desktop startup, reconnect a relay-capable default host. The Electron
|
||||
* shell boots the LOCAL UI for any host that carries a relay leg and defers
|
||||
@@ -48,4 +140,8 @@ export const restoreDesktopRelayRuntime = async (targetHostId?: string): Promise
|
||||
runtimeKey,
|
||||
relay: host.relay,
|
||||
});
|
||||
// Landed on the relay because the stored direct address failed — ask the
|
||||
// server for its current LAN address in the background and hot-switch back
|
||||
// to direct if it simply moved (DHCP re-lease).
|
||||
scheduleDesktopHostCandidateRefresh(host.id);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user