feat: add port forwarding and optimize connection status checks

This commit is contained in:
liumangmang
2026-06-11 14:10:30 +08:00
parent 4a17f0106e
commit e418e6ecc2
30 changed files with 1789 additions and 150 deletions
+86 -23
View File
@@ -1,38 +1,101 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="100%" height="100%">
<!-- 背景层:深色圆角矩形与发光效果 -->
<defs>
<!-- Background Gradient -->
<linearGradient id="bgGradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#0f172a" />
<stop offset="0%" stop-color="#0b1329" />
<stop offset="60%" stop-color="#040814" />
<stop offset="100%" stop-color="#02040a" />
</linearGradient>
<!-- Border Gradient -->
<linearGradient id="borderGradient" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#1e293b" />
<stop offset="50%" stop-color="#0f172a" />
<stop offset="100%" stop-color="#020617" />
</linearGradient>
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="15" result="blur" />
<feComposite in="SourceGraphic" in2="blur" operator="over" />
<!-- Terminal Border Gradient -->
<linearGradient id="termBorder" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#22d3ee" />
<stop offset="50%" stop-color="#3b82f6" />
<stop offset="100%" stop-color="#6366f1" />
</linearGradient>
<!-- Key Gradient -->
<linearGradient id="keyGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#22d3ee" />
<stop offset="40%" stop-color="#0ea5e9" />
<stop offset="100%" stop-color="#2563eb" />
</linearGradient>
<!-- Subtle Glow for Terminal -->
<filter id="termGlow" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="12" result="blur" />
<feComponentTransfer in="blur" result="boost">
<feFuncA type="linear" slope="0.3"/>
</feComponentTransfer>
<feMerge>
<feMergeNode in="boost" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
<linearGradient id="primaryGlow" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#3b82f6" stop-opacity="0.6" />
<stop offset="100%" stop-color="#10b981" stop-opacity="0.3" />
<!-- 3D Shadow for the Key -->
<filter id="keyShadow" x="-40%" y="-40%" width="180%" height="180%">
<feDropShadow dx="-6" dy="8" stdDeviation="6" flood-color="#020617" flood-opacity="0.8"/>
<feDropShadow dx="-2" dy="3" stdDeviation="3" flood-color="#06b6d4" flood-opacity="0.3"/>
</filter>
<!-- Glare Gradient -->
<linearGradient id="glareGrad" x1="0%" y1="0%" x2="1" y2="1">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.08" />
<stop offset="40%" stop-color="#ffffff" stop-opacity="0.03" />
<stop offset="100%" stop-color="#ffffff" stop-opacity="0.0" />
</linearGradient>
</defs>
<!-- 外部圆角底框 -->
<rect x="32" y="32" width="448" height="448" rx="100" ry="100" fill="url(#bgGradient)" stroke="#1e293b" stroke-width="8" />
<!-- Outer Squircle App Icon Base -->
<rect x="24" y="24" width="464" height="464" rx="120" ry="120" fill="url(#bgGradient)" stroke="url(#borderGradient)" stroke-width="6" />
<!-- 内部光晕点缀 -->
<circle cx="256" cy="256" r="180" fill="url(#primaryGlow)" filter="url(#glow)" />
<rect x="64" y="64" width="384" height="384" rx="80" ry="80" fill="#0f172a" opacity="0.85" />
<!-- Inner Soft Ambient Light (Top-Left glow) -->
<path d="M 24 144 A 120 120 0 0 1 144 24 L 300 24 C 200 80 80 200 24 300 Z" fill="#22d3ee" fill-opacity="0.02" />
<!-- 终端符号: >_ -->
<g transform="translate(130, 160)" stroke-linecap="round" stroke-linejoin="round">
<!-- 箭头 > -->
<path d="M 20 20 L 120 90 L 20 160" fill="none" stroke="#3b82f6" stroke-width="40" />
<!-- Terminal Window Console Card -->
<g filter="url(#termGlow)">
<!-- Terminal Outer Frame -->
<rect x="110" y="130" width="260" height="230" rx="36" ry="36" fill="#030712" stroke="url(#termBorder)" stroke-width="4.5" />
<!-- Glare reflection on terminal glass -->
<path d="M 112 166 Q 240 132 368 166 A 34 34 0 0 1 368 180 L 220 358 A 34 34 0 0 1 112 300 Z" fill="url(#glareGrad)" />
<!-- 下划线 _ -->
<line x1="140" y1="180" x2="240" y2="180" stroke="#10b981" stroke-width="36" />
<!-- Terminal Header Dots -->
<circle cx="150" cy="165" r="7" fill="#ef4444" fill-opacity="0.75" />
<circle cx="175" cy="165" r="7" fill="#f59e0b" fill-opacity="0.75" />
<circle cx="200" cy="165" r="7" fill="#10b981" fill-opacity="0.75" />
<!-- Host text simulation -->
<text x="230" y="169" fill="#94a3b8" fill-opacity="0.4" font-family="monospace" font-size="11" letter-spacing="1">ssh-session</text>
<!-- Terminal Prompts >_ -->
<g transform="translate(150, 210)">
<!-- Arrow > -->
<path d="M 10 20 L 40 45 L 10 70" fill="none" stroke="#22d3ee" stroke-width="12" stroke-linecap="round" stroke-linejoin="round" />
<!-- Cursor _ -->
<rect x="55" y="60" width="30" height="10" rx="2" fill="#34d399" />
</g>
</g>
<!-- 顶部状态指示灯 (红黄绿) -->
<circle cx="110" cy="110" r="12" fill="#ef4444" />
<circle cx="150" cy="110" r="12" fill="#eab308" />
<circle cx="190" cy="110" r="12" fill="#10b981" />
<!-- Security Key Overlap -->
<g transform="translate(315, 235) rotate(-45)" filter="url(#keyShadow)">
<!-- Shaft of Key -->
<path d="M -20 -7 L -175 -7 C -180 -7 -180 7 -175 7 L -20 7 Z" fill="url(#keyGrad)" />
<!-- Key Head (Terminal screen hole shape) -->
<circle cx="20" cy="0" r="45" fill="none" stroke="url(#keyGrad)" stroke-width="14" />
<circle cx="20" cy="0" r="14" fill="none" stroke="url(#keyGrad)" stroke-width="8" />
<!-- Key Teeth -->
<path d="M -115 5 L -115 32 A 4 4 0 0 0 -111 36 L -101 36 A 4 4 0 0 0 -97 32 L -97 5 Z" fill="url(#keyGrad)" />
<path d="M -150 5 L -150 32 A 4 4 0 0 0 -146 36 L -136 36 A 4 4 0 0 0 -132 32 L -132 5 Z" fill="url(#keyGrad)" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

