From de413db571834f1ce2266312b174ec0bff75c9de Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Tue, 24 Nov 2026 22:24:54 +1300 Subject: [PATCH 1/6] types: add public declaration file Declares SSH2Shell, HostConfig, ServerConfig, handlers, and event payloads, and points package.json at index.d.ts. No TypeScript build or runtime dependency is added. --- index.d.ts | 257 +++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 + 2 files changed, 259 insertions(+) create mode 100644 index.d.ts diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..70b124d --- /dev/null +++ b/index.d.ts @@ -0,0 +1,257 @@ +// Public TypeScript declarations for ssh2shell 4.x. +// The runtime package is plain CommonJS JavaScript; this file describes the +// public surface without adding a build step or runtime dependency. + +declare class SSH2Shell { + constructor( + hosts: SSH2Shell.HostConfig | ReadonlyArray + ); + + /** The active host object, including runtime state added during a run. */ + sshObj: SSH2Shell.HostConfig; + /** The command currently being processed. */ + command: string; + /** Active command timeout in milliseconds. */ + idleTime: number; + /** Active response-settling delay in milliseconds. */ + dataIdleTime: number; + /** Effective debug flag; assigning sets a run-wide override. */ + debug: boolean; + /** Effective verbose flag; assigning sets a run-wide override. */ + verbose: boolean; + + connect(callback?: (sessionText: string) => void): boolean; + stop(reason?: string): unknown; + close(options?: SSH2Shell.CloseOptions): unknown; + systemMsg(type: string, message: string, object?: unknown): void; + + on( + event: E, + listener: (this: SSH2Shell, ...args: SSH2Shell.EventMap[E]) => void + ): this; + on(event: string, listener: (...args: any[]) => void): this; + + addListener( + event: E, + listener: (this: SSH2Shell, ...args: SSH2Shell.EventMap[E]) => void + ): this; + addListener(event: string, listener: (...args: any[]) => void): this; + + once( + event: E, + listener: (this: SSH2Shell, ...args: SSH2Shell.EventMap[E]) => void + ): this; + once(event: string, listener: (...args: any[]) => void): this; + + removeListener( + event: E, + listener: (this: SSH2Shell, ...args: SSH2Shell.EventMap[E]) => void + ): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + + removeAllListeners(event?: keyof SSH2Shell.EventMap | string): this; + emit(event: keyof SSH2Shell.EventMap | string, ...args: any[]): boolean; + pipe(destination: T, options?: unknown): T; +} + +declare namespace SSH2Shell { + interface ServerConfig { + host?: string; + hostname?: string; + port?: number | string; + userName?: string; + username?: string; + password?: string; + privateKey?: string | Uint8Array; + passPhrase?: string; + passphrase?: string; + tryKeyboard?: boolean; + hostHash?: string; + hostVerifier?: HostVerifier; + algorithms?: Record; + [option: string]: unknown; + } + + interface HostVerifier { + ( + hashedKey: string, + verify: (permitted: boolean) => void + ): boolean | void; + } + + interface ShellStream { + write(data: string | Uint8Array, encoding?: string): boolean; + close(): void; + on(event: string, listener: (...args: any[]) => void): this; + [property: string]: unknown; + } + + interface SSHConnection { + connect(options: Record): void; + forwardOut( + sourceIP: string, + sourcePort: number, + destinationIP: string, + destinationPort: number, + callback: (error: Error | null, stream?: ShellStream) => void + ): void; + on(event: string, listener: (...args: any[]) => void): this; + [property: string]: unknown; + } + + interface CommandCompleteDetails { + rawResponse: string | Uint8Array; + stderr?: string; + [property: string]: unknown; + } + + interface TimeoutDetails { + attempt: number; + maxRetries: number; + final: boolean; + } + + interface KeyboardInteractivePrompt { + prompt: string; + echo: boolean; + } + + type KeyboardInteractiveFinish = (responses: string[]) => void; + type ErrorCallback = (this: SSH2Shell, error: unknown, type: string) => void; + + type MessageHandler = (this: SSH2Shell, message: unknown) => void; + type DataHandler = ( + this: SSH2Shell, + data: string | Uint8Array + ) => void; + type CommandProcessingHandler = ( + this: SSH2Shell, + command: string, + response: string | Uint8Array, + host: HostConfig, + stream: ShellStream + ) => void; + type CommandCompleteHandler = ( + this: SSH2Shell, + command: string, + response: string | Uint8Array, + host: HostConfig, + details: CommandCompleteDetails + ) => void; + type CommandTimeoutHandler = ( + this: SSH2Shell, + command: string, + response: string | Uint8Array, + stream: ShellStream, + connection: SSHConnection, + details: TimeoutDetails + ) => void; + type EndHandler = ( + this: SSH2Shell, + sessionText: string, + host: HostConfig + ) => void; + type ErrorHandler = ( + this: SSH2Shell, + error: unknown, + type: string, + close?: boolean | null, + callback?: ErrorCallback, + context?: unknown + ) => void; + type KeyboardInteractiveHandler = ( + this: SSH2Shell, + name: string, + instructions: string, + instructionsLanguage: string, + prompts: KeyboardInteractivePrompt[], + finish: KeyboardInteractiveFinish + ) => void; + + interface EventMap { + 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 + ]; + end: [string, HostConfig]; + error: [ + unknown, + string, + (boolean | null)?, + ErrorCallback?, + unknown? + ]; + 'keyboard-interactive': [ + string, + string, + string, + KeyboardInteractivePrompt[], + KeyboardInteractiveFinish + ]; + } + + interface CloseOptions { + graceful?: boolean; + } + + interface HostConfig { + server: ServerConfig; + commands: string[]; + hosts?: HostConfig[]; + + connectedMessage?: string; + readyMessage?: string; + closedMessage?: string; + verbose?: boolean; + debug?: boolean; + progress?: boolean; + exposeCredentials?: boolean; + showBanner?: boolean; + enter?: string; + streamEncoding?: string; + window?: boolean | Record; + pty?: boolean; + + standardPrompt?: string; + standardPromptRegex?: string | RegExp; + passwordPrompt?: string; + passPromptText?: string; + commandResponse?: 'raw' | 'handled'; + captureStderr?: boolean; + asciiFilter?: string; + disableASCIIFilter?: boolean; + textColorFilter?: string; + disableColorFilter?: boolean; + + idleTimeOut?: number; + dataIdleTimeOut?: number; + commandTimeoutRetries?: number; + + onMsg?: MessageHandler; + onData?: DataHandler; + onStderrData?: DataHandler; + onCommandProcessing?: CommandProcessingHandler; + onCommandComplete?: CommandCompleteHandler; + onCommandTimeout?: CommandTimeoutHandler; + onEnd?: EndHandler; + onError?: ErrorHandler; + onKeyboardInteractive?: KeyboardInteractiveHandler; + + [property: string]: unknown; + } +} + +export = SSH2Shell; diff --git a/package.json b/package.json index 0033569..17a7c25 100644 --- a/package.json +++ b/package.json @@ -4,8 +4,10 @@ "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", "files": [ "lib", + "index.d.ts", "CHANGELOG.md" ], "engines": { From f59be3c78b4ce834c86aa18bb8cd276933bf2b4b Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Tue, 24 Nov 2026 22:27:24 +1300 Subject: [PATCH 2/6] docs: add JSDoc type aliases to source Links the runtime source to the public declaration file and annotates the main public and helper signatures. No TypeScript dependency or ts-check gate is added yet. --- lib/ssh2shell.js | 44 +++++++++++++++++++++++++++++++++++++++ lib/ssh2shell/defaults.js | 8 +++++++ lib/ssh2shell/util.js | 36 ++++++++++++++++++++++++++++++++ src/ssh2shell.js | 44 +++++++++++++++++++++++++++++++++++++++ src/ssh2shell/defaults.js | 8 +++++++ src/ssh2shell/util.js | 36 ++++++++++++++++++++++++++++++++ 6 files changed, 176 insertions(+) diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index 23accba..24c681a 100644 --- a/lib/ssh2shell.js +++ b/lib/ssh2shell.js @@ -8,6 +8,25 @@ // real ssh2 connections opened through the parent connection's forwardOut // channel; there is no nested `ssh` command. +// Public type contracts live in index.d.ts. These aliases make the same +// contracts available to editors and JSDoc-aware tooling without a build step. +/** + * @typedef {import('../index').HostConfig} HostConfig + * @typedef {import('../index').ServerConfig} ServerConfig + * @typedef {import('../index').CommandCompleteDetails} CommandCompleteDetails + * @typedef {import('../index').TimeoutDetails} TimeoutDetails + * @typedef {import('../index').ShellStream} ShellStream + * @typedef {import('../index').SSHConnection} SSHConnection + * @typedef {import('../index').MessageHandler} MessageHandler + * @typedef {import('../index').DataHandler} DataHandler + * @typedef {import('../index').CommandProcessingHandler} CommandProcessingHandler + * @typedef {import('../index').CommandCompleteHandler} CommandCompleteHandler + * @typedef {import('../index').CommandTimeoutHandler} CommandTimeoutHandler + * @typedef {import('../index').EndHandler} EndHandler + * @typedef {import('../index').ErrorHandler} ErrorHandler + * @typedef {import('../index').KeyboardInteractiveHandler} KeyboardInteractiveHandler + */ + const Stream = require('node:stream'); const { applyHostDefaults } = require('./ssh2shell/defaults'); @@ -66,6 +85,9 @@ function stripEchoedCommand(buffer, command) { } class SSH2Shell extends Stream { + /** + * @param {HostConfig | HostConfig[]} hosts A host config or a non-empty array of them. + */ constructor(hosts) { super(hosts); @@ -353,6 +375,10 @@ class SSH2Shell extends Stream { // Copy the server options so the host config is not mutated. `ssh2` uses // `username` / `passphrase`; `userName` / `passPhrase` are the public names. + /** + * @param {ServerConfig | undefined} server Host server configuration. + * @returns {ServerConfig} A copied config with ssh2-native names. + */ _normalizeServer(server) { const options = Object.assign({}, server || {}); delete options.ssh; @@ -796,6 +822,12 @@ class SSH2Shell extends Stream { // Emits debug/verbose messages only when the matching flag is enabled. // An optional object payload is emitted as a second message. + /** + * @param {'debug' | 'verbose' | string} type Message channel. + * @param {string} message Message text. + * @param {unknown} [object] Optional structured payload. + * @returns {void} + */ systemMsg(type, message, object = null){ const enabled = (type === 'debug' && this._debug) || @@ -1665,6 +1697,10 @@ class SSH2Shell extends Stream { // Shutdown // --------------------------------------------------------------------------- + /** + * @param {string} [reason] Label reported in the stop message. + * @returns {unknown} The active stream placeholder or this instance. + */ stop(reason = 'user') { if (this._runComplete || this._stopping) { return this; @@ -1884,6 +1920,10 @@ class SSH2Shell extends Stream { return this._callFinalCallback(); } + /** + * @param {{ graceful?: boolean }} [options] Set `graceful` to back out of nested shells. + * @returns {unknown} The result of advancing the host queue, when applicable. + */ close(options = {}) { if (this._runComplete || this._closing) { return; @@ -2271,6 +2311,10 @@ class SSH2Shell extends Stream { this.systemMsg('verbose', 'loadDefaults: Config:', host); } + /** + * @param {(sessionText: string) => void} [callback] Receives the combined session text. + * @returns {boolean} The result of raising the internal `newPrimaryHost` event. + */ connect(callback) { // An instance owns one run. A second connect() used to drain the empty // host queue and call back with '', which looked like an empty session. diff --git a/lib/ssh2shell/defaults.js b/lib/ssh2shell/defaults.js index 3b54087..eff3dc6 100644 --- a/lib/ssh2shell/defaults.js +++ b/lib/ssh2shell/defaults.js @@ -1,7 +1,15 @@ 'use strict'; +/** + * @typedef {import('../../index').HostConfig} HostConfig + */ + // Applies the baseline host defaults in place. This mutates only the host // object; instance-level values (command, buffer, timers) stay in the class. +/** + * @param {HostConfig} sshObj Host config to fill in place. + * @returns {void} + */ function applyHostDefaults(sshObj) { if (!sshObj.connectedMessage) { sshObj.connectedMessage = 'Connected'; diff --git a/lib/ssh2shell/util.js b/lib/ssh2shell/util.js index 287e86f..5371e64 100644 --- a/lib/ssh2shell/util.js +++ b/lib/ssh2shell/util.js @@ -1,5 +1,11 @@ 'use strict'; +/** + * @typedef {import('../../index').HostConfig} HostConfig + * @typedef {{ filter: RegExp, usedFallback: boolean }} CompiledFilter + * @typedef {{ regex: RegExp | null, usedFallback: boolean }} CompiledPrompt + */ + const typeIsArray = Array.isArray; function escapeRegex(str) { @@ -18,6 +24,10 @@ function stripTerminalEscapes(value) { return String(value).replace(terminalEscapePattern, ''); } +/** + * @param {string} configured Configured ASCII filter pattern. + * @returns {CompiledFilter} Compiled filter and fallback flag. + */ function compileAsciiFilter(configured) { if (configured === '[^\r\n\x20-\x7e]') { return { filter: /[^\t\r\n\x20-\x7e]/g, usedFallback: false }; @@ -33,6 +43,10 @@ function compileAsciiFilter(configured) { return { filter: /[^\t\r\n\x20-\x7e]/g, usedFallback: true }; } +/** + * @param {string} configured Configured ANSI colour filter pattern. + * @returns {CompiledFilter} Compiled filter and fallback flag. + */ function compileTextColorFilter(configured) { if (configured === '\\x1b\\[[0-9;]*m') { return { filter: /\x1b\[[0-9;]*m/g, usedFallback: false }; @@ -51,6 +65,10 @@ function compileTextColorFilter(configured) { // the end so it cannot match mid-output. The stateful `g`/`y` flags are // stripped so repeated `.test()` calls stay stable, and `m` is stripped because // it would let the end anchor match a line end before the final prompt. +/** + * @param {string | RegExp | null | undefined} configured Optional full prompt pattern. + * @returns {CompiledPrompt} Compiled anchored regex or a fallback marker. + */ function compilePromptRegex(configured) { if (configured == null || configured === '') { return { regex: null, usedFallback: false }; @@ -71,6 +89,10 @@ function compilePromptRegex(configured) { } } +/** + * @param {HostConfig} sshObj Host config with prompt settings. + * @returns {{ passwordPrompt: RegExp, standardPrompt: RegExp, standardPromptFallback: boolean }} + */ function compilePrompts(sshObj) { // Prompts are fully sanitized at runtime via escapeRegex (they are cast as // pure literals, so no fallback is required). @@ -94,6 +116,10 @@ function compilePrompts(sshObj) { // password or passphrase. const CREDENTIAL_KEY = /^(password|passphrase|privateKey)$/i; +/** + * @param {HostConfig | null | undefined} sshObj Active host config. + * @returns {string[]} Credential values to redact from logs. + */ function credentialSecrets(sshObj) { const server = (sshObj && sshObj.server) || {}; @@ -107,6 +133,11 @@ function credentialSecrets(sshObj) { .map((secret) => String(secret)); } +/** + * @param {unknown} value String to scrub. + * @param {string[]} secrets Credential values to replace. + * @returns {unknown} Scrubbed string, or the original non-string value. + */ function redactString(value, secrets) { if (typeof value !== 'string' || secrets.length === 0) { return value; @@ -118,6 +149,11 @@ function redactString(value, secrets) { ); } +/** + * @param {unknown} value Value to copy with credential keys redacted. + * @param {WeakSet} [seen] Cycle tracker for recursive calls. + * @returns {unknown} Redacted copy, or the original primitive. + */ function redactCredentials(value, seen = new WeakSet()) { if (!value || typeof value !== 'object') { return value; diff --git a/src/ssh2shell.js b/src/ssh2shell.js index 23accba..24c681a 100644 --- a/src/ssh2shell.js +++ b/src/ssh2shell.js @@ -8,6 +8,25 @@ // real ssh2 connections opened through the parent connection's forwardOut // channel; there is no nested `ssh` command. +// Public type contracts live in index.d.ts. These aliases make the same +// contracts available to editors and JSDoc-aware tooling without a build step. +/** + * @typedef {import('../index').HostConfig} HostConfig + * @typedef {import('../index').ServerConfig} ServerConfig + * @typedef {import('../index').CommandCompleteDetails} CommandCompleteDetails + * @typedef {import('../index').TimeoutDetails} TimeoutDetails + * @typedef {import('../index').ShellStream} ShellStream + * @typedef {import('../index').SSHConnection} SSHConnection + * @typedef {import('../index').MessageHandler} MessageHandler + * @typedef {import('../index').DataHandler} DataHandler + * @typedef {import('../index').CommandProcessingHandler} CommandProcessingHandler + * @typedef {import('../index').CommandCompleteHandler} CommandCompleteHandler + * @typedef {import('../index').CommandTimeoutHandler} CommandTimeoutHandler + * @typedef {import('../index').EndHandler} EndHandler + * @typedef {import('../index').ErrorHandler} ErrorHandler + * @typedef {import('../index').KeyboardInteractiveHandler} KeyboardInteractiveHandler + */ + const Stream = require('node:stream'); const { applyHostDefaults } = require('./ssh2shell/defaults'); @@ -66,6 +85,9 @@ function stripEchoedCommand(buffer, command) { } class SSH2Shell extends Stream { + /** + * @param {HostConfig | HostConfig[]} hosts A host config or a non-empty array of them. + */ constructor(hosts) { super(hosts); @@ -353,6 +375,10 @@ class SSH2Shell extends Stream { // Copy the server options so the host config is not mutated. `ssh2` uses // `username` / `passphrase`; `userName` / `passPhrase` are the public names. + /** + * @param {ServerConfig | undefined} server Host server configuration. + * @returns {ServerConfig} A copied config with ssh2-native names. + */ _normalizeServer(server) { const options = Object.assign({}, server || {}); delete options.ssh; @@ -796,6 +822,12 @@ class SSH2Shell extends Stream { // Emits debug/verbose messages only when the matching flag is enabled. // An optional object payload is emitted as a second message. + /** + * @param {'debug' | 'verbose' | string} type Message channel. + * @param {string} message Message text. + * @param {unknown} [object] Optional structured payload. + * @returns {void} + */ systemMsg(type, message, object = null){ const enabled = (type === 'debug' && this._debug) || @@ -1665,6 +1697,10 @@ class SSH2Shell extends Stream { // Shutdown // --------------------------------------------------------------------------- + /** + * @param {string} [reason] Label reported in the stop message. + * @returns {unknown} The active stream placeholder or this instance. + */ stop(reason = 'user') { if (this._runComplete || this._stopping) { return this; @@ -1884,6 +1920,10 @@ class SSH2Shell extends Stream { return this._callFinalCallback(); } + /** + * @param {{ graceful?: boolean }} [options] Set `graceful` to back out of nested shells. + * @returns {unknown} The result of advancing the host queue, when applicable. + */ close(options = {}) { if (this._runComplete || this._closing) { return; @@ -2271,6 +2311,10 @@ class SSH2Shell extends Stream { this.systemMsg('verbose', 'loadDefaults: Config:', host); } + /** + * @param {(sessionText: string) => void} [callback] Receives the combined session text. + * @returns {boolean} The result of raising the internal `newPrimaryHost` event. + */ connect(callback) { // An instance owns one run. A second connect() used to drain the empty // host queue and call back with '', which looked like an empty session. diff --git a/src/ssh2shell/defaults.js b/src/ssh2shell/defaults.js index 3b54087..eff3dc6 100644 --- a/src/ssh2shell/defaults.js +++ b/src/ssh2shell/defaults.js @@ -1,7 +1,15 @@ 'use strict'; +/** + * @typedef {import('../../index').HostConfig} HostConfig + */ + // Applies the baseline host defaults in place. This mutates only the host // object; instance-level values (command, buffer, timers) stay in the class. +/** + * @param {HostConfig} sshObj Host config to fill in place. + * @returns {void} + */ function applyHostDefaults(sshObj) { if (!sshObj.connectedMessage) { sshObj.connectedMessage = 'Connected'; diff --git a/src/ssh2shell/util.js b/src/ssh2shell/util.js index 287e86f..5371e64 100644 --- a/src/ssh2shell/util.js +++ b/src/ssh2shell/util.js @@ -1,5 +1,11 @@ 'use strict'; +/** + * @typedef {import('../../index').HostConfig} HostConfig + * @typedef {{ filter: RegExp, usedFallback: boolean }} CompiledFilter + * @typedef {{ regex: RegExp | null, usedFallback: boolean }} CompiledPrompt + */ + const typeIsArray = Array.isArray; function escapeRegex(str) { @@ -18,6 +24,10 @@ function stripTerminalEscapes(value) { return String(value).replace(terminalEscapePattern, ''); } +/** + * @param {string} configured Configured ASCII filter pattern. + * @returns {CompiledFilter} Compiled filter and fallback flag. + */ function compileAsciiFilter(configured) { if (configured === '[^\r\n\x20-\x7e]') { return { filter: /[^\t\r\n\x20-\x7e]/g, usedFallback: false }; @@ -33,6 +43,10 @@ function compileAsciiFilter(configured) { return { filter: /[^\t\r\n\x20-\x7e]/g, usedFallback: true }; } +/** + * @param {string} configured Configured ANSI colour filter pattern. + * @returns {CompiledFilter} Compiled filter and fallback flag. + */ function compileTextColorFilter(configured) { if (configured === '\\x1b\\[[0-9;]*m') { return { filter: /\x1b\[[0-9;]*m/g, usedFallback: false }; @@ -51,6 +65,10 @@ function compileTextColorFilter(configured) { // the end so it cannot match mid-output. The stateful `g`/`y` flags are // stripped so repeated `.test()` calls stay stable, and `m` is stripped because // it would let the end anchor match a line end before the final prompt. +/** + * @param {string | RegExp | null | undefined} configured Optional full prompt pattern. + * @returns {CompiledPrompt} Compiled anchored regex or a fallback marker. + */ function compilePromptRegex(configured) { if (configured == null || configured === '') { return { regex: null, usedFallback: false }; @@ -71,6 +89,10 @@ function compilePromptRegex(configured) { } } +/** + * @param {HostConfig} sshObj Host config with prompt settings. + * @returns {{ passwordPrompt: RegExp, standardPrompt: RegExp, standardPromptFallback: boolean }} + */ function compilePrompts(sshObj) { // Prompts are fully sanitized at runtime via escapeRegex (they are cast as // pure literals, so no fallback is required). @@ -94,6 +116,10 @@ function compilePrompts(sshObj) { // password or passphrase. const CREDENTIAL_KEY = /^(password|passphrase|privateKey)$/i; +/** + * @param {HostConfig | null | undefined} sshObj Active host config. + * @returns {string[]} Credential values to redact from logs. + */ function credentialSecrets(sshObj) { const server = (sshObj && sshObj.server) || {}; @@ -107,6 +133,11 @@ function credentialSecrets(sshObj) { .map((secret) => String(secret)); } +/** + * @param {unknown} value String to scrub. + * @param {string[]} secrets Credential values to replace. + * @returns {unknown} Scrubbed string, or the original non-string value. + */ function redactString(value, secrets) { if (typeof value !== 'string' || secrets.length === 0) { return value; @@ -118,6 +149,11 @@ function redactString(value, secrets) { ); } +/** + * @param {unknown} value Value to copy with credential keys redacted. + * @param {WeakSet} [seen] Cycle tracker for recursive calls. + * @returns {unknown} Redacted copy, or the original primitive. + */ function redactCredentials(value, seen = new WeakSet()) { if (!value || typeof value !== 'object') { return value; From 75a2a3156e81e1e4839789e5f8c1840fc41ecbbc Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Tue, 24 Nov 2026 23:09:27 +1300 Subject: [PATCH 3/6] types: enable ts-check in source files Adds the ts-check directive needed by editor tooling, with lib/ rebuilt to match src/. --- lib/ssh2shell.js | 1 + lib/ssh2shell/defaults.js | 1 + lib/ssh2shell/util.js | 1 + src/ssh2shell.js | 1 + src/ssh2shell/defaults.js | 1 + src/ssh2shell/util.js | 1 + 6 files changed, 6 insertions(+) diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index 24c681a..0b4d277 100644 --- a/lib/ssh2shell.js +++ b/lib/ssh2shell.js @@ -1,3 +1,4 @@ +// @ts-check // ssh2shell // 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 diff --git a/lib/ssh2shell/defaults.js b/lib/ssh2shell/defaults.js index eff3dc6..8b8a034 100644 --- a/lib/ssh2shell/defaults.js +++ b/lib/ssh2shell/defaults.js @@ -1,3 +1,4 @@ +// @ts-check 'use strict'; /** diff --git a/lib/ssh2shell/util.js b/lib/ssh2shell/util.js index 5371e64..1d1af84 100644 --- a/lib/ssh2shell/util.js +++ b/lib/ssh2shell/util.js @@ -1,3 +1,4 @@ +// @ts-check 'use strict'; /** diff --git a/src/ssh2shell.js b/src/ssh2shell.js index 24c681a..0b4d277 100644 --- a/src/ssh2shell.js +++ b/src/ssh2shell.js @@ -1,3 +1,4 @@ +// @ts-check // ssh2shell // 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 diff --git a/src/ssh2shell/defaults.js b/src/ssh2shell/defaults.js index eff3dc6..8b8a034 100644 --- a/src/ssh2shell/defaults.js +++ b/src/ssh2shell/defaults.js @@ -1,3 +1,4 @@ +// @ts-check 'use strict'; /** diff --git a/src/ssh2shell/util.js b/src/ssh2shell/util.js index 5371e64..1d1af84 100644 --- a/src/ssh2shell/util.js +++ b/src/ssh2shell/util.js @@ -1,3 +1,4 @@ +// @ts-check 'use strict'; /** From ee62370e77b91cd760716dc6a14981178b945a55 Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Wed, 25 Nov 2026 01:53:25 +1300 Subject: [PATCH 4/6] types: document public API for editors Add hand-maintained index.d.ts and package types/files entries, JSDoc aliases and @ts-check in source, and README guidance with annotated README-linked live tests. Record the editor-support additions under Unreleased and add an AI-assisted workflow prompt for maintaining the declarations. Runtime behavior is unchanged. --- .gitignore | 1 + CHANGELOG.md | 15 +++ README.md | 32 ++++++ docs/AI-ASSISTED-WORKFLOWS.md | 26 +++++ index.d.ts | 153 +++++++++++++++++++++++++++- lib/ssh2shell.js | 42 +++++--- src/ssh2shell.js | 42 +++++--- test/live/bash_script.js | 2 + test/live/chaining.js | 4 + test/live/command_timeout.js | 6 +- test/live/fingerprint.js | 2 + test/live/host_faults.js | 17 +++- test/live/host_traversal.js | 17 +++- test/live/multiple_primary_hosts.js | 3 + test/live/notifications.js | 2 + test/live/private_key.js | 2 + test/live/prompt_response.js | 4 +- test/live/simple.js | 2 + test/live/sudo_no_pass.js | 2 + test/live/sudo_su.js | 4 +- test/live/tunnel.js | 3 + 21 files changed, 348 insertions(+), 33 deletions(-) diff --git a/.gitignore b/.gitignore index 05f6669..7cd40dd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ pm-debug.log node_modules +.idea .env *.log test/logs/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d2f2b2..4df4bba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,21 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. ## [Unreleased] +### Added + +- `index.d.ts` now describes the public API, host and server configuration, + handlers, events, and runtime state for TypeScript and JavaScript editors. + The package points `types` at the declaration file and includes it in the + published files list. Runtime behavior is unchanged. +- README-linked live tests now carry JSDoc annotations that demonstrate the + same editor support, and the README explains the annotation pattern for + consumers. + +### Development + +- Added an AI-assisted workflow prompt for maintaining public declarations and + JSDoc annotations. + ## [4.1.0] - 2026-11-23 ### Added diff --git a/README.md b/README.md index 9afe02f..12e2c2b 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ one command to decide what to do next. - [Why ssh2shell](#why-ssh2shell) - [Installation](#installation) - [Quick start](#quick-start) +- [Editor support](#editor-support) - [Core concepts](#core-concepts) - [Configuration reference](#configuration-reference) - [`server`](#server) @@ -124,6 +125,37 @@ SSH.connect((sessionText) => { See [`test/live/simple.js`](./test/live/simple.js) for a runnable version that appends messages and session text to a log file. +## Editor support + +The package includes `index.d.ts`, so TypeScript projects get types without any +extra install step. The declarations describe the public API, the host object, +server options, event payloads, and handler signatures. + +Plain JavaScript gets the same hover and completion information from JSDoc. +Annotate the module import and any host objects you want to document: + +```javascript +/** @type {typeof import('ssh2shell')} */ +const SSH2Shell = require('ssh2shell'); + +/** @type {import('ssh2shell').HostConfig} */ +const host = { + server: { host: '192.168.0.10', userName: 'deploy' }, + commands: ['pwd'], +}; +``` + +The `HostConfig` annotation also gives contextual types to inline handlers such +as `onCommandProcessing`, including their `command`, `response`, `sshObj`, and +`stream` arguments. This is editor-only metadata; it does not change runtime +behaviour and does not add a TypeScript dependency to the package. + +The README-linked live tests use the same annotations with a relative import +because they live inside this repository. See +[`test/live/simple.js`](./test/live/simple.js), +[`test/live/fingerprint.js`](./test/live/fingerprint.js), and +[`test/live/tunnel.js`](./test/live/tunnel.js) for examples. + ## Core concepts **The host object.** A host object has two required parts: `server` (how to diff --git a/docs/AI-ASSISTED-WORKFLOWS.md b/docs/AI-ASSISTED-WORKFLOWS.md index de8121f..2f6acce 100644 --- a/docs/AI-ASSISTED-WORKFLOWS.md +++ b/docs/AI-ASSISTED-WORKFLOWS.md @@ -153,6 +153,32 @@ A change to is ready. Keep README.md concise and put detail in docs/. - Run npm run check:changelog and report what changed. ``` +## Add or update TypeScript declarations and JSDoc + +```text +You are adding editor/type support to ssh2shell. Start read-only. + +- Treat index.d.ts as a hand-maintained public contract derived from runtime + code and documentation, not a generated artifact. +- Read README.md, docs/API-BASELINE.md, index.d.ts, package.json, + 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. +- 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. +- Use import('ssh2shell') in consumer-facing docs. Inside README-linked live + 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. +- 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. +``` + ## Decide whether a fix needs a release ```text diff --git a/index.d.ts b/index.d.ts index 70b124d..8e9394f 100644 --- a/index.d.ts +++ b/index.d.ts @@ -3,6 +3,10 @@ // public surface without adding a build step or runtime dependency. declare class SSH2Shell { + /** + * Create a runner for one host or for several independent primary hosts. + * Each host needs a `server` object and a `commands` array. + */ constructor( hosts: SSH2Shell.HostConfig | ReadonlyArray ); @@ -11,18 +15,22 @@ declare class SSH2Shell { sshObj: SSH2Shell.HostConfig; /** The command currently being processed. */ command: string; - /** Active command timeout in milliseconds. */ + /** Active command timeout in milliseconds. Default: 5000. */ idleTime: number; - /** Active response-settling delay in milliseconds. */ + /** Active response-settling delay in milliseconds. Default: 500. */ dataIdleTime: number; /** Effective debug flag; assigning sets a run-wide override. */ debug: boolean; /** Effective verbose flag; assigning sets a run-wide override. */ verbose: boolean; + /** 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; + /** 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. */ systemMsg(type: string, message: string, object?: unknown): void; on( @@ -55,30 +63,60 @@ declare class SSH2Shell { } declare namespace SSH2Shell { + /** + * Connection options passed to `ssh2.Client.connect()`. + * + * `ssh2shell` validates only that `server` exists and contains `host` or + * `hostname`. Other values are passed through to `ssh2`, which reports + * invalid options through the shell's error handlers. + * + * @see https://github.com/cmp-202/ssh2shell#server + */ interface ServerConfig { + /** Host name or IP address. Required unless `hostname` is supplied. */ host?: string; + /** ssh2's alternative spelling of `host`. */ hostname?: string; + /** SSH port. Default: `22`. */ port?: number | string; + /** Login name. Required for authentication. */ userName?: string; + /** ssh2's native spelling of `userName`. */ username?: string; + /** Password authentication. */ password?: string; + /** Private key contents, usually from `fs.readFileSync()`. */ privateKey?: string | Uint8Array; + /** Passphrase for `privateKey`. ssh2's native `passphrase` also works. */ passPhrase?: string; + /** ssh2's native spelling of `passPhrase`. */ passphrase?: string; + /** Enable keyboard-interactive authentication. Default: `false`. */ tryKeyboard?: boolean; + /** Hash algorithm used to verify the server key, for example `sha256`. */ hostHash?: string; + /** Receives the hashed key when `hostHash` is set; use it to pin hosts. */ hostVerifier?: HostVerifier; + /** ssh2 cipher, compression, hmac, kex, and server host key overrides. */ algorithms?: Record; + /** Any other option accepted by `ssh2.Client.connect()`. */ [option: string]: unknown; } + /** Callback used to accept or reject a server host key. */ interface HostVerifier { + /** + * @param hashedKey The hashed key produced with `hostHash`. + * @param verify Call with `false` to reject, `true` to accept. + * @returns Returning `false` also rejects the key. + */ ( hashedKey: string, verify: (permitted: boolean) => void ): boolean | void; } + /** The live shell stream passed to command handlers. */ interface ShellStream { write(data: string | Uint8Array, encoding?: string): boolean; close(): void; @@ -86,8 +124,13 @@ declare namespace SSH2Shell { [property: string]: unknown; } + /** The ssh2 connection, used for `forwardOut` hops and diagnostics. */ interface SSHConnection { connect(options: Record): void; + /** + * Open a forwarded TCP channel for a nested host. The private key stays + * in this process; the jump host only forwards bytes. + */ forwardOut( sourceIP: string, sourcePort: number, @@ -99,31 +142,52 @@ declare namespace SSH2Shell { [property: string]: unknown; } + /** Extra values supplied with the `commandComplete` event. */ interface CommandCompleteDetails { + /** Always the unprocessed response buffer. */ rawResponse: string | Uint8Array; + /** Captured stderr when `captureStderr` is enabled. */ stderr?: string; [property: string]: unknown; } + /** Timeout bookkeeping supplied with the `commandTimeout` event. */ interface TimeoutDetails { + /** Current attempt, starting at 1. */ attempt: number; + /** `commandTimeoutRetries`, or 0 for a single attempt. */ maxRetries: number; + /** True on the final attempt, when the default handler closes. */ final: boolean; } + /** One prompt from a keyboard-interactive authentication request. */ interface KeyboardInteractivePrompt { prompt: string; echo: boolean; } + /** Finish a keyboard-interactive exchange with one response per prompt. */ type KeyboardInteractiveFinish = (responses: string[]) => void; - type ErrorCallback = (this: SSH2Shell, error: unknown, type: string) => void; + /** + * Called before the default error handling closes the connection. `close` + * reports whether that planned close is about to happen. + */ + type ErrorCallback = ( + this: SSH2Shell, + error: unknown, + type: string, + close?: boolean | null + ) => void; + /** Handles per-host `msg` notifications. */ type MessageHandler = (this: SSH2Shell, message: unknown) => void; + /** Handles raw shell or stderr data for a host. */ type DataHandler = ( this: SSH2Shell, data: string | Uint8Array ) => void; + /** Runs while output arrives, before prompt detection completes a command. */ type CommandProcessingHandler = ( this: SSH2Shell, command: string, @@ -131,6 +195,7 @@ declare namespace SSH2Shell { host: HostConfig, stream: ShellStream ) => void; + /** Runs when a command returns to the prompt. */ type CommandCompleteHandler = ( this: SSH2Shell, command: string, @@ -138,6 +203,7 @@ declare namespace SSH2Shell { host: HostConfig, details: CommandCompleteDetails ) => void; + /** Runs when no prompt is detected before `idleTimeOut`. */ type CommandTimeoutHandler = ( this: SSH2Shell, command: string, @@ -146,11 +212,13 @@ declare namespace SSH2Shell { connection: SSHConnection, details: TimeoutDetails ) => void; + /** Runs when a host session finishes. */ type EndHandler = ( this: SSH2Shell, sessionText: string, host: HostConfig ) => void; + /** Runs before the default error handler; `close` reports planned closure. */ type ErrorHandler = ( this: SSH2Shell, error: unknown, @@ -159,6 +227,7 @@ declare namespace SSH2Shell { callback?: ErrorCallback, context?: unknown ) => void; + /** Answers a keyboard-interactive authentication challenge. */ type KeyboardInteractiveHandler = ( this: SSH2Shell, name: string, @@ -168,6 +237,7 @@ declare namespace SSH2Shell { finish: KeyboardInteractiveFinish ) => void; + /** Instance event names mapped to their listener argument tuples. */ interface EventMap { msg: [unknown]; data: [string | Uint8Array]; @@ -203,53 +273,130 @@ declare namespace SSH2Shell { ]; } + /** Options for `close()`. */ interface CloseOptions { + /** Back out of nested shells before closing. */ graceful?: boolean; } + /** + * A host authored by a script. + * + * Only `server` and `commands` are required. `ssh2shell` fills defaults into + * this object and mutates it during a run, so use a fresh object, or clone + * one, before reusing it with another instance. + * + * @see https://github.com/cmp-202/ssh2shell#configuration-reference + */ interface HostConfig { + /** How ssh2shell connects. Passed through to `ssh2.Client.connect()`. */ server: ServerConfig; + + /** + * Commands to run in order on this host. + * + * `msg:text` emits a status message. Backtick-wrapped text is appended to + * `sessionText` without sending a command. + */ commands: string[]; + + /** Nested hosts reached through this connection using `forwardOut`. */ hosts?: HostConfig[]; + /** Message emitted when the connection opens. Default: `"Connected"`. */ connectedMessage?: string; + /** Message emitted when the shell is ready. Default: `"Ready"`. */ readyMessage?: string; + /** Message emitted when the connection closes. Default: `"Closed"`. */ closedMessage?: string; + /** Emit process details and the loaded host config. Default: `false`. */ verbose?: boolean; + /** Emit internal processing steps. Default: `false`. */ debug?: boolean; + /** Show a stderr liveness indicator while a command runs. Default: `true`; TTY only. */ progress?: boolean; + /** Redact credentials in debug/verbose output. Set `true` to show them; default: `false`. */ exposeCredentials?: boolean; + /** Include the host banner in `sessionText`. Default: `false`. */ showBanner?: boolean; + /** End-of-line sequence written after each command. Default: `"\n"`. */ enter?: string; + /** Encoding applied to the shell stream. Default: `"utf8"`. */ streamEncoding?: string; + /** First argument to `connection.shell()`. Default: `true`; an object sets terminal size. */ window?: boolean | Record; + /** Request a pseudo-terminal. Default: `true`; `false` also disables `window`. */ pty?: boolean; + /** Characters that identify a prompt. Default: `">$%#"` (end of line). */ standardPrompt?: string; + /** Full prompt regex; replaces `standardPrompt`. Anchored to the end; `g`, `y`, and `m` flags ignored. */ standardPromptRegex?: string | RegExp; + /** Text that identifies a password prompt. Default: `":"`. */ passwordPrompt?: string; + /** Text required before a password prompt. Default: `"Password"`. */ passPromptText?: string; + /** Call `stop('sudo-failed')` when sudo authentication is rejected or unavailable. Default: `false`. */ + abortOnSudoFailure?: boolean; + /** Response shape for `commandComplete`. Default: `"raw"`. */ commandResponse?: 'raw' | 'handled'; + /** Merge captured stderr into the response and `sessionText`. Default: `false`. */ captureStderr?: boolean; + /** Regex removing non-standard ASCII. Default: `"[^\\r\\n\\x20-\\x7e]"`. Complete terminal escape sequences are removed first. */ asciiFilter?: string; + /** Keep non-standard ASCII instead of filtering. Default: `false`. */ disableASCIIFilter?: boolean; + /** Regex removing ANSI colour codes. Default: `"\\x1b\\[[0-9;]*m"`. */ textColorFilter?: string; + /** Keep ANSI colour codes instead of filtering. Default: `false`. */ disableColorFilter?: boolean; + /** Milliseconds of silence before `commandTimeout` fires. Default: `5000`. */ idleTimeOut?: number; + /** Milliseconds of silence that ends a response burst. Default: `500`; keep below `idleTimeOut`. */ dataIdleTimeOut?: number; + /** Number of times to re-arm `commandTimeout` after a non-final attempt. Default: `0`. */ commandTimeoutRetries?: number; + /** Set `false` from `onCommandTimeout` to stop retrying the current command. */ + retryCommandTimeout?: boolean; + /** Per-host `msg` handler; replaces the default console sink. */ onMsg?: MessageHandler; + /** Handles raw data from the shell stream, in addition to internal processing. */ onData?: DataHandler; + /** Handles stderr data for this host. */ onStderrData?: DataHandler; + /** Runs on each output chunk before the command prompt is detected. */ onCommandProcessing?: CommandProcessingHandler; + /** Runs when a command returns to the prompt. */ onCommandComplete?: CommandCompleteHandler; + /** Runs when a command produces no prompt before `idleTimeOut`. */ onCommandTimeout?: CommandTimeoutHandler; + /** Runs when this host's session finishes. */ onEnd?: EndHandler; + /** Runs before the default error handler for errors on this host. */ onError?: ErrorHandler; + /** Answers keyboard-interactive authentication for this connection. */ onKeyboardInteractive?: KeyboardInteractiveHandler; + /** Accumulated raw output for this host. */ + sessionText?: string; + /** Runtime flag set once a password has been sent for this host. */ + pwSent?: boolean; + /** Runtime flag set when a sudo password is rejected. Starts `false` for each host. */ + sudoFailed?: boolean; + /** Reason passed to `stop()` when the run was stopped early. */ + stopReason?: string; + /** Set from a handler to stop after the completed command. */ + skipCommands?: boolean; + /** Set from a handler to skip this host's own nested hosts. */ + skipHosts?: boolean; + /** Set from a handler to skip the remaining primary hosts. */ + skipPrimaryHosts?: boolean; + /** Set from a handler to abort the whole run; a string becomes the stop reason. */ + abort?: string | boolean; + + /** Runtime state and forward-compatible host keys. */ [property: string]: unknown; } } diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index 0b4d277..13023fa 100644 --- a/lib/ssh2shell.js +++ b/lib/ssh2shell.js @@ -26,6 +26,7 @@ * @typedef {import('../index').EndHandler} EndHandler * @typedef {import('../index').ErrorHandler} ErrorHandler * @typedef {import('../index').KeyboardInteractiveHandler} KeyboardInteractiveHandler + * @typedef {Error & {level?: string, hadError?: boolean}} TaggedError */ const Stream = require('node:stream'); @@ -90,7 +91,7 @@ class SSH2Shell extends Stream { * @param {HostConfig | HostConfig[]} hosts A host config or a non-empty array of them. */ constructor(hosts) { - super(hosts); + super(); // Public entry points keep own bound copies so they can be detached and // passed around. `_connect` and `_connectHop` are passed as bare callbacks @@ -121,7 +122,8 @@ class SSH2Shell extends Stream { this._hosts = list.slice(); this._primaryHostCount = this._hosts.length; this._multipleHosts = this._primaryHostCount > 1; - this.sshObj = {}; + /** @type {HostConfig} */ + 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. this._connections = []; @@ -181,10 +183,14 @@ class SSH2Shell extends Stream { this.dataIdleTime = 500; this.idleTimer = null; this.dataReceivedTimer = null; - this.asciiFilter = ''; - this.textColorFilter = ''; - this.passwordPrompt = ''; - this.standardPrompt = ''; + /** @type {RegExp} */ + this.asciiFilter = /** @type {any} */ (''); + /** @type {RegExp} */ + this.textColorFilter = /** @type {any} */ (''); + /** @type {RegExp} */ + this.passwordPrompt = /** @type {any} */ (''); + /** @type {RegExp} */ + this.standardPrompt = /** @type {any} */ (''); this._loadDefaultListeners(); } @@ -267,7 +273,10 @@ class SSH2Shell extends Stream { this.systemMsg('debug', `Class.error: ${err}, ${type}`); if (err instanceof Error) { - this.emit('msg', `Error: ${err.message}, Level: ${err.level}`); + this.emit( + 'msg', + `Error: ${err.message}, Level: ${/** @type {TaggedError} */ (err).level}` + ); } else { this.emit('msg', `${type} error: ${err}`); } @@ -878,7 +887,10 @@ class SSH2Shell extends Stream { } this._progressEnd(); - const attempt = (this.sshObj.commandTimeoutAttempt || 0) + 1; + const attempt = + (/** @type {number | undefined} */ ( + this.sshObj.commandTimeoutAttempt + ) || 0) + 1; this.sshObj.commandTimeoutAttempt = attempt; const maxRetries = toNonNegativeInteger(this.sshObj.commandTimeoutRetries); const final = attempt > maxRetries; @@ -1991,7 +2003,7 @@ class SSH2Shell extends Stream { this._primaryEnded = false; this._stream = {}; this.connection = null; - this.sshObj = {}; + this.sshObj = /** @type {any} */ ({}); this.host = 'No host'; this.command = ''; this._buffer = ''; @@ -2364,7 +2376,9 @@ class SSH2Shell extends Stream { 'parameters' ); } - const err = new Error('Missing connection parameters'); + const err = /** @type {TaggedError} */ ( + new Error('Missing connection parameters') + ); err.level = 'Parameters'; this._hopFailed(context, err); return this._stream; @@ -2550,7 +2564,9 @@ class SSH2Shell extends Stream { this._appendPartial('connection-close', context.host); if (had_error) { - const err = new Error('Connection closed with error'); + const err = /** @type {TaggedError} */ ( + new Error('Connection closed with error') + ); err.level = 'Connection close'; err.hadError = had_error; this.emit('error', err, 'Connection close', null, null, context); @@ -2672,7 +2688,9 @@ class SSH2Shell extends Stream { try { this.emit('data', data); } catch (e) { - const readError = new Error(`${e} ${e.stack}`); + const readError = /** @type {TaggedError} */ ( + new Error(`${e} ${e.stack}`) + ); readError.level = 'Data handling'; if (context.isPrimary) { this.emit( diff --git a/src/ssh2shell.js b/src/ssh2shell.js index 0b4d277..13023fa 100644 --- a/src/ssh2shell.js +++ b/src/ssh2shell.js @@ -26,6 +26,7 @@ * @typedef {import('../index').EndHandler} EndHandler * @typedef {import('../index').ErrorHandler} ErrorHandler * @typedef {import('../index').KeyboardInteractiveHandler} KeyboardInteractiveHandler + * @typedef {Error & {level?: string, hadError?: boolean}} TaggedError */ const Stream = require('node:stream'); @@ -90,7 +91,7 @@ class SSH2Shell extends Stream { * @param {HostConfig | HostConfig[]} hosts A host config or a non-empty array of them. */ constructor(hosts) { - super(hosts); + super(); // Public entry points keep own bound copies so they can be detached and // passed around. `_connect` and `_connectHop` are passed as bare callbacks @@ -121,7 +122,8 @@ class SSH2Shell extends Stream { this._hosts = list.slice(); this._primaryHostCount = this._hosts.length; this._multipleHosts = this._primaryHostCount > 1; - this.sshObj = {}; + /** @type {HostConfig} */ + 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. this._connections = []; @@ -181,10 +183,14 @@ class SSH2Shell extends Stream { this.dataIdleTime = 500; this.idleTimer = null; this.dataReceivedTimer = null; - this.asciiFilter = ''; - this.textColorFilter = ''; - this.passwordPrompt = ''; - this.standardPrompt = ''; + /** @type {RegExp} */ + this.asciiFilter = /** @type {any} */ (''); + /** @type {RegExp} */ + this.textColorFilter = /** @type {any} */ (''); + /** @type {RegExp} */ + this.passwordPrompt = /** @type {any} */ (''); + /** @type {RegExp} */ + this.standardPrompt = /** @type {any} */ (''); this._loadDefaultListeners(); } @@ -267,7 +273,10 @@ class SSH2Shell extends Stream { this.systemMsg('debug', `Class.error: ${err}, ${type}`); if (err instanceof Error) { - this.emit('msg', `Error: ${err.message}, Level: ${err.level}`); + this.emit( + 'msg', + `Error: ${err.message}, Level: ${/** @type {TaggedError} */ (err).level}` + ); } else { this.emit('msg', `${type} error: ${err}`); } @@ -878,7 +887,10 @@ class SSH2Shell extends Stream { } this._progressEnd(); - const attempt = (this.sshObj.commandTimeoutAttempt || 0) + 1; + const attempt = + (/** @type {number | undefined} */ ( + this.sshObj.commandTimeoutAttempt + ) || 0) + 1; this.sshObj.commandTimeoutAttempt = attempt; const maxRetries = toNonNegativeInteger(this.sshObj.commandTimeoutRetries); const final = attempt > maxRetries; @@ -1991,7 +2003,7 @@ class SSH2Shell extends Stream { this._primaryEnded = false; this._stream = {}; this.connection = null; - this.sshObj = {}; + this.sshObj = /** @type {any} */ ({}); this.host = 'No host'; this.command = ''; this._buffer = ''; @@ -2364,7 +2376,9 @@ class SSH2Shell extends Stream { 'parameters' ); } - const err = new Error('Missing connection parameters'); + const err = /** @type {TaggedError} */ ( + new Error('Missing connection parameters') + ); err.level = 'Parameters'; this._hopFailed(context, err); return this._stream; @@ -2550,7 +2564,9 @@ class SSH2Shell extends Stream { this._appendPartial('connection-close', context.host); if (had_error) { - const err = new Error('Connection closed with error'); + const err = /** @type {TaggedError} */ ( + new Error('Connection closed with error') + ); err.level = 'Connection close'; err.hadError = had_error; this.emit('error', err, 'Connection close', null, null, context); @@ -2672,7 +2688,9 @@ class SSH2Shell extends Stream { try { this.emit('data', data); } catch (e) { - const readError = new Error(`${e} ${e.stack}`); + const readError = /** @type {TaggedError} */ ( + new Error(`${e} ${e.stack}`) + ); readError.level = 'Data handling'; if (context.isPrimary) { this.emit( diff --git a/test/live/bash_script.js b/test/live/bash_script.js index 60b8e9e..3ad55d3 100644 --- a/test/live/bash_script.js +++ b/test/live/bash_script.js @@ -2,9 +2,11 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('bash_script.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, diff --git a/test/live/chaining.js b/test/live/chaining.js index 45a989f..a96c56c 100644 --- a/test/live/chaining.js +++ b/test/live/chaining.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('chaining.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); @@ -9,6 +10,7 @@ const { readPrivateKey } = require('../utils/private_key.js'); // authenticates with the runner's local key. const privateKey = readPrivateKey(); +/** @type {import('../../index').HostConfig} */ const jump = { server: { host: process.env.HOST, @@ -20,6 +22,7 @@ const jump = { commands: ['hostname'] }; +/** @type {import('../../index').HostConfig} */ const bastion = { server: { host: process.env.SERVER2_HOST, @@ -31,6 +34,7 @@ const bastion = { commands: ['hostname'] }; +/** @type {import('../../index').HostConfig} */ const target = { server: { host: process.env.SERVER3_HOST, diff --git a/test/live/command_timeout.js b/test/live/command_timeout.js index 946886a..9d081ea 100644 --- a/test/live/command_timeout.js +++ b/test/live/command_timeout.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('command_timeout.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); @@ -11,6 +12,7 @@ const { readPrivateKey } = require('../utils/private_key.js'); const promptCommand = 'printf "Install nodejs [Y/n]? "; read answer; echo "answer=$answer"'; +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, @@ -22,7 +24,7 @@ const host = { commands: [promptCommand], onCommandTimeout: function (command, response, stream, connection) { if (command === promptCommand - && response.includes('[Y/n]?') + && /** @type {string} */ (response).includes('[Y/n]?') && this.sshObj.answeredNode !== true) { this.sshObj.answeredNode = true; stream.write('y\n'); @@ -41,7 +43,7 @@ const host = { 'Command Timeout', true, () => { - this.sshObj.sessionText += response; + /** @type {any} */ (this.sshObj).sessionText += response; } ); } diff --git a/test/live/fingerprint.js b/test/live/fingerprint.js index b4af3d4..06f9bd2 100644 --- a/test/live/fingerprint.js +++ b/test/live/fingerprint.js @@ -2,9 +2,11 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('fingerprint.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, diff --git a/test/live/host_faults.js b/test/live/host_faults.js index 769e63b..d7d15cb 100644 --- a/test/live/host_faults.js +++ b/test/live/host_faults.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('host_faults.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); @@ -38,8 +39,15 @@ const privateKey = readPrivateKey(); // Labels are kept off the host config so they never reach the verbose config // dump or the credential redaction walk. +/** @type {WeakMap} */ const labels = new WeakMap(); +/** + * @param {string | undefined} host + * @param {number | string | undefined} port + * @param {string | undefined} userName + * @returns {import('../../index').ServerConfig} + */ function nestedServer(host, port, userName) { return { host, @@ -50,6 +58,12 @@ function nestedServer(host, port, userName) { }; } +/** + * @param {string} label + * @param {import('../../index').ServerConfig} server + * @param {import('../../index').HostConfig[]} [hosts] + * @returns {import('../../index').HostConfig} + */ function host(label, server, hosts) { const config = { server, @@ -145,7 +159,8 @@ SSH.on('msg', log); SSH.debug = (process.env.DEBUG === 'true'); SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('error', (err, type) => { - const message = err && err.message ? err.message : String(err); + const error = /** @type {{message?: string} | null | undefined} */ (err); + const message = error && error.message ? error.message : String(err); errors.push(`${type || ''}:${message}`); log(`error-event:${type || ''}:${message}`); }); diff --git a/test/live/host_traversal.js b/test/live/host_traversal.js index 04fa547..8b98363 100644 --- a/test/live/host_traversal.js +++ b/test/live/host_traversal.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('host_traversal.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); @@ -22,6 +23,12 @@ const { readPrivateKey } = require('../utils/private_key.js'); // needed. const privateKey = readPrivateKey(); +/** + * @param {string | undefined} host + * @param {number | string | undefined} port + * @param {string | undefined} userName + * @returns {import('../../index').ServerConfig} + */ function nestedServer(host, port, userName) { return { host, @@ -32,6 +39,11 @@ function nestedServer(host, port, userName) { }; } +/** + * @param {string} label + * @param {import('../../index').ServerConfig} server + * @returns {import('../../index').HostConfig} + */ function host(label, server) { return { server, @@ -187,7 +199,10 @@ SSH.debug = (process.env.DEBUG === 'true'); SSH.verbose = (process.env.VERBOSE === 'true'); SSH.on('error', (err, type) => { - log(`error-event:${type || ''}:${err && err.message ? err.message : err}`); + const error = /** @type {{message?: string} | null | undefined} */ (err); + log( + `error-event:${type || ''}:${error && error.message ? error.message : err}` + ); }); SSH.on('end', (sessionText, host) => { diff --git a/test/live/multiple_primary_hosts.js b/test/live/multiple_primary_hosts.js index 896a526..6e06cb6 100644 --- a/test/live/multiple_primary_hosts.js +++ b/test/live/multiple_primary_hosts.js @@ -2,9 +2,11 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('multiple_primary_hosts.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); +/** @type {import('../../index').HostConfig} */ const host1 = { server: { host: process.env.SERVER1_HOST || process.env.HOST, @@ -16,6 +18,7 @@ const host1 = { commands: ['hostname', 'uptime'] }; +/** @type {import('../../index').HostConfig} */ const host2 = { server: { host: process.env.SERVER2_HOST, diff --git a/test/live/notifications.js b/test/live/notifications.js index 873877f..4537d9c 100644 --- a/test/live/notifications.js +++ b/test/live/notifications.js @@ -2,9 +2,11 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('notifications.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, diff --git a/test/live/private_key.js b/test/live/private_key.js index 6ecc343..47ae75b 100644 --- a/test/live/private_key.js +++ b/test/live/private_key.js @@ -5,6 +5,7 @@ const path = require('node:path'); const { logFile, log } = require('../utils/logging.js'); logFile('private_key.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); // `~` is not expanded by fs.readFileSync(), so resolve it against os.homedir(). @@ -13,6 +14,7 @@ const keyPath = path.resolve( .replace(/^~(?=$|[\\/])/, os.homedir()) ); +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, diff --git a/test/live/prompt_response.js b/test/live/prompt_response.js index b3834c4..a34fef8 100644 --- a/test/live/prompt_response.js +++ b/test/live/prompt_response.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('prompt_response.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); @@ -9,6 +10,7 @@ const { readPrivateKey } = require('../utils/private_key.js'); const promptCommand = 'printf "Install nano [Y/n]? "; read answer; echo "answer=$answer"'; +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, @@ -20,7 +22,7 @@ const host = { commands: [promptCommand], onCommandProcessing: function (command, response, sshObj, stream) { if (command === promptCommand - && response.includes('[Y/n]?') + && /** @type {string} */ (response).includes('[Y/n]?') && sshObj.answeredNano !== true) { sshObj.answeredNano = true; stream.write('y\n'); diff --git a/test/live/simple.js b/test/live/simple.js index b81e5ce..dcaaf4d 100644 --- a/test/live/simple.js +++ b/test/live/simple.js @@ -2,9 +2,11 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('simple.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, diff --git a/test/live/sudo_no_pass.js b/test/live/sudo_no_pass.js index 2ffc89f..5cddd07 100644 --- a/test/live/sudo_no_pass.js +++ b/test/live/sudo_no_pass.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('sudo_no_pass.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); @@ -11,6 +12,7 @@ const { readPrivateKey } = require('../utils/private_key.js'); * would be required, so these commands prove that sudo runs without a prompt * and that the normal prompt is still detected so the next command runs. */ +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.SERVER2_HOST, diff --git a/test/live/sudo_su.js b/test/live/sudo_su.js index 1aa6c97..db8158b 100644 --- a/test/live/sudo_su.js +++ b/test/live/sudo_su.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('sudo_su.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); // `HOST` is server1, which has the `suuser` account used as the `su` target. @@ -9,6 +10,7 @@ const SSH2Shell = require('../utils/module.js'); // to answer the `sudo` prompt. const secondUser = process.env.SECOND_USER || 'suuser'; +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.HOST, @@ -28,7 +30,7 @@ const host = { ], onCommandProcessing: function (command, response, sshObj, stream) { if (command === `su ${secondUser}` - && response.includes('Password:') + && /** @type {string} */ (response).includes('Password:') && sshObj.suPasswordSent !== true) { sshObj.suPasswordSent = true; stream.write(`${sshObj.server.secondUserPassword}\n`); diff --git a/test/live/tunnel.js b/test/live/tunnel.js index 845d9bf..f1d1248 100644 --- a/test/live/tunnel.js +++ b/test/live/tunnel.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('tunnel.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); const { readPrivateKey } = require('../utils/private_key.js'); @@ -9,6 +10,7 @@ const { readPrivateKey } = require('../utils/private_key.js'); // authenticates with the runner's local key. const privateKey = readPrivateKey(); +/** @type {import('../../index').HostConfig} */ const jump = { server: { host: process.env.HOST, @@ -20,6 +22,7 @@ const jump = { commands: ['hostname'] }; +/** @type {import('../../index').HostConfig} */ const target = { server: { host: process.env.SERVER2_HOST, From 307cc048b439a0cc67e573936acadc4dadf32c07 Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Wed, 25 Nov 2026 01:57:08 +1300 Subject: [PATCH 5/6] chore: release 4.2.0 --- CHANGELOG.md | 5 ++++- REFACTORING.md | 23 +++++++++++++++++++++++ package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 30 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4df4bba..12c4743 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. ## [Unreleased] +## [4.2.0] - 2026-11-25 + ### Added - `index.d.ts` now describes the public API, host and server configuration, @@ -199,7 +201,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.1.0...HEAD +[Unreleased]: https://github.com/cmp-202/ssh2shell/compare/v4.2.0...HEAD +[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 [4.0.3]: https://github.com/cmp-202/ssh2shell/compare/v4.0.2...v4.0.3 diff --git a/REFACTORING.md b/REFACTORING.md index 1505185..08a595d 100644 --- a/REFACTORING.md +++ b/REFACTORING.md @@ -1155,6 +1155,29 @@ Pre-release cleanup of the instance and host-config surface. Released in - `npm run test:src` — 166/166. - `npm run test:baseline` — 158 pass, 8 baseline-skipped. +### L7.26 deliverables (editor type documentation) + +Public editor support shipped in `v4.2.0`. Runtime behavior and the JavaScript +API are unchanged; this level adds metadata, documentation, and examples. + +**Docs and declarations** + +- Added a hand-maintained `index.d.ts` covering the constructor, public methods, + host and server configuration, handlers, events, and runtime state. +- Added `types` and the declaration file to the published package files, with + no TypeScript dependency or CI gate. +- Added JSDoc typedef aliases and `// @ts-check` in `src/`; `lib/` remains synced + through the normal build check. +- Added a concise README **Editor support** section and annotated the + README-linked live tests as consumer-facing examples. +- Added an AI-assisted workflow prompt for maintaining declarations and JSDoc. + +#### Verification + +- `tsc` across sources and the annotated live tests — 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/package-lock.json b/package-lock.json index 5123269..4a2349b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ssh2shell", - "version": "4.1.0", + "version": "4.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ssh2shell", - "version": "4.1.0", + "version": "4.2.0", "license": "ISC", "dependencies": { "ssh2": "^1.4.0" diff --git a/package.json b/package.json index 17a7c25..b743b22 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ssh2shell", - "version": "4.1.0", + "version": "4.2.0", "author": "cmp-202", "description": "A wrapper class for ssh2 to run multiple sequential commands in an SSH shell session, handle command responses, and tunnel through to other hosts using nested host objects", "main": "./lib/ssh2shell.js", From 7b8fc086c19ebd6c221559c3d53f2c97f361432d Mon Sep 17 00:00:00 2001 From: cmp-202 Date: Wed, 25 Nov 2026 02:10:05 +1300 Subject: [PATCH 6/6] fix: address 4.2.0 release-candidate review Restore the constructor Stream/EventEmitter options pass-through and correct the editor declarations for hostVerifier key bytes and nullable error callbacks. Annotate the remaining README-linked keyboard-interactive example and record the review fixes. --- CHANGELOG.md | 9 +++++++++ REFACTORING.md | 3 +++ index.d.ts | 11 ++++++----- lib/ssh2shell.js | 4 +++- src/ssh2shell.js | 4 +++- test/live/fingerprint.js | 5 ++++- test/live/keyboard-interactive.js | 2 ++ 7 files changed, 30 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12c4743..4c9d35c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ Releases before `4.0.0` are recorded as git tags and GitHub Releases. same editor support, and the README explains the annotation pattern for consumers. +### Fixed + +- Restored the legacy `Stream`/`EventEmitter` options pass-through from the host + config so emitter options such as `captureRejections` still apply. The release + candidate had dropped it during JSDoc annotation. +- Corrected editor declarations for `hostVerifier` raw key bytes and nullable + error callbacks, and annotated the remaining README-linked + `keyboard-interactive` example. + ### Development - Added an AI-assisted workflow prompt for maintaining public declarations and diff --git a/REFACTORING.md b/REFACTORING.md index 08a595d..b5ab6f1 100644 --- a/REFACTORING.md +++ b/REFACTORING.md @@ -1171,6 +1171,9 @@ API are unchanged; this level adds metadata, documentation, and examples. - Added a concise README **Editor support** section and annotated the README-linked live tests as consumer-facing examples. - Added an AI-assisted workflow prompt for maintaining declarations and JSDoc. +- A release-candidate review restored the constructor's `Stream`/`EventEmitter` + options pass-through and corrected the `hostVerifier` and error-callback + declarations before tagging. #### Verification diff --git a/index.d.ts b/index.d.ts index 8e9394f..df0db20 100644 --- a/index.d.ts +++ b/index.d.ts @@ -95,7 +95,7 @@ declare namespace SSH2Shell { tryKeyboard?: boolean; /** Hash algorithm used to verify the server key, for example `sha256`. */ hostHash?: string; - /** Receives the hashed key when `hostHash` is set; use it to pin hosts. */ + /** Receives a hashed key string when `hostHash` is set, or raw key bytes otherwise; use it to pin hosts. */ hostVerifier?: HostVerifier; /** ssh2 cipher, compression, hmac, kex, and server host key overrides. */ algorithms?: Record; @@ -106,12 +106,13 @@ declare namespace SSH2Shell { /** Callback used to accept or reject a server host key. */ interface HostVerifier { /** - * @param hashedKey The hashed key produced with `hostHash`. + * @param hashedKey Hex digest string when `hostHash` is set; otherwise the + * raw server key bytes supplied by ssh2. * @param verify Call with `false` to reject, `true` to accept. * @returns Returning `false` also rejects the key. */ ( - hashedKey: string, + hashedKey: string | Uint8Array, verify: (permitted: boolean) => void ): boolean | void; } @@ -224,7 +225,7 @@ declare namespace SSH2Shell { error: unknown, type: string, close?: boolean | null, - callback?: ErrorCallback, + callback?: ErrorCallback | null, context?: unknown ) => void; /** Answers a keyboard-interactive authentication challenge. */ @@ -261,7 +262,7 @@ declare namespace SSH2Shell { unknown, string, (boolean | null)?, - ErrorCallback?, + (ErrorCallback | null)?, unknown? ]; 'keyboard-interactive': [ diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index 13023fa..e462b6a 100644 --- a/lib/ssh2shell.js +++ b/lib/ssh2shell.js @@ -91,7 +91,9 @@ class SSH2Shell extends Stream { * @param {HostConfig | HostConfig[]} hosts A host config or a non-empty array of them. */ constructor(hosts) { - super(); + // Preserve the legacy Stream/EventEmitter options pass-through. HostConfig + // can carry emitter options such as `captureRejections`. + super(/** @type {any} */ (hosts)); // Public entry points keep own bound copies so they can be detached and // passed around. `_connect` and `_connectHop` are passed as bare callbacks diff --git a/src/ssh2shell.js b/src/ssh2shell.js index 13023fa..e462b6a 100644 --- a/src/ssh2shell.js +++ b/src/ssh2shell.js @@ -91,7 +91,9 @@ class SSH2Shell extends Stream { * @param {HostConfig | HostConfig[]} hosts A host config or a non-empty array of them. */ constructor(hosts) { - super(); + // Preserve the legacy Stream/EventEmitter options pass-through. HostConfig + // can carry emitter options such as `captureRejections`. + super(/** @type {any} */ (hosts)); // Public entry points keep own bound copies so they can be detached and // passed around. `_connect` and `_connectHop` are passed as bare callbacks diff --git a/test/live/fingerprint.js b/test/live/fingerprint.js index 06f9bd2..b8563f1 100644 --- a/test/live/fingerprint.js +++ b/test/live/fingerprint.js @@ -26,7 +26,10 @@ const host = { return true; } - return hashedKey.toLowerCase() === expectedHash.toLowerCase(); + return ( + /** @type {string} */ (hashedKey).toLowerCase() === + expectedHash.toLowerCase() + ); }, }, commands: ['whoami'] diff --git a/test/live/keyboard-interactive.js b/test/live/keyboard-interactive.js index f9d06da..d240df9 100644 --- a/test/live/keyboard-interactive.js +++ b/test/live/keyboard-interactive.js @@ -2,6 +2,7 @@ const dotenv = require('dotenv').config(); const { logFile, log } = require('../utils/logging.js'); logFile('keyboard-interactive.js'); +/** @type {typeof import('../../index')} */ const SSH2Shell = require('../utils/module.js'); // The keyboard-interactive user has password auth disabled, so the client must @@ -15,6 +16,7 @@ if (!kbdPassword) { process.exit(1); } +/** @type {import('../../index').HostConfig} */ const host = { server: { host: process.env.KBD_HOST || process.env.HOST,