UNPKG

82.1 kBTypeScriptView Raw
1/// <reference types="node" />
2
3import { EventEmitter } from "events";
4import { Agent as BaseHTTPAgent, AgentOptions } from "http";
5import { Agent as BaseHTTPSAgent } 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}
1280
1281export interface PublicKey {
1282 /** The name of the key algorithm. */
1283 algo: string;
1284 /** The actual key data. */
1285 data: Buffer;
1286}
1287
1288export interface HostbasedAuthContext extends AuthContextBase {
1289 /** The method of authentication. */
1290 method: "hostbased";
1291 /** The public key sent by the client. */
1292 key: PublicKey;
1293 /** The signature to verify, or `undefined` if the client is only checking the validity of the key. */
1294 signature: Buffer;
1295 /** The data used to verify the key, or `undefined` if the client is only checking the validity of the key. */
1296 blob: Buffer;
1297 /** The local hostname of the client. */
1298 localHostname: string;
1299 /** The local username of the client. */
1300 localUsername: string;
1301}
1302
1303export interface PasswordAuthContext extends AuthContextBase {
1304 /** The method of authentication. */
1305 method: "password";
1306 /** The password sent by the client. */
1307 password: string;
1308 requestChange(prompt: string, cb: ChangePasswordCallback): void;
1309}
1310
1311export interface NoneAuthContext extends AuthContextBase {
1312 /** The method of authentication. */
1313 method: "none";
1314}
1315
1316export type AuthContext =
1317 | KeyboardAuthContext
1318 | PublicKeyAuthContext
1319 | HostbasedAuthContext
1320 | PasswordAuthContext
1321 | NoneAuthContext;
1322
1323export interface TcpipRequestInfo {
1324 /** Source IP address of outgoing connection. */
1325 srcIP: string;
1326 /** Source port of outgoing connection. */
1327 srcPort: number;
1328 /** Destination IP address of outgoing connection. */
1329 destIP: string;
1330 /** Destination port of outgoing connection. */
1331 destPort: number;
1332}
1333
1334export interface SocketRequestInfo {
1335 /** Destination socket path of outgoing connection. */
1336 socketPath: string;
1337}
1338
1339export interface TcpipBindInfo {
1340 /** The IP address to start/stop binding to. */
1341 bindAddr: string;
1342 /** The port to start/stop binding to. */
1343 bindPort: number;
1344}
1345
1346export interface SocketBindInfo {
1347 /** The socket path to start/stop binding to. */
1348 socketPath: string;
1349}
1350
1351// keep so anyone importing this doesn't see breaking changes
1352export type SessionAcceptReject = () => void;
1353export type SessionAccept = () => void;
1354
1355// NB: Doesn't actually extend ServerChannel/Channel/Duplex, it is just an EventEmitter
1356export interface Session extends ServerChannel {
1357 // Session events
1358
1359 /**
1360 * Emitted when the client requested allocation of a pseudo-TTY for this session.
1361 */
1362 on(event: "pty", listener: (accept: SessionAccept, reject: RejectConnection, info: PseudoTtyInfo) => void): this;
1363
1364 /**
1365 * Emitted when the client reported a change in window dimensions during this session.
1366 */
1367 on(
1368 event: "window-change",
1369 listener: (accept: SessionAccept, reject: RejectConnection, info: WindowChangeInfo) => void,
1370 ): this;
1371
1372 /**
1373 * Emitted when the client requested X11 forwarding.
1374 */
1375 on(event: "x11", listener: (accept: SessionAccept, reject: RejectConnection, info: X11Info) => void): this;
1376
1377 /**
1378 * Emitted when the client requested an environment variable to be set for this session.
1379 */
1380 on(event: "env", listener: (accept: SessionAccept, reject: RejectConnection, info: SetEnvInfo) => void): this;
1381
1382 /**
1383 * Emitted when the client has sent a POSIX signal.
1384 */
1385 on(event: "signal", listener: (accept: SessionAccept, reject: RejectConnection, info: SignalInfo) => void): this;
1386
1387 /**
1388 * Emitted when the client has requested incoming ssh-agent requests be forwarded to them.
1389 */
1390 on(event: "auth-agent", listener: (accept: SessionAccept, reject: RejectConnection) => void): this;
1391
1392 /**
1393 * Emitted when the client has requested an interactive shell.
1394 */
1395 on(event: "shell", listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection) => void): this;
1396
1397 /**
1398 * Emitted when the client has requested execution of a command string.
1399 */
1400 on(
1401 event: "exec",
1402 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: ExecInfo) => void,
1403 ): this;
1404
1405 /**
1406 * Emitted when the client has requested the SFTP subsystem.
1407 */
1408 on(event: "sftp", listener: (accept: AcceptSftpConnection, reject: RejectConnection) => void): this;
1409
1410 /**
1411 * Emitted when the client has requested an arbitrary subsystem.
1412 */
1413 on(
1414 event: "subsystem",
1415 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: SubsystemInfo) => void,
1416 ): this;
1417
1418 on(event: string | symbol, listener: Function): this;
1419
1420 /**
1421 * Emitted when the client requested allocation of a pseudo-TTY for this session.
1422 */
1423 once(event: "pty", listener: (accept: SessionAccept, reject: RejectConnection, info: PseudoTtyInfo) => void): this;
1424
1425 /**
1426 * Emitted when the client reported a change in window dimensions during this session.
1427 */
1428 once(
1429 event: "window-change",
1430 listener: (accept: SessionAccept, reject: RejectConnection, info: WindowChangeInfo) => void,
1431 ): this;
1432
1433 /**
1434 * Emitted when the client requested X11 forwarding.
1435 */
1436 once(event: "x11", listener: (accept: SessionAccept, reject: RejectConnection, info: X11Info) => void): this;
1437
1438 /**
1439 * Emitted when the client requested an environment variable to be set for this session.
1440 */
1441 once(event: "env", listener: (accept: SessionAccept, reject: RejectConnection, info: SetEnvInfo) => void): this;
1442
1443 /**
1444 * Emitted when the client has sent a POSIX signal.
1445 */
1446 once(event: "signal", listener: (accept: SessionAccept, reject: RejectConnection, info: SignalInfo) => void): this;
1447
1448 /**
1449 * Emitted when the client has requested incoming ssh-agent requests be forwarded to them.
1450 */
1451 once(event: "auth-agent", listener: (accept: SessionAccept, reject: RejectConnection) => void): this;
1452
1453 /**
1454 * Emitted when the client has requested an interactive shell.
1455 */
1456 once(event: "shell", listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection) => void): this;
1457
1458 /**
1459 * Emitted when the client has requested execution of a command string.
1460 */
1461 once(
1462 event: "exec",
1463 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: ExecInfo) => void,
1464 ): this;
1465
1466 /**
1467 * Emitted when the client has requested the SFTP subsystem.
1468 */
1469 once(event: "sftp", listener: (accept: AcceptSftpConnection, reject: RejectConnection) => void): this;
1470
1471 /**
1472 * Emitted when the client has requested an arbitrary subsystem.
1473 */
1474 once(
1475 event: "subsystem",
1476 listener: (accept: AcceptConnection<ServerChannel>, reject: RejectConnection, info: SubsystemInfo) => void,
1477 ): this;
1478
1479 once(event: string | symbol, listener: Function): this;
1480}
1481
1482export interface PseudoTtyInfo {
1483 /** The number of columns for the pseudo-TTY. */
1484 cols: number;
1485 /** The number of rows for the pseudo-TTY. */
1486 rows: number;
1487 /** The width of the pseudo-TTY in pixels. */
1488 width: number;
1489 /** The height of the pseudo-TTY in pixels. */
1490 height: number;
1491 /** Contains the requested terminal modes of the pseudo-TTY. */
1492 modes: TerminalModes;
1493}
1494
1495export interface TerminalModes {
1496 /** Interrupt character; `255` if none. Not all of these characters are supported on all systems. */
1497 VINTR?: number | undefined;
1498 /** The quit character (sends `SIGQUIT` signal on POSIX systems). */
1499 VQUIT?: number | undefined;
1500 /** Erase the character to left of the cursor. */
1501 VERASE?: number | undefined;
1502 /** Kill the current input line. */
1503 VKILL?: number | undefined;
1504 /** End-of-file character (sends `EOF` from the terminal). */
1505 VEOF?: number | undefined;
1506 /** End-of-line character in addition to carriage return and/or linefeed. */
1507 VEOL?: number | undefined;
1508 /** Additional end-of-line character. */
1509 VEOL2?: number | undefined;
1510 /** Continues paused output (normally control-Q). */
1511 VSTART?: number | undefined;
1512 /** Pauses output (normally control-S). */
1513 VSTOP?: number | undefined;
1514 /** Suspends the current program. */
1515 VSUSP?: number | undefined;
1516 /** Another suspend character. */
1517 VDSUSP?: number | undefined;
1518 /** Reprints the current input line. */
1519 VREPRINT?: number | undefined;
1520 /** Erases a word left of cursor. */
1521 VWERASE?: number | undefined;
1522 /** Enter the next character typed literally, even if it is a special character */
1523 VLNEXT?: number | undefined;
1524 /** Character to flush output. */
1525 VFLUSH?: number | undefined;
1526 /** Switch to a different shell layer. */
1527 VSWTCH?: number | undefined;
1528 /** Prints system status line (load, command, pid, etc). */
1529 VSTATUS?: number | undefined;
1530 /** Toggles the flushing of terminal output. */
1531 VDISCARD?: number | undefined;
1532 /** The ignore parity flag. The parameter SHOULD be `0` if this flag is FALSE, and `1` if it is TRUE. */
1533 IGNPAR?: 0 | 1 | undefined;
1534 /** Mark parity and framing errors. */
1535 PARMRK?: 0 | 1 | undefined;
1536 /** Enable checking of parity errors. */
1537 INPCK?: 0 | 1 | undefined;
1538 /** Strip 8th bit off characters. */
1539 ISTRIP?: 0 | 1 | undefined;
1540 /** Map NL into CR on input. */
1541 INLCR?: 0 | 1 | undefined;
1542 /** Ignore CR on input. */
1543 IGNCR?: 0 | 1 | undefined;
1544 /** Map CR to NL on input. */
1545 ICRNL?: 0 | 1 | undefined;
1546 /** Translate uppercase characters to lowercase. */
1547 IUCLC?: 0 | 1 | undefined;
1548 /** Enable output flow control. */
1549 IXON?: 0 | 1 | undefined;
1550 /** Any char will restart after stop. */
1551 IXANY?: 0 | 1 | undefined;
1552 /** Enable input flow control. */
1553 IXOFF?: 0 | 1 | undefined;
1554 /** Ring bell on input queue full. */
1555 IMAXBEL?: 0 | 1 | undefined;
1556 /** Enable signals INTR, QUIT, [D]SUSP. */
1557 ISIG?: 0 | 1 | undefined;
1558 /** Canonicalize input lines. */
1559 ICANON?: 0 | 1 | undefined;
1560 /** Enable input and output of uppercase characters by preceding their lowercase equivalents with `\`. */
1561 XCASE?: 0 | 1 | undefined;
1562 /** Enable echoing. */
1563 ECHO?: 0 | 1 | undefined;
1564 /** Visually erase chars. */
1565 ECHOE?: 0 | 1 | undefined;
1566 /** Kill character discards current line. */
1567 ECHOK?: 0 | 1 | undefined;
1568 /** Echo NL even if ECHO is off. */
1569 ECHONL?: 0 | 1 | undefined;
1570 /** Don't flush after interrupt. */
1571 NOFLSH?: 0 | 1 | undefined;
1572 /** Stop background jobs from output. */
1573 TOSTOP?: 0 | 1 | undefined;
1574 /** Enable extensions. */
1575 IEXTEN?: 0 | 1 | undefined;
1576 /** Echo control characters as ^(Char). */
1577 ECHOCTL?: 0 | 1 | undefined;
1578 /** Visual erase for line kill. */
1579 ECHOKE?: 0 | 1 | undefined;
1580 /** Retype pending input. */
1581 PENDIN?: 0 | 1 | undefined;
1582 /** Enable output processing. */
1583 OPOST?: 0 | 1 | undefined;
1584 /** Convert lowercase to uppercase. */
1585 OLCUC?: 0 | 1 | undefined;
1586 /** Map NL to CR-NL. */
1587 ONLCR?: 0 | 1 | undefined;
1588 /** Translate carriage return to newline (output). */
1589 OCRNL?: 0 | 1 | undefined;
1590 /** Translate newline to carriage return-newline (output). */
1591 ONOCR?: 0 | 1 | undefined;
1592 /** Newline performs a carriage return (output). */
1593 ONLRET?: 0 | 1 | undefined;
1594 /** 7 bit mode. */
1595 CS7?: 0 | 1 | undefined;
1596 /** 8 bit mode. */
1597 CS8?: 0 | 1 | undefined;
1598 /** Parity enable. */
1599 PARENB?: 0 | 1 | undefined;
1600 /** Odd parity, else even. */
1601 PARODD?: 0 | 1 | undefined;
1602 /** Specifies the input baud rate in bits per second. */
1603 TTY_OP_ISPEED?: number | undefined;
1604 /** Specifies the output baud rate in bits per second. */
1605 TTY_OP_OSPEED?: number | undefined;
1606}
1607
1608export interface WindowChangeInfo {
1609 /** The number of columns for the pseudo-TTY. */
1610 cols: number;
1611 /** The number of rows for the pseudo-TTY. */
1612 rows: number;
1613 /** The width of the pseudo-TTY in pixels. */
1614 width: number;
1615 /** The height of the pseudo-TTY in pixels. */
1616 height: number;
1617}
1618
1619export interface X11Info {
1620 /** true if only a single connection should be forwarded. */
1621 single: boolean;
1622 /** The name of the X11 authentication method used. */
1623 protocol: string;
1624 /** The X11 authentication cookie encoded in hexadecimal. */
1625 cookie: string;
1626 /** The screen number for which to forward X11 connections. */
1627 screen: number;
1628}
1629
1630export interface SetEnvInfo {
1631 /** The environment variable's name. */
1632 key: string;
1633 /** The environment variable's value. */
1634 value: string;
1635}
1636
1637export interface SignalInfo {
1638 /** The signal name (e.g. SIGUSR1). */
1639 name: string;
1640}
1641
1642export interface ExecInfo {
1643 /** The command line to be executed. */
1644 command: string;
1645}
1646
1647export interface SubsystemInfo {
1648 /** The name of the subsystem. */
1649 name: string;
1650}
1651
1652export interface TransferOptions {
1653 concurrency?: number;
1654 chunkSize?: number;
1655 fileSize?: number;
1656 step?: (total: number, nb: number, fsize: number) => void;
1657 mode?: number | string;
1658}
1659
1660export interface ReadFileOptions {
1661 encoding?: BufferEncoding;
1662 flag?: string;
1663}
1664
1665export interface WriteFileOptions {
1666 encoding?: BufferEncoding;
1667 mode?: number;
1668 flag?: string;
1669}
1670
1671export interface InputAttributes {
1672 mode?: number | string;
1673 uid?: number;
1674 gid?: number;
1675 size?: number;
1676 atime?: number | Date;
1677 mtime?: number | Date;
1678}
1679
1680export interface Attributes {
1681 mode: number;
1682 uid: number;
1683 gid: number;
1684 size: number;
1685 atime: number;
1686 mtime: number;
1687}
1688
1689export interface Stats extends Attributes {
1690 isDirectory(): boolean;
1691 isFile(): boolean;
1692 isBlockDevice(): boolean;
1693 isCharacterDevice(): boolean;
1694 isSymbolicLink(): boolean;
1695 isFIFO(): boolean;
1696 isSocket(): boolean;
1697}
1698
1699export interface FileEntry {
1700 filename: string;
1701 longname: string;
1702 attrs: Attributes;
1703}
1704
1705export interface FileEntryWithStats extends Omit<FileEntry, "attrs"> {
1706 attrs: Stats;
1707}
1708
1709export interface SFTPWrapper extends EventEmitter {
1710 /**
1711 * (Client-only)
1712 * Downloads a file at `remotePath` to `localPath` using parallel reads for faster throughput.
1713 */
1714 fastGet(remotePath: string, localPath: string, options: TransferOptions, callback: Callback): void;
1715
1716 /**
1717 * (Client-only)
1718 * Downloads a file at `remotePath` to `localPath` using parallel reads for faster throughput.
1719 */
1720 fastGet(remotePath: string, localPath: string, callback: Callback): void;
1721
1722 /**
1723 * (Client-only)
1724 * Uploads a file from `localPath` to `remotePath` using parallel reads for faster throughput.
1725 */
1726 fastPut(localPath: string, remotePath: string, options: TransferOptions, callback: Callback): void;
1727
1728 /**
1729 * (Client-only)
1730 * Uploads a file from `localPath` to `remotePath` using parallel reads for faster throughput.
1731 */
1732 fastPut(localPath: string, remotePath: string, callback: Callback): void;
1733
1734 /**
1735 * (Client-only)
1736 * Reads a file in memory and returns its contents
1737 */
1738 readFile(
1739 remotePath: string,
1740 options: ReadFileOptions,
1741 callback: (err: Error | undefined, handle: Buffer) => void,
1742 ): void;
1743
1744 /**
1745 * (Client-only)
1746 * Reads a file in memory and returns its contents
1747 */
1748 readFile(
1749 remotePath: string,
1750 encoding: BufferEncoding,
1751 callback: (err: Error | undefined, handle: Buffer) => void,
1752 ): void;
1753
1754 /**
1755 * (Client-only)
1756 * Reads a file in memory and returns its contents
1757 */
1758 readFile(remotePath: string, callback: (err: Error | undefined, handle: Buffer) => void): void;
1759
1760 /**
1761 * (Client-only)
1762 * Returns a new readable stream for `path`.
1763 */
1764 createReadStream(path: string, options?: ReadStreamOptions): ReadStream;
1765
1766 /**
1767 * (Client-only)
1768 * Writes data to a file
1769 */
1770 writeFile(remotePath: string, data: string | Buffer, options: WriteFileOptions, callback?: Callback): void;
1771
1772 /**
1773 * (Client-only)
1774 * Writes data to a file
1775 */
1776 writeFile(remotePath: string, data: string | Buffer, encoding: string, callback?: Callback): void;
1777
1778 /**
1779 * (Client-only)
1780 * Writes data to a file
1781 */
1782 writeFile(remotePath: string, data: string | Buffer, callback?: Callback): void;
1783
1784 /**
1785 * (Client-only)
1786 * Appends data to a file
1787 */
1788 appendFile(remotePath: string, data: string | Buffer, options: WriteFileOptions, callback?: Callback): void;
1789
1790 /**
1791 * (Client-only)
1792 * Appends data to a file
1793 */
1794 appendFile(remotePath: string, data: string | Buffer, callback?: Callback): void;
1795
1796 /**
1797 * (Client-only)
1798 * Returns a new writable stream for `path`.
1799 */
1800 createWriteStream(path: string, options?: WriteStreamOptions): WriteStream;
1801
1802 /**
1803 * (Client-only)
1804 * Opens a file `filename` for `mode` with optional `attributes`.
1805 */
1806 open(
1807 filename: string,
1808 mode: number | OpenMode,
1809 attributes: InputAttributes,
1810 callback: (err: Error | undefined, handle: Buffer) => void,
1811 ): void;
1812 open(
1813 filename: string,
1814 mode: number | OpenMode,
1815 attributes: string | number,
1816 callback: (err: Error | undefined, handle: Buffer) => void,
1817 ): void;
1818
1819 /**
1820 * (Client-only)
1821 * Opens a file `filename` for `mode`.
1822 */
1823 open(filename: string, mode: number | OpenMode, callback: (err: Error | undefined, handle: Buffer) => void): void;
1824
1825 /**
1826 * (Client-only)
1827 * Closes the resource associated with `handle` given by `open()` or `opendir()`.
1828 */
1829 close(handle: Buffer, callback: Callback): void;
1830
1831 /**
1832 * (Client-only)
1833 * Reads `length` bytes from the resource associated with `handle` starting at `position`
1834 * and stores the bytes in `buffer` starting at `offset`.
1835 */
1836 read(
1837 handle: Buffer,
1838 buffer: Buffer,
1839 offset: number,
1840 length: number,
1841 position: number,
1842 callback: (err: Error | undefined, bytesRead: number, buffer: Buffer, position: number) => void,
1843 ): void;
1844
1845 /**
1846 * (Client-only)
1847 */
1848 write(handle: Buffer, buffer: Buffer, offset: number, length: number, position: number, callback: Callback): void;
1849
1850 /**
1851 * (Client-only)
1852 * Retrieves attributes for the resource associated with `handle`.
1853 */
1854 fstat(handle: Buffer, callback: (err: Error | undefined, stats: Stats) => void): void;
1855
1856 /**
1857 * (Client-only)
1858 * Sets the attributes defined in `attributes` for the resource associated with `handle`.
1859 */
1860 fsetstat(handle: Buffer, attributes: InputAttributes, callback: Callback): void;
1861
1862 /**
1863 * (Client-only)
1864 * Sets the access time and modified time for the resource associated with `handle`.
1865 */
1866 futimes(handle: Buffer, atime: number | Date, mtime: number | Date, callback: Callback): void;
1867
1868 /**
1869 * (Client-only)
1870 * Sets the owner for the resource associated with `handle`.
1871 */
1872 fchown(handle: Buffer, uid: number, gid: number, callback: Callback): void;
1873
1874 /**
1875 * (Client-only)
1876 * Sets the mode for the resource associated with `handle`.
1877 */
1878 fchmod(handle: Buffer, mode: number | string, callback: Callback): void;
1879
1880 /**
1881 * (Client-only)
1882 * Opens a directory `path`.
1883 */
1884 opendir(path: string, callback: (err: Error | undefined, handle: Buffer) => void): void;
1885
1886 /**
1887 * (Client-only)
1888 * Retrieves a directory listing.
1889 */
1890 readdir(location: string | Buffer, callback: (err: Error | undefined, list: FileEntryWithStats[]) => void): void;
1891
1892 /**
1893 * (Client-only)
1894 * Removes the file/symlink at `path`.
1895 */
1896 unlink(path: string, callback: Callback): void;
1897
1898 /**
1899 * (Client-only)
1900 * Renames/moves `srcPath` to `destPath`.
1901 */
1902 rename(srcPath: string, destPath: string, callback: Callback): void;
1903
1904 /**
1905 * (Client-only)
1906 * Creates a new directory `path`.
1907 */
1908 mkdir(path: string, attributes: InputAttributes, callback: Callback): void;
1909
1910 /**
1911 * (Client-only)
1912 * Creates a new directory `path`.
1913 */
1914 mkdir(path: string, callback: Callback): void;
1915
1916 /**
1917 * (Client-only)
1918 * Removes the directory at `path`.
1919 */
1920 rmdir(path: string, callback: Callback): void;
1921
1922 /**
1923 * (Client-only)
1924 * Retrieves attributes for `path`.
1925 */
1926 stat(path: string, callback: (err: Error | undefined, stats: Stats) => void): void;
1927
1928 /**
1929 * (Client-only)
1930 * `path` exists.
1931 */
1932 exists(path: string, callback: (hasError: boolean) => void): void;
1933
1934 /**
1935 * (Client-only)
1936 * Retrieves attributes for `path`. If `path` is a symlink, the link itself is stat'ed
1937 * instead of the resource it refers to.
1938 */
1939 lstat(path: string, callback: (err: Error | undefined, stats: Stats) => void): void;
1940
1941 /**
1942 * (Client-only)
1943 * Sets the attributes defined in `attributes` for `path`.
1944 */
1945 setstat(path: string, attributes: InputAttributes, callback: Callback): void;
1946
1947 /**
1948 * (Client-only)
1949 * Sets the access time and modified time for `path`.
1950 */
1951 utimes(path: string, atime: number | Date, mtime: number | Date, callback: Callback): void;
1952
1953 /**
1954 * (Client-only)
1955 * Sets the owner for `path`.
1956 */
1957 chown(path: string, uid: number, gid: number, callback: Callback): void;
1958
1959 /**
1960 * (Client-only)
1961 * Sets the mode for `path`.
1962 */
1963 chmod(path: string, mode: number | string, callback: Callback): void;
1964
1965 /**
1966 * (Client-only)
1967 * Retrieves the target for a symlink at `path`.
1968 */
1969 readlink(path: string, callback: (err: Error | undefined, target: string) => void): void;
1970
1971 /**
1972 * (Client-only)
1973 * Creates a symlink at `linkPath` to `targetPath`.
1974 */
1975 symlink(targetPath: string, linkPath: string, callback: Callback): void;
1976
1977 /**
1978 * (Client-only)
1979 * Resolves `path` to an absolute path.
1980 */
1981 realpath(path: string, callback: (err: Error | undefined, absPath: string) => void): void;
1982
1983 /**
1984 * (Client-only, OpenSSH extension)
1985 * Performs POSIX rename(3) from `srcPath` to `destPath`.
1986 */
1987 ext_openssh_rename(srcPath: string, destPath: string, callback: Callback): void;
1988
1989 /**
1990 * (Client-only, OpenSSH extension)
1991 * Performs POSIX statvfs(2) on `path`.
1992 */
1993 ext_openssh_statvfs(path: string, callback: (err: Error | undefined, fsInfo: any) => void): void;
1994
1995 /**
1996 * (Client-only, OpenSSH extension)
1997 * Performs POSIX fstatvfs(2) on open handle `handle`.
1998 */
1999 ext_openssh_fstatvfs(handle: Buffer, callback: (err: Error | undefined, fsInfo: any) => void): void;
2000
2001 /**
2002 * (Client-only, OpenSSH extension)
2003 * Performs POSIX link(2) to create a hard link to `targetPath` at `linkPath`.
2004 */
2005 ext_openssh_hardlink(targetPath: string, linkPath: string, callback: Callback): void;
2006
2007 /**
2008 * (Client-only, OpenSSH extension)
2009 * Performs POSIX fsync(3) on the open handle `handle`.
2010 */
2011 ext_openssh_fsync(handle: Buffer, callback: (err: Error | undefined, fsInfo: any) => void): void;
2012
2013 /**
2014 * (Client-only, OpenSSH extension)
2015 * Similar to setstat(), but instead sets attributes on symlinks.
2016 */
2017 ext_openssh_lsetstat(path: string, attrs: InputAttributes, callback: Callback): void;
2018 ext_openssh_lsetstat(path: string, callback: Callback): void;
2019
2020 /**
2021 * (Client-only, OpenSSH extension)
2022 * Similar to realpath(), but supports tilde-expansion, i.e. "~", "~/..." and "~user/...". These paths are expanded using shell-like rules.
2023 */
2024 ext_openssh_expandPath(path: string, callback: (err: Error | undefined, absPath: string) => void): void;
2025
2026 /**
2027 * (Client-only)
2028 * Performs a remote file copy. If length is 0, then the server will read from srcHandle until EOF is reached.
2029 */
2030 ext_copy_data(
2031 handle: Buffer,
2032 srcOffset: number,
2033 len: number,
2034 dstHandle: Buffer,
2035 dstOffset: number,
2036 callback: Callback,
2037 ): void;
2038
2039 /**
2040 * Emitted after initial protocol version check has passed
2041 */
2042 on(event: "ready", listener: () => void): this;
2043 on(event: "OPEN", listener: (reqId: number, filename: string, flags: number, attrs: Attributes) => void): this;
2044 on(event: "READ", listener: (reqId: number, handle: Buffer, offset: number, len: number) => void): this;
2045 on(event: "WRITE", listener: (reqId: number, handle: Buffer, offset: number, data: Buffer) => void): this;
2046 on(event: "FSTAT", listener: (reqId: number, handle: Buffer) => void): this;
2047 on(event: "FSETSTAT", listener: (reqId: number, handle: Buffer, attrs: Attributes) => void): this;
2048 on(event: "CLOSE", listener: (reqId: number, handle: Buffer) => void): this;
2049 on(event: "OPENDIR", listener: (reqId: number, path: string) => void): this;
2050 on(event: "READDIR", listener: (reqId: number, handle: Buffer) => void): this;
2051 on(event: "LSTAT", listener: (reqId: number, path: string) => void): this;
2052 on(event: "STAT", listener: (reqId: number, path: string) => void): this;
2053 on(event: "REMOVE", listener: (reqId: number, path: string) => void): this;
2054 on(event: "RMDIR", listener: (reqId: number, path: string) => void): this;
2055 on(event: "REALPATH", listener: (reqId: number, path: string) => void): this;
2056 on(event: "READLINK", listener: (reqId: number, path: string) => void): this;
2057 on(event: "SETSTAT", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2058 on(event: "MKDIR", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2059 on(event: "RENAME", listener: (reqId: number, oldPath: string, newPath: string) => void): this;
2060 on(event: "SYMLINK", listener: (reqId: number, targetPath: string, linkPath: string) => void): this;
2061 on(event: "EXTENDED", listener: (reqId: number, extName: string, extData: Buffer) => void): this;
2062 on(event: string | symbol, listener: Function): this;
2063
2064 /**
2065 * Emitted after initial protocol version check has passed
2066 */
2067 once(event: "ready", listener: () => void): this;
2068 once(event: "OPEN", listener: (reqId: number, filename: string, flags: number, attrs: Attributes) => void): this;
2069 once(event: "READ", listener: (reqId: number, handle: Buffer, offset: number, len: number) => void): this;
2070 once(event: "WRITE", listener: (reqId: number, handle: Buffer, offset: number, data: Buffer) => void): this;
2071 once(event: "FSTAT", listener: (reqId: number, handle: Buffer) => void): this;
2072 once(event: "FSETSTAT", listener: (reqId: number, handle: Buffer, attrs: Attributes) => void): this;
2073 once(event: "CLOSE", listener: (reqId: number, handle: Buffer) => void): this;
2074 once(event: "OPENDIR", listener: (reqId: number, path: string) => void): this;
2075 once(event: "READDIR", listener: (reqId: number, handle: Buffer) => void): this;
2076 once(event: "LSTAT", listener: (reqId: number, path: string) => void): this;
2077 once(event: "STAT", listener: (reqId: number, path: string) => void): this;
2078 once(event: "REMOVE", listener: (reqId: number, path: string) => void): this;
2079 once(event: "RMDIR", listener: (reqId: number, path: string) => void): this;
2080 once(event: "REALPATH", listener: (reqId: number, path: string) => void): this;
2081 once(event: "READLINK", listener: (reqId: number, path: string) => void): this;
2082 once(event: "SETSTAT", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2083 once(event: "MKDIR", listener: (reqId: number, path: string, attrs: Attributes) => void): this;
2084 once(event: "RENAME", listener: (reqId: number, oldPath: string, newPath: string) => void): this;
2085 once(event: "SYMLINK", listener: (reqId: number, targetPath: string, linkPath: string) => void): this;
2086 once(event: "EXTENDED", listener: (reqId: number, extName: string, extData: Buffer) => void): this;
2087 once(event: string | symbol, listener: Function): this;
2088
2089 /**
2090 * Sends a status response for the request identified by id.
2091 */
2092 status(reqId: number, code: number, message?: string): void;
2093
2094 /**
2095 * Sends a handle response for the request identified by id.
2096 * handle must be less than 256 bytes and is an opaque value that could merely contain the value of a
2097 * backing file descriptor or some other unique, custom value.
2098 */
2099 handle(reqId: number, handle: Buffer): void;
2100
2101 /**
2102 * Sends a data response for the request identified by id. data can be a Buffer or string.
2103 * If data is a string, encoding is the encoding of data.
2104 */
2105 data(reqId: number, data: Buffer | string, encoding?: BufferEncoding): void;
2106
2107 /**
2108 * Sends a name response for the request identified by id.
2109 */
2110 name(reqId: number, names: FileEntry[]): void;
2111
2112 /**
2113 * Sends an attrs response for the request identified by id.
2114 */
2115 attrs(reqId: number, attrs: Attributes): void;
2116
2117 /**
2118 * Closes the channel.
2119 */
2120 end(): void;
2121
2122 /**
2123 * Closes the channel.
2124 */
2125 destroy(): void;
2126}
2127
2128export interface PublicKeyEntry {
2129 pubKey:
2130 | ParsedKey
2131 | {
2132 pubKey: ParsedKey | Buffer | string;
2133 comment?: string;
2134 };
2135}
2136
2137export type KnownPublicKeys<T extends string | Buffer | ParsedKey = string | Buffer | ParsedKey> = Array<
2138 | T
2139 | PublicKeyEntry
2140>;
2141
2142export type PrivateKeys = Array<Buffer | ParsedKey | EncryptedPrivateKey | string>;
2143
2144export type Callback = (err?: Error | null) => void;
2145
2146export type ErrorCallback = (err: Error) => void;
2147
2148export type IdentityCallback<T extends string | Buffer | ParsedKey = string | Buffer | ParsedKey> = (
2149 err?: Error | null,
2150 keys?: KnownPublicKeys<T>,
2151) => void;
2152
2153export type SignCallback = (err?: Error | null, signature?: Buffer) => void;
2154
2155export type GetStreamCallback = (err?: Error | null, stream?: Duplex) => void;
2156
2157/**
2158 * Interface representing an inbound agent request. This is defined as an
2159 * "opaque type" in the ssh2 documentation, and should only be used
2160 * for correlation, not introspected.
2161 */
2162export interface AgentInboundRequest {
2163 __opaque_type: never;
2164}
2165
2166export interface SigningRequestOptions {
2167 hash?: "sha1" | "sha256" | "sha512";
2168}
2169
2170export class AgentProtocol extends Duplex {
2171 /**
2172 * Creates and returns a new AgentProtocol instance. `isClient` determines
2173 * whether the instance operates in client or server mode.
2174 */
2175 constructor(isClient: boolean);
2176
2177 /**
2178 * (Server mode only)
2179 * Replies to the given `request` with a failure response.
2180 */
2181 failureReply(request: AgentInboundRequest): void;
2182
2183 /**
2184 * (Client mode only)
2185 * Requests a list of public keys from the agent. `callback` is passed
2186 * `(err, keys)` where `keys` is a possible array of public keys for
2187 * authentication.
2188 */
2189 getIdentities(callback: (err: Error | undefined, publicKeys?: ParsedKey[]) => void): void;
2190
2191 /**
2192 * (Server mode only)
2193 * Responds to a identities list `request` with the given array of keys in `keys`.
2194 */
2195 getIdentitiesReply(request: AgentInboundRequest, keys: ParsedKey[]): void;
2196
2197 /**
2198 * (Client mode only)
2199 * Signs the datawith the given public key, and calls back with its signature.
2200 */
2201 sign(
2202 pubKey: ParsedKey | Buffer | string,
2203 data: Buffer,
2204 options?: SigningRequestOptions,
2205 callback?: SignCallback,
2206 ): boolean;
2207 sign(pubKey: ParsedKey | Buffer | string, data: Buffer, callback?: SignCallback): boolean;
2208
2209 /**
2210 * (Server mode only)
2211 * Responds to a sign `request` with the given signature in `signature`.
2212 */
2213 signReply(request: AgentInboundRequest, signature: Buffer): void;
2214
2215 /**
2216 * (Server mode only)
2217 * The client has requested a list of public keys stored in the agent.
2218 * Use `failureReply()` or `getIdentitiesReply()` to reply appropriately.
2219 */
2220 on(event: "identities", listener: (req: AgentInboundRequest) => void): this;
2221
2222 /**
2223 * (Server mode only)
2224 * The client has requested `data` to be signed using the key identified
2225 * by `pubKey`. Use `failureReply()` or `signReply()` to reply appropriately.
2226 */
2227 on(
2228 event: "sign",
2229 listener: (req: AgentInboundRequest, pubKey: ParsedKey, data: Buffer, options: SigningRequestOptions) => void,
2230 ): this;
2231
2232 on(event: string | symbol, listener: Function): this;
2233
2234 /**
2235 * (Server mode only)
2236 * The client has requested a list of public keys stored in the agent.
2237 * Use `failureReply()` or `getIdentitiesReply()` to reply appropriately.
2238 */
2239 once(event: "identities", listener: (req: AgentInboundRequest) => void): this;
2240
2241 /**
2242 * (Server mode only)
2243 * The client has requested `data` to be signed using the key identified
2244 * by `pubKey`. Use `failureReply()` or `signReply()` to reply appropriately.
2245 */
2246 once(
2247 event: "sign",
2248 listener: (req: AgentInboundRequest, pubKey: ParsedKey, data: Buffer, options: SigningRequestOptions) => void,
2249 ): this;
2250
2251 once(event: string | symbol, listener: Function): this;
2252}
2253
2254/**
2255 * Creates and returns a new agent instance using the same logic as the
2256 * `Client`'s `agent` configuration option: if the platform is Windows and
2257 * it's the value "pageant", it creates a `PageantAgent`, otherwise if it's not
2258 * a path to a Windows pipe it creates a `CygwinAgent`. In all other cases,
2259 * it creates an `OpenSSHAgent`.
2260 */
2261export function createAgent(socketPath: string | "pageant"): BaseAgent;
2262
2263export abstract class BaseAgent<TPublicKey extends string | Buffer | ParsedKey = string | Buffer | ParsedKey> {
2264 /**
2265 * Retrieves user identities, where `keys` is a possible array of public
2266 * keys for authentication.
2267 */
2268 abstract getIdentities(cb: IdentityCallback<TPublicKey>): void;
2269
2270 /**
2271 * Signs the datawith the given public key, and calls back with its signature.
2272 * Note that, in the current implementation, "options" is always an empty object.
2273 */
2274 abstract sign(pubKey: TPublicKey, data: Buffer, options: SigningRequestOptions, cb?: SignCallback): void;
2275 abstract sign(pubKey: TPublicKey, data: Buffer, cb: SignCallback): void;
2276
2277 /**
2278 * Optional method that may be implemented to support agent forwarding. Callback
2279 * should be invoked with a Duplex stream to be used to communicate with your agent/
2280 * You will probably want to utilize `AgentProtocol` as agent forwarding is an
2281 * OpenSSH feature, so the `stream` needs to be able to
2282 * transmit/receive OpenSSH agent protocol packets.
2283 */
2284 getStream?(cb: GetStreamCallback): void;
2285}
2286
2287/**
2288 * Communicates with an OpenSSH agent listening on the UNIX socket at `socketPath`.
2289 */
2290export class OpenSSHAgent extends BaseAgent<ParsedKey> {
2291 constructor(socketPath: string);
2292
2293 /** @inheritdoc */
2294 getIdentities(cb: IdentityCallback<ParsedKey>): void;
2295
2296 /** @inheritdoc */
2297 sign(
2298 pubKey: ParsedKey | Buffer | string,
2299 data: Buffer,
2300 options?: SigningRequestOptions,
2301 cb?: SignCallback,
2302 ): boolean;
2303 sign(pubKey: ParsedKey | Buffer | string, data: Buffer, cb?: SignCallback): boolean;
2304
2305 /** @inheritdoc */
2306 getStream(cb: GetStreamCallback): void;
2307}
2308
2309/**
2310 * Communicates with an agent listening at `socketPath` in a Cygwin environment.
2311 */
2312export class CygwinAgent extends OpenSSHAgent {}
2313
2314/**
2315 * Creates a new agent instance for communicating with a running Pageant agent process.
2316 */
2317export class PageantAgent extends OpenSSHAgent {}
2318
2319export interface NegotiatedAlgorithms {
2320 kex: KexAlgorithm;
2321 serverHostKey: ServerHostKeyAlgorithm;
2322 cs: {
2323 cipher: CipherAlgorithm;
2324 mac: MacAlgorithm | "";
2325 compress: CompressionAlgorithm;
2326 lang: string;
2327 };
2328 sc: {
2329 cipher: CipherAlgorithm;
2330 mac: MacAlgorithm | "";
2331 compress: CompressionAlgorithm;
2332 lang: string;
2333 };
2334}
2335
2336export type VerifyCallback = (valid: boolean) => void;
2337
2338export interface ReadStreamOptions extends ReadableOptions {
2339 flags?: OpenMode;
2340 mode?: number;
2341 start?: number;
2342 end?: number;
2343 autoClose?: boolean;
2344 handle?: Buffer;
2345}
2346
2347export interface WriteStreamOptions extends WritableOptions {
2348 flags?: OpenMode;
2349 mode?: number;
2350 start?: number;
2351 autoClose?: boolean;
2352 handle?: Buffer;
2353 encoding?: BufferEncoding;
2354}
2355
2356export interface ReadStream extends Readable {
2357 pending: boolean;
2358 open(): void;
2359 close(cb: Callback): void;
2360 on(eventName: "ready", listener: () => void): this;
2361 on(eventName: "open", listener: (handle: Buffer) => void): this;
2362 on(event: string | symbol, listener: Function): this;
2363 once(eventName: "ready", listener: () => void): this;
2364 once(eventName: "open", listener: (handle: Buffer) => void): this;
2365 once(event: string | symbol, listener: Function): this;
2366}
2367
2368export interface WriteStream extends Writable {
2369 pending: boolean;
2370 open(): void;
2371 destroy(): this;
2372 close(cb: Callback): void;
2373 on(eventName: "ready", listener: () => void): this;
2374 on(eventName: "open", listener: (handle: Buffer) => void): this;
2375 on(event: string | symbol, listener: Function): this;
2376 once(eventName: "ready", listener: () => void): this;
2377 once(eventName: "open", listener: (handle: Buffer) => void): this;
2378 once(event: string | symbol, listener: Function): this;
2379}
2380
2381export type ClientCallback = (err: Error | undefined, channel: ClientChannel) => void;
2382
2383export type ServerCallback = (err: Error | undefined, channel: ServerChannel) => void;
2384
2385export type ClientForwardCallback = (err: Error | undefined, port: number) => void;
2386
2387export type ClientSFTPCallback = (err: Error | undefined, sftp: SFTPWrapper) => void;
2388
2389export type ChangePasswordCallback = (newPassword: string) => void;
2390
2391export type KeyboardInteractiveCallback = (answers: string[]) => void;
2392
2393export interface UNIXConnectionDetails {
2394 socketPath: string;
2395}
2396
2397export interface HTTPAgentOptions extends AgentOptions {
2398 srcIP?: string;
2399}
2400
2401export class HTTPAgent extends BaseHTTPAgent {
2402 constructor(connectCfg: ConnectConfig, agentOptions: HTTPAgentOptions);
2403}
2404
2405export class HTTPSAgent extends BaseHTTPSAgent {
2406 constructor(connectCfg: ConnectConfig, agentOptions: HTTPAgentOptions);
2407}