UNPKG

82.4 kBTypeScriptView Raw
1/// <reference types="node" />
2
3import { EventEmitter } from "events";
4import { Agent as BaseHTTPAgent, AgentOptions as BaseHTTPAgentOptions } from "http";
5import { Agent as BaseHTTPSAgent, AgentOptions as BaseHTTPSAgentOptions } from "https";
6import { Server as NetServer, Socket } from "net";
7import { Duplex, Readable, ReadableOptions, Writable, WritableOptions } from "stream";
8
9export interface Prompt {
10 prompt: string;
11 echo?: boolean;
12}
13
14/**
15 * Possible Key Exchange Algorithms
16 */
17export type KexAlgorithm =
18 | "curve25519-sha256"
19 | "curve25519-sha256@libssh.org"
20 | "ecdh-sha2-nistp256"
21 | "ecdh-sha2-nistp384"
22 | "ecdh-sha2-nistp521"
23 | "diffie-hellman-group-exchange-sha256"
24 | "diffie-hellman-group14-sha256"
25 | "diffie-hellman-group15-sha512"
26 | "diffie-hellman-group16-sha512"
27 | "diffie-hellman-group17-sha512"
28 | "diffie-hellman-group18-sha512"
29 | "diffie-hellman-group-exchange-sha1"
30 | "diffie-hellman-group14-sha1"
31 | "diffie-hellman-group1-sha1";
32
33export type ServerHostKeyAlgorithm =
34 | "ssh-ed25519"
35 | "ecdsa-sha2-nistp256"
36 | "ecdsa-sha2-nistp384"
37 | "ecdsa-sha2-nistp521"
38 | "rsa-sha2-512"
39 | "rsa-sha2-256"
40 | "ssh-rsa"
41 | "ssh-dss";
42
43export type CompressionAlgorithm = "none" | "zlib" | "zlib@openssh.com";
44
45export type CipherAlgorithm =
46 | "chacha20-poly1305@openssh.com"
47 | "aes128-gcm"
48 | "aes128-gcm@openssh.com"
49 | "aes256-gcm"
50 | "aes256-gcm@openssh.com"
51 | "aes128-ctr"
52 | "aes192-ctr"
53 | "aes256-ctr"
54 | "aes256-cbc"
55 | "aes192-cbc"
56 | "aes128-cbc"
57 | "blowfish-cbc"
58 | "3des-cbc"
59 | "arcfour256"
60 | "arcfour128"
61 | "cast128-cbc"
62 | "arcfour";
63
64export type MacAlgorithm =
65 | "hmac-sha2-256-etm@openssh.com"
66 | "hmac-sha2-512-etm@openssh.com"
67 | "hmac-sha1-etm@openssh.com"
68 | "hmac-sha2-256"
69 | "hmac-sha2-512"
70 | "hmac-sha1"
71 | "hmac-md5"
72 | "hmac-sha2-256-96"
73 | "hmac-sha2-512-96"
74 | "hmac-ripemd160"
75 | "hmac-sha1-96"
76 | "hmac-md5-96";
77
78/**
79 * Lists of supported algorithms can either be an ordered array of all supported algorithms,
80 * OR a map of algorithms to manipulate the default list
81 */
82export type AlgorithmList<T> = T[] | Record<"append" | "prepend" | "remove", T | T[]>;
83
84/**
85 * Overrides for the default transport layer algorithms used for the connection.
86 *
87 * The order of the algorithms in the arrays are important, with the most favorable being first.
88 */
89export interface Algorithms {
90 kex?: AlgorithmList<KexAlgorithm>;
91 cipher?: AlgorithmList<CipherAlgorithm>;
92 serverHostKey?: AlgorithmList<ServerHostKeyAlgorithm>;
93 hmac?: AlgorithmList<MacAlgorithm>;
94 compress?: AlgorithmList<CompressionAlgorithm>;
95}
96
97export type KeyType =
98 | "ssh-rsa"
99 | "ssh-dss"
100 | "ssh-ed25519"
101 | "ecdsa-sha2-nistp256"
102 | "ecdsa-sha2-nistp384"
103 | "ecdsa-sha2-nistp521";
104
105export interface ParsedKey {
106 type: KeyType;
107 comment: string;
108 sign(data: Buffer | string, algo?: string): Buffer;
109 verify(data: Buffer | string, signature: Buffer, algo?: string): boolean;
110 isPrivateKey(): boolean;
111 getPrivatePEM(): string;
112 getPublicPEM(): string;
113 getPublicSSH(): Buffer;
114 equals(key: Buffer | string | ParsedKey): boolean;
115}
116
117export interface Versions {
118 /**
119 * The SSH protocol version supported by the remote party.
120 */
121 protocol: string;
122
123 /**
124 * The software name and version used by the remote party.
125 */
126 software: string;
127}
128
129export interface Header {
130 /**
131 * The raw identification string sent by the remote party.
132 */
133 identRaw: string;
134
135 /**
136 * Contains various version information parsed from identRaw.
137 */
138 versions: Versions;
139
140 /**
141 * Any text that comes after the software name/version.
142 */
143 comments: string;
144
145 /**
146 * Any greeting sent by the server
147 */
148 greeting?: string;
149}
150
151export type OpenMode = "r" | "r+" | "w" | "wx" | "xw" | "w+" | "xw+" | "a" | "ax" | "xa" | "a+" | "ax+" | "xa+";
152
153export namespace utils {
154 interface KeySettings {
155 rsa: {
156 bits: number;
157 };
158 ecdsa: {
159 bits: 256 | 384 | 521;
160 };
161 ed25519: {};
162 }
163
164 type KeyPairOptions =
165 & {
166 comment?: string;
167 /**
168 * As of now, ssh2 only supports the "new" format;
169 * Specifying this won't have any effect,
170 * as it's already the default behavior.
171 */
172 format?: "new";
173 }
174 & ({
175 passphrase: string | Buffer;
176 cipher: string;
177 rounds: number;
178 } | {});
179
180 type KeyType = keyof KeySettings;
181
182 /** All optional key types where their settings are optional */
183 type OptionalKeyType = {
184 [K in keyof KeySettings]: {} extends KeySettings[K] ? K : never;
185 }[keyof KeySettings];
186
187 interface KeyPairReturn {
188 private: string;
189 public: string;
190 }
191
192 function parseKey(data: Buffer | string | ParsedKey, passphrase?: Buffer | string): ParsedKey | Error;
193
194 function generateKeyPair<K extends KeyType>(
195 keyType: K,
196 opts: KeySettings[K] & KeyPairOptions,
197 cb?: (err: Error | null, keyPair: KeyPairReturn) => void,
198 ): void;
199 function generateKeyPair<K extends OptionalKeyType>(
200 keyType: K,
201 opts?: KeySettings[K] & KeyPairOptions,
202 cb?: (err: Error | null, keyPair: KeyPairReturn) => void,
203 ): void;
204 function generateKeyPair(keyType: KeyType, cb: (err: Error | null, keyPair: KeyPairReturn) => void): void;
205
206 function generateKeyPairSync<K extends KeyType>(keyType: K, opts: KeySettings[K] & KeyPairOptions): KeyPairReturn;
207 function generateKeyPairSync<K extends OptionalKeyType>(
208 keyType: K,
209 opts?: KeySettings[K] & KeyPairOptions,
210 ): KeyPairReturn;
211 namespace sftp {
212 enum OPEN_MODE {
213 READ = 0x00000001,
214 WRITE = 0x00000002,
215 APPEND = 0x00000004,
216 CREAT = 0x00000008,
217 TRUNC = 0x00000010,
218 EXCL = 0x00000020,
219 }
220
221 enum STATUS_CODE {
222 OK = 0,
223 EOF = 1,
224 NO_SUCH_FILE = 2,
225 PERMISSION_DENIED = 3,
226 FAILURE = 4,
227 BAD_MESSAGE = 5,
228 NO_CONNECTION = 6,
229 CONNECTION_LOST = 7,
230 OP_UNSUPPORTED = 8,
231 }
232
233 function stringToFlags(str: OpenMode): number | null;
234 function flagsToString(flags: number): OpenMode | null;
235 }
236}
237
238export type ChannelType = "session" | "sftp" | "direct-tcpip" | "direct-streamlocal@openssh.com";
239
240export type ChannelSubType = "exec" | "shell";
241
242export interface Channel extends Duplex {
243 /** Standard input for the Channel. */
244 stdin: this;
245 /** Standard output for the Channel. */
246 stdout: this;
247 /** Standard error for the Channel. */
248 stderr: Writable | Readable;
249 /** Indicates whether this is a server or client channel. */
250 server: boolean;
251 /** The channel type, usually "session". */
252 type: ChannelType;
253 /** The channel subtype, usually "exec", "shell", or undefined. */
254 subtype?: ChannelSubType;
255 incoming: unknown;
256 outgoing: unknown;
257
258 /**
259 * Sends EOF to the remote side.
260 */
261 eof(): void;
262
263 /**
264 * Closes the channel on both sides.
265 */
266 close(...args: any[]): void;
267
268 /**
269 * Shuts down the channel on this side.
270 */
271 destroy(): this;
272
273 /**
274 * Session type-specific methods
275 */
276 setWindow(rows: number, cols: number, height: number, width: number): void;
277 signal(signalName: string): void;
278 exit(status: number): void;
279 exit(signalName: string, coreDumped?: boolean, msg?: string): void;
280
281 /**
282 * Emitted once the channel is completely closed on both the client and the server.
283 */
284 on(event: "close", listener: () => void): this;
285 on(event: "eof", listener: () => void): this;
286 on(event: "end", listener: () => void): this;
287 on(event: string | symbol, listener: Function): this;
288 once(event: "close", listener: () => void): this;
289 once(event: "eof", listener: () => void): this;
290 once(event: "end", listener: () => void): this;
291 once(event: string | symbol, listener: Function): this;
292}
293
294export interface ClientChannel extends Channel {
295 /** Standard error for the Channel. */
296 stderr: Readable;
297 /** Indicates whether this is a server or client channel. */
298 server: false;
299
300 /**
301 * An `exit` event *may* (the SSH2 spec says it is optional) be emitted when the process
302 * finishes. If the process finished normally, the process's return value is passed to
303 * the `exit` callback.
304 */
305 on(event: "exit", listener: (code: number) => void): this;
306 on(event: "exit", listener: (code: null, signal: string, dump: string, desc: string) => void): this;
307 on(event: string | symbol, listener: Function): this;
308 once(event: "exit", listener: (code: number) => void): this;
309 once(event: "exit", listener: (code: null, signal: string, dump: string, desc: string) => void): this;
310 once(event: string | symbol, listener: Function): this;
311}
312
313export interface ServerChannel extends Channel {
314 /** Standard error for the Channel. */
315 stderr: Writable;
316 /** Indicates whether this is a server or client channel. */
317 server: true;
318}
319
320export type AcceptConnection<T extends Channel = Channel> = () => T;
321export type AcceptSftpConnection = () => SFTPWrapper;
322export type RejectConnection = () => void;
323
324export class Client extends EventEmitter {
325 // Client-events
326
327 /**
328 * Emitted when a notice was sent by the server upon connection.
329 */
330 on(event: "banner", listener: (message: string) => void): this;
331
332 /**
333 * Emitted when authentication was successful.
334 */
335 on(event: "ready", listener: () => void): this;
336
337 /**
338 * Emitted when an incoming forwarded TCP connection is being requested.
339 *
340 * Calling `accept()` accepts the connection and returns a `Channel` object.
341 * Calling `reject()` rejects the connection and no further action is needed.
342 */
343 on(
344 event: "tcp connection",
345 listener: (
346 details: TcpConnectionDetails,
347 accept: AcceptConnection<ClientChannel>,
348 reject: RejectConnection,
349 ) => void,
350 ): this;
351
352 /**
353 * Emitted when an incoming X11 connection is being requested.
354 *
355 * Calling `accept()` accepts the connection and returns a `Channel` object.
356 * Calling `reject()` rejects the connection and no further action is needed.
357 */
358 on(
359 event: "x11",
360 listener: (details: X11Details, accept: AcceptConnection<ClientChannel>, reject: RejectConnection) => void,
361 ): this;
362
363 /**
364 * Emitted when the server is asking for replies to the given `prompts` for keyboard-
365 * interactive user authentication.
366 *
367 * * `name` is generally what you'd use as a window title (for GUI apps).
368 * * `prompts` is an array of `Prompt` objects.
369 *
370 * The answers for all prompts must be provided as an array of strings and passed to
371 * `finish` when you are ready to continue.
372 *
373 * NOTE: It's possible for the server to come back and ask more questions.
374 */
375 on(
376 event: "keyboard-interactive",
377 listener: (
378 name: string,
379 instructions: string,
380 lang: string,
381 prompts: Prompt[],
382 finish: KeyboardInteractiveCallback,
383 ) => void,
384 ): this;
385
386 /**
387 * Emitted when the server has requested that the user's password be changed, if using
388 * password-based user authentication.
389 *
390 * Call `done` with the new password.
391 */
392 on(event: "change password", listener: (message: string, done: ChangePasswordCallback) => void): this;
393
394 /**
395 * Emitted when an error occurred.
396 */
397 on(event: "error", listener: (err: Error & ClientErrorExtensions) => void): this;
398
399 /**
400 * Emitted when the socket was disconnected.
401 */
402 on(event: "end", listener: () => void): this;
403
404 /**
405 * Emitted when the socket was closed.
406 */
407 on(event: "close", listener: () => void): this;
408
409 /**
410 * Emitted when the socket has timed out.
411 */
412 on(event: "timeout", listener: () => void): this;
413
414 /**
415 * Emitted when the socket has connected.
416 */
417 on(event: "connect", listener: () => void): this;
418
419 /**
420 * Emitted when the server responds with a greeting message.
421 */
422 on(event: "greeting", listener: (greeting: string) => void): this;
423
424 /**
425 * Emitted when a handshake has completed (either initial or rekey).
426 */
427 on(event: "handshake", listener: (negotiated: NegotiatedAlgorithms) => void): this;
428
429 /**
430 * Emitted when the server announces its available host keys.
431 */
432 on(event: "hostkeys", listener: (keys: ParsedKey[]) => void): this;
433
434 /**
435 * An incoming forwarded UNIX socket connection is being requested.
436 */
437 on(
438 event: "unix connection",
439 listener: (info: UNIXConnectionDetails, accept: AcceptConnection, reject: RejectConnection) => void,
440 ): this;
441
442 /**
443 * Emitted when a notice was sent by the server upon connection.
444 */
445 once(event: "banner", listener: (message: string) => void): this;
446
447 /**
448 * Emitted when authentication was successful.
449 */
450 once(event: "ready", listener: () => void): this;
451
452 /**
453 * Emitted when an incoming forwarded TCP connection is being requested.
454 *
455 * Calling `accept()` accepts the connection and returns a `Channel` object.
456 * Calling `reject()` rejects the connection and no further action is needed.
457 */
458 once(
459 event: "tcp connection",
460 listener: (
461 details: TcpConnectionDetails,
462 accept: AcceptConnection<ClientChannel>,
463 reject: RejectConnection,
464 ) => void,
465 ): this;
466
467 /**
468 * Emitted when an incoming X11 connection is being requested.
469 *
470 * Calling `accept()` accepts the connection and returns a `Channel` object.
471 * Calling `reject()` rejects the connection and no further action is needed.
472 */
473 once(
474 event: "x11",
475 listener: (details: X11Details, accept: AcceptConnection<ClientChannel>, reject: RejectConnection) => void,
476 ): this;
477
478 /**
479 * Emitted when the server is asking for replies to the given `prompts` for keyboard-
480 * interactive user authentication.
481 *
482 * * `name` is generally what you'd use as a window title (for GUI apps).
483 * * `prompts` is an array of `Prompt` objects.
484 *
485 * The answers for all prompts must be provided as an array of strings and passed to
486 * `finish` when you are ready to continue.
487 *
488 * NOTE: It's possible for the server to come back and ask more questions.
489 */
490 once(
491 event: "keyboard-interactive",
492 listener: (
493 name: string,
494 instructions: string,
495 lang: string,
496 prompts: Prompt[],
497 finish: KeyboardInteractiveCallback,
498 ) => void,
499 ): this;
500
501 /**
502 * Emitted when the server has requested that the user's password be changed, if using
503 * password-based user authentication.
504 *
505 * Call `done` with the new password.
506 */
507 once(event: "change password", listener: (message: string, done: ChangePasswordCallback) => void): this;
508
509 /**
510 * Emitted when an error occurred.
511 */
512 once(event: "error", listener: (err: Error & ClientErrorExtensions) => void): this;
513
514 /**
515 * Emitted when the socket was disconnected.
516 */
517 once(event: "end", listener: () => void): this;
518
519 /**
520 * Emitted when the socket was closed.
521 */
522 once(event: "close", listener: () => void): this;
523
524 /**
525 * Emitted when the socket has timed out.
526 */
527 once(event: "timeout", listener: () => void): this;
528
529 /**
530 * Emitted when the socket has connected.
531 */
532 once(event: "connect", listener: () => void): this;
533
534 /**
535 * Emitted when the server responds with a greeting message.
536 */
537 once(event: "greeting", listener: (greeting: string) => void): this;
538
539 /**
540 * Emitted when a handshake has completed (either initial or rekey).
541 */
542 once(event: "handshake", listener: (negotiated: NegotiatedAlgorithms) => void): this;
543
544 /**
545 * Emitted when the server announces its available host keys.
546 */
547 once(event: "hostkeys", listener: (keys: ParsedKey[]) => void): this;
548
549 /**
550 * An incoming forwarded UNIX socket connection is being requested.
551 */
552 once(
553 event: "unix connection",
554 listener: (info: UNIXConnectionDetails, accept: AcceptConnection, reject: RejectConnection) => void,
555 ): this;
556
557 /**
558 * Attempts a connection to a server.
559 */
560 connect(config: ConnectConfig): this;
561
562 /**
563 * Executes a command on the server.
564 *
565 * @param command The command to execute.
566 * @param options Options for the command.
567 * @param callback The callback to execute when the command has completed.
568 */
569 exec(command: string, options: ExecOptions, callback: ClientCallback): this;
570
571 /**
572 * Executes a command on the server.
573 *
574 * @param command The command to execute.
575 * @param callback The callback to execute when the command has completed.
576 */
577 exec(command: string, callback: ClientCallback): this;
578
579 /**
580 * Starts an interactive shell session on the server.
581 *
582 * @param window Either an object containing pseudo-tty settings, `false` to suppress creation of a pseudo-tty.
583 * @param options Options for the command.
584 * @param callback The callback to execute when the channel has been created.
585 */
586 shell(window: PseudoTtyOptions | false, options: ShellOptions, callback: ClientCallback): this;
587
588 /**
589 * Starts an interactive shell session on the server.
590 *
591 * @param window Either an object containing pseudo-tty settings, `false` to suppress creation of a pseudo-tty.
592 * @param callback The callback to execute when the channel has been created.
593 */
594 shell(window: PseudoTtyOptions | false, callback: ClientCallback): this;
595
596 /**
597 * Starts an interactive shell session on the server.
598 *
599 * @param options Options for the command.
600 * @param callback The callback to execute when the channel has been created.
601 */
602 shell(options: ShellOptions, callback: ClientCallback): this;
603
604 /**
605 * Starts an interactive shell session on the server.
606 *
607 * @param callback The callback to execute when the channel has been created.
608 */
609 shell(callback: ClientCallback): this;
610
611 /**
612 * Bind to `remoteAddr` on `remotePort` on the server and forward incoming TCP connections.
613 *
614 * @param remoteAddr The remote address to bind on the server. The following lists several special values for `remoteAddr` and their respective bindings:
615 *
616 * | address | description
617 * |:--------------|:-----------
618 * | `''` | Listen on all protocol families supported by the server
619 * | `'0.0.0.0'` | Listen on all IPv4 addresses
620 * | `'::'` | Listen on all IPv6 addresses
621 * | `'localhost'` | Listen on the loopback interface for all protocol families
622 * | `'127.0.0.1'` | Listen on the loopback interfaces for IPv4
623 * | `'::1'` | Listen on the loopback interfaces for IPv6
624 *
625 * @param remotePort The remote port to bind on the server. If this value is `0`, the actual bound port is provided to `callback`.
626 * @param [callback] An optional callback that is invoked when the remote address is bound.
627 */
628 forwardIn(remoteAddr: string, remotePort: number, callback?: ClientForwardCallback): this;
629
630 /**
631 * Unbind from `remoteAddr` on `remotePort` on the server and stop forwarding incoming TCP
632 * connections. Until `callback` is called, more connections may still come in.
633 *
634 * @param remoteAddr The remote address to unbind on the server.
635 * @param remotePort The remote port to unbind on the server.
636 * @param [callback] An optional callback that is invoked when the remote address is unbound.
637 */
638 unforwardIn(remoteAddr: string, remotePort: number, callback?: Callback): this;
639
640 /**
641 * Open a connection with `srcIP` and `srcPort` as the originating address and port and
642 * `dstIP` and `dstPort` as the remote destination address and port.
643 *
644 * @param srcIP The originating address.
645 * @param srcPort The originating port.
646 * @param dstIP The destination address.
647 * @param dstPort The destination port.
648 * @param [callback] The callback that is invoked when the address is bound.
649 */
650 forwardOut(srcIP: string, srcPort: number, dstIP: string, dstPort: number, callback?: ClientCallback): this;
651
652 /**
653 * Starts an SFTP session.
654 *
655 * @param callback The callback that is invoked when the SFTP session has started.
656 */
657 sftp(callback: ClientSFTPCallback): this;
658
659 /**
660 * Invokes `subsystem` on the server.
661 *
662 * @param subsystem The subsystem to start on the server.
663 * @param callback The callback that is invoked when the subsystem has started.
664 */
665 subsys(subsystem: string, callback: ClientCallback): this;
666
667 /**
668 * Disconnects the socket.
669 */
670 end(): this;
671
672 /**
673 * Destroys the socket.
674 */
675 destroy(): this;
676
677 /**
678 * OpenSSH extension that sends a request to reject any new sessions (e.g. exec, shell,
679 * sftp, subsys) for this connection.
680 */
681 openssh_noMoreSessions(cb: Callback): this;
682
683 /**
684 * OpenSSH extension that binds to a UNIX domain socket at `socketPath` on the server and
685 * forwards incoming connections.
686 */
687 openssh_forwardInStreamLocal(socketPath: string, cb: Callback): this;
688
689 /**
690 * OpenSSH extension that unbinds from a UNIX domain socket at `socketPath` on the server
691 * and stops forwarding incoming connections.
692 */
693 openssh_unforwardInStreamLocal(socketPath: string, cb: Callback): this;
694
695 /**
696 * OpenSSH extension that opens a connection to a UNIX domain socket at `socketPath` on
697 * the server.
698 */
699 openssh_forwardOutStreamLocal(socketPath: string, cb: ClientCallback): this;
700}
701
702export type HostVerifier = (key: Buffer, verify: VerifyCallback) => void;
703export type SyncHostVerifier = (key: Buffer) => boolean;
704export type HostFingerprintVerifier = (fingerprint: string, verify: VerifyCallback) => boolean;
705export type SyncHostFingerprintVerifier = (fingerprint: string) => boolean;
706export type DebugFunction = (message: string) => void;
707export type AuthenticationType = "password" | "publickey" | "hostbased" | "agent" | "keyboard-interactive" | "none";
708
709export interface ConnectConfig {
710 /** Hostname or IP address of the server. */
711 host?: string;
712 /** Port number of the server. */
713 port?: number;
714 /** Only connect via resolved IPv4 address for `host`. */
715 forceIPv4?: boolean;
716 /** Only connect via resolved IPv6 address for `host`. */
717 forceIPv6?: boolean;
718 /** The host's key is hashed using this method and passed to `hostVerifier`. */
719 hostHash?: string;
720 /** Verifies a hexadecimal hash of the host's key. */
721 hostVerifier?: HostVerifier | SyncHostVerifier | HostFingerprintVerifier | SyncHostFingerprintVerifier;
722 /** Username for authentication. */
723 username?: string;
724 /** Password for password-based user authentication. */
725 password?: string;
726 /** Path to ssh-agent's UNIX socket for ssh-agent-based user authentication (or 'pageant' when using Pagent on Windows). */
727 agent?: BaseAgent | string;
728 /** Buffer or string that contains a private key for either key-based or hostbased user authentication (OpenSSH format). */
729 privateKey?: Buffer | string;
730 /** For an encrypted private key, this is the passphrase used to decrypt it. */
731 passphrase?: Buffer | string;
732 /** Along with `localUsername` and `privateKey`, set this to a non-empty string for hostbased user authentication. */
733 localHostname?: string;
734 /** Along with `localHostname` and `privateKey`, set this to a non-empty string for hostbased user authentication. */
735 localUsername?: string;
736 /** Try keyboard-interactive user authentication if primary user authentication method fails. */
737 tryKeyboard?: boolean;
738 /** How often (in milliseconds) to send SSH-level keepalive packets to the server. Set to 0 to disable. */
739 keepaliveInterval?: number;
740 /** How many consecutive, unanswered SSH-level keepalive packets that can be sent to the server before disconnection. */
741 keepaliveCountMax?: number;
742 /** * How long (in milliseconds) to wait for the SSH handshake to complete. */
743 readyTimeout?: number;
744 /** Performs a strict server vendor check before sending vendor-specific requests. */
745 strictVendor?: boolean;
746 /** A `ReadableStream` to use for communicating with the server instead of creating and using a new TCP connection (useful for connection hopping). */
747 sock?: Readable;
748 /** Set to `true` to use OpenSSH agent forwarding (`auth-agent@openssh.com`) for the life of the connection. */
749 agentForward?: boolean;
750 /** Explicit overrides for the default transport layer algorithms used for the connection. */
751 algorithms?: Algorithms;
752 /** A function that receives a single string argument to get detailed (local) debug information. */
753 debug?: DebugFunction;
754 /** Function with parameters (methodsLeft, partialSuccess, callback) where methodsLeft and partialSuccess are null on the first authentication attempt, otherwise are an array and boolean respectively. Return or call callback() with the name of the authentication method to try next (pass false to signal no more methods to try). Valid method names are: 'none', 'password', 'publickey', 'agent', 'keyboard-interactive', 'hostbased'. Default: function that follows a set method order: None -> Password -> Private Key -> Agent (-> keyboard-interactive if tryKeyboard is true) -> Hostbased. */
755 authHandler?: AuthenticationType[] | AuthHandlerMiddleware | AuthMethod[];
756 /** IP address of the network interface to use to connect to the server. Default: (none -- determined by OS) */
757 localAddress?: string;
758 /** The local port number to connect from. Default: (none -- determined by OS) */
759 localPort?: number;
760 /** The underlying socket timeout in ms. Default: none) */
761 timeout?: number;
762 /** A custom server software name/version identifier. Default: 'ssh2js' + moduleVersion + 'srv' */
763 ident?: Buffer | string;
764}
765
766export interface AuthMethod {
767 type: AuthenticationType;
768 username: string;
769}
770
771/**
772 * Strategy returned from the {@link ConnectConfig.authHandler} to connect without authentication.
773 */
774export interface NoAuthMethod extends AuthMethod {
775 type: "none";
776}
777
778/**
779 * Strategy returned from the {@link ConnectConfig.authHandler} to connect with a password.
780 */
781export interface PasswordAuthMethod extends AuthMethod {
782 type: "password";
783 password: string;
784}
785
786/**
787 * Strategy returned from the {@link ConnectConfig.authHandler} to connect with a public key.
788 */
789export interface PublicKeyAuthMethod extends AuthMethod {
790 type: "publickey";
791 key: ParsedKey | Buffer | string;
792 passphrase?: Buffer | string;
793}
794
795/**
796 * Strategy returned from the {@link ConnectConfig.authHandler} to connect with host-based authentication.
797 */
798export interface HostBasedAuthMethod extends AuthMethod {
799 type: "hostbased";
800 localHostname: string;
801 localUsername: string;
802 /**
803 * Can be a string, Buffer, or parsed key containing a private key
804 */
805 key: ParsedKey | Buffer | string;
806 /**
807 * `passphrase` only required for encrypted keys
808 */
809 passphrase?: Buffer | string;
810}
811
812/**
813 * Strategy returned from the {@link ConnectConfig.authHandler} to connect with an agent.
814 */
815export interface AgentAuthMethod extends AuthMethod {
816 type: "agent";
817 /**
818 * Can be a string that is interpreted exactly like the `agent` connection config
819 * option or can be a custom agent object/instance that extends and implements `BaseAgent`
820 */
821 agent: BaseAgent | string;
822}
823
824/**
825 * Strategy returned from the {@link ConnectConfig.authHandler} to connect with an agent.
826 */
827export interface KeyboardInteractiveAuthMethod extends AuthMethod {
828 type: "keyboard-interactive";
829 /**
830 * This works exactly the same way as a 'keyboard-interactive' client event handler
831 */
832 prompt(
833 name: string,
834 instructions: string,
835 lang: string,
836 prompts: Prompt[],
837 finish: KeyboardInteractiveCallback,
838 ): void;
839}
840
841export type AnyAuthMethod =
842 | NoAuthMethod
843 | PasswordAuthMethod
844 | HostBasedAuthMethod
845 | PublicKeyAuthMethod
846 | AgentAuthMethod
847 | KeyboardInteractiveAuthMethod;
848
849export type NextAuthHandler = (authName: AuthenticationType | AnyAuthMethod) => void;
850
851export type AuthHandlerMiddleware = (
852 authsLeft: AuthenticationType[],
853 partialSuccess: boolean,
854 next: NextAuthHandler,
855) => void;
856
857export interface TcpConnectionDetails {
858 /** The originating IP of the connection. */
859 srcIP: string;
860 /** The originating port of the connection. */
861 srcPort: number;
862 /** The remote IP the connection was received on (given in earlier call to `forwardIn()`). */
863 destIP: string;
864 /** The remote port the connection was received on (given in earlier call to `forwardIn()`). */
865 destPort: number;
866}
867
868export interface X11Details {
869 /** The originating IP of the connection. */
870 srcIP: string;
871 /** The originating port of the connection. */
872 srcPort: number;
873}
874
875export interface ClientErrorExtensions {
876 /** Indicates 'client-socket' for socket-level errors and 'client-ssh' for SSH disconnection messages. */
877 level?: string;
878 /** Additional detail for 'client-ssh' messages. */
879 description?: string;
880}
881
882export interface ExecOptions {
883 /** An environment to use for the execution of the command. */
884 env?: NodeJS.ProcessEnv;
885 /** Set to `true` to allocate a pseudo-tty with defaults, or an object containing specific pseudo-tty settings. */
886 pty?: PseudoTtyOptions | boolean;
887 /** Set either to `true` to use defaults, a number to specify a specific screen number, or an object containing x11 settings. */
888 x11?: X11Options | number | boolean;
889 allowHalfOpen?: boolean;
890}
891
892export interface ShellOptions {
893 /** An environment to use for the execution of the shell. */
894 env?: NodeJS.ProcessEnv;
895 /** Set either to `true` to use defaults, a number to specify a specific screen number, or an object containing x11 settings. */
896 x11?: X11Options | number | boolean;
897}
898
899export interface X11Options {
900 /** Whether to allow just a single connection (default: `false`).*/
901 single?: boolean;
902 /** The Screen number to use (default: `0`). */
903 screen?: number;
904 /** The authentication protocol name. Default: 'MIT-MAGIC-COOKIE-1' */
905 protocol?: string;
906 /** The authentication cookie. Can be a hex string or a Buffer containing the raw cookie value (which will be converted to a hex string). Default: (random 16 byte value) */
907 cookie?: Buffer | string;
908}
909
910export interface PseudoTtyOptions {
911 /** The number of rows (default: `24`). */
912 rows?: number;
913 /** The number of columns (default: `80`). */
914 cols?: number;
915 /** The height in pixels (default: `480`). */
916 height?: number;
917 /** The width in pixels (default: `640`). */
918 width?: number;
919 /** The value to use for $TERM (default: `'vt100'`) */
920 term?: string;
921 /** An object containing Terminal Modes as keys, with each value set to each mode argument. Default: null */
922 modes?: TerminalModes;
923}
924
925export type ServerConnectionListener = (client: Connection, info: ClientInfo) => void;
926
927export class Server extends NetServer {
928 static KEEPALIVE_CLIENT_INTERVAL: number;
929 static KEEPALIVE_CLIENT_COUNT_MAX: number;
930 constructor(cfg: ServerConfig, listener?: ServerConnectionListener);
931 injectSocket(socket: Socket): void;
932 on(event: "connection", listener: ServerConnectionListener): this;
933 on(event: string | symbol, listener: Function): this;
934 once(event: "connection", listener: ServerConnectionListener): this;
935 once(event: string | symbol, listener: Function): this;
936}
937
938export interface ServerConfig {
939 /** An array of host private keys. */
940 hostKeys: PrivateKeys;
941 /** Explicit overrides for the default transport layer algorithms used for the connection. */
942 algorithms?: Algorithms;
943 /** A message that is sent to clients immediately upon connection, before handshaking begins. */
944 greeting?: string;
945 /** A message that is sent to clients once, right before authentication begins. */
946 banner?: string;
947 /** A custom server software name/version identifier. */
948 ident?: string;
949 /** This is the highWaterMark to use for the parser stream (default: `32 * 1024`). */
950 highWaterMark?: number; // in docs but not in code
951 /** The keep alive interval for this server */
952 keepaliveInterval?: number;
953 /** The most allowed failed keep alive attempts before closing a connection */
954 keepaliveCountMax?: number;
955 /** A function that receives a single string argument to get detailed (local) debug information. */
956 debug?: DebugFunction;
957}
958
959export interface EncryptedPrivateKey {
960 /** A Buffer or string that contains a private key. */
961 key: ParsedKey | Buffer | string;
962 /** The passphrase to decrypt a private key. */
963 passphrase?: Buffer | string;
964}
965
966export interface ClientInfo {
967 /** The remote address of the connection. */
968 ip: string;
969 /** Information about the client. */
970 header: Header;
971 family: string;
972 port: number;
973}
974
975export interface Connection extends EventEmitter {
976 // Connection events
977
978 /**
979 * Emitted when the client has requested authentication.
980 */
981 on(event: "authentication", listener: (context: AuthContext) => void): this;
982
983 /**
984 * Emitted when the client has been successfully authenticated.
985 */
986 on(event: "ready", listener: () => void): this;
987
988 /**
989 * Emitted when the client has requested a new session.
990 * Sessions are used to start interactive shells, execute commands, request X11 forwarding, etc.
991 */
992 on(event: "session", listener: (accept: AcceptConnection<Session>, reject: RejectConnection) => void): this;
993
994 /**
995 * Emitted when the client has requested an outbound (TCP) connection.
996 */
997 on(
998 event: "tcpip",
999 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: TcpipRequestInfo) => void,
1000 ): this;
1001
1002 /**
1003 * Emitted when the client has requested a connection to a UNIX domain socket.
1004 */
1005 on(
1006 event: "openssh.streamlocal",
1007 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: SocketRequestInfo) => void,
1008 ): this;
1009
1010 /**
1011 * Emitted when the client has sent a global request for name.
1012 * If info.bindPort === 0, you should pass the chosen port to accept so that the client will know what port was bound.
1013 */
1014 on(
1015 event: "request",
1016 listener: (
1017 accept: ((chosenPort?: number) => void) | undefined,
1018 reject: (() => void) | undefined,
1019 name: "tcpip-forward" | "cancel-tcpip-forward",
1020 info: TcpipBindInfo,
1021 ) => void,
1022 ): this;
1023
1024 /**
1025 * Emitted when the client has sent a global request for name.
1026 */
1027 on(
1028 event: "request",
1029 listener: (
1030 accept: (() => void) | undefined,
1031 reject: () => void,
1032 name: "streamlocal-forward@openssh.com" | "cancel-streamlocal-forward@openssh.com",
1033 info: SocketBindInfo,
1034 ) => void,
1035 ): this;
1036
1037 /**
1038 * Emitted when the client has finished rekeying (either client or server initiated).
1039 */
1040 on(event: "rekey", listener: () => void): this;
1041
1042 /**
1043 * Emitted when an error occurrs.
1044 */
1045 on(event: "error", listener: ErrorCallback): this;
1046
1047 /**
1048 * Emitted when the socket has disconnected.
1049 */
1050 on(event: "end", listener: () => void): this;
1051
1052 /**
1053 * Emitted when the client socket was closed.
1054 */
1055 on(event: "close", listener: () => void): this;
1056
1057 /**
1058 * Emitted when the Alogrithms have been negotiated; emitted every time there is a rekey
1059 */
1060 on(event: "handshake", listener: (negotiated: NegotiatedAlgorithms) => void): this;
1061
1062 /**
1063 * Emitted if the server sends a greeting header
1064 */
1065 on(event: "greeting", listener: (greeting: string) => void): this;
1066
1067 /**
1068 * Emitted when the client has requested authentication.
1069 */
1070 once(event: "authentication", listener: (context: AuthContext) => void): this;
1071
1072 /**
1073 * Emitted when the client has been successfully authenticated.
1074 */
1075 once(event: "ready", listener: () => void): this;
1076
1077 /**
1078 * Emitted when the client has requested a new session.
1079 * Sessions are used to start interactive shells, execute commands, request X11 forwarding, etc.
1080 */
1081 once(event: "session", listener: (accept: AcceptConnection<Session>, reject: RejectConnection) => void): this;
1082
1083 /**
1084 * Emitted when the client has requested an outbound (TCP) connection.
1085 */
1086 once(
1087 event: "tcpip",
1088 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: TcpipRequestInfo) => void,
1089 ): this;
1090
1091 /**
1092 * Emitted when the client has requested a connection to a UNIX domain socket.
1093 */
1094 once(
1095 event: "openssh.streamlocal",
1096 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: SocketRequestInfo) => void,
1097 ): this;
1098
1099 /**
1100 * Emitted when the client has sent a global request for name.
1101 * If info.bindPort === 0, you should pass the chosen port to accept so that the client will know what port was bound.
1102 */
1103 once(
1104 event: "request",
1105 listener: (
1106 accept: ((chosenPort?: number) => void) | undefined,
1107 reject: (() => void) | undefined,
1108 name: "tcpip-forward" | "cancel-tcpip-forward",
1109 info: TcpipBindInfo,
1110 ) => void,
1111 ): this;
1112
1113 /**
1114 * Emitted when the client has sent a global request for name.
1115 */
1116 once(
1117 event: "request",
1118 listener: (
1119 accept: (() => void) | undefined,
1120 reject: () => void,
1121 name: "streamlocal-forward@openssh.com" | "cancel-streamlocal-forward@openssh.com",
1122 info: SocketBindInfo,
1123 ) => void,
1124 ): this;
1125
1126 /**
1127 * Emitted when the client has finished rekeying (either client or server initiated).
1128 */
1129 once(event: "rekey", listener: () => void): this;
1130
1131 /**
1132 * Emitted when an error occurrs.
1133 */
1134 once(event: "error", listener: ErrorCallback): this;
1135
1136 /**
1137 * Emitted when the socket has disconnected.
1138 */
1139 once(event: "end", listener: () => void): this;
1140
1141 /**
1142 * Emitted when the client socket was closed.
1143 */
1144 once(event: "close", listener: () => void): this;
1145
1146 /**
1147 * Emitted when the Alogrithms have been negotiated; emitted every time there is a rekey
1148 */
1149 once(event: "handshake", listener: (negotiated: NegotiatedAlgorithms) => void): this;
1150
1151 /**
1152 * Emitted if the server sends a greeting header
1153 */
1154 once(event: "greeting", listener: (greeting: string) => void): this;
1155
1156 noMoreSessions: boolean;
1157 authenticated: boolean;
1158
1159 // Connection methods
1160
1161 /**
1162 * Closes the client connection.
1163 */
1164 end(): this;
1165
1166 /**
1167 * Alert the client of an incoming X11 client connection from `originAddr` on port `originPort`.
1168 */
1169 x11(originAddr: string, originPort: number, channel: ServerCallback): this;
1170
1171 /**
1172 * Alert the client of an incoming TCP connection on `boundAddr` on port `boundPort` from
1173 * `remoteAddr` on port `remotePort`.
1174 */
1175 forwardOut(
1176 boundAddr: string,
1177 boundPort: number,
1178 remoteAddr: string,
1179 remotePort: number,
1180 callback: ServerCallback,
1181 ): this;
1182
1183 /**
1184 * Initiates a rekeying with the client.
1185 *
1186 * Returns `false` if you should wait for the `continue` event before sending any more traffic.
1187 *
1188 * @param callback An optional callback added as a one-time handler for the `rekey` event.
1189 */
1190 rekey(callback?: () => void): void;
1191
1192 /**
1193 * Alert the client of an incoming UNIX domain socket connection on socketPath.
1194 *
1195 * Returns `false` if you should wait for the `continue` event before sending any more traffic.
1196 */
1197 openssh_forwardOutStreamLocal(socketPath: string, callback: ServerCallback): this;
1198}
1199
1200export interface AuthContextBase extends EventEmitter {
1201 /** The client's username. */
1202 username: string;
1203 /** The service requesting authentication. */
1204 service: string;
1205 /** The method of authentication. */
1206 method: AuthenticationType;
1207
1208 /**
1209 * Accepts the authentication request.
1210 */
1211 accept(): void;
1212
1213 /**
1214 * Rejects the authentication request.
1215 */
1216 reject(authMethodsLeft?: AuthenticationType[], isPartialSuccess?: boolean): void;
1217
1218 /**
1219 * Emitted when the client aborts the authentication request.
1220 */
1221 on(event: "abort", listener: () => void): this;
1222
1223 /**
1224 * Emitted when the client aborts the authentication request.
1225 */
1226 once(event: "abort", listener: () => void): this;
1227}
1228
1229export interface KeyboardAuthContext extends AuthContextBase {
1230 /** The method of authentication. */
1231 method: "keyboard-interactive";
1232
1233 /** A list of preferred authentication "sub-methods" sent by the client. */
1234 submethods: string[];
1235
1236 /**
1237 * Send prompts to the client.
1238 * @param prompts The prompts to send to the client.
1239 * @param callback A callback to call with the responses from the client.
1240 */
1241 prompt(prompts: string | Prompt | Array<string | Prompt>, callback: KeyboardInteractiveCallback): void;
1242
1243 /**
1244 * Send prompts to the client.
1245 * @param prompts The prompts to send to the client.
1246 * @param title The title for the prompt.
1247 * @param callback A callback to call with the responses from the client.
1248 */
1249 prompt(
1250 prompts: string | Prompt | Array<string | Prompt>,
1251 title: string,
1252 callback: KeyboardInteractiveCallback,
1253 ): void;
1254
1255 /**
1256 * Send prompts to the client.
1257 * @param prompts The prompts to send to the client.
1258 * @param title The title for the prompt.
1259 * @param instructions Instructions for the client.
1260 * @param callback A callback to call with the responses from the client.
1261 */
1262 prompt(
1263 prompts: string | Prompt | Array<string | Prompt>,
1264 title: string,
1265 instructions: string,
1266 callback: KeyboardInteractiveCallback,
1267 ): void;
1268}
1269
1270export interface PublicKeyAuthContext extends AuthContextBase {
1271 /** The method of authentication. */
1272 method: "publickey";
1273 /** The public key sent by the client. */
1274 key: PublicKey;
1275 /** The signature to verify, or `undefined` if the client is only checking the validity of the key. */
1276 signature?: Buffer;
1277 /** The data used to verify the key, or `undefined` if the client is only checking the validity of the key. */
1278 blob?: Buffer;
1279 /** The explicit hash algorithm to be used during verification (passed to key.verify()). */
1280 hashAlgo?: string;
1281}
1282
1283export interface PublicKey {
1284 /** The name of the key algorithm. */
1285 algo: string;
1286 /** The actual key data. */
1287 data: Buffer;
1288}
1289
1290export interface HostbasedAuthContext extends AuthContextBase {
1291 /** The method of authentication. */
1292 method: "hostbased";
1293 /** The public key sent by the client. */
1294 key: PublicKey;
1295 /** The signature to verify, or `undefined` if the client is only checking the validity of the key. */
1296 signature: Buffer;
1297 /** The data used to verify the key, or `undefined` if the client is only checking the validity of the key. */
1298 blob: Buffer;
1299 /** The local hostname of the client. */
1300 localHostname: string;
1301 /** The local username of the client. */
1302 localUsername: string;
1303}
1304
1305export interface PasswordAuthContext extends AuthContextBase {
1306 /** The method of authentication. */
1307 method: "password";
1308 /** The password sent by the client. */
1309 password: string;
1310 requestChange(prompt: string, cb: ChangePasswordCallback): void;
1311}
1312
1313export interface NoneAuthContext extends AuthContextBase {
1314 /** The method of authentication. */
1315 method: "none";
1316}
1317
1318export type AuthContext =
1319 | KeyboardAuthContext
1320 | PublicKeyAuthContext
1321 | HostbasedAuthContext
1322 | PasswordAuthContext
1323 | NoneAuthContext;
1324
1325export interface TcpipRequestInfo {
1326 /** Source IP address of outgoing connection. */
1327 srcIP: string;
1328 /** Source port of outgoing connection. */
1329 srcPort: number;
1330 /** Destination IP address of outgoing connection. */
1331 destIP: string;
1332 /** Destination port of outgoing connection. */
1333 destPort: number;
1334}
1335
1336export interface SocketRequestInfo {
1337 /** Destination socket path of outgoing connection. */
1338 socketPath: string;
1339}
1340
1341export interface TcpipBindInfo {
1342 /** The IP address to start/stop binding to. */
1343 bindAddr: string;
1344 /** The port to start/stop binding to. */
1345 bindPort: number;
1346}
1347
1348export interface SocketBindInfo {
1349 /** The socket path to start/stop binding to. */
1350 socketPath: string;
1351}
1352
1353// keep so anyone importing this doesn't see breaking changes
1354export type SessionAcceptReject = () => void;
1355export type SessionAccept = () => void;
1356
1357// NB: Doesn't actually extend ServerChannel/Channel/Duplex, it is just an EventEmitter
1358export interface Session extends ServerChannel {
1359 // Session events
1360
1361 /**
1362 * Emitted when the client requested allocation of a pseudo-TTY for this session.
1363 */
1364 on(event: "pty", listener: (accept: SessionAccept, reject: RejectConnection, info: PseudoTtyInfo) => void): this;
1365
1366 /**
1367 * Emitted when the client reported a change in window dimensions during this session.
1368 */
1369 on(
1370 event: "window-change",
1371 listener: (accept: SessionAccept, reject: RejectConnection, info: WindowChangeInfo) => void,
1372 ): this;
1373
1374 /**
1375 * Emitted when the client requested X11 forwarding.
1376 */
1377 on(event: "x11", listener: (accept: SessionAccept, reject: RejectConnection, info: X11Info) => void): this;
1378
1379 /**
1380 * Emitted when the client requested an environment variable to be set for this session.
1381 */
1382 on(event: "env", listener: (accept: SessionAccept, reject: RejectConnection, info: SetEnvInfo) => void): this;
1383
1384 /**
1385 * Emitted when the client has sent a POSIX signal.
1386 */
1387 on(event: "signal", listener: (accept: SessionAccept, reject: RejectConnection, info: SignalInfo) => void): this;
1388
1389 /**
1390 * Emitted when the client has requested incoming ssh-agent requests be forwarded to them.
1391 */
1392 on(event: "auth-agent", listener: (accept: SessionAccept, reject: RejectConnection) => void): this;
1393
1394 /**
1395 * Emitted when the client has requested an interactive shell.
1396 */
1397 on(event: "shell", listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection) => void): this;
1398
1399 /**
1400 * Emitted when the client has requested execution of a command string.
1401 */
1402 on(
1403 event: "exec",
1404 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: ExecInfo) => void,
1405 ): this;
1406
1407 /**
1408 * Emitted when the client has requested the SFTP subsystem.
1409 */
1410 on(event: "sftp", listener: (accept: AcceptSftpConnection, reject: RejectConnection) => void): this;
1411
1412 /**
1413 * Emitted when the client has requested an arbitrary subsystem.
1414 */
1415 on(
1416 event: "subsystem",
1417 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: SubsystemInfo) => void,
1418 ): this;
1419
1420 on(event: string | symbol, listener: Function): this;
1421
1422 /**
1423 * Emitted when the client requested allocation of a pseudo-TTY for this session.
1424 */
1425 once(event: "pty", listener: (accept: SessionAccept, reject: RejectConnection, info: PseudoTtyInfo) => void): this;
1426
1427 /**
1428 * Emitted when the client reported a change in window dimensions during this session.
1429 */
1430 once(
1431 event: "window-change",
1432 listener: (accept: SessionAccept, reject: RejectConnection, info: WindowChangeInfo) => void,
1433 ): this;
1434
1435 /**
1436 * Emitted when the client requested X11 forwarding.
1437 */
1438 once(event: "x11", listener: (accept: SessionAccept, reject: RejectConnection, info: X11Info) => void): this;
1439
1440 /**
1441 * Emitted when the client requested an environment variable to be set for this session.
1442 */
1443 once(event: "env", listener: (accept: SessionAccept, reject: RejectConnection, info: SetEnvInfo) => void): this;
1444
1445 /**
1446 * Emitted when the client has sent a POSIX signal.
1447 */
1448 once(event: "signal", listener: (accept: SessionAccept, reject: RejectConnection, info: SignalInfo) => void): this;
1449
1450 /**
1451 * Emitted when the client has requested incoming ssh-agent requests be forwarded to them.
1452 */
1453 once(event: "auth-agent", listener: (accept: SessionAccept, reject: RejectConnection) => void): this;
1454
1455 /**
1456 * Emitted when the client has requested an interactive shell.
1457 */
1458 once(event: "shell", listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection) => void): this;
1459
1460 /**
1461 * Emitted when the client has requested execution of a command string.
1462 */
1463 once(
1464 event: "exec",
1465 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: ExecInfo) => void,
1466 ): this;
1467
1468 /**
1469 * Emitted when the client has requested the SFTP subsystem.
1470 */
1471 once(event: "sftp", listener: (accept: AcceptSftpConnection, reject: RejectConnection) => void): this;
1472
1473 /**
1474 * Emitted when the client has requested an arbitrary subsystem.
1475 */
1476 once(
1477 event: "subsystem",
1478 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: SubsystemInfo) => void,
1479 ): this;
1480
1481 once(event: string | symbol, listener: Function): this;
1482}
1483
1484export interface PseudoTtyInfo {
1485 /** The number of columns for the pseudo-TTY. */
1486 cols: number;
1487 /** The number of rows for the pseudo-TTY. */
1488 rows: number;
1489 /** The width of the pseudo-TTY in pixels. */
1490 width: number;
1491 /** The height of the pseudo-TTY in pixels. */
1492 height: number;
1493 /** Contains the requested terminal modes of the pseudo-TTY. */
1494 modes: TerminalModes;
1495}
1496
1497export interface TerminalModes {
1498 /** Interrupt character; `255` if none. Not all of these characters are supported on all systems. */
1499 VINTR?: number | undefined;
1500 /** The quit character (sends `SIGQUIT` signal on POSIX systems). */
1501 VQUIT?: number | undefined;
1502 /** Erase the character to left of the cursor. */
1503 VERASE?: number | undefined;
1504 /** Kill the current input line. */
1505 VKILL?: number | undefined;
1506 /** End-of-file character (sends `EOF` from the terminal). */
1507 VEOF?: number | undefined;
1508 /** End-of-line character in addition to carriage return and/or linefeed. */
1509 VEOL?: number | undefined;
1510 /** Additional end-of-line character. */
1511 VEOL2?: number | undefined;
1512 /** Continues paused output (normally control-Q). */
1513 VSTART?: number | undefined;
1514 /** Pauses output (normally control-S). */
1515 VSTOP?: number | undefined;
1516 /** Suspends the current program. */
1517 VSUSP?: number | undefined;
1518 /** Another suspend character. */
1519 VDSUSP?: number | undefined;
1520 /** Reprints the current input line. */
1521 VREPRINT?: number | undefined;
1522 /** Erases a word left of cursor. */
1523 VWERASE?: number | undefined;
1524 /** Enter the next character typed literally, even if it is a special character */
1525 VLNEXT?: number | undefined;
1526 /** Character to flush output. */
1527 VFLUSH?: number | undefined;
1528 /** Switch to a different shell layer. */
1529 VSWTCH?: number | undefined;
1530 /** Prints system status line (load, command, pid, etc). */
1531 VSTATUS?: number | undefined;
1532 /** Toggles the flushing of terminal output. */
1533 VDISCARD?: number | undefined;
1534 /** The ignore parity flag. The parameter SHOULD be `0` if this flag is FALSE, and `1` if it is TRUE. */
1535 IGNPAR?: 0 | 1 | undefined;
1536 /** Mark parity and framing errors. */
1537 PARMRK?: 0 | 1 | undefined;
1538 /** Enable checking of parity errors. */
1539 INPCK?: 0 | 1 | undefined;
1540 /** Strip 8th bit off characters. */
1541 ISTRIP?: 0 | 1 | undefined;
1542 /** Map NL into CR on input. */
1543 INLCR?: 0 | 1 | undefined;
1544 /** Ignore CR on input. */
1545 IGNCR?: 0 | 1 | undefined;
1546 /** Map CR to NL on input. */
1547 ICRNL?: 0 | 1 | undefined;
1548 /** Translate uppercase characters to lowercase. */
1549 IUCLC?: 0 | 1 | undefined;
1550 /** Enable output flow control. */
1551 IXON?: 0 | 1 | undefined;
1552 /** Any char will restart after stop. */
1553 IXANY?: 0 | 1 | undefined;
1554 /** Enable input flow control. */
1555 IXOFF?: 0 | 1 | undefined;
1556 /** Ring bell on input queue full. */
1557 IMAXBEL?: 0 | 1 | undefined;
1558 /** Enable signals INTR, QUIT, [D]SUSP. */
1559 ISIG?: 0 | 1 | undefined;
1560 /** Canonicalize input lines. */
1561 ICANON?: 0 | 1 | undefined;
1562 /** Enable input and output of uppercase characters by preceding their lowercase equivalents with `\`. */
1563 XCASE?: 0 | 1 | undefined;
1564 /** Enable echoing. */
1565 ECHO?: 0 | 1 | undefined;
1566 /** Visually erase chars. */
1567 ECHOE?: 0 | 1 | undefined;
1568 /** Kill character discards current line. */
1569 ECHOK?: 0 | 1 | undefined;
1570 /** Echo NL even if ECHO is off. */
1571 ECHONL?: 0 | 1 | undefined;
1572 /** Don't flush after interrupt. */
1573 NOFLSH?: 0 | 1 | undefined;
1574 /** Stop background jobs from output. */
1575 TOSTOP?: 0 | 1 | undefined;
1576 /** Enable extensions. */
1577 IEXTEN?: 0 | 1 | undefined;
1578 /** Echo control characters as ^(Char). */
1579 ECHOCTL?: 0 | 1 | undefined;
1580 /** Visual erase for line kill. */
1581 ECHOKE?: 0 | 1 | undefined;
1582 /** Retype pending input. */
1583 PENDIN?: 0 | 1 | undefined;
1584 /** Enable output processing. */
1585 OPOST?: 0 | 1 | undefined;
1586 /** Convert lowercase to uppercase. */
1587 OLCUC?: 0 | 1 | undefined;
1588 /** Map NL to CR-NL. */
1589 ONLCR?: 0 | 1 | undefined;
1590 /** Translate carriage return to newline (output). */
1591 OCRNL?: 0 | 1 | undefined;
1592 /** Translate newline to carriage return-newline (output). */
1593 ONOCR?: 0 | 1 | undefined;
1594 /** Newline performs a carriage return (output). */
1595 ONLRET?: 0 | 1 | undefined;
1596 /** 7 bit mode. */
1597 CS7?: 0 | 1 | undefined;
1598 /** 8 bit mode. */
1599 CS8?: 0 | 1 | undefined;
1600 /** Parity enable. */
1601 PARENB?: 0 | 1 | undefined;
1602 /** Odd parity, else even. */
1603 PARODD?: 0 | 1 | undefined;
1604 /** Specifies the input baud rate in bits per second. */
1605 TTY_OP_ISPEED?: number | undefined;
1606 /** Specifies the output baud rate in bits per second. */
1607 TTY_OP_OSPEED?: number | undefined;
1608}
1609
1610export interface WindowChangeInfo {
1611 /** The number of columns for the pseudo-TTY. */
1612 cols: number;
1613 /** The number of rows for the pseudo-TTY. */
1614 rows: number;
1615 /** The width of the pseudo-TTY in pixels. */
1616 width: number;
1617 /** The height of the pseudo-TTY in pixels. */
1618 height: number;
1619}
1620
1621export interface X11Info {
1622 /** true if only a single connection should be forwarded. */
1623 single: boolean;
1624 /** The name of the X11 authentication method used. */
1625 protocol: string;
1626 /** The X11 authentication cookie encoded in hexadecimal. */
1627 cookie: string;
1628 /** The screen number for which to forward X11 connections. */
1629 screen: number;
1630}
1631
1632export interface SetEnvInfo {
1633 /** The environment variable's name. */
1634 key: string;
1635 /** The environment variable's value. */
1636 val: string;
1637}
1638
1639export interface SignalInfo {
1640 /** The signal name (e.g. SIGUSR1). */
1641 name: string;
1642}
1643
1644export interface ExecInfo {
1645 /** The command line to be executed. */
1646 command: string;
1647}
1648
1649export interface SubsystemInfo {
1650 /** The name of the subsystem. */
1651 name: string;
1652}
1653
1654export interface TransferOptions {
1655 concurrency?: number;
1656 chunkSize?: number;
1657 fileSize?: number;
1658 step?: (total: number, nb: number, fsize: number) => void;
1659 mode?: number | string;
1660}
1661
1662export interface ReadFileOptions {
1663 encoding?: BufferEncoding;
1664 flag?: string;
1665}
1666
1667export interface WriteFileOptions {
1668 encoding?: BufferEncoding;
1669 mode?: number;
1670 flag?: string;
1671}
1672
1673export interface InputAttributes {
1674 mode?: number | string;
1675 uid?: number;
1676 gid?: number;
1677 size?: number;
1678 atime?: number | Date;
1679 mtime?: number | Date;
1680}
1681
1682export interface Attributes {
1683 mode: number;
1684 uid: number;
1685 gid: number;
1686 size: number;
1687 atime: number;
1688 mtime: number;
1689}
1690
1691export interface Stats extends Attributes {
1692 isDirectory(): boolean;
1693 isFile(): boolean;
1694 isBlockDevice(): boolean;
1695 isCharacterDevice(): boolean;
1696 isSymbolicLink(): boolean;
1697 isFIFO(): boolean;
1698 isSocket(): boolean;
1699}
1700
1701export interface FileEntry {
1702 filename: string;
1703 longname: string;
1704 attrs: Attributes;
1705}
1706
1707export interface FileEntryWithStats extends Omit<FileEntry, "attrs"> {
1708 attrs: Stats;
1709}
1710
1711export interface SFTPWrapper extends EventEmitter {
1712 /**
1713 * (Client-only)
1714 * Downloads a file at `remotePath` to `localPath` using parallel reads for faster throughput.
1715 */
1716 fastGet(remotePath: string, localPath: string, options: TransferOptions, callback: Callback): void;
1717
1718 /**
1719 * (Client-only)
1720 * Downloads a file at `remotePath` to `localPath` using parallel reads for faster throughput.
1721 */
1722 fastGet(remotePath: string, localPath: string, callback: Callback): void;
1723
1724 /**
1725 * (Client-only)
1726 * Uploads a file from `localPath` to `remotePath` using parallel reads for faster throughput.
1727 */
1728 fastPut(localPath: string, remotePath: string, options: TransferOptions, callback: Callback): void;
1729
1730 /**
1731 * (Client-only)
1732 * Uploads a file from `localPath` to `remotePath` using parallel reads for faster throughput.
1733 */
1734 fastPut(localPath: string, remotePath: string, callback: Callback): void;
1735
1736 /**
1737 * (Client-only)
1738 * Reads a file in memory and returns its contents
1739 */
1740 readFile(
1741 remotePath: string,
1742 options: ReadFileOptions,
1743 callback: (err: Error | undefined, handle: Buffer) => void,
1744 ): void;
1745
1746 /**
1747 * (Client-only)
1748 * Reads a file in memory and returns its contents
1749 */
1750 readFile(
1751 remotePath: string,
1752 encoding: BufferEncoding,
1753 callback: (err: Error | undefined, handle: Buffer) => void,
1754 ): void;
1755
1756 /**
1757 * (Client-only)
1758 * Reads a file in memory and returns its contents
1759 */
1760 readFile(remotePath: string, callback: (err: Error | undefined, handle: Buffer) => void): void;
1761
1762 /**
1763 * (Client-only)
1764 * Returns a new readable stream for `path`.
1765 */
1766 createReadStream(path: string, options?: ReadStreamOptions): ReadStream;
1767
1768 /**
1769 * (Client-only)
1770 * Writes data to a file
1771 */
1772 writeFile(remotePath: string, data: string | Buffer, options: WriteFileOptions, callback?: Callback): void;
1773
1774 /**
1775 * (Client-only)
1776 * Writes data to a file
1777 */
1778 writeFile(remotePath: string, data: string | Buffer, encoding: string, callback?: Callback): void;
1779
1780 /**
1781 * (Client-only)
1782 * Writes data to a file
1783 */
1784 writeFile(remotePath: string, data: string | Buffer, callback?: Callback): void;
1785
1786 /**
1787 * (Client-only)
1788 * Appends data to a file
1789 */
1790 appendFile(remotePath: string, data: string | Buffer, options: WriteFileOptions, callback?: Callback): void;
1791
1792 /**
1793 * (Client-only)
1794 * Appends data to a file
1795 */
1796 appendFile(remotePath: string, data: string | Buffer, callback?: Callback): void;
1797
1798 /**
1799 * (Client-only)
1800 * Returns a new writable stream for `path`.
1801 */
1802 createWriteStream(path: string, options?: WriteStreamOptions): WriteStream;
1803
1804 /**
1805 * (Client-only)
1806 * Opens a file `filename` for `mode` with optional `attributes`.
1807 */
1808 open(
1809 filename: string,
1810 mode: number | OpenMode,
1811 attributes: InputAttributes,
1812 callback: (err: Error | undefined, handle: Buffer) => void,
1813 ): void;
1814 open(
1815 filename: string,
1816 mode: number | OpenMode,
1817 attributes: string | number,
1818 callback: (err: Error | undefined, handle: Buffer) => void,
1819 ): void;
1820
1821 /**
1822 * (Client-only)
1823 * Opens a file `filename` for `mode`.
1824 */
1825 open(filename: string, mode: number | OpenMode, callback: (err: Error | undefined, handle: Buffer) => void): void;
1826
1827 /**
1828 * (Client-only)
1829 * Closes the resource associated with `handle` given by `open()` or `opendir()`.
1830 */
1831 close(handle: Buffer, callback: Callback): void;
1832
1833 /**
1834 * (Client-only)
1835 * Reads `length` bytes from the resource associated with `handle` starting at `position`
1836 * and stores the bytes in `buffer` starting at `offset`.
1837 */
1838 read(
1839 handle: Buffer,
1840 buffer: Buffer,
1841 offset: number,
1842 length: number,
1843 position: number,
1844 callback: (err: Error | undefined, bytesRead: number, buffer: Buffer, position: number) => void,
1845 ): void;
1846
1847 /**
1848 * (Client-only)
1849 */
1850 write(handle: Buffer, buffer: Buffer, offset: number, length: number, position: number, callback: Callback): void;
1851
1852 /**
1853 * (Client-only)
1854 * Retrieves attributes for the resource associated with `handle`.
1855 */
1856 fstat(handle: Buffer, callback: (err: Error | undefined, stats: Stats) => void): void;
1857
1858 /**
1859 * (Client-only)
1860 * Sets the attributes defined in `attributes` for the resource associated with `handle`.
1861 */
1862 fsetstat(handle: Buffer, attributes: InputAttributes, callback: Callback): void;
1863
1864 /**
1865 * (Client-only)
1866 * Sets the access time and modified time for the resource associated with `handle`.
1867 */
1868 futimes(handle: Buffer, atime: number | Date, mtime: number | Date, callback: Callback): void;
1869
1870 /**
1871 * (Client-only)
1872 * Sets the owner for the resource associated with `handle`.
1873 */
1874 fchown(handle: Buffer, uid: number, gid: number, callback: Callback): void;
1875
1876 /**
1877 * (Client-only)
1878 * Sets the mode for the resource associated with `handle`.
1879 */
1880 fchmod(handle: Buffer, mode: number | string, callback: Callback): void;
1881
1882 /**
1883 * (Client-only)
1884 * Opens a directory `path`.
1885 */
1886 opendir(path: string, callback: (err: Error | undefined, handle: Buffer) => void): void;
1887
1888 /**
1889 * (Client-only)
1890 * Retrieves a directory listing.
1891 */
1892 readdir(location: string | Buffer, callback: (err: Error | undefined, list: FileEntryWithStats[]) => void): void;
1893
1894 /**
1895 * (Client-only)
1896 * Removes the file/symlink at `path`.
1897 */
1898 unlink(path: string, callback: Callback): void;
1899
1900 /**
1901 * (Client-only)
1902 * Renames/moves `srcPath` to `destPath`.
1903 */
1904 rename(srcPath: string, destPath: string, callback: Callback): void;
1905
1906 /**
1907 * (Client-only)
1908 * Creates a new directory `path`.
1909 */
1910 mkdir(path: string, attributes: InputAttributes, callback: Callback): void;
1911
1912 /**
1913 * (Client-only)
1914 * Creates a new directory `path`.
1915 */
1916 mkdir(path: string, callback: Callback): void;
1917
1918 /**
1919 * (Client-only)
1920 * Removes the directory at `path`.
1921 */
1922 rmdir(path: string, callback: Callback): void;
1923
1924 /**
1925 * (Client-only)
1926 * Retrieves attributes for `path`.
1927 */
1928 stat(path: string, callback: (err: Error | undefined, stats: Stats) => void): void;
1929
1930 /**
1931 * (Client-only)
1932 * `path` exists.
1933 */
1934 exists(path: string, callback: (hasError: boolean) => void): void;
1935
1936 /**
1937 * (Client-only)
1938 * Retrieves attributes for `path`. If `path` is a symlink, the link itself is stat'ed
1939 * instead of the resource it refers to.
1940 */
1941 lstat(path: string, callback: (err: Error | undefined, stats: Stats) => void): void;
1942
1943 /**
1944 * (Client-only)
1945 * Sets the attributes defined in `attributes` for `path`.
1946 */
1947 setstat(path: string, attributes: InputAttributes, callback: Callback): void;
1948
1949 /**
1950 * (Client-only)
1951 * Sets the access time and modified time for `path`.
1952 */
1953 utimes(path: string, atime: number | Date, mtime: number | Date, callback: Callback): void;
1954
1955 /**
1956 * (Client-only)
1957 * Sets the owner for `path`.
1958 */
1959 chown(path: string, uid: number, gid: number, callback: Callback): void;
1960
1961 /**
1962 * (Client-only)
1963 * Sets the mode for `path`.
1964 */
1965 chmod(path: string, mode: number | string, callback: Callback): void;
1966
1967 /**
1968 * (Client-only)
1969 * Retrieves the target for a symlink at `path`.
1970 */
1971 readlink(path: string, callback: (err: Error | undefined, target: string) => void): void;
1972
1973 /**
1974 * (Client-only)
1975 * Creates a symlink at `linkPath` to `targetPath`.
1976 */
1977 symlink(targetPath: string, linkPath: string, callback: Callback): void;
1978
1979 /**
1980 * (Client-only)
1981 * Resolves `path` to an absolute path.
1982 */
1983 realpath(path: string, callback: (err: Error | undefined, absPath: string) => void): void;
1984
1985 /**
1986 * (Client-only, OpenSSH extension)
1987 * Performs POSIX rename(3) from `srcPath` to `destPath`.
1988 */
1989 ext_openssh_rename(srcPath: string, destPath: string, callback: Callback): void;
1990
1991 /**
1992 * (Client-only, OpenSSH extension)
1993 * Performs POSIX statvfs(2) on `path`.
1994 */
1995 ext_openssh_statvfs(path: string, callback: (err: Error | undefined, fsInfo: any) => void): void;
1996
1997 /**
1998 * (Client-only, OpenSSH extension)
1999 * Performs POSIX fstatvfs(2) on open handle `handle`.
2000 */
2001 ext_openssh_fstatvfs(handle: Buffer, callback: (err: Error | undefined, fsInfo: any) => void): void;
2002
2003 /**
2004 * (Client-only, OpenSSH extension)
2005 * Performs POSIX link(2) to create a hard link to `targetPath` at `linkPath`.
2006 */
2007 ext_openssh_hardlink(targetPath: string, linkPath: string, callback: Callback): void;
2008
2009 /**
2010 * (Client-only, OpenSSH extension)
2011 * Performs POSIX fsync(3) on the open handle `handle`.
2012 */
2013 ext_openssh_fsync(handle: Buffer, callback: (err: Error | undefined, fsInfo: any) => void): void;
2014
2015 /**
2016 * (Client-only, OpenSSH extension)
2017 * Similar to setstat(), but instead sets attributes on symlinks.
2018 */
2019 ext_openssh_lsetstat(path: string, attrs: InputAttributes, callback: Callback): void;
2020 ext_openssh_lsetstat(path: string, callback: Callback): void;
2021
2022 /**
2023 * (Client-only, OpenSSH extension)
2024 * Similar to realpath(), but supports tilde-expansion, i.e. "~", "~/..." and "~user/...". These paths are expanded using shell-like rules.
2025 */
2026 ext_openssh_expandPath(path: string, callback: (err: Error | undefined, absPath: string) => void): void;
2027
2028 /**
2029 * (Client-only)
2030 * Performs a remote file copy. If length is 0, then the server will read from srcHandle until EOF is reached.
2031 */
2032 ext_copy_data(
2033 handle: Buffer,
2034 srcOffset: number,
2035 len: number,
2036 dstHandle: Buffer,
2037 dstOffset: number,
2038 callback: Callback,
2039 ): void;
2040
2041 /**
2042 * Emitted after initial protocol version check has passed
2043 */
2044 on(event: "ready", listener: () => void): this;
2045 on(event: "OPEN", listener: (reqId: number, filename: string, flags: number, attrs: Attributes) => void): this;
2046 on(event: "READ", listener: (reqId: number, handle: Buffer, offset: number, len: number) => void): this;
2047 on(event: "WRITE", listener: (reqId: number, handle: Buffer, offset: number, data: Buffer) => void): this;
2048 on(event: "FSTAT", listener: (reqId: number, handle: Buffer) => void): this;
2049 on(event: "FSETSTAT", listener: (reqId: number, handle: Buffer, attrs: Attributes) => void): this;
2050 on(event: "CLOSE", listener: (reqId: number, handle: Buffer) => void): this;
2051 on(event: "OPENDIR", listener: (reqId: number, path: string) => void): this;
2052 on(event: "READDIR", listener: (reqId: number, handle: Buffer) => void): this;
2053 on(event: "LSTAT", listener: (reqId: number, path: string) => void): this;
2054 on(event: "STAT", listener: (reqId: number, path: string) => void): this;
2055 on(event: "REMOVE", listener: (reqId: number, path: string) => void): this;
2056 on(event: "RMDIR", listener: (reqId: number, path: string) => void): this;
2057 on(event: "REALPATH", listener: (reqId: number, path: string) => void): this;
2058 on(event: "READLINK", listener: (reqId: number, path: string) => void): this;
2059 on(event: "SETSTAT", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2060 on(event: "MKDIR", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2061 on(event: "RENAME", listener: (reqId: number, oldPath: string, newPath: string) => void): this;
2062 on(event: "SYMLINK", listener: (reqId: number, targetPath: string, linkPath: string) => void): this;
2063 on(event: "EXTENDED", listener: (reqId: number, extName: string, extData: Buffer) => void): this;
2064 on(event: string | symbol, listener: Function): this;
2065
2066 /**
2067 * Emitted after initial protocol version check has passed
2068 */
2069 once(event: "ready", listener: () => void): this;
2070 once(event: "OPEN", listener: (reqId: number, filename: string, flags: number, attrs: Attributes) => void): this;
2071 once(event: "READ", listener: (reqId: number, handle: Buffer, offset: number, len: number) => void): this;
2072 once(event: "WRITE", listener: (reqId: number, handle: Buffer, offset: number, data: Buffer) => void): this;
2073 once(event: "FSTAT", listener: (reqId: number, handle: Buffer) => void): this;
2074 once(event: "FSETSTAT", listener: (reqId: number, handle: Buffer, attrs: Attributes) => void): this;
2075 once(event: "CLOSE", listener: (reqId: number, handle: Buffer) => void): this;
2076 once(event: "OPENDIR", listener: (reqId: number, path: string) => void): this;
2077 once(event: "READDIR", listener: (reqId: number, handle: Buffer) => void): this;
2078 once(event: "LSTAT", listener: (reqId: number, path: string) => void): this;
2079 once(event: "STAT", listener: (reqId: number, path: string) => void): this;
2080 once(event: "REMOVE", listener: (reqId: number, path: string) => void): this;
2081 once(event: "RMDIR", listener: (reqId: number, path: string) => void): this;
2082 once(event: "REALPATH", listener: (reqId: number, path: string) => void): this;
2083 once(event: "READLINK", listener: (reqId: number, path: string) => void): this;
2084 once(event: "SETSTAT", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2085 once(event: "MKDIR", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2086 once(event: "RENAME", listener: (reqId: number, oldPath: string, newPath: string) => void): this;
2087 once(event: "SYMLINK", listener: (reqId: number, targetPath: string, linkPath: string) => void): this;
2088 once(event: "EXTENDED", listener: (reqId: number, extName: string, extData: Buffer) => void): this;
2089 once(event: string | symbol, listener: Function): this;
2090
2091 /**
2092 * Sends a status response for the request identified by id.
2093 */
2094 status(reqId: number, code: number, message?: string): void;
2095
2096 /**
2097 * Sends a handle response for the request identified by id.
2098 * handle must be less than 256 bytes and is an opaque value that could merely contain the value of a
2099 * backing file descriptor or some other unique, custom value.
2100 */
2101 handle(reqId: number, handle: Buffer): void;
2102
2103 /**
2104 * Sends a data response for the request identified by id. data can be a Buffer or string.
2105 * If data is a string, encoding is the encoding of data.
2106 */
2107 data(reqId: number, data: Buffer | string, encoding?: BufferEncoding): void;
2108
2109 /**
2110 * Sends a name response for the request identified by id.
2111 */
2112 name(reqId: number, names: FileEntry[]): void;
2113
2114 /**
2115 * Sends an attrs response for the request identified by id.
2116 */
2117 attrs(reqId: number, attrs: Attributes): void;
2118
2119 /**
2120 * Closes the channel.
2121 */
2122 end(): void;
2123
2124 /**
2125 * Closes the channel.
2126 */
2127 destroy(): void;
2128}
2129
2130export interface PublicKeyEntry {
2131 pubKey:
2132 | ParsedKey
2133 | {
2134 pubKey: ParsedKey | Buffer | string;
2135 comment?: string;
2136 };
2137}
2138
2139export type KnownPublicKeys<T extends string | Buffer | ParsedKey = string | Buffer | ParsedKey> = Array<
2140 | T
2141 | PublicKeyEntry
2142>;
2143
2144export type PrivateKeys = Array<Buffer | ParsedKey | EncryptedPrivateKey | string>;
2145
2146export type Callback = (err?: Error | null) => void;
2147
2148export type ErrorCallback = (err: Error) => void;
2149
2150export type IdentityCallback<T extends string | Buffer | ParsedKey = string | Buffer | ParsedKey> = (
2151 err?: Error | null,
2152 keys?: KnownPublicKeys<T>,
2153) => void;
2154
2155export type SignCallback = (err?: Error | null, signature?: Buffer) => void;
2156
2157export type GetStreamCallback = (err?: Error | null, stream?: Duplex) => void;
2158
2159/**
2160 * Interface representing an inbound agent request. This is defined as an
2161 * "opaque type" in the ssh2 documentation, and should only be used
2162 * for correlation, not introspected.
2163 */
2164export interface AgentInboundRequest {
2165 __opaque_type: never;
2166}
2167
2168export interface SigningRequestOptions {
2169 hash?: "sha1" | "sha256" | "sha512";
2170}
2171
2172export class AgentProtocol extends Duplex {
2173 /**
2174 * Creates and returns a new AgentProtocol instance. `isClient` determines
2175 * whether the instance operates in client or server mode.
2176 */
2177 constructor(isClient: boolean);
2178
2179 /**
2180 * (Server mode only)
2181 * Replies to the given `request` with a failure response.
2182 */
2183 failureReply(request: AgentInboundRequest): void;
2184
2185 /**
2186 * (Client mode only)
2187 * Requests a list of public keys from the agent. `callback` is passed
2188 * `(err, keys)` where `keys` is a possible array of public keys for
2189 * authentication.
2190 */
2191 getIdentities(callback: (err: Error | undefined, publicKeys?: ParsedKey[]) => void): void;
2192
2193 /**
2194 * (Server mode only)
2195 * Responds to a identities list `request` with the given array of keys in `keys`.
2196 */
2197 getIdentitiesReply(request: AgentInboundRequest, keys: ParsedKey[]): void;
2198
2199 /**
2200 * (Client mode only)
2201 * Signs the datawith the given public key, and calls back with its signature.
2202 */
2203 sign(
2204 pubKey: ParsedKey | Buffer | string,
2205 data: Buffer,
2206 options?: SigningRequestOptions,
2207 callback?: SignCallback,
2208 ): boolean;
2209 sign(pubKey: ParsedKey | Buffer | string, data: Buffer, callback?: SignCallback): boolean;
2210
2211 /**
2212 * (Server mode only)
2213 * Responds to a sign `request` with the given signature in `signature`.
2214 */
2215 signReply(request: AgentInboundRequest, signature: Buffer): void;
2216
2217 /**
2218 * (Server mode only)
2219 * The client has requested a list of public keys stored in the agent.
2220 * Use `failureReply()` or `getIdentitiesReply()` to reply appropriately.
2221 */
2222 on(event: "identities", listener: (req: AgentInboundRequest) => void): this;
2223
2224 /**
2225 * (Server mode only)
2226 * The client has requested `data` to be signed using the key identified
2227 * by `pubKey`. Use `failureReply()` or `signReply()` to reply appropriately.
2228 */
2229 on(
2230 event: "sign",
2231 listener: (req: AgentInboundRequest, pubKey: ParsedKey, data: Buffer, options: SigningRequestOptions) => void,
2232 ): this;
2233
2234 on(event: string | symbol, listener: Function): this;
2235
2236 /**
2237 * (Server mode only)
2238 * The client has requested a list of public keys stored in the agent.
2239 * Use `failureReply()` or `getIdentitiesReply()` to reply appropriately.
2240 */
2241 once(event: "identities", listener: (req: AgentInboundRequest) => void): this;
2242
2243 /**
2244 * (Server mode only)
2245 * The client has requested `data` to be signed using the key identified
2246 * by `pubKey`. Use `failureReply()` or `signReply()` to reply appropriately.
2247 */
2248 once(
2249 event: "sign",
2250 listener: (req: AgentInboundRequest, pubKey: ParsedKey, data: Buffer, options: SigningRequestOptions) => void,
2251 ): this;
2252
2253 once(event: string | symbol, listener: Function): this;
2254}
2255
2256/**
2257 * Creates and returns a new agent instance using the same logic as the
2258 * `Client`'s `agent` configuration option: if the platform is Windows and
2259 * it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not
2260 * a path to a Windows pipe it creates a `CygwinAgent`. In all other cases,
2261 * it creates an `OpenSSHAgent`.
2262 */
2263export function createAgent(socketPath: string | "pageant"): BaseAgent;
2264
2265export abstract class BaseAgent<TPublicKey extends string | Buffer | ParsedKey = string | Buffer | ParsedKey> {
2266 /**
2267 * Retrieves user identities, where `keys` is a possible array of public
2268 * keys for authentication.
2269 */
2270 abstract getIdentities(cb: IdentityCallback<TPublicKey>): void;
2271
2272 /**
2273 * Signs the datawith the given public key, and calls back with its signature.
2274 * Note that, in the current implementation, "options" is always an empty object.
2275 */
2276 abstract sign(pubKey: TPublicKey, data: Buffer, options: SigningRequestOptions, cb?: SignCallback): void;
2277 abstract sign(pubKey: TPublicKey, data: Buffer, cb: SignCallback): void;
2278
2279 /**
2280 * Optional method that may be implemented to support agent forwarding. Callback
2281 * should be invoked with a Duplex stream to be used to communicate with your agent/
2282 * You will probably want to utilize `AgentProtocol` as agent forwarding is an
2283 * OpenSSH feature, so the `stream` needs to be able to
2284 * transmit/receive OpenSSH agent protocol packets.
2285 */
2286 getStream?(cb: GetStreamCallback): void;
2287}
2288
2289/**
2290 * Communicates with an OpenSSH agent listening on the UNIX socket at `socketPath`.
2291 */
2292export class OpenSSHAgent extends BaseAgent<ParsedKey> {
2293 constructor(socketPath: string);
2294
2295 /** @inheritdoc */
2296 getIdentities(cb: IdentityCallback<ParsedKey>): void;
2297
2298 /** @inheritdoc */
2299 sign(
2300 pubKey: ParsedKey | Buffer | string,
2301 data: Buffer,
2302 options?: SigningRequestOptions,
2303 cb?: SignCallback,
2304 ): boolean;
2305 sign(pubKey: ParsedKey | Buffer | string, data: Buffer, cb?: SignCallback): boolean;
2306
2307 /** @inheritdoc */
2308 getStream(cb: GetStreamCallback): void;
2309}
2310
2311/**
2312 * Communicates with an agent listening at `socketPath` in a Cygwin environment.
2313 */
2314export class CygwinAgent extends OpenSSHAgent {}
2315
2316/**
2317 * Creates a new agent instance for communicating with a running Pageant agent process.
2318 */
2319export class PageantAgent extends OpenSSHAgent {}
2320
2321export interface NegotiatedAlgorithms {
2322 kex: KexAlgorithm;
2323 serverHostKey: ServerHostKeyAlgorithm;
2324 cs: {
2325 cipher: CipherAlgorithm;
2326 mac: MacAlgorithm | "";
2327 compress: CompressionAlgorithm;
2328 lang: string;
2329 };
2330 sc: {
2331 cipher: CipherAlgorithm;
2332 mac: MacAlgorithm | "";
2333 compress: CompressionAlgorithm;
2334 lang: string;
2335 };
2336}
2337
2338export type VerifyCallback = (valid: boolean) => void;
2339
2340export interface ReadStreamOptions extends ReadableOptions {
2341 flags?: OpenMode;
2342 mode?: number;
2343 start?: number;
2344 end?: number;
2345 autoClose?: boolean;
2346 handle?: Buffer;
2347}
2348
2349export interface WriteStreamOptions extends WritableOptions {
2350 flags?: OpenMode;
2351 mode?: number;
2352 start?: number;
2353 autoClose?: boolean;
2354 handle?: Buffer;
2355 encoding?: BufferEncoding;
2356}
2357
2358export interface ReadStream extends Readable {
2359 pending: boolean;
2360 open(): void;
2361 close(cb: Callback): void;
2362 on(eventName: "ready", listener: () => void): this;
2363 on(eventName: "open", listener: (handle: Buffer) => void): this;
2364 on(event: string | symbol, listener: Function): this;
2365 once(eventName: "ready", listener: () => void): this;
2366 once(eventName: "open", listener: (handle: Buffer) => void): this;
2367 once(event: string | symbol, listener: Function): this;
2368}
2369
2370export interface WriteStream extends Writable {
2371 pending: boolean;
2372 open(): void;
2373 destroy(): this;
2374 close(cb: Callback): void;
2375 on(eventName: "ready", listener: () => void): this;
2376 on(eventName: "open", listener: (handle: Buffer) => void): this;
2377 on(event: string | symbol, listener: Function): this;
2378 once(eventName: "ready", listener: () => void): this;
2379 once(eventName: "open", listener: (handle: Buffer) => void): this;
2380 once(event: string | symbol, listener: Function): this;
2381}
2382
2383export type ClientCallback = (err: Error | undefined, channel: ClientChannel) => void;
2384
2385export type ServerCallback = (err: Error | undefined, channel: ServerChannel) => void;
2386
2387export type ClientForwardCallback = (err: Error | undefined, port: number) => void;
2388
2389export type ClientSFTPCallback = (err: Error | undefined, sftp: SFTPWrapper) => void;
2390
2391export type ChangePasswordCallback = (newPassword: string) => void;
2392
2393export type KeyboardInteractiveCallback = (answers: string[]) => void;
2394
2395export interface UNIXConnectionDetails {
2396 socketPath: string;
2397}
2398
2399export interface HTTPAgentOptions extends BaseHTTPAgentOptions {
2400 srcIP?: string;
2401}
2402
2403export class HTTPAgent extends BaseHTTPAgent {
2404 constructor(connectCfg: ConnectConfig, agentOptions: HTTPAgentOptions);
2405}
2406
2407export interface HTTPSAgentOptions extends BaseHTTPSAgentOptions {
2408 srcIP?: string;
2409}
2410
2411export class HTTPSAgent extends BaseHTTPSAgent {
2412 constructor(connectCfg: ConnectConfig, agentOptions: HTTPSAgentOptions);
2413}