Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/rulesets/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ gh api --method POST repos/cmp-202/ssh2shell/rulesets \
`.github/workflows/ci.yml`; `Live suite` comes from
`.github/workflows/live.yml`. Renaming a job means updating
`branch-master.json` as well.
- Fork pull requests skip the `Live suite` job because its setup and stop
scripts run as root. GitHub reports a condition-skipped required check as
satisfied, so a fork PR can merge without live coverage; same-repo PRs,
pushes, schedules, and `workflow_call` still run it.
- `branch-master.json` has an empty bypass list, so direct pushes to `master`
are blocked for everyone, including the owner. Changes go through a pull
request. No approvals are required, but the checks must pass and review
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ jobs:
env:
EXPECTED_REF: ${{ inputs.ref || github.ref_name }}
run: |
expected="$EXPECTED_REF"
# A workflow_dispatch input may be a full ref (`refs/tags/v4.0.3`)
# while a tag push yields `v4.0.3`; compare the short form in both.
expected="${EXPECTED_REF#refs/tags/}"
actual="v$(node -p "require('./package.json').version")"
if [ "$expected" != "$actual" ]; then
echo "Ref $expected does not match package version $actual" >&2
Expand Down
23 changes: 21 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,25 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases.

## [Unreleased]

### Fixed

- A primary host with no `server`, or a server with neither `host` nor
`hostname`, now reports `Parameters`, finalizes that host, and continues to
the next primary instead of leaving the run unfinished. It no longer silently
targets `localhost:22`.
- Host labels, nested session text, and hop forwarding now use `hostname` when
`host` is absent.
- `privateKey` is included in string redaction as well as object dumps, so
verbose and debug messages cannot echo key material.
- `abortOnSudoFailure` sends a single Ctrl-C instead of two.
- A `workflow_dispatch` ref such as `refs/tags/vX.Y.Z` now passes the publish
version check.

### Development

- Documented that fork pull requests skip the `Live suite` job and that GitHub
treats the skipped required check as satisfied.

## [4.0.3] - 2026-11-18

### Fixed
Expand All @@ -20,8 +39,8 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases.
- `pty: false` now disables the pseudo-terminal. It was previously ignored
because `ssh2` takes the PTY request from the first `shell()` argument.
- `stop()` and `close({ graceful: true })` no longer empty the caller's nested
`hosts` arrays; the run's own queue is cleared instead, so a host config can
be reused.
`hosts` arrays; the run's own queue is cleared instead, so the nested `hosts`
array can be reused.
- `stop()` is now a no-op after a run that ended on a failure, and
`abortOnSudoFailure` finishes as soon as the interrupted shell returns to a
prompt instead of waiting out the idle timeout.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -935,7 +935,7 @@ part of the public API.
| Member | Description |
| --- | --- |
| `connect(callback)` | Start the session. `callback(sessionText)` is optional and receives the combined text when all hosts finish. An instance runs once; a second call throws. |
| `stop(reason)` | Abort the whole run. Clears every command and host queue, sends Ctrl-C if a command is in flight, closes the active connection and its ancestors, and calls the callback once. A no-op before `connect()` or after the run finishes. |
| `stop(reason)` | Abort the whole run. Clears the run's command and host queues, leaves the caller's nested `hosts` arrays intact, sends Ctrl-C if a command is in flight, closes the active connection and its ancestors, and calls the callback once. A no-op before `connect()` or after the run finishes. |
| `close()` | Close the current shell stream. A no-op if the shell has not opened yet. Remaining primary hosts still run; use `stop()` to abandon them. |
| `close({ graceful: true })` | Back out of nested shells before closing. Remaining primary hosts still run. |
| `emit(name, ...args)` | Raise an event. Inherited from `EventEmitter`. |
Expand Down
2 changes: 1 addition & 1 deletion docs/ERROR-HANDLING.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ call to `close()`.
| 8 | `_bindConnection` connection `error` | The `ssh2.Client` emits `error` | `(err, "Connection", <live>)` for a primary; `(err, "Hop", false, null, context)` for a hop | `true` only once a shell stream exists | None | Before the shell opens a primary error is a notification (`close=false`) and the guarded listener does not throw. Once a stream exists it closes and ends the connection. A hop error is contained by `_hopFailed()`. Baseline: always reports without closing. |
| 9 | `_bindConnection` connection `close` | `ssh2` reports `had_error` truthy | `(Error("Connection closed with error"), "Connection close")` with `err.level = "Connection close"` and `err.hadError = had_error` | `false` | `_appendPartial()`, then emit the close message or error, then `_failContext()` -> `_endPrimary()` | Non-fatal. The readable error is reported, every visited host is finalized, and the run advances to the next primary or calls the callback. |
| 10 | `_openClient` connect `try` | `connection.connect` throws synchronously | `(e + " " + e.stack, "Connection.connect", <live>)` for a primary; `(err, "Hop", false, null, context)` for a hop | `true` only once a shell stream exists | None | Before the shell opens a primary throw is a notification and the guarded listener does not throw. A hop throw is contained by `_hopFailed()`. `_stream` is reset per primary host, so a stale stream is never closed. |
| 11 | `_connect` missing parameters | No `sshObj.server` or no `sshObj.commands` | `("Missing connection parameters", "Parameters", false, callback)` | `false` | None | No close. The default listener now runs the diagnostic callback, which prints `server` and `commands`; the session still neither starts nor ends. |
| 11 | `_connect` missing parameters | No `sshObj.server`, or no `host`/`hostname` on it | `("Missing connection parameters", "Parameters", false, callback)` for a primary; `(Error("Missing connection parameters"), "Hop", false, null, context)` for a hop | `false` | `_failContext()` -> `_endPrimary()` for a primary; `_hopFailed()` for a hop | No close. The default listener runs the diagnostic callback, which prints the remaining `server` and `commands` details. A primary is finalized and the run advances to the next primary or calls the callback; a hop is contained and its parent continues. |

