diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7f6e3a..65e8067 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,3 +43,22 @@ jobs: - name: Verify publish contents run: npm pack --dry-run + + typecheck: + name: Typecheck + runs-on: ubuntu-latest + steps: + - name: Check out + uses: actions/checkout@v7 + + - name: Set up Node + uses: actions/setup-node@v7 + with: + node-version: 22 + cache: npm + + - name: Install + run: npm ci + + - name: Typecheck declarations and annotated sources + run: npm run typecheck diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index b24ceb6..df32bc2 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -44,6 +44,9 @@ jobs: - name: Install run: npm ci + - name: Typecheck + run: npm run typecheck + - name: Verify version matches the ref shell: bash # Pass the ref through the environment. Interpolating it into the diff --git a/.gitignore b/.gitignore index 7cd40dd..df2be6b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,9 @@ node_modules *.log test/logs/ +# Local editor project scope; tsconfig.json is the checked-in project file. +jsconfig.json + # Live-test private keys. Only the matching .pub files are committed. test/certs/*_ed25519 test/certs/*.pem diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c9d35c..66e41e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,38 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. ## [Unreleased] +## [4.2.1] - 2026-11-25 + +### Added + +- Added a conditional `exports` map so Node 16+/node16/nodenext resolution finds + `index.d.ts` for the root import while preserving `lib/*` (including + extensionless deep imports) and `package.json` subpaths. +- Added a dev-only, pinned TypeScript typecheck gate that validates static type + contracts across annotated sources, repository scripts, live tests, and strict + consumer fixtures under `node16` and `nodenext`. This is contract coverage, + not line coverage; the line-coverage report remains diagnostic only. It is a + required CI check and runs from `prepublishOnly`; runtime dependencies are + unchanged. A root `tsconfig.json` also gives editors explicit project scope + for `index.d.ts`. + +### Changed + +- Tightened editor typing: host context records are explicitly typed, command + responses are declared as strings, `HostConfig` carries `ThisType`, + and `stop()` returns `this`. Runtime behavior is unchanged. +- Cleaned up WebStorm inspection warnings in `src/ssh2shell.js`, + `src/ssh2shell/util.js`, `index.d.ts`, and the `scripts/` helpers: redundant + `return`s, unused callback parameters, timer/context JSDoc annotations, + redundant regex escapes, and EventEmitter-compatible `addListener` overloads. + The internal `compilePromptRegex` deep-import export remains available. + Runtime behavior is unchanged. +- Cleared the same WebStorm inspection categories from the live and unit tests: + unused `dotenv` bindings and callback parameters, annotated fixture hosts and + fake connections, typed timer stubs, corrected `Error` cause arguments, + simplified trivial ternaries, and removed redundant locals. Test behavior is + unchanged. + ## [4.2.0] - 2026-11-25 ### Added @@ -210,7 +242,8 @@ See [docs/MIGRATING-4.md](./docs/MIGRATING-4.md) for the symptom-to-fix guide. `~/.ssh/id_ed25519` copies that were only needed by nested `ssh -i` hops. - `ssh2Client` is now `_ssh2Client` and is documented as an internal test seam. -[Unreleased]: https://github.com/cmp-202/ssh2shell/compare/v4.2.0...HEAD +[Unreleased]: https://github.com/cmp-202/ssh2shell/compare/v4.2.1...HEAD +[4.2.1]: https://github.com/cmp-202/ssh2shell/compare/v4.2.0...v4.2.1 [4.2.0]: https://github.com/cmp-202/ssh2shell/compare/v4.1.0...v4.2.0 [4.1.0]: https://github.com/cmp-202/ssh2shell/compare/v4.0.4...v4.1.0 [4.0.4]: https://github.com/cmp-202/ssh2shell/compare/v4.0.3...v4.0.4 diff --git a/REFACTORING.md b/REFACTORING.md index b5ab6f1..d98f6da 100644 --- a/REFACTORING.md +++ b/REFACTORING.md @@ -1181,6 +1181,29 @@ API are unchanged; this level adds metadata, documentation, and examples. - `npm test`, `npm run check:changelog`, `git diff --check`, and `npm pack --dry-run` — passed. +### L7.27 deliverables (declaration typecheck gate) + +Post-4.2.0 hardening of the editor-support work. Runtime behavior and runtime +dependencies are unchanged. + +- Added pinned dev-only `typescript` and `@types/node`. +- Added `npm run typecheck` with checked-in configs that validate static type + contracts across annotated sources, repository scripts, README-linked live + tests, and strict consumer fixtures under `node16` and `nodenext`. This is + contract coverage, not line coverage; line coverage remains diagnostic only. +- Added a single-version `Typecheck` CI job and a publish step; + `prepublishOnly` also runs the gate. +- Added a conditional `exports` map with `types` first while preserving existing + subpaths, including extensionless `lib/*` deep imports. +- Narrowed command responses to `string`, added `ThisType` to + `HostConfig`, typed internal host records, and documented `stop()` as `this`. + +#### Verification + +- `npm run typecheck` — 0 errors. +- `npm test`, `npm run check:changelog`, `git diff --check`, and + `npm pack --dry-run` — passed. + ## Backlog and future work Items explicitly deferred until after the mechanical refactor. Each one changes diff --git a/docs/AI-ASSISTED-WORKFLOWS.md b/docs/AI-ASSISTED-WORKFLOWS.md index 2f6acce..84b3834 100644 --- a/docs/AI-ASSISTED-WORKFLOWS.md +++ b/docs/AI-ASSISTED-WORKFLOWS.md @@ -14,10 +14,12 @@ here. Apply these whether or not a prompt repeats them: -- No commit, push, PR, tag, or publish without explicit user approval. +- Follow the session modes below. Local commits are allowed in agreed review + cycles; no 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. +- Line coverage is diagnostic, not a release gate. No coverage dependency and + no CI line-coverage gate. `npm run typecheck` is a separate static-contract + gate; it is not line coverage and produces no coverage percentage. - 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. @@ -29,6 +31,27 @@ Apply these whether or not a prompt repeats them: - Before a task that depends on remote services, live hosts, or free models, run the environmental assessment below first. +## Session modes + +Use the narrowest mode that matches the request. A stop for exploration ends +when the user explicitly asks to create or use a branch and implement changes. + +1. **Read-only exploration** — inspect, review, compare, and report findings. + Do not edit files, create commits, or change branches. This is the default + when the user says “let’s look at this” or asks for a stop on repo activity. +2. **Branch implementation** — begins when the user asks to create or use a + branch and make changes. Normal development applies: edit files, add new + files, stage, commit locally in agreed review cycles, run checks, fix + findings, and expand the implementation. Push, PR, tag, publish, and release + remain blocked. +3. **Release and remote actions** — push, PR, tag, publish, or release only with + explicit user approval. Same-day follow-up releases still follow the critical + fix rule unless the user explicitly overrides it. + +A read-only limit is not a permanent repository freeze. It protects the +exploration phase; once implementation on a branch is requested, do not keep +asking for permission for ordinary local development steps. + ## Start or recover a session ```text @@ -38,8 +61,9 @@ You are working in the ssh2shell repository. Start read-only. 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. +4. Stay read-only until asked to create or use a branch and implement. Do not + push, tag, or publish. Commit only in agreed review cycles, and ask before + any action that changes remote state or release metadata. ``` ## Set up the environment @@ -112,7 +136,8 @@ Run the full pre-PR verification for ssh2shell and report results only. 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. +Commit only in agreed review cycles; do not push or open the PR without +explicit approval. ``` ## Add a live test @@ -164,7 +189,9 @@ You are adding editor/type support to ssh2shell. Start read-only. src/ssh2shell.js, src/ssh2shell/defaults.js, src/ssh2shell/util.js, and the README-linked live tests before changing anything. - Keep package.json `types` pointing at ./index.d.ts and keep index.d.ts in - `files`. Do not add a TypeScript runtime dependency, build step, or CI gate. + `files`. Do not add a TypeScript runtime dependency or build step. The + dev-only TypeScript toolchain is checked by the `typecheck` script in CI and + `prepublishOnly`. - Add JSDoc typedef aliases and `// @ts-check` in src/ where they improve the public contract. Keep lib/ in sync with src/ through the repository's normal build/check process. @@ -172,11 +199,12 @@ You are adding editor/type support to ssh2shell. Start read-only. tests, use import('../../index') for module and HostConfig annotations so they resolve locally. - Keep JSDoc @type tags immediately above the declaration they describe. -- Verify with tsc against src/ and the annotated live tests, npm test, - git diff --check, and npm pack --dry-run when package metadata changed. +- Verify with `npm run typecheck`, npm test, git diff --check, and + npm pack --dry-run when package metadata changed. - Report the declared fields/signatures, docs that changed, and verification - results. Do not commit, push, open a PR, tag, publish, or release without - explicit approval. Docs/test-only editor support does not trigger a release. + results. Commit only in agreed review cycles; do not push, open a PR, tag, + publish, or release without explicit approval. Docs/test-only editor support + does not trigger a release. ``` ## Decide whether a fix needs a release @@ -246,8 +274,10 @@ Refresh the coverage evidence for ssh2shell using test/coverage.md as the method 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. +- Never add a line-coverage dependency or a CI line-coverage gate. Line + coverage is informational; the gates are CI checks, the live suite, typecheck, + and RC review. `npm run typecheck` validates static contracts, not executed + lines. ``` ## Hand off a session diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index b9eee43..8de4d7a 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -81,7 +81,8 @@ Update the changelog in a fixed order: to the link definitions at the bottom. 3. Point the existing `[Unreleased]` link at `compare/vX.Y.Z...HEAD`. 4. Run `npm run check:changelog`. It fails if the version, date, bullets, or - compare links are missing, and it runs again from `prepublishOnly`. + compare links are missing. `prepublishOnly` runs it again alongside + `npm run typecheck` and `npm test`. Then update `REFACTORING.md` and any other affected docs, and push the branch: @@ -144,6 +145,8 @@ left to memory. link, and update the `[Unreleased]` link. - [ ] Update `REFACTORING.md` and any docs affected by the release. - [ ] `npm run check:changelog` passes. +- [ ] `npm run typecheck` passes (sources, annotated live tests, and strict + consumer fixtures under node16 and nodenext). - [ ] `npm test` passes (`check:build`, unit, baseline). - [ ] Run the live suite locally when the change touches connection or command flow: `npm run test:live:all`. @@ -170,8 +173,7 @@ If trusted publishing is not available, create a granular access token with: Store it as the `NPM_TOKEN` secret in GitHub Actions and set `NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}` on the publish step. This is a -stopgap: direct publishing with bypass-2FA tokens is being removed in January -2027. +stopgap: direct publishing with bypass-2FA tokens is being removed in January 2027. ## Do not diff --git a/index.d.ts b/index.d.ts index df0db20..d87cb39 100644 --- a/index.d.ts +++ b/index.d.ts @@ -26,8 +26,8 @@ declare class SSH2Shell { /** Connect and optionally receive the combined session text at the end. */ connect(callback?: (sessionText: string) => void): boolean; - /** Stop the run early with an optional reason label. */ - stop(reason?: string): unknown; + /** Stop the run early with an optional reason label. Returns this instance for chaining. */ + stop(reason?: string): this; /** Close the active connection; `graceful` backs out of nested shells. */ close(options?: SSH2Shell.CloseOptions): unknown; /** Emit a structured message on the `msg` or `debug`/`verbose` channel. */ @@ -39,10 +39,12 @@ declare class SSH2Shell { ): this; on(event: string, listener: (...args: any[]) => void): this; + // noinspection JSUnusedGlobalSymbols addListener( event: E, listener: (this: SSH2Shell, ...args: SSH2Shell.EventMap[E]) => void ): this; + // noinspection JSUnusedGlobalSymbols addListener(event: string, listener: (...args: any[]) => void): this; once( @@ -145,8 +147,8 @@ declare namespace SSH2Shell { /** Extra values supplied with the `commandComplete` event. */ interface CommandCompleteDetails { - /** Always the unprocessed response buffer. */ - rawResponse: string | Uint8Array; + /** Always a string; the shell stream is decoded before handlers receive it. */ + rawResponse: string; /** Captured stderr when `captureStderr` is enabled. */ stderr?: string; [property: string]: unknown; @@ -192,7 +194,7 @@ declare namespace SSH2Shell { type CommandProcessingHandler = ( this: SSH2Shell, command: string, - response: string | Uint8Array, + response: string, host: HostConfig, stream: ShellStream ) => void; @@ -200,7 +202,7 @@ declare namespace SSH2Shell { type CommandCompleteHandler = ( this: SSH2Shell, command: string, - response: string | Uint8Array, + response: string, host: HostConfig, details: CommandCompleteDetails ) => void; @@ -208,7 +210,7 @@ declare namespace SSH2Shell { type CommandTimeoutHandler = ( this: SSH2Shell, command: string, - response: string | Uint8Array, + response: string, stream: ShellStream, connection: SSHConnection, details: TimeoutDetails @@ -243,20 +245,9 @@ declare namespace SSH2Shell { msg: [unknown]; data: [string | Uint8Array]; stderrData: [string | Uint8Array]; - commandProcessing: [string, string | Uint8Array, HostConfig, ShellStream]; - commandComplete: [ - string, - string | Uint8Array, - HostConfig, - CommandCompleteDetails - ]; - commandTimeout: [ - string, - string | Uint8Array, - ShellStream, - SSHConnection, - TimeoutDetails - ]; + commandProcessing: [string, string, HostConfig, ShellStream]; + commandComplete: [string, string, HostConfig, CommandCompleteDetails]; + commandTimeout: [string, string, ShellStream, SSHConnection, TimeoutDetails]; end: [string, HostConfig]; error: [ unknown, @@ -289,7 +280,7 @@ declare namespace SSH2Shell { * * @see https://github.com/cmp-202/ssh2shell#configuration-reference */ - interface HostConfig { + interface HostOptions { /** How ssh2shell connects. Passed through to `ssh2.Client.connect()`. */ server: ServerConfig; @@ -400,6 +391,9 @@ declare namespace SSH2Shell { /** Runtime state and forward-compatible host keys. */ [property: string]: unknown; } + + /** Host configuration with `this` typed as the owning SSH2Shell instance. */ + type HostConfig = HostOptions & ThisType; } export = SSH2Shell; diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index e462b6a..6bd2863 100644 --- a/lib/ssh2shell.js +++ b/lib/ssh2shell.js @@ -29,6 +29,37 @@ * @typedef {Error & {level?: string, hadError?: boolean}} TaggedError */ +// Internal per-connection state passed through the context helpers. Typing it +// keeps accidental property typos from silently turning into `undefined`. +/** + * @typedef {object} HostRecord + * @property {HostConfig} host + * @property {HostRecord | null} parent + * @property {SSHConnection | null} connection + * @property {ShellStream | null} stream + * @property {boolean} isPrimary + * @property {boolean} closed + * @property {boolean} failing + * @property {Record void>} listeners + * @property {NodeJS.Timeout | number | null} idleTimer + * @property {NodeJS.Timeout | number | null} dataReceivedTimer + * @property {boolean} expectedClose + * @property {number} idleTime + * @property {number} dataIdleTime + * @property {string} command + * @property {string} buffer + * @property {HostConfig[] | null} pendingHosts + * @property {boolean} reportedError + * @property {RegExp} [standardPrompt] + * @property {RegExp} [passwordPrompt] + * @property {RegExp} [asciiFilter] + * @property {RegExp} [textColorFilter] + * @property {boolean} [debug] + * @property {boolean} [verbose] + * @property {boolean} [progress] + * @property {boolean} [exposeCredentials] + */ + const Stream = require('node:stream'); const { applyHostDefaults } = require('./ssh2shell/defaults'); @@ -128,7 +159,9 @@ class SSH2Shell extends Stream { this.sshObj = /** @type {any} */ ({}); // `_connections` holds the ancestors of the active record; `_active` is the // active record itself. A primary host has an empty stack. + /** @type {HostRecord[]} */ this._connections = []; + /** @type {HostRecord | null} */ this._active = null; this._primaryEnded = false; this.host = "No host"; @@ -306,7 +339,6 @@ class SSH2Shell extends Stream { if (!this.listeners('error').includes(this._defaultErrorListener)) { this.on('error', this._defaultErrorListener); } - return; } // A real shell stream exists only after `connection.shell` succeeds. Before @@ -405,6 +437,11 @@ class SSH2Shell extends Stream { // Creates the record for the active host. `parent === null` is a primary; // otherwise the parent record is pushed onto the ancestor stack first. + /** + * @param {HostConfig} host + * @param {HostRecord | null} parent + * @returns {HostRecord} + */ _pushContext(host, parent) { if (parent) { // `command` and `_buffer` are instance aliases for the active host. Save @@ -415,6 +452,7 @@ class SSH2Shell extends Stream { this._connections.push(parent); } + /** @type {HostRecord} */ const record = { host, parent: parent || null, @@ -445,12 +483,17 @@ class SSH2Shell extends Stream { return record; } + /** @returns {HostRecord | null} */ _activeContext() { return this._active || null; } // Makes a record the active host again and re-points the compatibility // aliases at it. + /** + * @param {HostRecord | null} context + * @returns {HostRecord | null} + */ _restoreContext(context) { if (!context) { return null; @@ -485,7 +528,7 @@ class SSH2Shell extends Stream { // 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 || {}; + const host = /** @type {HostConfig} */ (context.host || {}); this._debug = typeof this._debugOverride === 'boolean' ? this._debugOverride @@ -536,11 +579,16 @@ class SSH2Shell extends Stream { // Active record plus every record deeper than `context`, deepest-first. // `context` itself is excluded; callers close it separately. + /** + * @param {HostRecord | null} context + * @returns {HostRecord[]} + */ _descendantsOf(context) { if (!context) { return []; } + /** @type {HostRecord[]} */ const result = []; const active = this._activeContext(); if (active && active !== context && !active.closed) { @@ -560,6 +608,11 @@ class SSH2Shell extends Stream { } // The only record teardown point. Idempotent through `context.closed`. + /** + * @param {HostRecord | null} context + * @param {string} reason + * @returns {boolean} + */ _closeContext(context, reason) { if (!context || context.closed) { return false; @@ -605,6 +658,11 @@ class SSH2Shell extends Stream { // The only record failure entry point. Descendants are torn down first, then // the record itself, and navigation follows the primary/hop split. + /** + * @param {HostRecord | null} context + * @param {unknown} err + * @param {string} reason + */ _failContext(context, err, reason) { if (!context || context.closed || context.failing) { return; @@ -624,6 +682,10 @@ class SSH2Shell extends Stream { return this._runExit(); } + /** + * @param {HostRecord | null} context + * @param {unknown} err + */ _hopFailed(context, err) { if (!context || context.closed || context.failing) { return; @@ -689,7 +751,7 @@ class SSH2Shell extends Stream { 'Missing connection parameters', 'Parameters', false, - function (err, type, close) { + function () { const expose = this.exposeCredentials === true; if (this.sshObj.server) { this.emit( @@ -1480,8 +1542,9 @@ class SSH2Shell extends Stream { } } - const parent = - parentRecord && parentRecord.host ? parentRecord.host : parentRecord; + const parent = /** @type {HostConfig} */ ( + parentRecord && parentRecord.host ? parentRecord.host : parentRecord + ); if (!parent || parent === host) { return false; } @@ -1544,7 +1607,9 @@ class SSH2Shell extends Stream { if (this._connections) { for (let index = this._connections.length - 1; index >= 0; index -= 1) { const record = this._connections[index]; - const host = record && record.host ? record.host : record; + const host = /** @type {HostConfig} */ ( + record && record.host ? record.host : record + ); if (host && host.server) { hosts.push(host); } @@ -1578,7 +1643,9 @@ class SSH2Shell extends Stream { this._finalizeHost(this.sshObj, 'previous-host'); this._removeListeners(); const parent = this._connections.pop(); - const parentHost = parent && parent.host ? parent.host : parent; + const parentHost = /** @type {HostConfig} */ ( + parent && parent.host ? parent.host : parent + ); if (parent && parent.host) { this._restoreContext(parent); } else if (parentHost) { @@ -1714,7 +1781,7 @@ class SSH2Shell extends Stream { /** * @param {string} [reason] Label reported in the stop message. - * @returns {unknown} The active stream placeholder or this instance. + * @returns {this} This instance, for chaining. */ stop(reason = 'user') { if (this._runComplete || this._stopping) { @@ -2068,7 +2135,6 @@ class SSH2Shell extends Stream { if (typeof action === 'function') { return action(); } - return; } // Timer values can be set on the instance (`SSH.idleTime` / `SSH.dataIdleTime`) @@ -2129,7 +2195,7 @@ class SSH2Shell extends Stream { `${this.host}: Command timed out after ${this.idleTime / 1000} seconds`, 'Command Timeout', true, - (err, type) => { + () => { this.sshObj.sessionText += this._buffer; this._buffer = ''; } @@ -2489,6 +2555,7 @@ class SSH2Shell extends Stream { // Attaches the transport handlers to one record. Every handler closes over // `context`, so a late event from an ancestor cannot act on the active // child. + /** @param {HostRecord} context */ _bindConnection(context) { const connection = context.connection; @@ -2721,7 +2788,7 @@ class SSH2Shell extends Stream { this._finalizeHost(context.host, 'stream-finish'); }); - stream.on('close', (code, signal) => { + stream.on('close', () => { this._progressEnd(); this.systemMsg('debug', `connect: Stream.close`); diff --git a/lib/ssh2shell/util.js b/lib/ssh2shell/util.js index 1d1af84..4ef2a67 100644 --- a/lib/ssh2shell/util.js +++ b/lib/ssh2shell/util.js @@ -19,7 +19,7 @@ function escapeRegex(str) { // sequence while ESC is still present. Covers CSI, OSC (BEL or ST terminated), // and two-character escapes. const terminalEscapePattern = - /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-_]/g; + /\x1b][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-_]/g; function stripTerminalEscapes(value) { return String(value).replace(terminalEscapePattern, ''); @@ -36,6 +36,8 @@ function compileAsciiFilter(configured) { // Only allow basic structural character classes/ranges; reject dangerous // loops (+, *, ?, nested groups). + // Keep the 4.2.0 character set verbatim; the escapes are intentional. + // noinspection RegExpDuplicateCharacterInClass,RegExpRedundantEscape const safeAsciiPattern = /^\[\^?[a-zA-Z0-9\s\\x00-\\x7f\-\[\]]+\]$/; if (safeAsciiPattern.test(configured)) { return { filter: new RegExp(configured, 'g'), usedFallback: false }; @@ -84,6 +86,8 @@ function compilePromptRegex(configured) { const flags = isRegExp ? configured.flags.replace(/[gym]/g, '') : ''; try { + // The group is required when a configured prompt contains alternation. + // noinspection RegExpUnnecessaryNonCapturingGroup return { regex: new RegExp(`(?:${source})$`, flags), usedFallback: false }; } catch (error) { return { regex: null, usedFallback: true }; @@ -107,7 +111,9 @@ function compilePrompts(sshObj) { ), standardPrompt: custom.regex || - new RegExp(`[${escapeRegex(sshObj.standardPrompt || '>$%#')}]\\s?$`), + new RegExp( + '[' + escapeRegex(sshObj.standardPrompt || '>$%#') + ']\\s?$' + ), standardPromptFallback: custom.usedFallback, }; } @@ -216,6 +222,7 @@ function redactCredentials(value, seen = new WeakSet()) { module.exports = { compileAsciiFilter, + // noinspection JSUnusedGlobalSymbols compilePromptRegex, compilePrompts, compileTextColorFilter, diff --git a/package-lock.json b/package-lock.json index 4a2349b..3c5f466 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,23 +1,35 @@ { "name": "ssh2shell", - "version": "4.2.0", + "version": "4.2.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ssh2shell", - "version": "4.2.0", + "version": "4.2.1", "license": "ISC", "dependencies": { "ssh2": "^1.4.0" }, "devDependencies": { - "dotenv": "^18.0.10" + "@types/node": "22.20.5", + "dotenv": "^18.0.10", + "typescript": "5.9.3" }, "engines": { "node": ">=18.0.0" } }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, "node_modules/asn1": { "version": "0.2.6", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", @@ -108,6 +120,27 @@ "version": "0.14.5", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" } } } diff --git a/package.json b/package.json index b743b22..d3e65f1 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,22 @@ { "name": "ssh2shell", - "version": "4.2.0", + "version": "4.2.1", "author": "cmp-202", "description": "A wrapper class for ssh2 to run multiple sequential commands in an SSH shell session, handle command responses, and tunnel through to other hosts using nested host objects", "main": "./lib/ssh2shell.js", "types": "./index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./lib/ssh2shell.js" + }, + "./package.json": "./package.json", + "./index.d.ts": "./index.d.ts", + "./lib/ssh2shell": "./lib/ssh2shell.js", + "./lib/ssh2shell/util": "./lib/ssh2shell/util.js", + "./lib/ssh2shell/defaults": "./lib/ssh2shell/defaults.js", + "./lib/*": "./lib/*" + }, "files": [ "lib", "index.d.ts", @@ -17,12 +29,15 @@ "ssh2": "^1.4.0" }, "devDependencies": { - "dotenv": "^18.0.10" + "@types/node": "22.20.5", + "dotenv": "^18.0.10", + "typescript": "5.9.3" }, "scripts": { "build": "node scripts/build.js", "check:build": "node scripts/check-build.js", "check:changelog": "node scripts/check-changelog.js", + "typecheck": "tsc -p tsconfig.typecheck.json && tsc -p tsconfig.consumer.json && tsc -p tsconfig.consumer-nodenext.json", "test": "npm run check:build && npm run test:unit && npm run test:baseline", "test:unit": "node scripts/run-tests.js lib", "test:src": "node scripts/run-tests.js src", @@ -31,7 +46,7 @@ "test:live": "node scripts/run-live.js", "test:live:all": "node scripts/run-live.js --all", "provision": "node test/provision/provision.js", - "prepublishOnly": "npm run check:changelog && npm test" + "prepublishOnly": "npm run check:changelog && npm run typecheck && npm test" }, "keywords": [ "SSH", diff --git a/scripts/check-build.js b/scripts/check-build.js index d6c8ea0..7fb5738 100644 --- a/scripts/check-build.js +++ b/scripts/check-build.js @@ -31,7 +31,9 @@ for (const file of srcFiles) { problems.push(`${file}: missing from lib/`); continue; } - if (!fs.readFileSync(src).equals(fs.readFileSync(lib))) { + const srcBuffer = /** @type {Buffer} */ (fs.readFileSync(src)); + const libBuffer = /** @type {Buffer} */ (fs.readFileSync(lib)); + if (!srcBuffer.equals(libBuffer)) { problems.push(`${file}: out of sync`); } } diff --git a/scripts/check-changelog.js b/scripts/check-changelog.js index 394ff82..8cb271b 100644 --- a/scripts/check-changelog.js +++ b/scripts/check-changelog.js @@ -24,12 +24,12 @@ if (!/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(version)) { errors.push(`package.json has an unsupported version: ${version}`); } -if (!/^## \[Unreleased\]\s*$/m.test(changelog)) { +if (!/^## \[Unreleased]\s*$/m.test(changelog)) { errors.push('CHANGELOG.md is missing a "## [Unreleased]" section'); } const heading = new RegExp( - `^## \\[${escapeRegExp(version)}\\] - (\\d{4}-\\d{2}-\\d{2})\\s*$`, + `^## \\[${escapeRegExp(version)}] - (\\d{4}-\\d{2}-\\d{2})\\s*$`, 'm' ); const match = changelog.match(heading); @@ -49,7 +49,7 @@ if (!match) { } const versionLink = new RegExp( - `^\\[${escapeRegExp(version)}\\]: https://github\\.com/cmp-202/ssh2shell/compare/\\S+`, + `^\\[${escapeRegExp(version)}]: https://github\\.com/cmp-202/ssh2shell/compare/\\S+`, 'm' ); if (!versionLink.test(changelog)) { @@ -57,7 +57,7 @@ if (!versionLink.test(changelog)) { } const unreleasedLink = new RegExp( - `^\\[Unreleased\\]: https://github\\.com/cmp-202/ssh2shell/compare/v${escapeRegExp( + `^\\[Unreleased]: https://github\\.com/cmp-202/ssh2shell/compare/v${escapeRegExp( version )}\\.\\.\\.HEAD\\s*$`, 'm' diff --git a/scripts/run-tests.js b/scripts/run-tests.js index 51d686f..e4b0b9a 100644 --- a/scripts/run-tests.js +++ b/scripts/run-tests.js @@ -33,6 +33,7 @@ function testFiles(dir) { .sort(); } +/** @type {string[]} */ const files = testFiles(unitDir); if (files.length === 0) { @@ -40,13 +41,16 @@ if (files.length === 0) { process.exit(1); } -const child = spawn(process.execPath, ['--test', ...files], { +/** @type {import('node:child_process').SpawnOptions} */ +const spawnOptions = { cwd: repoRoot, stdio: 'inherit', env: Object.assign({}, process.env, { SSH2SHELL_TEST_MODULE: modulePath, }), -}); +}; + +const child = spawn(process.execPath, ['--test', ...files], spawnOptions); child.on('error', (error) => { console.error(error); diff --git a/src/ssh2shell.js b/src/ssh2shell.js index e462b6a..6bd2863 100644 --- a/src/ssh2shell.js +++ b/src/ssh2shell.js @@ -29,6 +29,37 @@ * @typedef {Error & {level?: string, hadError?: boolean}} TaggedError */ +// Internal per-connection state passed through the context helpers. Typing it +// keeps accidental property typos from silently turning into `undefined`. +/** + * @typedef {object} HostRecord + * @property {HostConfig} host + * @property {HostRecord | null} parent + * @property {SSHConnection | null} connection + * @property {ShellStream | null} stream + * @property {boolean} isPrimary + * @property {boolean} closed + * @property {boolean} failing + * @property {Record void>} listeners + * @property {NodeJS.Timeout | number | null} idleTimer + * @property {NodeJS.Timeout | number | null} dataReceivedTimer + * @property {boolean} expectedClose + * @property {number} idleTime + * @property {number} dataIdleTime + * @property {string} command + * @property {string} buffer + * @property {HostConfig[] | null} pendingHosts + * @property {boolean} reportedError + * @property {RegExp} [standardPrompt] + * @property {RegExp} [passwordPrompt] + * @property {RegExp} [asciiFilter] + * @property {RegExp} [textColorFilter] + * @property {boolean} [debug] + * @property {boolean} [verbose] + * @property {boolean} [progress] + * @property {boolean} [exposeCredentials] + */ + const Stream = require('node:stream'); const { applyHostDefaults } = require('./ssh2shell/defaults'); @@ -128,7 +159,9 @@ class SSH2Shell extends Stream { this.sshObj = /** @type {any} */ ({}); // `_connections` holds the ancestors of the active record; `_active` is the // active record itself. A primary host has an empty stack. + /** @type {HostRecord[]} */ this._connections = []; + /** @type {HostRecord | null} */ this._active = null; this._primaryEnded = false; this.host = "No host"; @@ -306,7 +339,6 @@ class SSH2Shell extends Stream { if (!this.listeners('error').includes(this._defaultErrorListener)) { this.on('error', this._defaultErrorListener); } - return; } // A real shell stream exists only after `connection.shell` succeeds. Before @@ -405,6 +437,11 @@ class SSH2Shell extends Stream { // Creates the record for the active host. `parent === null` is a primary; // otherwise the parent record is pushed onto the ancestor stack first. + /** + * @param {HostConfig} host + * @param {HostRecord | null} parent + * @returns {HostRecord} + */ _pushContext(host, parent) { if (parent) { // `command` and `_buffer` are instance aliases for the active host. Save @@ -415,6 +452,7 @@ class SSH2Shell extends Stream { this._connections.push(parent); } + /** @type {HostRecord} */ const record = { host, parent: parent || null, @@ -445,12 +483,17 @@ class SSH2Shell extends Stream { return record; } + /** @returns {HostRecord | null} */ _activeContext() { return this._active || null; } // Makes a record the active host again and re-points the compatibility // aliases at it. + /** + * @param {HostRecord | null} context + * @returns {HostRecord | null} + */ _restoreContext(context) { if (!context) { return null; @@ -485,7 +528,7 @@ class SSH2Shell extends Stream { // 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 || {}; + const host = /** @type {HostConfig} */ (context.host || {}); this._debug = typeof this._debugOverride === 'boolean' ? this._debugOverride @@ -536,11 +579,16 @@ class SSH2Shell extends Stream { // Active record plus every record deeper than `context`, deepest-first. // `context` itself is excluded; callers close it separately. + /** + * @param {HostRecord | null} context + * @returns {HostRecord[]} + */ _descendantsOf(context) { if (!context) { return []; } + /** @type {HostRecord[]} */ const result = []; const active = this._activeContext(); if (active && active !== context && !active.closed) { @@ -560,6 +608,11 @@ class SSH2Shell extends Stream { } // The only record teardown point. Idempotent through `context.closed`. + /** + * @param {HostRecord | null} context + * @param {string} reason + * @returns {boolean} + */ _closeContext(context, reason) { if (!context || context.closed) { return false; @@ -605,6 +658,11 @@ class SSH2Shell extends Stream { // The only record failure entry point. Descendants are torn down first, then // the record itself, and navigation follows the primary/hop split. + /** + * @param {HostRecord | null} context + * @param {unknown} err + * @param {string} reason + */ _failContext(context, err, reason) { if (!context || context.closed || context.failing) { return; @@ -624,6 +682,10 @@ class SSH2Shell extends Stream { return this._runExit(); } + /** + * @param {HostRecord | null} context + * @param {unknown} err + */ _hopFailed(context, err) { if (!context || context.closed || context.failing) { return; @@ -689,7 +751,7 @@ class SSH2Shell extends Stream { 'Missing connection parameters', 'Parameters', false, - function (err, type, close) { + function () { const expose = this.exposeCredentials === true; if (this.sshObj.server) { this.emit( @@ -1480,8 +1542,9 @@ class SSH2Shell extends Stream { } } - const parent = - parentRecord && parentRecord.host ? parentRecord.host : parentRecord; + const parent = /** @type {HostConfig} */ ( + parentRecord && parentRecord.host ? parentRecord.host : parentRecord + ); if (!parent || parent === host) { return false; } @@ -1544,7 +1607,9 @@ class SSH2Shell extends Stream { if (this._connections) { for (let index = this._connections.length - 1; index >= 0; index -= 1) { const record = this._connections[index]; - const host = record && record.host ? record.host : record; + const host = /** @type {HostConfig} */ ( + record && record.host ? record.host : record + ); if (host && host.server) { hosts.push(host); } @@ -1578,7 +1643,9 @@ class SSH2Shell extends Stream { this._finalizeHost(this.sshObj, 'previous-host'); this._removeListeners(); const parent = this._connections.pop(); - const parentHost = parent && parent.host ? parent.host : parent; + const parentHost = /** @type {HostConfig} */ ( + parent && parent.host ? parent.host : parent + ); if (parent && parent.host) { this._restoreContext(parent); } else if (parentHost) { @@ -1714,7 +1781,7 @@ class SSH2Shell extends Stream { /** * @param {string} [reason] Label reported in the stop message. - * @returns {unknown} The active stream placeholder or this instance. + * @returns {this} This instance, for chaining. */ stop(reason = 'user') { if (this._runComplete || this._stopping) { @@ -2068,7 +2135,6 @@ class SSH2Shell extends Stream { if (typeof action === 'function') { return action(); } - return; } // Timer values can be set on the instance (`SSH.idleTime` / `SSH.dataIdleTime`) @@ -2129,7 +2195,7 @@ class SSH2Shell extends Stream { `${this.host}: Command timed out after ${this.idleTime / 1000} seconds`, 'Command Timeout', true, - (err, type) => { + () => { this.sshObj.sessionText += this._buffer; this._buffer = ''; } @@ -2489,6 +2555,7 @@ class SSH2Shell extends Stream { // Attaches the transport handlers to one record. Every handler closes over // `context`, so a late event from an ancestor cannot act on the active // child. + /** @param {HostRecord} context */ _bindConnection(context) { const connection = context.connection; @@ -2721,7 +2788,7 @@ class SSH2Shell extends Stream { this._finalizeHost(context.host, 'stream-finish'); }); - stream.on('close', (code, signal) => { + stream.on('close', () => { this._progressEnd(); this.systemMsg('debug', `connect: Stream.close`); diff --git a/src/ssh2shell/util.js b/src/ssh2shell/util.js index 1d1af84..4ef2a67 100644 --- a/src/ssh2shell/util.js +++ b/src/ssh2shell/util.js @@ -19,7 +19,7 @@ function escapeRegex(str) { // sequence while ESC is still present. Covers CSI, OSC (BEL or ST terminated), // and two-character escapes. const terminalEscapePattern = - /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-_]/g; + /\x1b][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-?]*[ -/]*[@-~]|\x1b[@-_]/g; function stripTerminalEscapes(value) { return String(value).replace(terminalEscapePattern, ''); @@ -36,6 +36,8 @@ function compileAsciiFilter(configured) { // Only allow basic structural character classes/ranges; reject dangerous // loops (+, *, ?, nested groups). + // Keep the 4.2.0 character set verbatim; the escapes are intentional. + // noinspection RegExpDuplicateCharacterInClass,RegExpRedundantEscape const safeAsciiPattern = /^\[\^?[a-zA-Z0-9\s\\x00-\\x7f\-\[\]]+\]$/; if (safeAsciiPattern.test(configured)) { return { filter: new RegExp(configured, 'g'), usedFallback: false }; @@ -84,6 +86,8 @@ function compilePromptRegex(configured) { const flags = isRegExp ? configured.flags.replace(/[gym]/g, '') : ''; try { + // The group is required when a configured prompt contains alternation. + // noinspection RegExpUnnecessaryNonCapturingGroup return { regex: new RegExp(`(?:${source})$`, flags), usedFallback: false }; } catch (error) { return { regex: null, usedFallback: true }; @@ -107,7 +111,9 @@ function compilePrompts(sshObj) { ), standardPrompt: custom.regex || - new RegExp(`[${escapeRegex(sshObj.standardPrompt || '>$%#')}]\\s?$`), + new RegExp( + '[' + escapeRegex(sshObj.standardPrompt || '>$%#') + ']\\s?$' + ), standardPromptFallback: custom.usedFallback, }; } @@ -216,6 +222,7 @@ function redactCredentials(value, seen = new WeakSet()) { module.exports = { compileAsciiFilter, + // noinspection JSUnusedGlobalSymbols compilePromptRegex, compilePrompts, compileTextColorFilter, diff --git a/test/live/bash_script.js b/test/live/bash_script.js index 3ad55d3..e3e029a 100644 --- a/test/live/bash_script.js +++ b/test/live/bash_script.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('bash_script.js'); diff --git a/test/live/chaining.js b/test/live/chaining.js index a96c56c..52ea04f 100644 --- a/test/live/chaining.js +++ b/test/live/chaining.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('chaining.js'); diff --git a/test/live/close_from_handler.js b/test/live/close_from_handler.js index de5f7b2..b8fcd46 100644 --- a/test/live/close_from_handler.js +++ b/test/live/close_from_handler.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('close_from_handler.js'); diff --git a/test/live/command_timeout.js b/test/live/command_timeout.js index 9d081ea..5a288bc 100644 --- a/test/live/command_timeout.js +++ b/test/live/command_timeout.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('command_timeout.js'); @@ -22,7 +22,7 @@ const host = { passPhrase: process.env.KEY_PASSPHRASE, }, commands: [promptCommand], - onCommandTimeout: function (command, response, stream, connection) { + onCommandTimeout: function (command, response, stream) { if (command === promptCommand && /** @type {string} */ (response).includes('[Y/n]?') && this.sshObj.answeredNode !== true) { diff --git a/test/live/default_command_timeout.js b/test/live/default_command_timeout.js index 7aef32d..cc0d5d6 100644 --- a/test/live/default_command_timeout.js +++ b/test/live/default_command_timeout.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('default_command_timeout.js'); diff --git a/test/live/fingerprint.js b/test/live/fingerprint.js index b8563f1..0e5b3e8 100644 --- a/test/live/fingerprint.js +++ b/test/live/fingerprint.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('fingerprint.js'); @@ -6,6 +6,23 @@ logFile('fingerprint.js'); const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); +/** @type {import('../../index').HostVerifier} */ +const verifyHostKey = function (hashedKey) { + const expectedHash = process.env.EXPECTED_HOST_HASH; + + // With no pin recorded, print the hash and accept the first connection. + if (!expectedHash) { + const message = `Server hash: ${hashedKey}`; + log(message); + console.log(message); + return true; + } + + // noinspection JSValidateTypes + const hash = /** @type {string} */ (hashedKey); + return hash.toLowerCase() === expectedHash.toLowerCase(); +}; + /** @type {import('../../index').HostConfig} */ const host = { server: { @@ -15,22 +32,7 @@ const host = { privateKey: readPrivateKey(), passPhrase: process.env.KEY_PASSPHRASE, hostHash: 'sha256', // any crypto.getHashes() algorithm - hostVerifier: function (hashedKey) { - const expectedHash = process.env.EXPECTED_HOST_HASH; - - // With no pin recorded, print the hash and accept the first connection. - if (!expectedHash) { - const message = `Server hash: ${hashedKey}`; - log(message); - console.log(message); - return true; - } - - return ( - /** @type {string} */ (hashedKey).toLowerCase() === - expectedHash.toLowerCase() - ); - }, + hostVerifier: verifyHostKey, }, commands: ['whoami'] }; diff --git a/test/live/graceful_close.js b/test/live/graceful_close.js index 51e34fe..3c00ccf 100644 --- a/test/live/graceful_close.js +++ b/test/live/graceful_close.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('graceful_close.js'); diff --git a/test/live/hop_host_key.js b/test/live/hop_host_key.js index d34966d..8d0952d 100644 --- a/test/live/hop_host_key.js +++ b/test/live/hop_host_key.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('hop_host_key.js'); diff --git a/test/live/hop_keyboard_interactive.js b/test/live/hop_keyboard_interactive.js index 71f6308..6f834a8 100644 --- a/test/live/hop_keyboard_interactive.js +++ b/test/live/hop_keyboard_interactive.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('hop_keyboard_interactive.js'); diff --git a/test/live/host_faults.js b/test/live/host_faults.js index d7d15cb..f5145bf 100644 --- a/test/live/host_faults.js +++ b/test/live/host_faults.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('host_faults.js'); diff --git a/test/live/host_traversal.js b/test/live/host_traversal.js index 8b98363..75a32be 100644 --- a/test/live/host_traversal.js +++ b/test/live/host_traversal.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('host_traversal.js'); diff --git a/test/live/keyboard-interactive.js b/test/live/keyboard-interactive.js index d240df9..04539d3 100644 --- a/test/live/keyboard-interactive.js +++ b/test/live/keyboard-interactive.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('keyboard-interactive.js'); diff --git a/test/live/lots_of_commands.js b/test/live/lots_of_commands.js index 840a4c9..4c35e6f 100644 --- a/test/live/lots_of_commands.js +++ b/test/live/lots_of_commands.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('lots_of_commands.js'); diff --git a/test/live/multiple_primary_hosts.js b/test/live/multiple_primary_hosts.js index 6e06cb6..db947a5 100644 --- a/test/live/multiple_primary_hosts.js +++ b/test/live/multiple_primary_hosts.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('multiple_primary_hosts.js'); diff --git a/test/live/notifications.js b/test/live/notifications.js index 4537d9c..ce715a7 100644 --- a/test/live/notifications.js +++ b/test/live/notifications.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('notifications.js'); diff --git a/test/live/pipe.js b/test/live/pipe.js index 7c10fcc..5d52dab 100644 --- a/test/live/pipe.js +++ b/test/live/pipe.js @@ -1,6 +1,6 @@ const path = require('node:path'); const fs = require('node:fs'); -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('pipe.js'); diff --git a/test/live/private_key.js b/test/live/private_key.js index 47ae75b..c2cece4 100644 --- a/test/live/private_key.js +++ b/test/live/private_key.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); @@ -20,7 +20,7 @@ const host = { host: process.env.HOST, port: process.env.PORT, userName: process.env.USER_NAME, - privateKey: fs.readFileSync(keyPath), + privateKey: /** @type {any} */ (fs.readFileSync(keyPath)), passPhrase: process.env.KEY_PASSPHRASE, // omit if the key has no passphrase }, commands: ['whoami'] diff --git a/test/live/progress.js b/test/live/progress.js index f3b0191..ff56426 100644 --- a/test/live/progress.js +++ b/test/live/progress.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('progress.js'); diff --git a/test/live/progress_tty.js b/test/live/progress_tty.js index 5d4be91..a0fb296 100644 --- a/test/live/progress_tty.js +++ b/test/live/progress_tty.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('progress_tty.js'); diff --git a/test/live/prompt_response.js b/test/live/prompt_response.js index a34fef8..87de9a5 100644 --- a/test/live/prompt_response.js +++ b/test/live/prompt_response.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('prompt_response.js'); diff --git a/test/live/simple.js b/test/live/simple.js index dcaaf4d..410fc7d 100644 --- a/test/live/simple.js +++ b/test/live/simple.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('simple.js'); diff --git a/test/live/stop_multiple_hosts.js b/test/live/stop_multiple_hosts.js index 4c1a541..aa175a7 100644 --- a/test/live/stop_multiple_hosts.js +++ b/test/live/stop_multiple_hosts.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('stop_multiple_hosts.js'); diff --git a/test/live/stop_on_failure.js b/test/live/stop_on_failure.js index ac6c019..2ed876f 100644 --- a/test/live/stop_on_failure.js +++ b/test/live/stop_on_failure.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('stop_on_failure.js'); diff --git a/test/live/sudo_abort.js b/test/live/sudo_abort.js index 36cec5a..f6ef892 100644 --- a/test/live/sudo_abort.js +++ b/test/live/sudo_abort.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('sudo_abort.js'); diff --git a/test/live/sudo_no_pass.js b/test/live/sudo_no_pass.js index 5cddd07..d001fea 100644 --- a/test/live/sudo_no_pass.js +++ b/test/live/sudo_no_pass.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('sudo_no_pass.js'); diff --git a/test/live/sudo_rejected.js b/test/live/sudo_rejected.js index d563697..5aef724 100644 --- a/test/live/sudo_rejected.js +++ b/test/live/sudo_rejected.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('sudo_rejected.js'); diff --git a/test/live/sudo_su.js b/test/live/sudo_su.js index db8158b..175f9dd 100644 --- a/test/live/sudo_su.js +++ b/test/live/sudo_su.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('sudo_su.js'); diff --git a/test/live/timeout.js b/test/live/timeout.js index 7c3cea8..0a0fb57 100644 --- a/test/live/timeout.js +++ b/test/live/timeout.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('timeout.js'); @@ -31,7 +31,7 @@ const host = { standardPrompt: '$', idleTimeOut: 5000, FirstPass: false, - onCommandTimeout: function (command, response, stream, connection) { + onCommandTimeout: function (command, response, stream) { this.systemMsg( 'debug', `${this.sshObj.server.host}: host.onCommandTimeout` diff --git a/test/live/timeout_retries.js b/test/live/timeout_retries.js index 758d073..09a3b29 100644 --- a/test/live/timeout_retries.js +++ b/test/live/timeout_retries.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('timeout_retries.js'); diff --git a/test/live/transport_drop.js b/test/live/transport_drop.js index 9e6028f..978f560 100644 --- a/test/live/transport_drop.js +++ b/test/live/transport_drop.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('transport_drop.js'); diff --git a/test/live/tunnel.js b/test/live/tunnel.js index f1d1248..e264bb8 100644 --- a/test/live/tunnel.js +++ b/test/live/tunnel.js @@ -1,4 +1,4 @@ -const dotenv = require('dotenv').config(); +require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('tunnel.js'); diff --git a/test/types/consumer.ts b/test/types/consumer.ts new file mode 100644 index 0000000..ba7ec85 --- /dev/null +++ b/test/types/consumer.ts @@ -0,0 +1,31 @@ +import SSH2Shell = require('ssh2shell'); + +type HostConfig = import('ssh2shell').HostConfig; + +const host: HostConfig = { + server: { host: 'example.test', userName: 'user' }, + commands: ['whoami'], + onCommandProcessing(command, response) { + void response.includes('working'); + }, + onCommandComplete(command, response) { + const missing = response.includes('not installed'); + this.stop(missing ? 'missing' : 'present'); + }, + onCommandTimeout(command, response) { + void response.includes('prompt'); + }, + onData(data) { + if (typeof data !== 'string') { + void data.byteLength; + } + }, +}; + +const ssh = new SSH2Shell(host); +const chained: SSH2Shell = ssh.stop('typecheck'); +void chained; + +ssh.on('commandComplete', (command, response) => { + void response.includes('prompt'); +}); diff --git a/test/unit/api-baseline.test.js b/test/unit/api-baseline.test.js index 825d1d5..858c3fc 100644 --- a/test/unit/api-baseline.test.js +++ b/test/unit/api-baseline.test.js @@ -197,7 +197,7 @@ describe('_loadDefaults baseline', () => { } // pty is forced to true on baseline; current keeps an explicit false. - assert.equal(ssh.sshObj.pty, isBaseline() ? true : false); + assert.equal(ssh.sshObj.pty, isBaseline()); }); it('ignores the legacy passwordPromt/passphrasePromt aliases', () => { @@ -234,8 +234,8 @@ describe('_loadDefaults baseline', () => { it('keeps explicit window and pty false instead of forcing true', () => { const { ssh } = makeLoaded({ window: false, pty: false }); - assert.equal(ssh.sshObj.window, isBaseline() ? true : false); - assert.equal(ssh.sshObj.pty, isBaseline() ? true : false); + assert.equal(ssh.sshObj.window, isBaseline()); + assert.equal(ssh.sshObj.pty, isBaseline()); }); it('compiles the default prompt regexes', () => { diff --git a/test/unit/behavior-hardening.test.js b/test/unit/behavior-hardening.test.js index 965d4ad..53865c9 100644 --- a/test/unit/behavior-hardening.test.js +++ b/test/unit/behavior-hardening.test.js @@ -65,7 +65,7 @@ describe('behaviour hardening', () => { const timers = []; global.setTimeout = (callback) => { timers.push(callback); - return { unref() {} }; + return /** @type {any} */ ({ unref() {} }); }; try { @@ -96,7 +96,7 @@ describe('behaviour hardening', () => { const savedSetTimeout = global.setTimeout; global.setTimeout = (callback) => { secondTimers.push(callback); - return { unref() {} }; + return /** @type {any} */ ({ unref() {} }); }; secondSsh.command = ''; secondSsh._onData('second data'); @@ -161,7 +161,7 @@ describe('behaviour hardening', () => { global.setTimeout = (callback) => { timerCallback = callback; - return { unref() {} }; + return /** @type {any} */ ({ unref() {} }); }; global.clearTimeout = () => {}; @@ -242,7 +242,7 @@ describe('behaviour hardening', () => { newOnly('clears the close timer when moving to the next primary', () => { const { ssh, host } = make(); const originalSetTimeout = global.setTimeout; - global.setTimeout = () => ({ unref() {} }); + global.setTimeout = /** @type {any} */ (() => ({ unref() {} })); try { ssh._armCloseTimer(); diff --git a/test/unit/coverage-gaps-state.test.js b/test/unit/coverage-gaps-state.test.js index 0a6a187..05e9201 100644 --- a/test/unit/coverage-gaps-state.test.js +++ b/test/unit/coverage-gaps-state.test.js @@ -28,6 +28,7 @@ function make(overrides = {}) { return { ssh, host }; } +/** @returns {any} */ function shellConnection(stream) { return { shell(window, callback) { @@ -70,10 +71,12 @@ describe('coverage gaps: state and transport guards', () => { ssh._openShell(context); context.closed = true; + // noinspection JSCheckFunctionSignatures stream.emit('error', new Error('stale stream error')); assert.deepEqual(failures, []); context.closed = false; + // noinspection JSCheckFunctionSignatures stream.emit('error', new Error('hop stream error')); assert.deepEqual(failures, ['hop stream error']); }); @@ -107,6 +110,7 @@ describe('coverage gaps: state and transport guards', () => { throw new Error('listener boom'); }); + // noinspection JSCheckFunctionSignatures stream.emit('data', 'command output'); const args = errors.find((entry) => entry[1] === 'Stream.read error'); @@ -129,6 +133,7 @@ describe('coverage gaps: state and transport guards', () => { throw new Error('listener boom'); }); + // noinspection JSCheckFunctionSignatures stream.emit('data', 'hop output'); assert.equal(failures.length, 1); @@ -161,11 +166,11 @@ describe('coverage gaps: state and transport guards', () => { let completeForwardOut; const parent = ssh._pushContext(createHost(), null); - parent.connection = { + parent.connection = /** @type {any} */ ({ forwardOut(srcIP, srcPort, dstIP, dstPort, callback) { completeForwardOut = callback; }, - }; + }); ssh._connect(parent); const child = ssh._activeContext(); @@ -188,11 +193,11 @@ describe('coverage gaps: state and transport guards', () => { let completeForwardOut; const parent = ssh._pushContext(createHost(), null); - parent.connection = { + parent.connection = /** @type {any} */ ({ forwardOut(srcIP, srcPort, dstIP, dstPort, callback) { completeForwardOut = callback; }, - }; + }); ssh._connect(parent); const child = ssh._activeContext(); @@ -224,7 +229,7 @@ describe('coverage gaps: state and transport guards', () => { context.isPrimary = false; const connection = new EventEmitter(); - context.connection = connection; + context.connection = /** @type {any} */ (connection); const failures = []; ssh._hopFailed = (failedContext, error) => failures.push(error.message); ssh._appendPartial = () => {}; diff --git a/test/unit/helpers/fake-ssh2.js b/test/unit/helpers/fake-ssh2.js index f163989..0bfff3c 100644 --- a/test/unit/helpers/fake-ssh2.js +++ b/test/unit/helpers/fake-ssh2.js @@ -33,6 +33,7 @@ class FakeStream extends EventEmitter { if (this.closed) return; this.closed = true; this.emit('finish'); + // noinspection JSCheckFunctionSignatures this.emit('close', 0, null); } @@ -114,6 +115,7 @@ class FakeClient extends EventEmitter { // Completes a pending `forwardOut` request. Used by tests that need to stop // or close while the channel request is in flight. + // noinspection JSUnusedGlobalSymbols completeForwardOut(err = null) { if (typeof this.forwardOutCallback !== 'function') { return null; @@ -151,6 +153,7 @@ class FakeClient extends EventEmitter { end() { if (this.ended) return; this.ended = true; + // noinspection JSCheckFunctionSignatures process.nextTick(() => this.emit('close', false)); } } diff --git a/test/unit/helpers/harness.js b/test/unit/helpers/harness.js index 357480f..29024c4 100644 --- a/test/unit/helpers/harness.js +++ b/test/unit/helpers/harness.js @@ -4,6 +4,13 @@ const path = require('node:path'); const fakeSsh2 = require('./fake-ssh2'); +/** + * Host fixture with runtime-only fields shared by the current and baseline + * targets. A permissive index signature keeps those characterization asserts + * type-aware without pretending the frozen baseline has declarations. + * @typedef {import('../../../index').HostConfig & Record} TestHost + */ + const repoRoot = path.join(__dirname, '..', '..', '..'); const currentModulePath = path.join(repoRoot, 'lib', 'ssh2shell.js'); const baselineModulePath = path.join( @@ -37,12 +44,12 @@ function installFakeSsh2(fake = fakeSsh2) { const ssh2Path = require.resolve('ssh2'); const previous = require.cache[ssh2Path]; - require.cache[ssh2Path] = { + require.cache[ssh2Path] = /** @type {any} */ ({ id: ssh2Path, filename: ssh2Path, loaded: true, exports: fake, - }; + }); return function restore() { if (previous) { @@ -67,6 +74,7 @@ function systemMsg(ssh, type, message, object = null) { : ssh.systemMsg(type, message, object); } +/** @returns {TestHost} */ function createHost(overrides = {}) { const server = Object.assign( { diff --git a/test/unit/l5-behavior.test.js b/test/unit/l5-behavior.test.js index 2add57f..355dd99 100644 --- a/test/unit/l5-behavior.test.js +++ b/test/unit/l5-behavior.test.js @@ -69,8 +69,7 @@ describe('L5 listener lifecycle', () => { it('removes a host handler assigned after the defaults were loaded', () => { const { ssh, host } = make(); - const lateHandler = () => {}; - host.onCommandComplete = lateHandler; + host.onCommandComplete = () => {}; ssh._removeListeners(); diff --git a/test/unit/timers.test.js b/test/unit/timers.test.js index a02c299..16ea958 100644 --- a/test/unit/timers.test.js +++ b/test/unit/timers.test.js @@ -85,12 +85,11 @@ describe('instance timer values', () => { assert.equal(ssh.idleTime, 123); ssh._removeListeners(); - const second = createHost({ + ssh.sshObj = createHost({ idleTimeOut: undefined, dataIdleTime: undefined, dataIdleTimeOut: undefined, }); - ssh.sshObj = second; ssh._loadDefaults(); // Baseline reloads its hard-coded defaults for the second host. diff --git a/test/utils/logging.js b/test/utils/logging.js index 0f3167a..f14781f 100644 --- a/test/utils/logging.js +++ b/test/utils/logging.js @@ -14,7 +14,8 @@ function logFile(name) { fs.mkdirSync(logDir, { recursive: true }); fs.writeFileSync(currentLogFile, '', 'utf8'); } catch (err) { - throw new Error(`Failed to write file: ${currentLogFile}`, err); + // noinspection JSCheckFunctionSignatures + throw new Error(`Failed to write file: ${currentLogFile}`, { cause: err }); } } @@ -30,7 +31,8 @@ function log(content) { try { fs.writeFileSync(currentLogFile, `${content}\n`, { encoding: 'utf8', flag: 'a' }); } catch (err) { - throw new Error(`Failed to append to log: ${currentLogFile}`, err); + // noinspection JSCheckFunctionSignatures + throw new Error(`Failed to append to log: ${currentLogFile}`, { cause: err }); } } diff --git a/test/utils/private_key.js b/test/utils/private_key.js index 932aece..34fc011 100644 --- a/test/utils/private_key.js +++ b/test/utils/private_key.js @@ -6,6 +6,7 @@ const path = require('node:path'); // Loads the live-test private key. `~` is not expanded by fs, so resolve it // against the current user's home directory first. +/** @returns {any} */ function readPrivateKey() { const configured = process.env.PRIVATE_KEY_PATH || '~/.ssh/id_rsa'; const resolved = path.resolve( diff --git a/tsconfig.consumer-nodenext.json b/tsconfig.consumer-nodenext.json new file mode 100644 index 0000000..b51aac2 --- /dev/null +++ b/tsconfig.consumer-nodenext.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.consumer.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext" + } +} diff --git a/tsconfig.consumer.json b/tsconfig.consumer.json new file mode 100644 index 0000000..ea7960b --- /dev/null +++ b/tsconfig.consumer.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "Node16", + "strict": true, + "noEmit": true, + "skipLibCheck": true + }, + "files": ["test/types/consumer.ts"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..2a19401 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "./tsconfig.typecheck.json", + "include": ["index.d.ts", "test/types/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/tsconfig.typecheck.json b/tsconfig.typecheck.json new file mode 100644 index 0000000..153378b --- /dev/null +++ b/tsconfig.typecheck.json @@ -0,0 +1,38 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "Node16", + "allowJs": true, + "checkJs": true, + "noEmit": true, + "skipLibCheck": true, + "noImplicitAny": false + }, + "files": [ + "src/ssh2shell.js", + "src/ssh2shell/defaults.js", + "src/ssh2shell/util.js", + "scripts/build.js", + "scripts/check-build.js", + "scripts/check-changelog.js", + "scripts/live-instrument.js", + "scripts/run-live.js", + "scripts/run-tests.js", + "test/live/simple.js", + "test/live/notifications.js", + "test/live/private_key.js", + "test/live/fingerprint.js", + "test/live/sudo_no_pass.js", + "test/live/sudo_su.js", + "test/live/prompt_response.js", + "test/live/command_timeout.js", + "test/live/multiple_primary_hosts.js", + "test/live/host_faults.js", + "test/live/tunnel.js", + "test/live/chaining.js", + "test/live/host_traversal.js", + "test/live/bash_script.js", + "test/live/keyboard-interactive.js" + ] +}