@krovacloud/cli 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,21 +1,199 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { Command } from "commander";
4
- import { appendFileSync, chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
- import { homedir } from "node:os";
6
- import { dirname, join } from "node:path";
7
- import { KrovaClient, krovaErrorFrom } from "@krovacloud/sdk";
8
- import { spawn } from "node:child_process";
9
- import { isIP } from "node:net";
10
- import { createServer } from "node:http";
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
+ }
169
+ // src/lib/base-url.ts
170
+ const API_PATH = "/api/v1";
171
+ /**
172
+ * The API base URL the CLI talks to, by the same rule as the SDK's client: surrounding
173
+ * whitespace and trailing slashes are removed, a bare origin (`https://krova.cloud`) gets
174
+ * `/api/v1` appended, and any other path is kept as given. Call it only with a value that
175
+ * is set; an empty or whitespace-only one means "not set" and is the caller's to skip.
176
+ */
177
+ function normalizeBaseUrl(raw) {
178
+ const trimmed = raw.trim().replace(/\/+$/, "");
179
+ let url;
180
+ try {
181
+ url = new URL(trimmed);
182
+ } catch {
183
+ return trimmed;
184
+ }
185
+ if (url.pathname === "/" && !url.search && !url.hash) return `${trimmed}${API_PATH}`;
186
+ return trimmed;
187
+ }
188
+ // src/lib/config.ts
189
+ const DEFAULT_BASE_URL = "https://krova.cloud/api/v1";
13
190
  const DEFAULT_CONTEXT_NAME = "default";
14
191
  const ENV = {
15
192
  apiKey: "KROVA_API_KEY",
16
193
  spaceId: "KROVA_SPACE_ID",
17
194
  baseUrl: "KROVA_BASE_URL",
18
- context: "KROVA_CONTEXT"
195
+ context: "KROVA_CONTEXT",
196
+ npmRegistry: "KROVA_NPM_REGISTRY"
19
197
  };