## Notification vs terminator

Expand Down
2 changes: 1 addition & 1 deletion docs/NEXT-HOST-CONNECTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ record shape changes from a host config to `record.host`:
| Credentials | Local process: `password`, `privateKey`, `passPhrase`, `agent` | Local process, same fields | Same `ssh2` authentication. |
| Host key | `hostHash` / `hostVerifier` on `server` | Same fields passed to the child client | `_normalizeServer` applies `hostHash`. |
| Auth prompts | `ssh2` handles them; `keyboard-interactive` is re-emitted | Same | `_bindConnection` installs the same handler. |
| Shell | `context.connection.shell(window, { pty })` | Same | `_openShell`. |
| Shell | `context.connection.shell(window, callback)` | Same | `_openShell`; `window` carries the PTY choice. |
| Stream encoding | `streamEncoding`, default `utf8` | Same | `_openShell`. |
| Data routing | Active stream only | Active stream only; inactive parent streams are ignored | Stream handler compares `context` with `_activeContext()`. |
| Host defaults | `_loadDefaults` | `_loadDefaults` | Same host object contract. |
Expand Down
72 changes: 47 additions & 25 deletions lib/ssh2shell.js
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ class SSH2Shell extends Stream {

this._active = record;
this.sshObj = host;
this.host = host.server ? host.server.host : 'No host';
this.host = this._hostLabel(host);
this.connection = null;
this._stream = {};
this.idleTimer = null;
Expand All @@ -385,9 +385,7 @@ class SSH2Shell extends Stream {
this.connection = context.connection;
this._stream = context.stream || {};
this.sshObj = context.host;
this.host = context.host && context.host.server
? context.host.server.host
: this.host;
this.host = context.host ? this._hostLabel(context.host) : this.host;
this.idleTime = context.idleTime;
this.dataIdleTime = context.dataIdleTime;
this.idleTimer = context.idleTimer || null;
Expand Down Expand Up @@ -612,24 +610,33 @@ class SSH2Shell extends Stream {
false,
function (err, type, close) {
const expose = this.exposeCredentials === true;
this.emit(
'msg',
expose ? this.sshObj.server : redactCredentials(this.sshObj.server)
);
this.emit('msg', this.sshObj.commands);
if (this.sshObj.server) {
this.emit(
'msg',
expose ? this.sshObj.server : redactCredentials(this.sshObj.server)
);
}
if (
Array.isArray(this.sshObj.commands) &&
this.sshObj.commands.length > 0
) {
this.emit('msg', this.sshObj.commands);
}
}
);
return this._stream;
}

// A host config without `server` is invalid, but it must reach `_connect`
// before anything dereferences it: the primary reports `Parameters` and a
// hop reports `Hop`. Labels stay readable in the meantime.
// A host config without `server` (or without a usable host name) is invalid,
// but it must reach `_connect` before anything dereferences it: the primary
// reports `Parameters` and a hop reports `Hop`. Labels stay readable in the
// meantime. `ssh2` accepts `hostname` as an alternative to `host`.
_hostLabel(host) {
if (!host || !host.server || !host.server.host) {
const server = host && host.server;
if (!server || (!server.host && !server.hostname)) {
return 'No host';
}
return host.server.host;
return server.host || server.hostname;
}

// Host prefixes disambiguate messages when the session can span more than
Expand Down Expand Up @@ -1098,10 +1105,14 @@ class SSH2Shell extends Stream {
this._buffer = '';
this.command = '';
this._commandInFlight = false;
// Cancel command on host.
const result = this._stream.write('\x03');

if (this.sshObj.abortOnSudoFailure && !this._stopping) {
const aborting = this.sshObj.abortOnSudoFailure && !this._stopping;
// On the abort path `stop()` owns the interrupt because it needs the
// in-flight flag to arm its stop timer; sending Ctrl-C here too would
// interrupt the shell twice.
const result = aborting ? undefined : this._stream.write('\x03');

if (aborting) {
// Wait for the shell to return to a prompt (or the idle timeout) before
// running exit commands, so the Ctrl-C has a chance to cancel sudo.
this._commandInFlight = true;
Expand Down Expand Up @@ -1386,7 +1397,7 @@ class SSH2Shell extends Stream {
}

this._mergedHosts.add(host);
parent.sessionText += `\n${host.server.host}: ${host.sessionText || ''}`;
parent.sessionText += `\n${this._hostLabel(host)}: ${host.sessionText || ''}`;
return true;
}

Expand All @@ -1412,17 +1423,17 @@ class SSH2Shell extends Stream {
this._mergeNestedText(host);
this._systemMsg(
'debug',
`finalizeHost: end nested host ${host.server.host}${reason ? ` (${reason})` : ''}`
`finalizeHost: end nested host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}`
);
this.emit('end', `${host.server.host}: \n${host.sessionText || ''}`, host);
this.emit('end', `${this._hostLabel(host)}: \n${host.sessionText || ''}`, host);
return true;
}

this._primaryhostSessionText += `${host.sessionText || ''}\n`;
this._allSessions += this._primaryhostSessionText;
this._systemMsg(
'debug',
`finalizeHost: end primary host ${host.server.host}${reason ? ` (${reason})` : ''}`
`finalizeHost: end primary host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}`
);
this.emit('end', this._primaryhostSessionText, host);
return true;
Expand Down Expand Up @@ -2242,11 +2253,22 @@ class SSH2Shell extends Stream {
// exists and before the client is opened.
this._loadDefaults(context);

if (!host.server) {
// `ssh2` accepts either `host` or `hostname`. Without one it silently
// falls back to `localhost:22`, so treat both as required.
if (!host.server || (!server.host && !server.hostname)) {
if (context.isPrimary) {
return this._reportMissingParameters();
this._reportMissingParameters();
// Reporting alone leaves the run unfinished. Finalize the host and
// advance exactly like any other primary failure.
return this._failContext(
context,
new Error('Missing connection parameters'),
'parameters'
);
}
this._hopFailed(context, new Error('Missing connection parameters'));
const err = new Error('Missing connection parameters');
err.level = 'Parameters';
this._hopFailed(context, err);
return this._stream;
}

Expand All @@ -2264,7 +2286,7 @@ class SSH2Shell extends Stream {
parentConnection.forwardOut(
'127.0.0.1',
0,
server.host,
server.host || server.hostname,
Number(server.port) || 22,
(err, channel) => {
if (context.closed || context.failing) {
Expand Down
7 changes: 6 additions & 1 deletion lib/ssh2shell/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,12 @@ const CREDENTIAL_KEY = /^(password|passphrase|privateKey)$/i;
function credentialSecrets(sshObj) {
const server = (sshObj && sshObj.server) || {};

return [server.password, server.passPhrase, server.passphrase]
return [
server.password,
server.passPhrase,
server.passphrase,
server.privateKey,
]
.filter((secret) => secret != null && secret !== '')
.map((secret) => String(secret));
}
Expand Down
72 changes: 47 additions & 25 deletions src/ssh2shell.js
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ class SSH2Shell extends Stream {

this._active = record;
this.sshObj = host;
this.host = host.server ? host.server.host : 'No host';
this.host = this._hostLabel(host);
this.connection = null;
this._stream = {};
this.idleTimer = null;
Expand All @@ -385,9 +385,7 @@ class SSH2Shell extends Stream {
this.connection = context.connection;
this._stream = context.stream || {};
this.sshObj = context.host;
this.host = context.host && context.host.server
? context.host.server.host
: this.host;
this.host = context.host ? this._hostLabel(context.host) : this.host;
this.idleTime = context.idleTime;
this.dataIdleTime = context.dataIdleTime;
this.idleTimer = context.idleTimer || null;
Expand Down Expand Up @@ -612,24 +610,33 @@ class SSH2Shell extends Stream {
false,
function (err, type, close) {
const expose = this.exposeCredentials === true;
this.emit(
'msg',
expose ? this.sshObj.server : redactCredentials(this.sshObj.server)
);
this.emit('msg', this.sshObj.commands);
if (this.sshObj.server) {
this.emit(
'msg',
expose ? this.sshObj.server : redactCredentials(this.sshObj.server)
);
}
if (
Array.isArray(this.sshObj.commands) &&
this.sshObj.commands.length > 0
) {
this.emit('msg', this.sshObj.commands);
}
}
);
return this._stream;
}

// A host config without `server` is invalid, but it must reach `_connect`
// before anything dereferences it: the primary reports `Parameters` and a
// hop reports `Hop`. Labels stay readable in the meantime.
// A host config without `server` (or without a usable host name) is invalid,
// but it must reach `_connect` before anything dereferences it: the primary
// reports `Parameters` and a hop reports `Hop`. Labels stay readable in the
// meantime. `ssh2` accepts `hostname` as an alternative to `host`.
_hostLabel(host) {
if (!host || !host.server || !host.server.host) {
const server = host && host.server;
if (!server || (!server.host && !server.hostname)) {
return 'No host';
}
return host.server.host;
return server.host || server.hostname;
}

// Host prefixes disambiguate messages when the session can span more than
Expand Down Expand Up @@ -1098,10 +1105,14 @@ class SSH2Shell extends Stream {
this._buffer = '';
this.command = '';
this._commandInFlight = false;
// Cancel command on host.
const result = this._stream.write('\x03');

if (this.sshObj.abortOnSudoFailure && !this._stopping) {
const aborting = this.sshObj.abortOnSudoFailure && !this._stopping;
// On the abort path `stop()` owns the interrupt because it needs the
// in-flight flag to arm its stop timer; sending Ctrl-C here too would
// interrupt the shell twice.
const result = aborting ? undefined : this._stream.write('\x03');

if (aborting) {
// Wait for the shell to return to a prompt (or the idle timeout) before
// running exit commands, so the Ctrl-C has a chance to cancel sudo.
this._commandInFlight = true;
Expand Down Expand Up @@ -1386,7 +1397,7 @@ class SSH2Shell extends Stream {
}

this._mergedHosts.add(host);
parent.sessionText += `\n${host.server.host}: ${host.sessionText || ''}`;
parent.sessionText += `\n${this._hostLabel(host)}: ${host.sessionText || ''}`;
return true;
}

Expand All @@ -1412,17 +1423,17 @@ class SSH2Shell extends Stream {
this._mergeNestedText(host);
this._systemMsg(
'debug',
`finalizeHost: end nested host ${host.server.host}${reason ? ` (${reason})` : ''}`
`finalizeHost: end nested host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}`
);
this.emit('end', `${host.server.host}: \n${host.sessionText || ''}`, host);
this.emit('end', `${this._hostLabel(host)}: \n${host.sessionText || ''}`, host);
return true;
}

this._primaryhostSessionText += `${host.sessionText || ''}\n`;
this._allSessions += this._primaryhostSessionText;
this._systemMsg(
'debug',
`finalizeHost: end primary host ${host.server.host}${reason ? ` (${reason})` : ''}`
`finalizeHost: end primary host ${this._hostLabel(host)}${reason ? ` (${reason})` : ''}`
);
this.emit('end', this._primaryhostSessionText, host);
return true;
Expand Down Expand Up @@ -2242,11 +2253,22 @@ class SSH2Shell extends Stream {
// exists and before the client is opened.
this._loadDefaults(context);

if (!host.server) {
// `ssh2` accepts either `host` or `hostname`. Without one it silently
// falls back to `localhost:22`, so treat both as required.
if (!host.server || (!server.host && !server.hostname)) {
if (context.isPrimary) {
return this._reportMissingParameters();
this._reportMissingParameters();
// Reporting alone leaves the run unfinished. Finalize the host and
// advance exactly like any other primary failure.
return this._failContext(
context,
new Error('Missing connection parameters'),
'parameters'
);
}
this._hopFailed(context, new Error('Missing connection parameters'));
const err = new Error('Missing connection parameters');
err.level = 'Parameters';
this._hopFailed(context, err);
return this._stream;
}

Expand All @@ -2264,7 +2286,7 @@ class SSH2Shell extends Stream {
parentConnection.forwardOut(
'127.0.0.1',
0,
server.host,
server.host || server.hostname,
Number(server.port) || 22,
(err, channel) => {
if (context.closed || context.failing) {
Expand Down
Loading
Loading