Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passwords, Windows, and Error bubbling, oh my #21

Merged
merged 9 commits into from
May 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,17 @@ await sshConnection.executeCommand('uptime')

#### `new SSHConnection(options)`

Options are an object with following properties:
Options are an object with following properties:

* `username` (optional): The username used for your ssh connection (equivalent to `-l` option). If not set, it first looks for an `SSH_USERNAME` environment variable. If that is not set, it fallbacks to `USER` environment variable.
* `privateKey` (optional): Can be a `string` or `Buffer` that contains a private key. If not set, it fallbacks to `~/.ssh/id_rsa`
* `agentForward` (optional): Is a `boolean` which uses the `ssh-agent` for connection (defaults to `false`.
* `skipAutoPrivateKey` (optional): Don't try and read `~/.ssh/id_rsa` if no private key is provided
* `agentForward` (optional): Is a `boolean` which uses the `ssh-agent` for connection (defaults to `false`). If set defaults to the value of env.SSH_AUTH_SOCK (all platforms), then `pageant` [on Windows](https://github.com/mscdex/ssh2#client-methods) if no SSH_AUTH_SOCK is present.
* `agentSocket` (optional): Provide your own path to the SSH Agent Socket you want to use. Useful if your app doesn't have access to ENV directly.
* `endHost` (required): The host you want to end up on (connect to)
* `endPort` (optional): Port number of the server. Needed in case the server runs on a custom port (defaults to `22`)
* `bastionHost` (optional): You can specify a bastion host if you want
* `passphrase` (optional): You can specify the passphrase when you have an encrypted private key. If you don't specify the passphrase and you use an encrypted private key, you get prompted in the command line.
* `passphrase` (optional): You can specify the passphrase when you have an encrypted private key. If you don't specify the passphrase and you use an encrypted private key, you get prompted in the command line.

#### `connection.executeCommand(command: string): Promise<void>`

Expand Down
45 changes: 37 additions & 8 deletions src/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,15 @@ import * as debug from 'debug'

interface Options {
username?: string
password?: string
privateKey?: string | Buffer
agentForward? : boolean
bastionHost?: string
passphrase?: string
endPort?: number
endHost: string
agentSocket?: string,
skipAutoPrivateKey?: boolean
}

interface ForwardingOptions {
Expand All @@ -44,6 +47,7 @@ class SSHConnection {
private debug
private server
private connections: Client[] = []
private isWindows = process.platform === 'win32'

constructor(private options: Options) {
this.debug = debug('ssh')
Expand All @@ -53,8 +57,11 @@ class SSHConnection {
if (!options.endPort) {
this.options.endPort = 22
}
if (!options.privateKey) {
this.options.privateKey = fs.readFileSync(`${os.homedir()}${path.sep}.ssh${path.sep}id_rsa`)
if (!options.privateKey && !options.agentForward && !options.skipAutoPrivateKey) {
const defaultFilePath = path.join(os.homedir(), '.ssh', 'id_rsa' )
if (fs.existsSync(defaultFilePath)) {
this.options.privateKey = fs.readFileSync(defaultFilePath)
}
}
}

Expand Down Expand Up @@ -138,19 +145,31 @@ class SSHConnection {
private async connect(host: string, stream?: NodeJS.ReadableStream): Promise<Client> {
this.debug('Connecting to "%s"', host)
const connection = new Client()
return new Promise<Client>(async (resolve) => {
return new Promise<Client>(async (resolve, reject) => {

const options = {
host,
port: this.options.endPort,
username: this.options.username,
password: this.options.password,
privateKey: this.options.privateKey
}
if (this.options.agentForward) {
options['agentForward'] = true
// guaranteed to give the ssh agent sock if the agent is running
const agentSock = process.env['SSH_AUTH_SOCK']
if (agentSock === undefined) {
throw new Error('SSH Agent is not running and not set in the SSH_AUTH_SOCK env variable')

// see https://github.com/mscdex/ssh2#client for agents on Windows
// guaranteed to give the ssh agent sock if the agent is running (posix)
let agentDefault = process.env['SSH_AUTH_SOCK']
if (this.isWindows) {
// null or undefined
if (agentDefault == null) {
agentDefault = 'pageant'
}
}

const agentSock = this.options.agentSocket ? this.options.agentSocket : agentDefault
if (agentSock == null) {
throw new Error('SSH Agent Socket is not provided, or is not set in the SSH_AUTH_SOCK env variable')
}
options['agent'] = agentSock
}
Expand All @@ -160,11 +179,21 @@ class SSHConnection {
if (options.privateKey && options.privateKey.toString().toLowerCase().includes('encrypted')) {
options['passphrase'] = (this.options.passphrase) ? this.options.passphrase : await this.getPassphrase()
}
connection.connect(options)
connection.on('ready', () => {
this.connections.push(connection)
return resolve(connection)
})

connection.on('error', (error) => {
reject(error)
})
try {
connection.connect(options)
} catch (error) {
reject(error)
}


})
}

Expand Down