20
198
  function configDir() {
21
199
  const xdg = (process.env.XDG_CONFIG_HOME ?? "").trim();
@@ -59,13 +237,26 @@ function save(cfg) {
59
237
  if (cfg.currentContext) clean.currentContext = cfg.currentContext;
60
238
  if (cfg.contexts && cfg.contexts.length) clean.contexts = cfg.contexts.map((c) => {
61
239
  const o = { name: c.name };
62
- if (c.apiKey) o.apiKey = c.apiKey;
240
+ if (c.apiKey && c.keyStorage !== "keychain") o.apiKey = c.apiKey;
241
+ if (c.keyStorage) o.keyStorage = c.keyStorage;
63
242
  if (c.spaceId) o.spaceId = c.spaceId;
64
243
  if (c.spaceName) o.spaceName = c.spaceName;
65
244
  if (c.baseUrl) o.baseUrl = c.baseUrl;
66
245
  return o;
67
246
  });
68
- writeFileSync(path, `${JSON.stringify(clean, null, 2)}\n`, { mode: 384 });
247
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
248
+ try {
249
+ writeFileSync(tmp, `${JSON.stringify(clean, null, 2)}\n`, {
250
+ mode: 384,
251
+ flag: "wx"
252
+ });
253
+ renameSync(tmp, path);
254
+ } catch (e) {
255
+ try {
256
+ unlinkSync(tmp);
257
+ } catch {}
258
+ throw e;
259
+ }
69
260
  chmodSync(path, 384);
70
261
  }
71
262
  function find(cfg, name) {
@@ -95,6 +286,8 @@ function upsert(cfg, incoming) {
95
286
  if ((incoming.baseUrl ?? "").trim()) ctx.baseUrl = incoming.baseUrl;
96
287
  return ctx;
97
288
  }
289
+ /** Drop a context from `cfg` in memory only (the caller still calls `save`). Does not touch the
290
+ * keychain: use `removeContext` to remove a context and its keychain item together. */
98
291
  function remove(cfg, name) {
99
292
  const before = (cfg.contexts ?? []).length;
100
293
  cfg.contexts = (cfg.contexts ?? []).filter((c) => c.name !== name);
@@ -102,6 +295,26 @@ function remove(cfg, name) {
102
295
  if (cfg.currentContext === name) cfg.currentContext = cfg.contexts[0]?.name ?? "";
103
296
  return true;
104
297
  }
298
+ /** Remove a context, save the config, and only then delete its keychain item, so a failed save
299
+ * leaves both the context and its key intact. Returns false when there is no such context. */
300
+ function removeContext(cfg, name, persist = () => save(cfg)) {
301
+ const gone = find(cfg, name);
302
+ if (!gone) return false;
303
+ const snapshot = {
304
+ contexts: [...cfg.contexts ?? []],
305
+ currentContext: cfg.currentContext
306
+ };
307
+ remove(cfg, name);
308
+ try {
309
+ persist();
310
+ } catch (e) {
311
+ cfg.contexts = snapshot.contexts;
312
+ cfg.currentContext = snapshot.currentContext;
313
+ throw e;
314
+ }
315
+ deleteContextKey(gone);
316
+ return true;
317
+ }
105
318
  /** Resolve credentials with precedence flag > env > active context. */
106
319
  function resolve(cfg, flags) {
107
320
  const ctx = current(cfg, (flags.context ?? "").trim() || process.env[ENV.context]);
@@ -111,27 +324,211 @@ function resolve(cfg, flags) {
111
324
  if ((ctxVal ?? "").trim()) return [ctxVal, "context"];
112
325
  return ["", ""];
113
326
  };
114
- const [apiKey, apiKeySource] = pick(flags.apiKey, process.env[ENV.apiKey], ctx?.apiKey);
327
+ const overridden = Boolean((flags.apiKey ?? "").trim() || (process.env[ENV.apiKey] ?? "").trim());
328
+ const [apiKey, apiKeySource] = pick(flags.apiKey, process.env[ENV.apiKey], overridden || !ctx ? void 0 : contextKey(ctx));
115
329
  const [spaceId, spaceIdSource] = pick(flags.space, process.env[ENV.spaceId], ctx?.spaceId);
116
330
  const [baseUrlRaw] = pick(flags.baseUrl, process.env[ENV.baseUrl], ctx?.baseUrl);
117
331
  return {
118
332
  apiKey,
119
333
  spaceId,
120
- baseUrl: baseUrlRaw || "https://krova.cloud/api/v1",
334
+ baseUrl: baseUrlRaw ? normalizeBaseUrl(baseUrlRaw) : DEFAULT_BASE_URL,
121
335
  apiKeySource,
336
+ apiKeyStorage: apiKeySource === "context" && ctx ? storageOf(ctx) : "",
122
337
  spaceIdSource,
123
338
  contextName: ctx?.name ?? ""
124
339
  };
125
340
  }
341
+ function storageOf(ctx) {
342
+ return ctx.keyStorage === "keychain" ? "keychain" : "file";
343
+ }
344
+ const errText$1 = (e) => e instanceof Error ? e.message : String(e);
345
+ /** One short line on stderr (stdout stays clean for --json). */
346
+ function warn(msg) {
347
+ process.stderr.write(`krova: ${msg}\n`);
348
+ }
349
+ /** The context's API key: from the file, or from the OS keychain for a keychain context.
350
+ * A keychain that cannot be read warns on stderr and returns "" (so the caller sees
351
+ * "no key" and is told to log in again) instead of crashing every command. */
352
+ function contextKey(ctx) {
353
+ if (storageOf(ctx) !== "keychain") return ctx.apiKey ?? "";
354
+ try {
355
+ const key = readBackend().get(ctx.name);
356
+ if (key) return key;
357
+ 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`);
358
+ } catch (e) {
359
+ 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`);
360
+ }
361
+ return "";
362
+ }
363
+ /** Write `key` to the keychain (verified by a read-back) and mark `ctx` as a keychain
364
+ * context, else keep it in the 0600 file with a one-line stderr message. Mutates `ctx`;
365
+ * the caller still calls `save`. Never throws. */
366
+ function setContextKey(ctx, key) {
367
+ try {
368
+ const backend = writeBackend();
369
+ backend.set(ctx.name, key);
370
+ if (backend.get(ctx.name) !== key) {
371
+ try {
372
+ backend.delete(ctx.name);
373
+ } catch {}
374
+ throw new Error("the keychain did not return the stored key");
375
+ }
376
+ ctx.keyStorage = "keychain";
377
+ ctx.apiKey = void 0;
378
+ return {
379
+ storage: "keychain",
380
+ backend: backend.name
381
+ };
382
+ } catch (e) {
383
+ if (!(e instanceof KeychainUnavailableError && e.optOut)) warn(`OS keychain unavailable (${errText$1(e)}); storing the API key in ${configPath()} (mode 0600) instead`);
384
+ }
385
+ if (storageOf(ctx) === "keychain") deleteContextKey(ctx);
386
+ ctx.keyStorage = "file";
387
+ ctx.apiKey = key;
388
+ return { storage: "file" };
389
+ }
390
+ /** Delete the context's keychain item, if it has one. Failure is a warning, not an error:
391
+ * the context is being removed either way. */
392
+ function deleteContextKey(ctx) {
393
+ if (storageOf(ctx) !== "keychain") return;
394
+ try {
395
+ readBackend().delete(ctx.name);
396
+ } catch (e) {
397
+ warn(`could not delete the keychain item for context "${ctx.name}" (${errText$1(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${ctx.name})`);
398
+ }
399
+ }
400
+ /** Rename a context and save the config. A keychain key moves with it: the new item is written
401
+ * and verified first, the config is saved, and only then is the old item deleted. A failure at
402
+ * any step before that leaves the context (and its old item) as it was. */
403
+ function renameContext(cfg, oldName, newName, persist = () => save(cfg)) {
404
+ const c = find(cfg, oldName);
405
+ if (!c) throw new Error(`no context named "${oldName}"`);
406
+ assertContextName(newName);
407
+ if (find(cfg, newName)) throw new Error(`a context named "${newName}" already exists`);
408
+ const backend = storageOf(c) === "keychain" ? readBackend() : void 0;
409
+ if (backend) {
410
+ let key;
411
+ try {
412
+ key = backend.get(oldName);
413
+ } catch (e) {
414
+ throw new Error(`could not read the key for "${oldName}" from the OS keychain: ${errText$1(e)}`);
415
+ }
416
+ if (!key) throw new Error(`the API key for "${oldName}" is not in the OS keychain; run \`krova login --context ${oldName}\` first`);
417
+ try {
418
+ backend.set(newName, key);
419
+ if (backend.get(newName) !== key) throw new Error("the keychain did not return the stored key");
420
+ } catch (e) {
421
+ try {
422
+ backend.delete(newName);
423
+ } catch {}
424
+ throw new Error(`could not move the key to "${newName}" in the OS keychain: ${errText$1(e)}`);
425
+ }
426
+ }
427
+ const wasCurrent = cfg.currentContext === oldName;
428
+ c.name = newName;
429
+ if (wasCurrent) cfg.currentContext = newName;
430
+ try {
431
+ persist();
432
+ } catch (e) {
433
+ c.name = oldName;
434
+ if (wasCurrent) cfg.currentContext = oldName;
435
+ if (backend) try {
436
+ backend.delete(newName);
437
+ } catch {}
438
+ throw e;
439
+ }
440
+ if (backend) try {
441
+ backend.delete(oldName);
442
+ } catch (e) {
443
+ warn(`renamed, but could not delete the old keychain item (${errText$1(e)}); remove it by hand (service ${KEYCHAIN_SERVICE}, account ${oldName})`);
444
+ }
445
+ }
446
+ /** Move every file-stored key into the keychain. A key leaves the file only after the
447
+ * keychain read-back matches; `save` runs after each context so a later failure never
448
+ * loses an earlier move. Throws when no keychain can be used at all. */
449
+ function migrateKeysToKeychain(cfg) {
450
+ const backend = writeBackend();
451
+ const entries = [];
452
+ for (const ctx of cfg.contexts ?? []) {
453
+ if (storageOf(ctx) === "keychain") {
454
+ entries.push({
455
+ context: ctx.name,
456
+ result: "skipped",
457
+ detail: "already in the keychain"
458
+ });
459
+ continue;
460
+ }
461
+ const key = (ctx.apiKey ?? "").trim();
462
+ if (!key) {
463
+ entries.push({
464
+ context: ctx.name,
465
+ result: "skipped",
466
+ detail: "no API key stored"
467
+ });
468
+ continue;
469
+ }
470
+ try {
471
+ backend.set(ctx.name, key);
472
+ if (backend.get(ctx.name) !== key) {
473
+ try {
474
+ backend.delete(ctx.name);
475
+ } catch {}
476
+ throw new Error("the keychain did not return the stored key");
477
+ }
478
+ } catch (e) {
479
+ entries.push({
480
+ context: ctx.name,
481
+ result: "failed",
482
+ detail: errText$1(e)
483
+ });
484
+ continue;
485
+ }
486
+ ctx.keyStorage = "keychain";
487
+ ctx.apiKey = void 0;
488
+ save(cfg);
489
+ entries.push({
490
+ context: ctx.name,
491
+ result: "migrated"
492
+ });
493
+ }
494
+ return {
495
+ backend: backend.name,
496
+ entries
497
+ };
498
+ }
499
+ /** A context name becomes a keychain account passed to `security` and `secret-tool`, so one that
500
+ * starts with `-` could be read as an option. */
501
+ function assertContextName(name) {
502
+ if (name.trim().startsWith("-")) throw new Error(`context names cannot start with "-" (got "${name}")`);
503
+ }
126
504
  function sanitizeContextName(name) {
127
- return name.trim().toLowerCase().replace(/\s+/g, "-");
505
+ const clean = name.trim().toLowerCase().replace(/\s+/g, "-");
506
+ assertContextName(clean);
507
+ return clean;
128
508
  }
129
509
  function maskKey(key) {
130
510
  if (!key) return "";
131
511
  if (key.length <= 8) return "****";
132
512
  return `${key.slice(0, 6)}…${key.slice(-4)}`;
133
513
  }
514
+ /** The key as it should be printed: masked unless `--show-secrets` was passed. */
515
+ function displayKey(key, showSecrets) {
516
+ return showSecrets ? key : maskKey(key);
517
+ }
134
518
  // src/lib/output.ts
519
+ /**
520
+ * Stop quietly when the reader of stdout goes away (`krova cubes list | head -1`),
521
+ * the way standard Unix tools do: an EPIPE ends the process with status 0 and no
522
+ * stack trace. Every other write error is still reported, as `Error: ...` with
523
+ * status 1; only the one expected case is silent.
524
+ */
525
+ function exitQuietlyOnBrokenPipe(stream = process.stdout, exit = (code) => process.exit(code), warn = (text) => void process.stderr.write(text)) {
526
+ stream.on("error", (err) => {
527
+ if (err?.code === "EPIPE") return exit(0);
528
+ warn(`Error: ${err instanceof Error ? err.message : String(err)}\n`);
529
+ exit(1);
530
+ });
531
+ }
135
532
  function printJSON(value) {
136
533
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
137
534
  }
@@ -178,7 +575,7 @@ async function rawRequest(opts) {
178
575
  const headers = { Accept: "application/json" };
179
576
  if (opts.apiKey) headers["X-API-KEY"] = opts.apiKey;
180
577
  if (opts.body !== void 0) headers["Content-Type"] = "application/json";
181
- const res = await fetch(`${opts.baseUrl.replace(/\/+$/, "")}${opts.path}`, {
578
+ const res = await fetch(`${normalizeBaseUrl(opts.baseUrl)}${opts.path}`, {
182
579
  method: opts.method,
183
580
  headers,
184
581
  body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
@@ -200,6 +597,25 @@ async function rawRequest(opts) {
200
597
  clearTimeout(timer);
201
598
  }
202
599
  }
600
+ // src/lib/output-format.ts
601
+ /** The values the global `-o, --output <format>` flag accepts. */
602
+ const OUTPUT_FORMATS = ["table", "json"];
603
+ /** Values worth completing after a flag, keyed by the flag as typed. */
604
+ const FLAG_VALUE_CHOICES = {
605
+ "-o": OUTPUT_FORMATS,
606
+ "--output": OUTPUT_FORMATS
607
+ };
608
+ /**
609
+ * Validate the `--output` value. Unset means the default, `table`.
610
+ * Throws a one-line error for anything else, so a typo never silently
611
+ * falls back to a table in a script that expects JSON.
612
+ */
613
+ function parseOutputFormat(raw) {
614
+ if (raw === void 0 || raw === null || raw === "") return "table";
615
+ const value = String(raw);
616
+ if (OUTPUT_FORMATS.includes(value)) return value;
617
+ throw new Error(`--output must be "json" or "table" (got "${value}")`);
618
+ }
203
619
  // src/lib/runtime.ts
204
620
  /** Parse a Go-style duration ("30s", "500ms", "2m", "1h") to ms. Non-positive
205
621
  * or unparseable floors to 30s (matches the Go requestTimeout behavior). */
@@ -223,6 +639,12 @@ function parseDuration(input) {
223
639
  }
224
640
  return total > 0 ? total : 3e4;
225
641
  }
642
+ /** What the last `getRuntime` call resolved; the top-level error handler reads it
643
+ * to name the base URL in a connection hint and to stay quiet in JSON mode. */
644
+ let active;
645
+ function activeRuntime() {
646
+ return active;
647
+ }
226
648
  function getRuntime(cmd) {
227
649
  const opts = cmd.optsWithGlobals();
228
650
  const flags = {
@@ -232,11 +654,17 @@ function getRuntime(cmd) {
232
654
  context: opts.context
233
655
  };
234
656
  const cfg = load();
657
+ const res = resolve(cfg, flags);
658
+ const json = Boolean(opts.json) || parseOutputFormat(opts.output) === "json";
659
+ active = {
660
+ baseUrl: res.baseUrl,
661
+ json
662
+ };
235
663
  return {
236
664
  flags,
237
665
  cfg,
238
- res: resolve(cfg, flags),
239
- json: Boolean(opts.json),
666
+ res,
667
+ json,
240
668
  timeoutMs: parseDuration(opts.timeout)
241
669
  };
242
670
  }
@@ -319,18 +747,23 @@ async function persistLogin(input) {
319
747
  name = sanitizeContextName(name);
320
748
  const cur = upsert(cfg, {
321
749
  name,
322
- apiKey: input.apiKey,
323
750
  spaceId,
324
751
  spaceName,
325
752
  baseUrl: input.baseUrl
326
753
  });
754
+ const stored = setContextKey(cur, input.apiKey);
327
755
  cfg.currentContext = cur.name;
328
756
  save(cfg);
329
757
  return {
330
758
  ctxName: cur.name,
331
- spaceName: cur.spaceName ?? ""
759
+ spaceName: cur.spaceName ?? "",
760
+ stored
332
761
  };
333
762
  }
763
+ /** The line printed after a login: says where the key went. */
764
+ function loginMessage(ctxName, stored) {
765
+ return stored.storage === "keychain" ? `Logged in. Saved context "${ctxName}" to ${configPath()} (API key in the ${stored.backend})` : `Logged in. Saved context "${ctxName}" to ${configPath()}`;
766
+ }
334
767
  // src/commands/auth.ts
335
768
  /** Prompt for an API key. Hidden echo when stdin is a TTY. */
336
769
  function promptAPIKey() {
@@ -376,23 +809,24 @@ function authCommand() {
376
809
  let key = opts.apiKey || rt.flags.apiKey || "";
377
810
  if (!key.trim()) key = await promptAPIKey();
378
811
  if (!key.trim()) throw new Error("no API key provided");
379
- const { ctxName, spaceName } = await persistLogin({
812
+ const { ctxName, spaceName, stored } = await persistLogin({
380
813
  apiKey: key.trim(),
381
814
  baseUrl: rt.res.baseUrl,
382
815
  spaceId: opts.space,
383
- ctxName: opts.context,
816
+ ctxName: rt.flags.context,
384
817
  timeoutMs: rt.timeoutMs
385
818
  });
386
- process.stdout.write(`Logged in. Saved context "${ctxName}" to ${configPath()}\n`);
819
+ process.stdout.write(`${loginMessage(ctxName, stored)}\n`);
387
820
  if (spaceName) process.stdout.write(`Space: ${spaceName}\n`);
388
821
  });
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) => {
822
+ 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
823
  const rt = getRuntime(cmd);
824
+ const showSecrets = Boolean(opts.showSecrets);
391
825
  const offline = Boolean(opts.offline);
392
826
  const probe = offline ? { state: "missing" } : await probeAuth(rt.res.baseUrl, rt.res.apiKey, rt.timeoutMs);
393
827
  const hasKey = Boolean(rt.res.apiKey);
394
828
  const authenticated = offline ? hasKey : probe.state === "valid";
395
- const detail = offline || !hasKey ? "" : probe.state === "rejected" ? `the API rejected this key (HTTP ${probe.status}) — it was revoked 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" : "";
829
+ 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
830
  const spaceId = probe.state === "valid" ? probe.space.id : rt.res.spaceId;
397
831
  if (rt.json) return printJSON({
398
832
  authenticated,
@@ -401,7 +835,8 @@ function authCommand() {
401
835
  detail: detail || void 0,
402
836
  context: rt.res.contextName,
403
837
  apiKeySource: rt.res.apiKeySource,
404
- apiKeyMasked: maskKey(rt.res.apiKey),
838
+ apiKeyStorage: rt.res.apiKeyStorage || void 0,
839
+ ...showSecrets ? { apiKey: rt.res.apiKey } : { apiKeyMasked: displayKey(rt.res.apiKey, false) },
405
840
  spaceId,
406
841
  spaceSource: rt.res.spaceIdSource,
407
842
  baseUrl: rt.res.baseUrl,
@@ -410,7 +845,7 @@ function authCommand() {
410
845
  printKeyValue([
411
846
  ["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
847
  ["Context", rt.res.contextName || "—"],
413
- ["API key", rt.res.apiKey ? `${maskKey(rt.res.apiKey)} (${rt.res.apiKeySource})` : "—"],
848
+ ["API key", rt.res.apiKey ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : ""})` : "—"],
414
849
  ["Space ID", spaceId ? `${spaceId} (${rt.res.spaceIdSource})` : "—"],
415
850
  ["Base URL", rt.res.baseUrl],
416
851
  ["Config", configPath()]
@@ -418,6 +853,45 @@ function authCommand() {
418
853
  if (detail) process.stdout.write(`\n${detail}\n`);
419
854
  if (!hasKey || probe.state === "rejected") process.exitCode = 1;
420
855
  });
856
+ 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) => {
857
+ const rt = getRuntime(cmd);
858
+ const cfg = load();
859
+ const name = (opts.context ?? rt.flags.context ?? "").trim() || rt.res.contextName;
860
+ if (!name) throw new Error(`not logged in: no saved context in ${configPath()}`);
861
+ if (!find(cfg, name)) throw new Error(`no context named "${name}"`);
862
+ const wasCurrent = cfg.currentContext === name;
863
+ removeContext(cfg, name);
864
+ const current = cfg.currentContext || null;
865
+ if (rt.json) return printJSON({
866
+ context: name,
867
+ result: "logged_out",
868
+ current
869
+ });
870
+ process.stdout.write(`Logged out of ${name}. The API key still works until you revoke it in the dashboard (Settings > API keys).\n`);
871
+ if (wasCurrent && current) process.stdout.write(`Now using ${current}.\n`);
872
+ });
873
+ auth.command("migrate-keychain").description("move API keys saved in the config file into the OS keychain").action((_opts, cmd) => {
874
+ const rt = getRuntime(cmd);
875
+ const cfg = load();
876
+ let result;
877
+ try {
878
+ result = migrateKeysToKeychain(cfg);
879
+ } catch (e) {
880
+ 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()}`);
881
+ throw e;
882
+ }
883
+ if (result.entries.filter((x) => x.result === "failed").length > 0) process.exitCode = 1;
884
+ if (rt.json) return printJSON({
885
+ keychain: result.backend,
886
+ results: result.entries
887
+ });
888
+ if (result.entries.length === 0) process.stdout.write("No contexts to migrate.\n");
889
+ for (const x of result.entries) {
890
+ const tail = x.detail ? ` (${x.detail})` : "";
891
+ process.stdout.write(`${x.result === "migrated" ? "Moved" : x.result === "failed" ? "FAILED" : "Skipped"} ${x.context}${x.result === "migrated" ? ` to the ${result.backend}` : tail}\n`);
892
+ if (x.result === "failed") process.stderr.write(` ${x.detail}\n`);
893
+ }
894
+ });
421
895
  return auth;
422
896
  }
423
897
  // src/commands/backups.ts
@@ -612,17 +1086,210 @@ function imagesCommand() {
612
1086
  function pricingCommand() {
613
1087
  return catalogCmd("pricing", "show per-resource hourly pricing", (c) => c.catalog.pricing());
614
1088
  }
1089
+ // src/lib/completion.ts
1090
+ const COMPLETION_SHELLS = [
1091
+ "bash",
1092
+ "zsh",
1093
+ "fish"
1094
+ ];
1095
+ const oneLine = (s) => s.split("\n")[0].replace(/\s+/g, " ").trim();
1096
+ /** Walk the commander tree (visible commands and options only). */
1097
+ function walkCommands(cmd, path = []) {
1098
+ const help = cmd.createHelp();
1099
+ return {
1100
+ path,
1101
+ aliases: cmd.aliases(),
1102
+ description: oneLine(cmd.description()),
1103
+ options: help.visibleOptions(cmd).map((o) => ({
1104
+ long: o.long,
1105
+ short: o.short,
1106
+ description: oneLine(o.description),
1107
+ takesValue: o.required || o.optional
1108
+ })),
1109
+ commands: help.visibleCommands(cmd).map((c) => walkCommands(c, [...path, c.name()]))
1110
+ };
1111
+ }
1112
+ /** Shell single-quote: safe inside bash, zsh and fish single quotes. */
1113
+ const sq = (s) => `'${s.replace(/'/g, "'\\''")}'`;
1114
+ const fishSq = (s) => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
1115
+ const flat = (node) => [node, ...node.commands.flatMap(flat)];
1116
+ const key = (path) => path.join(" ");
1117
+ const optionWords = (n) => n.options.flatMap((o) => [o.long, o.short].filter((x) => Boolean(x)));
1118
+ const commandWords = (n) => n.commands.flatMap((c) => [c.path.at(-1), ...c.aliases]);
1119
+ /** Every (parent path, typed word) -> child path transition, aliases included. */
1120
+ function transitions(root) {
1121
+ return flat(root).flatMap((parent) => parent.commands.flatMap((c) => [c.path.at(-1), ...c.aliases].map((word) => ({
1122
+ from: key(parent.path),
1123
+ word,
1124
+ to: key(c.path)
1125
+ }))));
1126
+ }
1127
+ /** Every flag in the tree that takes a value but has no fixed choices (paths, names, numbers). */
1128
+ function freeValueFlags(root, choices) {
1129
+ const out = /* @__PURE__ */ new Set();
1130
+ for (const n of flat(root)) for (const o of n.options) {
1131
+ if (!o.takesValue) continue;
1132
+ for (const f of [o.long, o.short]) if (f && !choices[f]) out.add(f);
1133
+ }
1134
+ return [...out];
1135
+ }
1136
+ function bash(root, name, choices) {
1137
+ const fn = `_${name}_complete`;
1138
+ return `${[
1139
+ `# bash completion for ${name}, generated by \`${name} completion bash\``,
1140
+ `${fn}() {`,
1141
+ ` local cur prev cpath="" w next i`,
1142
+ ` cur="\${COMP_WORDS[COMP_CWORD]}"`,
1143
+ ` prev="\${COMP_WORDS[COMP_CWORD-1]}"`,
1144
+ ` for ((i=1; i<COMP_CWORD; i++)); do`,
1145
+ ` w="\${COMP_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 "$prev" in`,
1153
+ ...Object.entries(choices).map(([flag, values]) => ` ${sq(flag)}) COMPREPLY=( $(compgen -W ${sq(values.join(" "))} -- "$cur") ); return;;`),
1154
+ ...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) COMPREPLY=(); return;;`),
1155
+ ` esac`,
1156
+ ` local cmds="" opts=""`,
1157
+ ` case "$cpath" in`,
1158
+ ...flat(root).map((n) => ` ${sq(key(n.path))}) cmds=${sq(commandWords(n).join(" "))}; opts=${sq(optionWords(n).join(" "))};;`),
1159
+ ` esac`,
1160
+ ` if [[ "$cur" == -* ]]; then`,
1161
+ ` COMPREPLY=( $(compgen -W "$opts" -- "$cur") )`,
1162
+ ` else`,
1163
+ ` COMPREPLY=( $(compgen -W "$cmds" -- "$cur") )`,
1164
+ ` fi`,
1165
+ `}`,
1166
+ `complete -o default -F ${fn} ${name}`
1167
+ ].join("\n")}\n`;
1168
+ }
1169
+ function zsh(root, name, choices) {
1170
+ const fn = `_${name}`;
1171
+ const item = (word, desc) => sq(`${word.replace(/:/g, "\\:")}${desc ? `:${desc}` : ""}`);
1172
+ return `${[
1173
+ `#compdef ${name}`,
1174
+ `# zsh completion for ${name}, generated by \`${name} completion zsh\``,
1175
+ `${fn}() {`,
1176
+ ` local cpath="" w next i`,
1177
+ ` local -a cmds opts`,
1178
+ ` for (( i=2; i<CURRENT; i++ )); do`,
1179
+ ` w="\${words[i]}"`,
1180
+ ` next=""`,
1181
+ ` case "$cpath/$w" in`,
1182
+ ...transitions(root).map((t) => ` ${sq(`${t.from}/${t.word}`)}) next=${sq(t.to)};;`),
1183
+ ` esac`,
1184
+ ` [[ -n "$next" ]] && cpath="$next"`,
1185
+ ` done`,
1186
+ ` case "\${words[CURRENT-1]}" in`,
1187
+ ...Object.entries(choices).map(([flag, values]) => ` ${sq(flag)}) compadd -- ${values.map(sq).join(" ")}; return;;`),
1188
+ ...freeValueFlags(root, choices).map((f) => ` ${sq(f)}) _files; return;;`),
1189
+ ` esac`,
1190
+ ` case "$cpath" in`,
1191
+ ...flat(root).flatMap((n) => {
1192
+ const cmdItems = n.commands.flatMap((c) => [c.path.at(-1), ...c.aliases].map((w) => item(w, c.description)));
1193
+ const optItems = n.options.flatMap((o) => [o.long, o.short].filter((x) => Boolean(x)).map((w) => item(w, o.description)));
1194
+ return [
1195
+ ` ${sq(key(n.path))})`,
1196
+ ` cmds=(${cmdItems.join(" ")})`,
1197
+ ` opts=(${optItems.join(" ")});;`
1198
+ ];
1199
+ }),
1200
+ ` esac`,
1201
+ ` if [[ "$PREFIX" == -* ]]; then`,
1202
+ ` _describe -t options 'option' opts`,
1203
+ ` else`,
1204
+ ` _describe -t commands 'command' cmds`,
1205
+ ` (( \${#cmds} )) || _files`,
1206
+ ` fi`,
1207
+ `}`,
1208
+ `if [ "$funcstack[1]" = "${fn}" ]; then`,
1209
+ ` ${fn} "$@"`,
1210
+ `else`,
1211
+ ` compdef ${fn} ${name}`,
1212
+ `fi`
1213
+ ].join("\n")}\n`;
1214
+ }
1215
+ function fish(root, name, choices) {
1216
+ const fn = `__${name}_path`;
1217
+ const rootKey = "root";
1218
+ const k = (path) => path.length ? key(path) : rootKey;
1219
+ const lines = [
1220
+ `# fish completion for ${name}, generated by \`${name} completion fish\``,
1221
+ `function ${fn}`,
1222
+ ` set -l cpath ${rootKey}`,
1223
+ ` set -l tokens (commandline -opc)`,
1224
+ ` set -e tokens[1]`,
1225
+ ` for w in $tokens`,
1226
+ ` switch "$cpath/$w"`,
1227
+ ...transitions(root).flatMap((t) => [` case ${fishSq(`${t.from || rootKey}/${t.word}`)}`, ` set cpath ${fishSq(t.to)}`]),
1228
+ ` end`,
1229
+ ` end`,
1230
+ ` echo $cpath`,
1231
+ `end`
1232
+ ];
1233
+ for (const n of flat(root)) {
1234
+ const cond = `-n ${fishSq(`test (${fn}) = ${fishSq(k(n.path))}`)}`;
1235
+ if (n.commands.length) lines.push(`complete -c ${name} ${cond} -f`);
1236
+ 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)}`);
1237
+ for (const o of n.options) {
1238
+ const parts = [`complete -c ${name} ${cond}`];
1239
+ if (o.short) parts.push(`-s ${o.short.replace(/^-/, "")}`);
1240
+ if (o.long) parts.push(`-l ${o.long.replace(/^--/, "")}`);
1241
+ const values = [o.long, o.short].map((f) => f ? choices[f] : void 0).find(Boolean);
1242
+ if (values) parts.push(`-x -a ${fishSq(values.join(" "))}`);
1243
+ else if (o.takesValue) parts.push("-r");
1244
+ parts.push(`-d ${fishSq(o.description)}`);
1245
+ lines.push(parts.join(" "));
1246
+ }
1247
+ }
1248
+ return `${lines.join("\n")}\n`;
1249
+ }
1250
+ /** Generate the completion script for `shell` from the live command tree under `root`. */
1251
+ function generateCompletion(shell, root, choices = FLAG_VALUE_CHOICES) {
1252
+ const tree = walkCommands(root);
1253
+ const name = root.name();
1254
+ if (shell === "bash") return bash(tree, name, choices);
1255
+ if (shell === "zsh") return zsh(tree, name, choices);
1256
+ return fish(tree, name, choices);
1257
+ }
1258
+ const COMPLETION_INSTALL_HELP = `
1259
+ Install (restart your shell afterward):
1260
+
1261
+ bash mkdir -p ~/.local/share/bash-completion/completions
1262
+ krova completion bash > ~/.local/share/bash-completion/completions/krova
1263
+ (or add 'source <(krova completion bash)' to ~/.bashrc)
1264
+ zsh krova completion zsh > "\${fpath[1]}/_krova"
1265
+ (needs 'autoload -U compinit && compinit' in ~/.zshrc; or add
1266
+ 'source <(krova completion zsh)' to ~/.zshrc after compinit)
1267
+ fish krova completion fish > ~/.config/fish/completions/krova.fish
1268
+
1269
+ The script is generated from the commands in your installed version, so
1270
+ re-run it after you upgrade the CLI.
1271
+ `;
1272
+ // src/commands/completion.ts
1273
+ function completionCommand() {
1274
+ 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) => {
1275
+ let root = cmd;
1276
+ while (root.parent) root = root.parent;
1277
+ process.stdout.write(generateCompletion(shell, root));
1278
+ });
1279
+ }
615
1280
  // src/commands/context.ts
616
1281
  function contextCommand() {
617
1282
  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((_opts, cmd) => {
619
- const { json } = getRuntime(cmd);
1283
+ 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) => {
1284
+ const g = cmd.optsWithGlobals();
1285
+ const json = Boolean(g.json) || parseOutputFormat(g.output) === "json";
620
1286
  const cfg = load();
621
1287
  if (json) return printJSON({
622
1288
  currentContext: cfg.currentContext ?? "",
623
1289
  contexts: (cfg.contexts ?? []).map((c) => ({
624
1290
  name: c.name,
625
- apiKey: maskKey(c.apiKey ?? ""),
1291
+ apiKey: opts.showSecrets || storageOf(c) === "file" ? displayKey(contextKey(c), Boolean(opts.showSecrets)) : "****",
1292
+ keyStorage: storageOf(c),
626
1293
  spaceId: c.spaceId ?? "",
627
1294
  spaceName: c.spaceName ?? "",
628
1295
  baseUrl: c.baseUrl ?? ""
@@ -657,22 +1324,245 @@ function contextCommand() {
657
1324
  ctx.command("rename").argument("<old>", "current name").argument("<new>", "new name").description("rename a context").action((oldName, newName) => {
658
1325
  const cfg = load();
659
1326
  if (!newName.trim()) throw new Error("new name must not be empty");
660
- const c = (cfg.contexts ?? []).find((x) => x.name === oldName);
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);
1327
+ renameContext(cfg, oldName, newName);
666
1328
  process.stdout.write(`Renamed ${oldName} → ${newName}\n`);
667
1329
  });
668
1330
  ctx.command("delete").aliases(["rm"]).argument("<name>", "context name").description("delete a context").action((name) => {
669
- const cfg = load();
670
- if (!remove(cfg, name)) throw new Error(`no context named "${name}"`);
671
- save(cfg);
1331
+ if (!removeContext(load(), name)) throw new Error(`no context named "${name}"`);
672
1332
  process.stdout.write(`Deleted context ${name}\n`);
673
1333
  });
674
1334
  return ctx;
675
1335
  }
1336
+ // src/lib/create-prompt.ts
1337
+ /**
1338
+ * The interactive half of `krova cubes create`.
1339
+ *
1340
+ * Everything the prompt flow touches from the outside (the terminal, the
1341
+ * catalog, the key files) comes in through an interface, so tests drive it
1342
+ * with scripted answers and never need a TTY, a network or a real home dir.
1343
+ */
1344
+ /** Defaults for the resource flags. `cubes create` registers them on its options too. */
1345
+ const DEFAULT_RESOURCES = {
1346
+ vcpu: "1",
1347
+ ram: "1",
1348
+ disk: "10"
1349
+ };
1350
+ /** Input ended (Ctrl+C, Ctrl+D, closed pipe) before the questions were answered. */
1351
+ var PromptAbortError = class extends Error {
1352
+ constructor() {
1353
+ super("input closed");
1354
+ this.name = "PromptAbortError";
1355
+ }
1356
+ };
1357
+ /** Prompts run only on a real terminal, and never when the caller asked for JSON. */
1358
+ function isInteractive(opts) {
1359
+ if (opts.json) return false;
1360
+ const stdin = opts.stdin ?? process.stdin;
1361
+ const stdout = opts.stdout ?? process.stdout;
1362
+ return Boolean(stdin.isTTY && stdout.isTTY);
1363
+ }
1364
+ /** The real terminal, via node:readline/promises. */
1365
+ function createReadlineIO() {
1366
+ const rl = readline$1.createInterface({
1367
+ input: process.stdin,
1368
+ output: process.stdout
1369
+ });
1370
+ const closed = new Promise((_, reject) => {
1371
+ rl.once("close", () => reject(new PromptAbortError()));
1372
+ });
1373
+ closed.catch(() => void 0);
1374
+ rl.on("SIGINT", () => rl.close());
1375
+ return {
1376
+ ask: (question) => Promise.race([rl.question(question), closed]),
1377
+ write: (text) => void process.stdout.write(text),
1378
+ warn: (text) => void process.stderr.write(text),
1379
+ close: () => rl.close()
1380
+ };
1381
+ }
1382
+ function defaultKeyFiles() {
1383
+ return {
1384
+ home: homedir(),
1385
+ readFile: (path) => readFile(path, "utf8")
1386
+ };
1387
+ }
1388
+ /** Key files offered, in order. Public halves only; a private key is never opened. */
1389
+ const KEY_CANDIDATE_FILES = ["id_ed25519.pub", "id_rsa.pub"];
1390
+ const KEY_PREFIXES = [
1391
+ "ssh-rsa",
1392
+ "ssh-ed25519",
1393
+ "ecdsa-sha2-nistp256",
1394
+ "ecdsa-sha2-nistp384",
1395
+ "ecdsa-sha2-nistp521",
1396
+ "ssh-dss",
1397
+ "sk-ssh-ed25519@openssh.com",
1398
+ "sk-ecdsa-sha2-nistp256@openssh.com"
1399
+ ];
1400
+ /** A cube name: 1 to 64 characters after trimming, no control characters. Returns the trimmed name or null. */
1401
+ function validCubeName(raw) {
1402
+ const name = raw.trim();
1403
+ if (name.length === 0 || name.length > 64) return null;
1404
+ if (/[\x00-\x1F\x7F]/.test(name)) return null;
1405
+ return name;
1406
+ }
1407
+ function validSshPublicKey(raw) {
1408
+ const type = raw.trim().split(/\s+/)[0] ?? "";
1409
+ return KEY_PREFIXES.some((prefix) => type.startsWith(prefix));
1410
+ }
1411
+ function positiveInt(raw) {
1412
+ const n = Number(raw.trim());
1413
+ return Number.isInteger(n) && n > 0 ? n : null;
1414
+ }
1415
+ /** Read one public key file. Refuses anything that is not a `.pub` path. */
1416
+ async function readPublicKey(keyFiles, path) {
1417
+ if (!path.endsWith(".pub")) throw new Error(`refusing to read a non-public key file: ${path}`);
1418
+ try {
1419
+ const key = (await keyFiles.readFile(path)).trim();
1420
+ return validSshPublicKey(key) ? key : null;
1421
+ } catch {
1422
+ return null;
1423
+ }
1424
+ }
1425
+ async function findKeyCandidates(keyFiles) {
1426
+ const found = [];
1427
+ for (const file of KEY_CANDIDATE_FILES) {
1428
+ const key = await readPublicKey(keyFiles, join(keyFiles.home, ".ssh", file));
1429
+ if (key) found.push({
1430
+ label: `~/.ssh/${file}`,
1431
+ key
1432
+ });
1433
+ }
1434
+ return found;
1435
+ }
1436
+ /** "ssh-ed25519 AAAA you@laptop" -> "ssh-ed25519 you@laptop" (type and comment, never the key body). */
1437
+ function keyBlurb(key) {
1438
+ const [type, , ...comment] = key.trim().split(/\s+/);
1439
+ return [type, comment.join(" ")].filter(Boolean).join(" ");
1440
+ }
1441
+ function errText(err) {
1442
+ return err instanceof Error ? err.message : String(err);
1443
+ }
1444
+ async function askName(io) {
1445
+ for (;;) {
1446
+ const name = validCubeName(await io.ask("Name: "));
1447
+ if (name) return name;
1448
+ io.write("A name is 1 to 64 characters with no control characters.\n");
1449
+ }
1450
+ }
1451
+ async function askImage(io, catalog) {
1452
+ let images = [];
1453
+ try {
1454
+ images = (await catalog.images()).images;
1455
+ } catch (err) {
1456
+ io.warn(`Could not load the image list (${errText(err)}).\n`);
1457
+ }
1458
+ if (images.length === 0) for (;;) {
1459
+ const slug = (await io.ask("Image slug (see `krova images`): ")).trim();
1460
+ if (slug) return slug;
1461
+ }
1462
+ io.write("Images:\n");
1463
+ images.forEach((img, i) => {
1464
+ io.write(` ${i + 1}) ${img.id} (${[img.name, img.version].filter(Boolean).join(" ")})\n`);
1465
+ });
1466
+ for (;;) {
1467
+ const answer = (await io.ask("Image (number or slug): ")).trim();
1468
+ const byNumber = /^\d+$/.test(answer) ? images[Number(answer) - 1] : void 0;
1469
+ if (byNumber) return byNumber.id;
1470
+ const byId = images.find((img) => img.id === answer);
1471
+ if (byId) return byId.id;
1472
+ io.write(`Pick a number from 1 to ${images.length}, or one of the slugs above.\n`);
1473
+ }
1474
+ }
1475
+ /** `undefined` means "let Krova choose". */
1476
+ async function askRegion(io, catalog) {
1477
+ let regions = [];
1478
+ try {
1479
+ regions = (await catalog.regions()).regions;
1480
+ } catch (err) {
1481
+ io.warn(`Could not load the region list (${errText(err)}).\n`);
1482
+ }
1483
+ if (regions.length === 0) return void 0;
1484
+ io.write("Regions:\n");
1485
+ regions.forEach((r, i) => {
1486
+ io.write(` ${i + 1}) ${r.slug} (${r.name})\n`);
1487
+ });
1488
+ for (;;) {
1489
+ const answer = (await io.ask("Region (number or slug, Enter to let Krova choose): ")).trim();
1490
+ if (!answer) return void 0;
1491
+ const byNumber = /^\d+$/.test(answer) ? regions[Number(answer) - 1] : void 0;
1492
+ if (byNumber) return byNumber.slug;
1493
+ const bySlug = regions.find((r) => r.slug === answer);
1494
+ if (bySlug) return bySlug.slug;
1495
+ io.write(`Pick a number from 1 to ${regions.length}, a slug above, or press Enter.\n`);
1496
+ }
1497
+ }
1498
+ async function askSize(io, label, fallback) {
1499
+ for (;;) {
1500
+ const answer = (await io.ask(`${label} [${fallback}]: `)).trim();
1501
+ const n = positiveInt(answer === "" ? fallback : answer);
1502
+ if (n !== null) return String(n);
1503
+ io.write(`${label} must be a positive whole number.\n`);
1504
+ }
1505
+ }
1506
+ async function askSshKey(io, keyFiles) {
1507
+ const candidates = await findKeyCandidates(keyFiles);
1508
+ if (candidates.length > 0) {
1509
+ io.write("SSH public keys found:\n");
1510
+ candidates.forEach((c, i) => {
1511
+ io.write(` ${i + 1}) ${c.label} (${keyBlurb(c.key)})\n`);
1512
+ });
1513
+ }
1514
+ const prompt = candidates.length > 0 ? "SSH key (number, or paste a public key) [1]: " : "SSH public key (paste it, e.g. ssh-ed25519 AAAA...): ";
1515
+ for (;;) {
1516
+ const answer = (await io.ask(prompt)).trim();
1517
+ if (candidates.length > 0 && answer === "") return candidates[0].key;
1518
+ const picked = /^\d+$/.test(answer) ? candidates[Number(answer) - 1] : void 0;
1519
+ if (picked) return picked.key;
1520
+ if (validSshPublicKey(answer)) return answer;
1521
+ io.write("That is not a public key. It starts with ssh-ed25519, ssh-rsa, ecdsa-sha2-... or sk-...\n");
1522
+ }
1523
+ }
1524
+ /**
1525
+ * Ask for every value not already given on the command line. Questions come in
1526
+ * the order name, image, region, size, SSH key; a value given as a flag is
1527
+ * never asked again.
1528
+ */
1529
+ async function promptCreate(given, deps) {
1530
+ const { io, catalog, keyFiles } = deps;
1531
+ const name = given.name ?? await askName(io);
1532
+ const image = given.image ?? await askImage(io, catalog);
1533
+ const region = given.region ?? await askRegion(io, catalog);
1534
+ const vcpu = given.vcpu ?? await askSize(io, "vCPUs", DEFAULT_RESOURCES.vcpu);
1535
+ const ram = given.ram ?? await askSize(io, "RAM in GB", DEFAULT_RESOURCES.ram);
1536
+ const disk = given.disk ?? await askSize(io, "Disk in GB", DEFAULT_RESOURCES.disk);
1537
+ return {
1538
+ name,
1539
+ image,
1540
+ sshKey: given.sshKey ?? await askSshKey(io, keyFiles),
1541
+ ...region ? { region } : {},
1542
+ vcpu,
1543
+ ram,
1544
+ disk
1545
+ };
1546
+ }
1547
+ /** One line that says what is about to be created. */
1548
+ function summarize(a) {
1549
+ const parts = [
1550
+ a.image,
1551
+ a.region ? `region ${a.region}` : "region chosen by Krova",
1552
+ `${a.vcpu} vCPU`,
1553
+ `${a.ram} GB RAM`,
1554
+ `${a.disk} GB disk`
1555
+ ];
1556
+ return `Create cube "${a.name}" (${parts.join(", ")})`;
1557
+ }
1558
+ /** `[Y/n]`: Enter or y/yes is yes, n/no is no, anything else asks again. */
1559
+ async function confirmCreate(io, summary) {
1560
+ for (;;) {
1561
+ const answer = (await io.ask(`${summary}? [Y/n] `)).trim().toLowerCase();
1562
+ if (answer === "" || answer === "y" || answer === "yes") return true;
1563
+ if (answer === "n" || answer === "no") return false;
1564
+ }
1565
+ }
676
1566
  // src/lib/resolve.ts
677
1567
  /** Resolve a cube name-or-id to an id (parity with the Go resolveCube):
678
1568
  * exact id wins; else exactly one exact name match; else a clear error. */
@@ -685,6 +1575,254 @@ async function resolveCube(client, spaceId, ref) {
685
1575
  const ids = byName.map((c) => c.id).join(", ");
686
1576
  throw new Error(`cube name "${ref}" is ambiguous: it matches ${byName.length} cubes (${ids}) — use the cube ID instead`);
687
1577
  }
1578
+ // src/lib/safety.ts
1579
+ /** The real terminal state of this process. */
1580
+ function currentTTY() {
1581
+ return {
1582
+ stdin: Boolean(process.stdin.isTTY),
1583
+ stdout: Boolean(process.stdout.isTTY)
1584
+ };
1585
+ }
1586
+ /**
1587
+ * Whether a destructive or risky command should stop and ask first.
1588
+ *
1589
+ * Only a person at a terminal is asked: when stdin or stdout is piped (a script,
1590
+ * CI, an agent), the command proceeds exactly as it always did, so adding a
1591
+ * prompt never turns a working script into a hung one. `--yes` always skips it.
1592
+ */
1593
+ function shouldConfirm(opts, tty = currentTTY()) {
1594
+ if (opts.yes) return false;
1595
+ return tty.stdin && tty.stdout;
1596
+ }
1597
+ /** Dotted-quad IPv4 to a 32-bit number, or null when it is not one. */
1598
+ function ipv4ToNumber(addr) {
1599
+ const parts = addr.split(".");
1600
+ if (parts.length !== 4) return null;
1601
+ let n = 0;
1602
+ for (const part of parts) {
1603
+ if (!/^\d{1,3}$/.test(part) || Number(part) > 255) return null;
1604
+ n = n * 256 + Number(part);
1605
+ }
1606
+ return n;
1607
+ }
1608
+ /**
1609
+ * Whether a whitelist leaves the port open to every address.
1610
+ *
1611
+ * Open means: no entries at all; any entry whose prefix length is numerically 0
1612
+ * (`0.0.0.0/0`, `::/0`, and spellings such as `0.0.0.0/00` or `1.2.3.4/0`); or
1613
+ * the two IPv4 halves `0.0.0.0/1` and `128.0.0.0/1` together, which cover the
1614
+ * whole IPv4 space.
1615
+ */
1616
+ function isOpenWhitelist(whitelist) {
1617
+ const entries = whitelist.map((w) => w.trim()).filter(Boolean);
1618
+ if (entries.length === 0) return true;
1619
+ const halves = /* @__PURE__ */ new Set();
1620
+ for (const entry of entries) {
1621
+ const slash = entry.lastIndexOf("/");
1622
+ if (slash < 0) continue;
1623
+ const prefix = entry.slice(slash + 1).trim();
1624
+ if (!/^\d+$/.test(prefix)) continue;
1625
+ const length = Number(prefix);
1626
+ if (length === 0) return true;
1627
+ if (length === 1) {
1628
+ const n = ipv4ToNumber(entry.slice(0, slash).trim());
1629
+ if (n !== null) halves.add(n >= 2 ** 31 ? 1 : 0);
1630
+ }
1631
+ }
1632
+ return halves.size === 2;
1633
+ }
1634
+ function publicExposureWarning(cube, cubePort) {
1635
+ 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}.`;
1636
+ }
1637
+ /**
1638
+ * Read a y/N answer. The prompt goes to stderr so `--json` stdout stays pure
1639
+ * JSON. Anything but y or yes counts as no. If the input ends before an answer
1640
+ * (Ctrl+D), the answer is no and the exit code is set to 1: nobody chose to
1641
+ * abort, so a script wrapping a terminal session must not read it as success.
1642
+ * The streams are injectable for tests.
1643
+ */
1644
+ function confirm(question, io = {
1645
+ input: process.stdin,
1646
+ output: process.stderr
1647
+ }) {
1648
+ return new Promise((resolve) => {
1649
+ const rl = readline.createInterface({
1650
+ input: io.input,
1651
+ output: io.output
1652
+ });
1653
+ let answered = false;
1654
+ rl.on("close", () => {
1655
+ if (answered) return;
1656
+ process.exitCode = 1;
1657
+ resolve(false);
1658
+ });
1659
+ rl.question(question, (answer) => {
1660
+ answered = true;
1661
+ rl.close();
1662
+ resolve(/^y(es)?$/i.test(answer.trim()));
1663
+ });
1664
+ });
1665
+ }
1666
+ /** Print the abort notice: stdout for people, stderr under `--json`. */
1667
+ function printAborted(json) {
1668
+ (json ? process.stderr : process.stdout).write("Aborted.\n");
1669
+ }
1670
+ // src/lib/spinner.ts
1671
+ const FRAMES = [
1672
+ "⠋",
1673
+ "⠙",
1674
+ "⠹",
1675
+ "⠸",
1676
+ "⠼",
1677
+ "⠴",
1678
+ "⠦",
1679
+ "⠧",
1680
+ "⠇",
1681
+ "⠏"
1682
+ ];
1683
+ const CLEAR_LINE = "\r\x1B[K";
1684
+ const NOOP = { stop() {} };
1685
+ /**
1686
+ * Whether a spinner may be drawn: only on an interactive stderr, and never
1687
+ * when the command prints JSON (the caller passes `json`).
1688
+ */
1689
+ function spinnerEnabled(json, stream = process.stderr) {
1690
+ return Boolean(stream.isTTY) && !json;
1691
+ }
1692
+ /**
1693
+ * Start a tiny stderr spinner with `label`. Returns a no-op when stderr is not
1694
+ * a TTY or `json` is set, so piped and scripted output never changes.
1695
+ * The line is cleared by `stop()` and, as a backstop, when the process exits.
1696
+ */
1697
+ function startSpinner(label, opts = {}) {
1698
+ const stream = opts.stream ?? process.stderr;
1699
+ if (!spinnerEnabled(Boolean(opts.json), stream)) return NOOP;
1700
+ let i = 0;
1701
+ let active = true;
1702
+ const draw = () => stream.write(`${CLEAR_LINE}${FRAMES[i++ % FRAMES.length]} ${label}`);
1703
+ const clear = () => stream.write(CLEAR_LINE);
1704
+ const onExit = () => {
1705
+ if (active) clear();
1706
+ };
1707
+ draw();
1708
+ const timer = setInterval(draw, 80);
1709
+ timer.unref();
1710
+ process.once("exit", onExit);
1711
+ return { stop() {
1712
+ if (!active) return;
1713
+ active = false;
1714
+ clearInterval(timer);
1715
+ process.removeListener("exit", onExit);
1716
+ clear();
1717
+ } };
1718
+ }
1719
+ /** Run `fn` with a spinner that is cleared on success and on failure. */
1720
+ async function withSpinner(label, opts, fn) {
1721
+ const spinner = startSpinner(label, opts);
1722
+ try {
1723
+ return await fn();
1724
+ } finally {
1725
+ spinner.stop();
1726
+ }
1727
+ }
1728
+ // src/lib/wait.ts
1729
+ /** Every state the API reports for a Cube. */
1730
+ const CUBE_STATES = [
1731
+ "pending",
1732
+ "booting",
1733
+ "running",
1734
+ "stopped",
1735
+ "stopping",
1736
+ "resizing",
1737
+ "error",
1738
+ "deleted"
1739
+ ];
1740
+ /** States a Cube does not come back from, so waiting on another state is over. */
1741
+ const DEAD_ENDS = /* @__PURE__ */ new Set(["error", "deleted"]);
1742
+ /** Consecutive failed polls (a dropped connection, a 5xx) before the wait gives up. */
1743
+ const MAX_POLL_FAILURES = 3;
1744
+ /** A whole number of seconds, 1 or more. `undefined` gives the default. */
1745
+ function parseWaitSeconds(raw, flag) {
1746
+ if (raw === void 0) return 300;
1747
+ const s = String(raw).trim();
1748
+ const n = Number(s);
1749
+ if (!/^\d+$/.test(s) || !Number.isInteger(n) || n < 1) throw new Error(`${flag} must be a whole number of seconds, 1 or more (got "${raw}").`);
1750
+ return n;
1751
+ }
1752
+ function parseWaitState(raw) {
1753
+ const s = (raw ?? "running").trim().toLowerCase();
1754
+ if (!CUBE_STATES.includes(s)) throw new Error(`--state must be one of ${CUBE_STATES.join(", ")} (got "${raw}").`);
1755
+ return s;
1756
+ }
1757
+ /**
1758
+ * A flag's value only when it was typed on the command line, looking through
1759
+ * the parents too. The root command defines `--timeout` as well (the per-request
1760
+ * timeout), and commander hands a flag to the outermost command that knows it,
1761
+ * so a subcommand's own `--timeout` never sees the value.
1762
+ */
1763
+ function optionFromCli(cmd, key) {
1764
+ for (let c = cmd; c; c = c.parent) if (c.getOptionValueSource(key) === "cli") return String(c.getOptionValue(key));
1765
+ }
1766
+ const realSleep = (ms) => new Promise((r) => setTimeout(r, ms));
1767
+ function transient(err) {
1768
+ return !(err instanceof KrovaError) || err.status >= 500;
1769
+ }
1770
+ /**
1771
+ * Poll a Cube until it reaches `target`. Resolves with the Cube as last seen.
1772
+ * Rejects with a one-line message on a timeout, or when the Cube lands in
1773
+ * `error` or `deleted` (unless that is the state asked for).
1774
+ */
1775
+ async function waitForCubeState(o) {
1776
+ const interval = o.intervalMs ?? 2e3;
1777
+ const sleep = o.sleep ?? realSleep;
1778
+ const now = o.now ?? Date.now;
1779
+ const start = now();
1780
+ const deadline = start + o.timeoutS * 1e3;
1781
+ let last = "unknown";
1782
+ let failures = 0;
1783
+ for (;;) {
1784
+ let cube;
1785
+ try {
1786
+ cube = await o.get();
1787
+ failures = 0;
1788
+ } catch (err) {
1789
+ if (!transient(err) || ++failures >= MAX_POLL_FAILURES) throw err;
1790
+ }
1791
+ if (cube) {
1792
+ last = cube.state;
1793
+ o.onPoll?.(last, Math.floor((now() - start) / 1e3));
1794
+ if (last === o.target) return cube;
1795
+ if (DEAD_ENDS.has(last)) throw new Error(`cube ${o.cubeRef} is in the "${last}" state, so it will not become ${o.target}`);
1796
+ }
1797
+ const left = deadline - now();
1798
+ if (left <= 0) throw new Error(`timed out after ${o.timeoutS}s waiting for cube ${o.cubeRef} to be ${o.target} (last state: ${last})`);
1799
+ await sleep(Math.min(interval, left));
1800
+ }
1801
+ }
1802
+ /** The one-line progress readout on stderr: a TTY only, never with JSON. */
1803
+ function startWaitProgress(cubeRef, target, json, stream = process.stderr) {
1804
+ if (!spinnerEnabled(json, stream)) return {
1805
+ update() {},
1806
+ stop() {}
1807
+ };
1808
+ const CLEAR = "\r\x1B[K";
1809
+ let drawn = false;
1810
+ const clear = () => {
1811
+ if (drawn) stream.write(CLEAR);
1812
+ drawn = false;
1813
+ };
1814
+ process.once("exit", clear);
1815
+ return {
1816
+ update(state, elapsedS) {
1817
+ drawn = true;
1818
+ stream.write(`${CLEAR}Waiting for cube ${cubeRef} to be ${target}: ${state}, ${elapsedS}s`);
1819
+ },
1820
+ stop() {
1821
+ clear();
1822
+ process.removeListener("exit", clear);
1823
+ }
1824
+ };
1825
+ }
688
1826
  // src/commands/cubes.ts
