steelbrain / node-ssh

SSH2 with Promises
MIT License
947 stars 94 forks source link

NodeSSH Reconnect Issue: isConnected() Returns TRUE Even When Connection Unsuccessful #459

Open kddige opened 1 year ago

kddige commented 1 year ago

I am encountering an issue which seems to be related to ISSUE-429, where the problem still persists. As im not aware of any pitfalls in the code, i have created a suggestion to resolve the issue.

Description:

The problem is caused by the assignment of the this.connection property before the connection promise resolves. Specifically, the this.connection property is being set before the connection.on('ready') event is triggered.

Proposed Solution: To resolve this issue, I suggest moving the assignment of this.connection inside the connection.on('ready') event in the connect method:

public async connect(givenConfig: Config): Promise<this> {
  // ... (Rest of the code remains the same)

  const connection = new SSH2.Client();

  await new Promise<void>((resolve, reject) => {
    connection.on('error', reject);
    if (config.onKeyboardInteractive) {
      connection.on('keyboard-interactive', config.onKeyboardInteractive);
    }
    connection.on('ready', () => {
      connection.removeListener('error', reject);
      this.connection = connection; // Move this line inside the 'ready' event
      resolve();
    });
    connection.on('end', () => {
      if (this.connection === connection) {
        this.connection = null;
      }
    });
    connection.on('close', () => {
      if (this.connection === connection) {
        this.connection = null;
      }
      reject(new SSHError('No response from server', 'ETIMEDOUT'));
    });
    connection.connect(config);
  });

  return this;
}

Will i help? Yeah, let us discuss and i can create a PR :)