feat: add private relay for end-to-end-encrypted remote access (#2087)
Adds OpenChamber Relay — an opt-in way to reach an instance from a phone, browser, or another desktop from anywhere, with no open inbound ports, no tunnel, and no shared LAN. The instance dials outbound to a relay; all app traffic (HTTP, the event stream, terminal, dictation) is multiplexed and encrypted through a single connection per client, so the relay only ever forwards opaque ciphertext. Transport - End-to-end-encrypted channel over WebCrypto (ECDH P-256 -> HKDF -> AES-256-GCM) with a capability-negotiated handshake and a small HTTP/SSE/WebSocket multiplexing protocol. A byte-compatible JS host mirror is cross-checked by tests. - Host: outbound connection manager, per-client tunnel dispatcher to the local server over loopback, reuse of the existing instance identity key, and management routes. Disabled by default; explicit opt-in. - Client: plugs into the existing runtime layer (runtime-fetch/-url/-switch/ -auth, event pipeline, terminal, dictation) so features work over the relay unchanged; direct-URL and Electron realtime-proxy paths are untouched. Pairing & UX - Relay section in Settings -> Remote Instances (live status, QR/link pairing, revocation via the existing client-token list) and the mobile connect flow. - Frame batching and idle-gated keepalive keep tunnel message volume low without affecting streaming smoothness. Security - The tunnel is transport only; the server authenticates every tunneled request exactly as for a direct remote client. fragments only. The relay stores no keys, tokens, or payloads. Operability - The endpoint can be pinned to a self-hosted rel paired clients inherit it from the offer automatically. - Relay module DOCUMENTATION.md and a relay-trans invariants that future WebSocket/streaming changes must follow. The relay transport is complete and tested; the UI for enabling and pairing is gated behind openchamber_relay_gate and stays
This commit is contained in:
committed by
GitHub
parent
42e470cefa
commit
859b4529da
@@ -204,6 +204,14 @@ describe('cli args', () => {
|
||||
expect(parsed.options.server).toBe('http://homebridge:3002');
|
||||
});
|
||||
|
||||
it('parses connect-url --relay flag', () => {
|
||||
const parsed = parseArgs(['connect-url', '--relay', '--name', 'My laptop']);
|
||||
|
||||
expect(parsed.command).toBe('connect-url');
|
||||
expect(parsed.options.relay).toBe(true);
|
||||
expect(parsed.options.name).toBe('My laptop');
|
||||
});
|
||||
|
||||
it('parses connect-url api-only help', () => {
|
||||
const parsed = parseArgs(['connect-url', '--api-only', '--help']);
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ Command modules implement user-facing commands and preserve output contracts acr
|
||||
- `commands-connect-url.js`
|
||||
- Implements `openchamber connect-url`.
|
||||
- Finds or starts a local instance and prints the browser/connect URL according to the selected output mode.
|
||||
- `--relay` builds an end-to-end-encrypted relay pairing link instead: it mints a client token and an offer from the instance's local relay identity (no server URL, no auto-start). The relay endpoint follows `OPENCHAMBER_RELAY_URL` / the stored setting / the default, matching the running host; clients read it from the offer.
|
||||
|
||||
- `commands-update.js`
|
||||
- Implements `openchamber update`.
|
||||
|
||||
@@ -264,6 +264,9 @@ function parseArgs(argv = process.argv.slice(2)) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'relay':
|
||||
options.relay = true;
|
||||
break;
|
||||
case 'qr':
|
||||
options.qr = true;
|
||||
options.explicitQr = true;
|
||||
@@ -384,6 +387,7 @@ OPTIONS:
|
||||
--hostname Alias for --host outside tunnel commands
|
||||
--lan Bind to 0.0.0.0 for LAN access
|
||||
--server <url> Public/server URL for connect-url links
|
||||
--relay connect-url: generate an end-to-end-encrypted relay pairing link
|
||||
--ui-password Protect browser UI with single password
|
||||
--api-only Start API routes only, without serving browser UI assets
|
||||
--foreground Run server in foreground (use with systemd/process managers)
|
||||
@@ -461,6 +465,10 @@ OPTIONS:
|
||||
--lan Bind to 0.0.0.0 for LAN access when starting
|
||||
--server <url> Public URL saved into the connection link
|
||||
--server-url <url> Alias for --server
|
||||
--relay Generate an end-to-end-encrypted relay pairing link
|
||||
(no server URL needed; requires the relay enabled on
|
||||
this instance). Set OPENCHAMBER_RELAY_URL to use a
|
||||
self-hosted relay.
|
||||
--name <label> Label saved with the remote client token
|
||||
--ui-password <value> Protect browser access when UI routes are enabled
|
||||
--api-only Start in headless/API-only mode when starting
|
||||
@@ -473,6 +481,7 @@ EXAMPLES:
|
||||
openchamber connect-url --port 3000 --qr
|
||||
openchamber connect-url --port 3000 --api-only --lan --server http://workstation.local:3000 --qr
|
||||
openchamber connect-url --server https://openchamber.example.com --name Workstation
|
||||
openchamber connect-url --relay --name "My laptop"
|
||||
`);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ import {
|
||||
import { discoverRunningInstances } from './cli-lifecycle.js';
|
||||
import { getInstanceFilePath, readInstanceOptions } from './cli-process.js';
|
||||
import { createRemoteClientAuthRuntime } from '../../server/lib/client-auth/remote-clients.js';
|
||||
import { createRelayIdentityRuntime } from '../../server/lib/relay/identity.js';
|
||||
import { DEFAULT_RELAY_URL } from '../../server/lib/relay/service.js';
|
||||
import { bytesToBase64Url } from '../../server/lib/relay/e2ee.js';
|
||||
import {
|
||||
intro as clackIntro,
|
||||
outro as clackOutro,
|
||||
@@ -24,6 +27,102 @@ import {
|
||||
} from '../cli-output.js';
|
||||
|
||||
const REMOTE_CLIENTS_FILE_NAME = 'remote-clients.json';
|
||||
const SETTINGS_FILE_NAME = 'settings.json';
|
||||
|
||||
function isValidRelayUrl(value) {
|
||||
if (typeof value !== 'string') return false;
|
||||
try {
|
||||
const url = new URL(value.trim());
|
||||
return url.protocol === 'ws:' || url.protocol === 'wss:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the relay endpoint the same way the running host does (service.js):
|
||||
// OPENCHAMBER_RELAY_URL env override, then the stored setting, then the default —
|
||||
// so the pairing link points at the same relay the host connects out to.
|
||||
function resolveRelayUrl(settings) {
|
||||
const envUrl = process.env.OPENCHAMBER_RELAY_URL;
|
||||
if (isValidRelayUrl(envUrl)) return envUrl.trim();
|
||||
const stored = settings?.privateRelay?.relayUrl;
|
||||
if (isValidRelayUrl(stored)) return stored.trim();
|
||||
return DEFAULT_RELAY_URL;
|
||||
}
|
||||
|
||||
// Minimal settings.json read/write for the relay identity runtime. It reads the
|
||||
// whole object and writes it back with the relay keys added, so other settings
|
||||
// are preserved. Enough for the CLI without wiring the full settings runtime.
|
||||
function createSettingsAccessors() {
|
||||
const settingsPath = path.join(getOpenChamberDataDir(), SETTINGS_FILE_NAME);
|
||||
const readSettingsFromDiskMigrated = async () => {
|
||||
try {
|
||||
return JSON.parse(await fs.promises.readFile(settingsPath, 'utf8'));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
const writeSettingsToDisk = async (settings) => {
|
||||
await fs.promises.mkdir(path.dirname(settingsPath), { recursive: true });
|
||||
await fs.promises.writeFile(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
|
||||
};
|
||||
return { readSettingsFromDiskMigrated, writeSettingsToDisk };
|
||||
}
|
||||
|
||||
// Builds an end-to-end-encrypted relay pairing link. Reuses the instance's relay
|
||||
// identity (serverId + encryption public key), generating it if the relay was
|
||||
// never enabled. The client reads the relay URL from the offer, so no client-side
|
||||
// configuration is needed.
|
||||
async function buildRelayConnectionPayload({ token, label }) {
|
||||
const accessors = createSettingsAccessors();
|
||||
const settings = await accessors.readSettingsFromDiskMigrated();
|
||||
const relayUrl = resolveRelayUrl(settings);
|
||||
const identityRuntime = createRelayIdentityRuntime({ crypto, ...accessors });
|
||||
const identity = await identityRuntime.getRelayIdentity();
|
||||
const offer = {
|
||||
v: 1,
|
||||
mode: 'relay',
|
||||
relayUrl,
|
||||
serverId: identity.serverId,
|
||||
hostEncPubJwk: identity.hostEncPubJwk,
|
||||
label,
|
||||
token,
|
||||
};
|
||||
const encoded = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(offer)));
|
||||
return { connectUrl: `openchamber://connect?v=1&mode=relay#offer=${encoded}`, relayUrl, serverId: identity.serverId };
|
||||
}
|
||||
|
||||
async function generateRelayConnectUrl(options) {
|
||||
const label = options.name || os.hostname();
|
||||
const runtime = createRemoteClientAuthRuntime({
|
||||
fsPromises: fs.promises,
|
||||
path,
|
||||
crypto,
|
||||
storePath: path.join(getOpenChamberDataDir(), REMOTE_CLIENTS_FILE_NAME),
|
||||
});
|
||||
const result = await runtime.createClient({ label, clientKind: 'relay' });
|
||||
const { connectUrl, relayUrl, serverId } = await buildRelayConnectionPayload({ token: result.token, label });
|
||||
|
||||
if (isJsonMode(options)) {
|
||||
printJson({ mode: 'relay', relayUrl, serverId, connectUrl, token: result.token, client: result.client });
|
||||
return;
|
||||
}
|
||||
|
||||
if (isQuietMode(options)) {
|
||||
process.stdout.write(`${connectUrl}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
clackIntro('OpenChamber relay connect URL');
|
||||
logStatus('success', connectUrl);
|
||||
clackLog.info(`Relay: ${relayUrl}`);
|
||||
logStatus('info', '[RELAY_ENABLE]', 'Enable the relay on this instance so this link can connect (Settings -> Remote Instances).');
|
||||
clackLog.info('Copy this link into another OpenChamber client. The token is shown only once.');
|
||||
if (options.qr === true) {
|
||||
await displayTunnelQrCode(connectUrl);
|
||||
}
|
||||
clackOutro('relay connect URL generated');
|
||||
}
|
||||
|
||||
async function resolveConnectUrlServerUrl(options) {
|
||||
let hostOverride = options.host;
|
||||
@@ -119,6 +218,13 @@ function createConnectUrlCommand({ serveCommand }) {
|
||||
throw new TunnelCliError('Invalid --server URL. Use an http:// or https:// URL.', EXIT_CODE.USAGE_ERROR);
|
||||
}
|
||||
|
||||
// Relay pairing needs neither a reachable server URL nor a running server:
|
||||
// the link is built from the instance's local relay identity + a fresh client
|
||||
// token. The client reads the relay endpoint from the offer.
|
||||
if (options.relay) {
|
||||
return await generateRelayConnectUrl(options);
|
||||
}
|
||||
|
||||
const running = await discoverRunningInstances();
|
||||
const serverState = running.some((entry) => entry.port === options.port)
|
||||
? { port: options.port, autoStarted: false }
|
||||
|
||||
Reference in New Issue
Block a user