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:
Bohdan Triapitsyn
2026-07-12 18:09:54 +03:00
parent 22d5ad3814
commit afb368e11b
16 changed files with 610 additions and 27 deletions
@@ -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 () => {