689
1827
  function listCmd() {
690
1828
  return new Command("list").aliases(["ls"]).description("list Cubes in the space").action(async (_opts, cmd) => {
@@ -716,6 +1854,33 @@ function listCmd() {
716
1854
  ]));
717
1855
  });
718
1856
  }
1857
+ /** Block until a Cube reaches `target`, with a progress line on a terminal. */
1858
+ async function waitForCube(rt, client, space, id, cubeRef, target, timeoutS) {
1859
+ const progress = startWaitProgress(cubeRef, target, rt.json);
1860
+ try {
1861
+ return await waitForCubeState({
1862
+ cubeRef,
1863
+ target,
1864
+ timeoutS,
1865
+ get: () => client.cubes.get(space, id),
1866
+ onPoll: progress.update
1867
+ });
1868
+ } finally {
1869
+ progress.stop();
1870
+ }
1871
+ }
1872
+ function waitCmd() {
1873
+ return new Command("wait").argument("<cube>", "cube name or ID").description("wait until a Cube reaches a state (running by default); exits 1 on a timeout or an error state").option("--state <state>", "state to wait for: pending, booting, running, stopped, stopping, resizing, error or deleted (default running)").option("--timeout <seconds>", `give up after this many seconds (default 300)`).action(async (cubeRef, opts, cmd) => {
1874
+ const target = parseWaitState(opts.state);
1875
+ const timeoutS = parseWaitSeconds(optionFromCli(cmd, "timeout"), "--timeout");
1876
+ const rt = getRuntime(cmd);
1877
+ const client = makeClient(rt.res);
1878
+ const space = await resolveSpace(rt);
1879
+ const cube = await waitForCube(rt, client, space, await resolveCube(client, space, cubeRef), cubeRef, target, timeoutS);
1880
+ if (rt.json) return printJSON(cube);
1881
+ process.stdout.write(`Cube ${cube.id} is ${cube.state}\n`);
1882
+ });
1883
+ }
719
1884
  function getCmd() {
720
1885
  return new Command("get").argument("<cube>", "cube name or ID").description("show a single Cube").action(async (cubeRef, _opts, cmd) => {
721
1886
  const rt = getRuntime(cmd);
@@ -733,36 +1898,122 @@ function getCmd() {
733
1898
  ["RAM (GB)", String(cube.resources.ramGb)],
734
1899
  ["Disk (GB)", String(cube.resources.diskGb)],
735
1900
  ["Public IPv4", cube.publicIpv4 ?? "—"],
736
- ["Cost/hour", `$${cube.costPerHour}`]
1901
+ ["Cost/hour", `$${cube.costPerHour}`],
1902
+ ["Idle timeout", describeIdleTimeout(cube.idleTimeoutMinutes)],
1903
+ ["Last active", cube.lastActiveAt ?? "-"]
737
1904
  ]);
738
1905
  });
