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:
@@ -862,13 +862,37 @@ const fetchVersionPayload = async (versionUrl, { headers, timeoutMs }) => {
|
||||
}
|
||||
};
|
||||
|
||||
const probeHostWithTimeout = async (url, timeoutMs, clientToken = '', requestHeaders = {}) => {
|
||||
const probeHostWithTimeout = async (url, timeoutMs, clientToken = '', requestHeaders = {}, expectedServerId = '') => {
|
||||
const versionUrl = buildVersionUrl(url);
|
||||
if (!versionUrl) {
|
||||
throw new Error('Invalid URL');
|
||||
}
|
||||
|
||||
const started = Date.now();
|
||||
|
||||
// Identity gate for learned/untrusted addresses: verify the UNAUTHENTICATED
|
||||
// /health identity before the token-carrying version fetch, so the bearer
|
||||
// token is never sent to a re-assigned address that now belongs to a
|
||||
// different machine. Older servers omit serverId from /health; only an
|
||||
// explicit mismatch rejects.
|
||||
if (typeof expectedServerId === 'string' && expectedServerId.trim()) {
|
||||
const healthUrl = buildHealthUrl(url);
|
||||
if (healthUrl) {
|
||||
try {
|
||||
const response = await fetch(healthUrl, { signal: AbortSignal.timeout(timeoutMs), headers: { Accept: 'application/json' } });
|
||||
if (response.ok) {
|
||||
const payload = await response.json().catch(() => null);
|
||||
const reported = typeof payload?.serverId === 'string' ? payload.serverId.trim() : '';
|
||||
if (reported && reported !== expectedServerId.trim()) {
|
||||
return { status: 'wrong-service', latencyMs: Date.now() - started };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Unreachable/timeout surfaces in the version fetch below.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const headers = { ...sanitizeRuntimeRequestHeaders(requestHeaders), Accept: 'application/json' };
|
||||
const token = typeof clientToken === 'string' ? clientToken.trim() : '';
|
||||
@@ -3814,7 +3838,7 @@ const handleInvoke = async (browserWindow, command, args = {}) => {
|
||||
return getOrCreateDesktopInstallId();
|
||||
|
||||
case 'desktop_host_probe':
|
||||
return probeHostWithTimeout(String(args.url || ''), 2_000, String(args.clientToken || ''), args.requestHeaders || {});
|
||||
return probeHostWithTimeout(String(args.url || ''), 2_000, String(args.clientToken || ''), args.requestHeaders || {}, String(args.expectedServerId || ''));
|
||||
|
||||
case 'desktop_remote_password_login':
|
||||
return loginRemoteAndIssueClientToken({
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
@@ -365,6 +365,7 @@ const settingsRuntime = createSettingsRuntime({
|
||||
|
||||
const readSettingsFromDiskMigrated = (...args) => settingsRuntime.readSettingsFromDiskMigrated(...args);
|
||||
const readSettingsFromDisk = (...args) => settingsRuntime.readSettingsFromDisk(...args);
|
||||
const readSettingsFromDiskStrict = (...args) => settingsRuntime.readSettingsFromDiskStrict(...args);
|
||||
const writeSettingsToDisk = (...args) => settingsRuntime.writeSettingsToDisk(...args);
|
||||
const persistSettings = (...args) => settingsRuntime.persistSettings(...args);
|
||||
|
||||
@@ -409,6 +410,7 @@ const apnsRuntime = createApnsRuntime({
|
||||
APNS_TOKENS_FILE_PATH,
|
||||
readSettingsFromDiskMigrated,
|
||||
writeSettingsToDisk,
|
||||
readSettingsStrict: readSettingsFromDiskStrict,
|
||||
});
|
||||
|
||||
const addOrUpdateApnsToken = (...args) => apnsRuntime.addOrUpdateApnsToken(...args);
|
||||
@@ -1214,6 +1216,37 @@ async function main(options = {}) {
|
||||
const lan = lanHost ? `http://${lanHost.includes(':') ? `[${lanHost}]` : lanHost}:${activePort}` : null;
|
||||
return { local, lan, relayAvailable: true };
|
||||
};
|
||||
// ALL direct LAN URLs this server is currently reachable on, for the
|
||||
// candidates-refresh endpoint: the address the requesting client already
|
||||
// reached us on first (guaranteed routable from its network — over the relay
|
||||
// tunnel this is loopback and yields nothing), then every non-internal IPv4
|
||||
// interface. A client that paired while the machine had a different DHCP
|
||||
// lease uses this to replace its stale LAN candidate.
|
||||
const resolveDirectLanUrls = (req) => {
|
||||
const activePort = tunnelRuntimeContext.getActivePort() || port;
|
||||
const urls = [];
|
||||
const push = (host) => {
|
||||
if (typeof host !== 'string' || !host) return;
|
||||
const url = `http://${host.includes(':') ? `[${host}]` : host}:${activePort}`;
|
||||
if (!urls.includes(url)) urls.push(url);
|
||||
};
|
||||
if (isNetworkExposedBindHost(effectiveBindHost)) {
|
||||
push(requestReachedLanAddress(req));
|
||||
try {
|
||||
for (const list of Object.values(os.networkInterfaces())) {
|
||||
for (const entry of (list || [])) {
|
||||
if (entry.family === 'IPv4' && !entry.internal) push(entry.address);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// interface scan failure → whatever we already collected
|
||||
}
|
||||
} else {
|
||||
const h = String(effectiveBindHost || '').toLowerCase();
|
||||
if (h && h !== '127.0.0.1' && h !== 'localhost' && h !== '::1') push(effectiveBindHost);
|
||||
}
|
||||
return urls;
|
||||
};
|
||||
const uiPassword = typeof options.uiPassword === 'string'
|
||||
? options.uiPassword
|
||||
: (typeof process.env.OPENCHAMBER_UI_PASSWORD === 'string' ? process.env.OPENCHAMBER_UI_PASSWORD : null);
|
||||
@@ -1374,6 +1407,10 @@ async function main(options = {}) {
|
||||
// redeemed device can flip relay demand on or off).
|
||||
reconcileRelay: () => (relayServiceInstance ? relayServiceInstance.reconcile() : Promise.resolve()),
|
||||
getPairingTransports: resolvePairingTransports,
|
||||
getDirectCandidateUrls: resolveDirectLanUrls,
|
||||
// Stable server identity for client-side verification of learned addresses.
|
||||
// Lazily resolved: the relay service is constructed after these routes.
|
||||
getServerId: () => (relayServiceInstance ? relayServiceInstance.getServerId() : Promise.resolve(null)),
|
||||
// The display name a paired device shows for THIS server. Devices name the
|
||||
// connection by the issuing machine's hostname, not the per-device pairing
|
||||
// label typed by the operator.
|
||||
@@ -1436,6 +1473,7 @@ async function main(options = {}) {
|
||||
os,
|
||||
readSettingsFromDiskMigrated,
|
||||
writeSettingsToDisk,
|
||||
readSettingsStrict: readSettingsFromDiskStrict,
|
||||
remoteClientAuthRuntime,
|
||||
getLocalPort: () => tunnelRuntimeContext.getActivePort(),
|
||||
// Relay demand = any paired device or pending pairing session that uses the
|
||||
|
||||
@@ -42,6 +42,8 @@ export const createApnsRuntime = (deps) => {
|
||||
APNS_TOKENS_FILE_PATH,
|
||||
readSettingsFromDiskMigrated,
|
||||
writeSettingsToDisk,
|
||||
// Strict settings reader gating identity regeneration (see signing-key.js).
|
||||
readSettingsStrict,
|
||||
} = deps;
|
||||
|
||||
let persistLock = Promise.resolve();
|
||||
@@ -60,7 +62,7 @@ export const createApnsRuntime = (deps) => {
|
||||
// relay identity — same keypair, same storage, same serverId derivation).
|
||||
const getOrCreateRelayKeypair = async () => {
|
||||
if (cachedRelayKey) return cachedRelayKey;
|
||||
cachedRelayKey = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk });
|
||||
cachedRelayKey = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
|
||||
return cachedRelayKey;
|
||||
};
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@ export const createBootstrapRuntime = (dependencies) => {
|
||||
getRelayPairingCandidate,
|
||||
reconcileRelay,
|
||||
getPairingTransports,
|
||||
getDirectCandidateUrls,
|
||||
getServerId,
|
||||
getServerLabel,
|
||||
readSettingsFromDiskMigrated,
|
||||
normalizeTunnelSessionTtlMs,
|
||||
@@ -76,6 +78,7 @@ export const createBootstrapRuntime = (dependencies) => {
|
||||
serverStartedAt,
|
||||
gracefulShutdown,
|
||||
getHealthSnapshot,
|
||||
getServerId,
|
||||
tunnelAuthController,
|
||||
uiAuthController,
|
||||
});
|
||||
@@ -91,6 +94,8 @@ export const createBootstrapRuntime = (dependencies) => {
|
||||
getRelayPairingCandidate,
|
||||
reconcileRelay,
|
||||
getPairingTransports,
|
||||
getDirectCandidateUrls,
|
||||
getServerId,
|
||||
getServerLabel,
|
||||
readSettingsFromDiskMigrated,
|
||||
normalizeTunnelSessionTtlMs,
|
||||
|
||||
@@ -67,10 +67,29 @@ export const registerServerStatusRoutes = (app, dependencies) => {
|
||||
serverStartedAt,
|
||||
gracefulShutdown,
|
||||
getHealthSnapshot,
|
||||
// Stable server identity (hash of the public signing key — not a secret).
|
||||
// Exposed on /health and /api/version so a client can verify that a
|
||||
// learned/probed address belongs to the expected server BEFORE sending its
|
||||
// bearer token there. Optional: older wiring omits it.
|
||||
getServerId = async () => null,
|
||||
tunnelAuthController = null,
|
||||
uiAuthController = null,
|
||||
} = dependencies;
|
||||
|
||||
// The identity is immutable for the process lifetime; resolve once, and never
|
||||
// let an identity failure break health reporting.
|
||||
let cachedServerId = null;
|
||||
const resolveServerId = async () => {
|
||||
if (cachedServerId) return cachedServerId;
|
||||
try {
|
||||
const value = await getServerId();
|
||||
cachedServerId = typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
} catch {
|
||||
cachedServerId = null;
|
||||
}
|
||||
return cachedServerId;
|
||||
};
|
||||
|
||||
const allocateLoopbackPort = async () => {
|
||||
const net = await import('node:net');
|
||||
return await new Promise((resolve, reject) => {
|
||||
@@ -213,24 +232,28 @@ export const registerServerStatusRoutes = (app, dependencies) => {
|
||||
}
|
||||
};
|
||||
|
||||
app.get('/health', (_req, res) => {
|
||||
app.get('/health', async (_req, res) => {
|
||||
const serverId = await resolveServerId();
|
||||
res.json({
|
||||
status: 'ok',
|
||||
timestamp: new Date().toISOString(),
|
||||
openchamberVersion,
|
||||
runtime: runtimeName,
|
||||
compatibility,
|
||||
...(serverId ? { serverId } : {}),
|
||||
...getHealthSnapshot(),
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/version', (_req, res) => {
|
||||
app.get('/api/version', async (_req, res) => {
|
||||
const serverId = await resolveServerId();
|
||||
res.json({
|
||||
status: 'ok',
|
||||
openchamberVersion,
|
||||
runtime: runtimeName,
|
||||
startedAt: serverStartedAt,
|
||||
compatibility,
|
||||
...(serverId ? { serverId } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -371,6 +394,12 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
|
||||
// server can actually be reached on (LAN derived from the server bind, not
|
||||
// the UI origin), for the create-device dialog.
|
||||
getPairingTransports = () => ({ local: null, lan: null, relayAvailable: true }),
|
||||
// Returns ALL direct LAN URLs the server is currently reachable on (client-
|
||||
// reached address first, then interface scan) for the candidates-refresh
|
||||
// endpoint. Empty when the server is loopback-only.
|
||||
getDirectCandidateUrls = () => [],
|
||||
// Stable server identity for client-side verification of learned addresses.
|
||||
getServerId = async () => null,
|
||||
// Display name a paired device shows for THIS server (issuing machine's
|
||||
// hostname), distinct from the per-device pairing label typed by the operator.
|
||||
getServerLabel = () => 'OpenChamber',
|
||||
@@ -796,6 +825,48 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
|
||||
});
|
||||
});
|
||||
|
||||
// Current reachable transports for an ALREADY-PAIRED device. Pairing-payload
|
||||
// candidates are a snapshot: when DHCP hands this machine a new address, the
|
||||
// device's saved LAN candidate goes stale and it is stuck on the relay forever.
|
||||
// A client that connected over any live transport calls this to learn the
|
||||
// server's present LAN URLs (plus the relay candidate when enabled) and update
|
||||
// its saved candidate set. `serverId` lets the client bind the response — and
|
||||
// later /health probes of the learned addresses — to this server's identity
|
||||
// before trusting them with its bearer token.
|
||||
// Auth: UI session or client bearer; never the short-lived URL token.
|
||||
app.get('/api/client-auth/connection/candidates', async (req, res, next) => {
|
||||
await runWithClientManagementAuth(req, res, next, async () => {
|
||||
const candidates = [];
|
||||
const directUrls = (() => {
|
||||
try {
|
||||
const urls = getDirectCandidateUrls(req);
|
||||
return Array.isArray(urls) ? urls : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
for (const url of directUrls) {
|
||||
const normalized = normalizeCandidateUrl(url);
|
||||
if (normalized) candidates.push({ type: 'lan', url: normalized, priority: 10 });
|
||||
}
|
||||
try {
|
||||
const relayCandidate = await getRelayPairingCandidate({ ensureEnabled: false });
|
||||
if (relayCandidate) candidates.push(relayCandidate);
|
||||
} catch {
|
||||
// Relay status failure must not break the direct-candidate refresh.
|
||||
}
|
||||
let serverId = null;
|
||||
try {
|
||||
const value = await getServerId();
|
||||
serverId = typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
} catch {
|
||||
serverId = null;
|
||||
}
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.json({ label: getServerLabel(), ...(serverId ? { serverId } : {}), candidates });
|
||||
});
|
||||
});
|
||||
|
||||
// Direct transports the server can be reached on (for the create-device dialog).
|
||||
app.get('/api/client-auth/pairing/transports', async (req, res, next) => {
|
||||
await runWithClientCreateAuth(req, res, next, async () => {
|
||||
|
||||
@@ -571,6 +571,56 @@ describe('client auth routes', () => {
|
||||
expect(listedAfterPurge.body.clients).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('reports current connection candidates with server identity for paired devices', async () => {
|
||||
const app = express();
|
||||
const relayCandidate = {
|
||||
type: 'relay',
|
||||
relayUrl: 'wss://relay.example/ws',
|
||||
serverId: 'server-abc',
|
||||
hostEncPubJwk: { kty: 'EC', crv: 'P-256', x: 'x', y: 'y' },
|
||||
priority: 30,
|
||||
};
|
||||
const dependencies = {
|
||||
...createDependencies({ resolveAuthContext: async () => ({ type: 'client', clientId: 'client-1' }) }),
|
||||
getDirectCandidateUrls: () => ['http://192.168.1.20:3000', 'http://10.0.0.5:3000', 'not-a-url'],
|
||||
getRelayPairingCandidate: async () => relayCandidate,
|
||||
getServerId: async () => 'server-abc',
|
||||
getServerLabel: () => 'my-host',
|
||||
};
|
||||
registerAuthAndAccessRoutes(app, dependencies);
|
||||
|
||||
const response = await request(app).get('/api/client-auth/connection/candidates');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers['cache-control']).toBe('no-store');
|
||||
expect(response.body.serverId).toBe('server-abc');
|
||||
expect(response.body.label).toBe('my-host');
|
||||
expect(response.body.candidates).toEqual([
|
||||
{ type: 'lan', url: 'http://192.168.1.20:3000', priority: 10 },
|
||||
{ type: 'lan', url: 'http://10.0.0.5:3000', priority: 10 },
|
||||
relayCandidate,
|
||||
]);
|
||||
});
|
||||
|
||||
it('omits serverId and relay candidate when unavailable and survives failures', async () => {
|
||||
const app = express();
|
||||
const dependencies = {
|
||||
...createDependencies(),
|
||||
getDirectCandidateUrls: () => {
|
||||
throw new Error('scan failed');
|
||||
},
|
||||
getRelayPairingCandidate: async () => {
|
||||
throw new Error('relay status failed');
|
||||
},
|
||||
getServerId: async () => null,
|
||||
};
|
||||
registerAuthAndAccessRoutes(app, dependencies);
|
||||
|
||||
const response = await request(app).get('/api/client-auth/connection/candidates');
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).not.toHaveProperty('serverId');
|
||||
expect(response.body.candidates).toEqual([]);
|
||||
});
|
||||
|
||||
it('scopes non-desktop client credentials to list and revoke only themselves', async () => {
|
||||
const app = express();
|
||||
let authContext = { type: 'session' };
|
||||
|
||||
@@ -438,6 +438,30 @@ export const createSettingsRuntime = (deps) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Strict variant for callers that REGENERATE persisted identity when a key is
|
||||
// absent (relay signing/encryption keys). The lenient reader above maps every
|
||||
// failure — corrupt JSON, EACCES, transient I/O — to `{}`, which such callers
|
||||
// cannot distinguish from "first run": they would mint a NEW identity, orphan
|
||||
// every paired device and push binding, and overwrite the settings file with
|
||||
// the empty spread. Here only a genuinely missing file means "no settings";
|
||||
// any other failure (including a non-object payload) throws.
|
||||
const readSettingsFromDiskStrict = async () => {
|
||||
let raw;
|
||||
try {
|
||||
raw = await fsPromises.readFile(SETTINGS_FILE_PATH, 'utf8');
|
||||
} catch (error) {
|
||||
if (error && typeof error === 'object' && error.code === 'ENOENT') {
|
||||
return {};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!parsed || typeof parsed !== 'object') {
|
||||
throw new Error('Settings file is malformed (non-object payload)');
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const isTransientWindowsReplaceError = (error) => {
|
||||
@@ -870,6 +894,7 @@ export const createSettingsRuntime = (deps) => {
|
||||
|
||||
return {
|
||||
readSettingsFromDisk,
|
||||
readSettingsFromDiskStrict,
|
||||
readSettingsFromDiskMigrated,
|
||||
writeSettingsToDisk,
|
||||
persistSettings,
|
||||
|
||||
@@ -59,6 +59,25 @@ The host dispatcher restricts tunneled traffic to explicit path allowlists (one
|
||||
4. **Handshake.** Over that connection pair, client and host run the E2EE handshake and derive a shared encrypted channel the relay cannot read.
|
||||
5. **Traffic.** All normal app traffic is multiplexed and encrypted through that channel. On the host, decrypted requests are dispatched to the local server over loopback; responses stream back encrypted. Reconnects re-establish a fresh channel and the app's existing retry machinery recovers.
|
||||
|
||||
## Candidate refresh (staying off the relay when direct works)
|
||||
|
||||
Pairing-payload transport candidates are a snapshot: when DHCP hands the host
|
||||
machine a new LAN address, a device's saved direct candidate goes stale and the
|
||||
device silently degrades to relay-only. To recover, an already-paired client can
|
||||
call `GET /api/client-auth/connection/candidates` (UI session or client bearer;
|
||||
registered with the auth/access routes) over any live transport — including
|
||||
through the tunnel — to learn the server's **current** LAN URLs plus the relay
|
||||
candidate, and update its saved candidate set (mobile: `mobileConnections.ts`;
|
||||
desktop: `desktopRelayRestore.ts`).
|
||||
|
||||
Identity gating: the response carries the stable `serverId` (base64url SHA-256 of
|
||||
the public signing JWK — the same identity the relay routes by, exposed by the
|
||||
relay service's `getServerId()` and echoed unauthenticated on `/health` and
|
||||
`/api/version`). Clients ignore a refresh whose `serverId` does not match their
|
||||
pinned relay identity, and verify `/health`'s `serverId` on a learned address
|
||||
**before** sending their bearer token to it — a re-assigned LAN address may now
|
||||
belong to a different machine.
|
||||
|
||||
## Two implementations, kept in sync
|
||||
|
||||
The E2EE and framing logic exists twice: TypeScript in `packages/ui/src/lib/relay/` (shared by the client and the normative reference) and a JavaScript mirror in this module (the host, which is plain JS ESM). They **must stay byte-compatible** — a client encrypted by one must decrypt on the other. A cross-compatibility test (`cross-compat.test.js`) imports the TS modules directly and exercises a full TS-client ↔ JS-host exchange. Any change to the wire format, frame codec, handshake, or batching must update both sides and keep that test green.
|
||||
|
||||
@@ -16,10 +16,15 @@ import { exportPublicKeyJwk, generateEcdhKeyPair, importEcdhPrivateKey } from '.
|
||||
const isJwkPair = (value) => Boolean(value && typeof value === 'object' && value.privateJwk && value.publicJwk);
|
||||
|
||||
/**
|
||||
* @param {{ crypto: typeof import('node:crypto'), readSettingsFromDiskMigrated: () => Promise<object>, writeSettingsToDisk: (settings: object) => Promise<void> }} deps
|
||||
* @param {{
|
||||
* crypto: typeof import('node:crypto'),
|
||||
* readSettingsFromDiskMigrated: () => Promise<object>,
|
||||
* writeSettingsToDisk: (settings: object) => Promise<void>,
|
||||
* readSettingsStrict?: () => Promise<object>,
|
||||
* }} deps
|
||||
*/
|
||||
export const createRelayIdentityRuntime = (deps) => {
|
||||
const { crypto, readSettingsFromDiskMigrated, writeSettingsToDisk } = deps;
|
||||
const { crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict } = deps;
|
||||
|
||||
let cachedIdentity = null;
|
||||
|
||||
@@ -29,10 +34,25 @@ export const createRelayIdentityRuntime = (deps) => {
|
||||
if (isJwkPair(existing)) {
|
||||
return existing;
|
||||
}
|
||||
// Same regeneration gate as the signing key: never mint a replacement
|
||||
// identity key off a swallowed read failure — a new encryption key breaks
|
||||
// the E2EE trust anchor pinned by every paired device. Verify "missing" via
|
||||
// the strict reader (throws on corrupt/unreadable) before generating.
|
||||
let verifiedSettings = settings;
|
||||
if (readSettingsStrict) {
|
||||
verifiedSettings = await readSettingsStrict();
|
||||
const verified = verifiedSettings?.relayEncryptionKey;
|
||||
if (isJwkPair(verified)) {
|
||||
return verified;
|
||||
}
|
||||
}
|
||||
// Loud on purpose: a new encryption key invalidates the E2EE trust anchor of
|
||||
// every paired device. Expected exactly once, on first relay use.
|
||||
console.warn('[relay-identity] Generating NEW relay encryption keypair (E2EE trust anchor changes; previously paired devices must re-pair)');
|
||||
const keyPair = await generateEcdhKeyPair();
|
||||
const privateJwk = await globalThis.crypto.subtle.exportKey('jwk', keyPair.privateKey);
|
||||
const publicJwk = await exportPublicKeyJwk(keyPair.publicKey);
|
||||
await writeSettingsToDisk({ ...settings, relayEncryptionKey: { privateJwk, publicJwk } });
|
||||
await writeSettingsToDisk({ ...settings, ...(verifiedSettings || {}), relayEncryptionKey: { privateJwk, publicJwk } });
|
||||
return { privateJwk, publicJwk };
|
||||
};
|
||||
|
||||
@@ -46,7 +66,7 @@ export const createRelayIdentityRuntime = (deps) => {
|
||||
*/
|
||||
const getRelayIdentity = async () => {
|
||||
if (cachedIdentity) return cachedIdentity;
|
||||
const signing = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk });
|
||||
const signing = await getOrCreateRelaySigningKeypair({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
|
||||
const serverId = deriveServerId({ crypto }, signing.publicJwk);
|
||||
const encryption = await getOrCreateEncryptionKeypair();
|
||||
const hostEncPrivateKey = await importEcdhPrivateKey(encryption.privateJwk);
|
||||
|
||||
@@ -58,13 +58,16 @@ export const createRelayService = ({
|
||||
crypto,
|
||||
readSettingsFromDiskMigrated,
|
||||
writeSettingsToDisk,
|
||||
// Strict settings reader (throws on corrupt/unreadable) gating identity
|
||||
// regeneration — see identity.js/signing-key.js.
|
||||
readSettingsStrict,
|
||||
getLocalPort,
|
||||
// Returns true when any paired device or pending pairing session uses the
|
||||
// relay transport. The relay lifecycle is driven purely by this demand.
|
||||
hasRelayDemand = async () => false,
|
||||
logger = console,
|
||||
}) => {
|
||||
const identityRuntime = createRelayIdentityRuntime({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk });
|
||||
const identityRuntime = createRelayIdentityRuntime({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict });
|
||||
|
||||
let hostClient = null;
|
||||
let status = { state: 'disabled', lastError: null, connectedClients: 0 };
|
||||
@@ -145,6 +148,15 @@ export const createRelayService = ({
|
||||
}
|
||||
};
|
||||
|
||||
// Stable server identity (base64url SHA-256 of the canonical public signing
|
||||
// JWK). Derived from a public key, so it is not a secret; clients use it to
|
||||
// verify that a learned/probed address belongs to this server before trusting
|
||||
// it. Independent of whether the relay host is currently enabled.
|
||||
const getServerId = async () => {
|
||||
const identity = await identityRuntime.getRelayIdentity();
|
||||
return identity.serverId;
|
||||
};
|
||||
|
||||
const getStatus = async () => {
|
||||
const config = await readConfig();
|
||||
const identity = await identityRuntime.getRelayIdentity();
|
||||
@@ -241,6 +253,7 @@ export const createRelayService = ({
|
||||
reconcile,
|
||||
stop,
|
||||
getStatus,
|
||||
getServerId,
|
||||
getPairingCandidate,
|
||||
ensureEnabledForPairing,
|
||||
};
|
||||
|
||||
@@ -6,22 +6,45 @@
|
||||
// serverId must stay stable because push token binding depends on it.
|
||||
|
||||
/**
|
||||
* @param {{ crypto: typeof import('node:crypto'), readSettingsFromDiskMigrated: () => Promise<object>, writeSettingsToDisk: (settings: object) => Promise<void> }} deps
|
||||
* @param {{
|
||||
* crypto: typeof import('node:crypto'),
|
||||
* readSettingsFromDiskMigrated: () => Promise<object>,
|
||||
* writeSettingsToDisk: (settings: object) => Promise<void>,
|
||||
* readSettingsStrict?: () => Promise<object>,
|
||||
* }} deps
|
||||
* @returns {Promise<{ privateKey: import('node:crypto').KeyObject, publicJwk: JsonWebKey }>}
|
||||
*/
|
||||
export const getOrCreateRelaySigningKeypair = async ({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk }) => {
|
||||
export const getOrCreateRelaySigningKeypair = async ({ crypto, readSettingsFromDiskMigrated, writeSettingsToDisk, readSettingsStrict }) => {
|
||||
const toKeypair = (stored) => ({
|
||||
privateKey: crypto.createPrivateKey({ key: stored.privateJwk, format: 'jwk' }),
|
||||
publicJwk: stored.publicJwk,
|
||||
});
|
||||
const settings = await readSettingsFromDiskMigrated();
|
||||
const existing = settings?.relaySigningKey;
|
||||
if (existing && existing.privateJwk && existing.publicJwk) {
|
||||
return {
|
||||
privateKey: crypto.createPrivateKey({ key: existing.privateJwk, format: 'jwk' }),
|
||||
publicJwk: existing.publicJwk,
|
||||
};
|
||||
return toKeypair(existing);
|
||||
}
|
||||
// Regeneration gate: the lenient settings reader maps read failures to `{}`,
|
||||
// indistinguishable from "first run". Minting a new keypair changes serverId,
|
||||
// which orphans every paired device and push binding AND the write below would
|
||||
// clobber the settings file with the empty spread. Re-verify with the strict
|
||||
// reader (throws on corrupt/unreadable) before generating; if it finds the
|
||||
// key the lenient read lost, use it and generate nothing.
|
||||
let verifiedSettings = settings;
|
||||
if (readSettingsStrict) {
|
||||
verifiedSettings = await readSettingsStrict();
|
||||
const verified = verifiedSettings?.relaySigningKey;
|
||||
if (verified && verified.privateJwk && verified.publicJwk) {
|
||||
return toKeypair(verified);
|
||||
}
|
||||
}
|
||||
// Loud on purpose: a new signing key means a new serverId — every previously
|
||||
// paired device and push binding is orphaned. Expected exactly once, on first run.
|
||||
console.warn('[relay-identity] Generating NEW relay signing keypair (serverId changes; previously paired devices must re-pair)');
|
||||
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||
const privateJwk = privateKey.export({ format: 'jwk' });
|
||||
const publicJwk = publicKey.export({ format: 'jwk' });
|
||||
await writeSettingsToDisk({ ...settings, relaySigningKey: { privateJwk, publicJwk } });
|
||||
await writeSettingsToDisk({ ...settings, ...(verifiedSettings || {}), relaySigningKey: { privateJwk, publicJwk } });
|
||||
return { privateKey, publicJwk };
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user