From aff8a603d3bdcf3a92d39f1bf4ade7019dab1436 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 11 Dec 2025 03:28:44 +0800 Subject: [PATCH] Adds protocol selection and native Telnet support Improves host connection flow by allowing users to choose SSH, Mosh, or Telnet protocols when multiple are available. Implements native Telnet client, removing system dependency and enabling proper Telnet negotiation, window resizing, and terminal type handling. Ensures session protocol overrides persist during connection, improving accuracy of terminal sessions. Enhances UI logic for protocol-specific host details and quick connect wizard navigation. --- App.tsx | 61 ++++++- application/state/useSessionState.ts | 4 + components/HostDetailsPanel.tsx | 10 +- components/QuickConnectWizard.tsx | 25 +-- components/TerminalLayer.tsx | 15 +- domain/models.ts | 4 + electron/main.cjs | 260 ++++++++++++++++++++++----- 7 files changed, 309 insertions(+), 70 deletions(-) diff --git a/App.tsx b/App.tsx index e6f25ada1..cfa1f1ccd 100755 --- a/App.tsx +++ b/App.tsx @@ -5,7 +5,8 @@ import { TopTabs } from './components/TopTabs'; import { QuickSwitcher } from './components/QuickSwitcher'; import { VaultView } from './components/VaultView'; import { TerminalLayer } from './components/TerminalLayer'; -import { Host } from './types'; +import ProtocolSelectDialog from './components/ProtocolSelectDialog'; +import { Host, HostProtocol } from './types'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './components/ui/dialog'; import { Button } from './components/ui/button'; import { Input } from './components/ui/input'; @@ -37,6 +38,8 @@ function App() { const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [isQuickSwitcherOpen, setIsQuickSwitcherOpen] = useState(false); const [quickSearch, setQuickSearch] = useState(''); + // Protocol selection dialog state for QuickSwitcher + const [protocolSelectHost, setProtocolSelectHost] = useState(null); const { theme, @@ -131,6 +134,47 @@ function App() { updateHosts(hosts.filter(h => h.id !== hostId)); }, [hosts, updateHosts]); + // Check if host has multiple protocols enabled + const hasMultipleProtocols = useCallback((host: Host) => { + let count = 0; + // SSH is always available as base protocol (unless explicitly set to something else) + if (host.protocol === 'ssh' || !host.protocol) count++; + // Mosh adds another option + if (host.moshEnabled) count++; + // Telnet adds another option + if (host.telnetEnabled) count++; + // If protocol is explicitly telnet (not ssh), count it + if (host.protocol === 'telnet' && !host.telnetEnabled) count++; + return count > 1; + }, []); + + // Handle host connect with protocol selection (used by QuickSwitcher) + const handleHostConnectWithProtocolCheck = useCallback((host: Host) => { + if (hasMultipleProtocols(host)) { + setProtocolSelectHost(host); + setIsQuickSwitcherOpen(false); + setQuickSearch(''); + } else { + connectToHost(host); + setIsQuickSwitcherOpen(false); + setQuickSearch(''); + } + }, [hasMultipleProtocols, connectToHost]); + + // Handle protocol selection from dialog + const handleProtocolSelect = useCallback((protocol: HostProtocol, port: number) => { + if (protocolSelectHost) { + const hostWithProtocol: Host = { + ...protocolSelectHost, + protocol: protocol === 'mosh' ? 'ssh' : protocol, + port, + moshEnabled: protocol === 'mosh', + }; + connectToHost(hostWithProtocol); + setProtocolSelectHost(null); + } + }, [protocolSelectHost, connectToHost]); + const handleToggleTheme = useCallback(() => { setTheme(prev => prev === 'dark' ? 'light' : 'dark'); }, [setTheme]); @@ -229,11 +273,7 @@ function App() { sessions={sessions} workspaces={workspaces} onQueryChange={setQuickSearch} - onSelect={(host) => { - connectToHost(host); - setIsQuickSwitcherOpen(false); - setQuickSearch(''); - }} + onSelect={handleHostConnectWithProtocolCheck} onSelectTab={(tabId) => { setActiveTabId(tabId); setIsQuickSwitcherOpen(false); @@ -295,6 +335,15 @@ function App() { terminalThemeId={terminalThemeId} onTerminalThemeChange={setTerminalThemeId} /> + + {/* Protocol Select Dialog for QuickSwitcher */} + {protocolSelectHost && ( + setProtocolSelectHost(null)} + /> + )} ); } diff --git a/application/state/useSessionState.ts b/application/state/useSessionState.ts index 6f86853b0..e1bf6dc81 100644 --- a/application/state/useSessionState.ts +++ b/application/state/useSessionState.ts @@ -45,6 +45,10 @@ export const useSessionState = () => { hostname: host.hostname, username: host.username, status: 'connecting', + // Store connection-time protocol settings from the host object + protocol: host.protocol, + port: host.port, + moshEnabled: host.moshEnabled, }; setSessions(prev => [...prev, newSession]); setActiveTabId(newSession.id); diff --git a/components/HostDetailsPanel.tsx b/components/HostDetailsPanel.tsx index cacd037c8..1f9451247 100644 --- a/components/HostDetailsPanel.tsx +++ b/components/HostDetailsPanel.tsx @@ -108,7 +108,13 @@ const HostDetailsPanel: React.FC = ({ useEffect(() => { if (initialData) { - setForm(initialData); + // Ensure telnetEnabled is set when protocol is telnet + const updatedData = { ...initialData }; + if (initialData.protocol === 'telnet' && !initialData.telnetEnabled) { + updatedData.telnetEnabled = true; + updatedData.telnetPort = initialData.telnetPort || initialData.port || 23; + } + setForm(updatedData); setGroupInputValue(initialData.group || ""); } }, [initialData]); @@ -1090,7 +1096,7 @@ const HostDetailsPanel: React.FC = ({ {/* Telnet Protocol Card */} - {form.telnetEnabled ? ( + {(form.telnetEnabled || form.protocol === 'telnet') ? (
diff --git a/components/QuickConnectWizard.tsx b/components/QuickConnectWizard.tsx index 9f012bcc2..bc242a0ef 100644 --- a/components/QuickConnectWizard.tsx +++ b/components/QuickConnectWizard.tsx @@ -162,13 +162,8 @@ const QuickConnectWizard: React.FC = ({ const handleContinue = () => { switch (step) { case 'protocol': - // If no username provided yet, go to username step - if (!target.username && !username) { - setStep('username'); - } else { - // Skip to auth step (known host check happens during connection) - setStep('auth'); - } + // Always go to username step to let user confirm/edit username + setStep('username'); break; case 'username': setStep('auth'); @@ -189,18 +184,11 @@ const QuickConnectWizard: React.FC = ({ setStep('protocol'); break; case 'knownhost': - if (!target.username) { - setStep('username'); - } else { - setStep('protocol'); - } + setStep('username'); break; case 'auth': - if (!target.username && !username) { - setStep('username'); - } else { - setStep('protocol'); - } + // Always go back to username step + setStep('username'); break; } }; @@ -224,6 +212,9 @@ const QuickConnectWizard: React.FC = ({ password: authMethod === 'password' ? password : undefined, identityFileId: authMethod === 'key' ? selectedKeyId || undefined : undefined, moshEnabled: protocol === 'mosh', + // Set telnet-specific fields when using telnet protocol + telnetEnabled: protocol === 'telnet', + telnetPort: protocol === 'telnet' ? effectivePort : undefined, }; // Save host if requested diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index e7b0d39f4..c506b7fe9 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -138,7 +138,15 @@ const TerminalLayerInner: React.FC = ({ for (const session of sessions) { const existingHost = hostMap.get(session.hostId); if (existingHost) { - map.set(session.id, existingHost); + // Apply session-time protocol overrides to the host + const hostWithOverrides: Host = { + ...existingHost, + // Use session protocol settings if provided (from connection-time selection) + protocol: session.protocol ?? existingHost.protocol, + port: session.port ?? existingHost.port, + moshEnabled: session.moshEnabled ?? existingHost.moshEnabled, + }; + map.set(session.id, hostWithOverrides); } else { // Create stable fallback host object map.set(session.id, { @@ -146,11 +154,12 @@ const TerminalLayerInner: React.FC = ({ label: session.hostLabel || 'Local Terminal', hostname: session.hostname || 'localhost', username: session.username || 'local', - port: 22, + port: session.port ?? 22, os: 'linux', group: '', tags: [], - protocol: 'local' as const, + protocol: session.protocol ?? 'local' as const, + moshEnabled: session.moshEnabled, }); } } diff --git a/domain/models.ts b/domain/models.ts index 504e36d5c..f1cf37601 100755 --- a/domain/models.ts +++ b/domain/models.ts @@ -173,6 +173,10 @@ export interface TerminalSession { status: 'connecting' | 'connected' | 'disconnected'; workspaceId?: string; startupCommand?: string; // Command to run after connection (for snippet runner) + // Connection-time protocol overrides (used instead of looking up from hosts) + protocol?: 'ssh' | 'telnet' | 'local'; + port?: number; + moshEnabled?: boolean; } export interface RemoteFile { diff --git a/electron/main.cjs b/electron/main.cjs index e76e1fa4c..22a9827d8 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -661,11 +661,13 @@ const registerSSHBridge = (win) => { const write = (_event, payload) => { const session = sessions.get(payload.sessionId); if (!session) return; - // SSH sessions use stream, local terminal uses proc + // SSH sessions use stream, local terminal uses proc, telnet-native uses socket if (session.stream) { session.stream.write(payload.data); } else if (session.proc) { session.proc.write(payload.data); + } else if (session.socket) { + session.socket.write(payload.data); } }; @@ -679,6 +681,19 @@ const registerSSHBridge = (win) => { } else if (session.proc) { // Local terminal - use resize session.proc.resize(payload.cols, payload.rows); + } else if (session.socket && session.type === 'telnet-native') { + // Telnet native - send NAWS if supported + session.cols = payload.cols; + session.rows = payload.rows; + // Send NAWS sub-negotiation + const TELNET = { IAC: 255, SB: 250, SE: 240, NAWS: 31 }; + const buf = Buffer.from([ + TELNET.IAC, TELNET.SB, TELNET.NAWS, + (payload.cols >> 8) & 0xff, payload.cols & 0xff, + (payload.rows >> 8) & 0xff, payload.rows & 0xff, + TELNET.IAC, TELNET.SE + ]); + session.socket.write(buf); } } catch (err) { console.warn("Resize failed", err); @@ -694,6 +709,8 @@ const registerSSHBridge = (win) => { session.conn?.end(); } else if (session.proc) { session.proc.kill(); + } else if (session.socket) { + session.socket.destroy(); } // Cleanup chain connections if any if (session.chainConnections) { @@ -707,64 +724,223 @@ const registerSSHBridge = (win) => { sessions.delete(payload.sessionId); }; - // Telnet session using node-pty to spawn system telnet + // Telnet session using native Node.js net module (no system telnet dependency) const startTelnet = async (event, options) => { const sessionId = options.sessionId || `telnet-${Date.now()}-${Math.random().toString(16).slice(2)}`; + const hostname = options.hostname; + const port = options.port || 23; const cols = options.cols || 80; const rows = options.rows || 24; - // Find telnet executable - let telnetCmd = 'telnet'; - if (process.platform === 'win32') { - telnetCmd = findExecutable('telnet') || 'telnet.exe'; - } + console.log(`[Telnet] Starting connection to ${hostname}:${port}`); - const args = [options.hostname]; - if (options.port && options.port !== 23) { - args.push(String(options.port)); - } + return new Promise((resolve, reject) => { + const socket = new net.Socket(); + let connected = false; - const env = { - ...process.env, - ...(options.env || {}), - TERM: 'xterm-256color', - LANG: options.charset || 'en_US.UTF-8', - }; - - try { - const proc = pty.spawn(telnetCmd, args, { - cols, - rows, - env, - cwd: os.homedir(), - }); - - const session = { - proc, - type: 'telnet', - webContentsId: event.sender.id, + // Telnet protocol constants + const TELNET = { + IAC: 255, // Interpret As Command + DONT: 254, + DO: 253, + WONT: 252, + WILL: 251, + SB: 250, // Sub-negotiation Begin + SE: 240, // Sub-negotiation End + // Options + ECHO: 1, + SUPPRESS_GO_AHEAD: 3, + STATUS: 5, + TERMINAL_TYPE: 24, + NAWS: 31, // Negotiate About Window Size + TERMINAL_SPEED: 32, + LINEMODE: 34, + NEW_ENVIRON: 39, }; - sessions.set(sessionId, session); - proc.onData((data) => { - const contents = electronModule.webContents.fromId(session.webContentsId); - contents?.send("nebula:data", { sessionId, data }); + // Send NAWS (window size) sub-negotiation + const sendWindowSize = () => { + const buf = Buffer.from([ + TELNET.IAC, TELNET.SB, TELNET.NAWS, + (cols >> 8) & 0xff, cols & 0xff, + (rows >> 8) & 0xff, rows & 0xff, + TELNET.IAC, TELNET.SE + ]); + socket.write(buf); + }; + + // Handle Telnet protocol negotiation + const handleTelnetNegotiation = (data) => { + const output = []; + let i = 0; + + while (i < data.length) { + if (data[i] === TELNET.IAC) { + if (i + 1 >= data.length) break; + + const cmd = data[i + 1]; + + if (cmd === TELNET.IAC) { + // Escaped IAC (255 255) -> output single 255 + output.push(255); + i += 2; + continue; + } + + if (cmd === TELNET.DO || cmd === TELNET.DONT || cmd === TELNET.WILL || cmd === TELNET.WONT) { + if (i + 2 >= data.length) break; + + const opt = data[i + 2]; + console.log(`[Telnet] Received: ${cmd === TELNET.DO ? 'DO' : cmd === TELNET.DONT ? 'DONT' : cmd === TELNET.WILL ? 'WILL' : 'WONT'} ${opt}`); + + // Respond to negotiation + if (cmd === TELNET.DO) { + if (opt === TELNET.NAWS) { + // We support NAWS + socket.write(Buffer.from([TELNET.IAC, TELNET.WILL, opt])); + sendWindowSize(); + } else if (opt === TELNET.TERMINAL_TYPE) { + socket.write(Buffer.from([TELNET.IAC, TELNET.WILL, opt])); + } else if (opt === TELNET.SUPPRESS_GO_AHEAD) { + socket.write(Buffer.from([TELNET.IAC, TELNET.WILL, opt])); + } else { + // Refuse other options + socket.write(Buffer.from([TELNET.IAC, TELNET.WONT, opt])); + } + } else if (cmd === TELNET.WILL) { + if (opt === TELNET.ECHO || opt === TELNET.SUPPRESS_GO_AHEAD) { + socket.write(Buffer.from([TELNET.IAC, TELNET.DO, opt])); + } else { + socket.write(Buffer.from([TELNET.IAC, TELNET.DONT, opt])); + } + } else if (cmd === TELNET.DONT) { + socket.write(Buffer.from([TELNET.IAC, TELNET.WONT, opt])); + } else if (cmd === TELNET.WONT) { + socket.write(Buffer.from([TELNET.IAC, TELNET.DONT, opt])); + } + + i += 3; + continue; + } + + if (cmd === TELNET.SB) { + // Sub-negotiation - find SE + let seIndex = i + 2; + while (seIndex < data.length - 1) { + if (data[seIndex] === TELNET.IAC && data[seIndex + 1] === TELNET.SE) { + break; + } + seIndex++; + } + + if (seIndex < data.length - 1) { + const subOpt = data[i + 2]; + console.log(`[Telnet] Sub-negotiation for option ${subOpt}`); + + // Handle terminal type request + if (subOpt === TELNET.TERMINAL_TYPE && data[i + 3] === 1) { + // Server is asking for terminal type (SEND = 1) + const termType = 'xterm-256color'; + const response = Buffer.concat([ + Buffer.from([TELNET.IAC, TELNET.SB, TELNET.TERMINAL_TYPE, 0]), // 0 = IS + Buffer.from(termType), + Buffer.from([TELNET.IAC, TELNET.SE]) + ]); + socket.write(response); + } + + i = seIndex + 2; + continue; + } + } + + // Unknown command, skip + i += 2; + continue; + } + + // Regular data + output.push(data[i]); + i++; + } + + return Buffer.from(output); + }; + + // Connection timeout + const connectTimeout = setTimeout(() => { + if (!connected) { + console.error(`[Telnet] Connection timeout to ${hostname}:${port}`); + socket.destroy(); + reject(new Error(`Connection timeout to ${hostname}:${port}`)); + } + }, 10000); + + socket.on('connect', () => { + connected = true; + clearTimeout(connectTimeout); + console.log(`[Telnet] Connected to ${hostname}:${port}`); + + const session = { + socket, + type: 'telnet-native', + webContentsId: event.sender.id, + cols, + rows, + }; + sessions.set(sessionId, session); + + resolve({ sessionId }); }); - proc.onExit((evt) => { + socket.on('data', (data) => { + const session = sessions.get(sessionId); + if (!session) return; + + // Process Telnet protocol and extract clean data + const cleanData = handleTelnetNegotiation(data); + + if (cleanData.length > 0) { + const contents = electronModule.webContents.fromId(session.webContentsId); + contents?.send("nebula:data", { sessionId, data: cleanData.toString('binary') }); + } + }); + + socket.on('error', (err) => { + console.error(`[Telnet] Socket error: ${err.message}`); + clearTimeout(connectTimeout); + + if (!connected) { + reject(new Error(`Failed to connect: ${err.message}`)); + } else { + const session = sessions.get(sessionId); + if (session) { + const contents = electronModule.webContents.fromId(session.webContentsId); + contents?.send("nebula:exit", { sessionId, exitCode: 1, error: err.message }); + } + sessions.delete(sessionId); + } + }); + + socket.on('close', (hadError) => { + console.log(`[Telnet] Connection closed${hadError ? ' with error' : ''}`); + clearTimeout(connectTimeout); + + const session = sessions.get(sessionId); + if (session) { + const contents = electronModule.webContents.fromId(session.webContentsId); + contents?.send("nebula:exit", { sessionId, exitCode: hadError ? 1 : 0 }); + } sessions.delete(sessionId); - const contents = electronModule.webContents.fromId(session.webContentsId); - contents?.send("nebula:exit", { sessionId, ...evt }); }); - return { sessionId }; - } catch (err) { - console.error("[Telnet] Failed to start telnet session:", err.message); - throw err; - } + // Connect + console.log(`[Telnet] Connecting to ${hostname}:${port}...`); + socket.connect(port, hostname); + }); }; // Mosh session using node-pty to spawn system mosh-client