@krovacloud/cli 0.7.1 → 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/CHANGELOG.md CHANGED
@@ -58,8 +58,22 @@ All notable changes to `@krovacloud/cli` are documented here.
58
58
 
59
59
  - `krova whoami`, `krova auth status` and `krova context list --json` show where the key lives (`apiKeyStorage` / `keyStorage`: `keychain` or `file`), and `krova auth logout`, `krova context delete` and `krova context rename` delete or move the keychain item with the context, and only after the config file is saved. `krova context list` no longer reads the keychain unless you pass `--show-secrets`. The config file is now written atomically. Context names cannot start with `-`.
60
60
 
61
+ - `krova cubes create --wait` blocks until the Cube is running, and `--wait-timeout <seconds>` (default 300) sets how long. On a terminal it shows a progress line; with `--json` it prints the final Cube. It exits 1 with a clear message if the Cube lands in `error` or the time runs out.
62
+
63
+ - `krova cubes wait <cube> [--state running] [--timeout <seconds>]`: wait for a Cube to reach a state (any of `pending`, `booting`, `running`, `stopped`, `stopping`, `resizing`, `error`, `deleted`). It prints `Cube <id> is running` (`--json` prints the Cube) and exits 1 on a timeout (default 300 seconds) or when the Cube enters `error` or `deleted`.
64
+
61
65
  ### Fixed
62
66
 
67
+ - `krova auth login --context <name>` and `krova login --context <name>` save the context under the name you give. They used to save it as `default`.
68
+
69
+ - `--base-url` and `KROVA_BASE_URL` take a bare origin such as `https://krova.cloud` for every request the CLI makes, including the login and key checks, the same way the SDK does: a bare origin gets `/api/v1`, trailing slashes are dropped, and any other path is kept.
70
+
71
+ - `krova psql --help`, `redis` and `mysql` show each default once.
72
+
73
+ - `krova cubes list | head -1` and other pipes that close early end quietly with status 0, as standard tools do, instead of printing an `EPIPE` stack trace. Other write errors are still reported.
74
+
75
+ - `krova tunnel` prints `Forwarding ...` only once the local port is listening, so a tunnel that fails to start no longer claims to be forwarding.
76
+
63
77
  - `krova login` on Windows no longer passes the verification URL through `cmd.exe`: it opens the browser with `rundll32` and no shell. A URL containing `& | ^ < > "` (or `%` on Windows) is not opened; the CLI prints it so you can open it yourself. The URL it opens is now the normalized form of the one the server sent.
64
78
 
65
79
  ## 0.6.2
package/README.md CHANGED
@@ -59,6 +59,7 @@ krova cubes create \
59
59
  --name web --image ubuntu-24.04 \
60
60
  --vcpu 1 --ram 1 --disk 10 \
61
61
  --ssh-key "$(cat ~/.ssh/id_ed25519.pub)"
62
+ krova cubes wait <cube> # block until the Cube is running (--state, --timeout <seconds>)
62
63
  krova cubes power-off <cube>
63
64
  krova cubes wake <cube>
64
65
  krova cubes restart <cube> # cold restart — the only way to pick up a new kernel
@@ -77,6 +78,13 @@ In a terminal, `krova cubes delete` and `krova snapshots rm` ask `[y/N]` before
77
78
 
78
79
  `<cube>` is a Cube **name or ID** — a unique name resolves automatically.
79
80
 
81
+ Add `--wait` to `krova cubes create` to block until the Cube is running, with `--wait-timeout <seconds>` (default 300). `krova cubes wait <cube> [--state running] [--timeout <seconds>]` does the same for a Cube that already exists, and works for any state (`stopped`, for example). On a terminal you get a progress line; with `--json` you get the final Cube. A timeout, or a Cube that lands in `error` or `deleted`, exits 1 with a one-line message, so it drops into scripts and CI:
82
+
83
+ ```sh
84
+ krova cubes create --name web --image ubuntu-24.04 --ssh-key "$(cat ~/.ssh/id_ed25519.pub)" --wait
85
+ krova cubes wait web --state stopped --timeout 120
86
+ ```
87
+
80
88
  In a terminal, `krova cubes create` asks for whatever you leave out. Run it with no flags to pick the name, image, region, size and SSH key from lists:
81
89
 
