1+ // index.js (backend Node.js)
12const WebSocket = require ( 'ws' ) ;
23const { Client } = require ( 'ssh2' ) ;
34
@@ -15,14 +16,23 @@ wss.on('connection', function connection(ws) {
1516 const data = JSON . parse ( message ) ;
1617 console . log ( "📥 Mensaje recibido del front:" , data ) ;
1718
19+ if ( ! data ?. type ) return ;
20+
1821 // 🔌 Conexión SSH
1922 if ( data . type === 'connect' ) {
20- const { host, port, username, password } = data . payload ;
23+ const payload = data . payload ;
24+
25+ if ( ! payload ) {
26+ console . error ( "❌ connect recibido sin payload" ) ;
27+ ws . send ( "❌ connect recibido sin payload\n" ) ;
28+ return ;
29+ }
30+
31+ const { host, port, username, password } = payload ;
2132
2233 if ( ! host || ! port || ! username || ! password ) {
2334 console . error ( "❌ Faltan datos de conexión SSH" ) ;
2435 ws . send ( "❌ Datos incompletos para conectar al servidor SSH\n" ) ;
25- ws . close ( ) ;
2636 return ;
2737 }
2838
@@ -35,32 +45,28 @@ wss.on('connection', function connection(ws) {
3545 if ( err ) {
3646 console . error ( "❌ Error al iniciar shell SSH:" , err ) ;
3747 ws . send ( "❌ Error al iniciar shell SSH\n" ) ;
38- ws . close ( ) ;
3948 return ;
4049 }
4150
4251 sshStream = stream ;
4352
4453 stream
45- . on ( 'data' , ( chunk ) => {
46- ws . send ( chunk . toString ( ) ) ;
47- } )
54+ . on ( 'data' , ( chunk ) => ws . send ( chunk . toString ( ) ) )
4855 . on ( 'close' , ( ) => {
4956 console . log ( "🔌 Shell cerrada" ) ;
5057 sshClient . end ( ) ;
5158 } ) ;
5259
53- stream . stderr ?. on ( 'data' , ( chunk ) => {
54- console . error ( "🛑 STDERR:" , chunk . toString ( ) ) ;
55- } ) ;
60+ stream . stderr ?. on ( 'data' , ( chunk ) =>
61+ console . error ( "🛑 STDERR:" , chunk . toString ( ) )
62+ ) ;
5663
5764 ws . send ( "🟢 Conectado al servidor SSH\n" ) ;
5865 } ) ;
5966 } )
6067 . on ( 'error' , ( err ) => {
6168 console . error ( "❌ Error en SSH:" , err ) ;
6269 ws . send ( `❌ Error de conexión SSH: ${ err . message } \n` ) ;
63- ws . close ( ) ;
6470 } )
6571 . on ( 'end' , ( ) => {
6672 console . log ( "🔚 Conexión SSH finalizada" ) ;
@@ -75,11 +81,9 @@ wss.on('connection', function connection(ws) {
7581 }
7682
7783 // 📐 Redimensionar ventana
78- if ( data . type === 'resize' ) {
84+ if ( data . type === 'resize' && sshStream && data . payload ) {
7985 const { cols, rows } = data . payload ;
80- if ( sshStream ) {
81- sshStream . setWindow ( rows , cols , rows * 24 , cols * 8 ) ;
82- }
86+ sshStream . setWindow ( rows , cols , rows * 24 , cols * 8 ) ;
8387 }
8488
8589 } catch ( err ) {
@@ -90,9 +94,7 @@ wss.on('connection', function connection(ws) {
9094
9195 ws . on ( 'close' , ( ) => {
9296 console . log ( "🔴 Cliente WebSocket desconectado" ) ;
93- if ( sshClient ) {
94- sshClient . end ( ) ;
95- }
97+ if ( sshClient ) sshClient . end ( ) ;
9698 } ) ;
9799
98100 ws . on ( 'error' , ( err ) => {
0 commit comments