From b86f04f82ab2b3a5f9c8ae5166fd5c09dad01a6b Mon Sep 17 00:00:00 2001 From: "LAPTOP-O016UC3M\\Qi Chen" <16399091+binaricat@users.noreply.github.com> Date: Wed, 10 Dec 2025 17:26:48 +0800 Subject: [PATCH] Improves SSH auth failure handling and user feedback Enhances SSH connection logic to detect authentication failures and prompt users for credential re-entry with clear error messaging. Extends frontend dialog UX for retries and highlights errors. Adds backend event and IPC handling for auth failures and timeouts, improving reliability and troubleshooting for multi-hop scenarios. --- components/Terminal.tsx | 45 ++++++++++++++++++++++++++++++++------ electron/main.cjs | 48 +++++++++++++++++++++++++++++++++++++---- electron/preload.cjs | 20 +++++++++++++++++ global.d.ts | 4 ++++ 4 files changed, 107 insertions(+), 10 deletions(-) diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 108338661..c48abef21 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -90,6 +90,7 @@ const TerminalComponent: React.FC = ({ // Auth dialog state for hosts without credentials const [needsAuth, setNeedsAuth] = useState(false); + const [authRetryMessage, setAuthRetryMessage] = useState(null); // Error message for auth retry const [authUsername, setAuthUsername] = useState(host.username || 'root'); const [authMethod, setAuthMethod] = useState<'password' | 'key'>('password'); const [authPassword, setAuthPassword] = useState(''); @@ -253,7 +254,8 @@ const TerminalComponent: React.FC = ({ // Connection timeline and timeout visuals useEffect(() => { - if (status !== 'connecting') return; + // Don't run timeout timer when showing auth dialog (user is entering credentials) + if (status !== 'connecting' || needsAuth) return; const scripted = [ 'Resolving host and keys...', 'Negotiating ciphers...', @@ -299,7 +301,7 @@ const TerminalComponent: React.FC = ({ clearTimeout(timeout); clearInterval(prog); }; - }, [status]); + }, [status, needsAuth]); const safeFit = () => { if (!fitAddonRef.current) return; @@ -595,14 +597,33 @@ const TerminalComponent: React.FC = ({ } } catch (err) { const message = err instanceof Error ? err.message : String(err); - setError(message); + + // Check if this is an authentication failure + const isAuthError = message.toLowerCase().includes('authentication') || + message.toLowerCase().includes('auth') || + message.toLowerCase().includes('password') || + message.toLowerCase().includes('permission denied'); + + if (isAuthError) { + // Show auth dialog for password retry + setError(null); // Clear error so we show auth dialog instead + setNeedsAuth(true); + setAuthRetryMessage('Authentication failed. Please check your credentials and try again.'); + setAuthPassword(''); // Clear password for re-entry + setProgressLogs(prev => [...prev, 'Authentication failed. Please try again.']); + // Stay in connecting state to show auth dialog + setStatus('connecting'); + } else { + setError(message); + term.writeln(`\r\n[Failed to start SSH: ${message}]`); + updateStatus('disconnected'); + } + setChainProgress(null); // Clear chain progress on error // Clean up chain progress listener on error if (unsubscribeChainProgress) { unsubscribeChainProgress(); } - term.writeln(`\r\n[Failed to start SSH: ${message}]`); - updateStatus('disconnected'); } // Trigger distro detection once connected (hidden exec, no terminal output) @@ -675,6 +696,7 @@ const TerminalComponent: React.FC = ({ const handleCancelConnect = () => { setIsCancelling(true); setNeedsAuth(false); + setAuthRetryMessage(null); // Clear auth retry message setNeedsHostKeyVerification(false); setPendingHostKeyInfo(null); setError('Connection cancelled'); @@ -730,6 +752,7 @@ const TerminalComponent: React.FC = ({ if (!termRef.current) return; cleanupSession(); setNeedsAuth(false); + setAuthRetryMessage(null); // Clear auth retry message pendingAuthRef.current = null; setStatus('connecting'); setError(null); @@ -773,6 +796,7 @@ const TerminalComponent: React.FC = ({ // Hide auth dialog and start connection setNeedsAuth(false); + setAuthRetryMessage(null); // Clear any previous auth error message setStatus('connecting'); setProgressLogs(['Authenticating with provided credentials...']); @@ -1035,6 +1059,14 @@ const TerminalComponent: React.FC = ({ + {/* Auth retry error message */} + {authRetryMessage && ( +
+ + {authRetryMessage} +
+ )} +
@@ -1056,7 +1088,8 @@ const TerminalComponent: React.FC = ({ value={authPassword} onChange={(e) => setAuthPassword(e.target.value)} placeholder="Enter password" - className="pr-10" + className={cn("pr-10", authRetryMessage && "border-destructive/50")} + autoFocus={!!authRetryMessage} onKeyDown={(e) => { if (e.key === 'Enter' && authUsername.trim() && authPassword.trim()) { handleAuthSubmit(); diff --git a/electron/main.cjs b/electron/main.cjs index 8c82d02f4..94f3137dc 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -333,7 +333,7 @@ const registerSSHBridge = (win) => { host: jump.hostname, port: jump.port || 22, username: jump.username || 'root', - readyTimeout: 30000, + readyTimeout: 60000, keepaliveInterval: 5000, algorithms: { cipher: ['aes128-gcm@openssh.com', 'aes256-gcm@openssh.com', 'aes128-ctr', 'aes256-ctr'], @@ -365,13 +365,20 @@ const registerSSHBridge = (win) => { // Connect this hop await new Promise((resolve, reject) => { conn.on('ready', () => { + console.log(`[Chain] Hop ${i + 1}/${totalHops}: ${hopLabel} connected`); sendProgress(i + 1, totalHops + 1, hopLabel, 'connected'); resolve(); }); conn.on('error', (err) => { + console.error(`[Chain] Hop ${i + 1}/${totalHops}: ${hopLabel} error:`, err.message); sendProgress(i + 1, totalHops + 1, hopLabel, 'error'); reject(err); }); + conn.on('timeout', () => { + console.error(`[Chain] Hop ${i + 1}/${totalHops}: ${hopLabel} timeout`); + reject(new Error(`Connection timeout to ${hopLabel}`)); + }); + console.log(`[Chain] Hop ${i + 1}/${totalHops}: Connecting to ${hopLabel}...`); conn.connect(connOpts); }); @@ -391,13 +398,16 @@ const registerSSHBridge = (win) => { } // Create forward stream to next hop + console.log(`[Chain] Hop ${i + 1}/${totalHops}: Forwarding from ${hopLabel} to ${nextHost}:${nextPort}...`); sendProgress(i + 1, totalHops + 1, hopLabel, 'forwarding'); currentSocket = await new Promise((resolve, reject) => { conn.forwardOut('127.0.0.1', 0, nextHost, nextPort, (err, stream) => { if (err) { + console.error(`[Chain] Hop ${i + 1}/${totalHops}: forwardOut from ${hopLabel} to ${nextHost}:${nextPort} FAILED:`, err.message); reject(err); return; } + console.log(`[Chain] Hop ${i + 1}/${totalHops}: forwardOut from ${hopLabel} to ${nextHost}:${nextPort} SUCCESS`); resolve(stream); }); }); @@ -450,7 +460,7 @@ const registerSSHBridge = (win) => { host: options.hostname, port: options.port || 22, username: options.username || "root", - readyTimeout: 30000, + readyTimeout: 60000, keepaliveInterval: 5000, algorithms: { cipher: ['aes128-gcm@openssh.com', 'aes256-gcm@openssh.com', 'aes128-ctr', 'aes256-ctr'], @@ -513,6 +523,7 @@ const registerSSHBridge = (win) => { return new Promise((resolve, reject) => { conn.on("ready", () => { + console.log(`[Chain] Final target ${options.hostname} ready`); if (hasJumpHosts || hasProxy) { sendProgress(totalHops, totalHops, options.hostname, 'connected'); } @@ -583,8 +594,24 @@ const registerSSHBridge = (win) => { }); conn.on("error", (err) => { - console.error("SSH connection error:", err.message); + console.error(`[Chain] Final target ${options.hostname} error:`, err.message); const contents = BrowserWindow.fromWebContents(event.sender)?.webContents; + + // Check if this is an authentication failure + const isAuthError = err.message?.toLowerCase().includes('authentication') || + err.message?.toLowerCase().includes('auth') || + err.message?.toLowerCase().includes('password') || + err.level === 'client-authentication'; + + if (isAuthError) { + // Send auth failed event so frontend can prompt for re-entry + contents?.send("nebula:auth:failed", { + sessionId, + error: err.message, + hostname: options.hostname + }); + } + contents?.send("nebula:exit", { sessionId, exitCode: 1, error: err.message }); sessions.delete(sessionId); // Cleanup chain connections @@ -594,6 +621,18 @@ const registerSSHBridge = (win) => { reject(err); }); + conn.on("timeout", () => { + console.error(`[Chain] Final target ${options.hostname} connection timeout`); + const err = new Error(`Connection timeout to ${options.hostname}`); + const contents = BrowserWindow.fromWebContents(event.sender)?.webContents; + contents?.send("nebula:exit", { sessionId, exitCode: 1, error: err.message }); + sessions.delete(sessionId); + for (const c of chainConnections) { + try { c.end(); } catch {} + } + reject(err); + }); + conn.on("close", () => { const contents = BrowserWindow.fromWebContents(event.sender)?.webContents; contents?.send("nebula:exit", { sessionId, exitCode: 0 }); @@ -604,10 +643,11 @@ const registerSSHBridge = (win) => { } }); + console.log(`[Chain] Connecting to final target ${options.hostname}...`); conn.connect(connectOpts); }); } catch (err) { - console.error("SSH chain connection error:", err.message); + console.error("[Chain] SSH chain connection error:", err.message); const contents = BrowserWindow.fromWebContents(event.sender)?.webContents; contents?.send("nebula:exit", { sessionId, exitCode: 1, error: err.message }); throw err; diff --git a/electron/preload.cjs b/electron/preload.cjs index 3a5555cdd..6eaec1fdd 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -6,6 +6,7 @@ const transferProgressListeners = new Map(); const transferCompleteListeners = new Map(); const transferErrorListeners = new Map(); const chainProgressListeners = new Map(); +const authFailedListeners = new Map(); ipcRenderer.on("nebula:data", (_event, payload) => { const set = dataListeners.get(payload.sessionId); @@ -47,6 +48,20 @@ ipcRenderer.on("nebula:chain:progress", (_event, payload) => { }); }); +// Authentication failed events +ipcRenderer.on("nebula:auth:failed", (_event, payload) => { + const set = authFailedListeners.get(payload.sessionId); + if (set) { + set.forEach((cb) => { + try { + cb(payload); + } catch (err) { + console.error("Auth failed callback failed", err); + } + }); + } +}); + // Transfer progress events ipcRenderer.on("nebula:transfer:progress", (_event, payload) => { const cb = transferProgressListeners.get(payload.transferId); @@ -190,6 +205,11 @@ const api = { exitListeners.get(sessionId).add(cb); return () => exitListeners.get(sessionId)?.delete(cb); }, + onAuthFailed: (sessionId, cb) => { + if (!authFailedListeners.has(sessionId)) authFailedListeners.set(sessionId, new Set()); + authFailedListeners.get(sessionId).add(cb); + return () => authFailedListeners.get(sessionId)?.delete(cb); + }, openSftp: async (options) => { const result = await ipcRenderer.invoke("nebula:sftp:open", options); return result.sftpId; diff --git a/global.d.ts b/global.d.ts index 5b419340d..8b86e81c7 100644 --- a/global.d.ts +++ b/global.d.ts @@ -119,6 +119,10 @@ interface NebulaBridge { sessionId: string, cb: (evt: { exitCode?: number; signal?: number }) => void ): () => void; + onAuthFailed?( + sessionId: string, + cb: (evt: { sessionId: string; error: string; hostname: string }) => void + ): () => void; // SFTP operations openSftp(options: NebulaSSHOptions): Promise;