82
90
  ```sh
package/dist/index.js CHANGED
@@ -166,6 +166,27 @@ function writeBackend() {
166
166
  if (keychainOptedOut()) throw new KeychainUnavailableError(`${NO_KEYCHAIN_ENV} is set`, true);
167
167
  return readBackend();
168
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";
169
190
  const DEFAULT_CONTEXT_NAME = "default";
170
191
  const ENV = {
171
192
  apiKey: "KROVA_API_KEY",
@@ -310,7 +331,7 @@ function resolve(cfg, flags) {
310
331
  return {
311
332
  apiKey,
312
333
  spaceId,
313
- baseUrl: baseUrlRaw || "https://krova.cloud/api/v1",
334
+ baseUrl: baseUrlRaw ? normalizeBaseUrl(baseUrlRaw) : DEFAULT_BASE_URL,
314
335
  apiKeySource,
315
336
  apiKeyStorage: apiKeySource === "context" && ctx ? storageOf(ctx) : "",
316
337
  spaceIdSource,
@@ -495,6 +516,19 @@ function displayKey(key, showSecrets) {
495
516
  return showSecrets ? key : maskKey(key);
496
517
  }
497
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
+ }
498
532
  function printJSON(value) {
499
533
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
500
534
  }
@@ -541,7 +575,7 @@ async function rawRequest(opts) {
541
575
  const headers = { Accept: "application/json" };
542
576
  if (opts.apiKey) headers["X-API-KEY"] = opts.apiKey;
543
577
  if (opts.body !== void 0) headers["Content-Type"] = "application/json";
544
- const res = await fetch(`${opts.baseUrl.replace(/\/+$/, "")}${opts.path}`, {
578
+ const res = await fetch(`${normalizeBaseUrl(opts.baseUrl)}${opts.path}`, {
545
579
  method: opts.method,
546
580
  headers,
547
581
  body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0,
@@ -779,7 +813,7 @@ function authCommand() {
779
813
  apiKey: key.trim(),
780
814
  baseUrl: rt.res.baseUrl,
781
815
  spaceId: opts.space,
782
- ctxName: opts.context,
816
+ ctxName: rt.flags.context,
783
817
  timeoutMs: rt.timeoutMs
784
818
  });
785
819
  process.stdout.write(`${loginMessage(ctxName, stored)}\n`);
@@ -1691,6 +1725,104 @@ async function withSpinner(label, opts, fn) {
1691
1725
  spinner.stop();
1692
1726
  }
1693
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
+ }
1694
1826
  // src/commands/cubes.ts
1695
1827
  function listCmd() {
1696
1828
  return new Command("list").aliases(["ls"]).description("list Cubes in the space").action(async (_opts, cmd) => {
@@ -1722,6 +1854,33 @@ function listCmd() {
1722
1854
  ]));
1723
1855
  });
1724
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
+ }
1725
1884
  function getCmd() {
1726
1885
  return new Command("get").argument("<cube>", "cube name or ID").description("show a single Cube").action(async (cubeRef, _opts, cmd) => {
1727
1886
  const rt = getRuntime(cmd);
@@ -1783,7 +1942,8 @@ const REQUIRED_CREATE_FLAGS = [
1783
1942
  ["--ssh-key", "sshKey"]
1784
1943
  ];
1785
1944
  function createCmd(deps = defaultCreateDeps) {
1786
- return new Command("create").description("provision a new Cube (in a terminal, asks for anything you leave out)").option("--name <name>", "cube name").option("--image <slug>", "OS image slug (see `krova images`)").option("--ssh-key <key>", "SSH public key written to authorized_keys").option("--vcpu <n>", "number of vCPUs", DEFAULT_RESOURCES.vcpu).option("--ram <gb>", "RAM in GB", DEFAULT_RESOURCES.ram).option("--disk <gb>", "disk size in GB", DEFAULT_RESOURCES.disk).option("--region <slug>", "region slug (see `krova regions`)").option("--user-data <script>", "cloud-init script").option("--idempotency-key <key>", "idempotency key (24h dedupe)").option("--termination-protection", "turn on termination protection (the cube cannot be deleted until turned off)", false).option("--idle-timeout <minutes>", IDLE_TIMEOUT_HELP).option("-y, --yes", "skip the confirmation after the prompts").action(async (opts, cmd) => {
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");
1787
1947
  const idleTimeoutMinutes = opts.idleTimeout === void 0 ? void 0 : parseIdleTimeout(opts.idleTimeout);
1788
1948
  const missing = REQUIRED_CREATE_FLAGS.filter(([, key]) => opts[key] === void 0);
1789
1949
  const globals = cmd.optsWithGlobals();
@@ -1845,8 +2005,15 @@ function createCmd(deps = defaultCreateDeps) {
1845
2005
  });
1846
2006
  const cube = await withSpinner("Creating cube", { json: rt.json }, () => client.cubes.create(space, body, opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : void 0));
1847
2007
  if (idleTimeoutMinutes !== void 0 && !idleTimeoutApplied(cube.idleTimeoutMinutes, idleTimeoutMinutes)) process.stderr.write(IDLE_UNSUPPORTED_WARNING);
1848
- if (rt.json) return printJSON(cube);
1849
- out(`Created cube ${cube.id} (${cube.state})\n`);
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`);
1850
2017
  });
