index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. "use strict";
  2. var _path = _interopRequireDefault(require("path"));
  3. var _ssh = _interopRequireDefault(require("ssh2"));
  4. var _pMap = _interopRequireDefault(require("p-map"));
  5. var _assert = _interopRequireDefault(require("assert"));
  6. var _sbScandir = _interopRequireDefault(require("sb-scandir"));
  7. var _shellEscape = _interopRequireDefault(require("shell-escape"));
  8. var Helpers = _interopRequireWildcard(require("./helpers"));
  9. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  12. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  13. class SSH {
  14. constructor() {
  15. this.connection = null;
  16. }
  17. connect(givenConfig) {
  18. const connection = new _ssh.default();
  19. this.connection = connection;
  20. return new Promise(function (resolve) {
  21. resolve(Helpers.normalizeConfig(givenConfig));
  22. }).then(config => new Promise((resolve, reject) => {
  23. connection.on('error', reject);
  24. if (config.onKeyboardInteractive) {
  25. connection.on('keyboard-interactive', config.onKeyboardInteractive);
  26. }
  27. connection.on('ready', () => {
  28. connection.removeListener('error', reject);
  29. resolve(this);
  30. });
  31. connection.on('end', () => {
  32. if (this.connection === connection) {
  33. this.connection = null;
  34. }
  35. });
  36. connection.on('close', () => {
  37. if (this.connection === connection) {
  38. this.connection = null;
  39. }
  40. const error = new Error('No response from server'); // $FlowIgnore: Custom attribute
  41. error.code = 'ETIMEDOUT';
  42. reject(error);
  43. });
  44. connection.connect(config);
  45. }));
  46. }
  47. requestShell() {
  48. var _this = this;
  49. return _asyncToGenerator(function* () {
  50. const connection = _this.connection;
  51. (0, _assert.default)(connection, 'Not connected to server');
  52. return new Promise(function (resolve, reject) {
  53. connection.shell(Helpers.generateCallback(resolve, reject));
  54. });
  55. })();
  56. }
  57. requestSFTP() {
  58. var _this2 = this;
  59. return _asyncToGenerator(function* () {
  60. const connection = _this2.connection;
  61. (0, _assert.default)(connection, 'Not connected to server');
  62. return new Promise(function (resolve, reject) {
  63. connection.sftp(Helpers.generateCallback(resolve, reject));
  64. });
  65. })();
  66. }
  67. mkdir(path, type = 'sftp', givenSftp = null) {
  68. var _this3 = this;
  69. return _asyncToGenerator(function* () {
  70. (0, _assert.default)(_this3.connection, 'Not connected to server');
  71. (0, _assert.default)(type === 'exec' || type === 'sftp', 'Type should either be sftp or exec');
  72. if (type === 'exec') {
  73. const output = yield _this3.exec('mkdir', ['-p', path]);
  74. if (output.stdout) {
  75. throw new Error(output.stdout);
  76. }
  77. } else {
  78. (0, _assert.default)(!givenSftp || typeof givenSftp === 'object', 'sftp must be an object');
  79. const sftp = givenSftp || (yield _this3.requestSFTP());
  80. const makeSftpDirectory = retry => Helpers.mkdirSftp(path, sftp).catch(error => {
  81. if (retry && error && (error.message === 'No such file' || error.code === 'ENOENT')) {
  82. return _this3.mkdir(_path.default.dirname(path), 'sftp', sftp).then(() => makeSftpDirectory(false));
  83. }
  84. throw error;
  85. });
  86. try {
  87. yield makeSftpDirectory(true);
  88. } finally {
  89. if (!givenSftp) {
  90. sftp.end();
  91. }
  92. }
  93. }
  94. })();
  95. }
  96. exec(command, parameters = [], options = {}) {
  97. var _this4 = this;
  98. return _asyncToGenerator(function* () {
  99. (0, _assert.default)(_this4.connection, 'Not connected to server');
  100. (0, _assert.default)(typeof options === 'object' && options, 'options must be an Object');
  101. (0, _assert.default)(!options.cwd || typeof options.cwd === 'string', 'options.cwd must be a string');
  102. (0, _assert.default)(!options.stdin || typeof options.stdin === 'string', 'options.stdin must be a string');
  103. (0, _assert.default)(!options.stream || ['stdout', 'stderr', 'both'].indexOf(options.stream) !== -1, 'options.stream must be among "stdout", "stderr" and "both"');
  104. (0, _assert.default)(!options.options || typeof options.options === 'object', 'options.options must be an object');
  105. const output = yield _this4.execCommand([command].concat((0, _shellEscape.default)(parameters)).join(' '), options);
  106. if (!options.stream || options.stream === 'stdout') {
  107. if (output.stderr) {
  108. throw new Error(output.stderr);
  109. }
  110. return output.stdout;
  111. }
  112. if (options.stream === 'stderr') {
  113. return output.stderr;
  114. }
  115. return output;
  116. })();
  117. }
  118. execCommand(givenCommand, options = {}) {
  119. var _this5 = this;
  120. return _asyncToGenerator(function* () {
  121. let command = givenCommand;
  122. const connection = _this5.connection;
  123. (0, _assert.default)(connection, 'Not connected to server');
  124. (0, _assert.default)(typeof options === 'object' && options, 'options must be an Object');
  125. (0, _assert.default)(!options.cwd || typeof options.cwd === 'string', 'options.cwd must be a string');
  126. (0, _assert.default)(!options.stdin || typeof options.stdin === 'string', 'options.stdin must be a string');
  127. (0, _assert.default)(!options.options || typeof options.options === 'object', 'options.options must be an object');
  128. if (options.cwd) {
  129. // NOTE: Output piping cd command to hide directory non-existent errors
  130. command = `cd ${(0, _shellEscape.default)([options.cwd])} 1> /dev/null 2> /dev/null; ${command}`;
  131. }
  132. const output = {
  133. stdout: [],
  134. stderr: []
  135. };
  136. return new Promise(function (resolve, reject) {
  137. connection.exec(command, options.options || {}, Helpers.generateCallback(function (stream) {
  138. stream.on('data', function (chunk) {
  139. if (options.onStdout) options.onStdout(chunk);
  140. output.stdout.push(chunk);
  141. });
  142. stream.stderr.on('data', function (chunk) {
  143. if (options.onStderr) options.onStderr(chunk);
  144. output.stderr.push(chunk);
  145. });
  146. if (options.stdin) {
  147. stream.write(options.stdin);
  148. stream.end();
  149. }
  150. stream.on('close', function (code, signal) {
  151. resolve({
  152. code,
  153. signal,
  154. stdout: output.stdout.join('').trim(),
  155. stderr: output.stderr.join('').trim()
  156. });
  157. });
  158. }, reject));
  159. });
  160. })();
  161. }
  162. getFile(localFile, remoteFile, givenSftp = null, givenOpts = null) {
  163. var _this6 = this;
  164. return _asyncToGenerator(function* () {
  165. (0, _assert.default)(_this6.connection, 'Not connected to server');
  166. (0, _assert.default)(typeof localFile === 'string' && localFile, 'localFile must be a string');
  167. (0, _assert.default)(typeof remoteFile === 'string' && remoteFile, 'remoteFile must be a string');
  168. (0, _assert.default)(!givenSftp || typeof givenSftp === 'object', 'sftp must be an object');
  169. (0, _assert.default)(!givenOpts || typeof givenOpts === 'object', 'opts must be an object');
  170. const opts = givenOpts || {};
  171. const sftp = givenSftp || (yield _this6.requestSFTP());
  172. try {
  173. yield new Promise(function (resolve, reject) {
  174. sftp.fastGet(remoteFile, localFile, opts, Helpers.generateCallback(resolve, reject));
  175. });
  176. } finally {
  177. if (!givenSftp) {
  178. sftp.end();
  179. }
  180. }
  181. })();
  182. }
  183. putFile(localFile, remoteFile, givenSftp = null, givenOpts = null) {
  184. var _this7 = this;
  185. return _asyncToGenerator(function* () {
  186. (0, _assert.default)(_this7.connection, 'Not connected to server');
  187. (0, _assert.default)(typeof localFile === 'string' && localFile, 'localFile must be a string');
  188. (0, _assert.default)(typeof remoteFile === 'string' && remoteFile, 'remoteFile must be a string');
  189. (0, _assert.default)(!givenSftp || typeof givenSftp === 'object', 'sftp must be an object');
  190. (0, _assert.default)(!givenOpts || typeof givenOpts === 'object', 'opts must be an object');
  191. (0, _assert.default)((yield Helpers.exists(localFile)), `localFile does not exist at ${localFile}`);
  192. const that = _this7;
  193. const opts = givenOpts || {};
  194. const sftp = givenSftp || (yield _this7.requestSFTP());
  195. function putFile(retry) {
  196. return new Promise(function (resolve, reject) {
  197. sftp.fastPut(localFile, remoteFile, opts, Helpers.generateCallback(resolve, function (error) {
  198. if (error.message === 'No such file' && retry) {
  199. resolve(that.mkdir(_path.default.dirname(remoteFile), 'sftp', sftp).then(() => putFile(false)));
  200. } else {
  201. reject(error);
  202. }
  203. }));
  204. });
  205. }
  206. try {
  207. yield putFile(true);
  208. } finally {
  209. if (!givenSftp) {
  210. sftp.end();
  211. }
  212. }
  213. })();
  214. }
  215. putFiles(files, givenConfig = {}) {
  216. var _this8 = this;
  217. return _asyncToGenerator(function* () {
  218. (0, _assert.default)(_this8.connection, 'Not connected to server');
  219. (0, _assert.default)(Array.isArray(files), 'files must be an array');
  220. for (let i = 0, length = files.length; i < length; ++i) {
  221. const file = files[i];
  222. (0, _assert.default)(file, 'files items must be valid objects');
  223. (0, _assert.default)(file.local && typeof file.local === 'string', `files[${i}].local must be a string`);
  224. (0, _assert.default)(file.remote && typeof file.remote === 'string', `files[${i}].remote must be a string`);
  225. }
  226. const transferred = [];
  227. const config = Helpers.normalizePutFilesOptions(givenConfig);
  228. const sftp = config.sftp || (yield _this8.requestSFTP());
  229. try {
  230. yield (0, _pMap.default)(files,
  231. /*#__PURE__*/
  232. function () {
  233. var _ref = _asyncToGenerator(function* (file) {
  234. yield _this8.putFile(file.local, file.remote, sftp, config.sftpOptions);
  235. transferred.push(file);
  236. });
  237. return function (_x) {
  238. return _ref.apply(this, arguments);
  239. };
  240. }());
  241. } catch (error) {
  242. error.transferred = transferred;
  243. throw error;
  244. } finally {
  245. if (!sftp) {
  246. sftp.end();
  247. }
  248. }
  249. })();
  250. }
  251. putDirectory(localDirectory, remoteDirectory, givenConfig = {}) {
  252. var _this9 = this;
  253. return _asyncToGenerator(function* () {
  254. (0, _assert.default)(_this9.connection, 'Not connected to server');
  255. (0, _assert.default)(typeof localDirectory === 'string' && localDirectory, 'localDirectory must be a string');
  256. (0, _assert.default)(typeof remoteDirectory === 'string' && remoteDirectory, 'remoteDirectory must be a string');
  257. (0, _assert.default)((yield Helpers.exists(localDirectory)), `localDirectory does not exist at ${localDirectory}`);
  258. (0, _assert.default)((yield Helpers.stat(localDirectory)).isDirectory(), `localDirectory is not a directory at ${localDirectory}`);
  259. (0, _assert.default)(typeof givenConfig === 'object' && givenConfig, 'config must be an object');
  260. const config = Helpers.normalizePutDirectoryOptions(givenConfig);
  261. const sftp = config.sftp || (yield _this9.requestSFTP());
  262. const scanned = yield (0, _sbScandir.default)(localDirectory, config.recursive, config.validate);
  263. const files = scanned.files.map(i => _path.default.relative(localDirectory, i));
  264. const directories = scanned.directories.map(i => _path.default.relative(localDirectory, i));
  265. let failed = false;
  266. let directoriesQueue = Promise.resolve();
  267. const directoriesCreated = new Set();
  268. const createDirectory =
  269. /*#__PURE__*/
  270. function () {
  271. var _ref2 = _asyncToGenerator(function* (path) {
  272. if (!directoriesCreated.has(path)) {
  273. directoriesCreated.add(path);
  274. directoriesQueue = directoriesQueue.then(() => _this9.mkdir(path, 'sftp', sftp));
  275. yield directoriesQueue;
  276. }
  277. });
  278. return function createDirectory(_x2) {
  279. return _ref2.apply(this, arguments);
  280. };
  281. }();
  282. try {
  283. yield (0, _pMap.default)(files,
  284. /*#__PURE__*/
  285. function () {
  286. var _ref3 = _asyncToGenerator(function* (file) {
  287. const localFile = _path.default.join(localDirectory, file);
  288. const remoteFile = _path.default.join(remoteDirectory, file).split(_path.default.sep).join('/');
  289. const remoteFileDirectory = _path.default.dirname(remoteFile);
  290. yield createDirectory(remoteFileDirectory);
  291. try {
  292. yield _this9.putFile(localFile, remoteFile, sftp, config.sftpOptions);
  293. config.tick(localFile, remoteFile, null);
  294. } catch (_) {
  295. failed = true;
  296. config.tick(localFile, remoteFile, _);
  297. }
  298. });
  299. return function (_x3) {
  300. return _ref3.apply(this, arguments);
  301. };
  302. }(), {
  303. concurrency: config.concurrency
  304. });
  305. yield (0, _pMap.default)(directories,
  306. /*#__PURE__*/
  307. function () {
  308. var _ref4 = _asyncToGenerator(function* (entry) {
  309. const remoteEntry = _path.default.join(remoteDirectory, entry).split(_path.default.sep).join('/');
  310. yield createDirectory(remoteEntry);
  311. });
  312. return function (_x4) {
  313. return _ref4.apply(this, arguments);
  314. };
  315. }(), {
  316. concurrency: config.concurrency
  317. });
  318. } finally {
  319. if (!config.sftp) {
  320. sftp.end();
  321. }
  322. }
  323. return !failed;
  324. })();
  325. }
  326. dispose() {
  327. if (this.connection) {
  328. this.connection.end();
  329. }
  330. }
  331. }
  332. module.exports = SSH;