ssh-client-wrapper 3.4.3 → 3.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -204,6 +204,23 @@ Checks if a connection to the remote host can be established.
204
204
 
205
205
  * Returns: `Promise<boolean>` - Resolves with `true` on success.
206
206
 
207
+ ### Connection failures
208
+
209
+ If the login can not be done, the promise is rejected with an `Error` as soon as `ssh` gives up. `err.code` tells the cause, and `err.output` has what `ssh` said (the last 4096 characters). `host`, `user` and `port` tell which login failed.
210
+
211
+ | `err.code` | cause |
212
+ |---|---|
213
+ | `AUTH_FAILED` | the login is refused (`message` is `Permission denied`) |
214
+ | `CONNECTION_REFUSED` | nothing listens on the port |
215
+ | `HOST_UNREACHABLE` | no route to the host, or the network is unreachable |
216
+ | `HOST_NOT_FOUND` | the host name can not be resolved |
217
+ | `CONNECT_TIMEOUT` | the connection timed out (see `ConnectTimeout`) |
218
+ | `HOSTKEY_FAILED` | the host key verification failed |
219
+ | `BAD_PORT` | invalid port number |
220
+ | `CONTROL_SOCKET_FAILED` | the socket of the master connection can not be created |
221
+ | `TIMEEXPIRE` | `ssh` did not finish within `timeout` |
222
+ | `SSH_FAILED` | any other failure; `message` is the last line which `ssh` said |
223
+
207
224
  ### Wrong password
208
225
 
209
226
  If the login is refused, the promise is rejected with an `Error` whose `message` is `Permission denied` and whose `code` is `AUTH_FAILED`. `host`, `user` and `port` tell which login failed.
