feat(sshclient): add a promise-first SSH client with secure host verification and improve SSH key/config handling
This commit is contained in:
@@ -1,134 +1,430 @@
|
||||
# @push.rocks/smartssh
|
||||
setup SSH quickly and in a painless manner
|
||||
|
||||
Secure SSH configuration, key management, and remote machine control for modern TypeScript projects. `@push.rocks/smartssh` gives you two things in one focused package: safe local OpenSSH config/key orchestration and a promise-first SSH client for executing commands, opening shells, transferring files, and forwarding ports.
|
||||
|
||||
Built on top of the pure JavaScript `ssh2` engine, it keeps the low-level protocol details out of your application while still exposing the control you need for serious automation.
|
||||
|
||||
## Issue Reporting and Security
|
||||
|
||||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Install
|
||||
|
||||
To begin using `@push.rocks/smartssh` in your project, you'll need to install it via npm or yarn. You can do so by running one of the following commands:
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartssh --save
|
||||
pnpm add @push.rocks/smartssh
|
||||
```
|
||||
|
||||
or
|
||||
## What It Does
|
||||
|
||||
```bash
|
||||
yarn add @push.rocks/smartssh
|
||||
```
|
||||
- Manage SSH keys as typed `SshKey` objects.
|
||||
- Generate OpenSSH-compatible config files with secure defaults.
|
||||
- Read managed key material back from disk.
|
||||
- Connect to remote machines with `SshClient`.
|
||||
- Execute commands and collect stdout, stderr, exit code, and signal.
|
||||
- Stream long-running commands or start interactive shells.
|
||||
- Use SFTP for uploads, downloads, file reads, writes, stats, permissions, and directory operations.
|
||||
- Forward TCP connections through SSH.
|
||||
- Verify host keys by SHA256 or MD5 fingerprints, with explicit opt-out for disposable test systems.
|
||||
|
||||
## Usage
|
||||
|
||||
`@push.rocks/smartssh` is a powerful package designed to simplify SSH configurations, key management, and interaction in a Typescript environment, using ESM syntax. This guide will cover how to utilize the primary functionalities provided by the package.
|
||||
|
||||
#### Setting Up an SSH Instance
|
||||
|
||||
An SSH instance represents your SSH configurations, including the keys and the SSH directory. Here's how to create an instance:
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { SshInstance } from '@push.rocks/smartssh';
|
||||
import { SshClient, SshKey } from '@push.rocks/smartssh';
|
||||
|
||||
const mySshInstance = new SshInstance({
|
||||
sshDirPath: '/path/to/.ssh', // Optional: specify SSH directory path
|
||||
sshSync: true, // Optional: keep the instance in sync with the SSH directory automatically
|
||||
const privateKey = SshKey.fromFile('/home/deploy/.ssh/id_ed25519');
|
||||
|
||||
const sshClient = await SshClient.connect({
|
||||
host: 'server.example.com',
|
||||
username: 'deploy',
|
||||
privateKey,
|
||||
trustedHostFingerprints: ['SHA256:replaceWithYourKnownHostFingerprint'],
|
||||
});
|
||||
|
||||
const result = await sshClient.exec('uname -a');
|
||||
|
||||
console.log(result.code);
|
||||
console.log(result.stdout);
|
||||
console.error(result.stderr);
|
||||
|
||||
await sshClient.close();
|
||||
```
|
||||
|
||||
## Secure Defaults
|
||||
|
||||
`smartssh` is intentionally conservative:
|
||||
|
||||
- SSH config generation writes `StrictHostKeyChecking yes` by default.
|
||||
- `SshClient.connect()` requires host validation by default.
|
||||
- Private key files are written with `0600` permissions.
|
||||
- Public key files are written with `0644` permissions.
|
||||
- SSH directories are created with `0700` permissions.
|
||||
- Host aliases are validated before they are used as filenames or config entries.
|
||||
|
||||
For local throwaway test servers you can explicitly opt out of host checking:
|
||||
|
||||
```typescript
|
||||
const sshClient = await SshClient.connect({
|
||||
host: '127.0.0.1',
|
||||
username: 'tester',
|
||||
password: 'secret',
|
||||
strictHostKeyChecking: false,
|
||||
});
|
||||
```
|
||||
|
||||
#### Working with SSH Keys
|
||||
Do not disable host checking for production infrastructure unless another trust layer is already enforcing host identity.
|
||||
|
||||
SSH keys can be managed using the `SshKey` class. You can add, remove, or retrieve keys from your SSH instance.
|
||||
## Key Management
|
||||
|
||||
Create keys in memory:
|
||||
|
||||
```typescript
|
||||
import { SshKey } from '@push.rocks/smartssh';
|
||||
|
||||
// Creating a new SSH key
|
||||
const mySshKey = new SshKey({
|
||||
host: 'github.com', // Hostname
|
||||
private: 'privateKeyString', // Private key string
|
||||
public: 'publicKeyString', // Optional: public key string
|
||||
authorized: false // Optional: Is this key authorized? Defaults to false
|
||||
const githubKey = new SshKey({
|
||||
host: 'github.com',
|
||||
private: process.env.GITHUB_PRIVATE_KEY,
|
||||
public: process.env.GITHUB_PUBLIC_KEY,
|
||||
});
|
||||
|
||||
// Adding the SSH key to the instance
|
||||
mySshInstance.addKey(mySshKey);
|
||||
|
||||
// Getting an SSH key by host
|
||||
const githubKey = mySshInstance.getKey('github.com');
|
||||
|
||||
// Removing an SSH key by instance
|
||||
mySshInstance.removeKey(githubKey);
|
||||
console.log(githubKey.type); // 'duplex', 'private', 'public', or undefined
|
||||
console.log(githubKey.privKeyBase64);
|
||||
```
|
||||
|
||||
#### Syncing Keys with the File System
|
||||
|
||||
`@push.rocks/smartssh` makes it easy to synchronize your SSH keys with the file system, keeping your actual SSH configuration and your program state in alignment.
|
||||
Load keys from files:
|
||||
|
||||
```typescript
|
||||
// To write the current state to the SSH directory
|
||||
mySshInstance.writeToDisk();
|
||||
const deployKey = SshKey.fromFile('/home/deploy/.ssh/id_ed25519');
|
||||
|
||||
// To read and synchronize the state from the SSH directory
|
||||
mySshInstance.readFromDisk();
|
||||
const combinedKey = SshKey.fromFiles({
|
||||
host: 'production-app',
|
||||
privateKeyPath: '/home/deploy/.ssh/production-app',
|
||||
publicKeyPath: '/home/deploy/.ssh/production-app.pub',
|
||||
});
|
||||
```
|
||||
|
||||
#### Advanced Key Management
|
||||
Store keys safely:
|
||||
|
||||
- **Encoding and Decoding**: Keys can be encoded in `base64` for easier environment variable storage.
|
||||
- **Key Type Detection**: The package can detect and handle private, public, or both keys present scenarios (`duplex`).
|
||||
- **Custom SSH Directory**: Support for custom SSH directory locations.
|
||||
- **Automatic Syncing**: Optionally keep the SSH instance automatically synced with the SSH directory on modifications.
|
||||
```typescript
|
||||
await combinedKey.store('/home/deploy/.ssh');
|
||||
```
|
||||
|
||||
### Comprehensive Example
|
||||
## OpenSSH Config Management
|
||||
|
||||
Below is a comprehensive example demonstrating SSH instance creation, adding a new SSH key, and syncing with the filesystem.
|
||||
Use `SshInstance` when you want to manage a whole SSH directory and config file.
|
||||
|
||||
```typescript
|
||||
import { SshInstance, SshKey } from '@push.rocks/smartssh';
|
||||
|
||||
async function setupSsh() {
|
||||
// Initialize the SSH instance
|
||||
const sshInstance = new SshInstance({
|
||||
sshDirPath: '/custom/path/to/.ssh',
|
||||
sshSync: true,
|
||||
});
|
||||
const sshInstance = new SshInstance({
|
||||
sshDirPath: '/home/deploy/.ssh',
|
||||
strictHostKeyChecking: true,
|
||||
});
|
||||
|
||||
// Create a new SSH key
|
||||
const newSshKey = new SshKey({
|
||||
host: 'my.custom.server.com',
|
||||
private: 'myPrivateKeyInBase64',
|
||||
public: 'myPublicKeyInBase64',
|
||||
});
|
||||
sshInstance.addKey(
|
||||
new SshKey({
|
||||
host: 'git.example.com',
|
||||
private: process.env.GIT_PRIVATE_KEY,
|
||||
public: process.env.GIT_PUBLIC_KEY,
|
||||
})
|
||||
);
|
||||
|
||||
// Add the new key to the instance
|
||||
sshInstance.addKey(newSshKey);
|
||||
sshInstance.writeToDisk();
|
||||
```
|
||||
|
||||
// Optionally, write to disk immediately
|
||||
sshInstance.writeToDisk();
|
||||
Generated config example:
|
||||
|
||||
```sshconfig
|
||||
Host git.example.com
|
||||
HostName git.example.com
|
||||
IdentityFile /home/deploy/.ssh/git.example.com
|
||||
StrictHostKeyChecking yes
|
||||
```
|
||||
|
||||
Read keys back from disk:
|
||||
|
||||
```typescript
|
||||
const existingSsh = new SshInstance({
|
||||
sshDirPath: '/home/deploy/.ssh',
|
||||
});
|
||||
|
||||
existingSsh.readFromDisk();
|
||||
|
||||
const key = existingSsh.getKey('git.example.com');
|
||||
console.log(key?.pubKey);
|
||||
```
|
||||
|
||||
## Remote Command Execution
|
||||
|
||||
`exec()` waits for the remote command to finish and returns a structured result.
|
||||
|
||||
```typescript
|
||||
const result = await sshClient.exec('systemctl is-active nginx', {
|
||||
timeout: 10_000,
|
||||
});
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr);
|
||||
}
|
||||
|
||||
// Running the SSH setup
|
||||
setupSsh().then(() => {
|
||||
console.log('SSH setup complete.');
|
||||
}).catch((error) => {
|
||||
console.error('SSH setup failed:', error);
|
||||
console.log(result.stdout.trim());
|
||||
```
|
||||
|
||||
Send input to a command:
|
||||
|
||||
```typescript
|
||||
const result = await sshClient.exec('cat > /tmp/message.txt', {
|
||||
input: 'hello from smartssh\n',
|
||||
});
|
||||
```
|
||||
|
||||
This guide should provide a robust start to managing SSH configurations using `@push.rocks/smartssh`. Whether for individual projects or shared across a team, this package offers a streamlined approach to handling SSH keys, config synchronization, and more, all within a TypeScript project.
|
||||
Abort or time-limit a command:
|
||||
|
||||
```typescript
|
||||
const abortController = new AbortController();
|
||||
|
||||
setTimeout(() => abortController.abort(), 5_000);
|
||||
|
||||
await sshClient.exec('sleep 60', {
|
||||
signal: abortController.signal,
|
||||
});
|
||||
```
|
||||
|
||||
## Streaming Commands and Shells
|
||||
|
||||
Use `stream()` for long-running commands where you want to handle output as it arrives.
|
||||
|
||||
```typescript
|
||||
const stream = await sshClient.stream('tail -f /var/log/syslog');
|
||||
|
||||
stream.on('data', (chunk) => {
|
||||
process.stdout.write(chunk);
|
||||
});
|
||||
|
||||
stream.stderr.on('data', (chunk) => {
|
||||
process.stderr.write(chunk);
|
||||
});
|
||||
```
|
||||
|
||||
Start an interactive shell:
|
||||
|
||||
```typescript
|
||||
const shell = await sshClient.shell({
|
||||
window: {
|
||||
rows: 40,
|
||||
cols: 120,
|
||||
term: 'xterm-256color',
|
||||
},
|
||||
});
|
||||
|
||||
shell.write('whoami\n');
|
||||
shell.write('exit\n');
|
||||
```
|
||||
|
||||
## SFTP
|
||||
|
||||
Create an SFTP client from an active SSH connection:
|
||||
|
||||
```typescript
|
||||
const sftp = await sshClient.sftp();
|
||||
```
|
||||
|
||||
Upload and download files:
|
||||
|
||||
```typescript
|
||||
await sftp.upload({
|
||||
localPath: './dist/app.tar.gz',
|
||||
remotePath: '/tmp/app.tar.gz',
|
||||
});
|
||||
|
||||
await sftp.download({
|
||||
remotePath: '/var/log/app.log',
|
||||
localPath: './app.log',
|
||||
});
|
||||
```
|
||||
|
||||
Read and write remote files:
|
||||
|
||||
```typescript
|
||||
const osRelease = await sftp.readFile('/etc/os-release', 'utf8');
|
||||
|
||||
await sftp.writeFile('/tmp/deploy.json', JSON.stringify({
|
||||
version: '1.2.3',
|
||||
}));
|
||||
```
|
||||
|
||||
Inspect and manage remote paths:
|
||||
|
||||
```typescript
|
||||
const files = await sftp.readdir('/var/www');
|
||||
const stats = await sftp.stat('/var/www/app');
|
||||
|
||||
await sftp.mkdir('/tmp/smartssh');
|
||||
await sftp.chmod('/tmp/smartssh', 0o755);
|
||||
await sftp.rename('/tmp/old-name', '/tmp/new-name');
|
||||
await sftp.remove('/tmp/new-name');
|
||||
```
|
||||
|
||||
## Port Forwarding
|
||||
|
||||
Open a direct TCP channel through the SSH server:
|
||||
|
||||
```typescript
|
||||
const channel = await sshClient.forwardOut({
|
||||
destinationHost: '127.0.0.1',
|
||||
destinationPort: 5432,
|
||||
});
|
||||
|
||||
channel.write('raw tcp payload');
|
||||
```
|
||||
|
||||
Ask the remote SSH server to listen and forward incoming TCP connections:
|
||||
|
||||
```typescript
|
||||
const forward = await sshClient.forwardIn({
|
||||
remoteHost: '127.0.0.1',
|
||||
remotePort: 0,
|
||||
});
|
||||
|
||||
console.log(`Remote port: ${forward.remotePort}`);
|
||||
|
||||
await forward.close();
|
||||
```
|
||||
|
||||
## API Overview
|
||||
|
||||
### `SshClient`
|
||||
|
||||
- `SshClient.connect(profile)` creates and connects a client in one step.
|
||||
- `connect()` opens the SSH connection for an existing instance.
|
||||
- `exec(command, options)` runs a command and returns `ISshExecResult`.
|
||||
- `stream(command, options)` opens a command channel for streaming output.
|
||||
- `shell(options)` starts an interactive shell channel.
|
||||
- `sftp()` returns a typed `SshSftpClient`.
|
||||
- `forwardOut(options)` opens a direct TCP channel through SSH.
|
||||
- `forwardIn(options)` creates a remote listener and returns a closeable handle.
|
||||
- `close()` ends the connection.
|
||||
- `fingerprintSha256(key)` and `fingerprintMd5(key)` generate comparable host key fingerprints.
|
||||
|
||||
### `SshSftpClient`
|
||||
|
||||
- `upload({ localPath, remotePath })`
|
||||
- `download({ remotePath, localPath })`
|
||||
- `readFile(remotePath, encoding?)`
|
||||
- `writeFile(remotePath, data)`
|
||||
- `readdir(remotePath)`
|
||||
- `stat(remotePath)` and `lstat(remotePath)`
|
||||
- `mkdir(remotePath, attributes?)`
|
||||
- `chmod(remotePath, mode)`
|
||||
- `rename(sourcePath, destinationPath)`
|
||||
- `remove(remotePath)` and `rmdir(remotePath)`
|
||||
|
||||
### `SshKey`
|
||||
|
||||
- Construct with `{ host, private, public, authorized }`.
|
||||
- Read and write private/public key strings.
|
||||
- Encode and decode key material with `privKeyBase64` and `pubKeyBase64`.
|
||||
- Load keys from disk with `fromFile()` or `fromFiles()`.
|
||||
- Store keys to disk with safe permissions via `store()`.
|
||||
- Inspect `type` as `duplex`, `private`, `public`, or `undefined`.
|
||||
|
||||
### `SshInstance`
|
||||
|
||||
- `addKey(key)`, `removeKey(key)`, and `replaceKey(oldKey, newKey)` manage key collections.
|
||||
- `getKey(host)` retrieves a managed key by host alias.
|
||||
- `sshKeys` exposes the current key array.
|
||||
- `writeToDisk(dirPath?)` writes keys and config.
|
||||
- `readFromDisk(dirPath?)` reads key files from an SSH directory.
|
||||
- `sshSync: true` keeps disk state in sync on key changes.
|
||||
|
||||
### `SshConfig`
|
||||
|
||||
- `store(dirPath)` writes an OpenSSH config file.
|
||||
- `read(dirPath)` reads the config file.
|
||||
- `parse(dirPath)` parses host blocks from a config file.
|
||||
- `SshConfig.parse(configString)` parses host blocks from a string.
|
||||
|
||||
## Types You Will Usually Import
|
||||
|
||||
```typescript
|
||||
import type {
|
||||
ISshProfile,
|
||||
ISshExecOptions,
|
||||
ISshExecResult,
|
||||
ISshUploadOptions,
|
||||
ISshDownloadOptions,
|
||||
ISshForwardInHandle,
|
||||
ISshForwardInOptions,
|
||||
ISshForwardOutOptions,
|
||||
ISshShellOptions,
|
||||
TSshHostVerifier,
|
||||
} from '@push.rocks/smartssh';
|
||||
```
|
||||
|
||||
## Real-World Flow
|
||||
|
||||
```typescript
|
||||
import { SshClient, SshKey } from '@push.rocks/smartssh';
|
||||
|
||||
const key = SshKey.fromFile('/home/deploy/.ssh/production');
|
||||
|
||||
const server = await SshClient.connect({
|
||||
host: 'app-01.example.com',
|
||||
username: 'deploy',
|
||||
privateKey: key,
|
||||
trustedHostFingerprints: ['SHA256:replaceWithTheRealFingerprint'],
|
||||
keepaliveInterval: 30_000,
|
||||
});
|
||||
|
||||
try {
|
||||
const sftp = await server.sftp();
|
||||
|
||||
await sftp.upload({
|
||||
localPath: './release.tar.gz',
|
||||
remotePath: '/tmp/release.tar.gz',
|
||||
});
|
||||
|
||||
const deploy = await server.exec([
|
||||
'set -e',
|
||||
'mkdir -p /srv/app',
|
||||
'tar -xzf /tmp/release.tar.gz -C /srv/app',
|
||||
'systemctl restart app',
|
||||
].join(' && '), {
|
||||
timeout: 120_000,
|
||||
});
|
||||
|
||||
if (deploy.code !== 0) {
|
||||
throw new Error(deploy.stderr);
|
||||
}
|
||||
} finally {
|
||||
await server.close();
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- The package is ESM-first and intended for TypeScript projects.
|
||||
- `ssh2` is used directly as the SSH protocol engine.
|
||||
- Config generation is intentionally simple and focused on managed host/key entries.
|
||||
- `readFromDisk()` reads key files from the SSH directory; it does not attempt to preserve or rewrite arbitrary user-managed config comments.
|
||||
- Host aliases are intentionally restricted to filename-safe values to avoid path traversal and config injection.
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||||
|
||||
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
||||
Reference in New Issue
Block a user