This document tracks each level of improvement to ssh2shell as an atomic,
independently revertible step. The refactor was developed on the Refactoring
branch and completed on master, which is now the mainline.
The goal is simple: at any point we can identify exactly what changed at a given level, verify it, and roll back to it without guessing.
| Topic | Decision |
|---|---|
| End state | Modern JavaScript (CoffeeScript toolchain removed) |
| Compatibility | Strict: same public API, events, config keys, and observable behavior |
| Verification | Offline unit harness with a mocked ssh2; the same suite also runs against the frozen baseline artifact. Live-host tests are optional for unit work but required for release validation. |
| Rollback tracking | Annotated tags for levels through L7.6; later levels are ledger-only (see Branch and tag policy) |
The following must remain identical throughout the refactor:
require('ssh2shell')returns the same constructible class.- The class extends
Streamand supportsconnect(callback)and the inheritedpipe. (unpipeis documented but absent at baseline; adding it would be a behavior change, so it is not part of the strict contract.) - Public instance properties:
.sshObj,.command. - All events the code actually emits:
msg,data,stderrData,error,end,commandProcessing,commandComplete,commandTimeout,keyboard-interactive,newPrimaryHost. - All host/config keys the code actually reads (see
docs/API-BASELINE.md). README claims that the code ignores are recorded as discrepancies, not silently adopted. - Default prompts, filters, timeouts, and session-text behavior.
Internals (private _methods, file layout, helper functions) may change freely
as long as the contract above holds.
Note: a bug fix that changes observable behavior conflicts with "strict" compatibility. Such fixes need explicit sign-off and must be recorded in the ledger as behavior changes, not silent cleanups.
Two host layers exist and must stay distinct:
- Primary hosts live in
_hostsand are opened with a newssh2.Clientconnection._nextPrimaryHostiterates this array. - Secondary (nested) hosts live in the current host's
hostsarray. Since L7.24 a hop opens anssh2forwardOutchannel through the active record and logs in over it, instead of typing anssh ...command into the shell. The active records form an ancestor stack in_connections;_nextHostiterates the nested array. Several secondary hosts may be chained.
_runExit is the "finish this host" routine. It opens the next secondary host
if one remains, otherwise backs out through _connections via _previousHost,
and finally closes. The literal exit branch remains for su / sudo -i and
the final primary shell; a hop is left by closing its connection. Backing out to
a previous host re-runs _runExit, so that host's remaining hosts entries are
resumed rather than discarded. See docs/API-BASELINE.md for the exact order.
- The refactor was developed on
Refactoringand completed onmaster, which is now the mainline. - The
Refactoringbranch was deleted after the refactor. Its tip remains taggedv2.1.0(07f93ee), so the history is still reachable. refactor/L0-baselinemarks the pristine pre-refactor state.- Annotated tags exist locally for
refactor/L0-baselineandrefactor/L1throughrefactor/L7.6. Onlyrefactor/L7-refactor/L7.3are onorigin;L0-L6.1andL7.4-L7.6are local only. refactor/L7.7throughrefactor/L7.17were recorded in this ledger but never tagged, locally or remotely.L7.18has no level tag either; it shipped inv3.2.0.L7.19-L7.23have no level tags either; they shipped inv3.3.0. Use the release tags as the coarse rollback boundary; see Rollback after L7.6.- Levels through L7.6 are one atomic commit (or a small, clearly-scoped commit series). Later levels were recorded after the fact.
- Tags are the source of truth for rollback where they exist; commit SHAs are informational.
# Inspect a level
git show refactor/L2
git diff refactor/L2..HEAD
# Safe undo of everything after L2 (creates a revert commit)
git revert --no-commit refactor/L2..HEAD
git commit -m "revert to refactor/L2"
# Hard reset (local only, destructive)
git reset --hard refactor/L2
# Restore a single file from a level
git checkout refactor/L2 -- path/to/fileLevels after L7.6 have no tag. Use the release boundaries below.
The release tags give a stable coarse boundary for the untagged levels:
| Range | Boundary | Covers |
|---|---|---|
refactor/L7.6..v3.1.0 |
v3.1.0 |
L7.7-L7.17 plus follow-up commits (16 commits) |
v3.1.0..v3.2.0 |
v3.2.0 |
L7.18 (post-3.1.0 shutdown work) |
v3.2.0..v3.3.0 |
v3.3.0 |
L7.19-L7.23 (opt-in prompt/response/timeout/silent-command/stderr features) |
v3.3.0..v4.0.0 |
v4.0.0 |
L7.24-L7.25 (ssh2 forwardOut hops, always-on command idle timeout, surface cleanup) |
# Inspect everything after the last tagged level
git log --oneline refactor/L7.6..v3.1.0
git diff refactor/L7.6..v3.1.0
# Inspect the post-3.1.0 work
git log --oneline v3.1.0..v3.2.0
git diff v3.1.0..v3.2.0
# Inspect the post-3.2.0 work
git log --oneline v3.2.0..v3.3.0
git diff v3.2.0..v3.3.0
# Inspect the post-3.3.0 work
git log --oneline v3.3.0..v4.0.0
git diff v3.3.0..v4.0.0
# Revert the post-3.3.0 work as one commit (keeps history)
git revert --no-commit v3.3.0..v4.0.0
git commit -m "revert post-3.3.0 work"v2.0.14, v2.1.0, v3.0.0, v3.1.0, v3.2.0, v3.3.0, and v4.0.0
are the release boundaries. The release process, tag convention, and gitHead
check are in docs/PUBLISHING.md.
Every level must satisfy all of these before it is completed (and tagged, for levels through L7.6):
- Scope is limited to the level's stated goal.
- Characterization/unit tests pass against the current build.
- New tests also run against the frozen baseline artifact, so they describe real original behavior rather than the refactored implementation.
lib/ssh2shell.jsis rebuilt andnpm run check:buildpasses (until L7 changes the publish flow).- Public API/event smoke checks pass.
REFACTORING.mdledger row is updated.- Commit created and annotated tag
refactor/LNapplied. This applied through L7.6; later levels are recorded in the ledger without a tag. git statusis clean.
test/fixtures/baseline-ssh2shell.js is the frozen L0 compiled artifact.
npm run test:baseline sets SSH2SHELL_TEST_MODULE so the same unit suite loads
that artifact instead of lib/. This checks that every characterization still
describes the original behavior and separates real regressions from intentional
differences.
When adding a test:
- Run it against the current build (
npm run test:unit). - Run it against the baseline (
npm run test:baseline). - Passes on both: it characterizes shared behavior.
- Fails on baseline, passes on current: it covers an intentional change. Make the expectation level-aware and record why.
- Fails on both: it characterizes a bug. Keep the current (buggy) expectation and mark it as a known defect until a signed-off fix changes it.
| Level | Goal | Behavior change |
|---|---|---|
| L0 | Baseline: tag pristine v2.0.14, add this ledger |
None |
| L1 | Offline safety net: mocked-ssh2 harness and characterization tests |
None |
| L2 | Port src/ssh2shell.coffee to JavaScript 1:1, same structure and logic; remove the CoffeeScript source and toolchain |
None |
| L3 | Split into focused modules behind the existing class facade | None |
| L4 | Modernize syntax and clean up dead code, typos, duplication | None |
| L5 | Fix defects and security issues, each covered by a test | Only with sign-off |
| L6 | Signed-off post-L5 backlog, per-host prompt/filter, and error-handling fixes | Only with sign-off |
| L6.1 | Approved optimisation and robustness follow-ups (readability, timer/option de-duplication, SSH prompt timeout, guarded close, empty command, own-property options, build-sync guard) | Only with sign-off |
| L7 | Tooling, docs, CI, and publish pipeline | None |
| L7.x | Post-L7 follow-ups: live VMs and provisioning, escape filtering, message prefixes, the live runner, the progress indicator, stop/close semantics, and opt-in prompt/response/timeout/silent-command/stderr controls | Only with sign-off |
The ladder can be reordered or split as we learn more; any change to the plan must be recorded here.
| Level | Tag | Commit | Status | Goal | Verification | Rollback |
|---|---|---|---|---|---|---|
| L0 | refactor/L0-baseline |
— | Done | Tag pristine v2.0.14 and add this ledger |
Baseline tag points at the unmodified release commit | git reset --hard refactor/L0-baseline |
| L1 | refactor/L1 |
— | Done | Offline ssh2 mock and 57 characterization tests |
npm run test:unit passes; npm run build leaves lib/ in sync |
git reset --hard refactor/L1 |
| L2 | refactor/L2 |
— | Done | 1:1 JavaScript port; CoffeeScript source and toolchain removed | 61 tests pass against the port (57 baseline characterizations plus 4 port-semantics tests); baseline-vs-port comparison matches defaults, prototype surface, SSH command construction, return values, and event payloads; npm run build leaves lib/ in sync |
git reset --hard refactor/L2 |
| L3 | refactor/L3 |
— | Done | Split pure helpers into focused modules behind the existing class facade | 61 tests pass unchanged; baseline-vs-port comparison still matches; npm run build copies the module tree and leaves lib/ in sync |
git reset --hard refactor/L3 |
| L4 | refactor/L4 |
— | Done | Modernize syntax and remove dead code, duplication, and obsolete compatibility shims | 62 tests pass; the same 62 pass against the frozen baseline artifact, with only the _nextPrimaryHost empty-queue assertion level-aware; baseline-vs-port comparison still matches; npm run build leaves lib/ in sync |
git reset --hard refactor/L4 |
| L5 | refactor/L5 |
— | Done | Debug/verbose message gating, per-host listener lifecycle, and the signed-off multi-host/payload fixes | 72 tests pass; the same 72 pass against the frozen baseline artifact with L5 expectations level-aware; npm run build leaves lib/ in sync; backing out of a nested host no longer fires stale handlers or duplicates session text |
git reset --hard refactor/L5 |
| L6 | refactor/L6 |
— | Done | Signed-off post-L5 fixes: backlog config/flags, per-host prompt/filter compilation, and error-handling termination | 88 tests pass; the same 88 pass against the frozen baseline artifact with L6 expectations level-aware; npm run build leaves lib/ in sync; pre-shell errors no longer throw, host onError observes the error before close, and each host recompiles its own prompts/filters |
git reset --hard refactor/L6 |
| L6.1 | refactor/L6.1 |
— | Done | Approved optimisation and robustness follow-ups: comment accuracy, _systemMsg and timer de-duplication, buildSshCommand option table, test helpers, build-sync guard, and four signed-off fixes (post-auth SSH timeout, guarded close(), empty-command skip, own-property SSH options) |
92 tests pass; the same 92 pass against the frozen baseline artifact with L6.1 expectations level-aware; npm run check:build and npm run build leave lib/ in sync |
git reset --hard refactor/L6.1 |
| L7 | refactor/L7 |
— | Done | Tooling, docs, CI, and publish pipeline | 112 tests pass on the current build and the frozen baseline; npm run check:build passes; npm pack --dry-run contains only lib/, the README, and package.json; CI runs the suite on Node 18, 20, 22, and 24 |
git reset --hard refactor/L7 |
| L7.1 | refactor/L7.1 |
— | Done | Post-L7 fixes: drop the misspelled prompt aliases, document the stream.Stream base, and finish README reconciliation |
112 tests pass on the current build and the frozen baseline; the README discrepancy table is fully resolved; npm pack --dry-run still contains only lib/, the README, and package.json |
git reset --hard refactor/L7.1 |
| L7.2 | refactor/L7.2 |
— | Done | Pre-publish hardening: ISC LICENSE, Node requirement, complete .env-example, README example fixes, and the current ssh2 lockfile |
112 tests pass on the current build and the frozen baseline; npm pack --dry-run contains README.md, LICENSE, lib/, and package.json; npm audit reports no vulnerabilities |
git reset --hard refactor/L7.2 |
| L7.3 | refactor/L7.3 |
— | Done | Trusted publishing workflow and maintainer guide | publish.yml uses GitHub OIDC (id-token: write) with no long-lived token; docs/PUBLISHING.md covers the npm trusted-publisher setup and the OTP fallback |
git reset --hard refactor/L7.3 |
| L7.4 | refactor/L7.4 |
— | Done | README refactor for accuracy, use-case ordering, examples, and security guidance | Every JavaScript block passes node --check; all internal anchors and local links resolve; 112 tests pass on the current build and the frozen baseline; npm run check:build passes |
git reset --hard refactor/L7.4 |
| L7.5 | refactor/L7.5 |
— | Done | Mirror the README's full examples as live tests with dotenv and logging |
Every new or reworked live test passes node --check; npm test passes; every local README link resolves; .env-example documents the variables the tests read |
git reset --hard refactor/L7.5 |
| L7.6 | refactor/L7.6 |
— | Done | Audit and clean up the remaining legacy live tests | npm test passes on the current build and the frozen baseline; the deleted scripts' scenarios are covered by unit tests; every kept live test passes node --check and uses dotenv, logFile()/log(), and ../src |
git reset --hard refactor/L7.6 |
| L7.7 | — (ledger-only) | — | Done | Live VM host and user structure: static addresses, test users, sudo rules, keys, and authentication | sshd -t and the key/password auth checks pass; npm test 116/116; live suite 17/17 |
No tag; see L7.7 deliverables |
| L7.8 | — (ledger-only) | — | Done | Live-test VM provisioning script | All three roles report sudoers: OK, sshd: OK, and network: OK; npm test 116/116; live suite 17/17 |
No tag; see L7.8 deliverables |
| L7.9 | — (ledger-only) | — | Done | Strip complete terminal escape sequences before ASCII filtering | New unit test covers CSI/OSC removal; test:unit and test:baseline 117/117; live log is clean |
No tag; see L7.9 deliverables |
| L7.10 | — (ledger-only) | — | Done | Omit the host prefix for single-host messages | New unit tests cover single, multi-primary, and nested hosts; 121/121; live log omits the address | No tag; see L7.10 deliverables |
| L7.11 | — (ledger-only) | — | Done | Cross-platform live-test batch runner | Curated batch 12/12; --all 17/17; npm test 125/125 |
No tag; see L7.11 deliverables |
| L7.12 | — (ledger-only) | — | Done | Start nested key-only connections authenticated | New unit tests cover key-only, password, and passphrase auth; tunnel/chaining pass with nested output; 125/125 | No tag; see L7.12 deliverables |
| L7.13 | — (ledger-only) | — | Done | Move live tests to test/live/ |
Curated 12/12; --all 17/17; 125/125; npm pack --dry-run still only lib/, README.md, LICENSE, and package.json |
No tag; see L7.13 deliverables |
| L7.14 | — (ledger-only) | — | Done | Add test/README.md as the testing documentation hub |
Relative links resolve; no code changes, so the suites are unaffected | No tag; see L7.14 deliverables |
| L7.15 | — (ledger-only) | — | Done | Opt-in progress indicator | 138/138 unit and 138/138 baseline; live suite unchanged | No tag; see L7.15 deliverables |
| L7.16 | — (ledger-only) | — | Done | Three-hop tunnel coverage | tunnel and chaining pass; --all 17/17 |
No tag; see L7.16 deliverables |
| L7.17 | — (ledger-only) | — | Done | Progress on by default | 139/139 unit and 139/139 baseline; progress 1/1; --all 18/18 |
No tag; see L7.17 deliverables |
| L7.18 | — (ledger-only) | — | Done (v3.2.0) | Post-3.1.0 shutdown semantics: stop() and close({ graceful: true }), centralized host finalization, the Connection close payload, handler flags, and visible sudo failures with abortOnSudoFailure |
npm test 149/149 on the current build and the frozen baseline; curated live 18/18; full live 24/24; git diff --check clean |
No level tag; released in v3.2.0; see L7.18 deliverables |
| L7.19 | — (ledger-only) | — | Done (v3.3.0) | Opt-in full prompt regex (standardPromptRegex) |
New suite covers string, RegExp, invalid-pattern fallback, and completion/sudo/nested paths; npm test 169/169 unit and 169/169 baseline |
No level tag; released in v3.3.0; see L7.19 deliverables |
| L7.20 | — (ledger-only) | — | Done (v3.3.0) | Opt-in handled commandComplete payload (commandResponse) |
New suite covers the raw default, echo/prompt removal, PTY-wrapped echo, and no-regex behavior; npm test 169/169 unit and 169/169 baseline |
No level tag; released in v3.3.0; see L7.20 deliverables |
| L7.21 | — (ledger-only) | — | Done (v3.3.0) | Opt-in commandTimeoutRetries with library-owned attempts |
New suite covers the single-timeout default, re-arm, handler answer, stop, opt-out, final-only close, and reset points; npm test 169/169 unit and 169/169 baseline; live timeout passes |
No level tag; released in v3.3.0; see L7.21 deliverables |
| L7.22 | — (ledger-only) | — | Done (v3.3.0) | Opt-in commandStartTimeout for silent commands and details.noOutput |
New suite covers the default no-timer behavior, start-timer arming, noOutput true/false, and the per-command reset; npm test 179/179 unit and 179/179 baseline |
No level tag; released in v3.3.0; see L7.22 deliverables |
| L7.23 | — (ledger-only) | — | Done (v3.3.0) | Opt-in stderr capture in the command response (captureStderr) |
New suite covers the default, raw merge, handled merge, escape filtering, and per-command reset; npm test 179/179 unit and 179/179 baseline |
No level tag; released in v3.3.0; see L7.23 deliverables |
| L7.24 | — (ledger-only) | — | Done (v4.0.0) | ssh2 forwardOut host hops and an always-on command idle timeout |
npm run test:src 163/163; npm test 155 pass with 8 baseline-skipped; full live suite 28/28 on src twice; clean-VM provisioning reports sudoers: OK, sshd: OK, network: OK |
No level tag; released in v4.0.0; see L7.24 deliverables |
| L7.25 | — (ledger-only) | — | Done (v4.0.0) | Pre-release instance and host-config surface cleanup; removes legacy aliases and renames host.msg to host.onMsg |
npm run test:src 166/166; npm run test:baseline 158 pass with 8 baseline-skipped |
No level tag; released in v4.0.0; see L7.25 deliverables |
Commit SHAs are deliberately omitted from this table: a commit cannot contain
its own hash. Where a tag exists, it is the stable rollback reference; use
git rev-parse refactor/LN^{commit} when a commit SHA is needed. L7.7 onward
are ledger-only and have no tag.
test/unit/helpers/fake-ssh2.js— deterministic fakessh2.Clientand shell stream; no network access.test/unit/helpers/harness.js— require-cache injection, host factory, wait helpers.test/unit/*.test.js— 57 tests covering the public surface, defaults, prompt/filter compilation, command flow, notifications, timeouts, sudo and nested-SSH prompts, host lifecycle, primary/secondary host chains,_runExitordering, and SSH command construction/injection guards.docs/API-BASELINE.md— code-derived API inventory, host model, truthiness audit,forceProtocolVersionanalysis, and every README mismatch found.package.json-build,test, andtest:unitscripts.
src/ssh2shell.js— 1:1 port of the baseline CoffeeScript. Control flow, method binding order, messages, defaults, return values, and known quirks are preserved. The only structural difference is that it is a native ES class instead of CoffeeScript's prototype helper, so prototype methods are non-enumerable (internals, not public surface).src/ssh2shell.coffee— removed.scripts/build.jsandpackage.json—buildnow copiessrc/ssh2shell.jstolib/ssh2shell.js.package.json/package-lock.json— removed thecoffee-scriptdevDependency;engines.noderaised to>=18.0.0.lib/ssh2shell.js— rebuilt from the new source.test/unit/port-semantics.test.js— 4 tests that lock in the port's return values and thenewPrimaryHostpayload.docs/API-BASELINE.md— updated source-of-truth,newPrimaryHostpayload, and build-command references.
src/ssh2shell/util.js— pure helpers:typeIsArray,escapeRegex,shellQuote,shellControlChars,compileAsciiFilter,compileTextColorFilter, andcompilePrompts.src/ssh2shell/defaults.js—applyHostDefaults, the in-place host default application extracted from_loadDefaults.src/ssh2shell/ssh-command.js—buildSshCommand, the nested-hostssh ...command builder extracted from_sshConnect.src/ssh2shell.js— class facade now delegates to the modules. No control flow, message, default, return-value, or event changes.scripts/build.js— copiessrc/ssh2shell.jsand thesrc/ssh2shell/module tree intolib/.lib/ssh2shell.jsandlib/ssh2shell/*— rebuilt from source.
src/ssh2shell.js— consolidated module requires,node:core import,??instead of!= nullternaries,sliceinstead of the deprecatedsubstr, and merged consecutivedebugguards without changing message order.- Dead code removed: the constructor's misspelled
newPrimmaryHostlistener (nothing emits that event), the duplicatestderrDataremoval in_removeListeners, the redundant_previousHostbranch, and the unreachable_runExitreference at the end of_nextPrimaryHost. src/ssh2shell/util.js—typeIsArraynow aliases the built-inArray.isArray; the legacy fallback is gone.test/unit/hosts.test.js— locks in that an empty primary queue leaves_nextPrimaryHostreturningundefined; the same assertion accepts the baseline's implicit_runExitreturn when run in baseline mode. Also adds a characterization test for the known stale-secondary-handler bug.test/fixtures/baseline-ssh2shell.js— frozen L0 compiled artifact used as the dual-run target.test/unit/helpers/harness.js—SSH2SHELL_TEST_MODULEsupport andisBaseline().scripts/run-tests.jsandpackage.json—test:src,test:lib, andtest:baseline;testnow runs the build check, the lib suite, and the baseline suite.lib/ssh2shell.jsandlib/ssh2shell/*— rebuilt from source.
src/ssh2shell.js— centralized_systemMsg(type, message, object)gate sodebugandverbosemessages are emitted only when their host flags are enabled, while normal messages are unaffected._loadDefaultListeners,_boundListener, and_detachListener— default listeners are installed once, host listeners replace defaults, and both the cached handler and the current host handler are removed when a host is left. Reloading defaults no longer attaches duplicate handlers.- Listener lifecycle across host changes —
_nextHost,_nextPrimaryHost, and_previousHostdetach the outgoing host's handlers. Backing out of a nested host no longer leaves a stalecommandComplete(or similar) handler that fires against the new current host and duplicatessessionText. this.hostis kept in sync when moving to the next nested host and the next primary host, so callback/session text starts with the correct host name.keyboard-interactiveis registered and dispatched under the dashed event name, host handlers are honored, and the default handler callsfinish([''])instead of stalling the handshake.- Restored baseline payloads/defaults that the branch had changed accidentally:
commandCompleteemits the raw_buffer,hostHashis written tosshObj.server.hostHash, the legacymsg: { send }shape is mapped tomsg, and the default keyboard response is an empty string. test/unit/l5-behavior.test.js— 10 tests covering debug/verbose gating, listener detach/reload behavior,keyboard-interactivedispatch and cleanup, rawcommandComplete,msg.send, andserver.hostHash.test/unit/hosts.test.js— the former known-bug characterization now asserts the signed-off result: the baseline leaves the stale handler attached, while L5 removes it.test/unit/api-baseline.test.jsandtest/unit/prompts.test.js— level-aware expectations for per-instance state, the renamed_processSudoPrompt, and baseline-only behavior.lib/ssh2shell.jsandlib/ssh2shell/*— rebuilt from source.
L6 collects the fixes signed off after the L5 tag. It changes observable behavior only where the user explicitly approved it. The review that drove the error-handling work is kept below for context.
docs/ERROR-HANDLING.md— maps everyerroremit site to its payload,closeflag, follow-up flow, and connection/process outcome. It also records the default listener contract and findings F1-F11 (pre-shell close crash, L5 close-flag changes, ignored callbacks, listener accumulation, stale_stream, and related quirks).test/unit/error-handling.test.js— characterization tests that pass against both the current build and the frozen baseline, with level-aware expectations where the current behavior intentionally differs (close flags, callbacks, listener order and counts, stream reset).- The review itself did not change source behavior. Its recommended fixes were signed off and are part of L6 (below).
Signed-off-by: user review of docs/ERROR-HANDLING.md.
src/ssh2shell.js— the defaulterrorlistener only closes a live shell stream (_hasLiveStream()), so pre-shell errors cannot throw on the prototype{}placeholder (F1/F3).src/ssh2shell.js— Shell/Connection/Connection.connect errors classify by stream state: pre-shell they report withclose=false; once a shell exists they terminate (F2).src/ssh2shell.js— the default listener invokes the optional callback before closing, with the shell asthis, restoring timeout bookkeeping and missing-parameter diagnostics (F4).src/ssh2shell.js— the hostonErroris prepended so it runs before the default close (F5).src/ssh2shell.js— the defaulterrorlistener is tracked separately and installed exactly once (F6).src/ssh2shell.js—_nextPrimaryHostresets_streambefore each new primary host (F10).src/ssh2shell.js— the sudo timeout passesthis.connection, not the never-assignedthis._connection(F11).test/unit/error-handling.test.js— level-aware coverage for all of the above, including the new F5/F10/F11 tests.
Signed-off-by: user review of the backlog, before further error-handling work.
src/ssh2shell/defaults.js—windowandptyuse nullish checks so an explicitfalseis preserved.src/ssh2shell.js—_loadDefaultsmapsdataIdleTimeOutto the internaldataIdleTime, withdataIdleTimeas a fallback.src/ssh2shell.js— sudo password rejection is a debugmsgnotification, not anerrorevent. The command is still cancelled withCtrl-C. (Superseded at L7.18: rejection is now a visiblemsgwithsudoFailedand optionalabortOnSudoFailure.)src/ssh2shell/ssh-command.js—forceProtocolVersionandforceAddressTypemap to allow-listedsshflags.trueselects-2/-4; invalid truthy values return aSecurity Alerterror.src/ssh2shell.js—_loadDefaultsrecompiles prompt/filter regexes from the currentsshObjon every call, so multi-host chains honour per-host config.README.md— removedonPipe/onUnpipehost handlers and the.pipe/.unpipemethod/event documentation.pipeis a stream-level operation on the instance, not host config.test/unit/api-baseline.test.js,test/unit/ssh-connect.test.js,test/unit/prompts.test.js, andtest/unit/error-handling.test.js— updated with level-aware expectations for the baseline and the fixed behavior.docs/API-BASELINE.md— records the fixes and the resolved per-host prompt/filter compilation requirement.
Signed-off-by: user selection of the optimisation review's "safe set + approved behaviour fixes" option.
src/ssh2shell.js— top-of-file and_systemMsgcomments now describe the current build instead of the L1 baseline; removed the orphaned numbered "CRITICAL" comment and the stale "listeners defaults" comment.src/ssh2shell.js—_systemMsgmerges its identicaldebugandverbosebranches into one guarded block. Emitted messages are unchanged.src/ssh2shell.js—_scheduleIdleTimeout(response)replaces the three duplicatedcommandTimeouttimer blocks in_onDataand_processSudoPrompt.src/ssh2shell/ssh-command.js—appendSshOptionplus an option-spec table replaces the seven repeated control-character guards. Error strings, order, and command output are unchanged.test/unit/helpers/harness.js— sharedprocessSudoshim andwaitForStreamhelper; the duplicated copies in the test files are removed.test/unit/hosts.test.js— the chain tests drop the defaultmsglistener so expected host output no longer floods the test log.scripts/check-build.jsandpackage.json—check:buildverifies thatlib/matchessrc/;npm testruns it before the suites, so a stale build cannot silently pass.
src/ssh2shell.js— post-auth_processSSHPromptoutput that matches no prompt now re-arms the idle timer instead of returning with no timer. A silent nested shell therefore times out rather than hanging.src/ssh2shell.js—close()is a no-op before a live shell stream exists, so calling it early no longer throws on the prototype{}placeholder.src/ssh2shell.js—_processNotificationsskips an empty command and advances the queue instead of leaving the state machine idle.src/ssh2shell/ssh-command.js— customserver.ssh.optionsuse own enumerable properties only, so inherited values cannot reach the command line.test/unit/prompts.test.js,test/unit/errors.test.js, andtest/unit/ssh-connect.test.js— level-aware coverage for the four fixes.
npm test— 92 tests pass on the current build and 92 on the frozen baseline artifact, withcheck:buildconfirminglib/is in sync first.npm run build— rebuildslib/fromsrc/.
No runtime behavior changes. The public API, events, and config remain as they were after L6.1.
.github/workflows/ci.yml— runsnpm ci,npm test, andnpm pack --dry-runon Node 18, 20, 22, and 24 for pushes tomaster/Refactoringand for pull requests.scripts/run-tests.js— discovers*.test.jsfiles undertest/unitand passes them explicitly tonode --test, so the same runner works on Node 18 as well as newer releases.test:unitnow delegates to it as well.package.json—files: ["lib"]limits the published tarball to the runtime artifact (the README andpackage.jsonare always included), andprepublishOnlyrunsnpm testso a stale build or failing baseline cannot be published.docs/API-BASELINE.md— verification commands includenpm pack --dry-run; the README discrepancy table is fully resolved.REFACTORING.md— this L7 section and ledger row.- The README itself is corrected by the project owner. The L7 README pass
aligned the
stream.Streambase, bothasciiFilterexamples, theonErrorclose guidance, and theemitsignature, so the discrepancy table is now fully resolved. The misspelledpasswordPromt/passphrasePromtaliases were removed rather than documented (see the post-L7 entry in the backlog).
npm test— 112 tests pass on the current build and 112 on the frozen baseline artifact, withcheck:buildconfirminglib/is in sync first.npm pack --dry-run— the tarball containsREADME.md,lib/ssh2shell.js, the threelib/ssh2shell/*helpers, andpackage.json.- CI runs the same commands on Node 18, 20, 22, and 24.
src/ssh2shell/defaults.js— removed the misspelledpasswordPromt/passphrasePromtfallbacks; onlypasswordPromptandpassphrasePromptare read. The frozen baseline still honours the aliases, sotest/unit/api-baseline.test.jsis level-aware.README.md— documents thestream.Streambase and uses the tab-preservingasciiFilterdefault in both examples.docs/API-BASELINE.md— the README discrepancy table is fully resolved.
npm test— 112 tests pass on the current build and 112 on the frozen baseline artifact, withcheck:buildconfirminglib/is in sync first.npm pack --dry-run— still onlyREADME.md,lib/, andpackage.json.
LICENSE— added the ISC license text declared bypackage.json; npm includes it automatically in the published tarball.README.md— states the Node.js 18 requirement, uses the currentidleTimeproperty in the timeout examples, and fixes theapt-getand prose typos..env-example— lists every variable used by the live tests and the README examples, including the secondary user and nested hosts.package-lock.json— updatedssh2to1.17.0(still within the declared^1.4.0range) so CI exercises the same version users receive.test/devtest.js— targetssrc/like the other live scripts and throws a real error on timeout instead of calling an undefinedreject. (Removed at L7.6 after its scenario moved to the offline suite.)
npm test— 112 tests pass on the current build and 112 on the frozen baseline artifact, withcheck:buildconfirminglib/is in sync first.npm pack --dry-run—README.md,LICENSE,lib/ssh2shell.js, the threelib/ssh2shell/*helpers, andpackage.json.npm audit— no vulnerabilities.
.github/workflows/publish.yml— publishes onv*tags, or manually for a specified tag, using GitHub OIDC (id-token: write) and no long-lived npm token. It runsnpm testandnpm pack --dry-runbeforenpm publish.docs/PUBLISHING.md— npm trusted-publisher setup, the one-off--otpfallback, and the bypass-2FA stopgap.
- Reordered the README by reader use case: quick start, core concepts, configuration reference, common recipes, multiple/tunnelled hosts, events and API, advanced usage, troubleshooting, security, and development.
- Replaced the inline configuration block with per-section tables for
server, commands, prompts/filters, timeouts, messages, and host handlers. - Corrected defaults and behaviour:
textColorFilteris\\x1b\\[[0-9;]*m;asciiFilteris[^\r\n\x20-\x7e]and the compiled default preserves tabs;window/ptyaretrueand explicitfalsesurvives;idleTimeOut/dataIdleTimeOutare distinguished. - Removed the false
connect/ready/closeinstance events. The README now documentsconnectedMessage,readyMessage, andclosedMessageasmsgevents. - Added the missing
exposeCredentials,disableASCIIFilter,onStderrData,stderrData,close(),username/passphrasealiases, and theidleTimealias. - Documented
server.sshoptions and the nested-command safeguards: quoting, control-character rejection,optionskey sanitisation, and the always-addedStrictHostKeyChecking=no. - Corrected fingerprint validation:
hashMethodis a legacy alias forhostHash;hashKeyis unused; the verifier receives a hex digest without colons; anycrypto.getHashes()algorithm is accepted. - Corrected
suguidance to answer the prompt withstream.write(), not the removedthis.runCommand(). - Fixed broken example links (
test/keyboard-interactive.js,test/sudo_su.js), the tunnelling example syntax, thehost3command check, and the typos carried over from earlier revisions. - Added a Security section linking
GHSA-4j47-m47f-3jp8and a Development section describingnpm testand the legacy live tests.
- Reworked
test/simple.js,test/keyboard-interactive.js,test/sudo_su.js,test/multiple_primary_hosts.js,test/tunnel.js,test/chaining.js, andtest/notifications.jsto mirror the README's full examples withdotenv,logFile()/log(), andrequire('../src/ssh2shell'). - Added
test/private_key.js,test/fingerprint.js,test/prompt_response.js,test/command_timeout.js, andtest/bash_script.jsfor the remaining runnable README examples. - Replaced the broken
util.promisify(SSH.connect)call intest/chaining.jswith a real nested-host chain, and madetest/notifications.jsuse safe stand-in commands. - Extended
.env-examplewithPRIVATE_KEY_PATH,KEY_PASSPHRASE,EXPECTED_HOST_HASH,SECOND_USER,SECOND_USER_PASSWORD, and theSERVER1_*/SERVER2_*/SERVER3_*port fields. - Added README links from each recipe to its runnable live test.
- Removed the unused
SUDO_PASSWORDandSERVER1_PASS_PHRASE/SERVER1_PRIV_KEY_PATHentries from.env-example;sudousesserver.passwordand the multi-host example uses password authentication.
test/unit/ssh-connect.test.js— offline coverage for shell-quoting a malicioushost/userNameand rejecting control characters inserver.ssh.optionskeys, so the live injection script could be retired.- Deleted
test/ssh-options-regression.js,test/Config-poperties-test.js,test/devtest.js,test/issue_69.js,test/tunnel_ssh_user_commands.js, andtest/ssh tunneling argument injection.js; their scenarios are covered by the offline unit suite or the README-mirrored live tests. - Reworked
test/lots_of_commands.jsto queue 60 harmlessechocommands instead of repeatedsudo apt-get updatecalls. - Modernized
test/pipe.js,test/ssh_user_command.js,test/sudo_no_pass.js, andtest/timeout.jswithdotenv,logFile()/log(), current environment variable names, andrequire('../src/ssh2shell'). .gitignore— removed the obsoletetest/devtest.jsentry.
npm test— 115 tests pass on the current build and 115 on the frozen baseline artifact, withcheck:buildconfirminglib/is in sync first.node --checkpasses for every kept live test.npm pack --dry-runstill contains onlyREADME.md,LICENSE,lib/, andpackage.json.
- Static host-only networking (no gateway):
- server1
192.168.44.10/ hostnameserver1 - server2
192.168.44.11/ hostnameserver2 - server3
192.168.44.12/ hostnameserver3 /etc/network/interfacesusesifupdownwithenp0s3 inet static; the previous DHCP file is kept as/etc/network/interfaces.dhcp-backup.- Each clone has a unique
/etc/machine-idand hostname.
- server1
- Test user structure:
ssh2shell— bootstrap/admin account, sudo, admin key.tester— primary automated login, sudo with password, test key.nopasswd— sudo withNOPASSWDon server2, test key.suuser— no sudo,sutarget, test key.kbduser— server1 only, keyboard-interactive only (PasswordAuthentication nounderMatch User kbduser).- Legacy
userremoved fromsudo; the legacyuser ALL=(ALL) NOPASSWD:ALLline removed from/etc/sudoers.
- Keys:
test/certs/test_ed25519(.pub)for test logins and nested hops.test/certs/admin_ed25519(.pub)forssh2shell.- Private keys are gitignored; the
.pubfiles andtest/certs/README.mdare tracked. - The test private key is installed as
~/.ssh/id_ed25519for hop users on each host.HOP_KEY_PATH/HOP2_KEY_PATHoverride the remote path when a key is installed elsewhere or under another name.
- Live tests:
- General tests authenticate with
PRIVATE_KEY_PATHthroughtest/utils/private_key.js. Passwords remain only where the protocol needs them:sudo_su.js(sudo/su) andkeyboard-interactive.js. tunnel.jsandchaining.jsusessh.identityFilefor nested hops, so the hops use the key instead of a nested password.prompt_response.jsandcommand_timeout.jsuse localreadprompts instead ofapt-get, so they run without internet access.sudo_no_pass.jsusessudo -nagainst server2 and thenopasswduser, so a missingNOPASSWDrule fails instead of falling back to a password.keyboard-interactive.jsusesKBD_USER/KBD_PASSWORD.
- General tests authenticate with
.env-exampledocumentsPRIVATE_KEY_PATH,KEY_PASSPHRASE,HOP_KEY_PATH,HOP2_KEY_PATH,KBD_USER,KBD_PASSWORD,NOPASSWD_USER,NOPASSWD_PASSWORD, and the per-host static addresses.- Library fix:
_loadDefaultsno longer installs the fallback keyboard-interactive handler when the caller already supplied an instance or host handler. Two handlers both calledfinish(), resetting the handshake (ECONNRESET).
sshd -tpasses on server1;kbduserpassword auth is refused and keyboard-interactive succeeds.- Key and password logins verified for
tester,nopasswd, andsuuseron all three hosts;ssh2shellverified with the admin key. - Static addresses and hostnames verified; all three machine-ids are unique.
npm test— 116/116 pass after rebuildinglib/.- Live suite — 17/17 pass with key-based logins and no errors (including the
nested
tunnel.js/chaining.jshops and the keyboard-interactive test).
test/provision/provision.jsrebuilds a live-test VM from a fresh Ubuntu install throughssh2shell, using the same hostname, static address, users, sudo rules, keys, andsshdsettings as L7.7.- Per-server config lives in
test/provision/.env(gitignored), withtest/provision/.env.examplecommitted. Values resolve fromPROVISION_<ROLE>_*first, then genericPROVISION_*, then the built-in defaults; the repository.envsupplies the live-test passwords and key paths. - Roles
server1,server2, andserver3are selected by the first CLI argument orPROVISION_ROLE. - Bootstrap login uses
PROVISION_<ROLE>_USER/..._PASSWORD/..._KEY_PATH, falling back toUSER_NAME/PASSWORDand the test key...._KEY_PATH=noneforces password auth. PROVISION_<ROLE>_HOSTdefaults to the role's static IP, so a DHCP install can be provisioned before the address changes.- Passwords and key material are sent as base64; they are not written as bare text to the session log.
sudoers,sshd, and network changes are validated. A failedsudoersorsshdcheck restores the backup; a failed static-network bring-up restores the previous netplan directory or/etc/network/interfaces.dhcp-backup.- Network is applied last because changing it can drop the session.
- The network stack is detected at runtime: netplan on Ubuntu 26.04,
ifupdownon Ubuntu 18.04. The netplan path writes/etc/netplan/99-ssh2shell.yaml, disables cloud-init network regeneration, and validates withnetplan generate. - The
sshdpath selectsKbdInteractiveAuthenticationon OpenSSH 8.7+ andChallengeResponseAuthenticationon older releases, and updates/etc/ssh/sshd_config.d/*.confso a cloud-imagePasswordAuthentication nocannot override the main file. PROVISION_<ROLE>_REGENERATE_MACHINE_ID=trueregenerates the id for a cloned VM; the default leaves a fresh install's id alone.
- Per-server config lives in
test/provision/README.mddocuments the role matrix, environment variables, usage, output markers, and caveats..env-examplepoints totest/provision/.env.exampleand keeps the shared key overrides andSSH2SHELL_PASSWORD.npm run provision -- <role>runs the script.
node --check test/provision/provision.jspasses.- The generated network command passes both
bash -nandsh -n. - Ran the script against all three roles on the existing Ubuntu 18.04 VMs, with
test/provision/.envsupplying the per-server config. Every run reportedsudoers: OK,sshd: OK, andnetwork: OK; the repeated server3 run was idempotent. - The OpenSSH version check selected
ChallengeResponseAuthenticationon the 18.04 VMs andsshd -Treported the expected effective value on each role. The 26.04 path selectsKbdInteractiveAuthentication. - After provisioning, the full live suite passes: 17/17 (
simple,private_key,keyboard-interactive,fingerprint,sudo_su,prompt_response,command_timeout,multiple_primary_hosts,tunnel,chaining,notifications,bash_script,lots_of_commands,pipe,ssh_user_command,sudo_no_pass,timeout). npm test— 116/116 pass.- The netplan path was exercised on three fresh Ubuntu 26.04.1 VMs
(OpenSSH 10.2p1, netplan, interface
enp0s3). Each role ran once withAPPLY_NETWORK=falseto validate the generated config, then with the default to apply it. All three runs reportedsudoers: OK,sshd: OK,network: OKand exited 0. - After the static apply,
server1,server2, andserver3answered on192.168.44.10,.11, and.12respectively. On each hostsshd -Treported the expected effective auth settings,/etc/netplan/99-ssh2shell.yamlwas the only netplan file, the original config was preserved in/etc/netplan.ssh2shell-bak, and cloud-init network config was disabled.kbdinteractiveauthenticationwasyeson server1 andnoon server2 and server3. Key login astesterworked on all three. - The full live suite passes against the rebuilt 26.04 VMs: 17/17 (
simple,private_key,keyboard-interactive,fingerprint,sudo_su,prompt_response,command_timeout,multiple_primary_hosts,tunnel,chaining,notifications,bash_script,lots_of_commands,pipe,ssh_user_command,sudo_no_pass,timeout). - The rollback path (restore the previous netplan directory or
/etc/network/interfaces.dhcp-backupwhen the static address does not come up) is still unexercised. Only the successful apply path has run on 26.04.
- Ubuntu 26.04's shell emits bracketed-paste (
ESC[?2004h/ESC[?2004l) and OSC 3008 shell-integration markers. The defaultasciiFilterremoved only the ESC byte, leaving the printable payload ([?2004l,]3008;...) incommandCompleteresponses andsessionText. - Added
stripTerminalEscapesinsrc/ssh2shell/util.jsand applied it beforeasciiFilterwhen ASCII filtering is enabled. It removes complete CSI, OSC, and two-character escape sequences. disableASCIIFilterstill keeps the sequences.
- New unit test covers a response containing both bracketed-paste and OSC 3008 sequences; the current build strips them and the baseline fixture still leaves the payload.
npm run test:unitandnpm run test:baseline— 117/117 pass.node test/simple.jslog no longer contains]3008;...,[?2004l, or[?2004h.
- Debug/verbose and
msg:notification messages now omit the host prefix when the session has a single primary host and no nested hosts. Repeating the address on every line added noise to single-host logs. - Multi-primary and nested-host sessions keep the prefix for disambiguation. The nested flag is sticky so prefixes do not disappear when the nested queue empties.
sessionTextand callback output are unchanged.
- New unit tests cover a single host, multiple primary hosts, nested hosts, and
msg:notes. npm run test:unitandnpm run test:baseline— 121/121 pass.node test/simple.jsnow logsNote: ...without the host address.
- Added
scripts/run-live.js, a cross-platform runner for the live tests. The default batch covers 12 key use cases;--allruns every test,--listshows the selection, and positional names run a specific subset. - Each test runs in its own process with a configurable timeout (default 180s).
scripts/live-instrument.jsis preloaded with--requireto record the connect callback, session-text length, anderrorevents. The runner also applies per-test session/log expectations, so a failed connection cannot pass on exit code alone. - Added
npm run test:liveandnpm run test:live:all.
npm run test:live— 12/12 pass.node scripts/run-live.js --all— 17/17 pass.npm test— 125/125 unit and baseline pass.
_sshConnectnow starts a nested connection authenticated when the nested host has neither a password nor a passphrase. The first remote shell prompt is then treated as success. Previously the first prompt was treated as a failed connection, so key-only nested hosts never ran their commands; the live tests only appeared to pass because the callback still fired with the first host's text.- Password and passphrase nested connections still start unauthenticated so the first credential prompt is answered.
- New unit tests cover key-only, password, and passphrase nested auth state and the first-prompt success path.
node scripts/run-live.js tunnel chaining— both pass and include the nested host output.npm test— 125/125 unit and baseline pass.
- Moved the 17 live test scripts from
test/totest/live/. The support directories (certs,provision,utils,logs) and the offline suites (unit,fixtures) stay attest/. scripts/run-live.jsnow discovers tests intest/live/, so an unrelated script dropped intest/is not picked up as a live test.- Updated the test imports, the
pipeoutput path, README links, and.env-examplereferences.npm packstill publishes onlylib/; the.npmignore/testrule is unchanged and already covers the whole folder.
npm run test:live— 12/12 pass.node scripts/run-live.js --all— 17/17 pass.npm test— 125/125 unit and baseline pass.npm pack --dry-run— onlylib/,README.md,LICENSE, andpackage.json.
- Added
test/README.mdas the entry point for the testing environment: folder layout, offline commands, the curated live batch and runner options, environment variables, host roles, provisioning, how to add a live test, and where the logs go. - Trimmed the main
README.mdDevelopment section to install/test plus a link totest/README.md. The detailed live-test and provisioning material lives with the tests;test/certs/README.mdandtest/provision/README.mdremain the deep references.
- Relative links in
test/README.mdresolve to existing files. - No code changes;
npm testand the live runner are unaffected.
- Added the
progresshost option. It shipped opt-in (defaultfalse) at L7.15; L7.17 changes the default totrue(opt-out). When enabled and stderr is a TTY, the class writes a one-second heartbeat toprocess.stderrwhile a command is in flight. The indicator never modifiessessionTextor themsgstream. - Progress starts for real queued commands and nested
sshconnections, not for password/passphrase writes or internalexitcommands. It stops on command completion, timeout, error, close, and host change. - A host label (
[host]) is written only when the session spans multiple primary or nested hosts. A caller-suppliedmsgbreaks the progress line first so output stays readable. The heartbeat is suppressed whiledebugorverboseis enabled, because those modes already report internal steps. - The stream and interval are injectable instance state (
_progressStream,_progressInterval) so the unit tests can simulate a TTY without touching the real terminal.
npm test— 138/138 unit and 138/138 baseline pass. The newtest/unit/progress.test.jsskips its assertions against the frozen baseline, which has noprogressoption.npm run test:liveandnode scripts/run-live.js --all— unchanged; the indicator is TTY-gated and was off by default at L7.15.
test/live/tunnel.jsnow chainsjump -> bastion (server2) -> target (server3), so the live suite exercises two nestedsshcommands and the back-out path through each connection.- The runner's
tunnelcheck now requires server3 output as well, so the test fails if the final hop is not reached.
node scripts/run-live.js tunnel chaining— both pass.node scripts/run-live.js --all— 17/17 pass.
progressnow defaults totrue; an explicitprogress: falseopts out. Signed off because the output is purely visual, unobtrusive, TTY-gated, and has no process impact.test/live/progress.jsnow exercises the default instead of setting the flag.test/unit/progress.test.jscovers the default-on and explicit opt-out cases, andtest/unit/api-baseline.test.jsasserts the new default.- README,
docs/API-BASELINE.md, andtest/README.mddescribe the opt-out.
npm test— 139/139 unit and 139/139 baseline pass.node scripts/run-live.js progress— 1/1 pass.node scripts/run-live.js --all— 18/18 pass.
Signed-off-by: user review of docs/CLOSE-SEMANTICS.md and the stop/close work.
Released in v3.2.0.
src/ssh2shell.js— addedstop(reason)as the whole-run abort. It clears every command and host queue, sendsCtrl-Cwhen a command is in flight, keeps and drainsexitCommandsbounded byidleTimeOut, finalizes each visited host once, closes once, and calls the callback once.src/ssh2shell.js—close()is a safe shutdown;close({ graceful: true })runs queued exit commands and backs out of nested shells first. Remaining primary hosts still run, matching the compatibility contract.src/ssh2shell.js— centralized host finalization sosessionTextis complete beforeendand the final callback, including when a transport drop skips the streamfinishevent.src/ssh2shell.js— a connection close withhad_erroremits anErrorwithlevel = 'Connection close'andhadError, instead of a bare string.src/ssh2shell.js— command handlers can setskipCommands,skipHosts,skipPrimaryHosts, andabort;stop()andclose()are safe from any handler.src/ssh2shell.jsandsrc/ssh2shell/defaults.js— sudo rejection emits a visiblemsg, setssudoFailed, and callsstop('sudo-failed')only whenabortOnSudoFailureis true.test/unit/shutdown.test.js— stop/close, finalization, handler flags, and sudo-failure coverage. Existing unit tests were updated for the new payloads and messages.test/live/stop_on_failure.js,close_from_handler.js,stop_multiple_hosts.js,graceful_close.js,sudo_rejected.js, andtransport_drop.js— live coverage for the new paths;scripts/run-live.jsapplies per-test checks and includes them in the curated batch.docs/CLOSE-SEMANTICS.mdanddocs/ERROR-HANDLING.md— the stop/close matrix, flags, finalization order, and error payloads.README.mdandtest/README.md— the API table, stop/close guidance, sudo behavior, and live-test layout were updated to match.
npm test— 149/149 pass on the current build and 149/149 on the frozen baseline, withcheck:buildconfirminglib/is in sync.npm run test:live— 18/18 curated tests pass.node scripts/run-live.js --all— 24/24 live tests pass.git diff --check— clean.
Signed-off-by: user request for an opt-in full prompt match.
Released in v3.3.0.
src/ssh2shell/util.js—compilePromptRegex()accepts a string orRegExp, wraps it as(?:source)$, stripsg/y/m, and reports whether it fell back.compilePrompts()uses it forstandardPromptand returns the fallback flag.src/ssh2shell.js—_loadDefaultslogs a debug message when the configured regex is invalid and falls back tostandardPrompt.test/unit/prompt-regex.test.js— 6 tests: full-prompt matching,RegExpflags, invalid fallback, no false completion on output ending in a prompt character, sudo completion, and nested-SSH completion.
npm test— 169/169 unit and 169/169 baseline.- The suite passes against both the current build and the frozen baseline; the
opt-in cases are guarded by
isBaseline().
Signed-off-by: user request for an opt-in handled response.
Released in v3.3.0.
src/ssh2shell.js—stripEchoedCommand()removes the command echo (tolerating PTY CR/LF wrapping),_handleCommandResponse()removes the echo and trailing prompt and trims, and_commandCompleteemits the handled payload plusdetails.rawResponse.src/ssh2shell/defaults.js—commandResponsedefaults to'raw', so the secondcommandCompleteargument is unchanged unless opted in.test/unit/command-response.test.js— 5 tests: raw default, echo/prompt removal withsessionTextstaying raw, PTY-wrapped echo, no-regex behavior, and a response without the echoed command.
npm test— 169/169 unit and 169/169 baseline.sessionTextremains raw; only thecommandCompletepayload changes.
Signed-off-by: user request for library-owned retry re-arming.
Released in v3.3.0.
src/ssh2shell.js—_scheduleIdleTimeoutincrementscommandTimeoutAttempt, computesfinal, emitsdetails, and re-arms for non-final attempts unlessretryCommandTimeoutisfalseor a data event already scheduled the next timer.toNonNegativeInteger()coerces the retry count._runCommandresets the attempt count when the same command is written, and_commandCompleteresets it after completion. The default handler closes only on the final attempt.src/ssh2shell/defaults.js—commandTimeoutRetriesis coerced to a non-negative integer andcommandTimeoutAttemptstarts at0.test/unit/timeout-retries.test.js— 9 tests: unchanged single-timeout default, re-arm to the configured count, handler answer mid-command, no re-arm afterstop(),retryCommandTimeoutopt-out, final-only default close, and the three reset points.test/live/timeout_retries.js— new live coverage forcommandTimeoutRetriesanddetails.final; the originaltest/live/timeout.jsis kept unchanged as the handler-managed comparison.
npm test— 169/169 unit and 169/169 baseline.node scripts/run-live.js timeout timeout_retries— both live prompt/timeout tests pass. The original keeps the handler-managedFirstPassapproach; the new one answers on a non-final attempt and closes on the final one.
Signed-off-by: user request for the silent-command and "no output yet" distinction.
Released in v3.3.0.
Superseded in 4.0.0. The idle timer is now always armed when a command is written, so a silent command times out without an opt-in. The
commandStartTimeoutoption anddetails.noOutputwere removed. A detected prompt cancels the timer, so a silent command that returns to the prompt still completes normally. Seetest/unit/command-start-timeout.test.js.
src/ssh2shell.js—_runCommandarms the idle timer whencommandStartTimeoutistrueand resets_commandSawDatafor the new command._onDatamarks data as seen once a command is in flight._scheduleIdleTimeoutaddsnoOutputto thecommandTimeoutdetails and logs whether no output or no prompt caused the timeout.src/ssh2shell/defaults.js—commandStartTimeoutdefaults tofalse, so the data-driven timer is unchanged unless opted in.test/unit/command-start-timeout.test.js— 5 tests: default no-timer behavior, start-timer arming,noOutputtrue for a silent command,noOutputfalse after partial output, and the per-command reset.
npm test— 179/179 unit and 179/179 baseline.- The default test runs against both artifacts; the opt-in cases are guarded by
isBaseline().
Signed-off-by: user request for opt-in stderr in the command response.
Released in v3.3.0.
src/ssh2shell.js—_captureStderr()filters and buffers stderr,_mergeStderr()appends the trimmed capture with one newline, and_commandCompletemerges it into the raw or handled response andsessionTextand exposesdetails.stderr. The stderr handler captures before emittingstderrData, and_runCommandresets the buffer per command.src/ssh2shell/defaults.js—captureStderrdefaults tofalse.test/unit/stderr-capture.test.js— 5 tests: default no-merge behavior, raw merge anddetails.stderr, handled-response merge, escape filtering, and the per-command reset.
npm test— 179/179 unit and 179/179 baseline.stderrDatastill fires in every case; the default payload is unchanged.
Signed-off-by: user request to replace nested ssh host hops and to make silent
commands time out.
Released in v4.0.0.
src/ssh2shell.js—_connect(parent = null)owns primary and hop connections; a hop opens aforwardOutchannel and logs in over it. Records form an ancestor stack with per-record listeners and timers._failContext()contains hop failures,_endPrimary()advances past a failed primary, and_closeContext()is the only record teardown._sanitizeResponse()slices after the last echoed command. The command idle timer is armed when a command is written, reset by_onData, and cancelled by prompt detection.src/ssh2shell/defaults.js—commandStartTimeoutis gone andpassphrasePromptis no longer defaulted.- Removed
src/ssh2shell/ssh-command.js,buildSshCommand(),shellQuote(),shellControlChars,_sshConnect(),_processSSHPrompt(),sshAuth/sshToNextHost,exitCommands, and theSecurity Alertpath. test/unit/host-hop.test.js— record stack, hop transport, containment, primary advance, and host-list validation.test/unit/command-start-timeout.test.js— always-on timeout, a silent command returning to a prompt, and prompt-race cancellation.test/live/host_traversal.jsandtest/live/host_faults.js— depth-first traversal and contained-fault acceptance tests.test/utils/module-target.jsandtest/utils/module.js—SSH2SHELL_MODULEselection forsrc,lib,baseline, or a repo-relative path.docs/NEXT-HOST-CONNECTION.md— design and implementation record.
npm run test:src— 163/163.npm test— 155 pass, 8 baseline-skipped.- Live suite against
src— 28/28, run twice. - Clean-VM provisioning (
SSH2SHELL_MODULE=src) —sudoers: OK,sshd: OK,network: OK.
Pre-release cleanup of the instance and host-config surface. Released in
v4.0.0 on next-host-connection.
Breaking changes
host.msgis renamed tohost.onMsg. The Hubot-eramsg: { send: fn }shape is removed.server.hashMethodis removed; usehostHash.sshObj.stopis removed; useabort.- Host
idleTimeanddataIdleTimeare removed; useidleTimeOutanddataIdleTimeOut. Instance-levelSSH.idleTime/SSH.dataIdleTimeremain.
Host config no longer gains library state
_loadDefaultsresolves default command handlers per record instead of writing instance-capturing closures into the host object.- The
{ send }message shape is no longer rewritten intohost.msg. applyHostDefaultsno longer writesserver.hashKey.
Instance surface
- CoffeeScript-era prototype defaults moved into the constructor; the prototype default block is deleted.
- Constructor binds reduced to the public entry points,
_connect/_connectHop, and the three default command handlers. - Dead
_boundListener,_detachListener,_boundListeners, and prototype no-op handlers removed. ssh2Clientis now_ssh2Client, marked as an internal test seam.commandand_bufferare saved on the record and restored by_restoreContext(), so backing out of a hop resumes the parent's command state.
Docs
- README:
onMsgreplacesmsg; removed aliases deleted; active-host mirrors and internal members reduced to one Troubleshooting note; host-config mutation and handlerthisdocumented; garbled-buffer workaround removed. docs/API-BASELINE.md,docs/CLOSE-SEMANTICS.md, anddocs/NEXT-HOST-CONNECTION.mdupdated for the removed aliases.
npm run test:src— 166/166.npm run test:baseline— 158 pass, 8 baseline-skipped.
Items explicitly deferred until after the mechanical refactor. Each one changes observable behavior or security posture and needs its own level and sign-off.
- Done at L7.6 (signed off): audit each remaining legacy live test script.
The README-mirrored tests are
simple.js,private_key.js,keyboard-interactive.js,fingerprint.js,sudo_su.js,prompt_response.js,command_timeout.js,multiple_primary_hosts.js,tunnel.js,chaining.js,notifications.js, andbash_script.js. The audit deleteddevtest.js,Config-poperties-test.js,issue_69.js,ssh-options-regression.js,tunnel_ssh_user_commands.js, andssh tunneling argument injection.js; their scenarios are covered bytest/unit/ssh-connect.test.js,test/unit/hosts.test.js, andtest/unit/api-baseline.test.js. It kept and modernizedlots_of_commands.js,pipe.js,ssh_user_command.js,sudo_no_pass.js, andtimeout.jsas manual live-host checks. - Done at L7.24 (signed off, superseded by
L7.24 deliverables):
replace the nested-host
ssh ...command string with chainedssh2connections. The hop now opens anssh2forwardOutchannel and logs in over it, so there is no shell quoting, no remotesshbinary, and hop authentication uses the runner's local credentials. Nested hosts run on the normalonData/commandCompletepath. The old_sshConnect/buildSshCommand()path andsrc/ssh2shell/ssh-command.jsare removed. - Done post-L5 (signed off): map the documented
dataIdleTimeOutto the internaldataIdleTimetimer (default 500 ms).dataIdleTimeOutwins; the undocumenteddataIdleTimeremains as a fallback. - Done post-L5 (signed off): audit truthiness-based defaults.
windowandptynow use nullish checks, so an explicitfalsesurvives. - Done post-L5 (signed off): remove the documented
pipe/unpipesurface from the README. They are stream-level operations on the instance, not host config or host events; the inheritedpiperemains available. - Done post-L5 (signed off): map
forceProtocolVersion/forceAddressTypeto validsshflags (-1/-2,-4/-6).trueselects-2/-4; invalid values return aSecurity Alerterror. - Done at L4: removed
_nextPrimaryHost's bare@_runExitreference as dead code; the normal back-out path is_runExitvia_previousHost. - Done post-L5 (signed off, superseded at L7.18): sudo password rejection
was a debug notification, not an
errorevent. L7.18 makes it a visiblemsg, setssshObj.sudoFailed, and optionally stops the run withabortOnSudoFailure: true. - Done post-L5 (signed off): resolve the error-handling findings in
docs/ERROR-HANDLING.md. The default listener guards_stream.close()(F1/F3), Connection/Shell/Connection.connect errors classify by live stream state (F2), the optional callback runs before the close (F4), the hostonErroris prepended (F5), the defaulterrorlistener is installed once (F6),_streamis reset per primary host (F10), and the sudo timeout passesthis.connection(F11). F8 and F9 remain informational by design. - Done post-L5 (signed off): compile prompts/filters per host, not once per
instance.
_loadDefaultsrebuilds the compiled regexes from the currentsshObjon every call. See Per-host prompt/filter compilation. - Done post-L6.1 (signed off): remove the L5-added verbose log in
_sanitizeResponse. It re-printed the command-echo prefix on every prompt check, so verbose tunnel runs repeated bare command lines (echo ...,exit,ssh ...) and showed a strayssprefix. The method now returns the sanitized response without logging, matching the baseline. Test:test/unit/api-baseline.test.js— "does not emit the command echo as a verbose message". - Done post-L6.1 (signed off): hide credentials in debug/verbose output by
default and add the per-host
exposeCredentialsopt-in._systemMsgscrubs the configured password/passphrase from strings and masks credential keys in object dumps, so the sudo/nested-SSH password messages, the verboserunCommandecho, and the config dump show[REDACTED]. The frozen baseline still leaks the raw values;test/unit/credentials.test.jsis level-aware. A live verbose tunnel run confirmed no plaintext password in the log and[REDACTED]in its place. - Done post-L6.1 (signed off): let timer values be set on the instance
(
SSH.idleTime/SSH.dataIdleTime) without_loadDefaultsreplacing them with the hard-coded 5000 / 500 defaults. The first load captures the instance base; a hostidleTimeOut/dataIdleTimeOutoverrides it, and_removeListenersrestores the base when leaving the host so a host-specific value does not leak into the next.idleTimeis accepted as a legacy host alias. Non-positive/non-numeric values are treated as unset. Test:test/unit/timers.test.js. - Done post-L6.1 (signed off): keep the default
msglistener attached while hosts are swapped so_systemMsgoutput is not lost between_removeListenersand the next_loadDefaults._loadDefaultsnow falls back to the stored default handler when a host has nomsg. The live test scripts sharetest/utils/logging.jsand run againstsrc/so they can be used before a build. Tests:test/unit/l5-behavior.test.js— message-sink, duplicate-listener, and default-handler restoration cases. - Done post-L7 (signed off): remove the misspelled
passwordPromtandpassphrasePromtfallbacks. OnlypasswordPromptandpassphrasePromptare read now; the frozen baseline still honours the aliases.test/unit/api-baseline.test.jsis level-aware for the difference. - Done at L5:
_connectionsandsshObjare assigned per instance in the constructor, so instances no longer share prototype state beforeconnect(). - Done at L5: the default
keyboard-interactivehandler now callsfinish([''])(baseline default response) so the handshake cannot stall. - Done at L5: multi-host
sessionTextduplication._previousHostnow removes the outgoing host's handlers, so no stalecommandComplete(or similar) handler fires against the new current host.- Test:
test/unit/hosts.test.js— "drops the secondary host commandComplete handler after backing out". The baseline branch still characterizes the old leak; the current branch asserts no stale handler. - Sign-off: remove stale handlers; each host's text appears once.
- Test:
The provisioning script exercises the state machine harder than the unit tests:
one very long ;-joined command per step, automatic sudo, large echoed input,
a command that changes the network, and a session that can drop. The live suite
still passes, but the run exposed edges worth their own level before changing
behavior.
What the run confirmed
commandCompletefires after the standard prompt is detected and before_nextCommand()shiftssshObj.commands. That ordering is what makes output-driven queue changes work; it is currently an implementation detail, not a documented contract.- The
sudopassword prompt is handled automatically for any command whose text containssudo, including the long provisioning commands. - Markers such as
SSH2SHELL_SUDOERS_OKare safe to match withincludes(). commandTimeoutdoubles as a retry point. A timeout handler can answer the prompt and write to the stream; the nextonDataeither reachescommandCompleteif the prompt is detected or times out again.test/live/timeout.jsuses a hostFirstPassflag to stop that loop. The flag is caller-owned, not library state.- Backgrounding
netplan apply/ifupand polling for the address avoids the connection drop that a foreground network change causes.
Edges observed
- Prompt detection is a trailing character class:
standardPromptcompiles to[>$%#]\s?$. Output ending in%,$,>, or#can complete the command early, so the next command is sent while the previous one is still running. Provisioning avoids this because its last line is a marker ending inK. This is deliberate: the default set targets the most-used shell prompts, not every interactive prompt. - The PTY echoes long commands with hard wraps.
_sanitizeResponse()strips the echo by exact string match, so a wrapped echo is not removed. The prompt check is end-anchored and still works, but password-prompt matching sees the echo, andcommandCompleteresponses contain it. commandCompletereceives the_bufferafter the color/ASCII filters: echoed command, wrapping, and the trailing prompt. It is not normalized output. Raw content was a deliberate choice so a caller can do its own processing, but the handler already receivescommand, so repeating the echoed command inresponseis redundant. The preferred direction is to pass the handled response and keep the raw buffer only as an optional extra.commandProcessingreceives chunks before filtering, so handlers can see ANSI, partial prompts, and the same prompt more than once.commandCompletedoes not fire forexitor empty commands, and the timeout itself does not emitcommandComplete(a subsequent answeredonDatacan). The old nested-sshgap was a stage-engine difference, not a missing event; L7.24 removed that stage, so nested hosts now use the normalonData/commandCompletepath.- A command that restarts networking or
sshdin the foreground can drop the session or exceedidleTimeOut; the current workaround isnohup ... &plus polling. - stderr is emitted through
stderrData, not appended to_bufferby default. stderr is only really handled at thessh2connection layer; the command layer does not merge it unlesscaptureStderris enabled. With a PTY OpenSSH usually merges it, but the response/session text should not rely on that. - Prompts that are not the standard prompt (
su,sshhost-key confirmation, pagers, installers,read, custom/localizedsudo -p) are caller-handled incommandProcessingorcommandTimeout, not by the library. Prompt answering cannot move tocommandComplete, which runs only after the prompt returns.
Candidate improvements (behavior changes; implemented items are marked)
- Implemented: pass the handled response to
commandComplete: remove the echoed command, trailing prompt, ANSI, and wrap artifacts. The handler already receivescommand, so this avoids redundant parsing. The opt-incommandResponse: 'handled'keeps the raw buffer asdetails.rawResponse. See L7.20 deliverables. - Implemented: keep the default standard-prompt set small (the most-used
prompts) and add an opt-in full regular expression (
standardPromptRegex) for callers that need to anchor touser@host:~$. See L7.19 deliverables. - Implemented: treat
commandTimeoutas a first-class retry path: answering a prompt from the timeout handler can resume normal completion, andcommandTimeoutRetriesgives the library an attempt counter instead of per-hostFirstPassflags. See L7.21 deliverables. - Implemented: define and test the queue-mutation contract:
sshObj.commandspush/unshift/splice fromcommandComplete, plus explicit skip/stop flags (skipCommands,skipHosts,skipPrimaryHosts,abort/stop) checked by_nextCommand. The running command is not in the queue, andstop()drainsexitCommandsbefore closing. Seedocs/CLOSE-SEMANTICS.md. - Implemented: make termination explicit and race-free. Draining the queues
and letting
_runExit()close still works, andthis.close()/stop()fromcommandCompleteno longer let_nextCommand()write against a closing stream. Seedocs/CLOSE-SEMANTICS.md. - Implemented: handle silent long-running commands.
commandStartTimeoutarms the idle timer when the command is written, anddetails.noOutputdistinguishes "no output yet" from "prompt missed". See L7.22 deliverables. This was superseded in 4.0.0: the timer is always armed at command start and bothcommandStartTimeoutanddetails.noOutputare removed. - Implemented: opt-in stderr capture in the command response with
captureStderranddetails.stderr;onStderrDataremains the always-on event. See L7.23 deliverables.
These are library changes, not provisioning scope. The netplan run should be completed first so the findings are not mixed with an untested network path.
These are sensible defaults until confirmed:
- README reconciliation: completed at L7.1/L7.2. The README is documentation, not a source of truth; it is corrected to match the code. The discrepancy table in docs/API-BASELINE.md is fully resolved.
- Node target:
>=18(applied at L2:engines.nodeis now>=18.0.0). CI exercises Node 18, 20, 22, and 24. lib/artifact:lib/ssh2shell.jsstays committed and in sync; the published package contains onlylib/(plus the README,LICENSE, andpackage.json), andprepublishOnlyruns the full suite. There is no separate build-only publish flow.- Push policy:
masterand the release tags are pushed toorigin. Refactor tagsL7-L7.3are onorigin;L0-L6.1andL7.4-L7.6remain local, andL7.7onward have no tag. - Live hosts: the local
192.168.44.0/24VMs are used for the manual live suite (see L7.7);npm teststays offline. - Behavior-changing fixes: require explicit sign-off. L5 and L6 changes were approved; any remaining defect fixes still need their own sign-off.
- Branch:
Refactoring(identical tomasterat baseline) - Version:
2.0.14 - Source:
src/ssh2shell.coffee(739 lines) - Compiled:
lib/ssh2shell.js(~1044 lines, in sync modulo line endings) - Tests: 19 live integration scripts in
test/, plus 57 offline unit tests intest/unit/; no CI yet - Tooling: Node 26.13.0, npm 12.2.2, CoffeeScript 1.12.7