739
1906
  }
740
- function createCmd() {
741
- return new Command("create").description("provision a new Cube").requiredOption("--name <name>", "cube name").requiredOption("--image <slug>", "OS image slug (see `krova images`)").requiredOption("--ssh-key <key>", "SSH public key written to authorized_keys").option("--vcpu <n>", "number of vCPUs", "1").option("--ram <gb>", "RAM in GB", "1").option("--disk <gb>", "disk size in GB", "10").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).action(async (opts, cmd) => {
1907
+ /**
1908
+ * Build the POST /cubes body. Validates resources client-side so bad input
1909
+ * fails with a clear message rather than being coerced to NaN, then JSON null,
1910
+ * then a generic server 400.
1911
+ */
1912
+ function buildCreateBody(input) {
1913
+ const posInt = (flag, raw) => {
1914
+ const n = Number(raw);
1915
+ if (!Number.isInteger(n) || n <= 0) throw new Error(`--${flag} must be a positive integer (got "${raw}").`);
1916
+ return n;
1917
+ };
1918
+ const body = {
1919
+ name: input.name,
1920
+ image: input.image,
1921
+ sshPublicKey: input.sshKey,
1922
+ resources: {
1923
+ vcpu: posInt("vcpu", input.vcpu),
1924
+ ramGb: posInt("ram", input.ram),
1925
+ diskGb: posInt("disk", input.disk)
1926
+ }
1927
+ };
1928
+ if (input.region) body.region = input.region;
1929
+ if (input.userData) body.userData = input.userData;
1930
+ if (input.terminationProtection) body.terminationProtection = true;
1931
+ if (input.idleTimeoutMinutes !== void 0) body.idleTimeoutMinutes = input.idleTimeoutMinutes;
1932
+ return body;
1933
+ }
1934
+ const defaultCreateDeps = {
1935
+ interactive: (json) => isInteractive({ json }),
1936
+ makeIO: createReadlineIO,
1937
+ keyFiles: defaultKeyFiles
1938
+ };
1939
+ const REQUIRED_CREATE_FLAGS = [
1940
+ ["--name", "name"],
1941
+ ["--image", "image"],
1942
+ ["--ssh-key", "sshKey"]
1943
+ ];
1944
+ function createCmd(deps = defaultCreateDeps) {
1945
+ 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("--wait", "wait until the Cube is running before returning").option("--wait-timeout <seconds>", `with --wait, give up after this many seconds (default 300)`).option("-y, --yes", "skip the confirmation after the prompts").action(async (opts, cmd) => {
1946
+ const waitTimeoutS = parseWaitSeconds(opts.waitTimeout, "--wait-timeout");
1947
+ const idleTimeoutMinutes = opts.idleTimeout === void 0 ? void 0 : parseIdleTimeout(opts.idleTimeout);
1948
+ const missing = REQUIRED_CREATE_FLAGS.filter(([, key]) => opts[key] === void 0);
1949
+ const globals = cmd.optsWithGlobals();
1950
+ const wantsJson = Boolean(globals.json) || globals.output === "json";
1951
+ const prompting = missing.length > 0 && deps.interactive(wantsJson);
1952
+ if (missing.length > 0 && !prompting) {
1953
+ const flags = cmd.options.find((o) => o.long === missing[0]?.[0])?.flags;
1954
+ cmd.error(`error: required option '${flags}' not specified`, { code: "commander.missingMandatoryOptionValue" });
1955
+ }
742
1956
  const rt = getRuntime(cmd);
743
1957
  const client = makeClient(rt.res);
744
1958
  const space = await resolveSpace(rt);
745
- const posInt = (flag, raw) => {
746
- const n = Number(raw);
747
- if (!Number.isInteger(n) || n <= 0) throw new Error(`--${flag} must be a positive integer (got "${raw}").`);
748
- return n;
749
- };
750
- const body = {
1959
+ const out = deps.stdout ?? ((text) => void process.stdout.write(text));
1960
+ const build = (v) => buildCreateBody({
1961
+ ...v,
1962
+ userData: opts.userData,
1963
+ terminationProtection: opts.terminationProtection,
1964
+ idleTimeoutMinutes
1965
+ });
1966
+ let body;
1967
+ if (prompting) {
1968
+ const io = deps.makeIO();
1969
+ try {
1970
+ const given = (key) => cmd.getOptionValueSource(key) === "default" ? void 0 : opts[key];
1971
+ const answers = await promptCreate({
1972
+ name: opts.name,
1973
+ image: opts.image,
1974
+ sshKey: opts.sshKey,
1975
+ region: opts.region,
1976
+ vcpu: given("vcpu"),
1977
+ ram: given("ram"),
1978
+ disk: given("disk")
1979
+ }, {
1980
+ io,
1981
+ catalog: deps.catalog ? deps.catalog(client) : client.catalog,
1982
+ keyFiles: deps.keyFiles()
1983
+ });
1984
+ body = build(answers);
1985
+ if (!opts.yes && !await confirmCreate(io, summarize(answers))) {
1986
+ out("Aborted.\n");
1987
+ return;
1988
+ }
1989
+ } catch (err) {
1990
+ if (!(err instanceof PromptAbortError)) throw err;
1991
+ out("\nAborted.\n");
1992
+ process.exitCode = 1;
1993
+ return;
1994
+ } finally {
1995
+ io.close();
1996
+ }
1997
+ } else body = build({
751
1998
  name: opts.name,
752
1999
  image: opts.image,
753
- sshPublicKey: opts.sshKey,
754
- resources: {
755
- vcpu: posInt("vcpu", opts.vcpu),
756
- ramGb: posInt("ram", opts.ram),
757
- diskGb: posInt("disk", opts.disk)
758
- }
759
- };
760
- if (opts.region) body.region = opts.region;
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);
764
- if (rt.json) return printJSON(cube);
765
- process.stdout.write(`Created cube ${cube.id} (${cube.state})\n`);
2000
+ sshKey: opts.sshKey,
2001
+ vcpu: opts.vcpu,
2002
+ ram: opts.ram,
2003
+ disk: opts.disk,
2004
+ region: opts.region
2005
+ });
2006
+ const cube = await withSpinner("Creating cube", { json: rt.json }, () => client.cubes.create(space, body, opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : void 0));
2007
+ if (idleTimeoutMinutes !== void 0 && !idleTimeoutApplied(cube.idleTimeoutMinutes, idleTimeoutMinutes)) process.stderr.write(IDLE_UNSUPPORTED_WARNING);
2008
+ if (!opts.wait) {
2009
+ if (rt.json) return printJSON(cube);
2010
+ out(`Created cube ${cube.id} (${cube.state})\n`);
2011
+ return;
2012
+ }
2013
+ if (!rt.json) out(`Created cube ${cube.id} (${cube.state})\n`);
2014
+ const ready = await waitForCube(rt, client, space, cube.id, cube.id, "running", waitTimeoutS);
2015
+ if (rt.json) return printJSON(ready);
2016
+ out(`Cube ${ready.id} is running\n`);
766
2017
  });
767
2018
  }
768
2019
  function actionCmd(name, past, fn) {
@@ -779,6 +2030,23 @@ function actionCmd(name, past, fn) {
779
2030
  process.stdout.write(`${past} cube ${id}\n`);
780
2031
  });
781
2032
  }
