fix: restore desktop remote authentication
Fixes switching and unlocking password-protected remote instances Stores SSH forwarded host client tokens from saved UI passwords Avoids unnecessary auth churn when no runtime headers are configured
This commit is contained in:
@@ -1517,9 +1517,10 @@ const extractCookieHeader = (response) => {
|
||||
.join('; ');
|
||||
};
|
||||
|
||||
const loginRemoteAndIssueClientToken = async ({ url, password, trustDevice }) => {
|
||||
const loginRemoteAndIssueClientToken = async ({ url, password, trustDevice, requestHeaders }) => {
|
||||
const baseUrl = normalizeHostUrl(String(url || ''));
|
||||
const candidatePassword = typeof password === 'string' ? password : '';
|
||||
const safeRequestHeaders = sanitizeRuntimeRequestHeaders(requestHeaders || {});
|
||||
if (!baseUrl) throw new Error('Invalid URL');
|
||||
if (!candidatePassword) throw new Error('Password is required');
|
||||
|
||||
@@ -1527,6 +1528,7 @@ const loginRemoteAndIssueClientToken = async ({ url, password, trustDevice }) =>
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: {
|
||||
...safeRequestHeaders,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
@@ -1559,6 +1561,7 @@ const loginRemoteAndIssueClientToken = async ({ url, password, trustDevice }) =>
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: {
|
||||
...safeRequestHeaders,
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: cookie,
|
||||
@@ -3506,6 +3509,7 @@ const handleInvoke = async (browserWindow, command, args = {}) => {
|
||||
url: args.url,
|
||||
password: args.password,
|
||||
trustDevice: args.trustDevice === true,
|
||||
requestHeaders: args.requestHeaders || {},
|
||||
});
|
||||
|
||||
case 'desktop_set_window_theme': {
|
||||
|
||||
@@ -700,19 +700,84 @@ export class ElectronSshManager {
|
||||
}
|
||||
|
||||
async updateHostUrl(instanceId, label, localUrl) {
|
||||
return this.updateHostRuntime(instanceId, label, localUrl, '');
|
||||
}
|
||||
|
||||
async updateHostRuntime(instanceId, label, localUrl, clientToken = '') {
|
||||
const root = readJsonRoot(this.settingsFilePath);
|
||||
const hosts = Array.isArray(root.desktopHosts) ? root.desktopHosts : [];
|
||||
const existing = hosts.find((entry) => entry?.id === instanceId);
|
||||
const token = typeof clientToken === 'string' ? clientToken.trim() : '';
|
||||
if (existing) {
|
||||
existing.label = label;
|
||||
existing.url = localUrl;
|
||||
existing.apiUrl = localUrl;
|
||||
if (token) existing.clientToken = token;
|
||||
} else {
|
||||
hosts.push({ id: instanceId, label, url: localUrl });
|
||||
hosts.push({ id: instanceId, label, url: localUrl, apiUrl: localUrl, ...(token ? { clientToken: token } : {}) });
|
||||
}
|
||||
root.desktopHosts = hosts;
|
||||
await writeJsonRoot(this.settingsFilePath, root);
|
||||
}
|
||||
|
||||
async issueClientToken(localUrl, openchamberPassword) {
|
||||
const password = typeof openchamberPassword === 'string' ? openchamberPassword.trim() : '';
|
||||
if (!password) return '';
|
||||
|
||||
const loginResponse = await fetch(new URL('/auth/session', `${localUrl}/`).toString(), {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
password,
|
||||
trustDevice: true,
|
||||
issueClientToken: true,
|
||||
clientLabel: 'OpenChamber Desktop SSH',
|
||||
}),
|
||||
});
|
||||
if (!loginResponse.ok) {
|
||||
throw new Error(`Configured OpenChamber UI password was rejected by forwarded server (status ${loginResponse.status})`);
|
||||
}
|
||||
|
||||
const payload = await loginResponse.json().catch(() => null);
|
||||
const token = typeof payload?.clientToken === 'string' ? payload.clientToken.trim() : '';
|
||||
if (token) return token;
|
||||
|
||||
const cookie = this.extractCookieHeader(loginResponse);
|
||||
if (!cookie) return '';
|
||||
|
||||
const tokenResponse = await fetch(new URL('/api/client-auth/clients', `${localUrl}/`).toString(), {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: cookie,
|
||||
},
|
||||
body: JSON.stringify({ label: 'OpenChamber Desktop SSH' }),
|
||||
});
|
||||
if (!tokenResponse.ok) return '';
|
||||
const tokenPayload = await tokenResponse.json().catch(() => null);
|
||||
return typeof tokenPayload?.token === 'string' ? tokenPayload.token.trim() : '';
|
||||
}
|
||||
|
||||
extractCookieHeader(response) {
|
||||
const getSetCookie = typeof response.headers?.getSetCookie === 'function'
|
||||
? response.headers.getSetCookie.bind(response.headers)
|
||||
: null;
|
||||
const cookies = getSetCookie ? getSetCookie() : [];
|
||||
const rawCookies = cookies.length > 0
|
||||
? cookies
|
||||
: String(response.headers?.get?.('set-cookie') || '').split(/,(?=\s*[^;,=]+=[^;,]+)/);
|
||||
return rawCookies
|
||||
.map((cookie) => String(cookie || '').split(';')[0].trim())
|
||||
.filter(Boolean)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
async persistLocalPort(instanceId, localPort) {
|
||||
const root = readJsonRoot(this.settingsFilePath);
|
||||
const instances = Array.isArray(root.desktopSshInstances) ? root.desktopSshInstances : [];
|
||||
@@ -1090,7 +1155,8 @@ export class ElectronSshManager {
|
||||
|
||||
const localUrl = `http://127.0.0.1:${localPort}`;
|
||||
const label = instance.nickname?.trim() || parsed.destination || id;
|
||||
await this.updateHostUrl(id, label, localUrl);
|
||||
const clientToken = await this.issueClientToken(localUrl, this.configuredOpenChamberPassword(instance));
|
||||
await this.updateHostRuntime(id, label, localUrl, clientToken);
|
||||
if (instance.localForward?.preferredLocalPort !== localPort) {
|
||||
await this.persistLocalPort(id, localPort);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { ElectronSshManager } from './ssh-manager.mjs';
|
||||
|
||||
const servers = [];
|
||||
const tempDirs = [];
|
||||
|
||||
const listen = async (server) => {
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
servers.push(server);
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') throw new Error('Expected TCP server address');
|
||||
return `http://127.0.0.1:${address.port}`;
|
||||
};
|
||||
|
||||
const readBody = async (req) => {
|
||||
let body = '';
|
||||
for await (const chunk of req) body += chunk.toString();
|
||||
return body;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
while (servers.length > 0) {
|
||||
const server = servers.pop();
|
||||
await new Promise((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
while (tempDirs.length > 0) {
|
||||
await fsp.rm(tempDirs.pop(), { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('ElectronSshManager', () => {
|
||||
test('stores a client token for forwarded OpenChamber hosts when UI password is configured', async () => {
|
||||
let loginPayload = null;
|
||||
const server = http.createServer(async (req, res) => {
|
||||
if (req.method === 'POST' && req.url === '/auth/session') {
|
||||
loginPayload = JSON.parse(await readBody(req));
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ authenticated: true, clientToken: 'ssh-client-token' }));
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
});
|
||||
const localUrl = await listen(server);
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-ssh-manager-test-'));
|
||||
tempDirs.push(tempDir);
|
||||
const settingsFilePath = path.join(tempDir, 'settings.json');
|
||||
const manager = new ElectronSshManager({
|
||||
settingsFilePath,
|
||||
appVersion: '0.0.0-test',
|
||||
emit: () => undefined,
|
||||
});
|
||||
|
||||
const token = await manager.issueClientToken(localUrl, 'ui-secret');
|
||||
await manager.updateHostRuntime('ssh-1', 'SSH Host', localUrl, token);
|
||||
|
||||
const settings = JSON.parse(fs.readFileSync(settingsFilePath, 'utf8'));
|
||||
expect(loginPayload).toMatchObject({
|
||||
password: 'ui-secret',
|
||||
trustDevice: true,
|
||||
issueClientToken: true,
|
||||
});
|
||||
expect(settings.desktopHosts).toEqual([{ id: 'ssh-1', label: 'SSH Host', url: localUrl, apiUrl: localUrl, clientToken: 'ssh-client-token' }]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user