@krovacloud/cli 0.7.0 → 0.7.1
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/CHANGELOG.md +46 -1
- package/README.md +84 -5
- package/dist/index.js +2128 -135
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,21 +1,178 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import { Command } from "commander";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
3
|
+
import { Argument, Command } from "commander";
|
|
4
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { accessSync, appendFileSync, chmodSync, constants, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { constants as constants$1, homedir } from "node:os";
|
|
8
|
+
import { delimiter, dirname, join } from "node:path";
|
|
9
|
+
import { KrovaClient, KrovaError, TerminationProtectedError, krovaErrorFrom } from "@krovacloud/sdk";
|
|
10
|
+
import { readFile } from "node:fs/promises";
|
|
11
|
+
import * as readline$1 from "node:readline/promises";
|
|
11
12
|
import * as readline from "node:readline";
|
|
13
|
+
import { connect, createServer, isIP } from "node:net";
|
|
14
|
+
import { createServer as createServer$1 } from "node:http";
|
|
12
15
|
import { verifyKrovaWebhookOrThrow } from "@krovacloud/webhook";
|
|
16
|
+
// src/lib/keychain.ts
|
|
17
|
+
const KEYCHAIN_SERVICE = "krova-cli";
|
|
18
|
+
const NO_KEYCHAIN_ENV = "KROVA_NO_KEYCHAIN";
|
|
19
|
+
const TIMEOUT_MS = 15e3;
|
|
20
|
+
/** Thrown when no keychain can be used at all (opted out, unsupported platform, tool missing). */
|
|
21
|
+
var KeychainUnavailableError = class extends Error {
|
|
22
|
+
optOut;
|
|
23
|
+
constructor(message, optOut = false) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.optOut = optOut;
|
|
26
|
+
this.name = "KeychainUnavailableError";
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
function run(cmd, args, input, detached = false) {
|
|
30
|
+
const r = spawnSync(cmd, args, {
|
|
31
|
+
encoding: "utf8",
|
|
32
|
+
input,
|
|
33
|
+
timeout: TIMEOUT_MS,
|
|
34
|
+
windowsHide: true,
|
|
35
|
+
detached
|
|
36
|
+
});
|
|
37
|
+
if (r.error) {
|
|
38
|
+
const code = r.error.code;
|
|
39
|
+
if (code === "ENOENT") throw new KeychainUnavailableError(`\`${cmd}\` was not found`);
|
|
40
|
+
if (code === "ETIMEDOUT") throw new Error(`\`${cmd}\` timed out after ${TIMEOUT_MS / 1e3}s`);
|
|
41
|
+
throw new Error(`\`${cmd}\` failed: ${r.error.message}`);
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
status: r.status,
|
|
45
|
+
stdout: r.stdout ?? "",
|
|
46
|
+
stderr: r.stderr ?? ""
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function assertSecret(secret) {
|
|
50
|
+
if (!secret || /[\r\n\0]/.test(secret)) throw new Error("the API key is empty or contains a line break");
|
|
51
|
+
}
|
|
52
|
+
function failure(cmd, r) {
|
|
53
|
+
const detail = r.stderr.trim().split("\n")[0] || `exit ${r.status}`;
|
|
54
|
+
return /* @__PURE__ */ new Error(`\`${cmd}\` failed: ${detail}`);
|
|
55
|
+
}
|
|
56
|
+
/** macOS: the `security` CLI (verified against `man security` on macOS and a live round trip).
|
|
57
|
+
*
|
|
58
|
+
* The password never goes in argv: `add-generic-password ... -w` with NO value after
|
|
59
|
+
* the last option makes `security` prompt for it ("Put at end of command to be
|
|
60
|
+
* prompted (recommended)"), and the prompt reads stdin only when the process has no
|
|
61
|
+
* controlling terminal. A normal terminal run would read /dev/tty and ignore our pipe,
|
|
62
|
+
* so the child is spawned detached (setsid, no controlling terminal) and gets
|
|
63
|
+
* "<secret>\n<secret>\n" on stdin (prompt + retype). The write is verified by a read-back
|
|
64
|
+
* in config.ts, so a platform where this misbehaves falls back to the file. */
|
|
65
|
+
function macosBackend(service = KEYCHAIN_SERVICE) {
|
|
66
|
+
return {
|
|
67
|
+
name: "macOS Keychain",
|
|
68
|
+
get(account) {
|
|
69
|
+
const r = run("security", [
|
|
70
|
+
"find-generic-password",
|
|
71
|
+
"-s",
|
|
72
|
+
service,
|
|
73
|
+
"-a",
|
|
74
|
+
account,
|
|
75
|
+
"-w"
|
|
76
|
+
]);
|
|
77
|
+
if (r.status === 44) return void 0;
|
|
78
|
+
if (r.status !== 0) throw failure("security", r);
|
|
79
|
+
return r.stdout.replace(/\n$/, "");
|
|
80
|
+
},
|
|
81
|
+
set(account, secret) {
|
|
82
|
+
assertSecret(secret);
|
|
83
|
+
const r = run("security", [
|
|
84
|
+
"add-generic-password",
|
|
85
|
+
"-U",
|
|
86
|
+
"-s",
|
|
87
|
+
service,
|
|
88
|
+
"-a",
|
|
89
|
+
account,
|
|
90
|
+
"-l",
|
|
91
|
+
`Krova CLI (${account})`,
|
|
92
|
+
"-w"
|
|
93
|
+
], `${secret}\n${secret}\n`, true);
|
|
94
|
+
if (r.status !== 0) throw failure("security", r);
|
|
95
|
+
},
|
|
96
|
+
delete(account) {
|
|
97
|
+
const r = run("security", [
|
|
98
|
+
"delete-generic-password",
|
|
99
|
+
"-s",
|
|
100
|
+
service,
|
|
101
|
+
"-a",
|
|
102
|
+
account
|
|
103
|
+
]);
|
|
104
|
+
if (r.status !== 0 && r.status !== 44) throw failure("security", r);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** Linux: `secret-tool` from libsecret. `store` reads the secret from stdin when it is not a
|
|
109
|
+
* terminal (documented in secret-tool(1): "Everything up to EOF becomes the password"), so
|
|
110
|
+
* nothing secret is in argv. Not run on this build machine (macOS); the argv shapes follow the
|
|
111
|
+
* man page synopsis. */
|
|
112
|
+
function secretToolBackend(service = KEYCHAIN_SERVICE) {
|
|
113
|
+
return {
|
|
114
|
+
name: "Secret Service (secret-tool)",
|
|
115
|
+
get(account) {
|
|
116
|
+
const r = run("secret-tool", [
|
|
117
|
+
"lookup",
|
|
118
|
+
"service",
|
|
119
|
+
service,
|
|
120
|
+
"account",
|
|
121
|
+
account
|
|
122
|
+
]);
|
|
123
|
+
if (r.status === 0) return r.stdout.replace(/\n$/, "");
|
|
124
|
+
if (r.status === 1 && !r.stdout && !r.stderr.trim()) return void 0;
|
|
125
|
+
throw failure("secret-tool", r);
|
|
126
|
+
},
|
|
127
|
+
set(account, secret) {
|
|
128
|
+
assertSecret(secret);
|
|
129
|
+
const r = run("secret-tool", [
|
|
130
|
+
"store",
|
|
131
|
+
`--label=Krova CLI (${account})`,
|
|
132
|
+
"service",
|
|
133
|
+
service,
|
|
134
|
+
"account",
|
|
135
|
+
account
|
|
136
|
+
], secret);
|
|
137
|
+
if (r.status !== 0) throw failure("secret-tool", r);
|
|
138
|
+
},
|
|
139
|
+
delete(account) {
|
|
140
|
+
const r = run("secret-tool", [
|
|
141
|
+
"clear",
|
|
142
|
+
"service",
|
|
143
|
+
service,
|
|
144
|
+
"account",
|
|
145
|
+
account
|
|
146
|
+
]);
|
|
147
|
+
if (r.status === 0) return;
|
|
148
|
+
if (this.get(account) === void 0) return;
|
|
149
|
+
throw failure("secret-tool", r);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function keychainOptedOut() {
|
|
154
|
+
const v = (process.env["KROVA_NO_KEYCHAIN"] ?? "").trim().toLowerCase();
|
|
155
|
+
return v === "1" || v === "true" || v === "yes";
|
|
156
|
+
}
|
|
157
|
+
/** The backend to use for reads (an existing keychain context must be readable even
|
|
158
|
+
* under KROVA_NO_KEYCHAIN, which only governs where new keys are WRITTEN). */
|
|
159
|
+
function readBackend() {
|
|
160
|
+
if (process.platform === "darwin") return macosBackend();
|
|
161
|
+
if (process.platform === "linux") return secretToolBackend();
|
|
162
|
+
throw new KeychainUnavailableError(`no keychain support on ${process.platform}`);
|
|
163
|
+
}
|
|
164
|
+
/** The backend to use for writes: like readBackend, but KROVA_NO_KEYCHAIN=1 forces the file. */
|
|
165
|
+
function writeBackend() {
|
|
166
|
+
if (keychainOptedOut()) throw new KeychainUnavailableError(`${NO_KEYCHAIN_ENV} is set`, true);
|
|
167
|
+
return readBackend();
|
|
168
|
+
}
|
|
13
169
|
const DEFAULT_CONTEXT_NAME = "default";
|
|
14
170
|
const ENV = {
|
|
15
171
|
apiKey: "KROVA_API_KEY",
|
|
16
172
|
spaceId: "KROVA_SPACE_ID",
|
|
17
173
|
baseUrl: "KROVA_BASE_URL",
|
|
18
|
-
context: "KROVA_CONTEXT"
|
|
174
|
+
context: "KROVA_CONTEXT",
|
|
175
|
+
npmRegistry: "KROVA_NPM_REGISTRY"
|
|
19
176
|
};
|
|
20
177
|
function configDir() {
|
|
21
178
|
const xdg = (process.env.XDG_CONFIG_HOME ?? "").trim();
|
|
@@ -59,13 +216,26 @@ function save(cfg) {
|
|
|
59
216
|
if (cfg.currentContext) clean.currentContext = cfg.currentContext;
|
|
60
217
|
if (cfg.contexts && cfg.contexts.length) clean.contexts = cfg.contexts.map((c) => {
|
|
61
218
|
const o = { name: c.name };
|
|
62
|
-
if (c.apiKey) o.apiKey = c.apiKey;
|
|
219
|
+
if (c.apiKey && c.keyStorage !== "keychain") o.apiKey = c.apiKey;
|
|
220
|
+
if (c.keyStorage) o.keyStorage = c.keyStorage;
|
|
63
221
|
if (c.spaceId) o.spaceId = c.spaceId;
|
|
64
222
|
if (c.spaceName) o.spaceName = c.spaceName;
|
|
65
223
|
if (c.baseUrl) o.baseUrl = c.baseUrl;
|
|
66
224
|
return o;
|
|
67
225
|
});
|
|
68
|
-
|
|
226
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
227
|
+
try {
|
|
228
|
+
writeFileSync(tmp, `${JSON.stringify(clean, null, 2)}\n`, {
|
|
229
|
+
mode: 384,
|
|
230
|
+
flag: "wx"
|
|
231
|
+
});
|
|
232
|
+
renameSync(tmp, path);
|
|
233
|
+
} catch (e) {
|
|
234
|
+
try {
|
|
235
|
+
unlinkSync(tmp);
|
|
236
|
+
} catch {}
|
|
237
|
+
throw e;
|
|
238
|
+
}
|
|
69
239
|
chmodSync(path, 384);
|
|
70
240
|
}
|
|
71
241
|
function find(cfg, name) {
|
|
@@ -95,6 +265,8 @@ function upsert(cfg, incoming) {
|
|
|
95
265
|
if ((incoming.baseUrl ?? "").trim()) ctx.baseUrl = incoming.baseUrl;
|
|
96
266
|
return ctx;
|
|
97
267
|
}
|
|
268
|
+
/** Drop a context from `cfg` in memory only (the caller still calls `save`). Does not touch the
|
|
269
|
+
* keychain: use `removeContext` to remove a context and its keychain item together. */
|
|
98
270
|
function remove(cfg, name) {
|
|
99
271
|
const before = (cfg.contexts ?? []).length;
|
|
100
272
|
cfg.contexts = (cfg.contexts ?? []).filter((c) => c.name !== name);
|
|
@@ -102,6 +274,26 @@ function remove(cfg, name) {
|
|
|
102
274
|
if (cfg.currentContext === name) cfg.currentContext = cfg.contexts[0]?.name ?? "";
|
|
103
275
|
return true;
|
|
104
276
|
}
|
|
277
|
+
/** Remove a context, save the config, and only then delete its keychain item, so a failed save
|
|
278
|
+
* leaves both the context and its key intact. Returns false when there is no such context. */
|
|
279
|
+
function removeContext(cfg, name, persist = () => save(cfg)) {
|
|
280
|
+
const gone = find(cfg, name);
|
|
281
|
+
if (!gone) return false;
|
|
282
|
+
const snapshot = {
|
|
283
|
+
contexts: [...cfg.contexts ?? []],
|
|
284
|
+
currentContext: cfg.currentContext
|
|
285
|
+
};
|
|
286
|
+
remove(cfg, name);
|
|
287
|
+
try {
|
|
288
|
+
persist();
|
|
289
|
+
} catch (e) {
|
|
290
|
+
cfg.contexts = snapshot.contexts;
|
|
291
|
+
cfg.currentContext = snapshot.currentContext;
|
|
292
|
+
throw e;
|
|
293
|
+
}
|
|
294
|
+
deleteContextKey(gone);
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
105
297
|
/** Resolve credentials with precedence flag > env > active context. */
|
|
106
298
|
function resolve(cfg, flags) {
|
|
107
299
|
const ctx = current(cfg, (flags.context ?? "").trim() || process.env[ENV.context]);
|
|
@@ -111,7 +303,8 @@ function resolve(cfg, flags) {
|
|
|
111
303
|
if ((ctxVal ?? "").trim()) return [ctxVal, "context"];
|
|
112
304
|
return ["", ""];
|
|
113
305
|
};
|
|
114
|
-
const
|
|
306
|
+
const overridden = Boolean((flags.apiKey ?? "").trim() || (process.env[ENV.apiKey] ?? "").trim());
|
|
307
|
+
const [apiKey, apiKeySource] = pick(flags.apiKey, process.env[ENV.apiKey], overridden || !ctx ? void 0 : contextKey(ctx));
|
|
115
308
|
const [spaceId, spaceIdSource] = pick(flags.space, process.env[ENV.spaceId], ctx?.spaceId);
|
|
116
309
|
const [baseUrlRaw] = pick(flags.baseUrl, process.env[ENV.baseUrl], ctx?.baseUrl);
|
|
117
310
|
return {
|
|
@@ -119,18 +312,188 @@ function resolve(cfg, flags) {
|
|
|
119
312
|
spaceId,
|
|
120
313
|
baseUrl: baseUrlRaw || "https://krova.cloud/api/v1",
|
|
121
314
|
apiKeySource,
|
|
315
|
+
apiKeyStorage: apiKeySource === "context" && ctx ? storageOf(ctx) : "",
|
|
122
316
|
spaceIdSource,
|
|
123
317
|
contextName: ctx?.name ?? ""
|
|
124
318
|
};
|
|
125
319
|
}
|
|
320
|
+
function storageOf(ctx) {
|
|
321
|
+
return ctx.keyStorage === "keychain" ? "keychain" : "file";
|
|
322
|
+
}
|
|
323
|
+
const errText$1 = (e) => e instanceof Error ? e.message : String(e);
|
|
324
|
+
/** One short line on stderr (stdout stays clean for --json). */
|
|
325
|
+
function warn(msg) {
|
|
326
|
+
process.stderr.write(`krova: ${msg}\n`);
|
|
327
|
+
}
|
|
328
|
+
/** The context's API key: from the file, or from the OS keychain for a keychain context.
|
|
329
|
+
* A keychain that cannot be read warns on stderr and returns "" (so the caller sees
|
|
330
|
+
* "no key" and is told to log in again) instead of crashing every command. */
|
|
331
|
+
function contextKey(ctx) {
|
|
332
|
+
if (storageOf(ctx) !== "keychain") return ctx.apiKey ?? "";
|
|
333
|
+
try {
|
|
334
|
+
const key = readBackend().get(ctx.name);
|
|
335
|
+
if (key) return key;
|
|
336
|
+
warn(`the API key for context "${ctx.name}" is not in the OS keychain (service ${KEYCHAIN_SERVICE}); run \`krova login --context ${ctx.name}\` to store it again`);
|
|
337
|
+
} catch (e) {
|
|
338
|
+
warn(`could not read the API key for context "${ctx.name}" from the OS keychain (${errText$1(e)}); run \`krova login --context ${ctx.name}\` to store it again`);
|
|
339
|
+
}
|
|
340
|
+
return "";
|
|
341
|
+
}
|
|
342
|
+
/** Write `key` to the keychain (verified by a read-back) and mark `ctx` as a keychain
|
|
343
|
+
* context, else keep it in the 0600 file with a one-line stderr message. Mutates `ctx`;
|
|
344
|
+
* the caller still calls `save`. Never throws. */
|
|
345
|
+
function setContextKey(ctx, key) {
|
|
346
|
+
try {
|
|
347
|
+
const backend = writeBackend();
|
|
348
|
+
backend.set(ctx.name, key);
|
|
349
|
+
if (backend.get(ctx.name) !== key) {
|
|
350
|
+
try {
|
|
351
|
+
backend.delete(ctx.name);
|
|
352
|
+
} catch {}
|
|
353
|
+
throw new Error("the keychain did not return the stored key");
|
|
354
|
+
}
|
|
355
|
+
ctx.keyStorage = "keychain";
|
|
356
|
+
ctx.apiKey = void 0;
|
|
357
|
+
return {
|
|
358
|
+
storage: "keychain",
|
|
359
|
+
backend: backend.name
|
|
360
|
+
};
|
|
361
|
+
} catch (e) {
|
|
362
|
+
if (!(e instanceof KeychainUnavailableError && e.optOut)) warn(`OS keychain unavailable (${errText$1(e)}); storing the API key in ${configPath()} (mode 0600) instead`);
|
|
363
|
+
}
|
|
364
|
+
if (storageOf(ctx) === "keychain") deleteContextKey(ctx);
|
|
365
|
+
ctx.keyStorage = "file";
|
|
366
|
+
ctx.apiKey = key;
|
|
367
|
+
return { storage: "file" };
|
|
368
|
+
}
|
|
369
|
+
/** Delete the context's keychain item, if it has one. Failure is a warning, not an error:
|
|
370
|
+
* the context is being removed either way. */
|
|
371
|
+
function deleteContextKey(ctx) {
|
|
372
|
+
if (storageOf(ctx) !== "keychain") return;
|
|
373
|
+
try {
|
|
374
|
+
readBackend().delete(ctx.name);
|
|
375
|
+
} catch (e) {
|
|
376
|
+
warn(`could not delete the keychain item for context "${ctx.name}" (${errText$1(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${ctx.name})`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
/** Rename a context and save the config. A keychain key moves with it: the new item is written
|
|
380
|
+
* and verified first, the config is saved, and only then is the old item deleted. A failure at
|
|
381
|
+
* any step before that leaves the context (and its old item) as it was. */
|
|
382
|
+
function renameContext(cfg, oldName, newName, persist = () => save(cfg)) {
|
|
383
|
+
const c = find(cfg, oldName);
|
|
384
|
+
if (!c) throw new Error(`no context named "${oldName}"`);
|
|
385
|
+
assertContextName(newName);
|
|
386
|
+
if (find(cfg, newName)) throw new Error(`a context named "${newName}" already exists`);
|
|
387
|
+
const backend = storageOf(c) === "keychain" ? readBackend() : void 0;
|
|
388
|
+
if (backend) {
|
|
389
|
+
let key;
|
|
390
|
+
try {
|
|
391
|
+
key = backend.get(oldName);
|
|
392
|
+
} catch (e) {
|
|
393
|
+
throw new Error(`could not read the key for "${oldName}" from the OS keychain: ${errText$1(e)}`);
|
|
394
|
+
}
|
|
395
|
+
if (!key) throw new Error(`the API key for "${oldName}" is not in the OS keychain; run \`krova login --context ${oldName}\` first`);
|
|
396
|
+
try {
|
|
397
|
+
backend.set(newName, key);
|
|
398
|
+
if (backend.get(newName) !== key) throw new Error("the keychain did not return the stored key");
|
|
399
|
+
} catch (e) {
|
|
400
|
+
try {
|
|
401
|
+
backend.delete(newName);
|
|
402
|
+
} catch {}
|
|
403
|
+
throw new Error(`could not move the key to "${newName}" in the OS keychain: ${errText$1(e)}`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
const wasCurrent = cfg.currentContext === oldName;
|
|
407
|
+
c.name = newName;
|
|
408
|
+
if (wasCurrent) cfg.currentContext = newName;
|
|
409
|
+
try {
|
|
410
|
+
persist();
|
|
411
|
+
} catch (e) {
|
|
412
|
+
c.name = oldName;
|
|
413
|
+
if (wasCurrent) cfg.currentContext = oldName;
|
|
414
|
+
if (backend) try {
|
|
415
|
+
backend.delete(newName);
|
|
416
|
+
} catch {}
|
|
417
|
+
throw e;
|
|
418
|
+
}
|
|
419
|
+
if (backend) try {
|
|
420
|
+
backend.delete(oldName);
|
|
421
|
+
} catch (e) {
|
|
422
|
+
warn(`renamed, but could not delete the old keychain item (${errText$1(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${oldName})`);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
/** Move every file-stored key into the keychain. A key leaves the file only after the
|
|
426
|
+
* keychain read-back matches; `save` runs after each context so a later failure never
|
|
427
|
+
* loses an earlier move. Throws when no keychain can be used at all. */
|
|
428
|
+
function migrateKeysToKeychain(cfg) {
|
|
429
|
+
const backend = writeBackend();
|
|
430
|
+
const entries = [];
|
|
431
|
+
for (const ctx of cfg.contexts ?? []) {
|
|
432
|
+
if (storageOf(ctx) === "keychain") {
|
|
433
|
+
entries.push({
|
|
434
|
+
context: ctx.name,
|
|
435
|
+
result: "skipped",
|
|
436
|
+
detail: "already in the keychain"
|
|
437
|
+
});
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
const key = (ctx.apiKey ?? "").trim();
|
|
441
|
+
if (!key) {
|
|
442
|
+
entries.push({
|
|
443
|
+
context: ctx.name,
|
|
444
|
+
result: "skipped",
|
|
445
|
+
detail: "no API key stored"
|
|
446
|
+
});
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
try {
|
|
450
|
+
backend.set(ctx.name, key);
|
|
451
|
+
if (backend.get(ctx.name) !== key) {
|
|
452
|
+
try {
|
|
453
|
+
backend.delete(ctx.name);
|
|
454
|
+
} catch {}
|
|
455
|
+
throw new Error("the keychain did not return the stored key");
|
|
456
|
+
}
|
|
457
|
+
} catch (e) {
|
|
458
|
+
entries.push({
|
|
459
|
+
context: ctx.name,
|
|
460
|
+
result: "failed",
|
|
461
|
+
detail: errText$1(e)
|
|
462
|
+
});
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
ctx.keyStorage = "keychain";
|
|
466
|
+
ctx.apiKey = void 0;
|
|
467
|
+
save(cfg);
|
|
468
|
+
entries.push({
|
|
469
|
+
context: ctx.name,
|
|
470
|
+
result: "migrated"
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
return {
|
|
474
|
+
backend: backend.name,
|
|
475
|
+
entries
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
/** A context name becomes a keychain account passed to `security` and `secret-tool`, so one that
|
|
479
|
+
* starts with `-` could be read as an option. */
|
|
480
|
+
function assertContextName(name) {
|
|
481
|
+
if (name.trim().startsWith("-")) throw new Error(`context names cannot start with "-" (got "${name}")`);
|
|
482
|
+
}
|
|
126
483
|
function sanitizeContextName(name) {
|
|
127
|
-
|
|
484
|
+
const clean = name.trim().toLowerCase().replace(/\s+/g, "-");
|
|
485
|
+
assertContextName(clean);
|
|
486
|
+
return clean;
|
|
128
487
|
}
|
|
129
488
|
function maskKey(key) {
|
|
130
489
|
if (!key) return "";
|
|
131
490
|
if (key.length <= 8) return "****";
|
|
132
491
|
return `${key.slice(0, 6)}…${key.slice(-4)}`;
|
|
133
492
|
}
|
|
493
|
+
/** The key as it should be printed: masked unless `--show-secrets` was passed. */
|
|
494
|
+
function displayKey(key, showSecrets) {
|
|
495
|
+
return showSecrets ? key : maskKey(key);
|
|
496
|
+
}
|
|
134
497
|
// src/lib/output.ts
|
|
135
498
|
function printJSON(value) {
|
|
136
499
|
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
@@ -200,6 +563,25 @@ async function rawRequest(opts) {
|
|
|
200
563
|
clearTimeout(timer);
|
|
201
564
|
}
|
|
202
565
|
}
|
|
566
|
+
// src/lib/output-format.ts
|
|
567
|
+
/** The values the global `-o, --output <format>` flag accepts. */
|
|
568
|
+
const OUTPUT_FORMATS = ["table", "json"];
|
|
569
|
+
/** Values worth completing after a flag, keyed by the flag as typed. */
|
|
570
|
+
const FLAG_VALUE_CHOICES = {
|
|
571
|
+
"-o": OUTPUT_FORMATS,
|
|
572
|
+
"--output": OUTPUT_FORMATS
|
|
573
|
+
};
|
|
574
|
+
/**
|
|
575
|
+
* Validate the `--output` value. Unset means the default, `table`.
|
|
576
|
+
* Throws a one-line error for anything else, so a typo never silently
|
|
577
|
+
* falls back to a table in a script that expects JSON.
|
|
578
|
+
*/
|
|
579
|
+
function parseOutputFormat(raw) {
|
|
580
|
+
if (raw === void 0 || raw === null || raw === "") return "table";
|
|
581
|
+
const value = String(raw);
|
|
582
|
+
if (OUTPUT_FORMATS.includes(value)) return value;
|
|
583
|
+
throw new Error(`--output must be "json" or "table" (got "${value}")`);
|
|
584
|
+
}
|
|
203
585
|
// src/lib/runtime.ts
|
|
204
586
|
/** Parse a Go-style duration ("30s", "500ms", "2m", "1h") to ms. Non-positive
|
|
205
587
|
* or unparseable floors to 30s (matches the Go requestTimeout behavior). */
|
|
@@ -223,6 +605,12 @@ function parseDuration(input) {
|
|
|
223
605
|
}
|
|
224
606
|
return total > 0 ? total : 3e4;
|
|
225
607
|
}
|
|
608
|
+
/** What the last `getRuntime` call resolved; the top-level error handler reads it
|
|
609
|
+
* to name the base URL in a connection hint and to stay quiet in JSON mode. */
|
|
610
|
+
let active;
|
|
611
|
+
function activeRuntime() {
|
|
612
|
+
return active;
|
|
613
|
+
}
|
|
226
614
|
function getRuntime(cmd) {
|
|
227
615
|
const opts = cmd.optsWithGlobals();
|
|
228
616
|
const flags = {
|
|
@@ -232,11 +620,17 @@ function getRuntime(cmd) {
|
|
|
232
620
|
context: opts.context
|
|
233
621
|
};
|
|
234
622
|
const cfg = load();
|
|
623
|
+
const res = resolve(cfg, flags);
|
|
624
|
+
const json = Boolean(opts.json) || parseOutputFormat(opts.output) === "json";
|
|
625
|
+
active = {
|
|
626
|
+
baseUrl: res.baseUrl,
|
|
627
|
+
json
|
|
628
|
+
};
|
|
235
629
|
return {
|
|
236
630
|
flags,
|
|
237
631
|
cfg,
|
|
238
|
-
res
|
|
239
|
-
json
|
|
632
|
+
res,
|
|
633
|
+
json,
|
|
240
634
|
timeoutMs: parseDuration(opts.timeout)
|
|
241
635
|
};
|
|
242
636
|
}
|
|
@@ -319,18 +713,23 @@ async function persistLogin(input) {
|
|
|
319
713
|
name = sanitizeContextName(name);
|
|
320
714
|
const cur = upsert(cfg, {
|
|
321
715
|
name,
|
|
322
|
-
apiKey: input.apiKey,
|
|
323
716
|
spaceId,
|
|
324
717
|
spaceName,
|
|
325
718
|
baseUrl: input.baseUrl
|
|
326
719
|
});
|
|
720
|
+
const stored = setContextKey(cur, input.apiKey);
|
|
327
721
|
cfg.currentContext = cur.name;
|
|
328
722
|
save(cfg);
|
|
329
723
|
return {
|
|
330
724
|
ctxName: cur.name,
|
|
331
|
-
spaceName: cur.spaceName ?? ""
|
|
725
|
+
spaceName: cur.spaceName ?? "",
|
|
726
|
+
stored
|
|
332
727
|
};
|
|
333
728
|
}
|
|
729
|
+
/** The line printed after a login: says where the key went. */
|
|
730
|
+
function loginMessage(ctxName, stored) {
|
|
731
|
+
return stored.storage === "keychain" ? `Logged in. Saved context "${ctxName}" to ${configPath()} (API key in the ${stored.backend})` : `Logged in. Saved context "${ctxName}" to ${configPath()}`;
|
|
732
|
+
}
|
|
334
733
|
// src/commands/auth.ts
|
|
335
734
|
/** Prompt for an API key. Hidden echo when stdin is a TTY. */
|
|
336
735
|
function promptAPIKey() {
|
|
@@ -376,23 +775,24 @@ function authCommand() {
|
|
|
376
775
|
let key = opts.apiKey || rt.flags.apiKey || "";
|
|
377
776
|
if (!key.trim()) key = await promptAPIKey();
|
|
378
777
|
if (!key.trim()) throw new Error("no API key provided");
|
|
379
|
-
const { ctxName, spaceName } = await persistLogin({
|
|
778
|
+
const { ctxName, spaceName, stored } = await persistLogin({
|
|
380
779
|
apiKey: key.trim(),
|
|
381
780
|
baseUrl: rt.res.baseUrl,
|
|
382
781
|
spaceId: opts.space,
|
|
383
782
|
ctxName: opts.context,
|
|
384
783
|
timeoutMs: rt.timeoutMs
|
|
385
784
|
});
|
|
386
|
-
process.stdout.write(
|
|
785
|
+
process.stdout.write(`${loginMessage(ctxName, stored)}\n`);
|
|
387
786
|
if (spaceName) process.stdout.write(`Space: ${spaceName}\n`);
|
|
388
787
|
});
|
|
389
|
-
auth.command("status").description("show the resolved credentials and verify them against the API").option("--offline", "skip the live check; only report what's stored locally").action(async (opts, cmd) => {
|
|
788
|
+
auth.command("status").description("show the resolved credentials and verify them against the API").option("--offline", "skip the live check; only report what's stored locally").option("--show-secrets", "print the full API key instead of a masked one").action(async (opts, cmd) => {
|
|
390
789
|
const rt = getRuntime(cmd);
|
|
790
|
+
const showSecrets = Boolean(opts.showSecrets);
|
|
391
791
|
const offline = Boolean(opts.offline);
|
|
392
792
|
const probe = offline ? { state: "missing" } : await probeAuth(rt.res.baseUrl, rt.res.apiKey, rt.timeoutMs);
|
|
393
793
|
const hasKey = Boolean(rt.res.apiKey);
|
|
394
794
|
const authenticated = offline ? hasKey : probe.state === "valid";
|
|
395
|
-
const detail = offline || !hasKey ? "" : probe.state === "rejected" ? `the API rejected this key (HTTP ${probe.status}) — it
|
|
795
|
+
const detail = offline || !hasKey ? "" : probe.state === "rejected" ? `the API rejected this key (HTTP ${probe.status}) — it is invalid, revoked or expired, or belongs to another environment; run \`krova login\`` : probe.state === "unreachable" ? `could not reach ${rt.res.baseUrl} (${probe.error}) — the key was NOT verified` : probe.state === "unsupported" ? "this server has no /space endpoint, so the key could not be verified" : "";
|
|
396
796
|
const spaceId = probe.state === "valid" ? probe.space.id : rt.res.spaceId;
|
|
397
797
|
if (rt.json) return printJSON({
|
|
398
798
|
authenticated,
|
|
@@ -401,7 +801,8 @@ function authCommand() {
|
|
|
401
801
|
detail: detail || void 0,
|
|
402
802
|
context: rt.res.contextName,
|
|
403
803
|
apiKeySource: rt.res.apiKeySource,
|
|
404
|
-
|
|
804
|
+
apiKeyStorage: rt.res.apiKeyStorage || void 0,
|
|
805
|
+
...showSecrets ? { apiKey: rt.res.apiKey } : { apiKeyMasked: displayKey(rt.res.apiKey, false) },
|
|
405
806
|
spaceId,
|
|
406
807
|
spaceSource: rt.res.spaceIdSource,
|
|
407
808
|
baseUrl: rt.res.baseUrl,
|
|
@@ -410,7 +811,7 @@ function authCommand() {
|
|
|
410
811
|
printKeyValue([
|
|
411
812
|
["Authenticated", !hasKey ? "no (no API key found)" : offline ? "not checked (--offline; a key is stored)" : probe.state === "valid" ? "yes (verified against the API)" : probe.state === "rejected" ? "NO — key rejected by the API" : "unknown (could not verify)"],
|
|
412
813
|
["Context", rt.res.contextName || "—"],
|
|
413
|
-
["API key", rt.res.apiKey ? `${
|
|
814
|
+
["API key", rt.res.apiKey ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : ""})` : "—"],
|
|
414
815
|
["Space ID", spaceId ? `${spaceId} (${rt.res.spaceIdSource})` : "—"],
|
|
415
816
|
["Base URL", rt.res.baseUrl],
|
|
416
817
|
["Config", configPath()]
|
|
@@ -418,6 +819,45 @@ function authCommand() {
|
|
|
418
819
|
if (detail) process.stdout.write(`\n${detail}\n`);
|
|
419
820
|
if (!hasKey || probe.state === "rejected") process.exitCode = 1;
|
|
420
821
|
});
|
|
822
|
+
auth.command("logout").description("remove a saved context and its API key from this machine").option("--context <name>", "the context to remove (default: the current one)").action((opts, cmd) => {
|
|
823
|
+
const rt = getRuntime(cmd);
|
|
824
|
+
const cfg = load();
|
|
825
|
+
const name = (opts.context ?? rt.flags.context ?? "").trim() || rt.res.contextName;
|
|
826
|
+
if (!name) throw new Error(`not logged in: no saved context in ${configPath()}`);
|
|
827
|
+
if (!find(cfg, name)) throw new Error(`no context named "${name}"`);
|
|
828
|
+
const wasCurrent = cfg.currentContext === name;
|
|
829
|
+
removeContext(cfg, name);
|
|
830
|
+
const current = cfg.currentContext || null;
|
|
831
|
+
if (rt.json) return printJSON({
|
|
832
|
+
context: name,
|
|
833
|
+
result: "logged_out",
|
|
834
|
+
current
|
|
835
|
+
});
|
|
836
|
+
process.stdout.write(`Logged out of ${name}. The API key still works until you revoke it in the dashboard (Settings > API keys).\n`);
|
|
837
|
+
if (wasCurrent && current) process.stdout.write(`Now using ${current}.\n`);
|
|
838
|
+
});
|
|
839
|
+
auth.command("migrate-keychain").description("move API keys saved in the config file into the OS keychain").action((_opts, cmd) => {
|
|
840
|
+
const rt = getRuntime(cmd);
|
|
841
|
+
const cfg = load();
|
|
842
|
+
let result;
|
|
843
|
+
try {
|
|
844
|
+
result = migrateKeysToKeychain(cfg);
|
|
845
|
+
} catch (e) {
|
|
846
|
+
if (e instanceof KeychainUnavailableError) throw new Error(e.optOut ? `${e.message}; unset KROVA_NO_KEYCHAIN to move keys into the keychain` : `no OS keychain available (${e.message}); keys stay in ${configPath()}`);
|
|
847
|
+
throw e;
|
|
848
|
+
}
|
|
849
|
+
if (result.entries.filter((x) => x.result === "failed").length > 0) process.exitCode = 1;
|
|
850
|
+
if (rt.json) return printJSON({
|
|
851
|
+
keychain: result.backend,
|
|
852
|
+
results: result.entries
|
|
853
|
+
});
|
|
854
|
+
if (result.entries.length === 0) process.stdout.write("No contexts to migrate.\n");
|
|
855
|
+
for (const x of result.entries) {
|
|
856
|
+
const tail = x.detail ? ` (${x.detail})` : "";
|
|
857
|
+
process.stdout.write(`${x.result === "migrated" ? "Moved" : x.result === "failed" ? "FAILED" : "Skipped"} ${x.context}${x.result === "migrated" ? ` to the ${result.backend}` : tail}\n`);
|
|
858
|
+
if (x.result === "failed") process.stderr.write(` ${x.detail}\n`);
|
|
859
|
+
}
|
|
860
|
+
});
|
|
421
861
|
return auth;
|
|
422
862
|
}
|
|
423
863
|
// src/commands/backups.ts
|
|
@@ -612,17 +1052,210 @@ function imagesCommand() {
|
|
|
612
1052
|
function pricingCommand() {
|
|
613
1053
|
return catalogCmd("pricing", "show per-resource hourly pricing", (c) => c.catalog.pricing());
|
|
614
1054
|
}
|
|
1055
|
+
// src/lib/completion.ts
|
|
1056
|
+
const COMPLETION_SHELLS = [
|
|
1057
|
+
"bash",
|
|
1058
|
+
"zsh",
|
|
1059
|
+
"fish"
|
|
1060
|
+
];
|
|
1061
|
+
const oneLine = (s) => s.split("\n")[0].replace(/\s+/g, " ").trim();
|
|
1062
|
+
/** Walk the commander tree (visible commands and options only). */
|
|
1063
|
+
function walkCommands(cmd, path = []) {
|
|
1064
|
+
const help = cmd.createHelp();
|
|
1065
|
+
return {
|
|
1066
|
+
path,
|
|
1067
|
+
aliases: cmd.aliases(),
|
|
1068
|
+
description: oneLine(cmd.description()),
|
|
1069
|
+
options: help.visibleOptions(cmd).map((o) => ({
|
|
1070
|
+
long: o.long,
|
|
1071
|
+
short: o.short,
|
|
1072
|
+
description: oneLine(o.description),
|
|
1073
|
+
takesValue: o.required || o.optional
|
|
1074
|
+
})),
|
|
1075
|
+
commands: help.visibleCommands(cmd).map((c) => walkCommands(c, [...path, c.name()]))
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
/** Shell single-quote: safe inside bash, zsh and fish single quotes. */
|
|
1079
|
+
const sq = (s) => `'${s.replace(/'/g, "'\\''")}'`;
|
|
1080
|
+
const fishSq = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
1081
|
+
const flat = (node) => [node, ...node.commands.flatMap(flat)];
|
|
1082
|
+
const key = (path) => path.join(" ");
|
|
1083
|
+
const optionWords = (n) => n.options.flatMap((o) => [o.long, o.short].filter((x) => Boolean(x)));
|
|
1084
|
+
const commandWords = (n) => n.commands.flatMap((c) => [c.path.at(-1), ...c.aliases]);
|
|
1085
|
+
/** Every (parent path, typed word) -> child path transition, aliases included. */
|
|
1086
|
+
function transitions(root) {
|
|
1087
|
+
return flat(root).flatMap((parent) => parent.commands.flatMap((c) => [c.path.at(-1), ...c.aliases].map((word) => ({
|
|
1088
|
+
from: key(parent.path),
|
|
1089
|
+
word,
|
|
1090
|
+
to: key(c.path)
|
|
1091
|
+
}))));
|
|
1092
|
+
}
|
|
1093
|
+
/** Every flag in the tree that takes a value but has no fixed choices (paths, names, numbers). */
|
|
1094
|
+
function freeValueFlags(root, choices) {
|
|
1095
|
+
const out = /* @__PURE__ */ new Set();
|
|
1096
|
+
for (const n of flat(root)) for (const o of n.options) {
|
|
1097
|
+
if (!o.takesValue) continue;
|
|
1098
|
+
for (const f of [o.long, o.short]) if (f && !choices[f]) out.add(f);
|
|
1099
|
+
}
|
|
1100
|
+
return [...out];
|
|
1101
|
+
}
|
|
1102
|
+
function bash(root, name, choices) {
|
|
1103
|
+
const fn = `_${name}_complete`;
|
|
1104
|
+
return `${[
|
|
1105
|
+
`# bash completion for ${name}, generated by \`${name} completion bash\``,
|
|
1106
|
+
`${fn}() {`,
|
|
1107
|
+
` local cur prev cpath="" w next i`,
|
|
1108
|
+
` cur="\${COMP_WORDS[COMP_CWORD]}"`,
|
|
1109
|
+
` prev="\${COMP_WORDS[COMP_CWORD-1]}"`,
|
|
1110
|
+
` for ((i=1; i<COMP_CWORD; i++)); do`,
|
|
1111
|
+
` w="\${COMP_WORDS[i]}"`,
|
|
1112
|
+
` next=""`,
|
|
1113
|
+
` case "$cpath/$w" in`,
|
|
1114
|
+
...transitions(root).map((t) => ` ${sq(`${t.from}/${t.word}`)}) next=${sq(t.to)};;`),
|
|
1115
|
+
` esac`,
|
|
1116
|
+
` [ -n "$next" ] && cpath="$next"`,
|
|
1117
|
+
` done`,
|
|
1118
|
+
` case "$prev" in`,
|
|
1119
|
+
...Object.entries(choices).map(([flag, values]) => ` ${sq(flag)}) COMPREPLY=( $(compgen -W ${sq(values.join(" "))} -- "$cur") ); return;;`),
|
|
1120
|
+
...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) COMPREPLY=(); return;;`),
|
|
1121
|
+
` esac`,
|
|
1122
|
+
` local cmds="" opts=""`,
|
|
1123
|
+
` case "$cpath" in`,
|
|
1124
|
+
...flat(root).map((n) => ` ${sq(key(n.path))}) cmds=${sq(commandWords(n).join(" "))}; opts=${sq(optionWords(n).join(" "))};;`),
|
|
1125
|
+
` esac`,
|
|
1126
|
+
` if [[ "$cur" == -* ]]; then`,
|
|
1127
|
+
` COMPREPLY=( $(compgen -W "$opts" -- "$cur") )`,
|
|
1128
|
+
` else`,
|
|
1129
|
+
` COMPREPLY=( $(compgen -W "$cmds" -- "$cur") )`,
|
|
1130
|
+
` fi`,
|
|
1131
|
+
`}`,
|
|
1132
|
+
`complete -o default -F ${fn} ${name}`
|
|
1133
|
+
].join("\n")}\n`;
|
|
1134
|
+
}
|
|
1135
|
+
function zsh(root, name, choices) {
|
|
1136
|
+
const fn = `_${name}`;
|
|
1137
|
+
const item = (word, desc) => sq(`${word.replace(/:/g, "\\:")}${desc ? `:${desc}` : ""}`);
|
|
1138
|
+
return `${[
|
|
1139
|
+
`#compdef ${name}`,
|
|
1140
|
+
`# zsh completion for ${name}, generated by \`${name} completion zsh\``,
|
|
1141
|
+
`${fn}() {`,
|
|
1142
|
+
` local cpath="" w next i`,
|
|
1143
|
+
` local -a cmds opts`,
|
|
1144
|
+
` for (( i=2; i<CURRENT; i++ )); do`,
|
|
1145
|
+
` w="\${words[i]}"`,
|
|
1146
|
+
` next=""`,
|
|
1147
|
+
` case "$cpath/$w" in`,
|
|
1148
|
+
...transitions(root).map((t) => ` ${sq(`${t.from}/${t.word}`)}) next=${sq(t.to)};;`),
|
|
1149
|
+
` esac`,
|
|
1150
|
+
` [[ -n "$next" ]] && cpath="$next"`,
|
|
1151
|
+
` done`,
|
|
1152
|
+
` case "\${words[CURRENT-1]}" in`,
|
|
1153
|
+
...Object.entries(choices).map(([flag, values]) => ` ${sq(flag)}) compadd -- ${values.map(sq).join(" ")}; return;;`),
|
|
1154
|
+
...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) _files; return;;`),
|
|
1155
|
+
` esac`,
|
|
1156
|
+
` case "$cpath" in`,
|
|
1157
|
+
...flat(root).flatMap((n) => {
|
|
1158
|
+
const cmdItems = n.commands.flatMap((c) => [c.path.at(-1), ...c.aliases].map((w) => item(w, c.description)));
|
|
1159
|
+
const optItems = n.options.flatMap((o) => [o.long, o.short].filter((x) => Boolean(x)).map((w) => item(w, o.description)));
|
|
1160
|
+
return [
|
|
1161
|
+
` ${sq(key(n.path))})`,
|
|
1162
|
+
` cmds=(${cmdItems.join(" ")})`,
|
|
1163
|
+
` opts=(${optItems.join(" ")});;`
|
|
1164
|
+
];
|
|
1165
|
+
}),
|
|
1166
|
+
` esac`,
|
|
1167
|
+
` if [[ "$PREFIX" == -* ]]; then`,
|
|
1168
|
+
` _describe -t options 'option' opts`,
|
|
1169
|
+
` else`,
|
|
1170
|
+
` _describe -t commands 'command' cmds`,
|
|
1171
|
+
` (( \${#cmds} )) || _files`,
|
|
1172
|
+
` fi`,
|
|
1173
|
+
`}`,
|
|
1174
|
+
`if [ "$funcstack[1]" = "${fn}" ]; then`,
|
|
1175
|
+
` ${fn} "$@"`,
|
|
1176
|
+
`else`,
|
|
1177
|
+
` compdef ${fn} ${name}`,
|
|
1178
|
+
`fi`
|
|
1179
|
+
].join("\n")}\n`;
|
|
1180
|
+
}
|
|
1181
|
+
function fish(root, name, choices) {
|
|
1182
|
+
const fn = `__${name}_path`;
|
|
1183
|
+
const rootKey = "root";
|
|
1184
|
+
const k = (path) => path.length ? key(path) : rootKey;
|
|
1185
|
+
const lines = [
|
|
1186
|
+
`# fish completion for ${name}, generated by \`${name} completion fish\``,
|
|
1187
|
+
`function ${fn}`,
|
|
1188
|
+
` set -l cpath ${rootKey}`,
|
|
1189
|
+
` set -l tokens (commandline -opc)`,
|
|
1190
|
+
` set -e tokens[1]`,
|
|
1191
|
+
` for w in $tokens`,
|
|
1192
|
+
` switch "$cpath/$w"`,
|
|
1193
|
+
...transitions(root).flatMap((t) => [` case ${fishSq(`${t.from || rootKey}/${t.word}`)}`, ` set cpath ${fishSq(t.to)}`]),
|
|
1194
|
+
` end`,
|
|
1195
|
+
` end`,
|
|
1196
|
+
` echo $cpath`,
|
|
1197
|
+
`end`
|
|
1198
|
+
];
|
|
1199
|
+
for (const n of flat(root)) {
|
|
1200
|
+
const cond = `-n ${fishSq(`test (${fn}) = ${fishSq(k(n.path))}`)}`;
|
|
1201
|
+
if (n.commands.length) lines.push(`complete -c ${name} ${cond} -f`);
|
|
1202
|
+
for (const c of n.commands) for (const w of [c.path.at(-1), ...c.aliases]) lines.push(`complete -c ${name} ${cond} -a ${fishSq(w)} -d ${fishSq(c.description)}`);
|
|
1203
|
+
for (const o of n.options) {
|
|
1204
|
+
const parts = [`complete -c ${name} ${cond}`];
|
|
1205
|
+
if (o.short) parts.push(`-s ${o.short.replace(/^-/, "")}`);
|
|
1206
|
+
if (o.long) parts.push(`-l ${o.long.replace(/^--/, "")}`);
|
|
1207
|
+
const values = [o.long, o.short].map((f) => f ? choices[f] : void 0).find(Boolean);
|
|
1208
|
+
if (values) parts.push(`-x -a ${fishSq(values.join(" "))}`);
|
|
1209
|
+
else if (o.takesValue) parts.push("-r");
|
|
1210
|
+
parts.push(`-d ${fishSq(o.description)}`);
|
|
1211
|
+
lines.push(parts.join(" "));
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
return `${lines.join("\n")}\n`;
|
|
1215
|
+
}
|
|
1216
|
+
/** Generate the completion script for `shell` from the live command tree under `root`. */
|
|
1217
|
+
function generateCompletion(shell, root, choices = FLAG_VALUE_CHOICES) {
|
|
1218
|
+
const tree = walkCommands(root);
|
|
1219
|
+
const name = root.name();
|
|
1220
|
+
if (shell === "bash") return bash(tree, name, choices);
|
|
1221
|
+
if (shell === "zsh") return zsh(tree, name, choices);
|
|
1222
|
+
return fish(tree, name, choices);
|
|
1223
|
+
}
|
|
1224
|
+
const COMPLETION_INSTALL_HELP = `
|
|
1225
|
+
Install (restart your shell afterward):
|
|
1226
|
+
|
|
1227
|
+
bash mkdir -p ~/.local/share/bash-completion/completions
|
|
1228
|
+
krova completion bash > ~/.local/share/bash-completion/completions/krova
|
|
1229
|
+
(or add 'source <(krova completion bash)' to ~/.bashrc)
|
|
1230
|
+
zsh krova completion zsh > "\${fpath[1]}/_krova"
|
|
1231
|
+
(needs 'autoload -U compinit && compinit' in ~/.zshrc; or add
|
|
1232
|
+
'source <(krova completion zsh)' to ~/.zshrc after compinit)
|
|
1233
|
+
fish krova completion fish > ~/.config/fish/completions/krova.fish
|
|
1234
|
+
|
|
1235
|
+
The script is generated from the commands in your installed version, so
|
|
1236
|
+
re-run it after you upgrade the CLI.
|
|
1237
|
+
`;
|
|
1238
|
+
// src/commands/completion.ts
|
|
1239
|
+
function completionCommand() {
|
|
1240
|
+
return new Command("completion").description("print a shell completion script (bash, zsh or fish)").addArgument(new Argument("<shell>", "target shell").choices(COMPLETION_SHELLS)).addHelpText("after", COMPLETION_INSTALL_HELP).action((shell, _opts, cmd) => {
|
|
1241
|
+
let root = cmd;
|
|
1242
|
+
while (root.parent) root = root.parent;
|
|
1243
|
+
process.stdout.write(generateCompletion(shell, root));
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
615
1246
|
// src/commands/context.ts
|
|
616
1247
|
function contextCommand() {
|
|
617
1248
|
const ctx = new Command("context").aliases(["ctx", "contexts"]).description("manage named credential contexts (like kubectl/aws profiles)");
|
|
618
|
-
ctx.command("list").aliases(["ls"]).description("list all contexts").action((
|
|
619
|
-
const
|
|
1249
|
+
ctx.command("list").aliases(["ls"]).description("list all contexts").option("--show-secrets", "print full API keys instead of masked ones (JSON output only; the table has no key column)").action((opts, cmd) => {
|
|
1250
|
+
const g = cmd.optsWithGlobals();
|
|
1251
|
+
const json = Boolean(g.json) || parseOutputFormat(g.output) === "json";
|
|
620
1252
|
const cfg = load();
|
|
621
1253
|
if (json) return printJSON({
|
|
622
1254
|
currentContext: cfg.currentContext ?? "",
|
|
623
1255
|
contexts: (cfg.contexts ?? []).map((c) => ({
|
|
624
1256
|
name: c.name,
|
|
625
|
-
apiKey:
|
|
1257
|
+
apiKey: opts.showSecrets || storageOf(c) === "file" ? displayKey(contextKey(c), Boolean(opts.showSecrets)) : "****",
|
|
1258
|
+
keyStorage: storageOf(c),
|
|
626
1259
|
spaceId: c.spaceId ?? "",
|
|
627
1260
|
spaceName: c.spaceName ?? "",
|
|
628
1261
|
baseUrl: c.baseUrl ?? ""
|
|
@@ -657,22 +1290,245 @@ function contextCommand() {
|
|
|
657
1290
|
ctx.command("rename").argument("<old>", "current name").argument("<new>", "new name").description("rename a context").action((oldName, newName) => {
|
|
658
1291
|
const cfg = load();
|
|
659
1292
|
if (!newName.trim()) throw new Error("new name must not be empty");
|
|
660
|
-
|
|
661
|
-
if (!c) throw new Error(`no context named "${oldName}"`);
|
|
662
|
-
if ((cfg.contexts ?? []).some((x) => x.name === newName)) throw new Error(`a context named "${newName}" already exists`);
|
|
663
|
-
c.name = newName;
|
|
664
|
-
if (cfg.currentContext === oldName) cfg.currentContext = newName;
|
|
665
|
-
save(cfg);
|
|
1293
|
+
renameContext(cfg, oldName, newName);
|
|
666
1294
|
process.stdout.write(`Renamed ${oldName} → ${newName}\n`);
|
|
667
1295
|
});
|
|
668
1296
|
ctx.command("delete").aliases(["rm"]).argument("<name>", "context name").description("delete a context").action((name) => {
|
|
669
|
-
|
|
670
|
-
if (!remove(cfg, name)) throw new Error(`no context named "${name}"`);
|
|
671
|
-
save(cfg);
|
|
1297
|
+
if (!removeContext(load(), name)) throw new Error(`no context named "${name}"`);
|
|
672
1298
|
process.stdout.write(`Deleted context ${name}\n`);
|
|
673
1299
|
});
|
|
674
1300
|
return ctx;
|
|
675
1301
|
}
|
|
1302
|
+
// src/lib/create-prompt.ts
|
|
1303
|
+
/**
|
|
1304
|
+
* The interactive half of `krova cubes create`.
|
|
1305
|
+
*
|
|
1306
|
+
* Everything the prompt flow touches from the outside (the terminal, the
|
|
1307
|
+
* catalog, the key files) comes in through an interface, so tests drive it
|
|
1308
|
+
* with scripted answers and never need a TTY, a network or a real home dir.
|
|
1309
|
+
*/
|
|
1310
|
+
/** Defaults for the resource flags. `cubes create` registers them on its options too. */
|
|
1311
|
+
const DEFAULT_RESOURCES = {
|
|
1312
|
+
vcpu: "1",
|
|
1313
|
+
ram: "1",
|
|
1314
|
+
disk: "10"
|
|
1315
|
+
};
|
|
1316
|
+
/** Input ended (Ctrl+C, Ctrl+D, closed pipe) before the questions were answered. */
|
|
1317
|
+
var PromptAbortError = class extends Error {
|
|
1318
|
+
constructor() {
|
|
1319
|
+
super("input closed");
|
|
1320
|
+
this.name = "PromptAbortError";
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
/** Prompts run only on a real terminal, and never when the caller asked for JSON. */
|
|
1324
|
+
function isInteractive(opts) {
|
|
1325
|
+
if (opts.json) return false;
|
|
1326
|
+
const stdin = opts.stdin ?? process.stdin;
|
|
1327
|
+
const stdout = opts.stdout ?? process.stdout;
|
|
1328
|
+
return Boolean(stdin.isTTY && stdout.isTTY);
|
|
1329
|
+
}
|
|
1330
|
+
/** The real terminal, via node:readline/promises. */
|
|
1331
|
+
function createReadlineIO() {
|
|
1332
|
+
const rl = readline$1.createInterface({
|
|
1333
|
+
input: process.stdin,
|
|
1334
|
+
output: process.stdout
|
|
1335
|
+
});
|
|
1336
|
+
const closed = new Promise((_, reject) => {
|
|
1337
|
+
rl.once("close", () => reject(new PromptAbortError()));
|
|
1338
|
+
});
|
|
1339
|
+
closed.catch(() => void 0);
|
|
1340
|
+
rl.on("SIGINT", () => rl.close());
|
|
1341
|
+
return {
|
|
1342
|
+
ask: (question) => Promise.race([rl.question(question), closed]),
|
|
1343
|
+
write: (text) => void process.stdout.write(text),
|
|
1344
|
+
warn: (text) => void process.stderr.write(text),
|
|
1345
|
+
close: () => rl.close()
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
function defaultKeyFiles() {
|
|
1349
|
+
return {
|
|
1350
|
+
home: homedir(),
|
|
1351
|
+
readFile: (path) => readFile(path, "utf8")
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
/** Key files offered, in order. Public halves only; a private key is never opened. */
|
|
1355
|
+
const KEY_CANDIDATE_FILES = ["id_ed25519.pub", "id_rsa.pub"];
|
|
1356
|
+
const KEY_PREFIXES = [
|
|
1357
|
+
"ssh-rsa",
|
|
1358
|
+
"ssh-ed25519",
|
|
1359
|
+
"ecdsa-sha2-nistp256",
|
|
1360
|
+
"ecdsa-sha2-nistp384",
|
|
1361
|
+
"ecdsa-sha2-nistp521",
|
|
1362
|
+
"ssh-dss",
|
|
1363
|
+
"sk-ssh-ed25519@openssh.com",
|
|
1364
|
+
"sk-ecdsa-sha2-nistp256@openssh.com"
|
|
1365
|
+
];
|
|
1366
|
+
/** A cube name: 1 to 64 characters after trimming, no control characters. Returns the trimmed name or null. */
|
|
1367
|
+
function validCubeName(raw) {
|
|
1368
|
+
const name = raw.trim();
|
|
1369
|
+
if (name.length === 0 || name.length > 64) return null;
|
|
1370
|
+
if (/[\x00-\x1F\x7F]/.test(name)) return null;
|
|
1371
|
+
return name;
|
|
1372
|
+
}
|
|
1373
|
+
function validSshPublicKey(raw) {
|
|
1374
|
+
const type = raw.trim().split(/\s+/)[0] ?? "";
|
|
1375
|
+
return KEY_PREFIXES.some((prefix) => type.startsWith(prefix));
|
|
1376
|
+
}
|
|
1377
|
+
function positiveInt(raw) {
|
|
1378
|
+
const n = Number(raw.trim());
|
|
1379
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
1380
|
+
}
|
|
1381
|
+
/** Read one public key file. Refuses anything that is not a `.pub` path. */
|
|
1382
|
+
async function readPublicKey(keyFiles, path) {
|
|
1383
|
+
if (!path.endsWith(".pub")) throw new Error(`refusing to read a non-public key file: ${path}`);
|
|
1384
|
+
try {
|
|
1385
|
+
const key = (await keyFiles.readFile(path)).trim();
|
|
1386
|
+
return validSshPublicKey(key) ? key : null;
|
|
1387
|
+
} catch {
|
|
1388
|
+
return null;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
async function findKeyCandidates(keyFiles) {
|
|
1392
|
+
const found = [];
|
|
1393
|
+
for (const file of KEY_CANDIDATE_FILES) {
|
|
1394
|
+
const key = await readPublicKey(keyFiles, join(keyFiles.home, ".ssh", file));
|
|
1395
|
+
if (key) found.push({
|
|
1396
|
+
label: `~/.ssh/${file}`,
|
|
1397
|
+
key
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
return found;
|
|
1401
|
+
}
|
|
1402
|
+
/** "ssh-ed25519 AAAA you@laptop" -> "ssh-ed25519 you@laptop" (type and comment, never the key body). */
|
|
1403
|
+
function keyBlurb(key) {
|
|
1404
|
+
const [type, , ...comment] = key.trim().split(/\s+/);
|
|
1405
|
+
return [type, comment.join(" ")].filter(Boolean).join(" ");
|
|
1406
|
+
}
|
|
1407
|
+
function errText(err) {
|
|
1408
|
+
return err instanceof Error ? err.message : String(err);
|
|
1409
|
+
}
|
|
1410
|
+
async function askName(io) {
|
|
1411
|
+
for (;;) {
|
|
1412
|
+
const name = validCubeName(await io.ask("Name: "));
|
|
1413
|
+
if (name) return name;
|
|
1414
|
+
io.write("A name is 1 to 64 characters with no control characters.\n");
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
async function askImage(io, catalog) {
|
|
1418
|
+
let images = [];
|
|
1419
|
+
try {
|
|
1420
|
+
images = (await catalog.images()).images;
|
|
1421
|
+
} catch (err) {
|
|
1422
|
+
io.warn(`Could not load the image list (${errText(err)}).\n`);
|
|
1423
|
+
}
|
|
1424
|
+
if (images.length === 0) for (;;) {
|
|
1425
|
+
const slug = (await io.ask("Image slug (see `krova images`): ")).trim();
|
|
1426
|
+
if (slug) return slug;
|
|
1427
|
+
}
|
|
1428
|
+
io.write("Images:\n");
|
|
1429
|
+
images.forEach((img, i) => {
|
|
1430
|
+
io.write(` ${i + 1}) ${img.id} (${[img.name, img.version].filter(Boolean).join(" ")})\n`);
|
|
1431
|
+
});
|
|
1432
|
+
for (;;) {
|
|
1433
|
+
const answer = (await io.ask("Image (number or slug): ")).trim();
|
|
1434
|
+
const byNumber = /^\d+$/.test(answer) ? images[Number(answer) - 1] : void 0;
|
|
1435
|
+
if (byNumber) return byNumber.id;
|
|
1436
|
+
const byId = images.find((img) => img.id === answer);
|
|
1437
|
+
if (byId) return byId.id;
|
|
1438
|
+
io.write(`Pick a number from 1 to ${images.length}, or one of the slugs above.\n`);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
/** `undefined` means "let Krova choose". */
|
|
1442
|
+
async function askRegion(io, catalog) {
|
|
1443
|
+
let regions = [];
|
|
1444
|
+
try {
|
|
1445
|
+
regions = (await catalog.regions()).regions;
|
|
1446
|
+
} catch (err) {
|
|
1447
|
+
io.warn(`Could not load the region list (${errText(err)}).\n`);
|
|
1448
|
+
}
|
|
1449
|
+
if (regions.length === 0) return void 0;
|
|
1450
|
+
io.write("Regions:\n");
|
|
1451
|
+
regions.forEach((r, i) => {
|
|
1452
|
+
io.write(` ${i + 1}) ${r.slug} (${r.name})\n`);
|
|
1453
|
+
});
|
|
1454
|
+
for (;;) {
|
|
1455
|
+
const answer = (await io.ask("Region (number or slug, Enter to let Krova choose): ")).trim();
|
|
1456
|
+
if (!answer) return void 0;
|
|
1457
|
+
const byNumber = /^\d+$/.test(answer) ? regions[Number(answer) - 1] : void 0;
|
|
1458
|
+
if (byNumber) return byNumber.slug;
|
|
1459
|
+
const bySlug = regions.find((r) => r.slug === answer);
|
|
1460
|
+
if (bySlug) return bySlug.slug;
|
|
1461
|
+
io.write(`Pick a number from 1 to ${regions.length}, a slug above, or press Enter.\n`);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
async function askSize(io, label, fallback) {
|
|
1465
|
+
for (;;) {
|
|
1466
|
+
const answer = (await io.ask(`${label} [${fallback}]: `)).trim();
|
|
1467
|
+
const n = positiveInt(answer === "" ? fallback : answer);
|
|
1468
|
+
if (n !== null) return String(n);
|
|
1469
|
+
io.write(`${label} must be a positive whole number.\n`);
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
async function askSshKey(io, keyFiles) {
|
|
1473
|
+
const candidates = await findKeyCandidates(keyFiles);
|
|
1474
|
+
if (candidates.length > 0) {
|
|
1475
|
+
io.write("SSH public keys found:\n");
|
|
1476
|
+
candidates.forEach((c, i) => {
|
|
1477
|
+
io.write(` ${i + 1}) ${c.label} (${keyBlurb(c.key)})\n`);
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
const prompt = candidates.length > 0 ? "SSH key (number, or paste a public key) [1]: " : "SSH public key (paste it, e.g. ssh-ed25519 AAAA...): ";
|
|
1481
|
+
for (;;) {
|
|
1482
|
+
const answer = (await io.ask(prompt)).trim();
|
|
1483
|
+
if (candidates.length > 0 && answer === "") return candidates[0].key;
|
|
1484
|
+
const picked = /^\d+$/.test(answer) ? candidates[Number(answer) - 1] : void 0;
|
|
1485
|
+
if (picked) return picked.key;
|
|
1486
|
+
if (validSshPublicKey(answer)) return answer;
|
|
1487
|
+
io.write("That is not a public key. It starts with ssh-ed25519, ssh-rsa, ecdsa-sha2-... or sk-...\n");
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Ask for every value not already given on the command line. Questions come in
|
|
1492
|
+
* the order name, image, region, size, SSH key; a value given as a flag is
|
|
1493
|
+
* never asked again.
|
|
1494
|
+
*/
|
|
1495
|
+
async function promptCreate(given, deps) {
|
|
1496
|
+
const { io, catalog, keyFiles } = deps;
|
|
1497
|
+
const name = given.name ?? await askName(io);
|
|
1498
|
+
const image = given.image ?? await askImage(io, catalog);
|
|
1499
|
+
const region = given.region ?? await askRegion(io, catalog);
|
|
1500
|
+
const vcpu = given.vcpu ?? await askSize(io, "vCPUs", DEFAULT_RESOURCES.vcpu);
|
|
1501
|
+
const ram = given.ram ?? await askSize(io, "RAM in GB", DEFAULT_RESOURCES.ram);
|
|
1502
|
+
const disk = given.disk ?? await askSize(io, "Disk in GB", DEFAULT_RESOURCES.disk);
|
|
1503
|
+
return {
|
|
1504
|
+
name,
|
|
1505
|
+
image,
|
|
1506
|
+
sshKey: given.sshKey ?? await askSshKey(io, keyFiles),
|
|
1507
|
+
...region ? { region } : {},
|
|
1508
|
+
vcpu,
|
|
1509
|
+
ram,
|
|
1510
|
+
disk
|
|
1511
|
+
};
|
|
1512
|
+
}
|
|
1513
|
+
/** One line that says what is about to be created. */
|
|
1514
|
+
function summarize(a) {
|
|
1515
|
+
const parts = [
|
|
1516
|
+
a.image,
|
|
1517
|
+
a.region ? `region ${a.region}` : "region chosen by Krova",
|
|
1518
|
+
`${a.vcpu} vCPU`,
|
|
1519
|
+
`${a.ram} GB RAM`,
|
|
1520
|
+
`${a.disk} GB disk`
|
|
1521
|
+
];
|
|
1522
|
+
return `Create cube "${a.name}" (${parts.join(", ")})`;
|
|
1523
|
+
}
|
|
1524
|
+
/** `[Y/n]`: Enter or y/yes is yes, n/no is no, anything else asks again. */
|
|
1525
|
+
async function confirmCreate(io, summary) {
|
|
1526
|
+
for (;;) {
|
|
1527
|
+
const answer = (await io.ask(`${summary}? [Y/n] `)).trim().toLowerCase();
|
|
1528
|
+
if (answer === "" || answer === "y" || answer === "yes") return true;
|
|
1529
|
+
if (answer === "n" || answer === "no") return false;
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
676
1532
|
// src/lib/resolve.ts
|
|
677
1533
|
/** Resolve a cube name-or-id to an id (parity with the Go resolveCube):
|
|
678
1534
|
* exact id wins; else exactly one exact name match; else a clear error. */
|
|
@@ -685,6 +1541,156 @@ async function resolveCube(client, spaceId, ref) {
|
|
|
685
1541
|
const ids = byName.map((c) => c.id).join(", ");
|
|
686
1542
|
throw new Error(`cube name "${ref}" is ambiguous: it matches ${byName.length} cubes (${ids}) — use the cube ID instead`);
|
|
687
1543
|
}
|
|
1544
|
+
// src/lib/safety.ts
|
|
1545
|
+
/** The real terminal state of this process. */
|
|
1546
|
+
function currentTTY() {
|
|
1547
|
+
return {
|
|
1548
|
+
stdin: Boolean(process.stdin.isTTY),
|
|
1549
|
+
stdout: Boolean(process.stdout.isTTY)
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Whether a destructive or risky command should stop and ask first.
|
|
1554
|
+
*
|
|
1555
|
+
* Only a person at a terminal is asked: when stdin or stdout is piped (a script,
|
|
1556
|
+
* CI, an agent), the command proceeds exactly as it always did, so adding a
|
|
1557
|
+
* prompt never turns a working script into a hung one. `--yes` always skips it.
|
|
1558
|
+
*/
|
|
1559
|
+
function shouldConfirm(opts, tty = currentTTY()) {
|
|
1560
|
+
if (opts.yes) return false;
|
|
1561
|
+
return tty.stdin && tty.stdout;
|
|
1562
|
+
}
|
|
1563
|
+
/** Dotted-quad IPv4 to a 32-bit number, or null when it is not one. */
|
|
1564
|
+
function ipv4ToNumber(addr) {
|
|
1565
|
+
const parts = addr.split(".");
|
|
1566
|
+
if (parts.length !== 4) return null;
|
|
1567
|
+
let n = 0;
|
|
1568
|
+
for (const part of parts) {
|
|
1569
|
+
if (!/^\d{1,3}$/.test(part) || Number(part) > 255) return null;
|
|
1570
|
+
n = n * 256 + Number(part);
|
|
1571
|
+
}
|
|
1572
|
+
return n;
|
|
1573
|
+
}
|
|
1574
|
+
/**
|
|
1575
|
+
* Whether a whitelist leaves the port open to every address.
|
|
1576
|
+
*
|
|
1577
|
+
* Open means: no entries at all; any entry whose prefix length is numerically 0
|
|
1578
|
+
* (`0.0.0.0/0`, `::/0`, and spellings such as `0.0.0.0/00` or `1.2.3.4/0`); or
|
|
1579
|
+
* the two IPv4 halves `0.0.0.0/1` and `128.0.0.0/1` together, which cover the
|
|
1580
|
+
* whole IPv4 space.
|
|
1581
|
+
*/
|
|
1582
|
+
function isOpenWhitelist(whitelist) {
|
|
1583
|
+
const entries = whitelist.map((w) => w.trim()).filter(Boolean);
|
|
1584
|
+
if (entries.length === 0) return true;
|
|
1585
|
+
const halves = /* @__PURE__ */ new Set();
|
|
1586
|
+
for (const entry of entries) {
|
|
1587
|
+
const slash = entry.lastIndexOf("/");
|
|
1588
|
+
if (slash < 0) continue;
|
|
1589
|
+
const prefix = entry.slice(slash + 1).trim();
|
|
1590
|
+
if (!/^\d+$/.test(prefix)) continue;
|
|
1591
|
+
const length = Number(prefix);
|
|
1592
|
+
if (length === 0) return true;
|
|
1593
|
+
if (length === 1) {
|
|
1594
|
+
const n = ipv4ToNumber(entry.slice(0, slash).trim());
|
|
1595
|
+
if (n !== null) halves.add(n >= 2 ** 31 ? 1 : 0);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
return halves.size === 2;
|
|
1599
|
+
}
|
|
1600
|
+
function publicExposureWarning(cube, cubePort) {
|
|
1601
|
+
return `Warning: port ${cubePort} on ${cube} will be reachable from the whole internet. Limit it with --whitelist <cidr>, or use a private tunnel instead: krova tunnel ${cube} ${cubePort}.`;
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Read a y/N answer. The prompt goes to stderr so `--json` stdout stays pure
|
|
1605
|
+
* JSON. Anything but y or yes counts as no. If the input ends before an answer
|
|
1606
|
+
* (Ctrl+D), the answer is no and the exit code is set to 1: nobody chose to
|
|
1607
|
+
* abort, so a script wrapping a terminal session must not read it as success.
|
|
1608
|
+
* The streams are injectable for tests.
|
|
1609
|
+
*/
|
|
1610
|
+
function confirm(question, io = {
|
|
1611
|
+
input: process.stdin,
|
|
1612
|
+
output: process.stderr
|
|
1613
|
+
}) {
|
|
1614
|
+
return new Promise((resolve) => {
|
|
1615
|
+
const rl = readline.createInterface({
|
|
1616
|
+
input: io.input,
|
|
1617
|
+
output: io.output
|
|
1618
|
+
});
|
|
1619
|
+
let answered = false;
|
|
1620
|
+
rl.on("close", () => {
|
|
1621
|
+
if (answered) return;
|
|
1622
|
+
process.exitCode = 1;
|
|
1623
|
+
resolve(false);
|
|
1624
|
+
});
|
|
1625
|
+
rl.question(question, (answer) => {
|
|
1626
|
+
answered = true;
|
|
1627
|
+
rl.close();
|
|
1628
|
+
resolve(/^y(es)?$/i.test(answer.trim()));
|
|
1629
|
+
});
|
|
1630
|
+
});
|
|
1631
|
+
}
|
|
1632
|
+
/** Print the abort notice: stdout for people, stderr under `--json`. */
|
|
1633
|
+
function printAborted(json) {
|
|
1634
|
+
(json ? process.stderr : process.stdout).write("Aborted.\n");
|
|
1635
|
+
}
|
|
1636
|
+
// src/lib/spinner.ts
|
|
1637
|
+
const FRAMES = [
|
|
1638
|
+
"⠋",
|
|
1639
|
+
"⠙",
|
|
1640
|
+
"⠹",
|
|
1641
|
+
"⠸",
|
|
1642
|
+
"⠼",
|
|
1643
|
+
"⠴",
|
|
1644
|
+
"⠦",
|
|
1645
|
+
"⠧",
|
|
1646
|
+
"⠇",
|
|
1647
|
+
"⠏"
|
|
1648
|
+
];
|
|
1649
|
+
const CLEAR_LINE = "\r\x1B[K";
|
|
1650
|
+
const NOOP = { stop() {} };
|
|
1651
|
+
/**
|
|
1652
|
+
* Whether a spinner may be drawn: only on an interactive stderr, and never
|
|
1653
|
+
* when the command prints JSON (the caller passes `json`).
|
|
1654
|
+
*/
|
|
1655
|
+
function spinnerEnabled(json, stream = process.stderr) {
|
|
1656
|
+
return Boolean(stream.isTTY) && !json;
|
|
1657
|
+
}
|
|
1658
|
+
/**
|
|
1659
|
+
* Start a tiny stderr spinner with `label`. Returns a no-op when stderr is not
|
|
1660
|
+
* a TTY or `json` is set, so piped and scripted output never changes.
|
|
1661
|
+
* The line is cleared by `stop()` and, as a backstop, when the process exits.
|
|
1662
|
+
*/
|
|
1663
|
+
function startSpinner(label, opts = {}) {
|
|
1664
|
+
const stream = opts.stream ?? process.stderr;
|
|
1665
|
+
if (!spinnerEnabled(Boolean(opts.json), stream)) return NOOP;
|
|
1666
|
+
let i = 0;
|
|
1667
|
+
let active = true;
|
|
1668
|
+
const draw = () => stream.write(`${CLEAR_LINE}${FRAMES[i++ % FRAMES.length]} ${label}`);
|
|
1669
|
+
const clear = () => stream.write(CLEAR_LINE);
|
|
1670
|
+
const onExit = () => {
|
|
1671
|
+
if (active) clear();
|
|
1672
|
+
};
|
|
1673
|
+
draw();
|
|
1674
|
+
const timer = setInterval(draw, 80);
|
|
1675
|
+
timer.unref();
|
|
1676
|
+
process.once("exit", onExit);
|
|
1677
|
+
return { stop() {
|
|
1678
|
+
if (!active) return;
|
|
1679
|
+
active = false;
|
|
1680
|
+
clearInterval(timer);
|
|
1681
|
+
process.removeListener("exit", onExit);
|
|
1682
|
+
clear();
|
|
1683
|
+
} };
|
|
1684
|
+
}
|
|
1685
|
+
/** Run `fn` with a spinner that is cleared on success and on failure. */
|
|
1686
|
+
async function withSpinner(label, opts, fn) {
|
|
1687
|
+
const spinner = startSpinner(label, opts);
|
|
1688
|
+
try {
|
|
1689
|
+
return await fn();
|
|
1690
|
+
} finally {
|
|
1691
|
+
spinner.stop();
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
688
1694
|
// src/commands/cubes.ts
|
|
689
1695
|
function listCmd() {
|
|
690
1696
|
return new Command("list").aliases(["ls"]).description("list Cubes in the space").action(async (_opts, cmd) => {
|
|
@@ -733,36 +1739,114 @@ function getCmd() {
|
|
|
733
1739
|
["RAM (GB)", String(cube.resources.ramGb)],
|
|
734
1740
|
["Disk (GB)", String(cube.resources.diskGb)],
|
|
735
1741
|
["Public IPv4", cube.publicIpv4 ?? "—"],
|
|
736
|
-
["Cost/hour", `$${cube.costPerHour}`]
|
|
1742
|
+
["Cost/hour", `$${cube.costPerHour}`],
|
|
1743
|
+
["Idle timeout", describeIdleTimeout(cube.idleTimeoutMinutes)],
|
|
1744
|
+
["Last active", cube.lastActiveAt ?? "-"]
|
|
737
1745
|
]);
|
|
738
1746
|
});
|
|
739
1747
|
}
|
|
740
|
-
|
|
741
|
-
|
|
1748
|
+
/**
|
|
1749
|
+
* Build the POST /cubes body. Validates resources client-side so bad input
|
|
1750
|
+
* fails with a clear message rather than being coerced to NaN, then JSON null,
|
|
1751
|
+
* then a generic server 400.
|
|
1752
|
+
*/
|
|
1753
|
+
function buildCreateBody(input) {
|
|
1754
|
+
const posInt = (flag, raw) => {
|
|
1755
|
+
const n = Number(raw);
|
|
1756
|
+
if (!Number.isInteger(n) || n <= 0) throw new Error(`--${flag} must be a positive integer (got "${raw}").`);
|
|
1757
|
+
return n;
|
|
1758
|
+
};
|
|
1759
|
+
const body = {
|
|
1760
|
+
name: input.name,
|
|
1761
|
+
image: input.image,
|
|
1762
|
+
sshPublicKey: input.sshKey,
|
|
1763
|
+
resources: {
|
|
1764
|
+
vcpu: posInt("vcpu", input.vcpu),
|
|
1765
|
+
ramGb: posInt("ram", input.ram),
|
|
1766
|
+
diskGb: posInt("disk", input.disk)
|
|
1767
|
+
}
|
|
1768
|
+
};
|
|
1769
|
+
if (input.region) body.region = input.region;
|
|
1770
|
+
if (input.userData) body.userData = input.userData;
|
|
1771
|
+
if (input.terminationProtection) body.terminationProtection = true;
|
|
1772
|
+
if (input.idleTimeoutMinutes !== void 0) body.idleTimeoutMinutes = input.idleTimeoutMinutes;
|
|
1773
|
+
return body;
|
|
1774
|
+
}
|
|
1775
|
+
const defaultCreateDeps = {
|
|
1776
|
+
interactive: (json) => isInteractive({ json }),
|
|
1777
|
+
makeIO: createReadlineIO,
|
|
1778
|
+
keyFiles: defaultKeyFiles
|
|
1779
|
+
};
|
|
1780
|
+
const REQUIRED_CREATE_FLAGS = [
|
|
1781
|
+
["--name", "name"],
|
|
1782
|
+
["--image", "image"],
|
|
1783
|
+
["--ssh-key", "sshKey"]
|
|
1784
|
+
];
|
|
1785
|
+
function createCmd(deps = defaultCreateDeps) {
|
|
1786
|
+
return new Command("create").description("provision a new Cube (in a terminal, asks for anything you leave out)").option("--name <name>", "cube name").option("--image <slug>", "OS image slug (see `krova images`)").option("--ssh-key <key>", "SSH public key written to authorized_keys").option("--vcpu <n>", "number of vCPUs", DEFAULT_RESOURCES.vcpu).option("--ram <gb>", "RAM in GB", DEFAULT_RESOURCES.ram).option("--disk <gb>", "disk size in GB", DEFAULT_RESOURCES.disk).option("--region <slug>", "region slug (see `krova regions`)").option("--user-data <script>", "cloud-init script").option("--idempotency-key <key>", "idempotency key (24h dedupe)").option("--termination-protection", "turn on termination protection (the cube cannot be deleted until turned off)", false).option("--idle-timeout <minutes>", IDLE_TIMEOUT_HELP).option("-y, --yes", "skip the confirmation after the prompts").action(async (opts, cmd) => {
|
|
1787
|
+
const idleTimeoutMinutes = opts.idleTimeout === void 0 ? void 0 : parseIdleTimeout(opts.idleTimeout);
|
|
1788
|
+
const missing = REQUIRED_CREATE_FLAGS.filter(([, key]) => opts[key] === void 0);
|
|
1789
|
+
const globals = cmd.optsWithGlobals();
|
|
1790
|
+
const wantsJson = Boolean(globals.json) || globals.output === "json";
|
|
1791
|
+
const prompting = missing.length > 0 && deps.interactive(wantsJson);
|
|
1792
|
+
if (missing.length > 0 && !prompting) {
|
|
1793
|
+
const flags = cmd.options.find((o) => o.long === missing[0]?.[0])?.flags;
|
|
1794
|
+
cmd.error(`error: required option '${flags}' not specified`, { code: "commander.missingMandatoryOptionValue" });
|
|
1795
|
+
}
|
|
742
1796
|
const rt = getRuntime(cmd);
|
|
743
1797
|
const client = makeClient(rt.res);
|
|
744
1798
|
const space = await resolveSpace(rt);
|
|
745
|
-
const
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
1799
|
+
const out = deps.stdout ?? ((text) => void process.stdout.write(text));
|
|
1800
|
+
const build = (v) => buildCreateBody({
|
|
1801
|
+
...v,
|
|
1802
|
+
userData: opts.userData,
|
|
1803
|
+
terminationProtection: opts.terminationProtection,
|
|
1804
|
+
idleTimeoutMinutes
|
|
1805
|
+
});
|
|
1806
|
+
let body;
|
|
1807
|
+
if (prompting) {
|
|
1808
|
+
const io = deps.makeIO();
|
|
1809
|
+
try {
|
|
1810
|
+
const given = (key) => cmd.getOptionValueSource(key) === "default" ? void 0 : opts[key];
|
|
1811
|
+
const answers = await promptCreate({
|
|
1812
|
+
name: opts.name,
|
|
1813
|
+
image: opts.image,
|
|
1814
|
+
sshKey: opts.sshKey,
|
|
1815
|
+
region: opts.region,
|
|
1816
|
+
vcpu: given("vcpu"),
|
|
1817
|
+
ram: given("ram"),
|
|
1818
|
+
disk: given("disk")
|
|
1819
|
+
}, {
|
|
1820
|
+
io,
|
|
1821
|
+
catalog: deps.catalog ? deps.catalog(client) : client.catalog,
|
|
1822
|
+
keyFiles: deps.keyFiles()
|
|
1823
|
+
});
|
|
1824
|
+
body = build(answers);
|
|
1825
|
+
if (!opts.yes && !await confirmCreate(io, summarize(answers))) {
|
|
1826
|
+
out("Aborted.\n");
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
} catch (err) {
|
|
1830
|
+
if (!(err instanceof PromptAbortError)) throw err;
|
|
1831
|
+
out("\nAborted.\n");
|
|
1832
|
+
process.exitCode = 1;
|
|
1833
|
+
return;
|
|
1834
|
+
} finally {
|
|
1835
|
+
io.close();
|
|
1836
|
+
}
|
|
1837
|
+
} else body = build({
|
|
751
1838
|
name: opts.name,
|
|
752
1839
|
image: opts.image,
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
};
|
|
760
|
-
if (
|
|
761
|
-
if (opts.userData) body.userData = opts.userData;
|
|
762
|
-
if (opts.terminationProtection) body.terminationProtection = true;
|
|
763
|
-
const cube = await client.cubes.create(space, body, opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : void 0);
|
|
1840
|
+
sshKey: opts.sshKey,
|
|
1841
|
+
vcpu: opts.vcpu,
|
|
1842
|
+
ram: opts.ram,
|
|
1843
|
+
disk: opts.disk,
|
|
1844
|
+
region: opts.region
|
|
1845
|
+
});
|
|
1846
|
+
const cube = await withSpinner("Creating cube", { json: rt.json }, () => client.cubes.create(space, body, opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : void 0));
|
|
1847
|
+
if (idleTimeoutMinutes !== void 0 && !idleTimeoutApplied(cube.idleTimeoutMinutes, idleTimeoutMinutes)) process.stderr.write(IDLE_UNSUPPORTED_WARNING);
|
|
764
1848
|
if (rt.json) return printJSON(cube);
|
|
765
|
-
|
|
1849
|
+
out(`Created cube ${cube.id} (${cube.state})\n`);
|
|
766
1850
|
});
|
|
767
1851
|
}
|
|
768
1852
|
function actionCmd(name, past, fn) {
|
|
@@ -779,6 +1863,23 @@ function actionCmd(name, past, fn) {
|
|
|
779
1863
|
process.stdout.write(`${past} cube ${id}\n`);
|
|
780
1864
|
});
|
|
781
1865
|
}
|
|
1866
|
+
function deleteCmd() {
|
|
1867
|
+
return new Command("delete").argument("<cube>", "cube name or ID").option("-y, --yes", "skip the confirmation prompt").description("delete a Cube (permanent)").action(async (cubeRef, opts, cmd) => {
|
|
1868
|
+
const rt = getRuntime(cmd);
|
|
1869
|
+
const client = makeClient(rt.res);
|
|
1870
|
+
const space = await resolveSpace(rt);
|
|
1871
|
+
const id = await resolveCube(client, space, cubeRef);
|
|
1872
|
+
if (shouldConfirm(opts)) {
|
|
1873
|
+
if (!await confirm(`Delete cube ${cubeRef}${cubeRef === id ? "" : ` (${id})`}? This is permanent and cannot be undone. [y/N] `)) return printAborted(rt.json);
|
|
1874
|
+
}
|
|
1875
|
+
await client.cubes.delete(space, id);
|
|
1876
|
+
if (rt.json) return printJSON({
|
|
1877
|
+
id,
|
|
1878
|
+
result: "Deleting"
|
|
1879
|
+
});
|
|
1880
|
+
process.stdout.write(`Deleting cube ${id}\n`);
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
782
1883
|
function restartCmd() {
|
|
783
1884
|
return new Command("restart").argument("<cube>", "cube name or ID").description("restart a Cube (cold restart — picks up a refreshed kernel)").action(async (cubeRef, _opts, cmd) => {
|
|
784
1885
|
const rt = getRuntime(cmd);
|
|
@@ -810,6 +1911,129 @@ function sshPortCmd() {
|
|
|
810
1911
|
`));
|
|
811
1912
|
});
|
|
812
1913
|
}
|
|
1914
|
+
function renameCmd() {
|
|
1915
|
+
return new Command("rename").argument("<cube>", "cube name or ID").argument("<new-name>", "the new name (1 to 64 printable characters)").description("rename a Cube (names do not have to be unique; a running Cube's hostname changes on its next cold restart)").action(async (cubeRef, rawName, _opts, cmd) => {
|
|
1916
|
+
const newName = parseCubeName(rawName);
|
|
1917
|
+
const rt = getRuntime(cmd);
|
|
1918
|
+
const client = makeClient(rt.res);
|
|
1919
|
+
const space = await resolveSpace(rt);
|
|
1920
|
+
const id = await resolveCube(client, space, cubeRef);
|
|
1921
|
+
const cube = await client.cubes.rename(space, id, newName);
|
|
1922
|
+
if (rt.json) return printJSON(cube);
|
|
1923
|
+
process.stdout.write(`Renamed cube ${id} to ${cube.name}\n`);
|
|
1924
|
+
});
|
|
1925
|
+
}
|
|
1926
|
+
const IDLE_TIMEOUT_HELP = "power the Cube off after this many minutes without activity (10 to 10080), or \"off\" (needs a server with the idle-timeout feature)";
|
|
1927
|
+
const IDLE_UNSUPPORTED_WARNING = "Warning: this server did not report the requested idle timeout for the Cube, so --idle-timeout was probably ignored. It needs a server with the idle-timeout feature.\n";
|
|
1928
|
+
/**
|
|
1929
|
+
* Parse `--idle-timeout`: whole minutes from 10 to 10080 (7 days), or `off`
|
|
1930
|
+
* (sent as `null`). Plain decimal digits only, so 1e2, 0x10 and " 20" fail.
|
|
1931
|
+
*/
|
|
1932
|
+
function parseIdleTimeout(raw) {
|
|
1933
|
+
if (raw === "off") return null;
|
|
1934
|
+
const n = Number(raw);
|
|
1935
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(n) || n < 10 || n > 10080) throw new Error("--idle-timeout must be a whole number of minutes from 10 to 10080, or \"off\"");
|
|
1936
|
+
return n;
|
|
1937
|
+
}
|
|
1938
|
+
/**
|
|
1939
|
+
* Did the server apply the requested timeout? A present field must equal the request. An absent field means
|
|
1940
|
+
* the server omitted it (an older server, or a null it left out): that only counts as applied for `off`.
|
|
1941
|
+
*/
|
|
1942
|
+
function idleTimeoutApplied(returned, requested) {
|
|
1943
|
+
return returned === void 0 ? requested === null : returned === requested;
|
|
1944
|
+
}
|
|
1945
|
+
/** `off` for a Cube with no timeout, `N min` for one with a timeout, `-` when the server does not say. */
|
|
1946
|
+
function describeIdleTimeout(minutes) {
|
|
1947
|
+
if (minutes === void 0) return "-";
|
|
1948
|
+
return minutes === null ? "off" : `${minutes} min`;
|
|
1949
|
+
}
|
|
1950
|
+
function updateCmd() {
|
|
1951
|
+
return new Command("update").argument("<cube>", "cube name or ID").option("--idle-timeout <minutes>", IDLE_TIMEOUT_HELP).description("change a Cube's settings (idle auto-stop; `rename`, `resize` and `protect` cover the rest)").action(async (cubeRef, opts, cmd) => {
|
|
1952
|
+
if (opts.idleTimeout === void 0) throw new Error("nothing to update: pass --idle-timeout <minutes|off>");
|
|
1953
|
+
const minutes = parseIdleTimeout(opts.idleTimeout);
|
|
1954
|
+
const rt = getRuntime(cmd);
|
|
1955
|
+
const client = makeClient(rt.res);
|
|
1956
|
+
const space = await resolveSpace(rt);
|
|
1957
|
+
const id = await resolveCube(client, space, cubeRef);
|
|
1958
|
+
const cube = await client.cubes.setIdleTimeout(space, id, minutes);
|
|
1959
|
+
if (!idleTimeoutApplied(cube.idleTimeoutMinutes, minutes)) throw new Error(cube.idleTimeoutMinutes === void 0 ? "the server did not apply --idle-timeout (it needs a server with the idle-timeout feature)" : `the server kept the idle timeout at ${describeIdleTimeout(cube.idleTimeoutMinutes)}`);
|
|
1960
|
+
if (rt.json) return printJSON(cube);
|
|
1961
|
+
process.stdout.write(minutes === null ? `Turned off idle auto-stop for cube ${id}\n` : `Set idle auto-stop for cube ${id} to ${minutes} min\n`);
|
|
1962
|
+
});
|
|
1963
|
+
}
|
|
1964
|
+
/** Parse a `--vcpu`/`--ram`/`--disk` value. `integer` rejects fractions (RAM may be fractional). */
|
|
1965
|
+
function parseSize(flag, raw, integer) {
|
|
1966
|
+
const n = Number(raw);
|
|
1967
|
+
if (!(integer ? /^\d+$/ : /^\d+(\.\d+)?$/).test(raw) || !Number.isFinite(n) || n <= 0) throw new Error(`${flag} must be a positive ${integer ? "whole number" : "number"}`);
|
|
1968
|
+
return n;
|
|
1969
|
+
}
|
|
1970
|
+
/** Trim a new Cube name and check it locally: 1 to 64 characters, no control, line-separator or bidi characters. */
|
|
1971
|
+
function parseCubeName(raw) {
|
|
1972
|
+
const name = raw.trim();
|
|
1973
|
+
const length = [...name].length;
|
|
1974
|
+
if (length < 1 || length > 64 || /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069]/u.test(name)) throw new Error("the new name must be 1 to 64 printable characters");
|
|
1975
|
+
return name;
|
|
1976
|
+
}
|
|
1977
|
+
const RESIZE_DIMENSIONS = [
|
|
1978
|
+
{
|
|
1979
|
+
key: "vcpu",
|
|
1980
|
+
label: "vCPU",
|
|
1981
|
+
unit: ""
|
|
1982
|
+
},
|
|
1983
|
+
{
|
|
1984
|
+
key: "ramGb",
|
|
1985
|
+
label: "RAM",
|
|
1986
|
+
unit: " GB"
|
|
1987
|
+
},
|
|
1988
|
+
{
|
|
1989
|
+
key: "diskGb",
|
|
1990
|
+
label: "Disk",
|
|
1991
|
+
unit: " GB"
|
|
1992
|
+
}
|
|
1993
|
+
];
|
|
1994
|
+
function describeSize(size) {
|
|
1995
|
+
return `${size.vcpu} vCPU, ${size.ramGb} GB RAM, ${size.diskGb} GB disk`;
|
|
1996
|
+
}
|
|
1997
|
+
function resizeCmd() {
|
|
1998
|
+
return new Command("resize").argument("<cube>", "cube name or ID").option("--vcpu <n>", "new vCPU count").option("--ram <gb>", "new RAM in GB (fractions allowed)").option("--disk <gb>", "new disk in GB (disk can only grow)").option("-y, --yes", "skip the confirmation prompt").description("change a Cube's vCPU, RAM and/or disk; the API says whether it is applied live or restarts the Cube").action(async (cubeRef, opts, cmd) => {
|
|
1999
|
+
const resources = {};
|
|
2000
|
+
if (opts.vcpu !== void 0) resources.vcpu = parseSize("--vcpu", opts.vcpu, true);
|
|
2001
|
+
if (opts.ram !== void 0) resources.ramGb = parseSize("--ram", opts.ram, false);
|
|
2002
|
+
if (opts.disk !== void 0) resources.diskGb = parseSize("--disk", opts.disk, true);
|
|
2003
|
+
if (Object.keys(resources).length === 0) throw new Error("give at least one of --vcpu, --ram or --disk");
|
|
2004
|
+
const rt = getRuntime(cmd);
|
|
2005
|
+
const client = makeClient(rt.res);
|
|
2006
|
+
const space = await resolveSpace(rt);
|
|
2007
|
+
const id = await resolveCube(client, space, cubeRef);
|
|
2008
|
+
if (shouldConfirm(opts)) {
|
|
2009
|
+
const current = (await client.cubes.get(space, id)).resources;
|
|
2010
|
+
const target = {
|
|
2011
|
+
...current,
|
|
2012
|
+
...resources
|
|
2013
|
+
};
|
|
2014
|
+
if (!await confirm(`Resize cube ${cubeRef}${cubeRef === id ? "" : ` (${id})`} from ${describeSize(current)} to ${describeSize(target)}? A RAM decrease, or a vCPU change on a Cube that cannot hotplug, restarts the Cube. [y/N] `)) return printAborted(rt.json);
|
|
2015
|
+
}
|
|
2016
|
+
let result;
|
|
2017
|
+
try {
|
|
2018
|
+
result = await client.cubes.resize(space, id, resources);
|
|
2019
|
+
} catch (err) {
|
|
2020
|
+
if (err instanceof KrovaError && err.status === 400 && err.body?.code === "insufficient_host_capacity") Object.assign(err, { hint: "The server this Cube runs on has no room for that size. Try a smaller size, or contact support." });
|
|
2021
|
+
throw err;
|
|
2022
|
+
}
|
|
2023
|
+
if (rt.json) return printJSON({
|
|
2024
|
+
id,
|
|
2025
|
+
...result
|
|
2026
|
+
});
|
|
2027
|
+
process.stdout.write(`Resize queued for cube ${id} (job ${result.jobId})\n`);
|
|
2028
|
+
for (const { key, label, unit } of RESIZE_DIMENSIONS) {
|
|
2029
|
+
const from = result.previous[key];
|
|
2030
|
+
const to = result.requested[key];
|
|
2031
|
+
process.stdout.write(` ${label}: ${from === to ? `${to}${unit} (unchanged)` : `${from}${unit} -> ${to}${unit}`}\n`);
|
|
2032
|
+
}
|
|
2033
|
+
process.stdout.write(result.requiresRestart ? "The Cube restarts to apply this change.\n" : "Applied live: the Cube does not restart.\n");
|
|
2034
|
+
process.stdout.write(`The Cube keeps its current size until the change is applied. Check with: krova cubes get ${id}\n`);
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
813
2037
|
/**
|
|
814
2038
|
* Toggle a Cube's termination-protection flag. Shared by `protect` and
|
|
815
2039
|
* `unprotect`; only the boolean `enabled` differs.
|
|
@@ -832,9 +2056,12 @@ function cubesCommand() {
|
|
|
832
2056
|
cubes.addCommand(createCmd());
|
|
833
2057
|
cubes.addCommand(actionCmd("power-off", "Powering off", (c, s, id) => c.powerOff(s, id)));
|
|
834
2058
|
cubes.addCommand(actionCmd("wake", "Starting", (c, s, id) => c.wake(s, id)));
|
|
835
|
-
cubes.addCommand(
|
|
2059
|
+
cubes.addCommand(deleteCmd());
|
|
836
2060
|
cubes.addCommand(restartCmd());
|
|
837
2061
|
cubes.addCommand(sshPortCmd());
|
|
2062
|
+
cubes.addCommand(updateCmd());
|
|
2063
|
+
cubes.addCommand(renameCmd());
|
|
2064
|
+
cubes.addCommand(resizeCmd());
|
|
838
2065
|
cubes.addCommand(setProtectionCmd("protect", true, "Protected"));
|
|
839
2066
|
cubes.addCommand(setProtectionCmd("unprotect", false, "Unprotected"));
|
|
840
2067
|
return cubes;
|
|
@@ -985,26 +2212,67 @@ function domainsCommand() {
|
|
|
985
2212
|
}
|
|
986
2213
|
// src/commands/login.ts
|
|
987
2214
|
const BROWSER_UNAVAILABLE = "Browser login isn't enabled on this server yet — run `krova auth login` to paste an API key from https://krova.cloud";
|
|
988
|
-
/**
|
|
989
|
-
|
|
2215
|
+
/** Characters that never appear in a device-login URL and that cmd.exe treats as operators. */
|
|
2216
|
+
const SHELL_METACHARS = /[&|^<>"]/;
|
|
2217
|
+
/**
|
|
2218
|
+
* Only open https URLs, or http to a loopback host, and return the normalized href.
|
|
2219
|
+
* The device-login URL is `<base>/cli?code=<ALNUM-ALNUM>`: it never needs `& | ^ < > "`, so a URL
|
|
2220
|
+
* carrying one is refused on every platform. `%` is refused on Windows only, where it expands
|
|
2221
|
+
* environment variables in some launchers; the real URL never contains it (the code is alphanumeric).
|
|
2222
|
+
* A refused URL is not opened: the caller prints it for the user to open by hand.
|
|
2223
|
+
*/
|
|
2224
|
+
function safeBrowserURL(raw, platform = process.platform) {
|
|
990
2225
|
let u;
|
|
991
2226
|
try {
|
|
992
2227
|
u = new URL(raw);
|
|
993
2228
|
} catch {
|
|
994
2229
|
return null;
|
|
995
2230
|
}
|
|
996
|
-
|
|
997
|
-
if (u.protocol === "
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
2231
|
+
const loopbackHttp = u.protocol === "http:" && (u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]");
|
|
2232
|
+
if (!(u.protocol === "https:" && u.hostname || loopbackHttp)) return null;
|
|
2233
|
+
const href = u.href;
|
|
2234
|
+
if (SHELL_METACHARS.test(href)) return null;
|
|
2235
|
+
if (platform === "win32" && href.includes("%")) return null;
|
|
2236
|
+
return href;
|
|
2237
|
+
}
|
|
2238
|
+
/** Removes C0, DEL and C1 control characters (ESC included) so a server string cannot drive the terminal. */
|
|
2239
|
+
function stripControlChars(s) {
|
|
2240
|
+
return s.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
|
|
2241
|
+
}
|
|
2242
|
+
/** The URL as it is shown to the user: the normalized href when it parses, else the raw string, with control characters stripped. */
|
|
2243
|
+
function displayURL(raw) {
|
|
2244
|
+
try {
|
|
2245
|
+
return stripControlChars(new URL(raw).href);
|
|
2246
|
+
} catch {
|
|
2247
|
+
return stripControlChars(raw);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
/**
|
|
2251
|
+
* How to open `href` in the default browser. Never uses a shell: on Windows `rundll32` is a real
|
|
2252
|
+
* executable, so cmd.exe never parses the URL.
|
|
2253
|
+
*/
|
|
2254
|
+
function browserSpawnPlan(href, platform = process.platform) {
|
|
2255
|
+
if (platform === "win32") return {
|
|
2256
|
+
command: "rundll32",
|
|
2257
|
+
args: ["url.dll,FileProtocolHandler", href],
|
|
2258
|
+
options: {
|
|
2259
|
+
stdio: "ignore",
|
|
2260
|
+
detached: true,
|
|
2261
|
+
windowsHide: true
|
|
2262
|
+
}
|
|
2263
|
+
};
|
|
2264
|
+
return {
|
|
2265
|
+
command: platform === "darwin" ? "open" : "xdg-open",
|
|
2266
|
+
args: [href],
|
|
2267
|
+
options: {
|
|
2268
|
+
stdio: "ignore",
|
|
2269
|
+
detached: true
|
|
2270
|
+
}
|
|
2271
|
+
};
|
|
2272
|
+
}
|
|
2273
|
+
function openBrowser(href) {
|
|
2274
|
+
const plan = browserSpawnPlan(href);
|
|
2275
|
+
const child = spawn(plan.command, plan.args, plan.options);
|
|
1008
2276
|
child.on("error", () => {});
|
|
1009
2277
|
child.unref();
|
|
1010
2278
|
}
|
|
@@ -1022,44 +2290,49 @@ function loginCommand() {
|
|
|
1022
2290
|
if (start.status === 404) throw new Error(BROWSER_UNAVAILABLE);
|
|
1023
2291
|
if (start.status !== 200 || !start.data?.deviceCode) throw new Error(`device login failed to start (HTTP ${start.status})`);
|
|
1024
2292
|
const s = start.data;
|
|
1025
|
-
process.stdout.write(`Your verification code is: ${s.userCode}\n`);
|
|
2293
|
+
process.stdout.write(`Your verification code is: ${stripControlChars(String(s.userCode ?? ""))}\n`);
|
|
1026
2294
|
const target = s.verificationUriComplete || s.verificationUri;
|
|
1027
2295
|
const safe = safeBrowserURL(target);
|
|
1028
2296
|
if (safe && opts.browser !== false) {
|
|
1029
2297
|
process.stdout.write(`Opening ${safe} …\n`);
|
|
1030
2298
|
openBrowser(safe);
|
|
1031
|
-
} else
|
|
2299
|
+
} else {
|
|
2300
|
+
process.stdout.write(`Open this URL to approve the login:\n ${displayURL(target)}\n`);
|
|
2301
|
+
if (!safe) process.stdout.write("It was not opened automatically because it contains characters that are unsafe to pass to the system opener.\n");
|
|
2302
|
+
}
|
|
1032
2303
|
const intervalMs = Math.max((s.interval || 5) * 1e3, 5e3);
|
|
1033
2304
|
const deadline = Date.now() + Math.max(s.expiresIn || 600, 1) * 1e3;
|
|
1034
|
-
process.stdout.write("Waiting for approval…\n");
|
|
1035
|
-
for (
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
path: "/auth/cli/poll",
|
|
1042
|
-
body: { deviceCode: s.deviceCode },
|
|
1043
|
-
timeoutMs: rt.timeoutMs
|
|
1044
|
-
});
|
|
1045
|
-
if (poll.status === 200) {
|
|
1046
|
-
if (!poll.data?.apiKey) throw new Error("login succeeded but no API key was returned");
|
|
1047
|
-
const { ctxName, spaceName } = await persistLogin({
|
|
1048
|
-
apiKey: poll.data.apiKey,
|
|
2305
|
+
if (!spinnerEnabled(rt.json)) process.stdout.write("Waiting for approval…\n");
|
|
2306
|
+
const approved = await withSpinner("Waiting for approval", { json: rt.json }, async () => {
|
|
2307
|
+
for (;;) {
|
|
2308
|
+
if (Date.now() >= deadline) throw new Error("login timed out: the verification code expired before it was approved");
|
|
2309
|
+
await sleep(intervalMs);
|
|
2310
|
+
const poll = await rawRequest({
|
|
2311
|
+
method: "POST",
|
|
1049
2312
|
baseUrl,
|
|
1050
|
-
|
|
1051
|
-
|
|
2313
|
+
path: "/auth/cli/poll",
|
|
2314
|
+
body: { deviceCode: s.deviceCode },
|
|
1052
2315
|
timeoutMs: rt.timeoutMs
|
|
1053
2316
|
});
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
2317
|
+
if (poll.status === 200) {
|
|
2318
|
+
if (!poll.data?.apiKey) throw new Error("login succeeded but no API key was returned");
|
|
2319
|
+
return poll.data;
|
|
2320
|
+
}
|
|
2321
|
+
if (poll.status === 202 || poll.status === 425 || poll.status === 428) continue;
|
|
2322
|
+
if (poll.status === 410) throw new Error("login expired: request a new code with `krova login`");
|
|
2323
|
+
if (poll.status === 404) throw new Error(BROWSER_UNAVAILABLE);
|
|
2324
|
+
throw new Error(`login failed while polling (HTTP ${poll.status})`);
|
|
1057
2325
|
}
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
2326
|
+
});
|
|
2327
|
+
const { ctxName, spaceName, stored } = await persistLogin({
|
|
2328
|
+
apiKey: approved.apiKey,
|
|
2329
|
+
baseUrl,
|
|
2330
|
+
spaceId: approved.spaceId,
|
|
2331
|
+
ctxName: opts.context,
|
|
2332
|
+
timeoutMs: rt.timeoutMs
|
|
2333
|
+
});
|
|
2334
|
+
process.stdout.write(`${loginMessage(ctxName, stored)}\n`);
|
|
2335
|
+
if (spaceName) process.stdout.write(`Space: ${spaceName}\n`);
|
|
1063
2336
|
});
|
|
1064
2337
|
}
|
|
1065
2338
|
// src/commands/snapshots.ts
|
|
@@ -1098,11 +2371,15 @@ function snapshotsCommand() {
|
|
|
1098
2371
|
if (rt.json) return printJSON(snap);
|
|
1099
2372
|
process.stdout.write(`Created snapshot ${snap.id} (${snap.status})\n`);
|
|
1100
2373
|
});
|
|
1101
|
-
cmd.command("rm").argument("<cube>", "cube name or ID").argument("<snapshot-id>", "the snapshot ID (see `krova snapshots list`)").description("delete a snapshot").action(async (cubeRef, snapshotId,
|
|
2374
|
+
cmd.command("rm").argument("<cube>", "cube name or ID").argument("<snapshot-id>", "the snapshot ID (see `krova snapshots list`)").option("-y, --yes", "skip the confirmation prompt").description("delete a snapshot (permanent)").action(async (cubeRef, snapshotId, opts, c) => {
|
|
1102
2375
|
const rt = getRuntime(c);
|
|
1103
2376
|
const client = makeClient(rt.res);
|
|
1104
2377
|
const space = await resolveSpace(rt);
|
|
1105
2378
|
const id = await resolveCube(client, space, cubeRef);
|
|
2379
|
+
if (shouldConfirm(opts)) {
|
|
2380
|
+
const name = (await client.snapshots.list(space, id).catch(() => [])).find((s) => s.id === snapshotId)?.name;
|
|
2381
|
+
if (!await confirm(`Delete snapshot ${name ? `"${name}" (${snapshotId})` : snapshotId} of cube ${cubeRef}? This is permanent and cannot be undone. [y/N] `)) return printAborted(rt.json);
|
|
2382
|
+
}
|
|
1106
2383
|
await client.snapshots.delete(space, id, snapshotId);
|
|
1107
2384
|
if (rt.json) return printJSON({
|
|
1108
2385
|
id: snapshotId,
|
|
@@ -1127,7 +2404,8 @@ function snapshotsCommand() {
|
|
|
1127
2404
|
}
|
|
1128
2405
|
// src/lib/ssh.ts
|
|
1129
2406
|
const HOST_BANNED = new Set("@/\\'\"`$;&|<>(){}*?!#=,".split(""));
|
|
1130
|
-
const USER_BANNED = new Set("@/\\'\"`$;&|<>(){}
|
|
2407
|
+
const USER_BANNED = new Set("@/\\'\"`$;&|<>(){}*?!#,:[]".split(""));
|
|
2408
|
+
const DNS_NAME = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
|
1131
2409
|
function validateSSHHost(host) {
|
|
1132
2410
|
const h = host.trim();
|
|
1133
2411
|
if (!h) throw new Error("empty host");
|
|
@@ -1137,6 +2415,7 @@ function validateSSHHost(host) {
|
|
|
1137
2415
|
if (code <= 32 || code === 127) throw new Error("host contains whitespace or control characters");
|
|
1138
2416
|
if (HOST_BANNED.has(r)) throw new Error(`host contains a disallowed character ${JSON.stringify(r)}`);
|
|
1139
2417
|
}
|
|
2418
|
+
if (isIP(h) === 0 && !DNS_NAME.test(h)) throw new Error("host must be an IP address or a DNS hostname");
|
|
1140
2419
|
}
|
|
1141
2420
|
function validateSSHUser(user) {
|
|
1142
2421
|
const u = user.trim();
|
|
@@ -1197,7 +2476,7 @@ function writeKnownHosts(info) {
|
|
|
1197
2476
|
/** Build the ssh argv. `--` is placed immediately before the destination —
|
|
1198
2477
|
* the primary option-injection guard (with the validators above). */
|
|
1199
2478
|
function buildSSHArgs(info, o) {
|
|
1200
|
-
const args = [];
|
|
2479
|
+
const args = [...o.preArgs ?? []];
|
|
1201
2480
|
if (o.knownHosts) args.push("-o", `UserKnownHostsFile=${o.knownHosts}`, "-o", "StrictHostKeyChecking=yes");
|
|
1202
2481
|
if ((o.identity ?? "").trim()) args.push("-i", o.identity);
|
|
1203
2482
|
if (info.port > 0) args.push("-p", String(info.port));
|
|
@@ -1217,6 +2496,471 @@ function execSSH(args) {
|
|
|
1217
2496
|
child.on("exit", (code) => resolve(code ?? 0));
|
|
1218
2497
|
});
|
|
1219
2498
|
}
|
|
2499
|
+
/** Map a child's (code, signal) to a shell-style exit code. */
|
|
2500
|
+
function exitCodeFor(code, signal) {
|
|
2501
|
+
if (code !== null) return code;
|
|
2502
|
+
if (signal) return 128 + (constants$1.signals[signal] ?? 0);
|
|
2503
|
+
return 1;
|
|
2504
|
+
}
|
|
2505
|
+
/** Exec a binary with inherited stdio and resolve to its exit code. A signal
|
|
2506
|
+
* death maps to 128 + the signal number; a missing binary names itself. */
|
|
2507
|
+
function execInherit(bin, args) {
|
|
2508
|
+
return new Promise((resolve, reject) => {
|
|
2509
|
+
const child = spawn(bin, args, { stdio: "inherit" });
|
|
2510
|
+
const forward = (sig) => {
|
|
2511
|
+
child.kill(sig);
|
|
2512
|
+
};
|
|
2513
|
+
const signals = [
|
|
2514
|
+
"SIGINT",
|
|
2515
|
+
"SIGTERM",
|
|
2516
|
+
"SIGHUP"
|
|
2517
|
+
];
|
|
2518
|
+
for (const sig of signals) process.on(sig, forward);
|
|
2519
|
+
const done = () => {
|
|
2520
|
+
for (const sig of signals) process.off(sig, forward);
|
|
2521
|
+
};
|
|
2522
|
+
child.on("error", (err) => {
|
|
2523
|
+
done();
|
|
2524
|
+
if (err.code === "ENOENT") reject(/* @__PURE__ */ new Error(`\`${bin}\` was not found on your PATH`));
|
|
2525
|
+
else reject(err);
|
|
2526
|
+
});
|
|
2527
|
+
child.on("exit", (code, signal) => {
|
|
2528
|
+
done();
|
|
2529
|
+
resolve(exitCodeFor(code, signal));
|
|
2530
|
+
});
|
|
2531
|
+
});
|
|
2532
|
+
}
|
|
2533
|
+
/** Resolve a Cube (name or ID) to its validated SSH endpoint and pin its host
|
|
2534
|
+
* keys. Shared by `ssh`, `tunnel`, `connect`, `psql`, `redis`, `mysql`, `exec`
|
|
2535
|
+
* and `cp`, so every one of them keeps the same strict host-key checking. */
|
|
2536
|
+
async function resolveSshTarget(cmd, cubeRef, o = {}) {
|
|
2537
|
+
const rt = getRuntime(cmd);
|
|
2538
|
+
const client = makeClient(rt.res);
|
|
2539
|
+
const space = await resolveSpace(rt);
|
|
2540
|
+
const id = await resolveCube(client, space, cubeRef);
|
|
2541
|
+
const { status, data } = await rawRequest({
|
|
2542
|
+
method: "GET",
|
|
2543
|
+
baseUrl: rt.res.baseUrl,
|
|
2544
|
+
path: `/spaces/${space}/cubes/${id}/ssh`,
|
|
2545
|
+
apiKey: rt.res.apiKey,
|
|
2546
|
+
timeoutMs: rt.timeoutMs
|
|
2547
|
+
});
|
|
2548
|
+
if (status === 404) throw new Error(`SSH info isn't available on this server yet — try \`krova cubes get ${cubeRef}\` for the Cube's IP and ssh manually`);
|
|
2549
|
+
if (status === 401 || status === 403) throw new Error(`SSH info request was rejected (HTTP ${status})`);
|
|
2550
|
+
if (status !== 200 || !data?.host) throw new Error(`couldn't fetch SSH info (HTTP ${status})`);
|
|
2551
|
+
const info = {
|
|
2552
|
+
host: data.host,
|
|
2553
|
+
port: data.port ?? 0,
|
|
2554
|
+
user: data.user ?? "",
|
|
2555
|
+
hostKeys: data.hostKeys ?? []
|
|
2556
|
+
};
|
|
2557
|
+
validateSSHHost(info.host);
|
|
2558
|
+
validateSSHUser(info.user);
|
|
2559
|
+
if (info.port < 0 || info.port > 65535) throw new Error("invalid ssh port");
|
|
2560
|
+
if (o.requireHostKeys && !info.hostKeys.length) throw new Error("Krova has no recorded host key for this Cube yet; use `krova ssh` to connect interactively");
|
|
2561
|
+
let knownHosts = "";
|
|
2562
|
+
if (info.hostKeys.length) {
|
|
2563
|
+
if (isHostname(info.host) && isUnpinned(info.host, info.port)) process.stderr.write("note: this Cube now has a stable SSH hostname (it stays the same even if the Cube migrates to another server) — pinning it is expected and only happens once.\n");
|
|
2564
|
+
knownHosts = writeKnownHosts(info);
|
|
2565
|
+
} else process.stderr.write("note: this server didn't provide host keys — using ssh trust-on-first-use (host-key checking stays on).\n");
|
|
2566
|
+
return {
|
|
2567
|
+
cubeId: id,
|
|
2568
|
+
info,
|
|
2569
|
+
knownHosts
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
/** Split `<cube>:<path>`. A prefix with a slash in it (`./a:b`, `/tmp/x:y`) is
|
|
2573
|
+
* a local path, and on Windows a one-letter prefix is a drive letter. */
|
|
2574
|
+
function splitRemote(arg) {
|
|
2575
|
+
const i = arg.indexOf(":");
|
|
2576
|
+
if (i <= 0) return void 0;
|
|
2577
|
+
const cube = arg.slice(0, i);
|
|
2578
|
+
if (cube.includes("/") || cube.includes("\\")) return void 0;
|
|
2579
|
+
if (process.platform === "win32" && cube.length === 1) return void 0;
|
|
2580
|
+
return {
|
|
2581
|
+
cube,
|
|
2582
|
+
path: arg.slice(i + 1)
|
|
2583
|
+
};
|
|
2584
|
+
}
|
|
2585
|
+
/** scp reads `a:b` as host `a`; a local path with a colon before its first
|
|
2586
|
+
* slash gets a `./` so it stays local. */
|
|
2587
|
+
function safeLocalPath(p) {
|
|
2588
|
+
const colon = p.indexOf(":");
|
|
2589
|
+
if (process.platform === "win32" && colon === 1) return p;
|
|
2590
|
+
const slash = p.indexOf("/");
|
|
2591
|
+
if (colon !== -1 && (slash === -1 || colon < slash)) return `./${p}`;
|
|
2592
|
+
return p;
|
|
2593
|
+
}
|
|
2594
|
+
/** Decide which side of `krova cp` is the Cube. Exactly one must be. */
|
|
2595
|
+
function parseCpOperands(src, dst) {
|
|
2596
|
+
if (!src || !dst) throw new Error("cp needs a source and a destination");
|
|
2597
|
+
const s = splitRemote(src);
|
|
2598
|
+
const d = splitRemote(dst);
|
|
2599
|
+
if (s && d) throw new Error("cp copies between this machine and a Cube: only one side can be <cube>:<path>");
|
|
2600
|
+
if (!s && !d) throw new Error("one side must be a Cube path like <cube>:<path> (both sides are local)");
|
|
2601
|
+
const remote = s ?? d;
|
|
2602
|
+
if (remote.path.startsWith("-")) throw new Error("a remote path must not start with '-'");
|
|
2603
|
+
if (/[\0\r\n]/.test(remote.path)) throw new Error("a remote path must not contain control characters");
|
|
2604
|
+
return s ? {
|
|
2605
|
+
cube: s.cube,
|
|
2606
|
+
direction: "download",
|
|
2607
|
+
remotePath: s.path,
|
|
2608
|
+
localPath: safeLocalPath(dst)
|
|
2609
|
+
} : {
|
|
2610
|
+
cube: remote.cube,
|
|
2611
|
+
direction: "upload",
|
|
2612
|
+
remotePath: remote.path,
|
|
2613
|
+
localPath: safeLocalPath(src)
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
/** Build the scp argv: strict host keys, `-P` port, and `--` before the operands. */
|
|
2617
|
+
function buildSCPArgs(info, o) {
|
|
2618
|
+
const user = info.user.trim();
|
|
2619
|
+
if (/[:\[\]]/.test(user)) throw new Error("user contains a disallowed character");
|
|
2620
|
+
if (info.host.includes(":") && isIP(info.host) !== 6) throw new Error("host contains a disallowed character");
|
|
2621
|
+
const args = [];
|
|
2622
|
+
if (o.knownHosts) args.push("-o", `UserKnownHostsFile=${o.knownHosts}`, "-o", "StrictHostKeyChecking=yes");
|
|
2623
|
+
if ((o.identity ?? "").trim()) args.push("-i", o.identity);
|
|
2624
|
+
if (info.port > 0) args.push("-P", String(info.port));
|
|
2625
|
+
if (o.recursive) args.push("-r");
|
|
2626
|
+
const host = isIP(info.host) === 6 ? `[${info.host}]` : info.host;
|
|
2627
|
+
const remote = `${user ? `${user}@` : ""}${host}:${o.operands.remotePath}`;
|
|
2628
|
+
const { direction, localPath } = o.operands;
|
|
2629
|
+
args.push("--", ...direction === "upload" ? [localPath, remote] : [remote, localPath]);
|
|
2630
|
+
return args;
|
|
2631
|
+
}
|
|
2632
|
+
// src/lib/tunnel.ts
|
|
2633
|
+
/** The only address a tunnel ever binds. Never 0.0.0.0. */
|
|
2634
|
+
const LOOPBACK = "127.0.0.1";
|
|
2635
|
+
/** Parse a TCP port: digits only, 1 to 65535. */
|
|
2636
|
+
function parsePort(value, label) {
|
|
2637
|
+
const s = String(value ?? "").trim();
|
|
2638
|
+
const n = Number(s);
|
|
2639
|
+
if (!/^\d{1,5}$/.test(s) || !Number.isInteger(n) || n < 1 || n > 65535) throw new Error(`${label} must be a whole number from 1 to 65535`);
|
|
2640
|
+
return n;
|
|
2641
|
+
}
|
|
2642
|
+
/** Parse `[localPort:]cubePort`. The local port defaults to the Cube port. */
|
|
2643
|
+
function parseTunnelSpec(spec) {
|
|
2644
|
+
const m = /^(\d+)(?::(\d+))?$/.exec(String(spec ?? "").trim());
|
|
2645
|
+
if (!m) throw new Error(`invalid port spec "${spec}": use <cubePort> or <localPort>:<cubePort>`);
|
|
2646
|
+
if (m[2] === void 0) {
|
|
2647
|
+
const cubePort = parsePort(m[1], "cube port");
|
|
2648
|
+
return {
|
|
2649
|
+
localPort: cubePort,
|
|
2650
|
+
cubePort
|
|
2651
|
+
};
|
|
2652
|
+
}
|
|
2653
|
+
return {
|
|
2654
|
+
localPort: parsePort(m[1], "local port"),
|
|
2655
|
+
cubePort: parsePort(m[2], "cube port")
|
|
2656
|
+
};
|
|
2657
|
+
}
|
|
2658
|
+
/** Build the tunnel argv: loopback-only bind, no remote command, and ssh exits
|
|
2659
|
+
* if the forward cannot be set up. Host keys stay strictly checked. */
|
|
2660
|
+
function buildTunnelArgs(info, o) {
|
|
2661
|
+
return buildSSHArgs(info, {
|
|
2662
|
+
preArgs: [
|
|
2663
|
+
"-N",
|
|
2664
|
+
"-o",
|
|
2665
|
+
"ExitOnForwardFailure=yes"
|
|
2666
|
+
],
|
|
2667
|
+
identity: o.identity,
|
|
2668
|
+
knownHosts: o.knownHosts,
|
|
2669
|
+
localFwd: [`${LOOPBACK}:${o.localPort}:localhost:${o.cubePort}`]
|
|
2670
|
+
});
|
|
2671
|
+
}
|
|
2672
|
+
/** Ask the OS for a free loopback port (bind to port 0, read it, release it). */
|
|
2673
|
+
function freeLoopbackPort() {
|
|
2674
|
+
return new Promise((resolve, reject) => {
|
|
2675
|
+
const srv = createServer();
|
|
2676
|
+
srv.once("error", reject);
|
|
2677
|
+
srv.listen(0, LOOPBACK, () => {
|
|
2678
|
+
const addr = srv.address();
|
|
2679
|
+
if (addr && typeof addr === "object") {
|
|
2680
|
+
const { port } = addr;
|
|
2681
|
+
srv.close(() => resolve(port));
|
|
2682
|
+
} else srv.close(() => reject(/* @__PURE__ */ new Error("couldn't find a free local port")));
|
|
2683
|
+
});
|
|
2684
|
+
});
|
|
2685
|
+
}
|
|
2686
|
+
function canConnect(port) {
|
|
2687
|
+
return new Promise((resolve) => {
|
|
2688
|
+
const sock = connect({
|
|
2689
|
+
host: LOOPBACK,
|
|
2690
|
+
port
|
|
2691
|
+
});
|
|
2692
|
+
sock.once("connect", () => {
|
|
2693
|
+
sock.destroy();
|
|
2694
|
+
resolve(true);
|
|
2695
|
+
});
|
|
2696
|
+
sock.once("error", () => {
|
|
2697
|
+
sock.destroy();
|
|
2698
|
+
resolve(false);
|
|
2699
|
+
});
|
|
2700
|
+
});
|
|
2701
|
+
}
|
|
2702
|
+
const READY_GRACE_MS = 150;
|
|
2703
|
+
/** Wait until the local forward accepts a connection. ssh opens the listener
|
|
2704
|
+
* once it has authenticated, so a refused connect means "not yet": retry with a
|
|
2705
|
+
* short growing delay and stop at once if ssh exits or attempts run out. */
|
|
2706
|
+
async function waitForPort(port, ssh, maxAttempts = 480) {
|
|
2707
|
+
let sshDone = false;
|
|
2708
|
+
const markDone = () => {
|
|
2709
|
+
sshDone = true;
|
|
2710
|
+
};
|
|
2711
|
+
ssh.exited.then(markDone, markDone);
|
|
2712
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
2713
|
+
if (sshDone) return "ssh-exited";
|
|
2714
|
+
if (await canConnect(port)) {
|
|
2715
|
+
await Promise.race([ssh.exited.then(markDone, markDone), new Promise((r) => setTimeout(r, READY_GRACE_MS))]);
|
|
2716
|
+
return sshDone ? "ssh-exited" : "ready";
|
|
2717
|
+
}
|
|
2718
|
+
await new Promise((r) => setTimeout(r, Math.min(20 * 2 ** Math.min(attempt, 4), 250)));
|
|
2719
|
+
}
|
|
2720
|
+
return "timeout";
|
|
2721
|
+
}
|
|
2722
|
+
/** True when `name` is an executable file in one of the PATH directories. */
|
|
2723
|
+
function findOnPath(name, env = process.env) {
|
|
2724
|
+
const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean)] : [""];
|
|
2725
|
+
for (const dir of (env.PATH ?? "").split(delimiter)) {
|
|
2726
|
+
if (!dir) continue;
|
|
2727
|
+
for (const ext of exts) {
|
|
2728
|
+
const file = join(dir, name + ext);
|
|
2729
|
+
try {
|
|
2730
|
+
if (!statSync(file).isFile()) continue;
|
|
2731
|
+
accessSync(file, constants.X_OK);
|
|
2732
|
+
return true;
|
|
2733
|
+
} catch {}
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
return false;
|
|
2737
|
+
}
|
|
2738
|
+
/** Start the tunnel's ssh. stdin and stdout are not used (ssh prompts for a
|
|
2739
|
+
* passphrase on the terminal itself); stderr stays visible.
|
|
2740
|
+
*
|
|
2741
|
+
* `ignoreSigint` keeps a terminal Ctrl+C (sent to the whole foreground process
|
|
2742
|
+
* group) from killing the tunnel while a database client is using it: ssh is
|
|
2743
|
+
* started through `sh` with SIGINT ignored, which survives the exec. It is NOT
|
|
2744
|
+
* `detached: true`, because that calls setsid(), so ssh would lose the
|
|
2745
|
+
* controlling terminal and could no longer ask for a key passphrase. */
|
|
2746
|
+
function spawnTunnel(args, o = {}) {
|
|
2747
|
+
const stdio = [
|
|
2748
|
+
"ignore",
|
|
2749
|
+
"ignore",
|
|
2750
|
+
"inherit"
|
|
2751
|
+
];
|
|
2752
|
+
const child = o.ignoreSigint && process.platform !== "win32" ? spawn("/bin/sh", [
|
|
2753
|
+
"-c",
|
|
2754
|
+
"trap \"\" INT; exec ssh \"$@\"",
|
|
2755
|
+
"sh",
|
|
2756
|
+
...args
|
|
2757
|
+
], { stdio }) : spawn("ssh", args, { stdio });
|
|
2758
|
+
return {
|
|
2759
|
+
child,
|
|
2760
|
+
exited: new Promise((resolve, reject) => {
|
|
2761
|
+
child.once("error", (err) => {
|
|
2762
|
+
if (err.code === "ENOENT") reject(/* @__PURE__ */ new Error("`ssh` was not found on your PATH"));
|
|
2763
|
+
else reject(err);
|
|
2764
|
+
});
|
|
2765
|
+
child.once("exit", (code, signal) => resolve(exitCodeFor(code, signal)));
|
|
2766
|
+
})
|
|
2767
|
+
};
|
|
2768
|
+
}
|
|
2769
|
+
const STOP_SIGNALS = [
|
|
2770
|
+
"SIGINT",
|
|
2771
|
+
"SIGTERM",
|
|
2772
|
+
"SIGHUP"
|
|
2773
|
+
];
|
|
2774
|
+
/** Hold a tunnel open until it ends. Ctrl+C (or SIGTERM) stops it cleanly and
|
|
2775
|
+
* exits 0; otherwise the exit code is ssh's own. `onReady` runs once the local
|
|
2776
|
+
* port accepts connections, when a `readyPort` is given. */
|
|
2777
|
+
async function holdTunnel(args, opts = {}) {
|
|
2778
|
+
const ssh = spawnTunnel(args);
|
|
2779
|
+
let stopped = false;
|
|
2780
|
+
const stop = (sig) => {
|
|
2781
|
+
stopped = true;
|
|
2782
|
+
ssh.child.kill(sig);
|
|
2783
|
+
};
|
|
2784
|
+
for (const sig of STOP_SIGNALS) process.on(sig, stop);
|
|
2785
|
+
try {
|
|
2786
|
+
if (opts.readyPort !== void 0) {
|
|
2787
|
+
const state = await waitForPort(opts.readyPort, ssh);
|
|
2788
|
+
if (state === "ready") opts.onReady?.();
|
|
2789
|
+
else if (state === "timeout") {
|
|
2790
|
+
ssh.child.kill("SIGTERM");
|
|
2791
|
+
await ssh.exited;
|
|
2792
|
+
throw new Error("the tunnel didn't come up in time");
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
const code = await ssh.exited;
|
|
2796
|
+
return stopped ? 0 : code;
|
|
2797
|
+
} finally {
|
|
2798
|
+
for (const sig of STOP_SIGNALS) process.off(sig, stop);
|
|
2799
|
+
}
|
|
2800
|
+
}
|
|
2801
|
+
/** Open a tunnel, run `client` against the local port with stdio inherited,
|
|
2802
|
+
* then close the tunnel. Exits with the client's code. */
|
|
2803
|
+
async function runClientThroughTunnel(o) {
|
|
2804
|
+
const ssh = spawnTunnel(o.sshArgs, { ignoreSigint: true });
|
|
2805
|
+
let client;
|
|
2806
|
+
const onSignal = (sig) => {
|
|
2807
|
+
if (sig === "SIGINT") {
|
|
2808
|
+
if (!client) ssh.child.kill("SIGTERM");
|
|
2809
|
+
return;
|
|
2810
|
+
}
|
|
2811
|
+
client?.kill(sig);
|
|
2812
|
+
ssh.child.kill(sig);
|
|
2813
|
+
};
|
|
2814
|
+
const killTunnel = () => {
|
|
2815
|
+
if (ssh.child.exitCode === null && ssh.child.signalCode === null) ssh.child.kill("SIGTERM");
|
|
2816
|
+
};
|
|
2817
|
+
process.on("exit", killTunnel);
|
|
2818
|
+
for (const sig of STOP_SIGNALS) process.on(sig, onSignal);
|
|
2819
|
+
try {
|
|
2820
|
+
const state = await waitForPort(o.localPort, ssh);
|
|
2821
|
+
if (state === "ssh-exited") {
|
|
2822
|
+
const code = await ssh.exited;
|
|
2823
|
+
throw new Error(`ssh exited (code ${code}) before the tunnel was ready`);
|
|
2824
|
+
}
|
|
2825
|
+
if (state === "timeout") {
|
|
2826
|
+
ssh.child.kill("SIGTERM");
|
|
2827
|
+
await ssh.exited;
|
|
2828
|
+
throw new Error("the tunnel didn't come up in time");
|
|
2829
|
+
}
|
|
2830
|
+
const running = spawn(o.client, o.clientArgs, { stdio: "inherit" });
|
|
2831
|
+
client = running;
|
|
2832
|
+
return await new Promise((resolve, reject) => {
|
|
2833
|
+
running.once("error", (err) => {
|
|
2834
|
+
if (err.code === "ENOENT") reject(/* @__PURE__ */ new Error(`\`${o.client}\` was not found on your PATH`));
|
|
2835
|
+
else reject(err);
|
|
2836
|
+
});
|
|
2837
|
+
running.once("exit", (code, signal) => resolve(exitCodeFor(code, signal)));
|
|
2838
|
+
});
|
|
2839
|
+
} finally {
|
|
2840
|
+
killTunnel();
|
|
2841
|
+
await ssh.exited.catch(() => 0);
|
|
2842
|
+
for (const sig of STOP_SIGNALS) process.off(sig, onSignal);
|
|
2843
|
+
process.off("exit", killTunnel);
|
|
2844
|
+
}
|
|
2845
|
+
}
|
|
2846
|
+
// src/commands/dbclients.ts
|
|
2847
|
+
const PRIVATE_NOTE$1 = "It uses a private SSH tunnel on a free local port, so the database never needs a public `krova tcp add` mapping. Passwords are never read from flags: the client prompts for one itself.";
|
|
2848
|
+
/** A user or database name: no leading `-`, nothing a client could read as a
|
|
2849
|
+
* connection string (`=`, `:`, `/`, spaces). */
|
|
2850
|
+
const IDENT = /^[A-Za-z0-9_][A-Za-z0-9_.$-]{0,62}$/;
|
|
2851
|
+
function validateIdent(value, label) {
|
|
2852
|
+
if (!IDENT.test(value)) throw new Error(`${label} may only use letters, digits, '_', '.', '$' and '-', and must not start with '-'`);
|
|
2853
|
+
return value;
|
|
2854
|
+
}
|
|
2855
|
+
const DB_CLIENTS = [
|
|
2856
|
+
{
|
|
2857
|
+
command: "psql",
|
|
2858
|
+
client: "psql",
|
|
2859
|
+
defaultPort: 5432,
|
|
2860
|
+
userDefault: "postgres",
|
|
2861
|
+
dbDefault: "postgres",
|
|
2862
|
+
description: "open psql against a PostgreSQL server in a Cube",
|
|
2863
|
+
clientArgs: ({ port, user, db }) => [
|
|
2864
|
+
"-h",
|
|
2865
|
+
LOOPBACK,
|
|
2866
|
+
"-p",
|
|
2867
|
+
String(port),
|
|
2868
|
+
"-U",
|
|
2869
|
+
user,
|
|
2870
|
+
"-d",
|
|
2871
|
+
db
|
|
2872
|
+
]
|
|
2873
|
+
},
|
|
2874
|
+
{
|
|
2875
|
+
command: "redis",
|
|
2876
|
+
client: "redis-cli",
|
|
2877
|
+
defaultPort: 6379,
|
|
2878
|
+
description: "open redis-cli against a Redis server in a Cube",
|
|
2879
|
+
clientArgs: ({ port }) => [
|
|
2880
|
+
"-h",
|
|
2881
|
+
LOOPBACK,
|
|
2882
|
+
"-p",
|
|
2883
|
+
String(port)
|
|
2884
|
+
]
|
|
2885
|
+
},
|
|
2886
|
+
{
|
|
2887
|
+
command: "mysql",
|
|
2888
|
+
client: "mysql",
|
|
2889
|
+
defaultPort: 3306,
|
|
2890
|
+
userDefault: "root",
|
|
2891
|
+
description: "open mysql against a MySQL or MariaDB server in a Cube",
|
|
2892
|
+
clientArgs: ({ port, user, db }) => [
|
|
2893
|
+
"-h",
|
|
2894
|
+
LOOPBACK,
|
|
2895
|
+
"-P",
|
|
2896
|
+
String(port),
|
|
2897
|
+
"--protocol=tcp",
|
|
2898
|
+
"-u",
|
|
2899
|
+
user,
|
|
2900
|
+
...db ? [`--database=${db}`] : []
|
|
2901
|
+
]
|
|
2902
|
+
}
|
|
2903
|
+
];
|
|
2904
|
+
function dbClientCommand(spec) {
|
|
2905
|
+
const c = new Command(spec.command).argument("<cube>", "cube name or ID").description(`${spec.description}. ${PRIVATE_NOTE$1}`).option("--port <cubePort>", `port inside the Cube (default ${spec.defaultPort})`).option("-i, --identity <file>", "SSH identity (private key) file, passed to ssh -i");
|
|
2906
|
+
if (spec.userDefault) c.option("--user <user>", `database user (default ${spec.userDefault})`, spec.userDefault);
|
|
2907
|
+
if (spec.command === "psql") c.option("--db <name>", "database name (default postgres)", "postgres");
|
|
2908
|
+
if (spec.command === "mysql") c.option("--db <name>", "database to use");
|
|
2909
|
+
return c.action(async (cubeRef, opts, cmd) => {
|
|
2910
|
+
const cubePort = opts.port !== void 0 ? parsePort(opts.port, "--port") : spec.defaultPort;
|
|
2911
|
+
const user = spec.userDefault ? validateIdent(opts.user, "--user") : void 0;
|
|
2912
|
+
const db = opts.db ? validateIdent(opts.db, "--db") : void 0;
|
|
2913
|
+
if (!findOnPath(spec.client)) throw new Error(`\`${spec.client}\` was not found on your PATH — install it and try again`);
|
|
2914
|
+
const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
|
|
2915
|
+
const localPort = await freeLoopbackPort();
|
|
2916
|
+
const sshArgs = buildTunnelArgs(info, {
|
|
2917
|
+
identity: opts.identity,
|
|
2918
|
+
knownHosts,
|
|
2919
|
+
localPort,
|
|
2920
|
+
cubePort
|
|
2921
|
+
});
|
|
2922
|
+
process.exitCode = await runClientThroughTunnel({
|
|
2923
|
+
sshArgs,
|
|
2924
|
+
localPort,
|
|
2925
|
+
client: spec.client,
|
|
2926
|
+
clientArgs: spec.clientArgs({
|
|
2927
|
+
port: localPort,
|
|
2928
|
+
user,
|
|
2929
|
+
db
|
|
2930
|
+
})
|
|
2931
|
+
});
|
|
2932
|
+
});
|
|
2933
|
+
}
|
|
2934
|
+
const psqlCommand = () => dbClientCommand(DB_CLIENTS[0]);
|
|
2935
|
+
const redisCommand = () => dbClientCommand(DB_CLIENTS[1]);
|
|
2936
|
+
const mysqlCommand = () => dbClientCommand(DB_CLIENTS[2]);
|
|
2937
|
+
// src/commands/exec.ts
|
|
2938
|
+
function execCommand() {
|
|
2939
|
+
return new Command("exec").argument("<cube>", "cube name or ID").argument("<command...>", "command to run (after --)").description("run a command on a Cube over SSH without a terminal, and exit with its exit code. The words after -- are joined with spaces and run by the remote shell, like ssh.").option("-i, --identity <file>", "SSH identity (private key) file, passed to ssh -i").action(async (cubeRef, command, opts, cmd) => {
|
|
2940
|
+
if (!command.some((w) => w.trim())) throw new Error("exec needs a command to run, e.g. krova exec <cube> -- uname -a");
|
|
2941
|
+
const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
|
|
2942
|
+
const args = buildSSHArgs(info, {
|
|
2943
|
+
preArgs: ["-T"],
|
|
2944
|
+
identity: opts.identity,
|
|
2945
|
+
knownHosts,
|
|
2946
|
+
remoteCmd: command
|
|
2947
|
+
});
|
|
2948
|
+
process.exitCode = await execInherit("ssh", args);
|
|
2949
|
+
});
|
|
2950
|
+
}
|
|
2951
|
+
function cpCommand() {
|
|
2952
|
+
return new Command("cp").argument("<src>", "source: a local path or <cube>:<path>").argument("<dst>", "destination: a local path or <cube>:<path>").description("copy files between this machine and a Cube over scp. Exactly one side is <cube>:<path> (cube by name or ID).").option("-r, --recursive", "copy directories recursively").option("-i, --identity <file>", "SSH identity (private key) file, passed to scp -i").action(async (src, dst, opts, cmd) => {
|
|
2953
|
+
const operands = parseCpOperands(src, dst);
|
|
2954
|
+
const { info, knownHosts } = await resolveSshTarget(cmd, operands.cube, { requireHostKeys: true });
|
|
2955
|
+
const args = buildSCPArgs(info, {
|
|
2956
|
+
knownHosts,
|
|
2957
|
+
identity: opts.identity,
|
|
2958
|
+
recursive: Boolean(opts.recursive),
|
|
2959
|
+
operands
|
|
2960
|
+
});
|
|
2961
|
+
process.exitCode = await execInherit("scp", args);
|
|
2962
|
+
});
|
|
2963
|
+
}
|
|
1220
2964
|
// src/commands/ssh.ts
|
|
1221
2965
|
const collect = (v, acc) => {
|
|
1222
2966
|
acc.push(v);
|
|
@@ -1224,34 +2968,7 @@ const collect = (v, acc) => {
|
|
|
1224
2968
|
};
|
|
1225
2969
|
function sshCommand() {
|
|
1226
2970
|
return new Command("ssh").argument("<cube>", "cube name or ID").argument("[command...]", "command to run non-interactively (after --)").description("open an SSH session to a Cube (by name or ID)").option("-i, --identity <file>", "SSH identity (private key) file, passed to ssh -i").option("-L, --local-forward <spec>", "local port forward, passed to ssh -L (repeatable)", collect, []).option("-R, --remote-forward <spec>", "remote port forward, passed to ssh -R (repeatable)", collect, []).action(async (cubeRef, command, opts, cmd) => {
|
|
1227
|
-
const
|
|
1228
|
-
const client = makeClient(rt.res);
|
|
1229
|
-
const space = await resolveSpace(rt);
|
|
1230
|
-
const id = await resolveCube(client, space, cubeRef);
|
|
1231
|
-
const { status, data } = await rawRequest({
|
|
1232
|
-
method: "GET",
|
|
1233
|
-
baseUrl: rt.res.baseUrl,
|
|
1234
|
-
path: `/spaces/${space}/cubes/${id}/ssh`,
|
|
1235
|
-
apiKey: rt.res.apiKey,
|
|
1236
|
-
timeoutMs: rt.timeoutMs
|
|
1237
|
-
});
|
|
1238
|
-
if (status === 404) throw new Error(`SSH info isn't available on this server yet — try \`krova cubes get ${cubeRef}\` for the Cube's IP and ssh manually`);
|
|
1239
|
-
if (status === 401 || status === 403) throw new Error(`SSH info request was rejected (HTTP ${status})`);
|
|
1240
|
-
if (status !== 200 || !data?.host) throw new Error(`couldn't fetch SSH info (HTTP ${status})`);
|
|
1241
|
-
const info = {
|
|
1242
|
-
host: data.host,
|
|
1243
|
-
port: data.port ?? 0,
|
|
1244
|
-
user: data.user ?? "",
|
|
1245
|
-
hostKeys: data.hostKeys ?? []
|
|
1246
|
-
};
|
|
1247
|
-
validateSSHHost(info.host);
|
|
1248
|
-
validateSSHUser(info.user);
|
|
1249
|
-
if (info.port < 0 || info.port > 65535) throw new Error("invalid ssh port");
|
|
1250
|
-
let knownHosts = "";
|
|
1251
|
-
if (info.hostKeys.length) {
|
|
1252
|
-
if (isHostname(info.host) && isUnpinned(info.host, info.port)) process.stderr.write("note: this Cube now has a stable SSH hostname (it stays the same even if the Cube migrates to another server) — pinning it is expected and only happens once.\n");
|
|
1253
|
-
knownHosts = writeKnownHosts(info);
|
|
1254
|
-
} else process.stderr.write("note: this server didn't provide host keys — using ssh trust-on-first-use (host-key checking stays on).\n");
|
|
2971
|
+
const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef);
|
|
1255
2972
|
const args = buildSSHArgs(info, {
|
|
1256
2973
|
identity: opts.identity,
|
|
1257
2974
|
localFwd: opts.localForward,
|
|
@@ -1262,6 +2979,49 @@ function sshCommand() {
|
|
|
1262
2979
|
process.exitCode = await execSSH(args);
|
|
1263
2980
|
});
|
|
1264
2981
|
}
|
|
2982
|
+
// src/commands/tunnel.ts
|
|
2983
|
+
const PRIVATE_NOTE = "The port is reachable only from this machine, over your SSH key. Prefer it to a public `krova tcp add` mapping for databases.";
|
|
2984
|
+
function tunnelCommand() {
|
|
2985
|
+
return new Command("tunnel").argument("<cube>", "cube name or ID").argument("<ports>", "[localPort:]cubePort (the local port defaults to the Cube port)").description(`forward a local port to a port inside a Cube over SSH. ${PRIVATE_NOTE}`).option("-i, --identity <file>", "SSH identity (private key) file, passed to ssh -i").action(async (cubeRef, spec, opts, cmd) => {
|
|
2986
|
+
const { localPort, cubePort } = parseTunnelSpec(spec);
|
|
2987
|
+
const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
|
|
2988
|
+
const args = buildTunnelArgs(info, {
|
|
2989
|
+
identity: opts.identity,
|
|
2990
|
+
knownHosts,
|
|
2991
|
+
localPort,
|
|
2992
|
+
cubePort
|
|
2993
|
+
});
|
|
2994
|
+
process.stderr.write(`Forwarding localhost:${localPort} -> ${cubeRef}:${cubePort}. Press Ctrl+C to stop.\n`);
|
|
2995
|
+
process.exitCode = await holdTunnel(args);
|
|
2996
|
+
});
|
|
2997
|
+
}
|
|
2998
|
+
function connectCommand() {
|
|
2999
|
+
return new Command("connect").argument("<cube>", "cube name or ID").description(`open a private tunnel to a Cube port on a free local port and print the local endpoint. ${PRIVATE_NOTE}`).requiredOption("--port <cubePort>", "port inside the Cube to reach").option("--local-port <port>", "local port to listen on (default: a free one)").option("-i, --identity <file>", "SSH identity (private key) file, passed to ssh -i").action(async (cubeRef, opts, cmd) => {
|
|
3000
|
+
const cubePort = parsePort(opts.port, "--port");
|
|
3001
|
+
const localPort = opts.localPort !== void 0 ? parsePort(opts.localPort, "--local-port") : await freeLoopbackPort();
|
|
3002
|
+
const json = Boolean(cmd.optsWithGlobals().json);
|
|
3003
|
+
const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
|
|
3004
|
+
const args = buildTunnelArgs(info, {
|
|
3005
|
+
identity: opts.identity,
|
|
3006
|
+
knownHosts,
|
|
3007
|
+
localPort,
|
|
3008
|
+
cubePort
|
|
3009
|
+
});
|
|
3010
|
+
process.exitCode = await holdTunnel(args, {
|
|
3011
|
+
readyPort: localPort,
|
|
3012
|
+
onReady: () => {
|
|
3013
|
+
if (json) printJSON({
|
|
3014
|
+
host: LOOPBACK,
|
|
3015
|
+
port: localPort,
|
|
3016
|
+
cube: cubeRef,
|
|
3017
|
+
cubePort
|
|
3018
|
+
});
|
|
3019
|
+
else process.stdout.write(`localhost:${localPort}\n`);
|
|
3020
|
+
process.stderr.write(`Forwarding localhost:${localPort} -> ${cubeRef}:${cubePort}. Press Ctrl+C to stop.\n`);
|
|
3021
|
+
}
|
|
3022
|
+
});
|
|
3023
|
+
});
|
|
3024
|
+
}
|
|
1265
3025
|
// src/commands/tcp.ts
|
|
1266
3026
|
/** `krova tcp` — manage a Cube's TCP port mappings. */
|
|
1267
3027
|
function tcpCommand() {
|
|
@@ -1294,7 +3054,7 @@ function tcpCommand() {
|
|
|
1294
3054
|
cmd.command("add").argument("<cube>", "cube name or ID").requiredOption("--port <n>", "the in-Cube port to expose").option("--whitelist <cidr>", "restrict access to this IP/CIDR (repeatable)", (val, acc) => {
|
|
1295
3055
|
acc.push(val);
|
|
1296
3056
|
return acc;
|
|
1297
|
-
}, []).option("--no-udp", "don't forward UDP on this port (UDP is forwarded by default alongside TCP)").description("expose a Cube TCP port on the host, optionally IP-restricted").action(async (cubeRef, opts, c) => {
|
|
3057
|
+
}, []).option("-y, --yes", "skip the confirmation prompt when the port would be open to the whole internet").option("--no-udp", "don't forward UDP on this port (UDP is forwarded by default alongside TCP)").description("expose a Cube TCP port on the host, optionally IP-restricted").action(async (cubeRef, opts, c) => {
|
|
1298
3058
|
const rt = getRuntime(c);
|
|
1299
3059
|
const client = makeClient(rt.res);
|
|
1300
3060
|
const space = await resolveSpace(rt);
|
|
@@ -1302,6 +3062,12 @@ function tcpCommand() {
|
|
|
1302
3062
|
const cubePort = Number(opts.port);
|
|
1303
3063
|
if (!Number.isInteger(cubePort) || cubePort <= 0 || cubePort > 65535) throw new Error(`--port must be a valid port (got "${opts.port}").`);
|
|
1304
3064
|
const whitelist = opts.whitelist;
|
|
3065
|
+
if (isOpenWhitelist(whitelist)) {
|
|
3066
|
+
process.stderr.write(`${publicExposureWarning(cubeRef, cubePort)}\n`);
|
|
3067
|
+
if (shouldConfirm(opts)) {
|
|
3068
|
+
if (!await confirm("Open this port to the whole internet? [y/N] ")) return printAborted(rt.json);
|
|
3069
|
+
}
|
|
3070
|
+
}
|
|
1305
3071
|
const mapping = await client.tcpMappings.create(space, id, {
|
|
1306
3072
|
cubePort,
|
|
1307
3073
|
...whitelist.length ? { whitelistedIps: whitelist } : {},
|
|
@@ -1324,6 +3090,59 @@ function tcpCommand() {
|
|
|
1324
3090
|
});
|
|
1325
3091
|
return cmd;
|
|
1326
3092
|
}
|
|
3093
|
+
// src/lib/semver.ts
|
|
3094
|
+
function parseVersion(input) {
|
|
3095
|
+
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(input.trim());
|
|
3096
|
+
if (!m) return void 0;
|
|
3097
|
+
const [major, minor, patch] = [
|
|
3098
|
+
m[1],
|
|
3099
|
+
m[2],
|
|
3100
|
+
m[3]
|
|
3101
|
+
];
|
|
3102
|
+
if (major === void 0 || minor === void 0 || patch === void 0) return void 0;
|
|
3103
|
+
const pre = m[4];
|
|
3104
|
+
return {
|
|
3105
|
+
core: [
|
|
3106
|
+
Number(major),
|
|
3107
|
+
Number(minor),
|
|
3108
|
+
Number(patch)
|
|
3109
|
+
],
|
|
3110
|
+
pre: pre ? pre.split(".") : []
|
|
3111
|
+
};
|
|
3112
|
+
}
|
|
3113
|
+
/** Semver ordering of two pre-release parts: numeric identifiers below
|
|
3114
|
+
* alphanumeric ones, numbers compared as numbers, everything else as text. */
|
|
3115
|
+
function comparePre(a, b) {
|
|
3116
|
+
if (a.length === 0 || b.length === 0) return b.length - a.length;
|
|
3117
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) {
|
|
3118
|
+
const x = a[i] ?? "";
|
|
3119
|
+
const y = b[i] ?? "";
|
|
3120
|
+
const xNum = /^\d+$/.test(x);
|
|
3121
|
+
const yNum = /^\d+$/.test(y);
|
|
3122
|
+
if (xNum && yNum) {
|
|
3123
|
+
const diff = Number(x) - Number(y);
|
|
3124
|
+
if (diff !== 0) return diff;
|
|
3125
|
+
continue;
|
|
3126
|
+
}
|
|
3127
|
+
if (xNum !== yNum) return xNum ? -1 : 1;
|
|
3128
|
+
if (x !== y) return x < y ? -1 : 1;
|
|
3129
|
+
}
|
|
3130
|
+
return a.length - b.length;
|
|
3131
|
+
}
|
|
3132
|
+
/** Negative when `a` is older than `b`, zero when equal, positive when newer.
|
|
3133
|
+
* A pre-release sorts below the release it leads to (1.0.0-rc.1 < 1.0.0).
|
|
3134
|
+
* Throws on input that is not MAJOR.MINOR.PATCH[-pre][+build]. */
|
|
3135
|
+
function compareVersions(a, b) {
|
|
3136
|
+
const va = parseVersion(a);
|
|
3137
|
+
const vb = parseVersion(b);
|
|
3138
|
+
if (!va) throw new Error(`not a version: ${a}`);
|
|
3139
|
+
if (!vb) throw new Error(`not a version: ${b}`);
|
|
3140
|
+
for (let i = 0; i < 3; i++) {
|
|
3141
|
+
const diff = (va.core[i] ?? 0) - (vb.core[i] ?? 0);
|
|
3142
|
+
if (diff !== 0) return diff;
|
|
3143
|
+
}
|
|
3144
|
+
return comparePre(va.pre, vb.pre);
|
|
3145
|
+
}
|
|
1327
3146
|
const CLI_VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
1328
3147
|
function versionCommand() {
|
|
1329
3148
|
return new Command("version").description("print the krova CLI version").action((_opts, cmd) => {
|
|
@@ -1337,6 +3156,86 @@ function versionCommand() {
|
|
|
1337
3156
|
process.stdout.write(`krova ${info.version} (node ${info.node}, ${info.platform})\n`);
|
|
1338
3157
|
});
|
|
1339
3158
|
}
|
|
3159
|
+
// src/commands/update.ts
|
|
3160
|
+
const DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
3161
|
+
const UPDATE_COMMAND = "npm install -g @krovacloud/cli@latest";
|
|
3162
|
+
/** Checking npm is a quick metadata lookup, so never wait longer than this,
|
|
3163
|
+
* even when the global --timeout is larger. */
|
|
3164
|
+
const CHECK_TIMEOUT_CAP_MS = 1e4;
|
|
3165
|
+
/** One reason line, plus a hint when the failure looks like the network —
|
|
3166
|
+
* the top-level handler names the API base URL for any connection failure,
|
|
3167
|
+
* which would be wrong here: this check talks to npm, not to Krova. */
|
|
3168
|
+
function failureFor(err, timeoutMs) {
|
|
3169
|
+
const mirrorHint = `Check your connection or set ${ENV.npmRegistry} to use an npm mirror.`;
|
|
3170
|
+
if (!(err instanceof Error)) return { reason: String(err) };
|
|
3171
|
+
const code = err.code;
|
|
3172
|
+
if (err.name === "TimeoutError" || err.name === "AbortError" || code === "ABORT_ERR") return {
|
|
3173
|
+
reason: `timed out after ${timeoutMs / 1e3}s`,
|
|
3174
|
+
hint: mirrorHint
|
|
3175
|
+
};
|
|
3176
|
+
const cause = err.cause;
|
|
3177
|
+
if (cause && typeof cause === "object" && typeof cause.message === "string") return {
|
|
3178
|
+
reason: cause.message,
|
|
3179
|
+
hint: mirrorHint
|
|
3180
|
+
};
|
|
3181
|
+
return {
|
|
3182
|
+
reason: err.message,
|
|
3183
|
+
hint: err.message === "fetch failed" ? mirrorHint : void 0
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
function registryError(reason, hint) {
|
|
3187
|
+
const err = /* @__PURE__ */ new Error(`could not check the npm registry: ${reason}`);
|
|
3188
|
+
return hint ? Object.assign(err, { hint }) : err;
|
|
3189
|
+
}
|
|
3190
|
+
/** The canonical MAJOR.MINOR.PATCH[-prerelease] form: no leading v, no +build metadata. */
|
|
3191
|
+
function formatVersion(parsed) {
|
|
3192
|
+
const [major, minor, patch] = parsed.core;
|
|
3193
|
+
return `${major}.${minor}.${patch}${parsed.pre.length > 0 ? `-${parsed.pre.join(".")}` : ""}`;
|
|
3194
|
+
}
|
|
3195
|
+
/** The registry's latest published version, normalized, e.g. "0.7.0". */
|
|
3196
|
+
async function fetchLatestVersion(baseUrl, timeoutMs) {
|
|
3197
|
+
const base = (baseUrl || DEFAULT_REGISTRY).replace(/\/+$/, "");
|
|
3198
|
+
let res;
|
|
3199
|
+
try {
|
|
3200
|
+
res = await fetch(`${base}/@krovacloud%2fcli/latest`, {
|
|
3201
|
+
headers: { accept: "application/json" },
|
|
3202
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
3203
|
+
});
|
|
3204
|
+
} catch (err) {
|
|
3205
|
+
const failure = failureFor(err, timeoutMs);
|
|
3206
|
+
throw registryError(failure.reason, failure.hint);
|
|
3207
|
+
}
|
|
3208
|
+
if (!res.ok) throw registryError(`the registry answered HTTP ${res.status}`);
|
|
3209
|
+
let body;
|
|
3210
|
+
try {
|
|
3211
|
+
body = await res.json();
|
|
3212
|
+
} catch (err) {
|
|
3213
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
3214
|
+
const failure = failureFor(err, timeoutMs);
|
|
3215
|
+
throw registryError(failure.reason, failure.hint);
|
|
3216
|
+
}
|
|
3217
|
+
throw registryError("the response was not valid JSON");
|
|
3218
|
+
}
|
|
3219
|
+
const version = body?.version;
|
|
3220
|
+
const parsed = typeof version === "string" ? parseVersion(version) : void 0;
|
|
3221
|
+
if (!parsed) throw registryError("the response did not name a version");
|
|
3222
|
+
return formatVersion(parsed);
|
|
3223
|
+
}
|
|
3224
|
+
function updateCommand() {
|
|
3225
|
+
return new Command("update").description("check the npm registry for a newer krova CLI (never installs)").action(async (_opts, cmd) => {
|
|
3226
|
+
const rt = getRuntime(cmd);
|
|
3227
|
+
const latest = await fetchLatestVersion(process.env[ENV.npmRegistry] ?? "", Math.min(rt.timeoutMs, CHECK_TIMEOUT_CAP_MS));
|
|
3228
|
+
const current = CLI_VERSION;
|
|
3229
|
+
const updateAvailable = compareVersions(latest, current) > 0;
|
|
3230
|
+
if (rt.json) return printJSON({
|
|
3231
|
+
current,
|
|
3232
|
+
latest,
|
|
3233
|
+
updateAvailable,
|
|
3234
|
+
command: UPDATE_COMMAND
|
|
3235
|
+
});
|
|
3236
|
+
process.stdout.write(updateAvailable ? `krova ${latest} is available (you have ${current}). Update with: ${UPDATE_COMMAND}\n` : `krova ${latest} is the latest version.\n`);
|
|
3237
|
+
});
|
|
3238
|
+
}
|
|
1340
3239
|
// src/commands/webhooks.ts
|
|
1341
3240
|
const DEFAULT_LISTEN_HOST = "127.0.0.1";
|
|
1342
3241
|
const DEFAULT_LISTEN_PORT = 4666;
|
|
@@ -1519,7 +3418,7 @@ function webhooksCommand() {
|
|
|
1519
3418
|
if (!secret) throw new Error("a signing secret is required: pass --secret or set KROVA_WEBHOOK_SECRET");
|
|
1520
3419
|
const { host, port } = parseListenAddr(String(opts.addr));
|
|
1521
3420
|
const wantPath = String(opts.path);
|
|
1522
|
-
const server = createServer((req, res) => {
|
|
3421
|
+
const server = createServer$1((req, res) => {
|
|
1523
3422
|
const reqPath = (req.url ?? "/").split("?")[0];
|
|
1524
3423
|
if (req.method !== "POST" || reqPath !== wantPath) {
|
|
1525
3424
|
res.writeHead(405);
|
|
@@ -1568,9 +3467,20 @@ function webhooksCommand() {
|
|
|
1568
3467
|
return wh;
|
|
1569
3468
|
}
|
|
1570
3469
|
// src/commands/whoami.ts
|
|
3470
|
+
/** "never", or the ISO date with how far away it is, e.g. `2026-12-16T12:00:00.000Z (in 30 days)`. */
|
|
3471
|
+
function describeExpiry(expiresAt, now = Date.now()) {
|
|
3472
|
+
if (expiresAt === null) return "never";
|
|
3473
|
+
const at = Date.parse(expiresAt);
|
|
3474
|
+
if (Number.isNaN(at)) return expiresAt;
|
|
3475
|
+
const days = Math.floor((at - now) / 864e5);
|
|
3476
|
+
if (days < 0) return `${expiresAt} (expired)`;
|
|
3477
|
+
if (days === 0) return `${expiresAt} (within a day)`;
|
|
3478
|
+
return `${expiresAt} (in ${days} ${days === 1 ? "day" : "days"})`;
|
|
3479
|
+
}
|
|
1571
3480
|
function whoamiCommand() {
|
|
1572
|
-
return new Command("whoami").description("show the current context, space, and base URL").action(async (
|
|
3481
|
+
return new Command("whoami").description("show the current context, space, and base URL").option("--show-secrets", "print the full API key instead of a masked one").action(async (opts, cmd) => {
|
|
1573
3482
|
const rt = getRuntime(cmd);
|
|
3483
|
+
const showSecrets = Boolean(opts.showSecrets);
|
|
1574
3484
|
const ctx = find(rt.cfg, rt.res.contextName);
|
|
1575
3485
|
let spaceId = rt.res.spaceId;
|
|
1576
3486
|
let spaceName = ctx?.spaceName ?? "";
|
|
@@ -1580,13 +3490,17 @@ function whoamiCommand() {
|
|
|
1580
3490
|
spaceName = probe.space.name ?? spaceName;
|
|
1581
3491
|
}
|
|
1582
3492
|
const spaceLive = probe.state === "valid";
|
|
1583
|
-
const
|
|
3493
|
+
const keyInfo = probe.state === "valid" ? probe.space.apiKey : void 0;
|
|
3494
|
+
const expiresAt = keyInfo ? keyInfo.expiresAt : void 0;
|
|
3495
|
+
const warning = probe.state === "rejected" ? `the API rejected this key (HTTP ${probe.status}): it is invalid, revoked or expired. Run \`krova login\`. The values below are cached locally and may be stale.` : probe.state === "unreachable" ? `could not reach ${rt.res.baseUrl} (${probe.error}) — showing locally cached values.` : "";
|
|
1584
3496
|
if (rt.json) return printJSON({
|
|
1585
3497
|
context: rt.res.contextName,
|
|
1586
3498
|
spaceId,
|
|
1587
3499
|
spaceName,
|
|
1588
|
-
apiKeyMasked:
|
|
3500
|
+
...showSecrets ? { apiKey: rt.res.apiKey } : { apiKeyMasked: displayKey(rt.res.apiKey, false) },
|
|
3501
|
+
...expiresAt !== void 0 ? { apiKeyExpiresAt: expiresAt } : {},
|
|
1589
3502
|
apiKeySource: rt.res.apiKeySource,
|
|
3503
|
+
apiKeyStorage: rt.res.apiKeyStorage || void 0,
|
|
1590
3504
|
baseUrl: rt.res.baseUrl,
|
|
1591
3505
|
spaceLive,
|
|
1592
3506
|
checkState: probe.state,
|
|
@@ -1596,13 +3510,64 @@ function whoamiCommand() {
|
|
|
1596
3510
|
["Context", rt.res.contextName || "—"],
|
|
1597
3511
|
["Space", spaceName || "—"],
|
|
1598
3512
|
["Space ID", spaceId || "—"],
|
|
1599
|
-
["API key", rt.res.apiKey ? `${
|
|
3513
|
+
["API key", rt.res.apiKey ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : ""})` : "—"],
|
|
3514
|
+
...expiresAt !== void 0 ? [["Key expires", describeExpiry(expiresAt)]] : [],
|
|
1600
3515
|
["Base URL", rt.res.baseUrl]
|
|
1601
3516
|
]);
|
|
1602
3517
|
if (warning) process.stdout.write(`\n${warning}\n`);
|
|
1603
3518
|
if (probe.state === "rejected") process.exitCode = 1;
|
|
1604
3519
|
});
|
|
1605
3520
|
}
|
|
3521
|
+
// src/lib/hints.ts
|
|
3522
|
+
const NETWORK_CODES = /* @__PURE__ */ new Set([
|
|
3523
|
+
"ECONNREFUSED",
|
|
3524
|
+
"ENOTFOUND",
|
|
3525
|
+
"ETIMEDOUT",
|
|
3526
|
+
"UND_ERR_CONNECT_TIMEOUT"
|
|
3527
|
+
]);
|
|
3528
|
+
/** Hint for an API status, or undefined when a generic hint would not help (e.g. 400, 422). */
|
|
3529
|
+
function hintForStatus(status) {
|
|
3530
|
+
if (status === 401) return "Your API key was rejected. Run krova login, or check krova whoami.";
|
|
3531
|
+
if (status === 403) return "Your key's member lacks the permission for this action. Ask a space owner to grant it.";
|
|
3532
|
+
if (status === 404) return "Not found. Check the name or ID with the matching list command.";
|
|
3533
|
+
if (status === 409) return "The resource is busy or in a conflicting state. Try again in a moment.";
|
|
3534
|
+
if (status === 429) return "Rate limited. Wait a moment and try again.";
|
|
3535
|
+
if (status >= 500 && status <= 599) return "Krova had a server error. Try again; if it keeps happening, contact support.";
|
|
3536
|
+
}
|
|
3537
|
+
/** True when `err` (or anything in its cause chain) is a connection failure. */
|
|
3538
|
+
function isNetworkError(err) {
|
|
3539
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3540
|
+
const walk = (e, depth) => {
|
|
3541
|
+
if (!e || typeof e !== "object" || depth > 5 || seen.has(e)) return false;
|
|
3542
|
+
seen.add(e);
|
|
3543
|
+
const { code, message, cause, errors } = e;
|
|
3544
|
+
if (typeof code === "string" && NETWORK_CODES.has(code)) return true;
|
|
3545
|
+
if (typeof message === "string") {
|
|
3546
|
+
if (message === "fetch failed") return true;
|
|
3547
|
+
for (const c of NETWORK_CODES) if (message.includes(c)) return true;
|
|
3548
|
+
}
|
|
3549
|
+
if (walk(cause, depth + 1)) return true;
|
|
3550
|
+
return Array.isArray(errors) && errors.some((x) => walk(x, depth + 1));
|
|
3551
|
+
};
|
|
3552
|
+
return walk(err, 0);
|
|
3553
|
+
}
|
|
3554
|
+
/**
|
|
3555
|
+
* The one extra line the top-level error handler prints under `Error: ...`.
|
|
3556
|
+
*
|
|
3557
|
+
* - An error that carries its own `hint` string wins: it is returned as-is, so
|
|
3558
|
+
* a command that already explains itself is never given a second, generic one.
|
|
3559
|
+
* - A `KrovaError` (the API answered) gets a hint by status. A termination
|
|
3560
|
+
* protection refusal gets none: retrying cannot help and its message is exact.
|
|
3561
|
+
* - A connection failure gets a hint naming the base URL being used.
|
|
3562
|
+
* - Anything else (validation, local errors) gets none.
|
|
3563
|
+
*/
|
|
3564
|
+
function errorHint(err, baseUrl) {
|
|
3565
|
+
const own = err?.hint;
|
|
3566
|
+
if (typeof own === "string" && own) return own;
|
|
3567
|
+
if (err instanceof TerminationProtectedError) return void 0;
|
|
3568
|
+
if (err instanceof KrovaError) return hintForStatus(err.status);
|
|
3569
|
+
if (isNetworkError(err)) return `Could not reach ${baseUrl}. Check your connection or ${ENV.baseUrl}.`;
|
|
3570
|
+
}
|
|
1606
3571
|
// src/index.ts
|
|
1607
3572
|
const program = new Command();
|
|
1608
3573
|
program.name("krova").description("krova is the command-line interface for Krova Cloud — manage Cubes (Firecracker microVMs), browse the catalog, and receive webhooks.").version(CLI_VERSION, "-v, --version", "print the krova CLI version").showHelpAfterError();
|
|
@@ -1616,6 +3581,13 @@ program.addCommand(snapshotsCommand());
|
|
|
1616
3581
|
program.addCommand(backupsCommand());
|
|
1617
3582
|
program.addCommand(tcpCommand());
|
|
1618
3583
|
program.addCommand(sshCommand());
|
|
3584
|
+
program.addCommand(tunnelCommand());
|
|
3585
|
+
program.addCommand(connectCommand());
|
|
3586
|
+
program.addCommand(psqlCommand());
|
|
3587
|
+
program.addCommand(redisCommand());
|
|
3588
|
+
program.addCommand(mysqlCommand());
|
|
3589
|
+
program.addCommand(execCommand());
|
|
3590
|
+
program.addCommand(cpCommand());
|
|
1619
3591
|
program.addCommand(rootListCommand());
|
|
1620
3592
|
program.addCommand(rootGetCommand());
|
|
1621
3593
|
program.addCommand(regionsCommand());
|
|
@@ -1623,6 +3595,8 @@ program.addCommand(imagesCommand());
|
|
|
1623
3595
|
program.addCommand(pricingCommand());
|
|
1624
3596
|
program.addCommand(webhooksCommand());
|
|
1625
3597
|
program.addCommand(versionCommand());
|
|
3598
|
+
program.addCommand(updateCommand());
|
|
3599
|
+
program.addCommand(completionCommand());
|
|
1626
3600
|
const applyGlobals = (cmd) => {
|
|
1627
3601
|
const have = new Set(cmd.options.map((o) => o.long));
|
|
1628
3602
|
const add = (flags, desc, def) => {
|
|
@@ -1634,16 +3608,35 @@ const applyGlobals = (cmd) => {
|
|
|
1634
3608
|
add("--base-url <url>", "override the API base URL");
|
|
1635
3609
|
add("--context <name>", "use a named context (overrides KROVA_CONTEXT)");
|
|
1636
3610
|
add("--json", "output machine-readable JSON instead of a table");
|
|
3611
|
+
add("-o, --output <format>", "output format: table (default) or json; -o json is the same as --json");
|
|
1637
3612
|
add("--timeout <duration>", "per-request timeout", "30s");
|
|
1638
3613
|
for (const c of cmd.commands) applyGlobals(c);
|
|
1639
3614
|
};
|
|
1640
3615
|
applyGlobals(program);
|
|
3616
|
+
program.hook("preAction", (_root, actionCmd) => {
|
|
3617
|
+
parseOutputFormat(actionCmd.optsWithGlobals().output);
|
|
3618
|
+
});
|
|
3619
|
+
/** The base URL for a connection hint: the one the failing command resolved,
|
|
3620
|
+
* else what the environment and saved context would give. */
|
|
3621
|
+
function hintBaseUrl() {
|
|
3622
|
+
const active = activeRuntime();
|
|
3623
|
+
if (active) return active.baseUrl;
|
|
3624
|
+
try {
|
|
3625
|
+
return resolve(load(), {}).baseUrl;
|
|
3626
|
+
} catch {
|
|
3627
|
+
return process.env[ENV.baseUrl] || "https://krova.cloud/api/v1";
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
1641
3630
|
async function main() {
|
|
1642
3631
|
try {
|
|
1643
3632
|
await program.parseAsync(process.argv);
|
|
1644
3633
|
} catch (err) {
|
|
1645
3634
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1646
3635
|
process.stderr.write(`Error: ${msg}\n`);
|
|
3636
|
+
if (!activeRuntime()?.json) {
|
|
3637
|
+
const hint = errorHint(err, hintBaseUrl());
|
|
3638
|
+
if (hint) process.stderr.write(`${hint}\n`);
|
|
3639
|
+
}
|
|
1647
3640
|
process.exitCode = 1;
|
|
1648
3641
|
}
|
|
1649
3642
|
}
|