@@ -0,0 +1,87 @@
1
+ import { stripTerminalSequences } from "./util.js";
2
+
3
+ const MAX_OUTPUT = 4096;
4
+ const FAIL_PREFIX = "SCWFAIL";
5
+
6
+ //messages of ssh after which there is nothing to wait for. The first match wins.
7
+ const knownFailures = [
8
+ { re: /Permission denied \(/, code: "AUTH_FAILED", message: "Permission denied", fatal: true },
9
+ { re: /Could not resolve hostname/, code: "HOST_NOT_FOUND", message: "Could not resolve hostname", fatal: true },
10
+ { re: /Bad port/, code: "BAD_PORT", message: "Bad port", fatal: true },
11
+ { re: /(?:Operation|Connection) timed out/, code: "CONNECT_TIMEOUT", message: "Operation timed out", fatal: true },
12
+ { re: /muxserver_listen: link mux listener .* Bad file descriptor/, code: "CONTROL_SOCKET_FAILED", message: "Control socket creation failed", fatal: true },
13
+ { re: /ssh: connect to host .*: Connection refused/, code: "CONNECTION_REFUSED" },
14
+ { re: /ssh: connect to host .*: (?:No route to host|Network is unreachable)/, code: "HOST_UNREACHABLE" },
15
+ { re: /Host key verification failed/, code: "HOSTKEY_FAILED", message: "Host key verification failed" }
16
+ ];
17
+
18
+ /**
19
+ * check if the output of ssh tells that the connection can not be made any more
20
+ * @param {string} output - output of ssh
21
+ * @returns {boolean} - true if ssh has failed
22
+ */
23
+ export const isFatalOutput = (output)=>{
24
+ return knownFailures.some((e)=>{
25
+ return e.fatal && e.re.test(output);
26
+ });
27
+ };
28
+
29
+ /**
30
+ * make an error object which tells why ssh failed
31
+ * @param {string} output - output of ssh
32
+ * @param {object} hostInfo - hostinfo object
33
+ * @returns {Error} - error with code, host, user, port and output (the tail of the output of ssh)
34
+ */
35
+ export const makeSshError = (output, hostInfo)=>{
36
+ const lines = stripTerminalSequences(output).split(/[\r\n]+/)
37
+ .map((e)=>{
38
+ return e.trim();
39
+ })
40
+ .filter(Boolean);
41
+ const text = lines.join("\n");
42
+ const known = knownFailures.find((e)=>{
43
+ return e.re.test(text);
44
+ });
45
+ const matched = known && lines.find((e)=>{
46
+ return known.re.test(e);
47
+ });
48
+ const err = new Error(known?.message ?? matched ?? lines.at(-1) ?? "ssh connection failed");
49
+ err.code = known?.code ?? "SSH_FAILED";
50
+ err.host = hostInfo.host;
51
+ err.user = hostInfo.user;
52
+ err.port = hostInfo.port;
53
+ err.output = output.slice(-MAX_OUTPUT);
54
+ return err;
55
+ };
56
+
57
+ /**
58
+ * make the command line which is typed into the shell of the master pty
59
+ * the shell prints the mark only if ssh fails. The mark is written with "" in it,
60
+ * so that the line which the terminal echoes back does not contain the mark itself.
61
+ * "||" is understood by sh, bash, zsh, fish and csh.
62
+ * @param {string} cmd - ssh command
63
+ * @param {Array} args - arguments of ssh
64
+ * @param {string} words - string which the remote host echoes if the login succeeds
65
+ * @param {string} failId - string which makes the mark unique. It must differ from words
66
+ * @returns {object} - { line: command line, failMark: string which is printed if ssh fails }
67
+ */
68
+ export const makeMasterCommand = (cmd, args, words, failId)=>{
69
+ return {
70
+ line: `${cmd} ${args.join(" ")} echo ${words} || echo ${FAIL_PREFIX}""-${failId}\n`,
71
+ failMark: `${FAIL_PREFIX}-${failId}`
72
+ };
73
+ };
74
+
75
+ /**
76
+ * cut the output of ssh out of the output of the master pty
77
+ * @param {string} output - output of the master pty
78
+ * @param {string} failMark - failMark returned by makeMasterCommand
79
+ * @returns {string} - output without the echoed command line, the mark and what follows it
80
+ */
81
+ export const extractSshOutput = (output, failMark)=>{
82
+ const end = output.indexOf(failMark);
83
+ const head = end < 0 ? output : output.slice(0, end);
84
+ const typed = failMark.replace(FAIL_PREFIX, `${FAIL_PREFIX}""`);
85
+ const start = head.lastIndexOf(typed);
86
+ return start < 0 ? head : head.slice(start + typed.length).replace(/^\r*\n/, "");
87
+ };
package/lib/sshExec.js CHANGED
@@ -4,6 +4,7 @@ import Debug from "debug";
4
4
  import { sendPty, sshCmd, getSshOption, getNoStdinOption, isControlMasterEnabled, sanityCheck, watchDogTimer, rePwPrompt, rePhPrompt } from "./util.js";
5
5
  import { fork, createMasterPty, sshLoginCallback } from "./fork.js";
6
6
  import { shouldUseAgent, ensureAgentForHost } from "./agent.js";
7
+ import { makeSshError, makeMasterCommand, extractSshOutput, isFatalOutput } from "./sshError.js";
7
8
 
8
9
  const debug = Debug("sshClientWrapper:debug:sshExec");
9
10
  const debugVerbose = Debug("sshClientWrapper:verbose:sshExec");
@@ -168,26 +169,25 @@ async function verifyConnection(hostInfo, timeout) {
168
169
  try {
169
170
  await fork(hostInfo, sshCmd, args, timeout, cb);
170
171
  } catch (e) {
171
- const err = new Error(e.message);
172
- err.host = hostInfo.host;
173
- err.user = hostInfo.user;
174
- err.port = hostInfo.port;
175
- err.output = output;
176
172
  if (e.code === "TIMEEXPIRE") {
173
+ const err = makeSshError(output, hostInfo);
177
174
  err.message = `can not connect within ${timeout} sec`;
178
- } else if (/Permission denied \(/.test(output)) {
179
- err.message = "Permission denied";
180
- err.code = "AUTH_FAILED";
181
- } else if (/Could not resolve hostname/.test(output)) {
182
- err.message = "Could not resolve hostname";
183
- } else if (/Bad port/.test(output)) {
184
- err.message = "Bad port";
185
- } else if (/Operation|Connection timed out/.test(output)) {
186
- err.message = "Operation timed out";
187
- } else {
175
+ err.code = "TIMEEXPIRE";
176
+ throw err;
177
+ }
178
+ //an error which is neither the exit of ssh nor made from its output (e.g. thrown by a password callback) is passed as it is
179
+ if (e.rt === undefined && !e.retryable) {
188
180
  e.output = output;
189
181
  throw e;
190
182
  }
183
+ const err = makeSshError(output, hostInfo);
184
+ if (e.retryable) {
185
+ //fork() has stopped ssh by itself (kex_exchange_identification)
186
+ err.message = e.message;
187
+ err.retryable = true;
188
+ } else {
189
+ err.rt = e.rt;
190
+ }
191
191
  throw err;
192
192
  }
193
193
  debug(`connected to ${hostInfo.host}`);
@@ -233,19 +233,21 @@ export async function connect(hostInfo, timeout = 60) {
233
233
  debug(`create master ssh session to ${hostInfo.host}`);
234
234
  const words = crypto.randomUUID();
235
235
  const re = new RegExp(`^${words}`);
236
+ const { line, failMark } = makeMasterCommand(sshCmd, getSshOption(hostInfo), words, crypto.randomUUID());
236
237
 
237
238
  let ac = null;
238
- let output = null;
239
+ let output = "";
239
240
  const p = new Promise((resolve, reject)=>{
241
+ const failure = ()=>{
242
+ return makeSshError(extractSshOutput(output, failMark), hostInfo);
243
+ };
240
244
  ac = watchDogTimer(timeout, "make connection", ()=>{
241
245
  sendPty(hostInfo.masterPty, "\n", debugSendMasterPty, 137);
242
246
  sendPty(hostInfo.masterPty, "exit\n", debugSendMasterPty, 138);
243
247
 
244
- const err = new Error(`can not connect within ${timeout} sec`);
245
- err.host = hostInfo.host;
246
- err.user = hostInfo.user;
247
- err.port = hostInfo.port;
248
- err.output = output;
248
+ const err = failure();
249
+ err.message = `can not connect within ${timeout} sec`;
250
+ err.code = "TIMEEXPIRE";
249
251
  reject(err);
250
252
  });
251
253
 
@@ -255,28 +257,22 @@ export async function connect(hostInfo, timeout = 60) {
255
257
  //safeguard
256
258
  return;
257
259
  }
258
- output = data.toString();
259
- debugVerbose(output);
260
+ const chunk = data.toString();
261
+ output = `${output}${chunk}`.slice(-65536);
262
+ debugVerbose(chunk);
260
263
 
261
- if (re.test(output)) {
264
+ if (re.test(chunk)) {
262
265
  debug("test done. call exit on remotehost");
263
266
  done = true;
264
267
  resolve();
265
- } else if (/Permission denied \(/.test(output)) {
266
- const err = new Error("Permission denied");
267
- err.code = "AUTH_FAILED";
268
- err.host = hostInfo.host;
269
- err.user = hostInfo.user;
270
- err.port = hostInfo.port;
271
- reject(err);
272
- } else if (/Could not resolve hostname/.test(output)) {
273
- reject(new Error("Could not resolve hostname"));
274
- } else if (/Bad port/.test(output)) {
275
- reject(new Error("Bad port"));
276
- } else if (/Operation|Connection timed out/.test(output)) {
277
- reject(new Error("Operation timed out"));
278
- } else if (/muxserver_listen: link mux listener .* Bad file descriptor/.test(output)) {
279
- reject(new Error("Control socket creation failed"));
268
+ } else if (isFatalOutput(chunk)) {
269
+ reject(failure());
270
+ } else if (output.includes(failMark)) {
271
+ done = true;
272
+ //let the handler below reject first if it knows better (e.g. the host key has been changed)
273
+ setImmediate(()=>{
274
+ reject(failure());
275
+ });
280
276
  }
281
277
  });
282
278
  hostInfo.masterPty.onData((data)=>{
@@ -306,12 +302,8 @@ export async function connect(hostInfo, timeout = 60) {
306
302
  });
307
303
  });
308
304
 
309
- const args = getSshOption(hostInfo);
310
- args.push(`echo ${words}`);
311
- const cmd = `${sshCmd} ${args.join(" ")}\n`;
312
- sendPty(hostInfo.masterPty, cmd, debugSendMasterPty, 190);
313
-
314
305
  try {
306
+ await sendPty(hostInfo.masterPty, line, debugSendMasterPty, 190);
315
307
  await p;
316
308
  debug(`connected to ${hostInfo.host}`);
317
309
  } catch (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh-client-wrapper",
3
- "version": "3.4.3",
3
+ "version": "3.4.4",
4
4
  "description": "wrapper library for open ssh client and rsync",
5
5
  "keywords": [
6
6
  "ssh",