From 5909f4a9a3c780fab8e9693c7c233890ef1c5cad Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Mon, 23 Nov 2026 01:38:05 +1300 Subject: [PATCH] chore: release 4.1.0 --- CHANGELOG.md | 20 +- README.md | 36 ++- docs/API-BASELINE.md | 12 +- docs/MIGRATING-4.md | 10 +- docs/NEXT-HOST-CONNECTION.md | 6 +- lib/ssh2shell.js | 216 +++++++++-------- package-lock.json | 4 +- package.json | 2 +- scripts/run-live.js | 16 ++ src/ssh2shell.js | 216 +++++++++-------- test/coverage.md | 322 ++++++++++++++++++++++++++ test/live/bash_script.js | 6 +- test/live/chaining.js | 14 +- test/live/close_from_handler.js | 6 +- test/live/command_timeout.js | 6 +- test/live/default_command_timeout.js | 39 ++++ test/live/fingerprint.js | 6 +- test/live/graceful_close.js | 10 +- test/live/hop_keyboard_interactive.js | 10 +- test/live/host_faults.js | 2 + test/live/host_traversal.js | 12 +- test/live/keyboard-interactive.js | 6 +- test/live/lots_of_commands.js | 6 +- test/live/multiple_primary_hosts.js | 10 +- test/live/notifications.js | 6 +- test/live/pipe.js | 6 +- test/live/private_key.js | 6 +- test/live/progress.js | 2 + test/live/progress_tty.js | 65 ++++++ test/live/prompt_response.js | 6 +- test/live/simple.js | 6 +- test/live/stop_multiple_hosts.js | 10 +- test/live/stop_on_failure.js | 6 +- test/live/sudo_abort.js | 6 +- test/live/sudo_no_pass.js | 6 +- test/live/sudo_rejected.js | 6 +- test/live/sudo_su.js | 6 +- test/live/timeout.js | 43 ++-- test/live/timeout_retries.js | 46 ++-- test/live/transport_drop.js | 6 +- test/live/tunnel.js | 10 +- test/unit/behavior-hardening.test.js | 190 +++++++++++++++ test/unit/coverage-gaps-flow.test.js | 230 ++++++++++++++++++ test/unit/coverage-gaps-state.test.js | 308 ++++++++++++++++++++++++ test/unit/coverage-gaps.test.js | 98 ++++++++ test/unit/credentials.test.js | 3 +- test/unit/helpers/harness.js | 9 + test/unit/l5-behavior.test.js | 104 ++++++++- 48 files changed, 1817 insertions(+), 360 deletions(-) create mode 100644 test/coverage.md create mode 100644 test/live/default_command_timeout.js create mode 100644 test/live/progress_tty.js create mode 100644 test/unit/behavior-hardening.test.js create mode 100644 test/unit/coverage-gaps-flow.test.js create mode 100644 test/unit/coverage-gaps-state.test.js create mode 100644 test/unit/coverage-gaps.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 1964451..dffc4b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,18 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. ## [Unreleased] +## [4.1.0] - 2026-11-23 + +### Added + +- `debug` and `verbose` can be set once on the `SSH2Shell` instance to override + host values for the whole run, including `false` suppressing a host that + enables the flag. Reading the instance property reports the effective value. +- `systemMsg(type, message, object)` is now a public helper for emitting debug + and verbose messages from handlers. It gates on the effective flag and applies + the standard host prefix and credential redaction. The internal `_systemMsg` + name is replaced; the frozen baseline keeps it for comparison tests. + ### Development - Added live coverage for keyboard-interactive authentication on a nested hop @@ -19,6 +31,11 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. - Live workflow runs with the same ref now queue instead of cancelling each other, so a parallel publish or push cannot remove a PR's required `Live suite` check. +- Added a second round of unit tests for transport and state guards, host + traversal, shutdown flows, and behaviour hardening, plus two live tests for + the default command timeout and the TTY progress indicator. `test/coverage.md` + records the local coverage review and full miss-overlap analysis (98.12% + combined line coverage). ## [4.0.4] - 2026-11-18 @@ -153,7 +170,8 @@ See [docs/MIGRATING-4.md](./docs/MIGRATING-4.md) for the symptom-to-fix guide. `~/.ssh/id_ed25519` copies that were only needed by nested `ssh -i` hops. - `ssh2Client` is now `_ssh2Client` and is documented as an internal test seam. -[Unreleased]: https://github.com/cmp-202/ssh2shell/compare/v4.0.4...HEAD +[Unreleased]: https://github.com/cmp-202/ssh2shell/compare/v4.1.0...HEAD +[4.1.0]: https://github.com/cmp-202/ssh2shell/compare/v4.0.4...v4.1.0 [4.0.4]: https://github.com/cmp-202/ssh2shell/compare/v4.0.3...v4.0.4 [4.0.3]: https://github.com/cmp-202/ssh2shell/compare/v4.0.2...v4.0.3 [4.0.2]: https://github.com/cmp-202/ssh2shell/compare/v4.0.1...v4.0.2 diff --git a/README.md b/README.md index 1e8cfc0..07463c3 100644 --- a/README.md +++ b/README.md @@ -334,6 +334,10 @@ value for that host. | `window` | boolean \| object | `true` | First argument to `connection.shell()`. `false` disables the PTY; an object sets the terminal size. | | `pty` | boolean | `true` | Request a pseudo-terminal. `false` is equivalent to `window: false`, because `ssh2` has no separate PTY option. | +`debug` and `verbose` may also be set once on the `SSH2Shell` instance; an +explicit instance value overrides the host value. See +[Verbose and debug output](#verbose-and-debug-output). + ### Host event handlers Handlers defined on the host object run only for that host. For most events @@ -1146,16 +1150,38 @@ the session spans more than one host (multiple primary hosts or nested hosts); a single-host session omits the prefix. Do not enable them inside `onCommandProcessing`, which runs for every chunk of output. -Add your own messages with the same flags: +For a multi-host run, set either flag on the instance once before `connect()` +instead of repeating it in every host config. An explicit instance boolean +overrides every host value in both directions, so `false` also suppresses a +host that enables the flag: ```javascript -onCommandProcessing: function (command, response, sshObj, stream) { - if (sshObj.verbose) { - this.emit('msg', `${sshObj.server.host}: response: ${response}`); - } +const ssh = new SSH2Shell(hosts); +ssh.debug = process.env.DEBUG === 'true'; +ssh.verbose = process.env.VERBOSE === 'true'; +ssh.connect(callback); +``` + +`ssh.debug` and `ssh.verbose` report the effective value for the active host. +Host values are still used when the instance flag has not been set. + +To add your own debug or verbose messages from a handler, call +`this.systemMsg(type, message)` with `'debug'` or `'verbose'`. Inside a handler, +`this` is the `SSH2Shell` instance: + +```javascript +onCommandTimeout: function (command, response, stream, connection) { + this.systemMsg('debug', `${this.sshObj.server.host}: timeout: ${command}`); }, ``` +`systemMsg()` gates the message on the effective flag for the active host, then +applies the same host prefix and credential redaction as the library's own +messages. Prefer it over manually checking `this.debug` / `this.verbose` and +calling `this.emit('msg', ...)`: a manual check can read the wrong value and +bypasses redaction. Reading `ssh.debug` / `ssh.verbose` is still appropriate +when you need the effective value for some other purpose. + Debug and verbose output redacts the configured password, passphrase, and private key by default. Set `exposeCredentials: true` only while diagnosing an authentication problem, and never leave it enabled in production or in logs. diff --git a/docs/API-BASELINE.md b/docs/API-BASELINE.md index 4324332..dfd59f6 100644 --- a/docs/API-BASELINE.md +++ b/docs/API-BASELINE.md @@ -198,9 +198,9 @@ wrong, not because the code changed: 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.** `_systemMsg` emits debug and verbose messages only - when the host's `debug` / `verbose` flags are enabled. Normal `msg` output is - unchanged. +- **Debug/verbose gating.** `systemMsg` (called `_systemMsg` in the frozen + baseline) emits debug and verbose messages only when the effective `debug` / + `verbose` flags are enabled. Normal `msg` output 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. @@ -241,7 +241,7 @@ are covered by level-aware tests that also run against the frozen baseline. ## Post-L6.1 behavior changes (signed off) -- **Credential redaction in debug/verbose output.** `_systemMsg` now scrubs the +- **Credential redaction in debug/verbose output.** `systemMsg` now scrubs the configured password and passphrase from every debug/verbose string and masks `password` / `passphrase` keys in object dumps (including nested `hosts` config). The sudo and nested-SSH credential messages, the verbose @@ -249,7 +249,7 @@ are covered by level-aware tests that also run against the frozen baseline. the plaintext value. The frozen baseline logs the raw credentials. - **`exposeCredentials` (default `false`).** A per-host opt-in that restores the raw credential output for fault-finding. It is applied in `_loadDefaults` and - read by `_systemMsg`; it does not change the connection itself. Test: + read by `systemMsg`; it does not change the connection itself. Test: `test/unit/credentials.test.js`. - **Instance timer base values.** `SSH.idleTime` / `SSH.dataIdleTime` set before `connect()` are preserved instead of being replaced by the hard-coded 5000 / @@ -257,7 +257,7 @@ are covered by level-aware tests that also run against the frozen baseline. and leaving a host restores the base. `idleTime` is accepted as a legacy host alias for `idleTimeOut`. Test: `test/unit/timers.test.js`. - **Message listener continuity.** `_removeListeners` keeps the default `msg` - listener attached while a host is being swapped, so `_systemMsg` debug/verbose + listener attached while a host is being swapped, so `systemMsg` debug/verbose output is not dropped between hosts. `_loadDefaults` swaps in a host `msg` handler when one exists and falls back to the default handler otherwise. Tests: `test/unit/l5-behavior.test.js` — message-sink and duplicate-listener diff --git a/docs/MIGRATING-4.md b/docs/MIGRATING-4.md index 98813e5..c4ef972 100644 --- a/docs/MIGRATING-4.md +++ b/docs/MIGRATING-4.md @@ -162,10 +162,12 @@ SSH.connect((sessionText) => { }); ``` -Set `debug: true` and `verbose: true` on the host for connection-level detail. -The common error types are `Connection`, `Hop`, `Command Timeout`, `Stream`, -and `Connection close`; see [Error handling](./ERROR-HANDLING.md) for the full -contract. +Set `debug: true` and `verbose: true` on the host for connection-level detail, +or set `SSH.debug` / `SSH.verbose` once before `connect()` to apply the value to +every host in a multi-host run. An explicit instance boolean overrides the host +values in both directions. The common error types are `Connection`, `Hop`, +`Command Timeout`, `Stream`, and `Connection close`; see +[Error handling](./ERROR-HANDLING.md) for the full contract. When you open an issue, include the `ssh2shell` and Node.js versions, the error type, and a minimal host object and command list. Remove keys, passwords, and diff --git a/docs/NEXT-HOST-CONNECTION.md b/docs/NEXT-HOST-CONNECTION.md index c595a84..353fb16 100644 --- a/docs/NEXT-HOST-CONNECTION.md +++ b/docs/NEXT-HOST-CONNECTION.md @@ -198,7 +198,7 @@ _nextHost() { const parent = this._activeContext(); this._removeListeners(parent); const nextHost = parent.pendingHosts.shift(); - this._systemMsg('debug', `nextHost: hop to ${nextHost.server.host}`); + this.systemMsg('debug', `nextHost: hop to ${nextHost.server.host}`); this.sshObj = nextHost; this.host = nextHost.server.host; @@ -418,7 +418,7 @@ record shape changes from a host config to `record.host`: ### Deviation register -Logging is not a deviation. `_systemMsg`, `debug`, `verbose`, `msg` prefixes, +Logging is not a deviation. `systemMsg`, `debug`, `verbose`, `msg` prefixes, progress, sudo prompts, command-response handling, `captureStderr`, and the default error listener all read the active aliases and keep their current behaviour. Only the following need code changes. @@ -1479,7 +1479,7 @@ child is active. No handler needs to know whether the host is primary or nested. | `onStderrData` | Fires for the active child stream. `captureStderr` still merges into the child response. | | `onEnd` | Fires once per visited host, child before parent. | | `onError` | Host handler runs for the event's record; the default listener keeps its existing close semantics for the active record. | -| `onMsg` | Same `_systemMsg` path and `[host]` prefix rules. | +| `onMsg` | Same `systemMsg` path and `[host]` prefix rules. | | `onKeyboardInteractive` | Bound per connection; the instance event fires with that connection's `finish`. | | `reconnect` | Follow-up only. Fires with the record's `sshObj` and `{ phase, attempt, maxRetries, delay, expected, reason }`; a reboot reports `expected: true`, a real failure is an `error` with `level: 'Reconnect'`. | | `progress` | One heartbeat for the active command; `_progressEnd()` runs before a host switch. | diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index c828aa8..d9311eb 100644 --- a/lib/ssh2shell.js +++ b/lib/ssh2shell.js @@ -143,6 +143,13 @@ class SSH2Shell extends Stream { // class-body values used to be shared through the prototype until the first // host load, which aliased `_stream` between instances. this._callback = null; + // `debug`/`verbose` are public instance-level overrides. An explicit + // boolean wins over every host's setting; `undefined` means "use the host". + // `_debug`/`_verbose` are the effective values for the active host. + this._debugOverride = undefined; + this._verboseOverride = undefined; + this._debug = false; + this._verbose = false; this.command = ''; this._primaryhostSessionText = ''; this._stream = {}; @@ -157,7 +164,28 @@ class SSH2Shell extends Stream { this.standardPrompt = ''; this._loadDefaultListeners(); } - + + // Public override fields. Reading returns the effective value for the active + // host; assigning a boolean sets a run-wide override that applies to every + // host, including when the value is false. + get debug() { + return this._debug; + } + + set debug(value) { + this._debugOverride = typeof value === 'boolean' ? value : undefined; + this._debug = value === true; + } + + get verbose() { + return this._verbose; + } + + set verbose(value) { + this._verboseOverride = typeof value === 'boolean' ? value : undefined; + this._verbose = value === true; + } + _loadDefaultListeners() { if (!this.msg) { this.msg = (message) => { @@ -205,7 +233,7 @@ class SSH2Shell extends Stream { if (!this._defaultErrorListener) { this._defaultErrorListener = (err, type, close = false, callback, context) => { this._progressEnd(); - this._systemMsg('debug', `Class.error: ${err}, ${type}`); + this.systemMsg('debug', `Class.error: ${err}, ${type}`); if (err instanceof Error) { this.emit('msg', `Error: ${err.message}, Level: ${err.level}`); @@ -408,10 +436,10 @@ class SSH2Shell extends Stream { this.textColorFilter = context.textColorFilter; } if (typeof context.debug === 'boolean') { - this.debug = context.debug; + this._debug = context.debug; } if (typeof context.verbose === 'boolean') { - this.verbose = context.verbose; + this._verbose = context.verbose; } if (typeof context.progress === 'boolean') { this.progress = context.progress; @@ -667,8 +695,8 @@ class SSH2Shell extends Stream { _progressEnabled() { return ( this.progress === true && - this.debug !== true && - this.verbose !== true && + this._debug !== true && + this._verbose !== true && this._progressStream && this._progressStream.isTTY === true ); @@ -751,12 +779,12 @@ class SSH2Shell extends Stream { this._progressNewline(); } - // Emits debug/verbose messages only when the matching host flag is enabled. + // Emits debug/verbose messages only when the matching flag is enabled. // An optional object payload is emitted as a second message. - _systemMsg(type, message, object = null){ + systemMsg(type, message, object = null){ const enabled = - (type === 'debug' && this.debug) || - (type === 'verbose' && this.verbose); + (type === 'debug' && this._debug) || + (type === 'verbose' && this._verbose); if (!enabled) { return; @@ -807,7 +835,7 @@ class SSH2Shell extends Stream { const maxRetries = toNonNegativeInteger(this.sshObj.commandTimeoutRetries); const final = attempt > maxRetries; - this._systemMsg( + this.systemMsg( 'debug', `commandTimeout: no prompt detected (${attempt}/${maxRetries})` ); @@ -930,19 +958,19 @@ class SSH2Shell extends Stream { switch (true) { // Check if sudo password is needed. case this.command.length > 0 && this.command.indexOf('sudo ') !== -1: - this._systemMsg('debug', `onData: Sudo command data`); + this.systemMsg('debug', `onData: Sudo command data`); return this._processSudoPrompt(); // Check for standard prompt from a command. case this.command.length > 0 && this.standardPrompt.test(this._sanitizeResponse()): - this._systemMsg('debug', `onData: Normal prompt detected`); + this.systemMsg('debug', `onData: Normal prompt detected`); this.sshObj.pwSent = false; return this._commandComplete(); // Check for no command but first prompt detected. case this.command.length < 1 && this.standardPrompt.test(this._buffer): - this._systemMsg('debug', `onData: First prompt detected`); + this.systemMsg('debug', `onData: First prompt detected`); // A prompt during a stop means the interrupted command (or the // sudo session) returned. Clearing the in-flight flag lets the stop @@ -956,7 +984,7 @@ class SSH2Shell extends Stream { } return this._nextCommand(); default: - this._systemMsg('debug', `onData: Reset timeout`); + this.systemMsg('debug', `onData: Reset timeout`); return this._scheduleIdleTimeout(this._buffer); } @@ -1038,9 +1066,9 @@ class SSH2Shell extends Stream { const response = this._sanitizeResponse().trim(); const passwordPrompt = this.passwordPrompt.test(response); const standardPrompt = this.standardPrompt.test(response); - this._systemMsg('debug', `processSudoPrompt: Password handling`); + this.systemMsg('debug', `processSudoPrompt: Password handling`); - this._systemMsg( + this.systemMsg( 'verbose', `processSudoPrompt: Password prompt: ${passwordPrompt}, Standard prompt: ${standardPrompt}, Password previously sent: ${this.sshObj.pwSent}` ); @@ -1049,7 +1077,7 @@ class SSH2Shell extends Stream { switch (true) { // No password. case passwordPrompt && !this.sshObj.server.password: - this._systemMsg('debug', `processSudoPrompt: No password set`); + this.systemMsg('debug', `processSudoPrompt: No password set`); this.sshObj.sudoFailed = true; this.emit( 'msg', @@ -1058,23 +1086,23 @@ class SSH2Shell extends Stream { return this._resetFromSudoError(); case passwordPrompt && !this.sshObj.pwSent: - this._systemMsg('debug', `processSudoPrompt: Send password`); + this.systemMsg('debug', `processSudoPrompt: Send password`); - this._systemMsg('verbose',`processSudoPrompt: Password: ${this.sshObj.server.password}`); + this.systemMsg('verbose',`processSudoPrompt: Password: ${this.sshObj.server.password}`); // Send password. this.sshObj.pwSent = true; return this._runCommand(`${this.sshObj.server.password}`); case passwordPrompt && this.sshObj.pwSent: - this._systemMsg('debug', `processSudoPrompt: Failed login`); + this.systemMsg('debug', `processSudoPrompt: Failed login`); // A rejected sudo password is visible by default. It is not fatal // unless the host opts in with `abortOnSudoFailure: true`. - this._systemMsg( + this.systemMsg( 'debug', `Password was incorrect for ${this.sshObj.server.userName}` ); - this._systemMsg('verbose',`processSudoPrompt: Failed login: Response: ${response}`); + this.systemMsg('verbose',`processSudoPrompt: Failed login: Response: ${response}`); this.sshObj.sudoFailed = true; this.emit( 'msg', @@ -1085,14 +1113,14 @@ class SSH2Shell extends Stream { // Add buffer to sessionText so the sudo response can be seen. return this._resetFromSudoError(); case standardPrompt: - this._systemMsg('debug', `processSudoPrompt: Password accepted`); + this.systemMsg('debug', `processSudoPrompt: Password accepted`); this.sshObj.pwSent = false; - this._systemMsg('verbose',`processSudoPrompt: Successful response: ${response}`); + this.systemMsg('verbose',`processSudoPrompt: Successful response: ${response}`); return this._commandComplete(); default: - this._systemMsg('debug', `processSudoPrompt: Reset timeout`); + this.systemMsg('debug', `processSudoPrompt: Reset timeout`); return this._scheduleIdleTimeout(response); } @@ -1126,21 +1154,21 @@ class SSH2Shell extends Stream { // An empty command has nothing to run or report, so skip it and continue // with the queue instead of leaving the state machine idle. if (!this.command) { - this._systemMsg('debug', `processNotifications: Empty command, skip`); + this.systemMsg('debug', `processNotifications: Empty command, skip`); return this._nextCommand(); } // This is a message for the sessionText like an echo command in bash. const sessionNote = this.command.match(/^`(.*)`$/); if (sessionNote) { - this._systemMsg('debug', `processNotifications: sessionText output`); + this.systemMsg('debug', `processNotifications: sessionText output`); if (this._connections.length > 0) { this.sshObj.sessionText += `${this.host}: Note: ${sessionNote[1]}${this.sshObj.enter}`; } else { this.sshObj.sessionText += `Note: ${sessionNote[1]}${this.sshObj.enter}`; } - this._systemMsg('verbose', sessionNote[1]); + this.systemMsg('verbose', sessionNote[1]); return this._nextCommand(); } @@ -1148,13 +1176,13 @@ class SSH2Shell extends Stream { // This is a message to output in process. const msgNote = this.command.match(/^msg:(.*)$/); if (msgNote) { - this._systemMsg('debug', `processNotifications: msg to output`); + this.systemMsg('debug', `processNotifications: msg to output`); this.emit('msg', `${this._hostPrefix()}Note: ${msgNote[1]}`); return this._nextCommand(); } - this._systemMsg('debug', `processNotifications: Normal Command to run`); + this.systemMsg('debug', `processNotifications: Normal Command to run`); return this._checkCommand(); } @@ -1173,9 +1201,9 @@ class SSH2Shell extends Stream { // `exit` is reported by the shell, not as a command response. It is the // literal command that leaves `su` / `sudo -i` or the primary shell. if (this.command !== '' && this.command !== 'exit') { - this._systemMsg('debug',`commandComplete: Raising commandComplete event`); + this.systemMsg('debug',`commandComplete: Raising commandComplete event`); - this._systemMsg( + this.systemMsg( 'verbose', `commandComplete:\nCommand:\n ${this.command}\nResponse: ${response}` ); @@ -1268,15 +1296,15 @@ class SSH2Shell extends Stream { // Process the next command if there are any. if (this.sshObj.commands.length > 0) { - this._systemMsg('debug',`nextCommand: Setting next command`); + this.systemMsg('debug',`nextCommand: Setting next command`); - this._systemMsg( + this.systemMsg( 'verbose', `nextCommand: Host commands: ${this.sshObj.commands}` ); this.command = this.sshObj.commands.shift(); - this._systemMsg( + this.systemMsg( 'verbose', `nextCommand: Next command: ${this.command}` ); @@ -1284,7 +1312,7 @@ class SSH2Shell extends Stream { return this._processNotifications(); } - this._systemMsg('debug',`nextCommand: No commands so exit`); + this.systemMsg('debug',`nextCommand: No commands so exit`); // No more commands so exit. return this._runExit(); @@ -1306,7 +1334,7 @@ class SSH2Shell extends Stream { } // No more commands so exit. - this._systemMsg('debug',`checkCommand: No command so exit`); + this.systemMsg('debug',`checkCommand: No command so exit`); return this._runExit(); } @@ -1329,9 +1357,9 @@ class SSH2Shell extends Stream { this._stderrBuffer = ''; } - this._systemMsg('debug',`runCommand:`); + this.systemMsg('debug',`runCommand:`); - this._systemMsg('verbose',`runCommand: Command: ${command}`); + this.systemMsg('verbose',`runCommand: Command: ${command}`); this._commandInFlight = Boolean(command); const written = this._stream.write(`${command}${this.sshObj.enter}`); @@ -1421,7 +1449,7 @@ class SSH2Shell extends Stream { if (!isPrimary) { this._mergeNestedText(host); - this._systemMsg( + this.systemMsg( 'debug', `finalizeHost: end nested host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}` ); @@ -1431,7 +1459,7 @@ class SSH2Shell extends Stream { this._primaryhostSessionText += `${host.sessionText || ''}\n`; this._allSessions += this._primaryhostSessionText; - this._systemMsg( + this.systemMsg( 'debug', `finalizeHost: end primary host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}` ); @@ -1472,7 +1500,7 @@ class SSH2Shell extends Stream { } const child = this._activeContext(); - this._systemMsg( + this.systemMsg( 'debug', `previousHost: close child connection: ${this.host}` ); @@ -1481,7 +1509,7 @@ class SSH2Shell extends Stream { // Closing the child removes its handlers and finalizes it exactly once. this._closeContext(child, 'previous-host'); this._popContext(); - this._systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); + this.systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); } else if (this._connections.length > 0) { // Fallback for callers that built the stack manually. The record form is // the supported one. @@ -1495,7 +1523,7 @@ class SSH2Shell extends Stream { this.sshObj = parentHost; this.host = this._hostLabel(parentHost); } - this._systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); + this.systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); } return this._runExit(); @@ -1523,7 +1551,7 @@ class SSH2Shell extends Stream { return this._runExit(); } - this._systemMsg( + this.systemMsg( 'debug', `nextHost: hop to ${this._hostLabel(nextHost)} through ${this.host}` ); @@ -1542,7 +1570,7 @@ class SSH2Shell extends Stream { return this._callFinalCallback(); } - this._systemMsg('debug', `nextPrimaryHost: load next host for ssh2 connection`); + this.systemMsg('debug', `nextPrimaryHost: load next host for ssh2 connection`); // Close the current primary and every active hop before resetting the // stack, so a new primary never inherits a hop's socket. @@ -1576,7 +1604,7 @@ class SSH2Shell extends Stream { } this._progressEnd(); - this._systemMsg('debug',`runExit: Process an exit`); + this.systemMsg('debug',`runExit: Process an exit`); if (this._stopping) { return this._beginStopExit(); @@ -1590,14 +1618,14 @@ class SSH2Shell extends Stream { if (!this._gracefulClosing && pending.length > 0) { // More nested hosts to connect to so process the next one. - this._systemMsg('debug',`runExit: Load next host`); + this.systemMsg('debug',`runExit: Load next host`); return this._nextHost(); } if (this._connections && this._connections.length > 0) { // Leaving last host so load previous host. - this._systemMsg('debug',`runExit: load previous host`); + this.systemMsg('debug',`runExit: load previous host`); this.emit('msg', `${this._hostPrefix()}${this.sshObj.closedMessage}`); return this._previousHost(); @@ -1606,7 +1634,7 @@ class SSH2Shell extends Stream { if (!this._gracefulClosing && this.command === 'exit') { // The literal `exit` leaves `su` / `sudo -i` or the primary shell. A hop // is left by closing its connection, not by an exit command. - this._systemMsg('debug',`runExit: run exit command`); + this.systemMsg('debug',`runExit: run exit command`); return this._runCommand('exit'); } @@ -1668,7 +1696,7 @@ class SSH2Shell extends Stream { } this._hosts.length = 0; - this._systemMsg('debug', `stop: requested (${reason})`); + this.systemMsg('debug', `stop: requested (${reason})`); this.emit('msg', `${this._hostPrefix()}Stop requested: ${reason}`); if (this._commandInFlight) { @@ -1730,7 +1758,7 @@ class SSH2Shell extends Stream { _forceStop() { this._clearStopTimer(); - this._systemMsg('debug', `stop: idle timeout while stopping`); + this.systemMsg('debug', `stop: idle timeout while stopping`); return this._finishStop(); } @@ -1804,7 +1832,7 @@ class SSH2Shell extends Stream { _forceClose() { this._clearCloseTimer(); - this._systemMsg('debug', `close: idle timeout while closing`); + this.systemMsg('debug', `close: idle timeout while closing`); return this._closeStreamNow(); } @@ -1814,7 +1842,7 @@ class SSH2Shell extends Stream { this._gracefulClosing = false; this._closing = true; this._progressEnd(); - this._systemMsg('debug',`Stream: close`); + this.systemMsg('debug',`Stream: close`); // Close the active record and every ancestor. `_closeContext` finalizes // each host once and closes its stream/connection. @@ -1852,7 +1880,7 @@ class SSH2Shell extends Stream { if (graceful && !this._stopping && this._hasLiveStream()) { this._gracefulClosing = true; this._progressEnd(); - this._systemMsg('debug',`Stream: graceful close`); + this.systemMsg('debug',`Stream: graceful close`); this._prepareGracefulClose(); if (this._commandInFlight) { @@ -1919,7 +1947,7 @@ class SSH2Shell extends Stream { return; } - this._systemMsg( + this.systemMsg( 'debug', `removeListeners: removing event listeners linked to ${context.host ? this._hostLabel(context.host) : 'host'}` ); @@ -2000,14 +2028,14 @@ class SSH2Shell extends Stream { _defaultOnCommandProcessing() {} _defaultOnCommandComplete() { - this._systemMsg('debug', `onCommandComplete:`); + this.systemMsg('debug', `onCommandComplete:`); } _defaultOnCommandTimeout(command, response, stream, connection, details) { // With `commandTimeoutRetries` configured, only the final attempt closes // the run. The library re-arms the timer for earlier attempts. if (details && details.final === false) { - this._systemMsg( + this.systemMsg( 'debug', `loadDefaults: Class.commandTimeout retry ${details.attempt}/${details.maxRetries}` ); @@ -2015,9 +2043,9 @@ class SSH2Shell extends Stream { } response = response.replace(this.command, ''); - this._systemMsg('debug', `loadDefaults: Class.commandTimeout`); + this.systemMsg('debug', `loadDefaults: Class.commandTimeout`); - this._systemMsg( + this.systemMsg( 'verbose', `loadDefaults: Timeout command: ${command} response: ${response}` ); @@ -2054,8 +2082,14 @@ class SSH2Shell extends Stream { this.command = ''; this._buffer = ''; this._stderrBuffer = ''; - this.debug = host.debug ?? false; - this.verbose = host.verbose ?? false; + this._debug = + typeof this._debugOverride === 'boolean' + ? this._debugOverride + : (host.debug ?? false); + this._verbose = + typeof this._verboseOverride === 'boolean' + ? this._verboseOverride + : (host.verbose ?? false); this.progress = host.progress !== false; this.exposeCredentials = host.exposeCredentials ?? false; @@ -2081,7 +2115,7 @@ class SSH2Shell extends Stream { } else if (!this.listeners('msg').includes(this.msg)) { this.on('msg', this.msg); } - this._systemMsg('debug',`Load Defaults`); + this.systemMsg('debug',`Load Defaults`); applyHostDefaults(host); @@ -2099,8 +2133,8 @@ class SSH2Shell extends Stream { // every load so a later host with different filters/prompts is honoured. const ascii = compileAsciiFilter(host.asciiFilter); this.asciiFilter = ascii.filter; - if (ascii.usedFallback && this.debug) { - this._systemMsg( + if (ascii.usedFallback && this._debug) { + this.systemMsg( 'debug', `loadDefaults: AsciiFilter: incorrect regular expression reverting to default: ${host.asciiFilter}` ); @@ -2109,8 +2143,8 @@ class SSH2Shell extends Stream { // Compile Text Color Filter with Safe Fallback. const color = compileTextColorFilter(host.textColorFilter); this.textColorFilter = color.filter; - if (color.usedFallback && this.debug) { - this._systemMsg( + if (color.usedFallback && this._debug) { + this.systemMsg( 'debug', `loadDefaults: TextColorFilter: incorrect regular expression reverting to default: ${host.textColorFilter}` ); @@ -2122,7 +2156,7 @@ class SSH2Shell extends Stream { this.passwordPrompt = prompts.passwordPrompt; this.standardPrompt = prompts.standardPrompt; if (prompts.standardPromptFallback) { - this._systemMsg( + this.systemMsg( 'debug', `loadDefaults: StandardPromptRegex: incorrect regular expression reverting to standardPrompt: ${host.standardPromptRegex}` ); @@ -2134,8 +2168,8 @@ class SSH2Shell extends Stream { record.passwordPrompt = this.passwordPrompt; record.asciiFilter = this.asciiFilter; record.textColorFilter = this.textColorFilter; - record.debug = this.debug; - record.verbose = this.verbose; + record.debug = this._debug; + record.verbose = this._verbose; record.progress = this.progress; record.exposeCredentials = this.exposeCredentials; @@ -2195,16 +2229,16 @@ class SSH2Shell extends Stream { prompts, finish ) => { - this._systemMsg('debug', `keyboard-interactive:`); + this.systemMsg('debug', `keyboard-interactive:`); - this._systemMsg('verbose', `name: ${name}`); - this._systemMsg('verbose', `instructions: ${instructions}`); + this.systemMsg('verbose', `name: ${name}`); + this.systemMsg('verbose', `instructions: ${instructions}`); const responses = prompts.map((prompt) => { - this._systemMsg('verbose', `prompts: ${prompt.prompt}`); + this.systemMsg('verbose', `prompts: ${prompt.prompt}`); return ''; // Baseline fallback response }); - this._systemMsg('verbose', `Prompts object: ${responses}`); + this.systemMsg('verbose', `Prompts object: ${responses}`); // The handshake stalls unless finish() receives an array of strings. finish(responses); }; @@ -2213,9 +2247,9 @@ class SSH2Shell extends Stream { this._loadDefaultListeners(); - this._systemMsg('debug',`loadDefaults: Host loaded`); + this.systemMsg('debug',`loadDefaults: Host loaded`); - this._systemMsg('verbose', 'loadDefaults: Config:', host); + this.systemMsg('verbose', 'loadDefaults: Config:', host); } connect(callback) { @@ -2273,7 +2307,7 @@ class SSH2Shell extends Stream { } if (context.isPrimary) { - this._systemMsg('debug', `Connect: primary`); + this.systemMsg('debug', `Connect: primary`); return this._openClient(context, server); } @@ -2282,7 +2316,7 @@ class SSH2Shell extends Stream { this._hopFailed(context, new Error('No parent connection for host hop')); return this._stream; } - this._systemMsg('debug', `Connect: forwardOut`); + this.systemMsg('debug', `Connect: forwardOut`); parentConnection.forwardOut( '127.0.0.1', 0, @@ -2384,7 +2418,7 @@ class SSH2Shell extends Stream { if (context.closed || context !== this._activeContext()) { return; } - this._systemMsg('debug', `Connection.keyboard-interactive`); + this.systemMsg('debug', `Connection.keyboard-interactive`); this.emit( 'keyboard-interactive', @@ -2401,7 +2435,7 @@ class SSH2Shell extends Stream { if (context.closed) { return; } - this._systemMsg('debug', `connect: Connection.connect`); + this.systemMsg('debug', `connect: Connection.connect`); this.emit('msg', context.host.connectedMessage); }); @@ -2409,7 +2443,7 @@ class SSH2Shell extends Stream { if (context.closed || context.failing) { return; } - this._systemMsg('debug', `connect: Connection.ready`); + this.systemMsg('debug', `connect: Connection.ready`); this.emit('msg', context.host.readyMessage); return this._openShell(context); }); @@ -2418,7 +2452,7 @@ class SSH2Shell extends Stream { if (context.closed || context.failing) { return; } - this._systemMsg('debug', `connect: Connection.error`); + this.systemMsg('debug', `connect: Connection.error`); if (context.isPrimary) { // Before the shell opens there is no live stream to close, so report @@ -2441,7 +2475,7 @@ class SSH2Shell extends Stream { connection.on('close', (had_error) => { this._progressEnd(); - this._systemMsg('debug', `connect: Connection.close`); + this.systemMsg('debug', `connect: Connection.close`); if (context.closed || context.failing) { return; @@ -2509,7 +2543,7 @@ class SSH2Shell extends Stream { } if (err instanceof Error) { - this._systemMsg('debug', `connect: Connection.shell`); + this.systemMsg('debug', `connect: Connection.shell`); // ssh2 can hand back a stream alongside the error. Store it on the // record so teardown closes it instead of leaking the shell. @@ -2538,7 +2572,7 @@ class SSH2Shell extends Stream { if (context === this._activeContext()) { this._stream = stream; } - this._systemMsg('debug', `connect: Connection.shell`); + this.systemMsg('debug', `connect: Connection.shell`); stream.setEncoding(host.streamEncoding); @@ -2546,7 +2580,7 @@ class SSH2Shell extends Stream { if (context.closed || context.failing) { return; } - this._systemMsg('debug', `connect: Stream.error`); + this.systemMsg('debug', `connect: Stream.error`); if (context.isPrimary) { this.emit('error', err, 'Stream', true, null, context); @@ -2559,7 +2593,7 @@ class SSH2Shell extends Stream { if (context.closed || context !== this._activeContext()) { return; } - this._systemMsg('debug', `connect: Stream.stderr.data`); + this.systemMsg('debug', `connect: Stream.stderr.data`); // Opt-in capture happens before the event so a handler can rely on // the buffer being current. The event still fires either way. @@ -2596,7 +2630,7 @@ class SSH2Shell extends Stream { return; } this._progressEnd(); - this._systemMsg('debug', `connect: Stream.finish`); + this.systemMsg('debug', `connect: Stream.finish`); // Finalize through the same path as close/connection close so the // text is appended and `end` fires exactly once per host. @@ -2605,7 +2639,7 @@ class SSH2Shell extends Stream { stream.on('close', (code, signal) => { this._progressEnd(); - this._systemMsg('debug', `connect: Stream.close`); + this.systemMsg('debug', `connect: Stream.close`); if (context.closed || context.failing) { return; diff --git a/package-lock.json b/package-lock.json index a53e298..5123269 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ssh2shell", - "version": "4.0.4", + "version": "4.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ssh2shell", - "version": "4.0.4", + "version": "4.1.0", "license": "ISC", "dependencies": { "ssh2": "^1.4.0" diff --git a/package.json b/package.json index 0522460..0033569 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ssh2shell", - "version": "4.0.4", + "version": "4.1.0", "author": "cmp-202", "description": "A wrapper class for ssh2 to run multiple sequential commands in an SSH shell session, handle command responses, and tunnel through to other hosts using nested host objects", "main": "./lib/ssh2shell.js", diff --git a/scripts/run-live.js b/scripts/run-live.js index b11c102..f7f5ebd 100644 --- a/scripts/run-live.js +++ b/scripts/run-live.js @@ -57,6 +57,8 @@ const defaultTests = [ 'sudo_no_pass', 'prompt_response', 'command_timeout', + 'default_command_timeout', + 'progress_tty', 'multiple_primary_hosts', 'stop_on_failure', 'close_from_handler', @@ -123,6 +125,11 @@ const checks = { contains: ['answer=y'], allowErrors: ['Command Timeout'], }, + default_command_timeout: { + contains: ['Default timeout prompt'], + logContains: ['Command Timeout:'], + allowErrors: ['Command Timeout'], + }, multiple_primary_hosts: { contains: [server1, server2].filter(Boolean), }, @@ -208,6 +215,15 @@ const checks = { progress: { contains: ['progress-demo-', server1, server2].filter(Boolean), }, + progress_tty: { + contains: ['progress-tty-first', 'progress-tty-second'], + logContains: [ + 'progress-tty-output:', + 'progress-tty-ticks:ok', + 'progress-tty-labels:ok', + ], + logExcludes: ['progress-tty-ticks:missing', 'progress-tty-labels:missing'], + }, chaining: { contains: [server1, server2, server3].filter(Boolean), excludes: ['SSH failed'], diff --git a/src/ssh2shell.js b/src/ssh2shell.js index c828aa8..d9311eb 100644 --- a/src/ssh2shell.js +++ b/src/ssh2shell.js @@ -143,6 +143,13 @@ class SSH2Shell extends Stream { // class-body values used to be shared through the prototype until the first // host load, which aliased `_stream` between instances. this._callback = null; + // `debug`/`verbose` are public instance-level overrides. An explicit + // boolean wins over every host's setting; `undefined` means "use the host". + // `_debug`/`_verbose` are the effective values for the active host. + this._debugOverride = undefined; + this._verboseOverride = undefined; + this._debug = false; + this._verbose = false; this.command = ''; this._primaryhostSessionText = ''; this._stream = {}; @@ -157,7 +164,28 @@ class SSH2Shell extends Stream { this.standardPrompt = ''; this._loadDefaultListeners(); } - + + // Public override fields. Reading returns the effective value for the active + // host; assigning a boolean sets a run-wide override that applies to every + // host, including when the value is false. + get debug() { + return this._debug; + } + + set debug(value) { + this._debugOverride = typeof value === 'boolean' ? value : undefined; + this._debug = value === true; + } + + get verbose() { + return this._verbose; + } + + set verbose(value) { + this._verboseOverride = typeof value === 'boolean' ? value : undefined; + this._verbose = value === true; + } + _loadDefaultListeners() { if (!this.msg) { this.msg = (message) => { @@ -205,7 +233,7 @@ class SSH2Shell extends Stream { if (!this._defaultErrorListener) { this._defaultErrorListener = (err, type, close = false, callback, context) => { this._progressEnd(); - this._systemMsg('debug', `Class.error: ${err}, ${type}`); + this.systemMsg('debug', `Class.error: ${err}, ${type}`); if (err instanceof Error) { this.emit('msg', `Error: ${err.message}, Level: ${err.level}`); @@ -408,10 +436,10 @@ class SSH2Shell extends Stream { this.textColorFilter = context.textColorFilter; } if (typeof context.debug === 'boolean') { - this.debug = context.debug; + this._debug = context.debug; } if (typeof context.verbose === 'boolean') { - this.verbose = context.verbose; + this._verbose = context.verbose; } if (typeof context.progress === 'boolean') { this.progress = context.progress; @@ -667,8 +695,8 @@ class SSH2Shell extends Stream { _progressEnabled() { return ( this.progress === true && - this.debug !== true && - this.verbose !== true && + this._debug !== true && + this._verbose !== true && this._progressStream && this._progressStream.isTTY === true ); @@ -751,12 +779,12 @@ class SSH2Shell extends Stream { this._progressNewline(); } - // Emits debug/verbose messages only when the matching host flag is enabled. + // Emits debug/verbose messages only when the matching flag is enabled. // An optional object payload is emitted as a second message. - _systemMsg(type, message, object = null){ + systemMsg(type, message, object = null){ const enabled = - (type === 'debug' && this.debug) || - (type === 'verbose' && this.verbose); + (type === 'debug' && this._debug) || + (type === 'verbose' && this._verbose); if (!enabled) { return; @@ -807,7 +835,7 @@ class SSH2Shell extends Stream { const maxRetries = toNonNegativeInteger(this.sshObj.commandTimeoutRetries); const final = attempt > maxRetries; - this._systemMsg( + this.systemMsg( 'debug', `commandTimeout: no prompt detected (${attempt}/${maxRetries})` ); @@ -930,19 +958,19 @@ class SSH2Shell extends Stream { switch (true) { // Check if sudo password is needed. case this.command.length > 0 && this.command.indexOf('sudo ') !== -1: - this._systemMsg('debug', `onData: Sudo command data`); + this.systemMsg('debug', `onData: Sudo command data`); return this._processSudoPrompt(); // Check for standard prompt from a command. case this.command.length > 0 && this.standardPrompt.test(this._sanitizeResponse()): - this._systemMsg('debug', `onData: Normal prompt detected`); + this.systemMsg('debug', `onData: Normal prompt detected`); this.sshObj.pwSent = false; return this._commandComplete(); // Check for no command but first prompt detected. case this.command.length < 1 && this.standardPrompt.test(this._buffer): - this._systemMsg('debug', `onData: First prompt detected`); + this.systemMsg('debug', `onData: First prompt detected`); // A prompt during a stop means the interrupted command (or the // sudo session) returned. Clearing the in-flight flag lets the stop @@ -956,7 +984,7 @@ class SSH2Shell extends Stream { } return this._nextCommand(); default: - this._systemMsg('debug', `onData: Reset timeout`); + this.systemMsg('debug', `onData: Reset timeout`); return this._scheduleIdleTimeout(this._buffer); } @@ -1038,9 +1066,9 @@ class SSH2Shell extends Stream { const response = this._sanitizeResponse().trim(); const passwordPrompt = this.passwordPrompt.test(response); const standardPrompt = this.standardPrompt.test(response); - this._systemMsg('debug', `processSudoPrompt: Password handling`); + this.systemMsg('debug', `processSudoPrompt: Password handling`); - this._systemMsg( + this.systemMsg( 'verbose', `processSudoPrompt: Password prompt: ${passwordPrompt}, Standard prompt: ${standardPrompt}, Password previously sent: ${this.sshObj.pwSent}` ); @@ -1049,7 +1077,7 @@ class SSH2Shell extends Stream { switch (true) { // No password. case passwordPrompt && !this.sshObj.server.password: - this._systemMsg('debug', `processSudoPrompt: No password set`); + this.systemMsg('debug', `processSudoPrompt: No password set`); this.sshObj.sudoFailed = true; this.emit( 'msg', @@ -1058,23 +1086,23 @@ class SSH2Shell extends Stream { return this._resetFromSudoError(); case passwordPrompt && !this.sshObj.pwSent: - this._systemMsg('debug', `processSudoPrompt: Send password`); + this.systemMsg('debug', `processSudoPrompt: Send password`); - this._systemMsg('verbose',`processSudoPrompt: Password: ${this.sshObj.server.password}`); + this.systemMsg('verbose',`processSudoPrompt: Password: ${this.sshObj.server.password}`); // Send password. this.sshObj.pwSent = true; return this._runCommand(`${this.sshObj.server.password}`); case passwordPrompt && this.sshObj.pwSent: - this._systemMsg('debug', `processSudoPrompt: Failed login`); + this.systemMsg('debug', `processSudoPrompt: Failed login`); // A rejected sudo password is visible by default. It is not fatal // unless the host opts in with `abortOnSudoFailure: true`. - this._systemMsg( + this.systemMsg( 'debug', `Password was incorrect for ${this.sshObj.server.userName}` ); - this._systemMsg('verbose',`processSudoPrompt: Failed login: Response: ${response}`); + this.systemMsg('verbose',`processSudoPrompt: Failed login: Response: ${response}`); this.sshObj.sudoFailed = true; this.emit( 'msg', @@ -1085,14 +1113,14 @@ class SSH2Shell extends Stream { // Add buffer to sessionText so the sudo response can be seen. return this._resetFromSudoError(); case standardPrompt: - this._systemMsg('debug', `processSudoPrompt: Password accepted`); + this.systemMsg('debug', `processSudoPrompt: Password accepted`); this.sshObj.pwSent = false; - this._systemMsg('verbose',`processSudoPrompt: Successful response: ${response}`); + this.systemMsg('verbose',`processSudoPrompt: Successful response: ${response}`); return this._commandComplete(); default: - this._systemMsg('debug', `processSudoPrompt: Reset timeout`); + this.systemMsg('debug', `processSudoPrompt: Reset timeout`); return this._scheduleIdleTimeout(response); } @@ -1126,21 +1154,21 @@ class SSH2Shell extends Stream { // An empty command has nothing to run or report, so skip it and continue // with the queue instead of leaving the state machine idle. if (!this.command) { - this._systemMsg('debug', `processNotifications: Empty command, skip`); + this.systemMsg('debug', `processNotifications: Empty command, skip`); return this._nextCommand(); } // This is a message for the sessionText like an echo command in bash. const sessionNote = this.command.match(/^`(.*)`$/); if (sessionNote) { - this._systemMsg('debug', `processNotifications: sessionText output`); + this.systemMsg('debug', `processNotifications: sessionText output`); if (this._connections.length > 0) { this.sshObj.sessionText += `${this.host}: Note: ${sessionNote[1]}${this.sshObj.enter}`; } else { this.sshObj.sessionText += `Note: ${sessionNote[1]}${this.sshObj.enter}`; } - this._systemMsg('verbose', sessionNote[1]); + this.systemMsg('verbose', sessionNote[1]); return this._nextCommand(); } @@ -1148,13 +1176,13 @@ class SSH2Shell extends Stream { // This is a message to output in process. const msgNote = this.command.match(/^msg:(.*)$/); if (msgNote) { - this._systemMsg('debug', `processNotifications: msg to output`); + this.systemMsg('debug', `processNotifications: msg to output`); this.emit('msg', `${this._hostPrefix()}Note: ${msgNote[1]}`); return this._nextCommand(); } - this._systemMsg('debug', `processNotifications: Normal Command to run`); + this.systemMsg('debug', `processNotifications: Normal Command to run`); return this._checkCommand(); } @@ -1173,9 +1201,9 @@ class SSH2Shell extends Stream { // `exit` is reported by the shell, not as a command response. It is the // literal command that leaves `su` / `sudo -i` or the primary shell. if (this.command !== '' && this.command !== 'exit') { - this._systemMsg('debug',`commandComplete: Raising commandComplete event`); + this.systemMsg('debug',`commandComplete: Raising commandComplete event`); - this._systemMsg( + this.systemMsg( 'verbose', `commandComplete:\nCommand:\n ${this.command}\nResponse: ${response}` ); @@ -1268,15 +1296,15 @@ class SSH2Shell extends Stream { // Process the next command if there are any. if (this.sshObj.commands.length > 0) { - this._systemMsg('debug',`nextCommand: Setting next command`); + this.systemMsg('debug',`nextCommand: Setting next command`); - this._systemMsg( + this.systemMsg( 'verbose', `nextCommand: Host commands: ${this.sshObj.commands}` ); this.command = this.sshObj.commands.shift(); - this._systemMsg( + this.systemMsg( 'verbose', `nextCommand: Next command: ${this.command}` ); @@ -1284,7 +1312,7 @@ class SSH2Shell extends Stream { return this._processNotifications(); } - this._systemMsg('debug',`nextCommand: No commands so exit`); + this.systemMsg('debug',`nextCommand: No commands so exit`); // No more commands so exit. return this._runExit(); @@ -1306,7 +1334,7 @@ class SSH2Shell extends Stream { } // No more commands so exit. - this._systemMsg('debug',`checkCommand: No command so exit`); + this.systemMsg('debug',`checkCommand: No command so exit`); return this._runExit(); } @@ -1329,9 +1357,9 @@ class SSH2Shell extends Stream { this._stderrBuffer = ''; } - this._systemMsg('debug',`runCommand:`); + this.systemMsg('debug',`runCommand:`); - this._systemMsg('verbose',`runCommand: Command: ${command}`); + this.systemMsg('verbose',`runCommand: Command: ${command}`); this._commandInFlight = Boolean(command); const written = this._stream.write(`${command}${this.sshObj.enter}`); @@ -1421,7 +1449,7 @@ class SSH2Shell extends Stream { if (!isPrimary) { this._mergeNestedText(host); - this._systemMsg( + this.systemMsg( 'debug', `finalizeHost: end nested host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}` ); @@ -1431,7 +1459,7 @@ class SSH2Shell extends Stream { this._primaryhostSessionText += `${host.sessionText || ''}\n`; this._allSessions += this._primaryhostSessionText; - this._systemMsg( + this.systemMsg( 'debug', `finalizeHost: end primary host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}` ); @@ -1472,7 +1500,7 @@ class SSH2Shell extends Stream { } const child = this._activeContext(); - this._systemMsg( + this.systemMsg( 'debug', `previousHost: close child connection: ${this.host}` ); @@ -1481,7 +1509,7 @@ class SSH2Shell extends Stream { // Closing the child removes its handlers and finalizes it exactly once. this._closeContext(child, 'previous-host'); this._popContext(); - this._systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); + this.systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); } else if (this._connections.length > 0) { // Fallback for callers that built the stack manually. The record form is // the supported one. @@ -1495,7 +1523,7 @@ class SSH2Shell extends Stream { this.sshObj = parentHost; this.host = this._hostLabel(parentHost); } - this._systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); + this.systemMsg('debug', `previousHost: previous host loaded: ${this.host}`); } return this._runExit(); @@ -1523,7 +1551,7 @@ class SSH2Shell extends Stream { return this._runExit(); } - this._systemMsg( + this.systemMsg( 'debug', `nextHost: hop to ${this._hostLabel(nextHost)} through ${this.host}` ); @@ -1542,7 +1570,7 @@ class SSH2Shell extends Stream { return this._callFinalCallback(); } - this._systemMsg('debug', `nextPrimaryHost: load next host for ssh2 connection`); + this.systemMsg('debug', `nextPrimaryHost: load next host for ssh2 connection`); // Close the current primary and every active hop before resetting the // stack, so a new primary never inherits a hop's socket. @@ -1576,7 +1604,7 @@ class SSH2Shell extends Stream { } this._progressEnd(); - this._systemMsg('debug',`runExit: Process an exit`); + this.systemMsg('debug',`runExit: Process an exit`); if (this._stopping) { return this._beginStopExit(); @@ -1590,14 +1618,14 @@ class SSH2Shell extends Stream { if (!this._gracefulClosing && pending.length > 0) { // More nested hosts to connect to so process the next one. - this._systemMsg('debug',`runExit: Load next host`); + this.systemMsg('debug',`runExit: Load next host`); return this._nextHost(); } if (this._connections && this._connections.length > 0) { // Leaving last host so load previous host. - this._systemMsg('debug',`runExit: load previous host`); + this.systemMsg('debug',`runExit: load previous host`); this.emit('msg', `${this._hostPrefix()}${this.sshObj.closedMessage}`); return this._previousHost(); @@ -1606,7 +1634,7 @@ class SSH2Shell extends Stream { if (!this._gracefulClosing && this.command === 'exit') { // The literal `exit` leaves `su` / `sudo -i` or the primary shell. A hop // is left by closing its connection, not by an exit command. - this._systemMsg('debug',`runExit: run exit command`); + this.systemMsg('debug',`runExit: run exit command`); return this._runCommand('exit'); } @@ -1668,7 +1696,7 @@ class SSH2Shell extends Stream { } this._hosts.length = 0; - this._systemMsg('debug', `stop: requested (${reason})`); + this.systemMsg('debug', `stop: requested (${reason})`); this.emit('msg', `${this._hostPrefix()}Stop requested: ${reason}`); if (this._commandInFlight) { @@ -1730,7 +1758,7 @@ class SSH2Shell extends Stream { _forceStop() { this._clearStopTimer(); - this._systemMsg('debug', `stop: idle timeout while stopping`); + this.systemMsg('debug', `stop: idle timeout while stopping`); return this._finishStop(); } @@ -1804,7 +1832,7 @@ class SSH2Shell extends Stream { _forceClose() { this._clearCloseTimer(); - this._systemMsg('debug', `close: idle timeout while closing`); + this.systemMsg('debug', `close: idle timeout while closing`); return this._closeStreamNow(); } @@ -1814,7 +1842,7 @@ class SSH2Shell extends Stream { this._gracefulClosing = false; this._closing = true; this._progressEnd(); - this._systemMsg('debug',`Stream: close`); + this.systemMsg('debug',`Stream: close`); // Close the active record and every ancestor. `_closeContext` finalizes // each host once and closes its stream/connection. @@ -1852,7 +1880,7 @@ class SSH2Shell extends Stream { if (graceful && !this._stopping && this._hasLiveStream()) { this._gracefulClosing = true; this._progressEnd(); - this._systemMsg('debug',`Stream: graceful close`); + this.systemMsg('debug',`Stream: graceful close`); this._prepareGracefulClose(); if (this._commandInFlight) { @@ -1919,7 +1947,7 @@ class SSH2Shell extends Stream { return; } - this._systemMsg( + this.systemMsg( 'debug', `removeListeners: removing event listeners linked to ${context.host ? this._hostLabel(context.host) : 'host'}` ); @@ -2000,14 +2028,14 @@ class SSH2Shell extends Stream { _defaultOnCommandProcessing() {} _defaultOnCommandComplete() { - this._systemMsg('debug', `onCommandComplete:`); + this.systemMsg('debug', `onCommandComplete:`); } _defaultOnCommandTimeout(command, response, stream, connection, details) { // With `commandTimeoutRetries` configured, only the final attempt closes // the run. The library re-arms the timer for earlier attempts. if (details && details.final === false) { - this._systemMsg( + this.systemMsg( 'debug', `loadDefaults: Class.commandTimeout retry ${details.attempt}/${details.maxRetries}` ); @@ -2015,9 +2043,9 @@ class SSH2Shell extends Stream { } response = response.replace(this.command, ''); - this._systemMsg('debug', `loadDefaults: Class.commandTimeout`); + this.systemMsg('debug', `loadDefaults: Class.commandTimeout`); - this._systemMsg( + this.systemMsg( 'verbose', `loadDefaults: Timeout command: ${command} response: ${response}` ); @@ -2054,8 +2082,14 @@ class SSH2Shell extends Stream { this.command = ''; this._buffer = ''; this._stderrBuffer = ''; - this.debug = host.debug ?? false; - this.verbose = host.verbose ?? false; + this._debug = + typeof this._debugOverride === 'boolean' + ? this._debugOverride + : (host.debug ?? false); + this._verbose = + typeof this._verboseOverride === 'boolean' + ? this._verboseOverride + : (host.verbose ?? false); this.progress = host.progress !== false; this.exposeCredentials = host.exposeCredentials ?? false; @@ -2081,7 +2115,7 @@ class SSH2Shell extends Stream { } else if (!this.listeners('msg').includes(this.msg)) { this.on('msg', this.msg); } - this._systemMsg('debug',`Load Defaults`); + this.systemMsg('debug',`Load Defaults`); applyHostDefaults(host); @@ -2099,8 +2133,8 @@ class SSH2Shell extends Stream { // every load so a later host with different filters/prompts is honoured. const ascii = compileAsciiFilter(host.asciiFilter); this.asciiFilter = ascii.filter; - if (ascii.usedFallback && this.debug) { - this._systemMsg( + if (ascii.usedFallback && this._debug) { + this.systemMsg( 'debug', `loadDefaults: AsciiFilter: incorrect regular expression reverting to default: ${host.asciiFilter}` ); @@ -2109,8 +2143,8 @@ class SSH2Shell extends Stream { // Compile Text Color Filter with Safe Fallback. const color = compileTextColorFilter(host.textColorFilter); this.textColorFilter = color.filter; - if (color.usedFallback && this.debug) { - this._systemMsg( + if (color.usedFallback && this._debug) { + this.systemMsg( 'debug', `loadDefaults: TextColorFilter: incorrect regular expression reverting to default: ${host.textColorFilter}` ); @@ -2122,7 +2156,7 @@ class SSH2Shell extends Stream { this.passwordPrompt = prompts.passwordPrompt; this.standardPrompt = prompts.standardPrompt; if (prompts.standardPromptFallback) { - this._systemMsg( + this.systemMsg( 'debug', `loadDefaults: StandardPromptRegex: incorrect regular expression reverting to standardPrompt: ${host.standardPromptRegex}` ); @@ -2134,8 +2168,8 @@ class SSH2Shell extends Stream { record.passwordPrompt = this.passwordPrompt; record.asciiFilter = this.asciiFilter; record.textColorFilter = this.textColorFilter; - record.debug = this.debug; - record.verbose = this.verbose; + record.debug = this._debug; + record.verbose = this._verbose; record.progress = this.progress; record.exposeCredentials = this.exposeCredentials; @@ -2195,16 +2229,16 @@ class SSH2Shell extends Stream { prompts, finish ) => { - this._systemMsg('debug', `keyboard-interactive:`); + this.systemMsg('debug', `keyboard-interactive:`); - this._systemMsg('verbose', `name: ${name}`); - this._systemMsg('verbose', `instructions: ${instructions}`); + this.systemMsg('verbose', `name: ${name}`); + this.systemMsg('verbose', `instructions: ${instructions}`); const responses = prompts.map((prompt) => { - this._systemMsg('verbose', `prompts: ${prompt.prompt}`); + this.systemMsg('verbose', `prompts: ${prompt.prompt}`); return ''; // Baseline fallback response }); - this._systemMsg('verbose', `Prompts object: ${responses}`); + this.systemMsg('verbose', `Prompts object: ${responses}`); // The handshake stalls unless finish() receives an array of strings. finish(responses); }; @@ -2213,9 +2247,9 @@ class SSH2Shell extends Stream { this._loadDefaultListeners(); - this._systemMsg('debug',`loadDefaults: Host loaded`); + this.systemMsg('debug',`loadDefaults: Host loaded`); - this._systemMsg('verbose', 'loadDefaults: Config:', host); + this.systemMsg('verbose', 'loadDefaults: Config:', host); } connect(callback) { @@ -2273,7 +2307,7 @@ class SSH2Shell extends Stream { } if (context.isPrimary) { - this._systemMsg('debug', `Connect: primary`); + this.systemMsg('debug', `Connect: primary`); return this._openClient(context, server); } @@ -2282,7 +2316,7 @@ class SSH2Shell extends Stream { this._hopFailed(context, new Error('No parent connection for host hop')); return this._stream; } - this._systemMsg('debug', `Connect: forwardOut`); + this.systemMsg('debug', `Connect: forwardOut`); parentConnection.forwardOut( '127.0.0.1', 0, @@ -2384,7 +2418,7 @@ class SSH2Shell extends Stream { if (context.closed || context !== this._activeContext()) { return; } - this._systemMsg('debug', `Connection.keyboard-interactive`); + this.systemMsg('debug', `Connection.keyboard-interactive`); this.emit( 'keyboard-interactive', @@ -2401,7 +2435,7 @@ class SSH2Shell extends Stream { if (context.closed) { return; } - this._systemMsg('debug', `connect: Connection.connect`); + this.systemMsg('debug', `connect: Connection.connect`); this.emit('msg', context.host.connectedMessage); }); @@ -2409,7 +2443,7 @@ class SSH2Shell extends Stream { if (context.closed || context.failing) { return; } - this._systemMsg('debug', `connect: Connection.ready`); + this.systemMsg('debug', `connect: Connection.ready`); this.emit('msg', context.host.readyMessage); return this._openShell(context); }); @@ -2418,7 +2452,7 @@ class SSH2Shell extends Stream { if (context.closed || context.failing) { return; } - this._systemMsg('debug', `connect: Connection.error`); + this.systemMsg('debug', `connect: Connection.error`); if (context.isPrimary) { // Before the shell opens there is no live stream to close, so report @@ -2441,7 +2475,7 @@ class SSH2Shell extends Stream { connection.on('close', (had_error) => { this._progressEnd(); - this._systemMsg('debug', `connect: Connection.close`); + this.systemMsg('debug', `connect: Connection.close`); if (context.closed || context.failing) { return; @@ -2509,7 +2543,7 @@ class SSH2Shell extends Stream { } if (err instanceof Error) { - this._systemMsg('debug', `connect: Connection.shell`); + this.systemMsg('debug', `connect: Connection.shell`); // ssh2 can hand back a stream alongside the error. Store it on the // record so teardown closes it instead of leaking the shell. @@ -2538,7 +2572,7 @@ class SSH2Shell extends Stream { if (context === this._activeContext()) { this._stream = stream; } - this._systemMsg('debug', `connect: Connection.shell`); + this.systemMsg('debug', `connect: Connection.shell`); stream.setEncoding(host.streamEncoding); @@ -2546,7 +2580,7 @@ class SSH2Shell extends Stream { if (context.closed || context.failing) { return; } - this._systemMsg('debug', `connect: Stream.error`); + this.systemMsg('debug', `connect: Stream.error`); if (context.isPrimary) { this.emit('error', err, 'Stream', true, null, context); @@ -2559,7 +2593,7 @@ class SSH2Shell extends Stream { if (context.closed || context !== this._activeContext()) { return; } - this._systemMsg('debug', `connect: Stream.stderr.data`); + this.systemMsg('debug', `connect: Stream.stderr.data`); // Opt-in capture happens before the event so a handler can rely on // the buffer being current. The event still fires either way. @@ -2596,7 +2630,7 @@ class SSH2Shell extends Stream { return; } this._progressEnd(); - this._systemMsg('debug', `connect: Stream.finish`); + this.systemMsg('debug', `connect: Stream.finish`); // Finalize through the same path as close/connection close so the // text is appended and `end` fires exactly once per host. @@ -2605,7 +2639,7 @@ class SSH2Shell extends Stream { stream.on('close', (code, signal) => { this._progressEnd(); - this._systemMsg('debug', `connect: Stream.close`); + this.systemMsg('debug', `connect: Stream.close`); if (context.closed || context.failing) { return; diff --git a/test/coverage.md b/test/coverage.md new file mode 100644 index 0000000..270a788 --- /dev/null +++ b/test/coverage.md @@ -0,0 +1,322 @@ +# Code coverage + +This file records the coverage review, how it was measured, what the numbers +mean, the follow-up tests added, and where the unit and live suites overlap in +what they miss. Coverage is a diagnostic here, not a release gate. + +## Measurement method + +The repository has no coverage dependency. Node 26's built-in reporter was used +directly, so no packages or workflow changes are required to reproduce it. + +Unit tests (run against the built `lib/`): + +```sh +$env:SSH2SHELL_TEST_MODULE = (Resolve-Path 'lib/ssh2shell.js').Path +$files = Get-ChildItem -Recurse 'test/unit' -Filter '*.test.js' | + ForEach-Object { $_.FullName } | Sort-Object +node --experimental-test-coverage --test $files +``` + +Live tests (run against `src/`, which is what `scripts/run-live.js` defaults to). +The files must run serially because several use the same hosts/ports: + +```sh +$env:SSH2SHELL_LIVE_MODULE = (Resolve-Path 'src/ssh2shell.js').Path +$files = Get-ChildItem 'test/live' -Filter '*.js' | + ForEach-Object { $_.FullName } | Sort-Object +node --experimental-test-coverage --test --test-concurrency=1 $files +``` + +To compare the suites, ask Node for LCOV as well as the text report: + +```sh +node --experimental-test-coverage --test ` + --test-reporter=spec --test-reporter-destination=stdout ` + --test-reporter=lcov --test-reporter-destination="$env:TEMP\unit.lcov" ` + $files +``` + +Repeat for the live command with `$env:TEMP\live.lcov`. The two LCOV files can +be parsed for hit lines and misses to produce the overlap analysis below. +This is deliberately not a script: the live half needs the test hosts, and a +wrapper would only duplicate the commands above. The summary is written into the +PR description by hand, and the raw LCOV files stay local unless a reviewer asks +for them. + +Do **not** collect live coverage by setting `NODE_V8_COVERAGE` on +`npm run test:live:all`. That path slowed timing-sensitive tests enough to fail +four of them (`chaining`, `close_from_handler`, `command_timeout`, plus one +other) even though the same tests pass under the standard reporter. + +## First review — baseline numbers + +Measured on 2026-11-22 with Node v26.13.0, before the follow-up tests below. + +| Suite | Target | Lines | Branches | Functions | +| --- | --- | --- | --- | --- | +| Unit | `lib/ssh2shell.js` | 90.30% | 80.87% | 98.29% | +| Unit | `lib/ssh2shell/defaults.js` | 97.96% | 96.97% | 100% | +| Unit | `lib/ssh2shell/util.js` | 94.77% | 84.48% | 100% | +| Unit | all files | 90.82% | 81.95% | 98.47% | +| Live (28 tests) | `src/ssh2shell.js` | 76.68% | 57.01% | 83.48% | +| Live (28 tests) | `src/ssh2shell/defaults.js` | 97.96% | 50.00% | 100% | +| Live (28 tests) | `src/ssh2shell/util.js` | 83.14% | 68.09% | 100% | +| Live (28 tests) | all files | 77.77% | 57.99% | 85.27% | + +### How to read "uncovered lines" + +The reporter lists uncovered **line ranges**, not uncovered methods. A method +can be entered on every test and still show a large count, because the count is +the number of lines in branches that were not taken. Examples from the first +review: + +- Live `_loadDefaults`: 56 uncovered lines out of roughly 187 in the method. + The method runs on every test; the misses are conditional branches — the + direct-call context fallback, `msg` listener rebinding, invalid-regex debug + warnings, host `onError` / `onData` / `onStderrData` binding, and the default + keyboard-interactive handler. +- Unit `_openShell`: 29 uncovered lines, almost all transport error handling. +- Unit `_connect`: 23 uncovered lines, mostly the `forwardOut` cancellation + path. +- Unit `_reportMissingParameters`: fully covered by unit tests; the 23 live + uncovered lines belong to a branch the live suite never exercises. + +Grouping uncovered lines by enclosing method is a readability aid only. Nested +callbacks are attributed to their enclosing method, and the last method in the +file absorbs everything after its start line. The percentages themselves are +computed correctly by the reporter and are not affected by this. + +## Where each suite is strongest + +| Concern | Unit | Live | +| --- | --- | --- | +| Speed / determinism | Fast, offline, fake `ssh2` | Slow, needs the VMs | +| State machine and record stack | Strong | Moderate | +| Validation and error branches | Strong | Weak by nature | +| Credential redaction | Strong | Weak | +| Real prompt/sudo/hop handshakes | Weak | Strong | +| Real stream timing and idle timeouts | Weak | Strong | +| TTY-gated progress indicator | Strong with a fake TTY sink | Only with an injected sink | + +The suites are complementary: neither reaches a high line percentage alone, and +the union is what matters. New tests therefore go to the suite that can prove +the behaviour most directly, rather than duplicating a case in both. + +## Follow-up tests (implemented) + +The follow-up work was done in four passes. The first pass added the unit and +live tests below. The second and third passes added deterministic unit tests +for the largest blocks still missed by both suites after each preceding pass. +The final pass added five behaviour-focused tests for genuine failure modes. +Lower-priority defensive branches are deliberately left alone. + +Two candidates from the first review were **not** added: the keyboard-interactive +fallback is already covered by `l5-behavior.test.js`, and the invalid-regex +debug warnings are covered by `api-baseline.test.js` and `prompt-regex.test.js`. +Duplicating them would not improve the overlap. + +### First pass — unit: `test/unit/coverage-gaps.test.js` + +| Test | Gap addressed | Why unit | +| --- | --- | --- | +| binds host `stderrData` and `end` handlers | `_loadDefaults` lines 2206–2207 and 2209–2210 in `src/ssh2shell.js` | The fake emitter can assert listener registration and invocation directly. | +| replaces a previous host `msg` handler when defaults reload | `_loadDefaults` lines 2107–2109 | Reloading defaults on the same record is deterministic and needs no connection. | +| collects active and nested descendants, excluding closed records | `_descendantsOf` lines 488–489, 494–495, 499–505 | The record stack is directly constructible; live hops cannot isolate these branches. | + +### First pass — live + +| Test | Gap addressed | Why live | +| --- | --- | --- | +| `default_command_timeout.js` — no host `onCommandTimeout`, real idle timeout | `_defaultOnCommandTimeout`, 29 uncovered lines in the first live review (`src/ssh2shell.js` lines 2034–2063) | Only a real stalled command proves the default error/close path end to end. | +| `progress_tty.js` — injected TTY-like sink and slow commands on two primary hosts | `_progressStart`, `_progressTick`, `_progressLabel`, `_progressNewline`, `_progressEnd` (`src/ssh2shell.js` lines 695–780) | Progress is TTY-gated and timer-driven; the normal piped runner cannot exercise it. | + +Both live tests are registered in `scripts/run-live.js` checks and in the +curated default batch, so they run under `npm run test:live`, +`npm run test:live:all`, and CI. + +### Second pass — unit: `test/unit/coverage-gaps-state.test.js` + +These 12 tests target the five largest blocks that remained missed by both +suites after the first pass. Each test is skipped against the frozen baseline +because the record/transport guards do not exist there. + +| Coverage area | Lines targeted | Tests | +| --- | --- | --- | +| `_openShell` (29 lines) | 2535–2543, 2581–2582, 2589, 2594–2595, 2611–2625 | Stale-context stream close, ignored stale stream error, hop stream error, stale stderr guard, throwing `data` listener on a primary and on a hop. | +| `_connect` (23 lines) | 2280–2281, 2316–2318, 2331–2332, 2342–2357 | Stopped-run guard, hop without a parent connection, stale `forwardOut` channel close, stop during `forwardOut`. | +| `_bindConnection` (21 lines) | 2419–2420, 2436–2437, 2444–2445, 2453–2454, 2471–2473, 2507–2509, 2511–2517 | Closed-context keyboard-interactive/connect/ready/error guards, inactive active-context guard, and hop failure containment. | +| `_previousHost` (16 lines) | 1499–1500, 1514–1527 | Stopped-run guard and manual parent-stack restore. | +| `_checkCommand` (9 lines) | 1323–1324, 1327–1328, 1335–1339 | Closing, stopping, and no-command exit paths. | + +### Third pass — unit: `test/unit/coverage-gaps-flow.test.js` + +These 13 tests target the next five rows in the missed-by-both table. Like the +second pass, they are skipped against the frozen baseline. + +| Coverage area | Lines targeted | Tests | +| --- | --- | --- | +| `_nextHost` (8 lines) | 1534–1535, 1542–1545, 1551–1552 | Stopping/complete guards, no active record, and no pending hosts. | +| `_popTo` (7 lines) | 467–468, 472–474, 480–481 | No record, dropping a failed record with descendants, and no parent to restore. | +| `_mergeNestedText` (7 lines) | 1395–1396, 1398–1399, 1413, 1424–1425 | Missing stack/server, duplicate merge, stacked-host parent lookup, and no distinct parent. | +| `stop` (7 lines) | 1673–1674, 1683, 1690–1691, 1694–1695 | Clearing active/ancestor queues and the configured host when no record is active. | +| `_beginStopExit` (5 lines) | 1725–1726, 1731–1733 | Already-complete guard and deferred exit for an in-flight command. | + +### Final pass — unit: `test/unit/behavior-hardening.test.js` + +These five tests are behaviour tests, not coverage tests: they lock in failure +modes that matter even if the lines happen to be hit elsewhere. They are skipped +against the frozen baseline. + +| Test | Lines targeted | Why it matters | +| --- | --- | --- | +| marks circular references in redacted config dumps | `util.js` 138–139 | A cyclic host config must not crash a verbose dump. | +| preserves non-plain objects in redacted config dumps | `util.js` 132, 134–135 | Streams and buffers must survive redaction by identity. | +| ignores data received after close or after the active host changes | 875–876, 931–932 | Late data and stale idle timers must not process a command. | +| closes descendants before a failed record | 561–563 | An ancestor failure must not leave live descendants behind. | +| forces a close when the close timer fires | 1826, 1834–1837 | Shutdown fallback when a stream close stalls. | + +## Coverage after the follow-up tests + +Measured with the same Node and commands as the first review. Counts are shown +for the unit and live text reports respectively. The `Combined` row is the union +of hit lines from both LCOV reports (2874 of 2929 executable lines). Branch and +function denominators differ between an instrumented unit run and an +instrumented live run, so only a line figure is meaningful for the union. + +The live numbers are unchanged from the first pass; the second, third, and +final passes added only unit tests. + +| Suite | Target | Lines | Branches | Functions | +| --- | --- | --- | --- | --- | +| Unit (222 tests) | `lib/ssh2shell.js` | 96.95% | 90.71% | 100% | +| Unit (222 tests) | `lib/ssh2shell/defaults.js` | 97.96% | 96.97% | 100% | +| Unit (222 tests) | `lib/ssh2shell/util.js` | 97.67% | 89.66% | 100% | +| Unit (222 tests) | all files | 97.03% | 90.91% | 100% | +| Combined (unit ∪ live) | all files | **98.12%** | — | — | +| Live (30 tests) | `src/ssh2shell.js` | 79.47% | 58.64% | 87.07% | +| Live (30 tests) | `src/ssh2shell/defaults.js` | 97.96% | 50.00% | 100% | +| Live (30 tests) | `src/ssh2shell/util.js` | 83.14% | 68.09% | 100% | +| Live (30 tests) | all files | 80.30% | 59.43% | 88.46% | + +The targeted gaps closed: + +- First-pass unit tests hit lines 2107–2109, 2206–2207, 2209–2210, 488–489, + 494–495, and 499–505. Line coverage rose from 90.30% to 91.05% and branch + coverage from 80.87% to 82.30%. +- First-pass live tests hit the default timeout and TTY progress paths. Line + coverage rose from 76.68% to 79.47%, branch coverage from 57.01% to 58.64%, + and function coverage from 83.48% to 87.07%. +- Second-pass unit tests closed the five largest missed-by-both blocks: + `_openShell` (29 lines), `_connect` (23), `_bindConnection` (21), + `_previousHost` (16), and `_checkCommand` (9). Unit `ssh2shell.js` line + coverage rose from 91.05% to 94.85% and branch coverage from 82.30% to + 86.33%. +- Third-pass unit tests closed the next five rows: `_nextHost` (8 lines), + `_popTo` (7), `_mergeNestedText` (7), `stop` (7), and `_beginStopExit` (5). + Unit `ssh2shell.js` line coverage rose from 94.85% to about 96.1% and branch + coverage from 86.33% to about 90%. +- Final-pass unit tests covered the redaction safety branches and the stale + data, descendant-teardown, and forced-close paths. Unit `ssh2shell.js` line + coverage rose to 96.95%, `util.js` to 97.67%, and function coverage reached + 100% across all files. Branch figures vary slightly between runs; see the + variance note below. + +## Miss overlap — how the suites relate + +The useful comparison is not hit-set symmetry. It is which **missed** lines are +already covered by the other suite, and which lines remain missed by both. +Because `lib/ssh2shell.js` and `src/ssh2shell.js` are byte-identical builds, +line numbers are directly comparable. + +| File | Executable lines | Missed by unit | Missed by live | Missed by both | Live covers unit miss | Unit covers live miss | +| --- | --- | --- | --- | --- | --- | --- | +| `ssh2shell.js` | 2659 | 81 | 546 | 49 | 32 | 497 | +| `defaults.js` | 98 | 2 | 2 | 2 | 0 | 0 | +| `util.js` | 172 | 4 | 29 | 4 | 0 | 25 | +| all files | 2929 | 87 | 577 | 55 | 32 | 522 | + +What this means for test placement: + +- **32 unit misses are already covered by live**: `close` 1881–1896, + `_appendPartial` 624–630, `_removeListeners` 1970–1972 and 1979–1981, and + `_prepareGracefulClose` 1799 and 1810–1811. These are shutdown paths. Adding + unit copies would not improve combined coverage. +- **522 live misses are already covered by unit**, up from 371 before the + second pass, 472 before the third, and 506 before the final pass. The largest + groups are `_openShell` (73), `_loadDefaults` (56), `_connect` (45), + `_bindConnection` (25), module scope (24), and `_reportMissingParameters` + (23). Adding live copies of these branches would not improve combined + coverage. +- **55 lines are missed by both** — the headline residual figure, down from 206 + before the second pass, 105 before the third, and 71 before the final pass. + That is the residual target set, listed below. The combined hit-line union is + 2874 of 2929 lines (98.12%); the point of the split is to show where the + remaining lines sit, not to optimise that percentage. + +A note on variance: a few timer-driven unit tests are timing-sensitive, so +branch percentages move between runs. Across four repeated runs, line coverage +and every overlap figure were identical; only branch percentage varied +(90.56–90.71% for `ssh2shell.js`, 90.78–90.91% across all files). The numbers +above come from one representative run. + +### Missed-by-both lines, highest value first + +Line ranges are from `src/ssh2shell.js` and apply to the identical `lib/` build. +Method attribution is the same rough enclosing-method grouping described +earlier: nested callbacks are attributed to their enclosing method. + +The large blocks from the second and third passes are now closed, and the final +pass closed `_failContext`, `_forceClose`, half of `_onData`, and the redaction +branches in `util.js`. What remains is smaller and mostly defensive. Coverage +test work for this round is finished; no further tests are planned. + +| Method | Lines missed by both | Best place to target | +| --- | --- | --- | +| `_endPrimary`, `_prepareGracefulClose` | 4 each | **Unit**, only if a specific behaviour is at risk. | +| `_initiate` | 3: 1991–1992, 1997 | **Unit**: terminal-state guard. | +| other guards | 2 each across 18 methods and at module scope, plus `_onData` 875–876 | **Unit**, low priority. | +| `defaults.js` | 2: 43–44 | Low-value defensive branch. | +| `util.js` | 4: 44–45, 61–62 | Low-value defensive branches. | + +These are documented as residual risk, not as a queued task list. Adding tests +for them alone would assert guards and catch blocks without meaningful +confidence. + +## Reporting coverage with a pull request + +GitHub's native coverage reporting (public preview as of May 2026) wants a +Cobertura XML upload from CI via `actions/upload-code-coverage`. Node's built-in +reporter does not emit Cobertura, so that path needs a converter such as `c8` +with a Cobertura reporter. For this repository that is the wrong trade-off: the +live suite already runs in CI as a required check, but adding coverage +instrumentation to it creates timing risk, and coverage is diagnostic rather +than a gate. + +The preferred approach is to generate coverage locally and include the summary +with the PR: + +- Keep CI unchanged: unit checks in `ci.yml`, required live suite in `live.yml`, + and no coverage collection or coverage gate. +- Before a release PR, run the two local commands above (unit against `lib/`, + live against `src/`) with the LCOV reporters enabled. Use the reporter path + described here, not `NODE_V8_COVERAGE` on `npm run test:live:all`, which makes + timing-sensitive tests flaky. +- Derive the miss-overlap table and remaining-target list from the two LCOV + files. Keep the full table: it shows all four relationships between the + suites, not just the headline. +- Put the text coverage table, the full miss-overlap table, `missed by both` as + the residual-risk headline, the Node version, and the exact commands in the PR + description or a PR comment. `unit covers live miss` is the progress metric + while unit tests are still being added; once that work is done, `missed by + both` is the adequate summary number. Raw LCOV files are large and stay out of + the description unless a reviewer asks for them. +- Label the numbers informational. The real gates remain CI checks, the live + suite, and release-candidate review. + +This keeps live coverage evidence with the PR that proposes the change, avoids +a coverage dependency or Cobertura converter, and does not turn a timing- +sensitive local live run into a required check. The commands in this document +are the reproducible source of truth; no script has been added because the live +half cannot run on a generic CI runner, and no publishing-doc change is needed +because this is PR content, not a release step. diff --git a/test/live/bash_script.js b/test/live/bash_script.js index e96e376..60b8e9e 100644 --- a/test/live/bash_script.js +++ b/test/live/bash_script.js @@ -13,9 +13,7 @@ const host = { privateKey: readPrivateKey(), passPhrase: process.env.KEY_PASSPHRASE, }, - commands: [], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: [] }; host.commands = [ @@ -34,6 +32,8 @@ host.commands = [ const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/chaining.js b/test/live/chaining.js index 8d8f538..45a989f 100644 --- a/test/live/chaining.js +++ b/test/live/chaining.js @@ -17,9 +17,7 @@ const jump = { privateKey, passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname'] }; const bastion = { @@ -30,9 +28,7 @@ const bastion = { privateKey, passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname'] }; const target = { @@ -43,9 +39,7 @@ const target = { privateKey, passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname', 'uptime'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname', 'uptime'] }; jump.hosts = [bastion]; @@ -55,6 +49,8 @@ target.hosts = []; const SSH = new SSH2Shell(jump); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/close_from_handler.js b/test/live/close_from_handler.js index cb56dd6..de5f7b2 100644 --- a/test/live/close_from_handler.js +++ b/test/live/close_from_handler.js @@ -20,15 +20,15 @@ const host = { if (command.includes('close-test-first')) { SSH.close(); } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const SSH = new SSH2Shell(host); const ends = []; SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('end', () => { ends.push(Date.now()); }); diff --git a/test/live/command_timeout.js b/test/live/command_timeout.js index 35636a5..946886a 100644 --- a/test/live/command_timeout.js +++ b/test/live/command_timeout.js @@ -44,14 +44,14 @@ const host = { this.sshObj.sessionText += response; } ); - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('error', (err, type) => log(`${type}: ${err}`)); // To change timeout handling for every host, leave onCommandTimeout out of the diff --git a/test/live/default_command_timeout.js b/test/live/default_command_timeout.js new file mode 100644 index 0000000..7aef32d --- /dev/null +++ b/test/live/default_command_timeout.js @@ -0,0 +1,39 @@ +const dotenv = require('dotenv').config(); +const { logFile, log } = require('../utils/logging.js'); +logFile('default_command_timeout.js'); + +const SSH2Shell = require('../utils/module.js'); +const { readPrivateKey } = require('../utils/private_key.js'); + +// No host `onCommandTimeout` is supplied here, so the library's default +// handler must emit the `Command Timeout` error and close the run on its own. +// The command waits for input that never arrives; a short idle timeout keeps +// the test quick without depending on prompt detection. +const promptCommand = 'printf "Default timeout prompt: "; read answer'; + +const host = { + server: { + host: process.env.HOST, + port: process.env.PORT, + userName: process.env.USER_NAME, + privateKey: readPrivateKey(), + passPhrase: process.env.KEY_PASSPHRASE, + }, + commands: [promptCommand], + // Avoid `#` and `>` because prompt detection can trigger in the wrong place. + standardPrompt: '$', + idleTimeOut: 2000, +}; + +const SSH = new SSH2Shell(host); + +SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); +SSH.on('error', (err, type) => log(`${type}: ${err}`)); + +SSH.connect((sessionText) => { + const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; + log(text); + console.log(text); +}); diff --git a/test/live/fingerprint.js b/test/live/fingerprint.js index 4213e16..b4af3d4 100644 --- a/test/live/fingerprint.js +++ b/test/live/fingerprint.js @@ -27,14 +27,14 @@ const host = { return hashedKey.toLowerCase() === expectedHash.toLowerCase(); }, }, - commands: ['whoami'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['whoami'] }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/graceful_close.js b/test/live/graceful_close.js index 935e7b1..51e34fe 100644 --- a/test/live/graceful_close.js +++ b/test/live/graceful_close.js @@ -19,9 +19,7 @@ const jump = { privateKey, passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['echo jump-graceful-before'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['echo jump-graceful-before'] }; const nested = { @@ -40,9 +38,7 @@ const nested = { if (command.includes('nested-graceful-before')) { SSH.close({ graceful: true }); } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; jump.hosts = [nested]; @@ -52,6 +48,8 @@ const SSH = new SSH2Shell(jump); const ends = []; SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('end', () => { ends.push(Date.now()); }); diff --git a/test/live/hop_keyboard_interactive.js b/test/live/hop_keyboard_interactive.js index 7501e04..71f6308 100644 --- a/test/live/hop_keyboard_interactive.js +++ b/test/live/hop_keyboard_interactive.js @@ -26,9 +26,7 @@ const parent = { privateKey, passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname'] }; const child = { @@ -45,9 +43,7 @@ const child = { onKeyboardInteractive: function (name, instructions, instructionsLang, prompts, finish) { log(`hop-keyboard-interactive-handler:${this.sshObj.server.userName}`); finish([kbdPassword]); - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; parent.hosts = [child]; @@ -56,6 +52,8 @@ child.hosts = []; const SSH = new SSH2Shell(parent); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/host_faults.js b/test/live/host_faults.js index bdc72d4..769e63b 100644 --- a/test/live/host_faults.js +++ b/test/live/host_faults.js @@ -142,6 +142,8 @@ const SSH = new SSH2Shell([fault1, badPrimary, fault2]); const errors = []; const ends = []; SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('error', (err, type) => { const message = err && err.message ? err.message : String(err); errors.push(`${type || ''}:${message}`); diff --git a/test/live/host_traversal.js b/test/live/host_traversal.js index 59a5619..04fa547 100644 --- a/test/live/host_traversal.js +++ b/test/live/host_traversal.js @@ -32,13 +32,10 @@ function nestedServer(host, port, userName) { }; } -function host(label, server, hosts) { +function host(label, server) { return { server, - commands: [`echo traversal:${label}`], - hosts: hosts || [], - debug: process.env.DEBUG === 'true', - verbose: process.env.VERBOSE === 'true', + commands: [`echo traversal:${label}`] }; } @@ -184,10 +181,15 @@ const expectedOrder = [ const SSH = new SSH2Shell([primary1, primary2, primary3]); const ends = []; + SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); + SSH.on('error', (err, type) => { log(`error-event:${type || ''}:${err && err.message ? err.message : err}`); }); + SSH.on('end', (sessionText, host) => { ends.push(host && host.server ? host.server.host : 'unknown'); log(`end-event:${host && host.server ? host.server.host : 'unknown'}`); diff --git a/test/live/keyboard-interactive.js b/test/live/keyboard-interactive.js index 5a9a49d..f9d06da 100644 --- a/test/live/keyboard-interactive.js +++ b/test/live/keyboard-interactive.js @@ -23,14 +23,14 @@ const host = { password: kbdPassword, tryKeyboard: true, }, - commands: ['whoami'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['whoami'] }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('keyboard-interactive', function (name, instructions, instructionsLang, prompts, finish) { // This example assumes only the password is requested. diff --git a/test/live/lots_of_commands.js b/test/live/lots_of_commands.js index 5b16d37..840a4c9 100644 --- a/test/live/lots_of_commands.js +++ b/test/live/lots_of_commands.js @@ -23,14 +23,14 @@ const host = { privateKey: readPrivateKey(), passPhrase: process.env.KEY_PASSPHRASE, }, - commands, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('commandComplete', (command, response, sshObj) => { log(`${sshObj.server.host} $ ${command}`); log(response.trim()); diff --git a/test/live/multiple_primary_hosts.js b/test/live/multiple_primary_hosts.js index 1261517..896a526 100644 --- a/test/live/multiple_primary_hosts.js +++ b/test/live/multiple_primary_hosts.js @@ -13,9 +13,7 @@ const host1 = { privateKey: readPrivateKey(), passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname', 'uptime'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname', 'uptime'] }; const host2 = { @@ -26,14 +24,14 @@ const host2 = { privateKey: readPrivateKey(), passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname', 'uptime'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname', 'uptime'] }; const SSH = new SSH2Shell([host1, host2]); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((allSessionText) => { const text = `-----Callback session text:\n${allSessionText}\n-----Callback end`; diff --git a/test/live/notifications.js b/test/live/notifications.js index 8b45c43..873877f 100644 --- a/test/live/notifications.js +++ b/test/live/notifications.js @@ -20,14 +20,14 @@ const host = { // safe stand-ins for a live host. 'cd /tmp', 'pwd', - ], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + ] }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/pipe.js b/test/live/pipe.js index 3c0624b..7c10fcc 100644 --- a/test/live/pipe.js +++ b/test/live/pipe.js @@ -15,9 +15,7 @@ const host = { privateKey: readPrivateKey(), passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['echo host pipe'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['echo host pipe'] }; const SSH = new SSH2Shell(host); @@ -29,6 +27,8 @@ const firstLog = fs.createWriteStream(path.join(logDir, 'pipe-first.log')); const secondLog = fs.createWriteStream(path.join(logDir, 'pipe-second.log')); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.pipe(firstLog); SSH.pipe(secondLog); diff --git a/test/live/private_key.js b/test/live/private_key.js index 53e46b5..6ecc343 100644 --- a/test/live/private_key.js +++ b/test/live/private_key.js @@ -21,14 +21,14 @@ const host = { privateKey: fs.readFileSync(keyPath), passPhrase: process.env.KEY_PASSPHRASE, // omit if the key has no passphrase }, - commands: ['whoami'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['whoami'] }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/progress.js b/test/live/progress.js index 9da82ee..f3b0191 100644 --- a/test/live/progress.js +++ b/test/live/progress.js @@ -42,6 +42,8 @@ const host2 = makeHost( const SSH = new SSH2Shell([host1, host2]); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); if (!process.stderr.isTTY) { console.log( diff --git a/test/live/progress_tty.js b/test/live/progress_tty.js new file mode 100644 index 0000000..5d4be91 --- /dev/null +++ b/test/live/progress_tty.js @@ -0,0 +1,65 @@ +const dotenv = require('dotenv').config(); +const { logFile, log } = require('../utils/logging.js'); +logFile('progress_tty.js'); + +const SSH2Shell = require('../utils/module.js'); +const { readPrivateKey } = require('../utils/private_key.js'); + +// The normal runner pipes stderr, so progress is silently disabled by its TTY +// gate. Inject a TTY-like sink before connect() so the real heartbeat code runs +// without polluting the runner's captured output. Two primary hosts exercise +// the host-label branch of the indicator. +const makeHost = (host, user, marker) => ({ + server: { + host, + port: process.env.PORT || process.env.SERVER1_PORT, + userName: user, + privateKey: readPrivateKey(), + passPhrase: process.env.KEY_PASSPHRASE, + }, + commands: ['sleep 2', `echo ${marker}`], + // Debug and verbose suppress progress, so keep them off for this test. + debug: false, + verbose: false, +}); + +const host1 = makeHost( + process.env.SERVER1_HOST || process.env.HOST, + process.env.SERVER1_USER_NAME || process.env.USER_NAME, + 'progress-tty-first' +); +const host2 = makeHost( + process.env.SERVER2_HOST, + process.env.SERVER2_USER_NAME, + 'progress-tty-second' +); + +const SSH = new SSH2Shell([host1, host2]); + +SSH.debug = false; +SSH.verbose = false; + +const progressSink = { + isTTY: true, + output: '', + write(chunk) { + this.output += chunk; + return true; + }, +}; +SSH._progressStream = progressSink; + +SSH.on('msg', log); +SSH.on('error', (err, type) => log(`${type}: ${err}`)); + +SSH.connect((allSessionText) => { + const dots = (progressSink.output.match(/\./g) || []).length; + log(`progress-tty-output:${JSON.stringify(progressSink.output)}`); + log(`progress-tty-ticks:${dots > 0 ? 'ok' : 'missing'}`); + log(`progress-tty-labels:${progressSink.output.includes('[') ? 'ok' : 'missing'}`); + console.log(`progress-tty-ticks:${dots > 0 ? 'ok' : 'missing'}`); + + const text = `-----Callback session text:\n${allSessionText}\n-----Callback end`; + log(text); + console.log(text); +}); diff --git a/test/live/prompt_response.js b/test/live/prompt_response.js index 7ed3140..b3834c4 100644 --- a/test/live/prompt_response.js +++ b/test/live/prompt_response.js @@ -25,14 +25,14 @@ const host = { sshObj.answeredNano = true; stream.write('y\n'); } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); // To apply the same logic to every host, attach it to the instance instead: // SSH.on('commandProcessing', function (command, response, sshObj, stream) { diff --git a/test/live/simple.js b/test/live/simple.js index 646fc2f..b81e5ce 100644 --- a/test/live/simple.js +++ b/test/live/simple.js @@ -18,14 +18,14 @@ const host = { 'df -h', 'msg:Checking memory', 'free -m', - ], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + ] }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/stop_multiple_hosts.js b/test/live/stop_multiple_hosts.js index b979498..4c1a541 100644 --- a/test/live/stop_multiple_hosts.js +++ b/test/live/stop_multiple_hosts.js @@ -20,9 +20,7 @@ const host1 = { if (command.includes('stop-host-one')) { SSH.stop('command-failed'); } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const host2 = { @@ -33,15 +31,15 @@ const host2 = { privateKey: readPrivateKey(), passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['echo stop-host-two-marker'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['echo stop-host-two-marker'] }; const SSH = new SSH2Shell([host1, host2]); const ends = []; SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('end', () => { ends.push(Date.now()); }); diff --git a/test/live/stop_on_failure.js b/test/live/stop_on_failure.js index 5699f60..ac6c019 100644 --- a/test/live/stop_on_failure.js +++ b/test/live/stop_on_failure.js @@ -25,15 +25,15 @@ const host = { if (command.includes('stop-test-first')) { sshObj.abort = 'command-failed'; } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const SSH = new SSH2Shell(host); const ends = []; SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('end', () => { ends.push(Date.now()); }); diff --git a/test/live/sudo_abort.js b/test/live/sudo_abort.js index 02d3549..36cec5a 100644 --- a/test/live/sudo_abort.js +++ b/test/live/sudo_abort.js @@ -29,14 +29,14 @@ const host = { if (command.includes('sudo-abort-must-not-run')) { log('sudo-abort-follow-up-ran'); } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/sudo_no_pass.js b/test/live/sudo_no_pass.js index 82cc675..2ffc89f 100644 --- a/test/live/sudo_no_pass.js +++ b/test/live/sudo_no_pass.js @@ -23,14 +23,14 @@ const host = { 'sudo -n id -u', 'sudo -n hostname', 'sudo -n ls /root', - ], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + ] }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/sudo_rejected.js b/test/live/sudo_rejected.js index 095f72a..d563697 100644 --- a/test/live/sudo_rejected.js +++ b/test/live/sudo_rejected.js @@ -28,14 +28,14 @@ const host = { if (command.includes('sudo-rejected-continued')) { log(`sudo-failed:${sshObj.sudoFailed}`); } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/sudo_su.js b/test/live/sudo_su.js index d992cba..1aa6c97 100644 --- a/test/live/sudo_su.js +++ b/test/live/sudo_su.js @@ -33,14 +33,14 @@ const host = { sshObj.suPasswordSent = true; stream.write(`${sshObj.server.secondUserPassword}\n`); } - }, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + } }; const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/timeout.js b/test/live/timeout.js index 7b3c683..7c3cea8 100644 --- a/test/live/timeout.js +++ b/test/live/timeout.js @@ -31,21 +31,18 @@ const host = { standardPrompt: '$', idleTimeOut: 5000, FirstPass: false, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), onCommandTimeout: function (command, response, stream, connection) { - if (this.sshObj.debug) { - this.emit('msg', `${this.sshObj.server.host}: host.onCommandTimeout`); - } + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: host.onCommandTimeout` + ); // Answer the first prompt so the run reaches the final unhandled timeout. if (response.indexOf('(Y,n)') !== -1 && this.sshObj.FirstPass !== true) { - if (this.sshObj.debug) { - this.emit( - 'msg', - `${this.sshObj.server.host}: First prompt using correct input: Sending 'y' to the \`(y,n):\` prompt` - ); - } + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: First prompt using correct input: Sending 'y' to the \`(y,n):\` prompt` + ); this.sshObj.sessionText += response + this.sshObj.enter; this._buffer = ''; this.sshObj.FirstPass = true; @@ -53,16 +50,14 @@ const host = { return; } - if (this.sshObj.debug) { - this.emit( - 'msg', - `${this.sshObj.server.host}: Final timeout: All attempts completed` - ); - this.emit( - 'msg', - `${this.sshObj.server.host}: Timeout details:${this.sshObj.enter}Command: ${command} ${this.sshObj.enter}Response: ${response}` - ); - } + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: Final timeout: All attempts completed` + ); + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: Timeout details:${this.sshObj.enter}Command: ${command} ${this.sshObj.enter}Response: ${response}` + ); // No prompt matched, so record the response and close the connection. this.emit( @@ -75,9 +70,7 @@ const host = { this.close(); }, onEnd: function (sessionText, sshObj) { - if (this.sshObj.debug) { - this.emit('msg', `${sshObj.server.host}: host.onEnd`); - } + this.systemMsg('debug', `${sshObj.server.host}: host.onEnd`); this.emit( 'msg', `\nThis is the full session response:\n\n${this.sshObj.sessionText}\n` @@ -88,6 +81,8 @@ const host = { const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/timeout_retries.js b/test/live/timeout_retries.js index 3601508..758d073 100644 --- a/test/live/timeout_retries.js +++ b/test/live/timeout_retries.js @@ -35,24 +35,18 @@ const host = { standardPrompt: '$', idleTimeOut: 5000, commandTimeoutRetries: 1, - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), onCommandTimeout: function (command, response, stream, connection, details) { - if (this.sshObj.debug) { - this.emit( - 'msg', - `${this.sshObj.server.host}: host.onCommandTimeout attempt ${details.attempt}/${details.maxRetries} final=${details.final}` - ); - } + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: host.onCommandTimeout attempt ${details.attempt}/${details.maxRetries} final=${details.final}` + ); // Answer the first prompt while the library still has retries left. if (details.final === false && response.indexOf('(Y,n)') !== -1) { - if (this.sshObj.debug) { - this.emit( - 'msg', - `${this.sshObj.server.host}: First prompt using correct input: Sending 'y' to the \`(y,n):\` prompt` - ); - } + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: First prompt using correct input: Sending 'y' to the \`(y,n):\` prompt` + ); this.sshObj.sessionText += response + this.sshObj.enter; this._buffer = ''; stream.write('y' + this.sshObj.enter); @@ -68,16 +62,14 @@ const host = { return; } - if (this.sshObj.debug) { - this.emit( - 'msg', - `${this.sshObj.server.host}: Final timeout: All attempts completed` - ); - this.emit( - 'msg', - `${this.sshObj.server.host}: Timeout details:${this.sshObj.enter}Command: ${command} ${this.sshObj.enter}Response: ${response}` - ); - } + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: Final timeout: All attempts completed` + ); + this.systemMsg( + 'debug', + `${this.sshObj.server.host}: Timeout details:${this.sshObj.enter}Command: ${command} ${this.sshObj.enter}Response: ${response}` + ); // No prompt matched, so record the response and close the connection. this.emit( @@ -90,9 +82,7 @@ const host = { this.close(); }, onEnd: function (sessionText, sshObj) { - if (this.sshObj.debug) { - this.emit('msg', `${sshObj.server.host}: host.onEnd`); - } + this.systemMsg('debug', `${sshObj.server.host}: host.onEnd`); this.emit( 'msg', `\nThis is the full session response:\n\n${this.sshObj.sessionText}\n` @@ -103,6 +93,8 @@ const host = { const SSH = new SSH2Shell(host); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/live/transport_drop.js b/test/live/transport_drop.js index d719344..9e6028f 100644 --- a/test/live/transport_drop.js +++ b/test/live/transport_drop.js @@ -20,15 +20,15 @@ const host = { 'echo transport-drop-before', 'kill -9 $PPID', 'echo transport-drop-after', - ], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + ] }; const SSH = new SSH2Shell(host); const ends = []; SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('error', (err, type) => { log(`error-event:${type || ''}:${err && err.message ? err.message : err}`); }); diff --git a/test/live/tunnel.js b/test/live/tunnel.js index fa0b02c..845d9bf 100644 --- a/test/live/tunnel.js +++ b/test/live/tunnel.js @@ -17,9 +17,7 @@ const jump = { privateKey, passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname'] }; const target = { @@ -30,9 +28,7 @@ const target = { privateKey, passPhrase: process.env.KEY_PASSPHRASE, }, - commands: ['hostname', 'uptime'], - debug: (process.env.DEBUG === 'true'), - verbose: (process.env.VERBOSE === 'true'), + commands: ['hostname', 'uptime'] }; // Chain the hosts: jump -> target. Each hop closes its own connection after the @@ -43,6 +39,8 @@ jump.hosts = [target]; const SSH = new SSH2Shell(jump); SSH.on('msg', log); +SSH.debug = (process.env.DEBUG === 'true'); +SSH.verbose = (process.env.VERBOSE === 'true'); SSH.connect((sessionText) => { const text = `-----Callback session text:\n${sessionText}\n-----Callback end`; diff --git a/test/unit/behavior-hardening.test.js b/test/unit/behavior-hardening.test.js new file mode 100644 index 0000000..61603c8 --- /dev/null +++ b/test/unit/behavior-hardening.test.js @@ -0,0 +1,190 @@ +'use strict'; + +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); +const { EventEmitter } = require('node:events'); + +const { + installFakeSsh2, + isBaseline, + loadSSH2Shell, + createHost, +} = require('./helpers/harness'); +const { redactCredentials } = require('../../lib/ssh2shell/util.js'); + +installFakeSsh2(); +const SSH2Shell = loadSSH2Shell(); + +// These tests cover current-only safety behaviour. The frozen baseline has +// neither the record helpers nor the redaction utility. +const newOnly = isBaseline() ? it.skip : it; + +function make(overrides = {}) { + const host = createHost(overrides); + const ssh = new SSH2Shell(host); + ssh.sshObj = host; + ssh._loadDefaults(); + return { ssh, host }; +} + +describe('behaviour hardening', () => { + newOnly('marks circular references in redacted config dumps', () => { + const host = createHost({ + verbose: true, + server: { host: 'circle.test', password: 'secret' }, + }); + host.server.self = host; + + const copy = redactCredentials(host); + + assert.equal(copy.server.self, '[Circular]'); + assert.equal(copy.server.password, '[REDACTED]'); + assert.equal(copy.server.host, 'circle.test'); + }); + + newOnly('preserves non-plain objects in redacted config dumps', () => { + const socket = new EventEmitter(); + const config = { + server: { host: 'objects.test', password: 'secret' }, + socket, + data: Buffer.from('raw'), + nested: { value: 1 }, + }; + + const copy = redactCredentials(config); + + assert.equal(copy.socket, socket); + assert.equal(copy.data, config.data); + assert.notEqual(copy.nested, config.nested); + assert.deepEqual(copy.nested, { value: 1 }); + assert.equal(copy.server.password, '[REDACTED]'); + }); + + newOnly('ignores data received after close or after the active host changes', () => { + const originalSetTimeout = global.setTimeout; + const timers = []; + global.setTimeout = (callback) => { + timers.push(callback); + return { unref() {} }; + }; + + try { + const { ssh } = make(); + const first = ssh._pushContext( + createHost({ server: { host: 'first.test' } }), + null + ); + ssh.command = ''; + ssh._onData('first data'); + assert.equal(timers.length, 1); + + first.closed = true; + let processed = 0; + ssh._scheduleIdleTimeout = () => { + processed += 1; + }; + timers[0](); + assert.equal(processed, 0); + assert.equal(ssh._buffer, 'first data'); + + const { ssh: secondSsh } = make(); + const second = secondSsh._pushContext( + createHost({ server: { host: 'second.test' } }), + null + ); + const secondTimers = []; + const savedSetTimeout = global.setTimeout; + global.setTimeout = (callback) => { + secondTimers.push(callback); + return { unref() {} }; + }; + secondSsh.command = ''; + secondSsh._onData('second data'); + global.setTimeout = savedSetTimeout; + secondSsh._pushContext( + createHost({ server: { host: 'other.test' } }), + null + ); + let secondProcessed = 0; + secondSsh._scheduleIdleTimeout = () => { + secondProcessed += 1; + }; + secondTimers[0](); + assert.equal(secondProcessed, 0); + assert.equal(secondSsh._buffer, 'second data'); + assert.ok(second); + } finally { + global.setTimeout = originalSetTimeout; + } + }); + + newOnly('closes descendants before a failed record', () => { + const { ssh, host } = make(); + const context = ssh._pushContext(host, null); + const middle = ssh._pushContext( + createHost({ server: { host: 'middle.test' } }), + context + ); + const deepest = ssh._pushContext( + createHost({ server: { host: 'deepest.test' } }), + middle + ); + ssh._connections = [context, middle]; + ssh._active = deepest; + context.isPrimary = false; + + const closed = []; + ssh._closeContext = (record, reason) => { + closed.push([record.host.server.host, reason]); + }; + ssh._popTo = () => 'popped'; + ssh._runExit = () => 'exit'; + + assert.equal(ssh._failContext(context, new Error('boom'), 'failure'), 'exit'); + assert.equal(context.failing, true); + assert.deepEqual(closed, [ + ['deepest.test', 'ancestor-failed'], + ['middle.test', 'ancestor-failed'], + ['example.test', 'failure'], + ]); + + closed.length = 0; + ssh._failContext(context, new Error('again'), 'duplicate'); + assert.deepEqual(closed, []); + }); + + newOnly('forces a close when the close timer fires', () => { + const { ssh } = make(); + const originalSetTimeout = global.setTimeout; + const originalClearTimeout = global.clearTimeout; + let timerCallback = null; + + global.setTimeout = (callback) => { + timerCallback = callback; + return { unref() {} }; + }; + global.clearTimeout = () => {}; + + try { + ssh.idleTime = 100; + ssh._armCloseTimer(); + assert.equal(typeof timerCallback, 'function'); + + let closes = 0; + ssh._closeStreamNow = () => { + closes += 1; + return 'closed'; + }; + + timerCallback(); + + assert.equal(closes, 1); + assert.equal(ssh._closeTimer, null); + assert.equal(ssh._forceClose(), 'closed'); + assert.equal(closes, 2); + } finally { + global.setTimeout = originalSetTimeout; + global.clearTimeout = originalClearTimeout; + } + }); +}); diff --git a/test/unit/coverage-gaps-flow.test.js b/test/unit/coverage-gaps-flow.test.js new file mode 100644 index 0000000..810cde1 --- /dev/null +++ b/test/unit/coverage-gaps-flow.test.js @@ -0,0 +1,230 @@ +'use strict'; + +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); + +const { + installFakeSsh2, + isBaseline, + loadSSH2Shell, + createHost, +} = require('./helpers/harness'); +const { FakeStream } = require('./helpers/fake-ssh2'); + +installFakeSsh2(); +const SSH2Shell = loadSSH2Shell(); + +// These tests drive host-traversal and shutdown guards that only exist in the +// current record-stack implementation. +const newOnly = isBaseline() ? it.skip : it; + +function make(overrides = {}) { + const host = createHost(overrides); + const ssh = new SSH2Shell(host); + ssh.sshObj = host; + ssh._loadDefaults(); + ssh._stream = new FakeStream(); + return { ssh, host }; +} + +describe('coverage gaps: host traversal and shutdown', () => { + newOnly('returns early from _nextHost when stopping or complete', () => { + const { ssh } = make(); + let finals = 0; + let exits = 0; + ssh._callFinalCallback = () => { + finals += 1; + return 'final'; + }; + ssh._runExit = () => { + exits += 1; + return 'exit'; + }; + + ssh._stopping = true; + assert.equal(ssh._nextHost(), undefined); + + ssh._stopping = false; + ssh._runComplete = true; + assert.equal(ssh._nextHost(), undefined); + + assert.equal(finals, 0); + assert.equal(exits, 0); + }); + + newOnly('finalizes directly when _nextHost has no active record', () => { + const { ssh } = make(); + ssh._active = null; + ssh._callFinalCallback = () => 'final'; + + assert.equal(ssh._nextHost(), 'final'); + }); + + newOnly('exits _nextHost when there are no pending hosts', () => { + const { ssh, host } = make(); + const record = ssh._pushContext(host, null); + record.pendingHosts = []; + ssh._runExit = () => 'exit'; + + assert.equal(ssh._nextHost(), 'exit'); + }); + + newOnly('returns null from _popTo when no record is supplied', () => { + const { ssh } = make(); + assert.equal(ssh._popTo(null), null); + }); + + newOnly('drops a failed record and its descendants from the stack', () => { + const { ssh } = make(); + const root = ssh._pushContext( + createHost({ server: { host: 'root.test' } }), + null + ); + const middle = ssh._pushContext( + createHost({ server: { host: 'middle.test' } }), + root + ); + const failed = ssh._pushContext( + createHost({ server: { host: 'failed.test' } }), + middle + ); + ssh._pushContext(createHost({ server: { host: 'child.test' } }), failed); + + assert.equal(ssh._popTo(failed), middle); + assert.deepEqual(ssh._connections, [root]); + assert.equal(ssh._active, middle); + assert.equal(ssh.sshObj, middle.host); + }); + + newOnly('clears the active record when _popTo has no parent', () => { + const { ssh, host } = make(); + const record = ssh._pushContext(host, null); + ssh._connections = []; + + assert.equal(ssh._popTo(record), null); + assert.equal(ssh._active, null); + }); + + newOnly('rejects a nested merge without a stack or server', () => { + const { ssh, host } = make(); + ssh._connections = []; + + assert.equal(ssh._mergeNestedText(host), false); + assert.equal(ssh._mergeNestedText({ commands: [] }), false); + }); + + newOnly('merges a stacked host into its parent exactly once', () => { + const { ssh } = make(); + const parentHost = createHost({ server: { host: 'parent.test' } }); + parentHost.sessionText = ''; + const childHost = createHost({ + server: { host: 'child.test' }, + sessionText: 'child output', + }); + + const parent = ssh._pushContext(parentHost, null); + const child = ssh._pushContext(childHost, parent); + ssh._connections.push(child); + ssh._active = null; + + assert.equal(ssh._mergeNestedText(childHost), true); + assert.equal(parentHost.sessionText, '\nchild.test: child output'); + assert.equal(ssh._mergeNestedText(childHost), false); + }); + + newOnly('rejects a nested merge when there is no distinct parent', () => { + const { ssh, host } = make(); + const record = ssh._pushContext(host, null); + ssh._connections = [record]; + ssh._active = null; + + assert.equal(ssh._mergeNestedText(host), false); + }); + + newOnly('clears active and ancestor queues when stopping', () => { + const { ssh } = make(); + const activeHost = createHost({ + server: { host: 'active.test' }, + commands: ['echo active'], + }); + const ancestorHost = createHost({ + server: { host: 'ancestor.test' }, + commands: ['echo ancestor'], + }); + + const active = ssh._pushContext(activeHost, null); + active.stream = new FakeStream(); + ssh._stream = active.stream; + active.pendingHosts = [createHost({ server: { host: 'next.test' } })]; + + const ancestor = { + host: ancestorHost, + pendingHosts: ['queued'], + }; + ssh._connections = [ancestor]; + + let exits = 0; + ssh._beginStopExit = () => { + exits += 1; + }; + + assert.equal(ssh.stop('test'), ssh); + assert.deepEqual(activeHost.commands, []); + assert.deepEqual(active.pendingHosts, []); + assert.deepEqual(ancestorHost.commands, []); + assert.deepEqual(ancestor.pendingHosts, []); + assert.equal(ssh._hosts.length, 0); + assert.equal(exits, 1); + }); + + newOnly('clears the configured host when stop has no active record', () => { + const { ssh, host } = make(); + ssh._active = null; + ssh._connections = []; + + let exits = 0; + ssh._beginStopExit = () => { + exits += 1; + }; + + assert.equal(ssh.stop('test'), ssh); + assert.deepEqual(host.commands, []); + assert.equal(exits, 1); + }); + + newOnly('does not finish stop when the run is already complete', () => { + const { ssh } = make(); + ssh._runComplete = true; + + let finishes = 0; + ssh._finishStop = () => { + finishes += 1; + }; + + ssh._beginStopExit(); + assert.equal(finishes, 0); + }); + + newOnly('defers finish stop while a command is in flight', () => { + const { ssh } = make(); + ssh._stream = new FakeStream(); + ssh._commandInFlight = true; + + let arms = 0; + let finishes = 0; + ssh._armStopTimer = () => { + arms += 1; + }; + ssh._finishStop = () => { + finishes += 1; + }; + + ssh._beginStopExit(); + assert.equal(arms, 1); + assert.equal(finishes, 0); + + ssh._stream = {}; + ssh._beginStopExit(); + assert.equal(finishes, 1); + }); +}); diff --git a/test/unit/coverage-gaps-state.test.js b/test/unit/coverage-gaps-state.test.js new file mode 100644 index 0000000..0a6a187 --- /dev/null +++ b/test/unit/coverage-gaps-state.test.js @@ -0,0 +1,308 @@ +'use strict'; + +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); +const { EventEmitter } = require('node:events'); + +const { + installFakeSsh2, + isBaseline, + loadSSH2Shell, + createHost, +} = require('./helpers/harness'); +const { FakeStream } = require('./helpers/fake-ssh2'); + +installFakeSsh2(); +const SSH2Shell = loadSSH2Shell(); + +// These tests drive record/transport guard branches that only exist in the +// current forwardOut implementation. +const newOnly = isBaseline() ? it.skip : it; + +function make(overrides = {}) { + const host = createHost(overrides); + const ssh = new SSH2Shell(host); + ssh.sshObj = host; + ssh._loadDefaults(); + ssh._stream = new FakeStream(); + return { ssh, host }; +} + +function shellConnection(stream) { + return { + shell(window, callback) { + if (typeof window === 'function') callback = window; + callback(null, stream); + }, + }; +} + +describe('coverage gaps: state and transport guards', () => { + newOnly('closes a shell stream that arrives after its context is closed', () => { + const { ssh, host } = make(); + const context = ssh._pushContext(host, null); + context.closed = true; + + const stream = new FakeStream(); + context.connection = shellConnection(stream); + let closeAttempts = 0; + const close = stream.close.bind(stream); + stream.close = () => { + closeAttempts += 1; + close(); + }; + + ssh._openShell(context); + + assert.equal(closeAttempts, 1); + }); + + newOnly('ignores closed stream errors and contains hop stream errors', () => { + const { ssh, host } = make(); + const context = ssh._pushContext(host, null); + context.isPrimary = false; + + const failures = []; + ssh._hopFailed = (failedContext, error) => failures.push(error.message); + + const stream = new FakeStream(); + context.connection = shellConnection(stream); + ssh._openShell(context); + + context.closed = true; + stream.emit('error', new Error('stale stream error')); + assert.deepEqual(failures, []); + + context.closed = false; + stream.emit('error', new Error('hop stream error')); + assert.deepEqual(failures, ['hop stream error']); + }); + + newOnly('ignores stderr data from a stream that is no longer active', () => { + const { ssh, host } = make(); + const context = ssh._pushContext(host, null); + const stream = new FakeStream(); + context.connection = shellConnection(stream); + ssh._openShell(context); + + const captured = []; + ssh._captureStderr = (data) => captured.push(data); + ssh._active = null; + + stream.stderr.emit('data', 'ignored stderr'); + + assert.deepEqual(captured, []); + }); + + newOnly('reports a throwing data listener for a primary host', () => { + const { ssh, host } = make(); + const context = ssh._pushContext(host, null); + const errors = []; + ssh.on('error', (...args) => errors.push(args)); + + const stream = new FakeStream(); + context.connection = shellConnection(stream); + ssh._openShell(context); + ssh.prependListener('data', () => { + throw new Error('listener boom'); + }); + + stream.emit('data', 'command output'); + + const args = errors.find((entry) => entry[1] === 'Stream.read error'); + assert.ok(args); + assert.equal(args[0].level, 'Data handling'); + }); + + newOnly('contains a throwing data listener on a hop', () => { + const { ssh, host } = make(); + const context = ssh._pushContext(host, null); + context.isPrimary = false; + + const failures = []; + ssh._hopFailed = (failedContext, error) => failures.push(error.message); + + const stream = new FakeStream(); + context.connection = shellConnection(stream); + ssh._openShell(context); + ssh.prependListener('data', () => { + throw new Error('listener boom'); + }); + + stream.emit('data', 'hop output'); + + assert.equal(failures.length, 1); + assert.match(failures[0], /listener boom/); + }); + + newOnly('returns the placeholder stream when a run is already stopping', () => { + const { ssh } = make(); + ssh._stopping = true; + assert.equal(ssh._connect(), ssh._stream); + }); + + newOnly('contains a hop that has no parent connection', () => { + const { ssh } = make(); + ssh.sshObj = createHost({ server: { host: 'hop.test' } }); + const parent = ssh._pushContext(createHost(), null); + parent.connection = null; + + const failures = []; + ssh._hopFailed = (failedContext, error) => failures.push(error.message); + + ssh._connect(parent); + + assert.deepEqual(failures, ['No parent connection for host hop']); + }); + + newOnly('closes a channel safely when a forwardOut context is already closed', () => { + const { ssh } = make(); + ssh.sshObj = createHost({ server: { host: 'hop.test' } }); + + let completeForwardOut; + const parent = ssh._pushContext(createHost(), null); + parent.connection = { + forwardOut(srcIP, srcPort, dstIP, dstPort, callback) { + completeForwardOut = callback; + }, + }; + + ssh._connect(parent); + const child = ssh._activeContext(); + child.closed = true; + + let closeAttempts = 0; + completeForwardOut(null, { + close() { + closeAttempts += 1; + throw new Error('channel already gone'); + }, + }); + + assert.equal(closeAttempts, 1); + }); + + newOnly('fails the child context when stop happens during forwardOut', () => { + const { ssh } = make(); + ssh.sshObj = createHost({ server: { host: 'hop.test' } }); + + let completeForwardOut; + const parent = ssh._pushContext(createHost(), null); + parent.connection = { + forwardOut(srcIP, srcPort, dstIP, dstPort, callback) { + completeForwardOut = callback; + }, + }; + + ssh._connect(parent); + const child = ssh._activeContext(); + ssh._stopping = true; + + let failure = null; + ssh._failContext = (context, error, reason) => { + failure = { context, error, reason }; + return 'failed'; + }; + + let closeAttempts = 0; + const result = completeForwardOut(null, { + close() { + closeAttempts += 1; + throw new Error('channel already gone'); + }, + }); + + assert.equal(result, 'failed'); + assert.equal(closeAttempts, 1); + assert.equal(failure.context, child); + assert.equal(failure.reason, 'cancelled'); + }); + + newOnly('ignores stale connection events and contains hop failures', () => { + const { ssh, host } = make(); + const context = ssh._pushContext(host, null); + context.isPrimary = false; + + const connection = new EventEmitter(); + context.connection = connection; + const failures = []; + ssh._hopFailed = (failedContext, error) => failures.push(error.message); + ssh._appendPartial = () => {}; + ssh._bindConnection(context); + + context.closed = true; + connection.emit('keyboard-interactive', 'sshd', '', 'en', [], () => {}); + connection.emit('connect'); + connection.emit('ready'); + connection.emit('error', new Error('stale connection error')); + assert.deepEqual(failures, []); + + context.closed = false; + ssh._active = null; + connection.emit('keyboard-interactive', 'sshd', '', 'en', [], () => {}); + ssh._active = context; + + connection.emit('error', new Error('hop connection error')); + ssh._closing = true; + connection.emit('close', false); + ssh._closing = false; + connection.emit('close', false); + + assert.deepEqual(failures, [ + 'hop connection error', + 'Connection closed', + ]); + }); + + newOnly('restores a manually built parent stack in previousHost', () => { + const { ssh } = make(); + ssh._stopping = true; + assert.equal(ssh._previousHost(), undefined); + ssh._stopping = false; + + const parentHost = createHost({ server: { host: 'parent.test' } }); + const parent = ssh._pushContext(parentHost, null); + parent.command = 'parent command'; + parent.buffer = 'parent buffer'; + + ssh._active = null; + ssh._connections = [parent]; + ssh.sshObj = createHost({ server: { host: 'child.test' } }); + + const finalized = []; + let removed = 0; + ssh._finalizeHost = (host, reason) => finalized.push([host, reason]); + ssh._removeListeners = () => { + removed += 1; + }; + ssh._runExit = () => 'exit'; + + assert.equal(ssh._previousHost(), 'exit'); + assert.equal(ssh._active, parent); + assert.equal(ssh.sshObj, parentHost); + assert.equal(finalized.length, 1); + assert.equal(removed, 1); + }); + + newOnly('exits checkCommand on closing, stopping, and empty command states', () => { + const { ssh } = make(); + let exits = 0; + ssh._runExit = () => { + exits += 1; + return 'exit'; + }; + + ssh._closing = true; + assert.equal(ssh._checkCommand(), undefined); + + ssh._closing = false; + ssh._stopping = true; + assert.equal(ssh._checkCommand(), 'exit'); + + ssh._stopping = false; + ssh.command = ''; + assert.equal(ssh._checkCommand(), 'exit'); + + assert.equal(exits, 2); + }); +}); diff --git a/test/unit/coverage-gaps.test.js b/test/unit/coverage-gaps.test.js new file mode 100644 index 0000000..a381e60 --- /dev/null +++ b/test/unit/coverage-gaps.test.js @@ -0,0 +1,98 @@ +'use strict'; + +const { describe, it } = require('node:test'); +const assert = require('node:assert/strict'); + +const { + installFakeSsh2, + isBaseline, + loadSSH2Shell, + createHost, +} = require('./helpers/harness'); +const { FakeStream } = require('./helpers/fake-ssh2'); + +installFakeSsh2(); +const SSH2Shell = loadSSH2Shell(); + +// These tests target internals of the current record-stack implementation. The +// frozen baseline has no equivalent record shape, so skip it there. +const newOnly = isBaseline() ? it.skip : it; + +function make(overrides = {}) { + const host = createHost(overrides); + const ssh = new SSH2Shell(host); + ssh.sshObj = host; + ssh._loadDefaults(); + ssh._stream = new FakeStream(); + return { ssh, host }; +} + +describe('coverage gaps', () => { + newOnly('binds host stderrData and end handlers', () => { + const seen = { stderrData: [], end: [] }; + const { ssh, host } = make({ + onStderrData: function (data) { + seen.stderrData.push([this, data]); + }, + onEnd: function (sessionText, sshObj) { + seen.end.push([this, sessionText, sshObj]); + }, + }); + + assert.ok(ssh.listeners('stderrData').includes(host.onStderrData)); + assert.ok(ssh.listeners('end').includes(host.onEnd)); + + ssh.emit('stderrData', 'warning'); + ssh.emit('end', 'session text', host); + + assert.deepEqual(seen.stderrData, [[ssh, 'warning']]); + assert.deepEqual(seen.end, [[ssh, 'session text', host]]); + }); + + newOnly('replaces a previous host msg handler when defaults reload', () => { + const firstMessages = []; + const secondMessages = []; + const first = (message) => firstMessages.push(message); + const second = (message) => secondMessages.push(message); + + const { ssh, host } = make({ onMsg: first }); + assert.ok(ssh.listeners('msg').includes(first)); + + // Reloading defaults for the same record must detach the handler bound by + // the previous host config before installing the replacement. + host.onMsg = second; + ssh._loadDefaults(); + + const msgListeners = ssh.listeners('msg'); + assert.ok(!msgListeners.includes(first)); + assert.ok(msgListeners.includes(second)); + + ssh.emit('msg', 'hello'); + assert.deepEqual(firstMessages, []); + assert.deepEqual(secondMessages, ['hello']); + }); + + newOnly('collects active and nested descendants, excluding closed records', () => { + const { ssh } = make(); + const root = { host: createHost(), closed: false }; + const middle = { host: createHost(), closed: false }; + const closed = { host: createHost(), closed: true }; + const deepest = { host: createHost(), closed: false }; + + assert.deepEqual(ssh._descendantsOf(null), []); + + // The active record is not on the ancestors stack: it is the deepest + // record, with its ancestors (including a closed one) behind it. + ssh._connections = [root, middle, closed]; + ssh._active = deepest; + assert.deepEqual(ssh._descendantsOf(root), [deepest, middle]); + + deepest.closed = true; + assert.deepEqual(ssh._descendantsOf(root), [middle]); + deepest.closed = false; + + // The active record is also excluded when it is the context itself. + ssh._active = root; + assert.deepEqual(ssh._descendantsOf(root), [middle]); + }); +}); diff --git a/test/unit/credentials.test.js b/test/unit/credentials.test.js index 3f80dbb..37199ac 100644 --- a/test/unit/credentials.test.js +++ b/test/unit/credentials.test.js @@ -9,6 +9,7 @@ const { loadSSH2Shell, createHost, processSudo, + systemMsg, } = require('./helpers/harness'); const { FakeStream } = require('./helpers/fake-ssh2'); @@ -103,7 +104,7 @@ describe('credential logging', () => { }); messages.length = 0; - ssh._systemMsg('verbose', `key: ${privateKey}`); + systemMsg(ssh, 'verbose', `key: ${privateKey}`); const text = textOf(messages); assert.ok(text.includes('[REDACTED]')); diff --git a/test/unit/helpers/harness.js b/test/unit/helpers/harness.js index 5f80576..357480f 100644 --- a/test/unit/helpers/harness.js +++ b/test/unit/helpers/harness.js @@ -59,6 +59,14 @@ function loadSSH2Shell() { return require(modulePath); } +// The public helper is `systemMsg`; the frozen baseline only has `_systemMsg`. +// Tests that emit debug/verbose messages must work against both targets. +function systemMsg(ssh, type, message, object = null) { + return isBaseline() + ? ssh._systemMsg(type, message, object) + : ssh.systemMsg(type, message, object); +} + function createHost(overrides = {}) { const server = Object.assign( { @@ -196,6 +204,7 @@ module.exports = { loadSSH2Shell, once, processSudo, + systemMsg, waitFor, waitForStream, }; diff --git a/test/unit/l5-behavior.test.js b/test/unit/l5-behavior.test.js index b80740e..2add57f 100644 --- a/test/unit/l5-behavior.test.js +++ b/test/unit/l5-behavior.test.js @@ -9,6 +9,7 @@ const { loadSSH2Shell, createHost, injectSsh2Client, + systemMsg, } = require('./helpers/harness'); const { FakeClient, FakeStream } = require('./helpers/fake-ssh2'); @@ -99,7 +100,7 @@ describe('L5 listener lifecycle', () => { ssh._removeListeners(); assert.equal(msgListenerCount(ssh), 1); - ssh._systemMsg('debug', 'after remove'); + systemMsg(ssh,'debug', 'after remove'); assert.ok( messages.some( (message) => @@ -139,7 +140,7 @@ describe('L5 listener lifecycle', () => { ssh.sshObj = createHost({ msg: undefined }); ssh._loadDefaults(); ssh.debug = true; - ssh._systemMsg('debug', 'next host'); + systemMsg(ssh,'debug', 'next host'); assert.ok( messages.some( @@ -335,20 +336,105 @@ describe('L5 debug and verbose gating', () => { ssh.debug = false; ssh.verbose = false; - ssh._systemMsg('debug', 'hidden debug'); - ssh._systemMsg('verbose', 'hidden verbose'); + systemMsg(ssh,'debug', 'hidden debug'); + systemMsg(ssh,'verbose', 'hidden verbose'); assert.deepEqual(messages, []); ssh.debug = true; - ssh._systemMsg('debug', 'shown debug'); + systemMsg(ssh,'debug', 'shown debug'); assert.ok(messages.some((message) => message.includes('shown debug'))); messages.length = 0; ssh.debug = false; ssh.verbose = true; - ssh._systemMsg('verbose', 'shown verbose'); + systemMsg(ssh,'verbose', 'shown verbose'); assert.ok(messages.some((message) => message.includes('shown verbose'))); }); + + it('uses host flags when the instance has no override', () => { + if (isBaseline()) return; + + const messages = []; + const { ssh } = make({ + debug: true, + verbose: true, + msg: (message) => messages.push(String(message)), + }); + messages.length = 0; + + assert.equal(ssh.debug, true); + assert.equal(ssh.verbose, true); + + systemMsg(ssh,'debug', 'host debug'); + systemMsg(ssh,'verbose', 'host verbose'); + assert.ok(messages.some((message) => message.includes('host debug'))); + assert.ok(messages.some((message) => message.includes('host verbose'))); + }); + + it('lets an instance true override host flags that are off', () => { + if (isBaseline()) return; + + const messages = []; + const { ssh } = make({ + debug: false, + verbose: false, + msg: (message) => messages.push(String(message)), + }); + messages.length = 0; + + ssh.debug = true; + ssh.verbose = true; + // The override must survive a host reload, not just affect the getter. + ssh._loadDefaults(); + messages.length = 0; + + assert.equal(ssh.debug, true); + assert.equal(ssh.verbose, true); + + systemMsg(ssh,'debug', 'forced debug'); + systemMsg(ssh,'verbose', 'forced verbose'); + assert.ok(messages.some((message) => message.includes('forced debug'))); + assert.ok(messages.some((message) => message.includes('forced verbose'))); + }); + + it('lets an instance false override host flags that are on', () => { + if (isBaseline()) return; + + const messages = []; + const { ssh } = make({ + debug: true, + verbose: true, + msg: (message) => messages.push(String(message)), + }); + messages.length = 0; + + ssh.debug = false; + ssh.verbose = false; + ssh._loadDefaults(); + messages.length = 0; + + assert.equal(ssh.debug, false); + assert.equal(ssh.verbose, false); + + systemMsg(ssh,'debug', 'suppressed debug'); + systemMsg(ssh,'verbose', 'suppressed verbose'); + assert.deepEqual(messages, []); + }); + + it('applies an instance change immediately without a host reload', () => { + if (isBaseline()) return; + + const messages = []; + const { ssh } = make({ + debug: false, + msg: (message) => messages.push(String(message)), + }); + messages.length = 0; + + ssh.debug = true; + systemMsg(ssh,'debug', 'immediate debug'); + assert.ok(messages.some((message) => message.includes('immediate debug'))); + }); }); describe('host prefix in messages', () => { @@ -365,7 +451,7 @@ describe('host prefix in messages', () => { }); messages.length = 0; - ssh._systemMsg('debug', 'single host'); + systemMsg(ssh,'debug', 'single host'); assert.deepEqual(messages, ['single host']); }); @@ -384,7 +470,7 @@ describe('host prefix in messages', () => { ssh._loadDefaults(); messages.length = 0; - ssh._systemMsg('debug', 'multiple hosts'); + systemMsg(ssh,'debug', 'multiple hosts'); assert.deepEqual(messages, ['first.test: multiple hosts']); }); @@ -401,7 +487,7 @@ describe('host prefix in messages', () => { }); messages.length = 0; - ssh._systemMsg('debug', 'nested hosts'); + systemMsg(ssh,'debug', 'nested hosts'); assert.deepEqual(messages, ['primary.test: nested hosts']); });