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..4c9d35c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,32 @@ 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, + 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. + +### 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 + JSDoc annotations. + ## [4.1.0] - 2026-11-23 ### Added @@ -184,7 +210,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/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/REFACTORING.md b/REFACTORING.md index 1505185..b5ab6f1 100644 --- a/REFACTORING.md +++ b/REFACTORING.md @@ -1155,6 +1155,32 @@ 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. +- A release-candidate review restored the constructor's `Stream`/`EventEmitter` + options pass-through and corrected the `hostVerifier` and error-callback + declarations before tagging. + +#### 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/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 new file mode 100644 index 0000000..df0db20 --- /dev/null +++ b/index.d.ts @@ -0,0 +1,405 @@ +// 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 { + /** + * 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 + ); + + /** 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. Default: 5000. */ + idleTime: number; + /** 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( + 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 { + /** + * 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 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; + /** 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 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 | Uint8Array, + 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; + on(event: string, listener: (...args: any[]) => void): this; + [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, + destinationIP: string, + destinationPort: number, + callback: (error: Error | null, stream?: ShellStream) => void + ): void; + on(event: string, listener: (...args: any[]) => void): this; + [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; + /** + * 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, + response: string | Uint8Array, + host: HostConfig, + stream: ShellStream + ) => void; + /** Runs when a command returns to the prompt. */ + type CommandCompleteHandler = ( + this: SSH2Shell, + command: string, + response: string | Uint8Array, + host: HostConfig, + details: CommandCompleteDetails + ) => void; + /** Runs when no prompt is detected before `idleTimeOut`. */ + type CommandTimeoutHandler = ( + this: SSH2Shell, + command: string, + response: string | Uint8Array, + stream: ShellStream, + 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, + type: string, + close?: boolean | null, + callback?: ErrorCallback | null, + context?: unknown + ) => void; + /** Answers a keyboard-interactive authentication challenge. */ + type KeyboardInteractiveHandler = ( + this: SSH2Shell, + name: string, + instructions: string, + instructionsLanguage: string, + prompts: KeyboardInteractivePrompt[], + finish: KeyboardInteractiveFinish + ) => void; + + /** Instance event names mapped to their listener argument tuples. */ + 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 | null)?, + unknown? + ]; + 'keyboard-interactive': [ + string, + string, + string, + KeyboardInteractivePrompt[], + KeyboardInteractiveFinish + ]; + } + + /** 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; + } +} + +export = SSH2Shell; diff --git a/lib/ssh2shell.js b/lib/ssh2shell.js index 23accba..e462b6a 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 @@ -8,6 +9,26 @@ // 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 + * @typedef {Error & {level?: string, hadError?: boolean}} TaggedError + */ + const Stream = require('node:stream'); const { applyHostDefaults } = require('./ssh2shell/defaults'); @@ -66,8 +87,13 @@ 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); + // 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 @@ -98,7 +124,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 = []; @@ -158,10 +185,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(); } @@ -244,7 +275,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}`); } @@ -353,6 +387,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 +834,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) || @@ -845,7 +889,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; @@ -1665,6 +1712,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 +1935,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; @@ -1950,7 +2005,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 = ''; @@ -2271,6 +2326,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. @@ -2319,7 +2378,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; @@ -2505,7 +2566,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); @@ -2627,7 +2690,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/lib/ssh2shell/defaults.js b/lib/ssh2shell/defaults.js index 3b54087..8b8a034 100644 --- a/lib/ssh2shell/defaults.js +++ b/lib/ssh2shell/defaults.js @@ -1,7 +1,16 @@ +// @ts-check '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..1d1af84 100644 --- a/lib/ssh2shell/util.js +++ b/lib/ssh2shell/util.js @@ -1,5 +1,12 @@ +// @ts-check '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 +25,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 +44,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 +66,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 +90,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 +117,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 +134,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 +150,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/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 0033569..b743b22 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,13 @@ { "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", + "types": "./index.d.ts", "files": [ "lib", + "index.d.ts", "CHANGELOG.md" ], "engines": { diff --git a/src/ssh2shell.js b/src/ssh2shell.js index 23accba..e462b6a 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 @@ -8,6 +9,26 @@ // 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 + * @typedef {Error & {level?: string, hadError?: boolean}} TaggedError + */ + const Stream = require('node:stream'); const { applyHostDefaults } = require('./ssh2shell/defaults'); @@ -66,8 +87,13 @@ 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); + // 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 @@ -98,7 +124,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 = []; @@ -158,10 +185,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(); } @@ -244,7 +275,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}`); } @@ -353,6 +387,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 +834,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) || @@ -845,7 +889,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; @@ -1665,6 +1712,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 +1935,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; @@ -1950,7 +2005,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 = ''; @@ -2271,6 +2326,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. @@ -2319,7 +2378,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; @@ -2505,7 +2566,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); @@ -2627,7 +2690,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/defaults.js b/src/ssh2shell/defaults.js index 3b54087..8b8a034 100644 --- a/src/ssh2shell/defaults.js +++ b/src/ssh2shell/defaults.js @@ -1,7 +1,16 @@ +// @ts-check '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..1d1af84 100644 --- a/src/ssh2shell/util.js +++ b/src/ssh2shell/util.js @@ -1,5 +1,12 @@ +// @ts-check '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 +25,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 +44,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 +66,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 +90,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 +117,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 +134,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 +150,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/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..b8563f1 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, @@ -24,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/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/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, 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,