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.
This commit is contained in:
LAPTOP-O016UC3M\Qi Chen committed 2025-12-10 17:26:48 +08:00
1 parent 6b41dccd8e
commit b86f04f82a
4 files changed
+107 -10

No files matched your search

+39 -6
View File
@@ -90,6 +90,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
// Auth dialog state for hosts without credentials
const [needsAuth, setNeedsAuth] = useState(false);
const [authRetryMessage, setAuthRetryMessage] = useState<string | null>(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<TerminalProps> = ({
// 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<TerminalProps> = ({
clearTimeout(timeout);
clearInterval(prog);
};
}, [status]);
}, [status, needsAuth]);
const safeFit = () => {
if (!fitAddonRef.current) return;
@@ -595,14 +597,33 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
} 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<TerminalProps> = ({
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<TerminalProps> = ({
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<TerminalProps> = ({
// 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<TerminalProps> = ({
</button>
</div>
{/* Auth retry error message */}
{authRetryMessage && (
<div className="p-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-center gap-2">
<AlertCircle size={16} />
{authRetryMessage}
</div>
)}
<div className="space-y-3">
<div className="space-y-2">
<Label htmlFor="auth-username">Username</Label>
@@ -1056,7 +1088,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
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();
+44 -4
View File
@@ -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;
+20
View File
@@ -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;
Vendored
+4
View File
@@ -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<string>;