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:
@@ -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