- Baseline:
refactor/L0-baseline(v2.0.14) - Characterized build: the frozen baseline in
test/fixtures/baseline-ssh2shell.js, a 1:1 port of the baselinesrc/ssh2shell.coffee. - Method: read the implementation, exercise it with the offline harness in
test/unit/, and compare every documented claim inREADME.mdagainst the actual code. - Status: L1 baseline characterization, preserved through L4; L5, L6, and L6.1 record the signed-off behavior changes separately.
Superseded in 4.0.0. The current
src/ssh2shell.jsreplaced the nestedsshcommand withssh2forwardOuthops.server.ssh, the jump-host credential model,exitCommands,passphrasePrompt,commandStartTimeout, anddetails.noOutputno longer exist. The host message handler is nowonMsg;server.hashMethod,sshObj.stop, the hostidleTime/dataIdleTimealiases, and themsg: { send }shape are also removed. The sections below describe the frozen baseline and remain useful for comparison only. See NEXT-HOST-CONNECTION.md and the README for current behavior.
The README is treated as documented intent. Where it disagrees with the code, the code is recorded as the current behavior and the mismatch is listed below. Nothing here is fixed during L1 except the documentation-only corrections explicitly agreed at L1 (see L1 README corrections).
The code has two distinct host layers. They are iterated by different methods and must not be conflated.
| Layer | Stored in | Connection method | Iterated by |
|---|---|---|---|
| Primary host | _hosts |
A new ssh2.Client (_connect) |
_nextPrimaryHost |
| Secondary/nested host | current sshObj.hosts |
An ssh ... command typed into the current shell (_sshConnect) |
_nextHost |
_nextPrimaryHost(connect) is the primary-host loop. It shifts the next entry
from _hosts, emits end for the outgoing primary host, removes that host's
listeners, and starts the next ssh2 connection via _initiate(connect).
_runExit() is the "finish this host" routine, not the primary-host loop. It
decides what happens when the current host has no commands left (_nextCommand
/ _checkCommand), or after a manual exit, a failed nested connection, or
_previousHost. When the current host's own hosts array is exhausted, its
back-out branch is what returns to the previous connection. Its order is:
- Run queued
exitCommands(for example theexitpushed after a nestedsshconnection orsudo su). - If the current host still has entries in
sshObj.hosts, call_nextHost()to open the next secondary host with anssh ...command. - Otherwise, if
_connectionsis non-empty, emitendfor the current host and call_previousHost(). - Otherwise, if the command is the literal
exit, send it. - Otherwise,
close().
_previousHost() emits end for the outgoing host, detaches that host's
listeners (L5), pops one entry from _connections, makes it current again, and
calls _runExit() on it. That is what lets the code resume a previous host's
remaining hosts array: backing out does not discard unvisited secondary
hosts. A chain may be several levels deep; each level is backed out in turn
until _connections is empty and close() runs.
module.exports = SSH2Shell — a constructible class that extends Node's legacy
stream.Stream (which in turn extends EventEmitter).
new SSH2Shell(host) or new SSH2Shell([host1, host2, ...])
- A non-empty array is used as the primary-host queue (
_hosts). - Any other value is wrapped as a single primary host.
- An empty array becomes
[[]](one empty host) because the length check fails.
| Member | Status | Notes |
|---|---|---|
connect(callback) |
Implemented | Starts the first primary host. Callback receives full session text. |
close() |
Implemented | Closes the live shell stream. Before the shell opens it is a no-op (L6.1); baseline threw on the prototype {} placeholder. |
on, emit, once, removeListener |
Inherited | Normal EventEmitter API. |
pipe(destination) |
Inherited | Legacy Stream.prototype.pipe; works by listening to data/end. |
unpipe(destination) |
Missing | Stream.prototype.unpipe is undefined. The README no longer documents it; pipe/unpipe are stream-level operations on the instance, not host config. |
This table records the instance properties the baseline exposed, not a
supported API. In the current major, members beginning with _ are internal.
sshObj, command, idleTime, and dataIdleTime are documented in the
README; the rest are diagnostics or implementation state.
| Property | Status | Meaning |
|---|---|---|
sshObj |
Public | Current host object plus runtime state. |
command |
Public | Command currently being run ("" between commands). |
connection |
Diagnostic | Active host's ssh2.Client instance. |
_hosts |
Internal | Remaining primary hosts (each connected with ssh2). |
_connections |
Internal | Stack of previous hosts used to back out through secondary/nested connections. |
_stream |
Diagnostic | Active shell stream. |
_buffer |
Internal | Raw response buffer for the current command. |
_stderrBuffer |
Internal | Captured stderr for the current command when captureStderr is enabled. |
idleTime |
Public | Command timeout in ms (idleTimeOut, default 5000). |
dataIdleTime |
Public | Response-settling delay in ms (dataIdleTimeOut, default 500). |
standardPrompt, passwordPrompt, passphrasePrompt |
Diagnostic | Compiled RegExp prompt detectors. standardPrompt is compiled from standardPromptRegex when that opt-in is set, otherwise from the standardPrompt character set. |
asciiFilter, textColorFilter |
Diagnostic | Compiled RegExp response filters. |
| Event | Payload | Emitted from |
|---|---|---|
msg |
message (string or object) | Throughout; default prints to console, overridden by host.msg. |
data |
raw chunk | _connect stream handler; also consumed internally by _onData. |
stderrData |
raw chunk | _connect stream stderr handler; default prints to console.error. |
error |
(err, type, close = false, callback) |
Connection, shell, stream, timeout, sudo, and nested-SSH failures. |
end |
(sessionText, sshObj) |
Stream finish, _previousHost, _nextPrimaryHost. |
commandProcessing |
(command, response, sshObj, stream) |
_onData while a command is still producing output. |
commandComplete |
(command, response, sshObj, details) |
_commandComplete after a prompt is detected. response is the raw buffer by default; commandResponse: 'handled' removes the echoed command and trailing prompt. details.rawResponse is always the raw buffer; details.stderr carries captured stderr when captureStderr is enabled. |
commandTimeout |
(command, response, stream, connection, details) |
_scheduleIdleTimeout, armed when _runCommand writes a command and reset by _onData. A detected prompt cancels the timer. details is { attempt, maxRetries, final }. |
keyboard-interactive |
(name, instructions, lang, prompts, finish) |
Re-emitted from the ssh2.Client. |
newPrimaryHost |
value returned by _nextPrimaryHost, which is _initiate's return value: at connect() time this is _stream (the prototype placeholder {} until the shell opens) |
connect and connection close. |
pipe / Unpipe |
— | Not emitted by the class. These are stream-level concepts; the README no longer lists them. |
Connection and session: server, hosts, commands, msg,
connectedMessage, readyMessage, closedMessage, showBanner, verbose,
debug, progress, exposeCredentials, enter, streamEncoding, window,
pty, idleTimeOut, dataIdleTimeOut (public timer key; falls back to the
undocumented dataIdleTime), commandResponse,
captureStderr, commandTimeoutRetries, sessionText, exitCommands.
Prompts and filters: standardPrompt, standardPromptRegex,
passwordPrompt, passphrasePrompt, passPromptText, asciiFilter,
disableASCIIFilter, textColorFilter, disableColorFilter.
Runtime flags: pwSent, sshAuth, sshToNextHost,
commandTimeoutAttempt, retryCommandTimeout.
Event handlers: onCommandProcessing, onCommandComplete,
onCommandTimeout, onKeyboardInteractive, onData, onStderrData,
onError, onEnd.
Nested SSH command options (server.ssh, baseline only): forceProtocolVersion,
forceAddressType, disablePseudoTTY, forcePseudoTTY, verbose,
cipherSpec, escape, logFile, configFile, identityFile, loginName,
macSpec, options.
Removed legacy aliases: the misspelled passwordPromt and
passphrasePromt fallbacks were removed post-L7. The baseline reads
passwordPrompt and passphrasePrompt; the current build reads only
passwordPrompt (for sudo). The frozen baseline still honours the aliases.
The current major also removed the host msg handler (replaced by onMsg),
the msg: { send } shape, server.hashMethod (use hostHash), sshObj.stop
(use abort), and the host idleTime / dataIdleTime keys (use
idleTimeOut / dataIdleTimeOut). The frozen baseline still accepts them.
connect(callback)starts the session and returns full session text.sshObjandcommandare the public state handles.- The documented prompt keys and defaults are used.
- The documented filter keys and defaults are used.
idleTimeOut,connectedMessage,readyMessage,closedMessage,showBanner,verbose,debug,enter,streamEncodingwork as described.onCommandProcessing,onCommandComplete,onCommandTimeout,onKeyboardInteractive,onData,onStderrData,onError, andonEndare registered per host.- Multiple primary hosts, nested
hostsarrays, notifications, and sudo/su prompt handling are implemented. The baseline also implementsserver.sshoption construction; the current build does not. - Fingerprint validation is delegated to
ssh2throughserver.hostHashandserver.hostVerifier.
These documentation-only corrections were made at L1 because the README was wrong, not because the code changed:
- Removed the
callbackhost property. Onlyconnect(callback)is read. - Corrected the
host.idleTimeoutcomment tohost.idleTimeOut.
- Removed
onPipe/onUnpipefrom the host configuration block, the.pipe/.unpipemethods, and thepipe/Unpipeevents. Pipe and unpipe are stream-level operations on the instance, not host config or host events. The inheritedpiperemains available. - Updated
forceProtocolVersion/forceAddressTypeto show their accepted values instead oftrue/false.
These changes intentionally differ from the L0 baseline. Each is covered by a test that runs against both the current build and the frozen baseline artifact.
- Debug/verbose gating.
_systemMsgemits debug and verbose messages only when the host'sdebug/verboseflags are enabled. Normalmsgoutput is unchanged. - Listener lifecycle. Default listeners are installed once; host listeners replace defaults; leaving a host detaches both the cached handler and the current host handler. Reloading defaults does not attach duplicates.
- Multi-host back-out.
_previousHostnow detaches the outgoing host's handlers, so a stalecommandComplete(or similar) handler cannot fire against the new current host and repeatsessionText. This is the signed-off fix for the known multi-host duplication defect. - Host tracking.
this.hostis updated when moving to the next nested host and the next primary host, so session/callback text starts with the correct host name. - Keyboard-interactive. The event is registered and dispatched under the
dashed name, host handlers are honored, and the default handler calls
finish([''])instead of stalling the handshake. - Restored baseline payloads.
commandCompleteemits the raw_buffer;hostHashis written tosshObj.server.hostHash; the legacymsg: { send }shape is mapped tomsg; the default keyboard response is''.
These are the approved robustness follow-ups from the optimisation review. They are covered by level-aware tests that also run against the frozen baseline.
- Post-auth nested-SSH timeout. After the nested
sshpassword/passphrase is accepted, output that matches neither a standard prompt nor a repeated credential prompt now re-arms the idle timer. Baseline returned without a timer, so a silent nested shell could hang indefinitely. - Guarded
close(). Calling the publicclose()before the shell opens is a no-op. Baseline calledclose()on the prototype{}placeholder and threwTypeError. - Empty commands.
_processNotificationstreats an empty command as nothing to run and advances to the next queued command. Baseline left the state machine idle. - Own SSH option properties.
buildSshCommanditeratesserver.ssh.optionswithObject.entries, so inherited enumerable properties cannot leak into the generatedsshcommand. Baseline usedfor...in.
- Credential redaction in debug/verbose output.
_systemMsgnow scrubs the configured password and passphrase from every debug/verbose string and maskspassword/passphrasekeys in object dumps (including nestedhostsconfig). The sudo and nested-SSH credential messages, the verboserunCommandecho, and the config dump therefore show[REDACTED]instead of the plaintext value. The frozen baseline logs the raw credentials. exposeCredentials(defaultfalse). A per-host opt-in that restores the raw credential output for fault-finding. It is applied in_loadDefaultsand read by_systemMsg; it does not change the connection itself. Test:test/unit/credentials.test.js.- Instance timer base values.
SSH.idleTime/SSH.dataIdleTimeset beforeconnect()are preserved instead of being replaced by the hard-coded 5000 / 500 defaults. A host'sidleTimeOut/dataIdleTimeOutstill overrides them, and leaving a host restores the base.idleTimeis accepted as a legacy host alias foridleTimeOut. Test:test/unit/timers.test.js. - Message listener continuity.
_removeListenerskeeps the defaultmsglistener attached while a host is being swapped, so_systemMsgdebug/verbose output is not dropped between hosts._loadDefaultsswaps in a hostmsghandler when one exists and falls back to the default handler otherwise. Tests:test/unit/l5-behavior.test.js— message-sink and duplicate-listener cases. - Single-host message prefix. Debug/verbose and
msg:notification messages omit the${host}:prefix when the session has one primary host and no nested hosts. Multi-host and nested-host sessions keep the prefix. The frozen baseline always prefixes. Tests:test/unit/l5-behavior.test.js— host-prefix cases. - Key-only nested authentication.
_sshConnectstarts a nested connection authenticated when the nested host has neither apasswordnor apassPhrase, so the first remote shell prompt is treated as success. The frozen baseline treats that prompt as a failed connection, so key-only nested hosts never run their commands. Password and passphrase nested hosts still start unauthenticated. Test:test/unit/ssh-connect.test.js— nested authentication state. - Progress indicator (default on). The
progresshost flag is now on by default; setprogress: falseto opt out. When enabled, it writes a one-second heartbeat toprocess.stderrwhile a command is in flight, and only when stderr is a TTY. It ends the line on command completion, timeout, error, close, or host change, and labels host changes with[host]when the session spans more than one host. It never modifiessessionTextor themsgstream, and it is suppressed whendebugorverboseis enabled because those already report internal steps. The default changed fromfalsetotruewith sign-off because the output is purely visual, unobtrusive, and has no process impact. Tests:test/unit/progress.test.jsandtest/live/progress.js.
These are additive, opt-in controls. Defaults preserve the raw
commandComplete payload and the single-timeout behavior; tests that cover them
run against both the current build and the frozen baseline, guarded by
isBaseline() where the baseline has no equivalent.
standardPromptRegex. A string orRegExpthat replaces thestandardPromptcharacter class for prompt detection. It is wrapped as(?:source)$so it is always end-anchored; the statefulg,y, andmflags are stripped so repeated.test()calls stay stable. An invalid pattern falls back tostandardPromptand logs a debug message. It is used everywherestandardPromptis: normal completion, sudo, and nested SSH. Test:test/unit/prompt-regex.test.js.commandResponse: 'handled'. Changes only the secondcommandCompleteargument. The echoed command and the trailing prompt are removed and the result is trimmed;details.rawResponsestill carries the raw buffer, andsessionTextstays raw. WithoutstandardPromptRegex, only the final prompt character (plus optional whitespace) can be removed. Test:test/unit/command-response.test.js.commandTimeoutRetries. A non-negative integer, default0. The library owns the attempt count and re-arms the idle timer for each non-final attempt; the handler only reacts todetails = { attempt, maxRetries, final }. The default handler closes only on the final attempt, so0preserves the single-timeout behavior. A handler can setthis.sshObj.retryCommandTimeout = falseto stop retrying for the current command. The attempt count resets when the same command is written and when a command completes, not for internal password/exit writes. Test:test/unit/timeout-retries.test.js; live checks:test/live/timeout.js(handler-managed) andtest/live/timeout_retries.js(opt-in retries).- Command idle timeout. The idle timer is armed when a command is written, so
a command that never produces output still reaches
commandTimeout. Incoming data resets the timer, and a detected prompt cancels it. A silent command that returns to the prompt completes normally. The literalexitcommand and internal password writes do not arm the timer. Test:test/unit/command-start-timeout.test.js. captureStderr. A boolean, defaultfalse. Whentrue, stderr chunks are filtered with the same colour and ASCII filters as stdout, buffered in_stderrBuffer, and merged into thecommandCompleteresponse andsessionTextwith one separating newline.details.stderrcarries the trimmed captured text.commandResponse: 'handled'removes the echo and prompt from stdout before stderr is appended. The buffer resets for each command, andstderrDatastill fires for every chunk. Test:test/unit/stderr-capture.test.js.
| # | README claim | Code reality | Impact | Action |
|---|---|---|---|---|
| 1 | dataIdleTimeOut: 500 |
Reads dataIdleTime; the internal timer variable has the same name |
Documented key is ignored | Resolved post-L5: dataIdleTimeOut is mapped, with dataIdleTime fallback |
| 2 | window: false default |
window is forced to true when falsy |
Explicit false cannot be used |
Resolved post-L5: nullish check preserves false |
| 3 | pty is not documented |
pty defaults to and is forced to true |
{ pty: false } cannot be used |
Resolved post-L5: nullish check preserves false |
| 4 | .unpipe(stream) |
unpipe is undefined on instances |
Calling it throws TypeError |
Resolved post-L5: removed from the README; pipe is inherited |
| 5 | onPipe / onUnpipe host handlers |
Never read | Redundant | Resolved post-L5: removed from the README |
| 6 | pipe / Unpipe events on the instance |
Not emitted by the class; stream-level only | Listeners never fire | Resolved post-L5: removed from the README |
| 7 | host.callback |
Only connect(callback) is read |
Ignored | Resolved at L1 (removed from README) |
| 8 | SSH2Shell extends events.EventEmitter |
Extends legacy stream.Stream |
Mostly compatible, but not the documented base | Resolved at L7 (README): now documents stream.Stream |
| 9 | forceProtocolVersion: true/false |
Appends the value literally (-xtrue) |
Produces an invalid ssh flag | Resolved post-L5: maps to -1/-2; true → -2 |
| 10 | forceAddressType: true/false |
Appends the value literally | Produces an invalid ssh flag | Resolved post-L5: maps to -4/-6; true → -4 |
| 11 | asciiFilter default [^\r\n\x20-\x7e] |
Default regex is [^\t\r\n\x20-\x7e] |
Tab is preserved in code but stripped by the documented filter | Resolved at L7 (README): both the config default and the later example now include \t |
| 12 | host.idleTimeout in a comment |
Actual key is idleTimeOut |
Documentation typo | Resolved at L1 |
| 13 | onError says this.connection.close() |
Code uses _stream.close() / connection.end() |
Misleading guidance | Resolved at L7 (README): guidance now uses this.connection.end() |
| 14 | .emit("eventName", function, parms, ...) |
emit(name, ...args) |
Misleading API description | Resolved at L7 (README): signature is now emit(name, ...args) |
| 15 | passwordPromt / passphrasePromt |
Supported aliases, undocumented | Works, but undocumented | Resolved post-L7: the misspelled fallbacks were removed; only passwordPrompt / passphrasePrompt are read |
| 16 | window passed to ssh2 |
Code passes the value as the window argument to connection.shell |
A forced true may not match the intended pty settings |
Resolved post-L5: the nullish check preserves false and still passes the value to connection.shell |
| 17 | Prompts/filters are per host | Compiled once per instance and reused across hosts | Nested/primary hosts can inherit the first host's filters | Resolved post-L5: _loadDefaults recompiles prompts and filters from the current host |
| 18 | Sudo errors are reported | Error is only emitted when debug is true |
Incorrect sudo passwords can fail silently | Resolved post-L5: sudo rejection is a debug notification; the command is cancelled and the session continues |
_onData schedules dataReceivedTimer with @dataIdleTime (source line 84).
The internal variable is dataIdleTime. At baseline, _loadDefaults reads
@sshObj.dataIdleTime (source line 564), so the documented public key
dataIdleTimeOut (README line 137) is ignored.
The intended shape is:
- public host key:
dataIdleTimeOut(milliseconds, default 500) - internal instance variable:
dataIdleTime(used by the timer)
Fixed post-L5: _loadDefaults now resolves the public key first:
const dataIdleTimeOut =
toPositiveNumber(this.sshObj.dataIdleTimeOut) ||
toPositiveNumber(this.sshObj.dataIdleTime);
if (dataIdleTimeOut > 0) {
this.dataIdleTime = dataIdleTimeOut;
}dataIdleTimeOut wins; the undocumented dataIdleTime remains as a fallback
for existing callers. This is a behavior fix, not a rename of the internal
variable. The timer's purpose is to stop the script hanging when a command
response does not satisfy the state-engine tests (for example, a standard prompt
is never detected). It is separate from idleTimeOut, which is the command
timeout.
Post-L6.1: timer values can also be set on the instance before connect()
(for example SSH.idleTime = 15000). The first _loadDefaults captures that as
the base; a host idleTimeOut / dataIdleTimeOut overrides it for that host,
and _removeListeners restores the base when leaving the host so the override
does not leak into the next one. Non-positive or non-numeric values are treated
as "not configured". idleTime is also accepted as a legacy host alias for
idleTimeOut.
The code uses unless @sshObj.X for many defaults. This is safe when the
documented default is itself falsy and the value is a boolean (showBanner,
verbose, debug, disableColorFilter, disableASCIIFilter). It is unsafe
for properties whose default is truthy and where false is meaningful:
window = true unless @sshObj.window— explicitfalsebecomestrue.pty = true unless @sshObj.pty— explicitfalsebecomestrue.
window is passed as the first argument to
connection.shell(window, { pty }, callback), and pty is passed in the options
object. Both should use an undefined/null check (?) rather than truthiness so
false survives. The same audit should be applied to any new boolean host
property: use ? (nullish) or isnt undefined, not unless.
Fixed post-L5: applyHostDefaults now uses == null for both, so explicit
window: false and pty: false are preserved. hosts, commands,
exitCommands, and sessionText still use truthiness checks, but empty
arrays/strings are truthy or the replacement is equivalent, so they do not
change explicit values. idleTime and dataIdleTime already use ?.
Locations:
README.mdlines 688-689 (inside thehost.server.sshblock).src/ssh2shell.js(inside_sshConnect; baseline CoffeeScript lines 331-332).
Current behavior:
let sshFlags = '-x';
if (this.sshObj.server.ssh.forceProtocolVersion) {
sshFlags += this.sshObj.server.ssh.forceProtocolVersion;
}
if (this.sshObj.server.ssh.forceAddressType) {
sshFlags += this.sshObj.server.ssh.forceAddressType;
}The value is appended directly to the flag bundle. With the documented boolean
usage, forceProtocolVersion: true produces -xtrue; forceAddressType: true
produces -xtrue as well. Both are invalid ssh flags, so these options are
effectively unusable as documented.
Valid ssh CLI flags for the underlying concepts are:
-1/-2— force protocol version 1 / 2.-4/-6— force IPv4 / IPv6 address family.
There is no boolean -x variant.
Fixed post-L5: buildSshCommand maps these options through an allow-list:
forceProtocolVersion: 1or2(number or string) →-1/-2.trueselects the modern default,-2.forceAddressType: 4or6(number or string) →-4/-6.trueselects the IPv4 default,-4.false,null, andundefineddisable the option.- Any other truthy value returns a
Security Alerterror (Invalid forceProtocolVersion: <value>orInvalid forceAddressType: <value>) instead of producing an invalid flag.
The flags are appended as separate tokens (ssh -x -2 ...), so they no longer
merge with -x.
_loadDefaults runs for every primary host (_initiate) and every nested host
(_nextHost), so it always has the current sshObj. At baseline it only
compiled the regexes when the instance property was falsy:
asciiFilterwhenthis.asciiFilteris falsytextColorFilterwhenthis.textColorFilteris falsypasswordPromptwhenthis.passwordPromptis falsypassphrasePromptwhenthis.passphrasePromptis falsystandardPromptwhenthis.standardPromptis falsy
After the first host those instance properties were set, so later hosts reused
the first host's compiled regexes. applyHostDefaults still updated the sshObj
strings, but they were never recompiled.
Consequence: a second host with a different standardPrompt,
passwordPrompt, passphrasePrompt, asciiFilter, or textColorFilter was
still detected and filtered with the first host's patterns. In a chain this could
miss a prompt, time out a command, or filter output incorrectly.
What "per-host" means: the compiled regexes must be derived from the current
sshObj every time _loadDefaults runs. The instance properties
(this.asciiFilter, this.passwordPrompt, ...) are internal compiled state, not
public config; the public config is sshObj.*.
Fixed post-L5 (signed off): _loadDefaults now always assigns the
compilation result instead of guarding on the instance property:
const ascii = compileAsciiFilter(this.sshObj.asciiFilter);
this.asciiFilter = ascii.filter;
const color = compileTextColorFilter(this.sshObj.textColorFilter);
this.textColorFilter = color.filter;
const prompts = compilePrompts(this.sshObj);
this.passwordPrompt = prompts.passwordPrompt;
this.passphrasePrompt = prompts.passphrasePrompt;
this.standardPrompt = prompts.standardPrompt;The fallback debug messages stay conditional on debug.
Impact:
- Single-host behavior is unchanged.
- Multi-host behavior changes for hosts with different prompt/filter config. That is the intended fix.
test/unit/api-baseline.test.jsis level-aware: baseline keeps the stale first-host patterns; current recompiles. A two-host test asserts that the second host's regex matches.- Directly assigning
ssh.passwordPrompt = /.../on the instance is not a documented config path and would be overwritten; usehost.passwordPrompt.
These are recorded so a refactor does not accidentally "fix" them without sign-off:
_nextPrimaryHost's empty-queue branch uses@_runExit(a reference) instead of@_runExit(). In the normal flow_nextPrimaryHostis only re-entered when_hosts.length > 0(from the connectionclosehandler), so this branch is latent/dead code rather than the nested-host back-out path. Backing out of secondary hosts is_runExit's job (see Host model)._connectionsandsshObjare class-body objects on the prototype. Beforeconnect()assigns an ownsshObj, two instances share them. Fixed at L5: the constructor now assigns per-instancesshObjand_connections.- The constructor listens for
newPrimmaryHost(typo) while the code emitsnewPrimaryHost; the constructor listener is dead code. connect()emitsnewPrimaryHostwith the return value of_nextPrimaryHost(the shell stream placeholder, not a handler)._removeListenersremoves thestderrDatalistener twice._sanitizeResponseusescommand.substr(0, buffer.length); this can remove unintended text when the buffer is shorter than or unrelated to the command.- The constructor's
keyboard-interactivelistener only logs; it never callsfinish(prompts). A host that enablestryKeyboardwithout its own handler can hang. Fixed at L5: the default handler callsfinish(['']). _loadDefaultsonly compiles filters and prompt regexes when the instance property is empty, so they persist across hosts. Fixed post-L5 (signed off): compiled state is rebuilt from the current host on every call. See Per-host prompt/filter compilation._previousHostdoes not call_removeListeners, unlike_nextHostand_nextPrimaryHost. The previous secondary host's event handlers stay attached, so a latercommandComplete(or similar) can fire a stale handler with the now-current host assshObj. A handler that appendssshObj.sessionTextto the final output therefore repeats the current host's text each time the chain changes. Fixed at L5 (signed off):_previousHostcalls_removeListeners, andtest/unit/hosts.test.jsasserts the baseline leak and the current clean result in the same test.- Error handling had several latent defects and one L5 behavior change:
_stream.close()was unguarded, connection/stream errors gainedclose=trueat L5 (baseline only reported them), the default listener ignored its callback, and defaulterrorlisteners could accumulate after a host withonErrorwas followed by one without. Fixed post-L5 (signed off): the close is guarded, Shell/Connection/Connection.connect classify by live stream state, the callback runs before the close, the hostonErrorruns before the default close, the default listener is installed once,_streamis reset per primary host, and the sudo timeout usesthis.connection. Sudo rejection was converted from a conditionalerrorto a debug notification. Seedocs/ERROR-HANDLING.mdfor the emit-site map and F1-F11.
npm run test:unit # offline, mocked ssh2, current lib/
npm run test:src # same suite against src/ before building
npm run test:lib # same suite against lib/
npm run test:baseline # same suite against the frozen L0 artifact
npm test # check:build, then lib and baseline
npm run check:build # fails if lib/ differs from src/
npm run build # copies src/ssh2shell.js to lib/ssh2shell.js
npm pack --dry-run # show the published tarball contentsThe harness lives in test/unit/ and injects a fake ssh2 module through the
require cache, so it never opens a network connection. test:src, test:lib,
and test:baseline all use scripts/run-tests.js to set
SSH2SHELL_TEST_MODULE to src/ssh2shell.js, lib/ssh2shell.js, or
test/fixtures/baseline-ssh2shell.js. You can also pass a module path directly:
node scripts/run-tests.js src/ssh2shell.js.
scripts/run-tests.js passes the test files explicitly rather than a directory,
so the suite also runs on Node 18. CI runs npm test and npm pack --dry-run on
Node 18, 20, 22, and 24; the package publishes only lib/ plus the README,
LICENSE, and package.json, and prepublishOnly runs the full suite before a
publish.