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