2033
+ function deleteCmd() {
2034
+ 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) => {
2035
+ const rt = getRuntime(cmd);
2036
+ const client = makeClient(rt.res);
2037
+ const space = await resolveSpace(rt);
2038
+ const id = await resolveCube(client, space, cubeRef);
2039
+ if (shouldConfirm(opts)) {
2040
+ if (!await confirm(`Delete cube ${cubeRef}${cubeRef === id ? "" : ` (${id})`}? This is permanent and cannot be undone. [y/N] `)) return printAborted(rt.json);
2041
+ }
2042
+ await client.cubes.delete(space, id);
2043
+ if (rt.json) return printJSON({
2044
+ id,
2045
+ result: "Deleting"
2046
+ });
2047
+ process.stdout.write(`Deleting cube ${id}\n`);
2048
+ });
2049
+ }
782
2050
  function restartCmd() {
783
2051
  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
2052
  const rt = getRuntime(cmd);
@@ -810,6 +2078,129 @@ function sshPortCmd() {
810
2078
  `));
811
2079
  });
812
2080
  }
2081
+ function renameCmd() {
2082
+ 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) => {
2083
+ const newName = parseCubeName(rawName);
2084
+ const rt = getRuntime(cmd);
2085
+ const client = makeClient(rt.res);
2086
+ const space = await resolveSpace(rt);
2087
+ const id = await resolveCube(client, space, cubeRef);
2088
+ const cube = await client.cubes.rename(space, id, newName);
2089
+ if (rt.json) return printJSON(cube);
2090
+ process.stdout.write(`Renamed cube ${id} to ${cube.name}\n`);
2091
+ });
2092
+ }
2093
+ 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)";
2094
+ 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";
2095
+ /**
2096
+ * Parse `--idle-timeout`: whole minutes from 10 to 10080 (7 days), or `off`
2097
+ * (sent as `null`). Plain decimal digits only, so 1e2, 0x10 and " 20" fail.
2098
+ */
2099
+ function parseIdleTimeout(raw) {
2100
+ if (raw === "off") return null;
2101
+ const n = Number(raw);
2102
+ 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\"");
2103
+ return n;
2104
+ }
2105
+ /**
2106
+ * Did the server apply the requested timeout? A present field must equal the request. An absent field means
2107
+ * the server omitted it (an older server, or a null it left out): that only counts as applied for `off`.
2108
+ */
2109
+ function idleTimeoutApplied(returned, requested) {
2110
+ return returned === void 0 ? requested === null : returned === requested;
2111
+ }
2112
+ /** `off` for a Cube with no timeout, `N min` for one with a timeout, `-` when the server does not say. */
2113
+ function describeIdleTimeout(minutes) {
2114
+ if (minutes === void 0) return "-";
2115
+ return minutes === null ? "off" : `${minutes} min`;
2116
+ }
2117
+ function updateCmd() {
2118
+ 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) => {
2119
+ if (opts.idleTimeout === void 0) throw new Error("nothing to update: pass --idle-timeout <minutes|off>");
2120
+ const minutes = parseIdleTimeout(opts.idleTimeout);
2121
+ const rt = getRuntime(cmd);
2122
+ const client = makeClient(rt.res);
2123
+ const space = await resolveSpace(rt);
2124
+ const id = await resolveCube(client, space, cubeRef);
2125
+ const cube = await client.cubes.setIdleTimeout(space, id, minutes);
2126
+ 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)}`);
2127
+ if (rt.json) return printJSON(cube);
2128
+ 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`);
2129
+ });
2130
+ }
2131
+ /** Parse a `--vcpu`/`--ram`/`--disk` value. `integer` rejects fractions (RAM may be fractional). */
2132
+ function parseSize(flag, raw, integer) {
2133
+ const n = Number(raw);
2134
+ if (!(integer ? /^\d+$/ : /^\d+(\.\d+)?$/).test(raw) || !Number.isFinite(n) || n <= 0) throw new Error(`${flag} must be a positive ${integer ? "whole number" : "number"}`);
2135
+ return n;
2136
+ }
2137
+ /** Trim a new Cube name and check it locally: 1 to 64 characters, no control, line-separator or bidi characters. */
2138
+ function parseCubeName(raw) {
2139
+ const name = raw.trim();
2140
+ const length = [...name].length;
2141
+ 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");
2142
+ return name;
2143
+ }
2144
+ const RESIZE_DIMENSIONS = [
2145
+ {
2146
+ key: "vcpu",
2147
+ label: "vCPU",
2148
+ unit: ""
2149
+ },
2150
+ {
2151
+ key: "ramGb",
2152
+ label: "RAM",
2153
+ unit: " GB"
2154
+ },
2155
+ {
2156
+ key: "diskGb",
2157
+ label: "Disk",
2158
+ unit: " GB"
2159
+ }
2160
+ ];
2161
+ function describeSize(size) {
2162
+ return `${size.vcpu} vCPU, ${size.ramGb} GB RAM, ${size.diskGb} GB disk`;
2163
+ }
2164
+ function resizeCmd() {
2165
+ 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) => {
2166
+ const resources = {};
2167
+ if (opts.vcpu !== void 0) resources.vcpu = parseSize("--vcpu", opts.vcpu, true);
2168
+ if (opts.ram !== void 0) resources.ramGb = parseSize("--ram", opts.ram, false);
2169
+ if (opts.disk !== void 0) resources.diskGb = parseSize("--disk", opts.disk, true);
2170
+ if (Object.keys(resources).length === 0) throw new Error("give at least one of --vcpu, --ram or --disk");
2171
+ const rt = getRuntime(cmd);
2172
+ const client = makeClient(rt.res);
2173
+ const space = await resolveSpace(rt);
2174
+ const id = await resolveCube(client, space, cubeRef);
2175
+ if (shouldConfirm(opts)) {
2176
+ const current = (await client.cubes.get(space, id)).resources;
2177
+ const target = {
2178
+ ...current,
2179
+ ...resources
2180
+ };
2181
+ 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);
2182
+ }
2183
+ let result;
2184
+ try {
2185
+ result = await client.cubes.resize(space, id, resources);
2186
+ } catch (err) {
2187
+ 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." });
2188
+ throw err;
2189
+ }
2190
+ if (rt.json) return printJSON({
2191
+ id,
2192
+ ...result
2193
+ });
2194
+ process.stdout.write(`Resize queued for cube ${id} (job ${result.jobId})\n`);
2195
+ for (const { key, label, unit } of RESIZE_DIMENSIONS) {
2196
+ const from = result.previous[key];
2197
+ const to = result.requested[key];
2198
+ process.stdout.write(` ${label}: ${from === to ? `${to}${unit} (unchanged)` : `${from}${unit} -> ${to}${unit}`}\n`);
2199
+ }
2200
+ process.stdout.write(result.requiresRestart ? "The Cube restarts to apply this change.\n" : "Applied live: the Cube does not restart.\n");
2201
+ process.stdout.write(`The Cube keeps its current size until the change is applied. Check with: krova cubes get ${id}\n`);
2202
+ });
2203
+ }
813
2204
  /**
814
2205
  * Toggle a Cube's termination-protection flag. Shared by `protect` and
815
2206
  * `unprotect`; only the boolean `enabled` differs.
@@ -829,12 +2220,16 @@ function cubesCommand() {
829
2220
  const cubes = new Command("cubes").description("manage Cubes (Firecracker microVMs)");
830
2221
  cubes.addCommand(listCmd());
831
2222
  cubes.addCommand(getCmd());
2223
+ cubes.addCommand(waitCmd());
832
2224
  cubes.addCommand(createCmd());
833
2225
  cubes.addCommand(actionCmd("power-off", "Powering off", (c, s, id) => c.powerOff(s, id)));
834
2226
  cubes.addCommand(actionCmd("wake", "Starting", (c, s, id) => c.wake(s, id)));
835
- cubes.addCommand(actionCmd("delete", "Deleting", (c, s, id) => c.delete(s, id)));
2227
+ cubes.addCommand(deleteCmd());
836
2228
  cubes.addCommand(restartCmd());
837
2229
  cubes.addCommand(sshPortCmd());
2230
+ cubes.addCommand(updateCmd());
2231
+ cubes.addCommand(renameCmd());
2232
+ cubes.addCommand(resizeCmd());
838
2233
  cubes.addCommand(setProtectionCmd("protect", true, "Protected"));
839
2234
  cubes.addCommand(setProtectionCmd("unprotect", false, "Unprotected"));
840
2235
  return cubes;
@@ -985,26 +2380,67 @@ function domainsCommand() {
985
2380
  }
986
2381
  // src/commands/login.ts
987
2382
  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
- /** Only open https URLs, or http to a loopback host. Everything else is unsafe. */
989
- function safeBrowserURL(raw) {
2383
+ /** Characters that never appear in a device-login URL and that cmd.exe treats as operators. */
2384
+ const SHELL_METACHARS = /[&|^<>"]/;
2385
+ /**
2386
+ * Only open https URLs, or http to a loopback host, and return the normalized href.
2387
+ * The device-login URL is `<base>/cli?code=<ALNUM-ALNUM>`: it never needs `& | ^ < > "`, so a URL
2388
+ * carrying one is refused on every platform. `%` is refused on Windows only, where it expands
2389
+ * environment variables in some launchers; the real URL never contains it (the code is alphanumeric).
2390
+ * A refused URL is not opened: the caller prints it for the user to open by hand.
2391
+ */
2392
+ function safeBrowserURL(raw, platform = process.platform) {
990
2393
  let u;
991
2394
  try {
992
2395
  u = new URL(raw);
993
2396
  } catch {
994
2397
  return null;
995
2398
  }
996
- if (u.protocol === "https:" && u.hostname) return raw;
997
- if (u.protocol === "http:" && (u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "::1")) return raw;
998
- return null;
2399
+ const loopbackHttp = u.protocol === "http:" && (u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]");
2400
+ if (!(u.protocol === "https:" && u.hostname || loopbackHttp)) return null;
2401
+ const href = u.href;
2402
+ if (SHELL_METACHARS.test(href)) return null;
2403
+ if (platform === "win32" && href.includes("%")) return null;
2404
+ return href;
2405
+ }
2406
+ /** Removes C0, DEL and C1 control characters (ESC included) so a server string cannot drive the terminal. */
2407
+ function stripControlChars(s) {
2408
+ return s.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
2409
+ }
2410
+ /** The URL as it is shown to the user: the normalized href when it parses, else the raw string, with control characters stripped. */
2411
+ function displayURL(raw) {
2412
+ try {
2413
+ return stripControlChars(new URL(raw).href);
2414
+ } catch {
2415
+ return stripControlChars(raw);
2416
+ }
999
2417
  }
1000
- function openBrowser(url) {
1001
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1002
- const args = process.platform === "win32" ? ["", url] : [url];
1003
- const child = spawn(cmd, args, {
1004
- stdio: "ignore",
1005
- detached: true,
1006
- shell: process.platform === "win32"
1007
- });
2418
+ /**
2419
+ * How to open `href` in the default browser. Never uses a shell: on Windows `rundll32` is a real
2420
+ * executable, so cmd.exe never parses the URL.
2421
+ */
2422
+ function browserSpawnPlan(href, platform = process.platform) {
2423
+ if (platform === "win32") return {
2424
+ command: "rundll32",
2425
+ args: ["url.dll,FileProtocolHandler", href],
2426
+ options: {
2427
+ stdio: "ignore",
2428
+ detached: true,
2429
+ windowsHide: true
2430
+ }
2431
+ };
2432
+ return {
2433
+ command: platform === "darwin" ? "open" : "xdg-open",
2434
+ args: [href],
2435
+ options: {
2436
+ stdio: "ignore",
2437
+ detached: true
2438
+ }
2439
+ };
2440
+ }
2441
+ function openBrowser(href) {
2442
+ const plan = browserSpawnPlan(href);
2443
+ const child = spawn(plan.command, plan.args, plan.options);
1008
2444
  child.on("error", () => {});
1009
2445
  child.unref();
1010
2446
  }
@@ -1022,44 +2458,49 @@ function loginCommand() {
1022
2458
  if (start.status === 404) throw new Error(BROWSER_UNAVAILABLE);
1023
2459
  if (start.status !== 200 || !start.data?.deviceCode) throw new Error(`device login failed to start (HTTP ${start.status})`);
1024
2460
  const s = start.data;
1025
- process.stdout.write(`Your verification code is: ${s.userCode}\n`);
2461
+ process.stdout.write(`Your verification code is: ${stripControlChars(String(s.userCode ?? ""))}\n`);
1026
2462
  const target = s.verificationUriComplete || s.verificationUri;
1027
2463
  const safe = safeBrowserURL(target);
1028
2464
  if (safe && opts.browser !== false) {
1029
2465
  process.stdout.write(`Opening ${safe} …\n`);
1030
2466
  openBrowser(safe);
1031
- } else process.stdout.write(`Open this URL to approve the login:\n ${target}\n`);
2467
+ } else {
2468
+ process.stdout.write(`Open this URL to approve the login:\n ${displayURL(target)}\n`);
2469
+ if (!safe) process.stdout.write("It was not opened automatically because it contains characters that are unsafe to pass to the system opener.\n");
2470
+ }
1032
2471
  const intervalMs = Math.max((s.interval || 5) * 1e3, 5e3);
1033
2472
  const deadline = Date.now() + Math.max(s.expiresIn || 600, 1) * 1e3;
1034
- process.stdout.write("Waiting for approval…\n");
1035
- for (;;) {
1036
- if (Date.now() >= deadline) throw new Error("login timed out: the verification code expired before it was approved");
1037
- await sleep(intervalMs);
1038
- const poll = await rawRequest({
1039
- method: "POST",
1040
- baseUrl,
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,
2473
+ if (!spinnerEnabled(rt.json)) process.stdout.write("Waiting for approval…\n");
2474
+ const approved = await withSpinner("Waiting for approval", { json: rt.json }, async () => {
2475
+ for (;;) {
2476
+ if (Date.now() >= deadline) throw new Error("login timed out: the verification code expired before it was approved");
2477
+ await sleep(intervalMs);
2478
+ const poll = await rawRequest({
2479
+ method: "POST",
1049
2480
  baseUrl,
1050
- spaceId: poll.data.spaceId,
1051
- ctxName: opts.context,
2481
+ path: "/auth/cli/poll",
2482
+ body: { deviceCode: s.deviceCode },
1052
2483
  timeoutMs: rt.timeoutMs
1053
2484
  });
1054
- process.stdout.write(`Logged in. Saved context "${ctxName}" to ${configPath()}\n`);
1055
- if (spaceName) process.stdout.write(`Space: ${spaceName}\n`);
1056
- return;
2485
+ if (poll.status === 200) {
2486
+ if (!poll.data?.apiKey) throw new Error("login succeeded but no API key was returned");
2487
+ return poll.data;
2488
+ }
2489
+ if (poll.status === 202 || poll.status === 425 || poll.status === 428) continue;
2490
+ if (poll.status === 410) throw new Error("login expired: request a new code with `krova login`");
2491
+ if (poll.status === 404) throw new Error(BROWSER_UNAVAILABLE);
2492
+ throw new Error(`login failed while polling (HTTP ${poll.status})`);
1057
2493
  }
1058
- if (poll.status === 202 || poll.status === 425 || poll.status === 428) continue;
1059
- if (poll.status === 410) throw new Error("login expired: request a new code with `krova login`");
1060
- if (poll.status === 404) throw new Error(BROWSER_UNAVAILABLE);
1061
- throw new Error(`login failed while polling (HTTP ${poll.status})`);
1062
- }
2494
+ });
2495
+ const { ctxName, spaceName, stored } = await persistLogin({
2496
+ apiKey: approved.apiKey,
2497
+ baseUrl,
2498
+ spaceId: approved.spaceId,
2499
+ ctxName: rt.flags.context,
2500
+ timeoutMs: rt.timeoutMs
2501
+ });
2502
+ process.stdout.write(`${loginMessage(ctxName, stored)}\n`);
2503
+ if (spaceName) process.stdout.write(`Space: ${spaceName}\n`);
1063
2504
  });
1064
2505
  }
1065
2506
  // src/commands/snapshots.ts
@@ -1098,11 +2539,15 @@ function snapshotsCommand() {
1098
2539
  if (rt.json) return printJSON(snap);
1099
2540
  process.stdout.write(`Created snapshot ${snap.id} (${snap.status})\n`);
1100
2541
  });
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, _opts, c) => {
2542
+ 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
2543
  const rt = getRuntime(c);
1103
2544
  const client = makeClient(rt.res);
1104
2545
  const space = await resolveSpace(rt);
1105
2546
  const id = await resolveCube(client, space, cubeRef);
2547
+ if (shouldConfirm(opts)) {
2548
+ const name = (await client.snapshots.list(space, id).catch(() => [])).find((s) => s.id === snapshotId)?.name;
2549
+ 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);
2550
+ }
1106
2551
  await client.snapshots.delete(space, id, snapshotId);