1851
2018
  }
1852
2019
  function actionCmd(name, past, fn) {
@@ -2053,6 +2220,7 @@ function cubesCommand() {
2053
2220
  const cubes = new Command("cubes").description("manage Cubes (Firecracker microVMs)");
2054
2221
  cubes.addCommand(listCmd());
2055
2222
  cubes.addCommand(getCmd());
2223
+ cubes.addCommand(waitCmd());
2056
2224
  cubes.addCommand(createCmd());
2057
2225
  cubes.addCommand(actionCmd("power-off", "Powering off", (c, s, id) => c.powerOff(s, id)));
2058
2226
  cubes.addCommand(actionCmd("wake", "Starting", (c, s, id) => c.wake(s, id)));
@@ -2328,7 +2496,7 @@ function loginCommand() {
2328
2496
  apiKey: approved.apiKey,
2329
2497
  baseUrl,
2330
2498
  spaceId: approved.spaceId,
2331
- ctxName: opts.context,
2499
+ ctxName: rt.flags.context,
2332
2500
  timeoutMs: rt.timeoutMs
2333
2501
  });
2334
2502
  process.stdout.write(`${loginMessage(ctxName, stored)}\n`);
@@ -2903,8 +3071,8 @@ const DB_CLIENTS = [
2903
3071
  ];
2904
3072
  function dbClientCommand(spec) {
2905
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");
2906
- if (spec.userDefault) c.option("--user <user>", `database user (default ${spec.userDefault})`, spec.userDefault);
2907
- if (spec.command === "psql") c.option("--db <name>", "database name (default postgres)", "postgres");
3074
+ if (spec.userDefault) c.option("--user <user>", "database user", spec.userDefault);
3075
+ if (spec.command === "psql") c.option("--db <name>", "database name", "postgres");
2908
3076
  if (spec.command === "mysql") c.option("--db <name>", "database to use");
2909
3077
  return c.action(async (cubeRef, opts, cmd) => {
2910
3078
  const cubePort = opts.port !== void 0 ? parsePort(opts.port, "--port") : spec.defaultPort;
@@ -2981,6 +3149,9 @@ function sshCommand() {
2981
3149
  }
2982
3150
  // src/commands/tunnel.ts
2983
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
+ }
2984
3155
  function tunnelCommand() {
2985
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) => {
2986
3157
  const { localPort, cubePort } = parseTunnelSpec(spec);
@@ -2991,8 +3162,10 @@ function tunnelCommand() {
2991
3162
  localPort,
2992
3163
  cubePort
2993
3164
  });
2994
- process.stderr.write(`Forwarding localhost:${localPort} -> ${cubeRef}:${cubePort}. Press Ctrl+C to stop.\n`);
2995
- process.exitCode = await holdTunnel(args);
3165
+ process.exitCode = await holdTunnel(args, {
3166
+ readyPort: localPort,
3167
+ onReady: () => announceForwarding(localPort, cubeRef, cubePort)
3168
+ });
2996
3169
  });
2997
3170
  }
2998
3171
  function connectCommand() {
@@ -3017,7 +3190,7 @@ function connectCommand() {
3017
3190
  cubePort
3018
3191
  });
3019
3192
  else process.stdout.write(`localhost:${localPort}\n`);
3020
- process.stderr.write(`Forwarding localhost:${localPort} -> ${cubeRef}:${cubePort}. Press Ctrl+C to stop.\n`);
3193
+ announceForwarding(localPort, cubeRef, cubePort);
3021
3194
  }
3022
3195
  });
3023
3196
  });
@@ -3569,6 +3742,7 @@ function errorHint(err, baseUrl) {
3569
3742
  if (isNetworkError(err)) return `Could not reach ${baseUrl}. Check your connection or ${ENV.baseUrl}.`;
3570
3743
  }
3571
3744
  // src/index.ts
3745
+ exitQuietlyOnBrokenPipe();
3572
3746
  const program = new Command();
3573
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();
3574
3748
  program.addCommand(loginCommand());