Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/web-ui/src/features/ssh-remote/PortForwardDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
/**
* Remote Port Forwarding Dialog
*
* Manual mappings only: a forward exists because the user asked for it.
* A forward exists because the user asked for it: either here, or by
* Ctrl/Cmd+clicking a loopback link in a remote terminal (`openTerminalLink`),
* which lands in the same list. Nothing is forwarded in the background.
*
* Detection runs on open, though — knowing what the remote is listening on is
* not the same as forwarding it, and making people type a port number they
Expand Down
62 changes: 62 additions & 0 deletions src/web-ui/src/features/ssh-remote/loopbackLink.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest';
import { parseLoopbackLink, rewriteLoopbackLink, sameRemoteHost } from './loopbackLink';

describe('parseLoopbackLink', () => {
it.each([
['http://127.0.0.1:5173/', 5173, '127.0.0.1'],
['http://localhost:3000/app', 3000, 'localhost'],
['http://localhost.:3000/app', 3000, 'localhost'],
['https://0.0.0.0:8443', 8443, '127.0.0.1'],
['http://[::1]:8080/x', 8080, '::1'],
['http://app.localhost:4000', 4000, 'localhost'],
['http://127.1.2.3:9000', 9000, '127.1.2.3'],
])('recognizes %s', (uri, port, remoteHost) => {
const link = parseLoopbackLink(uri);
expect(link?.remotePort).toBe(port);
expect(link?.remoteHost).toBe(remoteHost);
});

it.each(['http://localhost/', 'http://127.0.0.1:80/', 'https://localhost./'])(
'recognizes %s without an explicit port',
(uri) => {
const link = parseLoopbackLink(uri);
expect(link).not.toBeNull();
expect(link?.remotePort).toBeNull();
},
);

it.each([
'https://example.com:3000',
'ftp://127.0.0.1:21',
'http://10.0.0.1:3000',
'not a url',
])('ignores %s', (uri) => {
expect(parseLoopbackLink(uri)).toBeNull();
});
});

describe('rewriteLoopbackLink', () => {
it('always uses the bound address, keeping path, query and hash', () => {
const link = parseLoopbackLink('http://localhost:5173/a/b?x=1#frag')!;
expect(rewriteLoopbackLink(link, '127.0.0.1', 5174)).toBe('http://127.0.0.1:5174/a/b?x=1#frag');
const sub = parseLoopbackLink('http://app.localhost:5173/')!;
expect(rewriteLoopbackLink(sub, '127.0.0.1', 5173)).toBe('http://127.0.0.1:5173/');
});

it('maps other loopback spellings to the bound address', () => {
const link = parseLoopbackLink('http://0.0.0.0:3000/p')!;
expect(rewriteLoopbackLink(link, '127.0.0.1', 3000)).toBe('http://127.0.0.1:3000/p');
const v6 = parseLoopbackLink('http://[::1]:3000/')!;
expect(rewriteLoopbackLink(v6, '0.0.0.0', 40001)).toBe('http://127.0.0.1:40001/');
});
});

describe('sameRemoteHost', () => {
it('matches exactly or localhost with 127.0.0.1 only', () => {
expect(sameRemoteHost('127.0.0.1', 'localhost')).toBe(true);
expect(sameRemoteHost('127.1.2.3', '127.1.2.3')).toBe(true);
expect(sameRemoteHost('[::1]', '::1')).toBe(true);
expect(sameRemoteHost('127.0.0.1', '::1')).toBe(false);
expect(sameRemoteHost('127.0.0.1', '127.1.2.3')).toBe(false);
});
});
88 changes: 88 additions & 0 deletions src/web-ui/src/features/ssh-remote/loopbackLink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* Loopback link detection and rewriting for remote terminals.
*
* A dev server running on an SSH host prints `http://127.0.0.1:5173`. That
* address names the remote machine, not this one, so opening it verbatim hits
* whatever happens to listen locally. These helpers recognize such links and
* rewrite them onto a local forward. They are pure: no IO, no forwarding.
*/

export interface LoopbackLink {
/** Parsed link. */
url: URL;
/**
* Port the service listens on, as seen from the remote host. `null` when the
* link carries no explicit port: it still names the remote machine, but there
* is no dev-server port worth forwarding.
*/
remotePort: number | null;
/** Host the forward should dial on the remote side. */
remoteHost: string;
}

/** Lower-case, drop a trailing root dot (`localhost.`) and IPv6 brackets. */
function canonicalHost(hostname: string): string {
let host = hostname.toLowerCase();
if (host.endsWith('.')) host = host.slice(0, -1);
if (host.startsWith('[') && host.endsWith(']')) host = host.slice(1, -1);
return host;
}

function isLoopbackHostname(host: string): boolean {
if (host === 'localhost' || host.endsWith('.localhost')) return true;
if (host === '0.0.0.0' || host === '::1') return true;
return /^127(?:\.\d{1,3}){3}$/.test(host);
}