@@ -0,0 +1,293 @@
import { useEffect, useState } from 'react'
import {
AlertCircle,
Network,
Play,
RefreshCw,
StopCircle,
Trash2,
} from 'lucide-react'
import Modal from './Modal'
import {
createPortForward,
listPortForwards,
stopPortForward,
type PortForwardTunnel,
} from '../services/portForwards'
import type { Connection } from '../types'
interface PortForwardModalProps {
open: boolean
connections: Connection[]
initialConnectionId?: number | null
onClose: () => void
}
export default function PortForwardModal({
open,
connections,
initialConnectionId,
onClose,
}: PortForwardModalProps) {
const [tunnels, setTunnels] = useState<PortForwardTunnel[]>([])
const [loading, setLoading] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
// Form state
const [connectionId, setConnectionId] = useState<number>(0)
const [localPort, setLocalPort] = useState<number>(8080)
const [remoteHost, setRemoteHost] = useState<string>('127.0.0.1')
const [remotePort, setRemotePort] = useState<number>(80)
// Load tunnels
const fetchTunnels = async (showLoading = true) => {
if (showLoading) setLoading(true)
setError(null)
try {
const data = await listPortForwards()
setTunnels(data)
} catch (err: any) {
setError(err.message ?? '获取端口转发列表失败')
} finally {
if (showLoading) setLoading(false)
}
}
useEffect(() => {
if (open) {
fetchTunnels(true)
// Pre-select connection if provided
if (initialConnectionId) {
setConnectionId(initialConnectionId)
} else if (connections.length > 0) {
setConnectionId(connections[0].id)
}
}
}, [open, initialConnectionId, connections])
const handleStartTunnel = async (e: React.FormEvent) => {
e.preventDefault()
if (!connectionId) {
setError('请选择 SSH 连接')
return
}
setError(null)
setSubmitting(true)
try {
await createPortForward({
connectionId,
localPort,
remoteHost: remoteHost.trim(),
remotePort,
})
// Reset form options (keep connection, maybe increment local port)
setLocalPort((prev) => prev + 1)
await fetchTunnels(false)
} catch (err: any) {
setError(err.message ?? '启动端口转发失败')
} finally {
setSubmitting(false)
}
}
const handleStopTunnel = async (id: string) => {
setError(null)
try {
await stopPortForward(id)
await fetchTunnels(false)
} catch (err: any) {
setError(err.message ?? '停止端口转发失败')
}
}
if (!open) return null
return (
<Modal
title="端口转发管理"
onClose={onClose}
open={open}
maxWidth="max-w-5xl"
>
<div className="flex flex-col gap-6 md:flex-row">
{/* Left Column: Form to create a new tunnel */}
<div className="flex-1 rounded-2xl border border-border-main bg-surface-muted/30 p-5 md:max-w-xs lg:max-w-sm">
<h4 className="mb-4 flex items-center gap-2 text-sm font-semibold text-content-main">
<Play size={16} className="text-emerald-500" />
</h4>
<form onSubmit={handleStartTunnel} className="space-y-4">
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-content-muted">
SSH
</label>
<select
value={connectionId}
onChange={(e) => setConnectionId(Number(e.target.value))}
className="w-full rounded-xl border border-border-main bg-surface-control px-3.5 py-2 text-sm text-content-main focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
>
{connections.length === 0 ? (
<option value={0}></option>
) : (
connections.map((c) => (
<option key={c.id} value={c.id}>
{c.name} ({c.host})
</option>
))
)}
</select>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-content-muted">
(Local Port)
</label>
<input
type="number"
min={1}
max={65535}
value={localPort}
onChange={(e) => setLocalPort(Number(e.target.value))}
className="w-full rounded-xl border border-border-main bg-surface-control px-3.5 py-2 text-sm text-content-main focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
required
/>
</div>
<div className="grid grid-cols-3 gap-2">
<div className="col-span-2 flex flex-col gap-1.5">
<label className="text-xs font-medium text-content-muted">
(Remote Host)
</label>
<input
type="text"
value={remoteHost}
onChange={(e) => setRemoteHost(e.target.value)}
className="w-full rounded-xl border border-border-main bg-surface-control px-3.5 py-2 text-sm text-content-main focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
required
/>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-content-muted">
</label>
<input
type="number"
min={1}
max={65535}
value={remotePort}
onChange={(e) => setRemotePort(Number(e.target.value))}
className="w-full rounded-xl border border-border-main bg-surface-control px-3.5 py-2 text-sm text-content-main focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition"
required
/>
</div>
</div>
{error && (
<div className="flex gap-2 rounded-xl bg-red-500/10 p-3 text-xs text-red-300 border border-red-500/20">
<AlertCircle size={16} className="shrink-0 text-red-400" />
<span>{error}</span>
</div>
)}
<button
type="submit"
disabled={submitting || connections.length === 0}
className="flex w-full items-center justify-center gap-2 rounded-xl bg-emerald-600 py-2.5 text-sm font-semibold text-white transition hover:bg-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{submitting ? '正在启动...' : '启动转发'}
</button>
</form>
</div>
{/* Right Column: List of running tunnels */}
<div className="flex-1 flex flex-col">
<div className="mb-4 flex items-center justify-between">
<h4 className="flex items-center gap-2 text-sm font-semibold text-content-main">
<Network size={16} className="text-blue-500 animate-pulse" />
</h4>
<button
onClick={() => fetchTunnels(true)}
disabled={loading}
className="rounded-xl border border-border-main bg-surface-muted p-2 text-content-muted transition hover:text-content-main hover:bg-surface-panel"
title="刷新列表"
>
<RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
</button>
</div>
<div className="flex-1 overflow-auto max-h-[400px] rounded-2xl border border-border-main bg-surface-panel/40 p-4">
{loading && tunnels.length === 0 ? (
<div className="flex h-48 items-center justify-center text-xs text-content-dim">
...
</div>
) : tunnels.length === 0 ? (
<div className="flex h-48 flex-col items-center justify-center text-content-dim">
<Network size={36} className="mb-2 text-content-dim/30" />
<span className="text-xs"></span>
</div>
) : (
<div className="space-y-3">
{tunnels.map((tunnel) => (
<div
key={tunnel.id}
className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-xl border border-border-subtle bg-surface-card p-3.5 transition hover:border-border-main"
>
<div className="space-y-1">
<div className="flex items-center gap-2 text-xs font-semibold text-content-main">
<span className="max-w-[120px] truncate text-blue-400">
{tunnel.connectionName}
</span>
<span className="text-content-dim font-normal">|</span>
<span className="text-emerald-500 font-mono">
:{tunnel.localPort}
</span>
<span className="text-content-dim font-normal"></span>
<span className="text-content-muted font-mono">
{tunnel.remoteHost}:{tunnel.remotePort}
</span>
</div>
<div className="flex items-center gap-2 text-[10px] text-content-dim">
<span>
: {new Date(tunnel.createdAt).toLocaleTimeString()}
</span>
<span className="h-1 w-1 rounded-full bg-content-dim" />
<span className="flex items-center gap-1">
<span
className={`h-1.5 w-1.5 rounded-full ${
tunnel.status === 'running'
? 'bg-emerald-500 animate-pulse'
: tunnel.status === 'error'
? 'bg-red-500'
: 'bg-content-muted'
}`}
/>
{tunnel.status === 'running'
? '运行中'
: tunnel.status === 'error'
? '异常'
: '已停止'}
</span>
</div>
</div>
<button
onClick={() => handleStopTunnel(tunnel.id)}
className="self-end sm:self-center flex items-center gap-1 rounded-lg border border-red-500/20 bg-red-500/5 px-2 py-1 text-[11px] font-medium text-red-300 transition hover:bg-red-500/10 hover:text-red-200"
>
<StopCircle size={12} />
</button>
</div>
))}
</div>
)}
</div>
</div>
</div>
</Modal>
)
}
+37 -1
View File
@@ -10,6 +10,7 @@ import {
Monitor,
Plus,
Search,
Network,
Settings,
SplitSquareHorizontal,
Terminal,
@@ -61,6 +62,7 @@ import SettingsModal from '../components/SettingsModal'
import SftpPane from '../components/SftpPane'
import TerminalPane from '../components/TerminalPane'
import TransferCenterModal from '../components/TransferCenterModal'
import PortForwardModal from '../components/PortForwardModal'
const terminalStatusCopy: Record<TerminalConnectionStatus, { label: string; tone: string; dot: string }> = {
idle: { label: '终端未打开', tone: 'text-content-muted', dot: 'bg-content-muted' },
@@ -254,6 +256,8 @@ export default function WorkspacePage({
const [showBatchModal, setShowBatchModal] = useState(false)
const [showTransferModal, setShowTransferModal] = useState(initialTool === 'transfers')
const [showSettingsModal, setShowSettingsModal] = useState(false)
const [showPortForwardModal, setShowPortForwardModal] = useState(false)
const [portForwardInitialConnId, setPortForwardInitialConnId] = useState<number | null>(null)
const [quickTokens, setQuickTokens] = useState<Record<string, string>>({})
const [showChangePassword, setShowChangePassword] = useState<boolean>(!!user?.passwordChangeRequired)
const [transferTasks, setTransferTasks] = useState<TransferTaskGroup[]>([])
@@ -740,6 +744,16 @@ export default function WorkspacePage({
<FileUp size={16} className="text-blue-400" />
</button>
<button
className="flex items-center gap-2 rounded-md px-3 py-1.5 text-sm text-content-muted transition hover:bg-surface-muted hover:text-content-main"
onClick={() => {
setPortForwardInitialConnId(null)
setShowPortForwardModal(true)
}}
>
<Network size={16} className="text-emerald-400" />
</button>
<button
className="flex items-center gap-2 rounded-md px-3 py-1.5 text-sm text-content-muted transition hover:bg-surface-muted hover:text-content-main"
onClick={async () => {
@@ -1097,6 +1111,12 @@ export default function WorkspacePage({
darkMode={darkMode}
onDarkModeChange={setDarkMode}
/>
<PortForwardModal
open={showPortForwardModal}
connections={connections}
initialConnectionId={portForwardInitialConnId}
onClose={() => setShowPortForwardModal(false)}
/>
{showChangePassword ? <ChangePasswordModal force={!!user?.passwordChangeRequired} onClose={() => setShowChangePassword(false)} /> : null}
{treeContextMenu.visible ? (
<div className="fixed inset-0 z-50" onClick={closeTreeContextMenu}>
@@ -1127,7 +1147,23 @@ export default function WorkspacePage({
</button>
</>
) : null}
) : (
<button
className="flex w-full items-center rounded-lg px-3 py-2 text-left text-sm text-content-main transition hover:bg-surface-muted hover:text-content-main"
onClick={() => {
const targetId = treeContextMenu.targetId
closeTreeContextMenu()
if (!targetId) return
const node = findTreeNode(targetId)
if (node && node.type === 'connection' && node.connectionId) {
setPortForwardInitialConnId(node.connectionId)
setShowPortForwardModal(true)
}
}}
>
</button>
)}
<button
className="flex w-full items-center rounded-lg px-3 py-2 text-left text-sm text-content-main transition hover:bg-surface-muted hover:text-content-main"
onClick={() => void handleEditTreeItem()}
+43
View File
@@ -0,0 +1,43 @@
import http from './http'
export interface PortForwardTunnel {
id: string
connectionId: number
connectionName: string
localPort: number
remoteHost: string
remotePort: number
status: 'running' | 'stopped' | 'error'
createdAt: string
}
export interface CreatePortForwardRequest {
connectionId: number
localPort: number
remoteHost: string
remotePort: number
}
export async function listPortForwards(): Promise<PortForwardTunnel[]> {
const res = await http.get<PortForwardTunnel[]>('/port-forwards')
return res.data
}
export async function createPortForward(req: CreatePortForwardRequest): Promise<PortForwardTunnel> {
try {
const res = await http.post<PortForwardTunnel>('/port-forwards', req)
return res.data
} catch (err: any) {
const errMsg = err.response?.data?.error ?? err.message ?? '启动端口转发失败'
throw new Error(errMsg)
}
}
export async function stopPortForward(id: string): Promise<void> {
try {
await http.delete(`/port-forwards/${id}`)
} catch (err: any) {
const errMsg = err.response?.data?.error ?? err.message ?? '停止端口转发失败'
throw new Error(errMsg)
}
}