Compare commits

...

45 Commits

Author SHA1 Message Date
jkunz d3a748d26e v2.1.0 2026-05-02 09:43:21 +00:00
jkunz 3b20db79d0 feat(sshclient): add a promise-first SSH client with secure host verification and improve SSH key/config handling 2026-05-02 09:43:21 +00:00
jkunz 4a97d63c04 v2.0.3 2026-05-01 18:44:22 +00:00
jkunz d8ab8a8d73 fix(ssh): modernize filesystem handling and package exports for NodeNext compatibility 2026-05-01 18:44:22 +00:00
philkunz a9820a9e98 update description 2024-05-29 14:16:27 +02:00
philkunz 7037cee3d8 update tsconfig 2024-04-14 18:22:42 +02:00
philkunz f7661e3133 update tsconfig 2024-04-01 21:41:15 +02:00
philkunz cfcaa5b059 update npmextra.json: githost 2024-04-01 19:59:45 +02:00
philkunz ac048b7025 update npmextra.json: githost 2024-03-30 21:48:46 +01:00
philkunz dcd32e2dd2 2.0.2 2024-02-09 18:21:33 +01:00
philkunz 9a10f83bb6 fix(core): update 2024-02-09 18:21:33 +01:00
philkunz 9fc03e8504 2.0.1 2023-07-27 15:52:02 +02:00
philkunz 9a32b156fe fix(core): update 2023-07-27 15:52:01 +02:00
philkunz a319e54d60 2.0.0 2022-10-11 13:18:35 +02:00
philkunz 6a2577cde6 BREAKING CHANGE(core): switch to esm 2022-10-11 13:18:35 +02:00
philkunz 1f1bf7c21f 1.2.7 2022-10-11 13:18:04 +02:00
philkunz c652d0bf07 fix(core): update 2022-10-11 13:18:04 +02:00
philkunz eccc6294a8 1.2.6 2022-10-11 13:13:14 +02:00
philkunz f8a75a8d42 fix(core): update 2022-10-11 13:13:14 +02:00
philkunz d5c2bc1b53 1.2.5 2022-10-11 13:05:30 +02:00
philkunz d577a82a7b fix(core): update 2022-10-11 13:05:29 +02:00
philkunz f0b52c8da7 1.2.4 2019-07-17 11:48:31 +02:00
philkunz 4cb6aa03e6 fix(core): update 2019-07-17 11:48:31 +02:00
philkunz 8b85b6c8bc 1.2.3 2018-09-17 22:32:31 +02:00
philkunz c032ff69d0 fix(core): update 2018-09-17 22:32:31 +02:00
philkunz 0454eef45f update structure 2017-06-15 19:25:12 +02:00
philkunz def368f8ab 1.2.2 2017-06-15 17:53:24 +02:00
philkunz 6853fa28b6 update to latest standards 2017-06-15 17:52:22 +02:00
philkunz 56318f28cf 1.2.1 2016-11-23 12:44:37 +01:00
philkunz 32b26f21cd improve README 2016-11-23 12:44:31 +01:00
philkunz 32c2698af7 1.2.0 2016-11-23 12:38:45 +01:00
philkunz 27237f14c7 update to latest standards 2016-11-23 12:38:38 +01:00
philkunz 8f29f234f1 introducde more flexible pathing 2016-06-28 02:10:51 +02:00
philkunz 5091625953 1.1.5 2016-06-26 16:16:28 +02:00
philkunz f74b3a51b0 now creating config as standard 2016-06-26 16:16:12 +02:00
philkunz 062f3ad060 1.1.4 2016-06-26 04:23:48 +02:00
philkunz ecd0fd8fad now setting rights for stored keys 2016-06-26 04:23:45 +02:00
philkunz 742bf694e4 1.1.3 2016-06-26 04:07:37 +02:00
philkunz 38165f11db some updates 2016-06-26 04:07:03 +02:00
philkunz ef2b31b4b2 1.1.2 2016-06-25 15:31:03 +02:00
philkunz 5b1f800067 update structure 2016-06-25 15:30:57 +02:00
philkunz 6339a3ed9b update SshKey.store() 2016-06-25 14:13:26 +02:00
philkunz bf27aaf167 update structure 2016-06-25 13:07:24 +02:00
philkunz 9bc3aea59c 1.1.1 2016-06-25 02:53:09 +02:00
philkunz f5ff302d4d updated structure of SshConfig 2016-06-25 02:53:05 +02:00
55 changed files with 9946 additions and 901 deletions
+66
View File
@@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
+124
View File
@@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true
+19 -6
View File
@@ -1,7 +1,20 @@
.idea/
node_modules/
.nogit/
# artifacts
coverage/
docs/
ts/typings/
ts/*.js
ts/*.js.map
public/
pages/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom
-38
View File
@@ -1,38 +0,0 @@
image: hosttoday/ht-docker-node:npmts
stages:
- test
- release
- page
testLTS:
stage: test
script:
- npmci test lts
tags:
- docker
- lossless
testSTABLE:
stage: test
script:
- npmci test stable
tags:
- docker
- lossless
testLEGACY:
stage: test
script:
- npmci test legacy
allow_failure: true
release:
stage: release
script:
- npmci publish
only:
- tags
tags:
- docker
- lossless
+38
View File
@@ -0,0 +1,38 @@
{
"@ship.zone/szci": {
"npmGlobalTools": [],
"npmRegistryUrl": "registry.npmjs.org"
},
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartssh",
"shortDescription": "SSH automation utilities",
"description": "Secure SSH configuration, key management, and remote machine control for TypeScript.",
"npmPackagename": "@push.rocks/smartssh",
"license": "MIT",
"keywords": [
"SSH",
"SSH configuration",
"SSH keys management",
"automation",
"development tools",
"node.js",
"security",
"server management"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"@git.zone/tsdoc": {
"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"
}
}
-12
View File
@@ -1,12 +0,0 @@
language: node_js
node_js:
- '4'
- stable
deploy:
provider: npm
email: npm@lossless.digital
api_key:
secure: xApCMlDyZcTOgq+iomxR2A/2aMBhhPpgEBxdFYqXDNC/AGkr+NQJhGt67W4840FMrSUFEDZNQhOS+t6gYMqxUHv+vJFc0cHskFSuLDnAH2MS45TqtFYNcP+GARs1suuM9Il5hXNEvjVJ6XF0lYlNlK8mJstKQscdEKWyBHj42oSsgWRcuzBgqps8Vnbp+Ey2Bpfaw1yV+P1fyv8dNnkwG5dSt3EIxAcbGiMOhCz0u6oMroKfAYfNTxMJjja2uJJOqoTTShzeMyIYx+YwxorcZGfchI+TOPHHeVc+fByCHfzTZJYCy9qTSSTvWcKD/H7q3RGciEXHzhwMj0d8dlY3WPHC6BBliD6bLwVgDmToD3cdHm8OLsxW7hjFLO51vOIbhJZrWBVztlusuLwuyVAlIgeAsV8Yb5FxetxZmBU42qr5itykPl45rNd7talI0ZcoFPRTAWxxmCD8hp0d3ZLdjcEdbCzc5GYmEFN0NwKLTZF3Q1G4UbsHMgN8Pe4ohjdaYYhJ7RKgbmLR0J4NBrWIAUOhDaUTkZhgsHFyEmtbKI6JkxQtwCEBBBursemZWFQSIdtj2+O/RBaBCgoUNIpxUDBFq+D3Pir7BZP7DK2m3Otl0F9aCdqJmhCc7rOn3MueLpmndjtO1RFteXAdAkDxKp2RehIB6yohxbRmQ1O9PsA=
on:
tags: true
repo: pushrocks/smartssh
+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}
-34
View File
@@ -1,34 +0,0 @@
# smartssh
setups SSH quickly and in a painless manner
> Attention: This is still alpha, so some things won't work, not all things are inplemented.
## Usage
```javascript
var smartssh = require("smartssh");
var sshInstance = new smartssh.sshInstance({
sshDir: "/some/path/.ssh", // the standard ssh directory, optional, defaults to "~./.ssh"
sshSync: true // sync ssh this instance will represent the status of an ssh dir if set to true;
});
sshInstance.addKey(new smartssh.sshKey({
private: "somestring",
public: "somestring", // optional
host:"github.com",
encoding: "base64" // optional, defaults to "utf8", can be "utf8" or "base64", useful for reading ssh keys from environment variables
}));
sshInstance.removeKey(sshInstance.getKey("github.com")); // removes key for host "github.com" is present
sshInstance.createKey({
host:"gitlab.com" // returns new key in the form sshKey, read more about the sshKey class below
})
sshInstance.getKey({ // returns ssh key in the form sshKey, read more about the sshKey class below
host:"github.com"
});
sshInstance.getKeys() // returns array of all available getKeys. Each key is in form of class sshKey
```
+103
View File
@@ -0,0 +1,103 @@
# 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
- replace smartfile, smartpromise, and shell-based chmod usage with direct fs operations
- add package exports and tighten TypeScript settings with noImplicitAny and Node types
- update tests to the current tstest runner and move them to a node-specific entry file
- refresh package metadata and dependency versions to match the updated toolchain
## 2024-05-29 - 2.0.2 - maintenance
Release 2.0.2 focused on repository and TypeScript configuration housekeeping.
- Updated project description
- Refined TypeScript configuration
- Updated npm metadata for git host configuration
- Summarizes trivial maintenance commits across 2024-02-09 to 2024-05-29
## 2024-02-09 - 2.0.1 - core
Delivered a core update in the 2.0.1 release line.
- Updated core implementation
## 2023-07-27 - 2.0.0 - core
Delivered a core update for the 2.0.0 release.
- Updated core implementation
## 2022-10-11 - 1.2.7 - core
Introduced a breaking core change by switching the package to ESM.
- BREAKING: switched core package output to ESM
## 2022-10-11 - 1.2.4 to 1.2.6 - core
This release range contained small core maintenance updates.
- Repeated core update fixes delivered across versions 1.2.4, 1.2.5, and 1.2.6
## 2017-06-15 - 1.2.2 - maintenance
Refined project structure in the 1.2.2 release.
- Updated project structure
## 2016-11-23 - 1.2.0 to 1.2.1 - maintenance
This release range focused on standards and documentation improvements.
- Updated project to latest standards
- Improved README documentation
## 2016-06-26 - 1.1.2 to 1.1.5 - core
This release range delivered several core configuration and path-handling improvements.
- Added more flexible path handling
- Created config generation as a standard behavior
- Set rights for stored keys
- Included general maintenance and standards updates
## 2016-06-25 - 1.1.0 to 1.1.1 - core
This release range reworked the internal structure around SSH configuration and key storage.
- Updated structure of `SshConfig`
- Updated `SshKey.store()`
- Performed related structural cleanup
## 2016-06-24 - 1.0.6 to 1.0.7 - core
This release range focused on structural changes in the core implementation.
- Major structural updates
- Additional structure refinements
## 2016-06-01 - 1.0.2 to 1.0.5 - features
This release range added testing, packaging, CI, and key-handling improvements.
- Renamed `Ssh` class to `SshInstance`
- Added support for base64-encoded keys
- Added typings to package metadata
- Expanded and improved test coverage, including an 80% coverage milestone
- Updated dependency and CI configuration
- Improved directory synchronization behavior
## 2016-04-25 - 1.0.1 - core
Expanded the initial API and improved class structure after the first stable release.
- Added `removeKey` and `replaceKey` methods
- Improved sync triggering
- Restructured class files
- Standardized class names to start with capital letters
- Added supporting logic and typing updates
## 2016-04-24 - 1.0.0 - project
Initial public release of the project.
- Started the project structure
- Created `package.json` and enabled CI
- Added `.gitignore`
- Added and improved README documentation
-5
View File
@@ -1,5 +0,0 @@
import "typings-global";
export { SshInstance } from "./smartssh.classes.sshinstance";
export { SshKey } from "./smartssh.classes.sshkey";
export { SshDir } from "./smartssh.classes.sshdir";
export { SshConfig } from "./smartssh.classes.sshconfig";
-12
View File
@@ -1,12 +0,0 @@
"use strict";
require("typings-global");
var smartssh_classes_sshinstance_1 = require("./smartssh.classes.sshinstance");
exports.SshInstance = smartssh_classes_sshinstance_1.SshInstance;
var smartssh_classes_sshkey_1 = require("./smartssh.classes.sshkey");
exports.SshKey = smartssh_classes_sshkey_1.SshKey;
var smartssh_classes_sshdir_1 = require("./smartssh.classes.sshdir");
exports.SshDir = smartssh_classes_sshdir_1.SshDir;
var smartssh_classes_sshconfig_1 = require("./smartssh.classes.sshconfig");
exports.SshConfig = smartssh_classes_sshconfig_1.SshConfig;
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxRQUFPLGdCQUNQLENBQUMsQ0FEc0I7QUFHdkIsNkNBQTBCLGdDQUFnQyxDQUFDO0FBQW5ELGlFQUFtRDtBQUMzRCx3Q0FBcUIsMkJBQTJCLENBQUM7QUFBekMsa0RBQXlDO0FBQ2pELHdDQUFxQiwyQkFBMkIsQ0FBQztBQUF6QyxrREFBeUM7QUFDakQsMkNBQXdCLDhCQUE4QixDQUFDO0FBQS9DLDJEQUErQyIsImZpbGUiOiJpbmRleC5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBcInR5cGluZ3MtZ2xvYmFsXCJcbmltcG9ydCAqIGFzIHBsdWdpbnMgZnJvbSBcIi4vc21hcnRzc2gucGx1Z2luc1wiO1xuXG5leHBvcnQge1NzaEluc3RhbmNlfSBmcm9tIFwiLi9zbWFydHNzaC5jbGFzc2VzLnNzaGluc3RhbmNlXCI7XG5leHBvcnQge1NzaEtleX0gZnJvbSBcIi4vc21hcnRzc2guY2xhc3Nlcy5zc2hrZXlcIjtcbmV4cG9ydCB7U3NoRGlyfSBmcm9tIFwiLi9zbWFydHNzaC5jbGFzc2VzLnNzaGRpclwiO1xuZXhwb3J0IHtTc2hDb25maWd9IGZyb20gXCIuL3NtYXJ0c3NoLmNsYXNzZXMuc3NoY29uZmlnXCI7Il19
-3
View File
@@ -1,3 +0,0 @@
import "typings-global";
import { SshKey } from "./smartssh.classes.sshkey";
export declare let sshKeyArrayFromDir: (dirArg: string) => SshKey[];
-8
View File
@@ -1,8 +0,0 @@
"use strict";
require("typings-global");
exports.sshKeyArrayFromDir = function (dirArg) {
var sshKeyArray = []; //TODO
return sshKeyArray;
};
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNtYXJ0c3NoLmNsYXNzZXMuaGVscGVycy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEsUUFBTyxnQkFDUCxDQUFDLENBRHNCO0FBSVosMEJBQWtCLEdBQUcsVUFBUyxNQUFhO0lBQ2xELElBQUksV0FBVyxHQUFHLEVBQUUsQ0FBQyxDQUFDLE1BQU07SUFDNUIsTUFBTSxDQUFDLFdBQVcsQ0FBQztBQUN2QixDQUFDLENBQUEiLCJmaWxlIjoic21hcnRzc2guY2xhc3Nlcy5oZWxwZXJzLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFwidHlwaW5ncy1nbG9iYWxcIlxuaW1wb3J0ICogYXMgcGx1Z2lucyBmcm9tIFwiLi9zbWFydHNzaC5wbHVnaW5zXCI7XG5pbXBvcnQge1NzaEtleX0gZnJvbSBcIi4vc21hcnRzc2guY2xhc3Nlcy5zc2hrZXlcIjtcblxuZXhwb3J0IGxldCBzc2hLZXlBcnJheUZyb21EaXIgPSBmdW5jdGlvbihkaXJBcmc6c3RyaW5nKTpTc2hLZXlbXXtcbiAgICBsZXQgc3NoS2V5QXJyYXkgPSBbXTsgLy9UT0RPXG4gICAgcmV0dXJuIHNzaEtleUFycmF5O1xufSJdfQ==
-15
View File
@@ -1,15 +0,0 @@
import "typings-global";
import { SshKey } from "./smartssh.classes.sshkey";
export declare class SshConfig {
sshKeyArray: SshKey[];
constructor(sshKeyArrayArg: SshKey[]);
/**
* the current config
*/
config: configObject[];
}
export interface configObject {
host: string;
authorized: boolean;
sshKey: SshKey;
}
-24
View File
@@ -1,24 +0,0 @@
"use strict";
require("typings-global");
var SshConfig = (function () {
function SshConfig(sshKeyArrayArg) {
this.sshKeyArray = sshKeyArrayArg;
}
Object.defineProperty(SshConfig.prototype, "config", {
/**
* the current config
*/
get: function () {
var configArray;
return configArray;
},
enumerable: true,
configurable: true
});
return SshConfig;
}());
exports.SshConfig = SshConfig;
;
;
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNtYXJ0c3NoLmNsYXNzZXMuc3NoY29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxRQUFPLGdCQUFnQixDQUFDLENBQUE7QUFLeEI7SUFFSSxtQkFBWSxjQUF1QjtRQUMvQixJQUFJLENBQUMsV0FBVyxHQUFHLGNBQWMsQ0FBQztJQUN0QyxDQUFDO0lBS0Qsc0JBQUksNkJBQU07UUFIVjs7V0FFRzthQUNIO1lBQ0ksSUFBSSxXQUEwQixDQUFDO1lBQy9CLE1BQU0sQ0FBQyxXQUFXLENBQUM7UUFDdkIsQ0FBQzs7O09BQUE7SUFDTCxnQkFBQztBQUFELENBYkEsQUFhQyxJQUFBO0FBYlksaUJBQVMsWUFhckIsQ0FBQTtBQUFBLENBQUM7QUFNRCxDQUFDIiwiZmlsZSI6InNtYXJ0c3NoLmNsYXNzZXMuc3NoY29uZmlnLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFwidHlwaW5ncy1nbG9iYWxcIjtcbmltcG9ydCAqIGFzIHBsdWdpbnMgZnJvbSBcIi4vc21hcnRzc2gucGx1Z2luc1wiO1xuaW1wb3J0ICogYXMgaGVscGVycyBmcm9tIFwiLi9zbWFydHNzaC5jbGFzc2VzLmhlbHBlcnNcIjtcbmltcG9ydCB7U3NoS2V5fSBmcm9tIFwiLi9zbWFydHNzaC5jbGFzc2VzLnNzaGtleVwiXG5cbmV4cG9ydCBjbGFzcyBTc2hDb25maWcge1xuICAgIHNzaEtleUFycmF5OlNzaEtleVtdO1xuICAgIGNvbnN0cnVjdG9yKHNzaEtleUFycmF5QXJnOlNzaEtleVtdKXtcbiAgICAgICAgdGhpcy5zc2hLZXlBcnJheSA9IHNzaEtleUFycmF5QXJnO1xuICAgIH1cblxuICAgIC8qKlxuICAgICAqIHRoZSBjdXJyZW50IGNvbmZpZ1xuICAgICAqL1xuICAgIGdldCBjb25maWcoKXtcbiAgICAgICAgbGV0IGNvbmZpZ0FycmF5OmNvbmZpZ09iamVjdFtdO1xuICAgICAgICByZXR1cm4gY29uZmlnQXJyYXk7XG4gICAgfVxufTtcblxuZXhwb3J0IGludGVyZmFjZSBjb25maWdPYmplY3Qge1xuICAgIGhvc3Q6c3RyaW5nO1xuICAgIGF1dGhvcml6ZWQ6Ym9vbGVhbjtcbiAgICBzc2hLZXk6U3NoS2V5O1xufTtcblxuIl19
-10
View File
@@ -1,10 +0,0 @@
import "typings-global";
import { SshKey } from "./smartssh.classes.sshkey";
export declare class SshDir {
path: string;
private sshKeyArray;
constructor(sshKeyArray: SshKey[], sshDirPathArg?: string);
writeToDir(): void;
readFromDir(): void;
getKeys(): SshKey[];
}
-32
View File
@@ -1,32 +0,0 @@
"use strict";
require("typings-global");
var plugins = require("./smartssh.plugins");
var helpers = require("./smartssh.classes.helpers");
var SshDir = (function () {
function SshDir(sshKeyArray, sshDirPathArg) {
this.sshKeyArray = sshKeyArray;
if (sshDirPathArg) {
this.path = sshDirPathArg;
}
else {
this.path = plugins.path.join(plugins.smartpath.get.home(), ".ssh/");
}
;
}
SshDir.prototype.writeToDir = function () {
var _this = this;
this.sshKeyArray.forEach(function (sshKeyArg) {
sshKeyArg.store(_this.path);
});
};
;
SshDir.prototype.readFromDir = function () {
};
SshDir.prototype.getKeys = function () {
return helpers.sshKeyArrayFromDir(this.path);
};
return SshDir;
}());
exports.SshDir = SshDir;
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNtYXJ0c3NoLmNsYXNzZXMuc3NoZGlyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQSxRQUFPLGdCQUFnQixDQUFDLENBQUE7QUFDeEIsSUFBWSxPQUFPLFdBQU0sb0JBQW9CLENBQUMsQ0FBQTtBQUM5QyxJQUFZLE9BQU8sV0FBTSw0QkFBNEIsQ0FBQyxDQUFBO0FBSXREO0lBR0ksZ0JBQVksV0FBb0IsRUFBQyxhQUFxQjtRQUNsRCxJQUFJLENBQUMsV0FBVyxHQUFHLFdBQVcsQ0FBQztRQUMvQixFQUFFLENBQUEsQ0FBQyxhQUFhLENBQUMsQ0FBQSxDQUFDO1lBQ2QsSUFBSSxDQUFDLElBQUksR0FBRyxhQUFhLENBQUM7UUFDOUIsQ0FBQztRQUFDLElBQUksQ0FBQyxDQUFDO1lBQ0osSUFBSSxDQUFDLElBQUksR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsU0FBUyxDQUFDLEdBQUcsQ0FBQyxJQUFJLEVBQUUsRUFBQyxPQUFPLENBQUMsQ0FBQztRQUN4RSxDQUFDO1FBQUEsQ0FBQztJQUNOLENBQUM7SUFDRCwyQkFBVSxHQUFWO1FBQUEsaUJBS0M7UUFKRyxJQUFJLENBQUMsV0FBVyxDQUFDLE9BQU8sQ0FBQyxVQUFDLFNBQVM7WUFDL0IsU0FBUyxDQUFDLEtBQUssQ0FBQyxLQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7UUFFL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDOztJQUNELDRCQUFXLEdBQVg7SUFFQSxDQUFDO0lBQ0Qsd0JBQU8sR0FBUDtRQUNJLE1BQU0sQ0FBQyxPQUFPLENBQUMsa0JBQWtCLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQ2pELENBQUM7SUFDTCxhQUFDO0FBQUQsQ0F2QkEsQUF1QkMsSUFBQTtBQXZCWSxjQUFNLFNBdUJsQixDQUFBIiwiZmlsZSI6InNtYXJ0c3NoLmNsYXNzZXMuc3NoZGlyLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFwidHlwaW5ncy1nbG9iYWxcIjtcbmltcG9ydCAqIGFzIHBsdWdpbnMgZnJvbSBcIi4vc21hcnRzc2gucGx1Z2luc1wiO1xuaW1wb3J0ICogYXMgaGVscGVycyBmcm9tIFwiLi9zbWFydHNzaC5jbGFzc2VzLmhlbHBlcnNcIjtcbmltcG9ydCB7U3NoSW5zdGFuY2V9IGZyb20gXCIuL3NtYXJ0c3NoLmNsYXNzZXMuc3NoaW5zdGFuY2VcIjtcbmltcG9ydCB7U3NoS2V5fSBmcm9tIFwiLi9zbWFydHNzaC5jbGFzc2VzLnNzaGtleVwiO1xuaW1wb3J0IHtTc2hDb25maWd9IGZyb20gXCIuL3NtYXJ0c3NoLmNsYXNzZXMuc3NoY29uZmlnXCI7XG5leHBvcnQgY2xhc3MgU3NoRGlyIHsgLy8gc3NoRGlyIGNsYXNzIC0+IE5PVCBFWFBPUlRFRCwgT05MWSBGT1IgSU5URVJOQUwgVVNFXG4gICAgcGF0aDpzdHJpbmc7IC8vIHRoZSBwYXRoIG9mIHRoZSBzc2ggZGlyZWN0b3J5XG4gICAgcHJpdmF0ZSBzc2hLZXlBcnJheTpTc2hLZXlbXTtcbiAgICBjb25zdHJ1Y3Rvcihzc2hLZXlBcnJheTpTc2hLZXlbXSxzc2hEaXJQYXRoQXJnPzpzdHJpbmcpe1xuICAgICAgICB0aGlzLnNzaEtleUFycmF5ID0gc3NoS2V5QXJyYXk7XG4gICAgICAgIGlmKHNzaERpclBhdGhBcmcpe1xuICAgICAgICAgICAgdGhpcy5wYXRoID0gc3NoRGlyUGF0aEFyZztcbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIHRoaXMucGF0aCA9IHBsdWdpbnMucGF0aC5qb2luKHBsdWdpbnMuc21hcnRwYXRoLmdldC5ob21lKCksXCIuc3NoL1wiKTtcbiAgICAgICAgfTtcbiAgICB9XG4gICAgd3JpdGVUb0RpcigpeyAvLyBzeW5jcyBzc2hJbnN0YW5jZSB0byBkaXJlY3RvcnlcbiAgICAgICAgdGhpcy5zc2hLZXlBcnJheS5mb3JFYWNoKChzc2hLZXlBcmcpID0+IHtcbiAgICAgICAgICAgIHNzaEtleUFyZy5zdG9yZSh0aGlzLnBhdGgpO1xuICAgICAgICAgICAgXG4gICAgICAgIH0pO1xuICAgIH07XG4gICAgcmVhZEZyb21EaXIoKXsgLy8gc3luY3Mgc3NoSW5zdGFuY2UgZnJvbSBkaXJlY3RvcnlcbiAgICAgICAgXG4gICAgfVxuICAgIGdldEtleXMoKXtcbiAgICAgICAgcmV0dXJuIGhlbHBlcnMuc3NoS2V5QXJyYXlGcm9tRGlyKHRoaXMucGF0aCk7XG4gICAgfVxufSJdfQ==
-34
View File
@@ -1,34 +0,0 @@
import "typings-global";
import { SshKey } from "./smartssh.classes.sshkey";
export declare class SshInstance {
private _sshKeyArray;
private _sshConfig;
private _sshDir;
private _sshSync;
constructor(optionsArg?: {
sshDirPath?: string;
sshSync?: boolean;
});
addKey(sshKeyArg: SshKey): void;
removeKey(sshKeyArg: SshKey): void;
replaceKey(sshKeyOldArg: SshKey, sshKeyNewArg: SshKey): void;
getKey(hostArg: string): SshKey;
sshKeys: SshKey[];
/**
* write SshInstance to disk
*/
writeToDisk(): void;
/**
* read ab SshInstance from disk
*/
readFromDisk(): void;
private _makeConfig();
/**
* method to invoke SshInstance _sync automatically when sshSync is true
*/
private _syncAuto(directionArg);
/**
* private method to sync SshInstance
*/
private _sync(directionArg);
}
File diff suppressed because one or more lines are too long
-21
View File
@@ -1,21 +0,0 @@
import "typings-global";
export declare class SshKey {
private _privKey;
private _pubKey;
private _hostVar;
private _authorized;
constructor(optionsArg?: {
private?: string;
public?: string;
host?: string;
authorized?: boolean;
});
host: string;
privKey: string;
privKeyBase64: string;
pubKey: string;
pubKeyBase64: string;
type: any;
read(filePathArg: any): void;
store(filePathArg?: string): void;
}
-114
View File
File diff suppressed because one or more lines are too long
-8
View File
@@ -1,8 +0,0 @@
import "typings-global";
export import beautylog = require("beautylog");
export declare let base64: any;
export declare let fs: any;
export declare let minimatch: any;
export import path = require("path");
export import smartfile = require("smartfile");
export import smartpath = require("smartpath");
-11
View File
@@ -1,11 +0,0 @@
"use strict";
require("typings-global");
exports.beautylog = require("beautylog");
exports.base64 = require("js-base64").Base64;
exports.fs = require("fs-extra");
exports.minimatch = require("minimatch");
exports.path = require("path");
exports.smartfile = require("smartfile");
exports.smartpath = require("smartpath");
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNtYXJ0c3NoLnBsdWdpbnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBLFFBQU8sZ0JBQ1AsQ0FBQyxDQURzQjtBQUNULGlCQUFTLFdBQVcsV0FBVyxDQUFDLENBQUM7QUFDcEMsY0FBTSxHQUFHLE9BQU8sQ0FBQyxXQUFXLENBQUMsQ0FBQyxNQUFNLENBQUM7QUFDckMsVUFBRSxHQUFHLE9BQU8sQ0FBQyxVQUFVLENBQUMsQ0FBQztBQUN6QixpQkFBUyxHQUFHLE9BQU8sQ0FBQyxXQUFXLENBQUMsQ0FBQztBQUM5QixZQUFJLFdBQVcsTUFBTSxDQUFDLENBQUM7QUFDdkIsaUJBQVMsV0FBVyxXQUFXLENBQUMsQ0FBQztBQUNqQyxpQkFBUyxXQUFXLFdBQVcsQ0FBQyxDQUFDIiwiZmlsZSI6InNtYXJ0c3NoLnBsdWdpbnMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgXCJ0eXBpbmdzLWdsb2JhbFwiXG5leHBvcnQgaW1wb3J0IGJlYXV0eWxvZyA9IHJlcXVpcmUoXCJiZWF1dHlsb2dcIik7XG5leHBvcnQgbGV0IGJhc2U2NCA9IHJlcXVpcmUoXCJqcy1iYXNlNjRcIikuQmFzZTY0O1xuZXhwb3J0IGxldCBmcyA9IHJlcXVpcmUoXCJmcy1leHRyYVwiKTtcbmV4cG9ydCBsZXQgbWluaW1hdGNoID0gcmVxdWlyZShcIm1pbmltYXRjaFwiKTtcbmV4cG9ydCBpbXBvcnQgcGF0aCA9IHJlcXVpcmUoXCJwYXRoXCIpO1xuZXhwb3J0IGltcG9ydCBzbWFydGZpbGUgPSByZXF1aXJlKFwic21hcnRmaWxlXCIpO1xuZXhwb3J0IGltcG9ydCBzbWFydHBhdGggPSByZXF1aXJlKFwic21hcnRwYXRoXCIpOyJdfQ==
+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2016 Push.Rocks
Copyright (c) 2026 Task Venture Capital GmbH <hello@task.vc>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+38
View File
@@ -0,0 +1,38 @@
{
"@ship.zone/szci": {
"npmGlobalTools": [],
"npmRegistryUrl": "registry.npmjs.org"
},
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartssh",
"shortDescription": "SSH automation utilities",
"description": "Secure SSH configuration, key management, and remote machine control for TypeScript.",
"npmPackagename": "@push.rocks/smartssh",
"license": "MIT",
"keywords": [
"SSH",
"SSH configuration",
"SSH keys management",
"automation",
"development tools",
"node.js",
"security",
"server management"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"@git.zone/tsdoc": {
"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
View File
@@ -1,3 +0,0 @@
{
"mode":"default"
}
+55 -23
View File
@@ -1,39 +1,71 @@
{
"name": "smartssh",
"version": "1.1.0",
"description": "setups SSH quickly and in a painless manner",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"name": "@push.rocks/smartssh",
"version": "2.1.0",
"private": false,
"description": "Secure SSH configuration, key management, and remote machine control for TypeScript.",
"exports": {
".": "./dist_ts/index.js"
},
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "(npmts)"
"test": "tstest test/",
"testDocker": "tsdocker",
"build": "tsbuild",
"buildDocs": "tsdoc"
},
"repository": {
"type": "git",
"url": "git+https://gitlab.com/pushrocks/smartssh.git"
"url": "https://code.foss.global/push.rocks/smartssh.git"
},
"keywords": [
"SSH",
"ENV",
"base64"
"SSH configuration",
"SSH keys management",
"automation",
"development tools",
"node.js",
"security",
"server management"
],
"author": "Lossless GmbH",
"author": "Task Venture Capital GmbH <hello@task.vc>",
"license": "MIT",
"bugs": {
"url": "https://gitlab.com/pushrocks/smartssh/issues"
"url": "https://code.foss.global/push.rocks/smartssh/issues"
},
"homepage": "https://gitlab.com/pushrocks/smartssh#readme",
"homepage": "https://code.foss.global/push.rocks/smartssh",
"dependencies": {
"beautylog": "^5.0.12",
"fs-extra": "^0.30.0",
"js-base64": "^2.1.9",
"minimatch": "^3.0.2",
"smartfile": "^4.0.5",
"smartpath": "^3.2.2",
"typings-global": "^1.0.3",
"typings-test": "^1.0.1"
"@push.rocks/smartcrypto": "^2.0.4",
"@push.rocks/smartjson": "^6.0.1",
"@push.rocks/smartpath": "^6.0.0",
"@push.rocks/smartstring": "^4.1.1",
"@types/fs-extra": "^11.0.4",
"@types/ssh2": "^1.15.5",
"fs-extra": "^11.3.4",
"minimatch": "^10.2.5",
"ssh2": "^1.17.0"
},
"devDependencies": {
"npmts-g": "^5.2.6",
"should": "^9.0.2"
}
"@git.zone/tsbuild": "^4.4.0",
"@git.zone/tstest": "^3.6.3",
"@types/node": "^25.6.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
".smartconfig.json",
"license",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
]
}
+7694
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
+430
View File
@@ -0,0 +1,430 @@
# @push.rocks/smartssh
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
```bash
pnpm add @push.rocks/smartssh
```
## What It Does
- 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.
## Quick Start
```typescript
import { SshClient, SshKey } from '@push.rocks/smartssh';
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,
});
```
Do not disable host checking for production infrastructure unless another trust layer is already enforcing host identity.
## Key Management
Create keys in memory:
```typescript
import { SshKey } from '@push.rocks/smartssh';
const githubKey = new SshKey({
host: 'github.com',
private: process.env.GITHUB_PRIVATE_KEY,
public: process.env.GITHUB_PUBLIC_KEY,
});
console.log(githubKey.type); // 'duplex', 'private', 'public', or undefined
console.log(githubKey.privKeyBase64);
```
Load keys from files:
```typescript
const deployKey = SshKey.fromFile('/home/deploy/.ssh/id_ed25519');
const combinedKey = SshKey.fromFiles({
host: 'production-app',
privateKeyPath: '/home/deploy/.ssh/production-app',
publicKeyPath: '/home/deploy/.ssh/production-app.pub',
});
```
Store keys safely:
```typescript
await combinedKey.store('/home/deploy/.ssh');
```
## OpenSSH Config Management
Use `SshInstance` when you want to manage a whole SSH directory and config file.
```typescript
import { SshInstance, SshKey } from '@push.rocks/smartssh';
const sshInstance = new SshInstance({
sshDirPath: '/home/deploy/.ssh',
strictHostKeyChecking: true,
});
sshInstance.addKey(
new SshKey({
host: 'git.example.com',
private: process.env.GIT_PRIVATE_KEY,
public: process.env.GIT_PUBLIC_KEY,
})
);
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);
}
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',
});
```
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 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 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
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.
+1
View File
@@ -0,0 +1 @@
somePrivateKey
+1
View File
@@ -0,0 +1 @@
somePublicKey
+15
View File
@@ -0,0 +1,15 @@
Host gitlab.com
HostName gitlab.com
IdentityFile ~/.ssh/gitlab.com
StrictHostKeyChecking no
Host bitbucket.org
HostName bitbucket.org
IdentityFile ~/.ssh/bitbucket.org
StrictHostKeyChecking no
Host github.com
HostName github.com
IdentityFile ~/.ssh/github.com
StrictHostKeyChecking no
+1
View File
@@ -0,0 +1 @@
someExamplePrivateKey
+1
View File
@@ -0,0 +1 @@
someExamplePublicKey
+1
View File
@@ -0,0 +1 @@
someGitHubPrivateKey
+1
View File
@@ -0,0 +1 @@
someGitHubPublicKey
+1
View File
@@ -0,0 +1 @@
somePrivateKey
+1
View File
@@ -0,0 +1 @@
somePublicKey
-2
View File
@@ -1,2 +0,0 @@
import "typings-test";
import "should";
-69
View File
File diff suppressed because one or more lines are too long
+214
View File
@@ -0,0 +1,214 @@
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',
private: 'someExamplePrivateKey',
public: 'someExamplePublicKey',
});
expect(testSshKey).toBeInstanceOf(smartssh.SshKey);
});
tap.test('.type should be a valid type', async () => {
expect(testSshKey.type).toEqual('duplex');
});
tap.test('.publicKey should be public key', async () => {
expect(testSshKey.pubKey).toEqual('someExamplePublicKey');
});
tap.test('.privateKey should be private key', async () => {
expect(testSshKey.privKey).toEqual('someExamplePrivateKey');
});
tap.test('.publicKeyBase64 should be public key base 64 encoded', async () => {
// tslint:disable-next-line:no-unused-expression
testSshKey.pubKeyBase64;
});
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
tap.test("'new' keyword should create a new SshInstance object from class", async () => {
testSshInstance = new smartssh.SshInstance({
sshDirPath: testDir,
});
expect(testSshInstance).toBeInstanceOf(smartssh.SshInstance);
});
tap.test('.addKey() should accept a new SshKey object', async () => {
testSshInstance.addKey(
new smartssh.SshKey({
public: 'somePublicKey',
private: 'somePrivateKey',
host: 'gitlab.com',
})
);
testSshInstance.addKey(
new smartssh.SshKey({
public: 'somePublicKey',
private: 'somePrivateKey',
host: 'bitbucket.org',
})
);
testSshInstance.addKey(
new smartssh.SshKey({
public: 'someGitHubPublicKey',
private: 'someGitHubPrivateKey',
host: 'github.com',
})
);
});
tap.test('.sshKeys should point to an array of sshKeys', async () => {
let sshKeyArray = testSshInstance.sshKeys;
expect(sshKeyArray).toBeInstanceOf(Array);
expect(sshKeyArray[0].host).toEqual('gitlab.com');
expect(sshKeyArray[1].host).toEqual('bitbucket.org');
expect(sshKeyArray[2].host).toEqual('github.com');
});
tap.test('.getKey() should get a specific key selected by host', async () => {
const sshKey = testSshInstance.getKey('github.com');
expect(sshKey).toBeInstanceOf(smartssh.SshKey);
expect(sshKey?.pubKey).toEqual('someGitHubPublicKey');
});
tap.test('.removeKey() should remove a key', async () => {
const sshKey = testSshInstance.getKey('bitbucket.org');
expect(sshKey).toBeInstanceOf(smartssh.SshKey);
testSshInstance.removeKey(sshKey!);
expect(testSshInstance.sshKeys[1].host).toEqual('github.com');
});
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();
-66
View File
@@ -1,66 +0,0 @@
import "typings-test"
import "should";
import smartssh = require("../dist/index");
describe("smartssh",function(){
let testSshInstance:smartssh.SshInstance;
let testSshKey:smartssh.SshKey;
describe(".SshKey",function(){
it("'new' keyword should create a valid SshKey object",function(){
testSshKey = new smartssh.SshKey({
host:"example.com",
private:"someExamplePrivateKey",
public:"someExamplePublicKey"
});
testSshKey.should.be.instanceof(smartssh.SshKey);
});
it(".type should be a valid type",function(){
testSshKey.type.should.equal("duplex");
});
it(".publicKey should be public key",function(){
testSshKey.pubKey.should.equal("someExamplePublicKey");
});
it(".privateKey should be private key",function(){
testSshKey.privKey.should.equal("someExamplePrivateKey");
});
it(".publicKeyBase64 should be public key base 64 encoded",function(){
testSshKey.pubKeyBase64;
})
});
describe(".SshInstance",function(){
it("'new' keyword should create a new SshInstance object from class",function(){
testSshInstance = new smartssh.SshInstance();
testSshInstance.should.be.instanceof(smartssh.SshInstance);
});
it(".addKey() should accept a new SshKey object",function(){
testSshInstance.addKey(new smartssh.SshKey({
public:"somePublicKey",
private:"somePrivateKey",
host:"gitlab.com"
}));
testSshInstance.addKey(new smartssh.SshKey({
public:"somePublicKey",
private:"somePrivateKey",
host:"bitbucket.org"
}));
testSshInstance.addKey(new smartssh.SshKey({
public:"someGitHubPublicKey",
private:"someGitHubPrivateKey",
host:"github.com"
}));
});
it(".sshKeys should point to an array of sshKeys",function(){
let sshKeyArray = testSshInstance.sshKeys;
sshKeyArray.should.be.Array();
sshKeyArray[0].host.should.equal("gitlab.com");
sshKeyArray[1].host.should.equal("bitbucket.org");
sshKeyArray[2].host.should.equal("github.com");
});
it(".getKey() should get a specific key selected by host",function(){
testSshInstance.getKey("github.com").pubKey.should.equal("someGitHubPublicKey");
})
it(".removeKey() should remove a key",function(){
testSshInstance.removeKey(testSshInstance.getKey("bitbucket.org"));
testSshInstance.sshKeys[1].host.should.equal("github.com");
})
});
})
+8
View File
@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartssh',
version: '2.1.0',
description: 'Secure SSH configuration, key management, and remote machine control for TypeScript.'
}
+23 -6
View File
@@ -1,7 +1,24 @@
import "typings-global"
import * as plugins from "./smartssh.plugins";
import * as plugins from './smartssh.plugins.js';
export {SshInstance} from "./smartssh.classes.sshinstance";
export {SshKey} from "./smartssh.classes.sshkey";
export {SshDir} from "./smartssh.classes.sshdir";
export {SshConfig} from "./smartssh.classes.sshconfig";
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';
+106 -7
View File
@@ -1,8 +1,107 @@
import "typings-global"
import * as plugins from "./smartssh.plugins";
import {SshKey} from "./smartssh.classes.sshkey";
import * as plugins from './smartssh.plugins.js';
import { SshKey } from './smartssh.classes.sshkey.js';
export let sshKeyArrayFromDir = function(dirArg:string):SshKey[]{
let sshKeyArray = []; //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;
}
}
+118 -20
View File
@@ -1,26 +1,124 @@
import "typings-global";
import * as plugins from "./smartssh.plugins";
import * as helpers from "./smartssh.classes.helpers";
import {SshKey} from "./smartssh.classes.sshkey"
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 {
sshKeyArray:SshKey[];
constructor(sshKeyArrayArg:SshKey[]){
this.sshKeyArray = sshKeyArrayArg;
private _sshKeyArray: 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) {
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 +
'\n' +
' HostName ' +
sshKey.host +
'\n' +
' 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,
authorized: sshKey.authorized,
sshKey: sshKey,
});
}
let configFile: string = '';
for (const config of configArray) {
configFile = configFile + config.configString + '\n';
}
plugins.fs.writeFileSync(plugins.path.join(resolvedDir, 'config'), configFile);
plugins.fs.chmodSync(plugins.path.join(resolvedDir, 'config'), 0o600);
}
read(dirPathArg: string) {
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;
}
}
/**
* the current config
*/
get config(){
let configArray:configObject[];
return configArray;
}
};
return blocks;
}
}
export interface configObject {
host:string;
authorized:boolean;
sshKey:SshKey;
};
configString: string;
authorized: boolean;
sshKey: SshKey;
}
+42 -27
View File
@@ -1,30 +1,45 @@
import "typings-global";
import * as plugins from "./smartssh.plugins";
import * as helpers from "./smartssh.classes.helpers";
import {SshInstance} from "./smartssh.classes.sshinstance";
import {SshKey} from "./smartssh.classes.sshkey";
import {SshConfig} from "./smartssh.classes.sshconfig";
export class SshDir { // sshDir class -> NOT EXPORTED, ONLY FOR INTERNAL USE
path:string; // the path of the ssh directory
private sshKeyArray:SshKey[];
constructor(sshKeyArray:SshKey[],sshDirPathArg?:string){
this.sshKeyArray = sshKeyArray;
if(sshDirPathArg){
this.path = sshDirPathArg;
} else {
this.path = plugins.path.join(plugins.smartpath.get.home(),".ssh/");
};
}
writeToDir(){ // syncs sshInstance to directory
this.sshKeyArray.forEach((sshKeyArg) => {
sshKeyArg.store(this.path);
import * as plugins from './smartssh.plugins.js';
import * as helpers from './smartssh.classes.helpers.js';
import { SshKey } from './smartssh.classes.sshkey.js';
import { SshConfig } from './smartssh.classes.sshconfig.js';
});
};
readFromDir(){ // syncs sshInstance from directory
export class SshDir {
// sshDir class -> NOT EXPORTED, ONLY FOR INTERNAL USE
private _path: string; // the path of the ssh directory
private _sshKeyArray: SshKey[];
private _sshConfig: SshConfig;
constructor(sshKeyArray: SshKey[], sshConfig: SshConfig, sshDirPathArg?: string) {
this._sshKeyArray = sshKeyArray;
this._sshConfig = sshConfig;
if (sshDirPathArg) {
this._path = helpers.resolveSshDirPath(sshDirPathArg);
} else {
this._path = helpers.resolveSshDirPath();
}
}
}
getKeys(){
return helpers.sshKeyArrayFromDir(this.path);
}
writeToDir(dirPathArg?: string) {
// syncs sshInstance to directory
let path = this._path;
if (dirPathArg) path = helpers.resolveSshDirPath(dirPathArg);
this._sshKeyArray.forEach((sshKeyArg) => {
sshKeyArg.storeSync(path);
});
this._sshConfig.store(path);
}
readFromDir(dirPathArg?: string) {
// syncs sshInstance from directory
let path = this._path;
if (dirPathArg) path = helpers.resolveSshDirPath(dirPathArg);
const sshKeys = helpers.sshKeyArrayFromDir(path);
this._sshKeyArray.splice(0, this._sshKeyArray.length, ...sshKeys);
}
updateDirPath(dirPathArg: string) {
this._path = helpers.resolveSshDirPath(dirPathArg);
}
getKeys() {
return helpers.sshKeyArrayFromDir(this._path);
}
}
+89 -91
View File
@@ -1,105 +1,103 @@
import "typings-global"
import * as plugins from "./smartssh.plugins";
import * as helpers from "./smartssh.classes.helpers";
import * as plugins from './smartssh.plugins.js';
import {SshDir} from "./smartssh.classes.sshdir";
import {SshConfig} from "./smartssh.classes.sshconfig";
import {SshKey} from "./smartssh.classes.sshkey";
import { SshDir } from './smartssh.classes.sshdir.js';
import { SshConfig, type ISshConfigOptions } from './smartssh.classes.sshconfig.js';
import { SshKey } from './smartssh.classes.sshkey.js';
/**
* SshInstance is the main class dealing with ssh management
*/
export class SshInstance {
private _sshKeyArray:SshKey[]; //holds all ssh keys
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}={}){
optionsArg ? void(0) : optionsArg = {};
this._sshKeyArray = [];
this._sshConfig = new SshConfig(this._sshKeyArray);
this._sshDir = new SshDir(this._sshKeyArray,optionsArg.sshDirPath);
this._sshSync = optionsArg.sshSync;
};
private _sshKeyArray: SshKey[]; // holds all ssh keys
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 } & ISshConfigOptions = {}) {
optionsArg ? void 0 : (optionsArg = {});
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;
}
//altering methods
addKey(sshKeyArg:SshKey){
this._syncAuto("from");
this._sshKeyArray.push(sshKeyArg);
this._syncAuto("to");
};
removeKey(sshKeyArg:SshKey){
this._syncAuto("from");
let filteredArray = this._sshKeyArray.filter((sshKeyArg2:SshKey) => {
return (sshKeyArg != sshKeyArg2);
});
this._sshKeyArray = filteredArray;
this._syncAuto("to");
};
replaceKey(sshKeyOldArg:SshKey,sshKeyNewArg:SshKey){
this._syncAuto("from");
this.removeKey(sshKeyOldArg);
this.addKey(sshKeyNewArg);
this._syncAuto("to");
};
//
getKey(hostArg:string):SshKey{
this._syncAuto("from");
let filteredArray = this._sshKeyArray.filter(function(keyArg){
return (keyArg.host == hostArg);
});
if(filteredArray.length > 0){
return filteredArray[0];
} else {
return undefined;
}
};
get sshKeys():SshKey[] {
this._syncAuto("from");
return this._sshKeyArray;
};
//FS methods
/**
* write SshInstance to disk
*/
writeToDisk(){
this._sync("to");
// altering methods
addKey(sshKeyArg: SshKey) {
this._syncAuto('from');
this._sshKeyArray.push(sshKeyArg);
this._syncAuto('to');
}
removeKey(sshKeyArg: SshKey) {
this._syncAuto('from');
const sshKeyIndex = this._sshKeyArray.indexOf(sshKeyArg);
if (sshKeyIndex >= 0) {
this._sshKeyArray.splice(sshKeyIndex, 1);
}
this._syncAuto('to');
}
replaceKey(sshKeyOldArg: SshKey, sshKeyNewArg: SshKey) {
this._syncAuto('from');
this.removeKey(sshKeyOldArg);
this.addKey(sshKeyNewArg);
this._syncAuto('to');
}
/**
* read ab SshInstance from disk
*/
readFromDisk(){
this._sync("from");
// non altering methods
getKey(hostArg: string): SshKey | undefined {
this._syncAuto('from');
let filteredArray = this._sshKeyArray.filter(function (keyArg) {
return keyArg.host === hostArg;
});
if (filteredArray.length > 0) {
return filteredArray[0];
} else {
return undefined;
}
}
get sshKeys(): SshKey[] {
this._syncAuto('from');
return this._sshKeyArray;
}
/* ===============================================================
========================= Private Methods ========================
================================================================*/
// FS methods
private _makeConfig (){
/**
* write SshInstance to disk
*/
writeToDisk(dirPathArg?: string) {
this._sync('to', dirPathArg);
}
/**
* read ab SshInstance from disk
*/
readFromDisk(dirPathArg?: string) {
this._sync('from', dirPathArg);
}
/* ===============================================================
========================= Private Methods ========================
================================================================*/
/**
* method to invoke SshInstance _sync automatically when sshSync is true
*/
private _syncAuto(directionArg: 'from' | 'to') {
if (this._sshSync) {
// if auto sync is not enabled, do nothing
this._sync(directionArg);
}
}
/**
* method to invoke SshInstance _sync automatically when sshSync is true
*/
private _syncAuto(directionArg){
if(this._sshSync) this._sync(directionArg);
/**
* private method to sync SshInstance
*/
private _sync(directionArg: 'from' | 'to', dirPathArg?: string) {
if (directionArg === 'from') {
this._sshDir.readFromDir(dirPathArg); // call sync method of sshDir class;
} else if (directionArg === 'to') {
this._sshDir.writeToDir(dirPathArg);
}
/**
* private method to sync SshInstance
*/
private _sync(directionArg:string){
if(directionArg == "from"){
this._sshDir.readFromDir(); // call sync method of sshDir class;
} else if(directionArg == "to") {
this._sshDir.writeToDir();
} else {
throw new Error("directionArg not recognised. Must be 'to' or 'from'");
}
};
}
}
+139 -75
View File
@@ -1,89 +1,153 @@
import "typings-global";
import * as plugins from "./smartssh.plugins";
import * as helpers from "./smartssh.classes.helpers";
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;
private _hostVar:string;
private _authorized:boolean;
constructor(optionsArg:{private?:string,public?:string,host?:string,authorized?:boolean}={}){
this._privKey = optionsArg.private;
this._pubKey = optionsArg.public;
this._hostVar = optionsArg.host;
this._authorized = optionsArg.authorized;
};
private _privKey: string;
private _pubKey: string;
private _hostVar: string;
private _authorized: boolean;
// this.host
get host(){
return this._hostVar;
};
set host(hostArg:string){
this._hostVar = hostArg;
};
// this.privKey
get privKey(){
return this._privKey;
};
set privKey(privateKeyArg:string){
this._privKey = privateKeyArg;
};
// this.privKeyBase64
get privKeyBase64(){
return plugins.base64.encode(this._privKey);
}
set privKeyBase64(privateKeyArg:string) {
this._privKey = plugins.base64.decode(privateKeyArg);
/**
* the constructor for class SshKey
*/
constructor(
optionsArg: { private?: string; public?: string; host?: string; authorized?: boolean } = {}
) {
this._privKey = optionsArg.private ?? '';
this._pubKey = optionsArg.public ?? '';
if (optionsArg.host) {
helpers.assertSafeHost(optionsArg.host);
}
this._hostVar = optionsArg.host ?? '';
this._authorized = optionsArg.authorized ?? false;
}
// this.pubKey
get pubKey(){
return this._pubKey;
// this.host
get host() {
return this._hostVar;
}
set host(hostArg: string) {
if (hostArg) {
helpers.assertSafeHost(hostArg);
}
set pubKey(publicKeyArg:string){
this._pubKey = publicKeyArg;
};
this._hostVar = hostArg;
}
// this.pubKeyBase64
get pubKeyBase64(){
return plugins.base64.encode(this._pubKey);
}
set pubKeyBase64(publicKeyArg:string) {
this._pubKey = plugins.base64.decode(publicKeyArg);
}
// this.privKey
get privKey() {
return this._privKey;
}
set privKey(privateKeyArg: string) {
this._privKey = privateKeyArg;
}
// this.privKeyBase64
get privKeyBase64() {
return plugins.smartstring.base64.encode(this._privKey);
}
set privKeyBase64(privateKeyArg: string) {
this._privKey = plugins.smartstring.base64.decode(privateKeyArg);
}
get type(){
if(this._privKey && this._pubKey){
return "duplex";
} else if(this._privKey){
return "private";
} else if(this._pubKey){
return "public";
}
};
set type(someVlueArg:any){
console.log("the type of an SshKey connot be set. This value is autpcomputed.")
}
// this.pubKey
get pubKey() {
return this._pubKey;
}
set pubKey(publicKeyArg: string) {
this._pubKey = publicKeyArg;
}
// methods
read(filePathArg){
// this.pubKeyBase64
get pubKeyBase64() {
return plugins.smartstring.base64.encode(this._pubKey);
}
set pubKeyBase64(publicKeyArg: string) {
this._pubKey = plugins.smartstring.base64.decode(publicKeyArg);
}
get authorized() {
return this._authorized;
}
set authorized(authorizedArg: boolean) {
this._authorized = authorizedArg;
}
/**
* returns wether there is a private, a public or both keys
*/
get type(): TSshKeyType | undefined {
if (this._privKey && this._pubKey) {
return 'duplex';
} else if (this._privKey) {
return 'private';
} else if (this._pubKey) {
return 'public';
}
store(filePathArg?:string){
let filePathObj = plugins.path.parse(filePathArg);
if(filePathObj.ext = ".priv"){
plugins.smartfile.memory.toFsSync(this._privKey,filePathArg);
} else if (filePathObj.ext = ".pub"){
plugins.smartfile.memory.toFsSync(this._pubKey,filePathArg);
} else { //we assume we are given a directory as filePathArg, so we store the whole key
plugins.fs.ensureDirSync(filePathObj.dir);
this.store(plugins.path.join(filePathObj.dir,"key.priv")); // call this function recursivly
this.store(plugins.path.join(filePathObj.dir,"key.pub")); // call this function recursivly
}
}
// methods
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) {
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) {
const filePath = plugins.path.join(resolvedDir, fileNameBase);
plugins.fs.writeFileSync(filePath, this._privKey);
plugins.fs.chmodSync(filePath, 0o600);
}
if (this._pubKey) {
const filePath = plugins.path.join(resolvedDir, fileNameBase + '.pub');
plugins.fs.writeFileSync(filePath, this._pubKey);
plugins.fs.chmodSync(filePath, 0o644);
}
}
}
let testKey = new SshKey();
+25 -8
View File
@@ -1,8 +1,25 @@
import "typings-global"
export import beautylog = require("beautylog");
export let base64 = require("js-base64").Base64;
export let fs = require("fs-extra");
export let minimatch = require("minimatch");
export import path = require("path");
export import smartfile = require("smartfile");
export import smartpath = require("smartpath");
// node native
import * as crypto from 'crypto';
import fs from 'fs-extra';
import * as path from 'path';
export { crypto, fs, path };
// @push.rocks scope
import * as smartjson from '@push.rocks/smartjson';
import * as smartcrypto from '@push.rocks/smartcrypto';
import * as smartpath from '@push.rocks/smartpath';
import * as smartstring from '@push.rocks/smartstring';
export {
smartjson,
smartcrypto,
smartpath,
smartstring,
};
// third party scope
import * as minimatch from 'minimatch';
import ssh2 from 'ssh2';
export { minimatch, ssh2 };
-8
View File
@@ -1,8 +0,0 @@
{
"version": false,
"dependencies": {},
"ambientDependencies": {
"colors": "registry:dt/colors#0.6.0-1+20160317120654",
"node": "registry:dt/node#4.0.0+20160423143914"
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noImplicitAny": true,
"esModuleInterop": true,
"verbatimModuleSyntax": true,
"types": ["node"]
},
"exclude": [
"dist_*/**/*.d.ts"
]
}