1107
2552
  if (rt.json) return printJSON({
1108
2553
  id: snapshotId,
@@ -1127,7 +2572,8 @@ function snapshotsCommand() {
1127
2572
  }
1128
2573
  // src/lib/ssh.ts
1129
2574
  const HOST_BANNED = new Set("@/\\'\"`$;&|<>(){}*?!#=,".split(""));
1130
- const USER_BANNED = new Set("@/\\'\"`$;&|<>(){}*?!#,".split(""));
2575
+ const USER_BANNED = new Set("@/\\'\"`$;&|<>(){}*?!#,:[]".split(""));
2576
+ 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
2577
  function validateSSHHost(host) {
1132
2578
  const h = host.trim();
1133
2579
  if (!h) throw new Error("empty host");
@@ -1137,6 +2583,7 @@ function validateSSHHost(host) {
1137
2583
  if (code <= 32 || code === 127) throw new Error("host contains whitespace or control characters");
1138
2584
  if (HOST_BANNED.has(r)) throw new Error(`host contains a disallowed character ${JSON.stringify(r)}`);
1139
2585
  }
2586
+ if (isIP(h) === 0 && !DNS_NAME.test(h)) throw new Error("host must be an IP address or a DNS hostname");
1140
2587
  }
1141
2588
  function validateSSHUser(user) {
1142
2589
  const u = user.trim();
@@ -1197,7 +2644,7 @@ function writeKnownHosts(info) {
1197
2644
  /** Build the ssh argv. `--` is placed immediately before the destination —
1198
2645
  * the primary option-injection guard (with the validators above). */
1199
2646
  function buildSSHArgs(info, o) {
1200
- const args = [];
2647
+ const args = [...o.preArgs ?? []];
1201
2648
  if (o.knownHosts) args.push("-o", `UserKnownHostsFile=${o.knownHosts}`, "-o", "StrictHostKeyChecking=yes");
1202
2649
  if ((o.identity ?? "").trim()) args.push("-i", o.identity);
1203
2650
  if (info.port > 0) args.push("-p", String(info.port));
@@ -1217,6 +2664,471 @@ function execSSH(args) {
1217
2664
  child.on("exit", (code) => resolve(code ?? 0));
1218
2665
  });
1219
2666
  }
2667
+ /** Map a child's (code, signal) to a shell-style exit code. */
2668
+ function exitCodeFor(code, signal) {
2669
+ if (code !== null) return code;
2670
+ if (signal) return 128 + (constants$1.signals[signal] ?? 0);
2671
+ return 1;
2672
+ }
2673
+ /** Exec a binary with inherited stdio and resolve to its exit code. A signal
2674
+ * death maps to 128 + the signal number; a missing binary names itself. */
2675
+ function execInherit(bin, args) {
2676
+ return new Promise((resolve, reject) => {
2677
+ const child = spawn(bin, args, { stdio: "inherit" });
2678
+ const forward = (sig) => {
2679
+ child.kill(sig);
2680
+ };
2681
+ const signals = [
2682
+ "SIGINT",
2683
+ "SIGTERM",
2684
+ "SIGHUP"
2685
+ ];
2686
+ for (const sig of signals) process.on(sig, forward);
2687
+ const done = () => {
2688
+ for (const sig of signals) process.off(sig, forward);
2689
+ };
2690
+ child.on("error", (err) => {
2691
+ done();
2692
+ if (err.code === "ENOENT") reject(/* @__PURE__ */ new Error(`\`${bin}\` was not found on your PATH`));
2693
+ else reject(err);
2694
+ });
2695
+ child.on("exit", (code, signal) => {
2696
+ done();
2697
+ resolve(exitCodeFor(code, signal));
2698
+ });
2699
+ });
2700
+ }
2701
+ /** Resolve a Cube (name or ID) to its validated SSH endpoint and pin its host
2702
+ * keys. Shared by `ssh`, `tunnel`, `connect`, `psql`, `redis`, `mysql`, `exec`
2703
+ * and `cp`, so every one of them keeps the same strict host-key checking. */
2704
+ async function resolveSshTarget(cmd, cubeRef, o = {}) {
2705
+ const rt = getRuntime(cmd);
2706
+ const client = makeClient(rt.res);
2707
+ const space = await resolveSpace(rt);
2708
+ const id = await resolveCube(client, space, cubeRef);
2709
+ const { status, data } = await rawRequest({
2710
+ method: "GET",
2711
+ baseUrl: rt.res.baseUrl,
2712
+ path: `/spaces/${space}/cubes/${id}/ssh`,
2713
+ apiKey: rt.res.apiKey,
2714
+ timeoutMs: rt.timeoutMs
2715
+ });
2716
+ 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`);
2717
+ if (status === 401 || status === 403) throw new Error(`SSH info request was rejected (HTTP ${status})`);
2718
+ if (status !== 200 || !data?.host) throw new Error(`couldn't fetch SSH info (HTTP ${status})`);
2719
+ const info = {
2720
+ host: data.host,
2721
+ port: data.port ?? 0,
2722
+ user: data.user ?? "",
2723
+ hostKeys: data.hostKeys ?? []
2724
+ };
2725
+ validateSSHHost(info.host);
2726
+ validateSSHUser(info.user);
2727
+ if (info.port < 0 || info.port > 65535) throw new Error("invalid ssh port");
2728
+ 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");
2729
+ let knownHosts = "";
2730
+ if (info.hostKeys.length) {
2731
+ 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");
2732
+ knownHosts = writeKnownHosts(info);
2733
+ } else process.stderr.write("note: this server didn't provide host keys — using ssh trust-on-first-use (host-key checking stays on).\n");
2734
+ return {
2735
+ cubeId: id,
2736
+ info,
2737
+ knownHosts
2738
+ };
2739
+ }
2740
+ /** Split `<cube>:<path>`. A prefix with a slash in it (`./a:b`, `/tmp/x:y`) is
2741
+ * a local path, and on Windows a one-letter prefix is a drive letter. */
2742
+ function splitRemote(arg) {
2743
+ const i = arg.indexOf(":");
2744
+ if (i <= 0) return void 0;
2745
+ const cube = arg.slice(0, i);
2746
+ if (cube.includes("/") || cube.includes("\\")) return void 0;
2747
+ if (process.platform === "win32" && cube.length === 1) return void 0;
2748
+ return {
2749
+ cube,
2750
+ path: arg.slice(i + 1)
2751
+ };
2752
+ }
2753
+ /** scp reads `a:b` as host `a`; a local path with a colon before its first
2754
+ * slash gets a `./` so it stays local. */
2755
+ function safeLocalPath(p) {
2756
+ const colon = p.indexOf(":");
2757
+ if (process.platform === "win32" && colon === 1) return p;
2758
+ const slash = p.indexOf("/");
2759
+ if (colon !== -1 && (slash === -1 || colon < slash)) return `./${p}`;
2760
+ return p;
2761
+ }
2762
+ /** Decide which side of `krova cp` is the Cube. Exactly one must be. */
2763
+ function parseCpOperands(src, dst) {
2764
+ if (!src || !dst) throw new Error("cp needs a source and a destination");
2765
+ const s = splitRemote(src);
2766
+ const d = splitRemote(dst);
2767
+ if (s && d) throw new Error("cp copies between this machine and a Cube: only one side can be <cube>:<path>");
2768
+ if (!s && !d) throw new Error("one side must be a Cube path like <cube>:<path> (both sides are local)");
2769
+ const remote = s ?? d;
2770
+ if (remote.path.startsWith("-")) throw new Error("a remote path must not start with '-'");
2771
+ if (/[\0\r\n]/.test(remote.path)) throw new Error("a remote path must not contain control characters");
2772
+ return s ? {
2773
+ cube: s.cube,
2774
+ direction: "download",
2775
+ remotePath: s.path,
2776
+ localPath: safeLocalPath(dst)
2777
+ } : {
2778
+ cube: remote.cube,
2779
+ direction: "upload",
2780
+ remotePath: remote.path,
2781
+ localPath: safeLocalPath(src)
2782
+ };
2783
+ }
2784
+ /** Build the scp argv: strict host keys, `-P` port, and `--` before the operands. */
2785
+ function buildSCPArgs(info, o) {
2786
+ const user = info.user.trim();
2787
+ if (/[:\[\]]/.test(user)) throw new Error("user contains a disallowed character");
2788
+ if (info.host.includes(":") && isIP(info.host) !== 6) throw new Error("host contains a disallowed character");
2789
+ const args = [];
2790
+ if (o.knownHosts) args.push("-o", `UserKnownHostsFile=${o.knownHosts}`, "-o", "StrictHostKeyChecking=yes");
2791
+ if ((o.identity ?? "").trim()) args.push("-i", o.identity);
2792
+ if (info.port > 0) args.push("-P", String(info.port));
2793
+ if (o.recursive) args.push("-r");
2794
+ const host = isIP(info.host) === 6 ? `[${info.host}]` : info.host;
2795
+ const remote = `${user ? `${user}@` : ""}${host}:${o.operands.remotePath}`;
2796
+ const { direction, localPath } = o.operands;
2797
+ args.push("--", ...direction === "upload" ? [localPath, remote] : [remote, localPath]);
2798
+ return args;
2799
+ }
2800
+ // src/lib/tunnel.ts
2801
+ /** The only address a tunnel ever binds. Never 0.0.0.0. */
2802
+ const LOOPBACK = "127.0.0.1";
2803
+ /** Parse a TCP port: digits only, 1 to 65535. */
2804
+ function parsePort(value, label) {
2805
+ const s = String(value ?? "").trim();
2806
+ const n = Number(s);
2807
+ 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`);
2808
+ return n;
2809
+ }
2810
+ /** Parse `[localPort:]cubePort`. The local port defaults to the Cube port. */
2811
+ function parseTunnelSpec(spec) {
2812
+ const m = /^(\d+)(?::(\d+))?$/.exec(String(spec ?? "").trim());
2813
+ if (!m) throw new Error(`invalid port spec "${spec}": use <cubePort> or <localPort>:<cubePort>`);
2814
+ if (m[2] === void 0) {
2815
+ const cubePort = parsePort(m[1], "cube port");
2816
+ return {
2817
+ localPort: cubePort,
2818
+ cubePort
2819
+ };
2820
+ }
2821
+ return {
2822
+ localPort: parsePort(m[1], "local port"),
2823
+ cubePort: parsePort(m[2], "cube port")
2824
+ };
2825
+ }
2826
+ /** Build the tunnel argv: loopback-only bind, no remote command, and ssh exits
2827
+ * if the forward cannot be set up. Host keys stay strictly checked. */
2828
+ function buildTunnelArgs(info, o) {
2829
+ return buildSSHArgs(info, {
2830
+ preArgs: [
2831
+ "-N",
2832
+ "-o",
2833
+ "ExitOnForwardFailure=yes"
2834
+ ],
2835
+ identity: o.identity,
2836
+ knownHosts: o.knownHosts,
2837
+ localFwd: [`${LOOPBACK}:${o.localPort}:localhost:${o.cubePort}`]
2838
+ });
2839
+ }
2840
+ /** Ask the OS for a free loopback port (bind to port 0, read it, release it). */
2841
+ function freeLoopbackPort() {
2842
+ return new Promise((resolve, reject) => {
2843
+ const srv = createServer();
2844
+ srv.once("error", reject);
2845
+ srv.listen(0, LOOPBACK, () => {
2846
+ const addr = srv.address();
2847
+ if (addr && typeof addr === "object") {
2848
+ const { port } = addr;
2849
+ srv.close(() => resolve(port));
2850
+ } else srv.close(() => reject(/* @__PURE__ */ new Error("couldn't find a free local port")));
2851
+ });
2852
+ });
2853
+ }
2854
+ function canConnect(port) {
2855
+ return new Promise((resolve) => {
2856
+ const sock = connect({
2857
+ host: LOOPBACK,
2858
+ port
2859
+ });
2860
+ sock.once("connect", () => {
2861
+ sock.destroy();
2862
+ resolve(true);
2863
+ });
2864
+ sock.once("error", () => {
2865
+ sock.destroy();
2866
+ resolve(false);
2867
+ });
2868
+ });
2869
+ }
2870
+ const READY_GRACE_MS = 150;
2871
+ /** Wait until the local forward accepts a connection. ssh opens the listener
2872
+ * once it has authenticated, so a refused connect means "not yet": retry with a
2873
+ * short growing delay and stop at once if ssh exits or attempts run out. */
2874
+ async function waitForPort(port, ssh, maxAttempts = 480) {
2875
+ let sshDone = false;
2876
+ const markDone = () => {
2877
+ sshDone = true;
2878
+ };
2879
+ ssh.exited.then(markDone, markDone);
2880
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
2881
+ if (sshDone) return "ssh-exited";
2882
+ if (await canConnect(port)) {
2883
+ await Promise.race([ssh.exited.then(markDone, markDone), new Promise((r) => setTimeout(r, READY_GRACE_MS))]);
2884
+ return sshDone ? "ssh-exited" : "ready";
2885
+ }
2886
+ await new Promise((r) => setTimeout(r, Math.min(20 * 2 ** Math.min(attempt, 4), 250)));
2887
+ }
2888
+ return "timeout";
2889
+ }
2890
+ /** True when `name` is an executable file in one of the PATH directories. */
2891
+ function findOnPath(name, env = process.env) {
2892
+ const exts = process.platform === "win32" ? ["", ...(env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean)] : [""];
2893
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
2894
+ if (!dir) continue;
2895
+ for (const ext of exts) {
2896
+ const file = join(dir, name + ext);
2897
+ try {
2898
+ if (!statSync(file).isFile()) continue;
2899
+ accessSync(file, constants.X_OK);
2900
+ return true;
2901
+ } catch {}
2902
+ }
2903
+ }
2904
+ return false;
2905
+ }
2906
+ /** Start the tunnel's ssh. stdin and stdout are not used (ssh prompts for a
2907
+ * passphrase on the terminal itself); stderr stays visible.
2908
+ *
2909
+ * `ignoreSigint` keeps a terminal Ctrl+C (sent to the whole foreground process
2910
+ * group) from killing the tunnel while a database client is using it: ssh is
2911
+ * started through `sh` with SIGINT ignored, which survives the exec. It is NOT
2912
+ * `detached: true`, because that calls setsid(), so ssh would lose the
2913
+ * controlling terminal and could no longer ask for a key passphrase. */
2914
+ function spawnTunnel(args, o = {}) {
2915
+ const stdio = [
2916
+ "ignore",
2917
+ "ignore",
2918
+ "inherit"
2919
+ ];
2920
+ const child = o.ignoreSigint && process.platform !== "win32" ? spawn("/bin/sh", [
2921
+ "-c",
2922
+ "trap \"\" INT; exec ssh \"$@\"",
2923
+ "sh",
2924
+ ...args
2925
+ ], { stdio }) : spawn("ssh", args, { stdio });
2926
+ return {
2927
+ child,
2928
+ exited: new Promise((resolve, reject) => {
2929
+ child.once("error", (err) => {
2930
+ if (err.code === "ENOENT") reject(/* @__PURE__ */ new Error("`ssh` was not found on your PATH"));
2931
+ else reject(err);
2932
+ });
2933
+ child.once("exit", (code, signal) => resolve(exitCodeFor(code, signal)));
2934
+ })
2935
+ };
2936
+ }
2937
+ const STOP_SIGNALS = [
2938
+ "SIGINT",
2939
+ "SIGTERM",
2940
+ "SIGHUP"
2941
+ ];
2942
+ /** Hold a tunnel open until it ends. Ctrl+C (or SIGTERM) stops it cleanly and
2943
+ * exits 0; otherwise the exit code is ssh's own. `onReady` runs once the local
2944
+ * port accepts connections, when a `readyPort` is given. */
2945
+ async function holdTunnel(args, opts = {}) {
2946
+ const ssh = spawnTunnel(args);
2947
+ let stopped = false;
2948
+ const stop = (sig) => {
2949
+ stopped = true;
2950
+ ssh.child.kill(sig);
2951
+ };
2952
+ for (const sig of STOP_SIGNALS) process.on(sig, stop);
2953
+ try {
2954
+ if (opts.readyPort !== void 0) {
2955
+ const state = await waitForPort(opts.readyPort, ssh);
2956
+ if (state === "ready") opts.onReady?.();
2957
+ else if (state === "timeout") {
2958
+ ssh.child.kill("SIGTERM");
2959
+ await ssh.exited;
2960
+ throw new Error("the tunnel didn't come up in time");
2961
+ }
2962
+ }
2963
+ const code = await ssh.exited;
2964
+ return stopped ? 0 : code;
2965
+ } finally {
2966
+ for (const sig of STOP_SIGNALS) process.off(sig, stop);
2967
+ }
2968
+ }
2969
+ /** Open a tunnel, run `client` against the local port with stdio inherited,
2970
+ * then close the tunnel. Exits with the client's code. */
2971
+ async function runClientThroughTunnel(o) {
2972
+ const ssh = spawnTunnel(o.sshArgs, { ignoreSigint: true });
2973
+ let client;
2974
+ const onSignal = (sig) => {
2975
+ if (sig === "SIGINT") {
2976
+ if (!client) ssh.child.kill("SIGTERM");
2977
+ return;
2978
+ }
2979
+ client?.kill(sig);
2980
+ ssh.child.kill(sig);
2981
+ };
2982
+ const killTunnel = () => {
2983
+ if (ssh.child.exitCode === null && ssh.child.signalCode === null) ssh.child.kill("SIGTERM");
2984
+ };
2985
+ process.on("exit", killTunnel);
2986
+ for (const sig of STOP_SIGNALS) process.on(sig, onSignal);
2987
+ try {
2988
+ const state = await waitForPort(o.localPort, ssh);
2989
+ if (state === "ssh-exited") {
2990
+ const code = await ssh.exited;
2991
+ throw new Error(`ssh exited (code ${code}) before the tunnel was ready`);
2992
+ }
2993
+ if (state === "timeout") {
2994
+ ssh.child.kill("SIGTERM");
2995
+ await ssh.exited;
2996
+ throw new Error("the tunnel didn't come up in time");
2997
+ }
2998
+ const running = spawn(o.client, o.clientArgs, { stdio: "inherit" });
2999
+ client = running;
3000
+ return await new Promise((resolve, reject) => {
3001
+ running.once("error", (err) => {
3002
+ if (err.code === "ENOENT") reject(/* @__PURE__ */ new Error(`\`${o.client}\` was not found on your PATH`));
3003
+ else reject(err);
3004
+ });
3005
+ running.once("exit", (code, signal) => resolve(exitCodeFor(code, signal)));
3006
+ });
3007
+ } finally {
3008
+ killTunnel();
3009
+ await ssh.exited.catch(() => 0);
3010
+ for (const sig of STOP_SIGNALS) process.off(sig, onSignal);
3011
+ process.off("exit", killTunnel);
3012
+ }
3013
+ }
3014
+ // src/commands/dbclients.ts
3015
+ 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.";
3016
+ /** A user or database name: no leading `-`, nothing a client could read as a
3017
+ * connection string (`=`, `:`, `/`, spaces). */
3018
+ const IDENT = /^[A-Za-z0-9_][A-Za-z0-9_.$-]{0,62}$/;
3019
+ function validateIdent(value, label) {
3020
+ if (!IDENT.test(value)) throw new Error(`${label} may only use letters, digits, '_', '.', '$' and '-', and must not start with '-'`);
3021
+ return value;
3022
+ }
3023
+ const DB_CLIENTS = [
3024
+ {
3025
+ command: "psql",
3026
+ client: "psql",
3027
+ defaultPort: 5432,
3028
+ userDefault: "postgres",
3029
+ dbDefault: "postgres",
3030
+ description: "open psql against a PostgreSQL server in a Cube",
3031
+ clientArgs: ({ port, user, db }) => [
3032
+ "-h",
3033
+ LOOPBACK,
3034
+ "-p",
3035
+ String(port),
3036
+ "-U",
3037
+ user,
3038
+ "-d",
3039
+ db
3040
+ ]
3041
+ },
3042
+ {
3043
+ command: "redis",
3044
+ client: "redis-cli",
3045
+ defaultPort: 6379,
3046
+ description: "open redis-cli against a Redis server in a Cube",
3047
+ clientArgs: ({ port }) => [
3048
+ "-h",
3049
+ LOOPBACK,
3050
+ "-p",
3051
+ String(port)
3052
+ ]
3053
+ },
3054
+ {
3055
+ command: "mysql",
3056
+ client: "mysql",
3057
+ defaultPort: 3306,
3058
+ userDefault: "root",
3059
+ description: "open mysql against a MySQL or MariaDB server in a Cube",
3060
+ clientArgs: ({ port, user, db }) => [
3061
+ "-h",
3062
+ LOOPBACK,
3063
+ "-P",
3064
+ String(port),
3065
+ "--protocol=tcp",
3066
+ "-u",
3067
+ user,
3068
+ ...db ? [`--database=${db}`] : []
3069
+ ]
3070
+ }
3071
+ ];
3072
+ function dbClientCommand(spec) {
3073
+ 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");
3074
+ if (spec.userDefault) c.option("--user <user>", "database user", spec.userDefault);
3075
+ if (spec.command === "psql") c.option("--db <name>", "database name", "postgres");
3076
+ if (spec.command === "mysql") c.option("--db <name>", "database to use");
3077
+ return c.action(async (cubeRef, opts, cmd) => {
3078
+ const cubePort = opts.port !== void 0 ? parsePort(opts.port, "--port") : spec.defaultPort;
3079
+ const user = spec.userDefault ? validateIdent(opts.user, "--user") : void 0;
3080
+ const db = opts.db ? validateIdent(opts.db, "--db") : void 0;
3081
+ if (!findOnPath(spec.client)) throw new Error(`\`${spec.client}\` was not found on your PATH — install it and try again`);
3082
+ const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
3083
+ const localPort = await freeLoopbackPort();
3084
+ const sshArgs = buildTunnelArgs(info, {
3085
+ identity: opts.identity,
3086
+ knownHosts,
3087
+ localPort,
3088
+ cubePort
3089
+ });
3090
+ process.exitCode = await runClientThroughTunnel({
3091
+ sshArgs,
3092
+ localPort,
3093
+ client: spec.client,
3094
+ clientArgs: spec.clientArgs({
3095
+ port: localPort,
3096
+ user,
3097
+ db
3098
+ })
3099
+ });
3100
+ });
3101
+ }
3102
+ const psqlCommand = () => dbClientCommand(DB_CLIENTS[0]);
3103
+ const redisCommand = () => dbClientCommand(DB_CLIENTS[1]);
3104
+ const mysqlCommand = () => dbClientCommand(DB_CLIENTS[2]);
3105
+ // src/commands/exec.ts
3106
+ function execCommand() {
3107
+ 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) => {
3108
+ if (!command.some((w) => w.trim())) throw new Error("exec needs a command to run, e.g. krova exec <cube> -- uname -a");
3109
+ const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
3110
+ const args = buildSSHArgs(info, {
3111
+ preArgs: ["-T"],
3112
+ identity: opts.identity,
3113
+ knownHosts,
3114
+ remoteCmd: command
3115
+ });
3116
+ process.exitCode = await execInherit("ssh", args);
3117
+ });
3118
+ }
3119
+ function cpCommand() {
3120
+ 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) => {
3121
+ const operands = parseCpOperands(src, dst);
3122
+ const { info, knownHosts } = await resolveSshTarget(cmd, operands.cube, { requireHostKeys: true });
3123
+ const args = buildSCPArgs(info, {
3124
+ knownHosts,
3125
+ identity: opts.identity,
3126
+ recursive: Boolean(opts.recursive),
3127
+ operands
3128
+ });
3129
+ process.exitCode = await execInherit("scp", args);
3130
+ });
3131
+ }
1220
3132
  // src/commands/ssh.ts
