by Helena

Pure JavaScript SSH2 client and server modules for Node.js, supporting exec, shell, SFTP, port forwarding, X11, and key-based authentication. Ideal for backend automation, tunneling, and remote server management.
This block provides a complete SSH2 client and server implementation for Node.js, supporting exec, shell, SFTP, port forwarding, X11, and agent authentication. It is drawn from user@example.com and targets backend engineers who need to programmatically connect to SSH servers, build SSH servers, or transfer files over SFTP without shelling out to system binaries.
index.js - Main entry point; re-exports Client, Server, agents, HTTP agents, and utilitiesclient.js - Client class: connects to SSH servers, opens channels, runs commands, starts shells, manages SFTPserver.js - Server class: accepts SSH connections, handles authentication contexts, sessionsagent.js - SSH agent classes (BaseAgent, OpenSSHAgent, CygwinAgent, PageantAgent, AgentProtocol) and createAgenthttp-agents.js - HTTPAgent / HTTPSAgent for tunneling HTTP(S) requests over an SSH connectionkeygen.js - generateKeyPair / generateKeyPairSync for RSA, ECDSA, and Ed25519 key generationutils.js - Internal channel/stream utilities shared by client and serverChannel.js - Channel duplex stream representing a single SSH channelprotocol/ - Low-level SSH protocol: crypto, KEX, key parsing, SFTP protocol, constants, handlersprotocol/Protocol.js - Core protocol state machineprotocol/SFTP.js - SFTP subsystem implementation with OPEN_MODE, STATUS_CODE, flag helpersprotocol/keyParser.js - parseKey: parse PEM/OpenSSH public and private keysprotocol/constants.js - All SSH protocol constantsprotocol/crypto.js - Cipher/MAC/compression initialisationprotocol/kex.js - Key exchange logicprotocol/utils.js - Buffer parsing helpersprotocol/zlib.js - Compression supportprotocol/handlers.js / - Inbound packet handlersSpin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This JavaScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 a601efe3b6410d5b…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
protocol/handlers.misc.jsprotocol/node-fs-compat.js - Node.js fs compatibility shimprotocol/crypto/ - Poly1305 and optional native crypto bindingnpm install asn1 bcrypt-pbkdf
No native build steps are required for core operation. An optional cpu-features native addon may be installed to improve cipher selection performance; if it fails to build it is silently ignored:
npm install cpu-features # optional; requires a C++ build toolchain (node-gyp)
source/ directory into your project, e.g. src/vendor/ssh2/.npm install --save-dev @types/ssh2
tsconfig.json add a path alias if desired:
{
"compilerOptions": {
"paths": {
"ssh2": ["./src/vendor/ssh2/index.js"]
}
}
}
require-based). In an ESM project use dynamic import() or set "type": "commonjs" in the nearest package.json.utils.sftp namespace exposed by index.js.import { Client } from './src/vendor/ssh2/index.js';
const conn = new Client();
conn.connect(config: ConnectConfig): void;
conn.exec(command: string, options?: ExecOptions, callback: (err, stream) => void): boolean;
conn.shell(options?: PseudoTtyOptions | false, callback: (err, stream) => void): boolean;
conn.sftp(callback: (err, sftp: SFTPWrapper) => void): boolean;
conn.end(): void;
// Events: 'ready', 'error', 'close', 'keyboard-interactive', 'tcp/ip forward', ...
Client is the primary class for outbound SSH connections. Instantiate it, attach a ready listener, then call connect() with host/port/credentials. All channel-opening methods (exec, shell, sftp, forwardOut, etc.) must be called inside the ready handler.
import { Server } from './src/vendor/ssh2/index.js';
const srv = new Server(options: ServerConfig, connectionListener?: (client, info) => void);
srv.listen(port: number, host?: string, callback?: () => void): Server;
srv.close(callback?: () => void): void;
// Connection events: 'authentication', 'ready', 'session', 'request', 'tcpip', ...
Server accepts inbound SSH connections. Supply at least one host key in options.hostKeys. Handle the connection event (or pass a listener to the constructor) to receive Client connection objects, then subscribe to authentication to validate credentials and session to handle channel requests.
import { utils } from './src/vendor/ssh2/index.js';
utils.parseKey(keyData: string | Buffer, passphrase?: string | Buffer):
ParsedKey | ParsedKey[] | Error | null;
Parses PEM, PKCS#8, or OpenSSH-format public or private keys. Returns a ParsedKey object (or array for files containing multiple keys) with .sign(), .verify(), .getPublicSSH(), and .equals() methods. Returns an Error instance (not thrown) on parse failure. Use this to pre-validate host keys or user public keys before passing them to connect() or an auth context.
import { utils } from './src/vendor/ssh2/index.js';
utils.generateKeyPair(
type: 'rsa' | 'ecdsa' | 'ed25519',
options: KeyPairOptions,
callback: (err, keys: { private: string; public: string }) => void
): void;
utils.generateKeyPairSync(
type: 'rsa' | 'ecdsa' | 'ed25519',
options: KeyPairOptions
): { private: string; public: string };
Generates SSH key pairs in OpenSSH wire format. RSA requires { bits: number }, ECDSA requires { bits: 256 | 384 | 521 }, Ed25519 takes no extra options. Use for automated key provisioning or test fixtures.
Connect to a remote host with a private key, run a command, and collect stdout/stderr.
import { readFileSync } from 'fs';
import { Client } from './src/vendor/ssh2/index.js';
const conn = new Client();
conn.on('ready', () => {
conn.exec('df -h', (err, stream) => {
if (err) throw err;
let stdout = '';
let stderr = '';
stream
.on('close', (code: number, signal: string) => {
console.log('exit code:', code);
console.log('stdout:', stdout);
console.error('stderr:', stderr);
conn.end();
})
.on('data', (chunk: Buffer) => { stdout += chunk; })
.stderr.on('data', (chunk: Buffer) => { stderr += chunk; });
});
}).on('error', (err: Error) => {
console.error('Connection error:', err.message);
}).connect({
host: '10.0.0.1',
port: 22,
username: 'deploy',
privateKey: readFileSync('/home/user/.ssh/id_ed25519'),
});
Open an SFTP session and write a local buffer to a remote path.
import { readFileSync } from 'fs';
import { Client } from './src/vendor/ssh2/index.js';
const conn = new Client();
const payload = Buffer.from('hello from ssh2\n');
conn.on('ready', () => {
conn.sftp((err, sftp) => {
if (err) throw err;
const writeStream = sftp.createWriteStream('/tmp/hello.txt');
writeStream.on('close', () => {
console.log('Upload complete');
conn.end();
});
writeStream.end(payload);
});
}).connect({
host: '10.0.0.1',
port: 22,
username: 'deploy',
privateKey: readFileSync('/home/user/.ssh/id_ed25519'),
});
Accept connections, validate a password, and handle an exec request.
import { readFileSync } from 'fs';
import { Server } from './src/vendor/ssh2/index.js';
import { utils } from './src/vendor/ssh2/index.js';
const hostKey = readFileSync('/etc/ssh/ssh_host_ed25519_key');
new Server({ hostKeys: [hostKey] }, (client) => {
client.on('authentication', (ctx) => {
if (ctx.method === 'password' && ctx.password === 'secret') {
ctx.accept();
} else {
ctx.reject(['password']);
}
});
client.on('ready', () => {
client.on('session', (accept) => {
const session = accept();
session.on('exec', (accept, reject, info) => {
console.log('exec:', info.command);
const stream = accept();
stream.stdout.write(`You ran: ${info.command}\n`);
stream.exit(0);
stream.close();
});
});
});
}).listen(2222, '0.0.0.0', () => {
console.log('SSH server listening on port 2222');
});
index.js - Aggregates and re-exports all public symbols; the sole import point for consumers.client.js - Full outbound SSH client; manages connection lifecycle, authentication, and all channel types.server.js - Inbound SSH server built on net.Server; exposes auth contexts and session objects.agent.js - SSH agent protocol client; OpenSSHAgent speaks to a UNIX socket, PageantAgent to Windows named pipe, CygwinAgent bridges the two. Extend BaseAgent for custom agents.http-agents.js - Drop-in http.Agent / https.Agent replacements that tunnel requests through an SSH connection using forwardOut.keygen.js - Wraps Node.js crypto.generateKeyPair to produce SSH-wire-format key strings with optional passphrase encryption.utils.js - Shared internal helpers: ChannelManager, generateAlgorithmList, isWritable, and channel-close callbacks.Channel.js - Duplex stream for a single SSH channel; handles windowing, extended data (stderr), and EOF/close sequencing.protocol/Protocol.js - Central SSH protocol state machine driving all packet I/O.protocol/SFTP.js - SFTP subsystem; exports OPEN_MODE, STATUS_CODE, flagsToString, stringToFlags.protocol/keyParser.js - Multi-format key parser supporting RSA, ECDSA, Ed25519, DSA in PEM and OpenSSH formats.protocol/constants.js - Numeric SSH protocol constants, algorithm name lists, disconnect reason codes.protocol/crypto.js - Cipher/MAC/AEAD initialisation; exports CIPHER_INFO and init.protocol/kex.js - Key exchange: DH, ECDH, curve25519, and KexInit negotiation.protocol/utils.js - Low-level buffer utilities: readUInt32BE, writeUInt32BE, makeBufferParser, sigSSHToASN1.protocol/zlib.js - Zlib compression/decompression for SSH transport.protocol/handlers.js / protocol/handlers.misc.js - Dispatch tables for inbound SSH packet types.protocol/node-fs-compat.js - Thin compatibility shim for Node.js fs differences across versions.protocol/crypto/ - Poly1305 MAC implementation and optional native C++ binding for performance.asn1 or bcrypt-pbkdf not found at runtime - These are runtime dependencies not bundled with Node; run npm install asn1 bcrypt-pbkdf in the project root before starting.parseKey returns an Error object instead of throwing - Always check if (result instanceof Error) before using the returned key; the API signals parse failure via return value, not exceptions.require in an ESM project causes ERR_REQUIRE_ESM or syntax errors - The source is CommonJS; in ESM files use const { Client } = await import('./src/vendor/ssh2/index.js') or add "type": "commonjs" to the vendor directory's package.json.0600; readFileSync itself does not validate permissions but the remote sshd may reject connections from clients presenting keys generated from world-readable files.open() flags must use OPEN_MODE constants, not string literals - Import utils.sftp.OPEN_MODE and combine flags with bitwise OR: OPEN_MODE.READ | OPEN_MODE.WRITE; passing raw integers not derived from these constants causes protocol errors on some servers.generateKeyPairSync throws TypeError: Key type must be a string - The first argument must be the lowercase string 'rsa', 'ecdsa', or 'ed25519'; passing a capitalized or enum value is not accepted.I have copied the ssh2 library source (ssh2@1.17.0) into `src/vendor/ssh2/`.
The integration guide is in `USAGE.md` next to this message.
Please help me integrate ssh2 into my project step by step:
1. Read `USAGE.md` and the file walkthrough to understand what each file in
`src/vendor/ssh2/` does.
2. Add the required runtime dependencies (`asn1`, `bcrypt-pbkdf`) to
`package.json` and provide the install command.
3. Import `Client` and/or `Server` from `src/vendor/ssh2/index.js` (not from
the npm registry) in the file I specify.
4. Write a working example for my use case (described below) using only the
real exports visible in USAGE.md: Client, Server, utils.parseKey,
utils.generateKeyPair, utils.sftp.OPEN_MODE, HTTPAgent, HTTPSAgent,
AgentProtocol, BaseAgent, OpenSSHAgent.
5. Do not invent methods or options not documented in USAGE.md or visible in
the source excerpts.
6. Flag any CJS/ESM interop issues for my module system.
My use case:
[DESCRIBE YOUR USE CASE HERE - e.g. "connect to a remote server, run a
command, and stream output to an HTTP response"]
ssh2 is released under the MIT License. See source/LICENSE if present, or refer to the upstream repository. Original package: ssh2 on npm by Brian White (mscdex), version 1.17.0.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free