@krovacloud/sdk 0.5.0 → 0.5.2

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/dist/ssh.js ADDED
@@ -0,0 +1,335 @@
1
+ import { createHash } from "node:crypto";
2
+ import ssh2 from "ssh2";
3
+ // src/ssh.ts
4
+ /**
5
+ * `@krovacloud/sdk/ssh` — run commands and move files on a Cube over its own SSH.
6
+ *
7
+ * Node only. Krova has no exec or files API: the commands and the bytes go
8
+ * straight from your process to the Cube's sshd, authenticated with a private
9
+ * key you supply. The Krova API is used for one thing, the Cube's address and
10
+ * its pinned host keys (`cubes.ssh()`), so the connection is verified strictly:
11
+ * a host key that does not match is refused, and there is no way to switch the
12
+ * check off.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { KrovaClient } from "@krovacloud/sdk";
17
+ * import { connectCube } from "@krovacloud/sdk/ssh";
18
+ *
19
+ * const krova = new KrovaClient({ apiKey: process.env.KROVA_API_KEY! });
20
+ * const shell = await connectCube(krova, spaceId, cubeId, { privateKey });
21
+ * try {
22
+ * const { stdout, exitCode } = await shell.run(["ls", "-la", "/srv"]);
23
+ * } finally {
24
+ * await shell.close();
25
+ * }
26
+ * ```
27
+ */
28
+ const { Client } = ssh2;
29
+ /** Base class for every error this module throws on its own. */
30
+ var SshError = class extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "SshError";
34
+ }
35
+ };
36
+ /** The Cube presented a host key that is not one of the pinned keys (or there were no keys to pin). */
37
+ var HostKeyMismatchError = class extends SshError {
38
+ /** `SHA256:...` fingerprint of the key the server presented, when it presented one. */
39
+ fingerprint;
40
+ constructor(message, fingerprint) {
41
+ super(message);
42
+ this.name = "HostKeyMismatchError";
43
+ this.fingerprint = fingerprint;
44
+ }
45
+ };
46
+ /** `run()` hit its `timeoutMs`; the channel was closed. */
47
+ var RunTimeoutError = class extends SshError {
48
+ timeoutMs;
49
+ constructor(timeoutMs) {
50
+ super(`Command timed out after ${timeoutMs} ms.`);
51
+ this.name = "RunTimeoutError";
52
+ this.timeoutMs = timeoutMs;
53
+ }
54
+ };
55
+ /**
56
+ * POSIX single-quote escape: the result is one shell word that expands to
57
+ * exactly `arg`. Nothing inside is interpreted (`$()`, backticks, `*`, newlines).
58
+ * A NUL byte cannot exist in a command line and is refused.
59
+ */
60
+ function shellQuote(arg) {
61
+ if (arg.includes("\0")) throw new TypeError("Shell arguments cannot contain a NUL byte.");
62
+ return `'${arg.replaceAll("'", `'\\''`)}'`;
63
+ }
64
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
65
+ /** Throws a `TypeError` unless `name` is a valid shell variable name. */
66
+ function assertEnvName(name) {
67
+ if (!ENV_NAME.test(name)) throw new TypeError(`Invalid environment variable name: ${JSON.stringify(name)}.`);
68
+ }
69
+ /**
70
+ * Build the remote command line. A string runs as written; a string array has
71
+ * each element quoted. `cwd` and `env` become `cd ... && export ... && ...`, with a
72
+ * string command wrapped in a group so both apply to all of it.
73
+ */
74
+ function buildCommand(command, opts = {}) {
75
+ const body = typeof command === "string" ? command : command.map((part) => shellQuote(part)).join(" ");
76
+ if (body.trim() === "") throw new TypeError("Command is empty.");
77
+ const pre = [];
78
+ if (opts.cwd !== void 0) {
79
+ if (opts.cwd === "") throw new TypeError("cwd cannot be an empty string.");
80
+ pre.push(`cd -- ${shellQuote(opts.cwd)}`);
81
+ }
82
+ const entries = Object.entries(opts.env ?? {});
83
+ if (entries.length > 0) {
84
+ const assigns = entries.map(([name, value]) => {
85
+ assertEnvName(name);
86
+ return `${name}=${shellQuote(value)}`;
87
+ });
88
+ pre.push(`export ${assigns.join(" ")}`);
89
+ }
90
+ if (pre.length === 0) return body;
91
+ const wrapped = typeof command === "string" ? `{\n${body}\n}` : body;
92
+ return `${pre.join(" && ")} && ${wrapped}`;
93
+ }
94
+ /**
95
+ * True when `presented` (the raw SSH host-key blob ssh2 hands the verifier)
96
+ * equals the decoded `key` of one of `pinned`, byte for byte. Fails closed: an
97
+ * empty list, an empty blob or an undecodable entry never matches.
98
+ */
99
+ function hostKeyMatches(presented, pinned) {
100
+ if (presented.length === 0) return false;
101
+ const blob = Buffer.from(presented);
102
+ for (const entry of pinned) {
103
+ if (typeof entry.key !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(entry.key)) continue;
104
+ const decoded = Buffer.from(entry.key, "base64");
105
+ if (decoded.length > 0 && decoded.equals(blob)) return true;
106
+ }
107
+ return false;
108
+ }
109
+ /** `SHA256:<base64>` fingerprint of a host-key blob, as `ssh-keygen -l` prints it. */
110
+ function hostKeyFingerprint(presented) {
111
+ return `SHA256:${createHash("sha256").update(presented).digest("base64").replace(/=+$/, "")}`;
112
+ }
113
+ function redact(message, secrets) {
114
+ let out = message;
115
+ for (const secret of secrets) if (secret) out = out.split(secret).join("[redacted]");
116
+ return out;
117
+ }
118
+ function toBuffer(data) {
119
+ return typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
120
+ }
121
+ /** An open SSH connection to one Cube. */
122
+ var CubeShell = class {
123
+ /** Address the connection went to. */
124
+ host;
125
+ port;
126
+ user;
127
+ files;
128
+ #client;
129
+ #closed = false;
130
+ /** @internal Use {@link connectCube} or {@link connectSsh}. */
131
+ constructor(client, host, port, user) {
132
+ this.#client = client;
133
+ this.host = host;
134
+ this.port = port;
135
+ this.user = user;
136
+ client.on("error", () => {});
137
+ client.on("close", () => {
138
+ this.#closed = true;
139
+ });
140
+ this.files = new CubeFiles(() => this.#sftp());
141
+ }
142
+ #assertOpen() {
143
+ if (this.#closed) throw new SshError("The SSH connection is closed.");
144
+ }
145
+ #sftpPromise;
146
+ #sftp() {
147
+ this.#assertOpen();
148
+ this.#sftpPromise ??= new Promise((resolve, reject) => {
149
+ this.#client.sftp((err, sftp) => {
150
+ if (err) {
151
+ this.#sftpPromise = void 0;
152
+ reject(new SshError(`Could not open SFTP: ${err.message}`));
153
+ return;
154
+ }
155
+ sftp.on("close", () => {
156
+ this.#sftpPromise = void 0;
157
+ });
158
+ resolve(sftp);
159
+ });
160
+ });
161
+ return this.#sftpPromise;
162
+ }
163
+ /** Run a command. A string runs as written by the remote shell; a string array is quoted argument by argument. */
164
+ run(command, options = {}) {
165
+ const { timeoutMs } = options;
166
+ if (timeoutMs !== void 0 && !(timeoutMs > 0)) return Promise.reject(/* @__PURE__ */ new TypeError("timeoutMs must be a positive number."));
167
+ let line;
168
+ try {
169
+ this.#assertOpen();
170
+ line = buildCommand(command, {
171
+ cwd: options.cwd,
172
+ env: options.env
173
+ });
174
+ } catch (err) {
175
+ return Promise.reject(err);
176
+ }
177
+ return new Promise((resolve, reject) => {
178
+ this.#client.exec(line, (err, stream) => {
179
+ if (err) {
180
+ reject(new SshError(`Could not start the command: ${err.message}`));
181
+ return;
182
+ }
183
+ const out = [];
184
+ const errOut = [];
185
+ let timedOut = false;
186
+ let timer;
187
+ if (timeoutMs !== void 0) timer = setTimeout(() => {
188
+ timedOut = true;
189
+ reject(new RunTimeoutError(timeoutMs));
190
+ stream.close();
191
+ stream.destroy();
192
+ }, timeoutMs);
193
+ stream.on("data", (chunk) => out.push(chunk));
194
+ stream.stderr.on("data", (chunk) => errOut.push(chunk));
195
+ stream.on("error", (e) => {
196
+ if (timedOut) return;
197
+ if (timer) clearTimeout(timer);
198
+ reject(new SshError(`The command channel failed: ${e.message}`));
199
+ });
200
+ stream.on("close", (code, signal) => {
201
+ if (timer) clearTimeout(timer);
202
+ if (timedOut) return;
203
+ const result = {
204
+ stdout: Buffer.concat(out).toString("utf8"),
205
+ stderr: Buffer.concat(errOut).toString("utf8"),
206
+ exitCode: typeof code === "number" ? code : null
207
+ };
208
+ if (typeof signal === "string" && signal !== "") result.signal = signal;
209
+ resolve(result);
210
+ });
211
+ if (options.stdin !== void 0) stream.end(toBuffer(options.stdin));
212
+ else stream.end();
213
+ });
214
+ });
215
+ }
216
+ /** Close the connection. Safe to call twice. */
217
+ close() {
218
+ if (this.#closed) return Promise.resolve();
219
+ return new Promise((resolve) => {
220
+ this.#client.once("close", () => resolve());
221
+ this.#client.end();
222
+ });
223
+ }
224
+ };
225
+ /** File transfer over the connection's SFTP subsystem. Remote paths are literal: `~` and `$VAR` are not expanded. */
226
+ var CubeFiles = class {
227
+ #sftp;
228
+ /** @internal */
229
+ constructor(sftp) {
230
+ this.#sftp = sftp;
231
+ }
232
+ /** Create or overwrite `remotePath` with `data` (strings are UTF-8). */
233
+ async write(remotePath, data) {
234
+ const sftp = await this.#sftp();
235
+ await new Promise((resolve, reject) => {
236
+ const ws = sftp.createWriteStream(remotePath);
237
+ ws.once("error", reject);
238
+ ws.once("close", () => resolve());
239
+ ws.end(toBuffer(data));
240
+ });
241
+ }
242
+ /** Read the whole of `remotePath` into memory. */
243
+ async read(remotePath) {
244
+ const sftp = await this.#sftp();
245
+ return new Promise((resolve, reject) => {
246
+ const chunks = [];
247
+ const rs = sftp.createReadStream(remotePath);
248
+ rs.on("data", (chunk) => chunks.push(chunk));
249
+ rs.once("error", reject);
250
+ rs.once("close", () => resolve(new Uint8Array(Buffer.concat(chunks))));
251
+ });
252
+ }
253
+ /** Copy a local file to `remotePath`. */
254
+ async upload(localPath, remotePath) {
255
+ const sftp = await this.#sftp();
256
+ await new Promise((resolve, reject) => {
257
+ sftp.fastPut(localPath, remotePath, (err) => err ? reject(err) : resolve());
258
+ });
259
+ }
260
+ /** Copy `remotePath` to a local file. */
261
+ async download(remotePath, localPath) {
262
+ const sftp = await this.#sftp();
263
+ await new Promise((resolve, reject) => {
264
+ sftp.fastGet(remotePath, localPath, (err) => err ? reject(err) : resolve());
265
+ });
266
+ }
267
+ };
268
+ /**
269
+ * Connect to a server over SSH with a private key, accepting only a host key
270
+ * from `hostKeys`. Most callers want {@link connectCube}.
271
+ */
272
+ function connectSsh(options) {
273
+ const { host, username, hostKeys, passphrase } = options;
274
+ const port = options.port ?? 22;
275
+ if (hostKeys.length === 0) return Promise.reject(new HostKeyMismatchError(`No host keys to verify ${host} against; refusing to connect without pinned host keys.`));
276
+ return new Promise((resolve, reject) => {
277
+ const client = new Client();
278
+ let mismatch;
279
+ let settled = false;
280
+ const fail = (err) => {
281
+ if (settled) return;
282
+ settled = true;
283
+ client.end();
284
+ reject(mismatch ?? err);
285
+ };
286
+ client.once("ready", () => {
287
+ if (settled) return;
288
+ settled = true;
289
+ resolve(new CubeShell(client, host, port, username));
290
+ });
291
+ client.once("error", (err) => {
292
+ fail(new SshError(`SSH connection failed: ${redact(err.message, [passphrase])}`));
293
+ });
294
+ client.once("close", () => fail(new SshError("The SSH connection closed before it was ready.")));
295
+ try {
296
+ client.connect({
297
+ host,
298
+ port,
299
+ username,
300
+ privateKey: toBuffer(options.privateKey),
301
+ ...passphrase !== void 0 ? { passphrase } : {},
302
+ readyTimeout: options.readyTimeoutMs ?? 2e4,
303
+ hostVerifier: (presented) => {
304
+ if (hostKeyMatches(presented, hostKeys)) return true;
305
+ mismatch = new HostKeyMismatchError(`Host key mismatch for ${host}:${port}; the server presented ${hostKeyFingerprint(presented)}, which is not one of the pinned keys.`, hostKeyFingerprint(presented));
306
+ return false;
307
+ }
308
+ });
309
+ } catch (err) {
310
+ fail(new SshError(`SSH connection failed: ${redact(err instanceof Error ? err.message : String(err), [passphrase])}`));
311
+ }
312
+ });
313
+ }
314
+ /**
315
+ * Open an SSH connection to a Cube. The address and host keys come from
316
+ * `krova.cubes.ssh(spaceId, cubeId)`; the connection is refused unless the Cube
317
+ * presents one of those keys (or one of `options.hostKeys`, which replaces them).
318
+ */
319
+ async function connectCube(krova, spaceId, cubeId, options) {
320
+ const info = await krova.cubes.ssh(spaceId, cubeId);
321
+ if (info.host === null || info.host === "") throw new SshError("This Cube has no SSH address yet. Wait for it to finish starting.");
322
+ const connect = {
323
+ host: info.host,
324
+ port: info.port,
325
+ username: info.user,
326
+ privateKey: options.privateKey,
327
+ hostKeys: options.hostKeys ?? info.hostKeys
328
+ };
329
+ if (options.passphrase !== void 0) connect.passphrase = options.passphrase;
330
+ if (options.readyTimeoutMs !== void 0) connect.readyTimeoutMs = options.readyTimeoutMs;
331
+ return connectSsh(connect);
332
+ }
333
+ export { CubeFiles, CubeShell, HostKeyMismatchError, RunTimeoutError, SshError, assertEnvName, buildCommand, connectCube, connectSsh, hostKeyFingerprint, hostKeyMatches, shellQuote };
334
+
335
+ //# sourceMappingURL=ssh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssh.js","names":[],"sources":["../src/ssh.ts"],"sourcesContent":["/**\n * `@krovacloud/sdk/ssh` — run commands and move files on a Cube over its own SSH.\n *\n * Node only. Krova has no exec or files API: the commands and the bytes go\n * straight from your process to the Cube's sshd, authenticated with a private\n * key you supply. The Krova API is used for one thing, the Cube's address and\n * its pinned host keys (`cubes.ssh()`), so the connection is verified strictly:\n * a host key that does not match is refused, and there is no way to switch the\n * check off.\n *\n * @example\n * ```ts\n * import { KrovaClient } from \"@krovacloud/sdk\";\n * import { connectCube } from \"@krovacloud/sdk/ssh\";\n *\n * const krova = new KrovaClient({ apiKey: process.env.KROVA_API_KEY! });\n * const shell = await connectCube(krova, spaceId, cubeId, { privateKey });\n * try {\n * const { stdout, exitCode } = await shell.run([\"ls\", \"-la\", \"/srv\"]);\n * } finally {\n * await shell.close();\n * }\n * ```\n */\nimport { createHash } from \"node:crypto\";\nimport ssh2, { type SFTPWrapper, type Client as SshClient } from \"ssh2\";\nimport type { CubeSshInfo } from \"./client.js\";\n\n// ssh2 is CommonJS; Node's named-export detection only finds some of its exports, so take them off the default.\nconst { Client } = ssh2;\n\n/** A host public key as the Krova API returns it: `key` is the base64 blob of the OpenSSH `.pub` line. */\nexport interface HostKey {\n type: string;\n key: string;\n}\n\n/** Base class for every error this module throws on its own. */\nexport class SshError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SshError\";\n }\n}\n\n/** The Cube presented a host key that is not one of the pinned keys (or there were no keys to pin). */\nexport class HostKeyMismatchError extends SshError {\n /** `SHA256:...` fingerprint of the key the server presented, when it presented one. */\n readonly fingerprint: string | undefined;\n constructor(message: string, fingerprint?: string) {\n super(message);\n this.name = \"HostKeyMismatchError\";\n this.fingerprint = fingerprint;\n }\n}\n\n/** `run()` hit its `timeoutMs`; the channel was closed. */\nexport class RunTimeoutError extends SshError {\n readonly timeoutMs: number;\n constructor(timeoutMs: number) {\n super(`Command timed out after ${timeoutMs} ms.`);\n this.name = \"RunTimeoutError\";\n this.timeoutMs = timeoutMs;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Quoting\n// ---------------------------------------------------------------------------\n\n/**\n * POSIX single-quote escape: the result is one shell word that expands to\n * exactly `arg`. Nothing inside is interpreted (`$()`, backticks, `*`, newlines).\n * A NUL byte cannot exist in a command line and is refused.\n */\nexport function shellQuote(arg: string): string {\n if (arg.includes(\"\\0\")) {\n throw new TypeError(\"Shell arguments cannot contain a NUL byte.\");\n }\n return `'${arg.replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Throws a `TypeError` unless `name` is a valid shell variable name. */\nexport function assertEnvName(name: string): void {\n if (!ENV_NAME.test(name)) {\n throw new TypeError(`Invalid environment variable name: ${JSON.stringify(name)}.`);\n }\n}\n\n/**\n * Build the remote command line. A string runs as written; a string array has\n * each element quoted. `cwd` and `env` become `cd ... && export ... && ...`, with a\n * string command wrapped in a group so both apply to all of it.\n */\nexport function buildCommand(\n command: string | readonly string[],\n opts: { cwd?: string | undefined; env?: Readonly<Record<string, string>> | undefined } = {},\n): string {\n const body =\n typeof command === \"string\" ? command : command.map((part) => shellQuote(part)).join(\" \");\n if (body.trim() === \"\") throw new TypeError(\"Command is empty.\");\n const pre: string[] = [];\n if (opts.cwd !== undefined) {\n if (opts.cwd === \"\") throw new TypeError(\"cwd cannot be an empty string.\");\n // `--` so a cwd that starts with `-` is a path, never an option to `cd`.\n pre.push(`cd -- ${shellQuote(opts.cwd)}`);\n }\n const entries = Object.entries(opts.env ?? {});\n if (entries.length > 0) {\n const assigns = entries.map(([name, value]) => {\n assertEnvName(name);\n return `${name}=${shellQuote(value)}`;\n });\n pre.push(`export ${assigns.join(\" \")}`);\n }\n if (pre.length === 0) return body;\n const wrapped = typeof command === \"string\" ? `{\\n${body}\\n}` : body;\n return `${pre.join(\" && \")} && ${wrapped}`;\n}\n\n// ---------------------------------------------------------------------------\n// Host keys\n// ---------------------------------------------------------------------------\n\n/**\n * True when `presented` (the raw SSH host-key blob ssh2 hands the verifier)\n * equals the decoded `key` of one of `pinned`, byte for byte. Fails closed: an\n * empty list, an empty blob or an undecodable entry never matches.\n */\nexport function hostKeyMatches(presented: Uint8Array, pinned: readonly HostKey[]): boolean {\n if (presented.length === 0) return false;\n const blob = Buffer.from(presented);\n for (const entry of pinned) {\n if (typeof entry.key !== \"string\" || !/^[A-Za-z0-9+/]+={0,2}$/.test(entry.key)) continue;\n const decoded = Buffer.from(entry.key, \"base64\");\n if (decoded.length > 0 && decoded.equals(blob)) return true;\n }\n return false;\n}\n\n/** `SHA256:<base64>` fingerprint of a host-key blob, as `ssh-keygen -l` prints it. */\nexport function hostKeyFingerprint(presented: Uint8Array): string {\n return `SHA256:${createHash(\"sha256\").update(presented).digest(\"base64\").replace(/=+$/, \"\")}`;\n}\n\n// ---------------------------------------------------------------------------\n// Connection\n// ---------------------------------------------------------------------------\n\nexport interface RunOptions {\n /** Working directory on the Cube; quoted by the SDK. */\n cwd?: string;\n /** Environment variables for the command; names are validated, values quoted. */\n env?: Record<string, string>;\n /** Close the channel and reject with {@link RunTimeoutError} after this many milliseconds. */\n timeoutMs?: number;\n /** Written to the command's stdin, which is then closed. Without it stdin is closed at once. */\n stdin?: string | Uint8Array;\n}\n\nexport interface RunResult {\n stdout: string;\n stderr: string;\n /** `null` when the command was killed by a signal or the channel closed without a status. */\n exitCode: number | null;\n /** Signal name (for example `TERM`) when the command was killed by one. */\n signal?: string;\n}\n\nexport interface ConnectSshOptions {\n host: string;\n port?: number;\n username: string;\n /** OpenSSH or PEM private key. Used for this connection only; the SDK never stores or logs it. */\n privateKey: string | Uint8Array;\n passphrase?: string;\n /** Host keys the server must present one of. An empty list refuses the connection. */\n hostKeys: readonly HostKey[];\n /** Handshake timeout in milliseconds. Default 20000. */\n readyTimeoutMs?: number;\n}\n\nexport interface ConnectCubeOptions {\n /** OpenSSH or PEM private key whose public half is in the Cube's `authorized_keys`. */\n privateKey: string | Uint8Array;\n /** For an encrypted `privateKey`. */\n passphrase?: string;\n /** Handshake timeout in milliseconds. Default 20000. */\n readyTimeoutMs?: number;\n /** Pin these keys instead of the ones `cubes.ssh()` returns, for callers that keep their own. */\n hostKeys?: readonly HostKey[];\n}\n\n/** The slice of `KrovaClient` that `connectCube` uses. */\nexport interface CubeSshSource {\n cubes: { ssh(spaceId: string, cubeId: string): Promise<CubeSshInfo> };\n}\n\nfunction redact(message: string, secrets: readonly (string | undefined)[]): string {\n let out = message;\n for (const secret of secrets) {\n if (secret) out = out.split(secret).join(\"[redacted]\");\n }\n return out;\n}\n\nfunction toBuffer(data: string | Uint8Array): Buffer {\n return typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data);\n}\n\n/** An open SSH connection to one Cube. */\nexport class CubeShell {\n /** Address the connection went to. */\n readonly host: string;\n readonly port: number;\n readonly user: string;\n readonly files: CubeFiles;\n\n readonly #client: SshClient;\n #closed = false;\n\n /** @internal Use {@link connectCube} or {@link connectSsh}. */\n constructor(client: SshClient, host: string, port: number, user: string) {\n this.#client = client;\n this.host = host;\n this.port = port;\n this.user = user;\n // After the handshake a dropped connection must not crash the process.\n client.on(\"error\", () => {});\n client.on(\"close\", () => {\n this.#closed = true;\n });\n this.files = new CubeFiles(() => this.#sftp());\n }\n\n #assertOpen(): void {\n if (this.#closed) throw new SshError(\"The SSH connection is closed.\");\n }\n\n #sftpPromise: Promise<SFTPWrapper> | undefined;\n\n #sftp(): Promise<SFTPWrapper> {\n this.#assertOpen();\n this.#sftpPromise ??= new Promise<SFTPWrapper>((resolve, reject) => {\n this.#client.sftp((err, sftp) => {\n if (err) {\n this.#sftpPromise = undefined;\n reject(new SshError(`Could not open SFTP: ${err.message}`));\n return;\n }\n sftp.on(\"close\", () => {\n this.#sftpPromise = undefined;\n });\n resolve(sftp);\n });\n });\n return this.#sftpPromise;\n }\n\n /** Run a command. A string runs as written by the remote shell; a string array is quoted argument by argument. */\n run(command: string | readonly string[], options: RunOptions = {}): Promise<RunResult> {\n const { timeoutMs } = options;\n if (timeoutMs !== undefined && !(timeoutMs > 0)) {\n return Promise.reject(new TypeError(\"timeoutMs must be a positive number.\"));\n }\n let line: string;\n try {\n this.#assertOpen();\n line = buildCommand(command, { cwd: options.cwd, env: options.env });\n } catch (err) {\n return Promise.reject(err);\n }\n return new Promise<RunResult>((resolve, reject) => {\n this.#client.exec(line, (err, stream) => {\n if (err) {\n reject(new SshError(`Could not start the command: ${err.message}`));\n return;\n }\n const out: Buffer[] = [];\n const errOut: Buffer[] = [];\n let timedOut = false;\n let timer: NodeJS.Timeout | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n timedOut = true;\n // Reject now: a server that ignores the channel close must not leave this pending.\n reject(new RunTimeoutError(timeoutMs as number));\n stream.close();\n stream.destroy();\n }, timeoutMs);\n }\n stream.on(\"data\", (chunk: Buffer) => out.push(chunk));\n stream.stderr.on(\"data\", (chunk: Buffer) => errOut.push(chunk));\n stream.on(\"error\", (e: Error) => {\n if (timedOut) return;\n if (timer) clearTimeout(timer);\n reject(new SshError(`The command channel failed: ${e.message}`));\n });\n stream.on(\"close\", (code?: number | null, signal?: string | null) => {\n if (timer) clearTimeout(timer);\n if (timedOut) return;\n const result: RunResult = {\n stdout: Buffer.concat(out).toString(\"utf8\"),\n stderr: Buffer.concat(errOut).toString(\"utf8\"),\n exitCode: typeof code === \"number\" ? code : null,\n };\n if (typeof signal === \"string\" && signal !== \"\") result.signal = signal;\n resolve(result);\n });\n if (options.stdin !== undefined) stream.end(toBuffer(options.stdin));\n else stream.end();\n });\n });\n }\n\n /** Close the connection. Safe to call twice. */\n close(): Promise<void> {\n if (this.#closed) return Promise.resolve();\n return new Promise<void>((resolve) => {\n this.#client.once(\"close\", () => resolve());\n this.#client.end();\n });\n }\n}\n\n/** File transfer over the connection's SFTP subsystem. Remote paths are literal: `~` and `$VAR` are not expanded. */\nexport class CubeFiles {\n readonly #sftp: () => Promise<SFTPWrapper>;\n\n /** @internal */\n constructor(sftp: () => Promise<SFTPWrapper>) {\n this.#sftp = sftp;\n }\n\n /** Create or overwrite `remotePath` with `data` (strings are UTF-8). */\n async write(remotePath: string, data: string | Uint8Array): Promise<void> {\n const sftp = await this.#sftp();\n await new Promise<void>((resolve, reject) => {\n const ws = sftp.createWriteStream(remotePath);\n ws.once(\"error\", reject);\n ws.once(\"close\", () => resolve());\n ws.end(toBuffer(data));\n });\n }\n\n /** Read the whole of `remotePath` into memory. */\n async read(remotePath: string): Promise<Uint8Array> {\n const sftp = await this.#sftp();\n return new Promise<Uint8Array>((resolve, reject) => {\n const chunks: Buffer[] = [];\n const rs = sftp.createReadStream(remotePath);\n rs.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n rs.once(\"error\", reject);\n rs.once(\"close\", () => resolve(new Uint8Array(Buffer.concat(chunks))));\n });\n }\n\n /** Copy a local file to `remotePath`. */\n async upload(localPath: string, remotePath: string): Promise<void> {\n const sftp = await this.#sftp();\n await new Promise<void>((resolve, reject) => {\n sftp.fastPut(localPath, remotePath, (err) => (err ? reject(err) : resolve()));\n });\n }\n\n /** Copy `remotePath` to a local file. */\n async download(remotePath: string, localPath: string): Promise<void> {\n const sftp = await this.#sftp();\n await new Promise<void>((resolve, reject) => {\n sftp.fastGet(remotePath, localPath, (err) => (err ? reject(err) : resolve()));\n });\n }\n}\n\n/**\n * Connect to a server over SSH with a private key, accepting only a host key\n * from `hostKeys`. Most callers want {@link connectCube}.\n */\nexport function connectSsh(options: ConnectSshOptions): Promise<CubeShell> {\n const { host, username, hostKeys, passphrase } = options;\n const port = options.port ?? 22;\n if (hostKeys.length === 0) {\n return Promise.reject(\n new HostKeyMismatchError(\n `No host keys to verify ${host} against; refusing to connect without pinned host keys.`,\n ),\n );\n }\n return new Promise<CubeShell>((resolve, reject) => {\n const client = new Client();\n let mismatch: HostKeyMismatchError | undefined;\n let settled = false;\n const fail = (err: Error) => {\n if (settled) return;\n settled = true;\n client.end();\n reject(mismatch ?? err);\n };\n client.once(\"ready\", () => {\n if (settled) return;\n settled = true;\n resolve(new CubeShell(client, host, port, username));\n });\n client.once(\"error\", (err: Error) => {\n fail(new SshError(`SSH connection failed: ${redact(err.message, [passphrase])}`));\n });\n client.once(\"close\", () =>\n fail(new SshError(\"The SSH connection closed before it was ready.\")),\n );\n try {\n client.connect({\n host,\n port,\n username,\n privateKey: toBuffer(options.privateKey),\n ...(passphrase !== undefined ? { passphrase } : {}),\n readyTimeout: options.readyTimeoutMs ?? 20_000,\n hostVerifier: (presented: Buffer) => {\n if (hostKeyMatches(presented, hostKeys)) return true;\n mismatch = new HostKeyMismatchError(\n `Host key mismatch for ${host}:${port}; the server presented ${hostKeyFingerprint(presented)}, which is not one of the pinned keys.`,\n hostKeyFingerprint(presented),\n );\n return false;\n },\n });\n } catch (err) {\n fail(\n new SshError(\n `SSH connection failed: ${redact(err instanceof Error ? err.message : String(err), [passphrase])}`,\n ),\n );\n }\n });\n}\n\n/**\n * Open an SSH connection to a Cube. The address and host keys come from\n * `krova.cubes.ssh(spaceId, cubeId)`; the connection is refused unless the Cube\n * presents one of those keys (or one of `options.hostKeys`, which replaces them).\n */\nexport async function connectCube(\n krova: CubeSshSource,\n spaceId: string,\n cubeId: string,\n options: ConnectCubeOptions,\n): Promise<CubeShell> {\n const info = await krova.cubes.ssh(spaceId, cubeId);\n if (info.host === null || info.host === \"\") {\n throw new SshError(\"This Cube has no SSH address yet. Wait for it to finish starting.\");\n }\n const connect: ConnectSshOptions = {\n host: info.host,\n port: info.port,\n username: info.user,\n privateKey: options.privateKey,\n hostKeys: options.hostKeys ?? info.hostKeys,\n };\n if (options.passphrase !== undefined) connect.passphrase = options.passphrase;\n if (options.readyTimeoutMs !== undefined) connect.readyTimeoutMs = options.readyTimeoutMs;\n return connectSsh(connect);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,EAAE,WAAW;;AASnB,IAAa,WAAb,cAA8B,MAAM;CAClC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,uBAAb,cAA0C,SAAS;;CAEjD;CACA,YAAY,SAAiB,aAAsB;EACjD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,cAAc;CACrB;AACF;;AAGA,IAAa,kBAAb,cAAqC,SAAS;CAC5C;CACA,YAAY,WAAmB;EAC7B,MAAM,2BAA2B,UAAU,KAAK;EAChD,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;;;;;;AAWA,SAAgB,WAAW,KAAqB;CAC9C,IAAI,IAAI,SAAS,IAAI,GACnB,MAAM,IAAI,UAAU,4CAA4C;CAElE,OAAO,IAAI,IAAI,WAAW,KAAK,OAAO,EAAE;AAC1C;AAEA,MAAM,WAAW;;AAGjB,SAAgB,cAAc,MAAoB;CAChD,IAAI,CAAC,SAAS,KAAK,IAAI,GACrB,MAAM,IAAI,UAAU,sCAAsC,KAAK,UAAU,IAAI,EAAE,EAAE;AAErF;;;;;;AAOA,SAAgB,aACd,SACA,OAAyF,CAAC,GAClF;CACR,MAAM,OACJ,OAAO,YAAY,WAAW,UAAU,QAAQ,KAAK,SAAS,WAAW,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;CAC1F,IAAI,KAAK,KAAK,MAAM,IAAI,MAAM,IAAI,UAAU,mBAAmB;CAC/D,MAAM,MAAgB,CAAC;CACvB,IAAI,KAAK,QAAQ,KAAA,GAAW;EAC1B,IAAI,KAAK,QAAQ,IAAI,MAAM,IAAI,UAAU,gCAAgC;EAEzE,IAAI,KAAK,SAAS,WAAW,KAAK,GAAG,GAAG;CAC1C;CACA,MA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,eAAe,KAAA,GAAW,QAAQ,aAAa,QAAQ;CACnE,IAAI,QAAQ,mBAAmB,KAAA,GAAW,QAAQ,iBAAiB,QAAQ;CAC3E,OAAO,WAAW,OAAO;AAC3B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krovacloud/sdk",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Official TypeScript SDK for Krova Cloud — a typed client for provisioning and managing Cubes (Firecracker microVMs) with dedicated resources.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -46,6 +46,17 @@
46
46
  "default": "./dist/index.cjs"
47
47
  }
48
48
  },
49
+ "./ssh": {
50
+ "types": "./dist/ssh.d.ts",
51
+ "import": {
52
+ "types": "./dist/ssh.d.ts",
53
+ "default": "./dist/ssh.js"
54
+ },
55
+ "require": {
56
+ "types": "./dist/ssh.d.cts",
57
+ "default": "./dist/ssh.cjs"
58
+ }
59
+ },
49
60
  "./package.json": "./package.json"
50
61
  },
51
62
  "files": [
@@ -58,10 +69,12 @@
58
69
  "node": ">=22"
59
70
  },
60
71
  "dependencies": {
61
- "openapi-fetch": "^0.17.0"
72
+ "openapi-fetch": "^0.17.0",
73
+ "ssh2": "^1.17.0"
62
74
  },
63
75
  "devDependencies": {
64
76
  "@types/node": "^26.6.6",
77
+ "@types/ssh2": "^1.15.6",
65
78
  "openapi-typescript": "^7.13.0",
66
79
  "tsdown": "0.23.7",
67
80
  "tsx": "^4.23.15",