{"id":14050,"library":"ssh2-streams","title":"SSH2 and SFTP Protocol Streams for Node.js","description":"ssh2-streams is a low-level Node.js library that provides direct, stream-based implementations of the SSH2 and SFTPv3 client/server protocols. It serves as a foundational component for higher-level SSH libraries, such as `ssh2`, offering granular control over the protocol handshake, channel management, and data transfer mechanisms. The current stable version is 0.4.10, and as a core utility, its release cadence is typically driven by security patches, bug fixes, and minor protocol compliance updates rather than rapid feature development. Its primary differentiators include its efficient Node.js stream integration, allowing for flexible and performant handling of network I/O, and its commitment to exposing the raw protocol events and structures, enabling developers to build custom SSH or SFTP solutions with deep control over the underlying communication. It requires Node.js v5.10.0 or newer.","status":"active","version":"0.4.10","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/mscdex/ssh2-streams","tags":["javascript","ssh","ssh2","sftp","secure","protocol","streams","client","server"],"install":[{"cmd":"npm install ssh2-streams","lang":"bash","label":"npm"},{"cmd":"yarn add ssh2-streams","lang":"bash","label":"yarn"},{"cmd":"pnpm add ssh2-streams","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primary export via CommonJS `require`. Direct ESM `import` is not supported without transpilation or Node.js CJS interop for default exports.","wrong":"import { SSH2Stream } from 'ssh2-streams';","symbol":"SSH2Stream","correct":"const { SSH2Stream } = require('ssh2-streams');"},{"note":"Similar to SSH2Stream, this is a named CommonJS export representing the SFTPv3 protocol stream.","wrong":"import { SFTPStream } from 'ssh2-streams';","symbol":"SFTPStream","correct":"const { SFTPStream } = require('ssh2-streams');"},{"note":"Contains helper functions, such as `fingerprint` for generating host key fingerprints.","wrong":"import { utils } from 'ssh2-streams';","symbol":"utils","correct":"const { utils } = require('ssh2-streams');"},{"note":"Provides SSH protocol constants for various message types, reason codes, and channel types.","wrong":"import { constants } from 'ssh2-streams';","symbol":"constants","correct":"const { constants } = require('ssh2-streams');"}],"quickstart":{"code":"const { SSH2Stream, utils, constants } = require('ssh2-streams');\nconst net = require('net');\n\n// This quickstart demonstrates how to initialize an SSH2Stream and set up\n// basic event listeners to observe the SSH protocol negotiation.\n// In a real-world scenario, you would pipe a connected net.Socket instance\n// to this SSH2Stream to process the raw SSH protocol bytes.\n// ssh2-streams itself does not handle the network connection.\n\nconst stream = new SSH2Stream();\n\n// Listen for the initial SSH protocol header from the remote party\nstream.on('header', (headerInfo) => {\n  console.log('SSH Header Received:', headerInfo);\n  console.log(`Remote software: ${headerInfo.versions.software}`);\n  // A real client would send its own header back: stream.write(Buffer.from('SSH-2.0-MyClient\\r\\n'));\n});\n\n// This event is crucial for host key verification in client implementations.\n// The default behavior is to auto-allow any host key if no handler is present.\nstream.on('fingerprint', (hostKeyBuffer, callback) => {\n  const finger = utils.fingerprint(hostKeyBuffer);\n  console.log('Received Host Key Fingerprint:', finger);\n  // In a production client, you'd compare 'finger' to known_hosts.\n  // For this example, we unconditionally accept the host key.\n  callback(true);\n});\n\n// Event for when new encryption keys have been exchanged\nstream.on('NEWKEYS', () => {\n  console.log('New encryption keys have been successfully exchanged.');\n  // After NEWKEYS, authentication can begin.\n});\n\n// Handle general errors that might occur within the stream processing\nstream.on('error', (err) => {\n  console.error('SSHStream encountered an error:', err.message);\n});\n\n// Listen for a disconnect message from the remote party\nstream.on('DISCONNECT', (reason, reasonCode, description) => {\n  console.warn(`Disconnected by remote: [${reasonCode}] ${reason} - ${description}`);\n});\n\nconsole.log('SSH2Stream initialized. Attach a net.Socket to this stream to start protocol communication.');\nconsole.log('Example of using utilities: SHA256 fingerprint for a dummy key:',\n  utils.fingerprint(Buffer.from('-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs...-----END PUBLIC KEY-----')));\nconsole.log('Example protocol constant:',\n  `Disconnect Reason: ${constants.DISCONNECT_REASON_CODE_NAMES[constants.DISCONNECT_REASON.HOST_NOT_ALLOWED_TO_CONNECT]}`);\n\n// To make this quickstart runnable, you would pipe a connected net.Socket to the stream:\n/*\nconst clientSocket = net.connect(22, 'localhost', () => {\n  clientSocket.pipe(stream).pipe(clientSocket);\n  // stream.write(...) would send data over the SSH protocol.\n});\n*/","lang":"javascript","description":"This quickstart initializes an SSH2Stream, attaches essential event listeners for protocol observation, and demonstrates basic utility usage. It clarifies that the stream requires a `net.Socket` for actual network communication."},"warnings":[{"fix":"Always implement a `stream.on('fingerprint', (hostKey, callback) => { ... })` handler in client code to verify the host key against known records (e.g., `~/.ssh/known_hosts`) and call `callback(true)` only if verified.","message":"By default, if no 'fingerprint' event handler is registered, ssh2-streams will automatically accept any host key presented by the remote server. This behavior is insecure for production client applications as it bypasses host authenticity verification.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure you create and manage a `net.Socket` (or similar network stream) and correctly pipe data between the socket and the `SSH2Stream` instance. Example: `socket.pipe(sshStream).pipe(socket);`","message":"ssh2-streams is a low-level protocol implementation. It does not handle the underlying network connection (e.g., TCP sockets) itself. Developers must establish and manage the `net.Socket` and pipe it to the `SSH2Stream` for communication.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Implement proper backpressure control mechanisms when reading from and writing to the stream, using `stream.pause()`, `stream.resume()`, and monitoring return values of `stream.write()` to buffer data appropriately.","message":"As a Node.js stream, proper backpressure handling is crucial to prevent memory exhaustion and ensure stable performance, especially when dealing with large data transfers over SSH channels. Neglecting backpressure can lead to 'write after end' errors or process crashes.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Listen for the generic `stream.on('error', (err) => { ... })` event for parser/stream-level issues, but also specific protocol events like `DISCONNECT`, `CHANNEL_OPEN_FAILURE`, etc., to gracefully handle protocol-level errors.","message":"Error handling in stream-based protocols can be complex, as errors can originate from the underlying socket, the stream parsing logic, or the SSH protocol itself (e.g., channel errors, disconnect messages). Not all error types are emitted as standard 'error' events.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"search_vec":"'0.4.10':65 'allow':101 'base':23 'bug':80 'build':124 'cadenc':73 'channel':54 'client':150 'client/server':30 'commit':112 'communic':136 'complianc':85 'compon':37 'control':49,132 'core':69 'current':61 'custom':125 'data':57 'deep':131 'develop':91,122 'differenti':94 'direct':20 'driven':76 'effici':97 'enabl':121 'event':118 'expos':114 'featur':90 'fix':81 'flexibl':103 'foundat':36 'granular':48 'handl':106 'handshak':53 'higher':40 'higher-level':39 'i/o':109 'implement':24 'includ':95 'integr':100 'javascript':143 'level':15,41 'librari':17,43 'low':14 'low-level':13 'manag':55 'mechan':59 'minor':83 'network':108 'newer':142 'node.js':7,16,98,139 'offer':47 'patch':79 'perform':105 'primari':93 'protocol':4,31,52,84,117,148 'provid':19 'rapid':89 'rather':87 'raw':116 'releas':72 'requir':138 'secur':78,147 'serv':33 'server':151 'sftp':3,128,146 'sftpv3':29 'solut':129 'ssh':42,126,144 'ssh2':1,9,27,46,145 'ssh2-streams':8 'stabl':62 'stream':5,10,22,99,149 'stream-bas':21 'structur':120 'transfer':58 'typic':75 'under':135 'updat':86 'util':70 'v5.10.0':140 'version':63","created_at":"2026-04-20T01:57:40.857383+00:00","updated_at":"2026-04-20T01:57:40.857383+00:00","problems":[{"fix":"Always instantiate `SSH2Stream` using the `new` keyword: `const stream = new SSH2Stream();`","cause":"Attempting to call `SSH2Stream()` as a function instead of a constructor.","error":"TypeError: Class constructor SSH2Stream cannot be invoked without 'new'"},{"fix":"Ensure no data is written to the stream after it has ended or been closed. Check stream state before writing, or handle 'close' and 'end' events to prevent further writes.","cause":"Attempting to write data to a Node.js stream after it has signaled its end (e.g., via `stream.end()` or remote disconnect).","error":"Error: stream.push() after EOF"},{"fix":"This often points to a protocol-level issue. Review the data flow, ensure correct packet boundaries, and potentially increase the maximum buffer size if legitimately handling extremely large SSH packets (though usually, this indicates an underlying problem).","cause":"The internal buffer for reassembling SSH packets has grown too large, indicating a potential protocol desynchronization or an attempt to send/receive an unusually large malformed packet.","error":"Error: Packetizer exceeded max buffer size"},{"fix":"Ensure `ssh2-streams` is installed (`npm install ssh2-streams`) and that you are correctly destructuring the named export: `const { SSH2Stream } = require('ssh2-streams');`.","cause":"The `require()` call did not correctly extract the `SSH2Stream` constructor, or the `ssh2-streams` package might not be correctly installed or resolved.","error":"TypeError: require(...).SSH2Stream is not a constructor"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/mscdex/ssh2-streams","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/ssh2-streams","openapi_spec":null,"status_page":null,"smithery":null,"categories":["http-networking","auth-security"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}