From 1966be6aff5f79f0ea16824eae0ec8e88d9119d0 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:05:33 +0800 Subject: [PATCH 1/2] feat(terminal): forward loopback links clicked in SSH terminals Ctrl/Cmd+clicking an http(s) loopback link with an explicit port in a remote SSH terminal now reuses or starts a local port forward for that remote port and opens the rewritten local URL. Forward failures, local Docker/WSL targets, and Peer Device Mode show an explicit warning with an 'open anyway' action instead of silently opening the local URL. Fixes #2285 --- .../features/ssh-remote/PortForwardDialog.tsx | 4 +- .../features/ssh-remote/loopbackLink.test.ts | 50 +++++++ .../src/features/ssh-remote/loopbackLink.ts | 81 ++++++++++ .../ssh-remote/openTerminalLink.test.ts | 113 ++++++++++++++ .../features/ssh-remote/openTerminalLink.ts | 141 ++++++++++++++++++ src/web-ui/src/locales/en-US/common.json | 2 +- .../src/locales/en-US/panels/terminal.json | 12 +- src/web-ui/src/locales/zh-CN/common.json | 2 +- .../src/locales/zh-CN/panels/terminal.json | 12 +- src/web-ui/src/locales/zh-TW/common.json | 2 +- .../src/locales/zh-TW/panels/terminal.json | 12 +- .../terminal/components/ConnectedTerminal.tsx | 28 ++++ .../tools/terminal/components/Terminal.tsx | 13 ++ 13 files changed, 465 insertions(+), 7 deletions(-) create mode 100644 src/web-ui/src/features/ssh-remote/loopbackLink.test.ts create mode 100644 src/web-ui/src/features/ssh-remote/loopbackLink.ts create mode 100644 src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts create mode 100644 src/web-ui/src/features/ssh-remote/openTerminalLink.ts 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..d7dff8d893 --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { isLoopbackRemoteHost, parseLoopbackLink, rewriteLoopbackLink } from './loopbackLink'; + +describe('parseLoopbackLink', () => { + it.each([ + ['http://127.0.0.1:5173/', 5173, '127.0.0.1'], + ['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://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('keeps localhost names and 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://localhost:5174/a/b?x=1#frag'); + }); + + 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('isLoopbackRemoteHost', () => { + it('accepts loopback remote hosts only', () => { + expect(isLoopbackRemoteHost('127.0.0.1')).toBe(true); + expect(isLoopbackRemoteHost('localhost')).toBe(true); + expect(isLoopbackRemoteHost('db.internal')).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..4ed77fa4df --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/loopbackLink.ts @@ -0,0 +1,81 @@ +/** + * 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. */ + remotePort: number; + /** Host the forward should dial on the remote side. */ + remoteHost: string; +} + +/** Remote-side hosts considered equivalent when reusing an existing forward. */ +const LOOPBACK_REMOTE_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']); + +function isLoopbackHostname(hostname: string): boolean { + const host = hostname.toLowerCase(); + if (host === 'localhost' || host.endsWith('.localhost')) return true; + if (host === '0.0.0.0') return true; + if (host === '[::1]' || 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(hostname: string): string { + const host = hostname.toLowerCase(); + if (host === '0.0.0.0') return '127.0.0.1'; + if (host === '[::1]' || host === '::1') return '::1'; + if (host === 'localhost' || host.endsWith('.localhost')) return 'localhost'; + return host; +} + +/** + * Recognize an http(s) link to a loopback address with an explicit port. + * Links without an explicit port are left alone: a scheme-default port on the + * remote is rarely a dev server and usually needs privileges to forward. + */ +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; + if (!isLoopbackHostname(url.hostname)) return null; + if (!url.port) return null; + const remotePort = Number(url.port); + if (!Number.isInteger(remotePort) || remotePort <= 0 || remotePort > 65535) return null; + return { url, remotePort, remoteHost: remoteDialHost(url.hostname) }; +} + +/** Whether an existing forward's remote host reaches the same loopback service. */ +export function isLoopbackRemoteHost(remoteHost: string): boolean { + return LOOPBACK_REMOTE_HOSTS.has(remoteHost.toLowerCase()); +} + +/** + * Point a loopback link at a local forward, keeping path, query and hash. + * + * `localhost` and `*.localhost` names are kept so cookies and OAuth callback + * origins still match; other loopback spellings (`0.0.0.0`, `[::1]`, `127.x`) + * become the forward's bound address, since the forward may not listen on them. + */ +export function rewriteLoopbackLink(link: LoopbackLink, localHost: string, localPort: number): string { + const url = new URL(link.url.href); + const hostname = url.hostname.toLowerCase(); + const keepName = hostname === 'localhost' || hostname.endsWith('.localhost'); + if (!keepName) { + const bound = localHost === '0.0.0.0' || localHost === '::' || !localHost ? '127.0.0.1' : localHost; + url.hostname = bound.includes(':') && !bound.startsWith('[') ? `[${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..cad92eb34e --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it, vi } from 'vitest'; +import { openTerminalLink, type TerminalLinkDeps } from './openTerminalLink'; +import type { PortForward } 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 deps(overrides: Partial = {}) { + return { + listPortForwards: vi.fn(async () => [] as PortForward[]), + startPortForward: vi.fn(async () => forward()), + openExternal: vi.fn(async () => {}), + isPeerDeviceModeActive: vi.fn(() => false), + notifyInfo: vi.fn(), + notifyWarning: vi.fn(), + t: vi.fn((key: string) => key), + ...overrides, + }; +} + +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/', { connectionId: 'conn' }, d); + expect(d.openExternal).toHaveBeenCalledWith('https://example.com/'); + expect(d.listPortForwards).not.toHaveBeenCalled(); + }); + + it('reuses an existing forward without notifying', async () => { + const d = deps({ listPortForwards: vi.fn(async () => [forward({ localPort: 40000 })]) }); + await expect( + openTerminalLink('http://localhost:5173/a?b=1', { connectionId: 'conn' }, d), + ).resolves.toBe('forward-reused'); + expect(d.startPortForward).not.toHaveBeenCalled(); + expect(d.notifyInfo).not.toHaveBeenCalled(); + expect(d.openExternal).toHaveBeenCalledWith('http://localhost:40000/a?b=1'); + }); + + 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/', { connectionId: 'conn' }, 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('Local Docker and WSL workspaces do not support SSH port forwarding.'); + }), + }); + await expect( + openTerminalLink('http://127.0.0.1:3000/', { connectionId: 'docker' }, d), + ).resolves.toBe('forward-failed'); + expect(d.openExternal).not.toHaveBeenCalled(); + expect(d.notifyWarning).toHaveBeenCalledTimes(1); + const action = d.notifyWarning.mock.calls[0][1]; + action?.onClick(); + expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:3000/'); + }); + + it('reuses a forward created concurrently when start reports a duplicate', 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/', { connectionId: 'conn' }, d), + ).resolves.toBe('forward-created'); + expect(d.openExternal).toHaveBeenCalledWith('http://127.0.0.1:41000/'); + }); + + 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/', { connectionId: 'conn' }, 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..33981a2ddc --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/openTerminalLink.ts @@ -0,0 +1,141 @@ +/** + * 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, local + * Docker/WSL targets, a failed bind) the user is told why and the local URL is + * never opened silently; an "open anyway" action keeps the escape hatch. + */ + +import { parseLoopbackLink, rewriteLoopbackLink, isLoopbackRemoteHost } from './loopbackLink'; +import type { PortForward, PortForwardRequest } from './types'; + +export interface TerminalLinkContext { + /** SSH connection that owns the terminal's PTY; absent for local terminals. */ + connectionId?: string; +} + +export interface TerminalLinkNotice { + label: string; + onClick: () => void; +} + +export interface TerminalLinkDeps { + listPortForwards: (connectionId: string) => Promise; + startPortForward: (request: PortForwardRequest) => 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' + | 'forward-reused' + | 'forward-created' + | 'peer-unsupported' + | 'forward-failed'; + +function errorMessage(error: unknown): string { + if (error instanceof Error) return error.message; + return typeof error === 'string' ? error : String(error); +} + +function findForward(forwards: PortForward[], remotePort: number): PortForward | undefined { + return forwards.find( + forward => + forward.direction === 'local' && + forward.remotePort === remotePort && + isLoopbackRemoteHost(forward.remoteHost), + ); +} + +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 }); + }); + }, + }; + + if (deps.isPeerDeviceModeActive()) { + deps.notifyWarning( + deps.t('linkForward.peerUnsupported', { port: link.remotePort }), + openAnyway, + ); + return 'peer-unsupported'; + } + + let forward: PortForward; + let outcome: TerminalLinkOutcome; + try { + const existing = findForward(await deps.listPortForwards(connectionId), link.remotePort); + if (existing) { + forward = existing; + outcome = 'forward-reused'; + } else { + forward = await startForward(connectionId, link.remotePort, link.remoteHost, deps); + outcome = 'forward-created'; + deps.notifyInfo( + deps.t('linkForward.created', { + remotePort: link.remotePort, + localAddress: `${forward.localHost}:${forward.localPort}`, + }), + ); + } + } catch (error) { + deps.logError?.('Failed to forward terminal link', { + connectionId, + remotePort: link.remotePort, + error, + }); + deps.notifyWarning( + deps.t('linkForward.failed', { port: link.remotePort, error: errorMessage(error) }), + openAnyway, + ); + return 'forward-failed'; + } + + await deps.openExternal(rewriteLoopbackLink(link, forward.localHost, forward.localPort)); + return outcome; +} + +async function startForward( + connectionId: string, + remotePort: number, + remoteHost: string, + deps: TerminalLinkDeps, +): Promise { + try { + // Prefer the same port locally; the backend binds another if it is taken. + return await deps.startPortForward({ + connectionId, + remotePort, + remoteHost, + localPort: remotePort, + label: deps.t('linkForward.label'), + }); + } catch (startError) { + // A concurrent click may have created the same forward first. + const raced = findForward(await deps.listPortForwards(connectionId), remotePort); + if (!raced) throw startError; + return raced; + } +} + 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..a4d612a148 100644 --- a/src/web-ui/src/locales/en-US/panels/terminal.json +++ b/src/web-ui/src/locales/en-US/panels/terminal.json @@ -1,7 +1,10 @@ { "title": "Terminal", "emptyState": "No terminal is open", - "actions": { "closeView": "Close terminal view", "stopTerminal": "Stop terminal" }, + "actions": { + "closeView": "Close terminal view", + "stopTerminal": "Stop terminal" + }, "dialog": { "editTerminal": { "title": "Edit Terminal", @@ -16,5 +19,12 @@ "cancel": "Cancel", "save": "Save" } + }, + "linkForward": { + "label": "Terminal link", + "created": "Forwarded remote port {{remotePort}} to {{localAddress}}.", + "failed": "Could not forward remote port {{port}}: {{error}}", + "peerUnsupported": "Remote port {{port}} cannot be forwarded while controlling another device. The link points at the remote host, not this machine.", + "openAnyway": "Open link anyway" } } 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..5a73a3982c 100644 --- a/src/web-ui/src/locales/zh-CN/panels/terminal.json +++ b/src/web-ui/src/locales/zh-CN/panels/terminal.json @@ -1,7 +1,10 @@ { "title": "终端", "emptyState": "当前没有打开的终端", - "actions": { "closeView": "关闭终端视图", "stopTerminal": "停止终端" }, + "actions": { + "closeView": "关闭终端视图", + "stopTerminal": "停止终端" + }, "dialog": { "editTerminal": { "title": "编辑终端", @@ -16,5 +19,12 @@ "cancel": "取消", "save": "保存" } + }, + "linkForward": { + "label": "终端链接", + "created": "已将远程端口 {{remotePort}} 映射到 {{localAddress}}。", + "failed": "无法映射远程端口 {{port}}:{{error}}", + "peerUnsupported": "控制其他设备时无法映射远程端口 {{port}}。该链接指向远程主机,而不是本机。", + "openAnyway": "仍然打开链接" } } 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..3d72e63ee4 100644 --- a/src/web-ui/src/locales/zh-TW/panels/terminal.json +++ b/src/web-ui/src/locales/zh-TW/panels/terminal.json @@ -1,7 +1,10 @@ { "title": "終端", "emptyState": "目前沒有開啟的終端", - "actions": { "closeView": "關閉終端機檢視", "stopTerminal": "停止終端機" }, + "actions": { + "closeView": "關閉終端機檢視", + "stopTerminal": "停止終端機" + }, "dialog": { "editTerminal": { "title": "編輯終端", @@ -16,5 +19,12 @@ "cancel": "取消", "save": "儲存" } + }, + "linkForward": { + "label": "終端機連結", + "created": "已將遠端連接埠 {{remotePort}} 對應到 {{localAddress}}。", + "failed": "無法對應遠端連接埠 {{port}}:{{error}}", + "peerUnsupported": "控制其他裝置時無法對應遠端連接埠 {{port}}。此連結指向遠端主機,而非本機。", + "openAnyway": "仍要開啟連結" } } diff --git a/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx b/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx index 7f5337f909..f0d32ecfc9 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,28 @@ const ConnectedTerminal: React.FC = memo(({ } }, [isExited]); + const connectionId = session?.connectionId ?? initialSession?.connectionId; + const handleLinkActivate = useCallback((uri: string) => { + void openTerminalLink(uri, { connectionId }, { + listPortForwards: (id) => sshApi.listPortForwards(id), + startPortForward: (request) => sshApi.startPortForward(request), + 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 +566,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.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 }); }); From 496c7e44baaa3433ad6049c2c7a7303e4c4c1c49 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:15:57 +0800 Subject: [PATCH 2/2] fix(terminal): harden remote terminal link forwarding - Open links unchanged for WSL and local Docker targets instead of calling the SSH forward backend. - Always rewrite to the forward's bound address so localhost cannot resolve to a local IPv6 server. - Match forwards by exact remote host (plus localhost/127.0.0.1), so 127.x and ::1 links reuse or create the right forward. - Treat a lost start race as reuse and keep the original start error when the fallback re-list fails. - Warn on port-less loopback links and strip a trailing host dot. - Restart an idle forward that recorded an error instead of reusing it. - Add Terminal onLinkActivate wiring test; keep terminal.json formatting. --- .../features/ssh-remote/loopbackLink.test.ts | 32 ++-- .../src/features/ssh-remote/loopbackLink.ts | 73 +++++---- .../ssh-remote/openTerminalLink.test.ts | 117 +++++++++++--- .../features/ssh-remote/openTerminalLink.ts | 143 ++++++++++++------ .../src/locales/en-US/panels/terminal.json | 10 +- .../src/locales/zh-CN/panels/terminal.json | 10 +- .../src/locales/zh-TW/panels/terminal.json | 10 +- .../terminal/components/ConnectedTerminal.tsx | 2 + .../Terminal.linkActivation.test.tsx | 100 ++++++++++++ 9 files changed, 363 insertions(+), 134 deletions(-) create mode 100644 src/web-ui/src/tools/terminal/components/Terminal.linkActivation.test.tsx diff --git a/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts b/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts index d7dff8d893..b8f57fe8cb 100644 --- a/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts +++ b/src/web-ui/src/features/ssh-remote/loopbackLink.test.ts @@ -1,10 +1,11 @@ import { describe, expect, it } from 'vitest'; -import { isLoopbackRemoteHost, parseLoopbackLink, rewriteLoopbackLink } from './loopbackLink'; +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'], @@ -15,9 +16,16 @@ describe('parseLoopbackLink', () => { 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([ - 'http://localhost/', - 'http://127.0.0.1:80/', 'https://example.com:3000', 'ftp://127.0.0.1:21', 'http://10.0.0.1:3000', @@ -28,9 +36,11 @@ describe('parseLoopbackLink', () => { }); describe('rewriteLoopbackLink', () => { - it('keeps localhost names and path, query and hash', () => { + 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://localhost:5174/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', () => { @@ -41,10 +51,12 @@ describe('rewriteLoopbackLink', () => { }); }); -describe('isLoopbackRemoteHost', () => { - it('accepts loopback remote hosts only', () => { - expect(isLoopbackRemoteHost('127.0.0.1')).toBe(true); - expect(isLoopbackRemoteHost('localhost')).toBe(true); - expect(isLoopbackRemoteHost('db.internal')).toBe(false); +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 index 4ed77fa4df..6705101877 100644 --- a/src/web-ui/src/features/ssh-remote/loopbackLink.ts +++ b/src/web-ui/src/features/ssh-remote/loopbackLink.ts @@ -10,37 +10,38 @@ export interface LoopbackLink { /** Parsed link. */ url: URL; - /** Port the service listens on, as seen from the remote host. */ - remotePort: number; + /** + * 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; } -/** Remote-side hosts considered equivalent when reusing an existing forward. */ -const LOOPBACK_REMOTE_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']); +/** 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(hostname: string): boolean { - const host = hostname.toLowerCase(); +function isLoopbackHostname(host: string): boolean { if (host === 'localhost' || host.endsWith('.localhost')) return true; - if (host === '0.0.0.0') return true; - if (host === '[::1]' || host === '::1') 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(hostname: string): string { - const host = hostname.toLowerCase(); +function remoteDialHost(host: string): string { if (host === '0.0.0.0') return '127.0.0.1'; - if (host === '[::1]' || host === '::1') return '::1'; if (host === 'localhost' || host.endsWith('.localhost')) return 'localhost'; return host; } -/** - * Recognize an http(s) link to a loopback address with an explicit port. - * Links without an explicit port are left alone: a scheme-default port on the - * remote is rarely a dev server and usually needs privileges to forward. - */ +/** Recognize an http(s) link whose host is a loopback address. */ export function parseLoopbackLink(uri: string): LoopbackLink | null { let url: URL; try { @@ -49,33 +50,39 @@ export function parseLoopbackLink(uri: string): LoopbackLink | null { return null; } if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; - if (!isLoopbackHostname(url.hostname)) return null; - if (!url.port) return null; - const remotePort = Number(url.port); - if (!Number.isInteger(remotePort) || remotePort <= 0 || remotePort > 65535) return null; - return { url, remotePort, remoteHost: remoteDialHost(url.hostname) }; + 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) }; } -/** Whether an existing forward's remote host reaches the same loopback service. */ -export function isLoopbackRemoteHost(remoteHost: string): boolean { - return LOOPBACK_REMOTE_HOSTS.has(remoteHost.toLowerCase()); +/** 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. * - * `localhost` and `*.localhost` names are kept so cookies and OAuth callback - * origins still match; other loopback spellings (`0.0.0.0`, `[::1]`, `127.x`) - * become the forward's bound address, since the forward may not listen on them. + * 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); - const hostname = url.hostname.toLowerCase(); - const keepName = hostname === 'localhost' || hostname.endsWith('.localhost'); - if (!keepName) { - const bound = localHost === '0.0.0.0' || localHost === '::' || !localHost ? '127.0.0.1' : localHost; - url.hostname = bound.includes(':') && !bound.startsWith('[') ? `[${bound}]` : bound; - } + 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 index cad92eb34e..6a680a6330 100644 --- a/src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts +++ b/src/web-ui/src/features/ssh-remote/openTerminalLink.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; import { openTerminalLink, type TerminalLinkDeps } from './openTerminalLink'; -import type { PortForward } from './types'; +import type { PortForward, SavedConnection } from './types'; function forward(overrides: Partial = {}): PortForward { return { @@ -17,10 +17,24 @@ function forward(overrides: Partial = {}): PortForward { }; } +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(), @@ -30,6 +44,8 @@ function deps(overrides: Partial = {}) { }; } +const ssh = { connectionId: 'conn' }; + describe('openTerminalLink', () => { it('opens links unchanged for local terminals', async () => { const d = deps(); @@ -40,26 +56,62 @@ describe('openTerminalLink', () => { it('opens non-loopback links unchanged for remote terminals', async () => { const d = deps(); - await openTerminalLink('https://example.com/', { connectionId: 'conn' }, d); + await openTerminalLink('https://example.com/', ssh, d); expect(d.openExternal).toHaveBeenCalledWith('https://example.com/'); expect(d.listPortForwards).not.toHaveBeenCalled(); }); - it('reuses an existing forward without notifying', async () => { + 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', { connectionId: 'conn' }, d), - ).resolves.toBe('forward-reused'); + 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://localhost:40000/a?b=1'); + 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/', { connectionId: 'conn' }, d), - ).resolves.toBe('forward-created'); + 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 }), ); @@ -71,22 +123,35 @@ describe('openTerminalLink', () => { it('warns and does not open the local URL when forwarding fails', async () => { const d = deps({ startPortForward: vi.fn(async () => { - throw new Error('Local Docker and WSL workspaces do not support SSH port forwarding.'); + throw new Error('bind failed'); }), }); - await expect( - openTerminalLink('http://127.0.0.1:3000/', { connectionId: 'docker' }, d), - ).resolves.toBe('forward-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); - const action = d.notifyWarning.mock.calls[0][1]; - action?.onClick(); + 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('reuses a forward created concurrently when start reports a duplicate', async () => { + 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>() + .fn<() => Promise>() .mockResolvedValueOnce([]) .mockResolvedValueOnce([forward({ localPort: 41000 })]); const d = deps({ @@ -95,17 +160,21 @@ describe('openTerminalLink', () => { throw new Error('already forwarded'); }), }); - await expect( - openTerminalLink('http://127.0.0.1:5173/', { connectionId: 'conn' }, d), - ).resolves.toBe('forward-created'); + 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/', { connectionId: 'conn' }, d), - ).resolves.toBe('peer-unsupported'); + 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 index 33981a2ddc..0731471856 100644 --- a/src/web-ui/src/features/ssh-remote/openTerminalLink.ts +++ b/src/web-ui/src/features/ssh-remote/openTerminalLink.ts @@ -2,16 +2,20 @@ * 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, local - * Docker/WSL targets, a failed bind) the user is told why and the local URL is + * 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, isLoopbackRemoteHost } from './loopbackLink'; -import type { PortForward, PortForwardRequest } from './types'; +import { parseLoopbackLink, rewriteLoopbackLink, sameRemoteHost, type LoopbackLink } from './loopbackLink'; +import type { PortForward, PortForwardRequest, SavedConnection } from './types'; export interface TerminalLinkContext { - /** SSH connection that owns the terminal's PTY; absent for local terminals. */ + /** Connection that owns the terminal's PTY; absent for local terminals. */ connectionId?: string; } @@ -21,8 +25,10 @@ export interface TerminalLinkNotice { } 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; @@ -33,25 +39,48 @@ export interface TerminalLinkDeps { 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[], remotePort: number): PortForward | undefined { - return forwards.find( - forward => - forward.direction === 'local' && - forward.remotePort === remotePort && - isLoopbackRemoteHost(forward.remoteHost), +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, @@ -74,68 +103,84 @@ export async function openTerminalLink( }, }; + // The forward would bind on the peer host, not on this controller. if (deps.isPeerDeviceModeActive()) { - deps.notifyWarning( - deps.t('linkForward.peerUnsupported', { port: link.remotePort }), - openAnyway, - ); + 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 { - const existing = findForward(await deps.listPortForwards(connectionId), link.remotePort); - if (existing) { - forward = existing; - outcome = 'forward-reused'; - } else { - forward = await startForward(connectionId, link.remotePort, link.remoteHost, deps); - outcome = 'forward-created'; - deps.notifyInfo( - deps.t('linkForward.created', { - remotePort: link.remotePort, - localAddress: `${forward.localHost}:${forward.localPort}`, - }), - ); - } + ({ forward, outcome } = await ensureForward(connectionId, link, remotePort, deps)); } catch (error) { - deps.logError?.('Failed to forward terminal link', { - connectionId, - remotePort: link.remotePort, - error, - }); + deps.logError?.('Failed to forward terminal link', { connectionId, remotePort, error }); deps.notifyWarning( - deps.t('linkForward.failed', { port: link.remotePort, error: errorMessage(error) }), + 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 startForward( +async function ensureForward( connectionId: string, + link: LoopbackLink, remotePort: number, - remoteHost: string, deps: TerminalLinkDeps, -): Promise { - try { +): 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. - return await deps.startPortForward({ - connectionId, - remotePort, - remoteHost, - localPort: remotePort, - label: deps.t('linkForward.label'), - }); + 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. - const raced = findForward(await deps.listPortForwards(connectionId), remotePort); + let raced: PortForward | undefined; + try { + raced = findForward(await deps.listPortForwards(connectionId), link.remoteHost, remotePort); + } catch { + throw startError; + } if (!raced) throw startError; - return raced; + return { forward: raced, outcome: 'forward-reused' }; } } - 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 a4d612a148..09df9f5057 100644 --- a/src/web-ui/src/locales/en-US/panels/terminal.json +++ b/src/web-ui/src/locales/en-US/panels/terminal.json @@ -1,10 +1,7 @@ { "title": "Terminal", "emptyState": "No terminal is open", - "actions": { - "closeView": "Close terminal view", - "stopTerminal": "Stop terminal" - }, + "actions": { "closeView": "Close terminal view", "stopTerminal": "Stop terminal" }, "dialog": { "editTerminal": { "title": "Edit Terminal", @@ -24,7 +21,8 @@ "label": "Terminal link", "created": "Forwarded remote port {{remotePort}} to {{localAddress}}.", "failed": "Could not forward remote port {{port}}: {{error}}", - "peerUnsupported": "Remote port {{port}} cannot be forwarded while controlling another device. The link points at the remote host, not this machine.", - "openAnyway": "Open link anyway" + "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/panels/terminal.json b/src/web-ui/src/locales/zh-CN/panels/terminal.json index 5a73a3982c..a4f3b06db2 100644 --- a/src/web-ui/src/locales/zh-CN/panels/terminal.json +++ b/src/web-ui/src/locales/zh-CN/panels/terminal.json @@ -1,10 +1,7 @@ { "title": "终端", "emptyState": "当前没有打开的终端", - "actions": { - "closeView": "关闭终端视图", - "stopTerminal": "停止终端" - }, + "actions": { "closeView": "关闭终端视图", "stopTerminal": "停止终端" }, "dialog": { "editTerminal": { "title": "编辑终端", @@ -24,7 +21,8 @@ "label": "终端链接", "created": "已将远程端口 {{remotePort}} 映射到 {{localAddress}}。", "failed": "无法映射远程端口 {{port}}:{{error}}", - "peerUnsupported": "控制其他设备时无法映射远程端口 {{port}}。该链接指向远程主机,而不是本机。", - "openAnyway": "仍然打开链接" + "peerUnsupported": "控制其他设备时无法映射端口。该链接指向远程主机,而不是本机。", + "openAnyway": "仍然打开链接", + "noPort": "该链接指向远程主机而不是本机,且没有可映射的端口。" } } 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 3d72e63ee4..c541f333cd 100644 --- a/src/web-ui/src/locales/zh-TW/panels/terminal.json +++ b/src/web-ui/src/locales/zh-TW/panels/terminal.json @@ -1,10 +1,7 @@ { "title": "終端", "emptyState": "目前沒有開啟的終端", - "actions": { - "closeView": "關閉終端機檢視", - "stopTerminal": "停止終端機" - }, + "actions": { "closeView": "關閉終端機檢視", "stopTerminal": "停止終端機" }, "dialog": { "editTerminal": { "title": "編輯終端", @@ -24,7 +21,8 @@ "label": "終端機連結", "created": "已將遠端連接埠 {{remotePort}} 對應到 {{localAddress}}。", "failed": "無法對應遠端連接埠 {{port}}:{{error}}", - "peerUnsupported": "控制其他裝置時無法對應遠端連接埠 {{port}}。此連結指向遠端主機,而非本機。", - "openAnyway": "仍要開啟連結" + "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 f0d32ecfc9..9488c5d753 100644 --- a/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx +++ b/src/web-ui/src/tools/terminal/components/ConnectedTerminal.tsx @@ -441,8 +441,10 @@ const ConnectedTerminal: React.FC = memo(({ 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) => { 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/'); + }); +});