/** Map the link host to the address the forward should dial remotely. */
function remoteDialHost(host: string): string {
if (host === '0.0.0.0') return '127.0.0.1';
if (host === 'localhost' || host.endsWith('.localhost')) return 'localhost';
return host;
}

/** Recognize an http(s) link whose host is a loopback address. */
export function parseLoopbackLink(uri: string): LoopbackLink | null {
let url: URL;
try {
url = new URL(uri);
} catch {
return null;
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
const host = canonicalHost(url.hostname);
if (!isLoopbackHostname(host)) return null;
let remotePort: number | null = null;
if (url.port) {
const port = Number(url.port);
if (!Number.isInteger(port) || port <= 0 || port > 65535) return null;
remotePort = port;
}
return { url, remotePort, remoteHost: remoteDialHost(host) };
}

/** Remote hosts that name the same service: exact, plus `localhost` <-> `127.0.0.1`. */
export function sameRemoteHost(left: string, right: string): boolean {
const a = canonicalHost(left);
const b = canonicalHost(right);
if (a === b) return true;
const ipv4Localhost = new Set(['localhost', '127.0.0.1']);
return ipv4Localhost.has(a) && ipv4Localhost.has(b);
}

/**
* Point a loopback link at a local forward, keeping path, query and hash.
*
* The host is always replaced with the forward's bound address. Keeping a
* `localhost` name would let the browser try `::1` first and reach a local
* server on the same port, which is the bug this rewrite exists to avoid.
*/
export function rewriteLoopbackLink(link: LoopbackLink, localHost: string, localPort: number): string {
const url = new URL(link.url.href);
let bound = canonicalHost(localHost || '127.0.0.1');
if (bound === '0.0.0.0') bound = '127.0.0.1';
if (bound === '::') bound = '::1';
url.hostname = bound.includes(':') ? `[${bound}]` : bound;
url.port = String(localPort);
return url.href;
}
182 changes: 182 additions & 0 deletions src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { describe, expect, it, vi } from 'vitest';
import { openTerminalLink, type TerminalLinkDeps } from './openTerminalLink';
import type { PortForward, SavedConnection } from './types';

function forward(overrides: Partial<PortForward> = {}): PortForward {
return {
id: 'f1',
connectionId: 'conn',
direction: 'local',
localHost: '127.0.0.1',
localPort: 5173,
remoteHost: '127.0.0.1',
remotePort: 5173,
activeConnections: 0,
totalConnections: 0,
...overrides,
};
}

function saved(overrides: Partial<SavedConnection>): SavedConnection {
return {
id: 'conn',
name: 'c',
host: 'h',
port: 22,
username: 'u',
authType: { type: 'Agent' },
...overrides,
};
}

function deps(overrides: Partial<TerminalLinkDeps> = {}) {
return {
listSavedConnections: vi.fn(async () => [saved({})]),
listPortForwards: vi.fn(async () => [] as PortForward[]),
startPortForward: vi.fn(async () => forward()),
stopPortForward: vi.fn(async () => {}),
openExternal: vi.fn(async () => {}),
isPeerDeviceModeActive: vi.fn(() => false),
notifyInfo: vi.fn(),
notifyWarning: vi.fn(),
t: vi.fn((key: string) => key),
...overrides,
};
}

const ssh = { connectionId: 'conn' };

describe('openTerminalLink', () => {
it('opens links unchanged for local terminals', async () => {
const d = deps();
await expect(openTerminalLink('http://127.0.0.1:5173/', {}, d)).resolves.toBe('opened');
expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:5173/');
expect(d.listPortForwards).not.toHaveBeenCalled();
});

it('opens non-loopback links unchanged for remote terminals', async () => {
const d = deps();
await openTerminalLink('https://example.com/', ssh, d);
expect(d.openExternal).toHaveBeenCalledWith('https://example.com/');
expect(d.listPortForwards).not.toHaveBeenCalled();
});

it.each([
['WSL', saved({ wsl: { distribution: 'Ubuntu' } })],
['local Docker', saved({
container: { name: 'c', access: 'docker-exec', local: true, dockerPath: 'docker', shell: '/bin/sh', interactive: true },
})],
])('opens links unchanged for %s targets without forwarding', async (_name, connection) => {
const d = deps({ listSavedConnections: vi.fn(async () => [connection]) });
await expect(openTerminalLink('http://localhost:3000/', ssh, d)).resolves.toBe('opened-local-target');
expect(d.openExternal).toHaveBeenCalledWith('http://localhost:3000/');
expect(d.listPortForwards).not.toHaveBeenCalled();
expect(d.startPortForward).not.toHaveBeenCalled();
});

it('reuses an existing forward without notifying and rewrites to the bound address', async () => {
const d = deps({ listPortForwards: vi.fn(async () => [forward({ localPort: 40000 })]) });
await expect(openTerminalLink('http://localhost:5173/a?b=1', ssh, d)).resolves.toBe('forward-reused');
expect(d.startPortForward).not.toHaveBeenCalled();
expect(d.notifyInfo).not.toHaveBeenCalled();
expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:40000/a?b=1');
});

it('reuses a forward for a non-default 127.x remote host on a second click', async () => {
const d = deps({
listPortForwards: vi.fn(async () => [forward({ remoteHost: '127.1.2.3', localPort: 9001 })]),
});
await expect(openTerminalLink('http://127.1.2.3:5173/', ssh, d)).resolves.toBe('forward-reused');
expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:9001/');
});

it('does not reuse a 127.0.0.1 forward for an [::1] link', async () => {
const d = deps({
listPortForwards: vi.fn(async () => [forward({ localPort: 40000 })]),
startPortForward: vi.fn(async () => forward({ remoteHost: '::1', localPort: 5173 })),
});
await expect(openTerminalLink('http://[::1]:5173/', ssh, d)).resolves.toBe('forward-created');
expect(d.startPortForward).toHaveBeenCalledWith(expect.objectContaining({ remoteHost: '::1' }));
});

it('restarts an idle forward that recorded an error, keeping its local port', async () => {
const d = deps({
listPortForwards: vi.fn(async () => [forward({ localPort: 40000, lastError: 'SSH connection is not active' })]),
startPortForward: vi.fn(async () => forward({ id: 'f2', localPort: 40000 })),
});
await expect(openTerminalLink('http://127.0.0.1:5173/', ssh, d)).resolves.toBe('forward-created');
expect(d.stopPortForward).toHaveBeenCalledWith('f1');
expect(d.startPortForward).toHaveBeenCalledWith(expect.objectContaining({ localPort: 40000 }));
});

it('starts a forward preferring the same local port and announces the mapping', async () => {
const d = deps({ startPortForward: vi.fn(async () => forward({ localPort: 5174 })) });
await expect(openTerminalLink('http://127.0.0.1:5173/', ssh, d)).resolves.toBe('forward-created');
expect(d.startPortForward).toHaveBeenCalledWith(
expect.objectContaining({ connectionId: 'conn', remotePort: 5173, remoteHost: '127.0.0.1', localPort: 5173 }),
);
expect(d.notifyInfo).toHaveBeenCalledTimes(1);
expect(d.t).toHaveBeenCalledWith('linkForward.created', { remotePort: 5173, localAddress: '127.0.0.1:5174' });
expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:5174/');
});

it('warns and does not open the local URL when forwarding fails', async () => {
const d = deps({
startPortForward: vi.fn(async () => {
throw new Error('bind failed');
}),
});
await expect(openTerminalLink('http://127.0.0.1:3000/', ssh, d)).resolves.toBe('forward-failed');
expect(d.openExternal).not.toHaveBeenCalled();
expect(d.notifyWarning).toHaveBeenCalledTimes(1);
expect(d.t).toHaveBeenCalledWith('linkForward.failed', { port: 3000, error: 'bind failed' });
d.notifyWarning.mock.calls[0][1]?.onClick();
expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:3000/');
});

it('reports the original start error when the fallback re-list throws', async () => {
const list = vi
.fn<() => Promise<PortForward[]>>()
.mockResolvedValueOnce([])
.mockRejectedValueOnce(new Error('list failed'));
const d = deps({
listPortForwards: list,
startPortForward: vi.fn(async () => {
throw new Error('start failed');
}),
});
await expect(openTerminalLink('http://127.0.0.1:3000/', ssh, d)).resolves.toBe('forward-failed');
expect(d.t).toHaveBeenCalledWith('linkForward.failed', { port: 3000, error: 'start failed' });
});

it('treats a lost start race as reuse with no toast', async () => {
const list = vi
.fn<() => Promise<PortForward[]>>()
.mockResolvedValueOnce([])
.mockResolvedValueOnce([forward({ localPort: 41000 })]);
const d = deps({
listPortForwards: list,
startPortForward: vi.fn(async () => {
throw new Error('already forwarded');
}),
});
await expect(openTerminalLink('http://127.0.0.1:5173/', ssh, d)).resolves.toBe('forward-reused');
expect(d.notifyInfo).not.toHaveBeenCalled();
expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:41000/');
});

it('warns about a port-less loopback link instead of opening it locally', async () => {
const d = deps();
await expect(openTerminalLink('http://localhost./', ssh, d)).resolves.toBe('no-port');
expect(d.openExternal).not.toHaveBeenCalled();
expect(d.notifyWarning).toHaveBeenCalledWith('linkForward.noPort', expect.any(Object));
});

it('refuses to forward in Peer Device Mode', async () => {
const d = deps({ isPeerDeviceModeActive: vi.fn(() => true) });
await expect(openTerminalLink('http://127.0.0.1:5173/', ssh, d)).resolves.toBe('peer-unsupported');
expect(d.listPortForwards).not.toHaveBeenCalled();
expect(d.openExternal).not.toHaveBeenCalled();
expect(d.notifyWarning).toHaveBeenCalledWith('linkForward.peerUnsupported', expect.any(Object));
});
});
Loading
Loading