1221
3133
  const collect = (v, acc) => {
1222
3134
  acc.push(v);
@@ -1224,34 +3136,7 @@ const collect = (v, acc) => {
1224
3136
  };
1225
3137
  function sshCommand() {
1226
3138
  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 rt = getRuntime(cmd);
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");
3139
+ const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef);
1255
3140
  const args = buildSSHArgs(info, {
1256
3141
  identity: opts.identity,
1257
3142
  localFwd: opts.localForward,
@@ -1262,6 +3147,54 @@ function sshCommand() {
1262
3147
  process.exitCode = await execSSH(args);
1263
3148
  });
1264
3149
  }
3150
+ // src/commands/tunnel.ts
3151
+ 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.";
3152
+ function announceForwarding(localPort, cubeRef, cubePort) {
3153
+ process.stderr.write(`Forwarding localhost:${localPort} -> ${cubeRef}:${cubePort}. Press Ctrl+C to stop.\n`);
3154
+ }
3155
+ function tunnelCommand() {
3156
+ 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) => {
3157
+ const { localPort, cubePort } = parseTunnelSpec(spec);
3158
+ const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
3159
+ const args = buildTunnelArgs(info, {
3160
+ identity: opts.identity,
3161
+ knownHosts,
3162
+ localPort,
3163
+ cubePort
3164
+ });
3165
+ process.exitCode = await holdTunnel(args, {
3166
+ readyPort: localPort,
3167
+ onReady: () => announceForwarding(localPort, cubeRef, cubePort)
3168
+ });
3169
+ });
3170
+ }
3171
+ function connectCommand() {
3172
+ 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) => {
3173
+ const cubePort = parsePort(opts.port, "--port");
3174
+ const localPort = opts.localPort !== void 0 ? parsePort(opts.localPort, "--local-port") : await freeLoopbackPort();
3175
+ const json = Boolean(cmd.optsWithGlobals().json);
3176
+ const { info, knownHosts } = await resolveSshTarget(cmd, cubeRef, { requireHostKeys: true });
3177
+ const args = buildTunnelArgs(info, {
3178
+ identity: opts.identity,
3179
+ knownHosts,
3180
+ localPort,
3181
+ cubePort
3182
+ });
3183
+ process.exitCode = await holdTunnel(args, {
3184
+ readyPort: localPort,
3185
+ onReady: () => {
3186
+ if (json) printJSON({
3187
+ host: LOOPBACK,
3188
+ port: localPort,
3189
+ cube: cubeRef,
3190
+ cubePort
3191
+ });
3192
+ else process.stdout.write(`localhost:${localPort}\n`);
3193
+ announceForwarding(localPort, cubeRef, cubePort);
3194
+ }
3195
+ });
3196
+ });
3197
+ }
1265
3198
  // src/commands/tcp.ts
1266
3199
  /** `krova tcp` — manage a Cube's TCP port mappings. */
1267
3200
  function tcpCommand() {
@@ -1294,7 +3227,7 @@ function tcpCommand() {
1294
3227
  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
3228
  acc.push(val);
1296
3229
  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) => {
3230
+ }, []).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
3231
  const rt = getRuntime(c);
1299
3232
  const client = makeClient(rt.res);
1300
3233
  const space = await resolveSpace(rt);
@@ -1302,6 +3235,12 @@ function tcpCommand() {
1302
3235
  const cubePort = Number(opts.port);
1303
3236
  if (!Number.isInteger(cubePort) || cubePort <= 0 || cubePort > 65535) throw new Error(`--port must be a valid port (got "${opts.port}").`);
1304
3237
  const whitelist = opts.whitelist;
3238
+ if (isOpenWhitelist(whitelist)) {
3239
+ process.stderr.write(`${publicExposureWarning(cubeRef, cubePort)}\n`);
3240
+ if (shouldConfirm(opts)) {
3241
+ if (!await confirm("Open this port to the whole internet? [y/N] ")) return printAborted(rt.json);
3242
+ }
3243
+ }
1305
3244
  const mapping = await client.tcpMappings.create(space, id, {
1306
3245
  cubePort,
1307
3246
  ...whitelist.length ? { whitelistedIps: whitelist } : {},
@@ -1324,6 +3263,59 @@ function tcpCommand() {
1324
3263
  });
1325
3264
  return cmd;
1326
3265
  }
3266
+ // src/lib/semver.ts
3267
+ function parseVersion(input) {
3268
+ const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(input.trim());
3269
+ if (!m) return void 0;
3270
+ const [major, minor, patch] = [
3271
+ m[1],
3272
+ m[2],
3273
+ m[3]
3274
+ ];
3275
+ if (major === void 0 || minor === void 0 || patch === void 0) return void 0;
3276
+ const pre = m[4];
3277
+ return {
3278
+ core: [
3279
+ Number(major),
3280
+ Number(minor),
3281
+ Number(patch)
3282
+ ],
3283
+ pre: pre ? pre.split(".") : []
3284
+ };
3285
+ }
3286
+ /** Semver ordering of two pre-release parts: numeric identifiers below
3287
+ * alphanumeric ones, numbers compared as numbers, everything else as text. */
3288
+ function comparePre(a, b) {
3289
+ if (a.length === 0 || b.length === 0) return b.length - a.length;
3290
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
3291
+ const x = a[i] ?? "";
3292
+ const y = b[i] ?? "";
3293
+ const xNum = /^\d+$/.test(x);
3294
+ const yNum = /^\d+$/.test(y);
3295
+ if (xNum && yNum) {
3296
+ const diff = Number(x) - Number(y);
3297
+ if (diff !== 0) return diff;
3298
+ continue;
3299
+ }
3300
+ if (xNum !== yNum) return xNum ? -1 : 1;
3301
+ if (x !== y) return x < y ? -1 : 1;
3302
+ }
3303
+ return a.length - b.length;
3304
+ }
3305
+ /** Negative when `a` is older than `b`, zero when equal, positive when newer.
3306
+ * A pre-release sorts below the release it leads to (1.0.0-rc.1 < 1.0.0).
3307
+ * Throws on input that is not MAJOR.MINOR.PATCH[-pre][+build]. */
3308
+ function compareVersions(a, b) {
3309
+ const va = parseVersion(a);
3310
+ const vb = parseVersion(b);
3311
+ if (!va) throw new Error(`not a version: ${a}`);
3312
+ if (!vb) throw new Error(`not a version: ${b}`);
3313
+ for (let i = 0; i < 3; i++) {
3314
+ const diff = (va.core[i] ?? 0) - (vb.core[i] ?? 0);
3315
+ if (diff !== 0) return diff;
3316
+ }
3317
+ return comparePre(va.pre, vb.pre);
3318
+ }
1327
3319
  const CLI_VERSION = createRequire(import.meta.url)("../package.json").version;
