From b0e0496003ee17cea452b705384a174534f70765 Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Mon, 23 Nov 2026 15:04:19 +1300 Subject: [PATCH] fix: address 4.1.0 release-candidate review findings Clear the graceful-close timer on primary transitions, restore debug and verbose overrides from host config, and redact credential-named properties on class instances including nested and cyclic values. Add regression tests, refresh coverage evidence, and document AI-assisted workflows and the release fixes. --- .github/PULL_REQUEST_TEMPLATE.md | 2 +- CHANGELOG.md | 18 +- CONTRIBUTING.md | 8 +- README.md | 2 +- REFACTORING.md | 8 +- docs/AI-ASSISTED-WORKFLOWS.md | 239 ++++++++++++++ docs/MIGRATING-4.md | 4 +- docs/NEXT-HOST-CONNECTION.md | 18 +- docs/PUBLISHING.md | 2 +- lib/ssh2shell.js | 35 ++- lib/ssh2shell/util.js | 25 +- src/ssh2shell.js | 35 ++- src/ssh2shell/util.js | 25 +- test/README.md | 3 +- test/coverage.md | 453 ++++++++++++--------------- test/unit/behavior-hardening.test.js | 130 ++++++++ 16 files changed, 719 insertions(+), 288 deletions(-) create mode 100644 docs/AI-ASSISTED-WORKFLOWS.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 27d4847..ac2dd15 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -4,7 +4,7 @@ ## Why - + ## How it was tested diff --git a/CHANGELOG.md b/CHANGELOG.md index dffc4b4..9d2f2b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,17 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. the standard host prefix and credential redaction. The internal `_systemMsg` name is replaced; the frozen baseline keeps it for comparison tests. +### Fixed + +- Applied four fixes from the release-candidate review: a graceful-close timer + no longer survives a primary-host transition, debug/verbose overrides are + reapplied when an ancestor is restored and when an override is cleared, + and class instances with credential-named properties are redacted in verbose + config dumps. A follow-up review tightened the latter two: restored flags + come from the host config rather than a cached effective value, nested + credentials and cycles on class instances are redacted too, and clearing an + override preserves the host's configured value. + ### Development - Added live coverage for keyboard-interactive authentication on a nested hop @@ -32,10 +43,13 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. 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 + traversal, shutdown flows, and behavior 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% + records the local coverage review and full miss-overlap analysis (98.15% combined line coverage). +- Added `docs/AI-ASSISTED-WORKFLOWS.md` with reusable prompts and approval + boundaries for AI-assisted session setup, releases, reviews, and coverage + refreshes. ## [4.0.4] - 2026-11-18 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8c61965..b113cf0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,7 +23,13 @@ documents the environment and the curated batch. - Branch from `master`. `master` requires a pull request, the CI matrix, and the live suite, so direct pushes are rejected. - Keep the change focused, and update `README.md`, `docs/`, and `CHANGELOG.md` - when behaviour changes. + when behavior changes. - Use `npm run test:live` for connection, command-flow, and hop changes. Run `npm run test:live:all` before a release. - The release process is in [docs/PUBLISHING.md](./docs/PUBLISHING.md). + +## AI-assisted work + +Reusable prompts and the boundaries that apply to AI assistants are in +[docs/AI-ASSISTED-WORKFLOWS.md](./docs/AI-ASSISTED-WORKFLOWS.md). The approval +and release rules in that document apply to human contributors too. diff --git a/README.md b/README.md index 07463c3..9afe02f 100644 --- a/README.md +++ b/README.md @@ -730,7 +730,7 @@ const host = { return; } - // Fall back to the default behaviour: record the response and close. + // Fall back to the default behavior: record the response and close. this.emit( 'error', `${this.sshObj.server.host}: Command timed out after ${this.idleTime / 1000} seconds`, diff --git a/REFACTORING.md b/REFACTORING.md index 9024340..1505185 100644 --- a/REFACTORING.md +++ b/REFACTORING.md @@ -411,9 +411,9 @@ Signed-off-by: user review of the backlog, before further error-handling work. ### L6.1 deliverables (approved optimisation and robustness follow-ups) Signed-off-by: user selection of the optimisation review's "safe set + approved -behaviour fixes" option. +behavior fixes" option. -#### Behaviour-neutral cleanups +#### behavior-neutral cleanups - `src/ssh2shell.js` — top-of-file and `_systemMsg` comments now describe the current build instead of the L1 baseline; removed the orphaned numbered @@ -434,7 +434,7 @@ behaviour fixes" option. `lib/` matches `src/`; `npm test` runs it before the suites, so a stale build cannot silently pass. -#### Behaviour fixes (signed off) +#### behavior fixes (signed off) - `src/ssh2shell.js` — post-auth `_processSSHPrompt` output that matches no prompt now re-arms the idle timer instead of returning with no timer. A silent @@ -539,7 +539,7 @@ were after L6.1. 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: `textColorFilter` is +- Corrected defaults and behavior: `textColorFilter` is `\\x1b\\[[0-9;]*m`; `asciiFilter` is `[^\r\n\x20-\x7e]` and the compiled default preserves tabs; `window`/`pty` are `true` and explicit `false` survives; `idleTimeOut`/`dataIdleTimeOut` are distinguished. diff --git a/docs/AI-ASSISTED-WORKFLOWS.md b/docs/AI-ASSISTED-WORKFLOWS.md new file mode 100644 index 0000000..de8121f --- /dev/null +++ b/docs/AI-ASSISTED-WORKFLOWS.md @@ -0,0 +1,239 @@ +# AI-assisted workflows + +This file holds reusable prompts for common ssh2shell tasks. They are written +for an AI assistant with repository access. Each prompt points to the canonical +documents for detail and repeats only the boundaries that must hold while the +assistant is working. + +Copy a prompt into a new session, fill the placeholders, and keep the assistant +read-only until you approve an action. Point-in-time state notes belong outside +the repository; only stable prompts that are useful to any contributor belong +here. + +## Guardrails for every task + +Apply these whether or not a prompt repeats them: + +- No commit, push, PR, tag, or publish without explicit user approval. +- Docs live in git. `README.md` stays concise; detail belongs in `docs/`. +- Coverage is diagnostic, not a release gate. No coverage dependency and no CI + coverage gate. +- Live tests count in CI. `publish` must not run unless the live suite passes. +- An external/free review of the release candidate is a release step; resolve + its actionable findings before tagging, with user sign-off on every change. + LongCat specifically is informational and quota-dependent, not a gate. +- Never dismiss a real CodeQL alert; fix the code. +- Merge continuously; no same-day follow-up release unless the fix is critical. +- Release only for a security/critical fix, user-facing bug fix, new feature, + or explicit milestone. Docs/test/CI-only changes do not trigger a release. +- Before a task that depends on remote services, live hosts, or free models, + run the environmental assessment below first. + +## Start or recover a session + +```text +You are working in the ssh2shell repository. Start read-only. + +1. Read README.md, CONTRIBUTING.md, docs/PUBLISHING.md, test/coverage.md, and + docs/AI-ASSISTED-WORKFLOWS.md. +2. Report git status --short, the current branch, and the latest commit. +3. Summarise which document is the source of truth for the requested task. +4. Do not commit, push, tag, or publish. Ask before any action that changes + the working tree or remote state. +``` + +## Set up the environment + +```text +You are preparing to work on ssh2shell. Start read-only. + +- Confirm Node.js 18 or newer is available. +- Run npm ci, then npm test. +- Live tests need reachable SSH hosts and a local .env. Copy .env-example to + .env and follow test/README.md for host and key setup. +- Provisioning uses its own test/provision/.env (PROVISION_* variables); see + test/provision/README.md. Check VM availability before either workflow. +- Report the Node version, the test result, and whether live tests can run here. + Do not change .env, change VM power state, or provision hosts without + approval. +``` + +## Assess environmental limitations + +```text +Run this before any other prompt that depends on remote services, live hosts, +or free models. Start read-only. Do not change .env, install packages, provision +hosts, alter CI or configuration, or take any remote action without approval. + +Check and record evidence for: + +1. Toolchain: node, npm, git, and gh versions. Compare them with the versions + the repository expects (CONTRIBUTING.md and .github/workflows/). +2. GitHub access: gh auth status and its token scopes, plus SSH auth to the git + remote. Note any missing scope that would block PRs, releases, or workflow + file edits via the API. +3. npm access: npm whoami and whether an auth token is configured. Publishing + uses GitHub OIDC trusted publishing, so a local token is not required. If + the trusted-publisher configuration on npmjs.com cannot be verified from + here, say so explicitly rather than assuming it works. +4. Live configuration: whether the root .env has the expected host/key + variables for live tests, and whether test/provision/.env has the + PROVISION_* variables for the role being rebuilt. List names only, never + values. +5. VM accessibility: probe SSH to the configured hosts (read-only) and, if a + hypervisor CLI such as VirtualBox VBoxManage is available, list VMs and + running VMs. Report which VMs are up and whether this machine can control + them. Starting, stopping, or provisioning a VM needs explicit approval. If + no control tooling exists, say VM availability is user-dependent and ask + the user to confirm the VMs are running. CI starts its own sshd hosts and + skips the live workflow for fork PRs. +6. Models: which free models are currently available and whether quotas are + exhausted. LongCat is informational only and may be unavailable. +7. Local resources: temp directory, free disk, timezone, and anything else the + planned commands need. + +Report a table with columns: capability, evidence, affected prompt(s), impact, +mitigation. Finish by stating which prompts are safe to run here and which need +a decision first. Ask before substituting a model, changing configuration, or +taking a remote action. +``` + +## Verify before a pull request + +```text +Run the full pre-PR verification for ssh2shell and report results only. + +1. npm test (build check, unit, and baseline) +2. npm run test:live:all, or npm run test:live if told the change is local-only; + say which set ran +3. npm run check:changelog +4. git diff --check +5. If code or tests changed, prepare the coverage summary from test/coverage.md: + the text table, full miss-overlap table, missed by both headline, Node + version, and commands. Keep raw LCOV files local. + +Do not commit, push, or open the PR without explicit approval. +``` + +## Add a live test + +```text +I am adding a live test for . Follow test/README.md. + +- Put the file in test/live/. +- Add per-test success checks in scripts/run-live.js where needed. +- Add the name to defaultTests only if it belongs in the curated batch; + acceptance tests for a specific change can stay out. +- Verify with node scripts/run-live.js --list, then run the new test by name, + then npm run test:live:all. +- Report whether it was added to the curated batch and why. +``` + +## Respond to a CodeQL or security alert + +```text +A CodeQL/security alert was reported for ssh2shell. Do not dismiss it. + +- Read the alert and locate the exact source line. +- Fix the code, not the alert configuration or a suppression. +- Add or update a test that would fail without the fix where practical. +- Re-run the relevant checks and report the result. +- Ask before changing CI or dependency configuration. +``` + +## Document a behavior change + +```text +A change to is ready. Keep README.md concise and put detail in docs/. + +- Identify what changed for users. +- Update the relevant docs/ page and add a CHANGELOG entry under the correct + version heading. +- If the release procedure is affected, update docs/PUBLISHING.md too. +- Run npm run check:changelog and report what changed. +``` + +## Decide whether a fix needs a release + +```text +Assess whether requires a release now. Follow docs/PUBLISHING.md. + +A release is triggered only by a security/critical fix, a user-facing bug fix, +a new feature, or an explicit milestone. Docs/test/CI-only changes do not +trigger one. + +- Classify the change and state the reason. +- If a release is due, state the target version and bump type. +- If not, say it can wait for the next release. +- Apply the cadence rule: no same-day follow-up release unless the fix is + critical. +- Do not bump versions, tag, or publish. Report the recommendation only. +``` + +## Prepare a release + +```text +We are preparing release of ssh2shell. Follow docs/PUBLISHING.md. + +- Confirm the bump has an allowed reason: security/critical fix, user-facing + bug fix, new feature, or explicit milestone. Docs/test/CI-only changes do not + trigger a release. +- Run npm test, npm run test:live:all, npm run check:changelog, and + git diff --check. +- Open a release PR from release/ to master. Include the coverage + summary from test/coverage.md: the text table, the full miss-overlap table, + missed by both as the residual headline, the Node version, and the commands. + Leave raw LCOV files local. +- Stop after the PR is opened. Report the URL and check status. Do not tag or + publish without a separate explicit approval. +``` + +## Review a release candidate + +```text +Review the release candidate read-only. Do not modify files, commit, push, +tag, or publish. + +- Candidate: . Base: . +- Diff: git diff -- src lib test docs README.md CHANGELOG.md +- Focus on src/ssh2shell.js and src/ssh2shell/util.js; tests and docs are + secondary. +- Report findings by severity with file:line and a concrete failure scenario. + State "No findings" explicitly if there are none. Skip style nits. +- Return only the report. Any fix needs explicit user sign-off first. +``` + +Use a free model from the currently available model list. This is the RC review +required by docs/PUBLISHING.md: report actionable findings and wait for user +sign-off before changing code. A LongCat pass, when available, is informational +only; account-wide free quotas can make it unavailable. + +## Refresh coverage evidence + +```text +Refresh the coverage evidence for ssh2shell using test/coverage.md as the method. + +- Run the unit and live commands from "Measurement method" with the LCOV + reporters enabled. The live command runs every file in test/live/, matching + npm run test:live:all and CI. Do not use NODE_V8_COVERAGE on the live suite. +- Recompute the miss-overlap table with the appendix parser in test/coverage.md. + Keep the full table and use missed by both as the residual-risk headline. +- Update test/coverage.md and include the summary in the PR description or a + PR comment. Raw LCOV files stay local. +- Never add a coverage dependency or a CI coverage gate. Coverage is + informational; the gates are CI checks, the live suite, and RC review. +``` + +## Hand off a session + +```text +Produce a handoff note for a replacement AI session. Keep it factual and +time-stamped, and do not store it in git. + +Include: +- branch, base, and uncommitted changes; +- open PR number and check status; +- what was approved, what is paused, and the next gate; +- which docs and commands are authoritative; +- anything a new session would otherwise have to rediscover. +``` diff --git a/docs/MIGRATING-4.md b/docs/MIGRATING-4.md index c4ef972..030b113 100644 --- a/docs/MIGRATING-4.md +++ b/docs/MIGRATING-4.md @@ -101,7 +101,7 @@ Consequences worth checking: - Each hop verifies its own host key. Set `hostHash` / `hostVerifier` on a nested host if the primary pins its key. -## Behaviour changes that look like bugs +## behavior changes that look like bugs - **A silent command times out.** The idle timer is armed when a command is written, not after the first output, and there is no longer an opt-in flag. @@ -191,5 +191,5 @@ rather than staying on 3.x silently. breaking-change list. - [Host-to-host connections](./NEXT-HOST-CONNECTION.md) — the hop design and the full `server.ssh` mapping. -- [Error handling](./ERROR-HANDLING.md) — `error` payloads and close behaviour. +- [Error handling](./ERROR-HANDLING.md) — `error` payloads and close behavior. - [README](../README.md) — current host, command, and tunnelling usage. diff --git a/docs/NEXT-HOST-CONNECTION.md b/docs/NEXT-HOST-CONNECTION.md index 353fb16..f24e9f9 100644 --- a/docs/NEXT-HOST-CONNECTION.md +++ b/docs/NEXT-HOST-CONNECTION.md @@ -72,7 +72,7 @@ minor. - **No command injection surface.** Nothing is interpolated into a remote shell. - **No dependency on the remote `ssh` binary or its configuration.** The hop works when the jump host has no `ssh` client, a restricted shell, or a - `~/.ssh/config` that changes behaviour. + `~/.ssh/config` that changes behavior. - **Real host-key verification.** The command path injects `StrictHostKeyChecking=no`. The hop can use the same `hostHash` / `hostVerifier` contract as the primary connection. @@ -421,7 +421,7 @@ record shape changes from a host config to `record.host`: 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. +behavior. Only the following need code changes. | ID | Deviation | Impact | Resolution | | --- | --- | --- | --- | @@ -659,7 +659,7 @@ handlers must be removed or they keep firing against the parent's events. ### `stop()` -The queue clearing and Ctrl-C behaviour is unchanged. The difference is the +The queue clearing and Ctrl-C behavior is unchanged. The difference is the final teardown: 1. Clear every `commands` and `hosts` queue, plus `_hosts`. @@ -747,7 +747,7 @@ but not `bad-deep-child`. **Decision: a failed primary does not end the run. Each remaining primary is attempted once, in order.** This is the current `connection.on('close')` -behaviour; the change makes it explicit and covers the paths that bypass it. +behavior; the change makes it explicit and covers the paths that bypass it. | Outcome | Action | | --- | --- | @@ -827,7 +827,7 @@ The last two are a real improvement, not just tidying. Today a single nested command that never returns a prompt takes down the whole primary. With one stream per record, a hop failure costs only that hop and its descendants. -The verified primary behaviour is worth recording because it is easy to assume +The verified primary behavior is worth recording because it is easy to assume otherwise: ```text @@ -1185,7 +1185,7 @@ Notes that matter for the transport change: #### The current nested topology is flat, not chained -This is the most important behaviour the transport change fixes, and it is easy +This is the most important behavior the transport change fixes, and it is easy to miss because the traversal order looks correct. `_processSSHPrompt()` pushes `exit` onto `sshObj.exitCommands` when the nested @@ -1220,7 +1220,7 @@ This also explains the fault result: a failed `ssh` command returns the parent prompt, which `_processSSHPrompt()` accepts as success when `sshAuth` is already true, so the failed host's commands run on the parent shell instead of being reported as a connection failure. `test/live/host_faults.js` records that -behaviour and is the acceptance test for the new per-hop transport. +behavior and is the acceptance test for the new per-hop transport. The new model opens a child client through `forwardOut` from its immediate parent record and keeps every ancestor connection open until the child is closed, @@ -1470,7 +1470,7 @@ sudo prompts, command responses, stderr capture, and the default error listener all read the active host and active aliases, which is still the child while the child is active. No handler needs to know whether the host is primary or nested. -| Handler / event | Behaviour on a hop | +| Handler / event | behavior on a hop | | --- | --- | | `onCommandProcessing` | Fires for the active child command, same as a primary command. | | `onCommandComplete` | Receives the child host's `sshObj` and the same `details` (`rawResponse`, optional `stderr`). | @@ -1524,7 +1524,7 @@ replacement: rejects it. Make the source values internal constants, not host properties. 5. **Name resolution.** `forwardOut` sends the destination to the jump host, so names resolve there. Document this; it matches the current `ssh` command - behaviour. + behavior. 6. **Inactive parent data.** A parent shell can emit a late prompt or keepalive output while the child runs. Drop it before it reaches the child's `_buffer`. 7. **`keyboard-interactive` on a child.** Already bound per client by diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index 5aa556b..b9eee43 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -109,7 +109,7 @@ does not start unless the live suite passes. Tags are protected by allows the tag to be pushed. To publish an existing tag manually, open **Actions → Publish to npm → Run -workflow**, choose `master`, and enter the tag (for example `v3.0.0`). +workflow**, choose `master`, and enter the tag (for example `vX.Y.Z`). ### 3. Verify diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index d9311eb..23accba 100644 --- a/lib/ssh2shell.js +++ b/lib/ssh2shell.js @@ -174,7 +174,11 @@ class SSH2Shell extends Stream { set debug(value) { this._debugOverride = typeof value === 'boolean' ? value : undefined; - this._debug = value === true; + const host = (this._activeContext() || {}).host || this.sshObj; + this._debug = + typeof this._debugOverride === 'boolean' + ? this._debugOverride + : (host && host.debug) ?? false; } get verbose() { @@ -183,7 +187,11 @@ class SSH2Shell extends Stream { set verbose(value) { this._verboseOverride = typeof value === 'boolean' ? value : undefined; - this._verbose = value === true; + const host = (this._activeContext() || {}).host || this.sshObj; + this._verbose = + typeof this._verboseOverride === 'boolean' + ? this._verboseOverride + : (host && host.verbose) ?? false; } _loadDefaultListeners() { @@ -435,12 +443,19 @@ class SSH2Shell extends Stream { if (context.textColorFilter) { this.textColorFilter = context.textColorFilter; } - if (typeof context.debug === 'boolean') { - this._debug = context.debug; - } - if (typeof context.verbose === 'boolean') { - this._verbose = context.verbose; - } + // A run-wide override outlives the record being restored. Without this, + // backing out of a hop would resurrect a host flag the caller silenced. + // Fall back to the host config rather than the cached effective value: the + // cache may have been written while an override was active. + const host = context.host || {}; + this._debug = + typeof this._debugOverride === 'boolean' + ? this._debugOverride + : (host.debug ?? false); + this._verbose = + typeof this._verboseOverride === 'boolean' + ? this._verboseOverride + : (host.verbose ?? false); if (typeof context.progress === 'boolean') { this.progress = context.progress; } @@ -1572,6 +1587,10 @@ class SSH2Shell extends Stream { this.systemMsg('debug', `nextPrimaryHost: load next host for ssh2 connection`); + // A graceful-close timer belongs to the primary being left behind. If it + // survives the transition it can force-close the next primary mid-run. + this._clearCloseTimer(); + // Close the current primary and every active hop before resetting the // stack, so a new primary never inherits a hop's socket. if (this._activeContext()) { diff --git a/lib/ssh2shell/util.js b/lib/ssh2shell/util.js index 03b3e26..287e86f 100644 --- a/lib/ssh2shell/util.js +++ b/lib/ssh2shell/util.js @@ -123,15 +123,34 @@ function redactCredentials(value, seen = new WeakSet()) { return value; } - // Preserve functions, Buffers, streams, and other class instances. Only - // plain objects and arrays are copied so config dumps stay readable. + // Preserve functions, Buffers, streams, and other class instances by + // identity. A class instance that carries credential-named properties is the + // exception: systemMsg is public, so dumping it verbatim would leak secrets. + // Its remaining values are redacted recursively, including nested configs. const prototype = Object.getPrototypeOf(value); if ( !Array.isArray(value) && prototype !== Object.prototype && prototype !== null ) { - return value; + const keys = Object.keys(value); + if (!keys.some((key) => CREDENTIAL_KEY.test(key))) { + return value; + } + + if (seen.has(value)) { + return '[Circular]'; + } + seen.add(value); + const copy = {}; + for (const key of keys) { + copy[key] = + CREDENTIAL_KEY.test(key) && value[key] + ? '[REDACTED]' + : redactCredentials(value[key], seen); + } + seen.delete(value); + return copy; } if (seen.has(value)) { diff --git a/src/ssh2shell.js b/src/ssh2shell.js index d9311eb..23accba 100644 --- a/src/ssh2shell.js +++ b/src/ssh2shell.js @@ -174,7 +174,11 @@ class SSH2Shell extends Stream { set debug(value) { this._debugOverride = typeof value === 'boolean' ? value : undefined; - this._debug = value === true; + const host = (this._activeContext() || {}).host || this.sshObj; + this._debug = + typeof this._debugOverride === 'boolean' + ? this._debugOverride + : (host && host.debug) ?? false; } get verbose() { @@ -183,7 +187,11 @@ class SSH2Shell extends Stream { set verbose(value) { this._verboseOverride = typeof value === 'boolean' ? value : undefined; - this._verbose = value === true; + const host = (this._activeContext() || {}).host || this.sshObj; + this._verbose = + typeof this._verboseOverride === 'boolean' + ? this._verboseOverride + : (host && host.verbose) ?? false; } _loadDefaultListeners() { @@ -435,12 +443,19 @@ class SSH2Shell extends Stream { if (context.textColorFilter) { this.textColorFilter = context.textColorFilter; } - if (typeof context.debug === 'boolean') { - this._debug = context.debug; - } - if (typeof context.verbose === 'boolean') { - this._verbose = context.verbose; - } + // A run-wide override outlives the record being restored. Without this, + // backing out of a hop would resurrect a host flag the caller silenced. + // Fall back to the host config rather than the cached effective value: the + // cache may have been written while an override was active. + const host = context.host || {}; + this._debug = + typeof this._debugOverride === 'boolean' + ? this._debugOverride + : (host.debug ?? false); + this._verbose = + typeof this._verboseOverride === 'boolean' + ? this._verboseOverride + : (host.verbose ?? false); if (typeof context.progress === 'boolean') { this.progress = context.progress; } @@ -1572,6 +1587,10 @@ class SSH2Shell extends Stream { this.systemMsg('debug', `nextPrimaryHost: load next host for ssh2 connection`); + // A graceful-close timer belongs to the primary being left behind. If it + // survives the transition it can force-close the next primary mid-run. + this._clearCloseTimer(); + // Close the current primary and every active hop before resetting the // stack, so a new primary never inherits a hop's socket. if (this._activeContext()) { diff --git a/src/ssh2shell/util.js b/src/ssh2shell/util.js index 03b3e26..287e86f 100644 --- a/src/ssh2shell/util.js +++ b/src/ssh2shell/util.js @@ -123,15 +123,34 @@ function redactCredentials(value, seen = new WeakSet()) { return value; } - // Preserve functions, Buffers, streams, and other class instances. Only - // plain objects and arrays are copied so config dumps stay readable. + // Preserve functions, Buffers, streams, and other class instances by + // identity. A class instance that carries credential-named properties is the + // exception: systemMsg is public, so dumping it verbatim would leak secrets. + // Its remaining values are redacted recursively, including nested configs. const prototype = Object.getPrototypeOf(value); if ( !Array.isArray(value) && prototype !== Object.prototype && prototype !== null ) { - return value; + const keys = Object.keys(value); + if (!keys.some((key) => CREDENTIAL_KEY.test(key))) { + return value; + } + + if (seen.has(value)) { + return '[Circular]'; + } + seen.add(value); + const copy = {}; + for (const key of keys) { + copy[key] = + CREDENTIAL_KEY.test(key) && value[key] + ? '[REDACTED]' + : redactCredentials(value[key], seen); + } + seen.delete(value); + return copy; } if (seen.has(value)) { diff --git a/test/README.md b/test/README.md index d0066fd..072b6d9 100644 --- a/test/README.md +++ b/test/README.md @@ -216,7 +216,8 @@ The main environment variables are: | `EXPECTED_HOST_HASH` | Pinned host fingerprint for the fingerprint test. | | `DEBUG`, `VERBOSE` | `ssh2shell` session output. | -[`.env-example`](../.env-example) lists every variable with its default. +[`.env-example`](../.env-example) lists the variables used by the suite with +their defaults. ## CI live tests diff --git a/test/coverage.md b/test/coverage.md index 270a788..76891cd 100644 --- a/test/coverage.md +++ b/test/coverage.md @@ -1,287 +1,208 @@ # 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. +This file records the current coverage measurement, how to read it, how the +unit and live suites overlap, and how to reproduce the numbers. Coverage is +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 -``` +## Current coverage (Node v26.13.0, measured 2026-11-23) -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. +Measured with Node 26's built-in test coverage reporter against the current +build. Unit tests run against `lib/`; live tests run against `src/`. The live +run uses the default environment (`DEBUG` and `VERBOSE` unset), so +debug/verbose-only branches — including credential redaction — are not +exercised there; the unit suite covers them. | Suite | Target | Lines | Branches | Functions | | --- | --- | --- | --- | --- | -| Unit | `lib/ssh2shell.js` | 90.30% | 80.87% | 98.29% | +| Unit | `lib/ssh2shell.js` | 96.98% | 90.45% | 100% | | 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% | +| Unit | `lib/ssh2shell/util.js` | 97.91% | 91.18% | 100% | +| Unit | all files | 97.07% | 90.81% | 100% | +| Combined (unit ∪ live) | all files | **98.15%** | — | — | +| Live | `src/ssh2shell.js` | 79.42% | 56.95% | 87.07% | +| Live | `src/ssh2shell/defaults.js` | 97.96% | 50.00% | 100% | +| Live | `src/ssh2shell/util.js` | 45.55% | 36.84% | 66.67% | +| Live | all files | 77.86% | 56.03% | 85.71% | -### How to read "uncovered lines" +The `Combined` row is the union of hit lines from the two LCOV reports: 2912 of +2967 executable lines. Branch and function denominators differ between an +instrumented unit run and an instrumented live run, so only the line figure is +meaningful for the union. The current headline residual is **55 lines missed by +both**, unchanged by the release-candidate review fixes. -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 +## How to read these numbers + +### 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 | +| Credential redaction | Strong | Weak with default live environment | | 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. +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 behavior most directly, rather than duplicating a case in both. -## Follow-up tests (implemented) +### Uncovered lines are ranges, not methods -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. +The reporter lists uncovered **line ranges**, not uncovered methods. A method +can be entered on every test and still show a large uncovered count, because +that count is the number of lines in branches that were not taken. Grouping +those lines by enclosing method is a readability aid only: nested callbacks are +attributed to their enclosing method, and the last method in a file absorbs +everything after its start line. The percentages themselves are computed by the +reporter and are unaffected by this grouping. -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. +## Miss overlap — how the suites relate -### First pass — unit: `test/unit/coverage-gaps.test.js` +The useful comparison is not hit-set symmetry. It is which **missed** lines are +already covered by the other suite, and which remain missed by both. Because +`lib/ssh2shell.js` and `src/ssh2shell.js` are byte-identical builds (checked +with `npm run check:build`), line numbers are directly comparable. -| 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. | +| File | Executable lines | Missed by unit | Missed by live | Missed by both | Live covers unit miss | Unit covers live miss | +| --- | --- | --- | --- | --- | --- | --- | +| `ssh2shell.js` | 2678 | 81 | 551 | 49 | 32 | 502 | +| `defaults.js` | 98 | 2 | 2 | 2 | 0 | 0 | +| `util.js` | 191 | 4 | 104 | 4 | 0 | 100 | +| all files | 2967 | 87 | 657 | 55 | 32 | 602 | -### First pass — live +What this means for test placement: -| 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. | +- **32 unit misses are already covered by live**: `close` 1900–1915, + `_appendPartial` 639–645, `_removeListeners` 1989–1991 and 1998–2000, and + `_prepareGracefulClose` 1818 and 1829–1830. These are shutdown paths. Adding + unit copies would not improve combined coverage. +- **602 live misses are already covered by unit**, up from 522 before the + review fixes. Most of that increase is the 100 redaction lines the default + live run no longer hits, not newly added unit tests. The other large groups + are `_openShell` (71), `_loadDefaults` (56), `_connect` (45), + `_bindConnection` (25), module scope (24), and `_reportMissingParameters` + (23). Adding live copies would not improve combined coverage. +- **55 lines are missed by both** — the residual-risk headline, unchanged by + the review fixes and down from 206 before the second pass, 105 before the + third, and 71 before the final pass. The combined hit-line union is 2912 of + 2967 lines (98.15%); the point of the split is to show where the remaining + lines sit, not to optimise that percentage. + +A few timer-driven unit tests are timing-sensitive, so branch percentages move +between runs. Observed range across runs, including this one: 90.45–90.71% for +`ssh2shell.js` and 90.78–90.91% across all files. Line coverage and every +overlap figure were stable. + +### Residual missed-by-both lines (highest test value first) + +Earlier passes closed the large defensive blocks in `_openShell`, `_connect`, +`_bindConnection`, `_previousHost`, `_checkCommand`, `_nextHost`, `_popTo`, +`_mergeNestedText`, `stop`, and `_beginStopExit`. The final pass closed +`_failContext`, `_forceClose`, half of `_onData`, and the redaction branches in +`util.js`. The review fixes shifted line numbers but did not change the +residual set. What remains is smaller and mostly defensive; coverage test work +for this round is finished. + +Rows are ordered by how worthwhile a test would be, not by line count; the +`util.js` row has four lines but they are low-value defensive branches. -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. +| Method | Lines missed by both | Best place to target | +| --- | --- | --- | +| `_endPrimary`, `_prepareGracefulClose` | 4 each: 602–603, 608–609 and 1808–1809, 1825–1826 | **Unit**, only if a specific behavior is at risk. | +| `_initiate` | 3: 2010–2011, 2016 | **Unit**: terminal-state guard. | +| other guards | 2 each across 18 methods and at module scope, plus `_onData` 890–891 | **Unit**, low priority. | +| `defaults.js` | 2: 43–44 | Low-value defensive branch. | +| `util.js` | 4: 44–45, 61–62 | Low-value defensive branches. | -### Second pass — unit: `test/unit/coverage-gaps-state.test.js` +These are documented as residual risk, not a queued task list. Adding tests for +them alone would assert guards and catch blocks without meaningful confidence. -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. +## Measurement method -| 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. | +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. +Run `npm run build` before the unit command so `lib/` matches `src/`. -### Third pass — unit: `test/unit/coverage-gaps-flow.test.js` +Unit tests (against the built `lib/`): -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. +```sh +$env:SSH2SHELL_TEST_MODULE = (Resolve-Path 'lib/ssh2shell.js').Path +$unitFiles = Get-ChildItem -Recurse 'test/unit' -Filter '*.test.js' | + ForEach-Object { $_.FullName } | Sort-Object +node --experimental-test-coverage --test ` + --test-reporter=spec --test-reporter-destination=stdout ` + --test-reporter=lcov --test-reporter-destination="$env:TEMP\unit.lcov" ` + $unitFiles +``` -| 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. | +Live tests (against `src/`, which is what `scripts/run-live.js` defaults to). +The files must run serially because several use the same hosts/ports: -### Final pass — unit: `test/unit/behavior-hardening.test.js` +```sh +$env:SSH2SHELL_LIVE_MODULE = (Resolve-Path 'src/ssh2shell.js').Path +$liveFiles = Get-ChildItem 'test/live' -Filter '*.js' | + ForEach-Object { $_.FullName } | Sort-Object +node --experimental-test-coverage --test --test-concurrency=1 ` + --test-reporter=spec --test-reporter-destination=stdout ` + --test-reporter=lcov --test-reporter-destination="$env:TEMP\live.lcov" ` + $liveFiles +``` -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. +This runs **every** file in `test/live/` — the same live tests run by +`npm run test:live:all` and the CI `Live suite` workflow. The curated batch from +`npm run test:live` is a local development shortcut and is **not** used for +these figures. -| 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. | +The overlap figures come from comparing `DA:` records in the two LCOV files as +per-file line sets. Paths are normalised to logical names (`ssh2shell.js`, +`defaults.js`, `util.js`). A compact parser is included at the end of this file +rather than added under `scripts/`, because the live half still needs the test +hosts. -## Coverage after the follow-up tests +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 (including `chaining`, `close_from_handler`, and `command_timeout`) +even though the same tests pass under the standard reporter. -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. +## History — baseline and follow-up work -The live numbers are unchanged from the first pass; the second, third, and -final passes added only unit tests. +Baseline numbers were measured on 2026-11-22 with Node v26.13.0, before the +follow-up tests. They are retained for comparison only; the current table at +the top of this file supersedes them. The baseline live `util.js` figure comes +from an earlier measurement context and is not directly comparable with the +current default-environment run. | 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. | +| 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% | -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. +Follow-up work added 42 tests in six passes. Line numbers in these historical +descriptions shift with source edits; the current overlap table above is +authoritative. + +| Pass | Tests | Targets | Where and why | +| --- | --- | --- | --- | +| First — `test/unit/coverage-gaps.test.js` | 3 | host `stderrData`/`end` binding, `msg` handler replacement, descendant collection | Unit: fake emitter and record stack assert registration directly. | +| First — live | 2: `default_command_timeout.js`, `progress_tty.js` | default command timeout, TTY-gated progress | Live: only real stalled commands and a TTY sink prove those paths. Both are registered in `scripts/run-live.js` and run in CI. | +| Second — `test/unit/coverage-gaps-state.test.js` | 12 | `_openShell`, `_connect`, `_bindConnection`, `_previousHost`, `_checkCommand` | Unit: fake sockets isolate transport and stale-record guards. Skipped against the baseline. | +| Third — `test/unit/coverage-gaps-flow.test.js` | 13 | `_nextHost`, `_popTo`, `_mergeNestedText`, `stop`, `_beginStopExit` | Unit: deterministic state-flow guards. Skipped against the baseline. | +| Final — `test/unit/behavior-hardening.test.js` | 5 | redaction safety, stale data, descendant teardown, forced close | Unit: behavior tests, not just line targets. Skipped against the baseline. | +| Review fixes — `test/unit/behavior-hardening.test.js` | 7 | class-instance redaction, override restore/clear, close-timer transition, cached-value restore, flag type | Unit: lock in the release-candidate findings. Skipped against the baseline. | + +The file `behavior-hardening.test.js` now holds 12 tests (5 from the final pass +and 7 from the review fixes). 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`. ## Reporting coverage with a pull request @@ -298,10 +219,10 @@ 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. +- Before **any PR that changes code or tests**, including a release PR, run the + two local commands above 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. @@ -320,3 +241,47 @@ 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. + +## Appendix: LCOV overlap calculation + +```js +'use strict'; +// node lcov-overlap.js unit.lcov live.lcov +const fs = require('node:fs'); + +function read(file) { + const files = new Map(); + let name; + for (const raw of fs.readFileSync(file, 'utf8').split(/\r?\n/)) { + const line = raw.trim(); + if (line.startsWith('SF:')) { + name = line.slice(3).replace(/\\/g, '/').split('/').pop(); + files.set(name, { all: new Set(), hit: new Set() }); + } else if (line.startsWith('DA:')) { + const [n, count] = line.slice(3).split(','); + files.get(name).all.add(Number(n)); + if (Number(count) > 0) files.get(name).hit.add(Number(n)); + } else if (line === 'end_of_record') { + name = undefined; + } + } + return files; +} + +const [unit, live] = process.argv.slice(2).map(read); +for (const name of new Set([...unit.keys(), ...live.keys()])) { + const all = unit.get(name)?.all || live.get(name).all; + const uh = unit.get(name)?.hit || new Set(); + const lh = live.get(name)?.hit || new Set(); + const unitMiss = new Set([...all].filter((n) => !uh.has(n))); + const liveMiss = new Set([...all].filter((n) => !lh.has(n))); + console.log(name, { + executable: all.size, + unitMiss: unitMiss.size, + liveMiss: liveMiss.size, + bothMiss: [...unitMiss].filter((n) => liveMiss.has(n)).length, + liveCoversUnitMiss: [...unitMiss].filter((n) => lh.has(n)).length, + unitCoversLiveMiss: [...liveMiss].filter((n) => uh.has(n)).length, + }); +} +``` diff --git a/test/unit/behavior-hardening.test.js b/test/unit/behavior-hardening.test.js index 61603c8..965d4ad 100644 --- a/test/unit/behavior-hardening.test.js +++ b/test/unit/behavior-hardening.test.js @@ -187,4 +187,134 @@ describe('behaviour hardening', () => { global.clearTimeout = originalClearTimeout; } }); + + newOnly('redacts credential fields on class instances', () => { + class SecureConfig { + constructor() { + this.host = 'secure.test'; + this.password = 'hunter2'; + this.nested = { value: 1 }; + } + } + + const copy = redactCredentials(new SecureConfig()); + + assert.notEqual(copy.host, undefined); + assert.equal(copy.host, 'secure.test'); + assert.equal(copy.password, '[REDACTED]'); + assert.deepEqual(copy.nested, { value: 1 }); + }); + + newOnly('reapplies the override when restoring an ancestor', () => { + const parentHost = createHost({ + server: { host: 'parent.test' }, + debug: true, + }); + const { ssh } = make(); + const parent = ssh._pushContext(parentHost, null); + parent.debug = true; + ssh._pushContext(createHost({ server: { host: 'child.test' } }), parent); + + ssh.debug = false; + assert.equal(ssh.debug, false); + ssh._restoreContext(parent); + assert.equal(ssh.debug, false); + + ssh.debug = undefined; + ssh._restoreContext(parent); + assert.equal(ssh.debug, true); + }); + + newOnly('restores the active host value when clearing an override', () => { + const { ssh } = make({ debug: true, verbose: true }); + + ssh.debug = false; + ssh.verbose = false; + assert.equal(ssh.debug, false); + assert.equal(ssh.verbose, false); + + ssh.debug = undefined; + ssh.verbose = undefined; + assert.equal(ssh.debug, true); + assert.equal(ssh.verbose, true); + }); + + newOnly('clears the close timer when moving to the next primary', () => { + const { ssh, host } = make(); + const originalSetTimeout = global.setTimeout; + global.setTimeout = () => ({ unref() {} }); + + try { + ssh._armCloseTimer(); + assert.ok(ssh._closeTimer); + + ssh._hosts = [host]; + ssh._closeAllContexts = () => {}; + ssh._progressEnd = () => {}; + const connect = () => 'connected'; + + assert.equal(ssh._nextPrimaryHost(connect), 'connected'); + assert.equal(ssh._closeTimer, null); + } finally { + global.setTimeout = originalSetTimeout; + } + }); + + newOnly('redacts nested credentials and cycles on class instances', () => { + class SecureConfig { + constructor() { + this.host = 'secure.test'; + this.password = 'hunter2'; + this.nested = { password: 'inner-secret' }; + } + } + + const config = new SecureConfig(); + config.self = config; + config.stream = new EventEmitter(); + config.data = Buffer.from('raw'); + + const copy = redactCredentials(config); + + assert.equal(copy.password, '[REDACTED]'); + assert.equal(copy.nested.password, '[REDACTED]'); + assert.equal(copy.self, '[Circular]'); + assert.equal(copy.stream, config.stream); + assert.equal(copy.data, config.data); + }); + + newOnly('uses host config when restoring after an override is cleared', () => { + const parentHost = createHost({ + server: { host: 'parent.test' }, + debug: true, + }); + const childHost = createHost({ + server: { host: 'child.test' }, + debug: false, + }); + const ssh = new SSH2Shell(parentHost); + ssh.sshObj = parentHost; + ssh.debug = false; + ssh._loadDefaults(); + const parent = ssh._activeContext(); + + ssh._pushContext(childHost, parent); + ssh.debug = undefined; + assert.equal(ssh.debug, false); + + ssh._restoreContext(parent); + assert.equal(ssh.debug, true); + assert.equal(ssh.verbose, false); + }); + + newOnly('keeps the configured flag type when an override is cleared', () => { + const { ssh } = make({ debug: 'yes', verbose: 'yes' }); + assert.equal(ssh.debug, 'yes'); + assert.equal(ssh.verbose, 'yes'); + + ssh.debug = undefined; + ssh.verbose = undefined; + assert.equal(ssh.debug, 'yes'); + assert.equal(ssh.verbose, 'yes'); + }); });