feat(sshclient): add a promise-first SSH client with secure host verification and improve SSH key/config handling

This commit is contained in:
2026-05-02 09:43:21 +00:00
parent 4a97d63c04
commit 3b20db79d0
17 changed files with 1332 additions and 170 deletions
+3 -3
View File
@@ -9,8 +9,8 @@
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartssh",
"shortDescription": "SSH configuration utilities",
"description": "A library for setting up SSH configuration quickly and painlessly.",
"shortDescription": "SSH automation utilities",
"description": "Secure SSH configuration, key management, and remote machine control for TypeScript.",
"npmPackagename": "@push.rocks/smartssh",
"license": "MIT",
"keywords": [
@@ -33,6 +33,6 @@
}
},
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.\n\n**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.\n\n### Trademarks\n\nThis 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.\n\nUse 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District Court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
}
}
+7
View File
@@ -1,5 +1,12 @@
# Changelog
## 2026-05-02 - 2.1.0 - feat(sshclient)
add a promise-first SSH client with secure host verification and improve SSH key/config handling
- introduces SshClient and SshSftpClient for command execution, shells, file transfer, and port forwarding using ssh2
- adds strict host key verification defaults with fingerprint-based trust options and explicit opt-out for test systems
- implements SSH directory and key loading from disk, host alias validation, and safer file permissions for keys and config
## 2026-05-01 - 2.0.3 - fix(ssh)
modernize filesystem handling and package exports for NodeNext compatibility
View File
+3 -3
View File
@@ -9,8 +9,8 @@
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartssh",
"shortDescription": "SSH configuration utilities",
"description": "A library for setting up SSH configuration quickly and painlessly.",
"shortDescription": "SSH automation utilities",
"description": "Secure SSH configuration, key management, and remote machine control for TypeScript.",
"npmPackagename": "@push.rocks/smartssh",
"license": "MIT",
"keywords": [
@@ -33,6 +33,6 @@
}
},
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.\n\n**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.\n\n### Trademarks\n\nThis 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.\n\nUse 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District Court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
}
}
+3 -3
View File
@@ -2,7 +2,7 @@
"name": "@push.rocks/smartssh",
"version": "2.0.3",
"private": false,
"description": "A library for setting up SSH configuration quickly and painlessly.",
"description": "Secure SSH configuration, key management, and remote machine control for TypeScript.",
"exports": {
".": "./dist_ts/index.js"
},
@@ -44,7 +44,7 @@
"@types/ssh2": "^1.15.5",
"fs-extra": "^11.3.4",
"minimatch": "^10.2.5",
"node-ssh": "^13.2.1"
"ssh2": "^1.17.0"
},
"devDependencies": {
"@git.zone/tsbuild": "^4.4.0",
@@ -61,7 +61,7 @@
"assets/**/*",
"cli.js",
".smartconfig.json",
"LICENSE",
"license",
"npmextra.json",
"readme.md"
],
+3 -41
View File
@@ -32,9 +32,9 @@ importers:
minimatch:
specifier: ^10.2.5
version: 10.2.5
node-ssh:
specifier: ^13.2.1
version: 13.2.1
ssh2:
specifier: ^1.17.0
version: 1.17.0
devDependencies:
'@git.zone/tsbuild':
specifier: ^4.4.0
@@ -2215,10 +2215,6 @@ packages:
resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}
engines: {node: '>=12'}
is-stream@2.0.1:
resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}
engines: {node: '>=8'}
is-stream@4.0.1:
resolution: {integrity: sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==}
engines: {node: '>=18'}
@@ -2563,10 +2559,6 @@ packages:
resolution: {integrity: sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ==}
engines: {node: '>= 6.13.0'}
node-ssh@13.2.1:
resolution: {integrity: sha512-rfl4GWMygQfzlExPkQ2LWyya5n2jOBm5vhEnup+4mdw7tQhNpJWbP5ldr09Jfj93k5SfY5lxcn8od5qrQ/6mBg==}
engines: {node: '>= 10'}
object-keys@1.1.1:
resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}
engines: {node: '>= 0.4'}
@@ -2840,14 +2832,6 @@ packages:
resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==}
engines: {node: '>=11.0.0'}
sb-promise-queue@2.1.1:
resolution: {integrity: sha512-qXfdcJQMxMljxmPprn4Q4hl3pJmoljSCzUvvEBa9Kscewnv56n0KqrO6yWSrGLOL9E021wcGdPa39CHGKA6G0w==}
engines: {node: '>= 8'}
sb-scandir@3.1.1:
resolution: {integrity: sha512-Q5xiQMtoragW9z8YsVYTAZcew+cRzdVBefPbb9theaIKw6cBo34WonP9qOCTKgyAmn/Ch5gmtAxT/krUgMILpA==}
engines: {node: '>= 8'}
semver@6.3.1:
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
@@ -2873,9 +2857,6 @@ packages:
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
engines: {node: '>=8'}
shell-escape@0.2.0:
resolution: {integrity: sha512-uRRBT2MfEOyxuECseCZd28jC1AJ8hmqqneWQ4VWUTgCAFvb3wKU1jLqj6egC4Exrr88ogg3dp+zroH4wJuaXzw==}
signal-exit@3.0.7:
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
@@ -6435,8 +6416,6 @@ snapshots:
is-plain-obj@4.1.0: {}
is-stream@2.0.1: {}
is-stream@4.0.1: {}
is-unicode-supported@2.1.0: {}
@@ -6988,15 +6967,6 @@ snapshots:
node-forge@1.4.0: {}
node-ssh@13.2.1:
dependencies:
is-stream: 2.0.1
make-dir: 3.1.0
sb-promise-queue: 2.1.1
sb-scandir: 3.1.1
shell-escape: 0.2.0
ssh2: 1.17.0
object-keys@1.1.1: {}
oblivious-set@2.0.0: {}
@@ -7319,12 +7289,6 @@ snapshots:
sax@1.6.0: {}
sb-promise-queue@2.1.1: {}
sb-scandir@3.1.1:
dependencies:
sb-promise-queue: 2.1.1
semver@6.3.1: {}
semver@7.7.4: {}
@@ -7375,8 +7339,6 @@ snapshots:
shebang-regex@3.0.0: {}
shell-escape@0.2.0: {}
signal-exit@3.0.7: {}
signal-exit@4.1.0: {}
+371 -75
View File
@@ -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.
+124
View File
@@ -1,11 +1,65 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartssh from '../ts/index.js';
import fs from 'fs-extra';
import type { AddressInfo } from 'net';
import * as path from 'path';
import ssh2 from 'ssh2';
import type { Server as TSsh2Server } from 'ssh2';
const { Server, utils } = ssh2;
const testDir = path.join(process.cwd(), '.nogit/test/temp');
const configPath = path.join(testDir, 'config');
let testSshInstance: smartssh.SshInstance;
let testSshKey: smartssh.SshKey;
let testSshServer: TSsh2Server;
let testSshServerPort: number;
const createTestSshServer = async () => {
const hostKeys = [utils.generateKeyPairSync('ed25519').private];
const server = new Server({ hostKeys }, (client) => {
client.on('authentication', (ctx) => {
if (ctx.method === 'password' && ctx.username === 'tester' && ctx.password === 'secret') {
ctx.accept();
return;
}
ctx.reject();
});
client.on('ready', () => {
client.on('session', (accept) => {
const session = accept();
session.on('exec', (acceptExec, _rejectExec, info) => {
const stream = acceptExec();
if (info.command === 'printf smartssh') {
stream.write('smartssh\n');
stream.stderr.write('warn\n');
stream.exit(0);
stream.end();
return;
}
stream.stderr.write(`unknown command: ${info.command}\n`);
stream.exit(127);
stream.end();
});
});
});
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
const address = server.address() as AddressInfo;
return {
server,
port: address.port,
};
};
tap.test('should prepare a clean test directory', async () => {
await fs.emptyDir(testDir);
});
tap.test('should create a valid SshKey object', async () => {
testSshKey = new smartssh.SshKey({
host: 'example.com',
@@ -29,6 +83,18 @@ tap.test('.publicKeyBase64 should be public key base 64 encoded', async () => {
});
tap.test('.store() should store the file to disk', async () => {
await testSshKey.store(testDir);
const privateKeyMode = (await fs.stat(path.join(testDir, 'example.com'))).mode & 0o777;
const publicKeyMode = (await fs.stat(path.join(testDir, 'example.com.pub'))).mode & 0o777;
expect(privateKeyMode).toEqual(0o600);
expect(publicKeyMode).toEqual(0o644);
});
tap.test('.store() should reject unsafe host aliases', async () => {
expect(() => {
new smartssh.SshKey({
host: '../evil',
private: 'somePrivateKey',
});
}).toThrow();
});
// SSH INstance
@@ -85,6 +151,64 @@ tap.test('.removeKey() should remove a key', async () => {
tap.test('it should store to disk', async () => {
testSshInstance.writeToDisk();
const config = await fs.readFile(configPath, 'utf8');
expect(config).toInclude(`IdentityFile ${path.join(testDir, 'github.com')}`);
expect(config).toInclude('StrictHostKeyChecking yes');
expect(config).not.toInclude('StrictHostKeyChecking no');
});
tap.test('it should read keys back from disk', async () => {
const readBackInstance = new smartssh.SshInstance({ sshDirPath: testDir });
readBackInstance.readFromDisk();
const githubKey = readBackInstance.getKey('github.com');
expect(githubKey).toBeInstanceOf(smartssh.SshKey);
expect(githubKey?.privKey).toEqual('someGitHubPrivateKey');
expect(githubKey?.pubKey).toEqual('someGitHubPublicKey');
});
tap.test('SshClient should require host validation by default', async () => {
let strictHostError: Error | undefined;
try {
await smartssh.SshClient.connect({
host: '127.0.0.1',
username: 'tester',
});
} catch (error) {
strictHostError = error as Error;
}
expect(strictHostError?.message).toInclude('strictHostKeyChecking');
});
tap.test('SshClient should execute a command over a real SSH server', async () => {
const testServer = await createTestSshServer();
testSshServer = testServer.server;
testSshServerPort = testServer.port;
const sshClient = await smartssh.SshClient.connect({
host: '127.0.0.1',
port: testSshServerPort,
username: 'tester',
password: 'secret',
strictHostKeyChecking: false,
});
const result = await sshClient.exec('printf smartssh');
await sshClient.close();
expect(result.code).toEqual(0);
expect(result.stdout).toEqual('smartssh\n');
expect(result.stderr).toEqual('warn\n');
});
tap.test('should close the real SSH test server', async () => {
await new Promise<void>((resolve, reject) => {
testSshServer.close((error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
});
export default tap.start();
+2 -2
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartssh',
version: '2.0.3',
description: 'A library for setting up SSH configuration quickly and painlessly.'
version: '2.1.0',
description: 'Secure SSH configuration, key management, and remote machine control for TypeScript.'
}
+18
View File
@@ -4,3 +4,21 @@ export { SshInstance } from './smartssh.classes.sshinstance.js';
export { SshKey } from './smartssh.classes.sshkey.js';
export { SshDir } from './smartssh.classes.sshdir.js';
export { SshConfig } from './smartssh.classes.sshconfig.js';
export { SshClient, SshSftpClient } from './smartssh.classes.sshclient.js';
export type {
ISshDownloadOptions,
ISshExecOptions,
ISshExecResult,
ISshForwardInHandle,
ISshForwardInOptions,
ISshForwardOutOptions,
ISshProfile,
ISshShellOptions,
ISshUploadOptions,
TSshHostVerifier,
} from './smartssh.classes.sshclient.js';
export type {
ISshConfigHostBlock,
ISshConfigOptions,
TSshStrictHostKeyChecking,
} from './smartssh.classes.sshconfig.js';
+103 -3
View File
@@ -1,7 +1,107 @@
import * as plugins from './smartssh.plugins.js';
import { SshKey } from './smartssh.classes.sshkey.js';
export let sshKeyArrayFromDir = function (dirArg: string): SshKey[] {
let sshKeyArray: SshKey[] = []; // TODO
return sshKeyArray;
const unsafeHostMessage =
'SSH host aliases must be single, filename-safe values without whitespace or path separators.';
export const assertSafeHost = (hostArg: string) => {
if (!hostArg || hostArg === '.' || hostArg === '..') {
throw new Error(unsafeHostMessage);
}
if (!/^[A-Za-z0-9._@:%+-]+$/.test(hostArg)) {
throw new Error(unsafeHostMessage);
}
};
export const isSafeHost = (hostArg: string) => {
try {
assertSafeHost(hostArg);
return true;
} catch {
return false;
}
};
export const resolveSshDirPath = (dirPathArg?: string) => {
return plugins.path.resolve(
dirPathArg ?? plugins.path.join(plugins.smartpath.get.home(), '.ssh')
);
};
export const ensureSshDirSync = (dirPathArg: string) => {
plugins.fs.ensureDirSync(dirPathArg);
plugins.fs.chmodSync(dirPathArg, 0o700);
};
export const quoteSshConfigValue = (valueArg: string) => {
if (/^[A-Za-z0-9._~/:@%+-]+$/.test(valueArg)) {
return valueArg;
}
return `"${valueArg.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
};
export const fingerprintSha256 = (keyArg: Buffer | string) => {
const hash = plugins.crypto
.createHash('sha256')
.update(keyArg)
.digest('base64')
.replace(/=+$/, '');
return `SHA256:${hash}`;
};
export const fingerprintMd5 = (keyArg: Buffer | string) => {
const hash = plugins.crypto.createHash('md5').update(keyArg).digest('hex');
return hash.match(/.{2}/g)?.join(':') ?? hash;
};
export const sshKeyArrayFromDir = (dirArg: string): SshKey[] => {
const resolvedDir = resolveSshDirPath(dirArg);
if (!plugins.fs.pathExistsSync(resolvedDir)) {
return [];
}
const entries = plugins.fs.readdirSync(resolvedDir, { withFileTypes: true });
const keyMap = new Map<string, { private?: string; public?: string }>();
for (const entry of entries) {
if (!entry.isFile()) {
continue;
}
const fileName = entry.name;
if (
fileName === 'config' ||
fileName === 'authorized_keys' ||
fileName === 'known_hosts' ||
fileName.startsWith('.')
) {
continue;
}
const isPublicKey = fileName.endsWith('.pub');
const host = isPublicKey ? fileName.slice(0, -4) : fileName;
if (!isSafeHost(host)) {
continue;
}
const keyRecord = keyMap.get(host) ?? {};
const filePath = plugins.path.join(resolvedDir, fileName);
const keyContent = plugins.fs.readFileSync(filePath, 'utf8');
if (isPublicKey) {
keyRecord.public = keyContent;
} else {
keyRecord.private = keyContent;
}
keyMap.set(host, keyRecord);
}
return Array.from(keyMap.entries()).map(([host, keyRecord]) => {
return new SshKey({
host,
private: keyRecord.private,
public: keyRecord.public,
});
});
};
+534
View File
@@ -0,0 +1,534 @@
import * as plugins from './smartssh.plugins.js';
import * as helpers from './smartssh.classes.helpers.js';
import { SshKey } from './smartssh.classes.sshkey.js';
import type * as ssh2 from 'ssh2';
export type TSshHostVerifier = (fingerprintArg: string, keyArg: Buffer) => boolean | Promise<boolean>;
export interface ISshProfile {
host: string;
port?: number;
username?: string;
password?: string;
privateKey?: string | Buffer | SshKey;
passphrase?: string | Buffer;
agent?: ssh2.ConnectConfig['agent'];
agentForward?: boolean;
tryKeyboard?: boolean;
readyTimeout?: number;
keepaliveInterval?: number;
keepaliveCountMax?: number;
strictVendor?: boolean;
strictHostKeyChecking?: boolean;
trustedHostFingerprints?: string[];
hostVerifier?: TSshHostVerifier;
algorithms?: ssh2.Algorithms;
authHandler?: ssh2.ConnectConfig['authHandler'];
sock?: ssh2.ConnectConfig['sock'];
forceIPv4?: boolean;
forceIPv6?: boolean;
localAddress?: string;
localPort?: number;
timeout?: number;
ident?: Buffer | string;
debug?: ssh2.DebugFunction;
}
export interface ISshExecOptions extends ssh2.ExecOptions {
input?: string | Buffer;
encoding?: BufferEncoding;
timeout?: number;
signal?: AbortSignal;
}
export interface ISshExecResult {
command: string;
code: number | null;
signal: string | null;
stdout: string;
stderr: string;
stdoutBuffer: Buffer;
stderrBuffer: Buffer;
}
export interface ISshShellOptions {
window?: ssh2.PseudoTtyOptions | false;
options?: ssh2.ShellOptions;
}
export interface ISshForwardOutOptions {
sourceHost?: string;
sourcePort?: number;
destinationHost: string;
destinationPort: number;
}
export interface ISshForwardInOptions {
remoteHost?: string;
remotePort: number;
}
export interface ISshForwardInHandle {
remoteHost: string;
remotePort: number;
close: () => Promise<void>;
}
export interface ISshUploadOptions {
localPath: string;
remotePath: string;
transferOptions?: ssh2.TransferOptions;
}
export interface ISshDownloadOptions {
remotePath: string;
localPath: string;
transferOptions?: ssh2.TransferOptions;
}
export class SshSftpClient {
constructor(private sftp: ssh2.SFTPWrapper) {}
async upload(optionsArg: ISshUploadOptions) {
await this.runVoid((done) => {
if (optionsArg.transferOptions) {
this.sftp.fastPut(optionsArg.localPath, optionsArg.remotePath, optionsArg.transferOptions, done);
} else {
this.sftp.fastPut(optionsArg.localPath, optionsArg.remotePath, done);
}
});
}
async download(optionsArg: ISshDownloadOptions) {
await this.runVoid((done) => {
if (optionsArg.transferOptions) {
this.sftp.fastGet(optionsArg.remotePath, optionsArg.localPath, optionsArg.transferOptions, done);
} else {
this.sftp.fastGet(optionsArg.remotePath, optionsArg.localPath, done);
}
});
}
async readFile(remotePathArg: string): Promise<Buffer>;
async readFile(remotePathArg: string, encodingArg: BufferEncoding): Promise<string>;
async readFile(remotePathArg: string, encodingArg?: BufferEncoding) {
const fileBuffer = await this.run<Buffer>((done) => {
this.sftp.readFile(remotePathArg, (error, fileContent) => done(error, fileContent));
});
return encodingArg ? fileBuffer.toString(encodingArg) : fileBuffer;
}
async writeFile(remotePathArg: string, dataArg: string | Buffer) {
await this.runVoid((done) => this.sftp.writeFile(remotePathArg, dataArg, done));
}
async readdir(remotePathArg: string) {
return this.run<ssh2.FileEntryWithStats[]>((done) => {
this.sftp.readdir(remotePathArg, (error, list) => done(error, list));
});
}
async stat(remotePathArg: string) {
return this.run<ssh2.Stats>((done) => {
this.sftp.stat(remotePathArg, (error, stats) => done(error, stats));
});
}
async lstat(remotePathArg: string) {
return this.run<ssh2.Stats>((done) => {
this.sftp.lstat(remotePathArg, (error, stats) => done(error, stats));
});
}
async mkdir(remotePathArg: string, attributesArg?: ssh2.InputAttributes) {
await this.runVoid((done) => {
if (attributesArg) {
this.sftp.mkdir(remotePathArg, attributesArg, done);
} else {
this.sftp.mkdir(remotePathArg, done);
}
});
}
async chmod(remotePathArg: string, modeArg: number | string) {
await this.runVoid((done) => this.sftp.chmod(remotePathArg, modeArg, done));
}
async remove(remotePathArg: string) {
await this.runVoid((done) => this.sftp.unlink(remotePathArg, done));
}
async rmdir(remotePathArg: string) {
await this.runVoid((done) => this.sftp.rmdir(remotePathArg, done));
}
async rename(sourcePathArg: string, destinationPathArg: string) {
await this.runVoid((done) => this.sftp.rename(sourcePathArg, destinationPathArg, done));
}
private async run<T>(runnerArg: (doneArg: (errorArg?: Error | null, valueArg?: T) => void) => void) {
return new Promise<T>((resolve, reject) => {
runnerArg((error, value) => {
if (error) {
reject(error);
return;
}
resolve(value as T);
});
});
}
private async runVoid(runnerArg: (doneArg: (errorArg?: Error | null) => void) => void) {
await this.run<void>((done) => runnerArg(done));
}
}
export class SshClient {
private connection?: ssh2.Client;
private connected = false;
private lastError?: Error;
constructor(private profile: ISshProfile) {}
static async connect(profileArg: ISshProfile) {
const sshClient = new SshClient(profileArg);
await sshClient.connect();
return sshClient;
}
static fingerprintSha256(keyArg: Buffer | string) {
return helpers.fingerprintSha256(keyArg);
}
static fingerprintMd5(keyArg: Buffer | string) {
return helpers.fingerprintMd5(keyArg);
}
async connect() {
if (this.connected) {
return;
}
const connectConfig = this.createConnectConfig();
const connection = new plugins.ssh2.Client();
this.connection = connection;
await new Promise<void>((resolve, reject) => {
let settled = false;
const settle = (errorArg?: Error) => {
if (settled) {
if (errorArg) {
this.lastError = errorArg;
}
return;
}
settled = true;
connection.removeListener('ready', handleReady);
connection.removeListener('close', handleClose);
if (errorArg) {
reject(errorArg);
} else {
resolve();
}
};
const handleReady = () => {
this.connected = true;
settle();
};
const handleClose = () => {
this.connected = false;
settle(new Error('SSH connection closed before it became ready.'));
};
const handleError = (errorArg: Error) => {
this.lastError = errorArg;
settle(errorArg);
};
connection.on('error', handleError);
connection.once('ready', handleReady);
connection.once('close', handleClose);
connection.connect(connectConfig);
});
}
async exec(commandArg: string, optionsArg: ISshExecOptions = {}): Promise<ISshExecResult> {
const connection = this.ensureConnected();
const { input, encoding = 'utf8', timeout, signal, ...execOptions } = optionsArg;
return new Promise<ISshExecResult>((resolve, reject) => {
let settled = false;
let timeoutHandle: NodeJS.Timeout | undefined;
let channel: ssh2.ClientChannel | undefined;
let code: number | null = null;
let exitSignal: string | null = null;
const stdoutChunks: Buffer[] = [];
const stderrChunks: Buffer[] = [];
const settle = (errorArg?: Error) => {
if (settled) {
return;
}
settled = true;
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
signal?.removeEventListener('abort', handleAbort);
if (errorArg) {
reject(errorArg);
return;
}
const stdoutBuffer = Buffer.concat(stdoutChunks);
const stderrBuffer = Buffer.concat(stderrChunks);
resolve({
command: commandArg,
code,
signal: exitSignal,
stdout: stdoutBuffer.toString(encoding),
stderr: stderrBuffer.toString(encoding),
stdoutBuffer,
stderrBuffer,
});
};
const handleAbort = () => {
channel?.close();
settle(new Error(`SSH exec aborted: ${commandArg}`));
};
if (signal?.aborted) {
handleAbort();
return;
}
if (timeout) {
timeoutHandle = setTimeout(() => {
channel?.close();
settle(new Error(`SSH exec timed out after ${timeout}ms: ${commandArg}`));
}, timeout);
}
signal?.addEventListener('abort', handleAbort);
connection.exec(commandArg, execOptions, (error, stream) => {
if (error) {
settle(error);
return;
}
channel = stream;
stream.on('data', (chunk: Buffer | string) => stdoutChunks.push(Buffer.from(chunk)));
stream.stderr.on('data', (chunk: Buffer | string) => stderrChunks.push(Buffer.from(chunk)));
stream.on('exit', (exitCode: number | null, signalName?: string) => {
code = exitCode;
exitSignal = signalName ?? null;
});
stream.on('error', (streamError: Error) => settle(streamError));
stream.on('close', () => settle());
stream.end(input);
});
});
}
async stream(commandArg: string, optionsArg: ssh2.ExecOptions = {}) {
const connection = this.ensureConnected();
return new Promise<ssh2.ClientChannel>((resolve, reject) => {
connection.exec(commandArg, optionsArg, (error, channel) => {
if (error) {
reject(error);
return;
}
resolve(channel);
});
});
}
async shell(optionsArg: ISshShellOptions = {}) {
const connection = this.ensureConnected();
return new Promise<ssh2.ClientChannel>((resolve, reject) => {
const done = (error: Error | undefined, channel: ssh2.ClientChannel) => {
if (error) {
reject(error);
return;
}
resolve(channel);
};
if (optionsArg.window !== undefined) {
connection.shell(optionsArg.window, optionsArg.options ?? {}, done);
} else {
connection.shell(optionsArg.options ?? {}, done);
}
});
}
async sftp() {
const connection = this.ensureConnected();
return new Promise<SshSftpClient>((resolve, reject) => {
connection.sftp((error, sftp) => {
if (error) {
reject(error);
return;
}
resolve(new SshSftpClient(sftp));
});
});
}
async forwardOut(optionsArg: ISshForwardOutOptions) {
const connection = this.ensureConnected();
return new Promise<ssh2.ClientChannel>((resolve, reject) => {
connection.forwardOut(
optionsArg.sourceHost ?? '127.0.0.1',
optionsArg.sourcePort ?? 0,
optionsArg.destinationHost,
optionsArg.destinationPort,
(error, channel) => {
if (error) {
reject(error);
return;
}
resolve(channel);
}
);
});
}
async forwardIn(optionsArg: ISshForwardInOptions): Promise<ISshForwardInHandle> {
const connection = this.ensureConnected();
const remoteHost = optionsArg.remoteHost ?? '127.0.0.1';
const remotePort = await new Promise<number>((resolve, reject) => {
connection.forwardIn(remoteHost, optionsArg.remotePort, (error, port) => {
if (error) {
reject(error);
return;
}
resolve(port);
});
});
return {
remoteHost,
remotePort,
close: async () => {
await new Promise<void>((resolve, reject) => {
connection.unforwardIn(remoteHost, remotePort, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
},
};
}
async close() {
const connection = this.connection;
if (!connection) {
return;
}
await new Promise<void>((resolve) => {
const timeoutHandle = setTimeout(resolve, 1000);
connection.once('close', () => {
clearTimeout(timeoutHandle);
resolve();
});
connection.end();
});
this.connected = false;
this.connection = undefined;
}
get isConnected() {
return this.connected;
}
get error() {
return this.lastError;
}
private createConnectConfig(): ssh2.ConnectConfig {
const strictHostKeyChecking = this.profile.strictHostKeyChecking ?? true;
const hasHostValidation =
Boolean(this.profile.hostVerifier) || Boolean(this.profile.trustedHostFingerprints?.length);
if (strictHostKeyChecking && !hasHostValidation) {
throw new Error(
'strictHostKeyChecking is enabled. Provide trustedHostFingerprints, hostVerifier, or set strictHostKeyChecking to false.'
);
}
const privateKey =
this.profile.privateKey instanceof SshKey
? this.profile.privateKey.privKey
: this.profile.privateKey;
const connectConfig: ssh2.ConnectConfig = {
host: this.profile.host,
port: this.profile.port,
username: this.profile.username,
password: this.profile.password,
privateKey,
passphrase: this.profile.passphrase,
agent: this.profile.agent,
agentForward: this.profile.agentForward,
tryKeyboard: this.profile.tryKeyboard,
readyTimeout: this.profile.readyTimeout,
keepaliveInterval: this.profile.keepaliveInterval,
keepaliveCountMax: this.profile.keepaliveCountMax,
strictVendor: this.profile.strictVendor,
algorithms: this.profile.algorithms,
authHandler: this.profile.authHandler,
sock: this.profile.sock,
forceIPv4: this.profile.forceIPv4,
forceIPv6: this.profile.forceIPv6,
localAddress: this.profile.localAddress,
localPort: this.profile.localPort,
timeout: this.profile.timeout,
ident: this.profile.ident,
debug: this.profile.debug,
};
connectConfig.hostVerifier = ((key: Buffer, verify: ssh2.VerifyCallback) => {
const verifyHost = async () => {
if (!strictHostKeyChecking && !hasHostValidation) {
return true;
}
const sha256Fingerprint = helpers.fingerprintSha256(key);
const md5Fingerprint = helpers.fingerprintMd5(key);
const trustedFingerprints = this.profile.trustedHostFingerprints ?? [];
if (
trustedFingerprints.includes(sha256Fingerprint) ||
trustedFingerprints.includes(md5Fingerprint) ||
trustedFingerprints.includes(`MD5:${md5Fingerprint}`)
) {
return true;
}
if (this.profile.hostVerifier) {
return this.profile.hostVerifier(sha256Fingerprint, key);
}
return false;
};
verifyHost().then(
(result) => verify(Boolean(result)),
() => verify(false)
);
}) as ssh2.HostVerifier;
return connectConfig;
}
private ensureConnected() {
if (!this.connection || !this.connected) {
throw new Error('SSH client is not connected.');
}
return this.connection;
}
}
+79 -9
View File
@@ -2,21 +2,40 @@ import * as plugins from './smartssh.plugins.js';
import * as helpers from './smartssh.classes.helpers.js';
import { SshKey } from './smartssh.classes.sshkey.js';
export type TSshStrictHostKeyChecking = boolean | 'accept-new';
export interface ISshConfigOptions {
strictHostKeyChecking?: TSshStrictHostKeyChecking;
}
export interface ISshConfigHostBlock {
host: string;
values: Record<string, string>;
}
export class SshConfig {
private _sshKeyArray: SshKey[];
constructor(sshKeyArrayArg: SshKey[]) {
private _options: ISshConfigOptions;
constructor(sshKeyArrayArg: SshKey[], optionsArg: ISshConfigOptions = {}) {
this._sshKeyArray = sshKeyArrayArg;
this._options = {
...optionsArg,
strictHostKeyChecking: optionsArg.strictHostKeyChecking ?? true,
};
}
/**
* stores a config file
*/
store(dirPathArg: string) {
plugins.fs.ensureDirSync(dirPathArg);
let configArray: configObject[] = [];
const resolvedDir = helpers.resolveSshDirPath(dirPathArg);
helpers.ensureSshDirSync(resolvedDir);
const configArray: configObject[] = [];
for (const sshKey of this._sshKeyArray) {
let configString = '';
if (sshKey.host) {
helpers.assertSafeHost(sshKey.host);
const identityFilePath = plugins.path.join(resolvedDir, sshKey.host);
configString =
'Host ' +
sshKey.host +
@@ -24,11 +43,20 @@ export class SshConfig {
' HostName ' +
sshKey.host +
'\n' +
' IdentityFile ~/.ssh/' +
sshKey.host +
'\n' +
' StrictHostKeyChecking no' +
' IdentityFile ' +
helpers.quoteSshConfigValue(identityFilePath) +
'\n';
if (this._options.strictHostKeyChecking !== undefined) {
const strictHostKeyChecking = this._options.strictHostKeyChecking;
configString +=
' StrictHostKeyChecking ' +
(strictHostKeyChecking === 'accept-new'
? 'accept-new'
: strictHostKeyChecking
? 'yes'
: 'no') +
'\n';
}
}
configArray.push({
configString: configString,
@@ -40,10 +68,52 @@ export class SshConfig {
for (const config of configArray) {
configFile = configFile + config.configString + '\n';
}
plugins.fs.writeFileSync(plugins.path.join(dirPathArg, 'config'), configFile);
plugins.fs.writeFileSync(plugins.path.join(resolvedDir, 'config'), configFile);
plugins.fs.chmodSync(plugins.path.join(resolvedDir, 'config'), 0o600);
}
read(dirPathArg: string) {
return plugins.fs.readFileSync(plugins.path.join(dirPathArg, 'config'), 'utf8');
const configPath = plugins.path.join(helpers.resolveSshDirPath(dirPathArg), 'config');
return plugins.fs.readFileSync(configPath, 'utf8');
}
parse(dirPathArg: string) {
return SshConfig.parse(this.read(dirPathArg));
}
static parse(configStringArg: string): ISshConfigHostBlock[] {
const blocks: ISshConfigHostBlock[] = [];
let currentBlock: ISshConfigHostBlock | undefined;
for (const rawLine of configStringArg.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) {
continue;
}
const [keyword, ...valueParts] = line.split(/\s+/);
const value = valueParts.join(' ');
if (!keyword || !value) {
continue;
}
if (keyword.toLowerCase() === 'host') {
if (!helpers.isSafeHost(value)) {
continue;
}
currentBlock = {
host: value,
values: {},
};
blocks.push(currentBlock);
continue;
}
if (currentBlock) {
currentBlock.values[keyword.toLowerCase()] = value;
}
}
return blocks;
}
}
+8 -10
View File
@@ -1,6 +1,5 @@
import * as plugins from './smartssh.plugins.js';
import * as helpers from './smartssh.classes.helpers.js';
import { SshInstance } from './smartssh.classes.sshinstance.js';
import { SshKey } from './smartssh.classes.sshkey.js';
import { SshConfig } from './smartssh.classes.sshconfig.js';
@@ -13,32 +12,31 @@ export class SshDir {
this._sshKeyArray = sshKeyArray;
this._sshConfig = sshConfig;
if (sshDirPathArg) {
this._path = sshDirPathArg;
this._path = helpers.resolveSshDirPath(sshDirPathArg);
} else {
this._path = plugins.path.join(plugins.smartpath.get.home(), '.ssh/');
this._path = helpers.resolveSshDirPath();
}
}
writeToDir(dirPathArg?: string) {
// syncs sshInstance to directory
let path = this._path;
if (dirPathArg) path = dirPathArg;
if (dirPathArg) path = helpers.resolveSshDirPath(dirPathArg);
this._sshKeyArray.forEach((sshKeyArg) => {
sshKeyArg.store(path);
sshKeyArg.storeSync(path);
});
this._sshConfig.store(path);
}
/**
* TODO: implement reading of directories
*/
readFromDir(dirPathArg?: string) {
// syncs sshInstance from directory
let path = this._path;
if (dirPathArg) path = dirPathArg;
if (dirPathArg) path = helpers.resolveSshDirPath(dirPathArg);
const sshKeys = helpers.sshKeyArrayFromDir(path);
this._sshKeyArray.splice(0, this._sshKeyArray.length, ...sshKeys);
}
updateDirPath(dirPathArg: string) {
this._path = dirPathArg;
this._path = helpers.resolveSshDirPath(dirPathArg);
}
getKeys() {
+9 -8
View File
@@ -1,8 +1,7 @@
import * as plugins from './smartssh.plugins.js';
import * as helpers from './smartssh.classes.helpers.js';
import { SshDir } from './smartssh.classes.sshdir.js';
import { SshConfig } from './smartssh.classes.sshconfig.js';
import { SshConfig, type ISshConfigOptions } from './smartssh.classes.sshconfig.js';
import { SshKey } from './smartssh.classes.sshkey.js';
/**
@@ -13,10 +12,12 @@ export class SshInstance {
private _sshConfig: SshConfig; // sshConfig (e.g. represents ~/.ssh/config)
private _sshDir: SshDir; // points to sshDir class instance.
private _sshSync: boolean; // if set to true, the ssh dir will be kept in sync automatically
constructor(optionsArg: { sshDirPath?: string; sshSync?: boolean } = {}) {
constructor(optionsArg: { sshDirPath?: string; sshSync?: boolean } & ISshConfigOptions = {}) {
optionsArg ? void 0 : (optionsArg = {});
this._sshKeyArray = [];
this._sshConfig = new SshConfig(this._sshKeyArray);
this._sshConfig = new SshConfig(this._sshKeyArray, {
strictHostKeyChecking: optionsArg.strictHostKeyChecking,
});
this._sshDir = new SshDir(this._sshKeyArray, this._sshConfig, optionsArg.sshDirPath);
this._sshSync = optionsArg.sshSync ?? false;
}
@@ -29,10 +30,10 @@ export class SshInstance {
}
removeKey(sshKeyArg: SshKey) {
this._syncAuto('from');
let filteredArray = this._sshKeyArray.filter((sshKeyArg2: SshKey) => {
return sshKeyArg != sshKeyArg2;
});
this._sshKeyArray = filteredArray;
const sshKeyIndex = this._sshKeyArray.indexOf(sshKeyArg);
if (sshKeyIndex >= 0) {
this._sshKeyArray.splice(sshKeyIndex, 1);
}
this._syncAuto('to');
}
replaceKey(sshKeyOldArg: SshKey, sshKeyNewArg: SshKey) {
+61 -10
View File
@@ -1,6 +1,8 @@
import * as plugins from './smartssh.plugins.js';
import * as helpers from './smartssh.classes.helpers.js';
export type TSshKeyType = 'duplex' | 'private' | 'public';
export class SshKey {
private _privKey: string;
private _pubKey: string;
@@ -15,6 +17,9 @@ export class SshKey {
) {
this._privKey = optionsArg.private ?? '';
this._pubKey = optionsArg.public ?? '';
if (optionsArg.host) {
helpers.assertSafeHost(optionsArg.host);
}
this._hostVar = optionsArg.host ?? '';
this._authorized = optionsArg.authorized ?? false;
}
@@ -24,6 +29,9 @@ export class SshKey {
return this._hostVar;
}
set host(hostArg: string) {
if (hostArg) {
helpers.assertSafeHost(hostArg);
}
this._hostVar = hostArg;
}
@@ -69,7 +77,7 @@ export class SshKey {
/**
* returns wether there is a private, a public or both keys
*/
get type() {
get type(): TSshKeyType | undefined {
if (this._privKey && this._pubKey) {
return 'duplex';
} else if (this._privKey) {
@@ -78,25 +86,68 @@ export class SshKey {
return 'public';
}
}
set type(someVlueArg: any) {
console.log('the type of an SshKey connot be set. This value is autocomputed.');
}
// methods
read(filePathArg: string) {}
read(filePathArg: string) {
const resolvedPath = plugins.path.resolve(filePathArg);
const fileName = plugins.path.basename(resolvedPath);
const isPublicKey = fileName.endsWith('.pub');
const host = isPublicKey ? fileName.slice(0, -4) : fileName;
helpers.assertSafeHost(host);
this._hostVar = host;
if (isPublicKey) {
this._pubKey = plugins.fs.readFileSync(resolvedPath, 'utf8');
} else {
this._privKey = plugins.fs.readFileSync(resolvedPath, 'utf8');
}
}
static fromFile(filePathArg: string) {
const sshKey = new SshKey();
sshKey.read(filePathArg);
return sshKey;
}
static fromFiles(optionsArg: { privateKeyPath?: string; publicKeyPath?: string; host?: string }) {
const sshKey = new SshKey({ host: optionsArg.host });
if (optionsArg.privateKeyPath) {
sshKey.privKey = plugins.fs.readFileSync(plugins.path.resolve(optionsArg.privateKeyPath), 'utf8');
if (!sshKey.host) {
const fileName = plugins.path.basename(optionsArg.privateKeyPath);
helpers.assertSafeHost(fileName);
sshKey.host = fileName;
}
}
if (optionsArg.publicKeyPath) {
sshKey.pubKey = plugins.fs.readFileSync(plugins.path.resolve(optionsArg.publicKeyPath), 'utf8');
if (!sshKey.host) {
const fileName = plugins.path.basename(optionsArg.publicKeyPath).replace(/\.pub$/, '');
helpers.assertSafeHost(fileName);
sshKey.host = fileName;
}
}
return sshKey;
}
async store(dirPathArg: string) {
plugins.fs.ensureDirSync(dirPathArg);
let fileNameBase = this.host;
this.storeSync(dirPathArg);
}
storeSync(dirPathArg: string) {
helpers.assertSafeHost(this.host);
const resolvedDir = helpers.resolveSshDirPath(dirPathArg);
helpers.ensureSshDirSync(resolvedDir);
const fileNameBase = this.host;
if (this._privKey) {
let filePath = plugins.path.join(dirPathArg, fileNameBase);
const filePath = plugins.path.join(resolvedDir, fileNameBase);
plugins.fs.writeFileSync(filePath, this._privKey);
plugins.fs.chmodSync(filePath, 0o600);
}
if (this._pubKey) {
let filePath = plugins.path.join(dirPathArg, fileNameBase + '.pub');
const filePath = plugins.path.join(resolvedDir, fileNameBase + '.pub');
plugins.fs.writeFileSync(filePath, this._pubKey);
plugins.fs.chmodSync(filePath, 0o600);
plugins.fs.chmodSync(filePath, 0o644);
}
}
}
+4 -3
View File
@@ -1,8 +1,9 @@
// node native
import * as crypto from 'crypto';
import fs from 'fs-extra';
import * as path from 'path';
export { fs, path };
export { crypto, fs, path };
// @push.rocks scope
import * as smartjson from '@push.rocks/smartjson';
@@ -19,6 +20,6 @@ export {
// third party scope
import * as minimatch from 'minimatch';
import * as nodeSsh from 'node-ssh';
import ssh2 from 'ssh2';
export { minimatch, nodeSsh };
export { minimatch, ssh2 };