1328
3320
  function versionCommand() {
1329
3321
  return new Command("version").description("print the krova CLI version").action((_opts, cmd) => {
@@ -1337,6 +3329,86 @@ function versionCommand() {
1337
3329
  process.stdout.write(`krova ${info.version} (node ${info.node}, ${info.platform})\n`);
1338
3330
  });
1339
3331
  }
3332
+ // src/commands/update.ts
3333
+ const DEFAULT_REGISTRY = "https://registry.npmjs.org";
3334
+ const UPDATE_COMMAND = "npm install -g @krovacloud/cli@latest";
3335
+ /** Checking npm is a quick metadata lookup, so never wait longer than this,
3336
+ * even when the global --timeout is larger. */
3337
+ const CHECK_TIMEOUT_CAP_MS = 1e4;
3338
+ /** One reason line, plus a hint when the failure looks like the network —
3339
+ * the top-level handler names the API base URL for any connection failure,
3340
+ * which would be wrong here: this check talks to npm, not to Krova. */
3341
+ function failureFor(err, timeoutMs) {
3342
+ const mirrorHint = `Check your connection or set ${ENV.npmRegistry} to use an npm mirror.`;
3343
+ if (!(err instanceof Error)) return { reason: String(err) };
3344
+ const code = err.code;
3345
+ if (err.name === "TimeoutError" || err.name === "AbortError" || code === "ABORT_ERR") return {
3346
+ reason: `timed out after ${timeoutMs / 1e3}s`,
3347
+ hint: mirrorHint
3348
+ };
3349
+ const cause = err.cause;
3350
+ if (cause && typeof cause === "object" && typeof cause.message === "string") return {
3351
+ reason: cause.message,
3352
+ hint: mirrorHint
3353
+ };
3354
+ return {
3355
+ reason: err.message,
3356
+ hint: err.message === "fetch failed" ? mirrorHint : void 0
3357
+ };
3358
+ }
3359
+ function registryError(reason, hint) {
3360
+ const err = /* @__PURE__ */ new Error(`could not check the npm registry: ${reason}`);
3361
+ return hint ? Object.assign(err, { hint }) : err;
3362
+ }
3363
+ /** The canonical MAJOR.MINOR.PATCH[-prerelease] form: no leading v, no +build metadata. */
3364
+ function formatVersion(parsed) {
3365
+ const [major, minor, patch] = parsed.core;
3366
+ return `${major}.${minor}.${patch}${parsed.pre.length > 0 ? `-${parsed.pre.join(".")}` : ""}`;
3367
+ }
3368
+ /** The registry's latest published version, normalized, e.g. "0.7.0". */
3369
+ async function fetchLatestVersion(baseUrl, timeoutMs) {
3370
+ const base = (baseUrl || DEFAULT_REGISTRY).replace(/\/+$/, "");
3371
+ let res;
3372
+ try {
3373
+ res = await fetch(`${base}/@krovacloud%2fcli/latest`, {
3374
+ headers: { accept: "application/json" },
3375
+ signal: AbortSignal.timeout(timeoutMs)
3376
+ });
3377
+ } catch (err) {
3378
+ const failure = failureFor(err, timeoutMs);
3379
+ throw registryError(failure.reason, failure.hint);
3380
+ }
3381
+ if (!res.ok) throw registryError(`the registry answered HTTP ${res.status}`);
3382
+ let body;
3383
+ try {
3384
+ body = await res.json();
3385
+ } catch (err) {
3386
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
3387
+ const failure = failureFor(err, timeoutMs);
3388
+ throw registryError(failure.reason, failure.hint);
3389
+ }
3390
+ throw registryError("the response was not valid JSON");
3391
+ }
3392
+ const version = body?.version;
3393
+ const parsed = typeof version === "string" ? parseVersion(version) : void 0;
3394
+ if (!parsed) throw registryError("the response did not name a version");
3395
+ return formatVersion(parsed);
3396
+ }
3397
+ function updateCommand() {
3398
+ return new Command("update").description("check the npm registry for a newer krova CLI (never installs)").action(async (_opts, cmd) => {
3399
+ const rt = getRuntime(cmd);
3400
+ const latest = await fetchLatestVersion(process.env[ENV.npmRegistry] ?? "", Math.min(rt.timeoutMs, CHECK_TIMEOUT_CAP_MS));
3401
+ const current = CLI_VERSION;
3402
+ const updateAvailable = compareVersions(latest, current) > 0;
3403
+ if (rt.json) return printJSON({
3404
+ current,
3405
+ latest,
3406
+ updateAvailable,
3407
+ command: UPDATE_COMMAND
3408
+ });
3409
+ process.stdout.write(updateAvailable ? `krova ${latest} is available (you have ${current}). Update with: ${UPDATE_COMMAND}\n` : `krova ${latest} is the latest version.\n`);
3410
+ });
3411
+ }
1340
3412
  // src/commands/webhooks.ts
1341
3413
  const DEFAULT_LISTEN_HOST = "127.0.0.1";
1342
3414
  const DEFAULT_LISTEN_PORT = 4666;
@@ -1519,7 +3591,7 @@ function webhooksCommand() {
1519
3591
  if (!secret) throw new Error("a signing secret is required: pass --secret or set KROVA_WEBHOOK_SECRET");
1520
3592
  const { host, port } = parseListenAddr(String(opts.addr));
1521
3593
  const wantPath = String(opts.path);
1522
- const server = createServer((req, res) => {
3594
+ const server = createServer$1((req, res) => {
1523
3595
  const reqPath = (req.url ?? "/").split("?")[0];
1524
3596
  if (req.method !== "POST" || reqPath !== wantPath) {
1525
3597
  res.writeHead(405);
@@ -1568,9 +3640,20 @@ function webhooksCommand() {
1568
3640
  return wh;
1569
3641
  }
1570
3642
  // src/commands/whoami.ts
3643
+ /** "never", or the ISO date with how far away it is, e.g. `2026-12-16T12:00:00.000Z (in 30 days)`. */
3644
+ function describeExpiry(expiresAt, now = Date.now()) {
3645
+ if (expiresAt === null) return "never";
3646
+ const at = Date.parse(expiresAt);
3647
+ if (Number.isNaN(at)) return expiresAt;
3648
+ const days = Math.floor((at - now) / 864e5);
3649
+ if (days < 0) return `${expiresAt} (expired)`;
3650
+ if (days === 0) return `${expiresAt} (within a day)`;
3651
+ return `${expiresAt} (in ${days} ${days === 1 ? "day" : "days"})`;
3652
+ }
1571
3653
  function whoamiCommand() {
1572
- return new Command("whoami").description("show the current context, space, and base URL").action(async (_opts, cmd) => {
3654
+ 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
3655
  const rt = getRuntime(cmd);
3656
+ const showSecrets = Boolean(opts.showSecrets);
1574
3657
  const ctx = find(rt.cfg, rt.res.contextName);
1575
3658
  let spaceId = rt.res.spaceId;
1576
3659
  let spaceName = ctx?.spaceName ?? "";
@@ -1580,13 +3663,17 @@ function whoamiCommand() {
1580
3663
  spaceName = probe.space.name ?? spaceName;
1581
3664
  }
1582
3665
  const spaceLive = probe.state === "valid";
1583
- const warning = probe.state === "rejected" ? `the API rejected this key (HTTP ${probe.status}) — 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.` : "";
3666
+ const keyInfo = probe.state === "valid" ? probe.space.apiKey : void 0;
3667
+ const expiresAt = keyInfo ? keyInfo.expiresAt : void 0;
3668
+ 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
3669
  if (rt.json) return printJSON({
1585
3670
  context: rt.res.contextName,
1586
3671
  spaceId,
1587
3672
  spaceName,
1588
- apiKeyMasked: maskKey(rt.res.apiKey),
3673
+ ...showSecrets ? { apiKey: rt.res.apiKey } : { apiKeyMasked: displayKey(rt.res.apiKey, false) },
3674
+ ...expiresAt !== void 0 ? { apiKeyExpiresAt: expiresAt } : {},
1589
3675
  apiKeySource: rt.res.apiKeySource,
3676
+ apiKeyStorage: rt.res.apiKeyStorage || void 0,
1590
3677
  baseUrl: rt.res.baseUrl,
1591
3678
  spaceLive,
1592
3679
  checkState: probe.state,
@@ -1596,14 +3683,66 @@ function whoamiCommand() {
1596
3683
  ["Context", rt.res.contextName || "—"],
1597
3684
  ["Space", spaceName || "—"],
1598
3685
  ["Space ID", spaceId || "—"],
1599
- ["API key", rt.res.apiKey ? `${maskKey(rt.res.apiKey)} (${rt.res.apiKeySource})` : "—"],
3686
+ ["API key", rt.res.apiKey ? `${displayKey(rt.res.apiKey, showSecrets)} (${rt.res.apiKeySource}${rt.res.apiKeyStorage ? `, ${rt.res.apiKeyStorage}` : ""})` : "—"],
3687
+ ...expiresAt !== void 0 ? [["Key expires", describeExpiry(expiresAt)]] : [],
1600
3688
  ["Base URL", rt.res.baseUrl]
1601
3689
  ]);
1602
3690
  if (warning) process.stdout.write(`\n${warning}\n`);
1603
3691
  if (probe.state === "rejected") process.exitCode = 1;
1604
3692
  });
1605
3693
  }
3694
+ // src/lib/hints.ts
3695
+ const NETWORK_CODES = /* @__PURE__ */ new Set([
3696
+ "ECONNREFUSED",
3697
+ "ENOTFOUND",
3698
+ "ETIMEDOUT",
3699
+ "UND_ERR_CONNECT_TIMEOUT"
3700
+ ]);
3701
+ /** Hint for an API status, or undefined when a generic hint would not help (e.g. 400, 422). */
3702
+ function hintForStatus(status) {
3703
+ if (status === 401) return "Your API key was rejected. Run krova login, or check krova whoami.";
3704
+ if (status === 403) return "Your key's member lacks the permission for this action. Ask a space owner to grant it.";
3705
+ if (status === 404) return "Not found. Check the name or ID with the matching list command.";
3706
+ if (status === 409) return "The resource is busy or in a conflicting state. Try again in a moment.";
3707
+ if (status === 429) return "Rate limited. Wait a moment and try again.";
3708
+ if (status >= 500 && status <= 599) return "Krova had a server error. Try again; if it keeps happening, contact support.";
3709
+ }
3710
+ /** True when `err` (or anything in its cause chain) is a connection failure. */
3711
+ function isNetworkError(err) {
3712
+ const seen = /* @__PURE__ */ new Set();
3713
+ const walk = (e, depth) => {
3714
+ if (!e || typeof e !== "object" || depth > 5 || seen.has(e)) return false;
3715
+ seen.add(e);
3716
+ const { code, message, cause, errors } = e;
3717
+ if (typeof code === "string" && NETWORK_CODES.has(code)) return true;
3718
+ if (typeof message === "string") {
3719
+ if (message === "fetch failed") return true;
3720
+ for (const c of NETWORK_CODES) if (message.includes(c)) return true;
3721
+ }
3722
+ if (walk(cause, depth + 1)) return true;
3723
+ return Array.isArray(errors) && errors.some((x) => walk(x, depth + 1));
3724
+ };
3725
+ return walk(err, 0);
3726
+ }
3727
+ /**
3728
+ * The one extra line the top-level error handler prints under `Error: ...`.
3729
+ *
3730
+ * - An error that carries its own `hint` string wins: it is returned as-is, so
3731
+ * a command that already explains itself is never given a second, generic one.
3732
+ * - A `KrovaError` (the API answered) gets a hint by status. A termination
3733
+ * protection refusal gets none: retrying cannot help and its message is exact.
3734
+ * - A connection failure gets a hint naming the base URL being used.
3735
+ * - Anything else (validation, local errors) gets none.
3736
+ */
3737
+ function errorHint(err, baseUrl) {
3738
+ const own = err?.hint;
3739
+ if (typeof own === "string" && own) return own;
3740
+ if (err instanceof TerminationProtectedError) return void 0;
3741
+ if (err instanceof KrovaError) return hintForStatus(err.status);
3742
+ if (isNetworkError(err)) return `Could not reach ${baseUrl}. Check your connection or ${ENV.baseUrl}.`;
3743
+ }
1606
3744
  // src/index.ts
3745
+ exitQuietlyOnBrokenPipe();
1607
3746
  const program = new Command();
1608
3747
  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();
1609
3748
  program.addCommand(loginCommand());
@@ -1616,6 +3755,13 @@ program.addCommand(snapshotsCommand());
1616
3755
  program.addCommand(backupsCommand());
1617
3756
  program.addCommand(tcpCommand());
1618
3757
  program.addCommand(sshCommand());
3758
+ program.addCommand(tunnelCommand());
3759
+ program.addCommand(connectCommand());
3760
+ program.addCommand(psqlCommand());
3761
+ program.addCommand(redisCommand());
3762
+ program.addCommand(mysqlCommand());
3763
+ program.addCommand(execCommand());
3764
+ program.addCommand(cpCommand());
1619
3765
  program.addCommand(rootListCommand());
1620
3766
  program.addCommand(rootGetCommand());
1621
3767
  program.addCommand(regionsCommand());
@@ -1623,6 +3769,8 @@ program.addCommand(imagesCommand());
1623
3769
  program.addCommand(pricingCommand());
1624
3770
  program.addCommand(webhooksCommand());
1625
3771
  program.addCommand(versionCommand());
3772
+ program.addCommand(updateCommand());
3773
+ program.addCommand(completionCommand());
1626
3774
  const applyGlobals = (cmd) => {
1627
3775
  const have = new Set(cmd.options.map((o) => o.long));
1628
3776
  const add = (flags, desc, def) => {
@@ -1634,16 +3782,35 @@ const applyGlobals = (cmd) => {
1634
3782
  add("--base-url <url>", "override the API base URL");
1635
3783
  add("--context <name>", "use a named context (overrides KROVA_CONTEXT)");
1636
3784
  add("--json", "output machine-readable JSON instead of a table");
3785
+ add("-o, --output <format>", "output format: table (default) or json; -o json is the same as --json");
1637
3786
  add("--timeout <duration>", "per-request timeout", "30s");
1638
3787
  for (const c of cmd.commands) applyGlobals(c);
1639
3788
  };
1640
3789
  applyGlobals(program);
3790
+ program.hook("preAction", (_root, actionCmd) => {
3791
+ parseOutputFormat(actionCmd.optsWithGlobals().output);
3792
+ });
3793
+ /** The base URL for a connection hint: the one the failing command resolved,
3794
+ * else what the environment and saved context would give. */
3795
+ function hintBaseUrl() {
3796
+ const active = activeRuntime();
3797
+ if (active) return active.baseUrl;
3798
+ try {
3799
+ return resolve(load(), {}).baseUrl;
3800
+ } catch {
3801
+ return process.env[ENV.baseUrl] || "https://krova.cloud/api/v1";
3802
+ }
3803
+ }
1641
3804
  async function main() {
1642
3805
  try {
1643
3806
  await program.parseAsync(process.argv);
1644
3807
  } catch (err) {
1645
3808
  const msg = err instanceof Error ? err.message : String(err);
1646
3809
  process.stderr.write(`Error: ${msg}\n`);
3810
+ if (!activeRuntime()?.json) {
3811
+ const hint = errorHint(err, hintBaseUrl());
3812
+ if (hint) process.stderr.write(`${hint}\n`);
3813
+ }
1647
3814
  process.exitCode = 1;
1648
3815
  }
1649
3816
  }