diff --git a/src/web-ui/src/features/ssh-remote/PortForwardDialog.tsx b/src/web-ui/src/features/ssh-remote/PortForwardDialog.tsx index 5268331abc..656e7a8115 100644 --- a/src/web-ui/src/features/ssh-remote/PortForwardDialog.tsx +++ b/src/web-ui/src/features/ssh-remote/PortForwardDialog.tsx @@ -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 diff --git a/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts b/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts new file mode 100644 index 0000000000..b8f57fe8cb --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts @@ -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); + }); +}); diff --git a/src/web-ui/src/features/ssh-remote/loopbackLink.ts b/src/web-ui/src/features/ssh-remote/loopbackLink.ts new file mode 100644 index 0000000000..6705101877 --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/loopbackLink.ts @@ -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; +} diff --git a/src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts b/src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts new file mode 100644 index 0000000000..6a680a6330 --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts @@ -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 { + 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 { + return { + id: 'conn', + name: 'c', + host: 'h', + port: 22, + username: 'u', + authType: { type: 'Agent' }, + ...overrides, + }; +} + +function deps(overrides: Partial = {}) { + 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>() + .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>() + .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)); + }); +}); diff --git a/src/web-ui/src/features/ssh-remote/openTerminalLink.ts b/src/web-ui/src/features/ssh-remote/openTerminalLink.ts new file mode 100644 index 0000000000..0731471856 --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/openTerminalLink.ts @@ -0,0 +1,186 @@ +/** + * Open a link clicked in a terminal, forwarding loopback ports for SSH terminals. + * + * A click is an explicit user action, so a forward is created without a + * confirmation prompt. When forwarding cannot happen (Peer Device Mode, a + * port-less link, a failed bind) the user is told why and the local URL is + * never opened silently; an "open anyway" action keeps the escape hatch. + * + * WSL and local Docker terminals also carry a connection id, but they run on + * this machine (WSL2 forwards localhost by default), have no SSH channel to + * forward over, and so open links unchanged. + */ + +import { parseLoopbackLink, rewriteLoopbackLink, sameRemoteHost, type LoopbackLink } from './loopbackLink'; +import type { PortForward, PortForwardRequest, SavedConnection } from './types'; + +export interface TerminalLinkContext { + /** Connection that owns the terminal's PTY; absent for local terminals. */ + connectionId?: string; +} + +export interface TerminalLinkNotice { + label: string; + onClick: () => void; +} + +export interface TerminalLinkDeps { + listSavedConnections: () => Promise; + listPortForwards: (connectionId: string) => Promise; + startPortForward: (request: PortForwardRequest) => Promise; + stopPortForward: (forwardId: string) => Promise; + openExternal: (url: string) => Promise; + isPeerDeviceModeActive: () => boolean; + notifyInfo: (message: string) => void; + notifyWarning: (message: string, action?: TerminalLinkNotice) => void; + t: (key: string, params?: Record) => string; + logError?: (message: string, data: Record) => void; +} + +export type TerminalLinkOutcome = + | 'opened' + | 'opened-local-target' + | 'forward-reused' + | 'forward-created' + | 'no-port' + | 'peer-unsupported' + | 'forward-failed'; + +/** WSL and local Docker targets run on this machine; nothing to forward. */ +export function isLocalProcessConnection(connection: SavedConnection | undefined): boolean { + return Boolean(connection && (connection.wsl || connection.container?.local)); +} + +function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message; + return typeof error === 'string' ? error : String(error); +} + +function findForward( + forwards: PortForward[], + remoteHost: string, + remotePort: number, +): PortForward | undefined { + const candidates = forwards.filter( + forward => forward.direction === 'local' && forward.remotePort === remotePort, + ); + return ( + candidates.find(forward => forward.remoteHost.toLowerCase() === remoteHost) ?? + candidates.find(forward => sameRemoteHost(forward.remoteHost, remoteHost)) + ); +} + +async function resolvesToLocalProcess(connectionId: string, deps: TerminalLinkDeps): Promise { + try { + const saved = await deps.listSavedConnections(); + return isLocalProcessConnection(saved.find(connection => connection.id === connectionId)); + } catch (error) { + // Unknown target: try forwarding; the backend rejects local targets loudly. + deps.logError?.('Failed to resolve terminal connection target', { connectionId, error }); + return false; + } +} + +export async function openTerminalLink( + uri: string, + context: TerminalLinkContext, + deps: TerminalLinkDeps, +): Promise { + const connectionId = context.connectionId?.trim(); + const link = connectionId ? parseLoopbackLink(uri) : null; + + if (!connectionId || !link) { + await deps.openExternal(uri); + return 'opened'; + } + + const openAnyway: TerminalLinkNotice = { + label: deps.t('linkForward.openAnyway'), + onClick: () => { + void deps.openExternal(uri).catch(error => { + deps.logError?.('Failed to open external link', { uri, error }); + }); + }, + }; + + // The forward would bind on the peer host, not on this controller. + if (deps.isPeerDeviceModeActive()) { + deps.notifyWarning(deps.t('linkForward.peerUnsupported'), openAnyway); + return 'peer-unsupported'; + } + + if (await resolvesToLocalProcess(connectionId, deps)) { + await deps.openExternal(uri); + return 'opened-local-target'; + } + + if (link.remotePort === null) { + deps.notifyWarning(deps.t('linkForward.noPort'), openAnyway); + return 'no-port'; + } + + const remotePort = link.remotePort; + let forward: PortForward; + let outcome: TerminalLinkOutcome; + try { + ({ forward, outcome } = await ensureForward(connectionId, link, remotePort, deps)); + } catch (error) { + deps.logError?.('Failed to forward terminal link', { connectionId, remotePort, error }); + deps.notifyWarning( + deps.t('linkForward.failed', { port: remotePort, error: errorMessage(error) }), + openAnyway, + ); + return 'forward-failed'; + } + + if (outcome === 'forward-created') { + deps.notifyInfo( + deps.t('linkForward.created', { + remotePort, + localAddress: `${forward.localHost}:${forward.localPort}`, + }), + ); + } + await deps.openExternal(rewriteLoopbackLink(link, forward.localHost, forward.localPort)); + return outcome; +} + +async function ensureForward( + connectionId: string, + link: LoopbackLink, + remotePort: number, + deps: TerminalLinkDeps, +): Promise<{ forward: PortForward; outcome: 'forward-reused' | 'forward-created' }> { + const existing = findForward(await deps.listPortForwards(connectionId), link.remoteHost, remotePort); + if (existing && (!existing.lastError || existing.activeConnections > 0)) { + return { forward: existing, outcome: 'forward-reused' }; + } + if (existing) { + // The forward reported a failure and carries no traffic. Starting again + // reconnects the SSH session if needed; keep its local port and exposure. + await deps.stopPortForward(existing.id); + } + + const request: PortForwardRequest = { + connectionId, + remotePort, + remoteHost: link.remoteHost, + // Prefer the same port locally; the backend binds another if it is taken. + localPort: existing?.localPort ?? remotePort, + exposeOnLan: existing?.localHost === '0.0.0.0' ? true : undefined, + label: existing?.label ?? deps.t('linkForward.label'), + }; + try { + return { forward: await deps.startPortForward(request), outcome: 'forward-created' }; + } catch (startError) { + // A concurrent click may have created the same forward first. + let raced: PortForward | undefined; + try { + raced = findForward(await deps.listPortForwards(connectionId), link.remoteHost, remotePort); + } catch { + throw startError; + } + if (!raced) throw startError; + return { forward: raced, outcome: 'forward-reused' }; + } +} diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index 788c74fb83..d648137477 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -2067,7 +2067,7 @@ "portForward": { "menuEntry": "Forward a Port", "title": "Port Forwarding", - "intro": "Reach a port listening on the remote host from this machine. Nothing is forwarded automatically — only the mappings you add here.", + "intro": "Reach a port listening on the remote host from this machine. Forwards are created only when you add one here or open a localhost link from a remote terminal.", "detectedTitle": "Listening on the remote", "detecting": "Detecting remote ports…", "detect": "Detect again", diff --git a/src/web-ui/src/locales/en-US/panels/terminal.json b/src/web-ui/src/locales/en-US/panels/terminal.json index 3f2e2f4617..09df9f5057 100644 --- a/src/web-ui/src/locales/en-US/panels/terminal.json +++ b/src/web-ui/src/locales/en-US/panels/terminal.json @@ -16,5 +16,13 @@ "cancel": "Cancel", "save": "Save" } + }, + "linkForward": { + "label": "Terminal link", + "created": "Forwarded remote port {{remotePort}} to {{localAddress}}.", + "failed": "Could not forward remote port {{port}}: {{error}}", + "peerUnsupported": "Ports cannot be forwarded while controlling another device. This link points at the remote host, not this machine.", + "openAnyway": "Open link anyway", + "noPort": "This link points at the remote host, not this machine, and has no port to forward." } } diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 6d98f5594b..93c2ee757c 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -2067,7 +2067,7 @@ "portForward": { "menuEntry": "端口映射", "title": "端口映射", - "intro": "把远程主机上正在监听的端口映射到本机访问。映射不会自动建立,只有你在这里添加的才会生效。", + "intro": "把远程主机上正在监听的端口映射到本机访问。只有你在这里添加,或在远程终端中打开 localhost 链接时,才会建立映射。", "detectedTitle": "远程正在监听", "detecting": "正在检测远程端口…", "detect": "重新检测", diff --git a/src/web-ui/src/locales/zh-CN/panels/terminal.json b/src/web-ui/src/locales/zh-CN/panels/terminal.json index 7536c9aaa8..a4f3b06db2 100644 --- a/src/web-ui/src/locales/zh-CN/panels/terminal.json +++ b/src/web-ui/src/locales/zh-CN/panels/terminal.json @@ -16,5 +16,13 @@ "cancel": "取消", "save": "保存" } + }, + "linkForward": { + "label": "终端链接", + "created": "已将远程端口 {{remotePort}} 映射到 {{localAddress}}。", + "failed": "无法映射远程端口 {{port}}:{{error}}", + "peerUnsupported": "控制其他设备时无法映射端口。该链接指向远程主机,而不是本机。", + "openAnyway": "仍然打开链接", + "noPort": "该链接指向远程主机而不是本机,且没有可映射的端口。" } } diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index efdd80cd52..3cb2a04bf2 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -2067,7 +2067,7 @@ "portForward": { "menuEntry": "連接埠對應", "title": "連接埠對應", - "intro": "把遠端主機上正在監聽的連接埠對應到本機存取。對應不會自動建立,只有你在這裡新增的才會生效。", + "intro": "把遠端主機上正在監聽的連接埠對應到本機存取。只有你在這裡新增,或在遠端終端機中開啟 localhost 連結時,才會建立對應。", "detectedTitle": "遠端正在監聽", "detecting": "正在偵測遠端連接埠…", "detect": "重新偵測", diff --git a/src/web-ui/src/locales/zh-TW/panels/terminal.json b/src/web-ui/src/locales/zh-TW/panels/terminal.json index fdb047c5a6..c541f333cd 100644 --- a/src/web-ui/src/locales/zh-TW/panels/terminal.json +++ b/src/web-ui/src/locales/zh-TW/panels/terminal.json @@ -16,5 +16,13 @@ "cancel": "取消", "save": "儲存" } + }, + "linkForward": { + "label": "終端機連結", + "created": "已將遠端連接埠 {{remotePort}} 對應到 {{localAddress}}。", + "failed": "無法對應遠端連接埠 {{port}}:{{error}}", + "peerUnsupported": "控制其他裝置時無法對應連接埠。此連結指向遠端主機,而非本機。", + "openAnyway": "仍要開啟連結", + "noPort": "此連結指向遠端主機而非本機,且沒有可對應的連接埠。" } } diff --git a/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx b/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx index 7f5337f909..9488c5d753 100644 --- a/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx +++ b/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx @@ -20,6 +20,11 @@ import { terminalReplayHasScreenText, } from '../utils'; import { createLogger } from '@/shared/utils/logger'; +import { systemAPI } from '@/infrastructure/api/service-api/SystemAPI'; +import { notificationService } from '@/shared/notification-system'; +import { isPeerDeviceModeActive } from '@/infrastructure/peer-device/peerModeFlag'; +import { sshApi } from '@/features/ssh-remote/sshApi'; +import { openTerminalLink } from '@/features/ssh-remote/openTerminalLink'; import type { SessionResponse, TerminalReplayEvent } from '../types'; import type { TerminalPasteDecision } from '../utils'; import './Terminal.scss'; @@ -433,6 +438,30 @@ const ConnectedTerminal: React.FC = memo(({ } }, [isExited]); + const connectionId = session?.connectionId ?? initialSession?.connectionId; + const handleLinkActivate = useCallback((uri: string) => { + void openTerminalLink(uri, { connectionId }, { + listSavedConnections: () => sshApi.listSavedConnections(), + listPortForwards: (id) => sshApi.listPortForwards(id), + startPortForward: (request) => sshApi.startPortForward(request), + stopPortForward: (forwardId) => sshApi.stopPortForward(forwardId), + openExternal: (url) => systemAPI.openExternal(url), + isPeerDeviceModeActive, + notifyInfo: (message) => { + notificationService.info(message); + }, + notifyWarning: (message, action) => { + notificationService.warning(message, action + ? { actions: [{ label: action.label, onClick: action.onClick }] } + : undefined); + }, + t: (key, params) => t(key, params), + logError: (message, data) => log.error(message, { sessionId, ...data }), + }).catch((error) => { + log.error('Failed to open external link', { sessionId, uri, error }); + }); + }, [connectionId, sessionId, t]); + const terminalId = `terminal-${sessionId}`; useEffect(() => { @@ -539,6 +568,7 @@ const ConnectedTerminal: React.FC = memo(({ onResize={handleResize} onTitleChange={handleTitleChange} onReady={handleTerminalReady} + onLinkActivate={handleLinkActivate} onPasteShortcut={handlePasteShortcut} onPaste={handlePaste} preventShrinkBelowColsRef={preventShrinkBelowColsRef} diff --git a/src/web-ui/src/tools/terminal/components/Terminal.linkActivation.test.tsx b/src/web-ui/src/tools/terminal/components/Terminal.linkActivation.test.tsx new file mode 100644 index 0000000000..8ac4bbe4ee --- /dev/null +++ b/src/web-ui/src/tools/terminal/components/Terminal.linkActivation.test.tsx @@ -0,0 +1,100 @@ +// @vitest-environment jsdom + +import React, { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +type LinkHandler = (event: MouseEvent, uri: string) => void; + +const hoisted = vi.hoisted(() => ({ + linkHandlers: [] as Array<(event: MouseEvent, uri: string) => void>, + openExternal: vi.fn(async () => {}), +})); + +/** Any property is a no-op function returning a disposable-ish stub. */ +function stub(): unknown { + const fn = () => stub(); + return new Proxy(fn, { + get: (_target, prop) => { + if (prop === 'dispose') return () => {}; + if (prop === Symbol.toPrimitive) return () => 0; + if (prop === 'then') return undefined; + if (prop === 'cols' || prop === 'rows' || prop === 'length') return 80; + return stub(); + }, + }); +} + +vi.mock('@xterm/xterm', () => ({ + Terminal: vi.fn(function MockXTerm() { + return stub(); + }), +})); +vi.mock('@xterm/addon-fit', () => ({ FitAddon: vi.fn(function MockFit() { return stub(); }) })); +vi.mock('@xterm/addon-webgl', () => ({ WebglAddon: vi.fn(function MockWebgl() { return stub(); }) })); +vi.mock('@xterm/addon-web-links', () => ({ + WebLinksAddon: vi.fn(function MockWebLinks(handler: LinkHandler) { + hoisted.linkHandlers.push(handler); + return stub(); + }), +})); +vi.mock('@xterm/xterm/css/xterm.css', () => ({})); +vi.mock('@/infrastructure/api/service-api/SystemAPI', () => ({ + systemAPI: { openExternal: hoisted.openExternal }, +})); +vi.mock('@/infrastructure/appearance/adapters/XtermAppearanceAdapter', () => ({ + xtermAppearanceAdapter: { + getColors: () => ({ background: '#000000', foreground: '#ffffff' }), + subscribe: () => () => {}, + onChange: () => () => {}, + }, +})); + +import Terminal from './Terminal'; + +describe('Terminal link activation', () => { + let container: HTMLDivElement; + let root: Root; + + beforeEach(() => { + hoisted.linkHandlers.length = 0; + hoisted.openExternal.mockClear(); + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + class NoopObserver { + observe() {} + unobserve() {} + disconnect() {} + } + vi.stubGlobal('ResizeObserver', NoopObserver); + vi.stubGlobal('IntersectionObserver', NoopObserver); + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + }); + + afterEach(() => { + act(() => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + }); + + function click(uri: string) { + const handler = hoisted.linkHandlers.at(-1); + expect(handler).toBeDefined(); + handler!(new MouseEvent('click', { ctrlKey: true }), uri); + } + + it('routes Ctrl/Cmd+click through onLinkActivate when provided', () => { + const onLinkActivate = vi.fn(); + act(() => root.render()); + click('http://127.0.0.1:5173/'); + expect(onLinkActivate).toHaveBeenCalledWith('http://127.0.0.1:5173/'); + expect(hoisted.openExternal).not.toHaveBeenCalled(); + }); + + it('opens the link externally when no handler is provided', () => { + act(() => root.render()); + click('https://example.com/'); + expect(hoisted.openExternal).toHaveBeenCalledWith('https://example.com/'); + }); +}); diff --git a/src/web-ui/src/tools/terminal/components/Terminal.tsx b/src/web-ui/src/tools/terminal/components/Terminal.tsx index 58ea21445b..9323551db4 100644 --- a/src/web-ui/src/tools/terminal/components/Terminal.tsx +++ b/src/web-ui/src/tools/terminal/components/Terminal.tsx @@ -106,6 +106,11 @@ export interface TerminalProps { /** Notify backend PTY about size changes. */ onResize?: (cols: number, rows: number) => void; onReady?: (terminal: XTerm) => void; + /** + * Link activation (Ctrl/Cmd+click). When omitted the link opens externally + * as-is; remote terminals use this to forward loopback ports first. + */ + onLinkActivate?: (uri: string) => void; /** * Keyboard paste shortcut interceptor. Return true when the shortcut was * handled without reading clipboard text, for example by sending Ctrl+V to a @@ -209,6 +214,7 @@ const Terminal = forwardRef(({ onTitleChange, onResize, onReady, + onLinkActivate, onPasteShortcut, onPaste, preventShrinkBelowColsRef, @@ -233,6 +239,7 @@ const Terminal = forwardRef(({ const onTitleChangeRef = useRef(onTitleChange); const onResizeRef = useRef(onResize); const onReadyRef = useRef(onReady); + const onLinkActivateRef = useRef(onLinkActivate); const onPasteShortcutRef = useRef(onPasteShortcut); const onPasteRef = useRef(onPaste); const resizeSuspendedRef = useRef(resizeSuspended); @@ -268,6 +275,7 @@ const Terminal = forwardRef(({ onTitleChangeRef.current = onTitleChange; onResizeRef.current = onResize; onReadyRef.current = onReady; + onLinkActivateRef.current = onLinkActivate; onPasteShortcutRef.current = onPasteShortcut; onPasteRef.current = onPaste; resizeSuspendedRef.current = resizeSuspended; @@ -500,6 +508,11 @@ const Terminal = forwardRef(({ const webLinksAddon = new WebLinksAddon( (event, uri) => { if (event.ctrlKey || event.metaKey) { + const activate = onLinkActivateRef.current; + if (activate) { + activate(uri); + return; + } systemAPI.openExternal(uri).catch((error) => { log.error('Failed to open external link', { uri, error }); });