"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var ssh_exports = {}; __export(ssh_exports, { connectSsh: () => connectSsh }); module.exports = __toCommonJS(ssh_exports); var import_ssh2 = require("ssh2"); var import_logger = require("../lib/logger"); const log = (0, import_logger.createLogger)("SSH"); async function connectSsh(host, privateKey, maxWaitMs = 3e5) { const start = Date.now(); while (Date.now() - start < maxWaitMs) { try { const conn = await tryConnect(host, privateKey, 1e4); let aborted = false; return { get aborted() { return aborted; }, abort() { aborted = true; try { conn.end(); } catch { } }, async exec(command) { if (aborted) throw new Error("SSH session aborted"); return execOnConn(conn, command); }, close() { try { conn.end(); } catch { } } }; } catch (e) { if (Date.now() - start > maxWaitMs) throw e; log.debug({ host, error: e.message }, "SSH connect retry"); await sleep(5e3); } } throw new Error(`Could not SSH into ${host} within timeout`); } function tryConnect(host, privateKey, timeoutMs) { return new Promise((resolve, reject) => { const conn = new import_ssh2.Client(); const timer = setTimeout(() => { conn.end(); reject(new Error(`SSH connection to ${host} timed out`)); }, timeoutMs); conn.on("ready", () => { clearTimeout(timer); resolve(conn); }); conn.on("error", (e) => { clearTimeout(timer); reject(e); }); conn.connect({ host, port: 22, username: "ubuntu", privateKey, readyTimeout: timeoutMs, algorithms: { serverHostKey: ["ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521"] } }); }); } function execOnConn(conn, command) { return new Promise((resolve, reject) => { conn.exec(command, (err, stream) => { if (err) return reject(err); let stdout = ""; let stderr = ""; stream.on("data", (d) => { stdout += d.toString(); }); stream.stderr.on("data", (d) => { stderr += d.toString(); }); stream.on("close", (code) => { resolve({ stdout, stderr, code: code ?? 0 }); }); }); }); } function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { connectSsh }); //# sourceMappingURL=ssh.js.map