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
+5
View File
@@ -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,