feat(ssh): rework remote instance setup and fix remote installs

Adding an SSH connection now starts from the hosts in the SSH config
instead of a blank command field, ports and install options sit behind
Advanced settings, and each connection reports one of three states with
the failure text and an action that resolves it.

Remote installs no longer touch the root-owned global npm prefix: npm is
pinned to a prefix under $HOME and bun is resolved at its known location,
because an SSH login shell exposes neither on PATH. The opencode CLI is
resolved the same way and handed to the remote server through
OPENCODE_BINARY, and the server is started and stopped through the
resolved binary rather than PATH — the HTTP shutdown route sits behind UI
authentication and never stopped anything.

A managed remote server can also be published to the remote machine's own
network. That requires a UI password, enforced in the form and again in
the SSH manager.
This commit is contained in:
Bohdan Triapitsyn
2026-08-22 16:45:56 +03:00
parent eed317f18d
commit f7a0d1f0f6
16 changed files with 1234 additions and 302 deletions
+127 -45
View File
@@ -10,6 +10,25 @@ import { replaceFileWithRetry } from './windows-file-replace.mjs';
const LOCAL_HOST_ID = 'local';
const DEFAULT_CONNECTION_TIMEOUT_SEC = 60;
const DEFAULT_LOCAL_BIND_HOST = '127.0.0.1';
// Global npm prefixes are root-owned on most distributions, so `npm install -g`
// fails with EACCES for a normal SSH user. Everything we install goes to a
// prefix inside the user's home instead.
const REMOTE_USER_PREFIX = '$HOME/.openchamber/npm-global';
const REMOTE_BUN_CANDIDATE = '"${BUN_INSTALL:-$HOME/.bun}/bin/bun"';
// The opencode CLI usually installs into the user's home, which an SSH login
// shell does not have on PATH. The remote server only looks at OPENCODE_BINARY
// and PATH, so resolve the CLI here and hand it over explicitly.
const REMOTE_OPENCODE_CANDIDATES = [
'"$HOME/.opencode/bin/opencode"',
'"${BUN_INSTALL:-$HOME/.bun}/bin/opencode"',
'"$HOME/.local/bin/opencode"',
'"$HOME/.openchamber/npm-global/bin/opencode"',
];
const REMOTE_PATH_PREFIX = '$HOME/.opencode/bin:${BUN_INSTALL:-$HOME/.bun}/bin:$HOME/.local/bin:$HOME/.openchamber/npm-global/bin';
const REMOTE_BIN_CANDIDATES = [
'"$HOME/.openchamber/npm-global/bin/openchamber"',
'"${BUN_INSTALL:-$HOME/.bun}/bin/openchamber"',
];
const DEFAULT_CONTROL_PERSIST_SEC = 300;
const DEFAULT_READY_TIMEOUT_SEC = 30;
const DEFAULT_RECONNECT_MAX_ATTEMPTS = 5;
@@ -585,6 +604,7 @@ export class ElectronSshManager {
localUrl: null,
localPort: null,
remotePort: null,
remoteBinPath: null,
startedByUs: false,
retryAttempt: 0,
requiresUserAction: false,
@@ -811,9 +831,10 @@ export class ElectronSshManager {
mode: instance?.remoteOpenchamber?.mode === 'external' ? 'external' : 'managed',
keepRunning: instance?.remoteOpenchamber?.keepRunning !== false,
...(Number.isFinite(instance?.remoteOpenchamber?.preferredPort) ? { preferredPort: Number(instance.remoteOpenchamber.preferredPort) } : {}),
installMethod: ['npm', 'bun', 'download_release', 'upload_bundle'].includes(instance?.remoteOpenchamber?.installMethod)
installMethod: ['auto', 'npm', 'bun'].includes(instance?.remoteOpenchamber?.installMethod)
? instance.remoteOpenchamber.installMethod
: 'bun',
: 'auto',
bindHost: instance?.remoteOpenchamber?.bindHost === '0.0.0.0' ? '0.0.0.0' : '127.0.0.1',
uploadBundleOverSsh: Boolean(instance?.remoteOpenchamber?.uploadBundleOverSsh),
},
localForward: {
@@ -988,38 +1009,77 @@ export class ElectronSshManager {
return secret?.enabled && typeof secret.value === 'string' && secret.value.trim() ? secret.value.trim() : null;
}
async remoteCommandExists(parsed, controlPath, commandName) {
try {
const output = await this.runRemoteCommand(parsed, controlPath, `command -v ${commandName} >/dev/null 2>&1 && echo yes || echo no`);
return output.trim() === 'yes';
} catch {
return false;
}
}
// A login shell over SSH does not source the user's interactive rc files, so
// tools installed into a home directory (bun above all) are missing from PATH
// even when they exist. Look at their known install locations too.
async resolveRemoteTool(parsed, controlPath, commandName, extraCandidates = []) {
const candidateList = [...extraCandidates, `"$(command -v ${commandName} 2>/dev/null)"`].join(' ');
const script = [
`for candidate in ${candidateList}; do`,
' [ -n "$candidate" ] || continue;',
' [ -x "$candidate" ] || continue;',
` printf '%s' "$candidate";`,
' exit 0;',
'done',
].join(' ');
async currentRemoteOpenChamberVersion(parsed, controlPath) {
try {
const output = await this.runRemoteCommand(parsed, controlPath, 'openchamber --version 2>/dev/null || true');
return parseVersionToken(output);
const output = await this.runRemoteCommand(parsed, controlPath, script);
return output.trim() || null;
} catch {
return null;
}
}
async installOpenChamberManaged(parsed, controlPath, version, preferred) {
const hasBun = await this.remoteCommandExists(parsed, controlPath, 'bun');
const hasNpm = await this.remoteCommandExists(parsed, controlPath, 'npm');
const commands = [];
// Every place OpenChamber may live on the remote host, with the version each
// one reports. Installs land in the user prefix while an older copy can still
// sit on PATH, so the caller picks by version instead of trusting PATH order.
async remoteOpenChamberCandidates(parsed, controlPath) {
const script = [
`for candidate in ${REMOTE_BIN_CANDIDATES.join(' ')} "$(command -v openchamber 2>/dev/null)"; do`,
' [ -n "$candidate" ] || continue;',
' [ -x "$candidate" ] || continue;',
` printf '%s\t%s\n' "$candidate" "$("$candidate" --version 2>/dev/null | head -n 1)";`,
'done',
].join(' ');
if (preferred === 'bun') {
if (hasBun) commands.push(`bun add -g @openchamber/web@${version}`);
if (hasNpm) commands.push(`npm install -g @openchamber/web@${version}`);
} else if (preferred === 'npm') {
if (hasNpm) commands.push(`npm install -g @openchamber/web@${version}`);
if (hasBun) commands.push(`bun add -g @openchamber/web@${version}`);
let output = '';
try {
output = await this.runRemoteCommand(parsed, controlPath, script);
} catch {
return [];
}
const candidates = [];
const seen = new Set();
for (const line of output.split(/\r?\n/)) {
const [binPath, versionRaw] = line.split('\t');
const trimmed = (binPath || '').trim();
if (!trimmed || seen.has(trimmed)) continue;
seen.add(trimmed);
candidates.push({ binPath: trimmed, version: parseVersionToken(versionRaw || '') });
}
return candidates;
}
async installOpenChamberManaged(parsed, controlPath, version, preferred) {
const bunPath = await this.resolveRemoteTool(parsed, controlPath, 'bun', [REMOTE_BUN_CANDIDATE]);
const npmPath = await this.resolveRemoteTool(parsed, controlPath, 'npm');
// bun's global install already targets ~/.bun; npm is pinned to a prefix in
// the user's home so it never touches the root-owned global directory.
const bunCommand = bunPath ? `${shellQuote(bunPath)} add -g @openchamber/web@${version}` : null;
const npmCommand = npmPath
? `mkdir -p "${REMOTE_USER_PREFIX}" && ${shellQuote(npmPath)} install -g --prefix "${REMOTE_USER_PREFIX}" @openchamber/web@${version}`
: null;
const commands = [];
if (preferred === 'npm') {
if (npmCommand) commands.push(npmCommand);
if (bunCommand) commands.push(bunCommand);
} else {
if (hasBun) commands.push(`bun add -g @openchamber/web@${version}`);
if (hasNpm) commands.push(`npm install -g @openchamber/web@${version}`);
if (bunCommand) commands.push(bunCommand);
if (npmCommand) commands.push(npmCommand);
}
if (commands.length === 0) {
@@ -1079,24 +1139,35 @@ export class ElectronSshManager {
}
}
async startRemoteServerManaged(parsed, controlPath, instance, desiredPort) {
let envPrefix = 'OPENCHAMBER_RUNTIME=ssh-remote';
async startRemoteServerManaged(parsed, controlPath, instance, desiredPort, binPath) {
const opencodePath = await this.resolveRemoteTool(parsed, controlPath, 'opencode', REMOTE_OPENCODE_CANDIDATES);
if (!opencodePath) {
throw new Error('The opencode CLI is not installed on the remote machine. Install it there, then connect again');
}
const secret = this.configuredOpenChamberPassword(instance);
const remoteBindHost = instance.remoteOpenchamber?.bindHost === '0.0.0.0' ? '0.0.0.0' : '127.0.0.1';
// Binding the remote server to every interface publishes its UI to the
// remote machine's whole network, so it may not run without a password.
if (remoteBindHost === '0.0.0.0' && !secret) {
throw new Error('Exposing the remote server to its network requires a UI password');
}
let envPrefix = `PATH="${REMOTE_PATH_PREFIX}:$PATH" OPENCODE_BINARY=${shellQuote(opencodePath)} OPENCHAMBER_RUNTIME=ssh-remote`;
if (secret) {
envPrefix += ` OPENCHAMBER_UI_PASSWORD=${shellQuote(secret)}`;
}
const output = await this.runRemoteCommand(parsed, controlPath, `${envPrefix} openchamber serve --hostname 127.0.0.1 --port ${desiredPort}`);
const output = await this.runRemoteCommand(parsed, controlPath, `${envPrefix} ${shellQuote(binPath)} serve --hostname ${remoteBindHost} --port ${desiredPort}`);
const port = output.split(/\s+/).map((token) => Number.parseInt(token, 10)).find((value) => Number.isFinite(value));
return port || desiredPort;
}
async stopRemoteServerBestEffort(parsed, controlPath, remotePort) {
// `openchamber stop` owns the daemon lifecycle. The HTTP shutdown route sits
// behind UI authentication, so it cannot stop a password-protected server.
async stopRemoteServerBestEffort(parsed, controlPath, remotePort, remoteBinPath) {
if (!remoteBinPath) return;
try {
await this.runRemoteCommand(
parsed,
controlPath,
`if command -v curl >/dev/null 2>&1; then curl -fsS -X POST http://127.0.0.1:${remotePort}/api/system/shutdown >/dev/null 2>&1 || true; elif command -v wget >/dev/null 2>&1; then wget -qO- --method=POST http://127.0.0.1:${remotePort}/api/system/shutdown >/dev/null 2>&1 || true; fi`,
);
await this.runRemoteCommand(parsed, controlPath, `${shellQuote(remoteBinPath)} stop --port ${remotePort}`);
} catch {
}
}
@@ -1150,17 +1221,27 @@ export class ElectronSshManager {
const port = instance.remoteOpenchamber.preferredPort;
this.setStatus(instance.id, 'server_detecting', 'Probing external OpenChamber server', null, null, port, false, 0, false);
await this.probeRemoteSystemInfo(parsed, controlPath, port, this.configuredOpenChamberPassword(instance));
return { remotePort: port, startedByUs: false };
return { remotePort: port, startedByUs: false, remoteBinPath: null };
}
this.setStatus(instance.id, 'remote_probe', 'Checking remote OpenChamber installation');
const installedVersion = await this.currentRemoteOpenChamberVersion(parsed, controlPath);
if (!installedVersion) {
this.setStatus(instance.id, 'installing', 'Installing OpenChamber on remote host');
await this.installOpenChamberManaged(parsed, controlPath, this.appVersion, instance.remoteOpenchamber.installMethod);
} else if (installedVersion !== this.appVersion) {
this.setStatus(instance.id, 'updating', `Updating remote OpenChamber from ${installedVersion} to ${this.appVersion}`);
const installed = await this.remoteOpenChamberCandidates(parsed, controlPath);
let binary = installed.find((candidate) => candidate.version === this.appVersion) || null;
if (!binary) {
const existing = installed[0] || null;
if (existing) {
this.setStatus(instance.id, 'updating', `Updating remote OpenChamber from ${existing.version || 'unknown'} to ${this.appVersion}`);
} else {
this.setStatus(instance.id, 'installing', 'Installing OpenChamber on remote host');
}
await this.installOpenChamberManaged(parsed, controlPath, this.appVersion, instance.remoteOpenchamber.installMethod);
const afterInstall = await this.remoteOpenChamberCandidates(parsed, controlPath);
binary = afterInstall.find((candidate) => candidate.version === this.appVersion) || afterInstall[0] || existing;
if (!binary) {
throw new Error('OpenChamber was installed on the remote host but no openchamber binary could be found');
}
}
this.setStatus(instance.id, 'server_detecting', 'Detecting managed OpenChamber server');
@@ -1172,13 +1253,13 @@ export class ElectronSshManager {
if (!remotePort) {
this.setStatus(instance.id, 'server_starting', 'Starting managed OpenChamber server');
const desiredPort = instance.remoteOpenchamber.preferredPort || randomPortCandidate(instance.id);
remotePort = await this.startRemoteServerManaged(parsed, controlPath, instance, desiredPort);
remotePort = await this.startRemoteServerManaged(parsed, controlPath, instance, desiredPort, binary.binPath);
startedByUs = true;
}
if (!(await this.remoteServerRunning(parsed, controlPath, remotePort, this.configuredOpenChamberPassword(instance)))) {
throw new Error('Managed OpenChamber server failed to become reachable');
}
return { remotePort, startedByUs };
return { remotePort, startedByUs, remoteBinPath: binary.binPath };
}
async disconnectInternal(id, reportIdle) {
@@ -1193,7 +1274,7 @@ export class ElectronSshManager {
if (session) {
if (session.startedByUs && session.remotePort && session.instance.remoteOpenchamber.mode === 'managed' && !session.instance.remoteOpenchamber.keepRunning) {
await this.stopRemoteServerBestEffort(session.parsed, session.controlPath, session.remotePort);
await this.stopRemoteServerBestEffort(session.parsed, session.controlPath, session.remotePort, session.remoteBinPath);
}
await this.stopControlMasterBestEffort(session.parsed, session.controlPath);
const auth = this.sshAuth.get(session.parsed);
@@ -1269,9 +1350,10 @@ export class ElectronSshManager {
throw new Error(`Unsupported remote OS: ${remoteOs}`);
}
const { remotePort, startedByUs } = await this.ensureRemoteServer(instance, parsed, controlPath);
const { remotePort, startedByUs, remoteBinPath } = await this.ensureRemoteServer(instance, parsed, controlPath);
session.remotePort = remotePort;
session.startedByUs = startedByUs;
session.remoteBinPath = remoteBinPath;
this.setStatus(id, 'forwarding', 'Setting up port forwards', null, null, remotePort, startedByUs, 0, false);
const bindHost = sanitizeBindHost(instance.localForward?.bindHost);
+157
View File
@@ -289,4 +289,161 @@ describe('ElectronSshManager', () => {
});
expect(settings.desktopHosts).toEqual([{ id: 'ssh-1', label: 'SSH Host', url: localUrl, apiUrl: localUrl, clientToken: 'ssh-client-token' }]);
});
test('installs OpenChamber into a home-owned npm prefix instead of the root-owned global one', async () => {
const commands = [];
const manager = new ElectronSshManager({
settingsFilePath: path.join(os.tmpdir(), 'unused-settings.json'),
appVersion: '1.2.3',
emit: () => undefined,
});
manager.resolveRemoteTool = async (_parsed, _controlPath, name) => (name === 'npm' ? '/usr/bin/npm' : null);
manager.runRemoteCommand = async (_parsed, _controlPath, script) => {
commands.push(script);
return '';
};
await manager.installOpenChamberManaged({ destination: 'user@example.test', args: [] }, '/tmp/control.sock', '1.2.3', 'auto');
expect(commands).toHaveLength(1);
expect(commands[0]).toContain('--prefix "$HOME/.openchamber/npm-global"');
expect(commands[0]).not.toMatch(/npm install -g @openchamber/);
});
test('lists every remote OpenChamber binary with its reported version', async () => {
const manager = new ElectronSshManager({
settingsFilePath: path.join(os.tmpdir(), 'unused-settings.json'),
appVersion: '1.2.3',
emit: () => undefined,
});
manager.runRemoteCommand = async () => [
'/home/pi/.openchamber/npm-global/bin/openchamber\t1.2.3',
'/usr/bin/openchamber\t0.9.0',
'',
].join('\n');
const candidates = await manager.remoteOpenChamberCandidates({ destination: 'user@example.test', args: [] }, '/tmp/control.sock');
expect(candidates).toEqual([
{ binPath: '/home/pi/.openchamber/npm-global/bin/openchamber', version: '1.2.3' },
{ binPath: '/usr/bin/openchamber', version: '0.9.0' },
]);
});
test('starts the resolved OpenChamber binary rather than whatever PATH exposes', async () => {
let started = '';
const manager = new ElectronSshManager({
settingsFilePath: path.join(os.tmpdir(), 'unused-settings.json'),
appVersion: '1.2.3',
emit: () => undefined,
});
manager.resolveRemoteTool = async () => '/home/pi/.opencode/bin/opencode';
manager.runRemoteCommand = async (_parsed, _controlPath, script) => {
started = script;
return '4321\n';
};
const instance = { id: 'ssh-1', auth: {}, remoteOpenchamber: { mode: 'managed' } };
const port = await manager.startRemoteServerManaged(
{ destination: 'user@example.test', args: [] },
'/tmp/control.sock',
instance,
4321,
'/home/pi/.openchamber/npm-global/bin/openchamber',
);
expect(port).toBe(4321);
expect(started).toContain("'/home/pi/.openchamber/npm-global/bin/openchamber' serve");
expect(started).toContain("OPENCODE_BINARY='/home/pi/.opencode/bin/opencode'");
expect(started).toContain('$HOME/.opencode/bin:');
});
test('refuses to start when the remote machine has no opencode CLI', async () => {
const manager = new ElectronSshManager({
settingsFilePath: path.join(os.tmpdir(), 'unused-settings.json'),
appVersion: '1.2.3',
emit: () => undefined,
});
manager.resolveRemoteTool = async () => null;
manager.runRemoteCommand = async () => {
throw new Error('should not start the server without a CLI');
};
await expect(manager.startRemoteServerManaged(
{ destination: 'user@example.test', args: [] },
'/tmp/control.sock',
{ id: 'ssh-1', auth: {}, remoteOpenchamber: { mode: 'managed' } },
4321,
'/home/pi/.bun/bin/openchamber',
)).rejects.toThrow(/opencode CLI is not installed/);
});
test('prefers a bun that only exists in the home directory over npm', async () => {
const commands = [];
const manager = new ElectronSshManager({
settingsFilePath: path.join(os.tmpdir(), 'unused-settings.json'),
appVersion: '1.2.3',
emit: () => undefined,
});
// A login shell over SSH does not put ~/.bun/bin on PATH.
manager.resolveRemoteTool = async (_parsed, _controlPath, name) =>
(name === 'bun' ? '/home/pi/.bun/bin/bun' : '/usr/bin/npm');
manager.runRemoteCommand = async (_parsed, _controlPath, script) => {
commands.push(script);
return '';
};
await manager.installOpenChamberManaged({ destination: 'user@example.test', args: [] }, '/tmp/control.sock', '1.2.3', 'auto');
expect(commands).toEqual(["'/home/pi/.bun/bin/bun' add -g @openchamber/web@1.2.3"]);
});
test('stops a remote server it started through the CLI, not the authenticated HTTP route', async () => {
const scripts = [];
const manager = new ElectronSshManager({
settingsFilePath: path.join(os.tmpdir(), 'unused-settings.json'),
appVersion: '1.2.3',
emit: () => undefined,
});
manager.runRemoteCommand = async (_parsed, _controlPath, script) => {
scripts.push(script);
return '';
};
await manager.stopRemoteServerBestEffort(
{ destination: 'user@example.test', args: [] },
'/tmp/control.sock',
41777,
'/home/pi/.bun/bin/openchamber',
);
expect(scripts).toEqual(["'/home/pi/.bun/bin/openchamber' stop --port 41777"]);
});
test('publishes the remote server to its network only with a UI password', async () => {
const manager = new ElectronSshManager({
settingsFilePath: path.join(os.tmpdir(), 'unused-settings.json'),
appVersion: '1.2.3',
emit: () => undefined,
});
manager.resolveRemoteTool = async () => '/home/pi/.opencode/bin/opencode';
let started = '';
manager.runRemoteCommand = async (_parsed, _controlPath, script) => {
started = script;
return '4321\n';
};
const parsed = { destination: 'user@example.test', args: [] };
const exposed = {
id: 'ssh-1',
auth: {},
remoteOpenchamber: { mode: 'managed', bindHost: '0.0.0.0' },
};
await expect(manager.startRemoteServerManaged(parsed, '/tmp/control.sock', exposed, 4321, '/bin/openchamber'))
.rejects.toThrow(/requires a UI password/);
const secured = {
...exposed,
auth: { openchamberPassword: { enabled: true, value: 'remote-secret', store: 'settings' } },
};
await manager.startRemoteServerManaged(parsed, '/tmp/control.sock', secured, 4321, '/bin/openchamber');
expect(started).toContain('--hostname 0.0.0.0');
});
});